@rise-x/apps-sdk 0.19.0 → 0.20.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.
Files changed (40) hide show
  1. package/API.md +145 -0
  2. package/README.md +177 -10
  3. package/build/accessors.d.ts +2 -1
  4. package/build/accessors.js +10 -0
  5. package/build/connectors/assets.d.ts +5 -2
  6. package/build/connectors/assets.js +22 -6
  7. package/build/connectors/index.d.ts +1 -1
  8. package/build/connectors/types.d.ts +8 -0
  9. package/build/connectors/types.js +36 -4
  10. package/build/connectors/work.d.ts +1 -0
  11. package/build/connectors/work.js +66 -3
  12. package/build/dependencies/bound.d.ts +2 -2
  13. package/build/index.d.ts +2 -1
  14. package/build/index.js +4 -1
  15. package/build/live/index.d.ts +43 -0
  16. package/build/live/index.js +183 -0
  17. package/build/liveChannel.d.ts +32 -0
  18. package/build/liveChannel.js +60 -0
  19. package/build/mockShell.d.ts +2 -0
  20. package/build/mockShell.js +1 -0
  21. package/build/query/assets.d.ts +4 -4
  22. package/build/query/assets.js +13 -7
  23. package/build/query/index.d.ts +1 -0
  24. package/build/query/index.js +4 -2
  25. package/build/query/live.d.ts +14 -0
  26. package/build/query/live.js +115 -0
  27. package/build/shell/index.d.ts +2 -1
  28. package/build/shell/installShellBridge.d.ts +15 -1
  29. package/build/shell/installShellBridge.js +7 -1
  30. package/build/shell/liveHub.d.ts +25 -0
  31. package/build/shell/liveHub.js +201 -0
  32. package/build/shellBridge.d.ts +116 -1
  33. package/build/shellBridge.js +5 -1
  34. package/build/ui/demo.html +199 -197
  35. package/build/ui/standalone.js +60 -60
  36. package/build/ui/styles.css +1 -1
  37. package/build/ui/theme.css +9 -5
  38. package/live/package.json +8 -0
  39. package/package.json +7 -1
  40. package/template/AGENTS.md +6 -0
package/API.md ADDED
@@ -0,0 +1,145 @@
1
+ # @rise-x/apps-sdk API summary
2
+
3
+ Read this before you write app code. It lists the calls most apps need and the
4
+ rules that make them work, for the SDK version installed next to it. For
5
+ anything it leaves out, follow the pointers in "Where to look next".
6
+
7
+ ## Import paths
8
+
9
+ - `@rise-x/apps-sdk`: shell hooks and accessors, lifecycle hook types, `createMockShell`.
10
+ - `@rise-x/apps-sdk/dependencies`: `useAppDependencies()`, the ids from `rise-x-app.json` with bound calls.
11
+ - `@rise-x/apps-sdk/query`: react-query hooks over the connectors. Mount no provider of your own.
12
+ - `@rise-x/apps-sdk/connectors`: `flows`, `work`, `assets`, `agents`, `attachments`, `integrations`, `vectorStores`, `ConnectorError`.
13
+ - `@rise-x/apps-sdk/live`: live events and editor locks.
14
+ - `@rise-x/apps-sdk/ui`: the design system components.
15
+
16
+ To reach the platform, use the first that fits: a declared dependency, a query
17
+ hook, a connector, and only then `getShellApiV4(key)`.
18
+
19
+ ## Shell hooks and accessors (`@rise-x/apps-sdk`)
20
+
21
+ - `useShellUser()` returns `{ id, name, email? } | null`. `id` is the user's directory id, the same value as `createdBy` and `assignedUsers.id` on a work item.
22
+ - `useShellEnvironment()` returns `{ id, name, slug } | null`.
23
+ - `useShellNavigate()` returns react-router's `navigate` function.
24
+ - `getShellApiV4(key)` with `key` `'apps' | 'work' | 'config' | 'attachment' | 'asset'`, and `getShellApi()`: raw axios clients, the last resort.
25
+ - `getShellAi()` and `getShellLive()` return `null` on a host without that feature.
26
+
27
+ ## Dependencies (`@rise-x/apps-sdk/dependencies`)
28
+
29
+ ```ts
30
+ import { useAppDependencies, type BoundFlowDependency } from '@rise-x/apps-sdk/dependencies';
31
+
32
+ type AppDeps = { tasks: BoundFlowDependency }; // a type alias: an interface fails the constraint
33
+ const { tasks } = useAppDependencies<AppDeps>(); // throws ConnectorError when no manifest is built in
34
+ const created = await tasks.work.start({ data: { title: 'New task' } });
35
+ ```
36
+
37
+ An undeclared alias reads as `undefined`; `getAppDependency(alias)` throws for one instead.
38
+
39
+ - `flow`: `dep.flowOriginId`, `dep.flow.get()`, `dep.flow.getConfig()`, `dep.work.start(args?)`, `dep.work.list(args?)`, `dep.work.iterate(args?)`, `dep.work.search(args?)`.
40
+ - `assetType`: `dep.flowOriginId`, `dep.assets.list()`, `.iterate()`, `.search()`, `.quickSearch()`, `.create()`.
41
+ - `agent`: `dep.agentId`, `dep.agent.get()`, `.run({ message })`, `.createChat()`, `.listChats()`.
42
+ - `integration`: `dep.integrationId`, `dep.endpointId`, `dep.integration.invoke({ data? })`.
43
+ - Each bound call takes the generic call's arguments minus the ref. On `dep.work.search` and `dep.assets.search`, `filter` is optional: the call adds the `flowOriginId` pin and ands your filter with it.
44
+
45
+ ## Query hooks (`@rise-x/apps-sdk/query`)
46
+
47
+ Read hooks take an optional last `SdkQueryOptions` (`enabled`, `staleTime`,
48
+ `retry`, and others). Their `error` is a `ConnectorError`. Defaults: `staleTime`
49
+ 30 s, `gcTime` 5 min, no refetch on window focus.
50
+
51
+ - Flows: `useFlows(args?)`, `useFlow(flowId)`, `useFlowConfig(flowId)`, `useFlowLayout(layoutId)`, `useFlowTask({ flow, task })`.
52
+ - Work: `useWork(workId)` (`WorkDetail | null`), `useWorkData(workId, { path? })`, `useWorkSearch(args)` and `useWorkRows(args)` (infinite), `useRelatedWork(args)`, `useWorkAudit(workId)`.
53
+ - Assets: `useAssetTypes()`, `useAsset(id)`, `useAssetSearch(args)` and `useAssetRows(args)` (infinite), `useAssetQuickSearch(args)`, `useRelatedAssets(args)`.
54
+ - Agents: `useAgents(args?)`, `useAgent(id)`, `useAgentChats(args?)`, `useAgentChat(id)`, `useAgentChatMessages(id, args?)`.
55
+ - Mutations: `useStartWork`, `usePatchWorkData` (`{ workId, originId, path, value }`), `useSubmitWork` (`{ workId, actionName, stepName? }`), `useDeleteWork` (`{ workId }`), and the asset and agent ones. On success they refresh the queries the write affects.
56
+ - Connector calls refresh nothing. Take `const client = useAppQueryClient()` in the component body, and after a raw connector write call `invalidateAppSdkQueries(client)`.
57
+ - `dedupeRows(query.data)` flattens the pages of an infinite hook and drops repeated rows.
58
+ - `useLiveInvalidation({ flowOriginIds? })` marks work and asset queries stale when a live event reports a change.
59
+
60
+ ```tsx
61
+ const { tasks } = useAppDependencies<AppDeps>();
62
+ const search = useWorkSearch({
63
+ filter: { and: [
64
+ { field: 'flowOriginId', operator: 'equals', values: [tasks.flowOriginId] },
65
+ { field: 'flowState', operator: 'notEquals', values: ['Complete'] }, // not done
66
+ ] },
67
+ fields: ['flowState', 'data.title'], // data.* arrives under row.data, prefix stripped
68
+ });
69
+ const rows = dedupeRows(search.data); // WorkSummary[]; key them by row.id
70
+ ```
71
+
72
+ ## Connectors (`@rise-x/apps-sdk/connectors`)
73
+
74
+ Work:
75
+ - `work.start({ flowId, stepName?, data? })` returns the new item's `WorkDetail`, the same as `work.get`, so its `actions` are ready for `work.submit`. `flowId` takes a flow id or a flow origin id.
76
+ If the SDK can't read the new item back, `start` still returns it, with `actions` empty and no `status`: call `work.get(id)` before you submit.
77
+ - `work.get(id)` returns `WorkDetail | null` (`null` only on a 404): `status`, `state`, `flowOriginId`, `actions`, `attachments`.
78
+ - `work.getData(id, { path? })` returns the data document, or the subtree at `path`.
79
+ - `work.patchData(id, { originId, path, value, operation? })` writes one field. `operation` defaults to `'Set'`.
80
+ - `work.submit({ workId, actionName, stepName? })` runs an action and returns the `WorkDetail` after the flow engine ran, the same as `work.get`. The same rule as `start` applies when the SDK can't read the item back. Leave `stepName` out: the SDK sends the name of the action set that offers the action.
81
+ - `work.delete(id)` soft-deletes the item.
82
+ - `work.search({ filter, fields?, sort?, page?, pageSize?, includeTotalCount? })` returns `{ items: WorkSummary[], page, pageSize, hasMore, totalCount? }`.
83
+ - `work.list({ flow, stepIds?, properties?, showCompleted?, sort?, pageSize?, skip? })` returns `{ items: WorkRow[], skip, pageSize, hasMore }`. `work.iterate({ ..., maxItems? })` yields every row.
84
+ - `work.getMyAccess(id)`, `work.listRelated({ workId, relationships })`, and `work.getAudit(id)` cover access, related items, and history.
85
+
86
+ Flows: `flows.list({ search?, statuses? })` lists work flows only. `flows.get(ref)`
87
+ returns the flow with its steps and throws on a 404. `flows.getConfig(ref)` and
88
+ `flows.getLayout(layoutId)` return `null` on a 404. `flows.flattenLayoutFields(layout)`
89
+ lists a layout's fields with their data paths. `flows.findTask({ flow, task })`
90
+ returns `{ flow, step, task } | null`.
91
+
92
+ Assets: `assets.types()` returns `AssetType[]`, with the origin id at
93
+ `type.flow.flowOriginId`. `assets.get(id)`, `assets.search({ filter, ... })` (same
94
+ shape as `work.search`), `assets.quickSearch({ search?, type?, typeOriginId? })`,
95
+ `assets.list({ type, ... })`, and `assets.iterate(...)` read. `assets.create({ type })`
96
+ and `assets.startEdit({ assetId, flowOriginId })` return an `AssetDraft`: the draft
97
+ work item as `work.get` returns it, plus `assetId`. Its `id` is the draft's, so fill
98
+ it with `work.patchData(draft.id, ...)` and save it with `work.submit` and one of its
99
+ `actions`. If the read of the draft fails, `actions` is empty: call `work.get(draft.id)`
100
+ before you submit. If the answer names no draft, the call throws `PARSE_ERROR`.
101
+ `assets.clone(id)` and `assets.delete(id)` complete the set.
102
+
103
+ Agents: `agents.run({ agentId, message, chatId?, context?, attachments?, vectorStoreIds? })`
104
+ streams `AgentRunEvent`s. `agents.createChat({ agentId })` returns a session whose
105
+ `send(message)` keeps the chat id between turns. `collectAgentReply(events)`
106
+ resolves to `{ text, delta, done, reason, error, chatId }`, and `streamAgentReply(events)`
107
+ yields the same snapshot as the reply grows. `agents.list`, `get`, `create`,
108
+ `update`, `delete`, and the chat calls manage agents and their chats.
109
+
110
+ Others: `attachments.getBlob({ id, resourceId })` returns `Blob | null`,
111
+ `attachments.upload({ workId, files, folder })`, `attachments.delete({ id })`.
112
+ `integrations.invoke({ integrationId, endpointId, data? })` returns
113
+ `{ statusCode, success, response, items, message, executionTimeMs }`. `vectorStores` creates and fills
114
+ vector stores for agents.
115
+
116
+ Errors: every connector call rejects with a `ConnectorError`. Check `code`:
117
+ `NOT_FOUND` (a 404), `HTTP_ERROR` (other non-2xx, with `status`), `NETWORK_ERROR`,
118
+ `ABORTED`, `INVALID_ARG`, `SHELL_UNAVAILABLE`, and others.
119
+
120
+ ```ts
121
+ // Submit the action the user picked, by its event name, from the item's own list.
122
+ const detail = await work.get(workId);
123
+ if (!detail) throw new Error(`Work item ${workId} not found`);
124
+ const chosen = detail.actions.find((a) => a.id === pickedActionId);
125
+ if (!chosen) throw new Error(`Action ${pickedActionId} is not available on this item`);
126
+ await work.patchData(workId, { originId: detail.flowOriginId!, path: '$.title', value: title });
127
+ await work.submit({ workId, actionName: chosen.eventName ?? chosen.name! });
128
+ ```
129
+
130
+ ## Work item rules
131
+
132
+ - `status` is the record's lifecycle: `Open` after `work.start`, `Deleted` after a delete. A finished item can still read `Open`, so never read done from `status`.
133
+ - Done is the flow's position: `flowState` is `'Complete'` on a `work.search` row, and the same value is `state` on `work.get`.
134
+ - `work.patchData` changes a field and runs no action. `work.submit` moves the step: approve, reject, send back, finish. Await `patchData` first: submit merges no data, and the platform checks the action's condition against the saved data.
135
+ - Take `actionName` from the item's own `actions`, as `eventName ?? name` of the action the user picked. Never guess a name or take `actions[0]`. The platform rejects a name that is not an action of the step with a 403 and leaves the item unchanged.
136
+ - `work.submit` reads the item and its flow config, finds the action set that offers the action, and sends that action set's name as `stepName`. Pass `stepName` only to pick between two action sets that offer the same action: the `name` of the entry in `flows.getConfig(detail.flowId)`'s `tasks[].actionSets` whose `id` is the picked action's `actionSetId`. Never pass a step or task name: with `Submit`, the platform answers 200 and the item doesn't move.
137
+ - `work.list` and `work.iterate` filter strictly by flow origin id. A concrete flow id returns an empty list, not an error. Pass the flow object or `dep.flowOriginId`.
138
+ - `work.search` and `assets.search` need a `flowOriginId` `equals` or `in` condition at the top level or under `and`. Without it the server returns a 400.
139
+ - `work.delete` is a soft delete: `status` and `flowState` become `Deleted`, and the record stays. A second delete rejects with `NOT_FOUND`. The SDK has no restore call. `work.search` leaves deleted items out unless the filter names `status`.
140
+ - Key rows by `id`. `displayName` can repeat, and `workCode` can be missing.
141
+
142
+ ## Where to look next
143
+
144
+ - README sections: "Choosing an API", "Bound connectors", "Work — items (read + write)", "Assets — typed records", "Agents — configurable AI", "Query layer (react-query)", "Live events and presence", "UI components".
145
+ - Types: `build/connectors/types.d.ts` (`WorkDetail`, `WorkSummary`, `WorkRow`, `AssetType`), `build/connectors/assets.d.ts` (`AssetDraft`), `build/connectors/work.d.ts`, `build/connectors/search.d.ts`, `build/dependencies/bound.d.ts`, `build/query/index.d.ts`, `build/live/index.d.ts`.
package/README.md CHANGED
@@ -2,9 +2,10 @@
2
2
 
3
3
  SDK for building federated apps on top of the Rise-X Diana shell.
4
4
 
5
- - **Runtime hooks/accessors** — `useShellUser`, `useShellEnvironment`, `useShellNavigate`, `getShellApi`, `getShellApiV4`, `getShellAi`.
5
+ - **Runtime hooks/accessors** — `useShellUser`, `useShellEnvironment`, `useShellNavigate`, `getShellApi`, `getShellApiV4`, `getShellAi`, `getShellLive`.
6
6
  - **App dependencies** — `rise-x-app.json` declares the flows, asset types, agents, and integration endpoints the app depends on, one id (or id pair) per environment; `@rise-x/apps-sdk/dependencies` reads them back as `deps.<alias>`, with the connector calls that take that ref pre-filled. This is the first choice for any Rise-X object the app knows at authoring time.
7
7
  - **Connectors** — `@rise-x/apps-sdk/connectors` exposes typed, higher-level API wrappers (`flows`, `work`, `assets`, `agents`, `integrations`) so apps don't hand-roll multi-step API calls. Use them for what a declared dependency can't express.
8
+ - **Live events and presence** — `@rise-x/apps-sdk/live` lets an app hear about other people's changes and see who is editing, over the host's own connection instead of polling; `useLiveInvalidation` on `@rise-x/apps-sdk/query` keeps the query cache current from the same events.
8
9
  - **Lifecycle hooks** — `onInstall`, `onUpdate`, `onUninstall` that apps export from a federated `./lifecycle` module; the shell invokes them best-effort.
9
10
  - **Standalone-dev mock** — `createMockShell` for running an app outside the shell.
10
11
  - **Shell-side installer** — `@rise-x/apps-sdk/shell` exposes `installShellBridge` for the host to wire the bridge.
@@ -1104,12 +1105,22 @@ await work.patchData(created.id, {
1104
1105
  });
1105
1106
 
1106
1107
  // Complete a task action. Patch data first — submit does not merge data.
1107
- const action = detail.actions[0];
1108
- const actionName = action?.eventName ?? action?.name;
1109
- if (!actionName) throw new Error('work item has no available action');
1110
- await work.submit({ workId: created.id, actionName });
1111
-
1112
- // Remove a work item (no server-side undo).
1108
+ // Submit the action the user picked, found by id in the item's own list; never
1109
+ // guess a name or take actions[0]. A missing action is normal (someone else moved
1110
+ // the step): tell the user and refresh, never skip it silently.
1111
+ // `pickedActionId` is the `id` of the action the user clicked, from a button
1112
+ // the app rendered for each entry of `detail.actions`.
1113
+ // Leave `stepName` out: submit reads the work and its flow config and sends the
1114
+ // name of the action set that offers the action. Pass one only to pick between
1115
+ // two action sets that offer the same action: the `name` of the `actionSets`
1116
+ // entry in flows.getConfig(detail.flowId) whose `id` is chosen.actionSetId.
1117
+ // A step or task name moves nothing.
1118
+ const chosen = detail.actions.find((a) => a.id === pickedActionId);
1119
+ if (!chosen) throw new Error(`Action ${pickedActionId} is not available on this item`);
1120
+ await work.submit({ workId: created.id, actionName: chosen.eventName ?? chosen.name! });
1121
+
1122
+ // Soft-delete a work item: its status becomes Deleted and the record stays.
1123
+ // A second delete rejects with NOT_FOUND. The SDK has no restore call.
1113
1124
  await work.delete(created.id);
1114
1125
 
1115
1126
  // Paginated listing — `properties` shapes each row's `data` subtree.
@@ -1232,8 +1243,11 @@ const related = await assets.listRelated({ assetId: detail.id, relationships: ['
1232
1243
  // fill it with work.patchData(), save it with work.submit().
1233
1244
  const draft = await assets.create({ type: supplier });
1234
1245
  await work.patchData(draft.id, { originId: draft.flowOriginId!, path: '$.supplier.name', value: 'Acme' });
1235
- const submitAction = draft.actions[0];
1236
- await work.submit({ workId: draft.id, actionName: submitAction.eventName ?? submitAction.name! });
1246
+ // Save with the action the user picked from the draft's own `actions`, found by
1247
+ // id, as in the work example; never take actions[0].
1248
+ const chosen = draft.actions.find((a) => a.id === pickedActionId);
1249
+ if (!chosen) throw new Error(`Action ${pickedActionId} is not available on this draft`);
1250
+ await work.submit({ workId: draft.id, actionName: chosen.eventName ?? chosen.name! });
1237
1251
 
1238
1252
  const editDraft = await assets.startEdit({ assetId: detail.id, flowOriginId: detail.flowOriginId! });
1239
1253
  await assets.clone(detail.id);
@@ -1624,7 +1638,7 @@ const devAxios = axios.create({
1624
1638
  window.__DIANA_SHELL__ = createMockShell({
1625
1639
  api: () => devAxios,
1626
1640
  apiV4: (_name) => devAxios, // one dev backend serves every V4ApiKey
1627
- ai: { baseUrl: 'http://localhost:50062', getHeaders: () => ({ Authorization: token, Ecosystem: 'dev' }) },
1641
+ ai: { baseUrl: 'http://localhost:50062', getHeaders: () => ({ Authorization: token, Environment: 'dev' }) },
1628
1642
  });
1629
1643
  ```
1630
1644
 
@@ -1792,6 +1806,148 @@ Details worth knowing:
1792
1806
  use the infinite hooks instead) and the SSE streams (`agents.run`,
1793
1807
  chat `send`) stay on the connectors.
1794
1808
 
1809
+ ## Live events and presence (`@rise-x/apps-sdk/live`)
1810
+
1811
+ The host holds one connection to the platform's event hub. Through the bridge
1812
+ (`getLive()`, bridge v5) an app hears about other people's changes and sees who
1813
+ is editing, without opening a connection of its own or polling. The host
1814
+ translates the hub's events into the SDK's own `LiveEvent`s, so an app never
1815
+ depends on the platform's wire names.
1816
+
1817
+ ### Keep the query cache current
1818
+
1819
+ An app that renders with this SDK's query hooks needs one line, near its root:
1820
+
1821
+ ```tsx
1822
+ import { useLiveInvalidation } from '@rise-x/apps-sdk/query';
1823
+
1824
+ function App() {
1825
+ const deps = useAppDependencies();
1826
+ useLiveInvalidation({ flowOriginIds: [deps.riskFlow.flowOriginId] });
1827
+ // …
1828
+ }
1829
+ ```
1830
+
1831
+ A change marks the work item's or asset's queries and the listings stale (only
1832
+ the ones on screen refetch), a delete drops the item's queries, and a `resync`
1833
+ marks every work and asset query stale. A burst, such as a form saved one field
1834
+ at a time, is collected for 300 ms and refreshes once. `flowOriginIds` skips
1835
+ data writes in other flows; a change that names no flow always counts.
1836
+
1837
+ ### Handle events yourself
1838
+
1839
+ ```tsx
1840
+ import { useLiveEvents, useLiveStatus } from '@rise-x/apps-sdk/live';
1841
+
1842
+ useLiveEvents((event) => {
1843
+ switch (event.type) {
1844
+ case 'workData': // a write: event.path, operation, hasValue, value, flowOriginId, userId
1845
+ case 'workUpdated': // created, submitted, moved to another step: read the work
1846
+ case 'workDeleted':
1847
+ if (held.has(event.workId)) reread(event.workId);
1848
+ break;
1849
+ case 'resync': // the connection came back: re-read what you show
1850
+ rereadEverythingShown();
1851
+ break;
1852
+ }
1853
+ });
1854
+
1855
+ const status = useLiveStatus();
1856
+ ```
1857
+
1858
+ | Event | When | Carries |
1859
+ | --- | --- | --- |
1860
+ | `workData` | a write to a work item's data | `workId`, `path`, `operation`, `hasValue`, `value`, `flowOriginId`, `userId`, `updateId` |
1861
+ | `workUpdated` | a create, a submit, a step move, a bulk write | `workId`, `displayName` |
1862
+ | `workDeleted` | a delete | `workId` |
1863
+ | `assetUpdated` / `assetDeleted` | an asset created, changed or deleted | `assetId`, and `displayName` on an update |
1864
+ | `lock` | a user took or released a component lock | `workId`, `userId`, `displayName`, `componentId`, `dataPath`, `at`, `locked` |
1865
+ | `resync` | the connection came back | nothing |
1866
+
1867
+ `useLiveStatus()` is `connecting` until the first connection, `reconnecting`
1868
+ while the host retries one that dropped, `disconnected` after a close, and
1869
+ `connected` while events arrive. Each return to `connected` sends one `resync`,
1870
+ and so does the host replacing its connection (an environment switch).
1871
+ `unavailable` means the host offers no live events at all.
1872
+
1873
+ Treat an event as a reason to re-read, never as the data:
1874
+
1875
+ - **Not every change sends one.** A change to a work item's properties (rather
1876
+ than its data) and a removed attachment send nothing. Keep a re-read for when
1877
+ the window regains focus.
1878
+ - **Your own writes come back.** `userId` says who wrote. A write that reaches a
1879
+ user twice (directly and through a group) is reported once, but a
1880
+ `workUpdated` or `workDeleted` can still arrive twice.
1881
+ - **Events arrive for everything the user can see**, in every ecosystem they
1882
+ belong to. Act on the ids and flows you hold.
1883
+ - **`hasValue: false` means read the path.** An object or list value, a delivery
1884
+ through a group, and an operation outside `WorkPatchOperationName` carry no
1885
+ value. A very large write can fail to arrive, so re-read by id rather than
1886
+ trusting `value`.
1887
+ - **Nothing is replayed.** Events sent while the connection was down are lost;
1888
+ `resync` says when to re-read.
1889
+
1890
+ Re-read by id (`work.getData(id)`) rather than through a search: a search can
1891
+ lag a write, the document does not.
1892
+
1893
+ ### Show who is editing
1894
+
1895
+ ```tsx
1896
+ import { useComponentLock, useWorkLocks } from '@rise-x/apps-sdk/live';
1897
+
1898
+ // A fixed GUID for this editor, the same in every session.
1899
+ const RISK_EDITOR = '6f1c2a4e-0b7d-4c55-9a51-3f0e8d2b7c19';
1900
+
1901
+ function RiskEditor({ workId, open }: { workId: string; open: boolean }) {
1902
+ useComponentLock(workId, RISK_EDITOR, open);
1903
+ const editing = useWorkLocks(workId).filter((lock) => lock.userId !== me.id);
1904
+ // …
1905
+ }
1906
+ ```
1907
+
1908
+ - `useComponentLock(workId, componentId, active, dataPath?)` takes the user's
1909
+ lock while `active`, says it again every `LOCK_REFRESH_MS` (one minute) and
1910
+ after a reconnect, and releases it when `active` ends or the component
1911
+ unmounts. `getShellLive()?.setComponentLock({ workId, componentId, dataPath,
1912
+ locked })` does the same by hand.
1913
+ - `useWorkLocks(workId)` is everyone's locks on the work, yours included: it
1914
+ starts from a read of the work (`WorkDetail.activeLocks`) and follows `lock`
1915
+ events.
1916
+ - Locks are advisory: they never block a write. They go over the host's
1917
+ connection, so without one a lock call rejects (`useComponentLock` ignores
1918
+ that) and the app keeps working.
1919
+ - The platform keeps **one lock per user per work**. A lock this app takes and
1920
+ one the host's own editor takes for the same user replace each other, and
1921
+ releasing either clears it. Within one app, several `useComponentLock` holds
1922
+ on a work stack: the newest shows, and releasing it takes the previous one
1923
+ again.
1924
+ - A lock from a closed browser can linger on the platform: compare `at` with the
1925
+ age you are willing to believe.
1926
+
1927
+ ### Hosts without live events, and standalone dev
1928
+
1929
+ On a host that predates bridge v5, or one that offers no live events,
1930
+ `getShellLive()` is null, `useLiveStatus()` is `unavailable`, and every hook
1931
+ does nothing, so keep the app's own reads for those hosts. A connection that is
1932
+ only down is different: `getShellLive()` still answers, its status is
1933
+ `disconnected` until the connection is back, and a `resync` follows.
1934
+
1935
+ Under `pnpm start`, give the mock shell a channel and drive it by hand:
1936
+
1937
+ ```ts
1938
+ import { createLiveChannel, createMockShell } from '@rise-x/apps-sdk';
1939
+
1940
+ const live = createLiveChannel({ status: 'connected' });
1941
+ createMockShell({ live });
1942
+
1943
+ live.emit({ type: 'workUpdated', workId: 'w1' });
1944
+ live.setStatus('reconnecting');
1945
+ live.setStatus('connected'); // sends a resync
1946
+ ```
1947
+
1948
+ Pass `setComponentLock` to `createLiveChannel` to see the locks the app sends;
1949
+ without it, a lock call rejects.
1950
+
1795
1951
  ## Shell-side (host) wiring
1796
1952
 
1797
1953
  ```ts
@@ -1819,6 +1975,17 @@ endpoint) to route asset search independently.
1819
1975
  and router `navigate` into the bridge via `getMutableShell` — also exported from
1820
1976
  `@rise-x/apps-sdk/shell`.
1821
1977
 
1978
+ The same keeper reports the hub connection for live events (bridge v5):
1979
+ `_setLiveConnection(connection, state)` whenever the connection or its state changes.
1980
+ `connection` is anything with SignalR's `on` / `off` / `invoke` (a `HubConnection` as is),
1981
+ or null while there is none; `state` is the connection's own `connecting`, `connected`,
1982
+ `reconnecting` or `disconnected`. The bridge does the rest the same way in every host: it
1983
+ maps the hub's events to `LiveEvent`s, moves its handlers to a new connection, turns the
1984
+ state into the status apps see (with a `resync` on each return to `connected` and on a
1985
+ replaced connection), reports a write delivered twice once, and sends locks over the hub.
1986
+ A host with no hub passes `live: false` to `installShellBridge`, and `getLive()` answers
1987
+ null.
1988
+
1822
1989
  The shell's `RemoteAppLoader` additionally wraps every mounted app in a
1823
1990
  per-app `QueryClient` (built with `createAppQueryClient` from
1824
1991
  `@rise-x/apps-sdk/query`), which is what the SDK's query hooks pick up
@@ -1,8 +1,9 @@
1
1
  import type { AxiosInstance } from "axios";
2
- import type { DianaShell, ShellAiApi, ShellEnvironment, ShellUser, V4ApiKey } from "./shellBridge";
2
+ import type { DianaShell, LiveApi, ShellAiApi, ShellEnvironment, ShellUser, V4ApiKey } from "./shellBridge";
3
3
  export declare function getShellApi(): AxiosInstance;
4
4
  export declare function getShellApiV4(name: V4ApiKey): AxiosInstance;
5
5
  export declare function getShell(): DianaShell | null;
6
6
  export declare function getShellUser(): ShellUser | null;
7
7
  export declare function getShellAi(): ShellAiApi | null;
8
+ export declare function getShellLive(): LiveApi | null;
8
9
  export declare function getShellEnvironment(): ShellEnvironment | null;
@@ -5,6 +5,7 @@ exports.getShellApiV4 = getShellApiV4;
5
5
  exports.getShell = getShell;
6
6
  exports.getShellUser = getShellUser;
7
7
  exports.getShellAi = getShellAi;
8
+ exports.getShellLive = getShellLive;
8
9
  exports.getShellEnvironment = getShellEnvironment;
9
10
  const _internal_1 = require("./_internal");
10
11
  function getShellApi() {
@@ -35,6 +36,15 @@ function getShellAi() {
35
36
  return null;
36
37
  return shell.getAi();
37
38
  }
39
+ // The host's live events and component locks, or null when the shell is missing, predates bridge
40
+ // v5 (no getLive), or offers no live events. Feature-detected so a v5-built app degrades cleanly
41
+ // on an older host.
42
+ function getShellLive() {
43
+ const shell = getShell();
44
+ if (!shell || typeof shell.getLive !== "function")
45
+ return null;
46
+ return shell.getLive();
47
+ }
38
48
  function getShellEnvironment() {
39
49
  return getShell()?.getEnvironment() ?? null;
40
50
  }
@@ -48,6 +48,9 @@ export interface CreateAssetArgs {
48
48
  type: AssetTypeRef;
49
49
  signal?: AbortSignal;
50
50
  }
51
+ export interface AssetDraft extends WorkDetail {
52
+ assetId: string;
53
+ }
51
54
  export interface StartEditAssetArgs {
52
55
  assetId: string;
53
56
  flowOriginId: string;
@@ -65,8 +68,8 @@ export interface AssetsConnector {
65
68
  list(args: ListAssetRowsArgs): Promise<AssetRowPage>;
66
69
  iterate(args: IterateAssetRowsArgs): AsyncIterable<AssetSummary>;
67
70
  listRelated(args: ListRelatedAssetsArgs): Promise<AssetSummary[]>;
68
- create(args: CreateAssetArgs): Promise<WorkDetail>;
69
- startEdit(args: StartEditAssetArgs): Promise<WorkDetail>;
71
+ create(args: CreateAssetArgs): Promise<AssetDraft>;
72
+ startEdit(args: StartEditAssetArgs): Promise<AssetDraft>;
70
73
  clone(assetId: string, opts?: {
71
74
  signal?: AbortSignal;
72
75
  }): Promise<AssetDetail>;
@@ -5,8 +5,9 @@
5
5
  // Asset types are defined by entity flows; the flow's origin id is the type
6
6
  // reference list()/create() take. Creating or editing an asset goes through a
7
7
  // draft work item (the platform's edit model): create()/startEdit() return the
8
- // draft as a WorkDetail — fill it with work.patchData() and save it with
9
- // work.submit(), exactly like any other work item.
8
+ // draft as work.get() returns it, plus the asset's id — fill it with
9
+ // work.patchData() and save it with work.submit(), exactly like any other work
10
+ // item.
10
11
  Object.defineProperty(exports, "__esModule", { value: true });
11
12
  exports.assets = exports.ASSET_TARGET_DATA_TYPES = void 0;
12
13
  exports.createAssetsConnector = createAssetsConnector;
@@ -30,6 +31,7 @@ const resolveTypeRef = (type) => {
30
31
  return flowOriginId;
31
32
  };
32
33
  const DEFAULT_PAGE_SIZE = 50;
34
+ const EMPTY_GUID = "00000000-0000-0000-0000-000000000000";
33
35
  function createAssetsConnector(deps = { shell: _internal_1.requireShell }) {
34
36
  const api = () => deps.shell().getApi();
35
37
  const types = async (opts = {}) => {
@@ -176,24 +178,38 @@ function createAssetsConnector(deps = { shell: _internal_1.requireShell }) {
176
178
  throw (0, errors_1.toConnectorError)(e);
177
179
  }
178
180
  };
181
+ // Both v3 answers are the asset; its draft is `draftWorkId`, read from v4 as
182
+ // work.start() does. `workDraft` is the v3 copy, used if that read fails.
183
+ const toDraft = async (answer, signal) => {
184
+ const asset = (0, types_1.mapAssetDetail)(answer ?? {});
185
+ const draftWorkId = asset.draftWorkId;
186
+ if (!draftWorkId || draftWorkId === EMPTY_GUID) {
187
+ throw new errors_1.ConnectorError("PARSE_ERROR", `the answer for asset '${asset.id}' named no draft work item`);
188
+ }
189
+ const written = (0, types_1.mapWorkDetail)(answer?.workDraft);
190
+ const draft = await (0, work_1.readWorkBack)(deps, draftWorkId, written, signal);
191
+ return { ...draft, assetId: asset.id };
192
+ };
179
193
  const create = async (args) => {
180
194
  const flowOriginId = resolveTypeRef(args.type);
195
+ let answer;
181
196
  try {
182
- const { data } = await api().post(`/api/v3/entity/create/${flowOriginId}`, undefined, { signal: args.signal });
183
- return (0, types_1.mapWorkDetail)(data ?? {});
197
+ ({ data: answer } = await api().post(`/api/v3/entity/create/${flowOriginId}`, undefined, { signal: args.signal }));
184
198
  }
185
199
  catch (e) {
186
200
  throw (0, errors_1.toConnectorError)(e);
187
201
  }
202
+ return toDraft(answer, args.signal);
188
203
  };
189
204
  const startEdit = async (args) => {
205
+ let answer;
190
206
  try {
191
- const { data } = await api().post(`/api/v3/asset/${args.assetId}/edit`, undefined, { params: { flowOriginId: args.flowOriginId }, signal: args.signal });
192
- return (0, types_1.mapWorkDetail)(data ?? {});
207
+ ({ data: answer } = await api().post(`/api/v3/asset/${args.assetId}/edit`, undefined, { params: { flowOriginId: args.flowOriginId }, signal: args.signal }));
193
208
  }
194
209
  catch (e) {
195
210
  throw (0, errors_1.toConnectorError)(e);
196
211
  }
212
+ return toDraft(answer, args.signal);
197
213
  };
198
214
  const clone = async (assetId, opts = {}) => {
199
215
  try {
@@ -5,7 +5,7 @@ export * from "./types";
5
5
  export { DEFAULT_SEARCH_PAGE_SIZE, searchCacheShape, type SearchArgs, type SearchCondition, type SearchFilter, type SearchOperator, type SearchPage, } from "./search";
6
6
  export { createFlowsConnector, findTaskIn, flattenLayoutFields, flows, type FindTaskArgs, type FindTaskResult, type FlowsConnector, type ListFlowsArgs, } from "./flows";
7
7
  export { createWorkConnector, work, type FlowRef, type IterateWorkRowsArgs, type ListRelatedWorkArgs, type ListWorkRowsArgs, type SearchWorkArgs, type StartWorkArgs, type SubmitWorkArgs, type WorkConnector, type WorkDataPatch, type WorkPatchOperation, type WorkRowPage, type WorkSearchPage, } from "./work";
8
- export { ASSET_TARGET_DATA_TYPES, assets, createAssetsConnector, type AssetRowPage, type AssetSearchPage, type AssetsConnector, type AssetTypeRef, type CreateAssetArgs, type IterateAssetRowsArgs, type ListAssetRowsArgs, type ListRelatedAssetsArgs, type QuickSearchAssetsArgs, type SearchAssetsArgs, type StartEditAssetArgs, } from "./assets";
8
+ export { ASSET_TARGET_DATA_TYPES, assets, createAssetsConnector, type AssetDraft, type AssetRowPage, type AssetSearchPage, type AssetsConnector, type AssetTypeRef, type CreateAssetArgs, type IterateAssetRowsArgs, type ListAssetRowsArgs, type ListRelatedAssetsArgs, type QuickSearchAssetsArgs, type SearchAssetsArgs, type StartEditAssetArgs, } from "./assets";
9
9
  export { agentEndReason, agentErrorText, agentMessageText, agents, collectAgentReply, createAgentsConnector, streamAgentReply, type AgentChatSession, type AgentReplyState, type AgentsConnector, type CreateAgentChatArgs, type GetChatMessagesArgs, type ListAgentsArgs, type ListChatsArgs, type RunAgentArgs, type SendChatArgs, } from "./agents";
10
10
  export { attachments, createAttachmentsConnector, type AttachmentsConnector, type GetAttachmentBlobArgs, type UploadAttachmentArgs, } from "./attachments";
11
11
  export { createIntegrationsConnector, integrations, type IntegrationsConnector, type InvokeIntegrationEndpointArgs, } from "./integrations";
@@ -1,3 +1,4 @@
1
+ import type { WorkComponentLock } from "../shellBridge";
1
2
  export type FlowStatus = "Active" | "Archived" | "Deleted";
2
3
  export interface FlowSummary {
3
4
  id: string;
@@ -34,10 +35,15 @@ export declare function mapFlowSummary(value: unknown): FlowSummary;
34
35
  export declare function mapFlowAction(value: unknown): FlowAction;
35
36
  export declare function mapFlowStep(value: unknown): FlowStep;
36
37
  export declare function mapFlow(value: unknown, steps?: unknown[]): Flow;
38
+ export interface FlowConfigActionSet {
39
+ id: string;
40
+ name: string;
41
+ }
37
42
  export interface FlowConfigTask {
38
43
  id: string;
39
44
  name: string;
40
45
  layoutId?: string;
46
+ actionSets?: FlowConfigActionSet[];
41
47
  }
42
48
  export interface FlowConfigStep {
43
49
  id: string;
@@ -85,6 +91,7 @@ export interface WorkAction {
85
91
  displayName?: string;
86
92
  eventName?: string;
87
93
  canExecute?: boolean;
94
+ actionSetId?: string;
88
95
  }
89
96
  export interface WorkAttachment {
90
97
  id: string;
@@ -105,6 +112,7 @@ export interface WorkDetail {
105
112
  flowOriginId?: string;
106
113
  status?: string;
107
114
  state?: string;
115
+ activeLocks: WorkComponentLock[];
108
116
  attachments: WorkAttachment[];
109
117
  actions: WorkAction[];
110
118
  }
@@ -97,8 +97,8 @@ function mapFlow(value, steps) {
97
97
  };
98
98
  }
99
99
  // GET /api/v4/config/flow/{id} returns flat {steps: [{stepId, stepName?,
100
- // stepDisplayName?, taskId, taskName?, taskDisplayName?, layoutId}]} rows;
101
- // group them by step preserving server order.
100
+ // stepDisplayName?, taskId, taskName?, taskDisplayName?, actionSetId?,
101
+ // actionSetName?, layoutId}]} rows; group them by step preserving server order.
102
102
  function mapFlowConfig(flowId, value) {
103
103
  const raw = asRecord(value);
104
104
  const byStep = new Map();
@@ -121,11 +121,27 @@ function mapFlowConfig(flowId, value) {
121
121
  nameMap.set(stepId, step.name);
122
122
  }
123
123
  const taskId = str(row?.taskId);
124
- if (taskId && !step.tasks.some((t) => t.id === taskId)) {
124
+ if (!taskId)
125
+ continue;
126
+ let actionSets = step.tasks.find((t) => t.id === taskId)?.actionSets;
127
+ if (!actionSets) {
125
128
  const name = str(row?.taskDisplayName) ?? str(row?.taskName) ?? taskId;
126
- step.tasks.push({ id: taskId, name, layoutId: str(row?.layoutId) });
129
+ actionSets = [];
130
+ step.tasks.push({
131
+ id: taskId,
132
+ name,
133
+ layoutId: str(row?.layoutId),
134
+ actionSets,
135
+ });
127
136
  nameMap.set(taskId, name);
128
137
  }
138
+ const actionSetId = str(row?.actionSetId);
139
+ const actionSetName = str(row?.actionSetName);
140
+ if (actionSetId &&
141
+ actionSetName &&
142
+ !actionSets.some((a) => a.id === actionSetId)) {
143
+ actionSets.push({ id: actionSetId, name: actionSetName });
144
+ }
129
145
  }
130
146
  return { flowId, steps: order.map((id) => byStep.get(id)), nameMap };
131
147
  }
@@ -164,6 +180,9 @@ function mapWorkDetail(value) {
164
180
  const attachments = Array.isArray(raw.attachments)
165
181
  ? raw.attachments
166
182
  : [];
183
+ const locks = Array.isArray(raw.activeLocks)
184
+ ? raw.activeLocks
185
+ : [];
167
186
  return {
168
187
  id,
169
188
  code: str(raw?.code),
@@ -173,6 +192,18 @@ function mapWorkDetail(value) {
173
192
  flowOriginId: str(raw?.flowOriginId),
174
193
  status: str(raw?.status),
175
194
  state: str(raw?.state),
195
+ activeLocks: locks.flatMap((l) => str(l?.userId) && typeof l?.componentId === "string"
196
+ ? [
197
+ {
198
+ workId: str(l?.workItemId) ?? id,
199
+ userId: String(l.userId),
200
+ displayName: str(l?.displayName),
201
+ componentId: l.componentId,
202
+ dataPath: str(l?.dataPath),
203
+ at: str(l?.utcTime),
204
+ },
205
+ ]
206
+ : []),
176
207
  attachments: attachments.map((a) => ({
177
208
  id: String(a?.id ?? ""),
178
209
  // The record's `fileName` is the storage name; the original is the one deletions queue.
@@ -188,6 +219,7 @@ function mapWorkDetail(value) {
188
219
  displayName: str(a?.displayName),
189
220
  eventName: str(a?.eventName),
190
221
  canExecute: typeof a?.canExecute === "boolean" ? a.canExecute : undefined,
222
+ actionSetId: str(a?.stepId),
191
223
  })),
192
224
  };
193
225
  }
@@ -98,5 +98,6 @@ export interface WorkConnector {
98
98
  }
99
99
  export declare const resolveFlowRef: (flow: FlowRef | null | undefined) => string;
100
100
  export declare function buildAdditionalProperties(properties?: Record<string, string>): unknown[];
101
+ export declare function readWorkBack(deps: ConnectorDeps, workId: string, written: WorkDetail, signal?: AbortSignal): Promise<WorkDetail>;
101
102
  export declare function createWorkConnector(deps?: ConnectorDeps): WorkConnector;
102
103
  export declare const work: WorkConnector;