Open source Grok Bot alternative, Bring your own agent and subscription: message Claude Code, Codex, Gemini CLI, Cursor, Copilot and 40+ AI agents as bots on your own computer, from iPhone, Mac, Windows, Linux or terminal. Agent-agnostic and free. Also a Muse and Dots alternative. Built in Rust.
Rust acpagent-client-protocolai-agentsai-assistantclaudeclaude-codecodexcoding-agentscursorgeminigemini-cligrok-bot-alternativeiosiphonelinuxmacosmcpopen-sourcerustself-hosted
feat(host): let bots share downloadable files
Sean Ferguson9e7c74e0e271
diff --git a/apps/desktop/src/main/file-saves.ts b/apps/desktop/src/main/file-saves.tsnew file mode 100644index 00000000..4567a49f--- /dev/null+++ b/apps/desktop/src/main/file-saves.ts@@ -0,0 +1,48 @@+import { randomUUID } from 'node:crypto'+import { BrowserWindow, dialog, ipcMain } from 'electron'+import type { SharedFile } from '../shared/models'+import { saveName, validateSharedFile } from '../shared/files'+import { FileSink } from './file-sink'++export function registerFileSaves() {+ const saves = new Map<string, { owner: number; sink: FileSink; dispose: () => void }>()+ ipcMain.handle('files:begin', async (event, meta: SharedFile) => {+ validateSharedFile(meta)+ const window = BrowserWindow.fromWebContents(event.sender)+ if (!window) throw new Error('Window closed')+ const result = await dialog.showSaveDialog(window, { defaultPath: saveName(meta.name), buttonLabel: 'Save' })+ if (result.canceled || !result.filePath || event.sender.isDestroyed()) return null+ const id = randomUUID()+ const sink = await FileSink.create(result.filePath, meta, id)+ if (event.sender.isDestroyed()) { await sink.cancel(); return null }+ const destroyed = () => { saves.delete(id); void sink.cancel().catch(console.error) }+ saves.set(id, { owner: event.sender.id, sink, dispose: () => event.sender.removeListener('destroyed', destroyed) })+ event.sender.once('destroyed', destroyed)+ return id+ })+ function owned(owner: number, id: string) {+ const save = saves.get(id)+ if (!save || save.owner !== owner) throw new Error('Unknown download')+ return save.sink+ }+ function forget(id: string) { saves.get(id)?.dispose(); saves.delete(id) }+ ipcMain.handle('files:write', async (event, id: string, offset: number, bytes: Uint8Array) => {+ const sink = owned(event.sender.id, id)+ try { await sink.write(offset, bytes) } catch (error) {+ forget(id)+ await sink.cancel()+ throw error+ }+ })+ ipcMain.handle('files:finish', async (event, id: string) => {+ const sink = owned(event.sender.id, id)+ try { await sink.finish() } finally { forget(id); await sink.cancel() }+ })+ ipcMain.handle('files:cancel', async (event, id: string) => {+ const save = saves.get(id)+ if (!save) return+ const sink = owned(event.sender.id, id)+ forget(id)+ await sink.cancel()+ })+}diff --git a/apps/desktop/src/main/file-sink.ts b/apps/desktop/src/main/file-sink.tsnew file mode 100644index 00000000..62fd0aae--- /dev/null+++ b/apps/desktop/src/main/file-sink.ts@@ -0,0 +1,61 @@+import { createHash } from 'node:crypto'+import { open, rename, rm, type FileHandle } from 'node:fs/promises'+import type { SharedFile } from '../shared/models'+import { FILE_CHUNK_SIZE, validateSharedFile } from '../shared/files.ts'++/** Only verified complete bytes replace the destination; every failure removes the partial. */+export class FileSink {+ private hash = createHash('sha256')+ private offset = 0+ private closed = false+ private busy = false+ private file: FileHandle+ private partial: string+ private destination: string+ private meta: SharedFile+ private constructor(file: FileHandle, partial: string, destination: string, meta: SharedFile) {+ this.file = file; this.partial = partial; this.destination = destination; this.meta = meta+ }++ static async create(destination: string, meta: SharedFile, id: string) {+ validateSharedFile(meta)+ const partial = `${destination}.${id}.codync-partial`+ const file = await open(partial, 'wx', 0o600)+ return new FileSink(file, partial, destination, meta)+ }++ async write(offset: number, bytes: Uint8Array) {+ if (this.closed || this.busy || offset !== this.offset || bytes.length !== Math.min(FILE_CHUNK_SIZE, this.meta.size - offset)) throw new Error('Invalid file chunk')+ this.busy = true+ try {+ let written = 0+ while (written < bytes.length) {+ const result = await this.file.write(bytes, written, bytes.length - written, this.offset + written)+ if (!result.bytesWritten) throw new Error('Could not write file')+ written += result.bytesWritten+ }+ if (this.closed) throw new Error('Download cancelled')+ this.hash.update(bytes)+ this.offset += bytes.length+ } finally { this.busy = false }+ }++ async finish() {+ if (this.closed || this.busy) throw new Error('Download cancelled or still writing')+ if (this.offset !== this.meta.size || this.hash.digest('hex') !== this.meta.sha256) throw new Error('File integrity check failed; retry the download')+ await this.file.sync()+ if (this.closed) throw new Error('Download cancelled')+ await this.file.close()+ if (this.closed) throw new Error('Download cancelled')+ // No asynchronous work between the last cancellation check and starting the rename.+ await rename(this.partial, this.destination)+ this.closed = true+ }++ async cancel() {+ if (this.closed) return+ this.closed = true+ await this.file.close()+ await rm(this.partial, { force: true })+ }+}diff --git a/apps/desktop/src/main/index.ts b/apps/desktop/src/main/index.tsindex 307fcb38..eaefae23 100644--- a/apps/desktop/src/main/index.ts+++ b/apps/desktop/src/main/index.ts@@ -4,6 +4,7 @@ import { join } from 'node:path'import { app, BrowserWindow, clipboard, dialog, ipcMain, Menu, nativeTheme, session, shell } from 'electron'import type { HostSnapshot, WindowCommand } from '../shared/ipc'import { devPort, fetchHealth, HostController } from './host-controller'+import { registerFileSaves } from './file-saves'import { registerHostProxy } from './host-proxy'import { readClipboardFiles, readFiles } from './files'import { Tray } from './tray'@@ -138,6 +139,7 @@ function menu() {function registerIPC(tray: Tray) {registerHostProxy()+ registerFileSaves()ipcMain.on('app:version', (e) => (e.returnValue = app.getVersion()))ipcMain.on('app:computerName', (e) => (e.returnValue = computerName()))ipcMain.on('app:debugOpen', (e) => (e.returnValue = app.isPackaged ? null : (process.env.CODYNC_DEBUG_OPEN ?? null)))diff --git a/apps/desktop/src/preload/index.ts b/apps/desktop/src/preload/index.tsindex c6fc20c1..3fc32278 100644--- a/apps/desktop/src/preload/index.ts+++ b/apps/desktop/src/preload/index.ts@@ -73,6 +73,12 @@ const bridge: CodyncBridge = {setAutoCheck: (on) => ipcRenderer.send('updates:autoCheck', on),setAutoDownload: (on) => ipcRenderer.send('updates:autoDownload', on),},+ files: {+ begin: (file) => ipcRenderer.invoke('files:begin', file),+ write: (id, offset, data) => ipcRenderer.invoke('files:write', id, offset, data),+ finish: (id) => ipcRenderer.invoke('files:finish', id),+ cancel: (id) => ipcRenderer.invoke('files:cancel', id),+ },app: {openExternal: (url) => ipcRenderer.send('app:openExternal', url),copy: (text) => ipcRenderer.send('app:copy', text),diff --git a/apps/desktop/src/renderer/client/host-client.ts b/apps/desktop/src/renderer/client/host-client.tsindex 012212bf..08e54fc3 100644--- a/apps/desktop/src/renderer/client/host-client.ts+++ b/apps/desktop/src/renderer/client/host-client.ts@@ -120,6 +120,10 @@ export function parseEvent(line: string): HostEvent | null {/** Typed host calls (host/src/api/); anything else goes through `call`. */export class HostClient {+ readFile(entryId: string, fileId: string, offset: number): Promise<{ data: string; size: number }> {+ return this.call('readFile', { entryId, fileId, offset })+ }+constructor(readonly transport: HostTransport) {}call<T>(method: string, body: unknown = {}, timeoutMs = 20_000): Promise<T> {diff --git a/apps/desktop/src/renderer/components/icon-fallbacks.ts b/apps/desktop/src/renderer/components/icon-fallbacks.tsindex 18cbeb08..ab317090 100644--- a/apps/desktop/src/renderer/components/icon-fallbacks.ts+++ b/apps/desktop/src/renderer/components/icon-fallbacks.ts@@ -7,6 +7,7 @@ const map: Record<string, IconNode> = {'arrow.clockwise': L.RotateCw,'arrow.counterclockwise': L.RotateCcw,'arrow.down': L.ArrowDown,+ 'arrow.down.to.line': L.Download,'arrow.down.circle': L.CircleArrowDown,'arrow.down.right.and.arrow.up.left': L.Minimize2,'arrow.left': L.ArrowLeft,diff --git a/apps/desktop/src/renderer/components/symbols.json b/apps/desktop/src/renderer/components/symbols.jsonindex 2d7bbf65..ddc9070b 100644--- a/apps/desktop/src/renderer/components/symbols.json+++ b/apps/desktop/src/renderer/components/symbols.json@@ -3,6 +3,7 @@"arrow.clockwise","arrow.counterclockwise","arrow.down",+"arrow.down.to.line","arrow.down.circle","arrow.down.doc.on.clipboard","arrow.down.right.and.arrow.up.left",diff --git a/apps/desktop/src/renderer/demo/bridge.ts b/apps/desktop/src/renderer/demo/bridge.tsindex fbba80bc..2ea1201b 100644--- a/apps/desktop/src/renderer/demo/bridge.ts+++ b/apps/desktop/src/renderer/demo/bridge.ts@@ -69,6 +69,7 @@ const bridge: CodyncBridge = {},cloud: { request: async () => ({ ok: false, error: { status: 503, code: 'demo', message: DEMO_UNAVAILABLE } }) },updates: { state: async () => updates, onChange: none, check() {}, setAutoCheck() {}, setAutoDownload() {} },+ files: { begin: unavailable, write: async () => {}, finish: async () => {}, cancel: async () => {} },app: {openExternal: (url) => void window.open(url, '_blank', 'noopener'),copy: (text) => void navigator.clipboard?.writeText(text).catch(() => {}),diff --git a/apps/desktop/src/renderer/demo/story.ts b/apps/desktop/src/renderer/demo/story.tsindex 5d85bec1..2e76fe5a 100644--- a/apps/desktop/src/renderer/demo/story.ts+++ b/apps/desktop/src/renderer/demo/story.ts@@ -71,6 +71,9 @@ export const entries: SeedEntry[] = [{ id: 's5', botId: 'scout', kind: 'tool', at: 56, data: { title: 'npm test', toolKind: 'execute', command: 'npm test', status: 'completed', output: '✓ isoWeek: mid year\n✓ isoWeek: first week\n✓ weeklyTotals: sums one week\n✓ weeklyTotals: week that crosses into 2027\n\n4 passing (12ms)', author: 'scout' } },reply('s6', 'scout', 'scout', 55, 'I added `weeklyTotals(runs)` to `src/pace.js`. It takes runs shaped like `{ date, distance, time }`, groups them by ISO week in UTC (keys like `"2026-W53"`) and sums distance and time. The new test covers the week that crosses into 2027. All 4 tests pass and nothing is committed yet.'),+ { id: 'generated-file', botId: 'scout', kind: 'agent', at: 0, data: { text: 'report.pdf (1250000 bytes)', final: true, files: [{ id: 'demo-report', name: 'report.pdf', size: 1250000, sha256: '0'.repeat(64) }] } },+ { id: 'generated-binary', botId: 'scout', kind: 'agent', at: 0, data: { text: 'binary-output.dat (2000000 bytes)', final: true, files: [{ id: 'demo-binary', name: 'binary-output.dat', size: 2000000, sha256: '0'.repeat(64) }] } },+// Reviewer looks it over.user('r1', 'reviewer', 50, 'Review weeklyTotals before we ship it.'),tool('r2', 'reviewer', 49, 'Read src/pace.js', 'read'),diff --git a/apps/desktop/src/renderer/store/bot-store.ts b/apps/desktop/src/renderer/store/bot-store.tsindex 75aeb414..a5da0746 100644--- a/apps/desktop/src/renderer/store/bot-store.ts+++ b/apps/desktop/src/renderer/store/bot-store.ts@@ -11,6 +11,7 @@ import {type ScreenState,type Usage,} from '@shared/models'+import { FileDownloads } from './file-downloads'import { BotSync, sleep } from './bot-sync'export { builtInBackendName, type Connection } from './bot-mirror'@@ -32,6 +33,10 @@ export const QUICK_REACTIONS = ['👍', '❤️', '😂', '🎉', '👀', '✅']* `rev`, then live). Port of kit's `BotStore`.*/export class BotStore extends BotSync {+ readonly fileDownloads = new FileDownloads(() => this.changed())++ override retire() { this.fileDownloads.retire(); super.retire() }+private outgoingFiles = new Map<string, OutgoingFile[]>()send(text: string, botId: string, thread: string | null = null, files: OutgoingFile[] = [], nonce: string = crypto.randomUUID()) {diff --git a/apps/desktop/src/renderer/store/file-downloads.ts b/apps/desktop/src/renderer/store/file-downloads.tsnew file mode 100644index 00000000..b79af302--- /dev/null+++ b/apps/desktop/src/renderer/store/file-downloads.ts@@ -0,0 +1,66 @@+import type { SharedFile } from '@shared/models'+import { decodeFileChunk, validateSharedFile } from '../../shared/files.ts'+import type { HostClient } from '../client/host-client'++export type DownloadState = { kind: 'downloading'; received: number } | { kind: 'saved' } | { kind: 'failed'; message: string }+interface Job { cancelled: boolean; handle: string | null }++/** Scoped to one computer store; retiring it cannot save a file into another account. */+export class FileDownloads {+ readonly states = new Map<string, DownloadState>()+ private jobs = new Map<string, Job>()+ private retired = false+ private changed: () => void+ constructor(changed: () => void) { this.changed = changed }++ cancel(id: string) {+ const job = this.jobs.get(id)+ if (!job) return+ job.cancelled = true+ this.jobs.delete(id)+ this.states.delete(id)+ if (job.handle) void window.codync.files.cancel(job.handle).catch(console.error)+ this.changed()+ }++ retire() { this.retired = true; for (const id of this.jobs.keys()) this.cancel(id) }++ async save(client: HostClient | null, entryId: string, file: SharedFile) {+ if (this.retired || this.jobs.has(file.id)) return+ const job: Job = { cancelled: false, handle: null }+ const alive = () => !job.cancelled && !this.retired+ this.jobs.set(file.id, job)+ this.states.set(file.id, { kind: 'downloading', received: 0 })+ this.changed()+ try {+ validateSharedFile(file)+ if (!client) throw new Error('Connect to this computer to download the file')+ job.handle = await window.codync.files.begin(file)+ if (!job.handle || !alive()) return+ let offset = 0+ // The empty file still performs an authenticated read and verifies its digest.+ do {+ const chunk = await client.readFile(entryId, file.id, offset)+ if (!alive()) return+ const bytes = decodeFileChunk(chunk, file.size, offset)+ if (bytes.length) await window.codync.files.write(job.handle, offset, bytes)+ if (!alive()) return+ offset += bytes.length+ this.states.set(file.id, { kind: 'downloading', received: offset })+ this.changed()+ } while (offset < file.size)+ if (!alive()) return+ await window.codync.files.finish(job.handle)+ if (alive()) this.states.set(file.id, { kind: 'saved' })+ } catch (error) {+ if (alive()) this.states.set(file.id, { kind: 'failed', message: error instanceof Error ? error.message : String(error) })+ } finally {+ if (job.handle) await window.codync.files.cancel(job.handle).catch(console.error)+ if (this.jobs.get(file.id) === job) {+ this.jobs.delete(file.id)+ if (this.states.get(file.id)?.kind === 'downloading') this.states.delete(file.id)+ this.changed()+ }+ }+ }+}diff --git a/apps/desktop/src/renderer/views/thread/ChatRows.tsx b/apps/desktop/src/renderer/views/thread/ChatRows.tsxindex d03bd146..ddc64917 100644--- a/apps/desktop/src/renderer/views/thread/ChatRows.tsx+++ b/apps/desktop/src/renderer/views/thread/ChatRows.tsx@@ -1,3 +1,4 @@+import { FileDownloadCard } from './FileDownloadCard'import { memo, useEffect, useRef, useState } from 'react'import { isGroup, isWorking, needsInput, type Bot, type Entry, type ThreadSummary } from '@shared/models'import { BotAvatar } from '../../components/Avatar'@@ -203,7 +204,7 @@ export function AgentBubble({ entry, openTrace, reply }: { entry: Entry; openTra<div className="message agent" title={fullDate.format(entry.createdAt)} onMouseEnter={() => setHovering(true)} onMouseLeave={() => setHovering(false)}><div className="message-body"><Bubble- className="bubble agent"+ className={entry.data.files?.length ? "file-message" : "bubble agent"}reactions={reactionPick(store, entry)}items={() => [{ title: 'Copy', icon: 'square.on.square', action: copy },@@ -211,7 +212,7 @@ export function AgentBubble({ entry, openTrace, reply }: { entry: Entry; openTra{ title: 'Show what it did', icon: 'list.bullet', action: openTrace },]}>- <MarkdownText text={entry.data.text ?? ''} />+ {entry.data.files?.length ? <div style={{ display: 'grid', gap: 6 }}>{entry.data.files.map((file) => <FileDownloadCard key={file.id} entry={entry} file={file} />)}</div> : <MarkdownText text={entry.data.text ?? ''} />}</Bubble><MessageActions className="trailing" visible={hovering} reactions={reactionPick(store, entry)} reply={reply} trace={openTrace} copy={copy} /></div>diff --git a/apps/desktop/src/renderer/views/thread/FileDownloadCard.tsx b/apps/desktop/src/renderer/views/thread/FileDownloadCard.tsxnew file mode 100644index 00000000..c5ca4791--- /dev/null+++ b/apps/desktop/src/renderer/views/thread/FileDownloadCard.tsx@@ -0,0 +1,23 @@+import type { Entry, SharedFile } from '@shared/models'+import { useStore } from '../../store/context'+import { Icon } from '../../components/Icon'+import { font } from '../../lib/fonts'+import { attachmentSymbol, byteCount } from './Attachments'++export function FileDownloadCard({ entry, file }: { entry: Entry; file: SharedFile }) {+ const store = useStore()+ const state = store.fileDownloads.states.get(file.id)+ const busy = state?.kind === 'downloading'+ const action = busy ? 'Cancel download' : state?.kind === 'failed' ? 'Retry download' : state?.kind === 'saved' ? 'Save again' : 'Download'+ const detail = busy ? `${byteCount(state.received)} of ${byteCount(file.size)}` : state?.kind === 'failed' ? state.message : state?.kind === 'saved' ? `${byteCount(file.size)} · Saved` : byteCount(file.size)+ return <div style={{ display: 'flex', alignItems: 'center', gap: 12, padding: 14, background: 'var(--bubble-agent)', borderRadius: 16, maxWidth: 380 }}>+ <Icon name={attachmentSymbol(file.name)} size={24} color="var(--secondary)" />+ <div style={{ minWidth: 0, flex: 1 }}>+ <div style={{ ...font('subheadline', 'semibold'), whiteSpace: 'nowrap', overflow: 'hidden', textOverflow: 'ellipsis' }} title={file.name}>{file.name}</div>+ <div role={state?.kind === 'failed' ? 'alert' : 'status'} style={{ ...font('caption2'), color: state?.kind === 'failed' ? 'var(--danger)' : 'var(--secondary)', overflowWrap: 'anywhere' }}>{detail}</div>+ </div>+ <button aria-label={`${action}: ${file.name}`} title={action} onClick={() => busy ? store.fileDownloads.cancel(file.id) : void store.fileDownloads.save(store.client, entry.id, file)} style={{ display: 'flex', padding: 8 }}>+ <Icon name={busy ? 'xmark' : 'arrow.down.to.line'} size={20} />+ </button>+ </div>+}diff --git a/apps/desktop/src/shared/files.test.ts b/apps/desktop/src/shared/files.test.tsnew file mode 100644index 00000000..747338dc--- /dev/null+++ b/apps/desktop/src/shared/files.test.ts@@ -0,0 +1,93 @@+import assert from 'node:assert/strict'+import { test } from 'node:test'+import { createHash, randomUUID } from 'node:crypto'+import { mkdtemp, readFile, readdir, rm, writeFile } from 'node:fs/promises'+import { tmpdir } from 'node:os'+import { join } from 'node:path'+import { FileSink } from '../main/file-sink.ts'+import { decodeFileChunk, FILE_CHUNK_SIZE, saveName } from './files.ts'++test('verified downloads preserve binary and empty files and replace only on success', async () => {+ const directory = await mkdtemp(join(tmpdir(), 'codync-download-'))+ try {+ for (const data of [Buffer.alloc(0), Buffer.alloc(FILE_CHUNK_SIZE + 11, 255)]) {+ const destination = join(directory, 'output')+ await writeFile(destination, 'original')+ const sink = await FileSink.create(destination, { id: 'id', name: 'file', size: data.length, sha256: createHash('sha256').update(data).digest('hex') }, randomUUID())+ for (let offset = 0; offset < data.length; offset += FILE_CHUNK_SIZE) await sink.write(offset, data.subarray(offset, offset + FILE_CHUNK_SIZE))+ const original = await readFile(destination, 'utf8')+ assert.equal(original, 'original')+ await sink.finish()+ const saved = await readFile(destination)+ assert.deepEqual(saved, data)+ const remaining = await readdir(directory)+ assert.deepEqual(remaining, ['output'])+ }+ } finally { await rm(directory, { recursive: true, force: true }) }+})++test('cancelled and corrupt downloads preserve existing destinations and remove partial files', async () => {+ const directory = await mkdtemp(join(tmpdir(), 'codync-download-'))+ try {+ const destination = join(directory, 'output')+ await writeFile(destination, 'original')+ for (const corrupt of [false, true]) {+ const sink = await FileSink.create(destination, { id: 'id', name: '.hidden', size: 1, sha256: '0'.repeat(64) }, randomUUID())+ await sink.write(0, new Uint8Array([42]))+ if (corrupt) await assert.rejects(sink.finish(), /integrity/)+ await sink.cancel()+ const original = await readFile(destination, 'utf8')+ assert.equal(original, 'original')+ const remaining = await readdir(directory)+ assert.deepEqual(remaining, ['output'])+ }+ } finally { await rm(directory, { recursive: true, force: true }) }+})++test('rejects changed, truncated and oversized chunks and provides portable save suggestions', () => {+ assert.throws(() => decodeFileChunk({ data: '', size: 1 }, 1, 0), /truncated/)+ assert.throws(() => decodeFileChunk({ data: 'AA==', size: 2 }, 1, 0), /Invalid/)+ assert.throws(() => decodeFileChunk({ data: 'A'.repeat(FILE_CHUNK_SIZE * 2), size: 1 }, 1, 0), /Invalid/)+ assert.equal(saveName('CON.txt'), 'file-CON.txt')+ assert.equal(saveName('file:report?.pdf'), 'file_report_.pdf')+ assert.equal(saveName('.hidden'), '.hidden')+})++test('retiring a computer while Save is pending cancels its handle without fetching bytes', async () => {+ const { FileDownloads } = await import('../renderer/store/file-downloads.ts')+ let resolve!: (value: string) => void+ const pending = new Promise<string>((done) => { resolve = done })+ const cancelled: string[] = []+ Object.defineProperty(globalThis, 'window', { configurable: true, value: { codync: { files: {+ begin: () => pending, cancel: async (id: string) => { cancelled.push(id) },+ } } } })+ const downloads = new FileDownloads(() => {})+ let calls = 0+ const client = { readFile: async () => { calls++; return { data: '', size: 0 } } }+ const task = downloads.save(client as never, 'entry', { id: 'id', name: 'empty', size: 0, sha256: createHash('sha256').digest('hex') })+ downloads.retire()+ resolve('handle')+ await task+ assert.equal(calls, 0)+ assert.deepEqual(cancelled, ['handle'])+ assert.equal(downloads.states.has('id'), false)+})++test('cancelling an outstanding chunk cannot write or commit a late response', async () => {+ const { FileDownloads } = await import('../renderer/store/file-downloads.ts')+ let resolve!: (value: { data: string; size: number }) => void+ const pending = new Promise<{ data: string; size: number }>((done) => { resolve = done })+ let writes = 0, commits = 0+ Object.defineProperty(globalThis, 'window', { configurable: true, value: { codync: { files: {+ begin: async () => 'handle', cancel: async () => {}, write: async () => { writes++ }, finish: async () => { commits++ },+ } } } })+ const downloads = new FileDownloads(() => {})+ const task = downloads.save({ readFile: () => pending } as never, 'entry', { id: 'id', name: 'empty', size: 0, sha256: createHash('sha256').digest('hex') })+ await new Promise((done) => setImmediate(done))+ downloads.cancel('id')+ resolve({ data: '', size: 0 })+ await task+ assert.equal(writes, 0)+ assert.equal(commits, 0)+ assert.equal(downloads.states.has('id'), false)+})diff --git a/apps/desktop/src/shared/files.ts b/apps/desktop/src/shared/files.tsnew file mode 100644index 00000000..781ab53f--- /dev/null+++ b/apps/desktop/src/shared/files.ts@@ -0,0 +1,22 @@+import type { SharedFile } from './models'++export const FILE_CHUNK_SIZE = 384 * 1024+export const FILE_LIMIT = 100 * 1024 * 1024++export function validateSharedFile(file: SharedFile) {+ if (!Number.isSafeInteger(file.size) || file.size < 0 || file.size > FILE_LIMIT || !/^[a-f0-9]{64}$/.test(file.sha256)) throw new Error('Invalid file metadata')+ if (!file.name || file.name.length > 200 || /[/\\\x00-\x1f\x7f]/.test(file.name) || file.name === '.' || file.name === '..') throw new Error('Invalid filename')+}++/** A display filename is a suggestion to the native dialog, never a storage path. */+export function saveName(name: string) {+ const portable = name.replace(/[<>:"|?*]/g, '_').replace(/[. ]+$/, '')+ return portable && !/^(con|prn|aux|nul|com[1-9]|lpt[1-9])(\.|$)/i.test(portable) ? portable : `file-${portable || 'download'}`+}++export function decodeFileChunk(chunk: { data: string; size: number }, size: number, offset: number): Uint8Array {+ if (chunk.size !== size || typeof chunk.data !== 'string' || chunk.data.length > Math.ceil(FILE_CHUNK_SIZE / 3) * 4) throw new Error('Invalid download response')+ const bytes = Uint8Array.from(atob(chunk.data), (v) => v.charCodeAt(0))+ if (bytes.length !== Math.min(FILE_CHUNK_SIZE, size - offset)) throw new Error('Download was truncated or changed')+ return bytes+}diff --git a/apps/desktop/src/shared/ipc.ts b/apps/desktop/src/shared/ipc.tsindex 68daea65..f6fb125c 100644--- a/apps/desktop/src/shared/ipc.ts+++ b/apps/desktop/src/shared/ipc.ts@@ -1,3 +1,4 @@+import type { SharedFile } from './models'import type { SSHBridge } from './ssh'// The bridge between the main process (host lifecycle, loopback HTTP, tray, windows)@@ -150,6 +151,12 @@ export interface CodyncBridge {setAutoCheck(on: boolean): voidsetAutoDownload(on: boolean): void}+ files: {+ begin(file: SharedFile): Promise<string | null>+ write(id: string, offset: number, data: Uint8Array): Promise<void>+ finish(id: string): Promise<void>+ cancel(id: string): Promise<void>+ }app: {openExternal(url: string): voidcopy(text: string): voiddiff --git a/apps/desktop/src/shared/models.ts b/apps/desktop/src/shared/models.tsindex 63f1c31e..bfc93965 100644--- a/apps/desktop/src/shared/models.ts+++ b/apps/desktop/src/shared/models.ts@@ -122,6 +122,8 @@ export interface Attachment {size: number}+export interface SharedFile extends Attachment { sha256: string }+export const isImageName = (name: string) =>['png', 'jpg', 'jpeg', 'heic', 'gif', 'webp', 'tiff', 'bmp'].includes(name.split('.').pop()?.toLowerCase() ?? '')@@ -155,6 +157,7 @@ export interface EntryData {thread?: ThreadSummaryreactions?: string[]attachments?: Attachment[]+ files?: SharedFile[]callSeconds?: number}diff --git a/apps/ios/Kit/Sources/CodyncKit/Client/FileDownload.swift b/apps/ios/Kit/Sources/CodyncKit/Client/FileDownload.swiftnew file mode 100644index 00000000..dde1f0f4--- /dev/null+++ b/apps/ios/Kit/Sources/CodyncKit/Client/FileDownload.swift@@ -0,0 +1,75 @@+import CryptoKit+import Foundation++public enum FileDownloadError: LocalizedError {+ case invalidMetadata, invalidChunk, integrity+ public var errorDescription: String? {+ switch self {+ case .invalidMetadata: "Invalid file metadata."+ case .invalidChunk: "The download was truncated or changed. Retry the download."+ case .integrity: "The file integrity check failed. Retry the download."+ }+ }+}++public extension HostClient {+ func readFile(entryId: String, fileId: String, offset: Int64) async throws -> FileChunk {+ struct Body: Encodable { let entryId: String; let fileId: String; let offset: Int64 }+ return try await call("readFile", Body(entryId: entryId, fileId: fileId, offset: offset))+ }+}++public struct FileChunk: Decodable, Sendable {+ public let data: String+ public let size: Int64+}++/// Filesystem work and hashing stay off the main actor, with one chunk in memory.+public actor FileDownload {+ public init() {}+ public static let chunkSize = 384 * 1024++ public func save(client: HostClient, entryId: String, file: SharedFile,+ directory: URL, progress: @Sendable (Int64) async -> Void) async throws -> URL {+ try file.validate()+ try Task.checkCancellation()+ let folder = directory.appendingPathComponent(UUID().uuidString, isDirectory: true)+ try FileManager.default.createDirectory(at: folder, withIntermediateDirectories: true)+ var successful = false+ defer { if !successful { try? FileManager.default.removeItem(at: folder) } }+ let partial = folder.appendingPathComponent(".download-partial")+ guard FileManager.default.createFile(atPath: partial.path, contents: nil) else { throw CocoaError(.fileWriteUnknown) }+ let handle = try FileHandle(forWritingTo: partial)+ defer { try? handle.close() }+ var offset: Int64 = 0+ var hash = SHA256()+ repeat {+ try Task.checkCancellation()+ let chunk = try await client.readFile(entryId: entryId, fileId: file.id, offset: offset)+ try Task.checkCancellation()+ guard chunk.size == file.size, chunk.data.utf8.count <= Self.chunkSize / 3 * 4,+ let bytes = Data(base64Encoded: chunk.data),+ bytes.count == min(Self.chunkSize, Int(file.size - offset)) else { throw FileDownloadError.invalidChunk }+ try handle.write(contentsOf: bytes)+ hash.update(data: bytes)+ offset += Int64(bytes.count)+ await progress(offset)+ } while offset < file.size+ let digest = hash.finalize().map { String(format: "%02x", $0) }.joined()+ guard offset == file.size, digest == file.sha256 else { throw FileDownloadError.integrity }+ try Task.checkCancellation()+ try handle.synchronize()+ try handle.close()+ // Keep a source named .download-partial valid too: the export lives in its own directory.+ let ready = folder.appendingPathComponent("ready", isDirectory: true)+ try FileManager.default.createDirectory(at: ready, withIntermediateDirectories: true)+ let destination = ready.appendingPathComponent(file.name)+ try FileManager.default.moveItem(at: partial, to: destination)+ successful = true+ return destination+ }++ public func remove(_ url: URL) throws {+ try FileManager.default.removeItem(at: url.deletingLastPathComponent().deletingLastPathComponent())+ }+}diff --git a/apps/ios/Kit/Sources/CodyncKit/Models/EntryData.swift b/apps/ios/Kit/Sources/CodyncKit/Models/EntryData.swiftindex 3eb23c28..1b3c2baa 100644--- a/apps/ios/Kit/Sources/CodyncKit/Models/EntryData.swift+++ b/apps/ios/Kit/Sources/CodyncKit/Models/EntryData.swift@@ -30,6 +30,8 @@ public struct EntryData: Codable, Hashable, Sendable {public var reactions: [String]?/// Files sent with a user message.public var attachments: [Attachment]?+ /// Immutable files explicitly sent by the bot.+ public var files: [SharedFile]?/// notice: a finished voice call's length.public var callSeconds: Int?diff --git a/apps/ios/Kit/Sources/CodyncKit/Models/SharedFile.swift b/apps/ios/Kit/Sources/CodyncKit/Models/SharedFile.swiftnew file mode 100644index 00000000..16a49ced--- /dev/null+++ b/apps/ios/Kit/Sources/CodyncKit/Models/SharedFile.swift@@ -0,0 +1,26 @@+import Foundation++/// An immutable host snapshot published by a bot. Separate from user uploads.+public struct SharedFile: Codable, Hashable, Sendable, Identifiable {+ public let id: String+ public let name: String+ public let size: Int64+ public let sha256: String++ public init(id: String, name: String, size: Int64, sha256: String) {+ self.id = id+ self.name = name+ self.size = size+ self.sha256 = sha256+ }++ public func validate() throws {+ guard size >= 0, size <= 100 * 1024 * 1024,+ sha256.count == 64, sha256.allSatisfy({ "0123456789abcdef".contains($0) }),+ !name.isEmpty, name.utf8.count <= 200, name != ".", name != "..",+ !name.contains("/"), !name.contains("\\"),+ !name.unicodeScalars.contains(where: { CharacterSet.controlCharacters.contains($0) }) else {+ throw FileDownloadError.invalidMetadata+ }+ }+}diff --git a/apps/ios/Kit/Sources/CodyncUI/Store/BotStore+Connection.swift b/apps/ios/Kit/Sources/CodyncUI/Store/BotStore+Connection.swiftindex 071e881f..0546cef6 100644--- a/apps/ios/Kit/Sources/CodyncUI/Store/BotStore+Connection.swift+++ b/apps/ios/Kit/Sources/CodyncUI/Store/BotStore+Connection.swift@@ -9,6 +9,7 @@ extension BotStore {voiceCalls.removeAll()setActive(false)retired = true+ fileDownloads.retire()for call in calls { call.end() }saveTask?.cancel()dropTimer?.cancel()diff --git a/apps/ios/Kit/Sources/CodyncUI/Store/BotStore.swift b/apps/ios/Kit/Sources/CodyncUI/Store/BotStore.swiftindex f9139633..ec5e430a 100644--- a/apps/ios/Kit/Sources/CodyncUI/Store/BotStore.swift+++ b/apps/ios/Kit/Sources/CodyncUI/Store/BotStore.swift@@ -63,6 +63,7 @@ public final class BotStore {public internal(set) var historyComplete: Set<String> = []var composerDrafts: [String: String] = [:]public var routineDrafts: [String: String] = [:]+ public let fileDownloads = FileDownloads()public var lastError: String?/// The open conversation (iOS navigation path / Mac sidebar selection).public var selection: String?diff --git a/apps/ios/Kit/Sources/CodyncUI/Store/FileDownloads.swift b/apps/ios/Kit/Sources/CodyncUI/Store/FileDownloads.swiftnew file mode 100644index 00000000..1b88bace--- /dev/null+++ b/apps/ios/Kit/Sources/CodyncUI/Store/FileDownloads.swift@@ -0,0 +1,74 @@+import CodyncKit+import Foundation+import Observation++@MainActor @Observable+public final class FileDownloads {+ public enum State {+ case downloading(Int64), saved, failed(String)+ }+ public struct Export: Identifiable {+ public let id: String+ public let url: URL+ public let botId: String+ public let threadId: String?+ }+ public private(set) var states: [String: State] = [:]+ public var export: Export?+ @ObservationIgnored private var exported: Export?+ @ObservationIgnored private var tasks: [String: Task<Void, Never>] = [:]+ @ObservationIgnored private let writer = FileDownload()+ @ObservationIgnored private var retired = false++ public init() {}++ public func save(client: HostClient?, entry: Entry, file: SharedFile) {+ guard !retired else { return }+ guard tasks.isEmpty, export == nil else {+ if tasks[file.id] == nil { states[file.id] = .failed("Finish the current download or export first.") }+ return+ }+ guard let client else { states[file.id] = .failed("Connect to this computer to download the file."); return }+ states[file.id] = .downloading(0)+ let directory = FileManager.default.temporaryDirectory.appendingPathComponent("CodyncDownloads", isDirectory: true)+ tasks[file.id] = Task {+ do {+ let url = try await writer.save(client: client, entryId: entry.id, file: file, directory: directory) { [weak self] received in+ await self?.update(file.id, received: received)+ }+ guard !Task.isCancelled, !retired else { try await writer.remove(url); return }+ states[file.id] = .saved+ let item = Export(id: file.id, url: url, botId: entry.botId, threadId: entry.threadId)+ exported = item+ export = item+ } catch is CancellationError {+ states[file.id] = nil+ } catch {+ if !Task.isCancelled, !retired { states[file.id] = .failed(error.localizedDescription) }+ }+ tasks[file.id] = nil+ }+ }++ private func update(_ id: String, received: Int64) {+ guard !retired, tasks[id]?.isCancelled == false else { return }+ states[id] = .downloading(received)+ }++ public func cancel(_ id: String) { tasks[id]?.cancel(); states[id] = nil }++ /// The native share sheet has finished using the verified temporary file.+ public func dismissExport() {+ export = nil+ guard let item = exported else { return }+ exported = nil+ Task { do { try await writer.remove(item.url) } catch { states[item.id] = .failed(error.localizedDescription) } }+ }++ public func retire() {+ retired = true+ for task in tasks.values { task.cancel() }+ dismissExport()+ states.removeAll()+ }+}diff --git a/apps/ios/Kit/Sources/CodyncUI/Thread/ChatRows.swift b/apps/ios/Kit/Sources/CodyncUI/Thread/ChatRows.swiftindex 57ca4aea..681ee5e9 100644--- a/apps/ios/Kit/Sources/CodyncUI/Thread/ChatRows.swift+++ b/apps/ios/Kit/Sources/CodyncUI/Thread/ChatRows.swift@@ -200,11 +200,16 @@ struct AgentBubble: View {var body: some View {VStack(alignment: .leading, spacing: 4) {- MarkdownText(entry.data.text ?? "")- .equatable()- .padding(.horizontal, 16)- .padding(.vertical, 10)- .background(Palette.bubbleAgent, in: RoundedRectangle(cornerRadius: 18, style: .continuous))+ Group {+ if let files = entry.data.files, !files.isEmpty {+ ForEach(files) { file in FileDownloadCard(entry: entry, file: file) }+ } else {+ MarkdownText(entry.data.text ?? "").equatable()+ .padding(.horizontal, 16)+ .padding(.vertical, 10)+ .background(Palette.bubbleAgent, in: RoundedRectangle(cornerRadius: 18, style: .continuous))+ }+ }.contextActions(reactions: model.reactionPick(entry)) {var items = [MenuItem("Copy", icon: "square.on.square") { Pasteboard.copy(entry.data.text) },diff --git a/apps/ios/Kit/Sources/CodyncUI/Thread/FileDownloadCard.swift b/apps/ios/Kit/Sources/CodyncUI/Thread/FileDownloadCard.swiftnew file mode 100644index 00000000..235a6246--- /dev/null+++ b/apps/ios/Kit/Sources/CodyncUI/Thread/FileDownloadCard.swift@@ -0,0 +1,60 @@+import CodyncKit+import SwiftUI+import UIKit++struct FileDownloadCard: View {+ let entry: Entry+ let file: SharedFile+ @Environment(BotStore.self) private var model++ var body: some View {+ let state = model.fileDownloads.states[file.id]+ HStack(spacing: 12) {+ Image(systemName: AttachmentIcon.symbol(file.name)).font(.system(size: 24)).foregroundStyle(Palette.secondary)+ VStack(alignment: .leading, spacing: 3) {+ Text(file.name).font(.subheadline.weight(.semibold)).foregroundStyle(Palette.text).lineLimit(2)+ Text(detail(state)).font(.caption2).foregroundStyle(Palette.secondary)+ }+ Spacer(minLength: 0)+ Button {+ Motion.animate {+ if case .downloading = state { model.fileDownloads.cancel(file.id) }+ else { model.fileDownloads.save(client: model.client, entry: entry, file: file) }+ }+ } label: {+ Image(systemName: busy(state) ? "xmark" : "arrow.down.to.line")+ .font(.system(size: 20)).frame(width: 36, height: 36)+ }+ .buttonStyle(.plain)+ .accessibilityLabel("\(busy(state) ? "Cancel download" : "Download") \(file.name)")+ }+ .padding(14)+ .background(Palette.bubbleAgent, in: RoundedRectangle(cornerRadius: 16))+ }++ private func busy(_ state: FileDownloads.State?) -> Bool {+ if case .downloading = state { return true }+ return false+ }+ private func detail(_ state: FileDownloads.State?) -> String {+ let size = ByteCountFormatter.string(fromByteCount: file.size, countStyle: .file)+ switch state {+ case .downloading(let received): return "\(ByteCountFormatter.string(fromByteCount: received, countStyle: .file)) of \(size)"+ case .failed(let message): return "\(message) Tap to retry."+ case .saved: return "\(size) · Downloaded"+ case nil: return size+ }+ }+}++/// iOS owns save/export destinations through its native share sheet.+struct FileExportSheet: UIViewControllerRepresentable {+ let url: URL+ let completed: () -> Void+ func makeUIViewController(context: Context) -> UIActivityViewController {+ let controller = UIActivityViewController(activityItems: [url], applicationActivities: nil)+ controller.completionWithItemsHandler = { _, _, _, _ in completed() }+ return controller+ }+ func updateUIViewController(_ controller: UIActivityViewController, context: Context) {}+}diff --git a/apps/ios/Kit/Sources/CodyncUI/Thread/RepliesView.swift b/apps/ios/Kit/Sources/CodyncUI/Thread/RepliesView.swiftindex 223277db..da04d1a3 100644--- a/apps/ios/Kit/Sources/CodyncUI/Thread/RepliesView.swift+++ b/apps/ios/Kit/Sources/CodyncUI/Thread/RepliesView.swift@@ -48,6 +48,12 @@ struct RepliesView: View {.task(id: rootId) { await model.loadThread(botId, root: rootId) }// A thread is read on its own: having it open reads its replies..readingConversation(botId, thread: rootId)+ .codyncSheet(item: Binding<FileDownloads.Export?>(get: {+ guard let item = model.fileDownloads.export, item.botId == botId, item.threadId == rootId else { return nil }+ return item+ }, set: { if $0 == nil { model.fileDownloads.dismissExport() } })) { item in+ FileExportSheet(url: item.url) { model.fileDownloads.dismissExport() }+ }.codyncSheet(isPresented: $showTrace) {TraceView(botId: botId, thread: rootId)}diff --git a/apps/ios/Kit/Sources/CodyncUI/Thread/ThreadView.swift b/apps/ios/Kit/Sources/CodyncUI/Thread/ThreadView.swiftindex 607dceab..9a53da52 100644--- a/apps/ios/Kit/Sources/CodyncUI/Thread/ThreadView.swift+++ b/apps/ios/Kit/Sources/CodyncUI/Thread/ThreadView.swift@@ -73,6 +73,12 @@ public struct ThreadView: View {var conversation: some View {chrome(chat).readingConversation(botId)+ .codyncSheet(item: Binding<FileDownloads.Export?>(get: {+ guard let item = model.fileDownloads.export, item.botId == botId, item.threadId == nil else { return nil }+ return item+ }, set: { if $0 == nil { model.fileDownloads.dismissExport() } })) { item in+ FileExportSheet(url: item.url) { model.fileDownloads.dismissExport() }+ }.codyncSheet(isPresented: $showTrace) {TraceView(botId: botId)}diff --git a/apps/ios/Kit/Tests/CodyncKitTests/FileDownloadTests.swift b/apps/ios/Kit/Tests/CodyncKitTests/FileDownloadTests.swiftnew file mode 100644index 00000000..7e2a983b--- /dev/null+++ b/apps/ios/Kit/Tests/CodyncKitTests/FileDownloadTests.swift@@ -0,0 +1,78 @@+import CryptoKit+import Foundation+import Testing+@testable import CodyncKit++private struct FileTransport: HostTransport {+ let bytes: Data+ var truncate = false+ var wrongSize = false+ func call(_ method: String, body: Data, timeout: TimeInterval) async throws -> Data {+ #expect(method == "readFile")+ let request = try #require(JSONSerialization.jsonObject(with: body) as? [String: Any])+ let offset = try #require(request["offset"] as? Int)+ let end = min(offset + FileDownload.chunkSize, bytes.count)+ let data = truncate ? Data() : bytes.subdata(in: offset..<end)+ return try JSONSerialization.data(withJSONObject: ["data": data.base64EncodedString(), "size": bytes.count + (wrongSize ? 1 : 0)])+ }+ func stream(_ request: HostStreamRequest) -> AsyncThrowingStream<Data, Error> { AsyncThrowingStream { $0.finish() } }+ func states() -> AsyncStream<LinkState> { AsyncStream { $0.finish() } }+}++private func metadata(_ data: Data, name: String = "file.bin") -> SharedFile {+ SharedFile(id: UUID().uuidString, name: name, size: Int64(data.count), sha256: SHA256.hash(data: data).map { String(format: "%02x", $0) }.joined())+}++@Test func generatedFilesDownloadExactBinaryAndEmptyBytes() async throws {+ let directory = FileManager.default.temporaryDirectory.appendingPathComponent(UUID().uuidString)+ defer { try? FileManager.default.removeItem(at: directory) }+ let writer = FileDownload()+ for bytes in [Data(), Data((0..<(FileDownload.chunkSize + 7)).map { UInt8($0 % 256) })] {+ let file = metadata(bytes, name: ".download-partial")+ let url = try await writer.save(client: HostClient(transport: FileTransport(bytes: bytes)), entryId: "entry", file: file, directory: directory) { _ in }+ #expect(try Data(contentsOf: url) == bytes)+ #expect(url.lastPathComponent == ".download-partial")+ try await writer.remove(url)+ }+}++@Test func generatedFileFailuresRemovePartialBytes() async throws {+ let directory = FileManager.default.temporaryDirectory.appendingPathComponent(UUID().uuidString)+ defer { try? FileManager.default.removeItem(at: directory) }+ let bytes = Data([0, 255, 42])+ let writer = FileDownload()+ for transport in [FileTransport(bytes: bytes, truncate: true), FileTransport(bytes: bytes, wrongSize: true)] {+ await #expect(throws: FileDownloadError.self) {+ try await writer.save(client: HostClient(transport: transport), entryId: "entry", file: metadata(bytes), directory: directory) { _ in }+ }+ #expect(try FileManager.default.contentsOfDirectory(atPath: directory.path).isEmpty)+ }+ let bad = SharedFile(id: "id", name: "file.bin", size: Int64(bytes.count), sha256: String(repeating: "0", count: 64))+ await #expect(throws: FileDownloadError.self) {+ try await writer.save(client: HostClient(transport: FileTransport(bytes: bytes)), entryId: "entry", file: bad, directory: directory) { _ in }+ }+ #expect(try FileManager.default.contentsOfDirectory(atPath: directory.path).isEmpty)+}++@Test func generatedFileCancellationRemovesPartialBytes() async throws {+ let directory = FileManager.default.temporaryDirectory.appendingPathComponent(UUID().uuidString)+ defer { try? FileManager.default.removeItem(at: directory) }+ let bytes = Data(repeating: 42, count: FileDownload.chunkSize + 1)+ let writer = FileDownload()+ let task = Task {+ try await writer.save(client: HostClient(transport: FileTransport(bytes: bytes)), entryId: "entry", file: metadata(bytes), directory: directory) { _ in+ withUnsafeCurrentTask { $0?.cancel() }+ }+ }+ await #expect(throws: CancellationError.self) { try await task.value }+ #expect(try FileManager.default.contentsOfDirectory(atPath: directory.path).isEmpty)+}++@Test func generatedFileMetadataIsAdditiveAndRejectsUnsafeNames() throws {+ let old = try JSONDecoder().decode(EntryData.self, from: Data(#"{"text":"hello","final":true}"#.utf8))+ #expect(old.files == nil)+ for name in ["../escape", "bad\\file", "..", "\n"] {+ #expect(throws: FileDownloadError.self) { try metadata(Data(), name: name).validate() }+ }+ try metadata(Data(), name: ".hidden").validate()+}diff --git a/apps/ios/Kit/Tests/CodyncUITests/FileDownloadTests.swift b/apps/ios/Kit/Tests/CodyncUITests/FileDownloadTests.swiftnew file mode 100644index 00000000..b5a1eb97--- /dev/null+++ b/apps/ios/Kit/Tests/CodyncUITests/FileDownloadTests.swift@@ -0,0 +1,64 @@+import Foundation+import SwiftUI+import Testing+@testable import CodyncKit+@testable import CodyncUI++private actor DelayedFileTransport: HostTransport {+ private var pending: CheckedContinuation<Data, any Error>?+ var called: Bool { pending != nil }+ func call(_ method: String, body: Data, timeout: TimeInterval) async throws -> Data {+ try await withCheckedThrowingContinuation { pending = $0 }+ }+ func release() { pending?.resume(returning: Data(#"{"data":"","size":0}"#.utf8)); pending = nil }+ nonisolated func stream(_ request: HostStreamRequest) -> AsyncThrowingStream<Data, Error> { AsyncThrowingStream { $0.finish() } }+ nonisolated func states() -> AsyncStream<LinkState> { AsyncStream { $0.finish() } }+}++@MainActor @Test func retiringFileDownloadsCannotExportALateChunk() async throws {+ let downloads = FileDownloads()+ let transport = DelayedFileTransport()+ let file = SharedFile(id: "file", name: "empty", size: 0, sha256: "e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855")+ let entry = Entry(id: "entry", seq: 1, botId: "bot", rev: 1, kind: "agent", turn: 1, data: EntryData(), createdAt: 0, updatedAt: 0)+ downloads.save(client: HostClient(transport: transport), entry: entry, file: file)+ for _ in 0..<100 {+ let called = await transport.called+ if called { break }+ try await Task.sleep(for: .milliseconds(10))+ }+ let called = await transport.called+ #expect(called)+ downloads.retire()+ await transport.release()+ try await Task.sleep(for: .milliseconds(30))+ #expect(downloads.export == nil)+ #expect(downloads.states.isEmpty)+}++/// Opt-in product screenshots using the actual card and text bubble views.+@MainActor @Test func renderGeneratedFileCards() throws {+ guard let directory = ProcessInfo.processInfo.environment["CODYNC_RENDER_DIR"] else { return }+ let suite = "CodyncFileCardRender.\(UUID().uuidString)"+ defer { UserDefaults(suiteName: suite)?.removePersistentDomain(forName: suite) }+ let store = BotStore(computer: Computer(id: "render", name: "Computer", signKey: "", boxKey: "", cloud: nil), clientKind: "ios", storage: SharedStore.Context(accountID: "render", suite: suite)) { FakeRemote(.connecting) }+ defer { store.retire() }+ func entry(_ name: String, size: Int64) -> Entry {+ var data = EntryData(text: "\(name) (\(size) bytes)")+ data.final = true+ data.files = [SharedFile(id: name, name: name, size: size, sha256: String(repeating: "0", count: 64))]+ return Entry(id: name, seq: 1, botId: "bot", rev: 1, kind: "agent", turn: 1, data: data, createdAt: 0, updatedAt: 0)+ }+ for scheme in [ColorScheme.light, .dark] {+ let content = VStack(alignment: .leading, spacing: 14) {+ Text("Your files are ready.").padding(14).background(Palette.bubbleAgent, in: RoundedRectangle(cornerRadius: 22))+ AgentBubble(entry: entry("sample-results.csv", size: 71_000), openTrace: {})+ AgentBubble(entry: entry("report.pdf", size: 1_250_000), openTrace: {})+ AgentBubble(entry: entry("binary-output-with-a-long-filename.dat", size: 2_000_000), openTrace: {})+ AgentBubble(entry: entry(".empty", size: 0), openTrace: {})+ }.padding(18).frame(width: 390).background(Palette.background).environment(store).environment(\.colorScheme, scheme)+ let renderer = ImageRenderer(content: content)+ renderer.scale = 2+ let image = try #require(renderer.uiImage?.pngData())+ try image.write(to: URL(fileURLWithPath: directory).appendingPathComponent("iphone-\(scheme == .dark ? "dark" : "light").png"))+ }+}diff --git a/docs/features/chat-messages.md b/docs/features/chat-messages.mdindex f39f445a..e3172427 100644--- a/docs/features/chat-messages.md+++ b/docs/features/chat-messages.md@@ -5,13 +5,16 @@ How a bot's work turns into what the user reads, copied from Grok Bot.## Messages are sent, not streamed- Every bot gets the built-in `chat` MCP server (`codync-host mcp chat`,- `host/src/chat/outbox.rs`) with one tool, `send_message {text}`. In the bot's own chat and its+ `host/src/chat/outbox.rs`) with `send_message {text}` and `send_file {path, name?}`. In the bot's own chat and itsthreads, each call is one chat bubble, added to the turn's lane at once as an `agent` entry with`final: true`. A turn can send several.- The agent's own reply text (`agent_message_chunk`) stays in the trace when the turn sent- anything. A turn that sent nothing (an agent that ignores the tool, or has no MCP) falls back to+ text through `send_message`. A turn that sent nothing (an agent that ignores the tool, or has no MCP) falls back tothe old rule: its last text becomes the turn's final message.-- Group room turns, `ask_bot` requests and routines reject `send_message`: their reply is the+- File cards are separate final entries. Sharing a file preserves an intended final text+ reply; a files-only turn uses its filename for the completion summary. See+ [file attachments](file-attachments.md#files-from-a-bot).+- Group room turns, `ask_bot` requests and routines reject `send_message` and `send_file`: their reply is theturn's last text, as before (`chat/group.rs`, `chat/team.rs`, `routines`).- The rules reach the agent twice: the MCP server's instructions, and the frozen instructionsnapshot (`chat/context.rs`).diff --git a/docs/features/file-attachments.md b/docs/features/file-attachments.mdindex 15f1fd87..6572b03c 100644--- a/docs/features/file-attachments.md+++ b/docs/features/file-attachments.md@@ -1,6 +1,6 @@# File attachments-Photos and files sent with a message, from the iPhone and the desktop app.+Files travel in both directions: users attach inputs, and bots explicitly share generated outputs.- Composer: the **+** button left of the message box. iPhone: a menu with Photos (sent as JPEG) andFiles (plus Paste when the clipboard has an image); desktop: an open panel. Files and images can@@ -29,3 +29,44 @@ Photos and files sent with a message, from the iPhone and the desktop app.an empty draft removes the last one); sent files show as `▤ name size` lines. It uploads with thesame `upload` chunks.- A files-only message previews in the roster as its file names.++## Files from a bot++In its own chat or a reply thread, a bot calls the built-in chat MCP tool+`send_file {path, name?}`. Paths may be absolute or relative to its working directory.+The optional name is a display filename without folders. Any regular file type is+accepted, including binary, hidden, extensionless and empty files, up to 100 MiB.+Directories and special files are refused. Group, routine and delegated turns cannot+publish files.++The host streams a snapshot into `~/.codync/bots/<bot>/files/<fileId>` and records+its byte size and SHA-256 before publishing a final agent entry with+`files: [{id, name, size, sha256}]`. Copying runs outside the bot actor; Stop,+reconfiguration, timeout and turn completion cancel unpublished copies. A success+response means the file message is already saved. Check the conversation before+retrying an interrupted publication, to avoid duplicate messages.++Snapshots remain available after the original is edited, removed, or its workspace+changes, and after a host restart. Storage follows the host data directory rather+than the bot working directory. Generated files are separate from input uploads;+`attachments` and `readUpload` retain their existing meaning. Older clients show+the entry's filename/size text fallback. No version or compatibility floor changes.++The authenticated `readFile {entryId, fileId, offset}` API requires a nonnegative+integer offset within the saved size and a file belonging to that final agent entry+in an undeleted bot's own chat or thread. Existing caller permissions apply: paired+clients need Control access. It returns `{data: <base64>, size}` in chunks of at most+384 KiB over loopback, SSH, direct encrypted and relay transports.++Updated clients show a filename, size, file icon and download action. File extension+only selects the icon; it never restricts saving or changes bytes. Desktop uses its+native Save dialog, iPhone hands the verified temporary file to the native share+sheet (including Save to Files), and the terminal's selected-message `f` action saves+to Downloads without replacing existing files. Progress and errors appear alongside+the action; cancel stops further reads, discards late responses and removes partial+files. Retry starts from zero. Account/computer retirement cancels its transfers.+Downloads use bounded memory and check size and SHA-256 before save/export.++This feature adds no previews, inline viewers, folder packaging, background transfers,+persistent resume, Android or Watch UI. Existing bots do not publish workspace files+automatically: they must call `send_file`.diff --git a/host/Cargo.lock b/host/Cargo.lockindex ddf0a065..1422e0af 100644--- a/host/Cargo.lock+++ b/host/Cargo.lock@@ -608,6 +608,7 @@ dependencies = ["hmac 0.13.0","if-addrs","keyring",+ "libc","portable-pty","qrcode","ratatui",diff --git a/host/Cargo.toml b/host/Cargo.tomlindex 74b80702..9055d0f7 100644--- a/host/Cargo.toml+++ b/host/Cargo.toml@@ -90,3 +90,6 @@ lto = "thin"codegen-units = 1strip = true++[target.'cfg(unix)'.dependencies]+libc = "0.2"diff --git a/host/src/agent/bot/files.rs b/host/src/agent/bot/files.rsnew file mode 100644index 00000000..f6521e2a--- /dev/null+++ b/host/src/agent/bot/files.rs@@ -0,0 +1,113 @@+//! File copies run outside the actor; publication still belongs to its original turn.+use super::Actor;+use crate::chat::files::{self, Snapshot};+use crate::store::EntryKind;+use anyhow::{Result, anyhow, ensure};+use serde_json::json;+use std::path::PathBuf;+use std::sync::{+ Arc,+ atomic::{AtomicBool, Ordering},+};+use tokio::sync::{mpsc, oneshot};++type Reply = oneshot::Sender<Result<()>>;+pub(super) struct Completed {+ epoch: u64,+ cancelled: Arc<AtomicBool>,+ reply: Reply,+ result: Result<Snapshot>,+}++pub(super) struct FileShares {+ epoch: u64,+ pub summary: Option<String>,+ pending: Vec<Arc<AtomicBool>>,+ pub tx: mpsc::UnboundedSender<Completed>,+ pub rx: mpsc::UnboundedReceiver<Completed>,+}+impl Default for FileShares {+ fn default() -> Self {+ let (tx, rx) = mpsc::unbounded_channel();+ Self { epoch: 0, summary: None, pending: Vec::new(), tx, rx }+ }+}+impl FileShares {+ pub fn cancel(&mut self) {+ self.epoch = self.epoch.wrapping_add(1);+ for flag in self.pending.drain(..) {+ flag.store(true, Ordering::Release);+ }+ }+}+impl Drop for FileShares {+ fn drop(&mut self) {+ self.cancel();+ }+}++impl Actor {+ pub(super) fn begin_file(+ &mut self,+ source: String,+ name: Option<String>,+ cancelled: Arc<AtomicBool>,+ reply: Reply,+ ) {+ if let Err(error) = self.can_send_file() {+ let _ = reply.send(Err(error));+ return;+ }+ self.files.pending.retain(|flag| !flag.load(Ordering::Acquire));+ if self.files.pending.len() >= 4 {+ let _ = reply.send(Err(anyhow!("too many pending file shares")));+ return;+ }+ self.files.pending.push(cancelled.clone());+ let epoch = self.files.epoch;+ let root = files::root(&self.cfg.id);+ let cwd = PathBuf::from(&self.cfg.cwd);+ let tx = self.files.tx.clone();+ tokio::spawn(async move {+ let flag = cancelled.clone();+ let result =+ tokio::task::spawn_blocking(move || files::snapshot(&root, &cwd, &source, name.as_deref(), &flag))+ .await;+ let result = result.map_err(anyhow::Error::from).and_then(std::convert::identity);+ let _ = tx.send(Completed { epoch, cancelled, reply, result });+ });+ }++ fn can_send_file(&self) -> Result<i64> {+ ensure!(!self.stop_requested, "turn is stopping");+ ensure!(+ self.active_group.is_none() && self.active_ask.is_none() && self.active_routine.is_none(),+ "send_file is only available in the bot's own chat and threads"+ );+ self.turn.ok_or_else(|| anyhow!("no turn is running"))+ }++ pub(super) fn finish_file(&mut self, completed: Completed) {+ self.files.pending.retain(|flag| !Arc::ptr_eq(flag, &completed.cancelled));+ let result = (|| {+ ensure!(+ completed.epoch == self.files.epoch+ && !completed.cancelled.load(Ordering::Acquire)+ && !completed.reply.is_closed(),+ "file sharing cancelled"+ );+ let turn = self.can_send_file()?;+ ensure!(self.hub.store.bot(&self.cfg.id)?.is_some_and(|bot| !bot.deleted), "bot was deleted");+ let mut snapshot = completed.result?;+ let text = format!("{} ({} bytes)", snapshot.meta.name, snapshot.meta.size);+ self.close_seg();+ self.add(EntryKind::Agent, turn, json!({"text": text, "final": true, "files": [snapshot.meta]}))+ .ok_or_else(|| anyhow!("couldn't save the file message"))?;+ snapshot.commit();+ self.files.summary = Some(text);+ self.set_activity("Working…");+ Ok(())+ })();+ let _ = completed.reply.send(result);+ }+}diff --git a/host/src/agent/bot/mod.rs b/host/src/agent/bot/mod.rsindex fe096df7..2cd87b06 100644--- a/host/src/agent/bot/mod.rs+++ b/host/src/agent/bot/mod.rs@@ -15,6 +15,7 @@//! forked from the main one when the agent can fork) and in group chats (turns in//! its main session, written to the group's transcript; see `group`).+mod files;mod queue;mod session;mod turn;@@ -60,6 +61,12 @@ pub enum Cmd {text: String,reply: tokio::sync::oneshot::Sender<Result<()>>,},+ SendFile {+ path: String,+ name: Option<String>,+ cancelled: Arc<std::sync::atomic::AtomicBool>,+ reply: tokio::sync::oneshot::Sender<Result<()>>,+ },CancelAsk {id: String,},@@ -132,6 +139,7 @@ pub fn spawn(hub: Arc<Hub>, cfg: BotConfig) -> BotHandle {plan_entry: None,last_text: None,sent: Vec::new(),+ files: files::FileShares::default(),perms: HashMap::new(),stop_requested: false,exit_tail: None,@@ -215,6 +223,7 @@ struct Actor {last_text: Option<String>,/// Messages the bot sent the user this turn (`send_message`); none: its last text is the reply.sent: Vec<String>,+ files: files::FileShares,/// permission entry id -> JSON-RPC request idperms: HashMap<String, Value>,stop_requested: bool,@@ -261,6 +270,7 @@ impl Actor {let Some(cmd) = cmd else { break };if !self.on_cmd(cmd, &done_tx).await { break }}+ Some(file) = self.files.rx.recv() => self.finish_file(file),inc = recv_incoming(&mut self.conn) => self.on_incoming(inc).await,Some(done) = done_rx.recv() => {// Updates sent before the prompt response are already queued; apply them first.@@ -284,6 +294,7 @@ impl Actor {},}}+ self.files.cancel();self.hub.team.cancel_from(&self.cfg.id);self.complete_request(Err(anyhow!("recipient shut down")), true);self.complete_group(Err(anyhow!("bot shut down")));diff --git a/host/src/agent/bot/queue.rs b/host/src/agent/bot/queue.rsindex 18a8c738..7eff6590 100644--- a/host/src/agent/bot/queue.rs+++ b/host/src/agent/bot/queue.rs@@ -61,6 +61,7 @@ impl Actor {Cmd::SendToUser { text, reply } => {let _ = reply.send(self.send_to_user(text));}+ Cmd::SendFile { path, name, cancelled, reply } => self.begin_file(path, name, cancelled, reply),Cmd::Stop => self.stop().await,Cmd::Permission { entry_id, option_id } => self.answer_permission(&entry_id, option_id).await,Cmd::NewSession => {@@ -85,6 +86,7 @@ impl Actor {// on the next message (see `context`).self.cfg = cfg;if restart {+ self.files.cancel();if let Some(c) = self.conn.take() {c.acp.kill().await;}@@ -131,6 +133,7 @@ impl Actor {return;}self.stop_requested = true;+ self.files.cancel();let ids: Vec<String> = self.perms.keys().cloned().collect();for id in ids {self.answer_permission(&id, None).await;diff --git a/host/src/agent/bot/turn.rs b/host/src/agent/bot/turn.rsindex 3735ebc3..74b3d0d2 100644--- a/host/src/agent/bot/turn.rs+++ b/host/src/agent/bot/turn.rs@@ -53,6 +53,8 @@ impl Actor {self.plan_entry = None;self.last_text = None;self.sent.clear();+ self.files.summary = None;+ self.files.cancel();// A delegated or group turn has no live waiter after a host restart. Its persisted// notices are marked interrupted instead of silently repeating work.self.set_inflight(@@ -108,6 +110,7 @@ impl Actor {let claude = self.conn.as_ref().is_some_and(|c| c.claude);let sid = self.turn_session.clone().ok_or_else(|| anyhow!("no session"))?;let snapshot = self.snapshot(&sid).await?;+ let remind_files = !snapshot.system.contains("send_file");let mut prompt = text.to_owned();if let Some(intro) = self.thread_intro.take() {prompt = format!("{intro}\n\n{prompt}");@@ -123,6 +126,9 @@ impl Actor {prompt = format!("{prompt}\n\n{update}");self.announce = Some((snapshot, identity));}+ if remind_files && self.active_group.is_none() && self.active_ask.is_none() && self.active_routine.is_none() {+ prompt.push_str("\n\n[Codync: send_file(path, name?) shares any regular file up to 100 MiB as a downloadable card. Use it instead of sending a local path.]");+ }self.hub.set_runtime(&self.id(), |r| r.activity = "Thinking…".into());let acp = self.conn.as_ref().ok_or_else(|| anyhow!("agent not running"))?.acp.clone();let params = json!({@@ -146,6 +152,7 @@ impl Actor {if self.turn.is_none() {return;}+ self.files.cancel();self.flush(true);self.seg = Seg::None;// Unanswered permission cards can't be answered after the turn.@@ -186,6 +193,9 @@ impl Actor {final_text = text;}}+ if final_text.is_none() {+ final_text = self.files.summary.take();+ }let stop_reason = match &done {Ok(v) => v["stopReason"].as_str().unwrap_or("end_turn").to_owned(),Err(_) => "error".into(),diff --git a/host/src/api/files.rs b/host/src/api/files.rsnew file mode 100644index 00000000..089b5fda--- /dev/null+++ b/host/src/api/files.rs@@ -0,0 +1,26 @@+use super::str_arg;+use crate::chat::files::{self, SharedFile};+use crate::hub::Hub;+use anyhow::{Result, anyhow, ensure};+use base64::Engine as _;+use serde_json::{Value, json};+use std::sync::Arc;++pub async fn read(hub: &Arc<Hub>, body: &Value) -> Result<Value> {+ let entry = hub.store.entry(str_arg(body, "entryId")?).ok_or_else(|| anyhow!("unknown file message"))?;+ ensure!(entry.kind == "agent" && entry.data["final"] == true, "not a file message");+ let bot = entry.data["author"].as_str().ok_or_else(|| anyhow!("missing file author"))?;+ ensure!(entry.bot_id == bot, "not a bot chat file");+ ensure!(hub.store.bot(bot)?.is_some_and(|row| !row.deleted), "unknown bot");+ let id = str_arg(body, "fileId")?;+ let meta = entry.data["files"]+ .as_array()+ .and_then(|files| files.iter().find(|meta| meta["id"] == id))+ .ok_or_else(|| anyhow!("file does not belong to this message"))?;+ let meta: SharedFile = serde_json::from_value(meta.clone())?;+ let offset = body["offset"].as_u64().ok_or_else(|| anyhow!("offset must be a nonnegative integer"))?;+ let root = files::root(bot);+ let size = meta.size;+ let data = tokio::task::spawn_blocking(move || files::read(&root, &meta, offset)).await??;+ Ok(json!({"data": base64::engine::general_purpose::STANDARD.encode(data), "size": size}))+}diff --git a/host/src/api/mod.rs b/host/src/api/mod.rsindex 4144f2de..4807d514 100644--- a/host/src/api/mod.rs+++ b/host/src/api/mod.rs@@ -5,6 +5,7 @@mod bots;pub mod devices;mod events;+mod files;mod host;mod http;mod marketplace;@@ -78,6 +79,9 @@ async fn route(hub: &Arc<Hub>, caller: &Caller, method: &str, b: Value) -> Resul{market::vault::unlock(hub.clone()).await?;}+ if method == "readFile" {+ return files::read(hub, &b).await;+ }// Each method group answers its own methods and hands the body back otherwise.let b = match host::call(hub, caller, method, b).await? {ControlFlow::Break(v) => return Ok(v),diff --git a/host/src/chat/files.rs b/host/src/chat/files.rsnew file mode 100644index 00000000..3cf262b7--- /dev/null+++ b/host/src/chat/files.rs@@ -0,0 +1,167 @@+//! Immutable snapshots explicitly published by a bot, independent of its workspace.+use crate::chat::uploads::MAX_FILE;+use anyhow::{Context as _, Result, ensure};+use serde::{Deserialize, Serialize};+use sha2::{Digest as _, Sha256};+use std::fs::{File, OpenOptions};+use std::io::{Read as _, Seek as _, SeekFrom};+use std::path::{Path, PathBuf};+use std::sync::atomic::{AtomicBool, Ordering};++pub const CHUNK_SIZE: usize = 384 * 1024;++#[derive(Clone, Debug, Deserialize, Serialize)]+pub struct SharedFile {+ pub id: String,+ pub name: String,+ pub size: u64,+ pub sha256: String,+}++/// Removes an unpublished snapshot on every failure, including a dropped actor.+pub struct Snapshot {+ pub meta: SharedFile,+ path: PathBuf,+ committed: bool,+}++impl Snapshot {+ pub fn commit(&mut self) {+ self.committed = true;+ }+}++impl Drop for Snapshot {+ fn drop(&mut self) {+ if !self.committed {+ let _ = std::fs::remove_file(&self.path);+ }+ }+}++pub fn root(bot: &str) -> PathBuf {+ crate::service::data_dir().join("bots").join(bot).join("files")+}++fn path(root: &Path, id: &str) -> Result<PathBuf> {+ let id = uuid::Uuid::parse_str(id).context("invalid file id")?;+ Ok(root.join(id.to_string()))+}++/// Display names never control storage paths; hidden and extensionless files are valid.+pub fn name(value: &str) -> Result<String> {+ ensure!(!value.is_empty() && value.len() <= 200, "file name must be 1–200 bytes");+ ensure!(+ value != "." && value != ".." && !value.contains(['/', '\\']) && !value.chars().any(char::is_control),+ "invalid file name"+ );+ Ok(value.to_owned())+}++fn open_regular(path: &Path) -> Result<File> {+ let mut options = OpenOptions::new();+ options.read(true);+ #[cfg(unix)]+ {+ use std::os::unix::fs::OpenOptionsExt as _;+ options.custom_flags(libc::O_NOFOLLOW | libc::O_NONBLOCK);+ }+ ensure!(std::fs::symlink_metadata(path)?.file_type().is_file(), "only regular files can be shared");+ #[cfg(windows)]+ {+ use std::os::windows::fs::OpenOptionsExt as _;+ options.custom_flags(0x0020_0000); // FILE_FLAG_OPEN_REPARSE_POINT+ }+ let file = options.open(path).context("opening the file")?;+ ensure!(file.metadata()?.is_file(), "only regular files can be shared");+ Ok(file)+}++/// Blocking, bounded-memory copy. Call on a blocking worker, never the bot actor.+pub fn snapshot(+ root: &Path,+ cwd: &Path,+ source: &str,+ display: Option<&str>,+ cancelled: &AtomicBool,+) -> Result<Snapshot> {+ let original = cwd.join(source);+ let source = original.canonicalize().context("finding the file")?;+ let display = match display {+ Some(value) => name(value)?,+ None => name(original.file_name().and_then(|v| v.to_str()).context("file name is not UTF-8; provide name")?)?,+ };+ let mut input = open_regular(&source)?;+ let before = input.metadata()?;+ ensure!(before.len() <= MAX_FILE, "file exceeds 100 MiB");+ std::fs::create_dir_all(root).context("creating the shared file folder")?;+ let id = uuid::Uuid::new_v4().to_string();+ let final_path = path(root, &id)?;+ let partial = final_path.with_extension("partial");+ let mut owned = Snapshot {+ meta: SharedFile { id, name: display, size: 0, sha256: String::new() },+ path: partial.clone(),+ committed: false,+ };+ let mut output = OpenOptions::new().write(true).create_new(true).open(&partial)?;+ let (size, digest) = copy(&mut input, &mut output, cancelled)?;+ owned.meta.size = size;+ let after = input.metadata()?;+ ensure!(+ owned.meta.size == before.len() && after.len() == before.len() && after.modified()? == before.modified()?,+ "source file changed while sharing; retry"+ );+ output.sync_all()?;+ drop(output);+ ensure!(!cancelled.load(Ordering::Acquire), "file sharing cancelled");+ std::fs::rename(&partial, &final_path)?;+ owned.path = final_path;+ owned.meta.sha256 = digest;+ Ok(owned)+}++fn copy(+ input: &mut impl std::io::Read,+ output: &mut impl std::io::Write,+ cancelled: &AtomicBool,+) -> Result<(u64, String)> {+ let mut hash = Sha256::new();+ let mut size = 0;+ let mut buffer = vec![0; CHUNK_SIZE];+ loop {+ ensure!(!cancelled.load(Ordering::Acquire), "file sharing cancelled");+ let count = input.read(&mut buffer)?;+ if count == 0 {+ break;+ }+ size += count as u64;+ ensure!(size <= MAX_FILE, "file exceeds 100 MiB");+ output.write_all(&buffer[..count])?;+ hash.update(&buffer[..count]);+ }+ Ok((size, digest_hex(&hash.finalize())))+}++pub fn digest_hex(bytes: &[u8]) -> String {+ use std::fmt::Write as _;+ let mut value = String::with_capacity(bytes.len() * 2);+ for byte in bytes {+ // Formatting into a String cannot fail.+ let _ = write!(value, "{byte:02x}");+ }+ value+}++pub fn read(root: &Path, meta: &SharedFile, offset: u64) -> Result<Vec<u8>> {+ ensure!(meta.size <= MAX_FILE && offset <= meta.size, "invalid file offset or size");+ let mut file = open_regular(&path(root, &meta.id)?)?;+ ensure!(file.metadata()?.len() == meta.size, "shared file is missing or damaged");+ file.seek(SeekFrom::Start(offset))?;+ let length = usize::try_from((meta.size - offset).min(CHUNK_SIZE as u64))?;+ let mut data = vec![0; length];+ file.read_exact(&mut data)?;+ Ok(data)+}++#[cfg(test)]+mod tests;diff --git a/host/src/chat/files/tests.rs b/host/src/chat/files/tests.rsnew file mode 100644index 00000000..c39990c8--- /dev/null+++ b/host/src/chat/files/tests.rs@@ -0,0 +1,104 @@+use super::*;++struct Temp(PathBuf);+impl Temp {+ fn new() -> Self {+ let path = std::env::temp_dir().join(format!("codync-files-{}", uuid::Uuid::new_v4()));+ std::fs::create_dir_all(&path).unwrap();+ Self(path)+ }+}+impl Drop for Temp {+ fn drop(&mut self) {+ let _ = std::fs::remove_dir_all(&self.0);+ }+}++#[test]+fn snapshots_preserve_binary_empty_and_hidden_files_after_source_changes() {+ let temp = Temp::new();+ for (name, data) in+ [("report.bin", vec![0, 255, 1, 128]), (".hidden", vec![]), ("no-extension", vec![42; CHUNK_SIZE + 13])]+ {+ std::fs::write(temp.0.join(name), &data).unwrap();+ let root = temp.0.join("snapshots");+ let mut saved = snapshot(&root, &temp.0, name, None, &AtomicBool::new(false)).unwrap();+ saved.commit();+ std::fs::remove_file(temp.0.join(name)).unwrap();+ let mut downloaded = read(&root, &saved.meta, 0).unwrap();+ if downloaded.len() < data.len() {+ downloaded.extend(read(&root, &saved.meta, CHUNK_SIZE as u64).unwrap());+ }+ assert_eq!(downloaded, data);+ assert_eq!(saved.meta.name, name);+ assert_eq!(saved.meta.size, data.len() as u64);+ assert_eq!(read(&root, &saved.meta, data.len() as u64).unwrap(), Vec::<u8>::new());+ assert!(read(&root, &saved.meta, data.len() as u64 + 1).is_err());+ }+}++#[test]+fn failures_and_unpublished_snapshots_leave_no_files() {+ let temp = Temp::new();+ let root = temp.0.join("snapshots");+ std::fs::write(temp.0.join("file"), [1]).unwrap();+ assert!(snapshot(&root, &temp.0, "missing", None, &AtomicBool::new(false)).is_err());+ assert!(snapshot(&root, &temp.0, ".", None, &AtomicBool::new(false)).is_err());+ assert!(snapshot(&root, &temp.0, "file", Some("../escape"), &AtomicBool::new(false)).is_err());+ assert!(snapshot(&root, &temp.0, "file", None, &AtomicBool::new(true)).is_err());+ let saved = snapshot(&root, &temp.0, "file", None, &AtomicBool::new(false)).unwrap();+ drop(saved);+ assert_eq!(std::fs::read_dir(root).unwrap().count(), 0);+}++#[test]+fn rejects_large_files_and_damaged_snapshots() {+ let temp = Temp::new();+ let root = temp.0.join("snapshots");+ let file = File::create(temp.0.join("large")).unwrap();+ file.set_len(MAX_FILE).unwrap();+ let exact = snapshot(&root, &temp.0, "large", None, &AtomicBool::new(false)).unwrap();+ assert_eq!(exact.meta.size, MAX_FILE);+ drop(exact);+ file.set_len(MAX_FILE + 1).unwrap();+ assert!(snapshot(&root, &temp.0, "large", None, &AtomicBool::new(false)).is_err());+ std::fs::write(temp.0.join("file"), [42]).unwrap();+ let saved = snapshot(&root, &temp.0, "file", None, &AtomicBool::new(false)).unwrap();+ std::fs::write(&saved.path, []).unwrap();+ assert!(read(&root, &saved.meta, 0).is_err());+ assert!(path(&root, "../file").is_err());+}++#[cfg(unix)]+#[test]+fn snapshot_reads_symlink_sources_but_never_symlink_storage_or_special_files() {+ use std::os::unix::fs::symlink;+ let temp = Temp::new();+ let root = temp.0.join("snapshots");+ std::fs::write(temp.0.join("file"), [42]).unwrap();+ symlink(temp.0.join("file"), temp.0.join("link")).unwrap();+ let saved = snapshot(&root, &temp.0, "link", Some("linked.dat"), &AtomicBool::new(false)).unwrap();+ std::fs::remove_file(&saved.path).unwrap();+ symlink(temp.0.join("file"), &saved.path).unwrap();+ assert!(read(&root, &saved.meta, 0).is_err());+ assert!(snapshot(&root, &temp.0, "/dev/null", Some("device"), &AtomicBool::new(false)).is_err());+}++#[test]+fn cancellation_during_copy_stops_before_reading_the_next_chunk() {+ struct CancellingReader<'a>(&'a AtomicBool, usize);+ impl std::io::Read for CancellingReader<'_> {+ fn read(&mut self, buffer: &mut [u8]) -> std::io::Result<usize> {+ self.1 += 1;+ self.0.store(true, Ordering::Release);+ buffer[0] = 42;+ Ok(1)+ }+ }+ let cancelled = AtomicBool::new(false);+ let mut reader = CancellingReader(&cancelled, 0);+ let mut output = Vec::new();+ assert!(copy(&mut reader, &mut output, &cancelled).is_err());+ assert_eq!(reader.1, 1);+ assert_eq!(output, [42]);+}diff --git a/host/src/chat/mod.rs b/host/src/chat/mod.rsindex c6a05831..fe7c3426 100644--- a/host/src/chat/mod.rs+++ b/host/src/chat/mod.rs@@ -2,6 +2,7 @@//! bot-to-bot requests, prompt snapshots, long-term memory and automatic bot names.pub mod context;+pub mod files;pub mod group;pub mod memory;pub mod naming;diff --git a/host/src/chat/outbox.rs b/host/src/chat/outbox.rsindex 12728c8c..d71d5f20 100644--- a/host/src/chat/outbox.rs+++ b/host/src/chat/outbox.rs@@ -14,7 +14,7 @@ use std::time::Duration;pub const INSTRUCTIONS: &str = "In your chat with the user and its threads, the user sees only what you send with send_message; \text you write as your reply never reaches them. Send a message whenever you have something worth telling them: \short and plain, one thought per message, in the user's language. Lead with the result, then what needs the user. \-Don't send just to acknowledge, to say you started or are still working, or to repeat yourself.";+Use send_file(path, name?) to share a generated regular file (any type, up to 100 MiB); a local path in text is not a download. Don't send just to acknowledge, to say you started or are still working, or to repeat yourself.";/// Longest message accepted, in bytes.const MAX_MESSAGE_BYTES: usize = 32 * 1024;@@ -31,10 +31,18 @@ pub fn tools() -> Value {"required": ["text"],},"annotations": {"readOnlyHint": false, "idempotentHint": false},+ }, {+ "name": "send_file",+ "description": "Share one regular file with the user in your own chat or thread. Any file type, including empty files, up to 100 MiB. The host saves an immutable copy. Paths are absolute or relative to your working directory. A successful response means the file message was published; do not repeat it.",+ "inputSchema": {"type": "object", "properties": {"path": {"type": "string"}, "name": {"type": "string", "description": "Optional display filename, without folders."}}, "required": ["path"]},+ "annotations": {"readOnlyHint": false, "idempotentHint": false},}])}pub async fn call(hub: &Arc<Hub>, bot: &str, name: &str, args: &Value) -> Result<Value> {+ if name == "send_file" {+ return send_file(hub, bot, args).await;+ }if name != "send_message" {bail!("unknown chat tool: {name}");}@@ -50,3 +58,25 @@ pub async fn call(hub: &Arc<Hub>, bot: &str, name: &str, args: &Value) -> Result.map_err(|_| anyhow!("the bot shut down"))??;Ok(json!({"sent": true}))}++struct CancelCopy(Arc<std::sync::atomic::AtomicBool>);+impl Drop for CancelCopy {+ fn drop(&mut self) {+ self.0.store(true, std::sync::atomic::Ordering::Release);+ }+}++async fn send_file(hub: &Arc<Hub>, bot: &str, args: &Value) -> Result<Value> {+ let path = args["path"].as_str().filter(|s| !s.is_empty()).ok_or_else(|| anyhow!("path is required"))?;+ let name = match args.get("name") {+ Some(value) => Some(crate::chat::files::name(value.as_str().ok_or_else(|| anyhow!("name must be a string"))?)?),+ None => None,+ };+ let guard = CancelCopy(Arc::new(std::sync::atomic::AtomicBool::new(false)));+ let (reply, delivered) = tokio::sync::oneshot::channel();+ hub.send_cmd(bot, Cmd::SendFile { path: path.to_owned(), name, cancelled: guard.0.clone(), reply })?;+ let result = tokio::time::timeout(Duration::from_secs(60), delivered).await;+ let delivered = result.map_err(|_| anyhow!("file sharing timed out; check the conversation before retrying"))?;+ delivered.map_err(|_| anyhow!("file sharing interrupted"))??;+ Ok(json!({"sent": true}))+}diff --git a/host/src/mcp.rs b/host/src/mcp.rsindex b6f33584..32b7285c 100644--- a/host/src/mcp.rs+++ b/host/src/mcp.rs@@ -105,7 +105,7 @@ async fn call(port: u16, token: &str, bot: &str, params: &Value, server: Server)Server::Connectors => ("connectorCall", Duration::from_secs(90)),Server::Routines => ("routineCall", Duration::from_secs(30)),Server::Computer => ("computerCall", Duration::from_secs(60)),- Server::Chat => ("chatCall", Duration::from_secs(30)),+ Server::Chat => ("chatCall", Duration::from_secs(if params["name"] == "send_file" { 70 } else { 30 })),Server::Team => ("teamCall", crate::chat::team::ASK_TIMEOUT + Duration::from_secs(30)),Server::Memory => ("memoryCall", Duration::from_secs(30)),Server::Composio => ("composioCall", Duration::from_secs(120)),diff --git a/host/src/tui/app/events.rs b/host/src/tui/app/events.rsindex cfba8297..253684d0 100644--- a/host/src/tui/app/events.rs+++ b/host/src/tui/app/events.rs@@ -30,6 +30,14 @@ impl App {}Msg::Event(v) => self.on_event(&v),Msg::Reply(after, r) => self.on_reply(after, r),+ Msg::FileDownload { id, status, done } => {+ if self.download.as_ref().is_some_and(|job| job.id == id) {+ self.flash(&status.unwrap_or_else(|error| format!("Download failed: {error}")));+ if done {+ self.download = None;+ }+ }+ }Msg::Term(id, v) => self.on_term(&id, &v),}}diff --git a/host/src/tui/app/mod.rs b/host/src/tui/app/mod.rsindex c050318a..c5cb03b5 100644--- a/host/src/tui/app/mod.rs+++ b/host/src/tui/app/mod.rs@@ -57,6 +57,7 @@ pub struct App {pub drafts: HashMap<String, Editor>,/// Files dropped on the composer (pasted paths), per draft like the text.pub files: HashMap<String, Vec<std::path::PathBuf>>,+ pub download: Option<super::net::files::Download>,sends: HashMap<String, PendingSend>,/// Lines scrolled up from the bottom of the chat (0 = follow new messages).pub chat_scroll: usize,@@ -101,6 +102,7 @@ pub struct App {impl App {pub fn new(client: Client, tx: UnboundedSender<Msg>, url: String) -> Self {Self {+ download: None,client,tx,url,diff --git a/host/src/tui/app/model.rs b/host/src/tui/app/model.rsindex bf4fe530..74d9561a 100644--- a/host/src/tui/app/model.rs+++ b/host/src/tui/app/model.rs@@ -7,6 +7,11 @@ use super::tilde;pub enum Msg {Online(bool),+ FileDownload {+ id: String,+ status: Result<String, String>,+ done: bool,+ },Event(Value),Reply(After, Result<Value, String>),/// The stream is starting over from rev 0: drop what we have.diff --git a/host/src/tui/app/navigate.rs b/host/src/tui/app/navigate.rsindex 312cfbbf..9beeed92 100644--- a/host/src/tui/app/navigate.rs+++ b/host/src/tui/app/navigate.rs@@ -168,7 +168,7 @@ impl App {}KeyCode::Char('f') => {if let Some(e) = picked {- self.save_files(&id, &e.data);+ self.save_files(&id, &e.id, &e.data);}}KeyCode::Char('c') => {diff --git a/host/src/tui/manage/mod.rs b/host/src/tui/manage/mod.rsindex 77051901..f7de77a3 100644--- a/host/src/tui/manage/mod.rs+++ b/host/src/tui/manage/mod.rs@@ -211,7 +211,21 @@ impl App {}/// Saves a message's files to Downloads.- pub(super) fn save_files(&mut self, bot: &str, data: &Value) {+ pub(super) fn save_files(&mut self, bot: &str, entry: &str, data: &Value) {+ if self.download.take().is_some() {+ self.flash("Download cancelled · f retries");+ return;+ }+ if let Some(meta) = data["files"].as_array().and_then(|files| files.first()) {+ match serde_json::from_value(meta.clone()) {+ Ok(file) => {+ self.download = Some(self.client.download_file(entry.to_owned(), file, self.tx.clone()));+ self.flash("Downloading… · f cancels");+ }+ Err(error) => self.flash(&format!("Invalid file: {error}")),+ }+ return;+ }let files: Vec<(String, String)> = data["attachments"].as_array().into_iter()diff --git a/host/src/tui/net.rs b/host/src/tui/net.rsindex b075827e..3fdfd46a 100644--- a/host/src/tui/net.rs+++ b/host/src/tui/net.rs@@ -1,5 +1,7 @@//! Host API over HTTP: JSON commands and the SSE event stream (same wire as the apps).+pub mod files;+use futures::StreamExt;use serde_json::{Value, json};use std::path::PathBuf;diff --git a/host/src/tui/net/files.rs b/host/src/tui/net/files.rsnew file mode 100644index 00000000..a9ae4c42--- /dev/null+++ b/host/src/tui/net/files.rs@@ -0,0 +1,96 @@+use super::Client;+use crate::chat::files::{CHUNK_SIZE, SharedFile};+use crate::chat::uploads::MAX_FILE;+use crate::tui::app::Msg;+use anyhow::{Result, anyhow, ensure};+use base64::Engine as _;+use serde_json::json;+use sha2::{Digest as _, Sha256};+use std::path::PathBuf;+use std::sync::Arc;+use tokio::io::AsyncWriteExt as _;+use tokio::sync::{Notify, mpsc::UnboundedSender};++pub struct Download {+ pub id: String,+ cancel: Arc<Notify>,+}+impl Drop for Download {+ fn drop(&mut self) {+ self.cancel.notify_one();+ }+}+struct Partial(PathBuf);+impl Drop for Partial {+ fn drop(&mut self) {+ let _ = std::fs::remove_file(&self.0);+ }+}++impl Client {+ pub fn download_file(&self, entry: String, file: SharedFile, tx: UnboundedSender<Msg>) -> Download {+ let id = uuid::Uuid::new_v4().to_string();+ let cancel = Arc::new(Notify::new());+ let task = Download { id: id.clone(), cancel: cancel.clone() };+ let client = self.clone();+ tokio::spawn(async move {+ let saved = tokio::select! {+ () = cancel.notified() => return,+ result = save(&client, &entry, &file, &id, &tx) => result,+ };+ let status = saved.map(|path| format!("Saved {}", path.display())).map_err(|error| format!("{error:#}"));+ let _ = tx.send(Msg::FileDownload { id, status, done: true });+ });+ task+ }+}++async fn save(client: &Client, entry: &str, meta: &SharedFile, id: &str, tx: &UnboundedSender<Msg>) -> Result<PathBuf> {+ crate::chat::files::name(&meta.name)?;+ ensure!(+ meta.size <= MAX_FILE && meta.sha256.len() == 64 && meta.sha256.bytes().all(|b| b.is_ascii_hexdigit()),+ "invalid file metadata"+ );+ let dir = dirs::download_dir().or_else(dirs::home_dir).ok_or_else(|| anyhow!("No Downloads folder"))?;+ let partial = Partial(dir.join(format!(".codync-{id}.partial")));+ let mut file = tokio::fs::OpenOptions::new().write(true).create_new(true).open(&partial.0).await?;+ let mut offset = 0;+ let mut hash = Sha256::new();+ loop {+ let result = client.call("readFile", &json!({"entryId": entry, "fileId": meta.id, "offset": offset})).await;+ let response = result.map_err(|e| anyhow!(e))?;+ ensure!(response["size"].as_u64() == Some(meta.size), "file size changed");+ let encoded = response["data"].as_str().ok_or_else(|| anyhow!("invalid file chunk"))?;+ ensure!(encoded.len() <= CHUNK_SIZE / 3 * 4, "file chunk too large");+ let data = base64::engine::general_purpose::STANDARD.decode(encoded)?;+ ensure!(+ data.len() as u64 == (meta.size - offset).min(CHUNK_SIZE as u64),+ "download truncated or changed; press f to retry"+ );+ file.write_all(&data).await?;+ hash.update(&data);+ offset += data.len() as u64;+ let _ = tx.send(Msg::FileDownload {+ id: id.to_owned(),+ status: Ok(format!("Downloading {}: {offset}/{} bytes · f cancels", meta.name, meta.size)),+ done: false,+ });+ if offset == meta.size {+ break;+ }+ }+ let digest: String = crate::chat::files::digest_hex(&hash.finalize());+ ensure!(digest == meta.sha256, "file integrity check failed; press f to retry");+ file.sync_all().await?;+ drop(file);+ // Link a complete file without replacing a concurrently created destination.+ for _ in 0..10_000 {+ let path = super::free_path(&dir, &meta.name);+ match tokio::fs::hard_link(&partial.0, &path).await {+ Ok(()) => return Ok(path),+ Err(error) if error.kind() == std::io::ErrorKind::AlreadyExists => {}+ Err(error) => return Err(error.into()),+ }+ }+ Err(anyhow!("No available filename in Downloads"))+}diff --git a/host/src/tui/view/transcript.rs b/host/src/tui/view/transcript.rsindex 9e7322ce..24c0cfef 100644--- a/host/src/tui/view/transcript.rs+++ b/host/src/tui/view/transcript.rs@@ -230,7 +230,22 @@ fn entry_lines(Span::styled(format!(" {name}"), name_style(color)),Span::styled(format!(" {}", clock(e.created_at)), t.dim),]));- out.lines.extend(md::render(e.text(), width, 1));+ if let Some(files) = e.data["files"].as_array().filter(|files| !files.is_empty()) {+ for file in files {+ let name = file["name"].as_str().unwrap_or("file");+ let size = file["size"].as_u64().unwrap_or(0);+ out.lines.push(Line::from(Span::styled(+ format!(" ▤ {} · {}", truncate(name, width.saturating_sub(18)), file_size(size)),+ t.text,+ )));+ out.lines.push(Line::from(Span::styled(+ " Select this message, then f to download · f again cancels",+ t.dim,+ )));+ }+ } else {+ out.lines.extend(md::render(e.text(), width, 1));+ }reactions(out, e);out.messages.push((e.id.clone(), from, out.lines.len()));if let Some(ti) = info.get(&e.turn).filter(|ti| ti.steps > 0 && ti.last_message.as_ref() == Some(&e.id)) {@@ -352,6 +367,23 @@ fn thread_summary(v: &serde_json::Value) -> Option<String> {mod tests {use super::*;+ #[tokio::test]+ async fn generated_files_are_selectable_cards_without_duplicate_fallback_text() {+ use crate::tui::app::Msg;+ use serde_json::json;+ let (tx, _rx) = tokio::sync::mpsc::unbounded_channel();+ let mut app = App::new(crate::tui::net::Client::new("http://127.0.0.1:1", Some("fixture")), tx, String::new());+ app.on_msg(Msg::Event(json!({"type":"bot", "bot":{"id":"bot", "name":"Files", "cwd":"/workspace", "backend":"custom", "status":"idle"}})));+ app.on_msg(Msg::Event(json!({"type":"entry", "entry":{"id":"file-entry", "botId":"bot", "seq":1, "kind":"agent", "turn":1, "data":{"author":"bot", "text":"fallback must stay hidden", "final":true, "files":[{"id":"file", "name":".empty", "size":0, "sha256":"hash"}]}}})));+ let bot = app.bots.get("bot").unwrap();+ let chat = build_chat(&app, bot, 80);+ let text = chat.lines.iter().map(ToString::to_string).collect::<Vec<_>>().join("\n");+ assert!(text.contains(".empty"));+ assert!(text.contains("f to download"));+ assert!(!text.contains("fallback must stay hidden"));+ assert!(chat.messages.iter().any(|(id, _, _)| id == "file-entry"));+ }+#[test]fn thread_summary_counts_replies() {assert_eq!(thread_summary(&serde_json::json!({"count": 0})), None);diff --git a/host/tests/files_e2e.rs b/host/tests/files_e2e.rsnew file mode 100644index 00000000..261498e5--- /dev/null+++ b/host/tests/files_e2e.rs@@ -0,0 +1,321 @@+//! Generated file publication through real ACP/MCP and authenticated HTTP.++#![allow(clippy::unwrap_used, clippy::expect_used, clippy::panic)]++mod common;++use serde_json::{Value, json};+use std::path::PathBuf;+use std::process::{Child, Command, Stdio};+use std::time::Duration;++struct Host {+ child: Child,+ home: PathBuf,+ base: String,+ token: String,+}++impl Drop for Host {+ fn drop(&mut self) {+ common::stop(&mut self.child);+ let _ = std::fs::remove_dir_all(&self.home);+ }+}++impl Host {+ async fn start() -> Self {+ let home = std::env::temp_dir().join(format!("codync-files-e2e-{}", uuid::Uuid::new_v4()));+ std::fs::create_dir_all(&home).unwrap();+ let port = std::net::TcpListener::bind("127.0.0.1:0").unwrap().local_addr().unwrap().port();+ let child = Command::new(env!("CARGO_BIN_EXE_codync-host"))+ .args(["serve", "--bind", "127.0.0.1", "--port", &port.to_string()])+ .env("CODYNC_CLOUD", "off")+ .env("CODYNC_HOME", &home)+ .stdout(Stdio::null())+ .stderr(Stdio::null())+ .spawn()+ .unwrap();+ let mut host = Self { child, home, base: format!("http://127.0.0.1:{port}"), token: String::new() };+ let waited = tokio::time::timeout(Duration::from_secs(20), async {+ loop {+ let response = reqwest::get(format!("{}/health", host.base)).await;+ if response.is_ok() {+ break;+ }+ tokio::time::sleep(Duration::from_millis(50)).await;+ }+ })+ .await;+ waited.unwrap();+ std::fs::read_to_string(host.home.join("token")).unwrap().trim().clone_into(&mut host.token);+ host+ }++ async fn restart(&mut self) {+ common::stop(&mut self.child);+ let port = self.base.rsplit(':').next().unwrap();+ self.child = Command::new(env!("CARGO_BIN_EXE_codync-host"))+ .args(["serve", "--bind", "127.0.0.1", "--port", port])+ .env("CODYNC_CLOUD", "off")+ .env("CODYNC_HOME", &self.home)+ .stdout(Stdio::null())+ .stderr(Stdio::null())+ .spawn()+ .unwrap();+ let waited = tokio::time::timeout(Duration::from_secs(20), async {+ loop {+ let response = reqwest::get(format!("{}/health", self.base)).await;+ if response.is_ok() {+ break;+ }+ tokio::time::sleep(Duration::from_millis(50)).await;+ }+ })+ .await;+ waited.unwrap();+ }++ async fn call(&self, method: &str, body: Value) -> Value {+ let response_result = reqwest::Client::new()+ .post(format!("{}/api/{method}", self.base))+ .bearer_auth(&self.token)+ .json(&body)+ .timeout(Duration::from_secs(10))+ .send()+ .await;+ let response = response_result.unwrap();+ let status = response.status();+ let decoded = response.json().await;+ let value: Value = decoded.unwrap();+ assert!(status.is_success(), "{method}: {value}");+ value+ }+}++async fn ready(host: &Host, bot: &str, expected_files: usize) -> Vec<Value> {+ let waited = tokio::time::timeout(Duration::from_secs(30), async {+ loop {+ let history = host.call("history", json!({"botId": bot})).await;+ let entries = history["entries"].as_array().unwrap();+ let files = entries.iter().filter(|e| e["data"]["files"].is_array()).count();+ if files == expected_files+ && entries.iter().any(|e| e["data"]["text"] == "The files are ready." && e["data"]["final"] == true)+ {+ return entries.clone();+ }+ tokio::time::sleep(Duration::from_millis(50)).await;+ }+ })+ .await;+ waited.unwrap()+}++#[tokio::test]+async fn publishes_all_types_with_final_text_and_survives_restart_workspace_changes_and_threads() {+ use base64::Engine as _;+ let mut host = Host::start().await;+ let cwd = host.home.join("workspace");+ std::fs::create_dir_all(&cwd).unwrap();+ let data = [0, 255, 128, 17].repeat(150_000);+ for (name, bytes) in [+ ("binary.dat", data.clone()),+ (".hidden", vec![13]),+ ("empty", vec![]),+ ("report.pdf", b"%PDF-example".to_vec()),+ ] {+ std::fs::write(cwd.join(name), bytes).unwrap();+ }+ let agent = PathBuf::from(env!("CARGO_MANIFEST_DIR")).join("tests/fixtures/file_agent.py");+ let created = host.call("createBot", json!({"name":"Files", "backend":"custom", "cwd":cwd, "command":common::python_agent(&agent), "connectors":[], "notify":false})).await;+ let bot = created["bot"]["id"].as_str().unwrap();+ let root = host.call("send", json!({"botId":bot,"text":"share-files"})).await;+ let entries = ready(&host, bot, 4).await;+ let file_entry = entries.iter().find(|e| e["data"]["files"][0]["name"] == "binary.dat").unwrap();+ let entry_id = file_entry["id"].as_str().unwrap();+ let file_id = file_entry["data"]["files"][0]["id"].as_str().unwrap();+ std::fs::remove_file(cwd.join("binary.dat")).unwrap();+ host.restart().await;+ let mut received = Vec::new();+ while received.len() < data.len() {+ let response =+ host.call("readFile", json!({"entryId":entry_id,"fileId":file_id,"offset":received.len()})).await;+ assert_eq!(response["size"], data.len());+ let bytes = base64::engine::general_purpose::STANDARD.decode(response["data"].as_str().unwrap()).unwrap();+ received.extend(bytes);+ }+ assert_eq!(received, data);+ let response_result = reqwest::Client::new()+ .post(format!("{}/api/readFile", host.base))+ .json(&json!({"entryId":entry_id,"fileId":file_id,"offset":0}))+ .send()+ .await;+ let response = response_result.unwrap();+ assert_eq!(response.status(), reqwest::StatusCode::UNAUTHORIZED);+ for body in [+ json!({"entryId":root["entry"]["id"],"fileId":file_id,"offset":0}),+ json!({"entryId":entry_id,"fileId":"../escape","offset":0}),+ json!({"entryId":entry_id,"fileId":file_id,"offset":-1}),+ json!({"entryId":entry_id,"fileId":file_id,"offset":data.len()+1}),+ ] {+ let response_result = reqwest::Client::new()+ .post(format!("{}/api/readFile", host.base))+ .bearer_auth(&host.token)+ .json(&body)+ .send()+ .await;+ let response = response_result.unwrap();+ assert!(!response.status().is_success());+ }+ std::fs::write(cwd.join("binary.dat"), &data).unwrap();+ host.call("send", json!({"botId":bot,"text":"share-files resumed"})).await;+ ready(&host, bot, 8).await;+ assert!(cwd.join("resumed").exists());+ host.call("send", json!({"botId":bot,"text":"share-files in a thread", "threadId":root["entry"]["id"]})).await;+ let waited = tokio::time::timeout(Duration::from_secs(30), async {+ loop {+ let response = host.call("thread", json!({"botId":bot,"rootId":root["entry"]["id"]})).await;+ let files: Vec<_> = response["entries"]+ .as_array()+ .unwrap()+ .iter()+ .filter(|e| e["data"]["files"].is_array())+ .cloned()+ .collect();+ if files.len() == 4 {+ let file = &files[0];+ host.call("readFile", json!({"entryId":file["id"],"fileId":file["data"]["files"][0]["id"],"offset":0}))+ .await;+ break;+ }+ tokio::time::sleep(Duration::from_millis(50)).await;+ }+ })+ .await;+ waited.unwrap();+ let mut updated = created["bot"].clone();+ updated["cwd"] = host.home.to_string_lossy().into();+ host.call("updateBot", updated).await;+ host.call("readFile", json!({"entryId":entry_id,"fileId":file_id,"offset":0})).await;+ host.call("deleteBot", json!({"botId":bot})).await;+ let response_result = reqwest::Client::new()+ .post(format!("{}/api/readFile", host.base))+ .bearer_auth(&host.token)+ .json(&json!({"entryId":entry_id,"fileId":file_id,"offset":0}))+ .send()+ .await;+ let response = response_result.unwrap();+ assert!(!response.status().is_success());+}++#[tokio::test]+async fn rejects_invalid_sources_without_a_file_entry() {+ let host = Host::start().await;+ let agent = PathBuf::from(env!("CARGO_MANIFEST_DIR")).join("tests/fixtures/file_agent.py");+ let large = std::fs::File::create(host.home.join("oversized")).unwrap();+ large.set_len(100 * 1024 * 1024 + 1).unwrap();+ let created = host.call("createBot", json!({"name":"Errors", "backend":"custom", "cwd":host.home, "command":common::python_agent(&agent), "connectors":[], "notify":false})).await;+ let bot = created["bot"]["id"].as_str().unwrap();+ host.call("send", json!({"botId":bot,"text":"invalid-files"})).await;+ ready(&host, bot, 0).await;+ let results: Value = serde_json::from_slice(&std::fs::read(host.home.join("file-results.json")).unwrap()).unwrap();+ assert!(results.as_array().unwrap().iter().all(|r| r["isError"] == true));+}++async fn rejected(path: &std::path::Path) {+ let waited = tokio::time::timeout(Duration::from_secs(20), async {+ loop {+ if let Ok(data) = std::fs::read(path) {+ let results: Value = serde_json::from_slice(&data).unwrap();+ assert!(+ results.as_array().unwrap().iter().all(|result| result["isError"] == true+ && result["content"][0]["text"].as_str().unwrap().contains("own chat and threads")),+ "{results}"+ );+ break;+ }+ tokio::time::sleep(Duration::from_millis(50)).await;+ }+ })+ .await;+ waited.unwrap();+}++#[tokio::test]+async fn groups_routines_and_delegated_turns_cannot_publish_files() {+ let host = Host::start().await;+ let agent = PathBuf::from(env!("CARGO_MANIFEST_DIR")).join("tests/fixtures/file_agent.py");+ let created = host.call("createBot", json!({"name":"Recipient", "backend":"custom", "cwd":host.home, "command":common::python_agent(&agent), "connectors":[], "notify":false})).await;+ let bot = created["bot"]["id"].as_str().unwrap();+ let results_path = host.home.join("file-results.json");+ let group = host.call("createBot", json!({"name":"Group", "kind":"group", "members":[bot]})).await;+ host.call("send", json!({"botId":group["bot"]["id"],"text":"share-files"})).await;+ rejected(&results_path).await;+ host.call("stop", json!({"botId":group["bot"]["id"]})).await;+ tokio::time::sleep(Duration::from_millis(300)).await;+ let _ = std::fs::remove_file(&results_path);+ let routine = host+ .call(+ "saveRoutine",+ json!({"botId":bot,"name":"Files","instruction":"share-files","triggers":[{"type":"webhook"}]}),+ )+ .await;+ host.call("runRoutine", json!({"botId":bot,"id":routine["routine"]["id"]})).await;+ rejected(&results_path).await;+ tokio::time::sleep(Duration::from_millis(300)).await;+ std::fs::remove_file(&results_path).unwrap();+ let caller_dir = host.home.join("caller");+ std::fs::create_dir_all(&caller_dir).unwrap();+ let caller_agent = PathBuf::from(env!("CARGO_MANIFEST_DIR")).join("tests/fixtures/team_agent.py");+ let caller = host.call("createBot", json!({"name":"Caller", "backend":"custom", "cwd":caller_dir, "command":common::python_agent(&caller_agent), "connectors":[], "notify":false})).await;+ let caller = caller["bot"]["id"].as_str().unwrap();+ host.call("send", json!({"botId":caller,"text":"warm up"})).await;+ tokio::time::sleep(Duration::from_millis(800)).await;+ host.call("send", json!({"botId":caller,"text":format!("DELEGATE {bot}")})).await;+ rejected(&results_path).await;+ let history = host.call("history", json!({"botId":bot})).await;+ assert!(history["entries"].as_array().unwrap().iter().all(|entry| entry["data"]["files"].is_null()));+}++#[tokio::test]+async fn files_only_turns_finish_without_duplicate_text_and_input_uploads_still_work() {+ use base64::Engine as _;+ let host = Host::start().await;+ let agent = PathBuf::from(env!("CARGO_MANIFEST_DIR")).join("tests/fixtures/file_agent.py");+ for name in ["binary.dat", ".hidden", "empty", "report.pdf"] {+ std::fs::write(host.home.join(name), []).unwrap();+ }+ let created = host.call("createBot", json!({"name":"Files only", "backend":"custom", "cwd":host.home, "command":common::python_agent(&agent), "connectors":[], "notify":false})).await;+ let bot = created["bot"]["id"].as_str().unwrap();+ let upload_id = uuid::Uuid::new_v4().to_string();+ host.call(+ "upload",+ json!({"botId":bot,"uploadId":upload_id,"name":"input.txt","offset":0,"data":"aGVsbG8=","done":true}),+ )+ .await;+ let sent = host.call("send", json!({"botId":bot,"text":"files-only","attachments":[upload_id]})).await;+ assert_eq!(sent["entry"]["data"]["attachments"][0]["id"], upload_id);+ let response = host.call("readUpload", json!({"botId":bot,"uploadId":upload_id,"offset":0})).await;+ assert_eq!(base64::engine::general_purpose::STANDARD.decode(response["data"].as_str().unwrap()).unwrap(), b"hello");+ let waited = tokio::time::timeout(Duration::from_secs(20), async {+ loop {+ let history = host.call("history", json!({"botId":bot})).await;+ let final_entries: Vec<_> = history["entries"]+ .as_array()+ .unwrap()+ .iter()+ .filter(|e| e["kind"] == "agent" && e["data"]["final"] == true)+ .collect();+ let sync = host.call("sync", json!({"since":0})).await;+ if final_entries.len() == 4+ && sync["bots"].as_array().unwrap().iter().any(|b| b["id"] == bot && b["status"] == "idle")+ {+ assert!(final_entries.iter().all(|e| e["data"]["files"].is_array()));+ break;+ }+ tokio::time::sleep(Duration::from_millis(50)).await;+ }+ })+ .await;+ waited.unwrap();+}diff --git a/host/tests/fixtures/file_agent.py b/host/tests/fixtures/file_agent.pynew file mode 100644index 00000000..39b4fec1--- /dev/null+++ b/host/tests/fixtures/file_agent.py@@ -0,0 +1,57 @@+"""ACP fixture using the real built-in stdio chat MCP, including resumed sessions."""+import json+import os+import subprocess+import sys+from pathlib import Path++sessions = {}++def send(value):+ print(json.dumps(value), flush=True)++def prompt(message):+ params = message['params']+ session = sessions[params['sessionId']]+ tool = next(server for server in session['mcpServers'] if server['name'] == 'chat')+ with subprocess.Popen([tool['command'], *tool['args']], stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.DEVNULL, text=True, env=os.environ.copy()) as mcp:+ sequence = 0+ def request(method, arguments):+ nonlocal sequence+ sequence += 1+ mcp.stdin.write(json.dumps({'jsonrpc':'2.0', 'id':sequence, 'method':method, 'params':arguments}) + '\n')+ mcp.stdin.flush()+ return json.loads(mcp.stdout.readline())['result']+ request('initialize', {'protocolVersion':'2025-06-18', 'capabilities':{}, 'clientInfo':{'name':'file-test','version':'1'}})+ tools = request('tools/list', {})['tools']+ assert any(tool['name'] == 'send_file' for tool in tools)+ text = params['prompt'][0]['text']+ results = []+ if 'invalid-files' in text:+ for path in ['missing', '.', 'oversized']:+ results.append(request('tools/call', {'name':'send_file', 'arguments':{'path':path}}))+ else:+ paths = ['binary.dat', '.hidden', 'empty', 'report.pdf']+ for path in paths:+ results.append(request('tools/call', {'name':'send_file', 'arguments':{'path':path}}))+ Path(session['cwd'], 'file-results.json').write_text(json.dumps(results))+ mcp.stdin.close()+ if 'files-only' not in text:+ send({'jsonrpc':'2.0','method':'session/update','params':{'sessionId':params['sessionId'],'update':{'sessionUpdate':'agent_message_chunk','content':{'type':'text','text':'The files are ready.'}}}})+ return {'stopReason':'end_turn'}++for line in sys.stdin:+ message = json.loads(line)+ method = message.get('method')+ if method == 'initialize':+ result = {'protocolVersion':1,'agentCapabilities':{'loadSession':True}}+ elif method in ['session/new', 'session/load']:+ session_id = message['params'].get('sessionId', 'file-test-' + str(len(sessions)))+ sessions[session_id] = message['params']+ if method == 'session/load': Path(message['params']['cwd'], 'resumed').touch()+ result = {'sessionId':session_id}+ elif method == 'session/prompt':+ result = prompt(message)+ else:+ continue+ send({'jsonrpc':'2.0','id':message['id'],'result':result})