Cleanup pass: one home for duplicated logic, stale comments out
Nothing behavioral except two status codes; mostly removing places where the same rule was written down more than once and could drift. - server/src/private.rs: the owner-only create/write helpers, which config.rs, certs.rs, and the session dirs each had their own copy of (certs.rs even duplicated the explanatory comment). One module owns the modes now, so the "nothing this server writes is readable by anyone else" property is checkable in one place. - server/src/media.rs: the image media-type/extension table, which the four places that have to agree on it each spelled out separately -- storing an upload, serving it back, building a content block, saving a produced image. The differing *defaults* stay at the call sites with the reasoning, since they genuinely differ by direction. - routes.rs: a missing file was a 400 and an unreadable one a 400 with a hand-rolled log line; they are now 404 and Internal respectively. UnknownSession became NotFound, since it was the only 404-with-message. - main.rs: xdg_dir takes the variable's value instead of reading the environment, which drops the unsafe set_var from its test and lets the test actually assert the relative-path rule. - echo.rs had its own 4-byte hex generator beside session::random_hex. - claude.rs: the two impl Translator blocks were one type's methods. - Stale comments: phase-2 markers on shipped work, a permission-mode list that had drifted from the CLI's, "dev-updater" as the leaf certificate's fallback common name, a half-written sentence in build-apk.sh. - App: the JSONArray walk written out in four fetchers, the four near-identical BackHandlers in AppRoot, and SessionScreen's inline fully-qualified names where the file otherwise imports. - server/wg-test.log was committed by accident; *.log is ignored now, and the gitignore comments describe where state actually lives. - PLAN.md's backend layout gains the new modules and drops hosts.rs for the ssh.rs that was built instead. Verified: 35 server tests, clippy clean, app compiles warning-free, and a scratch server driven over curl -- attachment upload/serve round-trip with both a known and an unknown content type, the new 404s, transcript and session-dir deletion, plus a real claude-cli session answering a prompt. Co-Authored-By: Claude Opus 5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_017xn8nHw1tw1R6PtiY1eEtw
This commit is contained in:
1 parent
d4a4ee7808
commit
99bcc341c1
18 files changed
+295
-241
No files matched your search
+9
-32
@@ -25,7 +25,6 @@
|
||||
//! which is exactly the attack pinning exists to stop.
|
||||
|
||||
use std::net::IpAddr;
|
||||
use std::os::unix::fs::{DirBuilderExt, OpenOptionsExt, PermissionsExt};
|
||||
use std::path::{Path, PathBuf};
|
||||
|
||||
use anyhow::{Context, Result};
|
||||
@@ -33,6 +32,8 @@ use rcgen::{
|
||||
BasicConstraints, CertificateParams, DnType, IsCa, Issuer, KeyPair, KeyUsagePurpose, SanType,
|
||||
};
|
||||
|
||||
use crate::private;
|
||||
|
||||
/// Where the leaf lives, for handing to the TLS listener.
|
||||
pub struct Certificates {
|
||||
pub leaf_cert: PathBuf,
|
||||
@@ -45,17 +46,7 @@ pub struct Certificates {
|
||||
/// Ensures `dir` holds a CA and a leaf covering `addresses`, creating what
|
||||
/// is missing. Safe to call on every start.
|
||||
pub fn ensure(dir: &Path, addresses: &[IpAddr]) -> Result<Certificates> {
|
||||
std::fs::DirBuilder::new()
|
||||
.recursive(true)
|
||||
.mode(0o700)
|
||||
.create(dir)
|
||||
.with_context(|| format!("create {}", dir.display()))?;
|
||||
// Set explicitly as well: `mode` applies only when the directory is
|
||||
// created, so a directory that already existed -- made by hand, or by
|
||||
// an older version -- would otherwise keep whatever permissions it had
|
||||
// while holding a private key.
|
||||
std::fs::set_permissions(dir, std::fs::Permissions::from_mode(0o700))
|
||||
.with_context(|| format!("restrict {}", dir.display()))?;
|
||||
private::create_dir(dir)?;
|
||||
|
||||
let ca_cert_path = dir.join("ca.pem");
|
||||
let ca_key_path = dir.join("ca-key.pem");
|
||||
@@ -63,8 +54,8 @@ pub fn ensure(dir: &Path, addresses: &[IpAddr]) -> Result<Certificates> {
|
||||
|
||||
let (ca_pem, ca_key_pem) = if ca_is_new {
|
||||
let (pem, key) = generate_ca()?;
|
||||
write_private(&ca_key_path, &key)?;
|
||||
write_private(&ca_cert_path, &pem)?;
|
||||
private::write_file(&ca_key_path, key.as_bytes())?;
|
||||
private::write_file(&ca_cert_path, pem.as_bytes())?;
|
||||
tracing::info!("generated a new CA in {}", dir.display());
|
||||
(pem, key)
|
||||
} else {
|
||||
@@ -79,8 +70,8 @@ pub fn ensure(dir: &Path, addresses: &[IpAddr]) -> Result<Certificates> {
|
||||
let (leaf_pem, leaf_key_pem) = generate_leaf(&ca_pem, &ca_key_pem, addresses)?;
|
||||
let leaf_cert = dir.join("leaf.pem");
|
||||
let leaf_key = dir.join("leaf-key.pem");
|
||||
write_private(&leaf_key, &leaf_key_pem)?;
|
||||
write_private(&leaf_cert, &leaf_pem)?;
|
||||
private::write_file(&leaf_key, leaf_key_pem.as_bytes())?;
|
||||
private::write_file(&leaf_cert, leaf_pem.as_bytes())?;
|
||||
|
||||
Ok(Certificates { leaf_cert, leaf_key, ca_is_new })
|
||||
}
|
||||
@@ -111,7 +102,7 @@ fn generate_leaf(
|
||||
params.distinguished_name.push(DnType::OrganizationName, "ai-app dev");
|
||||
params.distinguished_name.push(
|
||||
DnType::CommonName,
|
||||
addresses.first().map(|a| a.to_string()).unwrap_or_else(|| "dev-updater".to_string()),
|
||||
addresses.first().map(|a| a.to_string()).unwrap_or_else(|| "ai-app".to_string()),
|
||||
);
|
||||
params.subject_alt_names = addresses.iter().map(|a| SanType::IpAddress(*a)).collect();
|
||||
params.is_ca = IsCa::ExplicitNoCa;
|
||||
@@ -121,24 +112,10 @@ fn generate_leaf(
|
||||
Ok((certificate.pem(), key.serialize_pem()))
|
||||
}
|
||||
|
||||
/// Writes owner-readable only, from the moment the file exists rather than
|
||||
/// a `chmod` afterwards.
|
||||
fn write_private(path: &Path, contents: &str) -> Result<()> {
|
||||
use std::io::Write;
|
||||
let mut file = std::fs::OpenOptions::new()
|
||||
.write(true)
|
||||
.create(true)
|
||||
.truncate(true)
|
||||
.mode(0o600)
|
||||
.open(path)
|
||||
.with_context(|| format!("write {}", path.display()))?;
|
||||
file.write_all(contents.as_bytes())
|
||||
.with_context(|| format!("write {}", path.display()))
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use std::os::unix::fs::PermissionsExt;
|
||||
|
||||
fn addresses() -> Vec<IpAddr> {
|
||||
vec!["10.66.0.1".parse().unwrap(), "127.0.0.1".parse().unwrap()]
|
||||
|
||||
+8
-39
@@ -11,40 +11,12 @@
|
||||
//! JSONL file in its own directory (see `session::transcript`); this file
|
||||
//! holds only the metadata needed to list and respawn sessions.
|
||||
|
||||
use std::fs::File;
|
||||
use std::os::unix::fs::{DirBuilderExt, OpenOptionsExt, PermissionsExt};
|
||||
use std::path::{Path, PathBuf};
|
||||
|
||||
use anyhow::{Context, Result};
|
||||
use serde::{Deserialize, Serialize};
|
||||
|
||||
/// Creates `dir` (and parents) owner-accessible only. Session directories
|
||||
/// and the config directory both go through here: transcripts are whole
|
||||
/// conversations, which is the most sensitive thing this server stores.
|
||||
pub fn create_private_dir(dir: &Path) -> Result<()> {
|
||||
std::fs::DirBuilder::new()
|
||||
.recursive(true)
|
||||
.mode(0o700)
|
||||
.create(dir)
|
||||
.with_context(|| format!("create {}", dir.display()))?;
|
||||
// Set explicitly as well: `mode` applies only when the directory is
|
||||
// created, so one that already existed -- made by hand, or by a
|
||||
// version that didn't do this -- would otherwise keep whatever
|
||||
// permissions it had while holding transcripts.
|
||||
std::fs::set_permissions(dir, std::fs::Permissions::from_mode(0o700))
|
||||
.with_context(|| format!("restrict {}", dir.display()))
|
||||
}
|
||||
|
||||
/// Opens `path` for writing, creating it owner-readable only.
|
||||
pub fn private_file(path: &Path) -> Result<File> {
|
||||
std::fs::OpenOptions::new()
|
||||
.write(true)
|
||||
.create(true)
|
||||
.truncate(true)
|
||||
.mode(0o600)
|
||||
.open(path)
|
||||
.with_context(|| format!("write {}", path.display()))
|
||||
}
|
||||
use crate::private;
|
||||
|
||||
#[derive(Debug, Clone, Default, Serialize, Deserialize)]
|
||||
#[serde(rename_all = "camelCase", default)]
|
||||
@@ -154,9 +126,11 @@ pub struct SessionConfig {
|
||||
/// Working directory the session's process runs in.
|
||||
#[serde(skip_serializing_if = "Option::is_none")]
|
||||
pub cwd: Option<PathBuf>,
|
||||
/// Claude permission mode chosen at spawn (default/plan/acceptEdits/
|
||||
/// bypassPermissions). Meaningless for other kinds; kept as a string
|
||||
/// because it is passed through to the CLI, not interpreted here.
|
||||
/// Claude permission mode chosen at spawn. Meaningless for other
|
||||
/// kinds, and kept as a string because it is passed straight to the
|
||||
/// CLI's `--permission-mode` rather than interpreted here -- so the
|
||||
/// CLI stays the one authority on which modes exist, and a new one
|
||||
/// needs no change on this side.
|
||||
#[serde(skip_serializing_if = "Option::is_none")]
|
||||
pub permission_mode: Option<String>,
|
||||
/// Epoch seconds when the session was spawned.
|
||||
@@ -215,16 +189,11 @@ impl Config {
|
||||
/// config is never briefly world-readable at its real path.
|
||||
pub fn save(&self, path: &Path) -> Result<()> {
|
||||
if let Some(parent) = path.parent() {
|
||||
create_private_dir(parent)?;
|
||||
private::create_dir(parent)?;
|
||||
}
|
||||
let text = serde_json::to_string_pretty(self).context("serialize config")?;
|
||||
let tmp = path.with_extension("json.tmp");
|
||||
{
|
||||
use std::io::Write;
|
||||
let mut file = private_file(&tmp)?;
|
||||
file.write_all(text.as_bytes())
|
||||
.with_context(|| format!("write {}", tmp.display()))?;
|
||||
}
|
||||
private::write_file(&tmp, text.as_bytes())?;
|
||||
std::fs::rename(&tmp, path)
|
||||
.with_context(|| format!("replace {} with {}", path.display(), tmp.display()))?;
|
||||
Ok(())
|
||||
|
||||
+23
-14
@@ -16,6 +16,8 @@
|
||||
mod auth;
|
||||
mod certs;
|
||||
mod config;
|
||||
mod media;
|
||||
mod private;
|
||||
mod routes;
|
||||
mod session;
|
||||
mod ssh;
|
||||
@@ -37,18 +39,22 @@ const WG_INTERFACE: &str = "wg0";
|
||||
/// `$XDG_CONFIG_HOME/ai-app`, or `~/.config/ai-app`. Holds `config.json`
|
||||
/// and `certs/`.
|
||||
fn config_home() -> PathBuf {
|
||||
xdg_dir("XDG_CONFIG_HOME", ".config")
|
||||
xdg_dir(std::env::var_os("XDG_CONFIG_HOME"), ".config")
|
||||
}
|
||||
|
||||
/// `$XDG_DATA_HOME/ai-app`, or `~/.local/share/ai-app`. Holds the session
|
||||
/// directories: transcripts, attachments, produced images.
|
||||
fn data_home() -> PathBuf {
|
||||
xdg_dir("XDG_DATA_HOME", ".local/share")
|
||||
xdg_dir(std::env::var_os("XDG_DATA_HOME"), ".local/share")
|
||||
}
|
||||
|
||||
fn xdg_dir(var: &str, fallback: &str) -> PathBuf {
|
||||
std::env::var_os(var)
|
||||
.map(PathBuf::from)
|
||||
/// This app's directory under `base` -- the XDG variable's value, if it
|
||||
/// was set to an absolute path as the spec requires -- or under
|
||||
/// `~/<fallback>` otherwise. Takes the value rather than reading the
|
||||
/// environment itself so the rule is testable without mutating a
|
||||
/// process-wide variable other threads may be reading.
|
||||
fn xdg_dir(base: Option<std::ffi::OsString>, fallback: &str) -> PathBuf {
|
||||
base.map(PathBuf::from)
|
||||
.filter(|path| path.is_absolute())
|
||||
.unwrap_or_else(|| {
|
||||
std::env::home_dir().unwrap_or_else(|| PathBuf::from(".")).join(fallback)
|
||||
@@ -263,15 +269,18 @@ mod tests {
|
||||
|
||||
#[test]
|
||||
fn xdg_dirs_respect_the_environment_and_are_namespaced() {
|
||||
// Relative values are ignored per the spec, rather than resolving
|
||||
// against whatever the working directory happens to be.
|
||||
unsafe { std::env::set_var("AI_APP_TEST_XDG", "relative/path") };
|
||||
let fallback = xdg_dir("AI_APP_TEST_XDG", ".config");
|
||||
assert!(fallback.is_absolute() || fallback.starts_with("."));
|
||||
assert!(fallback.ends_with("ai-app"));
|
||||
let home_fallback = xdg_dir(None, ".config");
|
||||
assert!(home_fallback.ends_with("ai-app"));
|
||||
assert!(home_fallback.parent().expect("parent").ends_with(".config"));
|
||||
|
||||
unsafe { std::env::set_var("AI_APP_TEST_XDG", "/somewhere") };
|
||||
assert_eq!(xdg_dir("AI_APP_TEST_XDG", ".config"), PathBuf::from("/somewhere/ai-app"));
|
||||
unsafe { std::env::remove_var("AI_APP_TEST_XDG") };
|
||||
assert_eq!(
|
||||
xdg_dir(Some("/somewhere".into()), ".config"),
|
||||
PathBuf::from("/somewhere/ai-app"),
|
||||
);
|
||||
|
||||
// Relative values are ignored per the spec, rather than resolving
|
||||
// against whatever the working directory happens to be -- so a
|
||||
// relative setting lands on the same path as no setting at all.
|
||||
assert_eq!(xdg_dir(Some("relative/path".into()), ".config"), home_fallback);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,59 @@
|
||||
//! The image types that travel between the phone, the session
|
||||
//! directories, and a driver's dialect.
|
||||
//!
|
||||
//! Media type and file extension have to agree in four places -- storing
|
||||
//! an upload, serving it back, handing it to a CLI as a content block, and
|
||||
//! saving one a tool produced -- so the table lives here once. The
|
||||
//! *default* for an unrecognized type is deliberately not here: it differs
|
||||
//! by direction (a phone upload is a photo, a produced image is a
|
||||
//! screenshot), so each caller states its own.
|
||||
|
||||
/// Media type to extension. Only the types Claude's API accepts as image
|
||||
/// content blocks -- anything else has nowhere to go.
|
||||
const IMAGE_TYPES: [(&str, &str); 4] = [
|
||||
("image/png", "png"),
|
||||
("image/jpeg", "jpg"),
|
||||
("image/gif", "gif"),
|
||||
("image/webp", "webp"),
|
||||
];
|
||||
|
||||
/// The extension to store `media_type` under, or `None` if it isn't an
|
||||
/// image type this server handles.
|
||||
pub fn extension_for(media_type: &str) -> Option<&'static str> {
|
||||
IMAGE_TYPES
|
||||
.iter()
|
||||
.find(|(known, _)| *known == media_type)
|
||||
.map(|(_, extension)| *extension)
|
||||
}
|
||||
|
||||
/// The media type of a stored file, from its extension. Names are
|
||||
/// server-generated (`<hex>.<extension>`, always lowercase), so no case
|
||||
/// folding is needed; `None` for anything else.
|
||||
pub fn media_type_for(name: &str) -> Option<&'static str> {
|
||||
let (_, extension) = name.rsplit_once('.')?;
|
||||
IMAGE_TYPES
|
||||
.iter()
|
||||
.find(|(_, known)| *known == extension)
|
||||
.map(|(media_type, _)| *media_type)
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn the_two_directions_agree() {
|
||||
for (media_type, extension) in IMAGE_TYPES {
|
||||
assert_eq!(extension_for(media_type), Some(extension));
|
||||
assert_eq!(media_type_for(&format!("abc123.{extension}")), Some(media_type));
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn unknown_types_are_the_callers_problem() {
|
||||
assert_eq!(extension_for("application/pdf"), None);
|
||||
assert_eq!(media_type_for("abc123.pdf"), None);
|
||||
// No extension at all -- not "the whole name is the extension".
|
||||
assert_eq!(media_type_for("abc123"), None);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,48 @@
|
||||
//! Creating files and directories this server alone can read.
|
||||
//!
|
||||
//! Everything the server writes outside the repo goes through here: the
|
||||
//! config (token hashes, hosts, sessions), the TLS private keys, and the
|
||||
//! session directories holding whole transcripts. One module owns the
|
||||
//! modes so "owner-only" is a property that can be checked in one place
|
||||
//! rather than re-argued at every `create`.
|
||||
|
||||
use std::fs::File;
|
||||
use std::os::unix::fs::{DirBuilderExt, OpenOptionsExt, PermissionsExt};
|
||||
use std::path::Path;
|
||||
|
||||
use anyhow::{Context, Result};
|
||||
|
||||
/// Creates `dir` and its parents, owner-accessible only.
|
||||
pub fn create_dir(dir: &Path) -> Result<()> {
|
||||
std::fs::DirBuilder::new()
|
||||
.recursive(true)
|
||||
.mode(0o700)
|
||||
.create(dir)
|
||||
.with_context(|| format!("create {}", dir.display()))?;
|
||||
// Set explicitly as well: `mode` applies only when the directory is
|
||||
// created, so one that already existed -- made by hand, or by a
|
||||
// version that didn't do this -- would otherwise keep whatever
|
||||
// permissions it had while holding secrets.
|
||||
std::fs::set_permissions(dir, std::fs::Permissions::from_mode(0o700))
|
||||
.with_context(|| format!("restrict {}", dir.display()))
|
||||
}
|
||||
|
||||
/// Opens `path` for writing, truncating it, owner-readable only from the
|
||||
/// moment it exists rather than by a `chmod` afterwards.
|
||||
pub fn create_file(path: &Path) -> Result<File> {
|
||||
std::fs::OpenOptions::new()
|
||||
.write(true)
|
||||
.create(true)
|
||||
.truncate(true)
|
||||
.mode(0o600)
|
||||
.open(path)
|
||||
.with_context(|| format!("write {}", path.display()))
|
||||
}
|
||||
|
||||
/// Writes `contents` to `path`, owner-readable only.
|
||||
pub fn write_file(path: &Path, contents: &[u8]) -> Result<()> {
|
||||
use std::io::Write;
|
||||
create_file(path)?
|
||||
.write_all(contents)
|
||||
.with_context(|| format!("write {}", path.display()))
|
||||
}
|
||||
+15
-17
@@ -69,8 +69,8 @@ pub fn router(manager: Arc<SessionManager>) -> Router {
|
||||
|
||||
#[derive(Debug, thiserror::Error)]
|
||||
enum ApiError {
|
||||
#[error("no session {0}")]
|
||||
UnknownSession(String),
|
||||
#[error("{0}")]
|
||||
NotFound(String),
|
||||
#[error("no such route")]
|
||||
UnknownRoute,
|
||||
#[error("{0}")]
|
||||
@@ -82,7 +82,7 @@ enum ApiError {
|
||||
impl IntoResponse for ApiError {
|
||||
fn into_response(self) -> Response {
|
||||
let status = match self {
|
||||
Self::UnknownSession(_) | Self::UnknownRoute => StatusCode::NOT_FOUND,
|
||||
Self::NotFound(_) | Self::UnknownRoute => StatusCode::NOT_FOUND,
|
||||
Self::BadRequest(_) => StatusCode::BAD_REQUEST,
|
||||
Self::Internal(err) => {
|
||||
// The only variant whose real cause isn't safe to hand
|
||||
@@ -103,7 +103,7 @@ fn bad_request(err: anyhow::Error) -> ApiError {
|
||||
}
|
||||
|
||||
fn lookup(manager: &SessionManager, id: &str) -> Result<Arc<LiveSession>, ApiError> {
|
||||
manager.session(id).ok_or_else(|| ApiError::UnknownSession(id.to_string()))
|
||||
manager.session(id).ok_or_else(|| ApiError::NotFound(format!("no session {id}")))
|
||||
}
|
||||
|
||||
async fn list_sessions(State(manager): State<Arc<SessionManager>>) -> axum::Json<Vec<SessionInfo>> {
|
||||
@@ -207,8 +207,8 @@ async fn delete_session(
|
||||
#[serde(rename_all = "camelCase")]
|
||||
struct MessageRequest {
|
||||
text: String,
|
||||
/// Ids from `POST /attachments` (phase 2); accepted now so the request
|
||||
/// shape doesn't change under the app.
|
||||
/// Ids from `POST /attachments`, uploaded before the message that
|
||||
/// references them.
|
||||
#[serde(default)]
|
||||
attachment_ids: Vec<String>,
|
||||
}
|
||||
@@ -326,18 +326,16 @@ async fn serve_file(
|
||||
let candidates =
|
||||
[session.dir().join("files").join(&name), session.dir().join("attachments").join(&name)];
|
||||
let Some(path) = candidates.iter().find(|path| path.is_file()) else {
|
||||
return Err(ApiError::BadRequest(format!("no file {name} in session {id}")));
|
||||
};
|
||||
let bytes = std::fs::read(path).map_err(|err| {
|
||||
tracing::error!("read {} failed: {err}", path.display());
|
||||
ApiError::BadRequest("file unreadable".to_string())
|
||||
})?;
|
||||
let content_type = match name.rsplit('.').next() {
|
||||
Some("png") => "image/png",
|
||||
Some("gif") => "image/gif",
|
||||
Some("webp") => "image/webp",
|
||||
_ => "image/jpeg",
|
||||
return Err(ApiError::NotFound(format!("no file {name} in session {id}")));
|
||||
};
|
||||
// A file that is there but unreadable is this server's fault, not the
|
||||
// request's -- Internal logs it and says nothing more to the caller.
|
||||
let bytes = std::fs::read(path)
|
||||
.with_context(|| format!("read {}", path.display()))
|
||||
.map_err(ApiError::Internal)?;
|
||||
// Names are server-generated, so an unrecognized extension can only
|
||||
// mean a file this server didn't write.
|
||||
let content_type = crate::media::media_type_for(&name).unwrap_or("image/jpeg");
|
||||
Ok(([(axum::http::header::CONTENT_TYPE, content_type)], bytes).into_response())
|
||||
}
|
||||
|
||||
|
||||
@@ -339,21 +339,14 @@ fn attachment_block(session_dir: &Path, id: &str) -> Result<Value> {
|
||||
"type": "image",
|
||||
"source": {
|
||||
"type": "base64",
|
||||
"media_type": media_type_of(id),
|
||||
// Ids carry the extension the upload was stored under, so an
|
||||
// unrecognized one means a name this server didn't write.
|
||||
"media_type": crate::media::media_type_for(id).unwrap_or("image/jpeg"),
|
||||
"data": base64::engine::general_purpose::STANDARD.encode(bytes),
|
||||
}
|
||||
}))
|
||||
}
|
||||
|
||||
fn media_type_of(name: &str) -> &'static str {
|
||||
match name.rsplit('.').next() {
|
||||
Some("png") => "image/png",
|
||||
Some("gif") => "image/gif",
|
||||
Some("webp") => "image/webp",
|
||||
_ => "image/jpeg",
|
||||
}
|
||||
}
|
||||
|
||||
/// What answering a question produced.
|
||||
enum AnswerOutcome {
|
||||
/// Send this control_response line to the CLI.
|
||||
@@ -563,9 +556,7 @@ impl Translator {
|
||||
"response": {"subtype": "success", "request_id": request_id, "response": response},
|
||||
}))
|
||||
}
|
||||
}
|
||||
|
||||
impl Translator {
|
||||
/// `user` messages: tool results become ToolEnd, with any image parts
|
||||
/// saved into the session dir and referenced by an Image event (the
|
||||
/// phone fetches them from `/sessions/{id}/files/{ref}`). Replayed and
|
||||
@@ -620,16 +611,17 @@ impl Translator {
|
||||
let data = source.get("data")?.as_str()?;
|
||||
use base64::Engine;
|
||||
let bytes = base64::engine::general_purpose::STANDARD.decode(data).ok()?;
|
||||
let extension = match source.get("media_type").and_then(Value::as_str) {
|
||||
Some("image/jpeg") => "jpg",
|
||||
Some("image/gif") => "gif",
|
||||
Some("image/webp") => "webp",
|
||||
_ => "png",
|
||||
};
|
||||
// Screenshots are the overwhelming case, and they are PNG; an
|
||||
// unrecognized type is more likely a dialect change than a JPEG.
|
||||
let extension = source
|
||||
.get("media_type")
|
||||
.and_then(Value::as_str)
|
||||
.and_then(crate::media::extension_for)
|
||||
.unwrap_or("png");
|
||||
let name = format!("{}.{extension}", super::random_hex());
|
||||
let dir = self.session_dir.join("files");
|
||||
if let Err(err) =
|
||||
crate::config::create_private_dir(&dir)
|
||||
crate::private::create_dir(&dir)
|
||||
.map_err(std::io::Error::other)
|
||||
.and_then(|()| std::fs::write(dir.join(&name), bytes))
|
||||
{
|
||||
|
||||
@@ -9,9 +9,10 @@
|
||||
use serde::{Deserialize, Serialize};
|
||||
use tokio::sync::mpsc;
|
||||
|
||||
/// Attachment id of an uploaded image, as returned by `POST /attachments`
|
||||
/// (arrives in phase 2; the vocabulary is fixed now so the trait doesn't
|
||||
/// change under the first two drivers).
|
||||
/// The name a session's image is stored and served under -- returned by
|
||||
/// `POST /attachments` for an upload, minted by a driver for one a tool
|
||||
/// produced, and fetched back from `/sessions/{id}/files/{ref}`. Both
|
||||
/// directions use the one id so the transcript renders them identically.
|
||||
pub type ImageRef = String;
|
||||
|
||||
/// Everything a session can tell the outside world. Every event is
|
||||
@@ -36,8 +37,8 @@ pub enum Event {
|
||||
},
|
||||
ToolUpdate { id: String, output: String },
|
||||
ToolEnd { id: String, output: String },
|
||||
/// An image the session produced, saved under the session dir and
|
||||
/// referenced by id; the phone fetches it by URL (phase 2).
|
||||
/// An image the session produced or was sent, saved under the session
|
||||
/// dir and referenced by id; the phone fetches it by URL.
|
||||
Image {
|
||||
#[serde(rename = "ref")]
|
||||
image: ImageRef,
|
||||
|
||||
@@ -46,7 +46,7 @@ impl Driver for EchoDriver {
|
||||
let sink = self.sink.clone();
|
||||
|
||||
if let Some(rest) = text.strip_prefix("/question") {
|
||||
let id = format!("q-{}", rand_id());
|
||||
let id = format!("q-{}", super::random_hex());
|
||||
let prompt = if rest.trim().is_empty() {
|
||||
"Echo asks: proceed?".to_string()
|
||||
} else {
|
||||
@@ -71,7 +71,7 @@ impl Driver for EchoDriver {
|
||||
send(Event::Status { state: SessionStatus::Running });
|
||||
|
||||
if let Some(input) = run_tool {
|
||||
let id = format!("t-{}", rand_id());
|
||||
let id = format!("t-{}", super::random_hex());
|
||||
send(Event::ToolStart {
|
||||
id: id.clone(),
|
||||
tool: "echo-tool".to_string(),
|
||||
@@ -132,12 +132,3 @@ impl Driver for EchoDriver {
|
||||
self.emit(Event::Status { state: SessionStatus::Exited });
|
||||
}
|
||||
}
|
||||
|
||||
/// Short random suffix for tool/question ids -- unique within a session is
|
||||
/// all that's needed.
|
||||
fn rand_id() -> String {
|
||||
use rand::Rng;
|
||||
let mut bytes = [0u8; 4];
|
||||
rand::rng().fill_bytes(&mut bytes);
|
||||
bytes.iter().map(|b| format!("{b:02x}")).collect()
|
||||
}
|
||||
@@ -139,15 +139,12 @@ impl LiveSession {
|
||||
/// references it by. Removed with the session directory on delete --
|
||||
/// the same path out as everything else in it.
|
||||
pub fn save_attachment(&self, bytes: &[u8], content_type: &str) -> Result<String> {
|
||||
let extension = match content_type {
|
||||
"image/png" => "png",
|
||||
"image/gif" => "gif",
|
||||
"image/webp" => "webp",
|
||||
_ => "jpg",
|
||||
};
|
||||
// An unrecognized type is almost always a phone photo whose
|
||||
// content type the picker didn't set; jpg is the useful guess.
|
||||
let extension = crate::media::extension_for(content_type).unwrap_or("jpg");
|
||||
let name = format!("{}.{extension}", random_hex());
|
||||
let dir = self.dir().join("attachments");
|
||||
crate::config::create_private_dir(&dir)?;
|
||||
crate::private::create_dir(&dir)?;
|
||||
std::fs::write(dir.join(&name), bytes)
|
||||
.with_context(|| format!("write attachment {name}"))?;
|
||||
Ok(name)
|
||||
@@ -189,7 +186,7 @@ impl SessionManager {
|
||||
/// session spawns its event pump).
|
||||
pub fn new(config_path: PathBuf, data_dir: PathBuf) -> Result<Self> {
|
||||
let config = Config::load(&config_path)?;
|
||||
crate::config::create_private_dir(&data_dir)?;
|
||||
crate::private::create_dir(&data_dir)?;
|
||||
|
||||
let mut live = HashMap::new();
|
||||
for meta in &config.sessions {
|
||||
@@ -451,7 +448,7 @@ fn launch(
|
||||
data_dir: &Path,
|
||||
) -> Result<Arc<LiveSession>> {
|
||||
let dir = data_dir.join(&meta.id);
|
||||
crate::config::create_private_dir(&dir)?;
|
||||
crate::private::create_dir(&dir)?;
|
||||
let transcript_path = dir.join("transcript.jsonl");
|
||||
let transcript = Transcript::open(&transcript_path)?;
|
||||
|
||||
|
||||
Reference in new issue
Block a user