You are viewing a plain text version of this content. The canonical link for it is here.
Posted to commits@maka.apache.org by wy...@apache.org on 2026/10/16 05:39:48 UTC
(maka) branch rust-preview updated: feat(ui): add slash suggestions and contain prompt scrolling
This is an automated email from the ASF dual-hosted git repository.
M4n5ter pushed a commit to branch rust-preview
in repository https://gitbox.apache.org/repos/asf/maka.git
The following commit(s) were added to refs/heads/rust-preview by this push:
new 8c0c697d0e feat(ui): add slash suggestions and contain prompt scrolling
8c0c697d0e is described below
commit 8c0c697d0e14b647086f677575024d9dbb10d559
Author: Wang <m4...@gmail.com>
AuthorDate: Fri Oct 16 13:39:28 2026 +0800
feat(ui): add slash suggestions and contain prompt scrolling
Show available composer commands with filtering, keyboard navigation and completion. Bind menu keys to the current native editor revision on terminal and desktop. Keep overflowing prompt wheel gestures inside the editor and expand its terminal viewport.
Validated with plugin tests, native editor tests, real terminal command and settings flows, schema checks, typechecks and scoped Clippy.
Generated-by: Codex
---
packages/plugin-sdk/src/contracts.ts | 202 ++++++++++++++++
packages/plugin-sdk/src/generated/runtime.ts | 8 +
platform/render-gpui/src/textarea.rs | 67 +++--
platform/render-terminal/src/application/editor.rs | 9 +-
.../src/application/tests/textarea.rs | 130 +++++++++-
.../render-terminal/src/application/textarea.rs | 47 ++++
platform/render-terminal/src/editor.rs | 4 +-
platform/ui-runtime/src/textarea.rs | 60 +++++
plugins/agent/agent-screen/actions.ts | 20 ++
plugins/agent/agent-screen/component-events.ts | 14 +-
plugins/agent/agent-screen/conversation-view.ts | 4 +-
plugins/agent/assistant-preferences/index.ts | 2 +-
plugins/agent/composer/component.ts | 269 ++++++++++++++++++---
plugins/agent/composer/locale.ts | 9 +-
plugins/shared/contracts.ts | 21 +-
products/maka/bundle/tests/compact.test.mjs | 12 +-
products/maka/bundle/tests/composer.test.mjs | 174 ++++++++++++-
products/maka/cli/notices.json | 18 +-
.../tests/integration/terminal/bundled_product.rs | 59 +++++
.../terminal/bundled_product/chat/compaction.rs | 12 +-
products/maka/desktop/src/editor_tests/submit.rs | 86 ++++++-
21 files changed, 1134 insertions(+), 93 deletions(-)
diff --git a/packages/plugin-sdk/src/contracts.ts b/packages/plugin-sdk/src/contracts.ts
index eb4bb51758..5155a97020 100644
--- a/packages/plugin-sdk/src/contracts.ts
+++ b/packages/plugin-sdk/src/contracts.ts
@@ -3988,6 +3988,18 @@ export const contracts = {
],
default: null,
},
+ navigation: {
+ description: 'Yield suggestion navigation only for the original observed editor state.',
+ anyOf: [
+ {
+ $ref: '#/$defs/EditorNavigation',
+ },
+ {
+ type: 'null',
+ },
+ ],
+ default: null,
+ },
tabIndex: {
type: 'integer',
format: 'int16',
@@ -4639,6 +4651,24 @@ export const contracts = {
type: 'string',
enum: ['enter', 'primary_enter', 'control_enter'],
},
+ EditorNavigation: {
+ type: 'object',
+ properties: {
+ owner: {
+ type: 'string',
+ minLength: 1,
+ maxLength: 128,
+ },
+ basedOn: {
+ type: 'integer',
+ format: 'uint64',
+ minimum: 0,
+ maximum: 9007199254740991,
+ },
+ },
+ additionalProperties: false,
+ required: ['owner', 'basedOn'],
+ },
EditorCommand: {
type: 'object',
properties: {
@@ -5258,6 +5288,178 @@ export const contracts = {
},
},
},
+ navigated: {
+ $schema: 'https://json-schema.org/draft/2020-12/schema',
+ title: 'EditorNavigated',
+ type: 'object',
+ properties: {
+ key: {
+ $ref: '#/$defs/EditorNavigationKey',
+ },
+ observation: {
+ $ref: '#/$defs/EditorObservation',
+ },
+ },
+ additionalProperties: false,
+ required: ['key', 'observation'],
+ $defs: {
+ EditorNavigationKey: {
+ type: 'string',
+ enum: ['up', 'down', 'enter', 'tab', 'escape'],
+ },
+ EditorObservation: {
+ type: 'object',
+ properties: {
+ revision: {
+ type: 'integer',
+ format: 'uint64',
+ minimum: 0,
+ },
+ snapshot: {
+ $ref: '#/$defs/EditorSnapshot',
+ },
+ receipt: {
+ anyOf: [
+ {
+ $ref: '#/$defs/EditorReceipt',
+ },
+ {
+ type: 'null',
+ },
+ ],
+ },
+ },
+ additionalProperties: false,
+ required: ['revision', 'snapshot', 'receipt'],
+ },
+ EditorSnapshot: {
+ type: 'object',
+ properties: {
+ text: {
+ $ref: '#/$defs/EditorTextRef',
+ },
+ selection: {
+ $ref: '#/$defs/TextRange',
+ },
+ reversed: {
+ type: 'boolean',
+ },
+ marked: {
+ anyOf: [
+ {
+ $ref: '#/$defs/TextRange',
+ },
+ {
+ type: 'null',
+ },
+ ],
+ },
+ },
+ additionalProperties: false,
+ required: ['text', 'selection', 'reversed', 'marked'],
+ },
+ EditorTextRef: {
+ type: 'object',
+ properties: {
+ owner: {
+ type: 'string',
+ },
+ revision: {
+ type: 'integer',
+ format: 'uint64',
+ minimum: 0,
+ },
+ bytes: {
+ type: 'integer',
+ format: 'uint',
+ minimum: 0,
+ },
+ },
+ additionalProperties: false,
+ required: ['owner', 'revision', 'bytes'],
+ },
+ TextRange: {
+ type: 'object',
+ properties: {
+ start: {
+ type: 'integer',
+ format: 'uint',
+ minimum: 0,
+ },
+ end: {
+ type: 'integer',
+ format: 'uint',
+ minimum: 0,
+ },
+ },
+ additionalProperties: false,
+ required: ['start', 'end'],
+ },
+ EditorReceipt: {
+ type: 'object',
+ properties: {
+ owner: {
+ type: 'string',
+ },
+ sequence: {
+ type: 'integer',
+ format: 'uint64',
+ minimum: 0,
+ },
+ revision: {
+ type: 'integer',
+ format: 'uint64',
+ minimum: 0,
+ },
+ outcome: {
+ $ref: '#/$defs/EditorOutcome',
+ },
+ },
+ additionalProperties: false,
+ required: ['owner', 'sequence', 'revision', 'outcome'],
+ },
+ EditorOutcome: {
+ oneOf: [
+ {
+ type: 'object',
+ properties: {
+ status: {
+ type: 'string',
+ const: 'applied',
+ },
+ },
+ required: ['status'],
+ additionalProperties: false,
+ },
+ {
+ type: 'object',
+ properties: {
+ reason: {
+ $ref: '#/$defs/EditorConflict',
+ },
+ status: {
+ type: 'string',
+ const: 'conflict',
+ },
+ },
+ additionalProperties: false,
+ required: ['status', 'reason'],
+ },
+ ],
+ },
+ EditorConflict: {
+ type: 'string',
+ enum: [
+ 'persistence',
+ 'owner',
+ 'representation',
+ 'revision',
+ 'composition',
+ 'sequence',
+ ],
+ },
+ },
+ },
submitted: {
$schema: 'https://json-schema.org/draft/2020-12/schema',
title: 'EditorObservation',
diff --git a/packages/plugin-sdk/src/generated/runtime.ts b/packages/plugin-sdk/src/generated/runtime.ts
index b453da6a2e..c28393766c 100644
--- a/packages/plugin-sdk/src/generated/runtime.ts
+++ b/packages/plugin-sdk/src/generated/runtime.ts
@@ -6068,6 +6068,10 @@ export interface TextareaProps {
* None preserves native multiline editing without a submit shortcut.
*/
submit?: SubmitKey | null;
+ /**
+ * Yield suggestion navigation only for the original observed editor state.
+ */
+ navigation?: EditorNavigation | null;
tabIndex: number;
/**
* Offer native focus once when this original input becomes visible and
@@ -6205,6 +6209,10 @@ export interface TerminalTextareaRows {
*/
maxViewportFraction?: number | null;
}
+export interface EditorNavigation {
+ owner: string;
+ basedOn: number;
+}
export interface EditorCommand {
/**
* Correlation with the original native editor, never a resource grant.
diff --git a/platform/render-gpui/src/textarea.rs b/platform/render-gpui/src/textarea.rs
index ed08aa6b41..d3993191d3 100644
--- a/platform/render-gpui/src/textarea.rs
+++ b/platform/render-gpui/src/textarea.rs
@@ -51,6 +51,7 @@ pub struct TextareaOwner {
open_menu: Option<menu::OpenMenu>,
_menu_input: Option<Subscription>,
submit: Option<SubmitKey>,
+ navigation: Option<EditorNavigation>,
_keyboard: Option<Subscription>,
checkpoint: Option<maka_ui_runtime::checkpoint::EditorCheckpoint>,
persistence: Option<maka_ui_runtime::checkpoint::EditorPersistence>,
@@ -144,6 +145,7 @@ impl TextareaOwner {
open_menu: None,
_menu_input: None,
submit: props.submit,
+ navigation: props.navigation.clone(),
_keyboard: None,
checkpoint,
persistence: props.persistence.clone(),
@@ -185,16 +187,56 @@ impl TextareaOwner {
let weak = owner.downgrade();
let window_id = window.window_handle().window_id();
let keyboard = cx.intercept_keystrokes(move |event, window, cx| {
- if event.keystroke.key != "enter" || window.window_handle().window_id() != window_id {
+ if window.window_handle().window_id() != window_id
+ || !matches!(
+ event.keystroke.key.as_str(),
+ "up" | "down" | "enter" | "tab" | "escape"
+ )
+ {
return;
}
- let Ok(Some((input, observation))) = weak.update(cx, |owner, cx| {
+ let Ok(Some((input, key, value))) = weak.update(cx, |owner, cx| {
if !window
.input_focus_is_admitted(owner.state.read(cx).presentation().focus_handle())
{
return None;
}
+ if !owner.visible || !owner.accepts_text_input(window, cx) {
+ return None;
+ }
+ owner.refresh(false, window, cx);
+ let observation = EditorObservation {
+ revision: owner.revision,
+ snapshot: owner.observation_snapshot(),
+ receipt: owner.receipt.clone(),
+ };
let modifiers = &event.keystroke.modifiers;
+ if !modifiers.modified()
+ && owner
+ .navigation
+ .as_ref()
+ .is_some_and(|navigation| navigation.matches(&observation))
+ {
+ let key = match event.keystroke.key.as_str() {
+ "up" => Some(EditorNavigationKey::Up),
+ "down" => Some(EditorNavigationKey::Down),
+ "enter" => Some(EditorNavigationKey::Enter),
+ "tab" => Some(EditorNavigationKey::Tab),
+ "escape" => Some(EditorNavigationKey::Escape),
+ _ => None,
+ };
+ if let Some(key) = key {
+ return Some((
+ owner.input.clone(),
+ "navigate",
+ serde_json::to_value(EditorNavigated { key, observation })
+ .expect("native navigation"),
+ ));
+ }
+ }
+ if event.keystroke.key != "enter" {
+ return None;
+ }
let matches = match owner.submit {
Some(SubmitKey::Enter) => !modifiers.modified(),
Some(SubmitKey::ControlEnter) => {
@@ -227,11 +269,8 @@ impl TextareaOwner {
owner.input.current.borrow().as_ref()?;
Some((
owner.input.clone(),
- EditorObservation {
- revision: owner.revision,
- snapshot: owner.observation_snapshot(),
- receipt: owner.receipt.clone(),
- },
+ "submit",
+ serde_json::to_value(observation).expect("native submit observation"),
))
}) else {
return;
@@ -239,16 +278,8 @@ impl TextareaOwner {
window.prevent_default();
cx.stop_propagation();
// Leave the entity borrow before the original component dispatch.
- if input
- .capture_input(
- "submit",
- serde_json::to_value(observation).expect("native submit observation"),
- window,
- cx,
- )
- .is_err()
- {
- eprintln!("editor submit rejected");
+ if input.capture_input(key, value, window, cx).is_err() {
+ eprintln!("editor keyboard event rejected");
}
});
owner.update(cx, |owner, cx| {
@@ -423,6 +454,7 @@ impl TextareaOwner {
// This synchronous barrier is authoritative for command admission.
self.refresh(false, window, cx);
self.submit = props.submit;
+ self.navigation.clone_from(&props.navigation);
let appearance_changed = self.projection.data != props.appearance;
if appearance_changed {
self.projection = super::appearance::TextareaProjection::new(&props.appearance);
@@ -1051,6 +1083,7 @@ impl NativeComponent<dyn Widget> for TextareaComponent {
maka_ui_runtime::checkpoint::observation_schema(),
),
("submit".into(), observation_schema()),
+ ("navigate".into(), navigation_schema()),
]),
vec![],
)?
diff --git a/platform/render-terminal/src/application/editor.rs b/platform/render-terminal/src/application/editor.rs
index bd703701bd..2f7f724909 100644
--- a/platform/render-terminal/src/application/editor.rs
+++ b/platform/render-terminal/src/application/editor.rs
@@ -91,12 +91,15 @@ impl Owner {
marked: None,
}
}
- pub fn observation(&mut self) -> NativeInput {
- let observation = EditorObservation {
+ pub fn current_observation(&self) -> EditorObservation {
+ EditorObservation {
revision: self.revision,
snapshot: self.snapshot(),
receipt: self.receipt.clone(),
- };
+ }
+ }
+ pub fn observation(&mut self) -> NativeInput {
+ let observation = self.current_observation();
let replaceable = self.receipt == self.observed_receipt;
self.observed_receipt.clone_from(&self.receipt);
NativeInput {
diff --git a/platform/render-terminal/src/application/tests/textarea.rs b/platform/render-terminal/src/application/tests/textarea.rs
index 244e3044df..94e21adcf8 100644
--- a/platform/render-terminal/src/application/tests/textarea.rs
+++ b/platform/render-terminal/src/application/tests/textarea.rs
@@ -52,9 +52,9 @@ pub(super) fn editor_fixture() -> (tokio::runtime::Runtime, Input, Vec<Package>)
.replace("{kind:'button',key:'remove'", "{kind:'button',key:'reject',label:'Reject observation'},{kind:'button',key:'configure',label:'Configure editor'},{kind:'button',key:'remove'");
source.push_str("const normalFrame=frame;frame=(state)=>{const out=normalFrame(state);const editor=out.frame.view.children.find(node=>node.key==='editor');if(editor){editor.props={...editor.props,...state.options};delete editor.props.visible;delete editor.props.prefix;delete editor.props.readingViewport;}out.frame.view.children=out.frame.view.children.map(node=>node.key==='editor'?{kind:'stack',key:'presentation',direction:'column',gap:0,padding:0,background:out.frame [...]
}
- source = source.replace("on:{changed:'changed'}", "on:{changed:'changed',submitted:'submitted'}")
+ source = source.replace("on:{changed:'changed'}", "on:{changed:'changed',submitted:'submitted',navigated:'navigated'}")
.replace("name:'changed',value:event.event", "name:event.name,value:event.event")
- .replace("else if(event.kind==='component')next.observation=event.event;", "else if(event.kind==='component'){next.observation=event.event;if(event.name==='submitted')next.submissions=(state.submissions??0)+1;}");
+ .replace("else if(event.kind==='component')next.observation=event.event;", "else if(event.kind==='component'){if(event.name==='navigated'){next.navigation=event.event;next.navigations=(state.navigations??0)+1;}else next.observation=event.event;if(event.name==='submitted')next.submissions=(state.submissions??0)+1;}");
files.insert(module.clone(), source.into_bytes());
}
_ => {}
@@ -1001,6 +1001,66 @@ fn completely_clipped_editor_cannot_receive_focus_or_physical_input() {
assert_eq!(observation(&tui), before);
close(&mut tui);
}
+#[test]
+fn overflowing_editor_keeps_boundary_wheels_inside_its_scrollable_parent() {
+ let (_runtime, mut tui) = presenter();
+ dispatch(&mut tui, "configure", json!({"readingViewport":true}));
+ draw(&mut tui, 50, 20);
+ tui.input_settled(Event::Paste(
+ (0..20).map(|i| format!("\nrow {i:02}")).collect(),
+ ))
+ .unwrap();
+ draw(&mut tui, 50, 20);
+ let mount = draft(&tui);
+ let target = tui
+ .scene
+ .iter()
+ .find(|target| target.mount == mount)
+ .unwrap();
+ let point = target.area.visible();
+ let before = observation(&tui);
+ for direction in [MouseEventKind::ScrollUp, MouseEventKind::ScrollDown] {
+ for _ in 0..25 {
+ click(&mut tui, direction, point.x + 1, point.y + 1);
+ draw(&mut tui, 50, 20);
+ let state = tui.resources.owners[&tui.root.id()]
+ .state
+ .downcast_ref::<super::super::scroll::SceneState>()
+ .unwrap();
+ assert_eq!(state.scrolls["presentation"].offset, 0);
+ }
+ }
+ assert_eq!(observation(&tui), before);
+ close(&mut tui);
+}
+
+#[test]
+fn fitting_editor_leaves_wheel_scrolling_to_its_parent() {
+ let (_runtime, mut tui) = presenter();
+ dispatch(&mut tui, "configure", json!({"readingViewport":true}));
+ draw(&mut tui, 50, 20);
+ let mount = draft(&tui);
+ let point = tui
+ .scene
+ .iter()
+ .find(|target| target.mount == mount)
+ .unwrap()
+ .area
+ .visible();
+ click(
+ &mut tui,
+ MouseEventKind::ScrollDown,
+ point.x + 1,
+ point.y + 1,
+ );
+ let state = tui.resources.owners[&tui.root.id()]
+ .state
+ .downcast_ref::<super::super::scroll::SceneState>()
+ .unwrap();
+ assert!(state.scrolls["presentation"].offset > 0);
+ close(&mut tui);
+}
+
#[test]
fn unhandled_editor_page_key_reaches_its_original_scene_scroll_ancestor() {
let (_runtime, mut tui) = presenter();
@@ -1078,6 +1138,68 @@ fn pointer_capture_survives_tab_focus_change_and_release_keeps_the_new_focus() {
close(&mut tui);
}
+#[test]
+fn terminal_navigation_is_revision_bound_and_preserves_native_editing() {
+ let (_runtime, mut tui) = presenter();
+ draw(&mut tui, 50, 20);
+ tui.input_settled(Event::Paste("/co".into())).unwrap();
+ let original = observation(&tui);
+ let navigation =
+ json!({"owner":original["snapshot"]["text"]["owner"],"basedOn":original["revision"]});
+ dispatch(&mut tui, "configure", json!({"navigation":navigation}));
+ draw(&mut tui, 50, 20);
+ let focus = tui.focus.clone().unwrap();
+ for (index, code) in [
+ KeyCode::Up,
+ KeyCode::Down,
+ KeyCode::Tab,
+ KeyCode::Enter,
+ KeyCode::Esc,
+ ]
+ .into_iter()
+ .enumerate()
+ {
+ tui.input_settled(key(code)).unwrap();
+ assert_eq!(observation(&tui), original);
+ assert!(tui.focus.as_ref().unwrap().same(&focus));
+ assert_eq!(
+ tui.application.frame(&tui.root).unwrap().state["navigations"],
+ index + 1
+ );
+ assert_eq!(
+ tui.application.frame(&tui.root).unwrap().state["navigation"]["observation"],
+ original
+ );
+ }
+ tui.input_settled(Event::Paste("x".into())).unwrap();
+ tui.input_settled(key(KeyCode::Enter)).unwrap();
+ assert_eq!(
+ tui.application.frame(&tui.root).unwrap().state["navigations"],
+ 5
+ );
+ assert_eq!(
+ observation(&tui)["snapshot"]["text"]["bytes"],
+ original["snapshot"]["text"]["bytes"].as_u64().unwrap() + 2
+ );
+ let current = observation(&tui);
+ dispatch(
+ &mut tui,
+ "configure",
+ json!({"navigation":{"owner":"retired-owner","basedOn":current["revision"]}}),
+ );
+ draw(&mut tui, 50, 20);
+ tui.input_settled(key(KeyCode::Up)).unwrap();
+ assert_eq!(
+ tui.application.frame(&tui.root).unwrap().state["navigations"],
+ 5
+ );
+ assert_ne!(
+ observation(&tui)["snapshot"]["selection"],
+ current["snapshot"]["selection"]
+ );
+ close(&mut tui);
+}
+
#[test]
fn terminal_textarea_submit_keeps_native_draft_and_obeys_current_editor_policy() {
let (_runtime, mut tui) = presenter();
@@ -1513,13 +1635,13 @@ fn paste_then_enter_is_immediate_and_ordered_while_the_original_js_job_is_slow()
let declaration = original.manifest().application.as_ref().unwrap().declaration().clone();
let Implementation::JavaScript { module, .. } = &declaration.entries[&EntryTarget::Tui].implementation else { unreachable!() };
let mut source = std::str::from_utf8(original.file(module).unwrap()).unwrap()
- .replace("on:{changed:'changed',submitted:'submitted'}", "on:{changed:'changed',submitted:'submitted',checkpoint:'checkpoint'}");
+ .replace("on:{changed:'changed',submitted:'submitted',navigated:'navigated'}", "on:{changed:'changed',submitted:'submitted',checkpoint:'checkpoint'}");
if original.manifest().id == "dynamic.app" {
source = source.replace(
"if(event.key==='reject'){", "if(event.key==='reject'){const until=Date.now()+100;while(Date.now()<until){};",
).replace(
"next.observation=event.event;if(event.name==='submitted')next.submissions=(state.submissions??0)+1;",
- "if(event.name==='checkpoint'){next.nativeReady=event.event.state.initialized;}else{next.observation=event.event;if(event.name==='submitted'){if(!state.nativeReady)throw new Error('submission preceded its original checkpoint');next.submissions=(state.submissions??0)+1;}}",
+ "if(event.name==='checkpoint'){next.nativeReady=event.event.state.initialized;}else{if(event.name==='navigated'){next.navigation=event.event;next.navigations=(state.navigations??0)+1;}else next.observation=event.event;if(event.name==='submitted'){if(!state.nativeReady)throw new Error('submission preceded its original checkpoint');next.submissions=(state.submissions??0)+1;}}",
);
}
let package = support::package(&id, declaration, Some(source));
diff --git a/platform/render-terminal/src/application/textarea.rs b/platform/render-terminal/src/application/textarea.rs
index 26dc17e62e..ecbde504e9 100644
--- a/platform/render-terminal/src/application/textarea.rs
+++ b/platform/render-terminal/src/application/textarea.rs
@@ -267,6 +267,40 @@ impl Widget for Recipe {
WidgetInput::Consumed(None)
});
}
+ if !read_only
+ && owner.visible
+ && let Event::Key(key) = event
+ && key.modifiers.is_empty()
+ && let Some(navigation) = &self.props.navigation
+ {
+ owner.edit.refresh();
+ let observation = owner.edit.current_observation();
+ let navigation_key = match key.code {
+ KeyCode::Up => Some(EditorNavigationKey::Up),
+ KeyCode::Down => Some(EditorNavigationKey::Down),
+ KeyCode::Enter => Some(EditorNavigationKey::Enter),
+ KeyCode::Tab => Some(EditorNavigationKey::Tab),
+ KeyCode::Esc => Some(EditorNavigationKey::Escape),
+ _ => None,
+ };
+ if navigation.matches(&observation)
+ && let Some(key_value) = navigation_key
+ {
+ return Ok(if key.kind == KeyEventKind::Release {
+ WidgetInput::Consumed(None)
+ } else {
+ WidgetInput::Emitted(NativeInput {
+ key: "navigate".into(),
+ value: serde_json::to_value(EditorNavigated {
+ key: key_value,
+ observation,
+ })
+ .unwrap(),
+ replaceable: false,
+ })
+ });
+ }
+ }
if !read_only
&& owner.visible
&& let Event::Key(key) = event
@@ -359,6 +393,18 @@ impl Widget for Recipe {
.editor
.dragging()
}
+ fn handles_tab(&self, state: &dyn Any, _: &str) -> bool {
+ let owner = state.downcast_ref::<Owner>().unwrap();
+ !self.props.disabled
+ && !self.props.read_only
+ && owner.visible
+ && owner.persistence_ready()
+ && self
+ .props
+ .navigation
+ .as_ref()
+ .is_some_and(|navigation| navigation.matches(&owner.edit.current_observation()))
+ }
fn capture(
&self,
state: &dyn Any,
@@ -570,6 +616,7 @@ impl NativeComponent<dyn Widget> for Component {
maka_ui_runtime::checkpoint::observation_schema(),
),
("submit".into(), observation_schema()),
+ ("navigate".into(), navigation_schema()),
("file_choose".into(), maka_ui_runtime::file::choose_schema()),
("file_observe".into(), file_paste_schema()),
]),
diff --git a/platform/render-terminal/src/editor.rs b/platform/render-terminal/src/editor.rs
index 733cdfc612..a366f6128c 100644
--- a/platform/render-terminal/src/editor.rs
+++ b/platform/render-terminal/src/editor.rs
@@ -610,7 +610,9 @@ impl Editor {
self.top.saturating_sub(3)
};
if next == self.top {
- return false;
+ // Keep an overflowing editor's wheel gesture at its edge,
+ // matching desktop. Text that fits still yields to the page.
+ return !self.single_line && self.layout.rows.len() > area.height as usize;
}
self.top = next;
}
diff --git a/platform/ui-runtime/src/textarea.rs b/platform/ui-runtime/src/textarea.rs
index 4bf21835ef..612c085316 100644
--- a/platform/ui-runtime/src/textarea.rs
+++ b/platform/ui-runtime/src/textarea.rs
@@ -53,6 +53,9 @@ pub struct TextareaProps {
/// None preserves native multiline editing without a submit shortcut.
#[serde(default)]
pub submit: Option<SubmitKey>,
+ /// Yield suggestion navigation only for the original observed editor state.
+ #[serde(default)]
+ pub navigation: Option<EditorNavigation>,
#[schemars(range(min = -1, max = 32767))]
pub tab_index: i16,
/// Offer native focus once when this original input becomes visible and
@@ -186,6 +189,40 @@ pub enum SubmitKey {
ControlEnter,
}
+#[derive(Clone, Debug, Deserialize, Serialize, JsonSchema)]
+#[serde(rename_all = "camelCase", deny_unknown_fields)]
+pub struct EditorNavigation {
+ #[schemars(length(min = 1, max = 128))]
+ pub owner: String,
+ #[schemars(range(max = 9007199254740991u64))]
+ pub based_on: u64,
+}
+impl EditorNavigation {
+ pub fn matches(&self, observation: &EditorObservation) -> bool {
+ self.owner == observation.snapshot.text.owner
+ && self.based_on == observation.revision
+ && observation.snapshot.marked.is_none()
+ }
+}
+#[derive(Clone, Copy, Debug, Deserialize, Serialize, JsonSchema)]
+#[serde(rename_all = "snake_case")]
+pub enum EditorNavigationKey {
+ Up,
+ Down,
+ Enter,
+ Tab,
+ Escape,
+}
+#[derive(Clone, Debug, Deserialize, Serialize, JsonSchema)]
+#[serde(deny_unknown_fields)]
+pub struct EditorNavigated {
+ pub key: EditorNavigationKey,
+ pub observation: EditorObservation,
+}
+pub fn navigation_schema() -> serde_json::Value {
+ serde_json::to_value(schemars::schema_for!(EditorNavigated)).expect("editor navigation schema")
+}
+
/// Submit carries the same original editor observation as a change; it grants
/// no text read and adds no second buffer or command owner.
pub fn reduce(
@@ -206,7 +243,23 @@ pub fn reduce(
};
let mut files = None;
let mut checkpoint = None;
+ let mut navigation = None;
let call = match call {
+ crate::ComponentCall::Event {
+ state,
+ props,
+ key: "navigate",
+ input,
+ origin,
+ } => {
+ if !matches!(origin, crate::EventOrigin::Raw) {
+ return Err(crate::Error::Invalid(
+ "editor navigation requires native origin".into(),
+ ));
+ }
+ navigation = Some(input.clone());
+ crate::ComponentCall::Update { state, props }
+ }
crate::ComponentCall::Event {
state,
props,
@@ -299,6 +352,12 @@ pub fn reduce(
value,
});
}
+ if let Some(value) = navigation {
+ output.events.push(crate::Emission {
+ name: "navigated".into(),
+ value,
+ });
+ }
Ok(output.map_view(|props| TextareaView {
props,
file_request,
@@ -316,6 +375,7 @@ pub fn textarea_contract() -> Contract {
events: BTreeMap::from([
("changed".into(), observation_schema()),
("submitted".into(), observation_schema()),
+ ("navigated".into(), navigation_schema()),
("files".into(), file_paste_schema()),
("checkpoint".into(), crate::checkpoint::observation_schema()),
]),
diff --git a/plugins/agent/agent-screen/actions.ts b/plugins/agent/agent-screen/actions.ts
index c62984d0ec..ff9748746c 100644
--- a/plugins/agent/agent-screen/actions.ts
+++ b/plugins/agent/agent-screen/actions.ts
@@ -1056,6 +1056,26 @@ export function controlSidebar(state: State, op: TerminalPaneCommand['op']) {
}
}
+// Aliases only name existing root actions; availability and labels stay in rootCommands.
+export function composerCommands(state: State, locale: string, target: 'tui' | 'desktop') {
+ const aliases: Partial<Record<RootCommand, string>> = {
+ 'compact-open': 'compact',
+ create: 'new',
+ 'model-setup': 'model',
+ settings: 'settings',
+ 'help-open': 'help',
+ 'skills-open': 'skills',
+ 'plan-open': 'plan',
+ 'goal-open': 'goal',
+ 'recap-open': 'recap',
+ 'usage-open': 'usage',
+ 'terminal-open': 'terminal',
+ };
+ return rootCommands(state, locale, target).flatMap(({ kind, id, label, disabled }) =>
+ aliases[kind] ? [{ id, command: aliases[kind]!, label, disabled }] : [],
+ );
+}
+
export function rootCommand(
state: State,
actions: Action[],
diff --git a/plugins/agent/agent-screen/component-events.ts b/plugins/agent/agent-screen/component-events.ts
index f0abc1bd44..281b0e8432 100644
--- a/plugins/agent/agent-screen/component-events.ts
+++ b/plugins/agent/agent-screen/component-events.ts
@@ -17,7 +17,7 @@
* under the License.
*/
-import { compactComponent, openCompact } from './compact.js';
+import { compactComponent } from './compact.js';
import type {
Action,
AgentDirectorySelection,
@@ -105,13 +105,17 @@ export function handleComponent<N extends Node>(
locale: string,
) {
const target = presentation.target;
- if (input.child === 'composer' && input.name === 'compact') {
- const command = input.event as Pick<ComposerSent, 'context' | 'dataSource'>;
+ if (input.child === 'composer' && input.name === 'command') {
+ const command = input.event as Pick<ComposerSent, 'context' | 'dataSource'> & { id: string };
if (
command.context === state.selected?.id &&
sameValue(command.dataSource, state.selected.dataSource)
- )
- openCompact(state, actions);
+ ) {
+ const available = rootCommands(state, locale, target).find(
+ (item) => item.id === command.id && !item.disabled,
+ );
+ if (available) rootCommand(state, actions, locale, available.kind, target);
+ }
return frame(presentation, configuredLocale, state, values, actions);
}
if (compactComponent(state, input))
diff --git a/plugins/agent/agent-screen/conversation-view.ts b/plugins/agent/agent-screen/conversation-view.ts
index 25c0648d1b..3d7e1f7733 100644
--- a/plugins/agent/agent-screen/conversation-view.ts
+++ b/plugins/agent/agent-screen/conversation-view.ts
@@ -29,6 +29,7 @@ import { draftReady } from '../../shared/drafts.js';
import {
canExecute,
+ composerCommands,
reviewTarget,
selectedBackend,
catalogPending,
@@ -263,6 +264,7 @@ export function conversationView<N extends Node>(
['service_approval', 'permissions', 'client_capability'].includes(
reviewTarget(state)?.kind ?? '',
),
+ commands: composerCommands(state, locale, target),
backend: canExecute(state) ? selectedBackend(state) : null,
context: state.selected?.id ?? null,
dataSource: state.selected?.dataSource ?? null,
@@ -307,7 +309,7 @@ export function conversationView<N extends Node>(
autoFocus: !state.searchOpen && state.browse === null,
},
{
- compact: 'compact',
+ command: 'command',
sent: 'sent',
submission: 'submission',
setup: 'setup',
diff --git a/plugins/agent/assistant-preferences/index.ts b/plugins/agent/assistant-preferences/index.ts
index b06cbf7e4f..dc0bd7efe4 100644
--- a/plugins/agent/assistant-preferences/index.ts
+++ b/plugins/agent/assistant-preferences/index.ts
@@ -211,7 +211,7 @@ export function assistantPreferences<N extends Node>(
...common,
appearance: props.theme.textarea,
softWrap: true,
- terminalRows: { min: 3, max: 5 },
+ terminalRows: name === 'compaction' ? { min: 6, max: 12 } : { min: 3, max: 5 },
} satisfies TextareaProps,
{ changed: 'changed' },
);
diff --git a/plugins/agent/composer/component.ts b/plugins/agent/composer/component.ts
index 74a81fafac..e245cf5c56 100644
--- a/plugins/agent/composer/component.ts
+++ b/plugins/agent/composer/component.ts
@@ -55,7 +55,8 @@ interface Submission {
preview?: { key: string; text: string };
context: string;
dataSource: AgentDataSource;
- backend: ComposerBackend;
+ backend: ComposerBackend | null;
+ command?: string;
draft: EditorObservation;
attachments: string[];
}
@@ -69,7 +70,15 @@ type Delivery =
checking: string | null;
}
| { kind: 'clear'; command: EditorCommand; caller: CallerConfirmation | null };
+interface Prefix {
+ read: { key: string; observation: EditorObservation } | null;
+ attempted: EditorObservation['snapshot']['text'] | null;
+ cached: { metadata: EditorObservation['snapshot']['text']; text: string } | null;
+ selected: number;
+ dismissed: number | null;
+}
interface DraftEntry {
+ prefix: Prefix;
dataSource: AgentDataSource;
checkpoint: EditorCheckpointObservation | null;
retry: number;
@@ -79,7 +88,7 @@ interface DraftEntry {
files: FilePasteObservation | null;
history: { after: number; scope: string | null };
delivery: Delivery | null;
- notice: 'draftKept' | 'empty' | 'skillInputUnavailable' | null;
+ notice: 'draftKept' | 'empty' | 'skillInputUnavailable' | 'unknownCommand' | null;
}
interface Draft {
revision: number;
@@ -90,6 +99,42 @@ interface Draft {
recovery: { key: string; step: DraftStep } | null;
reported: ComposerReadiness[];
}
+// Only a single slash token is command input. Paths and multiline drafts stay prose.
+function slashQuery(text: string): string | null {
+ return /^\/[^\s/\\]*$/u.test(text) ? text.slice(1).toLocaleLowerCase() : null;
+}
+function candidates(props: ComposerProps, text: string) {
+ const query = slashQuery(text);
+ return query === null
+ ? []
+ : (props.commands ?? []).filter(
+ (item) =>
+ !item.disabled &&
+ (item.command.toLocaleLowerCase().includes(query) ||
+ item.label.toLocaleLowerCase().includes(query)),
+ );
+}
+function prefixText(entry: DraftEntry) {
+ return sameValue(entry.prefix.cached?.metadata, entry.observation?.snapshot.text)
+ ? (entry.prefix.cached?.text ?? null)
+ : null;
+}
+function snapshotRead(key: string, entry: DraftEntry, observation: EditorObservation): Action {
+ return {
+ ...action(key, 'reader', 'read', { start: 0, end: observation.snapshot.text.bytes }),
+ resources: {
+ text: {
+ child: entry.key,
+ method: 'snapshot',
+ input: {
+ kind: 'at_revision',
+ owner: observation.snapshot.text.owner,
+ revision: observation.snapshot.text.revision,
+ },
+ },
+ },
+ };
+}
function action(key: string, binding: string, method: string, input: unknown): Action {
return { key, binding, member: 0, method, input, resources: {}, continuations: [] };
}
@@ -211,6 +256,7 @@ export function composer<N extends Node>(
}
if (state.entries.length < 32)
state.entries.push({
+ prefix: { read: null, attempted: null, cached: null, selected: 0, dismissed: null },
context: props.context,
dataSource: props.dataSource,
checkpoint: null,
@@ -232,6 +278,37 @@ export function composer<N extends Node>(
if (current?.checkpoint?.state.kind === 'restore') current.retry++;
}
const pending = !!current?.delivery;
+ if (
+ current &&
+ observation &&
+ !pending &&
+ !current.prefix.read &&
+ observation.snapshot.text.bytes > 0 &&
+ observation.snapshot.text.bytes <= 128 &&
+ !observation.snapshot.marked &&
+ !sameValue(current.prefix.attempted, observation.snapshot.text)
+ ) {
+ const key = `prefix-${++state.serial}`;
+ current.prefix.read = { key, observation };
+ current.prefix.attempted = observation.snapshot.text;
+ actions.push(snapshotRead(key, current, observation));
+ }
+ const shortText = current ? prefixText(current) : null;
+ const menuOpen =
+ !!current &&
+ !!observation &&
+ !pending &&
+ props.enabled &&
+ !props.busy &&
+ !observation.snapshot.marked &&
+ current.prefix.dismissed !== observation.snapshot.text.revision &&
+ shortText !== null &&
+ slashQuery(shortText) !== null;
+ const choices = menuOpen ? candidates(props, shortText!) : [];
+ if (current)
+ current.prefix.selected = Math.min(current.prefix.selected, Math.max(0, choices.length - 1));
+ const selected = current?.prefix.selected ?? 0;
+ const first = Math.max(0, selected - 5);
const attached = props.attachments.filter(
(file) => file.sessionId === props.context && sameValue(file.dataSource, props.dataSource),
);
@@ -347,6 +424,10 @@ export function composer<N extends Node>(
retry: entry.retry,
},
autoFocus: entry === current && props.autoFocus,
+ navigation:
+ entry === current && menuOpen && observation
+ ? { owner: observation.snapshot.text.owner, basedOn: observation.revision }
+ : null,
command: entry.delivery?.kind === 'clear' ? entry.delivery.command : null,
filePaste:
entry === current
@@ -361,6 +442,7 @@ export function composer<N extends Node>(
},
{
changed: 'changed',
+ navigated: 'navigated',
submitted: 'submitted',
files: 'files',
checkpoint: 'checkpoint',
@@ -511,6 +593,33 @@ export function composer<N extends Node>(
),
]
: []),
+ ...(menuOpen
+ ? [
+ ui.box(
+ 'slash-menu',
+ [
+ ...choices
+ .slice(first, first + 6)
+ .map((item, index) =>
+ ui.button(
+ `slash:${item.id}`,
+ `${first + index === selected ? '› ' : ' '}/${item.command} ${item.label}`,
+ false,
+ first + index === selected,
+ { width: fill, align: 'start' },
+ undefined,
+ item.label,
+ ),
+ ),
+ ...(!choices.length
+ ? [ui.text('slash-empty', text.unknownCommand, 13, props.theme.muted)]
+ : []),
+ ui.text('slash-hint', text.commandHint, 12, props.theme.muted),
+ ],
+ { gap: 0, style: { width: fill }, terminal: { shrink: false } },
+ ),
+ ]
+ : []),
body,
],
{ style: { width: fill }, terminal: { shrink: true } },
@@ -544,6 +653,27 @@ export function composer<N extends Node>(
actions: Action[] = [];
if (input.kind === 'action') {
const outcome = input.event as ActionOutcome;
+ const prefixEntry = state.entries.find((entry) => entry.prefix.read?.key === input.key);
+ if (prefixEntry?.prefix.read) {
+ const read = prefixEntry.prefix.read;
+ prefixEntry.prefix.read = null;
+ if (outcome.status === 'succeeded') {
+ const chunk = outcome.value as TextChunk;
+ if (
+ sameValue(chunk.metadata, read.observation.snapshot.text) &&
+ sameValue(chunk.metadata, prefixEntry.observation?.snapshot.text) &&
+ new TextEncoder().encode(chunk.text).length ===
+ read.observation.snapshot.text.bytes &&
+ read.observation.snapshot.text.bytes <= 128
+ ) {
+ prefixEntry.prefix.cached = {
+ metadata: read.observation.snapshot.text,
+ text: chunk.text,
+ };
+ }
+ }
+ return composerFrame(state, props, events, actions);
+ }
if (state.recovery?.key === input.key) {
const step = state.recovery.step;
state.recovery = null;
@@ -573,21 +703,42 @@ export function composer<N extends Node>(
new TextEncoder().encode(chunk.text).length === submission.draft.snapshot.text.bytes
) {
if (!chunk.text.trim() && !submission.attachments.length) entry.notice = 'empty';
- else if (chunk.text.trim() === '/compact' && !submission.attachments.length) {
- events.push({
- name: 'compact',
- value: { context: submission.context, dataSource: submission.dataSource },
- });
- entry.delivery = {
- kind: 'clear',
- caller: null,
- command: {
- owner: submission.draft.snapshot.text.owner,
- sequence: ++state.serial,
- basedOn: submission.draft.revision,
- edit: { kind: 'reset', text: '' },
- },
- };
+ else if (slashQuery(chunk.text) !== null) {
+ const command = submission.command
+ ? candidates(props, chunk.text).find((item) => item.id === submission.command)
+ : (props.commands ?? []).find(
+ (item) => !item.disabled && `/${item.command}` === chunk.text,
+ );
+ if (
+ command &&
+ submission.context === props.context &&
+ sameValue(submission.dataSource, props.dataSource) &&
+ props.enabled &&
+ !props.busy &&
+ !submission.attachments.length &&
+ sameValue(entry.observation?.snapshot.text, submission.draft.snapshot.text)
+ ) {
+ events.push({
+ name: 'command',
+ value: {
+ context: submission.context,
+ dataSource: submission.dataSource,
+ id: command.id,
+ },
+ });
+ entry.delivery = {
+ kind: 'clear',
+ caller: null,
+ command: {
+ owner: submission.draft.snapshot.text.owner,
+ sequence: ++state.serial,
+ basedOn: submission.draft.revision,
+ edit: { kind: 'reset', text: '' },
+ },
+ };
+ } else entry.notice = command ? 'draftKept' : 'unknownCommand';
+ } else if (!submission.backend) {
+ events.push({ name: 'setup', value: { context: submission.context } });
} else {
const key = `send-${++state.serial}`,
backend = submission.backend;
@@ -682,7 +833,18 @@ export function composer<N extends Node>(
source &&
(input.name === 'changed' || input.name === 'submitted')
) {
- source.observation = input.event as EditorObservation;
+ const next = input.event as EditorObservation;
+ if (
+ source.observation &&
+ next.snapshot.text.owner === source.observation.snapshot.text.owner &&
+ next.revision < source.observation.revision
+ )
+ return composerFrame(state, props);
+ if (!sameValue(source.observation?.snapshot.text, next.snapshot.text)) {
+ source.prefix.selected = 0;
+ source.prefix.cached = null;
+ }
+ source.observation = next;
const delivery = source.delivery,
receipt = source.observation.receipt;
if (
@@ -700,6 +862,52 @@ export function composer<N extends Node>(
(entry) => entry.context === props.context && sameValue(entry.dataSource, props.dataSource),
);
const observation = current?.observation;
+ let command: string | undefined;
+ const shortText = current ? prefixText(current) : null;
+ const choices = shortText === null ? [] : candidates(props, shortText);
+ const menuOpen =
+ current &&
+ observation &&
+ shortText !== null &&
+ slashQuery(shortText) !== null &&
+ current.prefix.dismissed !== observation.snapshot.text.revision &&
+ !observation.snapshot.marked &&
+ props.enabled &&
+ !props.busy &&
+ !current.delivery;
+ if (input.kind === 'component' && source === current && input.name === 'navigated') {
+ const navigation = input.event as {
+ key: 'up' | 'down' | 'enter' | 'tab' | 'escape';
+ observation: EditorObservation;
+ };
+ if (!menuOpen || !sameValue(navigation.observation, observation))
+ return composerFrame(state, props);
+ const selected = Math.min(current.prefix.selected, Math.max(0, choices.length - 1));
+ if (navigation.key === 'escape')
+ current.prefix.dismissed = observation.snapshot.text.revision;
+ else if (navigation.key === 'up' || navigation.key === 'down')
+ current.prefix.selected = choices.length
+ ? (selected + (navigation.key === 'up' ? -1 : 1) + choices.length) % choices.length
+ : 0;
+ else if (choices[selected] && navigation.key === 'tab') {
+ current.delivery = {
+ kind: 'clear',
+ caller: null,
+ command: {
+ owner: observation.snapshot.text.owner,
+ sequence: ++state.serial,
+ basedOn: observation.revision,
+ edit: { kind: 'replace', text: `/${choices[selected].command}` },
+ },
+ };
+ } else if (choices[selected] && navigation.key === 'enter') command = choices[selected].id;
+ if (!command) return composerFrame(state, props);
+ }
+ if (input.kind === 'raw' && input.key.startsWith('slash:')) {
+ if (!menuOpen) return composerFrame(state, props);
+ command = choices.find((item) => `slash:${item.id}` === input.key)?.id;
+ if (!command) return composerFrame(state, props);
+ }
if (input.kind === 'raw' && input.key === 'draft-retry' && current?.checkpoint) {
if (current.delivery?.kind === 'unknown') {
if (!current.delivery.checking) {
@@ -712,14 +920,15 @@ export function composer<N extends Node>(
return composerFrame(state, props, [], actions);
}
if (
- ((input.kind === 'raw' && input.key === 'send') ||
+ (command !== undefined ||
+ (input.kind === 'raw' && input.key === 'send') ||
(input.kind === 'component' && source === current && input.name === 'submitted')) &&
current?.checkpoint?.state.kind === 'ready' &&
current.checkpoint.state.initialized &&
props.enabled &&
!props.busy &&
!current.delivery &&
- (target === 'tui' || !props.running) &&
+ (command !== undefined || target === 'tui' || !props.running) &&
observation &&
!observation.snapshot.marked
) {
@@ -731,10 +940,6 @@ export function composer<N extends Node>(
.map((file) => file.id);
if (!observation.snapshot.text.bytes && !attachments.length)
return composerFrame(state, props);
- if (!props.backend)
- return composerFrame(state, props, [
- { name: 'setup', value: { context: current.context } },
- ]);
const key = `read-${++state.serial}`;
current.notice = null;
current.delivery = {
@@ -744,24 +949,12 @@ export function composer<N extends Node>(
context: current.context,
dataSource: current.dataSource,
backend: props.backend,
+ ...(command ? { command } : {}),
draft: observation,
attachments,
},
};
- actions.push({
- ...action(key, 'reader', 'read', { start: 0, end: observation.snapshot.text.bytes }),
- resources: {
- text: {
- child: current.key,
- method: 'snapshot',
- input: {
- kind: 'at_revision',
- owner: observation.snapshot.text.owner,
- revision: observation.snapshot.text.revision,
- },
- },
- },
- });
+ actions.push(snapshotRead(key, current, observation));
return composerFrame(state, props, [], actions);
}
if (input.kind === 'raw' && input.key === 'attach' && props.context && !props.busy)
diff --git a/plugins/agent/composer/locale.ts b/plugins/agent/composer/locale.ts
index c459a9afa2..4da41d39ae 100644
--- a/plugins/agent/composer/locale.ts
+++ b/plugins/agent/composer/locale.ts
@@ -75,7 +75,14 @@ const messages = {
undo: msg_undo,
unknown: msg_unknown,
};
-export const copy = /* @__PURE__ */ createCopy(messages);
+const baseCopy = /* @__PURE__ */ createCopy(messages);
+export const copy = (locale: string) => ({
+ ...baseCopy(locale),
+ unknownCommand: locale.startsWith('zh') ? '没有可用的匹配命令' : 'No matching commands available',
+ commandHint: locale.startsWith('zh')
+ ? '↑↓ 选择 · Enter 执行 · Tab 补全 · Esc 关闭'
+ : '↑↓ select · Enter run · Tab complete · Esc dismiss',
+});
export type Copy = ReturnType<typeof copy>;
const terminalMessages = {
diff --git a/plugins/shared/contracts.ts b/plugins/shared/contracts.ts
index 11064c9e45..fd3c21ab87 100644
--- a/plugins/shared/contracts.ts
+++ b/plugins/shared/contracts.ts
@@ -333,7 +333,14 @@ export interface ComposerSent {
dataSource: AgentDataSource;
attachments: string[];
}
+export interface ComposerCommand {
+ id: string;
+ command: string;
+ label: string;
+ disabled: boolean;
+}
export interface ComposerProps {
+ commands?: ComposerCommand[];
approvalPending?: boolean;
backend: ComposerBackend | null;
sendLabel?: string;
@@ -1171,6 +1178,16 @@ export const composerContract = component(
object(
{
approvalPending: { type: 'boolean' },
+ commands: {
+ type: 'array',
+ maxItems: 32,
+ items: object({
+ id: string,
+ command: string,
+ label: string,
+ disabled: { type: 'boolean' },
+ }),
+ },
backend: composerBackend,
sendLabel: string,
context: { anyOf: [{ type: 'string', minLength: 1, maxLength: 512 }, { type: 'null' }] },
@@ -1227,7 +1244,9 @@ export const composerContract = component(
attachments: { type: 'array', maxItems: 8, items: string },
}),
),
- compact: withDefs(object({ context: string, dataSource: { $ref: '#/$defs/AgentDataSource' } })),
+ command: withDefs(
+ object({ context: string, dataSource: { $ref: '#/$defs/AgentDataSource' }, id: string }),
+ ),
setup: object({ context: string }),
readiness: withDefs({
type: 'array',
diff --git a/products/maka/bundle/tests/compact.test.mjs b/products/maka/bundle/tests/compact.test.mjs
index b287db5814..798184fc74 100644
--- a/products/maka/bundle/tests/compact.test.mjs
+++ b/products/maka/bundle/tests/compact.test.mjs
@@ -109,8 +109,8 @@ for (const target of ['tui', 'desktop']) {
c.event({
kind: 'component',
child: 'composer',
- name: 'compact',
- event: { context: 'session', dataSource: c.state.selected.dataSource },
+ name: 'command',
+ event: { context: 'session', dataSource: c.state.selected.dataSource, id: 'compact-open' },
});
assert.equal(c.state.dialog, 'compact');
assert.deepEqual(c.out.actions[0].input, { sessionId: 'session' });
@@ -160,8 +160,8 @@ for (const target of ['tui', 'desktop']) {
c.event({
kind: 'component',
child: 'composer',
- name: 'compact',
- event: { context: 'session', dataSource: c.state.selected.dataSource },
+ name: 'command',
+ event: { context: 'session', dataSource: c.state.selected.dataSource, id: 'compact-open' },
});
open();
c.reply({ compactionPrompt: 'Default', defaultCompactionPrompt: 'Default' });
@@ -187,8 +187,8 @@ for (const target of ['tui', 'desktop'])
c.event({
kind: 'component',
child: 'composer',
- name: 'compact',
- event: { context: 'session', dataSource: c.state.selected.dataSource },
+ name: 'command',
+ event: { context: 'session', dataSource: c.state.selected.dataSource, id: 'compact-open' },
});
c.reply({ compactionPrompt: 'Default', defaultCompactionPrompt: 'Default' });
c.ready();
diff --git a/products/maka/bundle/tests/composer.test.mjs b/products/maka/bundle/tests/composer.test.mjs
index 4cac02c210..2909478954 100644
--- a/products/maka/bundle/tests/composer.test.mjs
+++ b/products/maka/bundle/tests/composer.test.mjs
@@ -109,6 +109,11 @@ function slot(node, key = 'draft') {
async function client(target) {
const { component } = await import(`../dist/packages/composer/${target}.js`);
const props = {
+ commands: [
+ { id: 'compact-open', command: 'compact', label: '压缩上下文', disabled: false },
+ { id: 'create', command: 'new', label: 'New conversation', disabled: false },
+ { id: 'settings', command: 'settings', label: 'Settings', disabled: false },
+ ],
backend: structuredClone(backend),
context: 'session',
dataSource,
@@ -539,13 +544,14 @@ for (const target of ['tui', 'desktop']) {
c.ready('/compact');
c.send('/compact');
assert.deepEqual(c.out.events, [
- { name: 'compact', value: { context: 'session', dataSource } },
+ { name: 'command', value: { context: 'session', dataSource, id: 'compact-open' } },
]);
assert.deepEqual(c.editor().command.edit, { kind: 'reset', text: '' });
c.clear();
- c.ready('/compact is a command');
- c.send('/compact is a command');
- assert.deepEqual(c.out.actions[0].input, {
+ const prose = await client(target);
+ prose.ready('/compact is a command');
+ prose.send('/compact is a command');
+ assert.deepEqual(prose.out.actions[0].input, {
sessionId: 'session',
message: '/compact is a command',
attachments: [],
@@ -554,3 +560,163 @@ for (const target of ['tui', 'desktop']) {
});
});
}
+
+for (const target of ['tui', 'desktop']) {
+ const has = (c, key) => JSON.stringify(c.out.frame.view).includes(`"key":"${key}"`);
+ const resolvePrefix = (c, text, revision = 1) =>
+ c.reply(
+ {
+ status: 'succeeded',
+ value: { metadata: observed(text, revision).snapshot.text, text },
+ },
+ c.out.actions.find((item) => item.key.startsWith('prefix-')).key,
+ );
+ test(`${target} slash menu filters aliases and localized labels and keeps native text out of state`, async () => {
+ const c = await client(target);
+ c.ready('/');
+ resolvePrefix(c, '/');
+ assert.ok(has(c, 'slash:compact-open'));
+ assert.ok(has(c, 'slash:create'));
+ assert.deepEqual(c.editor().navigation, { owner: 'editor', basedOn: 1 });
+ c.emit('changed', observed('/压缩', 2));
+ assert.equal(c.editor().navigation, null);
+ resolvePrefix(c, '/压缩', 2);
+ assert.ok(has(c, 'slash:compact-open'));
+ assert.equal(has(c, 'slash:create'), false);
+ c.emit('changed', observed('x'.repeat(129), 3));
+ assert.deepEqual(c.out.actions, []);
+ assert.equal(has(c, 'slash-menu'), false);
+ assert.equal(JSON.stringify(c.state).includes('x'.repeat(129)), false);
+ });
+ test(`${target} slash reads coalesce and stale results cannot restore a menu`, async () => {
+ const c = await client(target);
+ c.ready('/');
+ const first = c.out.actions[0].key;
+ c.emit('changed', observed('/c', 2));
+ c.emit('changed', observed('/new', 3));
+ assert.deepEqual(c.out.actions, []);
+ c.reply(
+ { status: 'succeeded', value: { metadata: observed('/').snapshot.text, text: '/' } },
+ first,
+ );
+ assert.equal(has(c, 'slash-menu'), false);
+ assert.equal(c.out.actions.length, 1);
+ resolvePrefix(c, '/new', 3);
+ assert.ok(has(c, 'slash:create'));
+ assert.equal(has(c, 'slash:compact-open'), false);
+ });
+ test(`${target} slash keyboard selection executes locally without a model and Escape retains draft`, async () => {
+ const c = await client(target);
+ c.props.backend = null;
+ c.ready('/');
+ resolvePrefix(c, '/');
+ c.emit('navigated', { key: 'down', observation: observed('/') });
+ c.emit('navigated', { key: 'enter', observation: observed('/') });
+ c.reply({ status: 'succeeded', value: { metadata: observed('/').snapshot.text, text: '/' } });
+ assert.deepEqual(c.out.events, [
+ { name: 'command', value: { context: 'session', dataSource, id: 'create' } },
+ ]);
+ assert.equal(
+ c.out.actions.some((action) => action.binding === 'agent'),
+ false,
+ );
+ c.clear();
+ c.emit('changed', observed('/settings', 3));
+ resolvePrefix(c, '/settings', 3);
+ c.emit('navigated', { key: 'escape', observation: observed('/settings', 3) });
+ assert.equal(c.editor().navigation, null);
+ assert.equal(c.editor().command, null);
+ assert.equal(c.state.entries[0].observation.snapshot.text.bytes, 9);
+ });
+ test(`${target} click validates captured command and tab completes without executing`, async () => {
+ const c = await client(target);
+ c.ready('/co');
+ resolvePrefix(c, '/co');
+ c.emit('navigated', { key: 'tab', observation: observed('/co') });
+ assert.deepEqual(c.editor().command.edit, { kind: 'replace', text: '/compact' });
+ assert.deepEqual(c.out.events, []);
+ c.clear();
+ c.emit('changed', observed('/co', 3));
+ resolvePrefix(c, '/co', 3);
+ c.raw('slash:compact-open');
+ c.reply({
+ status: 'succeeded',
+ value: { metadata: observed('/co', 3).snapshot.text, text: '/co' },
+ });
+ assert.equal(c.out.events[0].value.id, 'compact-open');
+ });
+ test(`${target} unknown and disabled commands never submit and inactive captures retain drafts`, async () => {
+ for (const command of ['/unknown', '/compact']) {
+ const c = await client(target);
+ c.props.commands[0].disabled = true;
+ c.ready(command);
+ resolvePrefix(c, command);
+ assert.ok(has(c, 'slash-empty'));
+ c.send(command);
+ assert.equal(
+ c.out.actions.some((action) => action.binding === 'agent'),
+ false,
+ );
+ assert.equal(c.editor().command, null);
+ assert.deepEqual(c.out.events, []);
+ }
+ const c = await client(target);
+ c.ready('/compact');
+ c.emit('submitted', observed('/compact'));
+ const read = c.out.actions[0].key;
+ c.props.context = 'another';
+ c.update();
+ c.reply(
+ {
+ status: 'succeeded',
+ value: { metadata: observed('/compact').snapshot.text, text: '/compact' },
+ },
+ read,
+ );
+ assert.equal(c.editor('draft').command, null);
+ assert.equal(c.state.entries[0].notice, 'draftKept');
+ assert.equal(
+ c.out.events.some((event) => event.name === 'command'),
+ false,
+ );
+ });
+ test(`${target} stale navigation and IME retain normal editing; paths and multiline text send normally`, async () => {
+ const c = await client(target);
+ c.ready('/');
+ resolvePrefix(c, '/');
+ c.emit('navigated', { key: 'enter', observation: observed('/', 0) });
+ assert.deepEqual(c.out.actions, []);
+ const marked = observed('/', 2);
+ marked.snapshot.marked = { start: 0, end: 1 };
+ c.emit('changed', marked);
+ assert.equal(c.editor().navigation, null);
+ for (const text of ['/tmp/file', '/a\nb']) {
+ const normal = await client(target);
+ normal.ready(text);
+ normal.send(text);
+ assert.equal(normal.out.actions[0].input.message, text);
+ }
+ });
+}
+
+for (const target of ['tui', 'desktop']) {
+ test(`${target} command menu shows six rows and scrolls selection across the catalog`, async () => {
+ const c = await client(target);
+ c.props.commands = Array.from({ length: 10 }, (_, i) => ({
+ id: `command-${i}`,
+ command: `command${i}`,
+ label: `Command ${i}`,
+ disabled: false,
+ }));
+ c.ready('/');
+ c.reply({ status: 'succeeded', value: { metadata: observed('/').snapshot.text, text: '/' } });
+ const rows = () => [...JSON.stringify(c.out.frame.view).matchAll(/"key":"slash:command-\d+"/g)];
+ assert.equal(rows().length, 6);
+ c.emit('navigated', { key: 'up', observation: observed('/') });
+ assert.equal(rows().length, 6);
+ assert.ok(JSON.stringify(c.out.frame.view).includes('slash:command-9'));
+ c.emit('navigated', { key: 'enter', observation: observed('/') });
+ c.reply({ status: 'succeeded', value: { metadata: observed('/').snapshot.text, text: '/' } });
+ assert.equal(c.out.events[0].value.id, 'command-9');
+ });
+}
diff --git a/products/maka/cli/notices.json b/products/maka/cli/notices.json
index 9c86cf516b..238bad8406 100644
--- a/products/maka/cli/notices.json
+++ b/products/maka/cli/notices.json
@@ -5,8 +5,8 @@
"package-lock.json": "a5af15aca21fabe0e1bdd48784167df4dc81cee17777d54861dcbd641168a4eb",
"package.json": "38baf3beeb5876849ca16e31868d59bfaee769f260c7555b4a8a1847b92e28a1",
"packages/plugin-sdk/src/configurations.ts": "f2e890798ac26c9962e182c43331d570a0a76eabc13fdd8af9b167fcd2e2365f",
- "packages/plugin-sdk/src/contracts.ts": "2ca8edcb5eca868a6b9fdef780f9a4ef5aba5636edbb1ce608ebd3d52eeb7307",
- "packages/plugin-sdk/src/generated/runtime.ts": "c047eda314ec8ed841ce919dc8982a5b341e1e848109532c97f2fd55054f35e8",
+ "packages/plugin-sdk/src/contracts.ts": "c46b215224bdd741b9b406a2b6f236a1cbceb11ff62100918ba6527d71878492",
+ "packages/plugin-sdk/src/generated/runtime.ts": "2aaccbee525951c2fdb5dd4050579eef6f2abd349217fb13ffbb3f1a3bbe0719",
"packages/plugin-sdk/src/index.ts": "27b68be5a29d1857f7fe361c8c678e77ba21413c79ec3870c1ce30d0faf9323f",
"packages/plugin-sdk/src/native.ts": "2cf374759664132f1eba27b3c49c375174ad7e748e6d28a68ed07dde7ab05bf7",
"packages/plugin-sdk/src/ui.ts": "d6c64e9406c41ad6bbda73435b559aad24c31adb3c5bbb4ab6f49fff8a8330ca",
@@ -43,12 +43,12 @@
"plugins/agent/acp-executor/engine/tests/support/tui-auth.mjs": "b66436ace65b5874b6cd3ab66ece94984552c4a0772a0ae2d9b05db6b9f47d0f",
"plugins/agent/acp-executor/native/Cargo.toml": "6a896cb424d361ef3a98efa56a92ffc8680156473822bd1d38374b60f3f1da66",
"plugins/agent/acp-executor/package.ts": "d85747d6f02da7a316859d04d87706bf425699b90bf4053198a64b50eabd391f",
- "plugins/agent/agent-screen/actions.ts": "1bbfa94d989609dc3e4d006a96a3e5f6d20b09496bbe437d50672483d9b70e8a",
+ "plugins/agent/agent-screen/actions.ts": "2bfdeec0d1148005d53a64e5459cb76eb03657c9a872d1ed9695f8f2edcb0945",
"plugins/agent/agent-screen/checklist-view.ts": "e2976d6408df0407af4c26c9221a143761197f800f7a4f620639dad80091192f",
"plugins/agent/agent-screen/compact.ts": "aa90a96bde5769e32b7b3f8a98315997ff5202bc315286eec21710f6a7f08050",
- "plugins/agent/agent-screen/component-events.ts": "b74e44f6a3a936225d7af7f75148041741b96bdf0d9d48908e0afca36673f4a3",
+ "plugins/agent/agent-screen/component-events.ts": "5e3c8033662f48c9fed5a3038cb3fe08e7ad6b052c0f440d42b06044ea160887",
"plugins/agent/agent-screen/composer-status.ts": "ff8380142e1b247d508b5be10d2089b353019de8a705169703fd53f3008b2db9",
- "plugins/agent/agent-screen/conversation-view.ts": "75fda3997452bab76d56ba5806ae25eebd772f00dbe9ceb01c78c804baf8570e",
+ "plugins/agent/agent-screen/conversation-view.ts": "5daccf33f16994ae876b51671a9c13d970067c36ca51dcf7dc3d3e6b35b0d41c",
"plugins/agent/agent-screen/desktop.ts": "9cd44cb6a5225feead1aa87fc4e2d7935b994022fa38175342330119e72c4660",
"plugins/agent/agent-screen/events.ts": "b2ff520c01548565b1da878a265039edde35fb976229b7b4d0abfa5128a36050",
"plugins/agent/agent-screen/frame.ts": "6629873dce002ea72a9fa9cfff8dceced73ea443b7e286adf7962cf2bf2cd391",
@@ -72,7 +72,7 @@
"plugins/agent/agent/package.ts": "d4929e8b6e276705dbb3049b840ea64f53dd7d52176e2036d2f769df5e7bc82f",
"plugins/agent/api/Cargo.toml": "7f33b8ad23980598820684a18fbde28a078a8624e951147564da3d121736fecc",
"plugins/agent/assistant-preferences/desktop.ts": "7f5cc8f2087bf85f6b32b94b9110f87cf2acb6d46da9d581efc19c886c2ecd80",
- "plugins/agent/assistant-preferences/index.ts": "b00f74fdb772a604a1a05d2f6725f762ee1f5b2d0ee86302d1f7262a0fa7f45c",
+ "plugins/agent/assistant-preferences/index.ts": "5d312367fdd0488c06f4627e8b37b586a8aaef874c278f469be2b5696e34b759",
"plugins/agent/assistant-preferences/locale.ts": "604c27325f390a069c40217af0df7bc3ad5b891a2198e6d4dee804b677258931",
"plugins/agent/assistant-preferences/package.ts": "813f0a197cc326b4a48545f621e7888a2b5e6b213dd2e8d5b955ae69ed7880d0",
"plugins/agent/assistant-preferences/tui.ts": "1a5f4670eddd3ea99ba791125830bb56b653ac8e56aeb31edd5b60f71bd7a62a",
@@ -84,9 +84,9 @@
"plugins/agent/composer-footer/locale.ts": "bd05001fd6d38e8a548c391ddae441f4ba659cf7351f417cfa1cac7531c3da1e",
"plugins/agent/composer-footer/package.ts": "256408914147346b046d9447869acdf5d778f5822fe3b392b1ece8f805a10399",
"plugins/agent/composer-footer/tui.ts": "a42a739ba6a216de189ffee699a259f72a1a236ff8d96210a688ee29287939fb",
- "plugins/agent/composer/component.ts": "ce5114e2496303bb3b77884c8876b7b6985e627126a9a38605caaf89d9759315",
+ "plugins/agent/composer/component.ts": "db8460398a03be7ee9fcc244e18f045b95154f3caec983662c5ca924c70ad1ea",
"plugins/agent/composer/desktop.ts": "781fa9950b60606fd3301d3efc55af43dc95e8585b8a4b8ef4d967e278a8b653",
- "plugins/agent/composer/locale.ts": "291a6de52d51617c4d5802524063ea546b7aba3fda826faf4d76fc8e2cc40bb9",
+ "plugins/agent/composer/locale.ts": "3dd3837bdf58889210c5bc116e9f64c3e81918b854d508a5e76ede9188b8b152",
"plugins/agent/composer/package.ts": "d996adc3bfed1e72b4cbdfaf28525c942d38f8a3ff53910d6d76edd7e16a36c7",
"plugins/agent/composer/tui.ts": "0ab811d64335291a08f531bd09607e2a05e0564cc29cec6b4484fc86124ad7aa",
"plugins/agent/conversation-import/desktop.ts": "fb99d3d85fb9368363291dd467ffd67865841c04926a1785cdd668d5ebb12bf5",
@@ -316,7 +316,7 @@
"plugins/shared/attachments.ts": "e3e49eb56eb7dc28dc70db66dbc57062be502d42c1ed502b6eeae23eb6985bf9",
"plugins/shared/bookmark.ts": "d16b12b7aa9fd900271d6d8469c45d40e9295c8bd949adbcc7280f76e1d79dfc",
"plugins/shared/components.ts": "af68703685acbccf888458ac6502dc4f3fcfd455f5089148a1eb400c68b38c8c",
- "plugins/shared/contracts.ts": "1f119177f2d8d5e7e2cb2cdb3012f484fd9e48c429cc01a9d64ad16430df1bc1",
+ "plugins/shared/contracts.ts": "66fa27471fb10fcc66513144aaab31cdf8f0d7a5c987dca7bfa3a035970fae2a",
"plugins/shared/conversation-search.ts": "5355d6002832ec057511eea9be24f5a910bf43971e10c15e336bc83bde1f03ec",
"plugins/shared/deployment-document.ts": "7e1af7e2b599dffc1eefa0cb19f31d75b2e1f38e20f62989628a631731d711ac",
"plugins/shared/deployment-import.ts": "6515214d9c8a8c27e2810932923e2b8368762fb7c06126ac1b1132996cd9f89b",
diff --git a/products/maka/cli/tests/integration/terminal/bundled_product.rs b/products/maka/cli/tests/integration/terminal/bundled_product.rs
index 6329738007..10738c79d1 100644
--- a/products/maka/cli/tests/integration/terminal/bundled_product.rs
+++ b/products/maka/cli/tests/integration/terminal/bundled_product.rs
@@ -699,6 +699,65 @@ fn bundled_assistant_preferences_opens_with_compaction_editor() {
tui.wait_for("Your name");
tui.wait_for("Assistant tone");
tui.wait_for("Compression prompt");
+ tui.wait_for("## Critical Context");
+ // Scroll the settings pane until the entire prompt editor fits, then
+ // keep wheeling inside it past both boundaries.
+ for _ in 0..24 {
+ let screen = tui.screen.snapshot().unwrap().screen;
+ let (row, line) = screen
+ .lines()
+ .enumerate()
+ .find(|(_, line)| line.contains("Compression prompt"))
+ .unwrap();
+ if row <= 4 {
+ break;
+ }
+ let column = line[..line.find("Compression prompt").unwrap()].width() + 2;
+ tui.send(format!("\x1b[<65;{column};{}M", row + 1).as_bytes());
+ tui.wait_until(|s| {
+ s.lines()
+ .position(|line| line.contains("Compression prompt"))
+ != Some(row)
+ });
+ }
+ let screen = tui.screen.snapshot().unwrap().screen;
+ let (row, line) = screen
+ .lines()
+ .enumerate()
+ .find(|(_, line)| line.contains("Compression prompt"))
+ .unwrap();
+ assert!(row <= 4);
+ let column = line[..line.find("Compression prompt").unwrap()].width() + 4;
+ tui.send(
+ format!("\x1b[<64;{column};{}M", row + 3)
+ .repeat(80)
+ .as_bytes(),
+ );
+ tui.wait_for("You are a context summarization assistant.");
+ assert_eq!(
+ tui.screen
+ .snapshot()
+ .unwrap()
+ .screen
+ .lines()
+ .position(|line| line.contains("Compression prompt")),
+ Some(row)
+ );
+ tui.send(
+ format!("\x1b[<65;{column};{}M", row + 3)
+ .repeat(80)
+ .as_bytes(),
+ );
+ tui.wait_for("details are needed.");
+ assert_eq!(
+ tui.screen
+ .snapshot()
+ .unwrap()
+ .screen
+ .lines()
+ .position(|line| line.contains("Compression prompt")),
+ Some(row)
+ );
if let Some(path) = std::env::var_os("MAKA_SETTINGS_EVIDENCE") {
std::fs::create_dir_all(&path).unwrap();
let path = std::path::PathBuf::from(path);
diff --git a/products/maka/cli/tests/integration/terminal/bundled_product/chat/compaction.rs b/products/maka/cli/tests/integration/terminal/bundled_product/chat/compaction.rs
index 4657c0419c..d46ba05e7a 100644
--- a/products/maka/cli/tests/integration/terminal/bundled_product/chat/compaction.rs
+++ b/products/maka/cli/tests/integration/terminal/bundled_product/chat/compaction.rs
@@ -102,7 +102,17 @@ fn default_product_compaction_edits_one_shot_prompt_and_keeps_durable_divider()
tui.wait_for("Deployment is still pending.");
tui.wait_for("Workspace conversation");
click(&mut tui, "Message…");
- tui.send(b"/compact");
+ tui.send(b"/");
+ tui.wait_for("/compact");
+ tui.wait_for("/new");
+ evidence(&tui, "slash-candidates");
+ tui.send(b"\x1b[B");
+ tui.wait_for("› /help");
+ tui.send(b"co");
+ tui.wait_until(|s| s.contains("› /compact") && !s.contains("/help"));
+ evidence(&tui, "slash-filtered");
+ tui.send(b"\t");
+ tui.wait_until(|s| s.lines().filter(|line| line.contains("/compact")).count() >= 2);
tui.send(b"\r");
tui.wait_for("Compact context");
tui.wait_for(GLOBAL_PROMPT);
diff --git a/products/maka/desktop/src/editor_tests/submit.rs b/products/maka/desktop/src/editor_tests/submit.rs
index 87eb28fd2a..053480e72b 100644
--- a/products/maka/desktop/src/editor_tests/submit.rs
+++ b/products/maka/desktop/src/editor_tests/submit.rs
@@ -31,7 +31,7 @@ fn fixture() -> (
let entry = declaration.entries.values().next().unwrap();
let Implementation::JavaScript {module,..} = &entry.implementation else { return original; };
let source = std::str::from_utf8(original.file(module).unwrap()).unwrap()
- .replace("on:{changed:'changed'}", "on:{changed:'changed',submitted:'submitted'}")
+ .replace("on:{changed:'changed'}", "on:{changed:'changed',submitted:'submitted',navigated:'navigated'}")
.replace("softWrap:true,", "softWrap:true,submit:'primary_enter',")
.replace("name:'changed',value:event.event", "name:event.name,value:event.event")
.replace("else if(event.kind==='component')next.observation=event.event;", "else if(event.kind==='component'){next.observation=event.event;if(event.name==='submitted')next.submissions=(state.submissions??0)+1;}");
@@ -63,6 +63,90 @@ fn submissions(scene: &Scene) -> u64 {
.unwrap_or(0)
}
+#[gpui::test]
+fn textarea_navigation_keeps_focus_and_rejects_stale_or_marked_native_state(
+ cx: &mut TestAppContext,
+) {
+ let timer = timer();
+ let (mut input, packages) = fixture();
+ let packages = packages.into_iter().map(|original| {
+ if original.manifest().id != "dynamic.app" { return original; }
+ let declaration = original.manifest().application.as_ref().unwrap().declaration().clone();
+ let source = std::str::from_utf8(original.file("index.mjs").unwrap()).unwrap()
+ .replace("softWrap:true,", "softWrap:true,navigation:state.observation?{owner:state.observation.snapshot.text.owner,basedOn:state.observation.revision}:null,")
+ .replace("next.observation=event.event;", "if(event.name==='navigated'){next.navigations=(state.navigations??0)+1;}else next.observation=event.event;");
+ let package = support::package("dynamic.app", declaration, Some(source));
+ input.instances.get_mut("app").unwrap().package = package.application_ref().into();
+ package
+ }).collect();
+ let scene = Scene::from_packages(cx, &timer, false, (input, packages));
+ scene.draw(cx);
+ let owner = scene.owner();
+ cx.update_window(scene.window, |_, window, cx| {
+ owner.read(cx).state.clone().update(cx, |state, cx| {
+ state.focus(window, cx);
+ state.set_value("/co", window, cx);
+ });
+ })
+ .unwrap();
+ scene.settle(cx);
+ let original = scene.app.borrow().frame(&scene.root).unwrap().state["observation"].clone();
+ for (index, key) in ["up", "down", "tab", "enter", "escape"]
+ .into_iter()
+ .enumerate()
+ {
+ press(&scene, cx, key);
+ assert_eq!(
+ scene.app.borrow().frame(&scene.root).unwrap().state["navigations"],
+ index + 1
+ );
+ assert_eq!(
+ scene.app.borrow().frame(&scene.root).unwrap().state["observation"],
+ original
+ );
+ cx.update_window(scene.window, |_, window, cx| {
+ assert!(
+ owner
+ .read(cx)
+ .state
+ .read(cx)
+ .presentation()
+ .focus_handle()
+ .is_focused(window)
+ );
+ })
+ .unwrap();
+ }
+ // A native edit can get ahead of the candidate menu's published revision.
+ cx.update_window(scene.window, |_, window, cx| {
+ owner
+ .read(cx)
+ .state
+ .clone()
+ .update(cx, |state, cx| state.set_value("changed", window, cx));
+ window.dispatch_event(
+ PlatformInput::KeyDown(KeyDownEvent {
+ keystroke: Keystroke::parse("enter").unwrap(),
+ is_held: false,
+ prefer_character_input: false,
+ }),
+ cx,
+ );
+ assert!(owner.read(cx).state.read(cx).value().contains('\n'));
+ owner.update(cx, |owner, cx| {
+ owner.replace_and_mark_text_in_range(Some(0..7), "中文", Some(0..2), window, cx)
+ });
+ })
+ .unwrap();
+ scene.settle(cx);
+ press(&scene, cx, "down");
+ assert_eq!(
+ scene.app.borrow().frame(&scene.root).unwrap().state["navigations"],
+ 5
+ );
+ scene.close(cx);
+}
+
#[gpui::test]
fn original_desktop_paste_and_submit_stay_immediate_during_a_slow_js_transaction(
cx: &mut TestAppContext,
---------------------------------------------------------------------
To unsubscribe, e-mail: commits-unsubscribe@maka.apache.org
For additional commands, e-mail: commits-help@maka.apache.org