agent-stream-ui 0.0.0-stage → 0.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/LICENSE +21 -0
- package/README.md +220 -2
- package/dist/adapters/openai.d.ts +42 -0
- package/dist/adapters/openai.d.ts.map +1 -0
- package/dist/agent-stream-ui.css +2 -0
- package/dist/agent-stream-ui.js +1418 -0
- package/dist/agent-stream-ui.js.map +1 -0
- package/dist/core/reducer.d.ts +33 -0
- package/dist/core/reducer.d.ts.map +1 -0
- package/dist/core/scheduler.d.ts +15 -0
- package/dist/core/scheduler.d.ts.map +1 -0
- package/dist/core/store.d.ts +29 -0
- package/dist/core/store.d.ts.map +1 -0
- package/dist/core/transport.d.ts +57 -0
- package/dist/core/transport.d.ts.map +1 -0
- package/dist/index.d.ts +38 -0
- package/dist/index.d.ts.map +1 -0
- package/dist/markdown/blocks.d.ts +31 -0
- package/dist/markdown/blocks.d.ts.map +1 -0
- package/dist/markdown/inline.d.ts +13 -0
- package/dist/markdown/inline.d.ts.map +1 -0
- package/dist/markdown/render.d.ts +18 -0
- package/dist/markdown/render.d.ts.map +1 -0
- package/dist/react/agent-chat.d.ts +14 -0
- package/dist/react/agent-chat.d.ts.map +1 -0
- package/dist/react/composer.d.ts +11 -0
- package/dist/react/composer.d.ts.map +1 -0
- package/dist/react/icons.d.ts +12 -0
- package/dist/react/icons.d.ts.map +1 -0
- package/dist/react/markdown-stream.d.ts +14 -0
- package/dist/react/markdown-stream.d.ts.map +1 -0
- package/dist/react/message-body.d.ts +14 -0
- package/dist/react/message-body.d.ts.map +1 -0
- package/dist/react/message-list.d.ts +8 -0
- package/dist/react/message-list.d.ts.map +1 -0
- package/dist/react/tool-call-card.d.ts +13 -0
- package/dist/react/tool-call-card.d.ts.map +1 -0
- package/dist/react/use-agent-stream.d.ts +11 -0
- package/dist/react/use-agent-stream.d.ts.map +1 -0
- package/dist/react/use-stick-to-bottom.d.ts +14 -0
- package/dist/react/use-stick-to-bottom.d.ts.map +1 -0
- package/dist/sse/client.d.ts +60 -0
- package/dist/sse/client.d.ts.map +1 -0
- package/dist/sse/frame.d.ts +42 -0
- package/dist/sse/frame.d.ts.map +1 -0
- package/dist/types.d.ts +119 -0
- package/dist/types.d.ts.map +1 -0
- package/docs/design-notes.md +145 -0
- package/package.json +84 -4
- package/src/lib/adapters/openai.ts +112 -0
- package/src/lib/core/reducer.ts +417 -0
- package/src/lib/core/scheduler.ts +40 -0
- package/src/lib/core/store.ts +214 -0
- package/src/lib/core/transport.ts +197 -0
- package/src/lib/index.ts +102 -0
- package/src/lib/markdown/blocks.ts +201 -0
- package/src/lib/markdown/inline.tsx +87 -0
- package/src/lib/markdown/render.tsx +149 -0
- package/src/lib/react/agent-chat.tsx +121 -0
- package/src/lib/react/composer.tsx +105 -0
- package/src/lib/react/icons.tsx +83 -0
- package/src/lib/react/markdown-stream.tsx +37 -0
- package/src/lib/react/message-body.tsx +66 -0
- package/src/lib/react/message-list.tsx +109 -0
- package/src/lib/react/tool-call-card.tsx +117 -0
- package/src/lib/react/use-agent-stream.ts +14 -0
- package/src/lib/react/use-stick-to-bottom.ts +60 -0
- package/src/lib/sse/client.ts +263 -0
- package/src/lib/sse/frame.ts +116 -0
- package/src/lib/styles.css +790 -0
- package/src/lib/types.ts +130 -0
|
@@ -0,0 +1,109 @@
|
|
|
1
|
+
import { useMemo } from 'react'
|
|
2
|
+
import type { ConversationSnapshot } from '../types'
|
|
3
|
+
import { ErrorNote, MessageBody } from './message-body'
|
|
4
|
+
import { useStickToBottom } from './use-stick-to-bottom'
|
|
5
|
+
import { ArrowDownIcon, RetryIcon } from './icons'
|
|
6
|
+
|
|
7
|
+
export interface MessageListProps {
|
|
8
|
+
snapshot: ConversationSnapshot
|
|
9
|
+
onRetry?: () => void
|
|
10
|
+
emptyState?: React.ReactNode
|
|
11
|
+
}
|
|
12
|
+
|
|
13
|
+
export function MessageList({ snapshot, onRetry, emptyState }: MessageListProps) {
|
|
14
|
+
const { messages, live } = snapshot
|
|
15
|
+
|
|
16
|
+
// 内容签名:只有真正影响布局的东西变化时才触发贴底滚动
|
|
17
|
+
const signature = useMemo(() => {
|
|
18
|
+
const liveLength =
|
|
19
|
+
live?.parts.reduce((total, part) => (part.kind === 'text' ? total + part.text.length : total), 0) ??
|
|
20
|
+
0
|
|
21
|
+
return `${messages.length}:${liveLength}:${live?.status ?? 'none'}`
|
|
22
|
+
}, [messages.length, live])
|
|
23
|
+
|
|
24
|
+
const { ref, pinned, scrollToBottom } = useStickToBottom<HTMLDivElement>(signature)
|
|
25
|
+
|
|
26
|
+
if (messages.length === 0 && !live) {
|
|
27
|
+
return <div className="asui-empty">{emptyState}</div>
|
|
28
|
+
}
|
|
29
|
+
|
|
30
|
+
return (
|
|
31
|
+
<div className="asui-list" ref={ref} role="log" aria-live="polite">
|
|
32
|
+
<div className="asui-list-inner">
|
|
33
|
+
{messages.map((message) => (
|
|
34
|
+
<article
|
|
35
|
+
key={message.id}
|
|
36
|
+
className={`asui-msg asui-msg--${message.role}`}
|
|
37
|
+
data-testid={`message-${message.role}`}
|
|
38
|
+
>
|
|
39
|
+
{message.role === 'assistant' && (
|
|
40
|
+
<>
|
|
41
|
+
<MessageBody
|
|
42
|
+
parts={message.parts}
|
|
43
|
+
toolCalls={message.toolCalls}
|
|
44
|
+
streaming={false}
|
|
45
|
+
role="assistant"
|
|
46
|
+
/>
|
|
47
|
+
{message.error && (
|
|
48
|
+
<div className="asui-error-wrap">
|
|
49
|
+
<ErrorNote message={message.error.message} stage={message.error.stage} />
|
|
50
|
+
{onRetry && (
|
|
51
|
+
<button type="button" className="asui-inline-retry" onClick={onRetry}>
|
|
52
|
+
<RetryIcon /> 重试本轮
|
|
53
|
+
</button>
|
|
54
|
+
)}
|
|
55
|
+
</div>
|
|
56
|
+
)}
|
|
57
|
+
</>
|
|
58
|
+
)}
|
|
59
|
+
{message.role === 'user' && (
|
|
60
|
+
<p className="asui-user-text">
|
|
61
|
+
{message.parts
|
|
62
|
+
.filter((part): part is { kind: 'text'; text: string } => part.kind === 'text')
|
|
63
|
+
.map((part) => part.text)
|
|
64
|
+
.join('\n')}
|
|
65
|
+
</p>
|
|
66
|
+
)}
|
|
67
|
+
</article>
|
|
68
|
+
))}
|
|
69
|
+
|
|
70
|
+
{live && (
|
|
71
|
+
<article className="asui-msg asui-msg--assistant" data-testid="message-live">
|
|
72
|
+
<MessageBody
|
|
73
|
+
parts={live.parts}
|
|
74
|
+
toolCalls={live.toolCalls}
|
|
75
|
+
streaming={live.status === 'running' && !live.interrupted}
|
|
76
|
+
role="assistant"
|
|
77
|
+
/>
|
|
78
|
+
{live.interrupted && live.status === 'running' && (
|
|
79
|
+
<p className="asui-interrupted" data-testid="interrupted-hint">
|
|
80
|
+
连接中断,正在续传…
|
|
81
|
+
</p>
|
|
82
|
+
)}
|
|
83
|
+
{live.error && (
|
|
84
|
+
<div className="asui-error-wrap">
|
|
85
|
+
<ErrorNote message={live.error.message} stage={live.error.stage} />
|
|
86
|
+
{onRetry && (
|
|
87
|
+
<button type="button" className="asui-inline-retry" onClick={onRetry}>
|
|
88
|
+
<RetryIcon /> 重试本轮
|
|
89
|
+
</button>
|
|
90
|
+
)}
|
|
91
|
+
</div>
|
|
92
|
+
)}
|
|
93
|
+
</article>
|
|
94
|
+
)}
|
|
95
|
+
</div>
|
|
96
|
+
|
|
97
|
+
{!pinned && (
|
|
98
|
+
<button
|
|
99
|
+
type="button"
|
|
100
|
+
className="asui-jump-bottom"
|
|
101
|
+
onClick={scrollToBottom}
|
|
102
|
+
aria-label="回到底部"
|
|
103
|
+
>
|
|
104
|
+
<ArrowDownIcon />
|
|
105
|
+
</button>
|
|
106
|
+
)}
|
|
107
|
+
</div>
|
|
108
|
+
)
|
|
109
|
+
}
|
|
@@ -0,0 +1,117 @@
|
|
|
1
|
+
import { useState } from 'react'
|
|
2
|
+
import type { ToolCallState } from '../types'
|
|
3
|
+
import { repairPartialJson } from '../core/reducer'
|
|
4
|
+
import { CheckIcon, AlertIcon, ToolIcon } from './icons'
|
|
5
|
+
|
|
6
|
+
export interface ToolCallCardProps {
|
|
7
|
+
tool: ToolCallState
|
|
8
|
+
}
|
|
9
|
+
|
|
10
|
+
const MAX_VALUE_CHARS = 160
|
|
11
|
+
|
|
12
|
+
function formatValue(value: unknown): string {
|
|
13
|
+
if (typeof value === 'string') {
|
|
14
|
+
return value.length > MAX_VALUE_CHARS ? `${value.slice(0, MAX_VALUE_CHARS)}…` : value
|
|
15
|
+
}
|
|
16
|
+
if (typeof value === 'number' || typeof value === 'boolean' || value === null) {
|
|
17
|
+
return String(value)
|
|
18
|
+
}
|
|
19
|
+
try {
|
|
20
|
+
const text = JSON.stringify(value)
|
|
21
|
+
return text.length > MAX_VALUE_CHARS ? `${text.slice(0, MAX_VALUE_CHARS)}…` : text
|
|
22
|
+
} catch {
|
|
23
|
+
return '[unserializable]'
|
|
24
|
+
}
|
|
25
|
+
}
|
|
26
|
+
|
|
27
|
+
function statusLabel(tool: ToolCallState): string {
|
|
28
|
+
if (tool.status === 'running') return '调用中'
|
|
29
|
+
if (tool.status === 'ok') return '完成'
|
|
30
|
+
return '失败'
|
|
31
|
+
}
|
|
32
|
+
|
|
33
|
+
function durationLabel(tool: ToolCallState): string | null {
|
|
34
|
+
if (tool.durationMs === undefined) return null
|
|
35
|
+
if (tool.durationMs < 1000) return `${Math.max(1, Math.round(tool.durationMs))}ms`
|
|
36
|
+
return `${(tool.durationMs / 1000).toFixed(1)}s`
|
|
37
|
+
}
|
|
38
|
+
|
|
39
|
+
/**
|
|
40
|
+
* 工具调用卡。
|
|
41
|
+
*
|
|
42
|
+
* 三态:入参还在流式生成(可能是不完整 JSON)、成功、失败。
|
|
43
|
+
* 入参不完整时**不做激进补全**——把原文摆出来,比给用户看一个猜出来的
|
|
44
|
+
* 半截参数诚实得多。
|
|
45
|
+
*/
|
|
46
|
+
export function ToolCallCard({ tool }: ToolCallCardProps) {
|
|
47
|
+
const [expanded, setExpanded] = useState(tool.status === 'error')
|
|
48
|
+
|
|
49
|
+
const parsed = tool.args.trim() === '' ? null : repairPartialJson(tool.args)
|
|
50
|
+
const rows =
|
|
51
|
+
parsed && typeof parsed.value === 'object' && parsed.value !== null
|
|
52
|
+
? Object.entries(parsed.value as Record<string, unknown>)
|
|
53
|
+
: null
|
|
54
|
+
|
|
55
|
+
const duration = durationLabel(tool)
|
|
56
|
+
|
|
57
|
+
return (
|
|
58
|
+
<section
|
|
59
|
+
className={`asui-tool asui-tool--${tool.status}`}
|
|
60
|
+
data-testid="tool-call-card"
|
|
61
|
+
data-status={tool.status}
|
|
62
|
+
>
|
|
63
|
+
<button
|
|
64
|
+
type="button"
|
|
65
|
+
className="asui-tool-head"
|
|
66
|
+
onClick={() => setExpanded((value) => !value)}
|
|
67
|
+
aria-expanded={expanded}
|
|
68
|
+
>
|
|
69
|
+
<span className="asui-tool-icon">
|
|
70
|
+
{tool.status === 'ok' ? (
|
|
71
|
+
<CheckIcon />
|
|
72
|
+
) : tool.status === 'error' ? (
|
|
73
|
+
<AlertIcon />
|
|
74
|
+
) : (
|
|
75
|
+
<ToolIcon />
|
|
76
|
+
)}
|
|
77
|
+
</span>
|
|
78
|
+
<span className="asui-tool-name">{tool.name}</span>
|
|
79
|
+
<span className="asui-tool-status">{statusLabel(tool)}</span>
|
|
80
|
+
{duration && <span className="asui-tool-duration">{duration}</span>}
|
|
81
|
+
<span className={`asui-tool-chevron${expanded ? ' is-open' : ''}`} aria-hidden="true">
|
|
82
|
+
›
|
|
83
|
+
</span>
|
|
84
|
+
</button>
|
|
85
|
+
|
|
86
|
+
{expanded && (
|
|
87
|
+
<div className="asui-tool-body">
|
|
88
|
+
{rows && rows.length > 0 ? (
|
|
89
|
+
<dl className="asui-tool-args">
|
|
90
|
+
{rows.map(([key, value]) => (
|
|
91
|
+
<div className="asui-tool-arg" key={key}>
|
|
92
|
+
<dt>{key}</dt>
|
|
93
|
+
<dd>{formatValue(value)}</dd>
|
|
94
|
+
</div>
|
|
95
|
+
))}
|
|
96
|
+
</dl>
|
|
97
|
+
) : (
|
|
98
|
+
<pre className="asui-tool-raw">{tool.args || '(无参数)'}</pre>
|
|
99
|
+
)}
|
|
100
|
+
|
|
101
|
+
{!tool.argsComplete && tool.status === 'running' && (
|
|
102
|
+
<p className="asui-tool-hint">
|
|
103
|
+
参数生成中…
|
|
104
|
+
{parsed && !parsed.complete ? '(当前为不完整 JSON,已按可解析部分展示)' : ''}
|
|
105
|
+
</p>
|
|
106
|
+
)}
|
|
107
|
+
|
|
108
|
+
{tool.preview && (
|
|
109
|
+
<pre className="asui-tool-preview" data-testid="tool-preview">
|
|
110
|
+
{tool.preview}
|
|
111
|
+
</pre>
|
|
112
|
+
)}
|
|
113
|
+
</div>
|
|
114
|
+
)}
|
|
115
|
+
</section>
|
|
116
|
+
)
|
|
117
|
+
}
|
|
@@ -0,0 +1,14 @@
|
|
|
1
|
+
import { useSyncExternalStore } from 'react'
|
|
2
|
+
import type { AgentStreamStore } from '../core/store'
|
|
3
|
+
import type { ConversationSnapshot } from '../types'
|
|
4
|
+
|
|
5
|
+
/**
|
|
6
|
+
* 订阅会话快照。
|
|
7
|
+
*
|
|
8
|
+
* `useSyncExternalStore` 在这里不是炫技:它保证并发渲染下不会读到撕裂的状态
|
|
9
|
+
* (tearing)——流式更新是典型的高频外部源,用 useState + useEffect 很容易
|
|
10
|
+
* 读到半新半旧的快照。
|
|
11
|
+
*/
|
|
12
|
+
export function useAgentStream(store: AgentStreamStore): ConversationSnapshot {
|
|
13
|
+
return useSyncExternalStore(store.subscribe, store.getSnapshot, store.getSnapshot)
|
|
14
|
+
}
|
|
@@ -0,0 +1,60 @@
|
|
|
1
|
+
import { useCallback, useEffect, useLayoutEffect, useRef, useState } from 'react'
|
|
2
|
+
|
|
3
|
+
const STICK_THRESHOLD_PX = 48
|
|
4
|
+
|
|
5
|
+
/**
|
|
6
|
+
* 贴底滚动。
|
|
7
|
+
*
|
|
8
|
+
* 规则:只有用户本来就在底部时才自动滚;一旦上滑就"锁住",新内容只提示不打扰。
|
|
9
|
+
* 这是 AI 对话界面里最容易做错、也最影响体感的一个细节。
|
|
10
|
+
*
|
|
11
|
+
* @param signal 内容变化信号(一般是消息长度),变化后若处于贴底状态则滚到底。
|
|
12
|
+
*/
|
|
13
|
+
export function useStickToBottom<T extends HTMLElement>(signal: unknown) {
|
|
14
|
+
const ref = useRef<T | null>(null)
|
|
15
|
+
const pinnedRef = useRef(true)
|
|
16
|
+
const [pinned, setPinned] = useState(true)
|
|
17
|
+
|
|
18
|
+
useLayoutEffect(() => {
|
|
19
|
+
const element = ref.current
|
|
20
|
+
if (!element) return
|
|
21
|
+
if (pinnedRef.current) element.scrollTop = element.scrollHeight
|
|
22
|
+
}, [signal])
|
|
23
|
+
|
|
24
|
+
useEffect(() => {
|
|
25
|
+
const element = ref.current
|
|
26
|
+
if (!element) return
|
|
27
|
+
|
|
28
|
+
const onScroll = () => {
|
|
29
|
+
const gap = element.scrollHeight - element.scrollTop - element.clientHeight
|
|
30
|
+
const next = gap < STICK_THRESHOLD_PX
|
|
31
|
+
pinnedRef.current = next
|
|
32
|
+
setPinned(next)
|
|
33
|
+
}
|
|
34
|
+
|
|
35
|
+
element.addEventListener('scroll', onScroll, { passive: true })
|
|
36
|
+
|
|
37
|
+
const observer =
|
|
38
|
+
typeof ResizeObserver === 'function'
|
|
39
|
+
? new ResizeObserver(() => {
|
|
40
|
+
if (pinnedRef.current) element.scrollTop = element.scrollHeight
|
|
41
|
+
})
|
|
42
|
+
: null
|
|
43
|
+
observer?.observe(element)
|
|
44
|
+
|
|
45
|
+
return () => {
|
|
46
|
+
element.removeEventListener('scroll', onScroll)
|
|
47
|
+
observer?.disconnect()
|
|
48
|
+
}
|
|
49
|
+
}, [])
|
|
50
|
+
|
|
51
|
+
const scrollToBottom = useCallback(() => {
|
|
52
|
+
const element = ref.current
|
|
53
|
+
if (!element) return
|
|
54
|
+
element.scrollTop = element.scrollHeight
|
|
55
|
+
pinnedRef.current = true
|
|
56
|
+
setPinned(true)
|
|
57
|
+
}, [])
|
|
58
|
+
|
|
59
|
+
return { ref, pinned, scrollToBottom }
|
|
60
|
+
}
|
|
@@ -0,0 +1,263 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* SSE 客户端:`POST + text/event-stream`,带退避重连、`Last-Event-ID` 续传与游标去重。
|
|
3
|
+
*
|
|
4
|
+
* 三条不写在明面上的约定,都是踩过坑才有的:
|
|
5
|
+
* 1. **只对"可能自愈"的失败重连**:5xx / 408 / 429 / 网络中断。4xx(会话不存在、
|
|
6
|
+
* 未登录、已裁决)重连只会空转,直接停在 error。
|
|
7
|
+
* 2. **重连必须带游标**:服务端按 `Last-Event-ID` 从之后重放,客户端再按 id 去重,
|
|
8
|
+
* 这样"断在半个 token 中间"也能接到正确位置。
|
|
9
|
+
* 3. **停止是本地语义**:abort 之后不再重连,也不抛错——用户主动停的不是失败。
|
|
10
|
+
*/
|
|
11
|
+
|
|
12
|
+
import type { SseStatus, SseStatusInfo } from '../types'
|
|
13
|
+
import { isNewerEventId, parseSseChunk } from './frame'
|
|
14
|
+
import type { SseFrame } from './frame'
|
|
15
|
+
|
|
16
|
+
export const DEFAULT_BACKOFF_BASE_MS = 500
|
|
17
|
+
export const DEFAULT_BACKOFF_FACTOR = 2
|
|
18
|
+
export const DEFAULT_BACKOFF_MAX_MS = 7_000
|
|
19
|
+
export const DEFAULT_MAX_ATTEMPTS = 8
|
|
20
|
+
|
|
21
|
+
export interface SseClientOptions {
|
|
22
|
+
url: string
|
|
23
|
+
method?: 'POST' | 'GET'
|
|
24
|
+
headers?: Record<string, string>
|
|
25
|
+
body?: unknown
|
|
26
|
+
/** 断点续传游标;null 表示从头开始。 */
|
|
27
|
+
lastEventId?: string | null
|
|
28
|
+
backoffBaseMs?: number
|
|
29
|
+
backoffFactor?: number
|
|
30
|
+
backoffMaxMs?: number
|
|
31
|
+
/** 连续失败上限,超过就停在 error,避免无限重连。 */
|
|
32
|
+
maxAttempts?: number
|
|
33
|
+
/**
|
|
34
|
+
* 空闲超时:超过这么久没收到任何帧就主动断开重连。
|
|
35
|
+
*
|
|
36
|
+
* 半开连接(NAT 超时、LB 静默丢包、代理挂住上游)在 TCP 层看起来是"还活着",
|
|
37
|
+
* 读操作永远不会返回。没有这个看门狗,界面会永远停在"生成中"。
|
|
38
|
+
* 默认关闭(0):不同业务的首帧延迟差异太大,交给使用方决定。
|
|
39
|
+
*/
|
|
40
|
+
idleTimeoutMs?: number
|
|
41
|
+
/** 覆盖默认的可重试判定。 */
|
|
42
|
+
isRetriable?: (ctx: RetryContext) => boolean
|
|
43
|
+
/** 注入 fetch(测试/非浏览器环境用)。 */
|
|
44
|
+
fetch?: typeof fetch
|
|
45
|
+
onStatus?: (status: SseStatus, info?: SseStatusInfo) => void
|
|
46
|
+
onEvent: (frame: SseFrame) => void
|
|
47
|
+
/** 上一次处理过的游标,用于跨重连去重。 */
|
|
48
|
+
getCursor?: () => string | null
|
|
49
|
+
}
|
|
50
|
+
|
|
51
|
+
export interface RetryContext {
|
|
52
|
+
/** HTTP 状态码;网络错误时为 0。 */
|
|
53
|
+
status: number
|
|
54
|
+
attempt: number
|
|
55
|
+
}
|
|
56
|
+
|
|
57
|
+
export interface SseClient {
|
|
58
|
+
/** 主动停止:abort 在途请求并禁止后续重连。 */
|
|
59
|
+
close: () => void
|
|
60
|
+
/** 当前状态快照(同步读,不触发回调)。 */
|
|
61
|
+
readonly status: SseStatus
|
|
62
|
+
}
|
|
63
|
+
|
|
64
|
+
function sleep(ms: number, signal: AbortSignal): Promise<void> {
|
|
65
|
+
return new Promise((resolve) => {
|
|
66
|
+
if (signal.aborted) return resolve()
|
|
67
|
+
const timer = setTimeout(resolve, ms)
|
|
68
|
+
signal.addEventListener(
|
|
69
|
+
'abort',
|
|
70
|
+
() => {
|
|
71
|
+
clearTimeout(timer)
|
|
72
|
+
resolve()
|
|
73
|
+
},
|
|
74
|
+
{ once: true },
|
|
75
|
+
)
|
|
76
|
+
})
|
|
77
|
+
}
|
|
78
|
+
|
|
79
|
+
/**
|
|
80
|
+
* 带空闲看门狗的读。超时后取消 reader 并抛错,交给外层重连。
|
|
81
|
+
* 没有它,被代理挂住的半开连接会让 UI 永远停在"生成中"。
|
|
82
|
+
*/
|
|
83
|
+
async function readWithIdleTimeout(
|
|
84
|
+
reader: ReadableStreamDefaultReader<Uint8Array>,
|
|
85
|
+
idleTimeoutMs: number,
|
|
86
|
+
): Promise<ReadableStreamReadResult<Uint8Array>> {
|
|
87
|
+
if (idleTimeoutMs <= 0) return reader.read()
|
|
88
|
+
|
|
89
|
+
let timer: ReturnType<typeof setTimeout> | undefined
|
|
90
|
+
const timeout = new Promise<never>((_, reject) => {
|
|
91
|
+
timer = setTimeout(() => reject(new Error('idle timeout')), idleTimeoutMs)
|
|
92
|
+
})
|
|
93
|
+
|
|
94
|
+
try {
|
|
95
|
+
return await Promise.race([reader.read(), timeout])
|
|
96
|
+
} catch (error) {
|
|
97
|
+
void reader.cancel().catch(() => {})
|
|
98
|
+
throw error
|
|
99
|
+
} finally {
|
|
100
|
+
if (timer !== undefined) clearTimeout(timer)
|
|
101
|
+
}
|
|
102
|
+
}
|
|
103
|
+
|
|
104
|
+
export function shouldRetryStatus(status: number): boolean {
|
|
105
|
+
if (status === 0) return true // 网络层错误
|
|
106
|
+
if (status === 408 || status === 429) return true
|
|
107
|
+
return status >= 500
|
|
108
|
+
}
|
|
109
|
+
|
|
110
|
+
export function computeBackoff(
|
|
111
|
+
attempt: number,
|
|
112
|
+
base = DEFAULT_BACKOFF_BASE_MS,
|
|
113
|
+
factor = DEFAULT_BACKOFF_FACTOR,
|
|
114
|
+
max = DEFAULT_BACKOFF_MAX_MS,
|
|
115
|
+
): number {
|
|
116
|
+
return Math.min(base * factor ** Math.max(0, attempt - 1), max)
|
|
117
|
+
}
|
|
118
|
+
|
|
119
|
+
export function createSseClient(options: SseClientOptions): SseClient {
|
|
120
|
+
const {
|
|
121
|
+
url,
|
|
122
|
+
method = 'POST',
|
|
123
|
+
headers = {},
|
|
124
|
+
body,
|
|
125
|
+
backoffBaseMs = DEFAULT_BACKOFF_BASE_MS,
|
|
126
|
+
backoffFactor = DEFAULT_BACKOFF_FACTOR,
|
|
127
|
+
backoffMaxMs = DEFAULT_BACKOFF_MAX_MS,
|
|
128
|
+
maxAttempts = DEFAULT_MAX_ATTEMPTS,
|
|
129
|
+
idleTimeoutMs = 0,
|
|
130
|
+
isRetriable = (ctx: RetryContext) => shouldRetryStatus(ctx.status),
|
|
131
|
+
fetch: fetchImpl = globalThis.fetch,
|
|
132
|
+
onStatus = () => {},
|
|
133
|
+
onEvent,
|
|
134
|
+
getCursor = () => null,
|
|
135
|
+
} = options
|
|
136
|
+
|
|
137
|
+
const abort = new AbortController()
|
|
138
|
+
let status: SseStatus = 'idle'
|
|
139
|
+
let attempt = 0
|
|
140
|
+
let lastEventId = options.lastEventId ?? null
|
|
141
|
+
|
|
142
|
+
const setStatus = (next: SseStatus, info?: SseStatusInfo) => {
|
|
143
|
+
status = next
|
|
144
|
+
onStatus(next, info)
|
|
145
|
+
}
|
|
146
|
+
|
|
147
|
+
const consume = async (response: Response) => {
|
|
148
|
+
if (!response.body) throw new Error('response has no body')
|
|
149
|
+
|
|
150
|
+
const reader = response.body.getReader()
|
|
151
|
+
const decoder = new TextDecoder()
|
|
152
|
+
let buffer = ''
|
|
153
|
+
|
|
154
|
+
for (;;) {
|
|
155
|
+
const { value, done } = await readWithIdleTimeout(reader, idleTimeoutMs)
|
|
156
|
+
if (done) break
|
|
157
|
+
|
|
158
|
+
buffer += decoder.decode(value, { stream: true })
|
|
159
|
+
const { frames, rest } = parseSseChunk(buffer)
|
|
160
|
+
buffer = rest
|
|
161
|
+
|
|
162
|
+
for (const frame of frames) {
|
|
163
|
+
if (frame.id !== null) {
|
|
164
|
+
// 跨重连去重:服务端可能重放边界帧
|
|
165
|
+
if (!isNewerEventId(frame.id, getCursor() ?? lastEventId)) continue
|
|
166
|
+
lastEventId = frame.id
|
|
167
|
+
}
|
|
168
|
+
onEvent(frame)
|
|
169
|
+
}
|
|
170
|
+
}
|
|
171
|
+
|
|
172
|
+
// 流被服务端正常关闭(reader done):收拾残余并用非流式解码收尾
|
|
173
|
+
buffer += decoder.decode()
|
|
174
|
+
if (buffer.trim() !== '') {
|
|
175
|
+
const { frames } = parseSseChunk(`${buffer}\n\n`)
|
|
176
|
+
for (const frame of frames) {
|
|
177
|
+
if (frame.id !== null && !isNewerEventId(frame.id, getCursor() ?? lastEventId)) continue
|
|
178
|
+
if (frame.id !== null) lastEventId = frame.id
|
|
179
|
+
onEvent(frame)
|
|
180
|
+
}
|
|
181
|
+
}
|
|
182
|
+
}
|
|
183
|
+
|
|
184
|
+
const run = async () => {
|
|
185
|
+
while (!abort.signal.aborted) {
|
|
186
|
+
setStatus(attempt === 0 ? 'connecting' : 'reconnecting', {
|
|
187
|
+
attempt,
|
|
188
|
+
delayMs: 0,
|
|
189
|
+
})
|
|
190
|
+
|
|
191
|
+
try {
|
|
192
|
+
const requestHeaders: Record<string, string> = {
|
|
193
|
+
accept: 'text/event-stream',
|
|
194
|
+
...headers,
|
|
195
|
+
}
|
|
196
|
+
if (body !== undefined && method !== 'GET') {
|
|
197
|
+
requestHeaders['content-type'] = 'application/json'
|
|
198
|
+
}
|
|
199
|
+
if (lastEventId !== null) {
|
|
200
|
+
requestHeaders['last-event-id'] = lastEventId
|
|
201
|
+
}
|
|
202
|
+
|
|
203
|
+
const response = await fetchImpl(url, {
|
|
204
|
+
method,
|
|
205
|
+
headers: requestHeaders,
|
|
206
|
+
body: body === undefined || method === 'GET' ? undefined : JSON.stringify(body),
|
|
207
|
+
signal: abort.signal,
|
|
208
|
+
cache: 'no-store',
|
|
209
|
+
})
|
|
210
|
+
|
|
211
|
+
if (abort.signal.aborted) return
|
|
212
|
+
|
|
213
|
+
if (!response.ok) {
|
|
214
|
+
const reason = `HTTP ${response.status}`
|
|
215
|
+
const retriable = isRetriable({ status: response.status, attempt })
|
|
216
|
+
if (!retriable) {
|
|
217
|
+
setStatus('error', { attempt, delayMs: 0, reason })
|
|
218
|
+
return
|
|
219
|
+
}
|
|
220
|
+
throw new Error(reason)
|
|
221
|
+
}
|
|
222
|
+
|
|
223
|
+
attempt = 0
|
|
224
|
+
setStatus('open', { attempt: 0, delayMs: 0 })
|
|
225
|
+
await consume(response)
|
|
226
|
+
|
|
227
|
+
if (abort.signal.aborted) return
|
|
228
|
+
|
|
229
|
+
// 干净的 EOF 也是"没等到 turn.end 就断了":不能当成正常结束。
|
|
230
|
+
// 真正的结束由使用方在看到 turn.end 后调用 close() 表示。
|
|
231
|
+
throw new Error('stream ended before turn.end')
|
|
232
|
+
} catch (error) {
|
|
233
|
+
if (abort.signal.aborted) return
|
|
234
|
+
|
|
235
|
+
attempt += 1
|
|
236
|
+
const delayMs = computeBackoff(attempt, backoffBaseMs, backoffFactor, backoffMaxMs)
|
|
237
|
+
const reason = error instanceof Error ? error.message : String(error)
|
|
238
|
+
const retriable =
|
|
239
|
+
isRetriable({ status: 0, attempt }) && attempt <= maxAttempts
|
|
240
|
+
if (!retriable) {
|
|
241
|
+
setStatus('error', { attempt, delayMs: 0, reason })
|
|
242
|
+
return
|
|
243
|
+
}
|
|
244
|
+
|
|
245
|
+
setStatus('reconnecting', { attempt, delayMs, reason })
|
|
246
|
+
await sleep(delayMs, abort.signal)
|
|
247
|
+
}
|
|
248
|
+
}
|
|
249
|
+
}
|
|
250
|
+
|
|
251
|
+
void run()
|
|
252
|
+
|
|
253
|
+
return {
|
|
254
|
+
close() {
|
|
255
|
+
if (abort.signal.aborted) return
|
|
256
|
+
abort.abort()
|
|
257
|
+
setStatus('stopped', { attempt, delayMs: 0, reason: 'aborted-by-user' })
|
|
258
|
+
},
|
|
259
|
+
get status() {
|
|
260
|
+
return status
|
|
261
|
+
},
|
|
262
|
+
}
|
|
263
|
+
}
|
|
@@ -0,0 +1,116 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* SSE 分帧:纯函数,不碰 fetch、不碰 DOM。
|
|
3
|
+
*
|
|
4
|
+
* 为什么自己写:EventSource 不支持 POST、不能带自定义 header、断线重连策略
|
|
5
|
+
* 由浏览器决定(你没法控制退避、也没法只对 5xx 重试)。真正的 Agent 流式
|
|
6
|
+
* 接口几乎都是 `POST + text/event-stream`。
|
|
7
|
+
*/
|
|
8
|
+
|
|
9
|
+
export interface SseFrame {
|
|
10
|
+
/** 事件游标(服务端 outbox 自增 id),用于断点续传与去重。 */
|
|
11
|
+
id: string | null
|
|
12
|
+
event: string
|
|
13
|
+
data: string
|
|
14
|
+
/** 服务端建议的重连间隔;本实现不采纳,退避策略由客户端掌握。 */
|
|
15
|
+
retry: number | null
|
|
16
|
+
}
|
|
17
|
+
|
|
18
|
+
const FRAME_SEPARATOR = /\r?\n\r?\n/
|
|
19
|
+
|
|
20
|
+
/**
|
|
21
|
+
* 解析单帧(不含结尾空行)。
|
|
22
|
+
*
|
|
23
|
+
* 规范细节:一行可以是 `field`(无冒号)、`field:`(空值)、`field:value`,
|
|
24
|
+
* 值前的一个空格必须去掉;`:` 开头是注释(心跳),整帧没有 data 时不产生事件。
|
|
25
|
+
*/
|
|
26
|
+
export function parseSseFrame(raw: string): SseFrame | null {
|
|
27
|
+
if (raw.length === 0) return null
|
|
28
|
+
|
|
29
|
+
const lines = raw.split(/\r?\n/)
|
|
30
|
+
let id: string | null = null
|
|
31
|
+
let event = 'message'
|
|
32
|
+
let retry: number | null = null
|
|
33
|
+
const dataLines: string[] = []
|
|
34
|
+
|
|
35
|
+
for (const line of lines) {
|
|
36
|
+
if (line === '' || line.startsWith(':')) continue
|
|
37
|
+
|
|
38
|
+
const colon = line.indexOf(':')
|
|
39
|
+
const field = colon === -1 ? line : line.slice(0, colon)
|
|
40
|
+
let value = colon === -1 ? '' : line.slice(colon + 1)
|
|
41
|
+
if (value.startsWith(' ')) value = value.slice(1)
|
|
42
|
+
|
|
43
|
+
switch (field) {
|
|
44
|
+
case 'id':
|
|
45
|
+
id = value
|
|
46
|
+
break
|
|
47
|
+
case 'event':
|
|
48
|
+
event = value === '' ? 'message' : value
|
|
49
|
+
break
|
|
50
|
+
case 'data':
|
|
51
|
+
dataLines.push(value)
|
|
52
|
+
break
|
|
53
|
+
case 'retry': {
|
|
54
|
+
const parsed = Number(value)
|
|
55
|
+
if (Number.isFinite(parsed) && parsed > 0) retry = parsed
|
|
56
|
+
break
|
|
57
|
+
}
|
|
58
|
+
default:
|
|
59
|
+
// 未知字段按规范忽略,保证协议向前兼容
|
|
60
|
+
break
|
|
61
|
+
}
|
|
62
|
+
}
|
|
63
|
+
|
|
64
|
+
if (dataLines.length === 0) return null
|
|
65
|
+
|
|
66
|
+
return { id, event, data: dataLines.join('\n'), retry }
|
|
67
|
+
}
|
|
68
|
+
|
|
69
|
+
/**
|
|
70
|
+
* 从缓冲区里切出所有完整帧,返回剩余未闭合文本。
|
|
71
|
+
* 调用方负责把 `rest` 与下一次读到的 chunk 拼起来再解析。
|
|
72
|
+
*/
|
|
73
|
+
export function parseSseChunk(buffer: string): { frames: SseFrame[]; rest: string } {
|
|
74
|
+
const frames: SseFrame[] = []
|
|
75
|
+
let rest = buffer
|
|
76
|
+
|
|
77
|
+
for (;;) {
|
|
78
|
+
const match = FRAME_SEPARATOR.exec(rest)
|
|
79
|
+
if (!match) break
|
|
80
|
+
|
|
81
|
+
const raw = rest.slice(0, match.index)
|
|
82
|
+
rest = rest.slice(match.index + match[0].length)
|
|
83
|
+
|
|
84
|
+
const frame = parseSseFrame(raw)
|
|
85
|
+
if (frame) frames.push(frame)
|
|
86
|
+
}
|
|
87
|
+
|
|
88
|
+
return { frames, rest }
|
|
89
|
+
}
|
|
90
|
+
|
|
91
|
+
/** 序列化一帧(mock server 与测试用,保证和服务端输出同形)。 */
|
|
92
|
+
export function formatSseFrame(frame: {
|
|
93
|
+
id?: string | number | null
|
|
94
|
+
event?: string
|
|
95
|
+
data: string
|
|
96
|
+
}): string {
|
|
97
|
+
let out = ''
|
|
98
|
+
if (frame.id !== undefined && frame.id !== null) out += `id: ${frame.id}\n`
|
|
99
|
+
if (frame.event && frame.event !== 'message') out += `event: ${frame.event}\n`
|
|
100
|
+
for (const line of frame.data.split('\n')) out += `data: ${line}\n`
|
|
101
|
+
return `${out}\n`
|
|
102
|
+
}
|
|
103
|
+
|
|
104
|
+
/**
|
|
105
|
+
* 游标比较。服务端 id 是单调递增的整数游标,但协议本身不保证——
|
|
106
|
+
* 非数字 id 退化为"只要不相等就认为新"。
|
|
107
|
+
*/
|
|
108
|
+
export function isNewerEventId(next: string, current: string | null): boolean {
|
|
109
|
+
if (current === null) return true
|
|
110
|
+
|
|
111
|
+
const a = Number(next)
|
|
112
|
+
const b = Number(current)
|
|
113
|
+
if (Number.isFinite(a) && Number.isFinite(b)) return a > b
|
|
114
|
+
|
|
115
|
+
return next !== current
|
|
116
|
+
}
|