From 4ca81e47678756f6c7cc80eaea7b88e66dcf4cb9 Mon Sep 17 00:00:00 2001 From: Cameron Taylor Date: Wed, 11 Nov 2026 15:59:28 +1100 Subject: [PATCH] fix(tui): Verify ask-user form contracts and close input gaps --- crates/jcode-tui/src/tui/ask_form/keys.rs | 23 ++- crates/jcode-tui/src/tui/ask_form/paste.rs | 3 +- .../jcode-tui/src/tui/ask_form/tests/app.rs | 81 ++++++++++ .../jcode-tui/src/tui/ask_form/tests/keys.rs | 146 ++++++++++++++++++ .../src/tui/ask_form/tests/render.rs | 20 +-- docs/ASK_USER_FORM_VERIFICATION.md | 56 +++++++ 6 files changed, 309 insertions(+), 20 deletions(-) create mode 100644 docs/ASK_USER_FORM_VERIFICATION.md diff --git a/crates/jcode-tui/src/tui/ask_form/keys.rs b/crates/jcode-tui/src/tui/ask_form/keys.rs index ca9da2ce218..f8170395e2e 100644 --- a/crates/jcode-tui/src/tui/ask_form/keys.rs +++ b/crates/jcode-tui/src/tui/ask_form/keys.rs @@ -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 { @@ -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); } @@ -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 => { @@ -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, @@ -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 @@ -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, diff --git a/crates/jcode-tui/src/tui/ask_form/paste.rs b/crates/jcode-tui/src/tui/ask_form/paste.rs index e9a3f11d90a..2a76373a44c 100644 --- a/crates/jcode-tui/src/tui/ask_form/paste.rs +++ b/crates/jcode-tui/src/tui/ask_form/paste.rs @@ -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 { +pub(super) fn select_other(form: &mut Form, question_index: usize) -> Option { let question = form.questions.get_mut(question_index)?; let other = question.other.clone()?; if question.multi { @@ -95,6 +95,7 @@ fn select_other(form: &mut Form, question_index: usize) -> Option { question: question_index, kind: EditorKind::Other, }; + form.preview_focus = false; form.editor = Some(editor); Some(editor) } diff --git a/crates/jcode-tui/src/tui/ask_form/tests/app.rs b/crates/jcode-tui/src/tui/ask_form/tests/app.rs index b9bae71c96e..525ca94dde3 100644 --- a/crates/jcode-tui/src/tui/ask_form/tests/app.rs +++ b/crates/jcode-tui/src/tui/ask_form/tests/app.rs @@ -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::(); + assert_eq!(first.next().unwrap().unwrap(), json!("Which, \"界\"?")); + let decode = |line: &str| { + serde_json::Deserializer::from_str(line.split_once('=').unwrap().1) + .into_iter::() + .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::() + .next() + .unwrap() + .unwrap(), + json!("because \"both\"\nplease") + ); + broker.detach(CONNECTION); +} diff --git a/crates/jcode-tui/src/tui/ask_form/tests/keys.rs b/crates/jcode-tui/src/tui/ask_form/tests/keys.rs index ef97c20eb99..bd3c4ab673d 100644 --- a/crates/jcode-tui/src/tui/ask_form/tests/keys.rs +++ b/crates/jcode-tui/src/tui/ask_form/tests/keys.rs @@ -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" + ); +} diff --git a/crates/jcode-tui/src/tui/ask_form/tests/render.rs b/crates/jcode-tui/src/tui/ask_form/tests/render.rs index 4bd5754de3b..cdda3600e8e 100644 --- a/crates/jcode-tui/src/tui/ask_form/tests/render.rs +++ b/crates/jcode-tui/src/tui/ask_form/tests/render.rs @@ -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, @@ -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); }); } } diff --git a/docs/ASK_USER_FORM_VERIFICATION.md b/docs/ASK_USER_FORM_VERIFICATION.md new file mode 100644 index 00000000000..159da452337 --- /dev/null +++ b/docs/ASK_USER_FORM_VERIFICATION.md @@ -0,0 +1,56 @@ +# Ask-user form specification verification + +Specification: toolkit-research repository, +`projects/jcode/plans/done/ASK_USER_FORM.md` (2026-11-11). + +The specification lives outside this repository. It defines the model input, +ACP form schema and result contract as well as the TUI interaction and lifecycle. + +## Deviations found and corrected + +| Spec behavior | Deviation | Regression test | +| --- | --- | --- | +| Typing on Other opens its editor and preserves composed input | Printable input outside an editor was swallowed | `typing_on_other_keeps_the_first_composed_character_in_the_answer` | +| Shift+Tab navigates backward | Tab with SHIFT moved forward on question tabs; BackTab worked | `shift_tab_key_encoding_moves_back_without_changing_answers` | +| Active text editors remain visible, including in narrow terminals | Notes opened from preview remained covered by the preview | `opening_notes_from_preview_shows_the_text_being_edited` | + +All fixes are in the fork-owned form module. No protocol or upstream hooks changed. +No substantial implementation deviation was identified requiring delegation. + +## Focused coverage + +The new generated-form round trip executes the actual AskUserTool with a fake +form-capable broker attachment, drives its generated schema through TUI input, +submits through broker validation and decodes the resulting model-facing values. +It checks single-select Other, multi-select boundaries, Unicode, commas, quotes, +newlines and notes without constraining the order of a selection set. + +Additional tests exercise the 8192-code-point limit through submitted content +for both notes and Other (including preservation after rejected paste), and +schema-changed reconnects that must discard stale answers and drafts. +The panel-height helper test was folded into real rendering checks, including +the 11/12-row boundary; the expected cap no longer comes from the implementation +being tested. + +Existing tests retained cover input validation and reserved labels, Other +normalization, previews, escaping, broker validation, registration and explicit +allowlists, headless/late-attach/hibernation behavior, keyboard navigation, +grapheme edits, preview scrolling, narrow rendering, focus precedence, +acknowledgement ownership, submission races, reconnect and session cleanup. +Schema-field assertions were retained because they specify the public ACP +interface used by clients, rather than private implementation structure. + +This is automated contract verification, not a fresh interactive runtime +acceptance pass. Real terminal input encoding, live provider calls and daemon +reloads still require the private-socket runtime procedure in the specification. + +## Validation on 2026-11-11 + +On atlas, using the shared Cargo target cache and `nice -n 10`: + +- `cargo test -p jcode-tui --lib tui::ask_form::tests:: -- --test-threads=2`: + 54 passed. +- `cargo test -p jcode-tui --lib tui::app::remote::server_events::ask_form_tests:: -- --test-threads=2`: + 16 passed. +- The new composed-input test failed against the original implementation + before its fix. All final targeted tests pass; `git diff --check` passes.