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.

Agents that are not connected say so with Connect and Retry; popups no longer hide the Space's desktop (#6097)

ddupontc40ef077d148
diff --git a/apps/cua-spaces-desktop/src/model/agents.ts b/apps/cua-spaces-desktop/src/model/agents.ts
index 0e8739de49..5042412985 100644
--- a/apps/cua-spaces-desktop/src/model/agents.ts
+++ b/apps/cua-spaces-desktop/src/model/agents.ts
@@ -381,6 +381,7 @@ export function agentKeysInput(report: Json | null, error: string | null): AppAg
env: typeof k.env === "string" ? k.env : "",
last4: typeof k.last4 === "string" ? k.last4 : "",
addedMs: BigInt(typeof k.added_ms === "number" && k.added_ms >= 0 ? Math.floor(k.added_ms) : 0),
+ expired: k.expired === true,
}))
.filter((k) => k.env !== "");
const unavailable = report?.available === false ? (typeof report.unavailable === "string" ? report.unavailable : "this computer can't keep keys") : undefined;
diff --git a/apps/cua-spaces-desktop/src/native/generated/cua_spaces_ffi.ts b/apps/cua-spaces-desktop/src/native/generated/cua_spaces_ffi.ts
index 9da84baf1a..8ee01dea9c 100644
--- a/apps/cua-spaces-desktop/src/native/generated/cua_spaces_ffi.ts
+++ b/apps/cua-spaces-desktop/src/native/generated/cua_spaces_ffi.ts
@@ -8828,7 +8828,11 @@ export type AppAgentKeyInput = {
/**
* When it was added (Unix ms).
*/
- addedMs: bigint
+ addedMs: bigint,
+ /**
+ * A sign-in past its expiry: not used by any run until reconnected.
+ */
+ expired: boolean
}
/**
@@ -8855,7 +8859,8 @@ const FfiConverterTypeAppAgentKeyInput = (() => {
provider: FfiConverterString.read(from),
env: FfiConverterString.read(from),
last4: FfiConverterString.read(from),
- addedMs: FfiConverterUInt64.read(from)
+ addedMs: FfiConverterUInt64.read(from),
+ expired: FfiConverterBool.read(from)
};
}
write(value: TypeName, into: RustBuffer): void {
@@ -8863,12 +8868,14 @@ const FfiConverterTypeAppAgentKeyInput = (() => {
FfiConverterString.write(value.env, into);
FfiConverterString.write(value.last4, into);
FfiConverterUInt64.write(value.addedMs, into);
+ FfiConverterBool.write(value.expired, into);
}
allocationSize(value: TypeName): number {
return FfiConverterString.allocationSize(value.provider) +
FfiConverterString.allocationSize(value.env) +
FfiConverterString.allocationSize(value.last4) +
- FfiConverterUInt64.allocationSize(value.addedMs);
+ FfiConverterUInt64.allocationSize(value.addedMs) +
+ FfiConverterBool.allocationSize(value.expired);
}
};
diff --git a/apps/cua-spaces-macos/Sources/CuaSpacesMacKit/Models/AgentKeysModel.swift b/apps/cua-spaces-macos/Sources/CuaSpacesMacKit/Models/AgentKeysModel.swift
index 17214966b4..f6ebdb2bd8 100644
--- a/apps/cua-spaces-macos/Sources/CuaSpacesMacKit/Models/AgentKeysModel.swift
+++ b/apps/cua-spaces-macos/Sources/CuaSpacesMacKit/Models/AgentKeysModel.swift
@@ -70,7 +70,8 @@ public final class AgentKeysModel {
let keys = (report?["keys"] as? [Any] ?? []).compactMap { $0 as? [String: Any] }.map { k in
AppAgentKeyInput(provider: k["provider"] as? String ?? "other", env: k["env"] as? String ?? "",
last4: k["last4"] as? String ?? "",
- addedMs: (k["added_ms"] as? NSNumber)?.uint64Value ?? 0)
+ addedMs: (k["added_ms"] as? NSNumber)?.uint64Value ?? 0,
+ expired: k["expired"] as? Bool ?? false)
}
let unavailable = report?["available"] as? Bool == false
? (report?["unavailable"] as? String ?? "this computer can't keep keys") : nil
diff --git a/apps/cua-spaces-macos/Sources/CuaSpacesMacKit/WebHost/WebUIVideoSurfaces.swift b/apps/cua-spaces-macos/Sources/CuaSpacesMacKit/WebHost/WebUIVideoSurfaces.swift
index 9c5bc71bef..b18b2e9df1 100644
--- a/apps/cua-spaces-macos/Sources/CuaSpacesMacKit/WebHost/WebUIVideoSurfaces.swift
+++ b/apps/cua-spaces-macos/Sources/CuaSpacesMacKit/WebHost/WebUIVideoSurfaces.swift
@@ -184,8 +184,10 @@ final class WebUIVideoSurfaces: NSObject, WKScriptMessageHandler {
surface.view.input.showsCursorOverlay = u.interactive && surface.view.presence?.presenceView == nil
surface.view.apply(surface.layout)
show(surface)
- // Keys never stay with a viewer that page UI covers or that left the screen.
- if focusedId == surface.id, surface.view.isHidden { focus(nil) }
+ // Keys never stay with a viewer that page UI covers or that left the
+ // screen, nor with one the page made non-interactive (a modal dialog
+ // is open over it: the video keeps playing, the dialog takes the keys).
+ if focusedId == surface.id, surface.view.isHidden || !u.interactive { focus(nil) }
}
private func attach(_ u: VideoSurfaceUpdate, in webView: WKWebView) -> Surface {
diff --git a/apps/cua-spaces-macos/Tests/CuaSpacesMacTests/WebUIVideoSurfacesTests.swift b/apps/cua-spaces-macos/Tests/CuaSpacesMacTests/WebUIVideoSurfacesTests.swift
index 1e4298ef95..76dce20c7f 100644
--- a/apps/cua-spaces-macos/Tests/CuaSpacesMacTests/WebUIVideoSurfacesTests.swift
+++ b/apps/cua-spaces-macos/Tests/CuaSpacesMacTests/WebUIVideoSurfacesTests.swift
@@ -648,6 +648,36 @@ struct WebUIVideoSurfacesTests {
s.removeAll()
}
+ /// CUA-2641: a modal dialog over the viewer no longer hides the stream.
+ /// The page reports the viewer non-interactive instead: the video stays
+ /// shown and live, but it gives back the keyboard and takes no clicks
+ /// (the dialog's backdrop and Escape work), and takes both again after.
+ @Test func aModalDialogOverTheViewerKeepsItLiveButTakesItsKeysAndClicks() async throws {
+ let host = Host()
+ let units = AccessUnit.split(Self.tinyH264)
+ let s = surfaces(host) { _, _ in SyntheticStreamProvider(units: units, size: CGSize(width: 64, height: 48), fps: 30) }
+ s.handle(message([entry("v", space: "a")]))
+ await settle { host.phases("v").contains("live") }
+ s.handle(["type": "focus", "surfaceId": "v"])
+ #expect(s.focusedId == "v")
+ let view = try #require(s.surfaces["v"]?.view)
+ // The dialog opens: not occluded, not interactive, one hole where its popup is.
+ var modal = entry("v", space: "a", interactive: false)
+ modal["holes"] = [["x": 100, "y": 60, "width": 200, "height": 120]]
+ s.handle(message([modal]))
+ #expect(!view.isHidden)
+ #expect(host.phases("v").last == "live")
+ #expect(s.focusedId == nil)
+ #expect(view.layer?.mask != nil)
+ s.handle(["type": "focus", "surfaceId": "v"])
+ #expect(s.focusedId == nil)
+ // Closed: the viewer takes the keyboard again.
+ s.handle(message([entry("v", space: "a")]))
+ s.handle(["type": "focus", "surfaceId": "v"])
+ #expect(s.focusedId == "v")
+ s.removeAll()
+ }
+
@Test func theHarnessAddsRunningFixtureSpaces() {
#expect(FixtureSpacesBackend.rows(environment: [:]).count == FixtureSpacesBackend.sample.count)
let rows = FixtureSpacesBackend.rows(environment: ["CUA_SPACES_FIXTURE_SPACES": "3"])
diff --git a/apps/cua-spaces-macos/docs/native-video.md b/apps/cua-spaces-macos/docs/native-video.md
index 52d3874a11..56aba78862 100644
--- a/apps/cua-spaces-macos/docs/native-video.md
+++ b/apps/cua-spaces-macos/docs/native-video.md
@@ -35,11 +35,13 @@ The page keeps one reporter, with one set of observers and one animation frame.
- **`rect`** is the video area inside the slot's border, in CSS px from the web view's top left.
- **`clip`** is the part of `rect` that the viewport and every clipping ancestor leave visible. For example, a tile scrolled halfway under the page's top edge is cut there.
-- **`occluded`** is true when page UI covers the slot, and the host hides the video. Two checks feed it:
- - an element matching `[role=dialog|alertdialog]` overlaps the slot;
+- **`occluded`** is true when page UI covers a Space tile, and the host hides the video. Two checks feed it:
+ - an element matching `[role=dialog|alertdialog]` overlaps the slot (a dialog-role popup that marks itself a hole, such as the profile card, doesn't count);
- something else is on top at one of 9 sample points (a dialog's backdrop, for example).
The sample points sit inside the rounded corners. Transparent click catchers (`[data-base-ui-inert]`, which Base UI puts under an open menu or popover) paint nothing and are looked through, and floating UI that gets a hole doesn't count.
+
+ **The Space viewer is never occluded by page UI** (CUA-2641): menus, popovers, the profile card, tooltips, toasts and dialogs are holes over it, and a dialog's dimmed backdrop (`[data-window-dim]`) is looked through. While a modal dialog is open the page reports the viewer `interactive: false`: the video keeps playing, gives the keyboard back to the page and takes no clicks, so the dialog's own backdrop and Escape work.
- **`holes`** are the rects of floating UI over the slot, cut to `clip`: `[role=menu|listbox|tooltip]`, `[data-video-occluder]` (toasts, popovers) and `[data-video-hole]` (the viewer's own key bar, inside the slot). The host masks the video out there, so the menu shows and the rest of the desktop keeps playing, and clicks there go to the page. Hiding the whole video for a menu turned it black while the menu was open.
- **`visible`** is false when the page is hidden or the slot is clipped away entirely.
@@ -176,7 +178,7 @@ A live E2E should check:
- Type: keys arrive, including ⌘C and ⌘V inside the Space.
- Control+Option pressed and released alone: the key bar over the viewer goes.
- Scroll: the page scrolls before you click, and the Space scrolls after.
-3. **Covering.** Open the command palette (⌘K) and the Stop dialog over the viewer. The video hides while each is open, keys go to the dialog, and the video comes back after. Open the header's "⋯" menu and show a toast: the video stays live, with only the part under the menu or toast cut out.
+3. **Covering.** Open the command palette (⌘K) and the Stop dialog over the viewer: the video stays live with only the dialog's own rectangle cut out, keys go to the dialog, a click on the dimmed area closes it instead of reaching the Space, and the viewer takes the keyboard again after. On the Spaces grid a dialog still hides the tiles under it. Open the header's "⋯" menu, a name's profile card and Share, and show a toast: the video stays live, with only the part under each cut out.
4. **Picture in picture.** Pop the desktop out from the header, then close the panel (its own button or the header's): the inline desktop is live again at once, with no "Connecting…" and no error.
5. **Failure.** Stop a Space while its viewer is open. You should see the stopped state, not a frozen frame. Then delete a Space with an open tile.
6. **Hidden window.** Minimize the window, then restore it. The streams pause, then come back. A desktop popped out to picture in picture keeps playing in its panel.
diff --git a/apps/cua-spaces-web/e2e/space-popups-stream.spec.ts b/apps/cua-spaces-web/e2e/space-popups-stream.spec.ts
new file mode 100644
index 0000000000..2a86b104e6
--- /dev/null
+++ b/apps/cua-spaces-web/e2e/space-popups-stream.spec.ts
@@ -0,0 +1,161 @@
+// SPDX-License-Identifier: FSL-1.1-MIT
+// Copyright (c) 2026 Cua AI, Inc.
+
+/**
+ * CUA-2641: popups, menus, cards, dialogs and tooltips opened from a Space's
+ * page never hide, blank or resize its desktop stream.
+ *
+ * On macOS the SwiftUI host draws the desktop itself over the web view; the
+ * page only reports where it goes and what floats over it (apps/cua-spaces-
+ * macos/docs/native-video.md). This spec stands in for that host with a
+ * `cuaVideo` handler that records every report, runs the real page in a real
+ * browser (real hit-testing and layout), opens each popup type with the
+ * stream "running", and checks the last report for the viewer: still
+ * visible, not occluded, the same size as before, with a hole where the
+ * popup is (so the host cuts the video out there and keeps the rest playing),
+ * and, under a modal dialog, non-interactive (the dialog takes the keys and
+ * clicks).
+ */
+
+import type { Page } from "@playwright/test";
+
+import { ELECTRON, expect, test } from "./host";
+
+// The Electron shell draws video with WebCodecs, not the SwiftUI host's native views this stands in for.
+test.skip(ELECTRON, "native video slots are the SwiftUI host's");
+
+interface Surface {
+ surfaceId: string;
+ tier: "tile" | "full";
+ interactive: boolean;
+ rect: { x: number; y: number; width: number; height: number };
+ clip: { x: number; y: number; width: number; height: number } | null;
+ occluded: boolean;
+ visible: boolean;
+ holes?: { x: number; y: number; width: number; height: number }[];
+}
+
+const SPACE = `/spaces/${encodeURIComponent("relay:linux-box/ubuntu-build")}`;
+
+test.beforeEach(async ({ page }) => {
+ await page.addInitScript(() => {
+ const w = window as unknown as { __video: unknown[]; webkit: unknown };
+ w.__video = [];
+ w.webkit = { messageHandlers: { cuaVideo: { postMessage: (m: unknown) => w.__video.push(m) } } };
+ });
+});
+
+/** The newest report for the viewer (the full tier slot). */
+async function viewer(page: Page): Promise<Surface> {
+ return page.evaluate(() => {
+ const state = new Map<string, Surface>();
+ for (const m of (window as unknown as { __video: { type: string; update?: Surface[]; remove?: string[] }[] }).__video) {
+ if (m.type !== "surfaces") continue;
+ for (const u of m.update ?? []) state.set(u.surfaceId, u);
+ for (const id of m.remove ?? []) state.delete(id);
+ }
+ return [...state.values()].find((s) => s.tier === "full")!;
+ });
+}
+
+/** Tells the page the host's stream is live, as the host does when frames arrive. */
+async function live(page: Page, surfaceId: string) {
+ await page.evaluate((id) => window.dispatchEvent(new CustomEvent("cua:event", { detail: { event: "video.surface", payload: { surfaceId: id, state: "live" } } })), surfaceId);
+}
+
+const overlaps = (a: Surface["rect"], b: Surface["rect"]) => a.x < b.x + b.width && b.x < a.x + a.width && a.y < b.y + b.height && b.y < a.y + a.height;
+
+test("every popup on a Space's page leaves the stream drawn, the same size, with a hole where it floats", async ({ page }) => {
+ await page.goto(`${SPACE}?bridge=demo&parity`);
+ await expect(page.locator("[data-stream-surface]")).toBeVisible();
+ await expect.poll(async () => (await viewer(page))?.visible).toBe(true);
+ const before = await viewer(page);
+ await live(page, before.surfaceId);
+ expect(before.occluded).toBe(false);
+ expect(before.holes ?? []).toEqual([]);
+ expect(before.interactive).toBe(true);
+
+ /**
+ * The popup is open: the stream is still drawn at its size and place, and
+ * where the popup floats over the picture there is a hole for it (a popup
+ * that floats elsewhere, like a menu that opens over the header, needs none).
+ */
+ async function expectDrawn(name: string, popup: string, modal: boolean) {
+ const el = page.locator(popup).first();
+ await expect(el, name).toBeVisible();
+ // Reports follow layout over a few frames.
+ await page.waitForTimeout(400);
+ const box = (await el.boundingBox())!;
+ expect(box, name).not.toBeNull();
+ const now = await viewer(page);
+ const over = overlaps(box, before.rect);
+ if (over) {
+ await expect
+ .poll(async () => ((await viewer(page)).holes ?? []).some((h) => overlaps(h, box)), { message: `${name}: a hole where the popup is`, timeout: 5_000 })
+ .toBe(true);
+ }
+ const drawn = await viewer(page);
+ expect(drawn.occluded, `${name}: not hidden`).toBe(false);
+ expect(drawn.visible, `${name}: still visible`).toBe(true);
+ expect({ w: drawn.rect.width, h: drawn.rect.height }, `${name}: not resized`).toEqual({ w: before.rect.width, h: before.rect.height });
+ expect({ x: drawn.rect.x, y: drawn.rect.y }, `${name}: not moved`).toEqual({ x: before.rect.x, y: before.rect.y });
+ expect(drawn.interactive, `${name}: ${modal ? "takes no input under a modal dialog" : "stays interactive"}`).toBe(!modal);
+ void now;
+ return over;
+ }
+
+ /** The popup is closed: no holes, interactive again, same rect. */
+ async function expectClear(name: string) {
+ await expect.poll(async () => ((await viewer(page)).holes ?? []).length, { message: `${name}: holes gone`, timeout: 5_000 }).toBe(0);
+ const now = await viewer(page);
+ expect(now.interactive, `${name}: interactive again`).toBe(true);
+ expect(now.occluded, name).toBe(false);
+ expect(now.rect, `${name}: same rect`).toEqual(before.rect);
+ }
+
+ // The profile card (a Popover): click a name in "In this Space".
+ const overlapped: string[] = [];
+ const track = async (name: string, popup: string, modal: boolean) => {
+ if (await expectDrawn(name, popup, modal)) overlapped.push(name);
+ };
+ await page.locator("[data-profile-trigger='claude']").first().click();
+ await track("profile card", "[data-profile-card='agent']", false);
+ // A menu opened from inside the card: the rights listbox in its Details.
+ await page.locator("[data-card-details]").click();
+ const rights = page.locator("[data-profile-card='agent'] [role='combobox'], [data-profile-card='agent'] button[aria-haspopup='listbox']").first();
+ if (await rights.count()) {
+ await rights.click();
+ await track("member row menu", "[role='listbox']", false);
+ await page.keyboard.press("Escape");
+ }
+ await page.keyboard.press("Escape");
+ await expect(page.locator("[data-profile-card='agent']")).toHaveCount(0);
+ await expectClear("profile card closed");
+
+ // The header's ⋯ menu.
+ await page.locator("[data-header-more]").click();
+ await track("⋯ menu", "[role='menu']", false);
+ await page.keyboard.press("Escape");
+ await expectClear("⋯ menu closed");
+
+ // A tooltip (hover the picture-in-picture button).
+ await page.locator("[data-pip]").first().hover();
+ await track("tooltip", "[data-video-occluder]:not([role='dialog'])", false);
+ await page.mouse.move(5, 5);
+ await expectClear("tooltip closed");
+
+ // More (the rail's Details sheet): a modal dialog.
+ await page.locator("[data-call-more]").click();
+ await track("More", "[data-call-more-sheet]", true);
+ await page.keyboard.press("Escape");
+ await expectClear("More closed");
+
+ // Share: a modal dialog.
+ await page.locator("[data-share-space]").first().click();
+ await track("Share", "[role='dialog']:not([data-profile-card])", true);
+ await page.keyboard.press("Escape");
+ await expectClear("Share closed");
+
+ // The check means something only if popups really floated over the picture.
+ expect(overlapped, "popups that floated over the picture").toEqual(expect.arrayContaining(["profile card", "More", "Share"]));
+});
diff --git a/apps/cua-spaces-web/src/__tests__/agent-failure.test.tsx b/apps/cua-spaces-web/src/__tests__/agent-failure.test.tsx
new file mode 100644
index 0000000000..1f39fd2fea
--- /dev/null
+++ b/apps/cua-spaces-web/src/__tests__/agent-failure.test.tsx
@@ -0,0 +1,88 @@
+// SPDX-License-Identifier: FSL-1.1-MIT
+// Copyright (c) 2026 Cua AI, Inc.
+
+// An agent that is not connected (CUA-2638): its reply says so in plain
+// words with Connect and Retry, the complete error is under Show details,
+// the person's own message is not marked Failed, and the member list shows
+// the same, uncut.
+
+import { act, cleanup, fireEvent, waitFor } from "@testing-library/react";
+import { afterEach, describe, expect, it } from "vitest";
+
+import { DEMO_THREAD_SPACE } from "@/bridge/adapters/demo/thread";
+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)}`;
+const host = { failsCreates: false, listsGhost: false, demo: { threadAuthFailed: true } };
+
+describe("an agent that is not connected", () => {
+ it("answers in plain words with Connect and Retry, never as the raw error, and the person's message is not marked Failed", async () => {
+ await mountApp(path, host);
+ const failed = await waitFor(
+ () => {
+ const t = qa('[data-task-state="failed"]');
+ expect(t.length).toBe(2);
+ return t;
+ },
+ { timeout: 5000 },
+ );
+ const claude = failed.find((t) => t.textContent?.includes("@claude hi"))!;
+ // The person's own message carries no Failed chip; only the agent's reply is marked.
+ expect(claude.querySelector("[data-entry] [data-task-chip='failed']")?.closest("[data-task-replies]")).not.toBeNull();
+ const own = claude.querySelector(":scope > [data-entry]")!;
+ expect(own.querySelector("[data-task-chip]")).toBeNull();
+ const reply = claude.querySelector("[data-task-replies] [data-entry]")!;
+ expect(reply.querySelector("[data-task-chip='failed']")).not.toBeNull();
+ expect(reply.textContent).toContain("I can't reach Claude yet. Connect Claude, then try again.");
+ expect(reply.textContent).not.toMatch(/401|authentication_error|OAuth/);
+ // Connect opens Settings, Connectors on the app; Retry is there too.
+ const connect = reply.querySelector<HTMLAnchorElement>("[data-failure-connect]")!;
+ expect(connect.getAttribute("href")).toBe("/settings/connectors/claude-code");
+ expect(reply.querySelector("[data-failure-retry]")).not.toBeNull();
+ // No middle dot anywhere in what the failure draws.
+ expect(claude.textContent).not.toContain("·");
+ });
+
+ it("keeps the complete error under Show details, selectable, with Copy", async () => {
+ await mountApp(path, host);
+ const reply = await waitFor(
+ () => {
+ const t = qa('[data-task-state="failed"]').find((x) => x.textContent?.includes("@claude hi"));
+ const r = t?.querySelector("[data-task-replies] [data-entry]");
+ expect(r).toBeTruthy();
+ return r as HTMLElement;
+ },
+ { timeout: 5000 },
+ );
+ expect(reply.querySelector("[data-failure-message]")).toBeNull();
+ await act(async () => {
+ fireEvent.click(reply.querySelector("[data-failure-details]")!);
+ });
+ const text = reply.querySelector("[data-failure-message]")!.textContent!;
+ // Whole: the end of the provider's message is there, not clipped.
+ expect(text).toContain("API Error: 401");
+ expect(text).toContain("refresh your existing token.");
+ expect(reply.querySelector("[data-failure-message]")!.className).toContain("select-text");
+ expect(reply.querySelector("[data-failure-copy]")).not.toBeNull();
+ });
+
+ it("shows a failed member's reason whole in the member list", async () => {
+ await mountApp(path, host);
+ const row = await waitFor(
+ () => {
+ const r = q("[data-member='agent:hermes']");
+ expect(r?.dataset.memberStatus).toBe("failed");
+ return r!;
+ },
+ { timeout: 5000 },
+ );
+ const caption = row.querySelector<HTMLElement>("[data-member-caption]")!;
+ expect(caption.textContent).toBe("Not connected");
+ expect(caption.className).not.toContain("truncate");
+ });
+});
diff --git a/apps/cua-spaces-web/src/bridge/adapters/demo.ts b/apps/cua-spaces-web/src/bridge/adapters/demo.ts
index 8b3c90e124..7240690562 100644
--- a/apps/cua-spaces-web/src/bridge/adapters/demo.ts
+++ b/apps/cua-spaces-web/src/bridge/adapters/demo.ts
@@ -129,6 +129,8 @@ export interface DemoOptions {
threadRole?: "member" | "guest";
/** Extra scenes in the demo's thread: `?demo=thread-lookalike` (CUA-2262). */
threadLookalike?: boolean;
+ /** `?demo=thread-auth-failed`: Claude and Hermes answer "hi" with "not connected" (CUA-2638). */
+ threadAuthFailed?: boolean;
/** Join codes: redeemed this long after they are made (null: never, `?demo=thread-join-slow`). */
joinRedeemMs?: number | null;
/** Join codes expire this long after they are made (`?demo=thread-join-expire`). */
@@ -212,6 +214,7 @@ export function demoOptionsFromSearch(search: string): DemoOptions {
noThread: flags.has("nothread"),
...(flags.has("thread-guest") ? { threadRole: "guest" as const } : flags.has("thread-member") ? { threadRole: "member" as const } : {}),
threadLookalike: flags.has("thread-lookalike"),
+ threadAuthFailed: flags.has("thread-auth-failed"),
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 } : {}),
@@ -886,7 +889,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,
+ ...demoThreadHandlers({ now, wait, stepMs: step, enabled: !options.noThread, role: options.threadRole ?? "owner", lookalike: options.threadLookalike ?? false, authFailed: options.threadAuthFailed ?? 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 e5fdc3a9dc..c92146d772 100644
--- a/apps/cua-spaces-web/src/bridge/adapters/demo/thread.ts
+++ b/apps/cua-spaces-web/src/bridge/adapters/demo/thread.ts
@@ -154,6 +154,8 @@ interface DemoMember {
sessions: number;
rights: AgentRights;
identity: DemoIdentity;
+ /** A failed member's typed failure (the daemon's `status.failure`). */
+ failure?: Json;
}
export type DemoThreadRole = "owner" | "member" | "guest";
@@ -272,7 +274,7 @@ function demoSideThreads(now: number, me: { id: string; name: string }): [string
];
}
-function demoConversation(now: number, owner: { id: string; name: string }, opts: { lookalike?: boolean } = {}): DemoThread {
+function demoConversation(now: number, owner: { id: string; name: string }, opts: { lookalike?: boolean; authFailed?: 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] });
@@ -350,6 +352,36 @@ function demoConversation(now: number, owner: { id: string; name: string }, opts
{ name: "hermes", harness: "hermes", status: "asleep", activity: null, sessions: 1, rights: { ...DEFAULT_AGENT_RIGHTS, task: "owner" }, identity: ids.hermes! },
{ name: "cursor", harness: "cursor", status: "idle", activity: null, sessions: 1, rights: { ...DEFAULT_AGENT_RIGHTS, approve: [LINUS.id] }, identity: ids.cursor! },
];
+ if (opts.authFailed) {
+ // What the daemon posts when an agent has no working sign-in: plain words and the typed failure (CUA-2638).
+ const asked = (text: string, handle: string, ts: number) =>
+ add({ ts_ms: ts, author: DEMO_THREAD_ME, text, mentions: [handle], task: { to: handle, session: null } });
+ const failed = (task: number, ts: number, who: ReturnType<typeof agent>, text: string, failure: Json) => {
+ add({ ts_ms: ts, author: who, reply_to: task, text, failure });
+ update(ts, task, "failed", 1, "could not start " + who.name);
+ };
+ const hi = asked("@claude hi", "claude", min(2));
+ failed(hi, min(2), CLAUDE, "I can't reach Claude yet. Connect Claude, then try again.", {
+ class: "needs_connect",
+ provider: "anthropic",
+ retryable: true,
+ message: 'Internal error: Failed to authenticate. API Error: 401 {"type":"error","error":{"type":"authentication_error","message":"OAuth token has expired. Please obtain a new token or refresh your existing token."}}',
+ });
+ const hey = asked("@hermes hey", "hermes", min(1));
+ failed(hey, min(1), HERMES, "I can't reach Claude yet. Connect Claude, then try again.", {
+ class: "needs_connect",
+ provider: "anthropic",
+ retryable: true,
+ message: 'Internal error (code -32603) {"details":"Hermes is not connected to any AI provider. Run `hermes model` to set one up, or add an API key."}',
+ });
+ for (const m of members) {
+ if (m.name === "claude" || m.name === "hermes") {
+ m.status = "failed";
+ m.activity = "Not connected";
+ m.failure = { class: "needs_connect", provider: "anthropic", retryable: true, message: "Failed to authenticate. API Error: 401" };
+ }
+ }
+ }
if (opts.lookalike) {
// Linus's agent names itself Claude Code: both now show their owner after the tag.
ids.claude!.collides = true;
@@ -380,6 +412,7 @@ export function demoThreadHandlers({
enabled,
role = "owner",
lookalike = false,
+ authFailed = false,
joinRedeemMs,
joinExpireMs,
request = false,
@@ -391,6 +424,8 @@ export function demoThreadHandlers({
role?: DemoThreadRole;
/** `?demo=thread-lookalike`: Linus's agent that calls itself Claude Code. */
lookalike?: boolean;
+ /** `?demo=thread-auth-failed`: Claude and Hermes answer with a typed "not connected" failure. */
+ authFailed?: 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. */
@@ -399,7 +434,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 })], ...(role === "owner" ? demoSideThreads(now(), DEMO_THREAD_ME) : [])]);
+ const threads = new Map<string, DemoThread>([[DEMO_THREAD_SPACE, demoConversation(now(), owner, { lookalike, authFailed })], ...(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" };
@@ -483,11 +518,11 @@ export function demoThreadHandlers({
};
const youCan = (m: DemoMember) =>
Object.fromEntries((["task", "control", "approve"] as const).map((r) => [r, demoHolds(m.rights[r], role, DEMO_THREAD_ME.id)])) as Record<AgentRight, boolean>;
- const memberJson = ({ activity, rights, ...m }: DemoMember) => ({
+ const memberJson = ({ activity, rights, failure, ...m }: DemoMember) => ({
...m,
rights,
you_can: youCan({ activity, rights, ...m }),
- status: activity ? { state: m.status, activity } : { state: m.status },
+ status: { state: m.status, ...(activity ? { activity } : {}), ...(failure ? { failure } : {}) },
});
const denied = (message: string) => new HostError(message, "permission_denied");
const GUEST = "view only: guests can read this thread but cannot post, answer or claim tasks";
diff --git a/apps/cua-spaces-web/src/bridge/agent-keys.ts b/apps/cua-spaces-web/src/bridge/agent-keys.ts
index 8f82c528c6..d8b8d1f175 100644
--- a/apps/cua-spaces-web/src/bridge/agent-keys.ts
+++ b/apps/cua-spaces-web/src/bridge/agent-keys.ts
@@ -23,7 +23,7 @@ import type { AgentKeyProvider, AgentKeysReport } from "./ops/agent-keys";
/** What the section shows (`agent_keys::AgentKeysInput`). */
export interface AgentKeysInput {
- keys: { provider: string; env: string; last4: string; addedMs: number }[];
+ keys: { provider: string; env: string; last4: string; addedMs: number; expired?: boolean }[];
unavailable?: string | null;
error?: string | null;
}
@@ -83,7 +83,7 @@ export interface AgentKeyConfirm {
}
export const agentKeysInputOf = (report: AgentKeysReport | undefined, error: Error | null): AgentKeysInput => ({
- keys: (report?.keys ?? []).map(({ provider, env, last4, addedMs }) => ({ provider, env, last4, addedMs })),
+ keys: (report?.keys ?? []).map(({ provider, env, last4, addedMs, expired }) => ({ provider, env, last4, addedMs, ...(expired ? { expired: true } : {}) })),
unavailable: report?.available === false ? (report.unavailable ?? "this machine can't keep keys") : null,
error: error ? error.message : null,
});
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 7cb55dc848..1e4b73efd7 100644
--- a/apps/cua-spaces-web/src/bridge/contracts/bridge-shapes.json
+++ b/apps/cua-spaces-web/src/bridge/contracts/bridge-shapes.json
@@ -195,6 +195,9 @@
},
"addedMs": {
"type": "number"
+ },
+ "expired": {
+ "type": "boolean"
}
},
"required": [
@@ -254,6 +257,9 @@
"name": {
"type": "string"
},
+ "handle": {
+ "type": "string"
+ },
"harness": {
"type": "string"
},
@@ -266,6 +272,38 @@
"null"
]
},
+ "failure": {
+ "type": [
+ "object",
+ "null"
+ ],
+ "properties": {
+ "class": {
+ "enum": [
+ "needs_connect",
+ "error"
+ ]
+ },
+ "provider": {
+ "type": [
+ "string",
+ "null"
+ ]
+ },
+ "message": {
+ "type": "string"
+ },
+ "retryable": {
+ "type": "boolean"
+ }
+ },
+ "required": [
+ "class",
+ "provider",
+ "message",
+ "retryable"
+ ]
+ },
"sessions": {
"type": "number"
},
@@ -5499,6 +5537,38 @@
"title",
"windowId"
]
+ },
+ "failure": {
+ "type": [
+ "object",
+ "null"
+ ],
+ "properties": {
+ "class": {
+ "enum": [
+ "needs_connect",
+ "error"
+ ]
+ },
+ "provider": {
+ "type": [
+ "string",
+ "null"
+ ]
+ },
+ "message": {
+ "type": "string"
+ },
+ "retryable": {
+ "type": "boolean"
+ }
+ },
+ "required": [
+ "class",
+ "provider",
+ "message",
+ "retryable"
+ ]
}
},
"required": [
@@ -9088,6 +9158,9 @@
},
"added_ms": {
"type": "number"
+ },
+ "expired": {
+ "type": "boolean"
}
},
"required": [
@@ -9154,6 +9227,9 @@
},
"added_ms": {
"type": "number"
+ },
+ "expired": {
+ "type": "boolean"
}
},
"required": [
@@ -9220,6 +9296,9 @@
},
"added_ms": {
"type": "number"
+ },
+ "expired": {
+ "type": "boolean"
}
},
"required": [
@@ -9286,6 +9365,9 @@
},
"added_ms": {
"type": "number"
+ },
+ "expired": {
+ "type": "boolean"
}
},
"required": [
diff --git a/apps/cua-spaces-web/src/bridge/contracts/shapes.ts b/apps/cua-spaces-web/src/bridge/contracts/shapes.ts
index e9fe15c65d..2657bdbf77 100644
--- a/apps/cua-spaces-web/src/bridge/contracts/shapes.ts
+++ b/apps/cua-spaces-web/src/bridge/contracts/shapes.ts
@@ -73,7 +73,7 @@ import type { HostChecklistState } from "../ops/checklist";
import type { TipsState } from "./spaces-page";
import type { ShareLink } from "../ops/links";
import type { CliInstallPlan } from "./first-run";
-import type { AgentMember, JoinCode, JoinCodeRow, MemberIdentity, ThreadAttachment, ThreadAuthor, ThreadEntry, ThreadPage } from "../ops/thread";
+import type { AgentMember, JoinCode, JoinCodeRow, MemberIdentity, ThreadAttachment, ThreadAuthor, ThreadEntry, ThreadFailure, ThreadPage } from "../ops/thread";
import type { PresenceCursorWire, PresenceJoinInfo, PresenceParticipantWire } from "../ops/presence";
import type { StartupState } from "../ops/startup";
import type { StreamTicket } from "../ops/stream";
@@ -543,7 +543,7 @@ const NotificationShape = ref(
const AgentKeysShape = ref(
"AgentKeysReport",
obj<AgentKeysReport>()({
- keys: list(object({ provider: oneOf("anthropic", "openai", "other"), env: str, last4: str, addedMs: num })),
+ keys: list(object({ provider: oneOf("anthropic", "openai", "other"), env: str, last4: str, addedMs: num, expired: opt(bool) })),
providers: list(object({ id: oneOf("anthropic", "openai", "other"), label: str, env: str })),
available: bool,
unavailable: nullable(str),
@@ -931,6 +931,7 @@ const MemberIdentityShape = ref(
/** One Space thread entry as the page reads it (`ops/thread.ts`, DESIGN §3.2). */
const taskState = oneOf("queued", "claimed", "working", "done", "failed");
+const ThreadFailureShape = obj<ThreadFailure>()({ class: oneOf("needs_connect", "error"), provider: nullable(str), message: str, retryable: bool });
const ThreadEntryShape = ref(
"ThreadEntry",
obj<ThreadEntry>()({
@@ -956,6 +957,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)),
}),
);
@@ -986,9 +988,11 @@ const AgentMemberShape = ref(
"AgentMember",
obj<AgentMember>()({
name: str,
+ handle: opt(str),
harness: str,
status: str,
activity: nullable(str),
+ failure: opt(nullable(ThreadFailureShape)),
sessions: num,
rights: nullable(object({ task: rightHolders, control: rightHolders, approve: rightHolders })),
youCan: nullable(object({ task: bool, control: bool, approve: bool })),
@@ -1621,7 +1625,7 @@ const WkMachinesShape = ref(
/** The daemon's `agent_keys.*` answer, which `agentKeysFromWire` reads. */
const AgentKeysWire = object({
- keys: list(object({ provider: str, env: str, last4: str, added_ms: num })),
+ keys: list(object({ provider: str, env: str, last4: str, added_ms: num, expired: opt(bool) })),
providers: list(object({ id: str, env: str, label: opt(str) })),
available: bool,
unavailable: optNull(str),
diff --git a/apps/cua-spaces-web/src/bridge/index.ts b/apps/cua-spaces-web/src/bridge/index.ts
index b379a3cf05..f238dc3700 100644
--- a/apps/cua-spaces-web/src/bridge/index.ts
+++ b/apps/cua-spaces-web/src/bridge/index.ts
@@ -180,6 +180,7 @@ export {
type ThreadAttachment,
type ThreadAuthor,
type ThreadEntry,
+ type ThreadFailure,
type ThreadView,
type ThreadPage,
type ThreadRole,
diff --git a/apps/cua-spaces-web/src/bridge/ops/agent-keys.ts b/apps/cua-spaces-web/src/bridge/ops/agent-keys.ts
index 7959ea5fde..df512d0216 100644
--- a/apps/cua-spaces-web/src/bridge/ops/agent-keys.ts
+++ b/apps/cua-spaces-web/src/bridge/ops/agent-keys.ts
@@ -38,6 +38,8 @@ export interface AgentKeyInfo {
last4: string;
/** When it was added (Unix ms). */
addedMs: number;
+ /** A sign-in past its expiry: no run gets it until it is reconnected. */
+ expired?: boolean;
}
/** A provider row (`keys::Provider`). */
@@ -124,7 +126,7 @@ export function agentKeysFromWire(raw: unknown): AgentKeysReport {
const env = str(r.env);
if (!env) return [];
const added = r.added_ms ?? r.addedMs;
- return [{ provider: providerOf(r.provider), env, last4: str(r.last4).slice(-4), addedMs: typeof added === "number" ? added : 0 }];
+ return [{ provider: providerOf(r.provider), env, last4: str(r.last4).slice(-4), addedMs: typeof added === "number" ? added : 0, ...(r.expired === true ? { expired: true } : {}) }];
});
const providers = (Array.isArray(o.providers) ? o.providers : []).flatMap((p): AgentKeyProviderRow[] => {
const r = (p ?? {}) as Record<string, unknown>;
diff --git a/apps/cua-spaces-web/src/bridge/ops/thread.ts b/apps/cua-spaces-web/src/bridge/ops/thread.ts
index b7517c376b..16d43c7220 100644
--- a/apps/cua-spaces-web/src/bridge/ops/thread.ts
+++ b/apps/cua-spaces-web/src/bridge/ops/thread.ts
@@ -117,6 +117,18 @@ export interface ThreadAttachment {
mime: string | null;
}
+/** What failed in an agent's turn or start, typed (`cua_agents::failure::Failure`). */
+export interface ThreadFailure {
+ /** `needs_connect`: no working credential, connect (or reconnect) one; `error`: anything else. */
+ class: "needs_connect" | "error";
+ /** For `needs_connect`: the Connectors row that fixes it (`anthropic`, `openai`). */
+ provider: string | null;
+ /** The complete error as the harness or provider said it (for Show details; never the summary). */
+ message: string;
+ /** Sending the same message again can work. */
+ retryable: boolean;
+}
+
export interface ThreadEntry {
seq: number;
id: string;
@@ -146,6 +158,8 @@ export interface ThreadEntry {
joinRequest?: JoinRequest | null;
/** What the person was looking at in the Space as they posted (`view`): its desktop or a window. */
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;
}
/** `thread_post`'s `view` and every entry's: the Space's desktop, or one of its windows (`cua.env.v1.ThreadView`). */
@@ -189,11 +203,15 @@ export type AgentMemberStatus = string;
export interface AgentMember {
name: string;
+ /** What the Space calls it (`@claude`) when that is not `name` (a second Space's `claude` is stored as `claude-2`). */
+ handle?: string;
/** Harness id (`claude-code`, `hermes`, ...). */
harness: string;
status: AgentMemberStatus;
/** What it is doing, in a few words ("running e2e suite"), when it says. */
activity: string | null;
+ /** For a failed member: what failed, typed, with the complete text. */
+ failure?: ThreadFailure | null;
/** Sessions it runs (P2 shows each). */
sessions: number;
/** Its rights (null from a daemon without them: the defaults apply). */
@@ -601,6 +619,19 @@ export function threadEntryFromTool(v: unknown): ThreadEntry | null {
event: kind === "system" ? memberEvent(e.event) : null,
...(kind === "join_request" ? { joinRequest: joinRequest(e) } : {}),
...(e.view != null ? { view: threadViewFromTool(e.view) } : {}),
+ ...(e.failure != null ? { failure: threadFailure(e.failure) } : {}),
+ };
+}
+
+/** A typed failure (`failure` of an entry, or of a failed member's status). */
+export function threadFailure(v: unknown): ThreadFailure | null {
+ const f = obj(v);
+ if (!f) return null;
+ return {
+ class: f.class === "needs_connect" ? "needs_connect" : "error",
+ provider: str(f.provider) || null,
+ message: str(f.message),
+ retryable: f.retryable !== false,
};
}
@@ -746,10 +777,12 @@ function agentMember(r: unknown): AgentMember[] {
return [
{
name,
+ ...(str(m.handle) && str(m.handle) !== name ? { handle: str(m.handle) } : {}),
harness: str(m.harness),
// `status` is a word, or `{state, activity}`.
status: (status ? str(status.state) : str(m.status)) || "idle",
activity: (status ? str(status.activity) : str(m.activity)) || null,
+ ...(status && status.failure != null ? { failure: threadFailure(status.failure) } : {}),
sessions: num(m.sessions) ?? 1,
rights: rights(m.rights),
youCan: youCan(m.you_can),
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 6a905f8fe4..4f8da26e94 100644
--- a/apps/cua-spaces-web/src/components/agents/agent-chat.tsx
+++ b/apps/cua-spaces-web/src/components/agents/agent-chat.tsx
@@ -319,7 +319,7 @@ export function AgentDmView({ chat, space, onSpace, identity, onInfo, me }: { ch
<>
{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) => (
- <DmRow key={`${d.spaceId}${d.item.key}`} d={d} roster={rosters[d.spaceId]!} spaces={chat.spaces} multi={multi && !space} onAnswer={(seq, ok) => dm.answer(d.spaceId, seq, ok)} onOpenAttachment={openAttachment} />
+ <DmRow key={`${d.spaceId}${d.item.key}`} d={d} 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)} />
))}
</>
)}
@@ -345,11 +345,11 @@ export function AgentDmView({ chat, space, onSpace, identity, onInfo, me }: { ch
);
}
-function DmRow({ d, roster, spaces, multi, onAnswer, onOpenAttachment }: { d: DmItem; roster: Roster; spaces: AgentChatSpace[]; multi: boolean; onAnswer: (seq: number, ok: boolean) => Promise<void>; onOpenAttachment: (a: ThreadAttachment) => void }) {
+function DmRow({ d, roster, spaces, multi, onAnswer, onOpenAttachment, onRetry }: { d: DmItem; roster: Roster; spaces: AgentChatSpace[]; multi: boolean; onAnswer: (seq: number, ok: boolean) => Promise<void>; onOpenAttachment: (a: ThreadAttachment) => void; onRetry: (text: string) => Promise<void> }) {
const s = spaces.find((x) => x.spaceId === d.spaceId);
// Every message says its Space when the DM shows several.
const label = multi && s ? <SpaceLabel name={s.spaceName} os={s.os} /> : undefined;
- return <ThreadItemView item={d.item} roster={roster} onAnswer={onAnswer} onOpenAttachment={onOpenAttachment} label={label} />;
+ return <ThreadItemView item={d.item} roster={roster} onAnswer={onAnswer} onOpenAttachment={onOpenAttachment} onRetry={onRetry} label={label} />;
}
function SpaceLabel({ name, os }: { name: string; os: AgentChatSpace["os"] }) {
diff --git a/apps/cua-spaces-web/src/components/space-thread/failure-note.tsx b/apps/cua-spaces-web/src/components/space-thread/failure-note.tsx
new file mode 100644
index 0000000000..1546c31b03
--- /dev/null
+++ b/apps/cua-spaces-web/src/components/space-thread/failure-note.tsx
@@ -0,0 +1,142 @@
+// SPDX-License-Identifier: FSL-1.1-MIT
+// Copyright (c) 2026 Cua AI, Inc.
+
+import { CheckIcon, ChevronRightIcon, CopyIcon, Loader2Icon, PlugIcon, RotateCcwIcon } from "lucide-react";
+import { useState } from "react";
+import { Link } from "@tanstack/react-router";
+
+import type { ThreadFailure } from "@/bridge";
+import { Button } from "@/components/ui/button";
+import { useConnectors } from "@/hooks/use-connectors";
+import { cn } from "@/lib/utils";
+
+/** The Connectors app page that gives a harness its sign-in. */
+const HARNESS_APP: Record<string, string> = { "claude-code": "claude-code", "openai-codex": "codex", hermes: "hermes" };
+const PROVIDER_APP: Record<string, string> = { anthropic: "claude-code", openai: "codex" };
+
+/** The Connectors app a failed agent's Connect opens: its own harness first, else the provider's. */
+export function failureApp(harness: string, provider: string | null): string | null {
+ return HARNESS_APP[harness] ?? (provider ? (PROVIDER_APP[provider] ?? null) : null);
+}
+
+/**
+ * What sits under an agent's failed reply (the reply's own text is the plain
+ * words): Connect and Retry when it needs a sign-in, Retry for any other
+ * failure, and Show details with the complete error, selectable, with Copy.
+ * The raw error is never the summary and is never cut.
+ */
+export function FailureNote({
+ failure,
+ harness,
+ taskText,
+ onRetry,
+}: {
+ failure: ThreadFailure;
+ /** The failed agent's harness id. */
+ harness: string;
+ /** The message the agent was asked (re-sent by Retry). */
+ taskText: string | null;
+ onRetry?: (text: string) => Promise<void>;
+}) {
+ const needsConnect = failure.class === "needs_connect";
+ return (
+ <div data-failure={failure.class} className="mt-1.5">
+ <div className="flex flex-wrap items-center gap-2">
+ {needsConnect ? <ConnectActions harness={harness} provider={failure.provider} taskText={taskText} onRetry={onRetry} /> : <RetryButton taskText={taskText} onRetry={failure.retryable ? onRetry : undefined} enabled />}
+ <Details message={failure.message} />
+ </div>
+ </div>
+ );
+}
+
+function ConnectActions({ harness, provider, taskText, onRetry }: { harness: string; provider: string | null; taskText: string | null; onRetry?: (text: string) => Promise<void> }) {
+ const c = useConnectors();
+ const app = failureApp(harness, provider);
+ const connected = app ? c.view?.apps.find((a) => a.agent === app)?.state === "connected" : false;
+ return (
+ <>
+ <Button size="sm" variant="outline" data-failure-connect="" render={app ? <Link to="/settings/connectors/$app" params={{ app }} /> : <Link to="/settings/connectors" />}>
+ <PlugIcon /> Connect
+ </Button>
+ <RetryButton taskText={taskText} onRetry={onRetry} enabled={connected} />
+ </>
+ );
+}
+
+/** Sends the same message again, once. */
+function RetryButton({ taskText, onRetry, enabled }: { taskText: string | null; onRetry?: (text: string) => Promise<void>; enabled: boolean }) {
+ const [state, setState] = useState<"idle" | "sending" | "sent">("idle");
+ const [error, setError] = useState<string | null>(null);
+ if (!onRetry || !taskText) return null;
+ if (state === "sent")
+ return (
+ <span data-failure-retried="" className="inline-flex items-center gap-1.5 text-xs text-muted-foreground">
+ <CheckIcon className="size-3.5 text-success" /> Sent again
+ </span>
+ );
+ return (
+ <>
+ <Button
+ size="sm"
+ variant="outline"
+ data-failure-retry=""
+ disabled={!enabled || state === "sending"}
+ onClick={() => {
+ setState("sending");
+ setError(null);
+ onRetry(taskText).then(
+ () => setState("sent"),
+ (e: unknown) => {
+ setState("idle");
+ setError(e instanceof Error ? e.message : String(e));
+ },
+ );
+ }}
+ >
+ {state === "sending" ? <Loader2Icon className="animate-spin" /> : <RotateCcwIcon />} Retry
+ </Button>
+ {error ? <span className="text-xs text-destructive">{error}</span> : null}
+ </>
+ );
+}
+
+/** "Show details": the complete error, selectable, with Copy. */
+function Details({ message }: { message: string }) {
+ const [open, setOpen] = useState(false);
+ const [copied, setCopied] = useState(false);
+ if (!message) return null;
+ return (
+ <>
+ <button
+ type="button"
+ aria-expanded={open}
+ data-failure-details=""
+ onClick={() => setOpen(!open)}
+ className="flex cursor-default items-center gap-1 rounded-lg px-1 py-0.5 text-xs text-muted-foreground outline-none hover:text-foreground focus-visible:ring-2 focus-visible:ring-ring/60"
+ >
+ <ChevronRightIcon className={cn("size-3 transition-transform", open && "rotate-90")} />
+ {open ? "Hide details" : "Show details"}
+ </button>
+ {open ? (
+ <div data-failure-details-open="" className="basis-full rounded-lg bg-muted/60 px-3 py-2">
+ <pre data-failure-message="" className="font-mono text-[11.5px] leading-[1.5] break-words whitespace-pre-wrap text-foreground select-text">
+ {message}
+ </pre>
+ <Button
+ size="sm"
+ variant="ghost"
+ data-failure-copy=""
+ className="mt-1 -ml-2"
+ onClick={() => {
+ void navigator.clipboard?.writeText(message).catch(() => undefined);
+ setCopied(true);
+ setTimeout(() => setCopied(false), 1200);
+ }}
+ >
+ {copied ? <CheckIcon /> : <CopyIcon />} {copied ? "Copied" : "Copy"}
+ </Button>
+ </div>
+ ) : null}
+ </>
+ );
+}
diff --git a/apps/cua-spaces-web/src/components/space-thread/members-panel.tsx b/apps/cua-spaces-web/src/components/space-thread/members-panel.tsx
index 64c99d1374..65cedc9d74 100644
--- a/apps/cua-spaces-web/src/components/space-thread/members-panel.tsx
+++ b/apps/cua-spaces-web/src/components/space-thread/members-panel.tsx
@@ -259,7 +259,12 @@ function Row({
{mark}
<span className="min-w-0 flex-1">
<span className={dim ? "block truncate text-[13px] text-muted-foreground" : "block truncate text-[13px]"}>{label}</span>
- {caption ? <span className="block truncate text-[11px] text-muted-foreground">{caption}</span> : null}
+ {/* A failed agent's reason is shown whole (wrapped, selectable), never cut with an ellipsis. */}
+ {caption ? (
+ <span data-member-caption="" className={cn("block text-[11px] text-muted-foreground", status === "failed" ? "break-words select-text" : "truncate")}>
+ {caption}
+ </span>
+ ) : null}
</span>
</>
);
diff --git a/apps/cua-spaces-web/src/components/space-thread/roster-handle.test.ts b/apps/cua-spaces-web/src/components/space-thread/roster-handle.test.ts
new file mode 100644
index 0000000000..b14b390fa2
--- /dev/null
+++ b/apps/cua-spaces-web/src/components/space-thread/roster-handle.test.ts
@@ -0,0 +1,42 @@
+// SPDX-License-Identifier: FSL-1.1-MIT
+// Copyright (c) 2026 Cua AI, Inc.
+
+import { describe, expect, it } from "vitest";
+
+import type { AgentMember } from "@/bridge";
+
+import { buildRoster } from "./roster";
+
+const member = (over: Partial<AgentMember>): AgentMember =>
+ ({
+ name: "claude",
+ harness: "claude-code",
+ status: "idle",
+ activity: null,
+ sessions: 1,
+ rights: null,
+ ...over,
+ }) as AgentMember;
+
+describe("a Space's @claude when another Space has the plain name", () => {
+ it("answers to the handle the Space knows it by, not the key it is stored under", () => {
+ const roster = buildRoster({
+ members: [member({ name: "claude-2", handle: "claude" })],
+ shares: [],
+ entries: [],
+ me: null,
+ identity: null,
+ harnessName: () => "Claude Code",
+ });
+ expect(roster.handles.has("claude")).toBe(true);
+ expect(roster.handles.has("claude-2")).toBe(false);
+ expect(roster.candidates.find((c) => c.kind === "agent")?.handle).toBe("claude");
+ // Its key is still what ids and lookups use.
+ expect(roster.agents[0]).toMatchObject({ id: "agent:claude-2", name: "claude-2", handle: "claude" });
+ });
+
+ it("is its own name when the Space has no alias", () => {
+ const roster = buildRoster({ members: [member({})], shares: [], entries: [], me: null, identity: null, harnessName: () => "Claude Code" });
+ expect(roster.agents[0]!.handle).toBe("claude");
+ });
+});
diff --git a/apps/cua-spaces-web/src/components/space-thread/roster.ts b/apps/cua-spaces-web/src/components/space-thread/roster.ts
index 41c2cb20f4..0afd868031 100644
--- a/apps/cua-spaces-web/src/components/space-thread/roster.ts
+++ b/apps/cua-spaces-web/src/components/space-thread/roster.ts
@@ -32,6 +32,8 @@ export interface RosterAgent {
identity: MemberIdentity | null;
/** Another agent here uses the same name: its owner shows after the AI tag. */
collides: boolean;
+ /** What the Space calls it (`@claude`); `name` is its key on this machine (`claude-2` in a second Space). */
+ handle: string;
}
/** How an author shows in the thread. */
@@ -122,6 +124,7 @@ export function buildRoster(input: {
kind: "agent",
id: `agent:${m.name}`,
name: m.name,
+ handle: m.handle || m.name,
// The name the agent chose; without an identity, the harness's name when it is named after it.
label: m.identity?.displayName || agentLabel(m.name, m.harness, input.harnessName),
harness: m.identity?.harness.id || m.harness,
@@ -161,7 +164,7 @@ export function buildRoster(input: {
for (const a of posted.values()) add({ kind: "person", id: a.id, label: a.name, me: false }, a.id, a.name.toLowerCase());
const candidates: MentionCandidate[] = [
- ...agents.map((a) => ({ handle: a.name, label: a.label, kind: "agent" as const })),
+ ...agents.map((a) => ({ handle: a.handle, label: a.label, kind: "agent" as const })),
...people.filter((p) => !p.me).map((p) => ({ handle: p.label.toLowerCase().replace(/\s+/g, ""), label: p.label, kind: "person" as const })),
];
const labels = new Set(agents.map((a) => a.label.trim().toLowerCase()));
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 cdcf2b3b6e..7126d0d174 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
@@ -186,6 +186,7 @@ export function SpaceCall({
onAnswer={thread.answer}
onOpenAttachment={openAttachment}
onRemoveAgent={thread.removeAgent ?? undefined}
+ onRetry={(text) => summon.send(text, view ?? null)}
onReachTop={thread.hasMoreBefore ? thread.loadEarlier : undefined}
empty={
thread.status === "loading" ? 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 4fbee550a1..e2bdc8fe0b 100644
--- a/apps/cua-spaces-web/src/components/space-thread/summon.tsx
+++ b/apps/cua-spaces-web/src/components/space-thread/summon.tsx
@@ -175,7 +175,7 @@ export function useSummon({ spaceId, thread, roster, canAdd }: { spaceId: string
const connectors = useConnectors();
const input: SummonInput = useMemo(
() => ({
- members: thread.members.map((m) => ({ handle: m.name, harness: m.harness, label: roster.agents.find((a) => a.name === m.name)?.label ?? m.name })),
+ members: thread.members.map((m) => ({ handle: m.handle ?? m.name, harness: m.harness, label: roster.agents.find((a) => a.name === m.name)?.label ?? m.name })),
people: roster.people.map((p) => p.label.toLowerCase().replace(/\s+/g, "")),
canAdd: canAdd && !!data && threadOpAvailable(data.mode, "thread.agentAdd"),
connectors: connectors.input,
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 e3c0b1d224..045157fabb 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
@@ -12,6 +12,7 @@ import { mentionSegments } from "@/lib/mentions";
import { cn } from "@/lib/utils";
import { AgentTile, MemberAvatar } from "./avatar";
+import { FailureNote } from "./failure-note";
import { AgentName, AiTag, holderNames, MemberEventNote } from "./identity";
import { MentionChip, ProfileTrigger } from "./profile-card";
import { waitingFor } from "./rights";
@@ -43,6 +44,7 @@ export function ThreadView({
onOpenAttachment,
onReachTop,
onRemoveAgent,
+ onRetry,
empty,
className,
endInset = 0,
@@ -58,6 +60,8 @@ export function ThreadView({
tail?: ReactNode;
/** Removes an agent member from its card (absent: the host can't). */
onRemoveAgent?: (handle: string) => Promise<void>;
+ /** Sends a message again (a failed agent's Retry); absent: no Retry. */
+ onRetry?: (text: string) => Promise<void>;
/** Scrolled to the top: read the page before (when there is one). */
onReachTop?: () => Promise<void>;
roster: Roster;
@@ -138,7 +142,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) => (
<Fragment key={item.key}>
- <ThreadItemView item={item} roster={roster} onAnswer={onAnswer} onOpenAttachment={onOpenAttachment} onRemoveAgent={onRemoveAgent} />
+ <ThreadItemView item={item} roster={roster} onAnswer={onAnswer} onOpenAttachment={onOpenAttachment} onRemoveAgent={onRemoveAgent} onRetry={onRetry} />
{after && "entry" in item ? after(item.entry.seq) : null}
</Fragment>
))}
@@ -156,6 +160,7 @@ export const ThreadItemView = memo(function Item({
onAnswer,
onOpenAttachment,
onRemoveAgent,
+ onRetry,
label,
}: {
item: ThreadItem;
@@ -163,6 +168,7 @@ export const ThreadItemView = memo(function Item({
onAnswer: (approval: number, approve: boolean) => Promise<void>;
onOpenAttachment: (a: ThreadAttachment) => void;
onRemoveAgent?: (handle: string) => Promise<void>;
+ onRetry?: (text: string) => Promise<void>;
/** Beside each message's time (the DM's Space). */
label?: ReactNode;
}) {
@@ -188,7 +194,8 @@ export const ThreadItemView = memo(function Item({
case "task":
return (
<div data-task={item.entry.seq} data-task-state={item.state}>
- <Message entry={item.entry} {...m} status={<TaskChip state={item.state} />} footnote={keysLine(item.entry, roster)} />
+ {/* An agent that failed is marked on its own reply, never on the person's message. */}
+ <Message entry={item.entry} {...m} status={item.state === "failed" ? null : <TaskChip state={item.state} />} footnote={keysLine(item.entry, roster)} />
{item.replies.length || item.notes.length ? (
<div data-task-replies="" className="pl-10">
{[...item.notes.map((n) => ({ seq: n.entry.seq, note: n.text, entry: n.entry })), ...item.replies.map((r) => ({ seq: r.seq, note: null, entry: r }))]
@@ -199,7 +206,7 @@ export const ThreadItemView = memo(function Item({
{x.note}
</p>
) : (
- <Message key={x.seq} entry={x.entry} {...m} nested />
+ <Message key={x.seq} entry={x.entry} {...m} nested status={x.entry.failure ? <TaskChip state="failed" /> : undefined} task={{ text: item.entry.text, onRetry }} />
),
)}
</div>
@@ -248,6 +255,7 @@ function Message({
status,
footnote,
nested,
+ task,
surface = "background",
}: {
entry: ThreadEntry;
@@ -262,6 +270,8 @@ function Message({
/** A muted line under the text ("Runs on Ada's keys"). */
footnote?: string | null;
nested?: boolean;
+ /** The task this message replies to (its text, for a failed reply's Retry). */
+ task?: { text: string; onRetry?: (text: string) => Promise<void> };
}) {
const who = roster.author(entry.author);
// A person's card: the roster's entry for this author (by id, else by name).
@@ -306,6 +316,7 @@ function Message({
{status ? <span className="shrink-0">{status}</span> : null}
</div>
{entry.text ? <ThreadText text={entry.text} handles={roster.handles} /> : null}
+ {entry.failure ? <FailureNote failure={entry.failure} harness={who.harness ?? ""} taskText={task?.text ?? null} onRetry={task?.onRetry} /> : null}
{entry.view ? <ViewLine view={entry.view} /> : null}
{footnote ? (
<p data-entry-footnote="" className="mt-0.5 text-[11px] text-muted-foreground">
diff --git a/apps/cua-spaces-web/src/lib/stream-surface.test.tsx b/apps/cua-spaces-web/src/lib/stream-surface.test.tsx
index 9a91129c69..842c4ff4eb 100644
--- a/apps/cua-spaces-web/src/lib/stream-surface.test.tsx
+++ b/apps/cua-spaces-web/src/lib/stream-surface.test.tsx
@@ -127,6 +127,84 @@ describe("stream surface helpers", () => {
}
});
+ // CUA-2641: the profile card (a Popover, role "dialog", marked as a hole)
+ // counted as a dialog and hid the whole desktop while it was open.
+ it("never hides a viewer or a tile for a dialog-role popup that is a hole (the profile card)", () => {
+ const slot = document.createElement("div");
+ const card = document.createElement("div");
+ card.setAttribute("role", "dialog");
+ card.setAttribute("data-video-occluder", "");
+ document.body.append(slot, card);
+ box(card, { x: 100, y: 100, width: 200, height: 120 });
+ const clip = { x: 0, y: 0, width: 400, height: 300 };
+ for (const keep of [false, true]) {
+ expect(isOccluded(slot, clip, document, 0, keep)).toBe(false);
+ expect(videoHoles(slot, clip, document, keep)).toEqual([{ x: 100, y: 100, width: 200, height: 120 }]);
+ }
+ });
+
+ // CUA-2641: dialogs (Share, the command palette) over the Space viewer: the
+ // video stays drawn with a hole where the dialog is, its dimmed backdrop is
+ // looked through, and a Space tile still hides.
+ it("keeps the Space viewer drawn under a dialog and its backdrop, and still hides a tile", () => {
+ const slot = document.createElement("div");
+ const inner = document.createElement("span");
+ slot.append(inner);
+ const dim = document.createElement("div");
+ dim.setAttribute("data-window-dim", "");
+ const dialog = document.createElement("div");
+ dialog.setAttribute("role", "dialog");
+ document.body.append(slot, dim, dialog);
+ box(dialog, { x: 100, y: 60, width: 200, height: 160 });
+ const clip = { x: 0, y: 0, width: 400, height: 300 };
+ document.elementsFromPoint = (x, y) => (x > 100 && x < 300 && y > 60 && y < 220 ? [dialog, dim, inner, slot] : [dim, inner, slot]);
+ expect(isOccluded(slot, clip, document, 0, true)).toBe(false);
+ expect(videoHoles(slot, clip, document, true)).toEqual([{ x: 100, y: 60, width: 200, height: 160 }]);
+ // A tile keeps the old rule: the dialog hides it.
+ expect(isOccluded(slot, clip, document, 0, false)).toBe(true);
+ expect(videoHoles(slot, clip, document, false)).toEqual([]);
+ });
+
+ it("reports the viewer non-interactive, not hidden, while a modal dialog is open", () => {
+ vi.stubGlobal("innerWidth", 1000);
+ vi.stubGlobal("innerHeight", 700);
+ const posted: StreamSurfaceMessage[] = [];
+ const reporter = new VideoSlotReporter({ postMessage: (m) => posted.push(m) });
+ const viewer = document.createElement("div");
+ const tile = document.createElement("div");
+ document.body.append(viewer, tile);
+ box(viewer, { x: 10, y: 200, width: 640, height: 400 });
+ box(tile, { x: 700, y: 20, width: 232, height: 145 });
+ document.elementFromPoint = () => viewer;
+ document.elementsFromPoint = () => [viewer];
+ const stop = [
+ reporter.register(viewer, { spaceId: "b", tier: "full", interactive: true, radius: 12 }, () => {}),
+ reporter.register(tile, { spaceId: "a", tier: "tile", interactive: false, radius: 8 }, () => {}),
+ ];
+ const last = (space: string) => {
+ const m = [...posted].reverse().find((x) => x.type === "surfaces" && x.update.some((u) => u.spaceId === space)) as Extract<StreamSurfaceMessage, { type: "surfaces" }>;
+ return m.update.find((u) => u.spaceId === space)!;
+ };
+ expect(last("b")).toMatchObject({ interactive: true, occluded: false });
+ const dim = document.createElement("div");
+ dim.setAttribute("data-window-dim", "");
+ const dialog = document.createElement("div");
+ dialog.setAttribute("role", "dialog");
+ document.body.append(dim, dialog);
+ box(dialog, { x: 150, y: 260, width: 300, height: 200 });
+ document.elementsFromPoint = (x, y) => (x > 150 && x < 450 && y > 260 && y < 460 ? [dialog, dim, viewer] : [dim, viewer]);
+ reporter.flush();
+ expect(last("b")).toMatchObject({ interactive: false, occluded: false, holes: [{ x: 150, y: 260, width: 300, height: 200 }] });
+ expect(last("a")).toMatchObject({ occluded: true });
+ // Closed: the viewer takes input again.
+ dim.remove();
+ dialog.remove();
+ document.elementsFromPoint = () => [viewer];
+ reporter.flush();
+ expect(last("b")).toMatchObject({ interactive: true, occluded: false, holes: [] });
+ stop.forEach((f) => f());
+ });
+
// Regression: the Space header's "⋯" menu turned the desktop black. Base
// UI puts a transparent full-page click catcher (`data-base-ui-inert`)
// under an open menu; it hit every sample point, so the whole video hid.
diff --git a/apps/cua-spaces-web/src/lib/video-slots.ts b/apps/cua-spaces-web/src/lib/video-slots.ts
index 967172cdb2..39c4e47f79 100644
--- a/apps/cua-spaces-web/src/lib/video-slots.ts
+++ b/apps/cua-spaces-web/src/lib/video-slots.ts
@@ -49,10 +49,28 @@ export function sameSurface(a: SurfaceState | null, b: SurfaceState): boolean {
);
}
-/** Page UI that hides the video entirely when it overlaps a slot: a dialog
- * takes the keyboard and dims the page, so the video under it goes. */
+/** Page UI that hides a Space tile's video entirely when it overlaps the
+ * tile: a dialog takes the keyboard and dims the page, so the video under it
+ * goes. The Space viewer never hides for one (`keepUnderDialogs`): a dialog
+ * is a hole there, like a menu. A popover that marks itself a hole
+ * (`data-video-occluder`, a profile card) is no occluder for either. */
export const OCCLUDER_SELECTOR = ['[role="dialog"]', '[role="alertdialog"]'].join(",");
+/** The dimmed layer under a modal dialog (our Dialog and AlertDialog
+ * backdrops): it paints over the whole page, so over a viewer that keeps its
+ * video it is looked through, and the viewer takes no pointer or keys while
+ * it is open (`modalOpen`). */
+export const DIM_SELECTOR = "[data-window-dim]";
+
+/** A dialog as a hole (a viewer that keeps its video under dialogs). */
+const DIALOG_HOLE_SELECTOR = [OCCLUDER_SELECTOR, DIM_SELECTOR].join(",");
+
+/** Whether a modal dialog is open: the page dims behind it and the Space
+ * under it must take neither the pointer nor the keys. */
+export function modalOpen(doc: Document = document): boolean {
+ return doc.querySelector(`${DIM_SELECTOR}:not([data-closed]):not([data-ending-style])`) !== null;
+}
+
/**
* Small page UI that floats over a slot (menus, popovers, tooltips, toasts,
* the viewer's own key bar): the host cuts the video out under each one
@@ -229,6 +247,8 @@ export class VideoSlotReporter {
width: Math.max(0, box.width - 2 * inset),
height: Math.max(0, box.height - 2 * inset),
});
+ // The Space viewer stays drawn under every popup, card, menu, tooltip and dialog (CUA-2641); a tile hides under a dialog.
+ const keep = slot.tier === "full";
const clipRaw = visiblePart(slot.el, rect, this.win);
const clip = clipRaw ? roundRect(clipRaw) : null;
const shown = this.win.document.visibilityState !== "hidden" && clip !== null && clip.width > 0 && clip.height > 0;
@@ -236,12 +256,13 @@ export class VideoSlotReporter {
surfaceId: slot.id,
spaceId: slot.spaceId,
tier: slot.tier,
- interactive: slot.interactive,
+ // Under a modal dialog the viewer keeps playing but takes no pointer or keys.
+ interactive: slot.interactive && !(keep && modalOpen(this.win.document)),
rect,
clip,
radius: Math.max(0, slot.radius - inset),
- occluded: shown && clip ? isOccluded(slot.el, clip, this.win.document, slot.radius) : false,
- holes: shown && clip ? videoHoles(slot.el, clip, this.win.document).map(roundRect) : [],
+ occluded: shown && clip ? isOccluded(slot.el, clip, this.win.document, slot.radius, keep) : false,
+ holes: shown && clip ? videoHoles(slot.el, clip, this.win.document, keep).map(roundRect) : [],
visible: shown,
};
}
@@ -347,9 +368,11 @@ export function visiblePart(el: Element, rect: SurfaceRect, win: Window = window
* (`INERT_SELECTOR`) and the slot's own ancestors (hit when an open modal
* menu made the page `inert`) don't count.
*/
-export function isOccluded(el: Element, clip: SurfaceRect, doc: Document = document, radius = 0): boolean {
+export function isOccluded(el: Element, clip: SurfaceRect, doc: Document = document, radius = 0, keepUnderDialogs = false): boolean {
for (const o of doc.querySelectorAll(OCCLUDER_SELECTOR)) {
if (el.contains(o) || o.contains(el)) continue;
+ // A dialog-role popup that is a hole (a profile card) never hides the video, nor does any dialog over a viewer.
+ if (keepUnderDialogs || o.closest(HOLE_SELECTOR)) continue;
const r = o.getBoundingClientRect();
if (r.width > 0 && r.height > 0 && intersect(clip, { x: r.x, y: r.y, width: r.width, height: r.height })) return true;
}
@@ -365,7 +388,7 @@ export function isOccluded(el: Element, clip: SurfaceRect, doc: Document = docum
// An ancestor of the slot can't paint over it: it is what hit-testing
// reaches when the slot itself takes no hits (a modal menu makes the
// rest of the page `inert`).
- if (hit && !hit.contains(el) && !el.contains(hit) && !hit.closest(HOLE_SELECTOR)) return true;
+ if (hit && !hit.contains(el) && !el.contains(hit) && !hit.closest(keepUnderDialogs ? `${HOLE_SELECTOR},${DIALOG_HOLE_SELECTOR}` : HOLE_SELECTOR)) return true;
}
}
return false;
@@ -387,10 +410,12 @@ function topmostPainted(doc: Document, x: number, y: number): Element | null {
* viewer's key bar, a tile's checkbox and power button while they show),
* each clipped to it: the host draws no video there.
*/
-export function videoHoles(el: Element, clip: SurfaceRect, doc: Document = document): SurfaceRect[] {
+export function videoHoles(el: Element, clip: SurfaceRect, doc: Document = document, keepUnderDialogs = false): SurfaceRect[] {
const holes: SurfaceRect[] = [];
const win = doc.defaultView;
- for (const o of doc.querySelectorAll(HOLE_SELECTOR)) {
+ // Over a viewer that keeps its video under dialogs, a dialog's popup is a hole (its dimmed backdrop is not: the video shows through it).
+ const holeSelector = keepUnderDialogs ? `${HOLE_SELECTOR},${OCCLUDER_SELECTOR}` : HOLE_SELECTOR;
+ for (const o of doc.querySelectorAll(holeSelector)) {
// Floating UI inside the slot counts only when it asks (`data-video-hole`).
if (o.contains(el) || (el.contains(o) && !o.hasAttribute("data-video-hole"))) continue;
if (o.hasAttribute("data-video-hole")) {
@@ -400,7 +425,7 @@ export function videoHoles(el: Element, clip: SurfaceRect, doc: Document = docum
if (win && !showsNow(o, scope, win)) continue;
}
// One hole for a nested pair (a menu inside a marked popup).
- if (o.parentElement?.closest(HOLE_SELECTOR)) continue;
+ if (o.parentElement?.closest(holeSelector)) continue;
const r = o.getBoundingClientRect();
if (r.width <= 0 || r.height <= 0) continue;
const hole = intersect(clip, { x: r.x, y: r.y, width: r.width, height: r.height });
diff --git a/apps/cua-spaces/src-tauri/src/agents.rs b/apps/cua-spaces/src-tauri/src/agents.rs
index 0c084b4ce9..078eed6e0a 100644
--- a/apps/cua-spaces/src-tauri/src/agents.rs
+++ b/apps/cua-spaces/src-tauri/src/agents.rs
@@ -51,6 +51,7 @@ mod tests {
label: None,
repo: None,
home: None,
+ cred_hash: None,
}),
};
let run = space_agent_run(&info);
diff --git a/docs/content/docs/cua-sdk/guides/run-a-coding-agent.mdx b/docs/content/docs/cua-sdk/guides/run-a-coding-agent.mdx
index 2c9d5d8c0d..26af934a8c 100644
--- a/docs/content/docs/cua-sdk/guides/run-a-coding-agent.mdx
+++ b/docs/content/docs/cua-sdk/guides/run-a-coding-agent.mdx
@@ -235,7 +235,7 @@ print([h["id"] for h in json.loads(cua.agent_harnesses())])
| `opencode` | `ANTHROPIC_API_KEY`, `OPENAI_API_KEY`, `GEMINI_API_KEY`, `OPENROUTER_API_KEY` | `openai-chat` | |
| `goose` | `OPENAI_API_KEY`, `ANTHROPIC_API_KEY`, `GOOGLE_API_KEY`, `OPENROUTER_API_KEY` | `openai-chat` | |
| `pi` | `ANTHROPIC_API_KEY`, `OPENAI_API_KEY`, `GEMINI_API_KEY`, `OPENROUTER_API_KEY` | `openai-chat` | Community ACP adapter; no MCP client |
-| `hermes` | `OPENROUTER_API_KEY`, `ANTHROPIC_API_KEY`, `OPENAI_API_KEY` | `openai-chat` | Needs git; ignores run MCP servers |
+| `hermes` | `OPENROUTER_API_KEY`, `ANTHROPIC_API_KEY`, `CLAUDE_CODE_OAUTH_TOKEN`, `OPENAI_API_KEY` | `openai-chat` | Needs git; ignores run MCP servers; reads the Claude sign-in, not the ChatGPT one |
| `openclaw` | `ANTHROPIC_API_KEY`, `OPENAI_API_KEY`, `OPENROUTER_API_KEY` | `openai-chat` | Starts its own loopback Gateway; no per-run MCP servers |
`cua agent harnesses` (or `cua.agent_harnesses()`) prints the full record:
diff --git a/libs/cua/crates/cua-agent-setup/src/lib.rs b/libs/cua/crates/cua-agent-setup/src/lib.rs
index f73e5013fb..f65b91052d 100644
--- a/libs/cua/crates/cua-agent-setup/src/lib.rs
+++ b/libs/cua/crates/cua-agent-setup/src/lib.rs
@@ -157,6 +157,7 @@ const VARS: &[&str] = &[
"CUA_HOME",
"CLAUDE_CONFIG_DIR",
"CODEX_HOME",
+ "CUA_TOKEN_CHECK_URL",
"GEMINI_CLI_HOME",
"CLINE_DATA_DIR",
"OPENCLAW_STATE_DIR",
diff --git a/libs/cua/crates/cua-agent-setup/src/signin.rs b/libs/cua/crates/cua-agent-setup/src/signin.rs
index 8ef7ca2d3a..ec73a042da 100644
--- a/libs/cua/crates/cua-agent-setup/src/signin.rs
+++ b/libs/cua/crates/cua-agent-setup/src/signin.rs
@@ -273,14 +273,164 @@ fn claude_says_signed_out(env: &HostEnv, bin: &Path) -> bool {
/// How long `claude setup-token` waits for the browser approval.
pub const SETUP_TOKEN_WAIT: Duration = Duration::from_secs(600);
+/// The shortest string taken as a `claude setup-token` token. Real ones are
+/// about 108 characters (`sk-ant-oat01-` and 95 more); a shorter run is
+/// output cut off by a wrapped line or a redraw, and Claude answers it with
+/// a 401.
+const SETUP_TOKEN_MIN: usize = 100;
+/// The longest a token is taken to be (stops a joined line from running on).
+const SETUP_TOKEN_MAX: usize = 200;
+
+fn token_char(c: char) -> bool {
+ c.is_ascii_alphanumeric() || c == '-' || c == '_'
+}
+
+/// `s` without terminal escape sequences (colors, cursor moves, erases) and
+/// carriage returns.
+fn strip_ansi(s: &str) -> String {
+ let mut out = String::with_capacity(s.len());
+ let mut it = s.chars().peekable();
+ while let Some(c) = it.next() {
+ match c {
+ '\u{1b}' => match it.peek() {
+ // CSI: parameters, then a final byte in @..~.
+ Some('[') => {
+ it.next();
+ for d in it.by_ref() {
+ if ('@'..='~').contains(&d) {
+ break;
+ }
+ }
+ }
+ // OSC: up to BEL or ESC \.
+ Some(']') => {
+ it.next();
+ while let Some(d) = it.next() {
+ if d == '\u{7}' {
+ break;
+ }
+ if d == '\u{1b}' {
+ it.next();
+ break;
+ }
+ }
+ }
+ Some(_) => {
+ it.next();
+ }
+ None => {}
+ },
+ '\r' => {}
+ c => out.push(c),
+ }
+ }
+ out
+}
+
/// A `claude setup-token` token (`sk-ant-oat01-…`) in its output.
+///
+/// The output comes from a terminal: it holds color codes, and a token
+/// longer than the terminal is wide is wrapped onto the next line. Escape
+/// sequences are dropped, and lines that run on as one unbroken word are
+/// joined. Anything shorter than a real token is refused (`None`) rather
+/// than saved cut off.
pub fn find_setup_token(out: &str) -> Option<String> {
- let start = out.find("sk-ant-oat")?;
- let tok: String = out[start..]
+ let clean = strip_ansi(out);
+ let start = clean.find("sk-ant-oat")?;
+ let mut lines = clean[start..].lines();
+ let mut tok: String = lines
+ .next()?
.chars()
- .take_while(|c| c.is_ascii_alphanumeric() || *c == '-' || *c == '_')
+ .take_while(|c| token_char(*c))
.collect();
- (tok.len() > 20).then_some(tok)
+ // The first line ran to its end: the token goes on if the next line is
+ // one unbroken word.
+ let mut ran_to_end = clean[start..]
+ .lines()
+ .next()
+ .is_some_and(|l| l.chars().all(token_char));
+ for line in lines {
+ if !ran_to_end || tok.len() >= SETUP_TOKEN_MAX {
+ break;
+ }
+ let l = line.trim_end();
+ if l.is_empty() || !l.chars().all(token_char) {
+ break;
+ }
+ tok.push_str(l);
+ ran_to_end = true;
+ }
+ (tok.len() >= SETUP_TOKEN_MIN && tok.len() <= SETUP_TOKEN_MAX).then_some(tok)
+}
+
+/// What the provider said about a token.
+#[derive(Clone, Copy, Debug, PartialEq, Eq)]
+pub enum TokenCheck {
+ /// Accepted.
+ Valid,
+ /// Refused (401 or 403): saving it would only give every agent a 401.
+ Invalid,
+ /// No answer (offline, another status): it is saved and used.
+ Unknown,
+}
+
+/// What a status code of the provider's models list says about a token.
+fn token_check_for(status: u16) -> TokenCheck {
+ match status {
+ 200..=299 => TokenCheck::Valid,
+ 401 | 403 => TokenCheck::Invalid,
+ _ => TokenCheck::Unknown,
+ }
+}
+
+/// Asks Anthropic once whether `token` is accepted (a read-only GET of the
+/// models list, as the sign-in token the way Claude Code sends it). The token
+/// goes to `curl` on its standard input, never in its arguments. Without
+/// `run_agent_clis` nothing is asked.
+pub fn check_claude_token(env: &HostEnv, token: &str) -> TokenCheck {
+ use std::io::Write;
+ if !env.run_agent_clis {
+ return TokenCheck::Unknown;
+ }
+ let base = env
+ .var("CUA_TOKEN_CHECK_URL")
+ .map(|b| b.trim_end_matches('/').to_string())
+ .filter(|b| b.starts_with("http"))
+ .unwrap_or_else(|| "https://api.anthropic.com".into());
+ let Ok(mut child) = std::process::Command::new("curl")
+ .args([
+ "-sS",
+ "-o",
+ "/dev/null",
+ "-w",
+ "%{http_code}",
+ "--max-time",
+ "15",
+ "-K",
+ "-",
+ ])
+ .arg(format!("{base}/v1/models?limit=1"))
+ .stdin(std::process::Stdio::piped())
+ .stdout(std::process::Stdio::piped())
+ .stderr(std::process::Stdio::null())
+ .spawn()
+ else {
+ return TokenCheck::Unknown;
+ };
+ if let Some(mut stdin) = child.stdin.take() {
+ let cfg = format!(
+ "header = \"Authorization: Bearer {token}\"\nheader = \"anthropic-beta: oauth-2025-04-20\"\nheader = \"anthropic-version: 2023-06-01\"\n"
+ );
+ let _ = stdin.write_all(cfg.as_bytes());
+ }
+ let Ok(out) = child.wait_with_output() else {
+ return TokenCheck::Unknown;
+ };
+ String::from_utf8_lossy(&out.stdout)
+ .trim()
+ .parse::<u16>()
+ .map(token_check_for)
+ .unwrap_or(TokenCheck::Unknown)
}
fn claude_copy(env: &HostEnv, wait: Duration) -> Result<SignInCopy, CopyRefusal> {
@@ -295,16 +445,21 @@ fn claude_copy(env: &HostEnv, wait: Duration) -> Result<SignInCopy, CopyRefusal>
// system has it. The browser opens for the one approval.
let script = Path::new("/usr/bin/script");
let bin_s = bin.display().to_string();
+ // A wide terminal, so the token (about 108 characters) is never wrapped
+ // onto a second line.
+ let wide = format!(
+ "stty cols 1000 rows 50 2>/dev/null; exec {} setup-token",
+ shell_quote(&bin_s)
+ );
let out = match env.os {
crate::Os::MacOs if script.exists() => crate::connection::run_capture(
env,
script,
- &["-q", "/dev/null", &bin_s, "setup-token"],
+ &["-q", "/dev/null", "/bin/sh", "-c", &wide],
wait,
),
crate::Os::Linux if script.exists() => {
- let cmd = format!("{} setup-token", shell_quote(&bin_s));
- crate::connection::run_capture(env, script, &["-qec", &cmd, "/dev/null"], wait)
+ crate::connection::run_capture(env, script, &["-qec", &wide, "/dev/null"], wait)
}
_ => crate::connection::run_capture(env, &bin, &["setup-token"], wait),
};
@@ -314,6 +469,12 @@ fn claude_copy(env: &HostEnv, wait: Duration) -> Result<SignInCopy, CopyRefusal>
));
};
match find_setup_token(&stdout) {
+ Some(token) if check_claude_token(env, &token) == TokenCheck::Invalid => {
+ Err(CopyRefusal::Failed(
+ "Connected. Sign-in not copied: Claude didn't accept the token. Try Connect again."
+ .into(),
+ ))
+ }
Some(token) => Ok(SignInCopy {
source: "claude-code".into(),
env: "CLAUDE_CODE_OAUTH_TOKEN".into(),
@@ -868,15 +1029,112 @@ mod tests {
#[test]
fn setup_token_is_found_in_terminal_output() {
- let out = "\u{1b}[2K Your token:\r\n\r\n sk-ant-oat01-AbC_d3f-xyz0123456789AAAA\r\n\r\nStore it safely.";
- assert_eq!(
- find_setup_token(out).as_deref(),
- Some("sk-ant-oat01-AbC_d3f-xyz0123456789AAAA")
+ // A realistic token: `sk-ant-oat01-` and 95 more characters (108).
+ let token = format!(
+ "sk-ant-oat01-{}",
+ "AbC_d3f-xyZ0123456789"
+ .repeat(5)
+ .chars()
+ .take(95)
+ .collect::<String>()
);
+ assert_eq!(token.len(), 108);
+ let out =
+ format!("\x1b[2K Your token:\r\n\r\n \x1b[1m{token}\x1b[0m\r\n\r\nStore it safely.");
+ assert_eq!(find_setup_token(&out).as_deref(), Some(token.as_str()));
assert_eq!(find_setup_token("Login cancelled"), None);
assert_eq!(find_setup_token("sk-ant-oat"), None);
}
+ #[test]
+ fn a_wrapped_token_is_joined_and_a_cut_one_refused() {
+ let token = format!(
+ "sk-ant-oat01-{}",
+ "Qw3_rT-yUi0pAsDfGh"
+ .repeat(6)
+ .chars()
+ .take(95)
+ .collect::<String>()
+ );
+ // Wrapped at 80 columns by the terminal.
+ let (a, b) = token.split_at(80);
+ let out = format!("Your OAuth token:\r\n\r\n{a}\r\n{b}\r\n\r\nStore this token securely.");
+ assert_eq!(find_setup_token(&out).as_deref(), Some(token.as_str()));
+ // Wrapped at 40: three pieces.
+ let out = format!(
+ "{}\r\n{}\r\n{}\r\n\r\nDone",
+ &token[..40],
+ &token[40..80],
+ &token[80..]
+ );
+ assert_eq!(find_setup_token(&out).as_deref(), Some(token.as_str()));
+ // Only the first fragment printed (a redraw cut it): refused, not saved.
+ assert_eq!(find_setup_token(&format!("{a}\r\n")), None);
+ assert_eq!(find_setup_token(&format!("{}\r\n", &token[..60])), None);
+ // The old 36-character fake is not a plausible token.
+ assert_eq!(
+ find_setup_token("sk-ant-oat01-AbC_d3f-xyz0123456789AAAA"),
+ None
+ );
+ }
+
+ #[test]
+ fn a_token_check_reads_only_a_refusal_as_invalid() {
+ assert_eq!(token_check_for(200), TokenCheck::Valid);
+ assert_eq!(token_check_for(401), TokenCheck::Invalid);
+ assert_eq!(token_check_for(403), TokenCheck::Invalid);
+ assert_eq!(token_check_for(429), TokenCheck::Unknown);
+ assert_eq!(token_check_for(529), TokenCheck::Unknown);
+ }
+
+ /// A one-shot local provider answering `status`; the request it got.
+ fn stub_provider(status: &'static str) -> (String, std::thread::JoinHandle<String>) {
+ use std::io::{Read, Write};
+ let l = std::net::TcpListener::bind("127.0.0.1:0").unwrap();
+ let url = format!("http://{}", l.local_addr().unwrap());
+ let h = std::thread::spawn(move || {
+ let (mut c, _) = l.accept().unwrap();
+ let mut buf = [0u8; 4096];
+ let n = c.read(&mut buf).unwrap();
+ let body = r#"{"type":"error","error":{"type":"authentication_error","message":"OAuth token invalid"}}"#;
+ let _ = write!(
+ c,
+ "HTTP/1.1 {status}\r\ncontent-type: application/json\r\ncontent-length: {}\r\nconnection: close\r\n\r\n{body}",
+ body.len()
+ );
+ String::from_utf8_lossy(&buf[..n]).into_owned()
+ });
+ (url, h)
+ }
+
+ /// A corrupted token gets the provider's 401 and is refused before it is
+ /// saved; the token travels in a header, never in the command line.
+ #[test]
+ fn a_token_the_provider_refuses_is_not_saved() {
+ let d = tempfile::tempdir().unwrap();
+ for (status, want) in [
+ ("401 Unauthorized", TokenCheck::Invalid),
+ ("200 OK", TokenCheck::Valid),
+ ("529 Overloaded", TokenCheck::Unknown),
+ ] {
+ let (url, server) = stub_provider(status);
+ let mut env = HostEnv::isolated(d.path());
+ env.run_agent_clis = true;
+ env.vars.insert("CUA_TOKEN_CHECK_URL".into(), url);
+ let token = "sk-ant-oat01-corrupted-0123456789";
+ assert_eq!(check_claude_token(&env, token), want, "{status}");
+ let request = server.join().unwrap();
+ assert!(request.starts_with("GET /v1/models"), "{request}");
+ assert!(request.contains(&format!("Bearer {token}")), "{request}");
+ }
+ // Nothing is asked when agent commands are off.
+ let off = HostEnv::isolated(d.path());
+ assert_eq!(
+ check_claude_token(&off, "sk-ant-oat01-x"),
+ TokenCheck::Unknown
+ );
+ }
+
#[test]
fn dotenv_reads_hermes_lines() {
let d = tempfile::tempdir().unwrap();
diff --git a/libs/cua/crates/cua-agent-setup/tests/connection_matrix.rs b/libs/cua/crates/cua-agent-setup/tests/connection_matrix.rs
index 1dbe6bba9d..aa4c4e9443 100644
--- a/libs/cua/crates/cua-agent-setup/tests/connection_matrix.rs
+++ b/libs/cua/crates/cua-agent-setup/tests/connection_matrix.rs
@@ -117,7 +117,7 @@ const CLAUDE_EXTRA: &str = r#" auth)
echo '{"authMethod":"none"}'; exit 1 ;;
setup-token)
if [ -f "$HOME/.fake-claude-cancel" ]; then echo "Login cancelled"; exit 1; fi
- printf 'Your OAuth token:\r\n\r\n sk-ant-oat01-FAKEtoken_0123456789abcdef\r\n' ; exit 0 ;;
+ printf 'Your OAuth token:\r\n\r\n sk-ant-oat01-FAKEtoken_0123456789abcdef_ABCDEFGHIJKLMNOPQRSTUVWXYZ_abcdefghijklmnopqrstuvwxyz_0123456789_QQQQ\r\n' ; exit 0 ;;
"#;
impl World {
@@ -129,6 +129,10 @@ impl World {
std::fs::create_dir_all(&bin).unwrap();
let mut env = HostEnv::isolated(&home);
env.path = vec![bin.clone()];
+ // The pre-save token check asks this address, where nothing answers
+ // (the check is then inconclusive and the token is saved).
+ env.vars
+ .insert("CUA_TOKEN_CHECK_URL".into(), "http://127.0.0.1:9".into());
let w = World {
_dir: dir,
home,
@@ -419,6 +423,35 @@ fn connected_but_not_signed_in_says_so_and_offers_sign_in_where_cua_can_start_it
assert_eq!(r.signed_in, SignedInState::Unknown);
}
+/// A corrupted token gets the provider's 401 from a local stub and is never
+/// saved: Connect reports it, and the vault stays empty.
+#[test]
+fn a_token_the_provider_refuses_is_never_saved() {
+ use std::io::{Read, Write};
+ let listener = std::net::TcpListener::bind("127.0.0.1:0").unwrap();
+ let url = format!("http://{}", listener.local_addr().unwrap());
+ let server = std::thread::spawn(move || {
+ let (mut c, _) = listener.accept().unwrap();
+ let mut buf = [0u8; 4096];
+ let _ = c.read(&mut buf).unwrap();
+ let body = r#"{"type":"error","error":{"type":"authentication_error","message":"OAuth token invalid"}}"#;
+ let _ = write!(
+ c,
+ "HTTP/1.1 401 Unauthorized\r\ncontent-length: {}\r\nconnection: close\r\n\r\n{body}",
+ body.len()
+ );
+ });
+ let mut w = World::new();
+ w.env.vars.insert("CUA_TOKEN_CHECK_URL".into(), url);
+ w.install("claude-code", "2.4.1");
+ w.sign_in("claude-code");
+ w.connect("claude-code", true);
+ server.join().unwrap();
+ assert_eq!(w.vault.value("claude-code"), None);
+ let r = w.row("claude-code");
+ assert_ne!(r.signin_import, ImportState::Ok, "{r:#?}");
+}
+
#[test]
fn sign_ins_are_made_for_cua_and_never_read_from_the_apps_own_files() {
// Codex: its own device-code login in a folder Cua owns; your auth.json is never read.
@@ -509,7 +542,9 @@ fn sign_ins_are_made_for_cua_and_never_read_from_the_apps_own_files() {
assert_eq!(r.signin_import, ImportState::Ok);
assert_eq!(
w.vault.value("claude-code").as_deref(),
- Some("sk-ant-oat01-FAKEtoken_0123456789abcdef")
+ Some(
+ "sk-ant-oat01-FAKEtoken_0123456789abcdef_ABCDEFGHIJKLMNOPQRSTUVWXYZ_abcdefghijklmnopqrstuvwxyz_0123456789_QQQQ"
+ )
);
// Hermes: its .env is never copied; it uses the providers connected in Settings.
diff --git a/libs/cua/crates/cua-agents/runner/acp-runner.mjs b/libs/cua/crates/cua-agents/runner/acp-runner.mjs
index 2c27054149..02ebf31ddd 100644
--- a/libs/cua/crates/cua-agents/runner/acp-runner.mjs
+++ b/libs/cua/crates/cua-agents/runner/acp-runner.mjs
@@ -1107,7 +1107,9 @@ async function drive(a) {
// retries: one error, the turn ends, the supervisor notifies once.
emit("error", { message: rejected.message, data: { errorKind: "authentication_failed", status: rejected.status, source: "key_check" } });
endTurn("error");
- if (durable) finish(EXIT_PERMANENT, "authentication failed");
+ // A run whose credential is rejected is over: the next message starts
+ // a fresh run with whatever credential the person has connected by then.
+ finish(durable ? EXIT_PERMANENT : 1, withAuthHint(rejected.message, null));
return;
}
let res;
@@ -1123,6 +1125,10 @@ async function drive(a) {
throw new AgentFailure(`prompt failed: ${e?.message ?? e}`, isAuthError(e));
}
endTurn("error");
+ // Same for a credential the agent says it could not authenticate: the
+ // run ends as failed (its error kept) instead of idling for up to
+ // 30 minutes with a credential that does not work.
+ if (isAuthError(e)) finish(1, redact(withAuthHint(e?.message ?? String(e), e)));
return;
}
if (stale()) return;
diff --git a/libs/cua/crates/cua-agents/runner/test/key-check.test.mjs b/libs/cua/crates/cua-agents/runner/test/key-check.test.mjs
index 02483772fc..8e9f4e4c53 100644
--- a/libs/cua/crates/cua-agents/runner/test/key-check.test.mjs
+++ b/libs/cua/crates/cua-agents/runner/test/key-check.test.mjs
@@ -149,7 +149,10 @@ test("a rejected key ends the first turn in seconds with the provider's message,
// The harness would stall on its retries (STUB_PROMPT=hang): the run
// must end without ever sending it the prompt.
const r = await run({ port: p.port });
- assert.equal(r.code, 0);
+ // The run ends as failed (a rejected credential is not worth a half hour
+ // of idling): the next message starts a fresh run with a new credential.
+ assert.equal(r.code, 1);
+ assert.equal(r.state.status, "failed");
assert.ok(r.ms < 10_000, `took ${r.ms} ms`);
assert.equal(r.prompts, 0);
const types = r.events.map((e) => e.type);
diff --git a/libs/cua/crates/cua-agents/runner/test/run-end.test.mjs b/libs/cua/crates/cua-agents/runner/test/run-end.test.mjs
index fe714e7b8d..74f1f6a42c 100644
--- a/libs/cua/crates/cua-agents/runner/test/run-end.test.mjs
+++ b/libs/cua/crates/cua-agents/runner/test/run-end.test.mjs
@@ -108,7 +108,7 @@ test("prompt errors retain the provider reason without launch diagnostics", {tim
assert.equal(events.filter(e => e.type === "turn_ended").length, 1);
});
-test("prompt authentication errors include the guest sign-in command and remain recoverable", {timeout: 6000}, async (t) => {
+test("prompt authentication errors include the guest sign-in command and end the run as failed, so the next message starts a fresh one", {timeout: 6000}, async (t) => {
const authHint = "Run ~/.cua/bin/claude inside the Space to sign in";
const {events, state} = await failureRun(t, {
config: {prompt: "hello", idleExitSecs: 0.01, authHint},
@@ -121,6 +121,20 @@ test("prompt authentication errors include the guest sign-in command and remain
assert.equal(errors[0].message, `Authentication required\n${authHint}`);
assert.equal(errors[0].code, -32000);
assert.equal(events.filter(e => e.type === "turn_ended").length, 1);
+ // Not idle for half an hour with a credential that does not work: failed,
+ // with the error kept, so the owner's next message starts a new run.
+ assert.equal(events.filter(e => e.type === "run_exited").length, 1);
+ assert.equal(state.status, "failed");
+ assert.match(state.error, /Authentication required/);
+});
+
+test("other prompt errors still leave the run waiting for the next message", {timeout: 6000}, async (t) => {
+ const {state} = await failureRun(t, {
+ config: {prompt: "hello", idleExitSecs: 0.01},
+ request: `if (method === 'initialize') return {};
+ if (method === 'new') return {sessionId: 's'};
+ throw Object.assign(new Error('Provider quota exceeded'), {code: -32001});`,
+ });
assert.equal(state.status, "exited");
});
diff --git a/libs/cua/crates/cua-agents/src/failure.rs b/libs/cua/crates/cua-agents/src/failure.rs
new file mode 100644
index 0000000000..f340fbab41
--- /dev/null
+++ b/libs/cua/crates/cua-agents/src/failure.rs
@@ -0,0 +1,190 @@
+//! A failed turn or start, in one typed shape every surface reads.
+//!
+//! Providers and harnesses each word an authentication failure differently
+//! (`401 OAuth token invalid`, JSON-RPC `-32000`, Hermes' "not connected to
+//! any AI provider"). [`classify`] turns any of them into
+//! [`FailureClass::NeedsConnect`] with the provider whose Connect row fixes
+//! it; everything else is [`FailureClass::Error`]. The full text is kept
+//! (up to [`MAX_MESSAGE`] characters) so a surface can offer it under "Show
+//! details" and never has to clip or show it as the summary.
+
+use serde::{Deserialize, Serialize};
+
+/// The longest message kept (characters).
+pub const MAX_MESSAGE: usize = 4096;
+
+/// What kind of failure it is.
+#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)]
+#[serde(rename_all = "snake_case")]
+pub enum FailureClass {
+ /// The agent has no working credential: connect (or reconnect) one.
+ NeedsConnect,
+ /// Anything else.
+ Error,
+}
+
+/// A failure with its class, the provider to connect, and the full text.
+#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
+pub struct Failure {
+ pub class: FailureClass,
+ /// For `needs_connect`: `anthropic` or `openai` (the Connectors row),
+ /// when the harness has one.
+ #[serde(default, skip_serializing_if = "Option::is_none")]
+ pub provider: Option<String>,
+ /// The complete error as the harness or provider said it.
+ pub message: String,
+ /// Sending the same message again can work (after connecting).
+ pub retryable: bool,
+}
+
+/// The words providers and harnesses use for "your credential does not work".
+const AUTH_MARKERS: &[&str] = &[
+ "authentication_failed",
+ "authentication required",
+ "authentication failed",
+ "failed to authenticate",
+ "invalid x-api-key",
+ "invalid api key",
+ "incorrect api key",
+ "oauth token",
+ "oauth access token",
+ "not connected to any ai provider",
+ "no credential in this space",
+ "invalid bearer token",
+ "unauthorized",
+ "(code -32000)",
+ "code: -32000",
+ "\"code\":-32000",
+ "\"code\": -32000",
+];
+
+/// Whether `text` is an authentication failure.
+pub fn is_auth_failure(text: &str) -> bool {
+ let t = text.to_ascii_lowercase();
+ if AUTH_MARKERS.iter().any(|m| t.contains(m)) {
+ return true;
+ }
+ // A bare 401 counts when it is the status of an API error.
+ t.contains("api error: 401")
+ || t.contains("status 401")
+ || t.contains("http 401")
+ || t.contains("error 401")
+}
+
+fn cap(text: &str) -> String {
+ let text = text.trim();
+ if text.chars().count() <= MAX_MESSAGE {
+ text.to_string()
+ } else {
+ let mut s: String = text.chars().take(MAX_MESSAGE - 1).collect();
+ s.push('\u{2026}');
+ s
+ }
+}
+
+/// The provider whose Connect row fixes an auth failure of `harness`, read
+/// from the text where the harness has more than one.
+fn provider_for(harness: &str, text: &str) -> Option<String> {
+ let t = text.to_ascii_lowercase();
+ let from_text = if t.contains("anthropic") || t.contains("claude") {
+ Some("anthropic")
+ } else if t.contains("openai") || t.contains("chatgpt") || t.contains("codex") {
+ Some("openai")
+ } else {
+ None
+ };
+ let own = crate::harness::harness(harness).and_then(|h| h.connect_provider());
+ match harness {
+ "claude-code" => Some("anthropic".into()),
+ "openai-codex" => Some("openai".into()),
+ _ => from_text.or(own).map(str::to_string),
+ }
+}
+
+/// Classifies `text`, the error of a turn or start of `harness`.
+pub fn classify(harness: &str, text: &str) -> Failure {
+ let message = cap(text);
+ if is_auth_failure(text) {
+ Failure {
+ class: FailureClass::NeedsConnect,
+ provider: provider_for(harness, text),
+ message,
+ retryable: true,
+ }
+ } else {
+ Failure {
+ class: FailureClass::Error,
+ provider: None,
+ message,
+ retryable: true,
+ }
+ }
+}
+
+/// What a person reads instead of the raw error, in plain words from the
+/// agent's side (it is the agent's reply).
+pub fn plain(f: &Failure) -> String {
+ match f.class {
+ FailureClass::NeedsConnect => match f.provider.as_deref() {
+ Some("anthropic") => "I can't reach Claude yet. Connect Claude, then try again.".into(),
+ Some("openai") => "I can't reach OpenAI yet. Connect OpenAI, then try again.".into(),
+ _ => "I'm not connected to an AI provider yet. Connect one, then try again.".into(),
+ },
+ FailureClass::Error => "I couldn't finish that.".into(),
+ }
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+
+ #[test]
+ fn auth_failures_in_every_wording_need_a_connect() {
+ for (h, t, p) in [
+ (
+ "claude-code",
+ "Internal error: Failed to authenticate. API Error: 401 OAuth access token is invalid",
+ "anthropic",
+ ),
+ ("claude-code", "Authentication required", "anthropic"),
+ (
+ "openai-codex",
+ "Internal error (code -32000) {\"details\":\"x\"}",
+ "openai",
+ ),
+ (
+ "hermes",
+ "Internal error (code -32603) {\"details\":\"Hermes is not connected to any AI provider\"}",
+ "anthropic",
+ ),
+ (
+ "hermes",
+ "not connected to any AI provider; add an OpenAI key",
+ "openai",
+ ),
+ ] {
+ let f = classify(h, t);
+ assert_eq!(f.class, FailureClass::NeedsConnect, "{t}");
+ assert_eq!(f.provider.as_deref(), Some(p), "{t}");
+ assert_eq!(f.message, t);
+ }
+ }
+
+ #[test]
+ fn other_errors_stay_errors_and_keep_their_text() {
+ let f = classify("claude-code", "rate limited, try later");
+ assert_eq!(f.class, FailureClass::Error);
+ assert_eq!(f.provider, None);
+ let long = "x".repeat(10_000);
+ let f = classify("claude-code", &long);
+ assert_eq!(f.message.chars().count(), MAX_MESSAGE);
+ }
+
+ #[test]
+ fn plain_words_never_carry_the_raw_error() {
+ let f = classify("claude-code", "API Error: 401 {\"error\":\"invalid\"}");
+ let p = plain(&f);
+ assert!(!p.contains("401") && !p.contains('{'), "{p}");
+ assert!(!p.contains('\u{b7}'));
+ }
+}
diff --git a/libs/cua/crates/cua-agents/src/harness.rs b/libs/cua/crates/cua-agents/src/harness.rs
index e1f1a15c0c..d737102287 100644
--- a/libs/cua/crates/cua-agents/src/harness.rs
+++ b/libs/cua/crates/cua-agents/src/harness.rs
@@ -53,8 +53,10 @@ pub struct Harness {
/// Shell tests (run in the guest) for a sign-in the harness uses
/// instead of a key: a credentials file under `$HOME`, a Keychain item.
/// `Some(&[])`: only a key works. `None`: the harness can also be set up
- /// through its own config files, which cua does not read, so a missing
- /// key is not conclusive.
+ /// through config files cua does not know, so a missing key is not
+ /// conclusive (no harness here is `None` any more: each lists the files
+ /// of its own setup, and a run without a key or one of them is refused
+ /// before the install).
pub logins: Option<&'static [&'static str]>,
/// ACP `authenticate` method used with an env key, when the agent
/// requires one.
@@ -170,7 +172,10 @@ pub const HARNESSES: &[Harness] = &[
"GEMINI_API_KEY",
"OPENROUTER_API_KEY",
],
- logins: None,
+ logins: Some(&[
+ "[ -s \"$HOME/.local/share/opencode/auth.json\" ]",
+ "[ -s \"$HOME/.config/opencode/opencode.json\" ]",
+ ]),
auth_method: None,
wires: &[Wire::OpenaiChat],
mode_kinds: FULL,
@@ -191,7 +196,10 @@ pub const HARNESSES: &[Harness] = &[
"GOOGLE_API_KEY",
"OPENROUTER_API_KEY",
],
- logins: None,
+ logins: Some(&[
+ "[ -s \"$HOME/.config/goose/config.yaml\" ]",
+ "[ -s \"$HOME/.config/goose/secrets.yaml\" ]",
+ ]),
auth_method: None,
wires: &[Wire::OpenaiChat],
mode_kinds: FULL,
@@ -212,7 +220,10 @@ pub const HARNESSES: &[Harness] = &[
"GEMINI_API_KEY",
"OPENROUTER_API_KEY",
],
- logins: None,
+ logins: Some(&[
+ "[ -s \"$HOME/.pi/agent/auth.json\" ]",
+ "[ -s \"$HOME/.pi/agent/models.json\" ]",
+ ]),
auth_method: None,
wires: &[Wire::OpenaiChat],
mode_kinds: FULL,
@@ -230,8 +241,20 @@ pub const HARNESSES: &[Harness] = &[
installs: &["hermes"],
acp: &["hermes-acp"],
cli: Some("hermes"),
- keys: &["OPENROUTER_API_KEY", "ANTHROPIC_API_KEY", "OPENAI_API_KEY"],
- logins: None,
+ // CLAUDE_CODE_OAUTH_TOKEN: the Claude sign-in Connect made; Hermes
+ // reads it as its Anthropic credential. It has no reader for the
+ // ChatGPT sign-in (CODEX_AUTH_JSON), so that one is not forwarded.
+ keys: &[
+ "OPENROUTER_API_KEY",
+ "ANTHROPIC_API_KEY",
+ "CLAUDE_CODE_OAUTH_TOKEN",
+ "OPENAI_API_KEY",
+ ],
+ // Its own `.env` (a key set inside the Space) or a provider sign-in.
+ logins: Some(&[
+ "[ -s \"$HOME/.hermes/.env\" ]",
+ "[ -s \"$HOME/.hermes/auth.json\" ]",
+ ]),
auth_method: None,
wires: &[Wire::OpenaiChat],
mode_kinds: FULL,
@@ -251,7 +274,10 @@ pub const HARNESSES: &[Harness] = &[
acp: &["openclaw", "acp"],
cli: Some("openclaw"),
keys: &["ANTHROPIC_API_KEY", "OPENAI_API_KEY", "OPENROUTER_API_KEY"],
- logins: None,
+ logins: Some(&[
+ "[ -s \"$HOME/.openclaw/openclaw.json\" ]",
+ "[ -s \"$HOME/.openclaw/.env\" ]",
+ ]),
auth_method: None,
wires: &[Wire::OpenaiChat],
mode_kinds: FULL,
@@ -265,6 +291,21 @@ pub const HARNESSES: &[Harness] = &[
},
];
+impl Harness {
+ /// The provider whose Connect row gives this harness a credential
+ /// (`anthropic`, `openai`), when it has one. Hermes reads either; the
+ /// first is named.
+ pub fn connect_provider(&self) -> Option<&'static str> {
+ match self.id {
+ "claude-code" | "hermes" | "opencode" | "pi" | "openclaw" | "goose" => {
+ Some("anthropic")
+ }
+ "openai-codex" => Some("openai"),
+ _ => None,
+ }
+ }
+}
+
/// A harness by id.
pub fn harness(id: &str) -> Option<&'static Harness> {
HARNESSES.iter().find(|h| h.id == id)
diff --git a/libs/cua/crates/cua-agents/src/lib.rs b/libs/cua/crates/cua-agents/src/lib.rs
index 609cabb0c1..f56442057f 100644
--- a/libs/cua/crates/cua-agents/src/lib.rs
+++ b/libs/cua/crates/cua-agents/src/lib.rs
@@ -13,6 +13,7 @@
pub mod durable;
pub mod events;
+pub mod failure;
pub mod harness;
pub mod installables;
pub mod runs;
diff --git a/libs/cua/crates/cua-agents/src/runs.rs b/libs/cua/crates/cua-agents/src/runs.rs
index 21c636e057..304dbe8fde 100644
--- a/libs/cua/crates/cua-agents/src/runs.rs
+++ b/libs/cua/crates/cua-agents/src/runs.rs
@@ -145,6 +145,57 @@ pub struct RunMeta {
/// The persistent agent this run belongs to.
#[serde(default, skip_serializing_if = "Option::is_none")]
pub home: Option<String>,
+ /// A hash of the credentials this run was started with
+ /// ([`credential_hash`]; never the values). A caller that would start
+ /// the run with different ones restarts it instead of reusing it.
+ #[serde(default, skip_serializing_if = "Option::is_none")]
+ pub cred_hash: Option<String>,
+}
+
+/// Whether the forwarded Codex `auth.json` should replace the guest's: the
+/// guest has none, or its own copy is older (`last_refresh`, UTC) or
+/// unreadable. A guest copy that is as new, or newer (Codex refreshed it in
+/// the Space), is kept.
+fn codex_auth_replaces(forwarded: &str, existing: &[u8]) -> bool {
+ if existing.iter().all(u8::is_ascii_whitespace) {
+ return true;
+ }
+ let stamp = |v: &Value| {
+ v.get("last_refresh")
+ .and_then(Value::as_str)
+ .map(|t| t.chars().take(19).collect::<String>())
+ .filter(|t| t.len() == 19)
+ };
+ let new = serde_json::from_str::<Value>(forwarded)
+ .ok()
+ .and_then(|v| stamp(&v));
+ let old = serde_json::from_slice::<Value>(existing)
+ .ok()
+ .and_then(|v| stamp(&v));
+ match (new, old) {
+ (Some(n), Some(o)) => n > o,
+ (Some(_), None) => true,
+ (None, _) => false,
+ }
+}
+
+/// A hash of the credentials in `env` (the names and values of the keys
+/// `harness` reads, nothing else). Equal when the same credentials would be
+/// forwarded, so a run started with older ones can be told from a fresh
+/// start. Reveals nothing about the values.
+pub fn credential_hash(harness: &str, env: &BTreeMap<String, String>) -> String {
+ use sha2::{Digest, Sha256};
+ let keys: &[&str] = harness::harness(harness).map(|h| h.keys).unwrap_or(&[]);
+ let mut h = Sha256::new();
+ for (k, v) in env {
+ if keys.contains(&k.as_str()) || k == CODEX_AUTH_ENV {
+ h.update(k.as_bytes());
+ h.update([0]);
+ h.update(v.as_bytes());
+ h.update([0]);
+ }
+ }
+ hex::encode(&h.finalize()[..12])
}
/// One status vocabulary for every harness. `idle` means "no turn is
@@ -335,20 +386,22 @@ fn needs_probe(h: &Harness, opts: &RunOptions) -> bool {
}
/// Decides on the guest probe's output ([`Harness::auth_probe`]; `None`
-/// when it could not run): refused when no credential was found and cua
-/// knows every source, a note when it does not, nothing otherwise.
+/// when it could not run): refused when no credential was found, nothing
+/// otherwise. The refusal is typed (`needs_connect`, see [`crate::failure`]).
fn credential_check(h: &Harness, probe: Option<&str>) -> Result<Option<String>> {
if probe.map(str::trim) != Some(harness::PROBE_NONE) {
return Ok(None);
}
- if h.logins.is_some() {
- return Err(Error::NoCredential(h.missing_credential()));
+ match h.logins {
+ // Every harness lists the files of its own setup now; `None` stays
+ // for one added without them, which only gets a note.
+ None => Ok(Some(format!(
+ "no provider key reached this run; unless {} is configured inside the Space it fails with \"Authentication required\": {}",
+ h.name,
+ h.auth_hint()
+ ))),
+ Some(_) => Err(Error::NoCredential(h.missing_credential())),
}
- Ok(Some(format!(
- "no provider key reached this run; unless {} is configured inside the Space it fails with \"Authentication required\": {}",
- h.name,
- h.auth_hint()
- )))
}
pub(crate) fn valid_env_name(k: &str) -> Result<()> {
@@ -881,7 +934,8 @@ impl Agents {
&& !auth.trim().is_empty()
{
let file = format!("{}/.codex/auth.json", self.home.trim_end_matches('/'));
- if self.read(&file, 0, 1).await?.is_none_or(|b| b.is_empty()) {
+ let existing = self.read(&file, 0, 0).await?.unwrap_or_default();
+ if codex_auth_replaces(&auth, &existing) {
self.write(&file, auth.into_bytes(), 0o600).await?;
}
}
@@ -1011,6 +1065,7 @@ impl Agents {
label: opts.label.clone(),
repo: opts.repo.clone(),
home: opts.home.clone(),
+ cred_hash: Some(credential_hash(h.id, &opts.env)),
};
self.write(
&format!("{rdir}/meta.json"),
@@ -1438,6 +1493,46 @@ pub fn summarize(run_id: &str, status: RunStatus, evs: &[AgentEvent]) -> RunResu
mod tests {
use super::*;
+ #[test]
+ fn a_newer_forwarded_codex_sign_in_replaces_the_guests() {
+ let new = r#"{"last_refresh":"2026-10-27T10:00:00.5Z","tokens":{}}"#;
+ let old = r#"{"last_refresh":"2026-10-26T10:00:00Z","tokens":{}}"#;
+ assert!(codex_auth_replaces(new, b""));
+ assert!(codex_auth_replaces(new, old.as_bytes()));
+ assert!(!codex_auth_replaces(old, new.as_bytes()));
+ assert!(!codex_auth_replaces(old, old.as_bytes()));
+ assert!(codex_auth_replaces(new, b"not json"));
+ assert!(!codex_auth_replaces(r#"{"tokens":{}}"#, old.as_bytes()));
+ }
+
+ #[test]
+ fn the_credential_hash_changes_with_the_credentials_only() {
+ let env = |pairs: &[(&str, &str)]| -> BTreeMap<String, String> {
+ pairs
+ .iter()
+ .map(|(k, v)| (k.to_string(), v.to_string()))
+ .collect()
+ };
+ let a = credential_hash("claude-code", &env(&[("CLAUDE_CODE_OAUTH_TOKEN", "one")]));
+ assert_eq!(
+ a,
+ credential_hash("claude-code", &env(&[("CLAUDE_CODE_OAUTH_TOKEN", "one")]))
+ );
+ assert_ne!(
+ a,
+ credential_hash("claude-code", &env(&[("CLAUDE_CODE_OAUTH_TOKEN", "two")]))
+ );
+ // A variable the harness does not read does not count.
+ assert_eq!(
+ a,
+ credential_hash(
+ "claude-code",
+ &env(&[("CLAUDE_CODE_OAUTH_TOKEN", "one"), ("HOME_X", "y")])
+ )
+ );
+ assert!(!a.contains("one"));
+ }
+
fn probe(h: &Harness, home: &std::path::Path, env: &[(&str, &str)]) -> String {
let out = std::process::Command::new("/bin/sh")
.arg("-c")
@@ -1504,9 +1599,29 @@ mod tests {
let _ = std::fs::remove_dir_all(&home);
// A probe that could not run decides nothing.
assert_eq!(credential_check(codex, None).unwrap(), None);
- // A harness configurable through its own files: a note, not a refusal.
- let goose = harness::harness("goose").unwrap();
- let note = credential_check(goose, Some("none")).unwrap().unwrap();
+ // Every harness lists the files of its own setup, so each is refused
+ // before the install when it has neither a key nor one of them.
+ for h in harness::HARNESSES.iter().filter(|h| h.logins.is_some()) {
+ let e = credential_check(h, Some("none")).unwrap_err();
+ assert!(matches!(e, Error::NoCredential(_)), "{}", h.id);
+ let typed = crate::failure::classify(h.id, &e.to_string());
+ assert_eq!(
+ typed.class,
+ crate::failure::FailureClass::NeedsConnect,
+ "{}",
+ h.id
+ );
+ }
+ // Hermes reads the Claude sign-in too.
+ let hermes = harness::harness("hermes").unwrap();
+ assert!(hermes.keys.contains(&"CLAUDE_CODE_OAUTH_TOKEN"));
+ assert!(!hermes.keys.contains(&"CODEX_AUTH_JSON"));
+ // A harness added without a list of its own files only gets a note.
+ let open = Harness {
+ logins: None,
+ ..*harness::harness("goose").unwrap()
+ };
+ let note = credential_check(&open, Some("none")).unwrap().unwrap();
assert!(note.contains("OPENAI_API_KEY"), "{note}");
}
diff --git a/libs/cua/crates/cua-spaces-app-core/src/agent_keys.rs b/libs/cua/crates/cua-spaces-app-core/src/agent_keys.rs
index 732ef3cdb0..6996487b53 100644
--- a/libs/cua/crates/cua-spaces-app-core/src/agent_keys.rs
+++ b/libs/cua/crates/cua-spaces-app-core/src/agent_keys.rs
@@ -58,6 +58,8 @@ pub struct AgentKeyInput {
pub last4: String,
/// When it was added (Unix ms).
pub added_ms: u64,
+ /// A sign-in past its expiry: not used by any run until reconnected.
+ pub expired: bool,
}
/// What the section shows.
@@ -463,6 +465,7 @@ mod tests {
env: env.into(),
last4: last4.into(),
added_ms: 1,
+ expired: false,
}
}
diff --git a/libs/cua/crates/cua-spaces-app-core/src/connectors.rs b/libs/cua/crates/cua-spaces-app-core/src/connectors.rs
index 8f4a29c044..c67a96f9fc 100644
--- a/libs/cua/crates/cua-spaces-app-core/src/connectors.rs
+++ b/libs/cua/crates/cua-spaces-app-core/src/connectors.rs
@@ -102,7 +102,7 @@ const PROVIDERS: &[Provider] = &[
label: "OpenAI",
env: "OPENAI_API_KEY",
also: &["CODEX_AUTH_JSON"],
- used_by: "Codex, Hermes and other apps that use OpenAI models.",
+ used_by: "Codex. Hermes and other apps that use OpenAI models need an API key.",
key_help: "Create a key at platform.openai.com. Every app that uses OpenAI can use it.",
placeholder: "sk-…",
ways: &[CODEX_DEVICE, Way::Key, Way::Shell],
@@ -127,6 +127,10 @@ struct AppSignIn {
/// The way Connect starts when none is connected (`None`: it asks with
/// the provider's sheet).
way: Option<Way>,
+ /// The saved credentials the app can read, as the variables a run gets
+ /// (the harness's `keys`; a drift test holds them equal). Empty: the app
+ /// takes any credential of its providers.
+ reads: &'static [&'static str],
}
const APPS: &[AppSignIn] = &[
@@ -134,26 +138,41 @@ const APPS: &[AppSignIn] = &[
app: "claude-code",
providers: &["anthropic"],
way: Some(CLAUDE_TOKEN),
+ reads: &[
+ "ANTHROPIC_API_KEY",
+ "CLAUDE_CODE_OAUTH_TOKEN",
+ "ANTHROPIC_AUTH_TOKEN",
+ ],
},
AppSignIn {
app: "codex",
providers: &["openai"],
way: Some(CODEX_DEVICE),
+ reads: &["OPENAI_API_KEY", "CODEX_API_KEY", "CODEX_AUTH_JSON"],
},
AppSignIn {
app: "copilot-cli",
providers: &["github"],
way: None,
+ reads: &[],
},
AppSignIn {
app: "hermes",
providers: &["anthropic", "openai"],
way: None,
+ // Not CODEX_AUTH_JSON: Hermes has no reader for the ChatGPT sign-in.
+ reads: &[
+ "OPENROUTER_API_KEY",
+ "ANTHROPIC_API_KEY",
+ "CLAUDE_CODE_OAUTH_TOKEN",
+ "OPENAI_API_KEY",
+ ],
},
AppSignIn {
app: "t3code",
providers: &["anthropic", "openai"],
way: None,
+ reads: &[],
},
];
@@ -248,9 +267,19 @@ impl ConnectorsInput {
/// The saved credential that connects a provider, first match wins: the
/// pasted key, then a sign-in token.
fn provider_credential<'a>(input: &'a ConnectorsInput, p: &Provider) -> Option<&'a AgentKeyInput> {
- input
- .key(p.env)
- .or_else(|| p.also.iter().find_map(|e| input.key(e)))
+ input.key(p.env).filter(|k| !k.expired).or_else(|| {
+ p.also
+ .iter()
+ .find_map(|e| input.key(e).filter(|k| !k.expired))
+ })
+}
+
+/// A sign-in saved for the provider has expired (and none that works is).
+fn provider_expired(input: &ConnectorsInput, p: &Provider) -> bool {
+ provider_credential(input, p).is_none()
+ && std::iter::once(p.env)
+ .chain(p.also.iter().copied())
+ .any(|e| input.key(e).is_some_and(|k| k.expired))
}
fn provider_connected(input: &ConnectorsInput, id: &str) -> bool {
@@ -259,11 +288,30 @@ fn provider_connected(input: &ConnectorsInput, id: &str) -> bool {
/// The app's sign-in is in place: one of its providers is connected, or it
/// signs in on its own.
+///
+/// Only a credential the app can read counts: a provider being connected is
+/// not enough when what is saved is a sign-in that app has no reader for (the
+/// ChatGPT sign-in is for Codex; Hermes reads an OpenAI API key, not it).
fn app_signed_in(input: &ConnectorsInput, app: &str) -> bool {
- match app_sign_in(app) {
- Some(a) => a.providers.iter().any(|p| provider_connected(input, p)),
- None => true,
+ let Some(a) = app_sign_in(app) else {
+ return true;
+ };
+ if a.reads.is_empty() {
+ return a.providers.iter().any(|p| provider_connected(input, p));
}
+ a.reads
+ .iter()
+ .any(|k| input.key(k).is_some_and(|k| !k.expired))
+}
+
+/// An app's sign-in is saved but expired.
+fn app_expired(input: &ConnectorsInput, app: &str) -> bool {
+ app_sign_in(app).is_some_and(|a| {
+ a.providers
+ .iter()
+ .filter_map(|p| provider(p))
+ .any(|p| provider_expired(input, p))
+ })
}
fn dots(k: &AgentKeyInput) -> String {
@@ -432,7 +480,11 @@ fn app_row(input: &ConnectorsInput, a: &ConnectorAppInput) -> ConnectorAppRow {
} else if a.configured {
(
"not-connected",
- needs.map(|n| format!("Needs a sign-in to {n}.")),
+ if app_expired(input, &a.agent) {
+ Some("The sign-in expired. Reconnect.".to_string())
+ } else {
+ needs.map(|n| format!("Needs a sign-in to {n}."))
+ },
Some(button("connect", "Connect", true)),
)
} else {
@@ -483,6 +535,12 @@ fn provider_row(input: &ConnectorsInput, p: &Provider, can_edit: bool) -> Connec
credential_text(p, k),
button("sign-out", "Sign out", can_edit),
)
+ } else if provider_expired(input, p) {
+ (
+ "not-connected",
+ "Expired, reconnect".into(),
+ button("connect", "Reconnect", can_edit),
+ )
} else {
(
"not-connected",
@@ -990,6 +1048,7 @@ mod tests {
env: env.into(),
last4: last4.into(),
added_ms: 1_000,
+ expired: false,
}
}
@@ -1004,6 +1063,55 @@ mod tests {
}
}
+ /// The credentials an app reads here are the ones its harness reads
+ /// (`cua_agents::harness`), so "connected" never outruns what a run gets.
+ #[test]
+ fn what_an_app_reads_is_what_its_harness_reads() {
+ for (app, harness) in [
+ ("claude-code", "claude-code"),
+ ("codex", "openai-codex"),
+ ("hermes", "hermes"),
+ ] {
+ let a = app_sign_in(app).unwrap();
+ let h = cua_agents::harness::harness(harness).unwrap();
+ assert_eq!(a.reads, h.keys, "{app}");
+ }
+ }
+
+ #[test]
+ fn hermes_is_connected_only_by_a_credential_it_reads() {
+ let mut i = input();
+ // The ChatGPT sign-in is for Codex; Hermes can't read it.
+ i.keys.keys.push(key("CODEX_AUTH_JSON", "AAAA"));
+ assert!(app_signed_in(&i, "codex"));
+ assert!(!app_signed_in(&i, "hermes"));
+ // An OpenAI API key, or the Claude sign-in token, it reads.
+ let mut k = input();
+ k.keys.keys.push(key("OPENAI_API_KEY", "AAAA"));
+ assert!(app_signed_in(&k, "hermes"));
+ let mut t = input();
+ t.keys.keys.push(key("CLAUDE_CODE_OAUTH_TOKEN", "AAAA"));
+ assert!(app_signed_in(&t, "hermes") && app_signed_in(&t, "claude-code"));
+ assert!(!app_signed_in(&t, "codex"));
+ }
+
+ #[test]
+ fn an_expired_sign_in_is_not_connected_and_says_reconnect() {
+ let mut i = input();
+ i.apps[0].configured = true;
+ let mut k = key("CLAUDE_CODE_OAUTH_TOKEN", "AAAA");
+ k.expired = true;
+ i.keys.keys.push(k);
+ assert!(!app_signed_in(&i, "claude-code"));
+ let v = view(&i);
+ let p = v.providers.iter().find(|p| p.id == "anthropic").unwrap();
+ assert_eq!(p.state, "not-connected");
+ assert_eq!(p.status, "Expired, reconnect");
+ assert_eq!(p.button.label, "Reconnect");
+ let a = v.apps.iter().find(|a| a.agent == "claude-code").unwrap();
+ assert_eq!(a.line.as_deref(), Some("The sign-in expired. Reconnect."));
+ }
+
#[test]
fn apps_start_with_connect_and_providers_not_connected() {
let v = view(&input());
diff --git a/libs/cua/crates/cua-spaces-app-core/src/first_run.rs b/libs/cua/crates/cua-spaces-app-core/src/first_run.rs
index c90af44de2..ac3c1f4687 100644
--- a/libs/cua/crates/cua-spaces-app-core/src/first_run.rs
+++ b/libs/cua/crates/cua-spaces-app-core/src/first_run.rs
@@ -2043,6 +2043,7 @@ mod tests {
env: (*env).into(),
last4: "1234".into(),
added_ms: 1,
+ expired: false,
})
.collect(),
..Default::default()
diff --git a/libs/cua/crates/cua-spaces-app-core/src/profile_card.rs b/libs/cua/crates/cua-spaces-app-core/src/profile_card.rs
index 9c1d3c562d..c7756702b9 100644
--- a/libs/cua/crates/cua-spaces-app-core/src/profile_card.rs
+++ b/libs/cua/crates/cua-spaces-app-core/src/profile_card.rs
@@ -417,6 +417,7 @@ mod tests {
env: "CLAUDE_CODE_OAUTH_TOKEN".into(),
last4: String::new(),
added_ms: 1,
+ expired: false,
}],
..Default::default()
},
diff --git a/libs/cua/crates/cua-spaces-app-core/src/summon.rs b/libs/cua/crates/cua-spaces-app-core/src/summon.rs
index 8b3d1abd0d..ac4dcb0770 100644
--- a/libs/cua/crates/cua-spaces-app-core/src/summon.rs
+++ b/libs/cua/crates/cua-spaces-app-core/src/summon.rs
@@ -495,6 +495,7 @@ mod tests {
env: (*e).into(),
last4: "abcd".into(),
added_ms: 1,
+ expired: false,
})
.collect(),
..Default::default()
diff --git a/libs/cua/crates/cua-spaces-ext/src/persistent/identity.rs b/libs/cua/crates/cua-spaces-ext/src/persistent/identity.rs
index 5ab0fd0b1d..bc06663b0f 100644
--- a/libs/cua/crates/cua-spaces-ext/src/persistent/identity.rs
+++ b/libs/cua/crates/cua-spaces-ext/src/persistent/identity.rs
@@ -169,7 +169,7 @@ pub fn stored_of(rec: &AgentRecord, owner: &Author) -> Stored {
Stored {
origin: Origin::Space,
member_id: format!("mem_{}", rec.name),
- display_name: rec.name.clone(),
+ display_name: rec.handle().to_string(),
icon: Some("harness".into()),
harness: HarnessInfo {
id: harness_id(&rec.harness).into(),
@@ -203,7 +203,7 @@ pub fn identity_of(rec: &AgentRecord, owner: &Author) -> Identity {
let s = stored_of(rec, owner);
Identity {
origin: s.origin,
- handle: rec.name.clone(),
+ handle: rec.handle().to_string(),
display_name: s.display_name,
collides: None,
icon: s.icon,
diff --git a/libs/cua/crates/cua-spaces-ext/src/persistent/join.rs b/libs/cua/crates/cua-spaces-ext/src/persistent/join.rs
index 05bfd2d019..26b80491ab 100644
--- a/libs/cua/crates/cua-spaces-ext/src/persistent/join.rs
+++ b/libs/cua/crates/cua-spaces-ext/src/persistent/join.rs
@@ -585,6 +585,7 @@ impl Persistent {
let handle = identity::free_handle("agent", |h| all.iter().any(|a| a.name == h));
let rec = AgentRecord {
name: handle,
+ handle: None,
harness: "other".into(),
space: code.space.clone(),
model: None,
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 e5ee5d99d5..66f642e346 100644
--- a/libs/cua/crates/cua-spaces-ext/src/persistent/members.rs
+++ b/libs/cua/crates/cua-spaces-ext/src/persistent/members.rs
@@ -22,7 +22,7 @@ use std::path::Path;
use serde::{Deserialize, Serialize};
use serde_json::{Value, json};
-use super::{AgentRecord, AgentSpec, MAX_SESSIONS, Persistent};
+use super::{AgentRecord, AgentSpec, MAX_SESSIONS, Persistent, locked_json};
use crate::DriveResult as _;
use crate::thread::claims::{ClaimEntries, Holder};
use crate::thread::policy::{self, Right, Rights};
@@ -32,6 +32,7 @@ use crate::thread::{
refuse_secrets,
};
use cua_agents::RunStatus;
+use cua_spaces::agents as ag;
use cua_spaces::extension::Caller;
use cua_spaces::{Error, Result};
@@ -283,11 +284,35 @@ impl Persistent {
.collect())
}
+ /// A Space of this machine that is no longer there: its members' keys are
+ /// free again. Only the registry of this machine answers for itself, for a
+ /// local Space or an address added by hand (a Space on another computer
+ /// may be offline, not gone).
+ fn space_is_gone(&self, space: &str) -> bool {
+ (space.starts_with("local:") || space.starts_with("direct:"))
+ && self
+ .spaces
+ .list()
+ .map(|rows| !rows.iter().any(|s| s.id == space))
+ .unwrap_or(false)
+ }
+
+ /// `base`, or `base-2`, `base-3`, ... : the first key no persistent agent has.
+ fn free_key(&self, base: &str) -> Result<String> {
+ let taken: Vec<String> = self.list()?.into_iter().map(|r| r.name).collect();
+ (2..)
+ .map(|n| format!("{base}-{n}"))
+ .find(|k| k.len() <= 63 && !taken.contains(k))
+ .ok_or_else(|| Error::invalid(format!("no free name for {base}")))
+ }
+
/// Adds an agent member: a persistent agent of `spec.space`, added by
/// `caller`, with its policy (`durable`, `on`, `once`) and 1 to
/// [`MAX_SESSIONS`] sessions. Its Space's `.cua/setup` runs before it
- /// gets a task. A persistent agent that exists already (same harness and
- /// Space, for example one an older Cua created) takes the new policy.
+ /// gets a task. A member of that name that exists already in the Space
+ /// (same harness, for example one an older Cua created) takes the new
+ /// policy. A name used by another Space does not matter: each Space's
+ /// `@claude` is its own.
pub fn add_member(
&self,
caller: &Caller,
@@ -307,19 +332,45 @@ impl Persistent {
"on: auto needs the member's Space to be a durable Space",
));
}
- let existing = self.get(&spec.name).ok();
- let rec = match existing {
+ let space = self.spaces.resolve(&spec.space)?.to_string();
+ let wanted = spec.name.clone();
+ // This Space's own member of that name (an older Cua's included).
+ let here = self
+ .members_of(&space)?
+ .into_iter()
+ .find(|r| r.handle() == wanted);
+ let rec = match here {
Some(r) => {
- let space = self.spaces.resolve(&spec.space)?.to_string();
- if r.harness != spec.harness || r.space != space {
+ if r.harness != spec.harness {
return Err(Error::invalid(format!(
- "a persistent agent named {} exists with another harness or Space",
- r.name
+ "{wanted} in this Space is {}, not {}: pick another name",
+ r.harness, spec.harness
)));
}
r
}
- None => self.create(spec)?,
+ None => {
+ // Names are keys on this machine, but a Space's `@claude` is its
+ // own: when the key is taken elsewhere (or by a Space that is
+ // gone, which frees it), this Space's member gets a key of its
+ // own and answers to the name it was asked for.
+ let mut spec = spec;
+ if let Ok(other) = self.get(&wanted) {
+ if self.space_is_gone(&other.space) {
+ locked_json(&self.agents_path(), |all: &mut Vec<AgentRecord>| {
+ all.retain(|a| a.name != other.name)
+ })?;
+ } else {
+ spec.name = self.free_key(&wanted)?;
+ }
+ }
+ let alias = (spec.name != wanted).then(|| wanted.clone());
+ let rec = self.create(spec)?;
+ if alias.is_some() {
+ self.update(&rec.name, |r| r.handle = alias.clone())?;
+ }
+ self.get(&rec.name)?
+ }
};
let added_by = self.author_for(caller);
self.update(&rec.name, |r| {
@@ -400,7 +451,7 @@ impl Persistent {
.and_then(|seq| fold.tasks.get(&seq))
.map(|t| format!("task #{}: {}", t.seq, clip_words(&t.text, 80))),
"failed" if r.setup == super::durable::setup::FAILED => {
- Some(super::notify::short_reason(&r.setup_note))
+ Some(super::notify::reason(&r.setup_note))
}
"waiting" => sessions
.iter()
@@ -410,7 +461,7 @@ impl Persistent {
.iter()
.find(|s| s.state == "failed")
.and_then(|s| s.activity.clone())
- .or_else(|| r.last_error.as_deref().map(super::notify::short_reason)),
+ .or_else(|| r.last_error.as_deref().map(|e| failed_line(&r.harness, e))),
"idle" | "asleep" if open > 0 => Some(format!(
"{open} open task{}",
if open == 1 { "" } else { "s" }
@@ -421,6 +472,15 @@ impl Persistent {
if let Some(a) = activity {
status["activity"] = json!(a);
}
+ // The typed failure (and its complete text) of a failed member.
+ if state == "failed"
+ && let Some(f) = sessions
+ .iter()
+ .find_map(|s| s.failure.clone())
+ .or_else(|| r.last_error.as_deref().map(|e| failure_for(&r, e)))
+ {
+ status["failure"] = json!(f);
+ }
let mut row = member_row(&r, &self.owner());
row["run_id"] = json!(r.run_id);
row["status"] = status;
@@ -604,12 +664,26 @@ impl Persistent {
Ok(Delivered::Busy)
}
Err(e) => {
+ // The agent answers in the thread: plain words, with the
+ // complete error (and a Connect button when it needs a
+ // sign-in) in `failure`.
+ let failure = failure_for(rec, &e.to_string());
+ let mut reply = Draft::new(
+ Author::agent(&rec.name),
+ EntryKind::Message,
+ ag::failure::plain(&failure),
+ );
+ reply.reply_to = Some(task.seq);
+ reply.failure = Some(failure);
store.release(
task.seq,
- vec![update(
- TaskState::Failed,
- format!("could not start {}: {e}", session_name(rec)),
- )],
+ vec![
+ reply,
+ update(
+ TaskState::Failed,
+ format!("could not start {}", session_name(rec)),
+ ),
+ ],
)?;
Err(e)
}
@@ -787,8 +861,10 @@ impl Persistent {
{
let mut drafts = vec![];
if !t.replied {
- let text = match (&error, &answer) {
- (Some(e), _) => format!("Failed: {}", super::notify::short_reason(e)),
+ let failure = error.as_deref().map(|e| failure_for(rec, e));
+ let text = match (&failure, &answer) {
+ // Plain words; the complete error rides along as `failure`.
+ (Some(f), _) => ag::failure::plain(f),
(None, Some(a)) if !a.trim().is_empty() => a.trim().to_string(),
_ => "Finished.".to_string(),
};
@@ -800,6 +876,7 @@ impl Persistent {
};
let mut reply = Draft::new(Author::agent(&rec.name), EntryKind::Message, text);
reply.reply_to = Some(t.seq);
+ reply.failure = failure;
drafts.push(reply);
}
drafts.push(Draft::update(
@@ -1015,7 +1092,7 @@ pub fn member_row(r: &AgentRecord, owner: &Author) -> Value {
identity.collides.get_or_insert(false);
json!({
"identity": identity,
- "name": r.name, "harness": r.harness, "space": r.space, "model": r.model,
+ "name": r.name, "handle": r.handle(), "harness": r.harness, "space": r.space, "model": r.model,
"sessions": r.sessions, "policy": r.policy,
"added_by": r.added_by.clone().unwrap_or_else(|| owner.clone()),
"member_since_ms": if r.member_since_ms > 0 { r.member_since_ms } else { r.created_ms },
@@ -1072,10 +1149,20 @@ impl Thread {
.p
.members_of(self.store.space())?
.into_iter()
- .map(|r| r.name)
+ .map(|r| r.handle().to_string())
.collect())
}
+ /// The key of this Space's member that answers to `@handle`.
+ fn member_key(&self, handle: &str) -> Option<String> {
+ self.p
+ .members_of(self.store.space())
+ .ok()?
+ .into_iter()
+ .find(|r| r.handle() == handle)
+ .map(|r| r.name)
+ }
+
/// Posts as the caller. An @mention of an agent member (not the author
/// itself) makes the entry a task for the first one mentioned.
pub async fn post(&self, args: PostArgs) -> Result<ThreadEntry> {
@@ -1090,9 +1177,11 @@ impl Thread {
}
let author = self.author();
let members = self.member_names()?;
+ // `@claude` of this Space is the member's key (`claude-2` in a second Space).
let mentions: Vec<String> = parse_mentions(&args.text)
.into_iter()
.filter(|m| members.contains(m))
+ .filter_map(|m| self.member_key(&m))
.collect();
let fold = self.store.fold()?;
let mut kind = EntryKind::Message;
@@ -1775,6 +1864,27 @@ fn session_name(rec: &AgentRecord) -> String {
}
}
+/// The typed failure of `rec`'s turn or start with the error text `e`: its
+/// class, the provider to connect, and the complete text (a text that looks
+/// like a secret is withheld, as everything posted to the thread is).
+pub(crate) fn failure_for(rec: &AgentRecord, e: &str) -> ag::failure::Failure {
+ let mut f = ag::failure::classify(&rec.harness, e);
+ if check_text(&f.message).is_err() {
+ f.message = "(details withheld: they looked like they held a secret)".into();
+ }
+ f
+}
+
+/// A failed member's status line: "Not connected" when it needs a sign-in,
+/// else the error's first line, whole.
+fn failed_line(harness: &str, e: &str) -> String {
+ let f = ag::failure::classify(harness, e);
+ match f.class {
+ ag::failure::FailureClass::NeedsConnect => "Not connected".into(),
+ ag::failure::FailureClass::Error => super::notify::reason(e),
+ }
+}
+
/// One session of an agent member, as `agent_members` shows it.
#[derive(Clone, Debug, PartialEq, Eq, Serialize)]
pub struct SessionState {
@@ -1786,6 +1896,10 @@ pub struct SessionState {
/// what it waits for, or why it failed.
#[serde(skip_serializing_if = "Option::is_none")]
pub activity: Option<String>,
+ /// For a failed session: what failed, typed (`needs_connect` and the
+ /// provider, or an error) with the complete text.
+ #[serde(skip_serializing_if = "Option::is_none")]
+ pub failure: Option<ag::failure::Failure>,
/// The task its turn works on.
#[serde(skip_serializing_if = "Option::is_none")]
pub task_seq: Option<u64>,
@@ -1824,13 +1938,23 @@ pub fn session_state(
.map(|t| format!("task #{}: {}", t.seq, clip_words(&t.text, 80)))
}),
"waiting" => asked.map(|a| format!("waiting for an answer to #{a}")),
- "failed" => s.last_error.as_deref().map(super::notify::short_reason),
+ "failed" => s.last_error.as_deref().map(|e| failed_line(&s.harness, e)),
_ => None,
};
+ // An error is never cut: only a working line is clipped.
+ let activity = if state == "failed" {
+ activity
+ } else {
+ activity.map(|a| clip_line(&a, 80))
+ };
+ let failure = (state == "failed")
+ .then(|| s.last_error.as_deref().map(|e| failure_for(s, e)))
+ .flatten();
SessionState {
k: s.k(),
state,
- activity: activity.map(|a| clip_line(&a, 80)),
+ activity,
+ failure,
task_seq,
run_id: s.run_id.clone(),
}
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 0ba9851bf2..969354863f 100644
--- a/libs/cua/crates/cua-spaces-ext/src/persistent/mod.rs
+++ b/libs/cua/crates/cua-spaces-ext/src/persistent/mod.rs
@@ -119,7 +119,13 @@ pub struct Recreate {
/// One persistent agent.
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct AgentRecord {
+ /// The record's key on this machine: unique across Spaces.
pub name: String,
+ /// What its Space calls it (`@claude`), when that is not `name`: a
+ /// second Space's `claude` is stored as `claude-2` and still answers to
+ /// `@claude` there. Absent: the name is the handle.
+ #[serde(default, skip_serializing_if = "Option::is_none")]
+ pub handle: Option<String>,
/// Harness id (`claude-code`, `openai-codex`, `hermes`, `openclaw`, ...).
pub harness: String,
/// The Space it works in (a Space id).
@@ -269,6 +275,11 @@ pub struct SessionRun {
pub const MAX_SESSIONS: u32 = 8;
impl AgentRecord {
+ /// What its Space calls it: the `@handle`.
+ pub fn handle(&self) -> &str {
+ self.handle.as_deref().unwrap_or(&self.name)
+ }
+
/// The session this record shows (1-based).
pub fn k(&self) -> u32 {
self.session_k.max(1)
@@ -595,6 +606,7 @@ impl Persistent {
}
let rec = AgentRecord {
name: spec.name.clone(),
+ handle: None,
harness: h.id.into(),
space,
model: spec.model,
@@ -1025,6 +1037,27 @@ impl Persistent {
"{name} is in the middle of a turn (it crashed and is being resumed); try again when it ends"
)));
}
+ // An idle run whose credentials are not the ones forwarded
+ // now (the person reconnected in Settings), or whose last
+ // turn failed to authenticate, ends and starts again: it
+ // would otherwise keep using what it began with.
+ Ok(st)
+ if st.accepts_message
+ && st.status == RunStatus::Idle
+ && self.credentials_changed(&rec, &agents, run, &st).await =>
+ {
+ tracing::info!(
+ agent = name,
+ "credentials changed or rejected: starting a fresh run"
+ );
+ if rec.k() == 1 {
+ let _ = self.save(name).await;
+ }
+ if let Err(e) = agents.stop(run).await {
+ tracing::warn!(agent = name, "the old run did not stop: {e}");
+ }
+ self.release_writer(&rec).await;
+ }
Ok(st) if st.accepts_message && st.status == RunStatus::Idle => {
if rec.k() == 1 && !self.live.lock().await.leases.contains_key(name) {
self.take_lease(&rec).await?;
@@ -1044,6 +1077,35 @@ impl Persistent {
self.start_session(&rec, text, entry, None).await
}
+ /// Whether the idle run `run` of `rec` must not take another message:
+ /// it was started with other credentials than the ones forwarded now, or
+ /// its last turn failed to authenticate.
+ async fn credentials_changed(
+ &self,
+ rec: &AgentRecord,
+ agents: &cua_spaces::agents::Agents,
+ run: &str,
+ st: &ag::RunInfo,
+ ) -> bool {
+ if let Some(started) = st.meta.as_ref().and_then(|m| m.cred_hash.as_deref())
+ && let Ok((env, _)) = cua_spaces::agents::run_env(
+ &rec.harness,
+ &rec.env,
+ &rec.env_from_host,
+ rec.base_url.is_some(),
+ )
+ && ag::runs::credential_hash(&rec.harness, &env) != started
+ {
+ return true;
+ }
+ if st.stop_reason.as_deref() == Some("error")
+ && let Ok(r) = agents.result(run).await
+ {
+ return r.error.as_deref().is_some_and(ag::failure::is_auth_failure);
+ }
+ false
+ }
+
async fn stop_run(&self, rec: &AgentRecord) -> Result<Option<String>> {
let Some(run) = &rec.run_id else {
return Ok(None);
diff --git a/libs/cua/crates/cua-spaces-ext/src/persistent/notify.rs b/libs/cua/crates/cua-spaces-ext/src/persistent/notify.rs
index 7cdbcfb843..83ac622f04 100644
--- a/libs/cua/crates/cua-spaces-ext/src/persistent/notify.rs
+++ b/libs/cua/crates/cua-spaces-ext/src/persistent/notify.rs
@@ -52,6 +52,10 @@ const MAX_REASON: usize = 80;
/// The title of a failed run or turn: "<agent> stopped: <short reason>".
pub fn stopped_title(agent: &str, error: &str) -> String {
+ // A rejected or missing sign-in is said in words, not as the provider's error.
+ if cua_agents::failure::is_auth_failure(error) {
+ return format!("{agent} needs you to connect it");
+ }
format!("{agent} stopped: {}", short_reason(error))
}
@@ -59,6 +63,17 @@ pub fn stopped_title(agent: &str, error: &str) -> String {
/// error object (`API Error: 401 {"error":{"message":"invalid x-api-key"}}`)
/// reduced to its message.
pub fn short_reason(error: &str) -> String {
+ let r = reason(error);
+ if r == "unknown error" {
+ r
+ } else {
+ clip(&r, MAX_REASON)
+ }
+}
+
+/// [`short_reason`] without the clip: the error's first line as it is
+/// (surfaces that draw errors never cut them).
+pub fn reason(error: &str) -> String {
let first = error
.lines()
.map(str::trim)
@@ -84,7 +99,7 @@ pub fn short_reason(error: &str) -> String {
if short.is_empty() {
"unknown error".into()
} else {
- clip(short, MAX_REASON)
+ short.to_string()
}
}
@@ -204,16 +219,16 @@ mod tests {
#[test]
fn a_failure_title_names_the_agent_and_a_short_reason() {
assert_eq!(
- stopped_title("Claude Code", "Invalid API key · Please run /login"),
- "Claude Code stopped: Invalid API key · Please run /login"
- );
- assert_eq!(
- stopped_title(
- "ada",
- r#"API Error: 401 {"type":"error","error":{"type":"authentication_error","message":"invalid x-api-key"}}"#
- ),
- "ada stopped: API Error: 401 invalid x-api-key"
+ stopped_title("Claude Code", "rate limit reached for this model"),
+ "Claude Code stopped: rate limit reached for this model"
);
+ // A rejected or missing sign-in is said in words, never as the provider's error.
+ for raw in [
+ "Invalid API key · Please run /login",
+ r#"API Error: 401 {"type":"error","error":{"type":"authentication_error","message":"invalid x-api-key"}}"#,
+ ] {
+ assert_eq!(stopped_title("ada", raw), "ada needs you to connect it");
+ }
assert_eq!(
short_reason("Authentication required.\nsee the log"),
"Authentication required"
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 0470d66665..cbbd72c5fa 100644
--- a/libs/cua/crates/cua-spaces-ext/src/thread/mod.rs
+++ b/libs/cua/crates/cua-spaces-ext/src/thread/mod.rs
@@ -551,6 +551,11 @@ pub struct ThreadEntry {
/// What the person was looking at when they posted ([`ViewContext`]).
#[serde(default, skip_serializing_if = "Option::is_none")]
pub view: Option<ViewContext>,
+ /// On an agent's reply to a task that failed: what failed
+ /// (`needs_connect` with the provider to connect, or an error), with
+ /// the complete text. `text` says it in plain words.
+ #[serde(default, skip_serializing_if = "Option::is_none")]
+ pub failure: Option<cua_agents::failure::Failure>,
/// Fields of a newer format, kept as they are.
#[serde(flatten)]
pub extra: Map<String, Value>,
@@ -579,6 +584,7 @@ pub struct Draft {
pub event: Option<Value>,
pub join_request: Option<JoinRequest>,
pub view: Option<ViewContext>,
+ pub failure: Option<cua_agents::failure::Failure>,
}
impl Draft {
@@ -602,6 +608,7 @@ impl Draft {
event: None,
join_request: None,
view: None,
+ failure: None,
}
}
@@ -968,6 +975,7 @@ impl ThreadStore {
event: d.event,
join_request: d.join_request,
view: d.view,
+ failure: d.failure,
extra: Map::new(),
};
self.write_entry(&mut head, &e)?;
diff --git a/libs/cua/crates/cua-spaces-ext/tests/agent_failure_notifications.rs b/libs/cua/crates/cua-spaces-ext/tests/agent_failure_notifications.rs
index 33c0fee5f3..710fecf627 100644
--- a/libs/cua/crates/cua-spaces-ext/tests/agent_failure_notifications.rs
+++ b/libs/cua/crates/cua-spaces-ext/tests/agent_failure_notifications.rs
@@ -141,7 +141,7 @@ async fn an_agent_start_run_posts_one_notification_per_failed_turn() {
assert_eq!(
n,
vec![(
- "Claude Code stopped: API Error: 401 invalid x-api-key".to_string(),
+ "Claude Code needs you to connect it".to_string(),
AUTH_401.to_string()
)]
);
@@ -179,10 +179,7 @@ async fn an_agent_start_run_posts_one_notification_per_failed_turn() {
);
p.tick().await;
assert_eq!(errors(&p).len(), 2);
- assert_eq!(
- errors(&p)[1].0,
- "Claude Code stopped: Authentication required"
- );
+ assert_eq!(errors(&p)[1].0, "Claude Code needs you to connect it");
// The runner gives up (state failed, same turn): nothing more, and the
// run is no longer followed once its process is gone.
@@ -238,8 +235,7 @@ async fn a_key_the_provider_rejects_at_the_start_posts_one_notification() {
assert_eq!(
errors(&p),
vec![(
- "Claude Code stopped: Failed to authenticate. Anthropic API Error: 401 API key is invalid"
- .to_string(),
+ "Claude Code needs you to connect it".to_string(),
KEY_CHECK_401.to_string()
)]
);
@@ -326,10 +322,7 @@ async fn a_persistent_agent_failed_turn_is_one_stopped_notification() {
let all = p.feed().list(false, None).unwrap();
assert_eq!(all.len(), 1, "{all:?}");
assert_eq!(all[0].kind, "error");
- assert_eq!(
- all[0].title,
- "ada stopped: API Error: 401 invalid x-api-key"
- );
+ assert_eq!(all[0].title, "ada needs you to connect it");
assert_eq!(all[0].agent.as_deref(), Some("ada"));
// The pass recorded a problem (here: the mock cannot save the home).
assert!(p.get("ada").unwrap().last_error.is_some());
diff --git a/libs/cua/crates/cua-spaces-ext/tests/agent_tool_aliases.rs b/libs/cua/crates/cua-spaces-ext/tests/agent_tool_aliases.rs
index 3dcbd837ff..517543fbad 100644
--- a/libs/cua/crates/cua-spaces-ext/tests/agent_tool_aliases.rs
+++ b/libs/cua/crates/cua-spaces-ext/tests/agent_tool_aliases.rs
@@ -54,6 +54,7 @@ fn strip(mut v: Value) -> Value {
"member_since_ms",
"next_fire",
"name",
+ "handle",
"botID",
] {
if let Some(o) = v.as_object_mut() {
diff --git a/libs/cua/crates/cua-spaces-ext/tests/thread_compat.rs b/libs/cua/crates/cua-spaces-ext/tests/thread_compat.rs
index c5d9c31829..f06d0f1e6e 100644
--- a/libs/cua/crates/cua-spaces-ext/tests/thread_compat.rs
+++ b/libs/cua/crates/cua-spaces-ext/tests/thread_compat.rs
@@ -1062,6 +1062,235 @@ fn the_daemon_reports_the_thread_feature() {
assert_eq!(cua_spaces_ext::thread::FEATURE, "thread.v1");
}
+/// `meta.json` of the idle run, as a runner that stored the hash of the
+/// credentials it started with writes it.
+fn run_meta_with_hash(fx: &Fx, hash: &str) {
+ let meta = json!({"run_id": RUN, "harness": "claude-code", "prompt": "hi",
+ "cwd": "/home/cua/work", "created_at": 0.0, "cred_hash": hash});
+ fx.srv.state.put_file(
+ &format!("{RUNS}/{RUN}/meta.json"),
+ meta.to_string().into_bytes(),
+ );
+}
+
+async fn run_alive(fx: &Fx) -> bool {
+ let s = fx.spaces.space(&fx.space).await.unwrap();
+ s.spacesd()
+ .unwrap()
+ .list_processes(false)
+ .await
+ .unwrap()
+ .iter()
+ .any(|p| p.tag == format!("cua-agent/{RUN}"))
+}
+
+fn forwarded_hash(key: &str) -> String {
+ cua_agents::runs::credential_hash(
+ "claude-code",
+ &std::collections::BTreeMap::from([("ANTHROPIC_API_KEY".to_string(), key.to_string())]),
+ )
+}
+
+#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
+async fn a_message_reaches_the_idle_run_while_its_credentials_are_the_ones_forwarded() {
+ let fx = setup().await;
+ let (p, _proc) = member_with_idle_run(&fx).await;
+ edit_record(&fx, "ada", |r| {
+ r["env"] = json!({"ANTHROPIC_API_KEY": "sk-one"})
+ });
+ run_meta_with_hash(&fx, &forwarded_hash("sk-one"));
+ let d = p.send("ada", "again").await.unwrap();
+ assert!(!d.started, "the idle run takes it");
+ assert_eq!(inbox(&fx), vec!["again".to_string()]);
+ assert!(run_alive(&fx).await);
+}
+
+/// Reconnecting in Settings must take effect on the next message: a run that
+/// began with other credentials is ended, not reused.
+#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
+async fn a_changed_credential_ends_the_idle_run_instead_of_reusing_it() {
+ let fx = setup().await;
+ let (p, _proc) = member_with_idle_run(&fx).await;
+ edit_record(&fx, "ada", |r| {
+ r["env"] = json!({"ANTHROPIC_API_KEY": "sk-new"})
+ });
+ run_meta_with_hash(&fx, &forwarded_hash("sk-old"));
+ // The mock runs no shell, so the fresh start itself can't finish here;
+ // what matters is that the old run did not get the message and is gone.
+ let _ = p.send("ada", "again").await;
+ // (Stopping a run leaves a control message, not a prompt.)
+ assert!(
+ inbox(&fx).iter().all(|t| t.is_empty()),
+ "the old run was not reused: {:?}",
+ inbox(&fx)
+ );
+ assert!(!run_alive(&fx).await, "the old run was ended");
+}
+
+/// A run whose last turn failed to authenticate is not reused either, even
+/// with the same credentials (the provider rejected them).
+#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
+async fn a_run_that_failed_to_authenticate_is_not_reused() {
+ let fx = setup().await;
+ let (p, _proc) = member_with_idle_run(&fx).await;
+ edit_record(&fx, "ada", |r| {
+ r["env"] = json!({"ANTHROPIC_API_KEY": "sk-one"})
+ });
+ run_meta_with_hash(&fx, &forwarded_hash("sk-one"));
+ events(
+ &fx,
+ &[
+ ("turn_started", 2, None),
+ (
+ "error",
+ 2,
+ Some("Failed to authenticate. API Error: 401 OAuth access token is invalid"),
+ ),
+ ("turn_ended", 2, None),
+ ],
+ );
+ run_state(
+ &fx,
+ json!({"status": "idle", "turn": 2, "stopReason": "error"}),
+ );
+ run_meta_with_hash(&fx, &forwarded_hash("sk-one"));
+ let _ = p.send("ada", "again").await;
+ assert!(inbox(&fx).iter().all(|t| t.is_empty()), "{:?}", inbox(&fx));
+ assert!(!run_alive(&fx).await);
+}
+
+/// A second Space of the same machine (its own mock guest).
+async fn second_space(fx: &Fx) -> (MockServer, String) {
+ let srv = MockServer::start(MockAuth::default()).await;
+ let info = fx
+ .spaces
+ .add(
+ &format!("http://{}", srv.addr),
+ None,
+ Some("room-two".into()),
+ )
+ .await
+ .unwrap();
+ (srv, info.id)
+}
+
+async fn add_claude(fx: &Fx, space: &str) -> Result<Value, (String, String)> {
+ call(
+ &fx.mcp,
+ "agent_add",
+ json!({"space": space, "name": "claude", "harness": "claude-code"}),
+ )
+ .await
+}
+
+async fn member_names(fx: &Fx, space: &str) -> Vec<(String, String)> {
+ let m = call(&fx.mcp, "agent_members", json!({"space": space}))
+ .await
+ .unwrap();
+ m["members"]
+ .as_array()
+ .unwrap()
+ .iter()
+ .map(|r| {
+ (
+ r["name"].as_str().unwrap().to_string(),
+ r["handle"].as_str().unwrap().to_string(),
+ )
+ })
+ .collect()
+}
+
+/// Names were keys on the machine: the first Space with a `claude` owned the
+/// name and `@claude` in any other Space failed with "exists with another
+/// harness or Space". Each Space's `@claude` is its own now.
+#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
+async fn two_spaces_each_get_their_own_claude() {
+ let fx = setup().await;
+ let (_srv2, two) = second_space(&fx).await;
+ add_claude(&fx, &fx.space).await.unwrap();
+ add_claude(&fx, &two).await.unwrap();
+ // The first keeps the plain name; the second is stored apart and still answers to `claude`.
+ assert_eq!(
+ member_names(&fx, &fx.space).await,
+ [("claude".to_string(), "claude".to_string())]
+ );
+ assert_eq!(
+ member_names(&fx, &two).await,
+ [("claude-2".to_string(), "claude".to_string())]
+ );
+ // Adding again in either Space is the same member, not a third.
+ add_claude(&fx, &two).await.unwrap();
+ assert_eq!(member_names(&fx, &two).await.len(), 1);
+ // `@claude` in the second Space is a task for the second Space's member.
+ let posted = call(
+ &fx.mcp,
+ "thread_post",
+ json!({"space": two, "text": "@claude hello"}),
+ )
+ .await
+ .unwrap();
+ assert_eq!(posted["entry"]["task"]["to"], "claude-2");
+ assert_eq!(posted["entry"]["mentions"], json!(["claude-2"]));
+ let first = call(
+ &fx.mcp,
+ "thread_post",
+ json!({"space": fx.space, "text": "@claude hello"}),
+ )
+ .await
+ .unwrap();
+ assert_eq!(first["entry"]["task"]["to"], "claude");
+}
+
+/// Deleting a Space frees its members' names.
+#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
+async fn a_deleted_spaces_name_is_free_for_a_new_space() {
+ let fx = setup().await;
+ let (_srv2, two) = second_space(&fx).await;
+ add_claude(&fx, &fx.space).await.unwrap();
+ fx.spaces.remove(&fx.space).await.unwrap();
+ // The first Space is gone: `claude` is the second Space's, under its own plain name.
+ add_claude(&fx, &two).await.unwrap();
+ assert_eq!(
+ member_names(&fx, &two).await,
+ [("claude".to_string(), "claude".to_string())]
+ );
+}
+
+/// A record from before Spaces had their own names (name only) keeps working.
+#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
+async fn an_old_name_only_record_still_answers_in_its_space() {
+ let fx = setup().await;
+ std::fs::create_dir_all(agents_json(&fx).parent().unwrap()).unwrap();
+ let old = json!([{
+ "name": "claude", "harness": "claude-code", "space": fx.space,
+ "created_ms": 1761000000000u64, "paused": false, "space_state": "running",
+ "cursor": 0, "saved_turn": 0, "notify": true, "saved_ms": 0
+ }]);
+ std::fs::write(agents_json(&fx), old.to_string()).unwrap();
+ assert_eq!(
+ member_names(&fx, &fx.space).await,
+ [("claude".to_string(), "claude".to_string())]
+ );
+ // Adding it again in its own Space is that record, not a new one.
+ add_claude(&fx, &fx.space).await.unwrap();
+ assert_eq!(member_names(&fx, &fx.space).await.len(), 1);
+ let posted = call(
+ &fx.mcp,
+ "thread_post",
+ json!({"space": fx.space, "text": "@claude hi"}),
+ )
+ .await
+ .unwrap();
+ assert_eq!(posted["entry"]["task"]["to"], "claude");
+ // And a second Space can have its own.
+ let (_srv2, two) = second_space(&fx).await;
+ add_claude(&fx, &two).await.unwrap();
+ assert_eq!(
+ member_names(&fx, &two).await,
+ [("claude-2".to_string(), "claude".to_string())]
+ );
+}
+
#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
async fn a_failed_turn_fails_its_task_and_the_notification_points_at_it() {
let fx = setup().await;
@@ -1093,7 +1322,16 @@ async fn a_failed_turn_fails_its_task_and_the_notification_points_at_it() {
.iter()
.find(|x| x["reply_to"] == task && x["kind"] == "message")
.expect("a reply");
- assert_eq!(reply["text"], "Failed: Authentication required");
+ // Plain words from the agent; the complete error rides along typed, and
+ // the harness's own words are never the summary.
+ assert_eq!(
+ reply["text"],
+ "I can't reach Claude yet. Connect Claude, then try again."
+ );
+ assert_eq!(reply["failure"]["class"], "needs_connect");
+ assert_eq!(reply["failure"]["provider"], "anthropic");
+ assert_eq!(reply["failure"]["message"], "Authentication required");
+ assert_eq!(reply["failure"]["retryable"], true);
let update = e.iter().rev().find(|x| x["kind"] == "task_update").unwrap();
assert_eq!(update["update"]["state"], "failed");
let n = p
diff --git a/libs/cua/crates/cua-spaces-ffi/src/app_core_types.rs b/libs/cua/crates/cua-spaces-ffi/src/app_core_types.rs
index 2e82d47d52..bb3ee0a2d6 100644
--- a/libs/cua/crates/cua-spaces-ffi/src/app_core_types.rs
+++ b/libs/cua/crates/cua-spaces-ffi/src/app_core_types.rs
@@ -6669,6 +6669,8 @@ pub struct AppAgentKeyInput {
pub last4: String,
/// When it was added (Unix ms).
pub added_ms: u64,
+ /// A sign-in past its expiry: not used by any run until reconnected.
+ pub expired: bool,
}
/// What the section shows.
diff --git a/libs/cua/crates/cua-spaces/src/agents/keys.rs b/libs/cua/crates/cua-spaces/src/agents/keys.rs
index c936ab9586..661fa99987 100644
--- a/libs/cua/crates/cua-spaces/src/agents/keys.rs
+++ b/libs/cua/crates/cua-spaces/src/agents/keys.rs
@@ -263,6 +263,8 @@ pub struct KeyInfo {
/// When a copied sign-in stops working (Unix ms), when known.
#[serde(skip_serializing_if = "Option::is_none")]
pub expires_ms: Option<u64>,
+ /// It has stopped working (`expires_ms` has passed): runs no longer get it.
+ pub expired: bool,
}
/// `agent_keys.list`: the stored keys and whether this machine can store
@@ -303,6 +305,11 @@ impl std::fmt::Debug for Stored {
}
impl Stored {
+ /// Past its `expires_ms` (a copied sign-in that stopped working).
+ fn expired(&self) -> bool {
+ self.expires_ms.is_some_and(|e| e <= now_ms())
+ }
+
fn info(&self) -> KeyInfo {
let n = self.value.chars().count();
let last4 = if n >= 12 {
@@ -318,6 +325,7 @@ impl Stored {
label: self.label.clone(),
source: self.source.clone(),
expires_ms: self.expires_ms,
+ expired: self.expired(),
}
}
}
@@ -596,7 +604,11 @@ impl AgentKeys {
pub fn names(&self) -> Vec<String> {
let mut g = self.lock();
match self.read(&mut g, false) {
- Ok(keys) => keys.into_iter().map(|k| k.env).collect(),
+ Ok(keys) => keys
+ .into_iter()
+ .filter(|k| !k.expired())
+ .map(|k| k.env)
+ .collect(),
Err(e) => {
tracing::warn!(error = %e, "agent keys: the store can't be read");
vec![]
@@ -614,7 +626,9 @@ impl AgentKeys {
match self.read(&mut g, false) {
Ok(keys) => keys
.into_iter()
- .filter(|k| names.contains(&k.env.as_str()))
+ // A sign-in past its expiry is not forwarded: the run would
+ // only be told 401 by the provider.
+ .filter(|k| names.contains(&k.env.as_str()) && !k.expired())
.map(|k| (k.env, k.value))
.collect(),
Err(e) => {
@@ -841,6 +855,38 @@ mod tests {
let _ = std::fs::remove_dir_all(dir);
}
+ /// An expired sign-in is listed as expired, and no run gets it.
+ #[test]
+ fn an_expired_sign_in_reaches_no_run() {
+ let (keys, dir) = temp_keys();
+ let long_ago = now_ms() - 1_000;
+ keys.import(
+ "claude-code",
+ "CLAUDE_CODE_OAUTH_TOKEN",
+ "Claude Code · Claude sign-in",
+ "sk-ant-oat01-test",
+ Some(long_ago),
+ )
+ .unwrap();
+ let listed = keys.list().unwrap();
+ assert!(listed[0].expired && listed[0].expires_ms == Some(long_ago));
+ assert!(keys.names().is_empty());
+ assert!(keys.values(&["CLAUDE_CODE_OAUTH_TOKEN"]).is_empty());
+ // One that has time left still goes.
+ keys.import(
+ "claude-code",
+ "CLAUDE_CODE_OAUTH_TOKEN",
+ "Claude Code · Claude sign-in",
+ "sk-ant-oat01-test",
+ Some(now_ms() + 3_600_000),
+ )
+ .unwrap();
+ assert!(!keys.list().unwrap()[0].expired);
+ assert_eq!(keys.names(), ["CLAUDE_CODE_OAUTH_TOKEN"]);
+ assert_eq!(keys.values(&["CLAUDE_CODE_OAUTH_TOKEN"]).len(), 1);
+ let _ = std::fs::remove_dir_all(&dir);
+ }
+
#[test]
fn a_short_key_shows_no_characters() {
let (keys, dir) = temp_keys();
diff --git a/libs/cua/crates/cua-spaces/src/agents/mod.rs b/libs/cua/crates/cua-spaces/src/agents/mod.rs
index 520c258da5..51255a633b 100644
--- a/libs/cua/crates/cua-spaces/src/agents/mod.rs
+++ b/libs/cua/crates/cua-spaces/src/agents/mod.rs
@@ -18,8 +18,8 @@ use std::collections::BTreeMap;
pub mod keys;
pub use cua_agents::{
AgentEvent, Agents, Artifact, Attachment, Endpoint, EventPage, McpServer, RunInfo, RunOptions,
- RunResult, RunStatus, Started, Transcript, TranscriptItem, Wire, events, harness, installables,
- quote, runs, transcript,
+ RunResult, RunStatus, Started, Transcript, TranscriptItem, Wire, events, failure, harness,
+ installables, quote, runs, transcript,
};
impl From<cua_agents::Error> for Error {
diff --git a/libs/spaces-app-swift/Sources/CuaSpacesFFI/CuaSpacesFFI.swift b/libs/spaces-app-swift/Sources/CuaSpacesFFI/CuaSpacesFFI.swift
index cab5632bc6..5dfc81f991 100644
--- a/libs/spaces-app-swift/Sources/CuaSpacesFFI/CuaSpacesFFI.swift
+++ b/libs/spaces-app-swift/Sources/CuaSpacesFFI/CuaSpacesFFI.swift
@@ -4431,6 +4431,10 @@ public struct AppAgentKeyInput: Equatable, Hashable {
* When it was added (Unix ms).
*/
public var addedMs: UInt64
+ /**
+ * A sign-in past its expiry: not used by any run until reconnected.
+ */
+ public var expired: Bool
// Default memberwise initializers are never public by default, so we
// declare one manually.
@@ -4446,11 +4450,15 @@ public struct AppAgentKeyInput: Equatable, Hashable {
*/last4: String,
/**
* When it was added (Unix ms).
- */addedMs: UInt64) {
+ */addedMs: UInt64,
+ /**
+ * A sign-in past its expiry: not used by any run until reconnected.
+ */expired: Bool) {
self.provider = provider
self.env = env
self.last4 = last4
self.addedMs = addedMs
+ self.expired = expired
}
@@ -4472,7 +4480,8 @@ public struct FfiConverterTypeAppAgentKeyInput: FfiConverterRustBuffer {
provider: FfiConverterString.read(from: &buf),
env: FfiConverterString.read(from: &buf),
last4: FfiConverterString.read(from: &buf),
- addedMs: FfiConverterUInt64.read(from: &buf)
+ addedMs: FfiConverterUInt64.read(from: &buf),
+ expired: FfiConverterBool.read(from: &buf)
)
}
@@ -4481,6 +4490,7 @@ public struct FfiConverterTypeAppAgentKeyInput: FfiConverterRustBuffer {
FfiConverterString.write(value.env, into: &buf)
FfiConverterString.write(value.last4, into: &buf)
FfiConverterUInt64.write(value.addedMs, into: &buf)
+ FfiConverterBool.write(value.expired, into: &buf)
}
}