Linux port: first run, packaging, single instance, privacy and wiring
CI / test (push) Has been cancelled
CI / test (push) Has been cancelled
First run and backend - The companion opens without Ollama or a model (OFFLINE / SETUP REQUIRED), opens Settings > Language model and picks the model up once downloaded. - Model, provider and GPU changes apply without restarting (Ollama is restarted when launch settings change); no silent fallback from API mode. - Fatal startup errors are shown in a window; the fallback avatar loads again; the shipped Capri artwork is used when nothing was imported. Packaging and tooling - packaging/arch/PKGBUILD, capri.desktop (KWin ScreenShot2 key), icons, artwork under /usr/share/capri/assets, Gitea Actions CI. - xtask: `icons` and `release-check` (no private data or credentials). Runtime - One instance per data folder (flock + control socket): second launch shows the window; capri stop / restart / toggle / status (JSON, starts nothing) / doctor / setup / diagnostics export / purge. - A foreign program on the Ollama port is refused; an Ollama left behind by Capri is replaced. Privacy and security - No raw Ollama log on disk; API keys are never saved in plaintext (old ones move to the keyring); refused credential notes are stored as [Credentials omitted]; launched apps get an allow-listed environment. Fixes - Stop/Escape silence the voice; saved voice effects apply to replies; settings_control glitch settings apply; distinct KWin cursor scripts; KDE window capture authorized for source builds; Linux wording. - Voice pack references zipped with Windows separators are found. Wired features - Initiatives, request router, resource monitor, "clip that", questions about a snapshot, sleep mode, tap reactions, stopwatch, attachments, Internet mode button, voice-synced subtitles, wake visuals, dictation draft, tray switches, Spotify seek/shuffle/repeat; computer-control planner and classifier follow model switches and API mode. - Approval cards: one shown, 8 queued, deduplicated, cancelled on stop, failure, lock or pause; one Application access switch. Desktop - Compositor detection (no black overlay on i3 without picom), i3lock detection, unsupported desktops reported at startup, screenshot-only control without AT-SPI, fontconfig fallbacks, translatable feature pages with French translations. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
73 files changed
+4834
-517
No files matched your search
@@ -11,6 +11,7 @@ thiserror.workspace = true
|
||||
serde.workspace = true
|
||||
serde_json.workspace = true
|
||||
tokio.workspace = true
|
||||
parking_lot.workspace = true
|
||||
futures.workspace = true
|
||||
reqwest.workspace = true
|
||||
tracing.workspace = true
|
||||
|
||||
@@ -7,7 +7,7 @@ use serde_json::Value;
|
||||
use crate::openai::OpenAi;
|
||||
use crate::secrets::SecretStore;
|
||||
use crate::sections::ApiSection;
|
||||
use crate::{ChatDone, ChatRequest, LlmError, Ollama};
|
||||
use crate::{ChatDone, ChatRequest, LlmError, Message, Ollama, Options};
|
||||
|
||||
#[derive(Clone, Debug)]
|
||||
pub enum LlmBackend {
|
||||
@@ -51,6 +51,46 @@ impl LlmBackend {
|
||||
}
|
||||
}
|
||||
|
||||
/// Auxiliary request in Ollama `/api/chat` shape (messages with base64 `images`, optional
|
||||
/// `format` schema, `think`, `options`), answered on either backend in Ollama shape
|
||||
/// `{model, message: {role, content}, done, done_reason}` (spec 02 INF-45). With a `format`,
|
||||
/// `content` is the JSON object as text; API providers get the structured-output strategy of
|
||||
/// [`OpenAi::chat_json`] (INF-46).
|
||||
pub async fn aux_chat(&self, model: &str, body: &Value) -> Result<Value, LlmError> {
|
||||
let messages: Vec<Message> = body["messages"]
|
||||
.as_array()
|
||||
.into_iter()
|
||||
.flatten()
|
||||
.map(|m| {
|
||||
let mut message = Message::new(m["role"].as_str().unwrap_or("user"), m["content"].as_str().unwrap_or_default());
|
||||
message.images = m["images"].as_array().into_iter().flatten().filter_map(|i| i.as_str().map(str::to_string)).collect();
|
||||
message
|
||||
})
|
||||
.collect();
|
||||
let options = &body["options"];
|
||||
let request = ChatRequest {
|
||||
model: model.into(),
|
||||
messages,
|
||||
tools: vec![],
|
||||
options: Options {
|
||||
num_ctx: options["num_ctx"].as_u64().map_or(8192, |n| n as u32),
|
||||
temperature: options["temperature"].as_f64().unwrap_or(0.85) as f32,
|
||||
num_predict: options["num_predict"].as_i64().map(|n| n as i32),
|
||||
..Default::default()
|
||||
},
|
||||
keep_alive: -1,
|
||||
stream: false,
|
||||
think: body["think"].as_bool(),
|
||||
};
|
||||
let schema = body.get("format").filter(|f| f.is_object());
|
||||
let content = match (self, schema) {
|
||||
(_, Some(schema)) => self.chat_json(&request, Some(schema)).await?.to_string(),
|
||||
(Self::Api(api), None) => api.chat(&request, |_| {}).await?.content,
|
||||
(Self::Local(local), None) => local.chat(&request, |_| {}).await?.content,
|
||||
};
|
||||
Ok(serde_json::json!({"model": model, "message": {"role": "assistant", "content": content}, "done": true, "done_reason": "stop"}))
|
||||
}
|
||||
|
||||
/// Capabilities of an API connection (`tools`, `vision`, `thinking`); `None` for local models
|
||||
/// (ask `Ollama::show`).
|
||||
pub fn api_capabilities(&self) -> Option<Vec<String>> {
|
||||
@@ -123,4 +163,32 @@ mod tests {
|
||||
assert!(!backend.is_local(), "keyless loopback connections need no key");
|
||||
assert_eq!(backend.context_tokens(&settings), 8192);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn auxiliary_requests_reach_an_api_in_ollama_shape() {
|
||||
use wiremock::matchers::{method, path};
|
||||
use wiremock::{Mock, MockServer, Request, ResponseTemplate};
|
||||
let server = MockServer::start().await;
|
||||
Mock::given(method("POST"))
|
||||
.and(path("/v1/chat/completions"))
|
||||
.respond_with(|r: &Request| {
|
||||
let body: Value = serde_json::from_slice(&r.body).unwrap();
|
||||
// The image becomes an image_url part; the schema becomes a JSON contract.
|
||||
let parts = body["messages"].as_array().unwrap().iter().find(|m| m["role"] == "user").unwrap()["content"].clone();
|
||||
assert!(parts.as_array().is_some_and(|p| p.iter().any(|p| p["type"] == "image_url")), "{parts}");
|
||||
assert!(body["messages"][0]["content"].as_str().unwrap().contains("Return JSON matching this output schema"));
|
||||
ResponseTemplate::new(200).set_body_json(serde_json::json!({"choices": [{"message": {"role": "assistant", "content": "{\"intent\":\"chat\"}"}, "finish_reason": "stop"}]}))
|
||||
})
|
||||
.mount(&server)
|
||||
.await;
|
||||
let api = crate::OpenAi::new(crate::openai::ApiConnection { id: "c".into(), base_url: format!("{}/v1", server.uri()), model: "m".into(), vision: true, ..Default::default() }, Some("sk-test-123456".into()));
|
||||
let body = serde_json::json!({
|
||||
"options": {"num_predict": 64, "temperature": 0},
|
||||
"format": {"type": "object", "properties": {"intent": {"type": "string"}}, "required": ["intent"]},
|
||||
"messages": [{"role": "system", "content": "Classify."}, {"role": "user", "content": "hi", "images": ["iVBORw0KGgo="]}],
|
||||
});
|
||||
let packet = LlmBackend::Api(api).aux_chat("m", &body).await.unwrap();
|
||||
assert_eq!(packet["message"]["content"], "{\"intent\":\"chat\"}");
|
||||
assert_eq!(packet["done"], true);
|
||||
}
|
||||
}
|
||||
@@ -1,6 +1,8 @@
|
||||
//! API keys and the Hugging Face token: Secret Service over D-Bus
|
||||
//! (`org.freedesktop.secrets`: KWallet/ksecretd on KDE, gnome-keyring or ksecretd on i3),
|
||||
//! with a private 0600 file fallback. Secrets are never logged and never in `Debug` output.
|
||||
//! (`org.freedesktop.secrets`: KWallet/ksecretd on KDE, gnome-keyring or KeePassXC on i3).
|
||||
//! Without a Secret Service nothing new is saved (fail closed); keys an older build wrote to
|
||||
//! the private 0600 file stay readable and move into the keyring once it is available.
|
||||
//! Secrets are never logged and never in `Debug` output.
|
||||
use std::collections::{BTreeMap, HashMap};
|
||||
use std::path::{Path, PathBuf};
|
||||
use std::time::Duration;
|
||||
@@ -26,9 +28,13 @@ pub struct SecretStore(Backend);
|
||||
#[derive(Clone)]
|
||||
enum Backend {
|
||||
Service { conn: zbus::Connection, session: OwnedObjectPath },
|
||||
File(PathBuf),
|
||||
/// `writable` only for explicit file stores (tests); the fallback is read-only.
|
||||
File { path: PathBuf, writable: bool },
|
||||
}
|
||||
|
||||
/// Shown when a key cannot be saved because no keyring answers.
|
||||
pub const NO_KEYRING: &str = "Secure credential storage is unavailable: no Secret Service is running. Start KWallet (KDE Plasma), or gnome-keyring or KeePassXC with its Secret Service option (i3), then save the key again.";
|
||||
|
||||
impl std::fmt::Debug for SecretStore {
|
||||
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
|
||||
f.write_str(if self.secure() { "SecretStore(secret-service)" } else { "SecretStore(file)" })
|
||||
@@ -48,18 +54,41 @@ async fn proxy<'a>(conn: &zbus::Connection, path: &'a str, interface: &'a str) -
|
||||
impl SecretStore {
|
||||
/// Secret Service when reachable, else `<data>/secrets/credentials.json`.
|
||||
pub async fn open(data_dir: &Path) -> Self {
|
||||
let legacy = data_dir.join("secrets").join("credentials.json");
|
||||
match tokio::time::timeout(Duration::from_secs(3), Self::service()).await {
|
||||
Ok(Ok(backend)) => Self(backend),
|
||||
Ok(Ok(backend)) => {
|
||||
let store = Self(backend);
|
||||
store.migrate(&legacy).await;
|
||||
store
|
||||
}
|
||||
_ => {
|
||||
// TODO: falls back to a plaintext 0600 file when no Secret Service runs; refuse to save when `!secure()` to fail closed.
|
||||
tracing::warn!("Secret Service unavailable; API keys use a private file");
|
||||
Self::file(data_dir.join("secrets").join("credentials.json"))
|
||||
tracing::warn!("Secret Service unavailable; API keys cannot be saved until a keyring runs");
|
||||
Self(Backend::File { path: legacy, writable: false })
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Moves keys from the plaintext file of older builds into the keyring, then deletes the file.
|
||||
async fn migrate(&self, legacy: &Path) {
|
||||
let Ok(entries) = read_file(legacy) else { return };
|
||||
if entries.is_empty() {
|
||||
return;
|
||||
}
|
||||
for (account, entry) in &entries {
|
||||
if let Err(e) = self.set(account, &entry.origin, &entry.secret).await {
|
||||
tracing::warn!("saved access not moved to the keyring: {e:#}");
|
||||
return;
|
||||
}
|
||||
}
|
||||
match std::fs::remove_file(legacy) {
|
||||
Ok(()) => tracing::info!(count = entries.len(), "saved access moved to the keyring"),
|
||||
Err(e) => tracing::warn!("plaintext credentials file not removed: {e}"),
|
||||
}
|
||||
}
|
||||
|
||||
/// File store that also saves (tests and explicit tooling only).
|
||||
pub fn file(path: PathBuf) -> Self {
|
||||
Self(Backend::File(path))
|
||||
Self(Backend::File { path, writable: true })
|
||||
}
|
||||
|
||||
/// True when secrets are held by the desktop keyring.
|
||||
@@ -120,7 +149,7 @@ impl SecretStore {
|
||||
let (_, _, value, _): Secret = item.call("GetSecret", &(session,)).await.context("Saved access could not be read. Save it again.")?;
|
||||
Ok(Some(String::from_utf8(value).context("Saved access could not be read. Save it again.")?))
|
||||
}
|
||||
Backend::File(path) => Ok(read_file(path)?.remove(account).filter(|e| e.origin == origin).map(|e| e.secret)),
|
||||
Backend::File { path, .. } => Ok(read_file(path)?.remove(account).filter(|e| e.origin == origin).map(|e| e.secret)),
|
||||
}
|
||||
}
|
||||
|
||||
@@ -148,7 +177,8 @@ impl SecretStore {
|
||||
}
|
||||
bail!("Secure credential storage is unavailable.")
|
||||
}
|
||||
Backend::File(path) => {
|
||||
Backend::File { writable: false, .. } => bail!(NO_KEYRING),
|
||||
Backend::File { path, writable: true } => {
|
||||
let mut entries = read_file(path)?;
|
||||
entries.insert(account.into(), FileEntry { origin: origin.into(), secret: secret.into() });
|
||||
write_file(path, &entries)
|
||||
@@ -168,7 +198,8 @@ impl SecretStore {
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
Backend::File(path) => {
|
||||
// Deleting is allowed even read-only: it removes a plaintext secret.
|
||||
Backend::File { path, .. } => {
|
||||
let mut entries = read_file(path)?;
|
||||
if entries.remove(account).is_some() {
|
||||
write_file(path, &entries)?;
|
||||
@@ -241,6 +272,19 @@ mod tests {
|
||||
assert_eq!(store.get("c1", "https://a.example").await.unwrap(), None);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn without_keyring_nothing_new_is_saved() {
|
||||
let dir = tempfile::tempdir().unwrap();
|
||||
let path = dir.path().join("secrets/credentials.json");
|
||||
SecretStore::file(path.clone()).set("old", "https://a.example", "sk-legacy-key").await.unwrap();
|
||||
let fallback = SecretStore(Backend::File { path: path.clone(), writable: false });
|
||||
assert_eq!(fallback.set("new", "https://a.example", "sk-12345678").await.unwrap_err().to_string(), NO_KEYRING);
|
||||
// A key from an older build stays usable and can be removed.
|
||||
assert_eq!(fallback.get("old", "https://a.example").await.unwrap().as_deref(), Some("sk-legacy-key"));
|
||||
fallback.delete("old").await.unwrap();
|
||||
assert_eq!(fallback.get("old", "https://a.example").await.unwrap(), None);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn key_normalization_and_validation() {
|
||||
assert_eq!(normalize_api_key("\u{feff} \"sk-abcdefgh\" \n"), "sk-abcdefgh");
|
||||
|
||||
@@ -66,6 +66,73 @@ async fn version_gate(client: &Ollama, minimum: &str) -> Result<()> {
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Process listening on `127.0.0.1:<port>` (or any address), found through `/proc/net/tcp{,6}`
|
||||
/// and the socket inodes in `/proc/<pid>/fd`. Only processes of this user are visible.
|
||||
fn listener_pid(port: u16) -> Option<u32> {
|
||||
let inodes: Vec<String> = ["/proc/net/tcp", "/proc/net/tcp6"]
|
||||
.iter()
|
||||
.filter_map(|f| std::fs::read_to_string(f).ok())
|
||||
.flat_map(|table| {
|
||||
table
|
||||
.lines()
|
||||
.skip(1)
|
||||
.filter_map(|line| {
|
||||
let fields: Vec<&str> = line.split_whitespace().collect();
|
||||
let local_port = u16::from_str_radix(fields.get(1)?.rsplit(':').next()?, 16).ok()?;
|
||||
(local_port == port && fields.get(3) == Some(&"0A")).then(|| fields.get(9).map(|i| i.to_string()))?
|
||||
})
|
||||
.collect::<Vec<_>>()
|
||||
})
|
||||
.collect();
|
||||
if inodes.is_empty() {
|
||||
return None;
|
||||
}
|
||||
let targets: Vec<String> = inodes.iter().map(|i| format!("socket:[{i}]")).collect();
|
||||
std::fs::read_dir("/proc").ok()?.flatten().find_map(|entry| {
|
||||
let pid: u32 = entry.file_name().to_str()?.parse().ok()?;
|
||||
let fds = std::fs::read_dir(entry.path().join("fd")).ok()?;
|
||||
fds.flatten().any(|fd| std::fs::read_link(fd.path()).is_ok_and(|l| targets.iter().any(|t| l.as_os_str() == t.as_str()))).then_some(pid)
|
||||
})
|
||||
}
|
||||
|
||||
/// `true` when `pid` is an Ollama that Capri launched for this model store and port
|
||||
/// (left behind by a Capri that could not stop it). Its environment proves it.
|
||||
fn is_capri_ollama(pid: u32, settings: &Settings, paths: &Paths) -> bool {
|
||||
let Ok(environ) = std::fs::read(format!("/proc/{pid}/environ")) else { return false };
|
||||
let vars: Vec<&[u8]> = environ.split(|b| *b == 0).collect();
|
||||
let has = |key: &str, value: &str| vars.iter().any(|v| *v == format!("{key}={value}").as_bytes());
|
||||
has("OLLAMA_MODELS", &settings.models_dir(paths).display().to_string()) && has("OLLAMA_HOST", &format!("127.0.0.1:{}", settings.ollama_port))
|
||||
}
|
||||
|
||||
/// Last lines of the Ollama child's output, in memory only (never logged to disk).
|
||||
#[derive(Clone, Default)]
|
||||
struct OutputTail(std::sync::Arc<parking_lot::Mutex<std::collections::VecDeque<String>>>);
|
||||
|
||||
impl OutputTail {
|
||||
const LINES: usize = 40;
|
||||
|
||||
/// Drains `stderr` (a full pipe would block Ollama) and keeps the last lines.
|
||||
fn follow(&self, stderr: tokio::process::ChildStderr) {
|
||||
let lines = self.0.clone();
|
||||
tokio::spawn(async move {
|
||||
use tokio::io::AsyncBufReadExt;
|
||||
let mut reader = tokio::io::BufReader::new(stderr).lines();
|
||||
while let Ok(Some(line)) = reader.next_line().await {
|
||||
let mut lines = lines.lock();
|
||||
if lines.len() == Self::LINES {
|
||||
lines.pop_front();
|
||||
}
|
||||
lines.push_back(line.chars().take(400).collect());
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
fn last(&self, n: usize) -> String {
|
||||
let lines = self.0.lock();
|
||||
lines.iter().skip(lines.len().saturating_sub(n)).cloned().collect::<Vec<_>>().join("\n")
|
||||
}
|
||||
}
|
||||
|
||||
/// Running Ollama. The child (if Capri started it) is killed when this value is dropped.
|
||||
pub struct OllamaServer {
|
||||
pub client: Ollama,
|
||||
@@ -77,21 +144,82 @@ impl OllamaServer {
|
||||
self.child.is_some()
|
||||
}
|
||||
|
||||
/// Uses `settings.ollama_url` when set, an Ollama already answering on the Capri port,
|
||||
/// or starts `ollama serve` on that port with the Capri model store.
|
||||
/// Client for the configured address with no server behind it (Ollama missing or failed).
|
||||
/// Every request fails until Ollama answers there; the companion still opens.
|
||||
pub fn offline(settings: &Settings) -> Self {
|
||||
Self { client: Ollama::new(settings.ollama_base_url()), child: None }
|
||||
}
|
||||
|
||||
/// Launch settings of `ollama serve` that only a restart applies. Keep-alive and context
|
||||
/// length are also sent with every request, so they do not restart the server.
|
||||
pub fn launch_key(settings: &Settings, paths: &Paths) -> String {
|
||||
let inference: InferenceSection = settings.section();
|
||||
format!(
|
||||
"{}|{}|{}|{}|{}|{}",
|
||||
inference.device,
|
||||
settings.acceleration,
|
||||
inference.reasoning_budget.max(4096),
|
||||
settings.ollama_port,
|
||||
settings.ollama_url.as_deref().unwrap_or_default(),
|
||||
settings.models_dir(paths).display()
|
||||
)
|
||||
}
|
||||
|
||||
/// Uses `settings.ollama_url` when set, an Ollama already answering on the Capri port
|
||||
/// (the running companion's, for `capri pull`), or starts `ollama serve` on that port with
|
||||
/// the Capri model store.
|
||||
pub async fn start(settings: &Settings, paths: &Paths) -> Result<Self> {
|
||||
Self::launch(settings, paths, false).await
|
||||
}
|
||||
|
||||
/// For the instance that owns the Capri port (the companion or the terminal chat, holding the
|
||||
/// instance lock): a server already answering on the managed port is not adopted. An Ollama
|
||||
/// that a previous Capri left behind is stopped and replaced; any other program is refused.
|
||||
/// `settings.ollama_url` (an external server chosen by the owner) is used as is.
|
||||
pub async fn start_exclusive(settings: &Settings, paths: &Paths) -> Result<Self> {
|
||||
Self::launch(settings, paths, true).await
|
||||
}
|
||||
|
||||
async fn launch(settings: &Settings, paths: &Paths, exclusive: bool) -> Result<Self> {
|
||||
let client = Ollama::new(settings.ollama_base_url());
|
||||
let inference: InferenceSection = settings.section();
|
||||
if client.version().await.is_ok() {
|
||||
version_gate(&client, &inference.min_ollama_version).await?;
|
||||
return Ok(Self { client, child: None });
|
||||
if exclusive && settings.ollama_url.is_none() {
|
||||
let port = settings.ollama_port;
|
||||
match listener_pid(port) {
|
||||
Some(pid) if is_capri_ollama(pid, settings, paths) => {
|
||||
tracing::warn!(pid, "stopping an Ollama left behind by a previous Capri");
|
||||
unsafe { libc::kill(pid as i32, libc::SIGTERM) };
|
||||
let deadline = Instant::now() + Duration::from_secs(5);
|
||||
while client.version().await.is_ok() && Instant::now() < deadline {
|
||||
tokio::time::sleep(Duration::from_millis(200)).await;
|
||||
}
|
||||
if client.version().await.is_ok() {
|
||||
bail!("An earlier Ollama started by Capri (process {pid}) does not stop. End it, then restart Capri.");
|
||||
}
|
||||
}
|
||||
Some(pid) => bail!("Ollama port {port} is already in use by another program (process {pid}). Stop it, or choose a free ollamaPort in ~/.config/capri/settings.json."),
|
||||
None => bail!("Ollama port {port} is already in use by another program. Stop it, or choose a free ollamaPort in ~/.config/capri/settings.json."),
|
||||
}
|
||||
} else {
|
||||
version_gate(&client, &inference.min_ollama_version).await?;
|
||||
return Ok(Self { client, child: None });
|
||||
}
|
||||
}
|
||||
if settings.ollama_url.is_some() {
|
||||
bail!("Ollama does not answer at {}.", client.base());
|
||||
}
|
||||
// Something that is not Ollama holds the port: `ollama serve` would fail with a bind error.
|
||||
if std::net::TcpStream::connect_timeout(&([127, 0, 0, 1], settings.ollama_port).into(), Duration::from_millis(500)).is_ok() {
|
||||
let who = listener_pid(settings.ollama_port).map(|pid| format!(" (process {pid})")).unwrap_or_default();
|
||||
bail!("Ollama port {} is already in use by another program{who}. Stop it, or choose a free ollamaPort in ~/.config/capri/settings.json.", settings.ollama_port);
|
||||
}
|
||||
let models = settings.models_dir(paths);
|
||||
std::fs::create_dir_all(&models)?;
|
||||
let log = std::fs::OpenOptions::new().create(true).append(true).open(paths.logs().join("ollama.log"))?;
|
||||
// Ollama's own output (request lines, paths, model names) is never written to disk: older
|
||||
// builds appended it raw to logs/ollama.log, which is removed. The last lines stay in
|
||||
// memory to explain a failed start.
|
||||
let _ = std::fs::remove_file(paths.logs().join("ollama.log"));
|
||||
let exe = match std::env::var_os("CAPRI_OLLAMA_PATH") {
|
||||
Some(path) => {
|
||||
let path = std::path::PathBuf::from(path);
|
||||
@@ -127,8 +255,8 @@ impl OllamaServer {
|
||||
.env("OLLAMA_FLASH_ATTENTION", "1")
|
||||
.env("OLLAMA_KV_CACHE_TYPE", "q8_0")
|
||||
.stdin(Stdio::null())
|
||||
.stdout(log.try_clone()?)
|
||||
.stderr(log)
|
||||
.stdout(Stdio::null())
|
||||
.stderr(Stdio::piped())
|
||||
.kill_on_drop(true);
|
||||
// Ollama must not outlive Capri, even when Capri is killed (logout, SIGKILL).
|
||||
// Spawned from the main thread (`block_on`), whose exit is the process exit.
|
||||
@@ -141,6 +269,10 @@ impl OllamaServer {
|
||||
let mut child = command
|
||||
.spawn()
|
||||
.with_context(|| format!("Cannot start {}. Install Ollama (pacman -S ollama).", exe.display()))?;
|
||||
let tail = OutputTail::default();
|
||||
if let Some(stderr) = child.stderr.take() {
|
||||
tail.follow(stderr);
|
||||
}
|
||||
let deadline = Instant::now() + Duration::from_secs(30);
|
||||
while Instant::now() < deadline {
|
||||
if client.version().await.is_ok() {
|
||||
@@ -153,7 +285,9 @@ impl OllamaServer {
|
||||
return Ok(server);
|
||||
}
|
||||
if let Some(status) = child.try_wait()? {
|
||||
bail!("Ollama exited during startup ({status}). See {}.", paths.logs().join("ollama.log").display());
|
||||
tokio::time::sleep(Duration::from_millis(100)).await; // last lines still in the pipe
|
||||
let detail = tail.last(4);
|
||||
bail!("Ollama exited during startup ({status}).{}", if detail.is_empty() { String::new() } else { format!(" Last output:\n{detail}") });
|
||||
}
|
||||
tokio::time::sleep(Duration::from_millis(250)).await;
|
||||
}
|
||||
@@ -171,6 +305,11 @@ impl OllamaServer {
|
||||
|
||||
/// Stops the owned server, giving it 3 s to exit after SIGTERM.
|
||||
pub async fn stop(mut self) {
|
||||
self.shutdown().await;
|
||||
}
|
||||
|
||||
/// Like [`Self::stop`], in place: the value is left without a server (as [`Self::offline`]).
|
||||
pub async fn shutdown(&mut self) {
|
||||
if let Some(mut child) = self.child.take() {
|
||||
if let Some(pid) = child.id() {
|
||||
// SIGTERM lets Ollama unload models cleanly.
|
||||
@@ -193,7 +332,7 @@ pub async fn resolve_model(client: &Ollama, settings: &Settings) -> Result<(Stri
|
||||
return Ok((name.clone(), capabilities));
|
||||
}
|
||||
}
|
||||
bail!("Model {} is not installed. Run: capri models pull", settings.upstream_model)
|
||||
bail!("Model {} is not installed. Download it in Settings › Language model, or run: capri pull", settings.upstream_model)
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
@@ -215,4 +354,17 @@ mod tests {
|
||||
assert!(!version_at_least("0.40.9", "0.40.10") && !version_at_least("dev", "0.40.10"));
|
||||
assert!(allowed_env("LC_ALL") && allowed_env("CUDA_PATH") && !allowed_env("OPENAI_API_KEY") && !allowed_env("CAPRI_TOKEN"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn finds_the_process_listening_on_a_port() {
|
||||
let listener = std::net::TcpListener::bind("127.0.0.1:0").unwrap();
|
||||
let port = listener.local_addr().unwrap().port();
|
||||
assert_eq!(listener_pid(port), Some(std::process::id()));
|
||||
drop(listener);
|
||||
assert_eq!(listener_pid(port), None);
|
||||
// This test process is not an Ollama started by Capri.
|
||||
let dir = tempfile::tempdir().unwrap();
|
||||
let paths = Paths::under(dir.path().to_path_buf());
|
||||
assert!(!is_capri_ollama(std::process::id(), &Settings::default(), &paths));
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user