diff --git a/README.md b/README.md index 073ec02..05d685a 100644 --- a/README.md +++ b/README.md @@ -102,6 +102,8 @@ offline, same-origin so no CORS). It is a thin client over a **session-aware API their token usage. - `GET /api/stats` — aggregate counters (sessions, messages, prompt/completion tokens). - `GET/PUT /api/settings/defaults` — the global default settings template. +- `POST /api/uploads` — store an uploaded file (base64) in the shared upload dir; + returns metadata (kind, token count, path). Attach the returned id to a chat turn. - `PATCH /api/sessions/{id}` — rename (only before the first interaction) and/or replace the session's own settings instance. @@ -112,19 +114,34 @@ affects only *future* sessions — no retroactive surprises. The user jots the chat's purpose in **notes**. The framework assigns an evocative name (a curated word list); it is editable only before the first interaction, then **immutable**. At that first interaction a personal workspace folder is created -(`~/.strata-ctl//`, configurable via `workspace_root`) and a structural -identity reminder ("your name is …, your personal folder is …") is prepended to -the model's context — not an editable setting. The GUI exposes all of this in a -⚙️ settings panel (per-session or general). +(`~/.strata-ctl/sessions//`, under the configurable `workspace_root`) and a +structural identity reminder ("your name is …, your personal folder is …") is +prepended to the model's context — not an editable setting. The GUI exposes all of +this in a ⚙️ settings panel (per-session or general). + +**Uploads.** The 📎 button attaches files and images. Bytes land in a single +**shared** store (`~/.strata-ctl/uploads/`, filename converted to a uuid keeping the +extension); nothing is bulk-injected into context. Content is classified by +*sniffing* (not extension) and routed: **images** go through the Vision bridge +(pixels, not a path); **small text** (≤ ~2000 tokens, measured with the model's own +tokenizer) is inlined; **large text and binaries** are handed to the agent as a path +with a reminder to inspect them selectively via `shell_exec` — binaries never enter +the context directly. The `shell_exec` output cap is a second safety net. The standard `/v1` API stays **stateless**; conversation context lives server-side -in an embedded **SQLite** database (default `~/.config/strata-ctl/sessions.db`, +in an embedded **SQLite** database (default `~/.strata-ctl/data/sessions.db`, override with `db_path`). Storage sits behind a `Store` trait so it can be swapped (the planned direction is **ArangoDB**, multi-model: KV / documents / graphs / vector indexes) or complemented by another DBMS for advanced analytics later, without touching the API or the GUI. This is the foundation for multi-session, statistics and advanced settings to grow on top. +**Framework root.** All persistent state lives under `~/.strata-ctl/` (the Linux +user's home; override with `workspace_root`), separated by content type: +`sessions//` (agent workspace folders), `data/` (the SQLite database), +`uploads/` (uploaded files). A legacy DB at `~/.config/strata-ctl/sessions.db` is +copied into `data/` once on first run (the original is left in place). + ## Agent mode The GUI model can **act**, not just chat. Toggle the 🤖 button and the model runs as @@ -188,8 +205,10 @@ uses `tracing`; set `RUST_LOG` to control verbosity (default `info`). The config is the same JSON the other Strata tools use. Keys acted on here include `exe`, `args`, `cwd`, `tokenizer`, `model_name`, `host`, `port`, `reasoning_effort`, -`sampling`, `api_key`, `allowed_hosts`, `db_path` (GUI session database), and the -optional `startup_timeout_secs` / `silence_timeout_secs`. Everything else (`arch`, +`sampling`, `api_key`, `allowed_hosts`, `db_path` (GUI session database), +`workspace_root` (framework root), `system_prompt` (general default), `language` +(UI/prompt catalog, default `it`), and the optional `startup_timeout_secs` / +`silence_timeout_secs`. Everything else (`arch`, `mcp_servers`, `cors_origins`, …) is preserved untouched and reported as ignored — unknown keys never break startup. @@ -210,10 +229,11 @@ later adaptation round. ## Status -Working and tested (115 tests, plus 2 real-file tests run on demand). Text, images, +Working and tested (121 tests, plus 2 real-file tests run on demand). Text, images, the full client-side tool loop, the Anthropic endpoint, the web GUI (session -context, streaming, stats) and **agent mode** (the model using `shell_exec` on the -host) have been validated live against the real Inkling engine. +context, streaming, stats, **file/image upload**) and **agent mode** (the model +using `shell_exec` on the host) have been validated live against the real Inkling +engine. Not yet implemented (honest gaps): forced `tool_choice` (`required` / named function returns a clear 400), multi-slot batching, logprobs / structured output, automatic @@ -221,9 +241,10 @@ engine restart after a crash, a full SSRF guard against DNS rebinding, and the OpenAI Responses native endpoint. The Anthropic adapter covers the core cases but not yet the `defer_loading` / `tool_addition` / `tool_reference` tool machinery, the thinking `budget_tokens` mapping, or prompt-cache token accounting. The GUI agent's -**isolated mode** (Docker-container runner) and GUI file/image upload are still to -come; base/host agent mode, per-session settings (copy-on-create), session notes, -immutable names and personal workspace folders work. +**isolated mode** (Docker-container runner) is still to come; base/host agent mode, +per-session settings (copy-on-create), session notes, immutable names, personal +workspace folders and file/image upload (shared store, token-based routing, +images via Vision) work. ## License and credits diff --git a/locales/en.json b/locales/en.json index 93553ad..a4712a3 100644 --- a/locales/en.json +++ b/locales/en.json @@ -3,5 +3,11 @@ "identity.folder": " Your personal folder is {folder}.", "error.name_locked": "The session name is immutable after the first interaction.", "error.name_empty": "The name must not be empty.", - "error.session_not_found": "Session not found." + "error.session_not_found": "Session not found.", + "upload.bad_base64": "Invalid file data (base64).", + "upload.empty": "The file is empty.", + "upload.too_large": "The file exceeds the maximum allowed size.", + "upload.image_marker": "\n\n[Attached image: {name}]", + "upload.inline_file": "\n\n[File: {name}]\n{content}", + "upload.path_file": "\n\n[Attached file: {name} — path: {path}. Use shell_exec to inspect it selectively, do not dump it all into context.]" } \ No newline at end of file diff --git a/locales/it.json b/locales/it.json index 56b5d24..396b8fd 100644 --- a/locales/it.json +++ b/locales/it.json @@ -3,5 +3,11 @@ "identity.folder": " La tua cartella personale è {folder}.", "error.name_locked": "Il nome della sessione è immutabile dopo la prima interazione.", "error.name_empty": "Il nome non può essere vuoto.", - "error.session_not_found": "Sessione non trovata." + "error.session_not_found": "Sessione non trovata.", + "upload.bad_base64": "Dati del file non validi (base64).", + "upload.empty": "Il file è vuoto.", + "upload.too_large": "Il file supera la dimensione massima consentita.", + "upload.image_marker": "\n\n[Immagine allegata: {name}]", + "upload.inline_file": "\n\n[File: {name}]\n{content}", + "upload.path_file": "\n\n[File allegato: {name} — percorso: {path}. Usa shell_exec per ispezionarlo selettivamente, non riversarlo tutto nel contesto.]" } \ No newline at end of file diff --git a/src/api/formatter.rs b/src/api/formatter.rs index 68438ac..c7e2d05 100644 --- a/src/api/formatter.rs +++ b/src/api/formatter.rs @@ -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; diff --git a/src/api/mod.rs b/src/api/mod.rs index 9cfae42..40da299 100644 --- a/src/api/mod.rs +++ b/src/api/mod.rs @@ -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}; diff --git a/src/api/routes.rs b/src/api/routes.rs index 4017362..63a3127 100644 --- a/src/api/routes.rs +++ b/src/api/routes.rs @@ -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, diff --git a/src/api/service.rs b/src/api/service.rs index c170314..f9e77e6 100644 --- a/src/api/service.rs +++ b/src/api/service.rs @@ -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 { let mut prompt = self.build_prompt_blocking(req).await?; diff --git a/src/api/sessions.rs b/src/api/sessions.rs index 8fbd788..424a93e 100644 --- a/src/api/sessions.rs +++ b/src/api/sessions.rs @@ -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(st: &AppState, f: F) -> Result +pub(crate) async fn with_store(st: &AppState, f: F) -> Result where F: FnOnce(Arc) -> anyhow::Result + 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, #[serde(default)] max_tokens: Option, #[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(); diff --git a/src/api/uploads.rs b/src/api/uploads.rs new file mode 100644 index 0000000..dfe87b7 --- /dev/null +++ b/src/api/uploads.rs @@ -0,0 +1,239 @@ +//! File/image uploads for the GUI. +//! +//! Bytes land in a single shared on-disk store (`/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 { + 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 { + 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, 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, + Json(body): Json, +) -> Result, 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()); + } +} diff --git a/src/config.rs b/src/config.rs index f96b075..cbcb20f 100644 --- a/src/config.rs +++ b/src/config.rs @@ -84,7 +84,9 @@ pub struct Config { #[serde(default)] pub system_prompt: Option, - /// Parent of the per-session personal workspace folders (default `~/.strata-ctl`). + /// Framework root (default `~/.strata-ctl`, the Linux user's home). Content + /// is separated into subfolders by type: `sessions/` (agent workspace + /// folders), `data/` (SQLite), `uploads/` (uploaded files). #[serde(default)] pub workspace_root: Option, @@ -109,7 +111,7 @@ pub struct Config { pub allowed_hosts: Option>, /// Path to the GUI session database (SQLite). Defaults to - /// `~/.config/strata-ctl/sessions.db`. + /// `/data/sessions.db`. #[serde(default)] pub db_path: Option, @@ -209,13 +211,12 @@ impl Config { Duration::from_secs(self.silence_timeout_secs.unwrap_or(600)) } - /// Effective GUI database path: config > `~/.config/strata-ctl/sessions.db`. + /// Effective GUI database path: config > `/data/sessions.db`. pub fn gui_db_path(&self) -> PathBuf { if let Some(p) = &self.db_path { return PathBuf::from(p); } - let home = std::env::var("HOME").unwrap_or_default(); - PathBuf::from(home).join(".config/strata-ctl/sessions.db") + self.data_dir().join("sessions.db") } /// The global default settings template for new GUI sessions, seeded from @@ -232,8 +233,8 @@ impl Config { } } - /// Effective workspace root: config > `~/.strata-ctl`. Each session's - /// personal folder is created under this root at its first interaction. + /// Effective framework root: config > `~/.strata-ctl` (the Linux user's + /// home). Content is separated into subfolders by type. pub fn workspace_root(&self) -> PathBuf { if let Some(p) = &self.workspace_root { return PathBuf::from(p); @@ -242,6 +243,21 @@ impl Config { PathBuf::from(home).join(".strata-ctl") } + /// Per-session personal workspace folders: `/sessions/`. + pub fn sessions_dir(&self) -> PathBuf { + self.workspace_root().join("sessions") + } + + /// SQLite store directory: `/data`. + pub fn data_dir(&self) -> PathBuf { + self.workspace_root().join("data") + } + + /// Shared upload store: `/uploads`. + pub fn upload_dir(&self) -> PathBuf { + self.workspace_root().join("uploads") + } + /// Effective language: config > `it`. pub fn language(&self) -> String { self.language.clone().unwrap_or_else(|| "it".to_string()) @@ -396,10 +412,21 @@ mod tests { #[test] fn gui_db_path_default_and_override() { let cfg = Config::parse(REAL, "test").unwrap(); - assert!(cfg - .gui_db_path() - .ends_with(".config/strata-ctl/sessions.db")); + assert!(cfg.gui_db_path().ends_with(".strata-ctl/data/sessions.db")); let cfg2 = Config::parse(r#"{"exe":"/x/e","db_path":"/tmp/x.db"}"#, "test").unwrap(); assert_eq!(cfg2.gui_db_path(), PathBuf::from("/tmp/x.db")); } + + #[test] + fn framework_root_separates_content_types() { + let cfg = Config::parse(r#"{"exe":"/x/e","workspace_root":"/tmp/fwk"}"#, "test").unwrap(); + assert_eq!(cfg.workspace_root(), PathBuf::from("/tmp/fwk")); + assert_eq!(cfg.sessions_dir(), PathBuf::from("/tmp/fwk/sessions")); + assert_eq!(cfg.data_dir(), PathBuf::from("/tmp/fwk/data")); + assert_eq!(cfg.upload_dir(), PathBuf::from("/tmp/fwk/uploads")); + assert_eq!( + cfg.gui_db_path(), + PathBuf::from("/tmp/fwk/data/sessions.db") + ); + } } diff --git a/src/inkling/formatter.rs b/src/inkling/formatter.rs index 2041a9c..deef379 100644 --- a/src/inkling/formatter.rs +++ b/src/inkling/formatter.rs @@ -69,6 +69,13 @@ impl Formatter for InklingFormatter { self.max_new_default } + fn count_tokens(&self, text: &str) -> usize { + self.tok + .encode(text) + .map(|v| v.len()) + .unwrap_or_else(|_| text.len()) + } + fn build_prompt(&self, req: &ChatRequest) -> Result { let mut msgs = Self::messages_json(req); prepare_messages(&mut msgs); diff --git a/src/main.rs b/src/main.rs index dd3d71b..12306d5 100644 --- a/src/main.rs +++ b/src/main.rs @@ -180,6 +180,7 @@ async fn serve(cfg: &Config, cli_host: Option<&str>, cli_port: Option) -> E // Open the GUI session store (SQLite). The web GUI + session API are mounted // only when this succeeds; the standard /v1 API is unaffected either way. let db_path = cfg.gui_db_path(); + migrate_legacy_db(&db_path); let store: Arc = match SqliteStore::open(&db_path) { Ok(s) => Arc::new(s), Err(e) => { @@ -266,6 +267,39 @@ fn print_plan(cfg: &Config, path: &std::path::Path, cli_host: Option<&str>, cli_ } } +/// One-time relocation of the session DB from the old default +/// (`~/.config/strata-ctl/sessions.db`) into the framework `data/` dir. Copies +/// (never deletes) the legacy file plus any WAL/SHM siblings, so existing +/// history is preserved. A no-op once the new path exists or no legacy DB is +/// present. +fn migrate_legacy_db(db_path: &Path) { + if db_path.exists() { + return; + } + let home = std::env::var("HOME").unwrap_or_default(); + let legacy = Path::new(&home).join(".config/strata-ctl/sessions.db"); + if !legacy.exists() || legacy == db_path { + return; + } + if let Some(parent) = db_path.parent() { + let _ = std::fs::create_dir_all(parent); + } + for suffix in ["", "-wal", "-shm"] { + let mut from = legacy.as_os_str().to_os_string(); + from.push(suffix); + let mut to = db_path.as_os_str().to_os_string(); + to.push(suffix); + if Path::new(&from).exists() { + let _ = std::fs::copy(&from, &to); + } + } + tracing::info!( + from = %legacy.display(), + to = %db_path.display(), + "relocated legacy session database into the framework data dir" + ); +} + fn report_config_error(path: &std::path::Path, err: ConfigError) -> ExitCode { eprintln!("error: {err}"); if let ConfigError::MissingExe = err { diff --git a/src/store.rs b/src/store.rs index 4420b70..ea854d9 100644 --- a/src/store.rs +++ b/src/store.rs @@ -120,6 +120,21 @@ pub struct Stats { pub completion_tokens: u64, } +/// Metadata for an uploaded file (bytes live on disk under the shared upload dir). +#[derive(Debug, Clone, Serialize)] +pub struct UploadMeta { + /// Stored filename (uuid + extension), unique; resolves the on-disk path. + pub id: String, + pub original_name: String, + pub path: String, + /// "image" | "text" | "binary" — decided by content sniff, not extension. + pub kind: String, + /// Token count for text (0 otherwise), measured with the model tokenizer. + pub tokens: u32, + pub size: u64, + pub created_at: i64, +} + /// The storage interface. Synchronous; call via `spawn_blocking` from async code. pub trait Store: Send + Sync { fn create_session( @@ -141,6 +156,8 @@ pub trait Store: Send + Sync { /// The global default settings template (None until seeded). fn get_defaults(&self) -> Result>; fn set_defaults(&self, settings: &SessionSettings) -> Result<()>; + fn save_upload(&self, meta: &UploadMeta) -> Result<()>; + fn get_upload(&self, id: &str) -> Result>; } fn now_secs() -> i64 { @@ -190,6 +207,15 @@ CREATE TABLE IF NOT EXISTS defaults ( id INTEGER PRIMARY KEY CHECK (id = 1), settings_json TEXT NOT NULL ); +CREATE TABLE IF NOT EXISTS uploads ( + id TEXT PRIMARY KEY, + original_name TEXT NOT NULL, + path TEXT NOT NULL, + kind TEXT NOT NULL, + tokens INTEGER NOT NULL DEFAULT 0, + size INTEGER NOT NULL DEFAULT 0, + created_at INTEGER NOT NULL +); "; /// SQLite-backed store (bundled SQLite, compiled into the binary). WAL mode for @@ -470,6 +496,41 @@ impl Store for SqliteStore { )?; Ok(()) } + + fn save_upload(&self, meta: &UploadMeta) -> Result<()> { + let conn = self.lock(); + conn.execute( + "INSERT OR REPLACE INTO uploads (id, original_name, path, kind, tokens, size, created_at) + VALUES (?1, ?2, ?3, ?4, ?5, ?6, ?7)", + params![ + meta.id, + meta.original_name, + meta.path, + meta.kind, + meta.tokens as i64, + meta.size as i64, + meta.created_at + ], + )?; + Ok(()) + } + + fn get_upload(&self, id: &str) -> Result> { + let conn = self.lock(); + let mut stmt = conn.prepare("SELECT * FROM uploads WHERE id = ?1")?; + let mut rows = stmt.query_map(params![id], |r| { + Ok(UploadMeta { + id: r.get("id")?, + original_name: r.get("original_name")?, + path: r.get("path")?, + kind: r.get("kind")?, + tokens: r.get::<_, i64>("tokens")? as u32, + size: r.get::<_, i64>("size")? as u64, + created_at: r.get("created_at")?, + }) + })?; + Ok(rows.next().transpose()?) + } } #[cfg(test)] diff --git a/tests/api_sessions.rs b/tests/api_sessions.rs index 0726e21..957a670 100644 --- a/tests/api_sessions.rs +++ b/tests/api_sessions.rs @@ -322,6 +322,10 @@ async fn first_interaction_creates_personal_folder() { .folder .expect("personal folder created at first interaction"); assert!(std::path::Path::new(&folder).is_dir()); + assert!( + folder.contains("/sessions/"), + "folder under sessions/: {folder}" + ); assert!(s.name_locked); let _ = std::fs::remove_dir_all(&folder); } @@ -446,3 +450,72 @@ async fn settings_are_copied_on_create_and_isolated() { Some(0.5) ); } + +#[tokio::test] +async fn upload_routes_by_kind_and_attaches_to_chat() { + use base64::Engine; + let (app, store) = build_app().await; + let b64 = |bytes: &[u8]| base64::engine::general_purpose::STANDARD.encode(bytes); + + // Small text file -> kind "text", tokens measured, bytes on disk under uploads/. + let (st, text) = req( + &app, + Method::POST, + "/api/uploads", + Some(serde_json::json!({"name": "nota.txt", "data": b64(b"contenuto di prova")})), + ) + .await; + assert_eq!(st, StatusCode::OK, "{text}"); + let meta: serde_json::Value = serde_json::from_str(&text).unwrap(); + assert_eq!(meta["kind"], "text"); + assert!(meta["tokens"].as_u64().unwrap() > 0); + let path = meta["path"].as_str().unwrap().to_string(); + assert!(std::path::Path::new(&path).is_file()); + assert!(path.contains("/uploads/"), "shared upload dir: {path}"); + let text_id = meta["id"].as_str().unwrap().to_string(); + + // Binary (NUL / invalid UTF-8) -> kind "binary", never inlined. + let (st, text) = req( + &app, + Method::POST, + "/api/uploads", + Some(serde_json::json!({"name": "dat.bin", "data": b64(&[0u8, 1, 2, 255])})), + ) + .await; + assert_eq!(st, StatusCode::OK, "{text}"); + let bin: serde_json::Value = serde_json::from_str(&text).unwrap(); + assert_eq!(bin["kind"], "binary"); + let bin_id = bin["id"].as_str().unwrap().to_string(); + + // Image (PNG magic) -> kind "image" (routed through Vision, not inline text). + let png = [0x89u8, b'P', b'N', b'G', b'\r', b'\n', 0x1a, b'\n', 0, 0]; + let (st, text) = req( + &app, + Method::POST, + "/api/uploads", + Some(serde_json::json!({"name": "foto.png", "data": b64(&png)})), + ) + .await; + assert_eq!(st, StatusCode::OK, "{text}"); + let img: serde_json::Value = serde_json::from_str(&text).unwrap(); + assert_eq!(img["kind"], "image"); + + // Chat attaching text + binary: the persisted user turn carries the inline + // text and the binary path reminder — never the binary bytes themselves. + let id = create_session(&app).await; + let (st, _) = req( + &app, + Method::POST, + &format!("/api/sessions/{id}/chat"), + Some(serde_json::json!({"content": "vedi allegati", "attachments": [text_id, bin_id]})), + ) + .await; + assert_eq!(st, StatusCode::OK); + let msgs = store.messages(&id).unwrap(); + let user = &msgs[0].content; + assert!(user.contains("contenuto di prova"), "inline text: {user}"); + assert!(user.contains("dat.bin"), "binary path reminder: {user}"); + assert!(user.contains("/uploads/"), "path present: {user}"); + + let _ = std::fs::remove_file(&path); +} diff --git a/web/assets/app.css b/web/assets/app.css index 85d9fdf..7c5b330 100644 --- a/web/assets/app.css +++ b/web/assets/app.css @@ -177,6 +177,27 @@ details.thinking .reasoning { } #input:focus { outline: none; border-color: var(--accent); } #send { min-width: 52px; font-size: 1.3rem; } +#attach { min-width: 44px; font-size: 1.2rem; } + +/* ---- Attachment chips (composer + sent user turn) ---- */ +.attachments { + display: flex; flex-wrap: wrap; gap: 6px; + padding: 8px 12px 0; background: var(--panel); +} +.attach-chip { + display: inline-flex; align-items: center; gap: 6px; + max-width: 240px; padding: 4px 8px; + background: var(--panel-2); border: 1px solid var(--border); border-radius: 999px; + font-size: 0.8rem; color: var(--text); +} +.attach-chip .attach-name { overflow: hidden; text-overflow: ellipsis; white-space: nowrap; } +.attach-chip .attach-kind { color: var(--muted); } +.attach-chip button { + border: none; background: transparent; color: var(--muted); + cursor: pointer; font-size: 0.9rem; line-height: 1; padding: 0 2px; +} +.attach-chip button:hover { color: var(--danger); } +.msg-attachments { display: flex; flex-wrap: wrap; gap: 6px; margin-top: 6px; } /* ---- Stats modal ---- */ #stats-modal, #dialog, #settings-modal { diff --git a/web/assets/app.js b/web/assets/app.js index eb133d6..5aade8f 100644 --- a/web/assets/app.js +++ b/web/assets/app.js @@ -5,7 +5,7 @@ const $ = (sel) => document.querySelector(sel); -const state = { sessions: [], current: null, busy: false, agent: false }; +const state = { sessions: [], current: null, busy: false, agent: false, attachments: [] }; // ---- i18n: new user-facing strings go through t(key, params) -------------- // Catalogs are served at /assets/locales/.json; language follows the @@ -52,11 +52,11 @@ async function sendJSON(url, method, body) { } // Stream a chat turn, invoking onDelta for each SSE chunk. -async function streamChat(id, content, onDelta) { +async function streamChat(id, content, attachments, onDelta) { const r = await fetch(`/api/sessions/${id}/chat`, { method: "POST", headers: { "Content-Type": "application/json" }, - body: JSON.stringify({ content, stream: true }), + body: JSON.stringify({ content, stream: true, attachments }), }); if (!r.ok) throw new Error(await r.text()); const reader = r.body.getReader(); @@ -211,6 +211,8 @@ async function loadSessions(selectId) { async function selectSession(id) { state.current = id; + state.attachments = []; + renderAttachments(); const sess = state.sessions.find((s) => s.id === id); $("#session-title").textContent = sess ? sess.title : "Conversazione"; $("#model-name").textContent = sess ? sess.model : ""; @@ -265,24 +267,83 @@ async function deleteSessionById(id) { } } +// ---- Attachments (upload -> shared store; routed server-side by kind) ----- +function attachChip(a, removable) { + const chip = el("span", "attach-chip"); + const icon = a.kind === "image" ? "\u{1F5BC}\u{FE0F}" : a.kind === "binary" ? "\u{1F4E6}" : "\u{1F4C4}"; + chip.appendChild(el("span", "attach-kind", icon)); + chip.appendChild(el("span", "attach-name", a.original_name)); + if (removable) { + const x = el("button", null, "\u{00D7}"); + x.setAttribute("aria-label", t("attach.remove")); + x.addEventListener("click", () => { + state.attachments = state.attachments.filter((m) => m.id !== a.id); + renderAttachments(); + }); + chip.appendChild(x); + } + return chip; +} + +function renderAttachments() { + const box = $("#attachments"); + box.textContent = ""; + box.hidden = state.attachments.length === 0; + for (const a of state.attachments) box.appendChild(attachChip(a, true)); +} + +function readFileAsDataURL(file) { + return new Promise((resolve, reject) => { + const fr = new FileReader(); + fr.onload = () => resolve(fr.result); + fr.onerror = () => reject(fr.error || new Error("read failed")); + fr.readAsDataURL(file); + }); +} + +async function uploadFiles(files) { + for (const file of files) { + try { + const data = await readFileAsDataURL(file); + const meta = await sendJSON("/api/uploads", "POST", { name: file.name, data }); + state.attachments.push(meta); + renderAttachments(); + } catch (e) { + const tr = $("#transcript"); + tr.appendChild(messageNode("assistant", t("attach.error", { msg: e.message }))); + scrollDown(); + } + } +} + async function sendMessage() { const input = $("#input"); const content = input.value.trim(); - if (!content || state.busy || !state.current) return; + const attachments = state.attachments.slice(); + if ((!content && !attachments.length) || state.busy || !state.current) return; state.busy = true; $("#send").disabled = true; input.value = ""; autoGrow(input); + state.attachments = []; + renderAttachments(); const t = $("#transcript"); const empty = t.querySelector(".empty"); if (empty) empty.remove(); - t.appendChild(messageNode("user", content)); + const userNode = messageNode("user", content); + if (attachments.length) { + const row = el("div", "msg-attachments"); + for (const a of attachments) row.appendChild(attachChip(a, false)); + userNode.querySelector(".bubble").appendChild(row); + } + t.appendChild(userNode); scrollDown(); + const ids = attachments.map((a) => a.id); try { - if (state.agent) await agentTurn(content, t); - else await chatTurn(content, t); + if (state.agent) await agentTurn(content, t, ids); + else await chatTurn(content, t, ids); state.sessions = await getJSON("/api/sessions"); renderSessions(); } catch (e) { @@ -296,7 +357,7 @@ async function sendMessage() { } // Plain chat: stream OpenAI chunks into a live assistant bubble. -async function chatTurn(content, t) { +async function chatTurn(content, t, attachments) { const wrap = el("div", "msg assistant"); wrap.appendChild(el("div", "role", "Assistente")); const bubble = el("div", "bubble"); @@ -313,7 +374,7 @@ async function chatTurn(content, t) { scrollDown(); let reasoning = "", text = "", usage = null; - await streamChat(state.current, content, (chunk) => { + await streamChat(state.current, content, attachments, (chunk) => { const d = chunk.choices && chunk.choices[0] && chunk.choices[0].delta; if (d && d.reasoning_content) { reasoning += d.reasoning_content; @@ -331,11 +392,11 @@ async function chatTurn(content, t) { } // Agent mode: stream tool_call / tool_result / final events (observability, no gate). -async function agentTurn(content, t) { +async function agentTurn(content, t, attachments) { const r = await fetch(`/api/sessions/${state.current}/chat`, { method: "POST", headers: { "Content-Type": "application/json" }, - body: JSON.stringify({ content, agent: true }), + body: JSON.stringify({ content, agent: true, attachments }), }); if (!r.ok) throw new Error(await r.text()); const reader = r.body.getReader(); @@ -575,6 +636,14 @@ function wire() { $("#new-session").addEventListener("click", newSession); $("#delete-session").addEventListener("click", deleteSession); $("#send").addEventListener("click", sendMessage); + $("#attach").title = t("attach.title"); + $("#attach").setAttribute("aria-label", t("attach.title")); + $("#attach").addEventListener("click", () => $("#file-input").click()); + $("#file-input").addEventListener("change", (e) => { + const files = Array.from(e.target.files || []); + e.target.value = ""; + if (files.length) uploadFiles(files); + }); $("#agent-toggle").addEventListener("click", () => { state.agent = !state.agent; const b = $("#agent-toggle"); diff --git a/web/assets/locales/en.json b/web/assets/locales/en.json index ed2fca0..8cfa7a4 100644 --- a/web/assets/locales/en.json +++ b/web/assets/locales/en.json @@ -17,5 +17,8 @@ "settings.hint.general": "General defaults: apply only to future sessions.", "settings.name.locked": "The name is locked after the first interaction.", "settings.name.unlocked": "You can rename until you send the first message.", - "settings.error": "Error: {msg}" + "settings.error": "Error: {msg}", + "attach.title": "Attach files or images", + "attach.remove": "Remove attachment", + "attach.error": "Upload failed: {msg}" } \ No newline at end of file diff --git a/web/assets/locales/it.json b/web/assets/locales/it.json index d49b4fb..3301ef3 100644 --- a/web/assets/locales/it.json +++ b/web/assets/locales/it.json @@ -17,5 +17,8 @@ "settings.hint.general": "Default generali: si applicano solo alle sessioni future.", "settings.name.locked": "Il nome è bloccato dopo la prima interazione.", "settings.name.unlocked": "Puoi rinominare finché non invii il primo messaggio.", - "settings.error": "Errore: {msg}" + "settings.error": "Errore: {msg}", + "attach.title": "Allega file o immagini", + "attach.remove": "Rimuovi allegato", + "attach.error": "Caricamento fallito: {msg}" } \ No newline at end of file diff --git a/web/index.html b/web/index.html index 3e31169..40aaaed 100644 --- a/web/index.html +++ b/web/index.html @@ -38,10 +38,13 @@
+