@collective-intelligence/external-apps-client-sdk-react 0.2.0 → 0.2.1

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 ADDED
@@ -0,0 +1,39 @@
1
+ # `@collective-intelligence/external-apps-client-sdk-react`: agent guide
2
+
3
+ React bindings of Collective Intelligence (CI) external applications: the
4
+ provider, entity hooks with Optimistic Writes, declared entity views, realtime
5
+ hooks, and the Effect bridge for XState machines. The package `README.md`
6
+ holds the full API.
7
+
8
+ ## Rules
9
+
10
+ - Import entity hooks and views from `/resources`, and the Effect bridge
11
+ (`fromEffect`, `EffectRuntimeProvider`, `QueryCache`) from `/effect`.
12
+ - Install the peers once in the app: `react`, `react-dom`,
13
+ `@tanstack/react-query`, `xstate`, `effect` (`^4.1.0`) and
14
+ `@collective-intelligence/ui-react`.
15
+ - Keep user-scoped reads in TanStack Query: the entity hooks, or `useQuery` on
16
+ the keys that `QueryCache` writes. Only reads with the app's own credential
17
+ go into the Next.js server cache (`cacheCiRead` of the server SDK).
18
+ - To share one cache, pass the app's QueryClient to
19
+ `CollectiveIntelligenceProvider` as `queryClient`.
20
+ - Run each side effect of a machine in a `fromEffect` actor. Keep remote data
21
+ in `QueryCache`, never in machine context. A view renders: it calls no
22
+ `fetch` and runs no Effect.
23
+ - Show write failures with `onWriteFailed` on the provider, for example
24
+ `ciWriteFailedToast()` of `@collective-intelligence/ui-react/ui`.
25
+ - Give `RealtimeProvider` an `onReset` that refetches every realtime-driven
26
+ query.
27
+
28
+ ## Index
29
+
30
+ - [docs/effect.md](docs/effect.md): read when you write an XState machine
31
+ that calls CI, or connect Effect code to the QueryClient.
32
+ - [docs/realtime.md](docs/realtime.md): read when a view must follow changes
33
+ of a Realtime Topic.
34
+ - [docs/errors.md](docs/errors.md): read when you handle a failed entity read
35
+ or write, or an Optimistic Write goes back.
36
+ - [skills/client-sdk-react-move-to-effect/SKILL.md](skills/client-sdk-react-move-to-effect/SKILL.md):
37
+ run when machines use `fromPromise`, `fromCallback` or observable actors, a
38
+ view runs an Effect, or lint reports `ci-solution/effect-actors` or
39
+ `ci-solution/no-run-in-view`.
package/docs/effect.md ADDED
@@ -0,0 +1,76 @@
1
+ # Effect with XState
2
+
3
+ `/effect` connects XState machines to Effect and to the app's QueryClient. It
4
+ has no Effect Atom bindings. A UI flow is an XState machine; each side effect
5
+ is an actor; each actor is a `fromEffect` actor.
6
+
7
+ ## Parts
8
+
9
+ - `fromEffect(run)` makes actor logic from an Effect. The actor runs the
10
+ effect on `input.runtime`: type `input` with a `runtime: EffectRunner<R>`
11
+ that provides each service of the effect. `onDone` gets the value; `onError`
12
+ gets the typed error or the defect. A stop of the actor interrupts the
13
+ fiber; after the stop, no result of that run reaches the actor, also in
14
+ React Strict Mode.
15
+ - `EffectRuntimeProvider` gives its tree a runtime with `QueryCache` over the
16
+ nearest QueryClient; `useEffectRuntime()` returns it. Put it inside
17
+ `CollectiveIntelligenceProvider`. It holds no resource, so it never disposes.
18
+ - `QueryCache` is the one way for actors to read and write remote data:
19
+ - `fetch({ queryKey, query, staleTime? })` returns a fresh cached value or
20
+ runs `query` once, with no automatic retry. `CiError` and
21
+ `CiTransportError` stay typed errors; another failure is a defect.
22
+ - `invalidate(queryKey)` marks values stale and refetches the ones that
23
+ views show.
24
+ - `setData(queryKey, value)` writes a value that views show at once.
25
+ - Views read the same keys with `useQuery`.
26
+
27
+ ```tsx
28
+ import type { EffectRunner } from "@collective-intelligence/external-apps-client-sdk-react/effect"
29
+ import {
30
+ EffectRuntimeProvider,
31
+ QueryCache,
32
+ fromEffect,
33
+ useEffectRuntime
34
+ } from "@collective-intelligence/external-apps-client-sdk-react/effect"
35
+
36
+ const loadLead = fromEffect(
37
+ (input: Readonly<{ id: string; runtime: EffectRunner<QueryCache> }>) =>
38
+ QueryCache.use((cache) =>
39
+ cache.fetch({
40
+ query: readLead(input.id),
41
+ queryKey: ["crm", "lead", input.id]
42
+ })
43
+ )
44
+ )
45
+
46
+ // Inside CollectiveIntelligenceProvider and EffectRuntimeProvider:
47
+ const LeadEditor = ({ id }: { id: string }) => {
48
+ const runtime = useEffectRuntime()
49
+ const lead = useActorRef(leadMachine, { input: { id, runtime } })
50
+ // ...
51
+ }
52
+ ```
53
+
54
+ ## Rules
55
+
56
+ - Make each side-effect actor with `fromEffect`. The
57
+ `ci-solution/effect-actors` rule of `@collective-intelligence/lint` reports
58
+ `fromPromise`, `fromCallback`, `fromObservable` and
59
+ `fromEventObservable`.
60
+ - Machine context holds flow state only. Remote data lives in `QueryCache`.
61
+ - A view module renders: it starts machines and reads `useQuery`. The
62
+ `ci-solution/no-run-in-view` rule reports a view that calls `fetch` or runs
63
+ an Effect.
64
+ - Branch on a typed failure in the machine, for example with
65
+ `Schema.is(ErrorSchema)` in a guard.
66
+ - UI feedback, such as a toast, is a machine action that the view provides
67
+ with `machine.provide({ actions })`.
68
+ - A test swaps an actor with `machine.provide({ actors })`.
69
+ - In Strict Mode, an actor that `useActorRef` starts again can run its `query`
70
+ a second time: keep queries idempotent.
71
+
72
+ ## Client SDK services
73
+
74
+ The services of `external-apps-client-sdk/effect` (`CiClient`, `Resources`,
75
+ `RealtimeClient` and the others) run in the same actors: add their layers to
76
+ the runtime that the actor input carries.
package/docs/errors.md ADDED
@@ -0,0 +1,65 @@
1
+ # Errors and Optimistic Writes
2
+
3
+ Entity reads and writes run on the Effect Core of the client SDK. Their
4
+ errors stay values; other client SDK calls follow the client SDK error model
5
+ (`docs/errors.md` of `external-apps-client-sdk`).
6
+
7
+ ## Entity reads
8
+
9
+ A read that fails gives `error`, a `ResourceQueryError` with the resource
10
+ error. Reads never retry by themselves; call `refresh` on a user request.
11
+
12
+ ## Entity writes
13
+
14
+ Entity writes are Optimistic Writes: the views show the new value before CI
15
+ answers.
16
+
17
+ | Outcome | What the views show |
18
+ | ------------------------ | ---------------------------------------------------------------------------- |
19
+ | Pending update or delete | The new value; a deleted record leaves the list pages |
20
+ | Pending create | A pending row at the start of each cached first list page |
21
+ | Success | CI's record; then each view of the resource reads CI once more |
22
+ | Failure or interruption | The value from before the write, when the view still shows the write's value |
23
+
24
+ - `status` of a write is `idle`, `pending`, `success`, `conflict`, `rejected`
25
+ or `uncertain`. A write that fails in flight is `uncertain`.
26
+ - `submit` makes a new action; `resubmit` sends the same action again, with
27
+ its key, values and revision. Call `resubmit` only on a user request.
28
+ - Pass `optimistic: false` in the target to change the cache only when CI
29
+ answers: `useEntityUpdate(contract, { id, optimistic: false })`.
30
+ - Writes to one record run one at a time, in call order.
31
+
32
+ ## `onWriteFailed`
33
+
34
+ `onWriteFailed` on `CollectiveIntelligenceProvider` gets a `WriteFailed` for
35
+ each entity write that CI refuses or that does not reach CI, after the views
36
+ went back. It is not called for an interruption, or when the entity source
37
+ changed during the write.
38
+
39
+ - `error` is a `CiError` (CI refused) or a `CiTransportError` (the request did
40
+ not reach CI, or the answer was lost).
41
+ - `operation` is `create`, `update` or `delete`; `label` is `contract.id`.
42
+ - This package shows no toast. `ciWriteFailedToast(messages?)` of
43
+ `@collective-intelligence/ui-react/ui` gives a handler that shows one in the
44
+ app's `Toaster`.
45
+
46
+ ```tsx
47
+ import {
48
+ Toaster,
49
+ ciWriteFailedToast
50
+ } from "@collective-intelligence/ui-react/ui"
51
+
52
+ ;<CollectiveIntelligenceProvider
53
+ client={appSdk}
54
+ entitySource={entitySource}
55
+ onWriteFailed={ciWriteFailedToast()}
56
+ >
57
+ <Orders />
58
+ <Toaster />
59
+ </CollectiveIntelligenceProvider>
60
+ ```
61
+
62
+ ## In machines
63
+
64
+ A `fromEffect` actor gets `CiError` and `CiTransportError` as typed errors of
65
+ `QueryCache.fetch`; see [effect.md](effect.md).
@@ -0,0 +1,50 @@
1
+ # Realtime
2
+
3
+ `RealtimeProvider` takes the options of `createRealtimeClient` of
4
+ `external-apps-client-sdk` as props. It makes one client, and so one
5
+ connection, for its tree, and closes it on unmount. A server render makes no
6
+ client; a Strict Mode double mount opens one stream.
7
+
8
+ ```tsx
9
+ const AppRealtime = ({ children }: { children: ReactNode }) => {
10
+ const queryClient = useQueryClient()
11
+ return (
12
+ <RealtimeProvider
13
+ onAccessChanged={() => queryClient.invalidateQueries()}
14
+ onReset={() => queryClient.invalidateQueries()}
15
+ revalidateUrl="/api/realtime/revalidate"
16
+ ticketUrl="/api/realtime/ticket"
17
+ >
18
+ {children}
19
+ </RealtimeProvider>
20
+ )
21
+ }
22
+
23
+ const LeadBoard = () => {
24
+ const queryClient = useQueryClient()
25
+ useRealtimeTopic({ schema: "crm.lead" }, () =>
26
+ // One invalidation per batch, however many leads changed.
27
+ queryClient.invalidateQueries({ queryKey: ["leads"] })
28
+ )
29
+ // ...
30
+ }
31
+ ```
32
+
33
+ ## Rules
34
+
35
+ - Pass `onReset` and refetch every realtime-driven query in it. Without it,
36
+ the client cannot recover from a gap, and a change can be lost.
37
+ - `useRealtimeTopic(topic, onChanges)` subscribes while the component is
38
+ mounted. A new object for the same topic keeps the subscription; `null`
39
+ subscribes to nothing. The latest `onChanges` runs, with no resubscribe.
40
+ - Changes come in batches, one delivery per tab, with the latest change of
41
+ each record. Invalidate once per batch.
42
+ - The provider reads `ticketUrl`, `fetch` and the other client props once. To
43
+ use new values, remount it, for example with a React `key`.
44
+ - Entity reads wait for the pending write of their record, so a refetch after
45
+ a change does not replace an Optimistic Write.
46
+ - With `revalidateUrl`, the server expires its Next.js cache tags of the
47
+ changes before `onChanges` runs, so `router.refresh()` in `onChanges` reads
48
+ fresh server data.
49
+
50
+ Connection details: `docs/realtime.md` of `external-apps-client-sdk`.
package/package.json CHANGED
@@ -1,12 +1,15 @@
1
1
  {
2
2
  "name": "@collective-intelligence/external-apps-client-sdk-react",
3
- "version": "0.2.0",
3
+ "version": "0.2.1",
4
4
  "description": "React bindings for Collective Intelligence external applications.",
5
5
  "type": "module",
6
6
  "sideEffects": false,
7
7
  "files": [
8
8
  "dist",
9
- "README.md"
9
+ "README.md",
10
+ "AGENTS.md",
11
+ "docs",
12
+ "skills"
10
13
  ],
11
14
  "main": "./dist/index.js",
12
15
  "types": "./dist/index.d.ts",
@@ -45,7 +48,7 @@
45
48
  "type-check": "bun check"
46
49
  },
47
50
  "dependencies": {
48
- "@collective-intelligence/external-apps-client-sdk": "0.2.0",
51
+ "@collective-intelligence/external-apps-client-sdk": "0.2.1",
49
52
  "nuqs": "2.10.1"
50
53
  },
51
54
  "peerDependencies": {
@@ -85,5 +88,5 @@
85
88
  "vitest": "4.1.10",
86
89
  "xstate": "5.33.3"
87
90
  },
88
- "gitHead": "399369a97e85b54b43aeac887e7ba9c960cb7505"
91
+ "gitHead": "7b3d604c39db3969749b14174d660a814a1f3a72"
89
92
  }
@@ -0,0 +1,37 @@
1
+ ---
2
+ name: client-sdk-react-move-to-effect
3
+ description: Move the XState machines and views of a React app that uses `@collective-intelligence/external-apps-client-sdk-react` to the Effect bridge of its `/effect` entry. Use when machines use `fromPromise`, `fromCallback` or observable actors, machine context holds API data, a view calls `fetch` or runs an Effect, or lint reports `ci-solution/effect-actors` or `ci-solution/no-run-in-view`.
4
+ ---
5
+
6
+ # Move machines to the Effect bridge
7
+
8
+ Reference: [effect.md](../../docs/effect.md), [errors.md](../../docs/errors.md).
9
+
10
+ ## Steps
11
+
12
+ 1. **Inventory.** Run oxlint with the `recommended` config of
13
+ `@collective-intelligence/lint`, and search for `fromPromise`,
14
+ `fromCallback`, `fromObservable`, `fromEventObservable`, `Effect.run` and
15
+ `fetch(` in view modules. Done when you have each finding and each machine
16
+ context field that holds API data.
17
+ 2. **Mount the runtime.** Put `EffectRuntimeProvider` inside
18
+ `CollectiveIntelligenceProvider`, and pass the app's QueryClient as
19
+ `queryClient` when the app has one. Done when `useEffectRuntime()` works in
20
+ each view that starts a machine.
21
+ 3. **Rewrite each actor** as `fromEffect((input) => ...)`. Type `input` with
22
+ `runtime: EffectRunner<R>`, and pass `useEffectRuntime()` in the machine
23
+ input. Map the typed failure in `onError`. Done when step 1 finds no
24
+ side-effect actor of XState.
25
+ 4. **Move API data to `QueryCache`.** Read with `cache.fetch({ queryKey, query })`;
26
+ after a write, `cache.invalidate(queryKey)` or `cache.setData`. Views read
27
+ the same keys with `useQuery`. Remove the API data from machine context.
28
+ Done when machine context holds flow state only.
29
+ 5. **Empty the views.** Move each `fetch` and Effect run of a view into an
30
+ actor; a view starts the machine and renders. Done when oxlint reports no
31
+ `ci-solution/no-run-in-view` finding.
32
+ 6. **Move toasts.** Give the provider `onWriteFailed` (for example
33
+ `ciWriteFailedToast()`), and turn other UI feedback into machine actions
34
+ that the view provides. Done when no actor calls a toast.
35
+ 7. **Verify.** Run the type-check, the machine tests (swap actors with
36
+ `machine.provide({ actors })`) and oxlint. Done when all pass with no
37
+ `ci-solution/effect-actors` finding.