@collective-intelligence/extensions-sdk-frontend-react 0.2.3 → 0.2.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.
package/AGENTS.md CHANGED
@@ -13,7 +13,9 @@ the full API.
13
13
  - Keep one `effect` (`^4.1.0`) in the extension package. It is a required
14
14
  peer. `react`, `react-dom` and `xstate` come from the host.
15
15
  - Write in a `fromEffect` actor, never with `useMutation` or `fromPromise`;
16
- after the write, refresh the reads through `QueryCache`. Mount
16
+ after the write, refresh the reads through `QueryCache`. An optimistic
17
+ write calls `QueryCache.cancel` on its keys before `update`, and
18
+ `invalidate` when the write settles. Mount
17
19
  `EffectRuntimeProvider` at the root of each widget.
18
20
  - Call the Studio API from Effect code through `StudioApi`. A Studio Widget
19
21
  gives `layerStudioApi()` no base URL: the Studio Host binds the client.
package/README.md CHANGED
@@ -304,12 +304,17 @@ and after the write the actor refreshes the reads through `QueryCache`.
304
304
  - `fromEffect(run)` makes XState actor logic that runs the effect of `run` on
305
305
  `input.runtime`. A stop of the actor interrupts the fiber; after a stop, no
306
306
  result of that run gets to the actor, also in a React Strict Mode remount.
307
- - `QueryCache` has `fetch`, `invalidate`, `setData`, `update` and `remove`.
308
- `invalidate`, `update` and `remove` apply to the key and to each key below
309
- it. `fetch` runs its query once, without a retry, and fails with
310
- `StudioApiError` or `StudioApiTransportError`; another failure is a Defect,
311
- and a cancel of the key is an interruption. The Host and all widgets share
312
- one `QueryClient`, so start each key with the package name.
307
+ - `QueryCache` has `fetch`, `invalidate`, `cancel`, `setData`, `update` and
308
+ `remove`. `invalidate`, `cancel`, `update` and `remove` apply to the key and
309
+ to each key below it. `fetch` runs its query once, without a retry, and fails
310
+ with `StudioApiError` or `StudioApiTransportError`; another failure is a
311
+ Defect. A cancel of the key interrupts the query; the waiting `fetch` then
312
+ returns the cached value, or is interrupted when the key has no value.
313
+ `cancel` cancels the running fetches, so they write no value; it keeps the
314
+ cached values and starts no fetch. An optimistic write calls `cancel`, then
315
+ `update`, runs the write, and calls `invalidate` when the write settles. The
316
+ Host and all widgets share one `QueryClient`, so start each key with the
317
+ package name.
313
318
 
314
319
  ```tsx
315
320
  import type { EffectRunner } from "@collective-intelligence/extensions-sdk-frontend-react/effect"
@@ -14,11 +14,22 @@ export type QueryCacheValue = Readonly<{
14
14
  /**
15
15
  * The fresh cached value of `queryKey`, or the value of one run of `query`,
16
16
  * then cached. When the last view or caller of the key stops waiting, or
17
- * TanStack Query cancels the key, `query` is interrupted.
17
+ * `cancel` or TanStack Query cancels the key, `query` is interrupted. After
18
+ * a cancel, the caller gets the cached value of the key, or an interruption
19
+ * when the key holds no value.
18
20
  */
19
21
  fetch: <Data>(options: QueryCacheFetchOptions<Data>) => Effect.Effect<Data, StudioApiError | StudioApiTransportError>;
20
22
  /** Marks the values of `queryKey` and of the keys below it stale, and refetches the ones that views show. */
21
23
  invalidate: (queryKey: QueryKey) => Effect.Effect<void>;
24
+ /**
25
+ * Cancels the running fetches of `queryKey` and of the keys below it and
26
+ * interrupts their queries, so these fetches write no value. Keeps the
27
+ * cached values and starts no fetch, so a view of a key whose first fetch
28
+ * it cancels shows no value until the next fetch. Call it before an
29
+ * optimistic `update`, so that a fetch that ends later does not replace the
30
+ * new value, and `invalidate` when the write ends.
31
+ */
32
+ cancel: (queryKey: QueryKey) => Effect.Effect<void>;
22
33
  /** Caches `data` as the value of `queryKey`; views show it at once. */
23
34
  setData: <Data>(queryKey: QueryKey, data: Data) => Effect.Effect<void>;
24
35
  /**
@@ -28,7 +39,7 @@ export type QueryCacheValue = Readonly<{
28
39
  * without a value, and its `undefined` result keeps the value. Keys that the
29
40
  * cache does not hold stay absent. Each key below `queryKey` must hold a
30
41
  * `Data` value. A running fetch is not cancelled, and its value replaces the
31
- * new value when it ends.
42
+ * new value when it ends; call `cancel` first to keep the new value.
32
43
  */
33
44
  update: <Data>(queryKey: QueryKey, updater: (current: Data | undefined) => Data | undefined) => Effect.Effect<void>;
34
45
  /**
@@ -43,11 +54,22 @@ declare const QueryCache_base: Context.ServiceClass<QueryCache, "@collective-int
43
54
  /**
44
55
  * The fresh cached value of `queryKey`, or the value of one run of `query`,
45
56
  * then cached. When the last view or caller of the key stops waiting, or
46
- * TanStack Query cancels the key, `query` is interrupted.
57
+ * `cancel` or TanStack Query cancels the key, `query` is interrupted. After
58
+ * a cancel, the caller gets the cached value of the key, or an interruption
59
+ * when the key holds no value.
47
60
  */
48
61
  fetch: <Data>(options: QueryCacheFetchOptions<Data>) => Effect.Effect<Data, StudioApiError | StudioApiTransportError>;
49
62
  /** Marks the values of `queryKey` and of the keys below it stale, and refetches the ones that views show. */
50
63
  invalidate: (queryKey: QueryKey) => Effect.Effect<void>;
64
+ /**
65
+ * Cancels the running fetches of `queryKey` and of the keys below it and
66
+ * interrupts their queries, so these fetches write no value. Keeps the
67
+ * cached values and starts no fetch, so a view of a key whose first fetch
68
+ * it cancels shows no value until the next fetch. Call it before an
69
+ * optimistic `update`, so that a fetch that ends later does not replace the
70
+ * new value, and `invalidate` when the write ends.
71
+ */
72
+ cancel: (queryKey: QueryKey) => Effect.Effect<void>;
51
73
  /** Caches `data` as the value of `queryKey`; views show it at once. */
52
74
  setData: <Data>(queryKey: QueryKey, data: Data) => Effect.Effect<void>;
53
75
  /**
@@ -57,7 +79,7 @@ declare const QueryCache_base: Context.ServiceClass<QueryCache, "@collective-int
57
79
  * without a value, and its `undefined` result keeps the value. Keys that the
58
80
  * cache does not hold stay absent. Each key below `queryKey` must hold a
59
81
  * `Data` value. A running fetch is not cancelled, and its value replaces the
60
- * new value when it ends.
82
+ * new value when it ends; call `cancel` first to keep the new value.
61
83
  */
62
84
  update: <Data>(queryKey: QueryKey, updater: (current: Data | undefined) => Data | undefined) => Effect.Effect<void>;
63
85
  /**
package/dist/effect.js CHANGED
@@ -1 +1 @@
1
- import*as n from"effect/Schema";class c extends n.TaggedError()("StudioApiError",{body:n.Unknown,status:n.Int}){}class f extends n.TaggedError()("StudioApiTransportError",{cause:n.Defect()}){}import{fromPromise as v}from"xstate";var w=()=>Promise.race([]),L=(r)=>v(async({input:a,signal:i})=>{try{let e=await a.runtime.runPromise(r(a),{signal:i});return i.aborted?w():e}catch(e){if(i.aborted)return w();throw e}});import{isCancelledError as Q,QueryObserver as I}from"@tanstack/react-query";import*as D from"effect/Context";import*as o from"effect/Effect";import*as u from"effect/Exit";import{constVoid as N}from"effect/Function";import*as h from"effect/Layer";class l extends D.Service()("@collective-intelligence/extensions-sdk-frontend-react/QueryCache"){}var W=(r)=>{let a=async({query:e,...t},S)=>{try{return u.succeed(await r.fetchQuery({...t,queryFn:({signal:s})=>o.runPromiseWith(S)(e,{signal:s}),retry:!1}))}catch(s){if(Q(s))return u.interrupt();return s instanceof c||s instanceof f?u.fail(s):u.die(s)}},i=(e)=>o.sync(()=>new I(r,{enabled:!1,queryKey:e}).subscribe(N));return l.of({fetch:(e)=>o.flatMap(o.context(),(t)=>o.acquireUseRelease(i(e.queryKey),()=>o.flatten(o.promise(()=>a(e,t))),(S)=>o.sync(S))),invalidate:(e)=>o.promise(()=>r.invalidateQueries({queryKey:e})),remove:(e)=>o.sync(()=>{r.removeQueries({queryKey:e})}),setData:(e,t)=>o.sync(()=>{r.setQueryData(e,t)}),update:(e,t)=>o.sync(()=>{r.setQueriesData({queryKey:e},t)})})},x=(r)=>h.succeed(l,W(r));import{useQueryClient as M}from"@tanstack/react-query";import*as g from"effect/ManagedRuntime";import{createContext as q,useContext as U,useMemo as P}from"react";import{jsx as F}from"react/jsx-runtime";var V=q(null),T=({children:r})=>{let a=M(),i=P(()=>g.make(x(a)),[a]);return F(V.Provider,{value:i,children:r})},K=()=>{let r=U(V);if(r===null)throw Error("useEffectRuntime requires an EffectRuntimeProvider");return r};import{client as j,studioAgentRunsGet as z,studioAgentRunsList as B,studioViewDataGetItem as H,studioViewDataSearch as J,studioViewDataSearchMembers as X,studioViewDataUpdateItem as Y,studioWorkflowRunsGet as Z,studioWorkflowRunsList as _}from"@collective-intelligence/extensions-sdk-frontend-react/studio-api";import*as G from"effect/Config";import*as k from"effect/Context";import*as m from"effect/Effect";import*as y from"effect/Layer";class R extends k.Service()("@collective-intelligence/extensions-sdk-frontend-react/StudioApi"){}var ee=(r={})=>{let a=r.baseUrl===void 0?{}:{baseUrl:r.baseUrl},i=(e,t)=>m.fn(`StudioApi.${e}`)(function*(s){let E=!1,A=j.getConfig().fetch??globalThis.fetch,C=Object.assign(async(p,b)=>(E=!0,await A(p,b)),A),d=yield*m.tryPromise({catch:(p)=>{if(E)return new f({cause:p});throw p},try:(p)=>t(s,{...a,fetch:C,responseStyle:"fields",signal:p,throwOnError:!1})});if(d.response===void 0)return yield*new f({cause:d.error});if(!d.response.ok)return yield*new c({body:d.error,status:d.response.status});return d.data});return R.of({studioAgentRunsGet:i("studioAgentRunsGet",(e,t)=>z({...e,...t})),studioAgentRunsList:i("studioAgentRunsList",(e,t)=>B({...e,...t})),studioViewDataGetItem:i("studioViewDataGetItem",(e,t)=>H({...e,...t})),studioViewDataSearch:i("studioViewDataSearch",(e,t)=>J({...e,...t})),studioViewDataSearchMembers:i("studioViewDataSearchMembers",(e,t)=>X({...e,...t})),studioViewDataUpdateItem:i("studioViewDataUpdateItem",(e,t)=>Y({...e,...t})),studioWorkflowRunsGet:i("studioWorkflowRunsGet",(e,t)=>Z({...e,...t})),studioWorkflowRunsList:i("studioWorkflowRunsList",(e,t)=>_({...e,...t}))})},O=(r={})=>y.sync(R,()=>ee(r)),te=(r)=>y.unwrap(m.map(G.unwrap(r),O));export{T as EffectRuntimeProvider,l as QueryCache,R as StudioApi,c as StudioApiError,f as StudioApiTransportError,L as fromEffect,O as layerStudioApi,te as layerStudioApiConfig,K as useEffectRuntime};
1
+ import*as n from"effect/Schema";class c extends n.TaggedError()("StudioApiError",{body:n.Unknown,status:n.Int}){}class f extends n.TaggedError()("StudioApiTransportError",{cause:n.Defect()}){}import{fromPromise as Q}from"xstate";var w=()=>Promise.race([]),v=(r)=>Q(async({input:a,signal:i})=>{try{let e=await a.runtime.runPromise(r(a),{signal:i});return i.aborted?w():e}catch(e){if(i.aborted)return w();throw e}});import{isCancelledError as L,QueryObserver as I}from"@tanstack/react-query";import*as D from"effect/Context";import*as o from"effect/Effect";import*as u from"effect/Exit";import{constVoid as N}from"effect/Function";import*as h from"effect/Layer";class l extends D.Service()("@collective-intelligence/extensions-sdk-frontend-react/QueryCache"){}var W=(r)=>{let a=async({query:e,...t},S)=>{try{return u.succeed(await r.fetchQuery({...t,queryFn:({signal:s})=>o.runPromiseWith(S)(e,{signal:s}),retry:!1}))}catch(s){if(L(s))return u.interrupt();return s instanceof c||s instanceof f?u.fail(s):u.die(s)}},i=(e)=>o.sync(()=>new I(r,{enabled:!1,queryKey:e}).subscribe(N));return l.of({cancel:(e)=>o.promise(()=>r.cancelQueries({queryKey:e})),fetch:(e)=>o.flatMap(o.context(),(t)=>o.acquireUseRelease(i(e.queryKey),()=>o.flatten(o.promise(()=>a(e,t))),(S)=>o.sync(S))),invalidate:(e)=>o.promise(()=>r.invalidateQueries({queryKey:e})),remove:(e)=>o.sync(()=>{r.removeQueries({queryKey:e})}),setData:(e,t)=>o.sync(()=>{r.setQueryData(e,t)}),update:(e,t)=>o.sync(()=>{r.setQueriesData({queryKey:e},t)})})},x=(r)=>h.succeed(l,W(r));import{useQueryClient as M}from"@tanstack/react-query";import*as g from"effect/ManagedRuntime";import{createContext as q,useContext as U,useMemo as P}from"react";import{jsx as F}from"react/jsx-runtime";var V=q(null),K=({children:r})=>{let a=M(),i=P(()=>g.make(x(a)),[a]);return F(V.Provider,{value:i,children:r})},T=()=>{let r=U(V);if(r===null)throw Error("useEffectRuntime requires an EffectRuntimeProvider");return r};import{client as j,studioAgentRunsGet as z,studioAgentRunsList as B,studioViewDataGetItem as H,studioViewDataSearch as J,studioViewDataSearchMembers as X,studioViewDataUpdateItem as Y,studioWorkflowRunsGet as Z,studioWorkflowRunsList as _}from"@collective-intelligence/extensions-sdk-frontend-react/studio-api";import*as G from"effect/Config";import*as k from"effect/Context";import*as m from"effect/Effect";import*as y from"effect/Layer";class E extends k.Service()("@collective-intelligence/extensions-sdk-frontend-react/StudioApi"){}var ee=(r={})=>{let a=r.baseUrl===void 0?{}:{baseUrl:r.baseUrl},i=(e,t)=>m.fn(`StudioApi.${e}`)(function*(s){let R=!1,A=j.getConfig().fetch??globalThis.fetch,C=Object.assign(async(p,b)=>(R=!0,await A(p,b)),A),d=yield*m.tryPromise({catch:(p)=>{if(R)return new f({cause:p});throw p},try:(p)=>t(s,{...a,fetch:C,responseStyle:"fields",signal:p,throwOnError:!1})});if(d.response===void 0)return yield*new f({cause:d.error});if(!d.response.ok)return yield*new c({body:d.error,status:d.response.status});return d.data});return E.of({studioAgentRunsGet:i("studioAgentRunsGet",(e,t)=>z({...e,...t})),studioAgentRunsList:i("studioAgentRunsList",(e,t)=>B({...e,...t})),studioViewDataGetItem:i("studioViewDataGetItem",(e,t)=>H({...e,...t})),studioViewDataSearch:i("studioViewDataSearch",(e,t)=>J({...e,...t})),studioViewDataSearchMembers:i("studioViewDataSearchMembers",(e,t)=>X({...e,...t})),studioViewDataUpdateItem:i("studioViewDataUpdateItem",(e,t)=>Y({...e,...t})),studioWorkflowRunsGet:i("studioWorkflowRunsGet",(e,t)=>Z({...e,...t})),studioWorkflowRunsList:i("studioWorkflowRunsList",(e,t)=>_({...e,...t}))})},O=(r={})=>y.sync(E,()=>ee(r)),te=(r)=>y.unwrap(m.map(G.unwrap(r),O));export{K as EffectRuntimeProvider,l as QueryCache,E as StudioApi,c as StudioApiError,f as StudioApiTransportError,v as fromEffect,O as layerStudioApi,te as layerStudioApiConfig,T as useEffectRuntime};
package/docs/effect.md CHANGED
@@ -101,6 +101,40 @@ export const RowsWidget = (props: Readonly<{ name: string }>) => (
101
101
  )
102
102
  ```
103
103
 
104
+ ### Optimistic write
105
+
106
+ An optimistic write shows its value before the Studio API answers. In its
107
+ actor: `cancel` the keys that it changes, so that a fetch that ends later does
108
+ not replace the new value; `update` them; run the write; and `invalidate` the
109
+ keys when the actor ends, also when it fails or is interrupted, so views read
110
+ the stored value.
111
+
112
+ ```ts
113
+ type RenameInput = Readonly<{
114
+ id: string
115
+ name: string
116
+ runtime: EffectRunner<QueryCache>
117
+ }>
118
+
119
+ const rename = fromEffect((input: RenameInput) =>
120
+ QueryCache.use((cache) =>
121
+ cache
122
+ .cancel(rowsKey)
123
+ .pipe(
124
+ Effect.andThen(
125
+ cache.update<ReadonlyArray<Row>>(rowsKey, (rows) =>
126
+ rows?.map((row) =>
127
+ row.id === input.id ? { ...row, name: input.name } : row
128
+ )
129
+ )
130
+ ),
131
+ Effect.andThen(writeName(input.id, input.name)),
132
+ Effect.ensuring(cache.invalidate(rowsKey))
133
+ )
134
+ )
135
+ )
136
+ ```
137
+
104
138
  ## Rules of the write parts
105
139
 
106
140
  - Mount `EffectRuntimeProvider` at the root of each widget. It uses the
@@ -110,12 +144,18 @@ export const RowsWidget = (props: Readonly<{ name: string }>) => (
110
144
  `fromEffect` actor runs on `input.runtime`.
111
145
  - A stop of the actor interrupts the fiber. After a stop, no result of that
112
146
  run gets to the actor, also in a React Strict Mode remount.
113
- - `QueryCache.invalidate`, `update` and `remove` apply to the key and to each
114
- key below it. Start each key with the package name: the Host and all widgets
147
+ - `QueryCache.invalidate`, `cancel`, `update` and `remove` apply to the key
148
+ and to each key below it. Start each key with the package name: the Host and all widgets
115
149
  share one `QueryClient`.
116
150
  - `QueryCache.fetch` runs its query once, without a retry, and fails with
117
- `StudioApiError` or `StudioApiTransportError`. Another failure is a Defect;
118
- a cancel of the key is an interruption.
151
+ `StudioApiError` or `StudioApiTransportError`. Another failure is a Defect.
152
+ A cancel of the key interrupts the query; the waiting `fetch` then returns
153
+ the cached value, or is interrupted when the key has no value.
154
+ - `QueryCache.cancel` cancels the running fetches and interrupts their
155
+ queries, so they write no value. It keeps the cached values and starts no
156
+ fetch: a view of a key whose first fetch it cancels shows no value until the
157
+ next fetch. `update` does not cancel a running fetch, which can replace the new
158
+ value when it ends.
119
159
  - `xstate` is a required peer that the Studio and Dashboard Hosts provide; a
120
160
  widget bundle carries no copy of XState. The first Hosts that provide it
121
161
  ship in the first ci-app release after `@collective-intelligence/cli@0.2.2`,
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@collective-intelligence/extensions-sdk-frontend-react",
3
- "version": "0.2.3",
3
+ "version": "0.2.4",
4
4
  "description": "Public hosted React contribution contracts for Collective Intelligence extensions.",
5
5
  "type": "module",
6
6
  "sideEffects": false,
@@ -125,5 +125,5 @@
125
125
  "@xstate/react": "6.1.0",
126
126
  "xstate": "5.33.3"
127
127
  },
128
- "gitHead": "1718b80bc8d0ba696d78ac8f5f905c8dc46fe0c5"
128
+ "gitHead": "7972d94333f423906752b69ac20d4ffc44e5d841"
129
129
  }