The truly free, open-source, local-first, cross-platform CapCut replacement. Scriptable through a JSON-RPC API & MCP.
Rust ffmpegfree-video-editormodel-context-protocolnon-linear-editoroffline-firstopen-source-video-editorself-hostedvideo-editingvideo-editing-automationvideo-editing-softwarevideo-editing-toolsvideo-editorvoice-cloningyoutube-automationyoutube-shorts
fix(api): writes stay under the server's roots, sizes are bounded, the transport has limits, the window and its Remote page share one export slot and one register of open projects
Jareer2d47b71042a3
diff --git a/ARCHITECTURE.md b/ARCHITECTURE.mdindex 52cbb407..8458f81b 100644--- a/ARCHITECTURE.md+++ b/ARCHITECTURE.md@@ -255,7 +255,8 @@ flowchart LR```mermaidflowchart LR- window["the window"] --> api+ window["the window"] -- "Remote page: embeds a server" --> hub+ window -- "its own Session" --> hostcli["concat-cli"] --> apijson["JSON-RPC lines<br/>TCP or a Unix socket"] --> hubgrpc["gRPC (feature)"] --> hub@@ -269,6 +270,15 @@ comparison is constant-time. `version` reports `capabilities` so a client cantell what a build serves before calling. The CLI prints the token it serveswith; the window's Remote page shows it.+The window is not a client of its own API. Its Remote page embeds a+server whose `Api` has sessions of its own; what the two share is the+export slot, so one export at a time holds across them, and a register+of open project folders (`concat_api::OpenProjects`), so neither opens+a folder the other is editing. The API writes only under its roots+(`Config::roots`, the home folder by default) and bounds what a caller+may ask for; the JSON transport caps line length, connections and the+time to present a token.+## 8. Testing and measuring| Suite | Where | What it holds |diff --git a/docs/api/methods.md b/docs/api/methods.mdindex f6ccb563..750cac18 100644--- a/docs/api/methods.md+++ b/docs/api/methods.md@@ -93,6 +93,10 @@ Good to know:- A fresh project has one timeline `TL1` with four tracks `T1`–`T4`.- It is added to the recents list, like one the window made.- A folder that already holds a project is refused (`failed`).+- Over a socket, `location` must lie under one of the server's write+ roots, or the request is `refused`; see the JSON-RPC transport's+ [Security](../transports/json-rpc.md#security). A folder the window has+ open is `refused` too.---@@ -402,6 +406,8 @@ Good to know:- **Every slot must be filled.** A set that leaves one empty makes nothing.- Every file is probed first, so a bad path refuses the whole request andleaves no folder behind.+- Over a socket, `location` must lie under one of the server's write+ roots, or the request is `refused`.---@@ -465,8 +471,14 @@ orRules:-- **One export at a time.** A second is refused with `busy`.+- **One export at a time.** A second is refused with `busy`. From the+ window's Remote page the slot is the window's own, so an export begun+ in the Export sheet counts.- An empty timeline is `refused`.+- Over a socket, `output` must lie under one of the server's write roots,+ or the request is `refused`.+- `width` and `height` are at most 8192 a side, the frame rate at most+ 240 a second, `crf` at most 63: anything larger is `invalid`.- `cutout.progress` only appears for clips with an automatic cutout whosemasks are not cached yet. `fetching` is true while the model downloads.- Event shapes are in [Types → Events](types.md#events). The job model is@@ -522,6 +534,8 @@ Rules:- `width` and `height` count only **together**. Give both or neither;neither means the timeline's size.-- Zero for either is `invalid`.+- Zero for either is `invalid`, and so is anything over 8192 a side.+- Over a socket, `output` must lie under one of the server's write roots,+ or the request is `refused`.- The PNG is RGBA, 8 bits a channel, base64 in the standard alphabet withpadding.diff --git a/docs/transports/json-rpc.md b/docs/transports/json-rpc.mdindex 6f135327..ed4746ff 100644--- a/docs/transports/json-rpc.md+++ b/docs/transports/json-rpc.md@@ -91,6 +91,7 @@ Concat API 0.2: token 3f9c1e…| `--socket PATH` | A Unix socket path (Unix only). A file already there is replaced || `--grpc ADDR` | gRPC, in a build with the feature. See [gRPC](grpc.md) || `--token TOKEN` | The token every connection presents. Also `CONCAT_API_TOKEN`. Minted when absent |+| `--root DIR` | A folder the API may write under. Repeatable. Your home when absent; `--root /` for anywhere |Several flags at once serve on all of them. All callers share onedispatcher and its open projects.@@ -109,9 +110,11 @@ open.| **Token** | Yours, or one the window mints and shows you when the field is empty || Status line | "Listening on … · N connected", or why the bind failed |-Edits made over the socket land in the same session the window shows.-What you can do from the window, you can do from the socket, and the-other way round.+A caller on the socket edits projects of its own, never the one on+screen: a folder the window has open is `refused` over the socket, and+the window refuses to open one a caller holds. The export slot is shared,+so one export at a time holds across the two. The API writes under your+home folder.---@@ -162,15 +165,26 @@ you → {"jsonrpc":"2.0","id":7,"method":"project.get",...}## Security> [!WARNING]-> The API reads and writes whatever paths it is given, as the user running-> it. A server is a door into the machine.+> A server is a door into the machine, as the user running it. The door+> is narrow, and the token is the only key.- **No encryption.** Bind off loopback only behind something thatprovides it (an SSH tunnel, a reverse proxy with TLS).- The token gates the door; the network is the wall. Do not put the porton the open internet.-- Anyone with the token can create, edit and export projects and read any- file the server's user can read.+- **Writes stay under the roots.** A created project, an instantiated+ template, an export and a preview file must land under a `--root` (the+ window: your home folder); anything else is `refused`, and a path with+ `..` in it always is. Reads are not confined: anyone with the token can+ probe any file the server's user can read and open any project folder.+- **Sizes are bounded.** A frame or an export is at most 8192 a side, an+ export's frame rate at most 240 a second and its `crf` at most 63:+ anything larger is `invalid`.+- **The transport has limits.** A line is at most 4 MiB (the `auth` line+ 4 KiB); a caller has ten seconds to present its token; at most 64+ callers are connected at once, the next is answered `busy` and closed;+ a caller that stops reading is hung up on once 256 lines are waiting+ for it.---diff --git a/src/crates/concat-api/src/lib.rs b/src/crates/concat-api/src/lib.rsindex 38e5e886..6785a430 100644--- a/src/crates/concat-api/src/lib.rs+++ b/src/crates/concat-api/src/lib.rs@@ -33,7 +33,7 @@ pub mod rpc;use std::collections::BTreeMap;use std::path::{Path, PathBuf};-use std::sync::Arc;+use std::sync::{Arc, Mutex};use std::thread::JoinHandle;use base64::Engine as _;@@ -69,11 +69,90 @@ const CAPABILITIES: &[&str] = &["events"];/// that writes them to a caller locks its writer inside.pub type EventSink = Arc<dyn Fn(Event) + Send + Sync>;+/// The largest frame a preview or an export may ask for, a side: 8K. A+/// caller with the token is trusted to edit, not to ask the machine for+/// seventeen gigabytes of pixels (audit 2026-09-23, #4).+pub const MAX_SIDE: u32 = 8192;+/// The highest constant rate factor any codec here takes.+const MAX_CRF: u8 = 63;+/// The fastest frame rate an export may ask for.+const MAX_RATE: f64 = 240.0;++/// Who holds a project folder open on this machine.+#[derive(Clone, Copy, Debug, PartialEq, Eq)]+pub enum Holder {+ /// The window, on screen.+ Window,+ /// The API, for a caller on a socket.+ Api,+}++impl std::fmt::Display for Holder {+ fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {+ f.write_str(match self {+ Holder::Window => "the window",+ Holder::Api => "the API",+ })+ }+}++/// The project folders open on this machine and who has each, shared+/// between a window and the API it embeds, so neither opens a folder the+/// other is editing and saves over its work (audit 2026-09-23, #5). Cheap+/// to clone; every clone is the same register.+#[derive(Clone, Default)]+pub struct OpenProjects(Arc<Mutex<BTreeMap<String, Holder>>>);++impl OpenProjects {+ /// Claims `path` for `holder`. Refused, naming who has it, when the+ /// other side does; claiming again what one already holds is fine.+ pub fn claim(&self, path: &str, holder: Holder) -> Result<(), Holder> {+ let key = key_of(path);+ let mut open = self+ .0+ .lock()+ .unwrap_or_else(|poisoned| poisoned.into_inner());+ match open.get(&key) {+ Some(&other) if other != holder => Err(other),+ _ => {+ open.insert(key, holder);+ Ok(())+ }+ }+ }++ /// Gives `path` back, whoever had it.+ pub fn release(&self, path: &str) {+ let key = key_of(path);+ self.0+ .lock()+ .unwrap_or_else(|poisoned| poisoned.into_inner())+ .remove(&key);+ }++ /// Who has `path` open, if anyone.+ pub fn holder(&self, path: &str) -> Option<Holder> {+ let key = key_of(path);+ self.0+ .lock()+ .unwrap_or_else(|poisoned| poisoned.into_inner())+ .get(&key)+ .copied()+ }+}+/// The dispatcher: the open sessions and the services behind them.pub struct Api {dirs: AppDirs,/// Open projects by canonical folder path.sessions: BTreeMap<String, Session>,+ /// Where this API may write: a created project, an instantiated+ /// template, an export or a preview file lands under one of these.+ /// Empty means anywhere, for the process's own owner at a terminal.+ roots: Vec<PathBuf>,+ /// Which project folders are open on this machine, across this API+ /// and a window it is embedded in.+ open: OpenProjects,titles: Titles,cutouts: Arc<Cutouts>,monitor: Monitor,@@ -100,6 +179,8 @@ impl Api {monitor: Monitor::new(),exporter: Exporter::new(),sessions: BTreeMap::new(),+ roots: Vec::new(),+ open: OpenProjects::default(),events,jobs: Jobs::default(),dirs,@@ -127,6 +208,72 @@ impl Api {self.exporter.clone()}+ /// Takes an embedder's export slot in place of its own, so "one export+ /// at a time" holds across a window and this API together.+ pub fn share_exporter(&mut self, exporter: Exporter) {+ self.exporter = exporter;+ }++ /// Takes an embedder's register of open projects in place of its own,+ /// so a folder the window has open is refused here, and the other way+ /// round.+ pub fn share_open_projects(&mut self, open: OpenProjects) {+ self.open = open;+ }++ /// Confines every write to `roots`: from here on a created project, an+ /// instantiated template, an export and a preview file must land under+ /// one of them, and any other path is `refused`. Reads - a probe, a+ /// project opened by path - are not confined. An empty list confines+ /// nothing, which is right for the process's own owner at a terminal+ /// and wrong for a socket.+ pub fn restrict_writes_to(&mut self, roots: Vec<PathBuf>) {+ self.roots = roots+ .into_iter()+ .map(|root| root.canonicalize().unwrap_or(root))+ .collect();+ }++ /// The roots writes are confined to; empty when they are not.+ pub fn roots(&self) -> &[PathBuf] {+ &self.roots+ }++ /// `path` as somewhere this API may write, or why not.+ fn writable(&self, path: &str) -> Result<(), ApiError> {+ if self.roots.is_empty() {+ return Ok(());+ }+ let outside = || {+ let roots = self+ .roots+ .iter()+ .map(|root| root.display().to_string())+ .collect::<Vec<_>>()+ .join(", ");+ ApiError::new(+ ErrorCode::Refused,+ format!("{path} is outside where this API writes ({roots})"),+ )+ };+ let given = Path::new(path);+ // A `..` past the part of the path that exists cannot be resolved+ // and would walk out of a root on paper while staying under it in+ // this check; there is no reason a caller needs one.+ if given+ .components()+ .any(|part| matches!(part, std::path::Component::ParentDir))+ {+ return Err(outside());+ }+ let target = resolved(given);+ if self.roots.iter().any(|root| target.starts_with(root)) {+ Ok(())+ } else {+ Err(outside())+ }+ }+/// How many jobs are still running.pub fn running(&mut self) -> usize {self.jobs.reap();@@ -235,6 +382,7 @@ impl Api {name: &str,video: VideoSettings,) -> Result<EditorView, ApiError> {+ self.writable(location)?;let info = projects::create(location,name,@@ -260,7 +408,19 @@ impl Api {/// Opens a session on a project the host just described and puts it at/// the front of the recents list.fn adopt(&mut self, info: ProjectInfo) -> Result<EditorView, ApiError> {- let session = Session::open_info(&info).map_err(ApiError::failed)?;+ if let Err(holder) = self.open.claim(&info.path, Holder::Api) {+ return Err(ApiError::new(+ ErrorCode::Refused,+ format!("{} is open in {holder}", info.path),+ ));+ }+ let session = match Session::open_info(&info) {+ Ok(session) => session,+ Err(error) => {+ self.open.release(&info.path);+ return Err(ApiError::failed(error));+ }+ };// Recents are a convenience for the launch screen; a machine whose// config folder cannot be written still edits.let _ = projects::remember(&self.dirs.config, &info);@@ -274,10 +434,15 @@ impl Api {if save {self.save(path, None)?;}- self.sessions+ let closed = self+ .sessions.remove(&key_of(path)).map(drop)- .ok_or_else(|| not_open(path))+ .ok_or_else(|| not_open(path));+ if closed.is_ok() {+ self.open.release(path);+ }+ closed}/// [`Request::ProjectList`].@@ -309,6 +474,7 @@ impl Api {name: &str,fills: Vec<Fill>,) -> Result<EditorView, ApiError> {+ self.writable(location)?;// Every file is probed before anything is made, so a bad path// refuses the whole request rather than leaving a folder behind.let fills = fills@@ -350,6 +516,7 @@ impl Api {/// shot where there is none; then the render, with the titles already/// painted here and rejoining the clip list as stills.pub fn export(&mut self, path: &str, spec: &ExportSpec) -> Result<Started, ApiError> {+ self.writable(&spec.output)?;let session = self.session(path)?;if session.project().active().clips.is_empty() {return Err(ApiError::new(@@ -358,8 +525,18 @@ impl Api {));}let settings = session.settings();- let width = spec.width.unwrap_or(settings.width);- let height = spec.height.unwrap_or(settings.height);+ let (width, height) = checked_size(+ spec.width.unwrap_or(settings.width),+ spec.height.unwrap_or(settings.height),+ )?;+ if let Some(crf) = spec.crf+ && crf > MAX_CRF+ {+ return Err(ApiError::invalid(format!("crf {crf} is over {MAX_CRF}")));+ }+ let rate_num = spec.rate_num.unwrap_or(settings.rate_num);+ let rate_den = spec.rate_den.unwrap_or(settings.rate_den);+ checked_rate(rate_num, rate_den)?;let codec = match spec.codec.as_deref() {None => export::VideoCodec::H264,Some(name) => export::VideoCodec::parse(name).ok_or_else(|| {@@ -397,8 +574,8 @@ impl Api {let mut request = export::request(session, &host_spec, titles);request.width = width;request.height = height;- request.rate_num = spec.rate_num.unwrap_or(settings.rate_num);- request.rate_den = spec.rate_den.unwrap_or(settings.rate_den);+ request.rate_num = rate_num;+ request.rate_den = rate_den;let slot = self.exporter@@ -460,6 +637,7 @@ impl Api {output: &str,size: Option<(u32, u32)>,) -> Result<Written, ApiError> {+ self.writable(output)?;let (width, height, pixels) = self.pixels(path, time, size)?;write_png(Path::new(output), width, height, &pixels)?;Ok(Written {@@ -497,9 +675,7 @@ impl Api {let session = self.session(path)?;let settings = session.settings();let (width, height) = size.unwrap_or((settings.width, settings.height));- if width == 0 || height == 0 {- return Err(ApiError::invalid("A frame needs a width and a height"));- }+ let (width, height) = checked_size(width, height)?;let mut clips = session.flattened_clips();clips.extend(self.title_clips(session, width, height));let pixels = self@@ -681,6 +857,68 @@ fn catalogue(kind: Option<&str>) -> Result<Vec<PackageInfo>, ApiError> {/// The key a project folder is held under: its canonical path where the/// folder exists, so `.` and an absolute spelling of it are one session,/// and the path as given where it does not yet.+impl Drop for Api {+ /// The register is shared with an embedder that outlives this API:+ /// what it held open is given back.+ fn drop(&mut self) {+ for key in self.sessions.keys() {+ self.open.release(key);+ }+ }+}++/// A frame size a caller may ask for, or why not.+fn checked_size(width: u32, height: u32) -> Result<(u32, u32), ApiError> {+ if width == 0 || height == 0 {+ return Err(ApiError::invalid("A frame needs a width and a height"));+ }+ if width > MAX_SIDE || height > MAX_SIDE {+ return Err(ApiError::invalid(format!(+ "{width}×{height} is over {MAX_SIDE} a side"+ )));+ }+ Ok((width, height))+}++/// A frame rate a caller may ask for, or why not.+fn checked_rate(num: i64, den: i64) -> Result<(), ApiError> {+ if num <= 0 || den <= 0 {+ return Err(ApiError::invalid(+ "A frame rate needs a positive numerator and denominator",+ ));+ }+ if num as f64 / den as f64 > MAX_RATE {+ return Err(ApiError::invalid(format!(+ "{num}/{den} is over {MAX_RATE} frames a second"+ )));+ }+ Ok(())+}++/// `path` with its symlinks resolved as far as it exists: the deepest+/// ancestor that is there, canonicalised, with the rest appended. A file+/// not written yet still says where it would land.+fn resolved(path: &Path) -> PathBuf {+ let mut existing = path;+ let mut rest: Vec<std::ffi::OsString> = Vec::new();+ loop {+ if let Ok(real) = existing.canonicalize() {+ let mut out = real;+ for part in rest.iter().rev() {+ out.push(part);+ }+ return out;+ }+ match (existing.parent(), existing.file_name()) {+ (Some(parent), Some(name)) if !parent.as_os_str().is_empty() => {+ rest.push(name.to_owned());+ existing = parent;+ }+ _ => return path.to_path_buf(),+ }+ }+}+fn key_of(path: &str) -> String {std::fs::canonicalize(path).map(|canonical| canonical.to_string_lossy().into_owned())@@ -1130,4 +1368,101 @@ mod tests {}));assert_eq!(refused.code, ErrorCode::Invalid);}++ #[test]+ fn writes_stay_under_the_roots() {+ let (mut api, scratch, _events) = api();+ let allowed = scratch.path().join("allowed");+ std::fs::create_dir_all(&allowed).expect("allowed");+ api.restrict_writes_to(vec![allowed.clone()]);+ let outside = scratch+ .path()+ .join("elsewhere")+ .to_string_lossy()+ .into_owned();+ let refused = err(api.dispatch(Request::ProjectCreate {+ location: outside.clone(),+ name: "Out".to_owned(),+ video: None,+ }));+ assert_eq!(refused.code, ErrorCode::Refused);+ assert!(!scratch.path().join("elsewhere").exists(), "nothing made");+ let inside = allowed.to_string_lossy().into_owned();+ ok(api.dispatch(Request::ProjectCreate {+ location: inside.clone(),+ name: "In".to_owned(),+ video: None,+ }));+ let path = format!("{inside}/In");+ for output in [+ format!("{inside}/../elsewhere/frame.png"),+ format!("{outside}/frame.png"),+ ] {+ let refused = err(api.dispatch(Request::PreviewFrame {+ path: path.clone(),+ time: 0.0,+ output: Some(output.clone()),+ width: None,+ height: None,+ }));+ assert_eq!(refused.code, ErrorCode::Refused, "{output}");+ }+ // Under the root, into a folder not there yet, is fine.+ let written = serde_json::to_value(ok(api.dispatch(Request::PreviewFrame {+ path,+ time: 0.0,+ output: Some(format!("{inside}/frames/first.png")),+ width: Some(16),+ height: Some(9),+ })))+ .expect("JSON");+ assert!(+ written["path"]+ .as_str()+ .is_some_and(|written| written.ends_with("first.png"))+ );+ }++ #[test]+ fn a_frame_over_8k_a_side_is_invalid() {+ let (mut api, scratch, _events) = api();+ let path = project(&mut api, &scratch, "Big");+ let refused = err(api.dispatch(Request::PreviewFrame {+ path,+ time: 0.0,+ output: None,+ width: Some(65_535),+ height: Some(65_535),+ }));+ assert_eq!(refused.code, ErrorCode::Invalid);+ }++ #[test]+ fn a_project_the_window_holds_is_refused_and_the_other_way_round() {+ let (mut api, scratch, _events) = api();+ let path = project(&mut api, &scratch, "Mine");+ ok(api.dispatch(Request::ProjectClose {+ path: path.clone(),+ save: false,+ }));+ let open = OpenProjects::default();+ api.share_open_projects(open.clone());+ open.claim(&path, Holder::Window)+ .expect("the window has it");+ let refused = err(api.dispatch(Request::ProjectOpen { path: path.clone() }));+ assert_eq!(refused.code, ErrorCode::Refused);+ open.release(&path);+ ok(api.dispatch(Request::ProjectOpen { path: path.clone() }));+ assert_eq!(open.holder(&path), Some(Holder::Api));+ assert_eq!(+ open.claim(&path, Holder::Window),+ Err(Holder::Api),+ "and the window is refused in turn"+ );+ ok(api.dispatch(Request::ProjectClose {+ path: path.clone(),+ save: false,+ }));+ assert_eq!(open.holder(&path), None, "closing gives it back");+ }}diff --git a/src/crates/concat-cli/src/main.rs b/src/crates/concat-cli/src/main.rsindex a7895298..efbc8841 100644--- a/src/crates/concat-cli/src/main.rs+++ b/src/crates/concat-cli/src/main.rs@@ -85,6 +85,11 @@ enum Command {/// given, and printed either way.#[arg(long, env = "CONCAT_API_TOKEN")]token: Option<String>,+ /// A folder the API may write under: created projects, exports,+ /// preview files. Repeatable. Your home when none is given; `/`+ /// for anywhere.+ #[arg(long = "root", value_name = "DIR")]+ roots: Vec<PathBuf>,},/// Run one picture through an effect at its defaults and write the@@ -133,7 +138,8 @@ fn main() -> Result<(), Box<dyn Error>> {socket,grpc,token,- } => serve(json, socket, grpc, token),+ roots,+ } => serve(json, socket, grpc, token, roots),Command::Preview {input,output,@@ -193,6 +199,7 @@ fn serve(socket: Option<PathBuf>,grpc: Option<SocketAddr>,token: Option<String>,+ roots: Vec<PathBuf>,) -> Result<(), Box<dyn Error>> {let nothing_asked = json.is_none() && socket.is_none() && grpc.is_none();let config = concat_server::Config {@@ -200,6 +207,7 @@ fn serve(socket,grpc,token,+ roots,};let server = concat_server::Server::start(config, concat_api::Api::new)?;if let Some(address) = server.json_addr() {@@ -223,6 +231,20 @@ fn serve(concat_api::API_VERSION,server.token());+ let roots = server.roots();+ println!(+ "Concat API {}: writes under {}",+ concat_api::API_VERSION,+ if roots.is_empty() {+ "anywhere".to_owned()+ } else {+ roots+ .iter()+ .map(|root| root.display().to_string())+ .collect::<Vec<_>>()+ .join(", ")+ }+ );loop {std::thread::park();}diff --git a/src/crates/concat-server/src/grpc.rs b/src/crates/concat-server/src/grpc.rsindex 103fc283..0e709f58 100644--- a/src/crates/concat-server/src/grpc.rs+++ b/src/crates/concat-server/src/grpc.rs@@ -68,10 +68,11 @@ impl Concat for Service {_request: Request<proto::EventsRequest>,) -> Result<tonic::Response<Self::EventsStream>, Status> {let (sender, receiver) = tokio::sync::mpsc::channel(64);- // Called on the job's thread, where blocking is fine; a send that- // fails is a caller that hung up.- self.hub.subscribe(Box::new(move |event: &Event| {- sender.blocking_send(Ok(encode_event(event))).is_ok()+ // Called on the job's thread, which must not wait on a caller: one+ // that has not taken the last sixty-four events is treated as gone,+ // like one that hung up.+ self.hub.subscribe(Arc::new(move |event: &Event| {+ sender.try_send(Ok(encode_event(event))).is_ok()}));Ok(tonic::Response::new(ReceiverStream::new(receiver)))}diff --git a/src/crates/concat-server/src/hub.rs b/src/crates/concat-server/src/hub.rsindex ddd0fcbd..4997ecf4 100644--- a/src/crates/concat-server/src/hub.rs+++ b/src/crates/concat-server/src/hub.rs@@ -23,7 +23,7 @@ use concat_api::{Api, ApiError, ErrorCode, Event, EventSink, Request, Response};/// A way to hand an event to one caller. Returns false once the caller is/// gone, after which it is dropped.-pub type Subscriber = Box<dyn Fn(&Event) -> bool + Send>;+pub type Subscriber = Arc<dyn Fn(&Event) -> bool + Send + Sync>;/// One call waiting its turn.struct Task {@@ -49,8 +49,20 @@ impl Hub {let sink: EventSink = {let subscribers = Arc::clone(&subscribers);Arc::new(move |event: Event| {- if let Ok(mut subscribers) = subscribers.lock() {- subscribers.retain(|subscriber| subscriber(&event));+ // Called with the list unlocked: a caller slow to take an+ // event holds up the job's thread and nobody's subscribe.+ let listening: Vec<Subscriber> = match subscribers.lock() {+ Ok(list) => list.clone(),+ Err(_) => return,+ };+ let gone: Vec<&Subscriber> = listening+ .iter()+ .filter(|subscriber| !subscriber(&event))+ .collect();+ if !gone.is_empty()+ && let Ok(mut list) = subscribers.lock()+ {+ list.retain(|kept| !gone.iter().any(|left| Arc::ptr_eq(kept, left)));}})};diff --git a/src/crates/concat-server/src/json.rs b/src/crates/concat-server/src/json.rsindex aba0f470..04f3c5ff 100644--- a/src/crates/concat-server/src/json.rs+++ b/src/crates/concat-server/src/json.rs@@ -18,10 +18,11 @@use std::io::{BufRead, BufReader, Write};use std::net::TcpListener;-use std::sync::atomic::{AtomicBool, Ordering};-use std::sync::mpsc::{self, Sender};+use std::sync::atomic::{AtomicBool, AtomicUsize, Ordering};+use std::sync::mpsc::{self, SyncSender};use std::sync::{Arc, Mutex};use std::thread::JoinHandle;+use std::time::Duration;use concat_api::rpc::{Call, Id, Message};use concat_api::{ApiError, Done, ErrorCode, Reply, Response};@@ -29,6 +30,59 @@ use serde_json::Value;use crate::{Connections, Hub, token};+/// The longest line a caller may send once it is in: a document-sized+/// edit fits, a buffer grown to whatever arrives does not.+pub const MAX_LINE: usize = 4 * 1024 * 1024;+/// The longest first line: the `auth` call is a few dozen bytes.+pub const MAX_AUTH_LINE: usize = 4 * 1024;+/// How long a caller has to present its token before the connection is+/// closed, so one that connects and says nothing holds no thread.+pub const AUTH_TIMEOUT: Duration = Duration::from_secs(10);+/// How many callers may be connected at once; the next is refused with+/// `busy` and closed.+pub const MAX_CONNECTIONS: usize = 64;+/// How many lines may wait for a caller that is not reading them before+/// the connection is closed rather than the queue grown.+const OUTBOX_LINES: usize = 256;++/// One of the [`MAX_CONNECTIONS`] seats; given back when dropped.+struct Seat(Arc<AtomicUsize>);++impl Seat {+ fn take(seats: &Arc<AtomicUsize>) -> Option<Seat> {+ let mut taken = seats.load(Ordering::SeqCst);+ loop {+ if taken >= MAX_CONNECTIONS {+ return None;+ }+ match seats.compare_exchange(taken, taken + 1, Ordering::SeqCst, Ordering::SeqCst) {+ Ok(_) => return Some(Seat(Arc::clone(seats))),+ Err(now) => taken = now,+ }+ }+ }+}++impl Drop for Seat {+ fn drop(&mut self) {+ self.0.fetch_sub(1, Ordering::SeqCst);+ }+}++/// Tells a caller there is no seat, and hangs up.+fn refuse_full(mut writer: impl Write) {+ let line = Message::Reply {+ id: None,+ response: Response::Error(ApiError::new(+ ErrorCode::Busy,+ format!("{MAX_CONNECTIONS} callers are connected already"),+ )),+ }+ .to_json();+ let _ = writeln!(writer, "{line}");+ let _ = writer.flush();+}+/// Accepts JSON-RPC connections on `listener` until `stop` is set.pub(crate) fn serve_tcp(listener: TcpListener,@@ -36,6 +90,7 @@ pub(crate) fn serve_tcp(token: String,stop: Arc<AtomicBool>,connections: Connections,+ seats: Arc<AtomicUsize>,) -> JoinHandle<()> {std::thread::spawn(move || {for stream in listener.incoming() {@@ -44,6 +99,10 @@ pub(crate) fn serve_tcp(}let Ok(stream) = stream else { continue };let _ = stream.set_nodelay(true);+ let Some(seat) = Seat::take(&seats) else {+ refuse_full(stream);+ continue;+ };let Ok(reader) = stream.try_clone() else {continue;};@@ -53,15 +112,24 @@ pub(crate) fn serve_tcp(let Ok(ender) = stream.try_clone() else {continue;};+ let Ok(timer) = stream.try_clone() else {+ continue;+ };if let Ok(mut connections) = connections.lock() {connections.push(Box::new(move || {let _ = closer.shutdown(std::net::Shutdown::Both);}));}+ // The handshake has this long; once it is done the caller may+ // be silent for as long as it likes.+ let _ = stream.set_read_timeout(Some(AUTH_TIMEOUT));let hub = hub.clone();let token = token.clone();std::thread::spawn(move || {- connection(BufReader::new(reader), stream, hub, token);+ let _seat = seat;+ connection(BufReader::new(reader), stream, hub, token, move || {+ let _ = timer.set_read_timeout(None);+ });// The registry above still holds a handle, so the socket is// shut here rather than merely dropped: the caller sees EOF.let _ = ender.shutdown(std::net::Shutdown::Both);@@ -78,6 +146,7 @@ pub(crate) fn serve_unix(token: String,stop: Arc<AtomicBool>,connections: Connections,+ seats: Arc<AtomicUsize>,) -> JoinHandle<()> {std::thread::spawn(move || {for stream in listener.incoming() {@@ -85,6 +154,10 @@ pub(crate) fn serve_unix(break;}let Ok(stream) = stream else { continue };+ let Some(seat) = Seat::take(&seats) else {+ refuse_full(stream);+ continue;+ };let Ok(reader) = stream.try_clone() else {continue;};@@ -94,15 +167,24 @@ pub(crate) fn serve_unix(let Ok(ender) = stream.try_clone() else {continue;};+ let Ok(timer) = stream.try_clone() else {+ continue;+ };if let Ok(mut connections) = connections.lock() {connections.push(Box::new(move || {let _ = closer.shutdown(std::net::Shutdown::Both);}));}+ // The handshake has this long; once it is done the caller may+ // be silent for as long as it likes.+ let _ = stream.set_read_timeout(Some(AUTH_TIMEOUT));let hub = hub.clone();let token = token.clone();std::thread::spawn(move || {- connection(BufReader::new(reader), stream, hub, token);+ let _seat = seat;+ connection(BufReader::new(reader), stream, hub, token, move || {+ let _ = timer.set_read_timeout(None);+ });// The registry above still holds a handle, so the socket is// shut here rather than merely dropped: the caller sees EOF.let _ = ender.shutdown(std::net::Shutdown::Both);@@ -112,13 +194,26 @@ pub(crate) fn serve_unix(}/// One caller, start to end: the handshake, then a call per line.-fn connection(reader: impl BufRead, writer: impl Write + Send + 'static, hub: Hub, token: String) {+/// `authenticated` runs once the token has been presented, for the+/// transport to lift the handshake's timeout.+fn connection(+ mut reader: impl BufRead,+ writer: impl Write + Send + 'static,+ hub: Hub,+ token: String,+ authenticated: impl FnOnce(),+) {let outbox = Outbox::start(writer);- let mut lines = reader.lines().map_while(Result::ok);- let Some(first) = lines.find(|line| !line.trim().is_empty()) else {- outbox.close();- return;+ let first = loop {+ match read_line(&mut reader, MAX_AUTH_LINE) {+ None => {+ outbox.close();+ return;+ }+ Some(line) if line.trim().is_empty() => continue,+ Some(line) => break line,+ }};let (id, outcome) = handshake(&first, &token);let ok = outcome.is_ok();@@ -130,15 +225,16 @@ fn connection(reader: impl BufRead, writer: impl Write + Send + 'static, hub: Huoutbox.close();return;}+ authenticated();// Events reach this caller from here on: the outbox is shared with the// hub's fan-out, which drops it once a send fails.let events = outbox.clone();- hub.subscribe(Box::new(move |event| {+ hub.subscribe(Arc::new(move |event| {events.send(Message::Event(event.clone()))}));- for line in lines {+ while let Some(line) = read_line(&mut reader, MAX_LINE) {if line.trim().is_empty() {continue;}@@ -153,6 +249,19 @@ fn connection(reader: impl BufRead, writer: impl Write + Send + 'static, hub: Huoutbox.close();}+/// One line of at most `cap` bytes, its newline taken off. `None` at the+/// end of the stream, on a read error, and for a line over the cap, which+/// ends the connection: the buffer grows to the cap and no further,+/// whatever the caller sends.+fn read_line(reader: &mut impl BufRead, cap: usize) -> Option<String> {+ let mut line = String::new();+ match std::io::Read::take(&mut *reader, cap as u64 + 1).read_line(&mut line) {+ Ok(0) | Err(_) => None,+ Ok(_) if line.len() > cap && !line.ends_with('\n') => None,+ Ok(_) => Some(line.trim_end_matches(['\r', '\n']).to_owned()),+ }+}+/// Reads the first line as the `auth` call and checks its token, in/// constant time.fn handshake(line: &str, token: &str) -> (Option<Id>, Result<Reply, ApiError>) {@@ -184,13 +293,15 @@ fn handshake(line: &str, token: &str) -> (Option<Id>, Result<Reply, ApiError>) {/// The connection's one writer: a queue and the thread that drains it.#[derive(Clone)]struct Outbox {- queue: Arc<Mutex<Option<Sender<Message>>>>,+ queue: Arc<Mutex<Option<SyncSender<Message>>>>,writer: Arc<Mutex<Option<JoinHandle<()>>>>,}impl Outbox {fn start(mut writer: impl Write + Send + 'static) -> Outbox {- let (queue, messages) = mpsc::channel::<Message>();+ // Bounded: a caller that stops reading is hung up on at the cap,+ // not kept in memory line by line.+ let (queue, messages) = mpsc::sync_channel::<Message>(OUTBOX_LINES);let thread = std::thread::spawn(move || {for message in messages {if writeln!(writer, "{}", message.to_json()).is_err() || writer.flush().is_err() {@@ -209,7 +320,7 @@ impl Outbox {match self.queue.lock() {Ok(queue) => queue.as_ref()- .is_some_and(|queue| queue.send(message).is_ok()),+ .is_some_and(|queue| queue.try_send(message).is_ok()),Err(_) => false,}}@@ -270,6 +381,38 @@ mod tests {}}+ #[test]+ fn a_line_over_the_cap_ends_the_connection() {+ let (server, _scratch) = server(None);+ let mut client = Client::connect(&server);+ let long = "a".repeat(MAX_LINE + 2);+ // The write may fail part way once the server hangs up; that is+ // the point.+ let _ = writeln!(client.writer, "{long}");+ let mut after = String::new();+ assert_eq!(+ client.reader.read_line(&mut after).unwrap_or(0),+ 0,+ "closed without an answer"+ );+ server.stop();+ }++ #[test]+ fn a_full_house_refuses_the_next_caller() {+ let (server, _scratch) = server(None);+ let seated: Vec<Client> = (0..MAX_CONNECTIONS)+ .map(|_| Client::connect(&server))+ .collect();+ let mut late = Client::reach(&server);+ let mut line = String::new();+ late.reader.read_line(&mut line).expect("a refusal");+ let refused: Value = serde_json::from_str(&line).expect("a JSON line");+ assert_eq!(refused["error"]["data"]["code"], "busy", "{refused}");+ drop(seated);+ server.stop();+ }+#[test]fn a_call_over_tcp_is_answered_with_its_id() {let (server, _scratch) = server(None);diff --git a/src/crates/concat-server/src/lib.rs b/src/crates/concat-server/src/lib.rsindex d3fee2ee..a1c02c3b 100644--- a/src/crates/concat-server/src/lib.rs+++ b/src/crates/concat-server/src/lib.rs@@ -20,16 +20,21 @@//! caller; each names its job and its project, so a caller keeps the ones//! it asked for.//!-//! The API reads and writes whatever paths it is given, so a server is a-//! door into the machine. Every connection presents a token before its-//! first call, loopback included: another user's process on the same-//! machine reaches 127.0.0.1 as easily as this one does. A server given-//! no token mints one, 128 bits from the operating system's randomness,-//! that only the process that started it knows; [`Server::token`] is how-//! that process passes it on, to a page or a terminal. The token is-//! compared in constant time, whichever transport carries it. There is-//! no encryption: a bind off loopback belongs behind something that-//! provides it.+//! A server is a door into the machine, so the door is narrow. Every+//! connection presents a token before its first call, loopback included:+//! another user's process on the same machine reaches 127.0.0.1 as+//! easily as this one does. A server given no token mints one, 128 bits+//! from the operating system's randomness, that only the process that+//! started it knows; [`Server::token`] is how that process passes it on,+//! to a page or a terminal. The token is compared in constant time,+//! whichever transport carries it. The API writes only under the roots+//! the server is given - the user's home unless told otherwise+//! ([`Config::roots`]) - and a frame or an export is bounded in size.+//! The JSON transport reads a line of at most [`json::MAX_LINE`] bytes,+//! gives a caller [`json::AUTH_TIMEOUT`] to present its token, seats at+//! most [`json::MAX_CONNECTIONS`] callers at once and hangs up on one+//! that stops reading its replies. There is no encryption: a bind off+//! loopback belongs behind something that provides it.mod hub;pub mod json;@@ -64,6 +69,20 @@ pub struct Config {/// point, and it is why a bind off loopback needs no token set here/// to be safe to make.pub token: Option<String>,+ /// The folders the API may write under: a created project, an+ /// instantiated template, an export, a preview file. Empty means the+ /// user's home ([`home_root`]); to write anywhere, name `/`.+ pub roots: Vec<PathBuf>,+}++/// Where the API writes when told nothing else: the user's home folder,+/// or nowhere when the platform has none to name.+pub fn home_root() -> Vec<PathBuf> {+ std::env::var_os("HOME")+ .or_else(|| std::env::var_os("USERPROFILE"))+ .filter(|home| !home.is_empty())+ .map(|home| vec![PathBuf::from(home)])+ .unwrap_or_default()}impl Config {@@ -91,6 +110,7 @@ pub struct Server {socket: Option<PathBuf>,grpc: Option<SocketAddr>,token: String,+ roots: Vec<PathBuf>,stop: Arc<AtomicBool>,listeners: Vec<JoinHandle<()>>,connections: Connections,@@ -122,15 +142,23 @@ impl Server {.into_iter().flatten().collect();+ let roots = if config.roots.is_empty() {+ home_root()+ } else {+ config.roots.clone()+ };+ let confined = roots.clone();let (hub, dispatcher) = Hub::start(move |events| {let mut api = make(events)?;for transport in transports {api.add_capability(transport);}+ api.restrict_writes_to(confined);Ok(api)})?;let stop = Arc::new(AtomicBool::new(false));let connections: Connections = Arc::new(Mutex::new(Vec::new()));+ let seats = Arc::new(std::sync::atomic::AtomicUsize::new(0));let mut server = Server {hub,dispatcher: Some(dispatcher),@@ -138,6 +166,7 @@ impl Server {socket: None,grpc: None,token,+ roots,stop: Arc::clone(&stop),listeners: Vec::new(),connections: Arc::clone(&connections),@@ -157,6 +186,7 @@ impl Server {server.token.clone(),Arc::clone(&stop),Arc::clone(&connections),+ Arc::clone(&seats),));}@@ -171,6 +201,7 @@ impl Server {server.token.clone(),Arc::clone(&stop),Arc::clone(&connections),+ Arc::clone(&seats),));server.socket = Some(path);}@@ -217,6 +248,11 @@ impl Server {&self.token}+ /// The folders the API writes under; empty when it may write anywhere.+ pub fn roots(&self) -> &[PathBuf] {+ &self.roots+ }+/// How many callers are connected.pub fn connections(&self) -> usize {self.hub.subscribers()@@ -284,6 +320,7 @@ pub(crate) mod tests {let config = Config {json: Some("127.0.0.1:0".parse().expect("an address")),token: token.map(str::to_owned),+ roots: vec![scratch.path().to_path_buf()],..Config::default()};let server =diff --git a/src/crates/concat/locales/de.json b/src/crates/concat/locales/de.jsonindex ef79b155..0bf4fcc0 100644--- a/src/crates/concat/locales/de.json+++ b/src/crates/concat/locales/de.json@@ -899,6 +899,7 @@"This clip has no sound to render": "Dieser Clip hat keinen Ton zum Rendern","This file has no picture to enhance": "Diese Datei hat kein Bild zum Verbessern","This model reads only with its own speakers": "Dieses Modell liest nur mit seinen eigenen Sprechern",+ "This project is open through the Remote API": "Dieses Projekt ist über die Remote-API geöffnet","Threshold": "Threshold","Tiles": "Kacheln","Tilt Shift": "Tilt-Shift",diff --git a/src/crates/concat/locales/en.json b/src/crates/concat/locales/en.jsonindex a17fba8b..9548d89f 100644--- a/src/crates/concat/locales/en.json+++ b/src/crates/concat/locales/en.json@@ -899,6 +899,7 @@"This clip has no sound to render": "This clip has no sound to render","This file has no picture to enhance": "This file has no picture to enhance","This model reads only with its own speakers": "This model reads only with its own speakers",+ "This project is open through the Remote API": "This project is open through the Remote API","Threshold": "Threshold","Tiles": "Tiles","Tilt Shift": "Tilt Shift",diff --git a/src/crates/concat/locales/es.json b/src/crates/concat/locales/es.jsonindex 8bc2a1d3..b35476d4 100644--- a/src/crates/concat/locales/es.json+++ b/src/crates/concat/locales/es.json@@ -899,6 +899,7 @@"This clip has no sound to render": "Este clip no tiene sonido que renderizar","This file has no picture to enhance": "Este archivo no tiene imagen que mejorar","This model reads only with its own speakers": "Este modelo solo lee con sus propias voces",+ "This project is open through the Remote API": "Este proyecto está abierto a través de la API remota","Threshold": "Threshold","Tiles": "Mosaicos","Tilt Shift": "Tilt Shift",diff --git a/src/crates/concat/locales/fa.json b/src/crates/concat/locales/fa.jsonindex 3fb06f6b..4c600746 100644--- a/src/crates/concat/locales/fa.json+++ b/src/crates/concat/locales/fa.json@@ -899,6 +899,7 @@"This clip has no sound to render": "این کلیپ صدایی برای رندر ندارد","This file has no picture to enhance": "این فایل تصویری برای بهبود کیفیت ندارد","This model reads only with its own speakers": "این مدل فقط با گویندههای خودش میخواند",+ "This project is open through the Remote API": "این پروژه از طریق API راه دور باز است","Threshold": "آستانه","Tiles": "کاشیها","Tilt Shift": "تیلت شیفت (Tilt Shift)",diff --git a/src/crates/concat/locales/fr.json b/src/crates/concat/locales/fr.jsonindex c07ec7be..e5f2b484 100644--- a/src/crates/concat/locales/fr.json+++ b/src/crates/concat/locales/fr.json@@ -899,6 +899,7 @@"This clip has no sound to render": "Ce clip n'a pas de son à rendre","This file has no picture to enhance": "Ce fichier n'a pas d'image à améliorer","This model reads only with its own speakers": "Ce modèle ne lit qu'avec ses propres voix",+ "This project is open through the Remote API": "Ce projet est ouvert via l’API distante","Threshold": "Threshold","Tiles": "Tuiles","Tilt Shift": "Bascule-décentrement",diff --git a/src/crates/concat/locales/hr.json b/src/crates/concat/locales/hr.jsonindex 5e20766c..7a2979be 100644--- a/src/crates/concat/locales/hr.json+++ b/src/crates/concat/locales/hr.json@@ -899,6 +899,7 @@"This clip has no sound to render": "Ovaj klip nema zvuka za renderiranje","This file has no picture to enhance": "Ova datoteka nema slike za poboljšanje","This model reads only with its own speakers": "Ovaj model čita samo vlastitim govornicima",+ "This project is open through the Remote API": "Ovaj je projekt otvoren putem udaljenog API-ja","Threshold": "Prag","Tiles": "Pločice","Tilt Shift": "Tilt-shift",diff --git a/src/crates/concat/locales/it.json b/src/crates/concat/locales/it.jsonindex 4b85ffdf..7ac743de 100644--- a/src/crates/concat/locales/it.json+++ b/src/crates/concat/locales/it.json@@ -899,6 +899,7 @@"This clip has no sound to render": "Questa clip non ha un suono da renderizzare","This file has no picture to enhance": "Questo file non ha un'immagine da migliorare","This model reads only with its own speakers": "Questo modello legge solo con le proprie voci",+ "This project is open through the Remote API": "Questo progetto è aperto tramite l’API remota","Threshold": "Threshold","Tiles": "Tessere","Tilt Shift": "Tilt shift",diff --git a/src/crates/concat/locales/ja.json b/src/crates/concat/locales/ja.jsonindex ad43c899..6a45f0f5 100644--- a/src/crates/concat/locales/ja.json+++ b/src/crates/concat/locales/ja.json@@ -899,6 +899,7 @@"This clip has no sound to render": "このクリップにはレンダリングするサウンドがありません","This file has no picture to enhance": "このファイルには高画質化する映像がありません","This model reads only with its own speakers": "このモデルは内蔵の話者でのみ読み上げます",+ "This project is open through the Remote API": "このプロジェクトはリモート API で開かれています","Threshold": "Threshold","Tiles": "タイル","Tilt Shift": "ティルトシフト",diff --git a/src/crates/concat/locales/ko.json b/src/crates/concat/locales/ko.jsonindex c9a3e41e..10fcc728 100644--- a/src/crates/concat/locales/ko.json+++ b/src/crates/concat/locales/ko.json@@ -899,6 +899,7 @@"This clip has no sound to render": "이 클립에는 렌더링할 사운드가 없습니다","This file has no picture to enhance": "이 파일에는 향상할 영상이 없습니다","This model reads only with its own speakers": "이 모델은 자체 화자로만 읽습니다",+ "This project is open through the Remote API": "이 프로젝트는 원격 API를 통해 열려 있습니다","Threshold": "Threshold","Tiles": "타일","Tilt Shift": "틸트 시프트",diff --git a/src/crates/concat/locales/pt-BR.json b/src/crates/concat/locales/pt-BR.jsonindex 0bb9f1a9..8dcc18d3 100644--- a/src/crates/concat/locales/pt-BR.json+++ b/src/crates/concat/locales/pt-BR.json@@ -899,6 +899,7 @@"This clip has no sound to render": "Este clipe não tem som para renderizar","This file has no picture to enhance": "Este arquivo não tem imagem para melhorar","This model reads only with its own speakers": "Este modelo lê só com as próprias vozes",+ "This project is open through the Remote API": "Este projeto está aberto pela API remota","Threshold": "Threshold","Tiles": "Ladrilhos","Tilt Shift": "Tilt shift",diff --git a/src/crates/concat/locales/ru.json b/src/crates/concat/locales/ru.jsonindex 61c26d03..e0402bef 100644--- a/src/crates/concat/locales/ru.json+++ b/src/crates/concat/locales/ru.json@@ -899,6 +899,7 @@"This clip has no sound to render": "У этого клипа нет звука для рендеринга","This file has no picture to enhance": "В этом файле нет картинки для улучшения","This model reads only with its own speakers": "Эта модель читает только своими голосами",+ "This project is open through the Remote API": "Этот проект открыт через удалённый API","Threshold": "Порог","Tiles": "Плитки","Tilt Shift": "Тилт-шифт",diff --git a/src/crates/concat/locales/tr.json b/src/crates/concat/locales/tr.jsonindex f99cf95a..b51f0256 100644--- a/src/crates/concat/locales/tr.json+++ b/src/crates/concat/locales/tr.json@@ -899,6 +899,7 @@"This clip has no sound to render": "Bu klibin işlenecek sesi yok","This file has no picture to enhance": "Bu dosyanın iyileştirilecek görüntüsü yok","This model reads only with its own speakers": "Bu model yalnızca kendi konuşmacılarıyla okur",+ "This project is open through the Remote API": "Bu proje Uzak API üzerinden açık","Threshold": "Threshold","Tiles": "Döşemeler","Tilt Shift": "Tilt shift",diff --git a/src/crates/concat/locales/zh-Hans.json b/src/crates/concat/locales/zh-Hans.jsonindex 998cb6a8..9028f90d 100644--- a/src/crates/concat/locales/zh-Hans.json+++ b/src/crates/concat/locales/zh-Hans.json@@ -899,6 +899,7 @@"This clip has no sound to render": "此片段没有可渲染的声音","This file has no picture to enhance": "此文件没有可增强的画面","This model reads only with its own speakers": "此模型只能用自己的说话人朗读",+ "This project is open through the Remote API": "此项目已通过远程 API 打开","Threshold": "Threshold","Tiles": "拼贴数","Tilt Shift": "移轴",diff --git a/src/crates/concat/locales/zh-TW.json b/src/crates/concat/locales/zh-TW.jsonindex dd833d04..14a59774 100644--- a/src/crates/concat/locales/zh-TW.json+++ b/src/crates/concat/locales/zh-TW.json@@ -899,6 +899,7 @@"This clip has no sound to render": "此片段沒有可算繪的聲音","This file has no picture to enhance": "此檔案沒有可強化的畫面","This model reads only with its own speakers": "此模型僅能以內建語者朗讀",+ "This project is open through the Remote API": "此專案已透過遠端 API 開啟","Threshold": "臨界值","Tiles": "拼貼數","Tilt Shift": "移軸",diff --git a/src/crates/concat/src/host.rs b/src/crates/concat/src/host.rsindex 51ddfce2..8858fca1 100644--- a/src/crates/concat/src/host.rs+++ b/src/crates/concat/src/host.rs@@ -50,8 +50,12 @@ pub struct Host {pub enhancers: Arc<concat_host::Enhancers>,/// The Concat API on a socket, while the Remote page has it on. Its/// own sessions, apart from the window's: a caller edits projects of- /// its own, not the one on screen.+ /// its own, never the one on screen, which `open_projects` keeps it+ /// from opening; the export slot is shared, so one export at a time+ /// holds across the two.pub server: Option<concat_server::Server>,+ /// Which project folders are open, here or over the socket.+ pub open_projects: concat_api::OpenProjects,}impl Host {@@ -77,6 +81,7 @@ impl Host {transcriber: Arc::new(Transcriber::new()),speech: Arc::new(Speech::new()),server: None,+ open_projects: concat_api::OpenProjects::default(),})}}diff --git a/src/crates/concat/src/panes/settings.rs b/src/crates/concat/src/panes/settings.rsindex aea4fc1f..bfa4793c 100644--- a/src/crates/concat/src/panes/settings.rs+++ b/src/crates/concat/src/panes/settings.rs@@ -380,6 +380,8 @@ impl SettingsPane {server.stop();}self.server_error.clear();+ let exporter = studio.host.exporter.clone();+ let open_projects = studio.host.open_projects.clone();let prefs = &studio.prefs.server;if !prefs.enabled {return;@@ -400,7 +402,15 @@ impl SettingsPane {token: Some(prefs.token.clone()).filter(|token| !token.is_empty()),..concat_server::Config::default()};- concat_server::Server::start(config, concat_api::Api::new)+ // The window's export slot and its register of open+ // projects, so one export at a time holds across the two+ // and a caller never edits the project on screen.+ concat_server::Server::start(config, move |events| {+ let mut api = concat_api::Api::new(events)?;+ api.share_exporter(exporter);+ api.share_open_projects(open_projects);+ Ok(api)+ })});match started {Ok(server) => studio.host.server = Some(server),diff --git a/src/crates/concat/src/studio.rs b/src/crates/concat/src/studio.rsindex fbdfa4c3..db2f156f 100644--- a/src/crates/concat/src/studio.rs+++ b/src/crates/concat/src/studio.rs@@ -5231,6 +5231,14 @@ impl Studio {/// Opens a project as the session and leaves the launch screen, or/// says why it could not.pub fn open_project(&mut self, info: ProjectInfo) -> Result<(), String> {+ if self+ .host+ .open_projects+ .claim(&info.path, concat_api::Holder::Window)+ .is_err()+ {+ return Err(t("This project is open through the Remote API"));+ }match Session::open_info(&info) {Ok(session) => {if let Err(error) = projects::remember(&self.host.dirs.config, &info) {@@ -5286,7 +5294,10 @@ impl Studio {}Ok(())}- Err(error) => Err(error),+ Err(error) => {+ self.host.open_projects.release(&info.path);+ Err(error)+ }}}@@ -5325,6 +5336,9 @@ impl Studio {}}self.autosave.stop();+ if let Some(session) = self.session.as_ref() {+ self.host.open_projects.release(session.path());+ }self.session = None;// Whatever a worker still brings back for this project is dropped// at delivery; the sheets that were waiting on one stop waiting.