Merge pull request 'claude_cli: AskUserQuestion shows hx popup' (#177) from fix/claude-ask-question into main
build / version (push) Successful in 10s
build / build (aarch64-apple-darwin) (push) Successful in 5m45s
build / build (x86_64-unknown-linux-musl) (push) Successful in 4m55s
build / release (push) Successful in 21s

This commit was merged in pull request #177.
This commit is contained in:
hermes committed 2026-11-05 19:29:30 +00:00
commit 39a4e0c625
1 file changed
+55 -8
+55 -8
View File
@@ -78,7 +78,12 @@ pub async fn serve(path: &Path, cx: ToolCtx) -> std::io::Result<()> {
} }
let v: Value = serde_json::from_str(&line).unwrap_or_default(); let v: Value = serde_json::from_str(&line).unwrap_or_default();
// hx tools run by `codemode` inside mcp-serve ask for their own permission // hx tools run by `codemode` inside mcp-serve ask for their own permission
let ok = if let Some(q) = v.get("permit") { let mut input = None;
let ok = if v["tool_name"] == "AskUserQuestion" {
// claude's own question tool: show hx's popup, hand the answers back as input
input = ask(&cx, &v["input"]).await;
input.is_some()
} else if let Some(q) = v.get("permit") {
let s = |k: &str| q[k].as_str().unwrap_or_default().to_string(); let s = |k: &str| q[k].as_str().unwrap_or_default().to_string();
gate( gate(
&cx, &cx,
@@ -96,13 +101,40 @@ pub async fn serve(path: &Path, cx: ToolCtx) -> std::io::Result<()> {
} }
}; };
let _ = w let _ = w
.write_all(format!("{}\n", json!({"allow": ok})).as_bytes()) .write_all(format!("{}\n", json!({"allow": ok, "input": input})).as_bytes())
.await; .await;
}); });
} }
} }
async fn roundtrip(path: &Path, msg: Value) -> bool { /// Run each `AskUserQuestion` question through the popup; `input` plus `answers` (question -> label(s)).
/// None = no frontend or dismissed.
async fn ask(cx: &ToolCtx, input: &Value) -> Option<Value> {
let mut answers = serde_json::Map::new();
for q in input["questions"].as_array()? {
let text = q["question"].as_str().unwrap_or_default();
let options = q["options"].as_array().into_iter().flatten().map(|o| {
let s = |k| o[k].as_str().unwrap_or_default().to_string();
(s("label"), s("description"))
});
let r = cx
.state
.choose(crate::Question {
text: text.into(),
options: options.collect(),
multi: q["multiSelect"].as_bool().unwrap_or(false),
other: true,
})
.await
.ok()??;
answers.insert(text.into(), r.join(", ").into());
}
let mut out = input.clone();
out["answers"] = answers.into();
Some(out)
}
async fn roundtrip(path: &Path, msg: Value) -> Option<Value> {
let ask = async { let ask = async {
let mut c = UnixStream::connect(path).await?; let mut c = UnixStream::connect(path).await?;
c.write_all(format!("{msg}\n").as_bytes()).await?; c.write_all(format!("{msg}\n").as_bytes()).await?;
@@ -113,7 +145,7 @@ async fn roundtrip(path: &Path, msg: Value) -> bool {
ask.await ask.await
.ok() .ok()
.and_then(|l| serde_json::from_str::<Value>(&l).ok()) .and_then(|l| serde_json::from_str::<Value>(&l).ok())
.is_some_and(|v| v["allow"] == true) .filter(|v| v["allow"] == true)
} }
/// Permission hook for tools that run in another process (`hx mcp-serve`): ask the owner of the socket. /// Permission hook for tools that run in another process (`hx mcp-serve`): ask the owner of the socket.
@@ -125,7 +157,7 @@ pub fn remote_permit(path: PathBuf) -> crate::permit::Permit {
Box::pin(async move { Box::pin(async move {
let m = json!({"permit": {"tool": r.tool, "detail": r.detail, "rule": r.rule}}); let m = json!({"permit": {"tool": r.tool, "detail": r.detail, "rule": r.rule}});
// the owner stores "always" itself; here a yes is a plain yes // the owner stores "always" itself; here a yes is a plain yes
if roundtrip(&path, m).await { if roundtrip(&path, m).await.is_some() {
Decision::Once Decision::Once
} else { } else {
Decision::Deny Decision::Deny
@@ -149,9 +181,10 @@ impl Tool for Approve {
} }
} }
async fn call(&self, args: Value, _cx: &ToolCtx) -> ToolResult { async fn call(&self, args: Value, _cx: &ToolCtx) -> ToolResult {
let ok = roundtrip(&self.0, args.clone()).await; let r = roundtrip(&self.0, args.clone()).await;
ToolResult::ok(if ok { ToolResult::ok(if let Some(r) = r {
json!({"behavior": "allow", "updatedInput": args["input"]}) let input = if r["input"].is_null() { &args["input"] } else { &r["input"] };
json!({"behavior": "allow", "updatedInput": input})
} else { } else {
json!({"behavior": "deny", "message": "denied by the user; do not retry, ask what to do instead"}) json!({"behavior": "deny", "message": "denied by the user; do not retry, ask what to do instead"})
} }
@@ -179,6 +212,20 @@ mod tests {
assert_eq!(question("Foo", &json!({})).unwrap().rule, "claude:Foo"); assert_eq!(question("Foo", &json!({})).unwrap().rule, "claude:Foo");
} }
#[tokio::test]
async fn ask_user_question_uses_popup() {
let cx = ToolCtx {
cwd: ".".into(),
state: Default::default(),
};
let inp = json!({"questions": [{"question": "Which?", "options": [{"label": "A"}, {"label": "B"}]}]});
assert!(ask(&cx, &inp).await.is_none(), "no frontend = deny");
let _ = cx.state.choose.set(std::sync::Arc::new(|q| {
Box::pin(async move { Some(vec![q.options[1].0.clone()]) })
}));
assert_eq!(ask(&cx, &inp).await.unwrap()["answers"]["Which?"], "B");
}
#[tokio::test] #[tokio::test]
async fn socket_round_trip_allows_and_denies() { async fn socket_round_trip_allows_and_denies() {
use crate::permit::Decision; use crate::permit::Decision;