You are viewing a plain text version of this content. The canonical link for it is here.
Posted to commits@maka.apache.org by wy...@apache.org on 2026/10/14 13:51:16 UTC

(maka) branch rust-preview updated: fix(runtime): keep long conversations responsive without batch timeouts

This is an automated email from the ASF dual-hosted git repository.

M4n5ter pushed a commit to branch rust-preview
in repository https://gitbox.apache.org/repos/asf/maka.git


The following commit(s) were added to refs/heads/rust-preview by this push:
     new 8f948c60ba fix(runtime): keep long conversations responsive without batch timeouts
8f948c60ba is described below

commit 8f948c60bafb061c8d440aff7ac8b22497d16619
Author: Wang <m4...@gmail.com>
AuthorDate: Wed Oct 14 21:50:56 2026 +0800

    fix(runtime): keep long conversations responsive without batch timeouts
    
    Reuse native reading views and keep wheel input responsive over large histories. Remove fixed concurrent query limits and the composed UI update deadline while retaining per-callback execution guards and cooperative scheduling.
    
    Validate with runtime and terminal suites, a 320-query transport burst, and real PTY large-history scrolling and consecutive sends.
    
    Generated-by: OpenAI Codex
---
 .../tests/application_services/resource_ingress.rs |  27 +--
 platform/host-runtime/src/application.rs           |  30 +--
 platform/host-runtime/src/application/owner.rs     |  22 +-
 .../host-runtime/src/application/owner/tests.rs    |   1 -
 .../src/application/resource_ingress.rs            |  23 +-
 .../src/application/transport/server.rs            |  22 +-
 .../render-terminal/src/application/reading.rs     |  35 +++
 platform/render-terminal/src/application/run.rs    |  19 +-
 platform/render-terminal/src/application/scroll.rs |  14 +-
 platform/render-terminal/src/application/source.rs |  70 ++++--
 .../src/application/tests/layout.rs                |  35 +++
 .../src/application/tests/reading.rs               |  52 +++++
 .../src/application/tests/reading/markdown.rs      |  79 +++++++
 platform/transport/src/transport/native.rs         |  29 +--
 platform/transport/tests/private.rs                | 106 ++++++---
 platform/ui-js/tests/runtime.rs                    |   8 +-
 platform/ui-js/tests/runtime/events.rs             |  16 +-
 platform/ui-js/tests/runtime/native.rs             | 105 +++++++++
 platform/ui-runtime/src/actions.rs                 |   2 +-
 platform/ui-runtime/src/lib.rs                     |   9 +-
 platform/ui-runtime/src/native.rs                  |   5 +-
 platform/ui-runtime/src/tree.rs                    |  63 ++---
 .../terminal/bundled_product/chat/performance.rs   | 257 +++++++++++++++++++++
 23 files changed, 800 insertions(+), 229 deletions(-)

diff --git a/platform/host-js/tests/application_services/resource_ingress.rs b/platform/host-js/tests/application_services/resource_ingress.rs
index 49a1689d58..a15de02f32 100644
--- a/platform/host-js/tests/application_services/resource_ingress.rs
+++ b/platform/host-js/tests/application_services/resource_ingress.rs
@@ -170,25 +170,13 @@ fn observation(value: Value) -> Value {
 }
 
 #[tokio::test]
-async fn zero_byte_receptions_use_original_slots_and_transfer_without_double_charging() {
+async fn many_empty_resource_receptions_keep_scope_ownership_through_execution() {
     tokio::time::timeout(Duration::from_secs(15), async {
         let f = Fixture::new(MethodMode::Query).await;
         let mut pending = Vec::new();
-        for _ in 0..128 {
+        for _ in 0..320 {
             pending.push(f.capture(0, json!(null), ResourceEncoding::Bytes));
         }
-        let denied = scope(&f.issuer, true);
-        assert!(
-            f.client
-                .capture_resources(
-                    denied.clone(),
-                    descriptors(0, json!(null), ResourceEncoding::Bytes)
-                )
-                .err()
-                .unwrap()
-                .contains("call capacity")
-        );
-        denied.finish().await.unwrap();
         let (scope, capture) = pending.pop().unwrap();
         let accepted = f
             .client
@@ -202,15 +190,8 @@ async fn zero_byte_receptions_use_original_slots_and_transfer_without_double_cha
             .await
             .unwrap();
         permit(&f.started).await;
-        let extra = super::scope(&f.issuer, true);
-        assert!(
-            f.client
-                .capture_resources(
-                    extra.clone(),
-                    descriptors(0, json!(null), ResourceEncoding::Bytes)
-                )
-                .is_err()
-        );
+        let (extra, capture) = f.capture(0, json!(null), ResourceEncoding::Bytes);
+        drop(capture);
         extra.finish().await.unwrap();
         drop(accepted);
         f.release.add_permits(1);
diff --git a/platform/host-runtime/src/application.rs b/platform/host-runtime/src/application.rs
index ba942af428..b69ca4b762 100644
--- a/platform/host-runtime/src/application.rs
+++ b/platform/host-runtime/src/application.rs
@@ -335,7 +335,6 @@ struct PreparedInvocation {
     scope: Scope,
     attachments: Attachments,
     capture: Option<Uuid>,
-    slot: OwnedSemaphorePermit,
     bytes: OwnedSemaphorePermit,
     resources: OwnedSemaphorePermit,
     // Last: inert drop releases physical custody before acknowledging its Scope.
@@ -452,8 +451,7 @@ pub struct Client {
 }
 
 struct Dispatch {
-    commands: mpsc::Sender<Command>,
-    slots: Arc<Semaphore>,
+    commands: mpsc::UnboundedSender<Command>,
     bytes: Arc<Semaphore>,
     resources: Arc<Semaphore>,
     stream_buffers: Arc<Semaphore>,
@@ -480,7 +478,6 @@ pub(super) enum Command {
         scope: Scope,
         parent: Option<Ticket>,
         reply: oneshot::Sender<Result<Option<OperationObservation>>>,
-        _slot: OwnedSemaphorePermit,
         _bytes: OwnedSemaphorePermit,
     },
 }
@@ -492,7 +489,6 @@ pub(super) struct Call {
     scope: Scope,
     attachments: Attachments,
     capture: Option<Uuid>,
-    slot: OwnedSemaphorePermit,
     bytes: OwnedSemaphorePermit,
     resources: OwnedSemaphorePermit,
     parent: Option<Ticket>,
@@ -766,7 +762,7 @@ impl Application {
             None => prepare(&input, packages, &native, persisted.is_some())?,
         };
         let scheduler = tokio::runtime::Handle::try_current().map_err(|e| e.to_string())?;
-        let (commands, receiver) = mpsc::channel(128);
+        let (commands, receiver) = mpsc::unbounded_channel();
         let (control, controls) = mpsc::channel(16);
         let (adoptions, adoption_requests) = mpsc::channel(16);
         let (updates, observations) = watch::channel(Snapshot {
@@ -776,7 +772,6 @@ impl Application {
         let stop = CancellationToken::new();
         let dispatch = Arc::new(Dispatch {
             commands,
-            slots: Arc::new(Semaphore::new(128)),
             bytes: Arc::new(Semaphore::new(32 * 1024 * 1024)),
             resources: Arc::new(Semaphore::new(64 * 1024 * 1024)),
             stream_buffers: Arc::new(Semaphore::new(16)),
@@ -832,7 +827,6 @@ impl Application {
             .dispatch
             .commands
             .send(Command::ShutdownIdle { reply })
-            .await
             .map_err(|_| "Host owner disappeared before idle retirement".to_string())?;
         if !receive
             .await
@@ -920,7 +914,7 @@ impl Client {
         let (reply, result) = oneshot::channel();
         self.dispatch
             .commands
-            .try_send(Command::Bind {
+            .send(Command::Bind {
                 consumer,
                 import,
                 reply,
@@ -940,7 +934,7 @@ impl Client {
         let (reply, result) = oneshot::channel();
         self.dispatch
             .commands
-            .try_send(Command::CaptureImport {
+            .send(Command::CaptureImport {
                 consumer,
                 import,
                 reply,
@@ -1096,7 +1090,6 @@ impl Client {
             scope,
             attachments,
             capture,
-            slot,
             bytes,
             resources,
             parent,
@@ -1104,7 +1097,7 @@ impl Client {
         let (reply, result) = oneshot::channel();
         self.dispatch
             .commands
-            .try_send(Command::Call(Box::new(Call {
+            .send(Command::Call(Box::new(Call {
                 parent,
                 kind: CallKind::Mutation {
                     operation: reference.operation,
@@ -1117,7 +1110,6 @@ impl Client {
                 scope,
                 attachments,
                 capture,
-                slot,
                 bytes,
                 resources,
             })))
@@ -1211,7 +1203,6 @@ impl Dispatch {
         }
         let resource_ingress::Reserved {
             attachments,
-            slot,
             bytes,
             resources,
             parent,
@@ -1219,7 +1210,7 @@ impl Dispatch {
         } = self.resources(custody.0, &scope, size, custody.1)?;
         let capture = (kind.operation().is_some() && !attachments.is_empty()).then(Uuid::new_v4);
         self.commands
-            .try_send(Command::Call(Box::new(Call {
+            .send(Command::Call(Box::new(Call {
                 parent,
                 kind,
                 binding,
@@ -1228,7 +1219,6 @@ impl Dispatch {
                 scope,
                 attachments,
                 capture,
-                slot,
                 bytes,
                 resources,
             })))
@@ -1243,11 +1233,6 @@ impl Dispatch {
         parent: Option<Ticket>,
     ) -> Result<oneshot::Receiver<Result<Option<OperationObservation>>>> {
         let size = check_reference(&reference)?;
-        let slot = self
-            .slots
-            .clone()
-            .try_acquire_owned()
-            .map_err(|_| "Host recovery capacity exhausted")?;
         let bytes = self
             .bytes
             .clone()
@@ -1255,13 +1240,12 @@ impl Dispatch {
             .map_err(|_| "Host recovery budget exhausted")?;
         let (reply, result) = oneshot::channel();
         self.commands
-            .try_send(Command::Recover {
+            .send(Command::Recover {
                 consumer,
                 reference: Box::new(reference),
                 scope,
                 parent,
                 reply,
-                _slot: slot,
                 _bytes: bytes,
             })
             .map_err(|e| e.to_string())?;
diff --git a/platform/host-runtime/src/application/owner.rs b/platform/host-runtime/src/application/owner.rs
index ceaad50945..7716087760 100644
--- a/platform/host-runtime/src/application/owner.rs
+++ b/platform/host-runtime/src/application/owner.rs
@@ -47,7 +47,6 @@ fn next_change(
 struct Failed {
     _execution: Execution<Service>,
     _scope: Scope,
-    _slot: OwnedSemaphorePermit,
     _bytes: OwnedSemaphorePermit,
     _attachments: Attachments,
     _resources: OwnedSemaphorePermit,
@@ -88,7 +87,6 @@ enum Done {
         cleanup: Result<()>,
         receipt: Option<Box<Result<OperationObservation>>>,
         reply: Reply,
-        _slot: OwnedSemaphorePermit,
         _bytes: OwnedSemaphorePermit,
         attachments: Attachments,
         _resources: OwnedSemaphorePermit,
@@ -102,7 +100,6 @@ enum Done {
         parent: Option<Ticket>,
         result: Box<Result<Option<OperationObservation>>>,
         reply: oneshot::Sender<Result<Option<OperationObservation>>>,
-        _slot: OwnedSemaphorePermit,
         _bytes: OwnedSemaphorePermit,
     },
     Closed {
@@ -200,7 +197,7 @@ impl Owner {
     }
     pub async fn run(
         mut self,
-        mut commands: mpsc::Receiver<Command>,
+        mut commands: mpsc::UnboundedReceiver<Command>,
         mut control: mpsc::Receiver<Retirement>,
         mut adoptions: mpsc::Receiver<Adoption>,
         stop: CancellationToken,
@@ -1028,7 +1025,6 @@ impl Owner {
                     scope,
                     attachments,
                     capture,
-                    slot,
                     bytes,
                     resources,
                 } = *call;
@@ -1207,7 +1203,7 @@ impl Owner {
                 match admission {
                     Err(error) => {
                         drop(kind.take_confirmation());
-                        drop((attachments, resources, slot, bytes, input, scope));
+                        drop((attachments, resources, bytes, input, scope));
                         if let Some(ticket) = parent.take() {
                             ticket.complete(if descriptor_failed {
                                 Err(error.clone())
@@ -1228,7 +1224,6 @@ impl Owner {
                                     scope,
                                     attachments,
                                     capture,
-                                    slot,
                                     bytes,
                                     resources,
                                     parent,
@@ -1262,7 +1257,6 @@ impl Owner {
                                 scope,
                                 attachments,
                                 capture,
-                                slot,
                                 bytes,
                                 resources,
                             });
@@ -1359,7 +1353,7 @@ impl Owner {
                                 receipt=Some(Err("operation receipt unavailable; read original reference".into()));
                             }
                             Done::Called { parent, execution, result, historical, consumer, caller: Box::new(caller),
-                                scope: Box::new(scope), cleanup, receipt: receipt.map(Box::new), reply: output, _slot: slot, _bytes: bytes, attachments, _resources: resources, confirmation }
+                                scope: Box::new(scope), cleanup, receipt: receipt.map(Box::new), reply: output, _bytes: bytes, attachments, _resources: resources, confirmation }
                         }));
                     }
                 }
@@ -1370,7 +1364,6 @@ impl Owner {
                 scope,
                 mut parent,
                 reply,
-                _slot,
                 _bytes,
             } => {
                 let admission = self
@@ -1409,7 +1402,6 @@ impl Owner {
                                 parent,
                                 result: Box::new(result),
                                 reply,
-                                _slot,
                                 _bytes,
                             }
                         }));
@@ -1499,13 +1491,12 @@ impl Owner {
                         kind,
                         attachments,
                         resources,
-                        slot,
                         bytes,
                         input,
                         scope,
                         ..
                     } = *call;
-                    drop((attachments, resources, slot, bytes, input, scope));
+                    drop((attachments, resources, bytes, input, scope));
                     if let Some(ticket) = parent {
                         ticket.complete(Ok(()));
                     }
@@ -1566,7 +1557,6 @@ impl Owner {
                 cleanup,
                 mut receipt,
                 reply,
-                _slot,
                 _bytes,
                 attachments,
                 _resources,
@@ -1590,7 +1580,6 @@ impl Owner {
                     self.failed.push(Failed {
                         _execution: execution,
                         _scope: *scope,
-                        _slot,
                         _bytes,
                         _attachments: attachments,
                         _resources,
@@ -1599,7 +1588,7 @@ impl Owner {
                 } else {
                     // Confirmed physical cleanup releases caller custody before waking
                     // an observer that may immediately reopen the caller Root.
-                    drop((confirmation, attachments, _resources, _slot, _bytes, scope));
+                    drop((confirmation, attachments, _resources, _bytes, scope));
                 }
                 if let Some(ticket) = parent {
                     ticket.complete(cleanup.clone());
@@ -1614,7 +1603,6 @@ impl Owner {
                 parent,
                 result,
                 reply,
-                _slot,
                 _bytes,
             } => {
                 let result = self
diff --git a/platform/host-runtime/src/application/owner/tests.rs b/platform/host-runtime/src/application/owner/tests.rs
index 77b4648f88..8cfdf7f810 100644
--- a/platform/host-runtime/src/application/owner/tests.rs
+++ b/platform/host-runtime/src/application/owner/tests.rs
@@ -303,7 +303,6 @@ async fn final_admission_rejects_failed_consumer_before_terminal_notification_is
             resources: Arc::new(Semaphore::new(0))
                 .try_acquire_many_owned(0)
                 .unwrap(),
-            slot: Arc::new(Semaphore::new(1)).try_acquire_owned().unwrap(),
             bytes: Arc::new(Semaphore::new(1)).try_acquire_owned().unwrap(),
         })));
         assert!(
diff --git a/platform/host-runtime/src/application/resource_ingress.rs b/platform/host-runtime/src/application/resource_ingress.rs
index 68cc401770..99acae1583 100644
--- a/platform/host-runtime/src/application/resource_ingress.rs
+++ b/platform/host-runtime/src/application/resource_ingress.rs
@@ -72,7 +72,6 @@ impl CallResources {
 // Physical values precede permits and the inert Scope ticket in drop order.
 pub(super) struct Reserved {
     pub(super) attachments: Attachments,
-    pub(super) slot: OwnedSemaphorePermit,
     pub(super) bytes: OwnedSemaphorePermit,
     pub(super) resources: OwnedSemaphorePermit,
     group: Arc<Resources>,
@@ -87,15 +86,14 @@ struct Receiving {
 /// before confirming server shutdown; Application::shutdown does not own it.
 pub struct ResourceCapture {
     receiving: BTreeMap<String, Receiving>,
-    slot: OwnedSemaphorePermit,
     bytes: OwnedSemaphorePermit,
     resources: OwnedSemaphorePermit,
     scope: Scope,
-    commands: mpsc::Sender<Command>,
+    commands: mpsc::UnboundedSender<Command>,
     parent: Option<Ticket>,
 }
 impl Client {
-    /// Reserve the original call slot, JSON and payload budgets before allocation.
+    /// Reserve the original JSON and payload budgets before allocation.
     /// The trusted ingress must already bound the decoded descriptor envelope.
     /// Original request Scope custody covers partial reception and frozen input.
     pub fn capture_resources(
@@ -152,11 +150,6 @@ impl Dispatch {
         };
         // Ticket first; every subsequent local drop releases physical custody first.
         let parent = scope.resources.reserve().map_err(|e| e.to_string())?;
-        let slot = self
-            .slots
-            .clone()
-            .try_acquire_owned()
-            .map_err(|_| "Host call capacity exhausted")?;
         let bytes = self
             .bytes
             .clone()
@@ -186,7 +179,6 @@ impl Dispatch {
         }
         Ok(ResourceCapture {
             receiving,
-            slot,
             bytes,
             resources,
             scope,
@@ -238,7 +230,6 @@ impl ResourceCapture {
         }
         let Self {
             receiving,
-            slot,
             bytes,
             resources,
             scope,
@@ -257,7 +248,6 @@ impl ResourceCapture {
             .collect();
         Ok(CallResources(ResourceInput::Captured(Box::new(Reserved {
             attachments,
-            slot,
             bytes,
             resources,
             group: scope.resources.clone(),
@@ -360,8 +350,7 @@ impl Dispatch {
     ) -> Result<Reserved> {
         match value.0 {
             ResourceInput::Captured(mut reserved) => {
-                if !Arc::ptr_eq(reserved.slot.semaphore(), &self.slots)
-                    || !Arc::ptr_eq(reserved.bytes.semaphore(), &self.bytes)
+                if !Arc::ptr_eq(reserved.bytes.semaphore(), &self.bytes)
                     || !Arc::ptr_eq(reserved.resources.semaphore(), &self.resources)
                 {
                     return Err("captured resources belong to another Application".into());
@@ -392,11 +381,6 @@ impl Dispatch {
                         return Err(error);
                     }
                 };
-                let slot = self
-                    .slots
-                    .clone()
-                    .try_acquire_owned()
-                    .map_err(|_| "Host call capacity exhausted")?;
                 let bytes = self
                     .bytes
                     .clone()
@@ -410,7 +394,6 @@ impl Dispatch {
                 let (attachments, parent) = custody;
                 Ok(Reserved {
                     attachments,
-                    slot,
                     bytes,
                     resources,
                     group: scope.resources.clone(),
diff --git a/platform/host-runtime/src/application/transport/server.rs b/platform/host-runtime/src/application/transport/server.rs
index 9bb385b25a..57038495da 100644
--- a/platform/host-runtime/src/application/transport/server.rs
+++ b/platform/host-runtime/src/application/transport/server.rs
@@ -35,14 +35,12 @@ use std::{
 };
 use tokio::{
     io::{AsyncRead, AsyncReadExt, AsyncWrite},
-    sync::{OwnedSemaphorePermit, Semaphore, oneshot},
+    sync::oneshot,
 };
 use tokio_util::{sync::CancellationToken, task::TaskTracker};
 
-const CONNECTIONS: u32 = 16;
 struct Failed {
     _scope: Option<Scope>,
-    _permit: OwnedSemaphorePermit,
     reason: String,
 }
 /// Own this alongside the original Application and SQL Root. Close/drain this
@@ -51,7 +49,6 @@ pub struct Server {
     client: Client,
     policy: PolicyOwner,
     endpoints: Mutex<super::Endpoints>,
-    slots: Arc<Semaphore>,
     stop: CancellationToken,
     tasks: TaskTracker,
     failed: Mutex<Vec<Failed>>,
@@ -69,7 +66,6 @@ impl Server {
             client,
             policy,
             endpoints: Mutex::new(endpoints),
-            slots: Arc::new(Semaphore::new(CONNECTIONS as usize)),
             stop: CancellationToken::new(),
             tasks: TaskTracker::new(),
             failed: Mutex::new(Vec::new()),
@@ -103,8 +99,8 @@ impl Server {
         self.serve_inner(reader, writer, peer, None, false)
     }
     /// An inherited-bootstrap nonce pairs a private current-account channel
-    /// with this original Host incarnation. Hello uses the same capacity and
-    /// tracked connection owner as Open; it never creates request authority.
+    /// with this original Host incarnation. Hello uses the same tracked
+    /// connection owner as Open; it never creates request authority.
     pub fn serve_private<R, W>(
         self: &Arc<Self>,
         reader: R,
@@ -152,11 +148,6 @@ impl Server {
         if *gate {
             return Err("Application transport is closing".into());
         }
-        let permit = self
-            .slots
-            .clone()
-            .try_acquire_owned()
-            .map_err(|_| "Application connection capacity exhausted")?;
         let server = self.clone();
         let (reply, result) = oneshot::channel();
         // Publish actual custody before returning the first-poll observer.
@@ -185,7 +176,7 @@ impl Server {
             .await;
             let scope = session.scope.take();
             // Each generic physical half can fail independently during Drop.
-            // Keep Scope and lease outside both unwind boundaries.
+            // Keep Scope outside both unwind boundaries.
             let Session { reader, writer, .. } = session;
             let read_drop = std::panic::catch_unwind(AssertUnwindSafe(|| drop(reader)));
             let write_drop = std::panic::catch_unwind(AssertUnwindSafe(|| drop(writer)));
@@ -196,11 +187,8 @@ impl Server {
             if let Err(reason) = &cleanup {
                 server.failed.lock().unwrap().push(Failed {
                     _scope: scope,
-                    _permit: permit,
                     reason: reason.clone(),
                 });
-            } else {
-                drop(permit);
             }
             let _ = reply.send(execution.and(cleanup));
         });
@@ -608,7 +596,7 @@ mod tests {
         sync::atomic::{AtomicBool, Ordering},
         task::{Context, Poll, Waker},
     };
-    use tokio::io::DuplexStream;
+    use tokio::{io::DuplexStream, sync::Semaphore};
     struct Gate {
         entered: Semaphore,
         release: AtomicBool,
diff --git a/platform/render-terminal/src/application/reading.rs b/platform/render-terminal/src/application/reading.rs
index c6aa1035cf..8f42f8281f 100644
--- a/platform/render-terminal/src/application/reading.rs
+++ b/platform/render-terminal/src/application/reading.rs
@@ -634,6 +634,41 @@ impl Widget for Reading {
 }
 pub(super) struct Component;
 impl NativeComponent<dyn Widget> for Component {
+    fn start(
+        &self,
+        call: ComponentCall<'_>,
+        previous: Option<&NativeView<dyn Widget>>,
+        values: &maka_ui_runtime::abi::ValueBindings,
+        _: &tokio::runtime::Handle,
+        _: Instant,
+    ) -> maka_ui_runtime::backend::Job<ComponentOutput<NativeView<dyn Widget>>> {
+        if let ComponentCall::Event {
+            state,
+            key: OBSERVED,
+            input,
+            origin: EventOrigin::Raw,
+            ..
+        } = &call
+            && let Some(previous) = previous
+        {
+            // A native viewport observation reports geometry; it cannot change
+            // content or commands. Preserve the exact prepared scene and slots.
+            let revision = state["revision"].as_u64().unwrap() + 1;
+            let mut state = (*state).clone();
+            state["revision"] = json!(revision);
+            return maka_ui_runtime::backend::Job::ready(Ok(Frame {
+                revision,
+                state,
+                surface: None,
+                view: previous.clone(),
+            }
+            .output(vec![Emission {
+                name: "observed".into(),
+                value: (*input).clone(),
+            }])));
+        }
+        maka_ui_runtime::backend::Job::ready(self.call(call, values))
+    }
     fn capture(&self, call: CaptureCall<'_>) -> maka_ui_runtime::Result<CapturePlan> {
         if call.method != "tail" {
             return Err(maka_ui_runtime::Error::Invalid(
diff --git a/platform/render-terminal/src/application/run.rs b/platform/render-terminal/src/application/run.rs
index bc71a7de40..b6d621f23f 100644
--- a/platform/render-terminal/src/application/run.rs
+++ b/platform/render-terminal/src/application/run.rs
@@ -20,7 +20,7 @@
 use super::{PaintedScene, Presenter, registry, sanitize};
 use crate::terminal;
 use crossterm::event::{self, Event, EventStream, KeyCode, KeyEventKind, KeyModifiers};
-use futures_util::{FutureExt, StreamExt};
+use futures_util::StreamExt;
 use serde_json::json;
 use std::time::{Duration, Instant};
 use std::{
@@ -460,12 +460,17 @@ pub fn run(
                 // Keep other gestures for the next presented frame.
                 let until = Instant::now() + Duration::from_millis(8);
                 while scrolling && Instant::now() < until {
-                    let Some(Some(input)) = events
-                        .as_mut()
-                        .expect("initialized terminal")
-                        .next()
-                        .now_or_never()
-                    else {
+                    // The level-triggered tty backend does not drain its parser
+                    // on a zero-time poll. Give EventStream's reader a short
+                    // chance to publish already buffered input before repainting.
+                    let idle = until.min(Instant::now() + Duration::from_millis(1));
+                    let Ok(Some(input)) = scheduler.block_on(async {
+                        tokio::time::timeout_at(
+                            idle.into(),
+                            events.as_mut().expect("initialized terminal").next(),
+                        )
+                        .await
+                    }) else {
                         break;
                     };
                     let input = input.map_err(|e| e.to_string())?;
diff --git a/platform/render-terminal/src/application/scroll.rs b/platform/render-terminal/src/application/scroll.rs
index 35c6913dee..098bdd086c 100644
--- a/platform/render-terminal/src/application/scroll.rs
+++ b/platform/render-terminal/src/application/scroll.rs
@@ -212,19 +212,19 @@ impl SceneState {
         if !state.initialized && policy == ScrollPolicy::FollowEnd {
             offset = end;
         }
-        if let Some(old) = state
-            .presented
-            .as_ref()
-            .filter(|old| old.intent == state.intent)
-        {
-            if policy == ScrollPolicy::FollowEnd && old.at_end() {
+        if let Some(old) = &state.presented {
+            if old.intent == state.intent && policy == ScrollPolicy::FollowEnd && old.at_end() {
                 offset = end;
             } else if matches!(policy, ScrollPolicy::Anchor | ScrollPolicy::FollowEnd)
                 && let Some((key, delta)) = &old.anchor
                 && let Some((_, start, _)) =
                     children.iter().find(|(candidate, _, _)| candidate == key)
             {
-                offset = (i64::from(*start) + *delta).clamp(0, i64::from(end)) as u32;
+                // A history page can prepend rows while a wheel gesture is
+                // awaiting paint. Preserve its movement relative to the last
+                // visible child, rather than reusing an offset in the old page.
+                let movement = i64::from(state.offset) - i64::from(old.offset);
+                offset = (i64::from(*start) + *delta + movement).clamp(0, i64::from(end)) as u32;
             }
         }
         let reading = self
diff --git a/platform/render-terminal/src/application/source.rs b/platform/render-terminal/src/application/source.rs
index 9155764eb7..3fdba31516 100644
--- a/platform/render-terminal/src/application/source.rs
+++ b/platform/render-terminal/src/application/source.rs
@@ -91,12 +91,22 @@ impl Owner {
         doc.markdown = recipe.1.clone();
     }
 }
-type CachedLayout = (u16, super::selection::Layout, (u16, u32));
+struct CachedLayout {
+    width: u16,
+    layout: super::selection::Layout,
+    size: (u16, u32),
+    used: bool,
+}
+#[derive(Default)]
+struct LayoutCache {
+    frame: Option<std::time::Instant>,
+    layouts: Vec<CachedLayout>,
+}
 struct Recipe(
     SourceTextProps,
     Option<Arc<crate::markdown::prepared::Document>>,
     bool,
-    RefCell<Option<CachedLayout>>,
+    RefCell<LayoutCache>,
 );
 fn color(rgba: u32) -> Color {
     Color::Rgb((rgba >> 24) as u8, (rgba >> 16) as u8, (rgba >> 8) as u8)
@@ -204,7 +214,13 @@ impl Widget for Recipe {
         doc.standalone = None;
     }
     fn measure(&self, slots: &Slots<'_>, width: u16) -> maka_ui_runtime::Result<(u16, u32)> {
-        Ok(self.layout(width, &slots.presenter.resources.budget)?.1)
+        Ok(self
+            .layout(
+                width,
+                &slots.presenter.resources.budget,
+                slots.measurements.time(),
+            )?
+            .1)
     }
     fn paint(
         &self,
@@ -232,7 +248,11 @@ impl Widget for Recipe {
         }
         let doc = document.borrow();
         let scope = parent.clone().or_else(|| SelectionScope::active(&document));
-        let (layout, _) = self.layout(area.width, &slots.presenter.resources.budget)?;
+        let (layout, _) = self.layout(
+            area.width,
+            &slots.presenter.resources.budget,
+            slots.measurements.time(),
+        )?;
         let super::selection::Layout::Literal(literal_layout, _) = &layout else {
             unreachable!()
         };
@@ -409,22 +429,35 @@ impl Recipe {
         &self,
         width: u16,
         budget: &maka_ui_runtime::budget::NativeBudget,
+        frame: std::time::Instant,
     ) -> maka_ui_runtime::Result<(super::selection::Layout, (u16, u32))> {
-        if let Some((old_width, layout, size)) = &*self.3.borrow()
-            && *old_width == width
-        {
-            return Ok((layout.clone(), *size));
+        let mut cached = self.3.borrow_mut();
+        if cached.frame != Some(frame) {
+            // Retain the widths used by the preceding paint pass. A scroll bar,
+            // intrinsic sizing and nested wrappers can all probe different widths.
+            // Widths abandoned after resize disappear on the next pass; every
+            // retained row allocation remains charged to the aggregate budget.
+            cached
+                .layouts
+                .retain_mut(|entry| std::mem::replace(&mut entry.used, false));
+            cached.frame = Some(frame);
+        }
+        if let Some(entry) = cached.layouts.iter_mut().find(|entry| entry.width == width) {
+            entry.used = true;
+            return Ok((entry.layout.clone(), entry.size));
         }
-        // One width belongs to this immutable recipe. Source/style replacement
-        // creates another recipe; scrolling and selection share these same rows.
-        self.3.borrow_mut().take();
         let mut layout = match &self.1 {
             Some(document) => super::selection::Layout::markdown(document, width)?,
             None => Layout::literal(&self.0.source, width).into(),
         };
         let size = Self::measured(&layout, width);
         if layout.retain(budget) {
-            *self.3.borrow_mut() = Some((width, layout.clone(), size));
+            cached.layouts.push(CachedLayout {
+                width,
+                layout: layout.clone(),
+                size,
+                used: true,
+            });
         }
         Ok((layout, size))
     }
@@ -479,7 +512,11 @@ impl Recipe {
         if area.width == 0 || area.is_empty() && reveal.is_none() {
             return Ok(());
         }
-        let (layout, _) = self.layout(area.width, &slots.presenter.resources.budget)?;
+        let (layout, _) = self.layout(
+            area.width,
+            &slots.presenter.resources.budget,
+            slots.measurements.time(),
+        )?;
         if let Some(offset) = reveal {
             let row = area.y + layout.cursor(offset, false).0 as i64;
             let visible = area.visible();
@@ -725,7 +762,7 @@ fn prepare_markdown(
         focus_on_pointer: props.focus_on_pointer,
     };
     maka_ui_runtime::PreparedScene::new(
-        Recipe(source, Some(document), props.selectable, RefCell::new(None)),
+        Recipe(source, Some(document), props.selectable, RefCell::default()),
         BTreeMap::new(),
         vec![],
     )?
@@ -775,7 +812,7 @@ fn prepare_diff(
         focus_on_pointer: props.focus_on_pointer,
     };
     maka_ui_runtime::PreparedScene::new(
-        Recipe(source, Some(document), true, RefCell::new(None)),
+        Recipe(source, Some(document), true, RefCell::default()),
         BTreeMap::new(),
         vec![],
     )?
@@ -831,6 +868,7 @@ impl NativeComponent<dyn Widget> for Component {
     fn start(
         &self,
         call: ComponentCall<'_>,
+        _: Option<&NativeView<dyn Widget>>,
         _: &maka_ui_runtime::abi::ValueBindings,
         scheduler: &tokio::runtime::Handle,
         deadline: std::time::Instant,
@@ -878,7 +916,7 @@ fn prepare_source(
         return Err(maka_ui_runtime::Error::Invalid("source byte budget".into()));
     }
     maka_ui_runtime::PreparedScene::new(
-        Recipe(props, None, true, RefCell::new(None)),
+        Recipe(props, None, true, RefCell::default()),
         BTreeMap::new(),
         vec![],
     )?
diff --git a/platform/render-terminal/src/application/tests/layout.rs b/platform/render-terminal/src/application/tests/layout.rs
index a249939d3b..90e5fcfae0 100644
--- a/platform/render-terminal/src/application/tests/layout.rs
+++ b/platform/render-terminal/src/application/tests/layout.rs
@@ -981,6 +981,41 @@ fn anchor_keeps_gap_offset_and_original_child_after_hide_and_prepend() {
     presenter.shutdown_settled().unwrap();
 }
 
+#[test]
+fn history_prepend_preserves_wheel_movement_since_the_last_presented_anchor() {
+    for policy in ["anchor", "follow_end"] {
+        let text = (0..30).map(|n| format!("row {n:02}\n")).collect::<String>();
+        let source = Rc::new(std::cell::RefCell::new(scroll_scene(policy, &text)));
+        let (_runtime, mut presenter) = native(
+            View::ChangingScene(source.clone()),
+            Rc::new(Cell::new(true)),
+        );
+        flushed(&mut presenter, 12, 6);
+        for _ in 0..5 {
+            wheel(&mut presenter, policy == "anchor", 1, 1);
+        }
+        flushed(&mut presenter, 12, 6);
+        let before = scroll_state(&presenter, "body").0;
+        wheel(&mut presenter, false, 1, 1);
+        wheel(&mut presenter, false, 1, 1);
+        source.borrow_mut()["children"][0]["children"]
+            .as_array_mut()
+            .unwrap()
+            .insert(
+                0,
+                json!({"kind":"text","key":"older","text":"older\nolder\nolder","color":0xffffff}),
+            );
+        refresh(&mut presenter);
+        let buffer = flushed(&mut presenter, 12, 6);
+        assert_eq!(scroll_state(&presenter, "body"), (before + 1, before + 1));
+        assert_eq!(buffer[(5, 0)].symbol(), ((before - 2) % 10).to_string());
+        presenter
+            .surface_closed(&presenter.surface(), Ok(()))
+            .unwrap();
+        presenter.shutdown_settled().unwrap();
+    }
+}
+
 fn refresh(presenter: &mut Presenter) {
     let revision = presenter
         .application
diff --git a/platform/render-terminal/src/application/tests/reading.rs b/platform/render-terminal/src/application/tests/reading.rs
index 56692771a7..b5e61d4704 100644
--- a/platform/render-terminal/src/application/tests/reading.rs
+++ b/platform/render-terminal/src/application/tests/reading.rs
@@ -660,6 +660,58 @@ fn real_native_reading_slot_inherits_root_grow_and_receipts_route_through_origin
     close(&mut presenter);
 }
 
+#[test]
+fn native_reading_observations_reuse_the_scene_but_command_updates_replace_it() {
+    let settle = |presenter: &mut Presenter, width, height| {
+        draw(presenter, width, height);
+        presenter.settle().unwrap();
+    };
+    let mut declaration = props(vec![source("text", &"row\n".repeat(100))]);
+    declaration["content"]["layout"] = json!({"grow":1});
+    let props = Rc::new(RefCell::new(declaration));
+    let (_runtime, mut presenter) = layout::native(
+        layout::View::ReadingSlot(props.clone()),
+        Rc::new(Cell::new(true)),
+    );
+    settle(&mut presenter, 30, 12);
+    let reader = presenter
+        .application
+        .child_mount(&presenter.root, "reader")
+        .unwrap()
+        .clone();
+    let recipe = presenter
+        .application
+        .frame(&reader)
+        .unwrap()
+        .view
+        .view
+        .clone();
+    mouse(&mut presenter, MouseEventKind::ScrollDown, 5, 5);
+    settle(&mut presenter, 30, 12);
+    assert!(Rc::ptr_eq(
+        &recipe,
+        &presenter.application.frame(&reader).unwrap().view.view
+    ));
+    assert_eq!(observation(&presenter)["scroll"]["direction"], "down");
+    props.borrow_mut()["command"] = json!({"sequence":1,"target":{"kind":"end"}});
+    let root = presenter.root.clone();
+    let revision = presenter.application.frame(&root).unwrap().revision;
+    presenter
+        .application
+        .dispatch(&root, revision, "back", json!({"kind":"click"}))
+        .unwrap();
+    settle(&mut presenter, 30, 12);
+    assert!(!Rc::ptr_eq(
+        &recipe,
+        &presenter.application.frame(&reader).unwrap().view.view
+    ));
+    assert_eq!(
+        observation(&presenter)["receipt"],
+        json!({"sequence":1,"status":"applied"})
+    );
+    close(&mut presenter);
+}
+
 #[test]
 fn hidden_same_root_retains_pending_command_until_visible_flush() {
     let (_runtime, mut presenter, props) = native(vec![
diff --git a/platform/render-terminal/src/application/tests/reading/markdown.rs b/platform/render-terminal/src/application/tests/reading/markdown.rs
index 6138ff2cb4..6297238734 100644
--- a/platform/render-terminal/src/application/tests/reading/markdown.rs
+++ b/platform/render-terminal/src/application/tests/reading/markdown.rs
@@ -438,3 +438,82 @@ fn keyboard_range_crosses_markdown_decorations_into_clipped_literal_and_back() {
     assert_eq!(copied(&mut presenter).unwrap(), b"c");
     close(&mut presenter);
 }
+
+#[test]
+fn wheel_scrolling_reuses_text_layouts_with_a_scrollbar_and_after_resize() {
+    use super::super::super::selection::Layout;
+    use std::sync::Arc;
+
+    let text = "Short **bold** `code` 中.\n\n".repeat(100);
+    for child in [
+        source("text", &text),
+        markdown("text", &text),
+        diff(&text, json!([])),
+    ] {
+        let key = child["key"].as_str().unwrap().to_owned();
+        // The row probes the available width and then paints the child's
+        // intrinsic width, in addition to the reading area's scrollbar probe.
+        let row = json!({"kind":"stack","key":"message","direction":"row","gap":0,"padding":0,"background":0,"children":[child]});
+        let (_runtime, mut presenter, _) = native(vec![row]);
+        let geometry = |presenter: &Presenter| {
+            let mount = presenter
+                .application
+                .child_mount(&presenter.root, &key)
+                .unwrap();
+            let owner = presenter.resources.owners[&mount.id()]
+                .state
+                .downcast_ref::<super::super::super::source::Owner>()
+                .unwrap();
+            owner
+                .document
+                .borrow()
+                .glyphs
+                .as_ref()
+                .unwrap()
+                .layout
+                .clone()
+        };
+        let shared = |before: &Layout, after: &Layout| match (before, after) {
+            (Layout::Literal(a, _), Layout::Literal(b, _)) => Arc::ptr_eq(a, b),
+            (Layout::Markdown { lines: a, .. }, Layout::Markdown { lines: b, .. }) => {
+                Arc::ptr_eq(a, b)
+            }
+            _ => false,
+        };
+        let budget = presenter.resources.budget.clone();
+        let mut previous = None;
+        for width in [40, 15, 50, 12] {
+            settle(&mut presenter, width, 10);
+            settle(&mut presenter, width, 10);
+            let original = geometry(&presenter);
+            if let Some(before) = previous.take() {
+                assert!(
+                    !shared(&before, &original),
+                    "resize must recompute wrapping"
+                );
+            }
+            let retained = budget.usage();
+            for kind in [
+                MouseEventKind::ScrollDown,
+                MouseEventKind::ScrollDown,
+                MouseEventKind::ScrollUp,
+            ] {
+                mouse(&mut presenter, kind, 5, 5);
+                settle(&mut presenter, width, 10);
+                assert!(
+                    shared(&original, &geometry(&presenter)),
+                    "wheel scrolling must reuse wrapped rows even with a scrollbar"
+                );
+                assert_eq!(
+                    budget.usage(),
+                    retained,
+                    "warm scrolling must not retain more layout storage"
+                );
+            }
+            previous = Some(original);
+        }
+        close(&mut presenter);
+        drop(previous);
+        assert_eq!(budget.usage(), (0, 0, 0));
+    }
+}
diff --git a/platform/transport/src/transport/native.rs b/platform/transport/src/transport/native.rs
index 440cb990b6..98d90eb9df 100644
--- a/platform/transport/src/transport/native.rs
+++ b/platform/transport/src/transport/native.rs
@@ -30,11 +30,14 @@ use maka_plugin_core::{
 use maka_ui_runtime::actions::*;
 use std::{
     panic::AssertUnwindSafe,
-    sync::{Arc, Mutex},
+    sync::{
+        Arc, Mutex,
+        atomic::{AtomicUsize, Ordering},
+    },
 };
 use tokio::{
     io::{AsyncRead, AsyncWrite, ReadHalf, WriteHalf},
-    sync::{Notify, OwnedSemaphorePermit, Semaphore},
+    sync::Notify,
 };
 use tokio_util::sync::CancellationToken;
 
@@ -64,7 +67,6 @@ pub trait Connector: Send + Sync + 'static {
     fn connect(&self, stop: CancellationToken) -> BoxFuture<'static, Result<Stream>>;
 }
 type Invocation = Call<ReadHalf<Stream>, WriteHalf<Stream>>;
-const CONNECTIONS: u32 = 16;
 struct Failures {
     reason: Option<String>,
     custody: Vec<Failed>,
@@ -73,14 +75,13 @@ struct Failed {
     _call: Option<Invocation>,
     _request: Option<ServiceRequest>,
     _recorded: Option<RecordedIntent>,
-    _permit: OwnedSemaphorePermit,
 }
 /// Physical lifecycle custody. This is not a routing, replay or execution map.
 /// Failed original calls remain owned and fenced; historical receipts cannot
 /// settle them. Drain UI accepted tasks before awaiting this connection close.
 pub struct Connection {
     connector: Arc<dyn Connector>,
-    slots: Arc<Semaphore>,
+    active: AtomicUsize,
     stop: CancellationToken,
     closed: Mutex<bool>,
     failed: Mutex<Failures>,
@@ -90,7 +91,7 @@ impl Connection {
     pub fn new(connector: Arc<dyn Connector>) -> Arc<Self> {
         Arc::new(Self {
             connector,
-            slots: Arc::new(Semaphore::new(CONNECTIONS as usize)),
+            active: AtomicUsize::new(0),
             stop: CancellationToken::new(),
             closed: Mutex::new(false),
             failed: Mutex::new(Failures {
@@ -110,11 +111,7 @@ impl Connection {
         if *gate {
             return Err("physical connection is closing".into());
         }
-        let permit = self
-            .slots
-            .clone()
-            .try_acquire_owned()
-            .map_err(|_| "physical connection capacity exhausted")?;
+        self.active.fetch_add(1, Ordering::SeqCst);
         Ok(Arc::new(Session {
             connection: self.clone(),
             selection,
@@ -127,7 +124,6 @@ impl Connection {
                 physical_failure: None,
             }),
             recorded: Mutex::new(None),
-            permit: Some(permit),
         }))
     }
     fn failure(&self, reason: String) {
@@ -145,10 +141,11 @@ impl Connection {
                 let changed = own.changed.notified();
                 tokio::pin!(changed);
                 changed.as_mut().enable();
+                let active = own.active.load(Ordering::SeqCst);
                 if own.failed.lock().unwrap().reason.is_some() {
                     return Err("original physical call cleanup remains unconfirmed".into());
                 }
-                if own.slots.available_permits() == CONNECTIONS as usize {
+                if active == 0 {
                     return Ok(());
                 }
                 changed.await;
@@ -271,7 +268,6 @@ struct Session {
     stop: CancellationToken,
     state: tokio::sync::Mutex<State>,
     recorded: Mutex<Option<RecordedIntent>>,
-    permit: Option<OwnedSemaphorePermit>,
 }
 impl Session {
     async fn begin(&self, state: &mut State) -> Result<()> {
@@ -552,7 +548,7 @@ impl Drop for Session {
             || call.as_ref().is_some_and(|call| !call.cleanup_confirmed());
         if !failed {
             // Destructors own real resources and SQL leases. Complete them
-            // before publishing the final permit; panic keeps the close fence.
+            // before publishing completion; panic keeps the close fence.
             let inputs = std::panic::catch_unwind(AssertUnwindSafe(|| drop(state.request.take())));
             let token = std::panic::catch_unwind(AssertUnwindSafe(|| {
                 drop(self.recorded.get_mut().unwrap().take());
@@ -567,10 +563,9 @@ impl Drop for Session {
                 _call: call,
                 _request: state.request.take(),
                 _recorded: self.recorded.get_mut().unwrap().take(),
-                _permit: self.permit.take().unwrap(),
             });
         }
-        drop(self.permit.take());
+        self.connection.active.fetch_sub(1, Ordering::SeqCst);
         self.connection.changed.notify_waiters();
     }
 }
diff --git a/platform/transport/tests/private.rs b/platform/transport/tests/private.rs
index c84852ef58..d53dd51c6f 100644
--- a/platform/transport/tests/private.rs
+++ b/platform/transport/tests/private.rs
@@ -543,6 +543,56 @@ async fn native_ui(
     .unwrap();
     (ui, connection, source, business)
 }
+#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
+async fn burst_of_native_queries_completes_without_manual_retry() {
+    let f = Fixture::with_gate(Some(Arc::new(Gate::default()))).await;
+    let (mut ui, connection, source, service) = native_ui(
+        &f,
+        Arc::new(Physical {
+            server: f.server.clone(),
+            peer: f.peer.clone(),
+        }),
+    )
+    .await;
+    let root = ui.mount_launch(serde_json::json!({})).unwrap();
+    ui.wait_idle().await.unwrap();
+    assert_eq!(
+        ui_action(&mut ui, &root, "read").await["status"],
+        "succeeded"
+    );
+    let source = source.lock().unwrap().take().unwrap();
+    let calls = (0..320)
+        .map(|_| {
+            service.call(maka_ui_runtime::actions::ServiceRequest {
+                source: source.clone(),
+                method: "read".into(),
+                input: serde_json::Value::Null,
+                resources: Default::default(),
+            })
+        })
+        .collect::<Vec<_>>();
+    let results = tokio::time::timeout(
+        std::time::Duration::from_secs(10),
+        futures_util::future::join_all(calls),
+    )
+    .await
+    .unwrap();
+    let mut failures = Vec::new();
+    for result in results {
+        if let Err(reason) = result.result {
+            failures.push(reason);
+        }
+        assert!(result.cleanup.is_ok());
+    }
+    stop_ui(ui, &root).await;
+    connection.close().await.unwrap();
+    drop(service);
+    drop(connection);
+    f.server.close().await.unwrap();
+    f.cleanup().await;
+    assert!(failures.is_empty(), "read burst failed: {failures:?}");
+}
+
 async fn ui_action(
     ui: &mut maka_ui_runtime::Application,
     root: &maka_plugin_core::runtime::Mount,
@@ -993,7 +1043,7 @@ impl maka_transport::transport::native::Connector for Connecting {
 async fn connection_close_cancels_the_same_pending_native_connector_before_any_host_dispatch() {
     let f = Fixture::new().await;
     let entered = Arc::new(tokio::sync::Notify::new());
-    let (mut ui, connection, _, service) = native_ui(
+    let (mut ui, connection, source, service) = native_ui(
         &f,
         Arc::new(Connecting {
             entered: entered.clone(),
@@ -1018,13 +1068,30 @@ async fn connection_close_cancels_the_same_pending_native_connector_before_any_h
     tokio::time::timeout(std::time::Duration::from_secs(5), entered.notified())
         .await
         .unwrap();
-    let close = connection.close();
-    let (completion, cleanup) = tokio::time::timeout(std::time::Duration::from_secs(5), async {
-        tokio::join!(original, close)
-    })
-    .await
-    .unwrap();
+    let source = source.lock().unwrap().take().unwrap();
+    let pending = (0..32)
+        .map(|_| {
+            service.call(maka_ui_runtime::actions::ServiceRequest {
+                source: source.clone(),
+                method: "read".into(),
+                input: serde_json::Value::Null,
+                resources: Default::default(),
+            })
+        })
+        .collect::<Vec<_>>();
+    let mut close = connection.close();
+    assert!(futures_util::poll!(&mut close).is_pending());
+    let (completion, cleanup, pending) =
+        tokio::time::timeout(std::time::Duration::from_secs(5), async {
+            tokio::join!(original, close, futures_util::future::join_all(pending))
+        })
+        .await
+        .unwrap();
     cleanup.unwrap();
+    for result in pending {
+        assert!(result.result.is_err());
+        assert!(result.cleanup.is_ok());
+    }
     ui.finish_task(id, completion.unwrap()).unwrap();
     stop_ui(ui, &root).await;
     drop(service);
@@ -1543,7 +1610,7 @@ async fn lost_close_before_dispatch_poll_keeps_the_actual_confirmed_sql_token()
 }
 
 #[tokio::test(flavor = "multi_thread", worker_threads = 2)]
-async fn private_hello_uses_original_capacity_and_close_cancels_partial_handshakes() {
+async fn private_hello_accepts_bursts_and_close_cancels_partial_handshakes() {
     use tokio::io::{AsyncReadExt, AsyncWriteExt};
     let f = Fixture::new().await;
     let nonce = Uuid::new_v4();
@@ -1554,7 +1621,7 @@ async fn private_hello_uses_original_capacity_and_close_cancels_partial_handshak
     let mut listener = maka_host_runtime::ipc::LocalListener::bind(&path).unwrap();
     let mut clients = Vec::new();
     let mut observers = Vec::new();
-    for _ in 0..16 {
+    for _ in 0..48 {
         let mut client = maka_host_runtime::ipc::connect(&path).await.unwrap();
         let accepted = listener.accept().await.unwrap();
         let (reader, writer) = tokio::io::split(accepted);
@@ -1567,26 +1634,7 @@ async fn private_hello_uses_original_capacity_and_close_cancels_partial_handshak
         client.write_all(&[0]).await.unwrap();
         clients.push(client);
     }
-    let extra = maka_host_runtime::ipc::connect(&path).await.unwrap();
-    let accepted = listener.accept().await.unwrap();
-    let (reader, writer) = tokio::io::split(accepted);
-    assert!(
-        f.server
-            .serve_private(reader, writer, f.peer.clone(), nonce)
-            .err()
-            .unwrap()
-            .contains("capacity")
-    );
-    drop(extra);
-    drop(clients.remove(0));
-    assert!(
-        tokio::time::timeout(std::time::Duration::from_secs(2), observers.remove(0))
-            .await
-            .unwrap()
-            .is_err()
-    );
-    // The released original wire lease admits another connection. A foreign
-    // nonce fails before Scope and releases its same owner, without an Open.
+    // A foreign nonce still fails before Scope admission and without an Open.
     let mut foreign = maka_host_runtime::ipc::connect(&path).await.unwrap();
     let accepted = listener.accept().await.unwrap();
     let (reader, writer) = tokio::io::split(accepted);
diff --git a/platform/ui-js/tests/runtime.rs b/platform/ui-js/tests/runtime.rs
index f246d209d8..258c2d80d2 100644
--- a/platform/ui-js/tests/runtime.rs
+++ b/platform/ui-js/tests/runtime.rs
@@ -326,7 +326,7 @@ fn invalid_child_props_do_not_publish_parent_or_prior_sibling_updates() {
 }
 
 #[test]
-fn sibling_callbacks_share_one_deadline_and_cannot_each_buy_a_new_slice() {
+fn sibling_callbacks_each_receive_their_execution_slice() {
     let timer = timer();
     let mut app = composed(
         "const end=Date.now()+125;while(Date.now()<end){}return frame({...state,label:props.label,revision:state.revision+1});",
@@ -336,11 +336,11 @@ fn sibling_callbacks_share_one_deadline_and_cannot_each_buy_a_new_slice() {
     let root = app.mount_launch(json!({})).unwrap();
     let left = app.child_mount(&root, "left").unwrap().clone();
     let right = app.child_mount(&root, "right").unwrap().clone();
-    assert!(app.dispatch(&root, 0, "parent", Value::Null).is_err());
+    app.dispatch(&root, 0, "parent", Value::Null).unwrap();
     for mount in [&root, &left, &right] {
-        assert_eq!(app.frame(mount).unwrap().revision, 0);
+        assert_eq!(app.frame(mount).unwrap().revision, 1);
     }
-    assert!(app.is_retiring(&right));
+    assert!(!app.is_retiring(&right));
     close_all(&mut app, &root);
 }
 
diff --git a/platform/ui-js/tests/runtime/events.rs b/platform/ui-js/tests/runtime/events.rs
index bf3fb68352..5db090ff3b 100644
--- a/platform/ui-js/tests/runtime/events.rs
+++ b/platform/ui-js/tests/runtime/events.rs
@@ -238,7 +238,7 @@ fn parent_event_sibling_failure_rolls_back_emitter_and_prior_parent_transitions(
 }
 
 #[test]
-fn child_parent_feedback_deadline_rolls_back() {
+fn child_parent_feedback_remains_cancellable_without_partial_publication() {
     let timer = timer();
     let (input, packages, _) = fixture(
         MOUNT,
@@ -250,14 +250,16 @@ fn child_parent_feedback_deadline_rolls_back() {
     let mut app = application(&input, packages, &timer);
     let root = app.mount_launch(json!({})).unwrap();
     let left = app.child_mount(&root, "left").unwrap().clone();
-    let error = app
-        .dispatch(&left, 0, "inc", Value::Null)
-        .unwrap_err()
-        .to_string();
+    maka_ui_runtime::Application::dispatch(&mut app, &left, 0, "inc", Value::Null).unwrap();
     assert!(
-        error.contains("deadline") || error.contains("synchronous budget exceeded"),
-        "{error}"
+        timer
+            .block_on(async {
+                tokio::time::timeout(std::time::Duration::from_millis(100), app.wait_idle()).await
+            })
+            .is_err()
     );
+    app.retire(&root).unwrap();
+    assert!(timer.block_on(app.wait_idle()).is_err());
     assert_eq!(app.frame(&root).unwrap().revision, 0);
     assert_eq!(app.frame(&left).unwrap().revision, 0);
     close_all(&mut app, &root);
diff --git a/platform/ui-js/tests/runtime/native.rs b/platform/ui-js/tests/runtime/native.rs
index 968d8f3da4..2380a81677 100644
--- a/platform/ui-js/tests/runtime/native.rs
+++ b/platform/ui-js/tests/runtime/native.rs
@@ -36,6 +36,25 @@ struct Counter {
     calls: Rc<Cell<usize>>,
 }
 impl NativeComponent<String> for Counter {
+    fn start(
+        &self,
+        call: ComponentCall<'_>,
+        previous: Option<&NativeView<String>>,
+        values: &maka_ui_runtime::abi::ValueBindings,
+        _: &tokio::runtime::Handle,
+        _: std::time::Instant,
+    ) -> maka_ui_runtime::backend::Job<ComponentOutput<NativeView<String>>> {
+        match &call {
+            ComponentCall::Mount { .. } => assert!(previous.is_none()),
+            ComponentCall::Update { state, .. } | ComponentCall::Event { state, .. } => {
+                assert_eq!(
+                    previous.unwrap().view.as_str(),
+                    format!("{}={}", state["label"].as_str().unwrap(), state["count"])
+                );
+            }
+        }
+        maka_ui_runtime::backend::Job::ready(self.call(call, values))
+    }
     fn call(
         &self,
         call: ComponentCall<'_>,
@@ -180,6 +199,92 @@ fn opaque_native_children_share_transaction_identity_and_input_admission_with_js
     close_all(&mut app, &root);
 }
 
+struct DelayedCounter {
+    counter: Counter,
+    release: Rc<std::cell::RefCell<Option<tokio::sync::oneshot::Receiver<()>>>>,
+}
+impl NativeComponent<String> for DelayedCounter {
+    fn call(
+        &self,
+        call: ComponentCall<'_>,
+        values: &maka_ui_runtime::abi::ValueBindings,
+    ) -> maka_ui_runtime::Result<ComponentOutput<NativeView<String>>> {
+        self.counter.call(call, values)
+    }
+    fn start(
+        &self,
+        call: ComponentCall<'_>,
+        _: Option<&NativeView<String>>,
+        values: &maka_ui_runtime::abi::ValueBindings,
+        _: &tokio::runtime::Handle,
+        _: std::time::Instant,
+    ) -> maka_ui_runtime::backend::Job<ComponentOutput<NativeView<String>>> {
+        let release = if matches!(&call, ComponentCall::Event { .. }) {
+            self.release.borrow_mut().take()
+        } else {
+            None
+        };
+        let output = self.call(call, values);
+        maka_ui_runtime::backend::Job::new(async move {
+            if let Some(release) = release {
+                release.await.unwrap();
+            }
+            output
+        })
+    }
+}
+
+#[test]
+fn waiting_for_native_work_does_not_expire_the_composed_update() {
+    let timer = timer();
+    let (input, packages, contract) = fixture();
+    let (release, waiting) = tokio::sync::oneshot::channel();
+    let waiting = Rc::new(std::cell::RefCell::new(Some(waiting)));
+    let mut registry = crate::support::scene::registry(PresentationTarget::Desktop);
+    registry
+        .register("test.counter", move |_, _| {
+            Ok(BTreeMap::from([(
+                "Counter".into(),
+                NativeExport {
+                    contract: contract.clone(),
+                    value: NativeCapability::Component(Rc::new(DelayedCounter {
+                        counter: Counter {
+                            calls: Rc::new(Cell::new(0)),
+                        },
+                        release: waiting.clone(),
+                    })),
+                },
+            )]))
+        })
+        .unwrap();
+    let slice = std::time::Duration::from_millis(100);
+    let mut app = Application::new(
+        &input,
+        packages,
+        timer.handle().clone(),
+        maka_ui_js::execution(maka_js_runtime::plugin::Limits {
+            synchronous_slice: slice,
+            ..Default::default()
+        }),
+        registry,
+        Default::default(),
+    )
+    .unwrap();
+    let root = app.mount_launch(json!({})).unwrap();
+    let left = app.child_mount(&root, "left").unwrap().clone();
+    maka_ui_runtime::Application::dispatch(&mut app, &left, 0, "inc", json!({"delta":2})).unwrap();
+    assert!(
+        timer
+            .block_on(async { tokio::time::timeout(slice * 2, app.wait_idle()).await })
+            .is_err()
+    );
+    assert_eq!(app.frame(&left).unwrap().state["count"], 10);
+    release.send(()).unwrap();
+    timer.block_on(app.wait_idle()).unwrap();
+    assert_eq!(app.frame(&left).unwrap().state["count"], 12);
+    close_all(&mut app, &root);
+}
+
 #[test]
 fn native_availability_is_not_activation_and_actual_contract_or_value_mismatches_fail() {
     let timer = timer();
diff --git a/platform/ui-runtime/src/actions.rs b/platform/ui-runtime/src/actions.rs
index e3a8cbeb50..2d958e0b46 100644
--- a/platform/ui-runtime/src/actions.rs
+++ b/platform/ui-runtime/src/actions.rs
@@ -627,7 +627,7 @@ impl<V: ?Sized + 'static> Application<V> {
                         method: &source.method,
                         input: &source.input,
                     },
-                    update.deadline,
+                    std::time::Instant::now() + self.slice,
                 ),
                 Component::Native(component) => {
                     Ok(backend::Job::ready(component.capture(CaptureCall {
diff --git a/platform/ui-runtime/src/lib.rs b/platform/ui-runtime/src/lib.rs
index 7190e7a0c3..5c93ca6d31 100644
--- a/platform/ui-runtime/src/lib.rs
+++ b/platform/ui-runtime/src/lib.rs
@@ -740,6 +740,7 @@ impl<V: ?Sized + 'static> Application<V> {
         mount: &Mount,
         method: &str,
         args: &[Value],
+        previous: Option<&NativeView<V>>,
         deadline: std::time::Instant,
     ) -> Result<PendingInvocation<V>> {
         let input = if method == "event" {
@@ -801,7 +802,13 @@ impl<V: ?Sized + 'static> Application<V> {
                 Some(realm.clone()),
             ),
             Component::Native(component) => (
-                InvocationResult::Native(component.start(call, &values, &self.scheduler, deadline)),
+                InvocationResult::Native(component.start(
+                    call,
+                    previous,
+                    &values,
+                    &self.scheduler,
+                    deadline,
+                )),
                 None,
             ),
         };
diff --git a/platform/ui-runtime/src/native.rs b/platform/ui-runtime/src/native.rs
index 2ebdcdaded..bc56830396 100644
--- a/platform/ui-runtime/src/native.rs
+++ b/platform/ui-runtime/src/native.rs
@@ -294,9 +294,12 @@ pub trait NativeComponent<V: ?Sized>: 'static {
     /// Pure expensive preparation may return a pending job. The job retains
     /// the original invocation and yields only inert candidate recipe data;
     /// native resources and external operations remain with their existing owners.
+    /// `previous` is the immutable view matching this invocation's state, from
+    /// the current transaction when already staged, or the committed frame.
     fn start(
         &self,
         call: ComponentCall<'_>,
+        _previous: Option<&NativeView<V>>,
         values: &super::abi::ValueBindings,
         _: &tokio::runtime::Handle,
         _: std::time::Instant,
@@ -330,7 +333,7 @@ type Factory<V> =
 
 /// Presenter-owned, pure translation. No runtime or native owner is available
 /// at this precommit boundary. Implementations bound expansion and honor the
-/// caller's shared deadline; painting never executes a compiler.
+/// current callback's deadline; painting never executes a compiler.
 pub type PrepareScene = dyn Fn(&Value, std::time::Instant) -> Result<PreparedScene> + Send + Sync;
 type FinishScene<V> = dyn Fn(PreparedScene) -> Result<NativeView<V>>;
 pub(crate) struct SceneCompiler<V: ?Sized> {
diff --git a/platform/ui-runtime/src/tree.rs b/platform/ui-runtime/src/tree.rs
index e0611576ef..a6d0fb2404 100644
--- a/platform/ui-runtime/src/tree.rs
+++ b/platform/ui-runtime/src/tree.rs
@@ -109,7 +109,6 @@ pub(super) struct Update<V: ?Sized> {
     created: Vec<Mount>,
     removed: BTreeMap<Uuid, Mount>,
     events: VecDeque<Notification>,
-    pub deadline: Instant,
     actions: Vec<actions::Prepared<V>>,
     cancellations: Vec<(Mount, String)>,
     calls: VecDeque<Call>,
@@ -121,13 +120,12 @@ pub(super) struct Update<V: ?Sized> {
     publication: Option<tokio::sync::oneshot::Sender<Result<()>>>,
 }
 impl<V: ?Sized> Update<V> {
-    fn new(slice: std::time::Duration) -> Self {
+    fn new() -> Self {
         Self {
             changed: BTreeMap::new(),
             created: Vec::new(),
             removed: BTreeMap::new(),
             events: VecDeque::new(),
-            deadline: Instant::now() + slice,
             actions: Vec::new(),
             cancellations: Vec::new(),
             calls: VecDeque::new(),
@@ -139,8 +137,6 @@ impl<V: ?Sized> Update<V> {
             publication: None,
         }
     }
-    // Global presentation changes can visit every retained component. Bound
-    // actual work through the shared deadline, not serialized size or visit count.
     pub fn step(&mut self, depth: usize) -> Result<()> {
         if depth > 32 {
             return Err(Error::Invalid(
@@ -149,14 +145,6 @@ impl<V: ?Sized> Update<V> {
         }
         Ok(())
     }
-    fn check_deadline(&self) -> Result<()> {
-        if Instant::now() >= self.deadline {
-            return Err(Error::Invalid(
-                "composed UI update deadline exceeded".into(),
-            ));
-        }
-        Ok(())
-    }
     fn emit(
         &mut self,
         mount: &Mount,
@@ -297,7 +285,7 @@ impl<V: ?Sized + 'static> Application<V> {
         props: Value,
     ) -> Result<Mount> {
         let mount = self.runtime.mount_root(kind)?;
-        let mut update = Update::new(self.slice);
+        let mut update = Update::new();
         update.created.push(mount.clone());
         if let Err(error) = self.check_props(&mount, &props) {
             self.rollback(&update)?;
@@ -425,7 +413,7 @@ impl<V: ?Sized + 'static> Application<V> {
     ) -> Result<()> {
         let event =
             serde_json::to_value(event).map_err(|error| Error::Invalid(error.to_string()))?;
-        let mut update = Update::new(self.slice);
+        let mut update = Update::new();
         update.feedback = feedback;
         update.publication = publication;
         let current = self
@@ -490,8 +478,15 @@ impl<V: ?Sized + 'static> Application<V> {
         }
         let wake = self.waker();
         let mut cx = Context::from_waker(&wake);
+        // Yield long compositions to input and presentation without rejecting
+        // their original transaction or counting asynchronous waits as work.
+        let yield_at = Instant::now() + std::time::Duration::from_millis(4);
         let result = (|| {
             loop {
+                if Instant::now() >= yield_at {
+                    wake.wake_by_ref();
+                    return Ok(false);
+                }
                 if let Some((call, mut pending)) = update.pending.take() {
                     let invocation = match self.poll_invocation(&mut pending, &mut cx) {
                         Poll::Pending => {
@@ -524,8 +519,21 @@ impl<V: ?Sized + 'static> Application<V> {
                 }
                 if let Some(call) = update.calls.pop_front() {
                     update.step(call.depth)?;
-                    let pending =
-                        self.begin_invoke(&call.mount, call.method, &call.args, update.deadline)?;
+                    let previous = match &call.basis {
+                        Some((revision, _)) => {
+                            let current = self.current(&call.mount, &update)?;
+                            (current.frame.revision == *revision)
+                                .then(|| current.frame.view.clone())
+                        }
+                        None => None,
+                    };
+                    let pending = self.begin_invoke(
+                        &call.mount,
+                        call.method,
+                        &call.args,
+                        previous.as_ref(),
+                        Instant::now() + self.slice,
+                    )?;
                     update.pending = Some((call, pending));
                     continue;
                 }
@@ -535,7 +543,6 @@ impl<V: ?Sized + 'static> Application<V> {
                     }
                     continue;
                 }
-                update.check_deadline()?;
                 if self.deliver_one(&mut update)? {
                     continue;
                 }
@@ -1207,11 +1214,6 @@ impl<V: ?Sized + 'static> Application<V> {
         }
         let mut pending: Vec<_> = roots.into_values().map(|mount| (mount, 0u16)).collect();
         while let Some((mount, enclosing)) = pending.pop() {
-            if Instant::now() >= update.deadline {
-                return Err(Error::Invalid(
-                    "composed UI update deadline exceeded".into(),
-                ));
-            }
             let mounted = self.current(&mount, update)?;
             let view = &mounted.frame.view;
             let total = enclosing
@@ -1234,28 +1236,13 @@ impl<V: ?Sized + 'static> Application<V> {
     fn preflight(&mut self, update: &mut Update<V>) -> Result<()> {
         self.validate_render_depth(update)?;
         self.discard_private(update)?;
-        if Instant::now() >= update.deadline {
-            return Err(Error::Invalid(
-                "composed UI update deadline exceeded".into(),
-            ));
-        }
         self.validate_commit_fence(update)
     }
     fn validate_commit_fence(&mut self, update: &Update<V>) -> Result<()> {
-        if Instant::now() >= update.deadline {
-            return Err(Error::Invalid(
-                "composed UI update deadline exceeded".into(),
-            ));
-        }
         for view in update.changed.values() {
             let execution = self.runtime.admit_mount(&view.mount)?;
             self.runtime.settle(&execution, Ok(()))?;
         }
-        if Instant::now() >= update.deadline {
-            return Err(Error::Invalid(
-                "composed UI update deadline exceeded".into(),
-            ));
-        }
         Ok(())
     }
     fn commit(&mut self, update: &mut Update<V>) -> Result<()> {
diff --git a/products/maka/cli/tests/integration/terminal/bundled_product/chat/performance.rs b/products/maka/cli/tests/integration/terminal/bundled_product/chat/performance.rs
index dcd5473f9b..148435940d 100644
--- a/products/maka/cli/tests/integration/terminal/bundled_product/chat/performance.rs
+++ b/products/maka/cli/tests/integration/terminal/bundled_product/chat/performance.rs
@@ -110,3 +110,260 @@ fn default_product_input_continues_while_the_original_stdout_owner_is_blocked()
     assert!(!tui.screen.snapshot().unwrap().alternate_screen);
     drop(RootOwner::open(&host, &namespaces).unwrap());
 }
+
+fn large_history_fixture(model_base: Option<&str>) -> (tempfile::TempDir, std::path::PathBuf) {
+    use maka_agent_facts::import::{Content, Record, Source};
+    use maka_event_log::{EventLog, sessions::PluginSession};
+    let directory = tempfile::tempdir().unwrap();
+    let workspace = directory.path().join("workspace");
+    std::fs::create_dir(&workspace).unwrap();
+    let ui = directory.path().join("ui");
+    let host = ui.join("host");
+    let namespaces = RootNamespaces::for_current_account().unwrap();
+    drop(RootOwner::create(&ui, &namespaces).unwrap());
+    let runtime = tokio::runtime::Runtime::new().unwrap();
+    if let Some(base) = model_base {
+        runtime.block_on(seed_connection(&host, &namespaces, base, json!({})));
+    }
+    let args = [
+        "application",
+        "launch",
+        "--root",
+        ui.to_str().unwrap(),
+        "--workspace",
+        workspace.to_str().unwrap(),
+        "--trust-workspace",
+        "--locale",
+        "en",
+    ];
+    let mut bootstrap = Pty::spawn(&args);
+    bootstrap.wait_until_with_timeout(|s| s.contains("Settings"), Duration::from_secs(60));
+    bootstrap.send(b"\x11");
+    // Wait for the original Host shutdown as well as terminal restoration.
+    let closing = Instant::now();
+    while bootstrap.child.try_wait().unwrap().is_none() {
+        bootstrap.read();
+        assert!(
+            closing.elapsed() < Duration::from_secs(15),
+            "bootstrap did not exit"
+        );
+    }
+    bootstrap.finish();
+    runtime.block_on(async {
+        let identity = maka_fs_tools::workspace::ensure_identity(&workspace).await.unwrap();
+        let published = maka_fs_tools::workspace::directory::PublishedDirectory::open(&workspace).unwrap();
+        let owner = Arc::new(RootOwner::open(&host, &namespaces).unwrap());
+        let log = EventLog::for_root(owner).await.unwrap();
+        use sqlx::Connection;
+        let mut db = sqlx::SqliteConnection::connect_with(&sqlx::sqlite::SqliteConnectOptions::new().filename(host.join(maka_event_log::root::ROOT_DATABASE)).read_only(true)).await.unwrap();
+        let deployments: Vec<String> = sqlx::query_scalar("SELECT id FROM application_deployments").fetch_all(&mut db).await.unwrap();
+        db.close().await.unwrap();
+        let mut prefix = None;
+        for deployment in deployments {
+            let deployment = Uuid::parse_str(&deployment).unwrap();
+            let source = log.read_application_metadata(deployment).await.unwrap().unwrap();
+            if let Some(agent) = source.source.input.instances.get("agent") {
+                let head = log.application_head(deployment).await.unwrap().unwrap();
+                prefix = Some(maka_host_runtime::storage::instance_prefix(&head.state_domain, deployment, &maka_plugin_core::composition::InstanceId(vec![agent.key])));
+            }
+        }
+        let session = format!("{}{}", prefix.expect("default Agent namespace"), Uuid::new_v4().simple());
+        let mut records = Vec::new();
+        for message in 0..32 {
+            for (suffix, content) in [
+                ("user", Content::User { text: format!("Question {message:02}") }),
+                ("assistant", Content::Assistant {
+                    text: (0..30).map(|row| format!("Scroll row {message:02}-{row:02}: a paragraph with **bold** and `code` in a long conversation.\n\n")).collect(),
+                    model: None, thinking: None,
+                }),
+            ] {
+                records.push(Record {
+                    source_message_id: format!("{message}-{suffix}"),
+                    source_turn_id: format!("turn-{message}"),
+                    timestamp: Some(1), content,
+                });
+            }
+        }
+        log.import_session(
+            &PluginSession {
+                session_id: session,
+                creator: maka_capabilities::storage::Namespace::new(maka_agent_api::IMPLEMENTATION, maka_plugin_core::scope::Scope::Profile).unwrap(),
+                fingerprint: "scroll-fixture".into(), managed: false, authority_session_id: None,
+            },
+            &Source { adapter: "fixture".into(), session_id: "scroll-source".into() },
+            &json!({"title":"Scroll fixture","titleIsManual":true,"labels":[],
+                "workspace":{"path":published.path(),"directoryIdentity":published.identity().unwrap(),"identity":identity},
+                "permissions":{"access":"workspace_write","requestPermissions":true},"boundary_revision":0}),
+            records, 1,
+        ).await.unwrap();
+        log.close().await.unwrap();
+    });
+    (directory, ui)
+}
+
+#[test]
+#[ignore = "manual default product history scroll profiling in a real PTY"]
+fn default_product_scrolls_large_imported_history() {
+    let (_directory, ui) = large_history_fixture(None);
+    let mut tui = Pty::spawn(&["application", "launch", "--root", ui.to_str().unwrap()]);
+    eprintln!("scroll fixture PID {}", tui.child.id());
+    tui.wait_until_with_timeout(|s| s.contains("Scroll fixture"), Duration::from_secs(60));
+    click(&mut tui, "Scroll fixture");
+    tui.wait_until_with_timeout(|s| s.contains("Scroll row 31-29"), Duration::from_secs(60));
+    let ready = Instant::now();
+    while ready.elapsed() < Duration::from_millis(500) {
+        tui.read();
+    }
+    let first_row = |screen: &str| {
+        screen.lines().enumerate().find_map(|(index, line)| {
+            let at = line.find("Scroll row ")?;
+            Some((index, line[at..at + 16].to_owned()))
+        })
+    };
+    let rounds = std::env::var("MAKA_SCROLL_PROFILE_ROUNDS")
+        .ok()
+        .and_then(|s| s.parse().ok())
+        .unwrap_or(20);
+    // Start away from the tail: showing/hiding the "Scroll to end" control
+    // changes viewport height and is not an extra wheel movement.
+    for _ in 0..20 {
+        let before = first_row(&tui.screen.snapshot().unwrap().screen).unwrap();
+        tui.send(b"\x1b[<64;70;10M");
+        tui.wait_until(|screen| first_row(screen).is_some_and(|row| row != before));
+    }
+    let ready = Instant::now();
+    while ready.elapsed() < Duration::from_millis(500) {
+        tui.read();
+    }
+    let baseline = first_row(&tui.screen.snapshot().unwrap().screen).unwrap();
+    eprintln!("scroll baseline: {baseline:?}");
+    for _ in 0..rounds {
+        let before = first_row(&tui.screen.snapshot().unwrap().screen).unwrap();
+        let started = Instant::now();
+        tui.send(b"\x1b[<64;70;10M");
+        tui.wait_until(|screen| first_row(screen).is_some_and(|row| row != before));
+        eprintln!("history wheel to visible row: {:?}", started.elapsed());
+    }
+    let ready = Instant::now();
+    while ready.elapsed() < Duration::from_millis(500) {
+        tui.read();
+    }
+    let scrolled = first_row(&tui.screen.snapshot().unwrap().screen).unwrap();
+    eprintln!("scroll target: {scrolled:?}");
+    for (event, expected) in [
+        (b"\x1b[<65;70;10M", baseline),
+        (b"\x1b[<64;70;10M", scrolled),
+    ] {
+        // Keep consuming output while input arrives independently at 100 Hz,
+        // so the fixture itself cannot cause PTY output backpressure.
+        let mut input = tui.master.as_ref().unwrap().try_clone().unwrap();
+        let last_input = std::thread::scope(|scope| {
+            let sender = scope.spawn(move || {
+                use std::io::Write;
+                let mut last = Instant::now();
+                for _ in 0..rounds {
+                    std::thread::sleep(Duration::from_millis(10));
+                    input.write_all(event).unwrap();
+                    last = Instant::now();
+                }
+                last
+            });
+            tui.wait_until(|screen| first_row(screen).as_ref() == Some(&expected));
+            sender.join().unwrap()
+        });
+        let latency = last_input.elapsed();
+        eprintln!("history 100 Hz wheel burst stop to final row: {latency:?}");
+        assert!(
+            latency < Duration::from_millis(150),
+            "wheel backlog after stopping: {latency:?}"
+        );
+        let settled = Instant::now();
+        while settled.elapsed() < Duration::from_millis(250) {
+            tui.read();
+            if tui.frames.ready() {
+                assert_eq!(
+                    first_row(&tui.screen.snapshot().unwrap().screen).as_ref(),
+                    Some(&expected)
+                );
+            }
+        }
+        assert_eq!(
+            first_row(&tui.screen.snapshot().unwrap().screen).as_ref(),
+            Some(&expected)
+        );
+    }
+    evidence(&tui, "scroll-profile");
+    tui.send(b"\x11");
+    tui.finish();
+}
+
+#[test]
+#[ignore = "real default product sends over large imported history"]
+fn default_product_sends_over_large_imported_history() {
+    let listener = TcpListener::bind("127.0.0.1:0").unwrap();
+    let base = format!("http://{}/v1", listener.local_addr().unwrap());
+    let (requests, received) = mpsc::channel();
+    let server = model_server(listener, requests, 2, 0);
+    let (_directory, ui) = large_history_fixture(Some(&base));
+    let mut tui = Pty::spawn(&["application", "launch", "--root", ui.to_str().unwrap()]);
+    eprintln!("send fixture PID {}", tui.child.id());
+    tui.wait_until_with_timeout(|s| s.contains("Scroll fixture"), Duration::from_secs(60));
+    click(&mut tui, "Scroll fixture");
+    tui.wait_until_with_timeout(
+        |s| {
+            s.contains("Scroll row 31-29")
+                && s.contains("Message…")
+                && s.contains("fixture-model")
+                && !s.contains("Restoring draft…")
+        },
+        Duration::from_secs(60),
+    );
+    for turn in 0..2 {
+        let prompt = format!("Persistent history send {turn}");
+        click(&mut tui, "Message…");
+        paste(&mut tui, &prompt);
+        tui.wait_for(&prompt);
+        let started = Instant::now();
+        tui.send(b"\r");
+        let (sent, mut socket) = next_request(&mut tui, &received);
+        assert!(sent.to_string().contains(&prompt));
+        eprintln!(
+            "large history Enter to model request: {:?}",
+            started.elapsed()
+        );
+        let transcript = format!("❯ {prompt}");
+        tui.wait_for(&transcript);
+        eprintln!(
+            "large history Enter to visible message: {:?}",
+            started.elapsed()
+        );
+        let observed = Instant::now();
+        while observed.elapsed() < Duration::from_secs(6) {
+            tui.read();
+            if tui.frames.ready() {
+                assert!(
+                    tui.screen.snapshot().unwrap().screen.contains(&transcript),
+                    "submitted message disappeared"
+                );
+            }
+            assert!(
+                tui.child.try_wait().unwrap().is_none(),
+                "UI exited while awaiting model response"
+            );
+        }
+        let reply = format!("Completed history send {turn}");
+        delta(&mut socket, &reply);
+        complete(&mut socket);
+        tui.wait_until(|s| {
+            s.contains(&reply)
+                && s.contains("Message…")
+                && s.contains("Send")
+                && !s.contains("Queue for next turn")
+        });
+        assert!(tui.screen.snapshot().unwrap().screen.contains(&transcript));
+    }
+    evidence(&tui, "large-history-send");
+    tui.send(b"\x11");
+    tui.finish();
+    server.join().unwrap();
+}


---------------------------------------------------------------------
To unsubscribe, e-mail: commits-unsubscribe@maka.apache.org
For additional commands, e-mail: commits-help@maka.apache.org