diff --git a/hub/scripts/attachments.ts b/hub/scripts/attachments.ts new file mode 100644 index 00000000..ea98900e --- /dev/null +++ b/hub/scripts/attachments.ts @@ -0,0 +1,245 @@ +#!/usr/bin/env bun +/** + * Manage the hub's durable chat-image attachment store + * (`~/.hapi/attachments`, table `chat_attachments`). + * + * Usage: + * bun run hub/scripts/attachments.ts stats + * bun run hub/scripts/attachments.ts verify + * bun run hub/scripts/attachments.ts gc [--yes] + * bun run hub/scripts/attachments.ts export --session --out + * + * - stats totals for DB rows vs files on disk (orphan/missing counts) + * - verify sha256-check every registered file; lists missing/corrupt entries + * - gc deletes files on disk that no DB row references (dry-run by default) + * - export copies one session's attachments to a directory using their names + */ + +import { Database } from 'bun:sqlite' +import { createHash } from 'node:crypto' +import { copyFile, mkdir, readdir, readFile, rm, stat } from 'node:fs/promises' +import { homedir } from 'node:os' +import { join, relative, resolve } from 'node:path' + +interface Row { + session_id: string + id: string + filename: string + mime_type: string + size: number + sha256: string + storage_key: string + created_at: number +} + +function hapiHomeDir(): string { + return process.env.HAPI_HOME || join(homedir(), '.hapi') +} + +function attachmentsRoot(): string { + return join(hapiHomeDir(), 'attachments') +} + +function openDb(): Database { + const dbPath = join(hapiHomeDir(), 'hapi.db') + return new Database(dbPath, { readonly: true, create: false }) +} + +async function listFilesOnDisk(): Promise { + const root = attachmentsRoot() + const keys: string[] = [] + const walk = async (dir: string) => { + let entries + try { + entries = await readdir(dir, { withFileTypes: true }) + } catch { + return + } + for (const entry of entries) { + const full = join(dir, entry.name) + if (entry.isDirectory()) { + await walk(full) + } else if (entry.isFile()) { + keys.push(relative(root, full)) + } + } + } + await walk(root) + return keys +} + +function formatBytes(bytes: number): string { + if (bytes < 1024) return `${bytes} B` + if (bytes < 1024 * 1024) return `${(bytes / 1024).toFixed(1)} KB` + if (bytes < 1024 * 1024 * 1024) return `${(bytes / 1024 / 1024).toFixed(1)} MB` + return `${(bytes / 1024 / 1024 / 1024).toFixed(2)} GB` +} + +async function cmdStats(): Promise { + const db = openDb() + try { + const rows = db.prepare( + 'SELECT session_id, id, filename, mime_type, size, sha256, storage_key, created_at FROM chat_attachments' + ).all() as Row[] + const diskKeys = new Set(await listFilesOnDisk()) + const registered = new Set(rows.map((row) => row.storage_key)) + const orphans = [...diskKeys].filter((key) => !registered.has(key)) + const missing = rows.filter((row) => !diskKeys.has(row.storage_key)) + let diskBytes = 0 + for (const key of diskKeys) { + try { + diskBytes += (await stat(join(attachmentsRoot(), key))).size + } catch { + // raced with manual cleanup + } + } + const totalBytes = rows.reduce((sum, row) => sum + row.size, 0) + const bySession = new Map() + for (const row of rows) { + const entry = bySession.get(row.session_id) ?? { count: 0, bytes: 0 } + entry.count += 1 + entry.bytes += row.size + bySession.set(row.session_id, entry) + } + const top = [...bySession.entries()].sort((a, b) => b[1].bytes - a[1].bytes).slice(0, 10) + + console.log(`root: ${attachmentsRoot()}`) + console.log(`registered: ${rows.length} files, ${formatBytes(totalBytes)}`) + console.log(`on disk: ${diskKeys.size} files, ${formatBytes(diskBytes)}`) + console.log(`orphan files (no DB row): ${orphans.length}`) + console.log(`missing files (row without file): ${missing.length}`) + if (top.length > 0) { + console.log('top sessions:') + for (const [sessionId, entry] of top) { + console.log(` ${formatBytes(entry.bytes).padStart(10)} ${String(entry.count).padStart(4)} files ${sessionId}`) + } + } + } finally { + db.close() + } +} + +async function cmdVerify(): Promise { + const db = openDb() + try { + const rows = db.prepare( + 'SELECT session_id, id, filename, mime_type, size, sha256, storage_key, created_at FROM chat_attachments' + ).all() as Row[] + let ok = 0 + let missing = 0 + let corrupt = 0 + for (const row of rows) { + let buffer: Buffer + try { + buffer = await readFile(join(attachmentsRoot(), row.storage_key)) + } catch { + missing += 1 + console.log(`MISSING ${row.session_id} ${row.id} ${row.filename}`) + continue + } + const sha256 = createHash('sha256').update(buffer).digest('hex') + if (sha256 !== row.sha256 || buffer.length !== row.size) { + corrupt += 1 + console.log(`CORRUPT ${row.session_id} ${row.id} ${row.filename}`) + continue + } + ok += 1 + } + console.log(`verified: ${ok} ok, ${missing} missing, ${corrupt} corrupt (of ${rows.length})`) + if (missing + corrupt > 0) process.exitCode = 1 + } finally { + db.close() + } +} + +async function cmdGc(apply: boolean): Promise { + const db = openDb() + try { + const rows = db.prepare('SELECT storage_key FROM chat_attachments').all() as Array<{ storage_key: string }> + const registered = new Set(rows.map((row) => row.storage_key)) + const orphans = (await listFilesOnDisk()).filter((key) => !registered.has(key)) + if (orphans.length === 0) { + console.log('no orphan files') + return + } + let bytes = 0 + for (const key of orphans) { + try { + bytes += (await stat(join(attachmentsRoot(), key))).size + } catch { + // ignore + } + } + console.log(`orphan files: ${orphans.length} (${formatBytes(bytes)})`) + for (const key of orphans.slice(0, 20)) console.log(` ${key}`) + if (orphans.length > 20) console.log(` ... and ${orphans.length - 20} more`) + if (!apply) { + console.log('dry-run: nothing deleted (pass --yes to delete)') + return + } + for (const key of orphans) { + await rm(join(attachmentsRoot(), key), { force: true }) + } + console.log(`deleted ${orphans.length} orphan files (freed ${formatBytes(bytes)})`) + } finally { + db.close() + } +} + +async function cmdExport(sessionId: string, outDir: string): Promise { + if (!sessionId.trim()) throw new Error('--session is required') + if (!outDir.trim()) throw new Error('--out is required') + const db = openDb() + try { + const rows = db.prepare( + 'SELECT session_id, id, filename, mime_type, size, sha256, storage_key, created_at FROM chat_attachments WHERE session_id = ? ORDER BY created_at ASC' + ).all(sessionId) as Row[] + if (rows.length === 0) { + console.log(`no attachments for session ${sessionId}`) + return + } + const target = resolve(outDir) + await mkdir(target, { recursive: true }) + let copied = 0 + for (const [index, row] of rows.entries()) { + try { + const source = join(attachmentsRoot(), row.storage_key) + const name = `${String(index + 1).padStart(3, '0')}-${row.filename}` + await copyFile(source, join(target, name)) + copied += 1 + } catch { + console.log(`MISSING ${row.id} ${row.filename}`) + } + } + console.log(`exported ${copied}/${rows.length} files to ${target}`) + } finally { + db.close() + } +} + +function usage(): void { + console.log('usage: bun run hub/scripts/attachments.ts [options]') + console.log(' gc [--yes] delete unreferenced files (dry-run without --yes)') + console.log(' export --session --out copy one session attachments out') +} + +const [command, ...rest] = process.argv.slice(2) +const apply = rest.includes('--yes') +const argValue = (name: string): string => { + const index = rest.indexOf(name) + return index >= 0 ? (rest[index + 1] ?? '') : '' +} + +try { + if (command === 'stats') await cmdStats() + else if (command === 'verify') await cmdVerify() + else if (command === 'gc') await cmdGc(apply) + else if (command === 'export') await cmdExport(argValue('--session'), argValue('--out')) + else { + usage() + process.exitCode = 1 + } +} catch (error) { + console.error(error instanceof Error ? error.message : String(error)) + process.exitCode = 1 +} diff --git a/hub/src/chatAttachments/storage.test.ts b/hub/src/chatAttachments/storage.test.ts new file mode 100644 index 00000000..f3df665a --- /dev/null +++ b/hub/src/chatAttachments/storage.test.ts @@ -0,0 +1,62 @@ +import { describe, expect, it } from 'bun:test' +import { mkdtempSync, rmSync } from 'node:fs' +import { tmpdir } from 'node:os' +import { join } from 'node:path' + +import { + buildChatAttachmentStorageKey, + deleteChatAttachmentFile, + readChatAttachmentFile, + resolveChatAttachmentStoragePath, + writeChatAttachmentFile +} from './storage' + +describe('chat attachment storage', () => { + it('writes, reads and deletes original bytes with a sha256 fingerprint', async () => { + const home = mkdtempSync(join(tmpdir(), 'hapi-chat-att-')) + try { + const buffer = Buffer.from('image-bytes') + const { storageKey, sha256, size } = await writeChatAttachmentFile( + home, + 'session-1', + 'att-1', + 'photo.png', + buffer + ) + expect(storageKey).toBe('session-1/att-1-photo.png') + expect(sha256).toHaveLength(64) + expect(size).toBe(buffer.length) + + const read = await readChatAttachmentFile(home, storageKey) + expect(read?.toString()).toBe('image-bytes') + + await deleteChatAttachmentFile(home, storageKey) + expect(await readChatAttachmentFile(home, storageKey)).toBeNull() + } finally { + rmSync(home, { recursive: true, force: true }) + } + }) + + it('rejects storage keys that escape the attachments root', () => { + const home = mkdtempSync(join(tmpdir(), 'hapi-chat-att-')) + try { + expect(() => resolveChatAttachmentStoragePath(home, '../escape.png')).toThrow( + 'Invalid chat attachment path' + ) + expect(() => resolveChatAttachmentStoragePath(home, 'session/../../escape.png')).toThrow( + 'Invalid chat attachment path' + ) + } finally { + rmSync(home, { recursive: true, force: true }) + } + }) + + it('sanitizes path separators and traversal in ids and filenames', () => { + const key = buildChatAttachmentStorageKey('s/1', 'a..b', '../../x.png') + expect(key.startsWith('s_1/')).toBe(true) + const filePart = key.slice('s_1/'.length) + expect(filePart).not.toContain('..') + expect(filePart).not.toContain('/') + expect(filePart.endsWith('x.png')).toBe(true) + }) +}) diff --git a/hub/src/chatAttachments/storage.ts b/hub/src/chatAttachments/storage.ts new file mode 100644 index 00000000..db5cbb00 --- /dev/null +++ b/hub/src/chatAttachments/storage.ts @@ -0,0 +1,88 @@ +import { mkdir, readFile, rm, writeFile } from 'node:fs/promises' +import { createHash } from 'node:crypto' +import { join, resolve, sep } from 'node:path' + +import { getHapiHomeDir } from '../scratchlistAttachments/storage' + +export { getHapiHomeDir } + +function sanitizeSegment(segment: string): string { + return segment.replace(/[/\\]/g, '_').replace(/\.\./g, '_').slice(0, 128) +} + +function sanitizeFilename(filename: string): string { + const sanitized = filename + .replace(/[/\\]/g, '_') + .replace(/\.\./g, '_') + .replace(/[\r\n\0"\\]/g, '_') + .replace(/[\u0000-\u001f\u007f]/g, '_') + .replace(/\s+/g, '_') + .slice(0, 200) + return sanitized || 'attachment' +} + +export function getChatAttachmentsRoot(hapiHome: string = getHapiHomeDir()): string { + return join(hapiHome, 'attachments') +} + +export function buildChatAttachmentStorageKey( + sessionId: string, + attachmentId: string, + filename: string +): string { + return `${sanitizeSegment(sessionId)}/${sanitizeSegment(attachmentId)}-${sanitizeFilename(filename)}` +} + +export function resolveChatAttachmentStoragePath(hapiHome: string, storageKey: string): string { + const root = resolve(getChatAttachmentsRoot(hapiHome)) + const resolved = resolve(root, storageKey) + const prefix = root.endsWith(sep) ? root : `${root}${sep}` + if (!resolved.startsWith(prefix)) { + throw new Error('Invalid chat attachment path') + } + return resolved +} + +/** Persist the original bytes of a chat image attachment; idempotent per id. */ +export async function writeChatAttachmentFile( + hapiHome: string, + sessionId: string, + attachmentId: string, + filename: string, + buffer: Buffer +): Promise<{ storageKey: string; sha256: string; size: number }> { + const storageKey = buildChatAttachmentStorageKey(sessionId, attachmentId, filename) + const filePath = resolveChatAttachmentStoragePath(hapiHome, storageKey) + await mkdir(join(filePath, '..'), { recursive: true }) + await writeFile(filePath, buffer) + return { + storageKey, + sha256: createHash('sha256').update(buffer).digest('hex'), + size: buffer.length + } +} + +export async function readChatAttachmentFile( + hapiHome: string, + storageKey: string +): Promise { + try { + const filePath = resolveChatAttachmentStoragePath(hapiHome, storageKey) + return await readFile(filePath) + } catch { + return null + } +} + +export async function deleteChatAttachmentFile( + hapiHome: string, + storageKey: string +): Promise { + try { + const filePath = resolveChatAttachmentStoragePath(hapiHome, storageKey) + await rm(filePath, { force: true }) + return true + } catch { + return false + } +} diff --git a/hub/src/store/chatAttachments.ts b/hub/src/store/chatAttachments.ts new file mode 100644 index 00000000..ebbe1411 --- /dev/null +++ b/hub/src/store/chatAttachments.ts @@ -0,0 +1,104 @@ +import type { Database } from 'bun:sqlite' + +export type StoredChatAttachment = { + sessionId: string + id: string + filename: string + mimeType: string + size: number + sha256: string + storageKey: string + createdAt: number +} + +type ChatAttachmentRow = { + session_id: string + id: string + filename: string + mime_type: string + size: number + sha256: string + storage_key: string + created_at: number +} + +function toStoredChatAttachment(row: ChatAttachmentRow): StoredChatAttachment { + return { + sessionId: row.session_id, + id: row.id, + filename: row.filename, + mimeType: row.mime_type, + size: row.size, + sha256: row.sha256, + storageKey: row.storage_key, + createdAt: row.created_at + } +} + +const COLUMNS = 'session_id, id, filename, mime_type, size, sha256, storage_key, created_at' + +/** Durable hub copies of chat image attachments (schema v27). */ +export class ChatAttachmentsStore { + private readonly db: Database + + constructor(db: Database) { + this.db = db + } + + upsert(attachment: StoredChatAttachment): void { + this.db.prepare(` + INSERT INTO chat_attachments (${COLUMNS}) + VALUES (@session_id, @id, @filename, @mime_type, @size, @sha256, @storage_key, @created_at) + ON CONFLICT(session_id, id) DO UPDATE SET + filename = excluded.filename, + mime_type = excluded.mime_type, + size = excluded.size, + sha256 = excluded.sha256, + storage_key = excluded.storage_key + `).run({ + session_id: attachment.sessionId, + id: attachment.id, + filename: attachment.filename, + mime_type: attachment.mimeType, + size: attachment.size, + sha256: attachment.sha256, + storage_key: attachment.storageKey, + created_at: attachment.createdAt + }) + } + + get(sessionId: string, id: string): StoredChatAttachment | null { + const row = this.db.prepare( + `SELECT ${COLUMNS} FROM chat_attachments WHERE session_id = ? AND id = ?` + ).get(sessionId, id) as ChatAttachmentRow | undefined + return row ? toStoredChatAttachment(row) : null + } + + listBySession(sessionId: string): StoredChatAttachment[] { + const rows = this.db.prepare( + `SELECT ${COLUMNS} FROM chat_attachments WHERE session_id = ? ORDER BY created_at ASC` + ).all(sessionId) as ChatAttachmentRow[] + return rows.map(toStoredChatAttachment) + } + + listAll(): StoredChatAttachment[] { + const rows = this.db.prepare( + `SELECT ${COLUMNS} FROM chat_attachments ORDER BY session_id, created_at ASC` + ).all() as ChatAttachmentRow[] + return rows.map(toStoredChatAttachment) + } + + delete(sessionId: string, id: string): boolean { + const result = this.db.prepare( + 'DELETE FROM chat_attachments WHERE session_id = ? AND id = ?' + ).run(sessionId, id) + return result.changes > 0 + } + + sumBytes(): number { + const row = this.db.prepare( + 'SELECT COALESCE(SUM(size), 0) AS total FROM chat_attachments' + ).get() as { total: number } + return row.total + } +} diff --git a/hub/src/store/index.ts b/hub/src/store/index.ts index 59b79db2..d1b957d8 100644 --- a/hub/src/store/index.ts +++ b/hub/src/store/index.ts @@ -9,6 +9,7 @@ import type { StoredMessage } from './types' import { PushStore } from './pushStore' import { FcmStore } from './fcmStore' import { ScratchlistStore } from './scratchlistStore' +import { ChatAttachmentsStore } from './chatAttachments' import { SessionStore } from './sessionStore' import { UserStore } from './userStore' import { UsageStore } from './usageStore' @@ -39,6 +40,7 @@ export { MessageStore } from './messageStore' export { PushStore } from './pushStore' export { FcmStore } from './fcmStore' export { ScratchlistStore } from './scratchlistStore' +export { ChatAttachmentsStore } from './chatAttachments' export { SessionStore } from './sessionStore' export { UserStore } from './userStore' export { UsageStore } from './usageStore' @@ -54,7 +56,7 @@ export { // Usage history is a durable namespace ledger. Keep it independent from // session lifetime so deleting a session cannot erase historical totals. -const SCHEMA_VERSION: number = 26 +export const SCHEMA_VERSION: number = 27 const REQUIRED_TABLES = [ 'sessions', 'machines', @@ -64,6 +66,7 @@ const REQUIRED_TABLES = [ 'push_subscriptions', 'fcm_devices', 'session_scratchlist', + 'chat_attachments', 'usage_events', 'usage_scan_state', 'events', @@ -84,6 +87,7 @@ export class Store { readonly push: PushStore readonly fcm: FcmStore readonly scratchlist: ScratchlistStore + readonly chatAttachments: ChatAttachmentsStore readonly usage: UsageStore readonly studios: StudioStore readonly workGraph: WorkGraphStore @@ -142,6 +146,7 @@ export class Store { this.push = new PushStore(this.db) this.fcm = new FcmStore(this.db) this.scratchlist = new ScratchlistStore(this.db) + this.chatAttachments = new ChatAttachmentsStore(this.db) this.usage = new UsageStore(this.db) this.studios = new StudioStore(this.db) this.workGraph = new WorkGraphStore(this.db) @@ -368,6 +373,7 @@ export class Store { 23: () => this.migrateFromV23ToV24(), 24: () => this.migrateFromV24ToV25(), 25: () => this.migrateFromV25ToV26(), + 26: () => this.migrateFromV26ToV27(), }) if (currentVersion === 0) { @@ -653,6 +659,20 @@ export class Store { ); CREATE INDEX IF NOT EXISTS idx_studio_posts_room_created ON studio_posts(room_id, created_at ASC); + + CREATE TABLE IF NOT EXISTS chat_attachments ( + session_id TEXT NOT NULL, + id TEXT NOT NULL, + filename TEXT NOT NULL, + mime_type TEXT NOT NULL, + size INTEGER NOT NULL, + sha256 TEXT NOT NULL, + storage_key TEXT NOT NULL, + created_at INTEGER NOT NULL, + PRIMARY KEY (session_id, id) + ); + CREATE INDEX IF NOT EXISTS idx_chat_attachments_session + ON chat_attachments(session_id, created_at); `) } @@ -1171,6 +1191,29 @@ export class Store { `) } + /** + * Durable hub-side copies of chat image attachments, served by + * /api/sessions/:id/attachments/:attachmentId with ETag caching. The + * message payload keeps only a small thumbnail; the original lives here. + */ + private migrateFromV26ToV27(): void { + this.db.exec(` + CREATE TABLE IF NOT EXISTS chat_attachments ( + session_id TEXT NOT NULL, + id TEXT NOT NULL, + filename TEXT NOT NULL, + mime_type TEXT NOT NULL, + size INTEGER NOT NULL, + sha256 TEXT NOT NULL, + storage_key TEXT NOT NULL, + created_at INTEGER NOT NULL, + PRIMARY KEY (session_id, id) + ); + CREATE INDEX IF NOT EXISTS idx_chat_attachments_session + ON chat_attachments(session_id, created_at); + `) + } + /** * A2A Layer 1 / P1 (#1374) + P3 substrate: hub work-graph ledger tables. * Namespace + principal_json required on every events row. diff --git a/hub/src/store/migration-v13.test.ts b/hub/src/store/migration-v13.test.ts index 7c355f6e..6aadef95 100644 --- a/hub/src/store/migration-v13.test.ts +++ b/hub/src/store/migration-v13.test.ts @@ -3,14 +3,14 @@ import { Database } from 'bun:sqlite' import { mkdtempSync, rmSync } from 'node:fs' import { join } from 'node:path' import { tmpdir } from 'node:os' -import { Store } from './index' +import { SCHEMA_VERSION, Store } from './index' describe('Store V12/V13→V14 schema reconciliation', () => { it('fresh DB has both reconciled tables', () => { const store = new Store(':memory:') expect(tableExists(store, 'message_epochs')).toBe(true) expect(tableExists(store, 'session_scratchlist')).toBe(true) - expect(getUserVersion(store)).toBe(26) + expect(getUserVersion(store)).toBe(SCHEMA_VERSION) store.close() }) @@ -34,7 +34,7 @@ describe('Store V12/V13→V14 schema reconciliation', () => { store = new Store(dbPath) expect(tableExists(store, 'message_epochs')).toBe(true) expect(tableExists(store, 'session_scratchlist')).toBe(true) - expect(getUserVersion(store)).toBe(26) + expect(getUserVersion(store)).toBe(SCHEMA_VERSION) expect(store.messages.getMessageEpoch('session-1')).toBe(0) expect(store.messages.getMessages('session-1')).toHaveLength(1) } finally { @@ -72,7 +72,7 @@ describe('Store V12/V13→V14 schema reconciliation', () => { store = new Store(dbPath) expect(tableExists(store, 'message_epochs')).toBe(true) expect(tableExists(store, 'session_scratchlist')).toBe(true) - expect(getUserVersion(store)).toBe(26) + expect(getUserVersion(store)).toBe(SCHEMA_VERSION) expect(store.messages.getMessages('session-1')).toHaveLength(1) } finally { store?.close() diff --git a/hub/src/store/migration-v15.test.ts b/hub/src/store/migration-v15.test.ts index f3bdf273..bbe55a08 100644 --- a/hub/src/store/migration-v15.test.ts +++ b/hub/src/store/migration-v15.test.ts @@ -3,7 +3,7 @@ import { Database } from 'bun:sqlite' import { mkdtempSync, rmSync } from 'node:fs' import { join } from 'node:path' import { tmpdir } from 'node:os' -import { Store } from './index' +import { SCHEMA_VERSION, Store } from './index' /** * Tests for V14→V15 schema migration: adds `session_scratchlist.attachments` @@ -19,7 +19,7 @@ describe('Store V14→V15 migration: scratchlist attachments column', () => { expect(cols).toContain('attachments') expect(getColumns(store, 'usage_events')).toContain('last_input_tokens') expect(getColumns(store, 'usage_scan_state')).toContain('last_seq') - expect(getUserVersion(store)).toBe(26) + expect(getUserVersion(store)).toBe(SCHEMA_VERSION) store.close() }) @@ -40,7 +40,7 @@ describe('Store V14→V15 migration: scratchlist attachments column', () => { expect(cols).toContain('attachments') expect(getColumns(store, 'usage_events')).toContain('last_input_tokens') expect(getColumns(store, 'usage_scan_state')).toContain('last_seq') - expect(getUserVersion(store)).toBe(26) + expect(getUserVersion(store)).toBe(SCHEMA_VERSION) } finally { store?.close() rmSync(dir, { recursive: true, force: true }) @@ -60,7 +60,7 @@ describe('Store V14→V15 migration: scratchlist attachments column', () => { store2 = new Store(dbPath) const cols2 = getColumns(store2, 'session_scratchlist') expect(cols2).toEqual(cols1) - expect(getUserVersion(store2)).toBe(26) + expect(getUserVersion(store2)).toBe(SCHEMA_VERSION) } finally { store2?.close() store1?.close() diff --git a/hub/src/store/migration-v18.test.ts b/hub/src/store/migration-v18.test.ts index 2c31127b..9a638881 100644 --- a/hub/src/store/migration-v18.test.ts +++ b/hub/src/store/migration-v18.test.ts @@ -3,7 +3,7 @@ import { Database } from 'bun:sqlite' import { mkdtempSync, rmSync } from 'node:fs' import { join } from 'node:path' import { tmpdir } from 'node:os' -import { Store } from './index' +import { SCHEMA_VERSION, Store } from './index' describe('Store V18->V19 migration: usage scan state', () => { it('adds the usage_scan_state table to a V18 database', () => { @@ -38,7 +38,7 @@ describe('Store V18->V19 migration: usage scan state', () => { const usageRows = internalDb.prepare('SELECT COUNT(*) AS count FROM usage_events').get() as { count: number } expect(table?.name).toBe('usage_scan_state') - expect(version.user_version).toBe(26) + expect(version.user_version).toBe(SCHEMA_VERSION) expect(usageRows.count).toBe(0) } finally { store?.close() diff --git a/hub/src/store/migration-v19.test.ts b/hub/src/store/migration-v19.test.ts index 888b7455..bc1bf2d3 100644 --- a/hub/src/store/migration-v19.test.ts +++ b/hub/src/store/migration-v19.test.ts @@ -3,7 +3,7 @@ import { Database } from 'bun:sqlite' import { mkdtempSync, rmSync } from 'node:fs' import { join } from 'node:path' import { tmpdir } from 'node:os' -import { Store } from './index' +import { SCHEMA_VERSION, Store } from './index' import { getUsageSummary } from '../sync/usageService' describe('Store V19->current migration: usage re-index', () => { @@ -37,7 +37,7 @@ describe('Store V19->current migration: usage re-index', () => { const scanRows = internalDb.prepare('SELECT COUNT(*) AS count FROM usage_scan_state').get() as { count: number } const usageRows = internalDb.prepare('SELECT COUNT(*) AS count FROM usage_events').get() as { count: number } - expect(version.user_version).toBe(26) + expect(version.user_version).toBe(SCHEMA_VERSION) expect(scanRows.count).toBe(0) expect(usageRows.count).toBe(0) } finally { diff --git a/hub/src/store/migration-v20.test.ts b/hub/src/store/migration-v20.test.ts index fba1a455..39852a31 100644 --- a/hub/src/store/migration-v20.test.ts +++ b/hub/src/store/migration-v20.test.ts @@ -4,7 +4,7 @@ import { mkdtempSync, rmSync } from 'node:fs' import { join } from 'node:path' import { tmpdir } from 'node:os' import { getUsageSummary } from '../sync/usageService' -import { Store } from './index' +import { SCHEMA_VERSION, Store } from './index' describe('Store V20->V21 migration: usage semantics re-index', () => { it('clears both derived tables, preserves messages, and lazily rebuilds idempotently', () => { @@ -43,7 +43,7 @@ describe('Store V20->V21 migration: usage semantics re-index', () => { store = new Store(dbPath) const internalDb = (store as unknown as { db: Database }).db const count = (table: string): number => (internalDb.prepare(`SELECT COUNT(*) AS count FROM ${table}`).get() as { count: number }).count - expect((internalDb.prepare('PRAGMA user_version').get() as { user_version: number }).user_version).toBe(26) + expect((internalDb.prepare('PRAGMA user_version').get() as { user_version: number }).user_version).toBe(SCHEMA_VERSION) expect(count('usage_events')).toBe(0) expect(count('usage_scan_state')).toBe(0) expect(store.messages.getMessages(session.id)).toHaveLength(1) diff --git a/hub/src/store/migration-v23.test.ts b/hub/src/store/migration-v23.test.ts index 191fa1cd..f3d30de7 100644 --- a/hub/src/store/migration-v23.test.ts +++ b/hub/src/store/migration-v23.test.ts @@ -3,7 +3,7 @@ import { Database } from 'bun:sqlite' import { mkdtempSync, rmSync } from 'node:fs' import { tmpdir } from 'node:os' import { join } from 'node:path' -import { Store } from './index' +import { SCHEMA_VERSION, Store } from './index' const tempDirs: string[] = [] @@ -42,7 +42,7 @@ describe('schema migration v22 to v26', () => { expect(links?.name).toBe('event_links') const columns = internalDb.prepare('PRAGMA table_info(messages)').all() as Array<{ name: string }> expect(columns.map((column) => column.name)).toContain('delivery_state') - expect(version.user_version).toBe(26) + expect(version.user_version).toBe(SCHEMA_VERSION) migrated.close() }) }) diff --git a/hub/src/store/migration-v25.test.ts b/hub/src/store/migration-v25.test.ts index c72bac7e..daf250ed 100644 --- a/hub/src/store/migration-v25.test.ts +++ b/hub/src/store/migration-v25.test.ts @@ -3,7 +3,7 @@ import { Database } from 'bun:sqlite' import { mkdtempSync, rmSync } from 'node:fs' import { tmpdir } from 'node:os' import { join } from 'node:path' -import { Store } from './index' +import { SCHEMA_VERSION, Store } from './index' const tempDirs: string[] = [] @@ -41,7 +41,7 @@ describe('schema migration v25 to v26', () => { ORDER BY seq ASC `).all('session-id') as Array<{ detail: string }> - expect(version.user_version).toBe(26) + expect(version.user_version).toBe(SCHEMA_VERSION) expect(plan.some((row) => row.detail.includes('idx_messages_immediate_queued'))).toBe(true) migrated.close() }) diff --git a/hub/src/sync/syncEngine.ts b/hub/src/sync/syncEngine.ts index b5b6c4ce..af3078a5 100644 --- a/hub/src/sync/syncEngine.ts +++ b/hub/src/sync/syncEngine.ts @@ -4062,6 +4062,62 @@ export class SyncEngine { return await this.rpcGateway.uploadFile(sessionId, filename, content, mimeType) } + /** + * Keep a durable hub copy of an uploaded chat image. The message payload + * carries only a small thumbnail; this copy backs the session attachment + * URL used for zoom-to-original. Non-image uploads are not copied. + */ + async saveChatAttachmentCopy( + sessionId: string, + attachmentId: string, + filename: string, + mimeType: string, + contentBase64: string + ): Promise<{ id: string; url: string } | null> { + if (!mimeType.startsWith('image/')) return null + const buffer = Buffer.from(contentBase64, 'base64') + if (buffer.length === 0) return null + const { writeChatAttachmentFile, getHapiHomeDir } = await import('../chatAttachments/storage') + const { storageKey, sha256, size } = await writeChatAttachmentFile( + getHapiHomeDir(), + sessionId, + attachmentId, + filename, + buffer + ) + this.store.chatAttachments.upsert({ + sessionId, + id: attachmentId, + filename, + mimeType, + size, + sha256, + storageKey, + createdAt: Date.now() + }) + return { id: attachmentId, url: `/api/sessions/${sessionId}/attachments/${attachmentId}` } + } + + async readChatAttachment( + sessionId: string, + attachmentId: string + ): Promise<{ buffer: Buffer; mimeType: string; filename: string; sha256: string } | null> { + const row = this.store.chatAttachments.get(sessionId, attachmentId) + if (!row) return null + const { readChatAttachmentFile, getHapiHomeDir } = await import('../chatAttachments/storage') + const buffer = await readChatAttachmentFile(getHapiHomeDir(), row.storageKey) + if (!buffer) return null + return { buffer, mimeType: row.mimeType, filename: row.filename, sha256: row.sha256 } + } + + async deleteChatAttachment(sessionId: string, attachmentId: string): Promise { + const row = this.store.chatAttachments.get(sessionId, attachmentId) + if (!row) return false + const { deleteChatAttachmentFile, getHapiHomeDir } = await import('../chatAttachments/storage') + await deleteChatAttachmentFile(getHapiHomeDir(), row.storageKey) + return this.store.chatAttachments.delete(sessionId, attachmentId) + } + async deleteUploadFile(sessionId: string, path: string): Promise { return await this.rpcGateway.deleteUploadFile(sessionId, path) } diff --git a/hub/src/web/mediaCache.ts b/hub/src/web/mediaCache.ts new file mode 100644 index 00000000..7ed02872 --- /dev/null +++ b/hub/src/web/mediaCache.ts @@ -0,0 +1,15 @@ +// Media bytes addressed by an immutable id/fingerprint never change, so they +// are cached for a year as immutable (generated images, chat attachments). +export const IMMUTABLE_MEDIA_CACHE_CONTROL = 'private, max-age=31536000, immutable' + +// Weak comparison of an If-None-Match header against our ETag (handles lists, `*`, and W/ prefixes). +export function ifNoneMatchMatches(header: string | undefined, etag: string): boolean { + if (!header) { + return false + } + const normalized = etag.replace(/^W\//, '') + return header.split(',').some((candidate) => { + const trimmed = candidate.trim() + return trimmed === '*' || trimmed.replace(/^W\//, '') === normalized + }) +} diff --git a/hub/src/web/routes/git.ts b/hub/src/web/routes/git.ts index 24dde9c5..872c8c4c 100644 --- a/hub/src/web/routes/git.ts +++ b/hub/src/web/routes/git.ts @@ -4,6 +4,7 @@ import { z } from 'zod' import type { SyncEngine } from '../../sync/syncEngine' import type { WebAppEnv } from '../middleware/auth' import { requireSessionFromParam, requireSyncEngine } from './guards' +import { IMMUTABLE_MEDIA_CACHE_CONTROL as GENERATED_IMAGE_CACHE_CONTROL, ifNoneMatchMatches } from '../mediaCache' const fileSearchSchema = z.object({ query: z.string().optional(), @@ -44,20 +45,6 @@ async function runRpc(fn: () => Promise): Promise { - const trimmed = candidate.trim() - return trimmed === '*' || trimmed.replace(/^W\//, '') === normalized - }) -} export function createGitRoutes(getSyncEngine: () => SyncEngine | null): Hono { const app = new Hono() diff --git a/hub/src/web/routes/sessions.test.ts b/hub/src/web/routes/sessions.test.ts index 3377601d..bc1019ad 100644 --- a/hub/src/web/routes/sessions.test.ts +++ b/hub/src/web/routes/sessions.test.ts @@ -74,6 +74,7 @@ function createApp(session: Session, opts?: { updateSessionSummary?: SyncEngine['updateSessionSummary'] setSessionPinned?: (sessionId: string, pinned: boolean) => void setSessionPinMode?: (sessionId: string, mode: 'none' | 'project' | 'global') => void + readChatAttachment?: SyncEngine['readChatAttachment'] }) { const applySessionConfigCalls: Array<[string, Record]> = [] const applySessionConfig = async (sessionId: string, config: Record) => { @@ -173,7 +174,8 @@ function createApp(session: Session, opts?: { implementCodexPlan: opts?.implementCodexPlan, rewindConversation: opts?.rewindConversation ?? (async () => ({ type: 'success' })), suggestSessionTitle: opts?.suggestSessionTitle ?? (async () => 'Generated title'), - updateSessionSummary: opts?.updateSessionSummary ?? (async () => {}) + updateSessionSummary: opts?.updateSessionSummary ?? (async () => {}), + readChatAttachment: opts?.readChatAttachment ?? (async () => null) } as Partial const app = new Hono() @@ -187,6 +189,32 @@ function createApp(session: Session, opts?: { } describe('sessions routes', () => { + it('serves chat attachments with an immutable ETag and answers 304 revalidation', async () => { + const session = createSession() + const { app } = createApp(session, { + readChatAttachment: async () => ({ + buffer: Buffer.from('img-bytes'), + mimeType: 'image/png', + filename: 'photo.png', + sha256: 'abc123' + }) + }) + const first = await app.request('/api/sessions/session-1/attachments/att-1') + expect(first.status).toBe(200) + expect(first.headers.get('etag')).toBe('"abc123"') + expect(first.headers.get('cache-control')).toContain('immutable') + expect(await first.text()).toBe('img-bytes') + + const second = await app.request('/api/sessions/session-1/attachments/att-1', { + headers: { 'if-none-match': '"abc123"' } + }) + expect(second.status).toBe(304) + + const missing = createApp(createSession()) + expect((await missing.app.request('/api/sessions/session-1/attachments/att-1')).status).toBe(404) + expect((await missing.app.request('/api/sessions/session-1/attachments/bad%2Fid')).status).toBe(400) + }) + it('dispatches plan implementation using the authenticated namespace and returns stale/unknown outcomes', async () => { const session = createSession({ metadata: { path: '/tmp', host: 'test', flavor: 'codex', capabilities: { concurrentClients: true } } }) const calls: unknown[] = [] diff --git a/hub/src/web/routes/sessions.ts b/hub/src/web/routes/sessions.ts index 73591d0a..42203a1f 100644 --- a/hub/src/web/routes/sessions.ts +++ b/hub/src/web/routes/sessions.ts @@ -34,6 +34,7 @@ import { loadScratchlistAttachmentLimitsFromEnv } from '../../config/scratchlist import { validateScratchlistAttachmentsForWrite, scratchlistSessionBytesBeforeForPut } from '../../scratchlistAttachments/validate' import { TitleSuggestionError } from '../../sync/titleSuggestion' import { requireSessionFromParam, requireSyncEngine } from './guards' +import { IMMUTABLE_MEDIA_CACHE_CONTROL, ifNoneMatchMatches } from '../mediaCache' const MAX_UPLOAD_BYTES = 50 * 1024 * 1024 @@ -315,6 +316,26 @@ export function createSessionsRoutes(getSyncEngine: () => SyncEngine | null): Ho parsed.data.content, parsed.data.mimeType ) + // Keep a durable hub copy of images so the chat can show a small + // thumbnail inline and lazy-load the original from a cached URL. + // Copy failures must not fail the upload: the agent still gets the + // file, only zoom-to-original degrades. + if (result.success && parsed.data.attachmentId) { + try { + const saved = await engine.saveChatAttachmentCopy( + sessionResult.sessionId, + parsed.data.attachmentId, + parsed.data.filename, + parsed.data.mimeType, + parsed.data.content + ) + if (saved) { + return c.json({ ...result, attachmentId: saved.id, attachmentUrl: saved.url }) + } + } catch { + // Best-effort copy; keep the successful upload response. + } + } return c.json(result) } catch (error) { return c.json({ @@ -324,6 +345,46 @@ export function createSessionsRoutes(getSyncEngine: () => SyncEngine | null): Ho } }) + app.get('/sessions/:id/attachments/:attachmentId', async (c) => { + const engine = requireSyncEngine(c, getSyncEngine) + if (engine instanceof Response) { + return engine + } + + const sessionResult = requireSessionFromParam(c, engine) + if (sessionResult instanceof Response) { + return sessionResult + } + + const attachmentId = c.req.param('attachmentId') + if (!/^[A-Za-z0-9._-]{1,64}$/.test(attachmentId)) { + return c.json({ error: 'Invalid attachment id' }, 400) + } + + const attachment = await engine.readChatAttachment(sessionResult.sessionId, attachmentId) + if (!attachment) { + return c.json({ error: 'Attachment not found' }, 404) + } + + // The sha256 is a content fingerprint, so it doubles as the ETag. Answer + // 304 before re-reading bytes when the client already holds this version. + const etag = `"${attachment.sha256}"` + if (ifNoneMatchMatches(c.req.header('if-none-match'), etag)) { + return c.body(null, 304, { + 'Cache-Control': IMMUTABLE_MEDIA_CACHE_CONTROL, + ETag: etag + }) + } + + return c.body(Uint8Array.from(attachment.buffer), 200, { + 'Content-Type': attachment.mimeType, + 'Content-Disposition': `inline; filename="${encodeURIComponent(attachment.filename)}"`, + 'X-Content-Type-Options': 'nosniff', + 'Cache-Control': IMMUTABLE_MEDIA_CACHE_CONTROL, + ETag: etag + }) + }) + app.post('/sessions/:id/upload/delete', async (c) => { const engine = requireSyncEngine(c, getSyncEngine) if (engine instanceof Response) { @@ -343,6 +404,13 @@ export function createSessionsRoutes(getSyncEngine: () => SyncEngine | null): Ho try { const result = await engine.deleteUploadFile(sessionResult.sessionId, parsed.data.path) + if (parsed.data.attachmentId) { + try { + await engine.deleteChatAttachment(sessionResult.sessionId, parsed.data.attachmentId) + } catch { + // Best effort: an orphaned copy is reclaimable by the attachments gc script. + } + } return c.json(result) } catch (error) { return c.json({ diff --git a/shared/src/apiTypes.ts b/shared/src/apiTypes.ts index 25691f44..6a6d07a4 100644 --- a/shared/src/apiTypes.ts +++ b/shared/src/apiTypes.ts @@ -716,13 +716,16 @@ export type CursorMigrateRefusalReason = export const UploadFileRequestSchema = z.object({ filename: z.string().min(1).max(255), content: z.string().min(1), - mimeType: z.string().min(1).max(255) + mimeType: z.string().min(1).max(255), + /** Client attachment id; lets the hub keep a durable copy addressable by id. */ + attachmentId: z.string().min(1).max(64).regex(/^[A-Za-z0-9._-]+$/).optional() }) export type UploadFileRequest = z.infer export const DeleteUploadRequestSchema = z.object({ - path: z.string().min(1) + path: z.string().min(1), + attachmentId: z.string().min(1).max(64).regex(/^[A-Za-z0-9._-]+$/).optional() }) export type DeleteUploadRequest = z.infer @@ -955,6 +958,10 @@ export type GeneratedImageResponse = { export type UploadFileResponse = { success: boolean path?: string + /** Set when the hub kept a durable image copy for web display. */ + attachmentId?: string + /** Session-scoped URL for the hub copy, e.g. /api/sessions//attachments/. */ + attachmentUrl?: string error?: string } diff --git a/shared/src/schemas.ts b/shared/src/schemas.ts index ac3e1808..5bf8721f 100644 --- a/shared/src/schemas.ts +++ b/shared/src/schemas.ts @@ -318,7 +318,9 @@ export const AttachmentMetadataSchema = z.object({ mimeType: z.string(), size: z.number(), path: z.string(), - previewUrl: z.string().optional() + previewUrl: z.string().optional(), + /** Hub-served original image URL for zoom-to-full-size (web display detail). */ + attachmentUrl: z.string().optional() }) export type AttachmentMetadata = z.infer diff --git a/web/src/api/client.ts b/web/src/api/client.ts index 5d7d6a07..12d95564 100644 --- a/web/src/api/client.ts +++ b/web/src/api/client.ts @@ -766,20 +766,46 @@ export class ApiClient { ) } - async uploadFile(sessionId: string, filename: string, content: string, mimeType: string): Promise { + async uploadFile(sessionId: string, filename: string, content: string, mimeType: string, attachmentId?: string): Promise { return await this.request(`/api/sessions/${encodeURIComponent(sessionId)}/upload`, { method: 'POST', - body: JSON.stringify({ filename, content, mimeType }) + body: JSON.stringify(attachmentId ? { filename, content, mimeType, attachmentId } : { filename, content, mimeType }) }) } - async deleteUploadFile(sessionId: string, path: string): Promise { + async deleteUploadFile(sessionId: string, path: string, attachmentId?: string): Promise { return await this.request(`/api/sessions/${encodeURIComponent(sessionId)}/upload/delete`, { method: 'POST', - body: JSON.stringify({ path }) + body: JSON.stringify(attachmentId ? { path, attachmentId } : { path }) }) } + /** Hub-served original of a chat image attachment; immutable + ETag cached. */ + async getSessionAttachmentBlob(sessionId: string, attachmentId: string, attempt: number = 0): Promise { + const headers = new Headers() + const liveToken = this.getToken ? this.getToken() : null + const authToken = liveToken ?? this.token + if (authToken) { + headers.set('authorization', `Bearer ${authToken}`) + } + const url = this.buildUrl(`/api/sessions/${encodeURIComponent(sessionId)}/attachments/${encodeURIComponent(attachmentId)}`) + let res = await fetch(url, { headers }) + if (res.status === 304) { + res = await fetch(url, { headers, cache: 'force-cache' }) + } + if (res.status === 401 && attempt === 0 && this.onUnauthorized) { + const refreshed = await this.onUnauthorized() + if (refreshed) { + this.token = refreshed + return await this.getSessionAttachmentBlob(sessionId, attachmentId, attempt + 1) + } + } + if (!res.ok) { + throw new ApiError(`HTTP ${res.status}`, res.status, undefined, await res.text().catch(() => undefined)) + } + return await res.blob() + } + async resumeSession(sessionId: string, opts?: { permissionMode?: string }): Promise { const response = await this.request<{ sessionId: string }>( `/api/sessions/${encodeURIComponent(sessionId)}/resume`, diff --git a/web/src/chat/normalizeUser.ts b/web/src/chat/normalizeUser.ts index a9733e89..292a913e 100644 --- a/web/src/chat/normalizeUser.ts +++ b/web/src/chat/normalizeUser.ts @@ -20,7 +20,8 @@ function parseAttachments(raw: unknown): AttachmentMetadata[] | undefined { mimeType: item.mimeType, size: item.size, path: item.path, - previewUrl: typeof item.previewUrl === 'string' ? item.previewUrl : undefined + previewUrl: typeof item.previewUrl === 'string' ? item.previewUrl : undefined, + attachmentUrl: typeof item.attachmentUrl === 'string' ? item.attachmentUrl : undefined }) } } diff --git a/web/src/components/AssistantChat/messages/MessageAttachments.tsx b/web/src/components/AssistantChat/messages/MessageAttachments.tsx index 2dd66a37..15b35901 100644 --- a/web/src/components/AssistantChat/messages/MessageAttachments.tsx +++ b/web/src/components/AssistantChat/messages/MessageAttachments.tsx @@ -1,3 +1,5 @@ +import { useCallback, useState } from 'react' +import type { ApiClient } from '@/api/client' import type { AttachmentMetadata } from '@/types/api' import { FileIcon } from '@/components/FileIcon' import { isImageMimeType } from '@/lib/fileAttachments' @@ -9,15 +11,56 @@ function formatFileSize(bytes: number): string { return `${(bytes / (1024 * 1024)).toFixed(1)} MB` } -function ImageAttachment(props: { attachment: AttachmentMetadata }) { +const MAX_CACHED_ORIGINALS = 50 +const originalUrlCache = new Map() + +function rememberOriginal(key: string, objectUrl: string): void { + originalUrlCache.delete(key) + originalUrlCache.set(key, objectUrl) + while (originalUrlCache.size > MAX_CACHED_ORIGINALS) { + const oldest = originalUrlCache.entries().next().value as [string, string] | undefined + if (!oldest) break + originalUrlCache.delete(oldest[0]) + URL.revokeObjectURL(oldest[1]) + } +} + +function ImageAttachment(props: { attachment: AttachmentMetadata; api?: ApiClient; sessionId?: string }) { const { attachment } = props + const [fullSrc, setFullSrc] = useState(undefined) + + // Viewer opens with the inline thumbnail and upgrades to the hub-served + // original once it loads; old messages without a hub copy keep the thumb. + const requestFullSize = useCallback(() => { + const { api, sessionId } = props + const attachmentUrl = attachment.attachmentUrl + if (fullSrc || !attachmentUrl || !api || !sessionId) return + const cached = originalUrlCache.get(attachmentUrl) + if (cached) { + setFullSrc(cached) + return + } + void (async () => { + try { + const blob = await api.getSessionAttachmentBlob(sessionId, attachment.id) + const objectUrl = URL.createObjectURL(blob) + rememberOriginal(attachmentUrl, objectUrl) + setFullSrc(objectUrl) + } catch { + // Original unavailable; the thumbnail stays as the best view. + } + })() + }, [attachment.attachmentUrl, attachment.id, fullSrc, props]) + return ( @@ -46,7 +89,7 @@ function FileAttachment(props: { attachment: AttachmentMetadata }) { ) } -export function MessageAttachments(props: { attachments: AttachmentMetadata[] }) { +export function MessageAttachments(props: { attachments: AttachmentMetadata[]; api?: ApiClient; sessionId?: string }) { const { attachments } = props if (!attachments || attachments.length === 0) return null @@ -61,7 +104,7 @@ export function MessageAttachments(props: { attachments: AttachmentMetadata[] }) data-hapi-image-count={images.length} > {images.map(attachment => ( - + ))} )} diff --git a/web/src/components/AssistantChat/messages/UserMessage.tsx b/web/src/components/AssistantChat/messages/UserMessage.tsx index a3bb45c0..f09ac7a4 100644 --- a/web/src/components/AssistantChat/messages/UserMessage.tsx +++ b/web/src/components/AssistantChat/messages/UserMessage.tsx @@ -105,7 +105,7 @@ export function HappyUserMessage() {
{hasText ? : null} - {hasAttachments ? : null} + {hasAttachments ? : null}
{showStatus && (
diff --git a/web/src/components/ImagePreview.tsx b/web/src/components/ImagePreview.tsx index 09693e40..1edfeb7d 100644 --- a/web/src/components/ImagePreview.tsx +++ b/web/src/components/ImagePreview.tsx @@ -31,6 +31,8 @@ function getPointCenter(a: ImagePoint, b: ImagePoint): ImagePoint { export function ImagePreview(props: { src: string + /** Optional higher-resolution source swapped in once loaded (viewer only). */ + fullSrc?: string fileName: string label: string buttonClassName?: string @@ -377,7 +379,7 @@ export function ImagePreview(props: { onDoubleClick={resetView} > {activePreview.label} ({ + createImageThumbnailDataUrl: vi.fn(async () => 'data:image/webp;base64,dGh1bWI=' as string | null) +})) + +vi.mock('./imageThumbnail', () => ({ + createImageThumbnailDataUrl: thumbnail.createImageThumbnailDataUrl +})) + async function collectAdditions( file: File, uploadFile = vi.fn(async () => ({ success: true, path: '/uploads/file' })) @@ -19,6 +27,7 @@ async function collectAdditions( describe('attachmentAdapter', () => { beforeEach(() => { vi.stubGlobal('indexedDB', undefined) + thumbnail.createImageThumbnailDataUrl.mockClear() vi.resetModules() }) @@ -42,6 +51,7 @@ describe('attachmentAdapter', () => { file, path: '/uploads/ready.png', previewUrl: 'data:image/png;base64,aW1hZ2U=', + attachmentUrl: '/api/sessions/session-1/attachments/attachment-ready', }]) const [restored] = await drafts.getDraftAttachments('session-1') expect(restored).toBeDefined() @@ -59,34 +69,19 @@ describe('attachmentAdapter', () => { id: 'attachment-ready', path: '/uploads/ready.png', previewUrl: 'data:image/png;base64,aW1hZ2U=', + attachmentUrl: '/api/sessions/session-1/attachments/attachment-ready', status: { type: 'requires-action', reason: 'composer-send' }, })]) }) - it('uploads an image when the initial preview read fails', async () => { - let readCount = 0 - class FileReaderMock { - result: string | ArrayBuffer | null = null - onload: FileReader['onload'] = null - onerror: FileReader['onerror'] = null - - readAsDataURL(): void { - readCount += 1 - if (readCount === 1) { - this.onerror?.call(this as unknown as FileReader, {} as ProgressEvent) - return - } - this.result = 'data:image/png;base64,dXBsb2Fk' - this.onload?.call(this as unknown as FileReader, {} as ProgressEvent) - } - } - vi.stubGlobal('FileReader', FileReaderMock) - + it('still uploads the original image when no thumbnail can be generated', async () => { + thumbnail.createImageThumbnailDataUrl.mockResolvedValueOnce(null) const file = new File(['proof'], 'proof.png', { type: 'image/png' }) const { emitted, uploadFile } = await collectAdditions(file) - expect(readCount).toBe(2) - expect(uploadFile).toHaveBeenCalledWith('session-1', 'proof.png', 'dXBsb2Fk', 'image/png') + // The upload always sends the original bytes; a missing preview only + // downgrades the bubble to a file card. + expect(uploadFile).toHaveBeenCalledWith('session-1', 'proof.png', 'cHJvb2Y=', 'image/png', expect.any(String)) expect(emitted.at(-1)).toMatchObject({ status: { type: 'requires-action', reason: 'composer-send' }, path: '/uploads/file' @@ -96,31 +91,37 @@ describe('attachmentAdapter', () => { }) describe('attachmentAdapter image previews', () => { - it('includes the preview URL in every image upload state', async () => { - const file = new File(['image'], 'photo.png', { type: 'image/png' }) - const readSpy = vi.spyOn(FileReader.prototype, 'readAsDataURL') - const { emitted } = await collectAdditions(file) + beforeEach(() => { + thumbnail.createImageThumbnailDataUrl.mockClear() + }) + it('includes the thumbnail preview URL in every image upload state', async () => { + const file = new File(['image'], 'photo.png', { type: 'image/png' }) + const { emitted, uploadFile } = await collectAdditions(file) + + expect(thumbnail.createImageThumbnailDataUrl).toHaveBeenCalledWith(file) expect(emitted).toHaveLength(3) expect(emitted[0]).toMatchObject({ - previewUrl: 'data:image/png;base64,aW1hZ2U=', + previewUrl: 'data:image/webp;base64,dGh1bWI=', status: { type: 'running', progress: 0 } }) expect(emitted[1]).toMatchObject({ - previewUrl: 'data:image/png;base64,aW1hZ2U=', + previewUrl: 'data:image/webp;base64,dGh1bWI=', status: { type: 'running', progress: 50 } }) expect(emitted[2]).toMatchObject({ - previewUrl: 'data:image/png;base64,aW1hZ2U=', + previewUrl: 'data:image/webp;base64,dGh1bWI=', status: { type: 'requires-action' } }) - expect(readSpy).toHaveBeenCalledTimes(1) + // The wire payload carries the original, never the thumbnail. + expect(uploadFile).toHaveBeenCalledWith('session-1', 'photo.png', 'aW1hZ2U=', 'image/png', expect.any(String)) }) it('does not generate previews for non-image attachments', async () => { const file = new File(['notes'], 'notes.txt', { type: 'text/plain' }) const { emitted } = await collectAdditions(file) + expect(thumbnail.createImageThumbnailDataUrl).not.toHaveBeenCalled() expect(emitted).toHaveLength(3) expect(emitted.every((attachment) => attachment.previewUrl === undefined)).toBe(true) }) diff --git a/web/src/lib/attachmentAdapter.ts b/web/src/lib/attachmentAdapter.ts index 01db33eb..53bcd015 100644 --- a/web/src/lib/attachmentAdapter.ts +++ b/web/src/lib/attachmentAdapter.ts @@ -3,16 +3,17 @@ import type { ApiClient } from '@/api/client' import type { AttachmentMetadata } from '@/types/api' import { isImageMimeType } from '@/lib/fileAttachments' import { randomId } from '@/lib/randomId' +import { createImageThumbnailDataUrl } from '@/lib/imageThumbnail' import { getRestoredUploadMetadata } from '@/lib/composer-attachment-drafts' import type { AttachmentDraftHandoff } from '@/lib/composer-draft-transfer' /** Composer / share upload ceiling — keep deep-link fetch in sync. */ export const MAX_UPLOAD_BYTES = 50 * 1024 * 1024 -const MAX_PREVIEW_BYTES = 5 * 1024 * 1024 type PendingUploadAttachment = PendingAttachment & { path?: string previewUrl?: string + attachmentUrl?: string uploadSessionId?: string } @@ -27,10 +28,10 @@ export function createAttachmentAdapter( ): AttachmentAdapter { const cancelledAttachmentIds = new Set() - const deleteUpload = async (path?: string, uploadSessionId = sessionId) => { + const deleteUpload = async (path?: string, uploadSessionId = sessionId, attachmentId?: string) => { if (!path) return try { - await api.deleteUploadFile(uploadSessionId, path) + await api.deleteUploadFile(uploadSessionId, path, attachmentId) } catch { // Best effort cleanup } @@ -60,6 +61,7 @@ export function createAttachmentAdapter( status: { type: 'requires-action', reason: 'composer-send' }, path: restored.path, previewUrl: restored.previewUrl, + attachmentUrl: restored.attachmentUrl, uploadSessionId: restored.uploadSessionId, } as PendingUploadAttachment return @@ -70,12 +72,10 @@ export function createAttachmentAdapter( try { let previewUrl: string | undefined - if (isImageMimeType(contentType) && file.size <= MAX_PREVIEW_BYTES) { - try { - previewUrl = await fileToDataUrl(file) - } catch { - // Preview generation is optional; retry the read for the upload payload below. - } + if (isImageMimeType(contentType)) { + // Small thumbnail only: the original travels to the hub as a + // separate cached attachment, never inside the message JSON. + previewUrl = await createImageThumbnailDataUrl(file) ?? undefined } yield { @@ -121,9 +121,8 @@ export function createAttachmentAdapter( return } - const content = previewUrl - ? base64FromDataUrl(previewUrl) - : await fileToBase64(file) + // Upload the original bytes; the wire preview stays a thumbnail. + const content = await fileToBase64(file) if (cancelledAttachmentIds.has(id)) { return @@ -139,10 +138,10 @@ export function createAttachmentAdapter( previewUrl } as PendingUploadAttachment - const result = await api.uploadFile(uploadSessionId, file.name, content, contentType) + const result = await api.uploadFile(uploadSessionId, file.name, content, contentType, id) if (cancelledAttachmentIds.has(id)) { if (result.success && result.path) { - await deleteUpload(result.path, uploadSessionId) + await deleteUpload(result.path, uploadSessionId, id) } return } @@ -168,6 +167,7 @@ export function createAttachmentAdapter( status: { type: 'requires-action', reason: 'composer-send' }, path: result.path, previewUrl, + attachmentUrl: result.attachmentUrl, uploadSessionId, } as PendingUploadAttachment @@ -187,7 +187,7 @@ export function createAttachmentAdapter( cancelledAttachmentIds.add(attachment.id) const path = (attachment as PendingUploadAttachment).path const uploadSessionId = (attachment as PendingUploadAttachment).uploadSessionId - await deleteUpload(path, uploadSessionId) + await deleteUpload(path, uploadSessionId, attachment.id) }, async send(attachment: PendingAttachment): Promise { @@ -201,7 +201,8 @@ export function createAttachmentAdapter( mimeType: attachment.contentType ?? 'application/octet-stream', size: attachment.file?.size ?? 0, path, - previewUrl: pending.previewUrl + previewUrl: pending.previewUrl, + ...(pending.attachmentUrl ? { attachmentUrl: pending.attachmentUrl } : {}) } : undefined return { diff --git a/web/src/lib/composer-attachment-drafts.ts b/web/src/lib/composer-attachment-drafts.ts index 2eea158d..5eb92ea3 100644 --- a/web/src/lib/composer-attachment-drafts.ts +++ b/web/src/lib/composer-attachment-drafts.ts @@ -11,6 +11,7 @@ type StoredAttachment = { blob: Blob path?: string previewUrl?: string + attachmentUrl?: string uploadSessionId?: string } @@ -29,6 +30,7 @@ export type AttachmentDraftInput = { file: File path?: string previewUrl?: string + attachmentUrl?: string uploadSessionId?: string } @@ -36,6 +38,7 @@ export type RestoredUploadMetadata = { id: string path?: string previewUrl?: string + attachmentUrl?: string uploadSessionId?: string } @@ -77,6 +80,7 @@ function toStoredFile(attachment: AttachmentDraftInput): StoredAttachment { blob: file, path: attachment.path, previewUrl: attachment.previewUrl, + attachmentUrl: attachment.attachmentUrl, uploadSessionId: attachment.uploadSessionId, } } @@ -92,6 +96,7 @@ function toFile(file: StoredAttachment): File { id: file.id, path: file.path, previewUrl: file.previewUrl, + attachmentUrl: file.attachmentUrl, uploadSessionId: file.uploadSessionId, }) return restored diff --git a/web/src/lib/composer-draft-transfer.ts b/web/src/lib/composer-draft-transfer.ts index 1e72741b..12fa10d2 100644 --- a/web/src/lib/composer-draft-transfer.ts +++ b/web/src/lib/composer-draft-transfer.ts @@ -122,6 +122,7 @@ function stripSessionScopedUploadFields(attachment: AttachmentDraftInput): Attac ...attachment, path: undefined, previewUrl: undefined, + attachmentUrl: undefined, uploadSessionId: undefined, } } @@ -151,6 +152,7 @@ async function loadPersistedAttachments( file, path: metadata?.path, previewUrl: metadata?.previewUrl, + attachmentUrl: metadata?.attachmentUrl, uploadSessionId: metadata?.uploadSessionId, } }) diff --git a/web/src/lib/imageThumbnail.ts b/web/src/lib/imageThumbnail.ts new file mode 100644 index 00000000..2fa71b44 --- /dev/null +++ b/web/src/lib/imageThumbnail.ts @@ -0,0 +1,43 @@ +const MAX_THUMBNAIL_EDGE = 768 +const WEBP_QUALITY = 0.8 +const JPEG_QUALITY = 0.85 + +/** + * Downscale an image file into a small data-URL thumbnail for the chat payload. + * + * Full-size previews used to be stored inline in the message JSON, which made + * every conversation load transfer megabytes of base64. The wire preview is now + * a compact thumbnail; the original is served separately by the hub. + * + * Returns null when the browser cannot decode the image (e.g. unsupported + * format or a non-DOM test environment); callers fall back to a file card. + */ +export async function createImageThumbnailDataUrl(file: File): Promise { + if (typeof createImageBitmap !== 'function' || typeof document === 'undefined') { + return null + } + let bitmap: ImageBitmap + try { + bitmap = await createImageBitmap(file, { imageOrientation: 'from-image' }) + } catch { + return null + } + try { + const scale = Math.min(1, MAX_THUMBNAIL_EDGE / Math.max(bitmap.width, bitmap.height)) + const width = Math.max(1, Math.round(bitmap.width * scale)) + const height = Math.max(1, Math.round(bitmap.height * scale)) + const canvas = document.createElement('canvas') + canvas.width = width + canvas.height = height + const context = canvas.getContext('2d') + if (!context) return null + context.drawImage(bitmap, 0, 0, width, height) + const webp = canvas.toDataURL('image/webp', WEBP_QUALITY) + if (webp.startsWith('data:image/webp')) return webp + return canvas.toDataURL('image/jpeg', JPEG_QUALITY) + } catch { + return null + } finally { + bitmap.close() + } +}