@workflow/web-shared 5.0.7 → 5.1.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/components/event-list-view.d.ts +2 -2
- package/dist/components/event-list-view.d.ts.map +1 -1
- package/dist/components/sidebar/attribute-panel.d.ts +2 -2
- package/dist/components/sidebar/attribute-panel.d.ts.map +1 -1
- package/dist/components/sidebar/attribute-panel.js +2 -2
- package/dist/components/sidebar/attributes-block.d.ts +5 -5
- package/dist/components/sidebar/attributes-block.d.ts.map +1 -1
- package/dist/components/sidebar/conversation-view.d.ts +1 -1
- package/dist/components/sidebar/conversation-view.d.ts.map +1 -1
- package/dist/components/sidebar/copyable-data-block.d.ts +2 -2
- package/dist/components/sidebar/copyable-data-block.d.ts.map +1 -1
- package/dist/components/sidebar/entity-detail-panel.d.ts.map +1 -1
- package/dist/components/sidebar/entity-detail-panel.js +4 -17
- package/dist/components/sidebar/events-list.d.ts +1 -1
- package/dist/components/sidebar/events-list.d.ts.map +1 -1
- package/dist/components/sidebar/sidebar-data-context.d.ts +1 -1
- package/dist/components/sidebar/sidebar-data-context.d.ts.map +1 -1
- package/dist/components/stream-viewer-skeleton.d.ts +1 -1
- package/dist/components/stream-viewer-skeleton.d.ts.map +1 -1
- package/dist/components/stream-viewer.d.ts +2 -1
- package/dist/components/stream-viewer.d.ts.map +1 -1
- package/dist/components/trace-viewer/components/draggable-border.d.ts +1 -1
- package/dist/components/trace-viewer/components/draggable-border.d.ts.map +1 -1
- package/dist/components/trace-viewer/components/event-list.d.ts +1 -1
- package/dist/components/trace-viewer/components/event-list.d.ts.map +1 -1
- package/dist/components/trace-viewer/components/split-pane.d.ts +1 -1
- package/dist/components/trace-viewer/components/split-pane.d.ts.map +1 -1
- package/dist/components/trace-viewer/components/trace-shortcut-helper.d.ts +1 -1
- package/dist/components/trace-viewer/components/trace-shortcut-helper.d.ts.map +1 -1
- package/dist/components/trace-viewer/components/trace-viewer-skeleton.d.ts +1 -1
- package/dist/components/trace-viewer/components/trace-viewer-skeleton.d.ts.map +1 -1
- package/dist/components/trace-viewer/context.d.ts +1 -1
- package/dist/components/trace-viewer/context.d.ts.map +1 -1
- package/dist/components/trace-viewer/icons.d.ts +4 -4
- package/dist/components/trace-viewer/icons.d.ts.map +1 -1
- package/dist/components/trace-viewer/utils.d.ts.map +1 -1
- package/dist/components/trace-viewer/utils.js +12 -3
- package/dist/components/trace-viewer.d.ts +1 -1
- package/dist/components/trace-viewer.d.ts.map +1 -1
- package/dist/components/ui/collapsible.d.ts +4 -4
- package/dist/components/ui/collapsible.d.ts.map +1 -1
- package/dist/components/ui/decrypt-button.d.ts +1 -1
- package/dist/components/ui/decrypt-button.d.ts.map +1 -1
- package/dist/components/ui/error-card.d.ts +1 -1
- package/dist/components/ui/error-card.d.ts.map +1 -1
- package/dist/components/ui/error-stack-block.d.ts +1 -1
- package/dist/components/ui/error-stack-block.d.ts.map +1 -1
- package/dist/components/ui/load-more-button.d.ts +1 -1
- package/dist/components/ui/load-more-button.d.ts.map +1 -1
- package/dist/components/ui/menu-dropdown.d.ts +1 -1
- package/dist/components/ui/menu-dropdown.d.ts.map +1 -1
- package/dist/components/ui/skeleton.d.ts +1 -1
- package/dist/components/ui/skeleton.d.ts.map +1 -1
- package/dist/components/ui/spinner.d.ts +1 -1
- package/dist/components/ui/spinner.d.ts.map +1 -1
- package/dist/components/workflow-traces/trace-span-construction.d.ts +8 -2
- package/dist/components/workflow-traces/trace-span-construction.d.ts.map +1 -1
- package/dist/components/workflow-traces/trace-span-construction.js +29 -11
- package/dist/index.d.ts +1 -0
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js +2 -1
- package/dist/lib/event-analysis.d.ts.map +1 -1
- package/dist/lib/event-analysis.js +10 -2
- package/dist/lib/event-materialization.d.ts +4 -0
- package/dist/lib/event-materialization.d.ts.map +1 -1
- package/dist/lib/event-materialization.js +25 -7
- package/dist/lib/hydration.d.ts +5 -3
- package/dist/lib/hydration.d.ts.map +1 -1
- package/dist/lib/hydration.js +10 -6
- package/dist/lib/start-hook.d.ts +30 -0
- package/dist/lib/start-hook.d.ts.map +1 -0
- package/dist/lib/start-hook.js +50 -0
- package/dist/lib/state-hydration.d.ts +37 -0
- package/dist/lib/state-hydration.d.ts.map +1 -0
- package/dist/lib/state-hydration.js +148 -0
- package/dist/lib/trace-builder.d.ts.map +1 -1
- package/dist/lib/trace-builder.js +12 -5
- package/package.json +19 -18
- package/src/components/sidebar/attribute-panel.tsx +1 -1
- package/src/components/sidebar/entity-detail-panel.tsx +31 -61
- package/src/components/trace-viewer/utils.test.ts +24 -0
- package/src/components/trace-viewer/utils.ts +14 -2
- package/src/components/workflow-traces/trace-span-construction.test.ts +30 -0
- package/src/components/workflow-traces/trace-span-construction.ts +34 -11
- package/src/index.ts +6 -0
- package/src/lib/event-analysis.ts +9 -0
- package/src/lib/event-materialization.ts +26 -7
- package/src/lib/hydration.ts +11 -5
- package/src/lib/start-hook.test.ts +174 -0
- package/src/lib/start-hook.ts +82 -0
- package/src/lib/state-hydration.test.ts +332 -0
- package/src/lib/state-hydration.ts +208 -0
- package/src/lib/trace-builder.ts +17 -2
package/src/lib/hydration.ts
CHANGED
|
@@ -530,9 +530,10 @@ function replaceEncryptedAndExpiredWithMarkers<T>(resource: T): T {
|
|
|
530
530
|
*/
|
|
531
531
|
export async function hydrateResourceIOWithKey<T>(
|
|
532
532
|
resource: T,
|
|
533
|
-
key: Uint8Array
|
|
533
|
+
key: Uint8Array,
|
|
534
|
+
extraRevivers?: Revivers
|
|
534
535
|
): Promise<T> {
|
|
535
|
-
return hydrateResourceIOAsync(resource, key);
|
|
536
|
+
return hydrateResourceIOAsync(resource, key, extraRevivers);
|
|
536
537
|
}
|
|
537
538
|
|
|
538
539
|
/**
|
|
@@ -541,11 +542,14 @@ export async function hydrateResourceIOWithKey<T>(
|
|
|
541
542
|
* This follows the same resource-field mapping as {@link hydrateResourceIO},
|
|
542
543
|
* but can also inflate compressed browser payloads through the registered
|
|
543
544
|
* zstd WASM decoder. When a key is provided, encrypted fields are decrypted
|
|
544
|
-
* first and then inflated/hydrated.
|
|
545
|
+
* first and then inflated/hydrated. `extraRevivers` are merged over the web
|
|
546
|
+
* revivers, for example a run's frozen state revivers (see
|
|
547
|
+
* `createRunStateHydrator`).
|
|
545
548
|
*/
|
|
546
549
|
export async function hydrateResourceIOAsync<T>(
|
|
547
550
|
resource: T,
|
|
548
|
-
key?: Uint8Array
|
|
551
|
+
key?: Uint8Array,
|
|
552
|
+
extraRevivers?: Revivers
|
|
549
553
|
): Promise<T> {
|
|
550
554
|
const { hydrateDataWithKey, deriveRunPayloadKeys } = await import(
|
|
551
555
|
'@workflow/core/serialization-format'
|
|
@@ -563,7 +567,9 @@ export async function hydrateResourceIOAsync<T>(
|
|
|
563
567
|
// run's X25519 scalar in addition to its AES key. Both derive from the same
|
|
564
568
|
// 32 bytes the key-retrieval endpoint returns.
|
|
565
569
|
const cryptoKey = key ? await deriveRunPayloadKeys(key) : undefined;
|
|
566
|
-
const revivers =
|
|
570
|
+
const revivers = extraRevivers
|
|
571
|
+
? { ...getRevivers(), ...extraRevivers }
|
|
572
|
+
: getRevivers();
|
|
567
573
|
|
|
568
574
|
async function hydrateField(value: unknown): Promise<unknown> {
|
|
569
575
|
// Already-hydrated: encrypted marker with stored bytes
|
|
@@ -0,0 +1,174 @@
|
|
|
1
|
+
import type { Event, EventType, WorkflowRun } from '@workflow/world';
|
|
2
|
+
import { describe, expect, it } from 'vitest';
|
|
3
|
+
import { otelTimeToMs } from '../components/workflow-traces/trace-time-utils';
|
|
4
|
+
import { analyzeEvents } from './event-analysis';
|
|
5
|
+
import { materializeHooks } from './event-materialization';
|
|
6
|
+
import { findStartHookCreation } from './start-hook';
|
|
7
|
+
import { buildTrace } from './trace-builder';
|
|
8
|
+
|
|
9
|
+
const RUN_ID = 'wrun_01ARZ3NDEKTSV4RRFFQ69G5FAV';
|
|
10
|
+
const START_HOOK_ID = 'hook_01ARZ3NDEKTSV4RRFFQ69G5FAV';
|
|
11
|
+
const TOKEN = 'start-token';
|
|
12
|
+
const BASE_TIME = Date.parse('2026-01-01T00:00:00.000Z');
|
|
13
|
+
|
|
14
|
+
let slot = 0;
|
|
15
|
+
|
|
16
|
+
function event(
|
|
17
|
+
eventType: EventType,
|
|
18
|
+
at: number,
|
|
19
|
+
{
|
|
20
|
+
correlationId,
|
|
21
|
+
eventData = {},
|
|
22
|
+
}: { correlationId?: string; eventData?: Record<string, unknown> } = {}
|
|
23
|
+
): Event {
|
|
24
|
+
slot += 1;
|
|
25
|
+
return {
|
|
26
|
+
eventId: `evnt_${String(slot).padStart(26, '0')}`,
|
|
27
|
+
runId: RUN_ID,
|
|
28
|
+
eventType,
|
|
29
|
+
correlationId,
|
|
30
|
+
createdAt: new Date(BASE_TIME + at * 1000),
|
|
31
|
+
occurredAt: new Date(BASE_TIME + at * 1000),
|
|
32
|
+
eventData,
|
|
33
|
+
specVersion: 8,
|
|
34
|
+
} as unknown as Event;
|
|
35
|
+
}
|
|
36
|
+
|
|
37
|
+
const run = {
|
|
38
|
+
runId: RUN_ID,
|
|
39
|
+
workflowName: 'workflow//./workflows/demo//demo',
|
|
40
|
+
status: 'completed',
|
|
41
|
+
createdAt: new Date(BASE_TIME),
|
|
42
|
+
completedAt: new Date(BASE_TIME + 60_000),
|
|
43
|
+
} as unknown as WorkflowRun;
|
|
44
|
+
|
|
45
|
+
/** The shape of a start Hook run's log: deliveries but no `hook_created`. */
|
|
46
|
+
function startHookRunLog(): Event[] {
|
|
47
|
+
slot = 0;
|
|
48
|
+
return [
|
|
49
|
+
event('run_created', 0, {
|
|
50
|
+
correlationId: RUN_ID,
|
|
51
|
+
eventData: { startHook: { token: TOKEN, hookId: START_HOOK_ID } },
|
|
52
|
+
}),
|
|
53
|
+
event('hook_received', 1, { correlationId: START_HOOK_ID }),
|
|
54
|
+
event('run_started', 1),
|
|
55
|
+
event('hook_received', 2, { correlationId: START_HOOK_ID }),
|
|
56
|
+
event('run_completed', 60),
|
|
57
|
+
];
|
|
58
|
+
}
|
|
59
|
+
|
|
60
|
+
describe('start Hook', () => {
|
|
61
|
+
it('builds a span for a start Hook from its deliveries', () => {
|
|
62
|
+
const trace = buildTrace(
|
|
63
|
+
run,
|
|
64
|
+
startHookRunLog(),
|
|
65
|
+
new Date(BASE_TIME + 61_000),
|
|
66
|
+
{
|
|
67
|
+
isCompleteHistory: true,
|
|
68
|
+
}
|
|
69
|
+
);
|
|
70
|
+
|
|
71
|
+
const hookSpans = trace.spans.filter((span) => span.resource === 'hook');
|
|
72
|
+
expect(hookSpans).toHaveLength(1);
|
|
73
|
+
const [hookSpan] = hookSpans;
|
|
74
|
+
expect(hookSpan.spanId).toBe(START_HOOK_ID);
|
|
75
|
+
expect(hookSpan.name).toBe(TOKEN);
|
|
76
|
+
expect(otelTimeToMs(hookSpan.startTime)).toBe(BASE_TIME);
|
|
77
|
+
expect(hookSpan.events.map((spanEvent) => spanEvent.name)).toEqual([
|
|
78
|
+
'hook_received',
|
|
79
|
+
'hook_received',
|
|
80
|
+
]);
|
|
81
|
+
expect(hookSpan.attributes.data).toMatchObject({
|
|
82
|
+
hookId: START_HOOK_ID,
|
|
83
|
+
token: TOKEN,
|
|
84
|
+
receivedCount: 2,
|
|
85
|
+
});
|
|
86
|
+
});
|
|
87
|
+
|
|
88
|
+
it('builds a span for a start Hook nothing was delivered to yet', () => {
|
|
89
|
+
slot = 0;
|
|
90
|
+
const events = [
|
|
91
|
+
event('run_created', 0, {
|
|
92
|
+
correlationId: RUN_ID,
|
|
93
|
+
eventData: { startHook: { token: TOKEN, hookId: START_HOOK_ID } },
|
|
94
|
+
}),
|
|
95
|
+
event('run_started', 1),
|
|
96
|
+
];
|
|
97
|
+
const trace = buildTrace(
|
|
98
|
+
{ ...run, status: 'running', completedAt: undefined } as WorkflowRun,
|
|
99
|
+
events,
|
|
100
|
+
new Date(BASE_TIME + 5000)
|
|
101
|
+
);
|
|
102
|
+
|
|
103
|
+
expect(
|
|
104
|
+
trace.spans
|
|
105
|
+
.filter((span) => span.resource === 'hook')
|
|
106
|
+
.map((s) => s.spanId)
|
|
107
|
+
).toEqual([START_HOOK_ID]);
|
|
108
|
+
});
|
|
109
|
+
|
|
110
|
+
it('ends a start Hook span at its disposal', () => {
|
|
111
|
+
const events = startHookRunLog();
|
|
112
|
+
events.splice(
|
|
113
|
+
4,
|
|
114
|
+
0,
|
|
115
|
+
event('hook_disposed', 10, { correlationId: START_HOOK_ID })
|
|
116
|
+
);
|
|
117
|
+
const trace = buildTrace(run, events, new Date(BASE_TIME + 61_000));
|
|
118
|
+
const [hookSpan] = trace.spans.filter((span) => span.resource === 'hook');
|
|
119
|
+
|
|
120
|
+
expect(otelTimeToMs(hookSpan.endTime)).toBe(BASE_TIME + 10_000);
|
|
121
|
+
});
|
|
122
|
+
|
|
123
|
+
it('recognizes a start Hook listed without event data by its id', () => {
|
|
124
|
+
const events = startHookRunLog().map(
|
|
125
|
+
(e) => ({ ...e, eventData: undefined }) as unknown as Event
|
|
126
|
+
);
|
|
127
|
+
|
|
128
|
+
expect(findStartHookCreation(events)).toEqual({
|
|
129
|
+
hookId: START_HOOK_ID,
|
|
130
|
+
runId: RUN_ID,
|
|
131
|
+
token: undefined,
|
|
132
|
+
createdAt: new Date(BASE_TIME),
|
|
133
|
+
});
|
|
134
|
+
});
|
|
135
|
+
|
|
136
|
+
it('finds no start Hook on a run started without one', () => {
|
|
137
|
+
slot = 0;
|
|
138
|
+
const events = [
|
|
139
|
+
event('run_created', 0, { correlationId: RUN_ID }),
|
|
140
|
+
event('run_started', 1),
|
|
141
|
+
event('hook_created', 2, {
|
|
142
|
+
correlationId: 'hook_other',
|
|
143
|
+
eventData: { token: 'other' },
|
|
144
|
+
}),
|
|
145
|
+
];
|
|
146
|
+
|
|
147
|
+
expect(findStartHookCreation(events, run)).toBeUndefined();
|
|
148
|
+
const trace = buildTrace(run, events, new Date(BASE_TIME + 5000));
|
|
149
|
+
expect(
|
|
150
|
+
trace.spans
|
|
151
|
+
.filter((span) => span.resource === 'hook')
|
|
152
|
+
.map((s) => s.spanId)
|
|
153
|
+
).toEqual(['hook_other']);
|
|
154
|
+
});
|
|
155
|
+
|
|
156
|
+
it('materializes a start Hook', () => {
|
|
157
|
+
expect(materializeHooks(startHookRunLog())).toMatchObject([
|
|
158
|
+
{
|
|
159
|
+
hookId: START_HOOK_ID,
|
|
160
|
+
runId: RUN_ID,
|
|
161
|
+
token: TOKEN,
|
|
162
|
+
createdAt: new Date(BASE_TIME),
|
|
163
|
+
receivedCount: 2,
|
|
164
|
+
},
|
|
165
|
+
]);
|
|
166
|
+
});
|
|
167
|
+
|
|
168
|
+
it('counts an undisposed start Hook as pending', () => {
|
|
169
|
+
expect(analyzeEvents(startHookRunLog().slice(0, 4))).toMatchObject({
|
|
170
|
+
hasPendingHooks: true,
|
|
171
|
+
pendingHookIds: [START_HOOK_ID],
|
|
172
|
+
});
|
|
173
|
+
});
|
|
174
|
+
});
|
|
@@ -0,0 +1,82 @@
|
|
|
1
|
+
import {
|
|
2
|
+
type Event,
|
|
3
|
+
isHookLifecycleEventType,
|
|
4
|
+
isRunCreationEvent,
|
|
5
|
+
startHookId,
|
|
6
|
+
type WorkflowRun,
|
|
7
|
+
} from '@workflow/world';
|
|
8
|
+
|
|
9
|
+
/**
|
|
10
|
+
* The creation of a run's start Hook (`start(workflow, args, { hook })`).
|
|
11
|
+
*
|
|
12
|
+
* A start Hook has no `hook_created` of its own: the World creates it while
|
|
13
|
+
* it admits the run, and the run's creation event (`run_created`, or the
|
|
14
|
+
* `run_started` holding the first slot) stands for it, carrying
|
|
15
|
+
* `eventData.startHook`. Its deliveries are ordinary `hook_received` events
|
|
16
|
+
* under {@link startHookId}`(runId)`, and it ends with an ordinary
|
|
17
|
+
* `hook_disposed`. Anything that rebuilds Hooks from the log has to seed the
|
|
18
|
+
* start Hook from here, or it drops the Hook and every delivery to it.
|
|
19
|
+
*/
|
|
20
|
+
export interface StartHookCreation {
|
|
21
|
+
hookId: string;
|
|
22
|
+
runId: string;
|
|
23
|
+
token?: string;
|
|
24
|
+
createdAt: Date;
|
|
25
|
+
}
|
|
26
|
+
|
|
27
|
+
function eventTimestamp(event: Event | undefined): Date | undefined {
|
|
28
|
+
const value = event?.occurredAt ?? event?.createdAt;
|
|
29
|
+
if (!value) return undefined;
|
|
30
|
+
const date = value instanceof Date ? value : new Date(value);
|
|
31
|
+
return Number.isNaN(date.getTime()) ? undefined : date;
|
|
32
|
+
}
|
|
33
|
+
|
|
34
|
+
function tokenOf(startHook: unknown): string | undefined {
|
|
35
|
+
if (!startHook || typeof startHook !== 'object') return undefined;
|
|
36
|
+
const { token } = startHook as { token?: unknown };
|
|
37
|
+
return typeof token === 'string' && token.length > 0 ? token : undefined;
|
|
38
|
+
}
|
|
39
|
+
|
|
40
|
+
/**
|
|
41
|
+
* The run's start Hook, or `undefined` for a run started without one.
|
|
42
|
+
*
|
|
43
|
+
* Read from the creation event's `eventData.startHook`, falling back to
|
|
44
|
+
* `run.startHook`. Events listed without their data still identify the start
|
|
45
|
+
* Hook by its id, so a run whose log holds an event for
|
|
46
|
+
* {@link startHookId}`(runId)` has one even when no token is known.
|
|
47
|
+
*/
|
|
48
|
+
export function findStartHookCreation(
|
|
49
|
+
events: readonly Event[],
|
|
50
|
+
run?: Pick<WorkflowRun, 'runId' | 'createdAt'> & { startHook?: unknown }
|
|
51
|
+
): StartHookCreation | undefined {
|
|
52
|
+
const creationEvent = events.find(isRunCreationEvent);
|
|
53
|
+
const runId = run?.runId ?? creationEvent?.runId ?? events[0]?.runId;
|
|
54
|
+
if (!runId?.startsWith('wrun_') || runId.length <= 'wrun_'.length) {
|
|
55
|
+
return undefined;
|
|
56
|
+
}
|
|
57
|
+
const hookId = startHookId(runId);
|
|
58
|
+
const token =
|
|
59
|
+
tokenOf(
|
|
60
|
+
creationEvent && 'eventData' in creationEvent
|
|
61
|
+
? (creationEvent.eventData as { startHook?: unknown } | undefined)
|
|
62
|
+
?.startHook
|
|
63
|
+
: undefined
|
|
64
|
+
) ?? tokenOf(run?.startHook);
|
|
65
|
+
const hookEvents = events.filter(
|
|
66
|
+
(event) =>
|
|
67
|
+
event.correlationId === hookId &&
|
|
68
|
+
isHookLifecycleEventType(event.eventType)
|
|
69
|
+
);
|
|
70
|
+
if (token === undefined && hookEvents.length === 0) return undefined;
|
|
71
|
+
// `hook_created` for a start Hook's id is refused by every World, so one in
|
|
72
|
+
// the log means this is not a start Hook after all.
|
|
73
|
+
if (hookEvents.some((event) => event.eventType === 'hook_created')) {
|
|
74
|
+
return undefined;
|
|
75
|
+
}
|
|
76
|
+
const createdAt =
|
|
77
|
+
eventTimestamp(creationEvent) ??
|
|
78
|
+
(run?.createdAt ? new Date(run.createdAt) : undefined) ??
|
|
79
|
+
eventTimestamp(hookEvents[0]);
|
|
80
|
+
if (!createdAt) return undefined;
|
|
81
|
+
return { hookId, runId, token, createdAt };
|
|
82
|
+
}
|
|
@@ -0,0 +1,332 @@
|
|
|
1
|
+
import { produce } from 'immer';
|
|
2
|
+
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
|
|
3
|
+
// The SDK's own writers, so the fixtures are exactly what a run stores.
|
|
4
|
+
import { StateContext } from '../../../core/src/serialization/state-refs';
|
|
5
|
+
import * as workflow from '../../../core/src/serialization/workflow';
|
|
6
|
+
import { hydrateResourceIOAsync } from './hydration';
|
|
7
|
+
import { createRunStateHydrator } from './state-hydration';
|
|
8
|
+
|
|
9
|
+
type Message = { role: string; content: string };
|
|
10
|
+
|
|
11
|
+
/** A run whose second step's input refers to the first step's output. */
|
|
12
|
+
function storedRun() {
|
|
13
|
+
const body = new StateContext();
|
|
14
|
+
const write = (value: unknown) =>
|
|
15
|
+
workflow.serialize(value, { stateContext: body });
|
|
16
|
+
const read = (bytes: Uint8Array) =>
|
|
17
|
+
workflow.deserialize(bytes, { stateContext: body }) as any;
|
|
18
|
+
|
|
19
|
+
const output1 = write({
|
|
20
|
+
history: produce([] as Message[], (d) => {
|
|
21
|
+
d.push({ role: 'user', content: 'hello' });
|
|
22
|
+
}),
|
|
23
|
+
});
|
|
24
|
+
const v1 = read(output1).history;
|
|
25
|
+
const input2 = write({ history: v1 });
|
|
26
|
+
const output2 = write({
|
|
27
|
+
history: produce(v1 as Message[], (d) => {
|
|
28
|
+
d.push({ role: 'assistant', content: 'hi' });
|
|
29
|
+
}),
|
|
30
|
+
});
|
|
31
|
+
const runInput = workflow.serialize(
|
|
32
|
+
{ prompt: 'hello' },
|
|
33
|
+
{ stateContext: new StateContext() }
|
|
34
|
+
);
|
|
35
|
+
const events = [
|
|
36
|
+
{ eventId: 'e1', eventType: 'run_created', eventData: {} },
|
|
37
|
+
{
|
|
38
|
+
eventId: 'e2',
|
|
39
|
+
eventType: 'step_completed',
|
|
40
|
+
eventData: { result: output1 },
|
|
41
|
+
},
|
|
42
|
+
{
|
|
43
|
+
eventId: 'e3',
|
|
44
|
+
eventType: 'step_completed',
|
|
45
|
+
eventData: { result: output2 },
|
|
46
|
+
},
|
|
47
|
+
];
|
|
48
|
+
return { runInput, input2, output2, events };
|
|
49
|
+
}
|
|
50
|
+
|
|
51
|
+
describe('createRunStateHydrator', () => {
|
|
52
|
+
beforeEach(() => {});
|
|
53
|
+
afterEach(() => {});
|
|
54
|
+
|
|
55
|
+
it('shows the actual input and output of a step, reading the history once', async () => {
|
|
56
|
+
const run = storedRun();
|
|
57
|
+
const loadRunInput = vi.fn(async () => run.runInput);
|
|
58
|
+
const loadEvents = vi.fn(async () => ({
|
|
59
|
+
data: run.events,
|
|
60
|
+
hasMore: false,
|
|
61
|
+
}));
|
|
62
|
+
const hydrator = createRunStateHydrator({ loadRunInput, loadEvents });
|
|
63
|
+
const step = { stepId: 's2', input: run.input2, output: run.output2 };
|
|
64
|
+
|
|
65
|
+
// Without the history the input is only a placeholder.
|
|
66
|
+
const plain = (await hydrateResourceIOAsync(step)) as any;
|
|
67
|
+
expect(plain.input.history).toMatch(/^<state /);
|
|
68
|
+
|
|
69
|
+
const shown = (await hydrator.hydrate(step)) as any;
|
|
70
|
+
expect(shown.input.history).toEqual([{ role: 'user', content: 'hello' }]);
|
|
71
|
+
expect(shown.output.history).toEqual([
|
|
72
|
+
{ role: 'user', content: 'hello' },
|
|
73
|
+
{ role: 'assistant', content: 'hi' },
|
|
74
|
+
]);
|
|
75
|
+
|
|
76
|
+
// Later inspections reuse what was read.
|
|
77
|
+
await hydrator.hydrate(step);
|
|
78
|
+
expect(loadEvents).toHaveBeenCalledTimes(1);
|
|
79
|
+
expect(loadRunInput).toHaveBeenCalledTimes(1);
|
|
80
|
+
});
|
|
81
|
+
|
|
82
|
+
it('stops reading when the events cursor does not advance', async () => {
|
|
83
|
+
const run = storedRun();
|
|
84
|
+
// A misbehaving backend: always more, always the same cursor.
|
|
85
|
+
const loadEvents = vi.fn(async () => ({
|
|
86
|
+
data: [],
|
|
87
|
+
cursor: 'stuck',
|
|
88
|
+
hasMore: true,
|
|
89
|
+
}));
|
|
90
|
+
const hydrator = createRunStateHydrator({
|
|
91
|
+
loadRunInput: async () => run.runInput,
|
|
92
|
+
loadEvents,
|
|
93
|
+
});
|
|
94
|
+
const shown = (await hydrator.hydrate({
|
|
95
|
+
stepId: 's2',
|
|
96
|
+
input: run.input2,
|
|
97
|
+
})) as any;
|
|
98
|
+
expect(shown.input.history).toMatch(/^<state /);
|
|
99
|
+
expect(loadEvents).toHaveBeenCalledTimes(2);
|
|
100
|
+
});
|
|
101
|
+
|
|
102
|
+
it('does not read the history for values that do not need it', async () => {
|
|
103
|
+
const loadEvents = vi.fn();
|
|
104
|
+
const hydrator = createRunStateHydrator({
|
|
105
|
+
loadRunInput: vi.fn(),
|
|
106
|
+
loadEvents,
|
|
107
|
+
});
|
|
108
|
+
const run = storedRun();
|
|
109
|
+
const shown = (await hydrator.hydrate({ input: run.runInput })) as any;
|
|
110
|
+
expect(shown.input).toEqual({ prompt: 'hello' });
|
|
111
|
+
expect(loadEvents).not.toHaveBeenCalled();
|
|
112
|
+
});
|
|
113
|
+
|
|
114
|
+
it('reads only newer events when a later step needs them', async () => {
|
|
115
|
+
const run = storedRun();
|
|
116
|
+
const pages = [
|
|
117
|
+
{ data: run.events.slice(0, 1), cursor: 'c1', hasMore: false },
|
|
118
|
+
{ data: run.events, cursor: 'c2', hasMore: false },
|
|
119
|
+
];
|
|
120
|
+
const loadEvents = vi.fn(async () => pages.shift()!);
|
|
121
|
+
const hydrator = createRunStateHydrator({
|
|
122
|
+
loadRunInput: async () => run.runInput,
|
|
123
|
+
loadEvents,
|
|
124
|
+
});
|
|
125
|
+
const step = { input: run.input2 };
|
|
126
|
+
|
|
127
|
+
// The first read happened before the step that stored the state.
|
|
128
|
+
expect(((await hydrator.hydrate(step)) as any).input.history).toMatch(
|
|
129
|
+
/^<state /
|
|
130
|
+
);
|
|
131
|
+
expect(((await hydrator.hydrate(step)) as any).input.history).toEqual([
|
|
132
|
+
{ role: 'user', content: 'hello' },
|
|
133
|
+
]);
|
|
134
|
+
expect(loadEvents).toHaveBeenNthCalledWith(2, 'c1');
|
|
135
|
+
});
|
|
136
|
+
|
|
137
|
+
it('resolves strings later state takes from a hook payload', async () => {
|
|
138
|
+
const message = 'Weather in Oslo for the next three days, please. '.repeat(
|
|
139
|
+
4
|
|
140
|
+
);
|
|
141
|
+
const hook = workflow.serialize(
|
|
142
|
+
{ message },
|
|
143
|
+
{ stateContext: new StateContext() }
|
|
144
|
+
);
|
|
145
|
+
const replay = new StateContext();
|
|
146
|
+
replay.addSource(
|
|
147
|
+
'hook:evnt_h',
|
|
148
|
+
workflow.deserialize(hook, { stateContext: replay })
|
|
149
|
+
);
|
|
150
|
+
const output = workflow.serialize(
|
|
151
|
+
{
|
|
152
|
+
history: produce([] as Message[], (d) => {
|
|
153
|
+
d.push({ role: 'user', content: message });
|
|
154
|
+
}),
|
|
155
|
+
},
|
|
156
|
+
{ stateContext: replay }
|
|
157
|
+
);
|
|
158
|
+
const v1 = (workflow.deserialize(output, { stateContext: replay }) as any)
|
|
159
|
+
.history;
|
|
160
|
+
const input = workflow.serialize({ history: v1 }, { stateContext: replay });
|
|
161
|
+
const hydrator = createRunStateHydrator({
|
|
162
|
+
loadRunInput: async () => undefined,
|
|
163
|
+
loadEvents: async () => ({
|
|
164
|
+
data: [
|
|
165
|
+
{
|
|
166
|
+
eventId: 'evnt_h',
|
|
167
|
+
eventType: 'hook_received',
|
|
168
|
+
eventData: { payload: hook },
|
|
169
|
+
},
|
|
170
|
+
{
|
|
171
|
+
eventId: 'e2',
|
|
172
|
+
eventType: 'step_completed',
|
|
173
|
+
eventData: { result: output },
|
|
174
|
+
},
|
|
175
|
+
],
|
|
176
|
+
hasMore: false,
|
|
177
|
+
}),
|
|
178
|
+
});
|
|
179
|
+
const shown = (await hydrator.hydrate({ input })) as any;
|
|
180
|
+
expect(shown.input.history).toEqual([{ role: 'user', content: message }]);
|
|
181
|
+
});
|
|
182
|
+
|
|
183
|
+
it('reads only as much of a long run as the inspected step needs', async () => {
|
|
184
|
+
const writer = new StateContext();
|
|
185
|
+
let history: readonly unknown[] = Object.freeze([]);
|
|
186
|
+
const events: { eventId: string; eventType: string; eventData: unknown }[] =
|
|
187
|
+
[];
|
|
188
|
+
const inputs: Uint8Array[] = [];
|
|
189
|
+
for (let i = 0; i < 2_000; i++) {
|
|
190
|
+
inputs.push(
|
|
191
|
+
workflow.serialize(
|
|
192
|
+
{ history },
|
|
193
|
+
{ stateContext: writer, stateInput: true }
|
|
194
|
+
)
|
|
195
|
+
);
|
|
196
|
+
const next = Object.freeze([
|
|
197
|
+
...history,
|
|
198
|
+
Object.freeze({ role: 'user', content: `message ${i}` }),
|
|
199
|
+
]);
|
|
200
|
+
const result = workflow.serialize(
|
|
201
|
+
{ history: next },
|
|
202
|
+
{ stateContext: writer }
|
|
203
|
+
);
|
|
204
|
+
history = (workflow.deserialize(result, { stateContext: writer }) as any)
|
|
205
|
+
.history;
|
|
206
|
+
events.push({
|
|
207
|
+
eventId: `e${i}`,
|
|
208
|
+
eventType: 'step_completed',
|
|
209
|
+
eventData: { result },
|
|
210
|
+
});
|
|
211
|
+
}
|
|
212
|
+
const PAGE = 100;
|
|
213
|
+
let pages = 0;
|
|
214
|
+
const hydrator = createRunStateHydrator({
|
|
215
|
+
loadRunInput: async () => undefined,
|
|
216
|
+
loadEvents: async (cursor) => {
|
|
217
|
+
pages++;
|
|
218
|
+
const from = cursor ? Number(cursor) : 0;
|
|
219
|
+
const to = from + PAGE;
|
|
220
|
+
return {
|
|
221
|
+
data: events.slice(from, to),
|
|
222
|
+
cursor: String(to),
|
|
223
|
+
hasMore: to < events.length,
|
|
224
|
+
};
|
|
225
|
+
},
|
|
226
|
+
});
|
|
227
|
+
|
|
228
|
+
// Step 51's input refers to step 50's output: the first page has it.
|
|
229
|
+
let started = performance.now();
|
|
230
|
+
const early = (await hydrator.hydrate({ input: inputs[51] })) as any;
|
|
231
|
+
const earlyMs = performance.now() - started;
|
|
232
|
+
expect(early.input.history).toHaveLength(51);
|
|
233
|
+
expect(pages).toBe(1);
|
|
234
|
+
|
|
235
|
+
// The last step needs the whole run: read on from where the first stopped.
|
|
236
|
+
started = performance.now();
|
|
237
|
+
const late = (await hydrator.hydrate({ input: inputs[1_999] })) as any;
|
|
238
|
+
const lateMs = performance.now() - started;
|
|
239
|
+
expect(late.input.history).toHaveLength(1_999);
|
|
240
|
+
expect(pages).toBe(20);
|
|
241
|
+
// ~10 ms and ~250 ms on a laptop.
|
|
242
|
+
expect(earlyMs).toBeLessThan(lateMs);
|
|
243
|
+
expect(lateMs).toBeLessThan(10_000);
|
|
244
|
+
});
|
|
245
|
+
|
|
246
|
+
it('reads on for every concurrent inspection that needs a later page', async () => {
|
|
247
|
+
const writer = new StateContext();
|
|
248
|
+
let history: readonly unknown[] = Object.freeze([]);
|
|
249
|
+
const events: { eventId: string; eventType: string; eventData: unknown }[] =
|
|
250
|
+
[];
|
|
251
|
+
const inputs: Uint8Array[] = [];
|
|
252
|
+
for (let i = 0; i < 400; i++) {
|
|
253
|
+
inputs.push(
|
|
254
|
+
workflow.serialize(
|
|
255
|
+
{ history },
|
|
256
|
+
{ stateContext: writer, stateInput: true }
|
|
257
|
+
)
|
|
258
|
+
);
|
|
259
|
+
const next = Object.freeze([
|
|
260
|
+
...history,
|
|
261
|
+
Object.freeze({ role: 'user', content: `message ${i}` }),
|
|
262
|
+
]);
|
|
263
|
+
const result = workflow.serialize(
|
|
264
|
+
{ history: next },
|
|
265
|
+
{ stateContext: writer }
|
|
266
|
+
);
|
|
267
|
+
history = (workflow.deserialize(result, { stateContext: writer }) as any)
|
|
268
|
+
.history;
|
|
269
|
+
events.push({
|
|
270
|
+
eventId: `e${i}`,
|
|
271
|
+
eventType: 'step_completed',
|
|
272
|
+
eventData: { result },
|
|
273
|
+
});
|
|
274
|
+
}
|
|
275
|
+
const hydrator = createRunStateHydrator({
|
|
276
|
+
loadRunInput: async () => undefined,
|
|
277
|
+
loadEvents: async (cursor) => {
|
|
278
|
+
const from = cursor ? Number(cursor) : 0;
|
|
279
|
+
const to = from + 100;
|
|
280
|
+
return {
|
|
281
|
+
data: events.slice(from, to),
|
|
282
|
+
cursor: String(to),
|
|
283
|
+
hasMore: to < events.length,
|
|
284
|
+
};
|
|
285
|
+
},
|
|
286
|
+
});
|
|
287
|
+
// Each needs a later page than the one before it; started together, the
|
|
288
|
+
// later ones first wait on a read that stops early.
|
|
289
|
+
const results = (await Promise.all(
|
|
290
|
+
[51, 151, 251, 351].map((i) => hydrator.hydrate({ input: inputs[i] }))
|
|
291
|
+
)) as any[];
|
|
292
|
+
expect(results.map((r) => r.input.history.length)).toEqual([
|
|
293
|
+
51, 151, 251, 351,
|
|
294
|
+
]);
|
|
295
|
+
});
|
|
296
|
+
|
|
297
|
+
it("rebuilds the value when the run input can't be loaded", async () => {
|
|
298
|
+
const writer = new StateContext();
|
|
299
|
+
let history: readonly unknown[] = Object.freeze([]);
|
|
300
|
+
const events: { eventId: string; eventType: string; eventData: unknown }[] =
|
|
301
|
+
[];
|
|
302
|
+
for (let i = 0; i < 3; i++) {
|
|
303
|
+
const next = Object.freeze([
|
|
304
|
+
...history,
|
|
305
|
+
Object.freeze({ role: 'user', content: `message ${i}` }),
|
|
306
|
+
]);
|
|
307
|
+
const result = workflow.serialize(
|
|
308
|
+
{ history: next },
|
|
309
|
+
{ stateContext: writer }
|
|
310
|
+
);
|
|
311
|
+
history = (workflow.deserialize(result, { stateContext: writer }) as any)
|
|
312
|
+
.history;
|
|
313
|
+
events.push({
|
|
314
|
+
eventId: `e${i}`,
|
|
315
|
+
eventType: 'step_completed',
|
|
316
|
+
eventData: { result },
|
|
317
|
+
});
|
|
318
|
+
}
|
|
319
|
+
const input = workflow.serialize(
|
|
320
|
+
{ history },
|
|
321
|
+
{ stateContext: writer, stateInput: true }
|
|
322
|
+
);
|
|
323
|
+
const hydrator = createRunStateHydrator({
|
|
324
|
+
loadRunInput: async () => {
|
|
325
|
+
throw new Error('run not found');
|
|
326
|
+
},
|
|
327
|
+
loadEvents: async () => ({ data: events, hasMore: false }),
|
|
328
|
+
});
|
|
329
|
+
const shown = (await hydrator.hydrate({ input })) as any;
|
|
330
|
+
expect(shown.input.history).toHaveLength(3);
|
|
331
|
+
});
|
|
332
|
+
});
|