MCPcopy Index your code
hub / github.com/ChatLab/ChatLab / createSyncResultPoller

Function createSyncResultPoller

src/stores/syncResultPolling.ts:39–78  ·  view source on GitHub ↗
(options: SyncResultPollerOptions)

Source from the content-addressed store, hash-verified

37 * 不依赖短暂的 progress 记录,浏览器后台节流后恢复也能发现遗漏的完成事件。
38 */
39export function createSyncResultPoller(options: SyncResultPollerOptions): () => void {
40 const schedule = options.schedule ?? ((callback, intervalMs) => setInterval(callback, intervalMs))
41 const cancelSchedule = options.cancelSchedule ?? ((timer) => clearInterval(timer as ReturnType<typeof setInterval>))
42 let previousStates: Map<string, string> | null = null
43 let stopped = false
44 let polling = false
45
46 const poll = async () => {
47 if (stopped || polling) return
48 polling = true
49 try {
50 const sources = await options.loadDataSources()
51 if (stopped) return
52
53 const nextStates = buildSessionStateMap(sources)
54 if (previousStates) {
55 const completed = sources.some((source) =>
56 source.sessions.some((session) => {
57 const key = `${source.id}:${session.id}`
58 return session.lastStatus !== 'idle' && previousStates?.get(key) !== nextStates.get(key)
59 })
60 )
61 if (completed) await options.onResult()
62 }
63 previousStates = nextStates
64 } catch {
65 // 临时请求失败时保留旧基线,下次成功轮询仍可检测期间发生的同步结果。
66 } finally {
67 polling = false
68 }
69 }
70
71 void poll()
72 const timer = schedule(() => void poll(), options.intervalMs ?? 5000)
73
74 return () => {
75 stopped = true
76 cancelSchedule(timer)
77 }
78}

Callers 2

createWebTransportFunction · 0.90

Calls 1

pollFunction · 0.85

Tested by

no test coverage detected