1use alloc::collections::VecDeque;
6use alloc::string::{String, ToString};
7use alloc::vec::Vec;
8use std::path::Path;
9
10use standard_plugin_manifest::paths::{Excludes, PathGrants, real};
11
12use super::MockHost;
13use crate::daemon::process::{Command, Stdio};
14use crate::error::{Error, Result};
15use crate::ui_runtime::Event;
16
17#[derive(Clone, Debug, Default, PartialEq, Eq)]
21pub struct ProcessScript {
22 pub stdout: Vec<u8>,
23 pub stderr: Vec<u8>,
24 pub status: i32,
25}
26
27impl ProcessScript {
28 pub fn exit(status: i32) -> Self {
30 Self {
31 status,
32 ..Self::default()
33 }
34 }
35
36 pub fn stdout(mut self, bytes: impl AsRef<[u8]>) -> Self {
37 self.stdout = bytes.as_ref().to_vec();
38 self
39 }
40
41 pub fn stderr(mut self, bytes: impl AsRef<[u8]>) -> Self {
42 self.stderr = bytes.as_ref().to_vec();
43 self
44 }
45}
46
47#[derive(Clone, Debug, PartialEq, Eq)]
49pub struct MockProcess {
50 pub pid: u32,
52 pub program: String,
53 pub args: Vec<String>,
54 pub env: Vec<(String, String)>,
58 pub cwd: Option<String>,
60 pub stdin: Vec<u8>,
61 pub stdin_closed: bool,
62 pub status: Option<i32>,
67 pub killed: bool,
68 pub channel: bool,
71 pub sent: Vec<String>,
72 stdout: Stdio,
73 stderr: Stdio,
74}
75
76impl MockProcess {
77 pub fn var(&self, name: &str) -> Option<&str> {
79 self.env
80 .iter()
81 .find(|(key, _)| key == name)
82 .map(|(_, value)| value.as_str())
83 }
84}
85
86#[derive(Clone, Debug, PartialEq, Eq)]
88pub struct MockWatch {
89 pub handle: u32,
90 pub path: String,
91 pub recursive: bool,
92 pub exclude: Vec<String>,
93}
94
95#[derive(Clone, Debug, PartialEq, Eq)]
98pub struct MockPaneLaunch {
99 pub id: String,
101 pub project: String,
103 pub cwd: String,
104 pub command: Option<String>,
105 pub env: Vec<(String, String)>,
106 pub title: Option<String>,
109 pub hidden: bool,
111 pub input: Vec<u8>,
113 pub screen: crate::daemon::panes::Screen,
115 pub history: Option<serde_json::Value>,
117 pub history_queries: Vec<serde_json::Value>,
119 pub closed: bool,
121}
122
123#[derive(Clone, Debug, Default)]
125pub(crate) struct Machine {
126 pub processes: Vec<MockProcess>,
127 pub pane_launches: Vec<MockPaneLaunch>,
128 pub panes_subscribed: bool,
130 pub scripts: Vec<(String, Option<Vec<String>>, ProcessScript)>,
131 pub watches: Vec<MockWatch>,
132 pub websockets: Vec<MockWebSocket>,
134 next_pid: u32,
135 next_watch: u32,
136 pub pending: VecDeque<Event>,
138}
139
140#[derive(Clone, Debug, PartialEq, Eq)]
142pub struct MockWebSocket {
143 pub socket: u32,
144 pub url: String,
145 pub headers: Vec<(String, String)>,
146 pub sent: Vec<String>,
148 pub closed: bool,
149}
150
151const MAX_WATCHES: usize = 256;
153
154impl MockHost {
155 pub fn websockets(&self) -> &[MockWebSocket] {
157 &self.machine.websockets
158 }
159
160 pub fn websocket_event(&mut self, socket: u32, kind: &str, text: &str) {
164 let payload = match kind {
165 "message" => serde_json::json!({"socket": socket, "kind": kind, "text": text}),
166 "closed" => serde_json::json!({"socket": socket, "kind": kind, "reason": text}),
167 _ => serde_json::json!({"socket": socket, "kind": kind}),
168 };
169 self.machine.pending.push_back(Event::Plugin {
170 name: String::from(crate::daemon::net::WEBSOCKET_EVENT),
171 payload: crate::Json(payload.to_string()),
172 });
173 }
174
175 pub fn endpoint_accept(&mut self, endpoint: &str, machine: Option<&str>) -> u32 {
180 self.endpoint_accept_from(endpoint, machine, None)
181 }
182
183 pub fn endpoint_accept_from(
186 &mut self,
187 endpoint: &str,
188 machine: Option<&str>,
189 pane: Option<&str>,
190 ) -> u32 {
191 let socket = (1 << 31) | (self.machine.websockets.len() as u32 + 1);
192 self.machine.websockets.push(MockWebSocket {
193 socket,
194 url: alloc::format!("endpoint:{endpoint}"),
195 headers: Vec::new(),
196 sent: Vec::new(),
197 closed: false,
198 });
199 let payload = serde_json::json!({
200 "socket": socket,
201 "kind": "accepted",
202 "endpoint": endpoint,
203 "path": "/",
204 "machine": machine,
205 "pane": pane,
206 });
207 self.machine.pending.push_back(Event::Plugin {
208 name: String::from(crate::daemon::net::WEBSOCKET_EVENT),
209 payload: crate::Json(payload.to_string()),
210 });
211 socket
212 }
213
214 pub(crate) fn websocket_open(
215 &mut self,
216 url: &str,
217 headers: &[(String, String)],
218 ) -> Result<u32> {
219 let (target, secure) = match (url.strip_prefix("wss://"), url.strip_prefix("ws://")) {
220 (Some(rest), _) => (rest, true),
221 (None, Some(rest)) => (rest, false),
222 _ => {
223 return Err(Error::Invalid(alloc::format!(
224 "{url:?} is not a wss:// URL"
225 )));
226 }
227 };
228 let target = target.split('/').next().unwrap_or_default();
229 let (host, port) = match target.rsplit_once(':') {
230 Some((host, port)) => (host, port.parse::<u16>().unwrap_or(0)),
231 None => (target, if secure { 443 } else { 80 }),
232 };
233 if !secure {
234 if !matches!(host, "127.0.0.1" | "localhost" | "[::1]") {
237 return Err(Error::Invalid(alloc::format!(
238 "{url:?} is not on this machine's loopback"
239 )));
240 }
241 if !self.grants.allows("machine.full") && !self.grants.allows("network.full") {
242 return Err(self.deny(standard_plugin_manifest::GrantDenied {
243 grant: "network.full".into(),
244 }));
245 }
246 } else if !self.grants.socket_ports(host).contains(&port) {
247 return Err(self.deny(standard_plugin_manifest::GrantDenied {
248 grant: alloc::format!("socket.connect:{host}:{port}"),
249 }));
250 }
251 let socket = self.machine.websockets.len() as u32 + 1;
252 self.machine.websockets.push(MockWebSocket {
253 socket,
254 url: url.to_string(),
255 headers: headers.to_vec(),
256 sent: Vec::new(),
257 closed: false,
258 });
259 Ok(socket)
260 }
261
262 pub(crate) fn websocket_send(&mut self, socket: u32, text: &str) -> Result<()> {
263 let open = self
264 .machine
265 .websockets
266 .iter_mut()
267 .find(|open| open.socket == socket && !open.closed)
268 .ok_or_else(|| Error::Invalid(alloc::format!("socket {socket} is not open")))?;
269 open.sent.push(text.to_string());
270 Ok(())
271 }
272
273 pub(crate) fn websocket_close(&mut self, socket: u32) {
274 if let Some(open) = self
275 .machine
276 .websockets
277 .iter_mut()
278 .find(|open| open.socket == socket)
279 {
280 open.closed = true;
281 }
282 }
283
284 pub fn script(mut self, program: &str, script: ProcessScript) -> Self {
287 self.machine
288 .scripts
289 .insert(0, (program.to_string(), None, script));
290 self
291 }
292
293 pub fn script_args(mut self, program: &str, args: &[&str], script: ProcessScript) -> Self {
295 let args = args.iter().map(|arg| arg.to_string()).collect();
296 self.machine
297 .scripts
298 .insert(0, (program.to_string(), Some(args), script));
299 self
300 }
301
302 pub fn processes(&self) -> &[MockProcess] {
304 &self.machine.processes
305 }
306
307 pub fn pane_launches(&self) -> &[MockPaneLaunch] {
310 &self.machine.pane_launches
311 }
312
313 pub(crate) fn create_pane(
319 &mut self,
320 cwd: &str,
321 command: Option<&str>,
322 env: &[(String, String)],
323 title: Option<&str>,
324 hidden: bool,
325 ) -> Result<(String, u64)> {
326 let project = self.pane_project(cwd, env, title)?;
327 let live = self
328 .machine
329 .pane_launches
330 .iter()
331 .filter(|pane| !pane.closed);
332 if live.count() >= super::owned::OWNED_PANES_PER_PLUGIN {
333 return Err(Error::Invalid(alloc::format!(
334 "a plugin holds at most {} panes of its own; close one first",
335 super::owned::OWNED_PANES_PER_PLUGIN
336 )));
337 }
338 let machine = self.machine_id.clone();
339 let id = alloc::format!("pane-{}", self.machine.pane_launches.len() + 1);
340 self.panes.push(crate::api::account::Pane {
341 id: id.clone(),
342 generation: 1,
343 machine: machine.unwrap_or_default(),
344 project: Some(project.clone()),
345 title: title.map_or_else(|| self.plugin_id.clone(), str::to_string),
346 cwd: cwd.to_string(),
347 cols: 80,
348 rows: 24,
349 ..Default::default()
350 });
351 self.machine.pane_launches.push(MockPaneLaunch {
352 id: id.clone(),
353 project,
354 cwd: cwd.to_string(),
355 command: command.map(str::to_string),
356 env: env.to_vec(),
357 title: title.map(str::to_string),
358 hidden,
359 input: Vec::new(),
360 screen: crate::daemon::panes::Screen {
361 generation: 1,
362 cols: 80,
363 rows: 24,
364 ..Default::default()
365 },
366 history: None,
367 history_queries: Vec::new(),
368 closed: false,
369 });
370 self.owned_changed(crate::daemon::PaneChangeKind::Created, &id);
371 Ok((id, 1))
372 }
373
374 pub(super) fn pane_project(
377 &self,
378 cwd: &str,
379 env: &[(String, String)],
380 title: Option<&str>,
381 ) -> Result<String> {
382 if title.is_some_and(|title| {
383 title.trim().is_empty()
384 || title.chars().count() > 128
385 || title.chars().any(char::is_control)
386 }) {
387 return Err(Error::Invalid(
388 "a pane title is 1 to 128 characters with no control characters".to_string(),
389 ));
390 }
391 if env.len() > 64
392 || env.iter().any(|(name, value)| {
393 name.is_empty() || name.contains(['=', '\0']) || value.contains('\0')
394 })
395 {
396 return Err(Error::Invalid(
397 "variables a pane cannot be given".to_string(),
398 ));
399 }
400 let path = Path::new(cwd);
401 if !path.is_absolute() {
402 return Err(Error::Invalid(alloc::format!(
403 "{cwd} is not an absolute path"
404 )));
405 }
406 let resolved = real(path);
407 let machine = self.machine_id.clone();
408 let project = self
409 .account
410 .projects
411 .iter()
412 .filter(|project| machine.as_ref().is_none_or(|id| &project.machine == id))
413 .filter(|project| resolved.starts_with(real(Path::new(&project.path))))
414 .max_by_key(|project| real(Path::new(&project.path)).components().count())
415 .ok_or_else(|| {
416 Error::Invalid(alloc::format!(
417 "{cwd} is not inside a project root on this machine"
418 ))
419 })?
420 .id
421 .clone();
422 Ok(project)
423 }
424
425 pub fn watches(&self) -> &[MockWatch] {
426 &self.machine.watches
427 }
428
429 pub(crate) fn spawn(&mut self, command: &Command) -> Result<u32> {
430 if command.program.is_empty() {
431 return Err(Error::Invalid("no program".into()));
432 }
433 if !self.grants.allows("machine.full") {
434 self.check(&alloc::format!("process.exec:{}", command.program))?;
435 }
436 let mut env: Vec<(String, String)> = if command.clear_env {
437 Vec::new()
438 } else {
439 self.environment
440 .iter()
441 .filter(|(name, _)| !command.env_remove.contains(name))
442 .cloned()
443 .collect()
444 };
445 for (name, value) in &command.env {
446 env.retain(|(key, _)| key != name);
447 env.push((name.clone(), value.clone()));
448 }
449 env.sort();
450 let cwd = command.cwd.clone().or_else(|| {
451 self.environment
452 .iter()
453 .find(|(name, _)| name == "HOME")
454 .map(|(_, home)| home.clone())
455 });
456 let pid = 1000 + self.machine.next_pid;
457 self.machine.next_pid += 1;
458 let script = self
459 .machine
460 .scripts
461 .iter()
462 .find(|(program, args, _)| {
463 *program == command.program
464 && args
465 .as_ref()
466 .is_none_or(|args| command.args.starts_with(args))
467 })
468 .map(|(_, _, script)| script.clone());
469 self.machine.processes.push(MockProcess {
470 pid,
471 program: command.program.clone(),
472 args: command.args.clone(),
473 env,
474 cwd,
475 stdin: Vec::new(),
476 stdin_closed: false,
477 status: None,
478 killed: false,
479 channel: false,
480 sent: Vec::new(),
481 stdout: command.stdout,
482 stderr: command.stderr,
483 });
484 if let Some(script) = script {
485 self.output(pid, false, &script.stdout);
486 self.output(pid, true, &script.stderr);
487 self.exited(pid, script.status);
488 }
489 Ok(pid)
490 }
491
492 fn process(&mut self, pid: u32) -> Result<&mut MockProcess> {
493 self.machine
494 .processes
495 .iter_mut()
496 .find(|process| process.pid == pid)
497 .ok_or_else(|| Error::Invalid(alloc::format!("no child {pid} of this plugin")))
498 }
499
500 pub(crate) fn output(&mut self, pid: u32, stderr: bool, bytes: &[u8]) {
502 let Ok(process) = self.process(pid) else {
503 return;
504 };
505 let piped = if stderr {
506 process.stderr == Stdio::Piped
507 } else {
508 process.stdout == Stdio::Piped
509 };
510 if piped && !bytes.is_empty() {
511 self.machine.pending.push_back(Event::ProcessOutput {
512 pid,
513 stderr,
514 bytes: bytes.to_vec(),
515 });
516 }
517 }
518
519 pub(crate) fn exited(&mut self, pid: u32, status: i32) {
521 let Ok(process) = self.process(pid) else {
522 return;
523 };
524 if process.status.is_some() {
525 return;
526 }
527 process.status = Some(status);
528 self.machine
529 .pending
530 .push_back(Event::ProcessExited { pid, status });
531 }
532
533 pub(crate) fn wait(&mut self, pid: u32) -> Result<i32> {
534 let process = self.process(pid)?;
535 process.status.ok_or_else(|| {
536 Error::Unavailable(alloc::format!(
537 "child {pid} ({}) has no script and would block forever: script it \
538 (MockHost::script) or end it (DaemonHarness::exit) first",
539 process.program
540 ))
541 })
542 }
543
544 pub(crate) fn wait_timeout(&mut self, pid: u32) -> Result<Option<i32>> {
547 Ok(self.process(pid)?.status)
548 }
549
550 pub(crate) fn try_wait(&mut self, pid: u32) -> Result<Option<i32>> {
551 Ok(self.process(pid)?.status)
552 }
553
554 pub(crate) fn write(&mut self, pid: u32, bytes: &[u8]) -> Result<()> {
555 let process = self.process(pid)?;
556 if process.stdin_closed {
557 return Err(Error::Invalid(alloc::format!(
558 "child {pid}'s stdin is closed"
559 )));
560 }
561 process.stdin.extend_from_slice(bytes);
562 Ok(())
563 }
564
565 pub(crate) fn spawn_with_channel(&mut self, command: &Command) -> Result<u32> {
567 let pid = self.spawn(command)?;
568 self.process(pid)?.channel = true;
569 Ok(pid)
570 }
571
572 pub(crate) fn send(&mut self, pid: u32, message: &str) -> Result<()> {
573 let process = self.process(pid)?;
574 if !process.channel {
575 return Err(Error::Invalid(alloc::format!("child {pid} has no channel")));
576 }
577 process.sent.push(message.to_string());
578 Ok(())
579 }
580
581 pub fn channel_message(&mut self, pid: u32, message: &str) {
584 let message = serde_json::from_str::<serde_json::Value>(message)
585 .unwrap_or_else(|_| serde_json::Value::String(message.to_string()));
586 self.machine.pending.push_back(Event::Plugin {
587 name: String::from(crate::daemon::process::CHANNEL_EVENT),
588 payload: crate::Json(serde_json::json!({ "pid": pid, "message": message }).to_string()),
589 });
590 }
591
592 pub(crate) fn close_stdin(&mut self, pid: u32) -> Result<()> {
593 self.process(pid)?.stdin_closed = true;
594 Ok(())
595 }
596
597 pub(crate) fn kill(&mut self, pid: u32) -> Result<()> {
598 let process = self.process(pid)?;
599 if process.status.is_none() {
600 process.killed = true;
601 self.exited(pid, -9);
602 }
603 Ok(())
604 }
605
606 pub(crate) fn watch(&mut self, path: &str, recursive: bool, exclude: &[String]) -> Result<u32> {
610 let named = Path::new(path);
611 if !named.is_absolute() {
612 return Err(Error::Invalid(alloc::format!(
613 "{path} is not an absolute path"
614 )));
615 }
616 if !PathGrants::from_grants(&self.grants).allows(&real(named), false) {
617 return Err(self.deny(standard_plugin_manifest::GrantDenied {
618 grant: alloc::format!("fs.read:{path}"),
619 }));
620 }
621 Excludes::new(exclude).map_err(|error| Error::Invalid(error.to_string()))?;
622 if self.machine.watches.len() >= MAX_WATCHES {
623 return Err(Error::RateLimited);
624 }
625 self.machine.next_watch += 1;
626 let handle = self.machine.next_watch;
627 self.machine.watches.push(MockWatch {
628 handle,
629 path: path.to_string(),
630 recursive,
631 exclude: exclude.to_vec(),
632 });
633 Ok(handle)
634 }
635
636 pub(crate) fn unwatch(&mut self, handle: u32) -> Result<()> {
637 let before = self.machine.watches.len();
638 self.machine.watches.retain(|watch| watch.handle != handle);
639 if self.machine.watches.len() == before {
640 return Err(Error::Invalid(alloc::format!("no watch {handle}")));
641 }
642 Ok(())
643 }
644
645 pub(crate) fn changed(&mut self, path: &str) -> usize {
649 let path = Path::new(path);
650 let mut heard = 0;
651 for watch in &self.machine.watches {
652 let Ok(rest) = path.strip_prefix(&watch.path) else {
653 continue;
654 };
655 if !watch.recursive && rest.components().count() > 1 {
656 continue;
657 }
658 let excluded = Excludes::new(&watch.exclude).is_ok_and(|globs| globs.excludes(rest));
659 if excluded {
660 continue;
661 }
662 heard += 1;
663 self.machine.pending.push_back(Event::FileChanged {
664 watch: watch.handle,
665 paths: alloc::vec![path.to_string_lossy().into_owned()],
666 });
667 }
668 heard
669 }
670}