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
fix: artifact changes reach every device and artifacts open only what you click
leepokai2daa2a9a2df6
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 03da3db3..b2aac51c 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@@ -149,7 +149,7 @@ 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. */+ /** An artifact was published, updated or renamed (the catch-up replays it too), never a checkpoint. */data class ArtifactChanged(val artifact: Artifact) : MirrorEventdata object Resync : MirrorEventdata object Ignored : MirrorEvent@@ -163,7 +163,7 @@ 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.+ // One this app can't read is passed over rather than fetching everything again: a card or the Library reads it again."artifact" -> runCatching { ArtifactChanged(Artifact.decode(value.getValue("artifact"))) }.getOrDefault(Ignored)"resync" -> Resync// Match the existing clients: unknown events do not advance the cursor.diff --git a/apps/desktop/src/main/artifacts.ts b/apps/desktop/src/main/artifacts.tsindex 9dc6076e..400d7733 100644--- a/apps/desktop/src/main/artifacts.ts+++ b/apps/desktop/src/main/artifacts.ts@@ -1,23 +1,23 @@import { mkdir, writeFile } from 'node:fs/promises'import { join } from 'node:path'-import { app, ipcMain, protocol, shell, type WebContents } from 'electron'+import { app, ipcMain, protocol, shell, webFrameMain, type WebContents, type WebFrameMain } from 'electron'+import { ARTIFACT_SCHEME, followsUser, isArtifactURL, isArtifactViewer } from '../shared/artifacts'/*** 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 = 50const shown = new Map<string, Uint8Array>()/** Before the app is ready. */export function registerArtifactScheme() {- protocol.registerSchemesAsPrivileged([{ scheme: SCHEME, privileges: { standard: true, secure: true } }])+ protocol.registerSchemesAsPrivileged([{ scheme: ARTIFACT_SCHEME, privileges: { standard: true, secure: true } }])}export function registerArtifacts() {- protocol.handle(SCHEME, (request) => {+ protocol.handle(ARTIFACT_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' } })@@ -44,16 +44,53 @@ 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). */+/**+ * An artifact stays in its frame (frames inside it go where they go). What it opens goes to the browser only when the+ * user just clicked or pressed Return/Space in the window, after its viewer loaded, one link per press: a card opens+ * nothing, and neither does a script sending the artifact or a new window elsewhere on its own. The window's input+ * comes from here, not the page, so an artifact can't fake it. Electron reports no touchscreen tap in an artifact's+ * frame here, so a tapped link opens nothing.+ */export function keepArtifactsInFrame(contents: WebContents) {+ let input = 0+ let loaded = 0+ contents.on('before-mouse-event', (_e, mouse) => {+ if (mouse.type === 'mouseUp') input = Date.now()+ })+ contents.on('before-input-event', (_e, key) => {+ if (key.type === 'keyDown' && (key.key === 'Enter' || key.key === ' ')) input = Date.now()+ })+ // At commit, before the viewer's scripts run: the click that opened it doesn't count for what they open.+ contents.on('did-frame-navigate', (_e, _url, _code, _status, _isMainFrame, processId, routingId) => {+ if (isViewer(webFrameMain.fromId(processId, routingId))) loaded = Date.now()+ })+ const follow = (url: string) => {+ if (!followsUser(input, loaded, Date.now())) return+ input = 0+ openWebLink(url)+ }contents.on('will-frame-navigate', (event) => {- if (!event.frame?.url.startsWith(`${SCHEME}:`) || event.url.startsWith(`${SCHEME}:`)) return+ const { frame } = event+ if (!isArtifactURL(frame?.url)) return+ if (isArtifactURL(event.url)) {+ // A card can't make itself a viewer.+ if (!isArtifactViewer(frame.url) && isArtifactViewer(event.url)) event.preventDefault()+ return+ }event.preventDefault()- openWebLink(event.url)+ if (isViewer(frame)) follow(event.url)+ })+ // A new window: an artifact's target=_blank link or window.open (the app opens its own links through `app:openExternal`).+ contents.setWindowOpenHandler(({ url }) => {+ follow(url)+ return { action: 'deny' }})}+/** The viewer: an artifact frame in the chat window's own page (one inside an artifact never is), not a card's. */+const isViewer = (frame: WebFrameMain | null | undefined) => frame?.parent?.parent === null && isArtifactViewer(frame.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) {+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 b4a41c0b..e56c1545 100644--- a/apps/desktop/src/main/index.ts+++ b/apps/desktop/src/main/index.ts@@ -7,7 +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 { keepArtifactsInFrame, registerArtifacts, registerArtifactScheme } from './artifacts'import { registerHostProxy } from './host-proxy'import { readClipboardFiles, readFiles } from './files'import { Tray } from './tray'@@ -88,11 +88,6 @@ function openChat() {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 }) => {- openWebLink(url)- return { action: 'deny' }- })void chat.loadURL(rendererURL('chat'))return chat}diff --git a/apps/desktop/src/renderer/client/host-client.ts b/apps/desktop/src/renderer/client/host-client.tsindex 4a403e1e..fb1b471b 100644--- a/apps/desktop/src/renderer/client/host-client.ts+++ b/apps/desktop/src/renderer/client/host-client.ts@@ -67,7 +67,7 @@ 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). */+ /** An artifact was published, updated or renamed (the catch-up replays it too). */| { type: 'artifact'; artifact: Artifact }| { type: 'screen'; screen: ScreenState }| { type: 'accessRequests'; requests: AccessRequest[] }diff --git a/apps/desktop/src/renderer/views/library/ArtifactParts.tsx b/apps/desktop/src/renderer/views/library/ArtifactParts.tsxindex 5de852e3..8454105a 100644--- a/apps/desktop/src/renderer/views/library/ArtifactParts.tsx+++ b/apps/desktop/src/renderer/views/library/ArtifactParts.tsx@@ -1,5 +1,5 @@import { useEffect, useRef, useState } from 'react'-import type { Artifact } from '@shared/artifacts'+import { artifactFrameURL, type Artifact } from '@shared/artifacts'import type { MenuItem } from '../../components/Overlay'import type { BotStore } from '../../store/bot-store'import type { ArtifactHTML } from '../../store/artifacts'@@ -23,10 +23,10 @@ export function ArtifactFrame({ id, html, title, preview = false }: { id: stringreturn (<iframeclassName={preview ? 'artifact-frame preview' : 'artifact-frame'}- src={`codync-artifact://${id}/?v=${shown}`}+ src={artifactFrameURL(id, shown, preview)}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"+ // Its own origin already keeps it from the app; same-origin lets the artifact keep its own storage. A card opens nothing.+ sandbox={preview ? 'allow-scripts allow-same-origin' : '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"diff --git a/apps/desktop/src/shared/artifacts.test.ts b/apps/desktop/src/shared/artifacts.test.tsindex f3970807..7d375565 100644--- a/apps/desktop/src/shared/artifacts.test.ts+++ b/apps/desktop/src/shared/artifacts.test.ts@@ -1,7 +1,7 @@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 { artifactFrameURL, artifactQuote, followsUser, hasLibrary, isArtifactURL, isArtifactViewer, readArtifactHTML, type Artifact } from './artifacts.ts'import { FILE_CHUNK_SIZE } from './files.ts'function version(text: string, updatedAt: number) {@@ -46,3 +46,18 @@ test('the Library needs a host that has it, and only a card takes messages aboutassert.equal(artifactQuote(artifact), null, 'a routine published it')assert.deepEqual(artifactQuote({ ...artifact, entryId: 'e' }), { id: 'e', author: 'b', text: 'Artifact: Report', artifact: 'a' })})++test('an artifact opens only what the user just followed in its viewer', () => {+ const viewer = artifactFrameURL('a1', 5, false)+ const card = artifactFrameURL('a1', 5, true)+ assert.equal(isArtifactURL(card), true)+ assert.equal(isArtifactURL('https://example.com/'), false)+ assert.equal(isArtifactViewer(viewer), true)+ assert.equal(isArtifactViewer(card), false, 'a card opens nothing')+ assert.equal(isArtifactViewer('https://example.com/'), false)+ assert.equal(isArtifactViewer(undefined), false)+ assert.equal(followsUser(1_500, 1_000, 1_600), true, 'a click after the viewer loaded')+ assert.equal(followsUser(900, 1_000, 1_100), false, 'a redirect on load right after the click that opened the viewer')+ assert.equal(followsUser(1_500, 1_000, 3_000), false, 'a script acting long after the last click')+ assert.equal(followsUser(0, 0, 10), false, 'no input yet')+})diff --git a/apps/desktop/src/shared/artifacts.ts b/apps/desktop/src/shared/artifacts.tsindex f4335141..9fc188a9 100644--- a/apps/desktop/src/shared/artifacts.ts+++ b/apps/desktop/src/shared/artifacts.ts@@ -16,6 +16,25 @@ export interface Artifact {entryId?: string}+/** The desktop app loads each artifact from `codync-artifact://<id>/` (`main/artifacts.ts`), an origin of its own. */+export const ARTIFACT_SCHEME = 'codync-artifact'++/** An artifact frame's address; a card's preview is marked, so it opens nothing. */+export const artifactFrameURL = (id: string, version: number, preview: boolean) =>+ `${ARTIFACT_SCHEME}://${id}/?v=${version}${preview ? '&preview' : ''}`++/** An artifact frame's address, a card's or the viewer's. */+export const isArtifactURL = (url: string | undefined): url is string => !!url?.startsWith(`${ARTIFACT_SCHEME}:`)++/** An artifact's viewer frame: its scheme, without a card's `preview` marker. */+export const isArtifactViewer = (url: string | undefined) => isArtifactURL(url) && !new URL(url).searchParams.has('preview')++/** How long after a click or a key press a link it follows may open; later, it's a script acting alone. */+const FOLLOWED_MS = 1000++/** Whether what an artifact opens follows the user: a click or key in the window, after its viewer loaded, just now. */+export const followsUser = (input: number, loaded: number, now: number) => input > loaded && now - input < FOLLOWED_MS+/** 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 }diff --git a/apps/ios/Kit/Sources/CodyncKit/Client/HostClient.swift b/apps/ios/Kit/Sources/CodyncKit/Client/HostClient.swiftindex d63154f8..3dd457e5 100644--- a/apps/ios/Kit/Sources/CodyncKit/Client/HostClient.swift+++ b/apps/ios/Kit/Sources/CodyncKit/Client/HostClient.swift@@ -7,7 +7,7 @@ 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).+ /// An artifact published or renamed (the catch-up replays it too).case artifact(Artifact)case resync/// An event this app version couldn't decode (host newer/older than the app).@@ -118,7 +118,7 @@ public struct HostClient: Sendable {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.+ // Not worth a rewind: a card or the Library reads the artifact again.return (try? d.decode(ArtifactWrap.self, from: data)).map { .artifact($0.artifact) }case "resync":return .resyncdiff --git a/docs/features/artifacts.md b/docs/features/artifacts.mdindex 1346a15c..0b1430be 100644--- a/docs/features/artifacts.md+++ b/docs/features/artifacts.md@@ -35,8 +35,8 @@ title (`replies::quote`), and the bot reads `[Codync: this is about your artifac- 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.+ `{id, botId, title, size, sha256, createdAt, updatedAt, entryId?, rev}`, where `entryId` is the newest card and+ `rev` the sync rev of the last change. 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@@ -46,9 +46,12 @@ title (`replies::quote`), and the bot reads `[Codync: this is about your artifac- `readArtifact {botId, artifactId, offset}` → `{data: <base64>, size, artifact: Artifact}`, chunks of at most384 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.+ characters. The newest card (`entryId`) takes the new title too, so older apps and a cache that missed the rename+ show it.+- Event: `{"type": "artifact", "rev", "artifact": Artifact}` on every publish and rename, stamped with a global rev+ like every other change, so the catch-up (`/events?since=`) replays the artifacts changed after the client's cursor.+ Apps upsert what the events bring and fetch the `library` when they show it; one they can't read is skipped+ (no rewind), and 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@@ -63,7 +66,10 @@ All four clients show the same things; layout follows each platform.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).+ tapped web or mail link opens in the system browser, and other schemes go nowhere; the artifact sending itself or a+ new window elsewhere without a tap goes nowhere, and a card opens nothing. The desktop app checks the tap in its main+ process: a click or Return/Space in the window within a second, after the viewer loaded, opens one link; a+ touchscreen tap in the artifact never reaches the main process, so it opens nothing).- Header: close (`xmark`, "Close artifact"), the title in the middle (tapping it renames the artifact: "Renameartifact", "Artifact title"), and a share action: desktop "Save as HTML" and "Open in browser"; iPhone and Androidthe system share sheet with `<title>.html`.@@ -85,6 +91,7 @@ All four clients show the same things; layout follows each platform.Desktop: an artifact loads from `codync-artifact://<id>` (`apps/desktop/src/main/artifacts.ts`), its own origin, intoa 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).+What it opens goes to the browser by the Viewer's rule (`https`, `http` and `mailto` only): from the viewer only, after+a click or Return/Space; cards open nothing.Not yet: public links (Grok Bot's "Anyone with the link"), deleting or pinning an artifact, artifacts in group chats.diff --git a/host/src/api/events.rs b/host/src/api/events.rsindex 49231a58..fbff24fc 100644--- a/host/src/api/events.rs+++ b/host/src/api/events.rs@@ -66,6 +66,7 @@ pub fn events_stream(for e in hub.store.entries_since(since, CATCH_UP_PER_BOT)? {catch_up.push(json!({"type": "entry", "rev": e.rev, "entry": e}));}+ catch_up.extend(crate::chat::artifacts::since(&hub.store, since));catch_up.sort_by_key(|v| v["rev"].as_i64().unwrap_or(0));let hello = json!({"type": "hello",diff --git a/host/src/api/events/tests.rs b/host/src/api/events/tests.rsindex 71cfdfda..b24695f4 100644--- a/host/src/api/events/tests.rs+++ b/host/src/api/events/tests.rs@@ -79,3 +79,37 @@ async fn incremental_sync_replays_deletions_only_after_the_saved_cursor() {assert_eq!(events[1]["rev"], deleted_rev);assert_eq!(f.catch_up(deleted_rev).await.len(), 1);}++#[tokio::test]+async fn catch_up_brings_an_artifact_renamed_while_the_client_was_offline() {+ let f = Fixture::new();+ f.add_bot("b");+ let id = uuid::Uuid::new_v4().to_string();+ let card = f+ .hub+ .add_entry(+ &crate::store::Lane::main("b"),+ crate::store::EntryKind::Agent,+ 0,+ &json!({"text": "Artifact: Old", "final": true, "artifact": {"id": id, "title": "Old", "updatedAt": 1}}),+ )+ .unwrap();+ let saved = json!({"id": id, "botId": "b", "title": "Old", "size": 1, "sha256": "x", "createdAt": 1, "updatedAt": 1,+ "entryId": card.id});+ f.hub.store.kv_set(&format!("artifact.b.{id}"), &saved.to_string()).unwrap();+ let cursor = f.hub.store.current_rev();+ assert_eq!(f.catch_up(cursor).await[1..], [] as [Value; 0], "details without a rev default to 0, never replayed");++ crate::chat::artifacts::api(&f.hub, "renameArtifact", &json!({"botId": "b", "artifactId": id, "title": "New"}))+ .await+ .unwrap();+ let events = f.catch_up(cursor).await;+ let artifact = events.iter().find(|e| e["type"] == "artifact").expect("the rename is in the catch-up");+ assert_eq!(artifact["artifact"]["title"], "New");+ assert!(artifact["rev"].as_i64().unwrap() > cursor);+ let entry = events.iter().find(|e| e["type"] == "entry").expect("its card was retitled");+ assert_eq!(entry["entry"]["data"]["text"], "Artifact: New");+ assert_eq!(entry["entry"]["data"]["artifact"]["title"], "New");+ assert!(events[1..].windows(2).all(|pair| pair[0]["rev"].as_i64() < pair[1]["rev"].as_i64()), "in rev order");+ assert_eq!(f.catch_up(f.hub.store.current_rev()).await[1..], [] as [Value; 0]);+}diff --git a/host/src/chat/artifacts.rs b/host/src/chat/artifacts.rsindex cedbd624..9acbb86e 100644--- a/host/src/chat/artifacts.rs+++ b/host/src/chat/artifacts.rs@@ -38,6 +38,9 @@ pub struct Artifact {/// 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>,+ /// The sync rev of its last change, so a client's catch-up brings changes it missed.+ #[serde(default)]+ pub rev: i64,}impl Artifact {@@ -82,8 +85,15 @@ pub fn tools() -> [Value; 2] {]}+const KEY_PREFIX: &str = "artifact.";+fn key(bot: &str, id: &str) -> String {- format!("artifact.{bot}.{id}")+ format!("{KEY_PREFIX}{bot}.{id}")+}++/// The artifacts whose details are saved under keys starting with `prefix`.+fn saved<'a>(store: &'a Store, prefix: &str) -> impl Iterator<Item = Artifact> + 'a {+ store.kv_prefix(prefix).into_iter().filter_map(|k| serde_json::from_str(&store.kv_get(&k)?).ok())}/// Where a bot's artifacts live: `<id>.html` each.@@ -103,18 +113,30 @@ pub fn get(store: &Store, bot: &str, id: &str) -> Option<Artifact> {/// 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();+ let mut artifacts: Vec<Artifact> = saved(store, &format!("{KEY_PREFIX}{bot}.")).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(())+/// Saves an artifact's details under a new rev and tells the apps (`artifact` event; they upsert it by id).+fn put(hub: &Hub, artifact: &mut Artifact) -> Result<()> {+ hub.emit_change(|| {+ hub.store.kv_set_stamped(&key(&artifact.bot_id, &artifact.id), |rev| {+ artifact.rev = rev;+ Ok(serde_json::to_string(artifact)?)+ })?;+ Ok(event(artifact))+ })+}++fn event(artifact: &Artifact) -> Value {+ json!({"type": "artifact", "rev": artifact.rev, "artifact": artifact})+}++/// The `artifact` events a client's catch-up holds: every artifact changed after `since`.+// ponytail: scans every artifact's details; an index by rev if a computer ever keeps thousands.+pub fn since(store: &Store, since: i64) -> Vec<Value> {+ saved(store, KEY_PREFIX).filter(|artifact| artifact.rev > since).map(|artifact| event(&artifact)).collect()}pub fn title(value: &str) -> Result<String> {@@ -184,9 +206,10 @@ async fn publish(hub: &Arc<Hub>, bot: &str, args: &Value) -> Result<Value> {created_at: existing.as_ref().map_or(now, |artifact| artifact.created_at),updated_at: now,entry_id: existing.and_then(|artifact| artifact.entry_id),+ rev: 0,};// Saved before its card goes out, so an app opening the card finds it.- put(hub, &artifact)?;+ put(hub, &mut 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 })?;@@ -197,7 +220,7 @@ async fn publish(hub: &Arc<Hub>, bot: &str, args: &Value) -> Result<Value> {match posted {Ok(entry) => {artifact.entry_id = Some(entry);- put(hub, &artifact)?;+ put(hub, &mut 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(),@@ -224,13 +247,25 @@ pub async fn api(hub: &Arc<Hub>, method: &str, b: &Value) -> Result<Value> {}"renameArtifact" => {artifact.title = title(b["title"].as_str().unwrap_or_default())?;- put(hub, &artifact)?;+ put(hub, &mut artifact)?;+ retitle_card(hub, &artifact);Ok(json!({"artifact": artifact}))}_ => bail!("unknown artifact method: {method}"),}}+/// The artifact's newest card takes the new title too: older apps and a cache that never saw the rename show the card's.+fn retitle_card(hub: &Hub, artifact: &Artifact) {+ let Some(mut card) = artifact.entry_id.as_deref().and_then(|id| hub.store.entry(id)) else { return };+ if card.data["artifact"]["id"] != artifact.id.as_str() {+ return;+ }+ card.data["text"] = card_text(&artifact.title).into();+ card.data["artifact"]["title"] = artifact.title.clone().into();+ hub.set_entry(&card.id, &card.data);+}+/// 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");diff --git a/host/src/hub.rs b/host/src/hub.rsindex 0ccd9a71..12114281 100644--- a/host/src/hub.rs+++ b/host/src/hub.rs@@ -352,6 +352,13 @@ impl Hub {self.store.bot(id).ok().flatten().map(|r| self.bot_json(&r))}+ /// Saves a change that stamps its own rev and broadcasts the event `save` returns, in rev order.+ pub fn emit_change(&self, save: impl FnOnce() -> Result<Value>) -> Result<()> {+ let _g = self.emit_lock.locked();+ let _ = self.events.send(save()?);+ Ok(())+ }+/// Bumps the bot's rev and broadcasts its current state.pub fn emit_bot(&self, id: &str) {let _g = self.emit_lock.locked();diff --git a/host/src/store/mod.rs b/host/src/store/mod.rsindex 13b605d9..ce497950 100644--- a/host/src/store/mod.rs+++ b/host/src/store/mod.rs@@ -83,6 +83,16 @@ impl Store {pub fn current_rev(&self) -> i64 {self.kv_get("rev").and_then(|v| v.parse().ok()).unwrap_or(0)}++ /// Saves a row stamped with the next rev, in one transaction: `value` gets the rev and returns what to save.+ pub fn kv_set_stamped(&self, k: &str, value: impl FnOnce(i64) -> Result<String>) -> Result<()> {+ let mut c = self.db.locked();+ let tx = c.transaction()?;+ let rev = next_rev(&tx)?;+ tx.execute("INSERT INTO kv(k, v) VALUES(?1, ?2) ON CONFLICT(k) DO UPDATE SET v = ?2", params![k, value(rev)?])?;+ tx.commit()?;+ Ok(())+ }}#[cfg(test)]