Skip to content

The agent that grows with you

fix(desktop): budget group-chat preview downloads per connection

unsupportedpastels1f91da2a2770
diff --git a/apps/desktop/src/plugins/hermes-bots/canonical-group-history.tsx b/apps/desktop/src/plugins/hermes-bots/canonical-group-history.tsx
index 661faa49002..df11119f0d7 100644
--- a/apps/desktop/src/plugins/hermes-bots/canonical-group-history.tsx
+++ b/apps/desktop/src/plugins/hermes-bots/canonical-group-history.tsx
@@ -69,28 +69,31 @@ 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.
+// Automatic previews share a small download budget per connection, in request order; a file already
+// downloading is joined rather than requested again. Manual Download stays outside it. The budget is
+// per connection because a remote whose dial hangs holds its slots for good, and must not stall others.
type Preview = Awaited<ReturnType<typeof fetchCanonicalGroupAttachment>>
+interface PreviewQueue { slots: number; waiters: Array<() => void> }
const previewDownloads = new Map<string, Promise<Preview>>()
-const previewWaiters: Array<() => void> = []
-let previewSlots = 2
+const previewQueues = new Map<string, PreviewQueue>()
-function releasePreviewSlot() {
- const next = previewWaiters.shift()
+function releasePreviewSlot(queue: PreviewQueue) {
+ const next = queue.waiters.shift()
- if (next) {next()} else {previewSlots++}
+ if (next) {next()} else {queue.slots++}
}
-function queuePreview(key: string, fetch: () => Promise<Preview>, onPreview: (preview: Preview) => void) {
+function queuePreview(connectionId: string, key: string, fetch: () => Promise<Preview>, onPreview: (preview: Preview) => void) {
+ const queue = previewQueues.get(connectionId) ?? { slots: 2, waiters: [] }
+ previewQueues.set(connectionId, queue)
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() })
+ if (download) {releasePreviewSlot(queue)} else {
+ download = fetch().finally(() => { previewDownloads.delete(key); releasePreviewSlot(queue) })
previewDownloads.set(key, download)
}
@@ -99,14 +102,14 @@ function queuePreview(key: string, fetch: () => Promise<Preview>, onPreview: (pr
const running = previewDownloads.get(key)
- if (running) {deliver(running)} else if (previewSlots > 0) {previewSlots--; run()} else {previewWaiters.push(run)}
+ if (running) {deliver(running)} else if (queue.slots > 0) {queue.slots--; run()} else {queue.waiters.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)
+ const at = queue.waiters.indexOf(run)
- if (at >= 0) {previewWaiters.splice(at, 1)}
+ if (at >= 0) {queue.waiters.splice(at, 1)}
}
}
@@ -120,7 +123,8 @@ function ImagePreview({ binding, eventId, attachment, disabled }: {
const { connectionId, profile, roomId } = binding
const previewable = !!attachmentId && size !== undefined && size <= IMAGE_PREVIEW_MAX_BYTES
- // History loads the whole room: fetch only near the viewport. Leaving it before the bytes arrive releases the queued slot.
+ // History loads the whole room: fetch only near the viewport. Leaving before its turn gives up the queued place;
+ // a started download runs to completion and is shared if the preview returns.
useEffect(() => {
const el = box.current
@@ -137,7 +141,7 @@ function ImagePreview({ binding, eventId, attachment, disabled }: {
const key = JSON.stringify([connectionId, profile, roomId, eventId, attachmentId])
// A failed preview leaves the Download button as the way to the file.
- const cancel = queuePreview(key, () => fetchCanonicalGroupAttachment({ connectionId, profile, roomId }, eventId, attachmentId), ({ bytes, mime }) => {
+ const cancel = queuePreview(connectionId, key, () => fetchCanonicalGroupAttachment({ connectionId, profile, roomId }, eventId, attachmentId), ({ bytes, mime }) => {
url = URL.createObjectURL(new Blob([bytes], { type: mime }))
setSrc(url)
})
diff --git a/apps/desktop/src/plugins/hermes-bots/canonical-group-workspace.test.tsx b/apps/desktop/src/plugins/hermes-bots/canonical-group-workspace.test.tsx
index 96922a2ba51..58a7dc99bc6 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
@@ -370,18 +370,19 @@ it('keeps automatic preview downloads bounded and never requests one file twice
// 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.
+ expect(downloads()).toEqual(['img-0', 'img-1'])
+ // Hidden and shown again while img-0 is pending, with a slot free: the same file is not requested twice.
+ await act(async () => { held[1]() })
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.
+ expect(downloads()).toEqual(['img-0', 'img-1'])
+ // The shared request still paints the re-shown preview, and the previews that scrolled away are never requested.
await act(async () => { held.splice(0).forEach(release => release()) })
await screen.findByRole('img', { name: 'shot-0.png' })
+ expect(downloads()).toEqual(['img-0', 'img-1'])
})
it('starts waiting previews in order as downloads succeed or fail, never more than two at once', async () => {
@@ -421,6 +422,28 @@ it('starts waiting previews in order as downloads succeed or fail, never more th
expect(peak).toBe(2)
})
+it('lets a connection whose downloads never settle stall only its own previews', async () => {
+ Object.defineProperty(URL, 'createObjectURL', { configurable: true, value: vi.fn(() => 'blob:preview') })
+ Object.defineProperty(URL, 'revokeObjectURL', { configurable: true, value: vi.fn() })
+ const image = (id: string) => ({ attachment_id: id, kind: 'image', name: `${id}.png`, mime: 'image/png', size: 1 })
+ const message = (id: string, seq: number) => ({ seq, room_id: id[0], event_id: `e-${id}`, kind: 'message.member', payload: { attachments: [image(id)] } })
+ request.mockImplementation(async (route, method, params) => route.connectionId === 'hung'
+ ? roomReads([], [message('a0', 1), message('a1', 2)])(method) ?? (method === 'groups.attachment.download' ? new Promise(() => {}) : {})
+ : roomReads([], [message('b0', 1)])(method) ?? (method === 'groups.attachment.download' ? { ...image(params.attachment_id), data_base64: 'QQ==' } : {}))
+ const observers: IntersectionObserverCallback[] = []
+ vi.stubGlobal('IntersectionObserver', class { constructor(callback: IntersectionObserverCallback) { observers.push(callback) } observe() {} disconnect() {} })
+ const seen = (callback: IntersectionObserverCallback) => act(() => callback([{ isIntersecting: true }] as IntersectionObserverEntry[], {} as IntersectionObserver))
+ const stuck = render(<CanonicalGroupWorkspace binding={{ connectionId: 'hung', profile: 'team', roomId: 'a' }} />)
+ await waitFor(() => expect(observers).toHaveLength(2))
+ observers.forEach(seen)
+ stuck.unmount()
+ render(<CanonicalGroupWorkspace binding={{ connectionId: 'local', profile: 'team', roomId: 'b' }} />)
+ await waitFor(() => expect(observers).toHaveLength(3))
+ seen(observers[2])
+ await screen.findByRole('img', { name: 'b0.png' })
+ expect(request.mock.calls.filter(c => c[1] === 'groups.attachment.download').map(c => c[2].attachment_id)).toEqual(['a0', 'a1', 'b0'])
+})
+
it('uploads a file pasted while another upload runs once that one finishes, instead of dropping it', async () => {
let release!: () => void
const receipt = (params: Record<string, string>) => ({ attachment_id: `att-${params.name}`, kind: params.kind, name: params.name, mime: params.mime, size: 1 })