Scale computer-use 2.0 with open-source drivers, cross-OS sandboxes, and benchmarks for training, evaluation, and data generation.
Rust agentai-agentapplecomputer-usecomputer-use-agentcontainerizationcuadesktop-automationhacktoberfestlumemacosmanusoperatorswiftvirtualizationvirtualization-frameworkwindowswindows-sandbox
fix(agents): import the Claude Code sign-in instead of running claude setup-token (#6136)
ddupont08a2f0df1cf2
diff --git a/apps/cua-spaces-desktop/src/native/generated/cua_sdk.ts b/apps/cua-spaces-desktop/src/native/generated/cua_sdk.tsindex c5dfdf1958..f26687cc09 100644--- a/apps/cua-spaces-desktop/src/native/generated/cua_sdk.ts+++ b/apps/cua-spaces-desktop/src/native/generated/cua_sdk.ts@@ -25959,8 +25959,9 @@ export interface AgentSetupLike {/*** Connect (and Reconnect) for `agents`: Cua's skills and MCP entry* (`server`, default this channel's cua), and with `sign_in` the- * agent's sign-in copied into Keyvault on This Mac (Claude Code waits- * for its one browser approval). JSON: one result per agent.+ * agent's sign-in copied into Keyvault on This Mac (Claude Code's is the+ * sign-in it already has, read from where Claude Code keeps it). JSON:+ * one result per agent.*/connectJson(agents: Array<string>, server: AgentMcpServer | undefined, skills: boolean, mcp: boolean, signIn: boolean, asyncOpts_?: { signal: AbortSignal }) /*throws*/: Promise<string>;/**@@ -26109,8 +26110,9 @@ private constructor(pointer: UniffiHandle) {/*** Connect (and Reconnect) for `agents`: Cua's skills and MCP entry* (`server`, default this channel's cua), and with `sign_in` the- * agent's sign-in copied into Keyvault on This Mac (Claude Code waits- * for its one browser approval). JSON: one result per agent.+ * agent's sign-in copied into Keyvault on This Mac (Claude Code's is the+ * sign-in it already has, read from where Claude Code keeps it). JSON:+ * one result per agent.*/async connectJson(agents: Array<string>, server: AgentMcpServer | undefined, skills: boolean, mcp: boolean, signIn: boolean, asyncOpts_?: { signal: AbortSignal }): Promise<string> /*throws*/ {const __stack = uniffiIsDebug ? new Error().stack : undefined;@@ -46853,7 +46855,7 @@ function uniffiEnsureInitialized() {if (nativeModule().uniffi_cua_sdk_checksum_method_agentsetup_configure_mcp() !== 53713) {throw new UniffiInternalError.ApiChecksumMismatch("uniffi_cua_sdk_checksum_method_agentsetup_configure_mcp");}- if (nativeModule().uniffi_cua_sdk_checksum_method_agentsetup_connect_json() !== 32481) {+ if (nativeModule().uniffi_cua_sdk_checksum_method_agentsetup_connect_json() !== 21138) {throw new UniffiInternalError.ApiChecksumMismatch("uniffi_cua_sdk_checksum_method_agentsetup_connect_json");}if (nativeModule().uniffi_cua_sdk_checksum_method_agentsetup_connection_status_json() !== 47692) {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.tsindex 48dda1f51f..7f31f3d2bc 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@@ -8832,7 +8832,11 @@ export type AppAgentKeyInput = {/*** A sign-in past its expiry: not used by any run until reconnected.*/- expired: boolean+ expired: boolean,+ /**+ * A copied sign-in's name ("Signed in as [email protected] (Claude Max)").+ */+ label?: string}/**@@ -8860,7 +8864,8 @@ const FfiConverterTypeAppAgentKeyInput = (() => {env: FfiConverterString.read(from),last4: FfiConverterString.read(from),addedMs: FfiConverterUInt64.read(from),- expired: FfiConverterBool.read(from)+ expired: FfiConverterBool.read(from),+ label: FfiConverterOptionalString.read(from)};}write(value: TypeName, into: RustBuffer): void {@@ -8869,13 +8874,15 @@ const FfiConverterTypeAppAgentKeyInput = (() => {FfiConverterString.write(value.last4, into);FfiConverterUInt64.write(value.addedMs, into);FfiConverterBool.write(value.expired, into);+ FfiConverterOptionalString.write(value.label, into);}allocationSize(value: TypeName): number {return FfiConverterString.allocationSize(value.provider) +FfiConverterString.allocationSize(value.env) +FfiConverterString.allocationSize(value.last4) +FfiConverterUInt64.allocationSize(value.addedMs) +- FfiConverterBool.allocationSize(value.expired);+ FfiConverterBool.allocationSize(value.expired) ++ FfiConverterOptionalString.allocationSize(value.label);}};diff --git a/apps/cua-spaces-macos/Sources/CuaSpacesMacKit/Models/AgentKeysModel.swift b/apps/cua-spaces-macos/Sources/CuaSpacesMacKit/Models/AgentKeysModel.swiftindex f6ebdb2bd8..6d78aba217 100644--- a/apps/cua-spaces-macos/Sources/CuaSpacesMacKit/Models/AgentKeysModel.swift+++ b/apps/cua-spaces-macos/Sources/CuaSpacesMacKit/Models/AgentKeysModel.swift@@ -71,7 +71,8 @@ public final class AgentKeysModel {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,- expired: k["expired"] as? Bool ?? false)+ expired: k["expired"] as? Bool ?? false,+ label: k["label"] as? String)}let unavailable = report?["available"] as? Bool == false? (report?["unavailable"] as? String ?? "this computer can't keep keys") : nildiff --git a/apps/cua-spaces-macos/Tests/CuaSpacesMacTests/WebUIVideoSurfacesTests.swift b/apps/cua-spaces-macos/Tests/CuaSpacesMacTests/WebUIVideoSurfacesTests.swiftindex 76dce20c7f..2a09957820 100644--- a/apps/cua-spaces-macos/Tests/CuaSpacesMacTests/WebUIVideoSurfacesTests.swift+++ b/apps/cua-spaces-macos/Tests/CuaSpacesMacTests/WebUIVideoSurfacesTests.swift@@ -648,11 +648,12 @@ 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 {+ /// A modal dialog over the viewer (the page's dimmed layer is up): the page reports the+ /// viewer occluded and non-interactive, so the native video is not drawn over the dialog+ /// or the dimmed page, takes no clicks, and gives the keyboard back; the stream keeps+ /// running, and the video, the pointer and the keys come back when the dialog closes.+ /// (A popover or menu over it is still a hole: `aMenuOverTheViewerCutsAHoleAndTheVideoStaysLive`.)+ @Test func aModalDialogOverTheViewerHidesItAndTakesItsKeysAndClicks() 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) }@@ -661,18 +662,17 @@ struct WebUIVideoSurfacesTests {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")+ // The dialog opens: occluded, not interactive, no holes (the whole video is hidden).+ s.handle(message([entry("v", space: "a", interactive: false, occluded: true)]))+ #expect(view.isHidden)#expect(s.focusedId == nil)- #expect(view.layer?.mask != nil)+ #expect(view.layer?.mask == nil)s.handle(["type": "focus", "surfaceId": "v"])#expect(s.focusedId == nil)- // Closed: the viewer takes the keyboard again.+ // Closed: it is drawn again and takes the keyboard again, still live.s.handle(message([entry("v", space: "a")]))+ #expect(!view.isHidden)+ #expect(host.phases("v").last == "live")s.handle(["type": "focus", "surfaceId": "v"])#expect(s.focusedId == "v")s.removeAll()diff --git a/apps/cua-spaces-macos/docs/native-video.md b/apps/cua-spaces-macos/docs/native-video.mdindex 56aba78862..15acf69520 100644--- a/apps/cua-spaces-macos/docs/native-video.md+++ b/apps/cua-spaces-macos/docs/native-video.md@@ -41,7 +41,7 @@ The page keeps one reporter, with one set of observers and one animation frame.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.+ **The Space viewer is not occluded by floating page UI** (CUA-2641): menus, popovers, the profile card, tooltips and toasts are holes over it. **A modal dialog hides it.** Every modal (our Dialog and AlertDialog, the ones that draw the dimmed layer `[data-window-dim]`: Connect, Share, Teleport, Keyvault approvals, the command palette) reports every slot, the viewer too, `occluded: true`, `interactive: false` and no holes, and the page hands the keyboard back (`{ type: "focus", surfaceId: null }`, once per dialog). The native video layer sits above the web view, so it can neither sit under the page's dimmed layer nor under the dialog: left drawn it showed over the dialog's edge and kept the pointer. Hidden, it draws nothing there and catches no pointer or keys, so the local cursor stays visible everywhere over the dialog. The stream keeps running. When the dialog starts to close (`data-ending-style`) the next measurement reports the viewer drawn and interactive again, with no state left over. In the Electron shell, where the page draws the video itself, the canvas takes no pointer events and gives up the keyboard while a modal is open, and takes both again when it closes.- **`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.diff --git a/apps/cua-spaces-web/e2e/space-popups-stream.spec.ts b/apps/cua-spaces-web/e2e/space-popups-stream.spec.tsindex 2a86b104e6..44a57cdaa5 100644--- a/apps/cua-spaces-web/e2e/space-popups-stream.spec.ts+++ b/apps/cua-spaces-web/e2e/space-popups-stream.spec.ts@@ -13,8 +13,9 @@* 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).+ * and, under a modal dialog (the dimmed layer), hidden and non-interactive:+ * the native layer cannot sit under the dialog, so the host draws nothing and+ * takes no pointer or keys until it closes (CUA-2758).*/import type { Page } from "@playwright/test";@@ -89,13 +90,15 @@ test("every popup on a Space's page leaves the stream drawn, the same size, withexpect(box, name).not.toBeNull();const now = await viewer(page);const over = overlaps(box, before.rect);- if (over) {+ if (over && !modal) {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);+ // A modal dialog hides the video (no hole, nothing drawn over its edge); anything else leaves it drawn.+ await expect.poll(async () => (await viewer(page)).occluded, { message: `${name}: ${modal ? "hidden under a modal dialog" : "not hidden"}`, timeout: 5_000 }).toBe(modal);+ if (modal) expect((await viewer(page)).holes ?? [], `${name}: no hole to leak through`).toEqual([]);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 });diff --git a/apps/cua-spaces-web/src/__tests__/ask-first-in-space.test.tsx b/apps/cua-spaces-web/src/__tests__/ask-first-in-space.test.tsxindex 4573dbca02..cdb891821a 100644--- a/apps/cua-spaces-web/src/__tests__/ask-first-in-space.test.tsx+++ b/apps/cua-spaces-web/src/__tests__/ask-first-in-space.test.tsx@@ -76,6 +76,11 @@ describe.skipIf(!wasmBuilt)("Ask first in the Space (both flags)", () => {await act(async () => {fireEvent.click(q("[data-wake-connect]")!);});+ // Reading Claude Code's sign-in asks first; once you agree the message goes again by itself.+ expect(calls.filter((c) => c.op === "agents.connect")).toEqual([]);+ await act(async () => {+ fireEvent.click(await found("[data-import-confirm]"));+ });await waitFor(() => expect(q("[data-wake-note=claude]")!.dataset.state).toBe("retried"), { timeout: 15000 });expect(calls.filter((c) => c.op === "agents.connect").map((c) => c.args)).toEqual([{ agents: ["claude-code"], signIn: true }]);await waitFor(() => expect(calls.some((c) => c.op === "thread.agentAdd" && c.args.harness === "claude-code")).toBe(true));@@ -103,6 +108,9 @@ describe.skipIf(!wasmBuilt)("Send again when the agent can't join", () => {await act(async () => {fireEvent.click(q("[data-wake-connect]")!);});+ await act(async () => {+ fireEvent.click(await found("[data-import-confirm]"));+ });await waitFor(() => expect(q("[data-wake-note=claude]")!.textContent).toContain("this Space is full"), { timeout: 15000 });expect(q("[data-wake-note=claude]")!.dataset.state).not.toBe("retried");expect(posts).toEqual(["@claude fix the build"]);diff --git a/apps/cua-spaces-web/src/__tests__/claude-import.test.tsx b/apps/cua-spaces-web/src/__tests__/claude-import.test.tsxnew file mode 100644index 0000000000..bd3dbc6fc5--- /dev/null+++ b/apps/cua-spaces-web/src/__tests__/claude-import.test.tsx@@ -0,0 +1,183 @@+// SPDX-License-Identifier: FSL-1.1-MIT+// Copyright (c) 2026 Cua AI, Inc.++// Connect for Claude Code imports the sign-in Claude Code already has on this+// machine, once the person agrees: the consent says what is read, kept and sent+// (the core's words); nothing is read before it; "Signed in as ..." is the one+// wording on every surface; a sign-in that ran out reads "Needs reconnect" with+// Reconnect everywhere; and when there is nothing to import the ways on are+// offered in order (sign in with Claude Code, paste a token, use an API key).++import { act, cleanup, fireEvent, waitFor } from "@testing-library/react";+import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";++import { wasmBuilt } from "@/bridge/__tests__/testCore";+import { DEMO_THREAD_SPACE } from "@/bridge/adapters/demo/thread";+import { resetConnectedAppsState } from "@/hooks/use-connected-apps";+import { resetConnectState } from "@/hooks/use-connectors";+import { mountApp, stubBrowserApis } from "./app-harness";++stubBrowserApis();+beforeEach(() => {+ localStorage.clear();+ resetConnectedAppsState();+ resetConnectState();+});+afterEach(() => {+ cleanup();+ vi.unstubAllEnvs();+});++const q = (s: string) => document.querySelector<HTMLElement>(s);+const qa = (s: string) => [...document.querySelectorAll<HTMLElement>(s)];+const found = (s: string) =>+ waitFor(() => {+ const el = q(s);+ expect(el).not.toBeNull();+ return el!;+ });+const click = (el: Element) =>+ act(async () => {+ fireEvent.click(el);+ });++type Call = { op: string; args: unknown };+function host(calls: Call[], demo: { claudeLogin?: "signed-in" | "expired" | "none" } = {}) {+ return { failsCreates: false, listsGhost: false, demo, intercept: (op: string, args: unknown) => (calls.push({ op, args }), undefined) };+}+const connects = (calls: Call[]) => calls.filter((c) => c.op === "agents.connect");++const WHO = "Signed in as [email protected] (Claude Max)";++describe.skipIf(!wasmBuilt)("importing the Claude Code sign-in", () => {+ it("asks first, in plain words, and reads nothing until you agree", async () => {+ const calls: Call[] = [];+ await mountApp("/settings/connectors", host(calls));+ await click(await found("[data-connector-app=claude-code] [data-connector-connect]"));+ const sheet = await found("[data-import-sheet=consent]");+ const text = sheet.textContent ?? "";+ expect(q("[data-import-title]")!.textContent).toBe("Use your Claude Code sign-in");+ expect(text).toContain("Claude Code-credentials");+ expect(text).toContain("~/.claude/.credentials.json");+ expect(text).toContain("never your refresh token");+ expect(text).toContain("You stay signed in to Claude Code");+ expect(text).toContain("Your Spaces get that access token");+ // Nothing is read, and nothing is added anywhere, while the question is open.+ expect(connects(calls)).toEqual([]);+ expect(calls.some((c) => c.op === "agents.setupDriver")).toBe(false);+ // The words of this feature: no middle dot, no "devices", no setup-token promise.+ expect(text).not.toContain("·");+ expect(text.toLowerCase()).not.toContain("device");+ expect(document.body.textContent).not.toContain("claude setup-token");+ });++ it("Cancel leaves everything as it was", async () => {+ const calls: Call[] = [];+ await mountApp("/settings/connectors", host(calls));+ await click(await found("[data-connector-app=claude-code] [data-connector-connect]"));+ await found("[data-import-sheet=consent]");+ await click([...document.querySelectorAll("button")].find((b) => b.textContent === "Cancel")!);+ await waitFor(() => expect(q("[data-import-sheet]")).toBeNull());+ expect(connects(calls)).toEqual([]);+ expect(q("[data-connector-app=claude-code]")!.dataset.state).toBe("not-connected");+ });++ it("Use my sign-in imports it for Claude Code alone, then every surface says who", async () => {+ const calls: Call[] = [];+ await mountApp("/settings/connectors", host(calls));+ await click(await found("[data-connector-app=claude-code] [data-connector-connect]"));+ await click(await found("[data-import-confirm]"));+ await waitFor(() => expect(q("[data-import-sheet]")).toBeNull());+ expect(connects(calls).map((c) => c.args)).toEqual([{ agents: ["claude-code"], signIn: true }]);+ await waitFor(() => expect(q("[data-connector-app=claude-code]")!.dataset.state).toBe("connected"));+ // The row, the Anthropic provider row and the app's own page.+ expect(q("[data-connector-app=claude-code]")!.textContent).toContain(WHO);+ expect(q("[data-connector-provider=anthropic]")!.textContent).toContain(WHO);+ expect(q("[data-connector-provider=anthropic]")!.textContent).toContain("Sign out");+ // Hermes does not count it: a Claude sign-in is Claude Code's alone.+ expect(q("[data-connector-app=hermes]")!.dataset.state).not.toBe("connected");+ });++ it("a sign-in that ran out reads Needs reconnect with Reconnect, never the name", async () => {+ await mountApp("/settings/connectors", host([], { claudeLogin: "expired" }));+ await waitFor(() => expect(q("[data-connector-provider=anthropic]")?.textContent).toContain("Needs reconnect"));+ const app = q("[data-connector-app=claude-code]")!;+ expect(app.dataset.state).toBe("not-connected");+ expect(app.textContent).toContain("Needs reconnect");+ expect(app.querySelector("[data-connector-connect]")?.textContent).toBe("Reconnect");+ expect(q("[data-connector-provider=anthropic] [data-connector-provider-action]")?.textContent).toBe("Reconnect");+ expect(app.textContent).not.toContain("[email protected]");+ // Hermes reads an API key, not Claude Code's sign-in: its row does not say Reconnect.+ expect(q("[data-connector-app=hermes] [data-connector-connect]")?.textContent).toBe("Connect");+ });++ it("Reconnect asks again and imports the newer sign-in", async () => {+ const calls: Call[] = [];+ await mountApp("/settings/connectors", host(calls, { claudeLogin: "expired" }));+ await click(await found("[data-connector-app=claude-code] [data-connector-connect]"));+ await click(await found("[data-import-confirm]"));+ await waitFor(() => expect(q("[data-connector-app=claude-code]")!.dataset.state).toBe("connected"));+ expect(q("[data-connector-provider=anthropic]")!.textContent).toContain(WHO);+ expect(q("[data-connector-provider=anthropic]")!.textContent).not.toContain("Needs reconnect");+ });++ it("with nothing to import it offers, in order: sign in with Claude Code, paste a token, use an API key", async () => {+ const calls: Call[] = [];+ await mountApp("/settings/connectors", host(calls, { claudeLogin: "none" }));+ await click(await found("[data-connector-app=claude-code] [data-connector-connect]"));+ await click(await found("[data-import-confirm]"));+ const sheet = await found("[data-import-sheet=not-found]");+ expect(sheet.textContent).toContain("No Claude Code sign-in found");+ expect(qa("[data-import-option]").map((o) => o.dataset.importOption)).toEqual(["login", "token", "key"]);+ expect(q("[data-import-command]")!.textContent).toBe("claude auth login");+ // No error banner, and nothing saved.+ expect(q("[data-connector-app=claude-code]")!.dataset.state).not.toBe("connected");+ // Paste a token opens the Anthropic sheet straight on the token field.+ await click(q("[data-import-option-action=token]")!);+ const field = await found("[data-provider-key]");+ expect(document.body.textContent).toContain("Claude token");+ fireEvent.change(field, { target: { value: `sk-ant-oat01-${"aB3_".repeat(24)}` } });+ await click(q("[data-provider-save]")!);+ await waitFor(() => expect(q("[data-connector-provider=anthropic]")!.dataset.state).toBe("connected"));+ });++ it("Try again after signing in with Claude Code reads it again", async () => {+ const calls: Call[] = [];+ await mountApp("/settings/connectors", host(calls, { claudeLogin: "none" }));+ await click(await found("[data-connector-app=claude-code] [data-connector-connect]"));+ await click(await found("[data-import-confirm]"));+ await found("[data-import-sheet=not-found]");+ await click(q("[data-import-option-action=login]")!);+ await waitFor(() => expect(connects(calls)).toHaveLength(2));+ await found("[data-import-sheet=not-found]");+ });+});++describe.skipIf(!wasmBuilt)("the Space thread's Connect card", () => {+ const path = `/spaces/${encodeURIComponent(DEMO_THREAD_SPACE)}`;+ const failureReply = () => qa("[data-entry]").find((e) => e.querySelector("[data-failure-connect]") && e.textContent?.includes("Claude"));+ const reply = (demo: object) =>+ mountApp(path, { failsCreates: false, listsGhost: false, demo: { threadAuthFailed: true, ...demo } }).then(() =>+ waitFor(+ () => {+ const r = failureReply();+ expect(r).toBeTruthy();+ return r as HTMLElement;+ },+ { timeout: 5000 },+ ),+ );++ it("says Reconnect when the saved sign-in ran out, with the same word as Settings", async () => {+ const r = await reply({ claudeLogin: "expired" });+ await waitFor(() => expect(r.querySelector("[data-failure-connect]")?.textContent).toContain("Reconnect"));+ expect(r.querySelector<HTMLAnchorElement>("[data-failure-connect]")!.getAttribute("href")).toBe("/settings/connectors/claude-code");+ expect(r.textContent).not.toContain("\u00b7");+ });++ it("says Connect when there is no sign-in saved", async () => {+ const r = await reply({});+ expect(r.querySelector("[data-failure-connect]")?.textContent).toContain("Connect");+ expect(r.querySelector("[data-failure-connect]")?.textContent).not.toContain("Reconnect");+ });+});diff --git a/apps/cua-spaces-web/src/__tests__/connectors-redesign.test.tsx b/apps/cua-spaces-web/src/__tests__/connectors-redesign.test.tsxindex becbd0d9c6..99a521383b 100644--- a/apps/cua-spaces-web/src/__tests__/connectors-redesign.test.tsx+++ b/apps/cua-spaces-web/src/__tests__/connectors-redesign.test.tsx@@ -3,8 +3,9 @@// Settings, Connectors: each coding app has Connect (Cua's// tools and its sign-in, once) and a chevron to its own page; Providers has-// Connect or Sign out. Connect on Claude Code runs only its own token-// command (`signIn: true` for Claude Code alone) and connects Anthropic too.+// Connect or Sign out. Connect on Claude Code asks first, then imports the+// sign-in Claude Code already has (`signIn: true` for Claude Code alone) and+// connects Anthropic too (claude-import.test.tsx walks every state of it).// Off, the page as it was: switches and Account keys.import { act, cleanup, fireEvent, waitFor } from "@testing-library/react";@@ -107,14 +108,15 @@ describe.skipIf(!wasmBuilt)("Settings, Connectors", () => {expect(calls.filter((c) => c.op === "agents.connect")).toEqual([]);});- it("Connect on Claude Code runs its token command alone, and connects Anthropic", async () => {+ it("Connect on Claude Code imports its own sign-in once you agree, and connects Anthropic", async () => {const calls: { op: string; args: unknown }[] = [];await mountApp("/settings/connectors", host(calls));const btn = await found("[data-connector-app=claude-code] [data-connector-connect]");await click(btn);+ await click(await found("[data-import-confirm]"));await waitFor(() => expect(q("[data-connector-app=claude-code]")!.dataset.state).toBe("connected"));await waitFor(() => expect(q("[data-connector-provider=anthropic]")!.dataset.state).toBe("connected"));- expect(q("[data-connector-provider=anthropic]")!.textContent).toContain("Claude Code sign-in");+ expect(q("[data-connector-provider=anthropic]")!.textContent).toContain("Signed in as [email protected] (Claude Max)");const connects = calls.filter((c) => c.op === "agents.connect").map((c) => c.args as { agents: string[]; signIn: boolean });expect(connects).toEqual([{ agents: ["claude-code"], signIn: true }]);});@@ -154,7 +156,7 @@ describe.skipIf(!wasmBuilt)("Settings, Connectors", () => {expect(code.textContent).toBe("QX7P-4M2KD");expect(q("[data-device-sign-in=codex]")?.textContent).toContain("Open sign-in page");await waitFor(() => expect(q("[data-connector-provider=openai]")!.dataset.state).toBe("connected"), { timeout: 8000 });- expect(q("[data-connector-provider=openai]")!.textContent).toContain("ChatGPT sign-in, for Codex");+ expect(q("[data-connector-provider=openai]")!.textContent).toContain("Signed in with ChatGPT, for Codex");expect(q("[data-device-sign-in]")).toBeNull();// Never Codex's own files: no agents.connect with signIn for Codex.const signIns = calls.filter((c) => c.op === "agents.connect").map((c) => c.args as { agents: string[]; signIn: boolean });diff --git a/apps/cua-spaces-web/src/bridge/adapters/demo.ts b/apps/cua-spaces-web/src/bridge/adapters/demo.tsindex f85fe9f763..0900bf05eb 100644--- a/apps/cua-spaces-web/src/bridge/adapters/demo.ts+++ b/apps/cua-spaces-web/src/bridge/adapters/demo.ts@@ -77,6 +77,9 @@ export interface DemoOptions {signedInMachines?: boolean;/** Saved credentials the provider refuses (`?demo=rejected-key`: the OpenAI key): a check marks them as needing a reconnect. */rejectedKeys?: string[];+ /** Claude Code's sign-in on this Mac: imported already (`?demo=claude-signed-in`), imported and run out (`?demo=claude-expired`),+ * or none to import (`?demo=claude-none`: Connect finds nothing and offers the ways on). Default: there is one, not imported yet. */+ claudeLogin?: "signed-in" | "expired" | "none";/** Start with no Spaces (the first-Space empty state). */noSpaces?: boolean;/** This many more Spaces on the list, for scale (`?demo=scale-1000`;@@ -168,6 +171,7 @@ const DEMO_NOTES = "https://github.com/trycua/cua/releases/tag/cua-spaces-v0.9.3* `?demo=mac-host` (New Space options and the Keyvault's Settings rows in the* SwiftUI host's shape), `?demo=unenrolled` (this device not enrolled),* `?demo=agents-readonly` (Cua can't write Hermes's config),+ * `?demo=claude-signed-in` / `claude-expired` / `claude-none` (Claude Code's sign-in imported, run out, or not there to import),* `?demo=update-ready` (an update is downloaded), `?demo=update-downloading`, `?demo=update-error`,* `?demo=clouds` (AWS and Hetzner connected; `clouds-budget`, `clouds-untrusted`,* `clouds-token`, `clouds-approval`: one thing wrong with one of them;@@ -224,6 +228,7 @@ export function demoOptionsFromSearch(search: string): DemoOptions {noVault: flags.has("novault"),...(flags.has("signed-in-machines") ? { signedInMachines: true } : {}),...(flags.has("rejected-key") ? { rejectedKeys: ["OPENAI_API_KEY"] } : {}),+ ...(flags.has("claude-expired") ? { claudeLogin: "expired" as const } : flags.has("claude-signed-in") ? { claudeLogin: "signed-in" as const } : flags.has("claude-none") ? { claudeLogin: "none" as const } : {}),noSpaces: flags.has("empty"),...(() => {const scale = [...flags].find((f) => /^scale-\d+$/.test(f));@@ -336,7 +341,7 @@ export function createDemoAdapter(options: DemoOptions = {}): DataAdapter & { re// A named allowance is for showing the prompts, which wait for no agent run.runs: options.usage ? [] : demoRunRecords(now()),imported: [],- keyStore: demoKeyStore(now, options.rejectedKeys ?? []),+ keyStore: demoKeyStore(now, options.rejectedKeys ?? [], options.claudeLogin),readOnlyAgents: options.agentsReadOnly ?? [],agentSetup: demoAgentSetup(options.onboarded === false || options.agents === "unset", options.agents === "none" ? [] : options.agents === "codex" ? ["codex"] : null),platform: options.platform ?? MAC_DEMO_PLATFORM,@@ -815,12 +820,14 @@ export function createDemoAdapter(options: DemoOptions = {}): DataAdapter & { re: { ...r, configured: true, skillsInstalled: r.skillsTotal, detail: "Skills and MCP server set up" }: r,);- // Claude Code's own token command: one browser approval, then its token is saved with the keys.- if (signIn && agents.includes("claude-code")) {- await wait(step * 14);+ // Claude Code's own sign-in, read from where Claude Code keeps it (macOS asks to allow it), then its+ // access token is saved with the keys. `?demo=claude-none`: there is nothing to read.+ const claudeFound = options.claudeLogin !== "none";+ if (signIn && agents.includes("claude-code") && claudeFound) {+ await wait(step * 6);state.keyStore.keys = [...state.keyStore.keys.filter((k) => k.env !== "CLAUDE_CODE_OAUTH_TOKEN"),- { provider: "other", env: "CLAUDE_CODE_OAUTH_TOKEN", last4: "", addedMs: now() },+ { provider: "other", env: "CLAUDE_CODE_OAUTH_TOKEN", last4: "", addedMs: now(), label: "Signed in as [email protected] (Claude Max)" },];emit({ type: "agents.changed" });}@@ -829,7 +836,7 @@ export function createDemoAdapter(options: DemoOptions = {}): DataAdapter & { reif (row && state.readOnlyAgents.includes(agent)) {return { agent, tools_ok: false, tools_line: `Couldn't add Cua to ${row.mcpConfig ?? agent}: Permission denied (os error 13)`, sign_in: null };}- const copyable = agent === "hermes" || agent === "claude-code" || (agent === "codex" && Boolean(row?.signedIn));+ const copyable = agent === "hermes" || (agent === "claude-code" && claudeFound) || (agent === "codex" && Boolean(row?.signedIn));if (signIn && copyable && !state.imported.includes(agent)) state.imported = [...state.imported, agent];return {agent,@@ -839,7 +846,9 @@ export function createDemoAdapter(options: DemoOptions = {}): DataAdapter & { re? null: copyable? { imported: { source: agent, env: "", label: "", expires_ms: null, added_ms: now() }, refused: null, line: null }- : { imported: null, refused: "not_signed_in", line: "No ChatGPT sign-in on This Mac yet." },+ : agent === "claude-code"+ ? { imported: null, refused: "not_signed_in", line: "Claude Code isn't signed in on This Mac. Run `claude auth login` in Terminal, then try again." }+ : { imported: null, refused: "not_signed_in", line: "No ChatGPT sign-in on This Mac yet." },};});},@@ -853,7 +862,7 @@ export function createDemoAdapter(options: DemoOptions = {}): DataAdapter & { reawait wait(step * 20);state.keyStore.keys = [...state.keyStore.keys.filter((k) => k.env !== "CODEX_AUTH_JSON"), { provider: "other", env: "CODEX_AUTH_JSON", last4: "", addedMs: now() }];emit({ type: "agents.changed" });- return { imported: { source: "codex", env: "CODEX_AUTH_JSON", label: "Codex · ChatGPT sign-in", expires_ms: null, added_ms: now() }, refused: null, line: null };+ return { imported: { source: "codex", env: "CODEX_AUTH_JSON", label: "Signed in with ChatGPT", expires_ms: null, added_ms: now() }, refused: null, line: null };},"agents.disconnect": async ({ agents, signIn, skills, mcp }) => {await wait(step);diff --git a/apps/cua-spaces-web/src/bridge/adapters/demo/agent-keys.ts b/apps/cua-spaces-web/src/bridge/adapters/demo/agent-keys.tsindex 1d8505d4fa..ac7f4574e3 100644--- a/apps/cua-spaces-web/src/bridge/adapters/demo/agent-keys.ts+++ b/apps/cua-spaces-web/src/bridge/adapters/demo/agent-keys.ts@@ -24,8 +24,14 @@ export interface DemoKeyStore {rejected: string[];}-export const demoKeyStore = (now: () => number, rejected: string[] = []): DemoKeyStore => ({- keys: [{ provider: "openai", env: "OPENAI_API_KEY", last4: "3f9a", addedMs: now() - 6 * 24 * 3600_000 }],+export const demoKeyStore = (now: () => number, rejected: string[] = [], claude?: "signed-in" | "expired" | "none"): DemoKeyStore => ({+ keys: [+ { provider: "openai", env: "OPENAI_API_KEY", last4: "3f9a", addedMs: now() - 6 * 24 * 3600_000 },+ // The sign-in imported from Claude Code (`?demo=claude-signed-in`), or one that ran out (`?demo=claude-expired`).+ ...(claude === "signed-in" || claude === "expired"+ ? [{ provider: "other" as const, env: "CLAUDE_CODE_OAUTH_TOKEN", last4: "", addedMs: now() - 26 * 3600_000, label: "Signed in as [email protected] (Claude Max)", ...(claude === "expired" ? { expired: true } : {}) }]+ : []),+ ],rejected,});diff --git a/apps/cua-spaces-web/src/bridge/agent-keys.ts b/apps/cua-spaces-web/src/bridge/agent-keys.tsindex e627f031ae..9bf4134aab 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; expired?: boolean }[];+ keys: { provider: string; env: string; last4: string; addedMs: number; expired?: boolean; label?: string }[];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, expired }) => ({ provider, env, last4, addedMs, ...(expired ? { expired: true } : {}) })),+ keys: (report?.keys ?? []).map(({ provider, env, last4, addedMs, expired, label }) => ({ provider, env, last4, addedMs, ...(expired ? { expired: true } : {}), ...(label ? { label } : {}) })),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/connectors.ts b/apps/cua-spaces-web/src/bridge/connectors.tsindex a442707553..c5c910e8d4 100644--- a/apps/cua-spaces-web/src/bridge/connectors.ts+++ b/apps/cua-spaces-web/src/bridge/connectors.ts@@ -85,6 +85,21 @@ export interface ConnectorsView {addedLabel: string;}+/** The words around importing Claude Code's sign-in (`connectors.importSheet`). */+export interface ImportSheetView {+ title: string;+ lede: string;+ /** What is read, what is kept, where it goes. */+ points: string[];+ confirmLabel: string;+ cancelLabel: string;+ readingLabel: string;+ notFoundTitle: string;+ notFoundLede: string;+ /** In order: sign in with Claude Code, paste a token, use an API key. */+ options: { id: "login" | "token" | "key"; label: string; help: string; command: string | null; button: string }[];+}+export interface ConnectPlan {tools: boolean;appToken: boolean;@@ -94,7 +109,7 @@ export interface ConnectPlan {}export interface ProviderWay {- id: "app-token" | "app-device" | "key" | "shell";+ id: "app-token" | "app-device" | "token" | "key" | "shell";label: string;help: string;button: string;@@ -111,6 +126,9 @@ export interface ProviderSheetView {keyLabel: string;keyPlaceholder: string;keyHelp: string;+ /** The field when the person picks Paste a Claude token. */+ tokenLabel: string;+ tokenPlaceholder: string;saveLabel: string;keyProvider: "anthropic" | "openai" | "other";keyEnv: string | null;@@ -189,6 +207,9 @@ export const connectPlan = (core: CoreClient, input: ConnectorsInput, agent: strexport const providerSheet = (core: CoreClient, input: ConnectorsInput, provider: string, os: HostOs = hostOs(), forApp: string | null = null): ProviderSheetView | null =>core.tryCall<ProviderSheetView | null>("connectors.providerSheet", { input: input as unknown as Json, provider, hostOs: os, forApp }) ?? null;+export const importSheet = (core: CoreClient, os: HostOs = hostOs()): ImportSheetView | null =>+ core.tryCall<ImportSheetView>("connectors.importSheet", { hostOs: os }) ?? null;+export const appDetail = (core: CoreClient, input: ConnectorsInput, agent: string): AppDetailView | null =>core.tryCall<AppDetailView | null>("connectors.appDetail", { input: input as unknown as Json, agent }) ?? null;diff --git a/apps/cua-spaces-web/src/bridge/contracts/bridge-shapes.json b/apps/cua-spaces-web/src/bridge/contracts/bridge-shapes.jsonindex 83196b6929..6c3a142e0f 100644--- a/apps/cua-spaces-web/src/bridge/contracts/bridge-shapes.json+++ b/apps/cua-spaces-web/src/bridge/contracts/bridge-shapes.json@@ -198,6 +198,9 @@},"expired": {"type": "boolean"+ },+ "label": {+ "type": "string"}},"required": [@@ -9329,6 +9332,9 @@},"expired": {"type": "boolean"+ },+ "label": {+ "type": "string"}},"required": [@@ -9398,6 +9404,9 @@},"expired": {"type": "boolean"+ },+ "label": {+ "type": "string"}},"required": [@@ -9467,6 +9476,9 @@},"expired": {"type": "boolean"+ },+ "label": {+ "type": "string"}},"required": [@@ -9536,6 +9548,9 @@},"expired": {"type": "boolean"+ },+ "label": {+ "type": "string"}},"required": [@@ -9605,6 +9620,9 @@},"expired": {"type": "boolean"+ },+ "label": {+ "type": "string"}},"required": [diff --git a/apps/cua-spaces-web/src/bridge/contracts/shapes.ts b/apps/cua-spaces-web/src/bridge/contracts/shapes.tsindex 7545123903..6aca58480c 100644--- a/apps/cua-spaces-web/src/bridge/contracts/shapes.ts+++ b/apps/cua-spaces-web/src/bridge/contracts/shapes.ts@@ -566,7 +566,7 @@ const NotificationShape = ref(const AgentKeysShape = ref("AgentKeysReport",obj<AgentKeysReport>()({- keys: list(object({ provider: oneOf("anthropic", "openai", "other"), env: str, last4: str, addedMs: num, expired: opt(bool) })),+ keys: list(object({ provider: oneOf("anthropic", "openai", "other"), env: str, last4: str, addedMs: num, expired: opt(bool), label: opt(str) })),providers: list(object({ id: oneOf("anthropic", "openai", "other"), label: str, env: str })),available: bool,unavailable: nullable(str),@@ -1662,7 +1662,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, expired: opt(bool) })),+ keys: list(object({ provider: str, env: str, last4: str, added_ms: num, expired: opt(bool), label: opt(str) })),providers: list(object({ id: str, env: str, label: opt(str) })),available: bool,unavailable: optNull(str),diff --git a/apps/cua-spaces-web/src/bridge/ops/agent-keys.ts b/apps/cua-spaces-web/src/bridge/ops/agent-keys.tsindex 497789e7cc..f8d7a37f0b 100644--- a/apps/cua-spaces-web/src/bridge/ops/agent-keys.ts+++ b/apps/cua-spaces-web/src/bridge/ops/agent-keys.ts@@ -40,6 +40,8 @@ export interface AgentKeyInfo {addedMs: number;/** A sign-in past its expiry: no run gets it until it is reconnected. */expired?: boolean;+ /** A copied sign-in's name ("Signed in as [email protected] (Claude Max)"); never a value. */+ label?: string;}/** A provider row (`keys::Provider`). */@@ -124,6 +126,8 @@ const PROVIDERS: AgentKeyProviderRow[] = [];const str = (v: unknown) => (typeof v === "string" ? v : "");+/** A sign-in's name: one short line of text, else none. */+const label = (v: unknown): string => (typeof v === "string" && v.length <= 160 && !/[\u0000-\u001f]/.test(v) ? v.trim() : "");const providerOf = (v: unknown): AgentKeyProvider => (v === "anthropic" || v === "openai" ? v : "other");/** The daemon's `KeysReport` (snake_case) as the page reads it. Drops anything@@ -136,7 +140,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, ...(r.expired === true ? { expired: true } : {}) }];+ return [{ provider: providerOf(r.provider), env, last4: str(r.last4).slice(-4), addedMs: typeof added === "number" ? added : 0, ...(r.expired === true ? { expired: true } : {}), ...(label(r.label) ? { label: label(r.label) } : {}) }];});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/components/settings/connectors/provider-sheet.tsx b/apps/cua-spaces-web/src/components/settings/connectors/provider-sheet.tsxindex 371610fec9..bcea072b8f 100644--- a/apps/cua-spaces-web/src/components/settings/connectors/provider-sheet.tsx+++ b/apps/cua-spaces-web/src/components/settings/connectors/provider-sheet.tsx@@ -2,16 +2,16 @@// Copyright (c) 2026 Cua AI, Inc.import { CheckIcon, ChevronLeftIcon, ChevronRightIcon, CopyIcon, KeyRoundIcon, Loader2Icon, LogInIcon, SmartphoneIcon, TerminalIcon } from "lucide-react";-import { useState } from "react";+import { useEffect, useState } from "react";-import type { ProviderWay } from "@/bridge";+import { importSheet, useBridge, type ProviderWay } from "@/bridge";import { Button } from "@/components/ui/button";import { Dialog, DialogDescription, DialogPopup, DialogTitle } from "@/components/ui/dialog";import { Input } from "@/components/ui/input";import { useSession } from "@/bridge";-import { closeDeviceSignIn, useConnectors, useDeviceSignIn, useProviderSheetOpen } from "@/hooks/use-connectors";+import { closeDeviceSignIn, closeImport, useConnectors, useDeviceSignIn, useImporting, useProviderSheetOpen, useSheetWay } from "@/hooks/use-connectors";-const ICON = { "app-token": LogInIcon, "app-device": SmartphoneIcon, key: KeyRoundIcon, shell: TerminalIcon } as const;+const ICON = { "app-token": LogInIcon, "app-device": SmartphoneIcon, token: KeyRoundIcon, key: KeyRoundIcon, shell: TerminalIcon } as const;/*** "Connect <provider>": the ways the core offers (`connectors.providerSheet`),@@ -22,10 +22,120 @@ const ICON = { "app-token": LogInIcon, "app-device": SmartphoneIcon, key: KeyRouexport function ProviderSheetHost() {const device = useDeviceSignIn();const open = useProviderSheetOpen();+ const importing = useImporting();+ if (importing) return <ImportSheet />;if (device) return <DeviceCodeSheet />;return open ? <ProviderSheet /> : null;}+/**+ * Importing the sign-in Claude Code already has: first what is read, kept and+ * sent (the core's `connectors.importSheet` words), then Use my sign-in; while+ * it reads (macOS may ask to allow it); and when nothing is found, the ways+ * on in order: sign in with Claude Code, paste a token, use an API key.+ */+function ImportSheet() {+ const { core } = useBridge();+ const c = useConnectors();+ const importing = useImporting();+ const [copied, setCopied] = useState(false);+ const v = importSheet(core);+ if (!importing || !v) return null;+ const reading = importing.phase === "reading";+ return (+ <Dialog open onOpenChange={(o) => !o && !reading && closeImport()}>+ <DialogPopup data-import-sheet={importing.phase} className="top-[12vh] w-[min(520px,calc(100vw-2rem))]">+ <div className="px-6 pt-5 pb-5">+ {importing.phase === "not-found" ? (+ <>+ <DialogTitle className="text-[15px] font-semibold">{v.notFoundTitle}</DialogTitle>+ <DialogDescription className="mt-1 text-[13px] text-muted-foreground">{importing.line ?? v.notFoundLede}</DialogDescription>+ <div className="mt-3">+ {v.options.map((o) => {+ const Icon = o.id === "login" ? LogInIcon : KeyRoundIcon;+ return (+ <div key={o.id} data-import-option={o.id} className="-mx-2 flex w-[calc(100%+1rem)] items-center gap-3 rounded-lg px-2 py-2.5">+ <span className="flex size-7 shrink-0 items-center justify-center rounded-lg bg-muted text-muted-foreground">+ <Icon className="size-3.5" />+ </span>+ <span className="min-w-0 flex-1">+ <span className="block text-[13px]">{o.label}</span>+ <span className="block text-xs text-muted-foreground">{o.help}</span>+ {o.command ? (+ <span className="mt-1.5 flex items-center justify-between gap-2 rounded-lg bg-muted px-3 py-1.5">+ <code data-import-command="" className="font-mono text-xs select-all">+ {o.command}+ </code>+ <Button+ size="sm"+ variant="ghost"+ onClick={() => {+ void navigator.clipboard?.writeText(o.command ?? "").catch(() => undefined);+ setCopied(true);+ }}+ >+ {copied ? <CheckIcon /> : <CopyIcon />}+ {copied ? "Copied" : "Copy"}+ </Button>+ </span>+ ) : null}+ </span>+ <Button+ size="sm"+ variant="outline"+ data-import-option-action={o.id}+ onClick={() => {+ if (o.id === "login") void c.confirmImport();+ else {+ closeImport();+ c.openProvider("anthropic", importing.app, o.id);+ }+ }}+ >+ {o.button}+ </Button>+ </div>+ );+ })}+ </div>+ <div className="mt-4 flex justify-end">+ <Button variant="outline" onClick={closeImport}>+ {v.cancelLabel}+ </Button>+ </div>+ </>+ ) : (+ <>+ <DialogTitle className="text-[15px] font-semibold" data-import-title="">+ {v.title}+ </DialogTitle>+ <DialogDescription className="mt-1 text-[13px] text-muted-foreground">{v.lede}</DialogDescription>+ <ul data-import-points="" className="mt-3 space-y-2 text-[13px]">+ {v.points.map((p) => (+ <li key={p}>{p}</li>+ ))}+ </ul>+ {reading ? (+ <p className="mt-4 flex items-center gap-2 text-xs text-muted-foreground" data-import-reading="">+ <Loader2Icon className="size-3.5 animate-spin" /> {v.readingLabel}+ </p>+ ) : null}+ <div className="mt-4 flex justify-end gap-2">+ <Button variant="outline" disabled={reading} onClick={closeImport}>+ {v.cancelLabel}+ </Button>+ <Button disabled={reading} data-import-confirm="" onClick={() => void c.confirmImport()}>+ {v.confirmLabel}+ </Button>+ </div>+ </>+ )}+ </div>+ </DialogPopup>+ </Dialog>+ );+}+/*** A device-code sign-in (Codex with ChatGPT): the one-time code, Copy, and* the page to enter it on. The sheet closes by itself once it's approved;@@ -82,6 +192,11 @@ function ProviderSheet() {const [value, setValue] = useState("");const [busy, setBusy] = useState(false);const [error, setError] = useState<string | null>(null);+ const startWay = useSheetWay();+ // Sent here from "nothing found" to paste a token or a key: open straight on that field.+ useEffect(() => {+ if (startWay && v) setKeyWay(v.ways.find((w) => w.id === startWay) ?? null);+ }, [startWay, v?.provider]); // eslint-disable-line react-hooks/exhaustive-depsconst close = () => {setKeyWay(null);setValue("");@@ -95,7 +210,7 @@ function ProviderSheet() {const ok = await c.runWay(way, typed);setBusy(false);if (ok) close();- else if (way.id === "key") setError("Couldn't save the key. Check it and try again.");+ else if (way.id === "key" || way.id === "token") setError(way.id === "token" ? "Couldn't save the token. Check it and try again." : "Couldn't save the key. Check it and try again.");};return (<Dialog open onOpenChange={(o) => !o && close()}>@@ -121,13 +236,13 @@ function ProviderSheet() {</DialogTitle><DialogDescription className="mt-1 text-[13px] text-muted-foreground">{keyWay.help}</DialogDescription><label className="mt-4 block">- <span className="mb-1 block text-xs font-medium">{v.keyLabel}</span>+ <span className="mb-1 block text-xs font-medium">{keyWay.id === "token" ? v.tokenLabel : v.keyLabel}</span><Inputtype="password"autoFocusdata-provider-key=""value={value}- placeholder={v.keyPlaceholder}+ placeholder={keyWay.id === "token" ? v.tokenPlaceholder : v.keyPlaceholder}autoComplete="off"spellCheck={false}className="font-mono"@@ -160,7 +275,7 @@ function ProviderSheet() {type="button"data-provider-way={w.id}disabled={busy}- onClick={() => (w.id === "key" ? setKeyWay(w) : void run(w))}+ onClick={() => (w.id === "key" || w.id === "token" ? setKeyWay(w) : void run(w))}className="-mx-2 flex w-[calc(100%+1rem)] cursor-default items-center gap-3 rounded-lg px-2 py-2.5 text-left outline-none hover:bg-accent focus-visible:bg-accent disabled:opacity-50"><span className="flex size-7 shrink-0 items-center justify-center rounded-lg bg-muted text-muted-foreground">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.tsxindex 6d7e7ddeae..638bd80ed3 100644--- a/apps/cua-spaces-web/src/components/space-thread/failure-note.tsx+++ b/apps/cua-spaces-web/src/components/space-thread/failure-note.tsx@@ -58,11 +58,14 @@ function ConnectActions({ harness, provider, taskText, onRetry }: { harness: str// Once, when the failure appears.}, []); // eslint-disable-line react-hooks/exhaustive-depsconst app = failureApp(harness, provider);- const connected = app ? c.view?.apps.find((a) => a.agent === app)?.state === "connected" : false;+ const row = app ? c.view?.apps.find((a) => a.agent === app) : undefined;+ const connected = row?.state === "connected";+ // The same word as the Connectors row: Reconnect when the saved sign-in ran out or was refused.+ const label = row?.button?.label === "Reconnect" ? "Reconnect" : "Connect";return (<><Button size="sm" variant="outline" data-failure-connect="" render={app ? <Link to="/settings/connectors/$app" params={{ app }} /> : <Link to="/settings/connectors" />}>- <PlugIcon /> Connect+ <PlugIcon /> {label}</Button><RetryButton taskText={taskText} onRetry={onRetry} enabled={connected} /></>diff --git a/apps/cua-spaces-web/src/components/video/webcodecs-slots.test.tsx b/apps/cua-spaces-web/src/components/video/webcodecs-slots.test.tsxindex a3344afb02..8f4f5c91f4 100644--- a/apps/cua-spaces-web/src/components/video/webcodecs-slots.test.tsx+++ b/apps/cua-spaces-web/src/components/video/webcodecs-slots.test.tsx@@ -10,6 +10,7 @@ import { BridgeProvider } from "@/bridge";import type { MachineAccessNotice } from "@/bridge/contracts/devices";import type { CuaDesktopBridge } from "@/bridge/detect";import { StreamSurface } from "@/components/space-detail/stream-surface";+import { Dialog, DialogPopup, DialogTitle } from "@/components/ui/dialog";import { ToastProvider } from "@/components/ui/toast";import type { SlotStatus } from "@/lib/video-slots";@@ -348,6 +349,63 @@ describe("<StreamSurface> in the Electron shell", () => {await waitFor(() => expect(container.querySelector('[data-video-focus="space"]')?.textContent).toContain("Ctrl+Shift+F12"));});+ // The owner's report (a live desktop in the Space, the "Connect Anthropic" dialog opened from the Connect card): the+ // stream drew over the dialog and kept the pointer. At the shared overlay level, any modal dialog (the dimmed layer+ // our Dialog and AlertDialog draw) puts every stream below it and takes the pointer and keys from it; closing gives+ // both back.+ it("is below and deaf to the page while any modal dialog is open, and takes input again when it closes", async () => {+ const { desktop } = fakeDesktop();+ electron(desktop);+ const Page = ({ open }: { open: boolean }) => (+ <BridgeProvider adapter={createDemoAdapter({ latencyMs: 1 })} core={noCore}>+ <StreamSurface spaceId="local:a" os="linux" canStream previewText="Not reachable" />+ <Dialog open={open}>+ <DialogPopup data-test-dialog="">+ <DialogTitle>Connect Anthropic</DialogTitle>+ </DialogPopup>+ </Dialog>+ </BridgeProvider>+ );+ const view = render(<Page open={false} />);+ await waitFor(() => expect(sessions).toHaveLength(1));+ act(() => sessions[0]!.options.onFrame?.(1280, 800));+ const canvas = await waitFor(() => {+ const c = view.container.querySelector<HTMLCanvasElement>('canvas[data-webcodecs="full"]');+ expect(c).toBeTruthy();+ return c!;+ });+ // The desktop has the keyboard and the pointer.+ act(() => canvas.focus());+ expect(document.activeElement).toBe(canvas);+ expect(canvas.style.pointerEvents).toBe("");++ view.rerender(<Page open />);+ const dim = await waitFor(() => {+ const d = document.querySelector<HTMLElement>("[data-window-dim]");+ expect(d).toBeTruthy();+ return d!;+ });+ // Below the overlay: nothing inside the stream surface is stacked as high as the dialog's dimmed layer and popup.+ const z = (el: Element) => Number(/\bz-(\d+)\b/.exec(el.getAttribute("class") ?? "")?.[1] ?? el.getAttribute("style")?.match(/z-index:\s*(\d+)/)?.[1] ?? 0);+ const surface = view.container.querySelector('[data-stream-surface="local:a"]')!;+ const inside = Math.max(z(surface), ...[...surface.querySelectorAll("*")].map(z));+ expect(z(dim)).toBeGreaterThan(inside);+ expect(z(document.querySelector("[data-test-dialog]")!)).toBeGreaterThan(inside);+ // Non-interactive: the stream takes no pointer, and the keyboard is back with the page.+ await waitFor(() => expect(canvas.style.pointerEvents).toBe("none"));+ expect(document.activeElement).not.toBe(canvas);++ // Closed: pointer and keys are the stream's again, no stuck state.+ view.rerender(<Page open={false} />);+ await waitFor(() => expect(document.querySelector("[data-window-dim]")).toBeNull());+ await waitFor(() => expect(canvas.style.pointerEvents).toBe(""));+ act(() => canvas.focus());+ expect(document.activeElement).toBe(canvas);+ // And a stream mounted while a dialog is open starts deaf too.+ view.rerender(<Page open />);+ await waitFor(() => expect(canvas.style.pointerEvents).toBe("none"));+ });+// The SwiftUI app's ProviderFailureTests: the stream fails to open twice, then opens.describe.each([false, true])("when opening fails (auto-connect %s)", (autoConnect) => {it("offers Try again, says why once per attempt, never asks again by itself, then attempts media", async () => {diff --git a/apps/cua-spaces-web/src/components/video/webcodecs-slots.ts b/apps/cua-spaces-web/src/components/video/webcodecs-slots.tsindex 4a095dbd70..bc5fb62f71 100644--- a/apps/cua-spaces-web/src/components/video/webcodecs-slots.ts+++ b/apps/cua-spaces-web/src/components/video/webcodecs-slots.ts@@ -48,7 +48,7 @@ import type { CuaDesktopBridge } from "@/bridge/detect";import { ELECTRON_BRIDGE_CHANNEL } from "@/bridge/electron-channels";import { isWebkitResponse } from "@/bridge/webkit-protocol";import type { StreamTarget, StreamTicket } from "@/bridge/ops/stream";-import type { SlotOptions, SlotStatus } from "@/lib/video-slots";+import { modalOpen, type SlotOptions, type SlotStatus } from "@/lib/video-slots";import { KeyCapture } from "./key-capture";import { attachPresence, type PresenceAttachment } from "./presence";@@ -136,6 +136,9 @@ class TicketError extends Error {export class WebCodecsSlots {private readonly slots = new Map<string, Slot>();private next = 0;+ /** Watches for a modal dialog opening or closing (while any slot is mounted). */+ private modalWatch: MutationObserver | null = null;+ private modal = false;/** The video bench's counters, while the shell asks for them. */readonly stats: VideoStats | null;@@ -176,7 +179,11 @@ export class WebCodecsSlots {}this.stats?.open(id, options.spaceId, options.tier);this.slots.set(id, slot);- if (this.slots.size === 1) this.doc.addEventListener("visibilitychange", this.onVisibility);+ if (this.slots.size === 1) {+ this.doc.addEventListener("visibilitychange", this.onVisibility);+ this.watchModal();+ }+ if (this.modal) this.stepBack(slot, true);if (options.interactive) this.wireFocus(slot);this.open(slot);return () => {@@ -186,10 +193,41 @@ export class WebCodecsSlots {slot.presence?.detach();canvas.remove();this.stats?.close(id);- if (this.slots.size === 0) this.doc.removeEventListener("visibilitychange", this.onVisibility);+ if (this.slots.size === 0) {+ this.doc.removeEventListener("visibilitychange", this.onVisibility);+ this.modalWatch?.disconnect();+ this.modalWatch = null;+ this.modal = false;+ }};}+ /**+ * While a modal dialog is open no slot takes the pointer or the keys: the+ * canvas stops catching pointer events and gives the keyboard back to the+ * page (the dialog's own backdrop, Escape and focus work), and it takes+ * both again when the dialog closes. The canvas is inside the page here, so+ * the dialog already paints over it (nothing sits above the page's overlay).+ */+ private watchModal(): void {+ const View = this.doc.defaultView;+ if (!View || typeof View.MutationObserver !== "function") return;+ const check = () => {+ const now = modalOpen(this.doc);+ if (now === this.modal) return;+ this.modal = now;+ for (const slot of this.slots.values()) this.stepBack(slot, now);+ };+ this.modalWatch = new View.MutationObserver(check);+ this.modalWatch.observe(this.doc.body, { childList: true, subtree: true, attributes: true, attributeFilter: ["data-closed", "data-ending-style", "data-open", "data-starting-style"] });+ check();+ }++ private stepBack(slot: Slot, away: boolean): void {+ slot.canvas.style.pointerEvents = away ? "none" : "";+ if (away && this.doc.activeElement === slot.canvas) slot.canvas.blur();+ }+/** Gives keys to a slot's Space (null: back to the page). */focus(id: string | null): void {for (const slot of this.slots.values()) {diff --git a/apps/cua-spaces-web/src/hooks/use-connectors.ts b/apps/cua-spaces-web/src/hooks/use-connectors.tsindex a5357062c4..e38f413888 100644--- a/apps/cua-spaces-web/src/hooks/use-connectors.ts+++ b/apps/cua-spaces-web/src/hooks/use-connectors.ts@@ -10,10 +10,11 @@** - Cua's tools in an app: `agents.connect {signIn: false}` (and* Background computer use, best effort);- * - the app's own token command (`claude setup-token`, one browser- * approval): `agents.connect {signIn: true}`, only where the core's plan- * says so. Other apps never get `signIn: true` here, so Cua doesn't read- * their own sign-in files;+ * - importing the sign-in Claude Code already has on this machine:+ * `agents.connect {signIn: true}`, only where the core's plan says so and+ * only after the person agrees in the import sheet (what is read, kept and+ * sent, in the core's words). Other apps never get `signIn: true` here, so+ * Cua doesn't read their own sign-in files;* - a pasted key: `agentKeys.set`; Sign out: `agentKeys.remove`.*/@@ -43,14 +44,16 @@ interface ConnectState {busy: ConnectorsInput["busy"];failures: ConnectorsInput["failures"];/** The provider sheet open now, and what opened it (an app's Connect continues there). */- sheet: { provider: string; forApp: string | null } | null;+ sheet: { provider: string; forApp: string | null; way?: "token" | "key" } | null;/** Provider keys your login shell has set (names), read when a sheet opens. */shellKeys: string[];/** A device-code sign-in waiting for its code to be entered. */device: { app: string; provider: string; url: string; code: string } | null;+ /** Importing an app's own sign-in: asking first, reading, or nothing found. */+ importing: { app: string; phase: "consent" | "reading" | "not-found"; line: string | null } | null;}-const useConnectState = create<ConnectState>(() => ({ busy: [], failures: [], sheet: null, shellKeys: [], device: null }));+const useConnectState = create<ConnectState>(() => ({ busy: [], failures: [], sheet: null, shellKeys: [], device: null, importing: null }));const set = useConnectState.setState;const start = (id: string, step: Step) =>@@ -59,7 +62,27 @@ const stop = (id: string) => set((s) => ({ busy: s.busy.filter((b) => b.id !== iconst fail = (id: string, line: string) => set((s) => ({ failures: [...s.failures.filter((f) => f.id !== id), { id, line }] }));/** Whether a provider sheet is open (cheap: the host mounts the sheet only then). */-export const useProviderSheetOpen = () => useConnectState((s) => s.sheet !== null || s.device !== null);+export const useProviderSheetOpen = () => useConnectState((s) => s.sheet !== null || s.device !== null || s.importing !== null);++/** The sign-in import in progress (asking, reading, or nothing found), for its sheet. */+export const useImporting = () => useConnectState((s) => s.importing);++/** What a Connect that opened the import sheet is waiting for: it settles once the sheet is done with. */+let pendingImport: ((outcome: "connected" | "sheet") => void) | null = null;+const settleImport = (outcome: "connected" | "sheet") => {+ const done = pendingImport;+ pendingImport = null;+ done?.(outcome);+};++/** Closes the import sheet without a sign-in: the Connect that opened it is left waiting on a sheet. */+export const closeImport = () => {+ set({ importing: null });+ settleImport("sheet");+};++/** The way a provider sheet opens on (from "nothing found"), when it was sent to one. */+export const useSheetWay = () => useConnectState((s) => s.sheet?.way ?? null);/** The device-code sign-in waiting now (its code and page), for its sheet. */export const useDeviceSignIn = () => useConnectState((s) => s.device);@@ -67,7 +90,8 @@ export const closeDeviceSignIn = () => set({ device: null });/** Tests start clean. */export function resetConnectState(): void {- set({ busy: [], failures: [], sheet: null, shellKeys: [], device: null });+ pendingImport = null;+ set({ busy: [], failures: [], sheet: null, shellKeys: [], device: null, importing: null });}const message = (e: unknown) => (e instanceof Error ? e.message : String(e));@@ -86,7 +110,9 @@ export interface Connectors {sheetApp: string | null;/** One Connect for an app: Cua's tools, then its sign-in (its token command, or the provider's sheet). */connectApp(agent: string): Promise<ConnectOutcome>;- openProvider(provider: string, forApp?: string | null): void;+ openProvider(provider: string, forApp?: string | null, way?: "token" | "key"): void;+ /** Reads the sign-in the app already has, once the person agreed in the import sheet. */+ confirmImport(): Promise<boolean>;closeProvider(): void;/** Runs one of the sheet's ways (`key` with the pasted value). */runWay(way: ProviderWay, value?: string): Promise<boolean>;@@ -147,6 +173,15 @@ export function useConnectors(): Connectors {const id = `app:${agent}`;const plan = connectPlan(core, input, agent);if (!plan) return "failed";+ // Importing an app's own sign-in reads its files: ask first, in plain words.+ if (plan.appToken) {+ settleImport("sheet");+ set({ importing: { app: agent, phase: "consent", line: null }, failures: useConnectState.getState().failures.filter((f) => f.id !== id) });+ // Done when the person has agreed and it has read, or has left the sheet.+ return new Promise<ConnectOutcome>((resolve) => {+ pendingImport = resolve;+ });+ }try {if (plan.device) {if (plan.tools) {@@ -157,21 +192,16 @@ export function useConnectors(): Connectors {}return (await runDevice(agent, plan.tokenProvider ?? "openai")) ? "connected" : "failed";}- if (plan.tools || plan.appToken) {- start(id, plan.appToken ? "signing-in" : "connecting");- if (plan.tokenProvider) start(`provider:${plan.tokenProvider}`, "signing-in");- const [result] = await data.call("agents.connect", { agents: [agent], signIn: plan.appToken });- if (plan.tools) await data.call("agents.setupDriver", { agents: [agent] }).catch(() => undefined);+ if (plan.tools) {+ start(id, "connecting");+ const [result] = await data.call("agents.connect", { agents: [agent], signIn: false });+ await data.call("agents.setupDriver", { agents: [agent] }).catch(() => undefined);setConnectedAppsState(withSwitch(connectedAppsState(), agent, true));await reload();- if (result && plan.tools && !result.tools_ok) {+ if (result && !result.tools_ok) {fail(id, result.tools_line ?? "Couldn't add Cua to it.");return "failed";}- if (plan.appToken && !result?.sign_in?.imported) {- fail(id, result?.sign_in?.line ?? "The sign-in didn't finish. Try again.");- return "failed";- }}if (plan.provider) {set({ sheet: { provider: plan.provider, forApp: agent } });@@ -189,6 +219,47 @@ export function useConnectors(): Connectors {[core, data, input, reload, runDevice],);+ /**+ * The import itself, after the person agreed: Cua's tools and the sign-in Claude Code already+ * has (`agents.connect {signIn: true}`). macOS may ask to allow reading it. Nothing found+ * (or refused, or cut off) leaves the sheet open on what to do next, never an error banner.+ */+ const confirmImport = useCallback(async (): Promise<boolean> => {+ const open = useConnectState.getState().importing;+ if (!data || !open) return false;+ const agent = open.app;+ const id = `app:${agent}`;+ const plan = connectPlan(core, input, agent);+ const provider = plan?.tokenProvider ?? "anthropic";+ set({ importing: { app: agent, phase: "reading", line: null } });+ start(id, "signing-in");+ start(`provider:${provider}`, "signing-in");+ try {+ const [result] = await data.call("agents.connect", { agents: [agent], signIn: true });+ if (plan?.tools) await data.call("agents.setupDriver", { agents: [agent] }).catch(() => undefined);+ setConnectedAppsState(withSwitch(connectedAppsState(), agent, true));+ await reload();+ if (result && plan?.tools && !result.tools_ok) {+ set({ importing: null });+ fail(id, result.tools_line ?? "Couldn't add Cua to it.");+ return false;+ }+ if (!result?.sign_in?.imported) {+ set({ importing: { app: agent, phase: "not-found", line: result?.sign_in?.line ?? null } });+ return false;+ }+ set({ importing: null });+ settleImport("connected");+ return true;+ } catch (e) {+ set({ importing: { app: agent, phase: "not-found", line: message(e) } });+ return false;+ } finally {+ stop(id);+ stop(`provider:${provider}`);+ }+ }, [core, data, input, reload]);+const runWay = useCallback(async (way: ProviderWay, value?: string): Promise<boolean> => {const open = useConnectState.getState().sheet;@@ -196,13 +267,9 @@ export function useConnectors(): Connectors {const id = `provider:${open.provider}`;try {if (way.id === "app-token" && way.app) {- set({ sheet: null });- start(id, "signing-in");- const [r] = await data.call("agents.connect", { agents: [way.app], signIn: true });- if (!r?.sign_in?.imported) {- fail(id, r?.sign_in?.line ?? "The sign-in didn't finish. Try again.");- return false;- }+ // Reads another app's sign-in: ask first (the import sheet), then read.+ set({ sheet: null, importing: { app: way.app, phase: "consent", line: null } });+ return true;} else if (way.id === "app-device" && way.app) {set({ sheet: null });return await runDevice(way.app, open.provider);@@ -211,7 +278,7 @@ export function useConnectors(): Connectors {await data.call("agentKeys.fromShell", { env: way.env });await keys.refresh();set({ sheet: null });- } else if (way.id === "key" && value?.trim()) {+ } else if ((way.id === "key" || way.id === "token") && value?.trim()) {start(id, "connecting");await keys.save(sheet.keyProvider, value.trim(), sheet.keyEnv);set({ sheet: null });@@ -297,8 +364,9 @@ export function useConnectors(): Connectors {sheet,sheetApp: st.sheet?.forApp ?? null,connectApp,- openProvider: (provider, forApp = null) => {- set({ sheet: { provider, forApp } });+ confirmImport,+ openProvider: (provider, forApp = null, way) => {+ set({ sheet: { provider, forApp, ...(way ? { way } : {}) } });// Which keys your shell has (names only), for "Use … from your shell".void data?.call("agentKeys.shell", {})diff --git a/apps/cua-spaces-web/src/lib/stream-surface.test.tsx b/apps/cua-spaces-web/src/lib/stream-surface.test.tsxindex 842c4ff4eb..13bd37722f 100644--- a/apps/cua-spaces-web/src/lib/stream-surface.test.tsx+++ b/apps/cua-spaces-web/src/lib/stream-surface.test.tsx@@ -143,10 +143,11 @@ describe("stream surface helpers", () => {}});- // 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", () => {+ // CUA-2641: a dialog-role popup over the Space viewer: the video stays+ // drawn with a hole where it is, a dimmed layer is looked through, and a+ // Space tile still hides. (A modal dialog, the dimmed layer open, hides the+ // viewer too: `VideoSlotReporter.measure`, next test.)+ it("keeps the Space viewer drawn with a hole under a dialog-role popup, and still hides a tile", () => {const slot = document.createElement("div");const inner = document.createElement("span");slot.append(inner);@@ -165,7 +166,11 @@ describe("stream surface helpers", () => {expect(videoHoles(slot, clip, document, false)).toEqual([]);});- it("reports the viewer non-interactive, not hidden, while a modal dialog is open", () => {+ // The owner's report: with a live desktop in the Space, a modal ("Connect Anthropic") opened+ // from the Connect card and the native video drew over the bottom edge of the dialog, and+ // the desktop hid the local cursor on the way to it. A native layer sits above the web view:+ // the page's dimmed layer and the dialog cannot cover it, so the video goes while a modal is up.+ it("hides the viewer, takes no input and gives back the keys while a modal dialog is open, and restores all when it closes", () => {vi.stubGlobal("innerWidth", 1000);vi.stubGlobal("innerHeight", 700);const posted: StreamSurfaceMessage[] = [];@@ -185,7 +190,10 @@ describe("stream surface helpers", () => {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)!;};+ const focusPosts = () => posted.filter((m) => m.type === "focus");expect(last("b")).toMatchObject({ interactive: true, occluded: false });+ // The desktop has the keyboard when the dialog opens (the host says so).+ window.dispatchEvent(new CustomEvent("cua:event", { detail: { event: "video.focus", payload: { surfaceId: reporter.idOf(viewer) } } }));const dim = document.createElement("div");dim.setAttribute("data-window-dim", "");const dialog = document.createElement("div");@@ -194,17 +202,55 @@ describe("stream surface helpers", () => {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 }] });+ // Hidden (not drawn over the dialog's edge), no pointer, no keys, no holes to leak through.+ expect(last("b")).toMatchObject({ interactive: false, occluded: true, holes: [] });expect(last("a")).toMatchObject({ occluded: true });- // Closed: the viewer takes input again.+ expect(focusPosts()).toEqual([{ type: "focus", surfaceId: null }]);+ // Once per dialog: measuring again does not ask again.+ reporter.flush();+ expect(focusPosts()).toHaveLength(1);+ // Closed (the dialog starts to go: its dim is marked ending): the viewer takes input and draws again.+ dim.setAttribute("data-ending-style", "");+ reporter.flush();+ expect(last("b")).toMatchObject({ interactive: true, occluded: false });dim.remove();dialog.remove();document.elementsFromPoint = () => [viewer];reporter.flush();expect(last("b")).toMatchObject({ interactive: true, occluded: false, holes: [] });+ // The next dialog takes the keys again if the desktop has them.+ window.dispatchEvent(new CustomEvent("cua:event", { detail: { event: "video.focus", payload: { surfaceId: reporter.idOf(viewer) } } }));+ dim.removeAttribute("data-ending-style");+ document.body.append(dim);+ reporter.flush();+ expect(focusPosts()).toHaveLength(2);+ dim.remove();stop.forEach((f) => f());});+ it("still cuts a hole, not the whole video, for popovers and menus over the viewer (they are not modal)", () => {+ 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");+ document.body.append(viewer);+ box(viewer, { x: 10, y: 200, width: 640, height: 400 });+ document.elementFromPoint = () => viewer;+ document.elementsFromPoint = () => [viewer];+ const stop = reporter.register(viewer, { spaceId: "b", tier: "full", interactive: true, radius: 12 }, () => {});+ const card = document.createElement("div");+ card.setAttribute("role", "dialog");+ card.setAttribute("data-video-occluder", "");+ document.body.append(card);+ box(card, { x: 100, y: 300, width: 200, height: 120 });+ reporter.flush();+ const m = [...posted].reverse().find((x) => x.type === "surfaces") as Extract<StreamSurfaceMessage, { type: "surfaces" }>;+ expect(m.update[0]).toMatchObject({ interactive: true, occluded: false, holes: [{ x: 100, y: 300, width: 200, height: 120 }] });+ card.remove();+ stop();+ });+// 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/stream-surface.ts b/apps/cua-spaces-web/src/lib/stream-surface.tsindex a9e7970f1f..429580bb83 100644--- a/apps/cua-spaces-web/src/lib/stream-surface.ts+++ b/apps/cua-spaces-web/src/lib/stream-surface.ts@@ -55,7 +55,7 @@ export interface SurfaceState {/** The part of `rect` its scroll containers and the viewport leave visible; null when none is. */clip: SurfaceRect | null;radius: number;- /** A dialog (or anything else on top, but floating UI) covers part of the slot: the host hides the video. */+ /** A dialog (or anything else on top, but floating UI) covers part of the slot, or a modal dialog is open (any slot, the viewer too): the host hides the video. */occluded: boolean;/** Floating page UI over the slot (a menu, a popover, a tooltip, a toast, a tile's checkbox and power button while they show), in the same coordinates,* inside `clip`: the host cuts the video out there and keeps the rest playing. */diff --git a/apps/cua-spaces-web/src/lib/video-slots.ts b/apps/cua-spaces-web/src/lib/video-slots.tsindex 39c4e47f79..bd91bfbbdb 100644--- a/apps/cua-spaces-web/src/lib/video-slots.ts+++ b/apps/cua-spaces-web/src/lib/video-slots.ts@@ -51,22 +51,25 @@ export function sameSurface(a: SurfaceState | null, b: SurfaceState): boolean {/** 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. */+ * goes. A dialog-role popup that is not modal (`keepUnderDialogs`, the viewer)+ * is a hole, like a menu. A popover that marks itself a hole+ * (`data-video-occluder`, a profile card) is no occluder for either. A modal+ * dialog (one with the dimmed layer, [`modalOpen`]) hides the viewer too: see+ * `VideoSlotReporter.measure`. */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`). */+ * backdrops): it paints over the whole page. A native video layer sits above+ * the web view and cannot be dimmed or covered by it, so while a modal dialog+ * is open the viewer's video is hidden (`occluded`), takes no pointer or keys,+ * and gives the keyboard back (`modalOpen`); it returns when the dialog closes. */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. */+ * under it must take neither the pointer nor the keys, nor draw over it. */export function modalOpen(doc: Document = document): boolean {return doc.querySelector(`${DIM_SELECTOR}:not([data-closed]):not([data-ending-style])`) !== null;}@@ -173,6 +176,8 @@ export class VideoSlotReporter {private mutations: MutationObserver | null = null;private dpr: MediaQueryList | null = null;private focused: string | null = null;+ /** The keyboard was handed back to the page for the modal dialog open now (once per dialog). */+ private releasedForModal = false;private next = 0;constructor(@@ -226,6 +231,13 @@ export class VideoSlotReporter {/** Measures every slot now and sends what changed. */flush(): void {+ // A modal dialog takes the keyboard from a viewer that has it (once; the host answers `video.focus`).+ const modal = modalOpen(this.win.document);+ if (modal && this.focused && !this.releasedForModal) {+ this.releasedForModal = true;+ this.focus(null);+ }+ if (!modal) this.releasedForModal = false;const update: SurfaceState[] = [];for (const slot of this.slots.values()) {const next = this.measure(slot);@@ -247,8 +259,11 @@ 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.+ // The Space viewer stays drawn under every popup, card, menu and tooltip (CUA-2641: they are holes); a tile hides under a dialog.+ // A modal dialog hides both: the native video layer cannot sit under the page's dimmed layer or the dialog, and it must never+ // capture the pointer or keys while one is up.const keep = slot.tier === "full";+ const modal = modalOpen(this.win.document);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;@@ -256,13 +271,13 @@ export class VideoSlotReporter {surfaceId: slot.id,spaceId: slot.spaceId,tier: slot.tier,- // Under a modal dialog the viewer keeps playing but takes no pointer or keys.- interactive: slot.interactive && !(keep && modalOpen(this.win.document)),+ // Under a modal dialog nothing takes the pointer or keys.+ interactive: slot.interactive && !modal,rect,clip,radius: Math.max(0, slot.radius - inset),- 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) : [],+ occluded: shown && clip ? modal || isOccluded(slot.el, clip, this.win.document, slot.radius, keep) : false,+ holes: shown && clip && !modal ? videoHoles(slot.el, clip, this.win.document, keep).map(roundRect) : [],visible: shown,};}diff --git a/docs/content/docs/cua-cli/reference/cli/agents.mdx b/docs/content/docs/cua-cli/reference/cli/agents.mdxindex d4cb813e3a..fe5eeef33a 100644--- a/docs/content/docs/cua-cli/reference/cli/agents.mdx+++ b/docs/content/docs/cua-cli/reference/cli/agents.mdx@@ -1068,7 +1068,7 @@ cua connect setup [OPTIONS]| <span id="cua-connect-setup--yes"></span>`--yes` | `-y` | boolean | `false` | Answer yes to every prompt. || <span id="cua-connect-setup--force"></span>`--force` | | boolean | `false` | Replace skill folders cua did not write (the old one is backed up). || <span id="cua-connect-setup--cua-driver"></span>`--cua-driver` | | boolean | `false` | Set up background computer-use instead: the cua-driver skill and the cua-driver MCP server (`cua-driver mcp`). --mcp-command then names the cua-driver binary. |-| <span id="cua-connect-setup--sign-in"></span>`--sign-in` | | boolean | `false` | Also make a sign-in for each agent's runs in your Spaces and keep it in Keyvault on This Mac: Claude Code's `claude setup-token` (one browser approval) and Codex's own device sign-in (a link and a code to enter there, in a folder Cua owns); Hermes uses the providers connected in Cua Spaces (Settings, Connectors). The agent's own sign-in files are never read or changed. |+| <span id="cua-connect-setup--sign-in"></span>`--sign-in` | | boolean | `false` | Also make a sign-in for each agent's runs in your Spaces and keep it in Keyvault on This Mac: the sign-in Claude Code already has (read from where Claude Code keeps it, as an access token only; Claude Code's own sign-in is never changed) and Codex's own device sign-in (a link and a code to enter there, in a folder Cua owns); Hermes uses the providers connected in Cua Spaces (Settings, Connectors). Only Claude Code's own sign-in is read, and only its access token is kept; Codex's own `auth.json` is never read or changed. |**Examples**@@ -1088,7 +1088,7 @@ cua connect setup --mcp-only# Background computer-use: the cua-driver skill and MCP servercua connect setup --cua-driver --agents all -y-# Also copy each agent's sign-in to Keyvault on This Mac (Codex's ChatGPT sign-in, Claude Code's `claude setup-token`, Hermes' key)+# Also copy each agent's sign-in to Keyvault on This Mac (Codex's ChatGPT sign-in, the sign-in Claude Code already has, Hermes' key)cua connect setup --agents codex,claude --sign-in -y```@@ -1193,7 +1193,7 @@ cua agents setup [OPTIONS]| <span id="cua-agents-setup--yes"></span>`--yes` | `-y` | boolean | `false` | Answer yes to every prompt. || <span id="cua-agents-setup--force"></span>`--force` | | boolean | `false` | Replace skill folders cua did not write (the old one is backed up). || <span id="cua-agents-setup--cua-driver"></span>`--cua-driver` | | boolean | `false` | Set up background computer-use instead: the cua-driver skill and the cua-driver MCP server (`cua-driver mcp`). --mcp-command then names the cua-driver binary. |-| <span id="cua-agents-setup--sign-in"></span>`--sign-in` | | boolean | `false` | Also make a sign-in for each agent's runs in your Spaces and keep it in Keyvault on This Mac: Claude Code's `claude setup-token` (one browser approval) and Codex's own device sign-in (a link and a code to enter there, in a folder Cua owns); Hermes uses the providers connected in Cua Spaces (Settings, Connectors). The agent's own sign-in files are never read or changed. |+| <span id="cua-agents-setup--sign-in"></span>`--sign-in` | | boolean | `false` | Also make a sign-in for each agent's runs in your Spaces and keep it in Keyvault on This Mac: the sign-in Claude Code already has (read from where Claude Code keeps it, as an access token only; Claude Code's own sign-in is never changed) and Codex's own device sign-in (a link and a code to enter there, in a folder Cua owns); Hermes uses the providers connected in Cua Spaces (Settings, Connectors). Only Claude Code's own sign-in is read, and only its access token is kept; Codex's own `auth.json` is never read or changed. |**Examples**@@ -1213,7 +1213,7 @@ cua connect setup --mcp-only# Background computer-use: the cua-driver skill and MCP servercua connect setup --cua-driver --agents all -y-# Also copy each agent's sign-in to Keyvault on This Mac (Codex's ChatGPT sign-in, Claude Code's `claude setup-token`, Hermes' key)+# Also copy each agent's sign-in to Keyvault on This Mac (Codex's ChatGPT sign-in, the sign-in Claude Code already has, Hermes' key)cua connect setup --agents codex,claude --sign-in -y```diff --git a/docs/content/docs/cua-sdk/concepts/telemetry-events.mdx b/docs/content/docs/cua-sdk/concepts/telemetry-events.mdxindex c9c495d993..fe982f7986 100644--- a/docs/content/docs/cua-sdk/concepts/telemetry-events.mdx+++ b/docs/content/docs/cua-sdk/concepts/telemetry-events.mdx@@ -29,7 +29,8 @@ Every event carries: `telemetry_schema_version`, `event_version`, `product`| `cua_onboarding_step` | `step`, `outcome`, `onboarding_eligible` (`yes` or `no` on the Spaces app's `app_launched`: its first run was still due; `unknown` otherwise), `error_kind` (a failed `signed_in`: `timeout`, `cancelled`, `permission_denied`, `transport`, `unauthenticated` or `other`, never the message; `none` otherwise) | Install and onboarding funnel. Older Spaces apps also send their getting-started checklist's steps (`checklist_shown`, `checklist_<step>`, `checklist_completed`, `checklist_dismissed`, `checklist_reopened`); current apps have tips instead and send none. || `cua_installer_step` | `step` (`installer_started`, `installer_completed`, `installer_failed`), `outcome`, `install_stage`, `error_kind`, `installer` (`sh` or `ps1`), `items` (what was asked for: `cli`, `spaces`, `cua_driver`, `host` joined with `+`) | Install funnel: how many installs start and finish, and where and why they fail ([values](/cua-sdk/concepts/telemetry-counting#installers)). || `cua_agent_used_space` | `tool_group` (`shell`, `files`, `computer`, `services`, `agents` or `other`) | First success and agent retention: an AI agent's tool call acted inside a Space and worked. At most one per install per UTC day. |-| `cua_agent_signin_imported` | `harness` (`hermes`, `claude-code`, `codex` or `other`) | One-click Connect: an agent's sign-in was copied into Keyvault on This Mac. Never the sign-in, the account or the provider. |+| `cua_agent_signin_imported` | `harness` (`hermes`, `claude-code`, `codex` or `other`), `via` (`claude_login_keychain`, `claude_login_file`, `device_code`, `token` or `other`) | One-click Connect: an agent's sign-in was copied into Keyvault on This Mac, and the way it was made. Never the sign-in, the account or the provider. |+| `cua_agent_signin_refused` | `harness`, `reason` (`not_signed_in`, `cancelled`, `not_yet`, `failed` or `other`) | One-click Connect: why a sign-in could not be copied. Never the error text or the account. || `cua_agent_run_started` | `harness` (cua-agents id or `other`), `location`, `entry` (`spaces_tool`, `cli`, `sdk`, `persistent`, `routine`), `outcome`, `error_kind` | Agent runs started, and failed starts. || `cua_agent_run_completed` | `harness`, `location`, `entry`, `outcome`, `error_kind`, `duration_bucket` | First agent run, and how reliably runs finish. Once per run. || `cua_agent_join_phase` | `phase` (`posted`, `dispatch_picked`, `host_prepared`, `guest_spawned`, `install_done`, `runner_started`, `agent_spawned`, `acp_initialized`, `acp_authenticated`, `session_ready`, `turn_started`, `first_token`, `turn_ended` or `failed`), `harness`, `runtime`, `cold`, `ms_since_post`, `run` (a per-install salted hash, never the run id), `tool` (`install_done` only), `failure` (`failed` only: `auth`, `install`, `timeout` or `other`) | How long an agent takes to join a Space and answer, step by step, and where joins fail. Never the message, the Space or the account. |diff --git a/docs/content/docs/cua-sdk/reference/agent-setup.mdx b/docs/content/docs/cua-sdk/reference/agent-setup.mdxindex 1b10508d96..4a34dd4fce 100644--- a/docs/content/docs/cua-sdk/reference/agent-setup.mdx+++ b/docs/content/docs/cua-sdk/reference/agent-setup.mdx@@ -23,7 +23,7 @@ Returned by [`Cua.agent_setup`](/cua-sdk/reference/cua#cua).| Method | Description || --- | --- || [`configure_mcp`](#agentsetupconfigure_mcp) | Configures the MCP server (default: `cua mcp`, `cua` resolved on PATH; `cua-local mcp` named `cua-local` for the Local app) for `agents`. |-| [`connect_json`](#agentsetupconnect_json) | Connect (and Reconnect) for `agents`: Cua's skills and MCP entry (`server`, default this channel's cua), and with `sign_in` the agent's sign-in copied into Keyvault on This Mac (Claude Code waits for its one browser approval). |+| [`connect_json`](#agentsetupconnect_json) | Connect (and Reconnect) for `agents`: Cua's skills and MCP entry (`server`, default this channel's cua), and with `sign_in` the agent's sign-in copied into Keyvault on This Mac (Claude Code's is the sign-in it already has, read from where Claude Code keeps it). || [`connection_status_json`](#agentsetupconnection_status_json) | Whether each agent is really connected (CONTRACT §4: `{agents, checked_at_ms}`), as JSON, the same JSON `cua connect status --json` prints and the `connect_status` MCP tool answers. || [`device_sign_in_start_json`](#agentsetupdevice_sign_in_start_json) | Starts `agent`'s device-code sign-in made for Cua (Codex: `codex login --device-auth` in a folder Cua owns). || [`device_sign_in_wait_json`](#agentsetupdevice_sign_in_wait_json) | Waits for a device sign-in to be approved and saves it into Keyvault on This Mac. |@@ -100,8 +100,9 @@ pub async fn configure_mcp(&self, agents: Vec<String>, server: Option<AgentMcpSeConnect (and Reconnect) for `agents`: Cua's skills and MCP entry(`server`, default this channel's cua), and with `sign_in` the-agent's sign-in copied into Keyvault on This Mac (Claude Code waits-for its one browser approval). JSON: one result per agent.+agent's sign-in copied into Keyvault on This Mac (Claude Code's is the+sign-in it already has, read from where Claude Code keeps it). JSON:+one result per agent.<Tabs items={['Python', 'TypeScript', 'Swift', 'Kotlin', 'Rust']} groupId="sdk-lang" persist><Tab value="Python">diff --git a/docs/content/docs/spaces/guides/agents-in-a-space.mdx b/docs/content/docs/spaces/guides/agents-in-a-space.mdxindex eef8232a1b..409bec3008 100644--- a/docs/content/docs/spaces/guides/agents-in-a-space.mdx+++ b/docs/content/docs/spaces/guides/agents-in-a-space.mdx@@ -176,8 +176,11 @@ A harness needs a provider key. Save it once in **Cua Spaces, Settings,Agents** (or `cua agent keys set`), and each run gets the keys its harnessreads, written 0600 inside the run and redacted from its log; see[Agent keys](/spaces/guides/connect-your-agent#agent-keys). Credential files on-your computer, such as `~/.claude/.credentials.json` or Codex's ChatGPT-sign-in, are never copied into a Space. A harness can use a sign-in that is+your computer are never copied into a Space. The one exception is Claude Code's+own sign-in, which you choose to import: Cua reads it once you agree and gives+Claude Code runs the access token only, never the refresh token (see+[Claude Code and your Claude plan](/spaces/guides/connect-your-agent#claude-code-and-your-claude-plan)).+Codex's ChatGPT sign-in is never copied: Codex signs in with its own code. A harness can use a sign-in that isalready inside the Space, for example one you moved there with[Teleport an app](/spaces/guides/teleport-an-app), which asks you first.diff --git a/docs/content/docs/spaces/guides/connect-your-agent.mdx b/docs/content/docs/spaces/guides/connect-your-agent.mdxindex aed17b6fdd..64f628e9e8 100644--- a/docs/content/docs/spaces/guides/connect-your-agent.mdx+++ b/docs/content/docs/spaces/guides/connect-your-agent.mdx@@ -50,6 +50,45 @@ that hosts the Space: the **OpenAI key** for Codex and the **Anthropic key** forClaude Code. Add them on **Pick your agent** or in **Settings, Connectors**. They stayin this computer's Keychain (Credential Manager on Windows).+### Claude Code and your Claude plan++If you already use Claude Code on this computer, Cua can run it in your Spaces+with the same Claude plan. Press **Connect** next to Claude Code in **Settings,+Connectors**. Before it reads anything, Cua says what it will do and waits for+you to press **Use my sign-in**:++1. Cua reads the sign-in Claude Code already keeps on this computer. On a Mac+ that is the Keychain item "Claude Code-credentials", and macOS asks you to+ allow it. On Linux and Windows, and when Claude Code keeps it in a file, it+ is `.credentials.json` in Claude Code's folder (`~/.claude`, or the folder+ `CLAUDE_CONFIG_DIR` names). Who you are comes from Claude Code's+ `.claude.json`, which holds no tokens.+2. Cua keeps the access token in its own Keychain item, never your refresh+ token, and changes nothing about Claude Code's own sign-in. You stay signed+ in to Claude Code.+3. Each Claude Code run in a Space gets that access token as+ `CLAUDE_CODE_OAUTH_TOKEN`. Only Claude Code gets it: Hermes and the other+ agents never do, and a Space has no refresh token to spend.++The row then reads **Signed in as [email protected] (Claude Max)**, the same+words on the Claude Code page, the Anthropic row and the card an agent shows+when it can't start.++An access token lasts a few hours. A refresh token works only once, so if Cua+refreshed it too, your own Claude Code would be signed out. Cua never refreshes.+When its copy is about to run out, the next run reads the newer one Claude Code+has refreshed on its own. If Claude Code hasn't run for a while, Cua asks Claude+Code to refresh its own sign-in (one short request through `claude -p`, at most+every five minutes). Only when there is nothing newer does the row read **Needs+reconnect**, with **Reconnect**: open Claude Code once, or run `claude auth+login`, then press Reconnect.++If Claude Code isn't signed in on this computer, Cua offers the ways on in this+order: sign in with Claude Code (`claude auth login` in Terminal, then try+again), paste a token made with `claude setup-token` (a long-lived token for+people who prefer one), or use an Anthropic API key. Sign out removes Cua's copy+and never touches Claude Code.+To connect an agent later, or to remove one, open **Settings, AI agents**:- Press **Configure** next to a detected agent to set it up, or **Remove** todiff --git a/libs/cua/crates/cua-agent-setup/README.md b/libs/cua/crates/cua-agent-setup/README.mdindex 9e736fcc16..897abbb0db 100644--- a/libs/cua/crates/cua-agent-setup/README.md+++ b/libs/cua/crates/cua-agent-setup/README.md@@ -48,10 +48,33 @@ answering an MCP `initialize`; and the sign-in Connect copied to Keyvaulton This Mac (a `SignInVault`: the Keychain-backed agent keys in the app andCLI, a fake in tests). Every broken state is `attention` with one line andone action. `connect` / `disconnect` are Connect and Disconnect: the-backup-aware config edit plus the sign-in copy (Codex's `auth.json`, Claude-Code's `claude setup-token`, Hermes' `.env` key), and both undone.+backup-aware config edit plus the sign-in copy (Codex's device-code sign-in,+the access token of the sign-in Claude Code already has, Hermes' `.env` key),+and both undone.`tests/connection_matrix.rs` runs every state against fake harness homes.+## Claude Code's sign-in++`claude_login.rs` finds the sign-in Claude Code already has and Connect copies+its access token (never the refresh token) into Keyvault:++- the tokens: the macOS Keychain item `Claude Code-credentials` (with+ `CLAUDE_CONFIG_DIR` the service is `Claude Code-credentials-<8 hex of+ sha256(dir)>`, and `CLAUDE_SECURESTORAGE_CONFIG_DIR` overrides which dir is+ hashed), else `<config dir>/.credentials.json` (`CLAUDE_CONFIG_DIR` or+ `~/.claude`); when both exist the later expiry wins;+- who it is: `oauthAccount.emailAddress` in the global config+ (`<config dir>/.config.json` when Claude Code still uses that legacy file,+ else `$CLAUDE_CONFIG_DIR/.claude.json` or `~/.claude.json`). That file holds+ no tokens;+- the Keychain sits behind the `Keychain` trait: the real one is+ `/usr/bin/security`, and it refuses in a test process; tests use a fake and+ an isolated home.++A refresh token works once, so Cua never refreshes: when its copy runs out it+reads Claude Code's newer one, and asks Claude Code itself to refresh (a+one-line `claude -p`) when there is none.+## AgentsUser scope only. Sources checked 2026-09-22 (Hermes: 2026-09-30). "Unverified" items are bestdiff --git a/libs/cua/crates/cua-agent-setup/src/claude_login.rs b/libs/cua/crates/cua-agent-setup/src/claude_login.rsnew file mode 100644index 0000000000..ec21ee9ca9--- /dev/null+++ b/libs/cua/crates/cua-agent-setup/src/claude_login.rs@@ -0,0 +1,983 @@+//! Finding the sign-in Claude Code already has on this computer.+//!+//! Connect for Claude Code imports the login the person made with Claude+//! Code itself (the way cswap, ccswap and T3 Code work with it), instead of+//! asking for a new one. This module only knows where Claude Code keeps it+//! and how to read it; it never changes Claude Code's files or Keychain.+//!+//! Where the login lives (sources: Claude Code's own storage code as+//! mirrored by ccswap `internal/claudecode/creds.go` and cswap+//! `paths.py`/`credentials.py`; Hermes `agent/anthropic_credentials.py`):+//!+//! | What | Where |+//! |---|---|+//! | The tokens (`claudeAiOauth`: `accessToken`, `refreshToken`, `expiresAt`, `scopes`, `subscriptionType`) | macOS: Keychain item `Claude Code-credentials` (account = the login name; with `CLAUDE_CONFIG_DIR` the service is `Claude Code-credentials-<first 8 hex of sha256(dir)>`; `CLAUDE_SECURESTORAGE_CONFIG_DIR` overrides which dir is hashed). Linux and Windows, and the fallback on macOS: `<config dir>/.credentials.json` (config dir = `CLAUDE_CONFIG_DIR` or `~/.claude`). |+//! | Who it is (`oauthAccount`: `emailAddress`, `organizationName`) | the global config: `<config dir>/.config.json` when Claude Code (2.1.299 rule) still uses that legacy file, else `$CLAUDE_CONFIG_DIR/.claude.json` or `~/.claude.json`. |+//!+//! The global config holds who is signed in, never the tokens. When both a+//! Keychain item and a credentials file exist, the one with the later expiry+//! wins (Claude Code refreshes one source and not always the other).+//!+//! What Cua keeps: the access token only (never the refresh token), its+//! expiry, the account's email and the plan name. A refresh token works once+//! (each refresh returns a new pair and spends the old one), so a second+//! holder that refreshed would sign Claude Code out. Cua therefore never+//! refreshes: it re-reads this login when its copy runs out+//! ([`crate::signin`], `cua-spaces` agent keys).++use crate::{HostEnv, Os};+use serde_json::Value;+use sha2::{Digest, Sha256};+use std::path::{Path, PathBuf};++/// The Keychain service Claude Code keeps its login under (no config dir).+pub const KEYCHAIN_SERVICE: &str = "Claude Code-credentials";++/// An access token's shortest and longest believable length. Real ones are+/// about 108 characters (`sk-ant-oat01-` and 95 more).+const TOKEN_MIN: usize = 40;+const TOKEN_MAX: usize = 400;++/// What a Keychain read answered.+#[derive(Clone, PartialEq, Eq)]+pub enum KeychainRead {+ /// The item's secret.+ Found(String),+ /// No such item.+ NotFound,+ /// The person (or the system) refused access.+ Denied,+ /// The Keychain can't be used here (not macOS, a test process, an error).+ Unavailable,+}++impl std::fmt::Debug for KeychainRead {+ fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {+ match self {+ KeychainRead::Found(_) => f.write_str("Found(<redacted>)"),+ KeychainRead::NotFound => f.write_str("NotFound"),+ KeychainRead::Denied => f.write_str("Denied"),+ KeychainRead::Unavailable => f.write_str("Unavailable"),+ }+ }+}++/// The macOS Keychain as this module uses it, so tests use a fake and never+/// the real one.+pub trait Keychain: Send + Sync {+ /// Whether an item exists, asked without reading its secret (no prompt).+ fn exists(&self, service: &str, account: &str) -> bool;+ /// The item's secret. The system asks the person to allow this the first+ /// time (that prompt is the consent). `account` `None`: any account.+ fn read(&self, service: &str, account: Option<&str>) -> KeychainRead;+}++/// No Keychain (Linux, Windows, hermetic environments).+pub struct NoKeychain;++impl Keychain for NoKeychain {+ fn exists(&self, _: &str, _: &str) -> bool {+ false+ }+ fn read(&self, _: &str, _: Option<&str>) -> KeychainRead {+ KeychainRead::Unavailable+ }+}++/// The real macOS Keychain, through `/usr/bin/security` (the tool Claude+/// Code itself and cswap use). Refuses in a test process.+pub struct MacSecurity;++impl MacSecurity {+ const BIN: &'static str = "/usr/bin/security";+}++impl Keychain for MacSecurity {+ fn exists(&self, service: &str, account: &str) -> bool {+ if cua_home::is_test_process() || !cfg!(target_os = "macos") {+ return false;+ }+ // Without `-w` or `-g` only the attributes print: no secret, no prompt.+ std::process::Command::new(Self::BIN)+ .args(["find-generic-password", "-s", service, "-a", account])+ .stdin(std::process::Stdio::null())+ .stdout(std::process::Stdio::null())+ .stderr(std::process::Stdio::null())+ .status()+ .is_ok_and(|s| s.success())+ }++ fn read(&self, service: &str, account: Option<&str>) -> KeychainRead {+ if cua_home::is_test_process() || !cfg!(target_os = "macos") {+ return KeychainRead::Unavailable;+ }+ let mut cmd = std::process::Command::new(Self::BIN);+ cmd.args(["find-generic-password", "-s", service]);+ if let Some(a) = account {+ cmd.args(["-a", a]);+ }+ cmd.arg("-w")+ .stdin(std::process::Stdio::null())+ .stdout(std::process::Stdio::piped())+ .stderr(std::process::Stdio::piped());+ let Ok(out) = cmd.output() else {+ return KeychainRead::Unavailable;+ };+ match out.status.code() {+ Some(0) => {+ let s = String::from_utf8_lossy(&out.stdout).trim().to_string();+ if s.is_empty() {+ KeychainRead::NotFound+ } else {+ KeychainRead::Found(s)+ }+ }+ // 44: errSecItemNotFound.+ Some(44) => KeychainRead::NotFound,+ // 36: errSecAuthFailed / 51: user canceled / 128: errSecUserCanceled.+ Some(36) | Some(51) | Some(128) => KeychainRead::Denied,+ _ => {+ let err = String::from_utf8_lossy(&out.stderr).to_ascii_lowercase();+ if err.contains("could not be found") {+ KeychainRead::NotFound+ } else if err.contains("denied") || err.contains("cancel") {+ KeychainRead::Denied+ } else {+ KeychainRead::Unavailable+ }+ }+ }+ }+}++/// The Keychain this environment may use: the real one on a real Mac (agent+/// CLIs allowed), none in a hermetic environment.+pub fn default_keychain(env: &HostEnv) -> Box<dyn Keychain> {+ if env.os == Os::MacOs && env.run_agent_clis {+ Box::new(MacSecurity)+ } else {+ Box::new(NoKeychain)+ }+}++/// Where a login was found, in words a person recognises.+#[derive(Clone, Debug, PartialEq, Eq)]+pub enum Source {+ Keychain { service: String },+ File(PathBuf),+}++impl Source {+ /// "the macOS Keychain item Claude Code-credentials", "~/.claude/.credentials.json".+ pub fn describe(&self, env: &HostEnv) -> String {+ match self {+ Source::Keychain { service } => {+ format!("the macOS Keychain item \u{201c}{service}\u{201d}")+ }+ Source::File(p) => match p.strip_prefix(&env.home) {+ Ok(rel) => format!("~/{}", rel.display()),+ Err(_) => p.display().to_string(),+ },+ }+ }++ /// A fixed word for telemetry: `keychain` or `file`.+ pub fn kind(&self) -> &'static str {+ match self {+ Source::Keychain { .. } => "keychain",+ Source::File(_) => "file",+ }+ }+}++/// The login's tokens, as far as Cua keeps them. `Debug` never prints the token.+#[derive(Clone, PartialEq, Eq)]+pub struct Oauth {+ /// The access token (`sk-ant-oat01-...`).+ pub access_token: String,+ /// There is a refresh token (Cua never keeps it).+ pub has_refresh_token: bool,+ /// When the access token stops working (Unix ms).+ pub expires_ms: Option<u64>,+ pub scopes: Vec<String>,+ /// `max`, `pro`, `team`, `enterprise`.+ pub subscription_type: Option<String>,+}++impl std::fmt::Debug for Oauth {+ fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {+ f.debug_struct("Oauth")+ .field("access_token", &"<redacted>")+ .field("has_refresh_token", &self.has_refresh_token)+ .field("expires_ms", &self.expires_ms)+ .field("subscription_type", &self.subscription_type)+ .finish()+ }+}++impl Oauth {+ /// Not usable any more.+ pub fn expired(&self, now_ms: u64) -> bool {+ self.expires_ms.is_some_and(|e| e <= now_ms)+ }++ /// Less than `within_ms` left (or already gone).+ pub fn near_expiry(&self, now_ms: u64, within_ms: u64) -> bool {+ self.expires_ms.is_some_and(|e| e <= now_ms + within_ms)+ }+}++/// Who is signed in (from the global config's `oauthAccount`).+#[derive(Clone, Debug, Default, PartialEq, Eq)]+pub struct Account {+ pub email: Option<String>,+ pub organization: Option<String>,+}++/// A login found on this computer.+#[derive(Clone, Debug, PartialEq, Eq)]+pub struct Found {+ pub source: Source,+ pub oauth: Oauth,+ pub account: Account,+}++impl Found {+ /// "Signed in as [email protected] (Claude Max)": what the rows show.+ pub fn label(&self) -> String {+ label_for(+ self.account.email.as_deref(),+ self.oauth.subscription_type.as_deref(),+ )+ }+}++/// "Signed in as [email protected] (Claude Max)", or without the parts not known.+pub fn label_for(email: Option<&str>, subscription_type: Option<&str>) -> String {+ let plan = subscription_type.and_then(plan_name);+ match (email.filter(|e| !e.is_empty()), plan) {+ (Some(e), Some(p)) => format!("Signed in as {e} ({p})"),+ (Some(e), None) => format!("Signed in as {e}"),+ (None, Some(p)) => format!("Signed in to {p}"),+ (None, None) => "Signed in to Claude".to_string(),+ }+}++/// "Claude Max" for `max`; None for a type this does not know to name.+pub fn plan_name(subscription_type: &str) -> Option<String> {+ let t = subscription_type.trim().to_ascii_lowercase();+ if t.is_empty()+ || t.len() > 32+ || !t+ .chars()+ .all(|c| c.is_ascii_alphanumeric() || c == '_' || c == '-')+ {+ return None;+ }+ Some(match t.as_str() {+ "max" => "Claude Max".into(),+ "pro" => "Claude Pro".into(),+ "team" => "Claude Team".into(),+ "enterprise" => "Claude Enterprise".into(),+ "free" => "Claude Free".into(),+ other => {+ let mut c = other.chars();+ let first = c.next()?.to_ascii_uppercase();+ format!("Claude {first}{}", c.as_str())+ }+ })+}++/// What a lookup found.+#[derive(Clone, Debug, PartialEq, Eq)]+pub enum Lookup {+ Found(Found),+ /// Claude Code isn't signed in here (nothing at any location).+ NotSignedIn,+ /// A login exists but the Keychain refused to hand it over.+ Denied,+ /// There was something, but it isn't a login Cua can use (the line says why).+ Unusable(String),+}++/// Why a credentials document wasn't taken.+#[derive(Clone, Copy, Debug, PartialEq, Eq)]+pub enum ParseError {+ /// Not JSON.+ NotJson,+ /// No `claudeAiOauth` (an API-key login, or signed out).+ NoOauth,+ /// No access token, or one that isn't shaped like Claude's.+ BadToken,+}++fn token_char(c: char) -> bool {+ c.is_ascii_alphanumeric() || c == '-' || c == '_'+}++/// Whether `t` is shaped like a Claude access or setup token+/// (`sk-ant-oat01-...`): the prefix, a believable length, token characters only.+pub fn token_shaped(t: &str) -> bool {+ t.starts_with("sk-ant-oat")+ && (TOKEN_MIN..=TOKEN_MAX).contains(&t.len())+ && t.chars().all(token_char)+}++fn ms(v: Option<&Value>) -> Option<u64> {+ let n = v?.as_u64().or_else(|| v?.as_f64().map(|f| f as u64))?;+ // Seconds, not milliseconds (before the year 5138).+ Some(if n < 100_000_000_000 { n * 1000 } else { n })+}++/// Reads a credentials document (`{"claudeAiOauth": {...}}`).+pub fn parse_credentials(text: &str) -> Result<Oauth, ParseError> {+ let v: Value = serde_json::from_str(text.trim()).map_err(|_| ParseError::NotJson)?;+ let o = v+ .get("claudeAiOauth")+ .filter(|o| o.is_object())+ .ok_or(ParseError::NoOauth)?;+ let access = o+ .get("accessToken")+ .and_then(Value::as_str)+ .map(str::trim)+ .unwrap_or("");+ if !token_shaped(access) {+ return Err(if access.is_empty() {+ ParseError::NoOauth+ } else {+ ParseError::BadToken+ });+ }+ Ok(Oauth {+ access_token: access.to_string(),+ has_refresh_token: o+ .get("refreshToken")+ .and_then(Value::as_str)+ .is_some_and(|s| !s.trim().is_empty()),+ expires_ms: ms(o.get("expiresAt")),+ scopes: o+ .get("scopes")+ .and_then(Value::as_array)+ .map(|a| {+ a.iter()+ .filter_map(Value::as_str)+ .map(str::to_string)+ .collect()+ })+ .unwrap_or_default(),+ subscription_type: o+ .get("subscriptionType")+ .and_then(Value::as_str)+ .map(str::trim)+ .filter(|s| !s.is_empty())+ .map(str::to_string),+ })+}++// ------------------------------------------------------------ locations++/// Claude Code's config folder: `CLAUDE_CONFIG_DIR`, else `~/.claude`.+pub fn config_dir(env: &HostEnv) -> PathBuf {+ env.var("CLAUDE_CONFIG_DIR")+ .map(PathBuf::from)+ .unwrap_or_else(|| env.home.join(".claude"))+}++/// The credentials file in the config folder.+pub fn credentials_file(env: &HostEnv) -> PathBuf {+ config_dir(env).join(".credentials.json")+}++/// The Keychain service for a config folder: the plain name for the default,+/// else it with the first 8 hex digits of the folder path's SHA-256.+pub fn keychain_service_for(dir: &str) -> String {+ let h = Sha256::digest(dir.as_bytes());+ format!("{KEYCHAIN_SERVICE}-{}", &hex::encode(h)[..8])+}++/// The Keychain services this environment's login may be under, in the order+/// to try. `CLAUDE_SECURESTORAGE_CONFIG_DIR`, when defined, names the only+/// one Claude Code reads (empty: the default). Else `CLAUDE_CONFIG_DIR`+/// names a hashed one, plus the default when it names the default folder.+pub fn keychain_services(env: &HostEnv) -> Vec<String> {+ if let Some(secure) = env.vars.get("CLAUDE_SECURESTORAGE_CONFIG_DIR") {+ return vec![if secure.is_empty() {+ KEYCHAIN_SERVICE.to_string()+ } else {+ keychain_service_for(secure)+ }];+ }+ let Some(dir) = env.var("CLAUDE_CONFIG_DIR") else {+ return vec![KEYCHAIN_SERVICE.to_string()];+ };+ let mut v = vec![keychain_service_for(dir)];+ if same_dir(Path::new(dir), &env.home.join(".claude")) {+ v.push(KEYCHAIN_SERVICE.to_string());+ }+ v+}++fn same_dir(a: &Path, b: &Path) -> bool {+ match (a.canonicalize(), b.canonicalize()) {+ (Ok(x), Ok(y)) => x == y,+ _ => a == b,+ }+}++/// The Keychain account Claude Code uses: the login name, or `claude-code-user`+/// when that has characters outside letters, digits, `.`, `_`, `-`.+pub fn keychain_account(env: &HostEnv) -> String {+ let name = env+ .var("USER")+ .map(str::to_string)+ .or_else(|| {+ env.home+ .file_name()+ .map(|n| n.to_string_lossy().into_owned())+ })+ .unwrap_or_default();+ if !name.is_empty()+ && name+ .chars()+ .all(|c| c.is_ascii_alphanumeric() || matches!(c, '.' | '_' | '-'))+ {+ name+ } else {+ "claude-code-user".into()+ }+}++/// The global config file Claude Code uses (2.1.299's choice): the legacy+/// `<config dir>/.config.json` when it is a regular file that is non-empty+/// (or empty, writable and `.claude.json` is absent), else `.claude.json`+/// in `CLAUDE_CONFIG_DIR` or the home.+pub fn global_config(env: &HostEnv) -> PathBuf {+ let base = env+ .var("CLAUDE_CONFIG_DIR")+ .map(PathBuf::from)+ .unwrap_or_else(|| env.home.clone());+ let global = base.join(".claude.json");+ let legacy = config_dir(env).join(".config.json");+ match std::fs::metadata(&legacy) {+ Ok(m)+ if m.is_file()+ && (m.len() > 0 || (!m.permissions().readonly() && !global.exists())) =>+ {+ legacy+ }+ _ => global,+ }+}++/// Who is signed in, from the global config's `oauthAccount`.+pub fn account(env: &HostEnv) -> Account {+ let Some(v) = std::fs::read_to_string(global_config(env))+ .ok()+ .and_then(|t| serde_json::from_str::<Value>(&t).ok())+ else {+ return Account::default();+ };+ let a = v.get("oauthAccount");+ let s = |k: &str| {+ a.and_then(|a| a.get(k))+ .and_then(Value::as_str)+ .map(str::trim)+ .filter(|s| !s.is_empty() && s.len() <= 254 && !s.chars().any(char::is_control))+ .map(str::to_string)+ };+ Account {+ email: s("emailAddress"),+ organization: s("organizationName"),+ }+}++// -------------------------------------------------------------- refresh++/// The least time between two asks of Claude Code to refresh its sign-in.+const REFRESH_ASK_EVERY: std::time::Duration = std::time::Duration::from_secs(300);++/// Asks Claude Code itself to refresh its sign-in, by a one-line request+/// (`claude -p`), waiting up to `wait`. Claude Code refreshes when its access+/// token has run out and writes the new pair under its own lock, so its+/// refresh token stays the one Claude Code holds: Cua never spends it. Asked+/// at most once every five minutes. Whether it ended well; the caller reads+/// the sign-in again either way. Never in a hermetic environment.+pub fn ask_claude_to_refresh(env: &HostEnv, wait: std::time::Duration) -> bool {+ use std::sync::{Mutex, OnceLock};+ static LAST: OnceLock<Mutex<Option<std::time::Instant>>> = OnceLock::new();+ if !env.run_agent_clis || cua_home::is_test_process() {+ return false;+ }+ let Some(spec) = crate::registry::find("claude-code") else {+ return false;+ };+ let Some(bin) = crate::connection::binary(env, spec) else {+ return false;+ };+ {+ let mut last = LAST+ .get_or_init(Default::default)+ .lock()+ .unwrap_or_else(|p| p.into_inner());+ if last.is_some_and(|t| t.elapsed() < REFRESH_ASK_EVERY) {+ return false;+ }+ *last = Some(std::time::Instant::now());+ }+ matches!(+ crate::connection::run_capture(+ env,+ &bin,+ &[+ "-p",+ "Reply with the word ok.",+ "--model",+ "haiku",+ "--max-turns",+ "1"+ ],+ wait,+ ),+ Some((Some(0), _))+ )+}++// --------------------------------------------------------------- lookup++/// What exists, read without a secret: whether a Claude Code login looks+/// present (so the consent can say where it would be read from).+#[derive(Clone, Debug, PartialEq, Eq)]+pub struct Presence {+ /// Where it would be read from, first choice first.+ pub sources: Vec<Source>,+ pub account: Account,+}++/// Where a login would be read from, without reading any secret (a Keychain+/// item's attributes and a file's existence only).+pub fn presence(env: &HostEnv, keychain: &dyn Keychain) -> Presence {+ let mut sources = vec![];+ let account_name = keychain_account(env);+ for service in keychain_services(env) {+ if keychain.exists(&service, &account_name) {+ sources.push(Source::Keychain { service });+ }+ }+ let file = credentials_file(env);+ if std::fs::metadata(&file).is_ok_and(|m| m.is_file() && m.len() > 2) {+ sources.push(Source::File(file));+ }+ Presence {+ sources,+ account: account(env),+ }+}++/// Reads the login: the Keychain item (macOS), then the credentials file; the+/// one that works longest wins. Reading the Keychain item is what makes the+/// system ask the person to allow it.+pub fn lookup(env: &HostEnv, keychain: &dyn Keychain, now_ms: u64) -> Lookup {+ let mut found: Vec<(Source, Oauth)> = vec![];+ let mut denied = false;+ let mut unusable: Option<String> = None;+ let account_name = keychain_account(env);++ for service in keychain_services(env) {+ // Claude Code writes the item under the login name; fall back to any+ // account for an item another tool wrote.+ let mut r = keychain.read(&service, Some(&account_name));+ if r == KeychainRead::NotFound {+ r = keychain.read(&service, None);+ }+ match r {+ KeychainRead::Found(text) => match parse_credentials(&text) {+ Ok(o) => found.push((Source::Keychain { service }, o)),+ Err(ParseError::NoOauth) => {}+ Err(_) => {+ unusable =+ Some("Claude Code's sign-in in the Keychain isn't one Cua can read.".into())+ }+ },+ KeychainRead::Denied => denied = true,+ KeychainRead::NotFound | KeychainRead::Unavailable => {}+ }+ }++ let file = credentials_file(env);+ if let Ok(text) = std::fs::read_to_string(&file) {+ match parse_credentials(&text) {+ Ok(o) => found.push((Source::File(file), o)),+ Err(ParseError::NoOauth) => {}+ Err(_) => {+ unusable = Some("Claude Code's credentials file isn't one Cua can read.".into())+ }+ }+ }++ // One that has not run out beats one that has; then the later expiry.+ found.sort_by_key(|(_, o)| (!o.expired(now_ms), o.expires_ms.unwrap_or(u64::MAX)));+ match found.pop() {+ Some((source, oauth)) => Lookup::Found(Found {+ source,+ oauth,+ account: account(env),+ }),+ None if denied => Lookup::Denied,+ None => match unusable {+ Some(line) => Lookup::Unusable(line),+ None => Lookup::NotSignedIn,+ },+ }+}++#[cfg(test)]+mod tests {+ use super::*;+ use std::{collections::BTreeMap, sync::Mutex};++ const NOW: u64 = 1_800_000_000_000;++ fn tok(n: u8) -> String {+ format!("sk-ant-oat01-{}", format!("{n:02x}").repeat(45))+ }++ fn creds(access: &str, expires: u64, sub: &str) -> String {+ serde_json::json!({"claudeAiOauth": {+ "accessToken": access, "refreshToken": "sk-ant-ort01-refresh-not-kept",+ "expiresAt": expires, "scopes": ["user:inference", "user:profile"],+ "subscriptionType": sub, "rateLimitTier": "default_claude_max_20x"+ }, "mcpOAuth": {"x": {}}})+ .to_string()+ }++ /// A fake Keychain: `(service, account)` to secret.+ #[derive(Default)]+ struct Fake {+ items: Mutex<BTreeMap<(String, String), String>>,+ deny: bool,+ reads: Mutex<Vec<String>>,+ }+ impl Fake {+ fn with(service: &str, account: &str, secret: &str) -> Self {+ let f = Fake::default();+ f.items+ .lock()+ .unwrap()+ .insert((service.into(), account.into()), secret.into());+ f+ }+ }+ impl Keychain for Fake {+ fn exists(&self, s: &str, a: &str) -> bool {+ self.items+ .lock()+ .unwrap()+ .contains_key(&(s.into(), a.into()))+ }+ fn read(&self, s: &str, a: Option<&str>) -> KeychainRead {+ self.reads.lock().unwrap().push(s.into());+ if self.deny {+ return KeychainRead::Denied;+ }+ let items = self.items.lock().unwrap();+ items+ .iter()+ .find(|((svc, acct), _)| svc == s && a.is_none_or(|a| a == acct))+ .map(|(_, v)| KeychainRead::Found(v.clone()))+ .unwrap_or(KeychainRead::NotFound)+ }+ }++ fn env(dir: &tempfile::TempDir) -> HostEnv {+ let mut e = HostEnv::isolated(dir.path());+ e.vars.insert("USER".into(), "ada".into());+ e+ }++ #[test]+ fn parses_the_shape_claude_code_writes() {+ let o = parse_credentials(&creds(&tok(1), NOW + 3_600_000, "max")).unwrap();+ assert_eq!(o.access_token, tok(1));+ assert!(o.has_refresh_token);+ assert_eq!(o.expires_ms, Some(NOW + 3_600_000));+ assert_eq!(o.subscription_type.as_deref(), Some("max"));+ assert_eq!(o.scopes, ["user:inference", "user:profile"]);+ // Never prints the token.+ assert!(!format!("{o:?}").contains("sk-ant"));+ }++ #[test]+ fn refuses_what_is_not_a_login() {+ assert_eq!(parse_credentials("nope"), Err(ParseError::NotJson));+ assert_eq!(parse_credentials("{}"), Err(ParseError::NoOauth));+ assert_eq!(+ parse_credentials(r#"{"claudeAiOauth": null}"#),+ Err(ParseError::NoOauth)+ );+ assert_eq!(+ parse_credentials(&creds("sk-ant-oat01-short", NOW, "pro")),+ Err(ParseError::BadToken)+ );+ // An API key is not a login, and neither is a cut-off or joined token.+ assert_eq!(+ parse_credentials(&creds(+ &format!("sk-ant-api03-{}", "a".repeat(80)),+ NOW,+ "pro"+ )),+ Err(ParseError::BadToken)+ );+ assert!(!token_shaped(&format!("{}\n", tok(2)).replace('\n', " x")));+ assert!(!token_shaped(&"sk-ant-oat01-".repeat(40)[..450]));+ assert!(token_shaped(&tok(3)));+ }++ #[test]+ fn expiry_in_seconds_is_read_as_milliseconds() {+ let o = parse_credentials(&creds(&tok(1), 1_800_000_000, "pro")).unwrap();+ assert_eq!(o.expires_ms, Some(1_800_000_000_000));+ assert!(o.expired(NOW + 1));+ assert!(!o.expired(NOW - 1));+ assert!(o.near_expiry(NOW - 1000, 5000));+ assert!(!o.near_expiry(NOW - 10_000, 5000));+ }++ #[test]+ fn labels_say_who_and_which_plan() {+ assert_eq!(+ label_for(Some("[email protected]"), Some("max")),+ "Signed in as [email protected] (Claude Max)"+ );+ assert_eq!(+ label_for(Some("[email protected]"), None),+ "Signed in as [email protected]"+ );+ assert_eq!(label_for(None, Some("pro")), "Signed in to Claude Pro");+ assert_eq!(label_for(None, None), "Signed in to Claude");+ assert_eq!(+ plan_name("enterprise").as_deref(),+ Some("Claude Enterprise")+ );+ assert_eq!(plan_name("weird plan!"), None);+ for l in [+ label_for(Some("[email protected]"), Some("team")),+ label_for(None, None),+ ] {+ assert!(!l.contains('\u{b7}'), "no middle dot: {l}");+ }+ }++ #[test]+ fn keychain_service_names_follow_claude_codes_rules() {+ let d = tempfile::tempdir().unwrap();+ let mut e = env(&d);+ assert_eq!(keychain_services(&e), [KEYCHAIN_SERVICE]);+ // A custom folder is hashed (8 hex of sha256 of the path).+ e.vars+ .insert("CLAUDE_CONFIG_DIR".into(), "/work/claude-a".into());+ let s = keychain_services(&e);+ assert_eq!(s.len(), 1);+ assert!(+ s[0].starts_with("Claude Code-credentials-")+ && s[0].len() == KEYCHAIN_SERVICE.len() + 9+ );+ // The folder named the default one: the plain item is tried too.+ let def = d.path().join(".claude");+ std::fs::create_dir_all(&def).unwrap();+ e.vars+ .insert("CLAUDE_CONFIG_DIR".into(), def.display().to_string());+ let s = keychain_services(&e);+ assert_eq!(s.len(), 2);+ assert_eq!(s[1], KEYCHAIN_SERVICE);+ // The secure-storage override is the only store, and empty is the default.+ e.vars+ .insert("CLAUDE_SECURESTORAGE_CONFIG_DIR".into(), "".into());+ assert_eq!(keychain_services(&e), [KEYCHAIN_SERVICE]);+ e.vars+ .insert("CLAUDE_SECURESTORAGE_CONFIG_DIR".into(), "/x".into());+ assert_eq!(keychain_services(&e), [keychain_service_for("/x")]);+ }++ #[test]+ fn keychain_account_is_the_login_name_or_the_fallback() {+ let d = tempfile::tempdir().unwrap();+ let mut e = env(&d);+ assert_eq!(keychain_account(&e), "ada");+ e.vars.insert("USER".into(), "ada lovelace".into());+ assert_eq!(keychain_account(&e), "claude-code-user");+ }++ #[test]+ fn finds_the_login_in_the_keychain_with_the_account_from_config() {+ let d = tempfile::tempdir().unwrap();+ let e = env(&d);+ std::fs::write(+ d.path().join(".claude.json"),+ r#"{"oauthAccount": {"emailAddress": "[email protected]", "organizationName": "Analytical"}}"#,+ )+ .unwrap();+ let kc = Fake::with(+ KEYCHAIN_SERVICE,+ "ada",+ &creds(&tok(1), NOW + 7_200_000, "max"),+ );+ let Lookup::Found(f) = lookup(&e, &kc, NOW) else {+ panic!("found")+ };+ assert_eq!(+ f.source,+ Source::Keychain {+ service: KEYCHAIN_SERVICE.into()+ }+ );+ assert_eq!(f.account.email.as_deref(), Some("[email protected]"));+ assert_eq!(f.label(), "Signed in as [email protected] (Claude Max)");+ assert_eq!(f.source.kind(), "keychain");+ assert!(f.source.describe(&e).contains("Claude Code-credentials"));+ }++ #[test]+ fn finds_the_login_in_the_credentials_file_where_there_is_no_keychain() {+ let d = tempfile::tempdir().unwrap();+ let e = env(&d);+ std::fs::create_dir_all(d.path().join(".claude")).unwrap();+ std::fs::write(+ d.path().join(".claude/.credentials.json"),+ creds(&tok(4), NOW + 1_000_000, "pro"),+ )+ .unwrap();+ let Lookup::Found(f) = lookup(&e, &NoKeychain, NOW) else {+ panic!("found")+ };+ assert_eq!(f.source.kind(), "file");+ assert_eq!(f.source.describe(&e), "~/.claude/.credentials.json");+ assert_eq!(f.label(), "Signed in to Claude Pro");+ }++ #[test]+ fn config_dir_override_moves_every_location() {+ let d = tempfile::tempdir().unwrap();+ let mut e = env(&d);+ let dir = d.path().join("work-claude");+ std::fs::create_dir_all(&dir).unwrap();+ e.vars+ .insert("CLAUDE_CONFIG_DIR".into(), dir.display().to_string());+ std::fs::write(+ dir.join(".credentials.json"),+ creds(&tok(5), NOW + 10, "team"),+ )+ .unwrap();+ std::fs::write(+ dir.join(".claude.json"),+ r#"{"oauthAccount":{"emailAddress":"[email protected]"}}"#,+ )+ .unwrap();+ // The real home's files are never consulted.+ std::fs::write(+ d.path().join(".claude.json"),+ r#"{"oauthAccount":{"emailAddress":"[email protected]"}}"#,+ )+ .unwrap();+ let Lookup::Found(f) = lookup(&e, &NoKeychain, NOW) else {+ panic!("found")+ };+ assert_eq!(f.account.email.as_deref(), Some("[email protected]"));+ assert_eq!(f.source, Source::File(dir.join(".credentials.json")));+ }++ #[test]+ fn the_legacy_config_json_wins_when_claude_code_would_use_it() {+ let d = tempfile::tempdir().unwrap();+ let e = env(&d);+ std::fs::create_dir_all(d.path().join(".claude")).unwrap();+ std::fs::write(+ d.path().join(".claude.json"),+ r#"{"oauthAccount":{"emailAddress":"[email protected]"}}"#,+ )+ .unwrap();+ assert_eq!(global_config(&e), d.path().join(".claude.json"));+ std::fs::write(+ d.path().join(".claude/.config.json"),+ r#"{"oauthAccount":{"emailAddress":"[email protected]"}}"#,+ )+ .unwrap();+ assert_eq!(global_config(&e), d.path().join(".claude/.config.json"));+ assert_eq!(account(&e).email.as_deref(), Some("[email protected]"));+ }++ #[test]+ fn the_later_expiry_wins_when_both_stores_have_a_login() {+ let d = tempfile::tempdir().unwrap();+ let e = env(&d);+ std::fs::create_dir_all(d.path().join(".claude")).unwrap();+ std::fs::write(+ d.path().join(".claude/.credentials.json"),+ creds(&tok(6), NOW - 5000, "max"),+ )+ .unwrap();+ let kc = Fake::with(KEYCHAIN_SERVICE, "ada", &creds(&tok(7), NOW + 5000, "max"));+ let Lookup::Found(f) = lookup(&e, &kc, NOW) else {+ panic!("found")+ };+ assert_eq!(f.oauth.access_token, tok(7));+ // And the other way round.+ let kc = Fake::with(KEYCHAIN_SERVICE, "ada", &creds(&tok(7), NOW - 9000, "max"));+ std::fs::write(+ d.path().join(".claude/.credentials.json"),+ creds(&tok(6), NOW + 9000, "max"),+ )+ .unwrap();+ let Lookup::Found(f) = lookup(&e, &kc, NOW) else {+ panic!("found")+ };+ assert_eq!(f.oauth.access_token, tok(6));+ }++ #[test]+ fn nothing_and_denied_and_unreadable_are_told_apart() {+ let d = tempfile::tempdir().unwrap();+ let e = env(&d);+ assert_eq!(lookup(&e, &NoKeychain, NOW), Lookup::NotSignedIn);+ let denied = Fake {+ deny: true,+ ..Default::default()+ };+ assert_eq!(lookup(&e, &denied, NOW), Lookup::Denied);+ // A file that is not credentials is reported, never read as a login.+ std::fs::create_dir_all(d.path().join(".claude")).unwrap();+ std::fs::write(d.path().join(".claude/.credentials.json"), "garbage").unwrap();+ assert!(matches!(lookup(&e, &NoKeychain, NOW), Lookup::Unusable(_)));+ // An API-key login (no claudeAiOauth) is not a sign-in to import.+ std::fs::write(d.path().join(".claude/.credentials.json"), "{}").unwrap();+ assert_eq!(lookup(&e, &NoKeychain, NOW), Lookup::NotSignedIn);+ }++ #[test]+ fn presence_reads_no_secret() {+ let d = tempfile::tempdir().unwrap();+ let e = env(&d);+ let kc = Fake::with(KEYCHAIN_SERVICE, "ada", &creds(&tok(1), NOW, "max"));+ let p = presence(&e, &kc);+ assert_eq!(+ p.sources,+ [Source::Keychain {+ service: KEYCHAIN_SERVICE.into()+ }]+ );+ assert!(+ kc.reads.lock().unwrap().is_empty(),+ "presence never reads a secret"+ );+ assert!(presence(&e, &NoKeychain).sources.is_empty());+ }++ #[test]+ fn the_real_keychain_is_never_used_in_a_test_process() {+ // `MacSecurity` refuses here whatever the host has.+ assert!(!MacSecurity.exists(KEYCHAIN_SERVICE, "anyone"));+ assert_eq!(+ MacSecurity.read(KEYCHAIN_SERVICE, None),+ KeychainRead::Unavailable+ );+ }+}diff --git a/libs/cua/crates/cua-agent-setup/src/connection.rs b/libs/cua/crates/cua-agent-setup/src/connection.rsindex 864199ee17..600742c572 100644--- a/libs/cua/crates/cua-agent-setup/src/connection.rs+++ b/libs/cua/crates/cua-agent-setup/src/connection.rs@@ -184,7 +184,7 @@ pub struct ImportedSignIn {pub source: String,/// The variable a run in a Space gets it as.pub env: String,- /// "Codex · ChatGPT sign-in".+ /// "ChatGPT sign-in for Codex".pub label: String,/// When it stops working (Unix ms), when known.pub expires_ms: Option<u64>,@@ -199,6 +199,11 @@ pub struct SignInCopy {pub label: String,pub value: String,pub expires_ms: Option<u64>,+ /// How it was made: `claude-login-keychain` or `claude-login-file` (read+ /// from Claude Code's own sign-in), `device-code` (Codex), `token` (a+ /// pasted `claude setup-token`). Fixed words; the telemetry and the+ /// freshness check at run start read it.+ pub origin: Option<String>,}impl std::fmt::Debug for SignInCopy {@@ -209,6 +214,7 @@ impl std::fmt::Debug for SignInCopy {.field("label", &self.label).field("value", &"<redacted>").field("expires_ms", &self.expires_ms)+ .field("origin", &self.origin).finish()}}@@ -826,9 +832,9 @@ impl AgentSetup {r.connected_at = crate::state::now();}- /// Copies `agent`'s sign-in into `vault` (Claude Code waits up to- /// `wait` for its one browser approval). The agent's own sign-in is- /// never changed.+ /// Copies `agent`'s sign-in into `vault` (Claude Code's is the sign-in it+ /// already has; `wait` is how long Claude Code may take to refresh it).+ /// The agent's own sign-in is never changed.pub fn import_sign_in(&self,agent: &str,diff --git a/libs/cua/crates/cua-agent-setup/src/lib.rs b/libs/cua/crates/cua-agent-setup/src/lib.rsindex f73e5013fb..9d6739250d 100644--- a/libs/cua/crates/cua-agent-setup/src/lib.rs+++ b/libs/cua/crates/cua-agent-setup/src/lib.rs@@ -15,6 +15,7 @@//! - Host-safe: everything resolves from a [`HostEnv`] (HOME, XDG and agent//! overrides, PATH, app folders), so tests run against a temporary home.+pub mod claude_login;pub mod config;pub mod connection;mod edit;@@ -156,6 +157,8 @@ const VARS: &[&str] = &["LOCALAPPDATA","CUA_HOME","CLAUDE_CONFIG_DIR",+ "CLAUDE_SECURESTORAGE_CONFIG_DIR",+ "USER","CODEX_HOME","GEMINI_CLI_HOME","CLINE_DATA_DIR",diff --git a/libs/cua/crates/cua-agent-setup/src/signin.rs b/libs/cua/crates/cua-agent-setup/src/signin.rsindex 298af48410..473a999745 100644--- a/libs/cua/crates/cua-agent-setup/src/signin.rs+++ b/libs/cua/crates/cua-agent-setup/src/signin.rs@@ -7,7 +7,7 @@//! | Agent | Signed in | Copied to Keyvault |//! |---|---|---|//! | Codex | `$CODEX_HOME/auth.json` (`tokens`, `OPENAI_API_KEY`); with keyring storage, `codex login status`'s exit code | a sign-in made for Cua: `codex login --device-auth` in a folder Cua owns ([`DeviceSignIn`]), as `CODEX_AUTH_JSON`; never your own `auth.json` |-//! | Claude Code | `claude auth status` (exit 0, `authMethod`), else `.credentials.json` / `.claude.json` | the token `claude setup-token` prints after one browser approval, as `CLAUDE_CODE_OAUTH_TOKEN`; never the Keychain item `Claude Code-credentials` |+//! | Claude Code | `claude auth status` (exit 0, `authMethod`), else `.credentials.json` / `.claude.json` | the access token of the sign-in Claude Code already has ([`crate::claude_login`]: the Keychain item `Claude Code-credentials` or `<config dir>/.credentials.json`, who it is from `.claude.json`), as `CLAUDE_CODE_OAUTH_TOKEN`; never the refresh token, and Claude Code's own files and Keychain item are only read |//! | Hermes | `$HERMES_HOME/.env` provider keys, `auth.json` `providers` (whether a key is there; never its value) | nothing: it uses the providers connected in Settings, Connectors |//! | Cursor | `~/.config/cursor/auth.json`, `~/.cursor/auth.json`, `CURSOR_API_KEY`; else unknown | nothing (no supported export) |//! | OpenClaw | legacy `auth-profiles.json`; else unknown (profiles are in SQLite) | nothing yet |@@ -21,7 +21,7 @@//! Cursor cursor.com/docs/cli/reference/authentication.use crate::{- Error, HostEnv, Result,+ Error, HostEnv, Result, claude_login,connection::{SignInCopy, run_with_timeout},registry,};@@ -270,11 +270,12 @@ 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);+/// How long Connect waits for Claude Code to refresh its own sign-in when the+/// copy it finds has run out (one tiny request through `claude -p`).+pub const CLAUDE_IMPORT_WAIT: Duration = Duration::from_secs(30);-/// 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+/// The shortest string taken as a pasted `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;@@ -363,61 +364,79 @@ pub fn find_setup_token(out: &str) -> Option<String> {(tok.len() >= SETUP_TOKEN_MIN && tok.len() <= SETUP_TOKEN_MAX).then_some(tok)}-fn claude_copy(env: &HostEnv, wait: Duration) -> Result<SignInCopy, CopyRefusal> {- let bin = crate::connection::binary(env, registry::find("claude-code").unwrap())- .ok_or_else(|| CopyRefusal::Failed("Claude Code isn't installed on This Mac.".into()))?;- if !env.run_agent_clis {- return Err(CopyRefusal::Failed(- "agent commands are off in this environment".into(),- ));+/// The sign-in Claude Code already has, read from where Claude Code keeps it+/// ([`crate::claude_login`]) and copied as its access token only. Claude+/// Code's own files and Keychain item are never changed, and its refresh+/// token is never taken: a refresh token works once, so a second holder that+/// refreshed would sign Claude Code out.+///+/// When the copy found has run out, Claude Code is asked to refresh its own+/// sign-in (a one-line request through `claude -p`, up to `wait`) and the+/// sign-in is read again.+fn claude_import(+ env: &HostEnv,+ keychain: &dyn claude_login::Keychain,+ wait: Duration,+) -> Result<SignInCopy, CopyRefusal> {+ use claude_login::{Lookup, Source};+ let mut lookup = claude_login::lookup(env, keychain, now_ms());+ if let Lookup::Found(f) = &lookup+ && f.oauth.expired(now_ms())+ && claude_login::ask_claude_to_refresh(env, wait)+ {+ lookup = claude_login::lookup(env, keychain, now_ms());}- // `setup-token` draws in a terminal; `script` gives it one where the- // 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/sh", "-c", &wide],- wait,- ),- crate::Os::Linux if script.exists() => {- crate::connection::run_capture(env, script, &["-qec", &wide, "/dev/null"], wait)- }- _ => crate::connection::run_capture(env, &bin, &["setup-token"], wait),- };- let Some((code, stdout)) = out else {- return Err(CopyRefusal::Cancelled(- "The browser approval didn't finish. Try Connect again.".into(),- ));- };- match find_setup_token(&stdout) {- Some(token) => Ok(SignInCopy {+ match lookup {+ Lookup::Found(f) if f.oauth.expired(now_ms()) => Err(CopyRefusal::NotSignedIn(+ "Your Claude Code sign-in has run out. Open Claude Code once, or run `claude auth login`, then try again.".into(),+ )),+ Lookup::Found(f) => Ok(SignInCopy {source: "claude-code".into(),env: "CLAUDE_CODE_OAUTH_TOKEN".into(),- label: "Claude Code · Claude sign-in".into(),- value: token,- // A setup-token token lasts a year.- expires_ms: Some(now_ms() + 365 * 24 * 3600 * 1000),+ label: f.label(),+ origin: Some(+ match f.source {+ Source::Keychain { .. } => "claude-login-keychain",+ Source::File(_) => "claude-login-file",+ }+ .into(),+ ),+ expires_ms: f.oauth.expires_ms,+ value: f.oauth.access_token,}),- None if code == Some(0) => Err(CopyRefusal::Failed(- "Couldn't read the sign-in from Claude. Try Connect again.".into(),+ Lookup::NotSignedIn => Err(CopyRefusal::NotSignedIn(+ "Claude Code isn't signed in on This Mac. Run `claude auth login` in Terminal, then try again.".into(),)),- None => Err(CopyRefusal::Cancelled(- "The browser approval was cancelled. Try Connect again.".into(),+ Lookup::Denied => Err(CopyRefusal::Cancelled(+ "macOS didn't let Cua read your Claude Code sign-in. Try again and choose Allow.".into(),)),+ Lookup::Unusable(line) => Err(CopyRefusal::Failed(line)),}}-fn shell_quote(s: &str) -> String {- format!("'{}'", s.replace('\'', "'\\''"))+/// A `claude setup-token` token the person pasted (or the whole text it+/// printed), saved as a sign-in for Claude Code. A setup token lasts a year+/// and has no refresh token.+pub fn claude_pasted_token(pasted: &str) -> Result<SignInCopy, CopyRefusal> {+ let token = find_setup_token(pasted)+ .or_else(|| {+ let t = pasted.trim();+ claude_login::token_shaped(t).then(|| t.to_string())+ })+ .ok_or_else(|| {+ CopyRefusal::Failed(+ "That doesn't look like a Claude token. It starts with sk-ant-oat01- and is one long line.".into(),+ )+ })?;+ Ok(SignInCopy {+ source: "claude-code".into(),+ env: "CLAUDE_CODE_OAUTH_TOKEN".into(),+ label: "Signed in with a Claude token".into(),+ value: token,+ // A setup-token token lasts a year.+ expires_ms: Some(now_ms() + 365 * 24 * 3600 * 1000),+ origin: Some("token".into()),+ })}// --------------------------------------------------------------- Hermes@@ -639,8 +658,8 @@ pub fn check(env: &HostEnv, agent: &str) -> Check {}}-/// Whether Connect makes a sign-in for this agent at all (Claude Code's-/// `setup-token`, Codex's device code).+/// Whether Connect makes a sign-in for this agent at all (Claude Code's own+/// sign-in, imported; Codex's device code).pub fn importable(agent: &str) -> bool {matches!(agent, "codex" | "claude-code")}@@ -664,7 +683,7 @@ pub fn copy_label(env: &HostEnv, agent: &str) -> Option<String> {pub fn copy_source(_env: &HostEnv, agent: &str) -> Option<String> {match agent {"codex" => Some("codex login --device-auth".into()),- "claude-code" => Some("claude setup-token".into()),+ "claude-code" => Some("Claude Code's own sign-in".into()),_ => None,}}@@ -876,9 +895,10 @@ impl DeviceSignIn {Ok(SignInCopy {source: "codex".into(),env: CODEX_AUTH_ENV.into(),- label: "Codex · ChatGPT sign-in".into(),+ label: "ChatGPT sign-in for Codex".into(),value,expires_ms: None,+ origin: Some("device-code".into()),})}}@@ -926,12 +946,22 @@ impl CopyRefusal {}}-/// Reads the sign-in Connect copies. Claude Code's needs one browser-/// approval (`claude setup-token`, waiting up to `wait`).+/// Reads the sign-in Connect copies. Claude Code's is the one it already has+/// ([`claude_import`]); `wait` is how long Claude Code may take to refresh it.pub fn read_copy(env: &HostEnv, agent: &str, wait: Duration) -> Result<SignInCopy, CopyRefusal> {+ read_copy_with(env, agent, &*claude_login::default_keychain(env), wait)+}++/// [`read_copy`] with the Keychain to read (a fake in tests).+pub fn read_copy_with(+ env: &HostEnv,+ agent: &str,+ keychain: &dyn claude_login::Keychain,+ wait: Duration,+) -> Result<SignInCopy, CopyRefusal> {match agent {"codex" => codex_copy(),- "claude-code" => claude_copy(env, wait),+ "claude-code" => claude_import(env, keychain, wait),"hermes" => hermes_copy(),other => Err(CopyRefusal::NotYet(format!("{} has no sign-in Cua can copy.",diff --git a/libs/cua/crates/cua-agent-setup/src/state.rs b/libs/cua/crates/cua-agent-setup/src/state.rsindex f7d5891c24..38c2627c1f 100644--- a/libs/cua/crates/cua-agent-setup/src/state.rs+++ b/libs/cua/crates/cua-agent-setup/src/state.rs@@ -67,7 +67,7 @@ pub struct ConnectionRecord {pub struct SignInRecord {/// The variable a run gets it as.pub env: String,- /// "Codex · ChatGPT sign-in".+ /// "ChatGPT sign-in for Codex".pub label: String,/// RFC 3339.pub copied_at: String,diff --git a/libs/cua/crates/cua-agent-setup/tests/connection_matrix.rs b/libs/cua/crates/cua-agent-setup/tests/connection_matrix.rsindex fc7f656c99..c9b85f93ff 100644--- a/libs/cua/crates/cua-agent-setup/tests/connection_matrix.rs+++ b/libs/cua/crates/cua-agent-setup/tests/connection_matrix.rs@@ -23,6 +23,7 @@ use std::{#[derive(Default)]struct FakeVault {items: Mutex<Vec<(ImportedSignIn, String)>>,+ origins: Mutex<Vec<(String, Option<String>)>>,}impl SignInVault for FakeVault {@@ -46,6 +47,9 @@ impl SignInVault for FakeVault {let mut g = self.items.lock().unwrap();g.retain(|(x, _)| x.source != c.source);g.push((i.clone(), c.value.clone()));+ let mut o = self.origins.lock().unwrap();+ o.retain(|(s, _)| *s != c.source);+ o.push((c.source.clone(), c.origin.clone()));Ok(i)}fn remove(&self, source: &str) -> Result<Vec<String>, String> {@@ -61,6 +65,15 @@ impl SignInVault for FakeVault {}impl FakeVault {+ fn origin(&self, source: &str) -> Option<String> {+ self.origins+ .lock()+ .unwrap()+ .iter()+ .find(|(s, _)| s == source)+ .and_then(|(_, o)| o.clone())+ }+fn value(&self, source: &str) -> Option<String> {self.items.lock()@@ -112,13 +125,21 @@ const CODEX_EXTRA: &str = r#" login)fi ;;"#;+/// A real access token is about 108 characters.+const CLAUDE_ACCESS: &str = "sk-ant-oat01-FAKEaccess_0123456789abcdef_ABCDEFGHIJKLMNOPQRSTUVWXYZ_abcdefghijklmnopqrstuvwxyz_0123456789_QQQQ";+const CLAUDE_REFRESH: &str = "sk-ant-ort01-FAKErefresh-token-that-cua-must-never-keep";++fn claude_credentials(access: &str, expires_ms: u64) -> String {+ serde_json::json!({"claudeAiOauth": {+ "accessToken": access, "refreshToken": CLAUDE_REFRESH, "expiresAt": expires_ms,+ "scopes": ["user:inference"], "subscriptionType": "max"+ }})+ .to_string()+}+const CLAUDE_EXTRA: &str = r#" auth)if [ -f "$HOME/.fake-claude-signed-in" ]; then echo '{"authMethod":"claude.ai"}'; exit 0; fiecho '{"authMethod":"none"}'; exit 1 ;;- setup-token)- if [ -f "$HOME/.fake-claude-cancel" ]; then echo "Login cancelled"; exit 1; fi- if [ -f "$HOME/.fake-claude-short" ]; then printf 'Your OAuth token:\r\n\r\n sk-ant-oat01-FAKEtoken_0123456789\r\n' ; exit 0; fi- printf 'Your OAuth token:\r\n\r\n sk-ant-oat01-FAKEtoken_0123456789abcdef_ABCDEFGHIJKLMNOPQRSTUVWXYZ_abcdefghijklmnopqrstuvwxyz_0123456789_QQQQ\r\n' ; exit 0 ;;"#;impl World {@@ -195,6 +216,16 @@ impl World {}"claude-code" => {self.write(".fake-claude-signed-in", "1");+ // The login Claude Code keeps (its credentials file; the+ // fake Keychain is none): an access token and a refresh token.+ self.write(+ ".claude/.credentials.json",+ &claude_credentials(CLAUDE_ACCESS, 4_102_444_800_000),+ );+ self.write(+ ".claude.json",+ r#"{"oauthAccount":{"emailAddress":"[email protected]"}}"#,+ );}"hermes" => {self.write(".hermes/.env", "OPENROUTER_API_KEY=sk-or-v1-fake\n");@@ -227,8 +258,8 @@ impl World {fn connect(&self, id: &str, sign_in: bool) {let mut env = self.env.clone();- // Claude's setup-token is a CLI run; Claude's own config writer is- // not (the fake has no `mcp add-json`).+ // The sign-in import reads files only; Claude's own config writer is+ // a CLI run the fake has no `mcp add-json` for.env.run_agent_clis = id == "claude-code" && sign_in;let s = AgentSetup::new(env);let parts = ConnectParts {@@ -420,14 +451,17 @@ fn connected_but_not_signed_in_says_so_and_offers_sign_in_where_cua_can_start_itassert_eq!(r.signed_in, SignedInState::Unknown);}-/// A token cut short (a redraw, a wrapped line) is never saved, and the line+/// A credentials file that is not a whole login is never saved, and the line/// says what happened in plain words, never "Connected" next to "not copied".#[test]-fn a_truncated_token_is_refused_with_a_plain_line_and_a_whole_one_is_saved() {+fn a_cut_off_login_is_refused_with_a_plain_line_and_a_whole_one_is_saved() {let w = World::new();w.install("claude-code", "2.4.1");w.sign_in("claude-code");- w.write(".fake-claude-short", "1");+ w.write(+ ".claude/.credentials.json",+ &claude_credentials("sk-ant-oat01-FAKEtoken_0123456789", 4_102_444_800_000),+ );let mut env = w.env.clone();env.run_agent_clis = true;let r = AgentSetup::new(env)@@ -446,14 +480,17 @@ fn a_truncated_token_is_refused_with_a_plain_line_and_a_whole_one_is_saved() {let s = r[0].sign_in.as_ref().unwrap();assert_eq!(s.line.as_deref(),- Some("Couldn't read the sign-in from Claude. Try Connect again.")+ Some("Claude Code's credentials file isn't one Cua can read."));assert!(!s.line.as_ref().unwrap().contains("Connected"));assert_eq!(w.vault.value("claude-code"), None);// The whole token (about 108 characters) is saved with no network involved.- std::fs::remove_file(w.home.join(".fake-claude-short")).unwrap();+ w.sign_in("claude-code");w.connect("claude-code", true);- assert_eq!(w.vault.value("claude-code").unwrap().len(), 109);+ assert_eq!(+ w.vault.value("claude-code").unwrap().len(),+ CLAUDE_ACCESS.len()+ );}#[test]@@ -474,7 +511,7 @@ fn sign_ins_are_made_for_cua_and_never_read_from_the_apps_own_files() {.finish_device_sign_in(login, &w.vault, Duration::from_secs(10)).unwrap();assert_eq!(saved.env, "CODEX_AUTH_JSON");- assert_eq!(saved.label, "Codex · ChatGPT sign-in");+ assert_eq!(saved.label, "ChatGPT sign-in for Codex");let v: serde_json::Value = serde_json::from_str(&w.vault.value("codex").unwrap()).unwrap();assert_eq!(v["tokens"]["refresh_token"], "rt-for-cua");// Your own sign-in is untouched, and Cua's folder is gone.@@ -537,18 +574,28 @@ fn sign_ins_are_made_for_cua_and_never_read_from_the_apps_own_files() {.exists());- // Claude Code: the token `claude setup-token` prints.+ // Claude Code: the sign-in it already has is imported (its access token+ // only; its own files are read and left as they are).let w = World::new();w.install("claude-code", "2.4.1");w.sign_in("claude-code");+ let own = std::fs::read_to_string(w.home.join(".claude/.credentials.json")).unwrap();w.connect("claude-code", true);let r = check(&w, "claude-code", ConnectionState::Connected, None);assert_eq!(r.signin_import, ImportState::Ok);+ assert_eq!(w.vault.value("claude-code").as_deref(), Some(CLAUDE_ACCESS));assert_eq!(- w.vault.value("claude-code").as_deref(),- Some(- "sk-ant-oat01-FAKEtoken_0123456789abcdef_ABCDEFGHIJKLMNOPQRSTUVWXYZ_abcdefghijklmnopqrstuvwxyz_0123456789_QQQQ"- )+ w.vault.origin("claude-code").as_deref(),+ Some("claude-login-file")+ );+ let saved = w.vault.imported().unwrap().pop().unwrap();+ assert_eq!(saved.label, "Signed in as [email protected] (Claude Max)");+ assert_eq!(saved.expires_ms, Some(4_102_444_800_000));+ // The refresh token is never kept anywhere Cua writes, and Claude Code's file is untouched.+ assert!(!format!("{:?}", w.vault.value("claude-code")).contains("ort01"));+ assert_eq!(+ std::fs::read_to_string(w.home.join(".claude/.credentials.json")).unwrap(),+ own);// Hermes: its .env is never copied; it uses the providers connected in Settings.@@ -585,10 +632,8 @@ fn a_refused_sign_in_copy_leaves_the_tools_connected_with_one_line() {.unwrap().contains("Codex signs in with a code"));- // Claude's browser approval cancelled.+ // Claude Code not signed in: nothing to import, one plain line, Retry after signing in.w.install("claude-code", "2.4.1");- w.sign_in("claude-code");- w.write(".fake-claude-cancel", "1");let mut env = w.env.clone();env.run_agent_clis = true;let r = AgentSetup::new(env)@@ -605,13 +650,37 @@ fn a_refused_sign_in_copy_leaves_the_tools_connected_with_one_line() {).unwrap();let s = r[0].sign_in.as_ref().unwrap();- assert_eq!(s.refused.as_deref(), Some("cancelled"), "{s:?}");+ assert_eq!(s.refused.as_deref(), Some("not_signed_in"), "{s:?}");assert!(s.line.as_ref().unwrap()- .starts_with("The browser approval was cancelled")+ .starts_with("Claude Code isn't signed in on This Mac")+ );+ // A login that has run out (and no `claude` to refresh it here) asks to sign in again.+ w.write(+ ".claude/.credentials.json",+ &claude_credentials(CLAUDE_ACCESS, 1_000),);+ let mut env = w.env.clone();+ env.run_agent_clis = true;+ let r = AgentSetup::new(env)+ .connect(+ &["claude-code".into()],+ &w.server(),+ ConnectParts {+ mcp: false,+ skills: false,+ sign_in: true,+ },+ Some(&w.vault),+ Duration::from_secs(10),+ )+ .unwrap();+ let s = r[0].sign_in.as_ref().unwrap();+ assert_eq!(s.refused.as_deref(), Some("not_signed_in"), "{s:?}");+ assert!(s.line.as_ref().unwrap().contains("has run out"));+ assert_eq!(w.vault.value("claude-code"), None);// Hermes on an OAuth provider: not yet.w.install("hermes", "0.22.5");w.write(".hermes/config.yaml", "model:\n provider: nous\n");diff --git a/libs/cua/crates/cua-agents/src/failure.rs b/libs/cua/crates/cua-agents/src/failure.rsindex 92f50e9646..2cb445ef9a 100644--- a/libs/cua/crates/cua-agents/src/failure.rs+++ b/libs/cua/crates/cua-agents/src/failure.rs@@ -118,6 +118,14 @@ const AUTH_TEXTS: &[AuthText] = &[provider: None,reply: true,},+ // Hermes' sign-in variant of the same sentence ("Anthropic rejected your sign-in, so the+ // model can't be reached"), from `agent/turn_failure_copy.py`.+ AuthText {+ harness: "hermes",+ marker: "rejected your sign-in",+ provider: None,+ reply: true,+ },AuthText {harness: "hermes",marker: "hermes setup",@@ -230,6 +238,7 @@ fn refused(text: &str) -> bool {let t = text.to_ascii_lowercase();["rejected your api key",+ "rejected your sign-in","invalid x-api-key","invalid api key","incorrect api key",diff --git a/libs/cua/crates/cua-agents/src/lib.rs b/libs/cua/crates/cua-agents/src/lib.rsindex f56442057f..18b0d0a068 100644--- a/libs/cua/crates/cua-agents/src/lib.rs+++ b/libs/cua/crates/cua-agents/src/lib.rs@@ -19,6 +19,8 @@ pub mod installables;pub mod runs;pub mod transcript;+/// Where Claude Code keeps its sign-in (the freshness check at run start reads it).+pub use cua_agent_setup::{HostEnv, claude_login, signin};pub use durable::{DriverSpec, DurableOptions, Policy, durable_driver_spec};pub use events::{AgentEvent, EventPage};pub use harness::{Endpoint, Harness, Wire};diff --git a/libs/cua/crates/cua-cli/src/agents.rs b/libs/cua/crates/cua-cli/src/agents.rsindex a004ea36e9..d658eb01df 100644--- a/libs/cua/crates/cua-cli/src/agents.rs+++ b/libs/cua/crates/cua-cli/src/agents.rs@@ -34,7 +34,7 @@ pub enum AgentsCmd {# Background computer-use: the cua-driver skill and MCP servercua connect setup --cua-driver --agents all -y# Also copy each agent's sign-in to Keyvault on This Mac (Codex's- # ChatGPT sign-in, Claude Code's `claude setup-token`, Hermes' key)+ # ChatGPT sign-in, the sign-in Claude Code already has, Hermes' key)cua connect setup --agents codex,claude --sign-in -y")]Setup(SetupCmdArgs),/// Whether each agent is really connected: installed and its version,@@ -98,11 +98,13 @@ pub struct SetupCmdArgs {#[arg(long)]pub cua_driver: bool,/// Also make a sign-in for each agent's runs in your Spaces and keep it- /// in Keyvault on This Mac: Claude Code's `claude setup-token` (one- /// browser approval) and Codex's own device sign-in (a link and a code- /// to enter there, in a folder Cua owns); Hermes uses the providers- /// connected in Cua Spaces (Settings, Connectors).- /// The agent's own sign-in files are never read or changed.+ /// in Keyvault on This Mac: the sign-in Claude Code already has (read+ /// from where Claude Code keeps it, as an access token only; Claude+ /// Code's own sign-in is never changed) and Codex's own device sign-in+ /// (a link and a code to enter there, in a folder Cua owns); Hermes uses+ /// the providers connected in Cua Spaces (Settings, Connectors).+ /// Only Claude Code's own sign-in is read, and only its access token is+ /// kept; Codex's own `auth.json` is never read or changed.#[arg(long, conflicts_with = "cua_driver")]pub sign_in: bool,}@@ -763,7 +765,7 @@ fn run_connect(&server,parts,vault.as_deref(),- cua_agent_setup::signin::SETUP_TOKEN_WAIT,+ cua_agent_setup::signin::CLAUDE_IMPORT_WAIT,Some(&mut show),).map_err(err)?;diff --git a/libs/cua/crates/cua-cli/tests/connect_status.rs b/libs/cua/crates/cua-cli/tests/connect_status.rsindex a1d5e63f34..bc1a726b73 100644--- a/libs/cua/crates/cua-cli/tests/connect_status.rs+++ b/libs/cua/crates/cua-cli/tests/connect_status.rs@@ -230,7 +230,7 @@ async fn cli_mcp_and_app_report_the_same_connection_in_every_state() {// Codex signs in with its own device-code login, made for Cua; your own// `~/.codex/auth.json` is never read.assert_eq!(- codex["sign_in"]["imported"]["label"], "Codex · ChatGPT sign-in",+ codex["sign_in"]["imported"]["label"], "ChatGPT sign-in for Codex","{res}");assert!(diff --git a/libs/cua/crates/cua-sdk/src/native/agent_setup.rs b/libs/cua/crates/cua-sdk/src/native/agent_setup.rsindex 40fc3b1053..d0bbb09358 100644--- a/libs/cua/crates/cua-sdk/src/native/agent_setup.rs+++ b/libs/cua/crates/cua-sdk/src/native/agent_setup.rs@@ -408,9 +408,19 @@ impl cua_agent_setup::SignInVault for KeyvaultSignIns {) -> std::result::Result<cua_agent_setup::ImportedSignIn, String> {let k = self.0- .import(&c.source, &c.env, &c.label, &c.value, c.expires_ms)+ .import(+ &c.source,+ &c.env,+ &c.label,+ &c.value,+ c.expires_ms,+ c.origin.as_deref(),+ ).map_err(|e| e.to_string())?;- cua_telemetry::global().capture(cua_telemetry::events::agent_signin_imported(&c.source));+ cua_telemetry::global().capture(cua_telemetry::events::agent_signin_imported(+ &c.source,+ c.origin.as_deref(),+ ));Ok(cua_agent_setup::ImportedSignIn {source: c.source.clone(),env: k.env,@@ -425,6 +435,20 @@ impl cua_agent_setup::SignInVault for KeyvaultSignIns {}}+/// Counts the sign-ins Connect could not copy (fixed words only: the agent and+/// the kind, never the line or the account).+fn note_refusals(results: &[cua_agent_setup::connection::ConnectResult]) {+ #[cfg(feature = "spaces")]+ for r in results {+ if let Some(kind) = r.sign_in.as_ref().and_then(|s| s.refused.as_deref()) {+ cua_telemetry::global()+ .capture(cua_telemetry::events::agent_signin_refused(&r.agent, kind));+ }+ }+ #[cfg(not(feature = "spaces"))]+ let _ = results;+}+/// The vault this build uses, when it has one.pub fn sign_in_vault() -> Option<Box<dyn cua_agent_setup::SignInVault>> {#[cfg(feature = "spaces")]@@ -475,8 +499,9 @@ impl AgentSetup {/// Connect (and Reconnect) for `agents`: Cua's skills and MCP entry/// (`server`, default this channel's cua), and with `sign_in` the- /// agent's sign-in copied into Keyvault on This Mac (Claude Code waits- /// for its one browser approval). JSON: one result per agent.+ /// agent's sign-in copied into Keyvault on This Mac (Claude Code's is the+ /// sign-in it already has, read from where Claude Code keeps it). JSON:+ /// one result per agent.pub async fn connect_json(&self,agents: Vec<String>,@@ -497,8 +522,9 @@ impl AgentSetup {sign_in,},vault.as_deref(),- cua_agent_setup::signin::SETUP_TOKEN_WAIT,+ cua_agent_setup::signin::CLAUDE_IMPORT_WAIT,)?;+ note_refusals(&r);to_json(&r)}).awaitdiff --git a/libs/cua/crates/cua-spaces-app-core/parity/connectors.json b/libs/cua/crates/cua-spaces-app-core/parity/connectors.jsonindex d3677afdcd..4f14ca36eb 100644--- a/libs/cua/crates/cua-spaces-app-core/parity/connectors.json+++ b/libs/cua/crates/cua-spaces-app-core/parity/connectors.json@@ -1,6 +1,6 @@{"name": "connectors",- "about": "Settings, Connectors (redesign) and summoning agents in a Space: the coding apps with Connect and Connected, the Providers with Connect or Sign out, each provider's Connect sheet (an app's own sign-in, a pasted key, a key from your shell), what one Connect on an app does (its token command, its device code, or the provider's sheet), an app's page, what sending an @mention does (add, wake, or why it can't be woken), and the one agent list Home and the Agents page draw (agents in Spaces and this device's runs that haven't started).",+ "about": "Settings, Connectors (redesign) and summoning agents in a Space: the coding apps with Connect and Connected, the Providers with Connect or Sign out, each provider's Connect sheet (an app's own sign-in, a pasted token or key, a key from your shell), the words around importing Claude Code's sign-in, , what one Connect on an app does (importing the sign-in it already has, its device code, or the provider's sheet), an app's page, what sending an @mention does (add, wake, or why it can't be woken), and the one agent list Home and the Agents page draw (agents in Spaces and this device's runs that haven't started).","connectors": [{"step": "nothing connected",@@ -22,11 +22,32 @@{ "agent": "codex", "name": "OpenAI Codex", "installed": true, "configured": true, "skills": true, "mcp": true, "mcpConfig": "~/.codex/config.toml" }],"keys": { "keys": [- { "provider": "other", "env": "CLAUDE_CODE_OAUTH_TOKEN", "last4": "", "addedMs": 1790000000000 },+ { "provider": "other", "env": "CLAUDE_CODE_OAUTH_TOKEN", "last4": "", "addedMs": 1790000000000, "label": "Signed in as [email protected] (Claude Max)" },{ "provider": "openai", "env": "OPENAI_API_KEY", "last4": "3f9a", "addedMs": 1790000100000 }] },"busy": [{ "id": "app:codex", "step": "signing-in" }]}+ },+ {+ "step": "Claude Code sign-in ran out (needs reconnect)",+ "input": {+ "apps": [+ { "agent": "claude-code", "name": "Claude Code", "installed": true, "configured": true, "skills": true, "mcp": true, "mcpConfig": "~/.claude.json" }+ ],+ "keys": { "keys": [+ { "provider": "other", "env": "CLAUDE_CODE_OAUTH_TOKEN", "last4": "", "addedMs": 1790000000000, "label": "Signed in as [email protected] (Claude Max)", "expired": true }+ ] }+ }+ },+ {+ "step": "Claude Code is reading its sign-in",+ "input": {+ "apps": [+ { "agent": "claude-code", "name": "Claude Code", "installed": true, "configured": true, "skills": true, "mcp": true, "mcpConfig": "~/.claude.json" }+ ],+ "keys": { "keys": [] },+ "busy": [{ "id": "app:claude-code", "step": "signing-in" }]+ }}],"sheets": ["anthropic", "openai", "github"],diff --git a/libs/cua/crates/cua-spaces-app-core/parity/golden/connectors.json b/libs/cua/crates/cua-spaces-app-core/parity/golden/connectors.jsonindex e8e7f33aab..e9de8aa657 100644--- a/libs/cua/crates/cua-spaces-app-core/parity/golden/connectors.json+++ b/libs/cua/crates/cua-spaces-app-core/parity/golden/connectors.json@@ -26,7 +26,7 @@},{"apps": [- "claude-code | connected | - | - | Connected",+ "claude-code | connected | Signed in as [email protected] (Claude Max) | - | Connected","codex | connecting | Enter the code in your browser… | Connect | -","gemini-cli | not-connected | Needs an API key for Google. | Connect | -","antigravity | not-connected | Needs an API key for Google. | Connect | -",@@ -38,7 +38,7 @@],"footer": "Sign-ins and keys stay on this Mac in the Keychain. Each one is only given to the apps that use it.","providers": [- "anthropic | connected | Claude Code sign-in | Sign out",+ "anthropic | connected | Signed in as [email protected] (Claude Max) | Sign out","openai | connected | API key •••• 3f9a | Sign out","google | not-connected | Not connected | Connect","openrouter | not-connected | Not connected | Connect",@@ -46,12 +46,57 @@],"step": "Claude Code signed in, an OpenAI key pasted, Codex connecting"},+ {+ "apps": [+ "claude-code | not-connected | Needs reconnect | Reconnect | -",+ "codex | not-connected | Needs a sign-in to OpenAI. | Connect | -",+ "gemini-cli | not-connected | Needs an API key for Google. | Connect | -",+ "antigravity | not-connected | Needs an API key for Google. | Connect | -",+ "opencode | not-connected | Needs an API key for Anthropic, OpenAI, Google or OpenRouter. | Connect | -",+ "goose | not-connected | Needs an API key for OpenAI, Anthropic or OpenRouter. | Connect | -",+ "pi | not-connected | Needs an API key for Anthropic, OpenAI, Google or OpenRouter. | Connect | -",+ "hermes | not-connected | Needs an API key for Anthropic or OpenAI. | Connect | -",+ "openclaw | not-connected | Needs an API key for Anthropic, OpenAI or OpenRouter. | Connect | -"+ ],+ "footer": "Sign-ins and keys stay on this Mac in the Keychain. Each one is only given to the apps that use it.",+ "providers": [+ "anthropic | not-connected | Needs reconnect | Reconnect",+ "openai | not-connected | Not connected | Connect",+ "google | not-connected | Not connected | Connect",+ "openrouter | not-connected | Not connected | Connect",+ "github | not-connected | Not connected | Connect"+ ],+ "step": "Claude Code sign-in ran out (needs reconnect)"+ },+ {+ "apps": [+ "claude-code | connecting | Reading your Claude Code sign-in… | Connect | -",+ "codex | not-connected | Needs a sign-in to OpenAI. | Connect | -",+ "gemini-cli | not-connected | Needs an API key for Google. | Connect | -",+ "antigravity | not-connected | Needs an API key for Google. | Connect | -",+ "opencode | not-connected | Needs an API key for Anthropic, OpenAI, Google or OpenRouter. | Connect | -",+ "goose | not-connected | Needs an API key for OpenAI, Anthropic or OpenRouter. | Connect | -",+ "pi | not-connected | Needs an API key for Anthropic, OpenAI, Google or OpenRouter. | Connect | -",+ "hermes | not-connected | Needs an API key for Anthropic or OpenAI. | Connect | -",+ "openclaw | not-connected | Needs an API key for Anthropic, OpenAI or OpenRouter. | Connect | -"+ ],+ "footer": "Sign-ins and keys stay on this Mac in the Keychain. Each one is only given to the apps that use it.",+ "providers": [+ "anthropic | not-connected | Not connected | Connect",+ "openai | not-connected | Not connected | Connect",+ "google | not-connected | Not connected | Connect",+ "openrouter | not-connected | Not connected | Connect",+ "github | not-connected | Not connected | Connect"+ ],+ "step": "Claude Code is reading its sign-in"+ },{"key": "anthropic | -","sheet": "anthropic","title": "Connect Anthropic","ways": [- "app-token | Sign in with Claude | Sign in",+ "app-token | Use your Claude Code sign-in | Sign in",+ "token | Paste a Claude token | Paste token","key | Paste an API key | Paste key","shell | Use ANTHROPIC_API_KEY from your shell | Use it"]@@ -73,6 +118,40 @@"key | Paste an API key | Paste key"]},+ {+ "buttons": "Use my sign-in | Cancel | Reading your Claude Code sign-in…",+ "importSheet": "macos",+ "notFound": "No Claude Code sign-in found | Claude Code isn't signed in on this Mac, or its sign-in couldn't be read. Pick one:",+ "options": [+ "login | Sign in with Claude Code | claude auth login | Try again",+ "token | Paste a token | - | Paste token",+ "key | Use an Anthropic API key | - | Paste key"+ ],+ "points": [+ "Cua reads your Claude Code sign-in from the Keychain item “Claude Code-credentials” (macOS asks you to allow it), or the file ~/.claude/.credentials.json.",+ "It keeps the access token in Cua's own item in the Keychain, never your refresh token, and doesn't change Claude Code's sign-in. You stay signed in to Claude Code.",+ "Your Spaces get that access token so Claude Code can run there. Only Claude Code uses it.",+ "When it runs out, Cua reads the newer one from Claude Code. Sign out here to remove the copy."+ ],+ "title": "Use your Claude Code sign-in"+ },+ {+ "buttons": "Use my sign-in | Cancel | Reading your Claude Code sign-in…",+ "importSheet": "linux",+ "notFound": "No Claude Code sign-in found | Claude Code isn't signed in on this machine, or its sign-in couldn't be read. Pick one:",+ "options": [+ "login | Sign in with Claude Code | claude auth login | Try again",+ "token | Paste a token | - | Paste token",+ "key | Use an Anthropic API key | - | Paste key"+ ],+ "points": [+ "Cua reads your Claude Code sign-in from the file ~/.claude/.credentials.json.",+ "It keeps the access token in Cua's own place for credentials, never your refresh token, and doesn't change Claude Code's sign-in. You stay signed in to Claude Code.",+ "Your Spaces get that access token so Claude Code can run there. Only Claude Code uses it.",+ "When it runs out, Cua reads the newer one from Claude Code. Sign out here to remove the copy."+ ],+ "title": "Use your Claude Code sign-in"+ },{"does": "true | true | false | - | anthropic","plan": "claude-code"@@ -92,8 +171,8 @@{"detail": "claude-code","note": null,- "signIn": "Signs in with Anthropic | Claude Code sign-in | Sign out",- "status": "Connected",+ "signIn": "Signs in with Anthropic | Not connected | Sign in",+ "status": "Reading your Claude Code sign-in…","toggles": ["skills | Cua skills | true","mcp | Cua tools (MCP) | true",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.rsindex 6996487b53..a9659a6263 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@@ -60,6 +60,8 @@ pub struct AgentKeyInput {pub added_ms: u64,/// A sign-in past its expiry: not used by any run until reconnected.pub expired: bool,+ /// A copied sign-in's name ("Signed in as [email protected] (Claude Max)").+ pub label: Option<String>,}/// What the section shows.@@ -466,6 +468,7 @@ mod tests {last4: last4.into(),added_ms: 1,expired: false,+ label: None,}}diff --git a/libs/cua/crates/cua-spaces-app-core/src/connectors.rs b/libs/cua/crates/cua-spaces-app-core/src/connectors.rsindex 7b278961a6..d930c555b4 100644--- a/libs/cua/crates/cua-spaces-app-core/src/connectors.rs+++ b/libs/cua/crates/cua-spaces-app-core/src/connectors.rs@@ -22,10 +22,13 @@//! - **The setup card** ([`setup_card`]): what a task that couldn't start//! because its app isn't connected says, with "Connect <app>".//!-//! Only official sign-in paths are offered: an app's own token command-//! (`claude setup-token`, which prints a token meant for this use), a key-//! the person pastes, or a key already exported in their shell. Cua never-//! reads another app's private sign-in store for these.+//! The sign-in paths offered: for Claude Code, the sign-in Claude Code+//! already has on this machine, imported once the person agrees+//! ([`import_sheet_on`]; `cua-agent-setup`'s `claude_login` reads it and keeps+//! the access token only), a token from `claude setup-token` the person+//! pastes, a key the person pastes, or a key already exported in their shell.+//! Codex signs in with its own device code, in a folder Cua owns; Cua never+//! reads Codex's own `auth.json` for it.//!//! Every credential lives where the agent keys do (`agent_keys`: the//! daemon's Keychain-backed store); this module only decides the words.@@ -55,6 +58,14 @@ enum Way {label: &'static str,help: &'static str,},+ /// A token the person pastes (Claude's `claude setup-token`), saved+ /// under `env`; only that app uses it.+ Token {+ app: &'static str,+ env: &'static str,+ label: &'static str,+ help: &'static str,+ },/// A key the person pastes.Key,/// The key already exported in the person's shell, saved once.@@ -79,8 +90,15 @@ struct Provider {const CLAUDE_TOKEN: Way = Way::AppToken {app: "claude-code",env: "CLAUDE_CODE_OAUTH_TOKEN",- label: "Sign in with Claude",- help: "Opens your browser to approve. Uses your Claude plan. Only Claude Code uses this sign-in.",+ label: "Use your Claude Code sign-in",+ help: "Reads the sign-in Claude Code already has on this machine. Uses your Claude plan. Only Claude Code uses it.",+};++const CLAUDE_PASTE: Way = Way::Token {+ app: "claude-code",+ env: "CLAUDE_CODE_OAUTH_TOKEN",+ label: "Paste a Claude token",+ help: "Advanced. A token made by running claude setup-token in Terminal. It lasts a year. Only Claude Code uses it.",};const CODEX_DEVICE: Way = Way::AppDevice {@@ -99,7 +117,7 @@ const PROVIDERS: &[Provider] = &[used_by: "Claude Code. Hermes and other apps that use Claude need an API key.",key_help: "Create a key at console.anthropic.com. Every app that uses Claude can use it.",placeholder: "sk-ant-…",- ways: &[CLAUDE_TOKEN, Way::Key, Way::Shell],+ ways: &[CLAUDE_TOKEN, CLAUDE_PASTE, Way::Key, Way::Shell],},Provider {id: "openai",@@ -373,7 +391,7 @@ pub struct ConnectorAppInput {#[serde(rename_all = "camelCase", default)]pub struct ConnectorBusy {pub id: String,- /// `connecting` (tools), `signing-in` (a browser approval), `signing-out`.+ /// `connecting` (tools), `signing-in` (reading the app's sign-in, or a device code), `signing-out`.pub step: String,}@@ -479,8 +497,17 @@ fn app_signed_in(input: &ConnectorsInput, app: &str) -> bool {}/// An app's sign-in is saved but expired.+///+/// Only a sign-in the app can read counts: Claude Code's sign-in running out+/// is Claude Code's to reconnect, not Hermes' (it reads an API key).fn app_expired(input: &ConnectorsInput, app: &str) -> bool {app_sign_in(app).is_some_and(|a| {+ if !a.reads.is_empty() {+ return a+ .reads+ .iter()+ .any(|k| input.key(k).is_some_and(|k| k.expired));+ }a.providers.iter().filter_map(|p| provider(p))@@ -488,6 +515,18 @@ fn app_expired(input: &ConnectorsInput, app: &str) -> bool {})}+/// "Signed in as [email protected] (Claude Max)": the name of the sign-in an app+/// reads, when it has one that works (a copied sign-in, never a typed key).+fn signed_in_as(input: &ConnectorsInput, app: &str) -> Option<String> {+ app_sign_in(app)?.reads.iter().find_map(|e| {+ input+ .key(e)+ .filter(|k| !k.expired)+ .and_then(|k| k.label.clone())+ .filter(|l| !l.is_empty())+ })+}+fn dots(k: &AgentKeyInput) -> String {if k.last4.is_empty() {"Saved".into()@@ -499,8 +538,12 @@ fn dots(k: &AgentKeyInput) -> String {/// How a saved credential reads on its provider's row.fn credential_text(p: &Provider, k: &AgentKeyInput) -> String {match k.env.as_str() {- "CLAUDE_CODE_OAUTH_TOKEN" => "Claude Code sign-in".into(),- "CODEX_AUTH_JSON" => "ChatGPT sign-in, for Codex".into(),+ "CLAUDE_CODE_OAUTH_TOKEN" => k+ .label+ .clone()+ .filter(|l| !l.is_empty())+ .unwrap_or_else(|| "Signed in to Claude".into()),+ "CODEX_AUTH_JSON" => "Signed in with ChatGPT, for Codex".into(),e if e == p.env => format!("API key {}", dots(k)),e => format!("{e} {}", dots(k)),}@@ -551,7 +594,7 @@ pub struct ConnectorProviderRow {/// `connected`, `not-connected`, `connecting`, `failed`.pub state: String,/// "Not connected", "API key •••• 3f9a", "Claude Code sign-in",- /// "Approve in your browser…".+ /// "Reading your Claude Code sign-in…".pub status: String,/// Who uses it.pub detail: String,@@ -661,7 +704,7 @@ fn app_row(input: &ConnectorsInput, a: &ConnectorAppInput) -> ConnectorAppRow {{"Enter the code in your browser…".to_string()}- "signing-in" => "Approve in your browser…".to_string(),+ "signing-in" => "Reading your Claude Code sign-in…".to_string(),"signing-out" => "Signing out…".to_string(),_ => format!("Adding Cua to {}…", a.name),};@@ -680,7 +723,9 @@ fn app_row(input: &ConnectorsInput, a: &ConnectorAppInput) -> ConnectorAppRow {// Not on this machine: say where it runs, once.("connected",- (!a.installed && !a.configured).then(|| "Runs in your Spaces".to_string()),+ signed_in_as(input, &a.agent).or_else(|| {+ (!a.installed && !a.configured).then(|| "Runs in your Spaces".to_string())+ }),None,)} else if a.configured || !a.installed {@@ -689,7 +734,7 @@ fn app_row(input: &ConnectorsInput, a: &ConnectorAppInput) -> ConnectorAppRow {("not-connected",if reconnect {- Some("Needs reconnect.".to_string())+ Some("Needs reconnect".to_string())} else {needs},@@ -727,7 +772,7 @@ fn provider_row(input: &ConnectorsInput, p: &Provider, can_edit: bool) -> Connec"signing-in" if p.ways.iter().any(|w| matches!(w, Way::AppDevice { .. })) => {"Enter the code in your browser…"}- "signing-in" => "Approve in your browser…",+ "signing-in" => "Reading your Claude Code sign-in…",_ => "Connecting…",};(@@ -863,8 +908,9 @@ pub fn view_on(input: &ConnectorsInput, os: SpaceOs) -> ConnectorsView {pub struct ConnectPlan {/// Add Cua's skills and MCP server (`agents.connect`).pub tools: bool,- /// Run the app's own token command (`agents.connect` with `signIn`): one- /// browser approval.+ /// Import the sign-in the app already has on this machine+ /// (`agents.connect` with `signIn`), after the person agrees+ /// ([`import_sheet_on`]).pub app_token: bool,/// Run the app's own device-code sign-in (`agents.signInStart`, then/// `agents.signInWait`): a code to show, entered on the provider's page.@@ -931,12 +977,13 @@ pub fn provider_label(id: &str) -> Option<&'static str> {#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]#[serde(rename_all = "camelCase")]pub struct ProviderWay {- /// `app-token`, `key`, `shell`.+ /// `app-token`, `app-device`, `token`, `key`, `shell`.pub id: String,pub label: String,pub help: String,pub button: String,- /// For `app-token`: the app whose command runs (`agents.connect` with `signIn`).+ /// For `app-token`: the app whose sign-in is imported (`agents.connect` with `signIn`).+ /// For `token`: the app the pasted token is for.pub app: Option<String>,/// For `shell`: the variable read from the shell.pub env: Option<String>,@@ -955,6 +1002,9 @@ pub struct ProviderSheetView {pub key_label: String,pub key_placeholder: String,pub key_help: String,+ /// The field when the person picks Paste a Claude token.+ pub token_label: String,+ pub token_placeholder: String,pub save_label: String,/// What `agentKeys.set` gets with a pasted key: `anthropic`, `openai`, or `other` with `key_env`.pub key_provider: String,@@ -1014,6 +1064,16 @@ pub fn provider_sheet_on(app: Some(app.into()),env: None,}),+ Way::Token {+ app, label, help, ..+ } => for_app.is_none_or(|a| a == app).then(|| ProviderWay {+ id: "token".into(),+ label: label.into(),+ help: help.into(),+ button: "Paste token".into(),+ app: Some(app.into()),+ env: None,+ }),Way::Key => Some(ProviderWay {id: "key".into(),label: "Paste an API key".into(),@@ -1062,6 +1122,8 @@ pub fn provider_sheet_on(key_label: "API key".into(),key_placeholder: p.placeholder.into(),key_help: format!("It's saved {place}on {this} and won't be shown again."),+ token_label: "Claude token".into(),+ token_placeholder: "sk-ant-oat01-\u{2026}".into(),save_label: "Save".into(),key_provider: if matches!(p.id, "anthropic" | "openai") {p.id@@ -1075,6 +1137,100 @@ pub fn provider_sheet_on(})}+/// What importing Claude Code's sign-in says before it reads anything, and+/// what it offers when there is nothing to import.+#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]+#[serde(rename_all = "camelCase")]+pub struct ImportSheetView {+ pub title: String,+ pub lede: String,+ /// What is read, what is kept, where it goes: plain sentences.+ pub points: Vec<String>,+ pub confirm_label: String,+ pub cancel_label: String,+ /// While it reads (and macOS may be asking to allow it).+ pub reading_label: String,+ /// When there is no sign-in to import.+ pub not_found_title: String,+ pub not_found_lede: String,+ /// In order: sign in with Claude Code, paste a token, use an API key.+ pub options: Vec<ImportOption>,+}++/// One way forward when there is no sign-in to import.+#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]+#[serde(rename_all = "camelCase")]+pub struct ImportOption {+ /// `login`, `token`, `key`.+ pub id: String,+ pub label: String,+ pub help: String,+ /// Something to copy and run (`claude auth login`), when there is one.+ pub command: Option<String>,+ pub button: String,+}++/// The words around importing Claude Code's sign-in, for a shell on `os`.+pub fn import_sheet_on(os: SpaceOs) -> ImportSheetView {+ let this = os.this_machine_lower();+ let keychain = vault(os);+ let from = match os {+ SpaceOs::Macos => {+ "the Keychain item \u{201c}Claude Code-credentials\u{201d} (macOS asks you to allow it), or the file ~/.claude/.credentials.json"+ }+ SpaceOs::Windows => "the .credentials.json file in your .claude folder",+ SpaceOs::Linux | SpaceOs::Unknown => "the file ~/.claude/.credentials.json",+ };+ let keep = match keychain {+ Some(v) => format!("in Cua's own item in {v}"),+ None => "in Cua's own place for credentials".to_string(),+ };+ ImportSheetView {+ title: "Use your Claude Code sign-in".into(),+ lede: format!(+ "Run Claude Code in your Spaces with the Claude plan you already use on {this}."+ ),+ points: vec![+ format!("Cua reads your Claude Code sign-in from {from}."),+ format!(+ "It keeps the access token {keep}, never your refresh token, and doesn't change Claude Code's sign-in. You stay signed in to Claude Code."+ ),+ "Your Spaces get that access token so Claude Code can run there. Only Claude Code uses it.".into(),+ "When it runs out, Cua reads the newer one from Claude Code. Sign out here to remove the copy.".into(),+ ],+ confirm_label: "Use my sign-in".into(),+ cancel_label: "Cancel".into(),+ reading_label: "Reading your Claude Code sign-in…".into(),+ not_found_title: "No Claude Code sign-in found".into(),+ not_found_lede: format!(+ "Claude Code isn't signed in on {this}, or its sign-in couldn't be read. Pick one:"+ ),+ options: vec![+ ImportOption {+ id: "login".into(),+ label: "Sign in with Claude Code".into(),+ help: "Run this in Terminal, finish signing in, then try again.".into(),+ command: Some("claude auth login".into()),+ button: "Try again".into(),+ },+ ImportOption {+ id: "token".into(),+ label: "Paste a token".into(),+ help: "Advanced. A token made by running claude setup-token.".into(),+ command: None,+ button: "Paste token".into(),+ },+ ImportOption {+ id: "key".into(),+ label: "Use an Anthropic API key".into(),+ help: "Create a key at console.anthropic.com. It's billed to your API account, not your Claude plan.".into(),+ command: None,+ button: "Paste key".into(),+ },+ ],+ }+}+/// A switch on an app's page.#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]#[serde(rename_all = "camelCase")]@@ -1096,7 +1252,7 @@ pub struct ConnectorSignIn {/// The provider row's status for it ("Claude Code sign-in", "Not connected").pub status: String,pub connected: bool,- /// How Connect signs it in ("Claude sign-in, through claude setup-token").+ /// How Connect signs it in ("the sign-in Claude Code already has").pub way: String,/// The provider it uses (for Sign in and Sign out).pub provider: String,@@ -1131,7 +1287,7 @@ pub struct AppDetailView {fn way_text(app: &str) -> &'static str {match app {"claude-code" => {- "Connect runs claude setup-token: one browser approval, using your Claude plan. Or connect Anthropic with an API key."+ "Connect uses the sign-in Claude Code already has on this machine, with your Claude plan. Or connect Anthropic with an API key."}"codex" => {"Connect signs Codex in with ChatGPT: a code to enter on openai.com, using your ChatGPT plan. Or connect OpenAI with an API key."@@ -1222,7 +1378,7 @@ pub fn app_detail(input: &ConnectorsInput, agent: &str) -> Option<AppDetailView>name: a.name.clone(),back_label: "Connectors".into(),status: match row.state.as_str() {- "connected" => "Connected".into(),+ "connected" => signed_in_as(input, agent).unwrap_or_else(|| "Connected".into()),_ => row.line.clone().unwrap_or_else(|| "Not connected".into()),},connected: row.state == "connected",@@ -1269,7 +1425,7 @@ pub fn setup_card(input: &ConnectorsInput, agent: &str, name: &str) -> SetupCard.map(|p| p.label);let body = match provider {Some(p) if plan.app_token => format!(- "{name} needs a sign-in to {p} to work here. Connect it once: approve in your browser, and every Space can use it."+ "{name} needs a sign-in to {p} to work here. Connect it once: Cua uses the sign-in {name} already has on this machine, and every Space can use it."),Some(p) => format!("{name} needs a sign-in to {p} to work here. Connect it once and every Space can use it."@@ -1281,7 +1437,7 @@ pub fn setup_card(input: &ConnectorsInput, agent: &str, name: &str) -> SetupCardbody,connect_label: format!("Connect {name}"),connecting_label: if plan.app_token {- "Approve in your browser…".into()+ "Reading your Claude Code sign-in…".into()} else if plan.device {"Enter the code in your browser…".into()} else {@@ -1323,6 +1479,7 @@ mod tests {last4: last4.into(),added_ms: 1_000,expired: false,+ label: None,}}@@ -1552,7 +1709,7 @@ mod tests {assert_eq!(p.status, "Needs 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("Needs reconnect."));+ assert_eq!(a.line.as_deref(), Some("Needs reconnect"));// The app's row offers Reconnect, not a first Connect.assert_eq!(a.button.as_ref().map(|b| b.label.as_str()),@@ -1606,7 +1763,7 @@ mod tests {assert_eq!(v.apps[0].state, "connected");let a = &v.providers[0];assert_eq!(a.state, "connected");- assert_eq!(a.status, "Claude Code sign-in");+ assert_eq!(a.status, "Signed in to Claude");assert_eq!(a.button.label, "Sign out");assert_eq!(a.sign_out_envs, ["CLAUDE_CODE_OAUTH_TOKEN"]);// The sign-in token is the provider's, not an Other key.@@ -1645,10 +1802,13 @@ mod tests {});let v = view(&i);assert_eq!(v.apps[0].state, "connecting");- assert_eq!(v.apps[0].line.as_deref(), Some("Approve in your browser…"));+ assert_eq!(+ v.apps[0].line.as_deref(),+ Some("Reading your Claude Code sign-in…")+ );assert!(!v.apps[0].button.as_ref().unwrap().enabled);assert_eq!(v.providers[0].state, "connecting");- assert_eq!(v.providers[0].status, "Approve in your browser…");+ assert_eq!(v.providers[0].status, "Reading your Claude Code sign-in…");assert_eq!(v.apps[1].state, "failed");assert_eq!(v.apps[1].button.as_ref().unwrap().label, "Try again");}@@ -1718,16 +1878,17 @@ mod tests {let s = provider_sheet(&i, "anthropic").unwrap();assert_eq!(s.title, "Connect Anthropic");let ids: Vec<_> = s.ways.iter().map(|w| w.id.as_str()).collect();- assert_eq!(ids, ["app-token", "key", "shell"]);+ assert_eq!(ids, ["app-token", "token", "key", "shell"]);assert_eq!(s.ways[0].app.as_deref(), Some("claude-code"));- assert_eq!(s.ways[2].label, "Use ANTHROPIC_API_KEY from your shell");+ assert_eq!(s.ways[3].label, "Use ANTHROPIC_API_KEY from your shell");// Without Claude Code there is no Claude sign-in to offer; without the// variable, no shell row.i.apps.retain(|a| a.agent != "claude-code");i.shell_keys.clear();let s = provider_sheet(&i, "anthropic").unwrap();let ids: Vec<_> = s.ways.iter().map(|w| w.id.as_str()).collect();- assert_eq!(ids, ["key"]);+ // A token from `claude setup-token` can be pasted without Claude Code here.+ assert_eq!(ids, ["token", "key"]);assert_eq!((s.key_provider.as_str(), s.key_env), ("anthropic", None));let g = provider_sheet(&i, "github").unwrap();assert_eq!(@@ -1772,13 +1933,127 @@ mod tests {assert!(d.sign_in_note.unwrap().contains("signs in on its own"));}+ fn imported(label: &str) -> AgentKeyInput {+ let mut k = key("CLAUDE_CODE_OAUTH_TOKEN", "AAAA");+ k.label = Some(label.into());+ k+ }++ /// One sign-in, one wording, on every surface: the Claude Code app row, the+ /// Anthropic provider row, the app's page and the sign-in block.+ #[test]+ fn an_imported_sign_in_reads_signed_in_as_everywhere() {+ let who = "Signed in as [email protected] (Claude Max)";+ let mut i = input();+ i.apps[0].configured = true;+ i.keys.keys.push(imported(who));+ let v = view(&i);+ assert_eq!(v.apps[0].state, "connected");+ assert_eq!(v.apps[0].line.as_deref(), Some(who));+ assert_eq!(v.providers[0].status, who);+ let d = app_detail(&i, "claude-code").unwrap();+ assert_eq!(d.status, who);+ assert_eq!(d.sign_in.as_ref().unwrap().status, who);+ assert_eq!(d.sign_in.as_ref().unwrap().button.label, "Sign out");+ // Without a name (an older copy) it still says what it is.+ let mut j = input();+ j.apps[0].configured = true;+ j.keys.keys.push(key("CLAUDE_CODE_OAUTH_TOKEN", "AAAA"));+ assert_eq!(view(&j).providers[0].status, "Signed in to Claude");+ }++ #[test]+ fn needs_reconnect_reads_the_same_on_every_surface() {+ let mut i = input();+ i.apps[0].configured = true;+ let mut k = imported("Signed in as [email protected] (Claude Max)");+ k.expired = true;+ i.keys.keys.push(k);+ let v = view(&i);+ assert_eq!(v.apps[0].line.as_deref(), Some("Needs reconnect"));+ assert_eq!(v.providers[0].status, "Needs reconnect");+ assert_eq!(v.apps[0].button.as_ref().unwrap().label, "Reconnect");+ assert_eq!(v.providers[0].button.label, "Reconnect");+ let d = app_detail(&i, "claude-code").unwrap();+ assert_eq!(d.status, "Needs reconnect");+ assert_eq!(d.connect.as_ref().unwrap().label, "Reconnect");+ // An expired copy never shows the name as if it worked.+ assert!(!format!("{v:?}").contains("[email protected]"));+ }++ #[test]+ fn claude_codes_sign_in_running_out_is_not_hermes_to_reconnect() {+ let mut i = input();+ i.apps[0].configured = true;+ let mut k = imported("Signed in as [email protected] (Claude Max)");+ k.expired = true;+ i.keys.keys.push(k);+ let v = view(&i);+ let hermes = v.apps.iter().find(|a| a.agent == "hermes").unwrap();+ assert_eq!(+ hermes.line.as_deref(),+ Some("Needs an API key for Anthropic or OpenAI.")+ );+ assert_eq!(hermes.button.as_ref().unwrap().label, "Connect");+ let claude = v.apps.iter().find(|a| a.agent == "claude-code").unwrap();+ assert_eq!(claude.button.as_ref().unwrap().label, "Reconnect");+ }++ #[test]+ fn the_import_sheet_says_what_is_read_kept_and_sent_in_plain_words() {+ let mac = import_sheet_on(SpaceOs::Macos);+ let text = format!("{}\n{}", mac.lede, mac.points.join("\n"));+ assert!(+ text.contains("Claude Code-credentials")+ && text.contains("~/.claude/.credentials.json")+ );+ assert!(text.contains("Keychain") && text.contains("never your refresh token"));+ assert!(text.contains("stay signed in to Claude Code"));+ assert!(text.contains("Your Spaces get that access token"));+ assert_eq!(mac.confirm_label, "Use my sign-in");+ // Nothing found: sign in with Claude Code, then a token, then a key, in that order.+ let ids: Vec<_> = mac.options.iter().map(|o| o.id.as_str()).collect();+ assert_eq!(ids, ["login", "token", "key"]);+ assert_eq!(mac.options[0].command.as_deref(), Some("claude auth login"));+ // Other systems name their own place, never the macOS Keychain.+ let linux = import_sheet_on(SpaceOs::Linux);+ assert!(!linux.points.join(" ").contains("Keychain"));+ let win = import_sheet_on(SpaceOs::Windows);+ assert!(win.points[0].contains(".credentials.json"));+ }++ /// The words of this feature: no middle dot, no "devices", no promise of+ /// `claude setup-token` as the way Connect works.+ #[test]+ fn the_claude_wording_has_no_middle_dot_devices_or_setup_token_promise() {+ let mut i = input();+ i.apps[0].configured = true;+ i.keys+ .keys+ .push(imported("Signed in as [email protected] (Claude Max)"));+ let mut all = format!("{:?}", view(&i));+ for os in [SpaceOs::Macos, SpaceOs::Windows, SpaceOs::Linux] {+ all += &format!("{:?}", import_sheet_on(os));+ }+ all += &format!("{:?}", app_detail(&i, "claude-code"));+ all += &format!("{:?}", provider_sheet(&input(), "anthropic"));+ all += &format!("{:?}", setup_card(&input(), "claude-code", "Claude Code"));+ assert!(!all.contains('\u{b7}'), "no middle dot");+ assert!(+ !all.to_lowercase().contains("device"),+ "machines, not devices"+ );+ assert!(!all.contains("Connect runs claude setup-token"));+ assert!(!all.contains("one browser approval"));+ }+#[test]fn setup_card_names_the_app() {let i = input();let c = setup_card(&i, "claude-code", "Claude Code");assert_eq!(c.title, "Connect Claude Code to start");assert_eq!(c.connect_label, "Connect Claude Code");- assert_eq!(c.connecting_label, "Approve in your browser…");+ assert_eq!(c.connecting_label, "Reading your Claude Code sign-in…");assert!(c.body.contains("sign-in to Anthropic"));let c = setup_card(&i, "codex", "OpenAI Codex");assert_eq!(c.connect_label, "Connect OpenAI Codex");diff --git a/libs/cua/crates/cua-spaces-app-core/src/dispatch.rs b/libs/cua/crates/cua-spaces-app-core/src/dispatch.rsindex 8242f77424..81d7aeed3d 100644--- a/libs/cua/crates/cua-spaces-app-core/src/dispatch.rs+++ b/libs/cua/crates/cua-spaces-app-core/src/dispatch.rs@@ -199,6 +199,7 @@ pub const METHODS: &[&str] = &["connectors.view","connectors.connectPlan","connectors.providerSheet",+ "connectors.importSheet","connectors.appDetail","connectors.setupCard","summon.candidates",@@ -1005,6 +1006,10 @@ pub fn call_value(method: &str, args: Value) -> Result<Value, CoreError> {.unwrap_or(SpaceOs::Macos),a.get::<Option<String>>("forApp")?.as_deref(),)),+ "connectors.importSheet" => out(connectors::import_sheet_on(+ a.get::<Option<SpaceOs>>("hostOs")?+ .unwrap_or(SpaceOs::Macos),+ )),"connectors.appDetail" => out(connectors::app_detail(&a.get("input")?,&a.get::<String>("agent")?,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.rsindex 6d93ef8689..8b2b16a2b8 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@@ -2044,6 +2044,7 @@ mod tests {last4: "1234".into(),added_ms: 1,expired: false,+ label: None,}).collect(),..Default::default()diff --git a/libs/cua/crates/cua-spaces-app-core/src/parity.rs b/libs/cua/crates/cua-spaces-app-core/src/parity.rsindex 761b8a033e..c2e0051fde 100644--- a/libs/cua/crates/cua-spaces-app-core/src/parity.rs+++ b/libs/cua/crates/cua-spaces-app-core/src/parity.rs@@ -5084,6 +5084,23 @@ fn run_connectors(f: &Value, h: &dyn Host) -> Result<Value, String> {.collect();frames.push(json!({ "sheet": p, "title": s["title"], "ways": ways, "key": line(&[&s["keyProvider"], &s["keyEnv"]]) }));}+ for os in ["macos", "linux"] {+ let s = c(h, "connectors.importSheet", json!({ "hostOs": os }))?;+ let options: Vec<String> = s["options"]+ .as_array()+ .into_iter()+ .flatten()+ .map(|o| line(&[&o["id"], &o["label"], &o["command"], &o["button"]]))+ .collect();+ frames.push(json!({+ "importSheet": os,+ "title": s["title"],+ "points": s["points"],+ "buttons": line(&[&s["confirmLabel"], &s["cancelLabel"], &s["readingLabel"]]),+ "notFound": line(&[&s["notFoundTitle"], &s["notFoundLede"]]),+ "options": options,+ }));+ }for a in f["plans"].as_array().into_iter().flatten() {let p = c(h,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.rsindex e3483380f6..848ec8febc 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@@ -440,6 +440,7 @@ mod tests {last4: String::new(),added_ms: 1,expired: false,+ label: None,}],..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.rsindex 48c70e78dc..4adb4a79c4 100644--- a/libs/cua/crates/cua-spaces-app-core/src/summon.rs+++ b/libs/cua/crates/cua-spaces-app-core/src/summon.rs@@ -295,7 +295,7 @@ fn cant_wake(detail,connect_label: connect.then(|| format!("Connect {name}")),connecting_label: if plan.app_token {- "Approve in your browser…".into()+ "Reading your Claude Code sign-in…".into()} else if plan.device {"Enter the code in your browser…".into()} else {@@ -496,6 +496,7 @@ mod tests {last4: "abcd".into(),added_ms: 1,expired: false,+ label: None,}).collect(),..Default::default()@@ -575,7 +576,7 @@ mod tests {assert_eq!(c.connect_label.as_deref(), Some("Connect Claude Code"));assert_eq!(c.open_label.as_deref(), Some("Claude Code settings"));assert_eq!(c.retry_label, "Send again");- assert_eq!(c.connecting_label, "Approve in your browser…");+ assert_eq!(c.connecting_label, "Reading your Claude Code sign-in…");assert!(c.detail.contains("sign-in to Anthropic"));// A member runs on its owner's keys: woken, never checked against this device's.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.rsindex 1676c31155..1a27614530 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@@ -6671,6 +6671,8 @@ pub struct AppAgentKeyInput {pub added_ms: u64,/// A sign-in past its expiry: not used by any run until reconnected.pub expired: bool,+ /// A copied sign-in's name ("Signed in as [email protected] (Claude Max)").+ pub label: Option<String>,}/// 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.rsindex 0079d38733..b366b768a1 100644--- a/libs/cua/crates/cua-spaces/src/agents/keys.rs+++ b/libs/cua/crates/cua-spaces/src/agents/keys.rs@@ -17,6 +17,7 @@//! `env_from_host`, never into logs or telemetry.use crate::error::{Error, Result};+use cua_agents::claude_login;use serde::{Deserialize, Serialize};use std::collections::BTreeMap;use std::sync::{Mutex, OnceLock};@@ -254,7 +255,7 @@ pub struct KeyInfo {pub last4: String,/// When it was added (Unix ms).pub added_ms: u64,- /// A copied sign-in's name ("Codex · ChatGPT sign-in"); none for a key+ /// A copied sign-in's name ("ChatGPT sign-in for Codex"); none for a key/// typed in Settings.#[serde(skip_serializing_if = "Option::is_none")]pub label: Option<String>,@@ -297,6 +298,11 @@ struct Stored {/// the credential again replaces the entry, so a reconnect clears it.#[serde(default, skip_serializing_if = "Option::is_none")]rejected_ms: Option<u64>,+ /// How a copied sign-in was made (`claude-login-keychain`, `claude-login-file`,+ /// `device-code`, `token`). A `claude-login-*` copy is re-read from Claude+ /// Code's own sign-in when it runs out ([`AgentKeys::sync_claude_login`]).+ #[serde(default, skip_serializing_if = "Option::is_none")]+ origin: Option<String>,}impl std::fmt::Debug for Stored {@@ -353,12 +359,72 @@ struct Blob {/// the next run must see them.const CACHE_FOR: Duration = Duration::from_secs(2);+/// The variable Claude Code's sign-in is delivered as.+const CLAUDE_ENV: &str = "CLAUDE_CODE_OAUTH_TOKEN";++/// How long before its expiry a copied Claude sign-in is looked at again.+const REFRESH_WITHIN_MS: u64 = 30 * 60 * 1000;++/// The least time between two re-reads of Claude Code's own sign-in.+const RESYNC_EVERY: Duration = Duration::from_secs(20);++/// How long Claude Code may take to refresh its own sign-in when asked.+const ASK_WAIT: Duration = Duration::from_secs(25);++/// Where the freshness check reads Claude Code's own sign-in (a fake in tests).+pub trait ClaudeLogin: Send + Sync {+ /// Reads Claude Code's sign-in now.+ fn lookup(&self) -> claude_login::Lookup;+ /// Asks Claude Code to refresh its own sign-in; whether that ran well.+ fn ask_to_refresh(&self) -> bool;+}++/// This computer's Claude Code. Reads nothing in a test process.+pub struct HostClaudeLogin;++impl ClaudeLogin for HostClaudeLogin {+ fn lookup(&self) -> claude_login::Lookup {+ if cua_home::is_test_process() {+ return claude_login::Lookup::NotSignedIn;+ }+ let env = cua_agents::HostEnv::current();+ claude_login::lookup(&env, &*claude_login::default_keychain(&env), now_ms())+ }++ fn ask_to_refresh(&self) -> bool {+ let env = cua_agents::HostEnv::current();+ // Called from async code: tell the runtime this thread blocks.+ let ask = || claude_login::ask_claude_to_refresh(&env, ASK_WAIT);+ match tokio::runtime::Handle::try_current() {+ Ok(h) if h.runtime_flavor() == tokio::runtime::RuntimeFlavor::MultiThread => {+ tokio::task::block_in_place(ask)+ }+ _ => ask(),+ }+ }+}++/// What [`AgentKeys::sync_claude_login`] did.+#[derive(Clone, Copy, Debug, PartialEq, Eq)]+pub enum LoginSync {+ /// There is no copy of Claude Code's sign-in.+ NotApplicable,+ /// The copy works and is not about to run out.+ Fresh,+ /// A newer sign-in was read from Claude Code and saved.+ Updated,+ /// The copy has run out and Claude Code has nothing newer: Reconnect.+ Stale,+}+/// The stored agent keys of one credential store.pub struct AgentKeys {store: Option<cua_auth::Store>,unavailable: Option<String>,// Serializes read-modify-write; holds the last read.cache: Mutex<Option<(Instant, Vec<Stored>)>>,+ // When Claude Code's own sign-in was last re-read ([`AgentKeys::sync_claude_login`]).+ claude_sync: Mutex<Option<Instant>>,}impl std::fmt::Debug for AgentKeys {@@ -391,6 +457,7 @@ impl AgentKeys {store: Some(store),unavailable: None,cache: Mutex::new(None),+ claude_sync: Mutex::new(None),}} else {Self::unavailable(file_store_reason())@@ -403,6 +470,7 @@ impl AgentKeys {store: None,unavailable: Some(reason.into()),cache: Mutex::new(None),+ claude_sync: Mutex::new(None),}}@@ -475,6 +543,21 @@ impl AgentKeys {/// Adds or replaces a key. `provider` is `anthropic`, `openai` or/// `other`; `other` needs `env` (checked by [`validate_name`]).pub fn set(&self, provider: &str, env: Option<&str>, value: &str) -> Result<KeyInfo> {+ // A Claude token (`sk-ant-oat...`, from `claude setup-token`) pasted where an API+ // key goes is a sign-in for Claude Code, not an API key: saved as one, so it+ // works for Claude Code and is never offered to another app as a key.+ if provider == "anthropic" && value.trim().contains("sk-ant-oat") {+ let copy = cua_agents::signin::claude_pasted_token(value)+ .map_err(|r| Error::InvalidArgument(r.line().into()))?;+ return self.import(+ ©.source,+ ©.env,+ ©.label,+ ©.value,+ copy.expires_ms,+ copy.origin.as_deref(),+ );+ }let env = match (provider, env.map(str::trim).filter(|e| !e.is_empty())) {("other", Some(e)) => {validate_name(e)?;@@ -512,6 +595,7 @@ impl AgentKeys {source: None,expires_ms: None,rejected_ms: None,+ origin: None,};let info = stored.info();keys.push(stored);@@ -547,6 +631,7 @@ impl AgentKeys {label: &str,value: &str,expires_ms: Option<u64>,+ origin: Option<&str>,) -> Result<KeyInfo> {validate_name(env)?;let value = validate_value(value)?;@@ -573,6 +658,7 @@ impl AgentKeys {source: Some(source.into()),expires_ms,rejected_ms: None,+ origin: origin.map(str::to_string),};let info = stored.info();keys.push(stored);@@ -612,6 +698,100 @@ impl AgentKeys {.collect())}+ /// Keeps a copy of Claude Code's own sign-in usable, without ever+ /// refreshing it ourselves.+ ///+ /// Claude Code's access token lasts hours, and its refresh token works+ /// once: each refresh returns a new pair and spends the old one. If Cua+ /// refreshed, Claude Code's next refresh would fail and sign the person+ /// out of Claude Code. So Cua keeps the access token only, and when its+ /// copy is within [`REFRESH_WITHIN_MS`] of running out (or a run said it+ /// was refused) it reads Claude Code's own sign-in again: Claude Code+ /// refreshes it as it is used and writes the new pair under its own lock.+ /// With `ask` and nothing newer there, Claude Code is asked to refresh by+ /// a one-line request ([`ClaudeLogin::ask_to_refresh`], at most every five+ /// minutes), waiting a few seconds. Never a request of ours to Anthropic,+ /// and nothing is checked live before saving.+ ///+ /// Re-read at most every 20 seconds. Only copies made by importing+ /// Claude Code's sign-in are touched.+ pub fn sync_claude_login(&self, src: &dyn ClaudeLogin, ask: bool) -> LoginSync {+ let copy = {+ let mut g = self.lock();+ match self.read(&mut g, false) {+ Ok(keys) => keys.into_iter().find(|k| {+ k.env == CLAUDE_ENV+ && k.origin+ .as_deref()+ .is_some_and(|o| o.starts_with("claude-login"))+ }),+ Err(_) => None,+ }+ };+ let Some(copy) = copy else {+ return LoginSync::NotApplicable;+ };+ let now = now_ms();+ let rejected = copy.rejected_ms.is_some();+ let running_out = rejected+ || copy+ .expires_ms+ .is_some_and(|e| e <= now + REFRESH_WITHIN_MS);+ if !running_out {+ return LoginSync::Fresh;+ }+ let verdict = |copy: &Stored| {+ if copy.usable() {+ LoginSync::Fresh+ } else {+ LoginSync::Stale+ }+ };+ {+ let mut last = self.claude_sync.lock().unwrap_or_else(|p| p.into_inner());+ if last.is_some_and(|t| t.elapsed() < RESYNC_EVERY) {+ return verdict(©);+ }+ *last = Some(Instant::now());+ }+ let newer = |l: &claude_login::Lookup| -> Option<claude_login::Found> {+ match l {+ claude_login::Lookup::Found(f)+ if !f.oauth.expired(now_ms())+ && f.oauth.access_token != copy.value+ && (rejected+ || f.oauth.expires_ms.unwrap_or(u64::MAX)+ > copy.expires_ms.unwrap_or(0)) =>+ {+ Some(f.clone())+ }+ _ => None,+ }+ };+ let mut found = newer(&src.lookup());+ if found.is_none() && ask && src.ask_to_refresh() {+ found = newer(&src.lookup());+ }+ let Some(f) = found else {+ return verdict(©);+ };+ let origin = match f.source {+ claude_login::Source::Keychain { .. } => "claude-login-keychain",+ claude_login::Source::File(_) => "claude-login-file",+ };+ match self.import(+ "claude-code",+ CLAUDE_ENV,+ &f.label(),+ &f.oauth.access_token,+ f.oauth.expires_ms,+ Some(origin),+ ) {+ Ok(_) => LoginSync::Updated,+ Err(_) => verdict(©),+ }+ }+/// The names of the stored keys (readiness). A store that can't be read/// has none.pub fn names(&self) -> Vec<String> {@@ -921,7 +1101,12 @@ pub fn app_call(};Some(match name {// The check needs the network: `app_tool_async` does it; a synchronous caller gets the list.- "agent_keys.list" | "agent_keys.check" => report(keys.report()),+ "agent_keys.list" | "agent_keys.check" => {+ // A copy of Claude Code's sign-in that ran out is read again from+ // Claude Code before Settings calls it "Needs reconnect".+ keys.sync_claude_login(&HostClaudeLogin, false);+ report(keys.report())+ }"agent_keys.set" => report(serde_json::from_value::<SetArgs>(args).map_err(|e| {@@ -1070,9 +1255,10 @@ mod tests {app.import("codex","CODEX_AUTH_JSON",- "Codex · ChatGPT sign-in",+ "ChatGPT sign-in for Codex","{\"tokens\":{}}",None,+ None,).unwrap();// Settings' next read sees it right away.@@ -1099,9 +1285,10 @@ mod tests {keys.import("claude-code","CLAUDE_CODE_OAUTH_TOKEN",- "Claude Code · Claude sign-in",+ "Signed in as [email protected] (Claude Max)","sk-ant-oat01-test",Some(long_ago),+ None,).unwrap();let listed = keys.list().unwrap();@@ -1112,9 +1299,10 @@ mod tests {keys.import("claude-code","CLAUDE_CODE_OAUTH_TOKEN",- "Claude Code · Claude sign-in",+ "Signed in as [email protected] (Claude Max)","sk-ant-oat01-test",Some(now_ms() + 3_600_000),+ None,).unwrap();assert!(!keys.list().unwrap()[0].expired);@@ -1178,6 +1366,7 @@ mod tests {"Claude sign-in","sk-ant-oat01-whatever",None,+ None,).unwrap();let report = keys.recheck(&ep).await.unwrap();@@ -1244,6 +1433,7 @@ mod tests {"Claude sign-in","sk-ant-oat01-whatever",None,+ None,).unwrap();keys.set("openai", None, "sk-openai-1111-wxyz").unwrap();@@ -1450,4 +1640,295 @@ mod tests {}let _ = std::fs::remove_dir_all(&dir);}++ // ---- the freshness check on a copy of Claude Code's own sign-in++ const HOUR: u64 = 3_600_000;++ fn login(access: &str, expires_ms: u64, email: &str) -> claude_login::Lookup {+ claude_login::Lookup::Found(claude_login::Found {+ source: claude_login::Source::File(std::path::PathBuf::from(+ "/fixture/.credentials.json",+ )),+ oauth: claude_login::Oauth {+ access_token: access.into(),+ has_refresh_token: true,+ expires_ms: Some(expires_ms),+ scopes: vec![],+ subscription_type: Some("max".into()),+ },+ account: claude_login::Account {+ email: Some(email.into()),+ organization: None,+ },+ })+ }++ /// A fake Claude Code: what its sign-in reads as now, what it reads as after it+ /// is asked to refresh, and how often it was read and asked.+ struct FakeClaude {+ now: Mutex<claude_login::Lookup>,+ after_ask: Option<claude_login::Lookup>,+ reads: Mutex<u32>,+ asks: Mutex<u32>,+ }+ impl FakeClaude {+ fn new(now: claude_login::Lookup, after_ask: Option<claude_login::Lookup>) -> Self {+ Self {+ now: Mutex::new(now),+ after_ask,+ reads: Mutex::new(0),+ asks: Mutex::new(0),+ }+ }+ }+ impl ClaudeLogin for FakeClaude {+ fn lookup(&self) -> claude_login::Lookup {+ *self.reads.lock().unwrap() += 1;+ self.now.lock().unwrap().clone()+ }+ fn ask_to_refresh(&self) -> bool {+ *self.asks.lock().unwrap() += 1;+ match &self.after_ask {+ Some(l) => {+ *self.now.lock().unwrap() = l.clone();+ true+ }+ None => false,+ }+ }+ }++ fn import_login(keys: &AgentKeys, token: &str, expires_ms: u64) {+ keys.import(+ "claude-code",+ CLAUDE_ENV,+ "Signed in as [email protected] (Claude Max)",+ token,+ Some(expires_ms),+ Some("claude-login-file"),+ )+ .unwrap();+ }++ fn token_of(keys: &AgentKeys) -> String {+ keys.values(&[CLAUDE_ENV])+ .remove(CLAUDE_ENV)+ .unwrap_or_default()+ }++ #[test]+ fn a_copy_far_from_expiry_is_delivered_without_reading_claude_code() {+ let (keys, dir) = temp_keys();+ import_login(&keys, "sk-ant-oat01-one", now_ms() + 5 * HOUR);+ let claude = FakeClaude::new(claude_login::Lookup::NotSignedIn, None);+ assert_eq!(keys.sync_claude_login(&claude, true), LoginSync::Fresh);+ assert_eq!(+ *claude.reads.lock().unwrap(),+ 0,+ "no Keychain read when nothing is needed"+ );+ assert_eq!(*claude.asks.lock().unwrap(), 0);+ let _ = std::fs::remove_dir_all(&dir);+ }++ #[test]+ fn only_copies_made_from_claude_codes_own_sign_in_are_synced() {+ let (keys, dir) = temp_keys();+ let claude = FakeClaude::new(+ login("sk-ant-oat01-new", now_ms() + 8 * HOUR, "[email protected]"),+ None,+ );+ assert_eq!(+ keys.sync_claude_login(&claude, true),+ LoginSync::NotApplicable+ );+ // A pasted token (a year, no refresh) and an API key are never replaced.+ keys.import(+ "claude-code",+ CLAUDE_ENV,+ "Claude token you pasted",+ "sk-ant-oat01-pasted",+ Some(now_ms() - 1),+ Some("token"),+ )+ .unwrap();+ assert_eq!(+ keys.sync_claude_login(&claude, true),+ LoginSync::NotApplicable+ );+ assert_eq!(*claude.reads.lock().unwrap(), 0);+ assert_eq!(token_of(&keys), "");+ let _ = std::fs::remove_dir_all(&dir);+ }++ #[test]+ fn a_copy_about_to_run_out_is_replaced_by_what_claude_code_has_refreshed() {+ let (keys, dir) = temp_keys();+ import_login(&keys, "sk-ant-oat01-old", now_ms() + HOUR / 4);+ let claude = FakeClaude::new(+ login("sk-ant-oat01-new", now_ms() + 8 * HOUR, "[email protected]"),+ None,+ );+ assert_eq!(keys.sync_claude_login(&claude, true), LoginSync::Updated);+ assert_eq!(token_of(&keys), "sk-ant-oat01-new");+ let listed = keys.list().unwrap();+ assert_eq!(listed.len(), 1);+ assert!(!listed[0].expired);+ assert_eq!(+ listed[0].label.as_deref(),+ Some("Signed in as [email protected] (Claude Max)")+ );+ assert_eq!(+ *claude.asks.lock().unwrap(),+ 0,+ "no need to ask Claude Code: it had refreshed"+ );+ let _ = std::fs::remove_dir_all(&dir);+ }++ #[test]+ fn a_run_out_copy_asks_claude_code_to_refresh_once_and_reads_again() {+ let (keys, dir) = temp_keys();+ import_login(&keys, "sk-ant-oat01-old", now_ms() - 1000);+ assert!(keys.list().unwrap()[0].expired);+ // Claude Code has the same run-out token until asked; then it has a new one.+ let claude = FakeClaude::new(+ login("sk-ant-oat01-old", now_ms() - 1000, "[email protected]"),+ Some(login(+ "sk-ant-oat01-fresh",+ now_ms() + 8 * HOUR,+ "[email protected]",+ )),+ );+ assert_eq!(keys.sync_claude_login(&claude, true), LoginSync::Updated);+ assert_eq!(*claude.asks.lock().unwrap(), 1);+ assert_eq!(token_of(&keys), "sk-ant-oat01-fresh");+ assert!(!keys.list().unwrap()[0].expired);+ let _ = std::fs::remove_dir_all(&dir);+ }++ #[test]+ fn settings_reads_again_but_never_asks_claude_code_to_refresh() {+ let (keys, dir) = temp_keys();+ import_login(&keys, "sk-ant-oat01-old", now_ms() - 1000);+ let claude = FakeClaude::new(+ login("sk-ant-oat01-old", now_ms() - 1000, "[email protected]"),+ Some(login("sk-ant-oat01-fresh", now_ms() + HOUR, "[email protected]")),+ );+ assert_eq!(keys.sync_claude_login(&claude, false), LoginSync::Stale);+ assert_eq!(*claude.asks.lock().unwrap(), 0);+ assert!(+ keys.list().unwrap()[0].expired,+ "honest: Needs reconnect until Claude Code has a new one"+ );+ let _ = std::fs::remove_dir_all(&dir);+ }++ #[test]+ fn nothing_newer_anywhere_is_needs_reconnect_and_signed_out_is_not_guessed_at() {+ let (keys, dir) = temp_keys();+ import_login(&keys, "sk-ant-oat01-old", now_ms() - 1000);+ for gone in [+ claude_login::Lookup::NotSignedIn,+ claude_login::Lookup::Denied,+ ] {+ let (k2, d2) = temp_keys();+ import_login(&k2, "sk-ant-oat01-old", now_ms() - 1000);+ let claude = FakeClaude::new(gone, None);+ assert_eq!(k2.sync_claude_login(&claude, true), LoginSync::Stale);+ assert_eq!(token_of(&k2), "", "an expired copy is never delivered");+ let _ = std::fs::remove_dir_all(&d2);+ }+ // An older or equal token from Claude Code is not "newer".+ let claude = FakeClaude::new(login("sk-ant-oat01-old", now_ms() - 1000, "[email protected]"), None);+ assert_eq!(keys.sync_claude_login(&claude, true), LoginSync::Stale);+ let _ = std::fs::remove_dir_all(&dir);+ }++ #[test]+ fn claude_code_is_read_at_most_every_twenty_seconds() {+ let (keys, dir) = temp_keys();+ import_login(&keys, "sk-ant-oat01-old", now_ms() - 1000);+ let claude = FakeClaude::new(claude_login::Lookup::NotSignedIn, None);+ for _ in 0..5 {+ assert_eq!(keys.sync_claude_login(&claude, true), LoginSync::Stale);+ }+ assert_eq!(*claude.reads.lock().unwrap(), 1);+ assert_eq!(*claude.asks.lock().unwrap(), 1);+ let _ = std::fs::remove_dir_all(&dir);+ }++ #[test]+ fn a_refused_copy_recovers_when_claude_code_has_a_different_sign_in() {+ let (keys, dir) = temp_keys();+ import_login(&keys, "sk-ant-oat01-revoked", now_ms() + 5 * HOUR);+ keys.mark_rejected(&[CLAUDE_ENV]).unwrap();+ assert!(+ keys.list().unwrap()[0].expired,+ "refused reads as Needs reconnect"+ );+ // Claude Code still holds the same refused token: stays refused.+ let same = FakeClaude::new(+ login("sk-ant-oat01-revoked", now_ms() + 5 * HOUR, "[email protected]"),+ None,+ );+ assert_eq!(keys.sync_claude_login(&same, false), LoginSync::Stale);+ assert!(keys.list().unwrap()[0].expired);+ // The person signed in again in Claude Code: the new sign-in replaces it.+ let (keys2, dir2) = temp_keys();+ import_login(&keys2, "sk-ant-oat01-revoked", now_ms() + 5 * HOUR);+ keys2.mark_rejected(&[CLAUDE_ENV]).unwrap();+ let again = FakeClaude::new(+ login("sk-ant-oat01-again", now_ms() + 8 * HOUR, "[email protected]"),+ None,+ );+ assert_eq!(keys2.sync_claude_login(&again, false), LoginSync::Updated);+ assert!(!keys2.list().unwrap()[0].expired);+ assert_eq!(token_of(&keys2), "sk-ant-oat01-again");+ let _ = std::fs::remove_dir_all(&dir);+ let _ = std::fs::remove_dir_all(&dir2);+ }++ #[test]+ fn a_claude_token_pasted_as_an_api_key_is_saved_as_a_claude_code_sign_in() {+ let (keys, dir) = temp_keys();+ let token = format!("sk-ant-oat01-{}", "aB3_".repeat(24));+ let info = keys+ .set("anthropic", None, &format!(" {token}\n"))+ .unwrap();+ assert_eq!(info.env, CLAUDE_ENV);+ assert_eq!(info.label.as_deref(), Some("Signed in with a Claude token"));+ assert!(+ info.expires_ms+ .is_some_and(|e| e > now_ms() + 300 * 24 * 3600 * 1000)+ );+ assert_eq!(keys.values(&[CLAUDE_ENV]).get(CLAUDE_ENV), Some(&token));+ assert!(+ keys.values(&["ANTHROPIC_API_KEY"]).is_empty(),+ "never as an API key"+ );+ // Never re-read from Claude Code: a pasted token is the person's own.+ let claude = FakeClaude::new(login("sk-ant-oat01-x", now_ms() + HOUR, "[email protected]"), None);+ assert_eq!(+ keys.sync_claude_login(&claude, true),+ LoginSync::NotApplicable+ );+ // A cut-off one is refused in plain words, and a real API key is untouched.+ let e = keys+ .set("anthropic", None, "sk-ant-oat01-short")+ .unwrap_err()+ .to_string();+ assert!(e.contains("doesn't look like a Claude token"), "{e}");+ keys.set("anthropic", None, "sk-ant-api03-abcdefghijklmnop")+ .unwrap();+ assert_eq!(keys.values(&["ANTHROPIC_API_KEY"]).len(), 1);+ let _ = std::fs::remove_dir_all(&dir);+ }++ #[test]+ fn the_host_login_reads_nothing_in_a_test_process() {+ assert_eq!(HostClaudeLogin.lookup(), claude_login::Lookup::NotSignedIn);+ assert!(!HostClaudeLogin.ask_to_refresh());+ }}diff --git a/libs/cua/crates/cua-spaces/src/agents/mod.rs b/libs/cua/crates/cua-spaces/src/agents/mod.rsindex 51255a633b..97b1906481 100644--- a/libs/cua/crates/cua-spaces/src/agents/mod.rs+++ b/libs/cua/crates/cua-spaces/src/agents/mod.rs@@ -313,6 +313,11 @@ pub fn run_env_with(custom_endpoint: bool,) -> Result<(BTreeMap<String, String>, Vec<String>)> {let (host_env, missing) = env_from_host_with(saved, env_from_host)?;+ // A copy of Claude Code's own sign-in that is running out is read again+ // from Claude Code first (never refreshed by Cua: [`keys::AgentKeys::sync_claude_login`]).+ if harness == "claude-code" {+ saved.sync_claude_login(&keys::HostClaudeLogin, true);+ }let mut out = env.clone();out.extend(host_env);if !custom_endpoint && let Some(h) = harness::harness(harness) {@@ -324,9 +329,30 @@ pub fn run_env_with(.collect();out.extend(saved.values(&wanted));}+ oauth_token_as_api_key(harness, &mut out);Ok((out, missing))}+/// A Claude token (`sk-ant-oat...`) in `ANTHROPIC_API_KEY` is a subscription+/// sign-in that was put where a key goes (typed there, or exported that way+/// in a shell). Claude Code gets it as the sign-in it is+/// (`CLAUDE_CODE_OAUTH_TOKEN`; an API key slot answers it with a 401); no+/// other harness gets it at all: the Claude subscription is Claude Code's alone.+fn oauth_token_as_api_key(harness: &str, env: &mut BTreeMap<String, String>) {+ const KEY: &str = "ANTHROPIC_API_KEY";+ const TOKEN: &str = "CLAUDE_CODE_OAUTH_TOKEN";+ if !env+ .get(KEY)+ .is_some_and(|v| v.trim().starts_with("sk-ant-oat"))+ {+ return;+ }+ let value = env.remove(KEY).unwrap_or_default();+ if harness == "claude-code" && env.get(TOKEN).is_none_or(|v| v.is_empty()) {+ env.insert(TOKEN.into(), value.trim().to_string());+ }+}+/// Largest host file `agent_start.files` attaches.const MAX_ATTACHMENT: u64 = 8 * 1024 * 1024;@@ -464,6 +490,78 @@ mod tests {(k, dir)}+ /// Hermes (and every harness but Claude Code) gets exactly what its own adapter takes+ /// as an API key: never the Claude subscription sign-in, in any slot.+ /// Hermes' adapter would use `CLAUDE_CODE_OAUTH_TOKEN`, `ANTHROPIC_TOKEN` or a token in+ /// `ANTHROPIC_API_KEY` as a subscription login (and, given `~/.claude/.credentials.json`+ /// with a refresh token, refresh it and spend Claude Code's single-use refresh token), so+ /// none of those is ever forwarded to it.+ #[test]+ fn hermes_gets_api_keys_and_never_the_claude_subscription_sign_in() {+ let none = BTreeMap::new();+ let token = format!("sk-ant-oat01-{}", "aB3_".repeat(24));+ let (k, dir) = saved(&[+ ("openai", None, "sk-test-0000-bbbb"),+ ("other", Some("OPENROUTER_API_KEY"), "sk-or-test-0000-cccc"),+ ]);+ // The imported Claude sign-in is saved too.+ k.import(+ "claude-code",+ "CLAUDE_CODE_OAUTH_TOKEN",+ "Signed in as [email protected] (Claude Max)",+ &token,+ Some(u64::MAX / 2),+ Some("claude-login-file"),+ )+ .unwrap();+ let (env, _) = run_env_with(&k, "hermes", &none, &[], false).unwrap();+ assert_eq!(+ env.keys().collect::<Vec<_>>(),+ ["OPENAI_API_KEY", "OPENROUTER_API_KEY"],+ "Hermes gets provider keys only"+ );+ let (env, _) = run_env_with(&k, "claude-code", &none, &[], false).unwrap();+ assert_eq!(env["CLAUDE_CODE_OAUTH_TOKEN"], token);+ for h in [+ "hermes",+ "opencode",+ "goose",+ "pi",+ "openclaw",+ "gemini-cli",+ "openai-codex",+ ] {+ let (env, _) = run_env_with(&k, h, &none, &[], false).unwrap();+ assert!(+ env.values().all(|v| !v.contains("sk-ant-oat")),+ "{h} must not get the Claude subscription token"+ );+ assert!(+ !env.contains_key("CLAUDE_CODE_OAUTH_TOKEN")+ && !env.contains_key("ANTHROPIC_TOKEN"),+ "{h}"+ );+ }+ // A token that was exported as ANTHROPIC_API_KEY: Claude Code gets it as its sign-in,+ // Hermes gets nothing from it (so Hermes says it needs an API key).+ let shell = BTreeMap::from([("ANTHROPIC_API_KEY".to_string(), token.clone())]);+ let (env, _) = run_env_with(&k, "hermes", &shell, &[], false).unwrap();+ assert!(+ !env.contains_key("ANTHROPIC_API_KEY") && !env.contains_key("CLAUDE_CODE_OAUTH_TOKEN")+ );+ let (env, _) = run_env_with(&k, "claude-code", &shell, &[], false).unwrap();+ assert!(!env.contains_key("ANTHROPIC_API_KEY"));+ assert_eq!(env["CLAUDE_CODE_OAUTH_TOKEN"], token);+ // A real API key still goes to Hermes as ANTHROPIC_API_KEY.+ let key = BTreeMap::from([(+ "ANTHROPIC_API_KEY".to_string(),+ "sk-ant-api03-real".to_string(),+ )]);+ let (env, _) = run_env_with(&k, "hermes", &key, &[], false).unwrap();+ assert_eq!(env["ANTHROPIC_API_KEY"], "sk-ant-api03-real");+ let _ = std::fs::remove_dir_all(&dir);+ }+#[test]fn saved_keys_reach_only_the_harnesses_that_read_them() {let (k, dir) = saved(&[diff --git a/libs/cua/crates/cua-telemetry/src/events.rs b/libs/cua/crates/cua-telemetry/src/events.rsindex 214195b48a..a0c76579f8 100644--- a/libs/cua/crates/cua-telemetry/src/events.rs+++ b/libs/cua/crates/cua-telemetry/src/events.rs@@ -1472,10 +1472,28 @@ pub fn space_tool_group(tool: &str) -> Option<&'static str> {}/// `cua_agent_signin_imported`: Connect copied `harness`'s sign-in into-/// Keyvault on This Mac (only that it happened, and for which agent).-pub fn agent_signin_imported(harness: &str) -> Event {+/// Keyvault on This Mac (only that it happened, for which agent, and how:+/// `origin` is the copy's origin, `claude-login-keychain` and so on).+pub fn agent_signin_imported(harness: &str, origin: Option<&str>) -> Event {+ let via = match origin {+ Some("claude-login-keychain") => "claude_login_keychain",+ Some("claude-login-file") => "claude_login_file",+ Some("device-code") => "device_code",+ Some("token") => "token",+ _ => "other",+ };Event::new(event::AGENT_SIGNIN_IMPORTED).s("harness", pick(schema::SIGNIN_HARNESSES, harness, "other"))+ .s("via", via)+}++/// `cua_agent_signin_refused`: Connect could not copy `harness`'s sign-in;+/// `kind` is the refusal kind (`not_signed_in`, `cancelled`, `not_yet`,+/// `failed`). Never the line, the error or the account.+pub fn agent_signin_refused(harness: &str, kind: &str) -> Event {+ Event::new(event::AGENT_SIGNIN_REFUSED)+ .s("harness", pick(schema::SIGNIN_HARNESSES, harness, "other"))+ .s("reason", pick(schema::SIGNIN_REFUSALS, kind, "other"))}/// `cua_repo_cache`: what the repo cache did for one clone. Only fixed wordsdiff --git a/libs/cua/crates/cua-telemetry/src/schema.rs b/libs/cua/crates/cua-telemetry/src/schema.rsindex 40cad503b7..d280df1ea9 100644--- a/libs/cua/crates/cua-telemetry/src/schema.rs+++ b/libs/cua/crates/cua-telemetry/src/schema.rs@@ -739,6 +739,17 @@ pub const JOIN_TOOLS: &[&str] = &[/// Agents whose sign-in Connect copies into Keyvault on This Mac/// (`cua-agent-setup` ids), or `other`.pub const SIGNIN_HARNESSES: &[&str] = &["hermes", "claude-code", "codex", "other"];+/// How a copied sign-in was made: read from Claude Code's own sign-in (its+/// Keychain item or its credentials file), a device code, a pasted token.+pub const SIGNIN_VIAS: &[&str] = &[+ "claude_login_keychain",+ "claude_login_file",+ "device_code",+ "token",+ "other",+];+/// Why Connect did not copy a sign-in (`cua-agent-setup`'s refusal kinds).+pub const SIGNIN_REFUSALS: &[&str] = &["not_signed_in", "cancelled", "not_yet", "failed", "other"];/// Where an agent run was started from: a Spaces tool call (the MCP/// `agent_start`, the SDKs' `Space.agent_start`, the Spaces app), the/// `cua agent` CLI, the SDKs' sandbox `Agents.run`, a persistent agent's@@ -975,6 +986,7 @@ pub mod event {pub const INSTALLER_STEP: &str = "cua_installer_step";pub const AGENT_USED_SPACE: &str = "cua_agent_used_space";pub const AGENT_SIGNIN_IMPORTED: &str = "cua_agent_signin_imported";+ pub const AGENT_SIGNIN_REFUSED: &str = "cua_agent_signin_refused";pub const PLAN_LIMIT_SHOWN: &str = "cua_plan_limit_shown";pub const UPGRADE_LINK_OPENED: &str = "cua_upgrade_link_opened";}@@ -1271,16 +1283,43 @@ pub const EVENTS: &[EventSpec] = &[},EventSpec {name: event::AGENT_SIGNIN_IMPORTED,+ version: 2,+ tier: Tier::Usage,+ sample_rate: 1.0,+ products: ALL,+ props: &[+ p(+ "harness",+ Kind::Enum(SIGNIN_HARNESSES),+ "The agent whose sign-in Connect copied into Keyvault on This Mac. Never the sign-in, the account or the provider.",+ ),+ p(+ "via",+ Kind::Enum(SIGNIN_VIAS),+ "How it was made: read from Claude Code's own sign-in (Keychain or file), a device code, or a pasted token. Never the account.",+ ),+ ],+ purpose: "One-click Connect: how often an agent's sign-in is copied, per agent and way.",+ },+ EventSpec {+ name: event::AGENT_SIGNIN_REFUSED,version: 1,tier: Tier::Usage,sample_rate: 1.0,products: ALL,- props: &[p(- "harness",- Kind::Enum(SIGNIN_HARNESSES),- "The agent whose sign-in Connect copied into Keyvault on This Mac. Never the sign-in, the account or the provider.",- )],- purpose: "One-click Connect: how often an agent's sign-in is copied, per agent.",+ props: &[+ p(+ "harness",+ Kind::Enum(SIGNIN_HARNESSES),+ "The agent whose sign-in Connect could not copy.",+ ),+ p(+ "reason",+ Kind::Enum(SIGNIN_REFUSALS),+ "Why: not signed in, cancelled, not supported yet, or failed. Never the error text or the account.",+ ),+ ],+ purpose: "One-click Connect: how often importing a sign-in fails, and why, so the import can be made to work for more people.",},EventSpec {name: event::AGENT_RUN_STARTED,diff --git a/libs/cua/crates/cua-telemetry/tests/privacy.rs b/libs/cua/crates/cua-telemetry/tests/privacy.rsindex 8fd9b70c4c..286a088eb8 100644--- a/libs/cua/crates/cua-telemetry/tests/privacy.rs+++ b/libs/cua/crates/cua-telemetry/tests/privacy.rs@@ -306,6 +306,14 @@ fn all_builders(s: &str) -> Vec<Event> {).is_none());+ v.push(events::agent_signin_imported("codex", Some("device-code")));+ v.push(events::agent_signin_imported(+ "claude-code",+ Some("claude-login-keychain"),+ ));+ v.push(events::agent_signin_imported(s, Some(s)));+ v.push(events::agent_signin_refused("claude-code", "not_signed_in"));+ v.push(events::agent_signin_refused(s, s));v.push(events::repo_cache("hit", "local", 80_000_000, 4, "none").unwrap());v.push(events::repo_cache("fallback", "network", 0, 0, "verify_failed").unwrap());v.push(@@ -319,8 +327,6 @@ fn all_builders(s: &str) -> Vec<Event> {.unwrap(),);assert!(events::repo_cache("https://github.com/o/r", "local", 0, 0, "none").is_none());- v.push(events::agent_signin_imported("codex"));- v.push(events::agent_signin_imported(s));v.push(events::agent_used_space("space_bash").unwrap());v.push(events::agent_used_space("computer_click").unwrap());assert!(events::installer_step(s, "cli", "network", "sh", &[]).is_none());diff --git a/libs/cua/kotlin/src/main/kotlin/ai/cua/sdk/cua_sdk.kt b/libs/cua/kotlin/src/main/kotlin/ai/cua/sdk/cua_sdk.ktindex b3f7302b42..756f7ed9b8 100644--- a/libs/cua/kotlin/src/main/kotlin/ai/cua/sdk/cua_sdk.kt+++ b/libs/cua/kotlin/src/main/kotlin/ai/cua/sdk/cua_sdk.kt@@ -3280,7 +3280,7 @@ private fun uniffiCheckApiChecksums(lib: IntegrityCheckingUniffiLib) {if (lib.uniffi_cua_sdk_checksum_method_agentsetup_configure_mcp() != 53713.toShort()) {throw RuntimeException("UniFFI API checksum mismatch: try cleaning and rebuilding your project")}- if (lib.uniffi_cua_sdk_checksum_method_agentsetup_connect_json() != 32481.toShort()) {+ if (lib.uniffi_cua_sdk_checksum_method_agentsetup_connect_json() != 21138.toShort()) {throw RuntimeException("UniFFI API checksum mismatch: try cleaning and rebuilding your project")}if (lib.uniffi_cua_sdk_checksum_method_agentsetup_connection_status_json() != 47692.toShort()) {@@ -5737,8 +5737,9 @@ public interface AgentSetupInterface {/*** Connect (and Reconnect) for `agents`: Cua's skills and MCP entry* (`server`, default this channel's cua), and with `sign_in` the- * agent's sign-in copied into Keyvault on This Mac (Claude Code waits- * for its one browser approval). JSON: one result per agent.+ * agent's sign-in copied into Keyvault on This Mac (Claude Code's is the+ * sign-in it already has, read from where Claude Code keeps it). JSON:+ * one result per agent.*/suspend fun `connectJson`(`agents`: List<kotlin.String>, `server`: AgentMcpServer?, `skills`: kotlin.Boolean, `mcp`: kotlin.Boolean, `signIn`: kotlin.Boolean): kotlin.String@@ -5971,8 +5972,9 @@ open class AgentSetup: Disposable, AutoCloseable, AgentSetupInterface/*** Connect (and Reconnect) for `agents`: Cua's skills and MCP entry* (`server`, default this channel's cua), and with `sign_in` the- * agent's sign-in copied into Keyvault on This Mac (Claude Code waits- * for its one browser approval). JSON: one result per agent.+ * agent's sign-in copied into Keyvault on This Mac (Claude Code's is the+ * sign-in it already has, read from where Claude Code keeps it). JSON:+ * one result per agent.*/@Throws(CuaException::class)@Suppress("ASSIGNED_BUT_NEVER_ACCESSED_VARIABLE")diff --git a/libs/cua/python/src/cua/_native.py b/libs/cua/python/src/cua/_native.pyindex 839a084c27..d610a1828e 100644--- a/libs/cua/python/src/cua/_native.py+++ b/libs/cua/python/src/cua/_native.py@@ -615,7 +615,7 @@ def _uniffi_check_api_checksums(lib):raise InternalError("UniFFI API checksum mismatch: try cleaning and rebuilding your project")if lib.uniffi_cua_sdk_checksum_method_agentsetup_configure_mcp() != 53713:raise InternalError("UniFFI API checksum mismatch: try cleaning and rebuilding your project")- if lib.uniffi_cua_sdk_checksum_method_agentsetup_connect_json() != 32481:+ if lib.uniffi_cua_sdk_checksum_method_agentsetup_connect_json() != 21138:raise InternalError("UniFFI API checksum mismatch: try cleaning and rebuilding your project")if lib.uniffi_cua_sdk_checksum_method_agentsetup_connection_status_json() != 47692:raise InternalError("UniFFI API checksum mismatch: try cleaning and rebuilding your project")@@ -29971,8 +29971,9 @@ class AgentSetupProtocol(typing.Protocol):"""Connect (and Reconnect) for `agents`: Cua's skills and MCP entry(`server`, default this channel's cua), and with `sign_in` the- agent's sign-in copied into Keyvault on This Mac (Claude Code waits- for its one browser approval). JSON: one result per agent.+ agent's sign-in copied into Keyvault on This Mac (Claude Code's is the+ sign-in it already has, read from where Claude Code keeps it). JSON:+ one result per agent."""raise NotImplementedErrordef connection_status_json(self, expected: typing.Optional[AgentMcpServer],refresh: bool) -> str:@@ -30136,8 +30137,9 @@ class AgentSetup(AgentSetupProtocol):"""Connect (and Reconnect) for `agents`: Cua's skills and MCP entry(`server`, default this channel's cua), and with `sign_in` the- agent's sign-in copied into Keyvault on This Mac (Claude Code waits- for its one browser approval). JSON: one result per agent.+ agent's sign-in copied into Keyvault on This Mac (Claude Code's is the+ sign-in it already has, read from where Claude Code keeps it). JSON:+ one result per agent."""_UniffiFfiConverterSequenceString.check_lower(agents)diff --git a/libs/cua/swift/Sources/CuaSDK/CuaSDK.swift b/libs/cua/swift/Sources/CuaSDK/CuaSDK.swiftindex 9e10af10a9..91694388b1 100644--- a/libs/cua/swift/Sources/CuaSDK/CuaSDK.swift+++ b/libs/cua/swift/Sources/CuaSDK/CuaSDK.swift@@ -988,8 +988,9 @@ public protocol AgentSetupProtocol: AnyObject, Sendable {/*** Connect (and Reconnect) for `agents`: Cua's skills and MCP entry* (`server`, default this channel's cua), and with `sign_in` the- * agent's sign-in copied into Keyvault on This Mac (Claude Code waits- * for its one browser approval). JSON: one result per agent.+ * agent's sign-in copied into Keyvault on This Mac (Claude Code's is the+ * sign-in it already has, read from where Claude Code keeps it). JSON:+ * one result per agent.*/func connectJson(agents: [String], server: AgentMcpServer?, skills: Bool, mcp: Bool, signIn: Bool) async throws -> String@@ -1172,8 +1173,9 @@ open func configureMcp(agents: [String], server: AgentMcpServer?)async throws -/*** Connect (and Reconnect) for `agents`: Cua's skills and MCP entry* (`server`, default this channel's cua), and with `sign_in` the- * agent's sign-in copied into Keyvault on This Mac (Claude Code waits- * for its one browser approval). JSON: one result per agent.+ * agent's sign-in copied into Keyvault on This Mac (Claude Code's is the+ * sign-in it already has, read from where Claude Code keeps it). JSON:+ * one result per agent.*/open func connectJson(agents: [String], server: AgentMcpServer?, skills: Bool, mcp: Bool, signIn: Bool)async throws -> String {return@@ -51507,7 +51509,7 @@ private let initializationResult: InitializationResult = {if (uniffi_cua_sdk_checksum_method_agentsetup_configure_mcp() != 53713) {return InitializationResult.apiChecksumMismatch}- if (uniffi_cua_sdk_checksum_method_agentsetup_connect_json() != 32481) {+ if (uniffi_cua_sdk_checksum_method_agentsetup_connect_json() != 21138) {return InitializationResult.apiChecksumMismatch}if (uniffi_cua_sdk_checksum_method_agentsetup_connection_status_json() != 47692) {diff --git a/libs/cua/typescript/src/native/cua_sdk.ts b/libs/cua/typescript/src/native/cua_sdk.tsindex ba1bfc985e..ee84d72a64 100644--- a/libs/cua/typescript/src/native/cua_sdk.ts+++ b/libs/cua/typescript/src/native/cua_sdk.ts@@ -25953,8 +25953,9 @@ export interface AgentSetupLike {/*** Connect (and Reconnect) for `agents`: Cua's skills and MCP entry* (`server`, default this channel's cua), and with `sign_in` the- * agent's sign-in copied into Keyvault on This Mac (Claude Code waits- * for its one browser approval). JSON: one result per agent.+ * agent's sign-in copied into Keyvault on This Mac (Claude Code's is the+ * sign-in it already has, read from where Claude Code keeps it). JSON:+ * one result per agent.*/connectJson(agents: Array<string>, server: AgentMcpServer | undefined, skills: boolean, mcp: boolean, signIn: boolean, asyncOpts_?: { signal: AbortSignal }) /*throws*/: Promise<string>;/**@@ -26103,8 +26104,9 @@ private constructor(pointer: UniffiHandle) {/*** Connect (and Reconnect) for `agents`: Cua's skills and MCP entry* (`server`, default this channel's cua), and with `sign_in` the- * agent's sign-in copied into Keyvault on This Mac (Claude Code waits- * for its one browser approval). JSON: one result per agent.+ * agent's sign-in copied into Keyvault on This Mac (Claude Code's is the+ * sign-in it already has, read from where Claude Code keeps it). JSON:+ * one result per agent.*/async connectJson(agents: Array<string>, server: AgentMcpServer | undefined, skills: boolean, mcp: boolean, signIn: boolean, asyncOpts_?: { signal: AbortSignal }): Promise<string> /*throws*/ {const __stack = uniffiIsDebug ? new Error().stack : undefined;@@ -46847,7 +46849,7 @@ function uniffiEnsureInitialized() {if (nativeModule().uniffi_cua_sdk_checksum_method_agentsetup_configure_mcp() !== 53713) {throw new UniffiInternalError.ApiChecksumMismatch("uniffi_cua_sdk_checksum_method_agentsetup_configure_mcp");}- if (nativeModule().uniffi_cua_sdk_checksum_method_agentsetup_connect_json() !== 32481) {+ if (nativeModule().uniffi_cua_sdk_checksum_method_agentsetup_connect_json() !== 21138) {throw new UniffiInternalError.ApiChecksumMismatch("uniffi_cua_sdk_checksum_method_agentsetup_connect_json");}if (nativeModule().uniffi_cua_sdk_checksum_method_agentsetup_connection_status_json() !== 47692) {diff --git a/libs/spaces-app-swift/Sources/CuaSpacesFFI/CuaSpacesFFI.swift b/libs/spaces-app-swift/Sources/CuaSpacesFFI/CuaSpacesFFI.swiftindex 0fb99fca5a..b59dfdb897 100644--- a/libs/spaces-app-swift/Sources/CuaSpacesFFI/CuaSpacesFFI.swift+++ b/libs/spaces-app-swift/Sources/CuaSpacesFFI/CuaSpacesFFI.swift@@ -4435,6 +4435,10 @@ public struct AppAgentKeyInput: Equatable, Hashable {* A sign-in past its expiry: not used by any run until reconnected.*/public var expired: Bool+ /**+ * A copied sign-in's name ("Signed in as [email protected] (Claude Max)").+ */+ public var label: String?// Default memberwise initializers are never public by default, so we// declare one manually.@@ -4453,12 +4457,16 @@ public struct AppAgentKeyInput: Equatable, Hashable {*/addedMs: UInt64,/*** A sign-in past its expiry: not used by any run until reconnected.- */expired: Bool) {+ */expired: Bool,+ /**+ * A copied sign-in's name ("Signed in as [email protected] (Claude Max)").+ */label: String?) {self.provider = providerself.env = envself.last4 = last4self.addedMs = addedMsself.expired = expired+ self.label = label}@@ -4481,7 +4489,8 @@ public struct FfiConverterTypeAppAgentKeyInput: FfiConverterRustBuffer {env: FfiConverterString.read(from: &buf),last4: FfiConverterString.read(from: &buf),addedMs: FfiConverterUInt64.read(from: &buf),- expired: FfiConverterBool.read(from: &buf)+ expired: FfiConverterBool.read(from: &buf),+ label: FfiConverterOptionString.read(from: &buf))}@@ -4491,6 +4500,7 @@ public struct FfiConverterTypeAppAgentKeyInput: FfiConverterRustBuffer {FfiConverterString.write(value.last4, into: &buf)FfiConverterUInt64.write(value.addedMs, into: &buf)FfiConverterBool.write(value.expired, into: &buf)+ FfiConverterOptionString.write(value.label, into: &buf)}}diff --git a/scripts/docs-generators/cli-specs/cua.json b/scripts/docs-generators/cli-specs/cua.jsonindex a82d360910..c6aa6d9afa 100644--- a/scripts/docs-generators/cli-specs/cua.json+++ b/scripts/docs-generators/cli-specs/cua.json@@ -388,7 +388,7 @@},{"abstract": "Install the default cua skills and configure the cua MCP server",- "after_help": "Examples:\n # Every installed agent, asking before each change\n cua connect setup\n # Claude Code and Codex, no prompts\n cua connect setup --agents claude,codex -y\n # Hermes Agent (Nous Research): ~/.hermes/skills and ~/.hermes/config.yaml\n cua connect setup --agents hermes -y\n # Only the MCP server entry\n cua connect setup --mcp-only\n # Background computer-use: the cua-driver skill and MCP server\n cua connect setup --cua-driver --agents all -y\n # Also copy each agent's sign-in to Keyvault on This Mac (Codex's\n # ChatGPT sign-in, Claude Code's `claude setup-token`, Hermes' key)\n cua connect setup --agents codex,claude --sign-in -y",+ "after_help": "Examples:\n # Every installed agent, asking before each change\n cua connect setup\n # Claude Code and Codex, no prompts\n cua connect setup --agents claude,codex -y\n # Hermes Agent (Nous Research): ~/.hermes/skills and ~/.hermes/config.yaml\n cua connect setup --agents hermes -y\n # Only the MCP server entry\n cua connect setup --mcp-only\n # Background computer-use: the cua-driver skill and MCP server\n cua connect setup --cua-driver --agents all -y\n # Also copy each agent's sign-in to Keyvault on This Mac (Codex's\n # ChatGPT sign-in, the sign-in Claude Code already has, Hermes' key)\n cua connect setup --agents codex,claude --sign-in -y","aliases": [],"arguments": [],"flags": [@@ -455,7 +455,7 @@"aliases": [],"default_value": false,"env": null,- "help": "Also make a sign-in for each agent's runs in your Spaces and keep it in Keyvault on This Mac: Claude Code's `claude setup-token` (one browser approval) and Codex's own device sign-in (a link and a code to enter there, in a folder Cua owns); Hermes uses the providers connected in Cua Spaces (Settings, Connectors). The agent's own sign-in files are never read or changed",+ "help": "Also make a sign-in for each agent's runs in your Spaces and keep it in Keyvault on This Mac: the sign-in Claude Code already has (read from where Claude Code keeps it, as an access token only; Claude Code's own sign-in is never changed) and Codex's own device sign-in (a link and a code to enter there, in a folder Cua owns); Hermes uses the providers connected in Cua Spaces (Settings, Connectors). Only Claude Code's own sign-in is read, and only its access token is kept; Codex's own `auth.json` is never read or changed","hidden": false,"name": "sign-in","repeatable": false,@@ -662,7 +662,7 @@},{"abstract": "Install the default cua skills and configure the cua MCP server",- "after_help": "Examples:\n # Every installed agent, asking before each change\n cua connect setup\n # Claude Code and Codex, no prompts\n cua connect setup --agents claude,codex -y\n # Hermes Agent (Nous Research): ~/.hermes/skills and ~/.hermes/config.yaml\n cua connect setup --agents hermes -y\n # Only the MCP server entry\n cua connect setup --mcp-only\n # Background computer-use: the cua-driver skill and MCP server\n cua connect setup --cua-driver --agents all -y\n # Also copy each agent's sign-in to Keyvault on This Mac (Codex's\n # ChatGPT sign-in, Claude Code's `claude setup-token`, Hermes' key)\n cua connect setup --agents codex,claude --sign-in -y",+ "after_help": "Examples:\n # Every installed agent, asking before each change\n cua connect setup\n # Claude Code and Codex, no prompts\n cua connect setup --agents claude,codex -y\n # Hermes Agent (Nous Research): ~/.hermes/skills and ~/.hermes/config.yaml\n cua connect setup --agents hermes -y\n # Only the MCP server entry\n cua connect setup --mcp-only\n # Background computer-use: the cua-driver skill and MCP server\n cua connect setup --cua-driver --agents all -y\n # Also copy each agent's sign-in to Keyvault on This Mac (Codex's\n # ChatGPT sign-in, the sign-in Claude Code already has, Hermes' key)\n cua connect setup --agents codex,claude --sign-in -y","aliases": [],"arguments": [],"flags": [@@ -729,7 +729,7 @@"aliases": [],"default_value": false,"env": null,- "help": "Also make a sign-in for each agent's runs in your Spaces and keep it in Keyvault on This Mac: Claude Code's `claude setup-token` (one browser approval) and Codex's own device sign-in (a link and a code to enter there, in a folder Cua owns); Hermes uses the providers connected in Cua Spaces (Settings, Connectors). The agent's own sign-in files are never read or changed",+ "help": "Also make a sign-in for each agent's runs in your Spaces and keep it in Keyvault on This Mac: the sign-in Claude Code already has (read from where Claude Code keeps it, as an access token only; Claude Code's own sign-in is never changed) and Codex's own device sign-in (a link and a code to enter there, in a folder Cua owns); Hermes uses the providers connected in Cua Spaces (Settings, Connectors). Only Claude Code's own sign-in is read, and only its access token is kept; Codex's own `auth.json` is never read or changed","hidden": false,"name": "sign-in","repeatable": false,