The ultimate harness for coding agents and beyond. All your agents. All your machines. One command center. Start with code, then follow your curiosity and build across disciplines: CAD, circuits, robots, games and music.
TypeScript 3d-modelingagent-frameworkagent-harnessai-agentscadclaude-codecodexcoding-agentsdeveloper-toolsesp32game-developmentmcp-servermulti-agentopen-hardwareopencodeopenharnesspcbroboticsterminaltmux
Super Tab chat: paste screenshots and attach files (#1490)
0xken15003b8f9dd011
diff --git a/backend/integration/superTabs.test.ts b/backend/integration/superTabs.test.tsindex c39076e4f..33031fb5e 100644--- a/backend/integration/superTabs.test.ts+++ b/backend/integration/superTabs.test.ts@@ -3,12 +3,13 @@ import { execFile } from 'node:child_process'import { promisify } from 'node:util'import { join } from 'node:path'import { tmpdir } from 'node:os'-import { afterAll, beforeAll, describe, expect, it } from 'vitest'+import { afterAll, beforeAll, describe, expect, it, vi } from 'vitest'import { MongoMemoryReplSet } from 'mongodb-memory-server-core'import { PrismaClient } from '@prisma/client'import Fastify, { type FastifyInstance } from 'fastify'import type { AuthUser } from '../src/lib/ssoAuth.js'import { SuperTabStore } from '../src/superTabs/store.js'+import { MemoryAttachmentStore } from '../src/superTabs/attachments.js'import { superTabRoutes } from '../src/routes/superTabs.js'import { errorHandler } from '../src/middlewares/errorHandler.js'import type { Command } from '../src/superTabs/commands.js'@@ -1064,121 +1065,125 @@ it('allocates workgroup numbers transactionally and replays the same number afteexpect((await store.read(owner, tab)).state.conversations.map(c => c.number)).toEqual([undefined, 1, 2, 3])})-describe('images attached to Swarm messages', () => {- const PART = 256 * 1024- const png = (size: number) => {- const bytes = Buffer.alloc(size, 7)- Buffer.from([0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a, 0, 0, 0, 13, 0x49, 0x48, 0x44, 0x52, 0, 0, 0, 3, 0, 0, 0, 2]).copy(bytes)- return bytes- }- const http = (user: AuthUser, method: 'GET' | 'POST' | 'DELETE', url: string, payload?: object) =>- app.inject({ method, url, headers: { authorization: `Bearer ${user.sub}` }, ...(payload ? { payload } : {}) })- const upload = (user: AuthUser, tab: string, bytes: Buffer, name = 'screen.png') =>- http(user, 'POST', `/api/super-tabs/${tab}/attachments`, { name, size: bytes.length, data: bytes.subarray(0, PART).toString('base64') })- const send = (attachmentIds: string[], text = ''): Command =>- ({ type: 'message.send', conversationId: 'lead', text, replyTo: null, recipientIds: [], attachmentIds })-- it('uploads in parts, sends image-only messages, and lets only readers of the conversation see the bytes', async () => {- const { tab, lead } = await fixture()- await invite(tab)- const bytes = png(PART + 10)- const created = await upload(owner, tab, bytes)- expect(created.statusCode).toBe(200)- const image = created.json().data- expect(image).toMatchObject({ name: 'screen.png', mime: 'image/png', size: PART + 10, width: 3, height: 2, parts: 2, complete: false })- await expect(run(tab, send([image.id]))).rejects.toMatchObject({ code: 'ATTACHMENT_INCOMPLETE' })- const part = (data: Buffer, index = 1) => http(owner, 'POST', `/api/super-tabs/${tab}/attachments/${image.id}/parts/${index}`, { data: data.toString('base64') })- expect((await part(bytes.subarray(PART, PART + 5))).json().error.code).toBe('INVALID_ATTACHMENT')- expect((await part(bytes.subarray(PART), 2)).json().error.code).toBe('INVALID_ATTACHMENT')- // Unsent, the upload is its uploader's alone, to read or to send.- expect((await http(peer, 'GET', `/api/super-tabs/${tab}/attachments/${image.id}`)).statusCode).toBe(404)- expect((await http(peer, 'POST', `/api/super-tabs/${tab}/attachments/${image.id}/parts/1`, { data: bytes.subarray(PART).toString('base64') })).statusCode).toBe(404)- expect((await part(bytes.subarray(PART))).json().data).toEqual({ id: image.id, complete: true })- expect((await part(bytes.subarray(PART))).json().data).toEqual({ id: image.id, complete: true })- await expect(run(tab, send([image.id]), peer)).rejects.toMatchObject({ code: 'INVALID_ATTACHMENT' })-- const operationId = randomUUID()- const sent = await run(tab, send([image.id]), owner, undefined, operationId)- expect((await run(tab, send([image.id]), owner, undefined, operationId)).result).toEqual(sent.result)- await expect(run(tab, send([image.id], 'Again'))).rejects.toMatchObject({ code: 'INVALID_ATTACHMENT' })- const meta = { id: image.id, name: 'screen.png', mime: 'image/png', size: PART + 10, width: 3, height: 2, parts: 2 }- const [row] = (await store.messages(peer, tab, 'lead', { messageId: sent.result.messageId as string })).messages- expect(row).toMatchObject({ text: '[image]', attachments: [meta] })- expect(JSON.stringify(row)).not.toContain(bytes.subarray(0, 64).toString('base64'))-- // Sent, it is read with its conversation: a member, and the agent the message was delivered to.- const read = async (user: AuthUser, index: number, asAgentId?: string) => {- const response = await http(user, 'GET', `/api/super-tabs/${tab}/attachments/${image.id}/parts/${index}${asAgentId ? `?asAgentId=${asAgentId}` : ''}`)- return response.statusCode === 200 ? Buffer.from(response.json().data.data, 'base64') : response.statusCode+describe('Super Tab chat attachments', () => {+ const files = new MemoryAttachmentStore()+ let attaching: SuperTabStore+ let upload: FastifyInstance+ beforeAll(async () => {+ attaching = new SuperTabStore(db, Date.now, { store: files, prefix: 'super-tabs', publicBase: 'https://cdn.example.test' })+ upload = Fastify()+ upload.setErrorHandler(errorHandler)+ upload.addHook('onRequest', async (request, reply) => {+ const user = [owner, peer, host].find(u => `Bearer ${u.sub}` === request.headers.authorization)+ if (!user) return reply.code(401).send({ success: false })+ request.user = user+ })+ await upload.register(superTabRoutes, { store: attaching })+ await upload.ready()+ })+ afterAll(async () => { await upload?.close() })+ type Part = [string, string] | [string, Uint8Array, string, string]+ type Uploaded = { id: string; name: string; mime: string; size: number; url: string }+ const post = async (tab: string, parts: Part[], user = owner, asAgentId?: string, server = upload) => {+ const form = new FormData()+ for (const part of parts) {+ if (part.length === 2) form.append(part[0], part[1])+ else form.append(part[0], new Blob([part[1]], { type: part[3] }), part[2])}- expect(Buffer.concat([await read(peer, 0) as Buffer, await read(host, 1, lead) as Buffer]).equals(bytes)).toBe(true)- expect(await read(peer, 2)).toBe(404)- expect((await http(peer, 'GET', `/api/super-tabs/${tab}/attachments/${image.id}`)).json().data).toEqual({ ...meta, complete: true })- const delivery = (await store.deliveries(host, tab, lead))[0]!- const claimed = await store.delivery(host, tab, lead, delivery.id, { type: 'claim', claimId: 'claim' })- expect(claimed.message).toMatchObject({ id: sent.result.messageId, attachments: [meta] })+ const encoded = new Request('http://upload.test', { method: 'POST', body: form })+ const response = await server.inject({ method: 'POST', url: `/api/super-tabs/${tab}/attachments${asAgentId ? `?asAgentId=${asAgentId}` : ''}`,+ headers: { authorization: `Bearer ${user.sub}`, 'content-type': encoded.headers.get('content-type')! }, payload: Buffer.from(await encoded.arrayBuffer()) })+ const body = response.json()+ return { status: response.statusCode, code: body.error?.code ?? body.code, attachment: body.data?.attachment as Uploaded }+ }+ const file = (tab: string, name = 'screen.png', bytes = new Uint8Array([1, 2, 3]), mime = 'image/png', conversationId = 'lead', user = owner, asAgentId?: string) =>+ post(tab, [['conversationId', conversationId], ['file', bytes, name, mime]], user, asAgentId)+ const send = (tab: string, attachmentIds: string[], user = owner, asAgentId?: string, text = '', operationId = randomUUID()) =>+ attaching.execute(user, tab, { operationId, command: { type: 'message.send', conversationId: 'lead', text, replyTo: null, recipientIds: [], attachmentIds } }, asAgentId)+ const objectKey = (url: string) => url.slice('https://cdn.example.test/'.length)- // Another tab cannot name it, and leaving the tab ends access.- const other = (await store.create(owner, randomUUID(), 'Other')).id- await expect(run(other, send([image.id]))).rejects.toMatchObject({ code: 'INVALID_ATTACHMENT' })- expect((await http(owner, 'GET', `/api/super-tabs/${other}/attachments/${image.id}`)).statusCode).toBe(404)- await run(tab, { type: 'member.remove', userId: peer.sub }, peer)- expect(await read(peer, 0)).toBe(403)+ it('streams one file into the bucket under a random key and answers its metadata', async () => {+ const { tab } = await fixture()+ const bytes = new Uint8Array(2 * 1024 * 1024).map((_, i) => i % 251)+ bytes.set([0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a])+ const { status, attachment } = await file(tab, 'Screen Shot 1.png', bytes)+ expect(status).toBe(200)+ expect(attachment).toMatchObject({ name: 'Screen Shot 1.png', mime: 'image/png', size: bytes.byteLength })+ expect(attachment.url).toMatch(new RegExp(`^https://cdn\\.example\\.test/super-tabs/${tab}/[0-9a-f]{32}/Screen_Shot_1\\.png$`))+ expect(files.objects.get(objectKey(attachment.url))!.bytes.equals(Buffer.from(bytes))).toBe(true)+ expect(files.objects.get(objectKey(attachment.url))).toMatchObject({ contentType: 'image/png', contentDisposition: "inline; filename*=UTF-8''Screen%20Shot%201.png" })+ const html = await file(tab, 'page.html', new Uint8Array([60]), 'text/html')+ expect(html.attachment.mime).toBe('text/html')+ expect(files.objects.get(objectKey(html.attachment.url))).toMatchObject({ contentType: 'application/octet-stream', contentDisposition: "attachment; filename*=UTF-8''page.html" })+ // A page renamed to .png is not an image: it is kept whole, as bytes to download.+ const page = Buffer.from('<html><script>alert(1)</script></html>')+ const disguised = await file(tab, 'cat.png', page, 'image/png')+ expect(disguised.attachment.mime).toBe('application/octet-stream')+ expect(files.objects.get(objectKey(disguised.attachment.url))).toMatchObject({ contentType: 'application/octet-stream', contentDisposition: "attachment; filename*=UTF-8''cat.png" })+ expect(files.objects.get(objectKey(disguised.attachment.url))!.bytes.equals(page)).toBe(true)})- it('takes only PNG, JPEG and WebP within 5 MB, and keeps an image out of a private project it was not sent to', async () => {+ it('refuses an oversized, second, misordered or hidden-named file, and a server with no bucket', async () => {const { tab } = await fixture()- expect((await upload(owner, tab, Buffer.from('GIF89a-and-more'), 'cat.png')).json().error.code).toBe('UNSUPPORTED_ATTACHMENT')- const tooLarge = await http(owner, 'POST', `/api/super-tabs/${tab}/attachments`, { name: 'big.png', size: 5 * 1024 * 1024 + 1, data: png(PART).toString('base64') })- expect(tooLarge.statusCode).toBe(400)- const short = await http(owner, 'POST', `/api/super-tabs/${tab}/attachments`, { name: 'short.png', size: 100, data: png(50).toString('base64') })- expect(short.json().error.code).toBe('INVALID_ATTACHMENT')- const { conversationId } = (await run(tab, { type: 'project.create', name: 'Private', visibility: 'private', brief: '' })).result as { conversationId: string }- const image = (await upload(owner, tab, png(100))).json().data- expect(image.complete).toBe(true)- await run(tab, { ...send([image.id], 'For the private project'), conversationId } as Command)- await invite(tab)- expect((await http(peer, 'GET', `/api/super-tabs/${tab}/attachments/${image.id}/parts/0`)).statusCode).toBe(404)- expect((await http(owner, 'GET', `/api/super-tabs/${tab}/attachments/${image.id}/parts/0`)).statusCode).toBe(200)- expect((await upload(peer, tab, png(100))).json().data.complete).toBe(true)+ const before = files.objects.size+ expect(await file(tab, 'big.bin', new Uint8Array(10 * 1024 * 1024 + 1), 'application/octet-stream')).toMatchObject({ status: 413, code: 'ATTACHMENT_TOO_LARGE' })+ expect(await file(tab, 'exact.bin', new Uint8Array(10 * 1024 * 1024), 'application/octet-stream')).toMatchObject({ status: 200 })+ expect(await post(tab, [['conversationId', 'lead'], ['file', new Uint8Array(1), 'a.png', 'image/png'], ['file', new Uint8Array(1), 'b.png', 'image/png']]))+ .toMatchObject({ status: 400, code: 'INVALID_ATTACHMENT' })+ expect(await post(tab, [['file', new Uint8Array(1), 'a.png', 'image/png'], ['conversationId', 'lead']])).toMatchObject({ status: 400, code: 'INVALID_ATTACHMENT' })+ expect(await post(tab, [['conversationId', 'lead']])).toMatchObject({ status: 400, code: 'INVALID_ATTACHMENT' })+ expect(await file(tab, 'evilgnp.exe')).toMatchObject({ status: 400, code: 'INVALID_ATTACHMENT' })+ const json = await upload.inject({ method: 'POST', url: `/api/super-tabs/${tab}/attachments`, headers: { authorization: `Bearer ${owner.sub}` }, payload: { conversationId: 'lead' } })+ expect([json.statusCode, json.json().error?.code ?? json.json().code]).toEqual([400, 'INVALID_ATTACHMENT'])+ // The exact-size file, and the first of the two: the second is only seen after the first was stored. Its id was+ // never answered to anyone, so nothing can send it.+ expect(files.objects.size).toBe(before + 2)+ expect(await post(tab, [['conversationId', 'lead'], ['file', new Uint8Array(1), 'a.png', 'image/png']], owner, undefined, app))+ .toMatchObject({ status: 503, code: 'ATTACHMENTS_UNAVAILABLE' })})- it('lets the uploader resume or delete an unsent image, and prunes unfinished uploads after an hour', async () => {+ it('answers a bucket failure as unavailable, not as a server error', async () => {const { tab } = await fixture()- await invite(tab)- const bytes = png(2 * PART + 5)- const image = (await upload(owner, tab, bytes)).json().data- const meta = async (user = owner) => (await http(user, 'GET', `/api/super-tabs/${tab}/attachments/${image.id}`)).json()- expect((await meta()).data).toMatchObject({ parts: 3, complete: false, missing: [1, 2] })- await http(owner, 'POST', `/api/super-tabs/${tab}/attachments/${image.id}/parts/2`, { data: bytes.subarray(2 * PART).toString('base64') })- expect((await meta()).data.missing).toEqual([1])- const remove = (user: AuthUser, id = image.id) => http(user, 'DELETE', `/api/super-tabs/${tab}/attachments/${id}`)- expect((await remove(peer)).statusCode).toBe(404)- expect((await remove(owner)).json().data).toEqual({ id: image.id, deleted: true })- expect((await meta()).error.code).toBe('NOT_FOUND')- expect(await db.superTabAttachmentPart.count({ where: { attachmentId: image.id } })).toBe(0)- const sent = (await upload(owner, tab, png(100))).json().data- await run(tab, send([sent.id]))- expect((await remove(owner, sent.id)).json().error.code).toBe('ATTACHMENT_SENT')+ const put = vi.spyOn(files, 'put').mockRejectedValueOnce(Object.assign(new Error('Forbidden'), { code: 403 }))+ expect(await file(tab)).toMatchObject({ status: 503, code: 'ATTACHMENTS_UNAVAILABLE' })+ put.mockRestore()+ expect(await file(tab)).toMatchObject({ status: 200 })+ })- const unfinished = (await upload(owner, tab, png(PART + 1))).json().data- const finished = (await upload(owner, tab, png(100))).json().data- await new SuperTabStore(db, () => Date.now() + 2 * 3_600_000).attachments.upload(owner, tab,- { name: 'later.png', size: 100, data: png(100).toString('base64') })- expect(await db.superTabAttachment.findUnique({ where: { id: unfinished.id } })).toBeNull()- expect(await db.superTabAttachment.findUnique({ where: { id: finished.id } })).not.toBeNull()+ it('sends uploaded files once, with empty text, and delivers their metadata to the agent', async () => {+ const { tab, lead } = await fixture()+ const { attachment } = await file(tab, 'log.txt', new Uint8Array(10), 'text/plain')+ const sent = await send(tab, [attachment.id])+ const row = (await store.messages(owner, tab, 'lead', {})).messages.find(m => m.id === sent.result.messageId)!+ expect(row).toMatchObject({ text: '', attachments: [attachment] })+ const delivery = (await store.deliveries(host, tab, lead)).find(d => d.messageId === sent.result.messageId)!+ expect((await store.delivery(host, tab, lead, delivery.id, { type: 'claim', claimId: randomUUID() })).message!.attachments).toEqual([attachment])+ await expect(send(tab, [attachment.id])).rejects.toMatchObject({ code: 'ATTACHMENT_USED' })+ await expect(send(tab, [])).rejects.toMatchObject({ code: 'TEXT_REQUIRED' })})- it('refuses an empty message and carries the images when a person resends an uncertain delivery', async () => {+ it('lets only the uploading actor send a file, only in its conversation, and an agent attach from its host', async () => {const { tab, lead } = await fixture()- await expect(run(tab, message(' '))).rejects.toMatchObject({ code: 'EMPTY_MESSAGE' })- const image = (await upload(owner, tab, png(100))).json().data- await run(tab, send([image.id], 'Look at this'))- const first = (await store.deliveries(host, tab, lead))[0]!- await store.delivery(host, tab, lead, first.id, { type: 'claim', claimId: 'claim' })- await store.delivery(host, tab, lead, first.id, { type: 'ack', claimId: 'claim', receipt: 'lost', uncertain: true })- await run(tab, { type: 'delivery.resolve', deliveryId: first.id, resolution: 'resend' })- const rows = (await store.messages(owner, tab, 'lead', {})).messages- expect(rows.at(-1)).toMatchObject({ text: 'Look at this', replyTo: rows.at(-2)!.id, attachments: [expect.objectContaining({ id: image.id })] })+ await invite(tab)+ const mine = (await file(tab)).attachment+ await expect(send(tab, [mine.id], peer)).rejects.toMatchObject({ code: 'ATTACHMENT_UNAVAILABLE' })+ const group = String((await run(tab, { type: 'conversation.create', title: 'Elsewhere', brief: '', checks: [] })).result.conversationId)+ const elsewhere = (await file(tab, 'x.png', new Uint8Array(5), 'image/png', group)).attachment+ await expect(send(tab, [elsewhere.id])).rejects.toMatchObject({ code: 'ATTACHMENT_UNAVAILABLE' })+ await expect(send(tab, ['missing-attachment'])).rejects.toMatchObject({ code: 'ATTACHMENT_UNAVAILABLE' })+ expect(await file(tab, 'a.png', new Uint8Array(1), 'image/png', 'lead', peer, lead)).toMatchObject({ status: 403, code: 'FORBIDDEN' })+ expect(await file(tab, 'a.png', new Uint8Array(1), 'image/png', 'no-such-group')).toMatchObject({ status: 404 })+ const fromAgent = (await file(tab, 'result.png', new Uint8Array(7), 'image/png', 'lead', host, lead)).attachment+ const sent = await send(tab, [fromAgent.id], host, lead, 'Here is the screenshot.')+ expect((await store.messages(owner, tab, 'lead', {})).messages.find(m => m.id === sent.result.messageId))+ .toMatchObject({ author: { kind: 'agent', id: lead }, attachments: [{ name: 'result.png', size: 7 }] })+ })++ it('refuses a viewer before storing anything', async () => {+ const { tab } = await fixture()+ await invite(tab, 'viewer')+ const before = files.objects.size+ expect(await file(tab, 'a.png', new Uint8Array(1), 'image/png', 'lead', peer)).toMatchObject({ status: 403, code: 'READ_ONLY' })+ expect(files.objects.size).toBe(before)})})diff --git a/backend/package-lock.json b/backend/package-lock.jsonindex e3df75725..37f1c0420 100644--- a/backend/package-lock.json+++ b/backend/package-lock.json@@ -11,6 +11,7 @@"dependencies": {"@fastify/cors": "^10.1.0","@fastify/multipart": "^9.4.0",+ "@google-cloud/storage": "8.2.0","@noble/curves": "^2.4.0","@noble/hashes": "^2.4.0","@prisma/client": "^5.22.0",@@ -713,6 +714,76 @@"ipaddr.js": "^2.1.0"}},+ "node_modules/@google-cloud/paginator": {+ "version": "7.2.0",+ "resolved": "https://registry.npmjs.org/@google-cloud/paginator/-/paginator-7.2.0.tgz",+ "integrity": "sha512-l+x6YObHGTuqBCMvC0SXo3Cnyqg4FkWWKYRptf46PACHJ5GAUuhsd2b3wphgGrg1ybs/LAb+q5MnUTuG/3+v7w==",+ "license": "Apache-2.0",+ "dependencies": {+ "extend": "^3.0.2"+ },+ "engines": {+ "node": ">=22"+ }+ },+ "node_modules/@google-cloud/projectify": {+ "version": "6.2.1",+ "resolved": "https://registry.npmjs.org/@google-cloud/projectify/-/projectify-6.2.1.tgz",+ "integrity": "sha512-PV9oy7VpQRXLuqKuU5RSOHFQyWgvw2sT9MoTGykja9j6c9pv5+ttKTJiFsccu500YYIGiz8JCOsb60PfKmiV/w==",+ "license": "Apache-2.0",+ "engines": {+ "node": ">=22"+ }+ },+ "node_modules/@google-cloud/promisify": {+ "version": "6.2.1",+ "resolved": "https://registry.npmjs.org/@google-cloud/promisify/-/promisify-6.2.1.tgz",+ "integrity": "sha512-/+RvLJ5u+WhGay6Z3aY6OApDQmNqq1427Mmt7Eov9kYp69gdUiGSwFnygeTxfz69XBtYZLAnWikGMIoFXtKt+A==",+ "license": "Apache-2.0",+ "engines": {+ "node": ">=22"+ }+ },+ "node_modules/@google-cloud/storage": {+ "version": "8.2.0",+ "resolved": "https://registry.npmjs.org/@google-cloud/storage/-/storage-8.2.0.tgz",+ "integrity": "sha512-7ckgSjeEprV92VrlLjpYFA3PFerflvFtF7Ea86oQXGNCprGZq5rtpAVK0zgWnCy+44mLjms42M7MiWa433gz2A==",+ "license": "Apache-2.0",+ "dependencies": {+ "@google-cloud/paginator": "^7.0.1",+ "@google-cloud/projectify": "^6.0.1",+ "@google-cloud/promisify": "^6.0.1",+ "abort-controller": "^3.0.0",+ "async-retry": "^1.3.3",+ "duplexify": "^4.1.3",+ "fast-xml-parser": "^5.3.4",+ "gaxios": "^6.0.2",+ "google-auth-library": "^9.6.3",+ "html-entities": "^2.5.2",+ "mime": "^3.0.0",+ "p-limit": "^3.0.1",+ "retry-request": "^9.0.1",+ "teeny-request": "^11.0.1"+ },+ "engines": {+ "node": ">=22"+ }+ },+ "node_modules/@google-cloud/storage/node_modules/p-limit": {+ "version": "3.1.0",+ "resolved": "https://registry.npmjs.org/p-limit/-/p-limit-3.1.0.tgz",+ "integrity": "sha512-TYOanM3wGwNGsZN2cVTYPArw454xnXj5qmWF1bEoAc4+cU/ol7GVh7odevjp1FNHduHc3KZMcFduxU5Xc6uJRQ==",+ "license": "MIT",+ "dependencies": {+ "yocto-queue": "^0.1.0"+ },+ "engines": {+ "node": ">=10"+ },+ "funding": {+ "url": "https://github.com/sponsors/sindresorhus"+ }+ },"node_modules/@ioredis/commands": {"version": "1.10.0","resolved": "https://registry.npmjs.org/@ioredis/commands/-/commands-1.10.0.tgz",@@ -784,6 +855,18 @@"url": "https://paulmillr.com/funding/"}},+ "node_modules/@nodable/entities": {+ "version": "3.1.0",+ "resolved": "https://registry.npmjs.org/@nodable/entities/-/entities-3.1.0.tgz",+ "integrity": "sha512-LsS/DjHr+uDM647Gru/cA8+J3a3HfhttwCKLyuoyN7yXTFCxKBtSgMQBvrW9yNPa2/zDRUNuGPaH5QUFoa4arQ==",+ "funding": [+ {+ "type": "github",+ "url": "https://github.com/sponsors/nodable"+ }+ ],+ "license": "MIT"+ },"node_modules/@oxc-project/types": {"version": "0.148.0","resolved": "https://registry.npmjs.org/@oxc-project/types/-/types-0.148.0.tgz",@@ -1351,6 +1434,18 @@"url": "https://opencollective.com/vitest"}},+ "node_modules/abort-controller": {+ "version": "3.0.0",+ "resolved": "https://registry.npmjs.org/abort-controller/-/abort-controller-3.0.0.tgz",+ "integrity": "sha512-h8lQ8tacZYnR3vNQTgibj+tODHI5/+l06Au2Pcriv/Gmet0eaj4TwWH41sO9wnHDiQsEj19q0drzdWdeAHtweg==",+ "license": "MIT",+ "dependencies": {+ "event-target-shim": "^5.0.0"+ },+ "engines": {+ "node": ">=6.5"+ }+ },"node_modules/abstract-logging": {"version": "2.0.1","resolved": "https://registry.npmjs.org/abstract-logging/-/abstract-logging-2.0.1.tgz",@@ -1361,7 +1456,6 @@"version": "7.1.4","resolved": "https://registry.npmjs.org/agent-base/-/agent-base-7.1.4.tgz","integrity": "sha512-MnA+YT8fwfJPgBx3m60MNqakm30XOkyIoH1y6huTQvC0PwZG7ki8NacLBcrPbNoo8vEZy7Jpuk7+jMO+CUovTQ==",- "dev": true,"license": "MIT","engines": {"node": ">= 14"@@ -1442,6 +1536,18 @@"url": "https://github.com/chalk/ansi-styles?sponsor=1"}},+ "node_modules/anynum": {+ "version": "1.0.1",+ "resolved": "https://registry.npmjs.org/anynum/-/anynum-1.0.1.tgz",+ "integrity": "sha512-N6//FLET/tXYNM/F6ABca1oH6fWB+KlTt909Le28WMDBk8oaT4vY17DCrwg2MvmuqUKt3Ni4N5dGJ/EoBgcO6A==",+ "funding": [+ {+ "type": "github",+ "url": "https://github.com/sponsors/NaturalIntelligence"+ }+ ],+ "license": "MIT"+ },"node_modules/assertion-error": {"version": "2.0.1","resolved": "https://registry.npmjs.org/assertion-error/-/assertion-error-2.0.1.tgz",@@ -1474,6 +1580,15 @@"tslib": "^2.4.0"}},+ "node_modules/async-retry": {+ "version": "1.3.3",+ "resolved": "https://registry.npmjs.org/async-retry/-/async-retry-1.3.3.tgz",+ "integrity": "sha512-wfr/jstw9xNi/0teMHrRW7dsz3Lt5ARhYNZ2ewpadnhaIp5mbALhOAP+EAdsC7t4Z6wqsDVv9+W6gm1Dk9mEyw==",+ "license": "MIT",+ "dependencies": {+ "retry": "0.13.1"+ }+ },"node_modules/atomic-sleep": {"version": "1.0.0","resolved": "https://registry.npmjs.org/atomic-sleep/-/atomic-sleep-1.0.0.tgz",@@ -1603,6 +1718,35 @@"bare-path": "^3.0.0"}},+ "node_modules/base64-js": {+ "version": "1.5.1",+ "resolved": "https://registry.npmjs.org/base64-js/-/base64-js-1.5.1.tgz",+ "integrity": "sha512-AKpaYlHn8t4SVbOHCy+b5+KKgvR4vrsD8vbvrbiQJps7fKDTkjkDry6ji0rUJjC0kzbNePLwzxq8iypo41qeWA==",+ "funding": [+ {+ "type": "github",+ "url": "https://github.com/sponsors/feross"+ },+ {+ "type": "patreon",+ "url": "https://www.patreon.com/feross"+ },+ {+ "type": "consulting",+ "url": "https://feross.org/support"+ }+ ],+ "license": "MIT"+ },+ "node_modules/bignumber.js": {+ "version": "9.3.1",+ "resolved": "https://registry.npmjs.org/bignumber.js/-/bignumber.js-9.3.1.tgz",+ "integrity": "sha512-Ko0uX15oIUS7wJ3Rb30Fs6SkVbLmPBAKdlm7q9+ak9bbIeFf0MwuBsQV6z7+X768/cHsfg+WlysDWJcmthjsjQ==",+ "license": "MIT",+ "engines": {+ "node": "*"+ }+ },"node_modules/bson": {"version": "6.10.4","resolved": "https://registry.npmjs.org/bson/-/bson-6.10.4.tgz",@@ -1613,6 +1757,12 @@"node": ">=16.20.1"}},+ "node_modules/buffer-equal-constant-time": {+ "version": "1.0.1",+ "resolved": "https://registry.npmjs.org/buffer-equal-constant-time/-/buffer-equal-constant-time-1.0.1.tgz",+ "integrity": "sha512-zRpUiDwd/xk6ADqPMATG8vc9VPrkck7T07OIx0gnjmJAnHnTVXNQG3vfvWNuiZIkwu9KrKdA1iJKfsfTVxE6NA==",+ "license": "BSD-3-Clause"+ },"node_modules/camelcase": {"version": "6.3.0","resolved": "https://registry.npmjs.org/camelcase/-/camelcase-6.3.0.tgz",@@ -1762,6 +1912,15 @@"url": "https://opencollective.com/express"}},+ "node_modules/data-uri-to-buffer": {+ "version": "4.0.1",+ "resolved": "https://registry.npmjs.org/data-uri-to-buffer/-/data-uri-to-buffer-4.0.1.tgz",+ "integrity": "sha512-0R9ikRb668HB7QDxT1vkpuUBtqc53YyAwMwGeUFKRojY/NWKvdZ+9UYtRfGmhqNbRkTSVpMbmyhXipFFv2cb/A==",+ "license": "MIT",+ "engines": {+ "node": ">= 12"+ }+ },"node_modules/debug": {"version": "4.4.3","resolved": "https://registry.npmjs.org/debug/-/debug-4.4.3.tgz",@@ -1819,6 +1978,27 @@"url": "https://dotenvx.com"}},+ "node_modules/duplexify": {+ "version": "4.1.3",+ "resolved": "https://registry.npmjs.org/duplexify/-/duplexify-4.1.3.tgz",+ "integrity": "sha512-M3BmBhwJRZsSx38lZyhE53Csddgzl5R7xGJNk7CVddZD6CcmwMCH8J+7AprIrQKH7TonKxaCjcv27Qmf+sQ+oA==",+ "license": "MIT",+ "dependencies": {+ "end-of-stream": "^1.4.1",+ "inherits": "^2.0.3",+ "readable-stream": "^3.1.1",+ "stream-shift": "^1.0.2"+ }+ },+ "node_modules/ecdsa-sig-formatter": {+ "version": "1.0.11",+ "resolved": "https://registry.npmjs.org/ecdsa-sig-formatter/-/ecdsa-sig-formatter-1.0.11.tgz",+ "integrity": "sha512-nagl3RYrbNv6kQkeJIpt6NJZy8twLB/2vtz6yN9Z4vRKHN4/QZJIEbqohALSgwKdnksuY3k5Addp5lg8sVoVcQ==",+ "license": "Apache-2.0",+ "dependencies": {+ "safe-buffer": "^5.0.1"+ }+ },"node_modules/emoji-regex": {"version": "8.0.0","resolved": "https://registry.npmjs.org/emoji-regex/-/emoji-regex-8.0.0.tgz",@@ -1826,6 +2006,15 @@"dev": true,"license": "MIT"},+ "node_modules/end-of-stream": {+ "version": "1.4.5",+ "resolved": "https://registry.npmjs.org/end-of-stream/-/end-of-stream-1.4.5.tgz",+ "integrity": "sha512-ooEGc6HP26xXq/N+GCGOT0JKCLDGrq2bQUZrQ7gyrJiZANJ/8YDTxTpQBXGMn+WbIQXNVpyWymm7KYVICQnyOg==",+ "license": "MIT",+ "dependencies": {+ "once": "^1.4.0"+ }+ },"node_modules/es-module-lexer": {"version": "2.3.2","resolved": "https://registry.npmjs.org/es-module-lexer/-/es-module-lexer-2.3.2.tgz",@@ -1895,6 +2084,15 @@"@types/estree": "^1.0.0"}},+ "node_modules/event-target-shim": {+ "version": "5.0.1",+ "resolved": "https://registry.npmjs.org/event-target-shim/-/event-target-shim-5.0.1.tgz",+ "integrity": "sha512-i/2XbnSz/uxRCU6+NdVJgKWDTM427+MqYbkQzD321DuCQJUqOuJKIA0IM2+W2xtYHdKOmZ4dR6fExsd4SXL+WQ==",+ "license": "MIT",+ "engines": {+ "node": ">=6"+ }+ },"node_modules/eventemitter3": {"version": "4.0.7","resolved": "https://registry.npmjs.org/eventemitter3/-/eventemitter3-4.0.7.tgz",@@ -1921,6 +2119,12 @@"node": ">=12.0.0"}},+ "node_modules/extend": {+ "version": "3.0.2",+ "resolved": "https://registry.npmjs.org/extend/-/extend-3.0.2.tgz",+ "integrity": "sha512-fjquC59cD7CyW6urNXK0FBufkZcoiGG80wTuPujX590cB5Ttln20E2UB4S/WARVqhXffZl2LNgS+gQdPIIim/g==",+ "license": "MIT"+ },"node_modules/fast-decode-uri-component": {"version": "1.0.1","resolved": "https://registry.npmjs.org/fast-decode-uri-component/-/fast-decode-uri-component-1.0.1.tgz",@@ -1989,6 +2193,45 @@],"license": "BSD-3-Clause"},+ "node_modules/fast-xml-builder": {+ "version": "1.3.1",+ "resolved": "https://registry.npmjs.org/fast-xml-builder/-/fast-xml-builder-1.3.1.tgz",+ "integrity": "sha512-pIM/1n3ntFXKYrUZwW7QCK0gAW7XY+wzj1YMIV3tLDvPj/V+zTGJK5e3/4WJfwj0qWw2ElNXiTixda/R+3YSug==",+ "funding": [+ {+ "type": "github",+ "url": "https://github.com/sponsors/NaturalIntelligence"+ }+ ],+ "license": "MIT",+ "dependencies": {+ "path-expression-matcher": "^1.6.2",+ "xml-naming": "^0.3.0"+ }+ },+ "node_modules/fast-xml-parser": {+ "version": "5.11.2",+ "resolved": "https://registry.npmjs.org/fast-xml-parser/-/fast-xml-parser-5.11.2.tgz",+ "integrity": "sha512-R9iDuNrQYeQut46cn2r2wHKn4HYzVDvDm5J1wW+koZewykv0yuO2HChTYeZtrULyHIDM9cj9TUXloCsueCQUog==",+ "funding": [+ {+ "type": "github",+ "url": "https://github.com/sponsors/NaturalIntelligence"+ }+ ],+ "license": "MIT",+ "dependencies": {+ "@nodable/entities": "^3.0.1",+ "fast-xml-builder": "^1.2.0",+ "is-unsafe": "^2.0.0",+ "path-expression-matcher": "^1.6.2",+ "strnum": "^2.4.2",+ "xml-naming": "^0.3.0"+ },+ "bin": {+ "fxparser": "src/cli/cli.js"+ }+ },"node_modules/fastify": {"version": "5.12.1","resolved": "https://registry.npmjs.org/fastify/-/fastify-5.12.1.tgz",@@ -2065,6 +2308,29 @@}}},+ "node_modules/fetch-blob": {+ "version": "3.2.0",+ "resolved": "https://registry.npmjs.org/fetch-blob/-/fetch-blob-3.2.0.tgz",+ "integrity": "sha512-7yAQpD2UMJzLi1Dqv7qFYnPbaPx7ZfFK6PiIxQ4PfkGPyNyl2Ugx+a/umUonmKqjhM4DnfbMvdX6otXq83soQQ==",+ "funding": [+ {+ "type": "github",+ "url": "https://github.com/sponsors/jimmywarting"+ },+ {+ "type": "paypal",+ "url": "https://paypal.me/jimmywarting"+ }+ ],+ "license": "MIT",+ "dependencies": {+ "node-domexception": "^1.0.0",+ "web-streams-polyfill": "^3.0.3"+ },+ "engines": {+ "node": "^12.20 || >= 14.13"+ }+ },"node_modules/find-cache-dir": {"version": "3.3.2","resolved": "https://registry.npmjs.org/find-cache-dir/-/find-cache-dir-3.3.2.tgz",@@ -2157,6 +2423,18 @@}}},+ "node_modules/formdata-polyfill": {+ "version": "4.0.10",+ "resolved": "https://registry.npmjs.org/formdata-polyfill/-/formdata-polyfill-4.0.10.tgz",+ "integrity": "sha512-buewHzMvYL29jdeQTVILecSaZKnt/RJWjoZCF5OW60Z67/GmSLBkOFM7qh1PI3zFNtJbaZL5eQu1vLfazOwj4g==",+ "license": "MIT",+ "dependencies": {+ "fetch-blob": "^3.1.2"+ },+ "engines": {+ "node": ">=12.20.0"+ }+ },"node_modules/fsevents": {"version": "2.3.3","resolved": "https://registry.npmjs.org/fsevents/-/fsevents-2.3.3.tgz",@@ -2172,6 +2450,87 @@"node": "^8.16.0 || ^10.6.0 || >=11.0.0"}},+ "node_modules/gaxios": {+ "version": "6.7.1",+ "resolved": "https://registry.npmjs.org/gaxios/-/gaxios-6.7.1.tgz",+ "integrity": "sha512-LDODD4TMYx7XXdpwxAVRAIAuB0bzv0s+ywFonY46k126qzQHT9ygyoa9tncmOiQmmDrik65UYsEkv3lbfqQ3yQ==",+ "license": "Apache-2.0",+ "dependencies": {+ "extend": "^3.0.2",+ "https-proxy-agent": "^7.0.1",+ "is-stream": "^2.0.0",+ "node-fetch": "^2.6.9",+ "uuid": "^9.0.1"+ },+ "engines": {+ "node": ">=14"+ }+ },+ "node_modules/gcp-metadata": {+ "version": "5.3.0",+ "resolved": "https://registry.npmjs.org/gcp-metadata/-/gcp-metadata-5.3.0.tgz",+ "integrity": "sha512-FNTkdNEnBdlqF2oatizolQqNANMrcqJt6AAYt99B3y1aLLC8Hc5IOBb+ZnnzllodEEf6xMBp6wRcBbc16fa65w==",+ "dev": true,+ "license": "Apache-2.0",+ "optional": true,+ "peer": true,+ "dependencies": {+ "gaxios": "^5.0.0",+ "json-bigint": "^1.0.0"+ },+ "engines": {+ "node": ">=12"+ }+ },+ "node_modules/gcp-metadata/node_modules/agent-base": {+ "version": "6.0.2",+ "resolved": "https://registry.npmjs.org/agent-base/-/agent-base-6.0.2.tgz",+ "integrity": "sha512-RZNwNclF7+MS/8bDg70amg32dyeZGZxiDuQmZxKLAlQjr3jGyLx+4Kkk58UO7D2QdgFIQCovuSuZESne6RG6XQ==",+ "dev": true,+ "license": "MIT",+ "optional": true,+ "peer": true,+ "dependencies": {+ "debug": "4"+ },+ "engines": {+ "node": ">= 6.0.0"+ }+ },+ "node_modules/gcp-metadata/node_modules/gaxios": {+ "version": "5.1.3",+ "resolved": "https://registry.npmjs.org/gaxios/-/gaxios-5.1.3.tgz",+ "integrity": "sha512-95hVgBRgEIRQQQHIbnxBXeHbW4TqFk4ZDJW7wmVtvYar72FdhRIo1UGOLS2eRAKCPEdPBWu+M7+A33D9CdX9rA==",+ "dev": true,+ "license": "Apache-2.0",+ "optional": true,+ "peer": true,+ "dependencies": {+ "extend": "^3.0.2",+ "https-proxy-agent": "^5.0.0",+ "is-stream": "^2.0.0",+ "node-fetch": "^2.6.9"+ },+ "engines": {+ "node": ">=12"+ }+ },+ "node_modules/gcp-metadata/node_modules/https-proxy-agent": {+ "version": "5.0.1",+ "resolved": "https://registry.npmjs.org/https-proxy-agent/-/https-proxy-agent-5.0.1.tgz",+ "integrity": "sha512-dFcAjpTQFgoLMzC2VwU+C/CbS7uRL0lWmxDITmqm7C+7F0Odmj6s9l6alZc6AELXhrnggM2CeWSXHGOdX2YtwA==",+ "dev": true,+ "license": "MIT",+ "optional": true,+ "peer": true,+ "dependencies": {+ "agent-base": "6",+ "debug": "4"+ },+ "engines": {+ "node": ">= 6"+ }+ },"node_modules/get-caller-file": {"version": "2.0.5","resolved": "https://registry.npmjs.org/get-caller-file/-/get-caller-file-2.0.5.tgz",@@ -2182,6 +2541,59 @@"node": "6.* || 8.* || >= 10.*"}},+ "node_modules/google-auth-library": {+ "version": "9.15.1",+ "resolved": "https://registry.npmjs.org/google-auth-library/-/google-auth-library-9.15.1.tgz",+ "integrity": "sha512-Jb6Z0+nvECVz+2lzSMt9u98UsoakXxA2HGHMCxh+so3n90XgYWkq5dur19JAJV7ONiJY22yBTyJB1TSkvPq9Ng==",+ "license": "Apache-2.0",+ "dependencies": {+ "base64-js": "^1.3.0",+ "ecdsa-sig-formatter": "^1.0.11",+ "gaxios": "^6.1.1",+ "gcp-metadata": "^6.1.0",+ "gtoken": "^7.0.0",+ "jws": "^4.0.0"+ },+ "engines": {+ "node": ">=14"+ }+ },+ "node_modules/google-auth-library/node_modules/gcp-metadata": {+ "version": "6.1.1",+ "resolved": "https://registry.npmjs.org/gcp-metadata/-/gcp-metadata-6.1.1.tgz",+ "integrity": "sha512-a4tiq7E0/5fTjxPAaH4jpjkSv/uCaU2p5KC6HVGrvl0cDjA8iBZv4vv1gyzlmK0ZUKqwpOyQMKzZQe3lTit77A==",+ "license": "Apache-2.0",+ "dependencies": {+ "gaxios": "^6.1.1",+ "google-logging-utils": "^0.0.2",+ "json-bigint": "^1.0.0"+ },+ "engines": {+ "node": ">=14"+ }+ },+ "node_modules/google-logging-utils": {+ "version": "0.0.2",+ "resolved": "https://registry.npmjs.org/google-logging-utils/-/google-logging-utils-0.0.2.tgz",+ "integrity": "sha512-NEgUnEcBiP5HrPzufUkBzJOD/Sxsco3rLNo1F1TNf7ieU8ryUzBhqba8r756CjLX7rn3fHl6iLEwPYuqpoKgQQ==",+ "license": "Apache-2.0",+ "engines": {+ "node": ">=14"+ }+ },+ "node_modules/gtoken": {+ "version": "7.1.0",+ "resolved": "https://registry.npmjs.org/gtoken/-/gtoken-7.1.0.tgz",+ "integrity": "sha512-pCcEwRi+TKpMlxAQObHDQ56KawURgyAf6jtIY046fJ5tIv3zDe/LEIubckAO8fj6JnAxLdmWkUfNyulQ2iKdEw==",+ "license": "MIT",+ "dependencies": {+ "gaxios": "^6.0.0",+ "jws": "^4.0.0"+ },+ "engines": {+ "node": ">=14.0.0"+ }+ },"node_modules/has-flag": {"version": "4.0.0","resolved": "https://registry.npmjs.org/has-flag/-/has-flag-4.0.0.tgz",@@ -2192,6 +2604,22 @@"node": ">=8"}},+ "node_modules/html-entities": {+ "version": "2.6.0",+ "resolved": "https://registry.npmjs.org/html-entities/-/html-entities-2.6.0.tgz",+ "integrity": "sha512-kig+rMn/QOVRvr7c86gQ8lWXq+Hkv6CbAH1hLu+RG338StTpE8Z0b44SDVaqVu7HGKf27frdmUYEs9hTUX/cLQ==",+ "funding": [+ {+ "type": "github",+ "url": "https://github.com/sponsors/mdevils"+ },+ {+ "type": "patreon",+ "url": "https://patreon.com/mdevils"+ }+ ],+ "license": "MIT"+ },"node_modules/html-escaper": {"version": "2.0.2","resolved": "https://registry.npmjs.org/html-escaper/-/html-escaper-2.0.2.tgz",@@ -2213,11 +2641,23 @@"node": ">=8.0.0"}},+ "node_modules/http-proxy-agent": {+ "version": "7.0.2",+ "resolved": "https://registry.npmjs.org/http-proxy-agent/-/http-proxy-agent-7.0.2.tgz",+ "integrity": "sha512-T1gkAiYYDWYx3V5Bmyu7HcfcvL7mUrTWiM6yOfa3PIphViJ/gFPbvidQ+veqSOHci/PxBcDabeUNCzpOODJZig==",+ "license": "MIT",+ "dependencies": {+ "agent-base": "^7.1.0",+ "debug": "^4.3.4"+ },+ "engines": {+ "node": ">= 14"+ }+ },"node_modules/https-proxy-agent": {"version": "7.0.6","resolved": "https://registry.npmjs.org/https-proxy-agent/-/https-proxy-agent-7.0.6.tgz","integrity": "sha512-vK9P5/iUfdl95AI+JVyUuIcVtd4ofvtrOr3HNtM2yxC9bnMbEdp3x01OhQNnjb8IJYi38VlTE3mBXwcfvywuSw==",- "dev": true,"license": "MIT","dependencies": {"agent-base": "^7.1.2",@@ -2227,6 +2667,12 @@"node": ">= 14"}},+ "node_modules/inherits": {+ "version": "2.0.4",+ "resolved": "https://registry.npmjs.org/inherits/-/inherits-2.0.4.tgz",+ "integrity": "sha512-k/vGaX4/Yla3WzyMCvTQOXYeIHvqOKtnqBduzTHpzpQZzAskKMhZ2K+EnBiSM9zGSoIFeMpXKxa4dYeZIQqewQ==",+ "license": "ISC"+ },"node_modules/ioredis": {"version": "5.11.1","resolved": "https://registry.npmjs.org/ioredis/-/ioredis-5.11.1.tgz",@@ -2268,6 +2714,30 @@"node": ">=8"}},+ "node_modules/is-stream": {+ "version": "2.0.1",+ "resolved": "https://registry.npmjs.org/is-stream/-/is-stream-2.0.1.tgz",+ "integrity": "sha512-hFoiJiTl63nn+kstHGBtewWSKnQLpyb155KHheA1l39uvtO9nWIop1p3udqPcUd/xbF1VLMO4n7OI6p7RbngDg==",+ "license": "MIT",+ "engines": {+ "node": ">=8"+ },+ "funding": {+ "url": "https://github.com/sponsors/sindresorhus"+ }+ },+ "node_modules/is-unsafe": {+ "version": "2.0.2",+ "resolved": "https://registry.npmjs.org/is-unsafe/-/is-unsafe-2.0.2.tgz",+ "integrity": "sha512-HgbIHPBH0KHHCcjLfGsCvhtPTVxjaAZlXjwdz7/GQC40SjSe4sfQsar8J5VFo8JOSbarkpV0OLG95bbaNd9aAQ==",+ "funding": [+ {+ "type": "github",+ "url": "https://github.com/sponsors/NaturalIntelligence"+ }+ ],+ "license": "MIT"+ },"node_modules/istanbul-lib-coverage": {"version": "3.2.2","resolved": "https://registry.npmjs.org/istanbul-lib-coverage/-/istanbul-lib-coverage-3.2.2.tgz",@@ -2327,6 +2797,15 @@"dev": true,"license": "MIT"},+ "node_modules/json-bigint": {+ "version": "1.0.0",+ "resolved": "https://registry.npmjs.org/json-bigint/-/json-bigint-1.0.0.tgz",+ "integrity": "sha512-SiPv/8VpZuWbvLSMtTDU8hEfrZWg/mH/nV/b4o0CYbSxu1UIQPLdwKOCIyLQX+VIPO5vrLX3i8qtqFyhdPSUSQ==",+ "license": "MIT",+ "dependencies": {+ "bignumber.js": "^9.0.0"+ }+ },"node_modules/json-schema-ref-resolver": {"version": "3.0.0","resolved": "https://registry.npmjs.org/json-schema-ref-resolver/-/json-schema-ref-resolver-3.0.0.tgz",@@ -2352,6 +2831,27 @@"integrity": "sha512-NM8/P9n3XjXhIZn1lLhkFaACTOURQXjWhV4BA/RnOv8xvgqtqpAX9IO4mRQxSx1Rlo4tqzeqb0sOlruaOy3dug==","license": "MIT"},+ "node_modules/jwa": {+ "version": "2.0.1",+ "resolved": "https://registry.npmjs.org/jwa/-/jwa-2.0.1.tgz",+ "integrity": "sha512-hRF04fqJIP8Abbkq5NKGN0Bbr3JxlQ+qhZufXVr0DvujKy93ZCbXZMHDL4EOtodSbCWxOqR8MS1tXA5hwqCXDg==",+ "license": "MIT",+ "dependencies": {+ "buffer-equal-constant-time": "^1.0.1",+ "ecdsa-sig-formatter": "1.0.11",+ "safe-buffer": "^5.0.1"+ }+ },+ "node_modules/jws": {+ "version": "4.0.1",+ "resolved": "https://registry.npmjs.org/jws/-/jws-4.0.1.tgz",+ "integrity": "sha512-EKI/M/yqPncGUUh44xz0PxSidXFr/+r0pA70+gIYhjv+et7yxM+s29Y+VGDkovRofQem0fs7Uvf4+YmAdyRduA==",+ "license": "MIT",+ "dependencies": {+ "jwa": "^2.0.1",+ "safe-buffer": "^5.0.1"+ }+ },"node_modules/light-my-request": {"version": "6.6.0","resolved": "https://registry.npmjs.org/light-my-request/-/light-my-request-6.6.0.tgz",@@ -2708,6 +3208,18 @@"dev": true,"license": "MIT"},+ "node_modules/mime": {+ "version": "3.0.0",+ "resolved": "https://registry.npmjs.org/mime/-/mime-3.0.0.tgz",+ "integrity": "sha512-jSCU7/VB1loIWBZe14aEYHU/+1UMEHoaO7qxCOVJOw9GgH72VAWppxNcjU+x9a2k3GSIBXNKxXQFqRvvZ7vr3A==",+ "license": "MIT",+ "bin": {+ "mime": "cli.js"+ },+ "engines": {+ "node": ">=10.0.0"+ }+ },"node_modules/mnemonist": {"version": "0.40.0","resolved": "https://registry.npmjs.org/mnemonist/-/mnemonist-0.40.0.tgz",@@ -2837,6 +3349,68 @@"node": ">=12.22.0"}},+ "node_modules/node-domexception": {+ "version": "1.0.0",+ "resolved": "https://registry.npmjs.org/node-domexception/-/node-domexception-1.0.0.tgz",+ "integrity": "sha512-/jKZoMpw0F8GRwl4/eLROPA3cfcXtLApP0QzLmUT/HuPCZWyB7IY9ZrMeKw2O/nFIqPQB3PVM9aYm0F312AXDQ==",+ "deprecated": "Use your platform's native DOMException instead",+ "funding": [+ {+ "type": "github",+ "url": "https://github.com/sponsors/jimmywarting"+ },+ {+ "type": "github",+ "url": "https://paypal.me/jimmywarting"+ }+ ],+ "license": "MIT",+ "engines": {+ "node": ">=10.5.0"+ }+ },+ "node_modules/node-fetch": {+ "version": "2.7.0",+ "resolved": "https://registry.npmjs.org/node-fetch/-/node-fetch-2.7.0.tgz",+ "integrity": "sha512-c4FRfUm/dbcWZ7U+1Wq0AwCyFL+3nt2bEw05wfxSz+DWpWsitgmSgYmy2dQdWyKC1694ELPqMs/YzUSNozLt8A==",+ "license": "MIT",+ "dependencies": {+ "whatwg-url": "^5.0.0"+ },+ "engines": {+ "node": "4.x || >=6.0.0"+ },+ "peerDependencies": {+ "encoding": "^0.1.0"+ },+ "peerDependenciesMeta": {+ "encoding": {+ "optional": true+ }+ }+ },+ "node_modules/node-fetch/node_modules/tr46": {+ "version": "0.0.3",+ "resolved": "https://registry.npmjs.org/tr46/-/tr46-0.0.3.tgz",+ "integrity": "sha512-N3WMsuqV66lT30CrXNbEjx4GEwlow3v6rr4mCcv6prnfwhS01rkgyFdjPNBYd9br7LpXV1+Emh01fHnq2Gdgrw==",+ "license": "MIT"+ },+ "node_modules/node-fetch/node_modules/webidl-conversions": {+ "version": "3.0.1",+ "resolved": "https://registry.npmjs.org/webidl-conversions/-/webidl-conversions-3.0.1.tgz",+ "integrity": "sha512-2JAn3z8AR6rjK8Sm8orRC0h/bcl/DqL7tRPdGZ4I1CjdF+EaMLmYxBHyXuKL849eucPFhvBoxMsflfOb8kxaeQ==",+ "license": "BSD-2-Clause"+ },+ "node_modules/node-fetch/node_modules/whatwg-url": {+ "version": "5.0.0",+ "resolved": "https://registry.npmjs.org/whatwg-url/-/whatwg-url-5.0.0.tgz",+ "integrity": "sha512-saE57nupxk6v3HY35+jzBwYa0rKSy0XR8JSxZPwgLr7ys0IBzhGviA1/TUGJLmSVqs8pb9AnvICXEuOHLprYTw==",+ "license": "MIT",+ "dependencies": {+ "tr46": "~0.0.3",+ "webidl-conversions": "^3.0.0"+ }+ },"node_modules/obliterator": {"version": "2.0.5","resolved": "https://registry.npmjs.org/obliterator/-/obliterator-2.0.5.tgz",@@ -2866,6 +3440,15 @@"node": ">=14.0.0"}},+ "node_modules/once": {+ "version": "1.4.0",+ "resolved": "https://registry.npmjs.org/once/-/once-1.4.0.tgz",+ "integrity": "sha512-lNaJgI+2Q5URQBkccEKHTQOPaXdUxnZZElQTZY0MFUAuaEqe1E+Nyvgdz/aIyNi6Z9MzO5dv1H8n58/GELp3+w==",+ "license": "ISC",+ "dependencies": {+ "wrappy": "1"+ }+ },"node_modules/p-limit": {"version": "2.3.0","resolved": "https://registry.npmjs.org/p-limit/-/p-limit-2.3.0.tgz",@@ -2915,6 +3498,21 @@"node": ">=8"}},+ "node_modules/path-expression-matcher": {+ "version": "1.6.2",+ "resolved": "https://registry.npmjs.org/path-expression-matcher/-/path-expression-matcher-1.6.2.tgz",+ "integrity": "sha512-enSlaiat05iasnzmgNxRj8reFdj3puY2QpNgP1aPIaVfT6nn9ICuPoFlKHk8EN22HcwewshO+mN2DGbkCEOtqQ==",+ "funding": [+ {+ "type": "github",+ "url": "https://github.com/sponsors/NaturalIntelligence"+ }+ ],+ "license": "MIT",+ "engines": {+ "node": ">=14.0.0"+ }+ },"node_modules/pathe": {"version": "2.0.3","resolved": "https://registry.npmjs.org/pathe/-/pathe-2.0.3.tgz",@@ -3080,6 +3678,20 @@"integrity": "sha512-tYC1Q1hgyRuHgloV/YXs2w15unPVh8qfu/qCTfhTYamaw7fyhumKa2yGpdSo87vY32rIclj+4fWYQXUMs9EHvg==","license": "MIT"},+ "node_modules/readable-stream": {+ "version": "3.6.2",+ "resolved": "https://registry.npmjs.org/readable-stream/-/readable-stream-3.6.2.tgz",+ "integrity": "sha512-9u/sniCrY3D5WdsERHzHE4G2YCXqoG5FTHUiCC4SIbr6XcLZBY05ya9EKjYek9O5xOAwjGq+1JdGBAS7Q9ScoA==",+ "license": "MIT",+ "dependencies": {+ "inherits": "^2.0.3",+ "string_decoder": "^1.1.1",+ "util-deprecate": "^1.0.1"+ },+ "engines": {+ "node": ">= 6"+ }+ },"node_modules/real-require": {"version": "0.2.0","resolved": "https://registry.npmjs.org/real-require/-/real-require-0.2.0.tgz",@@ -3144,6 +3756,27 @@"node": ">=10"}},+ "node_modules/retry": {+ "version": "0.13.1",+ "resolved": "https://registry.npmjs.org/retry/-/retry-0.13.1.tgz",+ "integrity": "sha512-XQBQ3I8W1Cge0Seh+6gjj03LbmRFWuoszgK9ooCpwYIrhhoO80pfq4cUkU5DkknwfOfFteRwlZ56PYOGYyFWdg==",+ "license": "MIT",+ "engines": {+ "node": ">= 4"+ }+ },+ "node_modules/retry-request": {+ "version": "9.1.0",+ "resolved": "https://registry.npmjs.org/retry-request/-/retry-request-9.1.0.tgz",+ "integrity": "sha512-FILyVbis+DTo3KRbtKceqpj1595wIF+XQFW/+AVOBdCQmxwNDgcNXXr2FNM0Ej2qD7zVXbJGfH7lo4jB0wwhKA==",+ "license": "MIT",+ "dependencies": {+ "extend": "^3.0.2"+ },+ "engines": {+ "node": ">=22"+ }+ },"node_modules/reusify": {"version": "1.1.0","resolved": "https://registry.npmjs.org/reusify/-/reusify-1.1.0.tgz",@@ -3204,6 +3837,26 @@"tslib": "^2.1.0"}},+ "node_modules/safe-buffer": {+ "version": "5.2.1",+ "resolved": "https://registry.npmjs.org/safe-buffer/-/safe-buffer-5.2.1.tgz",+ "integrity": "sha512-rp3So07KcdmmKbGvgaNxQSJr7bGVSVk5S9Eq1F+ppbRo70+YeaDxkw5Dd8NPN+GD6bjnYm2VuPuCXmpuYvmCXQ==",+ "funding": [+ {+ "type": "github",+ "url": "https://github.com/sponsors/feross"+ },+ {+ "type": "patreon",+ "url": "https://www.patreon.com/feross"+ },+ {+ "type": "consulting",+ "url": "https://feross.org/support"+ }+ ],+ "license": "MIT"+ },"node_modules/safe-regex2": {"version": "5.1.1","resolved": "https://registry.npmjs.org/safe-regex2/-/safe-regex2-5.1.1.tgz",@@ -3347,6 +4000,21 @@"dev": true,"license": "MIT"},+ "node_modules/stream-events": {+ "version": "1.0.5",+ "resolved": "https://registry.npmjs.org/stream-events/-/stream-events-1.0.5.tgz",+ "integrity": "sha512-E1GUzBSgvct8Jsb3v2X15pjzN1tYebtbLaMg+eBOUOAxgbLoSbT2NS91ckc5lJD1KfLjId+jXJRgo0qnV5Nerg==",+ "license": "MIT",+ "dependencies": {+ "stubs": "^3.0.0"+ }+ },+ "node_modules/stream-shift": {+ "version": "1.0.3",+ "resolved": "https://registry.npmjs.org/stream-shift/-/stream-shift-1.0.3.tgz",+ "integrity": "sha512-76ORR0DO1o1hlKwTbi/DM3EXWGf3ZJYO8cXX5RJwnul2DEg2oyoZyjLNoQM8WsvZiFKCRfC1O0J7iCvie3RZmQ==",+ "license": "MIT"+ },"node_modules/streamx": {"version": "2.28.1","resolved": "https://registry.npmjs.org/streamx/-/streamx-2.28.1.tgz",@@ -3359,6 +4027,15 @@"text-decoder": "^1.1.0"}},+ "node_modules/string_decoder": {+ "version": "1.3.0",+ "resolved": "https://registry.npmjs.org/string_decoder/-/string_decoder-1.3.0.tgz",+ "integrity": "sha512-hkRX8U1WjJFd8LsDJ2yQ/wWWxaopEsABU1XfkM8A+j0+85JAGppt16cr1Whg6KIbb4okU6Mql6BOj+uup/wKeA==",+ "license": "MIT",+ "dependencies": {+ "safe-buffer": "~5.2.0"+ }+ },"node_modules/string-width": {"version": "4.2.3","resolved": "https://registry.npmjs.org/string-width/-/string-width-4.2.3.tgz",@@ -3387,6 +4064,27 @@"node": ">=8"}},+ "node_modules/strnum": {+ "version": "2.5.1",+ "resolved": "https://registry.npmjs.org/strnum/-/strnum-2.5.1.tgz",+ "integrity": "sha512-UM4nTLWzQiDBseVxUGxN0wJzIk0UU89Qi7pKXz9qISo+lhviJikTuikBsK/oFRlpvYHvSdz0TVoLyQ+sEpYwxA==",+ "funding": [+ {+ "type": "github",+ "url": "https://github.com/sponsors/NaturalIntelligence"+ }+ ],+ "license": "MIT",+ "dependencies": {+ "anynum": "^1.0.1"+ }+ },+ "node_modules/stubs": {+ "version": "3.0.0",+ "resolved": "https://registry.npmjs.org/stubs/-/stubs-3.0.0.tgz",+ "integrity": "sha512-PdHt7hHUJKxvTCgbKX9C1V/ftOcjJQgz8BZwNfV5c4B6dcGqlpelTbJ999jBGZ2jYiPAwcX5dP6oBwVlBlUbxw==",+ "license": "MIT"+ },"node_modules/supports-color": {"version": "8.1.1","resolved": "https://registry.npmjs.org/supports-color/-/supports-color-8.1.1.tgz",@@ -3416,6 +4114,39 @@"streamx": "^2.28.1"}},+ "node_modules/teeny-request": {+ "version": "11.1.1",+ "resolved": "https://registry.npmjs.org/teeny-request/-/teeny-request-11.1.1.tgz",+ "integrity": "sha512-I5OLOkPN3QDN2l1H/eGueuKaq32CdAcXt91WOF/bOfadtZD1WQ8/Fk28WsqDcGjIyhAW/GQDagYhVEjhuZUFyQ==",+ "license": "Apache-2.0",+ "dependencies": {+ "http-proxy-agent": "^7.0.0",+ "https-proxy-agent": "^7.0.1",+ "node-fetch": "^3.3.2",+ "stream-events": "^1.0.5"+ },+ "engines": {+ "node": ">=22"+ }+ },+ "node_modules/teeny-request/node_modules/node-fetch": {+ "version": "3.3.2",+ "resolved": "https://registry.npmjs.org/node-fetch/-/node-fetch-3.3.2.tgz",+ "integrity": "sha512-dRB78srN/l6gqWulah9SrxeYnxeddIG30+GOqK/9OlLVyLg3HPnr6SqOWTWOXKRwC2eGYCkZ59NNuSgvSrpgOA==",+ "license": "MIT",+ "dependencies": {+ "data-uri-to-buffer": "^4.0.0",+ "fetch-blob": "^3.1.4",+ "formdata-polyfill": "^4.0.10"+ },+ "engines": {+ "node": "^12.20.0 || ^14.13.1 || >=16.0.0"+ },+ "funding": {+ "type": "opencollective",+ "url": "https://opencollective.com/node-fetch"+ }+ },"node_modules/teex": {"version": "1.0.1","resolved": "https://registry.npmjs.org/teex/-/teex-1.0.1.tgz",@@ -4060,6 +4791,26 @@"integrity": "sha512-iwDZqg0QAGrg9Rav5H4n0M64c3mkR59cJ6wQp+7C4nI0gsmExaedaYLNO44eT4AtBBwjbTiGPMlt2Md0T9H9JQ==","license": "MIT"},+ "node_modules/util-deprecate": {+ "version": "1.0.2",+ "resolved": "https://registry.npmjs.org/util-deprecate/-/util-deprecate-1.0.2.tgz",+ "integrity": "sha512-EPD5q1uXyFxJpCrLnCc1nHnq3gOa6DZBocAIiI2TaSCA7VCJ1UJDMagCzIkXNsUYfD1daK//LTEQ8xiIbrHtcw==",+ "license": "MIT"+ },+ "node_modules/uuid": {+ "version": "9.0.1",+ "resolved": "https://registry.npmjs.org/uuid/-/uuid-9.0.1.tgz",+ "integrity": "sha512-b+1eJOlsR9K8HJpow9Ok3fiWOWSIcIzXodvv0rQjVoOVNpWMpxf1wZNpt4y9h10odCNrqnYp1OBzRktckBe3sA==",+ "deprecated": "uuid@10 and below is no longer supported. For ESM codebases, update to uuid@latest. For CommonJS codebases, use uuid@11 (but be aware this version will likely be deprecated in 2028).",+ "funding": [+ "https://github.com/sponsors/broofa",+ "https://github.com/sponsors/ctavan"+ ],+ "license": "MIT",+ "bin": {+ "uuid": "dist/bin/uuid"+ }+ },"node_modules/vite": {"version": "8.2.2","resolved": "https://registry.npmjs.org/vite/-/vite-8.2.2.tgz",@@ -4228,6 +4979,15 @@}}},+ "node_modules/web-streams-polyfill": {+ "version": "3.3.3",+ "resolved": "https://registry.npmjs.org/web-streams-polyfill/-/web-streams-polyfill-3.3.3.tgz",+ "integrity": "sha512-d2JWLCivmZYTSIoge9MsgFCZrt571BikcWGYkjC1khllbTeDlGqZ2D8vD8E/lJa8WGWbb7Plm8/XJYV7IJHZZw==",+ "license": "MIT",+ "engines": {+ "node": ">= 8"+ }+ },"node_modules/webidl-conversions": {"version": "7.0.0","resolved": "https://registry.npmjs.org/webidl-conversions/-/webidl-conversions-7.0.0.tgz",@@ -4287,6 +5047,12 @@"url": "https://github.com/chalk/wrap-ansi?sponsor=1"}},+ "node_modules/wrappy": {+ "version": "1.0.2",+ "resolved": "https://registry.npmjs.org/wrappy/-/wrappy-1.0.2.tgz",+ "integrity": "sha512-l4Sp/DRseor9wL6EvV2+TuQn63dMkPjZ/sp9XkghTEbV9KlPS1xUsZ3u7/IQO4wxtcFB4bgpQPRcR3QCvezPcQ==",+ "license": "ISC"+ },"node_modules/ws": {"version": "8.21.3","resolved": "https://registry.npmjs.org/ws/-/ws-8.21.3.tgz",@@ -4308,6 +5074,21 @@}}},+ "node_modules/xml-naming": {+ "version": "0.3.0",+ "resolved": "https://registry.npmjs.org/xml-naming/-/xml-naming-0.3.0.tgz",+ "integrity": "sha512-ghig2TBE/H11aOVgmahA3MhimvkBr6JIYknH/Dhdk10nXwdbIqBJsbfMxpvFPG8bAw77gN29aQWvKpmVoPlvPQ==",+ "funding": [+ {+ "type": "github",+ "url": "https://github.com/sponsors/NaturalIntelligence"+ }+ ],+ "license": "MIT",+ "engines": {+ "node": ">=16.0.0"+ }+ },"node_modules/y18n": {"version": "5.0.8","resolved": "https://registry.npmjs.org/y18n/-/y18n-5.0.8.tgz",@@ -4360,6 +5141,18 @@"node": ">=12"}},+ "node_modules/yocto-queue": {+ "version": "0.1.0",+ "resolved": "https://registry.npmjs.org/yocto-queue/-/yocto-queue-0.1.0.tgz",+ "integrity": "sha512-rVksvsnNCdJ/ohGc6xgPwyN8eheCxsiLM8mxuE/t/mOVqJewPuO1miLpTHQiRgTKCLexL4MeAFVagts7HmNZ2Q==",+ "license": "MIT",+ "engines": {+ "node": ">=10"+ },+ "funding": {+ "url": "https://github.com/sponsors/sindresorhus"+ }+ },"node_modules/zod": {"version": "4.5.4","resolved": "https://registry.npmjs.org/zod/-/zod-4.5.4.tgz",diff --git a/backend/package.json b/backend/package.jsonindex b236dab6b..59353f2e0 100644--- a/backend/package.json+++ b/backend/package.json@@ -30,6 +30,7 @@"dependencies": {"@fastify/cors": "^10.1.0","@fastify/multipart": "^9.4.0",+ "@google-cloud/storage": "8.2.0","@noble/curves": "^2.4.0","@noble/hashes": "^2.4.0","@prisma/client": "^5.22.0",diff --git a/backend/pnpm-lock.yaml b/backend/pnpm-lock.yamlindex 300a8616a..e97325fea 100644--- a/backend/pnpm-lock.yaml+++ b/backend/pnpm-lock.yaml@@ -14,6 +14,9 @@ importers:'@fastify/multipart':specifier: ^9.4.0version: 9.4.0+ '@google-cloud/storage':+ specifier: 8.2.0+ version: 8.2.0'@noble/curves':specifier: ^2.4.0version: 2.4.0@@ -34,10 +37,10 @@ importers:version: 5.11.3http-proxy:specifier: ^1.18.1- version: 1.18.1([email protected]([email protected]))+ version: 1.18.1ioredis:specifier: ^5.11.1- version: 5.11.1([email protected])+ version: 5.11.1ws:specifier: ^8.21.0version: 8.21.3@@ -60,6 +63,9 @@ importers:esbuild:specifier: ^0.27.2version: 0.27.7+ mongodb-memory-server-core:+ specifier: ^10.4.3+ version: 10.4.3prisma:specifier: ^5.22.0version: 5.22.0@@ -438,6 +444,22 @@ packages:'@fastify/[email protected]':resolution: {integrity: sha512-INS+6gh91cLUjB+PVHfu1UqcB76Sqtpyp7bnL+FYojhjygvOPA9ctiD/JDKsyD9Xgu4hUhCSJBPig/w7duNajw==}+ '@google-cloud/[email protected]':+ resolution: {integrity: sha512-l+x6YObHGTuqBCMvC0SXo3Cnyqg4FkWWKYRptf46PACHJ5GAUuhsd2b3wphgGrg1ybs/LAb+q5MnUTuG/3+v7w==}+ engines: {node: '>=22'}++ '@google-cloud/[email protected]':+ resolution: {integrity: sha512-PV9oy7VpQRXLuqKuU5RSOHFQyWgvw2sT9MoTGykja9j6c9pv5+ttKTJiFsccu500YYIGiz8JCOsb60PfKmiV/w==}+ engines: {node: '>=22'}++ '@google-cloud/[email protected]':+ resolution: {integrity: sha512-/+RvLJ5u+WhGay6Z3aY6OApDQmNqq1427Mmt7Eov9kYp69gdUiGSwFnygeTxfz69XBtYZLAnWikGMIoFXtKt+A==}+ engines: {node: '>=22'}++ '@google-cloud/[email protected]':+ resolution: {integrity: sha512-7ckgSjeEprV92VrlLjpYFA3PFerflvFtF7Ea86oQXGNCprGZq5rtpAVK0zgWnCy+44mLjms42M7MiWa433gz2A==}+ engines: {node: '>=22'}+'@ioredis/[email protected]':resolution: {integrity: sha512-UmeW7z4LfctwoQ5wkhVzgq8tXkreED2xZGpX+Bg+zA+WJFZCT6c062AfCK/Dfk81xZnnwdhJCUMkitihRaoC2Q==}@@ -451,6 +473,9 @@ packages:'@jridgewell/[email protected]':resolution: {integrity: sha512-zzNR+SdQSDJzc8joaeP8QQoCQr8NuYx2dIIytl1QeBEZHJ9uW6hebsrYgbz8hJwUQao3TWCMtmfV8Nu1twOLAw==}+ '@mongodb-js/[email protected]':+ resolution: {integrity: sha512-D4CQtk9IwjCLAvCf1xvHEod3960q8XMUzfmdRU9qjUNlHnesGuTOvJcOTaPm9koZ1caUKA2aTbszZiAkcmSgmg==}+'@noble/[email protected]':resolution: {integrity: sha512-P4/62zrgfH33CneE3Dn4WhJVA22YUU0eR51wKIan4NVRvwsA0YnPTwWGpNbpuacSujmSFLvyzpyuR30+fbq2Ew==}engines: {node: '>= 20.19.0'}@@ -459,6 +484,9 @@ packages:resolution: {integrity: sha512-X5XaVWZIBCT7HHZGm5I7ZQXDwLG+bGXuSrMQAW+7Zvl87h1kmc1ZB1VSRJcpUfoUrGQp4Fkoxm5kZ+Ms+aW+eA==}engines: {node: '>= 20.19.0'}+ '@nodable/[email protected]':+ resolution: {integrity: sha512-LsS/DjHr+uDM647Gru/cA8+J3a3HfhttwCKLyuoyN7yXTFCxKBtSgMQBvrW9yNPa2/zDRUNuGPaH5QUFoa4arQ==}+'@oxc-project/[email protected]':resolution: {integrity: sha512-rDS5/31E9HfPl/CIzGrn0DOlvBbXFseQ5URJ9sYMfstbKLD/c6Gm9vmRzRGDdAXyOIL4zmO37lc9RIwYqVruZw==}@@ -606,6 +634,12 @@ packages:'@types/[email protected]':resolution: {integrity: sha512-6oYBAi5ikg4Pl+kGsoYtawUMBT2zZMCvPNF7pVLnHZfd1zf38DRiWn/gT01RYCdUqkv7Fhr+C9ot4/tb+2sVvA==}+ '@types/[email protected]':+ resolution: {integrity: sha512-CiJJvcRtIgzadHCYXw7dqEnMNRjhGZlYK05Mj9OyktqV8uVT8fD2BFOB7S1uwBE3Kj2Z+4UyPmFw/Ixgw/LAlA==}++ '@types/[email protected]':+ resolution: {integrity: sha512-coYR071JRaHa+xoEvvYqvnIHaVqaYrLPbsufM9BF63HkwI5Lgmy2QR8Q5K/lYDYo5AK82wOvSOS0UsLTpTG7uQ==}+'@types/[email protected]':resolution: {integrity: sha512-ThVF6DCVhA8kUGy+aazFQ4kXQ7E1Ty7A3ypFOe0IcJV8O/M511G99AW24irKrW56Wt44yG9+ij8FaqoBGkuBXg==}@@ -647,9 +681,17 @@ packages:'@vitest/[email protected]':resolution: {integrity: sha512-zTCVGpyFsGWBhllOyKlTw/vnr6D9qxsfSDyfbyZmTyjHw5N/VuvzHpHoQjm2ZJzn4RJgx5w4r7V0er69CmLgPQ==}+ resolution: {integrity: sha512-h8lQ8tacZYnR3vNQTgibj+tODHI5/+l06Au2Pcriv/Gmet0eaj4TwWH41sO9wnHDiQsEj19q0drzdWdeAHtweg==}+ engines: {node: '>=6.5'}+resolution: {integrity: sha512-2BjRTZxTPvheOvGbBslFSYOUkr+SjPtOnrLP33f+VIWLzezQpZcqVg7ja3L4dBXmzzgwT+a029jRx5PCi3JuiA==}+ resolution: {integrity: sha512-MnA+YT8fwfJPgBx3m60MNqakm30XOkyIoH1y6huTQvC0PwZG7ki8NacLBcrPbNoo8vEZy7Jpuk7+jMO+CUovTQ==}+ engines: {node: '>= 14'}+resolution: {integrity: sha512-8iUql50EUR+uUcdRQ3HDqa6EVyo3docL8g5WJ3FNcWmu62IbkGUue/pEyLBW8VGKKucTPgqeks4fIU1DA4yowQ==}peerDependencies:@@ -669,6 +711,9 @@ packages:resolution: {integrity: sha512-zbB9rCJAT1rbjiVDb2hqKFHNYLxgtk8NURxZ3IZwD3F6NtxbXZQCnnSi1Lkx+IDohdPlFp222wVALIheZJQSEg==}engines: {node: '>=8'}+ resolution: {integrity: sha512-N6//FLET/tXYNM/F6ABca1oH6fWB+KlTt909Le28WMDBk8oaT4vY17DCrwg2MvmuqUKt3Ni4N5dGJ/EoBgcO6A==}+resolution: {integrity: sha512-Izi8RQcffqCeNVgFigKli1ssklIbpHnCYc6AknXGYoB6grJqyeby7jv12JUQgmTAnIDnbck1uxksT4dzN3PWBA==}engines: {node: '>=12'}@@ -676,6 +721,12 @@ packages:resolution: {integrity: sha512-fvpl29helSO2w/z7utIbrkNXILdrLwDwAMH2I/zPKlGf5244+gf+B4cyS1sANcrPY2h+hWCGSgC8N61s/+AF9A==}+ resolution: {integrity: sha512-1A94B18jkJ3DYq284ohPxoXbfTA5HsQ7/Mf4DEhcyLx3Bz27Rh59iScbB6EPiP+B+joue6YCxcMXSbFC1tZKwA==}++ resolution: {integrity: sha512-wfr/jstw9xNi/0teMHrRW7dsz3Lt5ARhYNZ2ewpadnhaIp5mbALhOAP+EAdsC7t4Z6wqsDVv9+W6gm1Dk9mEyw==}+resolution: {integrity: sha512-kNOjDqAh7px0XWNI+4QbzoiR/nTkHAWNud2uvnJquD1/x5a7EQZMJT0AczqK0Qn67oY/TTQ1LbUKajZpp3I9tQ==}engines: {node: '>=8.0.0'}@@ -683,6 +734,68 @@ packages:resolution: {integrity: sha512-g2tQ7LE7oOSqDfwEm3M+ZCMTJc7KiZCdJ4UwyZJb5ckTKyYu50OYmvv0mCFXPuYXoM4zkSt8zM9XQ9KCvxA74A==}+ resolution: {integrity: sha512-dpfcF9fDNR6++cthXR67iyhgqWy9CBouAvIWhIntzBG6cvK/cnIPiZQjBwi/ZqjjBEDGfoNDtmB0kTjroOJ3pQ==}+ peerDependencies:+ react-native-b4a: '*'+ peerDependenciesMeta:+ react-native-b4a:+ optional: true++ resolution: {integrity: sha512-AIPKioV7/Y/8KfZ3AAhjPJxLLbY49S64Ym5DakZlUg75qQiTgUq9hEJoEwa4eUezPUlXRy/i5NpsKvo9jgKmoA==}+ peerDependencies:+ bare-abort-controller: '*'+ peerDependenciesMeta:+ bare-abort-controller:+ optional: true++ resolution: {integrity: sha512-MPC2eyrpbk3A873sK4y6rk+Iv4o2enxTjHZ8zH3HO0mjrpm5XjnguY2XmfidIsDV6vnjpbMBKUAJpV0ISD2SsQ==}+ engines: {bare: '>=1.28.0'}+ peerDependencies:+ bare-buffer: '*'+ peerDependenciesMeta:+ bare-buffer:+ optional: true++ resolution: {integrity: sha512-ZyKbsuuqK6Ag0K8pX6V5Txq6XeJRvY+wXucnFGRjiyVYP9YWDpIQugk/b+enRYrEYBJaqLzghRQpXPMR7341Nw==}++ resolution: {integrity: sha512-PcrQ8lVLbiJscNm1Kez+Yp4Gy4AHGcN1lzwjvf5NybWen7VvEgUfyfnXYJ2zNqWnzOfCb1Abq6lH8ti0syQszA==}+ peerDependencies:+ bare-abort-controller: '*'+ bare-buffer: '*'+ bare-events: '*'+ peerDependenciesMeta:+ bare-abort-controller:+ optional: true+ bare-buffer:+ optional: true+ bare-events:+ optional: true++ resolution: {integrity: sha512-iM9qJCruvpt2rPaLsrumVDru9pogI7PHziHIa9kTNRFt8C8HuSa+kI9kFezK+NvHEFnnz71rKGZ1EAilq/3V/Q==}++ resolution: {integrity: sha512-AKpaYlHn8t4SVbOHCy+b5+KKgvR4vrsD8vbvrbiQJps7fKDTkjkDry6ji0rUJjC0kzbNePLwzxq8iypo41qeWA==}++ resolution: {integrity: sha512-Ko0uX15oIUS7wJ3Rb30Fs6SkVbLmPBAKdlm7q9+ak9bbIeFf0MwuBsQV6z7+X768/cHsfg+WlysDWJcmthjsjQ==}++ resolution: {integrity: sha512-WIsKqkSC0ABoBJuT1LEX+2HEvNmNKKgnTAyd0fL8qzK4SH2i9NXg+t08YtdZp/V9IZ33cxe3iV4yM0qg8lMQng==}+ engines: {node: '>=16.20.1'}++ resolution: {integrity: sha512-zRpUiDwd/xk6ADqPMATG8vc9VPrkck7T07OIx0gnjmJAnHnTVXNQG3vfvWNuiZIkwu9KrKdA1iJKfsfTVxE6NA==}++ resolution: {integrity: sha512-Gmy6FhYlCY7uOElZUSbxo2UCDH8owEk996gkbrpsgGtrJLM3J7jGxl9Ic7Qwwj4ivOE5AWZWRMecDdF7hqGjFA==}+ engines: {node: '>=10'}+resolution: {integrity: sha512-NUPRluOfOiTKBKvWPtSD4PhFvWCqOi0BGStNWs57X9js7XGTprSmFoz5F0tWhR4WPjNeR9jXqdC7/UpSJTnlRg==}engines: {node: '>=18'}@@ -706,6 +819,9 @@ packages:resolution: {integrity: sha512-dOy+3AuW3a2wNbZHIuMZpTcgjGuLU/uBL/ubcZF9OXbDo8ff4O8yVp5Bf0efS8uEoYo5q4Fx7dY9OgQGXgAsQA==}+ resolution: {integrity: sha512-W9pAhw0ja1Edb5GVdIF1mjZw/ASI0AlShXM83UUGe2DVr5TdAPEA1OA8m/g8zWp9x6On7gqufY+FatDbC3MDQg==}+resolution: {integrity: sha512-TZ0CEhyzvFjgtAvHTusDMgj7wNdihCh7LLLrzdUOXIhdlnL2JBBGA9eJxR24rtqgmdjh3OA3hrN1rCHj6HM8qA==}engines: {node: '>=18'}@@ -718,6 +834,10 @@ packages:resolution: {integrity: sha512-ei8Aos7ja0weRpFzJnEA9UHJ/7XQmqglbRwnf2ATjcB9Wq874VKH9kfjjirM6UhU2/E5fFYadylyhFldcqSidQ==}engines: {node: '>=18'}+ resolution: {integrity: sha512-0R9ikRb668HB7QDxT1vkpuUBtqc53YyAwMwGeUFKRojY/NWKvdZ+9UYtRfGmhqNbRkTSVpMbmyhXipFFv2cb/A==}+ engines: {node: '>= 12'}+resolution: {integrity: sha512-RGwwWnwQvkVfavKVt22FGLw+xYSdzARwm0ru6DhTVA3umU5hZc28V3kO4stgYryrTlLpuvgI9GiijltAjNbcqA==}engines: {node: '>=6.0'}@@ -743,9 +863,18 @@ packages:resolution: {integrity: sha512-nI4U3TottKAcAD9LLud4Cb7b2QztQMUEfHbvhTH09bqXTxnSie8WnjPALV/WMCrJZ6UV/qHJ6L03OqO3LcdYZw==}engines: {node: '>=12'}+ resolution: {integrity: sha512-M3BmBhwJRZsSx38lZyhE53Csddgzl5R7xGJNk7CVddZD6CcmwMCH8J+7AprIrQKH7TonKxaCjcv27Qmf+sQ+oA==}++ resolution: {integrity: sha512-nagl3RYrbNv6kQkeJIpt6NJZy8twLB/2vtz6yN9Z4vRKHN4/QZJIEbqohALSgwKdnksuY3k5Addp5lg8sVoVcQ==}+resolution: {integrity: sha512-MSjYzcWNOA0ewAHpz0MxpYFvwg6yjy1NG3xteoqz644VCo/RPgnr1/GGt+ic3iJTzQ8Eu3TdM14SawnVUmGE6A==}+ resolution: {integrity: sha512-ooEGc6HP26xXq/N+GCGOT0JKCLDGrq2bQUZrQ7gyrJiZANJ/8YDTxTpQBXGMn+WbIQXNVpyWymm7KYVICQnyOg==}+resolution: {integrity: sha512-poHGpORABojJJucnV9KbOavETW8lBVnphkW77ER5/BQ5Fz7oXSoCNek7IH3vR5nRjdsEz926ibFYX8KtLQmdyw==}@@ -766,19 +895,32 @@ packages:resolution: {integrity: sha512-7RUKfXgSMMkzt6ZuXmqapOurLGPPfgj6l9uRZ7lRGolvk0y2yocc35LdcxKC5PQZdn2DMqioAQ2NoWcrTKmm6g==}+ resolution: {integrity: sha512-i/2XbnSz/uxRCU6+NdVJgKWDTM427+MqYbkQzD321DuCQJUqOuJKIA0IM2+W2xtYHdKOmZ4dR6fExsd4SXL+WQ==}+ engines: {node: '>=6'}+resolution: {integrity: sha512-8guHBZCwKnFhYdHr2ysuRWErTwhoN2X8XELRlrRwpmfeY2jjuUN4taQMsULKUVo1K4DvZl+0pgfyoysHxvmvEw==}+ resolution: {integrity: sha512-LUd5euvbMLpwOF8m6ivPCbhQeSiYVNb8Vs0fQ8QjXo0JTkEHpz8pxdQf0gStltaPpw0Cca8b39KxvK9cfKRiAw==}+resolution: {integrity: sha512-KfYbmpRm0VbLjEvVa9yGwCi9GI34xvi7A/HXYWQO65CSD2u3MczUJSuwXKFIxlGsgBQizV9q5J9NHj4VG0n+pA==}engines: {node: '>=12.0.0'}+ resolution: {integrity: sha512-fjquC59cD7CyW6urNXK0FBufkZcoiGG80wTuPujX590cB5Ttln20E2UB4S/WARVqhXffZl2LNgS+gQdPIIim/g==}+resolution: {integrity: sha512-WKgKWg5eUxvRZGwW8FvfbaH7AXSh2cL+3j5fMGzUMCxWBJ3dV3a7Wz8y2f/uQ0e3B6WmodD3oS54jTQ9HVTIIg==}resolution: {integrity: sha512-f3qQ9oQy9j2AhBe/H9VC91wLmKBCCU/gDOnKNAYG5hswO7BLKj09Hc5HYNz9cGI++xlpDCIgDaitVs03ATR84Q==}+ resolution: {integrity: sha512-/d9sfos4yxzpwkDkuN7k2SqFKtYNmCTzgfEpz82x34IM9/zc8KGxQoXg1liNC/izpRM/MBdt44Nmx41ZWqk+FQ==}+resolution: {integrity: sha512-eRSayARSbbwlBjpP4vnTTIRD5QPcIrmihPxDeN1DtKnHPg66UuJLx+8hlK1kaFdjvzyQ/dzALoi4vwAQ+T+iZA==}@@ -791,6 +933,13 @@ packages:resolution: {integrity: sha512-TyGmBcbDTZXcb2cj5MV89DrF42DKvb3y5DDUNh95iO+IMeAzMkVSxK1PZRrRIpc9yg8U2GhGdbofNa0LS/a4Bw==}+ resolution: {integrity: sha512-pIM/1n3ntFXKYrUZwW7QCK0gAW7XY+wzj1YMIV3tLDvPj/V+zTGJK5e3/4WJfwj0qWw2ElNXiTixda/R+3YSug==}++ resolution: {integrity: sha512-R9iDuNrQYeQut46cn2r2wHKn4HYzVDvDm5J1wW+koZewykv0yuO2HChTYeZtrULyHIDM9cj9TUXloCsueCQUog==}+ hasBin: true+resolution: {integrity: sha512-FAIDA8eovSt5qcDgcBvDuX/v0Cjz0ohGhENZ/wpc3y+oZCY2afZ9Baqql3g/lC+OHRnciQol4ww7tuthOb9idw==}@@ -809,10 +958,22 @@ packages:picomatch:optional: true+ resolution: {integrity: sha512-7yAQpD2UMJzLi1Dqv7qFYnPbaPx7ZfFK6PiIxQ4PfkGPyNyl2Ugx+a/umUonmKqjhM4DnfbMvdX6otXq83soQQ==}+ engines: {node: ^12.20 || >= 14.13}++ resolution: {integrity: sha512-wXZV5emFEjrridIgED11OoUKLxiYjAcqot/NJdAkOhlJ+vGzwhOAfcG5OX1jP+S0PcjEn8bdMJv+g2jwQ3Onig==}+ engines: {node: '>=8'}+resolution: {integrity: sha512-f2JHn75x2JlwUwLenZypgczR7YWMb/uO9BvUXtus+JMgkbIkLADd38cI4EiV+OQqrGo1Zlq6V8wnqMJ8e62wUQ==}engines: {node: '>=20'}+ resolution: {integrity: sha512-PpOwAdQ/YlXQ2vj8a3h8IipDuYRi3wceVQQGYWxNINccq40Anw7BlsEXCMbt1Zt+OLA6Fq9suIpIWD0OsnISlw==}+ engines: {node: '>=8'}+resolution: {integrity: sha512-y5rN/uOsadFT/JfYwhxRS5R7Qce+g3zG97+JrtFZlC9klX/W5hD7iiLzScI4nZqUS7DNUdhPgw4xI8W2LuXlUw==}engines: {node: '>=4.0'}@@ -822,26 +983,64 @@ packages:debug:optional: true+ resolution: {integrity: sha512-buewHzMvYL29jdeQTVILecSaZKnt/RJWjoZCF5OW60Z67/GmSLBkOFM7qh1PI3zFNtJbaZL5eQu1vLfazOwj4g==}+ engines: {node: '>=12.20.0'}+resolution: {integrity: sha512-5xoDfX+fL7faATnagmWPpbFtwh/R77WmMMqqHGS65C3vvB0YHrgF+B1YmZ3441tMj5n63k0212XNoJwzlhffQw==}engines: {node: ^8.16.0 || ^10.6.0 || >=11.0.0}os: [darwin]+ resolution: {integrity: sha512-LDODD4TMYx7XXdpwxAVRAIAuB0bzv0s+ywFonY46k126qzQHT9ygyoa9tncmOiQmmDrik65UYsEkv3lbfqQ3yQ==}+ engines: {node: '>=14'}++ resolution: {integrity: sha512-a4tiq7E0/5fTjxPAaH4jpjkSv/uCaU2p5KC6HVGrvl0cDjA8iBZv4vv1gyzlmK0ZUKqwpOyQMKzZQe3lTit77A==}+ engines: {node: '>=14'}+resolution: {integrity: sha512-DyFP3BM/3YHTQOCUL/w0OZHR0lpKeGrxotcHWcqNEdnltqFwXVfhEBQ94eIo34AfQpo0rGki4cyIiftY06h2Fg==}engines: {node: 6.* || 8.* || >= 10.*}+ resolution: {integrity: sha512-Jb6Z0+nvECVz+2lzSMt9u98UsoakXxA2HGHMCxh+so3n90XgYWkq5dur19JAJV7ONiJY22yBTyJB1TSkvPq9Ng==}+ engines: {node: '>=14'}++ resolution: {integrity: sha512-NEgUnEcBiP5HrPzufUkBzJOD/Sxsco3rLNo1F1TNf7ieU8ryUzBhqba8r756CjLX7rn3fHl6iLEwPYuqpoKgQQ==}+ engines: {node: '>=14'}++ resolution: {integrity: sha512-pCcEwRi+TKpMlxAQObHDQ56KawURgyAf6jtIY046fJ5tIv3zDe/LEIubckAO8fj6JnAxLdmWkUfNyulQ2iKdEw==}+ engines: {node: '>=14.0.0'}+resolution: {integrity: sha512-EykJT/Q1KjTWctppgIAgfSO0tKVuZUjhgMr17kqTumMl6Afv3EISleU7qZUzoXDFTAHTDC4NOoG/ZxU3EvlMPQ==}engines: {node: '>=8'}+ resolution: {integrity: sha512-kig+rMn/QOVRvr7c86gQ8lWXq+Hkv6CbAH1hLu+RG338StTpE8Z0b44SDVaqVu7HGKf27frdmUYEs9hTUX/cLQ==}+resolution: {integrity: sha512-H2iMtd0I4Mt5eYiapRdIDjp+XzelXQ0tFE4JS7YFwFevXXMmOp9myNrUvCg0D6ws8iqkRPBfKHgbwig1SmlLfg==}+ resolution: {integrity: sha512-T1gkAiYYDWYx3V5Bmyu7HcfcvL7mUrTWiM6yOfa3PIphViJ/gFPbvidQ+veqSOHci/PxBcDabeUNCzpOODJZig==}+ engines: {node: '>= 14'}+resolution: {integrity: sha512-7mz/721AbnJwIVbnaSv1Cz3Am0ZLT/UBwkC92VlxhXv/k/BBQfM2fXElQNC27BVGr0uwUpplYPQM9LnaBMR5NQ==}engines: {node: '>=8.0.0'}+ resolution: {integrity: sha512-vK9P5/iUfdl95AI+JVyUuIcVtd4ofvtrOr3HNtM2yxC9bnMbEdp3x01OhQNnjb8IJYi38VlTE3mBXwcfvywuSw==}+ engines: {node: '>= 14'}++ resolution: {integrity: sha512-k/vGaX4/Yla3WzyMCvTQOXYeIHvqOKtnqBduzTHpzpQZzAskKMhZ2K+EnBiSM9zGSoIFeMpXKxa4dYeZIQqewQ==}+resolution: {integrity: sha512-ehuGcf94bQXhfagULNXrJdfnWO38v070jxSx/qE87Kjzmu2fU7ro5EFAb+OPituLqgfyuQaym5DlrNydW2sJ9A==}engines: {node: '>=12.22.0'}@@ -854,6 +1053,13 @@ packages:resolution: {integrity: sha512-zymm5+u+sCsSWyD9qNaejV3DFvhCKclKdizYaJUuHA83RLjb7nSuGnddCHGv0hk+KY7BMAlsWeK4Ueg6EV6XQg==}engines: {node: '>=8'}+ resolution: {integrity: sha512-hFoiJiTl63nn+kstHGBtewWSKnQLpyb155KHheA1l39uvtO9nWIop1p3udqPcUd/xbF1VLMO4n7OI6p7RbngDg==}+ engines: {node: '>=8'}++ resolution: {integrity: sha512-HgbIHPBH0KHHCcjLfGsCvhtPTVxjaAZlXjwdz7/GQC40SjSe4sfQsar8J5VFo8JOSbarkpV0OLG95bbaNd9aAQ==}+resolution: {integrity: sha512-O8dpsF+r0WV/8MNRKfnmrtCWhuKjxrq2w+jpzBL5UZKTi2LeVWnWOmWRxFlesJONmc+wLAGvKQZEOanko0LFTg==}engines: {node: '>=8'}@@ -869,12 +1075,21 @@ packages:resolution: {integrity: sha512-lM/UBzQmfJRo9ABXbPWemivdCW8V2G8FHaHdypQaIy523snUjog0W71ayWXTjiR+ixeMyVHN2XcpnTd/liPg/Q==}+ resolution: {integrity: sha512-SiPv/8VpZuWbvLSMtTDU8hEfrZWg/mH/nV/b4o0CYbSxu1UIQPLdwKOCIyLQX+VIPO5vrLX3i8qtqFyhdPSUSQ==}+resolution: {integrity: sha512-hOrZIVL5jyYFjzk7+y7n5JDzGlU8rfWDuYyHwGa2WA8/pcmMHezp2xsVwxrebD/Q9t8Nc5DboieySDpCp4WG4A==}resolution: {integrity: sha512-NM8/P9n3XjXhIZn1lLhkFaACTOURQXjWhV4BA/RnOv8xvgqtqpAX9IO4mRQxSx1Rlo4tqzeqb0sOlruaOy3dug==}+ resolution: {integrity: sha512-hRF04fqJIP8Abbkq5NKGN0Bbr3JxlQ+qhZufXVr0DvujKy93ZCbXZMHDL4EOtodSbCWxOqR8MS1tXA5hwqCXDg==}++ resolution: {integrity: sha512-EKI/M/yqPncGUUh44xz0PxSidXFr/+r0pA70+gIYhjv+et7yxM+s29Y+VGDkovRofQem0fs7Uvf4+YmAdyRduA==}+resolution: {integrity: sha512-CHYbu8RtboSIoVsHZ6Ye4cj4Aw/yg2oAFimlF7mNvfDV192LR7nDiKtSIfCuLT7KokPSTn/9kfVLm5OGN0A28A==}@@ -952,19 +1167,69 @@ packages:resolution: {integrity: sha512-WkUDrojuJs0xkgGf2udWxa3yGBRxPtxUkB79i6aCZLRgc7PM8fZe9TosfPDcvEpQZbuFASnHYmRLBLUbmLOIIA==}engines: {node: '>= 12.0.0'}+ resolution: {integrity: sha512-t7hw9pI+WvuwNJXwk5zVHpyhIqzg2qTlklJOf0mVxGSbe3Fp2VieZcduNYjaLDoy6p9uGpQEGWG87WpMKlNq8g==}+ engines: {node: '>=8'}+resolution: {integrity: sha512-vd2F4YUyEXKGcLHoq+TEyCjxueSeHnFxyyjNp80yg0XV4vUhnDer/lvvlqM/arB5bXQN5K2/3oinyCRyx8T2CQ==}resolution: {integrity: sha512-UicdXN8zQ3JHlxVq+28afMXPr1z7WNY6+7EJnzTdQWkTAlMLF5fNCCKxJHBQwGaNGR11581EiQmQzx73+MvszA==}+ resolution: {integrity: sha512-g3FeP20LNwhALb/6Cz6Dd4F2ngze0jz7tbzrD2wAV+o9FeNHe4rL+yK2md0J/fiSf1sa1ADhXqi5+oVwOM/eGw==}+ engines: {node: '>=8'}+resolution: {integrity: sha512-hXdUTZYIVOt1Ex//jAQi+wTZZpUpwBj/0QsOzqegb3rGMMeJiSEu5xLHnYfBrRV4RH2+OCSOO95Is/7x1WJ4bw==}engines: {node: '>=10'}+ resolution: {integrity: sha512-ZS4Bp4r/Zoeq6+NLJpP+0Zzm0pR8whtGPf1XExKLJBAczGMnSi3It14OiNCStjQjM6NU1okjQGSxgEZN8eBYKg==}++ resolution: {integrity: sha512-jSCU7/VB1loIWBZe14aEYHU/+1UMEHoaO7qxCOVJOw9GgH72VAWppxNcjU+x9a2k3GSIBXNKxXQFqRvvZ7vr3A==}+ engines: {node: '>=10.0.0'}+ hasBin: true+resolution: {integrity: sha512-kdd8AFNig2AD5Rkih7EPCXhu/iMvwevQFX/uEiGhZyPZi7fHqOoF4V4kHLpCfysxXMgQ4B52kdPMCwARshKvEg==}+ resolution: {integrity: sha512-rMO7CGo/9BFwyZABcKAWL8UJwH/Kc2x0g72uhDWzG48URRax5TCIcJ7Rc3RZqffZzO/Gwff/jyKwCU9TN8gehA==}++ resolution: {integrity: sha512-IPjlw73IoSYopnqBibQKxmAXMbOEPf5uGAOsBcaUiNH/TOI7V19WO+K7n5KYtnQ9FqzLGLpvwCGuPOTBSg4s5Q==}+ engines: {node: '>=16.20.1'}++ resolution: {integrity: sha512-URyb/VXMjJ4da46OeSXg+puO39XH9DeQpWCslifrRn9JWugy0D+DvvBvkm2WxmHe61O/H19JM66p1z7RHVkZ6A==}+ engines: {node: '>=16.20.1'}+ peerDependencies:+ '@aws-sdk/credential-providers': ^3.188.0+ '@mongodb-js/zstd': ^1.1.0 || ^2.0.0+ gcp-metadata: ^5.2.0+ kerberos: ^2.0.1+ mongodb-client-encryption: '>=6.0.0 <7'+ snappy: ^7.3.2+ socks: ^2.7.1+ peerDependenciesMeta:+ '@aws-sdk/credential-providers':+ optional: true+ '@mongodb-js/zstd':+ optional: true+ gcp-metadata:+ optional: true+ kerberos:+ optional: true+ mongodb-client-encryption:+ optional: true+ snappy:+ optional: true+ socks:+ optional: true+resolution: {integrity: sha512-6FlzubTLZG3J2a/NVCAleEhjzq5oxgHyaCU9yYXvcLsvoVaHJq/s5xXI6/XXP6tz7R9xAOtHnSO/tXtF3WRTlA==}@@ -973,6 +1238,28 @@ packages:engines: {node: ^10 || ^12 || ^13.7 || ^14 || >=15.0.1}hasBin: true+ resolution: {integrity: sha512-lDcBsjBSMlj3LXH2v/FW3txlh2pYTjmbOXPYJD93HI5EwuLzI11tdHSIpUMmfq/IOsldj4Ps8M8flhm+pCK4Ew==}+ engines: {node: '>=12.22.0'}++ resolution: {integrity: sha512-/jKZoMpw0F8GRwl4/eLROPA3cfcXtLApP0QzLmUT/HuPCZWyB7IY9ZrMeKw2O/nFIqPQB3PVM9aYm0F312AXDQ==}+ engines: {node: '>=10.5.0'}+ deprecated: Use your platform's native DOMException instead++ resolution: {integrity: sha512-c4FRfUm/dbcWZ7U+1Wq0AwCyFL+3nt2bEw05wfxSz+DWpWsitgmSgYmy2dQdWyKC1694ELPqMs/YzUSNozLt8A==}+ engines: {node: 4.x || >=6.0.0}+ peerDependencies:+ encoding: ^0.1.0+ peerDependenciesMeta:+ encoding:+ optional: true++ resolution: {integrity: sha512-dRB78srN/l6gqWulah9SrxeYnxeddIG30+GOqK/9OlLVyLg3HPnr6SqOWTWOXKRwC2eGYCkZ59NNuSgvSrpgOA==}+ engines: {node: ^12.20.0 || ^14.13.1 || >=16.0.0}+resolution: {integrity: sha512-42CPE9AhahZRsMNslczq0ctAEtqk8Eka26QofnqC346BZdHDySk3LWka23LI7ULIw11NmltpiLagIq8gBozxTw==}@@ -984,9 +1271,39 @@ packages:resolution: {integrity: sha512-0eJJY6hXLGf1udHwfNftBqH+g73EU4B504nZeKpz1sYRKafAghwxEJunB2O7rDZkL4PGfsMVnTXZ2EjibbqcsA==}engines: {node: '>=14.0.0'}+ resolution: {integrity: sha512-lNaJgI+2Q5URQBkccEKHTQOPaXdUxnZZElQTZY0MFUAuaEqe1E+Nyvgdz/aIyNi6Z9MzO5dv1H8n58/GELp3+w==}++ resolution: {integrity: sha512-//88mFWSJx8lxCzwdAABTJL2MyWB12+eIY7MDL2SqLmAkeKU9qxRvWuSyTjm3FUmpBEMuFfckAIqEaVGUDxb6w==}+ engines: {node: '>=6'}++ resolution: {integrity: sha512-TYOanM3wGwNGsZN2cVTYPArw454xnXj5qmWF1bEoAc4+cU/ol7GVh7odevjp1FNHduHc3KZMcFduxU5Xc6uJRQ==}+ engines: {node: '>=10'}++ resolution: {integrity: sha512-R79ZZ/0wAxKGu3oYMlz8jy/kbhsNrS7SKZ7PxEHBgJ5+F2mtFW2fK2cOtBh1cHYkQsbzFV7I+EoRKe6Yt0oK7A==}+ engines: {node: '>=8'}++ resolution: {integrity: sha512-R4nPAVTAU0B9D35/Gk3uJf/7XYbQcyohSKdvAxIRSNghFl4e71hVoGnBNQz9cWaXxO2I10KTC+3jMdvvoKw6dQ==}+ engines: {node: '>=6'}++ resolution: {integrity: sha512-ak9Qy5Q7jYb2Wwcey5Fpvg2KoAc/ZIhLSLOSBmRmygPsGwkVVt0fZa0qrtMz+m6tJTAHfZQ8FnmB4MG4LWy7/w==}+ engines: {node: '>=8'}++ resolution: {integrity: sha512-enSlaiat05iasnzmgNxRj8reFdj3puY2QpNgP1aPIaVfT6nn9ICuPoFlKHk8EN22HcwewshO+mN2DGbkCEOtqQ==}+ engines: {node: '>=14.0.0'}+resolution: {integrity: sha512-WUjGcAqP1gQacoQe+OBJsFA7Ld4DyXuUIjZ5cc75cLHvJ7dtNsTugphxIADwspS+AraAUePCKrSVtPLFj/F88w==}+ resolution: {integrity: sha512-F3asv42UuXchdzt+xXqfW1OGlVBe+mxa2mqI0pg5yAHZPvFmY3Y6drSf/GQ1A86WgWEN9Kzh/WrgKa6iGcHXLg==}+resolution: {integrity: sha512-xceH2snhtb5M9liqDsmEw56le376mTZkEX/jEb/RxNFyegNul7eNslCXP9FDj/Lcu0X8KEyMceP2ntpaHrDEVA==}@@ -1004,6 +1321,10 @@ packages:resolution: {integrity: sha512-r34yH/GlQpKZbU1BvFFqOjhISRo1MNx1tWYsYvmj6KIRHSPMT2+yHOEb1SG6NMvRoHRF0a07kCOox/9yakl1vg==}hasBin: true+ resolution: {integrity: sha512-HRDzbaKjC+AOWVXxAU/x54COGeIv9eb+6CkDSQoNTt4XyWoIJvuPsXizxu/Fr23EiekbtZwmh1IcIG/l/a10GQ==}+ engines: {node: '>=8'}+resolution: {integrity: sha512-RRuzqDtt5Y9h3quz5hWhK+TPnsmVs6WwSU6LkJMeY4HstUEDuYTG8UJSdawMRzmzAtV+KEoG8N3Qg2qLy5vM/A==}engines: {node: ^10 || ^12 || >=14}@@ -1019,9 +1340,17 @@ packages:resolution: {integrity: sha512-jQSaVHsPgtyw60e1rQ/A+/ArPEj/S8pS/vFnyGa/gYFXrKk/6RuDkoqVDQ5NI5MmS01698ltlAk0NoDBNLujRw==}+ resolution: {integrity: sha512-vYt7UD1U9Wg6138shLtLOvdAu+8DsC/ilFtEVHcH+wydcSpNE20AfSOduf6MkRFahL5FY7X1oU7nKVZFtfq8Fg==}+ engines: {node: '>=6'}+resolution: {integrity: sha512-tYC1Q1hgyRuHgloV/YXs2w15unPVh8qfu/qCTfhTYamaw7fyhumKa2yGpdSo87vY32rIclj+4fWYQXUMs9EHvg==}+ resolution: {integrity: sha512-9u/sniCrY3D5WdsERHzHE4G2YCXqoG5FTHUiCC4SIbr6XcLZBY05ya9EKjYek9O5xOAwjGq+1JdGBAS7Q9ScoA==}+ engines: {node: '>= 6'}+resolution: {integrity: sha512-57frrGM/OCTLqLOAh0mhVA9VBMHd+9U7Zb2THMGdBUoZVOtGbJzjxsYGDJ3A9AYYCP4hn6y1TVbaOfzWtm5GFg==}engines: {node: '>= 12.13.0'}@@ -1052,6 +1381,14 @@ packages:resolution: {integrity: sha512-I1XxrZSQ+oErkRR4jYbAyEEu2I0avBvvMM5JN+6EBprOGRCs63ENqZ3vjavq8fBw2+62G5LF5XelKwuJpcvcxw==}engines: {node: '>=10'}+ resolution: {integrity: sha512-FILyVbis+DTo3KRbtKceqpj1595wIF+XQFW/+AVOBdCQmxwNDgcNXXr2FNM0Ej2qD7zVXbJGfH7lo4jB0wwhKA==}+ engines: {node: '>=22'}++ resolution: {integrity: sha512-XQBQ3I8W1Cge0Seh+6gjj03LbmRFWuoszgK9ooCpwYIrhhoO80pfq4cUkU5DkknwfOfFteRwlZ56PYOGYyFWdg==}+ engines: {node: '>= 4'}+resolution: {integrity: sha512-g6QUff04oZpHs0eG5p83rFLhHeV00ug/Yf9nZM6fLeUrPguBTkTQOdpAWWspMh55TZfVQDPaN3NQJfbVRAxdIw==}engines: {iojs: '>=1.0.0', node: '>=0.10.0'}@@ -1067,6 +1404,9 @@ packages:resolution: {integrity: sha512-dhKf903U/PQZY6boNNtAGdWbG85WAbjT/1xYoZIC7FAY0yWapOBQVsVrDl58W86//e1VpMNBtRV4MaXfdMySFA==}+ resolution: {integrity: sha512-rp3So07KcdmmKbGvgaNxQSJr7bGVSVk5S9Eq1F+ppbRo70+YeaDxkw5Dd8NPN+GD6bjnYm2VuPuCXmpuYvmCXQ==}+resolution: {integrity: sha512-mOSBvHGDZMuIEZMdOz/aCEYDCv0E7nfcNsIhUF+/P+xC7Hyf3FkvymqgPbg9D1EdSGu+uKbJgy09K/RKKc7kJA==}hasBin: true@@ -1078,6 +1418,10 @@ packages:resolution: {integrity: sha512-l4KnYfEyqYJxDwlNVyRfO2E4NTHfMKAWdUuA8J0yve2Dz/E/PdBepY03RvyJpssIpRFwJoCD55wA+mEDs6ByWA==}+ resolution: {integrity: sha512-BR7VvDCVHO+q2xBEWskxS6DJE1qRnb7DxzUrogb71CWoSficBxYsiAGd+Kl0mmq/MprG9yArRkyrQxTO6XjMzA==}+ hasBin: true+resolution: {integrity: sha512-Y7/KDsb8LjooZpwaqGyulO6DQlksgCncchHGk+sZIY4SBvUocMBEFH5Ur1fI4dV+Jvl0w6cjvucaIi40puRioA==}engines: {node: '>=10'}@@ -1100,6 +1444,9 @@ packages:resolution: {integrity: sha512-UXWMKhLOwVKb728IUtQPXxfYU+usdybtUrK/8uGE8CQMvrhOpwvzDBwj0QhSL7MQc7vIsISBG8VQ8+IDQxpfQA==}engines: {node: '>=0.10.0'}+ resolution: {integrity: sha512-kvzhi7vqKTfkh0PZU+2D2PIllw2ymqJKujUcyPMd9Y75Nv4nPbGJZXNhxsgdQab2BmlDct1YnfQCguEvHr7VsQ==}+resolution: {integrity: sha512-UcjcJOWknrNkF6PLX83qcHM6KHgVKNkV62Y8a5uYDVv9ydGQVwAHMKqHdJje1VTWpljG0WYpCDhrCdAOYH4TWg==}engines: {node: '>= 10.x'}@@ -1113,14 +1460,32 @@ packages:resolution: {integrity: sha512-oCUKSupKTHX53EyjDtuZQ64pjLJ6yYCtpmEw0goYxtjG9KpbRe8KAsl2tBUGU9DyMcJ0RwJ8GqJAFzMXcXW1Rw==}+ resolution: {integrity: sha512-E1GUzBSgvct8Jsb3v2X15pjzN1tYebtbLaMg+eBOUOAxgbLoSbT2NS91ckc5lJD1KfLjId+jXJRgo0qnV5Nerg==}++ resolution: {integrity: sha512-76ORR0DO1o1hlKwTbi/DM3EXWGf3ZJYO8cXX5RJwnul2DEg2oyoZyjLNoQM8WsvZiFKCRfC1O0J7iCvie3RZmQ==}++ resolution: {integrity: sha512-zEzXb0s5Cds7tqMH6rhZ05lcJydCWiQPEwiNngVqzsxCc962vLY4Uw+mW7od8kDH258k2Uz/JrOkdIAAhSh9VA==}+resolution: {integrity: sha512-wKyQRQpjJ0sIp62ErSZdGsjMJWsap5oRNihHhu6G7JVO/9jIB6UyevL+tXuOqrng8j/cxKTWyWUwvSTriiZz/g==}engines: {node: '>=8'}+ resolution: {integrity: sha512-hkRX8U1WjJFd8LsDJ2yQ/wWWxaopEsABU1XfkM8A+j0+85JAGppt16cr1Whg6KIbb4okU6Mql6BOj+uup/wKeA==}+resolution: {integrity: sha512-Y38VPSHcqkFrCpFnQ9vuSXmquuv5oXOKpGeT6aGrr3o3Gc9AlVa6JBfUSOCnbxGGZF+/0ooI7KrPuUSztUdU5A==}engines: {node: '>=8'}+ resolution: {integrity: sha512-UM4nTLWzQiDBseVxUGxN0wJzIk0UU89Qi7pKXz9qISo+lhviJikTuikBsK/oFRlpvYHvSdz0TVoLyQ+sEpYwxA==}++ resolution: {integrity: sha512-PdHt7hHUJKxvTCgbKX9C1V/ftOcjJQgz8BZwNfV5c4B6dcGqlpelTbJ999jBGZ2jYiPAwcX5dP6oBwVlBlUbxw==}+resolution: {integrity: sha512-qpCAvRl9stuOHveKsn7HncJRvv501qIacKzQlO/+Lwxc9+0q2wLyv4Dfvt80/DPn2pqOBsJdDiogXGR9+OvwRw==}engines: {node: '>=8'}@@ -1129,6 +1494,19 @@ packages:resolution: {integrity: sha512-MpUEN2OodtUzxvKQl72cUF7RQ5EiHsGvSsVG0ia9c5RbWGL2CI4C7EpPS8UTBIplnlzZiNuV56w+FuNxy3ty2Q==}engines: {node: '>=10'}+ resolution: {integrity: sha512-+8NeqHRjQWH9nYlwo2gamAMImZCVzI4UoEgDpWorBt9OEfppiZn+uSkskzQKPWIZyji/C8fpWO7u69G0DX0tbg==}++ resolution: {integrity: sha512-I5OLOkPN3QDN2l1H/eGueuKaq32CdAcXt91WOF/bOfadtZD1WQ8/Fk28WsqDcGjIyhAW/GQDagYhVEjhuZUFyQ==}+ engines: {node: '>=22'}++ resolution: {integrity: sha512-eYE6iEI62Ni1H8oIa7KlDU6uQBtqr4Eajni3wX7rpfXD8ysFx8z0+dri+KWEPWpBsxXfxu58x/0jvTVT1ekOSg==}++ resolution: {integrity: sha512-vlLytXkeP4xvEq2otHeJfSQIRyWxo/oZGEbXrtEEF9Hnmrdly59sUbzZ/QgyWuLYHctCHxFF4tRQZNQ9k60ExQ==}+resolution: {integrity: sha512-e2zZ96wSChazBsbENf/Pcm/4swHt2cEKQ92rhUjkL9GCKiTDJIaTBenjE/m9DXi0QBmTMDkFDdOomUy20A1tDQ==}engines: {node: '>=20'}@@ -1152,6 +1530,13 @@ packages:resolution: {integrity: sha512-m1TdR/rvT7kgGJZhspNtXdsdYk0fddFpJJFlG5s+UkPFo6lkLoZ3YLOaovPYjq1R75NP5JfeTlSHaOsE09peCg==}engines: {node: '>=20'}+ resolution: {integrity: sha512-N3WMsuqV66lT30CrXNbEjx4GEwlow3v6rr4mCcv6prnfwhS01rkgyFdjPNBYd9br7LpXV1+Emh01fHnq2Gdgrw==}++ resolution: {integrity: sha512-hdF5ZgjTqgAntKkklYw0R03MG2x/bSzTtkxmIRw/sTNV8YXsCJ1tfLAX23lhxhHJlEf3CRCOCGGWw3vI3GaSPw==}+ engines: {node: '>=18'}+resolution: {integrity: sha512-L0Orpi8qGpRG//Nd+H90vFB+3iHnue1zSSGmNOOCh1GLJ7rUKVwV2HvijphGQS2UmhUZewS9VgvxYIdgr+fG1A==}hasBin: true@@ -1172,6 +1557,14 @@ packages:resolution: {integrity: sha512-iwDZqg0QAGrg9Rav5H4n0M64c3mkR59cJ6wQp+7C4nI0gsmExaedaYLNO44eT4AtBBwjbTiGPMlt2Md0T9H9JQ==}+ resolution: {integrity: sha512-EPD5q1uXyFxJpCrLnCc1nHnq3gOa6DZBocAIiI2TaSCA7VCJ1UJDMagCzIkXNsUYfD1daK//LTEQ8xiIbrHtcw==}++ resolution: {integrity: sha512-b+1eJOlsR9K8HJpow9Ok3fiWOWSIcIzXodvv0rQjVoOVNpWMpxf1wZNpt4y9h10odCNrqnYp1OBzRktckBe3sA==}+ deprecated: uuid@10 and below is no longer supported. For ESM codebases, update to uuid@latest. For CommonJS codebases, use uuid@11 (but be aware this version will likely be deprecated in 2028).+ hasBin: true+resolution: {integrity: sha512-lhZBVvEHefgE+HQZC9O7EBJgCU/nVzFNl7vkS4RE0APtWLP02/8QVIkQtzBxPquh7lq5/78NHipTj7ODQ6XuyQ==}engines: {node: ^20.19.0 || >=22.12.0}@@ -1256,6 +1649,24 @@ packages:jsdom:optional: true+ resolution: {integrity: sha512-d2JWLCivmZYTSIoge9MsgFCZrt571BikcWGYkjC1khllbTeDlGqZ2D8vD8E/lJa8WGWbb7Plm8/XJYV7IJHZZw==}+ engines: {node: '>= 8'}++ resolution: {integrity: sha512-2JAn3z8AR6rjK8Sm8orRC0h/bcl/DqL7tRPdGZ4I1CjdF+EaMLmYxBHyXuKL849eucPFhvBoxMsflfOb8kxaeQ==}++ resolution: {integrity: sha512-VwddBukDzu71offAQR975unBIGqfKZpM+8ZX6ySk8nYhVoo5CYaZyzt3YBvYtRtO+aoGlqxPg/B87NGVZ/fu6g==}+ engines: {node: '>=12'}++ resolution: {integrity: sha512-De72GdQZzNTUBBChsXueQUnPKDkg/5A5zp7pFDuQAj5UFoENpiACU0wlCvzpAGnTkj++ihpKwKyYewn/XNUbKw==}+ engines: {node: '>=18'}++ resolution: {integrity: sha512-saE57nupxk6v3HY35+jzBwYa0rKSy0XR8JSxZPwgLr7ys0IBzhGviA1/TUGJLmSVqs8pb9AnvICXEuOHLprYTw==}+resolution: {integrity: sha512-hUrmaWBdVDcxvYqnyh09zunKzROWjbZTiNy8dBEjkS7ehEDQibXJ7XvlmtbwuTclUiIyN+CyXQD4Vmko8fNm8w==}engines: {node: '>=8'}@@ -1265,6 +1676,9 @@ packages:resolution: {integrity: sha512-YVGIj2kamLSTxw6NsZjoBxfSwsn0ycdesmc4p+Q21c5zPuZ1pl+NfxVdxPtdHvmNVOQ6XSYG4AUtyt/Fi7D16Q==}engines: {node: '>=10'}+ resolution: {integrity: sha512-l4Sp/DRseor9wL6EvV2+TuQn63dMkPjZ/sp9XkghTEbV9KlPS1xUsZ3u7/IQO4wxtcFB4bgpQPRcR3QCvezPcQ==}+resolution: {integrity: sha512-201TZ/kPWxoPr/OKWjquZR1SWKXcvxdH+e1xrx89b3YbmzLMFCLfnaG1HFIgWzJOEWZ7MvpK++odZufgYR50Rw==}engines: {node: '>=10.0.0'}@@ -1277,6 +1691,10 @@ packages:utf-8-validate:optional: true+ resolution: {integrity: sha512-ghig2TBE/H11aOVgmahA3MhimvkBr6JIYknH/Dhdk10nXwdbIqBJsbfMxpvFPG8bAw77gN29aQWvKpmVoPlvPQ==}+ engines: {node: '>=16.0.0'}+resolution: {integrity: sha512-0pfFzegeDWJHJIAmTLRP2DwHjdF5s7jo9tuztdQxAhINCdvS+3nGINqPd00AphqJR/0LhANUS6/+7SCb98YOfA==}engines: {node: '>=10'}@@ -1289,6 +1707,14 @@ packages:resolution: {integrity: sha512-7dSzzRQ++CKnNI/krKnYRV7JKKPUXMEh61soaHKg9mrWEhzFWhFnxPxGl+69cD1Ou63C13NUPCnmIcrvqCuM6w==}engines: {node: '>=12'}+ resolution: {integrity: sha512-jIH9yLR9wqr0wOS0TpBvo/g/2UgZH5qePVbjgRliiF0BYvOZyaBknKsF+x9Iht0O6sqgnB93rCICdOZFecJuDw==}+ engines: {node: '>=12'}++ resolution: {integrity: sha512-rVksvsnNCdJ/ohGc6xgPwyN8eheCxsiLM8mxuE/t/mOVqJewPuO1miLpTHQiRgTKCLexL4MeAFVagts7HmNZ2Q==}+ engines: {node: '>=10'}+resolution: {integrity: sha512-v5l/aFXZQeai4awLbOpSoHecE9UiMrnfx75tEXLjNonXVARxQ5mOeipTjROUchszUNCqnE+hqAMujRsRHsut2Q==}@@ -1505,6 +1931,34 @@ snapshots:'@fastify/forwarded': 3.0.2ipaddr.js: 2.4.0+ '@google-cloud/[email protected]':+ dependencies:+ extend: 3.0.2++ '@google-cloud/[email protected]': {}++ '@google-cloud/[email protected]': {}++ '@google-cloud/[email protected]':+ dependencies:+ '@google-cloud/paginator': 7.2.0+ '@google-cloud/projectify': 6.2.1+ '@google-cloud/promisify': 6.2.1+ abort-controller: 3.0.0+ async-retry: 1.3.3+ duplexify: 4.1.3+ fast-xml-parser: 5.11.2+ gaxios: 6.7.1+ google-auth-library: 9.15.1+ html-entities: 2.6.0+ mime: 3.0.0+ p-limit: 3.1.0+ retry-request: 9.1.0+ teeny-request: 11.1.1+ transitivePeerDependencies:+ - encoding+ - supports-color+'@ioredis/[email protected]': {}'@jridgewell/[email protected]': {}@@ -1516,12 +1970,18 @@ snapshots:'@jridgewell/resolve-uri': 3.1.2'@jridgewell/sourcemap-codec': 1.6.0+ '@mongodb-js/[email protected]':+ dependencies:+ sparse-bitfield: 3.0.3+'@noble/[email protected]':dependencies:'@noble/hashes': 2.4.0'@noble/[email protected]': {}+ '@nodable/[email protected]': {}+'@oxc-project/[email protected]': {}'@pinojs/[email protected]': {}@@ -1617,6 +2077,12 @@ snapshots:dependencies:undici-types: 6.21.0+ '@types/[email protected]': {}++ '@types/[email protected]':+ dependencies:+ '@types/webidl-conversions': 7.0.3+'@types/[email protected]':dependencies:'@types/node': 20.19.43@@ -1676,8 +2142,14 @@ snapshots:convert-source-map: 2.0.0tinyrainbow: 3.1.1+ dependencies:+ event-target-shim: 5.0.1++ [email protected]: {}+optionalDependencies:ajv: 8.20.0@@ -1695,6 +2167,8 @@ snapshots:dependencies:color-convert: 2.0.1+ [email protected]: {}+@@ -1703,6 +2177,14 @@ snapshots:estree-walker: 3.0.3js-tokens: 10.0.0+ dependencies:+ tslib: 2.8.1++ dependencies:+ retry: 0.13.1+@@ -1710,6 +2192,47 @@ snapshots:'@fastify/error': 4.2.0fastq: 1.20.1+ [email protected]: {}++ [email protected]: {}++ dependencies:+ bare-events: 2.9.2+ bare-path: 3.1.2+ bare-stream: 2.13.4([email protected])+ bare-url: 2.5.5+ fast-fifo: 1.3.2+ transitivePeerDependencies:+ - bare-abort-controller+ - react-native-b4a++ [email protected]: {}++ dependencies:+ b4a: 1.9.0+ streamx: 2.28.1+ teex: 1.0.1+ optionalDependencies:+ bare-events: 2.9.2+ transitivePeerDependencies:+ - react-native-b4a++ dependencies:+ bare-path: 3.1.2++ [email protected]: {}++ [email protected]: {}++ [email protected]: {}++ [email protected]: {}++ [email protected]: {}+@@ -1731,6 +2254,8 @@ snapshots:+ [email protected]: {}+dependencies:chalk: 4.1.2@@ -1744,11 +2269,11 @@ snapshots:+ [email protected]: {}+dependencies:ms: 2.1.3- optionalDependencies:- supports-color: 8.1.1@@ -1758,8 +2283,23 @@ snapshots:+ dependencies:+ end-of-stream: 1.4.5+ inherits: 2.0.4+ readable-stream: 3.6.2+ stream-shift: 1.0.3++ dependencies:+ safe-buffer: 5.2.1++ dependencies:+ once: 1.4.0+@@ -1826,14 +2366,26 @@ snapshots:dependencies:'@types/estree': 1.0.9+ [email protected]: {}++ dependencies:+ bare-events: 2.9.2+ transitivePeerDependencies:+ - bare-abort-controller++ [email protected]: {}++ [email protected]: {}+dependencies:'@fastify/merge-json-schemas': 0.2.1@@ -1851,6 +2403,20 @@ snapshots:+ dependencies:+ path-expression-matcher: 1.6.2+ xml-naming: 0.3.0++ dependencies:+ '@nodable/entities': 3.1.0+ fast-xml-builder: 1.3.1+ is-unsafe: 2.0.2+ path-expression-matcher: 1.6.2+ strnum: 2.5.1+ xml-naming: 0.3.0+@@ -1879,38 +2445,118 @@ snapshots:optionalDependencies:picomatch: 4.0.7+ dependencies:+ node-domexception: 1.0.0+ web-streams-polyfill: 3.3.3++ dependencies:+ commondir: 1.0.1+ make-dir: 3.1.0+ pkg-dir: 4.2.0+dependencies:fast-deep-equal: 3.1.3fast-querystring: 1.1.2safe-regex2: 5.1.1+ dependencies:+ locate-path: 5.0.0+ path-exists: 4.0.0+optionalDependencies:- debug: 4.4.3([email protected])+ debug: 4.4.3++ dependencies:+ fetch-blob: 3.2.0optional: true+ dependencies:+ extend: 3.0.2+ https-proxy-agent: 7.0.6+ is-stream: 2.0.1+ node-fetch: 2.7.0+ uuid: 9.0.1+ transitivePeerDependencies:+ - encoding+ - supports-color++ dependencies:+ gaxios: 6.7.1+ google-logging-utils: 0.0.2+ json-bigint: 1.0.0+ transitivePeerDependencies:+ - encoding+ - supports-color++ dependencies:+ base64-js: 1.5.1+ ecdsa-sig-formatter: 1.0.11+ gaxios: 6.7.1+ gcp-metadata: 6.1.1+ gtoken: 7.1.0+ jws: 4.0.1+ transitivePeerDependencies:+ - encoding+ - supports-color++ [email protected]: {}++ dependencies:+ gaxios: 6.7.1+ jws: 4.0.1+ transitivePeerDependencies:+ - encoding+ - supports-color++ [email protected]: {}++ dependencies:+ agent-base: 7.1.4+ debug: 4.4.3+ transitivePeerDependencies:+ - supports-color+dependencies:eventemitter3: 4.0.7- follow-redirects: 1.16.0([email protected]([email protected]))+ follow-redirects: 1.16.0([email protected])requires-port: 1.0.0transitivePeerDependencies:- debug+ dependencies:+ agent-base: 7.1.4+ debug: 4.4.3+ transitivePeerDependencies:+ - supports-color++ [email protected]: {}+dependencies:'@ioredis/commands': 1.10.0cluster-key-slot: 1.1.1- debug: 4.4.3([email protected])+ debug: 4.4.3denque: 2.1.0redis-errors: 1.2.0redis-parser: 3.0.0@@ -1922,6 +2568,10 @@ snapshots:+ [email protected]: {}++ [email protected]: {}+@@ -1937,12 +2587,27 @@ snapshots:+ dependencies:+ bignumber.js: 9.3.1+dependencies:dequal: 2.0.3+ dependencies:+ buffer-equal-constant-time: 1.0.1+ ecdsa-sig-formatter: 1.0.11+ safe-buffer: 5.2.1++ dependencies:+ jwa: 2.0.1+ safe-buffer: 5.2.1+dependencies:cookie: 1.1.1@@ -1998,6 +2663,10 @@ snapshots:lightningcss-win32-arm64-msvc: 1.33.0lightningcss-win32-x64-msvc: 1.33.0+ dependencies:+ p-locate: 4.1.0+dependencies:'@jridgewell/sourcemap-codec': 1.6.0@@ -2008,26 +2677,114 @@ snapshots:'@babel/types': 7.29.8source-map-js: 1.2.1+ dependencies:+ semver: 6.3.1+dependencies:semver: 7.8.5+ [email protected]: {}++ [email protected]: {}+dependencies:obliterator: 2.0.5+ dependencies:+ '@types/whatwg-url': 11.0.5+ whatwg-url: 14.2.0++ dependencies:+ async-mutex: 0.5.0+ camelcase: 6.3.0+ debug: 4.4.3+ find-cache-dir: 3.3.2+ follow-redirects: 1.16.0([email protected])+ https-proxy-agent: 7.0.6+ mongodb: 6.21.0+ new-find-package-json: 2.0.0+ semver: 7.8.5+ tar-stream: 3.2.2+ tslib: 2.8.1+ yauzl: 3.4.0+ transitivePeerDependencies:+ - '@aws-sdk/credential-providers'+ - '@mongodb-js/zstd'+ - bare-abort-controller+ - bare-buffer+ - gcp-metadata+ - kerberos+ - mongodb-client-encryption+ - react-native-b4a+ - snappy+ - socks+ - supports-color++ dependencies:+ '@mongodb-js/saslprep': 1.6.1+ bson: 6.10.4+ mongodb-connection-string-url: 3.0.2++ dependencies:+ debug: 4.4.3+ transitivePeerDependencies:+ - supports-color++ [email protected]: {}++ dependencies:+ whatwg-url: 5.0.0++ dependencies:+ data-uri-to-buffer: 4.0.1+ fetch-blob: 3.2.0+ formdata-polyfill: 4.0.10++ dependencies:+ wrappy: 1.0.2++ dependencies:+ p-try: 2.2.0++ dependencies:+ yocto-queue: 0.1.0++ dependencies:+ p-limit: 2.3.0++ [email protected]: {}++ [email protected]: {}++ [email protected]: {}++ [email protected]: {}+@@ -2052,6 +2809,10 @@ snapshots:sonic-boom: 4.2.1thread-stream: 4.2.0+ dependencies:+ find-up: 4.1.0+dependencies:nanoid: 3.3.19@@ -2068,8 +2829,16 @@ snapshots:+ [email protected]: {}++ dependencies:+ inherits: 2.0.4+ string_decoder: 1.3.0+ util-deprecate: 1.0.2+@@ -2088,6 +2857,12 @@ snapshots:+ dependencies:+ extend: 3.0.2++ [email protected]: {}+@@ -2117,6 +2892,8 @@ snapshots:dependencies:tslib: 2.8.1+ [email protected]: {}+dependencies:ret: 0.5.0@@ -2125,6 +2902,8 @@ snapshots:+ [email protected]: {}+@@ -2139,6 +2918,10 @@ snapshots:+ dependencies:+ memory-pager: 1.5.0+@@ -2147,16 +2930,41 @@ snapshots:+ dependencies:+ stubs: 3.0.0++ [email protected]: {}++ dependencies:+ events-universal: 1.0.1+ fast-fifo: 1.3.2+ text-decoder: 1.2.7+ transitivePeerDependencies:+ - bare-abort-controller+ - react-native-b4a+dependencies:emoji-regex: 8.0.0is-fullwidth-code-point: 3.0.0strip-ansi: 6.0.1+ dependencies:+ safe-buffer: 5.2.1+dependencies:ansi-regex: 5.0.1+ dependencies:+ anynum: 1.0.1++ [email protected]: {}+dependencies:has-flag: 4.0.0@@ -2165,6 +2973,39 @@ snapshots:dependencies:has-flag: 4.0.0+ dependencies:+ b4a: 1.9.0+ bare-fs: 4.8.4+ fast-fifo: 1.3.2+ streamx: 2.28.1+ transitivePeerDependencies:+ - bare-abort-controller+ - bare-buffer+ - react-native-b4a++ dependencies:+ http-proxy-agent: 7.0.2+ https-proxy-agent: 7.0.6+ node-fetch: 3.3.2+ stream-events: 1.0.5+ transitivePeerDependencies:+ - supports-color++ dependencies:+ streamx: 2.28.1+ transitivePeerDependencies:+ - bare-abort-controller+ - react-native-b4a++ dependencies:+ b4a: 1.9.0+ transitivePeerDependencies:+ - react-native-b4a+dependencies:real-require: 1.0.0@@ -2182,6 +3023,12 @@ snapshots:+ [email protected]: {}++ dependencies:+ punycode: 2.3.1+@@ -2196,6 +3043,10 @@ snapshots:+ [email protected]: {}++ [email protected]: {}+dependencies:lightningcss: 1.33.0@@ -2237,6 +3088,22 @@ snapshots:transitivePeerDependencies:- msw+ [email protected]: {}++ [email protected]: {}++ [email protected]: {}++ dependencies:+ tr46: 5.1.1+ webidl-conversions: 7.0.0++ dependencies:+ tr46: 0.0.3+ webidl-conversions: 3.0.1+dependencies:siginfo: 2.0.0@@ -2248,8 +3115,12 @@ snapshots:string-width: 4.2.3strip-ansi: 6.0.1+ [email protected]: {}++ [email protected]: {}+@@ -2264,4 +3135,10 @@ snapshots:y18n: 5.0.8yargs-parser: 21.1.1+ dependencies:+ pend: 1.2.0++ [email protected]: {}+diff --git a/backend/prisma/schema.prisma b/backend/prisma/schema.prismaindex debb2f711..3ea43910f 100644--- a/backend/prisma/schema.prisma+++ b/backend/prisma/schema.prisma@@ -1017,44 +1017,29 @@ model SuperTabMessage {author Jsonsource Json?text String+ /// Files posted with the message (superTabs/attachments.ts); the bytes live in the attachments bucket.+ attachments Json?replyTo String?recipientIds String[]- /// Metadata of the images sent with it (superTabs/attachments.ts); never their bytes.- attachments Json?createdAt DateTime @default(now())@@index([tabId, conversationId, sequence])}-/// An image a member attached to a Super Tab message (superTabs/attachments.ts). Until it is sent only its-/// uploader can read it; after that, whoever can read the message's conversation. The bytes are in parts.+/// One uploaded file, which one message of the actor that uploaded it can send once.model SuperTabAttachment {- id String @id @map("_id")- tabId String- actorKey String- conversationId String?- messageId String?- name String- mime String- size Int- width Int?- height Int?- parts Int- complete Boolean @default(false)- createdAt DateTime @default(now())-- @@index([tabId, actorKey, messageId, createdAt])-}--/// One part of an attachment's bytes. Parts keep every upload and read small enough for the machine relay-/// the apps reach the backend through.-model SuperTabAttachmentPart {- id String @id @map("_id")- attachmentId String- index Int- data Bytes+ id String @id @map("_id")+ tabId String+ conversationId String+ actorKey String+ name String+ mime String+ size Int+ objectKey String+ usedBy String?+ createdAt DateTime @default(now())- @@unique([attachmentId, index])+ @@index([tabId, actorKey, createdAt])}model SuperTabOperation {diff --git a/backend/src/config/env.ts b/backend/src/config/env.tsindex 2fb1ace6f..82ba48af4 100644--- a/backend/src/config/env.ts+++ b/backend/src/config/env.ts@@ -225,6 +225,17 @@ const envSchema = z.object({// key's OpenRouter credit limit stays the hard cap. Past it ⌘B says Harness's Jev budget has run out until the next UTC day.JEV_DAILY_DECISIONS: z.coerce.number().int().positive().default(200_000),+ // Super Tab chat attachments (superTabs/attachments.ts). Clients upload through POST /api/super-tabs/:tabId/attachments,+ // which streams each file into this GCS bucket (10 MB at most); everyone reads it through the public CDN. No bucket:+ // uploads answer ATTACHMENTS_UNAVAILABLE and chat stays text only.+ SUPER_TAB_ATTACHMENTS_BUCKET: z.string().default(''),+ // The base64 of the service account JSON key that writes to the bucket. Empty: application default credentials (Workload Identity, or GOOGLE_APPLICATION_CREDENTIALS). A value that+ // is not base64 of such a key stops the backend at startup, with a message that never shows the value.+ SUPER_TAB_ATTACHMENTS_CREDENTIALS: z.string().default(''),+ SUPER_TAB_ATTACHMENTS_PREFIX: z.string().default('super-tabs'),+ // Where clients read the files. https:// in production (superTabs/attachments.ts refuses anything else at startup).+ SUPER_TAB_ATTACHMENTS_PUBLIC_BASE: z.string().url().default('https://cdn.harness.autonomous.ai'),+// TTL for the in-memory subdomain→machineId cache on the public app-proxy hot path// (avoids a Mongo lookup per request). Bounds staleness after a cross-instance app teardown.// 60 min default (mapping is stable; a same-instance delete evicts immediately).diff --git a/backend/src/routes/superTabs.ts b/backend/src/routes/superTabs.tsindex 76aa120dc..1854de551 100644--- a/backend/src/routes/superTabs.ts+++ b/backend/src/routes/superTabs.ts@@ -1,17 +1,19 @@import type { FastifyInstance, FastifyReply } from 'fastify'import { z } from 'zod'import { prisma } from '../lib/prisma.js'+import { env } from '../config/env.js'+import multipart from '@fastify/multipart'+import { attachmentsFromEnv, MAX_ATTACHMENT_BYTES } from '../superTabs/attachments.js'import { validateBody, validateParams, validateQuery } from '../middlewares/validation.js'import { sendError, sendSuccess } from '../utils/response.js'import { operationSchema } from '../superTabs/commands.js'-import { SuperTabError } from '../superTabs/model.js'+import { fail, SuperTabError } from '../superTabs/model.js'import { SuperTabStore } from '../superTabs/store.js'import { routingPolicySchema } from '../superTabs/routingPolicy.js'import { nativeEventSchema, openNativeSchema } from '../superTabs/native.js'import { machineObservationSchema } from '../superTabs/machines.js'import { joinSwarmSchema, previewJoinSchema, saveSharingSchema } from '../superTabs/sharing.js'import { holdReason } from '../superTabs/holdNotice.js'-import { ATTACHMENT_BODY_LIMIT, attachmentPartSchema, uploadAttachmentSchema } from '../superTabs/attachments.js'const id = z.string().min(1).max(160).regex(/^[A-Za-z0-9_-]+$/)const tabParams = z.object({ tabId: id })@@ -26,8 +28,6 @@ const messageQuery = agentQuery.extend({ after: z.coerce.number().int().nonnegatbefore: z.coerce.number().int().nonnegative().safe().optional(), messageId: id.optional() }).refine(q => [q.after, q.before, q.messageId].filter(value => value !== undefined).length <= 1, 'Choose one message cursor or exact message.')const decisionParams = tabParams.extend({ decisionId: id })-const attachmentParams = tabParams.extend({ attachmentId: id })-const partParams = attachmentParams.extend({ index: z.coerce.number().int().min(0).max(63) })const hostParams = z.object({ machineId: id })const hostStartParams = hostParams.extend({ tabId: id, startId: id })const machineParams = hostParams.extend({ tabId: id })@@ -41,6 +41,7 @@ const deliveryAction = z.discriminatedUnion('type', [const savePolicy = z.object({ revision: z.number().int().nonnegative().safe(), policy: routingPolicySchema }).strict()const stop = z.object({ assignmentId: id, receipt: z.string().min(1).max(2000) }).strict()+async function respond(reply: FastifyReply, action: () => Promise<unknown>) {try { sendSuccess(reply, await action()) } catch (error) {if (!(error instanceof SuperTabError)) throw error@@ -50,7 +51,7 @@ async function respond(reply: FastifyReply, action: () => Promise<unknown>) {/** Uses the normal authenticated control API. It never accepts caller-provided host/contributor identities. */export async function superTabRoutes(app: FastifyInstance, options: { store?: SuperTabStore } = {}) {- const store = options.store ?? new SuperTabStore(prisma)+ const store = options.store ?? new SuperTabStore(prisma, Date.now, attachmentsFromEnv(env))app.get<{ Params: z.infer<typeof hostParams> }>('/api/super-tabs/hosts/:machineId/pools', { preHandler: validateParams(hostParams) },(req, reply) => respond(reply, () => store.hostPools(req.user!, req.params.machineId)))app.get<{ Params: z.infer<typeof hostStartParams> }>('/api/super-tabs/hosts/:machineId/starts/:tabId/:startId', { preHandler: validateParams(hostStartParams) },@@ -107,6 +108,38 @@ export async function superTabRoutes(app: FastifyInstance, options: { store?: Su{ preHandler: [validateParams(tabParams), validateBody(operation, { named: true })] },(req, reply) => respond(reply, () => store.execute(req.user!, req.params.tabId,{ operationId: req.body.operationId, command: req.body.command }, req.body.asAgentId)))+ // A chat file comes straight from the client (the desktop's and the browser's account token, or the daemon's for+ // `post --attach`), never through a machine or the relay. Multipart is parsed in this scope alone, so no other+ // Super Tab route's body handling changes.+ await app.register(async scope => {+ // One byte over the limit, so the store sees an oversized file and refuses it rather than keeping a cut one.+ await scope.register(multipart, { limits: { fileSize: MAX_ATTACHMENT_BYTES + 1, files: 1, fields: 1, parts: 2 } })+ scope.post<{ Params: z.infer<typeof tabParams>; Querystring: z.infer<typeof agentQuery> }>('/api/super-tabs/:tabId/attachments',+ { preHandler: [validateParams(tabParams), validateQuery(agentQuery)] }, (req, reply) => respond(reply, async () => {+ let conversationId: string | null = null, uploaded: unknown = null, stored: unknown = null+ try {+ for await (const part of req.parts()) {+ if (part.type === 'field') {+ if (part.fieldname !== 'conversationId' || conversationId !== null || uploaded) fail('INVALID_ATTACHMENT', 'Send conversationId, then one file.', 400)+ conversationId = id.safeParse(part.value).data ?? fail('INVALID_ATTACHMENT', 'Name the conversation to attach the file to.', 400)+ } else {+ if (!conversationId || uploaded) { part.file.resume(); fail('INVALID_ATTACHMENT', 'Send conversationId, then one file.', 400) }+ try {+ uploaded = await store.upload(req.user!, req.params.tabId, conversationId,+ { name: part.filename, mime: part.mimetype, body: part.file }, req.query.asAgentId)+ } catch (error) { stored = error; throw error } finally { part.file.resume() }+ }+ }+ } catch (error) {+ // Only the form itself is the client's fault; the store's own failures keep their status.+ const code = error && typeof error === 'object' && 'code' in error ? error.code : null+ if (code === 'FST_REQ_FILE_TOO_LARGE') fail('ATTACHMENT_TOO_LARGE', 'A file can be at most 10 MB.', 413)+ if (error instanceof SuperTabError || (error === stored && !(code && String(code).startsWith('FST_')))) throw error+ fail('INVALID_ATTACHMENT', 'Send a multipart form with conversationId and one file.', 400)+ }+ return uploaded ?? fail('INVALID_ATTACHMENT', 'Attach one file.', 400)+ }))+ })app.get<{ Params: z.infer<typeof startParams>; Querystring: z.infer<typeof agentQuery> }>('/api/super-tabs/:tabId/starts/:startId',{ preHandler: [validateParams(startParams), validateQuery(agentQuery)] },(req, reply) => respond(reply, () => store.start(req.user!, req.params.tabId, req.params.startId, req.query.asAgentId)))@@ -131,22 +164,6 @@ export async function superTabRoutes(app: FastifyInstance, options: { store?: Suapp.get<{ Params: z.infer<typeof deliveryActionParams> }>('/api/super-tabs/:tabId/agents/:agentId/deliveries/:deliveryId',{ preHandler: validateParams(deliveryActionParams) },(req, reply) => respond(reply, () => store.deliveryReceipt(req.user!, req.params.tabId, req.params.agentId, req.params.deliveryId)))- // Images travel in parts (attachments.ts `ATTACHMENT_PART_BYTES`); each request carries at most one part as base64.- app.post<{ Params: z.infer<typeof tabParams>; Querystring: z.infer<typeof agentQuery>; Body: z.infer<typeof uploadAttachmentSchema> }>('/api/super-tabs/:tabId/attachments',- { bodyLimit: ATTACHMENT_BODY_LIMIT, preHandler: [validateParams(tabParams), validateQuery(agentQuery), validateBody(uploadAttachmentSchema)] },- (req, reply) => respond(reply, () => store.attachments.upload(req.user!, req.params.tabId, req.body, req.query.asAgentId)))- app.get<{ Params: z.infer<typeof attachmentParams>; Querystring: z.infer<typeof agentQuery> }>('/api/super-tabs/:tabId/attachments/:attachmentId',- { preHandler: [validateParams(attachmentParams), validateQuery(agentQuery)] },- (req, reply) => respond(reply, () => store.attachments.read(req.user!, req.params.tabId, req.params.attachmentId, req.query.asAgentId)))- app.delete<{ Params: z.infer<typeof attachmentParams>; Querystring: z.infer<typeof agentQuery> }>('/api/super-tabs/:tabId/attachments/:attachmentId',- { preHandler: [validateParams(attachmentParams), validateQuery(agentQuery)] },- (req, reply) => respond(reply, () => store.attachments.remove(req.user!, req.params.tabId, req.params.attachmentId, req.query.asAgentId)))- app.post<{ Params: z.infer<typeof partParams>; Querystring: z.infer<typeof agentQuery>; Body: z.infer<typeof attachmentPartSchema> }>('/api/super-tabs/:tabId/attachments/:attachmentId/parts/:index',- { bodyLimit: ATTACHMENT_BODY_LIMIT, preHandler: [validateParams(partParams), validateQuery(agentQuery), validateBody(attachmentPartSchema)] },- (req, reply) => respond(reply, () => store.attachments.uploadPart(req.user!, req.params.tabId, req.params.attachmentId, req.params.index, req.body, req.query.asAgentId)))- app.get<{ Params: z.infer<typeof partParams>; Querystring: z.infer<typeof agentQuery> }>('/api/super-tabs/:tabId/attachments/:attachmentId/parts/:index',- { preHandler: [validateParams(partParams), validateQuery(agentQuery)] },- (req, reply) => respond(reply, () => store.attachments.readPart(req.user!, req.params.tabId, req.params.attachmentId, req.params.index, req.query.asAgentId)))app.post<{ Params: z.infer<typeof tabParams>; Body: z.infer<typeof stop> }>('/api/super-tabs/:tabId/stopped',{ preHandler: [validateParams(tabParams), validateBody(stop)] },(req, reply) => respond(reply, () => store.stopped(req.user!, req.params.tabId, req.body.assignmentId, req.body.receipt)))diff --git a/backend/src/superTabs/attachments.test.ts b/backend/src/superTabs/attachments.test.tsindex 46d643abd..a002c72cb 100644--- a/backend/src/superTabs/attachments.test.ts+++ b/backend/src/superTabs/attachments.test.ts@@ -1,27 +1,121 @@+import { generateKeyPairSync } from 'node:crypto'import { describe, expect, it } from 'vitest'-import { imageInfo } from './attachments.js'--const bytes = (...parts: Array<number[] | string>) => Uint8Array.from(parts.flatMap(p => typeof p === 'string' ? [...p].map(c => c.charCodeAt(0)) : p))-const be32 = (n: number) => [n >>> 24, (n >> 16) & 0xff, (n >> 8) & 0xff, n & 0xff]--describe('Super Tab image attachments', () => {- it('reads the type and size of PNG, JPEG and WebP from their own headers', () => {- expect(imageInfo(bytes([0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a], be32(13), 'IHDR', be32(640), be32(480))))- .toEqual({ mime: 'image/png', width: 640, height: 480 })- // SOI, an APP0 segment to skip, then a baseline frame header: height 300, width 400.- expect(imageInfo(bytes([0xff, 0xd8, 0xff, 0xe0, 0x00, 0x04, 0x00, 0x00, 0xff, 0xc0, 0x00, 0x11, 0x08, 0x01, 0x2c, 0x01, 0x90, 0x03, 0, 0, 0])))- .toEqual({ mime: 'image/jpeg', width: 400, height: 300 })- expect(imageInfo(bytes([0xff, 0xd8, 0xff, 0xdb]))).toEqual({ mime: 'image/jpeg', width: null, height: null })- const riff = (chunk: string, body: number[]) => bytes('RIFF', [0, 0, 0, 0], 'WEBP', chunk, [0, 0, 0, 0], body)- expect(imageInfo(riff('VP8X', [0, 0, 0, 0, 0x1f, 0x03, 0x00, 0xdf, 0x01, 0x00]))).toEqual({ mime: 'image/webp', width: 800, height: 480 })- expect(imageInfo(riff('VP8 ', [0, 0, 0, 0x9d, 0x01, 0x2a, 0x20, 0x03, 0xe0, 0x01]))).toEqual({ mime: 'image/webp', width: 800, height: 480 })- expect(imageInfo(riff('VP8L', [0x2f, 0x1f, 0xc3, 0x77, 0x00]))).toEqual({ mime: 'image/webp', width: 800, height: 480 })- })-- it('refuses anything else, whatever it is called', () => {- expect(imageInfo(bytes('GIF89a'))).toBeNull()- expect(imageInfo(bytes('BM'))).toBeNull()- expect(imageInfo(bytes('<svg xmlns="http://www.w3.org/2000/svg"/>'))).toBeNull()- expect(imageInfo(new Uint8Array())).toBeNull()+import { Readable } from 'node:stream'+import { AttachmentTooLarge, attachmentName, attachmentsFromEnv, checkedType, imageTypeOf, GcsAttachmentStore, MemoryAttachmentStore, objectKeyFor, served, serviceAccountFrom } from './attachments.js'++const { privateKey } = generateKeyPairSync('rsa', { modulusLength: 2048 })+const key = { type: 'service_account', project_id: 'harness-test', client_email: '[email protected]',+ private_key: privateKey.export({ type: 'pkcs8', format: 'pem' }).toString() }+const encoded = (value: unknown) => Buffer.from(JSON.stringify(value)).toString('base64')+const env = (credentials: string, bucket = 'attachments') => ({ NODE_ENV: 'test', SUPER_TAB_ATTACHMENTS_BUCKET: bucket, SUPER_TAB_ATTACHMENTS_CREDENTIALS: credentials,+ SUPER_TAB_ATTACHMENTS_PREFIX: 'super-tabs', SUPER_TAB_ATTACHMENTS_PUBLIC_BASE: 'https://cdn.example.test' })++describe('attachment bucket credentials', () => {+ it('decodes a base64 service account key, also wrapped over lines', () => {+ const wrapped = encoded(key).replace(/(.{76})/g, '$1\n')+ expect(serviceAccountFrom(wrapped)).toEqual({ projectId: 'harness-test',+ credentials: { client_email: key.client_email, private_key: key.private_key } })+ })++ it('falls back to application default credentials when empty', () => {+ expect(serviceAccountFrom('')).toBeNull()+ expect(serviceAccountFrom(' \n')).toBeNull()+ expect(attachmentsFromEnv(env(''))?.store).toBeInstanceOf(GcsAttachmentStore)+ expect(attachmentsFromEnv(env('', ''))).toBeNull()+ })++ it('refuses a bad value at startup without repeating it, even with no bucket set', () => {+ const secret = 'not-base64-secret!'+ const cases: Array<[string, RegExp]> = [+ [secret, /is not base64/],+ [Buffer.from('{"private_key": "secret-material", oops').toString('base64'), /does not decode to JSON/],+ [encoded({ ...key, private_key: undefined }), /client_email and private_key/],+ [encoded({ ...key, client_email: '' }), /client_email and private_key/],+ [encoded('a string'), /client_email and private_key/],+ ]+ for (const [value, message] of cases) {+ let error: unknown+ try { attachmentsFromEnv(env(value, '')) } catch (thrown) { error = thrown }+ expect((error as Error).message).toMatch(message)+ expect((error as Error).message).not.toContain(secret)+ expect((error as Error).message).not.toContain('secret-material')+ }+ })++ it('takes a plain http file address only outside production', () => {+ const local = { ...env(''), SUPER_TAB_ATTACHMENTS_PUBLIC_BASE: 'http://127.0.0.1:9000' }+ expect(attachmentsFromEnv(local)?.publicBase).toBe('http://127.0.0.1:9000')+ expect(attachmentsFromEnv({ ...local, NODE_ENV: 'development' })).not.toBeNull()+ expect(() => attachmentsFromEnv({ ...local, NODE_ENV: 'production' })).toThrow('must be an https:// address in production')+ expect(attachmentsFromEnv({ ...env(''), NODE_ENV: 'production' })?.publicBase).toBe('https://cdn.example.test')+ })++ it('builds the storage client from the configured key, without a network call', async () => {+ const store = attachmentsFromEnv(env(encoded(key)))!.store as GcsAttachmentStore+ const bucket = await (store as unknown as { files(): Promise<import('@google-cloud/storage').Bucket> }).files()+ expect(bucket.name).toBe('attachments')+ expect(bucket.storage.projectId).toBe('harness-test')+ expect((await bucket.storage.authClient.getCredentials()).client_email).toBe(key.client_email)+ })+})++describe('attachment files', () => {+ const png = Buffer.from([0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a, 0, 0, 0, 13, 0x49, 0x48, 0x44, 0x52])+ const jpeg = Buffer.from([0xff, 0xd8, 0xff, 0xe0, 0, 16, 0x4a, 0x46, 0x49, 0x46, 0, 1, 1, 0, 0, 1])+ const read = async (body: Readable) => { const parts: Buffer[] = []; for await (const chunk of body) parts.push(Buffer.from(chunk)); return Buffer.concat(parts) }++ it('tells raster images by their first bytes', () => {+ expect(imageTypeOf(png)).toBe('image/png')+ expect(imageTypeOf(jpeg)).toBe('image/jpeg')+ expect(imageTypeOf(Buffer.from('GIF89a......'))).toBe('image/gif')+ expect(imageTypeOf(Buffer.from('RIFF\0\0\0\0WEBPVP8 '))).toBe('image/webp')+ expect(imageTypeOf(Buffer.from('<svg xmlns="http://www.w3.org/2000/svg">'))).toBeNull()+ expect(imageTypeOf(Buffer.alloc(0))).toBeNull()+ })++ it('serves a claimed image as what its bytes are, and hands the whole file on', async () => {+ const rest = Buffer.alloc(100_000, 7)+ // Small chunks, so the check has to gather the head across several and keep every byte.+ const chunks = [jpeg.subarray(0, 5), jpeg.subarray(5), rest]+ const renamed = await checkedType('image/png', Readable.from(chunks))+ expect(renamed.mime).toBe('image/jpeg')+ expect((await read(renamed.body)).equals(Buffer.concat([jpeg, rest]))).toBe(true)+ const page = Buffer.from('<html><script>alert(1)</script></html>')+ const disguised = await checkedType('image/png', Readable.from([page]))+ expect(disguised.mime).toBe('application/octet-stream')+ expect((await read(disguised.body)).equals(page)).toBe(true)+ const tiny = await checkedType('image/gif', Readable.from([Buffer.from('GI')]))+ expect(tiny.mime).toBe('application/octet-stream')+ expect((await read(tiny.body)).toString()).toBe('GI')+ })++ it('leaves files that do not claim to be images as they are', async () => {+ const body = Readable.from([Buffer.from('a,b\n')])+ const checked = await checkedType('text/csv', body)+ expect(checked).toEqual({ mime: 'text/csv', body })+ })++ it('serves only raster images as themselves; everything else downloads as bytes', () => {+ expect(served('a.png', 'image/png')).toEqual({ contentType: 'image/png', contentDisposition: "inline; filename*=UTF-8''a.png" })+ expect(served('page.html', 'text/html')).toEqual({ contentType: 'application/octet-stream', contentDisposition: "attachment; filename*=UTF-8''page.html" })+ expect(served('icon.svg', 'image/svg+xml').contentType).toBe('application/octet-stream')+ expect(served('ảnh 1.jpg', 'image/jpeg').contentDisposition).toBe("inline; filename*=UTF-8''%E1%BA%A3nh%201.jpg")+ })+ it('refuses names with control, format or separator characters', () => {+ for (const name of ['a\u0001.png', 'evilgnp.exe', 'zerowidth.png', 'line .png', 'para .png']) {+ expect(attachmentName.safeParse(name).success).toBe(false)+ }+ expect(attachmentName.safeParse('Ảnh chụp màn hình 1.png').success).toBe(true)+ })+ it('keys each object under the tab with 128 random bits and a safe name', () => {+ expect(objectKeyFor('/super-tabs/', 'tab', '../Screen Shot.png')).toMatch(/^super-tabs\/tab\/[0-9a-f]{32}\/Screen_Shot\.png$/)+ expect(objectKeyFor('', 'tab', '...')).toMatch(/^tab\/[0-9a-f]{32}\/file$/)+ })+ it('stores up to the cap and refuses one byte more, keeping nothing', async () => {+ const store = new MemoryAttachmentStore()+ expect(await store.put('k1', { name: 'x.html', mime: 'text/html' }, Readable.from([Buffer.alloc(3), Buffer.alloc(2)]), 5)).toBe(5)+ expect(store.objects.get('k1')).toMatchObject({ contentType: 'application/octet-stream', contentDisposition: "attachment; filename*=UTF-8''x.html" })+ await expect(store.put('k2', { name: 'b.bin', mime: 'application/octet-stream' }, Readable.from([Buffer.alloc(6)]), 5)).rejects.toBeInstanceOf(AttachmentTooLarge)+ expect(store.objects.has('k2')).toBe(false)})})diff --git a/backend/src/superTabs/attachments.ts b/backend/src/superTabs/attachments.tsindex ef3f42d33..545621da8 100644--- a/backend/src/superTabs/attachments.ts+++ b/backend/src/superTabs/attachments.ts@@ -1,210 +1,148 @@import { randomBytes } from 'node:crypto'-import type { Prisma, SuperTab, SuperTabAttachment } from '@prisma/client'+import { Readable, Transform, Writable } from 'node:stream'+import { pipeline } from 'node:stream/promises'import { z } from 'zod'-import type { AuthUser } from '../lib/ssoAuth.js'-import { actorKey, author, fail, stableId, type Actor, type AttachmentMeta, type SuperTabState } from './model.js'-import { readConversation } from './projects.js'-export const ATTACHMENT_MAX_BYTES = 5 * 1024 * 1024-export const ATTACHMENTS_PER_MESSAGE = 4-/** The apps reach this backend through a machine's relay (cli/src/superTabs/service.ts `backend`), and a browser's relay- * frame is 1 MiB (wsServer.ts `WS_LIMITS.web`) before E2EE sealing grows it. One 256 KiB part is about 342 KB of base64,- * so a 5 MB image travels as up to 20 small requests instead of one that no relay carries. */-export const ATTACHMENT_PART_BYTES = 256 * 1024-const PART_CHARS = Math.ceil(ATTACHMENT_PART_BYTES / 3) * 4-export const ATTACHMENT_BODY_LIMIT = PART_CHARS + 4096-/** Uploads never sent are drafts someone abandoned: an unfinished one goes after an hour, a finished one after a day,- * and one person keeps at most this many. The app deletes its own leftovers at once (`remove`); these bound the rest. */-const UNSENT_LIMIT = 24-const UNSENT_MS = 86_400_000-const INCOMPLETE_MS = 3_600_000+/** Metadata as a message stores and returns it. The bytes stay in the bucket. */+export interface Attachment { id: string; name: string; mime: string; size: number; url: string }-const id = z.string().min(1).max(160).regex(/^[A-Za-z0-9_-]+$/)-const data = z.string().min(1).max(PART_CHARS).regex(/^[A-Za-z0-9+/]+={0,2}$/, 'Send the bytes as base64.')-export const uploadAttachmentSchema = z.object({- name: z.string().trim().min(1).max(200).refine(value => !/[\x00-\x1f\x7f]/.test(value)),- size: z.number().int().min(1).max(ATTACHMENT_MAX_BYTES),- data,-}).strict()-export const attachmentPartSchema = z.object({ data }).strict()-export const attachmentIdsSchema = z.array(id).min(1).max(ATTACHMENTS_PER_MESSAGE)+export const MAX_ATTACHMENT_BYTES = 10 * 1024 * 1024+export const MAX_ATTACHMENTS = 10-type Transaction = Prisma.TransactionClient-type ImageInfo = { mime: 'image/png' | 'image/jpeg' | 'image/webp'; width: number | null; height: number | null }-interface Deps {- transaction<T>(body: (tx: Transaction) => Promise<T>): Promise<T>- row(tx: Transaction, user: AuthUser, tabId: string): Promise<{ row: SuperTab; state: SuperTabState }>- actor(tx: Transaction, user: AuthUser, state: SuperTabState, asAgentId?: string): Promise<Actor>- now(): number-}--const u16le = (bytes: Uint8Array, i: number) => (bytes[i] ?? 0) | ((bytes[i + 1] ?? 0) << 8)+// Control, format (bidi overrides, zero-width) and line/paragraph separators: a name that hides its real shape.+export const attachmentName = z.string().trim().min(1).max(255).refine(value => !/[\p{Cc}\p{Cf}\p{Zl}\p{Zp}]/u.test(value), 'Use a printable file name.')+export const attachmentMime = z.string().trim().toLowerCase().max(200).regex(/^[a-z0-9][a-z0-9!#$&^_.+-]*\/[a-z0-9][a-z0-9!#$&^_.+-]*$/)-/** The type the bytes are, read from their own header: a name or a client's word is not trusted. Width and height- * come along when the header holds them; a JPEG whose frame header is past the first part has none. */-export function imageInfo(bytes: Uint8Array): ImageInfo | null {- const at = (i: number) => bytes[i] ?? 0- const u16 = (i: number) => (at(i) << 8) | at(i + 1)- const u32 = (i: number) => ((at(i) << 24) >>> 0) + (at(i + 1) << 16) + (at(i + 2) << 8) + at(i + 3)- const le24 = (i: number) => at(i) | (at(i + 1) << 8) | (at(i + 2) << 16)- const ascii = (i: number, text: string) => [...text].every((c, n) => at(i + n) === c.charCodeAt(0))- if (bytes.length >= 8 && [0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a].every((b, i) => at(i) === b)) {- return ascii(12, 'IHDR') && bytes.length >= 24 ? { mime: 'image/png', width: u32(16), height: u32(20) } : { mime: 'image/png', width: null, height: null }- }- if (bytes.length >= 3 && at(0) === 0xff && at(1) === 0xd8 && at(2) === 0xff) {- for (let i = 2; i + 9 < bytes.length;) {- if (at(i) !== 0xff) break- const marker = at(i + 1)- if (marker === 0xff) { i++; continue }- if (marker >= 0xc0 && marker <= 0xcf && ![0xc4, 0xc8, 0xcc].includes(marker)) return { mime: 'image/jpeg', width: u16(i + 7), height: u16(i + 5) }- if (marker === 0x01 || (marker >= 0xd0 && marker <= 0xd9)) { i += 2; continue }- i += 2 + u16(i + 2)- }- return { mime: 'image/jpeg', width: null, height: null }- }- if (bytes.length >= 16 && ascii(0, 'RIFF') && ascii(8, 'WEBP')) {- if (ascii(12, 'VP8 ') && bytes.length >= 30) return { mime: 'image/webp', width: u16le(bytes, 26) & 0x3fff, height: u16le(bytes, 28) & 0x3fff }- if (ascii(12, 'VP8L') && bytes.length >= 25) {- const [b0, b1, b2, b3] = [at(21), at(22), at(23), at(24)]- return { mime: 'image/webp', width: 1 + (((b1 & 0x3f) << 8) | b0), height: 1 + (((b3 & 0x0f) << 10) | (b2 << 2) | ((b1 & 0xc0) >> 6)) }- }- if (ascii(12, 'VP8X') && bytes.length >= 30) return { mime: 'image/webp', width: 1 + le24(24), height: 1 + le24(27) }- return { mime: 'image/webp', width: null, height: null }- }- return null+export class AttachmentTooLarge extends Error {+ constructor() { super(`A file can be at most ${MAX_ATTACHMENT_BYTES / 1024 / 1024} MB.`) }}-const partId = (attachmentId: string, index: number) => stableId('attachment-part', attachmentId, String(index))-const partBytes = (record: SuperTabAttachment, index: number) =>- index === record.parts - 1 ? record.size - ATTACHMENT_PART_BYTES * (record.parts - 1) : ATTACHMENT_PART_BYTES-export const attachmentMeta = (record: SuperTabAttachment): AttachmentMeta => ({ id: record.id, name: record.name, mime: record.mime,- size: record.size, width: record.width ?? null, height: record.height ?? null, parts: record.parts })-/** What a message.send names, checked in its transaction: the sender's own finished uploads in this tab, each unsent.- * An id from another tab, another person or an earlier message is refused rather than shared. */-export async function attachmentsForSend(tx: Transaction, tabId: string, actor: Actor, ids: string[]): Promise<AttachmentMeta[]> {- if (new Set(ids).size !== ids.length) fail('INVALID_ATTACHMENT', 'Attach each image once.', 400)- const rows = await tx.superTabAttachment.findMany({ where: { id: { in: ids }, tabId } })- return ids.map(attachmentId => {- const record = rows.find(r => r.id === attachmentId)- if (!record || record.actorKey !== actorKey(actor) || record.messageId) fail('INVALID_ATTACHMENT', 'This image is no longer available. Attach it again.', 400)- if (!record.complete) fail('ATTACHMENT_INCOMPLETE', 'Wait for the image to finish uploading.')- return attachmentMeta(record)- })+/** The bucket behind the CDN. Tests and the local rig use the in-memory store below. */+export interface AttachmentStore {+ /** Streams `body` into the object and answers its size. Past `cap` bytes it throws AttachmentTooLarge and leaves no object. */+ put(objectKey: string, file: { name: string; mime: string }, body: Readable, cap: number): Promise<number>}+export interface Attachments { store: AttachmentStore; prefix: string; publicBase: string }-/** Sent, an attachment is read with its message: whoever can read that conversation. */-export async function attachToMessage(tx: Transaction, tabId: string, ids: string[], conversationId: string, messageId: string) {- const { count } = await tx.superTabAttachment.updateMany({ where: { id: { in: ids }, tabId, messageId: null }, data: { messageId, conversationId } })- // attachmentsForSend read them unsent in this transaction; anything else is a concurrent send, which must not commit.- if (count !== ids.length) fail('INVALID_ATTACHMENT', 'This image is no longer available. Attach it again.', 400)+/** Anyone holding a link can open the file, so the key carries 128 random bits; the name segment is for people. */+export function objectKeyFor(prefix: string, tabId: string, name: string): string {+ const safe = name.replaceAll(/[^A-Za-z0-9._-]+/g, '_').replace(/^[._]+/, '').slice(-120) || 'file'+ return [prefix.replace(/^\/+|\/+$/g, ''), tabId, randomBytes(16).toString('hex'), safe].filter(Boolean).join('/')+}+export const publicUrl = (base: string, objectKey: string) => `${base.replace(/\/+$/, '')}/${objectKey}`++/** How the bucket serves a file. The CDN shares a parent domain with the apps, so only raster images keep their type+ * and open in the browser. Anything else, HTML and SVG included, is stored as bytes to download, never run as a page.+ * The message keeps the declared type for clients to show. */+const INLINE = new Set(['image/png', 'image/jpeg', 'image/gif', 'image/webp'])+export function served(name: string, mime: string): { contentType: string; contentDisposition: string } {+ const inline = INLINE.has(mime)+ return { contentType: inline ? mime : 'application/octet-stream',+ contentDisposition: `${inline ? 'inline' : 'attachment'}; filename*=UTF-8''${encodeURIComponent(name)}` }}-/** The text stored for a message of images alone, so a client that shows no images still shows something. Clients- * that draw the images hide it (desktop model.dart `SuperTabMessage.shownText`). */-export const imagesPlaceholder = (count: number) => count === 1 ? '[image]' : `[${count} images]`--/** Images people attach to messages. Bytes never ride a message read; they are read part by part here. */-export class SuperTabAttachmentStore {- constructor(private readonly deps: Deps) {}+/** The raster type the first bytes really are, or null. */+export function imageTypeOf(head: Buffer): string | null {+ const ascii = (at: number, text: string) => head.subarray(at, at + text.length).toString('latin1') === text+ if (head.length >= 8 && head.subarray(0, 8).equals(Buffer.from([0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a]))) return 'image/png'+ if (head.length >= 3 && head[0] === 0xff && head[1] === 0xd8 && head[2] === 0xff) return 'image/jpeg'+ if (ascii(0, 'GIF87a') || ascii(0, 'GIF89a')) return 'image/gif'+ if (head.length >= 12 && ascii(0, 'RIFF') && ascii(8, 'WEBP')) return 'image/webp'+ return null+}- private async writer(tx: Transaction, user: AuthUser, tabId: string, asAgentId?: string) {- const { state } = await this.deps.row(tx, user, tabId)- const actor = await this.deps.actor(tx, user, state, asAgentId)- author(state, actor, true)- return actor+/** A file that claims to be an image is served as one only when its first bytes agree, and then as what they say: a+ * renamed page or script never opens inline, and a .png that is really a JPEG still shows. `body` is handed back with+ * those bytes in front, so the store still reads the whole file as a stream. */+export async function checkedType(mime: string, body: Readable): Promise<{ mime: string; body: Readable }> {+ if (!INLINE.has(mime)) return { mime, body }+ // One iterator for the whole read: leaving a `for await` early would destroy the request stream.+ const source = body[Symbol.asyncIterator]()+ const parts: Buffer[] = []+ let length = 0, done = false+ while (length < 16) {+ const next = await source.next()+ if (next.done) { done = true; break }+ parts.push(Buffer.from(next.value)); length += next.value.length}-- /** Before it is sent only its uploader sees an attachment; after, whoever can read its conversation. Both fail alike. */- private async readable(tx: Transaction, user: AuthUser, tabId: string, attachmentId: string, asAgentId?: string) {- const { state } = await this.deps.row(tx, user, tabId)- const actor = await this.deps.actor(tx, user, state, asAgentId)- author(state, actor)- const record = await tx.superTabAttachment.findFirst({ where: { id: attachmentId, tabId } })- if (record?.conversationId) readConversation(state, actor, record.conversationId)- else if (!record || record.actorKey !== actorKey(actor)) fail('NOT_FOUND', 'This image is unavailable.', 404)- return record!+ const head = Buffer.concat(parts)+ const rest = async function* () {+ if (head.length) yield head+ while (!done) {+ const next = await source.next()+ if (next.done) return+ yield Buffer.from(next.value)+ }}+ return { mime: imageTypeOf(head) ?? 'application/octet-stream', body: Readable.from(rest()) }+}- /** Creates the attachment with its first part, which carries the header that proves the image's type. */- async upload(user: AuthUser, tabId: string, input: z.infer<typeof uploadAttachmentSchema>, asAgentId?: string) {- const request = uploadAttachmentSchema.parse(input)- const first = Buffer.from(request.data, 'base64')- const parts = Math.ceil(request.size / ATTACHMENT_PART_BYTES)- if (first.length !== Math.min(request.size, ATTACHMENT_PART_BYTES)) fail('INVALID_ATTACHMENT', 'The image arrived incomplete. Attach it again.', 400)- const info = imageInfo(first) ?? fail('UNSUPPORTED_ATTACHMENT', 'Attach a PNG, JPEG, or WebP image.', 400)- return this.deps.transaction(async tx => {- const actor = await this.writer(tx, user, tabId, asAgentId)- const key = actorKey(actor)- const stale = await tx.superTabAttachment.findMany({ where: { tabId, actorKey: key, messageId: null, OR: [- { createdAt: { lt: new Date(this.deps.now() - UNSENT_MS) } },- { complete: false, createdAt: { lt: new Date(this.deps.now() - INCOMPLETE_MS) } },- ] }, select: { id: true }, take: 100 })- if (stale.length) {- await tx.superTabAttachmentPart.deleteMany({ where: { attachmentId: { in: stale.map(s => s.id) } } })- await tx.superTabAttachment.deleteMany({ where: { id: { in: stale.map(s => s.id) } } })- }- if (await tx.superTabAttachment.count({ where: { tabId, actorKey: key, messageId: null } }) >= UNSENT_LIMIT) {- fail('ATTACHMENT_LIMIT', 'Too many images are waiting to be sent. Send or remove the ones in your messages, or try again in an hour.', 429)- }- const attachmentId = randomBytes(12).toString('hex')- // Unsent is an explicit null: MongoDB's `messageId: null` filter does not match a field that was never written.- const record = await tx.superTabAttachment.create({ data: { id: attachmentId, tabId, actorKey: key, conversationId: null, messageId: null,- name: request.name, mime: info.mime, size: request.size, width: info.width, height: info.height, parts, complete: parts === 1 } })- await tx.superTabAttachmentPart.create({ data: { id: partId(attachmentId, 0), attachmentId, index: 0, data: first } })- return { ...attachmentMeta(record), complete: record.complete }- })- }+/** Counts what passes and fails the stream past `cap`, so a writer never commits more. */+async function capped(body: Readable, cap: number, sink: Writable): Promise<number> {+ let size = 0+ await pipeline(body, new Transform({ transform(chunk: Buffer, _encoding, done) {+ size += chunk.byteLength+ done(size > cap ? new AttachmentTooLarge() : null, chunk)+ } }), sink)+ return size+}- /** Repeating a part replaces it, so a retry after a lost reply is safe. A finished attachment no longer changes. */- async uploadPart(user: AuthUser, tabId: string, attachmentId: string, index: number, input: z.infer<typeof attachmentPartSchema>, asAgentId?: string) {- const bytes = Buffer.from(attachmentPartSchema.parse(input).data, 'base64')- return this.deps.transaction(async tx => {- const actor = await this.writer(tx, user, tabId, asAgentId)- const record = await tx.superTabAttachment.findFirst({ where: { id: attachmentId, tabId } })- if (!record || record.actorKey !== actorKey(actor)) fail('NOT_FOUND', 'This image is unavailable.', 404)- if (record.complete) return { id: record.id, complete: true }- if (index < 1 || index >= record.parts || bytes.length !== partBytes(record, index)) {- fail('INVALID_ATTACHMENT', 'The image arrived incomplete. Attach it again.', 400)- }- await tx.superTabAttachmentPart.upsert({ where: { attachmentId_index: { attachmentId, index } },- create: { id: partId(attachmentId, index), attachmentId, index, data: bytes }, update: { data: bytes } })- const complete = await tx.superTabAttachmentPart.count({ where: { attachmentId } }) === record.parts- // Always written: two final parts in parallel then conflict on this document and one retries, seeing both parts.- await tx.superTabAttachment.update({ where: { id: attachmentId }, data: { complete } })- return { id: record.id, complete }- })- }+/** A service account key the bucket is written with. */+export interface ServiceAccount { projectId?: string; credentials: { client_email: string; private_key: string } }++/** SUPER_TAB_ATTACHMENTS_CREDENTIALS: the base64 of a service account JSON key, or empty for application default+ * credentials. A bad value stops the backend at startup. No message repeats any of the value: JSON.parse's own+ * message quotes the text it failed on, so it is never passed on. */+export function serviceAccountFrom(raw: string): ServiceAccount | null {+ const value = raw.replaceAll(/\s+/g, '')+ if (!value) return null+ const invalid = (why: string): never => { throw new Error(`SUPER_TAB_ATTACHMENTS_CREDENTIALS ${why}. Set the base64 of the service account JSON key, or leave it empty to use application default credentials.`) }+ if (!/^[A-Za-z0-9+/]+={0,2}$/.test(value) || value.length % 4 === 1) invalid('is not base64')+ let key: Record<string, unknown> = {}+ try { key = JSON.parse(Buffer.from(value, 'base64').toString('utf8')) } catch { invalid('does not decode to JSON') }+ if (!key || typeof key !== 'object' || typeof key.client_email !== 'string' || !key.client_email+ || typeof key.private_key !== 'string' || !key.private_key.includes('PRIVATE KEY')) invalid('is not a service account key with client_email and private_key')+ return { ...(typeof key.project_id === 'string' ? { projectId: key.project_id } : {}),+ credentials: { client_email: key.client_email as string, private_key: key.private_key as string } }+}- /** Its uploader takes back an image not yet sent: removed from the composer, replaced, or left over from a failed send. */- async remove(user: AuthUser, tabId: string, attachmentId: string, asAgentId?: string) {- return this.deps.transaction(async tx => {- const actor = await this.writer(tx, user, tabId, asAgentId)- const record = await tx.superTabAttachment.findFirst({ where: { id: attachmentId, tabId } })- if (!record || record.actorKey !== actorKey(actor)) fail('NOT_FOUND', 'This image is unavailable.', 404)- if (record.messageId) fail('ATTACHMENT_SENT', 'This image was already sent.')- await tx.superTabAttachmentPart.deleteMany({ where: { attachmentId } })- await tx.superTabAttachment.delete({ where: { id: attachmentId } })- return { id: attachmentId, deleted: true }- })+export class GcsAttachmentStore implements AttachmentStore {+ private bucket: Promise<import('@google-cloud/storage').Bucket> | null = null+ constructor(private readonly name: string, private readonly account: ServiceAccount | null = null) {}+ // Loaded on first use, so a backend without a bucket never loads the client.+ private files() {+ this.bucket ??= import('@google-cloud/storage').then(({ Storage }) => new Storage(this.account ?? undefined).bucket(this.name))+ return this.bucket+ }+ async put(objectKey: string, file: { name: string; mime: string }, body: Readable, cap: number) {+ const { contentType, contentDisposition } = served(file.name, file.mime)+ // One request, not a resumable session: a failed or refused stream aborts it and no object is written.+ const sink = (await this.files()).file(objectKey).createWriteStream({ resumable: false, contentType,+ metadata: { contentDisposition, cacheControl: 'public, max-age=31536000, immutable' } })+ return capped(body, cap, sink)}+}- async read(user: AuthUser, tabId: string, attachmentId: string, asAgentId?: string) {- return this.deps.transaction(async tx => {- const record = await this.readable(tx, user, tabId, attachmentId, asAgentId)- // An unfinished upload is its uploader's alone: which parts it still needs lets an interrupted upload resume.- const missing = record.complete ? [] : await tx.superTabAttachmentPart.findMany({ where: { attachmentId }, select: { index: true } })- .then(have => Array.from({ length: record.parts }, (_, i) => i).filter(i => !have.some(p => p.index === i)))- return { ...attachmentMeta(record), complete: record.complete, ...(record.complete ? {} : { missing }) }- })+export class MemoryAttachmentStore implements AttachmentStore {+ readonly objects = new Map<string, { bytes: Buffer; contentType: string; contentDisposition: string }>()+ async put(objectKey: string, file: { name: string; mime: string }, body: Readable, cap: number) {+ const chunks: Buffer[] = []+ const size = await capped(body, cap, new Writable({ write(chunk: Buffer, _encoding, done) { chunks.push(chunk); done() } }))+ this.objects.set(objectKey, { bytes: Buffer.concat(chunks), ...served(file.name, file.mime) })+ return size}+}- /** One part's bytes, base64 in the JSON reply like every relayed answer. */- async readPart(user: AuthUser, tabId: string, attachmentId: string, index: number, asAgentId?: string) {- return this.deps.transaction(async tx => {- const record = await this.readable(tx, user, tabId, attachmentId, asAgentId)- const part = await tx.superTabAttachmentPart.findUnique({ where: { attachmentId_index: { attachmentId, index } } })- if (!part || part.index >= record.parts) fail('NOT_FOUND', 'This part of the image is unavailable.', 404)- return { id: record.id, index, parts: record.parts, data: Buffer.from(part.data).toString('base64') }- })+export function attachmentsFromEnv(env: { NODE_ENV: string; SUPER_TAB_ATTACHMENTS_BUCKET: string; SUPER_TAB_ATTACHMENTS_CREDENTIALS: string;+ SUPER_TAB_ATTACHMENTS_PREFIX: string; SUPER_TAB_ATTACHMENTS_PUBLIC_BASE: string }): Attachments | null {+ // Every message carries these links and every agent's computer downloads from them: in production only over HTTPS.+ // A local or test run may serve them from a plain loopback server.+ if (env.NODE_ENV === 'production' && new URL(env.SUPER_TAB_ATTACHMENTS_PUBLIC_BASE).protocol !== 'https:') {+ throw new Error('SUPER_TAB_ATTACHMENTS_PUBLIC_BASE must be an https:// address in production.')}+ // Read even without a bucket, so a broken key fails the deploy that set it rather than the one that adds the bucket.+ const account = serviceAccountFrom(env.SUPER_TAB_ATTACHMENTS_CREDENTIALS)+ if (!env.SUPER_TAB_ATTACHMENTS_BUCKET) return null+ return { store: new GcsAttachmentStore(env.SUPER_TAB_ATTACHMENTS_BUCKET, account), prefix: env.SUPER_TAB_ATTACHMENTS_PREFIX,+ publicBase: env.SUPER_TAB_ATTACHMENTS_PUBLIC_BASE }}diff --git a/backend/src/superTabs/commands.test.ts b/backend/src/superTabs/commands.test.tsindex c40e3767c..da2d6f182 100644--- a/backend/src/superTabs/commands.test.ts+++ b/backend/src/superTabs/commands.test.ts@@ -96,23 +96,6 @@ describe('Super Tab collaboration policy', () => {{ reply: { id: posted.id, conversationId: 'elsewhere', author: posted.author } })).toThrow('Reply to a message in this conversation')})- it('sends images the store checked, with or without text, and refuses a message with neither', () => {- const f = fixture()- const lead = f.add('lead', 'owner', 'lead', true)- const image = { id: 'img1', name: 'screen.png', mime: 'image/png', size: 10, width: 2, height: 1, parts: 1 }- const send = (text: string, attachmentIds?: string[]): Command =>- ({ type: 'message.send', conversationId: 'lead', text, replyTo: null, recipientIds: [], ...(attachmentIds ? { attachmentIds } : {}) })- const only = f.run(send('', ['img1']), owner, { attachments: [image] }).messages[0]!- expect(only).toMatchObject({ text: '[image]', recipients: [lead], attachments: [image] })- expect(f.run(send('', ['img1', 'img2']), owner, { attachments: [image, { ...image, id: 'img2' }] }).messages[0]!.text).toBe('[2 images]')- expect(f.run(send('Plain text')).messages[0]!).not.toHaveProperty('attachments')- expect(() => f.run(send(''))).toThrow('Write a message or attach an image')- expect(() => f.run(send('Hi', ['img1']))).toThrow('no longer available')- expect(() => f.run(send('Hi', ['img2']), owner, { attachments: [image] })).toThrow('no longer available')- expect(commandSchema.safeParse(send('Five', ['a', 'b', 'c', 'd', 'e'])).success).toBe(false)- expect(commandSchema.safeParse(send('Old client')).success).toBe(true)- })-it('lets a viewer read and leave, but not send, assign, attach or invite', () => {const f = fixture()f.invite('viewer')@@ -498,3 +481,26 @@ it('rejects embedded credentials in shared project metadata', () => {expect(commandSchema.safeParse({ type: 'project.repository', projectId: 'lead', repositoryUrl: 'github.com/example/project' }).success).toBe(false)expect(commandSchema.safeParse({ type: 'project.repository', projectId: 'lead', repositoryUrl: null }).success).toBe(false)})++describe('message attachments', () => {+ const file = { id: 'file-1', name: 'screen.png', mime: 'image/png', size: 12, url: 'https://cdn.example.test/super-tabs/tab/abc/screen.png' }+ const send = (attachmentIds?: string[], text = ''): Command => ({ type: 'message.send', conversationId: 'lead', text, replyTo: null, recipientIds: [], ...(attachmentIds ? { attachmentIds } : {}) })+ it('records verified files on the message and allows empty text with one', () => {+ const f = fixture()+ const sent = f.run(send(['file-1', 'file-1']), owner, { attachments: [file] })+ expect(sent.messages).toEqual([expect.objectContaining({ text: '', attachments: [file] })])+ expect(f.run(send(undefined, 'Plain text.')).messages[0]).not.toHaveProperty('attachments')+ })+ it('refuses empty text without files and a file the store did not verify', () => {+ const f = fixture()+ expect(() => f.run(send())).toThrow('Write a message or attach a file.')+ expect(() => f.run(send(['file-1']))).toThrow('Upload this file again')+ expect(() => commandSchema.parse(send(Array.from({ length: 11 }, (_, i) => `file-${i}`)))).toThrow()+ })+ it('resends a message with its files', () => {+ const f = fixture(), lead = f.add('lead', 'owner', 'lead', true)+ const resent = f.run({ type: 'delivery.resolve', deliveryId: 'd', resolution: 'resend' }, owner,+ { delivery: { id: 'd', conversationId: 'lead', agentId: lead, messageId: 'm', text: '', attachments: [file] } })+ expect(resent.messages[0]).toMatchObject({ recipients: [lead], attachments: [file] })+ })+})diff --git a/backend/src/superTabs/commands.ts b/backend/src/superTabs/commands.tsindex e2f33353a..75df0ab8d 100644--- a/backend/src/superTabs/commands.ts+++ b/backend/src/superTabs/commands.ts@@ -2,11 +2,11 @@ import { admitMachineStart, machineContribution } from './machines.js'import { z } from 'zod'import {activeWork, actorKey, agent, author, conversation, fail, person, stableId, numberConversations, nextConversationNumber,- type Actor, type Agent, type AttachmentMeta, type Author, type CommandEffects, type SuperTabState,+ type Actor, type Agent, type Author, type CommandEffects, type SuperTabState,} from './model.js'-import { attachmentIdsSchema, imagesPlaceholder } from './attachments.js'import { routeRecordSchema, routeTitle, startedAs, type RouteCandidate, type RouteDecision, type RouteFinal, type RouteOverride } from './routeRecord.js'import { routingOverrideSchema } from './routingPolicy.js'+import { MAX_ATTACHMENTS, type Attachment } from './attachments.js'import { agentProjectId, deleteProject, groupProject, manageProject, mutableProjects, projectMembers, projectOf, readAgent, readConversation, readProject, sameProject } from './projects.js'const id = z.string().min(1).max(160).regex(/^[A-Za-z0-9_-]+$/)@@ -71,9 +71,9 @@ export const commandSchema = z.discriminatedUnion('type', [z.object({ type: z.literal('invite.revoke'), inviteId: id }).strict(),z.object({ type: z.literal('invite.accept'), inviteId: id }).strict(),z.object({ type: z.literal('member.remove'), userId: id }).strict(),- // Text may be empty when the message carries an image; applyCommand refuses a message with neither.- z.object({ type: z.literal('message.send'), conversationId: id, text: z.string().trim().max(32_000), replyTo: id.nullable(),- recipientIds: z.array(id).max(16), attachmentIds: attachmentIdsSchema.optional() }).strict(),+ // Text may be empty when the message carries files; applyCommand checks that one of them is there.+ z.object({ type: z.literal('message.send'), conversationId: id, text: z.string().trim().max(32_000), replyTo: id.nullable(), recipientIds: z.array(id).max(16),+ attachmentIds: z.array(id).max(MAX_ATTACHMENTS).optional() }).strict(),z.object({ type: z.literal('delivery.resolve'), deliveryId: id, resolution: z.enum(['received', 'resend', 'cancel']) }).strict(),z.object({ type: z.literal('work.define'), conversationId: id, brief: text, checks: z.array(check).min(1).max(40) }).strict(),z.object({ type: z.literal('work.assign'), conversationId: id, agentId: id, routeDecisionId: id.optional(), overrideReason: reason.optional() }).strict(),@@ -97,9 +97,9 @@ export interface CommandContext {/** A host's receipt, not an elapsed lease, proves that an assignment stopped. */confirmedStopped?: boolean/** An uncertain receipt and its original message, read transactionally. */- delivery?: { id: string; conversationId: string; agentId: string; messageId: string; text: string; attachments?: AttachmentMeta[] }- /** The images a message.send names, checked by the store (attachments.ts `attachmentsForSend`). */- attachments?: AttachmentMeta[]+ delivery?: { id: string; conversationId: string; agentId: string; messageId: string; text: string; attachments?: Attachment[] }+ /** The files `message.send` names, each checked by the store: uploaded by this actor to this conversation, and unused. */+ attachments?: Attachment[]/** Route decisions this tab recorded in the last hour, counted by the store. */recentRoutes?: number/** The decision a command names, read from SuperTabRouteDecision by the store. */@@ -135,6 +135,12 @@ export function authorizeCommandAccess(state: SuperTabState, actor: Actor, commareadConversation(state, actor, context.routeDecision.conversationId)}}+/** Who may post in a conversation may also upload a file to it. Writer access is checked by `author(state, actor, true)`. */+export function postable(state: SuperTabState, actor: Actor, conversationId: string) {+ const group = open(state, conversationId)+ if (actor.kind === 'agent' && !group.agentIds.includes(actor.agentId)) fail('FORBIDDEN', 'This agent does not participate in the conversation.', 403)+ return group+}function owner(state: SuperTabState, actor: Actor): void {if (actor.kind !== 'person' || actor.userId !== state.ownerId) fail('OWNER_REQUIRED', 'Only the Super Tab owner can manage invitations.', 403)}@@ -175,9 +181,9 @@ export function applyCommand(original: SuperTabState, actor: Actor, input: Commabrief: group.brief, checks: group.checks, assignment: group.assignment }))}const message = (conversationId: string, body: string, recipients: string[] = [], replyTo: string | null = null, source?: Record<string, unknown>,- attachments: AttachmentMeta[] = []) => {+ attachments?: Attachment[]) => {effects.messages.push({ id: operationId, conversationId, author: sender, text: body, replyTo, recipients, ...(source ? { source } : {}),- ...(attachments.length ? { attachments } : {}) })+ ...(attachments?.length ? { attachments } : {}) })result.messageId = operationId}const openDecision = (): RouteDecision => {@@ -536,8 +542,10 @@ export function applyCommand(original: SuperTabState, actor: Actor, input: Commabreak}case 'message.send': {- const group = open(state, command.conversationId)- if (actor.kind === 'agent' && !group.agentIds.includes(actor.agentId)) fail('FORBIDDEN', 'This agent does not participate in the conversation.', 403)+ const group = postable(state, actor, command.conversationId)+ const ids = [...new Set(command.attachmentIds ?? [])]+ const attachments = ids.map(id => context.attachments?.find(a => a.id === id) ?? fail('ATTACHMENT_UNAVAILABLE', 'Upload this file again before sending it.', 400))+ if (!command.text && !attachments.length) fail('TEXT_REQUIRED', 'Write a message or attach a file.', 400)if (command.replyTo && (!context.reply || context.reply.id !== command.replyTo || context.reply.conversationId !== group.id)) {fail('INVALID_REPLY', 'Reply to a message in this conversation.', 400)}@@ -548,13 +556,8 @@ export function applyCommand(original: SuperTabState, actor: Actor, input: Commaagent(state, id)if (!group.agentIds.includes(id)) fail('INVALID_RECIPIENT', 'Choose an agent in this conversation.', 400)}- const attachments = command.attachmentIds?.length ? context.attachments ?? [] : []- if (attachments.length !== (command.attachmentIds?.length ?? 0) || attachments.some((a, i) => a.id !== command.attachmentIds![i])) {- fail('INVALID_ATTACHMENT', 'This image is no longer available. Attach it again.', 400)- }- if (!command.text && !attachments.length) fail('EMPTY_MESSAGE', 'Write a message or attach an image.', 400)// The transcript still accepts a human message while the lead is unavailable. The UI can say why no delivery was created.- message(group.id, command.text || imagesPlaceholder(attachments.length), recipients, command.replyTo, undefined, attachments)+ message(group.id, command.text, recipients, command.replyTo, undefined, attachments)break}case 'delivery.resolve': {@@ -566,7 +569,7 @@ export function applyCommand(original: SuperTabState, actor: Actor, input: Commaif (command.resolution === 'resend') {open(state, group.id)if (!group.agentIds.includes(target.id)) fail('INVALID_RECIPIENT', 'This agent is no longer in the conversation.', 400)- message(group.id, delivery.text, [target.id], delivery.messageId, undefined, delivery.attachments ?? [])+ message(group.id, delivery.text, [target.id], delivery.messageId, undefined, delivery.attachments)} else {message(group.id, command.resolution === 'received'? `Checked ${target.name}’s terminal and confirmed the earlier instruction was received.`diff --git a/backend/src/superTabs/model.ts b/backend/src/superTabs/model.tsindex 548b2ef22..7c3761747 100644--- a/backend/src/superTabs/model.ts+++ b/backend/src/superTabs/model.ts@@ -120,8 +120,6 @@ export type Actor =| { kind: 'person'; userId: string; email: string }| { kind: 'agent'; agentId: string; machineOwnerId: string }export interface Author { kind: 'person' | 'agent'; id: string; name: string; membershipGeneration: string }-/** What a message read carries about an attached image (attachments.ts); its bytes are read separately, part by part. */-export interface AttachmentMeta { id: string; name: string; mime: string; size: number; width: number | null; height: number | null; parts: number }export interface MessageDraft {id: stringconversationId: string@@ -129,9 +127,9 @@ export interface MessageDraft {text: stringreplyTo: string | nullrecipients: string[]- attachments?: AttachmentMeta[]/** Structured row kind for clients; `native` is written by native.ts, `route`/`route-override` by commands. */source?: Record<string, unknown>+ attachments?: import('./attachments.js').Attachment[]}export interface CommandEffects {state: SuperTabStatediff --git a/backend/src/superTabs/store.ts b/backend/src/superTabs/store.tsindex 58303232a..d9ca59d88 100644--- a/backend/src/superTabs/store.ts+++ b/backend/src/superTabs/store.ts@@ -5,15 +5,18 @@ import type { AuthUser } from '../lib/ssoAuth.js'import { machineAlive } from '../lib/prisma.js'import { machineShareGrant, sharedVia } from '../lib/machineSharePolicy.js'import { machineBillingAllowsDataPlane } from '../lib/billingState.js'-import { applyCommand, authorizeCommandAccess, operationSchema, type Command, type CommandContext } from './commands.js'+import { applyCommand, authorizeCommandAccess, operationSchema, postable, type Command, type CommandContext } from './commands.js'+import { attachmentMime, attachmentName, AttachmentTooLarge, checkedType, MAX_ATTACHMENT_BYTES, objectKeyFor, publicUrl, type Attachment, type Attachments } from './attachments.js'+import { randomBytes } from 'node:crypto'+import type { Readable } from 'node:stream'+import { logger } from '../utils/logger.js'import { canReadAgent, canReadProject, groupProject, projectsOf, readConversation, type ProjectVisibility } from './projects.js'import { bindSession, makeProjectPrivate } from './sessionScope.js'import { noteProjectReports, projectUpdateRequest } from './projectUpdates.js'import { revokeNativeContexts, SuperTabNativeStore } from './native.js'-import { attachmentsForSend, attachToMessage, SuperTabAttachmentStore } from './attachments.js'import {activeWork, actorKey, agent, author, conversation, createSuperTab, fail, person, stableId, visibleState,- SuperTabError, type Actor, type Agent, type Assignment, type AttachmentMeta, type Author, type MessageDraft, type SuperTabState,+ SuperTabError, type Actor, type Agent, type Assignment, type Author, type MessageDraft, type SuperTabState,} from './model.js'import { holdNoticeText, type HoldReason } from './holdNotice.js'import { closeAssignment, readDecision, recentRoutes, timedDecisionOf, writeRouteEffects } from './routeDecisions.js'@@ -23,6 +26,9 @@ import { authenticatedEmail, authorizeSwarmJoin, configureSharing, joinSwarmSchetype Transaction = Prisma.TransactionClientconst json = (value: unknown): Prisma.InputJsonValue => JSON.parse(JSON.stringify(value)) as Prisma.InputJsonValue+type SendCommand = Extract<Command, { type: 'message.send' }>+// Prisma on MongoDB: `usedBy: null` alone misses rows that never had the field.+const unused = { OR: [{ usedBy: null }, { usedBy: { isSet: false } }] }const hash = (value: unknown): string => createHash('sha256').update(JSON.stringify(value)).digest('hex')const stateOf = (row: SuperTab): SuperTabState => {const state = row.state as unknown as SuperTabState@@ -48,20 +54,14 @@ async function transaction<T>(db: PrismaClient, body: (tx: Transaction) => Promi/** Persistent coordination. Host adapters own execution and must confirm their local session grants. */export class SuperTabStore {readonly native: SuperTabNativeStore- readonly attachments: SuperTabAttachmentStore- constructor(private readonly db: PrismaClient, private readonly now: () => number = Date.now) {+ constructor(private readonly db: PrismaClient, private readonly now: () => number = Date.now,+ private readonly attachments: Attachments | null = null) {this.native = new SuperTabNativeStore({transaction: body => transaction(db, body),row: async (tx, user, tabId) => { const row = await this.row(tx, user, tabId); return { row, state: stateOf(row) } },agentGrant: (tx, state, target) => this.agentGrant(tx, state, target),contribution: (tx, state, actor, command) => this.contribution(tx, state, actor, command),})- this.attachments = new SuperTabAttachmentStore({- transaction: body => transaction(db, body),- row: async (tx, user, tabId) => { const row = await this.row(tx, user, tabId); return { row, state: stateOf(row) } },- actor: (tx, user, state, asAgentId) => this.actor(tx, user, state, asAgentId),- now: () => this.now(),- })}private policyId(user: AuthUser) { return stableId('routing-policy', user.sub, user.autonomousEnv) }@@ -356,8 +356,7 @@ export class SuperTabStore {}await this.agentGrant(tx, original, agent(original, delivery.agentId))}- // A resend carries the original's images with its text.- context.delivery = { ...delivery, text: message.text, attachments: (message.attachments ?? undefined) as AttachmentMeta[] | undefined }+ context.delivery = { ...delivery, text: message.text, ...(message.attachments ? { attachments: message.attachments as unknown as Attachment[] } : {}) }await tx.superTabDelivery.update({ where: { id: delivery.id }, data: {status: command.resolution === 'received' ? 'confirmed' : command.resolution === 'resend' ? 'superseded' : 'cancelled',// The native receipt remains intact; the operation records the person's resolution.@@ -371,9 +370,6 @@ export class SuperTabStore {const start = original.starts?.find(s => s.id === command.startId) ?? fail('NOT_FOUND', 'This agent start is unavailable.', 404)context.contribution = await this.contribution(tx, original, actor, start.request, true)}- if (command.type === 'message.send' && command.attachmentIds?.length) {- context.attachments = await attachmentsForSend(tx, tabId, actor, command.attachmentIds)- }if (command.type === 'message.send' && command.replyTo) {const reply = await tx.superTabMessage.findFirst({ where: { id: command.replyTo, tabId, conversationId: command.conversationId } })if (reply) context.reply = { id: reply.id, conversationId: reply.conversationId, author: reply.author as unknown as Author }@@ -384,6 +380,7 @@ export class SuperTabStore {context.confirmedStopped = !!proof && !!execution && proof.machineId === execution.machineId &&proof.harnessId === execution.harnessId && proof.machineOwnerId === execution.machineOwnerId}+ if (command.type === 'message.send' && command.attachmentIds?.length) context.attachments = await this.sendable(tx, tabId, actor, command)if (command.type === 'route.record') context.recentRoutes = await recentRoutes(tx, tabId, context.now)const decisionId = command.type === 'route.override' || command.type === 'route.modelResult' ? command.decisionId: command.type === 'work.assign' || command.type === 'agent.start' ? command.routeDecisionId : undefined@@ -442,8 +439,11 @@ export class SuperTabStore {await closeAssignment(tx, tabId, command.assignmentId, command.status, context.now)}await this.writeMessages(tx, tabId, effects.state, effects.messages, revision)- if (command.type === 'message.send' && command.attachmentIds?.length) {- await attachToMessage(tx, tabId, command.attachmentIds, command.conversationId, effects.result.messageId as string)+ if (context.attachments?.length) {+ // Conflicts with a concurrent send of the same file: only one message can take it.+ const taken = await tx.superTabAttachment.updateMany({ where: { tabId, id: { in: context.attachments.map(a => a.id) }, ...unused },+ data: { usedBy: effects.result.messageId as string } })+ if (taken.count !== context.attachments.length) fail('ATTACHMENT_USED', 'This file was already sent. Attach it again to send it in another message.')}// On 2026-10-20 a Lead answered a message it had already read, then answered it again when the held// delivery was finally typed. An agent's reply settles that agent's own deliveries of the message.@@ -478,12 +478,68 @@ export class SuperTabStore {})}+ /** Streams one file into the bucket for a later `message.send` by the same actor in the same conversation. Access is+ * checked before a byte is stored; the row that makes it sendable is written only once the whole file is. */+ async upload(user: AuthUser, tabId: string, conversationId: string, file: { name: string; mime: string; body: Readable }, asAgentId?: string) {+ const attachments = this.attachments ?? fail('ATTACHMENTS_UNAVAILABLE', 'File attachments are not available on this server.', 503)+ const name = attachmentName.safeParse(file.name), mime = attachmentMime.safeParse(file.mime)+ if (!name.success || !mime.success) fail('INVALID_ATTACHMENT', 'Attach a file with a printable name and a content type.', 400)+ const key = await transaction(this.db, async tx => {+ const { actor } = await this.poster(tx, user, tabId, conversationId, asAgentId)+ const key = actorKey(actor)+ // Unsent files cost bucket space, so one actor gets a bounded number an hour.+ const recent = await tx.superTabAttachment.count({ where: { tabId, actorKey: key, createdAt: { gte: new Date(this.now() - 3_600_000) } } })+ if (recent >= 200) fail('RATE_LIMITED', 'You attached 200 files in the last hour. Wait before attaching more.', 429)+ return key+ })+ const objectKey = objectKeyFor(attachments.prefix, tabId, name.data)+ let size: number, stored = mime.data+ try {+ const checked = await checkedType(mime.data, file.body)+ stored = checked.mime+ size = await attachments.store.put(objectKey, { name: name.data, mime: stored }, checked.body, MAX_ATTACHMENT_BYTES)+ } catch (error) {+ if (error instanceof AttachmentTooLarge) fail('ATTACHMENT_TOO_LARGE', error.message, 413)+ // The client's own stream breaking is the request's; anything else is the bucket's, and the person can try again.+ if (file.body.errored || (error && typeof error === 'object' && 'code' in error && String(error.code).startsWith('FST_'))) throw error+ logger.error('super-tab attachment storage failed', { tabId, error: error instanceof Error ? error.message : String(error) })+ fail('ATTACHMENTS_UNAVAILABLE', 'Could not store the file just now. Try again.', 503)+ }+ const row = await this.db.superTabAttachment.create({ data: { id: randomBytes(12).toString('hex'), tabId, conversationId,+ actorKey: key, name: name.data, mime: stored, size, objectKey } })+ return { attachment: { id: row.id, name: row.name, mime: row.mime, size: row.size, url: publicUrl(attachments.publicBase, objectKey) } satisfies Attachment }+ }++ /** The actor, once it may post in this conversation. */+ private async poster(tx: Transaction, user: AuthUser, tabId: string, conversationId: string, asAgentId?: string) {+ const state = stateOf(await this.row(tx, user, tabId))+ const actor = await this.actor(tx, user, state, asAgentId)+ author(state, actor, true)+ readConversation(state, actor, conversationId)+ postable(state, actor, conversationId)+ return { state, actor }+ }++ private async sendable(tx: Transaction, tabId: string, actor: Actor, command: SendCommand): Promise<Attachment[]> {+ const attachments = this.attachments ?? fail('ATTACHMENTS_UNAVAILABLE', 'File attachments are not available on this server.', 503)+ const ids = [...new Set(command.attachmentIds)]+ const rows = await tx.superTabAttachment.findMany({ where: { tabId, id: { in: ids } } })+ return ids.map(id => {+ const row = rows.find(r => r.id === id)+ if (!row || row.actorKey !== actorKey(actor) || row.conversationId !== command.conversationId) {+ fail('ATTACHMENT_UNAVAILABLE', 'Attach this file again before sending it.', 400)+ }+ if (row.usedBy) fail('ATTACHMENT_USED', 'This file was already sent. Attach it again to send it in another message.')+ return { id: row.id, name: row.name, mime: row.mime, size: row.size, url: publicUrl(attachments.publicBase, row.objectKey) }+ })+ }+/** Records committed messages and one delivery per recipient, at the tab revision that carried them. */private async writeMessages(tx: Transaction, tabId: string, state: SuperTabState, messages: MessageDraft[], revision: number) {for (const message of messages) {await tx.superTabMessage.create({ data: { id: message.id, tabId, conversationId: message.conversationId,sequence: revision, author: json(message.author), ...(message.source ? { source: json(message.source) } : {}),- ...(message.attachments?.length ? { attachments: json(message.attachments) } : {}),+ ...(message.attachments ? { attachments: json(message.attachments) } : {}),text: message.text, replyTo: message.replyTo, recipientIds: message.recipients } })for (const recipient of message.recipients) {const target = agent(state, recipient)diff --git a/cli/src/config/env.ts b/cli/src/config/env.tsindex b228a3e36..8306b2f85 100644--- a/cli/src/config/env.ts+++ b/cli/src/config/env.ts@@ -244,6 +244,12 @@ const fields = {// and every `harness` command with it).HARNESS_STORE_CATALOG_URL: url((address) => !address.username && !address.password && (address.protocol === 'https:'|| (address.protocol === 'http:' && ['127.0.0.1', 'localhost', '[::1]'].includes(address.hostname)))),+ // Where Super Tab chat files are served: the backend's SUPER_TAB_ATTACHMENTS_PUBLIC_BASE. The host downloads a+ // delivered message's files from here alone, so a message cannot make this computer fetch any other address.+ // Public HTTPS; loopback HTTP for the local Super Tab rig.+ SUPER_TAB_ATTACHMENTS_PUBLIC_BASE: (raw: string | undefined) => url((address) => !address.username && !address.password && !address.search+ && (address.protocol === 'https:' || (address.protocol === 'http:' && ['127.0.0.1', 'localhost', '[::1]'].includes(address.hostname))))(raw)+ ?? 'https://cdn.harness.autonomous.ai',// This computer's stable id, minted once and never regenerated (see computerIdFile above). Pin it// explicitly on a box with no durable home — a container or CI job that gets a fresh ~/.harness on// every boot would otherwise look like a NEW computer each time and collect a machine per start.diff --git a/cli/src/core/main.ts b/cli/src/core/main.tsindex e05db9de3..fffe100e2 100644--- a/cli/src/core/main.ts+++ b/cli/src/core/main.ts@@ -244,6 +244,7 @@ import { createRuntimeTransport } from './engines/runtimeTransport.js'import { RuntimeProfileController } from '../lib/runtimeControl.js'import { installTimestampedConsole, sid, prepareLogFile, trimLogFile, LOG_CHECK_INTERVAL_MS } from '../lib/log.js'import { backendHttpBase } from '../lib/controlPlane.js'+import { forwardAttachmentUpload } from '../lib/superTabAttachmentProxy.js'// Daemon stdout/stderr. Capped at LOG_MAX_BYTES — see prepareLogFile/trimLogFile in lib/log.ts.const LOG_FILE = DAEMON_LOG_FILE@@ -2028,6 +2029,8 @@ async function runForeground(session: AuthSession | null): Promise<void> {onAgentSettingsWrite: (body) => agentSettings.settingsWrite(body),onProductFeedback: (body) => proxyBackend('POST', '/api/product-usage/feedback', body),onSignInAnswer: (action, body) => proxyBackend('POST', `/api/auth/qr/${action}`, body),+ onSuperTabAttachment: (req, res, path) => forwardAttachmentUpload(req, res, path,+ { accessToken: () => auth.accessToken(), environment: autonomousEnv, base: backendHttpBase() }),onProductUsageReport: (body) => proxyBackend('POST', '/api/product-usage/report', body),onProductUsageRead: () => proxyBackend('GET', '/api/product-usage/settings'),onProductUsageWrite: (body) => proxyBackend('POST', '/api/product-usage/settings', body),diff --git a/cli/src/hookServer.spec.ts b/cli/src/hookServer.spec.tsindex 4106f1dea..daadb555d 100644--- a/cli/src/hookServer.spec.ts+++ b/cli/src/hookServer.spec.ts@@ -437,6 +437,40 @@ describe('sign-in approval proxy', () => {})})+// The native desktop's chat files: its REST client has no account token, so the daemon streams the upload on with its own.+describe('Super Tab attachment pass-through', () => {+ it('hands a local multipart POST to the pass-through as a stream, guarded like the other writes', async () => {+ const forward = vi.fn(async (req: import('node:http').IncomingMessage, res: import('node:http').ServerResponse, path: string) => {+ let bytes = 0+ for await (const chunk of req) bytes += (chunk as Buffer).byteLength+ res.writeHead(201, { 'Content-Type': 'application/json' })+ res.end(JSON.stringify({ path, bytes }))+ })+ const { base } = await start({ onSuperTabAttachment: forward })+ const headers = { 'x-adapter-local': '1', 'content-type': 'multipart/form-data; boundary=x' }+ const body = Buffer.alloc(300 * 1024, 1)+ for (const h of [{ 'content-type': headers['content-type'] }, { ...headers, origin: 'https://untrusted.example' }]) {+ expect((await fetch(`${base}/api/super-tabs/tab-1/attachments`, { method: 'POST', headers: h, body })).status).toBe(403)+ }+ expect((await fetch(`${base}/api/super-tabs/../attachments`, { method: 'POST', headers, body })).status).toBe(404)+ expect((await fetch(`${base}/api/super-tabs/tab-1/commands`, { method: 'POST', headers, body })).status).toBe(404)+ expect(forward).not.toHaveBeenCalled()+ // Past the 256 KiB the JSON routes read: the body reaches the pass-through whole, as a stream.+ const r = await fetch(`${base}/api/super-tabs/tab-1/attachments?asAgentId=agent-1&other=x`, { method: 'POST', headers, body })+ expect(r.status).toBe(201)+ // An agent's own `post --attach` names it; nothing else in the query goes on.+ expect(await r.json()).toEqual({ path: '/api/super-tabs/tab-1/attachments?asAgentId=agent-1', bytes: body.byteLength })+ const person = await fetch(`${base}/api/super-tabs/tab-1/attachments?asAgentId=../x`, { method: 'POST', headers, body: 'x' })+ expect(await person.json()).toEqual({ path: '/api/super-tabs/tab-1/attachments', bytes: 1 })+ })++ it('is unavailable on a daemon without it', async () => {+ const { base } = await start({})+ expect((await fetch(`${base}/api/super-tabs/tab-1/attachments`, { method: 'POST',+ headers: { 'x-adapter-local': '1', 'content-type': 'multipart/form-data; boundary=x' }, body: 'x' })).status).toBe(503)+ })+})+describe('account Experimental settings proxy', () => {it('proxies only voluntary fixed-choice feedback and guards it from cross-origin requests', async () => {const send = vi.fn(async () => ({ status: 200, body: { success: true, data: { accepted: true } } }))diff --git a/cli/src/hookServer.ts b/cli/src/hookServer.tsindex 8861535fe..c07d99f77 100644--- a/cli/src/hookServer.ts+++ b/cli/src/hookServer.ts@@ -192,6 +192,9 @@ export interface HookServerHandlers {/** The phone half of a sign-in (backend routes/qrSignIn.ts) for the desktop and web apps: approve a device* that says its code aloud (a lamp, #1410) with this computer's own session, as the phone does. */onSignInAnswer?: (action: 'lookup' | 'approve' | 'deny', body: { code: string }) => Promise<PairOutcome>+ /** A Super Tab chat file from the native desktop, streamed on to the backend with this computer's account+ * (lib/superTabAttachmentProxy.ts): the app's REST client holds no token of its own. Answers on `res` itself. */+ onSuperTabAttachment?: (req: http.IncomingMessage, res: http.ServerResponse, path: string) => Promise<void>onProductUsageReport?: (body: unknown) => Promise<PairOutcome>onProductUsageRead?: () => Promise<PairOutcome>onProductUsageWrite?: (body: unknown) => Promise<PairOutcome>@@ -1101,6 +1104,16 @@ export function startHookServer(} catch { json(502, { success: false, error: { code: 'USAGE_UNAVAILABLE', message: 'Product usage unavailable' } }) }return}+ const attachment = req.method === 'POST' ? /^\/api\/super-tabs\/[A-Za-z0-9_-]{1,160}\/attachments$/.exec(url) : null+ if (attachment) {+ if (!localOk) { json(403, { error: 'FORBIDDEN' }); return }+ if (!handlers.onSuperTabAttachment) { json(503, { error: 'UNAVAILABLE' }); return }+ // The body is the file, read by the handler as a stream: never readBody, which holds 256 KiB of text. An agent's+ // `post --attach` names itself; the backend checks that this account runs that agent.+ const asAgentId = new URLSearchParams((req.url ?? '').split('?')[1] ?? '').get('asAgentId')+ const agent = asAgentId && /^[A-Za-z0-9_-]{1,160}$/.test(asAgentId) ? `?asAgentId=${asAgentId}` : ''+ await handlers.onSuperTabAttachment(req, res, `${url}${agent}`); return+ }const signInAnswer = req.method === 'POST' ? /^\/api\/auth\/qr\/(lookup|approve|deny)$/.exec(url) : nullif (signInAnswer) {if (!localOk) { json(403, { error: 'FORBIDDEN' }); return }diff --git a/cli/src/lib/superTabAttachmentProxy.spec.ts b/cli/src/lib/superTabAttachmentProxy.spec.tsnew file mode 100644index 000000000..549ea5d01--- /dev/null+++ b/cli/src/lib/superTabAttachmentProxy.spec.ts@@ -0,0 +1,136 @@+import http from 'node:http'+import type { AddressInfo } from 'node:net'+import { afterEach, describe, expect, it, vi } from 'vitest'+import { forwardAttachmentUpload, type AttachmentProxyDeps } from './superTabAttachmentProxy.js'++const servers: http.Server[] = []+afterEach(async () => { await Promise.all(servers.splice(0).map(s => new Promise(resolve => s.close(resolve)))) })++const BOUNDARY = 'harness-test'+const TYPE = `multipart/form-data; boundary=${BOUNDARY}`++/** A daemon route that hands every request to the pass-through, and the URL to reach it. */+async function daemon(deps: Partial<AttachmentProxyDeps> & Pick<AttachmentProxyDeps, 'fetch'>) {+ const server = http.createServer((req, res) => {+ void forwardAttachmentUpload(req, res, '/api/super-tabs/tab-1/attachments',+ { accessToken: async () => 'token', environment: 'prod', base: 'https://backend.test', ...deps })+ })+ servers.push(server)+ await new Promise<void>(resolve => server.listen(0, '127.0.0.1', resolve))+ return `http://127.0.0.1:${(server.address() as AddressInfo).port}/`+}++/** Sends `parts` one write at a time, waiting on `between` after each but the last. */+function upload(url: string, parts: Buffer[], headers: Record<string, string> = { 'content-type': TYPE }, between?: () => Promise<void>) {+ return new Promise<{ status: number; body: string }>((resolve, reject) => {+ const req = http.request(url, { method: 'POST', headers }, res => {+ let body = ''+ res.setEncoding('utf8').on('data', chunk => { body += chunk }).on('end', () => resolve({ status: res.statusCode!, body }))+ })+ req.on('error', reject)+ void (async () => {+ for (const [index, part] of parts.entries()) {+ req.write(part)+ if (index < parts.length - 1) await between?.()+ }+ req.end()+ })()+ })+}++/** A backend that reads the whole forwarded body and answers `status` with `body`. */+function backend(status = 200, body: unknown = { success: true, data: { attachment: { id: 'f1' } } }) {+ const received: Buffer[] = []+ const seen: Array<{ url: string; init: RequestInit }> = []+ const fetch = vi.fn(async (url: string | URL | Request, init?: RequestInit) => {+ seen.push({ url: String(url), init: init! })+ // As real fetch does: an abort ends the upload with the signal's reason.+ const aborted = new Promise<never>((_, reject) => init!.signal!.addEventListener('abort', () => reject(init!.signal!.reason), { once: true }))+ await Promise.race([aborted, (async () => {+ for await (const chunk of init!.body as unknown as AsyncIterable<Uint8Array>) received.push(Buffer.from(chunk))+ })()])+ return new Response(JSON.stringify(body), { status, headers: { 'content-type': 'application/json; charset=utf-8' } })+ })+ return { fetch: fetch as unknown as typeof globalThis.fetch, calls: fetch, received, seen }+}++describe('Super Tab attachment pass-through', () => {+ it('streams the body on with the account token and hands back the backend answer as it came', async () => {+ let firstArrived: () => void = () => {}+ const arrived = new Promise<void>(resolve => { firstArrived = resolve })+ const received: Buffer[] = []+ let init: RequestInit | undefined+ const fetch = vi.fn(async (_url: string | URL | Request, options?: RequestInit) => {+ init = options+ for await (const chunk of options!.body as unknown as AsyncIterable<Uint8Array>) { received.push(Buffer.from(chunk)); firstArrived() }+ return new Response(JSON.stringify({ success: true, data: { attachment: { id: 'f1' } } }), { status: 200, headers: { 'content-type': 'application/json' } })+ })+ const url = await daemon({ fetch: fetch as unknown as typeof globalThis.fetch })+ const parts = [Buffer.from(`--${BOUNDARY}\r\n`), Buffer.alloc(512 * 1024, 7), Buffer.from(`\r\n--${BOUNDARY}--\r\n`)]+ // The second part is written only after the backend has read the first: the body is not held whole.+ const answer = await upload(url, parts, { 'content-type': TYPE }, () => arrived)+ expect(answer).toEqual({ status: 200, body: JSON.stringify({ success: true, data: { attachment: { id: 'f1' } } }) })+ expect(Buffer.concat(received).equals(Buffer.concat(parts))).toBe(true)+ expect(fetch).toHaveBeenCalledWith('https://backend.test/api/super-tabs/tab-1/attachments', expect.anything())+ expect(init).toMatchObject({ method: 'POST', duplex: 'half',+ headers: { authorization: 'Bearer token', 'x-autonomous-env': 'prod', 'content-type': TYPE } })+ })++ it('passes a refusal through with its status and body', async () => {+ const refused = { success: false, error: { code: 'FORBIDDEN', message: 'Not in this conversation.' } }+ const b = backend(403, refused)+ const answer = await upload(await daemon({ fetch: b.fetch }), [Buffer.from('--x--')])+ expect(answer).toEqual({ status: 403, body: JSON.stringify(refused) })+ })++ it('refuses a body over the cap, declared or streamed, without passing on more than the cap', async () => {+ const declared = backend()+ const url = await daemon({ fetch: declared.fetch, maxBytes: 1024 })+ const big = await upload(url, [Buffer.alloc(2048)], { 'content-type': TYPE, 'content-length': '2048' })+ expect(big.status).toBe(413)+ expect(JSON.parse(big.body).error.code).toBe('ATTACHMENT_TOO_LARGE')+ expect(declared.calls).not.toHaveBeenCalled()++ const streamed = backend()+ const chunked = await upload(await daemon({ fetch: streamed.fetch, maxBytes: 1024 }), [Buffer.alloc(600), Buffer.alloc(600)],+ { 'content-type': TYPE, 'transfer-encoding': 'chunked' })+ expect(chunked.status).toBe(413)+ expect(Buffer.concat(streamed.received).byteLength).toBeLessThanOrEqual(1024)++ const fits = backend()+ expect((await upload(await daemon({ fetch: fits.fetch, maxBytes: 1024 }), [Buffer.alloc(1024)])).status).toBe(200)+ })++ it('keeps a slow upload going while bytes move, and ends one that stalls', async () => {+ const steady = backend()+ const url = await daemon({ fetch: steady.fetch, idleMs: 200 })+ // Four pauses of 120 ms: longer than the idle window in all, never quiet for 200 ms at once.+ let pauses = 0+ const parts = Array.from({ length: 5 }, () => Buffer.alloc(1024, 1))+ const slow = await upload(url, parts, { 'content-type': TYPE }, () => new Promise(resolve => { pauses++; setTimeout(resolve, 120) }))+ expect([slow.status, pauses]).toEqual([200, 4])+ expect(Buffer.concat(steady.received).byteLength).toBe(5 * 1024)++ const stalled = backend()+ const quiet = await upload(await daemon({ fetch: stalled.fetch, idleMs: 100 }), [Buffer.alloc(10), Buffer.alloc(10)],+ { 'content-type': TYPE }, () => new Promise(resolve => setTimeout(resolve, 400)))+ expect([quiet.status, JSON.parse(quiet.body).error.code]).toEqual([504, 'BACKEND_TIMEOUT'])+ })++ it('takes multipart only, and says so when the account or the backend cannot be reached', async () => {+ const b = backend()+ const url = await daemon({ fetch: b.fetch })+ const json = await upload(url, [Buffer.from('{}')], { 'content-type': 'application/json' })+ expect([json.status, JSON.parse(json.body).error.code]).toEqual([400, 'INVALID_ATTACHMENT'])+ expect(b.calls).not.toHaveBeenCalled()++ const signedOut = await upload(await daemon({ fetch: b.fetch, accessToken: async () => { throw new Error('signed out') } }), [Buffer.from('--x--')])+ expect([signedOut.status, JSON.parse(signedOut.body).error.code]).toEqual([401, 'NOT_SIGNED_IN'])++ const down = await upload(await daemon({ fetch: (async () => { throw new TypeError('fetch failed') }) as unknown as typeof fetch }), [Buffer.from('--x--')])+ expect([down.status, JSON.parse(down.body).error.code]).toEqual([502, 'BACKEND_UNREACHABLE'])++ const slow = await upload(await daemon({ fetch: (async () => { throw Object.assign(new Error('timed out'), { name: 'TimeoutError' }) }) as unknown as typeof fetch }), [Buffer.from('--x--')])+ expect([slow.status, JSON.parse(slow.body).error.code]).toEqual([504, 'BACKEND_TIMEOUT'])+ })+})diff --git a/cli/src/lib/superTabAttachmentProxy.ts b/cli/src/lib/superTabAttachmentProxy.tsnew file mode 100644index 000000000..eb74de6ba--- /dev/null+++ b/cli/src/lib/superTabAttachmentProxy.ts@@ -0,0 +1,93 @@+/**+ * A Super Tab chat file from the native desktop, on its way to the backend. The app's REST client talks only to this+ * daemon over localhost and holds no account token (the browser build holds its own), so the daemon passes this one+ * upload on with the account's token: localhost in, HTTPS straight to the backend out, never the relay.+ *+ * The body is streamed, never held whole, and stops one byte past the cap. The backend's answer (its status and its+ * small JSON body) is handed back as it came.+ */+import type { IncomingMessage, ServerResponse } from 'node:http'+import { Readable, Transform } from 'node:stream'++/** The backend takes 10 MB a file; the multipart framing around it is a few hundred bytes. */+export const ATTACHMENT_UPLOAD_MAX_BYTES = 11 * 1024 * 1024+/** No bytes moving for this long ends an upload: a slow uplink keeps going, a stalled one does not hold the request. */+export const ATTACHMENT_IDLE_MS = 30_000+/** The ceiling however steadily it moves: 11 MB at about 100 kbit/s. */+export const ATTACHMENT_TOTAL_MS = 15 * 60_000++class TooLarge extends Error {}++export interface AttachmentProxyDeps {+ /** The account's token, refreshed by the core's session manager as it does for every backend call. */+ accessToken: () => Promise<string>+ environment: string+ base: string+ fetch?: typeof fetch+ maxBytes?: number+ idleMs?: number+ totalMs?: number+}++export async function forwardAttachmentUpload(req: IncomingMessage, res: ServerResponse, path: string, deps: AttachmentProxyDeps): Promise<void> {+ const answer = (status: number, code: string, message: string) => {+ if (res.headersSent) { res.destroy(); return }+ res.writeHead(status, { 'Content-Type': 'application/json' })+ res.end(JSON.stringify({ success: false, error: { code, message } }))+ }+ const max = deps.maxBytes ?? ATTACHMENT_UPLOAD_MAX_BYTES+ const type = req.headers['content-type'] ?? ''+ if (!/^multipart\/form-data;\s*boundary=/i.test(type)) {+ req.resume()+ return answer(400, 'INVALID_ATTACHMENT', 'Send the file as multipart/form-data.')+ }+ // A declared length already over the cap is refused before a byte is read or sent on.+ if (Number(req.headers['content-length'] ?? 0) > max) {+ req.resume()+ return answer(413, 'ATTACHMENT_TOO_LARGE', 'A file can be at most 10 MB.')+ }+ let token: string+ try { token = await deps.accessToken() } catch {+ req.resume()+ return answer(401, 'NOT_SIGNED_IN', 'Sign in on this computer to attach files.')+ }+ const idle = new AbortController()+ const idleMs = deps.idleMs ?? ATTACHMENT_IDLE_MS+ let quiet: NodeJS.Timeout | undefined+ const moved = () => {+ clearTimeout(quiet)+ quiet = setTimeout(() => idle.abort(new DOMException('No bytes moved', 'TimeoutError')), idleMs)+ }+ moved()+ let seen = 0+ const counted = req.pipe(new Transform({ transform(chunk: Buffer, _encoding, done) {+ seen += chunk.byteLength+ moved()+ done(seen > max ? new TooLarge() : null, chunk)+ } }))+ // The last byte sent starts the wait for the answer.+ counted.on('end', moved)+ // A body that stops early (the cap, or the app going away) must also stop the upload.+ counted.on('error', () => req.unpipe(counted))+ let response: Response+ try {+ response = await (deps.fetch ?? fetch)(`${deps.base}${path}`, {+ method: 'POST', body: Readable.toWeb(counted) as ReadableStream, duplex: 'half',+ headers: { authorization: `Bearer ${token}`, 'x-autonomous-env': deps.environment, 'content-type': type },+ signal: AbortSignal.any([idle.signal, AbortSignal.timeout(deps.totalMs ?? ATTACHMENT_TOTAL_MS)]),+ } as RequestInit)+ } catch (error) {+ clearTimeout(quiet)+ req.resume()+ if (seen > max) return answer(413, 'ATTACHMENT_TOO_LARGE', 'A file can be at most 10 MB.')+ const timedOut = error instanceof Error && (error.name === 'TimeoutError' || error.name === 'AbortError')+ return answer(timedOut ? 504 : 502, timedOut ? 'BACKEND_TIMEOUT' : 'BACKEND_UNREACHABLE',+ timedOut ? 'The Harness backend did not finish taking the file. Try again.' : 'Could not reach the Harness backend. Check the connection and try again.')+ }+ let body: Buffer+ try { body = Buffer.from(await response.arrayBuffer()) } catch {+ return answer(504, 'BACKEND_TIMEOUT', 'The Harness backend did not finish answering. Try again.')+ } finally { clearTimeout(quiet) }+ res.writeHead(response.status, { 'Content-Type': response.headers.get('content-type') ?? 'application/json' })+ res.end(body)+}diff --git a/cli/src/superTabs/attach.ts b/cli/src/superTabs/attach.tsnew file mode 100644index 000000000..cdc1c164f--- /dev/null+++ b/cli/src/superTabs/attach.ts@@ -0,0 +1,66 @@+import { createHash } from 'node:crypto'+import { openAsBlob } from 'node:fs'+import { stat } from 'node:fs/promises'+import { basename, extname } from 'node:path'+import { localCredentialHeaders } from '../lib/localCredential.js'+import { ATTACHMENT_TOTAL_MS } from '../lib/superTabAttachmentProxy.js'+import { object } from './wire.js'+import { formatSize, MAX_ATTACHMENT_BYTES } from './attachments.js'++const TYPES: Record<string, string> = {+ '.png': 'image/png', '.jpg': 'image/jpeg', '.jpeg': 'image/jpeg', '.gif': 'image/gif', '.webp': 'image/webp', '.svg': 'image/svg+xml',+ '.pdf': 'application/pdf', '.json': 'application/json', '.zip': 'application/zip', '.gz': 'application/gzip',+ '.txt': 'text/plain', '.log': 'text/plain', '.md': 'text/markdown', '.csv': 'text/csv', '.html': 'text/html',+ '.mp4': 'video/mp4', '.mov': 'video/quicktime', '.webm': 'video/webm',+}+export const mimeOf = (path: string) => TYPES[extname(path).toLowerCase()] ?? 'application/octet-stream'+/** A little past the daemon's own ceiling, so the daemon's answer, not this one, says why a slow upload ended. */+const UPLOAD_MS = ATTACHMENT_TOTAL_MS + 30_000++/** The id the backend gives the message `message.send` writes for this agent and operation (backend `stableId`). */+export const messageIdOf = (tabId: string, agentId: string, operationId: string) =>+ createHash('sha256').update(JSON.stringify([tabId, `agent:${agentId}`, operationId])).digest('hex').slice(0, 24)++type Request = (payload: Record<string, unknown>) => Promise<Record<string, unknown>>+const value = (answer: Record<string, unknown>) => {+ if (answer.error) throw Object.assign(new Error(String(answer.detail ?? answer.error)), { code: answer.error, status: answer.status })+ return object(answer.value)+}++/** One file of `post --attach`, multipart to this computer's daemon, which streams it on to the backend with the account's+ * token (lib/superTabAttachmentProxy.ts). Its own deadline, not a service answer's half minute: on a slow uplink 10 MB+ * takes longer, and the daemon ends it once no bytes move. */+async function uploadOne(path: string, target: UploadTarget, agentId: string, fetcher: typeof fetch): Promise<string> {+ const info = await stat(path)+ if (!info.isFile()) throw new Error(`${path} is not a file.`)+ if (info.size > MAX_ATTACHMENT_BYTES) throw new Error(`${basename(path)} is over the ${formatSize(MAX_ATTACHMENT_BYTES)} limit (${info.size} bytes).`)+ const form = new FormData()+ form.append('conversationId', target.conversationId)+ // Read from disk as it is sent, never whole.+ form.append('file', await openAsBlob(path, { type: mimeOf(path) }), basename(path))+ const response = await fetcher(`http://127.0.0.1:${target.port}/api/super-tabs/${target.tabId}/attachments?asAgentId=${agentId}`, {+ method: 'POST', body: form, signal: AbortSignal.timeout(UPLOAD_MS),+ // The local API's write gate, and its credential over TCP.+ headers: { 'x-adapter-local': '1', ...localCredentialHeaders(target.dataDir) },+ })+ const body = object(await response.json().catch(() => ({})))+ const attachment = object(object(body.data).attachment)+ if (!response.ok || typeof attachment.id !== 'string') {+ throw new Error(String(object(body.error).message ?? body.message ?? `Could not upload ${basename(path)} (HTTP ${response.status}).`))+ }+ return attachment.id+}++export interface UploadTarget { tabId: string; conversationId: string; port: number; dataDir: string }++/** Uploads each file of `post --attach` and answers the ids `message.send` names. Repeating a post whose message already+ * went out uploads nothing and names that message's files, so the send returns its receipt. */+export async function uploadAttachments(paths: string[], operationId: string, target: UploadTarget, request: Request,+ fetcher: typeof fetch = fetch): Promise<string[]> {+ const earlier = value(await request({ action: 'attachment', step: 'sent', conversationId: target.conversationId, operationId }))+ if (Array.isArray(earlier.attachmentIds)) return earlier.attachmentIds.map(String)+ if (typeof earlier.agentId !== 'string') throw new Error('Update Harness on this computer to attach files.')+ const ids: string[] = []+ for (const path of paths) ids.push(await uploadOne(path, target, earlier.agentId, fetcher))+ return ids+}diff --git a/cli/src/superTabs/attachments.spec.ts b/cli/src/superTabs/attachments.spec.tsindex f1794bf4d..85f493d30 100644--- a/cli/src/superTabs/attachments.spec.ts+++ b/cli/src/superTabs/attachments.spec.ts@@ -1,19 +1,70 @@import { readFileSync } from 'node:fs'-import { expect, it } from 'vitest'-import { attachmentsOf, saveAttachment } from './attachments.js'+import { basename } from 'node:path'+import { describe, expect, it, vi } from 'vitest'+import { attachedFiles, attachmentsOf, diskName, formatSize, servedFrom } from './attachments.js'-const image = { id: 'img1', name: 'a.png', mime: 'image/png', size: 3, parts: 1 }-it('keeps only well-formed image rows within the backend limits', () => {- expect(attachmentsOf({ attachments: [image, { ...image, id: '../x' }, { ...image, mime: 'image/gif' }, { ...image, mime: 'toString' },- { ...image, size: 5 * 1024 * 1024 + 1 }, { ...image, parts: 0 }, { ...image, parts: 65 }, 'junk'] })).toEqual([image])- expect(attachmentsOf({ text: 'no images' })).toEqual([])- expect(attachmentsOf(null)).toEqual([])-})-it('refuses an image whose parts do not add up to its size', async () => {- const read = async () => ({ data: Buffer.from([1, 2]).toString('base64') })- await expect(saveAttachment(read, 'tab', 'agent', image)).rejects.toThrow('incomplete')- await expect(saveAttachment(async () => ({}), 'tab', 'agent', image)).rejects.toThrow('unreadable')- const path = await saveAttachment(async () => ({ data: Buffer.from([1, 2, 3]).toString('base64') }), 'tab', 'agent', { ...image, name: 'no extension' })- expect(path).toMatch(/-no-extension\.png$/)- expect([...readFileSync(path)]).toEqual([1, 2, 3])+const base = 'https://cdn.example.test'+const file = (over: Record<string, unknown> = {}) => ({ id: 'a1', name: 'screen.png', mime: 'image/png', size: 5, url: `${base}/super-tabs/tab/abc/screen.png`, ...over })+const replying = (bytes: Uint8Array, status = 200) => vi.fn(async () => new Response(bytes, { status }))++describe('Super Tab attachment downloads', () => {+ it('downloads each file into paste-drops and lists its path for the prompt', async () => {+ const fetcher = replying(new Uint8Array([1, 2, 3, 4, 5]))+ const listed = await attachedFiles({ attachments: [file()] }, { base, fetch: fetcher })+ expect(listed.complete).toBe(true)+ const [, path] = listed.text.match(/^Attached files:\n- (\/\S+-screen\.png) \(sent as "screen\.png", 5 B\)$/) ?? []+ expect([...readFileSync(path!)]).toEqual([1, 2, 3, 4, 5])+ expect(fetcher).toHaveBeenCalledWith(file().url, expect.objectContaining({ redirect: 'error' }))+ })+ it('keeps shell syntax out of the path and the original name in the label', async () => {+ const name = '$(curl x|sh) "a b";.png'+ const listed = await attachedFiles({ attachments: [file({ name })] }, { base, fetch: replying(new Uint8Array(5)) })+ const [, path] = listed.text.match(/^Attached files:\n- (\S+) \(sent as (.+), 5 B\)$/) ?? []+ expect(basename(path!)).toMatch(/^[0-9a-f]{8}-_curl_x_sh_a_b_\.png$/)+ expect(listed.text).toContain(`(sent as ${JSON.stringify(name)}, 5 B)`)+ expect([diskName('..'), diskName('-rf.txt'), diskName('ảnh.png')]).toEqual(['file', 'rf.txt', '_nh.png'])+ })+ it('tries a failing file again, up to three times, and says when it never arrived', async () => {+ const flaky = vi.fn().mockResolvedValueOnce(new Response(null, { status: 503 })).mockResolvedValueOnce(new Response(new Uint8Array(5)))+ expect(await attachedFiles({ attachments: [file()] }, { base, fetch: flaky })).toMatchObject({ complete: true })+ expect(flaky).toHaveBeenCalledTimes(2)+ const down = replying(new Uint8Array(0), 503)+ expect(await attachedFiles({ attachments: [file()] }, { base, fetch: down }))+ .toEqual({ text: `Attached files:\n- Could not download ${file().url} (sent as "screen.png", 5 B): HTTP 503`, complete: false })+ expect(down).toHaveBeenCalledTimes(3)+ const short = replying(new Uint8Array(2))+ expect((await attachedFiles({ attachments: [file()] }, { base, fetch: short })).text).toContain('incomplete download')+ })+ it('stops trying when the message’s time budget is spent', async () => {+ let clock = 0+ const slow = vi.fn(async () => { clock += 30_000; return new Response(null, { status: 503 }) })+ expect(await attachedFiles({ attachments: [file()] }, { base, fetch: slow, now: () => clock, budgetMs: 45_000 })).toMatchObject({ complete: false })+ expect(slow).toHaveBeenCalledTimes(2)+ expect(await attachedFiles({ attachments: [file()] }, { base, fetch: slow, now: () => clock, budgetMs: 0 }))+ .toEqual({ text: `Attached files:\n- Could not download ${file().url} (sent as "screen.png", 5 B): out of time`, complete: false })+ })+ it('fetches only from the public base, and never retries a refusal', async () => {+ const fetcher = replying(new Uint8Array(5))+ const listed = await attachedFiles({ attachments: [file({ url: 'https://evil.example.test/x.png' }), file({ url: 'https://cdn.example.test.evil/x' }),+ file({ url: `${base}/y.png`, size: 3 })] }, { base: `${base}/`, fetch: fetcher })+ expect(listed.text).toContain('- Could not download a file (sent as "screen.png", 5 B): not a Harness file address')+ expect(listed.text).not.toContain('evil')+ expect(listed.text).toContain(`- Could not download ${base}/y.png (sent as "screen.png", 3 B): larger than declared`)+ expect(fetcher).toHaveBeenCalledTimes(1)+ const missing = replying(new Uint8Array(0), 404)+ expect((await attachedFiles({ attachments: [file()] }, { base, fetch: missing })).text).toContain('HTTP 404')+ expect(missing).toHaveBeenCalledTimes(1)+ })+ it('never reads past the 10 MB limit, whatever the message declares', async () => {+ const big = new Uint8Array(10 * 1024 * 1024 + 1)+ expect((await attachedFiles({ attachments: [file({ size: big.byteLength })] }, { base, fetch: replying(big) })).text).toContain('larger than declared')+ })+ it('reads only well-formed attachment rows and formats sizes', async () => {+ expect(attachmentsOf({})).toEqual([])+ expect(attachmentsOf({ attachments: [file(), { name: 'x' }, file({ size: -1 }), 'junk'] })).toEqual([file()])+ expect(await attachedFiles({ text: 'no files' })).toEqual({ text: '', complete: true })+ expect([formatSize(12), formatSize(2048), formatSize(3 * 1024 * 1024)]).toEqual(['12 B', '2.0 KB', '3.0 MB'])+ expect([servedFrom(base, `${base}/a`), servedFrom(`${base}/files`, `${base}/filesx/a`), servedFrom(base, 'not a url'),+ servedFrom(base, `https://user:[email protected]/a`)]).toEqual([true, false, false, false])+ })})diff --git a/cli/src/superTabs/attachments.ts b/cli/src/superTabs/attachments.tsindex 54f54c7b3..c8617fe56 100644--- a/cli/src/superTabs/attachments.ts+++ b/cli/src/superTabs/attachments.ts@@ -1,51 +1,83 @@+import { env } from '../config/env.js'import { writePasteDropFile } from '../lib/pasteDropFiles.js'-import { identifier, object } from './wire.js'--/** What a message read carries about one attached image (backend superTabs/attachments.ts); never its bytes. */-export interface SuperTabAttachment { id: string; name: string; mime: string; size: number; parts: number }--const EXTENSIONS: Record<string, string> = { 'image/png': 'png', 'image/jpeg': 'jpg', 'image/webp': 'webp' }-/** The backend's own limits: 5 MB an image, in 256 KiB parts. A row claiming more is refused before anything is read. */-const MAX_BYTES = 5 * 1024 * 1024-const MAX_PARTS = 64-const PARALLEL_PARTS = 4--/** The attachments of a message row; anything malformed is left out. */-export function attachmentsOf(message: unknown): SuperTabAttachment[] {- const rows = object(message).attachments- if (!Array.isArray(rows)) return []- return rows.map(object).filter(a => identifier(a.id) && typeof a.name === 'string' && typeof a.mime === 'string' && Object.hasOwn(EXTENSIONS, a.mime)- && Number.isInteger(a.size) && (a.size as number) > 0 && (a.size as number) <= MAX_BYTES- && Number.isInteger(a.parts) && (a.parts as number) > 0 && (a.parts as number) <= MAX_PARTS)- .map(a => ({ id: a.id as string, name: a.name as string, mime: a.mime as string, size: a.size as number, parts: a.parts as number }))+import { object } from './wire.js'++/** As the backend stores it on a message (backend/src/superTabs/attachments.ts). */+export interface MessageAttachment { id: string; name: string; mime: string; size: number; url: string }++/** The backend's per-file limit. A download never reads past it, whatever a message declares. */+export const MAX_ATTACHMENT_BYTES = 10 * 1024 * 1024+const DOWNLOAD_MS = 30_000+const BUDGET_MS = 45_000++export function attachmentsOf(message: Record<string, unknown>): MessageAttachment[] {+ if (!Array.isArray(message.attachments)) return []+ return message.attachments.slice(0, 10).map(object).filter((a): a is Record<string, unknown> & MessageAttachment =>+ typeof a.name === 'string' && typeof a.url === 'string' && typeof a.mime === 'string'+ && Number.isSafeInteger(a.size) && (a.size as number) >= 0)}-/** The sender's name, with the extension its bytes really have: an agent opens the file by that. Spaces and other- * characters a shell or a prompt line would split on become dashes. */-function fileName(attachment: SuperTabAttachment): string {- const dot = attachment.name.lastIndexOf('.')- const stem = (dot > 0 ? attachment.name.slice(0, dot) : attachment.name).replace(/[^\p{L}\p{N}._-]+/gu, '-').slice(0, 100) || 'image'- return `${stem}.${EXTENSIONS[attachment.mime]}`+export const formatSize = (bytes: number) => bytes < 1024 ? `${bytes} B`+ : bytes < 1024 * 1024 ? `${(bytes / 1024).toFixed(1)} KB` : `${(bytes / 1024 / 1024).toFixed(1)} MB`++/** Only files under the configured public base: a message's URL must not make this computer fetch another address. */+export function servedFrom(base: string, address: string): boolean {+ try {+ const root = new URL(base), target = new URL(address)+ const prefix = root.pathname.endsWith('/') ? root.pathname : `${root.pathname}/`+ return target.origin === root.origin && target.pathname.startsWith(prefix) && !target.username && !target.password+ } catch { return false }}-/**- * Reads an image part by part, as the agent this machine runs, and saves it where pasted and dropped files go- * (lib/pasteDropFiles.ts, pruned after a day). Returns the file's absolute path for the agent to open.- */-export async function saveAttachment(read: (path: string) => Promise<unknown>, tabId: string, agentId: string,- attachment: SuperTabAttachment): Promise<string> {- // Four parts at a time: a 5 MB image is 20 small requests, and one at a time made a delivery wait seconds.- const parts: Buffer[] = new Array(attachment.parts)- let next = 0- const worker = async () => {- for (let index = next++; index < attachment.parts; index = next++) {- const part = object(await read(`/api/super-tabs/${tabId}/attachments/${attachment.id}/parts/${index}?asAgentId=${agentId}`))- if (typeof part.data !== 'string') throw new Error('The image is unreadable.')- parts[index] = Buffer.from(part.data, 'base64')- }+/** A failure that another try cannot fix. */+class Refused extends Error {}++/** The name on disk: the prompt lists this path for an agent that may paste it into a shell, so it carries nothing a+ * shell reads as syntax ($(...), quotes, spaces, ;). The original name stays in the label beside it. */+export const diskName = (name: string) => name.replaceAll(/[^A-Za-z0-9._-]+/g, '_').replace(/^[.-]+/, '').slice(-120) || 'file'++async function download(file: MessageAttachment, base: string, fetcher: typeof fetch, ms: number): Promise<string> {+ if (!servedFrom(base, file.url)) throw new Refused('not a Harness file address')+ const limit = Math.min(file.size, MAX_ATTACHMENT_BYTES)+ // A redirect could leave the public base, so it is a failure, not followed.+ const response = await fetcher(file.url, { redirect: 'error', signal: AbortSignal.timeout(ms) })+ if (!response.ok || !response.body) {+ const Failure = response.status >= 400 && response.status < 500 && ![408, 429].includes(response.status) ? Refused : Error+ throw new Failure(`HTTP ${response.status}`)+ }+ const chunks: Uint8Array[] = []+ let total = 0+ for await (const chunk of response.body) {+ total += chunk.byteLength+ if (total > limit) { await response.body.cancel().catch(() => {}); throw new Refused('larger than declared') }+ chunks.push(chunk)}- await Promise.all(Array.from({ length: Math.min(PARALLEL_PARTS, attachment.parts) }, worker))- const bytes = Buffer.concat(parts)- if (bytes.length !== attachment.size) throw new Error('The image arrived incomplete.')- return writePasteDropFile(fileName(attachment), bytes)+ if (total !== file.size) throw new Error('incomplete download')+ return writePasteDropFile(diskName(file.name), Buffer.concat(chunks))+}++/** The prompt's list of a message's files, downloaded into this computer's paste-drops folder (kept 24 h), so an+ * agent on any machine can read them. Each file gets up to three tries within one time budget for the message, since+ * the host's single poll loop waits on it. A file that could not be downloaded is named by its URL instead, and+ * `complete` is false, so the host tries again before it next delivers the same message. */+export async function attachedFiles(message: Record<string, unknown>, options: { base?: string; fetch?: typeof fetch; budgetMs?: number; now?: () => number } = {}):+ Promise<{ text: string; complete: boolean }> {+ const files = attachmentsOf(message)+ if (!files.length) return { text: '', complete: true }+ const base = options.base ?? env.SUPER_TAB_ATTACHMENTS_PUBLIC_BASE+ const now = options.now ?? Date.now, deadline = now() + (options.budgetMs ?? BUDGET_MS)+ const lines = await Promise.all(files.map(async file => {+ // The sender's name, quoted so it reads as a name and is never taken for the path, which is the shell-safe one.+ const label = `sent as ${JSON.stringify(file.name)}, ${formatSize(file.size)}`+ let failure: unknown+ for (let attempt = 0; attempt < 3 && deadline - now() > 0; attempt++) {+ try { return { line: `- ${await download(file, base, options.fetch ?? fetch, Math.min(DOWNLOAD_MS, deadline - now()))} (${label})`, ok: true } } catch (error) {+ failure = error+ if (error instanceof Refused) break+ }+ }+ const why = failure instanceof Error ? failure.message : 'out of time'+ return { line: servedFrom(base, file.url) ? `- Could not download ${file.url} (${label}): ${why}` : `- Could not download a file (${label}): ${why}`, ok: false }+ }))+ return { text: `Attached files:\n${lines.map(l => l.line).join('\n')}`, complete: lines.every(l => l.ok) }}diff --git a/cli/src/superTabs/command.spec.ts b/cli/src/superTabs/command.spec.tsindex c350d39f7..722e1c8f0 100644--- a/cli/src/superTabs/command.spec.ts+++ b/cli/src/superTabs/command.spec.ts@@ -1,4 +1,5 @@import { expect, it, vi } from 'vitest'+import { resolve } from 'node:path'import { parseSuperTabArgs, superTabCommand } from './command.js'const where = { port: 14001, dataDir: '/fixture', machineId: 'machine' }const prefix = ['--tab', 'tab', '--agent', 'agent']@@ -7,8 +8,6 @@ it('keeps an explicit stable receipt for agent messages and arbitrary work commaexpect(parseSuperTabArgs([...prefix, 'command', 'op-2', '{"type":"work.assign"}'], where).payload).toMatchObject({ command: { type: 'work.assign' } })expect(parseSuperTabArgs(['--port', '14002', '--machine', 'target', ...prefix, 'messages', 'lead'], where)).toMatchObject({ where: { port: 14002, machineId: 'target' }, payload: { conversationId: 'lead' } })expect(parseSuperTabArgs(['help'], where).payload.action).toBe('help')- expect(parseSuperTabArgs([...prefix, 'attachment', 'img1'], where).payload).toMatchObject({ action: 'attachment', attachmentId: 'img1' })- expect(() => parseSuperTabArgs([...prefix, 'attachment', '../img'], where)).toThrow('attachment ATTACHMENT_ID')expect(parseSuperTabArgs([...prefix, 'message', 'lead', 'old-question'], where).payload).toMatchObject({ action: 'message', conversationId: 'lead', messageId: 'old-question' })expect(parseSuperTabArgs([...prefix, 'post', 'lead', '--tab', 'literal'], where).payload.command).toMatchObject({ text: '--tab' })@@ -68,3 +67,66 @@ it('posts a reply to one message with --reply-to, and rejects a bad id', () => {expect(() => parseSuperTabArgs([...prefix, 'post', 'lead', 'Ready', 'op-1', ...tail], where)).toThrow('harness super-tab')}})+it('parses repeated --attach, allows empty text with a file, and refuses empty text alone', () => {+ expect(parseSuperTabArgs([...prefix, 'post', 'lead', '', 'op-1', '--attach', 'a.png', '--reply-to', 'm1', '--attach', 'b.log'], where).payload)+ .toMatchObject({ attach: [resolve('a.png'), resolve('b.log')], command: { text: '', replyTo: 'm1' } })+ expect(parseSuperTabArgs([...prefix, 'post', 'lead', 'Ready', 'op-1'], where).payload).not.toHaveProperty('attach')+ for (const tail of [[], ['--attach'], ['--attach', '']]) {+ expect(() => parseSuperTabArgs([...prefix, 'post', 'lead', ' ', 'op-1', ...tail], where)).toThrow('harness super-tab')+ }+})+it('uploads each --attach file to the daemon\'s local upload route as the agent, then sends the message with their ids', async () => {+ const { mkdtempSync, writeFileSync, rmSync } = await import('node:fs')+ const { join } = await import('node:path')+ const { tmpdir } = await import('node:os')+ const dir = mkdtempSync(join(tmpdir(), 'super-tab-attach-'))+ try {+ writeFileSync(join(dir, 'shot.png'), Buffer.from([1, 2, 3]))+ writeFileSync(join(dir, 'big.bin'), Buffer.alloc(10 * 1024 * 1024 + 1))+ const calls: Array<Record<string, unknown>> = []+ const request = vi.fn(async (_type: string, payload: Record<string, unknown> = {}): Promise<Record<string, unknown>> => {+ calls.push(payload)+ if (payload.step === 'sent') return { ok: true, value: { agentId: 'agent-1', attachmentIds: null } }+ return { ok: true, value: { revision: 9, result: { messageId: 'm' } } }+ })+ let uploads = 0+ const fetch = vi.fn(async (_url: string, init?: RequestInit) => {+ const file = (init!.body as FormData).get('file') as File+ return file.name === 'denied.png'+ ? new Response(JSON.stringify({ success: false, error: { code: 'FORBIDDEN', message: 'Not in this conversation.' } }), { status: 403 })+ : new Response(JSON.stringify({ success: true, data: { attachment: { id: `f${++uploads}` } } }), { status: 200 })+ })+ const deps = { where: () => where, open: async () => ({ request, close: vi.fn(), machineId: 'machine' }), print: vi.fn(),+ fetch: fetch as unknown as typeof globalThis.fetch }+ expect(await superTabCommand([...prefix, 'post', 'lead', '', 'op', '--attach', join(dir, 'shot.png'), '--attach', join(dir, 'shot.png')], deps)).toBe(0)+ expect(calls.map(c => c.step ?? c.action)).toEqual(['sent', 'command'])+ const [url, init] = fetch.mock.calls[0]!+ expect(url).toBe('http://127.0.0.1:14001/api/super-tabs/tab/attachments?asAgentId=agent-1')+ expect(init!.headers).toMatchObject({ 'x-adapter-local': '1' })+ const form = init!.body as FormData+ expect([...form.keys()]).toEqual(['conversationId', 'file'])+ expect(form.get('file')).toMatchObject({ name: 'shot.png', type: 'image/png', size: 3 })+ // Its own deadline, well past a service answer's half minute.+ expect(init!.signal).toBeInstanceOf(AbortSignal)+ expect(calls.at(-1)).toMatchObject({ operationId: 'op', command: { type: 'message.send', text: '', attachmentIds: ['f1', 'f2'] } })+ expect(calls.at(-1)).not.toHaveProperty('attach')+ expect(request.mock.calls.every(c => (c as unknown[])[2] === 30_000)).toBe(true)++ // Already sent: nothing is uploaded and the send returns its receipt.+ calls.length = 0+ request.mockImplementationOnce(async () => ({ ok: true, value: { agentId: 'agent-1', attachmentIds: ['f0'] } }))+ expect(await superTabCommand([...prefix, 'post', 'lead', '', 'op', '--attach', join(dir, 'shot.png')], deps)).toBe(0)+ expect(calls.map(c => c.step ?? c.action)).toEqual(['command'])+ expect(calls[0]).toMatchObject({ command: { attachmentIds: ['f0'] } })+ expect(fetch).toHaveBeenCalledTimes(2)++ // A refused or oversized file stops the post: nothing is sent.+ calls.length = 0+ writeFileSync(join(dir, 'denied.png'), Buffer.from([1]))+ expect(await superTabCommand([...prefix, 'post', 'lead', 'x', 'op2', '--attach', join(dir, 'denied.png')], deps)).toBe(1)+ expect(JSON.parse(deps.print.mock.calls.at(-1)![0]).error).toBe('Not in this conversation.')+ expect(await superTabCommand([...prefix, 'post', 'lead', 'x', 'op3', '--attach', join(dir, 'big.bin')], deps)).toBe(1)+ expect(JSON.parse(deps.print.mock.calls.at(-1)![0]).error).toContain('over the 10.0 MB limit')+ expect(calls.map(c => c.step ?? c.action)).toEqual(['sent', 'sent'])+ } finally { rmSync(dir, { recursive: true, force: true }) }+})diff --git a/cli/src/superTabs/command.ts b/cli/src/superTabs/command.tsindex 265b6fa25..79722c6f6 100644--- a/cli/src/superTabs/command.ts+++ b/cli/src/superTabs/command.ts@@ -4,8 +4,10 @@ import { routeTask } from './routeCommand.js'import { openDaemon, whereFor, type Daemon, type Where } from '../agentClient/daemon.js'import { callerOf, type Frame } from '../agentClient/model.js'import { identifier } from './host.js'+import { resolve } from 'node:path'+import { uploadAttachments } from './attach.js'-const USAGE = 'harness super-tab --tab ID [--agent ID] [--port N --machine ID] status | messages GROUP | message GROUP MESSAGE_ID | attachment ATTACHMENT_ID | post GROUP TEXT OPERATION_ID [--reply-to MESSAGE_ID] | command OPERATION_ID JSON | start OPERATION_ID JSON | resume START_ID | capacity MACHINE_ID JSON | route GROUP JSON | help'+const USAGE = 'harness super-tab --tab ID [--agent ID] [--port N --machine ID] status | messages GROUP | message GROUP MESSAGE_ID | post GROUP TEXT OPERATION_ID [--reply-to MESSAGE_ID] [--attach PATH]... | command OPERATION_ID JSON | start OPERATION_ID JSON | resume START_ID | capacity MACHINE_ID JSON | route GROUP JSON | help'export function parseSuperTabArgs(argv: readonly string[], where: Where) {const positional: string[] = []let tabId = '', agentId = ''@@ -26,11 +28,19 @@ export function parseSuperTabArgs(argv: readonly string[], where: Where) {else if (action === 'message' && identifier(first) && identifier(second) && positional.length === 3) {Object.assign(payload, { conversationId: first, messageId: second })}- else if (action === 'attachment' && identifier(first) && positional.length === 2) payload.attachmentId = first- else if (action === 'post' && identifier(first) && second?.trim() && identifier(third)- && (positional.length === 4 || (positional.length === 6 && positional[4] === '--reply-to' && identifier(positional[5])))) {- Object.assign(payload, { action: 'command', operationId: third,- command: { type: 'message.send', conversationId: first, text: second, replyTo: positional[5] ?? null, recipientIds: [] } })+ else if (action === 'post' && identifier(first) && typeof second === 'string' && identifier(third)) {+ let replyTo: string | null = null+ const attach: string[] = []+ for (let i = 4; i < positional.length; i += 2) {+ const [flag, value] = [positional[i], positional[i + 1]]+ if (flag === '--reply-to' && identifier(value) && replyTo === null) replyTo = value+ else if (flag === '--attach' && value && attach.length < 10) attach.push(resolve(value))+ else throw new Error(USAGE)+ }+ // A screenshot or a log may go without words.+ if (!second.trim() && !attach.length) throw new Error(USAGE)+ Object.assign(payload, { action: 'command', operationId: third, ...(attach.length ? { attach } : {}),+ command: { type: 'message.send', conversationId: first, text: second, replyTo, recipientIds: [] } })} else if (action === 'command' && identifier(first) && second && positional.length === 3) {Object.assign(payload, { operationId: first, command: JSON.parse(second) })} else if (action === 'start' && identifier(first) && second && positional.length === 3) {@@ -45,7 +55,7 @@ export function parseSuperTabArgs(argv: readonly string[], where: Where) {}export async function superTabCommand(argv: readonly string[], deps: {- where?: () => Where; open?: typeof openDaemon; print?: (text: string) => void; pane?: string+ where?: () => Where; open?: typeof openDaemon; print?: (text: string) => void; pane?: string; fetch?: typeof fetch} = {}): Promise<number> {let daemon: Daemon | null = nulllet operationId: unknown@@ -81,7 +91,17 @@ export async function superTabCommand(argv: readonly string[], deps: {} else if (request.payload.action === 'route') {result = await routeTask({ tabId: String(request.payload.tabId), conversationId: String(request.payload.conversationId),assessment: request.payload.assessment }, scoped, request.where, deps.open)- } else result = await daemon.request('super_tabs', request.payload, 30_000)+ } else {+ const { attach, ...payload } = request.payload+ // Each file goes to the daemon's local upload route, which streams it to the backend with the account's token;+ // this process holds no account credential.+ if (Array.isArray(attach)) {+ const command = object(payload.command)+ command.attachmentIds = await uploadAttachments(attach as string[], String(payload.operationId), { tabId: String(payload.tabId),+ conversationId: String(command.conversationId), port: request.where.port, dataDir: request.where.dataDir }, scoped, deps.fetch)+ }+ result = await daemon.request('super_tabs', payload, 30_000)+ }print(JSON.stringify({ ...result, ...(operationId ? { operationId } : {}) }))return result.error ? 1 : 0} catch (error) {diff --git a/cli/src/superTabs/host.spec.ts b/cli/src/superTabs/host.spec.tsindex 5bb5c191e..74c864ae5 100644--- a/cli/src/superTabs/host.spec.ts+++ b/cli/src/superTabs/host.spec.ts@@ -178,45 +178,6 @@ describe('Super Tab native delivery handoff', () => {await host.reconcileReceipts()expect(Object.keys(t.saved().entries)).toEqual(['delivery'])})- it('saves the attached images on this machine and names their paths in the prompt', async () => {- const png = Buffer.concat([Buffer.from([0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a]), Buffer.alloc(20, 1)])- const t = setup({ text: '', attachments: [{ id: 'img1', name: 'screen shot', mime: 'image/png', size: png.length, parts: 2 },- { id: 'img2', name: 'gone.jpg', mime: 'image/jpeg', size: 10, parts: 1 }] })- const original = vi.mocked(t.call).getMockImplementation()!- let release!: () => void- const gate = new Promise<void>(resolve => { release = resolve })- vi.mocked(t.call).mockImplementation(async (method, path, body) => {- const part = /\/attachments\/(img\d)\/parts\/(\d)\?asAgentId=agent$/.exec(path)- if (!part) return original(method, path, body)- await gate- if (part[1] === 'img2') return { status: 404, body: { success: false, error: { code: 'NOT_FOUND', message: 'This image is unavailable.' } } }- const half = part[2] === '0' ? png.subarray(0, 10) : png.subarray(10)- return { status: 200, body: { success: true, data: { data: half.toString('base64') } } }- })- const host = t.open()- // The poll returns while the images are still being read: other deliveries' leases keep being renewed.- await host.tick()- await host.tick()- expect(t.core.turns.deliver).not.toHaveBeenCalled()- expect(t.core.turns.leaseDeliveries).toHaveBeenCalled()- release()- await vi.waitFor(() => expect(t.core.turns.deliver).toHaveBeenCalled())- await host.tick(); await host.tick()- expect(t.core.turns.deliver).toHaveBeenCalledTimes(1)- const prompt = vi.mocked(t.core.turns.deliver).mock.calls[0]![1] as string- const saved = /^Attached image: (.+)$/m.exec(prompt)![1]!- expect(saved).toMatch(/[/\\]paste-drops[/\\][0-9a-f]{8}-screen-shot\.png$/)- expect(readFileSync(saved).equals(png)).toBe(true)- expect(prompt).toContain("Attached image gone.jpg could not be fetched. Try again: ")- expect(prompt).toContain("attachment 'img2'")- expect(prompt).toContain('Open each attached image with your file-reading tool to see it.')- expect(t.log).toHaveBeenCalledWith(expect.stringContaining('attachment img2 for delivery delivery'))- })- it('adds nothing about images to a message without them', async () => {- const t = setup()- await t.open().tick()- expect(vi.mocked(t.core.turns.deliver).mock.calls[0]![1]).not.toContain('Attached image')- })it('tells the agent how to reply to this exact message, in short plain words', async () => {const t = setup({ author: { kind: 'person', id: 'p1', name: '[email protected]' }, text: 'How is it going?' })await t.open().tick()@@ -418,3 +379,42 @@ it('confirms a stopped assignment only with fresh native evidence, including aftawait host.reconcileStops()expect(proof).toHaveLength(1)})++describe('Super Tab attachments in delivered input', () => {+ it('lists the downloaded files after the text and downloads them once while the terminal holds the input', async () => {+ const file = { id: 'a1', name: 'screen.png', mime: 'image/png', size: 5, url: 'https://cdn.example.test/x/screen.png' }+ const t = setup({ text: 'See the screenshot.', attachments: [file] })+ const attachedFiles = vi.fn(async () => ({ text: 'Attached files:\n- /drops/1-screen.png (screen.png, 5 B)', complete: true }))+ const host = new SuperTabHost(t.core, 'machine-1', { log: vi.fn(), attachedFiles }); hosts.push(host)+ await host.tick()+ expect(attachedFiles).toHaveBeenCalledWith(expect.objectContaining({ attachments: [file] }))+ expect(vi.mocked(t.core.turns.deliver).mock.calls[0]?.[1])+ .toMatch(/:\nSee the screenshot\.\n\nAttached files:\n- \/drops\/1-screen\.png \(screen\.png, 5 B\)$/)+ t.event('rejected', 'team_waiting_busy')+ await host.tick()+ expect(t.core.turns.deliver).toHaveBeenCalledTimes(2)+ expect(vi.mocked(t.core.turns.deliver).mock.calls[1]?.[1]).toContain('/drops/1-screen.png')+ expect(attachedFiles).toHaveBeenCalledTimes(1)+ })+ it('downloads a failed file again before the next delivery of the held input', async () => {+ const t = setup({ text: 'Logs.', attachments: [{ id: 'a1', name: 'a.log', mime: 'text/plain', size: 1, url: 'https://cdn.example.test/a.log' }] })+ const attachedFiles = vi.fn()+ .mockResolvedValueOnce({ text: 'Attached files:\n- Could not download https://cdn.example.test/a.log (a.log, 1 B): HTTP 503', complete: false })+ .mockResolvedValue({ text: 'Attached files:\n- /drops/a.log (a.log, 1 B)', complete: true })+ const host = new SuperTabHost(t.core, 'machine-1', { log: vi.fn(), attachedFiles }); hosts.push(host)+ await host.tick()+ expect(vi.mocked(t.core.turns.deliver).mock.calls[0]?.[1]).toContain('Could not download')+ t.event('rejected', 'team_waiting_busy')+ await host.tick()+ expect(vi.mocked(t.core.turns.deliver).mock.calls[1]?.[1]).toContain('/drops/a.log')+ t.event('rejected', 'team_waiting_busy')+ await host.tick()+ expect(attachedFiles).toHaveBeenCalledTimes(2)+ })+ it('delivers a message of files alone', async () => {+ const t = setup({ text: '', attachments: [{ id: 'a1', name: 'a.log', mime: 'text/plain', size: 1, url: 'https://cdn.example.test/a.log' }] })+ const host = new SuperTabHost(t.core, 'machine-1', { log: vi.fn(), attachedFiles: async () => ({ text: 'Attached files:\n- /drops/a.log (a.log, 1 B)', complete: true }) }); hosts.push(host)+ await host.tick()+ expect(vi.mocked(t.core.turns.deliver).mock.calls[0]?.[1]).toMatch(/from Collaborator:\nAttached files:\n/)+ })+})diff --git a/cli/src/superTabs/host.ts b/cli/src/superTabs/host.tsindex ecc7a097b..d79a9a913 100644--- a/cli/src/superTabs/host.ts+++ b/cli/src/superTabs/host.ts@@ -3,13 +3,13 @@ import { ContributedMachines } from './machines.js'import { retainContributions } from './retention.js'import { configurationObservation } from './configuration.js'import { NativeRecorder, nativeJournalFile } from './native.js'+import { attachedFiles } from './attachments.js'import { randomUUID } from 'node:crypto'import { existsSync, mkdirSync, readFileSync, renameSync, writeFileSync } from 'node:fs'import { dirname, join } from 'node:path'import type { CoreApi, TurnDelivery } from '../core/api.js'import { shellQuote } from '../orchestrator/prompts.js'import { noticeReason, WithheldDeliveries } from './withheld.js'-import { attachmentsOf, saveAttachment, type SuperTabAttachment } from './attachments.js'type Json = Record<string, unknown>export class SuperTabHostError extends Error {@@ -45,10 +45,8 @@ export interface SuperTabHostOptions {write?: (file: string, journal: Journal) => voidlog?: (message: string) => voidobservers?: typeof publishObservers- /** Saves an attached image on this machine and returns its path (attachments.ts); tests pass their own. */- saveAttachment?: (tabId: string, agentId: string, attachment: SuperTabAttachment) => Promise<string>+ attachedFiles?: typeof attachedFiles}-type AttachedImage = { attachment: SuperTabAttachment; path: string | null }export const hostJournalFile = (dataDir: string, machineId: string) => join(dataDir, 'super-tabs', `host-${machineId}.json`)const typedId = (entry: Entry) => `team:service:superTabs:${entry.deliveryId}`@@ -78,12 +76,13 @@ export class SuperTabHost {private readonly log: (message: string) => voidprivate retentionError: string | null = nullprivate readonly observers: typeof publishObservers- private readonly saveAttachment: NonNullable<SuperTabHostOptions['saveAttachment']>+ private readonly attachedFiles: typeof attachedFiles+ /** Each delivery's downloaded files, so input held by a busy terminal is not downloaded again on every retry. Only a+ * complete download is kept: a failed one is tried again before the next delivery of the same message. */+ private readonly files = new Map<string, string>()private readonly active = new Set<string>()private readonly authorized = new Map<string, number>()private readonly withheld = new WithheldDeliveries()- /** Images being saved for a claimed delivery, by delivery: done (`images`) or still running. */- private readonly downloads = new Map<string, { images: AttachedImage[] | null }>()private readonly stopHearing: () => voidprivate stopped = falseprivate running: Promise<void> | null = null@@ -102,8 +101,7 @@ export class SuperTabHost {if (!identifier(machineId)) throw new SuperTabHostError('MACHINE_UNAVAILABLE', 'This machine is not signed in.')this.file = hostJournalFile(core.dataDir, machineId)this.observers = options.observers ?? publishObservers- this.saveAttachment = options.saveAttachment ?? ((tabId, agentId, attachment) =>- saveAttachment(path => backend(core, 'GET', path), tabId, agentId, attachment))+ this.attachedFiles = options.attachedFiles ?? attachedFilesthis.now = options.now ?? Date.nowthis.write = options.write ?? writeJournalthis.log = options.log ?? (message => console.warn(`[super-tabs] ${message}`))@@ -154,7 +152,6 @@ export class SuperTabHost {this.native?.stop()this.machines?.stop()this.authorized.clear()- this.downloads.clear()try { this.observers(this.core.dataDir, this.machineId, [], 0) } catch { /* The old snapshot expires. */ }void this.core.turns.leaseDeliveries('superTabs', {})for (const id of this.active) this.core.turns.cancelDelivery(id)@@ -290,6 +287,7 @@ export class SuperTabHost {}}if (this.stopped) return+ for (const deliveryId of this.files.keys()) if (!this.journal.entries[deliveryId]) this.files.delete(deliveryId)for (const entry of Object.values(this.journal.entries)) {const id = typedId(entry)if (!seen.has(entry.deliveryId)) {@@ -311,7 +309,6 @@ export class SuperTabHost {const id = typedId(entry)delete this.journal.entries[deliveryId]this.withheld.clear(deliveryId)- this.downloads.delete(deliveryId)this.authorized.delete(id)if (this.active.delete(id)) this.core.turns.cancelDelivery(id)this.persist()@@ -354,27 +351,19 @@ export class SuperTabHost {this.authorized.set(id, this.now() + 2_500)return}- // Its images are still being saved: a later poll delivers it, and the claim below rechecks authority then.- if (this.downloads.get(deliveryId)?.images === null) returnconst result = object(await backend(this.core, 'POST', `${path}/${deliveryId}`, { type: 'claim', claimId: entry.claimId }))// The receipt check may have retired this held entry while the claim was in flight.if (this.stopped || this.journal.entries[deliveryId] !== entry) returnconst message = object(result.message)if (typeof message.text !== 'string' || !identifier(message.conversationId)) throw new Error('The delivery has no message.')- const attached = attachmentsOf(message)- let images: AttachedImage[] = []- if (attached.length) {- // Saving up to four 5 MB images takes seconds. It runs beside the poll, which keeps renewing every other- // delivery's lease meanwhile; this one is typed on the first poll after its images are saved.- const download = this.downloads.get(deliveryId)- if (!download) {- const started: { images: AttachedImage[] | null } = { images: null }- this.downloads.set(deliveryId, started)- void this.saveImages(entry, attached).then(saved => { started.images = saved; if (!this.stopped) void this.tick() })- return- }- images = download.images!+ // Downloaded before the lease: a large file must not use up the 2.5 s the core gives a write.+ let files = this.files.get(deliveryId)+ if (files === undefined) {+ const downloaded = await this.attachedFiles(message)+ files = downloaded.text+ if (downloaded.complete) this.files.set(deliveryId, files)}+ if (this.stopped || this.journal.entries[deliveryId] !== entry) returnthis.authorized.set(id, this.now() + 2_500)if (!(await this.leases()) || this.stopped) { this.authorized.delete(id); return }if (this.active.has(id)) return@@ -382,18 +371,8 @@ export class SuperTabHost {// The durable intent must exist before the core can write. A thrown disk write must not deliver.entry.stage = 'submitting'this.persist()- this.downloads.delete(deliveryId)this.active.add(id)- this.core.turns.deliver(entry.harnessId, this.prompt(entry, message, images), id)- }-- /** An image that cannot be read never holds up its message: the agent is told, and how to fetch it later. */- private saveImages(entry: Entry, attached: SuperTabAttachment[]): Promise<AttachedImage[]> {- return Promise.all(attached.map(async attachment => ({ attachment,- path: await this.saveAttachment(entry.tabId, entry.agentId, attachment).catch(error => {- this.log(`attachment ${attachment.id} for delivery ${entry.deliveryId}: ${error instanceof Error ? error.message : String(error)}`)- return null- }) })))+ this.core.turns.deliver(entry.harnessId, this.prompt(entry, message, files), id)}private async recordConfigurations(rows: unknown[]): Promise<void> {@@ -408,7 +387,7 @@ export class SuperTabHost {}}- private prompt(entry: Entry, message: Json, images: AttachedImage[] = []): string {+ private prompt(entry: Entry, message: Json, files: string): string {const command = `${this.core.daemon.command} super-tab --port ${this.core.daemon.port} --machine ${shellQuote(this.machineId)} --tab ${shellQuote(entry.tabId)} --agent ${shellQuote(entry.agentId)}`const group = message.conversationId as stringconst reply = identifier(message.replyTo)@@ -424,9 +403,7 @@ export class SuperTabHost {+ `Manage agreed work and delegation: ${command} help. Leads: route before starting or assigning: ${command} route GROUP JSON. Use independently verifiable outcomes; local helper subagents need no separate group.\n`+ `Ask questions and post results in this conversation. ${SUPER_TAB_REPLY_STYLE} Replies to these delivered instructions must be posted here explicitly.\n\n`+ native + reply + `Message ${String(message.id)} from ${String(object(message.author).name ?? 'a collaborator')}:\n${message.text}`- + (images.length ? `\n\n${images.map(({ attachment, path }) => path ? `Attached image: ${path}`- : `Attached image ${attachment.name} could not be fetched. Try again: ${command} attachment ${shellQuote(attachment.id)}`).join('\n')}`- + '\nOpen each attached image with your file-reading tool to see it.' : '')+ + (files ? `${message.text ? '\n\n' : ''}${files}` : '')}/** Says why the core keeps holding this delivery: once in the log per change of reason, and once to the conversation after 30 s. */diff --git a/cli/src/superTabs/service.spec.ts b/cli/src/superTabs/service.spec.tsindex 746d0f9fc..37d2f6460 100644--- a/cli/src/superTabs/service.spec.ts+++ b/cli/src/superTabs/service.spec.ts@@ -1,5 +1,4 @@import { createHash } from 'node:crypto'-import { readFileSync } from 'node:fs'import { describe, expect, it, vi } from 'vitest'import { fakeCore } from '../testing/fakeCore.js'import { superTabService } from './service.js'@@ -47,9 +46,6 @@ it('limits the owner proxy to Super Tab endpoints and preserves backend failuresexpect(await t.ask({ action: 'backend', method: 'GET', path }, owner)).toMatchObject({ error: 'INVALID_REQUEST' })}expect(await t.ask({ action: 'backend', method: 'DELETE', path: '/api/super-tabs' }, owner)).toMatchObject({ error: 'INVALID_REQUEST' })- for (const path of ['/api/super-tabs/tab', '/api/super-tabs/tab/attachments', '/api/super-tabs/tab/attachments/img1/parts/0', '/api/super-tabs/tab/attachments/img1?x=1']) {- expect(await t.ask({ action: 'backend', method: 'DELETE', path }, owner)).toMatchObject({ error: 'INVALID_REQUEST' })- }expect(t.call).not.toHaveBeenCalled()expect(await t.ask({ action: 'backend', method: 'GET', path: '/api/super-tabs/tab?asAgentId=agent' }, owner)).toMatchObject({ ok: true })vi.mocked(t.core.account.backend).mockResolvedValueOnce({ status: 403, body: { success: false, error: { code: 'FORBIDDEN', message: 'Access withdrawn' } } })@@ -75,31 +71,6 @@ it('resolves a native caller to its exact contribution and rechecks it before evexpect(await t.ask({ action: 'status', tabId: 'tab', agentId: t.agentId }, owner)).toMatchObject({ error: 'AGENT_UNAVAILABLE' })})-it('relays the image routes to the backend, and saves an attached image for its agent', async () => {- const t = setup()- for (const path of ['/api/super-tabs/tab/attachments', '/api/super-tabs/tab/attachments/img1/parts/3']) {- expect(await t.ask({ action: 'backend', method: 'POST', path, body: { data: 'AAAA' } }, owner)).toMatchObject({ ok: true })- expect(t.call).toHaveBeenLastCalledWith('POST', path, { data: 'AAAA' })- }- expect(await t.ask({ action: 'backend', method: 'DELETE', path: '/api/super-tabs/tab/attachments/img1' }, owner)).toMatchObject({ ok: true })- expect(t.call).toHaveBeenLastCalledWith('DELETE', '/api/super-tabs/tab/attachments/img1', undefined)- const png = Buffer.from([0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a, 1, 2])- const meta = { id: 'img1', name: 'diagram.webp', mime: 'image/png', size: png.length, width: 1, height: 1, parts: 1, complete: true }- vi.mocked(t.call).mockImplementation((async (_method: string, path: string) => ({ status: 200, body: { success: true,- data: path.includes('/parts/0') ? { data: png.toString('base64') } : path.includes('/attachments/') ? meta : { state: { agents: [t.agent] } } } })) as never)- const saved = await t.ask({ action: 'attachment', tabId: 'tab', agentId: t.agentId, attachmentId: 'img1' }, owner)- expect(saved).toMatchObject({ ok: true, value: { id: 'img1', name: 'diagram.webp', mime: 'image/png', size: png.length } })- const file = (saved.value as { path: string }).path- expect(file).toMatch(/-diagram\.png$/)- expect(readFileSync(file).equals(png)).toBe(true)- expect(t.call).toHaveBeenCalledWith('GET', `/api/super-tabs/tab/attachments/img1?asAgentId=${t.agentId}`, undefined)- expect(t.call).toHaveBeenCalledWith('GET', `/api/super-tabs/tab/attachments/img1/parts/0?asAgentId=${t.agentId}`, undefined)- vi.mocked(t.call).mockImplementation((async (_method: string, path: string) => ({ status: 200, body: { success: true,- data: path.includes('/attachments/') ? { ...meta, mime: 'image/gif' } : { state: { agents: [t.agent] } } } })) as never)- expect(await t.ask({ action: 'attachment', tabId: 'tab', agentId: t.agentId, attachmentId: 'img1' }, owner)).toMatchObject({ error: 'ATTACHMENT_UNAVAILABLE' })- expect((await t.ask({ action: 'help' }, owner)).help).toMatchObject({ attachment: expect.stringContaining('file-reading tool') })-})-it('keeps host capacity separate from account authority and closes it on disconnect or identity change', async () => {const core = fakeCore()const reserve = vi.fn(async () => ({ ok: true, reservationId: 'native-creation-id' }))@@ -384,3 +355,19 @@ describe('which messages still need an answer', () => {expect(failed.value.messages[0]).not.toHaveProperty('answered')})})++describe('post --attach steps', () => {+ it('reads whether this post already went out with files, as the agent', async () => {+ const t = setup()+ const messageId = createHash('sha256').update(JSON.stringify(['tab', `agent:${t.agentId}`, 'op'])).digest('hex').slice(0, 24)+ vi.mocked(t.core.account.backend).mockImplementation(async (_method: string, path: string) => ({ status: 200, body: { success: true, data:+ path.includes('/messages?') ? { messages: [{ id: messageId, attachments: [{ id: 'f0' }] }] } : { state: { agents: [t.agent] } } } }))+ expect(await t.ask({ action: 'attachment', step: 'sent', tabId: 'tab', agentId: t.agentId, conversationId: 'lead', operationId: 'op' }, owner))+ .toEqual({ ok: true, value: { agentId: t.agentId, attachmentIds: ['f0'] } })+ expect(t.call).toHaveBeenLastCalledWith('GET', `/api/super-tabs/tab/conversations/lead/messages?asAgentId=${t.agentId}&messageId=${messageId}`, undefined)+ vi.mocked(t.core.account.backend).mockImplementation(async (_method: string, path: string) => ({ status: 200, body: { success: true, data:+ path.includes('/messages?') ? { messages: [] } : { state: { agents: [t.agent] } } } }))+ expect(await t.ask({ action: 'attachment', step: 'sent', tabId: 'tab', agentId: t.agentId, conversationId: 'lead', operationId: 'op' }, owner))+ .toEqual({ ok: true, value: { agentId: t.agentId, attachmentIds: null } })+ })+})diff --git a/cli/src/superTabs/service.ts b/cli/src/superTabs/service.tsindex 8b1169ecb..4aa04f608 100644--- a/cli/src/superTabs/service.ts+++ b/cli/src/superTabs/service.ts@@ -9,14 +9,13 @@ import { machineChoices } from '../lib/newCommand.js'import { START_REQUIREMENTS } from './capacity.js'import { CapacityReservations, type ReservationBook } from './reservations.js'import { ContributionPreparations, prepareContribution } from './contribution.js'-import { attachmentsOf, saveAttachment } from './attachments.js'+import { messageIdOf } from './attach.js'const HELP = {status: 'Read the shared tab roster and work.',- messages: 'messages GROUP: read recent messages in a conversation. A message with images lists them under attachments.',+ messages: 'messages GROUP: read recent messages in a conversation.',message: 'message GROUP MESSAGE_ID: read one exact message, including an earlier question or result referenced by a reply.',- attachment: 'attachment ATTACHMENT_ID: save an image attached to a message on this machine and print its path. Open that path with your file-reading tool to see it.',- post: 'post GROUP TEXT OPERATION_ID [--reply-to MESSAGE_ID]: reply in that conversation. Use a unique ID per message and reuse it after an interrupted request. Answer a message once, with --reply-to its ID.',+ post: 'post GROUP TEXT OPERATION_ID [--reply-to MESSAGE_ID] [--attach PATH]...: reply in that conversation. Use a unique ID per message and reuse it after an interrupted request. Answer a message once, with --reply-to its ID. --attach sends a file (a screenshot, a log; up to 10 files of 10 MB each), and TEXT may then be empty.',start: 'start OPERATION_ID JSON: create one agent in a conversation on a machine you can access. Repeat exactly after an interruption; it follows the same native creation receipt. It does not assign work.',resume: 'resume START_ID: finish a pending start without creating another agent.',route: 'route GROUP JSON: before starting or assigning work, choose who does it. JSON: {"difficulty":"low|medium|high","risk":"low|medium|high","why":"one sentence","needs":{"tools":[],"devices":[],"cwd":"/absolute/repo"}}. Start or assign the pick with its routeDecisionId; to choose otherwise, pass overrideReason.',@@ -105,10 +104,8 @@ export function superTabService(core: CoreApi, options: SuperTabServiceOptions =if (payload.action === 'prepareContribution') return preparations.read(payload)if (payload.action === 'backend') {const { method, path } = payload- // DELETE only takes back one's own unsent image; every other route reads or writes.- if (typeof path !== 'string' || !/^\/api\/super-tabs(?:\/[A-Za-z0-9_-]+)*(?:\?[A-Za-z0-9_=&%-]+)?$/.test(path)- || !(['GET', 'POST'].includes(String(method))- || (method === 'DELETE' && /^\/api\/super-tabs\/[A-Za-z0-9_-]+\/attachments\/[A-Za-z0-9_-]+$/.test(path)))) {+ if (!['GET', 'POST'].includes(String(method)) || typeof path !== 'string'+ || !/^\/api\/super-tabs(?:\/[A-Za-z0-9_-]+)*(?:\?[A-Za-z0-9_=&%-]+)?$/.test(path)) {return { error: 'INVALID_REQUEST', detail: 'Choose a Super Tab endpoint.' }}const value = await backend(core, method as string, path, payload.body)@@ -210,16 +207,17 @@ export function superTabService(core: CoreApi, options: SuperTabServiceOptions =return { ok: true, value: markAnswered(page, list(later), agentId) }} catch { return { ok: true, value: page } }}- if (payload.action === 'attachment' && identifier(payload.attachmentId)) {- const [attachment] = attachmentsOf({ attachments: [await backend(core, 'GET', `${path}/attachments/${payload.attachmentId}?${identity}`)] })- if (!attachment) return { error: 'ATTACHMENT_UNAVAILABLE', detail: 'This image cannot be read.' }- const file = await saveAttachment(target => backend(core, 'GET', target), payload.tabId, agentId, attachment)- return { ok: true, value: { id: attachment.id, name: attachment.name, mime: attachment.mime, size: attachment.size, path: file } }- }if (payload.action === 'command' && identifier(payload.operationId) && payload.command && typeof payload.command === 'object' && !Array.isArray(payload.command)) {return { ok: true, operationId: payload.operationId, value: await backend(core, 'POST', `${path}/commands`,{ operationId: payload.operationId, command: payload.command, asAgentId: agentId }) }}+ // `post --attach` asks first whether this post already went out with its files.+ if (payload.action === 'attachment' && identifier(payload.conversationId) && payload.step === 'sent' && identifier(payload.operationId)) {+ const sent = object(await backend(core, 'GET', `${path}/conversations/${payload.conversationId}/messages?${identity}&messageId=${messageIdOf(payload.tabId, agentId, payload.operationId)}`))+ const earlier = object(list(sent.messages)[0])+ // The agent's id goes back too: the files are uploaded as this agent, through the daemon's local upload route.+ return { ok: true, value: { agentId, attachmentIds: Array.isArray(earlier.attachments) ? list(earlier.attachments).map(a => String(a.id)) : null } }+ }return { error: 'INVALID_REQUEST' }} catch (error) {return error instanceof SuperTabHostErrordiff --git a/desktop/lib/api/api_client.dart b/desktop/lib/api/api_client.dartindex 0c7b83bd1..65e2d3179 100644--- a/desktop/lib/api/api_client.dart+++ b/desktop/lib/api/api_client.dart@@ -236,6 +236,28 @@ class ApiClient {);}+ /// Posts [form] to [path] and answers whatever came back, a refusal too: a+ /// file's way up has its own errors to read. A browser sends it to the+ /// backend with its token; on a computer the local daemon passes it on.+ Future<Response<dynamic>> postForm(+ String path,+ FormData form, {+ CancelToken? cancelToken,+ ProgressCallback? onSendProgress,+ }) => _dio.post<dynamic>(+ path,+ data: form,+ cancelToken: cancelToken,+ onSendProgress: onSendProgress,+ options: Options(+ // The backend streams the file into storage before it answers.+ receiveTimeout: const Duration(minutes: 2),+ // The daemon answers 403 without it. The backend is not sent it: from a+ // browser a custom header would add a CORS preflight.+ headers: auth == null ? {'x-adapter-local': '1'} : null,+ ),+ );+Future<Map<String, dynamic>?> me() async {final res = await _dio.get('/api/auth/me');return unwrapApiResponse(res) as Map<String, dynamic>?;diff --git a/desktop/lib/api/bearer_auth_interceptor.dart b/desktop/lib/api/bearer_auth_interceptor.dartindex 666eec70a..5386720af 100644--- a/desktop/lib/api/bearer_auth_interceptor.dart+++ b/desktop/lib/api/bearer_auth_interceptor.dart@@ -47,6 +47,8 @@ class BearerAuthInterceptor extends Interceptor {failedToken: options.extra[_tokenKey] as String?,);options.extra[_retriedKey] = true;+ // A form is read once: the retry sends a copy, as the first try did.+ if (options.data case final FormData form) options.data = form.clone();handler.resolve(await _dio.fetch<dynamic>(options));} catch (error) {// The old access token's 401 does not mean a refresh service outage revoked the session.diff --git a/desktop/lib/state/app_state.dart b/desktop/lib/state/app_state.dartindex 369d8de7f..097864305 100644--- a/desktop/lib/state/app_state.dart+++ b/desktop/lib/state/app_state.dart@@ -94,6 +94,7 @@ import '../settings/config_store.dart';import '../settings/experimental_features.dart';import '../core/local_key_value_store.dart';import '../core/harness_file_store.dart';+import '../super_tabs/attachment_upload.dart';import '../super_tabs/client.dart';import '../super_tabs/controller.dart';import '../measurement/setup_preference_store.dart';@@ -1703,6 +1704,7 @@ class AppNotifier extends ChangeNotifier {late final superTabs = SuperTabClient(storage: localStore ?? HarnessFileStore.shared,+ upload: uploadWith(() => api),discoveryInterval: kUnderTest ? Duration.zero : const Duration(seconds: 15),onTabs: (tabs, hidden) {// The browser can learn its account before the saved layout finishesdiff --git a/desktop/lib/state/harness_attachments.dart b/desktop/lib/state/harness_attachments.dartindex 15e221f12..3bf0dc43b 100644--- a/desktop/lib/state/harness_attachments.dart+++ b/desktop/lib/state/harness_attachments.dart@@ -15,11 +15,22 @@ class HarnessAttachment {/// The files a New Harness box carries into its harness. Held in memory/// until the harness's terminal is open to take them ([deliverAttachedTask]).class HarnessAttachments extends ChangeNotifier {- HarnessAttachments({this.onDeliveryProblem});+ HarnessAttachments({+ this.onDeliveryProblem,+ this.limitBytes = maxBytes,+ this.limitFiles,+ });/// What one file may weigh: the daemon's own ceiling for a pasted file.static const maxBytes = terminalLocalPasteFileMaxPayloadBytes;+ /// What one file may weigh in this box; a box whose files go somewhere with+ /// a lower ceiling than the daemon's passes it.+ final int limitBytes;++ /// How many files this box holds, or null for any number.+ final int? limitFiles;+/// Told when files could not reach a created harness — after its box has/// closed, so the workspace says it rather than the box.final void Function(String message)? onDeliveryProblem;@@ -38,19 +49,24 @@ class HarnessAttachments extends ChangeNotifier {Iterable<String> oversized = const [],}) {final tooLarge = [...oversized];+ var surplus = 0;for (final file in files) {if (file.bytes.isEmpty) continue;- if (file.bytes.length > maxBytes) {+ if (file.bytes.length > limitBytes) {tooLarge.add(file.name);continue;}- _files- ..removeWhere((kept) => kept.name == file.name)- ..add(file);+ _files.removeWhere((kept) => kept.name == file.name);+ if (limitFiles != null && _files.length >= limitFiles!) {+ surplus++;+ continue;+ }+ _files.add(file);}notifyListeners();+ if (surplus > 0) return 'Attach at most $limitFiles files.';if (tooLarge.isEmpty) return null;- final limit = '${maxBytes ~/ (1024 * 1024)} MB';+ final limit = '${limitBytes ~/ (1024 * 1024)} MB';return tooLarge.length == 1? '${tooLarge.single} is over $limit.': '${tooLarge.length} files are over $limit.';diff --git a/desktop/lib/super_tabs/attachment_chips.dart b/desktop/lib/super_tabs/attachment_chips.dartnew file mode 100644index 000000000..a6e4161fd--- /dev/null+++ b/desktop/lib/super_tabs/attachment_chips.dart@@ -0,0 +1,155 @@+import 'package:flutter/material.dart';++import '../core/open_in_browser.dart';+import '../shared/theme/file_type_icon.dart';+import '../shared/widgets/app_dialog.dart';+import '../widgets/desktop_chrome.dart';+import '../widgets/update_notice.dart' show formatDownloadSize;+import 'attachment_upload.dart';+import 'model.dart';++/// The files a message carries, one chip each. The chat never loads a file by+/// itself: a chip only names it, and a click opens it — an image in a viewer+/// that fetches it then, anything else in the browser.+class SuperTabAttachmentChips extends StatelessWidget {+ const SuperTabAttachmentChips(this.attachments, {super.key});++ final List<SuperTabAttachment> attachments;++ @override+ Widget build(BuildContext context) => Wrap(+ spacing: 6,+ runSpacing: 6,+ children: [for (final file in attachments) _AttachmentChip(file: file)],+ );+}++class _AttachmentChip extends StatelessWidget {+ const _AttachmentChip({required this.file});++ final SuperTabAttachment file;++ Future<void> _open(BuildContext context) async {+ final url = attachmentLink(file.url);+ if (url == null) {+ ScaffoldMessenger.maybeOf(context)?.showSnackBar(+ const SnackBar(+ content: Text(+ 'This file isn’t on Harness’s file storage, so it wasn’t opened.',+ ),+ ),+ );+ return;+ }+ if (file.isImage) {+ await showAppDialog<void>(+ context: context,+ builder: (_) => _ImageViewer(file: file, url: url),+ );+ } else {+ await openInBrowser(url);+ }+ }++ @override+ Widget build(BuildContext context) {+ final size = formatDownloadSize(file.size);+ return Material(+ color: DesktopChrome.foreground.withValues(alpha: .055),+ borderRadius: BorderRadius.circular(20),+ child: InkWell(+ key: ValueKey('super-attachment:${file.id}'),+ borderRadius: BorderRadius.circular(20),+ onTap: () => _open(context),+ child: Container(+ constraints: const BoxConstraints(maxWidth: 280),+ padding: const EdgeInsets.symmetric(horizontal: 10),+ height: DesktopChrome.compactControlHeight,+ child: Row(+ mainAxisSize: MainAxisSize.min,+ children: [+ Icon(+ fileTypeIcon(file.name),+ size: 13,+ color: DesktopChrome.muted,+ ),+ const SizedBox(width: 6),+ Flexible(+ child: Text(+ file.name,+ maxLines: 1,+ overflow: TextOverflow.ellipsis,+ style: DesktopChrome.control(),+ ),+ ),+ if (size.isNotEmpty) ...[+ const SizedBox(width: 6),+ Text(size, style: DesktopChrome.metadata()),+ ],+ ],+ ),+ ),+ ),+ );+ }+}++/// The picture, fetched when this opens.+class _ImageViewer extends StatelessWidget {+ const _ImageViewer({required this.file, required this.url});++ final SuperTabAttachment file;+ final Uri url;++ @override+ Widget build(BuildContext context) => Dialog(+ child: Padding(+ padding: const EdgeInsets.all(16),+ child: Column(+ mainAxisSize: MainAxisSize.min,+ crossAxisAlignment: CrossAxisAlignment.stretch,+ children: [+ Text(+ file.name,+ maxLines: 1,+ overflow: TextOverflow.ellipsis,+ style: DesktopChrome.control(medium: true),+ ),+ const SizedBox(height: 12),+ Flexible(+ child: InteractiveViewer(+ child: Image.network(+ url.toString(),+ key: ValueKey('super-attachment-image:${file.id}'),+ fit: BoxFit.contain,+ loadingBuilder: (_, child, progress) => progress == null+ ? child+ : const Center(child: CircularProgressIndicator()),+ errorBuilder: (_, _, _) => Center(+ child: Text(+ 'This image can’t be shown here.',+ style: DesktopChrome.metadata(),+ ),+ ),+ ),+ ),+ ),+ const SizedBox(height: 12),+ Row(+ mainAxisAlignment: MainAxisAlignment.end,+ children: [+ TextButton(+ onPressed: () => openInBrowser(url),+ child: const Text('Open in browser'),+ ),+ TextButton(+ onPressed: () => Navigator.pop(context),+ child: const Text('Close'),+ ),+ ],+ ),+ ],+ ),+ ),+ );+}diff --git a/desktop/lib/super_tabs/attachment_upload.dart b/desktop/lib/super_tabs/attachment_upload.dartnew file mode 100644index 000000000..e57214b4f--- /dev/null+++ b/desktop/lib/super_tabs/attachment_upload.dart@@ -0,0 +1,136 @@+import 'dart:typed_data';++import 'package:dio/dio.dart';++import '../api/api_client.dart';+import 'controller.dart';++/// What the backend allows one message to carry.+const kSuperTabAttachmentMaxBytes = 10 * 1024 * 1024;+const kSuperTabAttachmentMaxFiles = 10;++/// The content type a file of this [name] is sent as: the kinds a chat shows+/// or opens, and `application/octet-stream` for the rest.+String mimeForName(String name) {+ final dot = name.lastIndexOf('.');+ final extension = dot < 0 ? '' : name.substring(dot + 1).toLowerCase();+ return _mimes[extension] ?? 'application/octet-stream';+}++const _mimes = {+ 'png': 'image/png',+ 'jpg': 'image/jpeg',+ 'jpeg': 'image/jpeg',+ 'gif': 'image/gif',+ 'webp': 'image/webp',+ 'pdf': 'application/pdf',+ 'json': 'application/json',+ 'zip': 'application/zip',+ 'txt': 'text/plain',+ 'log': 'text/plain',+ 'md': 'text/markdown',+ 'csv': 'text/csv',+};++/// Where the backend serves attachments from; the same host as its+/// `SUPER_TAB_ATTACHMENTS_PUBLIC_BASE`.+const kSuperTabAttachmentHost = String.fromEnvironment(+ 'SUPER_TAB_ATTACHMENTS_HOST',+ defaultValue: 'cdn.harness.autonomous.ai',+);++/// [url] as a link to open, or null unless it is https on the attachments host:+/// a message's url is whatever its sender's backend row says.+Uri? attachmentLink(String url) {+ final link = Uri.tryParse(url);+ return link != null &&+ link.scheme == 'https' &&+ link.host == kSuperTabAttachmentHost+ ? link+ : null;+}++/// Sends one file to the backend and returns its answer, `{attachment: {...}}`.+/// [onProgress] is told the part sent, from 0 to 1. A refusal throws a+/// [SuperTabFailure] carrying the backend's code.+typedef SuperTabUpload = Future<Map<String, dynamic>> Function({+ required String tabId,+ required String conversationId,+ required String name,+ required String mime,+ required Uint8List bytes,+ required CancelToken cancel,+ required void Function(double sent) onProgress,+});++/// The upload of a build that cannot reach the backend with a file.+Future<Map<String, dynamic>> refuseUpload({+ required String tabId,+ required String conversationId,+ required String name,+ required String mime,+ required Uint8List bytes,+ required CancelToken cancel,+ required void Function(double sent) onProgress,+}) => Future.error(+ const SuperTabFailure('UPLOAD_UNAVAILABLE', 'Files can’t be sent from here.'),+);++/// Uploads with [api]: one `multipart/form-data` request, straight to the+/// backend in a browser and through the local daemon on a computer.+SuperTabUpload uploadWith(ApiClient Function() api) =>+ ({+ required tabId,+ required conversationId,+ required name,+ required mime,+ required bytes,+ required cancel,+ required onProgress,+ }) async {+ final response = await api().postForm(+ '/api/super-tabs/${Uri.encodeComponent(tabId)}/attachments',+ FormData.fromMap({+ 'conversationId': conversationId,+ 'file': MultipartFile.fromBytes(+ bytes,+ filename: name,+ contentType: DioMediaType.parse(mime),+ ),+ }),+ cancelToken: cancel,+ onSendProgress: (sent, total) {+ if (total > 0) onProgress(sent / total);+ },+ );+ final body = response.data;+ if (response.statusCode == 200 &&+ body is Map &&+ body['success'] == true) {+ return Map<String, dynamic>.from(body['data'] as Map);+ }+ throw _refusal(response);+ };++/// What a refused upload says. The backend answers `{error: {code, message}}`;+/// the local daemon, a bare code string such as `{error: 'FORBIDDEN'}`.+SuperTabFailure _refusal(Response<dynamic> response) {+ final body = response.data;+ final error = body is Map ? body['error'] : null;+ final code = error is Map+ ? error['code'] as String?+ : error is String+ ? error+ : null;+ final message = error is Map ? error['message'] as String? : null;+ return SuperTabFailure(+ code ?? 'UPLOAD_FAILED',+ message ??+ switch (code) {+ 'FORBIDDEN' => 'You can’t send files in this conversation.',+ 'ATTACHMENT_TOO_LARGE' => 'That file is over 10 MB.',+ _ => 'Could not upload the file. Try again.',+ },+ statusCode: response.statusCode ?? 0,+ );+}diff --git a/desktop/lib/super_tabs/attachments.dart b/desktop/lib/super_tabs/attachments.dartdeleted file mode 100644index f68e3448d..000000000--- a/desktop/lib/super_tabs/attachments.dart+++ /dev/null@@ -1,328 +0,0 @@-import 'dart:typed_data';--import 'package:flutter/material.dart';--import '../clipboard/copied_files.dart';-import '../clipboard/native_clipboard.dart';-import '../shared/theme/app_icons.dart';-import '../shared/widgets/app_dialog.dart';-import '../shared/widgets/app_icon_button.dart';-import '../state/harness_attachments.dart';-import '../widgets/desktop_chrome.dart';-import 'model.dart';--/// The backend's limits (backend/src/superTabs/attachments.ts): a message-/// carries up to four PNG, JPEG or WebP images of up to 5 MB each.-const kSuperTabImagesPerMessage = 4;-const kSuperTabImageMaxBytes = 5 * 1024 * 1024;--/// The bytes travel in parts this size, each one small request through the-/// machine relay (`ATTACHMENT_PART_BYTES` on the backend).-const kSuperTabImagePartBytes = 256 * 1024;--/// The image type [bytes] really are, read from their header, or null for-/// anything a Swarm does not take (a GIF, a PDF, a renamed file).-String? superTabImageMime(Uint8List bytes) {- bool starts(List<int> prefix, [int at = 0]) =>- bytes.length >= at + prefix.length &&- [for (var i = 0; i < prefix.length; i++) bytes[at + i] == prefix[i]]- .every((same) => same);- if (starts(const [0x89, 0x50, 0x4E, 0x47, 0x0D, 0x0A, 0x1A, 0x0A])) {- return 'image/png';- }- if (starts(const [0xFF, 0xD8, 0xFF])) return 'image/jpeg';- if (starts('RIFF'.codeUnits) && starts('WEBP'.codeUnits, 8)) {- return 'image/webp';- }- return null;-}--/// The images waiting in one conversation's composer. They stay in memory-/// only: a saved pending send names their uploaded IDs, never their bytes.-class SuperTabImages extends HarnessAttachments {- SuperTabImages({this.onDiscard});-- /// Told the backend ID of an upload nobody will send: removed, replaced,- /// or refused. The backend keeps at most 24 unsent images a person, so each- /// is deleted at once rather than left to expire.- final void Function(String id)? onDiscard;-- final _uploads = <HarnessAttachment, ({String id, bool complete})>{};-- /// The backend ID of [file] once all its parts are uploaded.- String? uploadedId(HarnessAttachment file) =>- _uploads[file]?.complete == true ? _uploads[file]!.id : null;-- /// The backend ID of [file] once its upload started, finished or not: an- /// interrupted upload resumes there.- String? startedId(HarnessAttachment file) => _uploads[file]?.id;- void markStarted(HarnessAttachment file, String id) =>- _uploads[file] = (id: id, complete: false);- void markUploaded(HarnessAttachment file, String id) =>- _uploads[file] = (id: id, complete: true);-- /// The backend no longer has [file]'s upload; the next send starts over.- void forget(HarnessAttachment file) => _uploads.remove(file);-- /// The backend refused these uploads; the next send uploads again.- void forgetUploads() {- for (final file in [..._uploads.keys]) {- _discard(file);- }- }-- /// [file] went out with a message: its upload is the message's now.- void sent(HarnessAttachment file) {- _uploads.remove(file);- super.remove(file);- }-- void _discard(HarnessAttachment file) {- final upload = _uploads.remove(file);- if (upload != null) onDiscard?.call(upload.id);- }-- /// Takes PNG, JPEG and WebP images up to 5 MB, four in all, and says what it- /// left out.- @override- String? add(- Iterable<HarnessAttachment> files, {- Iterable<String> oversized = const [],- }) {- final notImages = <String>[], tooLarge = [...oversized];- final taken = <HarnessAttachment>[];- var overCount = 0;- for (final file in files) {- if (file.bytes.isEmpty) continue;- if (superTabImageMime(file.bytes) == null) {- notImages.add(file.name);- } else if (file.bytes.length > kSuperTabImageMaxBytes) {- tooLarge.add(file.name);- } else if (this.files.length + taken.length >=- kSuperTabImagesPerMessage &&- !this.files.any((kept) => kept.name == file.name)) {- overCount++;- } else {- taken.add(file);- }- }- for (final file in this.files) {- if (taken.any((next) => next.name == file.name)) _discard(file);- }- super.add(taken);- return [- if (notImages.length == 1)- '${notImages.single} is not a PNG, JPEG or WebP image.'- else if (notImages.isNotEmpty)- '${notImages.length} files are not PNG, JPEG or WebP images.',- if (tooLarge.length == 1)- '${tooLarge.single} is over 5 MB.'- else if (tooLarge.isNotEmpty)- '${tooLarge.length} images are over 5 MB.',- if (overCount > 0) 'A message can carry up to 4 images.',- ].join(' ').nullIfEmpty;- }-- @override- void remove(HarnessAttachment file) {- _discard(file);- super.remove(file);- }-- @override- void clear() {- forgetUploads();- super.clear();- }-}--/// What ⌘V in the Swarm composer takes from files copied in a file manager:-/// only the images among them. Any other copied file pastes as before, its name-/// as text, rather than being refused.-Future<CopiedFiles> superTabCopiedImages() async {- final copied = await readCopiedFiles(- await NativeClipboard.readFilePaths(),- maxBytes: kSuperTabImageMaxBytes,- );- return (- files: [- for (final file in copied.files)- if (superTabImageMime(file.bytes) != null) file,- ],- tooLarge: [- for (final name in copied.tooLarge)- if (RegExp(r'\.(png|jpe?g|webp)$', caseSensitive: false).hasMatch(name))- name,- ],- );-}--extension on String {- String? get nullIfEmpty => isEmpty ? null : this;-}--/// A message's images as small thumbnails; a click shows one larger.-class SuperTabMessageImages extends StatelessWidget {- const SuperTabMessageImages({- super.key,- required this.attachments,- required this.load,- });-- final List<SuperTabAttachment> attachments;- final Future<Uint8List> Function(SuperTabAttachment attachment) load;-- static const thumbnail = 120.0;-- @override- Widget build(BuildContext context) => Padding(- padding: const EdgeInsets.only(top: 6),- child: Wrap(- spacing: 8,- runSpacing: 8,- children: [- for (final attachment in attachments)- _Thumbnail(attachment: attachment, load: load),- ],- ),- );-}--class _Thumbnail extends StatefulWidget {- const _Thumbnail({required this.attachment, required this.load});-- final SuperTabAttachment attachment;- final Future<Uint8List> Function(SuperTabAttachment attachment) load;-- @override- State<_Thumbnail> createState() => _ThumbnailState();-}--class _ThumbnailState extends State<_Thumbnail> {- late Future<Uint8List> _bytes = widget.load(widget.attachment);-- void _retry() => setState(() => _bytes = widget.load(widget.attachment));-- Future<void> _open(Uint8List bytes) => showAppDialog<void>(- context: context,- builder: (context) => Dialog(- backgroundColor: DesktopChrome.surface,- insetPadding: const EdgeInsets.all(32),- child: Column(- mainAxisSize: MainAxisSize.min,- crossAxisAlignment: CrossAxisAlignment.stretch,- children: [- Padding(- padding: const EdgeInsets.fromLTRB(16, 8, 8, 0),- child: Row(- children: [- Expanded(- child: Text(- widget.attachment.name,- maxLines: 1,- overflow: TextOverflow.ellipsis,- style: DesktopChrome.control(medium: true),- ),- ),- AppIconButton(- icon: AppIcons.close,- tooltip: 'Close',- onPressed: () => Navigator.pop(context),- ),- ],- ),- ),- Flexible(- child: Padding(- padding: const EdgeInsets.all(16),- child: InteractiveViewer(- child: Image.memory(- bytes,- key: ValueKey(- 'super-message-image-full:${widget.attachment.id}',- ),- fit: BoxFit.contain,- ),- ),- ),- ),- ],- ),- ),- );-- @override- Widget build(BuildContext context) {- final attachment = widget.attachment;- const size = SuperTabMessageImages.thumbnail;- return FutureBuilder<Uint8List>(- future: _bytes,- builder: (context, snapshot) {- final bytes = snapshot.data;- final Widget child;- if (bytes != null) {- child = Image.memory(- bytes,- key: ValueKey('super-message-image:${attachment.id}'),- width: size,- height: size,- // Decoded at the size it is drawn, not the screenshot's own.- cacheWidth: (size * 3).toInt(),- fit: BoxFit.cover,- gaplessPlayback: true,- errorBuilder: (_, _, _) => _placeholder('Image unavailable'),- );- } else if (snapshot.hasError) {- child = _placeholder('Could not load ${attachment.name}');- } else {- child = const Center(- child: SizedBox.square(- dimension: 16,- child: CircularProgressIndicator(strokeWidth: 2),- ),- );- }- return Tooltip(- message: snapshot.hasError- ? 'Could not load ${attachment.name}. Click to try again.'- : attachment.name,- child: Semantics(- button: true,- label: 'Image ${attachment.name}',- child: InkWell(- key: ValueKey('super-message-attachment:${attachment.id}'),- borderRadius: BorderRadius.circular(8),- onTap: bytes != null- ? () => _open(bytes)- : snapshot.hasError- ? _retry- : null,- child: ClipRRect(- borderRadius: BorderRadius.circular(8),- child: Container(- width: size,- height: size,- color: DesktopChrome.foreground.withValues(alpha: .055),- child: child,- ),- ),- ),- ),- );- },- );- }-- Widget _placeholder(String label) => Center(- child: Padding(- padding: const EdgeInsets.all(8),- child: Text(- label,- textAlign: TextAlign.center,- maxLines: 3,- overflow: TextOverflow.ellipsis,- style: DesktopChrome.metadata(),- ),- ),- );-}diff --git a/desktop/lib/super_tabs/client.dart b/desktop/lib/super_tabs/client.dartindex 30f7538ae..689698616 100644--- a/desktop/lib/super_tabs/client.dart+++ b/desktop/lib/super_tabs/client.dart@@ -2,6 +2,7 @@ import 'dart:async';import 'dart:convert';import '../core/local_key_value_store.dart';+import 'attachment_upload.dart';import 'controller.dart';import 'model.dart';@@ -21,12 +22,14 @@ class SuperTabClient {required this.storage,this.onSnapshot,this.onTabs,+ this.upload = refuseUpload,this.discoveryInterval = const Duration(seconds: 15),});final SuperTabTransport transport;final LocalKeyValueStore storage;final void Function(SuperTabController)? onSnapshot;final void Function(List<SuperTabListing>, Set<String> hidden)? onTabs;+ final SuperTabUpload upload;final Duration discoveryInterval;String? _account;int _generation = 0;@@ -238,6 +241,7 @@ class SuperTabClient {return map(method, path, body: body);},save: (state) => storage.write(key, jsonEncode(state)),+ upload: upload,);var seenRevision = -1;controller.addListener(() {diff --git a/desktop/lib/super_tabs/controller.dart b/desktop/lib/super_tabs/controller.dartindex ce7f1a2a3..808737e09 100644--- a/desktop/lib/super_tabs/controller.dart+++ b/desktop/lib/super_tabs/controller.dart@@ -1,12 +1,11 @@import 'dart:async';-import 'dart:convert';import 'dart:math';-import 'dart:typed_data';+import 'package:dio/dio.dart' show CancelToken, DioException, DioExceptionType;import 'package:flutter/foundation.dart';import '../state/harness_attachments.dart';-import 'attachments.dart';+import 'attachment_upload.dart';import 'model.dart';typedef SuperTabRequest = Future<Map<String, dynamic>> Function(@@ -39,6 +38,8 @@ class SuperTabController extends ChangeNotifier {required this.accountId,required this.request,required this.save,+ this.upload = refuseUpload,+ this.uploadTimeout = const Duration(minutes: 2),Map<String, dynamic> initial = const {},this.pollInterval = const Duration(seconds: 3),}) {@@ -97,11 +98,18 @@ class SuperTabController extends ChangeNotifier {final SuperTabRequest request;final Future<void> Function(Map<String, dynamic> state) save;final Duration pollInterval;++ /// Sends one file to the backend.+ final SuperTabUpload upload;++ /// How long an upload may go without a byte moving before the send gives up.+ final Duration uploadTimeout;SuperTabSnapshot? snapshot;String selectedId = 'lead';int revision = -1;- String? error, operationError;- bool loading = false, saving = false, accessRevoked = false;+ String? error, operationError, operationErrorCode;+ bool loading = false, saving = false, uploading = false;+ bool accessRevoked = false;bool _disposed = false;Timer? _poll, _draftSave;Future<void>? _refreshing;@@ -111,8 +119,14 @@ class SuperTabController extends ChangeNotifier {final _terminals = <String, String>{};final _mentions = <String, Map<String, String>>{};final _readAt = <String, int>{};- final _images = <String, SuperTabImages>{};- final _imageBytes = <String, Future<Uint8List>>{};+ final _attachments = <String, HarnessAttachments>{};+ // Files already uploaded for the message being sent, so a retry sends their+ // ids rather than uploading them again.+ final _uploaded = <HarnessAttachment, String>{};+ final _progress = <HarnessAttachment, double>{};+ CancelToken? _cancel;+ ({String conversationId, List<HarnessAttachment> files})? _sending;+ int _uploadRun = 0;final _messages = <String, List<SuperTabMessage>>{};final _before = <String, int?>{};final _reading = <String>{};@@ -137,103 +151,30 @@ class SuperTabController extends ChangeNotifier {_pending == null ? null : superTabMap(_pending!['command']);String draft(String id) => _drafts[id] ?? '';- /// The images waiting in [conversationId]'s composer, kept in memory only.- SuperTabImages images(String conversationId) =>- _images[conversationId] ??= (SuperTabImages(- onDiscard: (id) => unawaited(- request(- 'DELETE',- '$_path/attachments/${Uri.encodeComponent(id)}',- ).then((_) {}, onError: (Object _) {}),- ),- )..addListener(_changed));-- /// An attached image's bytes, read part by part through the same relay as- /// every other request. The last few stay in memory; a failed read is- /// forgotten so the next one tries again.- Future<Uint8List> attachmentBytes(SuperTabAttachment attachment) {- final known = _imageBytes.remove(attachment.id);- if (known != null) return _imageBytes[attachment.id] = known;- final read = _readAttachment(attachment);- _imageBytes[attachment.id] = read;- // A screenshot is a few megabytes: eight stay, about the images in view.- while (_imageBytes.length > 8) {- _imageBytes.remove(_imageBytes.keys.first);- }- read.catchError((Object _) {- if (identical(_imageBytes[attachment.id], read)) {- _imageBytes.remove(attachment.id);+ /// The files waiting to go with the next message in a conversation. They+ /// stay in memory: only the text of a draft is saved.+ HarnessAttachments attachments(String id) => _attachments.putIfAbsent(id, () {+ final files = HarnessAttachments(+ limitBytes: kSuperTabAttachmentMaxBytes,+ limitFiles: kSuperTabAttachmentMaxFiles,+ );+ // Taking a chip off while its files go up gives the upload up.+ files.addListener(() {+ if (uploading &&+ _sending?.conversationId == id &&+ !files.files.toSet().containsAll(_sending!.files)) {+ cancelUpload();}- return Uint8List(0);});- return read;- }+ return files;+ });- Future<Uint8List> _readAttachment(SuperTabAttachment attachment) async {- final bytes = BytesBuilder(copy: false);- for (var index = 0; index < attachment.parts; index++) {- final part = await request(- 'GET',- '$_path/attachments/${Uri.encodeComponent(attachment.id)}/parts/$index',- );- bytes.add(base64Decode(part['data'] as String));- }- if (bytes.length != attachment.size) {- throw const FormatException('The image arrived incomplete.');- }- return bytes.takeBytes();- }+ /// Whether [file] is still on its way to the backend in a send.+ bool isUploading(HarnessAttachment file) =>+ uploading && !_uploaded.containsKey(file);- /// Uploads [file] in parts unless it already was, and returns its ID. An- /// interrupted upload resumes with the parts the backend is missing.- Future<String> _upload(SuperTabImages staged, HarnessAttachment file) async {- if (staged.uploadedId(file) case final id?) return id;- final bytes = file.bytes;- final parts = (bytes.length / kSuperTabImagePartBytes).ceil();- String part(int index) => base64Encode(- bytes.sublist(- index * kSuperTabImagePartBytes,- min(bytes.length, (index + 1) * kSuperTabImagePartBytes),- ),- );- var id = staged.startedId(file);- List<int> missing = [for (var index = 1; index < parts; index++) index];- if (id != null) {- try {- final known = await request(- 'GET',- '$_path/attachments/${Uri.encodeComponent(id)}',- );- missing = [- for (final index in known['missing'] as List? ?? const [])- (index as num).toInt(),- ];- } on SuperTabFailure catch (failure) {- if (failure.code != 'NOT_FOUND') rethrow;- staged.forget(file);- id = null;- }- }- if (id == null) {- final created = await request(- 'POST',- '$_path/attachments',- body: {'name': file.name, 'size': bytes.length, 'data': part(0)},- );- id = created['id'] as String;- staged.markStarted(file, id);- }- for (final index in missing) {- if (_disposed) throw const SuperTabFailure('CLOSED', 'Swarm closed.');- await request(- 'POST',- '$_path/attachments/${Uri.encodeComponent(id)}/parts/$index',- body: {'data': part(index)},- );- }- staged.markUploaded(file, id);- return id;- }+ /// How much of [file] has gone up, from 0 to 1, while it is going up.+ double? uploadProgress(HarnessAttachment file) => _progress[file];SuperTabAgent? terminalAgent(String conversationId) {return terminalAgents(conversationId).firstOrNull;@@ -309,10 +250,6 @@ class SuperTabController extends ChangeNotifier {error = message;snapshot = null;_messages.clear();- _imageBytes.clear();- for (final staged in _images.values) {- staged.clear();- }_poll?.cancel();_changed();}@@ -430,10 +367,12 @@ class SuperTabController extends ChangeNotifier {(id) => !next.projects.any((project) => project.id == id),);_messages.removeWhere((id, _) => !allowed.contains(id));- for (final id in _images.keys.where((id) => !allowed.contains(id))) {- _images[id]!.clear();- }_drafts.removeWhere((id, _) => !allowed.contains(id));+ _attachments.removeWhere((id, files) {+ if (allowed.contains(id)) return false;+ files.dispose();+ return true;+ });_terminals.removeWhere((id, _) => !allowed.contains(id));_mentions.removeWhere((id, _) => !allowed.contains(id));_before.removeWhere((id, _) => !allowed.contains(id));@@ -558,6 +497,7 @@ class SuperTabController extends ChangeNotifier {}saving = true;operationError = null;+ operationErrorCode = null;_changed();try {// The receipt ID reaches durable local storage before the request can reach the server.@@ -573,11 +513,14 @@ class SuperTabController extends ChangeNotifier {_drafts.remove(id);_mentions.remove(id);}- final sent = (command['attachmentIds'] as List? ?? const []).toSet();- final staged = _images[id];- if (staged != null && sent.isNotEmpty) {- for (final file in staged.files) {- if (sent.contains(staged.uploadedId(file))) staged.sent(file);+ // Only what went with this message: more may have been added since.+ final sent = command['attachmentIds'];+ if (sent is List) {+ for (final entry in _uploaded.entries.toList()) {+ if (sent.contains(entry.value)) {+ _attachments[id]?.remove(entry.key);+ _uploaded.remove(entry.key);+ }}}}@@ -605,6 +548,7 @@ class SuperTabController extends ChangeNotifier {operationError = failure is SuperTabFailure? failure.message: 'The action is not confirmed. Retry to check it.';+ operationErrorCode = failure is SuperTabFailure ? failure.code : null;if (failure is SuperTabFailure &&failure.statusCode >= 400 &&failure.statusCode < 500 &&@@ -618,13 +562,6 @@ class SuperTabController extends ChangeNotifier {_pending = pending;}}- if (failure is SuperTabFailure &&- failure.code == 'INVALID_ATTACHMENT') {- // An expired or already sent upload: the images still in the- // composer upload again on the next send.- final command = superTabMap(pending['command']);- _images[command['conversationId']]?.forgetUploads();- }if (failure is SuperTabFailure &&const {'FORBIDDEN',@@ -648,18 +585,19 @@ class SuperTabController extends ChangeNotifier {command['type'] == 'member.remove' &&command['userId'] == accountId);- /// Uploads the composer's images first, then sends the text with their- /// IDs. Images alone are a message too.Future<Map<String, dynamic>?> send({String? replyTo,List<String> recipients = const [],}) async {- final conversationId = selectedId;- final text = draft(conversationId).trim();- final staged = images(conversationId);- if ((text.isEmpty && staged.isEmpty) ||+ final text = draft(selectedId).trim();+ final files = attachments(selectedId).files;+ if ((text.isEmpty && files.isEmpty) ||selected == null ||- selected!.archived) {+ selected!.archived ||+ !canWrite ||+ uploading ||+ saving ||+ _pending != null) {return null;}final addressed = recipients.isEmpty@@ -673,36 +611,131 @@ class SuperTabController extends ChangeNotifier {_changed();return null;}- final attachmentIds = <String>[];- if (!staged.isEmpty) {- if (_disposed || !canWrite || saving || _pending != null) return null;- saving = true;- operationError = null;- _changed();- try {- for (final file in staged.files) {- attachmentIds.add(await _upload(staged, file));- }- } catch (failure) {- if (_disposed) return null;- operationError = failure is SuperTabFailure- ? failure.message- : 'Could not upload the image. Try again.';- return null;- } finally {- saving = false;- _changed();- }- if (_disposed) return null;- }- return command({+ final conversationId = selectedId;+ final ids = await _uploadAll(conversationId, files);+ if (ids == null) return null;+ final result = await command({'type': 'message.send','conversationId': conversationId,'text': text,'replyTo': replyTo,'recipientIds': addressed,- if (attachmentIds.isNotEmpty) 'attachmentIds': attachmentIds,+ if (ids.isNotEmpty) 'attachmentIds': ids,});+ // A refusal of the files themselves sends them up once more; one of the+ // message (a mention, a recipient) leaves them uploaded.+ if (result == null &&+ _pending == null &&+ operationErrorCode?.contains('ATTACHMENT') == true) {+ _uploaded.clear();+ }+ return result;+ }++ /// Uploads each of [files] that has not gone up yet and returns their ids,+ /// or null with [operationError] set when one could not. The draft and the+ /// files stay where they are.+ Future<List<String>?> _uploadAll(+ String conversationId,+ List<HarnessAttachment> files,+ ) async {+ if (files.isEmpty) return const [];+ final run = ++_uploadRun;+ uploading = true;+ operationError = null;+ _sending = (conversationId: conversationId, files: files);+ _uploaded.removeWhere((file, _) => !files.contains(file));+ _changed();+ try {+ final ids = <String>[];+ for (final file in files) {+ var id = _uploaded[file];+ if (id == null) {+ final answer = await _uploadFile(conversationId, file);+ if (run != _uploadRun) return null;+ id = superTabMap(answer['attachment'])['id'] as String;+ _uploaded[file] = id;+ }+ ids.add(id);+ }+ return ids;+ } catch (failure) {+ if (!_disposed && run == _uploadRun) {+ operationError = failure is SuperTabFailure+ ? failure.message+ : failure is TimeoutException+ ? 'The upload stopped moving. Try again.'+ : 'Could not upload ${files.length == 1 ? 'the file' : 'the files'}. Try again.';+ operationErrorCode = failure is SuperTabFailure ? failure.code : null;+ }+ return null;+ } finally {+ if (run == _uploadRun) {+ uploading = false;+ _sending = null;+ _progress.clear();+ _changed();+ }+ }+ }++ /// Sends [file] to the backend and returns its attachment. Gives up when no+ /// byte has moved for [uploadTimeout], or when the upload is cancelled.+ Future<Map<String, dynamic>> _uploadFile(+ String conversationId,+ HarnessAttachment file,+ ) async {+ final token = _cancel = CancelToken();+ Timer? watchdog;+ var stalled = false;+ void watch() {+ watchdog?.cancel();+ watchdog = Timer(uploadTimeout, () {+ stalled = true;+ token.cancel('stalled');+ });+ }++ watch();+ try {+ // The token also ends a transport that ignores it.+ return await Future.any([+ upload(+ tabId: tabId,+ conversationId: conversationId,+ name: file.name,+ mime: mimeForName(file.name),+ bytes: file.bytes,+ cancel: token,+ onProgress: (sent) {+ watch();+ _progress[file] = sent;+ _changed();+ },+ ),+ token.whenCancel.then<Map<String, dynamic>>(+ (cancelled) => throw cancelled,+ ),+ ]);+ } on DioException catch (failure) {+ if (stalled && failure.type == DioExceptionType.cancel) {+ throw TimeoutException('The upload stopped moving.');+ }+ rethrow;+ } finally {+ watchdog?.cancel();+ }+ }++ /// Gives up the files on their way, whether they are stalled or not wanted+ /// any more: the composer is free again, and the draft and files stay.+ void cancelUpload() {+ if (!uploading) return;+ _cancel?.cancel('given up');+ _uploadRun++;+ uploading = false;+ _sending = null;+ _changed();}Future<void> flush() async {@@ -715,10 +748,9 @@ class SuperTabController extends ChangeNotifier {_disposed = true;_poll?.cancel();_draftSave?.cancel();- for (final staged in _images.values) {- staged.dispose();+ for (final files in _attachments.values) {+ files.dispose();}- _imageBytes.clear();// The owner awaits flush when changing account or closing the tab.super.dispose();}diff --git a/desktop/lib/super_tabs/message_row.dart b/desktop/lib/super_tabs/message_row.dartindex 7defdddd1..7acdacd15 100644--- a/desktop/lib/super_tabs/message_row.dart+++ b/desktop/lib/super_tabs/message_row.dart@@ -6,7 +6,7 @@ import '../shared/theme/app_theme.dart' as grid;import '../shared/widgets/app_icon_button.dart';import '../widgets/desktop_chrome.dart';import '../widgets/engine_identity.dart';-import 'attachments.dart';+import 'attachment_chips.dart';import 'identity.dart';import 'message_text.dart';import 'model.dart';@@ -29,7 +29,6 @@ class SuperTabMessageRow extends StatefulWidget {this.onOpenAgent,this.references = const {},this.onOpenGroup,- this.loadAttachment,});final SuperTabMessage message;@@ -45,10 +44,6 @@ class SuperTabMessageRow extends StatefulWidget {final VoidCallback onReturnToComposer;final List<Widget> receipts;- /// Reads an attached image's bytes; without it, images are not shown.- final Future<Uint8List> Function(SuperTabAttachment attachment)?- loadAttachment;-// Routing notes share the message body column, including grouped messages.static const horizontalInset = 24.0;static const avatarSize = 28.0;@@ -276,7 +271,7 @@ class _SuperTabMessageRowState extends State<SuperTabMessageRow> {widget.reply?.authorName ??'Earlier message',text:- widget.reply?.preview ??+ widget.reply?.text ??'The original message isn’t loaded.',),),@@ -288,23 +283,25 @@ class _SuperTabMessageRowState extends State<SuperTabMessageRow> {style: DesktopChrome.metadata(),),),- if (message.shownText.isNotEmpty ||- message.attachments.isEmpty)+ if (message.text.isNotEmpty)ConstrainedBox(constraints: const BoxConstraints(maxWidth: 960,),child: SuperTabMessageText(- message.shownText,+ message.text,references: widget.references,onOpenGroup: widget.onOpenGroup,),),- if (message.attachments.isNotEmpty &&- widget.loadAttachment != null)- SuperTabMessageImages(- attachments: message.attachments,- load: widget.loadAttachment!,+ if (message.attachments.isNotEmpty)+ Padding(+ padding: EdgeInsets.only(+ top: message.text.isEmpty ? 0 : 8,+ ),+ child: SuperTabAttachmentChips(+ message.attachments,+ ),),SuperTabPullRequestLinks(message.text),...widget.receipts,diff --git a/desktop/lib/super_tabs/model.dart b/desktop/lib/super_tabs/model.dartindex 3b551a350..9a65c1a93 100644--- a/desktop/lib/super_tabs/model.dart+++ b/desktop/lib/super_tabs/model.dart@@ -221,20 +221,40 @@ class SuperTabRoute {final List<SuperTabRouteChoice> alternatives;}-/// An image sent with a message. A message read never carries its bytes;-/// they are read in [parts] (SuperTabController.attachmentBytes).+/// A file sent with a message. The chat never loads [url] by itself.class SuperTabAttachment {SuperTabAttachment.fromJson(Map<String, dynamic> row): id = _text(row, 'id'),name = _text(row, 'name'),mime = _text(row, 'mime'),size = (row['size'] as num).toInt(),- width = (row['width'] as num?)?.toInt(),- height = (row['height'] as num?)?.toInt(),- parts = (row['parts'] as num).toInt();- final String id, name, mime;- final int size, parts;- final int? width, height;+ url = _text(row, 'url');+ final String id, name, mime, url;+ final int size;++ /// The kinds the backend serves to be seen in place; every other kind is+ /// served as a download.+ bool get isImage => const {+ 'image/png',+ 'image/jpeg',+ 'image/gif',+ 'image/webp',+ }.contains(mime);+}++/// A message's files. A row that does not read is left out, so one bad row+/// cannot hide the page of messages it came in.+List<SuperTabAttachment> _attachments(Object? rows) => List.unmodifiable([+ if (rows is List)+ for (final row in rows) ?_tryAttachment(row),+]);++SuperTabAttachment? _tryAttachment(Object? row) {+ try {+ return SuperTabAttachment.fromJson(superTabMap(row));+ } catch (_) {+ return null;+ }}class SuperTabMessage {@@ -247,41 +267,18 @@ class SuperTabMessage {author = Map.unmodifiable(superTabMap(row['author'])),source = Map.unmodifiable(superTabMap(row['source'] ?? const {})),createdAt = DateTime.tryParse(row['createdAt'] as String? ?? ''),+ attachments = _attachments(row['attachments']),deliveries = _list(row['deliveries'] ?? const [],(d) => Map<String, dynamic>.unmodifiable(d),- ),- attachments = _list(- row['attachments'] ?? const [],- SuperTabAttachment.fromJson,);final String id, conversationId, text;- final List<SuperTabAttachment> attachments;-- /// One line for a quote of it: its text, or what it carries when it is- /// only images.- String get preview => shownText.trim().isNotEmpty || attachments.isEmpty- ? shownText- : attachments.length == 1- ? 'Image'- : '${attachments.length} images';-- /// The text to draw beside its images. A message of images alone is stored- /// with `[image]` or `[N images]` (backend attachments.ts- /// `imagesPlaceholder`) for clients that cannot show them; this one does.- String get shownText =>- attachments.isNotEmpty &&- text ==- (attachments.length == 1- ? '[image]'- : '[${attachments.length} images]')- ? ''- : text;final String? replyTo;final int sequence;final Map<String, dynamic> author;final Map<String, dynamic> source;final DateTime? createdAt;+ final List<SuperTabAttachment> attachments;final List<Map<String, dynamic>> deliveries;String get authorName => author['name'] as String? ?? 'Unknown';String get authorId => author['id'] as String? ?? '';diff --git a/desktop/lib/super_tabs/view.dart b/desktop/lib/super_tabs/view.dartindex 4bfea50f6..c13ce8bcd 100644--- a/desktop/lib/super_tabs/view.dart+++ b/desktop/lib/super_tabs/view.dart@@ -11,7 +11,7 @@ import '../widgets/desktop_chrome.dart';import '../widgets/new_harness_attachments.dart';import '../widgets/new_harness_paste.dart';import '../state/app_state.dart';-import 'attachments.dart';+import '../state/harness_attachments.dart';import 'roster.dart';import 'recording_notice.dart';import 'pull_requests.dart';@@ -222,6 +222,8 @@ class _SuperTabViewState extends State<SuperTabView> {super.dispose();}+ HarnessAttachments get _files => c.attachments(c.selectedId);+Future<void> _send() async {final choices = _completionChoices;if (choices.isNotEmpty) {@@ -232,8 +234,9 @@ class _SuperTabViewState extends State<SuperTabView> {c.selected == null ||c.selected!.archived ||c.saving ||+ c.uploading ||c.hasPendingAction ||- (_composer.text.trim().isEmpty && c.images(c.selectedId).isEmpty)) {+ (_composer.text.trim().isEmpty && _files.isEmpty)) {return;}final id = c.selectedId;@@ -929,7 +932,6 @@ class _SuperTabViewState extends State<SuperTabView> {grouped: grouped,reply: reply,replyAuthor: reply == null ? null : _shownAuthor(c, reply),- loadAttachment: c.attachmentBytes,onReply: c.canWrite && c.selected?.archived == false? () {setState(() => _replies[c.selectedId] = message);@@ -1013,6 +1015,8 @@ class _SuperTabViewState extends State<SuperTabView> {);}final group = c.selected;+ final writable = c.canWrite && group != null && !group.archived;+ final busy = c.saving || c.uploading;final messages = c.messages(c.selectedId);final entries = superTabTranscriptEntries(messages);final byId = {for (final message in messages) message.id: message};@@ -1023,8 +1027,6 @@ class _SuperTabViewState extends State<SuperTabView> {: messages.where((message) => message.sequence > newAfter).length;final reply = _replies[c.selectedId];final choices = _completionChoices;- final images = c.images(c.selectedId);- final writable = c.canWrite && group != null && !group.archived;return Column(children: [if (c.error != null)@@ -1187,7 +1189,7 @@ class _SuperTabViewState extends State<SuperTabView> {Expanded(child: SuperTabReplyPreview(author: 'Replying to ${_authorName(reply)}',- text: reply.preview,+ text: reply.text,),),AppIconButton(@@ -1328,38 +1330,44 @@ class _SuperTabViewState extends State<SuperTabView> {}return KeyEventResult.ignored;},- child: NewHarnessDropZone(- attachments: images,- enabled: writable && !c.saving,- child: DecoratedBox(- key: const ValueKey('super-message-composer-surface'),- decoration: BoxDecoration(- color: DesktopChrome.field,- borderRadius: BorderRadius.circular(- DesktopChrome.controlRadius,- ),- border: Border.all(color: DesktopChrome.rim),+ child: DecoratedBox(+ key: const ValueKey('super-message-composer-surface'),+ decoration: BoxDecoration(+ color: DesktopChrome.field,+ borderRadius: BorderRadius.circular(+ DesktopChrome.controlRadius,),+ border: Border.all(color: DesktopChrome.rim),+ ),+ child: NewHarnessDropZone(+ attachments: _files,+ enabled: writable && !busy,child: GestureDetector(behavior: HitTestBehavior.translucent,- onTap: c.canWrite && group != null && !group.archived- ? _focus.requestFocus- : null,+ onTap: writable ? _focus.requestFocus : null,child: Padding(padding: const EdgeInsets.fromLTRB(16, 8, 8, 8),child: Column(mainAxisSize: MainAxisSize.min,- crossAxisAlignment: CrossAxisAlignment.start,+ crossAxisAlignment: CrossAxisAlignment.stretch,children: [- if (!images.isEmpty)- Padding(- padding: const EdgeInsets.only(bottom: 8, right: 8),- child: NewHarnessAttachmentChips(- key: const ValueKey('super-composer-images'),- attachments: images,- enabled: !c.saving,- ),- ),+ ListenableBuilder(+ listenable: _files,+ builder: (context, _) => _files.isEmpty+ ? const SizedBox.shrink()+ : Padding(+ padding: const EdgeInsets.only(+ bottom: 8,+ right: 8,+ ),+ child: NewHarnessAttachmentChips(+ attachments: _files,+ enabled: !c.saving,+ isUploading: c.isUploading,+ progressOf: c.uploadProgress,+ ),+ ),+ ),ConstrainedBox(constraints: BoxConstraints(minHeight: grid.AppControl.heightFieldScaled,@@ -1369,10 +1377,9 @@ class _SuperTabViewState extends State<SuperTabView> {children: [Expanded(child: NewHarnessPasteTarget(- attachments: images,- enabled: writable && !c.saving,+ attachments: _files,+ enabled: writable && !busy,focusNode: _focus,- readFiles: superTabCopiedImages,child: TextField(key: const ValueKey('super-message-composer',@@ -1380,10 +1387,7 @@ class _SuperTabViewState extends State<SuperTabView> {controller: _composer,focusNode: _focus,autofocus: !_terminalsVisible,- enabled:- c.canWrite &&- group != null &&- !group.archived,+ enabled: writable,minLines: 1,maxLines:MediaQuery.sizeOf(context).height < 600@@ -1425,18 +1429,25 @@ class _SuperTabViewState extends State<SuperTabView> {),),),- ValueListenableBuilder(- valueListenable: _composer,- builder: (context, value, _) => AppIconButton(+ NewHarnessAttachButton(+ attachments: _files,+ enabled: writable && !busy,+ ),+ ListenableBuilder(+ listenable: Listenable.merge([+ _composer,+ _files,+ ]),+ builder: (context, _) => AppIconButton(icon: AppIcons.arrowUp,tooltip: 'Send message',color: DesktopChrome.accent,onPressed:writable &&- !c.saving &&+ !busy &&!c.hasPendingAction &&- (value.text.trim().isNotEmpty ||- !images.isEmpty)+ (_composer.text.trim().isNotEmpty ||+ !_files.isEmpty)? () => unawaited(_send()): null,),diff --git a/desktop/lib/widgets/new_harness_attachment_chip.dart b/desktop/lib/widgets/new_harness_attachment_chip.dartindex 90e726363..ef48dbda7 100644--- a/desktop/lib/widgets/new_harness_attachment_chip.dart+++ b/desktop/lib/widgets/new_harness_attachment_chip.dart@@ -13,17 +13,35 @@ class NewHarnessAttachmentChip extends StatelessWidget {super.key,required this.file,required this.onRemove,+ this.uploading = false,+ this.progress,});final HarnessAttachment file;final VoidCallback? onRemove;+ /// The file is on its way somewhere: a spinner replaces its mark, filling as+ /// [progress] (0 to 1) says, or turning without end while that is unknown.+ final bool uploading;+ final double? progress;+/// The × in a chip stays small beside its file name; it is not a workspace/// close mark ([AppIcons.closeSize]).static const removeIconSize = 12.0;/// A picture shows itself; anything else, the mark of its kind.Widget _mark() {+ if (uploading) {+ return SizedBox.square(+ dimension: 13,+ child: CircularProgressIndicator(+ key: ValueKey('new-harness-attachment-progress:${file.name}'),+ value: progress,+ strokeWidth: 2,+ color: DesktopChrome.accent,+ ),+ );+ }final icon = Icon(fileTypeIcon(file.name),key: ValueKey('new-harness-attachment-icon:${file.name}'),diff --git a/desktop/lib/widgets/new_harness_attachments.dart b/desktop/lib/widgets/new_harness_attachments.dartindex 0c483ba3c..828a4d4d0 100644--- a/desktop/lib/widgets/new_harness_attachments.dart+++ b/desktop/lib/widgets/new_harness_attachments.dart@@ -63,11 +63,19 @@ class NewHarnessAttachmentChips extends StatelessWidget {super.key,required this.attachments,required this.enabled,+ this.isUploading,+ this.progressOf,});final HarnessAttachments attachments;final bool enabled;+ /// Whether a file is on its way somewhere, when files go up as they are sent.+ final bool Function(HarnessAttachment file)? isUploading;++ /// How much of a file has gone up, from 0 to 1, or null while unknown.+ final double? Function(HarnessAttachment file)? progressOf;+@overrideWidget build(BuildContext context) => ListenableBuilder(listenable: attachments,@@ -78,6 +86,8 @@ class NewHarnessAttachmentChips extends StatelessWidget {for (final file in attachments.files)NewHarnessAttachmentChip(file: file,+ uploading: isUploading?.call(file) ?? false,+ progress: progressOf?.call(file),onRemove: enabled ? () => attachments.remove(file) : null,),],diff --git a/desktop/test/super_tab_attachments_test.dart b/desktop/test/super_tab_attachments_test.dartnew file mode 100644index 000000000..7a651eb00--- /dev/null+++ b/desktop/test/super_tab_attachments_test.dart@@ -0,0 +1,698 @@+// Files in a Swarm conversation: the composer takes pasted, dropped and picked+// files and uploads them before the message, and a message shows its files as+// chips that load nothing until clicked.+import 'dart:async';+import 'dart:convert';+import 'dart:io';++import 'package:dio/dio.dart' show CancelToken;+import 'package:file_selector_platform_interface/file_selector_platform_interface.dart';+import 'package:flutter/foundation.dart';+import 'package:flutter/material.dart';+import 'package:flutter/services.dart';+import 'package:flutter_test/flutter_test.dart';+import 'package:harness/core/open_in_browser.dart';+import 'package:harness/super_tabs/attachment_upload.dart';+import 'package:harness/super_tabs/controller.dart';+import 'package:harness/super_tabs/model.dart';+import 'package:harness/super_tabs/view.dart';+import 'package:harness/state/harness_attachments.dart';+import 'package:harness/widgets/new_harness_paste.dart';++import 'support/super_tab_fixture.dart';++/// A real 1×1 PNG, so a chip has something to draw.+final _png = base64Decode(+ 'iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAYAAAAfFcSJAAAADUlEQVR42mNkYPhfDwAChwGA'+ '60e6kgAAAABJRU5ErkJggg==',+);++/// A picked file, which `XFile.fromData` cannot name off the web.+class _Picked extends XFile {+ _Picked(this.name, this.bytes) : super('/picked/$name');++ @override+ final String name;+ final Uint8List bytes;++ @override+ Future<Uint8List> readAsBytes() async => bytes;+}++class _Picker extends FileSelectorPlatform {+ _Picker(this.files);+ final List<XFile> files;++ @override+ Future<List<XFile>> openFiles({+ List<XTypeGroup>? acceptedTypeGroups,+ String? initialDirectory,+ String? confirmButtonText,+ }) async => files;+}++void main() {+ final composer = find.byKey(const ValueKey('super-message-composer'));+ final send = find.byTooltip('Send message');++ Future<void> mount(WidgetTester tester, SuperTabController controller) async {+ await tester.binding.setSurfaceSize(const Size(1100, 800));+ addTearDown(() => tester.binding.setSurfaceSize(null));+ await tester.pumpWidget(+ MaterialApp(+ home: Scaffold(+ body: SuperTabView(+ controller: controller,+ onInvite: () {},+ onAddAgent: (_) {},+ onOpenTerminal: (_) {},+ machineName: (_) => 'Test Mac',+ ),+ ),+ ),+ );+ await tester.pumpAndSettle();+ }++ Future<(ConversationServer, SuperTabController)> open(+ WidgetTester tester,+ ) async {+ final server = ConversationServer();+ final controller = server.controller();+ await controller.refresh();+ await mount(tester, controller);+ return (server, controller);+ }++ /// Takes the view down and settles the draft save before the test ends.+ Future<void> close(WidgetTester tester, SuperTabController c) async {+ await tester.pumpWidget(const SizedBox());+ await c.flush();+ c.dispose();+ }++ List<String> names(SuperTabController c) => [+ for (final file in c.attachments('lead').files) file.name,+ ];++ test('a web page is sent as an unknown kind, never as html', () {+ expect(mimeForName('page.html'), 'application/octet-stream');+ expect(mimeForName('shot.PNG'), 'image/png');+ expect(mimeForName('old.bmp'), 'application/octet-stream');+ });++ test('only the kinds the backend shows in place open as pictures', () {+ SuperTabAttachment of(String mime) => SuperTabAttachment.fromJson({+ 'id': 'a',+ 'name': 'f',+ 'mime': mime,+ 'size': 1,+ 'url': 'https://cdn.harness.autonomous.ai/a/f',+ });+ for (final mime in ['image/png', 'image/jpeg', 'image/gif', 'image/webp']) {+ expect(of(mime).isImage, isTrue, reason: mime);+ }+ for (final mime in ['image/bmp', 'image/svg+xml', 'application/pdf']) {+ expect(of(mime).isImage, isFalse, reason: mime);+ }+ });++ group('adding files', () {+ testWidgets('a pasted picture becomes a chip', (tester) async {+ debugDefaultTargetPlatformOverride = TargetPlatform.macOS;+ final messenger =+ TestDefaultBinaryMessengerBinding.instance.defaultBinaryMessenger;+ messenger.setMockMethodCallHandler(+ const MethodChannel('harness/clipboard_image'),+ (call) async => call.method == 'readImagePng' ? _png : <String>[],+ );+ messenger.setMockMethodCallHandler(SystemChannels.platform, (call) async {+ return switch (call.method) {+ 'Clipboard.getData' => null,+ 'Clipboard.hasStrings' => {'value': false},+ _ => null,+ };+ });+ addTearDown(() {+ messenger.setMockMethodCallHandler(+ const MethodChannel('harness/clipboard_image'),+ null,+ );+ messenger.setMockMethodCallHandler(SystemChannels.platform, null);+ });+ final (_, controller) = await open(tester);++ await tester.tap(composer);+ await tester.sendKeyDownEvent(LogicalKeyboardKey.metaLeft);+ await tester.sendKeyEvent(LogicalKeyboardKey.keyV);+ await tester.sendKeyUpEvent(LogicalKeyboardKey.metaLeft);+ await tester.pumpAndSettle();++ expect(names(controller), [kPastedImageName]);+ expect(+ find.byKey(const ValueKey('new-harness-attachment:$kPastedImageName')),+ findsOneWidget,+ );+ debugDefaultTargetPlatformOverride = null;+ await close(tester, controller);+ });++ testWidgets('a dropped file becomes a chip', (tester) async {+ // One logical pixel per device pixel, so the platform's drop position+ // needs no scaling on any host.+ tester.view.devicePixelRatio = 1;+ addTearDown(tester.view.resetDevicePixelRatio);+ final (_, controller) = await open(tester);+ final file = File('${Directory.systemTemp.path}/swarm-drop-test.log');+ await tester.runAsync(() => file.writeAsString('boom'));+ addTearDown(() => file.deleteSync());+ final inside = tester.getCenter(+ find.byKey(const ValueKey('super-message-composer-surface')),+ );++ Future<void> platform(String method, Object arguments) =>+ TestDefaultBinaryMessengerBinding.instance.defaultBinaryMessenger+ .handlePlatformMessage(+ 'desktop_drop',+ const StandardMethodCodec().encodeMethodCall(+ MethodCall(method, arguments),+ ),+ (_) {},+ );+ await platform('entered', [inside.dx, inside.dy]);+ await tester.pump();+ expect(find.text('Drop files to attach'), findsOneWidget);++ await tester.runAsync(() async {+ await platform('performOperation', [file.path]);+ await Future<void>.delayed(const Duration(milliseconds: 100));+ });+ await tester.pumpAndSettle();++ expect(names(controller), ['swarm-drop-test.log']);+ expect(+ find.byKey(+ const ValueKey('new-harness-attachment:swarm-drop-test.log'),+ ),+ findsOneWidget,+ );+ await close(tester, controller);+ });++ testWidgets('a picked file becomes a chip', (tester) async {+ final original = FileSelectorPlatform.instance;+ FileSelectorPlatform.instance = _Picker([+ _Picked('trace.zip', Uint8List.fromList([1, 2, 3])),+ ]);+ addTearDown(() => FileSelectorPlatform.instance = original);+ final (_, controller) = await open(tester);++ await tester.tap(find.byKey(const ValueKey('new-harness-attach')));+ await tester.pumpAndSettle();++ expect(names(controller), ['trace.zip']);+ await close(tester, controller);+ });++ test('a file over 10 MB, or an eleventh file, is refused', () {+ final controller = ConversationServer().controller();+ addTearDown(controller.dispose);+ final files = controller.attachments('lead');++ expect(+ files.add([+ HarnessAttachment(+ 'big.bin',+ Uint8List(kSuperTabAttachmentMaxBytes + 1),+ ),+ ]),+ 'big.bin is over 10 MB.',+ );+ expect(files.isEmpty, isTrue);++ String? problem;+ for (var i = 0; i <= kSuperTabAttachmentMaxFiles; i++) {+ problem = files.add([+ HarnessAttachment('f$i.txt', Uint8List.fromList([1])),+ ]);+ }+ expect(files.files, hasLength(kSuperTabAttachmentMaxFiles));+ expect(problem, 'Attach at most 10 files.');+ });+ });++ group('sending', () {+ testWidgets('uploads each file, then sends the ids', (tester) async {+ final (server, controller) = await open(tester);+ controller.attachments('lead').add([+ HarnessAttachment('shot.png', _png),+ HarnessAttachment('notes.txt', Uint8List.fromList([104, 105])),+ ]);+ await tester.enterText(composer, 'See these');+ await tester.pump();++ await tester.tap(send);+ await tester.pumpAndSettle();++ expect(+ server.uploads.map((u) => (u['conversationId'], u['name'], u['mime'])),+ [+ ('lead', 'shot.png', 'image/png'),+ ('lead', 'notes.txt', 'text/plain'),+ ],+ );+ expect(server.uploads.first['file'], _png);+ expect(server.uploads.last['file'], [104, 105]);+ expect(server.posts, hasLength(1));+ final command = server.posts.single['command'] as Map;+ expect(command['type'], 'message.send');+ expect(command['text'], 'See these');+ expect(command['attachmentIds'], ['attachment-1', 'attachment-2']);+ expect(controller.attachments('lead').isEmpty, isTrue);+ expect(+ find.byKey(const ValueKey('super-attachment:attachment-1')),+ findsOneWidget,+ );+ await close(tester, controller);+ });++ testWidgets('a file alone can be sent without text', (tester) async {+ final (server, controller) = await open(tester);+ controller.attachments('lead').add([HarnessAttachment('a.png', _png)]);+ await tester.pump();++ await tester.tap(send);+ await tester.pumpAndSettle();++ final command = server.posts.single['command'] as Map;+ expect(command['text'], '');+ expect(command['attachmentIds'], hasLength(1));+ await close(tester, controller);+ });++ testWidgets('a failed upload keeps the draft and the files, and a retry '+ 'sends only the file that did not go up', (tester) async {+ final (server, controller) = await open(tester);+ server.failUpload = 'two.png';+ controller.attachments('lead').add([+ HarnessAttachment('one.png', _png),+ HarnessAttachment('two.png', Uint8List.fromList([..._png, 0])),+ ]);+ await tester.enterText(composer, 'Look');+ await tester.pump();++ await tester.tap(send);+ await tester.pumpAndSettle();++ expect(server.posts, isEmpty);+ expect(controller.draft('lead'), 'Look');+ expect(names(controller), ['one.png', 'two.png']);+ expect(controller.operationError, 'The file is too large.');+ expect(find.text('The file is too large.'), findsOneWidget);+ expect(controller.uploading, isFalse);++ server.failUpload = null;+ await tester.tap(send);+ await tester.pumpAndSettle();++ expect(server.uploads.map((u) => u['name']), ['one.png', 'two.png']);+ final command = server.posts.single['command'] as Map;+ expect(command['attachmentIds'], ['attachment-1', 'attachment-2']);+ expect(controller.attachments('lead').isEmpty, isTrue);+ await close(tester, controller);+ });++ testWidgets('a chip fills as its file goes up', (tester) async {+ final server = ConversationServer();+ final release = Completer<void>();+ final controller = server.controller(+ upload:+ ({+ required tabId,+ required conversationId,+ required name,+ required mime,+ required bytes,+ required cancel,+ required onProgress,+ }) async {+ onProgress(.25);+ await release.future;+ return server.upload(+ tabId: tabId,+ conversationId: conversationId,+ name: name,+ mime: mime,+ bytes: bytes,+ cancel: cancel,+ onProgress: onProgress,+ );+ },+ );+ await controller.refresh();+ await mount(tester, controller);+ controller.attachments('lead').add([HarnessAttachment('a.png', _png)]);+ await tester.pump();+ final spinner = find.byKey(+ const ValueKey('new-harness-attachment-progress:a.png'),+ );++ await tester.tap(send);+ await tester.pump();+ await tester.pump();+ expect(spinner, findsOneWidget);+ expect(tester.widget<CircularProgressIndicator>(spinner).value, .25);++ release.complete();+ await tester.pumpAndSettle();+ expect(spinner, findsNothing);+ await close(tester, controller);+ });++ testWidgets(+ 'an upload that stops moving times out and frees the composer',+ (tester) async {+ final server = ConversationServer();+ CancelToken? token;+ final controller = SuperTabController(+ tabId: 'tab',+ accountId: 'owner',+ request: server.request,+ save: server.save,+ pollInterval: Duration.zero,+ uploadTimeout: const Duration(seconds: 5),+ upload:+ ({+ required tabId,+ required conversationId,+ required name,+ required mime,+ required bytes,+ required cancel,+ required onProgress,+ }) {+ token = cancel;+ onProgress(.1);+ return Completer<Map<String, dynamic>>().future;+ },+ );+ await controller.refresh();+ await mount(tester, controller);+ controller.attachments('lead').add([HarnessAttachment('a.png', _png)]);+ await tester.pump();++ await tester.tap(send);+ await tester.pump(const Duration(seconds: 6));+ await tester.pumpAndSettle();++ expect(token?.isCancelled, isTrue);+ expect(controller.uploading, isFalse);+ expect(+ controller.operationError,+ 'The upload stopped moving. Try again.',+ );+ expect(names(controller), ['a.png']);+ await close(tester, controller);+ },+ );++ testWidgets('taking a chip off cancels the upload and frees the composer', (+ tester,+ ) async {+ final server = ConversationServer();+ CancelToken? token;+ final controller = SuperTabController(+ tabId: 'tab',+ accountId: 'owner',+ request: server.request,+ save: server.save,+ pollInterval: Duration.zero,+ upload:+ ({+ required tabId,+ required conversationId,+ required name,+ required mime,+ required bytes,+ required cancel,+ required onProgress,+ }) {+ token = cancel;+ return Completer<Map<String, dynamic>>().future;+ },+ );+ await controller.refresh();+ await mount(tester, controller);+ controller.attachments('lead').add([+ HarnessAttachment('a.png', _png),+ HarnessAttachment('b.png', Uint8List.fromList([..._png, 1])),+ ]);+ await tester.pump();++ await tester.tap(send);+ await tester.pump();+ expect(controller.uploading, isTrue);++ await tester.tap(find.byTooltip('Remove a.png'));+ await tester.pumpAndSettle();++ expect(token?.isCancelled, isTrue);+ expect(controller.uploading, isFalse);+ expect(controller.operationError, isNull);+ expect(names(controller), ['b.png']);+ expect(server.posts, isEmpty);+ await close(tester, controller);+ });++ test('only the files that were sent leave the composer', () async {+ final server = ConversationServer();+ final held = Completer<void>();+ final controller = SuperTabController(+ tabId: 'tab',+ accountId: 'owner',+ request: (method, path, {body}) async {+ if (method == 'POST' &&+ (body?['command'] as Map?)?['type'] == 'message.send') {+ await held.future;+ }+ return server.request(method, path, body: body);+ },+ save: server.save,+ upload: server.upload,+ pollInterval: Duration.zero,+ );+ await controller.refresh();+ final first = HarnessAttachment('one.png', _png);+ final later = HarnessAttachment('two.png', Uint8List.fromList([1, 2]));+ controller.attachments('lead').add([first]);+ controller.setDraft('lead', 'Here');++ final sending = controller.send();+ await Future<void>.delayed(const Duration(milliseconds: 50));+ controller.attachments('lead').add([later]);+ held.complete();+ await sending;++ expect(names(controller), ['two.png']);+ controller.dispose();+ });++ test(+ 'a refused message re-uploads only after an attachment refusal',+ () async {+ for (final (code, reuploads) in [+ ('INVALID_RECIPIENT', false),+ ('INVALID_ATTACHMENT', true),+ ]) {+ final server = ConversationServer();+ final controller = SuperTabController(+ tabId: 'tab',+ accountId: 'owner',+ request: (method, path, {body}) {+ if (method == 'POST' &&+ (body?['command'] as Map?)?['type'] == 'message.send') {+ throw SuperTabFailure(code, 'Refused.', statusCode: 400);+ }+ return server.request(method, path, body: body);+ },+ save: server.save,+ upload: server.upload,+ pollInterval: Duration.zero,+ );+ await controller.refresh();+ controller.attachments('lead').add([+ HarnessAttachment('a.png', _png),+ ]);+ await controller.send();+ await controller.send();++ expect(server.uploads, hasLength(reuploads ? 2 : 1), reason: code);+ controller.dispose();+ }+ },+ );+ });++ group('messages', () {+ testWidgets('show chips and load nothing until a click', (tester) async {+ final server = ConversationServer()+ ..append(+ 'Here',+ attachments: [+ {+ 'id': 'a1',+ 'name': 'shot.png',+ 'mime': 'image/png',+ 'size': 2048,+ 'url': 'https://cdn.harness.autonomous.ai/a1/shot.png',+ },+ {+ 'id': 'a2',+ 'name': 'report.pdf',+ 'mime': 'application/pdf',+ 'size': 3 * 1024 * 1024,+ 'url': 'https://cdn.harness.autonomous.ai/a2/report.pdf',+ },+ ],+ );+ final controller = server.controller();+ await controller.refresh();+ await mount(tester, controller);+ final opened = <Uri>[];+ final original = browserOpener;+ browserOpener = (url) async {+ opened.add(url);+ return true;+ };+ addTearDown(() => browserOpener = original);++ expect(find.text('shot.png'), findsOneWidget);+ expect(find.text('2 KB'), findsOneWidget);+ expect(find.text('report.pdf'), findsOneWidget);+ expect(find.text('3.0 MB'), findsOneWidget);+ expect(find.byType(Image), findsNothing);++ await tester.tap(find.byKey(const ValueKey('super-attachment:a1')));+ await tester.pumpAndSettle();+ expect(+ find.byKey(const ValueKey('super-attachment-image:a1')),+ findsOneWidget,+ );+ expect(opened, isEmpty);+ await tester.tap(find.text('Close'));+ await tester.pumpAndSettle();++ await tester.tap(find.byKey(const ValueKey('super-attachment:a2')));+ await tester.pumpAndSettle();+ expect(opened, [+ Uri.parse('https://cdn.harness.autonomous.ai/a2/report.pdf'),+ ]);+ await close(tester, controller);+ });++ testWidgets('a message of files alone has no empty text block', (+ tester,+ ) async {+ final server = ConversationServer()+ ..append(+ '',+ attachments: [+ {+ 'id': 'a1',+ 'name': 'log.txt',+ 'mime': 'text/plain',+ 'size': 10,+ 'url': 'https://cdn.harness.autonomous.ai/a1/log.txt',+ },+ ],+ );+ final controller = server.controller();+ await controller.refresh();+ await mount(tester, controller);++ expect(find.text('log.txt'), findsOneWidget);+ expect(tester.takeException(), isNull);+ await close(tester, controller);+ });++ testWidgets('a link off the attachments host opens nothing and says why', (+ tester,+ ) async {+ final server = ConversationServer()+ ..append(+ 'Here',+ attachments: [+ {+ 'id': 'a1',+ 'name': 'evil.pdf',+ 'mime': 'application/pdf',+ 'size': 10,+ 'url': 'https://evil.example/a1/evil.pdf',+ },+ {+ 'id': 'a2',+ 'name': 'plain.pdf',+ 'mime': 'application/pdf',+ 'size': 10,+ 'url': 'http://cdn.harness.autonomous.ai/a2/plain.pdf',+ },+ ],+ );+ final controller = server.controller();+ await controller.refresh();+ await mount(tester, controller);+ final opened = <Uri>[];+ final original = browserOpener;+ browserOpener = (url) async {+ opened.add(url);+ return true;+ };+ addTearDown(() => browserOpener = original);++ const why =+ 'This file isn’t on Harness’s file storage, so it wasn’t opened.';+ await tester.tap(find.byKey(const ValueKey('super-attachment:a1')));+ await tester.pump();+ expect(find.text(why), findsOneWidget);++ // An http link on the right host is refused too.+ ScaffoldMessenger.of(+ tester.element(find.byKey(const ValueKey('super-attachment:a1'))),+ ).clearSnackBars();+ await tester.pumpAndSettle();+ await tester.tap(find.byKey(const ValueKey('super-attachment:a2')));+ await tester.pump();+ expect(find.text(why), findsOneWidget);+ expect(opened, isEmpty);+ await close(tester, controller);+ });++ testWidgets('a malformed attachment row is left out, not the page', (+ tester,+ ) async {+ final server = ConversationServer()+ ..append(+ 'Two files, one broken',+ attachments: [+ {'id': 'bad', 'name': 'no-size.txt'},+ {+ 'id': 'good',+ 'name': 'ok.txt',+ 'mime': 'text/plain',+ 'size': 10,+ 'url': 'https://cdn.harness.autonomous.ai/good/ok.txt',+ },+ ],+ )+ ..append('Next message');+ final controller = server.controller();+ await controller.refresh();+ await mount(tester, controller);++ expect(find.text('ok.txt'), findsOneWidget);+ expect(find.text('no-size.txt'), findsNothing);+ expect(find.text('Next message'), findsOneWidget);+ await close(tester, controller);+ });+ });+}diff --git a/desktop/test/super_tab_images_test.dart b/desktop/test/super_tab_images_test.dartdeleted file mode 100644index f34d6e20a..000000000--- a/desktop/test/super_tab_images_test.dart+++ /dev/null@@ -1,304 +0,0 @@-// Images in a Swarm conversation: pasted or dropped into the composer,-// uploaded in parts before the message, and shown as thumbnails.-import 'dart:convert';-import 'dart:io';--import 'package:flutter/foundation.dart';-import 'package:flutter/material.dart';-import 'package:flutter/services.dart';-import 'package:flutter_test/flutter_test.dart';-import 'package:harness/state/harness_attachments.dart';-import 'package:harness/super_tabs/attachments.dart';-import 'package:harness/super_tabs/view.dart';--import 'support/super_tab_fixture.dart';--/// A real 1×1 PNG, so a thumbnail has something to draw.-final _png = base64Decode(- 'iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAYAAAAfFcSJAAAADUlEQVR42mNkYPhfDwAChwGA'- '60e6kgAAAABJRU5ErkJggg==',-);--/// A PNG header followed by enough bytes to need two parts.-Uint8List _large() =>- Uint8List(kSuperTabImagePartBytes + 10)..setRange(0, _png.length, _png);--void main() {- test('only PNG, JPEG and WebP images, four at most and 5 MB each', () {- final images = SuperTabImages();- addTearDown(images.dispose);- expect(- images.add([- HarnessAttachment(- 'notes.pdf',- Uint8List.fromList('%PDF-1.7'.codeUnits),- ),- HarnessAttachment('cat.gif', Uint8List.fromList('GIF89a'.codeUnits)),- ]),- '2 files are not PNG, JPEG or WebP images.',- );- expect(- images.add([- HarnessAttachment(- 'huge.png',- Uint8List(kSuperTabImageMaxBytes + 1)..setRange(0, 8, _png),- ),- ]),- 'huge.png is over 5 MB.',- );- final jpeg = Uint8List.fromList([0xFF, 0xD8, 0xFF, 0xE0]);- final webp = Uint8List.fromList([- ...'RIFF'.codeUnits,- 0,- 0,- 0,- 0,- ...'WEBP'.codeUnits,- ]);- expect(- images.addPasted([- for (var i = 0; i < 3; i++) HarnessAttachment('shot.png', _png),- HarnessAttachment('photo.jpg', jpeg),- HarnessAttachment('art.webp', webp),- ]),- 'A message can carry up to 4 images.',- );- expect(images.files.map((f) => f.name), [- 'shot.png',- 'shot-2.png',- 'shot-3.png',- 'photo.jpg',- ]);- });-- test('images upload in parts before an image-only send, and only their IDs are saved', () async {- final server = ConversationServer();- final c = server.controller();- addTearDown(c.dispose);- await c.refresh();- final large = _large();- c.images('lead').add([HarnessAttachment('shot.png', large)]);- final sent = await c.send();- expect(sent, isNotNull);- expect(server.uploads, hasLength(2));- expect(server.uploads.first, {- 'name': 'shot.png',- 'size': large.length,- 'data': base64Encode(large.sublist(0, kSuperTabImagePartBytes)),- });- final command = server.posts.single['command'] as Map;- expect(command['text'], '');- expect(command['attachmentIds'], ['image-1']);- expect(c.images('lead').isEmpty, isTrue);- expect(- jsonEncode(server.saved),- isNot(contains(server.uploads.last['data'])),- );-- final message = c.messages('lead').single;- expect(message.text, '[image]');- expect(message.shownText, '');- expect(message.preview, 'Image');- final attachment = message.attachments.single;- expect(attachment.parts, 2);- expect(await c.attachmentBytes(attachment), large);- });-- test(- 'a failed upload sends nothing and keeps the images for a retry',- () async {- final server = ConversationServer()..failUploads = true;- final c = server.controller();- addTearDown(c.dispose);- await c.refresh();- c.setDraft('lead', 'See the screenshot');- c.images('lead').add([HarnessAttachment('shot.png', _png)]);- expect(await c.send(), isNull);- expect(server.posts, isEmpty);- expect(c.operationError, 'Could not upload the image. Try again.');- expect(c.images('lead').files, hasLength(1));- server.failUploads = false;- expect(await c.send(), isNotNull);- expect(- (server.posts.single['command'] as Map)['text'],- 'See the screenshot',- );- expect(c.images('lead').isEmpty, isTrue);- },- );-- test('an interrupted upload resumes with its missing parts', () async {- final server = ConversationServer()..failUploadAt = 2;- final c = server.controller();- addTearDown(c.dispose);- await c.refresh();- final large = Uint8List(2 * kSuperTabImagePartBytes + 3)- ..setRange(0, _png.length, _png);- c.images('lead').add([HarnessAttachment('shot.png', large)]);- expect(await c.send(), isNull);- expect(await c.send(), isNotNull);- expect(server.uploads.where((u) => u.containsKey('name')), hasLength(1));- expect(server.uploads, hasLength(4));- expect(- await c.attachmentBytes(c.messages('lead').single.attachments.single),- large,- );- });-- test('a removed or replaced image is deleted from the backend', () async {- final server = ConversationServer()..failUploadAt = 2;- final c = server.controller();- addTearDown(c.dispose);- await c.refresh();- final images = c.images('lead');- images.add([HarnessAttachment('shot.png', _large())]);- expect(await c.send(), isNull);- images.add([HarnessAttachment('shot.png', _png)]);- await pumpEventQueue();- expect(server.deletedAttachments, ['image-1']);- images.add([HarnessAttachment('two.png', _large())]);- server.failUploadAt = 5;- expect(await c.send(), isNull);- expect(server.attachments.keys, ['image-2', 'image-3']);- images.remove(images.files.last);- await pumpEventQueue();- expect(server.deletedAttachments, ['image-1', 'image-3']);- });-- testWidgets('a copied file that is not an image pastes its name as text', (- tester,- ) async {- final dir = Directory.systemTemp.createTempSync('swarm-paste-');- addTearDown(() => dir.deleteSync(recursive: true));- final notes = File('${dir.path}/notes.txt')..writeAsStringSync('hello');- debugDefaultTargetPlatformOverride = TargetPlatform.macOS;- final messenger =- TestDefaultBinaryMessengerBinding.instance.defaultBinaryMessenger;- messenger.setMockMethodCallHandler(SystemChannels.platform, (call) async {- return switch (call.method) {- 'Clipboard.getData' => {'text': 'notes.txt'},- 'Clipboard.hasStrings' => {'value': true},- _ => null,- };- });- const clipboard = MethodChannel('harness/clipboard_image');- messenger.setMockMethodCallHandler(clipboard, (call) async {- return switch (call.method) {- 'readImagePng' => _png,- 'readFilePaths' => [notes.path],- _ => null,- };- });- addTearDown(() {- messenger.setMockMethodCallHandler(SystemChannels.platform, null);- messenger.setMockMethodCallHandler(clipboard, null);- });- await tester.binding.setSurfaceSize(const Size(1100, 720));- addTearDown(() => tester.binding.setSurfaceSize(null));- final server = ConversationServer();- final c = server.controller();- await tester.runAsync(c.refresh);- await tester.pumpWidget(- MaterialApp(- home: Scaffold(- body: SuperTabView(- controller: c,- onInvite: () {},- onAddAgent: (_) {},- onOpenTerminal: (_) {},- machineName: (_) => 'Team Mac',- ),- ),- ),- );- await tester.pumpAndSettle();- await tester.tap(find.byKey(const ValueKey('super-message-composer')));- await tester.runAsync(() async {- await tester.sendKeyDownEvent(LogicalKeyboardKey.metaLeft);- await tester.sendKeyEvent(LogicalKeyboardKey.keyV);- await tester.sendKeyUpEvent(LogicalKeyboardKey.metaLeft);- await Future<void>.delayed(const Duration(milliseconds: 100));- });- await tester.pumpAndSettle();- expect(find.byKey(const ValueKey('super-composer-images')), findsNothing);- expect(- tester- .widget<TextField>(- find.byKey(const ValueKey('super-message-composer')),- )- .controller!- .text,- 'notes.txt',- );- await tester.pumpWidget(const SizedBox());- c.dispose();- debugDefaultTargetPlatformOverride = null;- });-- testWidgets('a pasted screenshot is a chip until sent, then a thumbnail', (- tester,- ) async {- debugDefaultTargetPlatformOverride = TargetPlatform.macOS;- final messenger =- TestDefaultBinaryMessengerBinding.instance.defaultBinaryMessenger;- messenger.setMockMethodCallHandler(SystemChannels.platform, (call) async {- return call.method == 'Clipboard.hasStrings' ? {'value': false} : null;- });- const clipboard = MethodChannel('harness/clipboard_image');- messenger.setMockMethodCallHandler(clipboard, (call) async {- return switch (call.method) {- 'readImagePng' => _png,- 'readFilePaths' => <String>[],- _ => null,- };- });- addTearDown(() {- messenger.setMockMethodCallHandler(SystemChannels.platform, null);- messenger.setMockMethodCallHandler(clipboard, null);- });- await tester.binding.setSurfaceSize(const Size(1100, 720));- addTearDown(() => tester.binding.setSurfaceSize(null));- final server = ConversationServer();- final c = server.controller();- await tester.runAsync(c.refresh);- await tester.pumpWidget(- MaterialApp(- home: Scaffold(- body: SuperTabView(- controller: c,- onInvite: () {},- onAddAgent: (_) {},- onOpenTerminal: (_) {},- machineName: (_) => 'Team Mac',- ),- ),- ),- );- await tester.pumpAndSettle();- await tester.tap(find.byKey(const ValueKey('super-message-composer')));- await tester.sendKeyDownEvent(LogicalKeyboardKey.metaLeft);- await tester.sendKeyEvent(LogicalKeyboardKey.keyV);- await tester.sendKeyUpEvent(LogicalKeyboardKey.metaLeft);- await tester.pumpAndSettle();- expect(find.byKey(const ValueKey('super-composer-images')), findsOneWidget);- expect(- find.byKey(const ValueKey('new-harness-attachment:pasted-image.png')),- findsOneWidget,- );-- await tester.tap(find.byTooltip('Send message'));- await tester.pumpAndSettle();- expect(find.byKey(const ValueKey('super-composer-images')), findsNothing);- expect((server.posts.single['command'] as Map)['attachmentIds'], [- 'image-1',- ]);- await tester.pumpAndSettle();- expect(- find.byKey(const ValueKey('super-message-image:image-1')),- findsOneWidget,- );- await tester.pumpWidget(const SizedBox());- c.dispose();- debugDefaultTargetPlatformOverride = null;- });-}diff --git a/desktop/test/super_tab_upload_test.dart b/desktop/test/super_tab_upload_test.dartnew file mode 100644index 000000000..09716fc40--- /dev/null+++ b/desktop/test/super_tab_upload_test.dart@@ -0,0 +1,258 @@+// The upload of a file to the backend's attachments route, against a real+// loopback server standing in for it. Its own file, with no `testWidgets`: under+// the widget binding every HttpClient answers 400 without touching the network.+import 'dart:convert';+import 'dart:io';+import 'dart:typed_data';++import 'package:dio/dio.dart';+import 'package:flutter_test/flutter_test.dart';+import 'package:harness/api/api_client.dart';+import 'package:harness/api/access_token_source.dart';+import 'package:harness/auth/auth_session.dart';+import 'package:harness/core/config.dart';+import 'package:harness/super_tabs/attachment_upload.dart';+import 'package:harness/super_tabs/controller.dart';++void main() {+ late HttpServer server;+ late SuperTabUpload upload;+ final seen =+ <+ ({+ String method,+ String path,+ String? type,+ String? local,+ String? bearer,+ String body,+ })+ >[];+ var reply = (200, <String, Object?>{});+ // Answers a request, given the one before it; null keeps `reply`.+ (int, Map<String, Object?>)? Function(String? bearer)? answer;++ setUp(() async {+ seen.clear();+ answer = null;+ server = await HttpServer.bind(InternetAddress.loopbackIPv4, 0);+ server.listen((request) async {+ final bytes = BytesBuilder();+ await for (final chunk in request) {+ bytes.add(chunk);+ }+ seen.add((+ method: request.method,+ path: request.uri.path,+ type: request.headers.contentType?.mimeType,+ local: request.headers.value('x-adapter-local'),+ bearer: request.headers.value('authorization'),+ body: latin1.decode(bytes.takeBytes()),+ ));+ // Like the daemon, which refuses a request that lacks its header.+ final chosen = request.headers.value('authorization') != null+ ? answer?.call(request.headers.value('authorization'))+ : request.headers.value('x-adapter-local') == null+ ? (403, <String, Object?>{'error': 'FORBIDDEN'})+ : null;+ final (status, payload) = chosen ?? reply;+ request.response+ ..statusCode = status+ ..headers.contentType = ContentType.json+ ..write(jsonEncode(payload));+ await request.response.close();+ });+ upload = uploadWith(+ () => ApiClient(+ config: AppConfig(+ apiBaseUrl: 'http://unused.invalid',+ localCliBaseUrl: 'http://127.0.0.1:${server.port}',+ ),+ session: AuthSession(),+ ),+ );+ });+ tearDown(() => server.close(force: true));++ Future<Map<String, dynamic>> send({void Function(double)? onProgress}) =>+ upload(+ tabId: 'tab 1',+ conversationId: 'lead',+ name: 'shot.png',+ mime: 'image/png',+ bytes: Uint8List.fromList(List.filled(2000, 7)),+ cancel: CancelToken(),+ onProgress: onProgress ?? (_) {},+ );++ test(+ 'posts the conversation, then the file, as one multipart form',+ () async {+ reply = (+ 200,+ {+ 'success': true,+ 'data': {+ 'attachment': {+ 'id': 'a1',+ 'name': 'shot.png',+ 'mime': 'image/png',+ 'size': 2000,+ 'url': 'https://cdn.harness.autonomous.ai/k/shot.png',+ },+ },+ },+ );+ final progress = <double>[];++ final answer = await send(onProgress: progress.add);++ expect((answer['attachment'] as Map)['id'], 'a1');+ final request = seen.single;+ expect(request.method, 'POST');+ expect(request.path, '/api/super-tabs/tab%201/attachments');+ expect(request.type, 'multipart/form-data');+ final conversation = request.body.indexOf('name="conversationId"');+ final file = request.body.indexOf('name="file"');+ expect(conversation, greaterThan(-1));+ expect(file, greaterThan(conversation));+ expect(request.body, contains('filename="shot.png"'));+ expect(request.body, contains('content-type: image/png'));+ expect(progress, isNotEmpty);+ expect(progress.last, 1);+ },+ );++ test('a refusal carries the backend\'s code, message and status', () async {+ reply = (+ 413,+ {+ 'success': false,+ 'error': {+ 'code': 'ATTACHMENT_TOO_LARGE',+ 'message': 'Files can be at most 10 MB.',+ },+ },+ );++ await expectLater(+ send(),+ throwsA(+ isA<SuperTabFailure>()+ .having((f) => f.code, 'code', 'ATTACHMENT_TOO_LARGE')+ .having((f) => f.message, 'message', 'Files can be at most 10 MB.')+ .having((f) => f.statusCode, 'status', 413),+ ),+ );+ });++ test('an answer without a body still reads as a refusal', () async {+ reply = (503, <String, Object?>{});++ await expectLater(+ send(),+ throwsA(+ isA<SuperTabFailure>()+ .having((f) => f.code, 'code', 'UPLOAD_FAILED')+ .having((f) => f.statusCode, 'status', 503),+ ),+ );+ });++ test('on a computer the daemon\'s header goes with it, and a 403 reads '+ 'plainly', () async {+ reply = (403, {'error': 'FORBIDDEN'});++ await expectLater(+ send(),+ throwsA(+ isA<SuperTabFailure>()+ .having((f) => f.code, 'code', 'FORBIDDEN')+ .having(+ (f) => f.message,+ 'message',+ 'You can’t send files in this conversation.',+ )+ .having((f) => f.statusCode, 'status', 403),+ ),+ );+ expect(seen.single.local, '1');+ });++ group('from a browser, straight to the backend', () {+ late AccessTokenSource tokens;+ final refreshes = <bool>[];++ setUp(() {+ refreshes.clear();+ tokens = _Tokens(refreshes);+ upload = uploadWith(+ () => ApiClient(+ config: AppConfig(+ apiBaseUrl: 'http://127.0.0.1:${server.port}',+ localCliBaseUrl: 'http://127.0.0.1:1',+ ),+ session: AuthSession(),+ auth: tokens,+ ),+ );+ });++ test('sends the bearer and not the daemon\'s header', () async {+ reply = (+ 200,+ {+ 'success': true,+ 'data': {'attachment': <String, Object?>{}},+ },+ );++ await send();++ expect(seen.single.bearer, 'Bearer old');+ expect(seen.single.local, isNull);+ });++ test(+ 'a token that expired is renewed and the file goes again, whole',+ () async {+ reply = (+ 200,+ {+ 'success': true,+ 'data': {+ 'attachment': {'id': 'a1'},+ },+ },+ );+ answer = (bearer) =>+ bearer == 'Bearer old' ? (401, <String, Object?>{}) : null;++ final result = await send();++ expect((result['attachment'] as Map)['id'], 'a1');+ expect(seen.map((r) => r.bearer), ['Bearer old', 'Bearer new']);+ expect(refreshes, [true]);+ // The second try carried the same form, file and all.+ expect(seen.last.body, contains('filename="shot.png"'));+ expect(seen.last.body.length, seen.first.body.length);+ },+ );+ });+}++/// Tokens that go stale: the first is refused, a forced renewal gives a new one.+class _Tokens implements AccessTokenSource {+ _Tokens(this.refreshes);+ final List<bool> refreshes;+ var _renewed = false;++ @override+ Future<String> accessToken({bool force = false, String? failedToken}) async {+ if (force) {+ refreshes.add(true);+ _renewed = true;+ }+ return _renewed ? 'new' : 'old';+ }+}diff --git a/desktop/test/support/super_tab_fixture.dart b/desktop/test/support/super_tab_fixture.dartindex 8bed9b01f..d642d80a4 100644--- a/desktop/test/support/super_tab_fixture.dart+++ b/desktop/test/support/super_tab_fixture.dart@@ -1,5 +1,8 @@import 'dart:convert';+import 'dart:typed_data';+import 'package:dio/dio.dart' show CancelToken;+import 'package:harness/super_tabs/attachment_upload.dart';import 'package:harness/super_tabs/controller.dart';Map<String, dynamic> conversationFixture(String id, String title) => {@@ -42,16 +45,6 @@ class ConversationServer {final routeDecisions = <String, Map<String, dynamic>>{};// The effective routing policy answered by GET .../routing-policy.Map<String, dynamic>? routingPolicy;- // Uploaded images by id: their metadata and base64 parts in order.- final attachments = <String, Map<String, dynamic>>{};- final attachmentParts = <String, List<String?>>{};- // Every attachment upload body, apart from [posts].- final uploads = <Map<String, dynamic>>[];- // Unsent uploads the client deleted.- final deletedAttachments = <String>[];- bool failUploads = false;- // Fails the upload request with this 1-based number, once.- int? failUploadAt;final state = <String, dynamic>{'version': 1,'id': 'tab',@@ -68,18 +61,28 @@ class ConversationServer {conversationFixture('offline', 'Offline editing'),],};+ // The files fully uploaded, in order, bytes included.+ final uploads = <Map<String, dynamic>>[];+ // Makes the upload of the file with this name fail with failUploadCode.+ String? failUpload;+ String failUploadCode = 'ATTACHMENT_TOO_LARGE';Future<void> save(Map<String, dynamic> value) async {if (failSave) throw StateError('Disk full');saved = jsonDecode(jsonEncode(value)) as Map<String, dynamic>;}- void append(String text, {String conversationId = 'lead'}) {+ void append(+ String text, {+ String conversationId = 'lead',+ List<Map<String, dynamic>> attachments = const [],+ }) {revision++;messages.add({'id': 'message-$revision','conversationId': conversationId,'sequence': revision,'text': text,+ 'attachments': attachments,'createdAt': '2026-10-18T00:00:00Z','author': {'kind': 'person', 'id': 'owner', 'name': '[email protected]'},'deliveries': <dynamic>[],@@ -89,15 +92,52 @@ class ConversationServer {)['lastMessageSequence'] = revision;}+ /// What the backend does with a file sent to its upload route.+ Future<Map<String, dynamic>> upload({+ required String tabId,+ required String conversationId,+ required String name,+ required String mime,+ required Uint8List bytes,+ required CancelToken cancel,+ required void Function(double sent) onProgress,+ }) async {+ if (name == failUpload) {+ throw SuperTabFailure(+ failUploadCode,+ 'The file is too large.',+ statusCode: 413,+ );+ }+ onProgress(.5);+ final id = 'attachment-${uploads.length + 1}';+ uploads.add({+ 'conversationId': conversationId,+ 'name': name,+ 'mime': mime,+ 'file': bytes,+ 'id': id,+ });+ onProgress(1);+ return {'attachment': _attachment(id)};+ }++ Map<String, dynamic> _attachment(String id) {+ final upload = uploads.firstWhere((u) => u['id'] == id);+ return {+ 'id': id,+ 'name': upload['name'],+ 'mime': upload['mime'],+ 'size': (upload['file'] as List).length,+ 'url': 'https://cdn.harness.autonomous.ai/$id/${upload['name']}',+ };+ }+Future<Map<String, dynamic>> request(String method,String path, {Map<String, dynamic>? body,}) async {- final segments = Uri.parse(path).pathSegments;- if (segments.length > 3 && segments[3] == 'attachments') {- return _attachment(method, segments, body);- }if (method == 'POST') {posts.add(Map<String, dynamic>.from(body!));if (reject) {@@ -119,19 +159,15 @@ class ConversationServer {final command = body['command'] as Map;final output = <String, dynamic>{};if (command['type'] == 'message.send') {- final images = (command['attachmentIds'] as List? ?? const []).length;- // As the backend stores a message of images alone.append(- (command['text'] as String).isEmpty && images > 0- ? (images == 1 ? '[image]' : '[$images images]')- : command['text'] as String,+ command['text'] as String,conversationId: command['conversationId'] as String,+ attachments: [+ for (final id in command['attachmentIds'] as List? ?? const [])+ _attachment(id as String),+ ],);messages.last['replyTo'] = command['replyTo'];- messages.last['attachments'] = [- for (final id in command['attachmentIds'] as List? ?? const [])- attachments[id],- ];output['messageId'] = 'message-$revision';} else if (command['type'] == 'conversation.create') {revision++;@@ -251,68 +287,16 @@ class ConversationServer {as Map<String, dynamic>;}- Map<String, dynamic> _attachment(- String method,- List<String> segments,- Map<String, dynamic>? body,- ) {- final parts = segments.length > 4 ? attachmentParts[segments[4]] : null;- if (segments.length > 4 && parts == null) {- throw const SuperTabFailure('NOT_FOUND', 'This image is unavailable.');- }- if (method == 'DELETE') {- attachments.remove(segments[4]);- attachmentParts.remove(segments[4]);- deletedAttachments.add(segments[4]);- return {'id': segments[4], 'deleted': true};- }- if (method == 'GET' && segments.length == 5) {- final missing = [- for (var i = 0; i < parts!.length; i++)- if (parts[i] == null) i,- ];- return {- ...attachments[segments[4]]!,- 'complete': missing.isEmpty,- if (missing.isNotEmpty) 'missing': missing,- };- }- if (method == 'GET') return {'data': parts![int.parse(segments[6])]};- uploads.add(Map<String, dynamic>.from(body!));- if (failUploads || failUploadAt == uploads.length) {- failUploadAt = null;- throw StateError('Connection lost');- }- if (segments.length == 4) {- final id = 'image-${uploads.where((u) => u.containsKey('name')).length}';- final size = body['size'] as int;- attachments[id] = {- 'id': id,- 'name': body['name'],- 'mime': 'image/png',- 'size': size,- 'width': null,- 'height': null,- 'parts': (size / (256 * 1024)).ceil(),- };- attachmentParts[id] = [- body['data'] as String,- for (var i = 1; i < (attachments[id]!['parts'] as int); i++) null,- ];- return {...attachments[id]!, 'complete': size <= 256 * 1024};- }- parts![int.parse(segments[6])] = body['data'] as String;- return {'id': segments[4], 'complete': !parts.contains(null)};- }-SuperTabController controller({Map<String, dynamic>? initial,String account = 'owner',+ SuperTabUpload? upload,}) => SuperTabController(tabId: 'tab',accountId: account,request: request,save: save,+ upload: upload ?? this.upload,initial: initial ?? const {},pollInterval: Duration.zero,);diff --git a/docs/plans/2026-10-21-super-tab-chat-attachments.md b/docs/plans/2026-10-21-super-tab-chat-attachments.mdnew file mode 100644index 000000000..e078bc732--- /dev/null+++ b/docs/plans/2026-10-21-super-tab-chat-attachments.md@@ -0,0 +1,108 @@+# Super Tab chat attachments++Status: planned 2026-10-21. Owner direction: files live on a public GCS bucket served through a CDN+(`https://cdn.harness.autonomous.ai`); clients upload through the backend, which returns the CDN link.+Bucket, credentials and CDN base are all environment variables.++## Problem++The Super Tab chat (Lead and every group) takes text only. A person cannot paste a screenshot, drop a+file or pick one, and an agent never receives one. The launch dialog's attachments go through the+terminal stream, which only reaches machines the sender can drive, and they never enter the transcript.++## Decisions++- Clients upload the bytes to the backend, which streams them into GCS and answers with the CDN link.+ The message stores only metadata.+- Public read through the CDN. Anyone holding a link can open the file, so every object key carries a+ random 128-bit segment: `<prefix>/<tabId>/<random hex 32>/<sanitized name>`.+- Limits: 10 MB per file, 10 files per message. Any MIME type; images get a preview.+- The chat never loads a file by itself (Super Tab MVP rule, `docs/research/2026-10-17-one-human-many-agents/17-super-tab-mvp.md:229`):+ a row shows a chip (name, size); an image opens only when clicked.+- The agent receives local file paths. The host CLI on the agent's machine downloads each file into+ its paste-drops folder (`cli/src/lib/pasteDropFiles.ts`, 24 h retention) and lists the paths in the+ delivered prompt. This works for an agent on anyone's machine; no terminal access is needed.++## Contract++Attachment metadata, as stored on a message and returned by every read:++```ts+type Attachment = { id: string; name: string; mime: string; size: number; url: string }+```++Upload is one HTTP request to the backend, never through another machine or the relay:++- The browser build sends it straight to the backend with its own account token (the bearer `ApiClient` sends).+- The native desktop holds no backend token: its `ApiClient` talks to this computer's daemon. It posts the same+ request to the daemon's local HTTP API (`POST /api/super-tabs/:tabId/attachments`, with the local write header+ `x-adapter-local: 1`). The daemon streams it on to the backend over HTTPS with the account's token and hands back+ the backend's status and body unchanged (`cli/src/lib/superTabAttachmentProxy.ts`). It takes 11 MB at most and+ ends an upload after 30 s with no bytes moving, or after 15 minutes in all.+- `post --attach` posts each file to the same daemon route as the agent (`?asAgentId=`), on its own deadline rather+ than a service answer's 30 s.++`POST /super-tabs/:tabId/attachments`, `multipart/form-data` with a `conversationId` field followed by one `file`+part (its filename and content type are the attachment's name and mime). The actor must be allowed to post in+that conversation. The backend streams the part into GCS and stops at 10 MB. Answers:++- `200 { attachment: Attachment }` with `url` = `<SUPER_TAB_ATTACHMENTS_PUBLIC_BASE>/<object key>`.+- `413 ATTACHMENT_TOO_LARGE`, `403 FORBIDDEN`, `400 INVALID_ATTACHMENT`, `503 ATTACHMENTS_UNAVAILABLE` (no bucket,+ or GCS failed).++Then `message.send { ..., attachmentIds?: string[] }` on `POST /super-tabs/:tabId/commands` (at most 10). Each id+must have been uploaded by the same actor for the same tab and conversation and not used yet. `text` may be+empty when there is at least one attachment.++Old clients ignore `attachments`; old daemons deliver text only, which stays correct.++## Phases++### 1. Backend (`backend/`)++- Config: `SUPER_TAB_ATTACHMENTS_BUCKET`, `SUPER_TAB_ATTACHMENTS_PREFIX`, `SUPER_TAB_ATTACHMENTS_PUBLIC_BASE`+ (default `https://cdn.harness.autonomous.ai`; an `https://` address in production, refused at startup otherwise), `SUPER_TAB_ATTACHMENTS_CREDENTIALS` (base64 of the service account+ JSON; empty falls back to application default credentials). Missing bucket means uploads answer+ `ATTACHMENTS_UNAVAILABLE`; nothing else changes.+- `@google-cloud/storage`. A small `AttachmentStore` interface (`put` bytes) so tests and the local E2E run on a+ fake. Only inline-safe images keep their type; everything else is stored as `application/octet-stream` with+ `Content-Disposition: attachment`, so nothing runs as a page on the CDN's domain. The CDN should send+ `X-Content-Type-Options: nosniff`.+- Prisma: `attachments Json?` on `SuperTabMessage`; a `SuperTabAttachment` row per upload (id, tabId,+ conversationId, actor key, name, mime, size, objectKey, usedBy messageId, createdAt) to enforce single use. Rows that never get used can be swept later; not in v1.+- Validation in `commands.ts` beside `message.send`; tests in `commands.test.ts`.++### 2. CLI (`cli/src/superTabs/`)++- `host.ts` delivery: before `core.turns.deliver`, download each attachment (only from the configured public+ base, size capped, timeout), write it with `writePasteDropFile`, and add+ `Attached files:\n- <path> (<name>, <size>)` to `prompt()`. A failed download names the URL instead of a path.+- `messages` / `message` output includes attachment names and URLs.+- `post ... --attach PATH` (repeatable): the agent can send a screenshot or a log back. Uploads each file through+ the daemon's local upload route, then `message.send` with the ids.+- The daemon's local HTTP API passes `POST /api/super-tabs/:tabId/attachments` on to the backend (see Contract).++### 3. Desktop (`desktop/lib/super_tabs/`)++- Composer (`view.dart`): wrap the `TextField` in `NewHarnessPasteTarget` and `NewHarnessDropZone`, add+ `NewHarnessAttachButton`, keep a `HarnessAttachments` per conversation, show chips under the field.+ Same code serves the web build.+- `controller.dart` `send()`: upload each file (progress on the chip), then send with the ids. The browser posts+ to the backend with its token; the native desktop posts to the daemon's local upload route with+ `x-adapter-local: 1`, which passes it on. A failed upload keeps the draft and the files; a stalled upload can be+ cancelled.+- `message_row.dart`: file chips; an image chip opens a viewer that fetches the URL only on click; others open+ in the browser.++### 4. Validation++- Unit: backend command tests, CLI host prompt and download tests, desktop composer and row widget tests.+- Local E2E on the Super Tab rig (`supertab-local-e2e-rig`) with the fake store: paste a PNG on desktop, agent on+ another machine receives a path and reads it; agent posts `--attach`, desktop shows the chip.+- One run against the real bucket from staging before release.++## Open (ops)++- Bucket and CDN values for each environment, and an ingress body limit of at least 11 MB on the upload route.+- CDN CORS for GET, so the browser build can show images.+- Lifecycle: delete objects after N days? Default proposal: keep 90 days.