Skip to content

Where agent teams gather. Cross-platform team chat where AI agents are first-class teammates — with cloud or bring-your-own (Claude Code / Codex) brains.

TypeScript

feat: add multi-attachment message foundation (#360)

Streliziaeaf9c24ffe39
diff --git a/server/src/__tests__/attachments.test.ts b/server/src/__tests__/attachments.test.ts
new file mode 100644
index 0000000..0f4eeb1
--- /dev/null
+++ b/server/src/__tests__/attachments.test.ts
@@ -0,0 +1,80 @@
+import assert from 'node:assert/strict'
+import { test } from 'node:test'
+import {
+ ATTACHMENT_MAX_FILES,
+ ATTACHMENT_MAX_FILE_BYTES,
+ ATTACHMENT_MAX_TOTAL_BYTES,
+ normalizeAttachments,
+ validateAttachmentInput,
+ type AttachmentDescriptor,
+} from '../../../shared/attachments.js'
+
+const file = (name: string, size?: number): AttachmentDescriptor => ({
+ name,
+ kind: 'file',
+ url: `/uploads/attachments/${name}`,
+ ...(size === undefined ? {} : { size }),
+})
+
+test('policy constants are 16 files, 25 MiB aggregate, 25 MiB each', () => {
+ assert.equal(ATTACHMENT_MAX_FILES, 16)
+ assert.equal(ATTACHMENT_MAX_FILE_BYTES, 25 * 1024 * 1024)
+ assert.equal(ATTACHMENT_MAX_TOTAL_BYTES, 25 * 1024 * 1024)
+})
+
+test('a legacy single attachment normalizes to one entry without changing it', () => {
+ const legacy = { name: 'report.pdf', kind: 'pdf', url: '/uploads/attachments/report.pdf', mime: 'APPLICATION/PDF' } as const
+ assert.deepEqual(normalizeAttachments(legacy), [{ ...legacy, mime: 'application/pdf' }])
+})
+
+test('a canonical attachment list preserves order', () => {
+ const attachments = [file('one.txt'), { name: 'two.png', kind: 'img', key: 'attachments/two.png' }] as const
+ const parsed = validateAttachmentInput(attachments)
+ assert.equal(parsed.ok, true)
+ if (parsed.ok) assert.deepEqual(parsed.attachments, attachments)
+})
+
+test('null, undefined, and an empty list normalize to no attachments', () => {
+ for (const value of [null, undefined, []]) assert.deepEqual(normalizeAttachments(value), [])
+})
+
+test('malformed or non-canonical descriptors reject the entire input', () => {
+ for (const value of [
+ {},
+ { name: '', kind: 'file', url: '/uploads/a' },
+ { name: 'x', kind: 'exe', url: '/uploads/a' },
+ { name: 'x', kind: 'file' },
+ { name: 'x', kind: 'file', url: ' ' },
+ { name: 'x', kind: 'file', url: '/uploads/a', size: -1 },
+ { name: 'x', kind: 'file', url: '/uploads/a', size: 1.5 },
+ [file('valid.txt'), null],
+ ]) {
+ const parsed = validateAttachmentInput(value)
+ assert.equal(parsed.ok, false, JSON.stringify(value))
+ if (!parsed.ok) assert.equal(parsed.issue, 'invalid-shape')
+ }
+})
+
+test('legacy render-only meta descriptors survive normalization', () => {
+ const parsed = validateAttachmentInput({ name: 'mock.pdf', kind: 'pdf', meta: '12 pages' })
+ assert.deepEqual(parsed, { ok: true, attachments: [{ name: 'mock.pdf', kind: 'pdf', meta: '12 pages' }] })
+})
+
+test('file count, per-file, and aggregate limits are enforced', () => {
+ assert.deepEqual(
+ validateAttachmentInput(Array.from({ length: 17 }, (_, index) => file(`${index}.txt`))),
+ { ok: false, issue: 'too-many-files' },
+ )
+ assert.deepEqual(
+ validateAttachmentInput(file('huge.bin', ATTACHMENT_MAX_FILE_BYTES + 1)),
+ { ok: false, issue: 'file-too-large', index: 0 },
+ )
+ assert.deepEqual(
+ validateAttachmentInput([
+ file('one.bin', 13 * 1024 * 1024),
+ file('two.bin', 13 * 1024 * 1024),
+ ]),
+ { ok: false, issue: 'total-too-large', index: 1 },
+ )
+ assert.equal(validateAttachmentInput(Array.from({ length: 16 }, (_, index) => file(`${index}.txt`))).ok, true)
+})
diff --git a/server/src/__tests__/composer-drafts.test.ts b/server/src/__tests__/composer-drafts.test.ts
index 023d482..72a828f 100644
--- a/server/src/__tests__/composer-drafts.test.ts
+++ b/server/src/__tests__/composer-drafts.test.ts
@@ -38,10 +38,11 @@ test('a thread composer does not share text with its conversation', () => {
assert.equal(d['convo-1::thread::m-9'].text, 'thread')
})
-test('an attachment rides along with the text', () => {
+test('multiple attachments ride along with the text in order', () => {
// Dropping it would strand a file the user already uploaded.
- const d = applyDraftUpdate({}, 'c', (c) => ({ ...c, attachment: att }))
- assert.deepEqual(d.c.attachment, att)
+ const second = { ...att, name: 'y.pdf', url: 'https://cdn.example/y.pdf' }
+ const d = applyDraftUpdate({}, 'c', (c) => ({ ...c, attachments: [att, second] }))
+ assert.deepEqual(d.c.attachments, [att, second])
assert.equal(d.c.text, '')
})
@@ -55,9 +56,9 @@ test('emptying a draft deletes it rather than leaving a tombstone', () => {
})
test('clearing text but keeping an attachment keeps the draft', () => {
- let d = applyDraftUpdate({}, 'c', (c) => ({ text: 'x', attachment: att }))
+ let d = applyDraftUpdate({}, 'c', (c) => ({ text: 'x', attachments: [att] }))
d = applyDraftUpdate(d, 'c', (c) => ({ ...c, text: '' }))
- assert.deepEqual(d.c, { text: '', attachment: att })
+ assert.deepEqual(d.c, { text: '', attachments: [att] })
})
test('an unchanged update returns the SAME object', () => {
@@ -99,26 +100,32 @@ test('touching an old draft protects it from eviction', () => {
// ── what comes back from storage is not trusted ─────────────────────────────
-test('a round trip preserves text and attachment', () => {
- const d = applyDraftUpdate({}, 'c', () => ({ text: 'hello', attachment: att }))
+test('a round trip preserves text and ordered attachments', () => {
+ const second = { ...att, name: 'y.pdf', url: 'https://cdn.example/y.pdf' }
+ const d = applyDraftUpdate({}, 'c', () => ({ text: 'hello', attachments: [att, second] }))
assert.deepEqual(parseStoredDrafts(serializeDrafts(d)), d)
})
+test('a legacy single-attachment draft is migrated to an array', () => {
+ const raw = JSON.stringify({ c: { text: 'hello', attachment: att } })
+ assert.deepEqual(parseStoredDrafts(raw), { c: { text: 'hello', attachments: [att] } })
+})
+
test('garbage in storage yields no drafts instead of throwing', () => {
for (const raw of [null, '', 'not json', '[]', '"str"', '3', '{"c":null}', '{"c":5}']) {
assert.deepEqual(parseStoredDrafts(raw), {}, JSON.stringify(raw))
}
})
-test('a malformed attachment is dropped, not replayed into the composer', () => {
+test('a malformed legacy attachment is dropped, not replayed into the composer', () => {
// This value is handed to the send path; a half-parsed one must not survive.
const raw = JSON.stringify({ c: { text: 'hi', attachment: { url: 'u' } } }) // no name/kind
- assert.deepEqual(parseStoredDrafts(raw), { c: { text: 'hi', attachment: null } })
+ assert.deepEqual(parseStoredDrafts(raw), { c: { text: 'hi', attachments: [] } })
})
test('an unknown attachment kind is rejected', () => {
const raw = JSON.stringify({ c: { text: 't', attachment: { ...att, kind: 'exe' } } })
- assert.equal(parseStoredDrafts(raw).c.attachment, null)
+ assert.deepEqual(parseStoredDrafts(raw).c.attachments, [])
})
test('stored entries that decode to empty are not resurrected', () => {
@@ -150,7 +157,7 @@ test('evict is a no-op below the cap and preserves identity', () => {
})
test('isEmptyDraft only calls a draft empty when both halves are', () => {
- assert.equal(isEmptyDraft({ text: '', attachment: null }), true)
- assert.equal(isEmptyDraft({ text: ' ', attachment: null }), false)
- assert.equal(isEmptyDraft({ text: '', attachment: att }), false)
+ assert.equal(isEmptyDraft({ text: '', attachments: [] }), true)
+ assert.equal(isEmptyDraft({ text: ' ', attachments: [] }), false)
+ assert.equal(isEmptyDraft({ text: '', attachments: [att] }), false)
})
diff --git a/server/src/__tests__/conversation-membership-source.test.ts b/server/src/__tests__/conversation-membership-source.test.ts
index 5f94bee..fc79ab3 100644
--- a/server/src/__tests__/conversation-membership-source.test.ts
+++ b/server/src/__tests__/conversation-membership-source.test.ts
@@ -24,9 +24,10 @@ async function productionTypeScriptFiles(root: string): Promise<string[]> {
test('production authorization and routing never use the JSONB membership projection', async () => {
const violations: string[] = []
for (const path of await productionTypeScriptFiles(serverSource)) {
+ const relativePath = relative(serverSource, path).replaceAll('\\', '/')
// Migration 0001 is frozen historical SQL and deliberately retains its
// old containment index and compatibility helpers.
- if (relative(serverSource, path) === 'db/migrate.ts') continue
+ if (relativePath === 'db/migrate.ts') continue
const source = await readFile(path, 'utf8')
for (const pattern of [
/members\s*@>/g,
@@ -34,7 +35,7 @@ test('production authorization and routing never use the JSONB membership projec
/jsonb_array_elements_text\([^\n]*members/g,
/\.members\.includes\(/g,
]) {
- if (pattern.test(source)) violations.push(`${relative(serverSource, path)}: ${pattern.source}`)
+ if (pattern.test(source)) violations.push(`${relativePath}: ${pattern.source}`)
}
}
assert.deepEqual(violations, [])
diff --git a/server/src/__tests__/message-attachments.test.ts b/server/src/__tests__/message-attachments.test.ts
new file mode 100644
index 0000000..baee11f
--- /dev/null
+++ b/server/src/__tests__/message-attachments.test.ts
@@ -0,0 +1,226 @@
+import assert from 'node:assert/strict'
+import { randomUUID } from 'node:crypto'
+import { mkdir, rm } from 'node:fs/promises'
+import { basename, dirname, join } from 'node:path'
+import { test } from 'node:test'
+
+process.env.OPENAI_API_KEY ??= 'test-key'
+const {
+ ATTACHMENT_MAX_FILE_BYTES,
+ ATTACHMENT_MAX_FILES,
+} = await import('../../../shared/attachments.js')
+const {
+ freshenMessageAttachments,
+ resolveMessageAttachments,
+ storage,
+ UPLOAD_DIR,
+ validateChatUpload,
+} = await import('../storage.js')
+import type { AttachmentDescriptor } from '../../../shared/attachments.js'
+import type { StoredObjectMetadata } from '../storage.js'
+
+const attachment = (name: string, extra: Partial<AttachmentDescriptor> = {}): AttachmentDescriptor => ({
+ name,
+ kind: 'file',
+ key: `attachments/${name}`,
+ ...extra,
+})
+
+function backend(objects: Record<string, StoredObjectMetadata>) {
+ return {
+ async statObject(key: string) {
+ return objects[key] ?? null
+ },
+ async publicUrl(key: string) {
+ return `https://files.test/${key}?fresh=1`
+ },
+ }
+}
+
+test('legacy singular input resolves to an ordered canonical list', async () => {
+ const key = 'attachments/legacy.txt'
+ const result = await resolveMessageAttachments(
+ attachment('legacy.txt'),
+ backend({ [key]: { key, sizeBytes: 12, mime: 'text/plain' } }),
+ )
+ assert.equal(result.ok, true)
+ if (!result.ok) return
+ assert.deepEqual(result.attachments, [{
+ name: 'legacy.txt', kind: 'file', key,
+ url: 'https://files.test/attachments/legacy.txt?fresh=1',
+ mime: 'text/plain', size: 12,
+ }])
+})
+
+test('multi-file input preserves order and derives kind, size, and MIME from storage', async () => {
+ const keys = ['attachments/second.png', 'attachments/first.pdf']
+ const result = await resolveMessageAttachments(
+ [
+ attachment('second.png', { kind: 'pdf', size: 3 }),
+ attachment('first.pdf', { kind: 'img', size: 5 }),
+ ],
+ backend({
+ [keys[0]]: { key: keys[0], sizeBytes: 3, mime: 'image/png' },
+ [keys[1]]: { key: keys[1], sizeBytes: 5, mime: 'application/pdf' },
+ }),
+ )
+ assert.equal(result.ok, true)
+ if (!result.ok) return
+
+ const trusted = await resolveMessageAttachments(
+ [
+ attachment('second.png', { size: 3 }),
+ attachment('first.pdf', { size: 5 }),
+ ],
+ backend({
+ [keys[0]]: { key: keys[0], sizeBytes: 3, mime: 'image/png' },
+ [keys[1]]: { key: keys[1], sizeBytes: 5, mime: 'application/pdf' },
+ }),
+ )
+ assert.equal(trusted.ok, true)
+ if (!trusted.ok) return
+ assert.deepEqual(trusted.attachments.map(({ name, kind, size, mime }) => ({ name, kind, size, mime })), [
+ { name: 'second.png', kind: 'img', size: 3, mime: 'image/png' },
+ { name: 'first.pdf', kind: 'pdf', size: 5, mime: 'application/pdf' },
+ ])
+})
+
+test('missing object is rejected before persistence', async () => {
+ const result = await resolveMessageAttachments(attachment('missing.txt'), backend({}))
+ assert.deepEqual(result, {
+ ok: false,
+ status: 400,
+ error: 'attachment object does not exist',
+ index: 0,
+ })
+})
+
+test('message attachment resolution requires an active tenant grant when supplied', async () => {
+ const key = 'attachments/granted.txt'
+ const result = await resolveMessageAttachments(
+ attachment('granted.txt'),
+ backend({ [key]: { key, sizeBytes: 4, mime: 'text/plain' } }),
+ { attachmentGrant: async () => false },
+ )
+ assert.deepEqual(result, {
+ ok: false,
+ status: 400,
+ error: 'attachment is not granted to this workspace',
+ index: 0,
+ })
+})
+
+test('local object lookup ignores only missing MIME sidecars', {
+ skip: storage.mode !== 'local',
+}, async () => {
+ const name = `sidecar-${randomUUID()}.txt`
+ const key = `attachments/${name}`
+ const objectPath = join(UPLOAD_DIR, key)
+ const sidecarPath = join(UPLOAD_DIR, dirname(key), `${basename(key)}.cumora-mime`)
+ try {
+ await storage.put(key, Buffer.from('body'), 'text/plain')
+ await rm(sidecarPath)
+ const metadata = await storage.statObject(key)
+ assert.equal(metadata?.sizeBytes, 4)
+ assert.equal(metadata?.mime, undefined)
+
+ await mkdir(sidecarPath)
+ await assert.rejects(storage.statObject(key), (error: unknown) => {
+ assert.notEqual((error as NodeJS.ErrnoException).code, 'ENOENT')
+ return true
+ })
+ } finally {
+ await Promise.all([
+ rm(objectPath, { force: true }),
+ rm(sidecarPath, { recursive: true, force: true }),
+ ])
+ }
+})
+
+test('declared and actual sizes must match exactly', async () => {
+ const key = 'attachments/report.pdf'
+ const result = await resolveMessageAttachments(
+ attachment('report.pdf', { size: 10 }),
+ backend({ [key]: { key, sizeBytes: 11, mime: 'application/pdf' } }),
+ )
+ assert.deepEqual(result, {
+ ok: false,
+ status: 400,
+ error: 'attachment size does not match uploaded object',
+ index: 0,
+ })
+})
+
+test('forged MIME is rejected', async () => {
+ const key = 'attachments/script.txt'
+ const result = await resolveMessageAttachments(
+ attachment('script.txt', { mime: 'text/html' }),
+ backend({ [key]: { key, sizeBytes: 1, mime: 'text/plain' } }),
+ )
+ assert.deepEqual(result, {
+ ok: false,
+ status: 400,
+ error: 'attachment MIME does not match uploaded object',
+ index: 0,
+ })
+})
+
+test('file count and total storage size are enforced', async () => {
+ const tooMany = Array.from({ length: ATTACHMENT_MAX_FILES + 1 }, (_, index) => attachment(`${index}.txt`))
+ assert.deepEqual(await resolveMessageAttachments(tooMany, backend({})), {
+ ok: false,
+ status: 413,
+ error: 'too many attachments (maximum 16)',
+ })
+
+ const keys = ['attachments/a.bin', 'attachments/b.bin']
+ const result = await resolveMessageAttachments(
+ keys.map((key, index) => ({ name: `${index}.bin`, kind: 'file', key })),
+ backend({
+ [keys[0]]: { key: keys[0], sizeBytes: 13 * 1024 * 1024, mime: 'application/zip' },
+ [keys[1]]: { key: keys[1], sizeBytes: 13 * 1024 * 1024, mime: 'application/zip' },
+ }),
+ )
+ assert.deepEqual(result, {
+ ok: false,
+ status: 413,
+ error: 'attachments exceed 25 MiB total',
+ index: 1,
+ })
+})
+
+test('actual stored object over the per-file limit is rejected', async () => {
+ const key = 'attachments/huge.zip'
+ const result = await resolveMessageAttachments(
+ attachment('huge.zip'),
+ backend({ [key]: { key, sizeBytes: ATTACHMENT_MAX_FILE_BYTES + 1, mime: 'application/zip' } }),
+ )
+ assert.deepEqual(result, {
+ ok: false,
+ status: 413,
+ error: 'attachment object size is invalid (maximum 25 MiB)',
+ index: 0,
+ })
+})
+
+test('response freshening retains all entries and sets the legacy first entry', async () => {
+ const result = await freshenMessageAttachments([
+ attachment('one.txt', { url: '/uploads/attachments/one.txt' }),
+ attachment('two.txt', { url: '/uploads/attachments/two.txt' }),
+ ])
+ assert.deepEqual(result.attachments.map((item) => item.name), ['one.txt', 'two.txt'])
+ assert.deepEqual(result.attachment, result.attachments[0])
+})
+
+test('presign validation caps the declared Content-Length at 25 MiB', () => {
+ assert.deepEqual(validateChatUpload({
+ name: 'note.txt', mime: 'text/plain', size: ATTACHMENT_MAX_FILE_BYTES + 1,
+ }), {
+ ok: false,
+ status: 413,
+ error: `size out of range (got ${ATTACHMENT_MAX_FILE_BYTES + 1}, max ${ATTACHMENT_MAX_FILE_BYTES})`,
+ })
+ assert.deepEqual(validateChatUpload({ name: 'note.txt', mime: 'text/plain', size: 12 }), {
+ ok: true, name: 'note.txt', mime: 'text/plain', size: 12, kind: 'file',
+ })
+})
diff --git a/server/src/__tests__/schema-migrations.test.ts b/server/src/__tests__/schema-migrations.test.ts
index 806337d..cb645ee 100644
--- a/server/src/__tests__/schema-migrations.test.ts
+++ b/server/src/__tests__/schema-migrations.test.ts
@@ -23,6 +23,8 @@ const { agentProviderProfileChecksum } = await import('../db/migrations/0008-age
const { agentRoutingClaimsChecksum } = await import('../db/migrations/0009-agent-routing-claims.js')
const { boardCardDueOnChecksum } = await import('../db/migrations/0010-board-card-due-on.js')
const { agentNativeFastModeChecksum } = await import('../db/migrations/0011-agent-native-fast-mode.js')
+const { messageAttachmentsChecksum } = await import('../db/migrations/0012-message-attachments.js')
+const { attachmentGrantsChecksum } = await import('../db/migrations/0013-attachment-grants.js')
const { verifySchemaCompatibility } = await import('../db/schema-version.js')
type SchemaVersionQueryable = import('../db/schema-version.js').SchemaVersionQueryable
@@ -72,6 +74,14 @@ test('the native Fast Mode migration matches its immutable manifest checksum', (
assert.equal(agentNativeFastModeChecksum(), SCHEMA_MIGRATIONS[10].checksum)
})
+test('the message attachments migration matches its immutable manifest checksum', () => {
+ assert.equal(messageAttachmentsChecksum(), SCHEMA_MIGRATIONS[11].checksum)
+})
+
+test('the attachment grants migration matches its immutable manifest checksum', () => {
+ assert.equal(attachmentGrantsChecksum(), SCHEMA_MIGRATIONS[12].checksum)
+})
+
test('the migration owner accepts an exact prefix and reports its pending suffix', () => {
const empty = validateMigrationHistory([], { allowPending: true })
assert.equal(empty.currentVersion, 0)
diff --git a/server/src/api/router.ts b/server/src/api/router.ts
index 0a5492a..6d21f11 100644
--- a/server/src/api/router.ts
+++ b/server/src/api/router.ts
@@ -13,8 +13,10 @@ import { isProviderProfileId } from '../agents/computer/provider-profiles.js'
import { InvalidModelIdError, parseModelId } from '../agents/computer/model-id.js'
import type { PoolClient } from 'pg'
import {
- storage, UPLOAD_DIR, freshenAttachmentUrl, normalizeStorageKey,
+ storage, UPLOAD_DIR, normalizeStorageKey,
storageKeyFromPublicUrl, messageAttachmentStorageKey,
+ CHAT_ATTACHMENT_MIME_POLICY, freshenMessageAttachments,
+ resolveMessageAttachments, validateChatUpload,
} from '../storage.js'
import { healthPool, pool } from '../db/pool.js'
import { CH_MESSAGE_NEW, CH_REACTIONS, CH_CONVO_UPDATED, CH_DOCS, CH_TYPING, CH_CALENDAR_EVENTS, CH_BOARDS, CH_STATUS, CH_WORKSPACES, publish } from '../redis.js'
@@ -60,6 +62,7 @@ import { attachComputerControlStream, deliverEngineDetect, deliverEngineUpdate }
import { getEngineUpdate, reportEngineUpdate, startEngineUpdate } from '../agents/computer/engine-update.js'
import { companyTier } from '../tier.js'
import { createShippingRouter } from './shipping-router.js'
+import { grantAttachment, hasAttachmentGrant, isGrantableAttachmentKey } from '../attachments/grants.js'
import {
findIdempotentCreate, IdempotencyConflictError,
parseRequestId, requestHash,
@@ -79,56 +82,12 @@ export { UPLOAD_DIR }
* content into context. Anything outside this map gets rejected at the
* upload edge.
*/
-const MIME_POLICY: Record<string, { kind: 'img' | 'file'; ext: string }> = {
- // Images — inline preview + vision
- 'image/png': { kind: 'img', ext: 'png' },
- 'image/jpeg': { kind: 'img', ext: 'jpg' },
- 'image/webp': { kind: 'img', ext: 'webp' },
- 'image/gif': { kind: 'img', ext: 'gif' },
- // Documents
- 'application/pdf': { kind: 'file', ext: 'pdf' },
- 'application/msword': { kind: 'file', ext: 'doc' },
- 'application/vnd.openxmlformats-officedocument.wordprocessingml.document': { kind: 'file', ext: 'docx' },
- 'application/vnd.ms-excel': { kind: 'file', ext: 'xls' },
- 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet': { kind: 'file', ext: 'xlsx' },
- 'application/vnd.ms-powerpoint': { kind: 'file', ext: 'ppt' },
- 'application/vnd.openxmlformats-officedocument.presentationml.presentation': { kind: 'file', ext: 'pptx' },
- // Archives
- 'application/zip': { kind: 'file', ext: 'zip' },
- 'application/x-tar': { kind: 'file', ext: 'tar' },
- 'application/gzip': { kind: 'file', ext: 'gz' },
- // Text & code (extractable into agent context)
- 'text/plain': { kind: 'file', ext: 'txt' },
- 'text/markdown': { kind: 'file', ext: 'md' },
- 'text/csv': { kind: 'file', ext: 'csv' },
- // NOTE: text/html is intentionally NOT accepted. An uploaded .html served
- // from the app origin (local-storage mode) would run as the app and could
- // read the localStorage session token — stored XSS → account takeover. The
- // /uploads static handler also forces nosniff + attachment disposition as
- // defense in depth, but the durable fix is never storing active content.
- 'application/json': { kind: 'file', ext: 'json' },
- 'application/x-yaml': { kind: 'file', ext: 'yml' },
- 'application/x-toml': { kind: 'file', ext: 'toml' },
- // Audio / video — light support
- 'audio/mpeg': { kind: 'file', ext: 'mp3' },
- 'audio/wav': { kind: 'file', ext: 'wav' },
- 'video/mp4': { kind: 'file', ext: 'mp4' },
- 'video/quicktime': { kind: 'file', ext: 'mov' },
-}
+/** The shared policy lives in storage.ts so message persistence and upload
+ * routes derive MIME/kind from the same trusted source. */
+const MIME_POLICY = CHAT_ATTACHMENT_MIME_POLICY
const MAX_UPLOAD_BYTES = 25 * 1024 * 1024 // 25 MB (Skype-like ceiling)
-interface AttachmentPayload {
- name: string
- kind: 'img' | 'pdf' | 'file' | 'fig'
- url: string
- mime?: string
- size?: number
- /** Storage key — present when the file lives in object storage; lets us
- * resolve a fresh URL later without re-uploading. */
- key?: string
-}
-
export const api = Router()
// Every request goes through the auth middleware first; handlers that need
@@ -581,23 +540,28 @@ api.post('/uploads/presign', async (req, res) => {
// signed R2 PUT URLs and burn through our storage quota / host arbitrary
// content under our domain. Membership-only is enough — we don't restrict
// uploads by role since attachments are a basic chat affordance.
- await requireCompany(req)
+ const { companyId: tenant } = await requireCompany(req)
if (storage.mode !== 'r2') {
res.status(501).json({ error: 'presign not available in local mode — POST /uploads instead' })
return
}
- const name = String(req.body?.name ?? '').trim().slice(0, 200)
- const mime = String(req.body?.mime ?? '').trim().toLowerCase()
- const size = Number(req.body?.size ?? 0)
- if (!name || !mime) { res.status(400).json({ error: 'name + mime required' }); return }
- if (!Number.isFinite(size) || size <= 0 || size > MAX_UPLOAD_BYTES) {
- res.status(413).json({ error: `size out of range (got ${size}, max ${MAX_UPLOAD_BYTES})` })
+ const checked = validateChatUpload({
+ name: req.body?.name,
+ mime: req.body?.mime,
+ size: req.body?.size,
+ })
+ if (!checked.ok) {
+ res.status(checked.status).json({ error: checked.error })
return
}
- const policy = MIME_POLICY[mime]
+ const { name, mime, size } = checked
const k = attachmentKey(mime)
- if (!policy || !k) { res.status(415).json({ error: `mime not allowed: ${mime}` }); return }
- const signed = await storage.presignPut(k.key, mime)
+ if (!k) { res.status(415).json({ error: `mime not allowed: ${mime}` }); return }
+ const signed = await storage.presignPut(k.key, mime, size)
+ // A presigned object has no DB row yet. Grant the tenant before returning
+ // the URL; message persistence still requires statObject, so an abandoned
+ // presign cannot be referenced as an attachment.
+ await grantAttachment(pool, tenant, k.key)
res.json({
uploadUrl: signed.uploadUrl,
publicUrl: signed.publicUrl,
@@ -605,7 +569,7 @@ api.post('/uploads/presign', async (req, res) => {
name,
mime,
size,
- kind: policy.kind,
+ kind: checked.kind,
})
})
@@ -620,7 +584,7 @@ api.post('/uploads', requireAuthBeforeLargeBody, uploadJsonParser, async (req, r
// Auth + tenant gate. Without this, anyone on the open internet could push
// 25MB blobs into our storage — a DoS + cost vector. Membership-only is
// sufficient since attachments are a baseline chat feature.
- await requireCompany(req)
+ const { companyId: tenant } = await requireCompany(req)
const name = String(req.body?.name ?? '').trim().slice(0, 200)
const mime = String(req.body?.mime ?? '').trim().toLowerCase()
const dataBase64 = String(req.body?.dataBase64 ?? '')
@@ -647,6 +611,7 @@ api.post('/uploads', requireAuthBeforeLargeBody, uploadJsonParser, async (req, r
const k = attachmentKey(mime)
if (!k) { res.status(415).json({ error: `mime not allowed: ${mime}` }); return }
const url = await storage.put(k.key, buf, mime)
+ await grantAttachment(pool, tenant, k.key)
res.json({
url,
key: k.key,
@@ -658,11 +623,14 @@ api.post('/uploads', requireAuthBeforeLargeBody, uploadJsonParser, async (req, r
})
api.post('/uploads/refresh-url', safe(async (req, res) => {
- await requireCompany(req)
+ const { companyId: tenant } = await requireCompany(req)
const url = String(req.body?.url ?? '').trim()
const requestedKey = String(req.body?.key ?? '').trim()
const key = normalizeStorageKey(requestedKey) ?? (url ? storageKeyFromPublicUrl(url) : null)
if (!key) throw new HttpError(400, 'not a Cumora storage URL')
+ if (!isGrantableAttachmentKey(key) || !(await hasAttachmentGrant(pool, tenant, key))) {
+ throw new HttpError(403, 'attachment is not granted to this workspace')
+ }
res.json({ key, url: await storage.publicUrl(key) })
}))
@@ -1917,12 +1885,22 @@ api.delete('/companies/:id', safe(async (req, res) => {
const key = row.storage_key ? normalizeStorageKey(row.storage_key) : null
if (key) storageKeys.add(key)
}
- const { rows: messageFiles } = await client.query<{ attachment: unknown }>(
- `SELECT attachment FROM messages WHERE company_id = $1 AND attachment IS NOT NULL`, [companyId],
+ const { rows: messageFiles } = await client.query<{ attachments: unknown }>(
+ `SELECT COALESCE(
+ CASE WHEN jsonb_typeof(attachments) = 'array' THEN attachments END,
+ CASE WHEN attachment IS NULL THEN '[]'::jsonb
+ ELSE jsonb_build_array(attachment) END
+ ) AS attachments
+ FROM messages
+ WHERE company_id = $1
+ AND (attachment IS NOT NULL OR CASE
+ WHEN jsonb_typeof(attachments) = 'array' THEN jsonb_array_length(attachments) > 0
+ ELSE FALSE
+ END)`,
+ [companyId],
)
for (const row of messageFiles) {
- const candidates = Array.isArray(row.attachment) ? row.attachment : [row.attachment]
- for (const candidate of candidates) {
+ for (const candidate of Array.isArray(row.attachments) ? row.attachments : []) {
if (!candidate || typeof candidate !== 'object') continue
const key = messageAttachmentStorageKey(candidate as { key?: unknown; url?: unknown })
if (key) storageKeys.add(key)
@@ -3463,7 +3441,12 @@ api.get('/conversations', async (req, res) => {
'kind', m.kind,
'body', m.body,
'tool', m.tool,
- 'attachment', m.attachment,
+ 'attachment', COALESCE(m.attachments->0, m.attachment),
+ 'attachments', COALESCE(
+ CASE WHEN jsonb_typeof(m.attachments) = 'array' THEN m.attachments END,
+ CASE WHEN m.attachment IS NULL THEN '[]'::jsonb
+ ELSE jsonb_build_array(m.attachment) END
+ ),
'createdAt', m.created_at,
-- For email messages, surface the subject + direction so the
-- sidebar preview can show "Re: contract draft" instead of a
@@ -3956,7 +3939,10 @@ api.get('/conversations/:id/messages', async (req, res) => {
m.id, m.conversation_id AS "conversationId",
m.author_id AS "authorId", m.kind, m.body, m.sequence,
m.client_id AS "clientId",
- m.tool, m.attachment, m.poll,
+ m.tool, COALESCE(m.attachments->0, m.attachment) AS attachment,
+ COALESCE(m.attachments, CASE WHEN m.attachment IS NULL THEN '[]'::jsonb
+ ELSE jsonb_build_array(m.attachment) END) AS attachments,
+ m.poll,
-- Per-option vote tallies for polls. Empty array for non-poll
-- rows. voterIds is sorted so the client can diff cheaply across
-- successive WS poll.updated events.
@@ -4080,12 +4066,13 @@ api.get('/conversations/:id/messages', async (req, res) => {
// wrap each refresh so a single bad attachment falls back to its
// stored (possibly stale) URL instead of bringing down the response.
for (const row of rows) {
- if (!row.attachment) continue
+ const stored = row.attachments ?? row.attachment
+ if (!stored) continue
try {
- row.attachment = await freshenAttachmentUrl(row.attachment)
+ Object.assign(row, await freshenMessageAttachments(stored))
} catch (e) {
console.warn(
- `[messages] freshenAttachmentUrl failed for message ${row.id} in ${id}; ` +
+ `[messages] freshenMessageAttachments failed for message ${row.id} in ${id}; ` +
`falling back to stored URL`, e,
)
}
@@ -4121,38 +4108,20 @@ api.post('/conversations/:id/messages', async (req, res) => {
const { userId: me, companyId: tenant } = await requireCompany(req)
const { id } = req.params
const body = String(req.body?.body ?? '').trim()
- const rawAttachment = req.body?.attachment
- let attachment: AttachmentPayload | null = null
- if (rawAttachment && typeof rawAttachment === 'object') {
- const a = rawAttachment as Record<string, unknown>
- if (typeof a.url === 'string' && typeof a.name === 'string') {
- // URLs are display data and may be client-controlled or expired. Resolve
- // the server-generated object key, then mint the URL ourselves so a chat
- // attachment can never turn an agent wake into an arbitrary server fetch.
- const key = messageAttachmentStorageKey(a)
- if (!key) {
- res.status(400).json({ error: 'attachment must reference Cumora storage' })
- return
- }
- let url: string
- try {
- url = await storage.publicUrl(key)
- } catch {
- res.status(400).json({ error: 'attachment storage reference is invalid' })
- return
- }
- attachment = {
- url,
- name: a.name.trim().slice(0, 200),
- kind: (a.kind === 'pdf' || a.kind === 'file' || a.kind === 'fig' ? a.kind : 'img') as AttachmentPayload['kind'],
- mime: typeof a.mime === 'string' ? a.mime : undefined,
- size: typeof a.size === 'number' ? a.size : undefined,
- key,
- }
- }
+ // New clients send an ordered `attachments` list. The historical singular
+ // field remains accepted and is normalized into a one-entry list.
+ const attachmentInput = req.body?.attachments ?? req.body?.attachment
+ const resolved = await resolveMessageAttachments(attachmentInput, storage, {
+ attachmentGrant: (key) => hasAttachmentGrant(pool, tenant, key),
+ })
+ if (!resolved.ok) {
+ res.status(resolved.status).json({ error: resolved.error })
+ return
}
- // Allow empty body when an attachment is present (e.g. user just shares an image)
- if (!body && !attachment) {
+ const attachments = resolved.attachments
+ const attachment = attachments[0] ?? null
+ // Allow an empty body when at least one attachment is present.
+ if (!body && attachments.length === 0) {
res.status(400).json({ error: 'empty message' })
return
}
@@ -4331,12 +4300,18 @@ api.post('/conversations/:id/messages', async (req, res) => {
const sequence = seqResult.rows[0]?.seq ?? 1
const inserted = await client.query<{ id: string; sequence: number }>(
`INSERT INTO messages
- (id, conversation_id, author_id, kind, body, sequence, attachment, quoted_message_id, company_id, client_id)
- VALUES ($1,$2,$3,'text',$4,$5,$6::jsonb,$7,$8,$9)
+ (id, conversation_id, author_id, kind, body, sequence, attachment, attachments,
+ quoted_message_id, company_id, client_id)
+ VALUES ($1,$2,$3,'text',$4,$5,$6::jsonb,$7::jsonb,$8,$9,$10)
ON CONFLICT (conversation_id, author_id, client_id) WHERE client_id IS NOT NULL
DO NOTHING
RETURNING id, sequence`,
- [proposedMessageId, id, me, body, sequence, attachment ? JSON.stringify(attachment) : null, resolvedQuotedId, tenant, clientId],
+ [
+ proposedMessageId, id, me, body, sequence,
+ attachment ? JSON.stringify(attachment) : null,
+ JSON.stringify(attachments),
+ resolvedQuotedId, tenant, clientId,
+ ],
)
persisted = inserted.rows[0] ?? (clientId
? (await client.query<{ id: string; sequence: number }>(
@@ -4360,6 +4335,7 @@ api.post('/conversations/:id/messages', async (req, res) => {
id: persisted.id, conversationId: id, authorId: me,
kind: 'text', body, sequence: persisted.sequence, at: new Date().toISOString(),
attachment: attachment ?? undefined,
+ attachments,
quotedMessageId: resolvedQuotedId ?? undefined,
quoted: quotedSummary ?? undefined,
clientId: clientId ?? undefined,
@@ -4524,7 +4500,7 @@ api.post('/polls/:messageId/close', async (req, res) => {
* 1. Reject pathological inputs (missing fields, too many, too big)
* 2. Resolve each key to a fresh signed URL so Resend can fetch it
* Returns an Error (not throws) so callers stay flat. */
-async function resolveHttpAttachments(raw: unknown[]): Promise<Array<{
+async function resolveHttpAttachments(raw: unknown[], companyId: string): Promise<Array<{
filename: string; mimeType: string; sizeBytes: number;
storageKey: string; publicUrl: string;
}> | Error> {
@@ -4540,11 +4516,16 @@ async function resolveHttpAttachments(raw: unknown[]): Promise<Array<{
let totalBytes = 0
for (const entry of raw) {
const a = entry as Record<string, unknown>
- const key = typeof a.key === 'string' ? a.key : ''
+ const key = typeof a.key === 'string' ? normalizeStorageKey(a.key) : null
const filename = typeof a.filename === 'string' ? a.filename.slice(0, 200) : ''
const mimeType = typeof a.mimeType === 'string' ? a.mimeType.slice(0, 120) : 'application/octet-stream'
const sizeBytes = Math.max(0, Number(a.sizeBytes ?? 0))
- if (!key || !filename) return new Error('each attachment needs key + filename')
+ if (!key || !filename || !key.startsWith('attachments/')) {
+ return new Error('each attachment needs a granted chat attachment key + filename')
+ }
+ if (!(await hasAttachmentGrant(pool, companyId, key))) {
+ return new Error('attachment is not granted to this workspace')
+ }
totalBytes += sizeBytes
if (totalBytes > MAX_ATTACH_TOTAL) return new Error(`attachments exceed ${MAX_ATTACH_TOTAL} bytes total`)
const publicUrl = await storage.publicUrl(key)
@@ -4617,7 +4598,7 @@ api.post('/email/send', async (req, res) => {
res.status(400).json({ error: 'to, subject, body required' })
return
}
- const resolvedAttachments = await resolveHttpAttachments(attachRaw)
+ const resolvedAttachments = await resolveHttpAttachments(attachRaw, tenant)
if (resolvedAttachments instanceof Error) {
res.status(400).json({ error: resolvedAttachments.message })
return
@@ -4785,7 +4766,7 @@ api.post('/email/reply/:messageId', async (req, res) => {
const ccRaw = Array.isArray(req.body?.cc) ? req.body.cc as unknown[] : []
const attachRaw = Array.isArray(req.body?.attachments) ? req.body.attachments as unknown[] : []
if (!body) { res.status(400).json({ error: 'body required' }); return }
- const resolvedAttachments = await resolveHttpAttachments(attachRaw)
+ const resolvedAttachments = await resolveHttpAttachments(attachRaw, tenant)
if (resolvedAttachments instanceof Error) {
res.status(400).json({ error: resolvedAttachments.message }); return
}
@@ -4952,7 +4933,10 @@ api.get('/conversations/:id/messages/:rootId/replies', async (req, res) => {
`SELECT
m.id, m.conversation_id AS "conversationId",
m.author_id AS "authorId", m.kind, m.body, m.sequence,
- m.tool, m.attachment, m.poll,
+ m.tool, COALESCE(m.attachments->0, m.attachment) AS attachment,
+ COALESCE(m.attachments, CASE WHEN m.attachment IS NULL THEN '[]'::jsonb
+ ELSE jsonb_build_array(m.attachment) END) AS attachments,
+ m.poll,
-- Per-option vote tallies for polls. Empty array for non-poll
-- rows. voterIds is sorted so the client can diff cheaply across
-- successive WS poll.updated events.
@@ -5016,11 +5000,12 @@ api.get('/conversations/:id/messages/:rootId/replies', async (req, res) => {
[id, rootId, tenant],
)
for (const row of rows) {
- if (!row.attachment) continue
- try { row.attachment = await freshenAttachmentUrl(row.attachment) }
+ const stored = row.attachments ?? row.attachment
+ if (!stored) continue
+ try { Object.assign(row, await freshenMessageAttachments(stored)) }
catch (e) {
console.warn(
- `[replies] freshenAttachmentUrl failed for message ${row.id}; ` +
+ `[replies] freshenMessageAttachments failed for message ${row.id}; ` +
`falling back to stored URL`, e,
)
}
diff --git a/server/src/attachments/grants.ts b/server/src/attachments/grants.ts
new file mode 100644
index 0000000..c247698
--- /dev/null
+++ b/server/src/attachments/grants.ts
@@ -0,0 +1,58 @@
+import type { PoolClient } from 'pg'
+
+export type AttachmentGrantStatus = 'pending' | 'active' | 'revoked'
+
+export type AttachmentGrantQueryable = Pick<PoolClient, 'query'>
+
+function grantableStorageKey(key: string): boolean {
+ return key.startsWith('attachments/') || key.startsWith('email-attachments/')
+}
+
+/** Record that a tenant may reference a storage object. The object itself is
+ * still validated by storage.statObject at message/email write time. */
+export async function grantAttachment(
+ db: AttachmentGrantQueryable,
+ companyId: string,
+ storageKey: string,
+ status: AttachmentGrantStatus = 'active',
+): Promise<void> {
+ if (!grantableStorageKey(storageKey)) return
+ await db.query(
+ `INSERT INTO attachment_grants (storage_key, company_id, status)
+ VALUES ($1, $2, $3)
+ ON CONFLICT (storage_key, company_id)
+ DO UPDATE SET status = EXCLUDED.status`,
+ [storageKey, companyId, status],
+ )
+}
+
+export async function grantAttachments(
+ db: AttachmentGrantQueryable,
+ companyId: string,
+ storageKeys: readonly string[],
+ status: AttachmentGrantStatus = 'active',
+): Promise<void> {
+ for (const key of [...new Set(storageKeys)]) {
+ await grantAttachment(db, companyId, key, status)
+ }
+}
+
+/** Only active grants authorize a tenant to read or attach an object. */
+export async function hasAttachmentGrant(
+ db: AttachmentGrantQueryable,
+ companyId: string,
+ storageKey: string,
+): Promise<boolean> {
+ if (!grantableStorageKey(storageKey)) return false
+ const result = await db.query(
+ `SELECT 1 FROM attachment_grants
+ WHERE storage_key = $1 AND company_id = $2 AND status = 'active'
+ LIMIT 1`,
+ [storageKey, companyId],
+ )
+ return result.rows.length === 1
+}
+
+export function isGrantableAttachmentKey(storageKey: string): boolean {
+ return grantableStorageKey(storageKey)
+}
diff --git a/server/src/db/migrate.ts b/server/src/db/migrate.ts
index 06a237c..d8cb641 100644
--- a/server/src/db/migrate.ts
+++ b/server/src/db/migrate.ts
@@ -53,6 +53,8 @@ import {
boardCardDueOnChecksum,
} from './migrations/0010-board-card-due-on.js'
import { AGENT_NATIVE_FAST_MODE_SQL, agentNativeFastModeChecksum } from './migrations/0011-agent-native-fast-mode.js'
+import { MESSAGE_ATTACHMENTS_SQL, messageAttachmentsChecksum } from './migrations/0012-message-attachments.js'
+import { ATTACHMENT_GRANTS_SQL, attachmentGrantsChecksum } from './migrations/0013-attachment-grants.js'
/** Frozen data backfill embedded in migration 0001. Exported so its behavior
* can be exercised against PostgreSQL without replaying the whole migration. */
@@ -2642,6 +2644,18 @@ const VERSIONED_MIGRATIONS: readonly VersionedMigration[] = [
transactional: true,
up: async (client) => { await client.query(AGENT_NATIVE_FAST_MODE_SQL) },
},
+ {
+ ...SCHEMA_MIGRATIONS[11],
+ sourceChecksum: messageAttachmentsChecksum(),
+ transactional: true,
+ up: async (client) => { await client.query(MESSAGE_ATTACHMENTS_SQL) },
+ },
+ {
+ ...SCHEMA_MIGRATIONS[12],
+ sourceChecksum: attachmentGrantsChecksum(),
+ transactional: true,
+ up: async (client) => { await client.query(ATTACHMENT_GRANTS_SQL) },
+ },
]
/** How many times a transactional migration may lose a lock race before the
diff --git a/server/src/db/migrations/0012-message-attachments.ts b/server/src/db/migrations/0012-message-attachments.ts
new file mode 100644
index 0000000..40db43c
--- /dev/null
+++ b/server/src/db/migrations/0012-message-attachments.ts
@@ -0,0 +1,54 @@
+import { createHash } from 'node:crypto'
+
+/**
+ * Canonical ordered chat-attachment list. The legacy `attachment` column
+ * remains a first-entry compatibility projection for clients and readers
+ * that predate multi-attachment messages.
+ */
+export const MESSAGE_ATTACHMENTS_SQL = `
+ALTER TABLE messages ADD COLUMN IF NOT EXISTS attachments JSONB;
+
+-- Backfill once from the historical single descriptor. A canonical array that
+-- already exists wins, so rerunning this statement cannot reorder attachments.
+UPDATE messages
+ SET attachments = jsonb_build_array(attachment)
+ WHERE attachments IS NULL
+ AND attachment IS NOT NULL;
+
+-- New messages use a non-null array. Nullable during backfill avoids a table
+-- rewrite and remains compatible with old writers during the expand phase.
+CREATE OR REPLACE FUNCTION sync_message_attachment_projection()
+RETURNS TRIGGER
+LANGUAGE plpgsql
+AS $migration$
+BEGIN
+ IF NEW.attachments IS NOT NULL THEN
+ NEW.attachments := CASE
+ WHEN jsonb_typeof(NEW.attachments) = 'array' THEN NEW.attachments
+ WHEN jsonb_typeof(NEW.attachments) = 'object' THEN jsonb_build_array(NEW.attachments)
+ ELSE '[]'::jsonb
+ END;
+ NEW.attachment := CASE
+ WHEN jsonb_array_length(NEW.attachments) = 0 THEN NULL
+ ELSE NEW.attachments->0
+ END;
+ ELSIF NEW.attachment IS NOT NULL THEN
+ -- Expand-phase compatibility for a server revision that still writes only
+ -- the legacy column while this migration is being deployed.
+ NEW.attachments := jsonb_build_array(NEW.attachment);
+ ELSE
+ NEW.attachments := '[]'::jsonb;
+ END IF;
+ RETURN NEW;
+END;
+$migration$;
+
+DROP TRIGGER IF EXISTS messages_sync_attachment_projection ON messages;
+CREATE TRIGGER messages_sync_attachment_projection
+BEFORE INSERT OR UPDATE OF attachment, attachments ON messages
+FOR EACH ROW EXECUTE FUNCTION sync_message_attachment_projection();
+`
+
+export function messageAttachmentsChecksum(): string {
+ return createHash('sha256').update(MESSAGE_ATTACHMENTS_SQL).digest('hex')
+}
diff --git a/server/src/db/migrations/0013-attachment-grants.ts b/server/src/db/migrations/0013-attachment-grants.ts
new file mode 100644
index 0000000..68b01c7
--- /dev/null
+++ b/server/src/db/migrations/0013-attachment-grants.ts
@@ -0,0 +1,46 @@
+import { createHash } from 'node:crypto'
+
+/** Tenant ownership records for every storage object that can appear in a
+ * message or email. The storage key is intentionally not globally readable:
+ * the same object may be granted to several companies (inbound mail fan-out),
+ * while an ungranted key cannot be refreshed or downloaded. */
+export const ATTACHMENT_GRANTS_SQL = `
+CREATE TABLE IF NOT EXISTS attachment_grants (
+ storage_key TEXT NOT NULL,
+ company_id TEXT NOT NULL REFERENCES companies(id) ON DELETE CASCADE,
+ status TEXT NOT NULL DEFAULT 'active'
+ CHECK (status IN ('pending', 'active', 'revoked')),
+ created_at TIMESTAMP WITH TIME ZONE NOT NULL DEFAULT NOW(),
+ PRIMARY KEY (storage_key, company_id)
+);
+CREATE INDEX IF NOT EXISTS idx_attachment_grants_company
+ ON attachment_grants(company_id, status, created_at DESC);
+
+-- Recover tenant ownership for objects persisted before this table existed.
+INSERT INTO attachment_grants (storage_key, company_id, status)
+SELECT DISTINCT candidate.storage_key, m.company_id, 'active'
+ FROM messages m
+ CROSS JOIN LATERAL (
+ SELECT value->>'key' AS storage_key
+ FROM jsonb_array_elements(
+ CASE WHEN jsonb_typeof(m.attachments) = 'array' THEN m.attachments
+ WHEN m.attachment IS NOT NULL THEN jsonb_build_array(m.attachment)
+ ELSE '[]'::jsonb END
+ ) value
+ UNION ALL
+ SELECT m.attachment->>'key'
+ WHERE jsonb_typeof(m.attachment) = 'object'
+ ) candidate
+ WHERE candidate.storage_key LIKE 'attachments/%'
+ON CONFLICT (storage_key, company_id) DO NOTHING;
+
+INSERT INTO attachment_grants (storage_key, company_id, status)
+SELECT DISTINCT storage_key, company_id, 'active'
+ FROM email_attachments
+ WHERE storage_key LIKE 'email-attachments/%'
+ON CONFLICT (storage_key, company_id) DO NOTHING;
+`
+
+export function attachmentGrantsChecksum(): string {
+ return createHash('sha256').update(ATTACHMENT_GRANTS_SQL).digest('hex')
+}
diff --git a/server/src/db/migrations/manifest.ts b/server/src/db/migrations/manifest.ts
index 20afe61..c8775f5 100644
--- a/server/src/db/migrations/manifest.ts
+++ b/server/src/db/migrations/manifest.ts
@@ -72,12 +72,22 @@ export const SCHEMA_MIGRATIONS = [
name: '0011_agent_native_fast_mode',
checksum: '18ef047d7ee5ad254918f95f8b8320a2c0395401ee7354769763773ebd43ab41',
},
+ {
+ version: 12,
+ name: '0012_message_attachments',
+ checksum: 'e33811b25478626ed879c3aad75364daff33922c572eb498c981c8a3d9c95d1d',
+ },
+ {
+ version: 13,
+ name: '0013_attachment_grants',
+ checksum: '7ad86f32412eea99834c28608c97c9fbbf7257c3e93e14896e2754b167908453',
+ },
] as const satisfies readonly MigrationMetadata[]
/** This build intentionally supports one exact schema range. Expand/contract
* releases may widen the range, but both bounds must remain explicit. */
-export const MIN_SUPPORTED_SCHEMA_VERSION = 11
-export const MAX_SUPPORTED_SCHEMA_VERSION = 11
+export const MIN_SUPPORTED_SCHEMA_VERSION = 13
+export const MAX_SUPPORTED_SCHEMA_VERSION = 13
function assertManifestShape(): void {
for (let i = 0; i < SCHEMA_MIGRATIONS.length; i++) {
diff --git a/server/src/db/schema.ts b/server/src/db/schema.ts
index 260ddb7..a581406 100644
--- a/server/src/db/schema.ts
+++ b/server/src/db/schema.ts
@@ -1,5 +1,6 @@
import { sql } from 'drizzle-orm'
import { pgTable, text, integer, timestamp, jsonb, boolean, index, uniqueIndex } from 'drizzle-orm/pg-core'
+import type { AttachmentDescriptor } from '../../../shared/attachments.js'
export const conversations = pgTable('conversations', {
id: text('id').primaryKey(),
@@ -25,7 +26,9 @@ export const messages = pgTable(
sequence: integer('sequence').notNull(),
reactions: jsonb('reactions').$type<Array<{ emoji: string; count: number; mine?: boolean }> | null>(),
tool: jsonb('tool').$type<Record<string, unknown> | null>(),
- attachment: jsonb('attachment').$type<Record<string, unknown> | null>(),
+ /** Legacy first-attachment projection. New code reads `attachments`. */
+ attachment: jsonb('attachment').$type<AttachmentDescriptor | null>(),
+ attachments: jsonb('attachments').$type<AttachmentDescriptor[] | null>(),
clientId: text('client_id'),
// Durable one-shot delivery for departure notices after membership is
// removed. Ordinary messages leave this null.
diff --git a/server/src/email.ts b/server/src/email.ts
index 3189781..0614cf5 100644
--- a/server/src/email.ts
+++ b/server/src/email.ts
@@ -18,6 +18,7 @@ import { randomUUID } from 'node:crypto'
import type { PoolClient } from 'pg'
import { pool } from './db/pool.js'
import { env } from './env.js'
+import { grantAttachment } from './attachments/grants.js'
/** Lowercased domain for an address-construction call. Returns '' when
* EMAIL_DOMAIN isn't configured — callers should treat that as "email
@@ -727,6 +728,9 @@ export async function persistEmailMessage(args: {
const filename = a.filename.slice(0, 200)
const mimeType = (a.mimeType || 'application/octet-stream').slice(0, 120)
const truncated = Boolean(a.truncated)
+ if (a.storageKey && !truncated) {
+ await grantAttachment(client, args.companyId, a.storageKey)
+ }
await client.query(
`INSERT INTO email_attachments
(id, message_id, conversation_id, company_id, filename, mime_type, size_bytes, storage_key, truncated)
diff --git a/server/src/redis.ts b/server/src/redis.ts
index 718be6d..31971bc 100644
--- a/server/src/redis.ts
+++ b/server/src/redis.ts
@@ -93,6 +93,9 @@ export interface MessageNewEvent extends TenantTagged {
reactions?: unknown
tool?: unknown
attachment?: unknown
+ /** Canonical ordered chat attachments; `attachment` remains for legacy
+ * clients and older message consumers. */
+ attachments?: unknown
/** Echoed verbatim from the POST body when the sender provided one.
* The renderer uses it to dedup the WS echo against its still-temp
* optimistic bubble when the WS event races the POST response — id
diff --git a/server/src/storage.ts b/server/src/storage.ts
index fbf4137..9152cd9 100644
--- a/server/src/storage.ts
+++ b/server/src/storage.ts
@@ -20,15 +20,23 @@
* - `email-attachments/` — inbound and outbound mail files (signed)
* - `avatars/` — portraits (the only unsigned R2 prefix)
*/
-import { writeFile, mkdir, readdir, stat, unlink } from 'node:fs/promises'
-import { join, resolve, dirname } from 'node:path'
+import { writeFile, mkdir, readdir, readFile, stat, unlink } from 'node:fs/promises'
+import { basename, join, resolve, dirname } from 'node:path'
import { createHmac } from 'node:crypto'
import {
- S3Client, PutObjectCommand, GetObjectCommand,
+ S3Client, PutObjectCommand, GetObjectCommand, HeadObjectCommand,
DeleteObjectCommand, ListObjectsV2Command,
} from '@aws-sdk/client-s3'
import { getSignedUrl } from '@aws-sdk/s3-request-presigner'
import { env } from './env.js'
+import {
+ ATTACHMENT_MAX_FILE_BYTES,
+ ATTACHMENT_MAX_TOTAL_BYTES,
+ normalizeAttachments,
+ validateAttachmentInput,
+ type AttachmentDescriptor,
+ type AttachmentKind,
+} from '../../shared/attachments.js'
import {
normalizeStorageKey,
storageKeyFromPublicUrl as storageKeyFromPublicUrlForBase,
@@ -70,6 +78,88 @@ export function signedUrlExpiresSoon(raw: string, leewaySeconds = 300): boolean
* abstraction lands. */
export const UPLOAD_DIR = resolve(process.cwd(), 'server/uploads')
+/** The chat-upload MIME allowlist also defines the extension and renderer kind
+ * for a new object. Message persistence derives both from stored metadata. */
+export const CHAT_ATTACHMENT_MIME_POLICY: Record<string, { kind: 'img' | 'file'; ext: string }> = {
+ 'image/png': { kind: 'img', ext: 'png' },
+ 'image/jpeg': { kind: 'img', ext: 'jpg' },
+ 'image/webp': { kind: 'img', ext: 'webp' },
+ 'image/gif': { kind: 'img', ext: 'gif' },
+ 'application/pdf': { kind: 'file', ext: 'pdf' },
+ 'application/msword': { kind: 'file', ext: 'doc' },
+ 'application/vnd.openxmlformats-officedocument.wordprocessingml.document': { kind: 'file', ext: 'docx' },
+ 'application/vnd.ms-excel': { kind: 'file', ext: 'xls' },
+ 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet': { kind: 'file', ext: 'xlsx' },
+ 'application/vnd.ms-powerpoint': { kind: 'file', ext: 'ppt' },
+ 'application/vnd.openxmlformats-officedocument.presentationml.presentation': { kind: 'file', ext: 'pptx' },
+ 'application/zip': { kind: 'file', ext: 'zip' },
+ 'application/x-tar': { kind: 'file', ext: 'tar' },
+ 'application/gzip': { kind: 'file', ext: 'gz' },
+ 'text/plain': { kind: 'file', ext: 'txt' },
+ 'text/markdown': { kind: 'file', ext: 'md' },
+ 'text/csv': { kind: 'file', ext: 'csv' },
+ 'application/json': { kind: 'file', ext: 'json' },
+ 'application/x-yaml': { kind: 'file', ext: 'yml' },
+ 'application/x-toml': { kind: 'file', ext: 'toml' },
+ 'audio/mpeg': { kind: 'file', ext: 'mp3' },
+ 'audio/wav': { kind: 'file', ext: 'wav' },
+ 'video/mp4': { kind: 'file', ext: 'mp4' },
+ 'video/quicktime': { kind: 'file', ext: 'mov' },
+}
+
+function attachmentKindForMime(mime: string): AttachmentKind {
+ if (mime === 'application/pdf') return 'pdf'
+ return CHAT_ATTACHMENT_MIME_POLICY[mime]?.kind ?? 'file'
+}
+
+/** Validate a presign request against the same policy the message write uses. */
+export function validateChatUpload(input: {
+ name: unknown
+ mime: unknown
+ size: unknown
+}):
+ | { ok: true; name: string; mime: string; size: number; kind: AttachmentKind }
+ | { ok: false; status: 400 | 413 | 415; error: string } {
+ const name = String(input.name ?? '').trim().slice(0, 200)
+ const mime = String(input.mime ?? '').trim().toLowerCase()
+ const size = Number(input.size ?? 0)
+ if (!name || !mime) return { ok: false, status: 400, error: 'name + mime required' }
+ if (!Number.isSafeInteger(size) || size <= 0 || size > ATTACHMENT_MAX_FILE_BYTES) {
+ return { ok: false, status: 413, error: `size out of range (got ${size}, max ${ATTACHMENT_MAX_FILE_BYTES})` }
+ }
+ const policy = CHAT_ATTACHMENT_MIME_POLICY[mime]
+ if (!policy) return { ok: false, status: 415, error: `mime not allowed: ${mime}` }
+ return { ok: true, name, mime, size, kind: attachmentKindForMime(mime) }
+}
+
+const STORAGE_MIME_BY_EXTENSION = new Map<string, string>()
+for (const [mime, policy] of Object.entries(CHAT_ATTACHMENT_MIME_POLICY)) {
+ STORAGE_MIME_BY_EXTENSION.set(policy.ext, mime)
+}
+
+function normalizedMime(raw: string): string {
+ return raw.split(';', 1)[0]?.trim().toLowerCase() ?? ''
+}
+
+/** Local uploads use a small sidecar for the exact MIME supplied when the
+ * server wrote the bytes. The sidecar never becomes a message attachment. */
+async function putLocalMimeMetadata(key: string, mime: string): Promise<void> {
+ const marker = localMimeMarker(key)
+ await mkdir(dirname(marker), { recursive: true })
+ await writeFile(marker, mime)
+}
+
+function localMimeMarker(key: string): string {
+ return join(UPLOAD_DIR, dirname(key), `${basename(key)}.cumora-mime`)
+}
+
+/** Local files have no object-store Content-Type header. Their server-minted
+ * extension is the storage-side type record used for persistence and reads. */
+export function mimeTypeFromStorageKey(key: string): string | undefined {
+ const extension = key.toLowerCase().match(/\.([a-z0-9]+)$/)?.[1]
+ return extension ? STORAGE_MIME_BY_EXTENSION.get(extension) : undefined
+}
+
/** One enumerated object. lastModifiedMs is the storage backend's notion
* of when the object was last written — GC uses it to spare keys that
* were uploaded recently (the row write may still be in flight). */
@@ -79,6 +169,14 @@ export interface StorageObject {
lastModifiedMs: number
}
+/** Authoritative metadata for one stored object. Callers use this instead of
+ * trusting browser-supplied MIME or size values when persisting a message. */
+export interface StoredObjectMetadata {
+ key: string
+ sizeBytes: number
+ mime?: string
+}
+
export interface Storage {
mode: 'local' | 'r2'
/** Write bytes synchronously from the server side (avatar gen path).
@@ -86,7 +184,14 @@ export interface Storage {
put(key: string, body: Buffer, mime: string): Promise<string>
/** Return a short-lived PUT URL the browser uploads to directly, plus
* the public URL the file will be available at after the upload. */
- presignPut(key: string, mime: string, ttlSeconds?: number): Promise<{ uploadUrl: string; publicUrl: string }>
+ presignPut(
+ key: string,
+ mime: string,
+ sizeBytes: number,
+ ttlSeconds?: number,
+ ): Promise<{ uploadUrl: string; publicUrl: string }>
+ /** Return object metadata, or null when the key does not exist. */
+ statObject(key: string): Promise<StoredObjectMetadata | null>
/** Resolve a long-lived public URL for a key. R2 mode emits a presigned
* GET when no public base is configured. */
publicUrl(key: string): Promise<string>
@@ -108,6 +213,7 @@ class LocalStorage implements Storage {
const path = join(UPLOAD_DIR, key)
await mkdir(dirname(path), { recursive: true })
await writeFile(path, body)
+ await putLocalMimeMetadata(key, _mime)
// Existing static handler mounts UPLOAD_DIR at /uploads/.
return `/uploads/${key}`
}
@@ -116,10 +222,35 @@ class LocalStorage implements Storage {
// `POST /uploads` (base64). Callers MUST check `storage.mode` first
// and pick the base64 path; this method only exists to satisfy the
// interface and will throw if reached.
- async presignPut(_key: string, _mime: string, _ttl?: number): Promise<{ uploadUrl: string; publicUrl: string }> {
+ async presignPut(
+ _key: string,
+ _mime: string,
+ _sizeBytes: number,
+ _ttl?: number,
+ ): Promise<{ uploadUrl: string; publicUrl: string }> {
throw new Error('presignPut not supported in local mode — POST /uploads (base64) instead')
}
+ async statObject(key: string): Promise<StoredObjectMetadata | null> {
+ const path = join(UPLOAD_DIR, key)
+ try {
+ const s = await stat(path)
+ if (!s.isFile()) return null
+ const metaMarker = localMimeMarker(key)
+ let mime: string | undefined
+ try {
+ const raw = (await readFile(metaMarker, 'utf8')).trim()
+ if (raw) mime = normalizedMime(raw)
+ } catch (error) {
+ if ((error as NodeJS.ErrnoException).code !== 'ENOENT') throw error
+ }
+ return { key, sizeBytes: s.size, mime }
+ } catch (error) {
+ if ((error as NodeJS.ErrnoException).code === 'ENOENT') return null
+ throw error
+ }
+ }
+
async publicUrl(key: string): Promise<string> {
return `/uploads/${key}`
}
@@ -204,17 +335,47 @@ class R2Storage implements Storage {
return this.publicUrl(key)
}
- async presignPut(key: string, mime: string, ttl = 300): Promise<{ uploadUrl: string; publicUrl: string }> {
+ async presignPut(
+ key: string,
+ mime: string,
+ sizeBytes: number,
+ ttl = 300,
+ ): Promise<{ uploadUrl: string; publicUrl: string }> {
const cmd = new PutObjectCommand({
Bucket: this.bucket,
Key: key,
ContentType: mime,
+ // SigV4 binds this header into the presigned URL. The browser's PUT must
+ // carry the same Content-Length, preventing a larger object upload.
+ ContentLength: sizeBytes,
})
const uploadUrl = await getSignedUrl(this.client, cmd, { expiresIn: ttl })
const publicUrl = await this.publicUrl(key)
return { uploadUrl, publicUrl }
}
+ async statObject(key: string): Promise<StoredObjectMetadata | null> {
+ try {
+ const res = await this.client.send(new HeadObjectCommand({
+ Bucket: this.bucket,
+ Key: key,
+ }))
+ if (typeof res.ContentLength !== 'number' || !Number.isSafeInteger(res.ContentLength)) {
+ throw new Error('storage object has no valid Content-Length')
+ }
+ return {
+ key,
+ sizeBytes: res.ContentLength,
+ ...(res.ContentType ? { mime: res.ContentType.toLowerCase() } : {}),
+ }
+ } catch (error) {
+ const name = (error as { name?: unknown } | null)?.name
+ const status = (error as { $metadata?: { httpStatusCode?: unknown } } | null)?.$metadata?.httpStatusCode
+ if (name === 'NotFound' || name === 'NoSuchKey' || status === 404) return null
+ throw error
+ }
+ }
+
async listObjectsByPrefix(prefix: string): Promise<StorageObject[]> {
// R2 / S3 ListObjectsV2 is paginated; loop on ContinuationToken so a
// large bucket doesn't silently truncate at 1000.
@@ -340,3 +501,113 @@ export async function freshenAttachmentUrl<T extends StoredAttachment | null | u
if (url === att.url && att.key === key) return att
return { ...att, url, key } as T
}
+
+export type ResolveMessageAttachmentsResult =
+ | { readonly ok: true; readonly attachments: readonly AttachmentDescriptor[] }
+ | {
+ readonly ok: false
+ readonly status: 400 | 413
+ readonly error: string
+ readonly index?: number
+ }
+
+/** Validate the ordered wire list, resolve each trusted Cumora object, and
+ * replace every client-controlled size/MIME/kind/URL with storage-derived
+ * values. Message persistence must use this result verbatim. */
+export async function resolveMessageAttachments(
+ raw: unknown,
+ backend: Pick<Storage, 'statObject' | 'publicUrl'> = storage,
+ opts: {
+ mimeForLegacyKey?: (key: string) => string | undefined
+ /** Tenant-bound grant check supplied by the API boundary. Keeping the
+ * callback here avoids coupling storage backends to Postgres. */
+ attachmentGrant?: (key: string) => Promise<boolean>
+ } = {},
+): Promise<ResolveMessageAttachmentsResult> {
+ const parsed = validateAttachmentInput(raw)
+ if (!parsed.ok) {
+ const indexSuffix = parsed.index === undefined ? '' : ` at index ${parsed.index}`
+ switch (parsed.issue) {
+ case 'too-many-files':
+ return { ok: false, status: 413, error: 'too many attachments (maximum 16)' }
+ case 'file-too-large':
+ return { ok: false, status: 413, error: `attachment${indexSuffix} exceeds 25 MiB` }
+ case 'total-too-large':
+ return { ok: false, status: 413, error: `attachments${indexSuffix} exceed 25 MiB total` }
+ case 'invalid-shape':
+ return { ok: false, status: 400, error: `invalid attachment${indexSuffix}` }
+ }
+ }
+
+ const attachments: AttachmentDescriptor[] = []
+ let totalBytes = 0
+ for (let index = 0; index < parsed.attachments.length; index++) {
+ const input = parsed.attachments[index]
+ const key = messageAttachmentStorageKey(input)
+ if (!key) {
+ return { ok: false, status: 400, error: 'attachment must reference Cumora storage', index }
+ }
+ if (opts.attachmentGrant && !(await opts.attachmentGrant(key))) {
+ return { ok: false, status: 400, error: 'attachment is not granted to this workspace', index }
+ }
+ let stored: StoredObjectMetadata | null
+ let url: string
+ try {
+ ;[stored, url] = await Promise.all([backend.statObject(key), backend.publicUrl(key)])
+ } catch {
+ return { ok: false, status: 400, error: 'attachment storage reference is invalid', index }
+ }
+ if (!stored) return { ok: false, status: 400, error: 'attachment object does not exist', index }
+ if (stored.sizeBytes <= 0 || stored.sizeBytes > ATTACHMENT_MAX_FILE_BYTES) {
+ return { ok: false, status: 413, error: `attachment object size is invalid (maximum 25 MiB)`, index }
+ }
+ if (input.size !== undefined && input.size !== stored.sizeBytes) {
+ return { ok: false, status: 400, error: 'attachment size does not match uploaded object', index }
+ }
+ totalBytes += stored.sizeBytes
+ if (totalBytes > ATTACHMENT_MAX_TOTAL_BYTES) {
+ return { ok: false, status: 413, error: 'attachments exceed 25 MiB total', index }
+ }
+
+ const mime = stored.mime
+ ? normalizedMime(stored.mime)
+ : (opts.mimeForLegacyKey ?? mimeTypeFromStorageKey)(key)
+ if (!mime || !CHAT_ATTACHMENT_MIME_POLICY[mime]) {
+ return { ok: false, status: 400, error: 'attachment object has an unsupported content type', index }
+ }
+ if (input.mime && normalizedMime(input.mime) !== mime) {
+ return { ok: false, status: 400, error: 'attachment MIME does not match uploaded object', index }
+ }
+ attachments.push({
+ name: input.name,
+ kind: attachmentKindForMime(mime),
+ url,
+ key,
+ mime,
+ size: stored.sizeBytes,
+ })
+ }
+ return { ok: true, attachments }
+}
+
+/** Add the canonical ordered list plus the first-entry legacy projection to a
+ * message response without changing any surrounding fields. */
+export async function freshenMessageAttachments(
+ value: unknown,
+): Promise<{ attachment?: AttachmentDescriptor; attachments: readonly AttachmentDescriptor[] }> {
+ const attachments = await Promise.all(normalizeAttachments(value).map(async (attachment) => {
+ const freshened = await freshenAttachmentUrl({
+ ...attachment,
+ url: attachment.url ?? '',
+ })
+ return {
+ ...attachment,
+ ...(freshened.url ? { url: freshened.url } : {}),
+ ...(freshened.key ? { key: freshened.key } : {}),
+ }
+ }))
+ return {
+ ...(attachments[0] ? { attachment: attachments[0] } : {}),
+ attachments,
+ }
+}
diff --git a/server/src/workspace-cleanup.ts b/server/src/workspace-cleanup.ts
index 0d14b5d..8ffbfb9 100644
--- a/server/src/workspace-cleanup.ts
+++ b/server/src/workspace-cleanup.ts
@@ -122,10 +122,21 @@ export async function findReferencedStorageKeys(keys: string[], client?: PoolCli
`SELECT storage_key FROM email_attachments WHERE storage_key = ANY($1::text[])`,
[uniqueKeys],
)
- const messageFiles = await db.query<{ attachment: unknown }>(
- `SELECT attachment
- FROM messages
- WHERE attachment->>'key' = ANY($1::text[])`,
+ const messageFiles = await db.query<{ attachments: unknown }>(
+ `SELECT COALESCE(
+ m.attachments,
+ CASE WHEN m.attachment IS NULL THEN '[]'::jsonb
+ ELSE jsonb_build_array(m.attachment) END
+ ) AS attachments
+ FROM messages m
+ WHERE m.attachment->>'key' = ANY($1::text[])
+ OR EXISTS (
+ SELECT 1 FROM jsonb_array_elements(
+ CASE WHEN jsonb_typeof(m.attachments) = 'array'
+ THEN m.attachments ELSE '[]'::jsonb END
+ ) attachment
+ WHERE attachment->>'key' = ANY($1::text[])
+ )`,
[uniqueKeys],
)
const avatars = await db.query<{ avatar_url: string }>(
@@ -150,7 +161,7 @@ export async function findReferencedStorageKeys(keys: string[], client?: PoolCli
if (key && uniqueKeys.includes(key)) referenced.add(key)
}
for (const row of messageFiles.rows) {
- const attachments = Array.isArray(row.attachment) ? row.attachment : [row.attachment]
+ const attachments = Array.isArray(row.attachments) ? row.attachments : [row.attachments]
for (const attachment of attachments) {
if (!attachment || typeof attachment !== 'object') continue
const key = messageAttachmentStorageKey(attachment as { key?: unknown; url?: unknown })
diff --git a/shared/attachments.ts b/shared/attachments.ts
new file mode 100644
index 0000000..017b155
--- /dev/null
+++ b/shared/attachments.ts
@@ -0,0 +1,157 @@
+/** Canonical chat-attachment policy and boundary parsing.
+ *
+ * Messages historically stored one descriptor in `messages.attachment`; email
+ * and newer clients also need ordered lists. Keep the persisted/wire value
+ * tolerant while giving application code one normalized shape. This module is
+ * deliberately storage-free so the browser, server, and tests can share it.
+ */
+
+export const ATTACHMENT_MAX_FILES = 16
+export const ATTACHMENT_MAX_FILE_BYTES = 25 * 1024 * 1024
+export const ATTACHMENT_MAX_TOTAL_BYTES = 25 * 1024 * 1024
+export const ATTACHMENT_TEXT_EXCERPT_BYTES = 50 * 1024
+
+export const ATTACHMENT_KINDS = ['img', 'pdf', 'file', 'fig'] as const
+export type AttachmentKind = (typeof ATTACHMENT_KINDS)[number]
+
+export interface AttachmentDescriptor {
+ readonly name: string
+ readonly kind: AttachmentKind
+ readonly url?: string
+ readonly key?: string
+ readonly mime?: string
+ readonly size?: number
+ /** Renderer-only legacy label used by old mock rows. */
+ readonly meta?: string
+}
+
+export type AttachmentInput = AttachmentDescriptor | readonly AttachmentDescriptor[]
+
+export type AttachmentValidationIssue =
+ | 'invalid-shape'
+ | 'too-many-files'
+ | 'file-too-large'
+ | 'total-too-large'
+
+export type AttachmentValidationResult =
+ | { readonly ok: true; readonly attachments: readonly AttachmentDescriptor[] }
+ | { readonly ok: false; readonly issue: AttachmentValidationIssue; readonly index?: number }
+
+function isRecord(value: unknown): value is Record<string, unknown> {
+ return value !== null && typeof value === 'object' && !Array.isArray(value)
+}
+
+function isAttachmentKind(value: unknown): value is AttachmentKind {
+ return typeof value === 'string' && (ATTACHMENT_KINDS as readonly string[]).includes(value)
+}
+
+function nonEmptyString(value: unknown): string | null {
+ if (typeof value !== 'string') return null
+ const trimmed = value.trim()
+ return trimmed ? trimmed : null
+}
+
+function parseOne(value: unknown): AttachmentDescriptor | null {
+ if (!isRecord(value)) return null
+ const name = nonEmptyString(value.name)
+ if (!name || !isAttachmentKind(value.kind)) return null
+
+ const parsedUrl = value.url === undefined ? undefined : nonEmptyString(value.url)
+ const parsedKey = value.key === undefined ? undefined : nonEmptyString(value.key)
+ if (value.url !== undefined && parsedUrl === null) return null
+ if (value.key !== undefined && parsedKey === null) return null
+ const url = parsedUrl ?? undefined
+ const key = parsedKey ?? undefined
+ if (url === undefined && key === undefined && value.meta === undefined) return null
+
+ const parsedMime = value.mime === undefined ? undefined : nonEmptyString(value.mime)
+ if (value.mime !== undefined && parsedMime === null) return null
+ const mime = parsedMime ?? undefined
+ const parsedMeta = value.meta === undefined ? undefined : nonEmptyString(value.meta)
+ if (value.meta !== undefined && parsedMeta === null) return null
+ const meta = parsedMeta ?? undefined
+ if (value.size !== undefined && (typeof value.size !== 'number'
+ || !Number.isSafeInteger(value.size) || value.size <= 0)) return null
+
+ return {
+ name,
+ kind: value.kind,
+ ...(url === undefined ? {} : { url }),
+ ...(key === undefined ? {} : { key }),
+ ...(mime === undefined ? {} : { mime: mime.toLowerCase() }),
+ ...(value.size === undefined ? {} : { size: value.size }),
+ ...(meta === undefined ? {} : { meta }),
+ }
+}
+
+/** Parse the old single-object wire value or the canonical array. A missing
+ * value is an empty attachment list; malformed entries reject the whole value
+ * so a router cannot partially persist a multi-file message. */
+export function validateAttachmentInput(value: unknown): AttachmentValidationResult {
+ if (value === null || value === undefined) return { ok: true, attachments: [] }
+ if (Array.isArray(value) && value.length === 0) return { ok: true, attachments: [] }
+ if (Array.isArray(value) && value.length > ATTACHMENT_MAX_FILES) {
+ return { ok: false, issue: 'too-many-files' }
+ }
+
+ const raw = Array.isArray(value) ? value : [value]
+ const attachments: AttachmentDescriptor[] = []
+ let totalBytes = 0
+ for (let index = 0; index < raw.length; index++) {
+ const attachment = parseOne(raw[index])
+ if (!attachment) return { ok: false, issue: 'invalid-shape', index }
+ if (attachment.size !== undefined) {
+ if (attachment.size > ATTACHMENT_MAX_FILE_BYTES) {
+ return { ok: false, issue: 'file-too-large', index }
+ }
+ totalBytes += attachment.size
+ if (totalBytes > ATTACHMENT_MAX_TOTAL_BYTES) {
+ return { ok: false, issue: 'total-too-large', index }
+ }
+ }
+ attachments.push(attachment)
+ }
+ return { ok: true, attachments }
+}
+
+/** Normalize a persisted single attachment to a list, and pass through a
+ * canonical list. Invalid legacy data becomes empty rather than crashing a
+ * historical-message read. */
+export function normalizeAttachments(value: unknown): readonly AttachmentDescriptor[] {
+ const parsed = validateAttachmentInput(value)
+ return parsed.ok ? parsed.attachments : []
+}
+
+export function attachmentTotalBytes(attachments: readonly AttachmentDescriptor[]): number {
+ return attachments.reduce((total, attachment) => total + (attachment.size ?? 0), 0)
+}
+
+export type AttachmentSelectionCheck =
+ | { readonly ok: true }
+ | {
+ readonly ok: false
+ readonly reason: 'too-many-files' | 'file-too-large' | 'total-too-large'
+ readonly maxFiles?: number
+ readonly maxBytes?: number
+ }
+
+/** Pure pre-upload check for the composer. Existing attachments are included
+ * because aggregate policy applies to the whole send, not one picker action. */
+export function checkAttachmentSelection(
+ current: readonly AttachmentDescriptor[],
+ incoming: readonly AttachmentDescriptor[],
+): AttachmentSelectionCheck {
+ const all = [...current, ...incoming]
+ if (all.length > ATTACHMENT_MAX_FILES) {
+ return { ok: false, reason: 'too-many-files', maxFiles: ATTACHMENT_MAX_FILES }
+ }
+ for (const attachment of incoming) {
+ if (attachment.size !== undefined && attachment.size > ATTACHMENT_MAX_FILE_BYTES) {
+ return { ok: false, reason: 'file-too-large', maxBytes: ATTACHMENT_MAX_FILE_BYTES }
+ }
+ }
+ if (attachmentTotalBytes(all) > ATTACHMENT_MAX_TOTAL_BYTES) {
+ return { ok: false, reason: 'total-too-large', maxBytes: ATTACHMENT_MAX_TOTAL_BYTES }
+ }
+ return { ok: true }
+}
diff --git a/src/api/client.ts b/src/api/client.ts
index 087ef3c..3e6ac2e 100644
--- a/src/api/client.ts
+++ b/src/api/client.ts
@@ -1,5 +1,6 @@
import { getActiveCompanyId, getAuthToken, useAuth } from '@/stores/auth'
import type { EngineUpdate } from '../../shared/engine-update'
+import type { AttachmentDescriptor } from '../../shared/attachments'
import type {
BoardCardComment, BoardCardLookup, BoardSnapshot, BoardSummary,
CalendarDispatch, CalendarEvent, CalendarEventKind, CalendarEventStatus,
@@ -138,6 +139,8 @@ export async function http<T>(path: string, init?: RequestInit): Promise<T> {
export interface ApiMessage extends Message {
sequence: number
createdAt?: string
+ /** Older reads and WS frames still carry the singular column value. */
+ attachments?: readonly AttachmentDescriptor[]
reactions?: Array<{ emoji: string; count: number; mine?: boolean; users?: string[] }>
}
@@ -166,7 +169,7 @@ export interface ApiConversation {
kind: string
body: string
tool?: unknown
- attachment?: { name?: string; kind?: 'img' | 'pdf' | 'file' | 'fig' } | null
+ attachment?: AttachmentDescriptor | readonly AttachmentDescriptor[] | null
createdAt: string
/** Set when last message is an email — used to render "Re: subject"
* previews in the sidebar instead of the raw body excerpt. */
@@ -1144,7 +1147,7 @@ export const api = {
sendMessage: (
conversationId: string,
body: string,
- attachment?: ApiAttachment | null,
+ attachments?: readonly ApiAttachment[],
quotedMessageId?: string | null,
/** Optional client-supplied idempotency key (the optimistic bubble's
* tempId). The server persists it and returns the original message when
@@ -1155,7 +1158,7 @@ export const api = {
method: 'POST',
body: JSON.stringify({
body,
- attachment: attachment ?? undefined,
+ attachments: attachments?.length ? attachments : undefined,
quotedMessageId: quotedMessageId ?? undefined,
clientId: clientId ?? undefined,
}),
diff --git a/src/components/ComposerAttachments.tsx b/src/components/ComposerAttachments.tsx
new file mode 100644
index 0000000..2e2b6a1
--- /dev/null
+++ b/src/components/ComposerAttachments.tsx
@@ -0,0 +1,82 @@
+import type { ComposerAttachment } from '@/lib/composerAttachments'
+import { IClip } from '@/components/icons'
+import { cn } from '@/lib/utils'
+import { useT } from '@/lib/i18n'
+
+function sizeLabel(size: number): string | null {
+ if (!size) return null
+ if (size >= 1024 * 1024) return `${(size / 1024 / 1024).toFixed(1)} MB`
+ return `${Math.max(1, Math.round(size / 1024))} KB`
+}
+
+export function ComposerAttachments({
+ items,
+ onRemove,
+ onRetry,
+ mobile = false,
+}: {
+ items: readonly ComposerAttachment[]
+ onRemove: (id: string) => void
+ onRetry: (id: string) => void
+ mobile?: boolean
+}) {
+ const t = useT()
+ if (items.length === 0) return null
+
+ return (
+ <div
+ className={cn('mb-2 grid gap-1.5', mobile ? 'grid-cols-1' : 'grid-cols-2 max-w-[620px]')}
+ role="list"
+ aria-label={t('chat.attachments')}
+ >
+ {items.map((item) => {
+ const url = item.attachment?.url
+ return (
+ <div
+ key={item.id}
+ role="listitem"
+ className={cn(
+ 'flex min-w-0 items-center gap-2 rounded-lg border px-2 py-1.5',
+ item.state === 'error'
+ ? 'border-coral-deep/30 bg-coral-soft/50'
+ : 'border-sky2-100 bg-sky2-50',
+ )}
+ >
+ {item.kind === 'img' && url ? (
+ <img src={url} alt={item.name} className="h-10 w-10 shrink-0 rounded-md object-cover" />
+ ) : (
+ <div className="grid h-10 w-10 shrink-0 place-items-center rounded-md"
+ style={{ background: 'linear-gradient(135deg, #2A2A35, #1A1A22)' }}>
+ <IClip className="h-4 w-4 text-white/85" strokeWidth={1.8} />
+ </div>
+ )}
+ <div className="min-w-0 flex-1">
+ <div className="truncate text-[12px] font-semibold text-ink-700" title={item.name}>{item.name}</div>
+ <div className="truncate text-[10.5px] text-ink-500">
+ {item.state === 'uploading'
+ ? t('chat.uploading')
+ : item.state === 'error'
+ ? item.error ?? t('chat.uploadFailed')
+ : [item.mime, sizeLabel(item.size)].filter(Boolean).join(' · ')}
+ </div>
+ </div>
+ {item.state === 'error' && (
+ <button
+ type="button"
+ onClick={() => onRetry(item.id)}
+ className="shrink-0 rounded-md px-1.5 py-1 text-[10.5px] font-semibold text-coral-deep hover:bg-cloud transition"
+ >{t('chat.retry')}</button>
+ )}
+ <button
+ type="button"
+ onClick={() => onRemove(item.id)}
+ className="grid h-6 w-6 shrink-0 place-items-center rounded-md text-ink-500 hover:bg-cloud hover:text-ink-900 transition"
+ aria-label={t('chat.removeAttachment')}
+ title={t('chat.removeAttachment')}
+ >×</button>
+ </div>
+ )
+ })}
+ </div>
+ )
+}
diff --git a/src/components/Message.tsx b/src/components/Message.tsx
index 763fb19..b8cd500 100644
--- a/src/components/Message.tsx
+++ b/src/components/Message.tsx
@@ -946,10 +946,9 @@ function ToolCard({ msg }: { msg: Message }) {
)
}
-function AttachmentCard({ msg }: { msg: Message }) {
+function SingleAttachmentCard({ attachment }: { attachment: NonNullable<Message['attachments']>[number] }) {
const [viewerOpen, setViewerOpen] = useState(false)
- if (!msg.attachment) return null
- const a = msg.attachment
+ const a = attachment
// Real image with a URL: render inline; clicking opens the lightbox.
if (a.kind === 'img' && a.url) {
@@ -1051,6 +1050,21 @@ function AttachmentCard({ msg }: { msg: Message }) {
)
}
+function AttachmentCard({ msg }: { msg: Message }) {
+ const attachments = msg.attachments ?? []
+ if (attachments.length === 0) return null
+ return (
+ <div className={cn(
+ 'flex flex-col gap-1',
+ attachments.length > 1 && 'rounded-[12px] border border-ink-100 bg-cloud/75 p-1.5',
+ )}>
+ {attachments.map((attachment, index) => (
+ <SingleAttachmentCard key={`${attachment.key ?? attachment.url ?? attachment.name}-${index}`} attachment={attachment} />
+ ))}
+ </div>
+ )
+}
+
/* ============== email ==============
* Distinct chrome from chat bubbles: pale parchment background, subject as
* a serif headline, then a header row (from / to / cc collapsed onto one
@@ -1738,7 +1752,8 @@ function MessageRowImpl({ msg, author, delay = 0, animate = true }: MessageRowPr
const isMine = msg.authorId === meId
const isToolOnly = msg.kind === 'tool' && !msg.body
- const isAttachOnly = Boolean(msg.attachment) && !msg.body
+ const hasAttachments = Boolean(msg.attachments?.length)
+ const isAttachOnly = hasAttachments && !msg.body
const _isEmail = msg.kind === 'email'
const isPoll = msg.kind === 'poll'
// Avatar click opens InfoPane for both kinds — humans now have profile
@@ -1802,7 +1817,7 @@ function MessageRowImpl({ msg, author, delay = 0, animate = true }: MessageRowPr
))}
</div>
)}
- {msg.attachment && <AttachmentCard msg={msg} />}
+ {hasAttachments && <AttachmentCard msg={msg} />}
</>
)
diff --git a/src/data/mock.ts b/src/data/mock.ts
index 34e6f45..34070cb 100644
--- a/src/data/mock.ts
+++ b/src/data/mock.ts
@@ -252,11 +252,11 @@ export const messages: Record<string, Message[]> = {
kind: 'attachment',
body: '',
at: '13:21',
- attachment: {
+ attachments: [{
name: 'Aurora · Competitor Brief v2.pdf',
meta: '12 pages · 1.4MB · just now',
kind: 'pdf',
- },
+ }],
reactions: [
{ emoji: '🎯', count: 3 },
{ emoji: '📌', count: 1 },
@@ -290,11 +290,11 @@ export const messages: Record<string, Message[]> = {
kind: 'attachment',
body: '',
at: '13:42',
- attachment: {
+ attachments: [{
name: 'aurora.hero — v3 (race-bars).fig',
meta: '3 frames · open in Figma →',
kind: 'fig',
- },
+ }],
reactions: [
{ emoji: '🌤️', count: 1, mine: true },
{ emoji: '🔥', count: 2 },
@@ -343,11 +343,11 @@ export const messages: Record<string, Message[]> = {
kind: 'attachment',
body: '',
at: '13:40',
- attachment: {
+ attachments: [{
name: 'aurora · launch milestones.pdf',
meta: '6 pages · 320KB',
kind: 'pdf',
- },
+ }],
},
],
'direct-iris': [
diff --git a/src/desktop/ChatPane.tsx b/src/desktop/ChatPane.tsx
index dccd256..1966da1 100644
--- a/src/desktop/ChatPane.tsx
+++ b/src/desktop/ChatPane.tsx
@@ -7,7 +7,7 @@ import { isMuted, useConversations } from '@/stores/conversations'
import { useParticipants } from '@/stores/participants'
import { useMessages, sendUserMessage, messagesFor, VIRTUOSO_FIRST_INDEX_BASE } from '@/stores/messages'
import type { MessagesState } from '@/stores/messages'
-import { api, type ApiAttachment } from '@/api/client'
+import { api } from '@/api/client'
import { Avatar, AvatarStack } from '@/components/Avatar'
import { MembersPopover } from '@/components/MembersPopover'
import { PreviewText } from '@/components/PreviewText'
@@ -21,10 +21,22 @@ import { COMPOSER_EMOJIS } from '@/lib/emoji'
import { isImeComposing } from '@/lib/keyboard'
import { MessageRow, TypingRow } from '@/components/Message'
import { PollComposer } from '@/components/PollComposer'
+import { ComposerAttachments } from '@/components/ComposerAttachments'
import { ScrollToLatestButton } from '@/components/ScrollToLatestButton'
import { ISearch, IPin, IClip, IAt, ISmile, ISend, IConvene } from '@/components/icons'
import type { Participant } from '@/types'
import { useT } from '@/lib/i18n'
+import {
+ checkRuntimeSelection,
+ descriptorsToRuntime,
+ hasPendingAttachments,
+ markAttachmentFailed,
+ markAttachmentUploaded,
+ markAttachmentUploading,
+ reconcileRuntimeWithDraft,
+ readyAttachments,
+ type ComposerAttachment,
+} from '@/lib/composerAttachments'
/** Soft "Coming soon" popover anchored beneath the trigger. Auto-dismisses
* after a beat; also closes on outside-click or Escape. The sparkle
@@ -581,8 +593,7 @@ export function Composer({
// to localStorage, so a reload doesn't lose it either.
const draftsByScope = useApp((s) => s.composerDrafts)
const updateDraftInStore = useApp((s) => s.updateComposerDraft)
- const [uploadingByScope, setUploadingByScope] = useState<Record<string, boolean>>({})
- const [uploadErrorsByScope, setUploadErrorsByScope] = useState<Record<string, string>>({})
+ const [attachmentsByScope, setAttachmentsByScope] = useState<Record<string, ComposerAttachment[]>>({})
const editorRef = useRef<RichInputHandle>(null)
const fileRef = useRef<HTMLInputElement>(null)
// Per-scope "have we hydrated the editor DOM yet?" map. Switching scope
@@ -595,9 +606,13 @@ export function Composer({
const currentDraft = draftsByScope[scopeKey] ?? EMPTY_COMPOSER_DRAFT
const draft = currentDraft.text
- const attachment = currentDraft.attachment
- const uploading = Boolean(uploadingByScope[scopeKey])
- const uploadError = uploadErrorsByScope[scopeKey] ?? null
+ const attachments = useMemo(
+ () => reconcileRuntimeWithDraft(attachmentsByScope[scopeKey], currentDraft.attachments),
+ [attachmentsByScope, scopeKey, currentDraft.attachments],
+ )
+ const ready = readyAttachments(attachments)
+ const uploading = hasPendingAttachments(attachments)
+ const hasErrors = attachments.some((item) => item.state === 'error')
// Same signature as before; the empty-draft deletion and the
// nothing-changed short-circuit now live in the store so both shells share
@@ -616,40 +631,28 @@ export function Composer({
}))
}, [scopeKey, updateComposerDraft])
- const setAttachmentForScope = useCallback((targetScope: string, nextAttachment: ApiAttachment | null) => {
- updateComposerDraft(targetScope, (current) => ({
- ...current,
- attachment: nextAttachment,
- }))
- }, [updateComposerDraft])
+ const setRuntimeAttachments = useCallback((targetScope: string, next: ComposerAttachment[]) => {
+ setAttachmentsByScope((prev) => ({ ...prev, [targetScope]: next }))
+ }, [])
- const setAttachment = useCallback((nextAttachment: ApiAttachment | null) => {
- setAttachmentForScope(scopeKey, nextAttachment)
- }, [scopeKey, setAttachmentForScope])
+ const persistReadyAttachments = useCallback((targetScope: string, next: ComposerAttachment[]) => {
+ const persisted = next.flatMap((item) => item.state === 'ready' && item.attachment ? [item.attachment] : [])
+ const current = draftsRef.current[targetScope]?.attachments ?? []
+ if (persisted.length === current.length
+ && persisted.every((attachment, index) => {
+ const prior = current[index]
+ return prior?.key === attachment.key && prior.url === attachment.url
+ })) return
+ updateComposerDraft(targetScope, (draft) => ({ ...draft, attachments: persisted }))
+ }, [updateComposerDraft])
const clearComposerDraft = useCallback(() => {
updateComposerDraft(scopeKey, () => EMPTY_COMPOSER_DRAFT)
- }, [scopeKey, updateComposerDraft])
-
- const setUploadingForScope = useCallback((targetScope: string, nextUploading: boolean) => {
- setUploadingByScope((prev) => {
- if (Boolean(prev[targetScope]) === nextUploading) return prev
- const copy = { ...prev }
- if (nextUploading) copy[targetScope] = true
- else delete copy[targetScope]
- return copy
- })
- }, [])
-
- const setUploadErrorForScope = useCallback((targetScope: string, nextError: string | null) => {
- setUploadErrorsByScope((prev) => {
- if ((prev[targetScope] ?? null) === nextError) return prev
- const copy = { ...prev }
- if (nextError) copy[targetScope] = nextError
- else delete copy[targetScope]
- return copy
+ setAttachmentsByScope((prev) => {
+ if (!(scopeKey in prev)) return prev
+ return { ...prev, [scopeKey]: [] }
})
- }, [])
+ }, [scopeKey, updateComposerDraft])
// Reply state — read the quoted message id for THIS convo. The store
// keeps a per-convo map so flipping rooms preserves each room's draft.
@@ -759,51 +762,88 @@ export function Composer({
requestAnimationFrame(() => editorRef.current?.focus())
}
- const upload = async (file: File, targetScope = scopeKey) => {
- setUploadingForScope(targetScope, true)
- setUploadErrorForScope(targetScope, null)
+ const upload = async (item: ComposerAttachment, targetScope = scopeKey) => {
+ if (!item.file) return
try {
- const a = await api.uploadFile(file)
- setAttachmentForScope(targetScope, a)
+ const uploaded = await api.uploadFile(item.file)
+ setAttachmentsByScope((prev) => {
+ const next = markAttachmentUploaded(
+ prev[targetScope] ?? descriptorsToRuntime(draftsRef.current[targetScope]?.attachments ?? []),
+ item.id,
+ uploaded,
+ )
+ persistReadyAttachments(targetScope, next)
+ return { ...prev, [targetScope]: next }
+ })
} catch (err) {
const msg = err instanceof Error ? err.message : String(err)
console.warn('[upload] failed', msg)
- setUploadErrorForScope(targetScope, msg)
- // Auto-clear after a few seconds so the composer doesn't carry
- // stale error chrome into the next message.
- window.setTimeout(() => setUploadErrorForScope(targetScope, null), 4500)
- } finally {
- setUploadingForScope(targetScope, false)
+ setAttachmentsByScope((prev) => ({
+ ...prev,
+ [targetScope]: markAttachmentFailed(
+ prev[targetScope] ?? descriptorsToRuntime(draftsRef.current[targetScope]?.attachments ?? []),
+ item.id,
+ msg,
+ ),
+ }))
}
}
- const onPickFile = async (e: React.ChangeEvent<HTMLInputElement>) => {
- const f = e.target.files?.[0]
+ const addFiles = useCallback((files: File[], targetScope = scopeKey) => {
+ const current = attachmentsByScope[targetScope] ?? descriptorsToRuntime(draftsRef.current[targetScope]?.attachments ?? [])
+ const selection = checkRuntimeSelection(current, files)
+ if (!selection.ok) {
+ console.warn('[upload] selection rejected', selection.error)
+ return
+ }
+ const next = [...current, ...selection.incoming]
+ setRuntimeAttachments(targetScope, next)
+ for (const item of selection.incoming) void upload(item, targetScope)
+ }, [attachmentsByScope, scopeKey, setRuntimeAttachments])
+
+ const onPickFile = (e: React.ChangeEvent<HTMLInputElement>) => {
+ const files = Array.from(e.target.files ?? [])
e.target.value = ''
- if (f) await upload(f)
+ addFiles(files)
}
- const onPaste = async (e: React.ClipboardEvent<HTMLDivElement>) => {
+ const onPaste = (e: React.ClipboardEvent<HTMLDivElement>) => {
const items = e.clipboardData?.items
if (!items) return
+ const files: File[] = []
for (const it of items) {
if (it.kind === 'file') {
const f = it.getAsFile()
// Paste path: still images-only. Pasting an arbitrary file is
// unusual outside of clipboard hijack attacks; keep this narrow.
if (f && f.type.startsWith('image/')) {
- e.preventDefault()
- await upload(f)
- return
+ files.push(f)
}
}
}
+ if (files.length > 0) {
+ e.preventDefault()
+ addFiles(files)
+ }
}
- const onDrop = async (e: React.DragEvent<HTMLDivElement>) => {
+ const onDrop = (e: React.DragEvent<HTMLDivElement>) => {
e.preventDefault()
- const f = e.dataTransfer.files?.[0]
- if (f) await upload(f)
+ addFiles(Array.from(e.dataTransfer.files ?? []))
+ }
+
+ const removeAttachment = (id: string) => {
+ const next = attachments.filter((item) => item.id !== id)
+ setRuntimeAttachments(scopeKey, next)
+ persistReadyAttachments(scopeKey, next)
+ }
+
+ const retryAttachment = (id: string) => {
+ const item = attachments.find((candidate) => candidate.id === id)
+ if (!item?.file) return
+ const next = markAttachmentUploading(attachments, id)
+ setRuntimeAttachments(scopeKey, next)
+ void upload(item)
}
/** Insert raw text at the current caret. Skype shortcodes get a
@@ -906,9 +946,9 @@ export function Composer({
openPollComposer()
return
}
- if (!v && !attachment) return
+ if ((!v && ready.length === 0) || uploading || hasErrors) return
finalizeTyping()
- sendUserMessage(convoId, v, attachment, replyingToId ?? null)
+ void sendUserMessage(convoId, v, ready, replyingToId ?? null)
clearComposerDraft()
editorRef.current?.setValue('')
if (!isThread) setReplyingTo(convoId, null)
@@ -1007,7 +1047,7 @@ export function Composer({
requestAnimationFrame(() => editorRef.current?.focus())
}, [scopeKey])
- const canSend = (draft.trim().length > 0 || attachment !== null) && !uploading
+ const canSend = (draft.trim().length > 0 || ready.length > 0) && !uploading && !hasErrors
return (
<div className={isThread ? '' : 'px-[22px] pt-1.5 pb-[18px]'}
@@ -1040,37 +1080,7 @@ export function Composer({
isThread ? 'bg-paper' : 'bg-cloud',
)}
style={{ border: '1.5px solid var(--ink-100)' }}>
- {attachment && (
- <div className="mb-2 inline-flex items-center gap-2.5 py-1.5 px-2 bg-sky2-50 border border-sky2-100 rounded-lg max-w-full">
- {attachment.kind === 'img' ? (
- <img src={attachment.url} alt={attachment.name}
- className="w-10 h-10 object-cover rounded-md" />
- ) : (
- <div className="w-10 h-10 rounded-md grid place-items-center shrink-0"
- style={{ background: 'linear-gradient(135deg, #2A2A35, #1A1A22)' }}>
- <IClip className="w-4 h-4 text-white/85" strokeWidth={1.8} />
- </div>
- )}
- <div className="min-w-0">
- <div className="text-[12px] font-semibold text-ink-700 truncate max-w-[260px]">{attachment.name}</div>
- <div className="text-[10.5px] text-ink-500 truncate">{attachment.mime ?? attachment.kind}{attachment.size ? ` · ${Math.round(attachment.size / 1024)}KB` : ''}</div>
- </div>
- <button
- type="button"
- onClick={() => setAttachment(null)}
- className="ml-1 w-6 h-6 rounded-md grid place-items-center text-ink-500 hover:bg-cloud hover:text-ink-900 transition shrink-0"
- aria-label={t('chat.removeAttachment')}
- >×</button>
- </div>
- )}
- {uploading && (
- <div className="mb-2 text-[11.5px] text-ink-500 italic">{t('chat.uploading')}</div>
- )}
- {uploadError && (
- <div className="mb-2 text-[11.5px] py-1 px-2 rounded-md text-coral-deep bg-coral-soft inline-block max-w-full truncate">
- {uploadError}
- </div>
- )}
+ <ComposerAttachments items={attachments} onRemove={removeAttachment} onRetry={retryAttachment} />
{showReplyingPill && (
<div className="mb-2 flex items-stretch gap-2 rounded-md bg-sky2-50 border border-sky2-100 pl-2 pr-1 py-1.5 min-w-0">
<div className="w-[3px] rounded bg-skype shrink-0" />
@@ -1235,6 +1245,7 @@ export function Composer({
<input
ref={fileRef}
type="file"
+ multiple
// No `accept` — let the user pick anything; the server enforces
// the mime whitelist. Browser-side accept is only a hint anyway
// (you can still pick any file via drag-drop), so we lean on
diff --git a/src/desktop/ThreadDrawer.tsx b/src/desktop/ThreadDrawer.tsx
index a9f3e43..fd3e7f4 100644
--- a/src/desktop/ThreadDrawer.tsx
+++ b/src/desktop/ThreadDrawer.tsx
@@ -15,6 +15,7 @@ import { useApp } from '@/stores/app'
import { useMessages } from '@/stores/messages'
import { useParticipants } from '@/stores/participants'
import { api, type ApiMessage } from '@/api/client'
+import { attachmentsFromMessage } from '@/lib/messageAttachments'
import { MessageRow } from '@/components/Message'
import { Composer } from '@/desktop/ChatPane'
import type { Message, Participant } from '@/types'
@@ -23,7 +24,6 @@ import { useT } from '@/lib/i18n'
function apiToMessage(m: ApiMessage): Message {
const raw = m as unknown as {
tool?: Message['tool']
- attachment?: Message['attachment']
whisperLink?: Message['whisperLink']
quotedMessageId?: string | null
quoted?: Message['quoted'] | null
@@ -38,7 +38,7 @@ function apiToMessage(m: ApiMessage): Message {
at: m.at ?? '',
reactions: m.reactions && m.reactions.length > 0 ? m.reactions : undefined,
tool: raw.tool ?? undefined,
- attachment: raw.attachment ?? undefined,
+ attachments: attachmentsFromMessage(m),
whisperLink: raw.whisperLink ?? undefined,
quotedMessageId: raw.quotedMessageId ?? undefined,
quoted: raw.quoted ?? undefined,
diff --git a/src/lib/attachmentPolicy.ts b/src/lib/attachmentPolicy.ts
new file mode 100644
index 0000000..4d8ce15
--- /dev/null
+++ b/src/lib/attachmentPolicy.ts
@@ -0,0 +1,34 @@
+import {
+ ATTACHMENT_MAX_FILES,
+ ATTACHMENT_MAX_TOTAL_BYTES,
+ checkAttachmentSelection,
+ type AttachmentDescriptor,
+} from '../../shared/attachments'
+
+export { ATTACHMENT_MAX_FILES, ATTACHMENT_MAX_TOTAL_BYTES }
+
+export type AttachmentSelectionResult =
+ | { readonly ok: true }
+ | { readonly ok: false; readonly error: string }
+
+/** Composer-facing policy check. The canonical shared function returns a
+ * machine-readable failure; this adapter supplies copy the UI can render. */
+export function canSelectAttachments(
+ current: readonly AttachmentDescriptor[],
+ incoming: readonly AttachmentDescriptor[],
+): AttachmentSelectionResult {
+ const result = checkAttachmentSelection(current, incoming)
+ if (result.ok) return result
+ switch (result.reason) {
+ case 'too-many-files':
+ return { ok: false, error: `Attach at most ${result.maxFiles} files.` }
+ case 'file-too-large':
+ return { ok: false, error: 'Each file must be 25 MiB or smaller.' }
+ case 'total-too-large':
+ return { ok: false, error: 'Attachments must total 25 MiB or less.' }
+ default: {
+ const exhaustive: never = result.reason
+ return exhaustive
+ }
+ }
+}
diff --git a/src/lib/composerAttachments.ts b/src/lib/composerAttachments.ts
new file mode 100644
index 0000000..eb4e25d
--- /dev/null
+++ b/src/lib/composerAttachments.ts
@@ -0,0 +1,132 @@
+import {
+ ATTACHMENT_MAX_FILES,
+ type AttachmentDescriptor,
+} from '../../shared/attachments'
+import { canSelectAttachments } from './attachmentPolicy'
+import { descriptorFromApiAttachment } from './messageAttachments'
+import type { ApiAttachment } from '@/api/client'
+
+export type ComposerAttachmentState = 'uploading' | 'ready' | 'error'
+
+/** Runtime-only upload state. `id` is stable for retry and removal; `file` is
+ * kept only for a failed upload and disappears as soon as it succeeds. */
+export interface ComposerAttachment {
+ readonly id: string
+ readonly name: string
+ readonly mime: string
+ readonly size: number
+ readonly kind: ApiAttachment['kind']
+ readonly state: ComposerAttachmentState
+ readonly attachment?: ApiAttachment
+ readonly error?: string
+ readonly file?: File
+}
+
+let attachmentSequence = 0
+
+export function createComposerAttachment(file: File): ComposerAttachment {
+ attachmentSequence += 1
+ return {
+ id: `attachment-${Date.now().toString(36)}-${attachmentSequence.toString(36)}`,
+ name: file.name || (file.type.startsWith('image/') ? 'pasted-image' : 'file'),
+ mime: file.type || 'application/octet-stream',
+ size: file.size,
+ kind: file.type.startsWith('image/') ? 'img' : 'file',
+ state: 'uploading',
+ file,
+ }
+}
+
+/** Runtime attachments mirror the persisted ones, but only ready uploads
+ * participate in aggregate policy. A failed file still reserves its place in
+ * the visual order and can retry independently. */
+export function runtimeToDescriptors(items: readonly ComposerAttachment[]): AttachmentDescriptor[] {
+ return items.flatMap((item) => item.state === 'ready' && item.attachment
+ ? [descriptorFromApiAttachment(item.attachment)]
+ : [])
+}
+
+export function descriptorsToRuntime(attachments: readonly ApiAttachment[]): ComposerAttachment[] {
+ return attachments.map((attachment, index) => ({
+ id: `draft-${index}-${attachment.key ?? attachment.url}`,
+ name: attachment.name,
+ mime: attachment.mime ?? attachment.kind,
+ size: attachment.size ?? 0,
+ kind: attachment.kind,
+ state: 'ready',
+ attachment,
+ }))
+}
+
+/** Rehydrate ready runtime rows with descriptors from the persisted draft. */
+export function reconcileRuntimeWithDraft(
+ runtime: readonly ComposerAttachment[] | undefined,
+ persisted: readonly ApiAttachment[],
+): ComposerAttachment[] {
+ const restored = descriptorsToRuntime(persisted)
+ if (!runtime) return restored
+ if (runtime.length === 0) return restored
+ const restoredByKey = new Map(restored.map((item) => [
+ item.attachment?.key ?? item.attachment?.url ?? item.id,
+ item,
+ ]))
+ return runtime.map((item) => item.state === 'ready' && item.attachment
+ ? restoredByKey.get(item.attachment.key ?? item.attachment.url) ?? item
+ : item)
+}
+
+export function checkRuntimeSelection(
+ current: readonly ComposerAttachment[],
+ incomingFiles: readonly File[],
+): { ok: true; incoming: ComposerAttachment[] } | { ok: false; error: string } {
+ const incoming = incomingFiles.map(createComposerAttachment)
+ // Count every visible row, including failed uploads. Otherwise repeatedly
+ // failing files could exceed the 16-item message ceiling.
+ if (current.length + incoming.length > ATTACHMENT_MAX_FILES) {
+ return { ok: false, error: `Attach at most ${ATTACHMENT_MAX_FILES} files.` }
+ }
+ const readyCurrent = runtimeToDescriptors(current.filter((item) => item.state === 'ready'))
+ const result = canSelectAttachments(
+ readyCurrent,
+ incoming.map((item) => ({ name: item.name, kind: item.kind, size: item.size })),
+ )
+ if (!result.ok) return result
+ return { ok: true, incoming }
+}
+
+export function markAttachmentUploaded(
+ items: readonly ComposerAttachment[],
+ id: string,
+ attachment: ApiAttachment,
+): ComposerAttachment[] {
+ return items.map((item) => item.id === id
+ ? { ...item, state: 'ready', attachment, error: undefined, file: undefined }
+ : item)
+}
+
+export function markAttachmentFailed(
+ items: readonly ComposerAttachment[],
+ id: string,
+ error: string,
+): ComposerAttachment[] {
+ return items.map((item) => item.id === id
+ ? { ...item, state: 'error', error }
+ : item)
+}
+
+export function markAttachmentUploading(
+ items: readonly ComposerAttachment[],
+ id: string,
+): ComposerAttachment[] {
+ return items.map((item) => item.id === id
+ ? { ...item, state: 'uploading', error: undefined }
+ : item)
+}
+
+export function readyAttachments(items: readonly ComposerAttachment[]): ApiAttachment[] {
+ return items.flatMap((item) => item.state === 'ready' && item.attachment ? [item.attachment] : [])
+}
+
+export function hasPendingAttachments(items: readonly ComposerAttachment[]): boolean {
+ return items.some((item) => item.state === 'uploading')
+}
diff --git a/src/lib/conversationRow.ts b/src/lib/conversationRow.ts
index 4d61be4..3b0f262 100644
--- a/src/lib/conversationRow.ts
+++ b/src/lib/conversationRow.ts
@@ -1,4 +1,5 @@
import type { ApiConversation, ApiMessage } from '@/api/client'
+import { previewAttachmentsFromMessage } from './messageAttachments'
import type { Conversation } from '@/types'
/**
@@ -39,7 +40,7 @@ export function lastMessageFromWs(m: ApiMessage): NonNullable<ApiConversation['l
kind: m.kind,
body: m.body,
tool: m.tool,
- attachment: m.attachment,
+ attachment: previewAttachmentsFromMessage(m),
createdAt: m.createdAt ?? m.at,
email: m.email
? { subject: m.email.subject, direction: m.email.direction, from: m.email.from }
diff --git a/src/lib/messageAttachments.ts b/src/lib/messageAttachments.ts
new file mode 100644
index 0000000..8d6c8d0
--- /dev/null
+++ b/src/lib/messageAttachments.ts
@@ -0,0 +1,70 @@
+import {
+ normalizeAttachments,
+ validateAttachmentInput,
+ type AttachmentDescriptor,
+} from '../../shared/attachments'
+import type { ApiAttachment } from '@/api/client'
+
+export interface AttachmentWireMessage {
+ readonly attachment?: unknown
+ readonly attachments?: unknown
+}
+
+/** Read boundary for history rows and WS frames. The canonical array wins;
+ * otherwise the old singular column is normalized into a one-item list. */
+export function attachmentsFromMessage(message: AttachmentWireMessage): readonly AttachmentDescriptor[] {
+ return normalizeAttachments(message.attachments ?? message.attachment)
+}
+
+/** Legacy sidebar/mock descriptors used `meta` in place of a real URL. Keep
+ * those visible even though canonical storage-boundary parsing rejects them. */
+export function previewAttachmentsFromMessage(message: AttachmentWireMessage): readonly AttachmentDescriptor[] {
+ const canonical = attachmentsFromMessage(message)
+ if (canonical.length > 0) return canonical
+ const source = message.attachments ?? message.attachment
+ const raw = Array.isArray(source) ? source : source ? [source] : []
+ return raw.flatMap((value) => {
+ if (!value || typeof value !== 'object') return []
+ const record = value as Record<string, unknown>
+ if (typeof record.name !== 'string' || typeof record.kind !== 'string'
+ || !['img', 'pdf', 'file', 'fig'].includes(record.kind)) return []
+ const candidate = {
+ name: record.name,
+ kind: record.kind as AttachmentDescriptor['kind'],
+ ...(typeof record.url === 'string' ? { url: record.url } : {}),
+ ...(typeof record.key === 'string' ? { key: record.key } : {}),
+ ...(typeof record.mime === 'string' ? { mime: record.mime } : {}),
+ ...(typeof record.size === 'number' ? { size: record.size } : {}),
+ ...(typeof record.meta === 'string' ? { meta: record.meta } : {}),
+ }
+ if (validateAttachmentInput(candidate).ok) return [candidate]
+ // Some older sidebar WS payloads contain only a filename and kind. They
+ // can label the preview but cannot be used to read or open an attachment.
+ if (record.url === undefined && record.key === undefined && record.meta === undefined) {
+ return [{ name: candidate.name, kind: candidate.kind }]
+ }
+ return []
+ })
+}
+
+export function descriptorFromApiAttachment(attachment: ApiAttachment): AttachmentDescriptor {
+ return {
+ name: attachment.name,
+ kind: attachment.kind,
+ ...(attachment.url ? { url: attachment.url } : {}),
+ ...(attachment.key ? { key: attachment.key } : {}),
+ ...(attachment.mime ? { mime: attachment.mime } : {}),
+ ...(attachment.size ? { size: attachment.size } : {}),
+ }
+}
+
+export function apiAttachmentsFromMessage(message: AttachmentWireMessage): ApiAttachment[] {
+ return attachmentsFromMessage(message).map((attachment) => ({
+ url: attachment.url ?? '',
+ name: attachment.name,
+ kind: attachment.kind,
+ key: attachment.key,
+ mime: attachment.mime,
+ size: attachment.size,
+ }))
+}
diff --git a/src/locales/en.ts b/src/locales/en.ts
index 99fae0b..fe1e58a 100644
--- a/src/locales/en.ts
+++ b/src/locales/en.ts
@@ -203,6 +203,9 @@ export const en = {
'chat.nextMatch': 'Next match (Enter / ↓)',
'chat.closeEsc': 'Close (Esc)',
'chat.uploading': 'uploading…',
+ 'chat.uploadFailed': 'Upload failed',
+ 'chat.attachments': 'Attachments',
+ 'chat.retry': 'Retry',
'chat.removeAttachment': 'Remove attachment',
'chat.cancelReply': 'Cancel reply',
'chat.cancelReplyEsc': 'Cancel reply (Esc)',
diff --git a/src/locales/zh-CN.ts b/src/locales/zh-CN.ts
index de3e900..2087a30 100644
--- a/src/locales/zh-CN.ts
+++ b/src/locales/zh-CN.ts
@@ -207,6 +207,9 @@ export const zhCN: Partial<Record<keyof typeof en, string>> = {
'chat.nextMatch': '下一个匹配(Enter / ↓)',
'chat.closeEsc': '关闭(Esc)',
'chat.uploading': '上传中…',
+ 'chat.uploadFailed': '上传失败',
+ 'chat.attachments': '附件',
+ 'chat.retry': '重试',
'chat.removeAttachment': '移除附件',
'chat.cancelReply': '取消回复',
'chat.cancelReplyEsc': '取消回复(Esc)',
diff --git a/src/mobile/MobileChat.tsx b/src/mobile/MobileChat.tsx
index 39c0c95..99b968e 100644
--- a/src/mobile/MobileChat.tsx
+++ b/src/mobile/MobileChat.tsx
@@ -11,10 +11,11 @@ import { useMessages, sendUserMessage, messagesFor, toggleReaction, VIRTUOSO_FIR
import type { MessagesState } from '@/stores/messages'
import { Avatar, AvatarStack } from '@/components/Avatar'
import { MessageRow, TypingRow } from '@/components/Message'
+import { ComposerAttachments } from '@/components/ComposerAttachments'
import { RichInput, type RichInputHandle } from '@/components/RichInput'
import { ScrollToLatestButton } from '@/components/ScrollToLatestButton'
import { IBack, IConvene, IMore, IClip, IAt, ISmile, ISend, ISearch } from '@/components/icons'
-import { api, type ApiAttachment } from '@/api/client'
+import { api } from '@/api/client'
import type { Message, Participant } from '@/types'
import { cn } from '@/lib/utils'
import { isImeComposing } from '@/lib/keyboard'
@@ -24,6 +25,17 @@ import { SKYPE_EMOJIS, findSkypeByShortcode } from '@/lib/skypeEmojis'
import { TwEmoji } from '@/components/TwEmoji'
import { SkypeEmoji } from '@/components/SkypeEmoji'
import { useT, type MessageKey } from '@/lib/i18n'
+import {
+ checkRuntimeSelection,
+ descriptorsToRuntime,
+ hasPendingAttachments,
+ markAttachmentFailed,
+ markAttachmentUploaded,
+ markAttachmentUploading,
+ readyAttachments,
+ reconcileRuntimeWithDraft,
+ type ComposerAttachment,
+} from '@/lib/composerAttachments'
export function MobileChat() {
const t = useT()
@@ -72,14 +84,21 @@ export function MobileChat() {
// message). Send + convo-switch clears the entry; the cleanup happens
// inside `send()` and the convoId effect below.
const draft = useApp((s) => (convoId ? s.composerDrafts[convoId]?.text ?? '' : ''))
+ const persistedAttachments = useApp((s) => (convoId ? s.composerDrafts[convoId]?.attachments : undefined))
const setComposerDraft = useApp((s) => s.setComposerDraft)
+ const updateComposerDraft = useApp((s) => s.updateComposerDraft)
const setDraft = useCallback((text: string) => {
if (!convoId) return
setComposerDraft(convoId, text)
}, [convoId, setComposerDraft])
- const [attachment, setAttachment] = useState<ApiAttachment | null>(null)
- const [uploading, setUploading] = useState(false)
- const [uploadError, setUploadError] = useState<string | null>(null)
+ const [attachmentsByConvo, setAttachmentsByConvo] = useState<Record<string, ComposerAttachment[]>>({})
+ const attachments = useMemo(
+ () => convoId ? reconcileRuntimeWithDraft(attachmentsByConvo[convoId], persistedAttachments ?? []) : [],
+ [attachmentsByConvo, convoId, persistedAttachments],
+ )
+ const ready = readyAttachments(attachments)
+ const uploading = hasPendingAttachments(attachments)
+ const hasErrors = attachments.some((item) => item.state === 'error')
// Per-convo "replying to" pointer, lifted from the global app store so
// it persists across mounts and matches the desktop composer's UX.
const replyingToId = useApp((s) => convoId ? s.replyingTo[convoId] : undefined)
@@ -130,7 +149,7 @@ export function MobileChat() {
// legacy manual `el.scrollTop = el.scrollHeight` effect is gone with the
// <div> stream container it depended on.
- // Reset attachment / mention / emoji-picker side state on convo
+ // Reset mention / emoji-picker side state on convo
// switch. The composer text itself is reset by REMOUNTING RichInput
// via `key={convoId}` on the JSX below — that path reads the right
// draft from the store via defaultValue without going through
@@ -138,8 +157,6 @@ export function MobileChat() {
// contenteditable in-gesture and pops the soft keyboard.
useEffect(() => {
if (!convoId) return
- setAttachment(null)
- setUploadError(null)
setMention(null)
setEmojiOpen(false)
}, [convoId])
@@ -342,23 +359,75 @@ export function MobileChat() {
setMenuOpen(false)
}
- const upload = async (file: File) => {
- setUploading(true); setUploadError(null)
+ const upload = async (item: ComposerAttachment) => {
+ if (!convoId || !item.file) return
try {
- const a = await api.uploadFile(file)
- setAttachment(a)
+ const uploaded = await api.uploadFile(item.file)
+ setAttachmentsByConvo((prev) => {
+ const current = prev[convoId] ?? descriptorsToRuntime(useApp.getState().composerDrafts[convoId]?.attachments ?? [])
+ const next = markAttachmentUploaded(current, item.id, uploaded)
+ const persisted = next.flatMap((entry) => entry.state === 'ready' && entry.attachment ? [entry.attachment] : [])
+ updateComposerDraft(convoId, (draft) => ({ ...draft, attachments: persisted }))
+ return { ...prev, [convoId]: next }
+ })
} catch (err) {
const msg = err instanceof Error ? err.message : String(err)
- setUploadError(msg)
- window.setTimeout(() => setUploadError(null), 4500)
- } finally {
- setUploading(false)
+ setAttachmentsByConvo((prev) => ({
+ ...prev,
+ [convoId]: markAttachmentFailed(
+ prev[convoId] ?? descriptorsToRuntime(useApp.getState().composerDrafts[convoId]?.attachments ?? []),
+ item.id,
+ msg,
+ ),
+ }))
}
}
- const onPickFile = async (e: React.ChangeEvent<HTMLInputElement>) => {
- const f = e.target.files?.[0]
+ const addFiles = (files: File[]) => {
+ if (!convoId || files.length === 0) return
+ const current = attachmentsByConvo[convoId]
+ ?? descriptorsToRuntime(useApp.getState().composerDrafts[convoId]?.attachments ?? [])
+ const selection = checkRuntimeSelection(current, files)
+ if (!selection.ok) {
+ console.warn('[upload] selection rejected', selection.error)
+ return
+ }
+ setAttachmentsByConvo((prev) => ({ ...prev, [convoId]: [...current, ...selection.incoming] }))
+ for (const item of selection.incoming) void upload(item)
+ }
+ const onPickFile = (e: React.ChangeEvent<HTMLInputElement>) => {
+ const files = Array.from(e.target.files ?? [])
e.target.value = ''
- if (f) await upload(f)
+ addFiles(files)
+ }
+
+ const onPaste = (e: React.ClipboardEvent<HTMLDivElement>) => {
+ const items = e.clipboardData?.items
+ if (!items) return
+ const files: File[] = []
+ for (const item of items) {
+ if (item.kind !== 'file') continue
+ const file = item.getAsFile()
+ if (file?.type.startsWith('image/')) files.push(file)
+ }
+ if (files.length === 0) return
+ e.preventDefault()
+ addFiles(files)
+ }
+
+ const removeAttachment = (id: string) => {
+ if (!convoId) return
+ const next = attachments.filter((item) => item.id !== id)
+ setAttachmentsByConvo((prev) => ({ ...prev, [convoId]: next }))
+ const persisted = next.flatMap((item) => item.state === 'ready' && item.attachment ? [item.attachment] : [])
+ updateComposerDraft(convoId, (draft) => ({ ...draft, attachments: persisted }))
+ }
+
+ const retryAttachment = (id: string) => {
+ if (!convoId) return
+ const item = attachments.find((candidate) => candidate.id === id)
+ if (!item?.file) return
+ setAttachmentsByConvo((prev) => ({ ...prev, [convoId]: markAttachmentUploading(attachments, id) }))
+ void upload(item)
}
// Recompute mention state when the draft or caret moves. Mirrors the
@@ -435,12 +504,15 @@ export function MobileChat() {
const send = () => {
const v = draft.trim()
- if (!v && !attachment) return
+ if ((!v && ready.length === 0) || uploading || hasErrors) return
if (!convoId) return
- sendUserMessage(convoId, v, attachment, replyingToId ?? null)
+ void sendUserMessage(convoId, v, ready, replyingToId ?? null)
setDraft('')
+ setAttachmentsByConvo((prev) => {
+ if (!(convoId in prev)) return prev
+ return { ...prev, [convoId]: [] }
+ })
editorRef.current?.setValue('')
- setAttachment(null)
setMention(null)
setReplyingTo(convoId, null)
void tapHaptic()
@@ -480,7 +552,7 @@ export function MobileChat() {
send()
}
}
- const canSend = (draft.trim().length > 0 || attachment !== null) && !uploading
+ const canSend = (draft.trim().length > 0 || ready.length > 0) && !uploading && !hasErrors
const memberPs = c.members
.map((m) => byId[m])
.filter((p): p is Participant => Boolean(p))
@@ -654,37 +726,12 @@ export function MobileChat() {
<div className="px-1 pb-1">
<TypingRow names={typingNames} />
</div>
- {attachment && (
- <div className="mb-2 inline-flex items-center gap-2.5 py-1.5 px-2 bg-sky2-50 border border-sky2-100 rounded-lg max-w-full">
- {attachment.kind === 'img' ? (
- <img src={attachment.url} alt={attachment.name}
- className="w-10 h-10 object-cover rounded-md shrink-0" />
- ) : (
- <div className="w-10 h-10 rounded-md grid place-items-center shrink-0"
- style={{ background: 'linear-gradient(135deg, #2A2A35, #1A1A22)' }}>
- <IClip className="w-4 h-4 text-white/85" strokeWidth={1.8} />
- </div>
- )}
- <div className="min-w-0">
- <div className="text-[12px] font-semibold text-ink-700 truncate max-w-[220px]">{attachment.name}</div>
- <div className="text-[10.5px] text-ink-500 truncate">{attachment.mime ?? attachment.kind}{attachment.size ? ` · ${Math.round(attachment.size / 1024)}KB` : ''}</div>
- </div>
- <button
- type="button"
- onClick={() => setAttachment(null)}
- className="ml-1 w-6 h-6 rounded-md grid place-items-center text-ink-500 active:bg-cloud transition shrink-0"
- aria-label={t('mobchat.removeAttachment')}
- >×</button>
- </div>
- )}
- {uploading && (
- <div className="mb-2 text-[11.5px] text-ink-500 italic">{t('mobchat.uploading')}</div>
- )}
- {uploadError && (
- <div className="mb-2 text-[11.5px] py-1 px-2 rounded-md text-coral-deep bg-coral-soft inline-block max-w-full truncate">
- {uploadError}
- </div>
- )}
+ <ComposerAttachments
+ items={attachments}
+ onRemove={removeAttachment}
+ onRetry={retryAttachment}
+ mobile
+ />
{replyingToId && convoId && (
<div className="mb-2 flex items-stretch gap-2 rounded-md bg-sky2-50 border border-sky2-100 pl-2 pr-1 py-1.5">
<div className="w-[3px] rounded bg-skype shrink-0" />
@@ -767,6 +814,7 @@ export function MobileChat() {
<input
ref={fileRef}
type="file"
+ multiple
// No `accept` filter — server's MIME whitelist is the source
// of truth. Browser-side accept is only a hint anyway.
className="hidden"
@@ -805,6 +853,7 @@ export function MobileChat() {
}}
onBlur={() => setTimeout(() => setMention(null), 120)}
onKeyDown={onKey}
+ onPaste={onPaste}
resolveMention={(id) => {
if (id === 'all') {
return { name: 'all', initial: '@', avatarBg: 'var(--ink-300)', kind: 'human' }
diff --git a/src/stores/composerDrafts.ts b/src/stores/composerDrafts.ts
index d55fb5c..551e96a 100644
--- a/src/stores/composerDrafts.ts
+++ b/src/stores/composerDrafts.ts
@@ -27,9 +27,10 @@ export interface DraftAttachment {
export interface ComposerDraft {
text: string
- /** An upload the user already paid for. Dropping it on navigation loses a
- * file that is sitting in storage, so it rides along with the text. */
- attachment: DraftAttachment | null
+ /** Ordered uploads already stored by the server. In-flight and failed local
+ * files stay in the composer runtime so a reload only restores sendable
+ * files. */
+ attachments: DraftAttachment[]
}
/** Keyed by composer SCOPE, not conversation: the desktop thread drawer is a
@@ -48,14 +49,14 @@ export const MAX_DRAFTS = 50
* for the whole origin; drafts are a guest in it, not the tenant. */
export const MAX_SERIALIZED_BYTES = 256 * 1024
-export const EMPTY_DRAFT: ComposerDraft = { text: '', attachment: null }
+export const EMPTY_DRAFT: ComposerDraft = { text: '', attachments: [] }
export function emptyComposerDraft(): ComposerDraft {
return EMPTY_DRAFT
}
export function isEmptyDraft(d: ComposerDraft): boolean {
- return d.text === '' && d.attachment === null
+ return d.text === '' && d.attachments.length === 0
}
/** Re-insert a key so it lands at the end of the object's iteration order.
@@ -83,7 +84,7 @@ export function applyDraftUpdate(
): ComposerDrafts {
const current = drafts[scope] ?? EMPTY_DRAFT
const next = updater(current)
- if (next.text === current.text && next.attachment === current.attachment) return drafts
+ if (next.text === current.text && next.attachments === current.attachments) return drafts
if (isEmptyDraft(next)) {
if (!(scope in drafts)) return drafts
const copy = { ...drafts }
@@ -113,15 +114,26 @@ export function parseStoredDrafts(raw: string | null): ComposerDrafts {
const out: ComposerDrafts = {}
for (const [scope, value] of Object.entries(parsed as Record<string, unknown>)) {
if (!scope || typeof value !== 'object' || value === null) continue
- const v = value as { text?: unknown; attachment?: unknown }
+ const v = value as { text?: unknown; attachment?: unknown; attachments?: unknown }
const text = typeof v.text === 'string' ? v.text : ''
- const attachment = parseAttachment(v.attachment)
- const draft: ComposerDraft = { text, attachment }
+ // `attachment` is the old single-file draft shape. Keep accepting it
+ // indefinitely so users who upgrade with a stored draft do not lose it.
+ const source = v.attachments === undefined ? v.attachment : v.attachments
+ const attachments = parseAttachments(source)
+ const draft: ComposerDraft = { text, attachments }
if (!isEmptyDraft(draft)) out[scope] = draft
}
return evict(out)
}
+function parseAttachments(value: unknown): DraftAttachment[] {
+ if (value === null || value === undefined) return []
+ const source = Array.isArray(value) ? value : [value]
+ return source
+ .map(parseAttachment)
+ .filter((attachment): attachment is DraftAttachment => attachment !== null)
+}
+
function parseAttachment(value: unknown): DraftAttachment | null {
if (!value || typeof value !== 'object') return null
const a = value as Record<string, unknown>
diff --git a/src/stores/conversations.ts b/src/stores/conversations.ts
index 245a34d..4b87807 100644
--- a/src/stores/conversations.ts
+++ b/src/stores/conversations.ts
@@ -130,12 +130,16 @@ function previewOf(last: ApiConversation['lastMessage']): string {
// optional caption. Prefix with a 📎 + filename so the row reads
// as "shared a file" instead of going blank when the user uploads
// without a caption.
- const a = last.attachment
+ const first = Array.isArray(last.attachment) ? last.attachment[0] : last.attachment
+ const count = Array.isArray(last.attachment) ? last.attachment.length : 1
+ if (!first) return trimmedBody
+ const a = first
const verb = a.kind === 'img' ? '📷' : '📎'
const filename = a.name ?? (a.kind === 'img' ? 'image' : 'file')
+ const fileLabel = count > 1 ? `${filename} +${count - 1}` : filename
const label = trimmedBody
- ? `${verb} ${filename} — ${trimmedBody.slice(0, 80)}`
- : `${verb} ${filename}`
+ ? `${verb} ${fileLabel} — ${trimmedBody.slice(0, 80)}`
+ : `${verb} ${fileLabel}`
return authorName ? `${authorName}: ${label}` : label
}
if (trimmedBody) {
diff --git a/src/stores/messages.ts b/src/stores/messages.ts
index 33d2731..82e2308 100644
--- a/src/stores/messages.ts
+++ b/src/stores/messages.ts
@@ -1,7 +1,8 @@
import { create } from 'zustand'
import type { Message, ReactionEntry } from '@/types'
import { applyReplyCountDelta } from '@/lib/replyCount'
-import { api, ApiError, ws, type WsEvent, type ApiMessage } from '@/api/client'
+import { api, ApiError, ws, type ApiAttachment, type WsEvent, type ApiMessage } from '@/api/client'
+import { attachmentsFromMessage, apiAttachmentsFromMessage } from '@/lib/messageAttachments'
import { useApp } from '@/stores/app'
import { getMeId } from '@/stores/auth'
@@ -251,7 +252,6 @@ function fromApi(m: ApiMessage): Message {
}
const raw = m as unknown as {
tool?: Message['tool']
- attachment?: Message['attachment']
whisperLink?: Message['whisperLink']
quotedMessageId?: string | null
quoted?: Message['quoted'] | null
@@ -270,7 +270,7 @@ function fromApi(m: ApiMessage): Message {
at,
reactions: deriveMineForReactions(m.reactions),
tool: raw.tool ?? undefined,
- attachment: raw.attachment ?? undefined,
+ attachments: attachmentsFromMessage(m),
whisperLink: raw.whisperLink ?? undefined,
quotedMessageId: raw.quotedMessageId ?? undefined,
quoted: raw.quoted ?? undefined,
@@ -676,17 +676,17 @@ function isDefinitiveSendFailure(error: unknown): boolean {
export async function sendUserMessage(
convoId: string,
body: string,
- attachment?: import('@/api/client').ApiAttachment | null,
+ attachments: readonly ApiAttachment[] = [],
quotedMessageId?: string | null,
clientId = newTempId(),
): Promise<void> {
const v = body.trim()
- if (!v && !attachment) return
+ if (!v && attachments.length === 0) return
const meId = getMeId()
// Without a signed-in user we can't paint an optimistic bubble (no authorId
// to attribute it to). Fall back to the old fire-and-forget path.
if (!meId) {
- try { await api.sendMessage(convoId, v, attachment ?? null, quotedMessageId ?? null) }
+ try { await api.sendMessage(convoId, v, attachments, quotedMessageId ?? null) }
catch (err) { console.warn('[messages] send failed', err) }
return
}
@@ -720,16 +720,14 @@ export async function sendUserMessage(
kind: 'text',
body: v,
at: timeFromIso(),
- attachment: attachment
- ? {
- name: attachment.name,
- kind: attachment.kind,
- url: attachment.url,
- key: attachment.key,
- mime: attachment.mime,
- size: attachment.size,
- }
- : undefined,
+ attachments: attachments.map((attachment) => ({
+ name: attachment.name,
+ kind: attachment.kind,
+ url: attachment.url,
+ key: attachment.key,
+ mime: attachment.mime,
+ size: attachment.size,
+ })),
quotedMessageId: quotedMessageId ?? undefined,
quoted: quotedSummary,
pending: true,
@@ -756,7 +754,7 @@ export async function sendUserMessage(
}))
try {
- const { id: realId } = await api.sendMessage(convoId, v, attachment ?? null, quotedMessageId ?? null, clientId)
+ const { id: realId } = await api.sendMessage(convoId, v, attachments, quotedMessageId ?? null, clientId)
// Reconcile the temp bubble with the server. Either the WS `message.new`
// already raced ahead of us (real id already in the list → drop the temp)
// or it hasn't (rename temp → real id so the eventual WS event dedupes
@@ -818,14 +816,11 @@ export async function retryFailedMessage(convoId: string, tempId: string): Promi
const msg = list.find((m) => m.id === tempId)
if (!msg) return
const body = msg.body ?? ''
- const att = msg.attachment
- const retryAttachment: import('@/api/client').ApiAttachment | null = att
- ? { url: att.url ?? '', name: att.name, kind: att.kind, key: att.key, mime: att.mime, size: att.size }
- : null
+ const retryAttachments = apiAttachmentsFromMessage(msg)
const quotedId = msg.quotedMessageId ?? null
const clientId = msg.clientId ?? tempId
discardFailedMessage(convoId, tempId)
- await sendUserMessage(convoId, body, retryAttachment, quotedId, clientId)
+ await sendUserMessage(convoId, body, retryAttachments, quotedId, clientId)
}
export async function toggleReaction(messageId: string, emoji: string): Promise<void> {
diff --git a/src/types.ts b/src/types.ts
index 2e5d68e..0436ef1 100644
--- a/src/types.ts
+++ b/src/types.ts
@@ -1,3 +1,5 @@
+import type { AttachmentDescriptor } from '../shared/attachments'
+
export type AgentRole = 'researcher' | 'designer' | 'engineer' | 'pm' | 'brand' | 'ops'
export type ParticipantKind = 'agent' | 'human'
export type Status = 'avail' | 'working' | 'thinking' | 'waiting' | 'resting'
@@ -15,6 +17,8 @@ export interface EngineModelOption {
description?: string | null
recommendedFor?: Array<'big' | 'small'>
supportsFastMode?: boolean
+ /** Explicit capability claim from the paired daemon. Missing is unknown. */
+ vision?: 'supported' | 'unsupported' | 'unknown'
}
export interface EngineModelCatalog {
@@ -269,20 +273,11 @@ export interface Message {
detail: string
icon?: 'web' | 'github' | 'figma' | 'db'
}
- /** for attachments */
- attachment?: {
- name: string
- /** kind 'img' renders inline; others render as a file card */
- kind: 'img' | 'pdf' | 'file' | 'fig'
- /** real assets carry a URL; mock/legacy data may not */
- url?: string
- /** Storage key used to refresh expiring signed URLs. */
- key?: string
- mime?: string
- size?: number
- /** legacy descriptor — fallback when no real file is present (e.g. mock data) */
- meta?: string
- }
+ /** Canonical ordered list. Older history and realtime payloads may still
+ * carry the first item through the singular compatibility field below. */
+ attachments?: readonly AttachmentDescriptor[]
+ /** Legacy single-attachment compatibility projection. */
+ attachment?: AttachmentDescriptor | null
/** for whisper-link cards in main chat */
whisperLink?: {
pair: [string, string]
diff --git a/tests/attachment-policy.test.ts b/tests/attachment-policy.test.ts
new file mode 100644
index 0000000..f70017c
--- /dev/null
+++ b/tests/attachment-policy.test.ts
@@ -0,0 +1,33 @@
+import assert from 'node:assert/strict'
+import { test } from 'node:test'
+import type { AttachmentDescriptor } from '../shared/attachments'
+import { canSelectAttachments } from '../src/lib/attachmentPolicy'
+
+const file = (name: string, size: number): AttachmentDescriptor => ({
+ name,
+ kind: 'file',
+ url: `/uploads/attachments/${name}`,
+ size,
+})
+
+test('client policy accepts a selection inside every limit', () => {
+ assert.deepEqual(canSelectAttachments([file('a', 10)], [file('b', 20)]), { ok: true })
+})
+
+test('client policy reports count, per-file, and aggregate failures', () => {
+ assert.deepEqual(canSelectAttachments([], Array.from({ length: 17 }, (_, index) => file(String(index), 1))), {
+ ok: false,
+ error: 'Attach at most 16 files.',
+ })
+ assert.deepEqual(canSelectAttachments([], [file('huge', 25 * 1024 * 1024 + 1)]), {
+ ok: false,
+ error: 'Each file must be 25 MiB or smaller.',
+ })
+ assert.deepEqual(canSelectAttachments(
+ [file('a', 13 * 1024 * 1024)],
+ [file('b', 13 * 1024 * 1024)],
+ ), {
+ ok: false,
+ error: 'Attachments must total 25 MiB or less.',
+ })
+})
diff --git a/tests/composer-attachments.test.ts b/tests/composer-attachments.test.ts
new file mode 100644
index 0000000..8fdf552
--- /dev/null
+++ b/tests/composer-attachments.test.ts
@@ -0,0 +1,45 @@
+import assert from 'node:assert/strict'
+import { describe, it } from 'node:test'
+import {
+ descriptorsToRuntime,
+ markAttachmentFailed,
+ markAttachmentUploaded,
+ readyAttachments,
+ reconcileRuntimeWithDraft,
+ runtimeToDescriptors,
+} from '../src/lib/composerAttachments'
+import type { ApiAttachment } from '../src/api/client'
+
+const uploaded = (name: string, size = 1): ApiAttachment => ({
+ name,
+ kind: 'file',
+ url: `/files/${name}`,
+ key: `attachments/${name}`,
+ mime: 'text/plain',
+ size,
+})
+
+describe('composer attachment lifecycle', () => {
+ it('keeps a failed upload isolated while its siblings remain sendable', () => {
+ const [first, second] = descriptorsToRuntime([uploaded('first.txt'), uploaded('second.txt')])
+ const failed = markAttachmentFailed([first, second], first.id, 'offline')
+
+ assert.equal(failed[0].state, 'error')
+ assert.deepEqual(readyAttachments(failed), [second.attachment])
+ assert.deepEqual(runtimeToDescriptors(failed), [{
+ name: 'second.txt', kind: 'file', url: '/files/second.txt',
+ key: 'attachments/second.txt', mime: 'text/plain', size: 1,
+ }])
+ })
+
+ it('preserves list order when an upload succeeds', () => {
+ const [first, second] = descriptorsToRuntime([uploaded('first.txt'), uploaded('second.txt')])
+ const next = markAttachmentUploaded([first, second], first.id, uploaded('first-final.txt'))
+ assert.deepEqual(readyAttachments(next).map((attachment) => attachment.name), ['first-final.txt', 'second.txt'])
+ })
+
+ it('rehydrates persisted attachments in their stored order', () => {
+ const restored = reconcileRuntimeWithDraft(undefined, [uploaded('a.txt'), uploaded('b.txt')])
+ assert.deepEqual(restored.map((item) => item.name), ['a.txt', 'b.txt'])
+ })
+})
diff --git a/tests/composer-drafts.test.ts b/tests/composer-drafts.test.ts
new file mode 100644
index 0000000..80427bc
--- /dev/null
+++ b/tests/composer-drafts.test.ts
@@ -0,0 +1,37 @@
+import assert from 'node:assert/strict'
+import { describe, it } from 'node:test'
+import {
+ applyDraftUpdate,
+ parseStoredDrafts,
+ serializeDrafts,
+ type ComposerDrafts,
+} from '../src/stores/composerDrafts'
+
+const first = { name: 'first.pdf', kind: 'pdf' as const, url: '/first.pdf', key: 'attachments/first.pdf', size: 10 }
+const second = { name: 'second.png', kind: 'img' as const, url: '/second.png', key: 'attachments/second.png', size: 20 }
+
+describe('composer draft attachment persistence', () => {
+ it('migrates the legacy singular attachment into an ordered array', () => {
+ const drafts = parseStoredDrafts(JSON.stringify({
+ room: { text: 'keep me', attachment: first },
+ }))
+ assert.deepEqual(drafts.room, { text: 'keep me', attachments: [first] })
+ })
+
+ it('round-trips multiple attachments without changing their order', () => {
+ const drafts: ComposerDrafts = {
+ room: { text: 'two files', attachments: [first, second] },
+ }
+ const json = serializeDrafts(drafts)
+ assert.ok(json)
+ assert.deepEqual(parseStoredDrafts(json), drafts)
+ })
+
+ it('deletes an emptied draft only when text and every attachment are gone', () => {
+ const drafts: ComposerDrafts = { room: { text: '', attachments: [first] } }
+ assert.deepEqual(applyDraftUpdate(drafts, 'room', (draft) => ({ ...draft, text: 'caption' })).room, {
+ text: 'caption', attachments: [first],
+ })
+ assert.deepEqual(applyDraftUpdate(drafts, 'room', (draft) => ({ ...draft, attachments: [] })), {})
+ })
+})
diff --git a/tests/conversation-row.test.ts b/tests/conversation-row.test.ts
index dd00c8c..91291d2 100644
--- a/tests/conversation-row.test.ts
+++ b/tests/conversation-row.test.ts
@@ -88,7 +88,7 @@ describe('WS payload → last-message shape', () => {
it('keeps the attachment descriptor the preview renders a 📎 from', () => {
const attachment = { name: 'contract.pdf', kind: 'pdf' as const }
- assert.deepEqual(lastMessageFromWs(wsMessage({ attachment })).attachment, attachment)
+ assert.deepEqual(lastMessageFromWs(wsMessage({ attachment })).attachment, [attachment])
})
})
diff --git a/tests/message-attachments.test.ts b/tests/message-attachments.test.ts
new file mode 100644
index 0000000..2db046d
--- /dev/null
+++ b/tests/message-attachments.test.ts
@@ -0,0 +1,44 @@
+import assert from 'node:assert/strict'
+import { readFileSync } from 'node:fs'
+import { describe, it } from 'node:test'
+import type { ApiMessage } from '../src/api/client'
+import { attachmentsFromMessage } from '../src/lib/messageAttachments'
+
+function message(overrides: Partial<ApiMessage>): ApiMessage {
+ return {
+ id: 'm-1', conversationId: 'room', authorId: 'user', kind: 'text',
+ body: '', at: '12:00', sequence: 1, ...overrides,
+ }
+}
+
+describe('message attachment normalization', () => {
+ it('turns a legacy singular attachment into an ordered list', () => {
+ const normalized = message({
+ attachment: { name: 'old.pdf', kind: 'pdf', url: '/old.pdf', key: 'attachments/old.pdf' },
+ })
+ assert.deepEqual(attachmentsFromMessage(normalized), [{
+ name: 'old.pdf', kind: 'pdf', url: '/old.pdf', key: 'attachments/old.pdf',
+ }])
+ })
+
+ it('keeps every canonical attachment in history order', () => {
+ const attachments = [
+ { name: 'one.png', kind: 'img' as const, url: '/one.png' },
+ { name: 'two.pdf', kind: 'pdf' as const, url: '/two.pdf' },
+ { name: 'three.zip', kind: 'file' as const, url: '/three.zip' },
+ ]
+ assert.deepEqual(attachmentsFromMessage(message({ attachments })), attachments)
+ })
+})
+
+describe('chat send wire payload', () => {
+ it('sends the full ordered attachments array rather than the legacy field', () => {
+ const source = readFileSync(new URL('../src/api/client.ts', import.meta.url), 'utf8')
+ const sendStart = source.indexOf('sendMessage: (')
+ const sendEnd = source.indexOf('/* ============== Polls', sendStart)
+ const sendSource = source.slice(sendStart, sendEnd)
+ assert.match(sendSource, /attachments\?: readonly ApiAttachment\[\]/)
+ assert.match(sendSource, /attachments: attachments\?\.length \? attachments : undefined/)
+ assert.doesNotMatch(sendSource, /attachment: attachment \?\? undefined/)
+ })
+})
diff --git a/tests/messages-history.test.ts b/tests/messages-history.test.ts
index cf060a6..fdf0762 100644
--- a/tests/messages-history.test.ts
+++ b/tests/messages-history.test.ts
@@ -6,6 +6,7 @@ import ts from 'typescript'
import { create } from 'zustand'
import type { ApiMessage } from '../src/api/client'
import { applyReplyCountDelta } from '../src/lib/replyCount'
+import { attachmentsFromMessage, apiAttachmentsFromMessage } from '../src/lib/messageAttachments'
import type { Message } from '../src/types'
// Execute the actual store with an in-memory API, without loading the browser
@@ -40,6 +41,7 @@ function setup(last: number, cache: Message[] = messages(1, 80)) {
zustand: { create },
'@/api/client': { api },
'@/lib/replyCount': { applyReplyCountDelta },
+ '@/lib/messageAttachments': { attachmentsFromMessage, apiAttachmentsFromMessage },
'@/stores/auth': { getMeId: () => 'user' },
'@/stores/app': { useApp: { getState: () => ({ selectedConversationId: 'chat' }) } },
}