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

+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();