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
Chat files up to 256 MB: over 10 MB straight to storage on one-write upload links (Dee) (#2441)
0xken15214ccc456602
diff --git a/backend/integration/superTabs.test.ts b/backend/integration/superTabs.test.tsindex 2e0c40852..322f272cb 100644--- a/backend/integration/superTabs.test.ts+++ b/backend/integration/superTabs.test.ts@@ -4,6 +4,7 @@ import { execFile } from 'node:child_process'import { promisify } from 'node:util'import { join } from 'node:path'import { tmpdir } from 'node:os'+import { Readable } from 'node:stream'import { afterAll, beforeAll, describe, expect, it, onTestFinished, vi } from 'vitest'import { MongoMemoryReplSet } from 'mongodb-memory-server-core'import { PrismaClient } from '@prisma/client'@@ -14,6 +15,8 @@ import { HostReads } from '../src/superTabs/read/host.js'import { MemoryAttachmentStore } from '../src/superTabs/attachments.js'import { superTabRoutes } from '../src/routes/superTabs.js'import { errorHandler } from '../src/middlewares/errorHandler.js'+import { logger } from '../src/utils/logger.js'+import { sweepPendingUploads } from '../src/lib/pendingUploadSweep.js'import { IGNORED_NOTE, type Command } from '../src/superTabs/commands.js'import { nextMachineShareGrants } from '../src/lib/machineSharePolicy.js'import { DEFAULT_ROUTING_POLICY } from '../src/superTabs/routingPolicy.js'@@ -2520,7 +2523,8 @@ describe('Super Tab chat attachments', () => {it('refuses an oversized, second, misordered or hidden-named file, and a server with no bucket', async () => {const { tab } = await fixture()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' })+ const big = await post(tab, [['conversationId', 'lead'], ['file', new Uint8Array(10 * 1024 * 1024 + 1), 'big.bin', 'application/octet-stream']])+ expect(big).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' })@@ -2573,6 +2577,211 @@ describe('Super Tab chat attachments', () => {.toMatchObject({ author: { kind: 'agent', id: lead }, attachments: [{ name: 'result.png', size: 7 }] })})+ type Link = { id: string; url: string; method: string; headers: Record<string, string>; expiresAt: number }+ const linkFor = async (tab: string, body: Record<string, unknown>, user = owner, asAgentId?: string) => {+ const response = await upload.inject({ method: 'POST', url: `/api/super-tabs/${tab}/attachments/uploads${asAgentId ? `?asAgentId=${asAgentId}` : ''}`,+ headers: { authorization: `Bearer ${user.sub}` }, payload: { conversationId: 'lead', name: 'AC4 - 26 Oct v2.step', mime: 'application/octet-stream', ...body } })+ const answer = response.json()+ return { status: response.statusCode, code: answer.error?.code ?? answer.code, message: answer.error?.message as string | undefined, upload: answer.data?.upload as Link }+ }+ const complete = async (tab: string, uploadId: string, user = owner, asAgentId?: string) => {+ const response = await upload.inject({ method: 'POST', url: `/api/super-tabs/${tab}/attachments/uploads/${uploadId}/complete${asAgentId ? `?asAgentId=${asAgentId}` : ''}`,+ headers: { authorization: `Bearer ${user.sub}` }, payload: {} })+ const answer = response.json()+ return { status: response.statusCode, code: answer.error?.code ?? answer.code, attachment: answer.data?.attachment as Uploaded }+ }+ /** `size` bytes in 1 MiB chunks, made as they are read: the bytes go to the bucket as a stream. */+ const streamOf = (size: number, first = Buffer.alloc(0)) => Readable.from((function* () {+ if (first.length) yield first+ for (let left = size - first.length; left > 0; left -= 1024 * 1024) yield Buffer.alloc(Math.min(left, 1024 * 1024), 7)+ })())++ it('takes a 256 MB file straight to the bucket on a one-write link, and delivers it to the agent once checked', async () => {+ const { tab, lead } = await fixture()+ const size = 256 * 1024 * 1024+ const { status, upload: link } = await linkFor(tab, { size })+ expect(status).toBe(200)+ expect(link.method).toBe('PUT')+ expect(link.expiresAt - Date.now()).toBeLessThanOrEqual(10 * 60_000)+ expect(link.headers).toMatchObject({ 'x-goog-content-length-range': `${size},${size}`, 'x-goog-if-generation-match': '0', 'content-type': 'application/octet-stream' })+ // Not sendable, by this server or an older one, until the server has seen the bytes.+ await expect(send(tab, [link.id])).rejects.toMatchObject({ code: 'ATTACHMENT_UNAVAILABLE' })+ expect(await complete(tab, link.id)).toMatchObject({ status: 409, code: 'UPLOAD_INCOMPLETE' })+ expect(await files.receive(link.url, link.headers, streamOf(size))).toBe(200)+ const done = await complete(tab, link.id)+ expect(done.status).toBe(200)+ expect(done.attachment).toMatchObject({ id: link.id, name: 'AC4 - 26 Oct v2.step', mime: 'application/octet-stream', size })+ expect(done.attachment.url).toMatch(new RegExp(`^https://cdn\\.example\\.test/super-tabs/${tab}/[0-9a-f]{32}/AC4_-_26_Oct_v2\\.step$`))+ expect(files.objects.get(objectKey(done.attachment.url))).toMatchObject({ contentType: 'application/octet-stream', contentDisposition: "attachment; filename*=UTF-8''AC4%20-%2026%20Oct%20v2.step" })+ // A lost answer is answered again the same way.+ expect(await complete(tab, link.id)).toEqual(done)+ const sent = await send(tab, [link.id])+ 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([done.attachment])+ files.objects.delete(objectKey(done.attachment.url))+ })++ it('refuses a link past 256 MB with the limit, and one with no size, before any is signed', async () => {+ const { tab } = await fixture()+ const rows = await db.superTabAttachment.count({ where: { tabId: tab } })+ expect(await linkFor(tab, { size: 256 * 1024 * 1024 + 1 })).toMatchObject({ status: 413, code: 'ATTACHMENT_TOO_LARGE', message: 'Files can be up to 256 MB.' })+ expect(await linkFor(tab, { size: 0 })).toMatchObject({ status: 400, code: 'INVALID_ATTACHMENT' })+ expect(await linkFor(tab, { size: 1.5 })).toMatchObject({ status: 400 })+ expect(await linkFor(tab, { size: 5, name: 'evilgnp.exe' })).toMatchObject({ status: 400, code: 'INVALID_ATTACHMENT' })+ expect(await db.superTabAttachment.count({ where: { tabId: tab } })).toBe(rows)+ const old = await post(tab, [['conversationId', 'lead'], ['file', new Uint8Array(10 * 1024 * 1024 + 1), 'big.bin', 'application/octet-stream']])+ expect(old).toMatchObject({ status: 413, code: 'ATTACHMENT_TOO_LARGE' })+ })++ it('lets only the actor that asked attach a link\'s upload, while it may still post there; others are refused alike', async () => {+ const { tab, lead } = await fixture()+ await invite(tab)+ const other = (await fixture()).tab+ const { upload: link } = await linkFor(tab, { size: 11 })+ expect(await files.receive(link.url, link.headers, Buffer.alloc(11))).toBe(200)+ const unknown = await complete(tab, 'aaaaaaaaaaaaaaaaaaaaaaaa')+ expect(unknown).toMatchObject({ status: 400, code: 'ATTACHMENT_UNAVAILABLE' })+ // Another member, the owner's own agent, and the same id in another Swarm: the same answer as an id that never was.+ expect(await complete(tab, link.id, peer)).toEqual(unknown)+ expect(await complete(tab, link.id, host, lead)).toEqual(unknown)+ expect((await complete(other, link.id)).code).toBe('ATTACHMENT_UNAVAILABLE')+ // Nobody but its owner can ask for a link where they cannot post, nor an agent its host does not run.+ expect(await linkFor(tab, { size: 11, conversationId: 'no-such-group' })).toMatchObject({ status: 404 })+ expect(await linkFor(tab, { size: 11 }, peer, lead)).toMatchObject({ status: 403, code: 'FORBIDDEN' })+ const agents = await linkFor(tab, { size: 11 }, host, lead)+ expect(agents.status).toBe(200)+ // Access gone while the bytes moved: the upload is not made sendable.+ const { upload: peers } = await linkFor(tab, { size: 3, name: 'notes.txt', mime: 'text/plain' }, peer)+ expect(await files.receive(peers.url, peers.headers, Buffer.from('abc'))).toBe(200)+ await run(tab, { type: 'member.remove', userId: peer.sub })+ expect((await complete(tab, peers.id, peer)).status).toBeGreaterThanOrEqual(403)+ expect((await db.superTabAttachment.findFirst({ where: { id: peers.id } }))!.purpose).toBe('pending-upload')+ })++ it('keeps a declared image\'s type only when its first bytes are one, and counts links in the hourly allowance', async () => {+ const { tab } = await fixture()+ const png = Buffer.from([0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a])+ const real = (await linkFor(tab, { size: 12 * 1024 * 1024, name: 'shot.png', mime: 'image/png' })).upload+ expect(await files.receive(real.url, real.headers, streamOf(12 * 1024 * 1024, png))).toBe(200)+ expect((await complete(tab, real.id)).attachment.mime).toBe('image/png')+ const page = Buffer.from('<html><script>alert(1)</script></html>')+ const fake = (await linkFor(tab, { size: page.length, name: 'cat.png', mime: 'image/png' })).upload+ expect(await files.receive(fake.url, fake.headers, page)).toBe(200)+ const disguised = (await complete(tab, fake.id)).attachment+ expect(disguised.mime).toBe('application/octet-stream')+ expect(files.objects.get(objectKey(disguised.url))!.contentType).toBe('application/octet-stream')+ await db.superTabAttachment.createMany({ data: Array.from({ length: 198 }, () => ({ id: randomUUID().replaceAll('-', '').slice(0, 24), tabId: tab, conversationId: 'lead',+ actorKey: `person:${owner.sub}`, name: 'x', mime: 'text/plain', size: 1, objectKey: 'x' })) })+ expect(await linkFor(tab, { size: 11 })).toMatchObject({ status: 429, code: 'RATE_LIMITED' })+ })++ it('holds the hourly limits under parallel link requests: 200 uploads and 4 GB a sender', async () => {+ const { tab } = await fixture()+ const old = (n: number, size = 1) => db.superTabAttachment.createMany({ data: Array.from({ length: n }, () => ({ id: randomUUID().replaceAll('-', '').slice(0, 24),+ tabId: tab, conversationId: 'lead', actorKey: `person:${owner.sub}`, name: 'x', mime: 'text/plain', size, objectKey: 'x' })) })+ await old(190)+ const answers = await Promise.all(Array.from({ length: 60 }, () => linkFor(tab, { size: 11 })))+ expect(answers.filter(a => a.status === 200)).toHaveLength(10)+ expect(answers.filter(a => a.status === 429).every(a => a.code === 'RATE_LIMITED')).toBe(true)+ expect(answers.filter(a => a.status !== 200 && a.status !== 429)).toEqual([])+ expect(await db.superTabAttachment.count({ where: { tabId: tab, actorKey: `person:${owner.sub}` } })).toBe(200)+ // Bytes: another sender, 3.9 GB already this hour.+ const { tab: other } = await fixture()+ await db.superTabAttachment.create({ data: { id: randomUUID().replaceAll('-', '').slice(0, 24), tabId: other, conversationId: 'lead',+ actorKey: `person:${owner.sub}`, name: 'x', mime: 'text/plain', size: 3900 * 1024 * 1024, objectKey: 'x' } })+ expect(await linkFor(other, { size: 200 * 1024 * 1024 })).toMatchObject({ status: 429, code: 'RATE_LIMITED', message: 'You attached 4 GB of files in the last hour. Wait before attaching more.' })+ expect((await linkFor(other, { size: 100 * 1024 * 1024 })).status).toBe(200)+ })++ it('removes an upload never finished, and what it stored, an hour after its link expired; nothing else', async () => {+ const { tab } = await fixture()+ const ask = async (size: number) => (await linkFor(tab, { size })).upload+ const [stale, unstored, finished, young, stuck] = [await ask(5), await ask(5), await ask(5), await ask(5), await ask(5)]+ for (const link of [stale, finished, young, stuck]) expect(await files.receive(link.url, link.headers, Buffer.alloc(5))).toBe(200)+ const done = await complete(tab, finished.id)+ const keyOf = async (id: string) => (await db.superTabAttachment.findFirst({ where: { id } }))!.objectKey+ const keys = { stale: await keyOf(stale.id), stuck: await keyOf(stuck.id), young: await keyOf(young.id) }+ const aged = new Date(Date.now() - 71 * 60_000)+ await db.superTabAttachment.updateMany({ where: { id: { in: [stale.id, unstored.id, finished.id, stuck.id] } }, data: { createdAt: aged } })+ const remove = vi.spyOn(files, 'delete')+ remove.mockImplementation(async key => { if (key === keys.stuck) throw Object.assign(new Error(`DELETE ${key} failed`), { code: 503 }); files.objects.delete(key) })+ const warn = vi.spyOn(logger, 'warn')+ expect(await sweepPendingUploads(db, files, Date.now())).toEqual({ removed: 2, failed: 1 })+ remove.mockRestore()+ expect(files.objects.has(keys.stale)).toBe(false)+ expect(await db.superTabAttachment.findFirst({ where: { id: { in: [stale.id, unstored.id] } } })).toBeNull()+ // A failed delete keeps the row for the next pass, and logs no key.+ expect(await db.superTabAttachment.findFirst({ where: { id: stuck.id } })).not.toBeNull()+ expect(JSON.stringify(warn.mock.calls)).not.toContain(keys.stuck)+ warn.mockRestore()+ // A finished upload and one whose link is young are kept, bytes and all.+ expect(files.objects.has(objectKey(done.attachment.url))).toBe(true)+ expect(files.objects.has(keys.young)).toBe(true)+ expect(await complete(tab, young.id)).toMatchObject({ status: 200 })+ expect(await sweepPendingUploads(db, files, Date.now())).toEqual({ removed: 1, failed: 0 })+ })++ it('never leaves a finished upload without its file when a finish races the sweep: the finish wins or is refused', async () => {+ const { tab } = await fixture()+ const aged = new Date(Date.now() - 71 * 60_000)+ const stored = async () => {+ const link = (await linkFor(tab, { size: 5 })).upload+ expect(await files.receive(link.url, link.headers, Buffer.from('bytes'))).toBe(200)+ await db.superTabAttachment.updateMany({ where: { id: link.id }, data: { createdAt: aged } })+ return { link, key: (await db.superTabAttachment.findFirst({ where: { id: link.id } }))!.objectKey }+ }+ // The finish lands after the sweep picked the row, before it claims it: the finish wins, and the sweep leaves it alone.+ const first = await stored()+ let finished: Awaited<ReturnType<typeof complete>> | null = null+ expect(await sweepPendingUploads(db, files, Date.now(), 100, async () => { finished = await complete(tab, first.link.id) })).toEqual({ removed: 0, failed: 0 })+ expect(finished!.status).toBe(200)+ expect(files.objects.has(first.key)).toBe(true)+ expect(await send(tab, [first.link.id])).toBeTruthy()+ // The sweep claims the row while a finish is checking the bytes: the finish is refused, and nothing sendable is left.+ const second = await stored()+ const head = vi.spyOn(files, 'head').mockImplementationOnce(async (key, bytes) => {+ const read = files.objects.get(key)!.bytes.subarray(0, bytes)+ await sweepPendingUploads(db, files, Date.now())+ return read+ })+ expect(await complete(tab, second.link.id)).toMatchObject({ status: 400, code: 'ATTACHMENT_UNAVAILABLE' })+ head.mockRestore()+ expect(files.objects.has(second.key)).toBe(false)+ expect(await db.superTabAttachment.findFirst({ where: { id: second.link.id } })).toBeNull()+ await expect(send(tab, [second.link.id])).rejects.toMatchObject({ code: 'ATTACHMENT_UNAVAILABLE' })+ })++ it('asks for a link even when the sweep removes the sender\'s allowance row between its create and its use', async () => {+ const { tab } = await fixture()+ await db.superTabUploadAllowance.deleteMany({})+ // As if the sweep removed it right after it was made.+ const made = vi.spyOn(db.superTabUploadAllowance, 'create').mockResolvedValueOnce({ id: 'gone', at: new Date() } as never)+ expect((await linkFor(tab, { size: 11 })).status).toBe(200)+ made.mockRestore()+ })++ it('answers a signing or bucket failure as unavailable, never with the object\'s key', async () => {+ const { tab } = await fixture()+ const error = vi.spyOn(logger, 'error')+ const rows = await db.superTabAttachment.count({ where: { tabId: tab } })+ let pendingWhenSigned = -1+ const signing = vi.spyOn(files, 'uploadLink').mockImplementationOnce(async () => {+ pendingWhenSigned = await db.superTabAttachment.count({ where: { tabId: tab, purpose: 'pending-upload' } })+ throw Object.assign(new Error('cannot sign super-tabs/secret-key'), { code: 'ENOSIGN' })+ })+ expect(await linkFor(tab, { size: 11 })).toMatchObject({ status: 503, code: 'ATTACHMENTS_UNAVAILABLE' })+ // The row was written before signing, and goes when no link was handed out.+ expect(pendingWhenSigned).toBe(1)+ expect(await db.superTabAttachment.count({ where: { tabId: tab } })).toBe(rows)+ signing.mockRestore()+ const { upload: link } = await linkFor(tab, { size: 11 })+ const stat = vi.spyOn(files, 'stored').mockRejectedValueOnce(Object.assign(new Error(`GET ${link.url} failed`), { code: 503 }))+ expect(await complete(tab, link.id)).toMatchObject({ status: 503, code: 'ATTACHMENTS_UNAVAILABLE' })+ stat.mockRestore()+ expect(JSON.stringify(error.mock.calls)).not.toMatch(/secret-key|super-tabs\//)+ error.mockRestore()+ })+it('refuses a viewer before storing anything', async () => {const { tab } = await fixture()await invite(tab, 'viewer')diff --git a/backend/integration/workerIndexPlans.test.ts b/backend/integration/workerIndexPlans.test.tsindex 3a9576483..6656f6564 100644--- a/backend/integration/workerIndexPlans.test.ts+++ b/backend/integration/workerIndexPlans.test.ts@@ -126,3 +126,28 @@ describe('the nightly routing reflection', () => {expect(rows[0]!.planSummary, JSON.stringify(plan(rows))).toMatch(/IXSCAN \{ tabId: 1, projectId: 1, createdAt: 1/)})})++describe('the pending-upload sweep', () => {+ it('reads only the unfinished uploads it removes, by the (purpose, createdAt) index', async () => {+ const { sweepPendingUploads } = await import('../src/lib/pendingUploadSweep.js')+ const { MemoryAttachmentStore } = await import('../src/superTabs/attachments.js')+ const row = (purpose: string | null, ageMs: number) => ({ id: randomUUID().replaceAll('-', '').slice(0, 24), tabId: 'tab', conversationId: 'lead',+ actorKey: 'person:x', name: 'x', mime: 'text/plain', size: 1, objectKey: `k/${randomUUID()}`, createdAt: new Date(Date.now() - ageMs),+ ...(purpose ? { purpose } : {}) })+ // Sent and unsent chat files, old and new, and young unfinished uploads: a read the index does not bound examines them all.+ await db.superTabAttachment.createMany({ data: [+ ...Array.from({ length: 40 }, () => row(null, 3 * DAY)), ...Array.from({ length: 5 }, () => row('pending-upload', 60_000)),+ row('pending-upload', 2 * 3_600_000), row('pending-upload', 3 * 3_600_000),+ ] })+ let result: unknown+ const entries = await profiled(db, async () => { result = await sweepPendingUploads(db, new MemoryAttachmentStore(), Date.now()) })+ expect(result).toEqual({ removed: 2, failed: 0 })+ // The two finds; the claims and removals that follow go by id.+ const rows = reads(entries, 'SuperTabAttachment', ['purpose'], ['_id'])+ expect(rows.length, JSON.stringify(plan(rows))).toBe(2)+ for (const read of rows) {+ expect(read.planSummary, JSON.stringify(plan(rows))).toMatch(/IXSCAN \{ purpose: 1, createdAt: 1/)+ expect(read.docsExamined, JSON.stringify(plan(rows))).toBeLessThanOrEqual(Math.max(read.nreturned ?? 0, 2))+ }+ })+})diff --git a/backend/prisma/schema.prisma b/backend/prisma/schema.prismaindex 2ccef3e69..7a1b94066 100644--- a/backend/prisma/schema.prisma+++ b/backend/prisma/schema.prisma@@ -1273,6 +1273,16 @@ model SuperTabAttachment {createdAt DateTime @default(now())@@index([tabId, actorKey, createdAt])+ /// Unfinished uploads by age, for the pending-upload sweep (lib/pendingUploadSweep.ts).+ @@index([purpose, createdAt])+}++/// One per sender per Swarm while it asks for upload links (superTabs/store.ts uploadLink): each link request writes it in the+/// transaction that counts the sender's last hour and adds the pending upload, so two requests at once conflict and one retries,+/// and the hourly limits hold. The pending-upload sweep (lib/pendingUploadSweep.ts) removes it an hour after its last use.+model SuperTabUploadAllowance {+ id String @id @map("_id")+ at DateTime}model SuperTabOperation {diff --git a/backend/src/lib/pendingUploadSweep.ts b/backend/src/lib/pendingUploadSweep.tsnew file mode 100644index 000000000..3c8c1ee5c--- /dev/null+++ b/backend/src/lib/pendingUploadSweep.ts@@ -0,0 +1,70 @@+import type { PrismaClient } from '@prisma/client'+import { attachmentsFromEnv, directUploads, errorCode, PENDING_UPLOAD_LIFE_MS, PENDING_UPLOAD_PURPOSE, REMOVING_UPLOAD_PURPOSE, type DirectUploads } from '../superTabs/attachments.js'+import { logger } from '../utils/logger.js'++/**+ * Removes uploads that went straight to the bucket on a link (superTabs/store.ts uploadLink) and were never finished: an hour+ * after the link expired, the stored object first, then the row. Finished but unsent uploads are not touched here; they are+ * unsent files like any other (#2268). Each sender's allowance row goes an hour after its last link request.+ *+ * Its reads go by the (purpose, createdAt) index (schema.prisma), so a pass reads only the uploads it removes, however many+ * attachments there are (workerIndexPlans.test.ts).+ */+export const PENDING_UPLOAD_SWEEP = { chunk: 100, everyMs: 10 * 60_000 } as const++export async function sweepPendingUploads(db: PrismaClient, bucket: DirectUploads, now: number, chunk: number = PENDING_UPLOAD_SWEEP.chunk,+ picked: () => Promise<void> = async () => {}) {+ // Both by the (purpose, createdAt) index: rows claimed by an earlier pass whose file delete failed, then the newly due.+ const claimed = await db.superTabAttachment.findMany({ where: { purpose: REMOVING_UPLOAD_PURPOSE }, select: { id: true, objectKey: true }, take: chunk })+ const due = await db.superTabAttachment.findMany({ where: { purpose: PENDING_UPLOAD_PURPOSE, createdAt: { lt: new Date(now - PENDING_UPLOAD_LIFE_MS) } },+ select: { id: true, objectKey: true }, take: chunk })+ await picked()+ let removed = 0, failed = 0+ const mine = [...claimed]+ for (const row of due) {+ // Claimed first, with one conditional write: a finish that wins it keeps its row and bytes, and this pass skips the row;+ // one that loses is refused (store.ts completeUpload). Only a row this write changed has its file removed.+ const claim = await db.superTabAttachment.updateMany({ where: { id: row.id, purpose: PENDING_UPLOAD_PURPOSE }, data: { purpose: REMOVING_UPLOAD_PURPOSE } })+ if (claim.count === 1) mine.push(row)+ }+ for (const row of mine) {+ try { await bucket.delete(row.objectKey) } catch (error) {+ // The row stays claimed for the next pass. Only its id and the error's code: the key, and the error's text, carry the file's link.+ logger.warn('[pending-upload-sweep] could not remove a stored file', { id: row.id, code: errorCode(error) })+ failed+++ continue+ }+ removed += (await db.superTabAttachment.deleteMany({ where: { id: row.id, purpose: REMOVING_UPLOAD_PURPOSE } })).count+ }+ await db.superTabUploadAllowance.deleteMany({ where: { at: { lt: new Date(now - 3_600_000) } } })+ return { removed, failed }+}++/** Runs the sweep in the worker every 10 minutes, once the attachment settings name a bucket; says once whether it is on. */+export function startPendingUploadSweep(db: PrismaClient, env: Parameters<typeof attachmentsFromEnv>[0], now: () => number = Date.now): () => void {+ let bucket: DirectUploads | null = null+ try {+ const attachments = attachmentsFromEnv(env)+ bucket = attachments ? directUploads(attachments.store) : null+ } catch (error) {+ logger.warn('[pending-upload-sweep] off: the attachment settings are invalid', { error: error instanceof Error ? error.message : String(error) })+ return () => {}+ }+ if (!bucket) { logger.info('[pending-upload-sweep] off: no attachments bucket is set'); return () => {} }+ logger.info('[pending-upload-sweep] on', { everyMinutes: PENDING_UPLOAD_SWEEP.everyMs / 60_000 })+ let running = false+ const pass = async () => {+ if (running) return+ running = true+ try {+ const result = await sweepPendingUploads(db, bucket!, now())+ if (result.removed || result.failed) logger.info('[pending-upload-sweep] pass', result)+ } catch (error) {+ logger.warn('[pending-upload-sweep] pass failed', { code: errorCode(error) })+ } finally { running = false }+ }+ void pass()+ const timer = setInterval(() => void pass(), PENDING_UPLOAD_SWEEP.everyMs)+ timer.unref()+ return () => clearInterval(timer)+}diff --git a/backend/src/routes/superTabs.ts b/backend/src/routes/superTabs.tsindex f8aa7b0fb..baf1f79e7 100644--- a/backend/src/routes/superTabs.ts+++ b/backend/src/routes/superTabs.ts@@ -3,7 +3,7 @@ import { z, ZodError } from 'zod'import { prisma } from '../lib/prisma.js'import { env } from '../config/env.js'import multipart from '@fastify/multipart'-import { attachmentsFromEnv, MAX_ATTACHMENT_BYTES, MAX_AVATAR_BYTES } from '../superTabs/attachments.js'+import { attachmentsFromEnv, FORM_TOO_LARGE_MESSAGE, MAX_FORM_ATTACHMENT_BYTES, MAX_AVATAR_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'@@ -38,6 +38,10 @@ import { WORKSPACE_ACCESS_REVOKED } from '../superTabs/workspaceStore.js'const id = z.string().min(1).max(160).regex(/^[A-Za-z0-9_-]+$/)const tabParams = z.object({ tabId: id })const agentQuery = z.object({ asAgentId: id.optional() }).strict()+const uploadParams = z.object({ tabId: id, uploadId: id })+// The store checks the name, type and size; this only bounds what reaches it.+const uploadLinkBody = z.object({ conversationId: id, name: z.string().max(1000), mime: z.string().max(1000), size: z.number().int() }).strict()+const emptyBody = z.object({}).strict().optional()const create = z.object({ operationId: id, name: z.string().trim().min(1).max(160), projectVisibility: z.enum(['public', 'private']).optional(),workspaceId: id.optional() }).strict()const operation = operationSchema.extend({ asAgentId: id.optional() })@@ -509,7 +513,7 @@ export async function superTabRoutes(app: FastifyInstance, options: { store?: Su// 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 } })+ await scope.register(multipart, { limits: { fileSize: MAX_FORM_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@@ -529,13 +533,22 @@ export async function superTabRoutes(app: FastifyInstance, options: { store?: Su} 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 (code === 'FST_REQ_FILE_TOO_LARGE') fail('ATTACHMENT_TOO_LARGE', FORM_TOO_LARGE_MESSAGE, 413)if (error instanceof SuperTabError || (error === stored && !(code && String(code).startsWith('FST_')))) throw errorfail('INVALID_ATTACHMENT', 'Send a multipart form with conversationId and one file.', 400)}return uploaded ?? fail('INVALID_ATTACHMENT', 'Attach one file.', 400)}))})+ // A file over the form's 10 MB goes straight to the bucket on a link this server signs, then is checked here before any+ // message can carry it (store.ts uploadLink, completeUpload). Neither request carries the file, so both stay small.+ app.post<{ Params: z.infer<typeof tabParams>; Querystring: z.infer<typeof agentQuery>; Body: z.infer<typeof uploadLinkBody> }>('/api/super-tabs/:tabId/attachments/uploads',+ { bodyLimit: 4096, preHandler: [validateParams(tabParams), validateQuery(agentQuery), validateBody(uploadLinkBody)] },+ (req, reply) => respond(reply, () => store.uploadLink(req.user!, req.params.tabId, req.body.conversationId,+ { name: req.body.name, mime: req.body.mime, size: req.body.size }, req.query.asAgentId)))+ app.post<{ Params: z.infer<typeof uploadParams>; Querystring: z.infer<typeof agentQuery>; Body: z.infer<typeof emptyBody> }>('/api/super-tabs/:tabId/attachments/uploads/:uploadId/complete',+ { bodyLimit: 1024, preHandler: [validateParams(uploadParams), validateQuery(agentQuery), validateBody(emptyBody)] },+ (req, reply) => respond(reply, () => store.completeUpload(req.user!, req.params.tabId, req.params.uploadId, req.query.asAgentId)))// An avatar picture (superTabs/profile.ts) comes the same way, alone in its form; the command that sets it names whose it is.await app.register(async scope => {await scope.register(multipart, { limits: { fileSize: MAX_AVATAR_BYTES + 1, files: 1, fields: 0, parts: 1 } })diff --git a/backend/src/superTabs/attachments.limits.test.ts b/backend/src/superTabs/attachments.limits.test.tsnew file mode 100644index 000000000..d029a5157--- /dev/null+++ b/backend/src/superTabs/attachments.limits.test.ts@@ -0,0 +1,26 @@+import { readFileSync } from 'node:fs'+import { join } from 'node:path'+import { describe, expect, it } from 'vitest'+import { MAX_ATTACHMENT_BYTES, MAX_FORM_ATTACHMENT_BYTES } from './attachments.js'++// The clients are other packages and languages, so they cannot import the server's number: each keeps its own copy, and+// this holds every copy to the server's, so a client never refuses a file the server takes or offers one it refuses.+const repo = join(import.meta.dirname, '../../..')+const value = (file: string, name: string) => {+ const line = new RegExp(`${name}\\s*=\\s*([0-9 *]+);?\\s*$`, 'm').exec(readFileSync(join(repo, file), 'utf8'))+ if (!line) throw new Error(`${name} not found in ${file}`)+ return line[1]!.split('*').map(n => Number(n.trim())).reduce((a, b) => a * b, 1)+}++describe('every client\'s attachment limit', () => {+ it.each([+ ['cli/src/superTabs/attachments.ts', 'MAX_ATTACHMENT_BYTES', MAX_ATTACHMENT_BYTES],+ ['cli/src/lib/superTabAttachmentProxy.ts', 'MAX_FORM_ATTACHMENT_BYTES', MAX_FORM_ATTACHMENT_BYTES],+ ['desktop/lib/super_tabs/attachment_upload.dart', 'kSuperTabAttachmentMaxBytes', MAX_ATTACHMENT_BYTES],+ ['desktop/lib/super_tabs/attachment_upload.dart', 'kSuperTabFormAttachmentMaxBytes', MAX_FORM_ATTACHMENT_BYTES],+ ['mobile/lib/swarm/swarm_outgoing_files.dart', 'swarmAttachmentMaxBytes', MAX_ATTACHMENT_BYTES],+ ['mobile/lib/swarm/swarm_outgoing_files.dart', 'swarmFormAttachmentMaxBytes', MAX_FORM_ATTACHMENT_BYTES],+ ])('%s %s is the server\'s', (file, name, want) => {+ expect(value(file, name)).toBe(want)+ })+})diff --git a/backend/src/superTabs/attachments.test.ts b/backend/src/superTabs/attachments.test.tsindex faa4ddb31..08c848a28 100644--- a/backend/src/superTabs/attachments.test.ts+++ b/backend/src/superTabs/attachments.test.ts@@ -1,7 +1,7 @@import { generateKeyPairSync } from 'node:crypto'import { describe, expect, it } from 'vitest'import { Readable } from 'node:stream'-import { AttachmentTooLarge, attachmentName, attachmentsFromEnv, checkedType, imageTypeOf, GcsAttachmentStore, GcsAvatarStore, MemoryAttachmentStore, objectKeyFor, served, serviceAccountFrom } from './attachments.js'+import { AttachmentTooLarge, attachmentName, attachmentsFromEnv, checkedType, directUploads, imageTypeOf, GcsAttachmentStore, GcsAvatarStore, MAX_ATTACHMENT_BYTES, MAX_FORM_ATTACHMENT_BYTES, MemoryAttachmentStore, objectKeyFor, served, serviceAccountFrom, typeFromHead, UPLOAD_LINK_MS } from './attachments.js'const { privateKey } = generateKeyPairSync('rsa', { modulusLength: 2048 })const key = { type: 'service_account', project_id: 'harness-test', client_email: '[email protected]',@@ -84,6 +84,23 @@ describe('attachment bucket credentials', () => {expect(Number(link.searchParams.get('X-Goog-Expires'))).toBeLessThanOrEqual(3600)})+ it('signs an upload link for one new object of one exact size, as a download, for minutes, without a network call', async () => {+ const store = attachmentsFromEnv(env(encoded(key)))!.store as GcsAttachmentStore+ const expires = Date.now() + UPLOAD_LINK_MS+ const { url, headers } = await store.uploadLink('super-tabs/tab/0123/AC4.step', { name: 'AC4 - 26 Oct v2.step' }, 150 * 1024 * 1024, expires)+ const link = new URL(url)+ expect(link.host).toBe('storage.googleapis.com')+ expect(link.pathname).toBe('/attachments/super-tabs/tab/0123/AC4.step')+ expect(link.searchParams.get('X-Goog-Credential')).toContain(key.client_email)+ expect(Number(link.searchParams.get('X-Goog-Expires'))).toBeLessThanOrEqual(600)+ // Every rule is a signed header: storage refuses a request that drops or changes one.+ expect(link.searchParams.get('X-Goog-SignedHeaders')!.split(';')).toEqual(['cache-control', 'content-disposition', 'content-type', 'host',+ 'x-goog-content-length-range', 'x-goog-if-generation-match'])+ expect(headers).toEqual({ 'content-type': 'application/octet-stream', 'content-disposition': "attachment; filename*=UTF-8''AC4%20-%2026%20Oct%20v2.step",+ 'cache-control': 'public, max-age=31536000, immutable', 'x-goog-content-length-range': '157286400,157286400', 'x-goog-if-generation-match': '0' })+ expect(directUploads(store)).toBe(store)+ })+it('builds the storage client from the configured key, without a network call', async () => {const store = attachmentsFromEnv(env(encoded(key)))!.store as GcsAttachmentStoreconst bucket = await (store as unknown as { files(): Promise<import('@google-cloud/storage').Bucket> }).files()@@ -153,3 +170,38 @@ describe('attachment files', () => {expect(store.objects.has('k2')).toBe(false)})})++describe('upload links on the memory bucket, with storage\'s rules', () => {+ const at = 1_800_000_000_000+ it('writes the linked object once, of exactly its size, before it expires, with its headers unchanged', async () => {+ let now = at+ const store = new MemoryAttachmentStore(() => now)+ const link = await store.uploadLink('k/big.bin', { name: 'big.bin' }, 5, at + UPLOAD_LINK_MS)+ expect(await store.receive(link.url, link.headers, Buffer.alloc(6))).toBe(400)+ expect(await store.receive(link.url, link.headers, Buffer.alloc(4))).toBe(400)+ expect(await store.receive(link.url, { ...link.headers, 'content-type': 'text/html' }, Buffer.alloc(5))).toBe(403)+ const { 'x-goog-if-generation-match': _, ...overwriting } = link.headers+ expect(await store.receive(link.url, overwriting, Buffer.alloc(5))).toBe(403)+ expect(await store.receive(link.url.replace('k%2Fbig.bin', 'k%2Fother.bin'), link.headers, Buffer.alloc(5))).toBe(403)+ expect(await store.stored('k/big.bin')).toBeNull()+ expect(await store.receive(link.url, link.headers, Buffer.from('hello'))).toBe(200)+ expect(store.objects.get('k/big.bin')).toMatchObject({ contentType: 'application/octet-stream', contentDisposition: "attachment; filename*=UTF-8''big.bin" })+ expect(await store.receive(link.url, link.headers, Buffer.from('HELLO'))).toBe(412)+ expect((await store.head('k/big.bin', 16)).toString()).toBe('hello')+ now = at + UPLOAD_LINK_MS+ const late = await store.uploadLink('k/late.bin', { name: 'late.bin' }, 1, at + UPLOAD_LINK_MS)+ expect(await store.receive(late.url, late.headers, Buffer.alloc(1))).toBe(403)+ await store.delete('k/big.bin')+ expect(await store.stored('k/big.bin')).toBeNull()+ })+ it('keeps a declared image only when its first bytes are one', () => {+ expect(typeFromHead('image/png', Buffer.from([0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a]))).toBe('image/png')+ expect(typeFromHead('image/png', Buffer.from('<html>'))).toBe('application/octet-stream')+ expect(typeFromHead('model/step', Buffer.from('ISO-10303-21;'))).toBe('model/step')+ })+ it('caps a file at 256 MB, and a form at 10 MB, with the message that names the limit', () => {+ expect(MAX_ATTACHMENT_BYTES).toBe(256 * 1024 * 1024)+ expect(MAX_FORM_ATTACHMENT_BYTES).toBe(10 * 1024 * 1024)+ expect(new AttachmentTooLarge().message).toBe('Files can be up to 256 MB.')+ })+})diff --git a/backend/src/superTabs/attachments.ts b/backend/src/superTabs/attachments.tsindex 8cabf5356..ee63e6d28 100644--- a/backend/src/superTabs/attachments.ts+++ b/backend/src/superTabs/attachments.ts@@ -6,8 +6,29 @@ import { z } from 'zod'/** 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 }-export const MAX_ATTACHMENT_BYTES = 10 * 1024 * 1024+/** One chat file, whichever way it comes. Every client checks the same number before it sends (attachments.limits.test.ts). */+export const MAX_ATTACHMENT_BYTES = 256 * 1024 * 1024+/** The most a file sent in a multipart form to this server may be. Production sits behind Cloudflare, whose plans below+ * Business refuse a request body over 100 MB, and an ingress whose body limit the repo does not set; 10 MB is what that+ * path has carried since #1490. A bigger file goes straight to the bucket on an upload link (uploadLink below). */+export const MAX_FORM_ATTACHMENT_BYTES = 10 * 1024 * 1024export const MAX_ATTACHMENTS = 10+/** How long an upload link may be started: storage checks it when a request begins, so a long transfer that started in time finishes. */+export const UPLOAD_LINK_MS = 10 * 60_000+/** The `purpose` of an upload whose link was handed out and whose bytes the server has not yet checked. Servers before this+ * one refuse a row with any purpose as a message's file, so a rollout never sends a file that has not arrived. */+export const PENDING_UPLOAD_PURPOSE = 'pending-upload'+/** An unfinished upload the sweep has claimed (lib/pendingUploadSweep.ts): its stored file is being removed, so it can no+ * longer be finished or sent. */+export const REMOVING_UPLOAD_PURPOSE = 'removing-upload'+export const TOO_LARGE_MESSAGE = 'Files can be up to 256 MB.'+/** Uploads a sender may start in a Swarm in an hour, and their bytes: bucket space for files that may never be sent. */+export const HOURLY_UPLOADS = 200+export const HOURLY_UPLOAD_BYTES = 4 * 1024 * 1024 * 1024+/** A link's upload never finished is removed, with what it stored, this long after the link was made: an hour after it expired. */+export const PENDING_UPLOAD_LIFE_MS = UPLOAD_LINK_MS + 3_600_000+/** The form route's own refusal, seen only by a client from before upload links. */+export const FORM_TOO_LARGE_MESSAGE = 'Update Harness to send files over 10 MB. Files can be up to 256 MB.'/** An avatar is a small picture: Desktop resizes it before upload, and the backend still holds it to this. */export const MAX_AVATAR_BYTES = 1024 * 1024export const AVATAR_TYPES: ReadonlySet<string> = new Set(['image/png', 'image/jpeg', 'image/webp'])@@ -19,9 +40,39 @@ export const attachmentName = z.string().trim().min(1).max(255).refine(value =>export const attachmentMime = z.string().trim().toLowerCase().max(200).regex(/^[a-z0-9][a-z0-9!#$&^_.+-]*\/[a-z0-9][a-z0-9!#$&^_.+-]*$/)export class AttachmentTooLarge extends Error {- constructor(cap = MAX_ATTACHMENT_BYTES) { super(`A file can be at most ${cap / 1024 / 1024} MB.`) }+ constructor(cap = MAX_ATTACHMENT_BYTES) {+ super(cap === MAX_ATTACHMENT_BYTES ? TOO_LARGE_MESSAGE : cap === MAX_FORM_ATTACHMENT_BYTES ? FORM_TOO_LARGE_MESSAGE : `A file can be at most ${cap / 1024 / 1024} MB.`)+ }}+/** A link that writes one object once, straight to storage, and the headers its request must carry unchanged. */+export interface UploadLink { url: string; headers: Record<string, string> }++/** A bucket the client can write to directly. Each link names one object, which must not exist yet, of exactly `size` bytes,+ * served as a download; storage itself refuses any other size, a second write, a changed header, or a start after `expiresAt`. */+export interface DirectUploads {+ uploadLink(objectKey: string, file: { name: string }, size: number, expiresAt: number): Promise<UploadLink>+ /** The stored object's size, or null while nothing is there. */+ stored(objectKey: string): Promise<{ size: number } | null>+ /** Its first `bytes` bytes. */+ head(objectKey: string, bytes: number): Promise<Buffer>+ /** Removes it; an object already gone counts as removed. */+ delete(objectKey: string): Promise<void>+}+export const directUploads = (store: AttachmentStore): DirectUploads | null =>+ 'uploadLink' in store && typeof (store as Partial<DirectUploads>).uploadLink === 'function' ? store as AttachmentStore & DirectUploads : null++/** The headers an upload link signs. The bytes are not seen before they are served, so they are always a download, whatever+ * type is declared; the message keeps the declared type (an image's checked from its first bytes) for clients to show. */+export function linkHeaders(name: string, size: number, cacheControl: string): Record<string, string> {+ return { 'content-type': 'application/octet-stream', 'content-disposition': served(name, 'application/octet-stream').contentDisposition,+ 'cache-control': cacheControl, 'x-goog-content-length-range': `${size},${size}`, 'x-goog-if-generation-match': '0' }+}+/** A storage error's code or HTTP status, for a log line: its text can quote the object's key, which is the file's link. */+export const errorCode = (error: unknown): string | number | null =>+ error && typeof error === 'object' && 'code' in error && (typeof error.code === 'string' || typeof error.code === 'number') ? error.code : null+export const CHAT_CACHE_CONTROL = 'public, max-age=31536000, immutable'+/** 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. */@@ -99,6 +150,9 @@ export async function checkedType(mime: string, body: Readable): Promise<{ mime:return { mime: peeked.type ?? 'application/octet-stream', body: peeked.body }}+/** The type a checked upload keeps: a declared raster image only when its first bytes agree, as checkedType decides for a form. */+export const typeFromHead = (mime: string, head: Buffer) => INLINE.has(mime) ? imageTypeOf(head) ?? 'application/octet-stream' : mime+/** 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@@ -128,10 +182,10 @@ export function serviceAccountFrom(raw: string): ServiceAccount | null {credentials: { client_email: key.client_email as string, private_key: key.private_key as string } }}-export class GcsAttachmentStore implements AttachmentStore {+export class GcsAttachmentStore implements AttachmentStore, DirectUploads {private bucket: Promise<import('@google-cloud/storage').Bucket> | null = nullconstructor(private readonly name: string, private readonly account: ServiceAccount | null = null,- private readonly cacheControl = 'public, max-age=31536000, immutable') {}+ private readonly cacheControl = CHAT_CACHE_CONTROL) {}// Loaded on first use, so a backend without a bucket never loads the client.protected files() {this.bucket ??= import('@google-cloud/storage').then(({ Storage }) => new Storage(this.account ?? undefined).bucket(this.name))@@ -144,6 +198,28 @@ export class GcsAttachmentStore implements AttachmentStore {metadata: { contentDisposition, cacheControl: this.cacheControl } })return capped(body, cap, sink)}+ /** A V4 signed PUT: the signature covers every header below, so storage refuses a request that drops or changes one. */+ async uploadLink(objectKey: string, file: { name: string }, size: number, expiresAt: number): Promise<UploadLink> {+ const { 'content-type': contentType, ...extensionHeaders } = linkHeaders(file.name, size, this.cacheControl)+ const [url] = await (await this.files()).file(objectKey).getSignedUrl({ version: 'v4', action: 'write', expires: expiresAt, contentType, extensionHeaders })+ return { url, headers: { 'content-type': contentType!, ...extensionHeaders } }+ }+ async stored(objectKey: string) {+ try {+ const [metadata] = await (await this.files()).file(objectKey).getMetadata()+ return { size: Number(metadata.size) }+ } catch (error) {+ if (error && typeof error === 'object' && 'code' in error && error.code === 404) return null+ throw error+ }+ }+ async head(objectKey: string, bytes: number) {+ const [content] = await (await this.files()).file(objectKey).download({ start: 0, end: bytes - 1 })+ return content+ }+ async delete(objectKey: string) {+ await (await this.files()).file(objectKey).delete({ ignoreNotFound: true })+ }}/** Avatars in a bucket that grants nobody read access: each read hands out V4 signed links instead (avatarLinks.ts). */@@ -162,14 +238,47 @@ export class CdnAvatarStore implements AvatarStore {async signedUrl(objectKey: string) { return publicUrl(this.publicBase, objectKey) }}-export class MemoryAttachmentStore implements AttachmentStore {- readonly objects = new Map<string, { bytes: Buffer; contentType: string; contentDisposition: string }>()+export class MemoryAttachmentStore implements AttachmentStore, DirectUploads {+ readonly objects = new Map<string, { bytes: Buffer; contentType: string; contentDisposition: string; cacheControl?: string }>()+ private readonly linkSecret = randomBytes(32)+ constructor(private readonly now: () => number = Date.now) {}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}+ private linkSignature(objectKey: string, expiresAt: number, headers: Record<string, string>) {+ return createHmac('sha256', this.linkSecret).update(JSON.stringify([objectKey, expiresAt, Object.entries(headers).sort()])).digest('hex')+ }+ async uploadLink(objectKey: string, file: { name: string }, size: number, expiresAt: number): Promise<UploadLink> {+ const headers = linkHeaders(file.name, size, CHAT_CACHE_CONTROL)+ const url = `https://storage.memory.test/${encodeURIComponent(objectKey)}?expires=${expiresAt}&signature=${this.linkSignature(objectKey, expiresAt, headers)}`+ return { url, headers }+ }+ /** What the bucket answers a PUT to `url`, with storage's rules: the status, and the object written only on 200. */+ async receive(url: string, headers: Record<string, string>, body: Readable | Buffer): Promise<number> {+ const link = new URL(url), objectKey = decodeURIComponent(link.pathname.slice(1)), expiresAt = Number(link.searchParams.get('expires'))+ const lower = Object.fromEntries(Object.entries(headers).map(([k, v]) => [k.toLowerCase(), v]))+ const signed = Object.fromEntries(['content-type', 'content-disposition', 'cache-control', 'x-goog-content-length-range', 'x-goog-if-generation-match']+ .flatMap(k => lower[k] === undefined ? [] : [[k, lower[k]!]]))+ const drain = async () => { if (!Buffer.isBuffer(body)) body.resume() }+ if (!(expiresAt > this.now()) || link.searchParams.get('signature') !== this.linkSignature(objectKey, expiresAt, signed) || lower.authorization) { await drain(); return 403 }+ if (signed['x-goog-if-generation-match'] === '0' && this.objects.has(objectKey)) { await drain(); return 412 }+ const [min, max] = (signed['x-goog-content-length-range'] ?? '').split(',').map(Number)+ const chunks: Buffer[] = []+ let size = 0+ try {+ size = await capped(Buffer.isBuffer(body) ? Readable.from([body]) : body, max ?? Infinity, new Writable({ write(chunk: Buffer, _encoding, done) { chunks.push(chunk); done() } }))+ } catch (error) { if (error instanceof AttachmentTooLarge) return 400; throw error }+ if (min !== undefined && size < min) return 400+ this.objects.set(objectKey, { bytes: Buffer.concat(chunks), contentType: signed['content-type']!, contentDisposition: signed['content-disposition']!,+ cacheControl: signed['cache-control'] })+ return 200+ }+ async stored(objectKey: string) { const object = this.objects.get(objectKey); return object ? { size: object.bytes.byteLength } : null }+ async head(objectKey: string, bytes: number) { return (this.objects.get(objectKey)?.bytes ?? Buffer.alloc(0)).subarray(0, bytes) }+ async delete(objectKey: string) { this.objects.delete(objectKey) }}/** Avatars for tests and the local rig: links carry their expiry and an HMAC of it, and `open` honours both as the bucket would. */diff --git a/backend/src/superTabs/store.ts b/backend/src/superTabs/store.tsindex 4806f6325..28323d4fe 100644--- a/backend/src/superTabs/store.ts+++ b/backend/src/superTabs/store.ts@@ -16,7 +16,7 @@ import { reactionCounts, type ReactionTarget } from './reactions.js'import { agentOpenDeliveries, compactedDelivery, deliveredCopies, messagesById, messagesPast, OPEN_DELIVERY, type MessageEdge, pageDeliveries, pageReactions, pageThreads, refreshReplies, type PageDelivery } from './pageReads.js'import { restoreDelivery } from './deliveryCompaction.js'import { threadSummaries } from './threads.js'-import { attachmentMime, attachmentName, AttachmentTooLarge, AVATAR_PURPOSE, AVATAR_TYPES, checkedType, MAX_ATTACHMENT_BYTES, MAX_AVATAR_BYTES, objectKeyFor, peekType, publicUrl, trimPrefix,+import { attachmentMime, attachmentName, AttachmentTooLarge, AVATAR_PURPOSE, AVATAR_TYPES, checkedType, directUploads, errorCode, HOURLY_UPLOAD_BYTES, HOURLY_UPLOADS, MAX_ATTACHMENT_BYTES, MAX_AVATAR_BYTES, MAX_FORM_ATTACHMENT_BYTES, objectKeyFor, peekType, PENDING_UPLOAD_PURPOSE, publicUrl, TOO_LARGE_MESSAGE, trimPrefix, typeFromHead, UPLOAD_LINK_MS,type Attachment, type Attachments, type AttachmentStore, type AvatarStore } from './attachments.js'import { randomBytes } from 'node:crypto'import type { Readable } from 'node:stream'@@ -1725,10 +1725,100 @@ export class SuperTabStore {if (!name.success || !mime.success) fail('INVALID_ATTACHMENT', 'Attach a file with a printable name and a content type.', 400)const key = await this.uploader(tabId, tx => this.poster(tx, user, tabId, conversationId, asAgentId).then(p => p.actor))const row = await this.keep(attachments.store, attachments.prefix, tabId, key, { name: name.data, conversationId },- async () => checkedType(mime.data, file.body), file.body, MAX_ATTACHMENT_BYTES)+ async () => checkedType(mime.data, file.body), file.body, MAX_FORM_ATTACHMENT_BYTES)return { attachment: { id: row.id, name: row.name, mime: row.mime, size: row.size, url: publicUrl(attachments.publicBase, row.objectKey) } satisfies Attachment }}+ /** A link to put one file of `size` bytes straight into the bucket, for a file too big for this server's form route. The+ * checks are upload()'s: the actor may post in this conversation and is under its hourly allowance, before any link is+ * signed. The row is written pending: no message can name it until completeUpload() has seen the stored bytes. An upload+ * never completed, like an unsent file, is an unused row the unsent-file sweep removes with its object (#2268). */+ async uploadLink(user: AuthUser, tabId: string, conversationId: string, file: { name: string; mime: string; size: number }, asAgentId?: string) {+ const attachments = this.attachments ?? fail('ATTACHMENTS_UNAVAILABLE', 'File attachments are not available on this server.', 503)+ const direct = directUploads(attachments.store) ?? fail('ATTACHMENTS_UNAVAILABLE', 'Files this big cannot be sent to this server.', 503)+ const name = attachmentName.transform(value => redactCredentials(value).text).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)+ if (!Number.isSafeInteger(file.size) || file.size < 1) fail('INVALID_ATTACHMENT', 'Name the file\'s size in bytes.', 400)+ if (file.size > MAX_ATTACHMENT_BYTES) fail('ATTACHMENT_TOO_LARGE', TOO_LARGE_MESSAGE, 413)+ const objectKey = objectKeyFor(attachments.prefix, tabId, name.data)+ // The pending row is written before any link is signed, in the transaction that counts the sender's last hour. Each request+ // first writes the sender's allowance row there, so two at once conflict and one retries after the other commits: parallel+ // requests stop at the limits. The row is made outside it once, since a duplicate key is not retried and a conflict is.+ const { key, allowance } = await transaction(this.db, async tx => {+ const { actor } = await this.poster(tx, user, tabId, conversationId, asAgentId)+ const key = actorKey(actor)+ return { key, allowance: `${tabId}:${key}` }+ })+ const counted = () => transaction(this.db, async tx => {+ await this.poster(tx, user, tabId, conversationId, asAgentId)+ await tx.superTabUploadAllowance.update({ where: { id: allowance }, data: { at: new Date(this.now()) } })+ const recent = await tx.superTabAttachment.findMany({ where: { tabId, actorKey: key, createdAt: { gte: new Date(this.now() - 3_600_000) } }, select: { size: true } })+ if (recent.length >= HOURLY_UPLOADS) fail('RATE_LIMITED', `You attached ${HOURLY_UPLOADS} files in the last hour. Wait before attaching more.`, 429)+ if (recent.reduce((sum, r) => sum + r.size, 0) + file.size > HOURLY_UPLOAD_BYTES) {+ fail('RATE_LIMITED', 'You attached 4 GB of files in the last hour. Wait before attaching more.', 429)+ }+ return tx.superTabAttachment.create({ data: { id: randomBytes(12).toString('hex'), tabId, conversationId, actorKey: key,+ name: name.data, mime: mime.data, size: file.size, objectKey, purpose: PENDING_UPLOAD_PURPOSE } })+ })+ // The sweep may remove the allowance row (an hour unused) between its create and the update: made again, a few times.+ let row: Awaited<ReturnType<typeof counted>> | undefined+ for (let attempt = 1; !row; attempt++) {+ await this.db.superTabUploadAllowance.create({ data: { id: allowance, at: new Date(this.now()) } }).catch(error => { if (errorCode(error) !== 'P2002') throw error })+ try { row = await counted() } catch (error) { if (errorCode(error) !== 'P2025' || attempt === 3) throw error }+ }+ const expiresAt = this.now() + UPLOAD_LINK_MS+ let link: { url: string; headers: Record<string, string> }+ try { link = await direct.uploadLink(objectKey, { name: name.data }, file.size, expiresAt) } catch (error) {+ // The signing error's text is never logged: it may carry the object's key, which is the file's link.+ logger.error('super-tab upload link failed', { tabId, code: errorCode(error) })+ // No link was handed out, so nothing can write the object: the row goes now, not with the sweep.+ await this.db.superTabAttachment.deleteMany({ where: { id: row.id, tabId, purpose: PENDING_UPLOAD_PURPOSE } }).catch(() => {})+ fail('ATTACHMENTS_UNAVAILABLE', 'Could not prepare the upload just now. Try again.', 503)+ }+ return { upload: { id: row.id, url: link.url, method: 'PUT' as const, headers: link.headers, expiresAt } }+ }++ /** Makes a link's upload sendable once its bytes are in the bucket: only by the actor that asked for the link, while it may+ * still post in that conversation, and only when storage holds exactly the size it asked for. An image keeps its type only+ * when its first bytes agree. Answered again, the same way, after a lost answer. */+ async completeUpload(user: AuthUser, tabId: string, uploadId: string, asAgentId?: string) {+ const attachments = this.attachments ?? fail('ATTACHMENTS_UNAVAILABLE', 'File attachments are not available on this server.', 503)+ const direct = directUploads(attachments.store) ?? fail('ATTACHMENTS_UNAVAILABLE', 'Files this big cannot be sent to this server.', 503)+ // Someone else's upload, another Swarm's and one that never was answer alike, so nobody learns that it exists.+ const unavailable = () => fail('ATTACHMENT_UNAVAILABLE', 'Attach this file again before sending it.', 400)+ const row = await transaction(this.db, async tx => {+ const { state } = await this.load(tx, user, tabId, {})+ const actor = await this.actor(tx, user, state, asAgentId)+ const found = await tx.superTabAttachment.findFirst({ where: { tabId, id: uploadId } })+ if (!found || found.actorKey !== actorKey(actor) || found.usedBy || (found.purpose && found.purpose !== PENDING_UPLOAD_PURPOSE)) unavailable()+ // Access may have gone while the bytes moved: the actor must still be able to post there.+ await this.poster(tx, user, tabId, found!.conversationId, asAgentId)+ return found!+ })+ const sendable = (mime: string) => ({ attachment: { id: row.id, name: row.name, mime, size: row.size, url: publicUrl(attachments.publicBase, row.objectKey) } satisfies Attachment })+ if (!row.purpose) return sendable(row.mime)+ let stored: { size: number } | null, head: Buffer+ try {+ stored = await direct.stored(row.objectKey)+ head = stored && stored.size === row.size ? await direct.head(row.objectKey, 16) : Buffer.alloc(0)+ } catch (error) {+ logger.error('super-tab upload check failed', { tabId, code: errorCode(error) })+ fail('ATTACHMENTS_UNAVAILABLE', 'Could not check the file just now. Try again.', 503)+ }+ if (!stored) fail('UPLOAD_INCOMPLETE', 'The file did not finish uploading. Try again.', 409)+ if (stored!.size !== row.size) {+ // Storage enforces the size the link signed, so this is never expected; the object goes and the row stays for the sweep.+ await direct.delete(row.objectKey).catch(() => {})+ unavailable()+ }+ const mime = typeFromHead(row.mime, head!)+ const finished = await this.db.superTabAttachment.updateMany({ where: { id: row.id, tabId, purpose: PENDING_UPLOAD_PURPOSE }, data: { purpose: { unset: true }, mime } })+ if (finished.count === 1) return sendable(mime)+ // Another finish of the same upload won: the same answer. The sweep claimed it first: its file is going, so it is refused.+ const now = await this.db.superTabAttachment.findFirst({ where: { id: row.id, tabId } })+ return now && !now.purpose && !now.usedBy ? sendable(now.mime) : unavailable()+ }+/** A picture for a person's or an agent's avatar (profile.ts): png, jpg or webp by its real bytes, at most 1 MB. Any* member who may write uploads one; the command that sets it decides whose it becomes. */async uploadAvatar(user: AuthUser, tabId: string, file: { body: Readable }, asAgentId?: string) {diff --git a/backend/src/worker.ts b/backend/src/worker.tsindex 456f71f10..a8219733c 100644--- a/backend/src/worker.ts+++ b/backend/src/worker.ts@@ -32,6 +32,7 @@ import { env } from './config/env.js'import { machineBillingWorkerService } from './services/MachineBillingWorkerService.js'import { productUsagePeopleRollupService } from './services/ProductUsagePeopleRollupService.js'import { startReceiptSweep } from './lib/productUsageReceiptSweep.js'+import { startPendingUploadSweep } from './lib/pendingUploadSweep.js'import { startRoutingReflection } from './lib/routingReflection.js'import { logger } from './utils/logger.js'@@ -71,6 +72,7 @@ async function start(): Promise<void> {let stopCompaction = (): void => {}let stopThreadBackfill = (): void => {}let stopReceiptSweep = (): void => {}+ let stopPendingUploads = (): void => {}let stopReflection = (): void => {}const shutdown = (signal: string): void => {logger.info(`Received ${signal}, stopping backend worker...`)@@ -84,6 +86,7 @@ async function start(): Promise<void> {stopDeliveries()stopCompaction()stopReceiptSweep()+ stopPendingUploads()stopReflection()stopThreadBackfill()// The last partial minute, before the database closes.@@ -98,6 +101,8 @@ async function start(): Promise<void> {productUsagePeopleRollupService.start()// Usage receipts from when they lived 36 days, a few at a time until none are left (lib/productUsageReceiptSweep.ts).stopReceiptSweep = startReceiptSweep(prisma)+ // Uploads begun on a link and never finished go an hour after the link expired, with what they stored (lib/pendingUploadSweep.ts).+ stopPendingUploads = startPendingUploadSweep(prisma, env)// The worker's sweeps and archive write Swarms: they bump the stamps the API processes read by. It reads too little to keep a cache.configureSwarmStamps(redisSwarmStamps(), { reads: false })// Archive notes and Workspace removals write messages too: their recipients' hosts hear of them at once, and of thediff --git a/cli/src/core/main.ts b/cli/src/core/main.tsindex 2d09f148b..f18c1a9d4 100644--- a/cli/src/core/main.ts+++ b/cli/src/core/main.ts@@ -2202,7 +2202,9 @@ async function runForeground(session: AuthSession | null): Promise<void> {onProductFeedback: (body) => proxyBackend('POST', '/api/product-usage/feedback', body),onSignInAnswer: (action, body) => proxyBackend('POST', `/api/auth/qr/${action}`, body),...(swarm ? { onSuperTabAttachment: (req, res, path) => swarm.forwardAttachmentUpload(req, res, path,- { accessToken: () => auth.accessToken(), environment: autonomousEnv, base: backendHttpBase() }) } : {}),+ { accessToken: () => auth.accessToken(), environment: autonomousEnv, base: backendHttpBase() }),+ // A file over 10 MB: its signed link and its completion, with the account's token; the bytes go straight to storage.+ onSuperTabAttachmentUpload: (path, body) => proxyBackend('POST', path, body) } : {}),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 970780f91..5a06da7f8 100644--- a/cli/src/hookServer.spec.ts+++ b/cli/src/hookServer.spec.ts@@ -496,8 +496,45 @@ describe('Super Tab attachment pass-through', () => {expect(await r.json()).toEqual({ path: '/api/super-tabs/tab-1/avatars', bytes: 7 })})+ // Files over 10 MB go straight to storage (contract of group 1604): the daemon asks the backend for the link and says the+ // upload is complete, with the account's token; the bytes never pass through it.+ it('passes a direct upload\'s link request and completion on, guarded like the other writes', async () => {+ const forward = vi.fn(async (path: string, body: unknown) => ({ status: 200, body: { success: true, data: { path, body } } }))+ const { base } = await start({ onSuperTabAttachmentUpload: forward })+ const headers = { 'x-adapter-local': '1', 'content-type': 'application/json' }+ const ask = { conversationId: 'c1', name: 'AC4 - 26 Oct v2.step', mime: 'application/octet-stream', size: 123456789 }+ const link = `${base}/api/super-tabs/tab-1/attachments/uploads`, complete = `${link}/0123456789abcdef01234567/complete`+ for (const url of [link, complete]) {+ for (const h of [{ 'content-type': 'application/json' }, { ...headers, origin: 'https://untrusted.example' }]) {+ expect((await fetch(url, { method: 'POST', headers: h, body: JSON.stringify(ask) })).status).toBe(403)+ }+ }+ // Only the two upload paths: no other path, encoded or not, reaches the backend with this account's token.+ for (const url of [`${base}/api/super-tabs/../attachments/uploads`, `${link}/../x/complete`, `${link}/u1`, `${link}/u1/complete/x`,+ `${link}/u1%2F..%2F..%2Fcommands/complete`, `${base}/api/super-tabs/tab-1%2Fcommands%3F/attachments/uploads`, `${link}/%2e%2e/complete`,+ `${base}/api/super-tabs/tab-1/commands`, `${base}/api/super-tabs/tab-1/attachments/uploads/u1/complete/../../../commands`]) {+ expect((await fetch(url, { method: 'POST', headers, body: '{}' })).status).toBe(404)+ }+ expect((await fetch(link, { method: 'POST', headers, body: 'not json' })).status).toBe(400)+ expect((await fetch(link, { method: 'POST', headers, body: '[1]' })).status).toBe(400)+ expect(forward).not.toHaveBeenCalled()+ const asked = await fetch(`${link}?asAgentId=agent-1&other=x`, { method: 'POST', headers, body: JSON.stringify({ ...ask, command: { type: 'member.remove' } }) })+ expect(asked.status).toBe(200)+ expect(await asked.json()).toEqual({ success: true, data: { path: '/api/super-tabs/tab-1/attachments/uploads?asAgentId=agent-1', body: ask } })+ // Completion's body is {}, and an empty one is read as that.+ const done = await fetch(`${complete}?asAgentId=../x`, { method: 'POST', headers })+ expect(await done.json()).toEqual({ success: true, data: { path: '/api/super-tabs/tab-1/attachments/uploads/0123456789abcdef01234567/complete', body: {} } })+ // The backend's refusal, as it said it.+ forward.mockResolvedValueOnce({ status: 413, body: { success: false, error: { code: 'ATTACHMENT_TOO_LARGE', message: 'Files can be up to 256 MB.' } } } as never)+ const refused = await fetch(link, { method: 'POST', headers, body: JSON.stringify({ ...ask, size: 256 * 1024 * 1024 + 1 }) })+ expect(refused.status).toBe(413)+ expect(await refused.json()).toEqual({ success: false, error: { code: 'ATTACHMENT_TOO_LARGE', message: 'Files can be up to 256 MB.' } })+ })+it('is unavailable on a daemon without it', async () => {const { base } = await start({})+ expect((await fetch(`${base}/api/super-tabs/tab-1/attachments/uploads`, { method: 'POST',+ headers: { 'x-adapter-local': '1', 'content-type': 'application/json' }, body: '{}' })).status).toBe(503)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)})diff --git a/cli/src/hookServer.ts b/cli/src/hookServer.tsindex 796d4a4ad..be4b23da5 100644--- a/cli/src/hookServer.ts+++ b/cli/src/hookServer.ts@@ -198,6 +198,9 @@ export interface HookServerHandlers {/** 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>+ /** A chat file over 10 MB goes straight to storage (superTabs/attach.ts): its link asked for, and its upload said complete,+ * with this computer's account. Small JSON both ways; the bytes never pass through here. */+ onSuperTabAttachmentUpload?: (path: string, body: Record<string, unknown>) => Promise<PairOutcome>onProductUsageReport?: (body: unknown) => Promise<PairOutcome>onProductUsageRead?: () => Promise<PairOutcome>onProductUsageWrite?: (body: unknown) => Promise<PairOutcome>@@ -1121,6 +1124,21 @@ export function startHookServer(const agent = asAgentId && /^[A-Za-z0-9_-]{1,160}$/.test(asAgentId) ? `?asAgentId=${asAgentId}` : ''await handlers.onSuperTabAttachment(req, res, `${url}${agent}`); return}+ const direct = req.method === 'POST'+ ? /^\/api\/super-tabs\/[A-Za-z0-9_-]{1,160}\/attachments\/uploads(\/[A-Za-z0-9_-]{1,160}\/complete)?$/.exec(url) : null+ if (direct) {+ if (!localOk) { json(403, { error: 'FORBIDDEN' }); return }+ if (!handlers.onSuperTabAttachmentUpload) { json(503, { error: 'UNAVAILABLE' }); return }+ // A link's request names the file ({conversationId, name, mime, size}); a completion's is {}, and may be empty.+ let body: unknown+ try { const raw = await readBody(req, 8192); body = direct[1] && !raw.trim() ? {} : JSON.parse(raw) } catch { body = null }+ if (!body || typeof body !== 'object' || Array.isArray(body)) { json(400, { error: 'BAD_REQUEST' }); return }+ const asAgentId = new URLSearchParams((req.url ?? '').split('?')[1] ?? '').get('asAgentId')+ const agent = asAgentId && /^[A-Za-z0-9_-]{1,160}$/.test(asAgentId) ? `?asAgentId=${asAgentId}` : ''+ // Only the fields a link's request has: nothing else the page sends reaches the backend with this account's token.+ const { conversationId, name, mime, size } = body as Record<string, unknown>+ await proxied(() => handlers.onSuperTabAttachmentUpload!(`${url}${agent}`, direct[1] ? {} : { conversationId, name, mime, size })); 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/buddyGuard.spec.ts b/cli/src/lib/buddyGuard.spec.tsindex 159886c17..4a4318273 100644--- a/cli/src/lib/buddyGuard.spec.ts+++ b/cli/src/lib/buddyGuard.spec.ts@@ -337,6 +337,19 @@ describe('a Buddy\'s guard (Ken, 10-29: reads without a prompt, refuses everythiexpect(permissionDecisionReason).toContain("harness super-tab post GROUP 'your message' OPERATION_ID")expect(permissionDecisionReason).toContain('in double quotes when it holds an apostrophe')})+ // A Buddy's own files are checked for secrets whole before they go, so they stay at the 10 MB the guard reads: a larger one+ // would now go by a link, with only its first 10 MB checked.+ it('refuses to attach a file of its folder over 10 MB, and says so', () => {+ const big = join(root, 'big.log')+ writeFileSync(big, 'start\n'); truncateSync(big, 10 * 1024 * 1024 + 1)+ try {+ const { permissionDecision, permissionDecisionReason } = refusal('harness super-tab --tab t post chat x op-1 --attach big.log')+ expect(permissionDecision).toBe('deny')+ expect(permissionDecisionReason).toContain('up to 10 MB')+ truncateSync(big, 10 * 1024 * 1024)+ expect(bash('harness super-tab --tab t post chat x op-1 --attach big.log')).toBe('allow')+ } finally { rmSync(big) }+ })// The fix it names goes through: a message with an apostrophe, the one a Buddy might have sent on stdin, in double quotes.it('sends the message the refusal tells it to, in double quotes when it holds an apostrophe', () => {expect(bash('harness super-tab --tab t post chat "it\'s done: the - case is refused" op-1 --reply-to m1')).toBe('allow')@@ -636,12 +649,25 @@ describe('the host\'s list of what a Buddy\'s person sent it', () => {['a file with a second name', () => { const twin = join(drops, 'aaaa0004-twin'); rmSync(twin, { force: true }); linkSync(later, twin); return later }],['a folder', () => drops],['a file that is gone', () => join(drops, 'aaaa0005-gone.png')],- ['a file larger than a message\'s file can be', () => { const big = join(drops, 'aaaa0006-big'); writeFileSync(big, Buffer.alloc(10 * 1024 * 1024 + 1)); return big }],+ // Past the 256 MB a chat file can be: sparse, so it takes no room.+ ['a file larger than a message\'s file can be', () => { const big = join(drops, 'aaaa0006-big'); writeFileSync(big, ''); truncateSync(big, 256 * 1024 * 1024 + 1); return big }],])('lists no %s', (_, path) => {allowBuddyReads(mine, { session: 'harness-1', files: [sent, path()], links: [] }, 1_000)expect(held().files).toEqual([{ ...identity(sent), at: 1_000 }])})+ // A chat file may be 256 MB since files over 10 MB go straight to storage: one past the old 10 MB is its person's too. Its+ // bytes are hashed 64 KiB at a time, never held whole.+ it('lists a file past the old 10 MB limit, and the guard lets the Buddy read it', () => {+ const big = join(drops, 'aaaa0007-model.step')+ writeFileSync(big, 'head'); truncateSync(big, 20 * 1024 * 1024)+ const now = Date.now()+ allowBuddyReads(mine, { session: 'harness-1', files: [big], links: [] }, now)+ expect(held().files).toEqual([{ ...identity(big), at: now }])+ expect(decide('Read', { file_path: big }, guard)).toBe('allow')+ rmSync(big)+ })+it('lists only claude.ai Artifact links', () => {allowBuddyReads(mine, { session: 'harness-1', files: [], links: ['https://example.com/artifact/x', 'https://claude.ai/artifact/ok', 'http://claude.ai/artifact/x','https://claude.ai/artifact/x?v=1', 'https://claude.ai/chat/x'] }, 1_000)diff --git a/cli/src/lib/buddyGuard.ts b/cli/src/lib/buddyGuard.tsindex 82dbd15e2..c98e1cc22 100644--- a/cli/src/lib/buddyGuard.ts+++ b/cli/src/lib/buddyGuard.ts@@ -563,13 +563,18 @@ function decoded(text) {}const SECRET = (kind) => 'This holds what looks like ' + kind + ', so nothing was sent, and nobody will be asked. Take it out and ' +'send again: never pass on secrets, tokens, keys or connection strings.'-// A file to attach, in the folder (outward refused any other): its first 10 MB, the most a chat file holds, read as text.-// One that is not there holds nothing, as sending it fails anyway; one there that cannot be read is refused.+// A file to attach, in the folder (outward refused any other), read whole as text to be checked for secrets. A Buddy's files+// stay at 10 MB, the form upload's size: a chat file may be 256 MB now, but one past 10 MB would go out with only its+// start checked, so it is refused. One that is not there holds nothing, as sending it fails anyway; one there that cannot+// be read is refused.+const ATTACH_MAX_BYTES = 10 * 1024 * 1024+const TOO_LARGE = 'A Buddy attaches files of up to 10 MB, so nothing was sent, and nobody will be asked. Attach a smaller file.'function fileText(path) {let fdtry {fd = openSync(resolve(ROOT, path), constants.O_RDONLY)- const buffer = Buffer.alloc(10 * 1024 * 1024), read = readSync(fd, buffer, 0, buffer.length, 0)+ const buffer = Buffer.alloc(ATTACH_MAX_BYTES + 1), read = readSync(fd, buffer, 0, buffer.length, 0)+ if (read > ATTACH_MAX_BYTES) { reason = TOO_LARGE; return null }return buffer.subarray(0, read).toString('utf8')} catch (error) { return error?.code === 'ENOENT' ? '' : null } finally { if (fd !== undefined) closeSync(fd) }}@@ -846,9 +851,9 @@ const MARK = /\.[0-9a-f]{64}\.owner$//** A message holds at most ten files (superTabs/attachments.ts): ten messages' worth, and as many links. */const MAX_FILES = 100const MAX_LINKS = 50-/** The backend's per-file limit (superTabs/attachments.ts MAX_ATTACHMENT_BYTES): no download is larger, so nothing larger- * is read whole to be listed. */-const MAX_BYTES = 10 * 1024 * 1024+/** The backend's per-file limit (superTabs/attachments.ts MAX_ATTACHMENT_BYTES, 256 MB): no download is larger, so nothing+ * larger is listed. A listed file is never read whole: its bytes are hashed 64 KiB at a time, here and in the guard. */+const MAX_BYTES = 256 * 1024 * 1024/** A claude.ai Artifact link as the guard compares it (`artifactLink` in the guard above, the same rules), or null. */function artifactLink(text: string): string | null {diff --git a/cli/src/lib/pasteDropFiles.ts b/cli/src/lib/pasteDropFiles.tsindex 9142d6167..09f567355 100644--- a/cli/src/lib/pasteDropFiles.ts+++ b/cli/src/lib/pasteDropFiles.ts@@ -11,8 +11,10 @@* Both need the same thing: a durable-enough file and a bound on how much accumulates over time.*/import { randomUUID } from 'node:crypto'-import { mkdir, readdir, rm, stat, writeFile } from 'node:fs/promises'+import { constants, createWriteStream } from 'node:fs'+import { copyFile, mkdir, readdir, rm, stat, writeFile } from 'node:fs/promises'import { join } from 'node:path'+import { pipeline } from 'node:stream/promises'import { env } from '../config/env.js'/** Where they land; a Buddy's guard reads its own person's files there (lib/buddyGuard.ts). */@@ -64,7 +66,38 @@ export async function writePasteImageFile(bytes: Uint8Array): Promise<string> {* `.../a1b2c3d4-report.pdf` rather than an opaque id. Used by `pasteFile()` for a dropped file. */export async function writePasteDropFile(originalFilename: string, bytes: Uint8Array): Promise<string> {await ensureDir()- const path = join(PASTE_DROPS_DIR, `${randomUUID().slice(0, 8)}-${sanitizeFilename(originalFilename)}`)+ const path = dropPath(originalFilename)await writeFile(path, bytes)return path}++const dropPath = (originalFilename: string) => join(PASTE_DROPS_DIR, `${randomUUID().slice(0, 8)}-${sanitizeFilename(originalFilename)}`)++/** As `writePasteDropFile`, written as [source] yields, never held whole: a Super Tab chat file of up to 256 MB+ * (superTabs/attachments.ts). A source that throws (past its size, short, stalled) leaves no file, not even part of one. */+export async function writePasteDropStream(originalFilename: string, source: AsyncIterable<Uint8Array>): Promise<string> {+ await ensureDir()+ const path = dropPath(originalFilename)+ try {+ await pipeline(source, createWriteStream(path, { flags: 'wx' }))+ } catch (error) {+ await rm(path, { force: true }).catch(() => {})+ throw error+ }+ return path+}++/** A copy of [source], a file in this folder, under its own name: each delivery of a file two agents were sent has its own,+ * so one agent editing it never changes the other's (nor its Buddy guard's hash of it). A clone that takes no room where the+ * disk can (APFS, btrfs), a copy elsewhere. A failed copy leaves no file. */+export async function copyPasteDropFile(source: string, originalFilename: string): Promise<string> {+ await ensureDir()+ const path = dropPath(originalFilename)+ try {+ await copyFile(source, path, constants.COPYFILE_EXCL | constants.COPYFILE_FICLONE)+ } catch (error) {+ await rm(path, { force: true }).catch(() => {})+ throw error+ }+ return path+}diff --git a/cli/src/lib/superTabAttachmentProxy.ts b/cli/src/lib/superTabAttachmentProxy.tsindex eb74de6ba..cdacb91cd 100644--- a/cli/src/lib/superTabAttachmentProxy.ts+++ b/cli/src/lib/superTabAttachmentProxy.ts@@ -9,8 +9,14 @@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+/** The most one file sent by this multipart route may be. A larger one, up to 256 MB, goes straight to storage by a signed+ * link (superTabs/attach.ts): production sits behind Cloudflare, which may refuse a request body over 100 MB. */+export const MAX_FORM_ATTACHMENT_BYTES = 10 * 1024 * 1024+/** The form's file and its multipart framing, a few hundred bytes. */+export const ATTACHMENT_UPLOAD_MAX_BYTES = MAX_FORM_ATTACHMENT_BYTES + 1024 * 1024+/** Said of a form past that cap. Every client sends a file over 10 MB by the link, and an older one refused it before+ * sending, so only a client in error meets this. */+const TOO_LARGE = 'A file can be at most 10 MB.'/** 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. */@@ -44,7 +50,7 @@ export async function forwardAttachmentUpload(req: IncomingMessage, res: ServerR// 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.')+ return answer(413, 'ATTACHMENT_TOO_LARGE', TOO_LARGE)}let token: stringtry { token = await deps.accessToken() } catch {@@ -79,7 +85,7 @@ export async function forwardAttachmentUpload(req: IncomingMessage, res: ServerR} catch (error) {clearTimeout(quiet)req.resume()- if (seen > max) return answer(413, 'ATTACHMENT_TOO_LARGE', 'A file can be at most 10 MB.')+ if (seen > max) return answer(413, 'ATTACHMENT_TOO_LARGE', TOO_LARGE)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.')diff --git a/cli/src/lib/swarmTools.ts b/cli/src/lib/swarmTools.tsindex 6e65a243f..ddb9638aa 100644--- a/cli/src/lib/swarmTools.ts+++ b/cli/src/lib/swarmTools.ts@@ -26,7 +26,7 @@ Every command starts \`harness super-tab --tab TAB\` (your tab id is in your lau## Post\`post GROUP TEXT OPERATION_ID [--to AGENT]... [--reply-to MESSAGE_ID] [--attach PATH]... [--mention PERSON]...\`- Answer a message once, inside its thread: \`--reply-to MESSAGE_ID\` puts your reply in that message's thread. Post at the top level only to start a new topic.-- \`--attach PATH\` sends a file (a screenshot, a log; up to 10 files of 10 MB each); TEXT may then be empty.+- \`--attach PATH\` sends a file (a screenshot, a log; up to 10 files of 256 MB each); TEXT may then be empty.- \`--mention PERSON\` tags a person by the id or email shown in status (up to 5), when you need them to act or decide; an @username or @email in TEXT tags too, outside code and links. Nobody is tagged who cannot read the conversation.- Quote TEXT so the shell keeps it one argument.diff --git a/cli/src/superTabs/attach.spec.ts b/cli/src/superTabs/attach.spec.tsindex 4dfeb1c5c..f12312ff7 100644--- a/cli/src/superTabs/attach.spec.ts+++ b/cli/src/superTabs/attach.spec.ts@@ -1,4 +1,4 @@-import { mkdtempSync, rmSync, symlinkSync, unlinkSync, writeFileSync } from 'node:fs'+import { mkdtempSync, rmSync, symlinkSync, truncateSync, unlinkSync, writeFileSync } from 'node:fs'import { execFile, execFileSync } from 'node:child_process'import { tmpdir } from 'node:os'import { join } from 'node:path'@@ -21,7 +21,8 @@ vi.mock('node:fs', async original => {const realpathSync = Object.assign((...args: Parameters<typeof fs.realpathSync>) => fs.realpathSync(...args), { native })return { ...fs, default: { ...fs, realpathSync }, realpathSync }})-const { readInsideFolder } = await import('./attach.js')+const { readInsideFolder, uploadAttachments } = await import('./attach.js')+const { loadOrCreateHookCredential } = await import('../lib/hookAuth.js')const made: string[] = []afterEach(() => { for (const dir of made.splice(0)) rmSync(dir, { recursive: true, force: true }) })@@ -54,10 +55,110 @@ it('refuses a link as the last name, a folder inside, and a file over the limit'symlinkSync(join(folder, 'plan.md'), join(folder, 'alias.md'))expect(() => readInsideFolder([join(folder, 'alias.md')], folder)).toThrow('is outside your folder')expect(() => readInsideFolder([folder.concat('/')], folder)).toThrow('is outside your folder')- writeFileSync(join(folder, 'big.bin'), Buffer.alloc(10 * 1024 * 1024 + 1))+ // A Buddy's files are read whole, so they keep the 10 MB of the form upload they go by, whatever a chat file may be.+ writeFileSync(join(folder, 'big.bin'), '')+ truncateSync(join(folder, 'big.bin'), 10 * 1024 * 1024 + 1)expect(() => readInsideFolder([join(folder, 'big.bin')], folder)).toThrow('over the 10.0 MB limit')})+const MiB = 1024 * 1024+/** A file of [size] bytes that takes no room: sparse, never a buffer that large. */+const sparse = (folder: string, name: string, size: number) => { const path = join(folder, name); writeFileSync(path, ''); truncateSync(path, size); return path }+const sent = () => vi.fn(async (_payload: Record<string, unknown>) => ({ ok: true, value: { agentId: 'agent-1', attachmentIds: null } }))+const json = (body: unknown, status = 200) => new Response(JSON.stringify(body), { status, headers: { 'content-type': 'application/json' } })+const SIGNED = { 'content-type': 'application/octet-stream', 'content-disposition': 'attachment; filename="big.bin"', 'cache-control': 'private, max-age=0',+ 'x-goog-content-length-range': `${10 * MiB + 1},${10 * MiB + 1}`, 'x-goog-if-generation-match': '0' }+const STORAGE = 'https://storage.googleapis.com/harness-attachments/super-tabs/tab/u1?X-Goog-Signature=abc'+/** The daemon's two upload routes and storage, as `post --attach` meets them. */+function direct(put = () => new Response(null, { status: 200 })) {+ return vi.fn(async (url: string, init?: RequestInit) => {+ if (url === 'http://127.0.0.1:14001/api/super-tabs/tab/attachments?asAgentId=agent-1') return json({ success: true, data: { attachment: { id: 'form-1' } } })+ if (url === 'http://127.0.0.1:14001/api/super-tabs/tab/attachments/uploads?asAgentId=agent-1') {+ return json({ success: true, data: { upload: { id: 'u1', url: STORAGE, method: 'PUT', headers: SIGNED, expiresAt: Date.now() + 600_000 } } })+ }+ if (url === STORAGE) return put()+ if (url === 'http://127.0.0.1:14001/api/super-tabs/tab/attachments/uploads/u1/complete?asAgentId=agent-1') return json({ success: true, data: { attachment: { id: 'att-1' } } })+ return json({ success: false, error: { code: 'NOT_FOUND', message: `unexpected ${init?.method} ${url}` } }, 404)+ })+}++it('sends a file of up to 10 MB by the form, and a larger one by a link: straight to storage, then complete', async () => {+ const folder = dir('attach-direct-')+ const credential = loadOrCreateHookCredential(folder)+ const target = { tabId: 'tab', conversationId: 'c1', port: 14001, dataDir: folder }+ const small = sparse(folder, 'small.bin', 10 * MiB), big = sparse(folder, 'big.bin', 10 * MiB + 1)+ const fetcher = direct()+ expect(await uploadAttachments([small, big], 'op', target, sent(), fetcher as unknown as typeof fetch)).toEqual(['form-1', 'att-1'])+ expect(fetcher.mock.calls.map(([url, init]) => `${init?.method} ${url.replace(/\?.*/, '')}`)).toEqual([+ 'POST http://127.0.0.1:14001/api/super-tabs/tab/attachments',+ 'POST http://127.0.0.1:14001/api/super-tabs/tab/attachments/uploads',+ `PUT ${STORAGE.replace(/\?.*/, '')}`,+ 'POST http://127.0.0.1:14001/api/super-tabs/tab/attachments/uploads/u1/complete',+ ])+ const [form, link, put, complete] = fetcher.mock.calls.map(([, init]) => init!)+ // 10 MB exactly still goes by the form, as before.+ expect((form!.body as FormData).get('file')).toMatchObject({ name: 'small.bin', size: 10 * MiB })+ // The daemon's calls carry its write gate and local credential, and only those.+ for (const local of [link!, complete!]) expect(local.headers).toEqual({ 'x-adapter-local': '1', 'X-Harness-Local': credential, 'content-type': 'application/json' })+ expect(JSON.parse(String(link!.body))).toEqual({ conversationId: 'c1', name: 'big.bin', mime: 'application/octet-stream', size: 10 * MiB + 1 })+ expect(JSON.parse(String(complete!.body))).toEqual({})+ // Storage gets exactly the signed headers and the length, never a credential: the link is the credential.+ expect(put!.headers).toEqual({ ...SIGNED, 'content-length': String(10 * MiB + 1) })+ expect(put!.body).toBeInstanceOf(Blob)+ expect((put!.body as Blob).size).toBe(10 * MiB + 1)+})++it('says the upload failed when storage refuses it, and completes nothing', async () => {+ const folder = dir('attach-direct-')+ const fetcher = direct(() => new Response('<Error>PreconditionFailed</Error>', { status: 412 }))+ await expect(uploadAttachments([sparse(folder, 'big.bin', 20 * MiB)], 'op', { tabId: 'tab', conversationId: 'c1', port: 14001, dataDir: folder }, sent(),+ fetcher as unknown as typeof fetch)).rejects.toThrow('Could not upload big.bin. Try again.')+ expect(fetcher.mock.calls.map(([url]) => url)).not.toContain('http://127.0.0.1:14001/api/super-tabs/tab/attachments/uploads/u1/complete?asAgentId=agent-1')+})++// Security review of the PR: the link is the credential, and a redirect would send the file somewhere else with its headers.+it('never follows a redirect from storage: the upload fails and the other address is never asked', async () => {+ const folder = dir('attach-direct-')+ const elsewhere = 'https://elsewhere.example.test/take'+ const base = direct(() => new Response(null, { status: 307, headers: { location: elsewhere } }))+ // As fetch does: a redirect refused when told so, else followed.+ const fetcher = vi.fn(async (url: string, init?: RequestInit) => {+ const answer = await base(url, init)+ if (answer.status < 300 || answer.status >= 400) return answer+ if (init?.redirect === 'error') throw new TypeError('fetch failed: unexpected redirect')+ return base(answer.headers.get('location')!, init).then(() => new Response(null, { status: 200 }))+ })+ await expect(uploadAttachments([sparse(folder, 'big.bin', 20 * MiB)], 'op', { tabId: 'tab', conversationId: 'c1', port: 14001, dataDir: folder }, sent(),+ fetcher as unknown as typeof fetch)).rejects.toThrow('Could not upload big.bin. Try again.')+ expect(base.mock.calls.map(([url]) => url)).not.toContain(elsewhere)+ expect(base.mock.calls.map(([url]) => url)).not.toContain('http://127.0.0.1:14001/api/super-tabs/tab/attachments/uploads/u1/complete?asAgentId=agent-1')+})++it('names the daemon\'s refusal of a link, as the backend said it', async () => {+ const folder = dir('attach-direct-')+ const fetcher = vi.fn(async () => json({ success: false, error: { code: 'ATTACHMENTS_UNAVAILABLE', message: 'Files over 10 MB cannot be sent right now.' } }, 503))+ await expect(uploadAttachments([sparse(folder, 'big.bin', 20 * MiB)], 'op', { tabId: 'tab', conversationId: 'c1', port: 14001, dataDir: folder }, sent(),+ fetcher as unknown as typeof fetch)).rejects.toThrow('Files over 10 MB cannot be sent right now.')+ expect(fetcher).toHaveBeenCalledTimes(1)+})++it('says to restart Harness when its daemon is older than the link route', async () => {+ const folder = dir('attach-direct-')+ const fetcher = vi.fn(async () => json({ error: 'not found' }, 404))+ await expect(uploadAttachments([sparse(folder, 'big.bin', 20 * MiB)], 'op', { tabId: 'tab', conversationId: 'c1', port: 14001, dataDir: folder }, sent(),+ fetcher as unknown as typeof fetch)).rejects.toThrow('big.bin is over 10 MB, which this computer\'s Harness cannot send yet. Restart Harness and try again.')+})++it('refuses a file over 256 MB before any request', async () => {+ const folder = dir('attach-direct-')+ const request = sent(), fetcher = direct()+ await expect(uploadAttachments([sparse(folder, 'small.bin', 5), sparse(folder, 'huge.bin', 256 * MiB + 1)], 'op',+ { tabId: 'tab', conversationId: 'c1', port: 14001, dataDir: folder }, request, fetcher as unknown as typeof fetch))+ .rejects.toThrow(`huge.bin is over the 256 MB limit (${256 * MiB + 1} bytes).`)+ expect(request).not.toHaveBeenCalled()+ expect(fetcher).not.toHaveBeenCalled()+})+// Run apart: a blocking open stops the whole process, which no test timeout in it can end (re-check of #2103).it.skipIf(process.platform === 'win32')('refuses a named pipe and the terminal\'s input without waiting on them', async () => {const folder = dir('buddy-folder-')diff --git a/cli/src/superTabs/attach.ts b/cli/src/superTabs/attach.tsindex 7bea02270..8a54ceb6d 100644--- a/cli/src/superTabs/attach.ts+++ b/cli/src/superTabs/attach.ts@@ -5,7 +5,7 @@ import { basename, extname, isAbsolute, relative, sep } 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'+import { formatSize, MAX_ATTACHMENT_BYTES, MAX_FORM_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',@@ -27,33 +27,105 @@ const value = (answer: Record<string, unknown>) => {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(file: string | CheckedFile, target: UploadTarget, agentId: string, fetcher: typeof fetch): Promise<string> {+/** What a daemon answered, or why not, in its own words (the backend's envelope) when it gave them. */+async function answered(response: Response, name: string): Promise<Record<string, unknown>> {+ const body = object(await response.json().catch(() => ({})))+ if (!response.ok || body.success === false) {+ throw new Error(String(object(body.error).message ?? body.message ?? `Could not upload ${name} (HTTP ${response.status}).`))+ }+ return object(body.data)+}++/** One file of `post --attach` up to 10 MB, 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 uploadForm(file: { path: string; size: number } | CheckedFile, target: UploadTarget, agentId: string, fetcher: typeof fetch): Promise<string> {const form = new FormData()form.append('conversationId', target.conversationId)- if (typeof file === 'string') {- const info = await stat(file)- if (!info.isFile()) throw new Error(`${file} is not a file.`)- if (info.size > MAX_ATTACHMENT_BYTES) throw new Error(`${basename(file)} is over the ${formatSize(MAX_ATTACHMENT_BYTES)} limit (${info.size} bytes).`)- // Read from disk as it is sent, never whole.- form.append('file', await openAsBlob(file, { type: mimeOf(file) }), basename(file))- } else form.append('file', new Blob([file.bytes], { type: file.type }), file.name)- const name = typeof file === 'string' ? basename(file) : file.name+ // Read from disk as it is sent, never whole.+ if ('path' in file) form.append('file', await openAsBlob(file.path, { type: mimeOf(file.path) }), basename(file.path))+ else form.append('file', new Blob([file.bytes], { type: file.type }), file.name)+ const name = 'path' in file ? basename(file.path) : file.nameconst 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 ${name} (HTTP ${response.status}).`))+ const attachment = object((await answered(response, name)).attachment)+ if (typeof attachment.id !== 'string') throw new Error(`Could not upload ${name} (HTTP ${response.status}).`)+ return attachment.id+}++/** The slowest steady uplink a file going straight to storage is given time for: 128 KB/s, 256 MB in about 35 minutes. */+const DIRECT_FLOOR_BYTES_PER_MS = 128 * 1024 / 1000+/** A daemon's answer to a link or a completion: small, through the backend. */+const DAEMON_MS = 60_000++/** Where the bytes may go: storage over HTTPS, or a test's or a local stack's own on this computer. */+const storageUrl = (url: unknown): url is string => {+ try {+ const parsed = new URL(String(url))+ return parsed.protocol === 'https:' || (parsed.protocol === 'http:' && ['127.0.0.1', 'localhost', '[::1]'].includes(parsed.hostname))+ } catch { return false }+}++/**+ * One file of `post --attach` over 10 MB (contract of group 1604): production sits behind Cloudflare, which may refuse a+ * request body over 100 MB, so its bytes go straight to the storage bucket. The daemon asks the backend for a short-lived+ * signed link with the account's token; the file goes to that link with exactly the headers it came with and its length,+ * read from disk as it is sent and with no credential of ours (the link is the credential); then the daemon says it is+ * complete, and the backend answers the attachment, as the form route does. A link writes once: a failed upload is+ * started again from the link, by posting again.+ */+async function uploadDirect(path: string, target: UploadTarget, agentId: string, fetcher: typeof fetch): Promise<string> {+ const name = basename(path)+ const blob = await openAsBlob(path)+ const route = `http://127.0.0.1:${target.port}/api/super-tabs/${target.tabId}/attachments/uploads`+ // The local API's write gate, and its credential over TCP.+ const local = { 'x-adapter-local': '1', ...localCredentialHeaders(target.dataDir), 'content-type': 'application/json' }+ const asked = await fetcher(`${route}?asAgentId=${agentId}`, {+ method: 'POST', headers: local, signal: AbortSignal.timeout(DAEMON_MS),+ body: JSON.stringify({ conversationId: target.conversationId, name, mime: mimeOf(path), size: blob.size }),+ })+ // A daemon from before this route answers its bare 404: it runs an older Harness than this command.+ if (asked.status === 404 && object(await asked.clone().json().catch(() => ({}))).error === 'not found') {+ throw new Error(`${name} is over 10 MB, which this computer's Harness cannot send yet. Restart Harness and try again.`)}+ const upload = object((await answered(asked, name)).upload)+ const headers = object(upload.headers)+ if (typeof upload.id !== 'string' || !/^[A-Za-z0-9_-]{1,160}$/.test(upload.id) || !storageUrl(upload.url)+ || !Object.values(headers).every(value => typeof value === 'string')) throw new Error(`Could not upload ${name}. Update Harness and try again.`)+ let stored: Response+ try {+ stored = await fetcher(upload.url, {+ // A redirect would carry the file and its signed headers to another address: a failure, never followed.+ method: 'PUT', body: blob, redirect: 'error',+ headers: { ...headers as Record<string, string>, 'content-length': String(blob.size) },+ signal: AbortSignal.timeout(60_000 + Math.ceil(blob.size / DIRECT_FLOOR_BYTES_PER_MS)),+ })+ await stored.body?.cancel().catch(() => {})+ } catch { throw new Error(`Could not upload ${name}. Try again.`) }+ if (!stored.ok) throw new Error(`Could not upload ${name}. Try again.`)+ const completed = await fetcher(`${route}/${upload.id}/complete?asAgentId=${agentId}`, {+ method: 'POST', headers: local, body: '{}', signal: AbortSignal.timeout(DAEMON_MS),+ })+ const attachment = object((await answered(completed, name)).attachment)+ if (typeof attachment.id !== 'string') throw new Error(`Could not upload ${name} (HTTP ${completed.status}).`)return attachment.id}+const tooLarge = (path: string, size: number) => size > MAX_ATTACHMENT_BYTES+ ? new Error(`${basename(path)} is over the ${MAX_ATTACHMENT_BYTES / 1024 / 1024} MB limit (${size} bytes).`) : null++/** A file named on the command line: a regular file, at most 256 MB. */+async function checkedPath(path: string): Promise<{ path: string; size: number }> {+ const info = await stat(path)+ if (!info.isFile()) throw new Error(`${path} is not a file.`)+ const refused = tooLarge(path, info.size)+ if (refused) throw refused+ return { path, size: info.size }+}+/** `sentIn`: where the message these files go with is written, when not where they are uploaded (a Buddy's proposal is* uploaded to its chat and posted in the project chat). */export interface UploadTarget { tabId: string; conversationId: string; sentIn?: string; port: number; dataDir: string }@@ -70,7 +142,9 @@ export interface CheckedFile { name: string; type: string; bytes: Buffer }* regular file inside its own folder, the one place it may read (lib/buddyGuard.ts), never under its repository's or* Harness's records. The last name is opened without following a link or waiting; the file must have that one name (a hard link* would give a file outside a second name inside), and the real path's file must be the one opened, so a name swapped- * for a link after the check is refused or never read. Each is at most a chat file's size, so read whole.+ * for a link after the check is refused or never read. Each is read whole, so each stays at the 10 MB of the form upload it+ * then goes by, not the 256 MB a chat file may be: a larger one would be held in memory, and its bytes read again from a+ * path to go by a link would no longer be the ones checked.*/export function readInsideFolder(paths: string[], folder: string): CheckedFile[] {const root = realpathSync.native(folder)@@ -87,7 +161,7 @@ export function readInsideFolder(paths: string[], folder: string): CheckedFile[]if (!inside || inside.startsWith('..') || isAbsolute(inside) || RECORDS.has(inside.split(sep)[0]!.toLowerCase())) throw outside()if (!opened.isFile()) throw new Error(`${path} is not a file.`)if (opened.nlink !== 1 || named.ino !== opened.ino || named.dev !== opened.dev) throw outside()- if (opened.size > MAX_ATTACHMENT_BYTES) throw new Error(`${basename(path)} is over the ${formatSize(MAX_ATTACHMENT_BYTES)} limit (${opened.size} bytes).`)+ if (opened.size > MAX_FORM_ATTACHMENT_BYTES) throw new Error(`${basename(path)} is over the ${formatSize(MAX_FORM_ATTACHMENT_BYTES)} limit (${opened.size} bytes).`)const bytes = Buffer.alloc(opened.size)let read = 0for (let got = -1; read < bytes.length && got !== 0; read += got) got = readSync(fd, bytes, read, bytes.length - read, read)@@ -100,10 +174,24 @@ export function readInsideFolder(paths: string[], folder: string): CheckedFile[]* went out uploads nothing and names that message's files, so the send returns its receipt. */export async function uploadAttachments(paths: Array<string | CheckedFile>, operationId: string, target: UploadTarget, request: Request,fetcher: typeof fetch = fetch): Promise<string[]> {+ // A file too large is refused before any request, and so uploads none of the others. One not there is left to the check+ // below, after the answer whether the post already went out: a repeat of one that did still names its files.+ for (const path of paths) {+ const refused = typeof path === 'string' ? tooLarge(path, await stat(path).then(info => info.size, () => 0)) : null+ if (refused) throw refused+ }const earlier = value(await request({ action: 'attachment', step: 'sent', conversationId: target.sentIn ?? 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.')+ // Every file checked before the first upload.+ const files: Array<{ path: string; size: number } | CheckedFile> = []+ for (const path of paths) files.push(typeof path === 'string' ? await checkedPath(path) : path)const ids: string[] = []- for (const path of paths) ids.push(await uploadOne(path, target, earlier.agentId, fetcher))+ // Up to 10 MB by the form, as before; larger, straight to storage. A Buddy's checked files are at most 10 MB (readInsideFolder).+ for (const file of files) {+ ids.push('path' in file && file.size > MAX_FORM_ATTACHMENT_BYTES+ ? await uploadDirect(file.path, target, earlier.agentId, fetcher)+ : await uploadForm(file, target, earlier.agentId, fetcher))+ }return ids}diff --git a/cli/src/superTabs/attachments.spec.ts b/cli/src/superTabs/attachments.spec.tsindex 944c217a1..116281b5a 100644--- a/cli/src/superTabs/attachments.spec.ts+++ b/cli/src/superTabs/attachments.spec.ts@@ -1,11 +1,31 @@-import { readFileSync } from 'node:fs'-import { basename } from 'node:path'+import { readdirSync, readFileSync, statSync, writeFileSync } from 'node:fs'+import { basename, dirname, join } from 'node:path'import { describe, expect, it, vi } from 'vitest'-import { attachedFiles, attachmentsOf, diskName, formatSize, servedFrom } from './attachments.js'+import { PASTE_DROPS_DIR } from '../lib/pasteDropFiles.js'+import { attachedFiles, attachmentsOf, diskName, formatSize, MAX_ATTACHMENT_BYTES, servedFrom } from './attachments.js'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 }))+/** The files in paste-drops written under [name]: a failed download must leave none, not even part of one. */+const dropped = (name: string) => { try { return readdirSync(PASTE_DROPS_DIR).filter(f => f.endsWith(`-${name}`)) } catch { return [] } }+/** A body of [chunks] chunks of 64 KiB of zeros, made as it is read (no large buffer), that then waits on [hold], if any. As fetch+ * does, it errors once the request's signal aborts. */+function streamed(chunks: number, hold?: Promise<void>) {+ const chunk = new Uint8Array(64 * 1024)+ return vi.fn(async (_url: string | URL | Request, init?: RequestInit) => {+ let sent = 0+ const body = new ReadableStream<Uint8Array>({+ start(controller) { init?.signal?.addEventListener('abort', () => controller.error(init.signal!.reason)) },+ async pull(controller) {+ if (sent < chunks) { sent++; controller.enqueue(chunk); return }+ if (hold) await hold+ controller.close()+ },+ })+ return new Response(body)+ })+}describe('Super Tab attachment downloads', () => {it('downloads each file into paste-drops and lists its path for the prompt', async () => {@@ -65,9 +85,132 @@ describe('Super Tab attachment downloads', () => {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('refuses a file declared over the 256 MB limit before fetching it', async () => {+ const fetcher = replying(new Uint8Array(5))+ const listed = await attachedFiles({ attachments: [file({ size: 256 * 1024 * 1024 + 1 })] }, { base, fetch: fetcher })+ expect(listed).toMatchObject({ complete: false, paths: [] })+ expect(listed.text).toContain('over the 256 MB limit')+ expect(fetcher).not.toHaveBeenCalled()+ expect(MAX_ATTACHMENT_BYTES).toBe(256 * 1024 * 1024)+ })+ it('downloads a file past the old 10 MB form limit, streamed to disk as it arrives', async () => {+ let release!: () => void+ const hold = new Promise<void>(resolve => { release = resolve })+ const name = 'twelve-mb-streamed.bin', size = 12 * 1024 * 1024+ const pending = attachedFiles({ attachments: [file({ name, size })] }, { base, fetch: streamed(size / (64 * 1024), hold) })+ // On disk before the last byte came: the bytes are written as they arrive, never collected in memory first.+ await vi.waitFor(() => { expect(dropped(name).map(f => statSync(join(PASTE_DROPS_DIR, f)).size)).toEqual([size]) })+ release()+ const listed = await pending+ expect(listed.complete).toBe(true)+ expect(statSync(listed.paths[0]!).size).toBe(size)+ })+ it('refuses a body past its declared size or short of it, and keeps no part of it', async () => {+ const over = 'over-declared.bin', short = 'short-of-declared.bin'+ const too = await attachedFiles({ attachments: [file({ name: over, size: 3 * 64 * 1024 })] }, { base, fetch: streamed(4) })+ expect(too.text).toContain('larger than declared')+ expect(dropped(over)).toEqual([])+ const few = await attachedFiles({ attachments: [file({ name: short, size: 3 * 64 * 1024 })] }, { base, fetch: streamed(2) })+ expect(few).toMatchObject({ complete: false, paths: [] })+ expect(few.text).toContain('incomplete download')+ expect(dropped(short)).toEqual([])+ // A declared length past the size is refused before a byte is read.+ const declared = vi.fn(async () => new Response(new Uint8Array(5), { headers: { 'content-length': '6' } }))+ expect((await attachedFiles({ attachments: [file()] }, { base, fetch: declared })).text).toContain('larger than declared')+ expect(declared).toHaveBeenCalledTimes(1)+ })+ it('ends a download once no bytes come for the idle time, tries again, and keeps no part of it', async () => {+ const name = 'stalls.bin'+ const stalled = streamed(1, new Promise<void>(() => {}))+ const listed = await attachedFiles({ attachments: [file({ name, size: 2 * 64 * 1024 })] }, { base, fetch: stalled, idleMs: 50 })+ expect(listed).toMatchObject({ complete: false, paths: [] })+ expect(listed.text).toContain('no bytes came for')+ expect(stalled).toHaveBeenCalledTimes(3)+ expect(dropped(name)).toEqual([])+ })+ it('downloads a file two deliveries share once at a time, and gives each its own copy', async () => {+ let release!: () => void+ const hold = new Promise<void>(resolve => { release = resolve })+ const fetcher = streamed(2, hold), inFlight = new Map()+ const shared = file({ name: 'shared-once.bin', size: 2 * 64 * 1024 })+ const both = Promise.all([attachedFiles({ attachments: [shared] }, { base, fetch: fetcher, inFlight }),+ attachedFiles({ attachments: [shared] }, { base, fetch: fetcher, inFlight })])+ await vi.waitFor(() => expect(fetcher).toHaveBeenCalled())+ release()+ const [first, second] = await both+ expect(fetcher).toHaveBeenCalledTimes(1)+ expect([first.complete, second.complete]).toEqual([true, true])+ const [mine, theirs] = [first.paths[0]!, second.paths[0]!]+ // Each delivery's own file in paste-drops, named as any download is, with the same bytes.+ expect(mine).not.toBe(theirs)+ expect(dirname(theirs)).toBe(PASTE_DROPS_DIR)+ expect(basename(theirs)).toMatch(/^[0-9a-f]{8}-shared-once\.bin$/)+ expect(statSync(theirs).mode).toBe(statSync(mine).mode)+ expect(readFileSync(theirs).equals(readFileSync(mine))).toBe(true)+ // One agent editing its copy leaves the other's as it was, so a Buddy guard's hash of it still matches.+ writeFileSync(mine, 'edited')+ expect(readFileSync(theirs).byteLength).toBe(2 * 64 * 1024)+ expect(second.text).toContain(theirs)+ // Done, it is no longer in flight: a later delivery downloads it again.+ expect(inFlight.size).toBe(0)+ })+ it('stops a download when told to, and keeps no part of it', async () => {+ const name = 'told-to-stop.bin', stop = new AbortController()+ const pending = attachedFiles({ attachments: [file({ name, size: 3 * 64 * 1024 })] }, { base, fetch: streamed(1, new Promise<void>(() => {})), signal: stop.signal })+ await vi.waitFor(() => expect(dropped(name)).toHaveLength(1))+ stop.abort()+ expect(await pending).toMatchObject({ complete: false, paths: [] })+ expect(dropped(name)).toEqual([])+ })+ it('refuses a file the disk has no room for, before fetching it and without trying again', async () => {+ const fetcher = replying(new Uint8Array(5))+ const size = 100 * 1024 * 1024+ // Room for the file but not the 512 MB kept free beside it.+ const statfs = vi.fn(async () => ({ bavail: (size + 256 * 1024 * 1024) / 4096, bsize: 4096 }))+ const listed = await attachedFiles({ attachments: [file({ size })] }, { base, fetch: fetcher, statfs })+ expect(listed).toEqual({ text: `Attached files:\n- Could not download ${file().url} (sent as "screen.png", 100.0 MB): not enough free disk space`,+ complete: false, paths: [] })+ expect(fetcher).not.toHaveBeenCalled()+ expect(statfs).toHaveBeenCalledWith(PASTE_DROPS_DIR)+ // With the room, it goes ahead.+ const roomy = vi.fn(async () => ({ bavail: 2 * 1024 * 1024 * 1024 / 4096, bsize: 4096 }))+ expect(await attachedFiles({ attachments: [file()] }, { base, fetch: fetcher, statfs: roomy })).toMatchObject({ complete: true })+ })+ it('keeps a shared download going while one delivery still wants it, and stops it, keeping nothing, once none does', async () => {+ const name = 'wanted-by-two.bin', inFlight = new Map()+ let release!: () => void+ const hold = new Promise<void>(resolve => { release = resolve })+ const fetcher = streamed(1, hold)+ const shared = file({ name, size: 64 * 1024 })+ const [one, two] = [new AbortController(), new AbortController()]+ const first = attachedFiles({ attachments: [shared] }, { base, fetch: fetcher, inFlight, signal: one.signal })+ const second = attachedFiles({ attachments: [shared] }, { base, fetch: fetcher, inFlight, signal: two.signal })+ await vi.waitFor(() => expect(dropped(name)).toHaveLength(1))+ // The first delivery left: the second still gets the file.+ one.abort()+ release()+ expect((await second).complete).toBe(true)+ await first+ // Both leave a download still under way: it stops, and its part file goes.+ const name2 = 'wanted-by-none.bin'+ const again = streamed(1, new Promise<void>(() => {}))+ const [three, four] = [new AbortController(), new AbortController()]+ const lone = file({ name: name2, size: 2 * 64 * 1024, url: `${base}/super-tabs/tab/abc/${name2}` })+ const third = attachedFiles({ attachments: [lone] }, { base, fetch: again, inFlight, signal: three.signal })+ const fourth = attachedFiles({ attachments: [lone] }, { base, fetch: again, inFlight, signal: four.signal })+ await vi.waitFor(() => expect(dropped(name2)).toHaveLength(1))+ three.abort(); four.abort()+ expect(await third).toMatchObject({ complete: false })+ expect(await fourth).toMatchObject({ complete: false })+ expect(dropped(name2)).toEqual([])+ expect(inFlight.size).toBe(0)+ })+ it('gives a large message time to finish: its budget grows with the bytes it declares', async () => {+ let clock = 0+ const slow = vi.fn(async () => { clock += 30_000; return new Response(null, { status: 503 }) })+ // 45 s would allow two tries of 30 s; 256 MB at the slowest steady pace allows all three.+ expect(await attachedFiles({ attachments: [file({ size: MAX_ATTACHMENT_BYTES })] }, { base, fetch: slow, now: () => clock })).toMatchObject({ complete: false })+ expect(slow).toHaveBeenCalledTimes(3)})it('reads only well-formed attachment rows and formats sizes', async () => {expect(attachmentsOf({})).toEqual([])diff --git a/cli/src/superTabs/attachments.ts b/cli/src/superTabs/attachments.tsindex e2b550a25..93ff424b7 100644--- a/cli/src/superTabs/attachments.ts+++ b/cli/src/superTabs/attachments.ts@@ -1,14 +1,43 @@+import { mkdir, statfs as fsStatfs } from 'node:fs/promises'import { env } from '../config/env.js'-import { writePasteDropFile } from '../lib/pasteDropFiles.js'+import { copyPasteDropFile, PASTE_DROPS_DIR, writePasteDropStream } from '../lib/pasteDropFiles.js'import { object } from './wire.js'+/** The most a file sent by the multipart route may be (lib/superTabAttachmentProxy.ts); a larger one goes by a link. */+export { MAX_FORM_ATTACHMENT_BYTES } from '../lib/superTabAttachmentProxy.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+export const MAX_ATTACHMENT_BYTES = 256 * 1024 * 1024+/** No bytes for this long ends a download: a slow link keeps going, a stalled one does not hold the host's loop. */+const IDLE_MS = 30_000+/** The slowest steady pace a download is given time for: 256 KB/s, so 256 MB in about 17 minutes. */+const FLOOR_BYTES_PER_MS = 256 * 1024 / 1000+/** One download's ceiling however steadily it moves: half a minute, and its bytes at the slowest pace. */+const downloadMs = (bytes: number) => 30_000 + Math.ceil(bytes / FLOOR_BYTES_PER_MS)+/** A message's time for all its files, which download together and share the link: at least 45 s, and their bytes at the+ * slowest pace, so a 256 MB file can finish. */const BUDGET_MS = 45_000+const budgetMs = (files: MessageAttachment[]) =>+ BUDGET_MS + Math.ceil(files.reduce((sum, file) => sum + Math.min(file.size, MAX_ATTACHMENT_BYTES), 0) / FLOOR_BYTES_PER_MS)+const megabytes = (bytes: number) => `${bytes / 1024 / 1024} MB`+/** Kept free beside a download: a 256 MB file must not fill the disk this computer's agents work on. */+const FREE_MARGIN_BYTES = 512 * 1024 * 1024+/** What `fs.statfs` tells of the disk: free blocks for this user, and their size. */+export type Statfs = (path: string) => Promise<{ bavail: number | bigint; bsize: number | bigint }>++/** Whether the paste-drops disk has room for [bytes] and the margin. A disk that cannot say (statfs unsupported) is not refused. */+async function roomFor(bytes: number, statfs: Statfs): Promise<boolean> {+ let free: number+ try {+ await mkdir(PASTE_DROPS_DIR, { recursive: true })+ const disk = await statfs(PASTE_DROPS_DIR)+ free = Number(disk.bavail) * Number(disk.bsize)+ } catch { return true }+ return free >= bytes + FREE_MARGIN_BYTES+}export function attachmentsOf(message: Record<string, unknown>): MessageAttachment[] {if (!Array.isArray(message.attachments)) return []@@ -36,52 +65,120 @@ class Refused extends Error {}* 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> {+async function download(file: MessageAttachment, base: string, fetcher: typeof fetch, ms: number, idleMs: number, stop: AbortSignal | undefined,+ statfs: Statfs): 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}`)+ if (file.size > MAX_ATTACHMENT_BYTES) throw new Refused(`over the ${megabytes(MAX_ATTACHMENT_BYTES)} limit`)+ // Another try would find the same disk: refused, not tried again.+ if (!await roomFor(file.size, statfs)) throw new Refused('not enough free disk space')+ const limit = file.size+ // No bytes for idleMs ends it, from the request on: waiting for the answer counts too.+ const idle = new AbortController()+ let quiet: NodeJS.Timeout | undefined+ const moved = () => {+ clearTimeout(quiet)+ quiet = setTimeout(() => idle.abort(new Error(`no bytes came for ${Math.round(idleMs / 1000)} s`)), idleMs)}- 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)- }- if (total !== file.size) throw new Error('incomplete download')- return writePasteDropFile(diskName(file.name), Buffer.concat(chunks))+ moved()+ try {+ // A redirect could leave the public base, so it is a failure, not followed.+ const response = await fetcher(file.url, { redirect: 'error', signal: AbortSignal.any([idle.signal, AbortSignal.timeout(ms), ...stop ? [stop] : []]) })+ if (!response.ok || !response.body) {+ await response.body?.cancel().catch(() => {})+ const Failure = response.status >= 400 && response.status < 500 && ![408, 429].includes(response.status) ? Refused : Error+ throw new Failure(`HTTP ${response.status}`)+ }+ // A length it declares past the size is refused before a byte is read. Compressed, the length is not the file's.+ const length = response.headers.get('content-length')+ if (length !== null && !response.headers.get('content-encoding') && Number(length) > limit) {+ await response.body.cancel().catch(() => {})+ throw new Refused('larger than declared')+ }+ const body = response.body+ // Counted as it goes to disk: one byte past the size ends it, and so does a body that ends short. Either way the file+ // written so far is removed (lib/pasteDropFiles.ts).+ async function* counted(): AsyncGenerator<Uint8Array> {+ let total = 0+ for await (const chunk of body) {+ moved()+ total += chunk.byteLength+ if (total > limit) throw new Refused('larger than declared')+ yield chunk+ }+ if (total !== file.size) throw new Error('incomplete download')+ }+ return await writePasteDropStream(diskName(file.name), counted())+ } catch (error) {+ // Ended for want of bytes: said so, rather than as the abort the fetch or the body threw.+ throw idle.signal.aborted && !(error instanceof Refused) ? idle.signal.reason : error+ } finally { clearTimeout(quiet) }}/** 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+ * agent on any machine can read them. Each file is streamed to disk, and gets up to three tries within one time budget for+ * the message, which grows with its bytes; 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. `paths` are the files written,* which a Buddy's guard may list when its own person sent them (lib/buddyGuard.ts). */-export async function attachedFiles(message: Record<string, unknown>, options: { base?: string; fetch?: typeof fetch; budgetMs?: number; now?: () => number } = {}):+/** A file being downloaded, by its address and size: a second delivery of the same file waits on the first's download+ * rather than start its own (superTabs/host.ts keeps one such map). [wanting]: the deliveries still waiting for it; the last+ * to leave stops it. */+export type FilesInFlight = Map<string, SharedDownload>+interface SharedDownload { result: Promise<{ line: string; path: string | null }>; wanting: number; stop: AbortController }++export async function attachedFiles(message: Record<string, unknown>,+ options: { base?: string; fetch?: typeof fetch; budgetMs?: number; idleMs?: number; now?: () => number+ inFlight?: FilesInFlight; signal?: AbortSignal; statfs?: Statfs } = {}):Promise<{ text: string; complete: boolean; paths: string[] }> {const files = attachmentsOf(message)if (!files.length) return { text: '', complete: true, paths: [] }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)}`+ const now = options.now ?? Date.now, deadline = now() + (options.budgetMs ?? budgetMs(files))+ // 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 labelOf = (file: MessageAttachment) => `sent as ${JSON.stringify(file.name)}, ${formatSize(file.size)}`+ const failed = (file: MessageAttachment, why: string) => ({ path: null, line: servedFrom(base, file.url)+ ? `- Could not download ${file.url} (${labelOf(file)}): ${why}` : `- Could not download a file (${labelOf(file)}): ${why}` })+ const one = async (file: MessageAttachment, signal: AbortSignal | undefined) => {+ const label = labelOf(file)let failure: unknown- for (let attempt = 0; attempt < 3 && deadline - now() > 0; attempt++) {+ for (let attempt = 0; attempt < 3 && deadline - now() > 0 && !signal?.aborted; attempt++) {try {- const path = await download(file, base, options.fetch ?? fetch, Math.min(DOWNLOAD_MS, deadline - now()))+ const path = await download(file, base, options.fetch ?? fetch, Math.min(downloadMs(file.size), deadline - now()), options.idleMs ?? IDLE_MS,+ signal, options.statfs ?? fsStatfs)return { line: `- ${path} (${label})`, path }} catch (error) {failure = errorif (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}`, path: null }+ return failed(file, signal?.aborted ? 'stopped' : failure instanceof Error ? failure.message : 'out of time')+ }+ const lines = await Promise.all(files.map(async file => {+ const inFlight = options.inFlight+ if (!inFlight) return one(file, options.signal)+ const key = `${file.size} ${file.url}`+ let shared = inFlight.get(key)+ const joined = !!shared+ if (!shared) {+ const stop = new AbortController()+ const started: SharedDownload = { wanting: 0, stop,+ result: one(file, stop.signal).finally(() => { if (inFlight.get(key) === started) inFlight.delete(key) }) }+ inFlight.set(key, shared = started)+ }+ const download = shared+ // This delivery wants it until it is in or the delivery leaves; the last one to leave stops it, and its part file goes.+ download.wanting+++ let left = false+ const leave = () => { if (left) return; left = true; if (--download.wanting === 0) download.stop.abort() }+ if (options.signal?.aborted) leave()+ else options.signal?.addEventListener('abort', leave, { once: true })+ const result = await download.result+ options.signal?.removeEventListener('abort', leave)+ if (!joined || result.path === null) return result+ // Downloaded once, but each delivery's own file: copied as soon as the download is in, before either is delivered.+ try {+ const path = await copyPasteDropFile(result.path, diskName(file.name))+ return { line: `- ${path} (${labelOf(file)})`, path }+ } catch (error) { return failed(file, error instanceof Error ? error.message : 'could not copy') }}))const paths = lines.flatMap(l => l.path === null ? [] : [l.path])return { text: `Attached files:\n${lines.map(l => l.line).join('\n')}`, complete: paths.length === lines.length, paths }diff --git a/cli/src/superTabs/command.spec.ts b/cli/src/superTabs/command.spec.tsindex 9db22cd4d..9b0ce0a42 100644--- a/cli/src/superTabs/command.spec.ts+++ b/cli/src/superTabs/command.spec.ts@@ -204,13 +204,15 @@ it('parses repeated --attach, allows empty text with a file, and refuses empty t}})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 { mkdtempSync, writeFileSync, rmSync, truncateSync } = 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))+ // Sparse: past the 256 MB limit without taking the room.+ writeFileSync(join(dir, 'big.bin'), '')+ truncateSync(join(dir, 'big.bin'), 256 * 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)@@ -254,8 +256,9 @@ it('uploads each --attach file to the daemon\'s local upload route as the agent,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'])+ expect(JSON.parse(deps.print.mock.calls.at(-1)![0]).error).toBe(`big.bin is over the 256 MB limit (${256 * 1024 * 1024 + 1} bytes).`)+ // Refused before any request: not even the check for an earlier send.+ expect(calls.map(c => c.step ?? c.action)).toEqual(['sent'])} finally { rmSync(dir, { recursive: true, force: true }) }})it('parses propose with up to 5 --attach files, always as a proposal', () => {diff --git a/cli/src/superTabs/host.spec.ts b/cli/src/superTabs/host.spec.tsindex f8843657c..15cd22a53 100644--- a/cli/src/superTabs/host.spec.ts+++ b/cli/src/superTabs/host.spec.ts@@ -1251,7 +1251,7 @@ describe('Super Tab attachments in delivered input', () => {const attachedFiles = vi.fn(async () => ({ text: 'Attached files:\n- /drops/1-screen.png (screen.png, 5 B)', complete: true, paths: ['/drops/1-screen.png'] }))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(attachedFiles).toHaveBeenCalledWith(expect.objectContaining({ attachments: [file] }), expect.anything())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')@@ -1275,6 +1275,155 @@ describe('Super Tab attachments in delivered input', () => {await host.tick()expect(attachedFiles).toHaveBeenCalledTimes(2)})+ // A file may be 256 MB (group 1604), minutes to download: the host's one poll loop must not wait on it, nor the backend's claim+ // go quiet for its 10 minutes (deliverySettle.ts CLAIM_QUIET_MS) while it does.+ const BIG = { id: 'a1', name: 'model.step', mime: 'application/octet-stream', size: 256 * 1024 * 1024, url: 'https://cdn.example.test/x/model.step' }+ const DOWNLOADED = { text: 'Attached files:\n- /drops/1-model.step (sent as "model.step", 256.0 MB)', complete: true, paths: ['/drops/1-model.step'] }+ const settle = () => new Promise(resolve => setTimeout(resolve, 50))+ /** A pass, given half a second: an old host waited on the download for the whole of it. */+ const pass = (host: SuperTabHost) => Promise.race([host.tick(), new Promise(resolve => setTimeout(resolve, 500))])+ it('keeps delivering to other agents while one delivery\'s file downloads, claims it again meanwhile, then delivers it', async () => {+ const t = setup()+ const second = { id: 'agent-2', harnessId: 'harness-2', machineId: 'machine-1' }+ const claims: string[] = [], claimed: Record<string, string> = {}+ vi.mocked(t.call).mockImplementation(async (method, path, body) => {+ let data: unknown+ if (path.endsWith('/readings')) return { status: 404, body: { message: 'not found', error: 'Not Found', statusCode: 404 } }+ if (path.includes('/hosts/')) data = hostForm([t.row, { tabId: 'tab', agent: second, leadsConversationId: 'leads' }], { tabs: ['tab'] })+ else if (path.includes('asAgentId=')) data = swarmReply(path, { conversations: [{ id: 'lead' }] })+ else {+ const id = path.includes('/agents/agent-2/') ? 'plain' : 'big'+ if (method === 'GET') data = [{ id, conversationId: 'lead', claimId: claimed[id] ?? null, status: claimed[id] ? 'claimed' : 'queued' }]+ else {+ const command = body as Record<string, unknown>+ if (command.type === 'claim') { claims.push(id); claimed[id] = command.claimId as string }+ data = { delivery: { id, claimId: claimed[id], status: 'claimed' }, message: { id: `m-${id}`, conversationId: 'lead', author: { name: 'Collaborator' },+ ...id === 'big' ? { text: 'The model.', attachments: [BIG] } : { text: 'Hello.' } } }+ }+ }+ return { status: 200, body: { success: true, data } }+ })+ let finish!: () => void+ const downloading = new Promise<void>(resolve => { finish = resolve })+ const attachedFiles = vi.fn(async (message: Record<string, unknown>) => {+ if (!Array.isArray(message.attachments)) return { text: '', complete: true, paths: [] }+ await downloading+ return DOWNLOADED+ })+ const host = t.open({ attachedFiles, downloadWaitMs: 10 })+ await pass(host)+ // The other agent's message went in while the file downloads; the file's waits.+ expect(t.core.turns.deliver).toHaveBeenCalledWith('harness-2', expect.stringContaining('Hello.'), expect.any(String))+ expect(vi.mocked(t.core.turns.deliver).mock.calls.map(c => c[0])).toEqual(['harness-2'])+ // Claimed again at the next try: each claim is a write, which keeps the backend's claim from going quiet.+ t.wait(1_000)+ await pass(host)+ expect(claims.filter(id => id === 'big')).toHaveLength(2)+ expect(vi.mocked(t.core.turns.deliver).mock.calls.map(c => c[0])).toEqual(['harness-2'])+ // Downloaded once, however many passes it took; delivered at the next pass once it is in, with no wait for a back-off.+ finish()+ await settle()+ await pass(host)+ expect(vi.mocked(t.core.turns.deliver).mock.calls.map(c => c[0])).toEqual(['harness-2', 'harness'])+ expect(vi.mocked(t.core.turns.deliver).mock.calls[1]?.[1]).toContain('/drops/1-model.step')+ expect(attachedFiles.mock.calls.filter(([message]) => Array.isArray(message.attachments))).toHaveLength(1)+ })+ it('starts a delivery\'s download again once the delivery left and came back, and stops downloads when the host stops', async () => {+ const t = setup({ text: 'The model.', attachments: [BIG] })+ let resolved = false+ const answer = vi.mocked(t.call).getMockImplementation()!+ vi.mocked(t.call).mockImplementation(async (method, path, body) => resolved && method === 'POST' && (body as Record<string, unknown>).type === 'claim'+ ? { status: 409, body: { success: false, error: { code: 'DELIVERY_RESOLVED', message: 'This message was already answered.' } } }+ : answer(method, path, body))+ const attachedFiles = vi.fn((_message: Record<string, unknown>, _options?: { signal?: AbortSignal }) => new Promise<typeof DOWNLOADED>(() => {}))+ const host = t.open({ attachedFiles: attachedFiles as never, downloadWaitMs: 10 })+ await pass(host)+ expect(attachedFiles).toHaveBeenCalledTimes(1)+ // Answered elsewhere while it downloads: the delivery leaves this host, and its download with it.+ resolved = true+ t.wait(5_000)+ await pass(host)+ // No other delivery wanted it: the download stopped (and with it, its part file: attachments.ts).+ expect(attachedFiles.mock.calls[0]?.[1]?.signal?.aborted).toBe(true)+ resolved = false+ t.send()+ t.wait(5_000)+ await pass(host)+ expect(attachedFiles).toHaveBeenCalledTimes(2)+ const signal = attachedFiles.mock.calls[1]?.[1]?.signal+ expect(signal?.aborted).toBe(false)+ host.stop()+ expect(signal?.aborted).toBe(true)+ expect(t.core.turns.deliver).not.toHaveBeenCalled()+ })+ /** A Swarm of agents on this machine, each with its deliveries, in order, as the backend lists them. */+ function swarmOf(t: ReturnType<typeof setup>, agents: Array<{ id: string; deliveries: Array<{ id: string; text: string; attachments?: unknown[] }> }>) {+ const claimed: Record<string, string> = {}+ vi.mocked(t.call).mockImplementation(async (method, path, body) => {+ let data: unknown+ if (path.endsWith('/readings')) return { status: 404, body: { message: 'not found', error: 'Not Found', statusCode: 404 } }+ if (path.includes('/hosts/')) {+ data = hostForm(agents.map(a => ({ tabId: 'tab', agent: { id: a.id, harnessId: `harness-${a.id}`, machineId: 'machine-1' }, leadsConversationId: 'leads' })), { tabs: ['tab'] })+ } else if (path.includes('asAgentId=')) data = swarmReply(path, { conversations: [{ id: 'lead' }] })+ else {+ const agent = agents.find(a => path.includes(`/agents/${a.id}/`))!+ if (method === 'GET') data = agent.deliveries.map(d => ({ id: d.id, conversationId: 'lead', claimId: claimed[d.id] ?? null, status: claimed[d.id] ? 'claimed' : 'queued' }))+ else {+ const id = path.split('/').at(-1)!, command = body as Record<string, unknown>, delivery = agent.deliveries.find(d => d.id === id)!+ if (command.type === 'claim') claimed[id] = command.claimId as string+ data = { delivery: { id, claimId: claimed[id], status: 'claimed' }, message: { id: `m-${id}`, conversationId: 'lead', author: { name: 'Collaborator' },+ text: delivery.text, ...delivery.attachments ? { attachments: delivery.attachments } : {} } }+ }+ }+ return { status: 200, body: { success: true, data } }+ })+ const delivered = () => vi.mocked(t.core.turns.deliver).mock.calls.map(c => `${String(c[0])}: ${String(c[1]).match(/(The model\.|Hello\.|Next\.)/)?.[0]}`)+ return { delivered }+ }+ /** A download that ends when [finish] is called, for messages with files. */+ function slowFiles() {+ let finish!: () => void+ const downloading = new Promise<void>(resolve => { finish = resolve })+ const attachedFiles = vi.fn(async (message: Record<string, unknown>) => {+ if (!Array.isArray(message.attachments)) return { text: '', complete: true, paths: [] }+ await downloading+ return DOWNLOADED+ })+ return { attachedFiles, finish }+ }+ // Review 1 of the PR, P2-2: a later message to the same agent must not reach it before the one whose file it waits for.+ it('holds an agent\'s later deliveries until the one waiting for its file is through', async () => {+ const t = setup()+ const { delivered } = swarmOf(t, [{ id: 'a', deliveries: [{ id: 'first', text: 'The model.', attachments: [BIG] }, { id: 'second', text: 'Next.' }] }])+ const { attachedFiles, finish } = slowFiles()+ const host = t.open({ attachedFiles, downloadWaitMs: 10 })+ await pass(host)+ // While its back-off runs, and once it is tried again.+ for (const ms of [500, 1_000, 2_000]) { t.wait(ms); await pass(host) }+ expect(delivered()).toEqual([])+ finish()+ await settle()+ await pass(host)+ expect(delivered()).toEqual(['harness-a: The model.', 'harness-a: Next.'])+ })+ // Review 1 of the PR, P2-3: one big file sent to many agents must not hold the loop that serves every agent for each of them.+ it('waits on new downloads at most once a pass, however many deliveries wait for files, and serves the others in it', async () => {+ const t = setup()+ const waiting = ['a', 'b', 'c', 'd', 'e'].map(id => ({ id, deliveries: [{ id: `big-${id}`, text: 'The model.', attachments: [BIG] }] }))+ const { delivered } = swarmOf(t, [...waiting, { id: 'z', deliveries: [{ id: 'plain', text: 'Hello.' }] }])+ const { attachedFiles } = slowFiles()+ const host = t.open({ attachedFiles, downloadWaitMs: 200 })+ const started = Date.now()+ await host.tick()+ expect(Date.now() - started).toBeLessThan(600)+ expect(delivered()).toEqual(['harness-z: Hello.'])+ expect(attachedFiles).toHaveBeenCalledTimes(6)+ // Known to be slow, they hold no later pass at all.+ t.wait(30_000)+ const again = Date.now()+ await host.tick()+ expect(Date.now() - again).toBeLessThan(150)+ })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, paths: ['/drops/a.log'] }) }); hosts.push(host)diff --git a/cli/src/superTabs/host.ts b/cli/src/superTabs/host.tsindex 74aa8b39d..011965d1d 100644--- a/cli/src/superTabs/host.ts+++ b/cli/src/superTabs/host.ts@@ -4,7 +4,7 @@ import { SwarmGrids } from './swarmGrids.js'import { retainContributions } from './retention.js'import { configurationObservation } from './configuration.js'import { NativeRecorder, nativeJournalFile } from './native.js'-import { attachedFiles, attachmentsOf } from './attachments.js'+import { attachedFiles, attachmentsOf, formatSize, type FilesInFlight } from './attachments.js'import { createHash, randomUUID } from 'node:crypto'import { existsSync, lstatSync, mkdirSync, readFileSync, realpathSync, renameSync, writeFileSync } from 'node:fs'import { readdir, readFile } from 'node:fs/promises'@@ -140,6 +140,8 @@ export interface SuperTabHostOptions {log?: (message: string) => voidobservers?: typeof publishObserversattachedFiles?: typeof attachedFiles+ /** How long a pass waits on the downloads it starts (DOWNLOAD_WAIT_MS), for a spec. */+ downloadWaitMs?: numberprepareContribution?: typeof prepareContribution/** This Mac's Harness Team account preparing its workspace through the relay (contribution.ts), for a spec. */prepareTeam?: (core: CoreApi, input: { tabId: string; machineId: string }) => Promise<Record<string, unknown>>@@ -262,6 +264,23 @@ const JOIN_FINAL = new Set(['MACHINES_FULL', 'OWNER_REQUIRED'])/** A delivery poll or claim the backend refused is asked again after 1 s, doubling to 30 s: every host retried each second, which* added to an overloaded backend (production at 5 pods, 2026-10-27). */const DELIVERY_RETRY_MS = 1_000+/** How long a pass waits on the downloads it starts, all of them together and once a pass (group 1604): a chat file may be 256+ * MB, minutes to download, and this one loop hands every agent on the host its deliveries. Most files are in by then and go+ * in the same pass; a larger one downloads on in the background while its delivery is withheld (FilesDownloading), and no+ * later pass waits on it at all: once in, it starts a pass of its own. */+const DOWNLOAD_WAIT_MS = 2_000+/** A delivery whose files are still downloading. Tried again like any withheld one (at most DELIVERY_RETRY_MAX_MS apart), and+ * each try claims it again with the same claim id: that writes the delivery, so the backend never takes the claim for one+ * nobody holds (backend deliverySettle.ts CLAIM_QUIET_MS, 10 minutes). Said once, not as a failure. */+class FilesDownloading extends Error {}+/** A delivery's files on their way. [stop] ends them when the delivery leaves (attachments.ts stops a file once no delivery+ * wants it, and removes its part); [result] is set once they are in; [said]: a pass stopped waiting on it. */+interface Download {+ pending: Promise<{ done: Awaited<ReturnType<typeof attachedFiles>> } | { error: unknown }>+ stop: AbortController+ result?: { done: Awaited<ReturnType<typeof attachedFiles>> } | { error: unknown }+ said: boolean+}const DELIVERY_RETRY_MAX_MS = 30_000/** Prod 10-30: a claim refused every 30 s said the backend's bare words 223 times in 2 hours. The same failure of a delivery is* named at most this often. */@@ -350,6 +369,14 @@ export class SuperTabHost {/** 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, { text: string; paths: string[] }>()+ /** Each delivery's download still running or not yet taken by a pass, off the poll loop. It goes once a pass takes it, when+ * the delivery leaves the journal, and when the host stops. */+ private readonly downloads = new Map<string, Download>()+ /** The files those downloads are fetching, so two deliveries of one file download it once at a time (attachments.ts). */+ private readonly inFlight: FilesInFlight = new Map()+ private readonly downloadWaitMs: number+ /** This pass's one wait on the downloads it starts (DOWNLOAD_WAIT_MS), shared by all of them; null until one starts. */+ private passWait: Promise<null> | null = null/** Each delivery's quote of the message it replies to ('' when none is shown), read once like its files. A failed read is* not kept, so the next try reads again. */private readonly quotes = new Map<string, string>()@@ -444,6 +471,7 @@ export class SuperTabHost {this.file = hostJournalFile(core.dataDir, machineId)this.observers = options.observers ?? publishObserversthis.attachedFiles = options.attachedFiles ?? attachedFiles+ this.downloadWaitMs = options.downloadWaitMs ?? DOWNLOAD_WAIT_MSthis.prepareContribution = options.prepareContribution ?? prepareContributionthis.machineDeps = options.machines ?? {}this.prepareTeam = options.prepareTeam ?? ((core, input) => prepareTeamContribution(core, input))@@ -520,6 +548,8 @@ export class SuperTabHost {// A running Buddy loses its wide grant at once (final review of #2310): the account it held for is none until a start.try { writeBuddyAccount(null) } catch { /* the next start writes none again until it knows */ }this.stopped = true+ for (const deliveryId of [...this.downloads.keys()]) this.dropDownload(deliveryId)+ this.inFlight.clear()if (this.timer) clearInterval(this.timer)this.timer = nullthis.stopHearing()@@ -834,6 +864,7 @@ export class SuperTabHost {return retry}private async poll(): Promise<void> {+ this.passWait = null// Each second, unless the server pushes Swarm changes: then when told, and in full each minute (hostFeed.ts due).const data = (await this.sources.feed.due()).rosterif (this.stopped) return@@ -943,12 +974,19 @@ export class SuperTabHost {const read = { readAt: this.now(), ids: deliveries.map(item => object(item).id).filter(identifier), busy: true }this.lists.set(listKey, read)this.deliveryRetries.delete(listKey)+ // One waiting for its files holds the agent's later deliveries: they reach it after it, in order.+ let held = falsefor (const item of deliveries) {const delivery = object(item)if (!identifier(delivery.id)) continueseen.add(delivery.id)+ if (held) continueconst claimKey = `claim:${delivery.id}`- if (this.backedOff(claimKey)) continue+ if (this.backedOff(claimKey)) {+ const download = this.downloads.get(delivery.id)+ if (download?.said && !download.result) held = true+ continue+ }// Checked before anything is typed: a new delivery, or one held while its agent may since have stopped leading. A// claimed one with no journal is never typed, only reported as uncertain; a delivered one only acknowledged.const entry = this.journal.entries[delivery.id]@@ -959,6 +997,12 @@ export class SuperTabHost {this.deliveryRetries.delete(claimKey)if (failed && failed.failures > 0) this.log(`Delivery ${delivery.id} went through after ${failed.failures + 1} tries, ${Math.round((this.now() - failed.since) / 60_000)} min.`)} catch (error) {+ // Its files still downloading: tried again, quietly, and the agent's later deliveries wait behind it, in order.+ if (error instanceof FilesDownloading) {+ this.retryLater(claimKey, listKey)+ claimError = error+ throw error+ }// Answered (or resolved by a person) between the roster read and this call: nothing is owed, and the// agent's other deliveries go on.if (!(error instanceof SuperTabHostError) || error.code !== 'DELIVERY_RESOLVED') {@@ -1014,6 +1058,7 @@ export class SuperTabHost {else if (key.startsWith('claim:') && listsRead.has(agentKey) && !listed.has(key.slice('claim:'.length))) this.deliveryRetries.delete(key)}for (const deliveryId of this.files.keys()) if (!this.journal.entries[deliveryId]) this.files.delete(deliveryId)+ for (const deliveryId of [...this.downloads.keys()]) if (!this.journal.entries[deliveryId]) this.dropDownload(deliveryId)for (const deliveryId of this.quotes.keys()) if (!this.journal.entries[deliveryId]) this.quotes.delete(deliveryId)for (const entry of Object.values(this.journal.entries)) {const id = typedId(entry)@@ -1480,6 +1525,7 @@ export class SuperTabHost {if (!entry) returnconst id = typedId(entry)delete this.journal.entries[deliveryId]+ this.dropDownload(deliveryId)this.lateAcks.delete(deliveryId)this.withheld.clear(deliveryId)this.authorized.delete(id)@@ -1558,7 +1604,7 @@ export class SuperTabHost {// 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)+ const downloaded = await this.downloaded(deliveryId, message, `list:${target.tabId}:${target.agent.id}`)files = { text: downloaded.text, paths: downloaded.paths }if (downloaded.complete) this.files.set(deliveryId, files)}@@ -1627,6 +1673,48 @@ export class SuperTabHost {this.core.turns.deliver(entry.harnessId, this.prompt(entry, message, attached, command, quote ?? '', result.buddyNews === true), id)}+ /** A delivery's files, downloaded off the poll loop. A pass waits only on the downloads it starts, all together for at most+ * downloadWaitMs (passWait); one still running is FilesDownloading, checked without a wait, and starts a pass of its own once+ * in. A download whose tries all failed answers its "Could not download" lines, delivered as before. */+ private async downloaded(deliveryId: string, message: Json, listKey: string): Promise<Awaited<ReturnType<typeof attachedFiles>>> {+ let download = this.downloads.get(deliveryId)+ if (!download) {+ const stop = new AbortController()+ const pending = this.attachedFiles(message, { inFlight: this.inFlight, signal: stop.signal })+ .then(done => ({ done }), (error: unknown) => ({ error }))+ const started: Download = download = { pending, stop, said: false }+ this.downloads.set(deliveryId, started)+ void pending.then(result => {+ started.result = result+ if (!started.said || this.downloads.get(deliveryId) !== started || this.stopped) return+ // Delivered at once, not after its back-off.+ this.deliveryRetries.delete(`claim:${deliveryId}`)+ this.pushes.add(listKey)+ void this.tick()+ })+ // Never cleared: the pass's later downloads wait on the same timer.+ this.passWait ??= new Promise<null>(resolve => { setTimeout(() => resolve(null), this.downloadWaitMs).unref?.() })+ await Promise.race([pending, this.passWait])+ }+ if (!download.result) {+ const bytes = attachmentsOf(message).reduce((sum, file) => sum + file.size, 0)+ if (!download.said) this.log(`Delivery ${deliveryId}: its files (${formatSize(bytes)}) are downloading; it goes in once they are.`)+ download.said = true+ throw new FilesDownloading(`Its files are still downloading (${formatSize(bytes)}).`)+ }+ this.downloads.delete(deliveryId)+ if ('error' in download.result) throw download.result.error+ return download.result.done+ }++ /** A delivery's download it no longer waits for: stopped, unless another delivery shares its file (attachments.ts). */+ private dropDownload(deliveryId: string): void {+ const download = this.downloads.get(deliveryId)+ if (!download) return+ this.downloads.delete(deliveryId)+ download.stop.abort()+ }+/** Whether a Buddy's delivery is its own person's message in their own Buddy chat, the one source of files and links its* guard lets it read (lib/buddyGuard.ts). Which agent the session is comes from this host: the id the backend gave the* agent this machine's session joined as. The Swarm as the Buddy reads it now decides the rest, never the delivery alone;diff --git a/cli/src/superTabs/service.ts b/cli/src/superTabs/service.tsindex 90f452b40..6452a0101 100644--- a/cli/src/superTabs/service.ts+++ b/cli/src/superTabs/service.ts@@ -39,7 +39,7 @@ import { createPullRequestsStatusReader } from '../lib/pullRequestsStatus.js'import { buddyArchived, buddyStatus, isBuddyIn, type BuddyStatusDeps } from './buddyStatus.js'import { startSubscriptionRelay } from '../lib/subscriptionRelay.js'-const POST_ABOUT = '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. --to names the agents it reaches (any agent of this project, by id from status; up to 16): they join the conversation if they are not in it. With no --to, your post reaches the PM.'+const POST_ABOUT = '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 256 MB each), and TEXT may then be empty. --to names the agents it reaches (any agent of this project, by id from status; up to 16): they join the conversation if they are not in it. With no --to, your post reaches the PM.'const POST_HELP = `${POST_ABOUT} TEXT is one argument: when it holds quotes, or is only -, put - in its place and send the message on stdin (post GROUP - OPERATION_ID <<'MSG' … MSG); an empty stdin is refused and nothing is posted.`/** A Buddy's guard refuses TEXT - (#2358): on stdin its message would skip the secret check. A Buddy that followed the stdin* hint was refused and tried again, so its help passes the message in quotes, as the guard's refusal says. */diff --git a/desktop/lib/api/api_client.dart b/desktop/lib/api/api_client.dartindex 7675bdd7f..9944e0cda 100644--- a/desktop/lib/api/api_client.dart+++ b/desktop/lib/api/api_client.dart@@ -277,6 +277,25 @@ class ApiClient {),);+ /// Posts [body] as JSON to [path] and answers whatever came back, a refusal+ /// too: the steps either side of a file sent straight to storage. Like+ /// [postForm], through the local daemon on a computer and to the backend+ /// with this browser's token.+ Future<Response<dynamic>> postJson(+ String path,+ Map<String, dynamic> body, {+ CancelToken? cancelToken,+ }) => _dio.post<dynamic>(+ path,+ data: body,+ cancelToken: cancelToken,+ options: Options(+ // Finishing checks the stored file before it answers.+ receiveTimeout: const Duration(minutes: 2),+ headers: auth == null ? {'x-adapter-local': '1'} : null,+ ),+ );+/// One Swarm call ([method] on [path], `/api/super-tabs…`) straight to the/// backend with this browser's sign-in, answered whole: the web's Swarm/// transport (super_tabs/backend_transport.dart) reads the envelope, as adiff --git a/desktop/lib/clipboard/copied_files.dart b/desktop/lib/clipboard/copied_files.dartindex 199d59cae..916b0ed97 100644--- a/desktop/lib/clipboard/copied_files.dart+++ b/desktop/lib/clipboard/copied_files.dart@@ -5,26 +5,41 @@ import 'package:path/path.dart' as p;import 'pasted_files.dart';/// Files copied in a file manager, read off this computer's disk: those that-/// fit, and the names of those that did not.-typedef CopiedFiles = ({List<PastedFile> files, List<String> tooLarge});+/// fit, the names of those that did not, and those left on disk to be read as+/// they are sent.+typedef CopiedFiles = ({+ List<PastedFile> files,+ List<String> tooLarge,+ List<CopiedFileOnDisk> onDisk,+});++/// A copied file too heavy to read now, weighed when it was pasted.+typedef CopiedFileOnDisk = ({String name, String path, int size});/// Reads the files at [paths], which a clipboard named/// ([NativeClipboard.readFilePaths]). A folder is left out, as is a file that-/// is gone or cannot be read. One over [maxBytes] is named in `tooLarge` and-/// never read: a copied video is not pulled into memory to be refused.+/// is gone or cannot be read. One over [maxBytes] is never read: a copied+/// video is not pulled into memory to be refused. It is named in `tooLarge`,+/// or with [keepOnDisk] listed in `onDisk` by its path and size, for a box+/// that sends large files from disk and refuses by size what it cannot take.Future<CopiedFiles> readCopiedFiles(Iterable<String> paths, {required int maxBytes,+ bool keepOnDisk = false,}) async {final files = <PastedFile>[];final tooLarge = <String>[];+ final onDisk = <CopiedFileOnDisk>[];for (final path in paths) {final name = p.basename(path);try {if (!await FileSystemEntity.isFile(path)) continue;final file = File(path);- if (await file.length() > maxBytes) {- tooLarge.add(name);+ final size = await file.length();+ if (size > maxBytes) {+ keepOnDisk+ ? onDisk.add((name: name, path: path, size: size))+ : tooLarge.add(name);continue;}files.add((name: name, bytes: await file.readAsBytes()));@@ -32,5 +47,5 @@ Future<CopiedFiles> readCopiedFiles(continue;}}- return (files: files, tooLarge: tooLarge);+ return (files: files, tooLarge: tooLarge, onDisk: onDisk);}diff --git a/desktop/lib/state/app_state.dart b/desktop/lib/state/app_state.dartindex 871867acb..fe115088f 100644--- a/desktop/lib/state/app_state.dart+++ b/desktop/lib/state/app_state.dart@@ -1843,7 +1843,7 @@ class AppNotifier extends ChangeNotifier {required conversationId,required name,required mime,- required bytes,+ required file,required cancel,required onProgress,}) => _teamComputer@@ -1858,7 +1858,7 @@ class AppNotifier extends ChangeNotifier {conversationId: conversationId,name: name,mime: mime,- bytes: bytes,+ file: file,cancel: cancel,onProgress: onProgress,),diff --git a/desktop/lib/state/attached_task_delivery.dart b/desktop/lib/state/attached_task_delivery.dartindex 09187e459..e119c781b 100644--- a/desktop/lib/state/attached_task_delivery.dart+++ b/desktop/lib/state/attached_task_delivery.dart@@ -108,7 +108,7 @@ Future<String?> deliverAttachedTask(if (stillWanted != null && !stillWanted()) {return 'Attachment delivery stopped.';}- if (!await session.pasteFile(file.name, file.bytes) ||+ if (!await session.pasteFile(file.name, await file.readBytes()) ||!await session.pasteText(' ')) {appLog.warn('attach', '${file.name} did not reach $agentId');return 'Could not attach ${file.name}. Attach it in the pane.';diff --git a/desktop/lib/state/harness_attachments.dart b/desktop/lib/state/harness_attachments.dartindex de20e2707..1a614406d 100644--- a/desktop/lib/state/harness_attachments.dart+++ b/desktop/lib/state/harness_attachments.dart@@ -1,15 +1,56 @@+import 'package:file_selector/file_selector.dart' show XFile;import 'package:flutter/foundation.dart';import '../terminal/terminal_binary.dart'show terminalLocalPasteFileMaxPayloadBytes;-/// One file attached to a harness that does not exist yet.+/// One file attached to a harness that does not exist yet, or to a chat+/// message: its bytes in memory, or a file on disk read only as it is sent.@immutableclass HarnessAttachment {- const HarnessAttachment(this.name, this.bytes);+ const HarnessAttachment(this.name, Uint8List this.bytes)+ : _disk = null,+ _size = 0;++ /// A file on disk, of the size it had when it was attached. It is read as+ /// it is sent, so a large file is never held whole in memory.+ const HarnessAttachment.onDisk(this.name, XFile this._disk, this._size)+ : bytes = null;final String name;- final Uint8List bytes;++ /// The file's bytes, or null when it stays on disk until it is sent.+ final Uint8List? bytes;+ final XFile? _disk;+ final int _size;++ /// This file under [name], wherever it is held.+ HarnessAttachment named(String name) => name == this.name+ ? this+ : bytes != null+ ? HarnessAttachment(name, bytes!)+ : HarnessAttachment.onDisk(name, _disk!, _size);++ /// Whether the file is read from disk as it is sent.+ bool get onDisk => _disk != null;++ /// How much it weighed when it was attached.+ int get size => bytes?.length ?? _size;++ /// How much it weighs now: a file on disk may have changed since.+ Future<int> length() async => bytes?.length ?? await _disk!.length();++ /// The whole file, read now when it is on disk.+ Future<Uint8List> readBytes() async => bytes ?? await _disk!.readAsBytes();++ /// Its first [length] bytes, as a stream read from disk as it is taken.+ Stream<List<int>> openRead(int length) {+ final held = bytes;+ if (held == null) return _disk!.openRead(0, length);+ return Stream.value(+ held.length > length ? Uint8List.sublistView(held, 0, length) : held,+ );+ }}/// The files a New Harness box carries into its harness. Held in memory@@ -19,7 +60,8 @@ class HarnessAttachments extends ChangeNotifier {this.onDeliveryProblem,this.limitBytes = maxBytes,this.limitFiles,- });+ int? readUpTo,+ }) : readUpTo = readUpTo ?? limitBytes;/// What one file may weigh: the daemon's own ceiling for a pasted file.static const maxBytes = terminalLocalPasteFileMaxPayloadBytes;@@ -28,6 +70,10 @@ class HarnessAttachments extends ChangeNotifier {/// a lower ceiling than the daemon's passes it.final int limitBytes;+ /// What a picked or dropped file may weigh to be read into memory when it+ /// is attached; a heavier one stays on disk and is read as it is sent.+ final int readUpTo;+/// How many files this box holds, or null for any number.final int? limitFiles;@@ -77,8 +123,8 @@ class HarnessAttachments extends ChangeNotifier {final tooLarge = [...oversized];var surplus = 0;for (final file in files) {- if (file.bytes.isEmpty) continue;- if (file.bytes.length > limitBytes) {+ if (file.size == 0) continue;+ if (file.size > limitBytes) {tooLarge.add(file.name);continue;}@@ -106,8 +152,7 @@ class HarnessAttachments extends ChangeNotifier {}) {final taken = {for (final file in _files) file.name};return add([- for (final file in files)- HarnessAttachment(_freeName(file.name, taken), file.bytes),+ for (final file in files) file.named(_freeName(file.name, taken)),], oversized: oversized);}diff --git a/desktop/lib/super_tabs/attachment_chips.dart b/desktop/lib/super_tabs/attachment_chips.dartindex c886ec705..cbe46a508 100644--- a/desktop/lib/super_tabs/attachment_chips.dart+++ b/desktop/lib/super_tabs/attachment_chips.dart@@ -31,8 +31,15 @@ class SuperTabAttachments extends StatelessWidget {final chips = <SuperTabAttachment>[];for (final file in attachments) {// A browser's fetch follows a redirect off the attachments host, so- // there a picture stays a chip that opens in a new tab.- final url = file.isImage && !kIsWeb ? attachmentLink(file.url) : null;+ // there a picture stays a chip that opens in a new tab. A picture over+ // the form's limit is a chip too: every reader would fetch and decode+ // it whole to draw it in place.+ final url =+ file.isImage &&+ file.size <= kSuperTabFormAttachmentMaxBytes &&+ !kIsWeb+ ? attachmentLink(file.url)+ : null;url == null ? chips.add(file) : pictures.add((file, url));}return Column(diff --git a/desktop/lib/super_tabs/attachment_upload.dart b/desktop/lib/super_tabs/attachment_upload.dartindex 9259d6ae3..360acbbd0 100644--- a/desktop/lib/super_tabs/attachment_upload.dart+++ b/desktop/lib/super_tabs/attachment_upload.dart@@ -1,16 +1,32 @@+import 'dart:async';import 'dart:convert';-import 'dart:typed_data';import 'package:dio/dio.dart';+import 'package:flutter/foundation.dart' show kIsWeb, visibleForTesting;import '../api/api_client.dart';import '../logging/app_log.dart';+import '../state/harness_attachments.dart';import 'controller.dart';+import 'model.dart' show superTabMap;-/// What the backend allows one message to carry.-const kSuperTabAttachmentMaxBytes = 10 * 1024 * 1024;+/// What one file of a message may weigh (backend superTabs/attachments.ts).+const kSuperTabAttachmentMaxBytes = 256 * 1024 * 1024;const kSuperTabAttachmentMaxFiles = 10;+/// What a file sent as one form to the attachments route may weigh. A heavier+/// one goes straight to storage on a link the backend signs: the edge in front+/// of the backend may refuse a large request.+const kSuperTabFormAttachmentMaxBytes = 10 * 1024 * 1024;++/// What a folder dropped into a chat may weigh as a zip. The zip is made and+/// held in memory until it is sent, so it keeps the form's limit.+const kSuperTabFolderZipMaxBytes = kSuperTabFormAttachmentMaxBytes;++/// What a file over [kSuperTabAttachmentMaxBytes] is refused with, before any+/// request; the backend answers the same.+const kSuperTabAttachmentTooLarge = 'Files can be up to 256 MB.';+/// 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) {@@ -53,6 +69,7 @@ Uri? attachmentLink(String url) {}/// Sends one file to the backend and returns its answer, `{attachment: {...}}`.+/// [file] may be in memory or on disk; one on disk is read as it goes up./// [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({@@ -60,7 +77,7 @@ typedef SuperTabUpload = Future<Map<String, dynamic>> Function({required String conversationId,required String name,required String mime,- required Uint8List bytes,+ required HarnessAttachment file,required CancelToken cancel,required void Function(double sent) onProgress,});@@ -71,31 +88,60 @@ Future<Map<String, dynamic>> refuseUpload({required String conversationId,required String name,required String mime,- required Uint8List bytes,+ required HarnessAttachment file,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) =>+/// Uploads with [api], straight to the backend in a browser and through the+/// local daemon on a computer. A file up to [kSuperTabFormAttachmentMaxBytes]+/// goes as one `multipart/form-data` request. A heavier one asks for a signed+/// link, goes on it straight to storage from disk with [storage] — a plain+/// client, since the link is the only credential it carries — and is then+/// finished. Either way the answer is `{attachment: {...}}`.+SuperTabUpload uploadWith(+ ApiClient Function() api, {+ Dio Function()? storage,+}) =>({required tabId,required conversationId,required name,required mime,- required bytes,+ required file,required cancel,required onProgress,}) async {+ final size = await file.length();+ if (size > kSuperTabAttachmentMaxBytes) {+ throw const SuperTabFailure(+ 'ATTACHMENT_TOO_LARGE',+ kSuperTabAttachmentTooLarge,+ );+ }+ final path = '/api/super-tabs/${Uri.encodeComponent(tabId)}/attachments';+ if (size > kSuperTabFormAttachmentMaxBytes) {+ return _uploadDirect(+ api(),+ storage ?? _storageClient,+ path: path,+ conversationId: conversationId,+ name: name,+ mime: mime,+ file: file,+ size: size,+ cancel: cancel,+ onProgress: onProgress,+ );+ }final response = await api().postForm(- '/api/super-tabs/${Uri.encodeComponent(tabId)}/attachments',+ path,FormData.fromMap({'conversationId': conversationId,'file': MultipartFile.fromBytes(- bytes,+ await file.readBytes(),filename: name,contentType: DioMediaType.parse(mime),),@@ -105,15 +151,159 @@ SuperTabUpload uploadWith(ApiClient Function() api) =>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 superTabUploadRefusal(response);+ return _attachmentOf(response);};+/// A client for storage alone: no base address, no token, no request log+/// (a signed link is a credential and is never written down).+Dio _storageClient() => Dio(+ BaseOptions(+ connectTimeout: const Duration(seconds: 15),+ // Storage answers once the last byte is in.+ receiveTimeout: const Duration(minutes: 2),+ ),+);++/// The answer's `data` when the backend took the file, or the refusal.+Map<String, dynamic> _attachmentOf(Response<dynamic> response) {+ final body = response.data;+ if (response.statusCode == 200 && body is Map && body['success'] == true) {+ return Map<String, dynamic>.from(body['data'] as Map);+ }+ throw superTabUploadRefusal(response);+}++/// A file over the form's limit: a link for it, the bytes straight to storage+/// on it, then the backend told to finish. Any failure on the way leaves+/// nothing to resume: a link writes once, so a retry starts over.+Future<Map<String, dynamic>> _uploadDirect(+ ApiClient api,+ Dio Function() storage, {+ required String path,+ required String conversationId,+ required String name,+ required String mime,+ required HarnessAttachment file,+ required int size,+ required CancelToken cancel,+ required void Function(double sent) onProgress,+}) async {+ final asked = await api.postJson('$path/uploads', {+ 'conversationId': conversationId,+ 'name': name,+ 'mime': mime,+ 'size': size,+ }, cancelToken: cancel);+ // A CLI that does not pass the route on answers its own 404, a bare code.+ final askedBody = asked.data;+ if (asked.statusCode == 404 &&+ askedBody is Map &&+ askedBody['error'] is! Map) {+ throw const SuperTabFailure(+ 'UPDATE_HARNESS',+ 'Update Harness on this computer to send files over 10 MB.',+ statusCode: 404,+ );+ }+ final link = superTabMap(_attachmentOf(asked)['upload']);+ final id = link['id'], url = link['url'], headers = link['headers'];+ if (id is! String ||+ url is! String ||+ headers is! Map ||+ !superTabStorageLinkAllowed(url)) {+ // Not the link: it is a credential.+ appLog.warn('super-tabs', 'upload link unreadable or not https');+ throw SuperTabFailure(+ 'UPLOAD_FAILED',+ 'Could not upload $name. Try again.',+ );+ }+ await _put(+ storage(),+ url,+ {+ for (final MapEntry(:key, :value) in headers.entries) '$key': '$value',+ Headers.contentLengthHeader: '$size',+ },+ name: name,+ file: file,+ size: size,+ cancel: cancel,+ onProgress: onProgress,+ );+ final done = await api.postJson(+ '$path/uploads/${Uri.encodeComponent(id)}/complete',+ const {},+ cancelToken: cancel,+ );+ return _attachmentOf(done);+}++/// Whether a file may be sent to storage at [url]: https only, so the bytes+/// and the link's signature never cross a network in the clear. A computer+/// also takes plain http to itself, for a local stack.+@visibleForTesting+bool superTabStorageLinkAllowed(String url, {bool web = kIsWeb}) {+ final link = Uri.tryParse(url);+ if (link == null || link.host.isEmpty || link.userInfo.isNotEmpty) {+ return false;+ }+ return link.scheme == 'https' ||+ (!web &&+ link.scheme == 'http' &&+ const {'127.0.0.1', 'localhost'}.contains(link.host));+}++/// Sends [file]'s [size] bytes to [url] with [headers], read as they go.+/// Neither the link nor what storage says reaches a log or an error: the link+/// is a credential, and storage's refusal can quote it.+Future<void> _put(+ Dio storage,+ String url,+ Map<String, String> headers, {+ required String name,+ required HarnessAttachment file,+ required int size,+ required CancelToken cancel,+ required void Function(double sent) onProgress,+}) async {+ final failed = SuperTabFailure(+ 'UPLOAD_FAILED',+ 'Could not upload $name. Try again.',+ );+ // A token of its own, so the one handed in never holds the link's request+ // (its cancel error carries the request, URL and all).+ final put = CancelToken();+ if (cancel.isCancelled) throw cancel.cancelError!;+ unawaited(cancel.whenCancel.then((_) => put.cancel('given up')));+ try {+ final response = await storage.put<dynamic>(+ url,+ data: file.openRead(size),+ cancelToken: put,+ onSendProgress: (sent, _) => onProgress(sent / size),+ options: Options(+ headers: headers,+ responseType: ResponseType.plain,+ validateStatus: (_) => true,+ followRedirects: false,+ ),+ );+ final status = response.statusCode ?? 0;+ if (status < 200 || status >= 300) {+ appLog.warn('super-tabs', 'upload to storage refused (status $status)');+ throw failed;+ }+ } on DioException catch (failure) {+ if (cancel.isCancelled) throw cancel.cancelError!;+ appLog.warn(+ 'super-tabs',+ 'upload to storage failed (${failure.type.name})',+ );+ throw failed;+ }+}+/// What a refused upload says. The backend answers `{error: {code, message}}`;/// the local daemon, a bare code string such as `{error: 'FORBIDDEN'}`. Either/// may reach here as a String Dio did not decode.@@ -141,7 +331,7 @@ SuperTabFailure superTabUploadRefusal(Response<dynamic> response) {message ??switch (code) {'FORBIDDEN' => 'You can’t send files in this conversation.',- 'ATTACHMENT_TOO_LARGE' => 'That file is over 10 MB.',+ 'ATTACHMENT_TOO_LARGE' => kSuperTabAttachmentTooLarge,'AVATAR_TOO_LARGE' => 'That picture is over 1 MB.','AVATAR_TYPE' => 'Use a PNG, JPEG or WebP picture.',null => 'Could not upload the file. Try again.',diff --git a/desktop/lib/super_tabs/attachment_viewer.dart b/desktop/lib/super_tabs/attachment_viewer.dartindex dfcb6bf31..d7bc53ee9 100644--- a/desktop/lib/super_tabs/attachment_viewer.dart+++ b/desktop/lib/super_tabs/attachment_viewer.dart@@ -10,10 +10,12 @@ import 'package:flutter/material.dart';import '../core/open_in_browser.dart';import '../finder/finder_file_kind.dart';import '../widgets/desktop_chrome.dart';+import 'attachment_upload.dart' show kSuperTabFormAttachmentMaxBytes;import 'model.dart';/// The largest file read into the chat's text viewer; a bigger one opens in-/// the browser. Specs and logs sit well under it, and the backend takes 10 MB.+/// the browser. Specs and logs sit well under it, though a message's file may+/// weigh up to 256 MB.const kAttachmentTextMaxBytes = 2 * 1024 * 1024;/// Reads a file off the attachments host, when a person asks for it.@@ -176,8 +178,13 @@ class AttachmentImage extends ImageProvider<AttachmentImage> {debugLabel: url.toString(),);- Future<ui.Codec> _decode(ImageDecoderCallback decode) async =>- decode(await ui.ImmutableBuffer.fromUint8List(await readAttachment(url)));+ // No more than a picture shown in place may weigh, whatever its row says:+ // a larger one fails to draw rather than being read whole.+ Future<ui.Codec> _decode(ImageDecoderCallback decode) async => decode(+ await ui.ImmutableBuffer.fromUint8List(+ await readAttachment(url, maxBytes: kSuperTabFormAttachmentMaxBytes),+ ),+ );@overridebool operator ==(Object other) =>diff --git a/desktop/lib/super_tabs/controller.dart b/desktop/lib/super_tabs/controller.dartindex d2ac2e9c9..d5ef221dc 100644--- a/desktop/lib/super_tabs/controller.dart+++ b/desktop/lib/super_tabs/controller.dart@@ -936,6 +936,8 @@ class SuperTabController extends ChangeNotifier {final files = HarnessAttachments(limitBytes: kSuperTabAttachmentMaxBytes,limitFiles: kSuperTabAttachmentMaxFiles,+ // A heavier file stays on disk until it goes, straight to storage.+ readUpTo: kSuperTabFormAttachmentMaxBytes,);files.addListener(() {// Changing the files answers a refused upload.@@ -2223,6 +2225,9 @@ class SuperTabController extends ChangeNotifier {}_queuedSends.clear();_poll?.cancel();+ // A file on its way stops: a large one would go on to storage for an+ // account that no longer reads this Swarm.+ cancelUpload();_changed();}@@ -3405,6 +3410,7 @@ class SuperTabController extends ChangeNotifier {_quoting.clear();_forgetThreads();_poll?.cancel();+ cancelUpload();}}@@ -4209,7 +4215,7 @@ class SuperTabController extends ChangeNotifier {conversationId: conversationId,name: file.name,mime: mimeForName(file.name),- bytes: file.bytes,+ file: file,cancel: token,onProgress: (sent) {watch();@@ -4259,6 +4265,8 @@ class SuperTabController extends ChangeNotifier {then();}_onDispose.clear();+ // Closing the tab or signing out stops a file on its way.+ cancelUpload();for (final queued in _queuedSends) {queued.result.complete(null);}diff --git a/desktop/lib/super_tabs/launch.dart b/desktop/lib/super_tabs/launch.dartindex f9d5f1790..214e729b0 100644--- a/desktop/lib/super_tabs/launch.dart+++ b/desktop/lib/super_tabs/launch.dart@@ -656,7 +656,7 @@ class SuperTabLaunch {conversationId: conversationId,name: file.name,mime: mimeForName(file.name),- bytes: file.bytes,+ file: file,cancel: CancelToken(),onProgress: (_) {},))['attachment'],@@ -889,7 +889,7 @@ class SuperTabLaunch {checkAccount();saved['files'] = [for (final file in files)- {'name': file.name, 'bytes': base64Encode(file.bytes)},+ {'name': file.name, 'bytes': base64Encode(await file.readBytes())},];saved['launchPrompt'] = prompt;saved['filesState'] = 'pending';diff --git a/desktop/lib/super_tabs/view.dart b/desktop/lib/super_tabs/view.dartindex 04857fc48..9038256df 100644--- a/desktop/lib/super_tabs/view.dart+++ b/desktop/lib/super_tabs/view.dart@@ -30,6 +30,7 @@ import 'live_card.dart';import 'personal_projects.dart';import 'pull_request_facts.dart';import 'pull_requests.dart';+import 'attachment_upload.dart' show kSuperTabFolderZipMaxBytes;import 'composer_files.dart';import 'composer_newline.dart';import 'composer_tags.dart';@@ -829,9 +830,16 @@ class _SuperTabViewState extends State<SuperTabView>final oversized = <String>[], failed = <String>[];for (final folder in folders) {try {- final bytes = await zipFolder(folder, limitBytes: files.limitBytes);- bytes == null- ? oversized.add(folderName(folder))+ final bytes = await zipFolder(+ folder,+ limitBytes: kSuperTabFolderZipMaxBytes,+ );+ bytes == null || bytes.length > kSuperTabFolderZipMaxBytes+ ? oversized.add(+ bytes == null+ ? folderName(folder)+ : '${folderName(folder)}.zip',+ ): zipped[folder] = bytes;} on Exception {// Unreadable, or gone since the drop.@@ -842,10 +850,13 @@ class _SuperTabViewState extends State<SuperTabView>setState(() => _zipping.remove(id));if (!identical(_droppedFolders[id], dropped)) return;// Numbered, so two folders of one name are both attached.- final problem = files.addPasted([- for (final MapEntry(key: folder, value: bytes) in zipped.entries)- HarnessAttachment('${folderName(folder)}.zip', bytes),- ], oversized: oversized);+ final added = zipped.isEmpty+ ? null+ : files.addPasted([+ for (final MapEntry(key: folder, value: bytes) in zipped.entries)+ HarnessAttachment('${folderName(folder)}.zip', bytes),+ ]);+ final problem = added ?? _folderZipsTooLarge(oversized);// Only a folder whose zip was taken gives up its path.final attached = [for (final MapEntry(key: folder, value: bytes) in zipped.entries)@@ -877,6 +888,16 @@ class _SuperTabViewState extends State<SuperTabView>);}+ /// What to say of the folders whose zips are over+ /// [kSuperTabFolderZipMaxBytes], or null for none.+ static String? _folderZipsTooLarge(List<String> names) {+ if (names.isEmpty) return null;+ const limit = '${kSuperTabFolderZipMaxBytes ~/ (1024 * 1024)} MB';+ return names.length == 1+ ? '${names.single} is over $limit.'+ : '${names.length} folders are over $limit.';+ }+/// The box was edited: keep it as this chat's draft and drop the pick state.void _composerEdited(String text) {c.setDraft(c.selectedId, text);diff --git a/desktop/lib/widgets/new_harness_attachment_chip.dart b/desktop/lib/widgets/new_harness_attachment_chip.dartindex ef48dbda7..d50f2caff 100644--- a/desktop/lib/widgets/new_harness_attachment_chip.dart+++ b/desktop/lib/widgets/new_harness_attachment_chip.dart@@ -48,11 +48,18 @@ class NewHarnessAttachmentChip extends StatelessWidget {size: 13,color: DesktopChrome.muted,);- if (!looksLikeImage(file.bytes)) return icon;+ // A heavy file — left on disk, or a large picture pasted — shows its+ // kind's mark: a preview would decode it whole.+ final bytes = file.bytes;+ if (bytes == null ||+ bytes.length > _previewMaxBytes ||+ !looksLikeImage(bytes)) {+ return icon;+ }return ClipRRect(borderRadius: BorderRadius.circular(3),child: Image.memory(- file.bytes,+ bytes,key: ValueKey('new-harness-attachment-preview:${file.name}'),width: _previewSize,height: _previewSize,@@ -67,6 +74,9 @@ class NewHarnessAttachmentChip extends StatelessWidget {static const _previewSize = 16.0;+ /// The largest picture previewed in its chip (a chat's form limit).+ static const _previewMaxBytes = 10 * 1024 * 1024;+@overrideWidget build(BuildContext context) => Container(key: ValueKey('new-harness-attachment:${file.name}'),diff --git a/desktop/lib/widgets/new_harness_attachments.dart b/desktop/lib/widgets/new_harness_attachments.dartindex ee9e4601c..8eedaa240 100644--- a/desktop/lib/widgets/new_harness_attachments.dart+++ b/desktop/lib/widgets/new_harness_attachments.dart@@ -18,12 +18,27 @@ import 'new_harness_attachment_chip.dart';Future<String?> _attach(HarnessAttachments attachments,Iterable<XFile> files,+) async => attachments.add(await attachmentsOf(attachments, files));++/// [files] as [attachments] holds them, weighed before any is read: one over+/// its [HarnessAttachments.readUpTo] stays on disk and is read as it is sent,+/// and one over its [HarnessAttachments.limitBytes] is never read at all, as+/// [HarnessAttachments.add] refuses it by its size.+@visibleForTesting+Future<List<HarnessAttachment>> attachmentsOf(+ HarnessAttachments attachments,+ Iterable<XFile> files,) async {- final read = [- for (final file in files)- HarnessAttachment(file.name, await file.readAsBytes()),- ];- return attachments.add(read);+ final weighed = <HarnessAttachment>[];+ for (final file in files) {+ final size = await file.length();+ weighed.add(+ size > attachments.readUpTo+ ? HarnessAttachment.onDisk(file.name, file, size)+ : HarnessAttachment(file.name, await file.readAsBytes()),+ );+ }+ return weighed;}/// Attaches the dropped files and hands [onFolders] the dropped folders'diff --git a/desktop/lib/widgets/new_harness_paste.dart b/desktop/lib/widgets/new_harness_paste.dartindex f59230586..14f2c762f 100644--- a/desktop/lib/widgets/new_harness_paste.dart+++ b/desktop/lib/widgets/new_harness_paste.dart@@ -1,5 +1,6 @@import 'dart:async';+import 'package:file_selector/file_selector.dart' show XFile;import 'package:flutter/material.dart';import 'package:flutter/services.dart';@@ -14,10 +15,13 @@ import 'new_harness_attachments.dart';/// holds pixels, not a file, so the picture has no name of its own.const kPastedImageName = 'pasted-image.png';-/// The files a file manager's Copy left on this computer's clipboard.+/// The files a file manager's Copy left on this computer's clipboard. One too+/// heavy to read now stays on disk; the box it is pasted in refuses it by its+/// size, or sends it from disk.Future<CopiedFiles> _clipboardFiles() async => readCopiedFiles(await NativeClipboard.readFilePaths(),maxBytes: HarnessAttachments.maxBytes,+ keepOnDisk: true,);/// Paste in [child]'s task field attaches what the clipboard holds besides@@ -107,7 +111,9 @@ class _NewHarnessPasteTargetState extends State<NewHarnessPasteTarget> {final target = widget.attachments;await target.reading(() async {final copied = await widget.readFiles();- if (copied.files.isNotEmpty || copied.tooLarge.isNotEmpty) {+ if (copied.files.isNotEmpty ||+ copied.tooLarge.isNotEmpty ||+ copied.onDisk.isNotEmpty) {return _attachCopied(target, copied);}if (pastedTextWins(await _clipboardText())) {@@ -121,7 +127,11 @@ class _NewHarnessPasteTargetState extends State<NewHarnessPasteTarget> {void _attachCopied(HarnessAttachments target, CopiedFiles copied) => _attach(target,- [for (final file in copied.files) HarnessAttachment(file.name, file.bytes)],+ [+ for (final file in copied.files) HarnessAttachment(file.name, file.bytes),+ for (final file in copied.onDisk)+ HarnessAttachment.onDisk(file.name, XFile(file.path), file.size),+ ],oversized: copied.tooLarge,);diff --git a/desktop/test/copied_files_test.dart b/desktop/test/copied_files_test.dartindex f588cd1e4..5d841d889 100644--- a/desktop/test/copied_files_test.dart+++ b/desktop/test/copied_files_test.dart@@ -36,6 +36,22 @@ void main() {expect(copied.files.single.name, 'at-the-limit.bin');});+ test('kept on disk, one over the limit is listed by its path and size, '+ 'never read', () async {+ final movie = write('movie.mov', List.filled(17, 0));+ final copied = await readCopiedFiles(+ [+ movie,+ write('small.txt', [1]),+ ],+ maxBytes: 16,+ keepOnDisk: true,+ );+ expect(copied.onDisk, [(name: 'movie.mov', path: movie, size: 17)]);+ expect(copied.tooLarge, isEmpty);+ expect(copied.files.single.name, 'small.txt');+ });+test('a folder, and a file that is gone, are left out', () async {Directory('${dir.path}/folder').createSync();final copied = await readCopiedFiles([diff --git a/desktop/test/harness_attachments_test.dart b/desktop/test/harness_attachments_test.dartindex 72882ad55..dcf8d9972 100644--- a/desktop/test/harness_attachments_test.dart+++ b/desktop/test/harness_attachments_test.dart@@ -113,7 +113,7 @@ void main() {expect(files.add([_file('a.png'), _file('b.txt')]), isNull);expect(files.add([_file('a.png', 8)]), isNull);expect(files.files.map((f) => f.name), ['b.txt', 'a.png']);- expect(files.files.last.bytes.length, 8);+ expect(files.files.last.size, 8);final problem = files.add([_file('huge.mov', HarnessAttachments.maxBytes + 1),]);diff --git a/desktop/test/new_harness_paste_test.dart b/desktop/test/new_harness_paste_test.dartindex 2d40b792d..08ea5cd38 100644--- a/desktop/test/new_harness_paste_test.dart+++ b/desktop/test/new_harness_paste_test.dart@@ -7,6 +7,7 @@ import 'package:flutter/material.dart';import 'package:flutter/services.dart';import 'package:flutter_test/flutter_test.dart';import 'package:harness/clipboard/copied_files.dart';+import 'package:harness/clipboard/pasted_files.dart';import 'package:harness/clipboard/pasted_text.dart';import 'package:harness/state/harness_attachments.dart';import 'package:harness/widgets/new_harness_attachments.dart';@@ -43,10 +44,15 @@ void main() {Future<({HarnessAttachments files, TextEditingController task})> mount(WidgetTester tester, {Uint8List? image,- CopiedFiles copied = (files: const [], tooLarge: const []),+ CopiedFiles copied = (+ files: const [],+ tooLarge: const [],+ onDisk: const [],+ ),bool enabled = true,+ int limitBytes = HarnessAttachments.maxBytes,}) async {- final files = HarnessAttachments();+ final files = HarnessAttachments(limitBytes: limitBytes);final task = TextEditingController();final focus = FocusNode();addTearDown(files.dispose);@@ -142,6 +148,7 @@ void main() {(name: 'shot.png', bytes: _png),],tooLarge: const [],+ onDisk: const [],),);await paste(tester);@@ -169,6 +176,7 @@ void main() {(name: 'notes.txt', bytes: Uint8List.fromList([1])),],tooLarge: const ['movie.mov'],+ onDisk: const [],),);await paste(tester);@@ -177,6 +185,31 @@ void main() {debugDefaultTargetPlatformOverride = null;});+ testWidgets('a copied file too heavy to read is attached from disk where '+ 'the box takes it, and refused by its size where not', (tester) async {+ const size = 30 * 1024 * 1024;+ const copied = (+ files: <PastedFile>[],+ tooLarge: <String>[],+ onDisk: [(name: 'cad.step', path: '/nowhere/cad.step', size: size)],+ );+ final chat = await mount(+ tester,+ copied: copied,+ limitBytes: 256 * 1024 * 1024,+ );+ await paste(tester);+ expect(names(chat.files), ['cad.step']);+ expect(chat.files.files.single.onDisk, isTrue);+ expect(chat.files.files.single.size, size);++ final harness = await mount(tester, copied: copied);+ await paste(tester);+ expect(harness.files.isEmpty, isTrue);+ expect(find.text('cad.step is over 20 MB.'), findsOneWidget);+ debugDefaultTargetPlatformOverride = null;+ });+testWidgets('a locked box attaches nothing', (tester) async {final box = await mount(tester, image: _png, enabled: false);await paste(tester);@@ -227,6 +260,32 @@ void main() {debugDefaultTargetPlatformOverride = null;});+ testWidgets('a picture over 10 MB shows its kind\'s mark, not a preview', (+ tester,+ ) async {+ // A PNG's header on 10 MB and a byte: decoding it would read it all.+ final big = Uint8List(10 * 1024 * 1024 + 1)..setAll(0, _png);+ final files = HarnessAttachments(limitBytes: 256 * 1024 * 1024)+ ..add([HarnessAttachment('big.png', big)]);+ addTearDown(files.dispose);+ await tester.pumpWidget(+ MaterialApp(+ home: Scaffold(+ body: NewHarnessAttachmentChips(attachments: files, enabled: true),+ ),+ ),+ );+ expect(+ find.byKey(const ValueKey('new-harness-attachment-preview:big.png')),+ findsNothing,+ );+ expect(+ find.byKey(const ValueKey('new-harness-attachment-icon:big.png')),+ findsOneWidget,+ );+ debugDefaultTargetPlatformOverride = null;+ });+test('pasted files are numbered, never swapped for one of their name', () {final files = HarnessAttachments()..add([HarnessAttachment('image.png', _png)]);diff --git a/desktop/test/super_tab_attachments_test.dart b/desktop/test/super_tab_attachments_test.dartindex 64ad7b56d..57d200b16 100644--- a/desktop/test/super_tab_attachments_test.dart+++ b/desktop/test/super_tab_attachments_test.dart@@ -5,6 +5,7 @@import 'dart:async';import 'dart:convert';import 'dart:io';+import 'dart:math' show min;import 'package:dio/dio.dart' show CancelToken;import 'package:file_selector_platform_interface/file_selector_platform_interface.dart';@@ -41,6 +42,35 @@ class _Picked extends XFile {@overrideFuture<Uint8List> readAsBytes() async => bytes;++ @override+ Future<int> length() async => bytes.length;+}++/// A file of [size] bytes that is never read whole: reading it fails the test.+class _Sized extends XFile {+ _Sized(this.size, {this.fileName = 'cad.step'}) : super('/picked/$fileName');++ final int size;+ final String fileName;++ @override+ String get name => fileName;++ @override+ Future<int> length() async => size;++ @override+ Future<Uint8List> readAsBytes() =>+ throw StateError('$fileName was read whole');++ @override+ Stream<Uint8List> openRead([int? start, int? end]) async* {+ const chunk = 64 * 1024;+ for (var at = start ?? 0; at < (end ?? size); at += chunk) {+ yield Uint8List(min(chunk, (end ?? size) - at));+ }+ }}class _Picker extends FileSelectorPlatform {@@ -234,21 +264,107 @@ void main() {await close(tester, controller);});- test('a file over 10 MB, or an eleventh file, is refused', () {+ testWidgets('a picked file over 10 MB stays on disk, and goes up from '+ 'there', (tester) async {+ const size = 12 * 1024 * 1024;+ final original = FileSelectorPlatform.instance;+ FileSelectorPlatform.instance = _Picker([_Sized(size)]);+ addTearDown(() => FileSelectorPlatform.instance = original);+ final server = ConversationServer();+ final sent = <(bool, int)>[];+ final controller = server.controller(+ upload:+ ({+ required tabId,+ required conversationId,+ required name,+ required mime,+ required file,+ required cancel,+ required onProgress,+ }) async {+ var read = 0;+ await for (final chunk in file.openRead(await file.length())) {+ read += chunk.length;+ }+ sent.add((file.onDisk, read));+ // The fixture keeps a stand-in: the file itself is not held.+ return server.upload(+ tabId: tabId,+ conversationId: conversationId,+ name: name,+ mime: mime,+ file: HarnessAttachment(name, Uint8List(1)),+ cancel: cancel,+ onProgress: onProgress,+ );+ },+ );+ await controller.refresh();+ await mount(tester, controller);++ await tester.tap(find.byKey(const ValueKey('new-harness-attach')));+ await tester.pumpAndSettle();+ expect(names(controller), ['cad.step']);+ expect(controller.attachments('lead').files.single.onDisk, isTrue);+ expect(controller.attachments('lead').files.single.size, size);++ await tester.tap(send);+ await tester.pumpAndSettle();++ expect(sent, [(true, size)]);+ final command = server.posts.single['command'] as Map;+ expect(command['attachmentIds'], ['attachment-1']);+ await close(tester, controller);+ });++ testWidgets('a picked file over 256 MB is refused without being read', (+ tester,+ ) async {+ final original = FileSelectorPlatform.instance;+ FileSelectorPlatform.instance = _Picker([+ _Sized(kSuperTabAttachmentMaxBytes + 1, fileName: 'huge.step'),+ ]);+ 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), isEmpty);+ expect(find.text('huge.step is over 256 MB.'), findsOneWidget);+ await close(tester, controller);+ });++ test('a file over 256 MB, or an eleventh file, is refused', () {final controller = ConversationServer().controller();addTearDown(controller.dispose);final files = controller.attachments('lead');+ // Weighed, never read: the file is only its size.expect(files.add([- HarnessAttachment(+ HarnessAttachment.onDisk('big.bin',- Uint8List(kSuperTabAttachmentMaxBytes + 1),+ _Sized(256 * 1024 * 1024 + 1),+ 256 * 1024 * 1024 + 1,),]),- 'big.bin is over 10 MB.',+ 'big.bin is over 256 MB.',);expect(files.isEmpty, isTrue);+ // 256 MB itself fits.+ expect(+ files.add([+ HarnessAttachment.onDisk(+ 'cad.step',+ _Sized(256 * 1024 * 1024),+ 256 * 1024 * 1024,+ ),+ ]),+ isNull,+ );+ files.clear();String? problem;for (var i = 0; i <= kSuperTabAttachmentMaxFiles; i++) {@@ -378,7 +494,7 @@ void main() {required conversationId,required name,required mime,- required bytes,+ required file,required cancel,required onProgress,}) async {@@ -389,7 +505,7 @@ void main() {conversationId: conversationId,name: name,mime: mime,- bytes: bytes,+ file: file,cancel: cancel,onProgress: onProgress,);@@ -433,7 +549,7 @@ void main() {required conversationId,required name,required mime,- required bytes,+ required file,required cancel,required onProgress,}) {@@ -479,7 +595,7 @@ void main() {required conversationId,required name,required mime,- required bytes,+ required file,required cancel,required onProgress,}) {diff --git a/desktop/test/super_tab_composer_error_test.dart b/desktop/test/super_tab_composer_error_test.dartindex d8055f00a..539c9d153 100644--- a/desktop/test/super_tab_composer_error_test.dart+++ b/desktop/test/super_tab_composer_error_test.dart@@ -3,7 +3,7 @@import 'dart:async';import 'dart:typed_data';-import 'package:dio/dio.dart' show RequestOptions, Response;+import 'package:dio/dio.dart' show CancelToken, RequestOptions, Response;import 'package:flutter_test/flutter_test.dart';import 'package:harness/state/harness_attachments.dart';import 'package:harness/super_tabs/attachment_upload.dart';@@ -113,43 +113,49 @@ void main() {expect(c.composerError('lead'), 'Choose an agent in this conversation.');});- test('a send forbidden in one conversation is not said in another',- () async {- server- ..refuse = {'code': 'FORBIDDEN', 'message': 'You can’t write here.'}- ..refuseStatus = 403;- c.setDraft('lead', 'Hello');- expect(await c.send(), isNull);- expect(c.composerError('lead'), 'You can’t write here.');-- server.refuse = null;- await c.select('offline');- expect(c.composerError('offline'), isNull);- });-- test('a mention that is gone says so only in its own conversation',- () async {- c.setDraft('lead', 'Hello');- await c.send(recipients: ['no-longer-present']);- expect(c.composerError('lead'), contains('mentioned agent'));+ test(+ 'a send forbidden in one conversation is not said in another',+ () async {+ server+ ..refuse = {'code': 'FORBIDDEN', 'message': 'You can’t write here.'}+ ..refuseStatus = 403;+ c.setDraft('lead', 'Hello');+ expect(await c.send(), isNull);+ expect(c.composerError('lead'), 'You can’t write here.');++ server.refuse = null;+ await c.select('offline');+ expect(c.composerError('offline'), isNull);+ },+ );- await c.select('offline');- expect(c.composerError('offline'), isNull);- });+ test(+ 'a mention that is gone says so only in its own conversation',+ () async {+ c.setDraft('lead', 'Hello');+ await c.send(recipients: ['no-longer-present']);+ expect(c.composerError('lead'), contains('mentioned agent'));- test('a send still unconfirmed blocks every composer, so each says why',- () async {- server.loseReply = true;- c.setDraft('lead', 'Hello');- expect(await c.send(), isNull);- expect(c.hasPendingAction, isTrue);+ await c.select('offline');+ expect(c.composerError('offline'), isNull);+ },+ );- await c.select('offline');- expect(- c.composerError('offline'),- 'The action is not confirmed. Retry to check it.',- );- });+ test(+ 'a send still unconfirmed blocks every composer, so each says why',+ () async {+ server.loseReply = true;+ c.setDraft('lead', 'Hello');+ expect(await c.send(), isNull);+ expect(c.hasPendingAction, isTrue);++ await c.select('offline');+ expect(+ c.composerError('offline'),+ 'The action is not confirmed. Retry to check it.',+ );+ },+ );test('a refusal outside any conversation still shows where the person ''is', () async {@@ -171,7 +177,7 @@ void main() {required conversationId,required name,required mime,- required bytes,+ required file,required cancel,required onProgress,}) => gate.future,@@ -192,6 +198,71 @@ void main() {await c.select('lead');expect(c.composerError('lead'), 'No files here.');});++ test('losing access while a file goes up stops it, and what it brings '+ 'later is dropped', () async {+ final gate = Completer<Map<String, dynamic>>();+ CancelToken? token;+ c.dispose();+ c = server.controller(+ upload:+ ({+ required tabId,+ required conversationId,+ required name,+ required mime,+ required file,+ required cancel,+ required onProgress,+ }) {+ token = cancel;+ return gate.future;+ },+ );+ await c.refresh();+ c.attachments('lead').add([HarnessAttachment('a.png', _png)]);+ final sending = c.send();+ await Future<void>.delayed(Duration.zero);+ expect(c.uploading, isTrue);++ c.revokeAccess('You were signed out.');++ expect(token!.isCancelled, isTrue);+ expect(c.uploading, isFalse);+ gate.complete({+ 'attachment': {'id': 'late'},+ });+ expect(await sending, isNull);+ expect(server.posts, isEmpty);+ });++ test('closing the Swarm while a file goes up stops it', () async {+ CancelToken? token;+ final closing = server.controller(+ upload:+ ({+ required tabId,+ required conversationId,+ required name,+ required mime,+ required file,+ required cancel,+ required onProgress,+ }) {+ token = cancel;+ return Completer<Map<String, dynamic>>().future;+ },+ );+ await closing.refresh();+ closing.attachments('lead').add([HarnessAttachment('a.png', _png)]);+ unawaited(closing.send());+ await Future<void>.delayed(Duration.zero);+ expect(closing.uploading, isTrue);++ closing.dispose();++ expect(token!.isCancelled, isTrue);+ });});group('superTabUploadRefusal', () {@@ -236,7 +307,7 @@ void main() {expect(superTabUploadRefusal(answer(413, {'error': 'ATTACHMENT_TOO_LARGE'})).message,- 'That file is over 10 MB.',+ 'Files can be up to 256 MB.',);});});diff --git a/desktop/test/super_tab_folder_drop_test.dart b/desktop/test/super_tab_folder_drop_test.dartindex d9d4d16a5..c94dbf7c8 100644--- a/desktop/test/super_tab_folder_drop_test.dart+++ b/desktop/test/super_tab_folder_drop_test.dart@@ -317,7 +317,7 @@ void main() {expect(controller.draft('lead'), 'Look at ');expect(hint, findsNothing);final zip = ZipDecoder().decodeBytes(- controller.attachments('lead').files.single.bytes,+ controller.attachments('lead').files.single.bytes!,);final entries = {for (final entry in zip.files)@@ -335,7 +335,7 @@ void main() {final controller = await open(tester, machineId: 'studio');final big = folder('big');File('${big.path}/blob.bin')- .writeAsBytesSync(List.filled(kSuperTabAttachmentMaxBytes + 1, 0));+ .writeAsBytesSync(List.filled(kSuperTabFolderZipMaxBytes + 1, 0));await drop(tester, [big.path,], until: () => field(tester).text.contains(big.path));@@ -452,7 +452,7 @@ void main() {// compress, and the archive adds its headers.final random = Random(1);File('${src.path}/noise.bin').writeAsBytesSync([- for (var i = 0; i < kSuperTabAttachmentMaxBytes - 16; i++)+ for (var i = 0; i < kSuperTabFolderZipMaxBytes - 16; i++)random.nextInt(256),]);await drop(tester, [diff --git a/desktop/test/super_tab_message_media_test.dart b/desktop/test/super_tab_message_media_test.dartindex f13e78403..544b97d57 100644--- a/desktop/test/super_tab_message_media_test.dart+++ b/desktop/test/super_tab_message_media_test.dart@@ -1,12 +1,14 @@// What a chat message shows besides its words, as Slack does: pictures in// the row, up to 360 px with their shape kept, that open full screen; code// in a block with Copy; every other file one compact chip (Dee, 10-29).+import 'dart:async';import 'dart:ui' as ui;import 'package:flutter/material.dart';import 'package:flutter/services.dart';import 'package:flutter_test/flutter_test.dart';import 'package:harness/shared/theme/app_theme.dart' as grid;+import 'package:harness/super_tabs/attachment_upload.dart';import 'package:harness/super_tabs/attachment_viewer.dart';import 'package:harness/super_tabs/controller.dart';import 'package:harness/super_tabs/view.dart';@@ -31,11 +33,12 @@ Map<String, dynamic> _file(String name,String mime, {String? url,+ int size = 120 * 1024,}) => {'id': id,'name': name,'mime': mime,- 'size': 120 * 1024,+ 'size': size,'url': url ?? 'https://cdn.harness.autonomous.ai/$id/$name',};@@ -123,6 +126,78 @@ void main() {});}+ testWidgets('a picture over 10 MB is a chip, and nothing is fetched', (+ tester,+ ) async {+ final c = await show(+ tester,+ files: [_file('a1', 'huge.png', 'image/png', size: 11 * 1024 * 1024)],+ );++ expect(find.byKey(const ValueKey('super-attachment:a1')), findsOneWidget);+ expect(+ find.byKey(const ValueKey('super-attachment-inline:a1')),+ findsNothing,+ );+ expect(loaded, isEmpty);+ await close(tester, c);+ });++ testWidgets('a picture of 1 MB, or 10 MB itself, still shows in place', (+ tester,+ ) async {+ final png = await _png(tester, 120, 80);+ pictures['one.png'] = png;+ pictures['ten.png'] = png;+ final c = await show(+ tester,+ files: [+ _file('a1', 'one.png', 'image/png', size: 1024 * 1024),+ _file('a2', 'ten.png', 'image/png', size: 10 * 1024 * 1024),+ ],+ );++ for (final id in ['a1', 'a2']) {+ expect(+ find.byKey(ValueKey('super-attachment-inline:$id')),+ findsOneWidget,+ );+ }+ expect(loaded.toSet(), hasLength(2));+ await close(tester, c);+ });++ testWidgets('a picture is read at most 10 MB, whatever its row says', (+ tester,+ ) async {+ int? asked;+ final fetcher = attachmentFetcher;+ attachmentFetcher = (url, {maxBytes}) async {+ asked = maxBytes;+ throw const AttachmentTooLarge();+ };+ addTearDown(() => attachmentFetcher = fetcher);+ final failed = Completer<Object>();+ AttachmentImage(+ Uri.parse('https://cdn.harness.autonomous.ai/a1/lies.png'),+ )+ .resolve(ImageConfiguration.empty)+ .addListener(+ ImageStreamListener(+ (_, _) {},+ onError: (error, _) {+ if (!failed.isCompleted) failed.complete(error);+ },+ ),+ );++ expect(+ await tester.runAsync(() => failed.future),+ isA<AttachmentTooLarge>(),+ );+ expect(asked, kSuperTabFormAttachmentMaxBytes);+ });+testWidgets('a click opens the picture full screen, with Download', (tester,) async {diff --git a/desktop/test/super_tab_thread_composer_test.dart b/desktop/test/super_tab_thread_composer_test.dartindex 489147fff..a51c8c959 100644--- a/desktop/test/super_tab_thread_composer_test.dart+++ b/desktop/test/super_tab_thread_composer_test.dart@@ -31,6 +31,9 @@ class _Picked extends XFile {@overrideFuture<Uint8List> readAsBytes() async => bytes;++ @override+ Future<int> length() async => bytes.length;}/// A file chooser that answers when the test says so.@@ -583,7 +586,7 @@ void main() {required conversationId,required name,required mime,- required bytes,+ required file,required cancel,required onProgress,}) async {@@ -596,7 +599,7 @@ void main() {conversationId: conversationId,name: name,mime: mime,- bytes: bytes,+ file: file,cancel: cancel,onProgress: onProgress,);diff --git a/desktop/test/super_tab_upload_test.dart b/desktop/test/super_tab_upload_test.dartindex 6770eba31..7e3dad0db 100644--- a/desktop/test/super_tab_upload_test.dart+++ b/desktop/test/super_tab_upload_test.dart@@ -1,16 +1,21 @@// 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:async';import 'dart:convert';import 'dart:io';+import 'dart:math' show min;import 'dart:typed_data';import 'package:dio/dio.dart';+import 'package:file_selector/file_selector.dart' show XFile;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/logging/app_log.dart';+import 'package:harness/state/harness_attachments.dart';import 'package:harness/super_tabs/attachment_upload.dart';import 'package:harness/super_tabs/avatar_upload.dart';import 'package:harness/super_tabs/controller.dart';@@ -30,11 +35,14 @@ void main() {})>[];var reply = (200, <String, Object?>{});+ // Answers by path, before `reply`: the steps of a file sent to storage.+ final replies = <String, (int, Map<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();+ replies.clear();answer = null;server = await HttpServer.bind(InternetAddress.loopbackIPv4, 0);server.listen((request) async {@@ -56,7 +64,7 @@ void main() {: request.headers.value('x-adapter-local') == null? (403, <String, Object?>{'error': 'FORBIDDEN'}): null;- final (status, payload) = chosen ?? reply;+ final (status, payload) = chosen ?? replies[request.uri.path] ?? reply;request.response..statusCode = status..headers.contentType = ContentType.json@@ -81,7 +89,10 @@ void main() {conversationId: 'lead',name: 'shot.png',mime: 'image/png',- bytes: Uint8List.fromList(List.filled(2000, 7)),+ file: HarnessAttachment(+ 'shot.png',+ Uint8List.fromList(List.filled(2000, 7)),+ ),cancel: CancelToken(),onProgress: onProgress ?? (_) {},);@@ -131,7 +142,7 @@ void main() {'success': false,'error': {'code': 'ATTACHMENT_TOO_LARGE',- 'message': 'Files can be at most 10 MB.',+ 'message': 'Files can be up to 256 MB.',},},);@@ -141,7 +152,7 @@ void main() {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.message, 'message', 'Files can be up to 256 MB.').having((f) => f.statusCode, 'status', 413),),);@@ -180,6 +191,389 @@ void main() {expect(seen.single.local, '1');});+ group('a file over 10 MB goes straight to storage', () {+ const size = 10 * 1024 * 1024 + 1;+ const secret = 'X-Goog-Signature=s3cr3t';+ late HttpServer storage;+ late String link;+ final puts =+ <+ ({String method, String path, Map<String, String> headers, int sent})+ >[];+ var storageStatus = 200;+ // Told once storage has the request's headers, before its body is in.+ Completer<void>? putStarted;+ final signed = {+ 'content-type': 'application/octet-stream',+ 'content-disposition': 'attachment; filename="AC4 - 26 Oct v2.step"',+ 'cache-control': 'private, max-age=0',+ 'x-goog-content-length-range': '$size,$size',+ 'x-goog-if-generation-match': '0',+ };+ final logged = <String>[];+ late AppLog log;++ setUp(() async {+ puts.clear();+ logged.clear();+ storageStatus = 200;+ putStarted = null;+ log = appLog;+ appLog = _Recorder(logged);+ storage = await HttpServer.bind(InternetAddress.loopbackIPv4, 0);+ storage.listen((request) async {+ putStarted?.complete();+ var sent = 0;+ try {+ await for (final chunk in request) {+ sent += chunk.length;+ }+ } catch (_) {+ // The sender gave up mid-body.+ }+ final headers = <String, String>{};+ request.headers.forEach(+ (name, values) => headers[name] = values.join(','),+ );+ puts.add((+ method: request.method,+ path: request.uri.toString(),+ headers: headers,+ sent: sent,+ ));+ try {+ request.response+ ..statusCode = storageStatus+ // Storage's refusal can quote the link it was sent on.+ ..write(storageStatus == 200 ? '' : '<Error>$link</Error>');+ await request.response.close();+ } catch (_) {}+ });+ link = 'http://127.0.0.1:${storage.port}/bucket/key?$secret';+ replies['/api/super-tabs/tab%201/attachments/uploads'] = (+ 200,+ {+ 'success': true,+ 'data': {+ 'upload': {+ 'id': 'u1',+ 'url': link,+ 'method': 'PUT',+ 'headers': signed,+ 'expiresAt': 1793436000000,+ },+ },+ },+ );+ replies['/api/super-tabs/tab%201/attachments/uploads/u1/complete'] = (+ 200,+ {+ 'success': true,+ 'data': {+ 'attachment': {+ 'id': 'u1',+ 'name': 'AC4 - 26 Oct v2.step',+ 'mime': 'application/octet-stream',+ 'size': size,+ 'url': 'https://cdn.harness.autonomous.ai/k/AC4.step',+ },+ },+ },+ );+ });+ tearDown(() async {+ appLog = log;+ await storage.close(force: true);+ });++ Future<Map<String, dynamic>> sendLarge({+ int length = size,+ CancelToken? cancel,+ Completer<void>? hold,+ void Function(double)? onProgress,+ }) => upload(+ tabId: 'tab 1',+ conversationId: 'lead',+ name: 'AC4 - 26 Oct v2.step',+ mime: 'application/octet-stream',+ file: HarnessAttachment.onDisk(+ 'AC4 - 26 Oct v2.step',+ _Sized(length, hold: hold),+ length,+ ),+ cancel: cancel ?? CancelToken(),+ onProgress: onProgress ?? (_) {},+ );++ test('asks for a link, sends the file on it with exactly its headers '+ 'and no token, then finishes', () async {+ final progress = <double>[];++ final answer = await sendLarge(onProgress: progress.add);++ expect((answer['attachment'] as Map)['id'], 'u1');+ expect(seen.map((r) => r.path), [+ '/api/super-tabs/tab%201/attachments/uploads',+ '/api/super-tabs/tab%201/attachments/uploads/u1/complete',+ ]);+ // Through the daemon, as JSON, each with its header.+ expect(seen.map((r) => r.type), ['application/json', 'application/json']);+ expect(seen.map((r) => r.local), ['1', '1']);+ expect(jsonDecode(seen.first.body), {+ 'conversationId': 'lead',+ 'name': 'AC4 - 26 Oct v2.step',+ 'mime': 'application/octet-stream',+ 'size': size,+ });+ expect(jsonDecode(seen.last.body), <String, Object?>{});++ final put = puts.single;+ expect(put.method, 'PUT');+ expect(put.path, '/bucket/key?$secret');+ expect(put.sent, size);+ expect(put.headers['content-length'], '$size');+ for (final MapEntry(:key, :value) in signed.entries) {+ expect(put.headers[key], value, reason: key);+ }+ expect(put.headers, isNot(contains('authorization')));+ expect(put.headers, isNot(contains('x-adapter-local')));+ expect(progress, isNotEmpty);+ expect(progress.last, 1);+ });++ test('storage refusing it fails plainly, never quoting the link, and '+ 'nothing is finished', () async {+ storageStatus = 403;++ await expectLater(+ sendLarge(),+ throwsA(+ isA<SuperTabFailure>()+ .having((f) => f.code, 'code', 'UPLOAD_FAILED')+ .having(+ (f) => f.message,+ 'message',+ 'Could not upload AC4 - 26 Oct v2.step. Try again.',+ ),+ ),+ );+ expect(seen.map((r) => r.path), [+ '/api/super-tabs/tab%201/attachments/uploads',+ ]);+ expect(logged, contains(contains('status 403')));+ expect(logged.where((line) => line.contains('s3cr3t')), isEmpty);+ expect(logged.where((line) => line.contains('bucket')), isEmpty);+ });++ test(+ 'a link that cannot be reached fails plainly, never quoting it',+ () async {+ link = 'http://127.0.0.1:1/bucket/key?$secret';+ final (status, body) =+ replies['/api/super-tabs/tab%201/attachments/uploads']!;+ ((body['data'] as Map)['upload'] as Map)['url'] = link;+ replies['/api/super-tabs/tab%201/attachments/uploads'] = (status, body);++ Object? failure;+ try {+ await sendLarge();+ } catch (error) {+ failure = error;+ }++ expect(failure, isA<SuperTabFailure>());+ expect((failure as SuperTabFailure).code, 'UPLOAD_FAILED');+ expect('$failure', isNot(contains('s3cr3t')));+ expect(logged.where((line) => line.contains('s3cr3t')), isEmpty);+ },+ );++ test(+ 'given up mid-file, the transfer stops and nothing is finished',+ () async {+ final cancel = CancelToken();+ final hold = Completer<void>();+ putStarted = Completer<void>();++ final sending = sendLarge(cancel: cancel, hold: hold);+ await putStarted!.future;+ cancel.cancel('given up');++ await expectLater(+ sending,+ throwsA(+ isA<DioException>().having(+ (f) => f.type,+ 'type',+ DioExceptionType.cancel,+ ),+ ),+ );+ // The cancel error names the link request, not storage.+ expect(+ cancel.cancelError!.requestOptions.uri.toString(),+ isNot(contains('s3cr3t')),+ );+ hold.complete();+ // Storage saw the transfer end short.+ await Future<void>.delayed(const Duration(milliseconds: 100));+ expect(puts.single.sent, lessThan(size));+ expect(seen.map((r) => r.path), [+ '/api/super-tabs/tab%201/attachments/uploads',+ ]);+ },+ );++ test('a link that is not https is refused before a byte is sent, never '+ 'quoting it', () async {+ // Plain http to a host that is not this computer by name: reachable+ // here, so a client that sent to it would be seen doing so.+ final plain = await HttpServer.bind(InternetAddress.loopbackIPv6, 0);+ addTearDown(() => plain.close(force: true));+ final reached = <String>[];+ plain.listen((request) async {+ reached.add(request.method);+ await request.drain<void>();+ await request.response.close();+ });+ link = 'http://[::1]:${plain.port}/bucket/key?$secret';+ final (status, body) =+ replies['/api/super-tabs/tab%201/attachments/uploads']!;+ ((body['data'] as Map)['upload'] as Map)['url'] = link;+ replies['/api/super-tabs/tab%201/attachments/uploads'] = (status, body);++ await expectLater(+ sendLarge(),+ throwsA(+ isA<SuperTabFailure>()+ .having((f) => f.code, 'code', 'UPLOAD_FAILED')+ .having(+ (f) => f.message,+ 'message',+ 'Could not upload AC4 - 26 Oct v2.step. Try again.',+ ),+ ),+ );+ expect(reached, isEmpty);+ expect(seen.map((r) => r.path), [+ '/api/super-tabs/tab%201/attachments/uploads',+ ]);+ expect(logged.where((line) => line.contains('s3cr3t')), isEmpty);+ });++ test('storage links: https, or plain http to this computer from a '+ 'computer only', () {+ expect(+ superTabStorageLinkAllowed('https://storage.googleapis.com/b/k?s=1'),+ isTrue,+ );+ expect(superTabStorageLinkAllowed('http://127.0.0.1:9000/b/k'), isTrue);+ expect(superTabStorageLinkAllowed('http://localhost:9000/b/k'), isTrue);+ expect(+ superTabStorageLinkAllowed('http://127.0.0.1:9000/b/k', web: true),+ isFalse,+ );+ for (final refused in [+ 'http://storage.googleapis.com/b/k',+ 'http://[::1]:9000/b/k',+ 'ftp://storage.googleapis.com/b/k',+ 'https://user:[email protected]/b/k',+ 'https:///b/k',+ 'not a link',+ ]) {+ expect(superTabStorageLinkAllowed(refused), isFalse, reason: refused);+ }+ });++ test('over 256 MB it is refused before any request', () async {+ await expectLater(+ sendLarge(length: 256 * 1024 * 1024 + 1),+ throwsA(+ isA<SuperTabFailure>()+ .having((f) => f.code, 'code', 'ATTACHMENT_TOO_LARGE')+ .having(+ (f) => f.message,+ 'message',+ 'Files can be up to 256 MB.',+ ),+ ),+ );+ expect(seen, isEmpty);+ expect(puts, isEmpty);+ });++ test('a daemon without the route says to update Harness', () async {+ replies['/api/super-tabs/tab%201/attachments/uploads'] = (+ 404,+ {'error': 'not found'},+ );++ await expectLater(+ sendLarge(),+ throwsA(+ isA<SuperTabFailure>()+ .having((f) => f.code, 'code', 'UPDATE_HARNESS')+ .having(+ (f) => f.message,+ 'message',+ 'Update Harness on this computer to send files over 10 MB.',+ ),+ ),+ );+ expect(puts, isEmpty);+ });++ test('a link the backend refuses carries its words, and nothing goes to '+ 'storage', () async {+ replies['/api/super-tabs/tab%201/attachments/uploads'] = (+ 413,+ {+ 'success': false,+ 'error': {+ 'code': 'ATTACHMENT_TOO_LARGE',+ 'message': 'Files can be up to 256 MB.',+ },+ },+ );++ await expectLater(+ sendLarge(),+ throwsA(+ isA<SuperTabFailure>()+ .having((f) => f.code, 'code', 'ATTACHMENT_TOO_LARGE')+ .having((f) => f.statusCode, 'status', 413),+ ),+ );+ expect(puts, isEmpty);+ });++ test('10 MB itself still goes as one form', () async {+ reply = (+ 200,+ {+ 'success': true,+ 'data': {+ 'attachment': {'id': 'a1'},+ },+ },+ );+ final answer = await upload(+ tabId: 'tab 1',+ conversationId: 'lead',+ name: 'edge.bin',+ mime: 'application/octet-stream',+ file: HarnessAttachment('edge.bin', Uint8List(10 * 1024 * 1024)),+ cancel: CancelToken(),+ onProgress: (_) {},+ );++ expect((answer['attachment'] as Map)['id'], 'a1');+ expect(seen.single.path, '/api/super-tabs/tab%201/attachments');+ expect(seen.single.type, 'multipart/form-data');+ expect(puts, isEmpty);+ });+ });+group('a profile picture', () {late SuperTabAvatarUpload avatar;@@ -286,6 +680,61 @@ void main() {);});+ test('a file over 10 MB: the token goes to the backend, never to '+ 'storage', () async {+ final storage = await HttpServer.bind(InternetAddress.loopbackIPv4, 0);+ addTearDown(() => storage.close(force: true));+ final storageHeaders = <String, String>{};+ storage.listen((request) async {+ request.headers.forEach(+ (name, values) => storageHeaders[name] = values.join(','),+ );+ await request.drain<void>();+ await request.response.close();+ });+ const size = 10 * 1024 * 1024 + 1;+ replies['/api/super-tabs/tab%201/attachments/uploads'] = (+ 200,+ {+ 'success': true,+ 'data': {+ 'upload': {+ 'id': 'u1',+ 'url': 'http://127.0.0.1:${storage.port}/bucket/key?sig=1',+ 'method': 'PUT',+ 'headers': {'content-type': 'application/octet-stream'},+ 'expiresAt': 1793436000000,+ },+ },+ },+ );+ replies['/api/super-tabs/tab%201/attachments/uploads/u1/complete'] = (+ 200,+ {+ 'success': true,+ 'data': {+ 'attachment': {'id': 'u1'},+ },+ },+ );++ final answer = await upload(+ tabId: 'tab 1',+ conversationId: 'lead',+ name: 'big.step',+ mime: 'application/octet-stream',+ file: HarnessAttachment.onDisk('big.step', _Sized(size), size),+ cancel: CancelToken(),+ onProgress: (_) {},+ );++ expect((answer['attachment'] as Map)['id'], 'u1');+ expect(seen.map((r) => r.bearer), ['Bearer old', 'Bearer old']);+ expect(seen.map((r) => r.local), [null, null]);+ expect(storageHeaders['content-length'], '$size');+ expect(storageHeaders, isNot(contains('authorization')));+ });+test('sends the bearer and not the daemon\'s header', () async {reply = (200,@@ -344,3 +793,43 @@ class _Tokens implements AccessTokenSource {return _renewed ? 'new' : 'old';}}++/// A file of [size] zero bytes on disk, never read whole: reading it so fails+/// the test. With [hold], it stops after its first part until that completes.+class _Sized extends XFile {+ _Sized(this.size, {this.hold}) : super('/picked/large.step');++ final int size;+ final Completer<void>? hold;++ @override+ Future<int> length() async => size;++ @override+ Future<Uint8List> readAsBytes() => throw StateError('read whole');++ @override+ Stream<Uint8List> openRead([int? start, int? end]) async* {+ const chunk = 256 * 1024;+ final last = end ?? size;+ for (var at = start ?? 0; at < last; at += chunk) {+ yield Uint8List(min(chunk, last - at));+ if (hold case final hold?) await hold.future;+ }+ }+}++/// The app log's lines, as they would be written.+class _Recorder implements AppLog {+ _Recorder(this.lines);+ final List<String> lines;++ @override+ void record(+ AppLogLevel level,+ String category,+ String message, {+ Object? error,+ StackTrace? stackTrace,+ }) => lines.add('$level $category $message ${error ?? ''}');+}diff --git a/desktop/test/support/super_tab_fixture.dart b/desktop/test/support/super_tab_fixture.dartindex 1cbea88ac..23b795db6 100644--- a/desktop/test/support/super_tab_fixture.dart+++ b/desktop/test/support/super_tab_fixture.dart@@ -5,6 +5,7 @@ import 'dart:typed_data';import 'package:cryptography/dart.dart' show DartSha256;import 'package:dio/dio.dart' show CancelToken;+import 'package:harness/state/harness_attachments.dart';import 'package:harness/super_tabs/attachment_upload.dart';import 'package:harness/super_tabs/buddies.dart' show kBuddyEngineRefusals;import 'package:harness/super_tabs/controller.dart';@@ -877,7 +878,7 @@ class ConversationServer {required String conversationId,required String name,required String mime,- required Uint8List bytes,+ required HarnessAttachment file,required CancelToken cancel,required void Function(double sent) onProgress,}) async {@@ -894,7 +895,7 @@ class ConversationServer {'conversationId': conversationId,'name': name,'mime': mime,- 'file': bytes,+ 'file': await file.readBytes(),'id': id,});onProgress(1);diff --git a/desktop/test/swarm_web_relay_team_test.dart b/desktop/test/swarm_web_relay_team_test.dartindex 302bcb66b..ed6d67d9b 100644--- a/desktop/test/swarm_web_relay_team_test.dart+++ b/desktop/test/swarm_web_relay_team_test.dart@@ -7,6 +7,7 @@ import 'package:harness/auth/auth_session.dart';import 'package:harness/core/config.dart';import 'package:harness/core/models.dart';import 'package:harness/state/app_state.dart';+import 'package:harness/state/harness_attachments.dart';import 'package:harness/state/pane_layout_store.dart';import 'package:harness/super_tabs/controller.dart' show SuperTabFailure;import 'package:harness/viewer/viewer_key_store.dart';@@ -249,7 +250,7 @@ void main() {conversationId: 'buddy-chat',name: 'shot.png',mime: 'image/png',- bytes: Uint8List.fromList([1, 2, 3]),+ file: HarnessAttachment('shot.png', Uint8List.fromList([1, 2, 3])),cancel: CancelToken(),onProgress: (_) {},);diff --git a/docs/swarms.md b/docs/swarms.mdindex 6a23b299d..8fd397273 100644--- a/docs/swarms.md+++ b/docs/swarms.md@@ -363,7 +363,8 @@ Buddies are on in every Swarm; there is no setting. They replaced Chat with PM (or one from the last hour, and only once for each such message. The server writes the "on behalf of" label, so a Buddy cannot leave it out or change it.- A proposal's files are only ones its owner handed it: a file inside the Buddy's own copy of the project (checked byits real path on its own machine, so never through a link out of it, and never the repository's or Harness's own- records), or a file its owner sent in their Buddy chat. Each file has a chat file's limits (10 MB). The server accepts+ records), or a file its owner sent in their Buddy chat. A file from its own copy is at most 10 MB, since its guard reads+ it whole to check it for secrets; a file its owner sent has a chat file's limit (256 MB). The server acceptsa Buddy's file only in its own chat and only on a proposal, so it cannot post a file in the project chat any other way.The files show on the proposal message like any message's files, for the product manager and every member.- Nobody else reads a Buddy chat: not the product manager, and not the project's or the Swarm's owner. Private matters@@ -641,6 +642,34 @@ Design:- Platforms: the counts come from Claude Code and Codex transcripts on macOS,Linux and Windows hosts alike.+## Chat files++A message carries up to 10 files, each up to 256 MB. A bigger file is refused+before it is sent, with "Files can be up to 256 MB."++- A file up to 10 MB goes to the server in one request, as since the first+ version. Production sits behind Cloudflare, which refuses request bodies over+ 100 MB on plans below Business, so bigger files do not pass through the server.+- A file over 10 MB goes straight to the attachments bucket. The server first+ checks that the sender may post in that conversation and is under 200 uploads+ and 4 GB an hour (counted together with the new upload, so requests at once+ cannot pass it), records the upload, then signs a link that writes one new object of exactly that size,+ served as a download. The upload must start within 10 minutes. A second write+ to the same link, another size, or a changed header is refused by storage+ itself. The sender then asks the server to finish the upload. Only the same+ person or agent, still able to post there, can finish it, and only once+ storage holds exactly that size. Until then no message can carry the file. An+ image keeps its type only when its first bytes are one.+- An upload that is never finished is removed, with anything it stored, an+ hour after its link expired. One finished but never sent is an unsent file,+ like any other.+- Desktop in a browser sends straight to the bucket only once the bucket allows+ it: a CORS rule for `https://harness.autonomous.ai` alone, method `PUT` alone,+ and the five headers the link signs (`Content-Type`, `Content-Disposition`,+ `Cache-Control`, `x-goog-content-length-range`, `x-goog-if-generation-match`).+- Agents' computers save each message's files straight to disk, never more than+ the size the message names.+## Avatars, status and celebrationsPeople and agents each show one avatar wherever they appear: messages, thediff --git a/mobile/lib/api/api_client.dart b/mobile/lib/api/api_client.dartindex 45832d018..396072ec1 100644--- a/mobile/lib/api/api_client.dart+++ b/mobile/lib/api/api_client.dart@@ -1,3 +1,4 @@+import 'dart:async';import 'dart:typed_data';import 'package:dio/dio.dart';@@ -5,7 +6,9 @@ import 'package:dio/dio.dart';import '../auth/auth_session.dart';import '../core/config.dart';import '../core/models.dart';+import '../logging/app_log.dart';import '../logging/http_log.dart';+import '../swarm/swarm_outgoing_files.dart';import '../swarm/swarm_request.dart' show SuperTabFailure;import '../viewer/device_ack.dart';import '../viewer/device_log.dart';@@ -342,64 +345,177 @@ class ApiClient {// -- Swarm chat files (backend only: the viewer's own SSO session signs it) --/// Sends one file for a message in [conversationId] of Swarm [tabId] and- /// answers the backend's `{attachment: {...}}` — `POST- /// /api/super-tabs/:tabId/attachments`, the form Desktop sends.+ /// answers the backend's `{attachment: {...}}`.+ ///+ /// A file of up to [swarmFormAttachmentMaxBytes] goes as the form Desktop+ /// sends, `POST /api/super-tabs/:tabId/attachments`. A larger one, up to+ /// [swarmAttachmentMaxBytes], goes in three steps, since a proxy in front of+ /// the backend may refuse a body that large: the backend is asked for a link+ /// (`POST …/attachments/uploads`), the file goes straight to storage by it,+ /// read from disk as it goes ([_putToStorage]), and the backend is told it is+ /// there (`POST …/attachments/uploads/:id/complete`), which answers the same+ /// attachment. A larger file still is refused before anything is sent.////// Straight to the backend with the token this viewer holds, unlike every/// other Swarm call, which one of the account's machines forwards/// (`AppNotifier.swarmRequest`): the backend takes a chat file only from the/// client itself, and a machine forwards only JSON. [onProgress] is told the/// part sent, from 0 to 1. A refusal throws a [SuperTabFailure] carrying the- /// backend's code, worded as Desktop's `superTabUploadRefusal`.+ /// backend's code, worded as Desktop's `superTabUploadRefusal`. [cancel]+ /// stops whichever step is under way and takes no other; so does+ /// [stillWanted] failing between steps.Future<Map<String, dynamic>> uploadSwarmAttachment({required String tabId,required String conversationId,required String name,required String mime,- required Uint8List bytes,+ required SwarmOutgoingFile file,required CancelToken cancel,required void Function(double sent) onProgress,+ bool Function()? stillWanted,}) async {- final body = multipartFileBody(- fields: {'conversationId': conversationId},- field: 'file',- filename: name,- fileContentType: mime,- file: bytes,- boundary: 'harness-${DateTime.now().microsecondsSinceEpoch}',+ if (file.size > swarmAttachmentMaxBytes) {+ throw const SuperTabFailure(+ 'ATTACHMENT_TOO_LARGE',+ _swarmAttachmentTooLarge,+ statusCode: 413,+ );+ }+ final tab = Uri.encodeComponent(tabId);+ if (file.size <= swarmFormAttachmentMaxBytes) {+ final body = multipartFileBody(+ fields: {'conversationId': conversationId},+ field: 'file',+ filename: name,+ fileContentType: mime,+ file: await file.readAll(),+ boundary: 'harness-${DateTime.now().microsecondsSinceEpoch}',+ );+ final res = await _dio.post(+ '/api/super-tabs/$tab/attachments',+ data: body.bytes,+ cancelToken: cancel,+ onSendProgress: (sent, total) {+ if (total > 0) onProgress(sent / total);+ },+ options: Options(+ contentType: body.contentType,+ // Ten megabytes on a phone connection; the chat's own watchdog gives+ // up on an upload that stops moving.+ sendTimeout: const Duration(minutes: 5),+ receiveTimeout: const Duration(minutes: 1),+ ),+ );+ return _swarmFileAnswer(res);+ }++ void stillGoing() {+ if (cancel.cancelError case final cancelled?) throw cancelled;+ if (stillWanted != null && !stillWanted()) {+ throw DioException.requestCancelled(+ requestOptions: RequestOptions(),+ reason: 'no longer wanted',+ );+ }+ }++ final asked = await _dio.post(+ '/api/super-tabs/$tab/attachments/uploads',+ data: {+ 'conversationId': conversationId,+ 'name': name,+ 'mime': mime,+ 'size': file.size,+ },+ cancelToken: cancel,+ options: Options(receiveTimeout: const Duration(minutes: 1)),);- final res = await _dio.post(- '/api/super-tabs/${Uri.encodeComponent(tabId)}/attachments',- data: body.bytes,+ final upload = _swarmUploadLink(_swarmFileAnswer(asked)['upload']);+ stillGoing();+ await _putToStorage(upload, file, name, cancel, onProgress);+ stillGoing();+ final done = await _dio.post(+ '/api/super-tabs/$tab/attachments/uploads/'+ '${Uri.encodeComponent(upload.id)}/complete',+ data: const <String, Object?>{},cancelToken: cancel,- onSendProgress: (sent, total) {- if (total > 0) onProgress(sent / total);- },- options: Options(- contentType: body.contentType,- // Ten megabytes on a phone connection; the chat's own watchdog gives- // up on an upload that stops moving.- sendTimeout: const Duration(minutes: 5),+ options: Options(receiveTimeout: const Duration(minutes: 1)),+ );+ return _swarmFileAnswer(done);+ }++ /// A client for storage links alone: no token, and no log line, since the+ /// link itself is the credential. Tests share the backend's transport.+ late final Dio _storage = () {+ final dio = Dio(+ BaseOptions(+ connectTimeout: const Duration(seconds: 15),+ // No send timeout: in Dio it bounds the whole body, and a few hundred+ // megabytes may take longer; the chat's watchdog gives up on one that+ // stops moving.receiveTimeout: const Duration(minutes: 1),+ validateStatus: (status) => status != null,),);- final data = res.data;- if (res.statusCode == 200 && data is Map && data['success'] == true) {- return Map<String, dynamic>.from(data['data'] as Map);- }- final error = data is Map ? data['error'] : null;- final code = error is Map ? error['code'] as String? : null;- final message = error is Map ? error['message'] as String? : null;- throw 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: res.statusCode ?? 0,+ final adapter = httpClientAdapter;+ if (adapter != null) dio.httpClientAdapter = adapter;+ return dio;+ }();++ /// Sends [file] to storage by [upload]'s link: exactly the headers the+ /// backend signed, its length, and nothing of this viewer's. A refusal, or a+ /// transfer that breaks, says which file did not go up — never the link.+ Future<void> _putToStorage(+ _SwarmUploadLink upload,+ SwarmOutgoingFile file,+ String name,+ CancelToken cancel,+ void Function(double sent) onProgress,+ ) async {+ // A token of its own, so that what the caller's token carries when it is+ // cancelled is the backend's request, never the link.+ final put = CancelToken();+ final cancelled = cancel.whenCancel.then((_) => put.cancel('given up'));+ unawaited(cancelled);+ final failed = SuperTabFailure(+ 'UPLOAD_FAILED',+ 'Could not upload $name. Try again.',);+ final int status;+ try {+ final res = await _storage.request<void>(+ upload.url,+ data: file.openRead(),+ cancelToken: put,+ onSendProgress: (sent, total) {+ if (total > 0) onProgress(sent / total);+ },+ options: Options(+ method: upload.method,+ headers: {+ ...upload.headers,+ Headers.contentLengthHeader: '${file.size}',+ },+ responseType: ResponseType.plain,+ ),+ );+ status = res.statusCode ?? 0;+ } on DioException catch (error) {+ if (error.type == DioExceptionType.cancel) {+ // Dropped on its way back up: the caller only learns it stopped.+ throw DioException.requestCancelled(+ requestOptions: RequestOptions(),+ reason: 'given up',+ );+ }+ appLog.warn('api', 'chat file to storage → failed (${error.type.name})');+ throw failed;+ }+ if (status < 200 || status >= 300) {+ appLog.warn('api', 'chat file to storage → $status');+ throw SuperTabFailure(failed.code, failed.message, statusCode: status);+ }+ appLog.debug('api', 'chat file to storage → $status');}// -- Swarm avatars (backend only: the computer a Swarm call goes through carries text) --@@ -426,6 +542,76 @@ class ApiClient {}}+/// What the backend says of a file past [swarmAttachmentMaxBytes].+const _swarmAttachmentTooLarge = 'Files can be up to $swarmAttachmentMaxLabel.';++/// The backend's answer to a chat file call: its `data`, or a+/// [SuperTabFailure] with its code and words, Desktop's when it gave none.+Map<String, dynamic> _swarmFileAnswer(Response<dynamic> res) {+ final data = res.data;+ if (res.statusCode == 200 && data is Map && data['success'] == true) {+ final answer = data['data'];+ if (answer is Map) return Map<String, dynamic>.from(answer);+ }+ final error = data is Map ? data['error'] : null;+ final code = error is Map ? error['code'] as String? : null;+ final message = error is Map ? error['message'] as String? : null;+ throw SuperTabFailure(+ code ?? 'UPLOAD_FAILED',+ message ??+ switch (code) {+ 'FORBIDDEN' => 'You can’t send files in this conversation.',+ 'ATTACHMENT_TOO_LARGE' => _swarmAttachmentTooLarge,+ 'UPLOAD_INCOMPLETE' =>+ 'The file did not finish uploading. Try again.',+ 'ATTACHMENT_UNAVAILABLE' =>+ 'Attach this file again before sending it.',+ _ => 'Could not upload the file. Try again.',+ },+ statusCode: res.statusCode ?? 0,+ );+}++/// Where the backend says a large chat file goes, and how.+typedef _SwarmUploadLink = ({+ String id,+ String url,+ String method,+ Map<String, String> headers,+});++/// [raw] as a link to send a file to: an id, an https link and its headers, or+/// a failed upload — a file is never sent anywhere less.+_SwarmUploadLink _swarmUploadLink(Object? raw) {+ const failed = SuperTabFailure(+ 'UPLOAD_FAILED',+ 'Could not upload the file. Try again.',+ );+ if (raw is! Map) throw failed;+ final id = raw['id'], url = raw['url'], method = raw['method'] ?? 'PUT';+ final headers = raw['headers'] ?? const <String, Object?>{};+ final uri = url is String ? Uri.tryParse(url) : null;+ if (id is! String ||+ id.isEmpty ||+ uri == null ||+ uri.scheme != 'https' ||+ uri.host.isEmpty ||+ method is! String ||+ headers is! Map ||+ headers.values.any((value) => value is! String)) {+ throw failed;+ }+ return (+ id: id,+ url: url as String,+ method: method.toUpperCase(),+ headers: {+ for (final MapEntry(:key, :value) in headers.entries)+ '$key': value as String,+ },+ );+}+class ApiException implements Exception {final String message;final int? status;diff --git a/mobile/lib/state/app_state.dart b/mobile/lib/state/app_state.dartindex 3cc578e17..1c19ba398 100644--- a/mobile/lib/state/app_state.dart+++ b/mobile/lib/state/app_state.dart@@ -84,7 +84,9 @@ import '../phone/phone_name_store.dart';import '../viewer/device_log.dart';import '../viewer/device_history.dart';import '../viewer/device_log_sync.dart';+import '../swarm/swarm_file_picker.dart' show clearSwarmPickerCopies;import '../swarm/swarm_notices.dart';+import '../swarm/swarm_outgoing_files.dart' show SwarmOutgoingFile;import '../swarm/swarm_request.dart';enum AppStatus { bootstrapping, unauthenticated, authenticated }@@ -561,6 +563,14 @@ class AppNotifier extends ChangeNotifier {!_disposed && revision == _authRevision;int _invalidateAuthWork() {+ // A chat file on its way stops: the next account takes no step of it, and its bytes stop+ // going to the link the last one was given.+ for (final upload in _swarmUploadsGoing) {+ upload.cancel('account changed');+ }+ _swarmUploadsGoing.clear();+ // The copies large chat files were kept in went with the chats that held them.+ unawaited(clearSwarmPickerCopies());_profileInFlight = null;_retryInFlight = null;machinesLoading = false;@@ -1652,6 +1662,8 @@ class AppNotifier extends ChangeNotifier {// ([_warmStartMachines]). Started after the config and the sign-in check, they landed after// the first frame, ~250ms into the dial's wait. Disk only; dropped when nobody is signed in.lastOpenedAgent.prefetch();+ // Copies of large chat files a run that ended first left behind; none is held yet.+ unawaited(clearSwarmPickerCopies());final cache = _machineCache;if (cache != null) {// Read before the first frame by `startHarness` — see [_preDialFromHint].@@ -6421,13 +6433,14 @@ class AppNotifier extends ChangeNotifier {/// Sends one Swarm chat file to the backend ([SwarmUpload]): straight from this phone with its own/// sign-in ([ApiClient.uploadSwarmAttachment]), not through a machine as [swarmRequest] goes — the/// backend takes a chat file only from the client, and a machine forwards only JSON. An answer- /// that lands after the account changed is dropped.+ /// that lands after the account changed is dropped, and a sign-out or another sign-in stops the+ /// upload where it is ([_invalidateAuthWork]).Future<Map<String, dynamic>> swarmUpload({required String tabId,required String conversationId,required String name,required String mime,- required Uint8List bytes,+ required SwarmOutgoingFile file,required CancelToken cancel,required void Function(double sent) onProgress,}) async {@@ -6441,24 +6454,36 @@ class AppNotifier extends ChangeNotifier {}}+ // A token of this sign-in's, which the chat's [cancel] also ends.+ final going = CancelToken();+ _swarmUploadsGoing.add(going);+ unawaited(cancel.whenCancel.then((_) => going.cancel('given up')));try {final answer = await api.uploadSwarmAttachment(tabId: tabId,conversationId: conversationId,name: name,mime: mime,- bytes: bytes,- cancel: cancel,+ file: file,+ cancel: going,onProgress: onProgress,+ // A file large enough to go up in steps stops between them once the+ // account changed: no step is taken for the next one.+ stillWanted: () => _authWorkCurrent(revision),);stillThisAccount();return answer;} catch (_) {stillThisAccount();rethrow;+ } finally {+ _swarmUploadsGoing.remove(going);}}+ /// The chat file uploads of this sign-in on their way ([swarmUpload]).+ final _swarmUploadsGoing = <CancelToken>{};+/// How many machines one Swarm call asks at most, one after another.static const _swarmAsksPerCall = 5;diff --git a/mobile/lib/swarm/swarm_attach.dart b/mobile/lib/swarm/swarm_attach.dartindex 3206f942b..8d4235196 100644--- a/mobile/lib/swarm/swarm_attach.dart+++ b/mobile/lib/swarm/swarm_attach.dart@@ -227,7 +227,11 @@ class _Chip extends StatelessWidget {@overrideWidget build(BuildContext context) {final tty = Tty.of(context);- final picture = swarmMimeForName(file.name).startsWith('image/');+ // A picture past what goes as a form is a file mark: no thumbnail is decoded from a file of+ // hundreds of megabytes, as a message shows it ([SwarmAttachment]).+ final picture =+ swarmMimeForName(file.name).startsWith('image/') &&+ file.size <= swarmFormAttachmentMaxBytes;final mark = Icon(picture ? LucideIcons.image : LucideIcons.file,size: AppIconSize.besideText,@@ -254,17 +258,19 @@ class _Chip extends StatelessWidget {borderRadius: BorderRadius.circular(AppCard.insetRadius),child: SizedBox.square(dimension: _thumbnail,- child: picture- ? Image.memory(- file.bytes,- fit: BoxFit.cover,- // Decoded small: a thumbnail, not the photo — three- // pixels a point, a phone's sharpest.- cacheWidth: (_thumbnail * 3).round(),- gaplessPlayback: true,- errorBuilder: (_, _, _) => Center(child: mark),- )- : Center(child: mark),+ child: switch ((picture, file.bytes)) {+ // Decoded small: a thumbnail, not the photo — three pixels a+ // point, a phone's sharpest. Only from memory: a file read+ // from disk as it goes up is never decoded to show.+ (true, final bytes?) => Image.memory(+ bytes,+ fit: BoxFit.cover,+ cacheWidth: (_thumbnail * 3).round(),+ gaplessPlayback: true,+ errorBuilder: (_, _, _) => Center(child: mark),+ ),+ _ => Center(child: mark),+ },),),const SizedBox(width: AppSpace.s),@@ -281,7 +287,7 @@ class _Chip extends StatelessWidget {),if (going == null)Text(- swarmFileSize(file.bytes.length),+ swarmFileSize(file.size),style: AppType.caption(color: AppPalette.textFaint,fontFeatures: const [FontFeature.tabularFigures()],diff --git a/mobile/lib/swarm/swarm_attachment.dart b/mobile/lib/swarm/swarm_attachment.dartindex fb501f409..e025cb757 100644--- a/mobile/lib/swarm/swarm_attachment.dart+++ b/mobile/lib/swarm/swarm_attachment.dart@@ -13,11 +13,13 @@ import 'package:harness_mobile/shared/widgets/skeleton.dart';import 'model.dart';import 'swarm_attachment_store.dart';+import 'swarm_outgoing_files.dart' show swarmFormAttachmentMaxBytes;import 'swarm_style.dart';/// A message's file: a picture on Harness's file storage shows in place-/// ([_Preview]); every other file, and a picture that cannot be shown, is-/// [chip].+/// ([_Preview]); every other file, a picture that cannot be shown, and one+/// past [swarmFormAttachmentMaxBytes] — which every phone in the chat would+/// otherwise fetch and decode whole — is [chip].class SwarmAttachment extends StatelessWidget {const SwarmAttachment({super.key,@@ -40,7 +42,11 @@ class SwarmAttachment extends StatelessWidget {@overrideWidget build(BuildContext context) {final url = link;- if (!file.isImage || url == null) return chip;+ if (!file.isImage ||+ url == null ||+ file.size > swarmFormAttachmentMaxBytes) {+ return chip;+ }return _Preview(file: file,url: url,diff --git a/mobile/lib/swarm/swarm_conversation.dart b/mobile/lib/swarm/swarm_conversation.dartindex bdda25d48..323aefcba 100644--- a/mobile/lib/swarm/swarm_conversation.dart+++ b/mobile/lib/swarm/swarm_conversation.dart@@ -56,8 +56,9 @@ class SwarmConversation extends ChangeNotifier implements SwarmFilesBox {/// How long an upload may go without a byte moving before the send gives up.final Duration uploadTimeout;- /// The files waiting to go with the next post. They stay in memory, and go- /// when the chat closes: only what the person typed is kept, and only while+ /// The files waiting to go with the next post. They stay in memory — a+ /// large one on disk, in the app's temporary folder — and go when the chat+ /// closes: only what the person typed is kept, and only while/// the chat is open.@overridefinal files = SwarmOutgoingFiles();diff --git a/mobile/lib/swarm/swarm_conversation_page.dart b/mobile/lib/swarm/swarm_conversation_page.dartindex e7e0ac80e..de4d07492 100644--- a/mobile/lib/swarm/swarm_conversation_page.dart+++ b/mobile/lib/swarm/swarm_conversation_page.dart@@ -2650,7 +2650,7 @@ class _Pending extends StatelessWidget {'id': '','name': file.name,'mime': swarmMimeForName(file.name),- 'size': file.bytes.length,+ 'size': file.size,'url': '',}),link: null,diff --git a/mobile/lib/swarm/swarm_file_picker.dart b/mobile/lib/swarm/swarm_file_picker.dartindex 293dd9823..b8768a8bd 100644--- a/mobile/lib/swarm/swarm_file_picker.dart+++ b/mobile/lib/swarm/swarm_file_picker.dart@@ -36,8 +36,9 @@ class SwarmPickFailed extends SwarmPickOutcome {}/// Photos are scaled to at most this many pixels on their long side and sent as JPEG at-/// [_photoQuality]: a phone's own photo can be past the 10 MB a file may be, and a HEIC one is not-/// a picture Desktop shows. A PNG or a GIF keeps its kind.+/// [_photoQuality]: a phone's own photo can run to tens of megabytes, far more than a chat picture+/// needs to carry over a phone connection, and a HEIC one is not a picture Desktop shows. A PNG or a+/// GIF keeps its kind.const double _photoMaxSide = 4096;const int _photoQuality = 85;@@ -80,14 +81,16 @@ Future<List<String>> Function() swarmPickerCopyFolders = () async => [];/// Opens [source] and adds what the person picks to [files], by Desktop's limits: ten files a-/// message, 10 MB each — reading no more files than there is room for, and naming any left out,+/// message, 256 MB each — reading no more files than there is room for, and naming any left out,/// over the size or empty. Photos are named `photo.jpg`, `photo-2.jpg`… since a picker names them by/// no name a person would know; other files keep their own.///-/// Each picker hands over its own copy of the file in the app's private temporary folder; it is-/// read into memory and deleted at once, kept or not, so no photo stays on the phone. A file-/// outside those folders is read and left where it is. Nothing is-/// added once [stillWanted] fails: the chat closed while its picker was up.+/// Each picker hands over its own copy of the file in the app's private temporary folder. One of+/// up to [swarmFormAttachmentMaxBytes] is read into memory and its copy deleted at once, kept or+/// not, so no photo stays on the phone. A larger one is never read whole: it goes up from its copy,+/// which is deleted once the file is let go ([SwarmOutgoingFile.onDisk]). A file outside those+/// folders is read, or read from, and left where it is. Nothing is added once [stillWanted] fails:+/// the chat closed while its picker was up.Future<SwarmPickOutcome> addSwarmPicked(SwarmOutgoingFiles files,SwarmPickSource source, {@@ -146,19 +149,22 @@ Future<SwarmPickOutcome> addSwarmPicked(}final own = file.name.isEmpty ? 'file' : file.name;final name = photos ? swarmFreeName(_photoName(own), taken) : own;+ var kept = false;try {- final bytes = await _read(file);- if (bytes == null) {+ final outgoing = await _take(file, name, copies);+ if (outgoing == null) {oversized.add(name);- } else if (bytes.isEmpty) {+ } else if (outgoing.size == 0) {empty.add(name);} else {- read.add(SwarmOutgoingFile(name, bytes));+ read.add(outgoing);+ kept = outgoing.path != null;}} catch (_) {unreadable ??= name;} finally {- delete(file);+ // A large file goes up from its copy, which goes once the file does.+ if (!kept) delete(file);}}final notes = [@@ -172,9 +178,15 @@ Future<SwarmPickOutcome> addSwarmPicked(bool _always() => true;-/// [file]'s bytes, or null when it is past the limit, which is measured before it is read so a-/// large file is never held whole.-Future<Uint8List?> _read(XFile file) async {+/// [file] to go up as [name], or null when it is past the limit, which is measured before it is+/// read so a large file is never held whole: one past [swarmFormAttachmentMaxBytes] with a path on+/// disk is read from there as it goes up, its copy (in one of the [copies] folders) deleted once+/// it is let go; a smaller one is read into memory.+Future<SwarmOutgoingFile?> _take(+ XFile file,+ String name,+ List<String> copies,+) async {int? size;try {size = await file.length();@@ -182,8 +194,77 @@ Future<Uint8List?> _read(XFile file) async {// No size to read is no reason to refuse yet: the read says whether the file is there.}if (size != null && size > swarmAttachmentMaxBytes) return null;+ if (size != null &&+ size > swarmFormAttachmentMaxBytes &&+ !kIsWeb &&+ file.path.isNotEmpty) {+ final path = _real(file.path);+ if (File(path).existsSync()) {+ final folder = copies+ .where((folder) => p.isWithin(folder, path))+ .firstOrNull;+ return folder == null+ // The person's own file, read where it is and never touched.+ ? SwarmOutgoingFile.onDisk(name, path, size)+ : SwarmOutgoingFile.onDisk(+ name,+ _keep(path, folder),+ size,+ temporary: true,+ );+ }+ }final bytes = await file.readAsBytes();- return bytes.length > swarmAttachmentMaxBytes ? null : bytes;+ return bytes.length > swarmAttachmentMaxBytes+ ? null+ : SwarmOutgoingFile(name, bytes);+}++/// The folder, in each of the app's temporary folders, a picker's copy of a large file is moved into+/// while it waits to go up: this app's alone, so that clearing it ([clearSwarmPickerCopies]) touches+/// nothing else there.+const _keptFolder = 'harness-swarm-outgoing';++/// Copies [_keep] could not move, kept where the picker put them.+final _keptInPlace = <String>{};+var _keptCount = 0;++/// Moves the picker's copy at [path], in the app's temporary [folder], into [_keptFolder] there+/// and answers where it now is; where it was when it cannot be moved.+String _keep(String path, String folder) {+ try {+ final kept = Directory(p.join(folder, _keptFolder))+ ..createSync(recursive: true);+ final to = p.join(+ kept.path,+ '${DateTime.now().microsecondsSinceEpoch}-${_keptCount++}${p.extension(path)}',+ );+ File(path).renameSync(to);+ return to;+ } catch (_) {+ _keptInPlace.add(path);+ return path;+ }+}++/// Deletes every picker's copy of a large file kept to go up ([_keep]) — on sign-out or a switch+/// of account, when the files of the chats that held them go, and at launch, for any left by a+/// run that ended first. Nothing else in the app's temporary folders is touched.+Future<void> clearSwarmPickerCopies() async {+ for (final folder in await _copyFolders()) {+ try {+ final kept = Directory(p.join(folder, _keptFolder));+ if (kept.existsSync()) kept.deleteSync(recursive: true);+ } catch (_) {+ // Gone already, or not ours to delete: nothing kept is left to read.+ }+ }+ for (final path in _keptInPlace) {+ try {+ File(path).deleteSync();+ } catch (_) {}+ }+ _keptInPlace.clear();}/// [swarmPickerCopyFolders], each as its real path; none when they cannot be read, and thendiff --git a/mobile/lib/swarm/swarm_new_message_sheet.dart b/mobile/lib/swarm/swarm_new_message_sheet.dartindex f8254d087..24a506be2 100644--- a/mobile/lib/swarm/swarm_new_message_sheet.dart+++ b/mobile/lib/swarm/swarm_new_message_sheet.dart@@ -220,7 +220,8 @@ class _SwarmNewMessageSheetState extends State<SwarmNewMessageSheet>final _text = TextEditingController();final _focus = FocusNode(debugLabel: 'New message');- /// The files going with the message, in memory only, until it goes.+ /// The files going with the message, until it goes: in memory, or a large+ /// one on disk in the app's temporary folder.@overridefinal files = SwarmOutgoingFiles();diff --git a/mobile/lib/swarm/swarm_outgoing_files.dart b/mobile/lib/swarm/swarm_outgoing_files.dartindex 808937dac..9ebba8221 100644--- a/mobile/lib/swarm/swarm_outgoing_files.dart+++ b/mobile/lib/swarm/swarm_outgoing_files.dart@@ -1,24 +1,134 @@+import 'dart:io';+import 'dart:typed_data';+import 'package:flutter/foundation.dart';/// What the backend allows one message to carry (the desktop's/// `kSuperTabAttachmentMaxBytes` and `kSuperTabAttachmentMaxFiles`,/// backend `superTabs/attachments.ts`).-const swarmAttachmentMaxBytes = 10 * 1024 * 1024;+const swarmAttachmentMaxBytes = 256 * 1024 * 1024;const swarmAttachmentMaxFiles = 10;-/// One file waiting to go with a message: its bytes in memory only, never-/// written anywhere on the phone.-@immutable+/// The most one file may be to go up as a form, in one request to the+/// backend (backend `MAX_FORM_ATTACHMENT_BYTES`). A larger one goes straight+/// to storage by a link the backend signs, which no proxy in between caps+/// ([ApiClient.uploadSwarmAttachment]).+const swarmFormAttachmentMaxBytes = 10 * 1024 * 1024;++/// What the person is told of a file past [swarmAttachmentMaxBytes].+const swarmAttachmentMaxLabel =+ '${swarmAttachmentMaxBytes ~/ (1024 * 1024)} MB';++/// One file waiting to go with a message: its [bytes] in memory, never+/// written anywhere on the phone — or, past [swarmFormAttachmentMaxBytes],+/// left where the picker put it at [path] and read from there as it goes up,+/// so a file of hundreds of megabytes is never held whole.class SwarmOutgoingFile {- const SwarmOutgoingFile(this.name, this.bytes);+ SwarmOutgoingFile(this.name, Uint8List this.bytes)+ : size = bytes.length,+ path = null,+ _open = null;++ /// A file read from [path] as it goes up, [size] bytes long. [temporary]+ /// is the picker's own copy in the app's temporary folder: it is deleted+ /// after nothing holds this file any more — sent, taken off, or its chat+ /// closed — once Dart collects it ([_copies]); one left by an app that was+ /// killed first stays in the temporary folder for the system to clear. A+ /// file anywhere else is never touched.+ SwarmOutgoingFile.onDisk(+ this.name,+ String this.path,+ this.size, {+ bool temporary = false,+ }) : bytes = null,+ _open = null {+ if (temporary) _copies.attach(this, path!);+ }++ /// A file of [size] bytes read by [open], for tests: no bytes held, none+ /// on disk.+ @visibleForTesting+ SwarmOutgoingFile.streamed(+ this.name,+ this.size,+ Stream<List<int>> Function() open,+ ) : bytes = null,+ path = null,+ _open = open;final String name;- final Uint8List bytes;++ /// How many bytes the file is.+ final int size;++ /// Its bytes, when they are held in memory.+ final Uint8List? bytes;++ /// Where it is read from, when it is not held in memory.+ final String? path;++ final Stream<List<int>> Function()? _open;++ /// The same file under [name].+ SwarmOutgoingFile named(String name) {+ if (name == this.name) return this;+ final held = bytes;+ if (held != null) return SwarmOutgoingFile(name, held);+ final at = path;+ // The copy stays with the file that holds it ([_copies]); this one only+ // points at it while both are around.+ if (at != null) return _Renamed(name, this, at);+ return SwarmOutgoingFile.streamed(name, size, _open!);+ }++ /// Its bytes, a part at a time.+ Stream<List<int>> openRead() {+ final held = bytes;+ if (held != null) return Stream.value(held);+ final at = path;+ if (at != null) return File(at).openRead(0, size);+ return _open!();+ }++ /// All its bytes at once: for a file small enough to go as a form.+ Future<Uint8List> readAll() async {+ final held = bytes;+ if (held != null) return held;+ final all = BytesBuilder(copy: false);+ await for (final part in openRead()) {+ all.add(part);+ }+ return all.takeBytes();+ }++ /// Deletes a picker's copy once the file that points at it is gone — never+ /// earlier, so one going up, put back after a refusal, or held by two+ /// boxes at once (New message and its chat) is always there to read. A+ /// box deleting what it lets go would delete a file another still holds.+ static final _copies = Finalizer<String>(_deleteCopy);+}++/// A file under a new name that reads [of]'s copy, and keeps [of] — and so+/// the copy — while it is held.+class _Renamed extends SwarmOutgoingFile {+ _Renamed(String name, this.of, String path)+ : super.onDisk(name, path, of.size);++ final SwarmOutgoingFile of;+}++/// Deletes the picker's copy at [path]; one already gone is nothing to do.+void _deleteCopy(String path) {+ try {+ File(path).deleteSync();+ } catch (_) {+ // Already gone: nothing of it is left to keep.+ }}/// The files waiting to go with the next message in a chat — the desktop's-/// `HarnessAttachments` with a Swarm chat's limits, wording and all. Held in-/// memory until sent, or until the chat closes.+/// `HarnessAttachments` with a Swarm chat's limits, wording and all. Held+/// until sent, or until the chat closes.class SwarmOutgoingFiles extends ChangeNotifier {final _files = <SwarmOutgoingFile>[];@@ -41,8 +151,8 @@ class SwarmOutgoingFiles extends ChangeNotifier {final tooLarge = [...oversized];var over = surplus;for (final file in files) {- if (file.bytes.isEmpty) continue;- if (file.bytes.length > swarmAttachmentMaxBytes) {+ if (file.size == 0) continue;+ if (file.size > swarmAttachmentMaxBytes) {tooLarge.add(file.name);continue;}@@ -54,7 +164,7 @@ class SwarmOutgoingFiles extends ChangeNotifier {_files.add(file);}notifyListeners();- const limit = '${swarmAttachmentMaxBytes ~/ (1024 * 1024)} MB';+ const limit = swarmAttachmentMaxLabel;// Both limits can leave files out at once; each says so.final notes = [if (over > 0) 'Attach at most $swarmAttachmentMaxFiles files.',@@ -74,10 +184,7 @@ class SwarmOutgoingFiles extends ChangeNotifier {}) {final taken = {for (final file in _files) file.name};return add(- [- for (final file in files)- SwarmOutgoingFile(swarmFreeName(file.name, taken), file.bytes),- ],+ [for (final file in files) file.named(swarmFreeName(file.name, taken))],oversized: oversized,surplus: surplus,);diff --git a/mobile/lib/swarm/swarm_request.dart b/mobile/lib/swarm/swarm_request.dartindex 302585197..8efe58994 100644--- a/mobile/lib/swarm/swarm_request.dart+++ b/mobile/lib/swarm/swarm_request.dart@@ -1,8 +1,9 @@import 'dart:math';-import 'dart:typed_data';import 'package:dio/dio.dart' show CancelToken;+import 'swarm_outgoing_files.dart' show SwarmOutgoingFile;+/// One Swarm backend call: what `AppNotifier.swarmRequest` does, and what the/// readers here are handed so their tests need no machine.typedef SwarmRequest = Future<Object?> Function(@@ -38,15 +39,16 @@ String superTabOperationId() {/// Sends one file for a message in [conversationId] of Swarm [tabId] and/// answers the backend's `{attachment: {...}}` — `ApiClient.uploadSwarmAttachment`,/// and what the chats here are handed so their tests need no backend.-/// [onProgress] is told the part sent, from 0 to 1. A refusal throws a-/// [SuperTabFailure] carrying the backend's code.+/// [file] is read as it goes, never whole when it is large. [onProgress] is+/// told the part sent, from 0 to 1. A refusal throws a [SuperTabFailure]+/// carrying the backend's code.typedef SwarmUpload =Future<Map<String, dynamic>> Function({required String tabId,required String conversationId,required String name,required String mime,- required Uint8List bytes,+ required SwarmOutgoingFile file,required CancelToken cancel,required void Function(double sent) onProgress,});@@ -57,7 +59,7 @@ Future<Map<String, dynamic>> refuseSwarmUpload({required String conversationId,required String name,required String mime,- required Uint8List bytes,+ required SwarmOutgoingFile file,required CancelToken cancel,required void Function(double sent) onProgress,}) => Future.error(diff --git a/mobile/lib/swarm/swarm_uploads.dart b/mobile/lib/swarm/swarm_uploads.dartindex 4729b4d1e..e32dca841 100644--- a/mobile/lib/swarm/swarm_uploads.dart+++ b/mobile/lib/swarm/swarm_uploads.dart@@ -131,7 +131,7 @@ class SwarmUploads {conversationId: conversationId,name: file.name,mime: swarmMimeForName(file.name),- bytes: file.bytes,+ file: file,cancel: token,onProgress: (sent) {if (token.isCancelled) return;diff --git a/mobile/test/api/api_client_test.dart b/mobile/test/api/api_client_test.dartindex 3e339590c..b044903dd 100644--- a/mobile/test/api/api_client_test.dart+++ b/mobile/test/api/api_client_test.dart@@ -9,6 +9,8 @@ import 'package:harness_mobile/api/access_token_source.dart';import 'package:harness_mobile/api/api_client.dart';import 'package:harness_mobile/auth/auth_session.dart';import 'package:harness_mobile/core/config.dart';+import 'package:harness_mobile/logging/app_log.dart';+import 'package:harness_mobile/swarm/swarm_outgoing_files.dart';import 'package:harness_mobile/swarm/swarm_request.dart';import 'package:harness_mobile/viewer/direct_auth.dart';import 'package:harness_mobile/viewer/direct_auth_api.dart';@@ -25,6 +27,10 @@ class _Backend implements HttpClientAdapter {_,) => (status: 200, body: {'success': true, 'data': <String, Object?>{}});+ /// Holds a request open until it completes, after its body was read; told+ /// the request's cancel signal.+ Future<void> Function(_Request request, Future<void>? cancelled)? hold;+@overrideFuture<ResponseBody> fetch(RequestOptions options,@@ -43,9 +49,11 @@ class _Backend implements HttpClientAdapter {options.uri.queryParameters,_Headers(options.headers),body,+ host: options.uri.host,);final index = requests.length;requests.add(request);+ await hold?.call(request, cancelFuture);final reply = answer(request, index);return ResponseBody.fromString(jsonEncode(reply.body),@@ -61,8 +69,15 @@ class _Backend implements HttpClientAdapter {}class _Request {- _Request(this.method, this.path, this.query, this.headers, this.body);- final String method, path;+ _Request(+ this.method,+ this.path,+ this.query,+ this.headers,+ this.body, {+ this.host = '',+ });+ final String method, path, host;final Map<String, String> query;final _Headers headers;final List<int> body;@@ -82,6 +97,20 @@ class _Headers {}}+/// Keeps every log line, with its error.+class _Log implements AppLog {+ final lines = <String>[];++ @override+ void record(+ AppLogLevel level,+ String category,+ String message, {+ Object? error,+ StackTrace? stackTrace,+ }) => lines.add('$category $message ${error ?? ''}');+}+/// Hands out tokens as told, and counts what it was asked.class _Tokens implements AccessTokenSource {_Tokens(this.tokens);@@ -420,17 +449,32 @@ void main() {String name = 'shot.jpg',String mime = 'image/jpeg',Uint8List? bytes,+ SwarmOutgoingFile? file,+ CancelToken? cancel,+ bool Function()? stillWanted,void Function(double sent)? onProgress,}) => api.uploadSwarmAttachment(tabId: 'tab-1',conversationId: 'conv-1',name: name,mime: mime,- bytes: bytes ?? Uint8List.fromList([1, 2, 3]),- cancel: CancelToken(),+ file:+ file ??+ SwarmOutgoingFile(name, bytes ?? Uint8List.fromList([1, 2, 3])),+ cancel: cancel ?? CancelToken(),+ stillWanted: stillWanted,onProgress: onProgress ?? (_) {},);+ /// A file said to be [size] bytes that is three: no test holds hundreds of+ /// megabytes.+ SwarmOutgoingFile sized(String name, int size) =>+ SwarmOutgoingFile.streamed(+ name,+ size,+ () => Stream.value(Uint8List.fromList([1, 2, 3])),+ );+test('goes straight to the backend as the conversation, then one file',() async {@@ -532,7 +576,11 @@ void main() {throwsA(isA<SuperTabFailure>().having((f) => f.code, 'code', 'ATTACHMENT_TOO_LARGE')- .having((f) => f.message, 'message', 'That file is over 10 MB.'),+ .having(+ (f) => f.message,+ 'message',+ 'Files can be up to 256 MB.',+ ),),);});@@ -554,6 +602,354 @@ void main() {),);});+ test('one of exactly 10 MB still goes as one form', () async {+ backend.answer = (_, _) =>+ (status: 200, body: ok({'attachment': <String, Object?>{}}));++ await upload(+ client(_Tokens(['t'])),+ name: 'edge.zip',+ file: sized('edge.zip', 10 * 1024 * 1024),+ );++ final sent = backend.requests.single;+ expect(sent.path, '/api/super-tabs/tab-1/attachments');+ expect(sent.headers.contentType!.mimeType, 'multipart/form-data');+ });++ group('over 10 MB, by a link straight to storage', () {+ const big = 10 * 1024 * 1024 + 1;+ const link =+ 'https://storage.googleapis.com/harness-files/x/AC4.step'+ '?X-Goog-Signature=s3cr3t&X-Goog-Credential=c';+ final signed = {+ 'content-type': 'application/octet-stream',+ 'content-disposition': 'attachment; filename="AC4.step"',+ 'cache-control': 'private, max-age=0',+ 'x-goog-content-length-range': '$big,$big',+ 'x-goog-if-generation-match': '0',+ };+ final attachment = {+ 'id': 'up-1',+ 'name': 'AC4.step',+ 'mime': 'application/octet-stream',+ 'size': big,+ 'url': 'https://cdn.harness.autonomous.ai/x/AC4.step',+ };++ /// The backend's link, then storage's [storage] status, then the+ /// finished attachment.+ void answers({int storage = 200, Map<String, Object?>? upload}) {+ backend.answer = (request, _) {+ if (request.host == 'storage.googleapis.com') {+ return (status: storage, body: '<Error>AccessDenied</Error>');+ }+ if (request.path.endsWith('/complete')) {+ return (status: 200, body: ok({'attachment': attachment}));+ }+ return (+ status: 200,+ body: ok({+ 'upload':+ upload ??+ {+ 'id': 'up-1',+ 'url': link,+ 'method': 'PUT',+ 'headers': signed,+ 'expiresAt': 1793436000000,+ },+ }),+ );+ };+ }++ test('asks for a link, sends the file to storage with exactly the signed '+ 'headers and no token, then completes', () async {+ answers();+ final told = <double>[];++ final answer = await upload(+ client(_Tokens(['t1'])),+ name: 'AC4.step',+ mime: 'application/octet-stream',+ file: sized('AC4.step', big),+ onProgress: told.add,+ );++ expect(answer, {'attachment': attachment});+ final [ask, put, done] = backend.requests;+ expect(ask.method, 'POST');+ expect(ask.host, 'api.invalid');+ expect(ask.path, '/api/super-tabs/tab-1/attachments/uploads');+ expect(ask.headers.value('authorization'), 'Bearer t1');+ expect(jsonDecode(utf8.decode(ask.body)), {+ 'conversationId': 'conv-1',+ 'name': 'AC4.step',+ 'mime': 'application/octet-stream',+ 'size': big,+ });++ expect(put.method, 'PUT');+ expect(put.host, 'storage.googleapis.com');+ expect(put.path, '/harness-files/x/AC4.step');+ expect(put.query['X-Goog-Signature'], 's3cr3t');+ expect(put.headers.values, {...signed, 'content-length': '$big'});+ expect(put.headers.value('authorization'), isNull);+ expect(put.body, [1, 2, 3]);+ expect(told, isNotEmpty);++ expect(done.method, 'POST');+ expect(+ done.path,+ '/api/super-tabs/tab-1/attachments/uploads/up-1/complete',+ );+ expect(done.headers.value('authorization'), 'Bearer t1');+ expect(jsonDecode(utf8.decode(done.body)), <String, Object?>{});+ });++ test('over 256 MB is refused before anything is sent', () async {+ answers();++ await expectLater(+ upload(+ client(_Tokens(['t'])),+ name: 'huge.step',+ file: sized('huge.step', 256 * 1024 * 1024 + 1),+ ),+ throwsA(+ isA<SuperTabFailure>()+ .having((f) => f.code, 'code', 'ATTACHMENT_TOO_LARGE')+ .having(+ (f) => f.message,+ 'message',+ 'Files can be up to 256 MB.',+ ),+ ),+ );+ expect(backend.requests, isEmpty);+ });++ test('exactly 256 MB goes', () async {+ answers();++ await upload(+ client(_Tokens(['t'])),+ name: 'AC4.step',+ file: sized('AC4.step', 256 * 1024 * 1024),+ );++ expect(backend.requests, hasLength(3));+ expect(+ backend.requests[1].headers.value('content-length'),+ '${256 * 1024 * 1024}',+ );+ });++ test('storage refusing the file names it, never the link, completes '+ 'nothing, and the next try asks for a new link', () async {+ final log = _Log();+ final before = appLog;+ appLog = log;+ addTearDown(() => appLog = before);+ answers(storage: 412);+ final api = client(_Tokens(['t']));++ Object? failure;+ try {+ await upload(api, name: 'AC4.step', file: sized('AC4.step', big));+ } catch (error) {+ failure = error;+ }++ expect(+ failure,+ isA<SuperTabFailure>()+ .having(+ (f) => f.message,+ 'message',+ 'Could not upload AC4.step. Try again.',+ )+ .having((f) => f.statusCode, 'status', 412),+ );+ expect('$failure', isNot(contains('googleapis')));+ expect([+ for (final r in backend.requests) r.path,+ ], isNot(contains(endsWith('/complete'))));+ expect(log.lines.join('\n'), contains('412'));+ expect(log.lines.join('\n'), isNot(contains('googleapis')));+ expect(log.lines.join('\n'), isNot(contains('s3cr3t')));++ answers();+ await upload(api, name: 'AC4.step', file: sized('AC4.step', big));+ expect([+ for (final r in backend.requests)+ if (r.path.endsWith('/uploads')) r.path,+ ], hasLength(2));+ });++ test('a transfer that breaks names the file, never the link', () async {+ answers();+ final api = client(_Tokens(['t']));+ final breaking = SwarmOutgoingFile.streamed(+ 'AC4.step',+ big,+ () => Stream.error(const SocketException('Broken pipe')),+ );++ Object? failure;+ try {+ await upload(api, name: 'AC4.step', file: breaking);+ } catch (error) {+ failure = error;+ }++ expect(+ failure,+ isA<SuperTabFailure>().having(+ (f) => f.message,+ 'message',+ 'Could not upload AC4.step. Try again.',+ ),+ );+ expect('$failure', isNot(contains('s3cr3t')));+ expect([+ for (final r in backend.requests) r.path,+ ], isNot(contains(endsWith('/complete'))));+ });++ test('given up while it goes to storage: nothing is completed, and the '+ 'link is in nothing the caller is handed', () async {+ answers();+ final cancel = CancelToken();+ backend.hold = (request, cancelled) async {+ if (request.host != 'storage.googleapis.com') return;+ cancel.cancel('closed');+ await cancelled;+ };++ Object? failure;+ try {+ await upload(+ client(_Tokens(['t'])),+ name: 'AC4.step',+ file: sized('AC4.step', big),+ cancel: cancel,+ );+ } catch (error) {+ failure = error;+ }++ expect(+ failure,+ isA<DioException>()+ .having((e) => e.type, 'type', DioExceptionType.cancel)+ .having(+ (e) => '${e.requestOptions.uri}',+ 'uri',+ isNot(contains('googleapis')),+ ),+ );+ expect('$failure', isNot(contains('s3cr3t')));+ expect([+ for (final r in backend.requests) r.path,+ ], isNot(contains(endsWith('/complete'))));+ });++ test(+ 'given up while the link is asked for: storage gets nothing',+ () async {+ answers();+ final cancel = CancelToken();+ backend.hold = (request, cancelled) async {+ if (request.path.endsWith('/uploads')) cancel.cancel('closed');+ };++ await expectLater(+ upload(+ client(_Tokens(['t'])),+ name: 'AC4.step',+ file: sized('AC4.step', big),+ cancel: cancel,+ ),+ throwsA(isA<DioException>()),+ );+ expect(backend.requests.map((r) => r.host), ['api.invalid']);+ },+ );++ test('the account changed once the link came: nothing goes to '+ 'storage', () async {+ answers();+ var current = true;+ backend.hold = (request, _) async {+ if (request.path.endsWith('/uploads')) current = false;+ };++ await expectLater(+ upload(+ client(_Tokens(['t'])),+ name: 'AC4.step',+ file: sized('AC4.step', big),+ stillWanted: () => current,+ ),+ throwsA(isA<DioException>()),+ );+ expect(backend.requests.map((r) => r.host), ['api.invalid']);+ });++ test('a link that is not https gets no file', () async {+ answers(+ upload: {+ 'id': 'up-1',+ 'url': 'http://storage.googleapis.com/x',+ 'method': 'PUT',+ 'headers': signed,+ },+ );++ await expectLater(+ upload(+ client(_Tokens(['t'])),+ name: 'AC4.step',+ file: sized('AC4.step', big),+ ),+ throwsA(+ isA<SuperTabFailure>().having(+ (f) => f.code,+ 'code',+ 'UPLOAD_FAILED',+ ),+ ),+ );+ expect(backend.requests, hasLength(1));+ });++ test('a refused link request says the backend\'s words', () async {+ backend.answer = (_, _) => (+ status: 429,+ body: {+ 'success': false,+ 'error': {'code': 'RATE_LIMITED', 'message': 'Slow down.'},+ },+ );++ await expectLater(+ upload(+ client(_Tokens(['t'])),+ name: 'AC4.step',+ file: sized('AC4.step', big),+ ),+ throwsA(+ isA<SuperTabFailure>()+ .having((f) => f.code, 'code', 'RATE_LIMITED')+ .having((f) => f.message, 'message', 'Slow down.')+ .having((f) => f.statusCode, 'status', 429),+ ),+ );+ expect(backend.requests, hasLength(1));+ });+ });});group('describing a failure', () {diff --git a/mobile/test/render/swarm_attach_render_test.dart b/mobile/test/render/swarm_attach_render_test.dartindex 490f75009..f9bd952ba 100644--- a/mobile/test/render/swarm_attach_render_test.dart+++ b/mobile/test/render/swarm_attach_render_test.dart@@ -14,6 +14,7 @@ import 'package:harness_mobile/swarm/swarm_conversation_page.dart';import 'package:harness_mobile/swarm/swarm_file_picker.dart';import 'package:harness_mobile/swarm/swarm_request.dart';import 'package:harness_mobile/swarm/swarm_session.dart';+import 'package:harness_mobile/swarm/swarm_outgoing_files.dart';import 'package:image_picker/image_picker.dart' show XFile;import '../voice_fakes.dart';@@ -174,7 +175,7 @@ void main() {required String conversationId,required String name,required String mime,- required Uint8List bytes,+ required SwarmOutgoingFile file,required dynamic cancel,required void Function(double sent) onProgress,}) {diff --git a/mobile/test/render/swarm_thread_render_test.dart b/mobile/test/render/swarm_thread_render_test.dartindex 82db44017..36b7726d0 100644--- a/mobile/test/render/swarm_thread_render_test.dart+++ b/mobile/test/render/swarm_thread_render_test.dart@@ -13,6 +13,7 @@ import 'package:harness_mobile/shared/theme/color_palette.dart';import 'package:harness_mobile/swarm/swarm_conversation_page.dart';import 'package:harness_mobile/swarm/swarm_file_picker.dart';import 'package:harness_mobile/swarm/swarm_session.dart';+import 'package:harness_mobile/swarm/swarm_outgoing_files.dart';import 'package:image_picker/image_picker.dart' show XFile;import '../swarm/swarm_fixture.dart';@@ -98,7 +99,7 @@ void main() {required String conversationId,required String name,required String mime,- required Uint8List bytes,+ required SwarmOutgoingFile file,required dynamic cancel,required void Function(double sent) onProgress,}) {diff --git a/mobile/test/swarm/swarm_attachment_test.dart b/mobile/test/swarm/swarm_attachment_test.dartindex 8cbbb881e..0063c5d94 100644--- a/mobile/test/swarm/swarm_attachment_test.dart+++ b/mobile/test/swarm/swarm_attachment_test.dart@@ -23,12 +23,12 @@ void main() {final link = Uri.parse('https://cdn.example/swarm/a.png');- SuperTabAttachment attachment({String mime = 'image/png'}) =>+ SuperTabAttachment attachment({String mime = 'image/png', int size = 2048}) =>SuperTabAttachment.fromJson({'id': 'file-1','name': 'screen.png','mime': mime,- 'size': 2048,+ 'size': size,'url': link.toString(),});@@ -226,6 +226,27 @@ void main() {expect(storage.asked, isEmpty);});+ testWidgets('a picture over 10 MB keeps the chip, and nothing is '+ 'fetched', (tester) async {+ await pump(tester, file: attachment(size: 11 * 1024 * 1024));+ await tester.pump();++ expect(chip, findsOneWidget);+ expect(preview, findsNothing);+ expect(storage.asked, isEmpty);+ });++ testWidgets('a picture of 1 MB still shows in place', (tester) async {+ storage.bytes = await png(tester, 40, 30);+ await pump(tester, file: attachment(size: 1024 * 1024));+ await until(tester, () => drawn(tester));++ expect(preview, findsOneWidget);+ expect(chip, findsNothing);+ expect(storage.asked, isNotEmpty);+ await closed(tester);+ });+testWidgets("a picture not on Harness's file storage keeps the chip", (tester,) async {diff --git a/mobile/test/swarm/swarm_chat_dictation_test.dart b/mobile/test/swarm/swarm_chat_dictation_test.dartindex 3fc6adc77..56c7d4231 100644--- a/mobile/test/swarm/swarm_chat_dictation_test.dart+++ b/mobile/test/swarm/swarm_chat_dictation_test.dart@@ -88,7 +88,7 @@ void main() {required conversationId,required name,required mime,- required bytes,+ required file,required cancel,required onProgress,}) {diff --git a/mobile/test/swarm/swarm_chat_test.dart b/mobile/test/swarm/swarm_chat_test.dartindex 6cc0f9fcf..420f9f243 100644--- a/mobile/test/swarm/swarm_chat_test.dart+++ b/mobile/test/swarm/swarm_chat_test.dart@@ -15,6 +15,7 @@ import 'package:harness_mobile/swarm/swarm_file_picker.dart';import 'package:harness_mobile/swarm/swarm_message_row.dart';import 'package:harness_mobile/swarm/swarm_request.dart';import 'package:harness_mobile/swarm/swarm_session.dart';+import 'package:harness_mobile/swarm/swarm_outgoing_files.dart';import 'package:lucide_icons_flutter/lucide_icons.dart';import '../theme/sheet_shape.dart';@@ -2399,7 +2400,7 @@ void main() {required String conversationId,required String name,required String mime,- required Uint8List bytes,+ required SwarmOutgoingFile file,required CancelToken cancel,required void Function(double sent) onProgress,}) {@@ -3348,7 +3349,7 @@ void main() {required String conversationId,required String name,required String mime,- required Uint8List bytes,+ required SwarmOutgoingFile file,required dynamic cancel,required void Function(double sent) onProgress,}) {@@ -3547,19 +3548,34 @@ void main() {expect(fake.commands, isEmpty);});- testWidgets('a file over 10 MB is named under the files', (tester) async {+ testWidgets('a file over 256 MB is named under the files', (tester) async {pickSwarmFiles = () async => [- picked('big.zip', 10 * 1024 * 1024 + 1),+ // Said to be past the limit, holding nothing: refused by its size.+ XFile.fromData(+ Uint8List(0),+ path: '/picker-copies/big.zip',+ length: 256 * 1024 * 1024 + 1,+ ),picked('ok.txt', 3),];await pump(tester, backend([message('m1', 1)]));await attach(tester, 'swarm-attach-files');- expect(find.text('big.zip is over 10 MB.'), findsOneWidget);+ expect(find.text('big.zip is over 256 MB.'), findsOneWidget);expect(key('swarm-outgoing-ok.txt'), findsOneWidget);});+ testWidgets('a file just over 10 MB is attached', (tester) async {+ pickSwarmFiles = () async => [picked('scan.pdf', 10 * 1024 * 1024 + 1)];+ await pump(tester, backend([message('m1', 1)]));++ await attach(tester, 'swarm-attach-files');++ expect(find.textContaining('is over'), findsNothing);+ expect(key('swarm-outgoing-scan.pdf'), findsOneWidget);+ });+testWidgets('camera access turned off offers Settings', (tester) async {takeSwarmPhoto = () async =>throw PlatformException(code: 'camera_access_denied');diff --git a/mobile/test/swarm/swarm_conversation_files_test.dart b/mobile/test/swarm/swarm_conversation_files_test.dartindex 838effd70..c9464dc72 100644--- a/mobile/test/swarm/swarm_conversation_files_test.dart+++ b/mobile/test/swarm/swarm_conversation_files_test.dart@@ -142,7 +142,7 @@ void main() {final r = rig();r.uploads.refuse['b.jpg'] = const SuperTabFailure('ATTACHMENT_TOO_LARGE',- 'That file is over 10 MB.',+ 'Files can be up to 256 MB.',statusCode: 413,);final c = await open(r.reader);@@ -151,7 +151,7 @@ void main() {expect(await c.send(), isFalse);- expect(c.error, 'That file is over 10 MB.');+ expect(c.error, 'Files can be up to 256 MB.');expect(c.draft, 'look');expect([for (final f in c.files.files) f.name], ['a.jpg', 'b.jpg']);expect(r.swarm.commands, isEmpty);@@ -393,6 +393,73 @@ void main() {expect(await sending, isFalse);});+ group('a file over 10 MB', () {+ /// Said to be 50 MB, and three bytes: no test holds the rest.+ SwarmOutgoingFile large(String name) => SwarmOutgoingFile.streamed(+ name,+ 50 * 1024 * 1024,+ () => Stream.value([1, 2, 3]),+ );++ test('goes up as its file, never read into memory first', () async {+ final r = rig();+ final c = await open(r.reader);+ c.files.add([large('AC4.step')]);++ expect(await c.send(), isTrue);++ final sent = r.uploads.asked.single.file;+ expect(sent.size, 50 * 1024 * 1024);+ expect(sent.bytes, isNull);+ expect(r.swarm.commands.single['attachmentIds'], ['id-AC4.step']);+ });++ test('leaving the chat while it goes up stops it, and an answer that '+ 'comes after lands nowhere', () async {+ final r = rig();+ r.uploads.answersAtOnce = false;+ await r.reader.refresh();+ final c = SwarmConversation(r.reader, 'g1');+ await c.load();+ c.draft = 'the model';+ c.files.add([large('AC4.step')]);++ final sending = c.send();+ await settle();+ final going = r.uploads.asked.single;+ c.dispose();+ going.answer.complete(FakeUploads.attachment('late'));++ expect(going.cancel.isCancelled, isTrue);+ expect(await sending, isFalse);+ expect(r.swarm.commands, isEmpty);+ expect(c.pending, isNull);+ expect(c.files.files, isEmpty);+ });++ test('a failed upload says which file, leaves nothing going, and goes '+ 'again from the start', () async {+ final r = rig();+ r.uploads.refuse['AC4.step'] = const SuperTabFailure(+ 'UPLOAD_FAILED',+ 'Could not upload AC4.step. Try again.',+ statusCode: 403,+ );+ final c = await open(r.reader);+ c.files.add([large('AC4.step')]);++ expect(await c.send(), isFalse);+ expect(c.error, 'Could not upload AC4.step. Try again.');+ expect(c.uploading, isFalse);+ expect(c.isUploading(c.files.files.single), isFalse);++ r.uploads.refuse.clear();+ expect(await c.send(), isTrue);+ expect(r.uploads.names, ['AC4.step', 'AC4.step']);+ expect(r.swarm.commands.single['attachmentIds'], ['id-AC4.step']);+ });+ });+test('closing the chat lets its files go', () async {final r = rig();await r.reader.refresh();diff --git a/mobile/test/swarm/swarm_file_picker_test.dart b/mobile/test/swarm/swarm_file_picker_test.dartindex a2827615e..158239a71 100644--- a/mobile/test/swarm/swarm_file_picker_test.dart+++ b/mobile/test/swarm/swarm_file_picker_test.dart@@ -45,14 +45,14 @@ void main() {return XFile(file.path, name: name);}- /// A copy past the limit, made without writing ten megabytes.- XFile bigCopy(String name) {+ /// A copy of [size] bytes, past the limit by default, made without writing them: a sparse file.+ XFile bigCopy(String name, [int size = 256 * 1024 * 1024 + 1]) {final file = File('${folder.path}/$name')..createSync();file.openSync(mode: FileMode.write)..setPositionSync(0)- ..truncateSync(swarmAttachmentMaxBytes + 1)+ ..truncateSync(size)..closeSync();- return XFile(file.path, name: name);+ return _Counted(file.path, name: name);}List<String> names() => [for (final f in files.files) f.name];@@ -69,7 +69,7 @@ void main() {expect(outcome, isA<SwarmPicked>());expect((outcome as SwarmPicked).note, isNull);expect(names(), ['photo.jpg', 'photo-2.jpg']);- expect([for (final f in files.files) f.bytes.length], [3, 4]);+ expect([for (final f in files.files) f.bytes!.length], [3, 4]);});test('keeps a photo’s own kind in its name', () async {@@ -135,13 +135,13 @@ void main() {expect((outcome as SwarmPickDenied).source, SwarmPickSource.library);});- test('a photo over 10 MB is named and left out', () async {+ test('a photo over 256 MB is named and left out', () async {final big = bigCopy('big.jpg');pickSwarmPhotos = (limit) async => [big, copy('ok.jpg', 2)];final outcome = await addSwarmPicked(files, SwarmPickSource.library);- expect((outcome as SwarmPicked).note, 'photo.jpg is over 10 MB.');+ expect((outcome as SwarmPicked).note, 'photo.jpg is over 256 MB.');expect(names(), ['photo-2.jpg']);expect(File(big.path).existsSync(), isFalse);});@@ -203,17 +203,60 @@ void main() {);});- test('a file over 10 MB is refused before it is read', () async {+ test('a file over 256 MB is refused before it is read', () async {final big = bigCopy('big.zip');pickSwarmFiles = () async => [big, copy('ok.txt', 2)];final outcome = await addSwarmPicked(files, SwarmPickSource.files);- expect((outcome as SwarmPicked).note, 'big.zip is over 10 MB.');+ expect((outcome as SwarmPicked).note, 'big.zip is over 256 MB.');expect(names(), ['ok.txt']);+ expect((big as _Counted).reads, 0);+ expect(File(big.path).existsSync(), isFalse);+ });++ test('a file over 10 MB is taken but never read into memory: it goes up from the picker\'s '+ 'copy, which stays for it', () async {+ final big = bigCopy('AC4.step', 10 * 1024 * 1024 + 1);+ pickSwarmFiles = () async => [big];++ final outcome = await addSwarmPicked(files, SwarmPickSource.files);++ expect((outcome as SwarmPicked).note, isNull);+ expect(names(), ['AC4.step']);+ expect((big as _Counted).reads, 0);+ expect(files.files.single.bytes, isNull);+ final kept = Directory('${folder.path}/harness-swarm-outgoing');+ expect(kept.listSync(), hasLength(1), reason: 'moved where it is kept');expect(File(big.path).existsSync(), isFalse);});+ test('clearing the kept copies deletes them, and nothing else of the '+ 'temporary folder', () async {+ pickSwarmFiles = () async => [bigCopy('AC4.step', 10 * 1024 * 1024 + 1)];+ await addSwarmPicked(files, SwarmPickSource.files);+ final other = File('${folder.path}/not-ours.tmp')..createSync();++ await clearSwarmPickerCopies();++ expect(+ Directory('${folder.path}/harness-swarm-outgoing').existsSync(),+ isFalse,+ );+ expect(other.existsSync(), isTrue);+ });++ test('a file of 10 MB is read into memory, and its copy deleted', () async {+ final edge = bigCopy('edge.bin', 10 * 1024 * 1024);+ pickSwarmFiles = () async => [edge];++ await addSwarmPicked(files, SwarmPickSource.files);++ expect(names(), ['edge.bin']);+ expect(files.files.single.bytes, hasLength(10 * 1024 * 1024));+ expect(File(edge.path).existsSync(), isFalse);+ });+test('files past the tenth are left out and counted', () async {files.add([for (var i = 0; i < 9; i++) SwarmOutgoingFile('f$i.txt', Uint8List(1)),@@ -361,7 +404,7 @@ void main() {/// A picker's file that counts how often its bytes are read.class _Counted extends XFile {- _Counted(super.path);+ _Counted(super.path, {super.name});int reads = 0;diff --git a/mobile/test/swarm/swarm_fixture.dart b/mobile/test/swarm/swarm_fixture.dartindex a496f573e..de546e6d5 100644--- a/mobile/test/swarm/swarm_fixture.dart+++ b/mobile/test/swarm/swarm_fixture.dart@@ -8,6 +8,7 @@ import 'package:flutter_test/flutter_test.dart';import 'package:harness_mobile/swarm/swarm_home_cache.dart';import 'package:harness_mobile/swarm/swarm_request.dart';+import 'package:harness_mobile/swarm/swarm_outgoing_files.dart';/// Swarm answers as the backend sends them (docs/design/2026-10-26-swarm-state-parts.md, section 4), built by hand so a/// test reads like the wire. Nothing here reaches a machine or the backend.@@ -277,14 +278,15 @@ class FakeUpload {FakeUpload(this.name,this.mime,- this.bytes,+ this.file,this.conversationId,this.tabId,this.cancel,this.onProgress,);final String name, mime, conversationId, tabId;- final Uint8List bytes;+ final SwarmOutgoingFile file;+ Uint8List? get bytes => file.bytes;final CancelToken cancel;final void Function(double sent) onProgress;final answer = Completer<Map<String, dynamic>>();@@ -308,14 +310,14 @@ class FakeUploads {required conversationId,required name,required mime,- required bytes,+ required file,required cancel,required onProgress,}) {final u = FakeUpload(name,mime,- bytes,+ file,conversationId,tabId,cancel,diff --git a/mobile/test/swarm/swarm_outgoing_files_test.dart b/mobile/test/swarm/swarm_outgoing_files_test.dartindex eb957f6bc..3dcb12ea9 100644--- a/mobile/test/swarm/swarm_outgoing_files_test.dart+++ b/mobile/test/swarm/swarm_outgoing_files_test.dart@@ -1,6 +1,8 @@import 'dart:typed_data';+import 'package:flutter/material.dart';import 'package:flutter_test/flutter_test.dart';+import 'package:harness_mobile/swarm/swarm_attach.dart';import 'package:harness_mobile/swarm/swarm_outgoing_files.dart';/// The files waiting to go with the next message in a phone Swarm chat: the@@ -10,6 +12,13 @@ void main() {SwarmOutgoingFile file(String name, int size) =>SwarmOutgoingFile(name, Uint8List(size));+ /// A file of [size] bytes on disk, never read here: no test holds hundreds+ /// of megabytes.+ SwarmOutgoingFile sized(String name, int size) =>+ SwarmOutgoingFile.onDisk(name, '/nowhere/$name', size);++ const mb = 1024 * 1024;+test('takes files in the order picked', () {final files = SwarmOutgoingFiles();addTearDown(files.dispose);@@ -19,32 +28,56 @@ void main() {expect([for (final f in files.files) f.name], ['a.jpg', 'b.pdf']);});- test('a file over 10 MB is left out and named', () {+ test('a file just over 10 MB is taken', () {+ final files = SwarmOutgoingFiles();+ addTearDown(files.dispose);++ final said = files.add([file('big.jpg', 10 * mb + 1)]);++ expect(said, isNull);+ expect([for (final f in files.files) f.name], ['big.jpg']);+ });++ test('a file over 256 MB is left out and named', () {final files = SwarmOutgoingFiles();addTearDown(files.dispose);final said = files.add([- file('big.jpg', 10 * 1024 * 1024 + 1),- file('ok.jpg', 10 * 1024 * 1024),+ sized('big.zip', 256 * mb + 1),+ sized('ok.zip', 256 * mb),]);- expect(said, 'big.jpg is over 10 MB.');- expect([for (final f in files.files) f.name], ['ok.jpg']);+ expect(said, 'big.zip is over 256 MB.');+ expect([for (final f in files.files) f.name], ['ok.zip']);});- test('several files over 10 MB are counted', () {+ test('several files over 256 MB are counted', () {final files = SwarmOutgoingFiles();addTearDown(files.dispose);final said = files.add([- file('a.jpg', 11 * 1024 * 1024),- file('b.jpg', 12 * 1024 * 1024),+ sized('a.zip', 257 * mb),+ sized('b.zip', 300 * mb),]);- expect(said, '2 files are over 10 MB.');+ expect(said, '2 files are over 256 MB.');expect(files.files, isEmpty);});+ test('a photo numbered beside another still goes up from its file', () {+ final files = SwarmOutgoingFiles();+ addTearDown(files.dispose);+ files.add([file('photo.png', 1)]);++ files.addNumbered([sized('photo.png', 20 * mb)]);++ final numbered = files.files.last;+ expect(numbered.name, 'photo-2.png');+ expect(numbered.bytes, isNull);+ expect(numbered.path, '/nowhere/photo.png');+ expect(numbered.size, 20 * mb);+ });+test('an eleventh file is refused', () {final files = SwarmOutgoingFiles();addTearDown(files.dispose);@@ -145,10 +178,52 @@ void main() {final said = files.add([for (var i = 0; i < 11; i++) file('f$i.txt', 1),- file('big.jpg', 10 * 1024 * 1024 + 1),+ sized('big.jpg', 256 * mb + 1),]);- expect(said, 'Attach at most 10 files. big.jpg is over 10 MB.');+ expect(said, 'Attach at most 10 files. big.jpg is over 256 MB.');expect(files.files, hasLength(10));});++ group('the composer\'s chips', () {+ Future<void> pumpChips(WidgetTester tester, SwarmOutgoingFile file) async {+ final box = _Box()..files.add([file]);+ addTearDown(box.files.dispose);+ await tester.pumpWidget(+ MaterialApp(+ home: Scaffold(body: SwarmOutgoingChips(box: box)),+ ),+ );+ }++ testWidgets('a picture over 10 MB shows a file mark, never decoded', (+ tester,+ ) async {+ await pumpChips(+ tester,+ SwarmOutgoingFile.onDisk('photo.png', '/nowhere/photo.png', 11 * mb),+ );++ expect(find.byType(Image), findsNothing);+ expect(find.text('photo.png'), findsOneWidget);+ });++ testWidgets('a small picture shows its thumbnail', (tester) async {+ await pumpChips(tester, file('photo.png', 3));++ expect(find.byType(Image), findsOneWidget);+ });+ });+}++/// A composer that holds files and sends none.+class _Box implements SwarmFilesBox {+ @override+ final files = SwarmOutgoingFiles();++ @override+ bool isUploading(SwarmOutgoingFile file) => false;++ @override+ double? uploadProgress(SwarmOutgoingFile file) => null;}diff --git a/mobile/test/swarm/swarm_request_test.dart b/mobile/test/swarm/swarm_request_test.dartindex f0e04d809..7c6e597be 100644--- a/mobile/test/swarm/swarm_request_test.dart+++ b/mobile/test/swarm/swarm_request_test.dart@@ -1,14 +1,18 @@import 'dart:async';+import 'dart:io';import 'dart:typed_data';import 'package:dio/dio.dart' show CancelToken;import 'package:flutter_test/flutter_test.dart';import 'package:harness_mobile/core/models.dart';import 'package:harness_mobile/swarm/swarm_conversation.dart';+import 'package:harness_mobile/swarm/swarm_file_picker.dart'+ show swarmPickerCopyFolders;import 'package:harness_mobile/swarm/swarm_inbox.dart';import 'package:harness_mobile/swarm/swarm_reader.dart';import 'package:harness_mobile/swarm/swarm_request.dart';import 'package:harness_mobile/ws/ws_conn.dart';+import 'package:harness_mobile/swarm/swarm_outgoing_files.dart';import '../viewer_app_fixture.dart';import 'swarm_fixture.dart' show changes, firstLoad, groupData, me, tab;@@ -662,7 +666,7 @@ void main() {conversationId: 'g1',name: 'shot.jpg',mime: 'image/jpeg',- bytes: Uint8List(1),+ file: SwarmOutgoingFile('shot.jpg', Uint8List(1)),cancel: CancelToken(),onProgress: (_) {},);@@ -680,6 +684,93 @@ void main() {expect(rig.conn('m').payloadsOf('super_tabs'), isEmpty);});+ test('signing out while a file goes up stops it, and it lands '+ 'nowhere', () async {+ final rig = await signedInWith({'m': []});+ addTearDown(rig.app.dispose);+ final answer = Completer<Map<String, dynamic>>();+ rig.api.onSwarmUpload = () => answer.future;+ final callers = CancelToken();++ final sending = rig.app.swarmUpload(+ tabId: 't',+ conversationId: 'g1',+ name: 'AC4.step',+ mime: 'application/octet-stream',+ file: SwarmOutgoingFile.streamed(+ 'AC4.step',+ 50 * 1024 * 1024,+ () => Stream.value([1]),+ ),+ cancel: callers,+ onProgress: (_) {},+ );+ await settle();+ await rig.app.logout();++ expect(rig.api.swarmUploadCancels.single.isCancelled, isTrue);+ expect(callers.isCancelled, isFalse, reason: 'the chat\'s own token');+ answer.complete({+ 'attachment': {'id': 'late'},+ });+ await expectLater(+ sending,+ throwsA(+ isA<SuperTabFailure>().having(+ (f) => f.code,+ 'code',+ 'ACCOUNT_CHANGED',+ ),+ ),+ );+ });++ test('the chat giving its upload up still stops it', () async {+ final rig = await signedInWith({'m': []});+ addTearDown(rig.app.dispose);+ rig.api.onSwarmUpload = () => Completer<Map<String, dynamic>>().future;+ final callers = CancelToken();++ unawaited(+ rig.app+ .swarmUpload(+ tabId: 't',+ conversationId: 'g1',+ name: 'a.zip',+ mime: 'application/zip',+ file: SwarmOutgoingFile('a.zip', Uint8List(1)),+ cancel: callers,+ onProgress: (_) {},+ )+ .catchError((_) => <String, dynamic>{}),+ );+ await settle();+ callers.cancel('closed');+ await settle();++ expect(rig.api.swarmUploadCancels.single.isCancelled, isTrue);+ });++ test('signing out deletes the copies large files were kept in, and only '+ 'those', () async {+ final temp = Directory.systemTemp.createTempSync('swarm-copies');+ addTearDown(() => temp.deleteSync(recursive: true));+ final before = swarmPickerCopyFolders;+ swarmPickerCopyFolders = () async => [temp.path];+ addTearDown(() => swarmPickerCopyFolders = before);+ final kept = File('${temp.path}/harness-swarm-outgoing/1-AC4.step')+ ..createSync(recursive: true);+ final other = File('${temp.path}/someone-elses.tmp')..createSync();+ final rig = await signedInWith({'m': []});+ addTearDown(rig.app.dispose);++ await rig.app.logout();+ await settle();++ expect(kept.existsSync(), isFalse);+ expect(other.existsSync(), isTrue);+ });+test('an answer that lands after sign-out is dropped', () async {final rig = await signedInWith({'m': []});addTearDown(rig.app.dispose);diff --git a/mobile/test/swarm/swarm_session_test.dart b/mobile/test/swarm/swarm_session_test.dartindex 26d55bcc6..6feec498a 100644--- a/mobile/test/swarm/swarm_session_test.dart+++ b/mobile/test/swarm/swarm_session_test.dart@@ -14,6 +14,7 @@ import 'package:harness_mobile/swarm/swarm_inbox.dart';import 'package:harness_mobile/swarm/swarm_request.dart';import 'package:harness_mobile/swarm/swarm_session.dart';import 'package:harness_mobile/swarm/swarm_start.dart';+import 'package:harness_mobile/swarm/swarm_outgoing_files.dart';import '../voice_fakes.dart';import 'swarm_fixture.dart';@@ -121,7 +122,7 @@ void main() {required conversationId,required name,required mime,- required bytes,+ required file,required cancel,required onProgress,}) async {@@ -142,7 +143,7 @@ void main() {conversationId: 'g9',name: 'shot.jpg',mime: 'image/jpeg',- bytes: Uint8List(1),+ file: SwarmOutgoingFile('shot.jpg', Uint8List(1)),cancel: CancelToken(),onProgress: (_) {},);diff --git a/mobile/test/swarm/swarm_thread_test.dart b/mobile/test/swarm/swarm_thread_test.dartindex 53410af59..521b2da80 100644--- a/mobile/test/swarm/swarm_thread_test.dart+++ b/mobile/test/swarm/swarm_thread_test.dart@@ -620,7 +620,7 @@ void main() {'the files, and sends nothing', () async {const refused = SuperTabFailure('ATTACHMENT_TOO_LARGE',- 'That file is over 10 MB.',+ 'Files can be up to 256 MB.',statusCode: 413,);final uploads = FakeUploads()..refuse['b.jpg'] = refused;@@ -634,7 +634,7 @@ void main() {expect(await t.send(), isFalse);expect(t.error, r.chat.error);- expect(t.error, 'That file is over 10 MB.');+ expect(t.error, 'Files can be up to 256 MB.');expect(t.draft, 'look');expect(names(t.files.files), ['a.jpg', 'b.jpg']);expect(r.swarm.commands, isEmpty);diff --git a/mobile/test/viewer_app_fixture.dart b/mobile/test/viewer_app_fixture.dartindex 74c6d797a..2ecd4cf3e 100644--- a/mobile/test/viewer_app_fixture.dart+++ b/mobile/test/viewer_app_fixture.dart@@ -33,6 +33,7 @@ import 'package:harness_mobile/viewer/viewer_services.dart';import 'package:harness_mobile/ws/relay_codec.dart';import 'package:harness_mobile/ws/terminal_transport_plugin.dart';import 'package:harness_mobile/ws/ws_conn.dart';+import 'package:harness_mobile/swarm/swarm_outgoing_files.dart';import 'agent_pager_fixture.dart';import 'viewer/fake_http.dart';@@ -188,6 +189,10 @@ class FakeApi extends ApiClient {/// Answers each Swarm chat file sent; records what was sent, by/// `tab/conversation/name`. Never the network.final List<String> swarmUploads = [];++ /// The cancel token each chat file upload was handed.+ final swarmUploadCancels = <CancelToken>[];+Future<Map<String, dynamic>> Function() onSwarmUpload = () async => {'attachment': <String, dynamic>{'id': 'att'},};@@ -198,10 +203,12 @@ class FakeApi extends ApiClient {required String conversationId,required String name,required String mime,- required Uint8List bytes,+ required SwarmOutgoingFile file,required CancelToken cancel,required void Function(double sent) onProgress,+ bool Function()? stillWanted,}) {+ swarmUploadCancels.add(cancel);swarmUploads.add('$tabId/$conversationId/$name');return onSwarmUpload();}