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/20 10:44:07 UTC

(maka) 02/10: feat(client): retain original Agent control operations

This is an automated email from the ASF dual-hosted git repository.

M4n5ter pushed a commit to branch feat/nsh-tui-shell
in repository https://gitbox.apache.org/repos/asf/maka.git

commit 742d348661bcd2ba38354dd9a524a9f1ad88c53e
Author: M4n5ter <m4...@gmail.com>
AuthorDate: Tue Oct 20 16:40:17 2026 +0800

    feat(client): retain original Agent control operations
    
    Generated-by: OpenAI Codex
---
 products/maka/client/src/journal.rs      | 10 ++++++-
 products/maka/client/src/lib.rs          | 48 ++++++++++++++++++++++++++++++++
 products/maka/client/src/tests.rs        | 23 ++++++++++++---
 products/maka/client/src/tests/drafts.rs |  2 ++
 4 files changed, 78 insertions(+), 5 deletions(-)

diff --git a/products/maka/client/src/journal.rs b/products/maka/client/src/journal.rs
index bfeecd18fb..2f371d2f1e 100644
--- a/products/maka/client/src/journal.rs
+++ b/products/maka/client/src/journal.rs
@@ -18,7 +18,7 @@
  */
 
 //! Client-owned correlation and original receipts, independent of UI nodes.
-use crate::Result;
+use crate::{CONTROL_METHODS, Result, control_correlation};
 use maka_plugin_core::{
     composition::InstanceId,
     deployment::DeploymentRef,
@@ -247,6 +247,14 @@ impl Journal {
             .bind(serde_json::to_string(key).map_err(error)?).fetch_all(&self.0).await.map_err(error)?;
         rows.into_iter().map(decode_operation).collect()
     }
+    pub(crate) async fn pending_controls(&self, host: &DeploymentRef) -> Result<Vec<Operation>> {
+        let rows = sqlx::query("SELECT context,reference,receipt,abandoned FROM operations WHERE domain=? AND deployment=? AND draft_owner IS NULL AND json_extract(context,'$.endpoint')='agent' AND json_extract(context,'$.method') IN (SELECT value FROM json_each(?)) AND json_extract(context,'$.correlation')=? AND receipt IS NULL AND abandoned=0 ORDER BY rowid DESC LIMIT 128")
+            .bind(&host.state_domain).bind(host.deployment.to_string())
+            .bind(serde_json::to_string(&CONTROL_METHODS).map_err(error)?)
+            .bind(control_correlation().to_string())
+            .fetch_all(&self.0).await.map_err(error)?;
+        rows.into_iter().map(decode_operation).collect()
+    }
     pub(crate) async fn observe(&self, operation: &Operation, receipt: &Receipt) -> Result<()> {
         let Receipt::Recorded {
             outcome: OperationOutcome::Returned { .. },
diff --git a/products/maka/client/src/lib.rs b/products/maka/client/src/lib.rs
index 654d1b1a03..956c399b8d 100644
--- a/products/maka/client/src/lib.rs
+++ b/products/maka/client/src/lib.rs
@@ -43,6 +43,11 @@ use uuid::Uuid;
 
 pub type Result<T> = std::result::Result<T, String>;
 
+const CONTROL_METHODS: [&str; 4] = ["create", "selectBackend", "stop", "respond"];
+fn control_correlation() -> Value {
+    serde_json::json!({"kind": "agent-control"})
+}
+
 /// A shell-owned scope over one launcher-selected, authenticated Host connection.
 /// Clones share custody; dropping a JS handle does not retire an accepted request.
 #[derive(Clone)]
@@ -194,6 +199,33 @@ impl Client {
             description,
         })
     }
+    /// Reserve a shell control attempt separately from composer draft sends.
+    pub async fn control(&self, id: Uuid, method: &str, input: Value) -> Result<Mutation> {
+        if !CONTROL_METHODS.contains(&method) {
+            return Err("unsupported agent control method".into());
+        }
+        let session_id = if method == "create" {
+            None
+        } else {
+            Some(
+                input
+                    .get("sessionId")
+                    .and_then(Value::as_str)
+                    .ok_or("agent control requires a sessionId")?
+                    .to_owned(),
+            )
+        };
+        self.mutation(
+            id,
+            "agent",
+            method,
+            input,
+            Attachments::new(),
+            session_id,
+            control_correlation(),
+        )
+        .await
+    }
     async fn draft_key(&self, endpoint: &str, session: &str, editor: &str) -> Result<DraftKey> {
         let host = self.0.host.lock().await;
         let target = host.catalogue().describe(endpoint)?;
@@ -291,6 +323,22 @@ impl Client {
     pub async fn operation(&self, id: Uuid) -> Result<Operation> {
         self.0.journal.load(&self.0.source, id).await
     }
+    /// A settled or abandoned original still retains its control owner.
+    pub async fn operation_for_control(&self, id: Uuid) -> Result<Operation> {
+        let operation = self.operation(id).await?;
+        if operation.draft.is_some()
+            || operation.endpoint != "agent"
+            || !CONTROL_METHODS.contains(&operation.method.as_str())
+            || operation.correlation != control_correlation()
+        {
+            return Err("original client operation belongs to another control owner".into());
+        }
+        Ok(operation)
+    }
+    /// Only this shell's unsettled Agent controls on the current Host deployment.
+    pub async fn pending_controls(&self) -> Result<Vec<Operation>> {
+        self.0.journal.pending_controls(&self.0.source).await
+    }
     /// Check the immutable product owner independently of a mutable pending list.
     /// A settled or abandoned original still belongs to the same draft editor.
     pub async fn operation_for_draft(
diff --git a/products/maka/client/src/tests.rs b/products/maka/client/src/tests.rs
index 0070b4aeeb..442c1016b7 100644
--- a/products/maka/client/src/tests.rs
+++ b/products/maka/client/src/tests.rs
@@ -70,7 +70,7 @@ impl Handler for CounterHandler {
         Box::pin(async move {
             match method.as_str() {
                 "read" => Ok(json!({"sent":owner.effects.load(Ordering::SeqCst)})),
-                "send" => {
+                "send" | "selectBackend" => {
                     owner.messages.lock().unwrap().push(input.clone());
                     if input.get("message").and_then(Value::as_str) == Some("reject") {
                         return Ok(
@@ -129,6 +129,7 @@ impl Fixture {
             "name":"test.Counter","version":1,"transport":"remote","interface":{"kind":"service","methods":{
                 "read":{"mode":"query","input":{},"output":{},"resources":{}},
                 "send":{"mode":"mutation","input":{},"output":{},"resources":{}},
+                "selectBackend":{"mode":"mutation","input":{},"output":{},"resources":{}},
                 "watch":{"mode":"subscription","input":{},"output":{},"resources":{}}
             }}
         })).unwrap();
@@ -229,7 +230,13 @@ impl Fixture {
                         consumer: InstanceId(vec![Uuid::from_u128(3)]),
                         import: "agent".into(),
                         grant: Grant {
-                            methods: ["read".into(), "send".into(), "watch".into()].into(),
+                            methods: [
+                                "read".into(),
+                                "send".into(),
+                                "selectBackend".into(),
+                                "watch".into(),
+                            ]
+                            .into(),
                             recovery: false,
                         },
                     },
@@ -303,11 +310,17 @@ async fn durable_original_receipt_survives_cancelled_observer_disconnect_and_res
         let fixture = Fixture::new().await;
         fixture.counter.blocked.store(true,Ordering::SeqCst);
         let client = fixture.client().await;
+        assert_eq!(client.control(Uuid::new_v4(),"send",Value::Null).await.err().unwrap(),"unsupported agent control method");
+        let unrelated = client.mutation(Uuid::new_v4(),"agent","selectBackend",Value::Null,Attachments::new(),None,Value::Null).await.unwrap();
+        assert_eq!(client.operation_for_control(unrelated.id()).await.unwrap_err(),"original client operation belongs to another control owner");
+        unrelated.close().await.unwrap();
+        assert!(client.pending_controls().await.unwrap().is_empty());
         let id = Uuid::new_v4();
-        let mutation = send(&client,id).await;
+        let mutation = client.control(id,"selectBackend",json!({"sessionId":"session-one","text":"private draft text"})).await.unwrap();
+        assert_eq!(client.pending_controls().await.unwrap().iter().map(|operation| operation.id).collect::<Vec<_>>(),[id]);
         let original = mutation.prepare().await.unwrap();
         assert_eq!(original.session_id.as_deref(),Some("session-one"));
-        assert_eq!(original.correlation,json!({"draftRevision":7}));
+        assert_eq!(original.correlation,json!({"kind":"agent-control"}));
         assert_eq!(client.operation(id).await.unwrap().reference,original.reference);
         assert_eq!(client.query("agent","read",Value::Null).await.unwrap(),json!({"sent":0}));
         assert!(client.mutation(id,"agent","send",Value::Null,Attachments::new(),None,Value::Null).await.is_err());
@@ -330,6 +343,7 @@ async fn durable_original_receipt_survives_cancelled_observer_disconnect_and_res
             tokio::time::sleep(Duration::from_millis(5)).await;
         }
         assert_eq!(client.pending_requests().await,1,"receipt recovery cannot settle a lost physical request");
+        assert!(client.pending_controls().await.unwrap().is_empty());
         drop(mutation);
         assert_eq!(client.pending_requests().await,1,"dropping a UI handle cannot discard shell custody");
         client.close().await.unwrap();
@@ -337,6 +351,7 @@ async fn durable_original_receipt_survives_cancelled_observer_disconnect_and_res
         let restarted = fixture.client().await;
         let recovered = restarted.recover(id).await.unwrap();
         assert_eq!(recovered.reference,original.reference.unwrap());
+        assert_eq!(restarted.operation_for_control(id).await.unwrap().id,id);
         assert!(matches!(recovered.receipt,Receipt::Recorded {outcome:OperationOutcome::Returned {ref value},..} if value==&json!({"sent":1})));
         assert_eq!(restarted.query("agent","read",Value::Null).await.unwrap(),json!({"sent":1}));
         assert!(restarted.mutation(id,"agent","send",Value::Null,Attachments::new(),None,Value::Null).await.is_err());
diff --git a/products/maka/client/src/tests/drafts.rs b/products/maka/client/src/tests/drafts.rs
index b4696f01f6..b8cf940ddb 100644
--- a/products/maka/client/src/tests/drafts.rs
+++ b/products/maka/client/src/tests/drafts.rs
@@ -42,6 +42,8 @@ async fn saved_drafts_and_receipts_preserve_new_edits_across_clear_ordering_and_
         let sent = client.send_draft(id, "agent", "session-one", "composer", first.revision, json!({"model":{"kind":"default"}})).await.unwrap();
         let pending = client.pending_operations("agent", "session-one", "composer").await.unwrap();
         assert_eq!(pending.iter().map(|operation|operation.id).collect::<Vec<_>>(), [id]);
+        assert!(client.pending_controls().await.unwrap().is_empty());
+        assert_eq!(client.operation_for_control(id).await.unwrap_err(), "original client operation belongs to another control owner");
         assert!(pending[0].reference.is_none());
         assert!(client.pending_operations("receipts", "session-one", "composer").await.unwrap().is_empty());
         let operation = sent.prepare().await.unwrap();


---------------------------------------------------------------------
To unsubscribe, e-mail: commits-unsubscribe@maka.apache.org
For additional commands, e-mail: commits-help@maka.apache.org