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.

perf(spaces): fill in the Agents page as Spaces answer, bound slow machines (#6177)

ddupont886179f87f26
diff --git a/apps/cua-spaces-desktop/src/bridge/machines.ts b/apps/cua-spaces-desktop/src/bridge/machines.ts
index 5f0b7b8b50..0ab2bf13e9 100644
--- a/apps/cua-spaces-desktop/src/bridge/machines.ts
+++ b/apps/cua-spaces-desktop/src/bridge/machines.ts
@@ -112,7 +112,12 @@ export function machinesMethods({ model }: BridgeContext): Handlers {
"machines.list": async () => {
if (model.host.state === null && model.servicesIn) await model.host.refresh();
// Who the relay sees connected now, not at the last visit; not before the services are in.
- if (model.servicesIn) await model.devices.refreshIfStale();
+ // With an earlier read the page is answered from it now and the relay's answer follows
+ // (`machines.changed`): a slow relay never holds the Machines page empty.
+ if (model.servicesIn) {
+ if (model.devices.snapshot === null) await model.devices.refreshIfStale();
+ else void model.devices.refreshIfStale().catch(() => undefined);
+ }
return machinesState(model);
},
// Renames one of your machines on the relay; `this-mac` is this
diff --git a/apps/cua-spaces-macos/Sources/CuaSpacesMacKit/WebHost/WebUIBridge.swift b/apps/cua-spaces-macos/Sources/CuaSpacesMacKit/WebHost/WebUIBridge.swift
index 36e14cf2b7..277bb31385 100644
--- a/apps/cua-spaces-macos/Sources/CuaSpacesMacKit/WebHost/WebUIBridge.swift
+++ b/apps/cua-spaces-macos/Sources/CuaSpacesMacKit/WebHost/WebUIBridge.swift
@@ -332,7 +332,16 @@ final class WebUIBridge: NSObject, WKScriptMessageHandlerWithReply {
// Who the relay sees connected now (a host that rejoined after
// sign-in is online), not at the last Devices page visit; not
// before the live services are in (answer from memory then).
- if model.servicesIn { await model.devices.refreshIfStale() }
+ // With an earlier read the page is answered from it now and the
+ // relay's answer follows (`machines.changed`): a slow relay never
+ // holds the Machines page empty.
+ if model.servicesIn {
+ if model.devices.snapshot == nil {
+ await model.devices.refreshIfStale()
+ } else {
+ Task { @MainActor [model] in await model.devices.refreshIfStale() }
+ }
+ }
return machines()
case "host.status":
if model.host.state == nil, model.servicesIn { await model.host.refresh() }
diff --git a/apps/cua-spaces-web/src/__tests__/agents-populate-timing.test.tsx b/apps/cua-spaces-web/src/__tests__/agents-populate-timing.test.tsx
new file mode 100644
index 0000000000..713cc61274
--- /dev/null
+++ b/apps/cua-spaces-web/src/__tests__/agents-populate-timing.test.tsx
@@ -0,0 +1,82 @@
+// SPDX-License-Identifier: FSL-1.1-MIT
+// Copyright (c) 2026 Cua AI, Inc.
+
+// How long the Agents page takes to fill in on an account like a busy one
+// (CUA-2849): every Space's thread answers after the time its machine takes,
+// one is far slower, one is off. Rows must show as their Space answers, and
+// the slow one must hold up nothing. The numbers are on the console; the
+// thresholds are generous, they fail on a page that waits for the slowest
+// Space (before: the first row came when the slowest answered).
+
+import { cleanup } from "@testing-library/react";
+import { afterEach, beforeEach, describe, expect, it } from "vitest";
+
+import { mountApp, stubBrowserApis } from "./app-harness";
+
+afterEach(cleanup);
+beforeEach(() => localStorage.clear());
+stubBrowserApis();
+
+const q = (s: string) => document.querySelector<HTMLElement>(s);
+const CODEX = "acct_ada/codex/codex";
+const HERMES = "acct_ada/hermes/hermes";
+const sleep = (ms: number) => new Promise<void>((r) => setTimeout(r, ms));
+/** What each Space's machine takes to answer a thread call (ms); `off` is a machine that is off. */
+const TAKES: Record<string, number | "off"> = {
+ "local:design-review": 20,
+ "local:agent-sandbox": 20,
+ "relay:mac-mini/release-checks": 300,
+ "relay:mac-mini/qa-windows": 300,
+ "relay:linux-box/ubuntu-build": 600,
+ "relay:linux-box/windows-legacy": 600,
+ "relay:space-sam-qa-shared": 1500,
+ "relay:space-priya-checkout": 8000,
+ "relay:space-qa-regression": "off",
+};
+
+async function visit(label: string): Promise<Record<string, number | null>> {
+ {
+ const t0 = Date.now();
+ // The host's own answer, after the time that Space's machine takes.
+ const host: { demo?: { call(op: never, args: never): Promise<unknown> } } = {};
+ const app = await mountApp("/agents", {
+ failsCreates: false,
+ listsGhost: false,
+ intercept: (op, args) => {
+ const space = (args as { spaceId?: string }).spaceId;
+ if (!op.startsWith("thread.") || !space || !(space in TAKES)) return undefined;
+ const t = TAKES[space]!;
+ if (t === "off") return Promise.reject(new Error("machine is offline"));
+ return sleep(t).then(() => host.demo!.call(op as never, args as never));
+ },
+ });
+ host.demo = app.demo;
+ const seen: Record<string, number> = {};
+ const settled = () => (q("[data-agents-loading]") ? null : Date.now() - t0);
+ let done: number | null = null;
+ while (Date.now() - t0 < 12_000) {
+ for (const [name, sel] of [["codex row", `[data-chat='${CODEX}']`], ["hermes row", `[data-chat='${HERMES}']`]] as const) if (!(name in seen) && q(sel)) seen[name] = Date.now() - t0;
+ if ("codex row" in seen && "hermes row" in seen && (done = settled()) !== null && seen["codex row"] !== undefined) break;
+ await sleep(10);
+ }
+ console.log(`agents page timeline, ${label} (ms from open): ${JSON.stringify({ ...seen, checkingGone: done })}`);
+ return { ...seen, checkingGone: done };
+ }
+}
+
+describe("the Agents page on a busy account", () => {
+ it("shows rows as their Spaces answer, not when the slowest one does", async () => {
+ const t = await visit("cold");
+ expect(t["codex row"], "first row").toBeDefined();
+ expect(t["codex row"]!).toBeLessThan(1500);
+ expect(t["hermes row"]!).toBeLessThan(2500);
+ }, 30_000);
+
+ it("the next visit draws from the last one at once, before the slow Spaces answer", async () => {
+ await visit("first visit");
+ cleanup();
+ const t = await visit("warm");
+ expect(t["codex row"]!).toBeLessThan(400);
+ expect(t["hermes row"]!).toBeLessThan(400);
+ }, 60_000);
+});
diff --git a/apps/cua-spaces-web/src/__tests__/agents-populate.test.tsx b/apps/cua-spaces-web/src/__tests__/agents-populate.test.tsx
new file mode 100644
index 0000000000..828ab5cd2b
--- /dev/null
+++ b/apps/cua-spaces-web/src/__tests__/agents-populate.test.tsx
@@ -0,0 +1,100 @@
+// SPDX-License-Identifier: FSL-1.1-MIT
+// Copyright (c) 2026 Cua AI, Inc.
+
+// The Agents page fills in at once (CUA-2849): from the last visit's list
+// while the Spaces are read again, row by row as each Space answers, with a
+// Space that never answers holding up nothing; and a long DM opens on its
+// newest messages with the older ones a click away.
+
+import { act, cleanup, fireEvent, waitFor } from "@testing-library/react";
+import { afterEach, beforeEach, describe, expect, it } from "vitest";
+
+import { mountApp, stubBrowserApis } from "./app-harness";
+
+afterEach(cleanup);
+beforeEach(() => localStorage.clear());
+stubBrowserApis();
+
+const q = (s: string) => document.querySelector<HTMLElement>(s);
+const qa = (s: string) => [...document.querySelectorAll<HTMLElement>(s)];
+const HERMES = "acct_ada/hermes/hermes";
+const CODEX = "acct_ada/codex/codex";
+const UBUNTU = "relay:linux-box/ubuntu-build";
+const never = () => new Promise<never>(() => undefined);
+const found = (s: string, timeout = 5000) =>
+ waitFor(
+ () => {
+ const el = q(s);
+ expect(el).not.toBeNull();
+ return el!;
+ },
+ { timeout },
+ );
+
+describe("the Agents page while Spaces are slow", () => {
+ it("draws the Spaces that answered and says it is still checking the one that has not", async () => {
+ const t0 = Date.now();
+ await mountApp("/agents", {
+ failsCreates: false,
+ listsGhost: false,
+ intercept: (op, args) => (op.startsWith("thread.") && (args as { spaceId?: string }).spaceId === UBUNTU ? never() : undefined),
+ });
+ // Codex lives in design-review: its row and Hermes's (also in release-checks) do not wait for ubuntu-build.
+ await found(`[data-chat='${CODEX}']`);
+ await found(`[data-chat='${HERMES}']`);
+ expect(Date.now() - t0).toBeLessThan(3000);
+ const loading = await found("[data-agents-loading]");
+ expect(loading.textContent).toBe("Checking 1 Space");
+ // Hermes is only in the Spaces that answered.
+ await waitFor(() => expect(q(`[data-chat='${HERMES}']`)).not.toBeNull());
+ });
+
+ it("draws the last visit's list before any Space has answered", async () => {
+ const first = await mountApp("/agents", { failsCreates: false, listsGhost: false });
+ await found(`[data-chat='${CODEX}']`);
+ // Let the pass finish and the list be kept.
+ await waitFor(() => expect(localStorage.getItem("cua.agents.lastKnown.v1")).toContain("design-review"));
+ expect(first.router).toBeDefined();
+ cleanup();
+ // The next visit: not one thread call is answered, and the rows are there.
+ await mountApp("/agents", { failsCreates: false, listsGhost: false, intercept: (op) => (op.startsWith("thread.") ? never() : undefined) });
+ await found(`[data-chat='${CODEX}']`, 2000);
+ expect(q(`[data-chat='${CODEX}'] [data-chat-line]`)?.textContent).toBe("Waiting for you in design-review");
+ // And it says it is checking, quietly.
+ await found("[data-agents-loading]");
+ });
+
+ it("a DM opens on the newest messages; earlier ones are a click away", async () => {
+ const { router, demo } = await mountApp("/", { failsCreates: false, listsGhost: false });
+ for (let i = 1; i <= 70; i++) await demo.call("thread.post", { spaceId: UBUNTU, text: `@hermes message ${i}` });
+ await act(async () => {
+ await router.navigate({ to: "/agents", search: { agent: HERMES, space: UBUNTU } });
+ });
+ await found("[data-dm-log] > div > *");
+ // The log's rows (the button above them is not one).
+ const shown = () => qa("[data-dm-log] > div > *").filter((el) => !el.hasAttribute("data-dm-older")).length;
+ await waitFor(() => expect(q("[data-dm-older]")).not.toBeNull(), { timeout: 5000 });
+ const first = shown();
+ expect(first).toBeGreaterThan(5);
+ expect(first).toBeLessThan(45);
+ // 70 tasks and their replies are 140 entries: one page of each Space is the newest 40.
+ expect(q("[data-dm-log]")?.textContent).not.toContain("message 1 ");
+ await act(async () => {
+ fireEvent.click(q("[data-dm-older]")!);
+ await new Promise((r) => setTimeout(r, 50));
+ });
+ await waitFor(() => expect(shown()).toBeGreaterThan(first));
+ });
+
+ it("one Space of an agent's DM never answering does not hold the other's messages", async () => {
+ await mountApp(`/agents?agent=${encodeURIComponent(HERMES)}`, {
+ failsCreates: false,
+ listsGhost: false,
+ intercept: (op, args) => (op === "thread.read" && (args as { spaceId?: string; with?: string }).spaceId === UBUNTU && (args as { with?: string }).with ? never() : undefined),
+ });
+ // release-checks' messages show though ubuntu-build's DM is still loading.
+ await found(`[data-dm='${HERMES}'][data-dm-space='all']`);
+ await waitFor(() => expect(q("[data-dm-log]")?.textContent?.length ?? 0).toBeGreaterThan(0), { timeout: 3000 });
+ expect(q("[data-dm-empty]")).toBeNull();
+ });
+});
diff --git a/apps/cua-spaces-web/src/bridge/adapters/demo.ts b/apps/cua-spaces-web/src/bridge/adapters/demo.ts
index cf9858212c..c2bceccee7 100644
--- a/apps/cua-spaces-web/src/bridge/adapters/demo.ts
+++ b/apps/cua-spaces-web/src/bridge/adapters/demo.ts
@@ -38,7 +38,7 @@ import {
} from "./demo-data";
import { demoNewSpaceState, newSpaceDemoHandlers, type DemoClouds, type DemoNewSpaceState } from "./demo/new-space";
import { demoShareHandlers } from "./demo/share";
-import { demoThreadHandlers } from "./demo/thread";
+import { DEMO_THREAD_SPACE, demoThreadHandlers, hangingSpace, seedLongDm } from "./demo/thread";
import { demoAgentDetailHandlers } from "./demo/agent-detail";
import { demoAgentKeysHandlers, demoKeyStore, type DemoKeyStore } from "./demo/agent-keys";
import { demoKeyvaultManageHandlers, demoKeyvaultManageState, withDemoCopies, type DemoKeyvaultManageState } from "./demo/keyvault-manage";
@@ -147,6 +147,10 @@ export interface DemoOptions {
threadAuthFailed?: boolean;
/** `?demo=thread-paused`: agents wake each other until the daemon pauses agent to agent messages (CUA-2757). */
threadPaused?: boolean;
+ /** `?demo=thread-slow`: the machine of the demo's thread Space does not answer. */
+ threadSlow?: boolean;
+ /** `?demo=thread-long`: this many more tasks for Hermes in the demo's thread Space. */
+ threadLongDm?: number;
/** `?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`). */
@@ -253,6 +257,8 @@ export function demoOptionsFromSearch(search: string): DemoOptions {
threadAuthFailed: flags.has("thread-auth-failed"),
threadStranger: flags.has("thread-stranger"),
threadPaused: flags.has("thread-paused"),
+ threadSlow: flags.has("thread-slow"),
+ ...(flags.has("thread-long") ? { threadLongDm: 60 } : {}),
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 } : {}),
@@ -932,11 +938,15 @@ 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, paused: options.threadPaused ?? false,
+ ...((): ReturnType<typeof demoThreadHandlers> => {
+ const h = 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,
- }),
+ });
+ if (options.threadLongDm && !options.noThread) seedLongDm(h, options.threadLongDm);
+ return options.threadSlow ? hangingSpace(h, DEMO_THREAD_SPACE) : h;
+ })(),
"nudges.pending": () => risky.filter((r) => r.expiresMs > now()).map((r) => ({ ...r })),
"nudges.answer": ({ id }) => {
risky = risky.filter((r) => r.id !== id);
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 01ee8b2679..29e1b0d54c 100644
--- a/apps/cua-spaces-web/src/bridge/adapters/demo/thread.ts
+++ b/apps/cua-spaces-web/src/bridge/adapters/demo/thread.ts
@@ -892,4 +892,22 @@ export function demoThreadHandlers({
};
}
+/**
+ * `?demo=thread-slow`: the machine that has `space` does not answer, so
+ * every thread call for it waits (the Agents page keeps drawing the other
+ * Spaces and says it is still checking this one).
+ */
+export function hangingSpace(handlers: DemoHandlers<ThreadOpName>, space: string): DemoHandlers<ThreadOpName> {
+ return Object.fromEntries(
+ Object.entries(handlers).map(([op, h]) => [op, (args: { spaceId?: string }) => (args.spaceId === space ? new Promise<never>(() => undefined) : (h as (a: unknown) => unknown)(args))]),
+ ) as unknown as DemoHandlers<ThreadOpName>;
+}
+
+/** `?demo=thread-long`: `count` more tasks for Hermes in the demo's Space, so its DM is long (the agents answer a few steps later). */
+export function seedLongDm(handlers: DemoHandlers<ThreadOpName>, count: number): void {
+ void (async () => {
+ for (let i = 1; i <= count; i++) await handlers["thread.post"]({ spaceId: DEMO_THREAD_SPACE, text: `@hermes check item ${i} of the release list` } as never);
+ })();
+}
+
const label = (agent: string) => (agent === "claude" ? "Claude Code" : agent.charAt(0).toUpperCase() + agent.slice(1));
diff --git a/apps/cua-spaces-web/src/bridge/agents-dm.ts b/apps/cua-spaces-web/src/bridge/agents-dm.ts
index 7f3666f8e4..ac7a1dee49 100644
--- a/apps/cua-spaces-web/src/bridge/agents-dm.ts
+++ b/apps/cua-spaces-web/src/bridge/agents-dm.ts
@@ -16,10 +16,10 @@
* answers approvals.
*/
-import { useCallback, useEffect, useRef, useState } from "react";
+import { useCallback, useEffect, useMemo, useRef, useState } from "react";
import type { CoreClient } from "./core";
-import { chatsPollMs, jittered, mapLimit, MissCache } from "../lib/poll-plan";
+import { chatsPollMs, forEachLimit, jittered, MissCache } from "../lib/poll-plan";
import { useBridge, useSpaces } from "./hooks";
import type { Space } from "./contracts/spaces";
import { foldThread, readSeqFrom, type ThreadItem } from "./thread";
@@ -176,62 +176,126 @@ interface AgentListRow {
/** The Agents tab's base poll; it slows as the account's Spaces grow (`chatsPollMs`). */
export const CHATS_POLL_MS = 5_000;
/** Spaces' threads read at once, at most. */
-const CHATS_PARALLEL = 8;
+const CHATS_PARALLEL = 16;
+/** A Space that has not answered in this long stops holding its read slot (it keeps going, and fills in when it answers). */
+export const CHATS_SLOT_MS = 4_000;
/** How long a Space with no thread is left alone. */
const MISS_TTL_MS = 60_000;
+/** The newest messages read first in each Space; older ones come on request. */
+export const DM_FIRST_PAGE = 40;
+/** The list as of the last visit, drawn at once on the next one. */
+const CACHE_KEY = "cua.agents.lastKnown.v1";
+/** Answers the page redraws on at most this often while a pass fills in. */
+const FLUSH_MS = 60;
export interface AgentChats {
- /** null while the first read is under way. */
+ /** null while there is nothing to show yet (no earlier list, no run of this device's, no Space has answered). */
chats: AgentChat[] | null;
/** Spaces with a thread (where an agent can be added). */
spaces: Space[];
/** Your author id, as the threads say it. */
me: string | null;
+ /** Spaces still to answer in this pass (the list draws what is known meanwhile). */
+ loading: number;
/** Read again now (after adding or removing an agent). */
refresh(): void;
}
+/** What one Space answered: its members with their DM summaries, and your role there. */
+export interface SpaceRead {
+ role: ThreadRole | null;
+ members: AgentMember[];
+ me: string | null;
+}
+
+function loadLastKnown(): Record<string, SpaceRead> {
+ try {
+ const raw = typeof localStorage === "undefined" ? null : localStorage.getItem(CACHE_KEY);
+ const v = raw ? (JSON.parse(raw) as unknown) : null;
+ return v && typeof v === "object" && !Array.isArray(v) ? (v as Record<string, SpaceRead>) : {};
+ } catch {
+ return {};
+ }
+}
+
+function saveLastKnown(reads: ReadonlyMap<string, SpaceRead>): void {
+ try {
+ localStorage.setItem(CACHE_KEY, JSON.stringify(Object.fromEntries(reads)));
+ } catch {
+ // No storage (a private window, a full disk): the list just draws after its first answers.
+ }
+}
+
/** Every agent in every Space you can see, as the Agents tab's list. */
export function useAgentChats(attempts: readonly ChatAttempt[] = []): AgentChats {
const { data, core } = useBridge();
const { data: spaces } = useSpaces();
- const [read, setRead] = useState<{ space: Space; role: ThreadRole | null; members: AgentMember[] }[] | null>(null);
- const [withThread, setWithThread] = useState<Space[]>([]);
- const [me, setMe] = useState<string | null>(null);
+ // What each Space last said: the last visit's answers first, then each Space's own as it comes. A Space
+ // that does not answer keeps its last answer (a machine that is off still lists its agents).
+ const reads = useRef<Map<string, SpaceRead> | null>(null);
+ reads.current ??= new Map(Object.entries(loadLastKnown()));
+ const [version, setVersion] = useState(0);
+ const [settled, setSettled] = useState(false);
+ const [pending, setPending] = useState(0);
const [round, setRound] = useState(0);
const list = (spaces ?? []).filter((s) => !s.id.startsWith("pending:"));
const ids = list.map((s) => s.id).join("\n");
// Not asked again for a minute: a Space with no thread (a stopped machine, an old daemon) stays that way.
const misses = useRef(new MissCache(MISS_TTL_MS));
+ const inflight = useRef(new Set<string>());
useEffect(() => {
if (!data || spaces === undefined) return;
let alive = true;
let timer: ReturnType<typeof setTimeout> | undefined;
- misses.current.prune(new Set(list.map((s) => s.id)));
- const read = async () => {
- const asked = list.filter((s) => !misses.current.has(s.id));
- const got = await mapLimit(asked, CHATS_PARALLEL, async (space) => {
- try {
- const [{ members }, page] = await Promise.all([data.call("thread.members", { spaceId: space.id, overview: true }), data.call("thread.read", { spaceId: space.id, limit: 1 })]);
- return { space, role: page.role, members, me: page.me };
- } catch (e) {
- // No thread there (an old daemon, a stopped machine): not in the list, and not asked again for a while.
- if (isMissingThreadTool(e)) misses.current.add(space.id);
- else console.debug("agents: couldn't read", space.id, e);
- return null;
+ let flushTimer: ReturnType<typeof setTimeout> | undefined;
+ const known = new Set(list.map((s) => s.id));
+ misses.current.prune(known);
+ for (const id of [...reads.current!.keys()]) if (!known.has(id)) reads.current!.delete(id);
+ // A pass's answers redraw the page together, not one by one.
+ const flush = () => {
+ if (flushTimer !== undefined) return;
+ flushTimer = setTimeout(() => {
+ flushTimer = undefined;
+ if (!alive) return;
+ saveLastKnown(reads.current!);
+ setVersion((v) => v + 1);
+ }, FLUSH_MS);
+ };
+ const readOne = async (space: Space) => {
+ inflight.current.add(space.id);
+ try {
+ const [{ members }, page] = await Promise.all([data.call("thread.members", { spaceId: space.id, overview: true }), data.call("thread.read", { spaceId: space.id, limit: 1 })]);
+ reads.current!.set(space.id, { role: page.role, members, me: page.me });
+ } catch (e) {
+ // No thread there (an old daemon): not in the list, and not asked again for a while.
+ if (isMissingThreadTool(e)) {
+ misses.current.add(space.id);
+ reads.current!.delete(space.id);
+ } else console.debug("agents: couldn't read", space.id, e);
+ } finally {
+ inflight.current.delete(space.id);
+ if (alive) {
+ setPending((n) => Math.max(0, n - 1));
+ flush();
}
- });
- if (!alive) return;
- const ok = got.filter((g): g is NonNullable<typeof g> => g !== null);
- setWithThread(ok.map((g) => g.space));
- setMe(ok.find((g) => g.me)?.me ?? null);
- setRead(ok);
+ }
+ };
+ const pass = async () => {
+ const asked = list.filter((s) => !misses.current.has(s.id) && !inflight.current.has(s.id));
+ setPending(asked.length);
+ // Spaces that answered last time go first: the slow ones are last in line, never in front.
+ asked.sort((x, y) => Number(reads.current!.has(y.id)) - Number(reads.current!.has(x.id)));
+ await forEachLimit(asked, CHATS_PARALLEL, CHATS_SLOT_MS, readOne);
+ if (alive) {
+ setSettled(true);
+ flush();
+ }
};
- // One read at a time, the next after the last one ends: slower as the
+ // One pass at a time, the next after the last one's slots end: slower as the
// account grows (`chatsPollMs`), spread so pages don't ask together, and
// paused while the page is hidden (it reads at once on coming back).
const loop = async () => {
- if (visible()) await read();
+ if (visible()) await pass();
if (alive) timer = setTimeout(() => void loop(), jittered(chatsPollMs(list.length)));
};
const onVisible = () => {
@@ -244,14 +308,27 @@ export function useAgentChats(attempts: readonly ChatAttempt[] = []): AgentChats
return () => {
alive = false;
clearTimeout(timer);
+ clearTimeout(flushTimer);
document.removeEventListener("visibilitychange", onVisible);
};
// `list` follows `ids`.
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [data, ids, round, spaces === undefined]);
- // One list, with this device's unfinished runs (the core's order and words).
- const chats = read === null ? null : mergeChats(core, read, attempts);
- return { chats, spaces: withThread, me, refresh: useCallback(() => setRound((r) => r + 1), []) };
+ // One list, with this device's unfinished runs (the core's order and words), made again only when an
+ // answer, the Spaces or the runs change.
+ const merged = useMemo(() => {
+ const perSpace = list.flatMap((space) => {
+ const r = reads.current!.get(space.id);
+ return r ? [{ space, role: r.role, members: r.members }] : [];
+ });
+ return { perSpace, chats: spaces === undefined ? [] : mergeChats(core, perSpace, attempts) };
+ // `list` follows `spaces`; `reads` is read when `version` says it changed.
+ // eslint-disable-next-line react-hooks/exhaustive-deps
+ }, [version, spaces, attempts, core]);
+ const chats = merged.chats.length === 0 && !settled ? null : merged.chats;
+ const withThread = useMemo(() => merged.perSpace.map((p) => p.space), [merged]);
+ const me = useMemo(() => [...reads.current!.values()].find((r) => r.me)?.me ?? null, [merged]);
+ return { chats, spaces: withThread, me, loading: pending, refresh: useCallback(() => setRound((r) => r + 1), []) };
}
/** One DM item, with the Space it came from. */
@@ -271,6 +348,12 @@ export interface AgentDm {
entries: Record<string, ThreadEntry[]>;
/** Your author id, when known. */
me: string | null;
+ /** Spaces whose first page has not come yet (the others' messages show meanwhile). */
+ pending: number;
+ /** Older messages exist in some Space than are shown. */
+ hasMore: boolean;
+ /** Reads the page before the oldest shown, in each Space that has more. */
+ loadOlder(): Promise<void>;
/** Sends `text` to the agent in `spaceId`: an @mention task in that Space's thread. */
send(spaceId: string, text: string): Promise<void>;
answer(spaceId: string, approval: number, approve: boolean): Promise<void>;
@@ -291,6 +374,8 @@ export function useAgentDm(chat: AgentChat | null, only: string | null): AgentDm
const [error, setError] = useState<string | null>(null);
const [me, setMe] = useState<string | null>(null);
const [readSeq, setReadSeq] = useState<Record<string, number | null>>({});
+ const [pending, setPending] = useState(0);
+ const [more, setMore] = useState<Record<string, boolean>>({});
const targets = (chat?.spaces ?? []).filter((s) => !only || s.spaceId === only);
const sig = targets.map((t) => `${t.spaceId}#${t.handle}`).join("\n");
const merge = useCallback((spaceId: string, more: readonly ThreadEntry[]) => {
@@ -301,29 +386,46 @@ export function useAgentDm(chat: AgentChat | null, only: string | null): AgentDm
return { ...was, [spaceId]: [...by.values()].sort((a, b) => a.seq - b.seq) };
});
}, []);
+ // The oldest seq shown per Space, for paging back (read at the click, not in a render).
+ const oldest = useRef<Record<string, number>>({});
+ useEffect(() => {
+ oldest.current = {};
+ for (const [id, list] of Object.entries(entries)) if (list.length) oldest.current[id] = list[0]!.seq;
+ }, [entries]);
useEffect(() => {
setEntries({});
setReadSeq({});
+ setMore({});
setStatus("loading");
setError(null);
+ setPending(targets.length);
if (!data || !targets.length) return;
let alive = true;
- let ready = 0;
+ let ok = 0;
+ let settled = 0;
+ // The first page of each Space shows as it comes: one Space's slow answer never holds the others'.
+ const settle = (good: boolean) => {
+ settled++;
+ if (good) ok++;
+ setPending(targets.length - settled);
+ setStatus(ok > 0 ? "ready" : settled === targets.length ? "error" : "loading");
+ };
for (const t of targets) {
void (async () => {
let cursor = 0;
try {
- const first = await data.call("thread.read", { spaceId: t.spaceId, with: t.handle, limit: 100, markRead: visible() });
+ const first = await data.call("thread.read", { spaceId: t.spaceId, with: t.handle, limit: DM_FIRST_PAGE, markRead: visible() });
if (!alive) return;
cursor = first.cursor;
merge(t.spaceId, first.entries);
setMe((m) => m ?? first.me);
+ setMore((m) => ({ ...m, [t.spaceId]: first.hasMoreBefore }));
setReadSeq((r) => ({ ...r, [t.spaceId]: first.readSeq ?? readSeqFrom(first.entries, first.unread, first.me) }));
- if (++ready === targets.length) setStatus("ready");
+ settle(true);
} catch (e) {
if (!alive) return;
setError(e instanceof Error ? e.message : String(e));
- setStatus("error");
+ settle(false);
return;
}
let backoff = 1_000;
@@ -350,15 +452,41 @@ export function useAgentDm(chat: AgentChat | null, only: string | null): AgentDm
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [data, sig, merge]);
- // Fold each Space's DM like its thread, then interleave by time.
- const items: DmItem[] = [];
- for (const t of targets) {
- for (const item of foldThread(entries[t.spaceId] ?? [], { readSeq: targets.length === 1 ? readSeq[t.spaceId] : null, me })) {
- const tsMs = item.type === "unread" ? 0 : item.entry.tsMs;
- items.push({ item, spaceId: t.spaceId, tsMs });
+ const loadOlder = useCallback(async () => {
+ if (!data) return;
+ await Promise.all(
+ targets
+ .filter((t) => more[t.spaceId] && oldest.current[t.spaceId] !== undefined)
+ .map(async (t) => {
+ try {
+ const page = await data.call("thread.read", { spaceId: t.spaceId, with: t.handle, before: oldest.current[t.spaceId], limit: DM_FIRST_PAGE });
+ merge(t.spaceId, page.entries);
+ setMore((m) => ({ ...m, [t.spaceId]: page.hasMoreBefore }));
+ } catch (e) {
+ setError(e instanceof Error ? e.message : String(e));
+ }
+ }),
+ );
+ // `targets` follows `sig`.
+ // eslint-disable-next-line react-hooks/exhaustive-deps
+ }, [data, sig, more, merge]);
+
+ // Fold each Space's DM like its thread, then interleave by time: made again only when the entries,
+ // the read positions or the Spaces shown change, not on every render of the page.
+ const items = useMemo(() => {
+ const out: DmItem[] = [];
+ for (const t of targets) {
+ for (const item of foldThread(entries[t.spaceId] ?? [], { readSeq: targets.length === 1 ? readSeq[t.spaceId] : null, me })) {
+ const tsMs = item.type === "unread" ? 0 : item.entry.tsMs;
+ out.push({ item, spaceId: t.spaceId, tsMs });
+ }
}
- }
- if (targets.length > 1) items.sort((a, b) => a.tsMs - b.tsMs);
+ if (targets.length > 1) out.sort((a, b) => a.tsMs - b.tsMs);
+ return out;
+ // `targets` follows `sig`.
+ // eslint-disable-next-line react-hooks/exhaustive-deps
+ }, [entries, readSeq, me, sig]);
+ const hasMore = targets.some((t) => more[t.spaceId]);
const send = useCallback(
async (spaceId: string, text: string) => {
@@ -380,5 +508,5 @@ export function useAgentDm(chat: AgentChat | null, only: string | null): AgentDm
},
[data, merge],
);
- return { status: targets.length ? status : "ready", error, items, entries, me, send, answer };
+ return { status: targets.length ? status : "ready", error, items, entries, me, pending, hasMore, loadOlder, send, answer };
}
diff --git a/apps/cua-spaces-web/src/components/agents/agent-chat.tsx b/apps/cua-spaces-web/src/components/agents/agent-chat.tsx
index 8cf4a164d8..64287f230c 100644
--- a/apps/cua-spaces-web/src/components/agents/agent-chat.tsx
+++ b/apps/cua-spaces-web/src/components/agents/agent-chat.tsx
@@ -11,7 +11,7 @@
import { Link, useNavigate } from "@tanstack/react-router";
import { ArrowUpRightIcon, EyeIcon, InfoIcon, LinkIcon, LockIcon, MonitorPlayIcon, PlayIcon, PlusIcon } from "lucide-react";
-import { useEffect, useMemo, useRef, useState, type ReactNode } from "react";
+import { useEffect, useLayoutEffect, useMemo, useRef, useState, type ReactNode } from "react";
import { useAgentDm, useAgents, useBridge, type AgentChat, type AgentChatSpace, type AgentSetupRow, type ChatNeed, type DmItem, type ThreadAttachment, type ThreadEntry } from "@/bridge";
import { AddAgentSheet, type AddAgentStage } from "@/components/add-agent/add-agent-sheet";
@@ -65,7 +65,7 @@ export function needText(t: string): string {
}
export function AgentList({
- chats,
+ chats: known,
me,
selected,
onSelect,
@@ -73,8 +73,10 @@ export function AgentList({
onAction,
onNew,
now,
+ loading = 0,
}: {
- chats: AgentChat[];
+ /** null while nothing is known yet: the list says nothing rather than "No agents yet". */
+ chats: AgentChat[] | null;
me: string | null;
selected: string | null;
onSelect: (key: string, space?: string) => void;
@@ -84,7 +86,10 @@ export function AgentList({
onAction?: (chat: AgentChat) => void;
onNew: () => void;
now: number;
+ /** Spaces still answering: the list draws what is known and says so quietly. */
+ loading?: number;
}) {
+ const chats = known ?? [];
const needs = chats.flatMap((c) => c.needsYou.map((n) => ({ n, c }))).sort((a, b) => b.n.tsMs - a.n.tsMs);
// Runs that haven't started (being made, not connected, failed): their own section, in the core's order.
const runs = chats.filter((c) => c.kind === "attempt");
@@ -100,7 +105,7 @@ export function AgentList({
</Button>
</div>
<div className="min-h-0 flex-1 overflow-y-auto px-3 pb-3">
- {chats.length === 0 ? <p className="px-2 text-xs text-muted-foreground">No agents yet</p> : null}
+ {known !== null && chats.length === 0 ? <p className="px-2 text-xs text-muted-foreground">No agents yet</p> : null}
{needs.length ? (
<Section title="Needs you" count={needs.length}>
{needs.map(({ n, c }) => (
@@ -142,6 +147,11 @@ export function AgentList({
))}
</Section>
) : null}
+ {loading > 0 ? (
+ <p data-agents-loading={loading} role="status" className="px-2 pt-3 text-xs text-muted-foreground">
+ {loading === 1 ? "Checking 1 Space" : `Checking ${loading} Spaces`}
+ </p>
+ ) : null}
</div>
<div className="shrink-0 px-5 pb-3">
<Link to="/agents/all" data-agents-show-all="" className="text-xs text-muted-foreground outline-none hover:text-foreground focus-visible:underline">
@@ -270,6 +280,19 @@ export function AgentDmView({ chat, space, onSpace, identity, onInfo, me }: { ch
const el = ref.current;
if (el) el.scrollTop = el.scrollHeight;
}, [lastKey, chat.key, space]);
+ // Earlier messages come in above: the log keeps what was in view where it was.
+ const keep = useRef<number | null>(null);
+ const older = async () => {
+ keep.current = ref.current ? ref.current.scrollHeight - ref.current.scrollTop : null;
+ await dm.loadOlder();
+ };
+ useLayoutEffect(() => {
+ const el = ref.current;
+ if (el && keep.current !== null) {
+ el.scrollTop = el.scrollHeight - keep.current;
+ keep.current = null;
+ }
+ }, [dm.items.length]);
const asleepHere = space && shown[0]?.member.status === "asleep";
return (
<section data-dm={chat.key} data-dm-space={space ?? "all"} className="flex min-w-0 flex-1 flex-col">
@@ -317,6 +340,11 @@ export function AgentDmView({ chat, space, onSpace, identity, onInfo, me }: { ch
</p>
) : (
<>
+ {dm.hasMore ? (
+ <button type="button" data-dm-older="" onClick={() => void older()} className="mx-auto mb-1 cursor-default rounded-lg px-2 py-1 text-xs text-muted-foreground outline-none hover:text-foreground focus-visible:underline">
+ Show earlier messages
+ </button>
+ ) : null}
{asleepHere ? <p className="my-1 text-center text-xs text-muted-foreground">{chat.label} is asleep here. A message wakes it.</p> : null}
{dm.items.map((d, i) => (
<DmRow key={`${d.spaceId}${d.item.key}`} d={d} above={dmAbove(dm.items, i)} roster={rosters[d.spaceId]!} spaces={chat.spaces} multi={multi && !space} onAnswer={(seq, ok) => dm.answer(d.spaceId, seq, ok)} onOpenAttachment={openAttachment} onRetry={(text) => dm.send(d.spaceId, text)} />
diff --git a/apps/cua-spaces-web/src/lib/poll-plan.test.ts b/apps/cua-spaces-web/src/lib/poll-plan.test.ts
index 3c313efb34..fa62866cab 100644
--- a/apps/cua-spaces-web/src/lib/poll-plan.test.ts
+++ b/apps/cua-spaces-web/src/lib/poll-plan.test.ts
@@ -3,7 +3,7 @@
import { describe, expect, it } from "vitest";
-import { chatsPollMs, jittered, JobQueue, mapLimit, MissCache } from "./poll-plan";
+import { chatsPollMs, forEachLimit, jittered, JobQueue, mapLimit, MissCache } from "./poll-plan";
describe("chatsPollMs", () => {
it("is 5 s for a small account and slows as it grows, to a minute", () => {
@@ -106,3 +106,52 @@ describe("JobQueue", () => {
await expect(next).resolves.toBe("ok");
});
});
+
+describe("forEachLimit", () => {
+ it("runs at most `limit` at once and starts every item", async () => {
+ let active = 0;
+ let peak = 0;
+ const done: number[] = [];
+ await forEachLimit([1, 2, 3, 4, 5, 6], 2, 1000, async (n) => {
+ active++;
+ peak = Math.max(peak, active);
+ await new Promise((r) => setTimeout(r, 5));
+ active--;
+ done.push(n);
+ });
+ expect(peak).toBe(2);
+ expect(done.sort()).toEqual([1, 2, 3, 4, 5, 6]);
+ });
+
+ it("a hung item holds its slot for the slot time only, never the rest of the list", async () => {
+ const started: number[] = [];
+ const t0 = Date.now();
+ await forEachLimit([1, 2, 3, 4], 1, 30, async (n) => {
+ started.push(n);
+ if (n === 1) await new Promise(() => undefined);
+ });
+ // One slot, the first never answers: the others still ran, after its 30 ms.
+ expect(started).toEqual([1, 2, 3, 4]);
+ expect(Date.now() - t0).toBeLessThan(1000);
+ });
+
+ it("a late result still lands: the job keeps running after its slot is freed", async () => {
+ let finished = false;
+ await forEachLimit([1], 1, 10, async () => {
+ await new Promise((r) => setTimeout(r, 40));
+ finished = true;
+ });
+ expect(finished).toBe(false);
+ await new Promise((r) => setTimeout(r, 60));
+ expect(finished).toBe(true);
+ });
+
+ it("a failing job does not stop the others", async () => {
+ const ran: number[] = [];
+ await forEachLimit([1, 2, 3], 3, 100, async (n) => {
+ ran.push(n);
+ if (n === 2) throw new Error("no");
+ });
+ expect(ran).toEqual([1, 2, 3]);
+ });
+});
diff --git a/apps/cua-spaces-web/src/lib/poll-plan.ts b/apps/cua-spaces-web/src/lib/poll-plan.ts
index d724d9c859..07f53a300e 100644
--- a/apps/cua-spaces-web/src/lib/poll-plan.ts
+++ b/apps/cua-spaces-web/src/lib/poll-plan.ts
@@ -33,6 +33,29 @@ export async function mapLimit<T, R>(items: readonly T[], limit: number, f: (ite
return out;
}
+/**
+ * `f` over `items`, at most `limit` at a time, where a slot is free again
+ * when its job ends or after `slotMs`, whichever comes first (a job that
+ * outlasts it keeps running; nothing waits for it). Resolves when every job
+ * has started and held its slot. One slow or hung item holds up one slot for
+ * `slotMs`, never the rest of the list. `f` handles its own results and
+ * errors.
+ */
+export async function forEachLimit<T>(items: readonly T[], limit: number, slotMs: number, f: (item: T, index: number) => Promise<void>): Promise<void> {
+ let next = 0;
+ const worker = async () => {
+ for (let i = next++; i < items.length; i = next++) {
+ let timer: ReturnType<typeof setTimeout> | undefined;
+ const slow = new Promise<void>((resolve) => {
+ timer = setTimeout(resolve, slotMs);
+ });
+ await Promise.race([f(items[i]!, i).catch(() => undefined), slow]);
+ clearTimeout(timer);
+ }
+ };
+ await Promise.all(Array.from({ length: Math.min(Math.max(1, limit), items.length) }, worker));
+}
+
/** Ids that failed in a way that will not change soon (a Space with no
* thread: a stopped machine, an old daemon), not asked again for `ttlMs`. */
export class MissCache {
diff --git a/apps/cua-spaces-web/src/routes/agents/index.tsx b/apps/cua-spaces-web/src/routes/agents/index.tsx
index 44019beba6..6eca36dea9 100644
--- a/apps/cua-spaces-web/src/routes/agents/index.tsx
+++ b/apps/cua-spaces-web/src/routes/agents/index.tsx
@@ -52,7 +52,7 @@ function AgentsChatPage() {
// The one list (agents in your Spaces and this device's runs that haven't started): Home shows it too.
const attempts = useAgentAttempts();
const act = useAttemptAction();
- const { chats, spaces, me, refresh } = useAgentChats(attempts);
+ const { chats, spaces, me, loading, refresh } = useAgentChats(attempts);
const now = useNow();
const [sheet, setSheet] = useState<AddAgentStage | null>(null);
const [info, setInfo] = useState(false);
@@ -64,7 +64,7 @@ function AgentsChatPage() {
return (
<div data-agents-chat="" className="flex h-full min-h-0">
<AgentList
- chats={chats ?? []}
+ chats={chats}
me={me}
selected={chat?.key ?? null}
onSelect={select}
@@ -72,8 +72,9 @@ function AgentsChatPage() {
onAction={act}
onNew={() => setSheet("pick")}
now={now}
+ loading={loading}
/>
- {chats === null ? (
+ {chats === null || (loading > 0 && chats.every((c) => c.kind !== "agent")) ? (
<div className="flex-1" />
) : chat ? (
<>
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 2c68ff31f5..1c7880064c 100644
--- a/libs/cua/crates/cua-spaces-ext/src/persistent/members.rs
+++ b/libs/cua/crates/cua-spaces-ext/src/persistent/members.rs
@@ -46,6 +46,13 @@ use cua_spaces::{Error, Result};
/// machine's.
pub const HOST_DESKTOP: &str = "this-mac";
+/// The longest a status read of one Space's runs may take (the list shows
+/// the record's last word for a run that did not answer in time).
+pub(crate) const PROBE_TIMEOUT: std::time::Duration = std::time::Duration::from_secs(2);
+/// How long a Space that did not answer is left alone before its runs are
+/// asked again.
+pub(crate) const UNREACHABLE_TTL: std::time::Duration = std::time::Duration::from_secs(20);
+
pub const CLAIM_TTL: std::time::Duration = std::time::Duration::from_secs(120);
/// The largest local file attached to a post.
@@ -446,6 +453,42 @@ impl Persistent {
});
}
+ /// The Space's agent service for a status read, or none when it does
+ /// not answer in [`PROBE_TIMEOUT`] or did not a moment ago
+ /// ([`UNREACHABLE_TTL`]).
+ async fn probe_agents(&self, space: &str) -> Option<cua_agents::Agents> {
+ if self.is_unreachable(space).await {
+ return None;
+ }
+ match tokio::time::timeout(PROBE_TIMEOUT, self.cached_agents(space)).await {
+ Ok(Ok(a)) => Some(a),
+ _ => {
+ self.mark_unreachable(space).await;
+ None
+ }
+ }
+ }
+
+ async fn is_unreachable(&self, space: &str) -> bool {
+ let mut live = self.live.lock().await;
+ match live.unreachable.get(space) {
+ Some(at) if at.elapsed() < UNREACHABLE_TTL => true,
+ Some(_) => {
+ live.unreachable.remove(space);
+ false
+ }
+ None => false,
+ }
+ }
+
+ async fn mark_unreachable(&self, space: &str) {
+ self.live
+ .lock()
+ .await
+ .unreachable
+ .insert(space.to_string(), std::time::Instant::now());
+ }
+
/// The agent members of `space` with what each is doing: the member's
/// `status` (`working | waiting | failed | idle | asleep | paused`, the
/// busiest of its sessions) and each session's in `session_states`.
@@ -456,25 +499,47 @@ impl Persistent {
let fold = store.fold()?;
let mut out = vec![];
let live = |r: &AgentRecord| r.session_views().iter().any(|s| s.run_id.is_some());
+ // What each running session reports, asked of the Space's agent
+ // service all at once and each bounded: a Space that does not answer
+ // (a stopped machine, one that is off) must not hold the list for
+ // the sum of every run's timeout. Its members show what the record
+ // last said, and the Space is not asked again for a while.
let agents = if recs.iter().any(|r| live(r) && !r.paused) {
- match tokio::time::timeout(std::time::Duration::from_secs(15), self.cached_agents(&id))
- .await
- {
- Ok(Ok(a)) => Some(a),
- _ => None,
- }
+ self.probe_agents(&id).await
} else {
None
};
+ let mut reported: std::collections::HashMap<(String, u32), Option<RunStatus>> =
+ std::collections::HashMap::new();
+ if let Some(a) = &agents {
+ let asks = recs
+ .iter()
+ .filter(|r| !r.paused)
+ .flat_map(|r| {
+ r.session_views()
+ .into_iter()
+ .map(move |s| (r.name.clone(), s))
+ })
+ .filter_map(|(name, s)| s.run_id.clone().map(|run| (name, s.k(), run)))
+ .map(|(name, k, run)| {
+ let a = a.clone();
+ async move {
+ let st = tokio::time::timeout(PROBE_TIMEOUT, a.status(&run)).await;
+ ((name, k), st.ok().and_then(|r| r.ok()).map(|st| st.status))
+ }
+ });
+ let answers = futures_util::future::join_all(asks).await;
+ if answers.iter().any(|(_, st)| st.is_none()) {
+ self.mark_unreachable(&id).await;
+ }
+ reported.extend(answers);
+ }
for r in recs {
let open = fold.open_tasks(Some(&r.name)).len();
let mut sessions = vec![];
let mut first_status = None;
for s in r.session_views() {
- let mut run_status = None;
- if let (Some(run), Some(a), false) = (&s.run_id, &agents, r.paused) {
- run_status = a.status(run).await.ok().map(|st| st.status);
- }
+ let run_status = reported.get(&(r.name.clone(), s.k())).copied().flatten();
if s.k() <= 1 {
first_status = run_status;
}
@@ -1876,22 +1941,40 @@ impl Thread {
/// The caller's DM with agent `with`, summed up for the Agents tab.
pub fn dm_summary(&self, with: &str, may_approve: bool) -> Result<crate::thread::DmSummary> {
+ Ok(self
+ .dm_summaries(&[(with.to_string(), may_approve)])?
+ .remove(0))
+ }
+
+ /// [`Self::dm_summary`] for several agents of one thread: the log, the
+ /// cursors and the approvals are read once, not once per agent.
+ pub fn dm_summaries(
+ &self,
+ members: &[(String, bool)],
+ ) -> Result<Vec<crate::thread::DmSummary>> {
let me = self.me();
let cursors = self.store.cursors()?;
- let key = crate::thread::dm_cursor_key(&me.id, with);
- let read = cursors
- .get(&key)
- .or_else(|| cursors.get(&me.id))
- .map_or(0, |c| c.read_seq);
- Ok(crate::thread::dm_summary(
- &self.store.read(0, usize::MAX)?,
- &me.id,
- &me.name,
- with,
- read,
- &self.store.fold()?.approvals,
- may_approve,
- ))
+ let entries = self.store.read(0, usize::MAX)?;
+ let fold = self.store.fold()?;
+ Ok(members
+ .iter()
+ .map(|(with, may_approve)| {
+ let key = crate::thread::dm_cursor_key(&me.id, with);
+ let read = cursors
+ .get(&key)
+ .or_else(|| cursors.get(&me.id))
+ .map_or(0, |c| c.read_seq);
+ crate::thread::dm_summary(
+ &entries,
+ &me.id,
+ &me.name,
+ with,
+ read,
+ &fold.approvals,
+ *may_approve,
+ )
+ })
+ .collect())
}
/// Open tasks of `member` (an agent caller: its own), oldest first.
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 dbfd5941ed..ddda796da9 100644
--- a/libs/cua/crates/cua-spaces-ext/src/persistent/mod.rs
+++ b/libs/cua/crates/cua-spaces-ext/src/persistent/mod.rs
@@ -455,6 +455,8 @@ pub struct TickReport {
pub(crate) struct Live {
leases: HashMap<String, cua_volume::lease::Lease>,
agents: HashMap<String, Agents>,
+ /// Spaces whose runs did not answer a status read, and when: not asked again for a while.
+ unreachable: HashMap<String, std::time::Instant>,
bridges: HashMap<String, bridge::BridgeState>,
routines: Option<Arc<tokio::sync::Mutex<RoutineStore>>>,
routines_mtime: Option<std::time::SystemTime>,
diff --git a/libs/cua/crates/cua-spaces-ext/src/thread_tools.rs b/libs/cua/crates/cua-spaces-ext/src/thread_tools.rs
index a31cfeb2b0..03aab93f61 100644
--- a/libs/cua/crates/cua-spaces-ext/src/thread_tools.rs
+++ b/libs/cua/crates/cua-spaces-ext/src/thread_tools.rs
@@ -237,19 +237,27 @@ pub(crate) async fn call(
}
}
let me = p.author_for(caller).id;
+ // One read of the records, not one per row.
+ let records = p.list().unwrap_or_default();
for row in &mut rows {
let name = row["name"].as_str().unwrap_or_default().to_string();
- if let Ok(rec) = p.get(&name) {
- row["you_can"] = Persistent::rights_of(&rec).you_can(p.role_of(caller), &me);
+ if let Some(rec) = records.iter().find(|r| r.name == name) {
+ row["you_can"] = Persistent::rights_of(rec).you_can(p.role_of(caller), &me);
}
}
// The Agents tab (CUA-2266): each agent's DM with the caller.
if a.overview.unwrap_or(false) && caller.agent_member().is_none() {
let t = p.thread(caller, &a.space).await?;
- for row in &mut rows {
- let name = row["name"].as_str().unwrap_or_default().to_string();
- let may_approve = row["you_can"]["approve"].as_bool().unwrap_or(true);
- let sum = t.dm_summary(&name, may_approve)?;
+ let asks: Vec<(String, bool)> = rows
+ .iter()
+ .map(|row| {
+ (
+ row["name"].as_str().unwrap_or_default().to_string(),
+ row["you_can"]["approve"].as_bool().unwrap_or(true),
+ )
+ })
+ .collect();
+ for (row, sum) in rows.iter_mut().zip(t.dm_summaries(&asks)?) {
row["dm"] = json!({"unread": sum.unread, "last": sum.last});
row["needs_you"] = json!(sum.needs_you);
}
diff --git a/libs/cua/crates/cua-spaces-ext/tests/agents_populate.rs b/libs/cua/crates/cua-spaces-ext/tests/agents_populate.rs
new file mode 100644
index 0000000000..1d48d31629
--- /dev/null
+++ b/libs/cua/crates/cua-spaces-ext/tests/agents_populate.rs
@@ -0,0 +1,244 @@
+// SPDX-License-Identifier: FSL-1.1-MIT
+// Copyright (c) 2026 Cua AI, Inc.
+
+//! How long the Agents page's reads take on the daemon (CUA-2849): a
+//! dataset like a busy account's, 13 Spaces with six agents and long
+//! threads, then the calls the page makes for each Space
+//! (`agent_members {overview}`, `thread_read {limit: 1}`, and the DM's
+//! `thread_read {with}`), timed one by one. The thresholds are generous
+//! (several times the numbers on a laptop): they fail on a read that grows
+//! with the whole thread for every agent (an N+1), not on a slow machine.
+//! Against in-process spacesd mocks and a temporary home.
+
+use std::time::{Duration, Instant};
+
+use cua_spaces::Spaces;
+use cua_spaces::extension::Caller;
+use cua_spaces::mcp::McpServer;
+use cua_spaces_ext::thread::{Author, Draft, EntryKind, TaskTo, ThreadStore};
+use cua_spacesd_client::testing::{MockAuth, MockServer};
+use serde_json::{Value, json};
+
+const SPACES: usize = 13;
+const LONG: usize = 3;
+const AGENTS: [&str; 6] = ["claude", "codex", "hermes-test", "ada", "bo", "cy"];
+
+fn entries(n: usize) -> Vec<Draft> {
+ let mut out = Vec::with_capacity(n);
+ for i in 0..n {
+ let agent = AGENTS[i % AGENTS.len()];
+ if i % 3 == 0 {
+ let mut d = Draft::new(
+ Author::owner(),
+ EntryKind::Message,
+ format!(
+ "@{agent} task number {i}: please look at the failing build and report back"
+ ),
+ );
+ d.mentions = vec![agent.into()];
+ d.task = Some(TaskTo {
+ to: agent.into(),
+ session: None,
+ });
+ out.push(d);
+ } else {
+ out.push(Draft::new(
+ Author::agent(agent),
+ EntryKind::Message,
+ format!("Reply {i}: I looked at it and the retry timeout is the cause, a longer one fixes it. ").repeat(3),
+ ));
+ }
+ }
+ out
+}
+
+async fn call(mcp: &McpServer, tool: &str, args: Value) -> (Value, Duration) {
+ let t = Instant::now();
+ let out = Caller::Owner.scope(Box::pin(mcp.call(tool, args))).await;
+ let v = cua_spaces::extension::outcome_json(out).unwrap_or_else(|e| panic!("{tool}: {e}"));
+ (v, t.elapsed())
+}
+
+#[tokio::test(flavor = "multi_thread", worker_threads = 4)]
+async fn the_pages_reads_do_not_grow_with_the_whole_thread_for_every_agent() {
+ 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 mcp = McpServer::new(spaces.clone());
+ let mut servers = vec![];
+ let mut ids = vec![];
+ for i in 0..SPACES {
+ let srv = MockServer::start(MockAuth::default()).await;
+ let info = spaces
+ .add(
+ &format!("http://{}", srv.addr),
+ None,
+ Some(format!("space-{i}")),
+ )
+ .await
+ .unwrap();
+ servers.push(srv);
+ ids.push(info.id);
+ }
+ for (i, id) in ids.iter().enumerate() {
+ for name in AGENTS {
+ call(
+ &mcp,
+ "agent_add",
+ json!({"space": id, "name": name, "harness": "claude-code"}),
+ )
+ .await;
+ }
+ let n = if i < LONG { 2000 } else { 40 };
+ ThreadStore::open(home.path(), id)
+ .append_many(entries(n))
+ .unwrap();
+ }
+
+ let mut worst_overview = Duration::ZERO;
+ let mut worst_tail = Duration::ZERO;
+ let mut worst_dm = Duration::ZERO;
+ let started = Instant::now();
+ for id in &ids {
+ let (_, o) = call(
+ &mcp,
+ "agent_members",
+ json!({"space": id, "overview": true}),
+ )
+ .await;
+ let (_, t) = call(&mcp, "thread_read", json!({"space": id, "limit": 1})).await;
+ worst_overview = worst_overview.max(o);
+ worst_tail = worst_tail.max(t);
+ }
+ let list_total = started.elapsed();
+ for id in ids.iter().take(LONG) {
+ let (page, d) = call(
+ &mcp,
+ "thread_read",
+ json!({"space": id, "with": "claude", "limit": 100}),
+ )
+ .await;
+ assert!(page["entries"].as_array().unwrap().len() <= 100);
+ worst_dm = worst_dm.max(d);
+ }
+ eprintln!(
+ "agents_populate: {SPACES} spaces, {LONG} with 2000 entries: overview worst {worst_overview:?}, tail worst {worst_tail:?}, whole list serial {list_total:?}, dm worst {worst_dm:?}"
+ );
+ assert!(
+ worst_overview < Duration::from_millis(1500),
+ "agent_members overview {worst_overview:?}"
+ );
+ assert!(
+ worst_tail < Duration::from_millis(1500),
+ "thread_read tail {worst_tail:?}"
+ );
+ assert!(
+ worst_dm < Duration::from_millis(1500),
+ "thread_read dm {worst_dm:?}"
+ );
+ assert!(
+ list_total < Duration::from_secs(8),
+ "serial list {list_total:?}"
+ );
+ drop(servers);
+}
+
+/// Marks every agent of `ids` as running (a `run_id` on its record), as the
+/// supervisor leaves them while their runs are up.
+fn mark_running(home: &std::path::Path, ids: &[String]) {
+ let path = std::fs::read_dir(home)
+ .unwrap()
+ .flatten()
+ .map(|e| e.path().join("agents.json"))
+ .find(|p| p.exists())
+ .or_else(|| walk(home, "agents.json"))
+ .expect("agents.json");
+ let mut all: Vec<Value> = serde_json::from_slice(&std::fs::read(&path).unwrap()).unwrap();
+ for a in &mut all {
+ if ids.iter().any(|i| a["space"] == i.as_str()) {
+ a["run_id"] = json!(format!("run-{}", a["name"].as_str().unwrap()));
+ }
+ }
+ std::fs::write(&path, serde_json::to_vec(&all).unwrap()).unwrap();
+}
+
+fn walk(dir: &std::path::Path, name: &str) -> Option<std::path::PathBuf> {
+ for e in std::fs::read_dir(dir).ok()?.flatten() {
+ let p = e.path();
+ if p.file_name().is_some_and(|n| n == name) {
+ return Some(p);
+ }
+ if p.is_dir()
+ && let Some(f) = walk(&p, name)
+ {
+ return Some(f);
+ }
+ }
+ None
+}
+
+/// A Space that can't be reached while its agents show a run (a stopped
+/// machine, a machine that is off) must not hold the page's read: the
+/// overview answers at once with what is known.
+#[tokio::test(flavor = "multi_thread", worker_threads = 4)]
+async fn an_unreachable_space_with_running_agents_does_not_hold_the_overview() {
+ 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 mcp = McpServer::new(spaces.clone());
+ let srv = MockServer::start(MockAuth::default()).await;
+ let info = spaces
+ .add(&format!("http://{}", srv.addr), None, Some("gone".into()))
+ .await
+ .unwrap();
+ for name in AGENTS {
+ call(
+ &mcp,
+ "agent_add",
+ json!({"space": info.id, "name": name, "harness": "claude-code"}),
+ )
+ .await;
+ }
+ mark_running(home.path(), std::slice::from_ref(&info.id));
+ drop(srv);
+ let t = Instant::now();
+ let r = spaces.space(&info.id).await.map(|_| ());
+ eprintln!(
+ "agents_populate: spaces.space() on it {:?} -> {:?}",
+ t.elapsed(),
+ r.err().map(|e| e.to_string())
+ );
+ let (_, d) = call(&mcp, "thread_read", json!({"space": info.id, "limit": 1})).await;
+ eprintln!("agents_populate: thread_read on it {d:?}");
+ let (_, d) = call(&mcp, "agent_members", json!({"space": info.id})).await;
+ eprintln!("agents_populate: agent_members (no overview) on it {d:?}");
+ let mut times = vec![];
+ for _ in 0..3 {
+ let (rows, d) = call(
+ &mcp,
+ "agent_members",
+ json!({"space": info.id, "overview": true}),
+ )
+ .await;
+ assert_eq!(rows["members"].as_array().unwrap().len(), AGENTS.len());
+ times.push(d);
+ }
+ eprintln!(
+ "agents_populate: unreachable space with {} running agents, overview x3: {times:?}",
+ AGENTS.len()
+ );
+ for d in &times {
+ assert!(
+ *d < Duration::from_secs(4),
+ "overview of an unreachable space took {d:?}"
+ );
+ }
+}