Skip to content

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.

feat(super-tabs): paste images into the Swarm chat (#1486)

0xdiego255a55e79fb60a
diff --git a/backend/integration/superTabs.test.ts b/backend/integration/superTabs.test.ts
index 6799510b8..c39076e4f 100644
--- a/backend/integration/superTabs.test.ts
+++ b/backend/integration/superTabs.test.ts
@@ -1063,3 +1063,122 @@ it('allocates workgroup numbers transactionally and replays the same number afte
expect((await run(tab, command, owner, undefined, operations[0])).result).toEqual(results[0]!.result)
expect((await store.read(owner, tab)).state.conversations.map(c => c.number)).toEqual([undefined, 1, 2, 3])
})
+
+describe('images attached to Swarm messages', () => {
+ const PART = 256 * 1024
+ const png = (size: number) => {
+ const bytes = Buffer.alloc(size, 7)
+ Buffer.from([0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a, 0, 0, 0, 13, 0x49, 0x48, 0x44, 0x52, 0, 0, 0, 3, 0, 0, 0, 2]).copy(bytes)
+ return bytes
+ }
+ const http = (user: AuthUser, method: 'GET' | 'POST' | 'DELETE', url: string, payload?: object) =>
+ app.inject({ method, url, headers: { authorization: `Bearer ${user.sub}` }, ...(payload ? { payload } : {}) })
+ const upload = (user: AuthUser, tab: string, bytes: Buffer, name = 'screen.png') =>
+ http(user, 'POST', `/api/super-tabs/${tab}/attachments`, { name, size: bytes.length, data: bytes.subarray(0, PART).toString('base64') })
+ const send = (attachmentIds: string[], text = ''): Command =>
+ ({ type: 'message.send', conversationId: 'lead', text, replyTo: null, recipientIds: [], attachmentIds })
+
+ it('uploads in parts, sends image-only messages, and lets only readers of the conversation see the bytes', async () => {
+ const { tab, lead } = await fixture()
+ await invite(tab)
+ const bytes = png(PART + 10)
+ const created = await upload(owner, tab, bytes)
+ expect(created.statusCode).toBe(200)
+ const image = created.json().data
+ expect(image).toMatchObject({ name: 'screen.png', mime: 'image/png', size: PART + 10, width: 3, height: 2, parts: 2, complete: false })
+ await expect(run(tab, send([image.id]))).rejects.toMatchObject({ code: 'ATTACHMENT_INCOMPLETE' })
+ const part = (data: Buffer, index = 1) => http(owner, 'POST', `/api/super-tabs/${tab}/attachments/${image.id}/parts/${index}`, { data: data.toString('base64') })
+ expect((await part(bytes.subarray(PART, PART + 5))).json().error.code).toBe('INVALID_ATTACHMENT')
+ expect((await part(bytes.subarray(PART), 2)).json().error.code).toBe('INVALID_ATTACHMENT')
+ // Unsent, the upload is its uploader's alone, to read or to send.
+ expect((await http(peer, 'GET', `/api/super-tabs/${tab}/attachments/${image.id}`)).statusCode).toBe(404)
+ expect((await http(peer, 'POST', `/api/super-tabs/${tab}/attachments/${image.id}/parts/1`, { data: bytes.subarray(PART).toString('base64') })).statusCode).toBe(404)
+ expect((await part(bytes.subarray(PART))).json().data).toEqual({ id: image.id, complete: true })
+ expect((await part(bytes.subarray(PART))).json().data).toEqual({ id: image.id, complete: true })
+ await expect(run(tab, send([image.id]), peer)).rejects.toMatchObject({ code: 'INVALID_ATTACHMENT' })
+
+ const operationId = randomUUID()
+ const sent = await run(tab, send([image.id]), owner, undefined, operationId)
+ expect((await run(tab, send([image.id]), owner, undefined, operationId)).result).toEqual(sent.result)
+ await expect(run(tab, send([image.id], 'Again'))).rejects.toMatchObject({ code: 'INVALID_ATTACHMENT' })
+ const meta = { id: image.id, name: 'screen.png', mime: 'image/png', size: PART + 10, width: 3, height: 2, parts: 2 }
+ const [row] = (await store.messages(peer, tab, 'lead', { messageId: sent.result.messageId as string })).messages
+ expect(row).toMatchObject({ text: '[image]', attachments: [meta] })
+ expect(JSON.stringify(row)).not.toContain(bytes.subarray(0, 64).toString('base64'))
+
+ // Sent, it is read with its conversation: a member, and the agent the message was delivered to.
+ const read = async (user: AuthUser, index: number, asAgentId?: string) => {
+ const response = await http(user, 'GET', `/api/super-tabs/${tab}/attachments/${image.id}/parts/${index}${asAgentId ? `?asAgentId=${asAgentId}` : ''}`)
+ return response.statusCode === 200 ? Buffer.from(response.json().data.data, 'base64') : response.statusCode
+ }
+ expect(Buffer.concat([await read(peer, 0) as Buffer, await read(host, 1, lead) as Buffer]).equals(bytes)).toBe(true)
+ expect(await read(peer, 2)).toBe(404)
+ expect((await http(peer, 'GET', `/api/super-tabs/${tab}/attachments/${image.id}`)).json().data).toEqual({ ...meta, complete: true })
+ const delivery = (await store.deliveries(host, tab, lead))[0]!
+ const claimed = await store.delivery(host, tab, lead, delivery.id, { type: 'claim', claimId: 'claim' })
+ expect(claimed.message).toMatchObject({ id: sent.result.messageId, attachments: [meta] })
+
+ // Another tab cannot name it, and leaving the tab ends access.
+ const other = (await store.create(owner, randomUUID(), 'Other')).id
+ await expect(run(other, send([image.id]))).rejects.toMatchObject({ code: 'INVALID_ATTACHMENT' })
+ expect((await http(owner, 'GET', `/api/super-tabs/${other}/attachments/${image.id}`)).statusCode).toBe(404)
+ await run(tab, { type: 'member.remove', userId: peer.sub }, peer)
+ expect(await read(peer, 0)).toBe(403)
+ })
+
+ it('takes only PNG, JPEG and WebP within 5 MB, and keeps an image out of a private project it was not sent to', async () => {
+ const { tab } = await fixture()
+ expect((await upload(owner, tab, Buffer.from('GIF89a-and-more'), 'cat.png')).json().error.code).toBe('UNSUPPORTED_ATTACHMENT')
+ const tooLarge = await http(owner, 'POST', `/api/super-tabs/${tab}/attachments`, { name: 'big.png', size: 5 * 1024 * 1024 + 1, data: png(PART).toString('base64') })
+ expect(tooLarge.statusCode).toBe(400)
+ const short = await http(owner, 'POST', `/api/super-tabs/${tab}/attachments`, { name: 'short.png', size: 100, data: png(50).toString('base64') })
+ expect(short.json().error.code).toBe('INVALID_ATTACHMENT')
+ const { conversationId } = (await run(tab, { type: 'project.create', name: 'Private', visibility: 'private', brief: '' })).result as { conversationId: string }
+ const image = (await upload(owner, tab, png(100))).json().data
+ expect(image.complete).toBe(true)
+ await run(tab, { ...send([image.id], 'For the private project'), conversationId } as Command)
+ await invite(tab)
+ expect((await http(peer, 'GET', `/api/super-tabs/${tab}/attachments/${image.id}/parts/0`)).statusCode).toBe(404)
+ expect((await http(owner, 'GET', `/api/super-tabs/${tab}/attachments/${image.id}/parts/0`)).statusCode).toBe(200)
+ expect((await upload(peer, tab, png(100))).json().data.complete).toBe(true)
+ })
+
+ it('lets the uploader resume or delete an unsent image, and prunes unfinished uploads after an hour', async () => {
+ const { tab } = await fixture()
+ await invite(tab)
+ const bytes = png(2 * PART + 5)
+ const image = (await upload(owner, tab, bytes)).json().data
+ const meta = async (user = owner) => (await http(user, 'GET', `/api/super-tabs/${tab}/attachments/${image.id}`)).json()
+ expect((await meta()).data).toMatchObject({ parts: 3, complete: false, missing: [1, 2] })
+ await http(owner, 'POST', `/api/super-tabs/${tab}/attachments/${image.id}/parts/2`, { data: bytes.subarray(2 * PART).toString('base64') })
+ expect((await meta()).data.missing).toEqual([1])
+ const remove = (user: AuthUser, id = image.id) => http(user, 'DELETE', `/api/super-tabs/${tab}/attachments/${id}`)
+ expect((await remove(peer)).statusCode).toBe(404)
+ expect((await remove(owner)).json().data).toEqual({ id: image.id, deleted: true })
+ expect((await meta()).error.code).toBe('NOT_FOUND')
+ expect(await db.superTabAttachmentPart.count({ where: { attachmentId: image.id } })).toBe(0)
+ const sent = (await upload(owner, tab, png(100))).json().data
+ await run(tab, send([sent.id]))
+ expect((await remove(owner, sent.id)).json().error.code).toBe('ATTACHMENT_SENT')
+
+ const unfinished = (await upload(owner, tab, png(PART + 1))).json().data
+ const finished = (await upload(owner, tab, png(100))).json().data
+ await new SuperTabStore(db, () => Date.now() + 2 * 3_600_000).attachments.upload(owner, tab,
+ { name: 'later.png', size: 100, data: png(100).toString('base64') })
+ expect(await db.superTabAttachment.findUnique({ where: { id: unfinished.id } })).toBeNull()
+ expect(await db.superTabAttachment.findUnique({ where: { id: finished.id } })).not.toBeNull()
+ })
+
+ it('refuses an empty message and carries the images when a person resends an uncertain delivery', async () => {
+ const { tab, lead } = await fixture()
+ await expect(run(tab, message(' '))).rejects.toMatchObject({ code: 'EMPTY_MESSAGE' })
+ const image = (await upload(owner, tab, png(100))).json().data
+ await run(tab, send([image.id], 'Look at this'))
+ const first = (await store.deliveries(host, tab, lead))[0]!
+ await store.delivery(host, tab, lead, first.id, { type: 'claim', claimId: 'claim' })
+ await store.delivery(host, tab, lead, first.id, { type: 'ack', claimId: 'claim', receipt: 'lost', uncertain: true })
+ await run(tab, { type: 'delivery.resolve', deliveryId: first.id, resolution: 'resend' })
+ const rows = (await store.messages(owner, tab, 'lead', {})).messages
+ expect(rows.at(-1)).toMatchObject({ text: 'Look at this', replyTo: rows.at(-2)!.id, attachments: [expect.objectContaining({ id: image.id })] })
+ })
+})
diff --git a/backend/prisma/schema.prisma b/backend/prisma/schema.prisma
index 7bbb0e07d..debb2f711 100644
--- a/backend/prisma/schema.prisma
+++ b/backend/prisma/schema.prisma
@@ -1019,11 +1019,44 @@ model SuperTabMessage {
text String
replyTo String?
recipientIds String[]
+ /// Metadata of the images sent with it (superTabs/attachments.ts); never their bytes.
+ attachments Json?
createdAt DateTime @default(now())
@@index([tabId, conversationId, sequence])
}
+/// An image a member attached to a Super Tab message (superTabs/attachments.ts). Until it is sent only its
+/// uploader can read it; after that, whoever can read the message's conversation. The bytes are in parts.
+model SuperTabAttachment {
+ id String @id @map("_id")
+ tabId String
+ actorKey String
+ conversationId String?
+ messageId String?
+ name String
+ mime String
+ size Int
+ width Int?
+ height Int?
+ parts Int
+ complete Boolean @default(false)
+ createdAt DateTime @default(now())
+
+ @@index([tabId, actorKey, messageId, createdAt])
+}
+
+/// One part of an attachment's bytes. Parts keep every upload and read small enough for the machine relay
+/// the apps reach the backend through.
+model SuperTabAttachmentPart {
+ id String @id @map("_id")
+ attachmentId String
+ index Int
+ data Bytes
+
+ @@unique([attachmentId, index])
+}
+
model SuperTabOperation {
id String @id @map("_id")
tabId String
diff --git a/backend/src/routes/superTabs.ts b/backend/src/routes/superTabs.ts
index 7caa01042..76aa120dc 100644
--- a/backend/src/routes/superTabs.ts
+++ b/backend/src/routes/superTabs.ts
@@ -11,6 +11,7 @@ import { nativeEventSchema, openNativeSchema } from '../superTabs/native.js'
import { machineObservationSchema } from '../superTabs/machines.js'
import { joinSwarmSchema, previewJoinSchema, saveSharingSchema } from '../superTabs/sharing.js'
import { holdReason } from '../superTabs/holdNotice.js'
+import { ATTACHMENT_BODY_LIMIT, attachmentPartSchema, uploadAttachmentSchema } from '../superTabs/attachments.js'
const id = z.string().min(1).max(160).regex(/^[A-Za-z0-9_-]+$/)
const tabParams = z.object({ tabId: id })
@@ -25,6 +26,8 @@ const messageQuery = agentQuery.extend({ after: z.coerce.number().int().nonnegat
before: z.coerce.number().int().nonnegative().safe().optional(), messageId: id.optional() })
.refine(q => [q.after, q.before, q.messageId].filter(value => value !== undefined).length <= 1, 'Choose one message cursor or exact message.')
const decisionParams = tabParams.extend({ decisionId: id })
+const attachmentParams = tabParams.extend({ attachmentId: id })
+const partParams = attachmentParams.extend({ index: z.coerce.number().int().min(0).max(63) })
const hostParams = z.object({ machineId: id })
const hostStartParams = hostParams.extend({ tabId: id, startId: id })
const machineParams = hostParams.extend({ tabId: id })
@@ -128,6 +131,22 @@ export async function superTabRoutes(app: FastifyInstance, options: { store?: Su
app.get<{ Params: z.infer<typeof deliveryActionParams> }>('/api/super-tabs/:tabId/agents/:agentId/deliveries/:deliveryId',
{ preHandler: validateParams(deliveryActionParams) },
(req, reply) => respond(reply, () => store.deliveryReceipt(req.user!, req.params.tabId, req.params.agentId, req.params.deliveryId)))
+ // Images travel in parts (attachments.ts `ATTACHMENT_PART_BYTES`); each request carries at most one part as base64.
+ app.post<{ Params: z.infer<typeof tabParams>; Querystring: z.infer<typeof agentQuery>; Body: z.infer<typeof uploadAttachmentSchema> }>('/api/super-tabs/:tabId/attachments',
+ { bodyLimit: ATTACHMENT_BODY_LIMIT, preHandler: [validateParams(tabParams), validateQuery(agentQuery), validateBody(uploadAttachmentSchema)] },
+ (req, reply) => respond(reply, () => store.attachments.upload(req.user!, req.params.tabId, req.body, req.query.asAgentId)))
+ app.get<{ Params: z.infer<typeof attachmentParams>; Querystring: z.infer<typeof agentQuery> }>('/api/super-tabs/:tabId/attachments/:attachmentId',
+ { preHandler: [validateParams(attachmentParams), validateQuery(agentQuery)] },
+ (req, reply) => respond(reply, () => store.attachments.read(req.user!, req.params.tabId, req.params.attachmentId, req.query.asAgentId)))
+ app.delete<{ Params: z.infer<typeof attachmentParams>; Querystring: z.infer<typeof agentQuery> }>('/api/super-tabs/:tabId/attachments/:attachmentId',
+ { preHandler: [validateParams(attachmentParams), validateQuery(agentQuery)] },
+ (req, reply) => respond(reply, () => store.attachments.remove(req.user!, req.params.tabId, req.params.attachmentId, req.query.asAgentId)))
+ app.post<{ Params: z.infer<typeof partParams>; Querystring: z.infer<typeof agentQuery>; Body: z.infer<typeof attachmentPartSchema> }>('/api/super-tabs/:tabId/attachments/:attachmentId/parts/:index',
+ { bodyLimit: ATTACHMENT_BODY_LIMIT, preHandler: [validateParams(partParams), validateQuery(agentQuery), validateBody(attachmentPartSchema)] },
+ (req, reply) => respond(reply, () => store.attachments.uploadPart(req.user!, req.params.tabId, req.params.attachmentId, req.params.index, req.body, req.query.asAgentId)))
+ app.get<{ Params: z.infer<typeof partParams>; Querystring: z.infer<typeof agentQuery> }>('/api/super-tabs/:tabId/attachments/:attachmentId/parts/:index',
+ { preHandler: [validateParams(partParams), validateQuery(agentQuery)] },
+ (req, reply) => respond(reply, () => store.attachments.readPart(req.user!, req.params.tabId, req.params.attachmentId, req.params.index, req.query.asAgentId)))
app.post<{ Params: z.infer<typeof tabParams>; Body: z.infer<typeof stop> }>('/api/super-tabs/:tabId/stopped',
{ preHandler: [validateParams(tabParams), validateBody(stop)] },
(req, reply) => respond(reply, () => store.stopped(req.user!, req.params.tabId, req.body.assignmentId, req.body.receipt)))
diff --git a/backend/src/superTabs/attachments.test.ts b/backend/src/superTabs/attachments.test.ts
new file mode 100644
index 000000000..46d643abd
--- /dev/null
+++ b/backend/src/superTabs/attachments.test.ts
@@ -0,0 +1,27 @@
+import { describe, expect, it } from 'vitest'
+import { imageInfo } from './attachments.js'
+
+const bytes = (...parts: Array<number[] | string>) => Uint8Array.from(parts.flatMap(p => typeof p === 'string' ? [...p].map(c => c.charCodeAt(0)) : p))
+const be32 = (n: number) => [n >>> 24, (n >> 16) & 0xff, (n >> 8) & 0xff, n & 0xff]
+
+describe('Super Tab image attachments', () => {
+ it('reads the type and size of PNG, JPEG and WebP from their own headers', () => {
+ expect(imageInfo(bytes([0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a], be32(13), 'IHDR', be32(640), be32(480))))
+ .toEqual({ mime: 'image/png', width: 640, height: 480 })
+ // SOI, an APP0 segment to skip, then a baseline frame header: height 300, width 400.
+ expect(imageInfo(bytes([0xff, 0xd8, 0xff, 0xe0, 0x00, 0x04, 0x00, 0x00, 0xff, 0xc0, 0x00, 0x11, 0x08, 0x01, 0x2c, 0x01, 0x90, 0x03, 0, 0, 0])))
+ .toEqual({ mime: 'image/jpeg', width: 400, height: 300 })
+ expect(imageInfo(bytes([0xff, 0xd8, 0xff, 0xdb]))).toEqual({ mime: 'image/jpeg', width: null, height: null })
+ const riff = (chunk: string, body: number[]) => bytes('RIFF', [0, 0, 0, 0], 'WEBP', chunk, [0, 0, 0, 0], body)
+ expect(imageInfo(riff('VP8X', [0, 0, 0, 0, 0x1f, 0x03, 0x00, 0xdf, 0x01, 0x00]))).toEqual({ mime: 'image/webp', width: 800, height: 480 })
+ expect(imageInfo(riff('VP8 ', [0, 0, 0, 0x9d, 0x01, 0x2a, 0x20, 0x03, 0xe0, 0x01]))).toEqual({ mime: 'image/webp', width: 800, height: 480 })
+ expect(imageInfo(riff('VP8L', [0x2f, 0x1f, 0xc3, 0x77, 0x00]))).toEqual({ mime: 'image/webp', width: 800, height: 480 })
+ })
+
+ it('refuses anything else, whatever it is called', () => {
+ expect(imageInfo(bytes('GIF89a'))).toBeNull()
+ expect(imageInfo(bytes('BM'))).toBeNull()
+ expect(imageInfo(bytes('<svg xmlns="http://www.w3.org/2000/svg"/>'))).toBeNull()
+ expect(imageInfo(new Uint8Array())).toBeNull()
+ })
+})
diff --git a/backend/src/superTabs/attachments.ts b/backend/src/superTabs/attachments.ts
new file mode 100644
index 000000000..ef3f42d33
--- /dev/null
+++ b/backend/src/superTabs/attachments.ts
@@ -0,0 +1,210 @@
+import { randomBytes } from 'node:crypto'
+import type { Prisma, SuperTab, SuperTabAttachment } from '@prisma/client'
+import { z } from 'zod'
+import type { AuthUser } from '../lib/ssoAuth.js'
+import { actorKey, author, fail, stableId, type Actor, type AttachmentMeta, type SuperTabState } from './model.js'
+import { readConversation } from './projects.js'
+
+export const ATTACHMENT_MAX_BYTES = 5 * 1024 * 1024
+export const ATTACHMENTS_PER_MESSAGE = 4
+/** The apps reach this backend through a machine's relay (cli/src/superTabs/service.ts `backend`), and a browser's relay
+ * frame is 1 MiB (wsServer.ts `WS_LIMITS.web`) before E2EE sealing grows it. One 256 KiB part is about 342 KB of base64,
+ * so a 5 MB image travels as up to 20 small requests instead of one that no relay carries. */
+export const ATTACHMENT_PART_BYTES = 256 * 1024
+const PART_CHARS = Math.ceil(ATTACHMENT_PART_BYTES / 3) * 4
+export const ATTACHMENT_BODY_LIMIT = PART_CHARS + 4096
+/** Uploads never sent are drafts someone abandoned: an unfinished one goes after an hour, a finished one after a day,
+ * and one person keeps at most this many. The app deletes its own leftovers at once (`remove`); these bound the rest. */
+const UNSENT_LIMIT = 24
+const UNSENT_MS = 86_400_000
+const INCOMPLETE_MS = 3_600_000
+
+const id = z.string().min(1).max(160).regex(/^[A-Za-z0-9_-]+$/)
+const data = z.string().min(1).max(PART_CHARS).regex(/^[A-Za-z0-9+/]+={0,2}$/, 'Send the bytes as base64.')
+export const uploadAttachmentSchema = z.object({
+ name: z.string().trim().min(1).max(200).refine(value => !/[\x00-\x1f\x7f]/.test(value)),
+ size: z.number().int().min(1).max(ATTACHMENT_MAX_BYTES),
+ data,
+}).strict()
+export const attachmentPartSchema = z.object({ data }).strict()
+export const attachmentIdsSchema = z.array(id).min(1).max(ATTACHMENTS_PER_MESSAGE)
+
+type Transaction = Prisma.TransactionClient
+type ImageInfo = { mime: 'image/png' | 'image/jpeg' | 'image/webp'; width: number | null; height: number | null }
+interface Deps {
+ transaction<T>(body: (tx: Transaction) => Promise<T>): Promise<T>
+ row(tx: Transaction, user: AuthUser, tabId: string): Promise<{ row: SuperTab; state: SuperTabState }>
+ actor(tx: Transaction, user: AuthUser, state: SuperTabState, asAgentId?: string): Promise<Actor>
+ now(): number
+}
+
+const u16le = (bytes: Uint8Array, i: number) => (bytes[i] ?? 0) | ((bytes[i + 1] ?? 0) << 8)
+
+/** The type the bytes are, read from their own header: a name or a client's word is not trusted. Width and height
+ * come along when the header holds them; a JPEG whose frame header is past the first part has none. */
+export function imageInfo(bytes: Uint8Array): ImageInfo | null {
+ const at = (i: number) => bytes[i] ?? 0
+ const u16 = (i: number) => (at(i) << 8) | at(i + 1)
+ const u32 = (i: number) => ((at(i) << 24) >>> 0) + (at(i + 1) << 16) + (at(i + 2) << 8) + at(i + 3)
+ const le24 = (i: number) => at(i) | (at(i + 1) << 8) | (at(i + 2) << 16)
+ const ascii = (i: number, text: string) => [...text].every((c, n) => at(i + n) === c.charCodeAt(0))
+ if (bytes.length >= 8 && [0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a].every((b, i) => at(i) === b)) {
+ return ascii(12, 'IHDR') && bytes.length >= 24 ? { mime: 'image/png', width: u32(16), height: u32(20) } : { mime: 'image/png', width: null, height: null }
+ }
+ if (bytes.length >= 3 && at(0) === 0xff && at(1) === 0xd8 && at(2) === 0xff) {
+ for (let i = 2; i + 9 < bytes.length;) {
+ if (at(i) !== 0xff) break
+ const marker = at(i + 1)
+ if (marker === 0xff) { i++; continue }
+ if (marker >= 0xc0 && marker <= 0xcf && ![0xc4, 0xc8, 0xcc].includes(marker)) return { mime: 'image/jpeg', width: u16(i + 7), height: u16(i + 5) }
+ if (marker === 0x01 || (marker >= 0xd0 && marker <= 0xd9)) { i += 2; continue }
+ i += 2 + u16(i + 2)
+ }
+ return { mime: 'image/jpeg', width: null, height: null }
+ }
+ if (bytes.length >= 16 && ascii(0, 'RIFF') && ascii(8, 'WEBP')) {
+ if (ascii(12, 'VP8 ') && bytes.length >= 30) return { mime: 'image/webp', width: u16le(bytes, 26) & 0x3fff, height: u16le(bytes, 28) & 0x3fff }
+ if (ascii(12, 'VP8L') && bytes.length >= 25) {
+ const [b0, b1, b2, b3] = [at(21), at(22), at(23), at(24)]
+ return { mime: 'image/webp', width: 1 + (((b1 & 0x3f) << 8) | b0), height: 1 + (((b3 & 0x0f) << 10) | (b2 << 2) | ((b1 & 0xc0) >> 6)) }
+ }
+ if (ascii(12, 'VP8X') && bytes.length >= 30) return { mime: 'image/webp', width: 1 + le24(24), height: 1 + le24(27) }
+ return { mime: 'image/webp', width: null, height: null }
+ }
+ return null
+}
+const partId = (attachmentId: string, index: number) => stableId('attachment-part', attachmentId, String(index))
+const partBytes = (record: SuperTabAttachment, index: number) =>
+ index === record.parts - 1 ? record.size - ATTACHMENT_PART_BYTES * (record.parts - 1) : ATTACHMENT_PART_BYTES
+export const attachmentMeta = (record: SuperTabAttachment): AttachmentMeta => ({ id: record.id, name: record.name, mime: record.mime,
+ size: record.size, width: record.width ?? null, height: record.height ?? null, parts: record.parts })
+
+/** What a message.send names, checked in its transaction: the sender's own finished uploads in this tab, each unsent.
+ * An id from another tab, another person or an earlier message is refused rather than shared. */
+export async function attachmentsForSend(tx: Transaction, tabId: string, actor: Actor, ids: string[]): Promise<AttachmentMeta[]> {
+ if (new Set(ids).size !== ids.length) fail('INVALID_ATTACHMENT', 'Attach each image once.', 400)
+ const rows = await tx.superTabAttachment.findMany({ where: { id: { in: ids }, tabId } })
+ return ids.map(attachmentId => {
+ const record = rows.find(r => r.id === attachmentId)
+ if (!record || record.actorKey !== actorKey(actor) || record.messageId) fail('INVALID_ATTACHMENT', 'This image is no longer available. Attach it again.', 400)
+ if (!record.complete) fail('ATTACHMENT_INCOMPLETE', 'Wait for the image to finish uploading.')
+ return attachmentMeta(record)
+ })
+}
+
+/** Sent, an attachment is read with its message: whoever can read that conversation. */
+export async function attachToMessage(tx: Transaction, tabId: string, ids: string[], conversationId: string, messageId: string) {
+ const { count } = await tx.superTabAttachment.updateMany({ where: { id: { in: ids }, tabId, messageId: null }, data: { messageId, conversationId } })
+ // attachmentsForSend read them unsent in this transaction; anything else is a concurrent send, which must not commit.
+ if (count !== ids.length) fail('INVALID_ATTACHMENT', 'This image is no longer available. Attach it again.', 400)
+}
+
+/** The text stored for a message of images alone, so a client that shows no images still shows something. Clients
+ * that draw the images hide it (desktop model.dart `SuperTabMessage.shownText`). */
+export const imagesPlaceholder = (count: number) => count === 1 ? '[image]' : `[${count} images]`
+
+/** Images people attach to messages. Bytes never ride a message read; they are read part by part here. */
+export class SuperTabAttachmentStore {
+ constructor(private readonly deps: Deps) {}
+
+ private async writer(tx: Transaction, user: AuthUser, tabId: string, asAgentId?: string) {
+ const { state } = await this.deps.row(tx, user, tabId)
+ const actor = await this.deps.actor(tx, user, state, asAgentId)
+ author(state, actor, true)
+ return actor
+ }
+
+ /** Before it is sent only its uploader sees an attachment; after, whoever can read its conversation. Both fail alike. */
+ private async readable(tx: Transaction, user: AuthUser, tabId: string, attachmentId: string, asAgentId?: string) {
+ const { state } = await this.deps.row(tx, user, tabId)
+ const actor = await this.deps.actor(tx, user, state, asAgentId)
+ author(state, actor)
+ const record = await tx.superTabAttachment.findFirst({ where: { id: attachmentId, tabId } })
+ if (record?.conversationId) readConversation(state, actor, record.conversationId)
+ else if (!record || record.actorKey !== actorKey(actor)) fail('NOT_FOUND', 'This image is unavailable.', 404)
+ return record!
+ }
+
+ /** Creates the attachment with its first part, which carries the header that proves the image's type. */
+ async upload(user: AuthUser, tabId: string, input: z.infer<typeof uploadAttachmentSchema>, asAgentId?: string) {
+ const request = uploadAttachmentSchema.parse(input)
+ const first = Buffer.from(request.data, 'base64')
+ const parts = Math.ceil(request.size / ATTACHMENT_PART_BYTES)
+ if (first.length !== Math.min(request.size, ATTACHMENT_PART_BYTES)) fail('INVALID_ATTACHMENT', 'The image arrived incomplete. Attach it again.', 400)
+ const info = imageInfo(first) ?? fail('UNSUPPORTED_ATTACHMENT', 'Attach a PNG, JPEG, or WebP image.', 400)
+ return this.deps.transaction(async tx => {
+ const actor = await this.writer(tx, user, tabId, asAgentId)
+ const key = actorKey(actor)
+ const stale = await tx.superTabAttachment.findMany({ where: { tabId, actorKey: key, messageId: null, OR: [
+ { createdAt: { lt: new Date(this.deps.now() - UNSENT_MS) } },
+ { complete: false, createdAt: { lt: new Date(this.deps.now() - INCOMPLETE_MS) } },
+ ] }, select: { id: true }, take: 100 })
+ if (stale.length) {
+ await tx.superTabAttachmentPart.deleteMany({ where: { attachmentId: { in: stale.map(s => s.id) } } })
+ await tx.superTabAttachment.deleteMany({ where: { id: { in: stale.map(s => s.id) } } })
+ }
+ if (await tx.superTabAttachment.count({ where: { tabId, actorKey: key, messageId: null } }) >= UNSENT_LIMIT) {
+ fail('ATTACHMENT_LIMIT', 'Too many images are waiting to be sent. Send or remove the ones in your messages, or try again in an hour.', 429)
+ }
+ const attachmentId = randomBytes(12).toString('hex')
+ // Unsent is an explicit null: MongoDB's `messageId: null` filter does not match a field that was never written.
+ const record = await tx.superTabAttachment.create({ data: { id: attachmentId, tabId, actorKey: key, conversationId: null, messageId: null,
+ name: request.name, mime: info.mime, size: request.size, width: info.width, height: info.height, parts, complete: parts === 1 } })
+ await tx.superTabAttachmentPart.create({ data: { id: partId(attachmentId, 0), attachmentId, index: 0, data: first } })
+ return { ...attachmentMeta(record), complete: record.complete }
+ })
+ }
+
+ /** Repeating a part replaces it, so a retry after a lost reply is safe. A finished attachment no longer changes. */
+ async uploadPart(user: AuthUser, tabId: string, attachmentId: string, index: number, input: z.infer<typeof attachmentPartSchema>, asAgentId?: string) {
+ const bytes = Buffer.from(attachmentPartSchema.parse(input).data, 'base64')
+ return this.deps.transaction(async tx => {
+ const actor = await this.writer(tx, user, tabId, asAgentId)
+ const record = await tx.superTabAttachment.findFirst({ where: { id: attachmentId, tabId } })
+ if (!record || record.actorKey !== actorKey(actor)) fail('NOT_FOUND', 'This image is unavailable.', 404)
+ if (record.complete) return { id: record.id, complete: true }
+ if (index < 1 || index >= record.parts || bytes.length !== partBytes(record, index)) {
+ fail('INVALID_ATTACHMENT', 'The image arrived incomplete. Attach it again.', 400)
+ }
+ await tx.superTabAttachmentPart.upsert({ where: { attachmentId_index: { attachmentId, index } },
+ create: { id: partId(attachmentId, index), attachmentId, index, data: bytes }, update: { data: bytes } })
+ const complete = await tx.superTabAttachmentPart.count({ where: { attachmentId } }) === record.parts
+ // Always written: two final parts in parallel then conflict on this document and one retries, seeing both parts.
+ await tx.superTabAttachment.update({ where: { id: attachmentId }, data: { complete } })
+ return { id: record.id, complete }
+ })
+ }
+
+ /** Its uploader takes back an image not yet sent: removed from the composer, replaced, or left over from a failed send. */
+ async remove(user: AuthUser, tabId: string, attachmentId: string, asAgentId?: string) {
+ return this.deps.transaction(async tx => {
+ const actor = await this.writer(tx, user, tabId, asAgentId)
+ const record = await tx.superTabAttachment.findFirst({ where: { id: attachmentId, tabId } })
+ if (!record || record.actorKey !== actorKey(actor)) fail('NOT_FOUND', 'This image is unavailable.', 404)
+ if (record.messageId) fail('ATTACHMENT_SENT', 'This image was already sent.')
+ await tx.superTabAttachmentPart.deleteMany({ where: { attachmentId } })
+ await tx.superTabAttachment.delete({ where: { id: attachmentId } })
+ return { id: attachmentId, deleted: true }
+ })
+ }
+
+ async read(user: AuthUser, tabId: string, attachmentId: string, asAgentId?: string) {
+ return this.deps.transaction(async tx => {
+ const record = await this.readable(tx, user, tabId, attachmentId, asAgentId)
+ // An unfinished upload is its uploader's alone: which parts it still needs lets an interrupted upload resume.
+ const missing = record.complete ? [] : await tx.superTabAttachmentPart.findMany({ where: { attachmentId }, select: { index: true } })
+ .then(have => Array.from({ length: record.parts }, (_, i) => i).filter(i => !have.some(p => p.index === i)))
+ return { ...attachmentMeta(record), complete: record.complete, ...(record.complete ? {} : { missing }) }
+ })
+ }
+
+ /** One part's bytes, base64 in the JSON reply like every relayed answer. */
+ async readPart(user: AuthUser, tabId: string, attachmentId: string, index: number, asAgentId?: string) {
+ return this.deps.transaction(async tx => {
+ const record = await this.readable(tx, user, tabId, attachmentId, asAgentId)
+ const part = await tx.superTabAttachmentPart.findUnique({ where: { attachmentId_index: { attachmentId, index } } })
+ if (!part || part.index >= record.parts) fail('NOT_FOUND', 'This part of the image is unavailable.', 404)
+ return { id: record.id, index, parts: record.parts, data: Buffer.from(part.data).toString('base64') }
+ })
+ }
+}
diff --git a/backend/src/superTabs/commands.test.ts b/backend/src/superTabs/commands.test.ts
index a61923dc5..c40e3767c 100644
--- a/backend/src/superTabs/commands.test.ts
+++ b/backend/src/superTabs/commands.test.ts
@@ -96,6 +96,23 @@ describe('Super Tab collaboration policy', () => {
{ reply: { id: posted.id, conversationId: 'elsewhere', author: posted.author } })).toThrow('Reply to a message in this conversation')
})
+ it('sends images the store checked, with or without text, and refuses a message with neither', () => {
+ const f = fixture()
+ const lead = f.add('lead', 'owner', 'lead', true)
+ const image = { id: 'img1', name: 'screen.png', mime: 'image/png', size: 10, width: 2, height: 1, parts: 1 }
+ const send = (text: string, attachmentIds?: string[]): Command =>
+ ({ type: 'message.send', conversationId: 'lead', text, replyTo: null, recipientIds: [], ...(attachmentIds ? { attachmentIds } : {}) })
+ const only = f.run(send('', ['img1']), owner, { attachments: [image] }).messages[0]!
+ expect(only).toMatchObject({ text: '[image]', recipients: [lead], attachments: [image] })
+ expect(f.run(send('', ['img1', 'img2']), owner, { attachments: [image, { ...image, id: 'img2' }] }).messages[0]!.text).toBe('[2 images]')
+ expect(f.run(send('Plain text')).messages[0]!).not.toHaveProperty('attachments')
+ expect(() => f.run(send(''))).toThrow('Write a message or attach an image')
+ expect(() => f.run(send('Hi', ['img1']))).toThrow('no longer available')
+ expect(() => f.run(send('Hi', ['img2']), owner, { attachments: [image] })).toThrow('no longer available')
+ expect(commandSchema.safeParse(send('Five', ['a', 'b', 'c', 'd', 'e'])).success).toBe(false)
+ expect(commandSchema.safeParse(send('Old client')).success).toBe(true)
+ })
+
it('lets a viewer read and leave, but not send, assign, attach or invite', () => {
const f = fixture()
f.invite('viewer')
diff --git a/backend/src/superTabs/commands.ts b/backend/src/superTabs/commands.ts
index 813cf2ba7..e2f33353a 100644
--- a/backend/src/superTabs/commands.ts
+++ b/backend/src/superTabs/commands.ts
@@ -2,8 +2,9 @@ import { admitMachineStart, machineContribution } from './machines.js'
import { z } from 'zod'
import {
activeWork, actorKey, agent, author, conversation, fail, person, stableId, numberConversations, nextConversationNumber,
- type Actor, type Agent, type Author, type CommandEffects, type SuperTabState,
+ type Actor, type Agent, type AttachmentMeta, type Author, type CommandEffects, type SuperTabState,
} from './model.js'
+import { attachmentIdsSchema, imagesPlaceholder } from './attachments.js'
import { routeRecordSchema, routeTitle, startedAs, type RouteCandidate, type RouteDecision, type RouteFinal, type RouteOverride } from './routeRecord.js'
import { routingOverrideSchema } from './routingPolicy.js'
import { agentProjectId, deleteProject, groupProject, manageProject, mutableProjects, projectMembers, projectOf, readAgent, readConversation, readProject, sameProject } from './projects.js'
@@ -70,7 +71,9 @@ export const commandSchema = z.discriminatedUnion('type', [
z.object({ type: z.literal('invite.revoke'), inviteId: id }).strict(),
z.object({ type: z.literal('invite.accept'), inviteId: id }).strict(),
z.object({ type: z.literal('member.remove'), userId: id }).strict(),
- z.object({ type: z.literal('message.send'), conversationId: id, text, replyTo: id.nullable(), recipientIds: z.array(id).max(16) }).strict(),
+ // Text may be empty when the message carries an image; applyCommand refuses a message with neither.
+ z.object({ type: z.literal('message.send'), conversationId: id, text: z.string().trim().max(32_000), replyTo: id.nullable(),
+ recipientIds: z.array(id).max(16), attachmentIds: attachmentIdsSchema.optional() }).strict(),
z.object({ type: z.literal('delivery.resolve'), deliveryId: id, resolution: z.enum(['received', 'resend', 'cancel']) }).strict(),
z.object({ type: z.literal('work.define'), conversationId: id, brief: text, checks: z.array(check).min(1).max(40) }).strict(),
z.object({ type: z.literal('work.assign'), conversationId: id, agentId: id, routeDecisionId: id.optional(), overrideReason: reason.optional() }).strict(),
@@ -94,7 +97,9 @@ export interface CommandContext {
/** A host's receipt, not an elapsed lease, proves that an assignment stopped. */
confirmedStopped?: boolean
/** An uncertain receipt and its original message, read transactionally. */
- delivery?: { id: string; conversationId: string; agentId: string; messageId: string; text: string }
+ delivery?: { id: string; conversationId: string; agentId: string; messageId: string; text: string; attachments?: AttachmentMeta[] }
+ /** The images a message.send names, checked by the store (attachments.ts `attachmentsForSend`). */
+ attachments?: AttachmentMeta[]
/** Route decisions this tab recorded in the last hour, counted by the store. */
recentRoutes?: number
/** The decision a command names, read from SuperTabRouteDecision by the store. */
@@ -169,8 +174,10 @@ export function applyCommand(original: SuperTabState, actor: Actor, input: Comma
if (group.assignment) effects.previousAttempts.push(structuredClone({ conversationId: group.id,
brief: group.brief, checks: group.checks, assignment: group.assignment }))
}
- const message = (conversationId: string, body: string, recipients: string[] = [], replyTo: string | null = null, source?: Record<string, unknown>) => {
- effects.messages.push({ id: operationId, conversationId, author: sender, text: body, replyTo, recipients, ...(source ? { source } : {}) })
+ const message = (conversationId: string, body: string, recipients: string[] = [], replyTo: string | null = null, source?: Record<string, unknown>,
+ attachments: AttachmentMeta[] = []) => {
+ effects.messages.push({ id: operationId, conversationId, author: sender, text: body, replyTo, recipients, ...(source ? { source } : {}),
+ ...(attachments.length ? { attachments } : {}) })
result.messageId = operationId
}
const openDecision = (): RouteDecision => {
@@ -541,8 +548,13 @@ export function applyCommand(original: SuperTabState, actor: Actor, input: Comma
agent(state, id)
if (!group.agentIds.includes(id)) fail('INVALID_RECIPIENT', 'Choose an agent in this conversation.', 400)
}
+ const attachments = command.attachmentIds?.length ? context.attachments ?? [] : []
+ if (attachments.length !== (command.attachmentIds?.length ?? 0) || attachments.some((a, i) => a.id !== command.attachmentIds![i])) {
+ fail('INVALID_ATTACHMENT', 'This image is no longer available. Attach it again.', 400)
+ }
+ if (!command.text && !attachments.length) fail('EMPTY_MESSAGE', 'Write a message or attach an image.', 400)
// The transcript still accepts a human message while the lead is unavailable. The UI can say why no delivery was created.
- message(group.id, command.text, recipients, command.replyTo)
+ message(group.id, command.text || imagesPlaceholder(attachments.length), recipients, command.replyTo, undefined, attachments)
break
}
case 'delivery.resolve': {
@@ -554,7 +566,7 @@ export function applyCommand(original: SuperTabState, actor: Actor, input: Comma
if (command.resolution === 'resend') {
open(state, group.id)
if (!group.agentIds.includes(target.id)) fail('INVALID_RECIPIENT', 'This agent is no longer in the conversation.', 400)
- message(group.id, delivery.text, [target.id], delivery.messageId)
+ message(group.id, delivery.text, [target.id], delivery.messageId, undefined, delivery.attachments ?? [])
} else {
message(group.id, command.resolution === 'received'
? `Checked ${target.name}’s terminal and confirmed the earlier instruction was received.`
diff --git a/backend/src/superTabs/model.ts b/backend/src/superTabs/model.ts
index 0f31a4554..548b2ef22 100644
--- a/backend/src/superTabs/model.ts
+++ b/backend/src/superTabs/model.ts
@@ -120,6 +120,8 @@ export type Actor =
| { kind: 'person'; userId: string; email: string }
| { kind: 'agent'; agentId: string; machineOwnerId: string }
export interface Author { kind: 'person' | 'agent'; id: string; name: string; membershipGeneration: string }
+/** What a message read carries about an attached image (attachments.ts); its bytes are read separately, part by part. */
+export interface AttachmentMeta { id: string; name: string; mime: string; size: number; width: number | null; height: number | null; parts: number }
export interface MessageDraft {
id: string
conversationId: string
@@ -127,6 +129,7 @@ export interface MessageDraft {
text: string
replyTo: string | null
recipients: string[]
+ attachments?: AttachmentMeta[]
/** Structured row kind for clients; `native` is written by native.ts, `route`/`route-override` by commands. */
source?: Record<string, unknown>
}
diff --git a/backend/src/superTabs/store.ts b/backend/src/superTabs/store.ts
index 3d19e8a17..58303232a 100644
--- a/backend/src/superTabs/store.ts
+++ b/backend/src/superTabs/store.ts
@@ -10,9 +10,10 @@ import { canReadAgent, canReadProject, groupProject, projectsOf, readConversatio
import { bindSession, makeProjectPrivate } from './sessionScope.js'
import { noteProjectReports, projectUpdateRequest } from './projectUpdates.js'
import { revokeNativeContexts, SuperTabNativeStore } from './native.js'
+import { attachmentsForSend, attachToMessage, SuperTabAttachmentStore } from './attachments.js'
import {
activeWork, actorKey, agent, author, conversation, createSuperTab, fail, person, stableId, visibleState,
- SuperTabError, type Actor, type Agent, type Assignment, type Author, type MessageDraft, type SuperTabState,
+ SuperTabError, type Actor, type Agent, type Assignment, type AttachmentMeta, type Author, type MessageDraft, type SuperTabState,
} from './model.js'
import { holdNoticeText, type HoldReason } from './holdNotice.js'
import { closeAssignment, readDecision, recentRoutes, timedDecisionOf, writeRouteEffects } from './routeDecisions.js'
@@ -47,6 +48,7 @@ async function transaction<T>(db: PrismaClient, body: (tx: Transaction) => Promi
/** Persistent coordination. Host adapters own execution and must confirm their local session grants. */
export class SuperTabStore {
readonly native: SuperTabNativeStore
+ readonly attachments: SuperTabAttachmentStore
constructor(private readonly db: PrismaClient, private readonly now: () => number = Date.now) {
this.native = new SuperTabNativeStore({
transaction: body => transaction(db, body),
@@ -54,6 +56,12 @@ export class SuperTabStore {
agentGrant: (tx, state, target) => this.agentGrant(tx, state, target),
contribution: (tx, state, actor, command) => this.contribution(tx, state, actor, command),
})
+ this.attachments = new SuperTabAttachmentStore({
+ transaction: body => transaction(db, body),
+ row: async (tx, user, tabId) => { const row = await this.row(tx, user, tabId); return { row, state: stateOf(row) } },
+ actor: (tx, user, state, asAgentId) => this.actor(tx, user, state, asAgentId),
+ now: () => this.now(),
+ })
}
private policyId(user: AuthUser) { return stableId('routing-policy', user.sub, user.autonomousEnv) }
@@ -348,7 +356,8 @@ export class SuperTabStore {
}
await this.agentGrant(tx, original, agent(original, delivery.agentId))
}
- context.delivery = { ...delivery, text: message.text }
+ // A resend carries the original's images with its text.
+ context.delivery = { ...delivery, text: message.text, attachments: (message.attachments ?? undefined) as AttachmentMeta[] | undefined }
await tx.superTabDelivery.update({ where: { id: delivery.id }, data: {
status: command.resolution === 'received' ? 'confirmed' : command.resolution === 'resend' ? 'superseded' : 'cancelled',
// The native receipt remains intact; the operation records the person's resolution.
@@ -362,6 +371,9 @@ export class SuperTabStore {
const start = original.starts?.find(s => s.id === command.startId) ?? fail('NOT_FOUND', 'This agent start is unavailable.', 404)
context.contribution = await this.contribution(tx, original, actor, start.request, true)
}
+ if (command.type === 'message.send' && command.attachmentIds?.length) {
+ context.attachments = await attachmentsForSend(tx, tabId, actor, command.attachmentIds)
+ }
if (command.type === 'message.send' && command.replyTo) {
const reply = await tx.superTabMessage.findFirst({ where: { id: command.replyTo, tabId, conversationId: command.conversationId } })
if (reply) context.reply = { id: reply.id, conversationId: reply.conversationId, author: reply.author as unknown as Author }
@@ -430,6 +442,9 @@ export class SuperTabStore {
await closeAssignment(tx, tabId, command.assignmentId, command.status, context.now)
}
await this.writeMessages(tx, tabId, effects.state, effects.messages, revision)
+ if (command.type === 'message.send' && command.attachmentIds?.length) {
+ await attachToMessage(tx, tabId, command.attachmentIds, command.conversationId, effects.result.messageId as string)
+ }
// On 2026-10-20 a Lead answered a message it had already read, then answered it again when the held
// delivery was finally typed. An agent's reply settles that agent's own deliveries of the message.
if (command.type === 'message.send' && command.replyTo && actor.kind === 'agent') {
@@ -468,6 +483,7 @@ export class SuperTabStore {
for (const message of messages) {
await tx.superTabMessage.create({ data: { id: message.id, tabId, conversationId: message.conversationId,
sequence: revision, author: json(message.author), ...(message.source ? { source: json(message.source) } : {}),
+ ...(message.attachments?.length ? { attachments: json(message.attachments) } : {}),
text: message.text, replyTo: message.replyTo, recipientIds: message.recipients } })
for (const recipient of message.recipients) {
const target = agent(state, recipient)
diff --git a/cli/src/superTabs/attachments.spec.ts b/cli/src/superTabs/attachments.spec.ts
new file mode 100644
index 000000000..f1794bf4d
--- /dev/null
+++ b/cli/src/superTabs/attachments.spec.ts
@@ -0,0 +1,19 @@
+import { readFileSync } from 'node:fs'
+import { expect, it } from 'vitest'
+import { attachmentsOf, saveAttachment } from './attachments.js'
+
+const image = { id: 'img1', name: 'a.png', mime: 'image/png', size: 3, parts: 1 }
+it('keeps only well-formed image rows within the backend limits', () => {
+ expect(attachmentsOf({ attachments: [image, { ...image, id: '../x' }, { ...image, mime: 'image/gif' }, { ...image, mime: 'toString' },
+ { ...image, size: 5 * 1024 * 1024 + 1 }, { ...image, parts: 0 }, { ...image, parts: 65 }, 'junk'] })).toEqual([image])
+ expect(attachmentsOf({ text: 'no images' })).toEqual([])
+ expect(attachmentsOf(null)).toEqual([])
+})
+it('refuses an image whose parts do not add up to its size', async () => {
+ const read = async () => ({ data: Buffer.from([1, 2]).toString('base64') })
+ await expect(saveAttachment(read, 'tab', 'agent', image)).rejects.toThrow('incomplete')
+ await expect(saveAttachment(async () => ({}), 'tab', 'agent', image)).rejects.toThrow('unreadable')
+ const path = await saveAttachment(async () => ({ data: Buffer.from([1, 2, 3]).toString('base64') }), 'tab', 'agent', { ...image, name: 'no extension' })
+ expect(path).toMatch(/-no-extension\.png$/)
+ expect([...readFileSync(path)]).toEqual([1, 2, 3])
+})
diff --git a/cli/src/superTabs/attachments.ts b/cli/src/superTabs/attachments.ts
new file mode 100644
index 000000000..54f54c7b3
--- /dev/null
+++ b/cli/src/superTabs/attachments.ts
@@ -0,0 +1,51 @@
+import { writePasteDropFile } from '../lib/pasteDropFiles.js'
+import { identifier, object } from './wire.js'
+
+/** What a message read carries about one attached image (backend superTabs/attachments.ts); never its bytes. */
+export interface SuperTabAttachment { id: string; name: string; mime: string; size: number; parts: number }
+
+const EXTENSIONS: Record<string, string> = { 'image/png': 'png', 'image/jpeg': 'jpg', 'image/webp': 'webp' }
+/** The backend's own limits: 5 MB an image, in 256 KiB parts. A row claiming more is refused before anything is read. */
+const MAX_BYTES = 5 * 1024 * 1024
+const MAX_PARTS = 64
+const PARALLEL_PARTS = 4
+
+/** The attachments of a message row; anything malformed is left out. */
+export function attachmentsOf(message: unknown): SuperTabAttachment[] {
+ const rows = object(message).attachments
+ if (!Array.isArray(rows)) return []
+ return rows.map(object).filter(a => identifier(a.id) && typeof a.name === 'string' && typeof a.mime === 'string' && Object.hasOwn(EXTENSIONS, a.mime)
+ && Number.isInteger(a.size) && (a.size as number) > 0 && (a.size as number) <= MAX_BYTES
+ && Number.isInteger(a.parts) && (a.parts as number) > 0 && (a.parts as number) <= MAX_PARTS)
+ .map(a => ({ id: a.id as string, name: a.name as string, mime: a.mime as string, size: a.size as number, parts: a.parts as number }))
+}
+
+/** The sender's name, with the extension its bytes really have: an agent opens the file by that. Spaces and other
+ * characters a shell or a prompt line would split on become dashes. */
+function fileName(attachment: SuperTabAttachment): string {
+ const dot = attachment.name.lastIndexOf('.')
+ const stem = (dot > 0 ? attachment.name.slice(0, dot) : attachment.name).replace(/[^\p{L}\p{N}._-]+/gu, '-').slice(0, 100) || 'image'
+ return `${stem}.${EXTENSIONS[attachment.mime]}`
+}
+
+/**
+ * Reads an image part by part, as the agent this machine runs, and saves it where pasted and dropped files go
+ * (lib/pasteDropFiles.ts, pruned after a day). Returns the file's absolute path for the agent to open.
+ */
+export async function saveAttachment(read: (path: string) => Promise<unknown>, tabId: string, agentId: string,
+ attachment: SuperTabAttachment): Promise<string> {
+ // Four parts at a time: a 5 MB image is 20 small requests, and one at a time made a delivery wait seconds.
+ const parts: Buffer[] = new Array(attachment.parts)
+ let next = 0
+ const worker = async () => {
+ for (let index = next++; index < attachment.parts; index = next++) {
+ const part = object(await read(`/api/super-tabs/${tabId}/attachments/${attachment.id}/parts/${index}?asAgentId=${agentId}`))
+ if (typeof part.data !== 'string') throw new Error('The image is unreadable.')
+ parts[index] = Buffer.from(part.data, 'base64')
+ }
+ }
+ await Promise.all(Array.from({ length: Math.min(PARALLEL_PARTS, attachment.parts) }, worker))
+ const bytes = Buffer.concat(parts)
+ if (bytes.length !== attachment.size) throw new Error('The image arrived incomplete.')
+ return writePasteDropFile(fileName(attachment), bytes)
+}
diff --git a/cli/src/superTabs/command.spec.ts b/cli/src/superTabs/command.spec.ts
index 5f2ca64e3..c350d39f7 100644
--- a/cli/src/superTabs/command.spec.ts
+++ b/cli/src/superTabs/command.spec.ts
@@ -7,6 +7,8 @@ it('keeps an explicit stable receipt for agent messages and arbitrary work comma
expect(parseSuperTabArgs([...prefix, 'command', 'op-2', '{"type":"work.assign"}'], where).payload).toMatchObject({ command: { type: 'work.assign' } })
expect(parseSuperTabArgs(['--port', '14002', '--machine', 'target', ...prefix, 'messages', 'lead'], where)).toMatchObject({ where: { port: 14002, machineId: 'target' }, payload: { conversationId: 'lead' } })
expect(parseSuperTabArgs(['help'], where).payload.action).toBe('help')
+ expect(parseSuperTabArgs([...prefix, 'attachment', 'img1'], where).payload).toMatchObject({ action: 'attachment', attachmentId: 'img1' })
+ expect(() => parseSuperTabArgs([...prefix, 'attachment', '../img'], where)).toThrow('attachment ATTACHMENT_ID')
expect(parseSuperTabArgs([...prefix, 'message', 'lead', 'old-question'], where).payload)
.toMatchObject({ action: 'message', conversationId: 'lead', messageId: 'old-question' })
expect(parseSuperTabArgs([...prefix, 'post', 'lead', '--tab', 'literal'], where).payload.command).toMatchObject({ text: '--tab' })
diff --git a/cli/src/superTabs/command.ts b/cli/src/superTabs/command.ts
index 7af6e3aa4..265b6fa25 100644
--- a/cli/src/superTabs/command.ts
+++ b/cli/src/superTabs/command.ts
@@ -5,7 +5,7 @@ import { openDaemon, whereFor, type Daemon, type Where } from '../agentClient/da
import { callerOf, type Frame } from '../agentClient/model.js'
import { identifier } from './host.js'
-const USAGE = 'harness super-tab --tab ID [--agent ID] [--port N --machine ID] status | messages GROUP | message GROUP MESSAGE_ID | post GROUP TEXT OPERATION_ID [--reply-to MESSAGE_ID] | command OPERATION_ID JSON | start OPERATION_ID JSON | resume START_ID | capacity MACHINE_ID JSON | route GROUP JSON | help'
+const USAGE = 'harness super-tab --tab ID [--agent ID] [--port N --machine ID] status | messages GROUP | message GROUP MESSAGE_ID | attachment ATTACHMENT_ID | post GROUP TEXT OPERATION_ID [--reply-to MESSAGE_ID] | command OPERATION_ID JSON | start OPERATION_ID JSON | resume START_ID | capacity MACHINE_ID JSON | route GROUP JSON | help'
export function parseSuperTabArgs(argv: readonly string[], where: Where) {
const positional: string[] = []
let tabId = '', agentId = ''
@@ -26,6 +26,7 @@ export function parseSuperTabArgs(argv: readonly string[], where: Where) {
else if (action === 'message' && identifier(first) && identifier(second) && positional.length === 3) {
Object.assign(payload, { conversationId: first, messageId: second })
}
+ else if (action === 'attachment' && identifier(first) && positional.length === 2) payload.attachmentId = first
else if (action === 'post' && identifier(first) && second?.trim() && identifier(third)
&& (positional.length === 4 || (positional.length === 6 && positional[4] === '--reply-to' && identifier(positional[5])))) {
Object.assign(payload, { action: 'command', operationId: third,
diff --git a/cli/src/superTabs/host.spec.ts b/cli/src/superTabs/host.spec.ts
index ab550e847..5bb5c191e 100644
--- a/cli/src/superTabs/host.spec.ts
+++ b/cli/src/superTabs/host.spec.ts
@@ -178,6 +178,45 @@ describe('Super Tab native delivery handoff', () => {
await host.reconcileReceipts()
expect(Object.keys(t.saved().entries)).toEqual(['delivery'])
})
+ it('saves the attached images on this machine and names their paths in the prompt', async () => {
+ const png = Buffer.concat([Buffer.from([0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a]), Buffer.alloc(20, 1)])
+ const t = setup({ text: '', attachments: [{ id: 'img1', name: 'screen shot', mime: 'image/png', size: png.length, parts: 2 },
+ { id: 'img2', name: 'gone.jpg', mime: 'image/jpeg', size: 10, parts: 1 }] })
+ const original = vi.mocked(t.call).getMockImplementation()!
+ let release!: () => void
+ const gate = new Promise<void>(resolve => { release = resolve })
+ vi.mocked(t.call).mockImplementation(async (method, path, body) => {
+ const part = /\/attachments\/(img\d)\/parts\/(\d)\?asAgentId=agent$/.exec(path)
+ if (!part) return original(method, path, body)
+ await gate
+ if (part[1] === 'img2') return { status: 404, body: { success: false, error: { code: 'NOT_FOUND', message: 'This image is unavailable.' } } }
+ const half = part[2] === '0' ? png.subarray(0, 10) : png.subarray(10)
+ return { status: 200, body: { success: true, data: { data: half.toString('base64') } } }
+ })
+ const host = t.open()
+ // The poll returns while the images are still being read: other deliveries' leases keep being renewed.
+ await host.tick()
+ await host.tick()
+ expect(t.core.turns.deliver).not.toHaveBeenCalled()
+ expect(t.core.turns.leaseDeliveries).toHaveBeenCalled()
+ release()
+ await vi.waitFor(() => expect(t.core.turns.deliver).toHaveBeenCalled())
+ await host.tick(); await host.tick()
+ expect(t.core.turns.deliver).toHaveBeenCalledTimes(1)
+ const prompt = vi.mocked(t.core.turns.deliver).mock.calls[0]![1] as string
+ const saved = /^Attached image: (.+)$/m.exec(prompt)![1]!
+ expect(saved).toMatch(/[/\\]paste-drops[/\\][0-9a-f]{8}-screen-shot\.png$/)
+ expect(readFileSync(saved).equals(png)).toBe(true)
+ expect(prompt).toContain("Attached image gone.jpg could not be fetched. Try again: ")
+ expect(prompt).toContain("attachment 'img2'")
+ expect(prompt).toContain('Open each attached image with your file-reading tool to see it.')
+ expect(t.log).toHaveBeenCalledWith(expect.stringContaining('attachment img2 for delivery delivery'))
+ })
+ it('adds nothing about images to a message without them', async () => {
+ const t = setup()
+ await t.open().tick()
+ expect(vi.mocked(t.core.turns.deliver).mock.calls[0]![1]).not.toContain('Attached image')
+ })
it('tells the agent how to reply to this exact message, in short plain words', async () => {
const t = setup({ author: { kind: 'person', id: 'p1', name: '[email protected]' }, text: 'How is it going?' })
await t.open().tick()
diff --git a/cli/src/superTabs/host.ts b/cli/src/superTabs/host.ts
index 499860faa..ecc7a097b 100644
--- a/cli/src/superTabs/host.ts
+++ b/cli/src/superTabs/host.ts
@@ -9,6 +9,7 @@ import { dirname, join } from 'node:path'
import type { CoreApi, TurnDelivery } from '../core/api.js'
import { shellQuote } from '../orchestrator/prompts.js'
import { noticeReason, WithheldDeliveries } from './withheld.js'
+import { attachmentsOf, saveAttachment, type SuperTabAttachment } from './attachments.js'
type Json = Record<string, unknown>
export class SuperTabHostError extends Error {
@@ -44,7 +45,10 @@ export interface SuperTabHostOptions {
write?: (file: string, journal: Journal) => void
log?: (message: string) => void
observers?: typeof publishObservers
+ /** Saves an attached image on this machine and returns its path (attachments.ts); tests pass their own. */
+ saveAttachment?: (tabId: string, agentId: string, attachment: SuperTabAttachment) => Promise<string>
}
+type AttachedImage = { attachment: SuperTabAttachment; path: string | null }
export const hostJournalFile = (dataDir: string, machineId: string) => join(dataDir, 'super-tabs', `host-${machineId}.json`)
const typedId = (entry: Entry) => `team:service:superTabs:${entry.deliveryId}`
@@ -74,9 +78,12 @@ export class SuperTabHost {
private readonly log: (message: string) => void
private retentionError: string | null = null
private readonly observers: typeof publishObservers
+ private readonly saveAttachment: NonNullable<SuperTabHostOptions['saveAttachment']>
private readonly active = new Set<string>()
private readonly authorized = new Map<string, number>()
private readonly withheld = new WithheldDeliveries()
+ /** Images being saved for a claimed delivery, by delivery: done (`images`) or still running. */
+ private readonly downloads = new Map<string, { images: AttachedImage[] | null }>()
private readonly stopHearing: () => void
private stopped = false
private running: Promise<void> | null = null
@@ -95,6 +102,8 @@ export class SuperTabHost {
if (!identifier(machineId)) throw new SuperTabHostError('MACHINE_UNAVAILABLE', 'This machine is not signed in.')
this.file = hostJournalFile(core.dataDir, machineId)
this.observers = options.observers ?? publishObservers
+ this.saveAttachment = options.saveAttachment ?? ((tabId, agentId, attachment) =>
+ saveAttachment(path => backend(core, 'GET', path), tabId, agentId, attachment))
this.now = options.now ?? Date.now
this.write = options.write ?? writeJournal
this.log = options.log ?? (message => console.warn(`[super-tabs] ${message}`))
@@ -145,6 +154,7 @@ export class SuperTabHost {
this.native?.stop()
this.machines?.stop()
this.authorized.clear()
+ this.downloads.clear()
try { this.observers(this.core.dataDir, this.machineId, [], 0) } catch { /* The old snapshot expires. */ }
void this.core.turns.leaseDeliveries('superTabs', {})
for (const id of this.active) this.core.turns.cancelDelivery(id)
@@ -301,6 +311,7 @@ export class SuperTabHost {
const id = typedId(entry)
delete this.journal.entries[deliveryId]
this.withheld.clear(deliveryId)
+ this.downloads.delete(deliveryId)
this.authorized.delete(id)
if (this.active.delete(id)) this.core.turns.cancelDelivery(id)
this.persist()
@@ -343,11 +354,27 @@ export class SuperTabHost {
this.authorized.set(id, this.now() + 2_500)
return
}
+ // Its images are still being saved: a later poll delivers it, and the claim below rechecks authority then.
+ if (this.downloads.get(deliveryId)?.images === null) return
const result = object(await backend(this.core, 'POST', `${path}/${deliveryId}`, { type: 'claim', claimId: entry.claimId }))
// The receipt check may have retired this held entry while the claim was in flight.
if (this.stopped || this.journal.entries[deliveryId] !== entry) return
const message = object(result.message)
if (typeof message.text !== 'string' || !identifier(message.conversationId)) throw new Error('The delivery has no message.')
+ const attached = attachmentsOf(message)
+ let images: AttachedImage[] = []
+ if (attached.length) {
+ // Saving up to four 5 MB images takes seconds. It runs beside the poll, which keeps renewing every other
+ // delivery's lease meanwhile; this one is typed on the first poll after its images are saved.
+ const download = this.downloads.get(deliveryId)
+ if (!download) {
+ const started: { images: AttachedImage[] | null } = { images: null }
+ this.downloads.set(deliveryId, started)
+ void this.saveImages(entry, attached).then(saved => { started.images = saved; if (!this.stopped) void this.tick() })
+ return
+ }
+ images = download.images!
+ }
this.authorized.set(id, this.now() + 2_500)
if (!(await this.leases()) || this.stopped) { this.authorized.delete(id); return }
if (this.active.has(id)) return
@@ -355,8 +382,18 @@ export class SuperTabHost {
// The durable intent must exist before the core can write. A thrown disk write must not deliver.
entry.stage = 'submitting'
this.persist()
+ this.downloads.delete(deliveryId)
this.active.add(id)
- this.core.turns.deliver(entry.harnessId, this.prompt(entry, message), id)
+ this.core.turns.deliver(entry.harnessId, this.prompt(entry, message, images), id)
+ }
+
+ /** An image that cannot be read never holds up its message: the agent is told, and how to fetch it later. */
+ private saveImages(entry: Entry, attached: SuperTabAttachment[]): Promise<AttachedImage[]> {
+ return Promise.all(attached.map(async attachment => ({ attachment,
+ path: await this.saveAttachment(entry.tabId, entry.agentId, attachment).catch(error => {
+ this.log(`attachment ${attachment.id} for delivery ${entry.deliveryId}: ${error instanceof Error ? error.message : String(error)}`)
+ return null
+ }) })))
}
private async recordConfigurations(rows: unknown[]): Promise<void> {
@@ -371,7 +408,7 @@ export class SuperTabHost {
}
}
- private prompt(entry: Entry, message: Json): string {
+ private prompt(entry: Entry, message: Json, images: AttachedImage[] = []): string {
const command = `${this.core.daemon.command} super-tab --port ${this.core.daemon.port} --machine ${shellQuote(this.machineId)} --tab ${shellQuote(entry.tabId)} --agent ${shellQuote(entry.agentId)}`
const group = message.conversationId as string
const reply = identifier(message.replyTo)
@@ -387,6 +424,9 @@ export class SuperTabHost {
+ `Manage agreed work and delegation: ${command} help. Leads: route before starting or assigning: ${command} route GROUP JSON. Use independently verifiable outcomes; local helper subagents need no separate group.\n`
+ `Ask questions and post results in this conversation. ${SUPER_TAB_REPLY_STYLE} Replies to these delivered instructions must be posted here explicitly.\n\n`
+ native + reply + `Message ${String(message.id)} from ${String(object(message.author).name ?? 'a collaborator')}:\n${message.text}`
+ + (images.length ? `\n\n${images.map(({ attachment, path }) => path ? `Attached image: ${path}`
+ : `Attached image ${attachment.name} could not be fetched. Try again: ${command} attachment ${shellQuote(attachment.id)}`).join('\n')}`
+ + '\nOpen each attached image with your file-reading tool to see it.' : '')
}
/** Says why the core keeps holding this delivery: once in the log per change of reason, and once to the conversation after 30 s. */
diff --git a/cli/src/superTabs/service.spec.ts b/cli/src/superTabs/service.spec.ts
index 96b44757b..746d0f9fc 100644
--- a/cli/src/superTabs/service.spec.ts
+++ b/cli/src/superTabs/service.spec.ts
@@ -1,4 +1,5 @@
import { createHash } from 'node:crypto'
+import { readFileSync } from 'node:fs'
import { describe, expect, it, vi } from 'vitest'
import { fakeCore } from '../testing/fakeCore.js'
import { superTabService } from './service.js'
@@ -46,6 +47,9 @@ it('limits the owner proxy to Super Tab endpoints and preserves backend failures
expect(await t.ask({ action: 'backend', method: 'GET', path }, owner)).toMatchObject({ error: 'INVALID_REQUEST' })
}
expect(await t.ask({ action: 'backend', method: 'DELETE', path: '/api/super-tabs' }, owner)).toMatchObject({ error: 'INVALID_REQUEST' })
+ for (const path of ['/api/super-tabs/tab', '/api/super-tabs/tab/attachments', '/api/super-tabs/tab/attachments/img1/parts/0', '/api/super-tabs/tab/attachments/img1?x=1']) {
+ expect(await t.ask({ action: 'backend', method: 'DELETE', path }, owner)).toMatchObject({ error: 'INVALID_REQUEST' })
+ }
expect(t.call).not.toHaveBeenCalled()
expect(await t.ask({ action: 'backend', method: 'GET', path: '/api/super-tabs/tab?asAgentId=agent' }, owner)).toMatchObject({ ok: true })
vi.mocked(t.core.account.backend).mockResolvedValueOnce({ status: 403, body: { success: false, error: { code: 'FORBIDDEN', message: 'Access withdrawn' } } })
@@ -71,6 +75,31 @@ it('resolves a native caller to its exact contribution and rechecks it before ev
expect(await t.ask({ action: 'status', tabId: 'tab', agentId: t.agentId }, owner)).toMatchObject({ error: 'AGENT_UNAVAILABLE' })
})
+it('relays the image routes to the backend, and saves an attached image for its agent', async () => {
+ const t = setup()
+ for (const path of ['/api/super-tabs/tab/attachments', '/api/super-tabs/tab/attachments/img1/parts/3']) {
+ expect(await t.ask({ action: 'backend', method: 'POST', path, body: { data: 'AAAA' } }, owner)).toMatchObject({ ok: true })
+ expect(t.call).toHaveBeenLastCalledWith('POST', path, { data: 'AAAA' })
+ }
+ expect(await t.ask({ action: 'backend', method: 'DELETE', path: '/api/super-tabs/tab/attachments/img1' }, owner)).toMatchObject({ ok: true })
+ expect(t.call).toHaveBeenLastCalledWith('DELETE', '/api/super-tabs/tab/attachments/img1', undefined)
+ const png = Buffer.from([0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a, 1, 2])
+ const meta = { id: 'img1', name: 'diagram.webp', mime: 'image/png', size: png.length, width: 1, height: 1, parts: 1, complete: true }
+ vi.mocked(t.call).mockImplementation((async (_method: string, path: string) => ({ status: 200, body: { success: true,
+ data: path.includes('/parts/0') ? { data: png.toString('base64') } : path.includes('/attachments/') ? meta : { state: { agents: [t.agent] } } } })) as never)
+ const saved = await t.ask({ action: 'attachment', tabId: 'tab', agentId: t.agentId, attachmentId: 'img1' }, owner)
+ expect(saved).toMatchObject({ ok: true, value: { id: 'img1', name: 'diagram.webp', mime: 'image/png', size: png.length } })
+ const file = (saved.value as { path: string }).path
+ expect(file).toMatch(/-diagram\.png$/)
+ expect(readFileSync(file).equals(png)).toBe(true)
+ expect(t.call).toHaveBeenCalledWith('GET', `/api/super-tabs/tab/attachments/img1?asAgentId=${t.agentId}`, undefined)
+ expect(t.call).toHaveBeenCalledWith('GET', `/api/super-tabs/tab/attachments/img1/parts/0?asAgentId=${t.agentId}`, undefined)
+ vi.mocked(t.call).mockImplementation((async (_method: string, path: string) => ({ status: 200, body: { success: true,
+ data: path.includes('/attachments/') ? { ...meta, mime: 'image/gif' } : { state: { agents: [t.agent] } } } })) as never)
+ expect(await t.ask({ action: 'attachment', tabId: 'tab', agentId: t.agentId, attachmentId: 'img1' }, owner)).toMatchObject({ error: 'ATTACHMENT_UNAVAILABLE' })
+ expect((await t.ask({ action: 'help' }, owner)).help).toMatchObject({ attachment: expect.stringContaining('file-reading tool') })
+})
+
it('keeps host capacity separate from account authority and closes it on disconnect or identity change', async () => {
const core = fakeCore()
const reserve = vi.fn(async () => ({ ok: true, reservationId: 'native-creation-id' }))
diff --git a/cli/src/superTabs/service.ts b/cli/src/superTabs/service.ts
index a2d84253d..8b1169ecb 100644
--- a/cli/src/superTabs/service.ts
+++ b/cli/src/superTabs/service.ts
@@ -9,11 +9,13 @@ import { machineChoices } from '../lib/newCommand.js'
import { START_REQUIREMENTS } from './capacity.js'
import { CapacityReservations, type ReservationBook } from './reservations.js'
import { ContributionPreparations, prepareContribution } from './contribution.js'
+import { attachmentsOf, saveAttachment } from './attachments.js'
const HELP = {
status: 'Read the shared tab roster and work.',
- messages: 'messages GROUP: read recent messages in a conversation.',
+ messages: 'messages GROUP: read recent messages in a conversation. A message with images lists them under attachments.',
message: 'message GROUP MESSAGE_ID: read one exact message, including an earlier question or result referenced by a reply.',
+ attachment: 'attachment ATTACHMENT_ID: save an image attached to a message on this machine and print its path. Open that path with your file-reading tool to see it.',
post: 'post GROUP TEXT OPERATION_ID [--reply-to MESSAGE_ID]: reply in that conversation. Use a unique ID per message and reuse it after an interrupted request. Answer a message once, with --reply-to its ID.',
start: 'start OPERATION_ID JSON: create one agent in a conversation on a machine you can access. Repeat exactly after an interruption; it follows the same native creation receipt. It does not assign work.',
resume: 'resume START_ID: finish a pending start without creating another agent.',
@@ -103,8 +105,10 @@ export function superTabService(core: CoreApi, options: SuperTabServiceOptions =
if (payload.action === 'prepareContribution') return preparations.read(payload)
if (payload.action === 'backend') {
const { method, path } = payload
- if (!['GET', 'POST'].includes(String(method)) || typeof path !== 'string'
- || !/^\/api\/super-tabs(?:\/[A-Za-z0-9_-]+)*(?:\?[A-Za-z0-9_=&%-]+)?$/.test(path)) {
+ // DELETE only takes back one's own unsent image; every other route reads or writes.
+ if (typeof path !== 'string' || !/^\/api\/super-tabs(?:\/[A-Za-z0-9_-]+)*(?:\?[A-Za-z0-9_=&%-]+)?$/.test(path)
+ || !(['GET', 'POST'].includes(String(method))
+ || (method === 'DELETE' && /^\/api\/super-tabs\/[A-Za-z0-9_-]+\/attachments\/[A-Za-z0-9_-]+$/.test(path)))) {
return { error: 'INVALID_REQUEST', detail: 'Choose a Super Tab endpoint.' }
}
const value = await backend(core, method as string, path, payload.body)
@@ -206,6 +210,12 @@ export function superTabService(core: CoreApi, options: SuperTabServiceOptions =
return { ok: true, value: markAnswered(page, list(later), agentId) }
} catch { return { ok: true, value: page } }
}
+ if (payload.action === 'attachment' && identifier(payload.attachmentId)) {
+ const [attachment] = attachmentsOf({ attachments: [await backend(core, 'GET', `${path}/attachments/${payload.attachmentId}?${identity}`)] })
+ if (!attachment) return { error: 'ATTACHMENT_UNAVAILABLE', detail: 'This image cannot be read.' }
+ const file = await saveAttachment(target => backend(core, 'GET', target), payload.tabId, agentId, attachment)
+ return { ok: true, value: { id: attachment.id, name: attachment.name, mime: attachment.mime, size: attachment.size, path: file } }
+ }
if (payload.action === 'command' && identifier(payload.operationId) && payload.command && typeof payload.command === 'object' && !Array.isArray(payload.command)) {
return { ok: true, operationId: payload.operationId, value: await backend(core, 'POST', `${path}/commands`,
{ operationId: payload.operationId, command: payload.command, asAgentId: agentId }) }
diff --git a/desktop/lib/super_tabs/attachments.dart b/desktop/lib/super_tabs/attachments.dart
new file mode 100644
index 000000000..f68e3448d
--- /dev/null
+++ b/desktop/lib/super_tabs/attachments.dart
@@ -0,0 +1,328 @@
+import 'dart:typed_data';
+
+import 'package:flutter/material.dart';
+
+import '../clipboard/copied_files.dart';
+import '../clipboard/native_clipboard.dart';
+import '../shared/theme/app_icons.dart';
+import '../shared/widgets/app_dialog.dart';
+import '../shared/widgets/app_icon_button.dart';
+import '../state/harness_attachments.dart';
+import '../widgets/desktop_chrome.dart';
+import 'model.dart';
+
+/// The backend's limits (backend/src/superTabs/attachments.ts): a message
+/// carries up to four PNG, JPEG or WebP images of up to 5 MB each.
+const kSuperTabImagesPerMessage = 4;
+const kSuperTabImageMaxBytes = 5 * 1024 * 1024;
+
+/// The bytes travel in parts this size, each one small request through the
+/// machine relay (`ATTACHMENT_PART_BYTES` on the backend).
+const kSuperTabImagePartBytes = 256 * 1024;
+
+/// The image type [bytes] really are, read from their header, or null for
+/// anything a Swarm does not take (a GIF, a PDF, a renamed file).
+String? superTabImageMime(Uint8List bytes) {
+ bool starts(List<int> prefix, [int at = 0]) =>
+ bytes.length >= at + prefix.length &&
+ [for (var i = 0; i < prefix.length; i++) bytes[at + i] == prefix[i]]
+ .every((same) => same);
+ if (starts(const [0x89, 0x50, 0x4E, 0x47, 0x0D, 0x0A, 0x1A, 0x0A])) {
+ return 'image/png';
+ }
+ if (starts(const [0xFF, 0xD8, 0xFF])) return 'image/jpeg';
+ if (starts('RIFF'.codeUnits) && starts('WEBP'.codeUnits, 8)) {
+ return 'image/webp';
+ }
+ return null;
+}
+
+/// The images waiting in one conversation's composer. They stay in memory
+/// only: a saved pending send names their uploaded IDs, never their bytes.
+class SuperTabImages extends HarnessAttachments {
+ SuperTabImages({this.onDiscard});
+
+ /// Told the backend ID of an upload nobody will send: removed, replaced,
+ /// or refused. The backend keeps at most 24 unsent images a person, so each
+ /// is deleted at once rather than left to expire.
+ final void Function(String id)? onDiscard;
+
+ final _uploads = <HarnessAttachment, ({String id, bool complete})>{};
+
+ /// The backend ID of [file] once all its parts are uploaded.
+ String? uploadedId(HarnessAttachment file) =>
+ _uploads[file]?.complete == true ? _uploads[file]!.id : null;
+
+ /// The backend ID of [file] once its upload started, finished or not: an
+ /// interrupted upload resumes there.
+ String? startedId(HarnessAttachment file) => _uploads[file]?.id;
+ void markStarted(HarnessAttachment file, String id) =>
+ _uploads[file] = (id: id, complete: false);
+ void markUploaded(HarnessAttachment file, String id) =>
+ _uploads[file] = (id: id, complete: true);
+
+ /// The backend no longer has [file]'s upload; the next send starts over.
+ void forget(HarnessAttachment file) => _uploads.remove(file);
+
+ /// The backend refused these uploads; the next send uploads again.
+ void forgetUploads() {
+ for (final file in [..._uploads.keys]) {
+ _discard(file);
+ }
+ }
+
+ /// [file] went out with a message: its upload is the message's now.
+ void sent(HarnessAttachment file) {
+ _uploads.remove(file);
+ super.remove(file);
+ }
+
+ void _discard(HarnessAttachment file) {
+ final upload = _uploads.remove(file);
+ if (upload != null) onDiscard?.call(upload.id);
+ }
+
+ /// Takes PNG, JPEG and WebP images up to 5 MB, four in all, and says what it
+ /// left out.
+ @override
+ String? add(
+ Iterable<HarnessAttachment> files, {
+ Iterable<String> oversized = const [],
+ }) {
+ final notImages = <String>[], tooLarge = [...oversized];
+ final taken = <HarnessAttachment>[];
+ var overCount = 0;
+ for (final file in files) {
+ if (file.bytes.isEmpty) continue;
+ if (superTabImageMime(file.bytes) == null) {
+ notImages.add(file.name);
+ } else if (file.bytes.length > kSuperTabImageMaxBytes) {
+ tooLarge.add(file.name);
+ } else if (this.files.length + taken.length >=
+ kSuperTabImagesPerMessage &&
+ !this.files.any((kept) => kept.name == file.name)) {
+ overCount++;
+ } else {
+ taken.add(file);
+ }
+ }
+ for (final file in this.files) {
+ if (taken.any((next) => next.name == file.name)) _discard(file);
+ }
+ super.add(taken);
+ return [
+ if (notImages.length == 1)
+ '${notImages.single} is not a PNG, JPEG or WebP image.'
+ else if (notImages.isNotEmpty)
+ '${notImages.length} files are not PNG, JPEG or WebP images.',
+ if (tooLarge.length == 1)
+ '${tooLarge.single} is over 5 MB.'
+ else if (tooLarge.isNotEmpty)
+ '${tooLarge.length} images are over 5 MB.',
+ if (overCount > 0) 'A message can carry up to 4 images.',
+ ].join(' ').nullIfEmpty;
+ }
+
+ @override
+ void remove(HarnessAttachment file) {
+ _discard(file);
+ super.remove(file);
+ }
+
+ @override
+ void clear() {
+ forgetUploads();
+ super.clear();
+ }
+}
+
+/// What ⌘V in the Swarm composer takes from files copied in a file manager:
+/// only the images among them. Any other copied file pastes as before, its name
+/// as text, rather than being refused.
+Future<CopiedFiles> superTabCopiedImages() async {
+ final copied = await readCopiedFiles(
+ await NativeClipboard.readFilePaths(),
+ maxBytes: kSuperTabImageMaxBytes,
+ );
+ return (
+ files: [
+ for (final file in copied.files)
+ if (superTabImageMime(file.bytes) != null) file,
+ ],
+ tooLarge: [
+ for (final name in copied.tooLarge)
+ if (RegExp(r'\.(png|jpe?g|webp)$', caseSensitive: false).hasMatch(name))
+ name,
+ ],
+ );
+}
+
+extension on String {
+ String? get nullIfEmpty => isEmpty ? null : this;
+}
+
+/// A message's images as small thumbnails; a click shows one larger.
+class SuperTabMessageImages extends StatelessWidget {
+ const SuperTabMessageImages({
+ super.key,
+ required this.attachments,
+ required this.load,
+ });
+
+ final List<SuperTabAttachment> attachments;
+ final Future<Uint8List> Function(SuperTabAttachment attachment) load;
+
+ static const thumbnail = 120.0;
+
+ @override
+ Widget build(BuildContext context) => Padding(
+ padding: const EdgeInsets.only(top: 6),
+ child: Wrap(
+ spacing: 8,
+ runSpacing: 8,
+ children: [
+ for (final attachment in attachments)
+ _Thumbnail(attachment: attachment, load: load),
+ ],
+ ),
+ );
+}
+
+class _Thumbnail extends StatefulWidget {
+ const _Thumbnail({required this.attachment, required this.load});
+
+ final SuperTabAttachment attachment;
+ final Future<Uint8List> Function(SuperTabAttachment attachment) load;
+
+ @override
+ State<_Thumbnail> createState() => _ThumbnailState();
+}
+
+class _ThumbnailState extends State<_Thumbnail> {
+ late Future<Uint8List> _bytes = widget.load(widget.attachment);
+
+ void _retry() => setState(() => _bytes = widget.load(widget.attachment));
+
+ Future<void> _open(Uint8List bytes) => showAppDialog<void>(
+ context: context,
+ builder: (context) => Dialog(
+ backgroundColor: DesktopChrome.surface,
+ insetPadding: const EdgeInsets.all(32),
+ child: Column(
+ mainAxisSize: MainAxisSize.min,
+ crossAxisAlignment: CrossAxisAlignment.stretch,
+ children: [
+ Padding(
+ padding: const EdgeInsets.fromLTRB(16, 8, 8, 0),
+ child: Row(
+ children: [
+ Expanded(
+ child: Text(
+ widget.attachment.name,
+ maxLines: 1,
+ overflow: TextOverflow.ellipsis,
+ style: DesktopChrome.control(medium: true),
+ ),
+ ),
+ AppIconButton(
+ icon: AppIcons.close,
+ tooltip: 'Close',
+ onPressed: () => Navigator.pop(context),
+ ),
+ ],
+ ),
+ ),
+ Flexible(
+ child: Padding(
+ padding: const EdgeInsets.all(16),
+ child: InteractiveViewer(
+ child: Image.memory(
+ bytes,
+ key: ValueKey(
+ 'super-message-image-full:${widget.attachment.id}',
+ ),
+ fit: BoxFit.contain,
+ ),
+ ),
+ ),
+ ),
+ ],
+ ),
+ ),
+ );
+
+ @override
+ Widget build(BuildContext context) {
+ final attachment = widget.attachment;
+ const size = SuperTabMessageImages.thumbnail;
+ return FutureBuilder<Uint8List>(
+ future: _bytes,
+ builder: (context, snapshot) {
+ final bytes = snapshot.data;
+ final Widget child;
+ if (bytes != null) {
+ child = Image.memory(
+ bytes,
+ key: ValueKey('super-message-image:${attachment.id}'),
+ width: size,
+ height: size,
+ // Decoded at the size it is drawn, not the screenshot's own.
+ cacheWidth: (size * 3).toInt(),
+ fit: BoxFit.cover,
+ gaplessPlayback: true,
+ errorBuilder: (_, _, _) => _placeholder('Image unavailable'),
+ );
+ } else if (snapshot.hasError) {
+ child = _placeholder('Could not load ${attachment.name}');
+ } else {
+ child = const Center(
+ child: SizedBox.square(
+ dimension: 16,
+ child: CircularProgressIndicator(strokeWidth: 2),
+ ),
+ );
+ }
+ return Tooltip(
+ message: snapshot.hasError
+ ? 'Could not load ${attachment.name}. Click to try again.'
+ : attachment.name,
+ child: Semantics(
+ button: true,
+ label: 'Image ${attachment.name}',
+ child: InkWell(
+ key: ValueKey('super-message-attachment:${attachment.id}'),
+ borderRadius: BorderRadius.circular(8),
+ onTap: bytes != null
+ ? () => _open(bytes)
+ : snapshot.hasError
+ ? _retry
+ : null,
+ child: ClipRRect(
+ borderRadius: BorderRadius.circular(8),
+ child: Container(
+ width: size,
+ height: size,
+ color: DesktopChrome.foreground.withValues(alpha: .055),
+ child: child,
+ ),
+ ),
+ ),
+ ),
+ );
+ },
+ );
+ }
+
+ Widget _placeholder(String label) => Center(
+ child: Padding(
+ padding: const EdgeInsets.all(8),
+ child: Text(
+ label,
+ textAlign: TextAlign.center,
+ maxLines: 3,
+ overflow: TextOverflow.ellipsis,
+ style: DesktopChrome.metadata(),
+ ),
+ ),
+ );
+}
diff --git a/desktop/lib/super_tabs/controller.dart b/desktop/lib/super_tabs/controller.dart
index 0590ffd65..ce7f1a2a3 100644
--- a/desktop/lib/super_tabs/controller.dart
+++ b/desktop/lib/super_tabs/controller.dart
@@ -1,8 +1,12 @@
import 'dart:async';
+import 'dart:convert';
import 'dart:math';
+import 'dart:typed_data';
import 'package:flutter/foundation.dart';
+import '../state/harness_attachments.dart';
+import 'attachments.dart';
import 'model.dart';
typedef SuperTabRequest = Future<Map<String, dynamic>> Function(
@@ -107,6 +111,8 @@ class SuperTabController extends ChangeNotifier {
final _terminals = <String, String>{};
final _mentions = <String, Map<String, String>>{};
final _readAt = <String, int>{};
+ final _images = <String, SuperTabImages>{};
+ final _imageBytes = <String, Future<Uint8List>>{};
final _messages = <String, List<SuperTabMessage>>{};
final _before = <String, int?>{};
final _reading = <String>{};
@@ -130,6 +136,105 @@ class SuperTabController extends ChangeNotifier {
Map<String, dynamic>? get pendingCommand =>
_pending == null ? null : superTabMap(_pending!['command']);
String draft(String id) => _drafts[id] ?? '';
+
+ /// The images waiting in [conversationId]'s composer, kept in memory only.
+ SuperTabImages images(String conversationId) =>
+ _images[conversationId] ??= (SuperTabImages(
+ onDiscard: (id) => unawaited(
+ request(
+ 'DELETE',
+ '$_path/attachments/${Uri.encodeComponent(id)}',
+ ).then((_) {}, onError: (Object _) {}),
+ ),
+ )..addListener(_changed));
+
+ /// An attached image's bytes, read part by part through the same relay as
+ /// every other request. The last few stay in memory; a failed read is
+ /// forgotten so the next one tries again.
+ Future<Uint8List> attachmentBytes(SuperTabAttachment attachment) {
+ final known = _imageBytes.remove(attachment.id);
+ if (known != null) return _imageBytes[attachment.id] = known;
+ final read = _readAttachment(attachment);
+ _imageBytes[attachment.id] = read;
+ // A screenshot is a few megabytes: eight stay, about the images in view.
+ while (_imageBytes.length > 8) {
+ _imageBytes.remove(_imageBytes.keys.first);
+ }
+ read.catchError((Object _) {
+ if (identical(_imageBytes[attachment.id], read)) {
+ _imageBytes.remove(attachment.id);
+ }
+ return Uint8List(0);
+ });
+ return read;
+ }
+
+ Future<Uint8List> _readAttachment(SuperTabAttachment attachment) async {
+ final bytes = BytesBuilder(copy: false);
+ for (var index = 0; index < attachment.parts; index++) {
+ final part = await request(
+ 'GET',
+ '$_path/attachments/${Uri.encodeComponent(attachment.id)}/parts/$index',
+ );
+ bytes.add(base64Decode(part['data'] as String));
+ }
+ if (bytes.length != attachment.size) {
+ throw const FormatException('The image arrived incomplete.');
+ }
+ return bytes.takeBytes();
+ }
+
+ /// Uploads [file] in parts unless it already was, and returns its ID. An
+ /// interrupted upload resumes with the parts the backend is missing.
+ Future<String> _upload(SuperTabImages staged, HarnessAttachment file) async {
+ if (staged.uploadedId(file) case final id?) return id;
+ final bytes = file.bytes;
+ final parts = (bytes.length / kSuperTabImagePartBytes).ceil();
+ String part(int index) => base64Encode(
+ bytes.sublist(
+ index * kSuperTabImagePartBytes,
+ min(bytes.length, (index + 1) * kSuperTabImagePartBytes),
+ ),
+ );
+ var id = staged.startedId(file);
+ List<int> missing = [for (var index = 1; index < parts; index++) index];
+ if (id != null) {
+ try {
+ final known = await request(
+ 'GET',
+ '$_path/attachments/${Uri.encodeComponent(id)}',
+ );
+ missing = [
+ for (final index in known['missing'] as List? ?? const [])
+ (index as num).toInt(),
+ ];
+ } on SuperTabFailure catch (failure) {
+ if (failure.code != 'NOT_FOUND') rethrow;
+ staged.forget(file);
+ id = null;
+ }
+ }
+ if (id == null) {
+ final created = await request(
+ 'POST',
+ '$_path/attachments',
+ body: {'name': file.name, 'size': bytes.length, 'data': part(0)},
+ );
+ id = created['id'] as String;
+ staged.markStarted(file, id);
+ }
+ for (final index in missing) {
+ if (_disposed) throw const SuperTabFailure('CLOSED', 'Swarm closed.');
+ await request(
+ 'POST',
+ '$_path/attachments/${Uri.encodeComponent(id)}/parts/$index',
+ body: {'data': part(index)},
+ );
+ }
+ staged.markUploaded(file, id);
+ return id;
+ }
+
SuperTabAgent? terminalAgent(String conversationId) {
return terminalAgents(conversationId).firstOrNull;
}
@@ -204,6 +309,10 @@ class SuperTabController extends ChangeNotifier {
error = message;
snapshot = null;
_messages.clear();
+ _imageBytes.clear();
+ for (final staged in _images.values) {
+ staged.clear();
+ }
_poll?.cancel();
_changed();
}
@@ -321,6 +430,9 @@ class SuperTabController extends ChangeNotifier {
(id) => !next.projects.any((project) => project.id == id),
);
_messages.removeWhere((id, _) => !allowed.contains(id));
+ for (final id in _images.keys.where((id) => !allowed.contains(id))) {
+ _images[id]!.clear();
+ }
_drafts.removeWhere((id, _) => !allowed.contains(id));
_terminals.removeWhere((id, _) => !allowed.contains(id));
_mentions.removeWhere((id, _) => !allowed.contains(id));
@@ -461,6 +573,13 @@ class SuperTabController extends ChangeNotifier {
_drafts.remove(id);
_mentions.remove(id);
}
+ final sent = (command['attachmentIds'] as List? ?? const []).toSet();
+ final staged = _images[id];
+ if (staged != null && sent.isNotEmpty) {
+ for (final file in staged.files) {
+ if (sent.contains(staged.uploadedId(file))) staged.sent(file);
+ }
+ }
}
if (command['type'] == 'conversation.create' &&
result['conversationId'] is String) {
@@ -499,6 +618,13 @@ class SuperTabController extends ChangeNotifier {
_pending = pending;
}
}
+ if (failure is SuperTabFailure &&
+ failure.code == 'INVALID_ATTACHMENT') {
+ // An expired or already sent upload: the images still in the
+ // composer upload again on the next send.
+ final command = superTabMap(pending['command']);
+ _images[command['conversationId']]?.forgetUploads();
+ }
if (failure is SuperTabFailure &&
const {
'FORBIDDEN',
@@ -522,13 +648,19 @@ class SuperTabController extends ChangeNotifier {
command['type'] == 'member.remove' &&
command['userId'] == accountId);
+ /// Uploads the composer's images first, then sends the text with their
+ /// IDs. Images alone are a message too.
Future<Map<String, dynamic>?> send({
String? replyTo,
List<String> recipients = const [],
- }) {
- final text = draft(selectedId).trim();
- if (text.isEmpty || selected == null || selected!.archived) {
- return Future.value(null);
+ }) async {
+ final conversationId = selectedId;
+ final text = draft(conversationId).trim();
+ final staged = images(conversationId);
+ if ((text.isEmpty && staged.isEmpty) ||
+ selected == null ||
+ selected!.archived) {
+ return null;
}
final addressed = recipients.isEmpty
? mentions(selectedId).entries
@@ -539,14 +671,37 @@ class SuperTabController extends ChangeNotifier {
if (addressed.any((id) => !selected!.agentIds.contains(id))) {
operationError = 'A mentioned agent is no longer in this conversation. Remove its mention or choose another agent.';
_changed();
- return Future.value(null);
+ return null;
+ }
+ final attachmentIds = <String>[];
+ if (!staged.isEmpty) {
+ if (_disposed || !canWrite || saving || _pending != null) return null;
+ saving = true;
+ operationError = null;
+ _changed();
+ try {
+ for (final file in staged.files) {
+ attachmentIds.add(await _upload(staged, file));
+ }
+ } catch (failure) {
+ if (_disposed) return null;
+ operationError = failure is SuperTabFailure
+ ? failure.message
+ : 'Could not upload the image. Try again.';
+ return null;
+ } finally {
+ saving = false;
+ _changed();
+ }
+ if (_disposed) return null;
}
return command({
'type': 'message.send',
- 'conversationId': selectedId,
+ 'conversationId': conversationId,
'text': text,
'replyTo': replyTo,
'recipientIds': addressed,
+ if (attachmentIds.isNotEmpty) 'attachmentIds': attachmentIds,
});
}
@@ -560,6 +715,10 @@ class SuperTabController extends ChangeNotifier {
_disposed = true;
_poll?.cancel();
_draftSave?.cancel();
+ for (final staged in _images.values) {
+ staged.dispose();
+ }
+ _imageBytes.clear();
// The owner awaits flush when changing account or closing the tab.
super.dispose();
}
diff --git a/desktop/lib/super_tabs/message_row.dart b/desktop/lib/super_tabs/message_row.dart
index ae51c6827..7defdddd1 100644
--- a/desktop/lib/super_tabs/message_row.dart
+++ b/desktop/lib/super_tabs/message_row.dart
@@ -6,6 +6,7 @@ import '../shared/theme/app_theme.dart' as grid;
import '../shared/widgets/app_icon_button.dart';
import '../widgets/desktop_chrome.dart';
import '../widgets/engine_identity.dart';
+import 'attachments.dart';
import 'identity.dart';
import 'message_text.dart';
import 'model.dart';
@@ -28,6 +29,7 @@ class SuperTabMessageRow extends StatefulWidget {
this.onOpenAgent,
this.references = const {},
this.onOpenGroup,
+ this.loadAttachment,
});
final SuperTabMessage message;
@@ -43,6 +45,10 @@ class SuperTabMessageRow extends StatefulWidget {
final VoidCallback onReturnToComposer;
final List<Widget> receipts;
+ /// Reads an attached image's bytes; without it, images are not shown.
+ final Future<Uint8List> Function(SuperTabAttachment attachment)?
+ loadAttachment;
+
// Routing notes share the message body column, including grouped messages.
static const horizontalInset = 24.0;
static const avatarSize = 28.0;
@@ -270,7 +276,7 @@ class _SuperTabMessageRowState extends State<SuperTabMessageRow> {
widget.reply?.authorName ??
'Earlier message',
text:
- widget.reply?.text ??
+ widget.reply?.preview ??
'The original message isn’t loaded.',
),
),
@@ -282,16 +288,24 @@ class _SuperTabMessageRowState extends State<SuperTabMessageRow> {
style: DesktopChrome.metadata(),
),
),
- ConstrainedBox(
- constraints: const BoxConstraints(
- maxWidth: 960,
+ if (message.shownText.isNotEmpty ||
+ message.attachments.isEmpty)
+ ConstrainedBox(
+ constraints: const BoxConstraints(
+ maxWidth: 960,
+ ),
+ child: SuperTabMessageText(
+ message.shownText,
+ references: widget.references,
+ onOpenGroup: widget.onOpenGroup,
+ ),
),
- child: SuperTabMessageText(
- message.text,
- references: widget.references,
- onOpenGroup: widget.onOpenGroup,
+ if (message.attachments.isNotEmpty &&
+ widget.loadAttachment != null)
+ SuperTabMessageImages(
+ attachments: message.attachments,
+ load: widget.loadAttachment!,
),
- ),
SuperTabPullRequestLinks(message.text),
...widget.receipts,
],
diff --git a/desktop/lib/super_tabs/model.dart b/desktop/lib/super_tabs/model.dart
index 53e48916b..3b551a350 100644
--- a/desktop/lib/super_tabs/model.dart
+++ b/desktop/lib/super_tabs/model.dart
@@ -221,6 +221,22 @@ class SuperTabRoute {
final List<SuperTabRouteChoice> alternatives;
}
+/// An image sent with a message. A message read never carries its bytes;
+/// they are read in [parts] (SuperTabController.attachmentBytes).
+class SuperTabAttachment {
+ SuperTabAttachment.fromJson(Map<String, dynamic> row)
+ : id = _text(row, 'id'),
+ name = _text(row, 'name'),
+ mime = _text(row, 'mime'),
+ size = (row['size'] as num).toInt(),
+ width = (row['width'] as num?)?.toInt(),
+ height = (row['height'] as num?)?.toInt(),
+ parts = (row['parts'] as num).toInt();
+ final String id, name, mime;
+ final int size, parts;
+ final int? width, height;
+}
+
class SuperTabMessage {
SuperTabMessage.fromJson(Map<String, dynamic> row)
: id = _text(row, 'id'),
@@ -234,8 +250,33 @@ class SuperTabMessage {
deliveries = _list(
row['deliveries'] ?? const [],
(d) => Map<String, dynamic>.unmodifiable(d),
+ ),
+ attachments = _list(
+ row['attachments'] ?? const [],
+ SuperTabAttachment.fromJson,
);
final String id, conversationId, text;
+ final List<SuperTabAttachment> attachments;
+
+ /// One line for a quote of it: its text, or what it carries when it is
+ /// only images.
+ String get preview => shownText.trim().isNotEmpty || attachments.isEmpty
+ ? shownText
+ : attachments.length == 1
+ ? 'Image'
+ : '${attachments.length} images';
+
+ /// The text to draw beside its images. A message of images alone is stored
+ /// with `[image]` or `[N images]` (backend attachments.ts
+ /// `imagesPlaceholder`) for clients that cannot show them; this one does.
+ String get shownText =>
+ attachments.isNotEmpty &&
+ text ==
+ (attachments.length == 1
+ ? '[image]'
+ : '[${attachments.length} images]')
+ ? ''
+ : text;
final String? replyTo;
final int sequence;
final Map<String, dynamic> author;
diff --git a/desktop/lib/super_tabs/view.dart b/desktop/lib/super_tabs/view.dart
index b4c3a78dc..4bfea50f6 100644
--- a/desktop/lib/super_tabs/view.dart
+++ b/desktop/lib/super_tabs/view.dart
@@ -8,7 +8,10 @@ import '../shared/theme/app_theme.dart' as grid;
import '../shared/widgets/app_dialog.dart';
import '../shared/widgets/app_icon_button.dart';
import '../widgets/desktop_chrome.dart';
+import '../widgets/new_harness_attachments.dart';
+import '../widgets/new_harness_paste.dart';
import '../state/app_state.dart';
+import 'attachments.dart';
import 'roster.dart';
import 'recording_notice.dart';
import 'pull_requests.dart';
@@ -230,7 +233,7 @@ class _SuperTabViewState extends State<SuperTabView> {
c.selected!.archived ||
c.saving ||
c.hasPendingAction ||
- _composer.text.trim().isEmpty) {
+ (_composer.text.trim().isEmpty && c.images(c.selectedId).isEmpty)) {
return;
}
final id = c.selectedId;
@@ -926,6 +929,7 @@ class _SuperTabViewState extends State<SuperTabView> {
grouped: grouped,
reply: reply,
replyAuthor: reply == null ? null : _shownAuthor(c, reply),
+ loadAttachment: c.attachmentBytes,
onReply: c.canWrite && c.selected?.archived == false
? () {
setState(() => _replies[c.selectedId] = message);
@@ -1019,6 +1023,8 @@ class _SuperTabViewState extends State<SuperTabView> {
: messages.where((message) => message.sequence > newAfter).length;
final reply = _replies[c.selectedId];
final choices = _completionChoices;
+ final images = c.images(c.selectedId);
+ final writable = c.canWrite && group != null && !group.archived;
return Column(
children: [
if (c.error != null)
@@ -1181,7 +1187,7 @@ class _SuperTabViewState extends State<SuperTabView> {
Expanded(
child: SuperTabReplyPreview(
author: 'Replying to ${_authorName(reply)}',
- text: reply.text,
+ text: reply.preview,
),
),
AppIconButton(
@@ -1322,91 +1328,120 @@ class _SuperTabViewState extends State<SuperTabView> {
}
return KeyEventResult.ignored;
},
- child: DecoratedBox(
- key: const ValueKey('super-message-composer-surface'),
- decoration: BoxDecoration(
- color: DesktopChrome.field,
- borderRadius: BorderRadius.circular(
- DesktopChrome.controlRadius,
+ child: NewHarnessDropZone(
+ attachments: images,
+ enabled: writable && !c.saving,
+ child: DecoratedBox(
+ key: const ValueKey('super-message-composer-surface'),
+ decoration: BoxDecoration(
+ color: DesktopChrome.field,
+ borderRadius: BorderRadius.circular(
+ DesktopChrome.controlRadius,
+ ),
+ border: Border.all(color: DesktopChrome.rim),
),
- border: Border.all(color: DesktopChrome.rim),
- ),
- child: GestureDetector(
- behavior: HitTestBehavior.translucent,
- onTap: c.canWrite && group != null && !group.archived
- ? _focus.requestFocus
- : null,
- child: Padding(
- padding: const EdgeInsets.fromLTRB(16, 8, 8, 8),
- child: ConstrainedBox(
- constraints: BoxConstraints(
- minHeight: grid.AppControl.heightFieldScaled,
- ),
- child: Row(
- crossAxisAlignment: CrossAxisAlignment.center,
+ child: GestureDetector(
+ behavior: HitTestBehavior.translucent,
+ onTap: c.canWrite && group != null && !group.archived
+ ? _focus.requestFocus
+ : null,
+ child: Padding(
+ padding: const EdgeInsets.fromLTRB(16, 8, 8, 8),
+ child: Column(
+ mainAxisSize: MainAxisSize.min,
+ crossAxisAlignment: CrossAxisAlignment.start,
children: [
- Expanded(
- child: TextField(
- key: const ValueKey('super-message-composer'),
- controller: _composer,
- focusNode: _focus,
- autofocus: !_terminalsVisible,
- enabled:
- c.canWrite && group != null && !group.archived,
- minLines: 1,
- maxLines: MediaQuery.sizeOf(context).height < 600
- ? 3
- : 8,
- maxLength: 32000,
- keyboardType: TextInputType.multiline,
- textAlignVertical: TextAlignVertical.center,
- style: DesktopChrome.text(),
- decoration: InputDecoration(
- // The row centers the line. Inheriting a decorated
- // field's minimum height leaves slack below its text.
- isCollapsed: true,
- constraints: const BoxConstraints(),
- visualDensity: VisualDensity.standard,
- hintStyle: DesktopChrome.text(
- color: DesktopChrome.muted,
- ),
- contentPadding: EdgeInsets.zero,
- hintText: group == null
- ? 'Loading conversation…'
- : c.canWrite
- ? 'Message ${group.title}'
- : 'Read-only conversation',
- border: InputBorder.none,
- enabledBorder: InputBorder.none,
- focusedBorder: InputBorder.none,
- disabledBorder: InputBorder.none,
- filled: false,
- counterText: '',
+ if (!images.isEmpty)
+ Padding(
+ padding: const EdgeInsets.only(bottom: 8, right: 8),
+ child: NewHarnessAttachmentChips(
+ key: const ValueKey('super-composer-images'),
+ attachments: images,
+ enabled: !c.saving,
),
- onChanged: (text) {
- c.setDraft(c.selectedId, text);
- setState(() {
- _mentionIndex = 0;
- _dismissedMention = null;
- });
- },
),
- ),
- ValueListenableBuilder(
- valueListenable: _composer,
- builder: (context, value, _) => AppIconButton(
- icon: AppIcons.arrowUp,
- tooltip: 'Send message',
- color: DesktopChrome.accent,
- onPressed:
- c.canWrite &&
- group != null &&
- !group.archived &&
- !c.saving &&
- !c.hasPendingAction &&
- value.text.trim().isNotEmpty
- ? () => unawaited(_send())
- : null,
+ ConstrainedBox(
+ constraints: BoxConstraints(
+ minHeight: grid.AppControl.heightFieldScaled,
+ ),
+ child: Row(
+ crossAxisAlignment: CrossAxisAlignment.center,
+ children: [
+ Expanded(
+ child: NewHarnessPasteTarget(
+ attachments: images,
+ enabled: writable && !c.saving,
+ focusNode: _focus,
+ readFiles: superTabCopiedImages,
+ child: TextField(
+ key: const ValueKey(
+ 'super-message-composer',
+ ),
+ controller: _composer,
+ focusNode: _focus,
+ autofocus: !_terminalsVisible,
+ enabled:
+ c.canWrite &&
+ group != null &&
+ !group.archived,
+ minLines: 1,
+ maxLines:
+ MediaQuery.sizeOf(context).height < 600
+ ? 3
+ : 8,
+ maxLength: 32000,
+ keyboardType: TextInputType.multiline,
+ textAlignVertical: TextAlignVertical.center,
+ style: DesktopChrome.text(),
+ decoration: InputDecoration(
+ // The row centers the line. Inheriting a decorated
+ // field's minimum height leaves slack below its text.
+ isCollapsed: true,
+ constraints: const BoxConstraints(),
+ visualDensity: VisualDensity.standard,
+ hintStyle: DesktopChrome.text(
+ color: DesktopChrome.muted,
+ ),
+ contentPadding: EdgeInsets.zero,
+ hintText: group == null
+ ? 'Loading conversation…'
+ : c.canWrite
+ ? 'Message ${group.title}'
+ : 'Read-only conversation',
+ border: InputBorder.none,
+ enabledBorder: InputBorder.none,
+ focusedBorder: InputBorder.none,
+ disabledBorder: InputBorder.none,
+ filled: false,
+ counterText: '',
+ ),
+ onChanged: (text) {
+ c.setDraft(c.selectedId, text);
+ setState(() {
+ _mentionIndex = 0;
+ _dismissedMention = null;
+ });
+ },
+ ),
+ ),
+ ),
+ ValueListenableBuilder(
+ valueListenable: _composer,
+ builder: (context, value, _) => AppIconButton(
+ icon: AppIcons.arrowUp,
+ tooltip: 'Send message',
+ color: DesktopChrome.accent,
+ onPressed:
+ writable &&
+ !c.saving &&
+ !c.hasPendingAction &&
+ (value.text.trim().isNotEmpty ||
+ !images.isEmpty)
+ ? () => unawaited(_send())
+ : null,
+ ),
+ ),
+ ],
),
),
],
diff --git a/desktop/test/super_tab_images_test.dart b/desktop/test/super_tab_images_test.dart
new file mode 100644
index 000000000..f34d6e20a
--- /dev/null
+++ b/desktop/test/super_tab_images_test.dart
@@ -0,0 +1,304 @@
+// Images in a Swarm conversation: pasted or dropped into the composer,
+// uploaded in parts before the message, and shown as thumbnails.
+import 'dart:convert';
+import 'dart:io';
+
+import 'package:flutter/foundation.dart';
+import 'package:flutter/material.dart';
+import 'package:flutter/services.dart';
+import 'package:flutter_test/flutter_test.dart';
+import 'package:harness/state/harness_attachments.dart';
+import 'package:harness/super_tabs/attachments.dart';
+import 'package:harness/super_tabs/view.dart';
+
+import 'support/super_tab_fixture.dart';
+
+/// A real 1×1 PNG, so a thumbnail has something to draw.
+final _png = base64Decode(
+ 'iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAYAAAAfFcSJAAAADUlEQVR42mNkYPhfDwAChwGA'
+ '60e6kgAAAABJRU5ErkJggg==',
+);
+
+/// A PNG header followed by enough bytes to need two parts.
+Uint8List _large() =>
+ Uint8List(kSuperTabImagePartBytes + 10)..setRange(0, _png.length, _png);
+
+void main() {
+ test('only PNG, JPEG and WebP images, four at most and 5 MB each', () {
+ final images = SuperTabImages();
+ addTearDown(images.dispose);
+ expect(
+ images.add([
+ HarnessAttachment(
+ 'notes.pdf',
+ Uint8List.fromList('%PDF-1.7'.codeUnits),
+ ),
+ HarnessAttachment('cat.gif', Uint8List.fromList('GIF89a'.codeUnits)),
+ ]),
+ '2 files are not PNG, JPEG or WebP images.',
+ );
+ expect(
+ images.add([
+ HarnessAttachment(
+ 'huge.png',
+ Uint8List(kSuperTabImageMaxBytes + 1)..setRange(0, 8, _png),
+ ),
+ ]),
+ 'huge.png is over 5 MB.',
+ );
+ final jpeg = Uint8List.fromList([0xFF, 0xD8, 0xFF, 0xE0]);
+ final webp = Uint8List.fromList([
+ ...'RIFF'.codeUnits,
+ 0,
+ 0,
+ 0,
+ 0,
+ ...'WEBP'.codeUnits,
+ ]);
+ expect(
+ images.addPasted([
+ for (var i = 0; i < 3; i++) HarnessAttachment('shot.png', _png),
+ HarnessAttachment('photo.jpg', jpeg),
+ HarnessAttachment('art.webp', webp),
+ ]),
+ 'A message can carry up to 4 images.',
+ );
+ expect(images.files.map((f) => f.name), [
+ 'shot.png',
+ 'shot-2.png',
+ 'shot-3.png',
+ 'photo.jpg',
+ ]);
+ });
+
+ test('images upload in parts before an image-only send, and only their IDs are saved', () async {
+ final server = ConversationServer();
+ final c = server.controller();
+ addTearDown(c.dispose);
+ await c.refresh();
+ final large = _large();
+ c.images('lead').add([HarnessAttachment('shot.png', large)]);
+ final sent = await c.send();
+ expect(sent, isNotNull);
+ expect(server.uploads, hasLength(2));
+ expect(server.uploads.first, {
+ 'name': 'shot.png',
+ 'size': large.length,
+ 'data': base64Encode(large.sublist(0, kSuperTabImagePartBytes)),
+ });
+ final command = server.posts.single['command'] as Map;
+ expect(command['text'], '');
+ expect(command['attachmentIds'], ['image-1']);
+ expect(c.images('lead').isEmpty, isTrue);
+ expect(
+ jsonEncode(server.saved),
+ isNot(contains(server.uploads.last['data'])),
+ );
+
+ final message = c.messages('lead').single;
+ expect(message.text, '[image]');
+ expect(message.shownText, '');
+ expect(message.preview, 'Image');
+ final attachment = message.attachments.single;
+ expect(attachment.parts, 2);
+ expect(await c.attachmentBytes(attachment), large);
+ });
+
+ test(
+ 'a failed upload sends nothing and keeps the images for a retry',
+ () async {
+ final server = ConversationServer()..failUploads = true;
+ final c = server.controller();
+ addTearDown(c.dispose);
+ await c.refresh();
+ c.setDraft('lead', 'See the screenshot');
+ c.images('lead').add([HarnessAttachment('shot.png', _png)]);
+ expect(await c.send(), isNull);
+ expect(server.posts, isEmpty);
+ expect(c.operationError, 'Could not upload the image. Try again.');
+ expect(c.images('lead').files, hasLength(1));
+ server.failUploads = false;
+ expect(await c.send(), isNotNull);
+ expect(
+ (server.posts.single['command'] as Map)['text'],
+ 'See the screenshot',
+ );
+ expect(c.images('lead').isEmpty, isTrue);
+ },
+ );
+
+ test('an interrupted upload resumes with its missing parts', () async {
+ final server = ConversationServer()..failUploadAt = 2;
+ final c = server.controller();
+ addTearDown(c.dispose);
+ await c.refresh();
+ final large = Uint8List(2 * kSuperTabImagePartBytes + 3)
+ ..setRange(0, _png.length, _png);
+ c.images('lead').add([HarnessAttachment('shot.png', large)]);
+ expect(await c.send(), isNull);
+ expect(await c.send(), isNotNull);
+ expect(server.uploads.where((u) => u.containsKey('name')), hasLength(1));
+ expect(server.uploads, hasLength(4));
+ expect(
+ await c.attachmentBytes(c.messages('lead').single.attachments.single),
+ large,
+ );
+ });
+
+ test('a removed or replaced image is deleted from the backend', () async {
+ final server = ConversationServer()..failUploadAt = 2;
+ final c = server.controller();
+ addTearDown(c.dispose);
+ await c.refresh();
+ final images = c.images('lead');
+ images.add([HarnessAttachment('shot.png', _large())]);
+ expect(await c.send(), isNull);
+ images.add([HarnessAttachment('shot.png', _png)]);
+ await pumpEventQueue();
+ expect(server.deletedAttachments, ['image-1']);
+ images.add([HarnessAttachment('two.png', _large())]);
+ server.failUploadAt = 5;
+ expect(await c.send(), isNull);
+ expect(server.attachments.keys, ['image-2', 'image-3']);
+ images.remove(images.files.last);
+ await pumpEventQueue();
+ expect(server.deletedAttachments, ['image-1', 'image-3']);
+ });
+
+ testWidgets('a copied file that is not an image pastes its name as text', (
+ tester,
+ ) async {
+ final dir = Directory.systemTemp.createTempSync('swarm-paste-');
+ addTearDown(() => dir.deleteSync(recursive: true));
+ final notes = File('${dir.path}/notes.txt')..writeAsStringSync('hello');
+ debugDefaultTargetPlatformOverride = TargetPlatform.macOS;
+ final messenger =
+ TestDefaultBinaryMessengerBinding.instance.defaultBinaryMessenger;
+ messenger.setMockMethodCallHandler(SystemChannels.platform, (call) async {
+ return switch (call.method) {
+ 'Clipboard.getData' => {'text': 'notes.txt'},
+ 'Clipboard.hasStrings' => {'value': true},
+ _ => null,
+ };
+ });
+ const clipboard = MethodChannel('harness/clipboard_image');
+ messenger.setMockMethodCallHandler(clipboard, (call) async {
+ return switch (call.method) {
+ 'readImagePng' => _png,
+ 'readFilePaths' => [notes.path],
+ _ => null,
+ };
+ });
+ addTearDown(() {
+ messenger.setMockMethodCallHandler(SystemChannels.platform, null);
+ messenger.setMockMethodCallHandler(clipboard, null);
+ });
+ await tester.binding.setSurfaceSize(const Size(1100, 720));
+ addTearDown(() => tester.binding.setSurfaceSize(null));
+ final server = ConversationServer();
+ final c = server.controller();
+ await tester.runAsync(c.refresh);
+ await tester.pumpWidget(
+ MaterialApp(
+ home: Scaffold(
+ body: SuperTabView(
+ controller: c,
+ onInvite: () {},
+ onAddAgent: (_) {},
+ onOpenTerminal: (_) {},
+ machineName: (_) => 'Team Mac',
+ ),
+ ),
+ ),
+ );
+ await tester.pumpAndSettle();
+ await tester.tap(find.byKey(const ValueKey('super-message-composer')));
+ await tester.runAsync(() async {
+ await tester.sendKeyDownEvent(LogicalKeyboardKey.metaLeft);
+ await tester.sendKeyEvent(LogicalKeyboardKey.keyV);
+ await tester.sendKeyUpEvent(LogicalKeyboardKey.metaLeft);
+ await Future<void>.delayed(const Duration(milliseconds: 100));
+ });
+ await tester.pumpAndSettle();
+ expect(find.byKey(const ValueKey('super-composer-images')), findsNothing);
+ expect(
+ tester
+ .widget<TextField>(
+ find.byKey(const ValueKey('super-message-composer')),
+ )
+ .controller!
+ .text,
+ 'notes.txt',
+ );
+ await tester.pumpWidget(const SizedBox());
+ c.dispose();
+ debugDefaultTargetPlatformOverride = null;
+ });
+
+ testWidgets('a pasted screenshot is a chip until sent, then a thumbnail', (
+ tester,
+ ) async {
+ debugDefaultTargetPlatformOverride = TargetPlatform.macOS;
+ final messenger =
+ TestDefaultBinaryMessengerBinding.instance.defaultBinaryMessenger;
+ messenger.setMockMethodCallHandler(SystemChannels.platform, (call) async {
+ return call.method == 'Clipboard.hasStrings' ? {'value': false} : null;
+ });
+ const clipboard = MethodChannel('harness/clipboard_image');
+ messenger.setMockMethodCallHandler(clipboard, (call) async {
+ return switch (call.method) {
+ 'readImagePng' => _png,
+ 'readFilePaths' => <String>[],
+ _ => null,
+ };
+ });
+ addTearDown(() {
+ messenger.setMockMethodCallHandler(SystemChannels.platform, null);
+ messenger.setMockMethodCallHandler(clipboard, null);
+ });
+ await tester.binding.setSurfaceSize(const Size(1100, 720));
+ addTearDown(() => tester.binding.setSurfaceSize(null));
+ final server = ConversationServer();
+ final c = server.controller();
+ await tester.runAsync(c.refresh);
+ await tester.pumpWidget(
+ MaterialApp(
+ home: Scaffold(
+ body: SuperTabView(
+ controller: c,
+ onInvite: () {},
+ onAddAgent: (_) {},
+ onOpenTerminal: (_) {},
+ machineName: (_) => 'Team Mac',
+ ),
+ ),
+ ),
+ );
+ await tester.pumpAndSettle();
+ await tester.tap(find.byKey(const ValueKey('super-message-composer')));
+ await tester.sendKeyDownEvent(LogicalKeyboardKey.metaLeft);
+ await tester.sendKeyEvent(LogicalKeyboardKey.keyV);
+ await tester.sendKeyUpEvent(LogicalKeyboardKey.metaLeft);
+ await tester.pumpAndSettle();
+ expect(find.byKey(const ValueKey('super-composer-images')), findsOneWidget);
+ expect(
+ find.byKey(const ValueKey('new-harness-attachment:pasted-image.png')),
+ findsOneWidget,
+ );
+
+ await tester.tap(find.byTooltip('Send message'));
+ await tester.pumpAndSettle();
+ expect(find.byKey(const ValueKey('super-composer-images')), findsNothing);
+ expect((server.posts.single['command'] as Map)['attachmentIds'], [
+ 'image-1',
+ ]);
+ await tester.pumpAndSettle();
+ expect(
+ find.byKey(const ValueKey('super-message-image:image-1')),
+ findsOneWidget,
+ );
+ await tester.pumpWidget(const SizedBox());
+ c.dispose();
+ debugDefaultTargetPlatformOverride = null;
+ });
+}
diff --git a/desktop/test/support/super_tab_fixture.dart b/desktop/test/support/super_tab_fixture.dart
index da06b3ca6..8bed9b01f 100644
--- a/desktop/test/support/super_tab_fixture.dart
+++ b/desktop/test/support/super_tab_fixture.dart
@@ -42,6 +42,16 @@ class ConversationServer {
final routeDecisions = <String, Map<String, dynamic>>{};
// The effective routing policy answered by GET .../routing-policy.
Map<String, dynamic>? routingPolicy;
+ // Uploaded images by id: their metadata and base64 parts in order.
+ final attachments = <String, Map<String, dynamic>>{};
+ final attachmentParts = <String, List<String?>>{};
+ // Every attachment upload body, apart from [posts].
+ final uploads = <Map<String, dynamic>>[];
+ // Unsent uploads the client deleted.
+ final deletedAttachments = <String>[];
+ bool failUploads = false;
+ // Fails the upload request with this 1-based number, once.
+ int? failUploadAt;
final state = <String, dynamic>{
'version': 1,
'id': 'tab',
@@ -84,6 +94,10 @@ class ConversationServer {
String path, {
Map<String, dynamic>? body,
}) async {
+ final segments = Uri.parse(path).pathSegments;
+ if (segments.length > 3 && segments[3] == 'attachments') {
+ return _attachment(method, segments, body);
+ }
if (method == 'POST') {
posts.add(Map<String, dynamic>.from(body!));
if (reject) {
@@ -105,11 +119,19 @@ class ConversationServer {
final command = body['command'] as Map;
final output = <String, dynamic>{};
if (command['type'] == 'message.send') {
+ final images = (command['attachmentIds'] as List? ?? const []).length;
+ // As the backend stores a message of images alone.
append(
- command['text'] as String,
+ (command['text'] as String).isEmpty && images > 0
+ ? (images == 1 ? '[image]' : '[$images images]')
+ : command['text'] as String,
conversationId: command['conversationId'] as String,
);
messages.last['replyTo'] = command['replyTo'];
+ messages.last['attachments'] = [
+ for (final id in command['attachmentIds'] as List? ?? const [])
+ attachments[id],
+ ];
output['messageId'] = 'message-$revision';
} else if (command['type'] == 'conversation.create') {
revision++;
@@ -229,6 +251,60 @@ class ConversationServer {
as Map<String, dynamic>;
}
+ Map<String, dynamic> _attachment(
+ String method,
+ List<String> segments,
+ Map<String, dynamic>? body,
+ ) {
+ final parts = segments.length > 4 ? attachmentParts[segments[4]] : null;
+ if (segments.length > 4 && parts == null) {
+ throw const SuperTabFailure('NOT_FOUND', 'This image is unavailable.');
+ }
+ if (method == 'DELETE') {
+ attachments.remove(segments[4]);
+ attachmentParts.remove(segments[4]);
+ deletedAttachments.add(segments[4]);
+ return {'id': segments[4], 'deleted': true};
+ }
+ if (method == 'GET' && segments.length == 5) {
+ final missing = [
+ for (var i = 0; i < parts!.length; i++)
+ if (parts[i] == null) i,
+ ];
+ return {
+ ...attachments[segments[4]]!,
+ 'complete': missing.isEmpty,
+ if (missing.isNotEmpty) 'missing': missing,
+ };
+ }
+ if (method == 'GET') return {'data': parts![int.parse(segments[6])]};
+ uploads.add(Map<String, dynamic>.from(body!));
+ if (failUploads || failUploadAt == uploads.length) {
+ failUploadAt = null;
+ throw StateError('Connection lost');
+ }
+ if (segments.length == 4) {
+ final id = 'image-${uploads.where((u) => u.containsKey('name')).length}';
+ final size = body['size'] as int;
+ attachments[id] = {
+ 'id': id,
+ 'name': body['name'],
+ 'mime': 'image/png',
+ 'size': size,
+ 'width': null,
+ 'height': null,
+ 'parts': (size / (256 * 1024)).ceil(),
+ };
+ attachmentParts[id] = [
+ body['data'] as String,
+ for (var i = 1; i < (attachments[id]!['parts'] as int); i++) null,
+ ];
+ return {...attachments[id]!, 'complete': size <= 256 * 1024};
+ }
+ parts![int.parse(segments[6])] = body['data'] as String;
+ return {'id': segments[4], 'complete': !parts.contains(null)};
+ }
+
SuperTabController controller({
Map<String, dynamic>? initial,
String account = 'owner',