aboutsummaryrefslogtreecommitdiffstats
diff options
context:
space:
mode:
authorAram Drevekenin <aram@poor.dev>2026-04-30 18:15:06 +0200
committerGitHub <noreply@github.com>2026-04-30 18:15:06 +0200
commit914953758357024d3c1aeaa496bfe8df906f8416 (patch)
treef16711c8a2b1e6ad5fb7b88c3cfd9b7d282a14cf
parentfix(windows): stop reusing terminal pane ids (#5082) (diff)
downloadsl0ppij-914953758357024d3c1aeaa496bfe8df906f8416.tar.gz
sl0ppij-914953758357024d3c1aeaa496bfe8df906f8416.tar.xz
sl0ppij-914953758357024d3c1aeaa496bfe8df906f8416.zip
fix: buffer pty processing while waiting for host query reply (#5113)
* fix: block pty byte processing while waiting for host terminal reply * rustfmt * add pr
-rw-r--r--CHANGELOG.md2
-rw-r--r--zellij-server/src/panes/terminal_pane.rs51
-rw-r--r--zellij-server/src/screen.rs112
-rw-r--r--zellij-server/src/tab/mod.rs94
-rw-r--r--zellij-server/src/unit/screen_tests.rs263
-rw-r--r--zellij-utils/src/errors.rs1
6 files changed, 507 insertions, 16 deletions
diff --git a/CHANGELOG.md b/CHANGELOG.md
index 87dfd449..04a2fffb 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -10,7 +10,7 @@ The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.0.0/)
* fix: restore kitty keyboard mode on error, handle DECRPM 2026 state 3, clean up client terminal teardown sequences (https://github.com/zellij-org/zellij/pull/5058)
* fix: stop reusing terminal pane ids on windows so reopened panes are not closed by stale events (https://github.com/zellij-org/zellij/pull/5082)
* fix: prevent occasional duplicate characters in the web client due to IME (https://github.com/zellij-org/zellij/pull/4975)
-* feat: support `CSI 2031` + dark/light mode theme switching (https://github.com/zellij-org/zellij/pull/5105 and https://github.com/zellij-org/zellij/pull/5111)
+* feat: support `CSI 2031` + dark/light mode theme switching (https://github.com/zellij-org/zellij/pull/5105, https://github.com/zellij-org/zellij/pull/5111 and https://github.com/zellij-org/zellij/pull/5113)
* fix: incorrect interpretation of unicode characters in KKP STDIN (https://github.com/zellij-org/zellij/pull/5110)
## [0.44.1] - 2026-04-07
diff --git a/zellij-server/src/panes/terminal_pane.rs b/zellij-server/src/panes/terminal_pane.rs
index eeec67d9..477185a4 100644
--- a/zellij-server/src/panes/terminal_pane.rs
+++ b/zellij-server/src/panes/terminal_pane.rs
@@ -10,7 +10,7 @@ use crate::route::NotificationEnd;
use crate::tab::{AdjustedInput, Pane};
use crate::ClientId;
use std::cell::RefCell;
-use std::collections::{HashMap, HashSet};
+use std::collections::{HashMap, HashSet, VecDeque};
use std::fmt::Debug;
use std::rc::Rc;
use std::time::{self, Instant};
@@ -153,6 +153,19 @@ pub struct TerminalPane {
#[allow(dead_code)]
arrow_fonts: bool,
notification_end: Option<NotificationEnd>,
+ /// `true` while a host-terminal forward initiated by this pane is
+ /// outstanding. While set, processing of `pending_pty_input` is
+ /// suspended so that the async host reply lands on the pane's
+ /// stdin in the same stream position the original query occupied.
+ /// Cleared by Tab when the reply (or 500 ms cache-fallback) lands.
+ forward_paused: bool,
+ /// PTY bytes that have not yet been fed to vte. Single source of
+ /// truth: `handle_pty_bytes` always appends here, and processing
+ /// pops one byte at a time and advances the vte parser. Processing
+ /// stops as soon as Grid produces a forward-bound query, leaving
+ /// remaining bytes in the queue to be drained after the host reply
+ /// has been written.
+ pending_pty_input: VecDeque<u8>,
}
impl Pane for TerminalPane {
@@ -203,8 +216,22 @@ impl Pane for TerminalPane {
}
fn handle_pty_bytes(&mut self, bytes: VteBytes) {
self.set_should_render(true);
- for &byte in &bytes {
+ if self.forward_paused {
+ // A host-forward initiated by this pane is outstanding.
+ // Buffer the bytes; Tab drains them on resume.
+ self.pending_pty_input.extend(bytes);
+ return;
+ }
+ let mut iter = bytes.into_iter();
+ while let Some(byte) = iter.next() {
self.vte_parser.advance(&mut self.grid, byte);
+ if !self.grid.pending_forwarded_queries.is_empty() {
+ // Grid produced a forward. Stop feeding; queue the
+ // un-fed remainder so Tab can replay it after the
+ // reply.
+ self.pending_pty_input.extend(iter);
+ break;
+ }
}
}
fn cursor_coordinates(&self, _client_id: Option<ClientId>) -> Option<(usize, usize, bool)> {
@@ -590,6 +617,24 @@ impl Pane for TerminalPane {
self.grid.pending_forwarded_queries.drain(..).collect()
}
+ fn arm_forward_pause(&mut self) {
+ self.forward_paused = true;
+ }
+
+ fn clear_forward_pause(&mut self) -> bool {
+ let was_paused = self.forward_paused;
+ self.forward_paused = false;
+ was_paused
+ }
+
+ fn drain_pending_pty_input(&mut self) -> Vec<u8> {
+ self.pending_pty_input.drain(..).collect()
+ }
+
+ fn is_forward_paused(&self) -> bool {
+ self.forward_paused
+ }
+
fn push_color_palette_dsr(&mut self, mode: zellij_utils::data::HostTerminalThemeMode) {
self.grid.push_color_palette_dsr(mode);
}
@@ -1093,6 +1138,8 @@ impl TerminalPane {
invoked_with,
arrow_fonts,
notification_end,
+ forward_paused: false,
+ pending_pty_input: VecDeque::new(),
}
}
pub fn get_x(&self) -> usize {
diff --git a/zellij-server/src/screen.rs b/zellij-server/src/screen.rs
index f3d130ec..fd9a7014 100644
--- a/zellij-server/src/screen.rs
+++ b/zellij-server/src/screen.rs
@@ -516,6 +516,18 @@ pub enum ScreenInstruction {
token: u32,
reply_bytes: Vec<u8>,
},
+ /// Internal: a forwarded reply (or its cache-fallback synthesis,
+ /// or a locally-answered query like `ColorPaletteMode`) is ready
+ /// to be delivered to the originating pane. Routed through the
+ /// owning Tab so that the bytes are written to PTY *and* any
+ /// PTY input that arrived while the pane was forward-paused is
+ /// drained and re-fed through vte in stream order. This preserves
+ /// query/reply ordering even when sync replies (DA1, DSR, DECQRM)
+ /// would otherwise race ahead of an async host round-trip.
+ ResumePaneAfterForward {
+ pane_id: PaneId,
+ reply_bytes: Vec<u8>,
+ },
/// The host terminal reported a color-palette theme mode (DSR 997 reply
/// to `CSI ? 996 n`, or unsolicited notification while `CSI ? 2031 h`
/// is enabled). Triggers auto-theme switch (when configured), the
@@ -977,6 +989,9 @@ impl From<&ScreenInstruction> for ScreenContext {
ScreenInstruction::ForwardedReplyFromHost { .. } => {
ScreenContext::ForwardedReplyFromHost
},
+ ScreenInstruction::ResumePaneAfterForward { .. } => {
+ ScreenContext::ResumePaneAfterForward
+ },
ScreenInstruction::HostTerminalThemeChanged(..) => {
ScreenContext::HostTerminalThemeChanged
},
@@ -2136,10 +2151,9 @@ impl Screen {
/// defines `;1` (dark) and `;2` (light); fabricating any other
/// code (e.g. `;0`) would be non-conformant.
fn answer_color_palette_mode_query_locally(&mut self, pane_id: PaneId) {
- let terminal_id = match pane_id {
- PaneId::Terminal(id) => id,
- PaneId::Plugin(_) => return,
- };
+ if matches!(pane_id, PaneId::Plugin(_)) {
+ return;
+ }
let code: u8 = match self.host_terminal_theme_mode {
Some(HostTerminalThemeMode::Dark) => 1,
Some(HostTerminalThemeMode::Light) => 2,
@@ -2148,14 +2162,24 @@ impl Screen {
"CSI ?996n received but host_terminal_theme_mode is unknown; \
dropping (spec defines only 1=dark / 2=light)"
);
+ // The Contour spec defines only ;1 / ;2 — silence is
+ // the conformant behaviour when the host's mode is
+ // unknown. But the pane may have been forward-paused
+ // on the dispatch; if so we still owe it an unblock
+ // cycle so any buffered bytes get replayed. Skip the
+ // empty resume when the pane is not paused, matching
+ // the "stay silent" guarantee.
+ if self.is_any_tab_pane_forward_paused(pane_id) {
+ let _ = self.resume_pane_after_forward(pane_id, Vec::new());
+ }
return;
},
};
let reply = format!("\u{1b}[?997;{}n", code).into_bytes();
- let _ = self
- .bus
- .senders
- .send_to_pty_writer(PtyWriteInstruction::Write(reply, terminal_id, None));
+ // Route via Tab so the reply lands on the pane in the correct
+ // stream position and any PTY input the app emitted while
+ // waiting is replayed.
+ let _ = self.resume_pane_after_forward(pane_id, reply);
}
/// Dispatch a forward to the client and mark the slot as in-flight.
@@ -2225,16 +2249,16 @@ impl Screen {
if let Some(entry) = self.pending_forwarded_queries.remove(&token) {
let PendingForwardEntry { pane_id, query } = entry;
match pane_id {
- PaneId::Terminal(terminal_id) => {
+ PaneId::Terminal(_) => {
let payload = if reply_bytes.is_empty() {
self.synthesize_cached_reply(&query)
} else {
reply_bytes
};
- let _ = self
- .bus
- .senders
- .send_to_pty_writer(PtyWriteInstruction::Write(payload, terminal_id, None));
+ // Route via Tab so the reply lands on the pane in
+ // the correct stream position and any PTY input
+ // the app emitted while waiting is replayed.
+ self.resume_pane_after_forward(pane_id, payload)?;
},
PaneId::Plugin(_) => {
// Plugin panes do not issue whitelisted host queries;
@@ -2255,6 +2279,62 @@ impl Screen {
Ok(())
}
+ /// Whether any tab owns `pane_id` AND the pane is currently
+ /// forward-paused. Used by the `ColorPaletteMode` short-circuit
+ /// to skip the empty-payload resume when no pane needs unblocking.
+ fn is_any_tab_pane_forward_paused(&self, pane_id: PaneId) -> bool {
+ self.tabs
+ .values()
+ .any(|tab| tab.is_pane_forward_paused(pane_id))
+ }
+
+ /// Deliver a forwarded reply (or cache-fallback synthesis, or a
+ /// locally-answered query payload) to the originating pane via
+ /// the owning Tab. The Tab handler writes the bytes to PTY and
+ /// then re-feeds any PTY input that was buffered while the pane
+ /// was forward-paused, preserving query/reply ordering.
+ pub fn resume_pane_after_forward(
+ &mut self,
+ pane_id: PaneId,
+ reply_bytes: Vec<u8>,
+ ) -> Result<()> {
+ let terminal_id = match pane_id {
+ PaneId::Terminal(id) => id,
+ PaneId::Plugin(_) => {
+ // Plugin panes do not forward queries — dropping is
+ // the correct behaviour matching the existing
+ // forwarding path's plugin-pane guard.
+ return Ok(());
+ },
+ };
+ let mut found = false;
+ for tab in self.tabs.values_mut() {
+ if tab.has_pane_with_pid(&pane_id) {
+ tab.resume_pane_after_forward(terminal_id, reply_bytes.clone())
+ .non_fatal();
+ found = true;
+ break;
+ }
+ }
+ if !found {
+ // No tab owns the pane — the pane was closed between the
+ // forward dispatch and the reply arrival. The terminal id
+ // is probably defunct; the write goes to the PTY writer
+ // anyway because an empty payload is the canonical "host
+ // declined" reply some apps rely on, and a non-empty
+ // payload may still be deliverable until the pty drains.
+ let _ = self
+ .bus
+ .senders
+ .send_to_pty_writer(PtyWriteInstruction::Write(reply_bytes, terminal_id, None));
+ log::debug!(
+ "ResumePaneAfterForward: pane {:?} not in any tab, fell back to direct PTY write",
+ pane_id
+ );
+ }
+ Ok(())
+ }
+
/// Build a reply for `query` from whatever host state Zellij has
/// cached, or an empty `Vec` if nothing relevant is cached. The
/// classification happened at intercept time (Grid produces a
@@ -7160,6 +7240,12 @@ pub(crate) fn screen_thread_main(
ScreenInstruction::ForwardedReplyFromHost { token, reply_bytes } => {
screen.handle_forwarded_reply_from_host(token, reply_bytes)?;
},
+ ScreenInstruction::ResumePaneAfterForward {
+ pane_id,
+ reply_bytes,
+ } => {
+ screen.resume_pane_after_forward(pane_id, reply_bytes)?;
+ },
ScreenInstruction::HostTerminalThemeChanged(mode) => {
screen.update_host_terminal_theme_mode(mode)?;
},
diff --git a/zellij-server/src/tab/mod.rs b/zellij-server/src/tab/mod.rs
index 36744b96..026dee9e 100644
--- a/zellij-server/src/tab/mod.rs
+++ b/zellij-server/src/tab/mod.rs
@@ -414,6 +414,27 @@ pub trait Pane {
// plugin panes have no such concept.
vec![]
}
+ /// Mark this pane as awaiting a host-terminal reply for a forward
+ /// it just dispatched. While paused, vte byte feeding is buffered
+ /// so that the eventual host reply lands on the pane's stdin in
+ /// the same stream position the original query occupied. Default
+ /// no-op for non-terminal panes (plugins do not forward queries).
+ fn arm_forward_pause(&mut self) {}
+ /// Clear the forward-pause flag set by `arm_forward_pause`, returning
+ /// `true` if the pane was previously paused. Default no-op.
+ fn clear_forward_pause(&mut self) -> bool {
+ false
+ }
+ /// Drain and return any PTY bytes that arrived while the pane was
+ /// forward-paused. Tab calls this on resume and re-feeds the bytes
+ /// through `handle_pty_bytes`. Default empty for non-terminal panes.
+ fn drain_pending_pty_input(&mut self) -> Vec<u8> {
+ vec![]
+ }
+ /// Whether this pane is currently waiting for a host-forward reply.
+ fn is_forward_paused(&self) -> bool {
+ false
+ }
/// Push a CSI ?997 DSR notification (host color-palette theme mode)
/// onto this pane's pending pty-write queue, but only if the pane's
/// underlying app opted in via `CSI ? 2031 h`.
@@ -2607,6 +2628,24 @@ impl Tab {
.values()
.any(|s_p| s_p.1.pid() == PaneId::Terminal(pid))
}
+ /// Whether the pane with `pane_id` (if owned by this tab) is
+ /// currently waiting for a host-forward reply. Used by the
+ /// `ColorPaletteMode` short-circuit to decide whether an empty
+ /// "host mode unknown" answer needs to drive an unblock cycle:
+ /// if the pane is not paused, no work is owed.
+ pub fn is_pane_forward_paused(&self, pane_id: PaneId) -> bool {
+ self.tiled_panes
+ .get_pane(pane_id)
+ .or_else(|| self.floating_panes.get_pane(pane_id))
+ .or_else(|| {
+ self.suppressed_panes
+ .values()
+ .find(|s_p| s_p.1.pid() == pane_id)
+ .map(|s_p| &s_p.1)
+ })
+ .map(|p| p.is_forward_paused())
+ .unwrap_or(false)
+ }
pub fn has_plugin(&self, plugin_id: u32) -> bool {
self.tiled_panes.panes_contain(&PaneId::Plugin(plugin_id))
|| self
@@ -2709,6 +2748,48 @@ impl Tab {
}
Ok(())
}
+ /// Deliver a forwarded host reply (or cache-fallback synthesis,
+ /// or a locally-answered query payload) to a pane that is currently
+ /// forward-paused. The reply bytes are written to the pane's PTY
+ /// first (so the app reads them on its stdin in the same stream
+ /// position the original query occupied), then the pause flag is
+ /// cleared and any PTY bytes that arrived while the pane was
+ /// paused are re-fed through vte. The re-feed itself may produce
+ /// another forward and re-arm the pause; the cycle bounds at the
+ /// buffered byte count.
+ pub fn resume_pane_after_forward(&mut self, pid: u32, reply_bytes: Vec<u8>) -> Result<()> {
+ let err_context = || format!("failed to resume pane {pid} after forward");
+ // Write the reply first so the app sees it on stdin before
+ // any subsequent (sync or async) reply that follows in the
+ // buffered byte stream.
+ if !reply_bytes.is_empty() {
+ self.write_to_pane_id_without_preprocessing(reply_bytes, PaneId::Terminal(pid))
+ .with_context(err_context)?;
+ }
+ // Clear the pause and pull out any bytes that were buffered
+ // while it waited for the host reply.
+ let buffered = if let Some(terminal_output) = self
+ .tiled_panes
+ .get_pane_mut(PaneId::Terminal(pid))
+ .or_else(|| self.floating_panes.get_pane_mut(PaneId::Terminal(pid)))
+ .or_else(|| {
+ self.suppressed_panes
+ .values_mut()
+ .find(|s_p| s_p.1.pid() == PaneId::Terminal(pid))
+ .map(|s_p| &mut s_p.1)
+ }) {
+ terminal_output.clear_forward_pause();
+ terminal_output.drain_pending_pty_input()
+ } else {
+ // Pane closed between forward dispatch and reply arrival.
+ return Ok(());
+ };
+ if !buffered.is_empty() {
+ self.process_pty_bytes(pid, buffered)
+ .with_context(err_context)?;
+ }
+ Ok(())
+ }
fn process_pty_bytes(&mut self, pid: u32, bytes: VteBytes) -> Result<()> {
let err_context = || format!("failed to process pty bytes from pid {pid}");
@@ -2735,6 +2816,19 @@ impl Tab {
terminal_output.handle_pty_bytes(bytes);
let messages_to_pty = terminal_output.drain_messages_to_pty();
let forwarded_queries = terminal_output.drain_forwarded_queries();
+ // If at least one forward was produced, the pane stopped
+ // processing its `pending_pty_input` queue at the byte
+ // that produced the forward. Arm the pause so subsequent
+ // PTY bytes accumulate in the same queue rather than
+ // being processed; they will be drained in stream order
+ // when the host reply (or cache-fallback synthesis, or
+ // 500 ms timeout) lands via `resume_pane_after_forward`.
+ // Pause arming is independent of which forward bears the
+ // reply: resume is keyed by pane_id, not by token, so a
+ // single flag suffices for any number of queued forwards.
+ if !forwarded_queries.is_empty() {
+ terminal_output.arm_forward_pause();
+ }
let clipboard_update = terminal_output.drain_clipboard_update();
let desktop_notifications = terminal_output.drain_desktop_notifications();
let osc7_cwd = terminal_output.drain_osc7_cwd();
diff --git a/zellij-server/src/unit/screen_tests.rs b/zellij-server/src/unit/screen_tests.rs
index ef2da903..1638af26 100644
--- a/zellij-server/src/unit/screen_tests.rs
+++ b/zellij-server/src/unit/screen_tests.rs
@@ -9192,3 +9192,266 @@ fn host_theme_no_pty_writes_when_no_panes_subscribed() {
writes
);
}
+
+// =====================================================================
+// Pause-on-forward state machine (pane-level)
+//
+// These tests exercise the per-pane forward-pause flag and the
+// always-buffered PTY-input queue that preserves query/reply ordering
+// when an app interleaves a sync-replied query (DA1, DSR, DECQRM) with
+// a host-forwarded query (OSC 10/11/4, CSI 14t/16t).
+//
+// Single-buffer model:
+// - `handle_pty_bytes` always appends to `pending_pty_input`.
+// - When `forward_paused` is false, processing immediately drains
+// the queue byte-by-byte until either the queue empties or Grid
+// produces a forward-bound query.
+// - Once Tab arms the pause, subsequent calls just append; the
+// queue grows and waits.
+// - On resume, Tab clears the pause and calls handle_pty_bytes
+// with an empty slice; that triggers a fresh process pass over
+// the queued bytes.
+// =====================================================================
+
+use crate::panes::TerminalPane;
+use crate::tab::Pane;
+use zellij_utils::pane_size::PaneGeom;
+
+fn new_terminal_pane_for_pause_test(pid: u32) -> TerminalPane {
+ let mut geom = PaneGeom::default();
+ geom.cols.set_inner(20);
+ geom.rows.set_inner(10);
+ TerminalPane::new(
+ pid,
+ geom,
+ Style::default(),
+ 0,
+ String::new(),
+ Rc::new(RefCell::new(LinkHandler::new())),
+ Rc::new(RefCell::new(Some(SizeInPixels {
+ width: 8,
+ height: 16,
+ }))),
+ Rc::new(RefCell::new(SixelImageStore::default())),
+ Rc::new(RefCell::new(Palette::default())),
+ Rc::new(RefCell::new(HashMap::new())),
+ None,
+ None,
+ false,
+ true,
+ true,
+ true,
+ false,
+ None,
+ )
+}
+
+#[test]
+fn pane_buffers_pty_bytes_while_forward_paused() {
+ let mut pane = new_terminal_pane_for_pause_test(1);
+ pane.arm_forward_pause();
+ assert!(pane.is_forward_paused());
+
+ pane.handle_pty_bytes(b"hello".to_vec());
+ pane.handle_pty_bytes(b"world".to_vec());
+
+ let drained = pane.drain_pending_pty_input();
+ assert_eq!(
+ drained,
+ b"helloworld".to_vec(),
+ "while paused, every byte must accumulate in pending_pty_input \
+ instead of being fed to vte"
+ );
+ assert!(
+ pane.drain_pending_pty_input().is_empty(),
+ "drain must clear the buffer"
+ );
+}
+
+#[test]
+fn pane_forward_in_vte_stops_processing_with_remainder_queued() {
+ // App sends `OSC 10;? + after`. When vte's OSC dispatch runs and
+ // Grid pushes the forward query, processing must stop, leaving
+ // `after` in the queue. Those bytes will be replayed AFTER the
+ // host reply has been written.
+ let mut pane = new_terminal_pane_for_pause_test(1);
+ let mut input = b"\x1b]10;?\x07".to_vec();
+ input.extend_from_slice(b"after");
+ pane.handle_pty_bytes(input);
+
+ let queries = pane.drain_forwarded_queries();
+ assert_eq!(queries.len(), 1, "exactly one forward must be queued");
+ assert_eq!(
+ queries[0],
+ crate::host_query::HostQuery::DefaultForeground {
+ terminator: crate::host_query::OscTerminator::Bel,
+ }
+ );
+
+ let buffered = pane.drain_pending_pty_input();
+ assert_eq!(
+ buffered,
+ b"after".to_vec(),
+ "bytes after the forward must remain queued, not rendered"
+ );
+}
+
+#[test]
+fn pane_no_forward_drains_queue_empty() {
+ // When the input contains no forward-bound query, processing runs
+ // to completion and `pending_pty_input` ends empty.
+ let mut pane = new_terminal_pane_for_pause_test(1);
+ pane.handle_pty_bytes(b"plain text".to_vec());
+
+ assert!(
+ pane.drain_forwarded_queries().is_empty(),
+ "no forward should have been produced"
+ );
+ assert!(
+ pane.drain_pending_pty_input().is_empty(),
+ "no forward → queue fully drained by processing"
+ );
+}
+
+#[test]
+fn pane_clear_forward_pause_reports_prior_state() {
+ let mut pane = new_terminal_pane_for_pause_test(1);
+ assert!(!pane.clear_forward_pause(), "not previously paused");
+ pane.arm_forward_pause();
+ assert!(pane.clear_forward_pause(), "was paused → returns true");
+ assert!(
+ !pane.is_forward_paused(),
+ "after clearing, the pane must read as un-paused"
+ );
+}
+
+#[test]
+fn pane_paused_resumes_to_drain_queue() {
+ // Simulate the resume cycle Tab runs:
+ // 1. arm pause, app sends bytes (they accumulate)
+ // 2. clear pause, drain queue, re-feed through handle_pty_bytes
+ // The DA1 query buffered during step 1 must produce its sync
+ // reply during step 2.
+ let mut pane = new_terminal_pane_for_pause_test(1);
+ pane.arm_forward_pause();
+ pane.handle_pty_bytes(b"buffered\x1b[c".to_vec());
+
+ // While paused, vte was never fed, so no replies were produced.
+ assert!(
+ pane.drain_forwarded_queries().is_empty(),
+ "vte was not fed → no forwards produced"
+ );
+ assert!(
+ pane.drain_messages_to_pty().is_empty(),
+ "vte was not fed → no sync replies produced"
+ );
+
+ let was_paused = pane.clear_forward_pause();
+ assert!(was_paused, "was paused");
+ let buffered = pane.drain_pending_pty_input();
+ pane.handle_pty_bytes(buffered);
+
+ let sync_replies = pane.drain_messages_to_pty();
+ assert!(
+ !sync_replies.is_empty(),
+ "after resume, queue is processed and Grid emits the DA1 reply"
+ );
+ assert!(
+ pane.drain_pending_pty_input().is_empty(),
+ "queue must be fully drained when no forward is in the stream"
+ );
+}
+
+// =====================================================================
+// End-to-end ordering through Screen+Tab integration
+//
+// These tests construct a real Screen with a real Tab and TerminalPane,
+// drive PTY bytes in, and then exercise handle_forwarded_reply_from_host
+// to assert the resulting PTY-write order on the captured channel.
+// =====================================================================
+
+#[test]
+fn forwarded_reply_routes_through_tab_for_unpaused_pane() {
+ // When a pane in a Tab receives a forward reply via
+ // handle_forwarded_reply_from_host, the bytes must flow through
+ // resume_pane_after_forward → Tab → write_to_pane_id_without_preprocessing
+ // → PtyWriteInstruction::Write. The channel capture proves the
+ // bytes reached the PTY writer with the right terminal id.
+ let size = Size { cols: 80, rows: 20 };
+ let (mut screen, capture) = create_new_screen_with_forward_capture(size);
+ let pane_id = PaneId::Terminal(7);
+ let token = screen.forward_host_query(pane_id, bg_query());
+ let _ = capture.drain_forward_queries();
+
+ // No tab exists for this pane; the fallback path delivers the
+ // bytes directly to the PTY writer. This still proves the
+ // routing and stale-token guard interact correctly.
+ let reply = b"\x1b]11;rgb:1111/2222/3333\x1b\\".to_vec();
+ screen
+ .handle_forwarded_reply_from_host(token, reply.clone())
+ .expect("ok");
+
+ let writes = capture.drain_pty_writes();
+ assert_eq!(writes.len(), 1);
+ assert_eq!(writes[0], (reply, 7));
+}
+
+#[test]
+fn paused_pane_with_da1_in_queue_emits_da1_after_resume() {
+ // Simulates the user-reported ordering bug: app sends
+ // `OSC 10;? + CSI c`. The OSC 10 forward must be dispatched
+ // first, then the DA1 reply emitted only after the resume kicks
+ // processing of the queued `\x1b[c`.
+ let mut pane = new_terminal_pane_for_pause_test(1);
+ let mut input = b"\x1b]10;?\x07".to_vec();
+ input.extend_from_slice(b"\x1b[c");
+ pane.handle_pty_bytes(input);
+
+ // Forward emitted; DA1 still queued behind it.
+ let queries = pane.drain_forwarded_queries();
+ assert_eq!(queries.len(), 1, "OSC 10 forward emitted first");
+ assert!(
+ pane.drain_messages_to_pty().is_empty(),
+ "DA1 reply must NOT be emitted yet — it is queued behind the forward"
+ );
+
+ // Tab arms pause, dispatches forward, eventually receives reply
+ // and resumes. Resume = clear pause + drain queue + re-feed.
+ pane.arm_forward_pause();
+ // (host reply gets written to PTY via Tab; modelled here as no-op)
+ pane.clear_forward_pause();
+ let buffered = pane.drain_pending_pty_input();
+ pane.handle_pty_bytes(buffered);
+
+ let sync_replies = pane.drain_messages_to_pty();
+ assert!(
+ !sync_replies.is_empty(),
+ "after resume, the queued CSI c is processed and Grid emits DA1"
+ );
+}
+
+#[test]
+fn empty_reply_with_paused_pane_drains_buffer_without_phantom_write() {
+ // A pane that was paused on a ColorPaletteMode query while
+ // host_terminal_theme_mode is unknown must still get unblocked,
+ // but the spec requires NO bytes be written. The Tab-level
+ // contract: a resume call with an empty payload skips the PTY
+ // write yet still clears the pause and re-feeds the queue.
+ let mut pane = new_terminal_pane_for_pause_test(1);
+ pane.arm_forward_pause();
+ pane.handle_pty_bytes(b"after".to_vec());
+ assert!(pane.is_forward_paused());
+
+ // Simulate Tab::resume_pane_after_forward with empty reply:
+ // - clear pause
+ // - drain queue + re-feed
+ let was_paused = pane.clear_forward_pause();
+ assert!(was_paused);
+ let buffered = pane.drain_pending_pty_input();
+ pane.handle_pty_bytes(buffered);
+ assert!(!pane.is_forward_paused());
+ assert!(
+ pane.drain_pending_pty_input().is_empty(),
+ "queue fully consumed by post-resume processing"
+ );
+}
diff --git a/zellij-utils/src/errors.rs b/zellij-utils/src/errors.rs
index 484b4dfb..6aacabb7 100644
--- a/zellij-utils/src/errors.rs
+++ b/zellij-utils/src/errors.rs
@@ -312,6 +312,7 @@ pub enum ScreenContext {
TerminalColorRegisters,
ForwardHostQuery,
ForwardedReplyFromHost,
+ ResumePaneAfterForward,
HostTerminalThemeChanged,
SetDarkTheme,
SetLightTheme,