Skip to content
Open
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
10 changes: 8 additions & 2 deletions apps/server/src/production/server_terminal.rs
Original file line number Diff line number Diff line change
Expand Up @@ -1416,8 +1416,14 @@ async fn readmit_input(
revision: u64,
) -> Result<(), Value> {
match acquire_terminal_input(Some(availability), thread_id).await {
Ok(admission) => {
terminal.readmit_input(input_id, revision, admission.map(input_admission));
Ok(Some(admission)) => {
terminal.readmit_input(input_id, revision, Some(input_admission(admission)));
Ok(())
}
// The server terminal has no workspace. `Ok(None)` is that success, not a failed
// admission. Passing `None` to `readmit_input` would seal the keyboard.
Ok(None) => {
terminal.retain_input_admission(input_id, revision);
Ok(())
}
// A newer round superseded this one; its result decides.
Expand Down
63 changes: 63 additions & 0 deletions apps/server/src/production/server_terminal_input_tests.rs
Original file line number Diff line number Diff line change
Expand Up @@ -963,6 +963,69 @@ async fn wait_for_live_sessions(fixture: &Fixture, count: usize) {
.expect("live session count");
}

/// Re-admitting the server terminal must leave its keyboard open. It has no workspace, so
/// the round's admission is `None`. That used to take the seal path and drop every later
/// keystroke until input was attached again.
#[tokio::test(flavor = "multi_thread", worker_threads = 4)]
async fn a_server_terminal_readmission_keeps_keyboard_input() {
let mut fixture = Fixture::start().await;
let home = fixture.root.join("home");
std::fs::create_dir_all(&home).expect("home");
success(
fixture
.request("terminal.open", server_terminal_open(&home))
.await,
);
let input = success(
fixture
.request(
"terminal.beginInput",
json!({"threadId": "server-terminal", "terminalId": "server-terminal", "attachmentSequence": 0}),
)
.await,
)["inputId"]
.as_str()
.expect("input id")
.to_owned();
let availability = fixture
.services
.workspace_admission
.clone()
.expect("workspace admission");
let (revision, sessions) = fixture
.services
.terminal
.start_input_readmission(crate::terminal::InputReadmissionScope::Session(&input));
assert!(
sessions.iter().any(|(id, _)| id == &input),
"the server terminal's input is in the round: {sessions:?}"
);
super::readmit_input(
&fixture.services.terminal,
&availability,
"server-terminal",
&input,
revision,
)
.await
.expect("readmission");
success(
fixture
.request(
"terminal.writeInput",
json!({
"threadId": "server-terminal",
"terminalId": "server-terminal",
"inputId": input,
"sequence": 0,
"data": "a",
}),
)
.await,
);
fixture.shutdown().await;
}

/// A thread row with the server terminal's id (#378), live or deleted, left by an older server
/// that accepted it, neither lends the server terminal a workspace nor stops it opening, even
/// when that row's workspace is unavailable and ordinary admission refuses it.
Expand Down
69 changes: 69 additions & 0 deletions apps/server/src/provider/claude/follow_up_turn_tests.rs
Original file line number Diff line number Diff line change
Expand Up @@ -193,6 +193,75 @@ fn an_answer_with_no_turn_ends_its_text_and_completes_no_turn() {
assert_eq!(completed.turn_id, delta.turn_id);
}

/// A delivered turn keeps the assistant message id from its `message_start`. Claude Code
/// 2.1.326 then answers a background task, with no turn open, by a text delta and no new
/// `message_start`. That delta must not reuse the previous message's id: a streaming delta
/// is appended to the projection row with that id, so the task answer would rewrite the
/// previous answer. With no provider message id it is stored under the turn, and a later
/// idle answer must not reuse an id this one claimed either.
#[test]
fn an_idle_answer_does_not_extend_the_previous_assistant_message() {
let mut runtime = runtime();
kinds(
&mut runtime,
&stream(json!({"type":"message_start","message":{"id":"msg-1"}})),
);
let delivered = runtime.handle_raw_value(&text_delta(), 1_000);
let delivered_delta = delivered
.events
.iter()
.find(|event| event.event_type == "content.delta")
.expect("the turn's text");
assert_eq!(delivered_delta.item_id.as_deref(), Some("msg-1"));
kinds(&mut runtime, &result());

let mut events = Vec::new();
for frame in [
task("task_notification", "bg"),
init(),
text_delta(),
idle_result(false),
] {
events.extend(runtime.handle_raw_value(&frame, 1_000).events);
}
let delta = events
.iter()
.find(|event| event.event_type == "content.delta")
.expect("the idle answer's text");
assert_ne!(
delta.item_id.as_deref(),
Some("msg-1"),
"the idle answer was appended to the previous message"
);
assert!(
delta.item_id.is_none(),
"the idle answer is stored under the turn, not a provider message: {:?}",
delta.item_id
);
let completed = events
.iter()
.find(|event| event.event_type == "assistant.message.completed")
.expect("the idle answer ends");
assert_eq!(completed.item_id, delta.item_id);
assert_eq!(completed.turn_id, delta.turn_id);

kinds(
&mut runtime,
&stream(json!({"type":"message_start","message":{"id":"idle-msg"}})),
);
kinds(&mut runtime, &text_delta());
kinds(&mut runtime, &idle_result(false));
let later = runtime.handle_raw_value(&text_delta(), 1_000);
let later_delta = later
.events
.iter()
.find(|event| event.event_type == "content.delta")
.expect("the next idle answer");
assert_ne!(later_delta.item_id.as_deref(), Some("idle-msg"));
assert_ne!(later_delta.item_id.as_deref(), Some("msg-1"));
assert!(later_delta.item_id.is_none(), "{:?}", later_delta.item_id);
}

/// An answer with no turn that streams text, calls a tool, then streams more text under a second
/// message: its `result` ends both texts under the ids each was stored with, and only the last
/// completion ends the answer, so one context query follows it.
Expand Down
11 changes: 11 additions & 0 deletions apps/server/src/provider/claude/runtime.rs
Original file line number Diff line number Diff line change
Expand Up @@ -3229,6 +3229,8 @@ impl ClaudeProviderRuntime {
item_id,
));
}
// The next idle answer must not reuse this one's `message_start` id.
self.release_assistant_message();
return events;
}
self.stop_turn_input();
Expand Down Expand Up @@ -3308,9 +3310,18 @@ impl ClaudeProviderRuntime {
events.extend(self.start_follow_up_turn());
}
self.follow_ups_carried = self.follow_ups_after_turn;
// The message id belongs to the turn that just ended. An answer Claude gives
// afterwards, with no new `message_start`, is stored under the turn. Leaving the
// id set appends that answer onto the previous message.
self.release_assistant_message();
events
}

/// Drops the assistant message id from the turn that owned it.
fn release_assistant_message(&mut self) {
self.active_assistant_item_id = None;
}

fn flush_incomplete_tools(&mut self) -> Vec<CanonicalEvent> {
let pending_ids = self
.in_flight_tools
Expand Down
26 changes: 26 additions & 0 deletions apps/server/src/terminal/input.rs
Original file line number Diff line number Diff line change
Expand Up @@ -412,6 +412,32 @@ impl TerminalInputRegistry {
true
}

/// Records that re-admission round `revision` kept the session's current admission.
/// The session stays open. A terminal with no workspace succeeds with no admission;
/// sealing it would close input that was opened that way. A result older than one
/// already applied, or than the latest round started for the session, is ignored.
pub(super) fn retain_admission(&self, input_id: &str, revision: u64) -> bool {
let Some(lease) = self
.0
.lock()
.expect("terminal input registry")
.leases
.get(input_id)
.cloned()
else {
return false;
};
let mut current = lease.admission.lock().expect("terminal input admission");
if revision <= current.revision || revision < current.pending {
return false;
}
current.revision = revision;
drop(current);
lease.admission_changed.notify_waiters();
lease.changed.notify_waiters();
true
}

/// Whether the session is still registered and not sealed.
pub(super) fn check_open(&self, input_id: &str) -> Result<(), TerminalInputError> {
let lease = self
Expand Down
6 changes: 6 additions & 0 deletions apps/server/src/terminal/manager.rs
Original file line number Diff line number Diff line change
Expand Up @@ -4007,6 +4007,12 @@ impl TerminalManager {
self.inner.input.readmit(input_id, revision, admission)
}

/// Applies round `revision` without changing the session's admission or sealing it.
/// A terminal that has no workspace re-admits this way: no admission is success.
pub(crate) fn retain_input_admission(&self, input_id: &str, revision: u64) -> bool {
self.inner.input.retain_admission(input_id, revision)
}

/// Whether the input session is still registered and not sealed.
pub(crate) fn check_input_open(&self, input_id: &str) -> Result<(), TerminalError> {
self.inner
Expand Down
3 changes: 2 additions & 1 deletion docs/providers/claude.md
Original file line number Diff line number Diff line change
Expand Up @@ -455,7 +455,8 @@ Known limits:
- An answer Claude gives in a turn of its own with no replay before it (what
Claude Code 2.1.326 sends when a background task finishes while no turn
runs) opens no BiBCode turn. Its text and tool calls are stored under the
last turn's id. A tool call completes from its own result. The answer's
last turn's id, not under the previous answer's provider message id, so the
task answer does not extend that message. A tool call completes from its own result. The answer's
`result` completes its text, any tool call, thinking block or compaction
still open, closes subagent rows Claude no longer lists, and withdraws an
approval or question it left pending, but completes no turn. It completes
Expand Down
Loading