Skip to content
Source
Sign inSign up
TanStack/ai
Open History to see the last commit

run-ownership.ts

52 lines1.6 KB

1import type { GenerationDevtoolsBridge } from './devtools'
2import type { GenerationClientState } from './generation-types'
3​
4/** True while `controller` is the client's current, unaborted run. */
5export function ownsRun(
6 current: AbortController | null,
7 controller: AbortController,
8): boolean {
9 return !controller.signal.aborted && current === controller
11​
12/** True without a controller: that caller does not own a run. */
13export function owns(
14 current: AbortController | null,
15 controller: AbortController | undefined,
16): boolean {
17 return !controller || ownsRun(current, controller)
19​
20/**
21 * Run `steps` in order while `controller` owns the client. A step can run
22 * user code, and that code can call `stop()` or start a new run. Returns
23 * whether `controller` still owns the client.
24 */
25export function whileOwned(
26 getCurrent: () => AbortController | null,
27 controller: AbortController | undefined,
28 ...steps: Array<() => unknown>
29): boolean {
30 for (const step of steps) {
31 if (!owns(getCurrent(), controller)) return false
32 step()
33 }
34 return owns(getCurrent(), controller)
36​
37/** Close a stopped run in devtools with the status it had when stopped. */
38export function finishStoppedRun(
39 bridge: Pick<GenerationDevtoolsBridge<unknown>, 'finishRun'>,
40 runId: string | null,
41 status: GenerationClientState,
42 error: Error | undefined,
43): void {
44 if (!runId) return
45 if (status === 'success') {
46 bridge.finishRun(runId, 'run:completed', 'completed')
47 } else if (status === 'error') {
48 bridge.finishRun(runId, 'run:errored', 'errored', error?.message)
49 } else {
50 bridge.finishRun(runId, 'run:cancelled', 'cancelled')
51 }