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: bots publish artifacts, and each chat gets a library
leepokai8aad74b75648
diff --git a/apps/android/WhatsNew.md b/apps/android/WhatsNew.mdindex 61c9d53f..3270426e 100644--- a/apps/android/WhatsNew.md+++ b/apps/android/WhatsNew.md@@ -10,12 +10,16 @@ else a generic "Bug fixes and improvements" line. Delete old sections.## 2.25.0### zh-Hant+- Bot 可以做 Artifact:報告、追蹤表、儀表板這類要回來看的內容會以卡片出現在聊天裡,點開看完整內容,直接在下方留言請它改,改好就自動更新。+- 每個 Bot 的「資料庫」收齊它做的 Artifact,以及聊天裡分享過的檔案和圖片。- 可以建立使用 Hermes Agent 的 Bot。- Bot 之間交辦工作不必等待,對方的回覆會回到發問的 Bot,再由它回覆你。- 帳號選單裡的「電腦與設定」和它打開的頁面同名。- 新增聯結器失敗後再試一次,會使用你改好的金鑰。### en-US+- Bots can make artifacts: reports, trackers and dashboards you come back to show as a card in the chat. Open one full screen and message the bot below it to change it; it updates in place.+- Each bot's Library collects its artifacts and the files and images shared in the chat.- Create bots that run Hermes Agent.- Bots hand work to each other without waiting; the answer comes back to the bot that asked, which then replies to you.- The account sheet's Computers & settings row now has the same name as the page it opens.diff --git a/apps/android/app/src/main/kotlin/com/codync/android/AnalyticsEvent.kt b/apps/android/app/src/main/kotlin/com/codync/android/AnalyticsEvent.ktindex e7a11e90..7af41b80 100644--- a/apps/android/app/src/main/kotlin/com/codync/android/AnalyticsEvent.kt+++ b/apps/android/app/src/main/kotlin/com/codync/android/AnalyticsEvent.kt@@ -160,4 +160,5 @@ internal enum class AnalyticsScreen(override val wire: String) : CatalogValue {Bots("bots"), State("state"), Chat("chat"), Trace("trace"), BotDetails("bot_details"), Memory("memory"),Routines("routines"), Marketplace("marketplace"), Settings("settings"), Computers("computers"), Usage("usage"),Account("account"), Pairing("pairing"), VoiceSettings("voice_settings"), RemoteScreen("remote_screen"),+ Library("library"), Artifact("artifact"),}diff --git a/apps/android/app/src/main/kotlin/com/codync/android/AppState.kt b/apps/android/app/src/main/kotlin/com/codync/android/AppState.ktindex 2a3de5d9..b52d3ecb 100644--- a/apps/android/app/src/main/kotlin/com/codync/android/AppState.kt+++ b/apps/android/app/src/main/kotlin/com/codync/android/AppState.kt@@ -44,6 +44,10 @@ data class AppState(val busy: Set<String> = emptySet(),val historyComplete: Set<String> = emptySet(),val routines: Map<String, RoutineListing> = emptyMap(),+ /** The computer's artifacts this phone has seen, with the HTML of the ones shown. */+ val artifacts: ArtifactCache = ArtifactCache(),+ /** Each chat's Library as last fetched, by chat ID (its artifacts as `artifacts` has them). */+ val library: Map<String, List<LibraryItem>> = emptyMap(),val plugins: PluginListing? = null,val voice: VoiceCallViewState? = null,/** The computer's remote screen (`null`: the host predates it). */diff --git a/apps/android/app/src/main/kotlin/com/codync/android/AppStoreArtifacts.kt b/apps/android/app/src/main/kotlin/com/codync/android/AppStoreArtifacts.ktnew file mode 100644index 00000000..e2da395f--- /dev/null+++ b/apps/android/app/src/main/kotlin/com/codync/android/AppStoreArtifacts.kt@@ -0,0 +1,75 @@+package com.codync.android++import java.io.File+import com.codync.android.core.*+import kotlinx.coroutines.*+import kotlinx.coroutines.flow.*+import kotlinx.serialization.json.*++// Artifacts bots publish (docs/features/artifacts.md): a chat's Library, each shown artifact's HTML (read again once a newer+// version is known), renaming and sharing.++private fun AppStore.updateArtifacts(change: (ArtifactCache) -> ArtifactCache) = mutableState.update { it.copy(artifacts = change(it.artifacts)) }++/** The `artifact` events in a batch: details only, a card or viewer showing the artifact reads its new HTML. */+internal fun AppStore.receiveArtifacts(events: List<MirrorEvent>) {+ val artifacts = events.filterIsInstance<MirrorEvent.ArtifactChanged>().map { it.artifact }+ if (artifacts.isNotEmpty()) updateArtifacts { cache -> artifacts.fold(cache, ArtifactCache::upsert) }+}++/**+ * A chat's Library, fetched when it shows: its artifacts' details join the artifact cache (events keep them current while+ * connected), its files stay listed for that chat.+ */+fun AppStore.loadLibrary(botId: String) = action("library:$botId") {+ val response = ready().call("library", body("botId" to botId)).jsonObject+ val items = response.getValue("items").jsonArray.mapNotNull { (it as? JsonObject)?.let(LibraryItem::decode) }+ val artifacts = items.filterIsInstance<LibraryItem.ArtifactItem>().map { it.artifact }+ mutableState.update { it.copy(library = it.library + (botId to items), artifacts = artifacts.fold(it.artifacts, ArtifactCache::upsert)) }+}++/**+ * Reads an artifact's HTML unless the newest version known (`announced`: the one its card names) is here already; one+ * published while it was read is read next. A failure stays with the artifact, for its card and viewer to show.+ */+fun AppStore.loadArtifact(botId: String, id: String, announced: Long = 0) {+ if (!state.value.artifacts.needsRead(id, announced)) return+ action("artifact:$id") {+ updateArtifacts { it.copy(failures = it.failures - id) }+ try {+ readArtifact(botId, id)+ if (state.value.artifacts.needsRead(id)) readArtifact(botId, id)+ } catch (error: CancellationException) { throw error }+ catch (error: Exception) { updateArtifacts { it.fail(id, error.message ?: "Couldn't read the artifact.") } }+ }+}++private suspend fun AppStore.readArtifact(botId: String, id: String): String {+ val (artifact, html) = HostFiles(ready()).readArtifact(botId, id)+ updateArtifacts { it.store(artifact, html) }+ return html+}++fun AppStore.renameArtifact(botId: String, id: String, title: String) = action("rename-artifact:$id") {+ val response = ready().call("renameArtifact", buildJsonObject { put("botId", botId); put("artifactId", id); put("title", title) }).jsonObject+ updateArtifacts { it.upsert(Artifact.decode(response.getValue("artifact"))) }+}++/** The system share sheet with the artifact's newest HTML as `<title>.html`. */+fun AppStore.shareArtifact(botId: String, id: String, title: String) = action("share-artifact:$id") {+ val cache = state.value.artifacts+ val html = cache.html[id]?.takeUnless { cache.needsRead(id) }?.text ?: readArtifact(botId, id)+ val file = withContext(Dispatchers.IO) {+ File(attachments.shareFolder().apply { mkdirs() }, artifactFileName(title)).apply { writeText(html) }+ }+ attachments.open(file, file.name)+}++/** `<title>.html`, a name the share sheet can hand out: no folders, at most 200 bytes. */+internal fun artifactFileName(title: String): String {+ var name = title.replace('/', '-').replace('\\', '-')+ while (name.toByteArray().size > MAX_NAME_BYTES - ".html".length) name = name.dropLast(1)+ return AttachmentFiles.cleanName("$name.html")+}++private const val MAX_NAME_BYTES = 200diff --git a/apps/android/app/src/main/kotlin/com/codync/android/AppStoreBots.kt b/apps/android/app/src/main/kotlin/com/codync/android/AppStoreBots.ktindex 1556aa68..b7e8ae14 100644--- a/apps/android/app/src/main/kotlin/com/codync/android/AppStoreBots.kt+++ b/apps/android/app/src/main/kotlin/com/codync/android/AppStoreBots.kt@@ -58,7 +58,8 @@ fun AppStore.deleteBot(bot: Bot, onDeleted: () -> Unit) = action("delete:" + botval active = ready()active.call("deleteBot", body("botId" to bot.id))mutableState.update { it.copy(selectedBot = it.selectedBot.takeUnless { id -> id == bot.id },- drafts = it.drafts.filterValues { draft -> draft.botId != bot.id }) }+ // Its chat's draft and its artifacts' (`artifactDraftKey`).+ drafts = it.drafts.filterKeys { key -> key != bot.id && !key.startsWith("${bot.id}/") }) }persistDrafts()onDeleted()}diff --git a/apps/android/app/src/main/kotlin/com/codync/android/AppStoreConnection.kt b/apps/android/app/src/main/kotlin/com/codync/android/AppStoreConnection.ktindex 0245efac..479d74fa 100644--- a/apps/android/app/src/main/kotlin/com/codync/android/AppStoreConnection.kt+++ b/apps/android/app/src/main/kotlin/com/codync/android/AppStoreConnection.kt@@ -184,6 +184,7 @@ private suspend fun AppStore.consumeEvents(active: EncryptedChannel, cursor: Lon}withContext(Dispatchers.IO) { requireNotNull(database).apply(batch) }refresh()+ receiveArtifacts(batch)acknowledgeVisible(readAfter(batch, state.value.readingChats))if (resync) throw Resync()}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 02874815..8312a8d8 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@@ -58,21 +58,21 @@ internal fun AppStore.persistDrafts() {}}-/** Sends the chat's draft, quoting `replyTo` when there is one. */-fun AppStore.sendDraft(botId: String, text: String, replyTo: ReplyQuote?, onQueued: () -> Unit) {- editDraft(botId, text)- val draft = state.value.drafts[botId] ?: return+/** Sends draft `key` (the chat's, or one of its artifacts') to chat `botId`, quoting `replyTo` when there is one. */+fun AppStore.sendDraft(key: String, botId: String, text: String, replyTo: ReplyQuote?, onQueued: () -> Unit) {+ editDraft(key, text)+ val draft = state.value.drafts[key] ?: returnif (draft.text != text) returnif (draft.text.isBlank() && draft.files.isEmpty()) return- action("draft-send:" + botId) {+ action("draft-send:$key") {// Persist its nonce before the pending commit. Recovery removes a draft// already represented by a pending or confirmed send with this nonce.persistDrafts()draftWriter?.join()- check(savedDrafts[botId] == draft) { "Couldn't save this draft. Retry to send it." }+ check(savedDrafts[key] == draft) { "Couldn't save this draft. Retry to send it." }val send = PendingSend(draft.nonce, botId, draft.text.trim(), System.currentTimeMillis(), files = draft.files, replyTo = replyTo)savePending(send)- mutableState.update { it.copy(drafts = it.drafts - botId) }+ mutableState.update { it.copy(drafts = it.drafts - key) }persistDrafts()onQueued()action("send:" + send.nonce) { deliver(send) }diff --git a/apps/android/app/src/main/kotlin/com/codync/android/AppStoreFiles.kt b/apps/android/app/src/main/kotlin/com/codync/android/AppStoreFiles.ktindex 8d1b5b12..da128a41 100644--- a/apps/android/app/src/main/kotlin/com/codync/android/AppStoreFiles.kt+++ b/apps/android/app/src/main/kotlin/com/codync/android/AppStoreFiles.kt@@ -16,8 +16,8 @@ sealed interface FileDownloadState {private fun downloadKey(fileId: String) = "file:$fileId"-/** Downloads `file` and opens the share sheet, if its conversation is still on screen by then. */-fun AppStore.saveFile(entry: Entry, file: SharedFile) {+/** Downloads `file` (shared in message `entryId` of chat `botId`) and opens the share sheet, if that chat is still on screen by then. */+fun AppStore.saveFile(entryId: String, botId: String, file: SharedFile) {val running = state.value.busy.filter { it.startsWith("file:") }if (running.isNotEmpty()) {if (downloadKey(file.id) !in running) setDownload(file.id, FileDownloadState.Failed("Finish the current download first."))@@ -27,9 +27,9 @@ fun AppStore.saveFile(entry: Entry, file: SharedFile) {try {setDownload(file.id, FileDownloadState.Downloading(0))val folder = withContext(Dispatchers.IO) { attachments.shareFolder() }- val saved = HostFiles(ready()).downloadShared(entry.id, file, folder) { setDownload(file.id, FileDownloadState.Downloading(it)) }+ val saved = HostFiles(ready()).downloadShared(entryId, file, folder) { setDownload(file.id, FileDownloadState.Downloading(it)) }setDownload(file.id, FileDownloadState.Saved)- if (showing(entry)) attachments.open(saved, file.name)+ if (showing(botId)) attachments.open(saved, file.name)} catch (cancelled: CancellationException) {setDownload(file.id, null)throw cancelled@@ -48,5 +48,5 @@ private fun AppStore.setDownload(fileId: String, download: FileDownloadState?) =it.copy(fileDownloads = if (download == null) it.fileDownloads - fileId else it.fileDownloads + (fileId to download))}-/** The chat the message is in is the one open. */-private fun AppStore.showing(entry: Entry): Boolean = foreground && state.value.selectedBot == entry.botId+/** The chat is the one open. */+private fun AppStore.showing(botId: String): Boolean = foreground && state.value.selectedBot == botIddiff --git a/apps/android/app/src/main/kotlin/com/codync/android/ArtifactCardView.kt b/apps/android/app/src/main/kotlin/com/codync/android/ArtifactCardView.ktnew file mode 100644index 00000000..8cedbdbb--- /dev/null+++ b/apps/android/app/src/main/kotlin/com/codync/android/ArtifactCardView.kt@@ -0,0 +1,76 @@+package com.codync.android++import androidx.compose.foundation.background+import androidx.compose.foundation.layout.Arrangement+import androidx.compose.foundation.layout.Box+import androidx.compose.foundation.layout.BoxWithConstraints+import androidx.compose.foundation.layout.Column+import androidx.compose.foundation.layout.Row+import androidx.compose.foundation.layout.fillMaxWidth+import androidx.compose.foundation.layout.height+import androidx.compose.foundation.layout.padding+import androidx.compose.foundation.layout.requiredSize+import androidx.compose.foundation.layout.wrapContentSize+import androidx.compose.material3.Text+import androidx.compose.runtime.Composable+import androidx.compose.runtime.LaunchedEffect+import androidx.compose.runtime.getValue+import androidx.compose.runtime.mutableStateOf+import androidx.compose.runtime.remember+import androidx.compose.runtime.setValue+import androidx.compose.ui.Alignment+import androidx.compose.ui.Modifier+import androidx.compose.ui.draw.clip+import androidx.compose.ui.draw.clipToBounds+import androidx.compose.ui.graphics.Brush+import androidx.compose.ui.graphics.Color+import androidx.compose.ui.graphics.TransformOrigin+import androidx.compose.ui.graphics.graphicsLayer+import androidx.compose.ui.input.pointer.pointerInput+import androidx.compose.ui.text.style.TextOverflow+import androidx.compose.ui.unit.dp+import com.codync.android.core.LinkState+import com.codync.android.core.ArtifactCard+import com.codync.android.design.*+import com.kyant.shapes.RoundedRectangle++/**+ * An artifact a bot published, in its chat (docs/features/artifacts.md): the top of the artifact's newest version, small and not+ * interactive, fading out over the artifact symbol, its title and "Artifact". `modifier` carries the card's tap and menu.+ */+@Composable internal fun ArtifactCardView(card: ArtifactCard, botId: String, state: AppState, store: AppStore, modifier: Modifier) {+ val artifacts = state.artifacts+ val newest = artifacts.newest(card.id, card.updatedAt)+ val online = state.actualConnection is LinkState.Ready+ LaunchedEffect(card.id, newest, online) { store.loadArtifact(botId, card.id, newest) }+ val html = artifacts.html[card.id]?.text+ // The artifact crashed its renderer: the card keeps its footer.+ var gone by remember(card.id) { mutableStateOf(false) }+ Column(modifier.fillMaxWidth().clip(RoundedRectangle(16.dp)).background(Palette.bubbleAgent)) {+ BoxWithConstraints(Modifier.fillMaxWidth().height(PREVIEW_HEIGHT).clipToBounds(), contentAlignment = Alignment.Center) {+ when {+ gone -> Unit+ html != null -> ArtifactWebView(card.id, html, interactive = false, gone = { gone = true },+ Modifier.wrapContentSize(Alignment.TopStart, unbounded = true)+ .requiredSize(maxWidth / PREVIEW_SCALE, PREVIEW_HEIGHT / PREVIEW_SCALE)+ .graphicsLayer { scaleX = PREVIEW_SCALE; scaleY = PREVIEW_SCALE; transformOrigin = TransformOrigin(0f, 0f) })+ card.id !in artifacts.failures -> Spinner(16.dp)+ }+ // The fade, and a cover that keeps touches off the artifact: they open the card or its menu.+ Box(Modifier.matchParentSize().pointerInput(Unit) {}+ .background(Brush.verticalGradient(0.5f to Color.Transparent, 1f to Palette.bubbleAgent)))+ }+ Row(Modifier.fillMaxWidth().padding(start = 14.dp, end = 14.dp, bottom = 12.dp), verticalAlignment = Alignment.CenterVertically,+ horizontalArrangement = Arrangement.spacedBy(10.dp)) {+ Symbol("chart.bar.doc.horizontal", size = 22.dp, tint = Palette.secondary)+ Column(Modifier.weight(1f), verticalArrangement = Arrangement.spacedBy(2.dp)) {+ Text(artifacts.title(card), style = Type.subheadline.semibold, color = Palette.text, maxLines = 2, overflow = TextOverflow.Ellipsis)+ Text(tr("Artifact"), style = Type.caption2, color = Palette.secondary)+ }+ }+ }+}++private val PREVIEW_HEIGHT = 168.dp+/** The artifact lays out twice the card's width, then shows at half size: the top of a wide artifact, not a zoomed-in corner. */+private const val PREVIEW_SCALE = 0.5fdiff --git a/apps/android/app/src/main/kotlin/com/codync/android/ArtifactViewer.kt b/apps/android/app/src/main/kotlin/com/codync/android/ArtifactViewer.ktnew file mode 100644index 00000000..6ba6ee8e--- /dev/null+++ b/apps/android/app/src/main/kotlin/com/codync/android/ArtifactViewer.kt@@ -0,0 +1,117 @@+package com.codync.android++import androidx.activity.compose.BackHandler+import androidx.compose.animation.AnimatedVisibility+import androidx.compose.animation.core.MutableTransitionState+import androidx.compose.animation.fadeIn+import androidx.compose.animation.fadeOut+import androidx.compose.animation.slideInVertically+import androidx.compose.animation.slideOutVertically+import androidx.compose.foundation.background+import androidx.compose.foundation.layout.Arrangement+import androidx.compose.foundation.layout.Box+import androidx.compose.foundation.layout.Column+import androidx.compose.foundation.layout.fillMaxSize+import androidx.compose.foundation.layout.fillMaxWidth+import androidx.compose.foundation.layout.imePadding+import androidx.compose.foundation.layout.navigationBarsPadding+import androidx.compose.foundation.layout.padding+import androidx.compose.foundation.layout.statusBarsPadding+import androidx.compose.material3.Text+import androidx.compose.runtime.Composable+import androidx.compose.runtime.LaunchedEffect+import androidx.compose.runtime.getValue+import androidx.compose.runtime.mutableStateOf+import androidx.compose.runtime.remember+import androidx.compose.runtime.setValue+import androidx.compose.ui.Alignment+import androidx.compose.ui.Modifier+import androidx.compose.ui.focus.FocusRequester+import androidx.compose.ui.focus.focusRequester+import androidx.compose.ui.text.style.TextAlign+import androidx.compose.ui.text.style.TextOverflow+import androidx.compose.ui.unit.dp+import com.codync.android.core.Bot+import com.codync.android.core.LinkState+import com.codync.android.core.artifactDraftKey+import com.codync.android.core.artifactQuote+import com.codync.android.design.*++/** The artifact a viewer shows, with what's known before its details arrive: a title, and the card to reply to. */+internal data class OpenArtifact(val id: String, val title: String, val entryId: String?)++/**+ * `content` over everything while `open` is set, sliding up like a full-screen cover; it keeps its artifact while it slides+ * away. The caller's `content` brings the state, so the layer follows it as a sheet's content does.+ */+@Composable internal fun ArtifactLayer(open: OpenArtifact?, content: @Composable (OpenArtifact) -> Unit) {+ val visible = remember { MutableTransitionState(false) }+ visible.targetState = open != null+ var last by remember { mutableStateOf(open) }+ if (open != null) last = open+ if (!visible.currentState && !visible.targetState) return+ Overlay {+ AnimatedVisibility(visible, enter = slideInVertically(Motion.layoutOffset) { it } + fadeIn(Motion.fade()),+ exit = slideOutVertically(Motion.layoutOffset) { it } + fadeOut(Motion.fade())) {+ last?.let { content(it) }+ }+ }+}++/**+ * An artifact full size (docs/features/artifacts.md): close, its title (tap to rename) and share on top, a message about it+ * at the bottom. It reads the artifact again when the bot publishes a newer version.+ */+@Composable internal fun ArtifactViewer(open: OpenArtifact, bot: Bot, state: AppState, store: AppStore, close: () -> Unit) {+ val artifacts = state.artifacts+ val artifact = artifacts.details[open.id]+ val title = artifact?.title ?: open.title+ val newest = artifacts.newest(open.id)+ val online = state.actualConnection is LinkState.Ready+ LaunchedEffect(open.id, newest, online) { store.loadArtifact(bot.id, open.id) }+ var renaming by remember { mutableStateOf(false) }+ AnalyticsOnAppear(AnalyticsEvent.ScreenViewed(AnalyticsScreen.Artifact))+ // The artifact crashed its renderer: this view is done; opening the artifact again starts a new one.+ var gone by remember(open.id) { mutableStateOf(false) }+ BackHandler(onBack = close)+ Column(Modifier.fillMaxSize().background(Palette.background).statusBarsPadding().navigationBarsPadding().imePadding()) {+ ScreenHeader({ IconButton("Close artifact", "xmark", action = close) }, {+ Text(title, Modifier.padding(horizontal = 56.dp).plainButton { renaming = true }, style = Type.body.semibold,+ color = Palette.text, maxLines = 1, overflow = TextOverflow.Ellipsis)+ }, { IconButton("Share artifact", "square.and.arrow.up") { store.shareArtifact(bot.id, open.id, title) } })+ Box(Modifier.weight(1f).fillMaxWidth(), contentAlignment = Alignment.Center) {+ val html = artifacts.html[open.id]?.text+ val failure = artifacts.failures[open.id]+ when {+ gone -> ArtifactFailure(null)+ // A newer version that couldn't be read leaves the one shown.+ html != null -> ArtifactWebView(open.id, html, interactive = true, gone = { gone = true }, Modifier.fillMaxSize())+ failure != null -> ArtifactFailure(failure)+ else -> Spinner(20.dp)+ }+ }+ // No card (a routine run published it): nothing a message could reply to.+ val quote = (artifact?.entryId ?: open.entryId)?.let { artifactQuote(it, bot.id, open.id, title) }+ if (quote != null) MessageComposer(bot, state, store, onCall = null, replyTo = quote, about = title, draftKey = artifactDraftKey(bot.id, open.id))+ }+ RenameArtifactDialog(title.takeIf { renaming }, { renaming = false }) { store.renameArtifact(bot.id, open.id, it) }+}++@Composable private fun ArtifactFailure(detail: String?) {+ Column(Modifier.padding(32.dp), horizontalAlignment = Alignment.CenterHorizontally, verticalArrangement = Arrangement.spacedBy(6.dp)) {+ Text(tr("Couldn't open the artifact"), style = Type.headline, color = Palette.text, textAlign = TextAlign.Center)+ if (detail != null) Text(detail, style = Type.subheadline, color = Palette.secondary, textAlign = TextAlign.Center)+ }+}++/** "Rename artifact" for the artifact titled `current`, shown while it's set. */+@Composable internal fun RenameArtifactDialog(current: String?, dismiss: () -> Unit, rename: (String) -> Unit) {+ var text by remember { mutableStateOf("") }+ // Set when it opens; kept while it fades away.+ LaunchedEffect(current) { if (current != null) text = current }+ CodyncDialog("Rename artifact", current != null, dismiss, field = {+ val focus = remember { FocusRequester() }+ LaunchedEffect(Unit) { focus.requestFocus() }+ PlainTextField(text, { text = it }, Modifier.fillMaxWidth().focusRequester(focus).pill(Palette.background), "Artifact title", singleLine = true)+ }) { listOf(DialogAction("Save") { text.trim().takeIf { it.isNotEmpty() && it != current }?.let(rename) }) }+}diff --git a/apps/android/app/src/main/kotlin/com/codync/android/ArtifactWebView.kt b/apps/android/app/src/main/kotlin/com/codync/android/ArtifactWebView.ktnew file mode 100644index 00000000..f32a2c3a--- /dev/null+++ b/apps/android/app/src/main/kotlin/com/codync/android/ArtifactWebView.kt@@ -0,0 +1,73 @@+package com.codync.android++import android.annotation.SuppressLint+import android.content.Context+import android.view.View+import android.webkit.RenderProcessGoneDetail+import android.webkit.WebResourceRequest+import android.webkit.WebView+import android.webkit.WebViewClient+import androidx.compose.runtime.Composable+import androidx.compose.runtime.getValue+import androidx.compose.runtime.remember+import androidx.compose.runtime.rememberUpdatedState+import androidx.compose.ui.Modifier+import androidx.compose.ui.platform.LocalContext+import androidx.compose.ui.platform.LocalUriHandler+import androidx.compose.ui.viewinterop.AndroidView++/**+ * Artifact `id`'s HTML in a web view of its own: scripts on, no bridge into the app, no files, and an origin of its own,+ * so what it keeps (a tracker's ticks) stays its own. In the viewer (`interactive`) a link the user taps opens in the+ * system browser; the card's preview follows none and is hidden from TalkBack. `gone`: the artifact crashed its renderer,+ * so this view can't be used again and the caller drops it.+ */+@Composable internal fun ArtifactWebView(id: String, html: String, interactive: Boolean, gone: () -> Unit, modifier: Modifier = Modifier) {+ val context = LocalContext.current+ val links = LocalUriHandler.current+ val onGone by rememberUpdatedState(gone)+ val view = remember(id) { ArtifactView(context, id, interactive, { url -> runCatching { links.openUri(url) } }) { onGone() } }+ AndroidView({ view }, modifier, onRelease = ArtifactView::destroy, update = { it.show(html) })+}++@SuppressLint("SetJavaScriptEnabled", "ViewConstructor")+private class ArtifactView(context: Context, id: String, interactive: Boolean, open: (String) -> Unit, gone: () -> Unit) : WebView(context) {+ private var shown: String? = null+ /** Never resolves: relative links go nowhere, and the artifact gets an origin to keep its storage under (as on iPhone). */+ private val origin = "${id.lowercase()}.artifact.codync.invalid"++ init {+ settings.javaScriptEnabled = true+ settings.domStorageEnabled = true+ settings.allowFileAccess = false+ settings.allowContentAccess = false+ settings.javaScriptCanOpenWindowsAutomatically = false+ settings.setSupportMultipleWindows(false)+ isVerticalScrollBarEnabled = false+ isHorizontalScrollBarEnabled = false+ if (!interactive) importantForAccessibility = View.IMPORTANT_FOR_ACCESSIBILITY_NO_HIDE_DESCENDANTS+ webViewClient = object : WebViewClient() {+ override fun shouldOverrideUrlLoading(view: WebView, request: WebResourceRequest): Boolean {+ val url = request.url+ // In-artifact anchors stay; a tapped link leaves for the browser, an artifact sending itself elsewhere goes nowhere.+ if (url.scheme == "about" || url.host == origin) return false+ if (interactive && request.hasGesture() && url.scheme in LINK_SCHEMES) open(url.toString())+ return true+ }++ override fun onRenderProcessGone(view: WebView, detail: RenderProcessGoneDetail): Boolean {+ gone()+ return true+ }+ }+ }++ /** Loads `html` unless it's what's shown already (the same version keeps its scroll and state). */+ fun show(html: String) {+ if (shown === html) return+ shown = html+ loadDataWithBaseURL("https://$origin/", html, "text/html", "UTF-8", null)+ }+}++private val LINK_SCHEMES = listOf("http", "https", "mailto", "tel")diff --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 1bbac319..6dfc6c37 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@@ -44,11 +44,16 @@ import kotlinx.coroutines.withContextelse AttachmentCard(file)}}- CodyncSheet(viewing, { viewing = null }) { file ->+ AttachmentImageSheet(viewing, botId, state, store) { viewing = null }+}++/** 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 ->Column(Modifier.fillMaxSize().background(Palette.background)) {- ModalHeader(file.name)+ ModalHeader(shown.name)Box(Modifier.weight(1f).padding(12.dp), contentAlignment = Alignment.Center) {- AttachmentImage(file, botId, 4096, state, store, Modifier.fillMaxSize())+ AttachmentImage(shown, botId, 4096, state, store, Modifier.fillMaxSize())}}}@@ -66,7 +71,8 @@ import kotlinx.coroutines.withContext}/** A sent image, fetched from the computer once and then read from the cache; a placeholder until then. */-@Composable private fun AttachmentImage(file: Attachment, botId: String, maxPixels: Int, state: AppState, store: AppStore, modifier: Modifier) {+@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) }// Retried whenever the link changes: an image the computer couldn't send stays a placeholder, as on iOS.LaunchedEffect(file.id, maxPixels, state.actualConnection) {@@ -78,7 +84,7 @@ import kotlinx.coroutines.withContextcatch (_: Exception) { /* The placeholder stays; the next link change tries again. */ }}val bitmap = image- if (bitmap != null) Image(bitmap, contentDescription = null, modifier = modifier, contentScale = ContentScale.Fit)+ if (bitmap != null) Image(bitmap, contentDescription = null, modifier = modifier, contentScale = scale)else Box(modifier.size(160.dp, 120.dp).clip(RoundedRectangle(16.dp)).background(Palette.bubbleUser), contentAlignment = Alignment.Center) {Symbol("photo", size = 20.dp, tint = Palette.tertiary)}diff --git a/apps/android/app/src/main/kotlin/com/codync/android/ChatRows.kt b/apps/android/app/src/main/kotlin/com/codync/android/ChatRows.ktindex eff57e8d..a1150649 100644--- a/apps/android/app/src/main/kotlin/com/codync/android/ChatRows.kt+++ b/apps/android/app/src/main/kotlin/com/codync/android/ChatRows.kt@@ -104,9 +104,10 @@ internal fun chatItems(entries: List<Entry>, pending: List<PendingSend>): List<Ccolor = Palette.tertiary, textAlign = TextAlign.Center)}-/** One chat-visible entry, with what can be done to it. `reply` quotes it in the composer; `addFallback` opens a bot's fallbacks. */+/** One chat-visible entry, with what can be done to it. `reply` quotes it in the composer; `addFallback` opens a bot's fallbacks;+ * `openArtifact` opens an artifact card's artifact. */@Composable internal fun ChatRow(entry: Entry, groupStart: Boolean, chat: Bot?, state: AppState, store: AppStore,- openTrace: () -> Unit, reply: (() -> Unit)?, connect: ConnectionRequestActions, addFallback: (Bot) -> Unit) {+ openTrace: () -> Unit, reply: (() -> Unit)?, connect: ConnectionRequestActions, addFallback: (Bot) -> Unit, openArtifact: (OpenArtifact) -> Unit) {val group = chat?.kind == "group"when (entry.kind) {"user" -> Column(Modifier.fillMaxWidth().padding(top = if (groupStart) 12.dp else 4.dp).animateContentSize(Motion.layoutSize),@@ -117,7 +118,7 @@ internal fun chatItems(entries: List<Entry>, pending: List<PendingSend>): List<C"agent" -> Column(Modifier.fillMaxWidth().padding(top = if (groupStart) 12.dp else 4.dp).animateContentSize(Motion.layoutSize),verticalArrangement = Arrangement.spacedBy(4.dp)) {if (group && groupStart) AuthorLabel(entry.data.text("author"), state)- AgentBubble(entry, state, store, openTrace, reply)+ AgentBubble(entry, state, store, openTrace, reply, openArtifact)Box(Modifier.padding(start = if (group) 34.dp else 0.dp)) { ReactionsRow(entry, state, store) }}"permission" -> Column(Modifier.padding(top = 12.dp), verticalArrangement = Arrangement.spacedBy(4.dp)) {@@ -236,13 +237,17 @@ internal val Entry.reactions: List<String> get() = (data["reactions"] as? JsonAr}}-@Composable private fun AgentBubble(entry: Entry, state: AppState, store: AppStore, openTrace: () -> Unit, reply: (() -> Unit)?) {+@Composable private fun AgentBubble(entry: Entry, state: AppState, store: AppStore, openTrace: () -> Unit, reply: (() -> Unit)?,+ openArtifact: (OpenArtifact) -> Unit) {val context = LocalContext.currentval focus = LocalFocusManager.currentval files = entry.files+ val artifact = entry.artifactColumn(Modifier.fillMaxWidth().padding(end = 40.dp), verticalArrangement = Arrangement.spacedBy(4.dp)) {- // A message with files is its files: the text is only the computer's fallback.- if (files.isNotEmpty()) Column(Modifier.contextActions(reactions = reactionPick(entry, store), onClick = { focus.clearFocus() }) { messageMenu(context, entry, reply, openTrace) },+ // An artifact card or a message with files is that: the text is only the computer's fallback.+ if (artifact != null) ArtifactCardView(artifact, entry.botId, state, store, Modifier.contextActions(reactions = reactionPick(entry, store),+ onClick = { focus.clearFocus(); openArtifact(OpenArtifact(artifact.id, artifact.title, entry.id)) }) { messageMenu(context, entry, reply, openTrace) })+ else if (files.isNotEmpty()) Column(Modifier.contextActions(reactions = reactionPick(entry, store), onClick = { focus.clearFocus() }) { messageMenu(context, entry, reply, openTrace) },verticalArrangement = Arrangement.spacedBy(4.dp)) {for (file in files) FileDownloadCard(entry, file, state, store)} else if (entry.text.isNotEmpty()) Box(Modifier.clip(RoundedRectangle(18.dp)).background(Palette.bubbleAgent)diff --git a/apps/android/app/src/main/kotlin/com/codync/android/ChatScreen.kt b/apps/android/app/src/main/kotlin/com/codync/android/ChatScreen.ktindex 04419c37..719e2949 100644--- a/apps/android/app/src/main/kotlin/com/codync/android/ChatScreen.kt+++ b/apps/android/app/src/main/kotlin/com/codync/android/ChatScreen.kt@@ -77,6 +77,9 @@ import com.kyant.shapes.Capsule// The routine the sheet opens on (a run's notice), or none for the list.var routineId by remember { mutableStateOf<String?>(null) }val openRoutine = { id: String? -> routineId = id; routines = true }+ var library by remember { mutableStateOf(false) }+ // The artifact open full size, over the chat and its Library.+ var viewing by remember(bot.id) { mutableStateOf<OpenArtifact?>(null) }// The bot whose conversation with this one is open.var peer by remember(bot.id) { mutableStateOf<String?>(null) }var micDenied by remember { mutableStateOf(false) }@@ -90,7 +93,7 @@ import com.kyant.shapes.Capsuleval density = LocalDensity.current// The message the composer quotes, until it sends or this chat closes.var replyId by rememberSaveable(bot.id) { mutableStateOf<String?>(null) }- val replyTo = state.entries.firstOrNull { it.id == replyId && it.botId == bot.id }+ val replyTo = state.entries.firstOrNull { it.id == replyId && it.botId == bot.id }?.replyQuoteval reply = { entry: Entry -> replyId = entry.id }// The chat ignores Full conversation over it: it stays put underneath.val chatState = state.copy(trace = false)@@ -98,7 +101,7 @@ import com.kyant.shapes.Capsule// Down to just above the header's bottom; the bottom one stops under Jump to latest.ScrollEdge(Edge.Top, top + 84.dp)ScrollEdge(Edge.Bottom, with(density) { composerHeight.toDp() } + 4.dp, Modifier.align(Alignment.BottomCenter))- ThreadHeader(bot, state, store, edit, { store.showTrace(true) }, { openRoutine(null) }, { confirmNewSession = true }, { confirmDelete = true })+ ThreadHeader(bot, state, store, edit, { store.showTrace(true) }, { openRoutine(null) }, { library = true }, { confirmNewSession = true }, { confirmDelete = true })// The call floats over the chat under the header, as on iOS; the chat stays readable and usable.AnimatedVisibility(state.voice != null, Modifier.padding(top = top + 54.dp),enter = fadeIn(Motion.fade()) + slideInVertically(Motion.layoutOffset) { -it }, exit = fadeOut(Motion.fade()) + slideOutVertically(Motion.layoutOffset) { -it }) {@@ -110,14 +113,15 @@ import com.kyant.shapes.Capsule// Nothing sent now could be read on the other side.val mismatch = state.mismatchif (mismatch != null) UpdateNeededCard(state, mismatch, Modifier.padding(start = 16.dp, end = 16.dp, bottom = 8.dp))- else MessageComposer(bot, chatState, store, onCall = if (state.voice == null && state.actualConnection is LinkState.Ready) startCall else null,+ // An artifact's viewer has its own box for the same draft; two would overwrite each other.+ else if (viewing == null) MessageComposer(bot, chatState, store, onCall = if (state.voice == null && state.actualConnection is LinkState.Ready) startCall else null,onInterrupt = if (state.voice?.botId == bot.id && state.voice.state.phase == VoicePhase.Speaking) store::interruptVoice else null,replyTo = replyTo, cancelReply = { replyId = null })}}) {Transcript(bot, chatState, store, connect, PaddingValues(start = 16.dp, end = 16.dp, top = top + 60.dp,bottom = with(density) { composerHeight.toDp() } + 8.dp), indicatorTop = top + 50.dp, openRoutine = openRoutine, reply = reply,- addFallback = editFallbacks) { peer = it }+ addFallback = editFallbacks, openArtifact = { viewing = it }) { peer = it }}CodyncDialog("Start a new session?", confirmNewSession, { confirmNewSession = false },message = "The conversation stays here, but the agent starts with a fresh context.") {@@ -141,6 +145,8 @@ import com.kyant.shapes.CapsuleAnalyticsOnAppear(AnalyticsEvent.ScreenViewed(AnalyticsScreen.Routines))RoutinesScreen(bot, state, store, routineId)}+ CodyncSheet(library, { library = false }) { LibrarySheet(bot, state, store) { viewing = it } }+ ArtifactLayer(viewing) { ArtifactViewer(it, bot, state, store) { viewing = null } }CodyncSheet(peer, { peer = null }) { BotConversationView(bot, it, state, store) }CodyncSheet(app, { app = null; setupEntry = null }) { ComposioConnectSheet(it, state, store, setupEntry) { store.refreshPlugins() } }CodyncSheet(connector, { connector = null; setupEntry = null }) { InstallConnectorSheet(it, state, store, setupEntry) }@@ -148,7 +154,7 @@ import com.kyant.shapes.Capsule/** The glass back button, the title (its menu holds the bot's actions) and the connection under it. */@Composable private fun ThreadHeader(bot: Bot, state: AppState, store: AppStore, edit: (Bot) -> Unit, trace: () -> Unit,- routines: () -> Unit, newSession: () -> Unit, delete: () -> Unit) {+ routines: () -> Unit, library: () -> Unit, newSession: () -> Unit, delete: () -> Unit) {Box(Modifier.fillMaxWidth().statusBarsPadding().padding(top = 6.dp).padding(horizontal = 16.dp).height(44.dp)) {val (source, pressed) = rememberPress()Box(Modifier.align(Alignment.CenterStart).size(44.dp).glass(Capsule(), pressed = pressed)@@ -173,6 +179,8 @@ import com.kyant.shapes.Capsule} else {add(MenuItem("Edit profile", icon = "pencil") { edit(bot) }); add(pin)add(MenuItem("Routines", icon = "clock.arrow.circlepath", action = routines))+ // An older host has no Library.+ if (hasLibrary(state.hello?.text("version"))) add(MenuItem("Library", icon = "books.vertical", action = library))add(MenuItem("New session", icon = "arrow.counterclockwise", action = newSession))add(MenuItem("Delete bot", icon = "trash", destructive = true, divider = true, action = delete))}@@ -221,7 +229,8 @@ import com.kyant.shapes.Capsule/** The messages: all this phone has, earlier ones from the computer near the top, following the newest. */@Composable private fun Transcript(bot: Bot, state: AppState, store: AppStore, connect: ConnectionRequestActions, padding: PaddingValues,- indicatorTop: Dp, openRoutine: (String) -> Unit, reply: (Entry) -> Unit, addFallback: (Bot) -> Unit, openPeer: (String) -> Unit) {+ indicatorTop: Dp, openRoutine: (String) -> Unit, reply: (Entry) -> Unit, addFallback: (Bot) -> Unit, openArtifact: (OpenArtifact) -> Unit,+ openPeer: (String) -> Unit) {val entries = state.entries.filter { it.botId == bot.id && it.isChat }val pending = state.pending.filter { it.botId == bot.id }val items = chatItems(entries, pending)@@ -246,7 +255,7 @@ import com.kyant.shapes.Capsuleelse ChatRow(item.entry, item.groupStart, bot, state, store, openTrace = { store.showTrace(true) },// An update card takes the composer's place, so there's nothing to reply with.reply = if (item.entry.isReplyable && state.mismatch == null) { { reply(item.entry) } } else null, connect = connect,- addFallback = addFallback)+ addFallback = addFallback, openArtifact = openArtifact)}is ChatItem.Pending -> PendingBubble(item.send, item.groupStart, state, store)is ChatItem.Exchanges -> BotMessageRow(item.group, state) { openPeer(item.group.peerId) }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 cd0e2f31..949f185e 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@@ -33,14 +33,15 @@ import com.kyant.shapes.RoundedRectangleText(file.name, style = Type.subheadline.semibold, color = Palette.text, maxLines = 2, overflow = TextOverflow.Ellipsis)Text(detail(file, download), style = Type.caption2, color = Palette.secondary)}- Box(Modifier.size(36.dp).plainButton { if (busy) store.cancelFile(file.id) else store.saveFile(entry, file) }+ Box(Modifier.size(36.dp).plainButton { if (busy) store.cancelFile(file.id) else store.saveFile(entry.id, entry.botId, file) }.semantics { contentDescription = (if (busy) "Cancel download " else "Download ") + file.name }, contentAlignment = Alignment.Center) {Symbol(if (busy) "xmark" else "arrow.down.to.line", size = 20.dp, tint = Palette.text)}}}-private fun detail(file: SharedFile, download: FileDownloadState?): String {+/** A shared file's size, or how its download goes. */+internal fun detail(file: SharedFile, download: FileDownloadState?): String {val size = formatBytes(file.size)return when (download) {is FileDownloadState.Downloading -> "${formatBytes(download.received)} of $size"diff --git a/apps/android/app/src/main/kotlin/com/codync/android/LibrarySheet.kt b/apps/android/app/src/main/kotlin/com/codync/android/LibrarySheet.ktnew file mode 100644index 00000000..f1e77212--- /dev/null+++ b/apps/android/app/src/main/kotlin/com/codync/android/LibrarySheet.kt@@ -0,0 +1,135 @@+package com.codync.android++import androidx.compose.foundation.background+import androidx.compose.foundation.layout.Arrangement+import androidx.compose.foundation.layout.Box+import androidx.compose.foundation.layout.Column+import androidx.compose.foundation.layout.Row+import androidx.compose.foundation.layout.RowScope+import androidx.compose.foundation.layout.fillMaxSize+import androidx.compose.foundation.layout.fillMaxWidth+import androidx.compose.foundation.layout.padding+import androidx.compose.foundation.layout.size+import androidx.compose.foundation.rememberScrollState+import androidx.compose.foundation.verticalScroll+import androidx.compose.material3.Text+import androidx.compose.runtime.Composable+import androidx.compose.runtime.LaunchedEffect+import androidx.compose.runtime.getValue+import androidx.compose.runtime.mutableStateOf+import androidx.compose.runtime.remember+import androidx.compose.runtime.setValue+import androidx.compose.ui.Alignment+import androidx.compose.ui.Modifier+import androidx.compose.ui.draw.clip+import androidx.compose.ui.layout.ContentScale+import androidx.compose.ui.semantics.heading+import androidx.compose.ui.semantics.semantics+import androidx.compose.ui.text.style.TextAlign+import androidx.compose.ui.text.style.TextOverflow+import androidx.compose.ui.unit.dp+import com.codync.android.core.Attachment+import com.codync.android.core.Bot+import com.codync.android.core.LibraryItem+import com.codync.android.core.LibraryPeriod+import com.codync.android.core.LinkState+import com.codync.android.core.Artifact+import com.codync.android.design.*+import com.kyant.shapes.RoundedRectangle++/**+ * A chat's Library, in a sheet over it (docs/features/artifacts.md): the artifacts its bot published and the files shared in+ * it, newest first by day. Each opens as it does in the chat.+ */+@Composable internal fun LibrarySheet(bot: Bot, state: AppState, store: AppStore, open: (OpenArtifact) -> Unit) {+ val online = state.actualConnection is LinkState.Ready+ AnalyticsOnAppear(AnalyticsEvent.ScreenViewed(AnalyticsScreen.Library))+ LaunchedEffect(bot.id, online) { if (online) store.loadLibrary(bot.id) }+ val items = state.artifacts.library(bot.id, state.library[bot.id].orEmpty())+ var renaming by remember { mutableStateOf<Artifact?>(null) }+ var image by remember { mutableStateOf<Attachment?>(null) }+ Column(Modifier.fillMaxSize().background(Palette.background)) {+ ModalHeader("Library")+ when {+ items.isNotEmpty() -> Column(Modifier.verticalScroll(rememberScrollState()).padding(start = 20.dp, end = 20.dp, bottom = 20.dp),+ verticalArrangement = Arrangement.spacedBy(16.dp)) {+ for ((period, members) in LibraryPeriod.sections(items)) Column(verticalArrangement = Arrangement.spacedBy(10.dp)) {+ Text(tr(period.title), Modifier.padding(start = 2.dp).semantics { heading() }, style = Type.system(15f).semibold, color = Palette.text)+ Column(Modifier.fillMaxWidth().clip(RoundedRectangle(16.dp)).background(Palette.surface)) {+ for ((index, item) in members.withIndex()) {+ if (index > 0) Hairline(Modifier.padding(horizontal = 16.dp))+ when (item) {+ is LibraryItem.ArtifactItem -> ArtifactRow(item.artifact, { open(OpenArtifact(item.artifact.id, item.artifact.title, item.artifact.entryId)) },+ { renaming = item.artifact }) { store.shareArtifact(bot.id, item.artifact.id, item.artifact.title) }+ is LibraryItem.FileItem -> FileRow(item, bot.id, state, store)+ is LibraryItem.AttachmentItem -> AttachmentRow(item.file, bot.id, state, store) { image = item.file }+ }+ }+ }+ }+ }+ "library:${bot.id}" in state.busy -> Box(Modifier.fillMaxWidth().padding(top = 40.dp), contentAlignment = Alignment.Center) { Spinner(20.dp) }+ else -> EmptyLibrary(bot.name)+ }+ }+ // The artifact as composed: Save closes the dialog (clearing `renaming`) before it renames.+ val target = renaming+ RenameArtifactDialog(target?.title, { renaming = null }) { title -> target?.let { store.renameArtifact(bot.id, it.id, title) } }+ AttachmentImageSheet(image, bot.id, state, store) { image = null }+}++/** One row of the Library: what it is on the left, its name and detail. */+@Composable private fun LibraryRow(modifier: Modifier, leading: @Composable () -> Unit, content: @Composable RowScope.() -> Unit) {+ Row(modifier.fillMaxWidth().padding(horizontal = 16.dp, vertical = 12.dp), verticalAlignment = Alignment.CenterVertically,+ horizontalArrangement = Arrangement.spacedBy(12.dp)) {+ Box(Modifier.size(36.dp), contentAlignment = Alignment.Center) { leading() }+ content()+ }+}++/** An artifact: tapping opens it, holding opens its menu. */+@Composable private fun ArtifactRow(artifact: Artifact, open: () -> Unit, rename: () -> Unit, share: () -> Unit) {+ LibraryRow(Modifier.contextActions(onClick = open) {+ listOf(MenuItem("Open", icon = "arrow.up.right", action = open), MenuItem("Rename artifact", icon = "pencil", action = rename),+ MenuItem("Share artifact", icon = "square.and.arrow.up", action = share))+ }, { Symbol("chart.bar.doc.horizontal", size = 22.dp, tint = Palette.secondary) }) {+ Text(artifact.title, Modifier.weight(1f), style = Type.system(13f), color = Palette.text, maxLines = 2, overflow = TextOverflow.Ellipsis)+ }+}++/** A file the bot shared: tapping downloads it to the share sheet, as its card in the chat does (again: cancels). */+@Composable private fun FileRow(item: LibraryItem.FileItem, botId: String, state: AppState, store: AppStore) {+ val download = state.fileDownloads[item.file.id]+ val busy = download is FileDownloadState.Downloading+ LibraryRow(Modifier.plainButton { if (busy) store.cancelFile(item.file.id) else store.saveFile(item.entryId, botId, item.file) },+ { Symbol(AttachmentIcon.symbol(item.file.name), size = 22.dp, tint = Palette.secondary) }) {+ NameAndDetail(item.file.name, detail(item.file, download))+ }+}++/** A file the user attached: an image opens full size, as in the chat; another file only shows. */+@Composable private fun AttachmentRow(file: Attachment, botId: String, state: AppState, store: AppStore, openImage: () -> Unit) {+ if (file.isImage) LibraryRow(Modifier.plainButton(action = openImage), {+ AttachmentImage(file, botId, 144, state, store, Modifier.size(36.dp).clip(RoundedRectangle(8.dp)), ContentScale.Crop)+ }) { NameAndDetail(file.name, formatBytes(file.size)) }+ else LibraryRow(Modifier.semantics(mergeDescendants = true) {}, { Symbol(AttachmentIcon.symbol(file.name), size = 22.dp, tint = Palette.secondary) }) {+ NameAndDetail(file.name, formatBytes(file.size))+ }+}++@Composable private fun RowScope.NameAndDetail(name: String, detail: String) {+ Column(Modifier.weight(1f), verticalArrangement = Arrangement.spacedBy(2.dp)) {+ Text(name, style = Type.system(13f), color = Palette.text, maxLines = 1, overflow = TextOverflow.MiddleEllipsis)+ Text(detail, style = Type.caption2, color = Palette.secondary)+ }+}++@Composable private fun EmptyLibrary(name: String) {+ Column(Modifier.fillMaxWidth().padding(horizontal = 32.dp, vertical = 48.dp), horizontalAlignment = Alignment.CenterHorizontally,+ verticalArrangement = Arrangement.spacedBy(8.dp)) {+ Symbol("books.vertical", size = 36.dp, tint = Palette.tertiary)+ Text(tr("Library is empty"), style = Type.headline, color = Palette.text, textAlign = TextAlign.Center)+ Text(tr("Artifacts {name} makes and files shared in this chat show here.").replace("{name}", name), style = Type.subheadline,+ color = Palette.secondary, textAlign = TextAlign.Center)+ }+}diff --git a/apps/android/app/src/main/kotlin/com/codync/android/MessageComposer.kt b/apps/android/app/src/main/kotlin/com/codync/android/MessageComposer.ktindex 3a8e9620..301169f1 100644--- a/apps/android/app/src/main/kotlin/com/codync/android/MessageComposer.kt+++ b/apps/android/app/src/main/kotlin/com/codync/android/MessageComposer.kt@@ -77,27 +77,30 @@ private enum class Trailing { Interrupt, Stop, Call, Send }/*** The message box under a chat, as iOS `Composer`: a glass + for files, a glass field whose* trailing button morphs between call, send, stop and interrupt. `onInterrupt` cuts the bot off- * while it speaks in a voice call. `replyTo` is the message the next send quotes, shown on top.+ * while it speaks in a voice call. `replyTo` is the message the next send quotes, shown on top. `about`, in an artifact's+ * viewer: the artifact's title, which the box names in place of the quote (its card) it sends with; `draftKey` is then the+ * artifact's draft, apart from the chat's.*/@OptIn(ExperimentalFoundationApi::class)@Composable fun MessageComposer(bot: Bot, state: AppState, store: AppStore, onCall: (() -> Unit)?,- onInterrupt: (() -> Unit)? = null, replyTo: Entry? = null, cancelReply: () -> Unit = {}) {- val draft = state.drafts[bot.id]+ onInterrupt: (() -> Unit)? = null, replyTo: ReplyQuote? = null, cancelReply: () -> Unit = {}, about: String? = null,+ draftKey: String = bot.id) {+ val draft = state.drafts[draftKey]val text = rememberTextFieldState(initialText = draft?.text.orEmpty())val files = draft?.files.orEmpty()- val queuing = "draft-send:" + bot.id in state.busy+ val queuing = "draft-send:$draftKey" in state.busyval importing = "attachments" in state.busy// What this box sent to the store, so a draft set elsewhere (a routine request) can be told from our own echo.- val echoes = remember(bot.id) { ArrayDeque<String>() }- LaunchedEffect(text, bot.id) {+ val echoes = remember(draftKey) { ArrayDeque<String>() }+ LaunchedEffect(text, draftKey) {snapshotFlow { text.text.toString() }.collect {echoes.addLast(it); while (echoes.size > 32) echoes.removeFirst()- store.editDraft(bot.id, it)+ store.editDraft(draftKey, it)}}// Choosing a message to reply to goes straight to typing.val focus = remember { FocusRequester() }- LaunchedEffect(replyTo?.id) { if (replyTo != null) focus.requestFocus() }+ LaunchedEffect(replyTo?.id) { if (replyTo != null && about == null) focus.requestFocus() }LaunchedEffect(draft?.text) {val external = draft?.text.orEmpty()if (external != text.text.toString() && external !in echoes) text.setTextAndPlaceCursorAtEnd(external)@@ -106,16 +109,16 @@ private enum class Trailing { Interrupt, Stop, Call, Send }val clips = LocalContext.current.getSystemService(ClipboardManager::class.java)val scope = rememberCoroutineScope()val photos = rememberLauncherForActivityResult(ActivityResultContracts.PickMultipleVisualMedia(10)) { uris ->- if (uris.isNotEmpty()) store.importFiles(uris) { store.addDraftFiles(bot.id, it) }+ if (uris.isNotEmpty()) store.importFiles(uris) { store.addDraftFiles(draftKey, it) }}val documents = rememberLauncherForActivityResult(ActivityResultContracts.OpenMultipleDocuments()) { uris ->- if (uris.isNotEmpty()) store.importFiles(uris) { store.addDraftFiles(bot.id, it) }+ if (uris.isNotEmpty()) store.importFiles(uris) { store.addDraftFiles(draftKey, it) }}- val receiver = remember(bot.id, importing, queuing) { ReceiveContentListener { content ->+ val receiver = remember(draftKey, importing, queuing) { ReceiveContentListener { content ->if (importing || queuing) content else {val uris = mutableListOf<android.net.Uri>()val remaining = content.consume { item -> item.uri?.takeIf { it.scheme == "content" }?.let { uris.add(it); true } ?: false }- if (uris.isNotEmpty()) store.importFiles(uris) { store.addDraftFiles(bot.id, it) }+ if (uris.isNotEmpty()) store.importFiles(uris) { store.addDraftFiles(draftKey, it) }remaining}} }@@ -132,6 +135,7 @@ private enum class Trailing { Interrupt, Stop, Call, Send }else -> Trailing.Send}val placeholder = when {+ about != null -> tr("Message about “{title}”").replace("{title}", about)replyTo != null -> tr("Reply…")bot.kind == "group" -> tr("Ask everyone · @ to ask one bot")working -> tr("Queue a message for {name}").replace("{name}", bot.name)@@ -157,7 +161,7 @@ private enum class Trailing { Interrupt, Stop, Call, Send }}fun send() {val command = if (files.isEmpty()) SlashCommands.builtIn(bot, typed, members) else null- if (command != null) run(command) else store.sendDraft(bot.id, typed, replyTo?.replyQuote) { clear(); cancelReply() }+ if (command != null) run(command) else store.sendDraft(draftKey, bot.id, typed, replyTo) { clear(); cancelReply() }}Column(verticalArrangement = Arrangement.spacedBy(6.dp)) {AnimatedVisibility(commands.isNotEmpty(), enter = fadeIn(Motion.fade()) + expandVertically(Motion.layoutSize),@@ -176,14 +180,14 @@ private enum class Trailing { Interrupt, Stop, Call, Send }if (clipOffersFiles(clips.primaryClipDescription?.mimeTypes().orEmpty())) add(MenuItem("Paste", icon = "doc.on.clipboard") { scope.launch {val data = clipboard.getClipEntry()?.clipDataval uris = if (data == null) emptyList() else (0 until data.itemCount).mapNotNull { data.getItemAt(it).uri?.takeIf { uri -> uri.scheme == "content" } }- if (uris.isNotEmpty()) store.importFiles(uris) { store.addDraftFiles(bot.id, it) }+ if (uris.isNotEmpty()) store.importFiles(uris) { store.addDraftFiles(draftKey, it) }} })} }, Modifier.size(FIELD_HEIGHT).glass(Capsule()), enabled = !queuing, label = "Add files") {Symbol("plus", size = 26.dp, tint = Palette.text)}Column(Modifier.weight(1f).glass(RoundedRectangle(24.dp)).animateContentSize(Motion.layoutSize)) {// Each quote keeps its own bar through the transition, so a cancelled one fades out with its text.- AnimatedContent(replyTo?.quotePreview, transitionSpec = { fadeIn(Motion.fade()) togetherWith fadeOut(Motion.fade()) },+ AnimatedContent(replyTo?.text?.takeIf { about == null }, transitionSpec = { fadeIn(Motion.fade()) togetherWith fadeOut(Motion.fade()) },label = "Reply") { quote ->if (quote != null) Row(Modifier.padding(start = 18.dp, end = 6.dp, top = 8.dp), verticalAlignment = Alignment.CenterVertically) {QuoteLine(quote, Modifier.weight(1f))@@ -192,7 +196,7 @@ private enum class Trailing { Interrupt, Stop, Call, Send }}if (files.isNotEmpty()) Row(Modifier.horizontalScroll(rememberScrollState()).padding(start = 10.dp, end = 10.dp, top = 8.dp),verticalAlignment = Alignment.CenterVertically, horizontalArrangement = Arrangement.spacedBy(6.dp)) {- for (file in files) ComposerAttachment(file) { store.removeDraftFile(bot.id, file) }+ for (file in files) ComposerAttachment(file) { store.removeDraftFile(draftKey, file) }}Row(Modifier.padding(start = 18.dp, end = 6.dp, top = 6.dp, bottom = 6.dp), verticalAlignment = Alignment.Bottom,horizontalArrangement = Arrangement.spacedBy(8.dp)) {diff --git a/apps/android/app/src/main/kotlin/com/codync/android/MirrorDatabase.kt b/apps/android/app/src/main/kotlin/com/codync/android/MirrorDatabase.ktindex b8d6a929..ccdaedf8 100644--- a/apps/android/app/src/main/kotlin/com/codync/android/MirrorDatabase.kt+++ b/apps/android/app/src/main/kotlin/com/codync/android/MirrorDatabase.kt@@ -84,7 +84,8 @@ class MirrorDatabase(context: Context, directory: File, computerId: String) :is MirrorEvent.EntryChanged -> { writeEntry(db, event.entry); bump(db, event.entry.rev) }is MirrorEvent.Usage -> setMeta(db, "usage", event.value.toString())is MirrorEvent.Screen -> setMeta(db, "screen", event.value.toString())- MirrorEvent.Resync, MirrorEvent.Ignored -> Unit+ // Artifacts live in memory (`AppStore.receiveArtifacts`).+ MirrorEvent.Resync, MirrorEvent.Ignored, is MirrorEvent.ArtifactChanged -> Unit}}diff --git a/apps/android/app/src/test/kotlin/com/codync/android/ArtifactFileNameTest.kt b/apps/android/app/src/test/kotlin/com/codync/android/ArtifactFileNameTest.ktnew file mode 100644index 00000000..3ff18c06--- /dev/null+++ b/apps/android/app/src/test/kotlin/com/codync/android/ArtifactFileNameTest.kt@@ -0,0 +1,14 @@+package com.codync.android++import org.junit.Assert.assertEquals+import org.junit.Assert.assertTrue+import org.junit.Test++class ArtifactFileNameTest {+ @Test fun `a shared artifact is its title as one html file of at most 200 bytes`() {+ assertEquals("Weekly report.html", artifactFileName("Weekly report"))+ assertEquals("Q3-Q4 plan.html", artifactFileName("Q3/Q4 plan"))+ val long = artifactFileName("週報".repeat(100))+ assertTrue(long.endsWith(".html") && long.toByteArray().size <= 200)+ }+}diff --git a/apps/android/core/src/main/kotlin/com/codync/android/core/Artifact.kt b/apps/android/core/src/main/kotlin/com/codync/android/core/Artifact.ktnew file mode 100644index 00000000..79e17be2--- /dev/null+++ b/apps/android/core/src/main/kotlin/com/codync/android/core/Artifact.kt@@ -0,0 +1,84 @@+package com.codync.android.core++import kotlinx.serialization.Serializable+import kotlinx.serialization.json.JsonElement+import kotlinx.serialization.json.decodeFromJsonElement++/**+ * A self-contained HTML document a bot published for the user (`host/src/chat/artifacts.rs`). Its HTML comes from+ * `readArtifact`; publishing again under the same id replaces it and moves `updatedAt`.+ */+@Serializable data class Artifact(+ val id: String,+ val botId: String,+ val title: String,+ val size: Long,+ val sha256: String = "",+ val createdAt: Long = 0,+ val updatedAt: Long = 0,+ /** Its newest card in the bot's chat, what a message about the artifact replies to; null when no card was posted+ * (a routine run, a group chat or another bot's request). */+ val entryId: String? = null,+) {+ companion object {+ const val MAX_BYTES = 5L * 1024 * 1024++ fun decode(value: JsonElement): Artifact = WireJson.decodeFromJsonElement<Artifact>(value).also {+ require(it.id.isNotBlank() && it.botId.isNotBlank() && it.size in 0..MAX_BYTES) { "The computer sent an invalid artifact." }+ }+ }+}++/** How a message about artifact `artifactId` quotes its card (`entryId`) until the computer's own quote arrives. */+fun artifactQuote(entryId: String, botId: String, artifactId: String, title: String) = ReplyQuote(entryId, botId, "Artifact: $title", artifactId)++/** The draft of the message box under an artifact, apart from its chat's (deleting the bot drops both). */+fun artifactDraftKey(botId: String, artifactId: String) = "$botId/artifact/$artifactId"++/** The first host with artifacts and the Library. */+const val ARTIFACTS_HOST = "2.25.0"++/** Whether the computer's host has the Library; an older one has no `library` method, so the app leaves it out. */+fun hasLibrary(hostVersion: String?): Boolean = hostVersion != null && !AppVersion.isBelow(hostVersion, ARTIFACTS_HOST)++/** What an artifact card in the chat carries (`data.artifact`): the artifact and the version it announced. */+@Serializable data class ArtifactCard(val id: String, val title: String = "", val updatedAt: Long = 0)++/** An artifact's HTML as last read: `updatedAt` names the version it is. */+data class ArtifactHtml(val updatedAt: Long, val text: String)++/**+ * One computer's artifacts: their details by id (from `library`, `readArtifact` and the `artifact` events) and the HTML of the+ * ones shown, read again once a newer version is known.+ */+data class ArtifactCache(+ val details: Map<String, Artifact> = emptyMap(),+ val html: Map<String, ArtifactHtml> = emptyMap(),+ /** Why an artifact's HTML couldn't be read, until it's read again. */+ val failures: Map<String, String> = emptyMap(),+) {+ /** Older details never replace newer ones; a rename keeps `updatedAt`, so it does. */+ fun upsert(artifact: Artifact): ArtifactCache {+ val known = details[artifact.id]+ return if (known != null && known.updatedAt > artifact.updatedAt) this else copy(details = details + (artifact.id to artifact))+ }++ fun store(artifact: Artifact, text: String): ArtifactCache =+ upsert(artifact).copy(html = html + (artifact.id to ArtifactHtml(artifact.updatedAt, text)), failures = failures - artifact.id)++ fun fail(id: String, message: String): ArtifactCache = copy(failures = failures + (id to message))++ /** The newest version of an artifact known here; `announced` is the version a card names. */+ fun newest(id: String, announced: Long = 0): Long = maxOf(announced, details[id]?.updatedAt ?: 0)++ /** The HTML held is older than the newest version known, or missing. */+ fun needsRead(id: String, announced: Long = 0): Boolean = (html[id]?.updatedAt ?: -1) < newest(id, announced)++ /** A card's title: the artifact's own once it is as new as the card. */+ fun title(card: ArtifactCard): String = details[card.id]?.takeIf { it.updatedAt >= card.updatedAt }?.title ?: card.title++ /** A chat's Library: its bot's artifacts as known here (events keep them current) with the files `listed` names, newest first. */+ fun library(botId: String, listed: List<LibraryItem>): List<LibraryItem> =+ (details.values.filter { it.botId == botId }.map { LibraryItem.ArtifactItem(it.updatedAt, it) } + listed.filter { it !is LibraryItem.ArtifactItem })+ .sortedByDescending { it.at }+}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 779b3951..d37bb568 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@@ -33,6 +33,8 @@ data class Entry(val status: String? get() = data.text("status")/** Files the bot shared in this message. */val files: List<SharedFile> get() = data["files"]?.let { WireJson.decodeFromJsonElement<List<SharedFile>>(it) }.orEmpty()+ /** The artifact a bot published in this message (an artifact card), read leniently: its text stands in for it. */+ val artifact: ArtifactCard? get() = (data["artifact"] as? JsonObject)?.let { runCatching { WireJson.decodeFromJsonElement<ArtifactCard>(it) }.getOrNull() }/** Of memory and context, only a fresh conversation gets a line: memory lives in the bot's memory settings, a* summary keeps the same conversation going, and a kept handoff changed nothing. */val isChat: Boolean get() = kind in listOf("user", "permission") ||@@ -78,8 +80,9 @@ private data class EntryFields(val callSeconds: Long? = null,)@Serializable private data class PermissionChoice(val optionId: String, val name: String, val kind: String)-/** A quoted message: its entry, who wrote it (`user` or a bot id) and its text, cut short by the computer. */-@Serializable data class ReplyQuote(val id: String = "", val author: String = "", val text: String = "")+/** A quoted message: its entry, who wrote it (`user` or a bot id) and its text, cut short by the computer; `artifact` when it+ * quotes an artifact card (the message is about that artifact). */+@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")@@ -130,6 +133,8 @@ sealed interface MirrorEvent {data class EntryChanged(val entry: Entry) : MirrorEventdata class Usage(val value: JsonObject) : MirrorEventdata class Screen(val value: JsonObject) : MirrorEvent+ /** An artifact was published, updated or renamed: live only, never a checkpoint. */+ data class ArtifactChanged(val artifact: Artifact) : MirrorEventdata object Resync : MirrorEventdata object Ignored : MirrorEvent@@ -142,6 +147,8 @@ sealed interface MirrorEvent {"entry" -> EntryChanged(Entry.decode(value.getValue("entry").jsonObject))"usage" -> Usage(value.getValue("usage").jsonObject)"screen" -> Screen(value.getValue("screen").jsonObject)+ // Not in the catch-up: one this app can't read is passed over rather than fetching everything again.+ "artifact" -> runCatching { ArtifactChanged(Artifact.decode(value.getValue("artifact"))) }.getOrDefault(Ignored)"resync" -> Resync// Match the existing clients: unknown events do not advance the cursor.else -> Ignoreddiff --git a/apps/android/core/src/main/kotlin/com/codync/android/core/HostFiles.kt b/apps/android/core/src/main/kotlin/com/codync/android/core/HostFiles.ktindex 0c8e053d..4a0cb11c 100644--- a/apps/android/core/src/main/kotlin/com/codync/android/core/HostFiles.kt+++ b/apps/android/core/src/main/kotlin/com/codync/android/core/HostFiles.kt@@ -103,6 +103,34 @@ class HostFiles(private val call: suspend (String, JsonObject, Long) -> JsonElem} finally { if (!saved) folder.deleteRecursively() }}+ /**+ * An artifact's newest HTML (`readArtifact`), chunk by chunk and checked against its SHA-256. An artifact published again while+ * it was read is read again, a few times at most.+ */+ suspend fun readArtifact(botId: String, artifactId: String): Pair<Artifact, String> {+ repeat(ARTIFACT_ATTEMPTS) { readArtifactOnce(botId, artifactId)?.let { return it } }+ throw IOException("The artifact kept changing while it was read. Try again.")+ }++ /** Null when the artifact changed between chunks. */+ private suspend fun readArtifactOnce(botId: String, artifactId: String): Pair<Artifact, String>? {+ val bytes = java.io.ByteArrayOutputStream()+ var first: Artifact? = null+ do {+ val chunk = call("readArtifact", buildJsonObject { put("botId", botId); put("artifactId", artifactId); put("offset", bytes.size()) }, 60_000).jsonObject+ val artifact = Artifact.decode(chunk.getValue("artifact"))+ if (first != null && artifact.updatedAt != first.updatedAt) return null+ first = artifact+ val data = chunk["data"]?.jsonPrimitive?.contentOrNull?.let { try { Base64.getDecoder().decode(it) } catch (_: IllegalArgumentException) { null } }+ require(data != null && chunk["size"]?.jsonPrimitive?.longOrNull == artifact.size && data.size <= CHUNK_BYTES &&+ bytes.size() + data.size <= artifact.size && (data.isNotEmpty() || artifact.size == 0L)) { "The computer returned an invalid artifact chunk." }+ bytes.write(data)+ } while (bytes.size() < artifact.size)+ val artifact = checkNotNull(first)+ val digest = MessageDigest.getInstance("SHA-256").digest(bytes.toByteArray()).joinToString("") { "%02x".format(it) }+ return if (digest == artifact.sha256) artifact to bytes.toString(Charsets.UTF_8) else null+ }+/** A small text file the host prepared (a memory export), read chunk by chunk. */suspend fun readText(botId: String, id: String): String {val bytes = java.io.ByteArrayOutputStream()@@ -135,5 +163,8 @@ class HostFiles(private val call: suspend (String, JsonObject, Long) -> JsonElem} while (offset < data.size)}- companion object { const val CHUNK_BYTES = 384 * 1024 }+ companion object {+ const val CHUNK_BYTES = 384 * 1024+ private const val ARTIFACT_ATTEMPTS = 3+ }}diff --git a/apps/android/core/src/main/kotlin/com/codync/android/core/Library.kt b/apps/android/core/src/main/kotlin/com/codync/android/core/Library.ktnew file mode 100644index 00000000..b1009190--- /dev/null+++ b/apps/android/core/src/main/kotlin/com/codync/android/core/Library.kt@@ -0,0 +1,56 @@+package com.codync.android.core++import java.time.Instant+import java.time.LocalDate+import java.time.ZoneId+import kotlinx.serialization.json.JsonObject+import kotlinx.serialization.json.decodeFromJsonElement+import kotlinx.serialization.json.jsonPrimitive+import kotlinx.serialization.json.longOrNull++/**+ * One thing in a chat's Library (`host/src/chat/library.rs`), `at` when it was last published or shared: an artifact, a+ * file the bot shared (read with `readFile`) or a file the user attached (read with `readUpload`).+ */+sealed interface LibraryItem {+ val at: Long++ data class ArtifactItem(override val at: Long, val artifact: Artifact) : LibraryItem+ data class FileItem(override val at: Long, val entryId: String, val file: SharedFile) : LibraryItem+ data class AttachmentItem(override val at: Long, val entryId: String, val file: Attachment) : LibraryItem++ companion object {+ /** An item, or null for a kind this app doesn't know (or can't read): the rest of the Library still shows. */+ fun decode(value: JsonObject): LibraryItem? = runCatching {+ val at = requireNotNull(value["at"]?.jsonPrimitive?.longOrNull)+ val file = value["file"]+ when (value.text("kind")) {+ "artifact" -> ArtifactItem(at, Artifact.decode(value.getValue("artifact")))+ "file" -> FileItem(at, requireNotNull(value.text("entryId")), WireJson.decodeFromJsonElement(requireNotNull(file)))+ "attachment" -> AttachmentItem(at, requireNotNull(value.text("entryId")), WireJson.decodeFromJsonElement(requireNotNull(file)))+ else -> null+ }+ }.getOrNull()+ }+}++/** Where an item falls in the Library, by the day it was published or shared. */+enum class LibraryPeriod(val title: String) {+ Today("Today"), Yesterday("Yesterday"), ThisWeek("This week"), Earlier("Earlier");++ companion object {+ fun of(at: Long, today: LocalDate, zone: ZoneId): LibraryPeriod {+ val day = Instant.ofEpochMilli(at).atZone(zone).toLocalDate()+ return when {+ !day.isBefore(today) -> Today+ day == today.minusDays(1) -> Yesterday+ !day.isBefore(today.minusDays(6)) -> ThisWeek+ else -> Earlier+ }+ }++ /** Items already newest first, in their periods, in that order; empty periods left out. */+ fun sections(items: List<LibraryItem>, today: LocalDate = LocalDate.now(), zone: ZoneId = ZoneId.systemDefault()): List<Pair<LibraryPeriod, List<LibraryItem>>> =+ items.groupBy { of(it.at, today, zone) }.toList().sortedBy { it.first.ordinal }+ }+}diff --git a/apps/android/core/src/test/kotlin/com/codync/android/core/ArtifactTest.kt b/apps/android/core/src/test/kotlin/com/codync/android/core/ArtifactTest.ktnew file mode 100644index 00000000..7f722e0f--- /dev/null+++ b/apps/android/core/src/test/kotlin/com/codync/android/core/ArtifactTest.kt@@ -0,0 +1,139 @@+package com.codync.android.core++import java.security.MessageDigest+import java.time.LocalDate+import java.time.ZoneOffset+import java.util.Base64+import kotlinx.coroutines.runBlocking+import kotlinx.serialization.json.*+import org.junit.Assert.*+import org.junit.Test++class ArtifactTest {+ private fun artifact(id: String = "p", updatedAt: Long = 10, title: String = "Weekly report", bytes: ByteArray = ByteArray(0)) =+ Artifact(id, "bot", title, bytes.size.toLong(), sha(bytes), 1, updatedAt, "card")++ private fun sha(bytes: ByteArray) = MessageDigest.getInstance("SHA-256").digest(bytes).joinToString("") { "%02x".format(it) }++ private fun json(artifact: Artifact) = WireJson.encodeToJsonElement(Artifact.serializer(), artifact)++ @Test fun `an artifact card and a quote about an artifact read leniently`() {+ val card = Entry("e", 1, "bot", rev = 1, kind = "agent", data = buildJsonObject {+ put("text", "Artifact: Weekly report"); put("final", true)+ putJsonObject("artifact") { put("id", "p"); put("title", "Weekly report"); put("updatedAt", 10) }+ })+ assertEquals(ArtifactCard("p", "Weekly report", 10), card.artifact)+ assertNull(Entry("e", 1, "bot", rev = 1, kind = "agent", data = buildJsonObject { put("artifact", "p") }).artifact)+ val reply = Entry("r", 2, "bot", rev = 2, kind = "user", data = buildJsonObject {+ putJsonObject("replyTo") { put("id", "e"); put("author", "bot"); put("text", "Artifact: Weekly report"); put("artifact", "p") }+ })+ assertEquals("p", reply.replyTo?.artifact)+ }++ @Test fun `artifact events upsert details, and one this app can't read is passed over`() {+ val event = MirrorEvent.decode(buildJsonObject { put("type", "artifact"); put("artifact", json(artifact())) })+ assertEquals(MirrorEvent.ArtifactChanged(artifact()), event)+ val broken = buildJsonObject { put("type", "artifact"); putJsonObject("artifact") { put("id", "p") } }+ assertEquals(MirrorEvent.Ignored, MirrorEvent.decode(broken))+ }++ @Test fun `the cache keeps the newest details and reads again once a newer version is known`() {+ var cache = ArtifactCache().upsert(artifact(updatedAt = 10))+ assertTrue(cache.needsRead("p"))+ cache = cache.store(artifact(updatedAt = 10), "<h1>One</h1>")+ assertFalse(cache.needsRead("p"))+ // A card announcing a newer version, then the event bringing it.+ assertTrue(cache.needsRead("p", announced = 20))+ cache = cache.upsert(artifact(updatedAt = 20)).upsert(artifact(updatedAt = 10, title = "Stale"))+ assertEquals(20, cache.details.getValue("p").updatedAt)+ assertTrue(cache.needsRead("p"))+ // A rename keeps updatedAt and replaces the title.+ cache = cache.upsert(artifact(updatedAt = 20, title = "Renamed"))+ assertEquals("Renamed", cache.title(ArtifactCard("p", "Weekly report", 10)))+ assertEquals("Newer card", cache.title(ArtifactCard("p", "Newer card", 30)))+ cache = cache.fail("p", "offline")+ assertEquals("offline", cache.failures["p"])+ assertNull(cache.store(artifact(updatedAt = 20), "<h1>Two</h1>").failures["p"])+ }++ @Test fun `the Library holds the artifacts known here and the listed files, and skips what it can't read`() {+ val listed = buildJsonObject {+ putJsonArray("items") {+ addJsonObject { put("kind", "artifact"); put("at", 5); put("artifact", json(artifact(updatedAt = 5, title = "Old"))) }+ addJsonObject { put("kind", "file"); put("at", 30); put("entryId", "e1")+ putJsonObject("file") { put("id", "f"); put("name", "report.pdf"); put("size", 3); put("sha256", "a".repeat(64)) } }+ addJsonObject { put("kind", "attachment"); put("at", 20); put("entryId", "e2")+ putJsonObject("file") { put("id", "u"); put("name", "photo.png"); put("size", 4) } }+ addJsonObject { put("kind", "video"); put("at", 40) }+ addJsonObject { put("kind", "file"); put("at", 50) }+ }+ }.getValue("items").jsonArray.mapNotNull { LibraryItem.decode(it.jsonObject) }+ assertEquals(3, listed.size)+ // The artifact as an event left it, not as listed.+ val items = ArtifactCache().upsert(artifact(updatedAt = 25, title = "New")).upsert(artifact("x", 99).copy(botId = "other")).library("bot", listed)+ assertEquals(listOf(30L, 25L, 20L), items.map { it.at })+ assertEquals("New", (items[1] as LibraryItem.ArtifactItem).artifact.title)+ assertEquals(SharedFile("f", "report.pdf", 3, "a".repeat(64)), (items[0] as LibraryItem.FileItem).file)+ assertEquals("e2", (items[2] as LibraryItem.AttachmentItem).entryId)+ }++ @Test fun `the Library groups items by the day they were published or shared`() {+ val today = LocalDate.of(2026, 10, 24)+ fun at(day: LocalDate, hour: Int) = day.atTime(hour, 0).toInstant(ZoneOffset.UTC).toEpochMilli()+ val items = listOf(at(today, 9), at(today.minusDays(1), 23), at(today.minusDays(6), 0), at(today.minusDays(7), 23))+ .map { LibraryItem.ArtifactItem(it, artifact(updatedAt = it)) }+ val sections = LibraryPeriod.sections(items, today, ZoneOffset.UTC)+ assertEquals(listOf(LibraryPeriod.Today, LibraryPeriod.Yesterday, LibraryPeriod.ThisWeek, LibraryPeriod.Earlier), sections.map { it.first })+ assertTrue(sections.all { it.second.size == 1 })+ }++ /** Serves the versions in turn as readArtifact does: one chunk per call, the version moving on after `switchAfter` calls. */+ private fun host(vararg versions: Pair<Artifact, ByteArray>, switchAfter: Int = Int.MAX_VALUE, corrupt: Boolean = false): Pair<HostFiles, () -> Int> {+ var calls = 0+ val files = HostFiles { method, body, _ ->+ assertEquals("readArtifact", method)+ assertEquals("p", body.getValue("artifactId").jsonPrimitive.content)+ val (artifact, bytes) = versions[minOf(calls++ / switchAfter, versions.size - 1)]+ val offset = body.getValue("offset").jsonPrimitive.long.toInt()+ val end = minOf(offset + HostFiles.CHUNK_BYTES, bytes.size)+ val data = if (corrupt) bytes.copyOfRange(offset, end).reversedArray() else bytes.copyOfRange(offset, end)+ buildJsonObject { put("data", Base64.getEncoder().encodeToString(data)); put("size", bytes.size); put("artifact", json(artifact)) }+ }+ return files to { calls }+ }++ @Test fun `messages about an artifact quote its card, from a draft of their own, on a host with the Library`() {+ assertEquals(ReplyQuote("e", "bot", "Artifact: Weekly report", "p"), artifactQuote("e", "bot", "p", "Weekly report"))+ assertEquals("bot/artifact/p", artifactDraftKey("bot", "p"))+ assertTrue(hasLibrary("2.25.0"))+ assertFalse(hasLibrary("2.24.3"))+ assertFalse(hasLibrary(null))+ }++ @Test fun `an artifact is read in chunks and checked`() = runBlocking {+ val html = "<h1>Weekly report</h1>".repeat(40_000).toByteArray()+ val (files, calls) = host(artifact(bytes = html) to html)+ val (read, text) = files.readArtifact("bot", "p")+ assertEquals(artifact(bytes = html), read)+ assertEquals(String(html), text)+ assertEquals(3, calls())+ val empty = ByteArray(0)+ assertEquals("", host(artifact(bytes = empty) to empty).first.readArtifact("bot", "p").second)+ }++ @Test fun `an artifact published again while it is read is read again`() = runBlocking {+ val one = "a".repeat(HostFiles.CHUNK_BYTES + 1).toByteArray()+ val two = "b".repeat(HostFiles.CHUNK_BYTES + 5).toByteArray()+ val (files, _) = host(artifact(bytes = one) to one, artifact(updatedAt = 20, bytes = two) to two, switchAfter = 1)+ val (read, text) = files.readArtifact("bot", "p")+ assertEquals(20, read.updatedAt)+ assertEquals(String(two), text)+ }++ @Test fun `an artifact whose HTML never matches its hash or whose chunk is invalid fails`() {+ val html = "<p>Updated</p>".toByteArray()+ assertFails<java.io.IOException> { runBlocking { host(artifact(bytes = html) to html, corrupt = true).first.readArtifact("bot", "p") } }+ val bad = HostFiles { _, _, _ -> buildJsonObject { put("data", "%%%"); put("size", 3); put("artifact", json(artifact().copy(size = 3))) } }+ assertFails<IllegalArgumentException> { runBlocking { bad.readArtifact("bot", "p") } }+ }+}diff --git a/apps/android/design/src/main/kotlin/com/codync/android/design/Dialog.kt b/apps/android/design/src/main/kotlin/com/codync/android/design/Dialog.ktindex 92372eb6..0dfe1784 100644--- a/apps/android/design/src/main/kotlin/com/codync/android/design/Dialog.kt+++ b/apps/android/design/src/main/kotlin/com/codync/android/design/Dialog.kt@@ -10,6 +10,7 @@ import androidx.compose.foundation.layout.Boximport androidx.compose.foundation.layout.Columnimport androidx.compose.foundation.layout.fillMaxSizeimport androidx.compose.foundation.layout.fillMaxWidth+import androidx.compose.foundation.layout.imePaddingimport androidx.compose.foundation.layout.paddingimport androidx.compose.foundation.layout.widthInimport androidx.compose.material3.Text@@ -39,10 +40,10 @@ class DialogAction(val title: String, val destructive: Boolean = false, val acti/*** A centered card over a dimmed screen with the actions and Cancel: the replacement for- * `confirmationDialog` and `alert`.+ * `confirmationDialog` and `alert`. `field`: what the user types for the actions (an alert's text field).*/@Composable fun CodyncDialog(title: String, isPresented: Boolean, onDismiss: () -> Unit, message: String? = null,- cancel: String? = "Cancel", actions: () -> List<DialogAction>) {+ cancel: String? = "Cancel", field: (@Composable () -> Unit)? = null, actions: () -> List<DialogAction>) {val shown = remember { Animatable(0f) }var mounted by remember { mutableStateOf(isPresented) }val focus = LocalFocusManager.current@@ -57,7 +58,7 @@ class DialogAction(val title: String, val destructive: Boolean = false, val actiOverlay {Box(Modifier.fillMaxSize().graphicsLayer { alpha = shown.value }.background(Color.Black.copy(alpha = 0.35f)).clickable(remember { MutableInteractionSource() }, null) { if (cancel != null) dismiss() }- .padding(24.dp), contentAlignment = Alignment.Center) {+ .imePadding().padding(24.dp), contentAlignment = Alignment.Center) {Column(Modifier.widthIn(max = 320.dp).fillMaxWidth().graphicsLayer { val s = 0.96f + 0.04f * shown.value; scaleX = s; scaleY = s; shadowElevation = 24f; shape = RoundedRectangle(22.dp); clip = true }.background(Palette.bubbleAgent).clickable(remember { MutableInteractionSource() }, null) {}@@ -67,6 +68,7 @@ class DialogAction(val title: String, val destructive: Boolean = false, val actiText(tr(title), style = Type.headline, color = Palette.text, textAlign = TextAlign.Center)if (!message.isNullOrEmpty()) Text(tr(message), style = Type.subheadline, color = Palette.secondary, textAlign = TextAlign.Center)}+ field?.invoke()Column(verticalArrangement = Arrangement.spacedBy(8.dp)) {for (action in actions()) DialogButton(tr(action.title), action.destructive, prominent = true) { dismiss(); action.action() }if (cancel != null) DialogButton(tr(cancel), destructive = false, prominent = false) { dismiss() }diff --git a/apps/android/design/src/main/kotlin/com/codync/android/design/Symbols.kt b/apps/android/design/src/main/kotlin/com/codync/android/design/Symbols.ktindex 10932981..0ecd493e 100644--- a/apps/android/design/src/main/kotlin/com/codync/android/design/Symbols.kt+++ b/apps/android/design/src/main/kotlin/com/codync/android/design/Symbols.kt@@ -32,12 +32,14 @@ import androidx.annotation.DrawableRes"bolt" -> R.drawable.sf_bolt"book.fill" -> R.drawable.sf_book_fill"book.pages" -> R.drawable.sf_book_pages+ "books.vertical" -> R.drawable.sf_books_vertical"brain" -> R.drawable.sf_brain"bubble.left.and.bubble.right" -> R.drawable.sf_bubble_left_and_bubble_right"bubble.left.and.bubble.right.fill" -> R.drawable.sf_bubble_left_and_bubble_right_fill"calendar" -> R.drawable.sf_calendar"camera.fill" -> R.drawable.sf_camera_fill"chart.bar" -> R.drawable.sf_chart_bar+ "chart.bar.doc.horizontal" -> R.drawable.sf_chart_bar_doc_horizontal"checklist" -> R.drawable.sf_checklist"checkmark" -> R.drawable.sf_checkmark"checkmark.circle" -> R.drawable.sf_checkmark_circlediff --git a/apps/android/design/src/main/res/drawable/sf_books_vertical.xml b/apps/android/design/src/main/res/drawable/sf_books_vertical.xmlnew file mode 100644index 00000000..9e96bf68--- /dev/null+++ b/apps/android/design/src/main/res/drawable/sf_books_vertical.xml@@ -0,0 +1,8 @@+<?xml version="1.0" encoding="utf-8"?>+<!-- Material Symbols Rounded `library_books`, Generated by tools/symbols.py. -->+<vector xmlns:android="http://schemas.android.com/apk/res/android"+ android:width="24dp" android:height="24dp" android:viewportWidth="960" android:viewportHeight="960">+ <group android:translateY="960">+ <path android:fillColor="#FF000000" android:pathData="M442.87-401.2h81.2q17.47 0 29.45-11.97 11.98-11.98 11.98-29.46t-11.98-29.46q-11.98-11.98-29.45-11.98h-81.2q-17.48 0-29.46 11.98t-11.98 29.46q0 17.48 11.98 29.46 11.98 11.97 29.46 11.97Zm-.09-122.87h245.44q17.39 0 29.37-11.97 11.98-11.98 11.98-29.46t-11.98-29.46q-11.98-11.97-29.37-11.97H442.78q-17.39 0-29.37 11.97-11.98 11.98-11.98 29.46t11.98 29.46q11.98 11.97 29.37 11.97Zm0-122.86h245.44q17.39 0 29.37-11.98t11.98-29.46q0-17.48-11.98-29.46-11.98-11.97-29.37-11.97H442.78q-17.39 0-29.37 11.97-11.98 11.98-11.98 29.46t11.98 29.46q11.98 11.98 29.37 11.98ZM328.37-237.37q-37.78 0-64.39-26.61t-26.61-64.39v-474.26q0-37.78 26.61-64.39t64.39-26.61h474.26q37.78 0 64.39 26.61t26.61 64.39v474.26q0 37.78-26.61 64.39t-64.39 26.61H328.37Zm0-91h474.26v-474.26H328.37v474.26Zm-171 262q-37.78 0-64.39-26.61t-26.61-64.39v-519.76q0-19.15 13.17-32.33 13.18-13.17 32.33-13.17t32.33 13.17q13.17 13.18 13.17 32.33v519.76h519.76q19.15 0 32.33 13.17 13.17 13.18 13.17 32.33t-13.17 32.33q-13.18 13.17-32.33 13.17H157.37Zm171-736.26v474.26-474.26Z"/>+ </group>+</vector>diff --git a/apps/android/design/src/main/res/drawable/sf_chart_bar_doc_horizontal.xml b/apps/android/design/src/main/res/drawable/sf_chart_bar_doc_horizontal.xmlnew file mode 100644index 00000000..c6ea245d--- /dev/null+++ b/apps/android/design/src/main/res/drawable/sf_chart_bar_doc_horizontal.xml@@ -0,0 +1,8 @@+<?xml version="1.0" encoding="utf-8"?>+<!-- Material Symbols Rounded `lab_profile`, Generated by tools/symbols.py. -->+<vector xmlns:android="http://schemas.android.com/apk/res/android"+ android:width="24dp" android:height="24dp" android:viewportWidth="960" android:viewportHeight="960">+ <group android:translateY="960">+ <path android:fillColor="#FF000000" android:pathData="M360-480q-17 0-28.5-11.5T320-520q0-17 11.5-28.5T360-560h240q17 0 28.5 11.5T640-520q0 17-11.5 28.5T600-480H360Zm0-160q-17 0-28.5-11.5T320-680q0-17 11.5-28.5T360-720h240q17 0 28.5 11.5T640-680q0 17-11.5 28.5T600-640H360ZM242.87-405.5h292.35q30.3 0 56.42 13.06t43.88 37.09l81.61 106.65v-548.43H242.87v391.63Zm0 242.63h425.26L563.91-299.65q-5.21-6.99-12.61-10.92-7.39-3.93-16.08-3.93H242.87v151.63Zm474.26 91H242.87q-37.78 0-64.39-26.61t-26.61-64.39v-634.26q0-37.78 26.61-64.39t64.39-26.61h474.26q37.78 0 64.39 26.61t26.61 64.39v634.26q0 37.78-26.61 64.39t-64.39 26.61Zm-474.26-91v-634.26 634.26Zm0-151.63v-91 91Z"/>+ </group>+</vector>diff --git a/apps/android/tools/symbols.py b/apps/android/tools/symbols.pyindex f629449f..e71c80d0 100644--- a/apps/android/tools/symbols.py+++ b/apps/android/tools/symbols.py@@ -43,12 +43,14 @@ MAP = {"bolt": "bolt","book.fill": "book+","book.pages": "menu_book",+ "books.vertical": "library_books","brain": "psychology","bubble.left.and.bubble.right": "forum","bubble.left.and.bubble.right.fill": "forum+","calendar": "calendar_today","camera.fill": "photo_camera+","chart.bar": "bar_chart",+ "chart.bar.doc.horizontal": "lab_profile","checklist": "checklist","checkmark": "check","checkmark.circle": "check_circle",diff --git a/apps/desktop/src/main/artifacts.ts b/apps/desktop/src/main/artifacts.tsnew file mode 100644index 00000000..9dc6076e--- /dev/null+++ b/apps/desktop/src/main/artifacts.ts@@ -0,0 +1,59 @@+import { mkdir, writeFile } from 'node:fs/promises'+import { join } from 'node:path'+import { app, ipcMain, protocol, shell, type WebContents } from 'electron'++/**+ * Artifacts (a bot's HTML documents, `docs/features/artifacts.md`) shown in the chat window. Each loads from+ * `codync-artifact://<id>`: an origin of its own, apart from the app's, whose scripts run (the window's content+ * security policy would block them in a `srcdoc` frame). The renderer hands over the HTML it read from the host.+ */+const SCHEME = 'codync-artifact'+const KEPT = 50+const shown = new Map<string, Uint8Array>()++/** Before the app is ready. */+export function registerArtifactScheme() {+ protocol.registerSchemesAsPrivileged([{ scheme: SCHEME, privileges: { standard: true, secure: true } }])+}++export function registerArtifacts() {+ protocol.handle(SCHEME, (request) => {+ const html = shown.get(new URL(request.url).hostname)+ if (html === undefined) return new Response('', { status: 404 })+ return new Response(html as Uint8Array<ArrayBuffer>, { headers: { 'content-type': 'text/html; charset=utf-8' } })+ })+ ipcMain.handle('artifacts:show', (_e, id: string, html: Uint8Array) => {+ check(id, html)+ shown.delete(id)+ shown.set(id, html)+ // The least recently shown go first.+ for (const old of shown.keys()) if (shown.size > KEPT) shown.delete(old)+ })+ ipcMain.handle('artifacts:openInBrowser', async (_e, id: string, html: Uint8Array) => {+ check(id, html)+ const folder = join(app.getPath('temp'), 'codync-artifacts')+ await mkdir(folder, { recursive: true })+ const path = join(folder, `${id}.html`)+ await writeFile(path, html)+ const failed = await shell.openPath(path)+ if (failed) throw new Error(failed)+ })+}++function check(id: string, html: Uint8Array) {+ if (!/^[0-9a-f-]{36}$/.test(id) || !(html instanceof Uint8Array)) throw new Error('Invalid artifact')+}++/** A link followed in an artifact opens in the browser; the artifact stays (frames inside it go where they go). */+export function keepArtifactsInFrame(contents: WebContents) {+ contents.on('will-frame-navigate', (event) => {+ if (!event.frame?.url.startsWith(`${SCHEME}:`) || event.url.startsWith(`${SCHEME}:`)) return+ event.preventDefault()+ openWebLink(event.url)+ })+}++/** A web or mail link opens in the system's app for it; any other scheme (an app's, a file share's) goes nowhere. */+export function openWebLink(url: string) {+ if (/^(https?|mailto):/.test(url)) void shell.openExternal(url)+}diff --git a/apps/desktop/src/main/index.ts b/apps/desktop/src/main/index.tsindex 055ae2a1..114b669a 100644--- a/apps/desktop/src/main/index.ts+++ b/apps/desktop/src/main/index.ts@@ -7,6 +7,7 @@ import { app, autoUpdater, BrowserWindow, clipboard, dialog, ipcMain, Menu, natiimport type { HostSnapshot, WindowCommand } from '../shared/ipc'import { devPort, HostController } from './host-controller'import { registerFileSaves } from './file-saves'+import { keepArtifactsInFrame, openWebLink, registerArtifacts, registerArtifactScheme } from './artifacts'import { registerHostProxy } from './host-proxy'import { readClipboardFiles, readFiles } from './files'import { Tray } from './tray'@@ -85,8 +86,10 @@ function openChat() {// Closing hides: the window keeps the stores (and the menu bar's data) alive.chat.on('close', (e) => quitLifecycle.closeToBackground(e, () => chat?.hide()))chat.on('closed', () => (chat = null))+ keepArtifactsInFrame(chat.webContents)+ // A new window (an artifact's target=_blank link or window.open, too) opens in the browser instead.chat.webContents.setWindowOpenHandler(({ url }) => {- void shell.openExternal(url)+ openWebLink(url)return { action: 'deny' }})void chat.loadURL(rendererURL('chat'))@@ -153,6 +156,7 @@ function registerIPC(tray: Tray) {ipcMain.on('app:name', (e) => (e.returnValue = app.getName()))ipcMain.on('app:scheme', (e) => (e.returnValue = identity.scheme))registerFileSaves()+ registerArtifacts()ipcMain.on('app:version', (e) => (e.returnValue = app.getVersion()))ipcMain.on('app:computerName', (e) => (e.returnValue = computerName()))ipcMain.on('app:openedAtLogin', (e) => (e.returnValue = openedAtLogin()))@@ -209,6 +213,7 @@ if (yieldsToInstall()) {app.quit()} else {registerSchemes()+ registerArtifactScheme()app.on('second-instance', (_e, argv) => {const url = urlFromArgv(argv)if (url) handleURL(url)diff --git a/apps/desktop/src/preload/index.ts b/apps/desktop/src/preload/index.tsindex 3f65b225..d9506b68 100644--- a/apps/desktop/src/preload/index.ts+++ b/apps/desktop/src/preload/index.ts@@ -98,6 +98,10 @@ const bridge: CodyncBridge = {setAutoCheck: (on) => ipcRenderer.send('updates:autoCheck', on),setAutoDownload: (on) => ipcRenderer.send('updates:autoDownload', on),},+ artifacts: {+ show: (id, html) => ipcRenderer.invoke('artifacts:show', id, html),+ openInBrowser: (id, html) => ipcRenderer.invoke('artifacts:openInBrowser', id, html),+ },files: {begin: (file) => ipcRenderer.invoke('files:begin', file),write: (id, offset, data) => ipcRenderer.invoke('files:write', id, offset, data),diff --git a/apps/desktop/src/renderer/client/host-client.ts b/apps/desktop/src/renderer/client/host-client.tsindex e9061058..a2b7152f 100644--- a/apps/desktop/src/renderer/client/host-client.ts+++ b/apps/desktop/src/renderer/client/host-client.ts@@ -10,6 +10,7 @@ import {type ScreenState,type Usage,} from '@shared/models'+import type { Artifact, ArtifactChunk, LibraryItem } from '@shared/artifacts'/** How a client reaches a host API. Only loopback today: the computer's own host or an SSH tunnel. */export type HostRoute = 'loopback' | 'direct' | 'relay'@@ -66,6 +67,8 @@ export type HostEvent =| { type: 'botDeleted'; id: string; rev: number }| { type: 'entry'; entry: Entry }| { type: 'usage'; usage: Usage }+ /** An artifact was published, updated or renamed (not part of catch-up: apps fetch the `library` when they show it). */+ | { type: 'artifact'; artifact: Artifact }| { type: 'screen'; screen: ScreenState }| { type: 'accessRequests'; requests: AccessRequest[] }| { type: 'cloud'; cloud: CloudStatus }@@ -103,6 +106,10 @@ export function parseEvent(line: string): HostEvent | null {}case 'usage':return raw.usage ? { type, usage: raw.usage as Usage } : null+ case 'artifact': {+ const artifact = raw.artifact as Artifact | undefined+ return artifact && typeof artifact.id === 'string' && typeof artifact.botId === 'string' ? { type, artifact } : null+ }case 'screen': {const screen = normalizeScreen(raw.screen as ScreenState | undefined)return screen ? { type, screen } : null@@ -124,6 +131,18 @@ export class HostClient {return this.call('readFile', { entryId, fileId, offset })}+ library(botId: string): Promise<{ items: LibraryItem[] }> {+ return this.call('library', { botId })+ }++ readArtifact(botId: string, artifactId: string, offset: number): Promise<ArtifactChunk> {+ return this.call('readArtifact', { botId, artifactId, offset })+ }++ renameArtifact(botId: string, artifactId: string, title: string): Promise<{ artifact: Artifact }> {+ return this.call('renameArtifact', { botId, artifactId, title })+ }+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 fd881660..4013680e 100644--- a/apps/desktop/src/renderer/components/icon-fallbacks.ts+++ b/apps/desktop/src/renderer/components/icon-fallbacks.ts@@ -48,6 +48,7 @@ const map: Record<string, IconNode> = {'bubble.left.and.bubble.right': L.MessagesSquare,calendar: L.Calendar,'chart.bar': L.ChartColumn,+ 'chart.bar.doc.horizontal': L.FileChartColumn,checklist: L.ListChecks,checkmark: L.Check,'checkmark.circle': L.CircleCheck,diff --git a/apps/desktop/src/renderer/components/symbols.json b/apps/desktop/src/renderer/components/symbols.jsonindex f5ba6f6e..40213182 100644--- a/apps/desktop/src/renderer/components/symbols.json+++ b/apps/desktop/src/renderer/components/symbols.json@@ -31,6 +31,7 @@"bubble.left.and.bubble.right","calendar","chart.bar",+"chart.bar.doc.horizontal","checklist","checkmark","checkmark.circle",diff --git a/apps/desktop/src/renderer/demo/bridge.ts b/apps/desktop/src/renderer/demo/bridge.tsindex 0c97badf..c84ad740 100644--- a/apps/desktop/src/renderer/demo/bridge.ts+++ b/apps/desktop/src/renderer/demo/bridge.ts@@ -90,6 +90,7 @@ const bridge: CodyncBridge = {},cloud: { request: async () => ({ ok: false, error: { status: 503, code: 'demo', message: DEMO_UNAVAILABLE } }) },updates: { state: async () => updates, onChange: none, check() {}, install() {}, setAutoCheck() {}, setAutoDownload() {} },+ artifacts: { show: async () => {}, openInBrowser: unavailable },files: { begin: unavailable, write: async () => {}, finish: async () => {}, cancel: async () => {} },app: {reportError() {},diff --git a/apps/desktop/src/renderer/index.html b/apps/desktop/src/renderer/index.htmlindex 913c7a6a..90ebe63e 100644--- a/apps/desktop/src/renderer/index.html+++ b/apps/desktop/src/renderer/index.html@@ -2,7 +2,7 @@<html lang="en"><head><meta charset="UTF-8" />- <meta http-equiv="Content-Security-Policy" content="default-src 'self'; img-src 'self' data: blob: https:; style-src 'self' 'unsafe-inline'; connect-src 'self' https: wss:; media-src 'self' blob: data:" />+ <meta http-equiv="Content-Security-Policy" content="default-src 'self'; img-src 'self' data: blob: https:; style-src 'self' 'unsafe-inline'; connect-src 'self' https: wss:; media-src 'self' blob: data:; frame-src codync-artifact:" /><title>Codync</title></head><body>diff --git a/apps/desktop/src/renderer/lib/library-groups.test.ts b/apps/desktop/src/renderer/lib/library-groups.test.tsnew file mode 100644index 00000000..b8bda7f0--- /dev/null+++ b/apps/desktop/src/renderer/lib/library-groups.test.ts@@ -0,0 +1,14 @@+import assert from 'node:assert/strict'+import { test } from 'node:test'+import { libraryGroups } from './library-groups.ts'++test('the library groups by the day things were published or sent', () => {+ const now = new Date(2026, 9, 24, 16, 40).getTime()+ const at = (day: number, hour = 9) => ({ at: new Date(2026, 9, day, hour).getTime() })+ const items = [at(24, 16), at(24, 0), at(23, 23), at(18), at(17, 23), at(1)]+ assert.deepEqual(+ libraryGroups(items, now).map((g) => [g.group, g.items.length]),+ [['Today', 2], ['Yesterday', 1], ['This week', 1], ['Earlier', 2]],+ )+ assert.deepEqual(libraryGroups([], now), [])+})diff --git a/apps/desktop/src/renderer/lib/library-groups.ts b/apps/desktop/src/renderer/lib/library-groups.tsnew file mode 100644index 00000000..60bd5101--- /dev/null+++ b/apps/desktop/src/renderer/lib/library-groups.ts@@ -0,0 +1,24 @@+/** Where something falls in a chat's Library (Grok Bot's), by when it was published or sent. */+export type LibraryGroup = 'Today' | 'Yesterday' | 'This week' | 'Earlier'++const DAY = 24 * 60 * 60 * 1000++export function libraryGroup(at: number, now = Date.now()): LibraryGroup {+ const today = new Date(now).setHours(0, 0, 0, 0)+ if (at >= today) return 'Today'+ if (at >= today - DAY) return 'Yesterday'+ if (at >= today - 6 * DAY) return 'This week'+ return 'Earlier'+}++/** Items already newest first, in their groups, in that order. */+export function libraryGroups<T extends { at: number }>(items: T[], now = Date.now()): { group: LibraryGroup; items: T[] }[] {+ const groups: { group: LibraryGroup; items: T[] }[] = []+ for (const item of items) {+ const group = libraryGroup(item.at, now)+ const last = groups[groups.length - 1]+ if (last?.group === group) last.items.push(item)+ else groups.push({ group, items: [item] })+ }+ return groups+}diff --git a/apps/desktop/src/renderer/store/artifacts.ts b/apps/desktop/src/renderer/store/artifacts.tsnew file mode 100644index 00000000..99ce03bc--- /dev/null+++ b/apps/desktop/src/renderer/store/artifacts.ts@@ -0,0 +1,106 @@+import { readArtifactHTML, type Artifact, type LibraryItem } from '@shared/artifacts'+import { FILE_CHUNK_SIZE } from '../../shared/files.ts'+import type { HostClient } from '../client/host-client'++/** An artifact's HTML as last read; `updatedAt` and `sha256` name the version it is. */+export interface ArtifactHTML { updatedAt: number; sha256: string; bytes: Uint8Array }++/**+ * One computer's artifacts (`host/src/chat/artifacts.rs`): their details by id, from `library`, `readArtifact` and the `artifact`+ * events, and the HTML of each one shown, read again once a newer version is published.+ */+export class Artifacts {+ readonly byId = new Map<string, Artifact>()+ readonly html = new Map<string, ArtifactHTML>()+ readonly failed = new Map<string, string>()+ private reading = new Map<string, Promise<ArtifactHTML>>()+ private changed: () => void+ constructor(changed: () => void) { this.changed = changed }++ upsert(artifact: Artifact) {+ const known = this.byId.get(artifact.id)+ if (known && known.updatedAt > artifact.updatedAt) return+ this.byId.set(artifact.id, artifact)+ this.changed()+ }++ /** The chat's Library (`library`); its artifacts join the ones known here. */+ async library(client: HostClient | null, botId: string): Promise<LibraryItem[]> {+ if (!client) throw new Error('Connect to this computer to see its library')+ const { items } = await client.library(botId)+ for (const item of items) if (item.kind === 'artifact') this.upsert(item.artifact)+ return items+ }++ /** Reads the artifact's HTML in the background unless the newest version known is already here; a failure shows. */+ load(client: HostClient | null, botId: string, id: string, updatedAt = 0) {+ if (this.current(id, updatedAt) || this.reading.has(id) || !client) return+ this.failed.delete(id)+ this.fetch(client, botId, id).catch((error: unknown) => {+ this.failed.set(id, error instanceof Error ? error.message : String(error))+ this.changed()+ })+ }++ async rename(client: HostClient | null, botId: string, id: string, title: string) {+ if (!client) throw new Error('Connect to this computer to rename the artifact')+ this.upsert((await client.renameArtifact(botId, id, title)).artifact)+ }++ /** Saves the artifact's newest HTML where the user picks (the native Save dialog). */+ async save(client: HostClient | null, artifact: Artifact) {+ const html = await this.newest(client, artifact)+ const title = this.byId.get(artifact.id)?.title ?? artifact.title+ const name = `${title.replace(/[/\\\x00-\x1f\x7f]/g, '-').slice(0, 190)}.html`+ const handle = await window.codync.files.begin({ id: artifact.id, name, size: html.bytes.length, sha256: html.sha256 })+ if (!handle) return+ try {+ for (let offset = 0; offset < html.bytes.length; offset += FILE_CHUNK_SIZE) {+ await window.codync.files.write(handle, offset, html.bytes.subarray(offset, offset + FILE_CHUNK_SIZE))+ }+ await window.codync.files.finish(handle)+ } finally {+ await window.codync.files.cancel(handle).catch(console.error)+ }+ }++ /** Opens the artifact's newest HTML in this computer's browser. */+ async openInBrowser(client: HostClient | null, artifact: Artifact) {+ await window.codync.artifacts.openInBrowser(artifact.id, (await this.newest(client, artifact)).bytes)+ }++ /** The artifact's newest HTML, read when it isn't here yet. */+ private async newest(client: HostClient | null, artifact: Artifact): Promise<ArtifactHTML> {+ const cached = this.html.get(artifact.id)+ if (cached && this.current(artifact.id)) return cached+ if (!client) throw new Error('Connect to this computer to open the artifact')+ return this.fetch(client, artifact.botId, artifact.id)+ }++ private current(id: string, updatedAt = 0) {+ const newest = Math.max(updatedAt, this.byId.get(id)?.updatedAt ?? 0)+ return (this.html.get(id)?.updatedAt ?? -1) >= newest+ }++ /** One read of an artifact at a time; callers share it. */+ private fetch(client: HostClient, botId: string, id: string): Promise<ArtifactHTML> {+ const running = this.reading.get(id)+ if (running) return running+ const read = this.read(client, botId, id).finally(() => {+ this.reading.delete(id)+ this.changed()+ })+ this.reading.set(id, read)+ return read+ }++ private async read(client: HostClient, botId: string, id: string): Promise<ArtifactHTML> {+ const { artifact, bytes } = await readArtifactHTML((offset) => client.readArtifact(botId, id, offset))+ const read = { updatedAt: artifact.updatedAt, sha256: artifact.sha256, bytes }+ this.html.set(id, read)+ this.upsert(artifact)+ // A newer version published while this one was read is read next.+ if (!this.current(id)) setTimeout(() => this.load(client, botId, id))+ return read+ }+}diff --git a/apps/desktop/src/renderer/store/bot-sync.ts b/apps/desktop/src/renderer/store/bot-sync.tsindex 6075a92c..f3640bd8 100644--- a/apps/desktop/src/renderer/store/bot-sync.ts+++ b/apps/desktop/src/renderer/store/bot-sync.ts@@ -2,6 +2,7 @@ import { isChat, type AccessRequest, type CloudStatus, type Entry } from '@shareimport { isOutsideLoadedWindow, snapshotFloors } from '@shared/mirror-window'import { HostClient, HostError, type HostEvent } from '../client/host-client'import { BotMirror, type Connection } from './bot-mirror'+import { Artifacts } from './artifacts'const DROP_GRACE = 5000const INITIAL_GRACE = 1000@@ -26,6 +27,7 @@ function keptEntries(entries: Map<string, Entry[]>, keep: (e: Entry) => boolean)* graces, waiting for the link before an action, and read acknowledgements.*/export class BotSync extends BotMirror {+ readonly artifacts = new Artifacts(() => this.changed())private heldDrop: Connection | null = nullprivate dropTimer: ReturnType<typeof setTimeout> | null = nullprivate closeEvents: (() => void) | null = null@@ -219,6 +221,9 @@ export class BotSync extends BotMirror {case 'usage':this.usage = event.usagebreak+ case 'artifact':+ this.artifacts.upsert(event.artifact)+ breakcase 'screen':this.screen = event.screenbreakdiff --git a/apps/desktop/src/renderer/views/library/ArtifactCard.tsx b/apps/desktop/src/renderer/views/library/ArtifactCard.tsxnew file mode 100644index 00000000..cc9704bb--- /dev/null+++ b/apps/desktop/src/renderer/views/library/ArtifactCard.tsx@@ -0,0 +1,31 @@+import { useEffect } from 'react'+import type { ArtifactCard as Card } from '@shared/artifacts'+import { Icon } from '../../components/Icon'+import { HStack, VStack } from '../../components/Stack'+import { Text } from '../../components/Text'+import { useTr } from '../../lib/use-language'+import { useStore } from '../../store/context'+import { ArtifactFrame } from './ArtifactParts'++/** An artifact in the chat (Grok Bot's artifact card): the top of its newest version over its title. Opens the artifact. */+export function ArtifactCard({ botId, card, open }: { botId: string; card: Card; open: () => void }) {+ const tr = useTr()+ const store = useStore()+ const artifact = store.artifacts.byId.get(card.id)+ const html = store.artifacts.html.get(card.id)+ const title = artifact?.title ?? card.title+ const newest = artifact?.updatedAt+ useEffect(() => store.artifacts.load(store.client, botId, card.id, card.updatedAt), [store, store.client, botId, card.id, card.updatedAt, newest])+ return (+ <button className="artifact-card" onClick={open} aria-label={`${title}, ${tr('Artifact')}`}>+ <div className="artifact-card-preview">{html ? <ArtifactFrame id={card.id} html={html} title={title} preview /> : null}</div>+ <HStack gap={12} className="artifact-card-footer">+ <Icon name="chart.bar.doc.horizontal" size={26} color="var(--secondary)" />+ <VStack shrink>+ <Text size="subheadline" weight="semibold" truncate>{title}</Text>+ <Text size="caption" tone="secondary">{tr('Artifact')}</Text>+ </VStack>+ </HStack>+ </button>+ )+}diff --git a/apps/desktop/src/renderer/views/library/ArtifactParts.tsx b/apps/desktop/src/renderer/views/library/ArtifactParts.tsxnew file mode 100644index 00000000..5de852e3--- /dev/null+++ b/apps/desktop/src/renderer/views/library/ArtifactParts.tsx@@ -0,0 +1,80 @@+import { useEffect, useRef, useState } from 'react'+import type { Artifact } from '@shared/artifacts'+import type { MenuItem } from '../../components/Overlay'+import type { BotStore } from '../../store/bot-store'+import type { ArtifactHTML } from '../../store/artifacts'+import { useTr } from '../../lib/use-language'+import './library.css'++/**+ * An artifact in a frame of its own origin (`main/artifacts.ts`): the whole artifact, or for a card its top, scaled down and+ * out of reach of the pointer.+ */+export function ArtifactFrame({ id, html, title, preview = false }: { id: string; html: ArtifactHTML; title: string; preview?: boolean }) {+ const [shown, setShown] = useState<number | null>(null)+ useEffect(() => {+ let live = true+ void window.codync.artifacts.show(id, html.bytes).then(() => live && setShown(html.updatedAt), console.error)+ return () => {+ live = false+ }+ }, [id, html])+ if (shown === null) return null+ return (+ <iframe+ className={preview ? 'artifact-frame preview' : 'artifact-frame'}+ src={`codync-artifact://${id}/?v=${shown}`}+ title={title}+ // Its own origin already keeps it from the app; same-origin lets the artifact keep its own storage.+ sandbox="allow-scripts allow-same-origin allow-forms allow-popups allow-popups-to-escape-sandbox allow-downloads"+ tabIndex={preview ? -1 : undefined}+ aria-hidden={preview || undefined}+ loading="lazy"+ />+ )+}++/** A title being edited in place: Return keeps it, Escape leaves it as it was. */+export function TitleField({ initial, className, done }: { initial: string; className: string; done: (title: string | null) => void }) {+ const tr = useTr()+ const [draft, setDraft] = useState(initial)+ const finished = useRef(false)+ const finish = (title: string | null) => {+ if (finished.current) return+ finished.current = true+ done(title && title !== initial ? title : null)+ }+ return (+ <input+ className={className}+ autoFocus+ value={draft}+ maxLength={200}+ aria-label={tr('Artifact title')}+ placeholder={tr('Artifact title')}+ onFocus={(e) => e.currentTarget.select()}+ onChange={(e) => setDraft(e.target.value)}+ onBlur={() => finish(draft.trim())}+ onKeyDown={(e) => {+ if (e.key === 'Enter') finish(draft.trim())+ if (e.key === 'Escape') finish(null)+ }}+ />+ )+}++const errorText = (error: unknown) => (error instanceof Error ? error.message : String(error))++/** Renames an artifact; what went wrong goes to `onError`. */+export function renameArtifact(store: BotStore, artifact: Artifact, title: string | null, onError: (message: string | null) => void) {+ if (title) store.artifacts.rename(store.client, artifact.botId, artifact.id, title).then(() => onError(null), (e: unknown) => onError(errorText(e)))+}++/** The artifact's share menu: Save as HTML (the native Save dialog) and Open in browser. */+export function artifactShareItems(store: BotStore, artifact: Artifact, onError: (message: string | null) => void): MenuItem[] {+ const run = (work: () => Promise<void>) => () => void work().then(() => onError(null), (e: unknown) => onError(errorText(e)))+ return [+ { title: 'Save as HTML', icon: 'arrow.down.to.line', action: run(() => store.artifacts.save(store.client, artifact)) },+ { title: 'Open in browser', icon: 'safari', action: run(() => store.artifacts.openInBrowser(store.client, artifact)) },+ ]+}diff --git a/apps/desktop/src/renderer/views/library/ArtifactView.tsx b/apps/desktop/src/renderer/views/library/ArtifactView.tsxnew file mode 100644index 00000000..58057038--- /dev/null+++ b/apps/desktop/src/renderer/views/library/ArtifactView.tsx@@ -0,0 +1,91 @@+import { useEffect, useState } from 'react'+import type { Artifact } from '@shared/artifacts'+import { DropdownMenu, Spinner } from '../../components/Controls'+import { Icon } from '../../components/Icon'+import { HStack, Spacer, VStack } from '../../components/Stack'+import { Text } from '../../components/Text'+import { useTr } from '../../lib/use-language'+import { useScreenViewed } from '../../store/analytics'+import { useStore } from '../../store/context'+import { Composer } from '../thread/Composer'+import { MacChatButton } from '../thread/MacChatButton'+import { ArtifactFrame, artifactShareItems, renameArtifact, TitleField } from './ArtifactParts'++/**+ * An artifact full size over its chat (Grok Bot's artifact view): close, its title (click to rename) and share on top, and a+ * message box for its bot at the bottom. It shows the newest version, so an artifact the bot changes reloads here.+ */+export function ArtifactView({ botId, artifactId, close }: { botId: string; artifactId: string; close: () => void }) {+ const tr = useTr()+ const store = useStore()+ const [error, setError] = useState<string | null>(null)+ const artifact = store.artifacts.byId.get(artifactId)+ const html = store.artifacts.html.get(artifactId)+ const failed = store.artifacts.failed.get(artifactId)+ const newest = artifact?.updatedAt+ useEffect(() => store.artifacts.load(store.client, botId, artifactId), [store, store.client, botId, artifactId, newest])+ useScreenViewed('artifact', artifactId)+ return (+ <div className="artifact-layer fade-in">+ <div className="top-chrome">+ <div className="top-chrome-row">+ <MacChatButton className="ringed" title={tr('Close artifact')} icon="xmark" direction={[-1, 0]} onClick={close} />+ <Spacer />+ {artifact ? (+ <DropdownMenu className="mac-chat-button ringed artifact-share" title={tr('Share artifact')} items={() => artifactShareItems(store, artifact, setError)}>+ <Icon name="square.and.arrow.up" size={16} weight="medium" />+ </DropdownMenu>+ ) : null}+ </div>+ {artifact ? <ArtifactTitle artifact={artifact} onError={setError} /> : null}+ </div>+ <div className="artifact-body">+ {html ? (+ <ArtifactFrame id={artifactId} html={html} title={artifact?.title ?? ''} />+ ) : failed ? (+ <VStack gap={6} className="artifact-state">+ <Text size="body" weight="semibold">{tr("Couldn't open the artifact")}</Text>+ <Text size="caption" tone="secondary">{failed}</Text>+ </VStack>+ ) : (+ <div className="artifact-state">+ <Spinner size={18} />+ </div>+ )}+ </div>+ <div className="composer-dock">+ {error ? <Text as="div" size="caption" tone="danger" role="alert" className="artifact-error">{error}</Text> : null}+ {/* A message here replies to the artifact's card, so its bot knows which artifact (`chat::replies`); an artifact+ published without one (a routine's) has nothing to reply to. */}+ {artifact?.entryId ? <Composer botId={botId} about={artifact} /> : null}+ </div>+ </div>+ )+}++/** The artifact's name in the top pill; clicking it edits the name in place. */+function ArtifactTitle({ artifact, onError }: { artifact: Artifact; onError: (message: string | null) => void }) {+ const tr = useTr()+ const store = useStore()+ const [editing, setEditing] = useState(false)+ if (editing) {+ return (+ <TitleField+ initial={artifact.title}+ className="title-pill artifact-title-field"+ done={(title) => {+ setEditing(false)+ renameArtifact(store, artifact, title, onError)+ }}+ />+ )+ }+ return (+ <button className="title-pill" title={tr('Rename artifact')} onClick={() => setEditing(true)}>+ <HStack as="span" gap={7}>+ <Icon name="chart.bar.doc.horizontal" size={16} color="var(--secondary)" />+ <Text size="body" weight="medium" tone="text" truncate>{artifact.title}</Text>+ </HStack>+ </button>+ )+}diff --git a/apps/desktop/src/renderer/views/library/LibraryView.tsx b/apps/desktop/src/renderer/views/library/LibraryView.tsxnew file mode 100644index 00000000..0c118bac--- /dev/null+++ b/apps/desktop/src/renderer/views/library/LibraryView.tsx@@ -0,0 +1,164 @@+import { useEffect, useState, type ReactNode } from 'react'+import type { Artifact, LibraryItem } from '@shared/artifacts'+import { isImageName, type Attachment, type SharedFile } from '@shared/models'+import { DropdownMenu, IconButton } from '../../components/Controls'+import { Icon } from '../../components/Icon'+import { HStack, VStack } from '../../components/Stack'+import { Text } from '../../components/Text'+import { libraryGroups } from '../../lib/library-groups'+import { useTr } from '../../lib/use-language'+import { useScreenViewed } from '../../store/analytics'+import { useStore } from '../../store/context'+import { AttachmentImage, AttachmentViewer, attachmentSymbol, byteCount } from '../thread/Attachments'+import { downloadAction, downloadDetail } from '../thread/FileDownloadCard'+import { artifactShareItems, renameArtifact, TitleField } from './ArtifactParts'++/**+ * A chat's Library in its details panel (Grok Bot's): the artifacts its bot made and the files shared in it, newest+ * first, by day. Each opens the way it does in the chat.+ */+export function LibraryView({ botId, openArtifact }: { botId: string; openArtifact: (artifactId: string) => void }) {+ const tr = useTr()+ const store = useStore()+ const [items, setItems] = useState<LibraryItem[]>([])+ const [error, setError] = useState<string | null>(null)+ const [viewing, setViewing] = useState<Attachment | null>(null)+ useScreenViewed('library')+ // Read again when the chat gets an artifact card or a file.+ const shared = store.allEntries(botId).filter((e) => e.data.artifact || e.data.files?.length || e.data.attachments?.length).length+ useEffect(() => {+ let live = true+ store.artifacts.library(store.client, botId).then(+ (items) => live && (setItems(items), setError(null)),+ (e: unknown) => live && setError(e instanceof Error ? e.message : String(e)),+ )+ return () => {+ live = false+ }+ }, [store, store.client, botId, shared])+ return (+ <VStack gap={20}>+ {error ? <Text size="caption" tone="danger" role="alert">{error}</Text> : null}+ {items.length === 0 ? (+ <VStack gap={4} className="outlined-card library-empty">+ <Text size="callout" weight="semibold">{tr('Library is empty')}</Text>+ <Text size="callout" tone="secondary">{tr('Artifacts {name} makes and files shared in this chat show here.').replace('{name}', store.bots.get(botId)?.name ?? '')}</Text>+ </VStack>+ ) : (+ libraryGroups(items).map(({ group, items }) => (+ <section key={group} className="details-section">+ <Text className="details-section-title">{tr(group)}</Text>+ <VStack gap={6}>+ {items.map((item) =>+ item.kind === 'artifact' ? (+ <ArtifactRow key={item.artifact.id} artifact={store.artifacts.byId.get(item.artifact.id) ?? item.artifact} open={() => openArtifact(item.artifact.id)} onError={setError} />+ ) : item.kind === 'file' ? (+ <FileRow key={item.file.id} entryId={item.entryId} file={item.file} />+ ) : (+ <AttachmentRow key={item.file.id} botId={botId} file={item.file} view={() => setViewing(item.file)} />+ ),+ )}+ </VStack>+ </section>+ ))+ )}+ <AttachmentViewer file={viewing} botId={botId} close={() => setViewing(null)} />+ </VStack>+ )+}++/** One line of the Library: what it is, its name, and what can be done with it. */+function Row({ leading, children, trailing }: { leading: ReactNode; children: ReactNode; trailing?: ReactNode }) {+ return (+ <HStack gap={4} className="outlined-card library-row">+ <HStack gap={10} grow className="library-row-main">+ <span className="library-row-icon">{leading}</span>+ {children}+ </HStack>+ {trailing}+ </HStack>+ )+}++function ArtifactRow({ artifact, open, onError }: { artifact: Artifact; open: () => void; onError: (message: string | null) => void }) {+ const tr = useTr()+ const store = useStore()+ const [renaming, setRenaming] = useState(false)+ const menu = (+ <DropdownMenu+ className="icon-button library-row-menu"+ title={tr('More actions')}+ items={() => [+ { title: 'Open', icon: 'doc.text', action: open },+ { title: 'Rename artifact', icon: 'pencil', action: () => setRenaming(true) },+ ...artifactShareItems(store, artifact, onError),+ ]}+ >+ <Icon name="ellipsis" size={14} weight="medium" />+ </DropdownMenu>+ )+ const icon = <Icon name="chart.bar.doc.horizontal" size={16} color="var(--secondary)" />+ if (renaming) {+ return (+ <Row leading={icon} trailing={menu}>+ <TitleField+ initial={artifact.title}+ className="library-row-field"+ done={(title) => {+ setRenaming(false)+ renameArtifact(store, artifact, title, onError)+ }}+ />+ </Row>+ )+ }+ return (+ <Row leading={icon} trailing={menu}>+ <button className="library-row-open" onClick={open}>+ <Name name={artifact.title} detail={tr('Artifact')} />+ </button>+ </Row>+ )+}++/** A file the bot shared: saved like its card in the chat. */+function FileRow({ entryId, file }: { entryId: string; file: SharedFile }) {+ const store = useStore()+ const state = store.fileDownloads.states.get(file.id)+ const busy = state?.kind === 'downloading'+ return (+ <Row+ leading={<Icon name={attachmentSymbol(file.name)} size={16} color="var(--secondary)" />}+ trailing={<IconButton title={downloadAction(state)} icon={busy ? 'xmark' : 'arrow.down.to.line'} onClick={() => (busy ? store.fileDownloads.cancel(file.id) : void store.fileDownloads.save(store.client, entryId, file))} />}+ >+ <Name name={file.name} detail={downloadDetail(state, file)} failed={state?.kind === 'failed'} />+ </Row>+ )+}++/** A file the user sent: an image opens full size, like in the chat. */+function AttachmentRow({ botId, file, view }: { botId: string; file: Attachment; view: () => void }) {+ if (!isImageName(file.name)) {+ return (+ <Row leading={<Icon name={attachmentSymbol(file.name)} size={16} color="var(--secondary)" />}>+ <Name name={file.name} detail={byteCount(file.size)} />+ </Row>+ )+ }+ return (+ <Row leading={<AttachmentImage file={file} botId={botId} fit="icon" />}>+ <button className="library-row-open" onClick={view}>+ <Name name={file.name} detail={byteCount(file.size)} />+ </button>+ </Row>+ )+}++function Name({ name, detail, failed = false }: { name: string; detail: string; failed?: boolean }) {+ return (+ <VStack gap={1} shrink>+ <Text size="callout" truncate title={name}>{name}</Text>+ <Text size="caption2" tone={failed ? 'danger' : 'tertiary'} truncate>{detail}</Text>+ </VStack>+ )+}diff --git a/apps/desktop/src/renderer/views/library/library.css b/apps/desktop/src/renderer/views/library/library.cssnew file mode 100644index 00000000..d9e09d88--- /dev/null+++ b/apps/desktop/src/renderer/views/library/library.css@@ -0,0 +1,137 @@+/* The Library: artifact cards in the chat, an artifact over its chat, and the details panel's list. */++/* The card: the top of the artifact, drawn at a desktop width and scaled to half, cut off at the footer. */+.artifact-card {+ display: flex;+ flex-direction: column;+ width: 380px;+ max-width: 100%;+ text-align: left;+ border: 1px solid var(--border);+ border-radius: var(--radius-l);+ overflow: hidden;+ transition: transform var(--press);+}+.artifact-card:active {+ transform: scale(0.98);+}+.artifact-card-preview {+ position: relative;+ height: 220px;+ /* The frame is its own layer: clipped by this path, its corners follow the card's (just inside its border). */+ clip-path: inset(0 round calc(var(--radius-l) - 1px) calc(var(--radius-l) - 1px) 0 0);+}+/* White behind an artifact without a background of its own, kept off the clipped edge: under the frame's+ antialiased corners it would show as light slivers. */+.artifact-card-preview::before {+ content: '';+ position: absolute;+ inset: 2px 2px 0;+ background: white;+ border-radius: var(--radius-m) var(--radius-m) 0 0;+}+.artifact-card-footer {+ padding: 12px 14px;+ border-top: 1px solid var(--border);+}++.artifact-frame {+ display: block;+ width: 100%;+ height: 100%;+ border: none;+ background: white;+}+.artifact-frame.preview {+ position: relative;+ background: none;+ width: 760px;+ height: 440px;+ transform: scale(0.5);+ transform-origin: 0 0;+ pointer-events: none;+}++/* The artifact over its chat: the chat's own chrome on top, the artifact under it, the message box floating below. */+.artifact-layer {+ position: absolute;+ inset: 0;+ z-index: 7;+ background: var(--background);+}+.artifact-body {+ position: absolute;+ inset: 60px 0 0;+}+.artifact-state {+ height: 100%;+ display: grid;+ place-content: center;+ text-align: center;+ padding: 0 24px;+}+.artifact-share {+ width: 32px;+ height: 32px;+}+.artifact-title-field {+ min-width: 240px;+ font: inherit;+ font-size: var(--text-body);+ text-align: center;+ color: var(--text);+ border: none;+ outline: none;+}+.artifact-error {+ max-width: var(--column);+ margin: 0 auto;+ padding: 0 24px 6px;+}++/* The details panel's Library. */+.library-empty {+ padding: 14px 16px;+}+.library-row {+ min-height: 46px;+ padding: 4px 6px 4px 14px;+}+.library-row-main {+ min-width: 0;+}+.library-row-icon {+ display: grid;+ place-items: center;+ width: 28px;+ flex: none;+}+.library-row-open {+ flex: 1;+ min-width: 0;+ padding: 6px 0;+ text-align: left;+}+.library-row-field {+ flex: 1;+ min-width: 0;+ padding: 6px 0;+ font: inherit;+ font-size: var(--text-callout);+ color: var(--text);+ background: none;+ border: none;+ outline: none;+}+.library-row-menu {+ width: 28px;+ height: 28px;+ border-radius: var(--radius-xs);+ opacity: 0;+ transition: opacity var(--hover);+}+.library-row:hover .library-row-menu,+.library-row-menu[aria-expanded='true'],+.library-row-menu:focus-visible {+ opacity: 1;+}diff --git a/apps/desktop/src/renderer/views/thread/Attachments.tsx b/apps/desktop/src/renderer/views/thread/Attachments.tsxindex 2e620d02..c2fd65f0 100644--- a/apps/desktop/src/renderer/views/thread/Attachments.tsx+++ b/apps/desktop/src/renderer/views/thread/Attachments.tsx@@ -50,22 +50,29 @@ export function AttachmentList({ attachments, botId }: { attachments: Attachment</HStack>),)}- <Sheet open={viewing !== null} onClose={() => setViewing(null)} width={720} height={560}>- {viewing ? (- <SheetPage>- <ModalHeader title={viewing.name} />- <div className="attachment-viewer">- <AttachmentImage file={viewing} botId={botId} fit="full" />- </div>- </SheetPage>- ) : null}- </Sheet>+ <AttachmentViewer file={viewing} botId={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 }) {+ return (+ <Sheet open={file !== null} onClose={close} width={720} height={560}>+ {file ? (+ <SheetPage>+ <ModalHeader title={file.name} />+ <div className="attachment-viewer">+ <AttachmentImage file={file} botId={botId} fit="full" />+ </div>+ </SheetPage>+ ) : null}+ </Sheet>+ )+}+/** A sent image, fetched from the computer once and then read from the cache. */-function AttachmentImage({ file, botId, fit }: { file: Attachment; botId: string; fit: 'thumbnail' | 'full' }) {+export function AttachmentImage({ file, botId, fit }: { file: Attachment; botId: string; fit: 'icon' | 'thumbnail' | 'full' }) {const store = useStoreRef()const [url, setUrl] = useState<string | null>(null)useEffect(() => {@@ -83,7 +90,7 @@ function AttachmentImage({ file, botId, fit }: { file: Attachment; botId: string}, [store, file.id, botId])if (!url) {return (- <div className="attachment-placeholder">+ <div className={`attachment-placeholder ${fit}`}><Icon name="photo" size={13} color="var(--tertiary)" /></div>)diff --git a/apps/desktop/src/renderer/views/thread/ChatRows.tsx b/apps/desktop/src/renderer/views/thread/ChatRows.tsxindex 340e0b60..5f4f2908 100644--- a/apps/desktop/src/renderer/views/thread/ChatRows.tsx+++ b/apps/desktop/src/renderer/views/thread/ChatRows.tsx@@ -1,4 +1,5 @@import { FileDownloadCard } from './FileDownloadCard'+import { ArtifactCard } from '../library/ArtifactCard'import { memo, useEffect, useRef, useState } from 'react'import { groupBotReactions, isGroup, isReplyable, isWorking, needsInput, type Bot, type Entry, type ReplyQuote } from '@shared/models'import { BotAvatar } from '../../components/Avatar'@@ -25,7 +26,7 @@ export function reactionPick(store: BotStore, entry: Entry): ReactionPick {}/** One chat-visible entry, with what can be done to it. */-export const ChatRow = memo(function ChatRow({ entry, groupStart, chat, openTrace, onReply, openAgent }: {+export const ChatRow = memo(function ChatRow({ entry, groupStart, chat, openTrace, onReply, openAgent, openArtifact }: {entry: EntrygroupStart: booleanchat: Bot | null@@ -34,6 +35,8 @@ export const ChatRow = memo(function ChatRow({ entry, groupStart, chat, openTraconReply?: (e: Entry) => void/** Opens a bot's Agent settings (a failure notice's "Add a fallback"). */openAgent?: (botId: string) => void+ /** Opens an artifact card's artifact over the chat. */+ openArtifact?: (artifactId: string) => void}) {const reply = onReply && isReplyable(entry) ? () => onReply(entry) : undefinedswitch (entry.kind) {@@ -48,7 +51,7 @@ export const ChatRow = memo(function ChatRow({ entry, groupStart, chat, openTracreturn (<VStack align="flex-start" gap={4} className={groupStart ? 'chat-row group-start' : 'chat-row'}>{chat && isGroup(chat) && groupStart ? <AuthorLabel botId={entry.data.author} /> : null}- <AgentBubble entry={entry} openTrace={openTrace} reply={reply} />+ <AgentBubble entry={entry} openTrace={openTrace} reply={reply} openArtifact={openArtifact} /><VStack gap={4} className={chat && isGroup(chat) ? 'chat-row-indent' : undefined}><ReactionsRow entry={entry} /></VStack>@@ -171,7 +174,7 @@ function UserStatus({ entry, botWorking, hovering }: { entry: Entry; botWorking:}}-export function AgentBubble({ entry, openTrace, reply }: { entry: Entry; openTrace: () => void; reply?: () => void }) {+export function AgentBubble({ entry, openTrace, reply, openArtifact }: { entry: Entry; openTrace: () => void; reply?: () => void; openArtifact?: (artifactId: string) => void }) {const store = useStore()const [hovering, setHovering] = useState(false)const copy = () => entry.data.text && window.codync.app.copy(entry.data.text)@@ -179,7 +182,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={entry.data.files?.length ? "file-message" : "bubble agent"}+ className={entry.data.files?.length || entry.data.artifact ? 'file-message' : 'bubble agent'}reactions={reactionPick(store, entry)}items={() => [{ title: 'Copy', icon: 'square.on.square', action: copy },@@ -187,7 +190,13 @@ export function AgentBubble({ entry, openTrace, reply }: { entry: Entry; openTra{ title: 'Show what it did', icon: 'list.bullet', action: openTrace },]}>- {entry.data.files?.length ? <div className="file-message-cards">{entry.data.files.map((file) => <FileDownloadCard key={file.id} entry={entry} file={file} />)}</div> : <MarkdownText text={entry.data.text ?? ''} />}+ {entry.data.artifact ? (+ <ArtifactCard botId={entry.botId} card={entry.data.artifact} open={() => openArtifact?.(entry.data.artifact!.id)} />+ ) : entry.data.files?.length ? (+ <div className="file-message-cards">{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/Composer.tsx b/apps/desktop/src/renderer/views/thread/Composer.tsxindex c84dd2a0..e8f75692 100644--- a/apps/desktop/src/renderer/views/thread/Composer.tsx+++ b/apps/desktop/src/renderer/views/thread/Composer.tsx@@ -1,5 +1,6 @@import { useEffect, useLayoutEffect, useRef, useState, useSyncExternalStore, type ReactNode } from 'react'import { groupFastMode } from '@shared/fast-mode'+import { artifactDraftKey, artifactQuote, type Artifact } from '@shared/artifacts'import { isGroup, isWorkingIn, quoteOf, type Bot, type Entry } from '@shared/models'import { BotAvatar } from '../../components/Avatar'import { Icon } from '../../components/Icon'@@ -27,11 +28,13 @@ type Trailing = 'interrupt' | 'stop' | 'call' | 'send'/*** The message box under a chat: send, or stop while the bot (or the group) is working there. A leading `/` lists* the commands (a group's are its bots'); in a group, typing `@` suggests its bots. While `reply` is set, the- * message it quotes sits at the top of the box and goes out with the next send.+ * message it quotes sits at the top of the box and goes out with the next send. Under an artifact, `about` is the+ * artifact: the box keeps a draft of its own, and every message replies to the artifact's card.*/-export function Composer({ botId, reply = null, cancelReply, onCall, onInterrupt }: {+export function Composer({ botId, reply = null, about = null, cancelReply, onCall, onInterrupt }: {botId: stringreply?: Entry | null+ about?: Artifact | nullcancelReply?: () => void/** Starts a voice call; while the box is empty it takes the send button's place. */onCall?: (() => void) | null@@ -40,22 +43,23 @@ export function Composer({ botId, reply = null, cancelReply, onCall, onInterrupt}) {const store = useStore()// Remount transient editor state (selection, attachments, IME) when its destination changes.- return <DestinationComposer key={JSON.stringify([store.contextId, store.computer.id, botId])}- botId={botId} reply={reply} cancelReply={cancelReply} onCall={onCall} onInterrupt={onInterrupt} />+ return <DestinationComposer key={JSON.stringify([store.contextId, store.computer.id, botId, about?.id])}+ botId={botId} reply={reply} about={about} cancelReply={cancelReply} onCall={onCall} onInterrupt={onInterrupt} />}-function DestinationComposer({ botId, reply, cancelReply, onCall, onInterrupt }: {- botId: string; reply: Entry | null; cancelReply?: () => void; onCall?: (() => void) | null; onInterrupt?: (() => void) | null+function DestinationComposer({ botId, reply, about, cancelReply, onCall, onInterrupt }: {+ botId: string; reply: Entry | null; about: Artifact | null; cancelReply?: () => void; onCall?: (() => void) | null; onInterrupt?: (() => void) | null}) {const store = useStore()const tr = useTr()const plugins = useModel(pluginsFor(store))const bot = store.bots.get(botId) ?? nullconst drafts = store.composerDrafts- const draft = useSyncExternalStore(drafts.subscribe, () => drafts.get(botId))- const setDraft = (text: string) => drafts.set(botId, text)+ const draftKey = about ? artifactDraftKey(about) : botId+ const draft = useSyncExternalStore(drafts.subscribe, () => drafts.get(draftKey))+ const setDraft = (text: string) => drafts.set(draftKey, text)const [files, setFiles] = useState<OutgoingFile[]>([])- const dictation = useDictation((change) => drafts.set(botId, change(drafts.get(botId))))+ const dictation = useDictation((change) => drafts.set(draftKey, change(drafts.get(draftKey))))const field = useRef<HTMLTextAreaElement>(null)const measure = useRef<HTMLDivElement>(null)const composing = useRef(false)@@ -69,7 +73,9 @@ function DestinationComposer({ botId, reply, cancelReply, onCall, onInterrupt }:const members = bot && isGroup(bot) ? store.members(bot) : []const name = bot?.name ?? ''- const placeholder = reply+ const placeholder = about+ ? tr('Message about “{title}”').replace('{title}', about.title)+ : reply? tr('Reply…'): bot && isGroup(bot)? tr('Ask everyone · @ to ask one bot')@@ -77,8 +83,8 @@ function DestinationComposer({ botId, reply, cancelReply, onCall, onInterrupt }:? tr('Queue a message for {name}').replace('{name}', name): tr('Ask {name}').replace('{name}', name)- // A routine's "Try it" fills the box.- const routineDraft = store.routineDrafts.get(botId)+ // A routine's "Try it" fills the chat's box (an artifact's leaves it for the chat).+ const routineDraft = about ? undefined : store.routineDrafts.get(botId)useEffect(() => {if (routineDraft === undefined) returnconst incoming = store.consumeRoutineDraft(botId)@@ -173,7 +179,7 @@ function DestinationComposer({ botId, reply, cancelReply, onCall, onInterrupt }:// Words still on their way would land in the emptied box (and the shortcut's tap would send them again).dictation.cancel()if (command) return run(command)- store.send(draft, botId, { files, pasted: pasted.current, replyTo: reply && quoteOf(reply) })+ store.send(draft, botId, { files, pasted: pasted.current, replyTo: reply ? quoteOf(reply) : about && artifactQuote(about) })cancelReply?.()pasted.current = []setDraft('')diff --git a/apps/desktop/src/renderer/views/thread/DetailsPanel.tsx b/apps/desktop/src/renderer/views/thread/DetailsPanel.tsxindex 6dd6fd53..c7a3df6b 100644--- a/apps/desktop/src/renderer/views/thread/DetailsPanel.tsx+++ b/apps/desktop/src/renderer/views/thread/DetailsPanel.tsx@@ -1,3 +1,4 @@+import { hasLibrary } from '@shared/artifacts'import { isGroup, isWorking, type Bot } from '@shared/models'import { AgentIcon } from '../../components/AgentIcon'import { BotAvatar, GroupAvatar } from '../../components/Avatar'@@ -10,27 +11,30 @@ import { useScreenViewed } from '../../store/analytics'import { BotSettingsPanel } from '../bots/BotEditorView'import { MemoryCard } from '../bots/MemoryView'import { RoutinesView } from '../routines/RoutinesView'+import { LibraryView } from '../library/LibraryView'import { MacChatButton } from './MacChatButton'import '../bots/bots.css'import './details-panel.css'import { useTr } from '../../lib/use-language'-export type DetailsTab = 'details' | 'memory' | 'settings'+export type DetailsTab = 'details' | 'library' | 'memory' | 'settings'const TABS: { id: DetailsTab; label: string }[] = [{ id: 'details', label: 'Details' },+ { id: 'library', label: 'Library' },{ id: 'memory', label: 'Memory' },{ id: 'settings', label: 'Settings' },]-/** The inspector beside a conversation (Grok Bot's): who the bot is, then its details, memory and settings. */-export function DetailsPanel({ botId, routineId, tab, setTab, editGroup, share, close }: {+/** The inspector beside a conversation (Grok Bot's): who the bot is, then its details, library, memory and settings. */+export function DetailsPanel({ botId, routineId, tab, setTab, editGroup, openArtifact, share, close }: {botId: stringroutineId: string | nulltab: DetailsTabsetTab: (tab: DetailsTab) => voideditGroup: () => void+ openArtifact: (artifactId: string) => voidshare: () => voidclose: () => void}) {@@ -51,7 +55,7 @@ export function DetailsPanel({ botId, routineId, tab, setTab, editGroup, share,<GroupMembersList group={bot} editGroup={editGroup} />) : (<>- <TabChoice label="Conversation details" selection={tab} options={TABS} onChange={setTab} />+ <TabChoice label="Conversation details" selection={tab} options={hasLibrary(store.hostVersion?.version) ? TABS : TABS.filter((t) => t.id !== 'library')} onChange={setTab} /><div key={tab} className="details-tab fade-in">{tab === 'details' ? (<>@@ -59,6 +63,8 @@ export function DetailsPanel({ botId, routineId, tab, setTab, editGroup, share,{bot ? <ComputerUse bot={bot} /> : null}<RoutinesView botId={botId} initialId={routineId} /></>+ ) : tab === 'library' ? (+ <LibraryView botId={botId} openArtifact={openArtifact} />) : tab === 'memory' ? (<MemoryCard botId={botId} />) : (diff --git a/apps/desktop/src/renderer/views/thread/FileDownloadCard.tsx b/apps/desktop/src/renderer/views/thread/FileDownloadCard.tsxindex 9a2d36e7..88a23bbc 100644--- a/apps/desktop/src/renderer/views/thread/FileDownloadCard.tsx+++ b/apps/desktop/src/renderer/views/thread/FileDownloadCard.tsx@@ -1,5 +1,6 @@import type { Entry, 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'@@ -7,12 +8,26 @@ import { Text } from '../../components/Text'import { attachmentSymbol, byteCount } from './Attachments'import './attachments.css'+/** What the download button does now (also the Library's file rows). */+export function downloadAction(state: DownloadState | undefined) {+ return state?.kind === 'downloading' ? 'Cancel download' : state?.kind === 'failed' ? 'Retry download' : state?.kind === 'saved' ? 'Save again' : 'Download'+}++/** The line under a shared file's name: its size, the download's progress, or what went wrong. */+export function downloadDetail(state: DownloadState | undefined, file: SharedFile) {+ switch (state?.kind) {+ case 'downloading': return `${byteCount(state.received)} of ${byteCount(file.size)}`+ case 'failed': return state.message+ case 'saved': return `${byteCount(file.size)} · Saved`+ default: return byteCount(file.size)+ }+}+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)+ 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>diff --git a/apps/desktop/src/renderer/views/thread/ThreadView.tsx b/apps/desktop/src/renderer/views/thread/ThreadView.tsxindex 6741acb2..6b0cecb7 100644--- a/apps/desktop/src/renderer/views/thread/ThreadView.tsx+++ b/apps/desktop/src/renderer/views/thread/ThreadView.tsx@@ -27,6 +27,7 @@ import { BotEditorView } from '../bots/BotEditorView'import { FormSheet } from '../marketplace/pieces'import { CallView } from '../call/CallView'import { MacChatButton } from './MacChatButton'+import { ArtifactView } from '../library/ArtifactView'import './thread.css'import './composer.css'import './chat-controls.css'@@ -56,6 +57,8 @@ export const ThreadView = memo(function ThreadView({ botId }: { botId: string })// A group member's settings, opened from its notice.const [editingMember, setEditingMember] = useState<string | null>(null)const [routineRequest, setRoutineRequest] = useState(0)+ // The artifact shown over the chat (a card or the Library opened it).+ const [artifactId, setArtifactId] = useState<string | null>(null)const root = useRef<HTMLDivElement>(null)const dock = useRef<HTMLDivElement>(null)// The width is measured, not rendered: resizing re-renders only when `wide` flips, or while the@@ -110,6 +113,10 @@ export const ThreadView = memo(function ThreadView({ botId }: { botId: string }))const openTrace = useCallback(() => setShowTrace(true), [])+ const openArtifact = useCallback((id: string) => {+ setArtifactId(id)+ setCompactDetails(false)+ }, [])const presentRoutine = useCallback((id: string | null) => {setRoutineId(id)@@ -131,6 +138,7 @@ export const ThreadView = memo(function ThreadView({ botId }: { botId: string })tab={detailsTab}setTab={setDetailsTab}editGroup={() => setEditingGroup(true)}+ openArtifact={openArtifact}share={() => {setCompactDetails(false)if (bot) setTemplateDraft(draftOf(bot))@@ -167,14 +175,15 @@ export const ThreadView = memo(function ThreadView({ botId }: { botId: string })</button></div>{/* An update card takes the composer's place, so there's nothing to reply with. */}- <Transcript botId={botId} openTrace={openTrace} onReply={store.mismatch ? undefined : setReplyTo} openRoutine={presentRoutine} openAgent={presentAgent} openBotChat={setBotChat} />+ <Transcript botId={botId} openTrace={openTrace} onReply={store.mismatch ? undefined : setReplyTo} openRoutine={presentRoutine} openAgent={presentAgent} openBotChat={setBotChat} openArtifact={openArtifact} /><div className="composer-dock" ref={dock}><div className="composer-fade" />{store.mismatch ? (<div className="composer-update-needed"><UpdateNeededCard /></div>- ) : (+ ) : artifactId ? null : (+ // The artifact over the chat has its own box (two would both take the voice shortcut).<ComposerbotId={botId}reply={replyTo}@@ -189,6 +198,7 @@ export const ThreadView = memo(function ThreadView({ botId }: { botId: string })<CallView botId={botId} onSpeaking={setCallSpeaking} interrupt={interruptCall} onEnd={() => setCalling(false)} /></div>) : null}+ {artifactId ? <ArtifactView botId={botId} artifactId={artifactId} close={() => setArtifactId(null)} /> : null}</div><ChatSidePanelopen={panelOpen}@@ -257,7 +267,7 @@ function ConnectionSubtitle() {/** The messages: every loaded message, brought to the newest as it changes while the reader is at the bottom. */const PAGE = 40-const Transcript = memo(function Transcript({ botId, openTrace, onReply, openRoutine, openAgent, openBotChat }: { botId: string; openTrace: () => void; onReply?: (e: Entry) => void; openRoutine: (id: string | null) => void; openAgent: (botId: string) => void; openBotChat: (peerId: string) => void }) {+const Transcript = memo(function Transcript({ botId, openTrace, onReply, openRoutine, openAgent, openBotChat, openArtifact }: { botId: string; openTrace: () => void; onReply?: (e: Entry) => void; openRoutine: (id: string | null) => void; openAgent: (botId: string) => void; openBotChat: (peerId: string) => void; openArtifact: (artifactId: string) => void }) {const store = useStore()const tr = useTr()const bot = store.bots.get(botId) ?? null@@ -363,7 +373,7 @@ const Transcript = memo(function Transcript({ botId, openTrace, onReply, openRou{items.length === 0 && bot ? <div className="transcript-intro">{isGroup(bot) ? <GroupIntroCard group={bot} /> : <IntroCard bot={bot} />}</div> : null}{items.map((item) => (<div key={item.id} className={arrivals.has(item.id) ? rowIn(item) : undefined}>- <Row item={item} chat={bot} openTrace={openTrace} onReply={onReply} openRoutine={openRoutine} openAgent={openAgent} openBotChat={openBotChat} />+ <Row item={item} chat={bot} openTrace={openTrace} onReply={onReply} openRoutine={openRoutine} openAgent={openAgent} openBotChat={openBotChat} openArtifact={openArtifact} /></div>))}{bot ? <WorkingTransition bot={bot} visible={live} /> : null}@@ -387,7 +397,7 @@ const Transcript = memo(function Transcript({ botId, openTrace, onReply, openRou)})-function Row({ item, chat, openTrace, onReply, openRoutine, openAgent, openBotChat }: { item: ChatItem; chat: Bot | null; openTrace: () => void; onReply?: (e: Entry) => void; openRoutine: (id: string | null) => void; openAgent: (botId: string) => void; openBotChat: (peerId: string) => void }) {+function Row({ item, chat, openTrace, onReply, openRoutine, openAgent, openBotChat, openArtifact }: { item: ChatItem; chat: Bot | null; openTrace: () => void; onReply?: (e: Entry) => void; openRoutine: (id: string | null) => void; openAgent: (botId: string) => void; openBotChat: (peerId: string) => void; openArtifact: (artifactId: string) => void }) {if (item.kind === 'separator') {return <TimeSeparator date={item.date} />}@@ -395,7 +405,7 @@ function Row({ item, chat, openTrace, onReply, openRoutine, openAgent, openBotChconst e = item.entryif (e.kind === 'notice' && e.data.routineId) return <RoutineNotice entry={e} open={() => openRoutine(e.data.routineId!)} />- return <ChatRow entry={e} groupStart={item.groupStart} chat={chat} openTrace={openTrace} onReply={onReply} openAgent={openAgent} />+ return <ChatRow entry={e} groupStart={item.groupStart} chat={chat} openTrace={openTrace} onReply={onReply} openAgent={openAgent} openArtifact={openArtifact} />}/** The start of an empty group chat: who's in it and how the room works. */diff --git a/apps/desktop/src/renderer/views/thread/attachments.css b/apps/desktop/src/renderer/views/thread/attachments.cssindex 0d6330d9..adacac34 100644--- a/apps/desktop/src/renderer/views/thread/attachments.css+++ b/apps/desktop/src/renderer/views/thread/attachments.css@@ -13,6 +13,13 @@max-width: 220px;max-height: 280px;}+.attachment-image.icon,+.attachment-placeholder.icon {+ width: 28px;+ height: 28px;+ border-radius: var(--radius-xs);+ object-fit: cover;+}.attachment-image.full {max-width: 100%;max-height: 100%;diff --git a/apps/desktop/src/shared/analytics.ts b/apps/desktop/src/shared/analytics.tsindex 6b86f94e..93dca598 100644--- a/apps/desktop/src/shared/analytics.ts+++ b/apps/desktop/src/shared/analytics.ts@@ -17,6 +17,8 @@ export type Screen =| 'pairing'| 'voice_settings'| 'computer_access'+ | 'library'+ | 'artifact'/** Outbound links, by what they lead to. */export type Link = 'github' | 'docs' | 'issues' | 'discord' | 'app_store' | 'demo' | 'tailscale' | 'privacy' | 'support' | 'install_command'diff --git a/apps/desktop/src/shared/artifacts.test.ts b/apps/desktop/src/shared/artifacts.test.tsnew file mode 100644index 00000000..f3970807--- /dev/null+++ b/apps/desktop/src/shared/artifacts.test.ts@@ -0,0 +1,48 @@+import assert from 'node:assert/strict'+import { createHash } from 'node:crypto'+import { test } from 'node:test'+import { artifactQuote, hasLibrary, readArtifactHTML, type Artifact } from './artifacts.ts'+import { FILE_CHUNK_SIZE } from './files.ts'++function version(text: string, updatedAt: number) {+ const bytes = Buffer.from(text)+ const sha256 = createHash('sha256').update(bytes).digest('hex')+ const artifact: Artifact = { id: 'a', botId: 'b', title: 'Report', size: bytes.length, sha256, createdAt: 0, updatedAt }+ return { bytes, artifact }+}++/** A host whose `readArtifact` answers from each version in turn, staying on the last one. */+function host(...versions: ReturnType<typeof version>[]) {+ const offsets: number[] = []+ const read = async (offset: number) => {+ const { bytes, artifact } = versions[Math.min(offsets.length, versions.length - 1)]!+ offsets.push(offset)+ return { data: bytes.subarray(offset, offset + FILE_CHUNK_SIZE).toString('base64'), size: artifact.size, artifact }+ }+ return { read, offsets }+}++test('an artifact republished while it is read is read again from its start', async () => {+ const first = version('a'.repeat(FILE_CHUNK_SIZE + 10), 1)+ const second = version('b'.repeat(FILE_CHUNK_SIZE + 20), 2)+ const { read, offsets } = host(first, second)+ const html = await readArtifactHTML(read)+ assert.equal(html.artifact.updatedAt, 2)+ assert.deepEqual(Buffer.from(html.bytes), second.bytes)+ assert.deepEqual(offsets, [0, FILE_CHUNK_SIZE, 0, FILE_CHUNK_SIZE], 'never one version spliced onto another')+})++test('HTML that fails its digest is refused', async () => {+ const stored = version('<h1>Hi</h1>', 1)+ const { read } = host({ ...stored, bytes: Buffer.from('<h1>Ho</h1>') })+ await assert.rejects(readArtifactHTML(read), /integrity/)+})++test('the Library needs a host that has it, and only a card takes messages about its artifact', () => {+ assert.equal(hasLibrary('2.25.0'), true)+ assert.equal(hasLibrary('2.24.3'), false)+ assert.equal(hasLibrary(undefined), false)+ const { artifact } = version('x', 1)+ assert.equal(artifactQuote(artifact), null, 'a routine published it')+ assert.deepEqual(artifactQuote({ ...artifact, entryId: 'e' }), { id: 'e', author: 'b', text: 'Artifact: Report', artifact: 'a' })+})diff --git a/apps/desktop/src/shared/artifacts.ts b/apps/desktop/src/shared/artifacts.tsnew file mode 100644index 00000000..f4335141--- /dev/null+++ b/apps/desktop/src/shared/artifacts.ts@@ -0,0 +1,83 @@+// 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'++/** An HTML artifact a bot published; `readArtifact` returns its HTML. */+export interface Artifact {+ id: string+ botId: string+ title: string+ size: number+ sha256: string+ createdAt: number+ updatedAt: number+ /** Its newest card in the bot's chat: what a message about the artifact replies to. */+ entryId?: string+}++/** One thing in a chat's Library (`library`): an artifact, a file the bot shared, or one the user attached. */+export type LibraryItem =+ | { kind: 'artifact'; at: number; artifact: Artifact }+ | { kind: 'file'; at: number; entryId: string; file: SharedFile }+ | { kind: 'attachment'; at: number; entryId: string; file: Attachment }++/** An artifact card in the chat (`data.artifact`): the artifact as it was published then. */+export interface ArtifactCard {+ id: string+ title: string+ updatedAt: number+}++/** One `readArtifact` answer. */+export interface ArtifactChunk { data: string; size: number; artifact: Artifact }++/** The first host with artifacts and the Library. */+export const ARTIFACTS_HOST = '2.25.0'++/** Whether the computer's host has the Library; an older one has no `library` method, so the app leaves it out. */+export function hasLibrary(hostVersion: string | undefined): boolean {+ return !!hostVersion && !isBelow(hostVersion, ARTIFACTS_HOST)+}++/** How a message about the artifact quotes its card (`chat::replies`) until the computer's own quote arrives; none+ * without a card (a routine published it). */+export function artifactQuote(artifact: Artifact): ReplyQuote | null {+ return artifact.entryId ? { id: artifact.entryId, author: artifact.botId, text: `Artifact: ${artifact.title}`, artifact: artifact.id } : null+}++/** The draft of the message box under an artifact, apart from its chat's (`ComposerDrafts.removeBot` drops both). */+export function artifactDraftKey(artifact: Artifact): string {+ return `${artifact.botId}/artifact/${artifact.id}`+}++/**+ * An artifact's whole HTML, read chunk by chunk with `read(offset)`: every chunk of one version (published again+ * meanwhile, the new version is read from its start), checked against its SHA-256.+ */+export async function readArtifactHTML(read: (offset: number) => Promise<ArtifactChunk>): Promise<{ artifact: Artifact; bytes: Uint8Array }> {+ let html = new Uint8Array(0)+ let offset = 0+ let version: string | null = null+ for (;;) {+ const { artifact, ...chunk } = await read(offset)+ if (artifact.sha256 !== version) {+ const restart = offset > 0+ version = artifact.sha256+ html = new Uint8Array(artifact.size)+ offset = 0+ if (restart) continue+ }+ const bytes = decodeFileChunk(chunk, artifact.size, offset)+ html.set(bytes, offset)+ offset += bytes.length+ if (offset < artifact.size) continue+ if ((await sha256Hex(html)) !== version) throw new Error('The artifact failed its integrity check; try again')+ return { 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/composer-drafts.test.ts b/apps/desktop/src/shared/composer-drafts.test.tsindex b7fbfb5c..d7812a6c 100644--- a/apps/desktop/src/shared/composer-drafts.test.ts+++ b/apps/desktop/src/shared/composer-drafts.test.ts@@ -36,9 +36,11 @@ test('drafts saved before quote replies stay with their chat', () => {test('deleting a bot removes its draft, but preserves other bots', () => {const drafts = new ComposerDrafts(storage(), 'drafts')drafts.set('bot', 'main')+ drafts.set('bot/artifact/a', 'about the artifact')drafts.set('other', 'keep')drafts.removeBot('bot')assert.equal(drafts.get('bot'), '')+ assert.equal(drafts.get('bot/artifact/a'), '')assert.equal(drafts.get('other'), 'keep')})diff --git a/apps/desktop/src/shared/composer-drafts.ts b/apps/desktop/src/shared/composer-drafts.tsindex 85420c87..e1d7da33 100644--- a/apps/desktop/src/shared/composer-drafts.ts+++ b/apps/desktop/src/shared/composer-drafts.ts@@ -49,9 +49,10 @@ export class ComposerDrafts {this.save()}+ /** The chat's draft and its artifacts' (`artifactDraftKey`). */removeBot(bot: string) {if (this.retired) return- this.values.delete(bot)+ for (const key of [...this.values.keys()]) if (key === bot || key.startsWith(`${bot}/`)) this.values.delete(key)this.save()}diff --git a/apps/desktop/src/shared/ipc.ts b/apps/desktop/src/shared/ipc.tsindex daf23f4e..243bba62 100644--- a/apps/desktop/src/shared/ipc.ts+++ b/apps/desktop/src/shared/ipc.ts@@ -207,6 +207,12 @@ export interface CodyncBridge {setAutoCheck(on: boolean): voidsetAutoDownload(on: boolean): void}+ /** Artifacts shown in a frame of their own (`main/artifacts.ts`). */+ artifacts: {+ /** Makes `codync-artifact://<id>` serve this HTML. */+ show(id: string, html: Uint8Array): Promise<void>+ openInBrowser(id: string, html: Uint8Array): Promise<void>+ }files: {begin(file: SharedFile): Promise<string | null>write(id: string, offset: number, data: Uint8Array): Promise<void>diff --git a/apps/desktop/src/shared/models.ts b/apps/desktop/src/shared/models.tsindex 8a8540f7..424bd2b1 100644--- a/apps/desktop/src/shared/models.ts+++ b/apps/desktop/src/shared/models.ts@@ -1,3 +1,5 @@+import type { ArtifactCard } from './artifacts'+// Wire types for codync-host (see host/src/api/). Field names match the// host's camelCase JSON. Timestamps are epoch milliseconds.@@ -202,6 +204,8 @@ export interface ReplyQuote {author: string/** Its text (or file names), at most 500 characters. */text: string+ /** The artifact, when it quotes an artifact card: the message is about that artifact. */+ artifact?: string}export interface Attachment {@@ -302,6 +306,8 @@ export interface EntryData {botReactions?: BotReaction[]attachments?: Attachment[]files?: SharedFile[]+ /** agent: an artifact the bot published (or updated) in this turn. */+ artifact?: ArtifactCardcallSeconds?: number}@@ -343,7 +349,9 @@ export function isReplyable(e: Entry): boolean {/** The quote a sending reply shows until the computer's own replaces it. */export function quoteOf(e: Entry): ReplyQuote {const names = [...(e.data.attachments ?? []), ...(e.data.files ?? [])].map((f) => f.name).join(', ')- return { id: e.id, author: e.kind === 'user' ? 'user' : (e.data.author ?? e.botId), text: (e.data.text || names).slice(0, 500) }+ const quote: ReplyQuote = { id: e.id, author: e.kind === 'user' ? 'user' : (e.data.author ?? e.botId), text: (e.data.text || names).slice(0, 500) }+ if (e.data.artifact) quote.artifact = e.data.artifact.id+ return quote}export interface UsageWindow {diff --git a/apps/ios/Kit/Sources/CodyncKit/Analytics/AnalyticsEvent.swift b/apps/ios/Kit/Sources/CodyncKit/Analytics/AnalyticsEvent.swiftindex 2ff1632f..4a079a98 100644--- a/apps/ios/Kit/Sources/CodyncKit/Analytics/AnalyticsEvent.swift+++ b/apps/ios/Kit/Sources/CodyncKit/Analytics/AnalyticsEvent.swift@@ -39,6 +39,7 @@ public enum AnalyticsEvent: Equatable, Sendable {public enum Screen: String, Sendable {case bots, state, chat, trace, botDetails = "bot_details", memory, routines, marketplacecase settings, computers, usage, account, pairing, voiceSettings = "voice_settings", remoteScreen = "remote_screen"+ case library, artifact}public enum NotificationKind: String, Sendable {diff --git a/apps/ios/Kit/Sources/CodyncKit/Client/HostClient+Artifacts.swift b/apps/ios/Kit/Sources/CodyncKit/Client/HostClient+Artifacts.swiftnew file mode 100644index 00000000..ab2b8e25--- /dev/null+++ b/apps/ios/Kit/Sources/CodyncKit/Client/HostClient+Artifacts.swift@@ -0,0 +1,51 @@+import CryptoKit+import Foundation++public struct ArtifactChunk: Decodable, Sendable {+ public let data: String+ public let size: Int64+ public let artifact: Artifact+}++public extension HostClient {+ /// The chat's Library, newest first. Kinds this app doesn't know are left out.+ func library(botId: String) async throws -> [ChatLibraryItem] {+ struct Res: Decodable { var items: [ChatLibraryItem.Wire] }+ let res: Res = try await call("library", ["botId": botId])+ return res.items.compactMap(\.item)+ }++ /// At most `FileDownload.chunkSize` bytes of an artifact's HTML, from `offset`.+ func readArtifact(botId: String, artifactId: String, offset: Int64) async throws -> ArtifactChunk {+ struct Body: Encodable { let botId: String; let artifactId: String; let offset: Int64 }+ return try await call("readArtifact", Body(botId: botId, artifactId: artifactId, offset: offset))+ }++ func renameArtifact(botId: String, artifactId: String, title: String) async throws -> Artifact {+ struct Res: Decodable { var artifact: Artifact }+ let res: Res = try await call("renameArtifact", ["botId": botId, "artifactId": artifactId, "title": title])+ return res.artifact+ }++ /// An artifact's whole HTML, chunk by chunk. Published again meanwhile, it reads the new version from its start.+ func readArtifactHTML(botId: String, artifactId: String) async throws -> (artifact: Artifact, html: Data) {+ var html = Data()+ var version: String?+ while true {+ let offset = html.count+ let chunk = try await readArtifact(botId: botId, artifactId: artifactId, offset: Int64(offset))+ if chunk.artifact.sha256 != version {+ version = chunk.artifact.sha256+ html = Data()+ if offset > 0 { continue }+ }+ guard let bytes = Data(base64Encoded: chunk.data), !bytes.isEmpty, Int64(html.count + bytes.count) <= chunk.size+ else { throw FileDownloadError.invalidChunk }+ html.append(bytes)+ guard Int64(html.count) == chunk.size else { continue }+ let digest = SHA256.hash(data: html).map { String(format: "%02x", $0) }.joined()+ guard digest == chunk.artifact.sha256 else { throw FileDownloadError.integrity }+ return (chunk.artifact, html)+ }+ }+}diff --git a/apps/ios/Kit/Sources/CodyncKit/Client/HostClient.swift b/apps/ios/Kit/Sources/CodyncKit/Client/HostClient.swiftindex 090d3fe3..73f4cbdd 100644--- a/apps/ios/Kit/Sources/CodyncKit/Client/HostClient.swift+++ b/apps/ios/Kit/Sources/CodyncKit/Client/HostClient.swift@@ -7,6 +7,8 @@ public enum HostEvent: Sendable {case entry(Entry)case usage(Usage)case screen(ScreenState)+ /// An artifact published or renamed (live only: the catch-up doesn't repeat them).+ case artifact(Artifact)case resync/// An event this app version couldn't decode (host newer/older than the app).case undecodable(type: String)@@ -96,6 +98,7 @@ public struct HostClient: Sendable {struct EntryWrap: Decodable { var entry: Entry }struct UsageWrap: Decodable { var usage: Usage }struct ScreenWrap: Decodable { var screen: ScreenState }+ struct ArtifactWrap: Decodable { var artifact: Artifact }let d = decoderguard let env = try? d.decode(Envelope.self, from: data) else { return nil }switch env.type {@@ -114,6 +117,9 @@ public struct HostClient: Sendable {return (try? d.decode(UsageWrap.self, from: data)).map { .usage($0.usage) }case "screen":return (try? d.decode(ScreenWrap.self, from: data)).map { .screen($0.screen) }+ case "artifact":+ // Not worth a rewind: the catch-up has no artifacts, and the list fetches them anyway.+ return (try? d.decode(ArtifactWrap.self, from: data)).map { .artifact($0.artifact) }case "resync":return .resyncdefault:diff --git a/apps/ios/Kit/Sources/CodyncKit/Models/Artifact.swift b/apps/ios/Kit/Sources/CodyncKit/Models/Artifact.swiftnew file mode 100644index 00000000..5e9e9124--- /dev/null+++ b/apps/ios/Kit/Sources/CodyncKit/Models/Artifact.swift@@ -0,0 +1,33 @@+import Foundation++/// A self-contained HTML document a bot published for the user (`host/src/chat/artifacts.rs`). Its HTML comes from+/// `readArtifact`; publishing again under the same id replaces it and moves `updatedAt`.+public struct Artifact: Codable, Hashable, Sendable, Identifiable {+ public var id: String+ public var botId: String+ public var title: String+ public var size: Int64+ public var sha256: String+ public var createdAt: Int64+ public var updatedAt: Int64+ /// Its newest card in the bot's chat: what a message about the artifact replies to. None when the artifact was+ /// published from a routine run or another bot's request.+ public var entryId: String?++ public var date: Date { Date(milliseconds: updatedAt) }++ /// The first host with artifacts and the Library.+ public static let firstHost = "2.25.0"++ /// How a message about the artifact quotes its card until the computer's own quote arrives.+ public var replyQuote: ReplyQuote? {+ entryId.map { ReplyQuote(id: $0, author: botId, text: "Artifact: \(title)", artifact: id) }+ }+}++/// What an artifact card in the chat carries (`data.artifact`): the artifact and the version it announced.+public struct ArtifactRef: Codable, Hashable, Sendable {+ public var id: String+ public var title: String+ public var updatedAt: Int64+}diff --git a/apps/ios/Kit/Sources/CodyncKit/Models/ChatLibraryItem.swift b/apps/ios/Kit/Sources/CodyncKit/Models/ChatLibraryItem.swiftnew file mode 100644index 00000000..c8b38c3c--- /dev/null+++ b/apps/ios/Kit/Sources/CodyncKit/Models/ChatLibraryItem.swift@@ -0,0 +1,75 @@+import Foundation++/// One thing in a chat's Library (`host/src/chat/library.rs`): an artifact its bot published, a file the bot shared, or+/// one the user attached, with when (an artifact's last publish, a file's message).+public struct ChatLibraryItem: Hashable, Sendable, Identifiable {+ public enum Kind: Hashable, Sendable {+ case artifact(Artifact)+ /// Saved like its chat card: `readFile` with the message's `entryId`.+ case file(SharedFile, entryId: String)+ /// Opened like in the chat: `readUpload`.+ case attachment(Attachment, entryId: String)+ }++ public var kind: Kind+ public var at: Int64++ public init(_ kind: Kind, at: Int64) {+ self.kind = kind+ self.at = at+ }++ public init(_ artifact: Artifact) { self.init(.artifact(artifact), at: artifact.updatedAt) }++ public var id: String {+ switch kind {+ case .artifact(let artifact): "artifact/\(artifact.id)"+ case .file(let file, let entryId): "file/\(entryId)/\(file.id)"+ case .attachment(let file, let entryId): "attachment/\(entryId)/\(file.id)"+ }+ }++ public var date: Date { Date(milliseconds: at) }++ /// What `library` sends; a kind or shape this app can't read becomes nil.+ struct Wire: Decodable {+ struct File: Decodable {+ var id: String+ var name: String+ var size: Int64+ var sha256: String?+ }++ var kind: String+ var at: Int64+ var entryId: String?+ var artifact: Artifact?+ var file: File?++ private enum CodingKeys: String, CodingKey { case kind, at, entryId, artifact, file }++ init(from decoder: any Decoder) throws {+ let c = try decoder.container(keyedBy: CodingKeys.self)+ kind = (try? c.decode(String.self, forKey: .kind)) ?? ""+ at = (try? c.decode(Int64.self, forKey: .at)) ?? 0+ entryId = try? c.decode(String.self, forKey: .entryId)+ artifact = try? c.decode(Artifact.self, forKey: .artifact)+ file = try? c.decode(File.self, forKey: .file)+ }++ var item: ChatLibraryItem? {+ switch (kind, artifact, file, entryId) {+ case ("artifact", let artifact?, _, _):+ ChatLibraryItem(.artifact(artifact), at: at)+ case ("file", _, let file?, let entryId?):+ file.sha256.map {+ ChatLibraryItem(.file(SharedFile(id: file.id, name: file.name, size: file.size, sha256: $0), entryId: entryId), at: at)+ }+ case ("attachment", _, let file?, let entryId?):+ ChatLibraryItem(.attachment(Attachment(id: file.id, name: file.name, size: file.size), entryId: entryId), at: at)+ default:+ nil+ }+ }+ }+}diff --git a/apps/ios/Kit/Sources/CodyncKit/Models/EntryData.swift b/apps/ios/Kit/Sources/CodyncKit/Models/EntryData.swiftindex 7e1436f0..0be53733 100644--- a/apps/ios/Kit/Sources/CodyncKit/Models/EntryData.swift+++ b/apps/ios/Kit/Sources/CodyncKit/Models/EntryData.swift@@ -55,6 +55,8 @@ public struct EntryData: Codable, Hashable, Sendable {public var files: [SharedFile]?/// notice: a finished voice call's length.public var callSeconds: Int?+ /// agent: an artifact card, the bot's artifact as published then (the newest version shows).+ public var artifact: ArtifactRef?public init(text: String? = nil, status: String? = nil, clientNonce: String? = nil) {self.text = text@@ -64,16 +66,19 @@ public struct EntryData: Codable, Hashable, Sendable {}/// The message a reply quotes: its entry, who wrote it (`user` or a bot id) and its text (at most 500-/// characters, or its file names). A partial quote still decodes, so the message itself always shows.+/// characters, or its file names), and the artifact when it is an artifact card. A partial quote still decodes, so the+/// message itself always shows.public struct ReplyQuote: Codable, Hashable, Sendable {public var id: Stringpublic var author: Stringpublic var text: String+ public var artifact: String?- public init(id: String, author: String, text: String) {+ public init(id: String, author: String, text: String, artifact: String? = nil) {self.id = idself.author = authorself.text = text+ self.artifact = artifact}public init(from decoder: any Decoder) throws {@@ -81,6 +86,7 @@ public struct ReplyQuote: Codable, Hashable, Sendable {id = try c.decodeIfPresent(String.self, forKey: .id) ?? ""author = try c.decodeIfPresent(String.self, forKey: .author) ?? ""text = try c.decodeIfPresent(String.self, forKey: .text) ?? ""+ artifact = try c.decodeIfPresent(String.self, forKey: .artifact)}}diff --git a/apps/ios/Kit/Sources/CodyncKit/Models/Models.swift b/apps/ios/Kit/Sources/CodyncKit/Models/Models.swiftindex 2d9e280e..3c9937b9 100644--- a/apps/ios/Kit/Sources/CodyncKit/Models/Models.swift+++ b/apps/ios/Kit/Sources/CodyncKit/Models/Models.swift@@ -140,7 +140,8 @@ public struct Entry: Codable, Identifiable, Hashable, Sendable {public var replyQuote: ReplyQuote {let names = (data.attachments?.map(\.name) ?? []) + (data.files?.map(\.name) ?? [])let text = data.text.flatMap { $0.isEmpty ? nil : $0 } ?? names.joined(separator: ", ")- return ReplyQuote(id: id, author: kind == "user" ? "user" : data.author ?? botId, text: String(text.prefix(500)))+ return ReplyQuote(id: id, author: kind == "user" ? "user" : data.author ?? botId, text: String(text.prefix(500)),+ artifact: data.artifact?.id)}public var date: Date { Date(milliseconds: createdAt) }diff --git a/apps/ios/Kit/Sources/CodyncKit/Resources/Languages/de.json b/apps/ios/Kit/Sources/CodyncKit/Resources/Languages/de.jsonindex e7ca89ed..80fc3d74 100644--- a/apps/ios/Kit/Sources/CodyncKit/Resources/Languages/de.json+++ b/apps/ios/Kit/Sources/CodyncKit/Resources/Languages/de.json@@ -1172,5 +1172,21 @@"Too many screen connections. Try again in a minute.": "Zu viele Bildschirmverbindungen. Versuche es in einer Minute erneut.","Choose the language for this device. Unsupported system languages use English.": "Wähle die Sprache für dieses Gerät. Nicht unterstützte Systemsprachen verwenden Englisch.","resets in {time}": "Zurücksetzung in {time}",- "Progress, step {step} of 4": "Fortschritt, Schritt {step} von 4"+ "Progress, step {step} of 4": "Fortschritt, Schritt {step} von 4",+ "Artifact": "Artefakt",+ "Message about “{title}”": "Nachricht zu „{title}“",+ "Close artifact": "Artefakt schließen",+ "Rename artifact": "Artefakt umbenennen",+ "Artifact title": "Artefakttitel",+ "Save as HTML": "Als HTML sichern",+ "Open in browser": "Im Browser öffnen",+ "Share artifact": "Artefakt teilen",+ "Couldn't open the artifact": "Artefakt konnte nicht geöffnet werden",+ "This week": "Diese Woche",+ "Earlier": "Früher",+ "Open": "Öffnen",+ "More actions": "Weitere Aktionen",+ "Library": "Mediathek",+ "Library is empty": "Die Mediathek ist leer",+ "Artifacts {name} makes and files shared in this chat show here.": "Artefakte von {name} und in diesem Chat geteilte Dateien erscheinen hier."}diff --git a/apps/ios/Kit/Sources/CodyncKit/Resources/Languages/es.json b/apps/ios/Kit/Sources/CodyncKit/Resources/Languages/es.jsonindex 5f372272..235f7baf 100644--- a/apps/ios/Kit/Sources/CodyncKit/Resources/Languages/es.json+++ b/apps/ios/Kit/Sources/CodyncKit/Resources/Languages/es.json@@ -1172,5 +1172,21 @@"Too many screen connections. Try again in a minute.": "Hay demasiadas conexiones de pantalla. Inténtalo de nuevo en un minuto.","Choose the language for this device. Unsupported system languages use English.": "Elige el idioma de este dispositivo. Los idiomas del sistema no compatibles usan inglés.","resets in {time}": "se restablece en {time}",- "Progress, step {step} of 4": "Progreso, paso {step} de 4"+ "Progress, step {step} of 4": "Progreso, paso {step} de 4",+ "Artifact": "Artefacto",+ "Message about “{title}”": "Mensaje sobre «{title}»",+ "Close artifact": "Cerrar artefacto",+ "Rename artifact": "Cambiar nombre del artefacto",+ "Artifact title": "Título del artefacto",+ "Save as HTML": "Guardar como HTML",+ "Open in browser": "Abrir en el navegador",+ "Share artifact": "Compartir artefacto",+ "Couldn't open the artifact": "No se pudo abrir el artefacto",+ "This week": "Esta semana",+ "Earlier": "Anteriores",+ "Open": "Abrir",+ "More actions": "Más acciones",+ "Library": "Biblioteca",+ "Library is empty": "La biblioteca está vacía",+ "Artifacts {name} makes and files shared in this chat show here.": "Los artefactos que crea {name} y los archivos compartidos en este chat aparecen aquí."}diff --git a/apps/ios/Kit/Sources/CodyncKit/Resources/Languages/fr.json b/apps/ios/Kit/Sources/CodyncKit/Resources/Languages/fr.jsonindex 2286cf22..ef5dcb27 100644--- a/apps/ios/Kit/Sources/CodyncKit/Resources/Languages/fr.json+++ b/apps/ios/Kit/Sources/CodyncKit/Resources/Languages/fr.json@@ -1172,5 +1172,21 @@"Too many screen connections. Try again in a minute.": "Trop de connexions à l’écran. Réessayez dans une minute.","Choose the language for this device. Unsupported system languages use English.": "Choisissez la langue de cet appareil. Les langues système non prises en charge utilisent l’anglais.","resets in {time}": "réinitialisation dans {time}",- "Progress, step {step} of 4": "Progression, étape {step} sur 4"+ "Progress, step {step} of 4": "Progression, étape {step} sur 4",+ "Artifact": "Artefact",+ "Message about “{title}”": "Message à propos de « {title} »",+ "Close artifact": "Fermer l'artefact",+ "Rename artifact": "Renommer l'artefact",+ "Artifact title": "Titre de l'artefact",+ "Save as HTML": "Enregistrer en HTML",+ "Open in browser": "Ouvrir dans le navigateur",+ "Share artifact": "Partager l'artefact",+ "Couldn't open the artifact": "Impossible d'ouvrir l'artefact",+ "This week": "Cette semaine",+ "Earlier": "Plus tôt",+ "Open": "Ouvrir",+ "More actions": "Autres actions",+ "Library": "Bibliothèque",+ "Library is empty": "La bibliothèque est vide",+ "Artifacts {name} makes and files shared in this chat show here.": "Les artefacts créés par {name} et les fichiers partagés dans cette discussion apparaissent ici."}diff --git a/apps/ios/Kit/Sources/CodyncKit/Resources/Languages/ja.json b/apps/ios/Kit/Sources/CodyncKit/Resources/Languages/ja.jsonindex 35429dca..c33c6589 100644--- a/apps/ios/Kit/Sources/CodyncKit/Resources/Languages/ja.json+++ b/apps/ios/Kit/Sources/CodyncKit/Resources/Languages/ja.json@@ -1172,5 +1172,21 @@"Too many screen connections. Try again in a minute.": "画面接続が多すぎます。 1分後にもう一度試してください。","Choose the language for this device. Unsupported system languages use English.": "このデバイスの言語を選択します。サポートされていないシステム言語では英語が使用されます。","resets in {time}": "{time}でリセット",- "Progress, step {step} of 4": "進捗、4 段階中 {step} 段階目"+ "Progress, step {step} of 4": "進捗、4 段階中 {step} 段階目",+ "Artifact": "アーティファクト",+ "Message about “{title}”": "「{title}」についてメッセージ",+ "Close artifact": "アーティファクトを閉じる",+ "Rename artifact": "アーティファクト名を変更",+ "Artifact title": "アーティファクトのタイトル",+ "Save as HTML": "HTML として保存",+ "Open in browser": "ブラウザで開く",+ "Share artifact": "アーティファクトを共有",+ "Couldn't open the artifact": "アーティファクトを開けませんでした",+ "This week": "今週",+ "Earlier": "それ以前",+ "Open": "開く",+ "More actions": "その他の操作",+ "Library": "ライブラリ",+ "Library is empty": "ライブラリは空です",+ "Artifacts {name} makes and files shared in this chat show here.": "{name} が作ったアーティファクトと、このチャットで共有したファイルがここに表示されます。"}diff --git a/apps/ios/Kit/Sources/CodyncKit/Resources/Languages/ko.json b/apps/ios/Kit/Sources/CodyncKit/Resources/Languages/ko.jsonindex 9de6601f..9d69ff04 100644--- a/apps/ios/Kit/Sources/CodyncKit/Resources/Languages/ko.json+++ b/apps/ios/Kit/Sources/CodyncKit/Resources/Languages/ko.json@@ -1172,5 +1172,21 @@"Too many screen connections. Try again in a minute.": "화면 연결이 너무 많습니다. 1분 후 다시 시도하세요.","Choose the language for this device. Unsupported system languages use English.": "이 기기의 언어를 선택하세요. 지원하지 않는 시스템 언어는 영어로 표시됩니다.","resets in {time}": "{time} 후 초기화",- "Progress, step {step} of 4": "진행 상황, 4단계 중 {step}단계"+ "Progress, step {step} of 4": "진행 상황, 4단계 중 {step}단계",+ "Artifact": "아티팩트",+ "Message about “{title}”": "“{title}”에 대해 메시지 보내기",+ "Close artifact": "아티팩트 닫기",+ "Rename artifact": "아티팩트 이름 변경",+ "Artifact title": "아티팩트 제목",+ "Save as HTML": "HTML로 저장",+ "Open in browser": "브라우저에서 열기",+ "Share artifact": "아티팩트 공유",+ "Couldn't open the artifact": "아티팩트를 열 수 없습니다",+ "This week": "이번 주",+ "Earlier": "이전",+ "Open": "열기",+ "More actions": "작업 더 보기",+ "Library": "라이브러리",+ "Library is empty": "라이브러리가 비어 있습니다",+ "Artifacts {name} makes and files shared in this chat show here.": "{name}이(가) 만든 아티팩트와 이 채팅에서 공유한 파일이 여기에 표시됩니다."}diff --git a/apps/ios/Kit/Sources/CodyncKit/Resources/Languages/zh-Hans.json b/apps/ios/Kit/Sources/CodyncKit/Resources/Languages/zh-Hans.jsonindex aeeef54a..df403ef9 100644--- a/apps/ios/Kit/Sources/CodyncKit/Resources/Languages/zh-Hans.json+++ b/apps/ios/Kit/Sources/CodyncKit/Resources/Languages/zh-Hans.json@@ -1172,5 +1172,21 @@"Too many screen connections. Try again in a minute.": "屏幕连接太多了。请过一分钟再试。","Choose the language for this device. Unsupported system languages use English.": "选择此设备的界面语言。不支持的系统语言将使用英文。","resets in {time}": "{time}后重置",- "Progress, step {step} of 4": "进度,第 {step} 步,共 4 步"+ "Progress, step {step} of 4": "进度,第 {step} 步,共 4 步",+ "Artifact": "Artifact",+ "Message about “{title}”": "针对“{title}”发消息",+ "Close artifact": "关闭 Artifact",+ "Rename artifact": "重命名 Artifact",+ "Artifact title": "Artifact 标题",+ "Save as HTML": "保存为 HTML",+ "Open in browser": "在浏览器中打开",+ "Share artifact": "分享 Artifact",+ "Couldn't open the artifact": "无法打开 Artifact",+ "This week": "本周",+ "Earlier": "更早",+ "Open": "打开",+ "More actions": "更多操作",+ "Library": "资料库",+ "Library is empty": "资料库还是空的",+ "Artifacts {name} makes and files shared in this chat show here.": "{name} 做的 Artifact,和这个对话里分享的文件,都会出现在这里。"}diff --git a/apps/ios/Kit/Sources/CodyncKit/Resources/Languages/zh-Hant.json b/apps/ios/Kit/Sources/CodyncKit/Resources/Languages/zh-Hant.jsonindex a3e4c5e4..5f56f03f 100644--- a/apps/ios/Kit/Sources/CodyncKit/Resources/Languages/zh-Hant.json+++ b/apps/ios/Kit/Sources/CodyncKit/Resources/Languages/zh-Hant.json@@ -1172,5 +1172,21 @@"Too many screen connections. Try again in a minute.": "螢幕連線太多了。請過一分鐘再試。","Choose the language for this device. Unsupported system languages use English.": "選擇此裝置的介面語言。不支援的系統語言會使用英文。","resets in {time}": "{time}後重置",- "Progress, step {step} of 4": "進度,第 {step} 步,共 4 步"+ "Progress, step {step} of 4": "進度,第 {step} 步,共 4 步",+ "Artifact": "Artifact",+ "Message about “{title}”": "針對「{title}」傳訊息",+ "Close artifact": "關閉 Artifact",+ "Rename artifact": "重新命名 Artifact",+ "Artifact title": "Artifact 標題",+ "Save as HTML": "儲存為 HTML",+ "Open in browser": "在瀏覽器中開啟",+ "Share artifact": "分享 Artifact",+ "Couldn't open the artifact": "無法開啟 Artifact",+ "This week": "本週",+ "Earlier": "更早",+ "Open": "開啟",+ "More actions": "更多操作",+ "Library": "資料庫",+ "Library is empty": "資料庫還是空的",+ "Artifacts {name} makes and files shared in this chat show here.": "{name} 做的 Artifact,和這個對話裡分享的檔案,都會出現在這裡。"}diff --git a/apps/ios/Kit/Sources/CodyncUI/Artifacts/ArtifactCard.swift b/apps/ios/Kit/Sources/CodyncUI/Artifacts/ArtifactCard.swiftnew file mode 100644index 00000000..42ff5bf1--- /dev/null+++ b/apps/ios/Kit/Sources/CodyncUI/Artifacts/ArtifactCard.swift@@ -0,0 +1,78 @@+import CodyncKit+import SwiftUI++/// An artifact card in the chat: the top of the artifact itself, small and still, fading into a footer with the+/// artifact symbol, its title and "Artifact". It shows the newest version, whichever card it is; tapping opens it.+struct ArtifactCard: View {+ let botId: String+ let ref: ArtifactRef+ let open: () -> Void+ @Environment(BotStore.self) private var model+ @Environment(\.accessibilityReduceMotion) private var reduceMotion++ static let symbol = "chart.bar.doc.horizontal"+ private static let width: CGFloat = 280+ private static let previewHeight: CGFloat = 150+ /// The artifact lays out at twice the card's size and shows at half.+ private static let scale: CGFloat = 0.5+ private static let shape = RoundedRectangle(cornerRadius: 16, style: .continuous)++ var body: some View {+ Button(action: open) {+ VStack(spacing: 0) {+ preview+ footer+ }+ .frame(width: Self.width)+ .background(Palette.bubbleAgent, in: Self.shape)+ .clipShape(Self.shape)+ .contentShape(Self.shape)+ }+ .buttonStyle(PressScale())+ .accessibilityLabel("\(L10n.tr("Artifact")): \(model.artifacts.title(ref))")+ // Read only once the row is on screen, and again when a newer version is published.+ .onAppear { model.showArtifact(ref, botId: botId) }+ .onChange(of: model.artifacts.newest(ref.id)) { model.loadArtifact(ref.id, botId: botId) }+ }++ private var preview: some View {+ let html = model.artifacts.html[ref.id]+ return ZStack {+ if let html {+ // ponytail: one live web view per card on screen; a cached snapshot per version if scrolling stutters.+ ArtifactWebView(artifactId: ref.id, html: html, interactive: false)+ .frame(width: Self.width / Self.scale, height: Self.previewHeight / Self.scale)+ .scaleEffect(Self.scale, anchor: .topLeading)+ .frame(width: Self.width, height: Self.previewHeight, alignment: .topLeading)+ .allowsHitTesting(false)+ .transition(.opacity)+ } else if model.artifacts.failures[ref.id] == nil {+ Spinner()+ } else {+ Image(systemName: Self.symbol).font(.system(size: 34)).foregroundStyle(Palette.tertiary)+ }+ }+ .frame(width: Self.width, height: Self.previewHeight)+ .clipped()+ .mask(LinearGradient(stops: [.init(color: .black, location: 0.5), .init(color: .clear, location: 1)],+ startPoint: .top, endPoint: .bottom))+ .animation(Motion.reduced(Motion.fade, reduceMotion), value: html?.updatedAt)+ .accessibilityHidden(true)+ }++ private var footer: some View {+ HStack(spacing: 8) {+ Image(systemName: Self.symbol)+ .font(.system(size: 15, weight: .medium))+ .foregroundStyle(Palette.secondary)+ Text(model.artifacts.title(ref))+ .font(.subheadline.weight(.semibold))+ .foregroundStyle(Palette.text)+ .lineLimit(1)+ Spacer(minLength: 8)+ Text(L10n.tr("Artifact")).font(.caption).foregroundStyle(Palette.secondary)+ }+ .padding(.horizontal, 14)+ .padding(.vertical, 12)+ }+}diff --git a/apps/ios/Kit/Sources/CodyncUI/Artifacts/ArtifactRenameSheet.swift b/apps/ios/Kit/Sources/CodyncUI/Artifacts/ArtifactRenameSheet.swiftnew file mode 100644index 00000000..904cce95--- /dev/null+++ b/apps/ios/Kit/Sources/CodyncUI/Artifacts/ArtifactRenameSheet.swift@@ -0,0 +1,62 @@+import CodyncKit+import SwiftUI++/// An artifact's new title; the computer trims it and every app shows it.+struct ArtifactRenameSheet: View {+ let artifact: Artifact+ @Environment(BotStore.self) private var model+ @Environment(\.dismissModal) private var dismiss+ @State private var title: String+ @State private var saving = false+ @State private var error: String?+ @FocusState private var focused: Bool++ init(artifact: Artifact) {+ self.artifact = artifact+ _title = State(initialValue: artifact.title)+ }++ private var trimmed: String { title.trimmingCharacters(in: .whitespacesAndNewlines) }++ var body: some View {+ VStack(spacing: 0) {+ ModalHeader("Rename artifact") {+ if saving {+ Spinner()+ } else {+ IconButton("Save", systemImage: "checkmark", action: save)+ .disabled(trimmed.isEmpty || trimmed == artifact.title)+ }+ }+ CardForm {+ CardSection {+ TextField(L10n.tr("Artifact title"), text: $title)+ .focused($focused)+ .submitLabel(.done)+ .onSubmit(save)+ }+ if let error {+ Text(L10n.tr(error)).font(.caption).foregroundStyle(Palette.danger).textSelection(.enabled)+ }+ }+ .textFieldStyle(.plain)+ }+ .background(Palette.background)+ .presentationDetents([.medium])+ .onAppear { focused = true }+ }++ private func save() {+ guard !saving, !trimmed.isEmpty, trimmed != artifact.title else { return }+ saving = true+ Task {+ do {+ try await model.renameArtifact(artifact, title: trimmed)+ dismiss()+ } catch {+ self.error = error.localizedDescription+ }+ saving = false+ }+ }+}diff --git a/apps/ios/Kit/Sources/CodyncUI/Artifacts/ArtifactView.swift b/apps/ios/Kit/Sources/CodyncUI/Artifacts/ArtifactView.swiftnew file mode 100644index 00000000..4375ffb1--- /dev/null+++ b/apps/ios/Kit/Sources/CodyncUI/Artifacts/ArtifactView.swift@@ -0,0 +1,125 @@+import CodyncKit+import SwiftUI++/// An artifact to open: its bot and id, and the title to show until its details arrive.+struct ArtifactTarget: Identifiable, Equatable {+ let botId: String+ let id: String+ let title: String+}++/// A temporary `<title>.html` for the share sheet.+struct ArtifactFile: Identifiable {+ let url: URL+ var id: URL { url }+}++extension View {+ /// The share sheet for an artifact's `<title>.html` while `file` is set; the temporary copy goes when it closes.+ func artifactShareSheet(_ file: Binding<ArtifactFile?>) -> some View { modifier(ArtifactShareSheet(file: file)) }+}++private struct ArtifactShareSheet: ViewModifier {+ @Binding var file: ArtifactFile?+ @Environment(BotStore.self) private var model++ func body(content: Content) -> some View {+ content.codyncSheet(item: $file) { shared in+ FileExportSheet(url: shared.url) {+ file = nil+ model.removeArtifactFile(shared.url)+ }+ }+ }+}++/// An artifact full size, in a web view of its own: close, the title (tap to rename) and share on top, and a box at the+/// bottom for messages about the artifact, which go to the bot as replies to its card. The viewer stays open, and a+/// version the bot publishes meanwhile replaces the one shown.+struct ArtifactView: View {+ let target: ArtifactTarget+ @Environment(BotStore.self) private var model+ @Environment(\.dismissModal) private var dismiss+ @Environment(\.accessibilityReduceMotion) private var reduceMotion+ @State private var renaming: Artifact?+ @State private var sharing: ArtifactFile?+ @State private var shareError: String?++ private var botId: String { target.botId }+ private var artifact: Artifact? { model.artifacts.details[target.id] }+ private var title: String { artifact?.title ?? target.title }++ var body: some View {+ VStack(spacing: 0) {+ // The sheet's grabber takes taps in its top ~30 pt, so the centred title (tap to rename) sits below them.+ header.padding(.top, 16)+ content+ }+ .safeAreaInset(edge: .bottom) {+ // An artifact published without a card (a routine run, another bot's request) has nothing to reply to.+ if let artifact, artifact.entryId != nil {+ Composer(botId: botId, replyingTo: .constant(nil), artifact: artifact)+ }+ }+ .background(Palette.background)+ .onAppear { model.loadArtifact(target.id, botId: botId) }+ .onChange(of: model.artifacts.newest(target.id)) { model.loadArtifact(target.id, botId: botId) }+ .codyncSheet(item: $renaming) { ArtifactRenameSheet(artifact: $0) }+ .artifactShareSheet($sharing)+ .tracked(.screenViewed(.artifact))+ .codyncDialog("Couldn't open the artifact",+ isPresented: Binding(get: { shareError != nil }, set: { if !$0 { shareError = nil } }),+ message: shareError, cancel: "OK") { [] }+ }++ private var header: some View {+ ScreenHeader {+ IconButton("Close artifact", systemImage: "xmark") { dismiss() }+ } title: {+ Button { renaming = artifact } label: {+ Text(title)+ .font(.body.weight(.semibold))+ .foregroundStyle(Palette.text)+ .lineLimit(1)+ .padding(.horizontal, 48)+ }+ .buttonStyle(PressScale())+ .disabled(artifact == nil)+ .accessibilityHint(L10n.tr("Rename artifact"))+ } trailing: {+ IconButton("Share artifact", systemImage: "square.and.arrow.up") { share() }+ .disabled(model.artifacts.html[target.id] == nil)+ }+ }++ @ViewBuilder private var content: some View {+ let html = model.artifacts.html[target.id]+ ZStack {+ if let html {+ ArtifactWebView(artifactId: target.id, html: html)+ .transition(.opacity)+ } else if let failure = model.artifacts.failures[target.id] {+ VStack(spacing: 6) {+ Text(L10n.tr("Couldn't open the artifact")).font(.headline).foregroundStyle(Palette.text)+ Text(L10n.tr(failure)).font(.subheadline).foregroundStyle(Palette.secondary).textSelection(.enabled)+ }+ .multilineTextAlignment(.center)+ .padding(24)+ } else {+ Spinner(size: 20)+ }+ }+ .frame(maxWidth: .infinity, maxHeight: .infinity)+ .animation(Motion.reduced(Motion.fade, reduceMotion), value: html?.updatedAt)+ }++ private func share() {+ Task {+ do {+ sharing = ArtifactFile(url: try await model.artifactFile(target.id, botId: botId))+ } catch {+ shareError = error.localizedDescription+ }+ }+ }+}diff --git a/apps/ios/Kit/Sources/CodyncUI/Artifacts/ArtifactWebView.swift b/apps/ios/Kit/Sources/CodyncUI/Artifacts/ArtifactWebView.swiftnew file mode 100644index 00000000..a090a73e--- /dev/null+++ b/apps/ios/Kit/Sources/CodyncUI/Artifacts/ArtifactWebView.swift@@ -0,0 +1,87 @@+import CodyncKit+import SwiftUI+import UIKit+import WebKit++/// An artifact's HTML in a web view of its own: its scripts run, nothing of the app is reachable from it, and what it+/// opens goes to the browser. Each artifact has an origin of its own, so what it keeps (a tracker's ticks) stays its own.+struct ArtifactWebView: UIViewRepresentable {+ let artifactId: String+ let html: ArtifactCache.HTML+ /// The chat card's preview: no touches, and the artifact opens nothing.+ var interactive = true++ func makeCoordinator() -> Coordinator { Coordinator() }++ func makeUIView(context: Context) -> WKWebView {+ let configuration = WKWebViewConfiguration()+ configuration.userContentController.addUserScript(Self.viewport)+ let view = WKWebView(frame: .zero, configuration: configuration)+ view.navigationDelegate = context.coordinator+ view.uiDelegate = context.coordinator+ return view+ }++ func updateUIView(_ view: WKWebView, context: Context) {+ let coordinator = context.coordinator+ coordinator.interactive = interactive+ view.isUserInteractionEnabled = interactive+ let origin = Self.origin(artifactId)+ let shown = "\(artifactId)@\(html.updatedAt)"+ guard coordinator.shown != shown else { return }+ coordinator.shown = shown+ coordinator.origin = origin?.host+ view.loadHTMLString(html.text, baseURL: origin)+ }++ /// Never resolves: relative links go nowhere, and the artifact gets an origin to keep its storage under.+ static func origin(_ artifactId: String) -> URL? {+ URL(string: "https://\(artifactId.lowercased()).artifact.codync.invalid/")+ }++ /// An artifact written without a viewport would lay out 980 points wide and show tiny on a phone.+ private static let viewport = WKUserScript(source: """+ if (!document.querySelector('meta[name="viewport"]')) {+ const meta = document.createElement('meta');+ meta.name = 'viewport';+ meta.content = 'width=device-width, initial-scale=1';+ document.head.appendChild(meta);+ }+ """, injectionTime: .atDocumentEnd, forMainFrameOnly: true)++ @MainActor final class Coordinator: NSObject, WKNavigationDelegate, WKUIDelegate {+ var interactive = true+ var shown: String?+ var origin: String?++ func webView(_ webView: WKWebView, decidePolicyFor action: WKNavigationAction,+ decisionHandler: @escaping @MainActor @Sendable (WKNavigationActionPolicy) -> Void) {+ decisionHandler(policy(for: action))+ }++ /// The artifact's own document (its #anchors too) and the frames it embeds load here; a link the user follows+ /// goes to the browser instead, and the artifact sending itself elsewhere goes nowhere.+ private func policy(for action: WKNavigationAction) -> WKNavigationActionPolicy {+ guard let url = action.request.url else { return .cancel }+ if (origin != nil && url.host == origin) || url.scheme == "about" { return .allow }+ let followed = action.navigationType == .linkActivated+ if action.targetFrame?.isMainFrame == false, !followed { return .allow }+ if followed { leave(to: url) }+ return .cancel+ }++ /// `target="_blank"` and `window.open` (WebKit lets a script open one only from a tap).+ func webView(_ webView: WKWebView, createWebViewWith configuration: WKWebViewConfiguration,+ for action: WKNavigationAction, windowFeatures: WKWindowFeatures) -> WKWebView? {+ if let url = action.request.url { leave(to: url) }+ return nil+ }++ /// Web, mail and phone links only, as on Android: another app's scheme goes nowhere.+ private func leave(to url: URL) {+ guard interactive, let scheme = url.scheme?.lowercased(), ["http", "https", "mailto", "tel"].contains(scheme)+ else { return }+ UIApplication.shared.open(url)+ }+ }+}diff --git a/apps/ios/Kit/Sources/CodyncUI/Artifacts/LibraryView.swift b/apps/ios/Kit/Sources/CodyncUI/Artifacts/LibraryView.swiftnew file mode 100644index 00000000..5d460652--- /dev/null+++ b/apps/ios/Kit/Sources/CodyncUI/Artifacts/LibraryView.swift@@ -0,0 +1,151 @@+import CodyncKit+import SwiftUI++/// A chat's Library (the details sheet's Library tab): the artifacts its bot published and the files shared in it,+/// grouped by when. A row does what tapping it in the chat does; an artifact's menu also renames or shares it.+struct LibraryView: View {+ let botId: String+ /// Opens an artifact in the chat's viewer (the details sheet closes first).+ let openArtifact: (ArtifactTarget) -> Void+ @Environment(BotStore.self) private var model+ @Environment(\.accessibilityReduceMotion) private var reduceMotion+ /// The files shared in the chat; its artifacts come from the store, where their events keep them current.+ @State private var files: [ChatLibraryItem] = []+ @State private var loaded = false+ @State private var error: String?+ @State private var renaming: Artifact?+ @State private var sharing: ArtifactFile?+ @State private var viewing: Attachment?++ var body: some View {+ let items = files + model.artifacts.artifacts(of: botId).map(ChatLibraryItem.init)+ VStack(alignment: .leading, spacing: 28) {+ if let error {+ Text(L10n.tr(error)).font(.caption).foregroundStyle(Palette.danger).textSelection(.enabled)+ }+ if !items.isEmpty {+ ForEach(ChatLibraryItem.sections(items), id: \.period) { section in+ CardSection(section.period.rawValue) {+ ForEach(section.items) { row($0) }+ }+ }+ } else if loaded {+ empty+ } else {+ Spinner(size: 20).frame(maxWidth: .infinity).padding(.top, 40)+ }+ }+ .animation(Motion.reduced(Motion.fade, reduceMotion), value: loaded)+ .tracked(.screenViewed(.library))+ .task(id: botId) {+ do {+ files = try await model.loadLibrary(botId)+ } catch {+ self.error = error.localizedDescription+ }+ loaded = true+ }+ .codyncSheet(item: $renaming) { ArtifactRenameSheet(artifact: $0) }+ .artifactShareSheet($sharing)+ .codyncSheet(item: $viewing) { AttachmentViewer(file: $0, botId: botId) }+ .fileExportSheet(model, botId: botId)+ }++ @ViewBuilder private func row(_ item: ChatLibraryItem) -> some View {+ switch item.kind {+ case .artifact(let artifact):+ Button { show(artifact) } label: {+ LibraryRow(title: artifact.title) { symbol(ArtifactCard.symbol) }+ }+ .buttonStyle(.plain)+ .contextActions {+ [MenuItem("Open", icon: "arrow.up.forward.square") { show(artifact) },+ MenuItem("Rename artifact", icon: "pencil") { renaming = artifact },+ MenuItem("Share artifact", icon: "square.and.arrow.up") { share(artifact) }]+ }+ case .file(let file, let entryId):+ Button { download(file, entryId: entryId) } label: {+ LibraryRow(title: file.name, detail: FileDownloadCard.detail(model.fileDownloads.states[file.id], size: file.size)) {+ symbol(AttachmentIcon.symbol(file.name))+ }+ }+ .buttonStyle(.plain)+ case .attachment(let file, _) where file.isImage:+ Button { viewing = file } label: {+ LibraryRow(title: file.name) {+ AttachmentImage(file: file, botId: botId, maxPixels: 120, contentMode: .fill)+ .frame(width: 36, height: 36)+ .clipShape(RoundedRectangle(cornerRadius: 8, style: .continuous))+ }+ }+ .buttonStyle(.plain)+ case .attachment(let file, _):+ // Like its chat card, nothing to open on the phone: the agent reads it on the computer.+ LibraryRow(title: file.name, detail: ByteCountFormatter.string(fromByteCount: file.size, countStyle: .file)) {+ symbol(AttachmentIcon.symbol(file.name))+ }+ }+ }++ private func symbol(_ name: String) -> some View {+ Image(systemName: name).font(.system(size: 18)).foregroundStyle(Palette.secondary)+ }++ private var empty: some View {+ VStack(spacing: 8) {+ Image(systemName: "books.vertical").font(.system(size: 34)).foregroundStyle(Palette.tertiary)+ Text(L10n.tr("Library is empty")).font(.headline).foregroundStyle(Palette.text)+ Text(L10n.tr("Artifacts {name} makes and files shared in this chat show here.")+ .replacingOccurrences(of: "{name}", with: model.bots[botId]?.name ?? ""))+ .font(.subheadline)+ .foregroundStyle(Palette.secondary)+ }+ .multilineTextAlignment(.center)+ .padding(.vertical, 32)+ .frame(maxWidth: .infinity)+ }++ private func show(_ artifact: Artifact) {+ openArtifact(ArtifactTarget(botId: artifact.botId, id: artifact.id, title: artifact.title))+ }++ private func share(_ artifact: Artifact) {+ Task {+ do {+ sharing = ArtifactFile(url: try await model.artifactFile(artifact.id, botId: botId))+ } catch {+ self.error = error.localizedDescription+ }+ }+ }++ /// As the file's chat card does: download it for the share sheet, or stop the download under way.+ private func download(_ file: SharedFile, entryId: String) {+ Motion.animate {+ if case .downloading = model.fileDownloads.states[file.id] {+ model.fileDownloads.cancel(file.id)+ } else {+ model.fileDownloads.save(client: model.client, entryId: entryId, botId: botId, file: file)+ }+ }+ }+}++/// One Library row: its picture (a symbol or a thumbnail), the name, and an optional line under it.+private struct LibraryRow<Leading: View>: View {+ let title: String+ var detail: String?+ @ViewBuilder let leading: Leading++ var body: some View {+ HStack(spacing: 12) {+ leading.frame(width: 36, height: 36)+ VStack(alignment: .leading, spacing: 2) {+ Text(title).foregroundStyle(Palette.text).lineLimit(2)+ if let detail { Text(L10n.tr(detail)).font(.caption).foregroundStyle(Palette.secondary) }+ }+ Spacer(minLength: 0)+ }+ .contentShape(Rectangle())+ }+}diff --git a/apps/ios/Kit/Sources/CodyncUI/Bots/BotDetailsView.swift b/apps/ios/Kit/Sources/CodyncUI/Bots/BotDetailsView.swiftindex 8aae0fa1..8d77f78e 100644--- a/apps/ios/Kit/Sources/CodyncUI/Bots/BotDetailsView.swift+++ b/apps/ios/Kit/Sources/CodyncUI/Bots/BotDetailsView.swift@@ -3,7 +3,7 @@ import SwiftUI/// The details sheet's pages, as on the desktop inspector.enum DetailsTab: Hashable {- case details, memory, settings+ case details, library, memory, settings}/// What to open the details sheet on.@@ -16,11 +16,13 @@ struct DetailsRequest: Identifiable {var botId: String?}-/// A bot's details (Grok Bot's): who it is, then its details, memory and settings. Settings save+/// A bot's details (Grok Bot's): who it is, then its details, library, memory and settings. Settings save/// as you edit.struct BotDetailsView: View {let botId: Stringlet routineId: String?+ /// An artifact picked in the Library, for the chat's viewer.+ let openArtifact: (ArtifactTarget) -> Void@State var tab: DetailsTab@Environment(BotStore.self) private var model@Environment(\.dismissModal) private var dismiss@@ -29,8 +31,9 @@ struct BotDetailsView: View {@State private var saving: Task<Void, Never>?@State private var template: EditorRequest?- init(botId: String, request: DetailsRequest) {+ init(botId: String, request: DetailsRequest, openArtifact: @escaping (ArtifactTarget) -> Void) {self.botId = botId+ self.openArtifact = openArtifactroutineId = request.routineId_tab = State(initialValue: request.tab)}@@ -41,7 +44,8 @@ struct BotDetailsView: View {ScrollView {VStack(spacing: 0) {if let bot { identity(bot) }- TabChoice(selection: $tab, options: [(.details, "Details"), (.memory, "Memory"), (.settings, "Settings")])+ TabChoice(selection: $tab, options: [(.details, "Details")] + (model.hasLibrary ? [(.library, "Library")] : [])+ + [(.memory, "Memory"), (.settings, "Settings")]).padding(.top, 18)page.padding(.top, 20).environment(\.cardStyle, .outlined)@@ -132,6 +136,8 @@ struct BotDetailsView: View {}RoutinesView(botId: botId, initialId: routineId) { dismiss() }}+ case .library:+ LibraryView(botId: botId, openArtifact: openArtifact)case .memory:MemoryCard(botId: botId)case .settings:diff --git a/apps/ios/Kit/Sources/CodyncUI/Store/ArtifactCache.swift b/apps/ios/Kit/Sources/CodyncUI/Store/ArtifactCache.swiftnew file mode 100644index 00000000..e91ff677--- /dev/null+++ b/apps/ios/Kit/Sources/CodyncUI/Store/ArtifactCache.swift@@ -0,0 +1,53 @@+import CodyncKit+import Foundation++/// One computer's artifacts: their details by id (from `library`, `readArtifact` and the `artifact` events), the+/// versions their cards announced, and the HTML of the ones shown with the version it is, read again once a newer one+/// is known.+struct ArtifactCache {+ struct HTML: Equatable {+ let updatedAt: Int64+ let text: String+ }++ private(set) var details: [String: Artifact] = [:]+ private(set) var html: [String: HTML] = [:]+ /// The newest version each artifact's cards announced (an entry can bring one the details missed while away).+ private var announced: [String: Int64] = [:]+ var failures: [String: String] = [:]+ var reading: Set<String> = []++ /// Older details never replace newer ones; a rename keeps `updatedAt`, so it does.+ mutating func upsert(_ artifact: Artifact) {+ if let known = details[artifact.id], known.updatedAt > artifact.updatedAt { return }+ details[artifact.id] = artifact+ }++ mutating func announce(_ card: ArtifactRef) {+ announced[card.id] = max(announced[card.id] ?? 0, card.updatedAt)+ }++ mutating func store(_ artifact: Artifact, html text: String) {+ html[artifact.id] = HTML(updatedAt: artifact.updatedAt, text: text)+ upsert(artifact)+ }++ /// The newest version of an artifact known here.+ func newest(_ id: String) -> Int64 {+ max(announced[id] ?? 0, details[id]?.updatedAt ?? 0)+ }++ /// The HTML held is older than the newest version known (or missing), and no read is under way.+ func needsRead(_ id: String) -> Bool {+ !reading.contains(id) && (html[id]?.updatedAt ?? -1) < newest(id)+ }++ /// A card's title: the artifact's own once it is as new as the card.+ func title(_ card: ArtifactRef) -> String {+ details[card.id].flatMap { $0.updatedAt >= card.updatedAt ? $0.title : nil } ?? card.title+ }++ func artifacts(of botId: String) -> [Artifact] {+ details.values.filter { $0.botId == botId }.sorted { $0.updatedAt > $1.updatedAt }+ }+}diff --git a/apps/ios/Kit/Sources/CodyncUI/Store/BotStore+Artifacts.swift b/apps/ios/Kit/Sources/CodyncUI/Store/BotStore+Artifacts.swiftnew file mode 100644index 00000000..2136aa48--- /dev/null+++ b/apps/ios/Kit/Sources/CodyncUI/Store/BotStore+Artifacts.swift@@ -0,0 +1,80 @@+import CodyncKit+import Foundation+import os++private let log = Logger(subsystem: "com.pokai.Codync", category: "Artifacts")++extension BotStore {+ /// Whether the computer's host has the Library; an older one has no `library` method, so the app leaves it out.+ var hasLibrary: Bool { hostVersion.map { !AppVersion.isBelow($0.version, Artifact.firstHost) } ?? false }++ /// The chat's Library as the computer lists it now: its artifacts go to `artifacts` (where their events land too),+ /// the files shared in the chat come back.+ func loadLibrary(_ botId: String) async throws -> [ChatLibraryItem] {+ let items = try await withLink(replay: true) { try await $0.library(botId: botId) }+ return items.filter { item in+ guard case .artifact(let artifact) = item.kind else { return true }+ artifacts.upsert(artifact)+ return false+ }+ }++ /// A card on screen: the version it names is known now (history and the cache don't come as events), and the+ /// artifact's HTML is read unless the newest version is here.+ func showArtifact(_ ref: ArtifactRef, botId: String) {+ artifacts.announce(ref)+ loadArtifact(ref.id, botId: botId)+ }++ /// Reads an artifact's HTML in the background unless the newest version known is already here.+ func loadArtifact(_ id: String, botId: String) {+ guard !retired, artifacts.needsRead(id) else { return }+ artifacts.reading.insert(id)+ artifacts.failures[id] = nil+ Task {+ do {+ try await readArtifact(id, botId: botId)+ artifacts.reading.remove(id)+ // A version published while this one was read is read next.+ loadArtifact(id, botId: botId)+ } catch {+ artifacts.reading.remove(id)+ artifacts.failures[id] = error.localizedDescription+ }+ }+ }++ private func readArtifact(_ id: String, botId: String) async throws {+ let read = try await withLink(replay: true) { try await $0.readArtifactHTML(botId: botId, artifactId: id) }+ artifacts.store(read.artifact, html: String(decoding: read.html, as: UTF8.self))+ }++ func renameArtifact(_ artifact: Artifact, title: String) async throws {+ let renamed = try await withLink {+ try await $0.renameArtifact(botId: artifact.botId, artifactId: artifact.id, title: title)+ }+ artifacts.upsert(renamed)+ }++ /// The artifact's newest HTML as `<title>.html`, in a folder of its own for the share sheet+ /// (`removeArtifactFile`).+ func artifactFile(_ id: String, botId: String) async throws -> URL {+ if artifacts.html[id] == nil || artifacts.needsRead(id) { try await readArtifact(id, botId: botId) }+ guard let artifact = artifacts.details[id], let html = artifacts.html[id] else { throw FileDownloadError.invalidMetadata }+ let folder = FileManager.default.temporaryDirectory.appending(path: "CodyncArtifacts/\(UUID().uuidString)")+ try FileManager.default.createDirectory(at: folder, withIntermediateDirectories: true)+ let name = artifact.title.components(separatedBy: CharacterSet(charactersIn: "/:\\")).joined(separator: "-")+ let url = folder.appending(path: "\(name).html")+ try Data(html.text.utf8).write(to: url)+ return url+ }++ func removeArtifactFile(_ url: URL) {+ do {+ try FileManager.default.removeItem(at: url.deletingLastPathComponent())+ } catch {+ // The system clears the temporary folder in time anyway.+ log.debug("artifact file left behind: \(error.localizedDescription)")+ }+ }+}diff --git a/apps/ios/Kit/Sources/CodyncUI/Store/BotStore+Sending.swift b/apps/ios/Kit/Sources/CodyncUI/Store/BotStore+Sending.swiftindex 5f36116b..737668a7 100644--- a/apps/ios/Kit/Sources/CodyncUI/Store/BotStore+Sending.swift+++ b/apps/ios/Kit/Sources/CodyncUI/Store/BotStore+Sending.swift@@ -35,20 +35,26 @@ extension BotStore {storage.composerDrafts[computer.id] = composerDrafts.isEmpty ? nil : composerDrafts}+ /// The chat's draft, and the drafts of its artifacts (`artifactDraftKey`).func removeComposerDrafts(for botId: String) {- composerDrafts[botId] = nil+ composerDrafts = composerDrafts.filter { $0.key != botId && !$0.key.hasPrefix("\(botId)/") }persistComposerDrafts()}+ /// An artifact viewer's message box keeps its own draft, apart from the chat's.+ static func artifactDraftKey(_ artifact: Artifact) -> String { "\(artifact.botId)/artifact/\(artifact.id)" }+/// Transfer to the outbox now; an eventual acknowledgement must not erase a newer draft.- /// `replyTo`: the chat message it quotes.+ /// `draft`: whose draft it is (the chat's when nil). `replyTo`: the chat message it quotes.@discardableResult- func sendComposerDraft(to botId: String, replyTo: Entry? = nil, files: [OutgoingFile] = []) -> Bool {- let text = composerDraft(for: botId)+ func sendComposerDraft(to botId: String, draft key: String? = nil, replyTo: ReplyQuote? = nil,+ files: [OutgoingFile] = []) -> Bool {+ let key = key ?? botId+ let text = composerDraft(for: key)guard !retired, !text.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty || !files.isEmpty else { return false }- let pasted = composerPasted[botId] ?? []- send(text, to: botId, replyTo: replyTo?.replyQuote, nonce: UUID().uuidString, files: files, pasted: pasted)- setComposerDraft("", for: botId)+ let pasted = composerPasted[key] ?? []+ send(text, to: botId, replyTo: replyTo, nonce: UUID().uuidString, files: files, pasted: pasted)+ setComposerDraft("", for: key)return true}diff --git a/apps/ios/Kit/Sources/CodyncUI/Store/BotStore+Sync.swift b/apps/ios/Kit/Sources/CodyncUI/Store/BotStore+Sync.swiftindex 2420bcf1..a4773e66 100644--- a/apps/ios/Kit/Sources/CodyncUI/Store/BotStore+Sync.swift+++ b/apps/ios/Kit/Sources/CodyncUI/Store/BotStore+Sync.swift@@ -118,6 +118,7 @@ extension BotStore {}let known = entries[e.botId]?.first(where: { $0.id == e.id })upsert(e)+ if let card = e.data.artifact { artifacts.announce(card) }bump(e.rev)acknowledgeVisibleConversations(e.botId, entry: e)let calls = Array(voiceCalls.values).filter { $0.botId == e.botId && e.rev > $0.startRev }@@ -133,6 +134,8 @@ extension BotStore {setUsage(u)case let .screen(s):screen = s+ case let .artifact(artifact):+ artifacts.upsert(artifact)case .resync:restartEvents()case let .undecodable(type):diff --git a/apps/ios/Kit/Sources/CodyncUI/Store/BotStore.swift b/apps/ios/Kit/Sources/CodyncUI/Store/BotStore.swiftindex c7bafcbd..3e5c7d25 100644--- a/apps/ios/Kit/Sources/CodyncUI/Store/BotStore.swift+++ b/apps/ios/Kit/Sources/CodyncUI/Store/BotStore.swift@@ -73,6 +73,7 @@ public final class BotStore {@ObservationIgnored var composerPasted: [String: [String]] = [:]public var routineDrafts: [String: String] = [:]public let fileDownloads = FileDownloads()+ var artifacts = ArtifactCache()public var lastError: String?/// The open conversation (navigation path).public var selection: String?diff --git a/apps/ios/Kit/Sources/CodyncUI/Store/FileDownloads.swift b/apps/ios/Kit/Sources/CodyncUI/Store/FileDownloads.swiftindex 575468ed..0ea9bbca 100644--- a/apps/ios/Kit/Sources/CodyncUI/Store/FileDownloads.swift+++ b/apps/ios/Kit/Sources/CodyncUI/Store/FileDownloads.swift@@ -32,6 +32,11 @@ public final class FileDownloads {init(writer: any FileDownloadWriting) { self.writer = writer }public func save(client: HostClient?, entry: Entry, file: SharedFile) {+ save(client: client, entryId: entry.id, botId: entry.botId, file: file)+ }++ /// `entryId`: the message that shared the file (a Library row has only that).+ public func save(client: HostClient?, entryId: String, botId: String, file: SharedFile) {guard !retired else { return }guard tasks.isEmpty else {if tasks[file.id] == nil { states[file.id] = .failed("Finish the current download first.") }@@ -47,12 +52,12 @@ public final class FileDownloads {tasks[file.id] = Task {defer { tasks[file.id] = nil }do {- let url = try await writer.save(client: client, entryId: entry.id, file: file, directory: directory) { [weak self] received in+ let url = try await writer.save(client: client, entryId: entryId, file: file, directory: directory) { [weak self] received inawait 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)+ let item = Export(id: file.id, url: url, botId: botId)exported = itemexport = item} catch is CancellationError {diff --git a/apps/ios/Kit/Sources/CodyncUI/Store/LibrarySections.swift b/apps/ios/Kit/Sources/CodyncUI/Store/LibrarySections.swiftnew file mode 100644index 00000000..8bc75368--- /dev/null+++ b/apps/ios/Kit/Sources/CodyncUI/Store/LibrarySections.swift@@ -0,0 +1,25 @@+import CodyncKit+import Foundation++extension ChatLibraryItem {+ enum Period: String, CaseIterable {+ case today = "Today", yesterday = "Yesterday", thisWeek = "This week", earlier = "Earlier"+ }++ /// The Library's groups by when each item was published or shared, newest first; empty groups left out.+ static func sections(_ items: [ChatLibraryItem], now: Date = .now, calendar: Calendar = .current)+ -> [(period: Period, items: [ChatLibraryItem])] {+ let grouped = Dictionary(grouping: items) { item -> Period in+ if calendar.isDate(item.date, inSameDayAs: now) { return .today }+ if let yesterday = calendar.date(byAdding: .day, value: -1, to: now), calendar.isDate(item.date, inSameDayAs: yesterday) {+ return .yesterday+ }+ // The last seven days, as on the other clients (not the calendar week).+ let weekAgo = calendar.date(byAdding: .day, value: -6, to: calendar.startOfDay(for: now)) ?? now+ return item.date >= weekAgo ? .thisWeek : .earlier+ }+ return Period.allCases.compactMap { period in+ grouped[period].map { (period, $0.sorted { $0.at > $1.at }) }+ }+ }+}diff --git a/apps/ios/Kit/Sources/CodyncUI/Thread/Attachments.swift b/apps/ios/Kit/Sources/CodyncUI/Thread/Attachments.swiftindex 836417ca..139f2570 100644--- a/apps/ios/Kit/Sources/CodyncUI/Thread/Attachments.swift+++ b/apps/ios/Kit/Sources/CodyncUI/Thread/Attachments.swift@@ -111,15 +111,7 @@ struct AttachmentList: View {}}}- .codyncSheet(item: $viewing) { file in- VStack(spacing: 0) {- ModalHeader(file.name)- AttachmentImage(file: file, botId: botId, maxPixels: 4096)- .frame(maxWidth: .infinity, maxHeight: .infinity)- .padding(12)- }- .background(Palette.background)- }+ .codyncSheet(item: $viewing) { AttachmentViewer(file: $0, botId: botId) }}private func card(_ file: Attachment) -> some View {@@ -145,18 +137,35 @@ struct AttachmentList: View {}}+/// A sent image full size.+struct AttachmentViewer: View {+ let file: Attachment+ let botId: String++ var body: some View {+ VStack(spacing: 0) {+ ModalHeader(file.name)+ AttachmentImage(file: file, botId: botId, maxPixels: 4096)+ .frame(maxWidth: .infinity, maxHeight: .infinity)+ .padding(12)+ }+ .background(Palette.background)+ }+}+/// A sent image, fetched from the computer once and then read from the cache.-private struct AttachmentImage: View {+struct AttachmentImage: View {let file: Attachmentlet botId: Stringlet maxPixels: Int+ var contentMode: ContentMode = .fit@Environment(BotStore.self) private var model@State private var image: CGImage?var body: some View {Group {if let image {- Image(decorative: image, scale: 1).resizable().aspectRatio(contentMode: .fit)+ Image(decorative: image, scale: 1).resizable().aspectRatio(contentMode: contentMode)} else {RoundedRectangle(cornerRadius: 16, style: .continuous).fill(Palette.bubbleUser)diff --git a/apps/ios/Kit/Sources/CodyncUI/Thread/ChatRows.swift b/apps/ios/Kit/Sources/CodyncUI/Thread/ChatRows.swiftindex 6b8a0935..bb8175fa 100644--- a/apps/ios/Kit/Sources/CodyncUI/Thread/ChatRows.swift+++ b/apps/ios/Kit/Sources/CodyncUI/Thread/ChatRows.swift@@ -14,6 +14,8 @@ struct ChatRow: View {var reply: (() -> Void)?/// A failure notice's "Add a fallback": the bot's details.var addFallback: (() -> Void)?+ /// An artifact card's artifact, full size.+ var openArtifact: ((ArtifactRef) -> Void)?@Environment(BotStore.self) private var model@Environment(\.accessibilityReduceMotion) private var reduceMotion@@ -30,7 +32,7 @@ struct ChatRow: View {case "agent":VStack(alignment: .leading, spacing: 4) {if chat?.isGroup == true, groupStart { AuthorLabel(botId: entry.data.author) }- AgentBubble(entry: entry, openTrace: openTrace, reply: reply)+ AgentBubble(entry: entry, openTrace: openTrace, reply: reply, openArtifact: openArtifact)ReactionsRow(entry: entry).padding(.leading, chat?.isGroup == true ? 34 : 0)}@@ -184,12 +186,15 @@ struct AgentBubble: View {let entry: Entrylet openTrace: () -> Voidvar reply: (() -> Void)?+ var openArtifact: ((ArtifactRef) -> Void)?@Environment(BotStore.self) private var modelvar body: some View {VStack(alignment: .leading, spacing: 4) {Group {- if let files = entry.data.files, !files.isEmpty {+ if let artifact = entry.data.artifact {+ ArtifactCard(botId: entry.botId, ref: artifact) { openArtifact?(artifact) }+ } else if let files = entry.data.files, !files.isEmpty {ForEach(files) { file in FileDownloadCard(entry: entry, file: file) }} else {MarkdownText(entry.data.text ?? "").equatable()diff --git a/apps/ios/Kit/Sources/CodyncUI/Thread/Composer.swift b/apps/ios/Kit/Sources/CodyncUI/Thread/Composer.swiftindex 880e5884..a170c088 100644--- a/apps/ios/Kit/Sources/CodyncUI/Thread/Composer.swift+++ b/apps/ios/Kit/Sources/CodyncUI/Thread/Composer.swift@@ -14,6 +14,8 @@ struct Composer: View {var onCall: (() -> Void)?/// Interrupts the bot while it is speaking in a voice call.var onInterrupt: (() -> Void)?+ /// An artifact's viewer: every message is about the artifact (a reply to its card), from a draft of its own.+ var artifact: Artifact?@Environment(BotStore.self) private var model@Environment(\.accessibilityReduceMotion) private var reduceMotion/// The field owns its text; the store only keeps a copy. A field bound straight to the@@ -32,6 +34,7 @@ struct Composer: View {@ScaledMetric(relativeTo: .body) private var lineHeight: CGFloat = 22private var bot: Bot? { model.bots[botId] }+ private var draftKey: String { artifact.map(BotStore.artifactDraftKey) ?? botId }private var working: Bool { bot?.isWorking(in: botId) == true }private var isEmpty: Bool { draft.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty && files.isEmpty }@@ -45,6 +48,7 @@ struct Composer: View {private var placeholder: String {let name = bot?.name ?? ""+ if let artifact { return L10n.tr("Message about “{title}”").replacingOccurrences(of: "{title}", with: artifact.title) }if replyingTo != nil { return L10n.tr("Reply…") }if bot?.isGroup == true { return L10n.tr("Ask everyone · @ to ask one bot") }let key = working ? "Queue a message for {name}" : "Ask {name}"@@ -263,21 +267,22 @@ struct Composer: View {.padding(.leading, 18).padding(.trailing, 6).padding(.vertical, boxPadding)- .onChange(of: botId, initial: true) {+ .onChange(of: draftKey, initial: true) {dictation.stop()- draft = model.composerDraft(for: botId)+ draft = model.composerDraft(for: draftKey)}// Another chat in the same view never inherits the reply..onChange(of: botId) { replyingTo = nil }.onChange(of: replyingTo?.id) { if replyingTo != nil { focused = true } }.onDisappear { dictation.stop() }.onChange(of: draft) { _, value in- model.setComposerDraft(value, for: botId)+ model.setComposerDraft(value, for: draftKey)// Starting a command: list the computer's skills again.if value == "/" { Task { await model.refreshPlugins() } }}.onChange(of: model.routineDrafts[botId]) { _, value in- guard let value else { return }+ // A request for a routine belongs in the chat.+ guard let value, artifact == nil else { return }draft = draft.isEmpty ? value : draft + "\n" + valuemodel.routineDrafts.removeValue(forKey: botId)focused = true@@ -408,7 +413,8 @@ struct Composer: View {if files.isEmpty, let command = SlashCommands.builtIn(for: bot, members: members, draft: draft) { return run(command) }guard canSend else { return }withAnimation(Motion.reduced(Motion.conversation, reduceMotion)) {- guard model.sendComposerDraft(to: botId, replyTo: replyingTo, files: files) else { return }+ guard model.sendComposerDraft(to: botId, draft: draftKey, replyTo: artifact?.replyQuote ?? replyingTo?.replyQuote,+ files: files) else { return }draft = ""files = []replyingTo = nildiff --git a/apps/ios/Kit/Sources/CodyncUI/Thread/FileDownloadCard.swift b/apps/ios/Kit/Sources/CodyncUI/Thread/FileDownloadCard.swiftindex 235a6246..dbac0f2b 100644--- a/apps/ios/Kit/Sources/CodyncUI/Thread/FileDownloadCard.swift+++ b/apps/ios/Kit/Sources/CodyncUI/Thread/FileDownloadCard.swift@@ -13,7 +13,7 @@ struct FileDownloadCard: View {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)+ Text(Self.detail(state, size: file.size)).font(.caption2).foregroundStyle(Palette.secondary)}Spacer(minLength: 0)Button {@@ -36,8 +36,9 @@ struct FileDownloadCard: View {if case .downloading = state { return true }return false}- private func detail(_ state: FileDownloads.State?) -> String {- let size = ByteCountFormatter.string(fromByteCount: file.size, countStyle: .file)+ /// The size, or how the download is going.+ static func detail(_ state: FileDownloads.State?, size bytes: Int64) -> String {+ let size = ByteCountFormatter.string(fromByteCount: bytes, 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."@@ -47,6 +48,19 @@ struct FileDownloadCard: View {}}+extension View {+ /// The share sheet for a file of this chat once it's downloaded (`FileDownloads.export`). Off (`active`) while+ /// a sheet over this view presents it instead.+ func fileExportSheet(_ model: BotStore, botId: String, active: Bool = true) -> some View {+ codyncSheet(item: Binding<FileDownloads.Export?>(get: {+ guard active, let item = model.fileDownloads.export, item.botId == botId else { return nil }+ return item+ }, set: { if $0 == nil { model.fileDownloads.dismissExport() } })) { item in+ FileExportSheet(url: item.url) { model.fileDownloads.dismissExport() }+ }+ }+}+/// iOS owns save/export destinations through its native share sheet.struct FileExportSheet: UIViewControllerRepresentable {let url: URLdiff --git a/apps/ios/Kit/Sources/CodyncUI/Thread/ThreadView.swift b/apps/ios/Kit/Sources/CodyncUI/Thread/ThreadView.swiftindex c4658835..ccf5f31d 100644--- a/apps/ios/Kit/Sources/CodyncUI/Thread/ThreadView.swift+++ b/apps/ios/Kit/Sources/CodyncUI/Thread/ThreadView.swift@@ -15,6 +15,7 @@ public struct ThreadView: View {/// The message the composer's next send quotes.@State var replyingTo: Entry?@State var botChat: BotChatTarget?+ @State var openArtifact: ArtifactTarget?@State var editingGroup = false@State var details: DetailsRequest?@State var confirmNewSession = false@@ -66,18 +67,18 @@ 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 else { return nil }- return item- }, set: { if $0 == nil { model.fileDownloads.dismissExport() } })) { item in- FileExportSheet(url: item.url) { model.fileDownloads.dismissExport() }- }+ // The details sheet's Library presents its own downloads.+ .fileExportSheet(model, botId: botId, active: details == nil).codyncSheet(isPresented: $showTrace) {TraceView(botId: botId)}.codyncSheet(item: $botChat) { BotConversationView(botId: botId, peerId: $0.id) }+ .codyncSheet(item: $openArtifact) { ArtifactView(target: $0) }.codyncSheet(item: $details) { request in- BotDetailsView(botId: request.botId ?? botId, request: request)+ BotDetailsView(botId: request.botId ?? botId, request: request) { artifact in+ details = nil+ openArtifact = artifact+ }}.codyncSheet(isPresented: $editingGroup) {if let bot { GroupEditorView(group: bot) }@@ -105,7 +106,8 @@ public struct ThreadView: View {// An update card takes the composer's place, so there's nothing to reply with.reply: e.isReplyable && model.mismatch == nil ? { reply(to: e) } : nil,// In a group, the bot whose agent failed.- addFallback: { details = DetailsRequest(botId: e.data.author ?? e.botId) })+ addFallback: { details = DetailsRequest(botId: e.data.author ?? e.botId) },+ openArtifact: { openArtifact = ArtifactTarget(botId: e.botId, id: $0.id, title: $0.title) }).equatable()}}@@ -198,6 +200,11 @@ public struct ThreadView: View {items.append(MenuItem("Routines", icon: "clock.arrow.circlepath") {openRoutine(nil)})+ if model.hasLibrary {+ items.append(MenuItem("Library", icon: "books.vertical") {+ withAnimation(Motion.reduced(Motion.layout, reduceMotion)) { details = DetailsRequest(tab: .library) }+ })+ }items.append(MenuItem("New session", icon: "arrow.counterclockwise") { confirmNewSession = true })items.append(MenuItem("Delete bot", icon: "trash", destructive: true, divider: true) { confirmDelete = bot })return itemsdiff --git a/apps/ios/Kit/Tests/CodyncKitTests/ArtifactTests.swift b/apps/ios/Kit/Tests/CodyncKitTests/ArtifactTests.swiftnew file mode 100644index 00000000..297b621e--- /dev/null+++ b/apps/ios/Kit/Tests/CodyncKitTests/ArtifactTests.swift@@ -0,0 +1,92 @@+import CryptoKit+import Foundation+import Testing+@testable import CodyncKit++private func artifactJSON(_ html: Data, id: String = "p1", updatedAt: Int64 = 5, title: String = "Weekly report") -> [String: Any] {+ ["id": id, "botId": "b1", "title": title, "size": html.count, "createdAt": 1, "updatedAt": updatedAt,+ "sha256": SHA256.hash(data: html).map { String(format: "%02x", $0) }.joined(), "entryId": "e9"]+}++@Test func parsesArtifactEventsAndCards() throws {+ let event = HostClient.parseEvent(Data(#"{"type":"artifact","artifact":{"id":"p1","botId":"b1","title":"Weekly report","size":22,"sha256":"ab","createdAt":1,"updatedAt":5,"entryId":"e9"}}"#.utf8))+ guard case let .artifact(artifact) = event else { Issue.record("artifact"); return }+ #expect(artifact.title == "Weekly report" && artifact.updatedAt == 5)+ #expect(artifact.replyQuote == ReplyQuote(id: "e9", author: "b1", text: "Artifact: Weekly report", artifact: "p1"))+ // An artifact event this app can't read is skipped, not a reason to fetch everything again.+ #expect(HostClient.parseEvent(Data(#"{"type":"artifact","artifact":{"id":"p1"}}"#.utf8)) == nil)++ let card = #"{"id":"e9","botId":"b1","seq":3,"rev":7,"kind":"agent","turn":1,"data":{"text":"Artifact: Weekly report","final":true,"artifact":{"id":"p1","title":"Weekly report","updatedAt":5}},"createdAt":1,"updatedAt":1}"#+ let entry = try JSONDecoder().decode(Entry.self, from: Data(card.utf8))+ #expect(entry.data.artifact == ArtifactRef(id: "p1", title: "Weekly report", updatedAt: 5))+ #expect(entry.replyQuote.artifact == "p1", "a reply to the card is about the artifact")++ let reply = #"{"id":"u1","botId":"b1","seq":4,"rev":8,"kind":"user","turn":2,"data":{"text":"Add totals","replyTo":{"id":"e9","author":"b1","text":"Artifact: Weekly report","artifact":"p1"}},"createdAt":1,"updatedAt":1}"#+ #expect(try JSONDecoder().decode(Entry.self, from: Data(reply.utf8)).data.replyTo?.artifact == "p1")+}++@Test func readsTheLibraryAndSkipsWhatItCantRead() throws {+ let json = #"{"items":[{"kind":"artifact","at":9,"artifact":{"id":"p1","botId":"b1","title":"Weekly report","size":1,"sha256":"ab","createdAt":1,"updatedAt":9}},{"kind":"file","at":8,"entryId":"e2","file":{"id":"f1","name":"r.csv","size":3,"sha256":"cd"}},{"kind":"attachment","at":7,"entryId":"e1","file":{"id":"u1","name":"a.png","size":4}},{"kind":"video","at":6},{"kind":"artifact","at":6,"artifact":{"id":"p2"}},{"kind":"file","at":5,"entryId":"e3","file":{"id":"f2","name":"x","size":1}}]}"#+ struct Res: Decodable { var items: [ChatLibraryItem.Wire] }+ let items = try JSONDecoder().decode(Res.self, from: Data(json.utf8)).items.compactMap(\.item)+ #expect(items.map(\.id) == ["artifact/p1", "file/e2/f1", "attachment/e1/u1"])+ guard case let .file(file, entryId) = items[1].kind else { Issue.record("file"); return }+ #expect(file.sha256 == "cd" && entryId == "e2" && items[1].at == 8)+}++/// Serves an artifact's HTML in `readArtifact` chunks; `republish` swaps in another version after the first chunk.+private actor ArtifactTransport: HostTransport {+ var html: Data+ var updatedAt: Int64 = 5+ var republish: Data?+ var damaged = false+ private(set) var offsets: [Int] = []++ init(_ html: Data, republish: Data? = nil, damaged: Bool = false) {+ self.html = html+ self.republish = republish+ self.damaged = damaged+ }++ func call(_ method: String, body: Data, timeout: TimeInterval) async throws -> Data {+ #expect(method == "readArtifact")+ let request = try #require(JSONSerialization.jsonObject(with: body) as? [String: Any])+ let offset = try #require(request["offset"] as? Int)+ offsets.append(offset)+ var artifact = artifactJSON(html, updatedAt: updatedAt)+ if damaged { artifact["sha256"] = "00" }+ let chunk = html.subdata(in: offset..<min(offset + FileDownload.chunkSize, html.count))+ if let next = republish {+ html = next+ updatedAt += 1+ republish = nil+ }+ return try JSONSerialization.data(withJSONObject: ["data": chunk.base64EncodedString(), "size": artifact["size"] ?? 0, "artifact": artifact])+ }++ nonisolated func stream(_ request: HostStreamRequest) -> AsyncThrowingStream<Data, Error> { AsyncThrowingStream { $0.finish() } }+ nonisolated func states() -> AsyncStream<LinkState> { AsyncStream { $0.finish() } }+}++@Test func readsAWholeArtifactInChunks() async throws {+ let html = Data(String(repeating: "<p>row</p>", count: FileDownload.chunkSize / 5).utf8)+ let transport = ArtifactTransport(html)+ let read = try await HostClient(transport: transport).readArtifactHTML(botId: "b1", artifactId: "p1")+ #expect(read.html == html && read.artifact.updatedAt == 5)+ #expect(await transport.offsets == [0, FileDownload.chunkSize])+}++@Test func aArtifactPublishedAgainMidReadIsReadFromItsStart() async throws {+ let first = Data(String(repeating: "a", count: FileDownload.chunkSize + 10).utf8)+ let second = Data(String(repeating: "b", count: FileDownload.chunkSize + 20).utf8)+ let transport = ArtifactTransport(first, republish: second)+ let read = try await HostClient(transport: transport).readArtifactHTML(botId: "b1", artifactId: "p1")+ #expect(read.html == second && read.artifact.updatedAt == 6)+ #expect(await transport.offsets == [0, FileDownload.chunkSize, 0, FileDownload.chunkSize])+}++@Test func aDamagedArtifactIsRefused() async {+ await #expect(throws: FileDownloadError.self) {+ _ = try await HostClient(transport: ArtifactTransport(Data("<h1>Hi</h1>".utf8), damaged: true)).readArtifactHTML(botId: "b1", artifactId: "p1")+ }+}diff --git a/apps/ios/Kit/Tests/CodyncUITests/ArtifactCacheTests.swift b/apps/ios/Kit/Tests/CodyncUITests/ArtifactCacheTests.swiftnew file mode 100644index 00000000..86c4e2be--- /dev/null+++ b/apps/ios/Kit/Tests/CodyncUITests/ArtifactCacheTests.swift@@ -0,0 +1,76 @@+import Foundation+import Testing+@testable import CodyncKit+@testable import CodyncUI++private func artifact(_ id: String = "p1", title: String = "Weekly report", updatedAt: Int64, entryId: String? = "e9") -> Artifact {+ Artifact(id: id, botId: "b1", title: title, size: 1, sha256: "", createdAt: 1, updatedAt: updatedAt, entryId: entryId)+}++@Test func aArtifactIsReadAgainOnlyWhenANewerVersionIsKnown() {+ var cache = ArtifactCache()+ #expect(cache.needsRead("p1"), "nothing held yet")+ cache.reading.insert("p1")+ #expect(!cache.needsRead("p1"), "one read at a time")+ cache.reading.remove("p1")++ cache.store(artifact(updatedAt: 5), html: "<h1>v5</h1>")+ #expect(!cache.needsRead("p1"))+ // The card a newer publish posted names its version before any artifact event does.+ cache.announce(ArtifactRef(id: "p1", title: "Weekly report", updatedAt: 9))+ #expect(cache.needsRead("p1"))+ cache.store(artifact(updatedAt: 9), html: "<h1>v9</h1>")+ #expect(!cache.needsRead("p1") && cache.html["p1"]?.text == "<h1>v9</h1>")++ // A late answer about an older version changes nothing; a rename keeps the version and still lands.+ cache.upsert(artifact(title: "Old", updatedAt: 5))+ #expect(cache.details["p1"]?.title == "Weekly report")+ cache.upsert(artifact(title: "Sales", updatedAt: 9))+ #expect(cache.details["p1"]?.title == "Sales" && !cache.needsRead("p1"))+ #expect(cache.title(ArtifactRef(id: "p1", title: "Weekly report", updatedAt: 9)) == "Sales", "an older card shows the newest title")+ #expect(cache.title(ArtifactRef(id: "p1", title: "Q4", updatedAt: 12)) == "Q4", "until the details catch up with a newer card")+}++@Test func theLibraryGroupsByWhenEachThingCame() throws {+ var calendar = Calendar(identifier: .gregorian)+ calendar.timeZone = try #require(TimeZone(identifier: "UTC"))+ calendar.firstWeekday = 2+ // Thursday 2026-10-22, noon.+ let now = Date(timeIntervalSince1970: 1_792_670_400)+ let hour: Int64 = 3_600_000+ let at = Int64(now.timeIntervalSince1970 * 1000)+ let photo = ChatLibraryItem(.attachment(Attachment(id: "photo", name: "a.png", size: 1), entryId: "e1"), at: at - 24 * hour)+ let items = [ChatLibraryItem(artifact("old", updatedAt: at - 30 * 24 * hour)), ChatLibraryItem(artifact("today", updatedAt: at - hour)),+ ChatLibraryItem(artifact("monday", updatedAt: at - 3 * 24 * hour)), photo, ChatLibraryItem(artifact("noon", updatedAt: at))]+ let sections = ChatLibraryItem.sections(items, now: now, calendar: calendar)+ #expect(sections.map(\.period) == [.today, .yesterday, .thisWeek, .earlier])+ #expect(sections.map { $0.items.map(\.id) } == [["artifact/noon", "artifact/today"], ["attachment/e1/photo"], ["artifact/monday"], ["artifact/old"]])+}++@MainActor @Test func aMessageAboutAArtifactRepliesToItsCardFromItsOwnDraft() async throws {+ let suite = "ArtifactCacheTests.\(UUID().uuidString)"+ let storage = SharedStore.Context(accountID: UUID().uuidString, suite: suite)+ defer { UserDefaults(suiteName: suite)?.removePersistentDomain(forName: suite) }+ let fake = FakeRemote(.ready(.direct))+ let store = BotStore(computer: Computer(id: "artifacts", name: "Mac", signKey: ""), storage: storage) { _ in fake }+ defer { store.retire() }+ store.setActive(true)+ #expect(await until { await fake.subscribed })+ await fake.emit(#"{"type":"bot","bot":{"id":"b1","name":"Bot","rev":1,"lastAt":1}}"#)+ await fake.emit(#"{"type":"artifact","artifact":{"id":"p1","botId":"b1","title":"Weekly report","size":1,"sha256":"","createdAt":1,"updatedAt":5,"entryId":"e9"}}"#)+ #expect(await until { store.artifacts.details["p1"] != nil })+ let report = try #require(store.artifacts.details["p1"])++ store.setComposerDraft("Half-written", for: "b1")+ let key = BotStore.artifactDraftKey(report)+ store.setComposerDraft("Add totals", for: key)+ #expect(store.sendComposerDraft(to: "b1", draft: key, replyTo: report.replyQuote))+ #expect(store.chat("b1").last?.data.replyTo?.artifact == "p1")+ #expect(store.composerDraft(for: key).isEmpty)+ #expect(store.composerDraft(for: "b1") == "Half-written", "the chat's own draft stays")+ #expect(await until { await fake.replyTos == ["e9"] })++ store.setComposerDraft("Later", for: key)+ store.removeComposerDrafts(for: "b1")+ #expect(store.composerDraft(for: key).isEmpty, "a deleted bot's artifact drafts go with it")+}diff --git a/apps/ios/Kit/Tests/CodyncUITests/ReplyTests.swift b/apps/ios/Kit/Tests/CodyncUITests/ReplyTests.swiftindex 3d8d84ae..6b7aa3a5 100644--- a/apps/ios/Kit/Tests/CodyncUITests/ReplyTests.swift+++ b/apps/ios/Kit/Tests/CodyncUITests/ReplyTests.swift@@ -40,7 +40,7 @@ private func message(_ id: String, kind: String, final: Bool? = nil, text: Strin#expect(await until { store.connection == .online })store.setComposerDraft("Why?", for: "b1")- #expect(store.sendComposerDraft(to: "b1", replyTo: message("a", kind: "agent", final: true)))+ #expect(store.sendComposerDraft(to: "b1", replyTo: message("a", kind: "agent", final: true).replyQuote))#expect(store.chat("b1").last?.data.replyTo?.id == "a")#expect(store.composerDraft(for: "b1").isEmpty)#expect(await until { await fake.replyTos == ["a"] })diff --git a/apps/ios/WhatsNew.md b/apps/ios/WhatsNew.mdindex d4fb3e8e..3ebb9dec 100644--- a/apps/ios/WhatsNew.md+++ b/apps/ios/WhatsNew.md@@ -9,6 +9,8 @@ a version without one gets a generic "Bug fixes and improvements" line. Delete o## 2.25.0### zh-Hant+- Bot 可以做 Artifact:報告、追蹤表、儀表板這類要回來看的內容會以卡片出現在聊天裡,點開看完整內容,直接在下方留言請它改,改好就自動更新。+- 每個 Bot 的「資料庫」收齊它做的 Artifact,以及聊天裡分享過的檔案和圖片。- 可以建立使用 Hermes Agent 的 Bot。- Bot 之間交辦工作不必等待,對方的回覆會回到發問的 Bot,再由它回覆你。- 鎖定畫面的即時動態加上進度條,四格依任務進度填滿,顏色跟著狀態走。@@ -17,6 +19,8 @@ a version without one gets a generic "Bug fixes and improvements" line. Delete o- 使用 Hermes Agent 或 Gemini CLI 的 Bot,記憶頁會說明它們自己的記憶由所有用同一個 agent 的 Bot 共用,Codync 沒辦法關掉。### en-US+- Bots can make artifacts: reports, trackers and dashboards you come back to show as a card in the chat. Open one full screen and message the bot below it to change it; it updates in place.+- Each bot's Library collects its artifacts and the files and images shared in the chat.- Create bots that run Hermes Agent.- Bots hand work to each other without waiting; the answer comes back to the bot that asked, which then replies to you.- Live Activities on the Lock Screen show a progress line that fills as the task moves, in the state's color.diff --git a/docs/README.md b/docs/README.mdindex 9b5d8e46..ca680cf4 100644--- a/docs/README.md+++ b/docs/README.md@@ -39,6 +39,7 @@ Source review, a passing build, local integration tests and production acceptanc- [Routines](features/routines.md)- [Voice calls](features/voice-call.md)- [File attachments](features/file-attachments.md)+- [Artifacts and the Library](features/artifacts.md)- [Remote screen](features/remote-screen.md) and [computer use](features/computer-use.md)- [Computer identity and list ordering](features/computer-order.md)- [Notch island (desktop)](features/notch-island.md)diff --git a/docs/architecture/file-structure.md b/docs/architecture/file-structure.mdindex b0ed0821..64133f07 100644--- a/docs/architecture/file-structure.md+++ b/docs/architecture/file-structure.md@@ -99,6 +99,7 @@ Codync/| Fast mode (session config option) | `host/src/agent/config.rs`, `agent/bot/fast_mode.rs` || Marketplace, Composio, connector OAuth | `host/src/market/` || Skills a bot writes (`save_skill`) | `host/src/chat/skills.rs`, stored by `host/src/market/skills.rs` |+| Artifacts (`publish_artifact`) and a chat's Library | `host/src/chat/artifacts.rs`, `library.rs`; desktop `apps/desktop/src/renderer/views/library/` (+ `src/main/artifacts.ts`); iPhone `apps/ios/Kit/Sources/CodyncUI/Artifacts/` (+ `Store/ArtifactCache.swift`, `BotStore+Artifacts.swift`); Android `ArtifactCardView.kt`, `ArtifactViewer.kt`, `ArtifactWebView.kt`, `LibrarySheet.kt`, `AppStoreArtifacts.kt` (+ `core/Artifact.kt`, `core/Library.kt`); terminal `host/src/tui/net/artifacts.rs`, `manage/library.rs` || Screen bridge and built-in MCP tools | `host/src/screen/`, `mcp.rs` || Swift transport and cloud API | `apps/ios/Kit/Sources/CodyncKit/Client/` || Account aggregation / one host mirror | `apps/ios/Kit/Sources/CodyncUI/Store/AccountStore.swift` / `BotStore.swift` (+ `BotStore+Connection`, `+Sync`, `+Sending`, `+Actions`, `+Plugins`, `+Cache`) |diff --git a/docs/design/ui-conventions.md b/docs/design/ui-conventions.mdindex 952edf57..81831e62 100644--- a/docs/design/ui-conventions.md+++ b/docs/design/ui-conventions.md@@ -95,7 +95,7 @@ Desktop conversations start with the details inspector closed; the title menu opPreserve the original character avatar design: dotted shading, highlight-only color, silhouettes and animation. Desktop roster avatars remain 30 points and iPhone roster avatars remain 46 points. iPhone shares readable secondary text and message previews; its native navigation remains platform-specific. Terminal avatars already use solid color and the terminal has no persistent details inspector; its secondary text uses the same readable palette.-The details inspector (`apps/desktop/src/renderer/views/thread/DetailsPanel.tsx`) copies Grok Bot's: share (Create template) and close (X) as round buttons in the corner, in the page color with a soft ring, over a 54-point band that drags the window; the bot's 60-point avatar, name and runtime centered on top; then page tabs (`TabChoice`: plain labels, the chosen one on a light capsule) for **Details**, **Memory** and **Settings**, all in one scroll. The chat's `<<` button (in the same ringed style) and the title pill open it; hovering the pill shows a `>` after the name. Details holds what changes often: Instructions, Agent (the agent with its logo, its model, fast mode and its [fallbacks](../features/agent-fallback.md#apps)), the Use the computer switch and Routines (one card per routine); Settings holds the rest: Profile (avatar row, name, and "Created by" for a bot another bot created), Workspace (computer, workspace, permissions), Activity, Connectors and Skills. Both are parts of `BotSettingsForm` (`part`), saved as you edit; the editor sheet shows all of it. Every bot settings form (these, the editor sheets, the terminal's form) keeps a change made elsewhere while it is open (a bot that manages the team, another device): it takes the new value in each field not edited there, or the terminal sends only what it changed. Memory is the read-only memory card, its sections in the same tabs; each layer's note ends with "To change it, tell the bot." and the Dreams tab has an info button. Every group in the panel is Grok Bot's outlined card (an outline on the page, no fill, inputs filled instead), a row with a note puts its control under the note, and long notes (skill descriptions, explanations, a note's description) stop at two lines with an ellipsis. A group shows its avatar, name, bot count and members instead of tabs. Use 16-point horizontal insets and 28-point section gaps; sections use the `CardSection` look: filled 16-point groups without borders, hairline-split rows, a note under each option. The iPhone's Details sheet (`BotDetailsView`, from the title menu's Details, Settings and Routines) has the same corner buttons, header, tabs, pages, outlined cards (`cardStyle`) and two-line notes (`noteLines`), and saves as you edit too.+The details inspector (`apps/desktop/src/renderer/views/thread/DetailsPanel.tsx`) copies Grok Bot's: share (Create template) and close (X) as round buttons in the corner, in the page color with a soft ring, over a 54-point band that drags the window; the bot's 60-point avatar, name and runtime centered on top; then page tabs (`TabChoice`: plain labels, the chosen one on a light capsule) for **Details**, **Library** (the chat's [artifacts and files](../features/artifacts.md)), **Memory** and **Settings**, all in one scroll. The chat's `<<` button (in the same ringed style) and the title pill open it; hovering the pill shows a `>` after the name. Details holds what changes often: Instructions, Agent (the agent with its logo, its model, fast mode and its [fallbacks](../features/agent-fallback.md#apps)), the Use the computer switch and Routines (one card per routine); Settings holds the rest: Profile (avatar row, name, and "Created by" for a bot another bot created), Workspace (computer, workspace, permissions), Activity, Connectors and Skills. Both are parts of `BotSettingsForm` (`part`), saved as you edit; the editor sheet shows all of it. Every bot settings form (these, the editor sheets, the terminal's form) keeps a change made elsewhere while it is open (a bot that manages the team, another device): it takes the new value in each field not edited there, or the terminal sends only what it changed. Memory is the read-only memory card, its sections in the same tabs; each layer's note ends with "To change it, tell the bot." and the Dreams tab has an info button. Every group in the panel is Grok Bot's outlined card (an outline on the page, no fill, inputs filled instead), a row with a note puts its control under the note, and long notes (skill descriptions, explanations, a note's description) stop at two lines with an ellipsis. A group shows its avatar, name, bot count and members instead of tabs. Use 16-point horizontal insets and 28-point section gaps; sections use the `CardSection` look: filled 16-point groups without borders, hairline-split rows, a note under each option. The iPhone's Details sheet (`BotDetailsView`, from the title menu's Details, Settings and Routines) has the same corner buttons, header, tabs, pages, outlined cards (`cardStyle`) and two-line notes (`noteLines`), and saves as you edit too.Routines are a compact grouped list: name, a one-line schedule (or the live run state), and an on/off switch per row; tapping a row opens the same form as +, filled in, with delete and test run beside Save. On the desktop the form card fits its content. The header's chat button asks the bot (puts "I want a routine that " in the composer); + opens the form, where When to run is a type choice (a segmented control on the desktop, the system menu on iPhone) and a schedule is a Repeat choice (Hourly, Daily, Weekdays, Weekly, Custom) with only the fields that choice needs (minute, time, weekday, or a typed cron for Custom) and a time zone picked from a searchable list. On the desktop these sit in one `CardSection` of labeled rows, Repeat and the weekday as `ChipChoice` chips with the chosen one on a light capsule. The empty state is one line of text. A saved webhook routine's form shows the public URL and key as monospaced rows (in the same group on the desktop) with copy, show/hide and replace-key (confirmed) icon buttons, and one caption on how to send and that deliveries pass through the Codync cloud. Agent metadata uses Runtime and Workspace labels for personal bots, or Project folder for explicitly configured projects; project paths remain selectable and wrap. Personal workspace paths stay out of the default details UI. Keep status and section headings readable in both appearances through `Palette`.@@ -153,8 +153,8 @@ and states.- TUI bot settings include **Use computer** and **Manage team**, matching the iPhone and desktop apps. Theremote-screen viewer and voice-call UI are not in the TUI.- A bot's pages in the TUI match the inspector's tabs: `R` opens Details (the agent, model and first line of the instructions, which `i` edits in- Settings; Use the computer, which `u` switches; then Routines), `M` Memory and `e` Settings, each with the Details / Memory / Settings- line on top; ⇧← ⇧→ moves between them. Settings with unsaved edits asks for ^S (or Esc) first.+ Settings; Use the computer, which `u` switches; then Routines), `L` Library, `M` Memory and `e` Settings, each with the+ Details / Library / Memory / Settings line on top; ⇧← ⇧→ moves between them. Settings with unsaved edits asks for ^S (or Esc) first.### Verificationdiff --git a/docs/features/artifacts.md b/docs/features/artifacts.mdnew file mode 100644index 00000000..224ac1ab--- /dev/null+++ b/docs/features/artifacts.md@@ -0,0 +1,91 @@+# Artifacts and the Library++An artifact is a self-contained HTML document a bot makes for the user to read as a whole or come back to: a report,+a plan, a comparison, a tracker, a dashboard (Grok Bot's Pages, on the user's own computer). The bot writes the HTML;+the host keeps it; every app shows it as a card in the chat and opens it full size. A chat's **Library** (Grok Bot's)+holds everything made or shared there: its artifacts, the files and images the bot shared, and the ones the user sent.+Asked to change an artifact, the bot publishes it again under the same id, and every open copy shows the new one.++## Bots++The built-in `chat` MCP server has two tools (`host/src/chat/artifacts.rs`):++- `publish_artifact {path, title?, artifact?}`: the HTML file (absolute or relative to the bot's working directory,+ up to 5 MiB, inline CSS and JS, libraries from a CDN allowed). Without `artifact` it makes a new artifact and needs+ a title; with `artifact` (an id) it replaces that artifact's HTML, and its title when given. The answer names the+ artifact's id.+- `list_artifacts {}`: the bot's artifacts, newest first, with each one's id, title, last publish time and the path of+ its current HTML. To make changes the bot edits a copy and publishes that: the stored file is the live one, checked+ against its size and SHA-256 on every read.++When to make one is part of every bot's instructions (`chat::outbox::INSTRUCTIONS`): an artifact instead of a long+message, one artifact per subject, updated rather than made again. A session whose frozen instructions predate+artifacts gets a one-line reminder of this with each message in the bot's own chat (`turn.rs`, like `send_file`'s).++A publish in the bot's own chat also posts an artifact card there: a final `agent` entry with+`{text: "Artifact: <title>", final: true, artifact: {id, title, updatedAt}}`. Older apps show the text. In a routine+run, a group chat or a request from another bot the artifact is saved and in the chat's Library, but no card is+posted (`card` in the answer says so), and the bot mentions it in its reply.++A message about an artifact is a reply to its card: `replyTo` carries the artifact id and quotes it under its current+title (`replies::quote`), and the bot reads `[Codync: this is about your artifact "<title>" (id …). Its current HTML is+<path>; …]` instead of the quoted text (`artifacts::note`).++## Host++- Storage: `~/.codync/bots/<bot>/artifacts/<id>.html` holds the newest HTML (replaced whole: written to `.partial`,+ then renamed). The details live in kv as `artifact.<bot>.<id>`:+ `{id, botId, title, size, sha256, createdAt, updatedAt, entryId?}`, where `entryId` is the newest card. Deleting the+ bot deletes both.+- API (Control access, like the chat):+ - `library {botId}` → `{items}`, newest first (`host/src/chat/library.rs`): the chat's artifacts+ `{kind: "artifact", at: updatedAt, artifact: Artifact}`, files its bot shared+ `{kind: "file", at, entryId, file: {id, name, size, sha256}}` (read with `readFile`) and files the user attached+ `{kind: "attachment", at, entryId, file: {id, name, size}}` (read with `readUpload`), from its newest 500 messages+ with files.+ - `readArtifact {botId, artifactId, offset}` → `{data: <base64>, size, artifact: Artifact}`, chunks of at most+ 384 KiB like `readFile`.+ - `renameArtifact {botId, artifactId, title}` → `{artifact}`. Titles are trimmed, 1–200 bytes, no control+ characters.+- Event: `{"type": "artifact", "artifact": Artifact}` on every publish and rename. It is live only (not in the+ catch-up): apps fetch the `library` when they show it and upsert what the events bring. Older apps ignore it.+- Additive: no `minApp` change. The apps show the Library only when the host's `hello` version is 2.25.0 or later+ (an older host has no `library`); cards need no check, since only those hosts post them.+- Analytics: `artifact_published {change, card}` and the `library` and `artifact` screens+ ([analytics events](../reference/analytics-events.md)).++## Apps++All four clients show the same things; layout follows each platform.++- **Card** (in the chat, for an `agent` entry with `artifact`): the top of the artifact itself, scaled down and not+ interactive, clipped to the card's corners, over a footer row with the artifact symbol (`chart.bar.doc.horizontal`),+ the title and "Artifact". It shows the newest version of that artifact (from `readArtifact`), whichever card it is.+ Tapping or clicking opens the viewer; the message menu still has Copy, Reply and reactions.+- **Viewer**: the artifact full size in a web view of its own (scripts on, no access to the app, storage of its own; a+ tapped web or mail link opens in the system browser, and other schemes go nowhere).+ - Header: close (`xmark`, "Close artifact"), the title in the middle (tapping it renames the artifact: "Rename+ artifact", "Artifact title"), and a share action: desktop "Save as HTML" and "Open in browser"; iPhone and Android+ the system share sheet with `<title>.html`.+ - Bottom: a message box, "Message about “<title>”", that sends a reply to the artifact's card (`entryId`) to its+ bot. It keeps a draft of its own (`<bot>/artifact/<id>`), apart from the chat's. The viewer stays open; when the bot publishes the artifact again, it reloads. An artifact without a card+ (published in a routine run) has no message box: there is nothing to reply to.+ - Loading shows the shared spinner; a failure shows "Couldn't open the artifact" with the error.+- **Library**: the chat's artifacts and the files shared in it, grouped Today / Yesterday / This week (the last+ seven days) / Earlier. An artifact row is the artifact symbol and its title, opens the viewer, and its menu has+ Open, Rename artifact and the share action. A file the bot shared is its file symbol, name and size, and saves like+ its card in the chat. An image the user sent shows a thumbnail and opens full size; other files they sent show their+ name and size. Empty: "Library is empty" / "Artifacts {name} makes and files shared in this chat show here."+ - Desktop: a Library tab in the conversation details panel (Details · Library · Memory · Settings).+ - iPhone: the same tab in the bot's details sheet; Library in the chat's menu opens it there.+ - Android: Library in the chat's menu (beside Routines), a sheet with the list.+- **Terminal UI**: a card is a `▤ Artifact: <title>` line. On the selected message, `o` opens the artifact in the+ computer's browser (its HTML written to a temporary file) and `f` saves `<title>.html` to Downloads, like files.+ The Library is a tab of the bot's pages (`L`, ⇧← ⇧→): `↵`/`o` opens an artifact in the browser, `f` saves any row to+ Downloads, `r` renames an artifact.++Desktop: an artifact loads from `codync-artifact://<id>` (`apps/desktop/src/main/artifacts.ts`), its own origin, into+a sandboxed frame: the chat window's content security policy would block an artifact's scripts in a `srcdoc` frame.+Links an artifact follows or opens in a new window go to the browser (`https`, `http` and `mailto` only).++Not yet: public links (Grok Bot's "Anyone with the link"), deleting or pinning an artifact, artifacts in group chats.diff --git a/docs/features/chat-messages.md b/docs/features/chat-messages.mdindex f3a1928b..9a76d0e5 100644--- a/docs/features/chat-messages.md+++ b/docs/features/chat-messages.md@@ -21,7 +21,8 @@ it has no pointer tooltip or link-opening action.needs neither words nor a reaction gets nothing, as in a group.- File cards are separate final entries. Sharing a file preserves an intended final textreply; a files-only turn uses its filename for the completion summary. See- [file attachments](file-attachments.md#files-from-a-bot).+ [file attachments](file-attachments.md#files-from-a-bot). Artifact cards (`publish_artifact`) are final entries the+ same way; see [artifacts](artifacts.md).- Group room turns, bot requests (`message_bot`) and routines reject `send_message` and `send_file`: their replyis the turn's last text, as before (`chat/group.rs`, `chat/team.rs`, `routines`).- A bot request's reply stays in the recipient's trace and the request notice; it doesdiff --git a/docs/reference/analytics-events.md b/docs/reference/analytics-events.mdindex b4db76ca..d60e3d12 100644--- a/docs/reference/analytics-events.md+++ b/docs/reference/analytics-events.md@@ -91,6 +91,7 @@ host answers and sends it once the host is up.| `skill_installed` | host | `installSkill` | `custom` || `skill_removed` | host | `removeSkill` | — || `skill_written` | host | A bot's `save_skill` (`chatCall`) | `change` (`new`/`update`) |+| `artifact_published` | host | A bot's `publish_artifact` (`chatCall`) | `change` (`new`/`update`), `card` (whether its card went into the bot's chat), never its title || `credential_saved` | host | A key, login or vault is saved (clearing one isn't) | `kind` (`login`/`onepassword`/`connector`/`composio`/`voice`/`agent_env`) || `agent_setup_started` | host | `agentSetup` (an agent's install or sign-in terminal) | `agent` || `agent_signed_in` | host | `agentAuthenticate` | `agent` |@@ -120,6 +121,8 @@ host answers and sends it once the host is up.| `remote_screen` | remote screen | — | — || `computer_access` | — | computer access | — || `help` | — | — | keys overlay |+| `library` | a chat's Library (iPhone: the details tab; Android: its sheet) | library tab | library overlay |+| `artifact` | an artifact's viewer | an artifact's viewer | — (opens in the browser) |## Funnelsdiff --git a/host/src/agent/bot/files.rs b/host/src/agent/bot/files.rsindex 25247e85..4a510f2b 100644--- a/host/src/agent/bot/files.rs+++ b/host/src/agent/bot/files.rs@@ -1,9 +1,9 @@-//! File copies run outside the actor; publication still belongs to its original turn.+//! File copies run outside the actor; publication still belongs to its original turn. Artifact cards post the same way.use super::Actor;use crate::chat::files::{self, Snapshot};use crate::store::EntryKind;use anyhow::{Result, anyhow, ensure};-use serde_json::json;+use serde_json::{Value, json};use std::path::PathBuf;use std::sync::{Arc,@@ -82,11 +82,22 @@ impl Actor {ensure!(!self.stop_requested, "turn is stopping");ensure!(self.active_group.is_none() && self.active_request.is_none() && self.active_routine.is_none(),- "send_file is only available in the bot's own chat"+ "send_file and artifact cards are only available in the bot's own chat");self.turn.ok_or_else(|| anyhow!("no turn is running"))}+ /// A published artifact's card (`chat::artifacts`, its entry's `data`): a message of the turn, like a shared file.+ pub(super) fn post_artifact(&mut self, data: Value) -> Result<String> {+ let turn = self.can_send_file()?;+ let text = data["text"].as_str().unwrap_or_default().to_owned();+ self.close_seg();+ let entry = self.add(EntryKind::Agent, turn, data).ok_or_else(|| anyhow!("couldn't save the artifact card"))?;+ self.files.summary = Some(text);+ self.set_activity("Working…");+ Ok(entry.id)+ }+pub(super) fn finish_file(&mut self, completed: Completed) {self.files.pending.retain(|flag| !Arc::ptr_eq(flag, &completed.cancelled));let result = (|| {diff --git a/host/src/agent/bot/mod.rs b/host/src/agent/bot/mod.rsindex 2f58a5a2..6a186ed4 100644--- a/host/src/agent/bot/mod.rs+++ b/host/src/agent/bot/mod.rs@@ -81,6 +81,12 @@ pub enum Cmd {cancelled: Arc<std::sync::atomic::AtomicBool>,reply: tokio::sync::oneshot::Sender<Result<()>>,},+ /// An artifact the bot just published (`chat::artifacts`): its card (the entry's `data`) in the turn's chat. Answers+ /// the card's entry id.+ PostArtifact {+ data: Value,+ reply: tokio::sync::oneshot::Sender<Result<String>>,+ },/// Its turn in a group's room turn.Group(GroupTurn),/// The group's room turns stopped: drop its queued turns, stop a running one.diff --git a/host/src/agent/bot/queue.rs b/host/src/agent/bot/queue.rsindex ae23af6c..a329924f 100644--- a/host/src/agent/bot/queue.rs+++ b/host/src/agent/bot/queue.rs@@ -40,6 +40,9 @@ impl Actor {let _ = reply.send(self.react(&emoji, to.as_deref()));}Cmd::SendFile { path, name, cancelled, reply } => self.begin_file(path, name, cancelled, reply),+ Cmd::PostArtifact { data, reply } => {+ let _ = reply.send(self.post_artifact(data));+ }Cmd::Stop => self.stop().await,Cmd::Permission { entry_id, option_id } => self.answer_permission(&entry_id, option_id).await,Cmd::Approve { title, detail, reply } => self.ask_approval(&title, &detail, reply),diff --git a/host/src/agent/bot/turn.rs b/host/src/agent/bot/turn.rsindex f18dcabe..cc5a97c3 100644--- a/host/src/agent/bot/turn.rs+++ b/host/src/agent/bot/turn.rs@@ -28,7 +28,9 @@ impl Actor {async fn compose(&mut self, sid: &str, text: &str) -> Result<String> {let instructions = self.conn.as_ref().map_or(Instructions::FirstMessage, Conn::instructions);let mut snapshot = self.snapshot(sid).await?;+ // Sessions whose frozen instructions predate send_file or artifacts hear about them each turn.let remind_files = !snapshot.system.contains("send_file");+ let remind_artifacts = !snapshot.system.contains("publish_artifact");let mut prompt = text.to_owned();// The user's handoff first, then what the fallback chain carries in.for first in [self.relay.carried.take(), self.handoff.take()].into_iter().flatten() {@@ -55,10 +57,13 @@ impl Actor {prompt = format!("{prompt}\n\n{update}");self.announce = Some((snapshot, identity));}- if remind_files && self.active_group.is_none() && self.active_request.is_none() && self.active_routine.is_none()- {+ let own_chat = self.active_group.is_none() && self.active_request.is_none() && self.active_routine.is_none();+ if remind_files && own_chat {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.]");}+ if remind_artifacts && own_chat {+ prompt.push_str("\n\n[Codync: for a report, plan, tracker or dashboard the user will come back to, write one self-contained HTML file and publish_artifact(path, title) instead of a long message. To change it, edit a copy of its HTML (list_artifacts) and publish_artifact(path, artifact: its id).]");+ }Ok(prompt)}diff --git a/host/src/analytics.rs b/host/src/analytics.rsindex 289ce620..8e1d6fc4 100644--- a/host/src/analytics.rs+++ b/host/src/analytics.rs@@ -87,6 +87,8 @@ pub enum Event {SkillInstalled,SkillRemoved,SkillWritten,+ /// A bot's `publish_artifact`.+ ArtifactPublished,CredentialSaved,AgentSetupStarted,AgentSignedIn,@@ -144,6 +146,7 @@ impl Event {Self::SkillInstalled => "skill_installed",Self::SkillRemoved => "skill_removed",Self::SkillWritten => "skill_written",+ Self::ArtifactPublished => "artifact_published",Self::CredentialSaved => "credential_saved",Self::AgentSetupStarted => "agent_setup_started",Self::AgentSignedIn => "agent_signed_in",diff --git a/host/src/analytics/observe.rs b/host/src/analytics/observe.rsindex 770e8ef3..0f23777d 100644--- a/host/src/analytics/observe.rs+++ b/host/src/analytics/observe.rs@@ -119,6 +119,12 @@ fn call_event(method: &str, b: &Value, p: &mut Map<String, Value>) -> Option<Evep.insert("change".into(), (if rewrite { "update" } else { "new" }).into());Event::SkillWritten}+ // A bot's `publish_artifact`: a new artifact, or a new version of one (`artifact`); never its title.+ "chatCall" if b["name"] == "publish_artifact" => {+ let update = b["arguments"]["artifact"].as_str().is_some_and(|id| !id.is_empty());+ p.insert("change".into(), (if update { "update" } else { "new" }).into());+ Event::ArtifactPublished+ }"agentSetup" | "agentAuthenticate" => {// An agent's catalog id; Node.js setup names none.if let Some(agent) = b["backend"].as_str().filter(|a| !a.is_empty()) {@@ -171,13 +177,18 @@ pub fn observe_call(hub: &Hub, caller: &Caller, method: &str, b: &Value) -> OptiSome((event, p))}-/// What only the answer tells: how many connectors an import added, and whether a Composio-/// app is connected yet (its sign-in is polled until the connection is active). `None`: not an event.+/// What only the answer tells: how many connectors an import added, whether a Composio app is+/// connected yet (its sign-in is polled until the connection is active), and whether a published+/// artifact's card went into its bot's chat. `None`: not an event.pub fn answered(event: Event, mut p: Map<String, Value>, answer: &Value) -> Option<Map<String, Value>> {match event {Event::ConnectorsImported => {p.insert("count".into(), answer["items"].as_array().map_or(0, Vec::len).into());}+ // A routine run, a room or a bot request gets no card (`card` says why).+ Event::ArtifactPublished => {+ p.insert("card".into(), answer["card"].is_null().into());+ }Event::ConnectorInstalledif p.get("connector").and_then(Value::as_str) == Some("composio") && answer["status"] != "active" =>{@@ -343,6 +354,27 @@ mod tests {);assert_eq!(written(json!({"id": "deploy"})).map(|(_, p)| p["change"].clone()), Some(json!("update")));assert_eq!(props("chatCall", &json!({"name": "send_message"})), None, "other chat tools aren't events");+ let published = |arguments: Value| {+ observe(+ &Caller::Local,+ "chatCall",+ &json!({"botId": "b", "name": "publish_artifact", "arguments": arguments}),+ )+ .expect("a publish is tracked")+ };+ let (event, p) = published(json!({"path": "/secret/report.html", "title": "Salaries"}));+ let p = answered(event, p, &json!({"published": true})).expect("published");+ assert_eq!(+ (event, Value::Object(p)),+ (Event::ArtifactPublished, json!({"change": "new", "card": true, "client": "local"}))+ );+ let (event, p) = published(json!({"path": "r.html", "artifact": "a1"}));+ let p = answered(event, p, &json!({"published": true, "card": "not posted"})).expect("published");+ assert_eq!(+ (p["change"].clone(), p["card"].clone()),+ (json!("update"), json!(false)),+ "a routine's has no card"+ );assert_eq!(props("connectorSignIn", &json!({"id": "c"})).map(|(e, _)| e), Some(Event::ConnectorSigninStarted));let setup = props("agentSetup", &json!({"backend": "claude-acp", "step": "install"}));assert_eq!(setup, Some((Event::AgentSetupStarted, json!({"agent": "claude-acp", "client": "local"}))));diff --git a/host/src/analytics/reported.rs b/host/src/analytics/reported.rsindex b191e3d8..dfd3a6cb 100644--- a/host/src/analytics/reported.rs+++ b/host/src/analytics/reported.rs@@ -147,6 +147,8 @@ pub enum Screen {RemoteScreen,ComputerAccess,Help,+ Library,+ Artifact,#[serde(other)]Other,}diff --git a/host/src/api/bots.rs b/host/src/api/bots.rsindex 0bcae38f..49069d2d 100644--- a/host/src/api/bots.rs+++ b/host/src/api/bots.rs@@ -1,4 +1,4 @@-//! Bot and chat methods: roster, messages, uploads, memory, routines and the bots' own MCP calls.+//! Bot and chat methods: roster, messages, uploads, memory, artifacts, routines and the bots' own MCP calls.use super::str_arg;use crate::agent::bot::Cmd;@@ -48,6 +48,8 @@ pub(super) async fn call(hub: &Arc<Hub>, method: &str, b: Value) -> Result<Contrcrate::chat::skills::call(hub, bot, &b["arguments"]).await?} else if crate::chat::fallbacks::TOOLS.contains(&name) {crate::chat::fallbacks::call(hub, bot, name, &b["arguments"]).await?+ } else if crate::chat::artifacts::TOOLS.contains(&name) {+ crate::chat::artifacts::call(hub, bot, name, &b["arguments"]).await?} else {crate::chat::outbox::call(hub, bot, name, &b["arguments"]).await?}@@ -210,6 +212,8 @@ pub(super) async fn call(hub: &Arc<Hub>, method: &str, b: Value) -> Result<Contrjson!({})}"memory" | "memoryFile" => crate::chat::memory::call(hub, method, &b).await?,+ "library" => crate::chat::library::list(hub, str_arg(&b, "botId")?)?,+ "readArtifact" | "renameArtifact" => crate::chat::artifacts::api(hub, method, &b).await?,"editHandoff" | "keepConversation" => crate::chat::handoff::call(hub, method, &b)?,"react" => {let e = hub.react(str_arg(&b, "entryId")?, str_arg(&b, "emoji")?)?;diff --git a/host/src/chat/artifacts.rs b/host/src/chat/artifacts.rsnew file mode 100644index 00000000..cedbd624--- /dev/null+++ b/host/src/chat/artifacts.rs@@ -0,0 +1,284 @@+//! Artifacts, Grok Bot's way: a self-contained HTML document a bot publishes for the user to come back to (a report,+//! a tracker, a dashboard). The host keeps each artifact's latest HTML and title; publishing again with its id replaces+//! it, and the apps show the newest. A publish in the bot's own chat also posts an artifact card there, and the user's+//! replies to that card reach the bot as messages about the artifact (`chat::replies`).++use crate::agent::bot::Cmd;+use crate::chat::files;+use crate::hub::Hub;+use crate::store::{Store, now_ms};+use anyhow::{Context as _, Result, anyhow, bail, ensure};+use base64::Engine as _;+use serde::{Deserialize, Serialize};+use serde_json::{Value, json};+use sha2::{Digest as _, Sha256};+use std::io::Read as _;+use std::path::{Path, PathBuf};+use std::sync::Arc;+use std::time::Duration;+use tokio::sync::oneshot;++/// Largest artifact, in bytes (images ride along as data URLs).+pub const MAX_ARTIFACT: u64 = 5 * 1024 * 1024;+const MAX_TITLE: usize = 200;++/// The `chat` server's artifact tools (when to use them: `outbox::INSTRUCTIONS`).+pub const TOOLS: [&str; 2] = ["publish_artifact", "list_artifacts"];++#[derive(Clone, Debug, Deserialize, Serialize, PartialEq, Eq)]+#[serde(rename_all = "camelCase")]+pub struct Artifact {+ pub id: String,+ pub bot_id: String,+ pub title: String,+ pub size: u64,+ pub sha256: String,+ pub created_at: i64,+ pub updated_at: i64,+ /// Its newest card in the bot's chat: what a message about the artifact replies to.+ #[serde(default, skip_serializing_if = "Option::is_none")]+ pub entry_id: Option<String>,+}++impl Artifact {+ /// An artifact card entry's data: its text, and the artifact as published (`data.artifact`; the apps read the rest+ /// with `readArtifact`).+ fn card_entry(&self) -> Value {+ json!({+ "text": card_text(&self.title),+ "final": true,+ "artifact": {"id": self.id, "title": self.title, "updatedAt": self.updated_at},+ })+ }+}++/// An artifact card's text: what older apps show, and what a reply to the card quotes.+pub fn card_text(title: &str) -> String {+ format!("Artifact: {title}")+}++pub fn tools() -> [Value; 2] {+ [+ json!({+ "name": "publish_artifact",+ "description": "Publish an Artifact: one self-contained HTML file (up to 5 MiB) the user opens from a card in your chat and from its Library. Without artifact, it creates a new artifact (title required). With artifact (an id from an earlier publish or list_artifacts), it replaces that artifact's HTML, and its title when given. Paths are absolute or relative to your working directory.",+ "inputSchema": {+ "type": "object",+ "properties": {+ "path": {"type": "string", "description": "The HTML file."},+ "title": {"type": "string", "description": "The artifact's title, as the user should see it."},+ "artifact": {"type": "string", "description": "The id of the artifact to update."},+ },+ "required": ["path"],+ },+ "annotations": {"readOnlyHint": false, "idempotentHint": false},+ }),+ json!({+ "name": "list_artifacts",+ "description": "Your artifacts, newest first: id, title, when each was last published, and the path of its current HTML (to make changes, edit a copy and publish that; never edit this file in place).",+ "inputSchema": {"type": "object", "properties": {}},+ "annotations": {"readOnlyHint": true},+ }),+ ]+}++fn key(bot: &str, id: &str) -> String {+ format!("artifact.{bot}.{id}")+}++/// Where a bot's artifacts live: `<id>.html` each.+pub fn root(bot: &str) -> PathBuf {+ crate::service::data_dir().join("bots").join(bot).join("artifacts")+}++/// The file holding an artifact's current HTML. Ids are UUIDs, so they never leave the folder.+pub fn html_path(bot: &str, id: &str) -> Result<PathBuf> {+ let id = uuid::Uuid::parse_str(id).context("invalid artifact id")?;+ Ok(root(bot).join(format!("{id}.html")))+}++pub fn get(store: &Store, bot: &str, id: &str) -> Option<Artifact> {+ serde_json::from_str(&store.kv_get(&key(bot, id))?).ok()+}++/// A bot's artifacts, the most recently published first.+pub fn list(store: &Store, bot: &str) -> Vec<Artifact> {+ let prefix = format!("artifact.{bot}.");+ let mut artifacts: Vec<Artifact> =+ store.kv_prefix(&prefix).iter().filter_map(|k| serde_json::from_str(&store.kv_get(k)?).ok()).collect();+ artifacts.sort_by_key(|artifact| std::cmp::Reverse(artifact.updated_at));+ artifacts+}++/// Saves an artifact's details and tells the apps (`artifact` event; they upsert it by id).+fn put(hub: &Hub, artifact: &Artifact) -> Result<()> {+ hub.store.kv_set(&key(&artifact.bot_id, &artifact.id), &serde_json::to_string(artifact)?)?;+ let _ = hub.events.send(json!({"type": "artifact", "artifact": artifact}));+ Ok(())+}++pub fn title(value: &str) -> Result<String> {+ let value = value.trim();+ ensure!(!value.is_empty() && value.len() <= MAX_TITLE, "title must be 1–{MAX_TITLE} bytes");+ ensure!(!value.chars().any(char::is_control), "title can't hold control characters");+ Ok(value.to_owned())+}++/// Blocking: copies the bot's HTML file over the artifact's own, whole or not at all. Returns its size and SHA-256.+fn write(dest: &Path, source: &Path) -> Result<(u64, String)> {+ let input = files::open_regular(source)?;+ ensure!(input.metadata()?.len() <= MAX_ARTIFACT, "an artifact can be at most 5 MiB");+ let mut html = Vec::new();+ input.take(MAX_ARTIFACT + 1).read_to_end(&mut html)?;+ ensure!(u64::try_from(html.len())? <= MAX_ARTIFACT, "an artifact can be at most 5 MiB");+ ensure!(!html.is_empty(), "the artifact is empty");+ std::fs::create_dir_all(dest.parent().context("artifact folder")?).context("creating the artifacts folder")?;+ let partial = dest.with_extension("partial");+ std::fs::write(&partial, &html)?;+ std::fs::rename(&partial, dest)?;+ Ok((u64::try_from(html.len())?, files::digest_hex(&Sha256::digest(&html))))+}++/// The `chat` server's artifact tools.+pub async fn call(hub: &Arc<Hub>, bot: &str, name: &str, args: &Value) -> Result<Value> {+ match name {+ "publish_artifact" => publish(hub, bot, args).await,+ "list_artifacts" => {+ let artifacts: Vec<Value> = list(&hub.store, bot)+ .iter()+ .map(|artifact| {+ let path = html_path(bot, &artifact.id).map(|path| path.display().to_string()).unwrap_or_default();+ json!({"id": artifact.id, "title": artifact.title, "updatedAt": artifact.updated_at, "path": path})+ })+ .collect();+ Ok(json!({"artifacts": artifacts}))+ }+ _ => bail!("unknown artifact tool: {name}"),+ }+}++async fn publish(hub: &Arc<Hub>, bot: &str, args: &Value) -> Result<Value> {+ let row = hub.store.bot(bot)?.filter(|r| !r.deleted).ok_or_else(|| anyhow!("unknown bot"))?;+ let source = args["path"].as_str().filter(|s| !s.is_empty()).ok_or_else(|| anyhow!("path is required"))?;+ let existing = match args["artifact"].as_str().filter(|s| !s.is_empty()) {+ Some(id) => {+ Some(get(&hub.store, bot, id).ok_or_else(|| anyhow!("no artifact {id}: list_artifacts shows yours"))?)+ }+ None => None,+ };+ let title = match (args["title"].as_str(), &existing) {+ (Some(value), _) => title(value)?,+ (None, Some(artifact)) => artifact.title.clone(),+ (None, None) => bail!("title is required for a new artifact"),+ };+ let id = existing.as_ref().map_or_else(|| uuid::Uuid::new_v4().to_string(), |artifact| artifact.id.clone());+ let (dest, source) = (html_path(bot, &id)?, Path::new(&row.config.cwd).join(source));+ let (size, sha256) = tokio::task::spawn_blocking(move || write(&dest, &source)).await??;+ let now = now_ms();+ let mut artifact = Artifact {+ id,+ bot_id: bot.to_owned(),+ title,+ size,+ sha256,+ created_at: existing.as_ref().map_or(now, |artifact| artifact.created_at),+ updated_at: now,+ entry_id: existing.and_then(|artifact| artifact.entry_id),+ };+ // Saved before its card goes out, so an app opening the card finds it.+ put(hub, &artifact)?;+ let mut answer = json!({"published": true, "artifact": {"id": artifact.id, "title": artifact.title}});+ let (reply, posted) = oneshot::channel();+ hub.send_cmd(bot, Cmd::PostArtifact { data: artifact.card_entry(), reply })?;+ let posted = tokio::time::timeout(Duration::from_secs(10), posted)+ .await+ .map_err(|_| anyhow!("the artifact was saved, but its card wasn't posted in time"))?+ .map_err(|_| anyhow!("the artifact was saved, but the bot shut down before posting its card"))?;+ match posted {+ Ok(entry) => {+ artifact.entry_id = Some(entry);+ put(hub, &artifact)?;+ }+ // A routine, a room or a bot request: the artifact is in the chat's Library, and its reply says so.+ Err(error) => answer["card"] = format!("not posted ({error:#}); mention the artifact in your reply").into(),+ }+ Ok(answer)+}++/// The apps' artifact methods: `readArtifact {botId, artifactId, offset}` and `renameArtifact {botId, artifactId,+/// title}`. The list is the chat's Library (`chat::library`).+pub async fn api(hub: &Arc<Hub>, method: &str, b: &Value) -> Result<Value> {+ let bot = b["botId"].as_str().ok_or_else(|| anyhow!("`botId` is required"))?;+ ensure!(hub.store.bot(bot)?.is_some_and(|row| !row.deleted), "unknown bot");+ let id = b["artifactId"].as_str().ok_or_else(|| anyhow!("`artifactId` is required"))?;+ let mut artifact = get(&hub.store, bot, id).ok_or_else(|| anyhow!("unknown artifact"))?;+ match method {+ "readArtifact" => {+ let offset = b["offset"].as_u64().ok_or_else(|| anyhow!("offset must be a nonnegative integer"))?;+ let path = html_path(bot, id)?;+ let size = artifact.size;+ let data = tokio::task::spawn_blocking(move || read(&path, size, offset)).await??;+ Ok(+ json!({"data": base64::engine::general_purpose::STANDARD.encode(data), "size": size, "artifact": artifact}),+ )+ }+ "renameArtifact" => {+ artifact.title = title(b["title"].as_str().unwrap_or_default())?;+ put(hub, &artifact)?;+ Ok(json!({"artifact": artifact}))+ }+ _ => bail!("unknown artifact method: {method}"),+ }+}++/// One chunk of an artifact's HTML, from `offset`.+fn read(path: &Path, size: u64, offset: u64) -> Result<Vec<u8>> {+ ensure!(offset <= size, "invalid artifact offset");+ files::read_chunk(path, size, offset, "the artifact is missing or damaged")+}++/// The note a bot reads before a message about one of its artifacts (a reply to the artifact's card).+pub fn note(store: &Store, bot: &str, id: &str) -> Option<String> {+ let artifact = get(store, bot, id)?;+ let path = html_path(bot, id).ok()?;+ Some(format!(+ "[Codync: this is about your artifact \"{}\" (id {id}). Its current HTML is {}; to change the artifact, edit a copy \+ and publish_artifact with artifact: \"{id}\".]",+ artifact.title,+ path.display()+ ))+}++#[cfg(test)]+mod tests {+ use super::*;++ #[test]+ fn titles_are_trimmed_and_bounded() {+ assert_eq!(title(" Weekly report ").unwrap(), "Weekly report");+ assert!(title(" ").is_err());+ assert!(title(&"x".repeat(MAX_TITLE + 1)).is_err());+ assert!(title("a\nb").is_err());+ }++ #[test]+ fn artifacts_are_written_whole_and_read_in_chunks() {+ let dir = std::env::temp_dir().join(format!("codync-artifacts-{}", uuid::Uuid::new_v4()));+ std::fs::create_dir_all(&dir).unwrap();+ let (source, dest) = (dir.join("artifact.html"), dir.join("artifacts/p.html"));+ let html = "<h1>Hi</h1>".repeat(50_000);+ std::fs::write(&source, &html).unwrap();+ let (size, sha) = write(&dest, &source).unwrap();+ assert_eq!(size, html.len() as u64);+ assert_eq!(sha, files::digest_hex(&Sha256::digest(html.as_bytes())));+ let first = read(&dest, size, 0).unwrap();+ assert_eq!(first.len(), files::CHUNK_SIZE);+ let rest = read(&dest, size, first.len() as u64).unwrap();+ assert_eq!([first, rest].concat(), html.as_bytes());+ assert!(read(&dest, size, size + 1).is_err(), "past the end");+ std::fs::write(&source, "").unwrap();+ assert!(write(&dest, &source).is_err(), "an empty artifact");+ assert!(html_path("b", "../x").is_err(), "ids are UUIDs");+ let _ = std::fs::remove_dir_all(dir);+ }+}diff --git a/host/src/chat/files.rs b/host/src/chat/files.rsindex a5db1265..0c3eb9ac 100644--- a/host/src/chat/files.rs+++ b/host/src/chat/files.rs@@ -58,7 +58,7 @@ pub fn name(value: &str) -> Result<String> {Ok(value.to_owned())}-fn open_regular(path: &Path) -> Result<File> {+pub(crate) fn open_regular(path: &Path) -> Result<File> {let mut options = OpenOptions::new();options.read(true);#[cfg(unix)]@@ -154,11 +154,16 @@ pub fn digest_hex(bytes: &[u8]) -> String {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");+ read_chunk(&path(root, &meta.id)?, meta.size, offset, "shared file is missing or damaged")+}++/// Up to `CHUNK_SIZE` bytes of the stored file `path` from `offset` (at most `size`); fails with `damaged` unless the+/// file is `size` bytes long.+pub(crate) fn read_chunk(path: &Path, size: u64, offset: u64, damaged: &str) -> Result<Vec<u8>> {+ let mut file = open_regular(path)?;+ ensure!(file.metadata()?.len() == size, "{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];+ let mut data = vec![0; usize::try_from((size - offset).min(CHUNK_SIZE as u64))?];file.read_exact(&mut data)?;Ok(data)}diff --git a/host/src/chat/library.rs b/host/src/chat/library.rsnew file mode 100644index 00000000..f543ba4d--- /dev/null+++ b/host/src/chat/library.rs@@ -0,0 +1,33 @@+//! A chat's Library, Grok Bot's way: the artifacts its bot published and the files shared in it, by the bot+//! (`send_file`) or the user (attachments), newest first. The apps open each one the way the chat does: an artifact with+//! `readArtifact`, a bot's file with `readFile`, an attachment with `readUpload`.++use crate::chat::artifacts;+use crate::hub::Hub;+use crate::store::EntryKind;+use anyhow::{Result, ensure};+use serde_json::{Value, json};++/// Messages with files it looks through, newest first.+const MAX_FILE_MESSAGES: i64 = 500;++/// `library {botId}` → `{items: [{kind: artifact | file | attachment, at, …}]}`.+pub fn list(hub: &Hub, bot: &str) -> Result<Value> {+ ensure!(hub.store.bot(bot)?.is_some_and(|row| !row.deleted), "unknown bot");+ let mut items: Vec<Value> = artifacts::list(&hub.store, bot)+ .into_iter()+ .map(|artifact| json!({"kind": "artifact", "at": artifact.updated_at, "artifact": artifact}))+ .collect();+ for e in hub.store.file_messages(bot, MAX_FILE_MESSAGES)? {+ let (kind, files) = if e.kind == EntryKind::User.as_str() {+ ("attachment", &e.data["attachments"])+ } else {+ ("file", &e.data["files"])+ };+ for file in files.as_array().into_iter().flatten() {+ items.push(json!({"kind": kind, "at": e.created_at, "entryId": e.id, "file": file}));+ }+ }+ items.sort_by_key(|item| std::cmp::Reverse(item["at"].as_i64().unwrap_or_default()));+ Ok(json!({"items": items}))+}diff --git a/host/src/chat/mod.rs b/host/src/chat/mod.rsindex b6da5614..1637d4be 100644--- a/host/src/chat/mod.rs+++ b/host/src/chat/mod.rs@@ -1,11 +1,13 @@//! Conversation features on top of bots: messages to the user, reactions and quote replies, group room turns,-//! bot-to-bot requests, team management, a bot's own fallbacks, prompt snapshots, long-term memory and automatic bot names.+//! bot-to-bot requests, artifacts and the Library, team management, a bot's own fallbacks, prompt snapshots, long-term memory and automatic bot names.+pub mod artifacts;pub mod context;pub mod fallbacks;pub mod files;pub mod group;pub mod handoff;+pub mod library;pub mod manage;pub mod memory;pub mod naming;diff --git a/host/src/chat/outbox.rs b/host/src/chat/outbox.rsindex ab7d96fd..da4022b5 100644--- a/host/src/chat/outbox.rs+++ b/host/src/chat/outbox.rs@@ -16,6 +16,10 @@ pub const INSTRUCTIONS: &str = "In your chat with the user, the user sees only wtext 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. \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. \+For something the user will read as a whole or come back to (a report, plan, comparison, tracker or dashboard), make an Artifact \+instead of a long message: write one self-contained HTML file (inline CSS and JS; it may load libraries from a CDN) and \+publish_artifact(path, title). It shows as a card in your chat and in its Library. To change an artifact, edit a copy of its HTML and \+publish_artifact(path, artifact: its id); never make a second artifact for the same thing. list_artifacts shows your artifacts and where each one's HTML is. \Reactions are rare: react(emoji) only where a person would (❤️ to thanks, 👍 to a plain OK, 🎉 to big news, 😂 to a real joke), \never to a question or a request. When a message needs no words, the reaction is the whole reply; when it needs neither, \end your turn by replying exactly \"(pass)\".";diff --git a/host/src/chat/replies.rs b/host/src/chat/replies.rsindex 3ca7fdc6..81f3b6b7 100644--- a/host/src/chat/replies.rs+++ b/host/src/chat/replies.rs@@ -10,19 +10,35 @@ use serde_json::{Value, json};/// How much of the answered message's text the reply keeps.const QUOTE_BYTES: usize = 500;-/// What `send` stores as `replyTo`: the message answered (`id`, in `chat`), who wrote it (`"user"` or a bot id) and-/// its text (or its files' names).+/// What `send` stores as `replyTo`: the message answered (`id`, in `chat`), who wrote it (`"user"` or a bot id), its+/// text (or its files' names), and the artifact when it's an artifact card.pub fn quote(store: &Store, chat: &str, id: &str) -> Result<Value> {let e = store.entry(id).filter(|e| e.bot_id == chat).ok_or_else(|| anyhow!("unknown message"))?;let user = e.kind == EntryKind::User.as_str();ensure!(user || (e.kind == EntryKind::Agent.as_str() && e.data["final"] == true), "only messages take replies");let author = if user { "user" } else { e.data["author"].as_str().unwrap_or(chat) };- Ok(json!({"id": e.id, "author": author, "text": acp::truncate(message_text(&e.data).trim(), QUOTE_BYTES)}))+ let mut quote =+ json!({"id": e.id, "author": author, "text": acp::truncate(message_text(&e.data).trim(), QUOTE_BYTES)});+ if let Some(artifact) = e.data["artifact"]["id"].as_str() {+ // Quoted under the artifact's current title: the card's text keeps the one it was published with.+ if let Some(current) = crate::chat::artifacts::get(store, author, artifact) {+ quote["text"] = crate::chat::artifacts::card_text(¤t.title).into();+ }+ quote["artifact"] = artifact.into();+ }+ Ok(quote)}-/// The note `me` reads before a reply's text: `[Codync: this replies to your message: "…"]`. Coming from-/// Codync, it stands even when the quoted message is no longer in the agent's session.+/// The note `me` reads before a reply's text: `[Codync: this replies to your message: "…"]`, or for its own artifact's+/// card, where that artifact is (`artifacts::note`). Coming from Codync, it stands even when the quoted message is no longer+/// in the agent's session.pub fn note(hub: &Hub, me: &str, reply: &Value) -> Option<String> {+ if reply["author"] == me+ && let Some(note) =+ reply["artifact"].as_str().and_then(|artifact| crate::chat::artifacts::note(&hub.store, me, artifact))+ {+ return Some(note);+ }let text = reply["text"].as_str()?.split_whitespace().collect::<Vec<_>>().join(" ");let whose = match reply["author"].as_str().unwrap_or_default() {"user" => "the user's earlier message".to_owned(),diff --git a/host/src/hub.rs b/host/src/hub.rsindex 485c8f0b..cac18386 100644--- a/host/src/hub.rs+++ b/host/src/hub.rs@@ -297,15 +297,17 @@ impl Hub {let _ =self.events.send(json!({"type": "bot", "rev": rev, "bot": {"id": id, "deleted": true, "rev": rev}}));}- // Its shared files are unreachable once the bot is deleted.- let files = crate::chat::files::root(id);+ // Its shared files and artifacts are unreachable once the bot is deleted.+ let folders = [crate::chat::files::root(id), crate::chat::artifacts::root(id)];let bot = id.to_owned();tokio::task::spawn_blocking(move || {crate::chat::memory::files::remove_bot(&bot);- if let Err(error) = std::fs::remove_dir_all(&files)- && error.kind() != std::io::ErrorKind::NotFound- {- tracing::warn!(error = %error, "couldn't remove a deleted bot's shared files");+ for folder in folders {+ if let Err(error) = std::fs::remove_dir_all(&folder)+ && error.kind() != std::io::ErrorKind::NotFound+ {+ tracing::warn!(error = %error, "couldn't remove a deleted bot's shared files or artifacts");+ }}});// A deleted bot leaves its groups; what it said there stays.diff --git a/host/src/mcp.rs b/host/src/mcp.rsindex 127fa8e0..67f98f29 100644--- a/host/src/mcp.rs+++ b/host/src/mcp.rs@@ -71,6 +71,7 @@ pub async fn serve(bot: String, port: u16, server: Server) -> Result<()> {Server::Chat => {let mut tools = crate::chat::outbox::tools();if let Some(list) = tools.as_array_mut() {+ list.extend(crate::chat::artifacts::tools());list.extend(crate::chat::profile::tools());list.extend(crate::chat::fallbacks::tools());list.push(crate::chat::reactions::tool());diff --git a/host/src/store/bots.rs b/host/src/store/bots.rsindex 7fc7b709..96294876 100644--- a/host/src/store/bots.rs+++ b/host/src/store/bots.rs@@ -79,6 +79,8 @@ impl Store {"DELETE FROM kv WHERE k GLOB ?1 OR k GLOB ?2",[format!("context.{id}.*"), format!("context.epoch.{id}.*")],)?;+ // Its artifacts' details (`chat::artifacts`).+ c.execute("DELETE FROM kv WHERE k GLOB ?1", [format!("artifact.{id}.*")])?;Ok(rev)}diff --git a/host/src/store/entries.rs b/host/src/store/entries.rsindex ced2d5df..01420dcc 100644--- a/host/src/store/entries.rs+++ b/host/src/store/entries.rs@@ -162,6 +162,18 @@ impl Store {Ok(rows)}+ /// A chat's messages with files (shared by a bot, attached by the user), newest first: its Library.+ // ponytail: scans the chat's entries without an index; add one if a long chat's Library gets slow.+ pub fn file_messages(&self, bot_id: &str, limit: i64) -> Result<Vec<Entry>> {+ let c = self.db.locked();+ let mut st = c.prepare(&format!(+ "SELECT {ENTRY_COLS} FROM entries WHERE bot_id = ?1+ AND (json_array_length(data, '$.files') > 0 OR json_array_length(data, '$.attachments') > 0)+ ORDER BY seq DESC LIMIT ?2"+ ))?;+ Ok(st.query_map(params![bot_id, limit], row_entry)?.collect::<rusqlite::Result<_>>()?)+ }+/// Cards still waiting for the user to sign in to agent `backend`, oldest first.// ponytail: scans notices without an index; sign-ins are rare, add one if it shows up in profiles.pub fn pending_sign_ins(&self, backend: &str) -> Result<Vec<Entry>> {diff --git a/host/src/tui/app/analytics.rs b/host/src/tui/app/analytics.rsindex bdca9897..8d904020 100644--- a/host/src/tui/app/analytics.rs+++ b/host/src/tui/app/analytics.rs@@ -56,6 +56,7 @@ impl App {Overlay::Usage => Some(Screen::Usage),Overlay::Pair(_) => Some(Screen::Pairing),Overlay::Memory(_) => Some(Screen::Memory),+ Overlay::Library(_) => Some(Screen::Library),Overlay::Routines(_) => Some(Screen::Routines),Overlay::Market(_) => Some(Screen::Marketplace),Overlay::Help(_) => Some(Screen::Help),diff --git a/host/src/tui/app/events.rs b/host/src/tui/app/events.rsindex b8f1461f..459c6ab1 100644--- a/host/src/tui/app/events.rs+++ b/host/src/tui/app/events.rs@@ -66,10 +66,14 @@ impl App {self.upsert_bot(&v["bot"]);self.memory_moved(&v["bot"]);}+ Some("artifact") => self.artifact_changed(&v["artifact"]),Some("entry") => {if let Some((bot, e)) = Entry::parse(&v["entry"])&& !self.outside_window(&bot, &e){+ if !self.entries.get(&bot).is_some_and(|m| m.contains_key(&e.seq)) {+ self.entry_added(&bot, &e);+ }self.entries.entry(bot).or_default().insert(e.seq, e);}}diff --git a/host/src/tui/app/input.rs b/host/src/tui/app/input.rsindex 37a885fd..050e997e 100644--- a/host/src/tui/app/input.rs+++ b/host/src/tui/app/input.rs@@ -306,6 +306,7 @@ impl App {KeyCode::Char('U') => self.overlays.push(Overlay::Usage),KeyCode::Char('M') => self.open_memory(),KeyCode::Char('R') => self.open_routines(),+ KeyCode::Char('L') => self.open_library(),KeyCode::Char('A') => self.open_market(),KeyCode::Char('r' | 'v') if !roster_page && self.selected.is_some() => {self.chat_page = true;diff --git a/host/src/tui/app/mod.rs b/host/src/tui/app/mod.rsindex a3b85227..b4e801a2 100644--- a/host/src/tui/app/mod.rs+++ b/host/src/tui/app/mod.rs@@ -72,6 +72,8 @@ pub struct App {/// What was pasted into each draft, sent along so memory never takes it as the user's own words.pub pasted: HashMap<String, Vec<String>>,pub download: Option<super::net::files::Download>,+ /// Each artifact's newest title, for its cards.+ pub artifact_titles: super::manage::ArtifactTitles,sends: HashMap<String, PendingSend>,/// Lines scrolled up from the bottom of the chat (0 = follow new messages).pub chat_scroll: usize,@@ -127,6 +129,7 @@ impl App {pub fn new(client: Client, tx: UnboundedSender<Msg>, url: String) -> Self {Self {download: None,+ artifact_titles: super::manage::ArtifactTitles::default(),client,tx,url,@@ -469,46 +472,4 @@ fn test_app() -> App {}#[cfg(test)]-mod tests {- use super::*;-- #[test]- fn fuzzy_is_a_subsequence_match() {- assert!(fuzzy("rx", &["Rex"]));- assert!(fuzzy("", &["anything"]));- assert!(!fuzzy("xr", &["Rex"]));- assert!(fuzzy("web", &["Rex", "~/mycode/web"]));- }-- #[tokio::test]- async fn the_chat_on_screen_is_marked_read() {- let mut app = test_app();- let bot = Bot::parse(&json!({"id": "b", "name": "Bot", "unread": 2})).expect("a bot with an id parses");- app.bots.insert("b".into(), bot);- app.selected = Some("b".into());- (app.width, app.term_focused) = (Width::Wide, true);- app.tick();- assert!(app.reading.contains("b"));- }-- #[tokio::test]- async fn r_on_a_picked_message_replies_to_it() {- let mut app = test_app();- app.bots.insert("b".into(), Bot::parse(&json!({"id": "b", "name": "Bot"})).expect("a bot with an id parses"));- app.selected = Some("b".into());- for (seq, kind) in [(1, "user"), (2, "agent")] {- let v = json!({"botId": "b", "id": format!("e{seq}"), "seq": seq, "turn": 1, "kind": kind,- "data": {"text": "hi", "final": true}});- let (bot, e) = Entry::parse(&v).expect("a full entry parses");- app.entries.entry(bot).or_default().insert(e.seq, e);- }- app.step_pick(0);- assert_eq!(app.pick.as_deref(), Some("e2"), "a fresh pick is the newest message");- app.step_pick(-1);- let r = crossterm::event::KeyEvent::from(crossterm::event::KeyCode::Char('r'));- assert!(app.pick_key(r));- assert_eq!(app.reply.as_deref(), Some("e1"));- assert_eq!(app.replying_to().map(Entry::quoted).as_deref(), Some("hi"));- assert!(app.typing && app.pick.is_none());- }-}+mod tests;diff --git a/host/src/tui/app/model.rs b/host/src/tui/app/model.rsindex 7c50df34..d65a51ed 100644--- a/host/src/tui/app/model.rs+++ b/host/src/tui/app/model.rs@@ -392,6 +392,11 @@ impl Entry {self.kind == Kind::User || self.is_final() || self.data["connectionRequest"].is_object()}+ /// An artifact card's artifact id (`docs/features/artifacts.md`): `o` opens it, `f` saves it.+ pub fn artifact(&self) -> Option<&str> {+ if self.is_final() { self.data["artifact"]["id"].as_str() } else { None }+ }+/// A line that folds away a longer text: a handoff (`o` shows it).pub fn unfolds(&self) -> bool {crate::tui::view::unfoldable(self).is_some()diff --git a/host/src/tui/app/navigate.rs b/host/src/tui/app/navigate.rsindex 520c35a0..caf8737b 100644--- a/host/src/tui/app/navigate.rs+++ b/host/src/tui/app/navigate.rs@@ -192,6 +192,11 @@ impl App {KeyCode::Enter if picked.as_ref().is_some_and(|e| e.data["connectionRequest"]["status"] == "pending") => {self.open_connection();}+ KeyCode::Char('o') if picked.as_ref().is_some_and(|e| e.artifact().is_some()) => {+ if let Some(artifact) = picked.as_ref().and_then(super::Entry::artifact) {+ self.fetch_artifact(&id, artifact, crate::tui::net::artifacts::ArtifactTo::Browser);+ }+ }KeyCode::Char('o') if picked.as_ref().is_some_and(super::Entry::unfolds) => {if let Some(e) = picked&& !self.unfolded.remove(&e.id)diff --git a/host/src/tui/app/overlay_keys.rs b/host/src/tui/app/overlay_keys.rsindex 4d74b82f..478a8327 100644--- a/host/src/tui/app/overlay_keys.rs+++ b/host/src/tui/app/overlay_keys.rs@@ -50,6 +50,7 @@ impl App {Action::Market => self.open_market(),Action::Memory => self.open_memory(),Action::Details => self.open_routines(),+ Action::Library => self.open_library(),Action::RefreshAgents => self.call("refreshBackends", json!({}), After::Backends),Action::Pair => self.open_pair(),Action::Usage => self.overlays.push(Overlay::Usage),@@ -116,6 +117,7 @@ impl App {Overlay::BotChat(c) => Self::bot_chat_key(c, k),Overlay::Routines(l) => self.routines_key(l, k),Overlay::Routine(f) => self.routine_key(f, k),+ Overlay::Library(l) => self.library_key(l, k),Overlay::Market(m) => self.market_key(m, k),Overlay::Agent(a) => self.agent_key(a, k),Overlay::Fields(f) => self.fields_key(f, k),diff --git a/host/src/tui/app/tests.rs b/host/src/tui/app/tests.rsnew file mode 100644index 00000000..c847c580--- /dev/null+++ b/host/src/tui/app/tests.rs@@ -0,0 +1,41 @@+use super::*;++#[test]+fn fuzzy_is_a_subsequence_match() {+ assert!(fuzzy("rx", &["Rex"]));+ assert!(fuzzy("", &["anything"]));+ assert!(!fuzzy("xr", &["Rex"]));+ assert!(fuzzy("web", &["Rex", "~/mycode/web"]));+}++#[tokio::test]+async fn the_chat_on_screen_is_marked_read() {+ let mut app = test_app();+ let bot = Bot::parse(&json!({"id": "b", "name": "Bot", "unread": 2})).expect("a bot with an id parses");+ app.bots.insert("b".into(), bot);+ app.selected = Some("b".into());+ (app.width, app.term_focused) = (Width::Wide, true);+ app.tick();+ assert!(app.reading.contains("b"));+}++#[tokio::test]+async fn r_on_a_picked_message_replies_to_it() {+ let mut app = test_app();+ app.bots.insert("b".into(), Bot::parse(&json!({"id": "b", "name": "Bot"})).expect("a bot with an id parses"));+ app.selected = Some("b".into());+ for (seq, kind) in [(1, "user"), (2, "agent")] {+ let v = json!({"botId": "b", "id": format!("e{seq}"), "seq": seq, "turn": 1, "kind": kind,+ "data": {"text": "hi", "final": true}});+ let (bot, e) = Entry::parse(&v).expect("a full entry parses");+ app.entries.entry(bot).or_default().insert(e.seq, e);+ }+ app.step_pick(0);+ assert_eq!(app.pick.as_deref(), Some("e2"), "a fresh pick is the newest message");+ app.step_pick(-1);+ let r = crossterm::event::KeyEvent::from(crossterm::event::KeyCode::Char('r'));+ assert!(app.pick_key(r));+ assert_eq!(app.reply.as_deref(), Some("e1"));+ assert_eq!(app.replying_to().map(Entry::quoted).as_deref(), Some("hi"));+ assert!(app.typing && app.pick.is_none());+}diff --git a/host/src/tui/app/ui.rs b/host/src/tui/app/ui.rsindex 6ed84f95..7ec7e125 100644--- a/host/src/tui/app/ui.rs+++ b/host/src/tui/app/ui.rs@@ -5,7 +5,8 @@ use std::collections::BTreeMap;use std::time::Instant;use super::super::manage::{- AgentSetup, AnalyticsSheet, BotChatSheet, Fields, Market, MemorySheet, RoutineForm, RoutineList, SkillSheet,+ AgentSetup, AnalyticsSheet, BotChatSheet, Fields, Library, Market, MemorySheet, RoutineForm, RoutineList,+ SkillSheet,};use super::{Editor, Mark};@@ -51,6 +52,7 @@ pub enum Action {Market,Memory,Details,+ Library,RefreshAgents,Pair,Usage,@@ -62,12 +64,13 @@ pub enum Action {Appearance(super::super::appearance::Appearance),}-pub const ACTIONS: [(&str, &str, Action); 16] = [+pub const ACTIONS: [(&str, &str, Action); 17] = [("New bot…", "n", Action::NewBot),("New group chat…", "m", Action::NewGroup),("Extensions: agents, connectors, skills…", "A", Action::Market),("Memory of this bot…", "M", Action::Memory),("Details of this bot…", "R", Action::Details),+ ("Library of this bot: artifacts and files…", "L", Action::Library),("Refresh agents", "", Action::RefreshAgents),("Pair a phone…", "P", Action::Pair),("Usage", "U", Action::Usage),@@ -303,6 +306,7 @@ pub enum Overlay {BotChat(BotChatSheet),Routines(RoutineList),Routine(Box<RoutineForm>),+ Library(Library),Market(Box<Market>),Agent(AgentSetup),Fields(Box<Fields>),diff --git a/host/src/tui/manage/fields.rs b/host/src/tui/manage/fields.rsindex 452b97af..ed597b90 100644--- a/host/src/tui/manage/fields.rs+++ b/host/src/tui/manage/fields.rs@@ -78,6 +78,10 @@ impl App {Submit::Handoff(entry) => {self.sheet("editHandoff", json!({"entryId": entry, "text": values["text"]}), Reply::FieldsSaved);}+ Submit::RenameArtifact { bot, artifact } => {+ let body = json!({"botId": bot, "artifactId": artifact, "title": values["title"]});+ self.sheet("renameArtifact", body, Reply::FieldsSaved);+ }}}}diff --git a/host/src/tui/manage/library.rs b/host/src/tui/manage/library.rsnew file mode 100644index 00000000..5a5bcc88--- /dev/null+++ b/host/src/tui/manage/library.rs@@ -0,0 +1,278 @@+//! A bot's Library (`docs/features/artifacts.md`): the artifacts it published and the files shared in its chat,+//! newest first; also the newest titles artifact cards show, and opening or saving an artifact.++use crossterm::event::{KeyCode, KeyEvent};+use serde_json::{Value, json};+use std::collections::{HashMap, HashSet};++use super::super::app::{App, Editor, Entry, Overlay};+use super::super::net::artifacts::ArtifactTo;+use super::{Fields, Input, Library, Page, Reply, Submit};+use crate::chat::artifacts::Artifact;+use crate::chat::files::SharedFile;++/// One row of a Library (`library {botId}`).+#[derive(Clone, Debug)]+pub enum LibraryItem {+ Artifact(Artifact),+ /// A file the bot shared (`readFile`).+ File {+ entry: String,+ file: SharedFile,+ at: i64,+ },+ /// A file the user attached (`readUpload`).+ Attachment {+ id: String,+ name: String,+ size: u64,+ at: i64,+ },+}++/// The newest title of each artifact (artifact id → title), and the bots whose Library was read for them.+#[derive(Default)]+pub struct ArtifactTitles {+ titles: HashMap<String, String>,+ asked: HashSet<String>,+}++impl LibraryItem {+ fn parse(v: &Value) -> Option<Self> {+ let at = v["at"].as_i64().unwrap_or_default();+ let file = &v["file"];+ match v["kind"].as_str()? {+ "artifact" => serde_json::from_value(v["artifact"].clone()).ok().map(Self::Artifact),+ "file" => Some(Self::File {+ entry: v["entryId"].as_str()?.to_owned(),+ file: serde_json::from_value(file.clone()).ok()?,+ at,+ }),+ "attachment" => Some(Self::Attachment {+ id: file["id"].as_str()?.to_owned(),+ name: file["name"].as_str()?.to_owned(),+ size: file["size"].as_u64().unwrap_or_default(),+ at,+ }),+ _ => None,+ }+ }++ /// When it was published or shared (epoch ms): the list's order.+ pub fn at(&self) -> i64 {+ match self {+ Self::Artifact(a) => a.updated_at,+ Self::File { at, .. } | Self::Attachment { at, .. } => *at,+ }+ }+}++impl App {+ pub fn open_library(&mut self) {+ let Some(b) = self.bot().filter(|b| !b.group) else {+ self.flash("The Library belongs to a bot, not a group");+ return;+ };+ let bot = b.id.clone();+ self.sheet("library", json!({"botId": bot}), Reply::Library(bot.clone()));+ self.overlays.push(Overlay::Library(Library { bot, items: None, cursor: 0 }));+ }++ pub(in crate::tui) fn library_key(&mut self, mut l: Library, k: KeyEvent) -> Option<Overlay> {+ if let Some(page) = Page::Library.step(k) {+ self.open_page(page);+ return None;+ }+ let n = l.items.as_ref().map_or(0, Vec::len);+ let current = l.items.as_ref().and_then(|v| v.get(l.cursor)).cloned();+ let bot = l.bot.clone();+ match (k.code, current) {+ (KeyCode::Esc | KeyCode::Char('q' | 'L'), _) => return None,+ (KeyCode::Down | KeyCode::Char('j'), _) => l.cursor = (l.cursor + 1).min(n.saturating_sub(1)),+ (KeyCode::Up | KeyCode::Char('k'), _) => l.cursor = l.cursor.saturating_sub(1),+ (KeyCode::Enter | KeyCode::Char('o'), Some(LibraryItem::Artifact(a))) => {+ self.fetch_artifact(&bot, &a.id, ArtifactTo::Browser);+ }+ (KeyCode::Enter | KeyCode::Char('o'), Some(_)) => self.flash("f saves it to Downloads"),+ (KeyCode::Char('f'), Some(item)) => self.save_item(&bot, item),+ (KeyCode::Char('r'), Some(LibraryItem::Artifact(a))) => {+ self.overlays.push(Overlay::Library(l));+ self.overlays.push(Overlay::Fields(Box::new(rename_fields(bot, a.id, &a.title))));+ return None;+ }+ (KeyCode::Char('r'), Some(_)) => self.flash("Only artifacts can be renamed"),+ _ => {}+ }+ Some(Overlay::Library(l))+ }++ /// `f`: saves the row to Downloads, or stops the download running.+ fn save_item(&mut self, bot: &str, item: LibraryItem) {+ if self.cancel_download() {+ return;+ }+ match item {+ LibraryItem::Artifact(a) => self.fetch_artifact(bot, &a.id, ArtifactTo::Downloads),+ LibraryItem::File { entry, file, .. } => self.download_shared(entry, file),+ LibraryItem::Attachment { id, name, .. } => self.save_uploads(bot, vec![(id, name)]),+ }+ }++ /// Reads the artifact's HTML into the browser or Downloads, in place of any download running.+ pub(in crate::tui) fn fetch_artifact(&mut self, bot: &str, artifact: &str, to: ArtifactTo) {+ self.download = Some(self.client.fetch_artifact(bot.to_owned(), artifact.to_owned(), to, self.tx.clone()));+ self.flash(match to {+ ArtifactTo::Browser => "Opening the artifact… · f cancels",+ ArtifactTo::Downloads => "Saving the artifact… · f cancels",+ });+ }++ /// A card's title: the newest one known (a rename or a publish since), else the card's own.+ pub(in crate::tui) fn artifact_title(&self, e: &Entry) -> Option<String> {+ let card = &e.data["artifact"];+ let id = card["id"].as_str()?;+ let title = self+ .artifact_titles+ .titles+ .get(id)+ .map_or_else(|| card["title"].as_str().unwrap_or_default(), String::as_str);+ Some(title.to_owned())+ }++ /// A new entry in `bot`'s chat. One that adds to its Library (an artifact card, a message with files)+ /// reads an open Library again. An artifact card also reads it once a run, so every card of an artifact+ /// shows its newest title (a card keeps the title it was posted with).+ pub(in crate::tui) fn entry_added(&mut self, bot: &str, e: &Entry) {+ let open = self.overlays.iter().any(|o| matches!(o, Overlay::Library(l) if l.bot == bot));+ let first_card = e.artifact().is_some() && !self.artifact_titles.asked.contains(bot);+ if open && adds_to_library(e) || first_card {+ self.artifact_titles.asked.insert(bot.to_owned());+ self.sheet("library", json!({"botId": bot}), Reply::Library(bot.to_owned()));+ }+ }++ /// A fetched Library: shown, and its artifacts' titles kept for their cards.+ pub(in crate::tui) fn library_loaded(&mut self, bot: &str, items: &[Value]) {+ let items: Vec<LibraryItem> = items.iter().filter_map(LibraryItem::parse).collect();+ for item in &items {+ if let LibraryItem::Artifact(a) = item {+ self.artifact_titles.titles.insert(a.id.clone(), a.title.clone());+ }+ }+ for o in &mut self.overlays {+ if let Overlay::Library(l) = o+ && l.bot == bot+ {+ l.cursor = l.cursor.min(items.len().saturating_sub(1));+ l.items = Some(items.clone());+ }+ }+ }++ /// An `artifact` event (a publish or a rename): its cards' title, and the open Library lists it first.+ pub(in crate::tui) fn artifact_changed(&mut self, v: &Value) {+ let Ok(artifact) = serde_json::from_value::<Artifact>(v.clone()) else { return };+ self.artifact_titles.titles.insert(artifact.id.clone(), artifact.title.clone());+ for o in &mut self.overlays {+ let Overlay::Library(l) = o else { continue };+ let Some(items) = l.items.as_mut().filter(|_| l.bot == artifact.bot_id) else { continue };+ items.retain(|x| !matches!(x, LibraryItem::Artifact(a) if a.id == artifact.id));+ items.push(LibraryItem::Artifact(artifact.clone()));+ items.sort_by_key(|x| std::cmp::Reverse(x.at()));+ }+ }+}++/// Whether an entry puts something in its chat's Library: an artifact card, or a message with files the+/// bot shared or the user attached.+fn adds_to_library(e: &Entry) -> bool {+ e.artifact().is_some()+ || ["files", "attachments"].iter().any(|k| e.data[*k].as_array().is_some_and(|a| !a.is_empty()))+}++/// `r` on an artifact: its title in a field of its own.+fn rename_fields(bot: String, artifact: String, title: &str) -> Fields {+ Fields {+ title: "Rename artifact".into(),+ note: String::new(),+ choices: vec![],+ choice: 0,+ inputs: vec![Input {+ name: "title".into(),+ label: "Artifact title".into(),+ secret: false,+ required: true,+ multiline: false,+ placeholder: String::new(),+ ed: Editor::with(title),+ }],+ cursor: 0,+ error: None,+ saving: false,+ submit: Submit::RenameArtifact { bot, artifact },+ }+}++#[cfg(test)]+mod tests {+ use super::super::super::app::Msg;+ use super::*;++ fn artifact(id: &str, title: &str, updated_at: i64) -> Value {+ json!({"id": id, "botId": "bot", "title": title, "size": 1, "sha256": "0".repeat(64),+ "createdAt": 0, "updatedAt": updated_at})+ }++ #[test]+ fn artifact_cards_and_messages_with_files_add_to_the_library() {+ let entry = |kind: &str, data: Value| {+ Entry::parse(&json!({"id": "e", "botId": "bot", "seq": 1, "kind": kind, "data": data})).expect("parses").1+ };+ let card = json!({"text": "Artifact: A", "final": true, "artifact": {"id": "a", "title": "A", "updatedAt": 1}});+ assert!(adds_to_library(&entry("agent", card)));+ let file = json!({"name": "a.csv", "id": "f", "size": 1, "sha256": ""});+ assert!(adds_to_library(&entry("agent", json!({"text": "", "final": true, "files": [file]}))));+ let attachment = json!({"id": "u", "name": "b.png", "size": 1});+ assert!(adds_to_library(&entry("user", json!({"text": "look", "attachments": [attachment]}))));+ assert!(!adds_to_library(&entry("user", json!({"text": "hi", "attachments": []}))));+ assert!(!adds_to_library(&entry("agent", json!({"text": "Done.", "final": true}))));+ assert!(!adds_to_library(&entry("tool", json!({"artifact": {"id": "a"}}))), "only a final reply is a card");+ }++ #[tokio::test]+ async fn artifact_events_rename_cards_and_move_the_artifact_to_the_top() {+ let (tx, _rx) = tokio::sync::mpsc::unbounded_channel();+ let mut app = App::new(crate::tui::net::Client::new("http://127.0.0.1:1", None), tx, String::new());+ app.on_msg(Msg::Event(json!({"type": "bot", "bot": {"id": "bot", "name": "Artifacts"}})));+ let card = Entry::parse(&json!({"id": "e", "botId": "bot", "seq": 1, "kind": "agent",+ "data": {"text": "Artifact: Old", "final": true, "artifact": {"id": "a", "title": "Old", "updatedAt": 1}}}))+ .expect("a card parses")+ .1;+ assert_eq!(app.artifact_title(&card).as_deref(), Some("Old"));+ app.overlays.push(Overlay::Library(Library { bot: "bot".into(), items: None, cursor: 0 }));+ let file = json!({"id": "x", "name": "a.csv", "size": 9, "sha256": "0".repeat(64)});+ app.library_loaded(+ "bot",+ &[+ json!({"kind": "file", "at": 3, "entryId": "f", "file": file}),+ json!({"kind": "attachment", "at": 2, "entryId": "u", "file": {"id": "y", "name": "b.png", "size": 4}}),+ json!({"kind": "artifact", "at": 1, "artifact": artifact("a", "Old", 1)}),+ json!({"kind": "unknown", "at": 0}),+ ],+ );+ app.on_msg(Msg::Event(json!({"type": "artifact", "artifact": artifact("a", "New", 9)})));+ assert_eq!(app.artifact_title(&card).as_deref(), Some("New"), "the newest title");+ let Some(Overlay::Library(l)) = app.overlays.last() else { panic!("the Library stays open") };+ let rows: Vec<String> = l+ .items+ .iter()+ .flatten()+ .map(|item| match item {+ LibraryItem::Artifact(a) => format!("artifact {}", a.title),+ LibraryItem::File { file, .. } => format!("file {}", file.name),+ LibraryItem::Attachment { name, .. } => format!("attachment {name}"),+ })+ .collect();+ assert_eq!(rows, ["artifact New", "file a.csv", "attachment b.png"]);+ }+}diff --git a/host/src/tui/manage/mod.rs b/host/src/tui/manage/mod.rsindex 79f0f39e..4700f5f8 100644--- a/host/src/tui/manage/mod.rs+++ b/host/src/tui/manage/mod.rs@@ -9,6 +9,7 @@ mod agent;mod analytics;mod bot_chat;mod fields;+mod library;mod market;mod memory;mod pages;@@ -19,6 +20,7 @@ mod when;pub use analytics::AnalyticsSheet;pub use fields::handoff_fields;+pub use library::{ArtifactTitles, LibraryItem};pub use memory::{MemoryMode, MemorySheet, Scroll, Section};pub use pages::Page;pub use skill::SkillSheet;@@ -43,6 +45,8 @@ pub enum Reply {MemoryFile(String),Routines(String),RoutineSaved,+ /// A bot's Library (`library {botId}`).+ Library(String),/// A routine's webhook URL and key: copied as a ready-to-run curl.Webhook,/// A bot conversation's fetched history.@@ -79,6 +83,13 @@ pub struct BotChatSheet {pub page: Cell<usize>,}+/// A bot's Library tab: its artifacts and the files shared in its chat, newest first.+pub struct Library {+ pub bot: String,+ pub items: Option<Vec<LibraryItem>>,+ pub cursor: usize,+}+pub struct RoutineList {pub bot: String,pub items: Option<Vec<Value>>,@@ -176,6 +187,10 @@ pub enum Submit {Import,/// A handoff card's text (the card's entry id).Handoff(String),+ RenameArtifact {+ bot: String,+ artifact: String,+ },}/// A few labeled text fields: an agent's keys, a connector's setup, a pasted MCP config.@@ -240,18 +255,27 @@ impl App {}}- /// Saves a message's files to Downloads.- pub(super) fn save_files(&mut self, bot: &str, entry: &str, data: &Value) {- if self.download.take().is_some() {+ /// `f` while a download runs: stops it.+ fn cancel_download(&mut self) -> bool {+ let running = self.download.take().is_some();+ if running {self.flash("Download cancelled · f retries");+ }+ running+ }++ /// Saves a message's files, or its artifact, to Downloads.+ pub(super) fn save_files(&mut self, bot: &str, entry: &str, data: &Value) {+ if self.cancel_download() {+ return;+ }+ if let Some(artifact) = data["artifact"]["id"].as_str() {+ self.fetch_artifact(bot, artifact, super::net::artifacts::ArtifactTo::Downloads);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");- }+ Ok(file) => self.download_shared(entry.to_owned(), file),Err(error) => self.flash(&format!("Invalid file: {error}")),}return;@@ -266,6 +290,17 @@ impl App {self.flash("No files on that message");return;}+ self.save_uploads(bot, files);+ }++ /// Saves a file the bot shared (`readFile`), with progress; `f` again cancels.+ fn download_shared(&mut self, entry: String, file: crate::chat::files::SharedFile) {+ self.download = Some(self.client.download_file(entry, file, self.tx.clone()));+ self.flash("Downloading… · f cancels");+ }++ /// Saves files the user attached (`(upload id, name)`, `readUpload`).+ fn save_uploads(&mut self, bot: &str, files: Vec<(String, String)>) {self.flash("Saving…");self.client.spawn_download(bot.to_owned(), files, self.tx.clone());}@@ -299,9 +334,11 @@ impl App {/// Opens `url` in this computer's browser, when the host is this computer.pub(super) fn open_browser(url: &str, host: &str) -> bool {let local = ["//127.0.0.1", "//localhost", "//[::1]"].iter().any(|h| host.contains(h));- if !local || url.is_empty() {- return false;- }+ local && !url.is_empty() && open_here(std::ffi::OsStr::new(url))+}++/// Opens a link or file with this computer's default app for it (a web page: the browser).+pub(in crate::tui) fn open_here(target: &std::ffi::OsStr) -> bool {let mut command = if cfg!(windows) {let mut c = std::process::Command::new("rundll32");c.arg("url.dll,FileProtocolHandler");@@ -309,5 +346,5 @@ pub(super) fn open_browser(url: &str, host: &str) -> bool {} else {std::process::Command::new(if cfg!(target_os = "macos") { "open" } else { "xdg-open" })};- command.arg(url).stdout(std::process::Stdio::null()).stderr(std::process::Stdio::null()).spawn().is_ok()+ command.arg(target).stdout(std::process::Stdio::null()).stderr(std::process::Stdio::null()).spawn().is_ok()}diff --git a/host/src/tui/manage/pages.rs b/host/src/tui/manage/pages.rsindex 91cc0179..65963124 100644--- a/host/src/tui/manage/pages.rs+++ b/host/src/tui/manage/pages.rs@@ -1,5 +1,6 @@-//! A bot's three pages, as in the desktop inspector and the iPhone's details: Details (whether it-//! may use the computer, and its routines), Memory and Settings. Shift+←→ moves between them.+//! A bot's pages of details, as in the desktop inspector and the iPhone's details: Details (whether it+//! may use the computer, and its routines), Library (the artifacts it made and the files shared in its+//! chat), Memory and Settings. Shift+←→ moves between them.use crossterm::event::{KeyCode, KeyEvent, KeyModifiers};@@ -8,16 +9,18 @@ use super::super::app::App;#[derive(Clone, Copy, PartialEq, Eq, Debug)]pub enum Page {Details,+ Library,Memory,Settings,}impl Page {- pub const ALL: [Self; 3] = [Self::Details, Self::Memory, Self::Settings];+ pub const ALL: [Self; 4] = [Self::Details, Self::Library, Self::Memory, Self::Settings];pub fn label(self) -> &'static str {match self {Self::Details => "Details",+ Self::Library => "Library",Self::Memory => "Memory",Self::Settings => "Settings",}@@ -43,6 +46,7 @@ impl App {pub(in crate::tui) fn open_page(&mut self, page: Page) {match page {Page::Details => self.open_routines(),+ Page::Library => self.open_library(),Page::Memory => self.open_memory(),Page::Settings => self.edit_bot(),}@@ -56,8 +60,9 @@ mod tests {#[test]fn shift_arrows_move_between_pages_and_stop_at_the_ends() {let key = |code| KeyEvent::new(code, KeyModifiers::SHIFT);- assert_eq!(Page::Details.step(key(KeyCode::Right)), Some(Page::Memory));- assert_eq!(Page::Memory.step(key(KeyCode::Left)), Some(Page::Details));+ assert_eq!(Page::Details.step(key(KeyCode::Right)), Some(Page::Library));+ assert_eq!(Page::Memory.step(key(KeyCode::Left)), Some(Page::Library));+ assert_eq!(Page::Library.step(key(KeyCode::Left)), Some(Page::Details));assert_eq!(Page::Settings.step(key(KeyCode::Right)), None);assert_eq!(Page::Details.step(key(KeyCode::Left)), None);assert_eq!(diff --git a/host/src/tui/manage/replies.rs b/host/src/tui/manage/replies.rsindex 19060db8..83c0e90b 100644--- a/host/src/tui/manage/replies.rs+++ b/host/src/tui/manage/replies.rs@@ -85,6 +85,7 @@ impl App {self.sheet("routines", json!({"botId": bot}), Reply::Routines(bot.clone()));}}+ Reply::Library(bot) => self.library_loaded(&bot, v["items"].as_array().map_or(&[], Vec::as_slice)),Reply::RoutineSaved => {if let Some(i) = self.overlays.iter().rposition(|o| matches!(o, Overlay::Routine(_))) {self.overlays.truncate(i);@@ -249,6 +250,16 @@ impl App {}}}+ Reply::Library(bot) => {+ for o in &mut self.overlays {+ if let Overlay::Library(l) = o+ && l.bot == *bot+ {+ l.items.get_or_insert_with(Vec::new);+ }+ }+ self.flash(&e);+ }Reply::Memory(_) | Reply::MemorySaved(_) | Reply::MemoryFile(_) | Reply::Routines(_) => {for o in &mut self.overlays {match o {@@ -282,6 +293,9 @@ impl App {Overlay::Routines(l) => {calls.push(("routines", json!({"botId": l.bot}), After::Sheet(Reply::Routines(l.bot.clone()))));}+ Overlay::Library(l) => {+ calls.push(("library", json!({"botId": l.bot}), After::Sheet(Reply::Library(l.bot.clone()))));+ }Overlay::Market(_) | Overlay::Form(_) => {calls.push(("connectors", json!({}), After::Connectors));calls.push(("skills", json!({}), After::Skills));diff --git a/host/src/tui/net.rs b/host/src/tui/net.rsindex 89f3f9e2..bd768296 100644--- a/host/src/tui/net.rs+++ b/host/src/tui/net.rs@@ -1,5 +1,6 @@//! Host API over HTTP: JSON commands and the SSE event stream (same wire as the apps).+pub mod artifacts;pub mod files;use futures::StreamExt;diff --git a/host/src/tui/net/artifacts.rs b/host/src/tui/net/artifacts.rsnew file mode 100644index 00000000..5c80797a--- /dev/null+++ b/host/src/tui/net/artifacts.rs@@ -0,0 +1,172 @@+//! A bot's artifact (`docs/features/artifacts.md`): its HTML read from the host (`readArtifact`), then saved to+//! Downloads or opened in this computer's browser. Progress and the outcome come as `Msg::FileDownload`.++use super::Client;+use super::files::{Download, Partial, decode_chunk, downloads, place};+use crate::chat::artifacts::MAX_ARTIFACT;+use crate::chat::files::digest_hex;+use crate::tui::app::Msg;+use anyhow::{Result, anyhow, ensure};+use serde_json::json;+use sha2::{Digest as _, Sha256};+use std::path::{Path, PathBuf};+use tokio::io::AsyncWriteExt as _;+use tokio::sync::mpsc::UnboundedSender;++/// Where an artifact's HTML goes.+#[derive(Clone, Copy, PartialEq, Eq, Debug)]+pub enum ArtifactTo {+ Downloads,+ Browser,+}++impl Client {+ pub fn fetch_artifact(&self, bot: String, artifact: String, to: ArtifactTo, tx: UnboundedSender<Msg>) -> Download {+ let (client, progress) = (self.clone(), tx.clone());+ Download::spawn(tx, move |id| async move { deliver(&client, &bot, &artifact, to, &id, &progress).await })+ }+}++async fn deliver(+ client: &Client,+ bot: &str,+ artifact: &str,+ to: ArtifactTo,+ id: &str,+ tx: &UnboundedSender<Msg>,+) -> Result<String> {+ let (title, html) = read(client, bot, artifact, id, tx).await?;+ let name = file_name(&title);+ match to {+ ArtifactTo::Downloads => {+ let dir = downloads()?;+ 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?;+ file.write_all(&html).await?;+ file.sync_all().await?;+ drop(file);+ Ok(format!("Saved {}", place(&partial, &dir, &name).await?.display()))+ }+ ArtifactTo::Browser => {+ let temp = std::env::temp_dir().join("codync-artifacts");+ let id = id.to_owned();+ let (path, opened) = tokio::task::spawn_blocking(move || -> Result<(PathBuf, bool)> {+ let path = write_temp(&temp, &name, &id, &html)?;+ let opened = crate::tui::manage::open_here(path.as_os_str());+ Ok((path, opened))+ })+ .await??;+ Ok(if opened {+ format!("Opened {title} in the browser")+ } else {+ format!("No browser to open it: saved {}", path.display())+ })+ }+ }+}++/// The artifact's title and whole HTML, checked against its size and SHA-256.+async fn read(+ client: &Client,+ bot: &str,+ artifact: &str,+ id: &str,+ tx: &UnboundedSender<Msg>,+) -> Result<(String, Vec<u8>)> {+ let mut html: Vec<u8> = Vec::new();+ // The size and hash of the version being read: a publish meanwhile changes them.+ let mut version: Option<(u64, String)> = None;+ loop {+ let offset = html.len() as u64;+ let body = json!({"botId": bot, "artifactId": artifact, "offset": offset});+ let response = client.call("readArtifact", &body).await.map_err(|e| anyhow!(e))?;+ let size = response["size"].as_u64().ok_or_else(|| anyhow!("invalid artifact"))?;+ let sha = response["artifact"]["sha256"].as_str().unwrap_or_default().to_owned();+ ensure!(size <= MAX_ARTIFACT && sha.len() == 64, "invalid artifact");+ let (want_size, want_sha) = version.get_or_insert_with(|| (size, sha.clone()));+ ensure!(*want_size == size && *want_sha == sha, "the artifact changed while loading; try again");+ html.extend_from_slice(&decode_chunk(&response, size, offset)?);+ let title = response["artifact"]["title"].as_str().unwrap_or_default();+ if html.len() as u64 == size {+ ensure!(digest_hex(&Sha256::digest(&html)) == sha, "artifact integrity check failed; try again");+ return Ok((title.to_owned(), html));+ }+ let status = Ok(format!("Loading {title}: {}/{size} bytes · f cancels", html.len()));+ let _ = tx.send(Msg::FileDownload { id: id.to_owned(), status, done: false });+ }+}++/// Blocking: writes `html` as `dir/name`, replacing the copy an earlier `o` left.+fn write_temp(dir: &Path, name: &str, id: &str, html: &[u8]) -> Result<PathBuf> {+ private_dir(dir)?;+ let partial = Partial(dir.join(format!(".{id}.partial")));+ std::fs::write(&partial.0, html)?;+ let path = dir.join(name);+ // A rename replaces whatever is there (even a link) instead of writing through it.+ std::fs::rename(&partial.0, &path)?;+ Ok(path)+}++/// Makes `dir`, which only its owner writes in. On Unix the temp folder may be shared: a link, or a+/// folder others may write in, is refused, so no one can swap the artifact before the browser reads it+/// (one only someone else may write in fails the write). The desktop app's copy (0755) is fine.+fn private_dir(dir: &Path) -> Result<()> {+ #[cfg(unix)]+ {+ use std::os::unix::fs::{DirBuilderExt as _, PermissionsExt as _};+ match std::fs::DirBuilder::new().mode(0o700).create(dir) {+ Err(error) if error.kind() != std::io::ErrorKind::AlreadyExists => return Err(error.into()),+ _ => {}+ }+ let meta = std::fs::symlink_metadata(dir)?;+ let writable_by_others = meta.permissions().mode() & 0o022;+ ensure!(meta.is_dir() && writable_by_others == 0, "{} isn't a private folder", dir.display());+ }+ #[cfg(not(unix))]+ std::fs::create_dir_all(dir)?;+ Ok(())+}++/// `<title>.html` as a file name on every system: no path separators or characters Windows refuses,+/// no leading dot (a hidden file).+pub fn file_name(title: &str) -> String {+ const UNSAFE: [char; 9] = ['/', '\\', ':', '*', '?', '"', '<', '>', '|'];+ let safe: String = title.chars().map(|c| if c.is_control() || UNSAFE.contains(&c) { ' ' } else { c }).collect();+ let safe = safe.split_whitespace().collect::<Vec<_>>().join(" ");+ let safe = safe.trim_matches(|c: char| c == '.' || c == ' ');+ format!("{}.html", if safe.is_empty() { "Artifact" } else { safe })+}++#[cfg(test)]+mod tests {+ use super::*;++ #[test]+ fn artifact_file_names_stay_one_plain_file() {+ assert_eq!(file_name("Weekly report"), "Weekly report.html");+ assert_eq!(file_name("Q3: revenue / costs"), "Q3 revenue costs.html");+ assert_eq!(file_name("../../etc/passwd"), "etc passwd.html");+ assert_eq!(file_name(".hidden."), "hidden.html");+ assert_eq!(file_name("a\nb\tc"), "a b c.html");+ assert_eq!(file_name(" ?* "), "Artifact.html");+ assert_eq!(file_name("報告:第一週"), "報告:第一週.html", "only ASCII separators are unsafe");+ }++ #[cfg(unix)]+ #[test]+ fn temp_copies_replace_the_last_one_where_only_the_owner_writes() {+ use std::os::unix::fs::PermissionsExt as _;+ let root = std::env::temp_dir().join(format!("codync-artifacts-test-{}", uuid::Uuid::new_v4()));+ std::fs::create_dir(&root).expect("test folder");+ let dir = root.join("codync-artifacts");+ let first = write_temp(&dir, "A.html", "1", b"one").expect("first copy");+ assert_eq!(write_temp(&dir, "A.html", "2", b"two").expect("second copy"), first);+ assert_eq!(std::fs::read(&first).expect("copy"), b"two");+ assert_eq!(std::fs::read_dir(&dir).expect("folder").count(), 1, "no partial left behind");+ std::fs::set_permissions(&dir, std::fs::Permissions::from_mode(0o755)).expect("chmod");+ assert!(write_temp(&dir, "A.html", "3", b"three").is_ok(), "a folder others only read is fine");+ std::fs::set_permissions(&dir, std::fs::Permissions::from_mode(0o777)).expect("chmod");+ assert!(write_temp(&dir, "A.html", "4", b"four").is_err(), "a folder others write in is refused");+ std::fs::remove_dir_all(&root).expect("cleanup");+ }+}diff --git a/host/src/tui/net/files.rs b/host/src/tui/net/files.rsindex a9ae4c42..395a3524 100644--- a/host/src/tui/net/files.rs+++ b/host/src/tui/net/files.rs@@ -4,7 +4,7 @@ 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 serde_json::{Value, json};use sha2::{Digest as _, Sha256};use std::path::PathBuf;use std::sync::Arc;@@ -20,7 +20,27 @@ impl Drop for Download {self.cancel.notify_one();}}-struct Partial(PathBuf);+impl Download {+ /// Runs `work` (handed this download's id) until it ends or the download is dropped; its outcome is the last+ /// `Msg::FileDownload`.+ pub(super) fn spawn<F>(tx: UnboundedSender<Msg>, work: impl FnOnce(String) -> F) -> Self+ where+ F: Future<Output = Result<String>> + Send + 'static,+ {+ let id = uuid::Uuid::new_v4().to_string();+ let cancel = Arc::new(Notify::new());+ let (work, task) = (work(id.clone()), Self { id: id.clone(), cancel: cancel.clone() });+ tokio::spawn(async move {+ let done = tokio::select! {+ () = cancel.notified() => return,+ result = work => result,+ };+ let _ = tx.send(Msg::FileDownload { id, status: done.map_err(|error| format!("{error:#}")), done: true });+ });+ task+ }+}+pub(super) struct Partial(pub(super) PathBuf);impl Drop for Partial {fn drop(&mut self) {let _ = std::fs::remove_file(&self.0);@@ -29,19 +49,11 @@ impl Drop for Partial {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+ let (client, progress) = (self.clone(), tx.clone());+ Download::spawn(tx, move |id| async move {+ let path = save(&client, &entry, &file, &id, &progress).await?;+ Ok(format!("Saved {}", path.display()))+ })}}@@ -51,7 +63,7 @@ async fn save(client: &Client, entry: &str, meta: &SharedFile, id: &str, tx: &Unmeta.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 dir = downloads()?;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;@@ -60,13 +72,7 @@ async fn save(client: &Client, entry: &str, meta: &SharedFile, id: &str, tx: &Unlet 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"- );+ let data = decode_chunk(&response, meta.size, offset)?;file.write_all(&data).await?;hash.update(&data);offset += data.len() as u64;@@ -83,9 +89,29 @@ async fn save(client: &Client, entry: &str, meta: &SharedFile, id: &str, tx: &Unensure!(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.+ place(&partial, &dir, &meta.name).await+}++/// One `readFile` or `readArtifact` chunk of a `size`-byte file: exactly the bytes from `offset` on.+pub(super) fn decode_chunk(response: &Value, size: u64, offset: u64) -> Result<Vec<u8>> {+ let encoded = response["data"].as_str().ok_or_else(|| anyhow!("invalid chunk"))?;+ ensure!(encoded.len() <= CHUNK_SIZE / 3 * 4, "chunk too large");+ let data = base64::engine::general_purpose::STANDARD.decode(encoded)?;+ ensure!(+ data.len() as u64 == (size - offset).min(CHUNK_SIZE as u64),+ "download truncated or changed; press f to retry"+ );+ Ok(data)+}++pub(super) fn downloads() -> Result<PathBuf> {+ dirs::download_dir().or_else(dirs::home_dir).ok_or_else(|| anyhow!("No Downloads folder"))+}++/// Links a complete file in `dir` as `name` (or `name (2)`…), never replacing one created meanwhile.+pub(super) async fn place(partial: &Partial, dir: &std::path::Path, name: &str) -> Result<PathBuf> {for _ in 0..10_000 {- let path = super::free_path(&dir, &meta.name);+ let path = super::free_path(dir, name);match tokio::fs::hard_link(&partial.0, &path).await {Ok(()) => return Ok(path),Err(error) if error.kind() == std::io::ErrorKind::AlreadyExists => {}diff --git a/host/src/tui/sheets.rs b/host/src/tui/sheets.rsindex 922fbde7..6700cb71 100644--- a/host/src/tui/sheets.rs+++ b/host/src/tui/sheets.rs@@ -10,7 +10,9 @@ use ratatui::style::{Modifier, Style};use crate::tui::l10n::tr;use serde_json::Value;+mod library_view;mod memory_view;+pub use library_view::draw as library;pub use memory_view::draw as memory;use super::app::{App, Editor};diff --git a/host/src/tui/sheets/library_view.rs b/host/src/tui/sheets/library_view.rsnew file mode 100644index 00000000..da82ca45--- /dev/null+++ b/host/src/tui/sheets/library_view.rs@@ -0,0 +1,102 @@+//! A bot's Library tab: its artifacts and the files shared in its chat, newest first, under Today /+//! Yesterday / This week / Earlier.++use super::{App, Buffer, Rect, centered, footer, frame_box, name_of, page_tabs, put, row, rput, theme, u, window};+use crate::tui::l10n::tr;+use crate::tui::manage::{Library, LibraryItem, Page};+use crate::tui::md::truncate;+use crate::tui::view::{file_size, when};+use chrono::TimeZone as _;++pub fn draw(buf: &mut Buffer, area: Rect, app: &App, l: &Library) {+ let t = theme();+ let r = centered(area, 90, 28);+ let title = name_of(app, &l.bot);+ let inner = frame_box(buf, r, t.text, t.panel, Some((&title, t.text)));+ let inner = page_tabs(buf, inner, Page::Library);+ match l.items.as_deref() {+ None => {+ put(buf, inner.x, inner.y, inner.width, &tr("Loading…"), t.dim.patch(t.panel));+ }+ Some([]) => {+ put(buf, inner.x, inner.y, inner.width, &tr("Library is empty"), t.bold.patch(t.panel));+ let note = format!("Artifacts {title} makes and files shared in this chat show here.");+ put(buf, inner.x, inner.y + 1, inner.width, &tr(¬e), t.secondary.patch(t.panel));+ }+ Some(items) => {+ let now = crate::store::now_ms();+ // Rows and the headings between them: `None` is a heading.+ let mut lines: Vec<(Option<usize>, &str)> = vec![];+ for (i, item) in items.iter().enumerate() {+ let heading = section(item.at(), now);+ if lines.last().is_none_or(|(_, h)| *h != heading) {+ lines.push((None, heading));+ }+ lines.push((Some(i), heading));+ }+ let at = lines.iter().position(|(i, _)| *i == Some(l.cursor)).unwrap_or(0);+ let h = usize::from(inner.height.saturating_sub(3));+ let room = usize::from(inner.width.saturating_sub(10));+ for (y, (i, heading)) in (inner.y..).zip(lines.iter().skip(window(at, h)).take(h)) {+ let Some(i) = *i else {+ put(buf, inner.x, y, inner.width, &tr(heading), t.dim.patch(t.panel));+ continue;+ };+ let item = &items[i];+ let base = row(buf, inner, y, i == l.cursor);+ put(buf, inner.x, y, u(room) + 2, &truncate(&label(item), room + 2), t.text.patch(base));+ rput(buf, inner.right(), y, &when(item.at()), t.dim.patch(base));+ }+ }+ }+ footer(buf, inner, None, "↵ open an artifact in the browser · f save to Downloads · r rename · esc");+}++/// A row as the chat shows it: `▤ <title>` for an artifact, `▤ name · size` for a file.+fn label(item: &LibraryItem) -> String {+ match item {+ LibraryItem::Artifact(a) => format!("▤ {}", a.title),+ LibraryItem::File { file, .. } => format!("▤ {} · {}", file.name, file_size(file.size)),+ LibraryItem::Attachment { name, size, .. } => format!("▤ {name} · {}", file_size(*size)),+ }+}++/// Today / Yesterday / This week / Earlier: the local day it was published or shared, from `now`.+fn section(at: i64, now: i64) -> &'static str {+ let day = |ms: i64| chrono::Local.timestamp_millis_opt(ms).single().map(|t| t.date_naive());+ match day(now).zip(day(at)).map(|(today, d)| (today - d).num_days()) {+ Some(..=0) => "Today",+ Some(1) => "Yesterday",+ Some(2..=6) => "This week",+ _ => "Earlier",+ }+}++#[cfg(test)]+mod tests {+ use super::*;++ #[test]+ fn rows_group_by_the_local_day() {+ let noon = |days_back: u64| {+ let date = chrono::NaiveDate::from_ymd_opt(2026, 10, 24).expect("a date") - chrono::Days::new(days_back);+ let time = date.and_hms_opt(12, 0, 0).expect("noon");+ chrono::Local.from_local_datetime(&time).earliest().expect("noon exists").timestamp_millis()+ };+ let now = noon(0);+ assert_eq!(section(now - 3_600_000, now), "Today");+ assert_eq!(section(noon(1), now), "Yesterday");+ assert_eq!(section(noon(6), now), "This week");+ assert_eq!(section(noon(7), now), "Earlier");+ assert_eq!(section(0, now), "Earlier");+ }++ #[test]+ fn rows_read_like_the_chat() {+ let attachment = LibraryItem::Attachment { id: "u".into(), name: "a.png".into(), size: 2048, at: 0 };+ assert_eq!(label(&attachment), "▤ a.png · 2 KB");+ let file =+ crate::chat::files::SharedFile { id: "f".into(), name: "b.csv".into(), size: 9, sha256: String::new() };+ assert_eq!(label(&LibraryItem::File { entry: "e".into(), file, at: 0 }), "▤ b.csv · 9 B");+ }+}diff --git a/host/src/tui/view/chat.rs b/host/src/tui/view/chat.rsindex 432eb047..25ef56d6 100644--- a/host/src/tui/view/chat.rs+++ b/host/src/tui/view/chat.rs@@ -125,8 +125,14 @@ pub(super) fn chat(buf: &mut Buffer, r: Rect, app: &mut App, narrow: bool) {let mut used = clines.get(first).map_or(0, |l| w(l));if draft.text.is_empty() {// The apps' wording.- let placeholder = if app.pick.is_some() {- "j k pick · ↵ reply · 1–6 react · f save files · c copy · esc".to_owned()+ let placeholder = if let Some(pick) = &app.pick {+ let artifact = app.lane(&b.id).iter().any(|e| &e.id == pick && e.artifact().is_some());+ if artifact {+ "j k pick · o open in the browser · f save as HTML · ↵ reply · 1–6 react · c copy · esc"+ } else {+ "j k pick · ↵ reply · 1–6 react · f save files · c copy · esc"+ }+ .to_owned()} else if app.reply.is_some() {tr("Reply…").into_owned()} else if b.group {diff --git a/host/src/tui/view/help.rs b/host/src/tui/view/help.rsindex 094bf128..6d65a694 100644--- a/host/src/tui/view/help.rs+++ b/host/src/tui/view/help.rs@@ -10,7 +10,7 @@ use super::buffer::{centered, frame_box, put, u};use super::overlay::field_line;use super::style::theme;-const HELP: [(&str, &str, &str); 64] = [+const HELP: [(&str, &str, &str); 66] = [("MOVE", "j k ↑ ↓", "next / previous bot"),("MOVE", "[ ]", "previous / next bot"),("MOVE", "1…9", "jump to bot 1–9"),@@ -35,7 +35,8 @@ const HELP: [(&str, &str, &str); 64] = [("CHAT", "v", "pick a message"),("CHAT", "j k ↵", "picking: move / reply"),("CHAT", "1…6", "picking: react"),- ("CHAT", "f", "picking: save its files"),+ ("CHAT", "f", "picking: save its files or artifact"),+ ("CHAT", "o", "picking an artifact: open it in the browser"),("CHAT", "o", "picking: show a summary, handoff or note change"),("CHAT", "e K", "picking a handoff: edit / keep the chat"),("CHAT", "A", "picking a failure: add a fallback agent"),@@ -59,7 +60,8 @@ const HELP: [(&str, &str, &str); 64] = [("BOTS", "M", "memory"),("BOTS", "R", "details: routines, computer"),("BOTS", "B", "details: switch back to the bot's own agent"),- ("BOTS", "⇧← ⇧→", "between details, memory, settings"),+ ("BOTS", "L", "library: artifacts and files; open, save, rename"),+ ("BOTS", "⇧← ⇧→", "between details, library, memory, settings"),("BOTS", "A", "extensions, sign-in"),("BOTS", "x", "delete bot or group"),("VIEW", "t", "trace pane"),diff --git a/host/src/tui/view/mod.rs b/host/src/tui/view/mod.rsindex 01a4e4ca..327e3c87 100644--- a/host/src/tui/view/mod.rs+++ b/host/src/tui/view/mod.rs@@ -34,7 +34,7 @@ pub(super) use fallbacks::{chain_line, using_line};pub(super) use overlay::{field_line, input_line};pub(super) use style::theme;pub(super) use time::when;-pub(super) use transcript::unfoldable;+pub(super) use transcript::{file_size, unfoldable};pub(super) use usage::when_future;use ratatui::Frame;diff --git a/host/src/tui/view/overlay.rs b/host/src/tui/view/overlay.rsindex 088a2afc..73725032 100644--- a/host/src/tui/view/overlay.rs+++ b/host/src/tui/view/overlay.rs@@ -131,6 +131,7 @@ pub(super) fn overlay(buf: &mut Buffer, area: Rect, app: &mut App, top: &OverlayOverlay::BotChat(c) => super::bot_chat::bot_chat(buf, area, app, c),Overlay::Routines(l) => super::super::sheets::routines(buf, area, app, l),Overlay::Routine(f) => super::super::sheets::routine(buf, area, f),+ Overlay::Library(l) => super::super::sheets::library(buf, area, app, l),Overlay::Market(m) => super::super::sheets::market(buf, area, app, m),Overlay::Agent(a) => super::super::sheets::agent(buf, area, app, a),Overlay::Fields(f) => super::super::sheets::fields(buf, area, f),diff --git a/host/src/tui/view/transcript.rs b/host/src/tui/view/transcript.rsindex 43dada9a..55c3ddcb 100644--- a/host/src/tui/view/transcript.rs+++ b/host/src/tui/view/transcript.rs@@ -189,7 +189,16 @@ fn entry_lines(out: &mut Built, app: &App, b: &Bot, e: &Entry, info: &HashMap<i6Span::styled(format!(" {name}"), name_style(color)),Span::styled(format!(" {}", clock(e.created_at)), t.dim),]));- if let Some(files) = e.data["files"].as_array().filter(|files| !files.is_empty()) {+ if let Some(title) = app.artifact_title(e) {+ out.lines.push(Line::from(Span::styled(+ format!(" ▤ Artifact: {}", truncate(&title, width.saturating_sub(10))),+ t.text,+ )));+ out.lines.push(Line::from(Span::styled(+ " Select this message, then o opens it in the browser · f saves it",+ t.dim,+ )));+ } else 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);@@ -357,7 +366,7 @@ pub(super) fn user_line(e: &Entry) -> String {[e.text(), files.as_str()].iter().filter(|s| !s.is_empty()).copied().collect::<Vec<_>>().join(" ")}-fn file_size(bytes: u64) -> String {+pub(in crate::tui) fn file_size(bytes: u64) -> String {match bytes {0..1024 => format!("{bytes} B"),1024..1_048_576 => format!("{} KB", bytes / 1024),@@ -372,144 +381,4 @@ fn quote_line(e: &Entry, width: usize) -> Option<Line<'static>> {}#[cfg(test)]-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"));- }-- fn app_with_bots() -> App {- let (tx, _) = tokio::sync::mpsc::unbounded_channel();- let mut app = App::new(super::super::super::net::Client::new("http://127.0.0.1:1", None), tx, String::new());- for (id, name) in [("a", "Egan"), ("b", "Owen")] {- app.on_msg(super::super::super::app::Msg::Event(- serde_json::json!({"type":"bot","bot":{"id":id,"name":name}}),- ));- }- app- }-- fn exchange_entry(status: &str) -> Entry {- Entry {- id: "n".into(),- seq: 1,- turn: 1,- kind: Kind::Notice,- created_at: 0,- data: serde_json::json!({- "text": "Messaged b: Please review the secret plan\nCompleted.", "style": "info", "status": status,- "heading": "Messaged b: Please review the secret plan",- "botMessage": {"sourceBotId": "a", "targetBotId": "b", "text": "Please review the secret plan"},- "sourceBotId": "a", "targetBotId": "b", "delegationId": "r",- }),- }- }-- #[test]- fn bot_message_is_one_line_with_a_click_and_marks_only_failure() {- let app = app_with_bots();- let bot = &app.bots["a"];- let render = |e: &Entry| {- let mut out = Built { lines: vec![], buttons: vec![], messages: vec![] };- entry_lines(&mut out, &app, bot, e, &HashMap::new(), 80);- out- };- let ok = render(&exchange_entry("completed"));- let text = ok.lines.iter().map(ToString::to_string).collect::<Vec<_>>().join("\n");- assert!(text.contains("Messaged") && text.contains("Owen"));- assert!(!text.contains("secret plan") && !text.contains("failed"));- assert!(matches!(ok.buttons.as_slice(), [(_, 3, _, Click::BotChat(id))] if id == "n"));- assert_eq!(ok.messages.len(), 1);- let mut failed = exchange_entry("failed");- failed.data["text"] = "Messaged b: Please review the secret plan\nRecipient stopped.".into();- let bad = render(&failed);- let line = bad.lines.last().unwrap();- assert!(line.to_string().ends_with("Owen · failed"));- assert_eq!(line.spans[0].style, theme().red);- }-- #[test]- fn memory_lines_and_kept_handoffs_stay_out_of_the_chat() {- let app = app_with_bots();- let mut line = exchange_entry("done");- line.data =- serde_json::json!({"text": "Remembered: likes tea", "memory": {"action": "remember", "status": "done"}});- let mut out = Built { lines: vec![], buttons: vec![], messages: vec![] };- entry_lines(&mut out, &app, &app.bots["a"], &line, &HashMap::new(), 80);- assert!(out.lines.is_empty() && out.messages.is_empty());- line.data = serde_json::json!({"text": "Kept this conversation.", "handoff": {"status": "kept"}});- entry_lines(&mut out, &app, &app.bots["a"], &line, &HashMap::new(), 80);- assert!(out.lines.is_empty(), "a kept handoff changed nothing");- line.data =- serde_json::json!({"text": "Earlier context was summarized to make room.", "compaction": {"byHost": true}});- entry_lines(&mut out, &app, &app.bots["a"], &line, &HashMap::new(), 80);- assert!(out.lines.is_empty(), "a summary keeps the same conversation going");- }-- #[test]- fn a_run_of_exchanges_is_one_counted_line() {- let app = app_with_bots();- let bot = &app.bots["a"];- let mut entries = vec![];- for (i, status) in ["completed", "failed", "completed"].into_iter().enumerate() {- let mut e = exchange_entry(status);- e.id = format!("n{i}");- e.seq = i64::try_from(i).unwrap_or(0) + 1;- entries.push(e);- }- let refs: Vec<&Entry> = entries.iter().collect();- let build = |refs: &[&Entry]| {- let mut out = Built { lines: vec![], buttons: vec![], messages: vec![] };- for item in group(&bot.id, refs) {- match item {- Item::Entry(e) => entry_lines(&mut out, &app, bot, e, &HashMap::new(), 80),- Item::Group(g) => {- let lead = format!("{} messages with ", g.count);- bot_message_line(&mut out, &app, g.first, &g.peer, &lead, g.failed, 0);- }- }- }- out- };- let out = build(&refs);- assert_eq!(out.lines.len(), 1);- let line = &out.lines[0];- assert!(line.to_string().contains("3 messages with") && line.to_string().ends_with("Owen · failed"), "{line}");- assert_eq!(line.spans[0].style, theme().red);- assert!(matches!(out.buttons.as_slice(), [(_, 3, _, Click::BotChat(id))] if id == "n0"));- assert_eq!(out.messages.len(), 1);- assert!(build(&refs[..1]).lines[0].to_string().contains("Messaged"));- }-- #[test]- fn a_reply_shows_the_message_it_answers() {- let app = app_with_bots();- let reply = Entry {- id: "u".into(),- seq: 2,- turn: 2,- kind: Kind::User,- created_at: 0,- data: serde_json::json!({"text": "why?", "replyTo": {"id": "e", "author": "a", "text": "## Plan\n- ready"}}),- };- let mut out = Built { lines: vec![], buttons: vec![], messages: vec![] };- entry_lines(&mut out, &app, &app.bots["a"], &reply, &HashMap::new(), 80);- let text: Vec<String> = out.lines.iter().map(ToString::to_string).collect();- assert_eq!(text[1], " ↳ “Plan”", "{text:?}");- assert!(text[2].contains("why?"));- }-}+mod tests;diff --git a/host/src/tui/view/transcript/tests.rs b/host/src/tui/view/transcript/tests.rsnew file mode 100644index 00000000..8f8945db--- /dev/null+++ b/host/src/tui/view/transcript/tests.rs@@ -0,0 +1,162 @@+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"));+}++#[tokio::test]+async fn an_artifact_card_is_one_line_with_its_newest_title() {+ use crate::tui::app::Msg;+ use serde_json::json;+ let mut app = app_with_bots();+ app.on_msg(Msg::Event(+ json!({"type":"entry", "entry":{"id":"card", "botId":"a", "seq":1, "kind":"agent", "turn":1,+ "data":{"author":"a", "text":"Artifact: Weekly report", "final":true,+ "artifact":{"id":"p", "title":"Weekly report", "updatedAt":1}}}}),+ ));+ let text = |app: &App| {+ let chat = build_chat(app, &app.bots["a"], 80);+ assert!(chat.messages.iter().any(|(id, _, _)| id == "card"), "a card can be picked");+ chat.lines.iter().map(ToString::to_string).collect::<Vec<_>>()+ };+ let lines = text(&app);+ assert!(lines.iter().any(|l| l == " ▤ Artifact: Weekly report"), "{lines:?}");+ assert!(lines.iter().any(|l| l.contains("o opens it in the browser · f saves it")));+ app.on_msg(Msg::Event(json!({"type":"artifact", "artifact":{"id":"p", "botId":"a", "title":"Q4 report", "size":1,+ "sha256":"0".repeat(64), "createdAt":0, "updatedAt":2}})));+ let lines = text(&app);+ assert!(lines.iter().any(|l| l == " ▤ Artifact: Q4 report"), "a rename shows: {lines:?}");+ assert!(!lines.iter().any(|l| l.contains("Weekly report")));+}++fn app_with_bots() -> App {+ let (tx, _) = tokio::sync::mpsc::unbounded_channel();+ let mut app = App::new(super::super::super::net::Client::new("http://127.0.0.1:1", None), tx, String::new());+ for (id, name) in [("a", "Egan"), ("b", "Owen")] {+ app.on_msg(super::super::super::app::Msg::Event(serde_json::json!({"type":"bot","bot":{"id":id,"name":name}})));+ }+ app+}++fn exchange_entry(status: &str) -> Entry {+ Entry {+ id: "n".into(),+ seq: 1,+ turn: 1,+ kind: Kind::Notice,+ created_at: 0,+ data: serde_json::json!({+ "text": "Messaged b: Please review the secret plan\nCompleted.", "style": "info", "status": status,+ "heading": "Messaged b: Please review the secret plan",+ "botMessage": {"sourceBotId": "a", "targetBotId": "b", "text": "Please review the secret plan"},+ "sourceBotId": "a", "targetBotId": "b", "delegationId": "r",+ }),+ }+}++#[test]+fn bot_message_is_one_line_with_a_click_and_marks_only_failure() {+ let app = app_with_bots();+ let bot = &app.bots["a"];+ let render = |e: &Entry| {+ let mut out = Built { lines: vec![], buttons: vec![], messages: vec![] };+ entry_lines(&mut out, &app, bot, e, &HashMap::new(), 80);+ out+ };+ let ok = render(&exchange_entry("completed"));+ let text = ok.lines.iter().map(ToString::to_string).collect::<Vec<_>>().join("\n");+ assert!(text.contains("Messaged") && text.contains("Owen"));+ assert!(!text.contains("secret plan") && !text.contains("failed"));+ assert!(matches!(ok.buttons.as_slice(), [(_, 3, _, Click::BotChat(id))] if id == "n"));+ assert_eq!(ok.messages.len(), 1);+ let mut failed = exchange_entry("failed");+ failed.data["text"] = "Messaged b: Please review the secret plan\nRecipient stopped.".into();+ let bad = render(&failed);+ let line = bad.lines.last().unwrap();+ assert!(line.to_string().ends_with("Owen · failed"));+ assert_eq!(line.spans[0].style, theme().red);+}++#[test]+fn memory_lines_and_kept_handoffs_stay_out_of_the_chat() {+ let app = app_with_bots();+ let mut line = exchange_entry("done");+ line.data =+ serde_json::json!({"text": "Remembered: likes tea", "memory": {"action": "remember", "status": "done"}});+ let mut out = Built { lines: vec![], buttons: vec![], messages: vec![] };+ entry_lines(&mut out, &app, &app.bots["a"], &line, &HashMap::new(), 80);+ assert!(out.lines.is_empty() && out.messages.is_empty());+ line.data = serde_json::json!({"text": "Kept this conversation.", "handoff": {"status": "kept"}});+ entry_lines(&mut out, &app, &app.bots["a"], &line, &HashMap::new(), 80);+ assert!(out.lines.is_empty(), "a kept handoff changed nothing");+ line.data =+ serde_json::json!({"text": "Earlier context was summarized to make room.", "compaction": {"byHost": true}});+ entry_lines(&mut out, &app, &app.bots["a"], &line, &HashMap::new(), 80);+ assert!(out.lines.is_empty(), "a summary keeps the same conversation going");+}++#[test]+fn a_run_of_exchanges_is_one_counted_line() {+ let app = app_with_bots();+ let bot = &app.bots["a"];+ let mut entries = vec![];+ for (i, status) in ["completed", "failed", "completed"].into_iter().enumerate() {+ let mut e = exchange_entry(status);+ e.id = format!("n{i}");+ e.seq = i64::try_from(i).unwrap_or(0) + 1;+ entries.push(e);+ }+ let refs: Vec<&Entry> = entries.iter().collect();+ let build = |refs: &[&Entry]| {+ let mut out = Built { lines: vec![], buttons: vec![], messages: vec![] };+ for item in group(&bot.id, refs) {+ match item {+ Item::Entry(e) => entry_lines(&mut out, &app, bot, e, &HashMap::new(), 80),+ Item::Group(g) => {+ let lead = format!("{} messages with ", g.count);+ bot_message_line(&mut out, &app, g.first, &g.peer, &lead, g.failed, 0);+ }+ }+ }+ out+ };+ let out = build(&refs);+ assert_eq!(out.lines.len(), 1);+ let line = &out.lines[0];+ assert!(line.to_string().contains("3 messages with") && line.to_string().ends_with("Owen · failed"), "{line}");+ assert_eq!(line.spans[0].style, theme().red);+ assert!(matches!(out.buttons.as_slice(), [(_, 3, _, Click::BotChat(id))] if id == "n0"));+ assert_eq!(out.messages.len(), 1);+ assert!(build(&refs[..1]).lines[0].to_string().contains("Messaged"));+}++#[test]+fn a_reply_shows_the_message_it_answers() {+ let app = app_with_bots();+ let reply = Entry {+ id: "u".into(),+ seq: 2,+ turn: 2,+ kind: Kind::User,+ created_at: 0,+ data: serde_json::json!({"text": "why?", "replyTo": {"id": "e", "author": "a", "text": "## Plan\n- ready"}}),+ };+ let mut out = Built { lines: vec![], buttons: vec![], messages: vec![] };+ entry_lines(&mut out, &app, &app.bots["a"], &reply, &HashMap::new(), 80);+ let text: Vec<String> = out.lines.iter().map(ToString::to_string).collect();+ assert_eq!(text[1], " ↳ “Plan”", "{text:?}");+ assert!(text[2].contains("why?"));+}diff --git a/host/tests/artifacts_e2e.rs b/host/tests/artifacts_e2e.rsnew file mode 100644index 00000000..32e416b2--- /dev/null+++ b/host/tests/artifacts_e2e.rs@@ -0,0 +1,189 @@+//! Artifacts through real ACP/MCP and the apps' API: publish, card, update in a reply to the card, read, rename, the live+//! `artifact` events, a routine's artifact (no card), the chat's Library, and what deleting the bot removes.++#![allow(clippy::unwrap_used, clippy::expect_used, clippy::panic)]++mod common;++use base64::Engine as _;+use common::host::Host;+use serde_json::{Value, json};+use std::path::{Path, PathBuf};+use std::time::Duration;+use tokio::sync::mpsc::UnboundedReceiver;++/// The bot's chat once its turn has ended with `Done.` and it holds `cards` artifact cards.+async fn cards(host: &Host, bot: &str, cards: usize) -> Vec<Value> {+ let waited = tokio::time::timeout(Duration::from_secs(30), async {+ loop {+ let entries = host.call("history", json!({"botId": bot})).await["entries"].as_array().unwrap().clone();+ let artifacts: Vec<Value> = entries.iter().filter(|e| e["data"]["artifact"].is_object()).cloned().collect();+ let done = entries.iter().filter(|e| e["data"]["text"] == "Done." && e["data"]["final"] == true).count();+ if artifacts.len() == cards && done == cards {+ return artifacts;+ }+ tokio::time::sleep(Duration::from_millis(50)).await;+ }+ })+ .await;+ waited.unwrap()+}++async fn html(host: &Host, bot: &str, artifact: &str) -> String {+ let read = host.call("readArtifact", json!({"botId": bot, "artifactId": artifact, "offset": 0})).await;+ let bytes = base64::engine::general_purpose::STANDARD.decode(read["data"].as_str().unwrap()).unwrap();+ assert_eq!(read["size"], bytes.len());+ String::from_utf8(bytes).unwrap()+}++fn results(cwd: &Path) -> Vec<Value> {+ serde_json::from_str(&std::fs::read_to_string(cwd.join("artifact-results.json")).unwrap()).unwrap()+}++/// The titles of the live `artifact` events, up to one titled `last`.+async fn artifact_titles(events: &mut UnboundedReceiver<Value>, last: &str) -> Vec<String> {+ let mut titles = vec![];+ let waited = tokio::time::timeout(Duration::from_secs(10), async {+ while let Some(event) = events.recv().await {+ if event["type"] == "artifact" {+ titles.push(event["artifact"]["title"].as_str().unwrap().to_owned());+ if titles.last().is_some_and(|t| t == last) {+ return;+ }+ }+ }+ })+ .await;+ waited.unwrap_or_else(|_| panic!("no artifact event titled {last:?}: {titles:?}"));+ titles+}++/// Waits until `ready` holds for the bot's Library, and returns it.+async fn library_until(host: &Host, bot: &str, ready: impl Fn(&[Value]) -> bool) -> Vec<Value> {+ let waited = tokio::time::timeout(Duration::from_secs(30), async {+ loop {+ let items = library(host, bot).await;+ if ready(&items) {+ return items;+ }+ tokio::time::sleep(Duration::from_millis(50)).await;+ }+ })+ .await;+ waited.unwrap()+}++#[tokio::test]+async fn bots_publish_update_and_the_apps_read_and_rename_artifacts() {+ let host = Host::start().await;+ let cwd = host.home.join("workspace");+ std::fs::create_dir_all(&cwd).unwrap();+ let agent = PathBuf::from(env!("CARGO_MANIFEST_DIR")).join("tests/fixtures/artifact_agent.py");+ let created = host.call("createBot", json!({"name":"Artifacts", "backend":"custom", "cwd":cwd, "command":common::python_agent(&agent), "connectors":[], "notify":false})).await;+ let bot = created["bot"]["id"].as_str().unwrap();+ let mut events = host.events().await;++ host.call("send", json!({"botId": bot, "text": "make-artifact"})).await;+ let card = cards(&host, bot, 1).await.remove(0);+ let made = results(&cwd);+ assert!(made[1]["isError"] == true, "a new artifact needs a title: {}", made[1]);+ let id = card["data"]["artifact"]["id"].as_str().unwrap();+ assert_eq!(card["data"]["artifact"]["title"], "Weekly report");+ assert_eq!(card["data"]["text"], "Artifact: Weekly report", "older apps show the text");+ let artifacts = library(&host, bot).await;+ assert_eq!(artifacts.len(), 1);+ assert_eq!(artifacts[0]["kind"], "artifact");+ assert_eq!(artifacts[0]["artifact"]["entryId"], card["id"], "messages about the artifact reply to its card");+ assert_eq!(html(&host, bot, id).await, "<h1>Weekly report</h1>");++ // A reply to the card tells the bot which artifact and where its HTML is; it updates that artifact.+ host.call("send", json!({"botId": bot, "text": "update-artifact", "replyTo": card["id"]})).await;+ let update = cards(&host, bot, 2).await.remove(1);+ let prompt = std::fs::read_to_string(cwd.join("last-prompt.txt")).unwrap();+ assert!(prompt.contains(&format!("this is about your artifact \"Weekly report\" (id {id})")), "{prompt}");+ assert_eq!(update["data"]["artifact"]["id"], id, "the same artifact, not a second one");+ assert_eq!(html(&host, bot, id).await, "<h1>Weekly report</h1><p>Updated</p>");+ let artifacts = library(&host, bot).await;+ assert_eq!(artifacts.len(), 1);+ assert_eq!(artifacts[0]["artifact"]["entryId"], update["id"]);++ let renamed = host.call("renameArtifact", json!({"botId": bot, "artifactId": id, "title": " Week 43 "})).await;+ assert_eq!(renamed["artifact"]["title"], "Week 43");+ let titles = artifact_titles(&mut events, "Week 43").await;+ assert_eq!(titles.first().map(String::as_str), Some("Weekly report"), "publishing tells the apps: {titles:?}");+ host.refused("renameArtifact", json!({"botId": bot, "artifactId": id, "title": " "})).await;+ let reply = host.call("send", json!({"botId": bot, "text": "thanks", "replyTo": card["id"]})).await;+ assert_eq!(+ reply["entry"]["data"]["replyTo"]["text"], "Artifact: Week 43",+ "a quote names the artifact as it's called now"+ );+ host.refused("readArtifact", json!({"botId": bot, "artifactId": id, "offset": 1_000_000})).await;+ host.refused("readArtifact", json!({"botId": bot, "artifactId": "../../token", "offset": 0})).await;+ host.refused("readArtifact", json!({"botId": "someone-else", "artifactId": id, "offset": 0})).await;++ // The user's attachments join the Library, newest first.+ let upload = uuid::Uuid::new_v4().to_string();+ let data = base64::engine::general_purpose::STANDARD.encode(b"plan");+ host.call(+ "upload",+ json!({"botId": bot, "uploadId": upload, "name": "plan.txt", "offset": 0, "data": data, "done": true}),+ )+ .await;+ host.call("send", json!({"botId": bot, "text": "", "attachments": [upload]})).await;+ let items = library(&host, bot).await;+ assert_eq!(items.len(), 2);+ assert_eq!((items[0]["kind"].as_str(), items[0]["file"]["name"].as_str()), (Some("attachment"), Some("plan.txt")));+ assert_eq!(items[1]["artifact"]["title"], "Week 43");++ // And the files the bot shares.+ host.call("send", json!({"botId": bot, "text": "share-file"})).await;+ let items = library_until(&host, bot, |items| items.len() == 3).await;+ assert_eq!((items[0]["kind"].as_str(), items[0]["file"]["name"].as_str()), (Some("file"), Some("notes.txt")));++ // A routine's artifact joins the Library without a card, and its answer says so.+ let routine =+ json!({"botId": bot, "name": "Report", "instruction": "make-artifact", "triggers": [{"type": "webhook"}]});+ let routine = host.call("saveRoutine", routine).await;+ host.call("runRoutine", json!({"botId": bot, "id": routine["routine"]["id"]})).await;+ let items = library_until(&host, bot, |items| items.iter().filter(|i| i["kind"] == "artifact").count() == 2).await;+ let made = items.iter().find(|i| i["artifact"]["title"] == "Weekly report").unwrap();+ assert!(made["artifact"]["entryId"].is_null(), "nothing to reply to: {made}");+ let answered = tokio::time::timeout(Duration::from_secs(30), async {+ loop {+ let made = std::fs::read_to_string(cwd.join("artifact-results.json")).ok();+ let answer = made+ .and_then(|made| serde_json::from_str::<Vec<Value>>(&made).ok())+ .and_then(|made| serde_json::from_str::<Value>(made.first()?["content"][0]["text"].as_str()?).ok());+ if let Some(answer) = answer.filter(|answer| answer["card"].is_string()) {+ return answer;+ }+ tokio::time::sleep(Duration::from_millis(50)).await;+ }+ })+ .await+ .unwrap();+ assert!(answered["card"].as_str().unwrap().starts_with("not posted"), "{answered}");+ let history = host.call("history", json!({"botId": bot})).await;+ let cards = history["entries"].as_array().unwrap().iter().filter(|e| e["data"]["artifact"].is_object()).count();+ assert_eq!(cards, 2, "the routine's artifact has no card");++ // Deleting the bot deletes its artifacts.+ host.call("deleteBot", json!({"botId": bot})).await;+ let folder = host.home.join("bots").join(bot).join("artifacts");+ tokio::time::timeout(Duration::from_secs(10), async {+ while folder.exists() {+ tokio::time::sleep(Duration::from_millis(50)).await;+ }+ })+ .await+ .expect("the artifacts folder goes");+ let db = rusqlite::Connection::open(host.home.join("codync.db")).unwrap();+ let rows: i64 = db+ .query_row("SELECT count(*) FROM kv WHERE k GLOB ?1", [format!("artifact.{bot}.*")], |row| row.get(0))+ .unwrap();+ assert_eq!(rows, 0, "nor do their details");+}++async fn library(host: &Host, bot: &str) -> Vec<Value> {+ host.call("library", json!({"botId": bot})).await["items"].as_array().unwrap().clone()+}diff --git a/host/tests/common/host.rs b/host/tests/common/host.rsindex cbdc1978..a99fb7fb 100644--- a/host/tests/common/host.rs+++ b/host/tests/common/host.rs@@ -74,6 +74,34 @@ impl Host {self.call("createBot", bot).await["bot"]["id"].as_str().unwrap().to_owned()}+ /// The event stream (its catch-up, then live events), each event as it arrives.+ pub async fn events(&self) -> tokio::sync::mpsc::UnboundedReceiver<Value> {+ use futures::StreamExt as _;+ let response = reqwest::Client::new()+ .get(format!("{}/events?client=test", self.base))+ .bearer_auth(&self.token)+ .send()+ .await+ .unwrap();+ let (tx, rx) = tokio::sync::mpsc::unbounded_channel();+ tokio::spawn(async move {+ let (mut body, mut buf) = (response.bytes_stream(), String::new());+ while let Some(Ok(chunk)) = body.next().await {+ buf.push_str(&String::from_utf8_lossy(&chunk));+ while let Some(i) = buf.find('\n') {+ let line: String = buf.drain(..=i).collect();+ if let Some(data) = line.trim_end().strip_prefix("data:")+ && let Ok(event) = serde_json::from_str(data.trim_start())+ && tx.send(event).is_err()+ {+ return;+ }+ }+ }+ });+ rx+ }+/// What a client holds after catching up (see `common::snapshot`).pub async fn snapshot(&self) -> Value {super::snapshot(&self.base, &self.token).awaitdiff --git a/host/tests/fixtures/artifact_agent.py b/host/tests/fixtures/artifact_agent.pynew file mode 100644index 00000000..255982e0--- /dev/null+++ b/host/tests/fixtures/artifact_agent.py@@ -0,0 +1,64 @@+"""ACP fixture publishing artifacts through the real built-in stdio chat MCP."""+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']]+ cwd = Path(session['cwd'])+ text = params['prompt'][0]['text']+ (cwd / 'last-prompt.txt').write_text(text)+ 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':'artifact-test','version':'1'}})+ names = [tool['name'] for tool in request('tools/list', {})['tools']]+ assert 'publish_artifact' in names and 'list_artifacts' in names+ def call(name, arguments):+ return request('tools/call', {'name':name, 'arguments':arguments})+ results = []+ if 'make-artifact' in text:+ (cwd / 'report.html').write_text('<h1>Weekly report</h1>')+ results.append(call('publish_artifact', {'path':'report.html', 'title':'Weekly report'}))+ results.append(call('publish_artifact', {'path':'report.html'}))+ elif 'update-artifact' in text:+ artifact = json.loads(call('list_artifacts', {})['content'][0]['text'])['artifacts'][0]+ html = Path(artifact['path']).read_text() + '<p>Updated</p>'+ (cwd / 'report.html').write_text(html)+ results.append(call('publish_artifact', {'path':'report.html', 'artifact':artifact['id']}))+ elif 'share-file' in text:+ (cwd / 'notes.txt').write_text('notes')+ results.append(call('send_file', {'path':'notes.txt'}))+ (cwd / 'artifact-results.json').write_text(json.dumps(results))+ mcp.stdin.close()+ send({'jsonrpc':'2.0','method':'session/update','params':{'sessionId':params['sessionId'],'update':{'sessionUpdate':'agent_message_chunk','content':{'type':'text','text':'Done.'}}}})+ 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', 'artifact-test-' + str(len(sessions)))+ sessions[session_id] = message['params']+ result = {'sessionId':session_id}+ elif method == 'session/prompt':+ result = prompt(message)+ else:+ continue+ send({'jsonrpc':'2.0','id':message['id'],'result':result})