The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
fix(desktop): cap group-chat preview downloads in flight
unsupportedpastels3221d411ac10
diff --git a/apps/desktop/src/plugins/hermes-bots/canonical-group-history.tsx b/apps/desktop/src/plugins/hermes-bots/canonical-group-history.tsxindex 2f38699bc9a..661faa49002 100644--- a/apps/desktop/src/plugins/hermes-bots/canonical-group-history.tsx+++ b/apps/desktop/src/plugins/hermes-bots/canonical-group-history.tsx@@ -69,6 +69,47 @@ function EventBody({ event, notice }: { event: CanonicalGroupEvent; notice?: str// Previews download the whole file over RPC; larger or unsized images keep only Download.const IMAGE_PREVIEW_MAX_BYTES = 5 * 1024 * 1024+// Automatic previews share one small download budget across the renderer, in request order;+// a file already downloading is joined rather than requested again. Manual Download stays outside it.+type Preview = Awaited<ReturnType<typeof fetchCanonicalGroupAttachment>>+const previewDownloads = new Map<string, Promise<Preview>>()+const previewWaiters: Array<() => void> = []+let previewSlots = 2++function releasePreviewSlot() {+ const next = previewWaiters.shift()++ if (next) {next()} else {previewSlots++}+}++function queuePreview(key: string, fetch: () => Promise<Preview>, onPreview: (preview: Preview) => void) {+ let cancelled = false+ const deliver = (download: Promise<Preview>) => void download.then(preview => { if (!cancelled) {onPreview(preview)} }, () => undefined)++ const run = () => {+ let download = previewDownloads.get(key)++ if (download) {releasePreviewSlot()} else {+ download = fetch().finally(() => { previewDownloads.delete(key); releasePreviewSlot() })+ previewDownloads.set(key, download)+ }++ deliver(download)+ }++ const running = previewDownloads.get(key)++ if (running) {deliver(running)} else if (previewSlots > 0) {previewSlots--; run()} else {previewWaiters.push(run)}++ // A preview that leaves before its turn gives up its place without sending a request.+ return () => {+ cancelled = true+ const at = previewWaiters.indexOf(run)++ if (at >= 0) {previewWaiters.splice(at, 1)}+ }+}+function ImagePreview({ binding, eventId, attachment, disabled }: {binding: CanonicalGroupBinding; eventId: string; attachment: CanonicalGroupAttachment; disabled: boolean}) {@@ -79,30 +120,30 @@ function ImagePreview({ binding, eventId, attachment, disabled }: {const { connectionId, profile, roomId } = bindingconst previewable = !!attachmentId && size !== undefined && size <= IMAGE_PREVIEW_MAX_BYTES- // History loads the whole room: fetch only near the viewport, which also bounds concurrent downloads.+ // History loads the whole room: fetch only near the viewport. Leaving it before the bytes arrive releases the queued slot.useEffect(() => {const el = box.current- if (near || disabled || !el) {return}- const observer = new IntersectionObserver(entries => { if (entries.some(entry => entry.isIntersecting)) {setNear(true)} }, { rootMargin: '200px' })+ if (src || disabled || !el) {return}+ const observer = new IntersectionObserver(entries => setNear(entries[entries.length - 1].isIntersecting), { rootMargin: '200px' })observer.observe(el)return () => observer.disconnect()- }, [near, disabled])+ }, [src, disabled])useEffect(() => {if (disabled || !near || !attachmentId || !previewable) {return}- let cancelled = falselet url = ''+ const key = JSON.stringify([connectionId, profile, roomId, eventId, attachmentId])+// A failed preview leaves the Download button as the way to the file.- void fetchCanonicalGroupAttachment({ connectionId, profile, roomId }, eventId, attachmentId).then(({ bytes, mime }) => {- if (cancelled) {return}+ const cancel = queuePreview(key, () => fetchCanonicalGroupAttachment({ connectionId, profile, roomId }, eventId, attachmentId), ({ bytes, mime }) => {url = URL.createObjectURL(new Blob([bytes], { type: mime }))setSrc(url)- }, () => undefined)+ })// Dropping `near` makes a re-shown room wait on the observer again, not refetch every preview seen so far at once.- return () => { cancelled = true; URL.revokeObjectURL(url); setSrc(''); setNear(false) }+ return () => { cancel(); URL.revokeObjectURL(url); setSrc(''); setNear(false) }}, [connectionId, profile, roomId, eventId, attachmentId, disabled, near, previewable])return previewable ? <div ref={box}>{src && <img alt={attachment.name} className="max-h-64 max-w-full rounded object-contain" src={src} />}</div> : nulldiff --git a/apps/desktop/src/plugins/hermes-bots/canonical-group-workspace.test.tsx b/apps/desktop/src/plugins/hermes-bots/canonical-group-workspace.test.tsxindex 4a70fb835e3..17c509ddb19 100644--- a/apps/desktop/src/plugins/hermes-bots/canonical-group-workspace.test.tsx+++ b/apps/desktop/src/plugins/hermes-bots/canonical-group-workspace.test.tsx@@ -349,6 +349,41 @@ it('re-gates previews on the observer after the room is hidden and shown, insteaawait waitFor(() => expect(downloads()).toBe(2))})+it('keeps automatic preview downloads bounded and never requests one file twice at once', async () => {+ Object.defineProperty(URL, 'createObjectURL', { configurable: true, value: vi.fn(() => 'blob:preview') })+ Object.defineProperty(URL, 'revokeObjectURL', { configurable: true, value: vi.fn() })+ const image = (n: number) => ({ attachment_id: `img-${n}`, kind: 'image', name: `shot-${n}.png`, mime: 'image/png', size: 4 * 1024 * 1024 })+ const events = Array.from({ length: 20 }, (_, n) => ({ seq: n + 1, room_id: 'bound', event_id: `e${n}`, kind: 'message.member', payload: { attachments: [image(n)] } }))+ const held: Array<() => void> = []+ request.mockImplementation(async (_route, method) => roomReads([], events)(method)+ ?? (method === 'groups.attachment.download' ? new Promise(resolve => { held.push(() => resolve({ ...image(0), data_base64: 'QQ==' })) }) : {}))+ const observers: IntersectionObserverCallback[] = []+ vi.stubGlobal('IntersectionObserver', class { constructor(callback: IntersectionObserverCallback) { observers.push(callback) } observe() {} disconnect() {} })++ const seen = (callback: IntersectionObserverCallback, isIntersecting: boolean) =>+ act(() => callback([{ isIntersecting }] as IntersectionObserverEntry[], {} as IntersectionObserver))++ const downloads = () => request.mock.calls.filter(c => c[1] === 'groups.attachment.download').map(c => c[2].attachment_id)+ const binding = { connectionId: 'remote', profile: 'team', roomId: 'bound' }+ const view = render(<CanonicalGroupWorkspace binding={binding} />)+ await waitFor(() => expect(observers).toHaveLength(20))++ // A fast scroll: every preview enters and leaves the viewport before any download finishes.+ for (const callback of [...observers]) { seen(callback, true); seen(callback, false) }+ expect(downloads().length).toBeGreaterThan(0)+ expect(downloads().length).toBeLessThanOrEqual(2)+ // Hidden and shown again while a download is pending: the same file is not requested twice.+ view.rerender(<CanonicalGroupWorkspace binding={binding} visible={false} />)+ view.rerender(<CanonicalGroupWorkspace binding={binding} />)+ await waitFor(() => expect(observers).toHaveLength(40))+ seen(observers[20], true)+ await act(async () => { await Promise.resolve() })+ expect(downloads().filter(id => id === 'img-0')).toHaveLength(1)+ // The shared request still paints the re-shown preview.+ await act(async () => { held.splice(0).forEach(release => release()) })+ await screen.findByRole('img', { name: 'shot-0.png' })+})+it('uploads a file pasted while another upload runs once that one finishes, instead of dropping it', async () => {let release!: () => voidconst receipt = (params: Record<string, string>) => ({ attachment_id: `att-${params.name}`, kind: params.kind, name: params.name, mime: params.mime, size: 1 })