fix(cli-rs): re-hydrate mini's requests and inbox on reconnect

Every hydration (connect, reconnect, resize) now lists the inbox with the messages: listed prompts become pending, so one delivered later prints as the user's row, and the composer's queue follows the list. A reconnect or resize also lists the permissions and forms again, so a request settled while the stream was down leaves the footer, and an idle hydration keeps the blocker's status. The fake server gains DROP, a then event that closes the event streams.
This commit is contained in:
Simon Klee
2026-11-06 06:23:58 +01:00
Unverified
parent 99cadddebf
commit 8e882923a9
7 changed files with 203 additions and 64 deletions
@@ -332,6 +332,14 @@ impl Footers {
self.0.close_route();
}
self.0.sync();
self.hydrate();
}
/// Lists the session's pending requests and the forms of no session at its location again, replacing what
/// was known (`hydrate` on connect, reconnect, and resize).
pub fn hydrate(&self) {
let Some(target) = self.0.target.borrow().clone() else { return };
let (client, session, directory) = (&target.client, target.session.as_str(), target.directory.as_str());
let weak = Rc::downgrade(&self.0);
let input = FormListInput { location: Some(LocationQueryInput { directory: Some(directory.to_owned()) }) };
let globals = client.clone();
@@ -369,6 +377,15 @@ impl Footers {
);
}
/// `blockerStatus`: the status of the request shown, if any.
pub fn blocker_status(&self) -> &'static str {
match self.0.state.borrow().shown {
Some(Shown::Permission(_)) => "awaiting permission",
Some(Shown::Form(_)) => "awaiting form",
_ => "",
}
}
/// A permission or form event of the session, or a form event of no session.
pub fn event(&self, event: &V2Event) {
let inner = &self.0;
+16 -37
View File
@@ -27,7 +27,7 @@ use std::rc::Rc;
use std::time::Duration;
use opencode_api::client::Client;
use opencode_api::generated::{SessionInboxDelivery, SessionInboxItem, V2Event};
use opencode_api::generated::{SessionInboxDelivery, SessionInboxItem, SessionInboxUser, V2Event};
use opencode_local::cli_config::Info;
use opencode_ui::dialog::{DialogKeymap, route_keys};
use opencode_ui::keymap::{Keybinds, KeymapLayer, TuiCommand};
@@ -382,20 +382,12 @@ impl Prompt {
inner.refresh();
}
});
let Some(target) = self.0.target.borrow().clone() else {
return;
};
let weak = Rc::downgrade(&self.0);
let client = target.client.clone();
let session = target.session.clone();
self.0.app.spawn(async move { inbox(&client, &session).await }, move |_, queued| {
if let Some(inner) = weak.upgrade() {
inner.state.borrow_mut().queued = queued;
}
});
if !resume {
return;
}
let Some(target) = self.0.target.borrow().clone() else {
return;
};
let weak = Rc::downgrade(&self.0);
self.0.app.spawn(async move { api::history(&target.client, &target.session).await }, move |_, history| {
if let Some(inner) = weak.upgrade() {
@@ -439,6 +431,18 @@ impl Prompt {
}
}
/// The session's pending prompts as a hydration listed them (`syncPending`).
pub fn set_queued(&self, items: &[SessionInboxUser]) {
self.0.state.borrow_mut().queued = items
.iter()
.map(|item| Queued {
id: item.id.as_str().to_owned(),
delivery: delivery(&item.delivery),
prompt: RunPrompt::from_message(&serde_json::to_value(&item.payload).unwrap_or_default()),
})
.collect();
}
/// A prompt this client admitted (`mergePending`).
pub fn admitted(&self, id: &str, delivery: Delivery, prompt: &RunPrompt) {
let mut state = self.0.state.borrow_mut();
@@ -1685,31 +1689,6 @@ fn delivery(value: &SessionInboxDelivery) -> Delivery {
}
}
/// `session.inbox.list`: the session's pending user prompts.
async fn inbox(client: &Client, session: &str) -> Vec<Queued> {
let input = opencode_api::generated::SessionInboxListInput { session_id: session.into() };
let Ok(call) = Client::session_inbox_list_call(&input) else {
return Vec::new();
};
client
.json::<Value>(call)
.await
.map(|value| {
value["data"]
.as_array()
.into_iter()
.flatten()
.filter(|item| item["type"] == "user")
.map(|item| Queued {
id: item["id"].as_str().unwrap_or_default().to_owned(),
delivery: delivery(&item["delivery"].as_str().unwrap_or_default().into()),
prompt: RunPrompt::from_message(&item["payload"]),
})
.collect()
})
.unwrap_or_default()
}
#[cfg(test)]
mod tests {
use super::*;
+46 -16
View File
@@ -18,12 +18,13 @@ use opencode_api::client::Client;
use opencode_api::error::Error;
use opencode_api::generated::{
ExperimentalSessionWaitInput, LocationQueryInput, MessageListInput, MessageListInputOrder, ModelDefaultInput,
PromptFileAttachment, PromptFileSource, SessionID, SessionInboxItem, SessionInterruptInput,
SessionMessageAssistant, SessionMessageAssistantContentItem as ContentItem, SessionMessageAssistantTool,
SessionMessageAssistantToolState, SessionMessageAssistantToolState as ToolPartState,
SessionMessageAssistantToolTime, SessionMessageCompaction, SessionMessageInfo, SessionMessageShellExit,
SessionMessageShellOutput, SessionMessageToolStateCompleted, SessionMessageToolStateError,
SessionMessageToolStateRunning, SessionMessageToolStateStreaming, SessionStructuredError, V2Event,
PromptFileAttachment, PromptFileSource, SessionID, SessionInboxInfo, SessionInboxItem, SessionInboxListInput,
SessionInboxUser, SessionInterruptInput, SessionMessageAssistant,
SessionMessageAssistantContentItem as ContentItem, SessionMessageAssistantTool, SessionMessageAssistantToolState,
SessionMessageAssistantToolState as ToolPartState, SessionMessageAssistantToolTime, SessionMessageCompaction,
SessionMessageInfo, SessionMessageShellExit, SessionMessageShellOutput, SessionMessageToolStateCompleted,
SessionMessageToolStateError, SessionMessageToolStateRunning, SessionMessageToolStateStreaming,
SessionStructuredError, V2Event,
};
use opentui::app::ProxyError;
use opentui::prelude::*;
@@ -374,6 +375,17 @@ impl Transcript {
output
}
/// The listed pending prompts replace the pending ones (`hydrate`), so each prints once it is delivered.
pub fn inbox(&mut self, items: &[SessionInboxUser]) {
self.pending = items
.iter()
.map(|item| {
let files = item.payload.files.clone().unwrap_or_default();
(item.id.as_str().to_owned(), Pending { text: item.payload.text.clone(), files })
})
.collect();
}
/// Starts a resize replay: events wait until [`Self::replayed`].
pub fn begin_replay(&mut self) {
self.buffered.get_or_insert_with(Vec::new);
@@ -1417,6 +1429,8 @@ pub enum Incoming {
messages: Vec<SessionMessageInfo>,
/// The sessions running now (`session.active`).
active: Vec<String>,
/// The session's pending prompts (`session.inbox.list`).
inbox: Vec<SessionInboxUser>,
},
Event(Box<V2Event>),
/// The stream dropped; it reconnects.
@@ -1451,14 +1465,30 @@ pub async fn active(client: &Client) -> Vec<String> {
client.session_active().await.map(|active| active.into_keys().collect()).unwrap_or_default()
}
/// Lists the messages and the running sessions, as a hydration does.
pub async fn hydration(
client: &Client,
session: &str,
limit: u32,
) -> Result<(Vec<SessionMessageInfo>, Vec<String>), String> {
let messages = messages(client, session, limit).await?;
Ok((messages, active(client).await))
/// The session's pending user prompts (`session.inbox.list`); none when the read fails.
pub async fn inbox(client: &Client, session: &str) -> Vec<SessionInboxUser> {
let input = SessionInboxListInput { session_id: SessionID(session.to_owned()) };
let items = client.session_inbox_list(&input).await.unwrap_or_else(|error| {
log::warn!("mini could not list the inbox: {error}");
Vec::new()
});
items
.into_iter()
.filter_map(|item| match item {
SessionInboxInfo::User(user) => Some(user),
_ => None,
})
.collect()
}
/// What a hydration lists: the messages, the running sessions, and the pending prompts.
pub type Hydration = (Vec<SessionMessageInfo>, Vec<String>, Vec<SessionInboxUser>);
/// Lists the messages, the running sessions, and the pending prompts, as a hydration does.
pub async fn hydration(client: &Client, session: &str, limit: u32) -> Result<Hydration, String> {
let (messages, active, inbox) =
futures_util::future::join3(messages(client, session, limit), active(client), inbox(client, session)).await;
Ok((messages?, active, inbox))
}
/// `connect`: subscribes, hydrates after `server.connected`, then forwards events, reconnecting after 250 ms
@@ -1485,8 +1515,8 @@ async fn stream(client: &Client, session: &str, limit: u32, proxy: &AppProxy) ->
_ => return Err("Event stream disconnected".into()),
}
// Events that arrive meanwhile wait in the stream, so they reach the UI after the hydration.
let (messages, active) = hydration(client, session, limit).await?;
if !post(proxy, Incoming::Hydrated { messages, active }).await {
let (messages, active, inbox) = hydration(client, session, limit).await?;
if !post(proxy, Incoming::Hydrated { messages, active, inbox }).await {
return Ok(());
}
while let Some(event) = events.next().await {
+34 -9
View File
@@ -738,12 +738,13 @@ impl Mini {
return;
};
match incoming {
Incoming::Hydrated { messages, active } => {
Incoming::Hydrated { messages, active, inbox } => {
let running = active.contains(&transcript.session_id);
self.trace("recv.hydrate", json!({ "messages": messages.len(), "active": running }));
let reconnect = !transcript.initial;
let output = transcript.hydrate(&messages, running);
hydrated = Some((messages, active, reconnect));
transcript.inbox(&inbox);
let output = self.blocked(transcript.hydrate(&messages, running));
hydrated = Some((messages, active, inbox, reconnect));
output
}
Incoming::Event(event) => {
@@ -767,7 +768,12 @@ impl Mini {
let connected =
output.patch.is_some() && self.transcript.borrow().as_ref().is_some_and(|transcript| transcript.connected);
self.output(cx, output);
if let Some((messages, active, reconnect)) = hydrated {
if let Some((messages, active, inbox, reconnect)) = hydrated {
self.queued(&inbox);
// The first hydration's requests were listed when the session opened.
if reconnect {
self.footers.hydrate();
}
self.footers.subagent_hydrate(&messages, &active, reconnect);
}
if connected {
@@ -775,6 +781,22 @@ impl Mini {
}
}
/// A hydration's idle status names the request shown (`blockerStatus`).
fn blocked(&self, mut output: Output) -> Output {
if let Some(patch) = output.patch.as_mut().filter(|patch| patch.running == Some(false)) {
patch.status = Some(self.footers.blocker_status().to_owned());
}
output
}
/// The pending prompts a hydration listed (`syncPending`).
fn queued(self: &Rc<Self>, inbox: &[opencode_api::generated::SessionInboxUser]) {
self.prompt.set_queued(inbox);
self.footers.queue_changed();
self.schedule_height();
self.paint_status();
}
/// Writes a transcript output: footer events, commits, then the status.
fn output(self: &Rc<Self>, cx: &mut Cx<'_>, output: Output) {
for event in &output.footer {
@@ -1494,12 +1516,15 @@ impl Mini {
let mini = self.clone();
self.app.spawn(async move { replay::hydration(&client, &session, limit).await }, move |cx, result| {
let output = match result {
Ok((messages, active)) => {
Ok((messages, active, inbox)) => {
mini.reset_for_replay(cx);
mini.transcript
.borrow_mut()
.as_mut()
.map(|transcript| transcript.replayed(&messages, active.contains(&transcript.session_id)))
mini.queued(&inbox);
mini.footers.hydrate();
let output = mini.transcript.borrow_mut().as_mut().map(|transcript| {
transcript.inbox(&inbox);
transcript.replayed(&messages, active.contains(&transcript.session_id))
});
output.map(|output| mini.blocked(output))
}
// Nothing was cleared; the events that waited still apply.
Err(error) => {
+10 -2
View File
@@ -26,6 +26,9 @@ export type Route = {
thenDelay?: number
}
// A `then` event that closes the open `events` streams instead, so the clients reconnect.
export const DROP = Symbol("drop")
export type Logged = {
method: string
path: string
@@ -66,9 +69,14 @@ export async function startFakeServer(options: Options = {}) {
if (route.delay) await Bun.sleep(route.delay)
const response = respond(route, streams, entry, requests)
if (route.then) {
const frames = route.then(entry, requests).map((event) => encode(event))
const events = route.then(entry, requests)
setTimeout(
() => streams.forEach((controller) => frames.forEach((frame) => controller.enqueue(frame))),
() =>
events.forEach((event) => {
if (event !== DROP) return streams.forEach((controller) => controller.enqueue(encode(event)))
streams.forEach((controller) => controller.close())
streams.clear()
}),
route.thenDelay ?? 0,
)
}
+46
View File
@@ -0,0 +1,46 @@
// A prompt waits in the inbox when mini attaches. Once the server delivers it, the transcript prints it above the
// answer, as a prompt this client sent.
import type { Logged } from "../../lib/fake-server"
import { definePty } from "../../pty/run"
import { answer } from "../M.2/fixture"
import { config, leave, opened, server } from "./fixture"
const item = {
id: "msg_prequeued",
sessionID: "ses_mini",
time: { created: 40 },
type: "user",
payload: { text: "queued before attach" },
delivery: "queue",
}
const lists = (requests: Logged[]) => requests.filter((entry) => entry.path === "/api/session/ses_mini/inbox")
const base = server()
export default definePty({
args: ["mini", "-s", "ses_mini"],
cols: 60,
rows: 20,
server: {
...base,
routes: [
{
path: "/api/session/ses_mini/inbox",
json: { data: [item] },
thenDelay: 1500,
then: (_entry: Logged, requests: Logged[]) =>
lists(requests).length === 1 ? answer(item.id, "Answered prequeued.") : [],
},
...(base.routes ?? []),
],
},
setup: (root) => config(root),
steps: [opened, { until: { screen: "Answered prequeued." }, settle: 800, checkpoint: "delivered" }, ...leave],
exits: true,
masks: [
{
pattern: /^(ctrl\+x q \d+ pending · )?build · model · demo( · ctrl\+p menu)?$/,
reason: "the ctrl+p menu and pending-prompt hints open M.3's views",
},
],
requests: "writes",
})
+34
View File
@@ -0,0 +1,34 @@
// A permission waits when mini opens the session. The event stream drops while another client answers it, so
// no `permission.replied` arrives: the reconnect lists the requests again and the composer comes back.
import { DROP, type Logged } from "../../lib/fake-server"
import { definePty } from "../../pty/run"
import { config, leave, opened, server, shellPermission } from "./fixture"
const lists = (requests: Logged[]) => requests.filter((entry) => entry.path === "/api/session/ses_mini/permission")
const base = server()
export default definePty({
args: ["mini", "-s", "ses_mini"],
cols: 80,
rows: 24,
server: {
...base,
routes: [
{
path: "/api/session/ses_mini/permission",
json: (_entry: Logged, requests: Logged[]) => ({ data: lists(requests).length === 1 ? [shellPermission] : [] }),
thenDelay: 1500,
then: (_entry: Logged, requests: Logged[]) => (lists(requests).length === 1 ? [DROP] : []),
},
...(base.routes ?? []),
],
},
setup: (root) => config(root),
steps: [
{ ...opened, until: { screen: "Permission required" }, checkpoint: "asked" },
{ until: { screen: "ctrl+p menu" }, settle: 800, checkpoint: "reconnected" },
...leave,
],
exits: true,
requests: "writes",
})