| 1 | import { PROVIDER_SEND_TURN_MAX_ATTACHMENTS } from "@t3tools/contracts"; |
| 2 | |
| 3 | export function remainingComposerAttachmentSlots( |
| 4 | attachmentCount: number, |
| 5 | pendingThreadImports: number, |
| 6 | ) { |
| 7 | return Math.max(0, PROVIDER_SEND_TURN_MAX_ATTACHMENTS - attachmentCount - pendingThreadImports); |
| 8 | } |
| 9 | |
| 10 | export async function importComposerThreadAttachment(input: { |
| 11 | readonly targetKey: string; |
| 12 | readonly pendingImports: Map<string, number>; |
| 13 | readonly countReservedAttachments: () => number; |
| 14 | readonly load: () => Promise<File>; |
| 15 | readonly isActive: () => boolean; |
| 16 | readonly attach: (file: File) => Promise<boolean>; |
| 17 | readonly onLimitReached: () => void; |
| 18 | }): Promise<void> { |
| 19 | if (input.countReservedAttachments() >= PROVIDER_SEND_TURN_MAX_ATTACHMENTS) { |
| 20 | input.onLimitReached(); |
| 21 | return; |
| 22 | } |
| 23 | input.pendingImports.set(input.targetKey, (input.pendingImports.get(input.targetKey) ?? 0) + 1); |
| 24 | let reserved = true; |
| 25 | const release = () => { |
| 26 | if (!reserved) return; |
| 27 | reserved = false; |
| 28 | const remaining = (input.pendingImports.get(input.targetKey) ?? 0) - 1; |
| 29 | if (remaining > 0) input.pendingImports.set(input.targetKey, remaining); |
| 30 | else input.pendingImports.delete(input.targetKey); |
| 31 | }; |
| 32 | try { |
| 33 | const file = await input.load(); |
| 34 | if (!input.isActive()) return; |
| 35 | release(); |
| 36 | await input.attach(file); |
| 37 | } finally { |
| 38 | release(); |
| 39 | } |
| 40 | } |