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(chat): show images a bot sends in the chat
leepokai1a5a9b1ae3ba
diff --git a/apps/android/app/src/main/kotlin/com/codync/android/AppStoreDrafts.kt b/apps/android/app/src/main/kotlin/com/codync/android/AppStoreDrafts.ktindex 8312a8d8..d5ed776c 100644--- a/apps/android/app/src/main/kotlin/com/codync/android/AppStoreDrafts.kt+++ b/apps/android/app/src/main/kotlin/com/codync/android/AppStoreDrafts.kt@@ -94,12 +94,22 @@ fun AppStore.importFiles(uris: List<Uri>, onImported: (List<OutgoingFile>) -> Un}fun AppStore.removeFile(file: OutgoingFile) = action("remove:" + file.path) { withContext(Dispatchers.IO) { attachments.discard(file) } }-suspend fun AppStore.attachment(botId: String, file: Attachment): File {- val request = contextScope.async { downloadLocks.getOrPut(file.id) { Mutex() }.withLock {- val destination = withContext(Dispatchers.IO) { attachments.cached(file.id) }- if (!destination.exists() || destination.length() != file.size) {- val active = ready()- HostFiles(active).download(botId, file, destination)+suspend fun AppStore.attachment(botId: String, file: Attachment): File =+ cachedFile(file.id, file.size) { files, destination -> files.download(botId, file, destination) }++/** A picture a bot shared (iOS `sharedFileData`): checked against its SHA-256 on its way into the same cache. */+suspend fun AppStore.sharedImage(entryId: String, file: SharedFile): File = cachedFile(file.id, file.size) { files, destination ->+ val folder = withContext(Dispatchers.IO) { attachments.shareFolder() }+ val saved = files.downloadShared(entryId, file, folder)+ withContext(Dispatchers.IO) { try { saved.copyTo(destination, overwrite = true) } finally { folder.deleteRecursively() } }+}++/** A file from the computer, fetched once into the attachment cache by `fetch`. */+private suspend fun AppStore.cachedFile(id: String, size: Long, fetch: suspend (HostFiles, File) -> Unit): File {+ val request = contextScope.async { downloadLocks.getOrPut(id) { Mutex() }.withLock {+ val destination = withContext(Dispatchers.IO) { attachments.cached(id) }+ if (!destination.exists() || destination.length() != size) {+ fetch(HostFiles(ready()), destination)withContext(Dispatchers.IO) { attachments.trim() }}destinationdiff --git a/apps/android/app/src/main/kotlin/com/codync/android/AttachmentList.kt b/apps/android/app/src/main/kotlin/com/codync/android/AttachmentList.ktindex 6dfc6c37..73717a85 100644--- a/apps/android/app/src/main/kotlin/com/codync/android/AttachmentList.kt+++ b/apps/android/app/src/main/kotlin/com/codync/android/AttachmentList.kt@@ -49,12 +49,20 @@ import kotlinx.coroutines.withContext/** A sent image full size, in a sheet while `file` is set. */@Composable internal fun AttachmentImageSheet(file: Attachment?, botId: String, state: AppState, store: AppStore, dismiss: () -> Unit) {- CodyncSheet(file, dismiss) { shown ->+ ImageSheet(file, { it.name }, dismiss) { shown, modifier -> AttachmentImage(shown, botId, 4096, state, store, modifier) }+}++/** An image a bot shared full size, in a sheet while `file` is set. */+@Composable internal fun SharedImageSheet(file: SharedFile?, entryId: String, state: AppState, store: AppStore, dismiss: () -> Unit) {+ ImageSheet(file, { it.name }, dismiss) { shown, modifier -> SharedImage(shown, entryId, 4096, state, store, modifier) }+}++/** A picture full size (iOS `AttachmentViewer`), in a sheet while `item` is set. */+@Composable private fun <T : Any> ImageSheet(item: T?, name: (T) -> String, dismiss: () -> Unit, image: @Composable (T, Modifier) -> Unit) {+ CodyncSheet(item, dismiss) { shown ->Column(Modifier.fillMaxSize().background(Palette.background)) {- ModalHeader(shown.name)- Box(Modifier.weight(1f).padding(12.dp), contentAlignment = Alignment.Center) {- AttachmentImage(shown, botId, 4096, state, store, Modifier.fillMaxSize())- }+ ModalHeader(name(shown))+ Box(Modifier.weight(1f).padding(12.dp), contentAlignment = Alignment.Center) { image(shown, Modifier.fillMaxSize()) }}}}@@ -72,13 +80,20 @@ import kotlinx.coroutines.withContext/** A sent image, fetched from the computer once and then read from the cache; a placeholder until then. */@Composable internal fun AttachmentImage(file: Attachment, botId: String, maxPixels: Int, state: AppState, store: AppStore, modifier: Modifier,- scale: ContentScale = ContentScale.Fit) {- var image by remember(file.id, maxPixels) { mutableStateOf<ImageBitmap?>(null) }+ scale: ContentScale = ContentScale.Fit) = RemoteImage(file.id, maxPixels, state, modifier, scale) { store.attachment(botId, file) }++/** An image a bot shared, like `AttachmentImage`. */+@Composable internal fun SharedImage(file: SharedFile, entryId: String, maxPixels: Int, state: AppState, store: AppStore, modifier: Modifier) =+ RemoteImage(file.id, maxPixels, state, modifier, ContentScale.Fit) { store.sharedImage(entryId, file) }++/** A picture `load` fetches from the computer into the cache (iOS `AttachmentImage`); a placeholder until then. */+@Composable private fun RemoteImage(id: String, maxPixels: Int, state: AppState, modifier: Modifier, scale: ContentScale, load: suspend () -> java.io.File) {+ var image by remember(id, maxPixels) { mutableStateOf<ImageBitmap?>(null) }// Retried whenever the link changes: an image the computer couldn't send stays a placeholder, as on iOS.- LaunchedEffect(file.id, maxPixels, state.actualConnection) {+ LaunchedEffect(id, maxPixels, state.actualConnection) {if (image != null) return@LaunchedEffecttry {- val source = store.attachment(botId, file)+ val source = load()image = withContext(Dispatchers.IO) { AttachmentFiles.thumbnail(source, maxPixels).asImageBitmap() }} catch (cancelled: CancellationException) { throw cancelled }catch (_: Exception) { /* The placeholder stays; the next link change tries again. */ }diff --git a/apps/android/app/src/main/kotlin/com/codync/android/FileDownloadCard.kt b/apps/android/app/src/main/kotlin/com/codync/android/FileDownloadCard.ktindex 949f185e..831f74c2 100644--- a/apps/android/app/src/main/kotlin/com/codync/android/FileDownloadCard.kt+++ b/apps/android/app/src/main/kotlin/com/codync/android/FileDownloadCard.kt@@ -8,8 +8,13 @@ import androidx.compose.foundation.layout.Rowimport androidx.compose.foundation.layout.fillMaxWidthimport androidx.compose.foundation.layout.paddingimport androidx.compose.foundation.layout.size+import androidx.compose.foundation.layout.sizeInimport androidx.compose.material3.Textimport androidx.compose.runtime.Composable+import androidx.compose.runtime.getValue+import androidx.compose.runtime.mutableStateOf+import androidx.compose.runtime.remember+import androidx.compose.runtime.setValueimport androidx.compose.ui.Alignmentimport androidx.compose.ui.Modifierimport androidx.compose.ui.draw.clip@@ -22,12 +27,23 @@ import com.codync.android.core.SharedFileimport com.codync.android.design.*import com.kyant.shapes.RoundedRectangle-/** A file a bot shared, as iOS `FileDownloadCard`: its name and size, and a button to download (or cancel). */+/** A file a bot shared, as iOS `FileDownloadCard`: an image shows itself (tap for full size), then its name and size, and a+ * button to download (or cancel). */@Composable internal fun FileDownloadCard(entry: Entry, file: SharedFile, state: AppState, store: AppStore) {+ var viewing by remember { mutableStateOf(false) }+ Column(Modifier.fillMaxWidth().clip(RoundedRectangle(16.dp)).background(Palette.bubbleAgent).padding(14.dp),+ verticalArrangement = Arrangement.spacedBy(12.dp)) {+ if (file.showsAsImage) SharedImage(file, entry.id, 720, state, store, Modifier.sizeIn(maxHeight = 280.dp)+ .clip(RoundedRectangle(10.dp)).plainButton { viewing = true }.semantics { contentDescription = file.name })+ FileRow(entry, file, state, store)+ }+ SharedImageSheet(file.takeIf { viewing }, entry.id, state, store) { viewing = false }+}++@Composable private fun FileRow(entry: Entry, file: SharedFile, state: AppState, store: AppStore) {val download = state.fileDownloads[file.id]val busy = download is FileDownloadState.Downloading- Row(Modifier.fillMaxWidth().clip(RoundedRectangle(16.dp)).background(Palette.bubbleAgent).padding(14.dp),- verticalAlignment = Alignment.CenterVertically, horizontalArrangement = Arrangement.spacedBy(12.dp)) {+ Row(Modifier.fillMaxWidth(), verticalAlignment = Alignment.CenterVertically, horizontalArrangement = Arrangement.spacedBy(12.dp)) {Symbol(AttachmentIcon.symbol(file.name), size = 24.dp, tint = Palette.secondary)Column(Modifier.weight(1f), verticalArrangement = Arrangement.spacedBy(3.dp)) {Text(file.name, style = Type.subheadline.semibold, color = Palette.text, maxLines = 2, overflow = TextOverflow.Ellipsis)diff --git a/apps/android/core/src/main/kotlin/com/codync/android/core/Conversation.kt b/apps/android/core/src/main/kotlin/com/codync/android/core/Conversation.ktindex 02ed57b7..38523d66 100644--- a/apps/android/core/src/main/kotlin/com/codync/android/core/Conversation.kt+++ b/apps/android/core/src/main/kotlin/com/codync/android/core/Conversation.kt@@ -98,11 +98,16 @@ private data class EntryFields(@Serializable data class ReplyQuote(val id: String = "", val author: String = "", val text: String = "", val artifact: String? = null)@Serializable data class Attachment(val id: String, val name: String, val size: Long) {- val isImage: Boolean get() = name.substringAfterLast('.', "").lowercase() in listOf("png", "jpg", "jpeg", "heic", "gif", "webp", "tiff", "bmp")+ val isImage: Boolean get() = isImageName(name)}+private fun isImageName(name: String) = name.substringAfterLast('.', "").lowercase() in listOf("png", "jpg", "jpeg", "heic", "gif", "webp", "tiff", "bmp")+/** A file a bot shared: immutable on the computer, checked against its SHA-256 once downloaded. */@Serializable data class SharedFile(val id: String, val name: String, val size: Long, val sha256: String) {+ /** An image small enough to show in the chat (the phone fetches all of it). */+ val showsAsImage: Boolean get() = isImageName(name) && size <= 20L * 1024 * 1024+/** Before any of it is read: a name that can't leave its folder and a hash to check. */fun validate() {require(size in 0..MAX_FILE_BYTES && sha256.length == 64 && sha256.all { it in "0123456789abcdef" } &&diff --git a/apps/desktop/src/renderer/store/bot-store.ts b/apps/desktop/src/renderer/store/bot-store.tsindex 7a68b1ad..d7284874 100644--- a/apps/desktop/src/renderer/store/bot-store.ts+++ b/apps/desktop/src/renderer/store/bot-store.ts@@ -10,10 +10,12 @@ import {type Hello,type ReplyQuote,type ScreenState,+ type SharedFile,type Usage,} from '@shared/models'import type { CallLine } from '@shared/calls'import type { HostClient } from '../client/host-client'+import { readSharedFile } from '../../shared/files.ts'import { FileDownloads } from './file-downloads'import { BotSync, sleep } from './bot-sync'@@ -121,14 +123,23 @@ export class BotStore extends BotSync {}/** A sent file's bytes: cached after the first fetch (sent files never change). */- async attachmentData(fileId: string, botId: string): Promise<Uint8Array | null> {- const cached = attachmentCache.get(fileId)+ attachmentData(fileId: string, botId: string): Promise<Uint8Array | null> {+ return this.cachedFile(fileId, (client) => client.readUpload(botId, fileId))+ }++ /** A file a bot shared, read whole and checked: cached after the first fetch (shared files never change). */+ sharedFileData(file: SharedFile, entryId: string): Promise<Uint8Array | null> {+ return this.cachedFile(file.id, (client) => readSharedFile(file, (offset) => client.readFile(entryId, file.id, offset)))+ }++ private async cachedFile(id: string, fetch: (client: HostClient) => Promise<Uint8Array>): Promise<Uint8Array | null> {+ const cached = attachmentCache.get(id)if (cached) return cachedconst client = this.liveif (!client) return nulltry {- const data = await client.readUpload(botId, fileId)- cacheAttachment(fileId, data)+ const data = await fetch(client)+ cacheAttachment(id, data)return data} catch {return nulldiff --git a/apps/desktop/src/renderer/views/library/LibraryView.tsx b/apps/desktop/src/renderer/views/library/LibraryView.tsxindex 0c118bac..aca8da98 100644--- a/apps/desktop/src/renderer/views/library/LibraryView.tsx+++ b/apps/desktop/src/renderer/views/library/LibraryView.tsx@@ -62,7 +62,7 @@ export function LibraryView({ botId, openArtifact }: { botId: string; openArtifa</section>)))}- <AttachmentViewer file={viewing} botId={botId} close={() => setViewing(null)} />+ <AttachmentViewer source={viewing && { file: viewing, botId }} close={() => setViewing(null)} /></VStack>)}@@ -146,7 +146,7 @@ function AttachmentRow({ botId, file, view }: { botId: string; file: Attachment;)}return (- <Row leading={<AttachmentImage file={file} botId={botId} fit="icon" />}>+ <Row leading={<AttachmentImage source={{ file, botId }} fit="icon" />}><button className="library-row-open" onClick={view}><Name name={file.name} detail={byteCount(file.size)} /></button>diff --git a/apps/desktop/src/renderer/views/thread/Attachments.tsx b/apps/desktop/src/renderer/views/thread/Attachments.tsxindex c2fd65f0..d07145e7 100644--- a/apps/desktop/src/renderer/views/thread/Attachments.tsx+++ b/apps/desktop/src/renderer/views/thread/Attachments.tsx@@ -1,5 +1,5 @@import { useEffect, useState } from 'react'-import { isImageName, type Attachment } from '@shared/models'+import { isImageName, type Attachment, type SharedFile } from '@shared/models'import { Icon } from '../../components/Icon'import { ModalHeader, Sheet, SheetPage } from '../../components/Overlay'import { HStack, VStack } from '../../components/Stack'@@ -38,7 +38,7 @@ export function AttachmentList({ attachments, botId }: { attachments: Attachment{attachments.map((file) =>isImageName(file.name) ? (<button key={file.id} className="attachment-image-button" aria-label={file.name} onClick={() => setViewing(file)}>- <AttachmentImage file={file} botId={botId} fit="thumbnail" />+ <AttachmentImage source={{ file, botId }} fit="thumbnail" /></button>) : (<HStack key={file.id} gap={8} className="attachment-file">@@ -50,20 +50,23 @@ export function AttachmentList({ attachments, botId }: { attachments: Attachment</HStack>),)}- <AttachmentViewer file={viewing} botId={botId} close={() => setViewing(null)} />+ <AttachmentViewer source={viewing && { file: viewing, botId }} close={() => setViewing(null)} /></VStack>)}-/** A sent image full size, in a sheet. */-export function AttachmentViewer({ file, botId, close }: { file: Attachment | null; botId: string; close: () => void }) {+/** Where a picture's bytes are on the computer: a file sent with a message, or one a bot shared. */+export type ImageSource = { file: Attachment; botId: string } | { file: SharedFile; entryId: string }++/** A picture full size, in a sheet. */+export function AttachmentViewer({ source, close }: { source: ImageSource | null; close: () => void }) {return (- <Sheet open={file !== null} onClose={close} width={720} height={560}>- {file ? (+ <Sheet open={source !== null} onClose={close} width={720} height={560}>+ {source ? (<SheetPage>- <ModalHeader title={file.name} />+ <ModalHeader title={source.file.name} /><div className="attachment-viewer">- <AttachmentImage file={file} botId={botId} fit="full" />+ <AttachmentImage source={source} fit="full" /></div></SheetPage>) : null}@@ -71,14 +74,15 @@ export function AttachmentViewer({ file, botId, close }: { file: Attachment | nu)}-/** A sent image, fetched from the computer once and then read from the cache. */-export function AttachmentImage({ file, botId, fit }: { file: Attachment; botId: string; fit: 'icon' | 'thumbnail' | 'full' }) {+/** A picture from the computer, fetched once and then read from the cache. */+export function AttachmentImage({ source, fit }: { source: ImageSource; fit: 'icon' | 'thumbnail' | 'full' }) {const store = useStoreRef()const [url, setUrl] = useState<string | null>(null)useEffect(() => {let revoked = falselet made: string | null = null- void store.attachmentData(file.id, botId).then((data) => {+ const data = 'entryId' in source ? store.sharedFileData(source.file, source.entryId) : store.attachmentData(source.file.id, source.botId)+ void data.then((data) => {if (!data || revoked) returnmade = URL.createObjectURL(new Blob([data as BlobPart]))setUrl(made)@@ -87,7 +91,8 @@ export function AttachmentImage({ file, botId, fit }: { file: Attachment; botId:revoked = trueif (made) URL.revokeObjectURL(made)}- }, [store, file.id, botId])+ // A file's id names its bytes for good; `source` is a new object every render.+ }, [store, source.file.id])if (!url) {return (<div className={`attachment-placeholder ${fit}`}>diff --git a/apps/desktop/src/renderer/views/thread/FileDownloadCard.tsx b/apps/desktop/src/renderer/views/thread/FileDownloadCard.tsxindex 88a23bbc..7ee0bf7c 100644--- a/apps/desktop/src/renderer/views/thread/FileDownloadCard.tsx+++ b/apps/desktop/src/renderer/views/thread/FileDownloadCard.tsx@@ -1,11 +1,12 @@-import type { Entry, SharedFile } from '@shared/models'+import { useState } from 'react'+import { showsAsImage, type Entry, type SharedFile } from '@shared/models'import { useStore } from '../../store/context'import type { DownloadState } from '../../store/file-downloads'import { Icon } from '../../components/Icon'import { IconButtonBase } from '../../components/Overlay'import { HStack, VStack } from '../../components/Stack'import { Text } from '../../components/Text'-import { attachmentSymbol, byteCount } from './Attachments'+import { AttachmentImage, AttachmentViewer, attachmentSymbol, byteCount, type ImageSource } from './Attachments'import './attachments.css'/** What the download button does now (also the Library's file rows). */@@ -28,12 +29,22 @@ export function FileDownloadCard({ entry, file }: { entry: Entry; file: SharedFiconst state = store.fileDownloads.states.get(file.id)const busy = state?.kind === 'downloading'const [action, detail] = [downloadAction(state), downloadDetail(state, file)]- return <HStack gap={12} className="file-card">- <Icon name={attachmentSymbol(file.name)} size={24} color="var(--secondary)" />- <VStack grow>- <Text as="div" size="subheadline" weight="semibold" truncate title={file.name}>{file.name}</Text>- <Text as="div" size="caption2" tone={state?.kind === 'failed' ? 'danger' : 'secondary'} role={state?.kind === 'failed' ? 'alert' : 'status'} className="file-card-detail">{detail}</Text>- </VStack>- <IconButtonBase title={action} icon={busy ? 'xmark' : 'arrow.down.to.line'} size={36} onClick={() => busy ? store.fileDownloads.cancel(file.id) : void store.fileDownloads.save(store.client, entry.id, file)} />- </HStack>+ const [viewing, setViewing] = useState(false)+ const image: ImageSource = { file, entryId: entry.id }+ return <VStack gap={12} className="file-card">+ {showsAsImage(file) ? <>+ <button className="file-card-image" aria-label={file.name} onClick={() => setViewing(true)}>+ <AttachmentImage source={image} fit="thumbnail" />+ </button>+ <AttachmentViewer source={viewing ? image : null} close={() => setViewing(false)} />+ </> : null}+ <HStack gap={12}>+ <Icon name={attachmentSymbol(file.name)} size={24} color="var(--secondary)" />+ <VStack grow>+ <Text as="div" size="subheadline" weight="semibold" truncate title={file.name}>{file.name}</Text>+ <Text as="div" size="caption2" tone={state?.kind === 'failed' ? 'danger' : 'secondary'} role={state?.kind === 'failed' ? 'alert' : 'status'} className="file-card-detail">{detail}</Text>+ </VStack>+ <IconButtonBase title={action} icon={busy ? 'xmark' : 'arrow.down.to.line'} size={36} onClick={() => busy ? store.fileDownloads.cancel(file.id) : void store.fileDownloads.save(store.client, entry.id, file)} />+ </HStack>+ </VStack>}diff --git a/apps/desktop/src/renderer/views/thread/attachments.css b/apps/desktop/src/renderer/views/thread/attachments.cssindex adacac34..ccb70537 100644--- a/apps/desktop/src/renderer/views/thread/attachments.css+++ b/apps/desktop/src/renderer/views/thread/attachments.css@@ -55,6 +55,12 @@border-radius: var(--radius-l);max-width: 380px;}+.file-card-image {+ display: flex;+ align-self: flex-start;+ border-radius: var(--radius-m);+ overflow: hidden;+}.file-card-detail {overflow-wrap: anywhere;}diff --git a/apps/desktop/src/shared/artifacts.ts b/apps/desktop/src/shared/artifacts.tsindex 9fc188a9..192b0089 100644--- a/apps/desktop/src/shared/artifacts.ts+++ b/apps/desktop/src/shared/artifacts.ts@@ -1,7 +1,7 @@// Artifacts and the Library on the wire (`host/src/chat/artifacts.rs`, `host/src/chat/library.rs`).import type { Attachment, ReplyQuote, SharedFile } from './models'import { isBelow } from './compat.ts'-import { decodeFileChunk } from './files.ts'+import { decodeFileChunk, sha256Hex } from './files.ts'/** An HTML artifact a bot published; `readArtifact` returns its HTML. */export interface Artifact {@@ -95,8 +95,3 @@ export async function readArtifactHTML(read: (offset: number) => Promise<Artifacreturn { artifact, bytes: html }}}--async function sha256Hex(bytes: Uint8Array<ArrayBuffer>): Promise<string> {- const digest = new Uint8Array(await crypto.subtle.digest('SHA-256', bytes))- return Array.from(digest, (b) => b.toString(16).padStart(2, '0')).join('')-}diff --git a/apps/desktop/src/shared/files.test.ts b/apps/desktop/src/shared/files.test.tsindex 747338dc..b5322770 100644--- a/apps/desktop/src/shared/files.test.ts+++ b/apps/desktop/src/shared/files.test.ts@@ -5,7 +5,7 @@ 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'+import { decodeFileChunk, FILE_CHUNK_SIZE, readSharedFile, 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-'))@@ -91,3 +91,11 @@ test('cancelling an outstanding chunk cannot write or commit a late response', aassert.equal(commits, 0)assert.equal(downloads.states.has('id'), false)})++test('a shared file read whole is checked against its digest', async () => {+ const data = Buffer.alloc(FILE_CHUNK_SIZE + 5, 7)+ const file = { id: 'id', name: 'picture.png', size: data.length, sha256: createHash('sha256').update(data).digest('hex') }+ const read = async (offset: number) => ({ data: data.subarray(offset, offset + FILE_CHUNK_SIZE).toString('base64'), size: data.length })+ assert.deepEqual(Buffer.from(await readSharedFile(file, read)), data)+ await assert.rejects(readSharedFile({ ...file, sha256: '0'.repeat(64) }, read), /integrity/)+})diff --git a/apps/desktop/src/shared/files.ts b/apps/desktop/src/shared/files.tsindex 781ab53f..f1f0154f 100644--- a/apps/desktop/src/shared/files.ts+++ b/apps/desktop/src/shared/files.ts@@ -14,6 +14,25 @@ export function saveName(name: string) {return portable && !/^(con|prn|aux|nul|com[1-9]|lpt[1-9])(\.|$)/i.test(portable) ? portable : `file-${portable || 'download'}`}+/** A shared file's whole bytes, read chunk by chunk with `read(offset)` and checked against its SHA-256. */+export async function readSharedFile(file: SharedFile, read: (offset: number) => Promise<{ data: string; size: number }>): Promise<Uint8Array> {+ validateSharedFile(file)+ const bytes = new Uint8Array(file.size)+ let offset = 0+ do {+ const chunk = decodeFileChunk(await read(offset), file.size, offset)+ bytes.set(chunk, offset)+ offset += chunk.length+ } while (offset < file.size)+ if ((await sha256Hex(bytes)) !== file.sha256) throw new Error('The file failed its integrity check')+ return bytes+}++export async function sha256Hex(bytes: Uint8Array<ArrayBuffer>): Promise<string> {+ const digest = new Uint8Array(await crypto.subtle.digest('SHA-256', bytes))+ return Array.from(digest, (b) => b.toString(16).padStart(2, '0')).join('')+}+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))diff --git a/apps/desktop/src/shared/models.ts b/apps/desktop/src/shared/models.tsindex b584cda7..fb60ac15 100644--- a/apps/desktop/src/shared/models.ts+++ b/apps/desktop/src/shared/models.ts@@ -223,6 +223,9 @@ 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() ?? '')+/** A shared image small enough to show in the chat (the whole file is fetched for it). */+export const showsAsImage = (file: SharedFile) => isImageName(file.name) && file.size <= 20 * 1024 * 1024+export interface ConnectionRequest {[key: string]: unknown}diff --git a/apps/ios/Kit/Sources/CodyncKit/Client/FileDownload.swift b/apps/ios/Kit/Sources/CodyncKit/Client/FileDownload.swiftindex dde1f0f4..3d7451ee 100644--- a/apps/ios/Kit/Sources/CodyncKit/Client/FileDownload.swift+++ b/apps/ios/Kit/Sources/CodyncKit/Client/FileDownload.swift@@ -41,6 +41,33 @@ public actor FileDownload {guard FileManager.default.createFile(atPath: partial.path, contents: nil) else { throw CocoaError(.fileWriteUnknown) }let handle = try FileHandle(forWritingTo: partial)defer { try? handle.close() }+ try await read(client: client, entryId: entryId, file: file) { bytes, offset in+ try handle.write(contentsOf: bytes)+ await progress(offset)+ }+ 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+ }++ /// The whole file in memory, checked like a saved one (pictures shown in the chat).+ public func data(client: HostClient, entryId: String, file: SharedFile) async throws -> Data {+ try file.validate()+ var data = Data(capacity: Int(file.size))+ try await read(client: client, entryId: entryId, file: file) { bytes, _ in data.append(bytes) }+ return data+ }++ /// Hands each chunk of `file` to `each` (with the bytes read so far); throws unless they add up to its size and digest.+ private func read(client: HostClient, entryId: String, file: SharedFile,+ each: (Data, Int64) async throws -> Void) async throws {var offset: Int64 = 0var hash = SHA256()repeat {@@ -50,23 +77,12 @@ public actor FileDownload {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)+ try await each(bytes, offset)} while offset < file.sizelet 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 {diff --git a/apps/ios/Kit/Sources/CodyncKit/Models/EntryData.swift b/apps/ios/Kit/Sources/CodyncKit/Models/EntryData.swiftindex c98667ca..e1e507df 100644--- a/apps/ios/Kit/Sources/CodyncKit/Models/EntryData.swift+++ b/apps/ios/Kit/Sources/CodyncKit/Models/EntryData.swift@@ -150,7 +150,9 @@ public struct Attachment: Codable, Hashable, Sendable, Identifiable {self.size = size}- public var isImage: Bool {+ public var isImage: Bool { Self.isImage(name) }++ public static func isImage(_ name: String) -> Bool {["png", "jpg", "jpeg", "heic", "gif", "webp", "tiff", "bmp"].contains((name as NSString).pathExtension.lowercased())}}diff --git a/apps/ios/Kit/Sources/CodyncKit/Models/SharedFile.swift b/apps/ios/Kit/Sources/CodyncKit/Models/SharedFile.swiftindex 16a49ced..a78cdbed 100644--- a/apps/ios/Kit/Sources/CodyncKit/Models/SharedFile.swift+++ b/apps/ios/Kit/Sources/CodyncKit/Models/SharedFile.swift@@ -14,6 +14,9 @@ public struct SharedFile: Codable, Hashable, Sendable, Identifiable {self.sha256 = sha256}+ /// An image small enough to show in the chat (the phone fetches all of it).+ public var showsAsImage: Bool { Attachment.isImage(name) && size <= 20 * 1024 * 1024 }+public func validate() throws {guard size >= 0, size <= 100 * 1024 * 1024,sha256.count == 64, sha256.allSatisfy({ "0123456789abcdef".contains($0) }),diff --git a/apps/ios/Kit/Sources/CodyncUI/Store/BotStore+Sending.swift b/apps/ios/Kit/Sources/CodyncUI/Store/BotStore+Sending.swiftindex 82a185e5..924992cd 100644--- a/apps/ios/Kit/Sources/CodyncUI/Store/BotStore+Sending.swift+++ b/apps/ios/Kit/Sources/CodyncUI/Store/BotStore+Sending.swift@@ -251,6 +251,15 @@ extension BotStore {return data}+ /// A file a bot shared, read whole and checked: on disk after the first fetch (shared files never change).+ public func sharedFileData(_ file: SharedFile, entryId: String) async -> Data? {+ guard let url = Self.attachmentCache(file.id) else { return nil }+ if let data = try? Data(contentsOf: url) { return data }+ guard let client = live, let data = try? await FileDownload().data(client: client, entryId: entryId, file: file) else { return nil }+ Self.cacheAttachment(file.id, data)+ return data+ }+private static func attachmentCache(_ id: String) -> URL? {guard let uuid = UUID(uuidString: id) else { return nil }return URL.cachesDirectory.appending(path: "codync-attachments").appending(path: uuid.uuidString)diff --git a/apps/ios/Kit/Sources/CodyncUI/Thread/Attachments.swift b/apps/ios/Kit/Sources/CodyncUI/Thread/Attachments.swiftindex 139f2570..df104856 100644--- a/apps/ios/Kit/Sources/CodyncUI/Thread/Attachments.swift+++ b/apps/ios/Kit/Sources/CodyncUI/Thread/Attachments.swift@@ -137,15 +137,25 @@ struct AttachmentList: View {}}-/// A sent image full size.+/// A picture full size: a sent image or one a bot shared.struct AttachmentViewer: View {- let file: Attachment- let botId: String+ let name: String+ let image: AttachmentImage++ init(file: Attachment, botId: String) {+ name = file.name+ image = AttachmentImage(file: file, botId: botId, maxPixels: 4096)+ }++ init(shared file: SharedFile, entryId: String) {+ name = file.name+ image = AttachmentImage(shared: file, entryId: entryId, maxPixels: 4096)+ }var body: some View {VStack(spacing: 0) {- ModalHeader(file.name)- AttachmentImage(file: file, botId: botId, maxPixels: 4096)+ ModalHeader(name)+ image.frame(maxWidth: .infinity, maxHeight: .infinity).padding(12)}@@ -153,15 +163,28 @@ struct AttachmentViewer: View {}}-/// A sent image, fetched from the computer once and then read from the cache.+/// A picture from the computer (a sent image or one a bot shared), fetched once and then read from the cache.struct AttachmentImage: View {- let file: Attachment- let botId: String+ let id: Stringlet maxPixels: Intvar contentMode: ContentMode = .fit+ let load: @MainActor (BotStore) async -> Data?@Environment(BotStore.self) private var model@State private var image: CGImage?+ init(file: Attachment, botId: String, maxPixels: Int, contentMode: ContentMode = .fit) {+ id = file.id+ self.maxPixels = maxPixels+ self.contentMode = contentMode+ load = { await $0.attachmentData(file, bot: botId) }+ }++ init(shared file: SharedFile, entryId: String, maxPixels: Int) {+ id = file.id+ self.maxPixels = maxPixels+ load = { await $0.sharedFileData(file, entryId: entryId) }+ }+var body: some View {Group {if let image {@@ -173,8 +196,8 @@ struct AttachmentImage: View {.overlay { Image(systemName: "photo").foregroundStyle(Palette.tertiary) }}}- .task(id: file.id) {- guard let data = await model.attachmentData(file, bot: botId) else { return }+ .task(id: id) {+ guard let data = await load(model) else { return }let size = maxPixelsimage = await Task.detached { ImageData.thumbnail(data, maxPixels: size) }.value}diff --git a/apps/ios/Kit/Sources/CodyncUI/Thread/FileDownloadCard.swift b/apps/ios/Kit/Sources/CodyncUI/Thread/FileDownloadCard.swiftindex dbac0f2b..ec40fa31 100644--- a/apps/ios/Kit/Sources/CodyncUI/Thread/FileDownloadCard.swift+++ b/apps/ios/Kit/Sources/CodyncUI/Thread/FileDownloadCard.swift@@ -6,10 +6,32 @@ struct FileDownloadCard: View {let entry: Entrylet file: SharedFile@Environment(BotStore.self) private var model+ @State private var viewing = falsevar body: some View {+ VStack(alignment: .leading, spacing: 12) {+ if file.showsAsImage { preview }+ row+ }+ .padding(14)+ .background(Palette.bubbleAgent, in: RoundedRectangle(cornerRadius: 16))+ .codyncSheet(isPresented: $viewing) { AttachmentViewer(shared: file, entryId: entry.id) }+ }++ /// The picture itself; tap for full size.+ private var preview: some View {+ AttachmentImage(shared: file, entryId: entry.id, maxPixels: 720)+ .clipShape(RoundedRectangle(cornerRadius: 10, style: .continuous))+ .contentShape(Rectangle())+ .onTapGesture { viewing = true }+ .accessibilityLabel(file.name)+ .accessibilityAddTraits(.isButton)+ .frame(maxWidth: .infinity, maxHeight: 280, alignment: .leading)+ }++ private var row: some View {let state = model.fileDownloads.states[file.id]- HStack(spacing: 12) {+ return 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)@@ -28,8 +50,6 @@ struct FileDownloadCard: View {.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 {diff --git a/apps/ios/Kit/Tests/CodyncKitTests/FileDownloadTests.swift b/apps/ios/Kit/Tests/CodyncKitTests/FileDownloadTests.swiftindex 7e2a983b..5e2cbf50 100644--- a/apps/ios/Kit/Tests/CodyncKitTests/FileDownloadTests.swift+++ b/apps/ios/Kit/Tests/CodyncKitTests/FileDownloadTests.swift@@ -36,6 +36,14 @@ private func metadata(_ data: Data, name: String = "file.bin") -> SharedFile {}}+@Test func sharedFileReadsWholeInMemoryAndChecksItsDigest() async throws {+ let bytes = Data((0..<(FileDownload.chunkSize + 7)).map { UInt8($0 % 256) })+ let client = HostClient(transport: FileTransport(bytes: bytes))+ #expect(try await FileDownload().data(client: client, entryId: "entry", file: metadata(bytes, name: "picture.png")) == bytes)+ let bad = SharedFile(id: "id", name: "picture.png", size: Int64(bytes.count), sha256: String(repeating: "0", count: 64))+ await #expect(throws: FileDownloadError.self) { try await FileDownload().data(client: client, entryId: "entry", file: bad) }+}+@Test func generatedFileFailuresRemovePartialBytes() async throws {let directory = FileManager.default.temporaryDirectory.appendingPathComponent(UUID().uuidString)defer { try? FileManager.default.removeItem(at: directory) }diff --git a/docs/features/file-attachments.md b/docs/features/file-attachments.mdindex 41288b95..2342fa31 100644--- a/docs/features/file-attachments.md+++ b/docs/features/file-attachments.md@@ -67,6 +67,12 @@ the action; cancel stops further reads, discards late responses and removes partfiles. 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+An image file (by extension) up to 20 MB also shows inline above its card on iPhone,+Android and desktop, tap/click for full size. For it the client reads the whole file+into memory through the same `readFile` chunks, checks size and SHA-256, and keeps it+in the sent-attachment cache under its file id; a failed read leaves the placeholder.+The terminal UI shows only the card.++This feature adds no previews of other file types, folder packaging, background+transfers, persistent resume or Watch UI. Existing bots do not publish workspace filesautomatically: they must call `send_file`.diff --git a/web/content/docs/conversations.mdx b/web/content/docs/conversations.mdxindex d506ab0e..aad5ff3a 100644--- a/web/content/docs/conversations.mdx+++ b/web/content/docs/conversations.mdx@@ -42,7 +42,7 @@ Use the **+** button left of the message box.A message can be files only. Each file can be up to 100 MB. The files are saved on the computer, in an `uploads` folder in the bot's personal workspace, or in Codync's data folder for a bot that works in a project folder. The agent gets your message with the path of each file and reads them with its own tools.-Bots can send files back when you ask, such as a report or a build. Each one shows as a card with its name and size and a download action:+Bots can send files back when you ask, such as a report or a build. Each one shows as a card with its name and size and a download action. An image up to 20 MB also shows the picture itself in the iPhone, Android and desktop apps; tap or click it to see it full size. To save a file:- **Desktop:** saves through the system Save dialog.- **iPhone:** opens the share sheet, including Save to Files.