mirror of
https://github.com/openai/codex.git
synced 2026-11-23 23:10:47 +00:00
Automatically resume disconnected cloud conversations in the TUI (#63211)
## Why A dropped cloud stream can leave the displayed conversation without replies that were saved while the terminal was disconnected. ## What changed Reattach the displayed cloud conversation in the background when no user turn is pending or running and no question answers need to be restored. Keep the draft and queued messages while sending is paused. Check that paginated history is complete and includes the conversation already shown before applying it and accepting live events. If history cannot be verified, keep sending paused and show an error. ## Testing Add regression coverage for preserving drafts and queued messages, recovering delayed history, rejecting incomplete history, and switching conversations during recovery. GitOrigin-RevId: bc38958170ea7905452cdc4fbadc838b53400641
This commit is contained in:
committed by
copyberry
parent
4ae20b9f28
commit
44848822b1
@@ -666,7 +666,7 @@ impl App {
|
||||
tui,
|
||||
destination,
|
||||
prepared,
|
||||
/*switched_backend*/ true,
|
||||
super::session_lifecycle::ResumeOrigin::BackendSwitch,
|
||||
)
|
||||
.await?;
|
||||
tui.frame_requester().schedule_frame();
|
||||
|
||||
@@ -4557,6 +4557,7 @@ impl App {
|
||||
app_server: &mut AppServerSession,
|
||||
mode: ExitMode,
|
||||
) -> AppRunControl {
|
||||
self.reconnect.cloud_resume = None;
|
||||
for (request_id, (source, task)) in self.dynamic_tool_tasks.drain() {
|
||||
if ThreadId::from_string(&source)
|
||||
.is_ok_and(|id| self.agents_overview.pending_archives.contains_key(&id))
|
||||
|
||||
@@ -21,6 +21,7 @@ pub(super) struct ReconnectState {
|
||||
pub(super) failed: bool,
|
||||
pub(super) presentation: ReconnectPresentation,
|
||||
pub(super) seen_version_notice: Option<String>,
|
||||
pub(super) cloud_resume: Option<super::resume_preparation::CloudResume>,
|
||||
}
|
||||
|
||||
pub(super) struct Reconnected {
|
||||
|
||||
@@ -5,7 +5,13 @@
|
||||
//! prepared result retains the connection identity and any provider error for read-only history.
|
||||
|
||||
use super::*;
|
||||
use crate::app_server_session::HistoryHydrationScope;
|
||||
use crate::app_server_session::thread_blocks_direct_input;
|
||||
use crate::backend_id::BackendId;
|
||||
use codex_app_server_client::CloudRecoveryRelease;
|
||||
use codex_app_server_client::TypedRequestError;
|
||||
use std::io;
|
||||
use tokio_util::task::AbortOnDropHandle;
|
||||
|
||||
/// Settings retained for a backend that is not currently displayed.
|
||||
#[derive(Clone)]
|
||||
@@ -36,7 +42,342 @@ pub(super) struct PreparedResume {
|
||||
pub(super) provider_error: Option<codex_app_server_protocol::ModelProviderError>,
|
||||
}
|
||||
|
||||
const CLOUD_REQUEST_TIMEOUT: Duration = Duration::from_secs(/*secs*/ 15);
|
||||
const REOPEN_CLOUD_THREAD: &str = "Cloud stream ended. Reopen the conversation to reconnect.";
|
||||
|
||||
#[derive(Debug, thiserror::Error)]
|
||||
enum CloudHistoryCheck {
|
||||
#[error("Cloud could not restore the reply stream in time. Your draft is still here.")]
|
||||
LockTimedOut,
|
||||
#[error(
|
||||
"Cloud conversation history is unavailable. Sending is paused and your draft is saved here."
|
||||
)]
|
||||
Unavailable,
|
||||
}
|
||||
|
||||
#[derive(PartialEq)]
|
||||
enum ResumePhase {
|
||||
Preparing,
|
||||
Installing,
|
||||
InstallInterruptedByNavigation,
|
||||
}
|
||||
|
||||
pub(super) struct CloudResume {
|
||||
pub(super) backend_id: BackendId,
|
||||
pub(super) thread_id: ThreadId,
|
||||
store: Arc<Mutex<super::thread_events::ThreadEventStore>>,
|
||||
_input_hold: Arc<()>,
|
||||
phase: ResumePhase,
|
||||
pub(super) task: AbortOnDropHandle<CloudResumeOutcome>,
|
||||
}
|
||||
|
||||
impl CloudResume {
|
||||
pub(super) fn installing(&self) -> bool {
|
||||
self.phase != ResumePhase::Preparing
|
||||
}
|
||||
}
|
||||
|
||||
pub(super) type CloudResumeOutcome = Result<(
|
||||
Box<(
|
||||
AppServerStartedThread,
|
||||
crate::app_server_session::AttachmentMetadata,
|
||||
)>,
|
||||
Option<CloudRecoveryRelease>,
|
||||
)>;
|
||||
|
||||
impl App {
|
||||
pub(super) fn start_cloud_resume(&mut self, app_server: &AppServerSession) {
|
||||
let backend_id = app_server.backend_id();
|
||||
let Some(thread_id) = self.current_displayed_thread_id() else {
|
||||
return;
|
||||
};
|
||||
if self.reconnect.offline || self.reconnect.cloud_resume.is_some() {
|
||||
return;
|
||||
}
|
||||
let (AppServerRequestHandle::Cloud(handle), Some(channel)) = (
|
||||
app_server.request_handle(),
|
||||
self.thread_event_channels.get(&thread_id),
|
||||
) else {
|
||||
return;
|
||||
};
|
||||
if self.chat_widget.is_user_turn_pending_or_running() {
|
||||
return;
|
||||
}
|
||||
if self.chat_widget.needs_question_answer_history() {
|
||||
return;
|
||||
}
|
||||
let mut view = app_server.attachment_view(thread_id);
|
||||
let config = self.config.clone();
|
||||
let local_settings = self.local_settings.clone();
|
||||
let store = Arc::clone(&channel.store);
|
||||
self.reconnect.cloud_resume = Some(CloudResume {
|
||||
backend_id,
|
||||
thread_id,
|
||||
store: Arc::clone(&store),
|
||||
_input_hold: self.chat_widget.pause_input_for_resume_handoff(),
|
||||
phase: ResumePhase::Preparing,
|
||||
task: AbortOnDropHandle::new(tokio::spawn(async move {
|
||||
let (session, latest, terminal, anchor, evidence) = {
|
||||
let store = tokio::time::timeout(CLOUD_REQUEST_TIMEOUT, store.lock())
|
||||
.await
|
||||
.map_err(|_| CloudHistoryCheck::LockTimedOut)?;
|
||||
let saved = store.turns.iter().flat_map(|turn| {
|
||||
turn.items.iter().map(move |item| {
|
||||
(
|
||||
item.id(),
|
||||
Some(item),
|
||||
item.completed_at_ms.is_some()
|
||||
|| (item.started_at_ms.is_none()
|
||||
&& turn.status == TurnStatus::Completed),
|
||||
)
|
||||
})
|
||||
});
|
||||
let live = store.buffer.iter().filter_map(|event| {
|
||||
let ThreadBufferedEvent::Notification(event) = event else {
|
||||
return None;
|
||||
};
|
||||
match event.as_ref() {
|
||||
ServerNotification::ItemStarted(n) => {
|
||||
Some((n.item.id(), Some(&n.item), false))
|
||||
}
|
||||
ServerNotification::ItemCompleted(n) => {
|
||||
Some((n.item.id(), Some(&n.item), true))
|
||||
}
|
||||
ServerNotification::AgentMessageDelta(n) => {
|
||||
Some((n.item_id.as_str(), None, false))
|
||||
}
|
||||
_ => None,
|
||||
}
|
||||
});
|
||||
let mut order = HashMap::new();
|
||||
let mut evidence = HashMap::new();
|
||||
let mut anchor = None;
|
||||
for (id, item, finished) in saved.chain(live) {
|
||||
let next = order.len();
|
||||
let rank = *order.entry(id.to_owned()).or_insert(next);
|
||||
let Some(item) = item else { continue };
|
||||
let reply = matches!(&item.payload, ThreadItemPayload::AgentMessage { .. });
|
||||
if reply || rank == next {
|
||||
anchor = anchor.max(Some((reply, rank, id)));
|
||||
}
|
||||
if reply && finished {
|
||||
evidence.insert(id.to_owned(), Some(item.clone()));
|
||||
} else if rank == next
|
||||
&& matches!(&item.payload, ThreadItemPayload::UserMessage { .. })
|
||||
{
|
||||
evidence.insert(id.to_owned(), None);
|
||||
}
|
||||
}
|
||||
(
|
||||
store
|
||||
.session
|
||||
.clone()
|
||||
.ok_or_else(|| color_eyre::eyre::eyre!(REOPEN_CLOUD_THREAD))?,
|
||||
store.latest_turn_id.clone(),
|
||||
store.active_turn_id.is_none(),
|
||||
anchor.map(|(_, _, id)| id.to_owned()),
|
||||
evidence,
|
||||
)
|
||||
};
|
||||
let (response, release) = handle
|
||||
.resume_disconnected_thread(
|
||||
thread_id.to_string(),
|
||||
/*require_history*/ false,
|
||||
CLOUD_REQUEST_TIMEOUT,
|
||||
)
|
||||
.await?;
|
||||
let Some(response) =
|
||||
response.filter(|r| r.thread.id == session.thread_id.to_string())
|
||||
else {
|
||||
color_eyre::eyre::bail!(REOPEN_CLOUD_THREAD);
|
||||
};
|
||||
for delay_ms in [0, 500, 1000] {
|
||||
if delay_ms != 0 {
|
||||
tokio::time::sleep(Duration::from_millis(delay_ms)).await;
|
||||
}
|
||||
// Each check starts at the newest saved turn; the client bounds each page.
|
||||
let mut thread = response.thread.clone();
|
||||
thread.turns.clear();
|
||||
view.hydrate_initial_thread_history(
|
||||
&mut thread,
|
||||
/*turn_cursor*/ None,
|
||||
/*item_cursor*/ None,
|
||||
Some(&config),
|
||||
Some(&local_settings),
|
||||
HistoryHydrationScope::CloudRecovery,
|
||||
)
|
||||
.await?;
|
||||
if !view.recovery_history_complete(thread_id) {
|
||||
// A remaining item cursor means we spent the scan budget.
|
||||
// Starting again at the newest item would repeat the same work.
|
||||
if view.has_older_history(thread_id) {
|
||||
break;
|
||||
}
|
||||
continue;
|
||||
}
|
||||
let turns = &mut thread.turns;
|
||||
if latest.as_ref().is_some_and(|id| {
|
||||
!turns.iter().any(|t| {
|
||||
&t.id == id && (!terminal || t.status != TurnStatus::InProgress)
|
||||
})
|
||||
}) {
|
||||
continue;
|
||||
}
|
||||
// A positively unfinished row cannot supersede a completion already shown.
|
||||
for item in turns.iter_mut().flat_map(|turn| &mut turn.items) {
|
||||
if item.started_at_ms.is_some()
|
||||
&& item.completed_at_ms.is_none()
|
||||
&& matches!(&item.payload, ThreadItemPayload::AgentMessage { .. })
|
||||
&& let Some(Some(known)) = evidence.get(item.id())
|
||||
{
|
||||
item.clone_from(known);
|
||||
}
|
||||
}
|
||||
let loaded: HashMap<_, _> = turns
|
||||
.iter()
|
||||
.flat_map(Turn::item_payloads)
|
||||
.map(|item| (item.id(), item))
|
||||
.collect();
|
||||
if anchor
|
||||
.as_ref()
|
||||
.is_some_and(|id| !loaded.contains_key(id.as_str()))
|
||||
|| evidence.iter().any(|(id, known)| match (known, loaded.get(id.as_str())) {
|
||||
(None, Some(_)) => false,
|
||||
(Some(known), Some(ThreadItemPayload::AgentMessage { text, .. })) => {
|
||||
matches!(&known.payload, ThreadItemPayload::AgentMessage {text: prior,..}
|
||||
if prior != text && prior.starts_with(text.as_str()))
|
||||
}
|
||||
_ => true,
|
||||
})
|
||||
{
|
||||
continue;
|
||||
}
|
||||
let started = AppServerStartedThread {
|
||||
session,
|
||||
blocks_direct_input: thread_blocks_direct_input(&thread),
|
||||
turns: thread.turns,
|
||||
task_tools_available: view.task_tools_available(thread_id),
|
||||
};
|
||||
let resume = (started, view.take_attachment_metadata(thread_id));
|
||||
return Ok((Box::new(resume), Some(release)));
|
||||
}
|
||||
Err(CloudHistoryCheck::Unavailable.into())
|
||||
})),
|
||||
});
|
||||
}
|
||||
|
||||
// Selecting a different attachment can close an in-progress install ACK.
|
||||
// Keep its result until the selection succeeds in case the worker already committed it.
|
||||
pub(super) fn interrupt_cloud_resume_for_navigation(&mut self) -> bool {
|
||||
if let Some(attempt) = self.reconnect.cloud_resume.as_mut()
|
||||
&& attempt.installing()
|
||||
{
|
||||
attempt.phase = ResumePhase::InstallInterruptedByNavigation;
|
||||
return false;
|
||||
}
|
||||
self.reconnect.cloud_resume.take().is_some()
|
||||
}
|
||||
|
||||
pub(super) async fn finish_cloud_resume(
|
||||
&mut self,
|
||||
tui: &mut tui::Tui,
|
||||
app_server: &mut AppServerSession,
|
||||
mut attempt: CloudResume,
|
||||
outcome: CloudResumeOutcome,
|
||||
) -> Result<AppRunControl> {
|
||||
let backend_id = attempt.backend_id;
|
||||
let thread_id = attempt.thread_id;
|
||||
if app_server.backend_id() != backend_id
|
||||
|| self.current_displayed_thread_id() != Some(thread_id)
|
||||
|| self.chat_widget.thread_id() != Some(thread_id)
|
||||
|| !self.chat_widget.thread_stream_disconnected
|
||||
|| self.reconnect.offline
|
||||
|| self
|
||||
.thread_event_channels
|
||||
.get(&thread_id)
|
||||
.is_none_or(|channel| {
|
||||
!Arc::ptr_eq(&attempt.store, &channel.store)
|
||||
|| channel.backend_id.is_some_and(|owner| owner != backend_id)
|
||||
})
|
||||
|| self
|
||||
.backend_registry
|
||||
.owner(thread_id)
|
||||
.is_some_and(|owner| owner != backend_id)
|
||||
{
|
||||
return Ok(AppRunControl::Continue);
|
||||
}
|
||||
|
||||
let result = match outcome {
|
||||
Ok((resumed, Some(release))) => {
|
||||
attempt.phase = ResumePhase::Installing;
|
||||
attempt.task = AbortOnDropHandle::new(tokio::spawn(async move {
|
||||
release.install().await?;
|
||||
Ok((resumed, None))
|
||||
}));
|
||||
self.reconnect.cloud_resume = Some(attempt);
|
||||
return Ok(AppRunControl::Continue);
|
||||
}
|
||||
Ok((resumed, None)) => Ok(*resumed),
|
||||
Err(error) if attempt.installing() => Err(error
|
||||
.downcast::<io::Error>()
|
||||
.unwrap_or_else(|_| io::Error::other(REOPEN_CLOUD_THREAD))),
|
||||
Err(error) => Err(match error.downcast::<TypedRequestError>() {
|
||||
Ok(TypedRequestError::Transport { source, .. }) => source,
|
||||
Ok(TypedRequestError::Server { source, .. }) => io::Error::other(source.message),
|
||||
Ok(TypedRequestError::Deserialize { .. }) => io::Error::other(REOPEN_CLOUD_THREAD),
|
||||
Err(error) => match error.downcast::<CloudHistoryCheck>() {
|
||||
Ok(reason) => io::Error::other(reason),
|
||||
Err(_) => io::Error::other(REOPEN_CLOUD_THREAD),
|
||||
},
|
||||
}),
|
||||
};
|
||||
let channel = self.ensure_thread_channel(thread_id);
|
||||
channel.history_may_be_incomplete = true;
|
||||
if let Err(error) = result {
|
||||
if matches!(
|
||||
error.kind(),
|
||||
io::ErrorKind::ConnectionAborted | io::ErrorKind::TimedOut
|
||||
) || (attempt.phase == ResumePhase::InstallInterruptedByNavigation
|
||||
&& error.kind() == io::ErrorKind::BrokenPipe)
|
||||
{
|
||||
// The worker backs off before the next Attach. Keep the draft and queue paused.
|
||||
self.start_cloud_resume(app_server);
|
||||
} else {
|
||||
channel.mark_replay_only();
|
||||
self.chat_widget.pause_unavailable_thread();
|
||||
self.chat_widget.add_error_message(error.to_string());
|
||||
}
|
||||
return Ok(AppRunControl::Continue);
|
||||
}
|
||||
let (thread, metadata) = result?;
|
||||
app_server
|
||||
.install_attachment_metadata(thread_id, metadata, /*observed_receipt*/ false);
|
||||
let accepted_model = self.chat_widget.cloud_picker_selection.clone();
|
||||
let service_tier = self.chat_widget.configured_service_tier();
|
||||
let control = self
|
||||
.activate_prepared_session_from(
|
||||
tui,
|
||||
app_server,
|
||||
PreparedResume {
|
||||
backend_id,
|
||||
config: self.config.clone(),
|
||||
local_settings: self.local_settings.clone(),
|
||||
thread,
|
||||
restored_blank_session: false,
|
||||
read_only: false,
|
||||
history_notice: None,
|
||||
provider_error: None,
|
||||
},
|
||||
super::session_lifecycle::ResumeOrigin::CloudRecovery,
|
||||
)
|
||||
.await?;
|
||||
self.chat_widget.cloud_picker_selection = accepted_model;
|
||||
self.chat_widget.set_service_tier(service_tier);
|
||||
self.sync_active_thread_service_tier_to_cached_session()
|
||||
.await;
|
||||
Ok(control)
|
||||
}
|
||||
|
||||
pub(super) fn backend_settings(&self) -> BackendSettings {
|
||||
BackendSettings {
|
||||
config: self.config.clone(),
|
||||
|
||||
@@ -28,6 +28,13 @@ use codex_app_server_protocol::ThreadPrepareApprovedPlanParams;
|
||||
use codex_model_provider_info::OPENAI_PROVIDER_ID;
|
||||
use std::collections::HashSet;
|
||||
|
||||
#[derive(Clone, Copy, PartialEq, Eq)]
|
||||
pub(super) enum ResumeOrigin {
|
||||
Manual,
|
||||
BackendSwitch,
|
||||
CloudRecovery,
|
||||
}
|
||||
|
||||
#[derive(Clone, Copy)]
|
||||
pub(super) enum ThreadAttachPresentation {
|
||||
/// A primary thread created by thread/start, without inherited history.
|
||||
@@ -1380,6 +1387,7 @@ impl App {
|
||||
// Start a fresh in-memory session while preserving resumability via persisted rollout
|
||||
// history. If an initial message is provided, `enqueue_primary_thread_session` suppresses it
|
||||
// until the new session is configured and any replayed turns have been rendered.
|
||||
let interrupted_recovery = self.interrupt_cloud_resume_for_navigation();
|
||||
let (session_start_source, mut draft) = match start {
|
||||
FreshSessionStart::NewConversation => (
|
||||
None,
|
||||
@@ -1400,6 +1408,7 @@ impl App {
|
||||
.await;
|
||||
match prepared {
|
||||
Ok(prepared) => {
|
||||
self.reconnect.cloud_resume = None;
|
||||
let presentation = if draft.is_some() {
|
||||
ThreadAttachPresentation::FreshWithDraft
|
||||
} else {
|
||||
@@ -1417,6 +1426,9 @@ impl App {
|
||||
}
|
||||
Err(err) => {
|
||||
self.chat_widget.add_error_message(err.to_string());
|
||||
if interrupted_recovery {
|
||||
self.start_cloud_resume(app_server);
|
||||
}
|
||||
if let Some(message) = initial_user_message {
|
||||
self.chat_widget.restore_user_message_to_composer(message);
|
||||
}
|
||||
@@ -1997,6 +2009,7 @@ impl App {
|
||||
if self.reject_pending_permission_root_switch() {
|
||||
return Ok(AppRunControl::Continue);
|
||||
}
|
||||
let interrupted_recovery = self.interrupt_cloud_resume_for_navigation();
|
||||
let prepared = match self
|
||||
.prepare_target_session(
|
||||
tui,
|
||||
@@ -2007,8 +2020,14 @@ impl App {
|
||||
.await
|
||||
{
|
||||
Ok(prepared) => prepared,
|
||||
Err(control) => return Ok(control),
|
||||
Err(control) => {
|
||||
if interrupted_recovery {
|
||||
self.start_cloud_resume(app_server);
|
||||
}
|
||||
return Ok(control);
|
||||
}
|
||||
};
|
||||
self.reconnect.cloud_resume = None;
|
||||
self.activate_prepared_session(tui, app_server, prepared)
|
||||
.await
|
||||
}
|
||||
@@ -2018,6 +2037,22 @@ impl App {
|
||||
tui: &mut tui::Tui,
|
||||
app_server: &mut AppServerSession,
|
||||
prepared: super::resume_preparation::PreparedResume,
|
||||
) -> Result<AppRunControl> {
|
||||
crate::boxed_future!(self.activate_prepared_session_from(
|
||||
tui,
|
||||
app_server,
|
||||
prepared,
|
||||
ResumeOrigin::Manual
|
||||
))
|
||||
.await
|
||||
}
|
||||
|
||||
pub(super) async fn activate_prepared_session_from(
|
||||
&mut self,
|
||||
tui: &mut tui::Tui,
|
||||
app_server: &mut AppServerSession,
|
||||
prepared: super::resume_preparation::PreparedResume,
|
||||
origin: ResumeOrigin,
|
||||
) -> Result<AppRunControl> {
|
||||
if prepared.backend_id != app_server.backend_id() {
|
||||
self.add_session_picker_error(
|
||||
@@ -2028,10 +2063,8 @@ impl App {
|
||||
}
|
||||
let handoff = self.chat_widget.pause_input_for_resume_handoff();
|
||||
let _handoff = self.prepare_resume_handoff(tui, handoff).await?;
|
||||
self.activate_prepared_session_after_clear(
|
||||
tui, app_server, prepared, /*switched_backend*/ false,
|
||||
)
|
||||
.await
|
||||
self.activate_prepared_session_after_clear(tui, app_server, prepared, origin)
|
||||
.await
|
||||
}
|
||||
|
||||
pub(super) async fn prepare_resume_handoff(
|
||||
@@ -2056,8 +2089,9 @@ impl App {
|
||||
tui: &mut tui::Tui,
|
||||
app_server: &mut AppServerSession,
|
||||
prepared: super::resume_preparation::PreparedResume,
|
||||
switched_backend: bool,
|
||||
origin: ResumeOrigin,
|
||||
) -> Result<AppRunControl> {
|
||||
let switched_backend = origin == ResumeOrigin::BackendSwitch;
|
||||
let super::resume_preparation::PreparedResume {
|
||||
backend_id,
|
||||
config: resume_config,
|
||||
@@ -2080,8 +2114,13 @@ impl App {
|
||||
let same_thread =
|
||||
!switched_backend && self.chat_widget.thread_id() == Some(resumed_thread_id);
|
||||
let refreshing_history = same_thread
|
||||
&& !was_reconnecting
|
||||
&& owned_channel.is_some_and(|channel| channel.history_may_be_incomplete);
|
||||
&& owned_channel.is_some_and(|channel| {
|
||||
if origin == ResumeOrigin::CloudRecovery {
|
||||
was_reconnecting || channel.history_may_be_incomplete
|
||||
} else {
|
||||
!was_reconnecting && channel.history_may_be_incomplete
|
||||
}
|
||||
});
|
||||
let retained_input = (same_thread
|
||||
&& owned_channel.is_some()
|
||||
&& (refreshing_history
|
||||
@@ -2142,8 +2181,9 @@ impl App {
|
||||
.await
|
||||
{
|
||||
Ok(()) => {
|
||||
self.ensure_thread_channel(resumed_thread_id)
|
||||
.history_may_be_incomplete = false;
|
||||
let channel = self.ensure_thread_channel(resumed_thread_id);
|
||||
channel.history_may_be_incomplete = false;
|
||||
channel.recovered_cloud_history = origin == ResumeOrigin::CloudRecovery;
|
||||
self.remember_attached_host_project(app_server);
|
||||
let resumed_turn_running = !read_only
|
||||
&& self
|
||||
|
||||
@@ -1470,6 +1470,13 @@ See the Codex keymap documentation for supported actions and examples."
|
||||
break Err(err.into());
|
||||
}
|
||||
}
|
||||
if app.reconnect.cloud_resume.as_ref().is_some_and(|resume| {
|
||||
resume.backend_id != displayed_owner
|
||||
|| Some(resume.thread_id) != app.current_displayed_thread_id()
|
||||
|| app.reconnect.offline
|
||||
}) {
|
||||
app.reconnect.cloud_resume = None;
|
||||
}
|
||||
// Process archive completions before the picker can list or mutate those threads.
|
||||
if app.pending_open_resume_picker && app.agents_overview.pending_archives.is_empty()
|
||||
{
|
||||
@@ -1561,7 +1568,14 @@ See the Codex keymap documentation for supported actions and examples."
|
||||
// Replay queues history and operations. A buffered closure must not switch
|
||||
// widgets before those app events have been applied.
|
||||
let has_pending_app_events = !app_event_rx.is_empty();
|
||||
// An installed stream can emit events before the install result is consumed.
|
||||
// Apply the recovered history before accepting those events.
|
||||
let paused_backend = ((app.reconnect.offline && !app.pending_startup_thread_start)
|
||||
|| app
|
||||
.reconnect
|
||||
.cloud_resume
|
||||
.as_ref()
|
||||
.is_some_and(super::resume_preparation::CloudResume::installing)
|
||||
|| (app.awaiting_side_replay(tui) && has_pending_app_events)
|
||||
|| (!matches!(app.app_server_target, AppServerTarget::Embedded)
|
||||
&& has_pending_app_events))
|
||||
@@ -1820,6 +1834,24 @@ See the Codex keymap documentation for supported actions and examples."
|
||||
}
|
||||
AppRunControl::Continue
|
||||
}
|
||||
result = async {
|
||||
match app.reconnect.cloud_resume.as_mut() {
|
||||
Some(resume) => (&mut resume.task).await,
|
||||
None => std::future::pending().await,
|
||||
}
|
||||
}, if app.reconnect.cloud_resume.is_some() && !has_pending_app_events => {
|
||||
let Some(attempt) = app.reconnect.cloud_resume.take() else { continue };
|
||||
let outcome = result.unwrap_or_else(|error| Err(error.into()));
|
||||
match Box::pin(app.finish_cloud_resume(
|
||||
tui,
|
||||
backends.session_at_mut(displayed_session),
|
||||
attempt,
|
||||
outcome,
|
||||
)).await {
|
||||
Ok(control) => control,
|
||||
Err(err) => break Err(err),
|
||||
}
|
||||
}
|
||||
(reconnect_owner, result) = async { match reconnect.as_mut() { Some((owner, future)) => (*owner, future.await), None => std::future::pending().await } }, if reconnect.is_some() && !has_pending_app_events => {
|
||||
reconnect = None;
|
||||
match result {
|
||||
@@ -1975,6 +2007,7 @@ See the Codex keymap documentation for supported actions and examples."
|
||||
};
|
||||
// Let the pending terminal poll unwind while the app server shuts down.
|
||||
tui.pause_events();
|
||||
app.reconnect.cloud_resume = None;
|
||||
// Skip pending inference on exit. Give the fallback writes a bounded chance
|
||||
// to finish before closing the connections they use.
|
||||
if app.cloud_title_shutdown.send(()).is_ok()
|
||||
|
||||
@@ -234,6 +234,302 @@ async fn cloud_enter_recovers_drafts_from_server_receipts() -> Result<()> {
|
||||
Ok(())
|
||||
}
|
||||
|
||||
async fn drive_automatic_recovery<F: std::future::Future>(
|
||||
future: F,
|
||||
commands: &mut tokio::sync::mpsc::Receiver<codex_app_server_client::CloudCommand>,
|
||||
) -> F::Output {
|
||||
tokio::pin!(future);
|
||||
loop {
|
||||
tokio::select! {
|
||||
value = &mut future => return value,
|
||||
Some(command) = commands.recv() => {
|
||||
let codex_app_server_client::CloudOperation::Request(request) = command.operation else {
|
||||
panic!("unexpected submission during automatic recovery");
|
||||
};
|
||||
let value = match *request {
|
||||
ClientRequest::ThreadLoadedList { .. } => serde_json::json!({"data":[],"nextCursor":null}),
|
||||
ClientRequest::ThreadGoalGet { .. } => serde_json::json!({"goal":null}),
|
||||
ClientRequest::ThreadUnsubscribe { .. } => serde_json::json!({"status":"unsubscribed"}),
|
||||
_ => panic!("unexpected request during automatic recovery"),
|
||||
};
|
||||
command.response.send(Ok(Ok(value))).unwrap();
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn quiet_cloud_recovery_keeps_the_draft() -> Result<()> {
|
||||
use codex_app_server_client::CLOUD_RECOVERY_NETWORK_BLOCKED;
|
||||
use codex_app_server_client::CloudRecoverySignInChanged;
|
||||
#[derive(Clone, Copy, PartialEq)]
|
||||
enum HistoryCase {
|
||||
Unchanged,
|
||||
SwitchThread,
|
||||
Changed,
|
||||
RepeatedCursor,
|
||||
ScanLimit,
|
||||
DelayedHistory,
|
||||
PersistentEmpty,
|
||||
SignInChanged,
|
||||
GenericServer,
|
||||
InvalidRequest,
|
||||
NetworkBlocked,
|
||||
}
|
||||
use HistoryCase::*;
|
||||
for case in [
|
||||
Unchanged,
|
||||
SwitchThread,
|
||||
Changed,
|
||||
RepeatedCursor,
|
||||
ScanLimit,
|
||||
DelayedHistory,
|
||||
PersistentEmpty,
|
||||
SignInChanged,
|
||||
GenericServer,
|
||||
InvalidRequest,
|
||||
NetworkBlocked,
|
||||
] {
|
||||
let destination = (case == SwitchThread).then(ThreadId::new);
|
||||
let (mut app, mut events, mut ops) = make_test_app_with_channels().await;
|
||||
let id = ThreadId::new();
|
||||
app.app_server_target = AppServerTarget::Cloud;
|
||||
if case == ScanLimit {
|
||||
app.local_settings.transcript_mode = crate::transcript_mode::TranscriptMode::Terminal;
|
||||
}
|
||||
let saved_turns = if matches!(case, PersistentEmpty | ScanLimit) {
|
||||
vec![test_turn("already-seen", TurnStatus::Completed, Vec::new())]
|
||||
} else {
|
||||
Vec::new()
|
||||
};
|
||||
app.enqueue_primary_thread_session(
|
||||
test_thread_session(id, app.config.cwd.to_path_buf()),
|
||||
saved_turns.clone(),
|
||||
)
|
||||
.await?;
|
||||
let (client, mut commands, _events) =
|
||||
codex_app_server_client::CloudClient::channel(/*capacity*/ 1);
|
||||
let mut server = AppServerSession::new(
|
||||
crate::backend_id::BackendId::new(),
|
||||
codex_app_server_client::AppServerClient::Cloud(client),
|
||||
crate::ThreadParamsMode::Cloud,
|
||||
);
|
||||
app.chat_widget.thread_stream_disconnected = true;
|
||||
app.chat_widget.apply_external_edit("queued prompt".into());
|
||||
app.chat_widget
|
||||
.handle_key_event(KeyEvent::from(KeyCode::Enter));
|
||||
app.chat_widget.apply_external_edit("unsent draft".into());
|
||||
let mut tui = crate::tui::test_support::make_test_tui()?;
|
||||
tokio::time::pause();
|
||||
app.start_cloud_resume(&server);
|
||||
// Suspend after losing the connection. Only the recovery task wakes the UI.
|
||||
let stalled = commands.recv().await.unwrap();
|
||||
tokio::time::advance(Duration::from_secs(/*secs*/ 300)).await;
|
||||
let mut attempt = app.reconnect.cloud_resume.take().unwrap();
|
||||
let outcome =
|
||||
tokio::time::timeout(Duration::from_secs(/*secs*/ 1), &mut attempt.task).await??;
|
||||
assert!(stalled.response.is_closed());
|
||||
app.finish_cloud_resume(&mut tui, &mut server, attempt, outcome)
|
||||
.await?;
|
||||
assert!(app.reconnect.cloud_resume.is_some());
|
||||
assert!(app.chat_widget.thread_stream_disconnected);
|
||||
let command = commands.recv().await.unwrap();
|
||||
let codex_app_server_client::CloudOperation::ResumeDisconnectedThread {
|
||||
release,
|
||||
require_history,
|
||||
..
|
||||
} = command.operation
|
||||
else {
|
||||
panic!("expected idle attachment")
|
||||
};
|
||||
assert!(!require_history);
|
||||
let mut thread = crate::app::agents_overview::tests::overview_thread(
|
||||
id,
|
||||
/*parent_thread_id*/ None,
|
||||
"Current",
|
||||
ThreadStatus::Idle,
|
||||
);
|
||||
thread.cwd = app.config.cwd.clone().into();
|
||||
thread.history_mode = ThreadHistoryMode::Paginated;
|
||||
let response = serde_json::json!({"thread":thread,"model":"gpt-5.5","modelProvider":thread.model_provider,"cwd":thread.cwd,"approvalPolicy":"never","approvalsReviewer":"user","sandbox":{"type":"readOnly"}});
|
||||
command.response.send(Ok(Ok(response))).unwrap();
|
||||
let mut attempt = app.reconnect.cloud_resume.take().unwrap();
|
||||
let mut reads = Vec::new();
|
||||
let mut scanned = 0;
|
||||
let outcome = loop {
|
||||
tokio::select! {
|
||||
outcome = &mut attempt.task => break outcome?,
|
||||
Some(read) = commands.recv() => {
|
||||
let codex_app_server_client::CloudOperation::Request(request) = read.operation else {
|
||||
panic!("expected paginated recovery history");
|
||||
};
|
||||
let response = match *request {
|
||||
ClientRequest::ThreadTurnsList { .. } if case == ScanLimit => {
|
||||
reads.push("turns");
|
||||
serde_json::json!({"data": saved_turns, "nextCursor": null})
|
||||
}
|
||||
ClientRequest::ThreadTurnsList { .. } => {
|
||||
reads.push("turns");
|
||||
let turn = test_turn("missed", TurnStatus::Completed, Vec::new());
|
||||
serde_json::json!({
|
||||
"data": (case == Changed).then_some(turn).into_iter().collect::<Vec<_>>(),
|
||||
"nextCursor": (case == DelayedHistory && reads.len() == 1).then_some("projection-not-ready"),
|
||||
})
|
||||
}
|
||||
ClientRequest::ThreadItemsList { params, .. } if case == ScanLimit => {
|
||||
// Pages of hidden items still count against the scan budget.
|
||||
reads.push("items");
|
||||
scanned += params.limit.unwrap() as usize;
|
||||
serde_json::json!({"data": [], "nextCursor": scanned.to_string()})
|
||||
}
|
||||
ClientRequest::ThreadItemsList { .. } => {
|
||||
reads.push("items");
|
||||
let answer = ThreadItemPayload::UserMessage {
|
||||
id: "new-user-message".into(),
|
||||
client_id: Some("another-client".into()),
|
||||
content: vec![UserInput::Text { text: "Remote follow-up".into(), text_elements: Vec::new() }],
|
||||
};
|
||||
let row = serde_json::json!({"turnId":"missed","item":answer});
|
||||
serde_json::json!({
|
||||
"data": (case == Changed).then_some(row).into_iter().collect::<Vec<_>>(),
|
||||
"nextCursor": (case == RepeatedCursor).then_some("same-page"),
|
||||
})
|
||||
}
|
||||
_ => panic!("expected paginated recovery history"),
|
||||
};
|
||||
// Each page arrives promptly, but the full read takes over 15 seconds.
|
||||
tokio::time::advance(Duration::from_secs(/*secs*/ 10)).await;
|
||||
let server_error = |code, message| Ok(Err(codex_app_server_protocol::JSONRPCErrorError {
|
||||
code,
|
||||
message,
|
||||
data: None,
|
||||
}));
|
||||
let response = match (case, reads.len()) {
|
||||
(SignInChanged, 1) => Err(std::io::Error::other(CloudRecoverySignInChanged)),
|
||||
(GenericServer, 1) => server_error(-32000, CloudRecoverySignInChanged.to_string()),
|
||||
(InvalidRequest, 1) => server_error(-32602, "Recovery history request was rejected".into()),
|
||||
(NetworkBlocked, 1) => server_error(-32000, CLOUD_RECOVERY_NETWORK_BLOCKED.into()),
|
||||
_ => Ok(Ok(response)),
|
||||
};
|
||||
read.response.send(response).unwrap();
|
||||
}
|
||||
}
|
||||
};
|
||||
match case {
|
||||
ScanLimit => {
|
||||
assert_eq!(scanned, crate::app_server_session::HISTORY_ITEM_SCAN_LIMIT);
|
||||
assert_eq!(reads.iter().filter(|&&read| read == "turns").count(), 1);
|
||||
}
|
||||
RepeatedCursor => assert_eq!(reads, ["turns", "items", "items"].repeat(3)),
|
||||
PersistentEmpty => assert_eq!(reads, ["turns", "items"].repeat(3)),
|
||||
SignInChanged | GenericServer | InvalidRequest | NetworkBlocked => {
|
||||
assert_eq!(reads, ["turns"]);
|
||||
}
|
||||
DelayedHistory => assert_eq!(reads, ["turns", "items", "turns", "items"]),
|
||||
Unchanged | SwitchThread | Changed => assert_eq!(reads, ["turns", "items"]),
|
||||
}
|
||||
assert_eq!(
|
||||
app.chat_widget.queued_user_message_texts(),
|
||||
["queued prompt"]
|
||||
);
|
||||
assert!(
|
||||
!std::iter::from_fn(|| ops.try_recv().ok()).any(|op| matches!(op, Op::UserTurn { .. }))
|
||||
);
|
||||
// The UI event handler must return even when the worker withholds its final ACK.
|
||||
tokio::time::timeout(
|
||||
Duration::from_secs(/*secs*/ 1),
|
||||
app.finish_cloud_resume(&mut tui, &mut server, attempt, outcome),
|
||||
)
|
||||
.await??;
|
||||
let installed = if let Ok(ack) = release.await {
|
||||
if let Some(side) = destination {
|
||||
let mut session = test_thread_session(side, app.config.cwd.to_path_buf());
|
||||
session.model_provider_id = app.chat_widget.quota_provider_id().to_owned();
|
||||
app.ensure_thread_channel(side)
|
||||
.store
|
||||
.lock()
|
||||
.await
|
||||
.set_session(session, Vec::new());
|
||||
app.side_threads.insert(side, SideThreadState::new(id));
|
||||
let key = TuiEvent::Key(KeyCode::Backspace.into());
|
||||
boxed_future!(app.handle_tui_event(&mut tui, &mut server, key)).await?;
|
||||
assert_eq!(app.chat_widget.composer_text_with_pending(), "unsent draf");
|
||||
assert_eq!(
|
||||
app.chat_widget.queued_user_message_texts(),
|
||||
["queued prompt"]
|
||||
);
|
||||
let select = app.select_agent_thread(&mut tui, &mut server, side);
|
||||
drive_automatic_recovery(select, &mut commands).await?;
|
||||
}
|
||||
ack.send(Ok(())).unwrap();
|
||||
let mut attempt = app.reconnect.cloud_resume.take().unwrap();
|
||||
let outcome = (&mut attempt.task).await?;
|
||||
drive_automatic_recovery(
|
||||
app.finish_cloud_resume(&mut tui, &mut server, attempt, outcome),
|
||||
&mut commands,
|
||||
)
|
||||
.await?;
|
||||
true
|
||||
} else {
|
||||
false
|
||||
};
|
||||
tokio::time::resume();
|
||||
let must_reopen = !matches!(case, Unchanged | SwitchThread | Changed | DelayedHistory);
|
||||
assert!(app.reconnect.cloud_resume.is_none());
|
||||
assert!(commands.try_recv().is_err());
|
||||
assert_eq!(installed, !must_reopen);
|
||||
assert_eq!(app.chat_widget.thread_stream_disconnected, must_reopen);
|
||||
let app_events: Vec<_> = std::iter::from_fn(|| events.try_recv().ok()).collect();
|
||||
let dispatched = app_events
|
||||
.iter()
|
||||
.filter(|event| matches!(event, AppEvent::CodexOp(Op::UserTurn { .. })))
|
||||
.count();
|
||||
let submitted = std::iter::from_fn(|| ops.try_recv().ok())
|
||||
.filter(|op| matches!(op, Op::UserTurn { .. }))
|
||||
.count()
|
||||
+ dispatched;
|
||||
assert_eq!(
|
||||
submitted,
|
||||
usize::from(!must_reopen && destination.is_none())
|
||||
);
|
||||
if let Some(side) = destination {
|
||||
assert_eq!(app.current_displayed_thread_id(), Some(side));
|
||||
assert_eq!(app.chat_widget.thread_id(), Some(side));
|
||||
continue;
|
||||
}
|
||||
assert_eq!(app.chat_widget.composer_text_with_pending(), "unsent draft");
|
||||
if must_reopen {
|
||||
let rendered = app_events
|
||||
.into_iter()
|
||||
.filter_map(|event| match event {
|
||||
AppEvent::InsertHistoryCell(cell) => {
|
||||
Some(lines_to_single_string(&cell.display_lines(/*width*/ 120)))
|
||||
}
|
||||
_ => None,
|
||||
})
|
||||
.last()
|
||||
.unwrap();
|
||||
insta::allow_duplicates! {
|
||||
match case {
|
||||
InvalidRequest => insta::assert_snapshot!(rendered, @"■ Recovery history request was rejected"),
|
||||
SignInChanged | GenericServer => insta::assert_snapshot!(rendered, @"■ Your cloud sign-in changed or expired. Sign in again to access this conversation."),
|
||||
NetworkBlocked => insta::assert_snapshot!(rendered, @"■ The current network policy blocks cloud reconnection."),
|
||||
RepeatedCursor | PersistentEmpty | ScanLimit => insta::assert_snapshot!(rendered, @"■ Cloud conversation history is unavailable. Sending is paused and your draft is saved here."),
|
||||
Unchanged | SwitchThread | Changed | DelayedHistory => unreachable!(),
|
||||
}
|
||||
}
|
||||
}
|
||||
let store = app.ensure_thread_channel(id).store.lock().await;
|
||||
if case == Changed {
|
||||
assert_eq!(store.turns.len(), 1);
|
||||
assert_eq!(store.turns[0].id, "missed");
|
||||
} else {
|
||||
assert_eq!(store.turns, saved_turns);
|
||||
}
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn cloud_async_question_reply_uses_cloud_admission() -> Result<()> {
|
||||
use codex_app_server_client::CloudOperation;
|
||||
|
||||
@@ -655,6 +655,7 @@ pub(super) struct ThreadEventChannel {
|
||||
pub(super) store: Arc<Mutex<ThreadEventStore>>,
|
||||
/// Live Attach restored delivery without reading the history from the gap.
|
||||
pub(super) history_may_be_incomplete: bool,
|
||||
pub(super) recovered_cloud_history: bool,
|
||||
attachment: ThreadEventAttachment,
|
||||
pub(super) archived: bool,
|
||||
}
|
||||
@@ -668,20 +669,24 @@ impl ThreadEventChannel {
|
||||
store: Arc::new(Mutex::new(ThreadEventStore::new(capacity))),
|
||||
backend_id: None,
|
||||
history_may_be_incomplete: false,
|
||||
recovered_cloud_history: false,
|
||||
attachment: ThreadEventAttachment::Live,
|
||||
archived: false,
|
||||
}
|
||||
}
|
||||
|
||||
pub(super) fn mark_live(&mut self) {
|
||||
self.recovered_cloud_history = false;
|
||||
self.attachment = ThreadEventAttachment::Live;
|
||||
}
|
||||
|
||||
pub(super) fn mark_replay_only(&mut self) {
|
||||
self.recovered_cloud_history = false;
|
||||
self.attachment = ThreadEventAttachment::ReplayOnly;
|
||||
}
|
||||
|
||||
pub(super) fn mark_external_writer(&mut self) {
|
||||
self.recovered_cloud_history = false;
|
||||
self.attachment = ThreadEventAttachment::ExternalWriter;
|
||||
}
|
||||
|
||||
@@ -704,6 +709,7 @@ impl ThreadEventChannel {
|
||||
))),
|
||||
backend_id: None,
|
||||
history_may_be_incomplete: false,
|
||||
recovered_cloud_history: false,
|
||||
attachment: ThreadEventAttachment::Live,
|
||||
archived: false,
|
||||
}
|
||||
|
||||
@@ -1136,12 +1136,52 @@ impl App {
|
||||
pub(super) async fn enqueue_thread_notification(
|
||||
&mut self,
|
||||
thread_id: ThreadId,
|
||||
notification: ServerNotification,
|
||||
mut notification: ServerNotification,
|
||||
) -> Result<()> {
|
||||
self.deliver_background_voice_notification(thread_id, ¬ification);
|
||||
if self.abandoned_side_threads.contains(&thread_id) {
|
||||
return Ok(());
|
||||
}
|
||||
// Cloud attaches before reading history. The live stream can repeat events
|
||||
// from the snapshot, including a completion that would release queued input.
|
||||
if matches!(self.app_server_target, AppServerTarget::Cloud)
|
||||
&& matches!(
|
||||
notification,
|
||||
ServerNotification::TurnStarted(_)
|
||||
| ServerNotification::TurnCompleted(_)
|
||||
| ServerNotification::ItemCompleted(_)
|
||||
)
|
||||
&& self.active_thread_id == Some(thread_id)
|
||||
&& let Some(channel) = self.thread_event_channels.get(&thread_id)
|
||||
&& channel.recovered_cloud_history
|
||||
{
|
||||
let store = channel.store.lock().await;
|
||||
if store.turns.iter().any(|turn| match &mut notification {
|
||||
ServerNotification::TurnStarted(event) => turn.id == event.turn.id,
|
||||
ServerNotification::TurnCompleted(event) => {
|
||||
turn.id == event.turn.id
|
||||
&& turn.status != TurnStatus::InProgress
|
||||
&& turn.status == event.turn.status
|
||||
}
|
||||
ServerNotification::ItemCompleted(event) if turn.id == event.turn_id => {
|
||||
match &mut event.item.payload {
|
||||
ThreadItemPayload::UserMessage { .. } => {
|
||||
turn.items.iter().any(|item| item.id() == event.item.id())
|
||||
}
|
||||
ThreadItemPayload::AgentMessage { questions, .. }
|
||||
if turn.status != TurnStatus::InProgress =>
|
||||
{
|
||||
*questions = None;
|
||||
false
|
||||
}
|
||||
_ => false,
|
||||
}
|
||||
}
|
||||
_ => false,
|
||||
}) {
|
||||
return Ok(());
|
||||
}
|
||||
}
|
||||
self.track_side_chat_title(thread_id, ¬ification);
|
||||
self.notice_sidebar_file_item(thread_id, ¬ification);
|
||||
if self.current_displayed_thread_id() == Some(thread_id)
|
||||
|
||||
@@ -126,6 +126,11 @@ impl App {
|
||||
destination: Option<ThreadId>,
|
||||
) {
|
||||
app_server.task_search.cancel();
|
||||
if self.reconnect.cloud_resume.as_ref().is_some_and(|resume| {
|
||||
resume.backend_id == app_server.backend_id() && Some(resume.thread_id) != destination
|
||||
}) {
|
||||
self.reconnect.cloud_resume = None;
|
||||
}
|
||||
let thread_ids: Vec<_> = self
|
||||
.thread_event_channels
|
||||
.iter()
|
||||
|
||||
@@ -37,6 +37,7 @@ pub(crate) const HISTORY_ITEM_SCAN_LIMIT: usize = 4 * HISTORY_ITEM_PAGE_LIMIT as
|
||||
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
|
||||
pub(crate) enum HistoryHydrationScope<'a> {
|
||||
Initial,
|
||||
CloudRecovery,
|
||||
Complete,
|
||||
/// Include older turns that have no items.
|
||||
FullTranscript,
|
||||
@@ -56,11 +57,14 @@ impl HistoryLoadBudget {
|
||||
local_settings: Option<&crate::local_settings::LocalSettings>,
|
||||
terminal_height: u16,
|
||||
) -> Self {
|
||||
use HistoryHydrationScope::CloudRecovery;
|
||||
|
||||
let transcript_mode = local_settings
|
||||
.map(|settings| settings.transcript_mode)
|
||||
.or_else(|| config.map(|config| LocalSettings::from(config).transcript_mode));
|
||||
if scope == HistoryHydrationScope::Initial
|
||||
&& transcript_mode.is_some_and(crate::transcript_mode::TranscriptMode::is_owned)
|
||||
if scope == CloudRecovery
|
||||
|| (scope == HistoryHydrationScope::Initial
|
||||
&& transcript_mode.is_some_and(crate::transcript_mode::TranscriptMode::is_owned))
|
||||
{
|
||||
// A few screenfuls cover the first viewport and nearby reading without coupling
|
||||
// owned history to terminal scrollback settings, including unlimited scrollback.
|
||||
@@ -73,7 +77,7 @@ impl HistoryLoadBudget {
|
||||
.and_then(|settings| resize_reflow_max_rows(settings.terminal_resize_reflow()));
|
||||
let items = match (scope, config, rows) {
|
||||
(HistoryHydrationScope::Complete | HistoryHydrationScope::FullTranscript, _, _)
|
||||
| (HistoryHydrationScope::ThroughTurn(_), _, _)
|
||||
| (HistoryHydrationScope::ThroughTurn(_) | CloudRecovery, _, _)
|
||||
| (HistoryHydrationScope::Initial, Some(_), None) => None,
|
||||
(HistoryHydrationScope::Initial, Some(_), Some(max_rows)) => {
|
||||
Some(max_rows.saturating_add(HISTORY_ITEM_SCAN_LIMIT))
|
||||
@@ -131,6 +135,18 @@ fn advancing_cursor(
|
||||
next.filter(|next| seen_cursors.insert(next.clone()))
|
||||
}
|
||||
|
||||
fn recovery_cursor(
|
||||
current: Option<&str>,
|
||||
next: Option<String>,
|
||||
seen_cursors: &mut HashSet<String>,
|
||||
incomplete: &mut bool,
|
||||
) -> Option<String> {
|
||||
let continued = next.is_some();
|
||||
let next = advancing_cursor(current, next, seen_cursors);
|
||||
*incomplete |= continued && next.is_none();
|
||||
next
|
||||
}
|
||||
|
||||
fn prepend_older_turns(turns: &mut Vec<Turn>, mut older: Vec<Turn>) {
|
||||
let mut new_ids: HashSet<_> = older.iter().map(|turn| turn.id.clone()).collect();
|
||||
for known in turns.iter() {
|
||||
@@ -163,6 +179,7 @@ pub(crate) struct ThreadHistoryPagination {
|
||||
seen_turn_cursors: HashSet<String>,
|
||||
seen_item_cursors: HashSet<String>,
|
||||
loading_older: bool,
|
||||
incomplete: bool,
|
||||
}
|
||||
|
||||
impl AppServerSession {
|
||||
@@ -201,6 +218,13 @@ impl AppServerSession {
|
||||
Ok(response)
|
||||
}
|
||||
|
||||
/// A recovery snapshot is complete only after all item and turn metadata pages are exhausted.
|
||||
pub(crate) fn recovery_history_complete(&self, thread_id: ThreadId) -> bool {
|
||||
self.history_pagination.get(&thread_id).is_some_and(|page| {
|
||||
!page.incomplete && page.next_item_cursor.is_none() && page.next_turn_cursor.is_none()
|
||||
})
|
||||
}
|
||||
|
||||
pub(crate) fn has_older_history(&self, thread_id: ThreadId) -> bool {
|
||||
self.older_item_cursor(thread_id).is_some()
|
||||
}
|
||||
@@ -309,10 +333,11 @@ impl AppServerSession {
|
||||
state: &mut ThreadHistoryPagination,
|
||||
turns: &mut Vec<Turn>,
|
||||
) -> Result<Vec<(String, ThreadItemPayload)>> {
|
||||
state.next_item_cursor = advancing_cursor(
|
||||
state.next_item_cursor = recovery_cursor(
|
||||
state.next_item_cursor.as_deref(),
|
||||
page.next_cursor,
|
||||
&mut state.seen_item_cursors,
|
||||
&mut state.incomplete,
|
||||
);
|
||||
let mut missing_turn_ids = page
|
||||
.data
|
||||
@@ -332,19 +357,22 @@ impl AppServerSession {
|
||||
let page = self
|
||||
.thread_turns_page(thread_id, Some(cursor.clone()), limit)
|
||||
.await?;
|
||||
state.next_turn_cursor = advancing_cursor(
|
||||
state.next_turn_cursor = recovery_cursor(
|
||||
Some(&cursor),
|
||||
page.next_cursor,
|
||||
&mut state.seen_turn_cursors,
|
||||
&mut state.incomplete,
|
||||
);
|
||||
for turn in &page.data {
|
||||
missing_turn_ids.remove(&turn.id);
|
||||
}
|
||||
prepend_older_turns(turns, page.data);
|
||||
}
|
||||
if let Some(turn) = turns.iter_mut().find(|turn| turn.id == entry.turn_id)
|
||||
&& !turn.items.iter().any(|item| item.id() == entry.item.id())
|
||||
{
|
||||
let Some(turn) = turns.iter_mut().find(|turn| turn.id == entry.turn_id) else {
|
||||
state.incomplete = true;
|
||||
continue;
|
||||
};
|
||||
if !turn.items.iter().any(|item| item.id() == entry.item.id()) {
|
||||
let turn_id = entry.turn_id.clone();
|
||||
let item = ThreadItem::try_from(entry)?;
|
||||
items.push((turn_id, item.payload.clone()));
|
||||
@@ -418,10 +446,11 @@ impl AppServerSession {
|
||||
)
|
||||
.await?;
|
||||
if page.data.is_empty() {
|
||||
state.next_item_cursor = advancing_cursor(
|
||||
state.next_item_cursor = recovery_cursor(
|
||||
state.next_item_cursor.as_deref(),
|
||||
page.next_cursor,
|
||||
&mut state.seen_item_cursors,
|
||||
&mut state.incomplete,
|
||||
);
|
||||
if self.thread_params_mode() == super::ThreadParamsMode::Cloud
|
||||
&& state.next_item_cursor.is_some()
|
||||
@@ -476,14 +505,19 @@ impl AppServerSession {
|
||||
let page = self
|
||||
.thread_turns_page(thread_id, Some(cursor.clone()), HISTORY_TURN_PAGE_LIMIT)
|
||||
.await?;
|
||||
state.next_turn_cursor = advancing_cursor(
|
||||
state.next_turn_cursor = recovery_cursor(
|
||||
Some(&cursor),
|
||||
page.next_cursor,
|
||||
&mut state.seen_turn_cursors,
|
||||
&mut state.incomplete,
|
||||
);
|
||||
prepend_older_turns(&mut thread.turns, page.data);
|
||||
}
|
||||
}
|
||||
if matches!(scope, HistoryHydrationScope::CloudRecovery) && state.incomplete {
|
||||
// Keep incomplete history ineligible even where an older item cursor would suffice.
|
||||
state.next_item_cursor = None;
|
||||
}
|
||||
mark_loaded_interruptions(&mut thread.turns, state.next_item_cursor.as_deref());
|
||||
if config.is_some() {
|
||||
self.history_pagination.insert(thread_id, state);
|
||||
|
||||
@@ -63,6 +63,16 @@ async fn owned_initial_history_stops_after_viewport_or_scan_budget() {
|
||||
[Some(30), Some(100), None, Some(1), None],
|
||||
);
|
||||
|
||||
// Recovery remains bounded even when terminal scrollback is unlimited.
|
||||
config.tui_fullscreen_transcript = false;
|
||||
let recovery = HistoryLoadBudget::new(
|
||||
HistoryHydrationScope::CloudRecovery,
|
||||
Some(&config),
|
||||
Some(&LocalSettings::from(&config)),
|
||||
/*terminal_height*/ 10,
|
||||
);
|
||||
assert_eq!((recovery.rows, recovery.items), (budget.rows, budget.items));
|
||||
|
||||
let complete = HistoryLoadBudget::new(
|
||||
HistoryHydrationScope::Complete,
|
||||
Some(&config),
|
||||
|
||||
@@ -32,6 +32,25 @@ impl ChatWidget {
|
||||
self.bottom_pane.take_question_drafts()
|
||||
}
|
||||
|
||||
pub(crate) fn needs_question_answer_history(&self) -> bool {
|
||||
self.bottom_pane
|
||||
.questions
|
||||
.as_ref()
|
||||
.is_some_and(|questions| questions.unanswered_count() > 0)
|
||||
|| self.has_queued_question_answer()
|
||||
}
|
||||
|
||||
fn has_queued_question_answer(&self) -> bool {
|
||||
self.input_queue
|
||||
.queued_user_messages
|
||||
.iter()
|
||||
.any(|message| message.source == UserMessageSource::QuestionAnswer)
|
||||
|| self
|
||||
.input_queue
|
||||
.rejected_steer_sources
|
||||
.contains(&UserMessageSource::QuestionAnswer)
|
||||
}
|
||||
|
||||
pub(super) fn add_async_questions(
|
||||
&mut self,
|
||||
message_id: &str,
|
||||
|
||||
Reference in New Issue
Block a user