Scale computer-use 2.0 with open-source drivers, cross-OS sandboxes, and benchmarks for training, evaluation, and data generation.
Rust agentai-agentapplecomputer-usecomputer-use-agentcontainerizationcuadesktop-automationhacktoberfestlumemacosmanusoperatorswiftvirtualizationvirtualization-frameworkwindowswindows-sandbox
An @mention by the host's agent name wakes the Space's agent (#6517)
ddupont83a40652f7eb
diff --git a/apps/cua-spaces-web/src/__tests__/agent-home-box.test.tsx b/apps/cua-spaces-web/src/__tests__/agent-home-box.test.tsxindex 391f48be49..60a67d9f5e 100644--- a/apps/cua-spaces-web/src/__tests__/agent-home-box.test.tsx+++ b/apps/cua-spaces-web/src/__tests__/agent-home-box.test.tsx@@ -103,4 +103,31 @@ describe.skipIf(!wasmBuilt)("the box with an agent home", () => {expect(calls.some((c) => c.op === "spaces.create")).toBe(false);await waitFor(() => expect(calls.some((c) => c.op === "thread.post" && c.args.text === "@claude run the tests")).toBe(true), { timeout: 15000 });});++ it("names the Space's handle for the Home's agent, never the host's unique name for it", async () => {+ // `cua agent ls` says claude-8 (the host made it unique: other Spaces have a claude); the Space calls it @claude.+ const calls: { op: string; args: Record<string, unknown> }[] = [];+ const member = { name: "claude-8", handle: "claude", harness: "claude-code", status: "idle", activity: null, sessions: 1 };+ const { router } = await mountApp("/home", {+ ...HOME,+ intercept: (op, args) => {+ calls.push({ op, args: args as Record<string, unknown> });+ return op === "thread.members" && (args as { spaceId: string }).spaceId === "local:agent-home-demo" ? { members: [member] } : undefined;+ },+ });+ const box = (await screen.findByLabelText("What should it do?")) as HTMLTextAreaElement;+ await waitFor(() => expect(q("[data-ask-agent]")!.textContent).toContain("Codex"));+ await useClaude();+ await waitFor(() => expect(q("[data-ask-agent]")!.textContent).toBe("Claude Code"));+ await new Promise((r) => setTimeout(r, 300));+ fireEvent.change(box, { target: { value: "hi" } });+ await act(async () => {+ fireEvent.keyDown(box, { key: "Enter" });+ });+ await waitFor(() => expect(router.state.location.pathname).toBe("/spaces/local%3Aagent-home-demo"));+ await waitFor(() => expect(calls.some((c) => c.op === "thread.post" && c.args.text === "@claude hi")).toBe(true), { timeout: 15000 });+ // Adding the standby agent names the handle too (it is the same member), and nothing is posted to @claude-8.+ expect(calls.filter((c) => c.op === "thread.agentAdd").every((c) => c.args.name === "claude")).toBe(true);+ expect(calls.some((c) => c.op === "thread.post" && String(c.args.text).includes("claude-8"))).toBe(false);+ });});diff --git a/apps/cua-spaces-web/src/__tests__/ask-first-in-space.test.tsx b/apps/cua-spaces-web/src/__tests__/ask-first-in-space.test.tsxindex a2e6604976..aa0f736917 100644--- a/apps/cua-spaces-web/src/__tests__/ask-first-in-space.test.tsx+++ b/apps/cua-spaces-web/src/__tests__/ask-first-in-space.test.tsx@@ -136,6 +136,25 @@ describe.skipIf(!wasmBuilt)("Send again when the agent can't join", () => {await waitFor(() => expect(calls.filter((c) => c.op === "thread.post" && c.args.text === "@claude fix the build")).toHaveLength(2));});+ it("says plainly when an @ names nobody in the Space (never a silent no-op)", { timeout: 40000 }, async () => {+ const calls: { op: string; args: Record<string, unknown> }[] = [];+ await inAFreshSpace({+ failsCreates: false,+ listsGhost: false,+ intercept: (op, args) => (calls.push({ op, args: args as Record<string, unknown> }), undefined),+ });+ calls.length = 0;+ await compose("@ghost are you there");+ await waitFor(() => expect(calls.some((c) => c.op === "thread.post" && String(c.args.text).includes("@ghost are you there"))).toBe(true), { timeout: 15000 });+ const note = await found("[data-wake-note=ghost]", 15000);+ expect(note.textContent).toContain("Nobody called @ghost is in this Space");+ expect(note.textContent).toContain("Only visible to you");+ // Nothing to connect or send again: it is not an agent that failed to start.+ expect(q("[data-wake-connect]")).toBeNull();+ expect(q("[data-wake-retry]")).toBeNull();+ expect(calls.some((c) => c.op === "thread.agentAdd")).toBe(false);+ });+it("says why and posts nothing more (a message no agent reads would look sent)", { timeout: 40000 }, async () => {const posts: string[] = [];let armed = false;diff --git a/apps/cua-spaces-web/src/bridge/agents-dm.ts b/apps/cua-spaces-web/src/bridge/agents-dm.tsindex de2b6a0d41..ed4f2a4e04 100644--- a/apps/cua-spaces-web/src/bridge/agents-dm.ts+++ b/apps/cua-spaces-web/src/bridge/agents-dm.ts@@ -496,7 +496,9 @@ export function useAgentDm(chat: AgentChat | null, only: string | null): AgentDmconst t = chat?.spaces.find((s) => s.spaceId === spaceId);if (!data || !t || !text.trim()) return;// Sending is posting: an @mention of the agent is its task in that Space.- const body = new RegExp(`(^|\\s)@${t.handle}\\b`, "i").test(text) ? text.trim() : `@${t.handle} ${text.trim()}`;+ // It names the Space's handle (`@claude`), never the host's key for the member (`claude-8`).+ const at = t.member.handle ?? t.handle;+ const body = new RegExp(`(^|\\s)@${at}\\b`, "i").test(text) ? text.trim() : `@${at} ${text.trim()}`;const entry = await data.call("thread.post", { spaceId, text: body });if (entry) merge(spaceId, [entry]);setReadSeq((r) => ({ ...r, [spaceId]: null }));diff --git a/apps/cua-spaces-web/src/bridge/connectors.ts b/apps/cua-spaces-web/src/bridge/connectors.tsindex e50ede0237..f9fafb6f5a 100644--- a/apps/cua-spaces-web/src/bridge/connectors.ts+++ b/apps/cua-spaces-web/src/bridge/connectors.ts@@ -454,7 +454,12 @@ export const setupCard = (core: CoreClient, input: ConnectorsInput, agent: strin/* ---- Summoning agents in a Space ---------------------------------------------------- */export interface SummonMember {+ /** What the Space calls it (`claude`): the handle the thread matches. */handle: string;+ /** The host's name for it (`claude-8`), an alias only. */+ key?: string;+ /** Runs on this device's own sign-ins (a Home's agent): waking it checks them. */+ mine?: boolean;harness: string;label: string;}@@ -463,6 +468,8 @@ export interface SummonInput {members: SummonMember[];people: string[];canAdd: boolean;+ /** Report an @mention of nobody in the Space (the thread's composer; not Ask first's job). */+ reportUnknown?: boolean;connectors: ConnectorsInput;}@@ -475,7 +482,7 @@ export interface SummonCandidate {}export interface CantWake {- reason: "not-connected" | "cant-add" | "failed";+ reason: "not-connected" | "cant-add" | "failed" | "no-such-member";handle: string;harness: string;name: string;@@ -506,7 +513,7 @@ export const queuedNote = (core: CoreClient, creating: boolean): LocalNote | nulexport interface SummonStep {handle: string;harness: string;- action: "wake" | "add" | "blocked";+ action: "wake" | "add" | "blocked" | "unknown";cantWake: CantWake | null;}diff --git a/apps/cua-spaces-web/src/components/agents/agent-chat.tsx b/apps/cua-spaces-web/src/components/agents/agent-chat.tsxindex 64287f230c..6b3219f725 100644--- a/apps/cua-spaces-web/src/components/agents/agent-chat.tsx+++ b/apps/cua-spaces-web/src/components/agents/agent-chat.tsx@@ -539,7 +539,7 @@ export function AgentPage({ chat, open, onOpenChange, me, identity }: { chat: Ag<ProvenanceCard identity={s.member.identity} agent={roster.agents[0]} roster={roster} />) : (<p className="p-3.5 text-[13px]">- @{s.handle} in {s.spaceName}+ @{s.member.handle ?? s.handle} in {s.spaceName}</p>)}</div>diff --git a/apps/cua-spaces-web/src/components/ask-first/use-summon-in.ts b/apps/cua-spaces-web/src/components/ask-first/use-summon-in.tsindex 2b701ffefa..b46048d741 100644--- a/apps/cua-spaces-web/src/components/ask-first/use-summon-in.ts+++ b/apps/cua-spaces-web/src/components/ask-first/use-summon-in.ts@@ -19,7 +19,8 @@ export function useSummonIn() {/** What summoning reads for `spaceId`: its agents now and this device's connectors. */const summonInput = async (spaceId: string) => {const members = ((await host!.call("thread.members", { spaceId }).catch(() => null))?.members ?? []) as AgentMember[];- return { members: members.map((m) => ({ handle: m.name, harness: m.harness, label: m.name })), people: [], canAdd: true, connectors };+ // The Space's handle for the member (`claude`), never the host's key for it (`claude-8` in `cua agent ls`): the thread matches the handle.+ return { members: members.map((m) => ({ handle: m.handle ?? m.name, key: m.name, mine: true, harness: m.harness, label: m.name })), people: [], canAdd: true, reportUnknown: false, connectors };};const send = (spaceId: string, input: Awaited<ReturnType<typeof summonInput>>) => (text: string) =>sendWithSummon({ core, data: host!, spaceId, input, text, post: (t) => host!.call("thread.post", { spaceId, text: t }) });diff --git a/apps/cua-spaces-web/src/components/space-thread/summon.tsx b/apps/cua-spaces-web/src/components/space-thread/summon.tsxindex 3874c847e7..4686db2607 100644--- a/apps/cua-spaces-web/src/components/space-thread/summon.tsx+++ b/apps/cua-spaces-web/src/components/space-thread/summon.tsx@@ -175,9 +175,10 @@ export function useSummon({ spaceId, thread, roster, canAdd }: { spaceId: stringconst connectors = useConnectors();const input: SummonInput = useMemo(() => ({- members: thread.members.map((m) => ({ handle: m.handle ?? m.name, harness: m.harness, label: roster.agents.find((a) => a.name === m.name)?.label ?? m.name })),+ members: thread.members.map((m) => ({ handle: m.handle ?? m.name, key: m.name, harness: m.harness, label: roster.agents.find((a) => a.name === m.name)?.label ?? m.name })),people: roster.people.map((p) => p.label.toLowerCase().replace(/\s+/g, "")),canAdd: canAdd && !!data && threadOpAvailable(data.mode, "thread.agentAdd"),+ reportUnknown: true,connectors: connectors.input,}),[thread.members, roster, canAdd, data, connectors.input],@@ -263,7 +264,7 @@ export function WakeNoteView({</p><p className="mt-0.5 text-[12.5px] text-muted-foreground">{c.detail}</p><div className="mt-2 flex flex-wrap items-center gap-2">- {connected && note.state !== "connecting" ? (+ {c.reason === "no-such-member" ? null : connected && note.state !== "connecting" ? (<Button size="sm" variant="outline" onClick={onRetry} data-wake-retry="">{c.retryLabel}</Button>diff --git a/apps/cua-spaces-web/src/hooks/use-agent-attempts.ts b/apps/cua-spaces-web/src/hooks/use-agent-attempts.tsindex 9578b8037f..76b99fb9fd 100644--- a/apps/cua-spaces-web/src/hooks/use-agent-attempts.ts+++ b/apps/cua-spaces-web/src/hooks/use-agent-attempts.ts@@ -36,7 +36,8 @@ export function useAgentAttempts(): ChatAttempt[] {}for (const [spaceId, list] of Object.entries(notes)) {for (const n of list ?? []) {- if (n.state === "retried") continue;+ // An @ of nobody here is a note under its message only: it is no agent's run.+ if (n.state === "retried" || n.cant.reason === "no-such-member") continue;out.push({id: `note:${spaceId}:${n.id}`,spaceId,diff --git a/libs/cua/crates/cua-spaces-app-core/src/phone/start_task.rs b/libs/cua/crates/cua-spaces-app-core/src/phone/start_task.rsindex ff38179872..6c0824e061 100644--- a/libs/cua/crates/cua-spaces-app-core/src/phone/start_task.rs+++ b/libs/cua/crates/cua-spaces-app-core/src/phone/start_task.rs@@ -632,6 +632,7 @@ mod tests {handle: "claude".into(),harness: "claude-code".into(),label: "Claude Code".into(),+ ..Default::default()}],}],choice: Choice::default(),diff --git a/libs/cua/crates/cua-spaces-app-core/src/summon.rs b/libs/cua/crates/cua-spaces-app-core/src/summon.rsindex ec7d7169a5..bdb8917b74 100644--- a/libs/cua/crates/cua-spaces-app-core/src/summon.rs+++ b/libs/cua/crates/cua-spaces-app-core/src/summon.rs@@ -115,7 +115,17 @@ pub fn parse_mentions(text: &str) -> Vec<String> {#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]#[serde(rename_all = "camelCase", default)]pub struct SummonMember {+ /// What the Space calls it: the `@handle` the thread matches.pub handle: String,+ /// Its name on the host (`claude-8` in `cua agent ls`), when that differs+ /// from the handle. Never what the page types; an @mention of it still+ /// reaches this member (the thread accepts it as an alias).+ pub key: String,+ /// It runs on this device's own sign-ins (a Home's agent, added from here):+ /// waking it is checked against them, so "not connected" is said up front+ /// instead of a message nobody answers. Other members run on their owner's+ /// keys, which this device cannot see.+ pub mine: bool,/// `claude-code`, `codex`, ... (empty when the thread doesn't say).pub harness: String,pub label: String,@@ -130,6 +140,10 @@ pub struct SummonInput {pub people: Vec<String>,/// Agents can be added to this Space (`thread.agentAdd` there, and you may post).pub can_add: bool,+ /// The text is what the person typed in this Space's thread: an @mention+ /// of nobody here is reported (never a silent no-op). Off for Ask first's+ /// job, which may @mention computers and Spaces as places.+ pub report_unknown: bool,/// Coding apps and saved sign-ins (Settings, Connections).pub connectors: ConnectorsInput,}@@ -163,11 +177,27 @@ fn taken(input: &SummonInput) -> Vec<String> {input.members.iter()- .map(|m| m.handle.clone())+ .flat_map(|m| [m.handle.clone(), m.key.clone()])+ .filter(|h| !h.is_empty()).chain(input.people.iter().cloned()).collect()}+/// The member an `@token` names: its handle, else (as an alias) its host+/// name. The same rule the thread applies when it reads the posted text.+pub fn member_named<'a>(input: &'a SummonInput, token: &str) -> Option<&'a SummonMember> {+ input+ .members+ .iter()+ .find(|m| m.handle.eq_ignore_ascii_case(token))+ .or_else(|| {+ input+ .members+ .iter()+ .find(|m| !m.key.is_empty() && m.key.eq_ignore_ascii_case(token))+ })+}+/// The handle a new `harness` agent gets in this Space.fn new_handle(input: &SummonInput, s: &Startable) -> String {free_handle(s.handle, &taken(input))@@ -217,7 +247,8 @@ pub fn candidates(input: &SummonInput) -> Vec<SummonCandidate> {#[serde(rename_all = "camelCase")]pub struct CantWake {/// `not-connected` (no sign-in it can use), `cant-add` (this Space can't- /// add agents), `failed` (adding or waking it failed).+ /// add agents), `failed` (adding or waking it failed), `no-such-member`+ /// (an @mention of nobody in this Space).pub reason: String,pub handle: String,pub harness: String,@@ -356,7 +387,8 @@ pub struct SummonStep {pub harness: String,/// `wake` (in the Space: the posted message wakes it), `add` (add it/// asleep under `handle` first, then post), `blocked` (post only; see- /// `cant_wake`).+ /// `cant_wake`), `unknown` (nobody by that name is in the Space: post+ /// only; `cant_wake` says so).pub action: String,pub cant_wake: Option<CantWake>,}@@ -378,26 +410,72 @@ fn startable_for(input: &SummonInput, handle: &str) -> Option<&'static Startable})}+/// The line under a message that @mentions nobody who is in the Space.+fn unknown_mention(input: &SummonInput, handle: &str) -> CantWake {+ let here: Vec<String> = input+ .members+ .iter()+ .map(|m| format!("@{}", m.handle))+ .collect();+ CantWake {+ reason: "no-such-member".into(),+ handle: handle.into(),+ harness: String::new(),+ name: String::new(),+ app: String::new(),+ text: format!("Nobody called @{handle} is in this Space"),+ detail: if here.is_empty() {+ "Your message was posted, but no agent is in this Space to read it. Add one first."+ .into()+ } else {+ format!(+ "Your message was posted, but it did not reach anyone. Agents here: {}.",+ here.join(", ")+ )+ },+ connect_label: None,+ connecting_label: String::new(),+ open_label: None,+ retry_label: String::new(),+ retried_text: String::new(),+ only_you: true,+ only_you_label: ONLY_YOU.into(),+ dismiss_label: "Dismiss".into(),+ }+}+pub fn plan(input: &SummonInput, text: &str) -> SummonPlan {let steps = parse_mentions(text).into_iter().filter_map(|h| {- if let Some(m) = input- .members- .iter()- .find(|m| m.handle.eq_ignore_ascii_case(&h))- {+ if let Some(m) = member_named(input, &h) {// In the Space already: the posted message wakes it. It runs on// its owner's keys, which this device can't see, so nothing is- // checked here; the thread says if it can't start.+ // checked here; the thread says if it can't start. One of this+ // device's own (a Home's agent) is: it runs on these sign-ins.+ let blocked = startable(&m.harness)+ .filter(|s| m.mine && !connectors::signed_in(&input.connectors, s.app))+ .map(|s| cant_wake(input, s, &m.handle, "not-connected", None));return Some(SummonStep {handle: m.handle.clone(),harness: m.harness.clone(),- action: "wake".into(),- cant_wake: None,+ action: if blocked.is_some() { "blocked" } else { "wake" }.into(),+ cant_wake: blocked,});}- let s = startable_for(input, &h)?;+ let Some(s) = startable_for(input, &h) else {+ // A person, `@everyone`, or nobody: only the last is a mistake worth a line.+ let person = input.people.iter().any(|p| p.eq_ignore_ascii_case(&h));+ if !input.report_unknown || person || h == "everyone" {+ return None;+ }+ return Some(SummonStep {+ handle: h.clone(),+ harness: String::new(),+ action: "unknown".into(),+ cant_wake: Some(unknown_mention(input, &h)),+ });+ };let blocked = if !input.can_add {Some(cant_wake(input, s, &h, "cant-add", None))} else if !connectors::signed_in(&input.connectors, s.app) {@@ -484,9 +562,11 @@ mod tests {handle: "hermes".into(),harness: "hermes".into(),label: "Hermes".into(),+ ..Default::default()}],people: vec!["grace".into()],can_add: true,+ report_unknown: true,connectors: ConnectorsInput {apps: vec![ConnectorAppInput {agent: "claude-code".into(),@@ -559,6 +639,85 @@ mod tests {assert_eq!(p.steps[0].harness, "claude-code");}+ #[test]+ fn the_hosts_name_for_a_member_is_an_alias_never_what_the_page_types() {+ // `cua agent ls` says claude-8; the Space calls the member @claude.+ let mut i = input(&[]);+ i.members.push(SummonMember {+ handle: "claude".into(),+ key: "claude-8".into(),+ harness: "claude-code".into(),+ label: "Claude Code".into(),+ ..Default::default()+ });+ // Ask first's message names the handle, whichever name it was given.+ assert_eq!(first_message(&i, "claude-code", "hi").text, "@claude hi");+ // The alias still wakes the member (no add, no unknown note).+ let s = &plan(&i, "@claude-8 hi").steps;+ assert_eq!(s.len(), 1);+ assert_eq!(+ (s[0].handle.as_str(), s[0].action.as_str()),+ ("claude", "wake")+ );+ // A new agent never takes the host name of a member either.+ i.members.clear();+ i.members.push(SummonMember {+ handle: "hermes".into(),+ key: "claude-2".into(),+ harness: "hermes".into(),+ label: "Hermes".into(),+ ..Default::default()+ });+ assert_eq!(+ candidates(&i)+ .iter()+ .find(|c| c.harness == "claude-code")+ .unwrap()+ .handle,+ "claude"+ );+ }++ #[test]+ fn a_homes_agent_without_a_sign_in_says_so_instead_of_waking_nothing() {+ let mut i = input(&[]);+ i.members.push(SummonMember {+ handle: "claude".into(),+ key: "claude-8".into(),+ harness: "claude-code".into(),+ label: "Claude Code".into(),+ mine: true,+ });+ let s = &plan(&i, "@claude hi").steps[0];+ assert_eq!(s.action, "blocked");+ let c = s.cant_wake.as_ref().unwrap();+ assert_eq!(c.reason, "not-connected");+ assert_eq!(c.text, "Claude Code isn't connected yet");+ assert_eq!(c.handle, "claude");+ // Signed in: woken. Not this device's: never checked against its sign-ins.+ let mut ok = input(&["CLAUDE_CODE_OAUTH_TOKEN"]);+ ok.members = i.members.clone();+ assert_eq!(plan(&ok, "@claude hi").steps[0].action, "wake");+ i.members[1].mine = false;+ assert_eq!(plan(&i, "@claude hi").steps[0].action, "wake");+ }++ #[test]+ fn an_at_of_nobody_here_is_said_plainly() {+ let p = plan(&input(&["CLAUDE_CODE_OAUTH_TOKEN"]), "@ghost are you there");+ let c = p.steps[0].cant_wake.clone().unwrap();+ assert_eq!(p.steps[0].action, "unknown");+ assert_eq!(c.reason, "no-such-member");+ assert_eq!(c.text, "Nobody called @ghost is in this Space");+ assert!(c.detail.contains("Agents here: @hermes"), "{}", c.detail);+ assert_eq!(c.connect_label, None);+ // A person, or Ask first's job (places are @mentioned there), is not reported.+ assert!(plan(&input(&[]), "@grace hi").steps.is_empty());+ let mut i = input(&[]);+ i.report_unknown = false;+ assert!(plan(&i, "@my-mac run it").steps.is_empty());+ }+#[test]fn sending_adds_wakes_or_says_why_not() {// Signed in: Claude Code is added, then woken by the message; Hermes,@@ -573,7 +732,11 @@ mod tests {.iter().map(|s| (s.handle.as_str(), s.action.as_str())).collect();- assert_eq!(s, [("claude", "add"), ("hermes", "wake")]);+ // `@nobody` is nobody in this Space: it says so instead of doing nothing.+ assert_eq!(+ s,+ [("claude", "add"), ("hermes", "wake"), ("nobody", "unknown")]+ );// No sign-in: blocked, with Connect.let p = plan(&input(&[]), "@claude fix the build");diff --git a/libs/cua/crates/cua-spaces-app-core/tests/summon_harnesses.rs b/libs/cua/crates/cua-spaces-app-core/tests/summon_harnesses.rsindex ef489cb37d..0e1c552c2f 100644--- a/libs/cua/crates/cua-spaces-app-core/tests/summon_harnesses.rs+++ b/libs/cua/crates/cua-spaces-app-core/tests/summon_harnesses.rs@@ -13,6 +13,7 @@ fn input() -> SummonInput {members: vec![],people: vec![],can_add: true,+ report_unknown: false,connectors: ConnectorsInput::default(),}}diff --git a/libs/cua/crates/cua-spaces-ext/src/persistent/members.rs b/libs/cua/crates/cua-spaces-ext/src/persistent/members.rsindex 199472f706..142a975e33 100644--- a/libs/cua/crates/cua-spaces-ext/src/persistent/members.rs+++ b/libs/cua/crates/cua-spaces-ext/src/persistent/members.rs@@ -365,6 +365,20 @@ impl Persistent {}}+ /// The member of `space` that `token` names: the `@handle` the Space+ /// knows it by, else its key on this machine (`claude-8`). The key+ /// is only an alias: a member's handle always wins, and a Space never+ /// answers to another Space's key. The one rule every @mention, add+ /// and wake goes through, so a name copied from `cua agent ls` reaches+ /// the same member as the handle the thread shows.+ pub fn member_named(&self, space: &str, token: &str) -> Result<Option<AgentRecord>> {+ let token = token.trim().trim_start_matches('@').to_ascii_lowercase();+ let members = self.members_of(space)?;+ let by = |f: &dyn Fn(&AgentRecord) -> bool| members.iter().find(|r| f(r)).cloned();+ Ok(by(&|r| r.handle().eq_ignore_ascii_case(&token))+ .or_else(|| by(&|r| r.name.eq_ignore_ascii_case(&token))))+ }+/// The agent members of `space` (a Space id).pub fn members_of(&self, space: &str) -> Result<Vec<AgentRecord>> {Ok(self@@ -425,10 +439,7 @@ impl Persistent {let space = self.spaces.resolve(&spec.space)?.to_string();let wanted = spec.name.clone();// This Space's own member of that name (an older Cua's included).- let here = self- .members_of(&space)?- .into_iter()- .find(|r| r.handle() == wanted);+ let here = self.member_named(&space, &wanted)?;let rec = match here {Some(r) => {if r.harness != spec.harness {@@ -1597,13 +1608,12 @@ impl Thread {.collect())}- /// The key of this Space's member that answers to `@handle`.+ /// The key of this Space's member that answers to `@handle` (or, as an+ /// alias, to its key on this machine).fn member_key(&self, handle: &str) -> Option<String> {self.p- .members_of(self.store.space())+ .member_named(self.store.space(), handle).ok()?- .into_iter()- .find(|r| r.handle() == handle).map(|r| r.name)}@@ -1653,18 +1663,22 @@ impl Thread {}let author = self.author();let members = self.member_names()?;- // `@claude` of this Space is the member's key (`claude-2` in a second Space).- let mentions: Vec<String> = parse_mentions(&args.text)+ // `@claude` of this Space is the member's key (`claude-2` in a second+ // Space); the key itself (`@claude-2`) reaches the same member.+ let mut mentions: Vec<String> = vec![];+ for key in parse_mentions(&args.text).into_iter()- .filter(|m| members.contains(m)).filter_map(|m| self.member_key(&m))- .collect();+ {+ if !mentions.contains(&key) {+ mentions.push(key);+ }+ }let fold = self.store.fold()?;let by_agent = author.agent_name().map(str::to_string);// Mentions a person did not type: `@everyone`, or a reply to an agent's message.let mut implied: Vec<String> = vec![];let mut everyone = false;- let mut mentions = mentions;if by_agent.is_none() {let typed = parse_mentions(&args.text);if typed.iter().any(|m| m == "everyone") && !members.iter().any(|h| h == "everyone") {diff --git a/libs/cua/crates/cua-spaces-ext/src/persistent/phone/task.rs b/libs/cua/crates/cua-spaces-ext/src/persistent/phone/task.rsindex 69063a33ff..bb7fbb411d 100644--- a/libs/cua/crates/cua-spaces-ext/src/persistent/phone/task.rs+++ b/libs/cua/crates/cua-spaces-ext/src/persistent/phone/task.rs@@ -682,11 +682,7 @@ impl Job {/// updates it). In a Space the caller was given, an agent that is not a/// member yet is the owner's to add.fn add_agent(&self, space: &str, existing: bool) -> Result<()> {- let rec = self- .p- .members_of(space)?- .into_iter()- .find(|r| r.handle() == self.agent.handle);+ let rec = self.p.member_named(space, self.agent.handle)?;if rec.is_some() && existing {return Ok(());}diff --git a/libs/cua/crates/cua-spaces-ext/tests/thread_compat.rs b/libs/cua/crates/cua-spaces-ext/tests/thread_compat.rsindex 5c9c296071..81edd9206b 100644--- a/libs/cua/crates/cua-spaces-ext/tests/thread_compat.rs+++ b/libs/cua/crates/cua-spaces-ext/tests/thread_compat.rs@@ -1472,6 +1472,58 @@ async fn two_spaces_each_get_their_own_claude() {assert_eq!(first["entry"]["task"]["to"], "claude");}+/// The name `cua agent ls` shows (`claude-2`, the member's key on this+/// machine) is an alias of the Space's `@claude`: an @mention or an add+/// by that name reaches the same member instead of waking nobody (or+/// adding a second one). Only inside the member's own Space.+#[tokio::test(flavor = "multi_thread", worker_threads = 2)]+async fn the_hosts_key_for_a_member_answers_as_an_alias_in_its_own_space() {+ let fx = setup().await;+ let (_srv2, two) = second_space(&fx).await;+ add_claude(&fx, &fx.space).await.unwrap();+ add_claude(&fx, &two).await.unwrap();+ // `@claude-2` in the second Space is its member `claude` (key claude-2).+ let by_key = call(+ &fx.mcp,+ "thread_post",+ json!({"space": two, "text": "@claude-2 hi"}),+ )+ .await+ .unwrap();+ assert_eq!(by_key["entry"]["task"]["to"], "claude-2");+ assert_eq!(by_key["entry"]["mentions"], json!(["claude-2"]));+ // The handle and the key together are one member, one task.+ let both = call(+ &fx.mcp,+ "thread_post",+ json!({"space": two, "text": "@claude @claude-2 hi"}),+ )+ .await+ .unwrap();+ assert_eq!(both["entry"]["mentions"], json!(["claude-2"]));+ // Adding by the key is the same member, not a third.+ call(+ &fx.mcp,+ "agent_add",+ json!({"space": two, "name": "claude-2", "harness": "claude-code"}),+ )+ .await+ .unwrap();+ assert_eq!(+ member_names(&fx, &two).await,+ [("claude-2".to_string(), "claude".to_string())]+ );+ // Another Space's key is nobody's here.+ let other = call(+ &fx.mcp,+ "thread_post",+ json!({"space": fx.space, "text": "@claude-2 hi"}),+ )+ .await+ .unwrap();+ assert!(other["entry"]["task"].is_null());+}+/// Deleting a Space frees its members' names.#[tokio::test(flavor = "multi_thread", worker_threads = 2)]async fn a_deleted_spaces_name_is_free_for_a_new_space() {