@collective-intelligence/external-apps-client-sdk-react 0.11.0 → 0.12.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.
- package/AGENTS.md +42 -20
- package/README.md +77 -72
- package/dist/effect.d.ts +1 -67
- package/dist/effect.js +1 -1
- package/dist/index-0k92txne.js +2 -0
- package/dist/index-7r4n344n.js +2 -0
- package/dist/index-h4fpzytm.js +2 -0
- package/dist/index-v7pbmwry.js +2 -0
- package/dist/index-ycckwta5.js +2 -0
- package/dist/index.d.ts +18 -8
- package/dist/index.js +1 -1
- package/dist/realtime.d.ts +11 -8
- package/dist/realtime.js +1 -1
- package/dist/records.d.ts +322 -0
- package/dist/records.js +2 -0
- package/dist/records.server.d.ts +155 -0
- package/dist/records.server.js +1 -0
- package/dist/resources.d.ts +13 -10
- package/dist/resources.js +1 -1
- package/docs/effect.md +6 -96
- package/docs/errors.md +14 -14
- package/docs/guide/ai/index.md +1 -1
- package/docs/realtime.md +14 -10
- package/docs/record-collections.md +277 -0
- package/docs/tanstack-skills.md +73 -0
- package/package.json +28 -8
- package/skills/client-sdk-react-move-to-record-collections/SKILL.md +62 -0
- package/skills/client-sdk-react-record-collections/SKILL.md +49 -0
- package/skills/client-sdk-react-tanstack-db-ssr/SKILL.md +52 -0
- package/dist/index-5t792h25.js +0 -2
- package/dist/index-ktw8msmm.js +0 -2
package/docs/effect.md
CHANGED
|
@@ -108,105 +108,15 @@ const LeadEditor = ({ id }: { id: string }) => {
|
|
|
108
108
|
|
|
109
109
|
### Optimistic write
|
|
110
110
|
|
|
111
|
-
|
|
112
|
-
|
|
113
|
-
|
|
114
|
-
|
|
115
|
-
|
|
116
|
-
|
|
117
|
-
call order at once, so a second quick write shows while CI has not
|
|
118
|
-
answered the first. An entry without a value shows no edit until a fetch
|
|
119
|
-
gives it one.
|
|
120
|
-
- **Order.** The writes to one key go to CI one at a time, in call order.
|
|
121
|
-
When CI gets a write, the running fetch of the key is cancelled.
|
|
122
|
-
- **Fetches.** A fetch that ends while writes are pending, for example after
|
|
123
|
-
a realtime change or a window focus, updates the confirmed value, and the
|
|
124
|
-
layers show over it again. Thus an edit must give the same value for a
|
|
125
|
-
value that already holds it: set fields, or replace or remove a row by its
|
|
126
|
-
id. To add a row, skip the add when the row is there.
|
|
127
|
-
- **Send-time payload.** Give `write` as a function to build the payload when
|
|
128
|
-
CI gets the write. It gets `{ confirmed, optimistic }`: the confirmed value
|
|
129
|
-
with the answers of the writes before it, and that value with this edit
|
|
130
|
-
only. A refused write before it is not in either value.
|
|
131
|
-
- **Answer.** When CI confirms the write, its layer goes, and the confirmed
|
|
132
|
-
value becomes `options.confirm(result, confirmed)`, for example CI's row
|
|
133
|
-
with its new revision. Without `confirm`, or when it gives `undefined`, the
|
|
134
|
-
confirmed value gets the edit. When `write` fails, is interrupted or dies,
|
|
135
|
-
only its own layer goes; the other layers show over the confirmed value.
|
|
136
|
-
When `confirm` throws, the write dies with its error, the confirmed value
|
|
137
|
-
stays, and its layer still goes. When the write ends, the key is
|
|
138
|
-
invalidated, so views read CI's value.
|
|
139
|
-
- **Other members.** A value that `setData`, `update` or `remove` puts while
|
|
140
|
-
writes are pending stays. The edits before it no longer show or roll back,
|
|
141
|
-
and their `confirm` does not run, so an older answer of CI never replaces
|
|
142
|
-
the newer value.
|
|
143
|
-
- **Runs.** Each run of the effect that `optimisticUpdate` returns is one
|
|
144
|
-
write with its own layer, so an actor can run one save effect twice.
|
|
145
|
-
- **Pending.** `pending(queryKey)` gives the number of optimistic writes of
|
|
146
|
-
the key that wait for CI or run, for example to show "Saving…".
|
|
147
|
-
|
|
148
|
-
The writes of one key share their layers across every `QueryCache` over the
|
|
149
|
-
same QueryClient. The QueryClient holds them, so two bundled copies of the
|
|
150
|
-
SDK over it, such as the app's and a library's, also share them. Copies of
|
|
151
|
-
releases with another layout of these writes keep their own. A write that changes several keys does the steps itself:
|
|
111
|
+
`QueryCache` has no optimistic write. An optimistic write of a CI record is
|
|
112
|
+
a Record Collection transaction: write it with the entity hooks
|
|
113
|
+
([record-collections.md](record-collections.md)). TanStack DB shows the write
|
|
114
|
+
at once, writes to one record go to CI one at a time, and a refused write
|
|
115
|
+
rolls back only its own change. A write that changes other keys of
|
|
116
|
+
`QueryCache` does the steps itself:
|
|
152
117
|
`cancel` the keys, `update` them, run the write, and `invalidate` the keys
|
|
153
118
|
when the actor ends.
|
|
154
119
|
|
|
155
|
-
```ts
|
|
156
|
-
type Task = Readonly<{
|
|
157
|
-
done: boolean
|
|
158
|
-
id: string
|
|
159
|
-
revision: string
|
|
160
|
-
title: string
|
|
161
|
-
}>
|
|
162
|
-
const tasksKey = ["portal", "tasks"]
|
|
163
|
-
|
|
164
|
-
const saveTask = fromEffect(
|
|
165
|
-
(
|
|
166
|
-
input: Readonly<{
|
|
167
|
-
patch: Partial<Pick<Task, "done" | "title">>
|
|
168
|
-
id: string
|
|
169
|
-
runtime: EffectRunner<QueryCache>
|
|
170
|
-
}>
|
|
171
|
-
) =>
|
|
172
|
-
QueryCache.use((cache) =>
|
|
173
|
-
cache.optimisticUpdate(
|
|
174
|
-
tasksKey,
|
|
175
|
-
// Replaces the row by its id, so a fetch under the layer keeps it.
|
|
176
|
-
(tasks: readonly Task[]) =>
|
|
177
|
-
tasks.map((task) =>
|
|
178
|
-
task.id === input.id ? { ...task, ...input.patch } : task
|
|
179
|
-
),
|
|
180
|
-
// Built when CI gets the save: the revision of the save before it,
|
|
181
|
-
// and no change of a refused save.
|
|
182
|
-
({ optimistic }) => {
|
|
183
|
-
const task = optimistic?.find(({ id }) => id === input.id)
|
|
184
|
-
return task === undefined
|
|
185
|
-
? Effect.die("no task")
|
|
186
|
-
: writeTask(input.id, {
|
|
187
|
-
done: task.done,
|
|
188
|
-
revision: task.revision,
|
|
189
|
-
title: task.title
|
|
190
|
-
})
|
|
191
|
-
},
|
|
192
|
-
// `writeTask` answers CI's row with its new revision.
|
|
193
|
-
{
|
|
194
|
-
confirm: (row: Task, confirmed) =>
|
|
195
|
-
confirmed?.map((task) => (task.id === row.id ? row : task))
|
|
196
|
-
}
|
|
197
|
-
)
|
|
198
|
-
)
|
|
199
|
-
)
|
|
200
|
-
|
|
201
|
-
const savingTasks = fromEffect(
|
|
202
|
-
(input: Readonly<{ runtime: EffectRunner<QueryCache> }>) =>
|
|
203
|
-
QueryCache.use((cache) => cache.pending(tasksKey))
|
|
204
|
-
)
|
|
205
|
-
```
|
|
206
|
-
|
|
207
|
-
A `write` given as an Effect works as before: it is the same for each
|
|
208
|
-
confirmed value.
|
|
209
|
-
|
|
210
120
|
## Rules
|
|
211
121
|
|
|
212
122
|
- Make each side-effect actor with `fromEffect`. The
|
package/docs/errors.md
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
# Errors and
|
|
1
|
+
# Errors and rolled-back writes
|
|
2
2
|
|
|
3
3
|
Entity reads and writes run on the Effect Core of the client SDK. Their
|
|
4
4
|
errors stay values; other client SDK calls follow the client SDK error model
|
|
@@ -11,29 +11,29 @@ error. Reads never retry by themselves; call `refresh` on a user request.
|
|
|
11
11
|
|
|
12
12
|
## Entity writes
|
|
13
13
|
|
|
14
|
-
Entity writes are
|
|
15
|
-
|
|
14
|
+
Entity writes are Record Collection transactions
|
|
15
|
+
([record-collections.md](record-collections.md)).
|
|
16
16
|
|
|
17
|
-
| Outcome
|
|
18
|
-
|
|
|
19
|
-
| Pending
|
|
20
|
-
|
|
|
21
|
-
|
|
|
22
|
-
| Failure or interruption | The value from before the write, when the view still shows the write's value |
|
|
17
|
+
| Outcome | Record Collection of the record | Entity reads |
|
|
18
|
+
| ----------------------- | ---------------------------------------- | --------------------------------------------------------- |
|
|
19
|
+
| Pending | The new value; a delete hides the row | CI's record |
|
|
20
|
+
| Success | CI's confirmed row, with no flicker back | CI's record; each read of the resource reads CI once more |
|
|
21
|
+
| Failure or interruption | Only this write's change rolls back | CI's record |
|
|
23
22
|
|
|
24
23
|
- `status` of a write is `idle`, `pending`, `success`, `conflict`, `rejected`
|
|
25
|
-
or `uncertain`. A write
|
|
24
|
+
or `uncertain`. A write whose answer is lost is sent again with its key for
|
|
25
|
+
up to 60 seconds; it is `uncertain` only after that.
|
|
26
26
|
- `submit` makes a new action; `resubmit` sends the same action again, with
|
|
27
27
|
its key, values and revision. Call `resubmit` only on a user request.
|
|
28
|
-
-
|
|
29
|
-
|
|
28
|
+
- `optimistic: false` in the target has no effect: every write shows at once
|
|
29
|
+
in its Record Collection.
|
|
30
30
|
- Writes to one record run one at a time, in call order.
|
|
31
31
|
|
|
32
32
|
## `onWriteFailed`
|
|
33
33
|
|
|
34
34
|
`onWriteFailed` on `CollectiveIntelligenceProvider` gets a `WriteFailed` for
|
|
35
|
-
each entity write that CI refuses or that does not reach CI, after the
|
|
36
|
-
|
|
35
|
+
each entity write that CI refuses or that does not reach CI, after the
|
|
36
|
+
Record Collection rolled the write back. It is not called for an interruption, or when the entity source
|
|
37
37
|
changed during the write.
|
|
38
38
|
|
|
39
39
|
- `error` is a `CiError` (CI refused) or a `CiTransportError` (the request did
|
package/docs/guide/ai/index.md
CHANGED
|
@@ -226,7 +226,7 @@ Your server invokes an Agent with `agents.invoke({ agentId, input })`, which ret
|
|
|
226
226
|
|
|
227
227
|
For a multi-turn chat, use the shared chat. Start a Conversation with the Agent with `ci.chat.createConversation({ organizationId, payload: { agentId } })`, send each message with `createChatClient(ci, { organizationId }).send({ conversationId, message })` from `@collective-intelligence/external-apps-server-sdk/chat`, and read earlier turns with `ci.chat.getTranscript`. Each turn is an ordinary Agent run, and the earlier successful turns, with their saved Agent Output, become the model's conversation history. A message sent while a turn still runs steers that turn and starts no second turn, and a resend with the same message `id` adds nothing.
|
|
228
228
|
|
|
229
|
-
`send` resolves `{ ok: true, value, runId }`: `runId` is the id of the turn's run, which the answer message also carries as `metadata.invocationId`, and `turnRunId(message)` reads it from any answer message. `runs.get`, `runs.sources` and `runs.feedback` accept that id like the `runId` of `agents.invoke`. They answer only the caller that owns the Conversation (the member, the app server or the visitor) through the application where the Conversation started, and answer `not_found` to every other caller. As for any run, only a signed-in member reads `runs.sources` and gives `runs.feedback`. `runs.get` gives the status and `result: { message, output? }`, where `output` is the Agent Output that the turn saved. `runs.feedback` also rates a succeeded turn whose answer is only its Agent Output, with the Output's JSON text as the rated answer; a turn with neither text nor Output has no answer to rate and gets `not_found`. The member can also rate and clear the answer with `ci.chat.putAnswerFeedback` and `ci.chat.clearAnswerFeedback` (`params: { invocationId: runId }`); it is the same rating. Each completed Agent turn with an answer to rate (its text or its Agent Output) of `ci.chat.getTranscript` gives that member `feedbackTargetId` (the turn's run id) and `currentUserFeedback`, so the app shows a saved rating again after a reload. `runs.sources` gives the searched Document Versions with their pages and a download link. `runs.stream`
|
|
229
|
+
`send` resolves `{ ok: true, value, runId }`: `runId` is the id of the turn's run, which the answer message also carries as `metadata.invocationId`, and `turnRunId(message)` reads it from any answer message. `runs.get`, `runs.stream`, `runs.cancel`, `runs.sources` and `runs.feedback` accept that id like the `runId` of `agents.invoke`. They answer only the caller that owns the Conversation (the member, the app server or the visitor) through the application where the Conversation started, and answer `not_found` to every other caller. As for any run, only a signed-in member reads `runs.sources` and gives `runs.feedback`. `runs.get` gives the status and `result: { message, output? }`, where `output` is the Agent Output that the turn saved. `runs.feedback` also rates a succeeded turn whose answer is only its Agent Output, with the Output's JSON text as the rated answer; a turn with neither text nor Output has no answer to rate and gets `not_found`. The member can also rate and clear the answer with `ci.chat.putAnswerFeedback` and `ci.chat.clearAnswerFeedback` (`params: { invocationId: runId }`); it is the same rating. Each completed Agent turn with an answer to rate (its text or its Agent Output) of `ci.chat.getTranscript` gives that member `feedbackTargetId` (the turn's run id) and `currentUserFeedback`, so the app shows a saved rating again after a reload. `runs.sources` gives the searched Document Versions with their pages and a download link. `runs.stream` pages the turn's events as for `agents.invoke`: `accepted`, the `agent.*` events and the application events that its tools publish, then one terminal event with the `runs.get` result. `runs.cancel` stops the turn. The answer itself streams from `GET /runs/:runId/stream` of the chat mount.
|
|
230
230
|
|
|
231
231
|
Anonymous visitors can chat with an Agent only when its audience has `anonymous: [app]` for that application and the call passes `caller: { kind: "anonymous_visitor", visitor: { issuer, subjectId } }`. Their turns run with the Agent's own bindings, never with the application's grants, and visitors never see each other's conversations.
|
|
232
232
|
|
package/docs/realtime.md
CHANGED
|
@@ -12,8 +12,7 @@ const AppRealtime = ({ children }: { children: ReactNode }) => {
|
|
|
12
12
|
const queryClient = useQueryClient()
|
|
13
13
|
return (
|
|
14
14
|
<RealtimeProvider
|
|
15
|
-
|
|
16
|
-
onReset={() => queryClient.invalidateQueries()}
|
|
15
|
+
onResync={() => queryClient.invalidateQueries()}
|
|
17
16
|
revalidateUrl="/api/realtime/revalidate"
|
|
18
17
|
ticketUrl="/api/realtime/ticket"
|
|
19
18
|
>
|
|
@@ -34,11 +33,12 @@ const LeadBoard = () => {
|
|
|
34
33
|
|
|
35
34
|
## Rules
|
|
36
35
|
|
|
37
|
-
- Pass `
|
|
38
|
-
|
|
39
|
-
`
|
|
40
|
-
|
|
41
|
-
|
|
36
|
+
- Pass `onResync` and reload every realtime-driven query in it. It runs once
|
|
37
|
+
per delivery that holds a Resync. Its `reasons` (`"gap"`, `"access"`,
|
|
38
|
+
`"server"`, `"first-open"`) and `generation` are for logs and metrics;
|
|
39
|
+
every call means reload, also for a generation seen before. With
|
|
40
|
+
`accessChanged` true, check the session too. Without `onResync` the client
|
|
41
|
+
cannot recover from a gap, and a change can be lost.
|
|
42
42
|
- `startedAt` (default `performance.timeOrigin`) is when the page started to
|
|
43
43
|
read its data. A page that shows cached data read before its navigation
|
|
44
44
|
passes `performance.timeOrigin - ageMs`; never a server timestamp.
|
|
@@ -48,9 +48,13 @@ const LeadBoard = () => {
|
|
|
48
48
|
- Changes come in batches, one delivery per tab, with the latest change of
|
|
49
49
|
each record. Invalidate once per batch.
|
|
50
50
|
- The provider reads `ticketUrl`, `fetch` and the other client props once. To
|
|
51
|
-
use new values, remount it, for example with a React `key`.
|
|
52
|
-
|
|
53
|
-
|
|
51
|
+
use new values, remount it, for example with a React `key`. It calls the
|
|
52
|
+
`onResync` and `onRefused` of the latest render; a render that adds or
|
|
53
|
+
removes `onResync` opens a new stream.
|
|
54
|
+
- A Realtime Record Collection follows its topic with no `useRealtimeTopic`:
|
|
55
|
+
inside `CollectiveIntelligenceProvider`, `RealtimeProvider` feeds it the
|
|
56
|
+
Change Hints and Resyncs of its connection
|
|
57
|
+
([record-collections.md](record-collections.md)).
|
|
54
58
|
- With `revalidateUrl`, the server expires its Next.js cache tags of the
|
|
55
59
|
changes before `onChanges` runs, so `router.refresh()` in `onChanges` reads
|
|
56
60
|
fresh server data.
|
|
@@ -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.
|
|
3
|
+
"version": "0.12.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.
|
|
58
|
-
"@collective-intelligence/external-apps-client-sdk": "0.
|
|
68
|
+
"@collective-intelligence/effect-xstate": "0.12.0",
|
|
69
|
+
"@collective-intelligence/external-apps-client-sdk": "0.12.0",
|
|
59
70
|
"nuqs": "2.10.1"
|
|
60
71
|
},
|
|
61
72
|
"peerDependencies": {
|
|
62
|
-
"@collective-intelligence/ui-react": "0.
|
|
73
|
+
"@collective-intelligence/ui-react": "0.12.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.
|
|
89
|
+
"@collective-intelligence/ui-react": "0.12.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": "
|
|
122
|
+
"gitHead": "995aa5542f6f440c5cebe836b57bc9bae57ae7e8"
|
|
103
123
|
}
|