| 127 | * zwanzig Zustandsketten aufmachen, aus denen jede die vorige ueberschreibt. |
| 128 | */ |
| 129 | export function useAgentStream(options: AgentStreamOptions): AgentStream { |
| 130 | const project = options.project ?? ''; |
| 131 | const fetchImpl = options.fetch; |
| 132 | const on = options.on; |
| 133 | |
| 134 | const stateRef = useRef<AgentsState>(emptyAgentsState()); |
| 135 | const [reading, setReading] = useState({ project, value: stateRef.current }); |
| 136 | const requests = useRef(0); |
| 137 | const drops = useRef(0); |
| 138 | const cursor = useRef(0); |
| 139 | const incomplete = useRef(false); |
| 140 | const generation = useRef<string | undefined>(undefined); |
| 141 | const previousProject = useRef(project); |
| 142 | const [source, setSource] = useState<{ project: string; value: AgentSourceStatus }>({ project, value: { |
| 143 | state: 'off', |
| 144 | origin: '', |
| 145 | requests: 0, |
| 146 | drops: 0, |
| 147 | hello: undefined, |
| 148 | error: '', |
| 149 | } }); |
| 150 | |
| 151 | const push = useCallback((event: AgentEvent, you: boolean) => { |
| 152 | if (previousProject.current !== project) return; |
| 153 | const next = withEvent(stateRef.current, event); |
| 154 | stateRef.current = you |
| 155 | ? { |
| 156 | ...next, |
| 157 | actors: next.actors.map((actor) => |
| 158 | (actor.id === event.agent ? { ...actor, you: true } : actor)), |
| 159 | } |
| 160 | : next; |
| 161 | setReading({ project, value: stateRef.current }); |
| 162 | }, [project]); |
| 163 | |
| 164 | useEffect(() => { |
| 165 | if (previousProject.current !== project) { |
| 166 | previousProject.current = project; |
| 167 | cursor.current = 0; |
| 168 | generation.current = undefined; |
| 169 | incomplete.current = false; |
| 170 | stateRef.current = emptyAgentsState(); |
| 171 | setReading({ project, value: stateRef.current }); |
| 172 | } |
| 173 | if (!on) { |
| 174 | setSource({ project, value: { |
| 175 | state: 'off', |
| 176 | origin: '', |
| 177 | requests: requests.current, |
| 178 | drops: drops.current, |
| 179 | hello: undefined, |
| 180 | error: '', |
| 181 | } }); |
| 182 | return; |
| 183 | } |
| 184 | const origin = typeof location === 'undefined' ? '' : location.origin; |
| 185 | const doFetch = fetchImpl ?? globalThis.fetch; |
| 186 | let stopped = false; |