feat: file/image upload + separated framework root (sessions/data/uploads)

- POST /api/uploads: base64 -> shared ~/.strata-ctl/uploads store (uuid+ext),
  content-sniffed kind (image/text/binary), text token-counted via the model
  tokenizer; metadata persisted in a new uploads table.
- Chat attachments routed by kind: images -> Vision bridge (multipart image_url),
  small text (<=2000 tokens) inlined, large text/binary -> path + shell_exec
  reminder; binaries never inlined. Attachment context persisted with the turn.
- GUI: attach button + file picker, removable chips, attachments sent with the
  turn and shown on the user bubble; cleared on session switch.
- Framework root ~/.strata-ctl separated by type: sessions/<name>/, data/ (SQLite,
  moved from ~/.config/strata-ctl), uploads/. Legacy DB copied once on first run.
- count_tokens seam on Formatter (real tokenizer override) + ChatService.
- i18n: upload errors + attachment markers (backend) and attach.* (GUI), it+en.
- 121 tests + 2 ignored; clippy/fmt clean; validated live (upload routing, real
  tokenizer count, image->Vision answered "Rosso", new layout).
This commit is contained in:
adm committed 2026-11-25 16:25:55 +01:00
1 parent 498e3dbc1b
commit 65f8111ba2
19 files changed
+672 -47

No files matched your search

+6
View File
@@ -69,6 +69,12 @@ pub trait Formatter: Send + Sync {
2048
}
/// Token count of a text, used to route uploads (small-text inline threshold).
/// Default is a byte-length estimate; dialects with a real tokenizer override.
fn count_tokens(&self, text: &str) -> usize {
text.len()
}
/// Render the conversation to a prompt and derive the engine request.
/// Errors map straight to an HTTP 400.
fn build_prompt(&self, req: &ChatRequest) -> Result<Prompt, ApiErrorEnvelope>;
+1
View File
@@ -11,6 +11,7 @@ pub mod service;
mod sessions;
pub mod stop;
pub mod types;
mod uploads;
mod web;
pub use formatter::{Decoder, Formatter, Piece, Prompt};
+3 -1
View File
@@ -15,7 +15,7 @@ use std::sync::Arc;
use super::anthropic::{self, AnthropicRequest, AnthropicStream};
use super::service::ChatService;
use super::types::{ApiErrorEnvelope, ChatRequest, ModelCard, ModelList};
use super::{sessions, web};
use super::{sessions, uploads, web};
use crate::store::Store;
/// Build the router. Mount this inside any axum `Router` or serve it directly.
@@ -80,6 +80,7 @@ fn build_router(state: AppState, auth: AuthConfig) -> Router {
)
.route("/api/sessions/{id}/messages", get(sessions::get_messages))
.route("/api/sessions/{id}/chat", post(sessions::session_chat))
.route("/api/uploads", post(uploads::upload))
.route(
"/api/settings/defaults",
get(sessions::get_defaults).put(sessions::put_defaults),
@@ -178,6 +179,7 @@ pub(crate) struct AppState {
}
/// An OpenAI error with the HTTP status the code implies.
#[derive(Debug)]
pub struct Error {
status: StatusCode,
body: ApiErrorEnvelope,
+5
View File
@@ -38,6 +38,11 @@ impl ChatService {
self.fmt.model_name()
}
/// Token count of a text via the formatter's tokenizer (upload routing).
pub fn count_tokens(&self, text: &str) -> usize {
self.fmt.count_tokens(text)
}
/// One-shot completion.
pub async fn complete(&self, req: &ChatRequest) -> Result<ChatResponse, ApiErrorEnvelope> {
let mut prompt = self.build_prompt_blocking(req).await?;
+46 -8
View File
@@ -17,6 +17,7 @@ use serde::Deserialize;
use super::routes::{AppState, Error};
use super::types::{ChatChunk, ChatMessage, ChatRequest, FunctionCall, Role, ToolCall, Usage};
use super::uploads;
use crate::agent::shell::{HostShell, ShellRunner};
use crate::agent::{self, AgentEvent};
use crate::i18n::t;
@@ -25,7 +26,7 @@ use crate::store::{NewMessage, Session, SessionSettings, Stats, Store, StoredMes
use tokio_stream::wrappers::UnboundedReceiverStream;
/// Run a synchronous store operation off the async runtime.
async fn with_store<T, F>(st: &AppState, f: F) -> Result<T, Error>
pub(crate) async fn with_store<T, F>(st: &AppState, f: F) -> Result<T, Error>
where
F: FnOnce(Arc<dyn Store>) -> anyhow::Result<T> + Send + 'static,
T: Send + 'static,
@@ -69,6 +70,9 @@ pub(crate) struct SessionChat {
/// Run the model as an agent with the `shell_exec` tool (host mode).
#[serde(default)]
agent: bool,
/// Uploaded file ids to attach to this turn (routed by kind/token count).
#[serde(default)]
attachments: Vec<String>,
#[serde(default)]
max_tokens: Option<u32>,
#[serde(default)]
@@ -208,7 +212,13 @@ fn text_message(role: Role, text: String) -> ChatMessage {
/// Rebuild a stateless [`ChatRequest`] from the stored history plus the new turn.
/// Prior `reasoning_content` is deliberately NOT replayed into the prompt.
fn build_request(sess: &Session, history: &[StoredMessage], body: &SessionChat) -> ChatRequest {
fn build_request(
sess: &Session,
history: &[StoredMessage],
body: &SessionChat,
extra: &str,
images: &[serde_json::Value],
) -> ChatRequest {
let mut messages = Vec::new();
// Structural identity reminder: always present, not an editable setting. It
// tells the agent its name and personal workspace folder.
@@ -228,7 +238,24 @@ fn build_request(sess: &Session, history: &[StoredMessage], body: &SessionChat)
.and_then(|s| serde_json::from_str(s).ok());
messages.push(msg);
}
messages.push(text_message(Role::User, body.content.clone()));
// The user turn: typed text + attachment context (inline files / path
// reminders / image markers). Images become multipart image_url parts that
// the Vision bridge materializes; without images it stays a plain string.
let user_text = format!("{}{}", body.content, extra);
if images.is_empty() {
messages.push(text_message(Role::User, user_text));
} else {
let mut parts = vec![serde_json::json!({"type": "text", "text": user_text})];
parts.extend(images.iter().cloned());
messages.push(ChatMessage {
role: Role::User,
content: Some(serde_json::Value::Array(parts)),
tool_call_id: None,
tool_calls: None,
name: None,
reasoning_content: None,
});
}
ChatRequest {
model: sess.model.clone(),
messages,
@@ -339,7 +366,7 @@ pub(crate) async fn session_chat(
// workspace folder (its identity). Done before building the prompt so the
// identity reminder can reference the folder.
if history.is_empty() {
let root = st.workspace_root.clone();
let root = st.workspace_root.join("sessions");
let title = sess.title.clone();
let idc = id.clone();
if let Ok(folder) = with_store(&st, move |s| {
@@ -362,10 +389,20 @@ pub(crate) async fn session_chat(
}
}
let mut req = build_request(&sess, &history, &body);
// Resolve attachments (upload ids) into metadata and route by kind/tokens.
let mut metas = Vec::new();
for aid in &body.attachments {
let aid = aid.clone();
if let Ok(Some(m)) = with_store(&st, move |s| s.get_upload(&aid)).await {
metas.push(m);
}
}
let extra = uploads::context_text(&metas);
let images = uploads::image_parts(&metas);
let mut req = build_request(&sess, &history, &body, &extra, &images);
// Persist the user turn before generating.
let user_content = body.content.clone();
// Persist the user turn (text + attachment context) before generating.
let user_content = format!("{}{}", body.content, extra);
if let Err(e) = with_store(&st, {
let id = id.clone();
move |s| {
@@ -556,11 +593,12 @@ mod tests {
content: "ciao".into(),
stream: false,
agent: false,
attachments: Vec::new(),
max_tokens: None,
temperature: None,
top_p: None,
};
let req = build_request(&sess, &[], &body);
let req = build_request(&sess, &[], &body, "", &[]);
// Identity reminder first (name + folder), then the session SP, then user.
assert!(matches!(req.messages[0].role, Role::System));
let t0 = req.messages[0].text().unwrap();
+239
View File
@@ -0,0 +1,239 @@
//! File/image uploads for the GUI.
//!
//! Bytes land in a single shared on-disk store (`<workspace_root>/uploads`,
//! filename converted to a uuid keeping the extension); metadata is persisted.
//! Content is classified by *sniffing* (not extension) and routed at chat time:
//! images go through the Vision bridge, small text is inlined into context,
//! large text and binaries are handed to the agent as a path (it reads
//! selectively via `shell_exec`). "Small" is measured in model tokens, never
//! characters. Binaries never enter the context directly.
use std::sync::atomic::{AtomicU64, Ordering};
use std::time::{SystemTime, UNIX_EPOCH};
use axum::extract::State;
use axum::response::Json;
use base64::Engine;
use serde::Deserialize;
use serde_json::{json, Value as JsonValue};
use super::routes::{AppState, Error};
use super::sessions::with_store;
use crate::i18n::t;
use crate::store::UploadMeta;
/// Cap on an uploaded file body.
const MAX_UPLOAD_BYTES: usize = 32 * 1024 * 1024;
/// Text files at or below this token count are inlined into context; larger ones
/// are handed to the agent as a path. A knob, not a dogma.
pub const INLINE_TOKEN_THRESHOLD: u32 = 2000;
#[derive(Deserialize)]
pub(crate) struct UploadRequest {
name: String,
/// File bytes as base64 (raw, or a `data:...;base64,` URL).
data: String,
}
/// Unique filename stem without a `uuid` dependency (nanos + counter).
fn unique_stem() -> String {
static COUNTER: AtomicU64 = AtomicU64::new(0);
let nanos = SystemTime::now()
.duration_since(UNIX_EPOCH)
.map(|d| d.as_nanos())
.unwrap_or(0);
let n = COUNTER.fetch_add(1, Ordering::Relaxed);
format!("{nanos:016x}{n:08x}")
}
/// Magic-byte image detection (formats the Vision bridge reads or normalizes).
fn image_ext(data: &[u8]) -> Option<&'static str> {
if data.starts_with(&[0x89, b'P', b'N', b'G', b'\r', b'\n', 0x1a, b'\n']) {
Some(".png")
} else if data.starts_with(&[0xff, 0xd8, 0xff]) {
Some(".jpg")
} else if data.starts_with(b"GIF") {
Some(".gif")
} else if data.starts_with(b"BM") {
Some(".bmp")
} else if data.len() >= 12 && &data[0..4] == b"RIFF" && &data[8..12] == b"WEBP" {
Some(".webp")
} else {
None
}
}
/// Classify by content: image (magic bytes), text (valid UTF-8, no NUL), else
/// binary. The extension is irrelevant to the decision.
pub fn sniff_kind(data: &[u8]) -> &'static str {
if image_ext(data).is_some() {
"image"
} else if !data.contains(&0) && std::str::from_utf8(data).is_ok() {
"text"
} else {
"binary"
}
}
/// Whether an attachment is inlined into context (small text) rather than handed
/// to the agent as a path. Images go through Vision; binaries never inline.
pub fn routes_inline(kind: &str, tokens: u32) -> bool {
kind == "text" && tokens <= INLINE_TOKEN_THRESHOLD
}
/// Text appended to the user turn for attachments: inline small text files,
/// path reminders for large/binary files, markers for images. Used both for the
/// live prompt and for persistence, so context survives across turns.
pub fn context_text(metas: &[UploadMeta]) -> String {
let mut s = String::new();
for m in metas {
if m.kind == "image" {
s.push_str(&t("upload.image_marker", &[("name", &m.original_name)]));
} else if routes_inline(&m.kind, m.tokens) {
let content = std::fs::read_to_string(&m.path).unwrap_or_default();
s.push_str(&t(
"upload.inline_file",
&[("name", &m.original_name), ("content", &content)],
));
} else {
s.push_str(&t(
"upload.path_file",
&[("name", &m.original_name), ("path", &m.path)],
));
}
}
s
}
/// `image_url` parts for the live request; the Vision bridge reads the local path.
pub fn image_parts(metas: &[UploadMeta]) -> Vec<JsonValue> {
metas
.iter()
.filter(|m| m.kind == "image")
.map(|m| json!({"type": "image_url", "image_url": {"url": m.path}}))
.collect()
}
/// A safe extension taken from the original name, if present and sane.
fn original_ext(name: &str) -> Option<String> {
let ext = name.rsplit_once('.')?.1;
if !ext.is_empty() && ext.len() <= 8 && ext.chars().all(|c| c.is_ascii_alphanumeric()) {
Some(format!(".{}", ext.to_ascii_lowercase()))
} else {
None
}
}
fn decode_data(data: &str) -> Result<Vec<u8>, Error> {
let b64 = match data.strip_prefix("data:") {
Some(rest) => rest.split_once(',').map(|(_, d)| d).unwrap_or(rest),
None => data,
};
base64::engine::general_purpose::STANDARD
.decode(b64.trim())
.map_err(|_| Error::bad_request(t("upload.bad_base64", &[])))
}
/// `POST /api/uploads` — store a file and return its metadata (kind, tokens, path).
pub(crate) async fn upload(
State(st): State<AppState>,
Json(body): Json<UploadRequest>,
) -> Result<Json<UploadMeta>, Error> {
let bytes = decode_data(&body.data)?;
if bytes.is_empty() {
return Err(Error::bad_request(t("upload.empty", &[])));
}
if bytes.len() > MAX_UPLOAD_BYTES {
return Err(Error::bad_request(t("upload.too_large", &[])));
}
let kind = sniff_kind(&bytes);
let ext = match kind {
"image" => image_ext(&bytes).unwrap_or(".png").to_string(),
"text" => original_ext(&body.name).unwrap_or_else(|| ".txt".to_string()),
_ => original_ext(&body.name).unwrap_or_else(|| ".bin".to_string()),
};
let id = format!("{}{}", unique_stem(), ext);
let dir = st.workspace_root.join("uploads");
let path = dir.join(&id);
let size = bytes.len() as u64;
let kind_s = kind.to_string();
let svc = st.service.clone();
// File write + token count run off the async runtime (tokenizer can be heavy).
let (path_str, tokens) =
tokio::task::spawn_blocking(move || -> anyhow::Result<(String, u32)> {
std::fs::create_dir_all(&dir)?;
std::fs::write(&path, &bytes)?;
let tokens = if kind_s == "text" {
svc.count_tokens(&String::from_utf8_lossy(&bytes)) as u32
} else {
0
};
Ok((path.to_string_lossy().into_owned(), tokens))
})
.await
.map_err(|e| Error::internal(format!("upload task failed: {e}")))?
.map_err(|e| Error::internal(format!("upload write failed: {e}")))?;
let meta = UploadMeta {
id,
original_name: body.name,
path: path_str,
kind: kind.to_string(),
tokens,
size,
created_at: SystemTime::now()
.duration_since(UNIX_EPOCH)
.map(|d| d.as_secs() as i64)
.unwrap_or(0),
};
let m = meta.clone();
with_store(&st, move |s| s.save_upload(&m)).await?;
Ok(Json(meta))
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn sniff_by_content_not_extension() {
assert_eq!(sniff_kind(b"hello world"), "text");
assert_eq!(sniff_kind("ciao àèì".as_bytes()), "text");
assert_eq!(
sniff_kind(&[0x89, b'P', b'N', b'G', b'\r', b'\n', 0x1a, b'\n']),
"image"
);
assert_eq!(sniff_kind(&[0xff, 0xd8, 0xff, 0x00]), "image");
assert_eq!(sniff_kind(b"\x7fELF\x00\x01"), "binary"); // ELF magic, has NUL
assert_eq!(sniff_kind(&[0x00, 0x01, 0x02]), "binary"); // NUL -> binary
assert_eq!(sniff_kind(&[0xff, 0xfe, 0xfd]), "binary"); // invalid UTF-8
}
#[test]
fn extension_sanitized() {
assert_eq!(original_ext("note.TXT").as_deref(), Some(".txt"));
assert_eq!(original_ext("archive.tar.gz").as_deref(), Some(".gz"));
assert_eq!(original_ext("noext"), None);
assert_eq!(original_ext("bad./etc/passwd"), None);
assert_eq!(original_ext("file.verylongext"), None);
}
#[test]
fn inline_routing_by_tokens() {
assert!(routes_inline("text", 100));
assert!(routes_inline("text", INLINE_TOKEN_THRESHOLD));
assert!(!routes_inline("text", INLINE_TOKEN_THRESHOLD + 1));
assert!(!routes_inline("binary", 0));
assert!(!routes_inline("image", 0));
}
#[test]
fn decode_raw_and_data_url() {
let raw = base64::engine::general_purpose::STANDARD.encode(b"ciao");
assert_eq!(decode_data(&raw).unwrap(), b"ciao");
let url = format!("data:text/plain;base64,{raw}");
assert_eq!(decode_data(&url).unwrap(), b"ciao");
assert!(decode_data("!!!not base64!!!").is_err());
}
}