返回 CodeWhale
terminal.rs
根目录 / crates / app-server / src / runtime_api / terminal.rs
1 //! `/v1/threads/{id}/terminals` — the Engine's terminal byte stream.
2 //!
3 //! The owner is [`codewhale_engine::tools::terminal_session`]: the same PTY-backed shell
4 //! the agent's terminal tools drive, so a client attaching here sees the
5 //! session the model is already working in rather than a second shell beside
6 //! it. These routes never create a session — an identity with no live session
7 //! is a 404, because conjuring a shell from an HTTP request would give the app
8 //! a terminal the Engine does not know about.
9 //!
10 //! A terminal is addressed by the thread that owns it and the identity the
11 //! Engine issued when the shell started (`terminal_id`). Every call resolves
12 //! the thread's recorded workspace again and answers only that thread's shells
13 //! in it, so another thread's or workspace's shell with the same name is never
14 //! reached. Reset and restart issue new identities; an old identity stays a
15 //! 404 instead of attaching to its replacement.
16 //!
17 //! Authentication is the `/v1` route layer's bearer token (see
18 //! [`super::auth`]); nothing here re-implements or bypasses it.
19 //!
20 //! Wire shape deliberately follows `/v1/threads/{id}/jobs/{job_id}/output`:
21 //! `cursor` / `max_bytes` / `format` in, `offset` / `next_cursor` / `total` /
22 //! `dropped` out. Two byte streams in one product should not speak two
23 //! dialects.
24 //!
25 //! Known limitations, recorded because a reader will otherwise assume them:
26 //!
27 //! - **No long poll.** `wait_ms` is not accepted; a client polls the cursor.
28 //! The jobs route can block because a job owns a notification; a terminal
29 //! session's ring has no wake-up channel yet, and inventing one here would
30 //! be a second mechanism rather than a reuse.
31 //! - **No scrollback recovery.** `dropped` reports what the 512 KiB ring
32 //! discarded; those bytes are gone with the process, not on disk.
33 //! - **Live sessions only.** Persistence is identity and lifecycle, never
34 //! output, so a restarted Engine reports a new `instance` and none of the
35 //! old identities rather than pretending to reattach (#34 acceptance:
36 //! "Restart truthfully reports lost live PTYs").
37 //! - **Thread-owned shells only.** A shell started outside a runtime thread
38 //! (the TUI dock, a headless run) has no route here.
39 //! - **Unix only.** The owner is `#[cfg(all(unix, not(target_env = "ohos")))]` end to end; on Windows these
40 //! routes do not exist yet. ConPTY qualification is its own slice.
41
42 #[cfg(all(unix, not(target_env = "ohos")))]
43 use std::path::PathBuf;
44
45 use axum::Json;
46 use axum::extract::{Path, Query, State};
47 #[cfg(all(unix, not(target_env = "ohos")))]
48 use base64::Engine as _;
49 use serde::{Deserialize, Serialize};
50
51 // The owner does not exist on ohos (`tools/mod.rs`), so neither does any
52 // handler that drives it; the stubs below answer there instead.
53 #[cfg(all(unix, not(target_env = "ohos")))]
54 use codewhale_engine::tools::terminal_session;
55
56 #[cfg(all(unix, not(target_env = "ohos")))]
57 use super::workspace::thread_workspace;
58 use super::{ApiError, RuntimeApiState};
59
60 /// Default per-response ceiling; the owner clamps to its own `READ_LIMIT`.
61 #[cfg(all(unix, not(target_env = "ohos")))]
62 const TERMINAL_CHUNK_DEFAULT: usize = 64 * 1024;
63 /// Identities are issued UUIDs; this only bounds the lookup.
64 #[cfg(all(unix, not(target_env = "ohos")))]
65 const TERMINAL_ID_MAX_BYTES: usize = 64;
66 /// One input frame. Interactive typing is bytes, not uploads.
67 #[cfg(all(unix, not(target_env = "ohos")))]
68 const TERMINAL_INPUT_MAX_BYTES: usize = 64 * 1024;
69 #[cfg(all(unix, not(target_env = "ohos")))]
70 const TERMINAL_DIMENSION_MAX: u16 = 1000;
71
72 // The request shape is the contract on every platform; only the Unix
73 // handlers read it, so the 501 builds expect the fields to stay unread.
74 #[cfg_attr(any(not(unix), target_env = "ohos"), expect(dead_code))]
75 #[derive(Deserialize)]
76 #[serde(deny_unknown_fields)]
77 pub(super) struct TerminalOutputQuery {
78 /// Absolute byte offset into the session's lifetime output.
79 #[serde(default)]
80 cursor: Option<u64>,
81 /// Per-response byte ceiling, default 64 KiB, clamped by the owner.
82 #[serde(default)]
83 max_bytes: Option<usize>,
84 /// `base64` (default, exact bytes) or `text` (lossy UTF-8).
85 #[serde(default)]
86 format: Option<String>,
87 }
88
89 #[derive(Debug, Serialize)]
90 pub(super) struct TerminalView {
91 terminal_id: String,
92 name: String,
93 state: String,
94 running: bool,
95 exit_code: Option<u32>,
96 updated_at: String,
97 }
98
99 #[derive(Debug, Serialize)]
100 pub(super) struct TerminalListResponse {
101 thread_id: String,
102 workspace: std::path::PathBuf,
103 instance: String,
104 terminals: Vec<TerminalView>,
105 }
106
107 #[derive(Debug, Serialize)]
108 pub(super) struct TerminalOutputResponse {
109 terminal_id: String,
110 /// Absolute offset of `data[0]`; exceeds `cursor` when the ring already
111 /// discarded that prefix (`dropped` reports the cutoff).
112 offset: u64,
113 /// Pass back as `cursor` to continue.
114 next_cursor: u64,
115 /// Everything the session has produced, including discarded bytes.
116 total: u64,
117 /// Leading bytes the bounded ring permanently discarded.
118 dropped: u64,
119 gap: bool,
120 encoding: &'static str,
121 data: String,
122 /// False once the shell has exited and no bytes remain past `next_cursor`.
123 running: bool,
124 exit_code: Option<i64>,
125 }
126
127 #[cfg_attr(any(not(unix), target_env = "ohos"), expect(dead_code))]
128 #[derive(Deserialize)]
129 #[serde(deny_unknown_fields)]
130 pub(super) struct TerminalInputRequest {
131 data: String,
132 /// `base64` (default, exact bytes) or `text`.
133 #[serde(default)]
134 encoding: Option<String>,
135 }
136
137 #[derive(Debug, Serialize)]
138 pub(super) struct TerminalWriteResponse {
139 terminal_id: String,
140 written: usize,
141 }
142
143 #[cfg_attr(any(not(unix), target_env = "ohos"), expect(dead_code))]
144 #[derive(Deserialize)]
145 #[serde(deny_unknown_fields)]
146 pub(super) struct TerminalResizeRequest {
147 rows: u16,
148 cols: u16,
149 }
150
151 #[derive(Debug, Serialize)]
152 pub(super) struct TerminalResizeResponse {
153 terminal_id: String,
154 rows: u16,
155 cols: u16,
156 }
157
158 #[derive(Debug, Serialize)]
159 pub(super) struct TerminalKillResponse {
160 terminal_id: String,
161 killed: bool,
162 }
163
164 /// `base64` keeps bytes exact; `text` is the lossy convenience form.
165 #[cfg(all(unix, not(target_env = "ohos")))]
166 fn chunk_encoding(format: &str) -> Result<&'static str, ApiError> {
167 match format {
168 "base64" => Ok("base64"),
169 "text" => Ok("text"),
170 _ => Err(ApiError::bad_request("format must be base64 or text")),
171 }
172 }
173
174 #[cfg(all(unix, not(target_env = "ohos")))]
175 fn encode_bytes(bytes: &[u8], encoding: &str) -> String {
176 if encoding == "base64" {
177 base64::engine::general_purpose::STANDARD.encode(bytes)
178 } else {
179 String::from_utf8_lossy(bytes).into_owned()
180 }
181 }
182
183 #[cfg(all(unix, not(target_env = "ohos")))]
184 fn decode_bytes(data: &str, encoding: &str) -> Result<Vec<u8>, ApiError> {
185 let bytes = match encoding {
186 "base64" => base64::engine::general_purpose::STANDARD
187 .decode(data)
188 .map_err(|_| ApiError::bad_request("data is not valid base64"))?,
189 "text" => data.as_bytes().to_vec(),
190 _ => return Err(ApiError::bad_request("encoding must be base64 or text")),
191 };
192 if bytes.len() > TERMINAL_INPUT_MAX_BYTES {
193 return Err(ApiError::bad_request(format!(
194 "input exceeds {TERMINAL_INPUT_MAX_BYTES} bytes"
195 )));
196 }
197 Ok(bytes)
198 }
199
200 #[cfg(all(unix, not(target_env = "ohos")))]
201 fn bounded_max_bytes(requested: Option<usize>) -> Result<usize, ApiError> {
202 let max_bytes = requested.unwrap_or(TERMINAL_CHUNK_DEFAULT);
203 if !(1..=terminal_session::READ_LIMIT).contains(&max_bytes) {
204 return Err(ApiError::bad_request(format!(
205 "max_bytes must be between 1 and {}",
206 terminal_session::READ_LIMIT
207 )));
208 }
209 Ok(max_bytes)
210 }
211
212 #[cfg(all(unix, not(target_env = "ohos")))]
213 fn bounded_dimension(value: u16, field: &str) -> Result<u16, ApiError> {
214 if !(1..=TERMINAL_DIMENSION_MAX).contains(&value) {
215 return Err(ApiError::bad_request(format!(
216 "{field} must be between 1 and {TERMINAL_DIMENSION_MAX}"
217 )));
218 }
219 Ok(value)
220 }
221
222 #[cfg(all(unix, not(target_env = "ohos")))]
223 fn terminal_not_found() -> ApiError {
224 ApiError::not_found("no live terminal with this identity in this thread")
225 .with_code("terminal_not_found")
226 }
227
228 #[cfg(all(unix, not(target_env = "ohos")))]
229 fn lock(
230 session: &terminal_session::SharedSession,
231 ) -> Result<std::sync::MutexGuard<'_, terminal_session::TerminalSession>, ApiError> {
232 session
233 .lock()
234 .map_err(|_| ApiError::internal("terminal session lock poisoned"))
235 }
236
237 #[cfg(all(unix, not(target_env = "ohos")))]
238 fn state_label(state: terminal_session::DurableTerminalState) -> String {
239 serde_json::to_value(state)
240 .ok()
241 .and_then(|value| value.as_str().map(str::to_owned))
242 .unwrap_or_default()
243 }
244
245 #[cfg(all(unix, not(target_env = "ohos")))]
246 fn input_error(error: terminal_session::HumanInputError) -> ApiError {
247 use terminal_session::HumanInputError;
248 match &error {
249 HumanInputError::Gone => terminal_not_found(),
250 HumanInputError::Posture => {
251 ApiError::forbidden(error.to_string()).with_code("terminal_posture_changed")
252 }
253 HumanInputError::Exited => {
254 ApiError::conflict(error.to_string()).with_code("terminal_exited")
255 }
256 HumanInputError::Rejected(message) => ApiError::bad_request(message.clone()),
257 HumanInputError::Failed(message) => ApiError::internal(message.clone()),
258 }
259 }
260
261 /// How many terminal route calls may occupy blocking threads at once. The
262 /// rest wait in `with_terminal` asynchronously, so a client that disconnects
263 /// while queued simply disappears instead of holding a pool thread, and one
264 /// stuck write (a child that stopped reading, lock held) can stall terminal
265 /// routes but never the runtime's other blocking work.
266 #[cfg(all(unix, not(target_env = "ohos")))]
267 static ROUTE_GATE: tokio::sync::Semaphore = tokio::sync::Semaphore::const_new(8);
268
269 /// Resolve one of the thread's live shells by identity and run one operation
270 /// against it on the blocking pool.
271 ///
272 /// The session mutex and the PTY behind it are synchronous: the agent's own
273 /// tool holds the lock across a whole command, and a write to a child that
274 /// stopped reading blocks until the kernel buffer drains. Neither may park a
275 /// runtime worker (#6149), so a route never touches the session inline, and
276 /// `ROUTE_GATE` bounds how many such touches can be in flight.
277 #[cfg(all(unix, not(target_env = "ohos")))]
278 async fn with_terminal<T>(
279 workspace: PathBuf,
280 thread_id: String,
281 terminal_id: String,
282 operation: impl FnOnce(&terminal_session::SharedSession) -> Result<T, ApiError> + Send + 'static,
283 ) -> Result<T, ApiError>
284 where
285 T: Send + 'static,
286 {
287 if terminal_id.is_empty() || terminal_id.len() > TERMINAL_ID_MAX_BYTES {
288 return Err(terminal_not_found());
289 }
290 let permit = ROUTE_GATE
291 .acquire()
292 .await
293 .map_err(|_| ApiError::internal("terminal route gate closed"))?;
294 tokio::task::spawn_blocking(move || {
295 let _permit = permit;
296 let session = terminal_session::lookup(&workspace, Some(&thread_id), &terminal_id)
297 .ok_or_else(terminal_not_found)?;
298 operation(&session)
299 })
300 .await
301 .map_err(|error| ApiError::internal(error.to_string()))?
302 }
303
304 /// `GET /v1/threads/{id}/terminals` — the thread's live shells, newest
305 /// activity first, with the registry `instance` they belong to.
306 #[cfg(all(unix, not(target_env = "ohos")))]
307 pub(super) async fn list_thread_terminals(
308 State(state): State<RuntimeApiState>,
309 Path(thread_id): Path<String>,
310 ) -> Result<Json<TerminalListResponse>, ApiError> {
311 let (_, workspace) = thread_workspace(&state, &thread_id).await?;
312 let permit = ROUTE_GATE
313 .acquire()
314 .await
315 .map_err(|_| ApiError::internal("terminal route gate closed"))?;
316 let scope = workspace.clone();
317 let owner = thread_id.clone();
318 let sessions = tokio::task::spawn_blocking(move || {
319 let _permit = permit;
320 terminal_session::owned_sessions(&scope, &owner).map_err(ApiError::internal)
321 })
322 .await
323 .map_err(|error| ApiError::internal(error.to_string()))??;
324 Ok(Json(TerminalListResponse {
325 thread_id,
326 workspace,
327 instance: terminal_session::instance_id().to_string(),
328 terminals: sessions
329 .into_iter()
330 .map(|info| TerminalView {
331 running: info.exit_code.is_none(),
332 terminal_id: info.id,
333 name: info.name,
334 state: if info.exit_code.is_some() {
335 "exited".to_string()
336 } else {
337 state_label(info.state)
338 },
339 exit_code: info.exit_code,
340 updated_at: info.updated_at,
341 })
342 .collect(),
343 }))
344 }
345
346 /// `GET /v1/threads/{id}/terminals/{terminal_id}/output` — the resumable byte
347 /// stream.
348 ///
349 /// Reads are non-consuming: several clients may hold independent cursors, and
350 /// polling here never steals output from the agent's own consuming read.
351 #[cfg(all(unix, not(target_env = "ohos")))]
352 pub(super) async fn terminal_output(
353 State(state): State<RuntimeApiState>,
354 Path((thread_id, terminal_id)): Path<(String, String)>,
355 Query(query): Query<TerminalOutputQuery>,
356 ) -> Result<Json<TerminalOutputResponse>, ApiError> {
357 let encoding = chunk_encoding(query.format.as_deref().unwrap_or("base64"))?;
358 let max_bytes = bounded_max_bytes(query.max_bytes)?;
359 let cursor = query.cursor.unwrap_or(0);
360 let (_, workspace) = thread_workspace(&state, &thread_id).await?;
361 let (chunk, exit) = with_terminal(workspace, thread_id, terminal_id.clone(), move |session| {
362 let mut session = lock(session)?;
363 let chunk = terminal_session::read_session_since(&session, cursor, max_bytes)
364 .map_err(ApiError::internal)?;
365 let exit =
366 terminal_session::session_exit_status(&mut session).map_err(ApiError::internal)?;
367 Ok((chunk, exit))
368 })
369 .await?;
370 let running = exit.is_none();
371 Ok(Json(TerminalOutputResponse {
372 terminal_id,
373 offset: chunk.offset,
374 next_cursor: chunk.next_cursor,
375 total: chunk.total,
376 dropped: chunk.dropped,
377 gap: chunk.gap,
378 encoding,
379 data: encode_bytes(&chunk.bytes, encoding),
380 // A gap means bytes were lost; `running` alone must not imply there is
381 // nothing behind us, so drain state is reported independently.
382 running,
383 exit_code: exit.map(|status| i64::from(status.exit_code())),
384 }))
385 }
386
387 /// `POST /v1/threads/{id}/terminals/{terminal_id}/input` — bytes into the live
388 /// shell. The thread's shell consent and shell policy apply, and so does the
389 /// sandbox-reuse guard the TUI dock applies to a person's input.
390 ///
391 /// Input attribution is the caller's: this route is the client's writer, and
392 /// the agent's writer is `terminal_send`. Nothing here re-labels one as the
393 /// other.
394 #[cfg(all(unix, not(target_env = "ohos")))]
395 pub(super) async fn terminal_input(
396 State(state): State<RuntimeApiState>,
397 Path((thread_id, terminal_id)): Path<(String, String)>,
398 Json(request): Json<TerminalInputRequest>,
399 ) -> Result<Json<TerminalWriteResponse>, ApiError> {
400 let bytes = decode_bytes(
401 &request.data,
402 request.encoding.as_deref().unwrap_or("base64"),
403 )?;
404 let (thread, workspace) = thread_workspace(&state, &thread_id).await?;
405 if !thread.allow_shell {
406 return Err(
407 ApiError::forbidden("this thread does not allow shell commands")
408 .with_code("thread_shell_disabled"),
409 );
410 }
411 state
412 .runtime_threads
413 .validate_shell_access_policy(
414 &workspace,
415 state.config_path.as_deref(),
416 state.config_profile.as_deref(),
417 )
418 .await
419 .map_err(|error| ApiError::forbidden(error.to_string()))?;
420 let policy = state
421 .runtime_threads
422 .thread_job_sandbox_policy(&thread)
423 .await;
424 let written = bytes.len();
425 with_terminal(workspace, thread_id, terminal_id.clone(), move |session| {
426 terminal_session::write_human_input(session, &bytes, &policy).map_err(input_error)
427 })
428 .await?;
429 Ok(Json(TerminalWriteResponse {
430 terminal_id,
431 written,
432 }))
433 }
434
435 /// `POST /v1/threads/{id}/terminals/{terminal_id}/resize` — the window the
436 /// child should draw for.
437 #[cfg(all(unix, not(target_env = "ohos")))]
438 pub(super) async fn terminal_resize(
439 State(state): State<RuntimeApiState>,
440 Path((thread_id, terminal_id)): Path<(String, String)>,
441 Json(request): Json<TerminalResizeRequest>,
442 ) -> Result<Json<TerminalResizeResponse>, ApiError> {
443 let rows = bounded_dimension(request.rows, "rows")?;
444 let cols = bounded_dimension(request.cols, "cols")?;
445 let (_, workspace) = thread_workspace(&state, &thread_id).await?;
446 with_terminal(workspace, thread_id, terminal_id.clone(), move |session| {
447 let session = lock(session)?;
448 terminal_session::resize_session(&session, rows, cols).map_err(ApiError::internal)
449 })
450 .await?;
451 Ok(Json(TerminalResizeResponse {
452 terminal_id,
453 rows,
454 cols,
455 }))
456 }
457
458 /// `POST /v1/threads/{id}/terminals/{terminal_id}/kill` — end the shell.
459 ///
460 /// The exit itself is observed through `output` (`running` / `exit_code`),
461 /// so a client that kills and then polls learns the truth instead of an
462 /// optimistic acknowledgement. `killed` is false when the shell had already
463 /// exited.
464 #[cfg(all(unix, not(target_env = "ohos")))]
465 pub(super) async fn terminal_kill(
466 State(state): State<RuntimeApiState>,
467 Path((thread_id, terminal_id)): Path<(String, String)>,
468 ) -> Result<Json<TerminalKillResponse>, ApiError> {
469 let (_, workspace) = thread_workspace(&state, &thread_id).await?;
470 let killed = with_terminal(workspace, thread_id, terminal_id.clone(), |session| {
471 let mut session = lock(session)?;
472 if terminal_session::session_exit_status(&mut session)
473 .map_err(ApiError::internal)?
474 .is_some()
475 {
476 return Ok(false);
477 }
478 terminal_session::kill_session(&mut session).map_err(ApiError::internal)?;
479 Ok(true)
480 })
481 .await?;
482 Ok(Json(TerminalKillResponse {
483 terminal_id,
484 killed,
485 }))
486 }
487
488 /// `/v1/terminal/{name}/*` addressed a shell by a reusable name at the
489 /// server's workspace, which could reach another thread's or workspace's
490 /// shell. It answers 410 on every platform so a client built for it fails
491 /// loudly instead of attaching to the wrong shell.
492 pub(super) async fn retired_terminal_route() -> ApiError {
493 ApiError::gone(
494 "name-addressed terminal routes were retired; list GET /v1/threads/{id}/terminals and address a terminal by its terminal_id",
495 )
496 .with_code("terminal_route_retired")
497 }
498
499 /// Windows build: the owner is `#[cfg(all(unix, not(target_env = "ohos")))]` end to end, so the contract
500 /// exists but cannot be served. These answer 501 rather than 404 so a client
501 /// can tell "this Engine build cannot do terminals" apart from "that session
502 /// is gone" — and so the ConPTY slice has one place to replace.
503 #[cfg(any(not(unix), target_env = "ohos"))]
504 mod platform {
505 use super::*;
506
507 fn unsupported() -> ApiError {
508 ApiError::not_implemented(
509 "terminal sessions are Unix-only in this build; native Windows PTY support is not implemented yet",
510 )
511 }
512
513 pub(crate) async fn list_thread_terminals(
514 State(_): State<RuntimeApiState>,
515 Path(_): Path<String>,
516 ) -> Result<Json<TerminalListResponse>, ApiError> {
517 Err(unsupported())
518 }
519
520 pub(crate) async fn terminal_output(
521 State(_): State<RuntimeApiState>,
522 Path(_): Path<(String, String)>,
523 Query(_): Query<TerminalOutputQuery>,
524 ) -> Result<Json<TerminalOutputResponse>, ApiError> {
525 Err(unsupported())
526 }
527
528 pub(crate) async fn terminal_input(
529 State(_): State<RuntimeApiState>,
530 Path(_): Path<(String, String)>,
531 Json(_): Json<TerminalInputRequest>,
532 ) -> Result<Json<TerminalWriteResponse>, ApiError> {
533 Err(unsupported())
534 }
535
536 pub(crate) async fn terminal_resize(
537 State(_): State<RuntimeApiState>,
538 Path(_): Path<(String, String)>,
539 Json(_): Json<TerminalResizeRequest>,
540 ) -> Result<Json<TerminalResizeResponse>, ApiError> {
541 Err(unsupported())
542 }
543
544 pub(crate) async fn terminal_kill(
545 State(_): State<RuntimeApiState>,
546 Path(_): Path<(String, String)>,
547 ) -> Result<Json<TerminalKillResponse>, ApiError> {
548 Err(unsupported())
549 }
550 }
551
552 #[cfg(any(not(unix), target_env = "ohos"))]
553 pub(super) use platform::{
554 list_thread_terminals, terminal_input, terminal_kill, terminal_output, terminal_resize,
555 };
556
557 #[cfg(all(test, unix, not(target_env = "ohos")))]
558 mod tests {
559 use super::*;
560
561 #[test]
562 fn encodings_round_trip_exact_bytes_and_stay_lossy_only_on_request() {
563 // Non-UTF-8 bytes survive base64 and are the reason it is the default.
564 let raw = [0xf0, 0x9f, 0x90, 0x8b, 0x00, 0xff];
565 let encoded = encode_bytes(&raw, "base64");
566 assert_eq!(decode_bytes(&encoded, "base64").unwrap(), raw);
567 // The lossy form is explicit and cannot be mistaken for fidelity.
568 let text = encode_bytes(&raw, "text");
569 assert!(text.contains('\u{fffd}'));
570 assert_eq!(decode_bytes(&text, "text").unwrap(), text.as_bytes());
571 }
572
573 #[test]
574 fn encoding_names_are_closed_sets() {
575 for good in ["base64", "text"] {
576 assert_eq!(chunk_encoding(good).unwrap(), good);
577 }
578 for bad in ["utf8", "raw", "Base64", ""] {
579 assert!(chunk_encoding(bad).is_err(), "{bad} must not be accepted");
580 assert!(decode_bytes("", bad).is_err(), "{bad} must not decode");
581 }
582 // A base64 decoder that ignores padding would accept junk bytes.
583 assert!(decode_bytes("not base64!!", "base64").is_err());
584 }
585
586 #[test]
587 fn chunk_and_dimension_bounds_reject_the_edges() {
588 assert_eq!(bounded_max_bytes(None).unwrap(), TERMINAL_CHUNK_DEFAULT);
589 assert_eq!(
590 bounded_max_bytes(Some(terminal_session::READ_LIMIT)).unwrap(),
591 terminal_session::READ_LIMIT
592 );
593 assert!(bounded_max_bytes(Some(0)).is_err());
594 assert!(bounded_max_bytes(Some(terminal_session::READ_LIMIT + 1)).is_err());
595 assert_eq!(bounded_dimension(24, "rows").unwrap(), 24);
596 assert!(bounded_dimension(0, "rows").is_err());
597 assert!(bounded_dimension(TERMINAL_DIMENSION_MAX + 1, "cols").is_err());
598 }
599
600 #[test]
601 fn input_is_bounded_before_it_reaches_the_pty() {
602 let too_much =
603 base64::engine::general_purpose::STANDARD
604 .encode(vec![b'a'; TERMINAL_INPUT_MAX_BYTES + 1]);
605 assert!(decode_bytes(&too_much, "base64").is_err());
606 let at_limit =
607 base64::engine::general_purpose::STANDARD.encode(vec![b'a'; TERMINAL_INPUT_MAX_BYTES]);
608 assert_eq!(
609 decode_bytes(&at_limit, "base64").unwrap().len(),
610 TERMINAL_INPUT_MAX_BYTES
611 );
612 }
613 }
614
614 lines RUST