@alexkroman1/aai-ui 7.0.0 → 8.0.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/dist/{_colors-CcAi2FOU.js → _colors-j8XMToi9.js} +13 -2
- package/dist/_upload-pause.d.ts +31 -0
- package/dist/{chat-view-BKsFfFZJ.js → chat-view-BJ6sOARu.js} +2 -2
- package/dist/{client-config-B4nznRvH.js → client-config-BT_kWID5.js} +1 -1
- package/dist/components/button.js +1 -1
- package/dist/components/chat-view.js +1 -1
- package/dist/components/controls.js +1 -1
- package/dist/components/message-list.js +1 -1
- package/dist/components/start-screen.js +1 -1
- package/dist/components/tool-call-block.js +1 -1
- package/dist/default-client/assets/index-Du8SVFin.js +299 -0
- package/dist/default-client/index.html +1 -1
- package/dist/define-client.js +3 -3
- package/dist/index.d.ts +3 -3
- package/dist/index.js +141 -746
- package/dist/internal.d.ts +3 -0
- package/dist/internal.js +5 -3
- package/dist/{message-list-DHddO4QC.js → message-list-Dtl03sGr.js} +4 -68
- package/dist/{session-core-C2JtLArh.js → session-core-CMEpwRP1.js} +4 -4
- package/dist/session-core-audio-setup.d.ts +2 -2
- package/dist/session-core-messages.d.ts +1 -1
- package/dist/session-core.js +1 -1
- package/dist/{tool-call-block-DoF-cSIZ.js → tool-call-block-B7KlhaWl.js} +1 -1
- package/dist/{url-chips-DpM7Oocj.js → url-chips-DxXKgyL9.js} +1 -1
- package/dist/use-user-transcript-C14qWFu2.js +72 -0
- package/dist/use-user-transcript.d.ts +7 -2
- package/dist/use-workflow-progress-C4KgVldr.js +610 -0
- package/package.json +2 -2
- package/dist/default-client/assets/index-fEkrcZgo.js +0 -293
|
@@ -0,0 +1,610 @@
|
|
|
1
|
+
import { t as pageBaseUrl } from "./_utils-B6498_bm.js";
|
|
2
|
+
import { useCallback, useEffect, useRef, useState } from "react";
|
|
3
|
+
import { errorMessage } from "@alexkroman1/aai";
|
|
4
|
+
import { omitUndefined } from "@alexkroman1/aai/utils";
|
|
5
|
+
import { createWorkflowApiClient, isTerminal, isTerminal as isTerminal$1, readEventStream } from "@alexkroman1/aai/workflow-api";
|
|
6
|
+
//#region workflow-client.ts
|
|
7
|
+
/**
|
|
8
|
+
* Browser client for the workflow HTTP API (`aai/host/workflow-api.ts`).
|
|
9
|
+
*
|
|
10
|
+
* This is the whole client half of a WORKFLOW APP: an agent whose front door is
|
|
11
|
+
* a form rather than a microphone (`workflowApp()`) starts runs
|
|
12
|
+
* here and watches them for the answer. It deliberately does NOT go through
|
|
13
|
+
* `SessionCore` — there is no socket, no audio graph, and no session to resume.
|
|
14
|
+
*
|
|
15
|
+
* **The requests themselves are the SDK's now**
|
|
16
|
+
* (`createWorkflowApiClient`, `@alexkroman1/aai/workflow-api`), and what is left
|
|
17
|
+
* here is the one thing that is genuinely a BROWSER's: the default base URL.
|
|
18
|
+
* Every route, every query, the 404-is-an-answer rule and the `wait` clamp were
|
|
19
|
+
* written three times over — here, in the studio's Workflows card, and in
|
|
20
|
+
* `aai workflow` — and the parts the copies disagreed on were exactly the ones a
|
|
21
|
+
* reader cannot check by eye. The SDK module's doc carries that argument; this
|
|
22
|
+
* file must not grow a second implementation of any of it.
|
|
23
|
+
*
|
|
24
|
+
* The one thing worth knowing before using it: **a run outlives the page.**
|
|
25
|
+
* Starting one resolves as soon as the run is created, so `runId` is the only
|
|
26
|
+
* handle that matters and it stays valid across a reload, a different device, or
|
|
27
|
+
* `curl` — which is what makes `useWorkflowRun` a watch rather than a
|
|
28
|
+
* subscription to something the page owns.
|
|
29
|
+
*
|
|
30
|
+
* The loop that keeps asking lives in `use-workflow-run.ts`, and the streaming
|
|
31
|
+
* fast path under it in `workflow-events.ts`.
|
|
32
|
+
*/
|
|
33
|
+
/**
|
|
34
|
+
* Create a workflow API client aimed at the agent serving this page.
|
|
35
|
+
*
|
|
36
|
+
* Hoist it out of the component that uses it. `useWorkflowRun` holds the client
|
|
37
|
+
* in a ref precisely so a fresh object per render does not restart its watch,
|
|
38
|
+
* but a client built in render is still a new `fetch` closure every time and
|
|
39
|
+
* reads as though it were free.
|
|
40
|
+
*
|
|
41
|
+
* @example
|
|
42
|
+
* ```tsx
|
|
43
|
+
* import { createWorkflowApi, useWorkflowRun } from "@alexkroman1/aai-ui";
|
|
44
|
+
* import { useState } from "react";
|
|
45
|
+
*
|
|
46
|
+
* // Module scope, not render scope — see above.
|
|
47
|
+
* const api = createWorkflowApi();
|
|
48
|
+
*
|
|
49
|
+
* function StartDigest() {
|
|
50
|
+
* const [runId, setRunId] = useState<string>();
|
|
51
|
+
* const { run } = useWorkflowRun(runId, { api });
|
|
52
|
+
* return (
|
|
53
|
+
* <button
|
|
54
|
+
* type="button"
|
|
55
|
+
* onClick={() => void api.start("digest", { url: "…" }).then(setRunId)}
|
|
56
|
+
* >
|
|
57
|
+
* {run ? run.status : "Start"}
|
|
58
|
+
* </button>
|
|
59
|
+
* );
|
|
60
|
+
* }
|
|
61
|
+
* ```
|
|
62
|
+
*
|
|
63
|
+
* @param opts - See {@link WorkflowApiOptions}. Both fields are optional; the
|
|
64
|
+
* default base URL is the page's own origin and path.
|
|
65
|
+
* @returns The call set — see {@link WorkflowApi}.
|
|
66
|
+
*
|
|
67
|
+
* @public
|
|
68
|
+
*/
|
|
69
|
+
function createWorkflowApi(opts = {}) {
|
|
70
|
+
return createWorkflowApiClient({
|
|
71
|
+
baseUrl: opts.baseUrl ?? pageBaseUrl(),
|
|
72
|
+
...omitUndefined({ token: opts.token })
|
|
73
|
+
});
|
|
74
|
+
}
|
|
75
|
+
//#endregion
|
|
76
|
+
//#region _workflow-api-ref.ts
|
|
77
|
+
/**
|
|
78
|
+
* The client preamble every workflow hook needs, once.
|
|
79
|
+
*
|
|
80
|
+
* Five hooks (`useWorkflowRun`, `useWorkflowProgress`, `useWorkflowRuns`,
|
|
81
|
+
* `useWorkflows`, `useWorkflowSubmit`) opened with the same two refs and the
|
|
82
|
+
* same two paragraphs explaining them, and both halves are load-bearing rather
|
|
83
|
+
* than stylistic — which is exactly why they should not be re-derived per hook:
|
|
84
|
+
*
|
|
85
|
+
* - **The caller's client lives in a REF, never in an effect's dependency
|
|
86
|
+
* array.** The natural call site is
|
|
87
|
+
* `useWorkflowRun(id, { api: createWorkflowApi() })`, which passes a NEW
|
|
88
|
+
* object every render; as a dependency that tears the effect down and
|
|
89
|
+
* restarts it on each one, and because a restart clears state and re-renders,
|
|
90
|
+
* it schedules the next. The result is an unbounded request loop against the
|
|
91
|
+
* agent — on the platform, against the BROKER — with `error` wiped before
|
|
92
|
+
* anything can read it, presenting as "the page polls forever" rather than as
|
|
93
|
+
* a mistake at the call site.
|
|
94
|
+
* - **The no-client default is built lazily and ONCE.** As a render-time
|
|
95
|
+
* default (`api ?? createWorkflowApi()`) it is a fresh object per render,
|
|
96
|
+
* which is the same hazard one layer down; built inside an effect it is a
|
|
97
|
+
* fresh object per watch.
|
|
98
|
+
*
|
|
99
|
+
* The returned getter is stable for the life of the component and reads the ref
|
|
100
|
+
* on every call, so a caller that SWAPS clients mid-watch — a token arriving
|
|
101
|
+
* after login — is picked up by the next request without the watch restarting.
|
|
102
|
+
*/
|
|
103
|
+
/**
|
|
104
|
+
* Resolve the client a workflow hook should use, now.
|
|
105
|
+
*
|
|
106
|
+
* @param api - The caller's client, or undefined for one aimed at the page's
|
|
107
|
+
* own agent.
|
|
108
|
+
* @returns A stable getter. Call it per request, never once per watch.
|
|
109
|
+
*
|
|
110
|
+
* @internal
|
|
111
|
+
*/
|
|
112
|
+
function useWorkflowApiRef(api) {
|
|
113
|
+
const apiRef = useRef(api);
|
|
114
|
+
apiRef.current = api;
|
|
115
|
+
const fallbackRef = useRef(void 0);
|
|
116
|
+
return useCallback(() => {
|
|
117
|
+
const current = apiRef.current;
|
|
118
|
+
if (current) return current;
|
|
119
|
+
fallbackRef.current ??= createWorkflowApi();
|
|
120
|
+
return fallbackRef.current;
|
|
121
|
+
}, []);
|
|
122
|
+
}
|
|
123
|
+
//#endregion
|
|
124
|
+
//#region _repeat-until.ts
|
|
125
|
+
/**
|
|
126
|
+
* A bounded read, re-armed from the SETTLED read — the loop both workflow
|
|
127
|
+
* watchers are built out of.
|
|
128
|
+
*
|
|
129
|
+
* `pollUntilTerminal` (`use-workflow-run.ts`) and `readProgressUntilComplete`
|
|
130
|
+
* (`use-workflow-progress.ts`) each open a request, decide from its answer
|
|
131
|
+
* whether to come back, and stop when told to. What they had in common was not
|
|
132
|
+
* the decision — one reads a snapshot, the other drains an SSE body — but the
|
|
133
|
+
* scaffold around it, and that scaffold is where the two rules live:
|
|
134
|
+
*
|
|
135
|
+
* - **Re-armed from the settled read, never on an interval.** A slow response
|
|
136
|
+
* would otherwise stack overlapping requests on an agent that is already
|
|
137
|
+
* struggling, and on the platform every one of them BROKERS.
|
|
138
|
+
* - **Cancellation is a signal, not a flag.** The teardown has to reach the
|
|
139
|
+
* in-flight request too — an abandoned progress read otherwise keeps pulling
|
|
140
|
+
* chunks out of a run for a page that has navigated away — so `step` is
|
|
141
|
+
* handed the signal rather than being trusted to check a boolean.
|
|
142
|
+
*/
|
|
143
|
+
/**
|
|
144
|
+
* Call `step` until it reports it is finished, or until the returned stop
|
|
145
|
+
* function is called.
|
|
146
|
+
*
|
|
147
|
+
* `step` resolves `true` when there is nothing left to come back for. It is
|
|
148
|
+
* responsible for its own failures: a rejection would leave the loop stopped
|
|
149
|
+
* with nobody told, so each caller decides whether its failure is terminal or
|
|
150
|
+
* just another reason to try again.
|
|
151
|
+
*
|
|
152
|
+
* @internal
|
|
153
|
+
*/
|
|
154
|
+
function repeatUntil(intervalMs, step) {
|
|
155
|
+
const controller = new AbortController();
|
|
156
|
+
let timer;
|
|
157
|
+
const tick = async () => {
|
|
158
|
+
if (await step(controller.signal) || controller.signal.aborted) return;
|
|
159
|
+
timer = setTimeout(() => void tick(), intervalMs);
|
|
160
|
+
};
|
|
161
|
+
tick();
|
|
162
|
+
return () => {
|
|
163
|
+
controller.abort();
|
|
164
|
+
if (timer !== void 0) clearTimeout(timer);
|
|
165
|
+
};
|
|
166
|
+
}
|
|
167
|
+
//#endregion
|
|
168
|
+
//#region workflow-events.ts
|
|
169
|
+
/**
|
|
170
|
+
* Watching a run over server-sent events — the PUSH half of `useWorkflowRun`.
|
|
171
|
+
*
|
|
172
|
+
* Its own module because the seam is clean: everything in `workflow-client.ts`
|
|
173
|
+
* is request/response shaping plus the poll, and this is one long-lived stream
|
|
174
|
+
* and the SSE parser it needs.
|
|
175
|
+
*
|
|
176
|
+
* @internal
|
|
177
|
+
*/
|
|
178
|
+
/**
|
|
179
|
+
* Watch a run over SSE, falling back to the caller's poll on any failure.
|
|
180
|
+
*
|
|
181
|
+
* The poll stays the fallback rather than being replaced, and that is the whole
|
|
182
|
+
* shape of this: a stream is an optimisation over a mechanism that already
|
|
183
|
+
* works, so every way it can fail — an older agent with no `/events` route, a
|
|
184
|
+
* proxy that buffers, a network that drops it — has to degrade to the thing that
|
|
185
|
+
* does. What it buys is real, though: on the platform every polled read BROKERS,
|
|
186
|
+
* so N open tabs at `DEFAULT_WORKFLOW_POLL_MS` is N/2 brokered requests a
|
|
187
|
+
* second, each able to boot a sandbox. One stream per tab replaces all of it.
|
|
188
|
+
*
|
|
189
|
+
* `EventSource` is not used, for two reasons that both matter here: it cannot
|
|
190
|
+
* send an `Authorization` header (an agent with `AAI_WORKFLOW_API_TOKEN` set
|
|
191
|
+
* would be unreachable), and it reconnects on its own schedule, which would
|
|
192
|
+
* fight the caller's. A `fetch` stream gives both back.
|
|
193
|
+
*
|
|
194
|
+
* Returns a stop function. `onFallback` is called at most once, when this stream
|
|
195
|
+
* cannot be relied on and the poll should take over.
|
|
196
|
+
*/
|
|
197
|
+
function watchRunEvents(getClient, runId, onRun, onSettled, onFallback) {
|
|
198
|
+
const controller = new AbortController();
|
|
199
|
+
let handedOver = false;
|
|
200
|
+
const handOver = () => {
|
|
201
|
+
if (handedOver || controller.signal.aborted) return;
|
|
202
|
+
handedOver = true;
|
|
203
|
+
onFallback();
|
|
204
|
+
};
|
|
205
|
+
/**
|
|
206
|
+
* Consume the stream. Resolves `"settled"` when the run reached a state
|
|
207
|
+
* nothing will change, and `"fallback"` for every other ending — including a
|
|
208
|
+
* clean end with no final frame, which is a dropped connection.
|
|
209
|
+
*
|
|
210
|
+
* A named function rather than an inline IIFE so `watchRunEvents` stays under
|
|
211
|
+
* the cognitive-complexity cap, and so the two outcomes are a return value
|
|
212
|
+
* instead of two callbacks invoked from six places.
|
|
213
|
+
*/
|
|
214
|
+
const pump = async () => {
|
|
215
|
+
const res = await getClient().watch(runId, controller.signal);
|
|
216
|
+
if (!(res.ok && res.body)) return "fallback";
|
|
217
|
+
for await (const frame of readEventStream(res.body, controller.signal)) {
|
|
218
|
+
if (frame.event === "run" && frame.data) onRun(frame.data);
|
|
219
|
+
const outcome = endingFor(frame.event);
|
|
220
|
+
if (outcome) return outcome;
|
|
221
|
+
}
|
|
222
|
+
return "fallback";
|
|
223
|
+
};
|
|
224
|
+
pump().then((outcome) => outcome === "settled" ? onSettled() : handOver(), () => handOver());
|
|
225
|
+
return () => controller.abort();
|
|
226
|
+
}
|
|
227
|
+
/**
|
|
228
|
+
* Does this frame END the stream, and does the run need watching afterwards?
|
|
229
|
+
*
|
|
230
|
+
* `done` and `missing` are both final and neither wants a reconnect: the run is
|
|
231
|
+
* terminal, or the id will never exist (a 404 is a stable answer — the world's
|
|
232
|
+
* record is durable). `idle` is the stream handing ITSELF back after its
|
|
233
|
+
* duration cap, so that one falls back to the poll. Anything else is not an
|
|
234
|
+
* ending.
|
|
235
|
+
*/
|
|
236
|
+
function endingFor(event) {
|
|
237
|
+
if (event === "done" || event === "missing") return "settled";
|
|
238
|
+
return event === "idle" ? "fallback" : void 0;
|
|
239
|
+
}
|
|
240
|
+
//#endregion
|
|
241
|
+
//#region use-workflow-run.ts
|
|
242
|
+
/**
|
|
243
|
+
* `useWorkflowRun` — watch one run until it settles.
|
|
244
|
+
*
|
|
245
|
+
* Split from `workflow-client.ts` on the seam that module's doc already draws:
|
|
246
|
+
* everything there is a REQUEST (one call, one answer, no React), and everything
|
|
247
|
+
* here is the loop that keeps asking. They are read for different reasons — the
|
|
248
|
+
* client is what a script or a `curl` equivalent needs, this is what a page needs
|
|
249
|
+
* — and only this half imports React.
|
|
250
|
+
*
|
|
251
|
+
* `workflow-events.ts` sits under it as the streaming fast path, and
|
|
252
|
+
* `use-workflow-form.ts` above it as the form-shaped caller.
|
|
253
|
+
*/
|
|
254
|
+
/** How often {@link useWorkflowRun} re-reads a live run when it has to poll. */
|
|
255
|
+
const DEFAULT_WORKFLOW_POLL_MS = 2e3;
|
|
256
|
+
/**
|
|
257
|
+
* Consecutive "no such run" reads {@link useWorkflowRun} tolerates before giving
|
|
258
|
+
* up on the id.
|
|
259
|
+
*
|
|
260
|
+
* Small on purpose: a 404 is a stable answer, so the budget exists only to
|
|
261
|
+
* absorb a first read that races the run's creation — not to keep hoping.
|
|
262
|
+
* Unbounded, a stale id polls (and, on the platform, BROKERS) for as long as the
|
|
263
|
+
* tab is open.
|
|
264
|
+
*/
|
|
265
|
+
const MAX_MISSING_READS = 3;
|
|
266
|
+
/**
|
|
267
|
+
* Poll `runId` until it is terminal, reporting each read. Returns a stop
|
|
268
|
+
* function.
|
|
269
|
+
*
|
|
270
|
+
* Module-level rather than inline in the hook below, so neither function carries
|
|
271
|
+
* the whole loop's branching — and so the loop can be read without React in the
|
|
272
|
+
* way.
|
|
273
|
+
*/
|
|
274
|
+
function pollUntilTerminal(getClient, runId, intervalMs, onRun, onError, onStopped) {
|
|
275
|
+
let missing = 0;
|
|
276
|
+
/**
|
|
277
|
+
* A read that came back empty. Resolves whether the loop should STOP.
|
|
278
|
+
*
|
|
279
|
+
* A 404 is a STABLE answer — a run the agent does not know about now will not
|
|
280
|
+
* appear later — and retrying it unbounded is how a stale id (one restored
|
|
281
|
+
* from `localStorage`, or one whose agent was redeployed onto a fresh
|
|
282
|
+
* database) polls forever: the page stays `polling` and therefore busy, and on
|
|
283
|
+
* the platform every read BROKERS, so a tab's worth of dead ids keeps
|
|
284
|
+
* sandboxes resident. A small budget is kept anyway, because the first read
|
|
285
|
+
* can race a replica that has not yet seen the run.
|
|
286
|
+
*/
|
|
287
|
+
const onMissing = (signal) => {
|
|
288
|
+
missing += 1;
|
|
289
|
+
if (missing < 3) return false;
|
|
290
|
+
if (!signal.aborted) onError(`No workflow run ${runId}`);
|
|
291
|
+
return true;
|
|
292
|
+
};
|
|
293
|
+
const read = async (signal) => {
|
|
294
|
+
try {
|
|
295
|
+
const next = await getClient().get(runId);
|
|
296
|
+
if (signal.aborted) return true;
|
|
297
|
+
if (!next) return onMissing(signal);
|
|
298
|
+
missing = 0;
|
|
299
|
+
onRun(next);
|
|
300
|
+
return isTerminal(next);
|
|
301
|
+
} catch (err) {
|
|
302
|
+
if (!signal.aborted) onError(errorMessage(err));
|
|
303
|
+
return false;
|
|
304
|
+
}
|
|
305
|
+
};
|
|
306
|
+
return repeatUntil(intervalMs, async (signal) => {
|
|
307
|
+
if (!await read(signal)) return false;
|
|
308
|
+
if (!signal.aborted) onStopped();
|
|
309
|
+
return true;
|
|
310
|
+
});
|
|
311
|
+
}
|
|
312
|
+
/**
|
|
313
|
+
* Watch one run until it reaches a terminal status.
|
|
314
|
+
*
|
|
315
|
+
* A watch rather than a subscription because a run is durable and the page is
|
|
316
|
+
* not: it can complete while the tab is closed, on a different sandbox, hours
|
|
317
|
+
* later. There is no session to reconnect — the id is the whole state.
|
|
318
|
+
*
|
|
319
|
+
* The stream (`GET /runs/:id/events`) is tried first and the poll is its
|
|
320
|
+
* fallback, so an agent deployed before that route existed still works. Watching
|
|
321
|
+
* STOPS on a terminal status, so a finished run costs nothing; passing
|
|
322
|
+
* `undefined` (nothing started yet) also costs nothing.
|
|
323
|
+
*
|
|
324
|
+
* @example
|
|
325
|
+
* ```tsx
|
|
326
|
+
* import type { ToolInputSchema, WorkflowDef } from "@alexkroman1/aai";
|
|
327
|
+
* import type { WorkflowOutputOf } from "@alexkroman1/aai/workflow-api";
|
|
328
|
+
* import { useWorkflowRun } from "@alexkroman1/aai-ui";
|
|
329
|
+
*
|
|
330
|
+
* // A real page writes `import type { digest } from "./agent.ts"`. Stood in
|
|
331
|
+
* // for here so the example compiles on its own.
|
|
332
|
+
* declare const digest: WorkflowDef<ToolInputSchema, Promise<{ points: string[] }>>;
|
|
333
|
+
*
|
|
334
|
+
* type Digest = WorkflowOutputOf<typeof digest>;
|
|
335
|
+
*
|
|
336
|
+
* function RunPanel({ runId }: { runId: string | undefined }) {
|
|
337
|
+
* // The type argument is what makes `run.output` a `Digest` below.
|
|
338
|
+
* const { run, error, polling } = useWorkflowRun<Digest>(runId);
|
|
339
|
+
* if (error !== undefined) return <p role="alert">{error}</p>;
|
|
340
|
+
* if (run?.status === "completed") {
|
|
341
|
+
* return (
|
|
342
|
+
* <ul>
|
|
343
|
+
* {run.output.points.map((point) => (
|
|
344
|
+
* <li key={point}>{point}</li>
|
|
345
|
+
* ))}
|
|
346
|
+
* </ul>
|
|
347
|
+
* );
|
|
348
|
+
* }
|
|
349
|
+
* return <p>{polling ? "Working…" : "Nothing running."}</p>;
|
|
350
|
+
* }
|
|
351
|
+
* ```
|
|
352
|
+
*
|
|
353
|
+
* @typeParam R - The workflow's output type. Supplying it is what makes
|
|
354
|
+
* `run.status === "completed"` narrow to a typed `run.output` instead of
|
|
355
|
+
* `unknown`. Derive it with `WorkflowOutputOf<typeof myWorkflow>` — a
|
|
356
|
+
* type-only import of `agent.ts` is erased, so it costs the bundle nothing.
|
|
357
|
+
* @param runId - The run to watch. `undefined` costs nothing, so a page may
|
|
358
|
+
* pass its state straight through before a run exists.
|
|
359
|
+
* @param opts - `api` when the page holds its own client; `intervalMs` to
|
|
360
|
+
* change the poll interval the stream falls back to.
|
|
361
|
+
* @returns The latest snapshot, the last read's error, and whether the watch
|
|
362
|
+
* is still going — see {@link UseWorkflowRunResult}.
|
|
363
|
+
*
|
|
364
|
+
* @public
|
|
365
|
+
*/
|
|
366
|
+
function useWorkflowRun(runId, opts = {}) {
|
|
367
|
+
const { api, intervalMs = DEFAULT_WORKFLOW_POLL_MS } = opts;
|
|
368
|
+
const [run, setRun] = useState(void 0);
|
|
369
|
+
const [error, setError] = useState(void 0);
|
|
370
|
+
/**
|
|
371
|
+
* Has the watch stopped for a reason the snapshot does not show?
|
|
372
|
+
*
|
|
373
|
+
* Only one such reason exists — an id the agent kept reporting as unknown,
|
|
374
|
+
* past {@link MAX_MISSING_READS} — and it leaves `run` undefined, so `polling`
|
|
375
|
+
* derived from `isTerminal(run)` alone would stay true forever.
|
|
376
|
+
*/
|
|
377
|
+
const [stopped, setStopped] = useState(false);
|
|
378
|
+
const getClient = useWorkflowApiRef(api);
|
|
379
|
+
useEffect(() => {
|
|
380
|
+
setRun(void 0);
|
|
381
|
+
setError(void 0);
|
|
382
|
+
setStopped(false);
|
|
383
|
+
if (!runId) return;
|
|
384
|
+
const onRun = (next) => {
|
|
385
|
+
setRun(next);
|
|
386
|
+
setError(void 0);
|
|
387
|
+
};
|
|
388
|
+
let stopPoll;
|
|
389
|
+
const stopStream = watchRunEvents(getClient, runId, onRun, () => setStopped(true), () => {
|
|
390
|
+
stopPoll = pollUntilTerminal(getClient, runId, intervalMs, onRun, setError, () => setStopped(true));
|
|
391
|
+
});
|
|
392
|
+
return () => {
|
|
393
|
+
stopStream();
|
|
394
|
+
stopPoll?.();
|
|
395
|
+
};
|
|
396
|
+
}, [
|
|
397
|
+
runId,
|
|
398
|
+
intervalMs,
|
|
399
|
+
getClient
|
|
400
|
+
]);
|
|
401
|
+
return {
|
|
402
|
+
run,
|
|
403
|
+
error,
|
|
404
|
+
polling: runId !== void 0 && !stopped && !isTerminal(run)
|
|
405
|
+
};
|
|
406
|
+
}
|
|
407
|
+
//#endregion
|
|
408
|
+
//#region use-workflow-progress.ts
|
|
409
|
+
/**
|
|
410
|
+
* `useWorkflowProgress` — read what a run has WRITTEN while it runs.
|
|
411
|
+
*
|
|
412
|
+
* The sibling of `useWorkflowRun`, and the split between them is the whole
|
|
413
|
+
* reason this exists. That hook reports a run's STATE: the status transitions
|
|
414
|
+
* the world records, which every run has. This reports what the run itself
|
|
415
|
+
* wrote through `getWritable()`, which is the only thing a long run can say
|
|
416
|
+
* before it finishes — a snapshot carries a status and, once terminal, an
|
|
417
|
+
* output, and nothing in between. A page that shows only status shows
|
|
418
|
+
* "Working…" for ten minutes and then a result.
|
|
419
|
+
*
|
|
420
|
+
* ## There is no poll fallback, and that is not an omission
|
|
421
|
+
*
|
|
422
|
+
* `useWorkflowRun` degrades to polling `GET /runs/:id` because a run's STATE is
|
|
423
|
+
* readable that way. A run's written chunks are not: the stream is the only
|
|
424
|
+
* route to them, so an agent that does not serve it has no progress to give and
|
|
425
|
+
* `supported` says so once, rather than a poll pretending to look for something
|
|
426
|
+
* that is not there. A page renders its status line either way.
|
|
427
|
+
*
|
|
428
|
+
* ## Chunks are RETAINED, so this is a replay as much as a tail
|
|
429
|
+
*
|
|
430
|
+
* The run's stream keeps every chunk, so a page that mounts late — a reload, a
|
|
431
|
+
* second tab, a link opened tomorrow — reads the whole history from index 0 and
|
|
432
|
+
* arrives at the same list as one that watched throughout. That is what makes a
|
|
433
|
+
* durable run's progress durable too, and it is why the default `startIndex` is
|
|
434
|
+
* 0 rather than "from now": a tail-only default would make the same page show
|
|
435
|
+
* different things depending on when it opened.
|
|
436
|
+
*
|
|
437
|
+
* ## It RE-OPENS while the run is live, because a progress read is bounded
|
|
438
|
+
*
|
|
439
|
+
* The route answers with the chunks written when the request arrived and then
|
|
440
|
+
* ends, reporting `complete` — whether the run itself was terminal. It has to:
|
|
441
|
+
* a workflow stream signals its end only once CLOSED, and a progress channel
|
|
442
|
+
* written by one step after another is never closed, so a read that waited for
|
|
443
|
+
* the end would hang forever on a finished run. (It did: see the route's own
|
|
444
|
+
* doc.)
|
|
445
|
+
*
|
|
446
|
+
* So this hook re-opens from where it left off until a read comes back
|
|
447
|
+
* `complete`. That is a poll, and the honest description of progress is a durable
|
|
448
|
+
* log rather than a socket — but it is a poll of a CHEAP shape: each read asks
|
|
449
|
+
* only for chunks past the last index it saw, so a quiet run costs an empty
|
|
450
|
+
* answer rather than the whole log again.
|
|
451
|
+
*/
|
|
452
|
+
/** How often a live run's progress is re-read once a bounded read has ended. */
|
|
453
|
+
const DEFAULT_PROGRESS_POLL_MS = 1e3;
|
|
454
|
+
/**
|
|
455
|
+
* Drain one bounded read's frames, reporting how it ended and everything it
|
|
456
|
+
* carried.
|
|
457
|
+
*
|
|
458
|
+
* The chunks are RETURNED rather than handed over one at a time, and that is
|
|
459
|
+
* what lets the hook commit a whole read in one React update: a per-chunk
|
|
460
|
+
* callback re-rendered the page once per progress line and rebuilt the list
|
|
461
|
+
* each time, which for a fan-out writing a line per segment is an O(n²) copy of
|
|
462
|
+
* the log a reader can already only see one frame at a time. A read is bounded
|
|
463
|
+
* by construction (see the module doc), so buffering one is bounded too.
|
|
464
|
+
*/
|
|
465
|
+
async function consumeFrames(body, signal) {
|
|
466
|
+
const chunks = [];
|
|
467
|
+
let ending = "partial";
|
|
468
|
+
for await (const frame of readEventStream(body, signal)) if (frame.event === "chunk") chunks.push(frame.data);
|
|
469
|
+
else if (frame.event === "done") ending = frame.data?.complete ? "complete" : "partial";
|
|
470
|
+
else if (frame.event === "missing") return {
|
|
471
|
+
ending: "complete",
|
|
472
|
+
chunks
|
|
473
|
+
};
|
|
474
|
+
return {
|
|
475
|
+
ending,
|
|
476
|
+
chunks
|
|
477
|
+
};
|
|
478
|
+
}
|
|
479
|
+
/**
|
|
480
|
+
* Read one run's progress until it is complete, reporting each read's chunks.
|
|
481
|
+
*
|
|
482
|
+
* Module-level rather than inline in the hook, so the loop reads without React in
|
|
483
|
+
* the way — the same split `useWorkflowRun` makes with `pollUntilTerminal`.
|
|
484
|
+
*
|
|
485
|
+
* Every re-open asks from an ABSOLUTE position past the last chunk read, so a
|
|
486
|
+
* read only ever fetches what this reader has not seen. That is what keeps the
|
|
487
|
+
* poll cheap: a quiet run answers with a bare `done` rather than the whole log
|
|
488
|
+
* again.
|
|
489
|
+
*
|
|
490
|
+
* ## A negative `startIndex` is resolved on the FIRST read, not carried
|
|
491
|
+
*
|
|
492
|
+
* "The last N lines" names no position a later read can resume from — the tail
|
|
493
|
+
* it counts back from moves with every line the run writes. Carrying it meant a
|
|
494
|
+
* re-open asking for everything from 0 and dropping `seen` chunks off the
|
|
495
|
+
* FRONT, which is a different set entirely: a reader that opened at
|
|
496
|
+
* `startIndex: -3` on a 10-line log holds lines 7-9, and its next read handed
|
|
497
|
+
* over lines 3 onwards — four lines it never asked for, then the three it
|
|
498
|
+
* already had, in that order. The dedupe the old comment claimed would need the
|
|
499
|
+
* first read's absolute tail, which the reader never learned.
|
|
500
|
+
*
|
|
501
|
+
* So the first read is issued from 0 instead, and only its last N chunks are
|
|
502
|
+
* handed over. The window the caller asked for is unchanged, and the reader now
|
|
503
|
+
* knows exactly where it is — every read after it is the ordinary absolute case.
|
|
504
|
+
* The cost is that the first read transfers the whole log, which is what the
|
|
505
|
+
* DEFAULT (`startIndex: 0`, "replay everything") already does.
|
|
506
|
+
*/
|
|
507
|
+
function readProgressUntilComplete(getClient, runId, options, intervalMs, onChunks, onEnded) {
|
|
508
|
+
const start = options.startIndex ?? 0;
|
|
509
|
+
const tail = start < 0 ? -start : void 0;
|
|
510
|
+
let next = tail === void 0 ? start : 0;
|
|
511
|
+
let firstRead = true;
|
|
512
|
+
/** One bounded read. Resolves how it ended. */
|
|
513
|
+
const readOnce = async (signal) => {
|
|
514
|
+
const res = await getClient().streamOutput(runId, {
|
|
515
|
+
...omitUndefined({
|
|
516
|
+
namespace: options.namespace,
|
|
517
|
+
startIndex: next === 0 ? void 0 : next
|
|
518
|
+
}),
|
|
519
|
+
signal
|
|
520
|
+
});
|
|
521
|
+
if (!(res.ok && res.body)) return "unsupported";
|
|
522
|
+
const { ending, chunks } = await consumeFrames(res.body, signal);
|
|
523
|
+
next += chunks.length;
|
|
524
|
+
const fresh = firstRead && tail !== void 0 ? chunks.slice(-tail) : chunks;
|
|
525
|
+
firstRead = false;
|
|
526
|
+
if (fresh.length > 0 && !signal.aborted) onChunks(fresh);
|
|
527
|
+
return ending;
|
|
528
|
+
};
|
|
529
|
+
return repeatUntil(intervalMs, async (signal) => {
|
|
530
|
+
let ending;
|
|
531
|
+
try {
|
|
532
|
+
ending = await readOnce(signal);
|
|
533
|
+
} catch {
|
|
534
|
+
ending = "partial";
|
|
535
|
+
}
|
|
536
|
+
if (signal.aborted) return true;
|
|
537
|
+
if (ending === "partial") return false;
|
|
538
|
+
onEnded(ending);
|
|
539
|
+
return true;
|
|
540
|
+
});
|
|
541
|
+
}
|
|
542
|
+
/**
|
|
543
|
+
* Follow one run's progress stream.
|
|
544
|
+
*
|
|
545
|
+
* Passing `undefined` (nothing started yet) costs nothing, and reading stops for
|
|
546
|
+
* good once a read reports the run terminal — so a finished run costs one read.
|
|
547
|
+
*
|
|
548
|
+
* @example
|
|
549
|
+
* ```tsx
|
|
550
|
+
* import { useWorkflowProgress } from "@alexkroman1/aai-ui";
|
|
551
|
+
*
|
|
552
|
+
* function Progress({ runId }: { runId?: string }) {
|
|
553
|
+
* const { progress, streaming, supported } = useWorkflowProgress(runId);
|
|
554
|
+
* if (!supported) return null;
|
|
555
|
+
* return (
|
|
556
|
+
* <pre>
|
|
557
|
+
* {progress.join("\n")}
|
|
558
|
+
* {streaming && "\n…"}
|
|
559
|
+
* </pre>
|
|
560
|
+
* );
|
|
561
|
+
* }
|
|
562
|
+
* ```
|
|
563
|
+
*
|
|
564
|
+
* @typeParam T - What the workflow writes. Defaults to `string`, which is what
|
|
565
|
+
* a progress channel usually carries; a workflow writing objects names its own
|
|
566
|
+
* shape. Nothing in the browser can verify it — the route describes no type —
|
|
567
|
+
* so this is the page's assertion about its own agent, narrowed once here
|
|
568
|
+
* rather than at every read.
|
|
569
|
+
*
|
|
570
|
+
* @public
|
|
571
|
+
*/
|
|
572
|
+
function useWorkflowProgress(runId, opts = {}) {
|
|
573
|
+
const { api, namespace, startIndex, intervalMs = DEFAULT_PROGRESS_POLL_MS } = opts;
|
|
574
|
+
const [progress, setProgress] = useState([]);
|
|
575
|
+
const [streaming, setStreaming] = useState(false);
|
|
576
|
+
const [supported, setSupported] = useState(true);
|
|
577
|
+
const getClient = useWorkflowApiRef(api);
|
|
578
|
+
useEffect(() => {
|
|
579
|
+
setProgress([]);
|
|
580
|
+
setSupported(true);
|
|
581
|
+
setStreaming(false);
|
|
582
|
+
if (!runId) return;
|
|
583
|
+
setStreaming(true);
|
|
584
|
+
const stop = readProgressUntilComplete(getClient, runId, {
|
|
585
|
+
namespace,
|
|
586
|
+
startIndex
|
|
587
|
+
}, intervalMs, (chunks) => setProgress((seen) => [...seen, ...chunks]), (ending) => {
|
|
588
|
+
setStreaming(false);
|
|
589
|
+
if (ending === "unsupported") setSupported(false);
|
|
590
|
+
});
|
|
591
|
+
return () => {
|
|
592
|
+
stop();
|
|
593
|
+
setStreaming(false);
|
|
594
|
+
};
|
|
595
|
+
}, [
|
|
596
|
+
runId,
|
|
597
|
+
namespace,
|
|
598
|
+
startIndex,
|
|
599
|
+
intervalMs,
|
|
600
|
+
getClient
|
|
601
|
+
]);
|
|
602
|
+
return {
|
|
603
|
+
progress,
|
|
604
|
+
latest: progress.at(-1),
|
|
605
|
+
streaming,
|
|
606
|
+
supported
|
|
607
|
+
};
|
|
608
|
+
}
|
|
609
|
+
//#endregion
|
|
610
|
+
export { useWorkflowRun as a, isTerminal$1 as c, MAX_MISSING_READS as i, useWorkflowProgress as n, useWorkflowApiRef as o, DEFAULT_WORKFLOW_POLL_MS as r, createWorkflowApi as s, DEFAULT_PROGRESS_POLL_MS as t };
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@alexkroman1/aai-ui",
|
|
3
|
-
"version": "
|
|
3
|
+
"version": "8.0.0",
|
|
4
4
|
"type": "module",
|
|
5
5
|
"files": [
|
|
6
6
|
"dist",
|
|
@@ -33,7 +33,7 @@
|
|
|
33
33
|
"use-stick-to-bottom": "^1.1.6",
|
|
34
34
|
"use-sync-external-store": "^1.6.0",
|
|
35
35
|
"xstate": "^5.32.5",
|
|
36
|
-
"@alexkroman1/aai": "
|
|
36
|
+
"@alexkroman1/aai": "8.0.0"
|
|
37
37
|
},
|
|
38
38
|
"peerDependencies": {
|
|
39
39
|
"react": "^19.0.0",
|