Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
11 changes: 7 additions & 4 deletions Cargo.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

22 changes: 20 additions & 2 deletions Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -51,6 +51,21 @@ codegen-units = 1
strip = true
panic = "abort"

# Profiling build: release-speed, but with symbols and line tables kept so a
# system sampler (`sample`, Instruments, samply) can name our own functions.
# The shipped release profile strips them, which turns every frame inside
# CrabPort into a bare address — useless for finding a hotspot.
# cargo build --profile profiling
# scripts/profile.sh --build
[profile.profiling]
inherits = "release"
strip = false
debug = 1
# Thin LTO and parallel codegen: a profiling build is linked often enough that
# the full-LTO wait is not worth it, and neither changes what the profile says.
lto = "thin"
codegen-units = 16

[workspace]
members = [
"crabport-agent",
Expand All @@ -66,15 +81,18 @@ members = [
"crabport-serial",
]
# The vendored `gpui-component` copy is a dependency (via `[patch.crates-io]`
# below), not a workspace member — excluding it keeps cargo from treating it
# as one. See `vendor/gpui-component/PATCHES.md` for what we patch and why.
# below), not a workspace member — excluding it keeps cargo from treating it as
# one. See `vendor/gpui-component/PATCHES.md` for what we patch and why.
exclude = ["vendor/gpui-component"]

# Patched third-party crates. `gpui-component`'s text rendering has a
# selection-painting path that is O(chars²) per frame, which stalls the AI
# panel on long messages (see `vendor/gpui-component/PATCHES.md`); upstream
# has no fix on the gpui 0.2 line, so we build our patched copy. Reverting =
# delete the `vendor/` directory and this block.
#
# `gpui-animation` used to be vendored here too; its fix now lives upstream and
# `crabport-ui` depends on the git revision directly.
[patch.crates-io]
gpui-component = { path = "vendor/gpui-component" }

Expand Down
46 changes: 39 additions & 7 deletions crabport-agent/src/agent.rs
Original file line number Diff line number Diff line change
Expand Up @@ -264,22 +264,54 @@ impl Agent {
smol::spawn(async move {
let started = Instant::now();
let mut last = before.clone();
let mut quiet_since = Instant::now();
let mut timed_out = false;
let mut cancelled = false;
// `try_dump_text` materializes every scrollback line into a
// `String`, so the loop reads the grid only on ticks that actually
// saw a write. When the session reports a write counter that
// counter is also the authority on quietness — a command that
// stopped printing is exactly a command whose counter stopped
// moving, whereas "the dumped text looks the same" cannot be
// judged on a tick where the read failed (a flooding terminal
// holds the lock) or where the program redraws identical text.
let mut last_rev = session.grid_revision();
let revision_tracking = last_rev.is_some();
// Quietness clocks: `last_write` for the counter path,
// `quiet_since` for the text-comparison fallback.
let mut last_write = Instant::now();
let mut quiet_since = Instant::now();
loop {
smol::Timer::after(OUTPUT_POLL).await;
if task_cancel.is_cancelled() {
cancelled = true;
break;
}
let Some(now) = session.try_dump_text(AGENT_READ_LINES) else {
continue; // terminal lock held by the reader; try next tick
let rev = session.grid_revision();
let grid_changed = match (rev, last_rev) {
(Some(rev), Some(prev)) => rev != prev,
// No counter: poll the grid every tick, as before.
_ => true,
};
let mut dumped = false;
if grid_changed {
last_rev = rev;
last_write = Instant::now();
if let Some(now) = session.try_dump_text(AGENT_READ_LINES) {
dumped = true;
if now != last {
last = now;
quiet_since = Instant::now();
}
}
}
let quiet = if revision_tracking {
last_write.elapsed() >= OUTPUT_QUIET
} else {
// Without a counter, quiet is only knowable from a read
// that succeeded.
dumped && quiet_since.elapsed() >= OUTPUT_QUIET
};
if now != last {
last = now;
quiet_since = Instant::now();
} else if quiet_since.elapsed() >= OUTPUT_QUIET {
if quiet {
break;
}
if started.elapsed() >= OUTPUT_TIMEOUT {
Expand Down
13 changes: 13 additions & 0 deletions crabport-agent/src/session.rs
Original file line number Diff line number Diff line change
Expand Up @@ -68,6 +68,19 @@ pub trait AgentSession: Send + Sync {
String::new()
}

/// Monotonic counter of writes into the terminal grid, when the session
/// can provide one.
///
/// Pollers compare it against the value from their previous tick and skip
/// [`Self::try_dump_text`] entirely while nothing has been written — the
/// extraction allocates a `String` per grid line, so calling it on a fixed
/// timer just to discover "no change" is pure waste. Implementors that
/// cannot report a counter return `None` (the default), and pollers then
/// fall back to reading the grid every tick.
fn grid_revision(&self) -> Option<u64> {
None
}

/// Non-blocking [`Self::dump_text`]: `None` while the terminal reader
/// holds its lock — the caller retries on its next tick.
fn try_dump_text(&self, _lines: usize) -> Option<String> {
Expand Down
14 changes: 14 additions & 0 deletions crabport-core/src/config.rs
Original file line number Diff line number Diff line change
Expand Up @@ -1266,10 +1266,24 @@ pub fn update<R>(f: impl FnOnce(&mut CrabPortConfig) -> R) -> Result<R, ConfigEr
}

/// Convenience: take a read lock and clone the current config snapshot.
///
/// Cloning `CrabPortConfig` walks the AI provider list (several `String`s per
/// entry), so this is not free. Render paths that read only a couple of
/// fields should call [`with`] instead.
pub fn snapshot() -> CrabPortConfig {
CONFIG.read().clone()
}

/// Run `f` against the live config without cloning it.
///
/// Use this from render hot paths: the read lock is held for the duration of
/// the closure only. Do not call [`update`] (or anything else that takes the
/// write lock) from inside `f` — `parking_lot`'s `RwLock` cannot upgrade a
/// held read lock, and the write would deadlock.
pub fn with<R>(f: impl FnOnce(&CrabPortConfig) -> R) -> R {
f(&CONFIG.read())
}

#[cfg(test)]
mod tests {
use super::*;
Expand Down
2 changes: 2 additions & 0 deletions crabport-serial/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,8 @@ crabport-core = { path = "../crabport-core" }
serialport = { version = "4", default-features = false }
tokio = { version = "1", features = ["rt", "macros", "io-util", "sync"] }
async-broadcast = "0.7"
# `BackendEvent::Data` payload type (see crabport-terminal).
bytes = "1"
async-channel = "2.5"
tracing = { version = "0.1", default-features = false, features = ["std"] }
parking_lot = "0.12"
2 changes: 1 addition & 1 deletion crabport-serial/src/backend.rs
Original file line number Diff line number Diff line change
Expand Up @@ -200,7 +200,7 @@ impl SerialBackend {
loop {
match data_rx.try_recv() {
Ok(data) => {
let _ = event_tx2.broadcast(BackendEvent::Data(data)).await;
let _ = event_tx2.broadcast(BackendEvent::Data(data.into())).await;
}
Err(std::sync::mpsc::TryRecvError::Empty) => {
tokio::time::sleep(Duration::from_millis(5)).await;
Expand Down
2 changes: 2 additions & 0 deletions crabport-ssh/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,8 @@ russh = "0.45"
secrecy = "0.10"
zeroize = "1"
async-broadcast = "0.7"
# `BackendEvent::Data` payload type (see crabport-terminal).
bytes = "1"
async-channel = "2.5"
tokio = { version = "1", features = ["rt", "net", "macros", "io-util", "time"] }
async-trait = "0.1"
Expand Down
16 changes: 14 additions & 2 deletions crabport-ssh/src/backend.rs
Original file line number Diff line number Diff line change
Expand Up @@ -527,8 +527,14 @@ impl SshBackend {
msg = channel.wait() => {
match msg {
Some(ChannelMsg::Data { data }) => {
// russh hands out its own `CryptoVec`, which
// cannot be adopted by `Bytes`; copy it into
// one shared buffer here (the broadcast clones
// per subscriber are then refcount bumps).
let _ = event_tx2
.broadcast(BackendEvent::Data(data.to_vec()))
.broadcast(BackendEvent::Data(
bytes::Bytes::copy_from_slice(&data),
))
.await;
}
Some(ChannelMsg::Eof) | Some(ChannelMsg::Close) | None => {
Expand Down Expand Up @@ -731,8 +737,14 @@ impl SshBackend {
msg = channel.wait() => {
match msg {
Some(ChannelMsg::Data { data }) => {
// russh hands out its own `CryptoVec`, which
// cannot be adopted by `Bytes`; copy it into
// one shared buffer here (the broadcast clones
// per subscriber are then refcount bumps).
let _ = event_tx2
.broadcast(BackendEvent::Data(data.to_vec()))
.broadcast(BackendEvent::Data(
bytes::Bytes::copy_from_slice(&data),
))
.await;
}
Some(ChannelMsg::Eof) | Some(ChannelMsg::Close) | None => {
Expand Down
Loading
Loading