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

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
23 changes: 20 additions & 3 deletions crates/jcode-tui/src/tui/ask_form/keys.rs
Original file line number Diff line number Diff line change
Expand Up @@ -79,7 +79,7 @@ pub(super) fn handle_key(
let result = if form.editor.is_some() {
handle_editor(form, code, modifiers, text_input)
} else {
handle_normal(form, code, modifiers)
handle_normal(form, code, modifiers, text_input)
};

if let KeyOutcome::Send {
Expand Down Expand Up @@ -181,7 +181,12 @@ fn handle_editor(
KeyResult::consumed()
}

fn handle_normal(form: &mut Form, code: KeyCode, modifiers: KeyModifiers) -> KeyResult {
fn handle_normal(
form: &mut Form,
code: KeyCode,
modifiers: KeyModifiers,
text_input: Option<&str>,
) -> KeyResult {
if form.is_submit_tab() {
return handle_summary(form, code, modifiers);
}
Expand All @@ -196,7 +201,7 @@ fn handle_normal(form: &mut Form, code: KeyCode, modifiers: KeyModifiers) -> Key
KeyResult::consumed()
}
KeyCode::Tab => {
form.move_tab(true);
form.move_tab(!modifiers.contains(KeyModifiers::SHIFT));
KeyResult::consumed()
}
KeyCode::BackTab => {
Expand Down Expand Up @@ -252,6 +257,7 @@ fn handle_normal(form: &mut Form, code: KeyCode, modifiers: KeyModifiers) -> Key
if let Some(question) = form.questions.get_mut(question) {
question.notes_cursor = question.notes.len();
}
form.preview_focus = false;
form.editor = Some(EditorFocus {
question,
kind: EditorKind::Notes,
Expand Down Expand Up @@ -300,6 +306,16 @@ fn handle_normal(form: &mut Form, code: KeyCode, modifiers: KeyModifiers) -> Key
KeyResult::consumed()
}
KeyCode::Esc => decline(form),
KeyCode::Char(_)
if form
.current_question()
.is_some_and(super::state::Question::highlight_is_other) =>
{
// Match paste routing: typing on Other selects it and keeps the
// first character, including composed input from the terminal.
super::paste::select_other(form, form.tab);
handle_editor(form, code, modifiers, text_input)
}
KeyCode::Char(_) => {
// Printable keys outside an editor are shortcuts only. Swallow
// them so they cannot type into the composer hidden behind the
Expand Down Expand Up @@ -449,6 +465,7 @@ fn choose_row(form: &mut Form, question_index: usize, row: usize) {

let cursor = form.questions[question_index].other_text.len();
form.questions[question_index].other_cursor = cursor;
form.preview_focus = false;
form.editor = Some(EditorFocus {
question: question_index,
kind: EditorKind::Other,
Expand Down
3 changes: 2 additions & 1 deletion crates/jcode-tui/src/tui/ask_form/paste.rs
Original file line number Diff line number Diff line change
Expand Up @@ -82,7 +82,7 @@ pub(super) fn handle_paste(state: &mut State, context: &ViewContext, text: &str)
}
}

fn select_other(form: &mut Form, question_index: usize) -> Option<EditorFocus> {
pub(super) fn select_other(form: &mut Form, question_index: usize) -> Option<EditorFocus> {
let question = form.questions.get_mut(question_index)?;
let other = question.other.clone()?;
if question.multi {
Expand All @@ -95,6 +95,7 @@ fn select_other(form: &mut Form, question_index: usize) -> Option<EditorFocus> {
question: question_index,
kind: EditorKind::Other,
};
form.preview_focus = false;
form.editor = Some(editor);
Some(editor)
}
Expand Down
81 changes: 81 additions & 0 deletions crates/jcode-tui/src/tui/ask_form/tests/app.rs
Original file line number Diff line number Diff line change
Expand Up @@ -185,3 +185,84 @@ fn public_send_failure_restores_editing() {
send_failed(&mut app, "offline");
active(|form| assert!(matches!(form.submit, SubmitState::Rejected(_))));
}

/// Exercise the real tool -> broker -> TUI -> broker -> model-result contract.
#[tokio::test]
async fn generated_form_round_trips_unicode_choices_other_and_notes() {
use crate::elicitation::ask_user::AskUserTool;
use crate::tool::{Tool, ToolContext, ToolExecutionMode};
const SESSION: &str = "ask-form-contract";
const CONNECTION: &str = "ask-form-contract-client";
reset();
let (tx, mut rx) = tokio::sync::mpsc::unbounded_channel();
let broker = crate::elicitation::global();
broker.attach(CONNECTION, SESSION, true, false, false, tx);
rx.recv().await.expect("replay complete");
let task = tokio::spawn(async {
AskUserTool.execute(json!({"questions": [
{"question": "Which, \"界\"?", "header": "Pick", "multiSelect": false,
"options": [{"label": "A", "description": "First"}, {"label": "B", "description": "Second"}]},
{"question": "Which many?", "header": "Many", "multiSelect": true,
"options": [{"label": "界, 🎉", "description": "First"}, {"label": "B\nC", "description": "Second"}]}
], "answers": {}, "annotations": {}, "metadata": {}}), ToolContext {
session_id: SESSION.into(), message_id: "message".into(), tool_call_id: "call".into(),
working_dir: None, stdin_request_tx: None, graceful_shutdown_signal: None,
execution_mode: ToolExecutionMode::AgentTurn,
}).await.unwrap().output
});
let event = tokio::time::timeout(std::time::Duration::from_secs(5), rx.recv())
.await
.unwrap()
.unwrap();
let ServerEvent::ElicitationRequest(request) = event else {
panic!("expected form");
};
let context = install(SESSION, request.clone());
key(&context, KeyCode::Char('3'));
assert!(paste_text(&context, "custom 界🎉\nanswer"));
key(&context, KeyCode::Esc);
key(&context, KeyCode::Right);
key(&context, KeyCode::Char('1'));
key(&context, KeyCode::Char('2'));
key(&context, KeyCode::Char('n'));
assert!(paste_text(&context, "because \"both\"\nplease"));
key(&context, KeyCode::Esc);
key(&context, KeyCode::Enter);
let KeyOutcome::Send { response, .. } = key(&context, KeyCode::Enter) else {
panic!("expected submit");
};
broker
.respond(CONNECTION, SESSION, &request.elicitation_id, response)
.unwrap();
let output = tokio::time::timeout(std::time::Duration::from_secs(5), task)
.await
.unwrap()
.unwrap();
let lines: Vec<_> = output.lines().collect();
// Decode serialized values rather than comparing renderer or formatter internals.
let mut first = serde_json::Deserializer::from_str(lines[1]).into_iter::<Value>();
assert_eq!(first.next().unwrap().unwrap(), json!("Which, \"界\"?"));
let decode = |line: &str| {
serde_json::Deserializer::from_str(line.split_once('=').unwrap().1)
.into_iter::<Value>()
.next()
.unwrap()
.unwrap()
};
assert_eq!(decode(lines[1]), json!("custom 界🎉\nanswer"));
let selected = decode(lines[2]);
let selected = selected.as_array().expect("multi-select stays an array");
assert_eq!(selected.len(), 2);
assert!(selected.contains(&json!("界, 🎉")));
assert!(selected.contains(&json!("B\nC")));
let notes = lines[2].split_once("user notes: ").unwrap().1;
assert_eq!(
serde_json::Deserializer::from_str(notes)
.into_iter::<Value>()
.next()
.unwrap()
.unwrap(),
json!("because \"both\"\nplease")
);
broker.detach(CONNECTION);
}
146 changes: 146 additions & 0 deletions crates/jcode-tui/src/tui/ask_form/tests/keys.rs
Original file line number Diff line number Diff line change
Expand Up @@ -177,3 +177,149 @@ fn hidden_editor_cannot_take_paste() {
assert!(!paste_text(&blocked, "hidden"));
active(|form| assert_eq!(form.questions[0].notes, "visible"));
}

// ASK_USER_FORM.md: typing on Other opens its editor; composed text wins.
#[test]
fn typing_on_other_keeps_the_first_composed_character_in_the_answer() {
reset();
let context = install(SESSION, form("e1", SESSION, single_schema()));
key(&context, KeyCode::Down);
key(&context, KeyCode::Down);
key_with(
&context,
KeyCode::Char('x'),
KeyModifiers::NONE,
Some("界🎉"),
);
key(&context, KeyCode::Esc); // Save the editor, without declining.
key(&context, KeyCode::Right);
let KeyOutcome::Send { response, .. } = key(&context, KeyCode::Enter) else {
panic!("typed Other answer must be submittable");
};
let crate::protocol::elicitation::ElicitationResponse::Accept {
content: Some(content),
} = response
else {
panic!("expected accepted answer");
};
assert_eq!(content.get("q1"), Some(&json!("__other__")));
assert_eq!(content.get("q1_other"), Some(&json!("界🎉")));
}

#[test]
fn shift_tab_key_encoding_moves_back_without_changing_answers() {
reset();
let context = install_default();
key(&context, KeyCode::Char('1'));
key(&context, KeyCode::Right);
key_with(&context, KeyCode::Tab, KeyModifiers::SHIFT, None);
let screen = render_buffer(&context, 80, 24);
assert!(
(0..24).any(|row| row_text(&screen, row).contains("Which option do you want?")),
"Shift+Tab must show the previous question, rather than Submit"
);
// Enter on q1 advances to q2; Enter on q2 advances to summary.
key(&context, KeyCode::Enter);
key(&context, KeyCode::Char('2'));
key(&context, KeyCode::Enter);
let KeyOutcome::Send { response, .. } = key(&context, KeyCode::Enter) else {
panic!("back navigation must preserve q1 and let q2 be answered");
};
let crate::protocol::elicitation::ElicitationResponse::Accept {
content: Some(content),
} = response
else {
panic!("expected accepted answer");
};
assert_eq!(content.get("q1"), Some(&json!("a")));
assert_eq!(content.get("q2"), Some(&json!(["y"])));
}

#[test]
fn unicode_editor_limit_accepts_code_points_and_rejects_without_losing_text() {
for shortcut in ['n', '3'] {
reset();
let context = install_default();
key(&context, KeyCode::Char(shortcut));
let draft = "界".repeat(MAX_TEXT_CODE_POINTS);
assert!(paste_text(&context, &draft));
assert!(paste_text(&context, "🎉")); // Consumed, rejected, never sent to composer.
active(|form| assert!(form.notice.as_deref().unwrap().contains("Text limit")));
key(&context, KeyCode::Esc);
if shortcut == 'n' {
key(&context, KeyCode::Char('1'));
}
key(&context, KeyCode::Right);
key(&context, KeyCode::Char('1'));
key(&context, KeyCode::Enter);
let KeyOutcome::Send { response, .. } = key(&context, KeyCode::Enter) else {
panic!("exactly 8192 code points must be submittable");
};
let crate::protocol::elicitation::ElicitationResponse::Accept {
content: Some(content),
} = response
else {
panic!("expected accepted answer");
};
let field = if shortcut == 'n' {
"q1_notes"
} else {
"q1_other"
};
assert_eq!(content.get(field), Some(&json!(draft)));
}
}

#[test]
fn replay_with_changed_choices_never_submits_the_old_answer_or_notes() {
reset();
let context = install(SESSION, form("e1", SESSION, single_schema()));
key(&context, KeyCode::Char('3'));
paste_text(&context, "stale private draft");
key(&context, KeyCode::Esc);
state::with(|state| reconcile::connection_replaced(state, Some(SESSION)));
let mut changed = single_schema();
changed["properties"]["q1"]["oneOf"][0]["const"] = json!("new");
send_event(
&context,
&ServerEvent::ElicitationRequest(form("e1", SESSION, changed)),
);
send_event(
&context,
&ServerEvent::ElicitationReplayComplete {
session_id: SESSION.into(),
},
);
key(&context, KeyCode::Right);
assert!(!matches!(
key(&context, KeyCode::Enter),
KeyOutcome::Send { .. }
));
key(&context, KeyCode::Left);
key(&context, KeyCode::Char('1'));
key(&context, KeyCode::Right);
let KeyOutcome::Send { response, .. } = key(&context, KeyCode::Enter) else {
panic!("new answer should submit");
};
let crate::protocol::elicitation::ElicitationResponse::Accept {
content: Some(content),
} = response
else {
panic!("expected accepted answer");
};
assert_eq!(content, json!({"q1": "new"}).as_object().unwrap().clone());
}

#[test]
fn opening_notes_from_preview_shows_the_text_being_edited() {
reset();
let context = install_default();
key(&context, KeyCode::Char('p'));
key(&context, KeyCode::Char('n'));
paste_text(&context, "visible draft 界");
let screen = render_buffer(&context, 80, 24);
assert!(
(0..24).any(|row| row_text(&screen, row).contains("visible draft 界")),
"narrow preview must yield to the active text editor"
);
}
20 changes: 4 additions & 16 deletions crates/jcode-tui/src/tui/ask_form/tests/render.rs
Original file line number Diff line number Diff line change
Expand Up @@ -117,23 +117,14 @@ fn chrome_rows_never_exceed_width_with_cjk_and_emoji_headers() {
assert!(line_width(&narrow) <= 40);
}

#[test]
fn panel_height_caps_at_sixty_percent_and_uses_all_rows_below_12() {
assert_eq!(form_render::panel_height(0), 0);
assert_eq!(form_render::panel_height(10), 10);
assert_eq!(form_render::panel_height(11), 11);
assert_eq!(form_render::panel_height(12), 7);
assert_eq!(form_render::panel_height(15), 9);
assert_eq!(form_render::panel_height(24), 14);
}

#[test]
fn render_at_80x24_40x15_and_80x10_is_bottom_anchored_and_height_capped() {
reset();
let context = install_default();
for (width, height) in [(80u16, 24u16), (40, 15), (80, 10)] {
for (width, height) in [(80u16, 24u16), (40, 15), (80, 10), (80, 11), (80, 12)] {
let buffer = render_buffer(&context, width, height);
let top = height - form_render::panel_height(height);
let expected_height = if height < 12 { height } else { height * 3 / 5 };
let top = height - expected_height;
let first = first_nonblank_row(&buffer).expect("panel content");
assert!(
first >= top,
Expand All @@ -144,10 +135,7 @@ fn render_at_80x24_40x15_and_80x10_is_bottom_anchored_and_height_capped() {
"{width}x{height}: status row should not be blank"
);
active(|form| {
assert_eq!(
form.last_body_height as u16,
form_render::panel_height(height) - 2
);
assert_eq!(form.last_body_height as u16, expected_height - 2);
});
}
}
Expand Down
Loading
Loading