forked from 1jehuang/jcode
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathprocess_title.rs
More file actions
259 lines (231 loc) · 9.15 KB
/
process_title.rs
File metadata and controls
259 lines (231 loc) · 9.15 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
use crate::cli::args::{AmbientCommand, Args, Command};
const LINUX_PROCESS_TITLE_LIMIT: usize = 15;
const KILLALL_PROCESS_NAME: &str = "jcode";
fn compact_process_title(prefix: &str, name: Option<&str>) -> String {
let mut title = prefix.to_string();
if let Some(name) = name.filter(|name| !name.is_empty()) {
let remaining = LINUX_PROCESS_TITLE_LIMIT.saturating_sub(title.len());
if remaining > 0 {
title.push_str(&name.chars().take(remaining).collect::<String>());
}
}
title
}
pub(crate) fn session_name(session_id: &str) -> String {
crate::id::extract_session_name(session_id)
.map(|name| name.to_string())
.unwrap_or_else(|| session_id.to_string())
}
fn normalized_display_title(title: &str) -> Option<String> {
let normalized = title.split_whitespace().collect::<Vec<_>>().join(" ");
(!normalized.is_empty()).then_some(normalized)
}
fn capitalize_ascii_label(label: &str) -> String {
let mut chars = label.chars();
match chars.next() {
Some(first) => first.to_uppercase().collect::<String>() + chars.as_str(),
None => String::new(),
}
}
fn truncate_chars(text: &str, max_chars: usize) -> String {
let mut chars = text.chars();
let truncated: String = chars.by_ref().take(max_chars).collect();
if chars.next().is_some() {
format!("{}…", truncated)
} else {
truncated
}
}
pub(crate) fn terminal_session_label(session_name: &str, display_title: Option<&str>) -> String {
let fallback = capitalize_ascii_label(session_name);
let Some(title) = display_title.and_then(normalized_display_title) else {
return fallback;
};
if title.eq_ignore_ascii_case(session_name) || title.eq_ignore_ascii_case(&fallback) {
return fallback;
}
format!("{} ({})", truncate_chars(&title, 48), session_name)
}
pub(crate) fn terminal_session_label_for_id(session_id: &str) -> String {
let session_name = session_name(session_id);
let display_title = crate::session::Session::load_startup_stub(session_id)
.ok()
.and_then(|session| session.display_title().map(ToOwned::to_owned));
match display_title.as_deref() {
Some(title) => terminal_session_label(&session_name, Some(title)),
None => session_name,
}
}
pub(crate) fn set_title(title: impl AsRef<str>) {
proctitle::set_title(title.as_ref());
set_killall_process_name();
}
fn set_killall_process_name() {
#[cfg(target_os = "linux")]
unsafe {
let mut name = [0u8; 16];
let bytes = KILLALL_PROCESS_NAME.as_bytes();
let len = bytes.len().min(name.len().saturating_sub(1));
name[..len].copy_from_slice(&bytes[..len]);
let _ = libc::prctl(libc::PR_SET_NAME, name.as_ptr(), 0, 0, 0);
}
}
pub(crate) fn set_server_title(server_name: &str) {
set_title(compact_process_title("jcode:s:", Some(server_name)));
}
pub(crate) fn set_client_generic_title(is_selfdev: bool) {
let prefix = if is_selfdev {
"jcode:selfdev"
} else {
"jcode:client"
};
set_title(compact_process_title(prefix, None));
}
pub(crate) fn set_client_session_title(session_id: &str, is_selfdev: bool) {
set_client_display_title(&session_name(session_id), is_selfdev);
}
pub(crate) fn set_client_display_title(session_name: &str, is_selfdev: bool) {
let prefix = if is_selfdev { "jcode:d:" } else { "jcode:c:" };
set_title(compact_process_title(prefix, Some(session_name)));
}
pub(crate) fn set_client_remote_display_title(
server_name: &str,
session_name: &str,
is_selfdev: bool,
) {
if server_name.is_empty() || server_name.eq_ignore_ascii_case("jcode") {
set_client_display_title(session_name, is_selfdev);
return;
}
let prefix = if is_selfdev { "jcode:d:" } else { "jcode:c:" };
set_title(format!("{prefix}{server_name}/{session_name}"));
}
pub(crate) fn initial_title(args: &Args) -> String {
match &args.command {
Some(Command::Serve { .. }) => "jcode:server".to_string(),
Some(Command::Connect) => "jcode:client".to_string(),
Some(Command::Run { .. }) => "jcode run".to_string(),
Some(Command::Login { .. }) => "jcode login".to_string(),
Some(Command::Repl) => "jcode repl".to_string(),
Some(Command::Update) => "jcode update".to_string(),
Some(Command::Version { .. }) => "jcode version".to_string(),
Some(Command::Usage { .. }) => "jcode usage".to_string(),
Some(Command::SelfDev { .. }) => "jcode:selfdev".to_string(),
Some(Command::Debug { .. }) => "jcode debug".to_string(),
Some(Command::Auth(_)) => "jcode auth".to_string(),
Some(Command::Provider(_)) => "jcode provider".to_string(),
Some(Command::Memory(_)) => "jcode memory".to_string(),
Some(Command::Session(_)) => "jcode session".to_string(),
Some(Command::Ambient(subcommand)) => match subcommand {
AmbientCommand::RunVisible => "jcode ambient visible".to_string(),
_ => "jcode ambient".to_string(),
},
Some(Command::Pair { .. }) => "jcode pair".to_string(),
Some(Command::Permissions) => "jcode permissions".to_string(),
Some(Command::Transcript { .. }) => "jcode transcript".to_string(),
Some(Command::Dictate { .. }) => "jcode dictate".to_string(),
Some(Command::SetupHotkey {
listen_macos_hotkey,
}) => {
if *listen_macos_hotkey {
"jcode hotkey listener".to_string()
} else {
"jcode hotkey setup".to_string()
}
}
Some(Command::Browser { .. }) => "jcode browser".to_string(),
Some(Command::Replay { .. }) => "jcode replay".to_string(),
Some(Command::Model(_)) => "jcode model".to_string(),
Some(Command::AuthTest { .. }) => "jcode auth-test".to_string(),
Some(Command::Restart { .. }) => "jcode restart".to_string(),
Some(Command::SetupLauncher) => "jcode setup-launcher".to_string(),
None => {
if let Some(resume) = args.resume.as_deref().filter(|resume| !resume.is_empty()) {
let prefix = if crate::cli::selfdev::client_selfdev_requested() {
"jcode:d:"
} else {
"jcode:c:"
};
compact_process_title(prefix, Some(&session_name(resume)))
} else if crate::cli::selfdev::client_selfdev_requested() {
"jcode:selfdev".to_string()
} else {
"jcode:client".to_string()
}
}
}
}
pub(crate) fn set_initial_title(args: &Args) {
set_title(initial_title(args));
}
#[cfg(test)]
mod tests {
use super::*;
use crate::cli::args::Args;
use crate::storage::lock_test_env;
use clap::Parser;
const SELFDEV_ENV: &str = crate::cli::selfdev::CLIENT_SELFDEV_ENV;
fn with_selfdev_env_removed<T>(f: impl FnOnce() -> T) -> T {
let _guard = lock_test_env();
let previous = std::env::var_os(SELFDEV_ENV);
crate::env::remove_var(SELFDEV_ENV);
let result = f();
if let Some(value) = previous {
crate::env::set_var(SELFDEV_ENV, value);
}
result
}
#[test]
fn initial_title_labels_server() {
with_selfdev_env_removed(|| {
let args = Args::parse_from(["jcode", "serve"]);
assert_eq!(initial_title(&args), "jcode:server");
});
}
#[test]
fn initial_title_labels_resume_client_with_short_name() {
with_selfdev_env_removed(|| {
let args = Args::parse_from(["jcode", "--resume", "session_fox_123"]);
assert_eq!(initial_title(&args), "jcode:c:fox");
});
}
#[test]
fn terminal_session_label_includes_custom_title_and_short_name() {
assert_eq!(
terminal_session_label("fox", Some("Release planning")),
"Release planning (fox)"
);
assert_eq!(terminal_session_label("fox", Some("Fox")), "Fox");
assert_eq!(terminal_session_label("fox", None), "Fox");
}
#[test]
fn terminal_session_label_for_id_reads_custom_title_from_session() {
let _guard = lock_test_env();
let previous_home = std::env::var_os("JCODE_HOME");
let temp = tempfile::tempdir().expect("temp dir");
crate::env::set_var("JCODE_HOME", temp.path());
let mut session = crate::session::Session::create_with_id(
"session_fox_123".to_string(),
None,
Some("Generated title".to_string()),
);
session.rename_title(Some("Release planning".to_string()));
session.save().expect("save session");
assert_eq!(
terminal_session_label_for_id("session_fox_123"),
"Release planning (fox)"
);
if let Some(previous_home) = previous_home {
crate::env::set_var("JCODE_HOME", previous_home);
} else {
crate::env::remove_var("JCODE_HOME");
}
}
#[test]
fn initial_title_labels_selfdev_command() {
with_selfdev_env_removed(|| {
let args = Args::parse_from(["jcode", "self-dev"]);
assert_eq!(initial_title(&args), "jcode:selfdev");
});
}
}