Skip to content

armgit / cua

Public Imported from GitHub
0

Scale computer-use 2.0 with open-source drivers, cross-OS sandboxes, and benchmarks for training, evaluation, and data generation.

feat(spaces): talk to agents without typing @ every time (#6135)

ddupont19c1f22cbeb0
diff --git a/apps/cua-spaces-web/src/__tests__/agent-addressing.test.tsx b/apps/cua-spaces-web/src/__tests__/agent-addressing.test.tsx
new file mode 100644
index 0000000000..0b895784e4
--- /dev/null
+++ b/apps/cua-spaces-web/src/__tests__/agent-addressing.test.tsx
@@ -0,0 +1,213 @@
+// SPDX-License-Identifier: FSL-1.1-MIT
+// Copyright (c) 2026 Cua AI, Inc.
+
+// Talking to agents without typing @ every time (CUA-2757): the Reply button
+// on an agent's message, the sticky "talking to" chip in the composer, and
+// `@everyone`. The page names the agent in the text it posts.
+
+import { act, cleanup, fireEvent, render, waitFor } from "@testing-library/react";
+import { createRef } from "react";
+import { afterEach, describe, expect, it, vi } from "vitest";
+
+import { Composer, type ComposerHandle } from "@/components/space-thread/composer";
+import { DEMO_THREAD_SPACE } from "@/bridge/adapters/demo/thread";
+import { pinAgent, useAddressing } from "@/lib/addressing";
+import { mountApp, stubBrowserApis } from "./app-harness";
+
+afterEach(cleanup);
+stubBrowserApis();
+
+const q = (s: string) => document.querySelector<HTMLElement>(s);
+const qa = (s: string) => [...document.querySelectorAll<HTMLElement>(s)];
+const path = `/spaces/${encodeURIComponent(DEMO_THREAD_SPACE)}`;
+
+async function composer() {
+ return waitFor(() => {
+ const el = q("[data-composer]") as HTMLTextAreaElement | null;
+ expect(el?.disabled).toBe(false);
+ return el!;
+ });
+}
+
+describe("Reply on an agent's message", () => {
+ it("is on agents' messages only, named for screen readers, and fills the box once without touching the text", async () => {
+ await mountApp(path, { failsCreates: false, listsGhost: false });
+ const box = await composer();
+ await waitFor(() => expect(qa("[data-reply]").length).toBeGreaterThan(0));
+ const buttons = qa("[data-reply]");
+ for (const b of buttons) {
+ expect(b.getAttribute("aria-label")).toMatch(/^Reply to /);
+ // Only agents' rows have one.
+ expect(b.closest("[data-entry]")?.querySelector("[data-person-name]")).toBeNull();
+ }
+ // Hidden until hover or focus, but there for keyboards and touch.
+ expect(buttons[0]!.className).toContain("group-focus-within/msg:opacity-100");
+ expect(buttons[0]!.className).toContain("max-md:opacity-100");
+
+ // Clicking a message's text does not reply, fill the box or take focus.
+ const row = buttons[0]!.closest<HTMLElement>("[data-entry]")!;
+ await act(async () => {
+ fireEvent.click(row.querySelector("p, div.select-text") ?? row);
+ });
+ expect(box.value).toBe("");
+
+ const handle = buttons[0]!.dataset.reply!;
+ await act(async () => {
+ fireEvent.click(buttons[0]!);
+ });
+ expect(box.value).toBe(`@${handle} `);
+ expect(document.activeElement).toBe(box);
+ expect(box.selectionStart).toBe(box.value.length);
+ // Once: replying again keeps what is there.
+ await act(async () => {
+ fireEvent.change(box, { target: { value: `@${handle} half a sentence`, selectionStart: 20 } });
+ fireEvent.click(buttons[0]!);
+ });
+ expect(box.value).toBe(`@${handle} half a sentence`);
+ });
+
+ it("replies with the R key on a focused message", async () => {
+ await mountApp(path, { failsCreates: false, listsGhost: false });
+ const box = await composer();
+ await waitFor(() => expect(qa("[data-reply]").length).toBeGreaterThan(0));
+ const button = qa("[data-reply]")[0]!;
+ button.focus();
+ await act(async () => {
+ fireEvent.keyDown(button, { key: "r" });
+ });
+ expect(box.value).toBe(`@${button.dataset.reply} `);
+ expect(document.activeElement).toBe(box);
+ });
+
+ it("pins the agent as a chip once the reply is sent, and the next message needs no @", async () => {
+ await mountApp(path, { failsCreates: false, listsGhost: false });
+ const box = await composer();
+ await waitFor(() => expect(qa("[data-reply]").length).toBeGreaterThan(0));
+ // Several agents, nobody addressed yet: no chip.
+ expect(q("[data-addressee]")).toBeNull();
+ const reply = qa("[data-reply]").find((b) => b.dataset.reply === "claude")!;
+ await act(async () => {
+ fireEvent.click(reply);
+ });
+ await act(async () => {
+ fireEvent.change(box, { target: { value: "@claude can you check the tests?", selectionStart: 32 } });
+ fireEvent.keyDown(box, { key: "Enter" });
+ await new Promise((r) => setTimeout(r, 30));
+ });
+ await waitFor(() => expect(q("[data-addressee-chip='claude']")).not.toBeNull());
+ expect(q("[data-addressee]")?.getAttribute("aria-label")).toBe("Talking to Claude Code");
+ expect(box.placeholder).toBe("Message Claude Code");
+ // The next message names no one; the posted text does.
+ await act(async () => {
+ fireEvent.change(box, { target: { value: "and the lint", selectionStart: 12 } });
+ fireEvent.keyDown(box, { key: "Enter" });
+ await new Promise((r) => setTimeout(r, 30));
+ });
+ await waitFor(() => expect(qa("[data-entry]").some((e) => e.textContent?.includes("and the lint") && e.textContent.includes("@claude"))).toBe(true));
+ // It is kept for this Space.
+ expect(useAddressing.getState().bySpace[DEMO_THREAD_SPACE]).toMatchObject({ pinned: ["claude"], last: "claude", told: true });
+ // The X removes it, and focus returns to the box.
+ await act(async () => {
+ fireEvent.click(q("[data-addressee-remove='claude']")!);
+ });
+ expect(q("[data-addressee]")).toBeNull();
+ expect(document.activeElement).toBe(box);
+ expect(useAddressing.getState().bySpace[DEMO_THREAD_SPACE]?.pinned).toEqual([]);
+ });
+
+ it("offers @everyone in the picker", async () => {
+ await mountApp(path, { failsCreates: false, listsGhost: false });
+ const box = await composer();
+ fireEvent.change(box, { target: { value: "@eve", selectionStart: 4 } });
+ await waitFor(() => expect(q("[data-mention-option='everyone']")).not.toBeNull());
+ expect(q("[data-mention-option='everyone']")?.getAttribute("aria-disabled")).toBeNull();
+ fireEvent.keyDown(box, { key: "Enter" });
+ expect(box.value).toBe("@everyone ");
+ });
+});
+
+describe("an addressee that is not connected", () => {
+ it("says so on the chip, and the send still goes", async () => {
+ // Claude was addressed earlier in this Space and is not signed in.
+ pinAgent(DEMO_THREAD_SPACE, "claude");
+ await mountApp(path, { failsCreates: false, listsGhost: false, demo: { threadAuthFailed: true } });
+ const box = await composer();
+ // The chip uses the Connections wording for a sign-in that is missing.
+ const chip = await waitFor(() => {
+ const c = q("[data-addressee-chip='claude']");
+ expect(c?.hasAttribute("data-addressee-problem")).toBe(true);
+ return c!;
+ });
+ expect(chip.textContent).toBe("Claude Code needs to be connected");
+ expect(chip.textContent).not.toContain("·");
+ // The send still goes, with the name in front.
+ await act(async () => {
+ fireEvent.change(box, { target: { value: "try again", selectionStart: 9 } });
+ fireEvent.keyDown(box, { key: "Enter" });
+ await new Promise((r) => setTimeout(r, 30));
+ });
+ await waitFor(() => expect(qa("[data-entry]").some((e) => e.textContent?.includes("@claude try again"))).toBe(true));
+ });
+});
+
+describe("the composer's chip", () => {
+ const props = {
+ placeholder: "Message room",
+ candidates: [
+ { handle: "claude", label: "Claude Code", kind: "agent" as const },
+ { handle: "everyone", label: "Everyone", kind: "agent" as const, detail: "Only people who can give tasks can message everyone", disabled: true },
+ ],
+ handles: new Set(["claude"]),
+ agentHarness: () => "claude-code",
+ onSend: async () => {},
+ };
+ const agentHandles = new Set(["claude", "hermes"]);
+
+ it("shows who it goes to, says when they can't take it, and goes with the X or Backspace", async () => {
+ const onRemove = vi.fn();
+ const { container } = render(
+ <Composer {...props} addressee={{ handles: ["claude"], label: () => "Claude Code", problem: () => "Claude Code needs to be connected", onRemove, agentHandles }} />,
+ );
+ const chip = container.querySelector("[data-addressee-chip='claude']")!;
+ expect(chip.hasAttribute("data-addressee-problem")).toBe(true);
+ expect(chip.textContent).toBe("Claude Code needs to be connected");
+ const x = container.querySelector<HTMLElement>("[data-addressee-remove='claude']")!;
+ expect(x.getAttribute("aria-label")).toBe("Stop talking to Claude Code");
+ fireEvent.click(x);
+ expect(onRemove).toHaveBeenCalledWith("claude");
+ onRemove.mockClear();
+ fireEvent.keyDown(container.querySelector("[data-composer]")!, { key: "Backspace" });
+ expect(onRemove).toHaveBeenCalledWith("claude");
+ });
+
+ it("steps aside while the text names an agent itself", () => {
+ const { container } = render(<Composer {...props} addressee={{ handles: ["claude"], label: () => "Claude Code", problem: () => null, onRemove: () => {}, agentHandles }} />);
+ const box = container.querySelector<HTMLTextAreaElement>("[data-composer]")!;
+ expect(container.querySelector("[data-addressee]")).not.toBeNull();
+ fireEvent.change(box, { target: { value: "@hermes hi", selectionStart: 10 } });
+ expect(container.querySelector("[data-addressee]")).toBeNull();
+ });
+
+ it("lists a disabled @everyone with its reason and does not pick it", () => {
+ const { container } = render(<Composer {...props} />);
+ const box = container.querySelector<HTMLTextAreaElement>("[data-composer]")!;
+ fireEvent.change(box, { target: { value: "@ev", selectionStart: 3 } });
+ const opt = container.querySelector("[data-mention-option='everyone']")!;
+ expect(opt.getAttribute("aria-disabled")).toBe("true");
+ expect(opt.textContent).toContain("Only people who can give tasks can message everyone");
+ fireEvent.keyDown(box, { key: "Enter" });
+ expect(box.value).toBe("@ev");
+ });
+
+ it("fills the box and focuses it from its handle, once", () => {
+ const ref = createRef<ComposerHandle>();
+ const { container } = render(<Composer {...props} composerRef={ref} />);
+ const box = container.querySelector<HTMLTextAreaElement>("[data-composer]")!;
+ fireEvent.change(box, { target: { value: "look at this", selectionStart: 12 } });
+ act(() => ref.current!.reply("claude"));
+ expect(box.value).toBe("@claude look at this");
+ expect(document.activeElement).toBe(box);
+ act(() => ref.current!.reply("claude"));
+ expect(box.value).toBe("@claude look at this");
+ });
+});
diff --git a/apps/cua-spaces-web/src/__tests__/space-thread.test.tsx b/apps/cua-spaces-web/src/__tests__/space-thread.test.tsx
index 4e62309156..cb9197553f 100644
--- a/apps/cua-spaces-web/src/__tests__/space-thread.test.tsx
+++ b/apps/cua-spaces-web/src/__tests__/space-thread.test.tsx
@@ -76,7 +76,7 @@ describe("a Space's thread", () => {
});
fireEvent.change(box, { target: { value: "@", selectionStart: 1 } });
await waitFor(() => expect(q("[data-mention-picker]")).not.toBeNull());
- expect(qa("[data-mention-option]").map((o) => o.dataset.mentionOption)).toEqual(["claude", "hermes", "cursor", "codex", "openclaw", "grace", "linus"]);
+ expect(qa("[data-mention-option]").map((o) => o.dataset.mentionOption)).toEqual(["claude", "hermes", "cursor", "codex", "openclaw", "everyone", "grace", "linus"]);
fireEvent.keyDown(box, { key: "ArrowDown" });
fireEvent.keyDown(box, { key: "Enter" });
expect(box.value).toBe("@hermes ");
diff --git a/apps/cua-spaces-web/src/bridge/__tests__/thread.test.ts b/apps/cua-spaces-web/src/bridge/__tests__/thread.test.ts
index 8101272c78..5c0937b925 100644
--- a/apps/cua-spaces-web/src/bridge/__tests__/thread.test.ts
+++ b/apps/cua-spaces-web/src/bridge/__tests__/thread.test.ts
@@ -185,6 +185,21 @@ describe("folding the thread", () => {
expect((items[2] as Extract<(typeof items)[number], { type: "message" }>).quote).toBeNull();
});
+ it("draws a message that tasks several agents once, and reads its copy's marker from the tools' JSON", () => {
+ seq = 0;
+ const first = entry({ text: "@claude @hermes review", task: { to: "claude", session: null } });
+ const copy = entry({ text: "@claude @hermes review", task: { to: "hermes", session: null }, fanoutOf: first.seq });
+ const reply = entry({ author: { kind: "agent", id: "agent:hermes", name: "hermes" }, replyTo: copy.seq, text: "Looks good" });
+ const items = foldThread([first, copy, update(copy.seq, "working"), reply]);
+ expect(items.map((i) => i.type)).toEqual(["task", "message"]);
+ expect((items[1] as Extract<(typeof items)[number], { type: "message" }>).entry.text).toBe("Looks good");
+ const page = threadPageFromTool({
+ entries: [{ seq: 3, kind: "message", author: { kind: "person", id: "a", name: "A" }, text: "x", task: { to: "hermes" }, fanout_of: 2 }, { seq: 2, kind: "message", author: { kind: "person", id: "a", name: "A" }, text: "x" }],
+ });
+ expect(page.entries.find((e) => e.seq === 3)?.fanoutOf).toBe(2);
+ expect(page.entries.find((e) => e.seq === 2)?.fanoutOf).toBeUndefined();
+ });
+
it("keeps a task queued until it is picked up, and shows a failure", () => {
seq = 0;
const queued = entry({ task: { to: "claude", session: null } });
diff --git a/apps/cua-spaces-web/src/bridge/adapters/demo.ts b/apps/cua-spaces-web/src/bridge/adapters/demo.ts
index 8030574882..f85fe9f763 100644
--- a/apps/cua-spaces-web/src/bridge/adapters/demo.ts
+++ b/apps/cua-spaces-web/src/bridge/adapters/demo.ts
@@ -135,6 +135,8 @@ export interface DemoOptions {
threadLookalike?: boolean;
/** `?demo=thread-auth-failed`: Claude and Hermes answer "hi" with "not connected" (CUA-2638). */
threadAuthFailed?: boolean;
+ /** `?demo=thread-paused`: agents wake each other until the daemon pauses agent to agent messages (CUA-2757). */
+ threadPaused?: boolean;
/** `?demo=thread-stranger`: an agent whose owner is not in the Space (its card opens their profile in place). */
threadStranger?: boolean;
/** Join codes: redeemed this long after they are made (null: never, `?demo=thread-join-slow`). */
@@ -234,6 +236,7 @@ export function demoOptionsFromSearch(search: string): DemoOptions {
threadLookalike: flags.has("thread-lookalike"),
threadAuthFailed: flags.has("thread-auth-failed"),
threadStranger: flags.has("thread-stranger"),
+ threadPaused: flags.has("thread-paused"),
threadRequest: flags.has("thread-request"),
...(flags.has("thread-join-slow") || flags.has("thread-join-expire") ? { joinRedeemMs: null } : {}),
...(flags.has("thread-join-expire") ? { joinExpireMs: 6_000 } : {}),
@@ -909,7 +912,7 @@ export function createDemoAdapter(options: DemoOptions = {}): DataAdapter & { re
...(options.noTeam ? { "teams.list": () => ({ teams: [], currentTeamId: null }) } : {}),
...demoRelayUsageHandlers(ctx),
...demoLinksHandlers(ctx),
- ...demoThreadHandlers({ now, wait, stepMs: step, enabled: !options.noThread, role: options.threadRole ?? "owner", lookalike: options.threadLookalike ?? false, authFailed: options.threadAuthFailed ?? false, stranger: options.threadStranger ?? false,
+ ...demoThreadHandlers({ now, wait, stepMs: step, enabled: !options.noThread, role: options.threadRole ?? "owner", lookalike: options.threadLookalike ?? false, authFailed: options.threadAuthFailed ?? false, stranger: options.threadStranger ?? false, paused: options.threadPaused ?? false,
joinRedeemMs: options.joinRedeemMs,
joinExpireMs: options.joinExpireMs,
request: options.threadRequest ?? false,
diff --git a/apps/cua-spaces-web/src/bridge/adapters/demo/thread.ts b/apps/cua-spaces-web/src/bridge/adapters/demo/thread.ts
index 14d1f47a3a..0bd8372f32 100644
--- a/apps/cua-spaces-web/src/bridge/adapters/demo/thread.ts
+++ b/apps/cua-spaces-web/src/bridge/adapters/demo/thread.ts
@@ -278,7 +278,7 @@ function demoSideThreads(now: number, me: { id: string; name: string }): [string
];
}
-function demoConversation(now: number, owner: { id: string; name: string }, opts: { lookalike?: boolean; authFailed?: boolean; stranger?: boolean } = {}): DemoThread {
+function demoConversation(now: number, owner: { id: string; name: string }, opts: { lookalike?: boolean; authFailed?: boolean; stranger?: boolean; paused?: boolean } = {}): DemoThread {
const ids = demoIdentities(now, owner);
// An agent's posts carry who it was when it posted (they stay after it leaves).
const agent = (handle: string) => ({ kind: "agent", id: `agent:${handle}`, name: handle, identity: ids[handle] });
@@ -386,6 +386,18 @@ function demoConversation(now: number, owner: { id: string; name: string }, opts
}
}
}
+ if (opts.paused) {
+ // Agents asked each other three times in a row; the fourth ask is posted, wakes nobody, and the daemon says so once.
+ const ask = (from: ReturnType<typeof agent>, to: string, text: string, ts: number, hops: number) =>
+ add({ ts_ms: ts, author: from, text, mentions: [to], ...(hops <= 3 ? { task: { to, session: null }, hops } : {}) });
+ const first = add({ ts_ms: min(4), author: DEMO_THREAD_ME, text: "@claude look at the flaky ws_reconnect test and get a second opinion", mentions: ["claude"], task: { to: "claude", session: null } });
+ update(min(4), first, "done");
+ ask(CLAUDE, "hermes", "@hermes can you check the timeout I picked?", min(3), 1);
+ ask(HERMES, "claude", "@claude it looks fine, can you confirm with a rerun?", min(2), 2);
+ ask(CLAUDE, "hermes", "@hermes rerun is green, anything else?", min(1), 3);
+ ask(HERMES, "claude", "@claude nothing else from me, anything from you?", min(1), 4);
+ add({ ts_ms: min(1), author: { kind: "system", id: "system:limits", name: "Cua" }, kind: "system", text: "Paused agent to agent messages for a moment" });
+ }
if (opts.stranger) {
// Dana's Gemini CLI: Dana is not in this Space, so her card opens in place.
const dana = { id: "acct_dana", name: "Dana" };
@@ -443,6 +455,7 @@ export function demoThreadHandlers({
lookalike = false,
authFailed = false,
stranger = false,
+ paused = false,
joinRedeemMs,
joinExpireMs,
request = false,
@@ -458,6 +471,8 @@ export function demoThreadHandlers({
authFailed?: boolean;
/** `?demo=thread-stranger`: an agent whose owner is not in the Space. */
stranger?: boolean;
+ /** `?demo=thread-paused`: the thread shows the daemon's note that agent to agent messages were paused. */
+ paused?: boolean;
/** How long after it is made an open code is redeemed (null: never). Default 12 steps. */
joinRedeemMs?: number | null;
/** Codes expire this long after they are made, instead of their ttl. */
@@ -466,7 +481,7 @@ export function demoThreadHandlers({
request?: boolean;
}): DemoHandlers<ThreadOpName> {
const owner = role === "owner" ? DEMO_THREAD_ME : GRACE;
- const threads = new Map<string, DemoThread>([[DEMO_THREAD_SPACE, demoConversation(now(), owner, { lookalike, authFailed, stranger })], ...(role === "owner" ? demoSideThreads(now(), DEMO_THREAD_ME) : [])]);
+ const threads = new Map<string, DemoThread>([[DEMO_THREAD_SPACE, demoConversation(now(), owner, { lookalike, authFailed, stranger, paused })], ...(role === "owner" ? demoSideThreads(now(), DEMO_THREAD_ME) : [])]);
let codeSeq = 0;
const redeemAfter = joinRedeemMs === undefined ? stepMs * 12 : joinRedeemMs;
const SYSTEM = { kind: "system", id: "system:members", name: "Cua" };
diff --git a/apps/cua-spaces-web/src/bridge/contracts/bridge-shapes.json b/apps/cua-spaces-web/src/bridge/contracts/bridge-shapes.json
index 92b94eb4ad..fb28c61fb6 100644
--- a/apps/cua-spaces-web/src/bridge/contracts/bridge-shapes.json
+++ b/apps/cua-spaces-web/src/bridge/contracts/bridge-shapes.json
@@ -5590,6 +5590,12 @@
"message",
"retryable"
]
+ },
+ "fanoutOf": {
+ "type": [
+ "number",
+ "null"
+ ]
}
},
"required": [
diff --git a/apps/cua-spaces-web/src/bridge/contracts/shapes.ts b/apps/cua-spaces-web/src/bridge/contracts/shapes.ts
index c8230d8912..9ced978b9b 100644
--- a/apps/cua-spaces-web/src/bridge/contracts/shapes.ts
+++ b/apps/cua-spaces-web/src/bridge/contracts/shapes.ts
@@ -965,6 +965,7 @@ const ThreadEntryShape = ref(
),
view: opt(nullable(object({ kind: oneOf("desktop", "window"), app: nullable(str), title: nullable(str), windowId: nullable(str) }))),
failure: opt(nullable(ThreadFailureShape)),
+ fanoutOf: opt(nullable(num)),
}),
);
diff --git a/apps/cua-spaces-web/src/bridge/ops/thread.ts b/apps/cua-spaces-web/src/bridge/ops/thread.ts
index 50861bc021..9e933bbe46 100644
--- a/apps/cua-spaces-web/src/bridge/ops/thread.ts
+++ b/apps/cua-spaces-web/src/bridge/ops/thread.ts
@@ -160,6 +160,8 @@ export interface ThreadEntry {
view?: ThreadView | null;
/** On an agent's reply to a task that failed: what failed, with the complete text. `text` says it in plain words. */
failure?: ThreadFailure | null;
+ /** On the copy of a message that tasks one more agent when it names several (`@a @b`, `@everyone`): the entry it copies. The page draws the original only. */
+ fanoutOf?: number | null;
}
/** `thread_post`'s `view` and every entry's: the Space's desktop, or one of its windows (`cua.env.v1.ThreadView`). */
@@ -643,6 +645,7 @@ export function threadEntryFromTool(v: unknown): ThreadEntry | null {
...(kind === "join_request" ? { joinRequest: joinRequest(e) } : {}),
...(e.view != null ? { view: threadViewFromTool(e.view) } : {}),
...(e.failure != null ? { failure: threadFailure(e.failure) } : {}),
+ ...(num(e.fanout_of) !== null ? { fanoutOf: num(e.fanout_of) } : {}),
};
}
diff --git a/apps/cua-spaces-web/src/bridge/thread.ts b/apps/cua-spaces-web/src/bridge/thread.ts
index d38f387328..22be4789bc 100644
--- a/apps/cua-spaces-web/src/bridge/thread.ts
+++ b/apps/cua-spaces-web/src/bridge/thread.ts
@@ -87,6 +87,8 @@ export function foldThread(entries: readonly ThreadEntry[], opts: { readSeq?: nu
const tasks = new Map<number, Extract<ThreadItem, { type: "task" }>>();
const approvals = new Map<number, Extract<ThreadItem, { type: "approval" | "join_request" }>>();
for (const e of sorted) {
+ // The copy of a message that tasks one more agent: the original is the row.
+ if (e.fanoutOf != null) continue;
if (e.kind === "task_update") {
const u = e.update;
const task = u ? tasks.get(u.task) : undefined;
@@ -192,7 +194,7 @@ export interface SpaceThread {
/** Reads the page before the oldest entry shown. */
loadEarlier(): Promise<void>;
/** Posts `text`; `view` says what the person is looking at in the Space (the main view's window). */
- post(text: string, view?: ThreadView | null): Promise<ThreadEntry | null>;
+ post(text: string, view?: ThreadView | null, replyTo?: number | null): Promise<ThreadEntry | null>;
answer(approval: number, approve: boolean): Promise<void>;
/** Changes who can task, control and approve an agent (owners and admins). */
setRights(name: string, rights: Partial<AgentRights>): Promise<void>;
@@ -399,9 +401,9 @@ export function useSpaceThread(spaceId: string | null): SpaceThread {
}, [data, spaceId, entries, hasMoreBefore, merge]);
const post = useCallback(
- async (text: string, view?: ThreadView | null) => {
+ async (text: string, view?: ThreadView | null, replyTo?: number | null) => {
if (!spaceId || !data || !text.trim()) return null;
- const entry = await data.call("thread.post", { spaceId, text: text.trim(), ...(view ? { view } : {}) });
+ const entry = await data.call("thread.post", { spaceId, text: text.trim(), ...(view ? { view } : {}), ...(replyTo != null ? { replyTo } : {}) });
if (entry) merge([entry]);
// Your own message: everything above it is read; the divider goes.
setReadSeq(null);
diff --git a/apps/cua-spaces-web/src/components/space-thread/composer.tsx b/apps/cua-spaces-web/src/components/space-thread/composer.tsx
index 3ebe38cd19..e59e7372b1 100644
--- a/apps/cua-spaces-web/src/components/space-thread/composer.tsx
+++ b/apps/cua-spaces-web/src/components/space-thread/composer.tsx
@@ -1,14 +1,34 @@
// SPDX-License-Identifier: FSL-1.1-MIT
// Copyright (c) 2026 Cua AI, Inc.
-import { SendHorizontalIcon } from "lucide-react";
-import { useLayoutEffect, useRef, useState, type KeyboardEvent, type ReactNode } from "react";
+import { SendHorizontalIcon, TriangleAlertIcon, XIcon } from "lucide-react";
+import { useImperativeHandle, useLayoutEffect, useRef, useState, type KeyboardEvent, type ReactNode, type Ref } from "react";
-import { activeMention, insertMention, matchMentions, mentionSegments, type MentionCandidate } from "@/lib/mentions";
+import { activeMention, insertMention, matchMentions, mentionedHandles, mentionSegments, startsWithMention, type MentionCandidate } from "@/lib/mentions";
import { cn } from "@/lib/utils";
import { MemberAvatar } from "./avatar";
+/** The composer, for the thread's Reply button. */
+export interface ComposerHandle {
+ /** Puts `@handle ` at the start (once) and focuses the box, caret after what was already written. */
+ reply(handle: string): void;
+ focus(): void;
+}
+
+/** Who the next message goes to without an @ typed: shown as a chip with an X. */
+export interface ComposerAddressee {
+ handles: string[];
+ /** How the chip names a handle (`Claude Code`). */
+ label: (handle: string) => string;
+ /** Why the agent can't take it yet, in words ("Claude Code needs to be connected"), or null. */
+ problem: (handle: string) => string | null;
+ /** The chip's X. */
+ onRemove: (handle: string) => void;
+ /** Every handle an agent answers to: an @ of one of them in the text means the chip is not used. */
+ agentHandles: ReadonlySet<string>;
+}
+
/**
* The thread's message box. Enter sends, Shift+Enter is a new line. `@`
* opens a picker of the Space's members (agents first): arrows move, Enter
@@ -26,6 +46,8 @@ export function Composer({
disabledReason,
footer,
className,
+ addressee,
+ composerRef,
}: {
placeholder: string;
candidates: readonly MentionCandidate[];
@@ -39,6 +61,9 @@ export function Composer({
/** A row inside the box, beside Send (the Agents tab's "In <Space> · Members see it"). */
footer?: ReactNode;
className?: string;
+ /** Who a message goes to when it names no agent (the sticky chip). */
+ addressee?: ComposerAddressee;
+ composerRef?: Ref<ComposerHandle>;
}) {
const off = disabled || !!disabledReason;
const [text, setText] = useState("");
@@ -51,6 +76,28 @@ export function Composer({
const layer = useRef<HTMLDivElement | null>(null);
const nextCaret = useRef<number | null>(null);
+ useImperativeHandle(
+ composerRef,
+ () => ({
+ focus: () => area.current?.focus(),
+ reply: (handle) => {
+ const el = area.current;
+ if (!el) return;
+ const cur = el.value;
+ // Once: a box already addressed to them keeps its text.
+ const next = startsWithMention(cur, handle) ? cur : `@${handle} ${cur.replace(/^\s+/, "")}`;
+ const end = next.length;
+ nextCaret.current = end;
+ setText(next);
+ setCaret(end);
+ setError(null);
+ el.focus();
+ el.setSelectionRange(Math.min(end, el.value.length), Math.min(end, el.value.length));
+ },
+ }),
+ [],
+ );
+
const mention = activeMention(text, caret);
const matches = mention && closedAt !== mention.start ? matchMentions(mention.query, candidates) : [];
const open = matches.length > 0;
@@ -70,7 +117,7 @@ export function Composer({
}, [text]);
const pick = (c: MentionCandidate) => {
- if (!mention) return;
+ if (!mention || c.disabled) return;
const next = insertMention(text, mention.start, caret, c.handle);
nextCaret.current = next.caret;
setText(next.text);
@@ -78,6 +125,9 @@ export function Composer({
setPicked(0);
};
+ // Typing an @ of an agent replaces the chip for this message.
+ const chips = addressee && !mentionedHandles(text, addressee.agentHandles).some((h) => addressee.agentHandles.has(h)) ? addressee.handles : [];
+
const send = () => {
const t = text.trim();
if (!t || sending || off) return;
@@ -118,6 +168,12 @@ export function Composer({
if (e.key === "Enter" && !e.shiftKey) {
e.preventDefault();
send();
+ return;
+ }
+ // Backspace in an empty box takes the last chip off, like a recipient field.
+ if (e.key === "Backspace" && !text && chips.length && addressee) {
+ e.preventDefault();
+ addressee.onRemove(chips[chips.length - 1]!);
}
};
@@ -141,13 +197,14 @@ export function Composer({
key={`${c.kind}:${c.handle}`}
role="option"
aria-selected={i === index}
+ aria-disabled={c.disabled || undefined}
data-mention-option={c.handle}
onMouseDown={(e) => {
e.preventDefault();
pick(c);
}}
onMouseEnter={() => setPicked(i)}
- className={cn("flex h-9 cursor-default items-center gap-2.5 rounded-lg px-2 text-[13px]", i === index && "bg-accent")}
+ className={cn("flex h-9 cursor-default items-center gap-2.5 rounded-lg px-2 text-[13px]", i === index && "bg-accent", c.disabled && "opacity-60")}
>
<MemberAvatar kind={c.kind} name={c.label} harness={c.kind === "agent" ? (c.harness ?? agentHarness(c.handle)) : ""} size={24} />
<span className="min-w-0 flex-1 truncate">{c.label}</span>
@@ -159,7 +216,38 @@ export function Composer({
</div>
) : null}
<div className={cn("relative flex gap-2 rounded-lg bg-muted py-1.5 pr-1.5 pl-3 focus-within:ring-2 focus-within:ring-ring/50", footer ? "flex-col" : "items-end")}>
- <div className="relative min-w-0 flex-1">
+ <div className="min-w-0 flex-1">
+ {chips.length && addressee ? (
+ <div role="group" aria-label={`Talking to ${chips.map(addressee.label).join(", ")}`} data-addressee="" className="flex flex-wrap items-center gap-1.5 pt-1">
+ {chips.map((h) => {
+ const problem = addressee.problem(h);
+ return (
+ <span
+ key={h}
+ data-addressee-chip={h}
+ data-addressee-problem={problem ? "" : undefined}
+ className={cn("inline-flex h-6 max-w-full items-center gap-1 rounded-lg bg-background pr-0.5 pl-2 text-xs text-foreground")}
+ >
+ {problem ? <TriangleAlertIcon aria-hidden className="size-3 shrink-0 text-warning" /> : null}
+ <span className="min-w-0 truncate">{problem ?? `Talking to ${addressee.label(h)}`}</span>
+ <button
+ type="button"
+ data-addressee-remove={h}
+ aria-label={`Stop talking to ${addressee.label(h)}`}
+ onClick={() => {
+ addressee.onRemove(h);
+ area.current?.focus();
+ }}
+ className="inline-flex size-5 shrink-0 cursor-default items-center justify-center rounded-lg text-muted-foreground outline-none hover:bg-accent hover:text-foreground focus-visible:ring-2 focus-visible:ring-ring/60"
+ >
+ <XIcon className="size-3" />
+ </button>
+ </span>
+ );
+ })}
+ </div>
+ ) : null}
+ <div className="relative">
{/* What you typed, with mentions as chips; the textarea above it draws only the caret. */}
<div ref={layer} aria-hidden className="pointer-events-none absolute inset-0 overflow-hidden py-1.5 text-[13px] leading-5 break-words whitespace-pre-wrap text-foreground">
{mentionSegments(text, handles).map((s, i) =>
@@ -194,6 +282,7 @@ export function Composer({
disabledReason && "disabled:opacity-100",
)}
/>
+ </div>
</div>
{disabledReason ? null : footer ? (
<div className="flex items-center gap-2" data-composer-footer="">
diff --git a/apps/cua-spaces-web/src/components/space-thread/space-call.tsx b/apps/cua-spaces-web/src/components/space-thread/space-call.tsx
index 1c47b6f294..c890ad6a41 100644
--- a/apps/cua-spaces-web/src/components/space-thread/space-call.tsx
+++ b/apps/cua-spaces-web/src/components/space-thread/space-call.tsx
@@ -2,7 +2,7 @@
// Copyright (c) 2026 Cua AI, Inc.
import { XIcon } from "lucide-react";
-import { useEffect, useMemo, useState, type ReactNode } from "react";
+import { useCallback, useEffect, useMemo, useRef, useState, type ReactNode } from "react";
import { Minimize2Icon } from "lucide-react";
@@ -17,7 +17,10 @@ import { AddAgentSheet } from "@/components/add-agent/add-agent-sheet";
import { registerAddAgent } from "@/components/add-agent/add-agent-launcher";
import { CallSplit } from "./call-split";
-import { Composer } from "./composer";
+import { defaultAddressee, EMPTY_ADDRESS, resolveAddressing, setAddress, unpinAgent, useAddressing } from "@/lib/addressing";
+import { EVERYONE, type MentionCandidate } from "@/lib/mentions";
+
+import { Composer, type ComposerHandle } from "./composer";
import { LiveRows } from "./live-row";
import { MembersPanel, type MemberPresence } from "./members-panel";
import { panelFacts } from "./rail";
@@ -31,6 +34,9 @@ import { queuedItems, useQueued } from "./queued";
import { ThreadView } from "./thread-view";
+/** Why `@everyone` is off for someone who can't give tasks. */
+const EVERYONE_REASON = "Only people who can give tasks can message everyone";
+
/**
* A Space as a call (the call storyboard): the header, the desktop on top
* with the thread below it, and who is in the Space on the right with the
@@ -173,6 +179,66 @@ export function SpaceCall({
selected: selectedMember,
select: setSelectedMember,
};
+ // Who a message goes to when it names no agent (the chip), and `@everyone`.
+ const stored = useAddressing((st) => st.bySpace[spaceId]);
+ const address = stored ?? EMPTY_ADDRESS;
+ const inSpace = useMemo(() => roster.agents.map((a) => a.handle.toLowerCase()), [roster.agents]);
+ const mayTask = thread.role !== "guest" && roster.agents.some((a) => a.youCan.task);
+ const everyoneOffered = !creating && roster.agents.length > 1;
+ const candidates = useMemo<MentionCandidate[]>(() => {
+ if (!everyoneOffered) return summon.candidates;
+ const all: MentionCandidate = { handle: EVERYONE, label: "Everyone", kind: "agent", detail: mayTask ? "All agents you can give tasks" : EVERYONE_REASON, disabled: !mayTask };
+ const lastAgent = summon.candidates.map((c) => c.kind).lastIndexOf("agent");
+ return [...summon.candidates.slice(0, lastAgent + 1), all, ...summon.candidates.slice(lastAgent + 1)];
+ }, [summon.candidates, everyoneOffered, mayTask]);
+ const known = useMemo(() => (everyoneOffered && mayTask ? new Set([...summon.handles, EVERYONE]) : summon.handles), [summon.handles, everyoneOffered, mayTask]);
+ const agentHandles = useMemo(() => new Set([...inSpace, ...summon.candidates.filter((c) => c.kind === "agent").map((c) => c.handle.toLowerCase())]), [inSpace, summon.candidates]);
+ const addressee = useMemo(() => defaultAddressee({ agents: inSpace, canEveryone: everyoneOffered && mayTask, state: address }), [inSpace, everyoneOffered, mayTask, address]);
+ const nameOf = (h: string) => (h === EVERYONE ? "Everyone" : (roster.agents.find((a) => a.handle.toLowerCase() === h)?.label ?? h));
+ const problemOf = (h: string): string | null => {
+ const a = roster.agents.find((x) => x.handle.toLowerCase() === h);
+ if (!a) return null;
+ if (a.status === "failed") return a.failure?.class === "needs_connect" ? `${a.label} needs to be connected` : `${a.label} couldn't start`;
+ if (a.identity?.state === "pending") return `${a.label} isn't connected yet`;
+ return null;
+ };
+ // Reply on an agent's message: its @handle goes in the box; the message is posted as a reply to it.
+ const composerRef = useRef<ComposerHandle | null>(null);
+ const replying = useRef<{ seq: number; handle: string } | null>(null);
+ const onReply = useCallback((handle: string, seq: number) => {
+ replying.current = { seq, handle: handle.toLowerCase() };
+ composerRef.current?.reply(handle);
+ }, []);
+ // ⌘⇧A (Ctrl+Shift+A): reply to the latest message from an agent that is still here (⌘⇧R is a reload in the desktop app).
+ useEffect(() => {
+ if (creating) return;
+ const onKey = (e: KeyboardEvent) => {
+ const mod = isMacPlatform() ? e.metaKey : e.ctrlKey;
+ if (!(mod && e.shiftKey && !e.altKey && e.key.toLowerCase() === "a")) return;
+ for (let i = thread.items.length - 1; i >= 0; i--) {
+ const it = thread.items[i]!;
+ if (!("entry" in it) || it.entry.author.kind !== "agent") continue;
+ const handle = roster.author(it.entry.author).agent?.handle;
+ if (!handle) continue;
+ e.preventDefault();
+ onReply(handle, it.entry.seq);
+ return;
+ }
+ };
+ window.addEventListener("keydown", onKey);
+ return () => window.removeEventListener("keydown", onKey);
+ }, [creating, thread.items, roster, onReply]);
+ const sendResolved = async (text: string) => {
+ const reply = replying.current;
+ const r = resolveAddressing({ text, agents: inSpace, agentHandles, known, canEveryone: everyoneOffered && mayTask, state: address, replyTo: reply?.handle });
+ const replyTo = reply && r.addressee.handles.includes(reply.handle) ? reply.seq : null;
+ await summon.send(r.text, view ?? null, replyTo);
+ replying.current = null;
+ // The first time a message is addressed for you, say so quietly.
+ const told = address.told || r.auto;
+ setAddress(spaceId, { ...r.next, told });
+ if (r.auto && !address.told) toast(`${r.addressee.handles.map(nameOf).join(" and ")} will be mentioned automatically`, { description: "Click the X on the name in the box to stop." });
+ };
const harnessOf = (handle: string) => roster.agents.find((a) => a.name === handle)?.harness ?? summon.candidates.find((c) => c.handle === handle)?.harness ?? "";
// Attachments are Cua Volume paths: show the file where the Volume is mounted.
const openAttachment = (a: ThreadAttachment) => {
@@ -198,6 +264,7 @@ export function SpaceCall({
onOpenAttachment={openAttachment}
onRemoveAgent={thread.removeAgent ?? undefined}
onRetry={(text) => summon.send(text, view ?? null)}
+ onReply={creating ? undefined : onReply}
onReachTop={thread.hasMoreBefore ? thread.loadEarlier : undefined}
empty={
thread.status === "loading" ? null : (
@@ -213,11 +280,17 @@ export function SpaceCall({
{thread.error && thread.items.length ? <p className="px-6 pb-1 text-xs text-muted-foreground">Reconnecting to the thread…</p> : null}
<div className="px-5 pb-4">
<Composer
- placeholder={`Message ${spaceName}`}
- candidates={summon.candidates}
- handles={summon.handles}
+ placeholder={!creating && addressee.handles.length ? `Message ${addressee.handles.map(nameOf).join(" and ")}` : `Message ${spaceName}`}
+ candidates={candidates}
+ handles={known}
agentHarness={harnessOf}
- onSend={(text) => (creating ? thread.post(text).then(() => undefined) : summon.send(text, view ?? null))}
+ composerRef={composerRef}
+ addressee={
+ creating || !addressee.handles.length
+ ? undefined
+ : { handles: addressee.handles, label: nameOf, problem: problemOf, agentHandles, onRemove: (h) => unpinAgent(spaceId, h, addressee.source) }
+ }
+ onSend={(text) => (creating ? thread.post(text).then(() => undefined) : sendResolved(text))}
disabled={thread.status !== "ready"}
disabledReason={thread.role === "guest" ? GUEST_COMPOSER : null}
/>
diff --git a/apps/cua-spaces-web/src/components/space-thread/summon.tsx b/apps/cua-spaces-web/src/components/space-thread/summon.tsx
index fb2bcef3af..7af56cea2f 100644
--- a/apps/cua-spaces-web/src/components/space-thread/summon.tsx
+++ b/apps/cua-spaces-web/src/components/space-thread/summon.tsx
@@ -197,9 +197,9 @@ export function useSummon({ spaceId, thread, roster, canAdd }: { spaceId: string
const handles = useMemo(() => new Set([...roster.handles, ...extra.map((c) => c.handle.toLowerCase())]), [roster.handles, extra]);
const send = useCallback(
- async (text: string, view: PostView | null) => {
+ async (text: string, view: PostView | null, replyTo?: number | null) => {
if (!data) return;
- await sendWithSummon({ core, data, spaceId, input, text, post: (t) => thread.post(t, view) });
+ await sendWithSummon({ core, data, spaceId, input, text, post: (t) => thread.post(t, view, replyTo) });
},
[core, data, spaceId, input, thread],
);
diff --git a/apps/cua-spaces-web/src/components/space-thread/thread-view.tsx b/apps/cua-spaces-web/src/components/space-thread/thread-view.tsx
index 6437c11a87..f9bc5340eb 100644
--- a/apps/cua-spaces-web/src/components/space-thread/thread-view.tsx
+++ b/apps/cua-spaces-web/src/components/space-thread/thread-view.tsx
@@ -1,7 +1,7 @@
// SPDX-License-Identifier: FSL-1.1-MIT
// Copyright (c) 2026 Cua AI, Inc.
-import { CheckIcon, FileTextIcon, ImageIcon, XIcon } from "lucide-react";
+import { CheckIcon, FileTextIcon, ImageIcon, ReplyIcon, XIcon } from "lucide-react";
import { Fragment, memo, useEffect, useLayoutEffect, useRef, useState, type ReactNode } from "react";
import { useBridge, type ThreadAttachment, type ThreadEntry, type ThreadItem, type ThreadQuote, type ThreadView } from "@/bridge";
@@ -9,7 +9,7 @@ import { Inlines } from "@/components/markdown";
import { Button } from "@/components/ui/button";
import { parseInline } from "@/lib/markdown";
import { mentionSegments } from "@/lib/mentions";
-import { cn } from "@/lib/utils";
+import { cn, isMacPlatform } from "@/lib/utils";
import { AgentTile, MemberAvatar } from "./avatar";
import { FailureNote } from "./failure-note";
@@ -45,6 +45,7 @@ export function ThreadView({
onReachTop,
onRemoveAgent,
onRetry,
+ onReply,
empty,
className,
endInset = 0,
@@ -62,6 +63,8 @@ export function ThreadView({
onRemoveAgent?: (handle: string) => Promise<void>;
/** Sends a message again (a failed agent's Retry); absent: no Retry. */
onRetry?: (text: string) => Promise<void>;
+ /** Reply on an agent's message: puts its @handle in the composer (absent: no Reply button). */
+ onReply?: (handle: string, seq: number) => void;
/** Scrolled to the top: read the page before (when there is one). */
onReachTop?: () => Promise<void>;
roster: Roster;
@@ -146,7 +149,7 @@ export function ThreadView({
<div ref={body} className="flex min-h-full flex-col justify-end gap-1 px-8 pt-5 pb-4" style={endInset ? { paddingBottom: endInset + 16 } : undefined}>
{items.map((item, i) => (
<Fragment key={item.key}>
- <ThreadItemView item={item} above={aboveSeq(items, i)} roster={roster} onAnswer={onAnswer} onOpenAttachment={onOpenAttachment} onRemoveAgent={onRemoveAgent} onRetry={onRetry} />
+ <ThreadItemView item={item} above={aboveSeq(items, i)} roster={roster} onAnswer={onAnswer} onOpenAttachment={onOpenAttachment} onRemoveAgent={onRemoveAgent} onRetry={onRetry} onReply={onReply} />
{after && "entry" in item ? after(item.entry.seq) : null}
</Fragment>
))}
@@ -175,6 +178,7 @@ export const ThreadItemView = memo(function Item({
onOpenAttachment,
onRemoveAgent,
onRetry,
+ onReply,
label,
above = null,
}: {
@@ -186,10 +190,11 @@ export const ThreadItemView = memo(function Item({
onOpenAttachment: (a: ThreadAttachment) => void;
onRemoveAgent?: (handle: string) => Promise<void>;
onRetry?: (text: string) => Promise<void>;
+ onReply?: (handle: string, seq: number) => void;
/** Beside each message's time (the DM's Space). */
label?: ReactNode;
}) {
- const m = { roster, onOpenAttachment, onRemoveAgent, label };
+ const m = { roster, onOpenAttachment, onRemoveAgent, onReply, label };
switch (item.type) {
case "unread":
return (
@@ -235,6 +240,7 @@ function Message({
roster,
onOpenAttachment,
onRemoveAgent,
+ onReply,
label,
status,
footnote,
@@ -246,6 +252,7 @@ function Message({
roster: Roster;
onOpenAttachment: (a: ThreadAttachment) => void;
onRemoveAgent?: (handle: string) => Promise<void>;
+ onReply?: (handle: string, seq: number) => void;
label?: ReactNode;
/** What the avatar sits on (the owner badge is cut out of it). */
surface?: "background" | "muted";
@@ -272,8 +279,37 @@ function Message({
className="mt-0.5"
/>
);
+ // Reply: an agent still in the Space can be addressed from its message.
+ const replyTo = who.kind === "agent" && onReply ? who.agent?.handle : undefined;
return (
- <div data-entry={entry.seq} className="flex gap-3 py-2">
+ <div
+ data-entry={entry.seq}
+ className="group/msg relative flex gap-3 py-2"
+ // R on a focused message (or its Reply button) replies, as the button does.
+ onKeyDown={
+ replyTo
+ ? (e) => {
+ if (e.key.toLowerCase() !== "r" || e.metaKey || e.ctrlKey || e.altKey || e.shiftKey || e.nativeEvent.isComposing) return;
+ const t = e.target as HTMLElement;
+ if (t.closest("input, textarea, [contenteditable=true]")) return;
+ e.preventDefault();
+ onReply!(replyTo, entry.seq);
+ }
+ : undefined
+ }
+ >
+ {replyTo ? (
+ <button
+ type="button"
+ data-reply={replyTo}
+ aria-label={`Reply to ${who.label}`}
+ title={`Reply to ${who.label} (R, or ${isMacPlatform() ? "⌘⇧A" : "Ctrl+Shift+A"} for the latest)`}
+ onClick={() => onReply!(replyTo, entry.seq)}
+ className="absolute top-1 right-0 inline-flex size-7 cursor-default items-center justify-center rounded-lg bg-background text-muted-foreground opacity-0 shadow-sm outline-none ring-1 ring-border transition-opacity group-focus-within/msg:opacity-100 group-hover/msg:opacity-100 hover:bg-accent hover:text-foreground focus-visible:opacity-100 focus-visible:ring-2 focus-visible:ring-ring/60 max-md:opacity-100 [@media(hover:none)]:opacity-100 [@media(pointer:coarse)]:size-9"
+ >
+ <ReplyIcon className="size-3.5" />
+ </button>
+ ) : null}
{who.kind === "agent" && who.identity ? (
<ProfileTrigger identity={who.identity} agent={who.agent} roster={roster} onRemove={onRemoveAgent} className="self-start rounded-full">
{avatar}
diff --git a/apps/cua-spaces-web/src/lib/addressing.test.ts b/apps/cua-spaces-web/src/lib/addressing.test.ts
new file mode 100644
index 0000000000..fcc982633a
--- /dev/null
+++ b/apps/cua-spaces-web/src/lib/addressing.test.ts
@@ -0,0 +1,115 @@
+// SPDX-License-Identifier: FSL-1.1-MIT
+// Copyright (c) 2026 Cua AI, Inc.
+
+import { beforeEach, describe, expect, it } from "vitest";
+
+import { defaultAddressee, EMPTY_ADDRESS, pinAgent, resetAddressing, resolveAddressing, setAddress, unpinAgent, useAddressing, type ResolveInput } from "./addressing";
+
+const base = (over: Partial<ResolveInput> = {}): ResolveInput => ({
+ text: "run the tests",
+ agents: ["claude", "hermes"],
+ agentHandles: new Set(["claude", "hermes", "codex"]),
+ known: new Set(["claude", "hermes", "codex", "grace", "everyone"]),
+ canEveryone: true,
+ state: EMPTY_ADDRESS,
+ ...over,
+});
+
+describe("who a message goes to", () => {
+ it("sends a plain message as it is when nobody is the default", () => {
+ const r = resolveAddressing(base());
+ expect(r.text).toBe("run the tests");
+ expect(r.addressee).toEqual({ handles: [], source: "none" });
+ expect(r.auto).toBe(false);
+ });
+
+ it("needs no @ with exactly one agent in the Space", () => {
+ const r = resolveAddressing(base({ agents: ["claude"] }));
+ expect(r.text).toBe("@claude run the tests");
+ expect(r.addressee).toEqual({ handles: ["claude"], source: "only" });
+ expect(r.auto).toBe(true);
+ });
+
+ it("defaults to the last addressed agent when several are here", () => {
+ const first = resolveAddressing(base({ text: "@hermes draft the note" }));
+ expect(first.text).toBe("@hermes draft the note");
+ expect(first.addressee).toEqual({ handles: ["hermes"], source: "typed" });
+ expect(first.next.last).toBe("hermes");
+ const next = resolveAddressing(base({ state: first.next, text: "and shorter" }));
+ // The typed mention pinned it: the pin is what carries on.
+ expect(next.text).toBe("@hermes and shorter");
+ expect(next.addressee.source).toBe("pinned");
+ // Without a pin (the chip was removed), the last addressed one is the default.
+ const quiet = resolveAddressing(base({ state: { ...first.next, pinned: [] }, text: "and shorter" }));
+ expect(quiet.text).toBe("@hermes and shorter");
+ expect(quiet.addressee.source).toBe("last");
+ });
+
+ it("lets an @ you typed win and become the pin", () => {
+ const state = { ...EMPTY_ADDRESS, pinned: ["claude"], last: "claude" };
+ const r = resolveAddressing(base({ state, text: "@hermes take this one" }));
+ expect(r.text).toBe("@hermes take this one");
+ expect(r.next.pinned).toEqual(["hermes"]);
+ expect(r.next.last).toBe("hermes");
+ });
+
+ it("ends the pin when you @ a person, and adds nothing", () => {
+ const state = { ...EMPTY_ADDRESS, pinned: ["claude"], last: "claude" };
+ const r = resolveAddressing(base({ state, text: "@grace can you look?" }));
+ expect(r.text).toBe("@grace can you look?");
+ expect(r.addressee.handles).toEqual([]);
+ expect(r.next.pinned).toEqual([]);
+ });
+
+ it("counts a reply to an agent's message as addressing it", () => {
+ const r = resolveAddressing(base({ text: "why that one?", replyTo: "Hermes" }));
+ expect(r.text).toBe("@hermes why that one?");
+ expect(r.addressee).toEqual({ handles: ["hermes"], source: "reply" });
+ expect(r.next.pinned).toEqual(["hermes"]);
+ });
+
+ it("names @everyone only when it is allowed", () => {
+ expect(resolveAddressing(base({ text: "@everyone status?" })).addressee).toEqual({ handles: ["everyone"], source: "typed" });
+ const off = resolveAddressing(base({ text: "@everyone status?", canEveryone: false }));
+ expect(off.addressee.handles).toEqual([]);
+ expect(off.text).toBe("@everyone status?");
+ });
+
+ it("keeps a pinned @everyone only while it is allowed and agents are here", () => {
+ const state = { ...EMPTY_ADDRESS, pinned: ["everyone"] };
+ expect(defaultAddressee({ agents: ["claude", "hermes"], canEveryone: true, state }).handles).toEqual(["everyone"]);
+ expect(defaultAddressee({ agents: ["claude", "hermes"], canEveryone: false, state }).source).toBe("none");
+ });
+
+ it("drops a pinned or last agent that left the Space", () => {
+ const state = { ...EMPTY_ADDRESS, pinned: ["codex"], last: "codex" };
+ expect(defaultAddressee({ agents: ["claude", "hermes"], canEveryone: true, state })).toEqual({ handles: [], source: "none" });
+ });
+
+ it("stays plain after the chip's X until someone is addressed again", () => {
+ const state = { ...EMPTY_ADDRESS, off: true };
+ expect(resolveAddressing(base({ agents: ["claude"], state })).text).toBe("run the tests");
+ expect(resolveAddressing(base({ agents: ["claude"], state, text: "@claude hi" })).next.off).toBe(false);
+ });
+});
+
+describe("what is kept per Space", () => {
+ beforeEach(resetAddressing);
+
+ it("pins on a Reply, removes with the chip's X, and keeps each Space apart", () => {
+ pinAgent("a", "Claude");
+ pinAgent("b", "hermes");
+ expect(useAddressing.getState().bySpace.a).toMatchObject({ pinned: ["claude"], last: "claude", off: false });
+ expect(useAddressing.getState().bySpace.b?.pinned).toEqual(["hermes"]);
+ unpinAgent("a", "claude", "pinned");
+ // With nothing left pinned, a single-agent default does not come straight back.
+ expect(useAddressing.getState().bySpace.a).toMatchObject({ pinned: [], off: true });
+ unpinAgent("b", "hermes", "only");
+ expect(useAddressing.getState().bySpace.b).toMatchObject({ pinned: [], off: true });
+ });
+
+ it("is written to this machine so a reload keeps it", () => {
+ setAddress("a", { pinned: ["claude"], last: "claude", off: false, told: true });
+ expect(JSON.parse(localStorage.getItem("cua.thread.addressing")!)).toEqual({ a: { pinned: ["claude"], last: "claude", off: false, told: true } });
+ });
+});
diff --git a/apps/cua-spaces-web/src/lib/addressing.ts b/apps/cua-spaces-web/src/lib/addressing.ts
new file mode 100644
index 0000000000..614112370a
--- /dev/null
+++ b/apps/cua-spaces-web/src/lib/addressing.ts
@@ -0,0 +1,145 @@
+// SPDX-License-Identifier: FSL-1.1-MIT
+// Copyright (c) 2026 Cua AI, Inc.
+
+/**
+ * Who a message in a Space goes to when you do not type an @. The page
+ * resolves it, so the posted text always names the agent(s) explicitly
+ * (the daemon wakes only on an explicit mention):
+ *
+ * 1. An @ you typed wins. It also becomes the sticky addressee.
+ * 2. A mention of a person only is a message to someone else: nothing is added.
+ * 3. A Reply to an agent's message addresses that agent.
+ * 4. The agents pinned in the composer (the chip).
+ * 5. The one agent in the Space, or else the last one addressed.
+ *
+ * The pinned agents and the last addressed one are kept per Space on this
+ * machine (never sent anywhere).
+ */
+
+import { create } from "zustand";
+
+import { addLeadingMention, EVERYONE, mentionedHandles } from "./mentions";
+
+/** What the page keeps about a Space's addressee. */
+export interface AddressState {
+ /** Agents pinned in the composer (`everyone` addresses all of them). */
+ pinned: string[];
+ /** The agent addressed last (the default when several are here). */
+ last: string | null;
+ /** The default was dismissed with the chip's X: plain messages until you address someone again. */
+ off: boolean;
+ /** The "will be mentioned automatically" note was shown once already. */
+ told: boolean;
+}
+
+export const EMPTY_ADDRESS: AddressState = { pinned: [], last: null, off: false, told: false };
+
+/** Where the addressee came from. */
+export type AddressSource = "typed" | "reply" | "pinned" | "only" | "last" | "none";
+
+export interface Addressee {
+ handles: string[];
+ source: AddressSource;
+}
+
+export interface ResolveInput {
+ text: string;
+ /** Handles of the agents in the Space. */
+ agents: readonly string[];
+ /** Every handle an agent can answer to, in the Space or able to start in it. */
+ agentHandles: ReadonlySet<string>;
+ /** Handles of everyone the picker offers (people too). */
+ known: ReadonlySet<string>;
+ /** `@everyone` is allowed (you may task at least one agent here). */
+ canEveryone: boolean;
+ state: AddressState;
+ /** The agent whose message is being replied to. */
+ replyTo?: string | null;
+}
+
+/** Who the next message goes to when nothing is typed (the chip shows this). */
+export function defaultAddressee(i: Pick<ResolveInput, "agents" | "canEveryone" | "state">): Addressee {
+ const here = new Set(i.agents.map((a) => a.toLowerCase()));
+ const pinned = i.state.pinned.filter((h) => (h === EVERYONE ? i.canEveryone && here.size > 0 : here.has(h)));
+ if (pinned.length) return { handles: pinned, source: "pinned" };
+ if (i.state.off) return { handles: [], source: "none" };
+ if (i.agents.length === 1) return { handles: [i.agents[0]!.toLowerCase()], source: "only" };
+ if (i.state.last && here.has(i.state.last)) return { handles: [i.state.last], source: "last" };
+ return { handles: [], source: "none" };
+}
+
+/** The text to post, who it goes to, and what to remember afterwards. */
+export function resolveAddressing(i: ResolveInput): { text: string; addressee: Addressee; next: AddressState; auto: boolean } {
+ const typed = mentionedHandles(i.text, i.known);
+ const typedAgents = typed.filter((h) => i.agentHandles.has(h) || (h === EVERYONE && i.canEveryone));
+ const remember = (handles: string[]): AddressState => {
+ const named = handles.filter((h) => h !== EVERYONE);
+ return { ...i.state, pinned: handles, last: named.length ? named[named.length - 1]! : i.state.last, off: false };
+ };
+ if (typedAgents.length) return { text: i.text, addressee: { handles: typedAgents, source: "typed" }, next: remember(typedAgents), auto: false };
+ // Someone else (a person): the pin ends, nothing is added.
+ if (typed.length) return { text: i.text, addressee: { handles: [], source: "none" }, next: { ...i.state, pinned: [] }, auto: false };
+ const reply = i.replyTo?.toLowerCase();
+ if (reply) return { text: addLeadingMention(i.text, reply), addressee: { handles: [reply], source: "reply" }, next: remember([reply]), auto: true };
+ const d = defaultAddressee(i);
+ if (!d.handles.length) return { text: i.text, addressee: d, next: i.state, auto: false };
+ return {
+ text: addLeadingMention(i.text, ...d.handles),
+ addressee: d,
+ // Pinned stays pinned; a default becomes the last addressed.
+ next: d.source === "pinned" ? i.state : { ...i.state, last: d.handles[d.handles.length - 1]! },
+ auto: true,
+ };
+}
+
+/* ---- Kept per Space ------------------------------------------------------------------- */
+
+const KEY = "cua.thread.addressing";
+const load = (): Record<string, AddressState> => {
+ try {
+ const raw = globalThis.localStorage?.getItem(KEY);
+ const all = raw ? (JSON.parse(raw) as Record<string, Partial<AddressState>>) : {};
+ return Object.fromEntries(
+ Object.entries(all).map(([id, s]) => [
+ id,
+ {
+ pinned: Array.isArray(s.pinned) ? s.pinned.filter((h) => typeof h === "string") : [],
+ last: typeof s.last === "string" ? s.last : null,
+ off: s.off === true,
+ told: s.told === true,
+ },
+ ]),
+ );
+ } catch {
+ return {};
+ }
+};
+
+export const useAddressing = create<{ bySpace: Record<string, AddressState> }>(() => ({ bySpace: load() }));
+useAddressing.subscribe((s) => {
+ try {
+ globalThis.localStorage?.setItem(KEY, JSON.stringify(s.bySpace));
+ } catch {
+ // Not kept past this session.
+ }
+});
+
+export const setAddress = (spaceId: string, next: AddressState): void => useAddressing.setState((s) => ({ bySpace: { ...s.bySpace, [spaceId]: next } }));
+
+/** Pins `handle` (a Reply), replacing whatever was pinned. */
+export function pinAgent(spaceId: string, handle: string): void {
+ const cur = useAddressing.getState().bySpace[spaceId] ?? EMPTY_ADDRESS;
+ setAddress(spaceId, { ...cur, pinned: [handle.toLowerCase()], last: handle === EVERYONE ? cur.last : handle.toLowerCase(), off: false });
+}
+
+/** The chip's X: `handle` leaves the pin; when nothing was pinned (a default), the default is off. */
+export function unpinAgent(spaceId: string, handle: string, source: AddressSource): void {
+ const cur = useAddressing.getState().bySpace[spaceId] ?? EMPTY_ADDRESS;
+ if (source === "pinned") setAddress(spaceId, { ...cur, pinned: cur.pinned.filter((h) => h !== handle), off: cur.pinned.filter((h) => h !== handle).length === 0 });
+ else setAddress(spaceId, { ...cur, pinned: [], off: true });
+}
+
+/** Tests start clean. */
+export function resetAddressing(): void {
+ useAddressing.setState({ bySpace: {} });
+}
diff --git a/apps/cua-spaces-web/src/lib/mentions.test.ts b/apps/cua-spaces-web/src/lib/mentions.test.ts
index ac2935964c..5e5e394093 100644
--- a/apps/cua-spaces-web/src/lib/mentions.test.ts
+++ b/apps/cua-spaces-web/src/lib/mentions.test.ts
@@ -3,7 +3,7 @@
import { describe, expect, it } from "vitest";
-import { activeMention, insertMention, matchMentions, mentionSegments, type MentionCandidate } from "./mentions";
+import { activeMention, addLeadingMention, insertMention, matchMentions, mentionedHandles, mentionSegments, startsWithMention, type MentionCandidate } from "./mentions";
const PEOPLE: MentionCandidate[] = [
{ handle: "grace", label: "Grace", kind: "person" },
@@ -45,3 +45,26 @@ describe("the composer's mentions", () => {
expect(mentionSegments("mail [email protected]")).toEqual([{ text: "mail [email protected]", mention: false }]);
});
});
+
+describe("addressing from the text", () => {
+ it("lists the handles a text mentions, once each, lower case", () => {
+ expect(mentionedHandles("@Claude and @hermes, then @claude again")).toEqual(["claude", "hermes"]);
+ expect(mentionedHandles("mail [email protected]")).toEqual([]);
+ expect(mentionedHandles("@claude @nobody", new Set(["claude"]))).toEqual(["claude"]);
+ });
+
+ it("knows whether a text already starts with a mention of a handle", () => {
+ expect(startsWithMention("@claude go", "claude")).toBe(true);
+ expect(startsWithMention(" @Claude. go", "claude")).toBe(true);
+ expect(startsWithMention("ask @claude", "claude")).toBe(false);
+ expect(startsWithMention("@hermes go", "claude")).toBe(false);
+ });
+
+ it("puts the missing mentions in front, once", () => {
+ expect(addLeadingMention("run the tests", "claude")).toBe("@claude run the tests");
+ expect(addLeadingMention("run the tests", "claude", "hermes")).toBe("@claude @hermes run the tests");
+ expect(addLeadingMention("@claude run the tests", "claude")).toBe("@claude run the tests");
+ expect(addLeadingMention("ask @claude to run", "claude")).toBe("ask @claude to run");
+ expect(addLeadingMention("@claude go", "claude", "hermes")).toBe("@hermes @claude go");
+ });
+});
diff --git a/apps/cua-spaces-web/src/lib/mentions.ts b/apps/cua-spaces-web/src/lib/mentions.ts
index 5206184bea..270b918992 100644
--- a/apps/cua-spaces-web/src/lib/mentions.ts
+++ b/apps/cua-spaces-web/src/lib/mentions.ts
@@ -19,6 +19,8 @@ export interface MentionCandidate {
harness?: string;
/** Under the name for an agent not in the Space yet ("Starts in this Space", "Not connected yet"). */
detail?: string;
+ /** Listed but not pickable (`@everyone` for someone who can't give tasks); `detail` says why. */
+ disabled?: boolean;
}
/** `@` starts a mention at the start or after a space or an opening
@@ -73,3 +75,27 @@ export function mentionSegments(text: string, handles?: ReadonlySet<string>): Me
if (last < text.length) out.push({ text: text.slice(last), mention: false });
return out;
}
+
+/** The handle that addresses every agent you may task. */
+export const EVERYONE = "everyone";
+
+/** The lower-case handles `text` mentions, in order and once each. With
+ * `handles`, only those names count. */
+export function mentionedHandles(text: string, handles?: ReadonlySet<string>): string[] {
+ const out: string[] = [];
+ for (const s of mentionSegments(text, handles)) if (s.mention && !out.includes(s.handle)) out.push(s.handle);
+ return out;
+}
+
+/** Whether `text` already starts with a mention of `handle` (so a Reply does not add it twice). */
+export function startsWithMention(text: string, handle: string): boolean {
+ const m = /^\s*@([\w][\w.-]*)/.exec(text);
+ return !!m && m[1]!.replace(/[.-]+$/, "").toLowerCase() === handle.toLowerCase();
+}
+
+/** `text` addressed to `handles`: `@a @b ` in front, unless `text` already starts with `@handle` (one handle). */
+export function addLeadingMention(text: string, ...handles: string[]): string {
+ const missing = handles.filter((h) => !mentionedHandles(text).includes(h.toLowerCase()));
+ if (!missing.length) return text;
+ return `${missing.map((h) => `@${h}`).join(" ")} ${text.replace(/^\s+/, "")}`;
+}
diff --git a/apps/cua-spaces-web/src/test-setup.ts b/apps/cua-spaces-web/src/test-setup.ts
index 62455286fb..41dbfc1c06 100644
--- a/apps/cua-spaces-web/src/test-setup.ts
+++ b/apps/cua-spaces-web/src/test-setup.ts
@@ -7,5 +7,11 @@
// settle. Passing tests return as soon as their condition holds.
import { configure } from "@testing-library/react";
+import { afterEach } from "vitest";
+
+import { resetAddressing } from "@/lib/addressing";
configure({ asyncUtilTimeout: 5_000 });
+
+// Who each Space's composer is talking to is kept per Space; a test never inherits another's.
+afterEach(resetAddressing);
diff --git a/docs/content/docs/spaces/guides/agents-in-a-space.mdx b/docs/content/docs/spaces/guides/agents-in-a-space.mdx
index 3ab997e84a..eef8232a1b 100644
--- a/docs/content/docs/spaces/guides/agents-in-a-space.mdx
+++ b/docs/content/docs/spaces/guides/agents-in-a-space.mdx
@@ -74,6 +74,43 @@ last run is idle, the message is a follow-up in the same session; if it has
none, a new run starts with its memory restored. A message sent while a turn is
running is refused, never interrupts it, and the reply says why.
+## Talk to agents in the thread
+
+In a Space's thread in Cua Spaces you do not have to type an @ every time. An
+@name still works anywhere in a message, and it is always what the agent is
+woken by, so the message you post always names who it is for.
+
+To answer an agent, hover or focus its message and press the Reply button, or
+press R while you are on the message. Cua Spaces puts `@name` at the start of
+the box once and puts the cursor in it, and your message is posted as a reply
+to that message. Selecting its text and clicking its links work as before.
+`Command+Shift+A` (`Ctrl+Shift+A` elsewhere) replies to the latest agent
+message. On a narrow window the Reply button is always visible.
+
+After you talk to an agent, a small chip with its name and an X sits in the
+box, and the next message goes to it until you @ someone else or press the X.
+Cua Spaces adds the `@name` when you send, and says so quietly the first time.
+Which agent is kept for each Space on your computer, so it is still there after
+a reload.
+
+When you have not said who, the message goes to the one agent in the Space, or
+to the last agent you talked to when there are several. A message with no
+agent to go to is a plain message to the people in the Space, as before.
+`@everyone` gives the task to every agent in the Space you are allowed to task;
+if your role cannot give tasks it is shown disabled, with the reason. A reply to
+an agent's message with no @ counts as talking to that agent.
+
+If the agent is not connected or has failed, its chip says so in words such as
+"Claude Code needs to be connected". The message is still sent, and the Connect
+card appears under it as usual.
+
+Agents do not chat among themselves without being asked. An agent wakes another
+agent only by naming it with an @, a chain of those stops after three agent to
+agent messages from your last message, and a Space allows twenty such wakes a
+minute. When a limit is reached the message is still posted, but wakes no one,
+and the thread says "Paused agent to agent messages for a moment". Any message
+from you starts a new chain.
+
## Check back
| To see | CLI | MCP |
diff --git a/docs/content/docs/spaces/reference/threads.mdx b/docs/content/docs/spaces/reference/threads.mdx
index 41ac912b91..5ee619fb2d 100644
--- a/docs/content/docs/spaces/reference/threads.mdx
+++ b/docs/content/docs/spaces/reference/threads.mdx
@@ -62,7 +62,7 @@ Every Space has one thread: what people and its agent members said, the tasks @m
#### Result
-JSON: `space`, `me` (your author object), `role` (yours here: `owner`, `admin`, `member`, `guest` (reads only) or `agent`), `entries` (oldest first; each `v`, `seq`, `id`, `ts_ms`, `author` &#123;`kind`, `id`, `name`&#125;, `kind`, `text`, `mentions`, `reply_to`, `task`, `attachments`, `approval`, `answer`, `update`, and when set `imported`, `import`, `task_seq` (the task a system note is about), `view` (what the person was looking at as they posted: &#123;`kind` `desktop` or `window`, `app`, `title`, `window_id`&#125;)), `cursor` (pass it as `after`), `caught_up`, `has_more_before`, `read_seq` (your read position), `unread` (entries after it, not yours) and `tasks` (open tasks: `seq`, `to`, `state`, `session`, `lease_until_ms`, `author`, `ts_ms`, `text`, `view`). `live`: &#123;`key`, `agents`: [&#123;`agent`, `stage`, `since_ms`, `text`&#125;]&#125;, what each agent member with a task on its way is doing now (`starting`, `installing`, `thinking`, `replying`, `using <tool>`; `since_ms`: when its oldest open task was given; `text`: what it has said so far this turn, the whole text each time and only while it streams, replaced by its reply when the turn ends); pass `key` back as `live_after` with `follow_ms` to be woken when it changes. With `with`: `with` and only your DM's entries, its own `read_seq` and `unread`, and no `tasks`.
+JSON: `space`, `me` (your author object), `role` (yours here: `owner`, `admin`, `member`, `guest` (reads only) or `agent`), `entries` (oldest first; each `v`, `seq`, `id`, `ts_ms`, `author` &#123;`kind`, `id`, `name`&#125;, `kind`, `text`, `mentions`, `reply_to`, `task`, `attachments`, `approval`, `answer`, `update`, and when set `imported`, `import`, `task_seq` (the task a system note is about), `fanout_of` (on the copy of a message that tasks one more agent it names: the entry it copies), `hops` (on a task an agent gave another agent: agent to agent hops from a person's message), `view` (what the person was looking at as they posted: &#123;`kind` `desktop` or `window`, `app`, `title`, `window_id`&#125;)), `cursor` (pass it as `after`), `caught_up`, `has_more_before`, `read_seq` (your read position), `unread` (entries after it, not yours) and `tasks` (open tasks: `seq`, `to`, `state`, `session`, `lease_until_ms`, `author`, `ts_ms`, `text`, `view`). `live`: &#123;`key`, `agents`: [&#123;`agent`, `stage`, `since_ms`, `text`&#125;]&#125;, what each agent member with a task on its way is doing now (`starting`, `installing`, `thinking`, `replying`, `using <tool>`; `since_ms`: when its oldest open task was given; `text`: what it has said so far this turn, the whole text each time and only while it streams, replaced by its reply when the turn ends); pass `key` back as `live_after` with `follow_ms` to be woken when it changes. With `with`: `with` and only your DM's entries, its own `read_seq` and `unread`, and no `tasks`.
#### Errors
@@ -72,7 +72,7 @@ JSON: `space`, `me` (your author object), `role` (yours here: `owner`, `admin`,
Post to a Space's thread.
-Posts as you (the daemon stamps the author; it is never an argument). `@name` of an agent member of this Space makes the message a task for it: the daemon wakes the agent (restoring its home if it was asleep), delivers the message as its next turn, and posts its answer as a reply when the turn ends. An agent with several sessions gives it to its lowest free session (`to_session` picks one); a busy agent gets it after its current turn; a paused one keeps it queued. Text and attachment names that look like a secret are refused: secrets belong in the Keyvault. `view` says what the person is looking at in the Space as they post (its desktop, or a window by app, title and window_id); it is stored with the entry, so an agent reads which window "this" means.
+Posts as you (the daemon stamps the author; it is never an argument). `@name` of an agent member of this Space makes the message a task for it: the daemon wakes the agent (restoring its home if it was asleep), delivers the message as its next turn, and posts its answer as a reply when the turn ends. An agent with several sessions gives it to its lowest free session (`to_session` picks one); a busy agent gets it after its current turn; a paused one keeps it queued. Naming several agents (`@ada @bo`) gives each one the task (the second and later on a copy of the message, `fanout_of` the first), and `@everyone` names every agent member you may task. A person's reply (`reply_to`) to an agent member's message with no @mention addresses that agent. An agent's post wakes another agent only through an explicit `@name` (never `@everyone` or a reply): a chain stops after 3 agent to agent hops from a person's message, and a Space allows 20 agent to agent wakes a minute; past a limit the message is posted but wakes nobody, and the thread says "Paused agent to agent messages for a moment" once. Text and attachment names that look like a secret are refused: secrets belong in the Keyvault. `view` says what the person is looking at in the Space as they post (its desktop, or a window by app, title and window_id); it is stored with the entry, so an agent reads which window "this" means.
| | |
| --- | --- |
diff --git a/libs/cua/crates/cua-spaces-contract/src/lib.rs b/libs/cua/crates/cua-spaces-contract/src/lib.rs
index d773f7545e..a0b39b15aa 100644
--- a/libs/cua/crates/cua-spaces-contract/src/lib.rs
+++ b/libs/cua/crates/cua-spaces-contract/src/lib.rs
@@ -701,7 +701,7 @@ pub const JOIN_NEXT_STEPS: &str = join_next_steps!();
const THREAD_READ_INSTRUCTIONS: &str = "Every Space has one thread: what people and its agent members said, the tasks @mentions created and how they went. Without `after` it returns the newest entries (`before` pages back, `has_more_before` says whether there are older ones); pass the returned `cursor` as `after` to read on; `follow_ms` waits for the next entry (a check-in from any device). `mark_read` moves your read cursor, which `unread` counts from. Entries are never edited: a task's state is the last `task_update` entry for it, folded into `tasks`.";
-const THREAD_POST_INSTRUCTIONS: &str = "Posts as you (the daemon stamps the author; it is never an argument). `@name` of an agent member of this Space makes the message a task for it: the daemon wakes the agent (restoring its home if it was asleep), delivers the message as its next turn, and posts its answer as a reply when the turn ends. An agent with several sessions gives it to its lowest free session (`to_session` picks one); a busy agent gets it after its current turn; a paused one keeps it queued. Text and attachment names that look like a secret are refused: secrets belong in the Keyvault. `view` says what the person is looking at in the Space as they post (its desktop, or a window by app, title and window_id); it is stored with the entry, so an agent reads which window \"this\" means.";
+const THREAD_POST_INSTRUCTIONS: &str = "Posts as you (the daemon stamps the author; it is never an argument). `@name` of an agent member of this Space makes the message a task for it: the daemon wakes the agent (restoring its home if it was asleep), delivers the message as its next turn, and posts its answer as a reply when the turn ends. An agent with several sessions gives it to its lowest free session (`to_session` picks one); a busy agent gets it after its current turn; a paused one keeps it queued. Naming several agents (`@ada @bo`) gives each one the task (the second and later on a copy of the message, `fanout_of` the first), and `@everyone` names every agent member you may task. A person's reply (`reply_to`) to an agent member's message with no @mention addresses that agent. An agent's post wakes another agent only through an explicit `@name` (never `@everyone` or a reply): a chain stops after 3 agent to agent hops from a person's message, and a Space allows 20 agent to agent wakes a minute; past a limit the message is posted but wakes nobody, and the thread says \"Paused agent to agent messages for a moment\" once. Text and attachment names that look like a secret are refused: secrets belong in the Keyvault. `view` says what the person is looking at in the Space as they post (its desktop, or a window by app, title and window_id); it is stored with the entry, so an agent reads which window \"this\" means.";
const AGENT_ADD_INSTRUCTIONS: &str = "A persistent agent is an agent member of the Space it works in, with its memory in its home in the Cua Volume (agents/<name>/), restored before each run and saved after each turn. People @mention it in the Space's thread (thread_post) and it answers there; it sleeps until a message or a schedule wakes it. Its harness keeps its memory in the home (Claude Code auto memory, Codex memories, Hermes MEMORY.md, the OpenClaw workspace). With every_minutes, daily_at or weekly_on and a prompt it also gets a schedule. With sessions (1-8) it works on up to that many tasks at once, each in its own run; session 1 alone writes its home, the others start from the home as last saved. durable, on other than local and once are not available yet and are refused. Inside the Space the agent gets the `cua` bridge: the thread, notify_user, the drive, and the user's computers it was granted.";
@@ -1306,7 +1306,7 @@ pub fn tools() -> Vec<Tool> {
// --- Space thread and members ------------------------------------------
Spec {
category: Category::Thread,
- result: "JSON: `space`, `me` (your author object), `role` (yours here: `owner`, `admin`, `member`, `guest` (reads only) or `agent`), `entries` (oldest first; each `v`, `seq`, `id`, `ts_ms`, `author` {`kind`, `id`, `name`}, `kind`, `text`, `mentions`, `reply_to`, `task`, `attachments`, `approval`, `answer`, `update`, and when set `imported`, `import`, `task_seq` (the task a system note is about), `view` (what the person was looking at as they posted: {`kind` `desktop` or `window`, `app`, `title`, `window_id`})), `cursor` (pass it as `after`), `caught_up`, `has_more_before`, `read_seq` (your read position), `unread` (entries after it, not yours) and `tasks` (open tasks: `seq`, `to`, `state`, `session`, `lease_until_ms`, `author`, `ts_ms`, `text`, `view`). `live`: {`key`, `agents`: [{`agent`, `stage`, `since_ms`, `text`}]}, what each agent member with a task on its way is doing now (`starting`, `installing`, `thinking`, `replying`, `using <tool>`; `since_ms`: when its oldest open task was given; `text`: what it has said so far this turn, the whole text each time and only while it streams, replaced by its reply when the turn ends); pass `key` back as `live_after` with `follow_ms` to be woken when it changes. With `with`: `with` and only your DM's entries, its own `read_seq` and `unread`, and no `tasks`.",
+ result: "JSON: `space`, `me` (your author object), `role` (yours here: `owner`, `admin`, `member`, `guest` (reads only) or `agent`), `entries` (oldest first; each `v`, `seq`, `id`, `ts_ms`, `author` {`kind`, `id`, `name`}, `kind`, `text`, `mentions`, `reply_to`, `task`, `attachments`, `approval`, `answer`, `update`, and when set `imported`, `import`, `task_seq` (the task a system note is about), `fanout_of` (on the copy of a message that tasks one more agent it names: the entry it copies), `hops` (on a task an agent gave another agent: agent to agent hops from a person's message), `view` (what the person was looking at as they posted: {`kind` `desktop` or `window`, `app`, `title`, `window_id`})), `cursor` (pass it as `after`), `caught_up`, `has_more_before`, `read_seq` (your read position), `unread` (entries after it, not yours) and `tasks` (open tasks: `seq`, `to`, `state`, `session`, `lease_until_ms`, `author`, `ts_ms`, `text`, `view`). `live`: {`key`, `agents`: [{`agent`, `stage`, `since_ms`, `text`}]}, what each agent member with a task on its way is doing now (`starting`, `installing`, `thinking`, `replying`, `using <tool>`; `since_ms`: when its oldest open task was given; `text`: what it has said so far this turn, the whole text each time and only while it streams, replaced by its reply when the turn ends); pass `key` back as `live_after` with `follow_ms` to be woken when it changes. With `with`: `with` and only your DM's entries, its own `read_seq` and `unread`, and no `tasks`.",
instructions: THREAD_READ_INSTRUCTIONS,
capabilities: &["thread.read"],
sdk_symbol: "space.thread().read(after:limit:)",
diff --git a/libs/cua/crates/cua-spaces-ext/src/persistent/bridge.rs b/libs/cua/crates/cua-spaces-ext/src/persistent/bridge.rs
index 4496883b87..c5f958d7c9 100644
--- a/libs/cua/crates/cua-spaces-ext/src/persistent/bridge.rs
+++ b/libs/cua/crates/cua-spaces-ext/src/persistent/bridge.rs
@@ -590,7 +590,7 @@ impl ToolExtension for AgentTools {
),
tool(
"thread_post",
- "Post to your Space's thread, as yourself. @name of another agent member gives it a task. Never post secrets.",
+ "Post to your Space's thread, as yourself. An explicit @name of another agent member gives it a task, within limits: a chain stops after 3 agent to agent hops from a person's message and a Space allows 20 such wakes a minute. Never post secrets.",
schema(
json!({"text": {"type": "string"},
"reply_to": {"type": "integer", "description": "The seq this answers."},
diff --git a/libs/cua/crates/cua-spaces-ext/src/persistent/members.rs b/libs/cua/crates/cua-spaces-ext/src/persistent/members.rs
index 7a49938b65..1ef72b19ca 100644
--- a/libs/cua/crates/cua-spaces-ext/src/persistent/members.rs
+++ b/libs/cua/crates/cua-spaces-ext/src/persistent/members.rs
@@ -1401,7 +1401,12 @@ impl Thread {
}
/// Posts as the caller. An @mention of an agent member (not the author
- /// itself) makes the entry a task for the first one mentioned.
+ /// itself) makes the entry a task for it, and each further agent
+ /// mentioned (`@a @b`) gets the same task on a copy of the message.
+ /// `@everyone` mentions every member the caller may task, and a person's
+ /// reply to an agent's message with no @mention addresses that agent.
+ /// An agent's message wakes another agent only through an explicit
+ /// @mention, within the chatter limits ([`super::wake`]).
pub async fn post(&self, args: PostArgs) -> Result<ThreadEntry> {
policy::may_write(self.p.role_of(&self.caller))?;
check_text(&args.text)?;
@@ -1421,6 +1426,40 @@ impl Thread {
.filter_map(|m| self.member_key(&m))
.collect();
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") {
+ everyone = true;
+ implied = self
+ .p
+ .members_of(self.store.space())?
+ .into_iter()
+ .map(|r| r.name)
+ .filter(|k| !mentions.contains(k))
+ .collect();
+ } else if mentions.is_empty()
+ && let Some(r) = args.reply_to
+ && let Some(parent) = self.store.get(r)?
+ && let Some(key) = parent.author.agent_name()
+ && self
+ .p
+ .get(key)
+ .is_ok_and(|rec| rec.space == self.store.space())
+ {
+ implied = vec![key.to_string()];
+ }
+ }
+ let quiet: Vec<String> = if everyone { implied.clone() } else { vec![] };
+ for k in &implied {
+ if !mentions.contains(k) {
+ mentions.push(k.clone());
+ }
+ }
let mut kind = EntryKind::Message;
let mut draft_approval = None;
let mut draft_answer = None;
@@ -1462,27 +1501,50 @@ impl Thread {
.transpose()?;
let id = new_entry_id();
let attachments = self.attachments(&id, &args.attachments).await?;
- let task_to = mentions
- .iter()
- .find(|m| author.agent_name() != Some(m.as_str()))
- .cloned();
+ // Everyone mentioned but the author itself, the caller may task.
+ let mut targets: Vec<(String, Option<crate::thread::KeyOwner>)> = vec![];
// A mention of an agent the caller can't task is posted, but gives
- // no task (a note says why).
- let mut refused = None;
- let mut keys_of = None;
- let task_to = match task_to.map(|to| (self.p.get(&to), to)) {
- Some((Ok(rec), to)) => {
- if self.p.allows(&self.caller, &rec, Right::Task) {
- keys_of = self.p.keys_of(&self.caller, &rec);
- Some(to)
- } else {
- refused = Some((to, Persistent::rights_of(&rec).task));
- None
+ // no task (a note says why; `@everyone` skips them quietly).
+ let mut refused = vec![];
+ for to in mentions
+ .iter()
+ .filter(|m| author.agent_name() != Some(m.as_str()))
+ {
+ match self.p.get(to) {
+ Ok(rec) if self.p.allows(&self.caller, &rec, Right::Task) => {
+ targets.push((to.clone(), self.p.keys_of(&self.caller, &rec)));
+ }
+ Ok(rec) => {
+ if !quiet.contains(to) {
+ refused.push((to.clone(), Persistent::rights_of(&rec).task));
+ }
}
+ Err(_) => targets.push((to.clone(), None)),
}
- Some((Err(_), to)) => Some(to),
- None => None,
- };
+ }
+ // Chatter limits: an agent's wake counts hops from the person who started the chain.
+ let mut hops = 0;
+ if let Some(me) = &by_agent {
+ if !targets.is_empty() {
+ let mine = fold
+ .tasks
+ .values()
+ .filter(|t| t.to == *me)
+ .max_by_key(|t| (!t.state.is_closed(), t.seq));
+ hops = mine.map_or(0, |t| t.hops) + 1;
+ if !self
+ .p
+ .wake_allowed(&self.store, hops, targets.len())
+ .await?
+ {
+ targets.clear();
+ }
+ }
+ } else if !targets.is_empty() {
+ self.p.wake_reset(self.store.space()).await;
+ }
+ let keys_of = targets.first().and_then(|t| t.1.clone());
+ let task_to = targets.first().map(|t| t.0.clone());
let who = author.name.clone();
let answered_join = draft_answer
.as_ref()
@@ -1500,8 +1562,27 @@ impl Thread {
)));
}
}
+ // The other agents it names get the same task on a copy of the message.
+ let copies: Vec<(String, Draft)> = targets
+ .iter()
+ .skip(1)
+ .map(|(to, keys)| {
+ let mut c = Draft::new(author.clone(), kind, args.text.clone());
+ c.mentions = mentions.clone();
+ c.attachments = attachments.clone();
+ c.task = Some(TaskTo {
+ to: to.clone(),
+ session: None,
+ });
+ c.runs_on_keys_of = keys.clone();
+ c.view = view.clone();
+ c.hops = hops;
+ (to.clone(), c)
+ })
+ .collect();
let mut d = Draft::new(author, kind, args.text);
d.id = Some(id);
+ d.hops = if task_to.is_some() { hops } else { 0 };
d.mentions = mentions;
d.reply_to = args.reply_to.or(draft_answer.as_ref().map(|a| a.approval));
d.attachments = attachments;
@@ -1513,29 +1594,35 @@ impl Thread {
});
d.runs_on_keys_of = keys_of;
d.view = view;
- // The agent shows as at work in the thread's live row right away
+ // Each agent shows as at work in the thread's live row right away
// (the dispatcher gives it the task within a second).
- if let Some(to) = &task_to
- && let Ok(rec) = self.p.get(to)
- && !rec.paused
- && !super::identity::is_external(&rec)
- && rec.session_views().iter().all(|s| s.activity.is_none())
- {
- self.p.set_stage(
- &rec,
- Some(if rec.run_id.is_some() {
- "thinking"
- } else {
- "starting"
- }),
- );
+ for to in targets.iter().map(|t| &t.0) {
+ if let Ok(rec) = self.p.get(to)
+ && !rec.paused
+ && !super::identity::is_external(&rec)
+ && rec.session_views().iter().all(|s| s.activity.is_none())
+ {
+ self.p.set_stage(
+ &rec,
+ Some(if rec.run_id.is_some() {
+ "thinking"
+ } else {
+ "starting"
+ }),
+ );
+ }
}
let e = self.store.append(d)?;
+ let mut copied = vec![];
+ for (to, mut c) in copies {
+ c.fanout_of = Some(e.seq);
+ copied.push((to, self.store.append(c)?.seq));
+ }
if let Some((seq, approve)) = answered_join {
self.p
.answer_join_request(&self.caller, &self.store, seq, approve)?;
}
- if let Some((to, holders)) = refused {
+ for (to, holders) in refused {
self.store.append(Draft::note(
"rights",
None,
@@ -1545,15 +1632,21 @@ impl Thread {
),
))?;
}
- if let Some(to) = task_to
- && let Ok(rec) = self.p.get(&to)
- && rec.paused
- {
- self.store.append(Draft::note(
- "dispatch",
- Some(e.seq),
- format!("{to} is paused; task #{} waits until it is resumed.", e.seq),
- ))?;
+ let seqs = task_to
+ .into_iter()
+ .map(|to| (to, e.seq))
+ .chain(copied)
+ .collect::<Vec<_>>();
+ for (to, seq) in seqs {
+ if let Ok(rec) = self.p.get(&to)
+ && rec.paused
+ {
+ self.store.append(Draft::note(
+ "dispatch",
+ Some(seq),
+ format!("{to} is paused; task #{seq} waits until it is resumed."),
+ ))?;
+ }
}
Ok(e)
}
diff --git a/libs/cua/crates/cua-spaces-ext/src/persistent/mod.rs b/libs/cua/crates/cua-spaces-ext/src/persistent/mod.rs
index dcc375fc17..4b4534621d 100644
--- a/libs/cua/crates/cua-spaces-ext/src/persistent/mod.rs
+++ b/libs/cua/crates/cua-spaces-ext/src/persistent/mod.rs
@@ -37,6 +37,7 @@ pub mod notify;
pub mod phases;
pub(crate) use phases::DISPATCH_BUDGET;
pub mod rights;
+pub mod wake;
use crate::DriveResult as _;
use crate::SpacesDrive as _;
@@ -471,6 +472,8 @@ pub(crate) struct Live {
/// Runs started for a task whose "woke up and joined" note waits until
/// the agent is up: run id to the task's seq.
joining: HashMap<String, u64>,
+ /// Agent-to-agent wakes per Space ([`wake`]).
+ wake: wake::LiveWake,
}
/// The persistent agents of one cua home. Cheap to clone.
diff --git a/libs/cua/crates/cua-spaces-ext/src/persistent/wake.rs b/libs/cua/crates/cua-spaces-ext/src/persistent/wake.rs
new file mode 100644
index 0000000000..1ab3d22437
--- /dev/null
+++ b/libs/cua/crates/cua-spaces-ext/src/persistent/wake.rs
@@ -0,0 +1,116 @@
+// SPDX-License-Identifier: FSL-1.1-MIT
+// Copyright (c) 2026 Cua AI, Inc.
+
+//! Agent-to-agent chatter limits. An agent's message wakes another agent
+//! only through an explicit `@mention`, and a chain of such wakes stops at
+//! [`MAX_HOPS`] hops from the person who started it; a Space also allows at
+//! most [`MAX_WAKES_PER_MINUTE`] agent-to-agent wakes a minute. A person's
+//! message resets the chain (their tasks carry no hops). When a limit
+//! trips, the message is still posted (it just wakes nobody) and the
+//! thread gets one plain note per episode; the daemon logs it too.
+
+use std::collections::{HashMap, HashSet, VecDeque};
+
+use super::Persistent;
+use crate::Result;
+use crate::thread::{Draft, ThreadStore};
+
+/// Agent-to-agent hops a chain may go (a person asks A, A asks B, B asks C, C asks D).
+pub const MAX_HOPS: u32 = 3;
+/// Agent-to-agent wakes one Space allows a minute.
+pub const MAX_WAKES_PER_MINUTE: usize = 20;
+
+/// The note the thread gets when a limit trips.
+pub const PAUSED_NOTE: &str = "Paused agent to agent messages for a moment";
+
+/// The two limits (the defaults are the product's; not a user setting).
+#[derive(Clone, Copy, Debug, PartialEq, Eq)]
+pub struct WakeLimits {
+ pub max_hops: u32,
+ pub per_minute: usize,
+}
+
+impl Default for WakeLimits {
+ fn default() -> Self {
+ WakeLimits {
+ max_hops: MAX_HOPS,
+ per_minute: MAX_WAKES_PER_MINUTE,
+ }
+ }
+}
+
+/// Per process: each Space's recent agent-to-agent wakes and the Spaces already told.
+#[derive(Default)]
+pub(crate) struct LiveWake {
+ limits: WakeLimits,
+ wakes: HashMap<String, VecDeque<u64>>,
+ noted: HashSet<String>,
+}
+
+/// Why a wake was refused.
+#[derive(Clone, Copy, Debug, PartialEq, Eq)]
+pub enum Tripped {
+ Depth,
+ Rate,
+}
+
+impl Persistent {
+ /// Sets the limits (tests and hosts; the defaults are [`WakeLimits::default`]).
+ pub async fn set_wake_limits(&self, limits: WakeLimits) {
+ self.live.lock().await.wake.limits = limits;
+ }
+
+ /// A person's message: the chain starts over, so the next trip says so again.
+ pub(crate) async fn wake_reset(&self, space: &str) {
+ self.live.lock().await.wake.noted.remove(space);
+ }
+
+ /// Whether an agent's message that would wake `n` agents, `hops` hops
+ /// from a person, may. Allowed wakes are counted. A refusal is logged
+ /// and noted in the thread once per episode.
+ pub(crate) async fn wake_allowed(
+ &self,
+ store: &ThreadStore,
+ hops: u32,
+ n: usize,
+ ) -> Result<bool> {
+ let now = cua_volume::now_ms();
+ let (tripped, first) = {
+ let mut live = self.live.lock().await;
+ let w = &mut live.wake;
+ let limits = w.limits;
+ let space = store.space().to_string();
+ let q = w.wakes.entry(space.clone()).or_default();
+ while q.front().is_some_and(|t| now.saturating_sub(*t) >= 60_000) {
+ q.pop_front();
+ }
+ let tripped = if hops > limits.max_hops {
+ Some(Tripped::Depth)
+ } else if q.len() + n > limits.per_minute {
+ Some(Tripped::Rate)
+ } else {
+ None
+ };
+ match tripped {
+ Some(t) => (Some(t), w.noted.insert(space)),
+ None => {
+ q.extend(std::iter::repeat_n(now, n));
+ (None, false)
+ }
+ }
+ };
+ let Some(t) = tripped else {
+ return Ok(true);
+ };
+ tracing::warn!(
+ space = store.space(),
+ reason = ?t,
+ hops,
+ "paused agent to agent messages"
+ );
+ if first {
+ store.append(Draft::note("limits", None, PAUSED_NOTE))?;
+ }
+ Ok(false)
+ }
+}
diff --git a/libs/cua/crates/cua-spaces-ext/src/thread/mod.rs b/libs/cua/crates/cua-spaces-ext/src/thread/mod.rs
index 1647f96c0f..78b0ec7d10 100644
--- a/libs/cua/crates/cua-spaces-ext/src/thread/mod.rs
+++ b/libs/cua/crates/cua-spaces-ext/src/thread/mod.rs
@@ -556,11 +556,25 @@ pub struct ThreadEntry {
/// the complete text. `text` says it in plain words.
#[serde(default, skip_serializing_if = "Option::is_none")]
pub failure: Option<cua_agents::failure::Failure>,
+ /// On a task an agent gave another agent: how many agent-to-agent hops
+ /// it is from the person who started the chain (a person's own tasks
+ /// carry none). The daemon stops a chain at [`crate::persistent::wake::MAX_HOPS`].
+ #[serde(default, skip_serializing_if = "is_zero")]
+ pub hops: u32,
+ /// On the copy of a message that tasks one more agent when it names
+ /// several (`@a @b`, `@everyone`): the entry it copies. Clients draw
+ /// the original only.
+ #[serde(default, skip_serializing_if = "Option::is_none")]
+ pub fanout_of: Option<u64>,
/// Fields of a newer format, kept as they are.
#[serde(flatten)]
pub extra: Map<String, Value>,
}
+fn is_zero(n: &u32) -> bool {
+ *n == 0
+}
+
/// An entry before the store numbers it.
#[derive(Clone, Debug)]
pub struct Draft {
@@ -585,6 +599,8 @@ pub struct Draft {
pub join_request: Option<JoinRequest>,
pub view: Option<ViewContext>,
pub failure: Option<cua_agents::failure::Failure>,
+ pub hops: u32,
+ pub fanout_of: Option<u64>,
}
impl Draft {
@@ -609,6 +625,8 @@ impl Draft {
join_request: None,
view: None,
failure: None,
+ hops: 0,
+ fanout_of: None,
}
}
@@ -984,6 +1002,8 @@ impl ThreadStore {
join_request: d.join_request,
view: d.view,
failure: d.failure,
+ hops: d.hops,
+ fanout_of: d.fanout_of,
extra: Map::new(),
};
self.write_entry(&mut head, &e)?;
@@ -1417,6 +1437,9 @@ pub struct TaskInfo {
/// What the person who gave it was looking at ([`ViewContext`]).
#[serde(skip_serializing_if = "Option::is_none")]
pub view: Option<ViewContext>,
+ /// Agent-to-agent hops from the person who started the chain (0: a person gave it).
+ #[serde(skip_serializing_if = "is_zero")]
+ pub hops: u32,
}
/// What the entries add up to.
@@ -1471,6 +1494,7 @@ impl Fold {
replied: false,
holder: None,
view: e.view.clone(),
+ hops: e.hops,
},
);
}
diff --git a/libs/cua/crates/cua-spaces-ext/tests/agent_addressing.rs b/libs/cua/crates/cua-spaces-ext/tests/agent_addressing.rs
new file mode 100644
index 0000000000..ac994f7e38
--- /dev/null
+++ b/libs/cua/crates/cua-spaces-ext/tests/agent_addressing.rs
@@ -0,0 +1,298 @@
+// SPDX-License-Identifier: FSL-1.1-MIT
+// Copyright (c) 2026 Cua AI, Inc.
+
+//! Talking to agents without typing every @: a message that names several
+//! agents (or `@everyone`) tasks each one the poster may task, a reply to an
+//! agent's message addresses it, and an agent wakes another agent only
+//! through an explicit @, within a hop limit and a per-Space rate limit.
+//! Against the in-process spacesd mock and a temporary cua home: nothing
+//! runs, nothing touches the host.
+
+use cua_spaces::Spaces;
+use cua_spaces::extension::Caller;
+use cua_spaces::mcp::McpServer;
+use cua_spaces_ext::SpacesPersistent as _;
+use cua_spaces_ext::persistent::wake::{PAUSED_NOTE, WakeLimits};
+use cua_spacesd_client::testing::{MockAuth, MockServer};
+use serde_json::{Value, json};
+
+struct Fx {
+ _srv: MockServer,
+ _home: tempfile::TempDir,
+ spaces: Spaces,
+ space: String,
+ mcp: McpServer,
+}
+
+async fn setup() -> Fx {
+ let srv = MockServer::start(MockAuth::default()).await;
+ let home = tempfile::tempdir().unwrap();
+ let spaces = cua_spaces_ext::register(
+ Spaces::builder().home(home.path()),
+ cua_volume::Drive::open_local(home.path()),
+ None,
+ )
+ .build();
+ let info = spaces
+ .add(&format!("http://{}", srv.addr), None, Some("room".into()))
+ .await
+ .unwrap();
+ let mcp = McpServer::new(spaces.clone());
+ Fx {
+ _srv: srv,
+ _home: home,
+ spaces,
+ space: info.id,
+ mcp,
+ }
+}
+
+type Out = Result<Value, (String, String)>;
+
+async fn call_as(fx: &Fx, caller: &Caller, tool: &str, args: Value) -> Out {
+ let out = caller
+ .clone()
+ .scope(Box::pin(fx.mcp.call(tool, args)))
+ .await;
+ cua_spaces::extension::outcome_json(out).map_err(|e| (e.tag().to_string(), e.to_string()))
+}
+
+fn relay(account: &str, name: &str, role: &str) -> Caller {
+ Caller::Relay {
+ account: account.into(),
+ name: Some(name.into()),
+ role: role.into(),
+ }
+}
+
+fn owner() -> Caller {
+ Caller::Owner
+}
+fn member() -> Caller {
+ relay("acct_mia", "Mia", "shared")
+}
+
+fn agent(name: &str, fx: &Fx) -> Caller {
+ Caller::Agent {
+ name: name.into(),
+ space: fx.space.clone(),
+ }
+}
+
+async fn add(fx: &Fx, name: &str) {
+ call_as(
+ fx,
+ &owner(),
+ "agent_add",
+ json!({"space": fx.space, "name": name, "harness": "claude-code",
+ "base_url": "http://127.0.0.1:9/v1"}),
+ )
+ .await
+ .unwrap();
+}
+
+async fn post(fx: &Fx, who: &Caller, text: &str) -> Value {
+ call_as(
+ fx,
+ who,
+ "thread_post",
+ json!({"space": fx.space, "text": text}),
+ )
+ .await
+ .unwrap()["entry"]
+ .clone()
+}
+
+async fn entries(fx: &Fx) -> Vec<Value> {
+ call_as(
+ fx,
+ &owner(),
+ "thread_read",
+ json!({"space": fx.space, "limit": 500}),
+ )
+ .await
+ .unwrap()["entries"]
+ .as_array()
+ .unwrap()
+ .clone()
+}
+
+/// Who got a task, in thread order, with the message's copy marker.
+async fn tasks(fx: &Fx) -> Vec<String> {
+ entries(fx)
+ .await
+ .iter()
+ .filter(|e| !e["task"].is_null())
+ .map(|e| e["task"]["to"].as_str().unwrap().to_string())
+ .collect()
+}
+
+async fn paused_notes(fx: &Fx) -> usize {
+ entries(fx)
+ .await
+ .iter()
+ .filter(|e| e["text"] == PAUSED_NOTE)
+ .count()
+}
+
+#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
+async fn several_mentions_task_each_agent() {
+ let fx = setup().await;
+ add(&fx, "ada").await;
+ add(&fx, "bo").await;
+ add(&fx, "cy").await;
+ let e = post(&fx, &owner(), "@ada @bo please review").await;
+ assert_eq!(e["task"]["to"], "ada");
+ assert_eq!(e["mentions"], json!(["ada", "bo"]));
+ assert_eq!(tasks(&fx).await, ["ada", "bo"]);
+ // The second task sits on a copy that points at the message, so a client draws one message.
+ let all = entries(&fx).await;
+ let copy = all.iter().find(|x| x["task"]["to"] == "bo").unwrap();
+ assert_eq!(copy["fanout_of"], e["seq"]);
+ assert_eq!(copy["text"], e["text"]);
+ assert!(e.get("fanout_of").is_none());
+ // One mention is still one task, and a repeated mention is not two.
+ post(&fx, &owner(), "@cy @cy go").await;
+ assert_eq!(tasks(&fx).await, ["ada", "bo", "cy"]);
+}
+
+#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
+async fn everyone_tasks_each_agent_the_poster_may_task() {
+ let fx = setup().await;
+ add(&fx, "ada").await;
+ add(&fx, "bo").await;
+ call_as(
+ &fx,
+ &owner(),
+ "agent_set_rights",
+ json!({"name": "bo", "task": "owner"}),
+ )
+ .await
+ .unwrap();
+ let before = entries(&fx).await.len();
+ // A member may task ada only: bo is skipped without a note.
+ post(&fx, &member(), "@everyone status?").await;
+ assert_eq!(tasks(&fx).await, ["ada"]);
+ assert_eq!(entries(&fx).await.len(), before + 1);
+ // The owner tasks both.
+ post(&fx, &owner(), "@everyone status?").await;
+ assert_eq!(tasks(&fx).await, ["ada", "ada", "bo"]);
+ // Naming an agent the poster may not task still says why.
+ post(&fx, &member(), "@bo status?").await;
+ let all = entries(&fx).await;
+ assert!(
+ all.last().unwrap()["text"]
+ .as_str()
+ .unwrap()
+ .contains("can't give bo tasks")
+ );
+}
+
+#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
+async fn a_reply_to_an_agent_addresses_it() {
+ let fx = setup().await;
+ add(&fx, "ada").await;
+ add(&fx, "bo").await;
+ let said = post(&fx, &agent("ada", &fx), "I found two failures").await;
+ assert!(said["task"].is_null());
+ let r = call_as(
+ &fx,
+ &owner(),
+ "thread_post",
+ json!({"space": fx.space, "text": "fix the first", "reply_to": said["seq"]}),
+ )
+ .await
+ .unwrap();
+ assert_eq!(r["entry"]["task"]["to"], "ada");
+ // A plain message wakes nobody; an explicit mention wins over the reply.
+ let plain = post(&fx, &owner(), "thanks all").await;
+ assert!(plain["task"].is_null());
+ let r = call_as(
+ &fx,
+ &owner(),
+ "thread_post",
+ json!({"space": fx.space, "text": "@bo and you?", "reply_to": said["seq"]}),
+ )
+ .await
+ .unwrap();
+ assert_eq!(r["entry"]["task"]["to"], "bo");
+ assert_eq!(tasks(&fx).await, ["ada", "bo"]);
+}
+
+#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
+async fn an_agent_wakes_only_through_an_explicit_mention_and_never_itself() {
+ let fx = setup().await;
+ add(&fx, "ada").await;
+ add(&fx, "bo").await;
+ let ada = agent("ada", &fx);
+ assert!(post(&fx, &ada, "done").await["task"].is_null());
+ // `@everyone` from an agent wakes nobody.
+ assert!(post(&fx, &ada, "@everyone look").await["task"].is_null());
+ // Self mention is guarded; the other agent is woken.
+ let e = post(&fx, &ada, "@ada @bo take a look").await;
+ assert_eq!(e["task"]["to"], "bo");
+ assert_eq!(e["hops"], 1);
+ assert_eq!(tasks(&fx).await, ["bo"]);
+}
+
+#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
+async fn a_chain_stops_after_three_hops_and_a_person_resets_it() {
+ let fx = setup().await;
+ add(&fx, "ada").await;
+ add(&fx, "bo").await;
+ let (ada, bo) = (agent("ada", &fx), agent("bo", &fx));
+ let t = post(&fx, &owner(), "@ada start").await;
+ assert!(t.get("hops").is_none());
+ assert_eq!(post(&fx, &ada, "@bo one").await["hops"], 1);
+ assert_eq!(post(&fx, &bo, "@ada two").await["hops"], 2);
+ assert_eq!(post(&fx, &ada, "@bo three").await["hops"], 3);
+ assert_eq!(paused_notes(&fx).await, 0);
+ // The fourth hop is posted but wakes nobody; the thread says so once.
+ let over = post(&fx, &bo, "@ada four").await;
+ assert!(over["task"].is_null());
+ assert_eq!(over["mentions"], json!(["ada"]));
+ assert_eq!(paused_notes(&fx).await, 1);
+ assert!(post(&fx, &bo, "@ada five").await["task"].is_null());
+ assert_eq!(paused_notes(&fx).await, 1, "one note per episode");
+ assert_eq!(tasks(&fx).await.len(), 4);
+ // A person's message starts the chain over, and a later trip says so again.
+ let again = post(&fx, &owner(), "@ada carry on").await;
+ assert_eq!(again["task"]["to"], "ada");
+ assert_eq!(post(&fx, &ada, "@bo one").await["hops"], 1);
+ assert_eq!(post(&fx, &bo, "@ada two").await["hops"], 2);
+ assert_eq!(post(&fx, &ada, "@bo three").await["hops"], 3);
+ assert!(post(&fx, &bo, "@ada four").await["task"].is_null());
+ assert_eq!(paused_notes(&fx).await, 2);
+}
+
+#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
+async fn a_space_allows_a_limited_number_of_agent_wakes_a_minute() {
+ let fx = setup().await;
+ add(&fx, "ada").await;
+ add(&fx, "bo").await;
+ let ada = agent("ada", &fx);
+ fx.spaces
+ .persistent()
+ .set_wake_limits(WakeLimits {
+ max_hops: 100,
+ per_minute: 3,
+ })
+ .await;
+ for i in 0..3 {
+ assert_eq!(
+ post(&fx, &ada, &format!("@bo {i}")).await["task"]["to"],
+ "bo"
+ );
+ }
+ assert!(post(&fx, &ada, "@bo 3").await["task"].is_null());
+ assert!(post(&fx, &ada, "@bo 4").await["task"].is_null());
+ assert_eq!(paused_notes(&fx).await, 1);
+ // A person is not rate limited here.
+ assert_eq!(post(&fx, &owner(), "@bo hello").await["task"]["to"], "bo");
+}
+
+#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
+async fn the_default_limits_are_three_hops_and_twenty_wakes_a_minute() {
+ let l = WakeLimits::default();
+ assert_eq!((l.max_hops, l.per_minute), (3, 20));
+}
diff --git a/libs/cua/spaces-contract/manifest.json b/libs/cua/spaces-contract/manifest.json
index 8ee6fcaf29..520a316fc5 100644
--- a/libs/cua/spaces-contract/manifest.json
+++ b/libs/cua/spaces-contract/manifest.json
@@ -3220,7 +3220,7 @@
"sdk_symbol": "space.thread().read(after:limit:)",
"rust_symbol": "thread::Thread::read",
"notes": [],
- "result": "JSON: `space`, `me` (your author object), `role` (yours here: `owner`, `admin`, `member`, `guest` (reads only) or `agent`), `entries` (oldest first; each `v`, `seq`, `id`, `ts_ms`, `author` {`kind`, `id`, `name`}, `kind`, `text`, `mentions`, `reply_to`, `task`, `attachments`, `approval`, `answer`, `update`, and when set `imported`, `import`, `task_seq` (the task a system note is about), `view` (what the person was looking at as they posted: {`kind` `desktop` or `window`, `app`, `title`, `window_id`})), `cursor` (pass it as `after`), `caught_up`, `has_more_before`, `read_seq` (your read position), `unread` (entries after it, not yours) and `tasks` (open tasks: `seq`, `to`, `state`, `session`, `lease_until_ms`, `author`, `ts_ms`, `text`, `view`). `live`: {`key`, `agents`: [{`agent`, `stage`, `since_ms`, `text`}]}, what each agent member with a task on its way is doing now (`starting`, `installing`, `thinking`, `replying`, `using <tool>`; `since_ms`: when its oldest open task was given; `text`: what it has said so far this turn, the whole text each time and only while it streams, replaced by its reply when the turn ends); pass `key` back as `live_after` with `follow_ms` to be woken when it changes. With `with`: `with` and only your DM's entries, its own `read_seq` and `unread`, and no `tasks`.",
+ "result": "JSON: `space`, `me` (your author object), `role` (yours here: `owner`, `admin`, `member`, `guest` (reads only) or `agent`), `entries` (oldest first; each `v`, `seq`, `id`, `ts_ms`, `author` {`kind`, `id`, `name`}, `kind`, `text`, `mentions`, `reply_to`, `task`, `attachments`, `approval`, `answer`, `update`, and when set `imported`, `import`, `task_seq` (the task a system note is about), `fanout_of` (on the copy of a message that tasks one more agent it names: the entry it copies), `hops` (on a task an agent gave another agent: agent to agent hops from a person's message), `view` (what the person was looking at as they posted: {`kind` `desktop` or `window`, `app`, `title`, `window_id`})), `cursor` (pass it as `after`), `caught_up`, `has_more_before`, `read_seq` (your read position), `unread` (entries after it, not yours) and `tasks` (open tasks: `seq`, `to`, `state`, `session`, `lease_until_ms`, `author`, `ts_ms`, `text`, `view`). `live`: {`key`, `agents`: [{`agent`, `stage`, `since_ms`, `text`}]}, what each agent member with a task on its way is doing now (`starting`, `installing`, `thinking`, `replying`, `using <tool>`; `since_ms`: when its oldest open task was given; `text`: what it has said so far this turn, the whole text each time and only while it streams, replaced by its reply when the turn ends); pass `key` back as `live_after` with `follow_ms` to be woken when it changes. With `with`: `with` and only your DM's entries, its own `read_seq` and `unread`, and no `tasks`.",
"errors": [],
"input_schema": {
"properties": {
@@ -3275,7 +3275,7 @@
"name": "thread_post",
"category": "thread",
"description": "Post to a Space's thread.",
- "instructions": "Posts as you (the daemon stamps the author; it is never an argument). `@name` of an agent member of this Space makes the message a task for it: the daemon wakes the agent (restoring its home if it was asleep), delivers the message as its next turn, and posts its answer as a reply when the turn ends. An agent with several sessions gives it to its lowest free session (`to_session` picks one); a busy agent gets it after its current turn; a paused one keeps it queued. Text and attachment names that look like a secret are refused: secrets belong in the Keyvault. `view` says what the person is looking at in the Space as they post (its desktop, or a window by app, title and window_id); it is stored with the entry, so an agent reads which window \"this\" means.",
+ "instructions": "Posts as you (the daemon stamps the author; it is never an argument). `@name` of an agent member of this Space makes the message a task for it: the daemon wakes the agent (restoring its home if it was asleep), delivers the message as its next turn, and posts its answer as a reply when the turn ends. An agent with several sessions gives it to its lowest free session (`to_session` picks one); a busy agent gets it after its current turn; a paused one keeps it queued. Naming several agents (`@ada @bo`) gives each one the task (the second and later on a copy of the message, `fanout_of` the first), and `@everyone` names every agent member you may task. A person's reply (`reply_to`) to an agent member's message with no @mention addresses that agent. An agent's post wakes another agent only through an explicit `@name` (never `@everyone` or a reply): a chain stops after 3 agent to agent hops from a person's message, and a Space allows 20 agent to agent wakes a minute; past a limit the message is posted but wakes nobody, and the thread says \"Paused agent to agent messages for a moment\" once. Text and attachment names that look like a secret are refused: secrets belong in the Keyvault. `view` says what the person is looking at in the Space as they post (its desktop, or a window by app, title and window_id); it is stored with the entry, so an agent reads which window \"this\" means.",
"platforms": [
"macos",
"windows",