Attached pictures through the bridge, and a notification for a scheduled task's result
ci / check (push) Failing after 4s
ci / start (push) Failing after 2s

The picture command also serves a message's attached file (/attachments/<id>, one plain id,
8 MB at most) as a data: URL, for thumbnails; the page still reaches the server only through
the bridge.

The watch asks /schedules beside the chats and tells, by the schedule's title, of a new run the
server says is worth telling (`notified`); a silent run never, a server without the routes
never.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
HomerandClaude Opus 5.5 committed 2026-11-09 12:50:46 +00:00
1 parent 1749d2369e
commit 5b00822551
3 files changed
+163 -15

No files matched your search

+25 -2
View File
@@ -1368,7 +1368,8 @@ fn on_agent_state(handle: &AppHandle, state: &AgentState) {
announce(handle);
}
/// Look at the chat list every so often, and say when a reply finished out of sight.
/// Look at the chat list every so often, and say when a reply finished out of sight; and at the
/// scheduled tasks, and say when one has a result the server tells of.
fn watch_chats(handle: AppHandle) {
std::thread::spawn(move || loop {
std::thread::sleep(watch::EVERY);
@@ -1386,7 +1387,11 @@ fn watch_chats(handle: AppHandle) {
}
};
let done = app.watch.look(&list);
if done.is_empty() || !app.settings().notify {
// Scheduled tasks: a server without the routes (404) has none to tell of.
let ran = server::request(&app_url, &token, "GET", "/schedules", None)
.map(|v| app.watch.look_schedules(&v))
.unwrap_or_default();
if (done.is_empty() && ran.is_empty()) || !app.settings().notify {
continue;
}
let in_front = main_window(&handle)
@@ -1409,6 +1414,24 @@ fn watch_chats(handle: AppHandle) {
.body(if d.agent { &words.agent } else { &words.reply })
.show();
}
// A scheduled result is said even with the window in front: it ran on its own.
for r in ran {
let title = if r.title.is_empty() {
"LLeMbas".to_string()
} else {
r.title
};
let _ = handle
.notification()
.builder()
.title(title)
.body(if r.failed {
&words.scheduled_failed
} else {
&words.scheduled
})
.show();
}
});
}
+34 -12
View File
@@ -539,22 +539,32 @@ pub fn request_text(app: &str, token: &str, path: &str) -> Result<String, ApiErr
/// The most a model's picture may be: the server's own limit for one (2 MB), and a little room.
pub const IMAGE_LIMIT: u64 = 2 * 1024 * 1024 + 4096;
/// The most an attached picture shown as a thumbnail may be: a screenshot fits; a larger one
/// shows as a file.
pub const ATTACHMENT_IMAGE_LIMIT: u64 = 8 * 1024 * 1024;
/// The pictures a model may have, by the type the server serves them as: the four it accepts on
/// upload. Nothing else is shown, whatever the server says it is.
const IMAGE_TYPES: [&str; 4] = ["image/png", "image/jpeg", "image/webp", "image/gif"];
/// A model's picture path as `/api/v2/models` names it (`/api/v2/models/images/<file>`), on the
/// app's door: `/models/images/<file>`, or None for anything else. One plain file name, no more.
/// A picture's path on the app's door, or None for anything else: a model's picture as
/// `/api/v2/models` names it (`/models/images/<file>`), or a message's attached file
/// (`/attachments/<id>`, shown as a thumbnail when the server serves it as a picture). One plain
/// name after the prefix, no more.
pub fn image_path(path: &str) -> Option<String> {
let rest = path.strip_prefix("/api/v2").unwrap_or(path);
let name = rest.strip_prefix("/models/images/")?;
let plain = !name.is_empty()
&& name
.chars()
.all(|c| c.is_ascii_alphanumeric() || matches!(c, '.' | '-' | '_'))
&& !name.starts_with('.');
plain.then(|| format!("/models/images/{name}"))
let plain = |name: &str| {
!name.is_empty()
&& name
.chars()
.all(|c| c.is_ascii_alphanumeric() || matches!(c, '.' | '-' | '_'))
&& !name.starts_with('.')
};
if let Some(name) = rest.strip_prefix("/models/images/") {
return plain(name).then(|| format!("/models/images/{name}"));
}
let id = rest.strip_prefix("/attachments/")?;
(plain(id) && !id.contains('.')).then(|| format!("/attachments/{id}"))
}
/// A model's picture, as a `data:` URL the page can show without a request of its own (its
@@ -562,7 +572,7 @@ pub fn image_path(path: &str) -> Option<String> {
/// token, as the page reads nothing itself.
pub fn request_image(app: &str, token: &str, path: &str) -> Result<String, ApiError> {
let Some(path) = image_path(path) else {
return Err(ApiError::new(400, format!("Not a model's picture: {path}")));
return Err(ApiError::new(400, format!("Not a picture's path: {path}")));
};
let res = agent(Duration::from_secs(30))
.get(&format!("{app}{path}"))
@@ -578,12 +588,17 @@ pub fn request_image(app: &str, token: &str, path: &str) -> Result<String, ApiEr
if !IMAGE_TYPES.contains(&kind.as_str()) {
return Err(ApiError::new(415, format!("Not a picture: {kind}")));
}
let limit = if path.starts_with("/attachments/") {
ATTACHMENT_IMAGE_LIMIT
} else {
IMAGE_LIMIT
};
let mut bytes = Vec::new();
res.into_reader()
.take(IMAGE_LIMIT)
.take(limit)
.read_to_end(&mut bytes)
.map_err(|e| ApiError::new(0, format!("The server's answer could not be read: {e}")))?;
if bytes.len() as u64 >= IMAGE_LIMIT {
if bytes.len() as u64 >= limit {
return Err(ApiError::new(413, "The picture is too large."));
}
Ok(format!("data:{kind};base64,{}", base64(&bytes)))
@@ -912,12 +927,19 @@ mod tests {
image_path("/models/images/a-b_c.webp").as_deref(),
Some("/models/images/a-b_c.webp")
);
assert_eq!(
image_path("/api/v2/attachments/att_01x").as_deref(),
Some("/attachments/att_01x")
);
for bad in [
"/api/v2/models/images/",
"/api/v2/models/images/../me",
"/api/v2/models/images/a/b.png",
"/api/v2/models/images/.hidden",
"/api/v2/chats/x",
"/api/v2/attachments/",
"/api/v2/attachments/a/b",
"/api/v2/attachments/..",
"/uploads/models/a.png",
"https://elsewhere/models/images/a.png",
] {
+104 -1
View File
@@ -1,11 +1,17 @@
//! Native notifications: a reply finished, or an agent chat's work did, while the person was not
//! looking at it. The app's own, so the server's Web Push can stay off.
//! looking at it; and a scheduled task has a result the server decided to tell of. The app's own,
//! so the server's Web Push can stay off.
//!
//! The app asks the server's chat list (`/api/v2/chats`) every `EVERY` and notes which chats are
//! being answered; a chat that was and no longer is has finished. The notification is shown
//! unless that chat is open in a window in front. Its words come from the page (`set_words`), in
//! the page's language; the chat's title is the person's own. Nothing from the reply itself is
//! put on screen outside the app.
//!
//! Scheduled tasks: the app asks `/api/v2/schedules` as often, and a schedule whose last run is a
//! new one, with the server's word that it is worth telling (`notified`: its notify policy, and a
//! `[SILENT]` run not), is said once -- by the schedule's title, never the result's words. A
//! server without the routes answers 404, and nothing is said.
use std::collections::HashMap;
use std::sync::Mutex;
@@ -23,6 +29,20 @@ pub struct Words {
pub reply: String,
/// An agent chat has finished its work.
pub agent: String,
/// A scheduled task has a result.
#[serde(default = "scheduled_word")]
pub scheduled: String,
/// A scheduled task's run failed.
#[serde(default = "scheduled_failed_word")]
pub scheduled_failed: String,
}
fn scheduled_word() -> String {
"A scheduled task has a result.".into()
}
fn scheduled_failed_word() -> String {
"A scheduled task failed.".into()
}
impl Default for Words {
@@ -30,6 +50,8 @@ impl Default for Words {
Words {
reply: "The reply is ready.".into(),
agent: "The agent has finished.".into(),
scheduled: scheduled_word(),
scheduled_failed: scheduled_failed_word(),
}
}
}
@@ -49,6 +71,15 @@ pub struct Watch {
pub words: Mutex<Words>,
/// Which chats were being answered at the last look (None before the first look).
running: Mutex<Option<HashMap<String, bool>>>,
/// Each schedule's last run at the last look (None before the first look).
runs: Mutex<Option<HashMap<String, String>>>,
}
/// A scheduled task's new run that the server says is worth telling of.
#[derive(Clone, Debug, PartialEq)]
pub struct Ran {
pub title: String,
pub failed: bool,
}
impl Watch {
@@ -89,9 +120,50 @@ impl Watch {
done
}
/// Note the schedules as the server gave them; the new runs to tell of since the last look.
/// The first look only notes, as with the chats.
pub fn look_schedules(&self, list: &Value) -> Vec<Ran> {
let rows = list
.get("schedules")
.and_then(Value::as_array)
.cloned()
.unwrap_or_default();
let mut seen = self.runs.lock().unwrap();
let first = seen.is_none();
let mut now = HashMap::new();
let mut out = Vec::new();
for row in &rows {
let Some(id) = row.get("id").and_then(Value::as_str) else {
continue;
};
let Some(run) = row.get("last_run").filter(|r| r.is_object()) else {
continue;
};
let Some(run_id) = run.get("id").and_then(Value::as_str) else {
continue;
};
let before = seen.as_ref().and_then(|s| s.get(id));
let told = run.get("notified").and_then(Value::as_bool) == Some(true);
if !first && before.map(String::as_str) != Some(run_id) && told {
out.push(Ran {
title: row
.get("title")
.and_then(Value::as_str)
.unwrap_or("")
.to_string(),
failed: run.get("status").and_then(Value::as_str) == Some("failed"),
});
}
now.insert(id.to_string(), run_id.to_string());
}
*seen = Some(now);
out
}
/// Start again from nothing: another server, or signed out.
pub fn reset(&self) {
*self.running.lock().unwrap() = None;
*self.runs.lock().unwrap() = None;
}
}
@@ -100,6 +172,37 @@ mod tests {
use super::*;
use serde_json::json;
fn schedules(rows: &[(&str, Option<(&str, &str, bool)>)]) -> Value {
json!({"schedules": rows.iter().map(|(id, run)| json!({
"id": id, "title": format!("Task {id}"),
"last_run": run.map(|(r, status, told)| json!({"id": r, "status": status, "notified": told})),
})).collect::<Vec<_>>()})
}
#[test]
fn a_new_run_the_server_tells_of_is_said_once_and_a_silent_one_never() {
let w = Watch::default();
assert!(w
.look_schedules(&schedules(&[("a", Some(("r1", "ok", true))), ("b", None)]))
.is_empty());
let ran = w.look_schedules(&schedules(&[
("a", Some(("r2", "ok", true))),
("b", Some(("r3", "silent", false))),
]));
assert_eq!(
ran,
vec![Ran {
title: "Task a".into(),
failed: false
}]
);
assert!(w
.look_schedules(&schedules(&[("a", Some(("r2", "ok", true)))]))
.is_empty());
let failed = w.look_schedules(&schedules(&[("a", Some(("r4", "failed", true)))]));
assert!(failed[0].failed);
}
fn list(rows: &[(&str, bool, &str)]) -> Value {
json!({"chats": rows.iter().map(|(id, running, kind)| json!({
"id": id, "title": format!("Chat {id}"), "running": running, "kind": kind