Repository navigation
Expand file tree
/
Copy pathSessionContext.tsx
More file actions
284 lines (252 loc) · 9.97 KB
/
Copy pathSessionContext.tsx
File metadata and controls
284 lines (252 loc) · 9.97 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
import { useState, useCallback, useEffect, useRef, useMemo, type ReactNode } from 'react'
import {
getSessions,
getSession,
createSession as apiCreateSession,
deleteSession as apiDeleteSession,
subscribeToEvents,
type ApiSession,
type SessionListParams,
} from '../api'
import { affectsBoundServer } from '../store/serverChangeScope'
import { serverStore } from '../store/serverStore'
import { pinnedSessionsStore } from '../store/pinnedSessionsStore'
import { useDirectory } from './useDirectory'
import { sessionErrorHandler, normalizeToForwardSlash, isSameDirectory, autoDetectPathStyle } from '../utils'
import { clearSessionRuntimeState } from '../utils/sessionLifecycle'
import { SessionContext, type SessionContextValue } from './SessionContext.shared'
export function SessionProvider({ children }: { children: ReactNode }) {
const { currentDirectory } = useDirectory()
const [sessions, setSessions] = useState<ApiSession[]>([])
const [isLoading, setIsLoading] = useState(true)
const [isLoadingMore, setIsLoadingMore] = useState(false)
const [hasMore, setHasMore] = useState(true)
const [search, setSearch] = useState('')
const requestIdRef = useRef(0)
const searchTimerRef = useRef<number | null>(null)
const currentDirectoryRef = useRef(currentDirectory)
const searchRef = useRef(search)
const isLoadingMoreRef = useRef(false) // 防止并发 loadMore
const isFetchingRef = useRef(false) // 防止 onReconnected 密集触发时重复请求
const queuedReconnectRefreshRef = useRef(false)
const retryTimerRef = useRef<number | null>(null)
const fetchSessionsRef = useRef<
(params?: SessionListParams & { append?: boolean; retryAttempt?: number }) => Promise<void>
>(() => Promise.resolve())
const currentLimitRef = useRef(30) // 当前 limit,loadMore 时递增
// 保持 ref 同步
useEffect(() => {
currentDirectoryRef.current = currentDirectory
}, [currentDirectory])
useEffect(() => {
searchRef.current = search
}, [search])
// 核心获取逻辑
// 注意:directory 传给 getSessions 时使用正斜杠格式
// http 层的 fetchWithBothSlashesAndMerge 会处理两种斜杠格式的兼容
const fetchSessions = useCallback(
async (params: SessionListParams & { append?: boolean; retryAttempt?: number } = {}) => {
const { append = false, retryAttempt = 0, ...queryParams } = params
const requestId = ++requestIdRef.current
isFetchingRef.current = true
if (append) {
setIsLoadingMore(true)
} else {
setIsLoading(true)
}
try {
// 使用正斜杠格式传给 API(http 层会处理兼容)
const targetDir = normalizeToForwardSlash(currentDirectory) || undefined
const data = await getSessions({
// v2 没有 roots 开关:根会话用 parentID: null 表达
parentID: null,
limit: currentLimitRef.current,
directory: targetDir,
search: search || undefined,
...queryParams,
})
if (requestId !== requestIdRef.current) return
// 自动检测路径风格(从后端返回的 directory 字段)
if (data.length > 0 && data[0].location?.directory) {
autoDetectPathStyle(data[0].location?.directory)
}
if (append) {
// 去重:过滤掉已存在的 session
setSessions(prev => {
const existingIds = new Set(prev.map(s => s.id))
const newSessions = data.filter(s => !existingIds.has(s.id))
return [...prev, ...newSessions]
})
} else {
setSessions(data)
}
setHasMore(data.length >= currentLimitRef.current)
} catch (e) {
if (requestId === requestIdRef.current && !append) {
if (retryAttempt < 3) {
if (retryTimerRef.current) clearTimeout(retryTimerRef.current)
retryTimerRef.current = window.setTimeout(() => {
if (requestId !== requestIdRef.current) return
void fetchSessions({ ...queryParams, retryAttempt: retryAttempt + 1 })
}, [500, 1500, 3000][retryAttempt])
} else {
setSessions([])
setHasMore(false)
}
}
sessionErrorHandler('fetch sessions', e)
} finally {
if (requestId === requestIdRef.current) {
isFetchingRef.current = false
setIsLoading(false)
setIsLoadingMore(false)
if (queuedReconnectRefreshRef.current) {
queuedReconnectRefreshRef.current = false
setSessions([])
void fetchSessionsRef.current({ search: searchRef.current || undefined })
}
}
}
},
[currentDirectory, search],
)
// 保持 fetchSessions ref 同步(用于 SSE onReconnected 回调)
fetchSessionsRef.current = fetchSessions
const matchesCurrentDirectory = useCallback((session: ApiSession) => {
return !currentDirectoryRef.current || isSameDirectory(currentDirectoryRef.current, session.location?.directory)
}, [])
// 监听 directory 和 search 变化
useEffect(() => {
if (searchTimerRef.current) clearTimeout(searchTimerRef.current)
// 切换目录或搜索时重置 limit
currentLimitRef.current = 30
searchTimerRef.current = window.setTimeout(
() => {
fetchSessions()
},
search ? 300 : 0,
)
return () => {
if (searchTimerRef.current) clearTimeout(searchTimerRef.current)
if (retryTimerRef.current) clearTimeout(retryTimerRef.current)
}
}, [fetchSessions, search, currentDirectory])
// 订阅 SSE 事件,实时更新 session 列表
useEffect(() => {
const unsubscribe = subscribeToEvents({
onSessionCreated: data => {
// 忽略子 session(有 parentID 的是子 agent 创建的)
if (data.parentID) return
// v2 的 session.created 负载是**创建记录**(以 sessionID 为键、带 slug/version),
// 不是 SessionInfo,因此回读一次拿到完整会话再入列表。
void getSession(data.sessionID, normalizeToForwardSlash(currentDirectory) || undefined, data.location?.directory)
.then(session => {
if (!session || !matchesCurrentDirectory(session)) return
// 搜索态下交给服务端重新给出结果,避免本地过滤和服务端逻辑不一致
if (searchRef.current) {
fetchSessionsRef.current()
return
}
setSessions(prev => {
if (prev.some(s => s.id === session.id)) return prev
return [session, ...prev]
})
})
.catch(() => {
// 回读失败时退回整表刷新,保证列表不落后
fetchSessionsRef.current()
})
},
onSessionRenamed: data => {
// v2 把 v1 的 session.updated 收敛成 session.renamed(只有标题变化)
setSessions(prev => {
const index = prev.findIndex(s => s.id === data.sessionID)
if (index === -1) return prev
const next = [...prev]
next[index] = { ...next[index], title: data.title }
return next
})
},
onSessionDeleted: data => {
// v2 的 session.deleted 负载是 { sessionID }(v1 直接是字符串)
clearSessionRuntimeState(data.sessionID)
setSessions(prev => prev.filter(s => s.id !== data.sessionID))
},
onReconnected: reason => {
if (reason === 'server-switch') return
if (isFetchingRef.current) {
queuedReconnectRefreshRef.current = true
return
}
setSessions([])
fetchSessionsRef.current()
},
})
return unsubscribe
}, [matchesCurrentDirectory])
useEffect(() => {
return serverStore.onServerChange((serverId, reason) => {
// 会话列表跟随 active server:非 active 服务器端点变化(WSL 重启)不影响本列表,
// 避免无关事件触发「清空 → 重拉」的可见闪烁;只有 active 数据源真的变了才重置
if (!affectsBoundServer(undefined, serverId, reason, serverStore.getActiveServerId())) return
currentLimitRef.current = 30
setSessions([])
void fetchSessionsRef.current()
})
}, [])
// Actions
const refresh = useCallback(() => fetchSessions(), [fetchSessions])
const loadMore = useCallback(async () => {
// 使用 ref 检查,防止并发请求
if (isLoadingMoreRef.current || !hasMore || sessions.length === 0) return
isLoadingMoreRef.current = true
try {
// 跟官方 webui 一样,递增 limit 重新请求整个列表
currentLimitRef.current += 15
setIsLoadingMore(true)
await fetchSessions()
} finally {
isLoadingMoreRef.current = false
setIsLoadingMore(false)
}
}, [hasMore, sessions, fetchSessions])
const createSession = useCallback(
async (title?: string) => {
// 使用正斜杠格式传给后端
const targetDir = normalizeToForwardSlash(currentDirectory) || undefined
const newSession = await apiCreateSession({
title,
directory: targetDir,
})
return newSession
},
[currentDirectory],
)
const deleteSession = useCallback(
async (id: string) => {
const targetDir = normalizeToForwardSlash(currentDirectory) || undefined
await apiDeleteSession(id, targetDir)
pinnedSessionsStore.unpin(id)
clearSessionRuntimeState(id)
setSessions(prev => prev.filter(s => s.id !== id))
},
[currentDirectory],
)
// 稳定化 Provider value,避免每次渲染创建新对象导致子组件不必要重渲染
const value = useMemo<SessionContextValue>(
() => ({
sessions,
isLoading,
isLoadingMore,
hasMore,
search,
setSearch,
refresh,
loadMore,
createSession,
deleteSession,
}),
[sessions, isLoading, isLoadingMore, hasMore, search, refresh, loadMore, createSession, deleteSession],
)
return <SessionContext.Provider value={value}>{children}</SessionContext.Provider>
}