Skip to content

Commit 394d49d

Browse files
authored
feat(process-daemon): run commands without a PTY on Unix (#60697)
1 parent 805a42f commit 394d49d

15 files changed

Lines changed: 1382 additions & 127 deletions

File tree

‎packages/process-daemon/SPEC.md‎

Lines changed: 39 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -107,6 +107,44 @@ when it changes; an OSC change hidden behind a user title publishes nothing.
107107

108108
`list` returns terminals in creation order.
109109

110+
## Pipe Processes
111+
112+
`Create` takes `mode: "pty" | "pipe"` (default `"pty"`). A pipe process runs
113+
any command without a terminal; it is Unix-only for now, and only daemons that
114+
list the `pipe` feature accept it. Older daemons ignore `mode` and would start
115+
a PTY instead, so clients check `features` first.
116+
117+
- `title`, `cols` and `rows` are optional for pipe processes; the title
118+
defaults to the program's file name and the size is reported as `0x0`.
119+
- The child gets its own process group, an empty signal mask with default
120+
actions (the daemon blocks SIGTERM and SIGINT, and std keeps the mask across
121+
exec), stdin on `/dev/null`, and one pipe for
122+
both stdout and stderr, so their bytes stay in order. No `TERM` or
123+
`COLORTERM` is added, and nothing parses the output: there is no emulator,
124+
no terminal replies, no OSC title and no foreground process.
125+
- Output goes through the same raw replay and subscriptions as a PTY, with the
126+
same absolute offsets. A pipe has no controller or observer distinction for
127+
writing, since it accepts no input.
128+
- `write`, `resize`, `control`, `input`, `snapshot`, `read_rows` and `rename`
129+
fail for pipe processes. `replay`, `subscribe` and `terminate`
130+
work.
131+
- Exit is published once both the exit status and the end of output are
132+
known. A descendant that keeps the pipe open (`cmd &`) delays that by at
133+
most one second after the child exits; output after that is not read.
134+
- `Exited` (the lifecycle and the subscription response) carries `signal`,
135+
the signal's name such as `"SIGTERM"`, when a pipe process was killed by
136+
one; `exit_code` is then null. The field is left out when there is no
137+
signal, so PTY exits serialize as before.
138+
- An exited pipe process stays listed, as a zombie, until `terminate`. The
139+
zombie keeps its PID and process group ID reserved, so `terminate` can kill
140+
any descendants left in the group without reaching an unrelated process.
141+
`terminate` sends SIGKILL to the group and to the child, reaps it, and never
142+
waits on a descendant that left the group and still holds the pipe.
143+
144+
`List` takes `mode` too. Without it, `list` returns PTYs only, so servers that
145+
predate pipe processes never see them. Clients leave `mode` out of the request
146+
when it is unset: older daemons reject a `list` with any extra field.
147+
110148
## Failure Boundary
111149

112150
Losing the owning server connection stops `opencode-pty` and its terminals.
@@ -131,7 +169,7 @@ subscriptions, title updates, rename, controller takeover, terminate, and destru
131169
shutdown, ownership acquisition, and restart handoff preparation.
132170

133171
`Pong` and the registration carry `features`, the daemon's additive
134-
capabilities (currently `["rename"]`). Additive changes, such as a new request
172+
capabilities (currently `["rename", "pipe"]` on Unix and `["rename"]` on Windows). Additive changes, such as a new request
135173
or field older clients can ignore, extend `features` and keep the protocol
136174
version; clients check `features` before sending a new request, since a daemon
137175
that cannot parse one drops the connection. Only breaking changes bump

‎packages/process-daemon/src/client.rs‎

Lines changed: 12 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -13,7 +13,7 @@ use crate::protocol::{
1313
AttachmentRole, Envelope, SubscriptionEvent, read_frame, read_subscription_event, write_frame,
1414
};
1515
use crate::protocol::{PROTOCOL_VERSION, Request, Response};
16-
use crate::service::{CreateTerminal, TerminalId, TerminalInfo, TerminalRows};
16+
use crate::service::{CreateTerminal, ProcessMode, TerminalId, TerminalInfo, TerminalRows};
1717
#[cfg(unix)]
1818
use crate::transport::Connection;
1919

@@ -165,14 +165,15 @@ impl TerminalClient {
165165
env: request.env,
166166
cols: request.cols,
167167
rows: request.rows,
168+
mode: request.mode,
168169
})? {
169170
Response::Created { terminal } => Ok(terminal),
170171
response => unexpected(response),
171172
}
172173
}
173174

174175
pub fn list(&self) -> Result<Vec<TerminalInfo>> {
175-
match self.request(Request::List)? {
176+
match self.request(Request::List { mode: None })? {
176177
Response::Terminals { terminals } => Ok(terminals),
177178
response => unexpected(response),
178179
}
@@ -524,8 +525,13 @@ fn watch(directory: &Path, id: TerminalId) -> Result<()> {
524525
io::stdout().flush()?;
525526
}
526527
SubscriptionEvent::Response(response) => match *response {
527-
Response::Exited { exit_code, .. } => {
528-
eprintln!("\nterminal exited: {exit_code:?}");
528+
Response::Exited {
529+
exit_code, signal, ..
530+
} => {
531+
match signal {
532+
Some(signal) => eprintln!("\nterminal killed by {signal}"),
533+
None => eprintln!("\nterminal exited: {exit_code:?}"),
534+
}
529535
return Ok(());
530536
}
531537
Response::Resized { cols, rows, .. } => {
@@ -588,6 +594,7 @@ fn play(directory: &Path) -> Result<()> {
588594
cwd: env::current_dir()?,
589595
cols: 100,
590596
rows: 30,
597+
mode: ProcessMode::Pty,
591598
}
592599
};
593600
let info = client.create(request)?;
@@ -665,6 +672,7 @@ fn play(directory: &Path) -> Result<()> {
665672
cwd: env::current_dir()?,
666673
cols: 100,
667674
rows: 30,
675+
mode: ProcessMode::Pty,
668676
})?;
669677
active = Some(info.id);
670678
thread::sleep(Duration::from_millis(200));

‎packages/process-daemon/src/daemon/server.rs‎

Lines changed: 6 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -503,9 +503,11 @@ fn stream_subscription(
503503
},
504504
StreamEvent::Exited {
505505
exit_code,
506+
signal,
506507
final_offset,
507508
} => Response::Exited {
508509
exit_code,
510+
signal,
509511
final_offset,
510512
},
511513
StreamEvent::ControllerChanged {
@@ -556,6 +558,7 @@ fn dispatch(
556558
env,
557559
cols,
558560
rows,
561+
mode,
559562
} => Response::Created {
560563
terminal: service.create(CreateTerminal {
561564
program,
@@ -566,10 +569,11 @@ fn dispatch(
566569
env,
567570
cols,
568571
rows,
572+
mode,
569573
})?,
570574
},
571-
Request::List => Response::Terminals {
572-
terminals: service.list()?,
575+
Request::List { mode } => Response::Terminals {
576+
terminals: service.list_mode(mode.unwrap_or_default())?,
573577
},
574578
Request::Write {
575579
id,

‎packages/process-daemon/src/protocol.rs‎

Lines changed: 101 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -4,10 +4,14 @@ use std::path::PathBuf;
44
use anyhow::{Context, Result, bail};
55
use serde::{Deserialize, Serialize};
66

7-
use crate::service::{TerminalId, TerminalInfo};
7+
use crate::service::{ProcessMode, TerminalId, TerminalInfo};
88

99
pub const PROTOCOL_VERSION: u32 = 7;
1010
/// Additive capabilities of this daemon. Breaking changes bump `PROTOCOL_VERSION`.
11+
/// `pipe` (non-PTY processes) is Unix-only for now.
12+
#[cfg(unix)]
13+
pub const FEATURES: &[&str] = &["rename", "pipe"];
14+
#[cfg(not(unix))]
1115
pub const FEATURES: &[&str] = &["rename"];
1216

1317
pub fn features() -> Vec<String> {
@@ -38,17 +42,31 @@ pub enum Request {
3842
ticket: Option<String>,
3943
},
4044
PrepareHandoff,
45+
/// Old daemons ignore `mode` and would start a PTY, so clients send
46+
/// `"pipe"` only to a daemon that lists the `pipe` feature.
4147
Create {
4248
program: String,
4349
args: Vec<String>,
4450
cwd: PathBuf,
51+
#[serde(default)]
4552
title: String,
4653
group_id: String,
4754
env: std::collections::HashMap<String, String>,
55+
/// Terminal size; required for `pty`, ignored for `pipe`.
56+
#[serde(default)]
4857
cols: u16,
58+
#[serde(default)]
4959
rows: u16,
60+
#[serde(default, skip_serializing_if = "ProcessMode::is_pty")]
61+
mode: ProcessMode,
62+
},
63+
/// Without `mode`, lists PTYs only, so older servers never see pipe processes.
64+
/// `mode` is left out of the JSON when unset: older daemons reject a `list`
65+
/// with any extra key.
66+
List {
67+
#[serde(default, skip_serializing_if = "Option::is_none")]
68+
mode: Option<ProcessMode>,
5069
},
51-
List,
5270
Write {
5371
id: TerminalId,
5472
attachment_id: Option<String>,
@@ -161,6 +179,9 @@ pub enum Response {
161179
},
162180
Exited {
163181
exit_code: Option<u32>,
182+
/// Signal name such as `SIGTERM` when a pipe process was killed by one.
183+
#[serde(default, skip_serializing_if = "Option::is_none")]
184+
signal: Option<String>,
164185
final_offset: u64,
165186
},
166187
ControllerChanged {
@@ -335,4 +356,82 @@ mod tests {
335356
serde_json::Value::Null
336357
);
337358
}
359+
360+
#[test]
361+
fn pipe_fields_keep_the_wire_compatible_with_older_peers() {
362+
use crate::service::{ProcessMode, TerminalLifecycle};
363+
364+
// An older daemon rejects `list` with any extra key, and an older
365+
// client sends a bare `list` and a `create` with no mode.
366+
assert_eq!(
367+
serde_json::to_value(Request::List { mode: None }).unwrap(),
368+
serde_json::json!({"op": "list"})
369+
);
370+
assert!(matches!(
371+
serde_json::from_str::<Request>(r#"{"op":"list"}"#).unwrap(),
372+
Request::List { mode: None }
373+
));
374+
assert!(matches!(
375+
serde_json::from_str::<Request>(r#"{"op":"list","mode":"pipe"}"#).unwrap(),
376+
Request::List {
377+
mode: Some(ProcessMode::Pipe)
378+
}
379+
));
380+
let create = serde_json::json!({
381+
"op": "create", "program": "sh", "args": [], "cwd": "/",
382+
"title": "t", "group_id": "g", "env": {}, "cols": 80, "rows": 24,
383+
});
384+
assert!(matches!(
385+
serde_json::from_value::<Request>(create.clone()).unwrap(),
386+
Request::Create {
387+
mode: ProcessMode::Pty,
388+
cols: 80,
389+
..
390+
}
391+
));
392+
// A PTY create serializes exactly as before.
393+
assert_eq!(
394+
serde_json::to_value(serde_json::from_value::<Request>(create.clone()).unwrap())
395+
.unwrap(),
396+
create
397+
);
398+
assert!(matches!(
399+
serde_json::from_str::<Request>(
400+
r#"{"op":"create","program":"sh","args":[],"cwd":"/","group_id":"g","env":{},"mode":"pipe"}"#
401+
)
402+
.unwrap(),
403+
Request::Create {
404+
mode: ProcessMode::Pipe,
405+
cols: 0,
406+
rows: 0,
407+
..
408+
}
409+
));
410+
// Exits without a signal look exactly as before.
411+
assert_eq!(
412+
serde_json::to_value(Response::Exited {
413+
exit_code: Some(1),
414+
signal: None,
415+
final_offset: 2,
416+
})
417+
.unwrap(),
418+
serde_json::json!({"type": "exited", "exit_code": 1, "final_offset": 2})
419+
);
420+
assert_eq!(
421+
serde_json::to_value(TerminalLifecycle::Exited {
422+
exit_code: Some(1),
423+
signal: None,
424+
})
425+
.unwrap(),
426+
serde_json::json!({"status": "exited", "exit_code": 1})
427+
);
428+
assert_eq!(
429+
serde_json::from_str::<TerminalLifecycle>(r#"{"status":"exited","exit_code":null}"#)
430+
.unwrap(),
431+
TerminalLifecycle::Exited {
432+
exit_code: None,
433+
signal: None,
434+
}
435+
);
436+
}
338437
}

0 commit comments

Comments
 (0)