mirror of
https://github.com/anomalyco/opencode.git
synced 2026-11-19 17:01:37 +03:00
feat(process-daemon): rename terminals (#60324)
This commit is contained in:
committed by
GitHub
Unverified
parent
17f4634afe
commit
6b1131202d
@@ -71,7 +71,7 @@ ownership deadline is due, or a two-second safety net elapses. Windows still
|
||||
polls every 25 ms.
|
||||
|
||||
The Windows named-pipe backend keeps protocol 7 and the registration fields
|
||||
`instance_id`, `pid`, `protocol`, `socket`, and `token`. Treat `socket` as an opaque
|
||||
`instance_id`, `pid`, `protocol`, `socket`, `token`, and `features`. Treat `socket` as an opaque
|
||||
local endpoint: on Windows it is `\\.\pipe\opencode-pty-<instance_id>`, not a
|
||||
filesystem socket. A random per-instance name, exclusive first pipe instance,
|
||||
current-user access control, and rejection of remote clients protect the endpoint;
|
||||
|
||||
@@ -27,6 +27,7 @@ replay, and explicit lifecycle state.
|
||||
- Promotion, canonical resize, and input are one ordered actor command.
|
||||
- Subscription replay and live events cross one ordered actor boundary.
|
||||
- OSC 0/2 title changes update authoritative terminal metadata and publish ordered subscription events.
|
||||
- A user title set by rename takes precedence over OSC titles; title changes publish only when the effective title changes.
|
||||
- The deepest TTY-attached process in the foreground process group updates authoritative process metadata.
|
||||
- Controller delivery applies backpressure; observers tolerate bounded output bursts and are disconnected when their backlog remains full.
|
||||
- Adjacent output is coalesced before fanout, flushing at 8 KiB, after 1 ms, or before the next non-output event.
|
||||
@@ -57,7 +58,7 @@ A snapshot is built on the actor thread and contains owned values only:
|
||||
- Plain parsed screen text
|
||||
- VT checkpoint synthesized by libghostty formatter
|
||||
- Raw replay head and tail offsets
|
||||
- Current title derived from libghostty state
|
||||
- Current effective title and user title
|
||||
- Current foreground process derived from PTY process state
|
||||
|
||||
No borrowed libghostty object crosses a thread boundary.
|
||||
@@ -88,6 +89,24 @@ bounded. Results exceeding that budget fail rather than truncate. Complete
|
||||
responses remain subject to the transport's 8 MiB frame limit. Protocol 7
|
||||
supports `read_rows` alongside the existing snapshot and replay operations.
|
||||
|
||||
## Titles
|
||||
|
||||
`TerminalInfo.title` is the effective title: the user title, else the latest
|
||||
OSC 0/2 title, else the title given at creation. An empty OSC title (a program
|
||||
resetting it) or an empty user title counts as unset. `TerminalInfo.user_title`
|
||||
is always serialized, as `null` when unset.
|
||||
|
||||
`Request::Rename { id, title: Option<String> }` (`op: "rename"`) sets the user
|
||||
title, or clears it when `title` is null or empty, and returns `Response::Ok`.
|
||||
The terminal actor handles it as one command, so it is ordered with output.
|
||||
OSC titles keep being tracked while a user title is set and show through again
|
||||
once it is cleared.
|
||||
|
||||
Rename and OSC updates publish `TitleChanged` with the effective title only
|
||||
when it changes; an OSC change hidden behind a user title publishes nothing.
|
||||
|
||||
`list` returns terminals in creation order.
|
||||
|
||||
## Failure Boundary
|
||||
|
||||
Losing the owning server connection stops `opencode-pty` and its terminals.
|
||||
@@ -108,11 +127,19 @@ only observe or operate an existing daemon and never start one.
|
||||
Protocol v7 uses four-byte big-endian framing with bounded UTF-8 JSON control
|
||||
frames and tagged raw binary output frames. It supports ping, create, list,
|
||||
write, resize, atomic interaction promotion, snapshot, read_rows, replay, replay-to-live
|
||||
subscriptions, title updates, controller takeover, terminate, and destructive service
|
||||
subscriptions, title updates, rename, controller takeover, terminate, and destructive service
|
||||
shutdown, ownership acquisition, and restart handoff preparation.
|
||||
|
||||
`Pong` and the registration carry `features`, the daemon's additive
|
||||
capabilities (currently `["rename"]`). Additive changes, such as a new request
|
||||
or field older clients can ignore, extend `features` and keep the protocol
|
||||
version; clients check `features` before sending a new request, since a daemon
|
||||
that cannot parse one drops the connection. Only breaking changes bump
|
||||
`PROTOCOL_VERSION`, which clients reject on mismatch. A missing `features`
|
||||
means none.
|
||||
|
||||
Registration is written atomically with private permissions and contains an
|
||||
instance ID, PID, protocol version, socket path, and random credential. A
|
||||
instance ID, PID, protocol version, features, socket path, and random credential. A
|
||||
service lock elects one process and protects stale socket cleanup. On Unix, the
|
||||
socket uses a fixed-length hash of the canonical runtime path
|
||||
under a private per-user `/tmp` directory to stay below platform path limits.
|
||||
|
||||
@@ -144,6 +144,7 @@ impl TerminalClient {
|
||||
instance_id,
|
||||
pid,
|
||||
protocol,
|
||||
..
|
||||
} if instance_id == client.registration.instance_id
|
||||
&& pid == client.registration.pid
|
||||
&& protocol == PROTOCOL_VERSION =>
|
||||
|
||||
@@ -14,6 +14,8 @@ pub struct Registration {
|
||||
/// Opaque local transport endpoint, not necessarily a filesystem entry.
|
||||
pub socket: PathBuf,
|
||||
pub token: String,
|
||||
#[serde(default)]
|
||||
pub features: Vec<String>,
|
||||
}
|
||||
|
||||
/// Shared parent of runtime directories, inside OpenCode's state directory.
|
||||
|
||||
@@ -447,6 +447,7 @@ fn dispatch(
|
||||
instance_id: registration.instance_id.clone(),
|
||||
pid: registration.pid,
|
||||
protocol: registration.protocol,
|
||||
features: registration.features.clone(),
|
||||
},
|
||||
Request::Create {
|
||||
program,
|
||||
@@ -534,6 +535,10 @@ fn dispatch(
|
||||
cursor_y: rows.cursor_y,
|
||||
}
|
||||
}
|
||||
Request::Rename { id, title } => {
|
||||
service.rename(id, title)?;
|
||||
Response::Ok
|
||||
}
|
||||
Request::Replay { id, offset } => {
|
||||
let replay = service.replay(id, offset)?;
|
||||
Response::Replay {
|
||||
|
||||
@@ -106,7 +106,7 @@ mod tests {
|
||||
use std::path::PathBuf;
|
||||
|
||||
use super::*;
|
||||
use crate::protocol::PROTOCOL_VERSION;
|
||||
use crate::protocol::{PROTOCOL_VERSION, features};
|
||||
|
||||
fn random_id() -> String {
|
||||
format!("{:032x}", rand::random::<u128>())
|
||||
@@ -135,6 +135,7 @@ mod tests {
|
||||
protocol: PROTOCOL_VERSION,
|
||||
socket: PathBuf::from("/nonexistent.sock"),
|
||||
token: random_id(),
|
||||
features: features(),
|
||||
};
|
||||
fs::write(
|
||||
directory.join(REGISTRATION_FILE),
|
||||
|
||||
@@ -10,7 +10,7 @@ use fs2::FileExt;
|
||||
use sha2::{Digest, Sha256};
|
||||
|
||||
use super::{LOCK_FILE, Registration, read_registration, registration_path};
|
||||
use crate::protocol::PROTOCOL_VERSION;
|
||||
use crate::protocol::{PROTOCOL_VERSION, features};
|
||||
use crate::transport::Listener;
|
||||
|
||||
pub(super) struct Runtime {
|
||||
@@ -48,6 +48,7 @@ impl Runtime {
|
||||
protocol: PROTOCOL_VERSION,
|
||||
socket: socket.path.clone(),
|
||||
token: random_id(),
|
||||
features: features(),
|
||||
};
|
||||
write_registration(&directory, ®istration)?;
|
||||
let sweeper = {
|
||||
@@ -364,6 +365,7 @@ mod tests {
|
||||
protocol: PROTOCOL_VERSION,
|
||||
socket: socket.clone(),
|
||||
token: random_id(),
|
||||
features: features(),
|
||||
};
|
||||
write_registration(&abandoned, ®istration).unwrap();
|
||||
|
||||
|
||||
@@ -28,7 +28,7 @@ use windows_sys::Win32::System::WindowsProgramming::{
|
||||
};
|
||||
|
||||
use super::{LOCK_FILE, REGISTRATION_FILE, Registration, registration_path, sweep};
|
||||
use crate::protocol::PROTOCOL_VERSION;
|
||||
use crate::protocol::{PROTOCOL_VERSION, features};
|
||||
use crate::transport::Listener;
|
||||
use crate::transport::windows::{owned_handle, security::PrivateSecurity};
|
||||
|
||||
@@ -112,6 +112,7 @@ impl Runtime {
|
||||
pid: std::process::id(),
|
||||
protocol: PROTOCOL_VERSION,
|
||||
token: format!("{:032x}", rand::random::<u128>()),
|
||||
features: features(),
|
||||
};
|
||||
let listener = Listener::bind(®istration.socket)?;
|
||||
write_registration(&directory, &directory_handle, ®istration, &security)?;
|
||||
@@ -364,6 +365,7 @@ mod tests {
|
||||
protocol: PROTOCOL_VERSION,
|
||||
socket: PathBuf::from(r"\\.\pipe\opencode-pty-first"),
|
||||
token: "secret".into(),
|
||||
features: features(),
|
||||
};
|
||||
write_registration(&directory, &directory_handle, ®istration, &security).unwrap();
|
||||
let path = directory.join(REGISTRATION_FILE);
|
||||
|
||||
@@ -7,6 +7,12 @@ use serde::{Deserialize, Serialize};
|
||||
use crate::service::{TerminalId, TerminalInfo};
|
||||
|
||||
pub const PROTOCOL_VERSION: u32 = 7;
|
||||
/// Additive capabilities of this daemon. Breaking changes bump `PROTOCOL_VERSION`.
|
||||
pub const FEATURES: &[&str] = &["rename"];
|
||||
|
||||
pub fn features() -> Vec<String> {
|
||||
FEATURES.iter().map(|feature| feature.to_string()).collect()
|
||||
}
|
||||
pub const MAX_FRAME_BYTES: usize = 8 * 1024 * 1024;
|
||||
const OUTPUT_FRAME_TAG: u8 = 0;
|
||||
|
||||
@@ -74,6 +80,10 @@ pub enum Request {
|
||||
id: TerminalId,
|
||||
rows: Option<u16>,
|
||||
},
|
||||
Rename {
|
||||
id: TerminalId,
|
||||
title: Option<String>,
|
||||
},
|
||||
Replay {
|
||||
id: TerminalId,
|
||||
offset: u64,
|
||||
@@ -103,6 +113,8 @@ pub enum Response {
|
||||
instance_id: String,
|
||||
pid: u32,
|
||||
protocol: u32,
|
||||
#[serde(default)]
|
||||
features: Vec<String>,
|
||||
},
|
||||
Created {
|
||||
terminal: TerminalInfo,
|
||||
@@ -284,4 +296,43 @@ mod tests {
|
||||
}
|
||||
assert_eq!(PROTOCOL_VERSION, 7);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn additive_fields_default_when_absent() {
|
||||
assert!(matches!(
|
||||
serde_json::from_str::<Response>(
|
||||
r#"{"type":"pong","instance_id":"a","pid":1,"protocol":7}"#
|
||||
)
|
||||
.unwrap(),
|
||||
Response::Pong { features, .. } if features.is_empty()
|
||||
));
|
||||
assert!(matches!(
|
||||
serde_json::from_str::<Request>(r#"{"op":"rename","id":1,"title":null}"#).unwrap(),
|
||||
Request::Rename { id: 1, title: None }
|
||||
));
|
||||
assert!(matches!(
|
||||
serde_json::from_str::<Request>(r#"{"op":"rename","id":1}"#).unwrap(),
|
||||
Request::Rename { id: 1, title: None }
|
||||
));
|
||||
let terminal = serde_json::json!({
|
||||
"id": 1,
|
||||
"pid": null,
|
||||
"title": "shell",
|
||||
"foreground_process": null,
|
||||
"group_id": "group",
|
||||
"command": [],
|
||||
"cwd": "/",
|
||||
"cols": 80,
|
||||
"rows": 24,
|
||||
"lifecycle": {"status": "running"},
|
||||
"output_head": 0,
|
||||
"output_tail": 0,
|
||||
});
|
||||
let info = serde_json::from_value::<TerminalInfo>(terminal).unwrap();
|
||||
assert_eq!(info.user_title, None);
|
||||
assert_eq!(
|
||||
serde_json::to_value(&info).unwrap()["user_title"],
|
||||
serde_json::Value::Null
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -4,6 +4,7 @@ use std::collections::{HashMap, VecDeque};
|
||||
use std::env;
|
||||
use std::io::{self, Read, Write};
|
||||
use std::path::PathBuf;
|
||||
use std::sync::atomic::{AtomicU64, Ordering};
|
||||
use std::sync::{Arc, Mutex, RwLock, mpsc as std_mpsc};
|
||||
use std::thread::{self, JoinHandle};
|
||||
use std::time::{Duration, Instant};
|
||||
@@ -44,7 +45,11 @@ pub enum TerminalLifecycle {
|
||||
pub struct TerminalInfo {
|
||||
pub id: TerminalId,
|
||||
pub pid: Option<u32>,
|
||||
/// Effective title: the user title, else the latest non-empty OSC title,
|
||||
/// else the title given at creation.
|
||||
pub title: String,
|
||||
#[serde(default)]
|
||||
pub user_title: Option<String>,
|
||||
pub foreground_process: Option<String>,
|
||||
pub group_id: String,
|
||||
pub command: Vec<String>,
|
||||
@@ -169,6 +174,7 @@ impl CreateTerminal {
|
||||
|
||||
pub struct TerminalService {
|
||||
terminals: Mutex<HashMap<TerminalId, Arc<TerminalHandle>>>,
|
||||
created: AtomicU64,
|
||||
replay_capacity: usize,
|
||||
}
|
||||
|
||||
@@ -182,6 +188,7 @@ impl TerminalService {
|
||||
pub fn new(replay_capacity: usize) -> Self {
|
||||
Self {
|
||||
terminals: Mutex::new(HashMap::new()),
|
||||
created: AtomicU64::new(0),
|
||||
replay_capacity,
|
||||
}
|
||||
}
|
||||
@@ -205,7 +212,8 @@ impl TerminalService {
|
||||
break id;
|
||||
}
|
||||
};
|
||||
let handle = TerminalHandle::spawn(id, request, self.replay_capacity)?;
|
||||
let order = self.created.fetch_add(1, Ordering::Relaxed);
|
||||
let handle = TerminalHandle::spawn(id, order, request, self.replay_capacity)?;
|
||||
let info = handle.info();
|
||||
self.terminals
|
||||
.lock()
|
||||
@@ -215,13 +223,14 @@ impl TerminalService {
|
||||
}
|
||||
|
||||
pub fn list(&self) -> Result<Vec<TerminalInfo>> {
|
||||
let handles = self
|
||||
let mut handles = self
|
||||
.terminals
|
||||
.lock()
|
||||
.map_err(|_| anyhow!("terminal registry lock poisoned"))?
|
||||
.values()
|
||||
.cloned()
|
||||
.collect::<Vec<_>>();
|
||||
handles.sort_by_key(|terminal| terminal.order);
|
||||
let mut terminals = Vec::with_capacity(handles.len());
|
||||
for terminal in handles {
|
||||
// Windows has no foreground query; do not wait behind actor
|
||||
@@ -230,7 +239,6 @@ impl TerminalService {
|
||||
terminal.request(|reply| ActorMessage::RefreshForegroundProcess { reply })?;
|
||||
terminals.push(terminal.info());
|
||||
}
|
||||
terminals.sort_by_key(|terminal| terminal.id);
|
||||
Ok(terminals)
|
||||
}
|
||||
|
||||
@@ -322,6 +330,13 @@ impl TerminalService {
|
||||
.request(|reply| ActorMessage::ReadRows { rows, reply })
|
||||
}
|
||||
|
||||
/// Sets or clears (`None` or empty) the user title, which takes precedence
|
||||
/// over titles set by the terminal's programs.
|
||||
pub fn rename(&self, id: TerminalId, title: Option<String>) -> Result<()> {
|
||||
self.get(id)?
|
||||
.request(|reply| ActorMessage::Rename { title, reply })
|
||||
}
|
||||
|
||||
pub fn replay(&self, id: TerminalId, offset: u64) -> Result<RawReplay> {
|
||||
self.get(id)?
|
||||
.request(|reply| ActorMessage::Replay { offset, reply })
|
||||
@@ -409,6 +424,8 @@ impl Drop for TerminalService {
|
||||
}
|
||||
|
||||
struct TerminalHandle {
|
||||
/// Creation sequence number; orders `list` results.
|
||||
order: u64,
|
||||
actor_tx: Sender<ActorMessage>,
|
||||
/// Disconnects when the actor thread exits; never carries a message.
|
||||
actor_done: Receiver<()>,
|
||||
@@ -419,7 +436,12 @@ struct TerminalHandle {
|
||||
}
|
||||
|
||||
impl TerminalHandle {
|
||||
fn spawn(id: TerminalId, request: CreateTerminal, replay_capacity: usize) -> Result<Self> {
|
||||
fn spawn(
|
||||
id: TerminalId,
|
||||
order: u64,
|
||||
request: CreateTerminal,
|
||||
replay_capacity: usize,
|
||||
) -> Result<Self> {
|
||||
let pty_system = native_pty_system();
|
||||
let pair = pty_system
|
||||
.openpty(PtySize {
|
||||
@@ -459,6 +481,7 @@ impl TerminalHandle {
|
||||
id,
|
||||
pid,
|
||||
title: request.title,
|
||||
user_title: None,
|
||||
foreground_process: None,
|
||||
group_id: request.group_id,
|
||||
command: std::iter::once(request.program)
|
||||
@@ -589,6 +612,7 @@ impl TerminalHandle {
|
||||
.context("failed to spawn terminal child waiter")?;
|
||||
|
||||
Ok(Self {
|
||||
order,
|
||||
actor_tx,
|
||||
actor_done,
|
||||
shutdown_tx: Mutex::new(Some(shutdown_tx)),
|
||||
@@ -692,6 +716,10 @@ enum ActorMessage {
|
||||
rows: Option<u16>,
|
||||
reply: Reply<Result<TerminalRows>>,
|
||||
},
|
||||
Rename {
|
||||
title: Option<String>,
|
||||
reply: Reply<Result<()>>,
|
||||
},
|
||||
Replay {
|
||||
offset: u64,
|
||||
reply: Reply<Result<RawReplay>>,
|
||||
@@ -803,6 +831,12 @@ fn run_actor(config: ActorConfig) -> Result<()> {
|
||||
max_scrollback: replay_capacity,
|
||||
})?;
|
||||
|
||||
let create_title = info
|
||||
.read()
|
||||
.map_err(|_| anyhow!("terminal info lock poisoned"))?
|
||||
.title
|
||||
.clone();
|
||||
let mut osc_title = None::<String>;
|
||||
let mut replay = ReplayBuffer::new(replay_capacity);
|
||||
let mut subscribers = HashMap::<String, Subscriber>::new();
|
||||
let mut controller = None::<String>;
|
||||
@@ -853,17 +887,10 @@ fn run_actor(config: ActorConfig) -> Result<()> {
|
||||
StreamEvent::Output { start, end, bytes },
|
||||
);
|
||||
if let Some(title) = terminal.take_title() {
|
||||
let changed = if let Ok(mut value) = info.write() {
|
||||
if value.title == title {
|
||||
false
|
||||
} else {
|
||||
value.title = title.clone();
|
||||
true
|
||||
}
|
||||
} else {
|
||||
false
|
||||
};
|
||||
if changed {
|
||||
osc_title = Some(title).filter(|title| !title.is_empty());
|
||||
if let Ok(Some(title)) =
|
||||
refresh_title(&info, None, osc_title.as_deref(), &create_title)
|
||||
{
|
||||
broadcast(
|
||||
&shutdown,
|
||||
&mut subscribers,
|
||||
@@ -1020,6 +1047,26 @@ fn run_actor(config: ActorConfig) -> Result<()> {
|
||||
})();
|
||||
let _ = reply.send(result);
|
||||
}
|
||||
Ok(ActorMessage::Rename { title, reply }) => {
|
||||
let result = refresh_title(
|
||||
&info,
|
||||
Some(title.filter(|title| !title.is_empty())),
|
||||
osc_title.as_deref(),
|
||||
&create_title,
|
||||
);
|
||||
if let Ok(Some(title)) = &result {
|
||||
broadcast(
|
||||
&shutdown,
|
||||
&mut subscribers,
|
||||
&mut controller,
|
||||
&mut controller_generation,
|
||||
StreamEvent::TitleChanged {
|
||||
title: title.clone(),
|
||||
},
|
||||
);
|
||||
}
|
||||
let _ = reply.send(result.map(|_| ()));
|
||||
}
|
||||
Ok(ActorMessage::Replay { offset, reply }) => {
|
||||
let _ = reply.send(replay.read_from(offset));
|
||||
}
|
||||
@@ -1387,6 +1434,33 @@ fn run_writer(
|
||||
}
|
||||
}
|
||||
|
||||
/// Applies an optional user-title update and stores the effective title under
|
||||
/// one write guard, returning the title only when it changed.
|
||||
fn refresh_title(
|
||||
info: &Arc<RwLock<TerminalInfo>>,
|
||||
user_title: Option<Option<String>>,
|
||||
osc_title: Option<&str>,
|
||||
create_title: &str,
|
||||
) -> Result<Option<String>> {
|
||||
let mut value = info
|
||||
.write()
|
||||
.map_err(|_| anyhow!("terminal info lock poisoned"))?;
|
||||
if let Some(user_title) = user_title {
|
||||
value.user_title = user_title;
|
||||
}
|
||||
let title = value
|
||||
.user_title
|
||||
.as_deref()
|
||||
.or(osc_title)
|
||||
.unwrap_or(create_title)
|
||||
.to_string();
|
||||
if value.title == title {
|
||||
return Ok(None);
|
||||
}
|
||||
value.title = title.clone();
|
||||
Ok(Some(title))
|
||||
}
|
||||
|
||||
fn make_snapshot(
|
||||
terminal: &Terminal,
|
||||
info: &Arc<RwLock<TerminalInfo>>,
|
||||
@@ -1664,6 +1738,7 @@ mod tests {
|
||||
id: 1,
|
||||
pid: None,
|
||||
title: "test".into(),
|
||||
user_title: None,
|
||||
foreground_process: None,
|
||||
group_id: "test".into(),
|
||||
command: vec![],
|
||||
@@ -1716,6 +1791,7 @@ mod tests {
|
||||
init_rx.recv().unwrap().unwrap();
|
||||
(
|
||||
TerminalHandle {
|
||||
order: 0,
|
||||
actor_tx,
|
||||
actor_done,
|
||||
shutdown_tx: Mutex::new(Some(shutdown_tx)),
|
||||
@@ -1979,6 +2055,69 @@ mod tests {
|
||||
assert!(detached.is_err());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn user_title_overrides_osc_titles_until_cleared() {
|
||||
let (actor, _writer) = test_actor();
|
||||
let observer = actor
|
||||
.request(|reply| ActorMessage::Attach {
|
||||
offset: 0,
|
||||
attachment_id: "observer".into(),
|
||||
role: AttachmentRole::Observer,
|
||||
takeover: false,
|
||||
reply,
|
||||
})
|
||||
.unwrap();
|
||||
let rename = |title: Option<&str>| {
|
||||
actor
|
||||
.request(|reply| ActorMessage::Rename {
|
||||
title: title.map(String::from),
|
||||
reply,
|
||||
})
|
||||
.unwrap()
|
||||
};
|
||||
let osc = |title: &str| {
|
||||
actor
|
||||
.actor_tx
|
||||
.send(ActorMessage::Output(
|
||||
format!("\x1b]2;{title}\x07").into_bytes(),
|
||||
))
|
||||
.unwrap()
|
||||
};
|
||||
let info = || {
|
||||
actor
|
||||
.request(|reply| ActorMessage::Snapshot { reply })
|
||||
.unwrap()
|
||||
.info
|
||||
};
|
||||
|
||||
osc("shell");
|
||||
rename(Some("mine"));
|
||||
osc("prompt");
|
||||
let renamed = info();
|
||||
assert_eq!(renamed.title, "mine");
|
||||
assert_eq!(renamed.user_title.as_deref(), Some("mine"));
|
||||
rename(Some("mine"));
|
||||
rename(None);
|
||||
let cleared = info();
|
||||
assert_eq!(cleared.title, "prompt");
|
||||
assert_eq!(cleared.user_title, None);
|
||||
rename(Some(""));
|
||||
assert_eq!(info().user_title, None);
|
||||
osc("");
|
||||
assert_eq!(info().title, "test");
|
||||
actor.shutdown().unwrap();
|
||||
|
||||
let titles = observer
|
||||
.events
|
||||
.try_iter()
|
||||
.filter_map(|event| match event {
|
||||
StreamEvent::TitleChanged { title } => Some(title),
|
||||
_ => None,
|
||||
})
|
||||
.collect::<Vec<_>>();
|
||||
assert_eq!(titles, ["shell", "mine", "prompt", "test"]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn broadcast_removes_failed_observers_before_promoting() {
|
||||
let mut subscribers = HashMap::new();
|
||||
|
||||
@@ -308,6 +308,66 @@ fn shutdown_ends_an_idle_subscription() {
|
||||
assert_terminal_stopped(&terminal);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn rename_is_advertised_and_served() {
|
||||
use opencode_pty::protocol::{SubscriptionEvent, read_subscription_event};
|
||||
|
||||
let mut daemon = Daemon::start();
|
||||
assert_eq!(daemon.registration.features, ["rename"]);
|
||||
assert!(matches!(
|
||||
daemon.request(Request::Ping),
|
||||
Response::Pong { features, .. } if features == ["rename"]
|
||||
));
|
||||
let (owner, response) = daemon.own(None);
|
||||
assert!(matches!(response, Response::Owned));
|
||||
let terminal = daemon.terminal("exec cat");
|
||||
let mut subscription = daemon.connect();
|
||||
assert!(matches!(
|
||||
daemon.send(
|
||||
&mut subscription,
|
||||
Request::Subscribe {
|
||||
id: terminal.id,
|
||||
offset: 0,
|
||||
attachment_id: "rename-observer".into(),
|
||||
role: AttachmentRole::Observer,
|
||||
takeover: false,
|
||||
}
|
||||
),
|
||||
Response::Attached { .. }
|
||||
));
|
||||
assert!(matches!(
|
||||
daemon.request(Request::Rename {
|
||||
id: terminal.id,
|
||||
title: Some("renamed".into()),
|
||||
}),
|
||||
Response::Ok
|
||||
));
|
||||
loop {
|
||||
if let SubscriptionEvent::Response(response) =
|
||||
read_subscription_event(&mut subscription).unwrap()
|
||||
&& let Response::TitleChanged { title } = *response
|
||||
{
|
||||
assert_eq!(title, "renamed");
|
||||
break;
|
||||
}
|
||||
}
|
||||
assert!(
|
||||
matches!(daemon.request(Request::List), Response::Terminals { terminals }
|
||||
if terminals.len() == 1 && terminals[0].title == "renamed"
|
||||
&& terminals[0].user_title.as_deref() == Some("renamed"))
|
||||
);
|
||||
assert!(matches!(
|
||||
daemon.request(Request::Rename {
|
||||
id: terminal.id.wrapping_add(1),
|
||||
title: None,
|
||||
}),
|
||||
Response::Error { .. }
|
||||
));
|
||||
drop(subscription);
|
||||
drop(owner);
|
||||
daemon.wait();
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn handoff_preserves_daemon_and_terminal_and_shutdown_overrides_it() {
|
||||
let mut daemon = Daemon::start();
|
||||
|
||||
@@ -245,6 +245,84 @@ fn title_changes_update_metadata_and_notify_subscribers() {
|
||||
service.terminate(terminal.id).expect("terminal removed");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn rename_updates_metadata_and_notifies_subscribers_once() {
|
||||
let service = TerminalService::new(64 * 1024);
|
||||
let terminal = service
|
||||
.create(command("exec cat"))
|
||||
.expect("terminal created");
|
||||
let observer = service
|
||||
.attach(
|
||||
terminal.id,
|
||||
0,
|
||||
"observer".to_string(),
|
||||
AttachmentRole::Observer,
|
||||
false,
|
||||
)
|
||||
.expect("observer attached");
|
||||
|
||||
service
|
||||
.rename(terminal.id, Some("renamed".to_string()))
|
||||
.unwrap();
|
||||
service
|
||||
.rename(terminal.id, Some("renamed".to_string()))
|
||||
.unwrap();
|
||||
let snapshot = service.snapshot(terminal.id).unwrap();
|
||||
assert_eq!(snapshot.info.title, "renamed");
|
||||
assert_eq!(snapshot.info.user_title.as_deref(), Some("renamed"));
|
||||
assert!(service.list().is_ok_and(|items| {
|
||||
items.iter().any(|item| {
|
||||
item.id == terminal.id
|
||||
&& item.title == "renamed"
|
||||
&& item.user_title.as_deref() == Some("renamed")
|
||||
})
|
||||
}));
|
||||
service.terminate(terminal.id).expect("terminal removed");
|
||||
|
||||
let titles = observer
|
||||
.events
|
||||
.iter()
|
||||
.filter_map(|event| match event {
|
||||
StreamEvent::TitleChanged { title } => Some(title),
|
||||
_ => None,
|
||||
})
|
||||
.collect::<Vec<_>>();
|
||||
assert_eq!(titles, ["renamed"]);
|
||||
assert!(service.rename(terminal.id, None).is_err());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn list_returns_terminals_in_creation_order() {
|
||||
let service = TerminalService::new(64 * 1024);
|
||||
let created = (0..6)
|
||||
.map(|_| service.create(command("exec cat")).unwrap().id)
|
||||
.collect::<Vec<_>>();
|
||||
let listed = service
|
||||
.list()
|
||||
.unwrap()
|
||||
.into_iter()
|
||||
.map(|terminal| terminal.id)
|
||||
.collect::<Vec<_>>();
|
||||
assert_eq!(listed, created);
|
||||
service.terminate(created[2]).unwrap();
|
||||
let id = service.create(command("exec cat")).unwrap().id;
|
||||
let listed = service
|
||||
.list()
|
||||
.unwrap()
|
||||
.into_iter()
|
||||
.map(|terminal| terminal.id)
|
||||
.collect::<Vec<_>>();
|
||||
assert_eq!(
|
||||
listed,
|
||||
[
|
||||
created[0], created[1], created[3], created[4], created[5], id
|
||||
]
|
||||
);
|
||||
for id in listed {
|
||||
service.terminate(id).unwrap();
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
#[cfg(target_os = "linux")]
|
||||
fn foreground_process_tracks_deepest_tty_attached_job() {
|
||||
|
||||
@@ -651,7 +651,7 @@ fn observer_disconnect_and_control_input_preserve_independent_terminals() {
|
||||
matches!(daemon.request(Request::List), Response::Terminals { terminals } if terminals.len() == 2)
|
||||
);
|
||||
assert!(
|
||||
matches!(daemon.request(Request::Ping), Response::Pong { instance_id, pid, protocol: 7 }
|
||||
matches!(daemon.request(Request::Ping), Response::Pong { instance_id, pid, protocol: 7, .. }
|
||||
if instance_id == daemon.registration.instance_id && pid == daemon.registration.pid)
|
||||
);
|
||||
assert!(matches!(daemon.own(None).1, Response::Error { .. }));
|
||||
|
||||
Reference in New Issue
Block a user