basalt-ui 1.9.0 → 1.11.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/AGENTS.md +2 -1
- package/CHANGELOG.md +18 -0
- package/README.md +64 -34
- package/agent/rules/basalt-agent.md +49 -6
- package/configs/oxlint-plugin.js +279 -0
- package/configs/oxlint-plugin.test.ts +216 -1
- package/configs/oxlint.json +5 -2
- package/dist/agent/ai-sdk-transport.d.ts +3 -52
- package/dist/agent/ai-sdk-transport.d.ts.map +1 -1
- package/dist/agent/ai-sdk-transport.js +108 -24
- package/dist/agent/coalesce.d.ts +26 -0
- package/dist/agent/coalesce.d.ts.map +1 -0
- package/dist/agent/coalesce.js +69 -0
- package/dist/agent/foreign.d.ts +97 -0
- package/dist/agent/foreign.d.ts.map +1 -0
- package/dist/agent/foreign.js +18 -0
- package/dist/agent/history.d.ts +2 -0
- package/dist/agent/history.d.ts.map +1 -1
- package/dist/agent/id.d.ts +35 -0
- package/dist/agent/id.d.ts.map +1 -0
- package/dist/agent/id.js +14 -0
- package/dist/agent/index.d.ts +9 -4
- package/dist/agent/index.d.ts.map +1 -1
- package/dist/agent/index.js +15 -3
- package/dist/agent/merge.d.ts +8 -0
- package/dist/agent/merge.d.ts.map +1 -0
- package/dist/agent/merge.js +23 -0
- package/dist/agent/part-list.d.ts.map +1 -1
- package/dist/agent/part-list.js +16 -6
- package/dist/agent/parts.d.ts +100 -21
- package/dist/agent/parts.d.ts.map +1 -1
- package/dist/agent/parts.js +128 -11
- package/dist/agent/transport.d.ts +39 -3
- package/dist/agent/transport.d.ts.map +1 -1
- package/dist/agent/transport.js +20 -17
- package/dist/agent/use-agent-stream.d.ts +2 -1
- package/dist/agent/use-agent-stream.d.ts.map +1 -1
- package/dist/agent/use-agent-stream.js +5 -2
- package/dist/agent/use-agent-thread-runs.d.ts +9 -3
- package/dist/agent/use-agent-thread-runs.d.ts.map +1 -1
- package/dist/agent/use-agent-thread-runs.js +76 -23
- package/dist/agent-chat/index.d.ts +6 -3
- package/dist/agent-chat/index.d.ts.map +1 -1
- package/dist/agent-chat/index.js +2 -0
- package/dist/agent-chat/thread-message.d.ts +24 -7
- package/dist/agent-chat/thread-message.d.ts.map +1 -1
- package/dist/agent-chat/thread-message.js +102 -43
- package/dist/agent-chat/tool-chip.d.ts +21 -0
- package/dist/agent-chat/tool-chip.d.ts.map +1 -0
- package/dist/agent-chat/tool-chip.js +120 -0
- package/dist/cli/index.d.ts +33 -0
- package/dist/cli/index.d.ts.map +1 -1
- package/dist/cli/index.js +131 -0
- package/dist/guard/index.d.ts.map +1 -1
- package/dist/guard/index.js +1 -3
- package/dist/index.d.ts +2 -2
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js +3 -1
- package/dist/surfaces.d.ts +11 -1
- package/dist/surfaces.d.ts.map +1 -1
- package/dist/surfaces.js +22 -1
- package/llms.txt +10 -3
- package/package.json +6 -1
- package/src/agent/ai-sdk-transport.test.ts +567 -0
- package/src/agent/ai-sdk-transport.ts +206 -53
- package/src/agent/coalesce.test.ts +194 -0
- package/src/agent/coalesce.ts +118 -0
- package/src/agent/foreign.test.ts +47 -0
- package/src/agent/foreign.ts +140 -0
- package/src/agent/history.ts +2 -0
- package/src/agent/id.test.ts +71 -0
- package/src/agent/id.ts +43 -0
- package/src/agent/index.ts +26 -3
- package/src/agent/merge.test.ts +119 -0
- package/src/agent/merge.ts +67 -0
- package/src/agent/part-list.test.tsx +82 -0
- package/src/agent/part-list.tsx +31 -6
- package/src/agent/parts.test.ts +603 -0
- package/src/agent/parts.ts +262 -32
- package/src/agent/thread.test.ts +147 -0
- package/src/agent/transport.test.ts +70 -0
- package/src/agent/transport.ts +72 -20
- package/src/agent/use-agent-stream.test.tsx +261 -0
- package/src/agent/use-agent-stream.ts +13 -3
- package/src/agent/use-agent-thread-runs.foreign.test.tsx +133 -0
- package/src/agent/use-agent-thread-runs.resume.test.tsx +289 -0
- package/src/agent/use-agent-thread-runs.test.tsx +781 -0
- package/src/agent/use-agent-thread-runs.ts +177 -27
- package/src/agent/use-agent-thread-runs.wedge.test.tsx +301 -0
- package/src/agent-chat/index.ts +8 -3
- package/src/agent-chat/thread-message.test.tsx +211 -0
- package/src/agent-chat/thread-message.tsx +235 -62
- package/src/agent-chat/tool-chip.test.tsx +139 -0
- package/src/agent-chat/tool-chip.tsx +219 -0
- package/src/charts/primitives/ChartFrame.test.tsx +8 -5
- package/src/cli/index.ts +285 -0
- package/src/dashboard/stat-card.test.tsx +5 -3
- package/src/guard/check-source.test.ts +8 -4
- package/src/guard/index.ts +1 -3
- package/src/index.ts +2 -0
- package/src/provider/index.test.tsx +6 -5
- package/src/surfaces.ts +23 -1
- package/src/theme/use-basalt-spacing.test.tsx +7 -4
- package/src/tokens/build-fonts-css.test.ts +3 -2
package/src/agent/transport.ts
CHANGED
|
@@ -29,7 +29,7 @@
|
|
|
29
29
|
* api.chat.post({ body: { message: input }, fetch: { signal } }),
|
|
30
30
|
* )
|
|
31
31
|
*/
|
|
32
|
-
import type { AgentPart } from './parts'
|
|
32
|
+
import type { AgentPart, AgentPartDraft } from './parts'
|
|
33
33
|
|
|
34
34
|
// ── AgentTransport ────────────────────────────────────────────────────────────
|
|
35
35
|
|
|
@@ -37,6 +37,11 @@ import type { AgentPart } from './parts'
|
|
|
37
37
|
* The injected transport seam. `stream(input, signal)` returns an async generator of parts.
|
|
38
38
|
* Implement this interface for any backend — Eden, fetch-based SSE, AI SDK, or a mock.
|
|
39
39
|
*
|
|
40
|
+
* The default `TPart` is `AgentPartDraft` (not `AgentPart`): transports yield DRAFTS — `id`
|
|
41
|
+
* optional — and the consuming hooks (or `withPartIds`) normalize a draft into a fully-identified
|
|
42
|
+
* part before it is ever accumulated. Pass an explicit `AgentPart` generic when a transport mints
|
|
43
|
+
* its own ids directly (as `aiSdkTransport` does).
|
|
44
|
+
*
|
|
40
45
|
* @example
|
|
41
46
|
* // Minimal mock transport for tests / playground:
|
|
42
47
|
* const mockTransport: AgentTransport = {
|
|
@@ -45,12 +50,48 @@ import type { AgentPart } from './parts'
|
|
|
45
50
|
* },
|
|
46
51
|
* }
|
|
47
52
|
*/
|
|
48
|
-
export type AgentTransport<TPart =
|
|
53
|
+
export type AgentTransport<TPart = AgentPartDraft, TInput = string> = {
|
|
49
54
|
stream: (input: TInput, signal?: AbortSignal) => AsyncGenerator<TPart>
|
|
50
55
|
/** Optional: resume a previously-started run from its resumeToken (see StartPart). Transports that don't support resumption simply omit this. */
|
|
51
56
|
resume?: (resumeToken: string, signal?: AbortSignal) => AsyncGenerator<TPart>
|
|
52
57
|
}
|
|
53
58
|
|
|
59
|
+
// ── ResumableAgentTransport ───────────────────────────────────────────────────
|
|
60
|
+
|
|
61
|
+
/**
|
|
62
|
+
* A transport whose replay is safe to run over an already-rendered turn. Implementing `resume`
|
|
63
|
+
* alone is no longer enough: `idempotentReplay: true` is a literal-typed assertion that every
|
|
64
|
+
* text/reasoning part this transport emits carries an authoritative `offset`, so mergePart
|
|
65
|
+
* rewrites instead of appending.
|
|
66
|
+
*/
|
|
67
|
+
export type ResumableAgentTransport<TPart = AgentPartDraft, TInput = string> = AgentTransport<
|
|
68
|
+
TPart,
|
|
69
|
+
TInput
|
|
70
|
+
> & {
|
|
71
|
+
readonly resume: (resumeToken: string, signal?: AbortSignal) => AsyncGenerator<TPart>
|
|
72
|
+
readonly idempotentReplay: true
|
|
73
|
+
}
|
|
74
|
+
|
|
75
|
+
/**
|
|
76
|
+
* Type guard: true when `t` both implements `resume` AND has explicitly asserted
|
|
77
|
+
* `idempotentReplay: true`. A transport with `resume` but no `idempotentReplay` is NOT resumable
|
|
78
|
+
* — the mount-time reconcile in `useAgentThreadRuns` falls back to `'interrupted'` for it rather
|
|
79
|
+
* than risk duplicating already-rendered content.
|
|
80
|
+
*
|
|
81
|
+
* @example
|
|
82
|
+
* if (isResumable(transport)) {
|
|
83
|
+
* for await (const part of transport.resume(resumeToken)) { ... }
|
|
84
|
+
* }
|
|
85
|
+
*/
|
|
86
|
+
export function isResumable<TPart, TInput>(
|
|
87
|
+
t: AgentTransport<TPart, TInput>,
|
|
88
|
+
): t is ResumableAgentTransport<TPart, TInput> {
|
|
89
|
+
return (
|
|
90
|
+
typeof t.resume === 'function' &&
|
|
91
|
+
(t as Partial<ResumableAgentTransport<TPart, TInput>>).idempotentReplay === true
|
|
92
|
+
)
|
|
93
|
+
}
|
|
94
|
+
|
|
54
95
|
// ── edenTransport ─────────────────────────────────────────────────────────────
|
|
55
96
|
|
|
56
97
|
/**
|
|
@@ -70,6 +111,12 @@ export type AgentTransport<TPart = AgentPart, TInput = string> = {
|
|
|
70
111
|
* object has NO `resume` key at all (not `resume: undefined`) — consumers that don't wire a
|
|
71
112
|
* resumable backend get a transport that behaves exactly as before.
|
|
72
113
|
*
|
|
114
|
+
* `resumeCall` alone does NOT make the transport resumable per `isResumable` — pass
|
|
115
|
+
* `{ idempotentReplay: true }` as the third argument to opt in EXPLICITLY once the server-side
|
|
116
|
+
* `resumeCall` route is verified to re-emit every text/reasoning delta with an authoritative
|
|
117
|
+
* `offset` (never a bare append). This is an opt-in, not an inference: a `resumeCall` whose deltas
|
|
118
|
+
* aren't offset-accurate would double-render on replay if treated as resumable.
|
|
119
|
+
*
|
|
73
120
|
* @example
|
|
74
121
|
* import { edenTransport, type AgentPart } from 'basalt-ui/agent'
|
|
75
122
|
*
|
|
@@ -78,6 +125,7 @@ export type AgentTransport<TPart = AgentPart, TInput = string> = {
|
|
|
78
125
|
* const transport = edenTransport<AgentPart>(
|
|
79
126
|
* (input, signal) => api.chat.post({ body: { message: input }, fetch: { signal } }),
|
|
80
127
|
* (resumeToken, signal) => api.chat.resume.post({ body: { resumeToken }, fetch: { signal } }),
|
|
128
|
+
* { idempotentReplay: true },
|
|
81
129
|
* )
|
|
82
130
|
*
|
|
83
131
|
* // Wire into useAgentStream:
|
|
@@ -92,23 +140,27 @@ export function edenTransport<TPart = AgentPart, TInput = string>(
|
|
|
92
140
|
resumeToken: string,
|
|
93
141
|
signal?: AbortSignal,
|
|
94
142
|
) => Promise<{ data: AsyncGenerator<TPart> | null; error: unknown }>,
|
|
95
|
-
|
|
96
|
-
|
|
97
|
-
|
|
98
|
-
|
|
99
|
-
|
|
100
|
-
|
|
101
|
-
|
|
102
|
-
|
|
103
|
-
|
|
104
|
-
|
|
105
|
-
|
|
106
|
-
|
|
107
|
-
|
|
108
|
-
|
|
109
|
-
|
|
110
|
-
|
|
111
|
-
|
|
112
|
-
|
|
143
|
+
options?: { readonly idempotentReplay?: true },
|
|
144
|
+
): AgentTransport<TPart, TInput> | ResumableAgentTransport<TPart, TInput> {
|
|
145
|
+
const stream = async function* (input: TInput, signal?: AbortSignal): AsyncGenerator<TPart> {
|
|
146
|
+
const { data, error } = await call(input, signal)
|
|
147
|
+
if (error) throw error
|
|
148
|
+
if (data === null) return
|
|
149
|
+
yield* data
|
|
150
|
+
}
|
|
151
|
+
|
|
152
|
+
if (resumeCall === undefined) return { stream }
|
|
153
|
+
|
|
154
|
+
const resume = async function* (
|
|
155
|
+
resumeToken: string,
|
|
156
|
+
signal?: AbortSignal,
|
|
157
|
+
): AsyncGenerator<TPart> {
|
|
158
|
+
const { data, error } = await resumeCall(resumeToken, signal)
|
|
159
|
+
if (error) throw error
|
|
160
|
+
if (data === null) return
|
|
161
|
+
yield* data
|
|
113
162
|
}
|
|
163
|
+
|
|
164
|
+
if (options?.idempotentReplay !== true) return { stream, resume }
|
|
165
|
+
return { stream, resume, idempotentReplay: true }
|
|
114
166
|
}
|
|
@@ -0,0 +1,261 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* useAgentStream — single in-flight-turn lifecycle: abort, supersede, error, AbortError handling,
|
|
3
|
+
* unmount cleanup, and StrictMode double-invoke of a "send on mount" consumer effect.
|
|
4
|
+
*
|
|
5
|
+
* Scope: the API AS IT EXISTS TODAY (B1) — no stop-preserves-the-partial-turn semantics, no
|
|
6
|
+
* `ChatMessage.finish`; those are later-release surface (see the sibling `use-agent-thread-runs.*`
|
|
7
|
+
* test files' scope note).
|
|
8
|
+
*/
|
|
9
|
+
import { describe, expect, test } from 'bun:test'
|
|
10
|
+
import { StrictMode, useEffect } from 'react'
|
|
11
|
+
import { act, render, renderHook, waitFor } from '@testing-library/react'
|
|
12
|
+
import { useAgentStream } from './use-agent-stream'
|
|
13
|
+
import type { AgentTransport } from './transport'
|
|
14
|
+
import type { AgentPart } from './parts'
|
|
15
|
+
|
|
16
|
+
function deferred<T>(): { promise: Promise<T>; resolve: (value: T) => void } {
|
|
17
|
+
let resolve!: (value: T) => void
|
|
18
|
+
const promise = new Promise<T>((r) => {
|
|
19
|
+
resolve = r
|
|
20
|
+
})
|
|
21
|
+
return { promise, resolve }
|
|
22
|
+
}
|
|
23
|
+
|
|
24
|
+
describe('useAgentStream', () => {
|
|
25
|
+
test('stop() mid-stream sets status "done" and discards any parts that arrive after the abort', async () => {
|
|
26
|
+
const gate = deferred<void>()
|
|
27
|
+
const transport: AgentTransport<AgentPart, string> = {
|
|
28
|
+
async *stream() {
|
|
29
|
+
yield { id: 'p1', type: 'text', text: 'a' }
|
|
30
|
+
await gate.promise
|
|
31
|
+
// Must never be observed — the consumer's guard should discard this once aborted.
|
|
32
|
+
yield { id: 'p2', type: 'text', text: 'b' }
|
|
33
|
+
},
|
|
34
|
+
}
|
|
35
|
+
|
|
36
|
+
const { result } = renderHook(() => useAgentStream({ transport }))
|
|
37
|
+
|
|
38
|
+
act(() => {
|
|
39
|
+
void result.current.send('hi')
|
|
40
|
+
})
|
|
41
|
+
await waitFor(() => {
|
|
42
|
+
expect(result.current.parts).toEqual([{ id: 'p1', type: 'text', text: 'a' }])
|
|
43
|
+
})
|
|
44
|
+
expect(result.current.status).toBe('streaming')
|
|
45
|
+
|
|
46
|
+
act(() => {
|
|
47
|
+
result.current.stop()
|
|
48
|
+
})
|
|
49
|
+
// stop() sets 'done' synchronously — never 'error', even for an in-flight stream.
|
|
50
|
+
expect(result.current.status).toBe('done')
|
|
51
|
+
|
|
52
|
+
gate.resolve(undefined)
|
|
53
|
+
await waitFor(() => {
|
|
54
|
+
expect(result.current.status).toBe('done')
|
|
55
|
+
})
|
|
56
|
+
expect(result.current.parts).toEqual([{ id: 'p1', type: 'text', text: 'a' }])
|
|
57
|
+
})
|
|
58
|
+
|
|
59
|
+
test("a second send() supersedes an in-flight one — the first stream's later parts are discarded", async () => {
|
|
60
|
+
const gateFirst = deferred<void>()
|
|
61
|
+
const transport: AgentTransport<AgentPart, string> = {
|
|
62
|
+
async *stream(input) {
|
|
63
|
+
if (input === 'first') {
|
|
64
|
+
yield { id: 'f1', type: 'text', text: 'first-1' }
|
|
65
|
+
await gateFirst.promise
|
|
66
|
+
// Must never be observed — 'second' has already superseded this controller.
|
|
67
|
+
yield { id: 'f2', type: 'text', text: 'first-2' }
|
|
68
|
+
} else {
|
|
69
|
+
yield { id: 's1', type: 'text', text: 'second-1' }
|
|
70
|
+
}
|
|
71
|
+
},
|
|
72
|
+
}
|
|
73
|
+
|
|
74
|
+
const { result } = renderHook(() => useAgentStream({ transport }))
|
|
75
|
+
|
|
76
|
+
act(() => {
|
|
77
|
+
void result.current.send('first')
|
|
78
|
+
})
|
|
79
|
+
await waitFor(() => {
|
|
80
|
+
expect(result.current.parts).toEqual([{ id: 'f1', type: 'text', text: 'first-1' }])
|
|
81
|
+
})
|
|
82
|
+
|
|
83
|
+
act(() => {
|
|
84
|
+
void result.current.send('second')
|
|
85
|
+
})
|
|
86
|
+
await waitFor(() => {
|
|
87
|
+
expect(result.current.parts).toEqual([{ id: 's1', type: 'text', text: 'second-1' }])
|
|
88
|
+
})
|
|
89
|
+
expect(result.current.status).toBe('done')
|
|
90
|
+
|
|
91
|
+
gateFirst.resolve(undefined)
|
|
92
|
+
await waitFor(() => {
|
|
93
|
+
expect(result.current.status).toBe('done')
|
|
94
|
+
})
|
|
95
|
+
expect(result.current.parts).toEqual([{ id: 's1', type: 'text', text: 'second-1' }])
|
|
96
|
+
})
|
|
97
|
+
|
|
98
|
+
test('F1 regression: id-less drafts of different types within one send() do not destroy each other', async () => {
|
|
99
|
+
const transport: AgentTransport<AgentPart, string> = {
|
|
100
|
+
async *stream() {
|
|
101
|
+
yield { type: 'text', text: 'Hi' }
|
|
102
|
+
yield {
|
|
103
|
+
type: 'tool',
|
|
104
|
+
toolCallId: 'c1',
|
|
105
|
+
toolName: 'search',
|
|
106
|
+
state: 'input-available',
|
|
107
|
+
input: { q: 'x' },
|
|
108
|
+
}
|
|
109
|
+
yield { type: 'text', text: 'Bye' }
|
|
110
|
+
},
|
|
111
|
+
}
|
|
112
|
+
|
|
113
|
+
const { result } = renderHook(() => useAgentStream({ transport }))
|
|
114
|
+
|
|
115
|
+
await act(async () => {
|
|
116
|
+
await result.current.send('hi')
|
|
117
|
+
})
|
|
118
|
+
|
|
119
|
+
// Pre-fix: mergePart matched all three drafts on `undefined === undefined`, so text→tool→text
|
|
120
|
+
// collapsed to a single (wrong-typed) entry instead of three. withPartIds stamping a distinct
|
|
121
|
+
// id per draft is what keeps them apart.
|
|
122
|
+
expect(result.current.parts).toHaveLength(3)
|
|
123
|
+
expect(result.current.parts.map((part) => part.type)).toEqual(['text', 'tool', 'text'])
|
|
124
|
+
const ids = result.current.parts.map((part) => (part as { id: string }).id)
|
|
125
|
+
expect(new Set(ids).size).toBe(3)
|
|
126
|
+
})
|
|
127
|
+
|
|
128
|
+
test('a thrown (non-abort) error sets status "error" and captures the error', async () => {
|
|
129
|
+
const boom = new Error('boom')
|
|
130
|
+
const transport: AgentTransport<AgentPart, string> = {
|
|
131
|
+
async *stream() {
|
|
132
|
+
throw boom
|
|
133
|
+
// eslint-disable-next-line no-unreachable
|
|
134
|
+
yield { type: 'text', text: 'unreachable' }
|
|
135
|
+
},
|
|
136
|
+
}
|
|
137
|
+
|
|
138
|
+
const { result } = renderHook(() => useAgentStream({ transport }))
|
|
139
|
+
|
|
140
|
+
await act(async () => {
|
|
141
|
+
await result.current.send('hi')
|
|
142
|
+
})
|
|
143
|
+
|
|
144
|
+
expect(result.current.status).toBe('error')
|
|
145
|
+
expect(result.current.error).toBe(boom)
|
|
146
|
+
})
|
|
147
|
+
|
|
148
|
+
test('an AbortError thrown by the transport is ignored — it never overwrites status with "error"', async () => {
|
|
149
|
+
const gate = deferred<void>()
|
|
150
|
+
const transport: AgentTransport<AgentPart, string> = {
|
|
151
|
+
async *stream(_input, signal) {
|
|
152
|
+
yield { id: 'p1', type: 'text', text: 'a' }
|
|
153
|
+
await gate.promise
|
|
154
|
+
if (signal?.aborted) throw new DOMException('The operation was aborted.', 'AbortError')
|
|
155
|
+
yield { id: 'p2', type: 'text', text: 'b' }
|
|
156
|
+
},
|
|
157
|
+
}
|
|
158
|
+
|
|
159
|
+
const { result } = renderHook(() => useAgentStream({ transport }))
|
|
160
|
+
|
|
161
|
+
act(() => {
|
|
162
|
+
void result.current.send('hi')
|
|
163
|
+
})
|
|
164
|
+
await waitFor(() => {
|
|
165
|
+
expect(result.current.parts).toEqual([{ id: 'p1', type: 'text', text: 'a' }])
|
|
166
|
+
})
|
|
167
|
+
|
|
168
|
+
// stop() aborts the signal AND sets 'done' synchronously.
|
|
169
|
+
act(() => {
|
|
170
|
+
result.current.stop()
|
|
171
|
+
})
|
|
172
|
+
expect(result.current.status).toBe('done')
|
|
173
|
+
|
|
174
|
+
// The transport now throws AbortError (asynchronously, after 'done' is already set) — this
|
|
175
|
+
// must be swallowed by the catch's `err.name === 'AbortError'` guard, never flip to 'error'.
|
|
176
|
+
gate.resolve(undefined)
|
|
177
|
+
await waitFor(() => {
|
|
178
|
+
expect(result.current.status).toBe('done')
|
|
179
|
+
})
|
|
180
|
+
expect(result.current.error).toBeUndefined()
|
|
181
|
+
})
|
|
182
|
+
|
|
183
|
+
test('unmount aborts the in-flight stream', async () => {
|
|
184
|
+
let observedAbortedOnResume = false
|
|
185
|
+
const gate = deferred<void>()
|
|
186
|
+
const transport: AgentTransport<AgentPart, string> = {
|
|
187
|
+
async *stream(_input, signal) {
|
|
188
|
+
yield { id: 'p1', type: 'text', text: 'a' }
|
|
189
|
+
await gate.promise
|
|
190
|
+
observedAbortedOnResume = signal?.aborted ?? false
|
|
191
|
+
},
|
|
192
|
+
}
|
|
193
|
+
|
|
194
|
+
const { result, unmount } = renderHook(() => useAgentStream({ transport }))
|
|
195
|
+
|
|
196
|
+
act(() => {
|
|
197
|
+
void result.current.send('hi')
|
|
198
|
+
})
|
|
199
|
+
await waitFor(() => {
|
|
200
|
+
expect(result.current.parts).toEqual([{ id: 'p1', type: 'text', text: 'a' }])
|
|
201
|
+
})
|
|
202
|
+
|
|
203
|
+
unmount()
|
|
204
|
+
|
|
205
|
+
gate.resolve(undefined)
|
|
206
|
+
// Let the generator's resumed step run and observe the signal.
|
|
207
|
+
await new Promise((resolveTick) => setTimeout(resolveTick, 0))
|
|
208
|
+
expect(observedAbortedOnResume).toBe(true)
|
|
209
|
+
})
|
|
210
|
+
|
|
211
|
+
test('StrictMode double-invoke of a "send on mount" consumer effect: the surviving stream is the only one reflected in final state', async () => {
|
|
212
|
+
// useAgentStream itself never calls transport.stream() from an effect — only send() does, and
|
|
213
|
+
// send() is consumer-invoked. The realistic StrictMode hazard is therefore a consumer's own
|
|
214
|
+
// `useEffect(() => { void send(x) }, [])` "send the first turn on mount" pattern, which
|
|
215
|
+
// StrictMode's dev-only double-invoke runs twice against the SAME fiber. Verified empirically
|
|
216
|
+
// (reported alongside this suite): transport.stream() IS called twice in that scenario — the
|
|
217
|
+
// first pass's controller is aborted (both by useAgentStream's own unmount-cleanup effect
|
|
218
|
+
// during the simulated unmount, and redundantly by send()'s own
|
|
219
|
+
// `controllerRef.current?.abort()` at the top of the second call) — so exactly ONE stream's
|
|
220
|
+
// output is ever reflected in the hook's observable state, even though the transport function
|
|
221
|
+
// itself was invoked twice. That is the invariant this test pins, not a literal single
|
|
222
|
+
// `transport.stream()` call count.
|
|
223
|
+
let streamCalls = 0
|
|
224
|
+
let capturedParts: AgentPart[] = []
|
|
225
|
+
let capturedStatus = ''
|
|
226
|
+
|
|
227
|
+
const transport: AgentTransport<AgentPart, string> = {
|
|
228
|
+
async *stream() {
|
|
229
|
+
streamCalls++
|
|
230
|
+
yield { id: `call-${streamCalls}`, type: 'text', text: `call-${streamCalls}` }
|
|
231
|
+
},
|
|
232
|
+
}
|
|
233
|
+
|
|
234
|
+
function Consumer(): null {
|
|
235
|
+
const { send, parts, status } = useAgentStream({ transport })
|
|
236
|
+
capturedParts = parts
|
|
237
|
+
capturedStatus = status
|
|
238
|
+
useEffect(() => {
|
|
239
|
+
void send('initial')
|
|
240
|
+
// eslint-disable-next-line react-hooks/exhaustive-deps
|
|
241
|
+
}, [])
|
|
242
|
+
return null
|
|
243
|
+
}
|
|
244
|
+
|
|
245
|
+
await act(async () => {
|
|
246
|
+
render(
|
|
247
|
+
<StrictMode>
|
|
248
|
+
<Consumer />
|
|
249
|
+
</StrictMode>,
|
|
250
|
+
)
|
|
251
|
+
})
|
|
252
|
+
|
|
253
|
+
await waitFor(() => {
|
|
254
|
+
expect(capturedStatus).toBe('done')
|
|
255
|
+
})
|
|
256
|
+
|
|
257
|
+
expect(streamCalls).toBe(2)
|
|
258
|
+
// Only the SECOND (surviving) call's part made it into final state — the first is discarded.
|
|
259
|
+
expect(capturedParts).toEqual([{ id: 'call-2', type: 'text', text: 'call-2' }])
|
|
260
|
+
})
|
|
261
|
+
})
|
|
@@ -27,7 +27,10 @@
|
|
|
27
27
|
* }
|
|
28
28
|
*/
|
|
29
29
|
import { useCallback, useEffect, useRef, useState } from 'react'
|
|
30
|
+
import { withPartIds } from './id'
|
|
30
31
|
import { isStartPart } from './parts'
|
|
32
|
+
import { mergePart } from './merge'
|
|
33
|
+
import type { PartLike } from './merge'
|
|
31
34
|
import type { AgentPart } from './parts'
|
|
32
35
|
import type { AgentTransport } from './transport'
|
|
33
36
|
|
|
@@ -67,7 +70,7 @@ export type UseAgentStreamReturn<TPart, TInput> = {
|
|
|
67
70
|
* // parts accumulates as the stream arrives
|
|
68
71
|
* // status: 'idle' → 'streaming' → 'done' (or 'error')
|
|
69
72
|
*/
|
|
70
|
-
export function useAgentStream<TPart = AgentPart, TInput = string>({
|
|
73
|
+
export function useAgentStream<TPart extends PartLike = AgentPart, TInput = string>({
|
|
71
74
|
transport,
|
|
72
75
|
}: {
|
|
73
76
|
transport: AgentTransport<TPart, TInput>
|
|
@@ -100,15 +103,22 @@ export function useAgentStream<TPart = AgentPart, TInput = string>({
|
|
|
100
103
|
setError(undefined)
|
|
101
104
|
setStatus('streaming')
|
|
102
105
|
|
|
106
|
+
// Per-send namespace: this hook has no thread/session id to key off, and each send() call
|
|
107
|
+
// fully resets `parts` anyway, so a fresh id per call is enough to keep two id-less drafts
|
|
108
|
+
// ARRIVING WITHIN THE SAME SEND from colliding on `undefined === undefined` in mergePart (the
|
|
109
|
+
// F1 bug — text→tool→text destroying each other). Not a replay mechanism — this hook has no
|
|
110
|
+
// resume() path — see withPartIds' own doc for why it can't be one anyway.
|
|
111
|
+
const runId = crypto.randomUUID()
|
|
112
|
+
|
|
103
113
|
try {
|
|
104
|
-
for await (const part of transport.stream(input, controller.signal)) {
|
|
114
|
+
for await (const part of withPartIds(runId, transport.stream(input, controller.signal))) {
|
|
105
115
|
// Guard: if a newer send() has superseded this stream, stop updating state.
|
|
106
116
|
if (controllerRef.current !== controller) return
|
|
107
117
|
if (controller.signal.aborted) break
|
|
108
118
|
// StartPart is a no-op signal (run id + resume token), not renderable content — this
|
|
109
119
|
// hook has no persistence layer to resume across, so just skip it.
|
|
110
120
|
if (isStartPart(part)) continue
|
|
111
|
-
setParts((prev) =>
|
|
121
|
+
setParts((prev) => mergePart(prev, part))
|
|
112
122
|
}
|
|
113
123
|
// Only mark done if this stream is still the current one and wasn't aborted.
|
|
114
124
|
if (controllerRef.current === controller && !controller.signal.aborted) setStatus('done')
|
|
@@ -0,0 +1,133 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* useAgentThreadRuns — foreign-part round trip (B2 convergence fix).
|
|
3
|
+
*
|
|
4
|
+
* The open part registry (./foreign) only serves its headline purpose — a transport streaming an
|
|
5
|
+
* app-specific part type (`data-toolProgress`, `data-chart`, …) reaching `ThreadTranscript` — if a
|
|
6
|
+
* ForeignPart can flow all the way through this hook's mergePart accumulator: transport →
|
|
7
|
+
* consumeAndFinalize → runs.get(id).parts → the persisted assistant ChatMessage. This file proves
|
|
8
|
+
* that path end to end with `useAgentThreadRuns<TranscriptPart>`, which was a tsc error before
|
|
9
|
+
* mergePart's constraint was widened from `AgentPart` to the structural `PartLike`.
|
|
10
|
+
*/
|
|
11
|
+
import { describe, expect, test } from 'bun:test'
|
|
12
|
+
import { act, renderHook, waitFor } from '@testing-library/react'
|
|
13
|
+
import { useAgentThreadRuns } from './use-agent-thread-runs'
|
|
14
|
+
import type { AgentThread, ThreadsStore } from './thread'
|
|
15
|
+
import type { AgentTransport } from './transport'
|
|
16
|
+
import type { TranscriptPart } from './foreign'
|
|
17
|
+
import type { AgentOutcome, OutcomeResolver } from './outcome'
|
|
18
|
+
|
|
19
|
+
// ── test-only ThreadsStore double, typed over TranscriptPart ─────────────────────────────────────
|
|
20
|
+
function createTestThreadsStore(): ThreadsStore<TranscriptPart> {
|
|
21
|
+
let threads: AgentThread<TranscriptPart>[] = []
|
|
22
|
+
let activeId: string | null = null
|
|
23
|
+
|
|
24
|
+
return {
|
|
25
|
+
get threads() {
|
|
26
|
+
return threads
|
|
27
|
+
},
|
|
28
|
+
get activeId() {
|
|
29
|
+
return activeId
|
|
30
|
+
},
|
|
31
|
+
select(id) {
|
|
32
|
+
activeId = id
|
|
33
|
+
},
|
|
34
|
+
create(createOpts) {
|
|
35
|
+
const id = crypto.randomUUID()
|
|
36
|
+
const now = Date.now()
|
|
37
|
+
const thread: AgentThread<TranscriptPart> = {
|
|
38
|
+
id,
|
|
39
|
+
messages: [],
|
|
40
|
+
outcome: null,
|
|
41
|
+
status: 'pending',
|
|
42
|
+
read: false,
|
|
43
|
+
createdAt: now,
|
|
44
|
+
updatedAt: now,
|
|
45
|
+
...(createOpts?.meta !== undefined ? { meta: createOpts.meta } : {}),
|
|
46
|
+
}
|
|
47
|
+
threads = [thread, ...threads]
|
|
48
|
+
return id
|
|
49
|
+
},
|
|
50
|
+
appendMessage(id, message) {
|
|
51
|
+
threads = threads.map((thread) =>
|
|
52
|
+
thread.id === id
|
|
53
|
+
? { ...thread, messages: [...thread.messages, message], updatedAt: Date.now() }
|
|
54
|
+
: thread,
|
|
55
|
+
)
|
|
56
|
+
},
|
|
57
|
+
setOutcome(id, outcome) {
|
|
58
|
+
threads = threads.map((thread) =>
|
|
59
|
+
thread.id === id ? { ...thread, outcome, updatedAt: Date.now() } : thread,
|
|
60
|
+
)
|
|
61
|
+
},
|
|
62
|
+
setStatus(id, status) {
|
|
63
|
+
threads = threads.map((thread) =>
|
|
64
|
+
thread.id === id ? { ...thread, status, updatedAt: Date.now() } : thread,
|
|
65
|
+
)
|
|
66
|
+
},
|
|
67
|
+
setResumeToken(id, token) {
|
|
68
|
+
threads = threads.map((thread) => {
|
|
69
|
+
if (thread.id !== id) return thread
|
|
70
|
+
const { resumeToken: _resumeToken, ...rest } = thread
|
|
71
|
+
return {
|
|
72
|
+
...rest,
|
|
73
|
+
...(token !== undefined ? { resumeToken: token } : {}),
|
|
74
|
+
updatedAt: Date.now(),
|
|
75
|
+
}
|
|
76
|
+
})
|
|
77
|
+
},
|
|
78
|
+
markRead(id) {
|
|
79
|
+
threads = threads.map((thread) => (thread.id === id ? { ...thread, read: true } : thread))
|
|
80
|
+
},
|
|
81
|
+
remove(id) {
|
|
82
|
+
threads = threads.filter((thread) => thread.id !== id)
|
|
83
|
+
if (activeId === id) activeId = null
|
|
84
|
+
},
|
|
85
|
+
clear() {
|
|
86
|
+
threads = []
|
|
87
|
+
activeId = null
|
|
88
|
+
},
|
|
89
|
+
}
|
|
90
|
+
}
|
|
91
|
+
|
|
92
|
+
const resolveOutcome: OutcomeResolver<TranscriptPart> = (): AgentOutcome => ({
|
|
93
|
+
title: 'title',
|
|
94
|
+
summary: 'summary',
|
|
95
|
+
status: 'done',
|
|
96
|
+
})
|
|
97
|
+
|
|
98
|
+
describe('useAgentThreadRuns<TranscriptPart> — foreign part round trip', () => {
|
|
99
|
+
test('a foreign part survives accumulation and a replay replaces rather than duplicates', async () => {
|
|
100
|
+
const store = createTestThreadsStore()
|
|
101
|
+
const threadId = store.create()
|
|
102
|
+
|
|
103
|
+
const transport: AgentTransport<TranscriptPart, string> = {
|
|
104
|
+
async *stream() {
|
|
105
|
+
yield { id: 'progress-1', type: 'data-toolProgress', message: 'searching' }
|
|
106
|
+
// Same id, second delta — must REPLACE the first entry, not duplicate it.
|
|
107
|
+
yield { id: 'progress-1', type: 'data-toolProgress', message: 'done' }
|
|
108
|
+
yield { id: 'text-1', type: 'text', text: 'Found it.' }
|
|
109
|
+
},
|
|
110
|
+
}
|
|
111
|
+
|
|
112
|
+
const { result } = renderHook(() =>
|
|
113
|
+
useAgentThreadRuns<TranscriptPart>({ transport, store, resolveOutcome }),
|
|
114
|
+
)
|
|
115
|
+
|
|
116
|
+
act(() => {
|
|
117
|
+
result.current.start(threadId, 'go find it')
|
|
118
|
+
})
|
|
119
|
+
|
|
120
|
+
await waitFor(() => {
|
|
121
|
+
expect(store.threads.find((t) => t.id === threadId)?.status).toBe('done')
|
|
122
|
+
})
|
|
123
|
+
|
|
124
|
+
const assistantMessage = store.threads
|
|
125
|
+
.find((t) => t.id === threadId)
|
|
126
|
+
?.messages.find((m) => m.role === 'assistant')
|
|
127
|
+
|
|
128
|
+
expect(assistantMessage?.parts).toEqual([
|
|
129
|
+
{ id: 'progress-1', type: 'data-toolProgress', message: 'done' },
|
|
130
|
+
{ id: 'text-1', type: 'text', text: 'Found it.' },
|
|
131
|
+
])
|
|
132
|
+
})
|
|
133
|
+
})
|