Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
6ae7c3eb97 | ||
|
|
a73eb6284f | ||
|
|
57efb615f6 | ||
|
|
fe26dab6a8 | ||
|
|
8eecd9961e |
@@ -10,7 +10,7 @@ use std::future::Future;
|
||||
use std::path::PathBuf;
|
||||
use std::pin::Pin;
|
||||
use std::sync::atomic::{AtomicBool, AtomicU64, AtomicUsize, Ordering};
|
||||
use std::sync::Arc;
|
||||
use std::sync::{Arc, Weak};
|
||||
use std::task::{Context, Poll};
|
||||
use std::time::Duration;
|
||||
|
||||
@@ -102,8 +102,12 @@ pub struct SessionRecord {
|
||||
/// outside the sessions lock. Daemon-local; never rides the wire.
|
||||
pub acp: Option<Arc<AcpSession>>,
|
||||
/// Open log plus its post-append live sender. Their shared lock is the
|
||||
/// replay/live seam used by the structured WebSocket in #138.
|
||||
/// replay/live seam used by the structured WebSocket in #138. Callers may
|
||||
/// clone this handle under `sessions`, but must never hold either guard
|
||||
/// while acquiring the other.
|
||||
acp_events: Option<Arc<Mutex<AcpEventStream>>>,
|
||||
/// Latest activity snapshot applied, keyed to its originating stream.
|
||||
structured_activity_watermark: Option<StructuredActivityWatermark>,
|
||||
/// Completion signal for the task draining ACP notifications into the
|
||||
/// event log. Shutdown waits for it before returning.
|
||||
acp_event_pump: Option<watch::Receiver<bool>>,
|
||||
@@ -118,6 +122,12 @@ impl SessionRecord {
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Debug)]
|
||||
struct StructuredActivityWatermark {
|
||||
stream: Weak<Mutex<AcpEventStream>>,
|
||||
sequence: u64,
|
||||
}
|
||||
|
||||
#[derive(Debug)]
|
||||
struct AcpEventStream {
|
||||
log: EventLog,
|
||||
@@ -129,6 +139,14 @@ struct AcpEventStream {
|
||||
/// claimed: it is queued onto ACP before another operation can proceed.
|
||||
operation: Arc<Mutex<()>>,
|
||||
dispatch: AcpDispatchState,
|
||||
activity_sequence: u64,
|
||||
}
|
||||
|
||||
impl AcpEventStream {
|
||||
fn activity_snapshot(&mut self) -> (u64, ActivityState) {
|
||||
self.activity_sequence += 1;
|
||||
(self.activity_sequence, self.projection.activity())
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Debug, Default)]
|
||||
@@ -1220,6 +1238,7 @@ impl SessionManager {
|
||||
pending_approvals: HashMap::new(),
|
||||
operation: Arc::new(Mutex::new(())),
|
||||
dispatch: AcpDispatchState::default(),
|
||||
activity_sequence: 0,
|
||||
})))
|
||||
}
|
||||
Err(e) => {
|
||||
@@ -1323,6 +1342,7 @@ impl SessionManager {
|
||||
awaiting_suppressed: false,
|
||||
acp,
|
||||
acp_events,
|
||||
structured_activity_watermark: None,
|
||||
acp_event_pump: event_pump,
|
||||
},
|
||||
);
|
||||
@@ -1534,6 +1554,7 @@ impl SessionManager {
|
||||
// daemon; only tmux-backed sessions can be adopted.
|
||||
acp: None,
|
||||
acp_events: None,
|
||||
structured_activity_watermark: None,
|
||||
acp_event_pump: None,
|
||||
},
|
||||
);
|
||||
@@ -1655,6 +1676,7 @@ impl SessionManager {
|
||||
pending_approvals: HashMap::new(),
|
||||
operation: Arc::new(Mutex::new(())),
|
||||
dispatch: AcpDispatchState::default(),
|
||||
activity_sequence: 0,
|
||||
})))
|
||||
}
|
||||
Err(error) => {
|
||||
@@ -1702,6 +1724,7 @@ impl SessionManager {
|
||||
awaiting_suppressed: false,
|
||||
acp,
|
||||
acp_events,
|
||||
structured_activity_watermark: None,
|
||||
acp_event_pump: None,
|
||||
},
|
||||
);
|
||||
@@ -2122,57 +2145,59 @@ async fn sync_structured_activity_from_stream(
|
||||
id: Uuid,
|
||||
events: Arc<Mutex<AcpEventStream>>,
|
||||
) {
|
||||
let event_stream = events.lock().await;
|
||||
let raw = event_stream.projection.activity();
|
||||
// Stream state must stay fixed until its catalog transition is applied;
|
||||
// every other path releases `sessions` before awaiting this stream lock.
|
||||
apply_structured_activity(inner, id, Some(&events), raw).await;
|
||||
let (sequence, raw) = events.lock().await.activity_snapshot();
|
||||
apply_structured_activity(inner, id, Some((&events, sequence)), raw).await;
|
||||
}
|
||||
|
||||
async fn apply_structured_activity(
|
||||
inner: &Arc<Inner>,
|
||||
id: Uuid,
|
||||
expected_events: Option<&Arc<Mutex<AcpEventStream>>>,
|
||||
expected_events: Option<(&Arc<Mutex<AcpEventStream>>, u64)>,
|
||||
raw: ActivityState,
|
||||
) {
|
||||
let updated = {
|
||||
let mut sessions = inner.sessions.lock().await;
|
||||
let Some(record) = sessions.get_mut(&id) else {
|
||||
return;
|
||||
};
|
||||
if record.session.view != SessionView::Structured {
|
||||
return;
|
||||
}
|
||||
let current_events = record.acp_events.as_ref();
|
||||
let stream_matches = match (expected_events, current_events) {
|
||||
(Some(expected), Some(current)) => Arc::ptr_eq(expected, current),
|
||||
(None, None) => true,
|
||||
_ => false,
|
||||
};
|
||||
if !stream_matches {
|
||||
return;
|
||||
}
|
||||
let raw = if record.session.status == SessionStatus::Dead {
|
||||
ActivityState::Error
|
||||
} else {
|
||||
raw
|
||||
};
|
||||
let activity = crate::activity::apply_focus_suppression(
|
||||
raw,
|
||||
record.focused_since,
|
||||
std::time::Instant::now(),
|
||||
&mut record.awaiting_suppressed,
|
||||
);
|
||||
if record.session.activity == activity {
|
||||
None
|
||||
} else {
|
||||
record.session.activity = activity;
|
||||
record.session.activity_since = Utc::now();
|
||||
Some(record.session.clone())
|
||||
}
|
||||
let mut sessions = inner.sessions.lock().await;
|
||||
let Some(record) = sessions.get_mut(&id) else {
|
||||
return;
|
||||
};
|
||||
if let Some(session) = updated {
|
||||
let _ = inner.events.send(CatalogEvent::SessionUpdated { session });
|
||||
if record.session.view != SessionView::Structured {
|
||||
return;
|
||||
}
|
||||
let current_events = record.acp_events.as_ref();
|
||||
match (expected_events, current_events) {
|
||||
(Some((expected, sequence)), Some(current)) if Arc::ptr_eq(expected, current) => {
|
||||
let stream = Arc::downgrade(current);
|
||||
if record
|
||||
.structured_activity_watermark
|
||||
.as_ref()
|
||||
.is_some_and(|watermark| {
|
||||
watermark.stream.ptr_eq(&stream) && sequence < watermark.sequence
|
||||
})
|
||||
{
|
||||
return;
|
||||
}
|
||||
record.structured_activity_watermark =
|
||||
Some(StructuredActivityWatermark { stream, sequence });
|
||||
}
|
||||
(None, None) => {}
|
||||
_ => return,
|
||||
}
|
||||
let raw = if record.session.status == SessionStatus::Dead {
|
||||
ActivityState::Error
|
||||
} else {
|
||||
raw
|
||||
};
|
||||
let activity = crate::activity::apply_focus_suppression(
|
||||
raw,
|
||||
record.focused_since,
|
||||
std::time::Instant::now(),
|
||||
&mut record.awaiting_suppressed,
|
||||
);
|
||||
if record.session.activity != activity {
|
||||
record.session.activity = activity;
|
||||
record.session.activity_since = Utc::now();
|
||||
let _ = inner.events.send(CatalogEvent::SessionUpdated {
|
||||
session: record.session.clone(),
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
@@ -2849,16 +2874,17 @@ mod tests {
|
||||
PermissionOption, PermissionOptionKind, RequestPermissionOutcome, RequestPermissionRequest,
|
||||
ToolCallUpdate, ToolCallUpdateFields,
|
||||
};
|
||||
use maestro_protocol::{ActivityState, CreateSessionRequest, SessionView};
|
||||
use maestro_protocol::{ActivityState, CatalogEvent, CreateSessionRequest, SessionView};
|
||||
|
||||
use super::{
|
||||
cancel_pending_approvals, permission_outcome, record_permission_request,
|
||||
run_structured_activity_pass, sync_structured_activity_from_stream, AcpDispatchState,
|
||||
AcpEventStream, ApprovalDecision, RecordOutcome, SessionManager,
|
||||
apply_structured_activity, cancel_pending_approvals, permission_outcome,
|
||||
record_permission_request, run_structured_activity_pass,
|
||||
sync_structured_activity_from_stream, AcpDispatchState, AcpEventStream, ApprovalDecision,
|
||||
RecordOutcome, SessionManager,
|
||||
};
|
||||
use crate::activity::FOCUS_CLEAR_HOLD;
|
||||
use crate::panes::FakePanes;
|
||||
use crate::projection::Projection;
|
||||
use crate::projection::{Projection, TurnLifecycle};
|
||||
use crate::sidecar::{
|
||||
EventCursor, EventLog, FaultyLogSink, PersistedEvent, SharedBuf, SidecarStore,
|
||||
};
|
||||
@@ -2887,6 +2913,7 @@ mod tests {
|
||||
pending_approvals: std::collections::HashMap::new(),
|
||||
operation: std::sync::Arc::new(tokio::sync::Mutex::new(())),
|
||||
dispatch: AcpDispatchState::default(),
|
||||
activity_sequence: 0,
|
||||
}
|
||||
}
|
||||
|
||||
@@ -3043,6 +3070,87 @@ mod tests {
|
||||
.expect("terminal resize remains available");
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn structured_activity_releases_stream_before_waiting_for_catalog() {
|
||||
let (_state, manager, _panes, structured_id, events, _terminal_id) =
|
||||
manager_with_structured_stream().await;
|
||||
let sessions = manager.inner.sessions.lock().await;
|
||||
let sync =
|
||||
sync_structured_activity_from_stream(&manager.inner, structured_id, events.clone());
|
||||
tokio::pin!(sync);
|
||||
assert!(matches!(futures_util::poll!(sync.as_mut()), Poll::Pending));
|
||||
|
||||
assert!(
|
||||
events.try_lock().is_ok(),
|
||||
"activity sync held the event stream while waiting for the catalog"
|
||||
);
|
||||
|
||||
drop(sessions);
|
||||
tokio::time::timeout(Duration::from_secs(1), sync)
|
||||
.await
|
||||
.expect("activity sync did not finish");
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn newer_structured_activity_snapshot_cannot_be_overtaken() {
|
||||
let (_state, manager, _panes, structured_id, events, _terminal_id) =
|
||||
manager_with_structured_stream().await;
|
||||
let mut catalog = manager.events();
|
||||
manager
|
||||
.inner
|
||||
.sessions
|
||||
.lock()
|
||||
.await
|
||||
.get_mut(&structured_id)
|
||||
.unwrap()
|
||||
.focused_since = None;
|
||||
|
||||
let (older_sequence, older_activity) = events.lock().await.activity_snapshot();
|
||||
let (newer_sequence, newer_activity) = {
|
||||
let mut event_stream = events.lock().await;
|
||||
let turn = event_stream.projection.active_turn().unwrap();
|
||||
event_stream.projection.clear_approval();
|
||||
event_stream
|
||||
.projection
|
||||
.turn_lifecycle(TurnLifecycle::Finish, turn);
|
||||
event_stream.activity_snapshot()
|
||||
};
|
||||
|
||||
apply_structured_activity(
|
||||
&manager.inner,
|
||||
structured_id,
|
||||
Some((&events, newer_sequence)),
|
||||
newer_activity,
|
||||
)
|
||||
.await;
|
||||
apply_structured_activity(
|
||||
&manager.inner,
|
||||
structured_id,
|
||||
Some((&events, older_sequence)),
|
||||
older_activity,
|
||||
)
|
||||
.await;
|
||||
|
||||
let CatalogEvent::SessionUpdated { session } = catalog.try_recv().unwrap() else {
|
||||
panic!("unexpected catalog event");
|
||||
};
|
||||
assert_eq!(session.activity, ActivityState::Idle);
|
||||
assert!(matches!(
|
||||
catalog.try_recv(),
|
||||
Err(tokio::sync::broadcast::error::TryRecvError::Empty)
|
||||
));
|
||||
assert_eq!(
|
||||
manager
|
||||
.snapshot()
|
||||
.await
|
||||
.into_iter()
|
||||
.find(|session| session.id == structured_id)
|
||||
.unwrap()
|
||||
.activity,
|
||||
ActivityState::Idle
|
||||
);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn delayed_activity_from_a_replaced_stream_is_discarded() {
|
||||
let (_state, manager, _panes, structured_id, old_events, _terminal_id) =
|
||||
@@ -3076,6 +3184,73 @@ mod tests {
|
||||
));
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn replacement_accepts_new_activity_after_a_high_old_watermark() {
|
||||
let (_state, manager, _panes, structured_id, old_events, _terminal_id) =
|
||||
manager_with_structured_stream().await;
|
||||
let replacement = Arc::new(tokio::sync::Mutex::new(stream(
|
||||
manager
|
||||
.inner
|
||||
.sidecar
|
||||
.open_events(uuid::Uuid::new_v4())
|
||||
.expect("open replacement event log"),
|
||||
)));
|
||||
manager
|
||||
.inner
|
||||
.sessions
|
||||
.lock()
|
||||
.await
|
||||
.get_mut(&structured_id)
|
||||
.unwrap()
|
||||
.focused_since = None;
|
||||
let _ = old_events.lock().await.activity_snapshot();
|
||||
let (old_high_sequence, old_high_activity) = old_events.lock().await.activity_snapshot();
|
||||
apply_structured_activity(
|
||||
&manager.inner,
|
||||
structured_id,
|
||||
Some((&old_events, old_high_sequence)),
|
||||
old_high_activity,
|
||||
)
|
||||
.await;
|
||||
let (delayed_old_sequence, delayed_old_activity) =
|
||||
old_events.lock().await.activity_snapshot();
|
||||
|
||||
{
|
||||
let mut sessions = manager.inner.sessions.lock().await;
|
||||
let record = sessions.get_mut(&structured_id).unwrap();
|
||||
record.acp_events = Some(replacement.clone());
|
||||
record.session.activity = ActivityState::Error;
|
||||
}
|
||||
|
||||
let (new_sequence, new_activity) = replacement.lock().await.activity_snapshot();
|
||||
assert!(new_sequence < old_high_sequence);
|
||||
apply_structured_activity(
|
||||
&manager.inner,
|
||||
structured_id,
|
||||
Some((&replacement, new_sequence)),
|
||||
new_activity,
|
||||
)
|
||||
.await;
|
||||
apply_structured_activity(
|
||||
&manager.inner,
|
||||
structured_id,
|
||||
Some((&old_events, delayed_old_sequence)),
|
||||
delayed_old_activity,
|
||||
)
|
||||
.await;
|
||||
|
||||
let sessions = manager.inner.sessions.lock().await;
|
||||
let record = sessions.get(&structured_id).unwrap();
|
||||
assert_eq!(record.session.activity, ActivityState::Idle);
|
||||
let watermark = record.structured_activity_watermark.as_ref().unwrap();
|
||||
assert_eq!(watermark.sequence, new_sequence);
|
||||
assert!(watermark.stream.ptr_eq(&Arc::downgrade(&replacement)));
|
||||
assert!(Arc::ptr_eq(
|
||||
record.acp_events.as_ref().unwrap(),
|
||||
&replacement
|
||||
));
|
||||
}
|
||||
|
||||
/// A handle that can never append *or* roll back: opened read-only, so
|
||||
/// both `write_all` and the rollback `truncate` fail with the OS's own
|
||||
/// error (`ftruncate` requires a writable fd too) instead of a
|
||||
|
||||
@@ -90,6 +90,7 @@ impl StructuredPane {
|
||||
|
||||
let viewport = usize::from(area.height);
|
||||
let max_scroll = lines.len().saturating_sub(viewport);
|
||||
state.scroll = reconcile_scroll(&state.scroll, &state.line_rows, &lines);
|
||||
if state.follow_selection {
|
||||
if let Some(selected) = state.selected.as_deref() {
|
||||
let first = lines
|
||||
@@ -138,6 +139,7 @@ impl StructuredPane {
|
||||
Rect::new(area.x, area.y + offset as u16, area.width, 1),
|
||||
);
|
||||
}
|
||||
state.line_rows = lines.iter().map(|line| line.row_id.clone()).collect();
|
||||
}
|
||||
|
||||
fn render_projection_status(&self, f: &mut Frame, area: Rect, state: &StructuredState) {
|
||||
@@ -214,6 +216,96 @@ fn error_line(text: &str) -> VisualLine {
|
||||
}
|
||||
}
|
||||
|
||||
/// Translate `scroll` — a raw line index into `old_rows` (the previous
|
||||
/// render's row-per-line layout) — into the equivalent index into `lines`
|
||||
/// (this render's freshly rebuilt layout), anchored on row identity rather
|
||||
/// than raw position. A row's wrapped lines above or intersecting the
|
||||
/// viewport growing, shrinking, or moving index therefore shifts `scroll`
|
||||
/// along with it instead of leaving the viewport looking at different
|
||||
/// content. Falls back to the nearest surviving neighbour row when the
|
||||
/// anchor row itself is gone, and to the raw index (clamped) when nothing
|
||||
/// nearby survived either.
|
||||
fn reconcile_scroll(scroll: &usize, old_rows: &[Option<String>], lines: &[VisualLine]) -> usize {
|
||||
if old_rows.is_empty() {
|
||||
return *scroll;
|
||||
}
|
||||
let old_index = (*scroll).min(old_rows.len() - 1);
|
||||
let anchor = old_rows[old_index].clone();
|
||||
match anchor {
|
||||
Some(id) => match find_row_block(lines, &id) {
|
||||
Some((start, len)) => {
|
||||
start + (old_index - block_start(old_rows, old_index)).min(len - 1)
|
||||
}
|
||||
None => fallback_after_removal(old_rows, lines, old_index),
|
||||
},
|
||||
None => {
|
||||
// Untagged tail lines (connecting/dead/error) carry no row identity;
|
||||
// approximate by preserving distance from the end of the transcript.
|
||||
let distance_from_end = old_rows.len() - old_index;
|
||||
lines.len().saturating_sub(distance_from_end)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Index of the first line belonging to `id`, and how many lines it spans.
|
||||
/// A row's wrapped lines are always contiguous in `lines` — `build_lines`
|
||||
/// emits them as one run per row — so a single forward scan suffices.
|
||||
fn find_row_block(lines: &[VisualLine], id: &str) -> Option<(usize, usize)> {
|
||||
let start = lines
|
||||
.iter()
|
||||
.position(|line| line.row_id.as_deref() == Some(id))?;
|
||||
let mut end = start;
|
||||
while end + 1 < lines.len() && lines[end + 1].row_id.as_deref() == Some(id) {
|
||||
end += 1;
|
||||
}
|
||||
Some((start, end - start + 1))
|
||||
}
|
||||
|
||||
/// First index of the contiguous run that `index` sits in within `rows`.
|
||||
fn block_start(rows: &[Option<String>], index: usize) -> usize {
|
||||
let mut start = index;
|
||||
while start > 0 && rows[start - 1] == rows[index] {
|
||||
start -= 1;
|
||||
}
|
||||
start
|
||||
}
|
||||
|
||||
/// The anchor row is gone (removed, or replaced wholesale by a fresh
|
||||
/// snapshot). Search outward from its old position, nearest first, for a
|
||||
/// still-live neighbour row and land on its first line; if none of the old
|
||||
/// layout's rows survived, fall back to the raw old index clamped into the
|
||||
/// new layout.
|
||||
fn fallback_after_removal(
|
||||
old_rows: &[Option<String>],
|
||||
lines: &[VisualLine],
|
||||
old_index: usize,
|
||||
) -> usize {
|
||||
let len = old_rows.len();
|
||||
let mut distance = 1usize;
|
||||
loop {
|
||||
if distance > old_index && old_index + distance >= len {
|
||||
return old_index.min(lines.len().saturating_sub(1));
|
||||
}
|
||||
if distance <= old_index {
|
||||
if let Some((start, _)) = old_rows[old_index - distance]
|
||||
.as_ref()
|
||||
.and_then(|id| find_row_block(lines, id))
|
||||
{
|
||||
return start;
|
||||
}
|
||||
}
|
||||
if old_index + distance < len {
|
||||
if let Some((start, _)) = old_rows[old_index + distance]
|
||||
.as_ref()
|
||||
.and_then(|id| find_row_block(lines, id))
|
||||
{
|
||||
return start;
|
||||
}
|
||||
}
|
||||
distance += 1;
|
||||
}
|
||||
}
|
||||
|
||||
fn build_lines(state: &StructuredState, width: usize) -> Vec<VisualLine> {
|
||||
let mut out = Vec::new();
|
||||
for row in &state.rows {
|
||||
@@ -1272,4 +1364,213 @@ mod tests {
|
||||
assert!(text.contains("adapter exited"), "{text}");
|
||||
assert!(text.contains("request failed"), "{text}");
|
||||
}
|
||||
|
||||
fn test_pane() -> StructuredPane {
|
||||
StructuredPane {
|
||||
handle: StructuredHandle::test_handle(StructuredState::default()),
|
||||
focused: true,
|
||||
mode: Mode::Normal,
|
||||
session_status: SessionStatus::Running,
|
||||
activity_detail: None,
|
||||
}
|
||||
}
|
||||
|
||||
fn numbered_rows(state: &mut StructuredState, count: usize) {
|
||||
for n in 0..count {
|
||||
state.rows.push(row(
|
||||
&format!("r{n}"),
|
||||
TranscriptRowKind::AgentText,
|
||||
json!({"content":{"type":"text","text":format!("line {n}")}}),
|
||||
));
|
||||
}
|
||||
}
|
||||
|
||||
fn grow_row(state: &mut StructuredState, id: &str) {
|
||||
let index = state.rows.iter().position(|r| r.id == id).unwrap();
|
||||
state.rows[index] = row(
|
||||
id,
|
||||
TranscriptRowKind::AgentText,
|
||||
json!({"content":{"type":"text","text":"a very long streaming reply that keeps growing and will wrap across several lines now"}}),
|
||||
);
|
||||
}
|
||||
|
||||
fn render_transcript_lines(
|
||||
pane: &StructuredPane,
|
||||
state: &mut StructuredState,
|
||||
width: u16,
|
||||
height: u16,
|
||||
) -> Vec<String> {
|
||||
let mut terminal = Terminal::new(TestBackend::new(width, height)).unwrap();
|
||||
terminal
|
||||
.draw(|frame| pane.render_transcript(frame, frame.area(), state))
|
||||
.unwrap();
|
||||
let buffer = terminal.backend().buffer().clone();
|
||||
(0..height)
|
||||
.map(|y| {
|
||||
(0..width)
|
||||
.map(|x| buffer[(x, y)].symbol())
|
||||
.collect::<String>()
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn row_growing_above_the_viewport_keeps_the_visual_anchor() {
|
||||
let pane = test_pane();
|
||||
let mut state = StructuredState::default();
|
||||
state.follow_selection = false;
|
||||
numbered_rows(&mut state, 20);
|
||||
state.scroll = 10;
|
||||
|
||||
let before = render_transcript_lines(&pane, &mut state, 30, 5);
|
||||
assert!(before[0].contains("line 10"), "{before:?}");
|
||||
|
||||
grow_row(&mut state, "r3");
|
||||
let after = render_transcript_lines(&pane, &mut state, 30, 5);
|
||||
assert!(
|
||||
after[0].contains("line 10"),
|
||||
"a row growing above the viewport must not shift what's on screen: {after:?}"
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn appending_a_row_below_the_viewport_keeps_the_visual_anchor() {
|
||||
let pane = test_pane();
|
||||
let mut state = StructuredState::default();
|
||||
state.follow_selection = false;
|
||||
numbered_rows(&mut state, 20);
|
||||
state.scroll = 10;
|
||||
|
||||
let before = render_transcript_lines(&pane, &mut state, 30, 5);
|
||||
assert!(before[0].contains("line 10"), "{before:?}");
|
||||
|
||||
state.rows.push(row(
|
||||
"r20",
|
||||
TranscriptRowKind::AgentText,
|
||||
json!({"content":{"type":"text","text":"line 20"}}),
|
||||
));
|
||||
let after = render_transcript_lines(&pane, &mut state, 30, 5);
|
||||
assert_eq!(before, after, "growth below the viewport must not move it");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn removing_a_row_above_the_viewport_keeps_the_visual_anchor() {
|
||||
let pane = test_pane();
|
||||
let mut state = StructuredState::default();
|
||||
state.follow_selection = false;
|
||||
numbered_rows(&mut state, 20);
|
||||
state.scroll = 10;
|
||||
|
||||
let before = render_transcript_lines(&pane, &mut state, 30, 5);
|
||||
assert!(before[0].contains("line 10"), "{before:?}");
|
||||
|
||||
state.rows.retain(|r| r.id != "r3");
|
||||
let after = render_transcript_lines(&pane, &mut state, 30, 5);
|
||||
assert!(
|
||||
after[0].contains("line 10"),
|
||||
"a row removed above the viewport must not shift what's on screen: {after:?}"
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn removing_the_anchor_row_falls_back_to_the_nearest_surviving_neighbor() {
|
||||
let pane = test_pane();
|
||||
let mut state = StructuredState::default();
|
||||
state.follow_selection = false;
|
||||
numbered_rows(&mut state, 20);
|
||||
state.scroll = 10;
|
||||
|
||||
let before = render_transcript_lines(&pane, &mut state, 30, 5);
|
||||
assert!(before[0].contains("line 10"), "{before:?}");
|
||||
|
||||
state.rows.retain(|r| r.id != "r10");
|
||||
let after = render_transcript_lines(&pane, &mut state, 30, 5);
|
||||
assert!(
|
||||
after[0].contains("line 9"),
|
||||
"removing the anchor row should fall back to its nearest surviving neighbor: {after:?}"
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn patching_a_row_above_the_viewport_keeps_the_visual_anchor() {
|
||||
let pane = test_pane();
|
||||
let mut state = StructuredState::default();
|
||||
state.follow_selection = false;
|
||||
numbered_rows(&mut state, 20);
|
||||
state.scroll = 10;
|
||||
|
||||
render_transcript_lines(&pane, &mut state, 30, 5);
|
||||
// Simulate a `TranscriptDelta::Patch` on a collapsed tool row above the
|
||||
// viewport expanding into a multi-line diff.
|
||||
let index = state.rows.iter().position(|r| r.id == "r5").unwrap();
|
||||
state.rows[index] = row(
|
||||
"r5",
|
||||
TranscriptRowKind::ToolDiff,
|
||||
json!({"title":"Edit(x)","content":[{"type":"diff","path":"x","oldText":"a","newText":"a\nb\nc\nd"}]}),
|
||||
);
|
||||
let after = render_transcript_lines(&pane, &mut state, 30, 5);
|
||||
assert!(
|
||||
after[0].contains("line 10"),
|
||||
"a patched row above the viewport must not shift what's on screen: {after:?}"
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn narrow_width_reconciles_without_panicking() {
|
||||
let pane = test_pane();
|
||||
let mut state = StructuredState::default();
|
||||
state.follow_selection = false;
|
||||
numbered_rows(&mut state, 20);
|
||||
state.scroll = 10;
|
||||
|
||||
render_transcript_lines(&pane, &mut state, 1, 3);
|
||||
grow_row(&mut state, "r3");
|
||||
render_transcript_lines(&pane, &mut state, 1, 3);
|
||||
assert!(state.scroll <= state.line_rows.len());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn follow_selection_without_a_selection_stays_pinned_to_the_live_edge() {
|
||||
let pane = test_pane();
|
||||
let mut state = StructuredState::default();
|
||||
state.follow_selection = true;
|
||||
state.selected = None;
|
||||
numbered_rows(&mut state, 20);
|
||||
|
||||
let before = render_transcript_lines(&pane, &mut state, 30, 5);
|
||||
assert!(before.last().unwrap().contains("line 19"), "{before:?}");
|
||||
|
||||
state.rows.push(row(
|
||||
"r20",
|
||||
TranscriptRowKind::AgentText,
|
||||
json!({"content":{"type":"text","text":"line 20"}}),
|
||||
));
|
||||
let after = render_transcript_lines(&pane, &mut state, 30, 5);
|
||||
assert!(
|
||||
after.last().unwrap().contains("line 20"),
|
||||
"bottom-follow must track the live edge as rows are appended: {after:?}"
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn follow_selection_keeps_the_selected_row_visible_when_a_row_above_it_grows() {
|
||||
let pane = test_pane();
|
||||
let mut state = StructuredState::default();
|
||||
state.follow_selection = true;
|
||||
numbered_rows(&mut state, 20);
|
||||
state.selected = Some("r15".into());
|
||||
|
||||
let before = render_transcript_lines(&pane, &mut state, 30, 5);
|
||||
assert!(
|
||||
before.iter().any(|line| line.contains("line 15")),
|
||||
"{before:?}"
|
||||
);
|
||||
|
||||
grow_row(&mut state, "r3");
|
||||
let after = render_transcript_lines(&pane, &mut state, 30, 5);
|
||||
assert!(
|
||||
after.iter().any(|line| line.contains("line 15")),
|
||||
"the selected row must stay visible while follow_selection is on: {after:?}"
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -25,6 +25,12 @@ pub struct StructuredState {
|
||||
pub selected: Option<String>,
|
||||
pub expanded: HashSet<String>,
|
||||
pub scroll: usize,
|
||||
/// Row id per rendered line from the last render pass, parallel to that
|
||||
/// pass's `lines`. Lets the next render translate `scroll` — a raw index
|
||||
/// into that now-stale layout — back into a row identity before mapping
|
||||
/// it onto the freshly rebuilt layout, so growth/shrinkage above the
|
||||
/// viewport shifts indices without shifting what's on screen.
|
||||
pub(crate) line_rows: Vec<Option<String>>,
|
||||
pub follow_selection: bool,
|
||||
pub composer: TextInput,
|
||||
pub error: Option<String>,
|
||||
@@ -42,6 +48,7 @@ impl Default for StructuredState {
|
||||
selected: None,
|
||||
expanded: HashSet::new(),
|
||||
scroll: 0,
|
||||
line_rows: Vec::new(),
|
||||
follow_selection: true,
|
||||
composer: TextInput::default(),
|
||||
error: None,
|
||||
|
||||
Reference in New Issue
Block a user