feat: add image attachments for vision models

A chat line can carry up to four images, each capped at 5 MB and
sniffed from its bytes. Uploads go to a room route first, the message
references the ids, and the bytes are served back to members; an
upload no message claims within an hour is swept on the next send.

Images only make sense when the model can look at them, and the
catalog's answer is tri-state, so the gate is a stored fact, not a
guess: the provider listing remembers supports_vision per kind and
model, the upload and send routes refuse when the room's effective
model is not a known vision model, and the composer hides the attach
button on the same fact, which rides the room payload. At turn time
the fact goes to the host agent, which sends the blocks on a vision
model and leaves a note where each image was on the rest.
This commit is contained in:
vhaudiquet committed 2026-12-01 21:59:53 +01:00
1 parent acc545ede7
commit 2e17e7463c
18 files changed
+624 -46

No files matched your search

+3 -2
View File
@@ -7,8 +7,9 @@ agent; the people and the agent see the same sandbox.
The room is a browser workspace: The room is a browser workspace:
- **Chat** with the room and with `@rhema`. Human messages carry their - **Chat** with the room and with `@rhema`. Human messages carry their
author's name; the agent speaks through a `message` tool so that its author's name and can carry images when the room's model has vision;
private reasoning never leaks into the room. the agent speaks through a `message` tool so that its private
reasoning never leaks into the room.
- **Preview** iframe for a dev server or a static build, set from the - **Preview** iframe for a dev server or a static build, set from the
chat by the agent's `preview` tool. chat by the agent's `preview` tool.
- **Files** pane: the tree, a read-only file view, `git status`, and - **Files** pane: the tree, a read-only file view, `git status`, and
+13 -2
View File
@@ -350,7 +350,12 @@ paged backwards. Composer at the bottom with `@` completion for the
agent and for people. Each message carries author, colour, time, and, agent and for people. Each message carries author, colour, time, and,
for agent messages, the turn. Images and pastes ride the message row; for agent messages, the turn. Images and pastes ride the message row;
the bytes are served from a room route, and vision models get inline the bytes are served from a room route, and vision models get inline
image blocks the way the claw already sends them. image blocks the way the claw already sends them. A line carries at
most four images, each capped at 5 MB and sniffed from its bytes. Only
a model the provider listing says has vision accepts them: the composer
hides the attach button and the upload route refuses otherwise, and the
turn passes the fact to the host agent, which masks the blocks for a
model that cannot see.
A running turn has no transcript card. The status line above the composer A running turn has no transcript card. The status line above the composer
shows `Rhema is working...` until `turn_end`. When the turn ends, the log shows `Rhema is working...` until `turn_end`. When the turn ends, the log
@@ -610,6 +615,12 @@ members(room_id, id, account_id, display_name, role, color, guest_token_hash,
invites(token_hash, room_id, role, created_by, expires_at, max_uses, uses) invites(token_hash, room_id, role, created_by, expires_at, max_uses, uses)
messages(room_id, seq, id, author_kind, author_id, text, mentions_json, messages(room_id, seq, id, author_kind, author_id, text, mentions_json,
turn_id, created_at) turn_id, created_at)
attachments(id, room_id, uploader, mime, bytes, size, message_id,
created_at) -- message_id set when a line sent it; older
-- unreferenced uploads are swept after an hour
model_facts(kind, model_id, supports_vision, updated_at) -- filled by
-- the provider listing; the send, upload, and turn paths
-- read it instead of repeating a live call
turn_events(room_id, seq, turn_id, kind, body_json, created_at) turn_events(room_id, seq, turn_id, kind, body_json, created_at)
turns(room_id, id, status, started_by, started_at, ended_at, steps, turns(room_id, id, status, started_by, started_at, ended_at, steps,
usage_json, cost_usd) usage_json, cost_usd)
@@ -645,7 +656,7 @@ Refuse to start on a non-loopback `listen` without a `public_url`, a
secret key, and at least one account. First run prints a one-time setup secret key, and at least one account. First run prints a one-time setup
token that creates the first account. token that creates the first account.
Backups: the SQLite file, the secret key, and the attachment directory. Backups: the SQLite file (attachments included) and the secret key.
## 11. Framework changes ## 11. Framework changes
+157
View File
@@ -0,0 +1,157 @@
//! Room image attachments. An upload stores the bytes and their
//! sniffed type; a message carries the ids, and a turn turns them into
//! inline image blocks when the model can see.
use axum::Json;
use axum::body::Bytes;
use axum::extract::{Path, State};
use axum::http::{HeaderValue, StatusCode, header};
use axum::response::{IntoResponse, Response};
use rhema_core::ImageMediaType;
use serde_json::{Value, json};
use crate::auth::AuthUser;
use crate::error::{AppError, AppResult};
use crate::models::Attachment;
use crate::state::Shared;
use crate::util::{now_ms, random_id, room_model_vision};
use super::rooms::member_of;
/// Five megabytes per image. The picker on the client refuses bigger
/// files before the upload starts; this is the server's own cap.
pub const MAX_ATTACHMENT_BYTES: usize = 5 * 1024 * 1024;
/// Images ride one message in groups of at most four.
pub const MAX_ATTACHMENTS_PER_MESSAGE: usize = 4;
/// How long an upload that no message picked up stays stored.
const ORPHAN_TTL_MS: i64 = 60 * 60 * 1000;
/// The room's model must be a known vision model: attachments are for
/// the agent to look at, and an upload a model cannot see is noise.
pub fn require_vision(state: &Shared, room: &str) -> AppResult<()> {
if room_model_vision(&state.db.conn(), room) == Some(true) {
return Ok(());
}
Err(AppError::bad_request(
"image attachments need a model with vision; this room's model does not have it, or the room has no model",
))
}
/// Stores one image. The body is the raw file, the way the avatar
/// route takes it: the client sends bytes, the server sniffs the type
/// and never trusts a claimed content type.
pub async fn upload(
user: AuthUser,
State(state): State<Shared>,
Path(room): Path<String>,
body: Bytes,
) -> AppResult<Json<Value>> {
member_of(&state, &room, &user.user.id)?;
require_vision(&state, &room)?;
if body.is_empty() {
return Err(AppError::bad_request("the attachment is empty"));
}
if body.len() > MAX_ATTACHMENT_BYTES {
return Err(AppError::new(
StatusCode::PAYLOAD_TOO_LARGE,
"images are capped at 5 MB",
));
}
let media = ImageMediaType::sniff(&body).ok_or_else(|| {
AppError::bad_request("attachments must be PNG, JPEG, GIF, or WebP images")
})?;
let id = random_id(16);
state.db.conn().execute(
"INSERT INTO attachments (id, room_id, uploader, mime, bytes, size, message_id, created_at)
VALUES (?1, ?2, ?3, ?4, ?5, ?6, NULL, ?7)",
rusqlite::params![
id,
room,
user.user.id,
media.as_str(),
body.as_ref(),
body.len() as i64,
now_ms()
],
)?;
Ok(Json(json!({
"attachment": { "id": id, "mime": media.as_str(), "size": body.len() }
})))
}
/// Serves one stored image to a room member. The id never changes, so
/// the response caches forever in the member's browser.
pub async fn get(
user: AuthUser,
State(state): State<Shared>,
Path((room, attachment)): Path<(String, String)>,
) -> AppResult<Response> {
member_of(&state, &room, &user.user.id)?;
let row = state
.db
.conn()
.query_row(
"SELECT mime, bytes FROM attachments WHERE id = ?1 AND room_id = ?2",
rusqlite::params![attachment, room],
|row| Ok((row.get::<_, String>(0)?, row.get::<_, Vec<u8>>(1)?)),
)
.map_err(|_| AppError::not_found("attachment not found"))?;
let mut response = row.1.into_response();
let headers = response.headers_mut();
headers.insert(
header::CONTENT_TYPE,
HeaderValue::from_str(&row.0)
.unwrap_or(HeaderValue::from_static("application/octet-stream")),
);
headers.insert(
header::CACHE_CONTROL,
HeaderValue::from_static("private, max-age=31536000, immutable"),
);
Ok(response)
}
/// Fills in the metadata a message stores beside the ids, refusing an
/// id that is not one of this room's uploads.
pub fn load_metadata(state: &Shared, room: &str, ids: &[String]) -> AppResult<Vec<Attachment>> {
let conn = state.db.conn();
let mut attachments = Vec::with_capacity(ids.len());
for id in ids {
let (mime, size) = conn
.query_row(
"SELECT mime, size FROM attachments WHERE id = ?1 AND room_id = ?2",
rusqlite::params![id, room],
|row| Ok((row.get::<_, String>(0)?, row.get::<_, i64>(1)?)),
)
.map_err(|_| AppError::bad_request("an attachment is missing; upload it again"))?;
attachments.push(Attachment {
id: id.clone(),
mime,
size,
});
}
Ok(attachments)
}
/// Marks the uploads a posted message carries, so the sweep keeps them.
pub fn mark_used(state: &Shared, room: &str, message_id: &str, ids: &[String]) {
let conn = state.db.conn();
for id in ids {
let _ = conn.execute(
"UPDATE attachments SET message_id = ?1 WHERE id = ?2 AND room_id = ?3",
rusqlite::params![message_id, id, room],
);
}
}
/// Deletes uploads nobody sent within the hour. Runs beside a send,
/// where uploads just settled: one statement, and only this room's
/// orphans go.
pub fn sweep(state: &Shared, room: &str) {
let cutoff = now_ms() - ORPHAN_TTL_MS;
let _ = state.db.conn().execute(
"DELETE FROM attachments WHERE room_id = ?1 AND message_id IS NULL AND created_at < ?2",
rusqlite::params![room, cutoff],
);
}
+27 -1
View File
@@ -29,6 +29,9 @@ pub type EventStream = Pin<Box<dyn Stream<Item = Result<SseEvent, Infallible>> +
#[derive(Deserialize)] #[derive(Deserialize)]
pub struct SendBody { pub struct SendBody {
pub text: String, pub text: String,
/// Ids from `POST /rooms/{id}/attachments`, uploaded just before.
#[serde(default)]
pub attachments: Vec<String>,
} }
/// Posts one human line and wakes the agent when it mentions `@rhema`. /// Posts one human line and wakes the agent when it mentions `@rhema`.
@@ -40,7 +43,26 @@ pub async fn send(
) -> AppResult<Json<Value>> { ) -> AppResult<Json<Value>> {
let member = member_of(&state, &room, &user.user.id)?; let member = member_of(&state, &room, &user.user.id)?;
let text = body.text.trim(); let text = body.text.trim();
if text.is_empty() { let ids = &body.attachments;
if ids.len() > super::attachments::MAX_ATTACHMENTS_PER_MESSAGE {
return Err(AppError::bad_request(
"a message carries at most four images",
));
}
if ids.iter().any(|id| id.is_empty()) {
return Err(AppError::bad_request("an attachment id is empty"));
}
let duplicate = (1..ids.len()).any(|at| ids[..at].contains(&ids[at]));
if duplicate {
return Err(AppError::bad_request("the same attachment is listed twice"));
}
let attachments = if ids.is_empty() {
Vec::new()
} else {
super::attachments::require_vision(&state, &room)?;
super::attachments::load_metadata(&state, &room, ids)?
};
if text.is_empty() && attachments.is_empty() {
return Err(AppError::bad_request("the message is empty")); return Err(AppError::bad_request("the message is empty"));
} }
if text.chars().count() > 16_000 { if text.chars().count() > 16_000 {
@@ -57,6 +79,7 @@ pub async fn send(
text: text.to_owned(), text: text.to_owned(),
mentions, mentions,
created_at: now_ms(), created_at: now_ms(),
attachments,
}; };
let data = serde_json::to_value(&message)?; let data = serde_json::to_value(&message)?;
state.hub.insert(&state.db, &room, seq, "message", &data)?; state.hub.insert(&state.db, &room, seq, "message", &data)?;
@@ -68,6 +91,8 @@ pub async fn send(
data, data,
}, },
); );
super::attachments::mark_used(&state, &room, &message.id, ids);
super::attachments::sweep(&state, &room);
state.rooms.wake( state.rooms.wake(
&state, &state,
&room, &room,
@@ -312,6 +337,7 @@ pub async fn interrupt(
text, text,
mentions: false, mentions: false,
created_at: now_ms(), created_at: now_ms(),
attachments: Vec::new(),
}; };
let data = serde_json::to_value(&message)?; let data = serde_json::to_value(&message)?;
state.hub.insert(&state.db, &room, seq, "message", &data)?; state.hub.insert(&state.db, &room, seq, "message", &data)?;
+11
View File
@@ -1,6 +1,7 @@
//! HTTP routes: the JSON API, the event feed, the presence socket, and //! HTTP routes: the JSON API, the event feed, the presence socket, and
//! the built client. //! the built client.
pub mod attachments;
pub mod auth; pub mod auth;
pub mod files; pub mod files;
pub mod messages; pub mod messages;
@@ -76,6 +77,16 @@ pub fn router(state: Shared) -> Router {
"/rooms/{id}/messages", "/rooms/{id}/messages",
get(messages::list).post(messages::send), get(messages::list).post(messages::send),
) )
.route(
"/rooms/{id}/attachments",
post(attachments::upload).layer(DefaultBodyLimit::max(
attachments::MAX_ATTACHMENT_BYTES + 64 * 1024,
)),
)
.route(
"/rooms/{id}/attachments/{attachment}",
get(attachments::get),
)
.route("/rooms/{id}/events", get(messages::events)) .route("/rooms/{id}/events", get(messages::events))
.route("/rooms/{id}/presence", get(messages::presence)) .route("/rooms/{id}/presence", get(messages::presence))
.route("/rooms/{id}/files", get(files::list)) .route("/rooms/{id}/files", get(files::list))
+25 -27
View File
@@ -54,34 +54,32 @@ pub fn owner_of(state: &Shared, room: &str, account: &str) -> AppResult<Membersh
Ok(member) Ok(member)
} }
fn room_from_row(row: &rusqlite::Row<'_>) -> rusqlite::Result<Room> {
Ok(Room {
id: row.get("id")?,
name: row.get("name")?,
owner_id: row.get("owner_id")?,
provider_config_id: row.get("provider_config_id")?,
sandbox_target_id: row.get("sandbox_target_id")?,
workspace: row.get("workspace")?,
repo_url: row.get("repo_url")?,
model: row.get("model")?,
max_turn_steps: row.get("max_turn_steps")?,
created_at: row.get("created_at")?,
archived_at: row.get("archived_at")?,
})
}
fn load_room(state: &Shared, id: &str) -> AppResult<Room> { fn load_room(state: &Shared, id: &str) -> AppResult<Room> {
state let conn = state.db.conn();
.db let vision = crate::util::room_model_vision(&conn, id);
.conn() conn.query_row(
.query_row( "SELECT id, name, owner_id, provider_config_id, sandbox_target_id, workspace,
"SELECT id, name, owner_id, provider_config_id, sandbox_target_id, workspace, repo_url, model, max_turn_steps, created_at, archived_at
repo_url, model, max_turn_steps, created_at, archived_at FROM rooms WHERE id = ?1",
FROM rooms WHERE id = ?1", rusqlite::params![id],
rusqlite::params![id], |row| {
room_from_row, Ok(Room {
) id: row.get("id")?,
.map_err(|_| AppError::not_found("room not found")) name: row.get("name")?,
owner_id: row.get("owner_id")?,
provider_config_id: row.get("provider_config_id")?,
sandbox_target_id: row.get("sandbox_target_id")?,
workspace: row.get("workspace")?,
repo_url: row.get("repo_url")?,
model: row.get("model")?,
max_turn_steps: row.get("max_turn_steps")?,
model_vision: vision,
created_at: row.get("created_at")?,
archived_at: row.get("archived_at")?,
})
},
)
.map_err(|_| AppError::not_found("room not found"))
} }
fn load_members(state: &Shared, room: &str) -> AppResult<Vec<Member>> { fn load_members(state: &Shared, room: &str) -> AppResult<Vec<Member>> {
+31
View File
@@ -290,12 +290,43 @@ pub async fn list_provider_models(
tracing::warn!(provider = %id, error = %err, "provider catalog"); tracing::warn!(provider = %id, error = %err, "provider catalog");
AppError::new(StatusCode::BAD_GATEWAY, catalog_error(&err)) AppError::new(StatusCode::BAD_GATEWAY, catalog_error(&err))
})?; })?;
remember_model_facts(&state, &kind, &models);
Ok(Json(json!({ Ok(Json(json!({
"provider": { "id": id, "kind": kind, "model": model }, "provider": { "id": id, "kind": kind, "model": model },
"models": models, "models": models,
}))) })))
} }
/// Keeps each card's vision fact, keyed by the provider kind and the
/// model id. The send, upload, and turn paths read the table instead
/// of repeating a live listing, and a model the listing leaves blank
/// stays unknown. A failed write only loses facts, so it logs.
fn remember_model_facts(state: &Shared, kind: &str, models: &[rhema_provider::ModelCard]) {
let now = crate::util::now_ms();
let result: rusqlite::Result<()> = (|| {
let conn = state.db.conn();
let mut stmt = conn.prepare(
"INSERT INTO model_facts (kind, model_id, supports_vision, updated_at)
VALUES (?1, ?2, ?3, ?4)
ON CONFLICT(kind, model_id) DO UPDATE SET
supports_vision = excluded.supports_vision,
updated_at = excluded.updated_at",
)?;
for card in models {
stmt.execute(rusqlite::params![
kind,
card.id,
card.supports_vision.map(|value| value as i64),
now
])?;
}
Ok(())
})();
if let Err(err) = result {
tracing::warn!(provider_kind = %kind, error = %err, "model facts");
}
}
/// A short reason for a failed catalog fetch. The provider's own body /// A short reason for a failed catalog fetch. The provider's own body
/// can be an HTML error page and is not worth showing; the full error /// can be an HTML error page and is not worth showing; the full error
/// stays in the log. /// stays in the log.
+21 -1
View File
@@ -47,7 +47,7 @@ impl Db {
} }
} }
const SCHEMA: &str = r#" pub(crate) const SCHEMA: &str = r#"
CREATE TABLE IF NOT EXISTS meta ( CREATE TABLE IF NOT EXISTS meta (
key TEXT PRIMARY KEY, key TEXT PRIMARY KEY,
value TEXT NOT NULL value TEXT NOT NULL
@@ -161,7 +161,27 @@ CREATE TABLE IF NOT EXISTS events (
PRIMARY KEY (room_id, seq) PRIMARY KEY (room_id, seq)
) STRICT; ) STRICT;
CREATE TABLE IF NOT EXISTS attachments (
id TEXT PRIMARY KEY,
room_id TEXT NOT NULL REFERENCES rooms(id) ON DELETE CASCADE,
uploader TEXT NOT NULL REFERENCES accounts(id) ON DELETE CASCADE,
mime TEXT NOT NULL,
bytes BLOB NOT NULL,
size INTEGER NOT NULL,
message_id TEXT,
created_at INTEGER NOT NULL
) STRICT;
CREATE TABLE IF NOT EXISTS model_facts (
kind TEXT NOT NULL,
model_id TEXT NOT NULL,
supports_vision INTEGER,
updated_at INTEGER NOT NULL,
PRIMARY KEY (kind, model_id)
) STRICT;
CREATE INDEX IF NOT EXISTS members_room ON members(room_id); CREATE INDEX IF NOT EXISTS members_room ON members(room_id);
CREATE INDEX IF NOT EXISTS events_room_seq ON events(room_id, seq); CREATE INDEX IF NOT EXISTS events_room_seq ON events(room_id, seq);
CREATE INDEX IF NOT EXISTS auth_sessions_account ON auth_sessions(account_id); CREATE INDEX IF NOT EXISTS auth_sessions_account ON auth_sessions(account_id);
CREATE INDEX IF NOT EXISTS attachments_room ON attachments(room_id);
"#; "#;
+16
View File
@@ -15,6 +15,19 @@ pub struct Message {
pub text: String, pub text: String,
pub mentions: bool, pub mentions: bool,
pub created_at: i64, pub created_at: i64,
/// The images riding this line, metadata only: the bytes are served
/// from the room's attachment route. Empty for older rows.
#[serde(default, skip_serializing_if = "Vec::is_empty")]
pub attachments: Vec<Attachment>,
}
/// An image attached to a chat line. `mime` comes from the stored
/// bytes' magic, never from the uploader's header.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct Attachment {
pub id: String,
pub mime: String,
pub size: i64,
} }
/// A room as the sidebar needs it. /// A room as the sidebar needs it.
@@ -40,6 +53,9 @@ pub struct Room {
pub repo_url: Option<String>, pub repo_url: Option<String>,
pub model: Option<String>, pub model: Option<String>,
pub max_turn_steps: i64, pub max_turn_steps: i64,
/// Whether the room's effective model is known to accept images.
/// `None` is unknown, not no: facts arrive with a provider listing.
pub model_vision: Option<bool>,
pub created_at: i64, pub created_at: i64,
pub archived_at: Option<i64>, pub archived_at: Option<i64>,
} }
+36 -1
View File
@@ -26,6 +26,8 @@ pub struct TurnConfig {
pub workspace: String, pub workspace: String,
pub repo_url: Option<String>, pub repo_url: Option<String>,
pub model: String, pub model: String,
/// The model's stored vision fact; `None` is unknown, not no.
pub supports_vision: Option<bool>,
pub max_turn_steps: u32, pub max_turn_steps: u32,
pub absorbed_seq: i64, pub absorbed_seq: i64,
pub seeded: bool, pub seeded: bool,
@@ -135,12 +137,14 @@ pub fn load_turn_config(state: &Shared, room_id: &str) -> AppResult<TurnConfig>
if model.trim().is_empty() { if model.trim().is_empty() {
return Err(AppError::bad_request("room has no model selected")); return Err(AppError::bad_request("room has no model selected"));
} }
let supports_vision = crate::util::model_supports_vision(&conn, &kind, &model);
Ok(TurnConfig { Ok(TurnConfig {
room_id: room_id.to_owned(), room_id: room_id.to_owned(),
room_name: name, room_name: name,
workspace, workspace,
repo_url, repo_url,
model, model,
supports_vision,
max_turn_steps: max_steps.max(1) as u32, max_turn_steps: max_steps.max(1) as u32,
absorbed_seq: absorbed, absorbed_seq: absorbed,
seeded: seeded != 0, seeded: seeded != 0,
@@ -358,7 +362,7 @@ pub fn build_agent(state: &Shared, config: &TurnConfig, session: Session) -> App
concat!("rhema-together ", env!("CARGO_PKG_VERSION")), concat!("rhema-together ", env!("CARGO_PKG_VERSION")),
)), )),
user_preferences: None, user_preferences: None,
supports_vision: None, supports_vision: config.supports_vision,
vision: None, vision: None,
jobs: None, jobs: None,
websearch: None, websearch: None,
@@ -397,6 +401,37 @@ pub fn load_session(state: &Shared, room: &str) -> AppResult<Session> {
} }
} }
/// The images a human message carries, read back as inline blocks.
/// An attachment that vanished or is not a wire format the providers
/// share is skipped: the text still reaches the model.
pub fn load_images(
state: &Shared,
room: &str,
attachments: &[crate::models::Attachment],
) -> Vec<rhema_core::Image> {
use base64::Engine as _;
let conn = state.db.conn();
let mut images = Vec::with_capacity(attachments.len());
for attachment in attachments {
let row = conn.query_row(
"SELECT mime, bytes FROM attachments WHERE id = ?1 AND room_id = ?2",
rusqlite::params![attachment.id, room],
|row| Ok((row.get::<_, String>(0)?, row.get::<_, Vec<u8>>(1)?)),
);
let Ok((mime, bytes)) = row else {
continue;
};
let Some(media) = rhema_core::ImageMediaType::parse(&mime) else {
continue;
};
images.push(rhema_core::Image::new(
media,
base64::engine::general_purpose::STANDARD.encode(bytes),
));
}
images
}
/// Persists a session outside the commit hook (the end of a turn). /// Persists a session outside the commit hook (the end of a turn).
pub fn save_session(state: &Shared, room: &str, session: &Session) -> AppResult<()> { pub fn save_session(state: &Shared, room: &str, session: &Session) -> AppResult<()> {
let json = serde_json::to_string(session)?; let json = serde_json::to_string(session)?;
+1
View File
@@ -23,6 +23,7 @@ pub fn post_agent_message(state: &Shared, room: &str, text: &str) -> AppResult<M
text: text.to_owned(), text: text.to_owned(),
mentions: mentions_agent(text), mentions: mentions_agent(text),
created_at: now_ms(), created_at: now_ms(),
attachments: Vec::new(),
}; };
let data = serde_json::to_value(&message)?; let data = serde_json::to_value(&message)?;
state.hub.insert(&state.db, room, seq, "message", &data)?; state.hub.insert(&state.db, room, seq, "message", &data)?;
+7 -4
View File
@@ -68,10 +68,13 @@ pub async fn run(state: Shared, room: String, mut rx: UnboundedReceiver<Wake>) {
} }
}; };
for message in &pending { for message in &pending {
session.history.push(Message::text( let text = format!("{}: {}", message.author_name, message.text);
Role::User, let images = agent::load_images(&state, &room, &message.attachments);
format!("{}: {}", message.author_name, message.text), session.history.push(if images.is_empty() {
)); Message::text(Role::User, text)
} else {
Message::text_with_images(Role::User, text, images)
});
} }
if let Err(err) = agent::save_session(&state, &room, &session) { if let Err(err) = agent::save_session(&state, &room, &session) {
notice(&state, &room, "error", err.message); notice(&state, &room, "error", err.message);
+52
View File
@@ -137,6 +137,35 @@ pub fn safe_rel_path(path: &str) -> Result<String, String> {
}) })
} }
/// The stored vision fact for one model id, when a listing carried it.
/// `None` is unknown: no row, or a row the last listing left blank.
pub fn model_supports_vision(conn: &rusqlite::Connection, kind: &str, model: &str) -> Option<bool> {
conn.query_row(
"SELECT supports_vision FROM model_facts WHERE kind = ?1 AND model_id = ?2",
rusqlite::params![kind, model],
|row| row.get::<_, Option<i64>>(0),
)
.ok()
.flatten()
.map(|value| value != 0)
}
/// The room's effective model vision: the stored fact for the room's
/// provider kind and its effective model, the room override or the
/// provider default. `None` when the room has no provider or no fact.
pub fn room_model_vision(conn: &rusqlite::Connection, room: &str) -> Option<bool> {
let (kind, model): (String, String) = conn
.query_row(
"SELECT p.kind, COALESCE(NULLIF(r.model, ''), p.model)
FROM rooms r JOIN provider_configs p ON p.id = r.provider_config_id
WHERE r.id = ?1",
rusqlite::params![room],
|row| Ok((row.get(0)?, row.get(1)?)),
)
.ok()?;
model_supports_vision(conn, &kind, &model)
}
/// `@rhema` in any case, as a whole word. /// `@rhema` in any case, as a whole word.
pub fn mentions_agent(text: &str) -> bool { pub fn mentions_agent(text: &str) -> bool {
let lower = text.to_lowercase(); let lower = text.to_lowercase();
@@ -212,6 +241,29 @@ mod tests {
assert!(check_target_address("1.1.1.1", 22).await.is_ok()); assert!(check_target_address("1.1.1.1", 22).await.is_ok());
} }
#[test]
fn vision_facts_read_back_and_stay_unknown_when_absent() {
let conn = rusqlite::Connection::open_in_memory().unwrap();
conn.execute_batch(crate::db::SCHEMA).unwrap();
assert_eq!(model_supports_vision(&conn, "openai", "gpt-5"), None);
conn.execute(
"INSERT INTO model_facts (kind, model_id, supports_vision, updated_at)
VALUES ('openai', 'gpt-5', 1, 0), ('llama-cpp', 'qwen', NULL, 0)",
[],
)
.unwrap();
assert_eq!(model_supports_vision(&conn, "openai", "gpt-5"), Some(true));
assert_eq!(model_supports_vision(&conn, "llama-cpp", "qwen"), None);
assert_eq!(model_supports_vision(&conn, "openai", "other"), None);
}
#[test]
fn a_room_without_a_provider_has_no_vision_fact() {
let conn = rusqlite::Connection::open_in_memory().unwrap();
conn.execute_batch(crate::db::SCHEMA).unwrap();
assert_eq!(room_model_vision(&conn, "room"), None);
}
#[test] #[test]
fn mentions_need_a_word_boundary() { fn mentions_need_a_word_boundary() {
assert!(mentions_agent("@rhema fix this")); assert!(mentions_agent("@rhema fix this"));
+63
View File
@@ -1213,6 +1213,27 @@ button {
margin-bottom: 0; margin-bottom: 0;
} }
.msg-attachments {
display: flex;
flex-wrap: wrap;
gap: var(--sp-2);
margin-top: var(--sp-1);
}
.msg-attachment {
display: block;
border: 1px solid var(--border);
border-radius: var(--r-card);
overflow: hidden;
line-height: 0;
}
.msg-attachment img {
display: block;
max-width: 240px;
max-height: 180px;
}
.msg-text p, .msg-text p,
.msg-text ul, .msg-text ul,
.msg-text ol, .msg-text ol,
@@ -1577,6 +1598,48 @@ button {
padding-left: var(--sp-2); padding-left: var(--sp-2);
} }
.composer-attachments {
display: flex;
flex-wrap: wrap;
gap: var(--sp-2);
padding: var(--sp-1) var(--sp-2) var(--sp-2);
}
.composer-attachment {
position: relative;
}
.composer-attachment-thumb {
display: block;
width: 56px;
height: 56px;
object-fit: cover;
border: 1px solid var(--border);
border-radius: var(--r-control);
}
.composer-attachment-remove {
position: absolute;
top: -6px;
right: -6px;
display: grid;
place-items: center;
width: 18px;
height: 18px;
padding: 0;
border: 1px solid var(--border-strong);
border-radius: var(--r-avatar);
background: var(--surface);
color: var(--muted);
cursor: pointer;
line-height: 0;
}
.composer-attachment-remove:hover {
color: var(--danger);
border-color: var(--danger);
}
.composer-buttons { .composer-buttons {
display: flex; display: flex;
align-items: center; align-items: center;
+124 -7
View File
@@ -1,16 +1,28 @@
<script setup lang="ts"> <script setup lang="ts">
import { nextTick, onBeforeUnmount, onMounted, ref } from 'vue' import { nextTick, onBeforeUnmount, onMounted, ref } from 'vue'
import { AtSign, Send } from 'lucide-vue-next' import { AtSign, ImagePlus, Send, X } from 'lucide-vue-next'
import type { Message, SendMessageResponse } from '~/types' import type {
Message,
SendMessageResponse,
UploadedAttachment,
UploadAttachmentResponse,
} from '~/types'
import { apiErrorMessage } from '~/utils/errors' import { apiErrorMessage } from '~/utils/errors'
const props = defineProps<{ roomId: string }>() const props = defineProps<{ roomId: string; canAttach: boolean }>()
const emit = defineEmits<{ sent: [message: Message]; typing: [active: boolean]; resized: [] }>() const emit = defineEmits<{ sent: [message: Message]; typing: [active: boolean]; resized: [] }>()
const MAX_ATTACHMENTS = 4
const MAX_ATTACHMENT_BYTES = 5 * 1024 * 1024
const ATTACHMENT_TYPES = ['image/png', 'image/jpeg', 'image/gif', 'image/webp']
const api = useApi() const api = useApi()
const text = ref('') const text = ref('')
const sending = ref(false) const sending = ref(false)
const uploading = ref(false)
const error = ref('') const error = ref('')
const attachments = ref<UploadedAttachment[]>([])
const fileInput = ref<HTMLInputElement | null>(null)
const input = ref<HTMLTextAreaElement | null>(null) const input = ref<HTMLTextAreaElement | null>(null)
const sizer = ref<HTMLTextAreaElement | null>(null) const sizer = ref<HTMLTextAreaElement | null>(null)
let typingTimer: number | null = null let typingTimer: number | null = null
@@ -79,14 +91,83 @@ function onKeydown(event: KeyboardEvent) {
void send() void send()
} }
function clearAttachments() {
for (const att of attachments.value) URL.revokeObjectURL(att.previewUrl)
attachments.value = []
}
function rejectFile(file: File): string | null {
if (!ATTACHMENT_TYPES.includes(file.type)) return `${file.name} is not a PNG, JPEG, GIF, or WebP image`
if (file.size > MAX_ATTACHMENT_BYTES) return `${file.name} is over the 5 MB cap`
return null
}
async function addFiles(files: Iterable<File>) {
const picked = [...files]
if (picked.length === 0) return
const reason = picked.map(rejectFile).find((value) => value !== null)
if (reason) {
error.value = reason
return
}
const capacity = Math.max(0, MAX_ATTACHMENTS - attachments.value.length)
if (picked.length > capacity) {
error.value = `A message carries at most ${MAX_ATTACHMENTS} images.`
return
}
uploading.value = true
error.value = ''
try {
for (const file of picked) {
const response = await api.upload<UploadAttachmentResponse>(
`/rooms/${props.roomId}/attachments`,
file,
)
attachments.value.push({ ...response.attachment, previewUrl: URL.createObjectURL(file) })
}
} catch (err) {
error.value = apiErrorMessage(err)
} finally {
uploading.value = false
}
}
function pickFiles() {
fileInput.value?.click()
}
function onFilesChosen(event: Event) {
const element = event.target as HTMLInputElement
void addFiles(element.files ?? [])
element.value = ''
}
function onPaste(event: ClipboardEvent) {
const files = [...(event.clipboardData?.files ?? [])].filter((file) => file.type.startsWith('image/'))
if (files.length === 0) return
event.preventDefault()
void addFiles(files)
}
function removeAttachment(at: number) {
const att = attachments.value[at]
if (!att) return
URL.revokeObjectURL(att.previewUrl)
attachments.value.splice(at, 1)
}
async function send() { async function send() {
const value = text.value.trim() const value = text.value.trim()
if (!value || sending.value) return if ((!value && attachments.value.length === 0) || sending.value || uploading.value) return
sending.value = true sending.value = true
error.value = '' error.value = ''
try { try {
const response = await api.post<SendMessageResponse>(`/rooms/${props.roomId}/messages`, { text: value }) const response = await api.post<SendMessageResponse>(`/rooms/${props.roomId}/messages`, {
text: value,
attachments: attachments.value.map((att) => att.id),
})
text.value = '' text.value = ''
clearAttachments()
if (typingTimer !== null) { if (typingTimer !== null) {
window.clearTimeout(typingTimer) window.clearTimeout(typingTimer)
typingTimer = null typingTimer = null
@@ -120,6 +201,7 @@ onBeforeUnmount(() => {
if (typingTimer !== null) window.clearTimeout(typingTimer) if (typingTimer !== null) window.clearTimeout(typingTimer)
widthObserver?.disconnect() widthObserver?.disconnect()
widthObserver = null widthObserver = null
clearAttachments()
}) })
</script> </script>
@@ -136,7 +218,22 @@ onBeforeUnmount(() => {
placeholder="Message the room. Use @rhema to ask the agent." placeholder="Message the room. Use @rhema to ask the agent."
@input="onInput" @input="onInput"
@keydown="onKeydown" @keydown="onKeydown"
@paste="onPaste"
/> />
<div v-if="attachments.length > 0" class="composer-attachments">
<div v-for="(att, index) in attachments" :key="att.id" class="composer-attachment">
<img :src="att.previewUrl" alt="" class="composer-attachment-thumb">
<button
type="button"
class="composer-attachment-remove"
:aria-label="`Remove image ${index + 1}`"
title="Remove"
@click="removeAttachment(index)"
>
<X :size="12" aria-hidden="true" />
</button>
</div>
</div>
<textarea <textarea
ref="sizer" ref="sizer"
class="composer-sizer" class="composer-sizer"
@@ -150,6 +247,26 @@ onBeforeUnmount(() => {
<div class="composer-actions"> <div class="composer-actions">
<span class="composer-hint">Enter sends, Shift+Enter adds a line.</span> <span class="composer-hint">Enter sends, Shift+Enter adds a line.</span>
<div class="composer-buttons"> <div class="composer-buttons">
<input
ref="fileInput"
type="file"
class="sr-only"
accept="image/png,image/jpeg,image/gif,image/webp"
multiple
tabindex="-1"
aria-hidden="true"
@change="onFilesChosen"
>
<button
v-if="canAttach"
type="button"
class="icon-btn"
aria-label="Attach images"
title="Attach images, or paste one into the message"
@click="pickFiles"
>
<ImagePlus :size="16" aria-hidden="true" />
</button>
<button <button
type="button" type="button"
class="icon-btn" class="icon-btn"
@@ -162,13 +279,13 @@ onBeforeUnmount(() => {
<button <button
type="button" type="button"
class="btn btn-primary btn-sm" class="btn btn-primary btn-sm"
:disabled="!text.trim() || sending" :disabled="(!text.trim() && attachments.length === 0) || sending || uploading"
aria-label="Send message" aria-label="Send message"
title="Send" title="Send"
@click="send" @click="send"
> >
<Send :size="14" aria-hidden="true" /> <Send :size="14" aria-hidden="true" />
{{ sending ? 'Sending' : 'Send' }} {{ sending ? 'Sending' : uploading ? 'Uploading' : 'Send' }}
</button> </button>
</div> </div>
</div> </div>
+19 -1
View File
@@ -5,7 +5,12 @@ import { fullTime, relativeTime } from '~/utils/format'
import { memberColorVar } from '~/utils/member' import { memberColorVar } from '~/utils/member'
import { renderMarkdown } from '~/utils/markdown' import { renderMarkdown } from '~/utils/markdown'
const props = defineProps<{ message: Message; color?: string | null; avatar?: string | null }>() const props = defineProps<{
message: Message
roomId: string
color?: string | null
avatar?: string | null
}>()
const html = computed(() => renderMarkdown(props.message.text)) const html = computed(() => renderMarkdown(props.message.text))
const style = computed(() => ({ '--member': memberColorVar(props.color) })) const style = computed(() => ({ '--member': memberColorVar(props.color) }))
@@ -32,6 +37,19 @@ const style = computed(() => ({ '--member': memberColorVar(props.color) }))
<span class="msg-time" :title="fullTime(message.created_at)">{{ relativeTime(message.created_at) }}</span> <span class="msg-time" :title="fullTime(message.created_at)">{{ relativeTime(message.created_at) }}</span>
</div> </div>
<div class="msg-text" v-html="html"></div> <div class="msg-text" v-html="html"></div>
<div v-if="message.attachments?.length" class="msg-attachments">
<a
v-for="att in message.attachments"
:key="att.id"
class="msg-attachment"
:href="`/api/rooms/${roomId}/attachments/${att.id}`"
target="_blank"
rel="noopener"
:aria-label="`Open attached image, ${att.mime.replace('image/', '')}, ${Math.ceil(att.size / 1024)} KB`"
>
<img :src="`/api/rooms/${roomId}/attachments/${att.id}`" alt="" loading="lazy">
</a>
</div>
</div> </div>
</div> </div>
</template> </template>
+2
View File
@@ -837,6 +837,7 @@ onBeforeUnmount(() => {
<ChatMessage <ChatMessage
v-if="entry.kind === 'message'" v-if="entry.kind === 'message'"
:message="entry.message" :message="entry.message"
:room-id="roomId"
:color="colorFor(entry.message)" :color="colorFor(entry.message)"
:avatar="avatarFor(entry.message)" :avatar="avatarFor(entry.message)"
/> />
@@ -873,6 +874,7 @@ onBeforeUnmount(() => {
<ChatComposer <ChatComposer
:room-id="roomId" :room-id="roomId"
:can-attach="detail?.room.model_vision === true"
@sent="onSent" @sent="onSent"
@typing="onTyping" @typing="onTyping"
@resized="onComposerResized" @resized="onComposerResized"
+16
View File
@@ -14,6 +14,12 @@ export interface BootstrapResponse {
preview_origin: string preview_origin: string
} }
export interface MessageAttachment {
id: string
mime: string
size: number
}
export interface Message { export interface Message {
seq: number seq: number
id: string id: string
@@ -23,6 +29,15 @@ export interface Message {
text: string text: string
mentions: boolean mentions: boolean
created_at: number created_at: number
attachments?: MessageAttachment[]
}
export interface UploadedAttachment extends MessageAttachment {
previewUrl: string
}
export interface UploadAttachmentResponse {
attachment: MessageAttachment
} }
export interface MessagePage { export interface MessagePage {
@@ -56,6 +71,7 @@ export interface Room {
workspace: string workspace: string
repo_url: string | null repo_url: string | null
model: string | null model: string | null
model_vision: boolean | null
max_turn_steps: number max_turn_steps: number
created_at: number created_at: number
archived_at: number | null archived_at: number | null