Skip to content

armgit / cua

Public Imported from GitHub
0

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

Spaces: opt-in diagnostic report on a failed create, sent privately to [email protected] (#5406)

Francesco Bonacciba755cbee885
diff --git a/apps/cua-spaces-desktop/src/external-url.ts b/apps/cua-spaces-desktop/src/external-url.ts
new file mode 100644
index 0000000000..77fa1b4a81
--- /dev/null
+++ b/apps/cua-spaces-desktop/src/external-url.ts
@@ -0,0 +1,13 @@
+// SPDX-License-Identifier: FSL-1.1-MIT
+// Copyright (c) 2026 Cua AI, Inc.
+
+/**
+ * What a link or `window.open` in the app may hand to the OS: a web page, or
+ * the diagnostic report's email to Cua support (a `mailto:` to that one
+ * address, subject and body only). Anything else stays closed.
+ */
+const SUPPORT_MAILTO = /^mailto:support@trycua\.com(\?((subject|body)=[A-Za-z0-9\-._~%]*)(&(subject|body)=[A-Za-z0-9\-._~%]*)*)?$/;
+
+export function opensOutside(url: string): boolean {
+ return /^https?:\/\//.test(url) || SUPPORT_MAILTO.test(url);
+}
diff --git a/apps/cua-spaces-desktop/src/window.ts b/apps/cua-spaces-desktop/src/window.ts
index e95d7826e2..9c35737e86 100644
--- a/apps/cua-spaces-desktop/src/window.ts
+++ b/apps/cua-spaces-desktop/src/window.ts
@@ -5,6 +5,7 @@ import { app, BrowserWindow, ipcMain, screen, shell, type BrowserWindowConstruct
import { existsSync, writeFileSync } from "node:fs";
import * as path from "node:path";
import { captureRoutes } from "./capture";
+import { opensOutside } from "./external-url";
import { windowIconPath } from "./icon";
import { APP_ORIGIN } from "./protocol";
import { readSettings, writeSettings, type WindowBounds } from "./settings";
@@ -194,13 +195,13 @@ export function appWindow(options: BrowserWindowConstructorOptions): BrowserWind
});
syncTitlebarInset(win);
win.webContents.setWindowOpenHandler(({ url }) => {
- if (/^https?:\/\//.test(url)) void shell.openExternal(url);
+ if (opensOutside(url)) void shell.openExternal(url);
return { action: "deny" };
});
win.webContents.on("will-navigate", (event, url) => {
if (!url.startsWith(`${APP_ORIGIN}/`)) {
event.preventDefault();
- if (/^https?:\/\//.test(url)) void shell.openExternal(url);
+ if (opensOutside(url)) void shell.openExternal(url);
}
});
return win;
diff --git a/apps/cua-spaces-desktop/test/external-url.test.ts b/apps/cua-spaces-desktop/test/external-url.test.ts
new file mode 100644
index 0000000000..d3317a308a
--- /dev/null
+++ b/apps/cua-spaces-desktop/test/external-url.test.ts
@@ -0,0 +1,34 @@
+// SPDX-License-Identifier: FSL-1.1-MIT
+// Copyright (c) 2026 Cua AI, Inc.
+
+import { describe, expect, it } from "vitest";
+import { opensOutside } from "../src/external-url";
+
+describe("what the app opens outside itself", () => {
+ it("opens web pages and the diagnostic report's email to Cua support", () => {
+ for (const url of [
+ "https://cua.ai/pricing",
+ "http://localhost:8080/x",
+ "mailto:[email protected]",
+ "mailto:[email protected]?subject=Spaces%3A%20create%20failed&body=a%0D%0Ab",
+ ]) {
+ expect(opensOutside(url), url).toBe(true);
+ }
+ });
+
+ it("keeps everything else closed, including mail to anyone else", () => {
+ for (const url of [
+ "",
+ "file:///etc/passwd",
+ "javascript:alert(1)",
+ "mailto:[email protected]?subject=x",
+ "mailto:[email protected]",
+ "mailto:[email protected]?subject=a b",
+ ]) {
+ expect(opensOutside(url), url).toBe(false);
+ }
+ });
+});
diff --git a/apps/cua-spaces-web/src/__tests__/diagnostic-report.test.tsx b/apps/cua-spaces-web/src/__tests__/diagnostic-report.test.tsx
new file mode 100644
index 0000000000..d28f4ca51d
--- /dev/null
+++ b/apps/cua-spaces-web/src/__tests__/diagnostic-report.test.tsx
@@ -0,0 +1,64 @@
+// SPDX-License-Identifier: FSL-1.1-MIT
+// Copyright (c) 2026 Cua AI, Inc.
+
+// "Send a report…" on a failed create: the review sheet shows the core's
+// redacted report, each part can be edited or left out, and nothing leaves
+// until the person presses Send in their mail app. Open email prefills an
+// email to Cua support with only the kept parts.
+
+import { act, cleanup, fireEvent, screen, waitFor } from "@testing-library/react";
+import { afterEach, describe, expect, it } from "vitest";
+import { wasmBuilt } from "@/bridge/__tests__/testCore";
+import { NAME, mountApp, stubBrowserApis } from "./app-harness";
+
+afterEach(cleanup);
+stubBrowserApis();
+
+describe.skipIf(!wasmBuilt)("the diagnostic report for a failed create (real routes, wasm core)", () => {
+ it("sends nothing until Open email, and then only the kept parts, redacted", async () => {
+ const opened: string[] = [];
+ const { router, hooks } = await mountApp("/spaces", {
+ failsCreates: true,
+ listsGhost: false,
+ intercept: (op, args) => {
+ if (op !== "session.openExternal") return undefined;
+ opened.push((args as { url: string }).url);
+ return null;
+ },
+ });
+ await waitFor(() => expect(hooks.machines.data?.some((m) => m.id === "mac-mini")).toBe(true));
+ await act(async () => {
+ await hooks.spaces.createSpace({ image: "ghcr.io/trycua/macos:26", os: "macos", on: "host:mac-mini", name: NAME }).catch(() => {});
+ });
+ const failed = hooks.spaces.data!.find((s) => s.name === NAME && s.id.startsWith("pending:"))!;
+ await act(() => router.navigate({ to: "/spaces/$spaceId", params: { spaceId: failed.id } }));
+
+ fireEvent.click(await screen.findByRole("button", { name: "Send a report…" }));
+ const error = (await screen.findByRole("textbox", { name: "Error" })) as HTMLTextAreaElement;
+ expect(error.value).toContain("Local Network access is not available");
+ expect((screen.getByRole("textbox", { name: "What was created" }) as HTMLTextAreaElement).value).toContain("Failure kind: local_network");
+ expect(opened).toEqual([]);
+ // One "Send" in the sheet's copy: the one in the mail app.
+ const sheet = document.querySelector("[data-diagnostic-report]")!;
+ expect(sheet.textContent).toContain("press Send there");
+ expect(screen.queryByRole("button", { name: "Send" })).toBeNull();
+
+ // Leave the app and system out, and paste a secret into the error.
+ fireEvent.click(screen.getByRole("checkbox", { name: /^Include App and system/ }));
+ // A fake token, split so secret scanners don't flag the source.
+ const fake = "gh" + "p_abcdefghijklmnopqrstuvwxyz0123456789";
+ fireEvent.change(error, { target: { value: `${error.value}\ntoken=${fake} from [email protected]` } });
+ fireEvent.click(screen.getByRole("button", { name: "Open email" }));
+
+ await waitFor(() => expect(opened).toHaveLength(1));
+ const link = opened[0]!;
+ expect(link.startsWith("mailto:[email protected]?subject=")).toBe(true);
+ expect(link).not.toContain("github");
+ expect(link).not.toContain("ghp_");
+ expect(link).not.toContain("maya");
+ const body = decodeURIComponent(new URLSearchParams(link.split("?")[1]).get("body") ?? "");
+ expect(body).toContain("Local Network access is not available");
+ expect(body).not.toContain("App and system");
+ expect(link.length).toBeLessThan(2100);
+ });
+});
diff --git a/apps/cua-spaces-web/src/bridge/diagnostic-report.ts b/apps/cua-spaces-web/src/bridge/diagnostic-report.ts
new file mode 100644
index 0000000000..5cdfeb2b2e
--- /dev/null
+++ b/apps/cua-spaces-web/src/bridge/diagnostic-report.ts
@@ -0,0 +1,58 @@
+// SPDX-License-Identifier: FSL-1.1-MIT
+// Copyright (c) 2026 Cua AI, Inc.
+
+// The opt-in diagnostic report for a failed create (the app core's
+// `diagnostics` module). The core builds and redacts it; the review sheet
+// lets the person edit or leave out each part; Send opens a prefilled email
+// to Cua support in their mail app with what they kept. Reports are private:
+// nothing is sent before they press Send there, and it goes only to support.
+
+import type { CoreClient } from "./core";
+import type { AboutInput } from "./contracts/settings";
+
+/** What the page knows about one failed create (`CreateReportInput`). */
+export interface CreateReportInput {
+ error: string;
+ shown?: string | null;
+ phase: string;
+ os: string;
+ provider: string;
+ kind?: string | null;
+ image?: string | null;
+ gpu: boolean;
+ elapsedMs?: number | null;
+ about?: AboutInput | null;
+ names: string[];
+}
+
+/** One part the person can edit or leave out. */
+export interface ReportPart {
+ id: string;
+ label: string;
+ text: string;
+}
+
+/** The review sheet (`CreateReport`). */
+export interface CreateReport {
+ title: string;
+ intro: string;
+ subject: string;
+ parts: ReportPart[];
+ sendLabel: string;
+ errorKind: string;
+}
+
+/** The parts the person kept, as they edited them. */
+export interface ReportSend {
+ subject: string;
+ parts: ReportPart[];
+}
+
+type Json = Parameters<CoreClient["tryCall"]>[1];
+
+export const createReport = (core: CoreClient, input: CreateReportInput): CreateReport | null =>
+ core.tryCall<CreateReport>("diagnostics.createReport", { input } as unknown as Json) ?? null;
+
+/** The `mailto:` link to Cua support with the kept parts, redacted again. */
+export const reportMailto = (core: CoreClient, send: ReportSend, names: string[]): string | null =>
+ core.tryCall<string>("diagnostics.reportMailto", { send, names } as unknown as Json) ?? null;
diff --git a/apps/cua-spaces-web/src/bridge/hooks.ts b/apps/cua-spaces-web/src/bridge/hooks.ts
index 788e1e9965..4199cce420 100644
--- a/apps/cua-spaces-web/src/bridge/hooks.ts
+++ b/apps/cua-spaces-web/src/bridge/hooks.ts
@@ -48,6 +48,7 @@ import type {
SessionData,
SettingsData,
} from "./store";
+import type { CreateReport, ReportSend } from "./diagnostic-report";
function useBridgeContext(): BridgeContextValue {
const ctx = useContext(BridgeContext);
@@ -100,6 +101,11 @@ export interface SpacesHook extends Resource<Space[]> {
retryCreate(pendingId: string): string | undefined;
/** Whether Try again can run the failed create again. */
canRetryCreate(pendingId: string): boolean;
+ /** A failed create's diagnostic report, redacted, for the review sheet
+ * (null when there is none). Nothing is sent. */
+ createReport(pendingId: string): Promise<CreateReport | null>;
+ /** Send on the review sheet: opens an email to Cua support with the kept parts. */
+ sendCreateReport(send: ReportSend): Promise<void>;
startSpace(id: string): Promise<void>;
stopSpace(id: string): Promise<void>;
/** Deletes the Space, or with `removeOnly` only removes it from the list. */
@@ -126,6 +132,8 @@ export function useSpaces(): SpacesHook {
dismissCreate: (id) => run((s) => s.dismissCreate(id)),
retryCreate: (id) => (ctx.store?.canRetryCreate(id) ? ctx.store.retryCreate(id) : undefined),
canRetryCreate: (id) => ctx.store?.canRetryCreate(id) ?? false,
+ createReport: async (id) => (ctx.store ? ctx.store.createReport(id) : null),
+ sendCreateReport: (send) => run((s) => s.sendCreateReport(send)),
startSpace: (id) => run((s) => s.setPower(id, true)),
stopSpace: (id) => run((s) => s.setPower(id, false)),
deleteSpace: (id, removeOnly) => run((s) => s.deleteSpace(id, removeOnly)),
diff --git a/apps/cua-spaces-web/src/bridge/index.ts b/apps/cua-spaces-web/src/bridge/index.ts
index cac7851b4c..8d102a5a08 100644
--- a/apps/cua-spaces-web/src/bridge/index.ts
+++ b/apps/cua-spaces-web/src/bridge/index.ts
@@ -151,3 +151,4 @@ export {
type UpsellPrompt,
type UpsellSurface,
} from "./upsell";
+export type { CreateReport, ReportPart, ReportSend } from "./diagnostic-report";
diff --git a/apps/cua-spaces-web/src/bridge/store.ts b/apps/cua-spaces-web/src/bridge/store.ts
index 99e3447c57..5665d963e2 100644
--- a/apps/cua-spaces-web/src/bridge/store.ts
+++ b/apps/cua-spaces-web/src/bridge/store.ts
@@ -13,6 +13,8 @@ import { isUnsupported, type DataAdapter } from "./adapter";
import type { AgentRunStatus, AgentSetupRow, PersistentAgent, SpaceAgentRun } from "./contracts/agents";
import type { CoreClient } from "./core";
import { withCreateContext } from "./create-context";
+import { createReport, reportMailto, type CreateReport, type ReportSend } from "./diagnostic-report";
+import type { AboutInput } from "./contracts/settings";
import { passedSteps } from "./onboarding";
import type { MachineRow, OnboardingMode, SettingsPage, SignInPhase, SignInStart, SpaceCreateConfig, TelemetryView } from "./contracts/host";
import type { OnboardingAction, OnboardingFlowState } from "./contracts/onboarding";
@@ -572,6 +574,8 @@ export class BridgeStore {
return space;
} catch (e) {
const message = toError(e).message;
+ // The words it failed with, for a diagnostic report the person may send.
+ this.createFailures.set(pendingId, { error: message, at: this.now() });
if (message.startsWith("cancelled")) this.dispatch({ type: "cancel-done", id: pendingId });
// The failed row, and its one notification (`noteFailures`).
else this.dispatch({ type: "fail", id: pendingId, error: message });
@@ -580,6 +584,47 @@ export class BridgeStore {
}
}
+ /** Each failed create's error text and when it failed, by pending id. */
+ private readonly createFailures = new Map<string, { error: string; at: number }>();
+
+ /** Machine names a report hides (Bonjour names have no dots to find). */
+ private reportNames(): string[] {
+ const machines = (this.resources.machines.data as { name?: string }[] | undefined) ?? [];
+ return machines.map((m) => m.name ?? "").filter((n) => n.trim().length > 0);
+ }
+
+ /** The diagnostic report for a failed create, redacted by the core, for
+ * the review sheet. Null when the row is not a failed create. Builds the
+ * report only: nothing is sent. */
+ async createReport(pendingId: string): Promise<CreateReport | null> {
+ const p = this.creates.pending.find((c) => c.id === pendingId);
+ if (!p?.error) return null;
+ const failure = this.createFailures.get(pendingId);
+ const about = await this.adapter.call("about.get", {}).catch(() => null);
+ return createReport(this.core, {
+ error: failure?.error ?? p.error,
+ shown: p.error,
+ phase: p.phase,
+ os: p.os,
+ provider: p.provider,
+ kind: p.kind ?? null,
+ image: p.image ?? null,
+ gpu: Boolean(p.gpu),
+ elapsedMs: failure ? Math.max(0, failure.at - p.startedAt) : null,
+ about: (about as AboutInput | null) ?? null,
+ names: [...this.reportNames(), ...(p.hostName ? [p.hostName] : [])],
+ });
+ }
+
+ /** Send on the review sheet: opens a prefilled email to Cua support with
+ * the parts the person kept (redacted again) in their mail app, where they
+ * send it themselves. */
+ async sendCreateReport(send: ReportSend): Promise<void> {
+ const link = reportMailto(this.core, send, this.reportNames());
+ if (!link) throw new Error("The report could not be prepared. Try again.");
+ await this.openExternal(link);
+ }
+
async cancelCreate(pendingId: string): Promise<void> {
this.dispatch({ type: "cancel-start", id: pendingId });
try {
@@ -595,6 +640,7 @@ export class BridgeStore {
* pending id does that), so it doesn't come back as a ghost. */
async dismissCreate(pendingId: string): Promise<void> {
this.dispatch({ type: "dismiss", id: pendingId });
+ this.createFailures.delete(pendingId);
// A removed row is not followed to a Space it might still become.
this.createdIds.delete(pendingId);
await this.adapter.call("spaces.delete", { spaceId: pendingId }).catch(() => {});
diff --git a/apps/cua-spaces-web/src/components/diagnostic-report-dialog.tsx b/apps/cua-spaces-web/src/components/diagnostic-report-dialog.tsx
new file mode 100644
index 0000000000..1c5e756e81
--- /dev/null
+++ b/apps/cua-spaces-web/src/components/diagnostic-report-dialog.tsx
@@ -0,0 +1,123 @@
+// SPDX-License-Identifier: FSL-1.1-MIT
+// Copyright (c) 2026 Cua AI, Inc.
+
+import { useEffect, useLayoutEffect, useRef, useState, type ComponentProps } from "react";
+
+import type { CreateReport, ReportPart } from "@/bridge";
+import { Button } from "@/components/ui/button";
+import { Checkbox } from "@/components/ui/checkbox";
+import { Dialog, DialogDescription, DialogPopup, DialogTitle } from "@/components/ui/dialog";
+
+/** The tallest a part grows before it scrolls (matches `max-h-60`). */
+const TEXT_MAX_PX = 240;
+
+/** A textarea that grows to show every wrapped line, up to [`TEXT_MAX_PX`]
+ * (then it scrolls). Rows would count line breaks, not wrapped lines. */
+function FitTextarea({ value, ...props }: Omit<ComponentProps<"textarea">, "rows">) {
+ const ref = useRef<HTMLTextAreaElement>(null);
+ const fit = () => {
+ const el = ref.current;
+ if (!el) return;
+ el.style.height = "auto";
+ if (el.scrollHeight === 0) return;
+ const border = el.offsetHeight - el.clientHeight;
+ el.style.height = `${Math.min(el.scrollHeight + border, TEXT_MAX_PX)}px`;
+ };
+ useLayoutEffect(fit, [value]);
+ useEffect(() => {
+ window.addEventListener("resize", fit);
+ return () => window.removeEventListener("resize", fit);
+ }, []);
+ return <textarea ref={ref} rows={2} value={value} {...props} />;
+}
+
+/**
+ * The review sheet for a failed create's diagnostic report (standard
+ * crash-report pattern): the app core's redacted report, each part
+ * editable and kept by default, and nothing sent until the person presses
+ * Send in their mail app. Open email opens a message to Cua support there
+ * with the parts they kept.
+ */
+export function DiagnosticReportDialog({
+ open,
+ onOpenChange,
+ report,
+ onSend,
+}: {
+ open: boolean;
+ onOpenChange: (open: boolean) => void;
+ report: CreateReport | null;
+ onSend: (subject: string, parts: ReportPart[]) => Promise<void>;
+}) {
+ const [parts, setParts] = useState<(ReportPart & { kept: boolean })[]>([]);
+ const [busy, setBusy] = useState(false);
+ const [error, setError] = useState<string | null>(null);
+ useEffect(() => {
+ if (open && report) {
+ setParts(report.parts.map((p) => ({ ...p, kept: true })));
+ setError(null);
+ }
+ }, [open, report]);
+
+ const kept = parts.filter((p) => p.kept);
+ const send = async () => {
+ if (!report || kept.length === 0) return;
+ setBusy(true);
+ setError(null);
+ try {
+ await onSend(
+ report.subject,
+ kept.map(({ id, label, text }) => ({ id, label, text })),
+ );
+ onOpenChange(false);
+ } catch (e) {
+ setError(e instanceof Error ? e.message : String(e));
+ } finally {
+ setBusy(false);
+ }
+ };
+ const edit = (id: string, change: Partial<{ text: string; kept: boolean }>) =>
+ setParts((all) => all.map((p) => (p.id === id ? { ...p, ...change } : p)));
+
+ return (
+ <Dialog open={open} onOpenChange={(next) => (busy ? undefined : onOpenChange(next))}>
+ <DialogPopup className="top-[8vh] w-[min(600px,calc(100vw-2rem))]" data-diagnostic-report="">
+ <div className="px-6 pt-5 pb-4">
+ <DialogTitle className="text-[15px] font-semibold">{report?.title ?? "Send a diagnostic report"}</DialogTitle>
+ <DialogDescription className="mt-1 text-[13px] text-muted-foreground">{report?.intro}</DialogDescription>
+ <div className="mt-4 flex max-h-[55vh] flex-col gap-4 overflow-y-auto">
+ {parts.map((p) => (
+ <div key={p.id} data-report-part={p.id}>
+ <label className="flex items-center gap-2 text-[13px] font-medium">
+ <Checkbox checked={p.kept} onCheckedChange={(v) => edit(p.id, { kept: Boolean(v) })} aria-label={`Include ${p.label}`} />
+ {p.label}
+ </label>
+ <FitTextarea
+ aria-label={p.label}
+ className="mt-1.5 max-h-60 min-h-[4.5rem] w-full resize-y overflow-y-auto rounded-md border bg-background px-2.5 py-2 font-mono text-xs leading-relaxed disabled:opacity-50"
+ value={p.text}
+ disabled={!p.kept || busy}
+ spellCheck={false}
+ onChange={(e) => edit(p.id, { text: e.target.value })}
+ />
+ </div>
+ ))}
+ </div>
+ {error ? (
+ <p role="alert" className="mt-2 text-xs text-destructive">
+ {error}
+ </p>
+ ) : null}
+ <div className="mt-4 flex justify-end gap-2">
+ <Button variant="outline" disabled={busy} onClick={() => onOpenChange(false)}>
+ Cancel
+ </Button>
+ <Button data-report-send="" disabled={busy || !report || kept.length === 0} onClick={() => void send()}>
+ {report?.sendLabel ?? "Open email"}
+ </Button>
+ </div>
+ </div>
+ </DialogPopup>
+ </Dialog>
+ );
+}
diff --git a/apps/cua-spaces-web/src/routes/spaces/$spaceId.tsx b/apps/cua-spaces-web/src/routes/spaces/$spaceId.tsx
index 7c86989e56..1bf04fe9a6 100644
--- a/apps/cua-spaces-web/src/routes/spaces/$spaceId.tsx
+++ b/apps/cua-spaces-web/src/routes/spaces/$spaceId.tsx
@@ -5,7 +5,8 @@ import { createFileRoute, Link, useNavigate } from "@tanstack/react-router";
import { ArrowDownCircleIcon, ChevronLeftIcon, MonitorIcon, PictureInPicture2Icon, PlayIcon, SquareIcon, Trash2Icon, UserPlusIcon } from "lucide-react";
import { useEffect, useRef, useState, type ReactNode } from "react";
-import { parseDropped, useBridge, useDevices, useExperiments, useMachines, useSession, useShareSheet, useSpaceDetail, useSpaceFiles, useSpaces, useTeleport, type Space, type StreamRow } from "@/bridge";
+import { parseDropped, useBridge, useDevices, useExperiments, useMachines, useSession, useShareSheet, useSpaceDetail, useSpaceFiles, useSpaces, useTeleport, type CreateReport, type Space, type StreamRow } from "@/bridge";
+import { DiagnosticReportDialog } from "@/components/diagnostic-report-dialog";
import { OsIcon } from "@/components/os-icon";
import { EmptyState, Page } from "@/components/page";
import { AgentsSection } from "@/components/space-detail/agents-section";
@@ -38,8 +39,24 @@ function SpaceDetailPage() {
const { spaceId } = Route.useParams();
const { dropped } = Route.useSearch();
const navigate = useNavigate();
- const { data: spaces, isLoading, error, startSpace, stopSpace, deleteSpace, openSpace, dismissCreate, retryCreate, canRetryCreate, createdId } =
- useSpaces();
+ const {
+ data: spaces,
+ isLoading,
+ error,
+ startSpace,
+ stopSpace,
+ deleteSpace,
+ openSpace,
+ dismissCreate,
+ retryCreate,
+ canRetryCreate,
+ createdId,
+ createReport,
+ sendCreateReport,
+ } = useSpaces();
+ // The failed create's diagnostic report, while its review sheet is open.
+ const [report, setReport] = useState<CreateReport | null>(null);
+ const [reportOpen, setReportOpen] = useState(false);
const { data: machines = [] } = useMachines();
const [confirm, setConfirm] = useState<Confirm>(null);
const teleport = useTeleport();
@@ -155,6 +172,14 @@ function SpaceDetailPage() {
if (next) void navigate({ to: "/spaces/$spaceId", params: { spaceId: next }, replace: true });
}
: undefined;
+ // Send report: the review sheet with the core's redacted report; nothing
+ // is sent until the person presses Send there.
+ const openReport = () =>
+ void createReport(space.id).then((r) => {
+ if (!r) return;
+ setReport(r);
+ setReportOpen(true);
+ });
// Picture in picture where the host has panels; its own window where it doesn't.
const onPip = (row: StreamRow) =>
run("open", async () => {
@@ -254,7 +279,7 @@ function SpaceDetailPage() {
onAccessAction={enroll}
className="h-72"
>
- {surfaceState(space, pending, turnOn, start, dismiss, retry) ?? poppedOutState}
+ {surfaceState(space, pending, turnOn, start, dismiss, retry, openReport) ?? poppedOutState}
</StreamSurface>
)}
@@ -328,6 +353,12 @@ function SpaceDetailPage() {
onConfirm={() => remove()}
alternative={detail.confirm.removeLabel ? { label: detail.confirm.removeLabel, onClick: () => remove(true) } : null}
/>
+ <DiagnosticReportDialog
+ open={reportOpen}
+ onOpenChange={setReportOpen}
+ report={report}
+ onSend={(subject, parts) => sendCreateReport({ subject, parts })}
+ />
</Page>
);
}
@@ -387,7 +418,15 @@ function BackLink() {
/** What replaces the stream while there is no desktop to show: a create's
* progress, a delete, a stopped Space. Undefined: the stream surface. */
-function surfaceState(space: Space, pending: string | null, startLabel: string, onStart: () => void, onDismiss: () => void, onRetry?: () => void): ReactNode {
+function surfaceState(
+ space: Space,
+ pending: string | null,
+ startLabel: string,
+ onStart: () => void,
+ onDismiss: () => void,
+ onRetry?: () => void,
+ onReport?: () => void,
+): ReactNode {
const state = spaceState(space);
if (state === "failed") {
return (
@@ -396,11 +435,16 @@ function surfaceState(space: Space, pending: string | null, startLabel: string,
<p data-create-error="" className="mt-2 max-w-md text-center text-xs text-destructive">
{createError(space) || "No reason was reported."}
</p>
- <div className="mt-4 flex gap-2">
+ <div className="mt-4 flex flex-wrap justify-center gap-2">
{onRetry ? <Button onClick={onRetry}>Try again</Button> : null}
<Button variant="outline" onClick={onDismiss}>
Remove from list
</Button>
+ {onReport ? (
+ <Button variant="outline" data-send-report="" onClick={onReport}>
+ Send a report…
+ </Button>
+ ) : null}
</div>
</>
);
diff --git a/apps/cua-spaces/src-tauri/src/lib.rs b/apps/cua-spaces/src-tauri/src/lib.rs
index 714dd5071a..9addd60962 100644
--- a/apps/cua-spaces/src-tauri/src/lib.rs
+++ b/apps/cua-spaces/src-tauri/src/lib.rs
@@ -288,11 +288,17 @@ fn set_display_style(
}
/// Open an `http(s)` URL in the user's default browser (Settings "Sign in to
-/// Cua"). Restricted to web schemes so a webview call can never launch an
+/// Cua"), or the diagnostic report's email link to Cua support in the user's
+/// mail app. Restricted to those so a webview call can never launch an
/// arbitrary local handler, and it hands the URL to the OS opener as a single
/// argument (never a shell string) so nothing is interpreted by a shell.
#[tauri::command]
fn open_external(url: String) -> Result<(), String> {
+ if let Some(link) = checked_support_mailto(&url) {
+ // Not the link in the message: it carries the report.
+ return open_with_os(link)
+ .map_err(|error| format!("failed to open your mail app: {error}"));
+ }
open_web_url(&url)
}
@@ -304,6 +310,11 @@ fn open_external(url: String) -> Result<(), String> {
/// shell.
pub(crate) fn open_web_url(url: &str) -> Result<(), String> {
let url = checked_web_url(url)?;
+ open_with_os(url).map_err(|error| format!("failed to open {url}: {error}"))
+}
+
+/// Hands an already checked `url` to the OS opener as one argument.
+fn open_with_os(url: &str) -> std::io::Result<()> {
#[cfg(target_os = "macos")]
let mut command = {
let mut c = std::process::Command::new("open");
@@ -324,10 +335,16 @@ pub(crate) fn open_web_url(url: &str) -> Result<(), String> {
c.arg(url);
c
};
- command
- .spawn()
- .map(|_| ())
- .map_err(|error| format!("failed to open {url}: {error}"))
+ command.spawn().map(|_| ())
+}
+
+/// The first character of `url` that a real URL percent-encodes: anything but
+/// printable ASCII, and quotes, backslashes, angle brackets, carets, pipes,
+/// backticks and braces.
+fn unencoded_char(url: &str) -> Option<char> {
+ url.chars().find(|c| {
+ !c.is_ascii_graphic() || matches!(c, '"' | '\\' | '<' | '>' | '^' | '|' | '`' | '{' | '}')
+ })
}
/// The URL `open_web_url` hands to the OS opener: an `http(s)` URL with a
@@ -344,9 +361,7 @@ fn checked_web_url(url: &str) -> Result<&str, String> {
if host.is_empty() {
return Err("the URL has no host".to_string());
}
- if let Some(bad) = trimmed.chars().find(|c| {
- !c.is_ascii_graphic() || matches!(c, '"' | '\\' | '<' | '>' | '^' | '|' | '`' | '{' | '}')
- }) {
+ if let Some(bad) = unencoded_char(trimmed) {
return Err(format!(
"the URL contains a character that must be percent-encoded ({:?})",
bad
@@ -355,6 +370,24 @@ fn checked_web_url(url: &str) -> Result<&str, String> {
Ok(trimmed)
}
+/// The diagnostic report's link: a `mailto:` to Cua support (and nobody else)
+/// with a percent-encoded subject and body. Nothing else with that scheme
+/// opens.
+fn checked_support_mailto(url: &str) -> Option<&str> {
+ let trimmed = url.trim();
+ let rest = trimmed.strip_prefix("mailto:[email protected]")?;
+ if !(rest.is_empty() || rest.starts_with('?')) || unencoded_char(trimmed).is_some() {
+ return None;
+ }
+ // Only the subject and body: no `cc`, `bcc` or second recipient.
+ let only_subject_and_body = rest
+ .trim_start_matches('?')
+ .split('&')
+ .filter(|kv| !kv.is_empty())
+ .all(|kv| kv.starts_with("subject=") || kv.starts_with("body="));
+ only_subject_and_body.then_some(trimmed)
+}
+
/// The host backend: the `cua-host` library driven by the app's sign-in.
fn host_backend(core: &std::sync::Arc<core::AppCore>) -> std::sync::Arc<dyn host::HostBackend> {
std::sync::Arc::new(host_backend::CuaHostBackend::new(
@@ -847,7 +880,7 @@ pub fn run() {
#[cfg(test)]
mod open_web_url_tests {
- use super::checked_web_url;
+ use super::{checked_support_mailto, checked_web_url};
#[test]
fn only_plain_web_urls_reach_the_opener() {
@@ -880,6 +913,41 @@ mod open_web_url_tests {
}
}
+#[cfg(test)]
+mod support_mailto_tests {
+ use super::{checked_support_mailto, checked_web_url};
+
+ #[test]
+ fn only_the_report_email_to_cua_support_opens() {
+ for ok in [
+ "mailto:[email protected]",
+ "mailto:[email protected]?subject=Spaces%3A%20create%20failed&body=a%0D%0Ab",
+ " mailto:[email protected]?body=x ",
+ ] {
+ assert_eq!(checked_support_mailto(ok), Some(ok.trim()), "{ok:?}");
+ }
+ for bad in [
+ "",
+ "mailto:",
+ "mailto:[email protected]?subject=x",
+ "mailto:[email protected]?subject=x",
+ "mailto:[email protected]?subject=a b",
+ "mailto:[email protected]?subject=\"x\"",
+ "mailto:[email protected]?subject=\u{e9}",
+ "MAILTO:[email protected]",
+ "https://trycua.com",
+ ] {
+ assert_eq!(checked_support_mailto(bad), None, "{bad:?}");
+ }
+ // The sign-in's opener stays web only.
+ assert!(checked_web_url("mailto:[email protected]").is_err());
+ }
+}
+
#[cfg(test)]
mod dev_hook_tests {
use super::{dev_hook_in, DEV_HOOKS};
diff --git a/libs/cua/crates/cua-spaces-app-core/src/diagnostics.rs b/libs/cua/crates/cua-spaces-app-core/src/diagnostics.rs
new file mode 100644
index 0000000000..53d15a6dae
--- /dev/null
+++ b/libs/cua/crates/cua-spaces-app-core/src/diagnostics.rs
@@ -0,0 +1,1191 @@
+// SPDX-License-Identifier: FSL-1.1-MIT
+// Copyright (c) 2026 Cua AI, Inc.
+
+//! The opt-in diagnostic report for a failed Space create.
+//!
+//! Standard crash-report pattern: on a failed create the app builds the
+//! report here ([`create_report`]), redacted ([`redact`]), and shows it in a
+//! review sheet. The person can edit or leave out each part, and nothing
+//! leaves the machine unless they send it. Open email opens a prefilled
+//! email to Cua support ([`report_mailto`], a `mailto:` link) in their mail
+//! app with the kept parts. Reports are private: they go only to
+//! [email protected], and only when the person sends that email themselves.
+//! No new service receives anything.
+//!
+//! Redaction runs twice: when the sheet is built, and again on the text the
+//! person sends (their edits included).
+
+use serde::{Deserialize, Serialize};
+
+use crate::about::AboutInput;
+
+/// What the app knows about one failed create.
+#[derive(Debug, Clone, Default, PartialEq, Serialize, Deserialize)]
+#[serde(rename_all = "camelCase", default)]
+pub struct CreateReportInput {
+ /// The error text the create failed with (the SDK's words, before the
+ /// app rewrote them).
+ pub error: String,
+ /// What the failed row showed, when different.
+ pub shown: Option<String>,
+ /// The phase it failed in (`pulling`, `booting`, ...).
+ pub phase: String,
+ /// `linux`, `windows` or `macos`.
+ pub os: String,
+ /// `local`, `cloud` or `relay`.
+ pub provider: String,
+ /// `container` or `vm`, when known.
+ pub kind: Option<String>,
+ /// The image asked for.
+ pub image: Option<String>,
+ /// GPU acceleration was asked for.
+ pub gpu: bool,
+ /// Milliseconds from Create to the failure.
+ pub elapsed_ms: Option<u64>,
+ /// The app and this machine (Settings > About's input).
+ pub about: Option<AboutInput>,
+ /// Names to hide wherever they appear: this machine's and the account's
+ /// other machines' names (Bonjour names have no dots, so [`redact`]
+ /// cannot find them on its own).
+ pub names: Vec<String>,
+}
+
+/// One part of the report the person can edit or leave out.
+#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
+#[serde(rename_all = "camelCase")]
+pub struct ReportPart {
+ /// `details`, `error` or `environment`.
+ pub id: String,
+ /// "What was created".
+ pub label: String,
+ /// The redacted text.
+ pub text: String,
+}
+
+/// The review sheet for a failed create.
+#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
+#[serde(rename_all = "camelCase")]
+pub struct CreateReport {
+ /// "Send a diagnostic report".
+ pub title: String,
+ /// What Open email does, in plain words.
+ pub intro: String,
+ /// The email subject.
+ pub subject: String,
+ /// The parts, in order.
+ pub parts: Vec<ReportPart>,
+ /// "Open email".
+ pub send_label: String,
+ /// The fixed failure word (`image_pull_auth`), as telemetry records it.
+ pub error_kind: String,
+}
+
+/// The parts the person kept, as they edited them.
+#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
+#[serde(rename_all = "camelCase", default)]
+pub struct ReportSend {
+ pub subject: String,
+ pub parts: Vec<ReportPart>,
+}
+
+fn word(s: &str) -> &str {
+ match s {
+ "linux" => "Linux",
+ "windows" => "Windows",
+ "macos" => "macOS",
+ "local" => "this machine",
+ "cloud" => "Cua Cloud",
+ "relay" => "another of my machines",
+ "container" => "container",
+ "vm" => "VM",
+ _ => s,
+ }
+}
+
+fn phase_words(phase: &str) -> &str {
+ match phase {
+ "preparing" => "preparing",
+ "pulling" => "downloading the image",
+ "creating" => "creating",
+ "booting" => "starting up",
+ "waiting_for_services" => "starting its services",
+ "connecting" => "connecting",
+ "" => "an unknown step",
+ p => p,
+ }
+}
+
+fn platform_name(platform: &str) -> &'static str {
+ match platform {
+ "windows" => "Windows",
+ "linux" => "Linux",
+ _ => "macOS",
+ }
+}
+
+/// The report for a failed create, redacted.
+pub fn create_report(input: &CreateReportInput) -> CreateReport {
+ let kind = cua_create_failure::create_failure_kind(
+ &crate::errors::plain_error(&input.error),
+ &input.phase,
+ "",
+ input.provider != "cloud",
+ );
+ let error_kind = if kind.is_empty() { "other" } else { kind }.to_string();
+ let r = |s: &str| redact_with(s, &input.names);
+ let mut details = vec![
+ format!(
+ "Space: {} {}",
+ word(&input.os),
+ input.kind.as_deref().map(word).unwrap_or("Space")
+ ),
+ format!("Where: {}", word(&input.provider)),
+ ];
+ if let Some(image) = input.image.as_deref().filter(|i| !i.trim().is_empty()) {
+ details.push(format!("Image: {}", r(image.trim())));
+ }
+ details.push(format!("Failed while: {}", phase_words(&input.phase)));
+ details.push(format!("Failure kind: {error_kind}"));
+ if input.gpu {
+ details.push("GPU acceleration: on".into());
+ }
+ if let Some(ms) = input.elapsed_ms {
+ let secs = ms / 1000;
+ details.push(if secs >= 120 {
+ format!("Time to failure: {} min", secs / 60)
+ } else {
+ format!("Time to failure: {secs} s")
+ });
+ }
+ let mut error = r(input.error.trim());
+ if error.is_empty() {
+ error = "No error text was reported.".into();
+ }
+ if let Some(shown) = input.shown.as_deref().map(str::trim)
+ && !shown.is_empty()
+ && shown != input.error.trim()
+ {
+ error = format!("{error}\n\nThe app showed: {}", r(shown));
+ }
+ let environment = match &input.about {
+ Some(a) => {
+ let mut e = format!(
+ "Cua Spaces for {} {}",
+ platform_name(&a.platform),
+ crate::about::version_line(&a.version, &a.build).trim_start_matches("Version ")
+ );
+ if !a.os.is_empty() {
+ e.push('\n');
+ e.push_str(&r(&a.os));
+ }
+ e
+ }
+ None => "Cua Spaces".into(),
+ };
+ CreateReport {
+ title: "Send a diagnostic report".into(),
+ intro: format!(
+ "This is what the report says. We removed tokens, email addresses, \
+ hostnames and your home folder. Edit it or leave parts out. Open \
+ email starts an email to Cua support ({SUPPORT_EMAIL}) in your mail \
+ app, with the parts you kept. It goes nowhere else, and nothing is \
+ sent until you press Send there."
+ ),
+ subject: format!(
+ "Spaces: {} {} create failed ({error_kind})",
+ word(&input.os),
+ input.kind.as_deref().map(word).unwrap_or("Space")
+ ),
+ parts: vec![
+ ReportPart {
+ id: "details".into(),
+ label: "What was created".into(),
+ text: details.join("\n"),
+ },
+ ReportPart {
+ id: "error".into(),
+ label: "Error".into(),
+ text: error,
+ },
+ ReportPart {
+ id: "environment".into(),
+ label: "App and system".into(),
+ text: environment,
+ },
+ ],
+ send_label: "Open email".into(),
+ error_kind,
+ }
+}
+
+/// Where reports go: Cua's support address, as on the public site.
+pub const SUPPORT_EMAIL: &str = "[email protected]";
+
+/// Longest body the email link carries, counted as written in the link
+/// (percent-encoded). Mail apps and the OS cut or drop much longer links
+/// (Windows' limit is about 2,000 characters for the whole link).
+const BODY_MAX: usize = 1800;
+
+/// Longest subject, in characters.
+const SUBJECT_MAX: usize = 150;
+
+/// Added where a part is cut to fit the link.
+const CUT_NOTE: &str = "[cut: too long for an email link]";
+
+/// Whether `b` stays as it is in a URL query value (RFC 3986 unreserved).
+fn is_unreserved(b: u8) -> bool {
+ b.is_ascii_alphanumeric() || matches!(b, b'-' | b'.' | b'_' | b'~')
+}
+
+/// `s` for a URL query value. Line breaks become `%0D%0A`, as RFC 6068 asks
+/// for a mail body.
+fn query_value(s: &str) -> String {
+ let mut out = String::with_capacity(s.len());
+ for b in s.bytes() {
+ if b == b'\n' {
+ out.push_str("%0D%0A");
+ } else if is_unreserved(b) {
+ out.push(b as char);
+ } else {
+ out.push_str(&format!("%{b:02X}"));
+ }
+ }
+ out
+}
+
+/// What `c` adds to a query value, as [`query_value`] writes it.
+fn encoded_cost(c: char) -> usize {
+ match c {
+ '\n' => 6,
+ c if c.is_ascii() => {
+ if is_unreserved(c as u8) {
+ 1
+ } else {
+ 3
+ }
+ }
+ c => 3 * c.len_utf8(),
+ }
+}
+
+fn encoded_len(s: &str) -> usize {
+ s.chars().map(encoded_cost).sum()
+}
+
+/// The longest start of `s` that takes at most `max` in a query value.
+fn encoded_prefix(s: &str, max: usize) -> &str {
+ let mut used = 0;
+ for (i, c) in s.char_indices() {
+ used += encoded_cost(c);
+ if used > max {
+ return &s[..i];
+ }
+ }
+ s
+}
+
+/// `s` with line breaks as `\n` and no leading or trailing blank space.
+fn tidy(s: &str) -> String {
+ s.replace("\r\n", "\n")
+ .replace('\r', "\n")
+ .trim()
+ .to_string()
+}
+
+/// The email body from the parts the person kept. Over [`BODY_MAX`], the
+/// error is cut first (it is the part that grows), then the whole body, each
+/// with a note. Redaction has already run, so a cut never shows half a secret.
+fn mail_body(details: Option<&str>, error: Option<&str>, environment: Option<&str>) -> String {
+ let build = |error: Option<&str>| {
+ let mut out = String::from(
+ "Sent from the diagnostic report in Cua Spaces after a Space failed to create.",
+ );
+ for (heading, text) in [
+ ("What was created", details),
+ ("Error", error),
+ ("App and system", environment),
+ ] {
+ if let Some(text) = text {
+ out.push_str(&format!("\n\n{heading}\n{text}"));
+ }
+ }
+ out
+ };
+ let note = format!("\n{CUT_NOTE}");
+ let body = build(error);
+ if encoded_len(&body) <= BODY_MAX {
+ return body;
+ }
+ if let Some(error) = error {
+ // The error gets the room the other parts leave.
+ let room = BODY_MAX.saturating_sub(encoded_len(&build(Some(&note))));
+ let kept = encoded_prefix(error, room).trim_end();
+ let body = build(Some(&format!("{kept}{note}")));
+ if encoded_len(&body) <= BODY_MAX {
+ return body;
+ }
+ }
+ let room = BODY_MAX.saturating_sub(encoded_len(&note));
+ format!("{}{note}", encoded_prefix(&body, room).trim_end())
+}
+
+/// The prefilled email to Cua support with the parts the person kept,
+/// redacted again (their edits included), as a `mailto:` link. Nothing is
+/// sent by building it: the shell opens it in the person's mail app, where
+/// they press Send themselves.
+pub fn report_mailto(send: &ReportSend, names: &[String]) -> String {
+ let r = |s: &str| redact_with(&tidy(s), names);
+ let part = |id: &str| {
+ send.parts
+ .iter()
+ .find(|p| p.id == id)
+ .map(|p| r(&p.text))
+ .filter(|t| !t.is_empty())
+ };
+ let subject = r(&send.subject)
+ .split_whitespace()
+ .collect::<Vec<_>>()
+ .join(" ");
+ let subject: String = subject.chars().take(SUBJECT_MAX).collect();
+ let subject = if subject.is_empty() {
+ "Spaces: create failed".to_string()
+ } else {
+ subject
+ };
+ let body = mail_body(
+ part("details").as_deref(),
+ part("error").as_deref(),
+ part("environment").as_deref(),
+ );
+ format!(
+ "mailto:{SUPPORT_EMAIL}?subject={}&body={}",
+ query_value(&subject),
+ query_value(&body)
+ )
+}
+
+// ---- Redaction --------------------------------------------------------------
+
+/// `text` with tokens, email addresses, home folders, hostnames and public
+/// IP addresses replaced.
+pub fn redact(text: &str) -> String {
+ redact_with(text, &[])
+}
+
+/// [`redact`], also hiding each of `names` (machine names) wherever it
+/// appears.
+pub fn redact_with(text: &str, names: &[String]) -> String {
+ let s = hide_names(&home_paths(text), names);
+ let mut out = String::with_capacity(s.len());
+ let mut secret_next = false;
+ for (piece, is_space) in split_keep(&s) {
+ if is_space {
+ out.push_str(piece);
+ continue;
+ }
+ let (word, next_secret) = redact_word(piece, secret_next);
+ secret_next = next_secret;
+ out.push_str(&word);
+ }
+ out
+}
+
+/// Whitespace and non-whitespace runs, in order.
+fn split_keep(s: &str) -> Vec<(&str, bool)> {
+ let mut out = Vec::new();
+ let mut start = 0;
+ let mut space = None;
+ for (i, c) in s.char_indices() {
+ let w = c.is_whitespace();
+ match space {
+ Some(prev) if prev != w => {
+ out.push((&s[start..i], prev));
+ start = i;
+ }
+ _ => {}
+ }
+ space = Some(w);
+ }
+ if start < s.len() {
+ out.push((&s[start..], space.unwrap_or(false)));
+ }
+ out
+}
+
+/// How the app words the machine it runs on ("This Mac", "This PC",
+/// "This computer", and the This machine page). They identify no one, so
+/// they stay even when a machine's name is the phrase itself.
+const THIS_MACHINE_PHRASES: &[&str] = &["this mac", "this pc", "this computer", "this machine"];
+
+/// Byte ranges of every ASCII case-insensitive `needle` in `hay` (which
+/// `lower` is the ASCII lowercase of, so offsets agree), not overlapping.
+fn find_all_ci(lower: &str, needle: &str) -> Vec<(usize, usize)> {
+ let n = needle.to_ascii_lowercase();
+ let mut out = Vec::new();
+ if n.is_empty() {
+ return out;
+ }
+ let mut i = 0;
+ while let Some(off) = lower[i..].find(&n) {
+ let at = i + off;
+ out.push((at, at + n.len()));
+ i = at + n.len();
+ }
+ out
+}
+
+/// Whether a phrase at `at..end` of `s` stands alone, not inside a longer
+/// word or name (`This MacBook-Pro`).
+fn is_whole_phrase(s: &str, at: usize, end: usize) -> bool {
+ let joins = |c: char| c.is_alphanumeric() || matches!(c, '-' | '_');
+ !s[..at].chars().next_back().is_some_and(joins) && !s[end..].chars().next().is_some_and(joins)
+}
+
+/// `s` with each of `names` (machine names, ASCII case-insensitive) replaced
+/// by `<machine>`, except where the match sits inside the app's own words
+/// for this machine ([`THIS_MACHINE_PHRASES`]). A name that contains such a
+/// phrase and more (`This Mac (Maya)`) is still hidden whole.
+fn hide_names(s: &str, names: &[String]) -> String {
+ let lower = s.to_ascii_lowercase();
+ let phrases: Vec<(usize, usize)> = THIS_MACHINE_PHRASES
+ .iter()
+ .flat_map(|p| find_all_ci(&lower, p))
+ .filter(|&(at, end)| is_whole_phrase(s, at, end))
+ .collect();
+ let mut hits: Vec<(usize, usize)> = names
+ .iter()
+ .map(|n| n.trim())
+ .filter(|n| n.chars().count() >= 3)
+ .flat_map(|n| find_all_ci(&lower, n))
+ .filter(|&(at, end)| !phrases.iter().any(|&(pa, pe)| pa <= at && end <= pe))
+ .collect();
+ if hits.is_empty() {
+ return s.to_string();
+ }
+ hits.sort_unstable();
+ // Overlapping hits (`Studio` and `Studio Mac`) become one.
+ let mut spans: Vec<(usize, usize)> = Vec::new();
+ for (at, end) in hits {
+ match spans.last_mut() {
+ Some(last) if at < last.1 => last.1 = last.1.max(end),
+ _ => spans.push((at, end)),
+ }
+ }
+ let mut out = String::with_capacity(s.len());
+ let mut i = 0;
+ for (at, end) in spans {
+ out.push_str(&s[i..at]);
+ out.push_str("<machine>");
+ i = end;
+ }
+ out.push_str(&s[i..]);
+ out
+}
+
+/// `/Users/<name>`, `/home/<name>`, `C:\Users\<name>` (any case, either
+/// slash) become `~`.
+fn home_paths(s: &str) -> String {
+ let mut out = s.to_string();
+ for prefix in [
+ "/Users/",
+ "/home/",
+ "C:\\Users\\",
+ "C:/Users/",
+ "/var/home/",
+ ] {
+ let mut result = String::with_capacity(out.len());
+ let lower = out.to_ascii_lowercase();
+ let p = prefix.to_ascii_lowercase();
+ let mut i = 0;
+ while let Some(off) = lower[i..].find(&p) {
+ let at = i + off;
+ let name_start = at + p.len();
+ let name_end = out[name_start..]
+ .find(['/', '\\', ' ', '\'', '"', ')', ':', ',', '\n'])
+ .map_or(out.len(), |e| name_start + e);
+ let name = &out[name_start..name_end];
+ result.push_str(&out[i..at]);
+ if name.is_empty() || name.eq_ignore_ascii_case("shared") {
+ result.push_str(&out[at..name_end]);
+ } else {
+ result.push('~');
+ }
+ i = name_end;
+ }
+ result.push_str(&out[i..]);
+ out = result;
+ }
+ out
+}
+
+/// Keys whose value is a secret (`token=`, `password:`, `Authorization`).
+const SECRET_KEYS: &[&str] = &[
+ "token",
+ "secret",
+ "password",
+ "passwd",
+ "api_key",
+ "apikey",
+ "api-key",
+ "authorization",
+ "bearer",
+ "credential",
+ "private_key",
+ "session",
+ "cookie",
+ "signature",
+ "x-amz-signature",
+ "sig",
+];
+
+/// Token prefixes of well-known credentials.
+const TOKEN_PREFIXES: &[&str] = &[
+ "ghp_",
+ "gho_",
+ "ghu_",
+ "ghs_",
+ "ghr_",
+ "github_pat_",
+ "glpat-",
+ "sk-",
+ "sk_live_",
+ "sk_test_",
+ "rk_live_",
+ "pk_live_",
+ "xoxb-",
+ "xoxp-",
+ "xoxa-",
+ "akia",
+ "eyj",
+ "cua_",
+ "cuak_",
+ "hf_",
+ "npm_",
+];
+
+/// Registries and services whose names say nothing about the person.
+const PUBLIC_HOSTS: &[&str] = &[
+ "ghcr.io",
+ "github.com",
+ "docker.io",
+ "registry-1.docker.io",
+ "index.docker.io",
+ "quay.io",
+ "cua.ai",
+ "trycua.com",
+ "apple.com",
+ "microsoft.com",
+ "ubuntu.com",
+ "debian.org",
+ "localhost",
+];
+
+/// Top-level domains a hostname ends with (filenames like `config.json`
+/// do not).
+const TLDS: &[&str] = &[
+ "com",
+ "net",
+ "org",
+ "io",
+ "ai",
+ "dev",
+ "co",
+ "cloud",
+ "sh",
+ "me",
+ "xyz",
+ "tech",
+ "us",
+ "uk",
+ "de",
+ "fr",
+ "eu",
+ "it",
+ "es",
+ "nl",
+ "ch",
+ "ca",
+ "au",
+ "jp",
+ "in",
+ "br",
+ "info",
+ "biz",
+ "local",
+ "lan",
+ "internal",
+ "home",
+ "corp",
+ "localdomain",
+ "arpa",
+];
+
+fn is_secret_key(k: &str) -> bool {
+ let k = k
+ .trim_matches(|c: char| !c.is_ascii_alphanumeric() && c != '_' && c != '-')
+ .to_ascii_lowercase();
+ !k.is_empty()
+ && SECRET_KEYS
+ .iter()
+ .any(|s| k == *s || k.ends_with(&format!("_{s}")) || k.ends_with(&format!("-{s}")))
+}
+
+fn looks_like_token(w: &str) -> bool {
+ let l = w.to_ascii_lowercase();
+ if TOKEN_PREFIXES.iter().any(|p| l.starts_with(p))
+ && w.len() >= 12
+ && w.chars().any(|c| c.is_ascii_digit())
+ && !w.contains('=')
+ {
+ return true;
+ }
+ // Digests and ids stay: they help and are not secrets.
+ if l.starts_with("sha256:") || l.starts_with("sha512:") || is_uuid(w) {
+ return false;
+ }
+ if w.len() < 32 {
+ return false;
+ }
+ let allowed = w
+ .chars()
+ .all(|c| c.is_ascii_alphanumeric() || matches!(c, '_' | '-' | '+' | '/' | '=' | '.'));
+ let digits = w.chars().any(|c| c.is_ascii_digit());
+ let letters = w.chars().any(|c| c.is_ascii_alphabetic());
+ // A plain hex string (a digest without its prefix, a container id)
+ // stays too.
+ let hex = w.chars().all(|c| c.is_ascii_hexdigit());
+ allowed && digits && letters && !hex && !w.contains("..") && !w.starts_with('/')
+}
+
+fn is_uuid(w: &str) -> bool {
+ let parts: Vec<&str> = w.split('-').collect();
+ parts.len() == 5
+ && [8, 4, 4, 4, 12]
+ .iter()
+ .zip(&parts)
+ .all(|(n, p)| p.len() == *n && p.chars().all(|c| c.is_ascii_hexdigit()))
+}
+
+fn is_email(w: &str) -> bool {
+ let Some((user, domain)) = w.split_once('@') else {
+ return false;
+ };
+ !user.is_empty()
+ && domain.contains('.')
+ && !domain.starts_with('.')
+ && domain
+ .chars()
+ .all(|c| c.is_ascii_alphanumeric() || matches!(c, '.' | '-'))
+ && user
+ .chars()
+ .all(|c| c.is_ascii_alphanumeric() || matches!(c, '.' | '_' | '-' | '+' | '%'))
+}
+
+/// A hostname to hide: dotted labels ending in a known TLD, not a public
+/// registry or service.
+fn is_private_host(h: &str) -> bool {
+ let h = h.trim_end_matches('.').to_ascii_lowercase();
+ let labels: Vec<&str> = h.split('.').collect();
+ if labels.len() < 2
+ || labels
+ .iter()
+ .any(|l| l.is_empty() || !l.chars().all(|c| c.is_ascii_alphanumeric() || c == '-'))
+ {
+ return false;
+ }
+ let tld = labels[labels.len() - 1];
+ if !TLDS.contains(&tld) {
+ return false;
+ }
+ !PUBLIC_HOSTS
+ .iter()
+ .any(|p| h == *p || h.ends_with(&format!(".{p}")))
+}
+
+fn is_public_ipv4(h: &str) -> bool {
+ let parts: Vec<u8> = h.split('.').filter_map(|p| p.parse().ok()).collect();
+ if parts.len() != 4 || h.split('.').count() != 4 {
+ return false;
+ }
+ let private = parts[0] == 10
+ || parts[0] == 127
+ || (parts[0] == 192 && parts[1] == 168)
+ || (parts[0] == 172 && (16..=31).contains(&parts[1]))
+ || (parts[0] == 169 && parts[1] == 254)
+ || (parts[0] == 100 && (64..=127).contains(&parts[1]))
+ || parts[0] == 0;
+ !private
+}
+
+/// `a=1&token=x`: secret values and token-like values hidden.
+fn redact_query(q: &str) -> String {
+ q.split('&')
+ .map(|pair| match pair.split_once('=') {
+ Some((k, _)) if is_secret_key(k) => format!("{k}=<redacted>"),
+ Some((k, v)) if is_email(v) || looks_like_token(v) => format!("{k}=<redacted>"),
+ _ => pair.to_string(),
+ })
+ .collect::<Vec<_>>()
+ .join("&")
+}
+
+/// One whitespace-free piece, redacted; also whether the next piece is a
+/// secret (it followed `Bearer` or `password:`).
+fn redact_word(piece: &str, secret: bool) -> (String, bool) {
+ // Keep surrounding punctuation as it is.
+ let start = piece
+ .find(|c: char| !matches!(c, '"' | '\'' | '(' | '[' | '<' | '{' | '`'))
+ .unwrap_or(piece.len());
+ let end = piece
+ .rfind(|c: char| {
+ !matches!(
+ c,
+ '"' | '\'' | ')' | ']' | '>' | '}' | ',' | ';' | '.' | '`' | ':'
+ )
+ })
+ .map_or(start, |e| {
+ e + piece[e..].chars().next().map_or(1, char::len_utf8)
+ });
+ let (lead, core, tail) = if start < end {
+ (&piece[..start], &piece[start..end], &piece[end..])
+ } else {
+ return (piece.to_string(), secret);
+ };
+ if secret {
+ // `Authorization: Bearer x`: the scheme stays, the next word goes.
+ if core.eq_ignore_ascii_case("bearer") || core.eq_ignore_ascii_case("basic") {
+ return (piece.to_string(), true);
+ }
+ return (format!("{lead}<redacted>{tail}"), false);
+ }
+ // `Bearer x`, `password: x`, `token x`.
+ let key_alone =
+ is_secret_key(core) && (tail.contains(':') || core.eq_ignore_ascii_case("bearer"));
+ if key_alone || core.eq_ignore_ascii_case("bearer") {
+ return (piece.to_string(), true);
+ }
+ (format!("{lead}{}{tail}", redact_core(core)), false)
+}
+
+fn redact_core(core: &str) -> String {
+ // A query string: each pair on its own (`?token=..&page=2`).
+ if let Some((before, query)) = core.split_once('?') {
+ return format!("{}?{}", redact_core(before), redact_query(query));
+ }
+ // key=value and key:value pairs.
+ for sep in ['=', ':'] {
+ if let Some((k, v)) = core.split_once(sep)
+ && !v.is_empty()
+ && !v.starts_with("//")
+ && is_secret_key(k)
+ {
+ return format!("{k}{sep}<redacted>");
+ }
+ }
+ if is_email(core) {
+ return "<email>".into();
+ }
+ if looks_like_token(core) {
+ return "<redacted>".into();
+ }
+ // URLs and host[:port][/path]: hide the host, and any user:pass@.
+ let (scheme, rest) = match core.find("://") {
+ Some(i) => (&core[..i + 3], &core[i + 3..]),
+ None => ("", core),
+ };
+ let host_end = rest.find(['/', '?', '#']).unwrap_or(rest.len());
+ let (authority, path) = rest.split_at(host_end);
+ let (userinfo, hostport) = match authority.rsplit_once('@') {
+ Some((u, h)) => (Some(u), h),
+ None => (None, authority),
+ };
+ let host = if hostport.starts_with('[') {
+ hostport
+ } else {
+ hostport.rsplit_once(':').map_or(hostport, |(h, p)| {
+ if p.chars().all(|c| c.is_ascii_digit()) {
+ h
+ } else {
+ hostport
+ }
+ })
+ };
+ let port = &hostport[host.len()..];
+ let hide_host = is_private_host(host) || is_public_ipv4(host);
+ if userinfo.is_none() && !hide_host {
+ return core.to_string();
+ }
+ let host_out = if is_public_ipv4(host) {
+ "<ip>".to_string()
+ } else if hide_host {
+ "<host>".to_string()
+ } else {
+ host.to_string()
+ };
+ let user_out = if userinfo.is_some() {
+ "<redacted>@"
+ } else {
+ ""
+ };
+ format!("{scheme}{user_out}{host_out}{port}{path}")
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+
+ #[test]
+ fn hides_tokens() {
+ for (raw, want) in [
+ (
+ concat!(
+ "token gh",
+ "p_abcdefghijklmnopqrstuvwxyz0123456789 rejected"
+ ),
+ "token <redacted> rejected",
+ ),
+ (
+ // A JWT-shaped fake, joined at build time so no scanner reads
+ // a token in the source.
+ concat!(
+ "Authorization: Bearer ey",
+ "JfaGVhZGVy.ey",
+ "JfcGF5bG9hZA.c2lnbmF0dXJl"
+ ),
+ "Authorization: Bearer <redacted>",
+ ),
+ (
+ concat!("api_key=sk", "-live-1234567890abcdef"),
+ "api_key=<redacted>",
+ ),
+ ("password: hunter2!", "password: <redacted>"),
+ (
+ "GET /v1/x?token=abc123&page=2",
+ "GET /v1/x?token=<redacted>&page=2",
+ ),
+ (
+ concat!("key AKI", "AIOSFODNN7EXAMPLE leaked"),
+ "key <redacted> leaked",
+ ),
+ (concat!("xox", "b-1234-5678-abcdefghijkl"), "<redacted>"),
+ ("CUA_API_KEY=cua_0123456789abcdef", "CUA_API_KEY=<redacted>"),
+ (
+ "blob Zm9vYmFyYmF6cXV4MTIzNDU2Nzg5MGFiY2RlZmdoaWo= ok",
+ "blob <redacted> ok",
+ ),
+ ] {
+ assert_eq!(redact(raw), want, "{raw}");
+ }
+ }
+
+ #[test]
+ fn keeps_digests_ids_and_ordinary_words() {
+ for raw in [
+ "pull ghcr.io/trycua/linux:24.04@sha256:0123456789abcdef0123456789abcdef0123456789abcdef0123456789abcdef",
+ "sandbox 3f2504e0-4f89-11d3-9a0c-0305e82c3301 was not ready after 300s",
+ "container 0123456789abcdef0123456789abcdef0123456789abcdef0123456789abcdef exited",
+ "Not enough disk space: this Space needs about 30.0 GB.",
+ "QEMU (qemu-system-x86_64, qemu-img) is not available: install it",
+ "cannot reach the VM at 192.168.64.45:3211 (No route to host (os error 65))",
+ "read config.json and Cua Spaces.app",
+ ] {
+ assert_eq!(redact(raw), raw, "{raw}");
+ }
+ }
+
+ #[test]
+ fn hides_emails() {
+ assert_eq!(
+ redact("signed in as [email protected]."),
+ "signed in as <email>."
+ );
+ assert_eq!(redact("<[email protected]>"), "<<email>>");
+ }
+
+ #[test]
+ fn hides_home_folders() {
+ assert_eq!(
+ redact("only 12.0 GB is available on /Users/maya/.lume (APFS)"),
+ "only 12.0 GB is available on ~/.lume (APFS)"
+ );
+ assert_eq!(redact("open /home/sam/.cua/x.sock"), "open ~/.cua/x.sock");
+ assert_eq!(redact(r"C:\Users\sam\AppData\Local"), r"~\AppData\Local");
+ assert_eq!(redact("/Users/Shared/cua"), "/Users/Shared/cua");
+ }
+
+ #[test]
+ fn hides_hostnames_and_public_ips() {
+ assert_eq!(
+ redact("connect to build-box.corp.example.net:8443 failed"),
+ "connect to <host>:8443 failed"
+ );
+ assert_eq!(redact("Mac-mini.local refused"), "<host> refused");
+ assert_eq!(
+ redact("https://build-7.internal.acme.com/v2/x?sig=abc"),
+ "https://<host>/v2/x?sig=<redacted>"
+ );
+ assert_eq!(
+ redact("https://user:[email protected]/v2/"),
+ "https://<redacted>@ghcr.io/v2/"
+ );
+ assert_eq!(redact("dial 203.0.113.9:443"), "dial <ip>:443");
+ // Public registries and services stay: they say what failed.
+ assert_eq!(
+ redact("registry: Not authorized: ghcr.io/trycua/macos:26 from api.cua.ai"),
+ "registry: Not authorized: ghcr.io/trycua/macos:26 from api.cua.ai"
+ );
+ }
+
+ #[test]
+ fn hides_machine_names_it_is_told() {
+ let names = vec!["Francescos-MacBook-Pro".to_string(), "x".to_string()];
+ assert_eq!(
+ redact_with("host francescos-macbook-pro said no; x stays", &names),
+ "host <machine> said no; x stays"
+ );
+ }
+
+ #[test]
+ fn keeps_the_apps_words_for_this_machine() {
+ // The machine row is named "This Mac" ("This PC", "This computer"),
+ // so it is among the names to hide. The phrase stays: it names no one.
+ for phrase in ["This Mac", "This PC", "This computer", "This machine"] {
+ let names = vec![phrase.to_string(), "Studio".to_string()];
+ assert_eq!(
+ redact_with(&format!("{phrase} can't reach Studio."), &names),
+ format!("{phrase} can't reach <machine>."),
+ );
+ assert_eq!(
+ redact_with(&format!("{} can't reach it", phrase.to_uppercase()), &names),
+ format!("{} can't reach it", phrase.to_uppercase()),
+ );
+ }
+ // A real name that is part of the phrase (`Mac`) is still hidden
+ // elsewhere, but not inside "This Mac".
+ let names = vec!["Mac".to_string()];
+ assert_eq!(
+ redact_with("This Mac lost Mac and my mac", &names),
+ "This Mac lost <machine> and my <machine>"
+ );
+ // A name that contains the phrase and more is hidden whole.
+ let names = vec!["This Mac (Maya)".to_string()];
+ assert_eq!(
+ redact_with("on This Mac (Maya) and This Mac", &names),
+ "on <machine> and This Mac"
+ );
+ // Longer words that start like the phrase are not the phrase.
+ let names = vec!["This MacBook-Pro".to_string()];
+ assert_eq!(
+ redact_with("This MacBook-Pro is offline", &names),
+ "<machine> is offline"
+ );
+ // Overlapping names become one marker.
+ let names = vec!["Studio".to_string(), "Studio Mini".to_string()];
+ assert_eq!(redact_with("Studio Mini slept", &names), "<machine> slept");
+ }
+
+ #[test]
+ fn the_report_keeps_this_mac_and_hides_real_names() {
+ let mut i = input();
+ i.error = "This Mac can't reach Studio-7: connection refused".into();
+ i.shown = Some("This Mac can't reach Francescos-Mac-Studio.".into());
+ i.names = vec![
+ "This Mac".into(),
+ "Francescos-Mac-Studio".into(),
+ "Studio-7".into(),
+ ];
+ let r = create_report(&i);
+ assert_eq!(
+ r.parts[1].text,
+ "This Mac can't reach <machine>: connection refused\n\n\
+ The app showed: This Mac can't reach <machine>."
+ );
+ // The second pass, on what the person sends, agrees.
+ let mail = report_mailto(&send_of(&r), &i.names);
+ assert!(mail_field(&mail, "body").contains("This Mac can't reach <machine>"));
+ }
+
+ fn input() -> CreateReportInput {
+ CreateReportInput {
+ error: concat!(
+ "container engine: pull ghcr.io/me/private:1: pull access denied for \
+ ghcr.io/me/private, token gh",
+ "p_abcdefghijklmnopqrstuvwxyz0123456789 \
+ ([email protected], /Users/maya/.cua)"
+ )
+ .into(),
+ shown: Some("Could not download the image.".into()),
+ phase: "pulling".into(),
+ os: "linux".into(),
+ provider: "local".into(),
+ kind: Some("container".into()),
+ image: Some("ghcr.io/me/private:1".into()),
+ gpu: false,
+ elapsed_ms: Some(42_000),
+ about: Some(AboutInput {
+ platform: "macos".into(),
+ version: "0.4.0".into(),
+ build: "0.4.0.200".into(),
+ os: "macOS 26.0 (arm64)".into(),
+ ..AboutInput::default()
+ }),
+ names: vec!["Studio".into()],
+ }
+ }
+
+ #[test]
+ fn the_report_is_redacted_and_names_the_failure() {
+ let r = create_report(&input());
+ assert_eq!(r.error_kind, "image_pull_auth");
+ assert_eq!(
+ r.subject,
+ "Spaces: Linux container create failed (image_pull_auth)"
+ );
+ let ids: Vec<&str> = r.parts.iter().map(|p| p.id.as_str()).collect();
+ assert_eq!(ids, ["details", "error", "environment"]);
+ let all: String = r.parts.iter().map(|p| p.text.as_str()).collect();
+ for leak in ["ghp_", "maya", "/Users/"] {
+ assert!(!all.contains(leak), "{leak} in {all}");
+ }
+ assert!(
+ r.parts[0]
+ .text
+ .contains("Failed while: downloading the image")
+ );
+ assert!(r.parts[0].text.contains("Time to failure: 42 s"));
+ assert!(
+ r.parts[1]
+ .text
+ .contains("The app showed: Could not download the image.")
+ );
+ assert_eq!(
+ r.parts[2].text,
+ "Cua Spaces for macOS 0.4.0 (0.4.0.200)\nmacOS 26.0 (arm64)"
+ );
+ assert!(!r.intro.contains('\u{2014}'), "no em dashes in UI copy");
+ // One "Send" in the sheet's copy: the one in the mail app.
+ assert_eq!(r.send_label, "Open email");
+ assert_eq!(r.intro.matches("Send").count(), 1, "{}", r.intro);
+ assert!(r.intro.contains("press Send there"), "{}", r.intro);
+ // The sheet says where it goes: an email to Cua support.
+ assert!(
+ r.intro
+ .contains("email to Cua support ([email protected])")
+ );
+ for public in ["public", "GitHub", "issue"] {
+ assert!(!r.intro.contains(public), "{public} in {}", r.intro);
+ }
+ }
+
+ /// The query value `name` of a `mailto:` link, decoded (line breaks as `\n`).
+ fn mail_field(url: &str, name: &str) -> String {
+ let query = url.split_once('?').expect("a query").1;
+ let raw = query
+ .split('&')
+ .find_map(|kv| kv.strip_prefix(&format!("{name}=")))
+ .unwrap_or_else(|| panic!("no {name} in {url}"));
+ let mut bytes = Vec::new();
+ let mut it = raw.bytes();
+ while let Some(b) = it.next() {
+ if b == b'%' {
+ let hex: Vec<u8> = it.by_ref().take(2).collect();
+ bytes.push(u8::from_str_radix(std::str::from_utf8(&hex).unwrap(), 16).unwrap());
+ } else {
+ bytes.push(b);
+ }
+ }
+ String::from_utf8(bytes).unwrap().replace("\r\n", "\n")
+ }
+
+ fn body_len(url: &str) -> usize {
+ url.split_once("&body=").expect("a body").1.len()
+ }
+
+ fn send_of(r: &CreateReport) -> ReportSend {
+ ReportSend {
+ subject: r.subject.clone(),
+ parts: r.parts.clone(),
+ }
+ }
+
+ #[test]
+ fn the_link_is_a_private_email_with_only_the_kept_parts_redacted_again() {
+ let r = create_report(&input());
+ let mut send = send_of(&r);
+ // The person left the environment out and pasted a secret in.
+ send.parts.retain(|p| p.id != "environment");
+ send.parts[1].text.push_str(concat!(
+ "\nmy token=gh",
+ "p_zzzzzzzzzzzzzzzzzzzzzzzzzzzzzz9 at [email protected]"
+ ));
+ let url = report_mailto(&send, &[]);
+ assert!(url.starts_with(
+ "mailto:[email protected]?subject=Spaces%3A%20Linux%20container%20create%20failed"
+ ));
+ assert!(!url.contains("github"), "no GitHub address in {url}");
+ for leak in ["ghp_", "sam%40example.com", "maya"] {
+ assert!(!url.contains(leak), "{leak} in {url}");
+ }
+ assert!(url.contains("token%3D%3Credacted%3E"));
+ assert!(url.contains("%0D%0A"), "line breaks follow RFC 6068");
+ let body = mail_field(&url, "body");
+ assert!(body.contains("What was created\nSpace: Linux container"));
+ assert!(body.contains("Error\n"));
+ assert!(body.contains("token=<redacted> at <email>"));
+ assert!(
+ !body.contains("App and system"),
+ "a part left out stays out"
+ );
+ assert_eq!(
+ mail_field(&url, "subject"),
+ "Spaces: Linux container create failed (image_pull_auth)"
+ );
+ }
+
+ #[test]
+ fn a_long_error_is_cut_and_the_rest_of_the_report_stays() {
+ let r = create_report(&input());
+ let mut send = send_of(&r);
+ send.parts[1].text = "word ".repeat(2000);
+ let url = report_mailto(&send, &[]);
+ assert!(body_len(&url) <= BODY_MAX, "{} chars", body_len(&url));
+ let body = mail_field(&url, "body");
+ assert!(body.contains("[cut: too long for an email link]"));
+ assert!(body.contains("Space: Linux container"), "details stay");
+ assert!(body.contains("Cua Spaces for macOS"), "environment stays");
+ assert!(body.contains("word word"), "the start of the error stays");
+ }
+
+ #[test]
+ fn a_report_that_fits_is_not_cut() {
+ let url = report_mailto(&send_of(&create_report(&input())), &[]);
+ assert!(body_len(&url) <= BODY_MAX);
+ assert!(!mail_field(&url, "body").contains("[cut"));
+ }
+
+ #[test]
+ fn the_whole_body_is_cut_when_the_other_parts_are_too_long() {
+ let r = create_report(&input());
+ let mut send = send_of(&r);
+ send.parts[0].text = "é ".repeat(3000);
+ let url = report_mailto(&send, &[]);
+ assert!(body_len(&url) <= BODY_MAX, "{} chars", body_len(&url));
+ assert!(mail_field(&url, "body").ends_with("[cut: too long for an email link]"));
+ }
+
+ #[test]
+ fn the_subject_is_one_short_line() {
+ let mut send = send_of(&create_report(&input()));
+ send.subject = format!("first line\r\nBcc: [email protected] {}", "long ".repeat(100));
+ let url = report_mailto(&send, &[]);
+ let subject = mail_field(&url, "subject");
+ assert!(!subject.contains('\n') && !subject.contains('\r'));
+ assert!(subject.chars().count() <= SUBJECT_MAX);
+ assert!(subject.starts_with("first line Bcc: <email>"), "{subject}");
+ send.subject = " ".into();
+ assert_eq!(
+ mail_field(&report_mailto(&send, &[]), "subject"),
+ "Spaces: create failed"
+ );
+ }
+}
diff --git a/libs/cua/crates/cua-spaces-app-core/src/dispatch.rs b/libs/cua/crates/cua-spaces-app-core/src/dispatch.rs
index b8f6c8b329..9ee67ba0da 100644
--- a/libs/cua/crates/cua-spaces-app-core/src/dispatch.rs
+++ b/libs/cua/crates/cua-spaces-app-core/src/dispatch.rs
@@ -14,10 +14,10 @@ use crate::model::*;
use crate::spaces::{self, creating, roster, sidebar, stream};
use crate::teleport::{drag, flow, grid, transfer, windows};
use crate::{
- CoreError, about, agent_keys, agents, checklist, cloud_connect, devices, drive_mount_preview,
- drive_page, drive_settings, driver_preview, experiments, host, login_item, machines, notch,
- notifications, onboarding, onboarding_preview, palette, paths, persistent, presence,
- relay_usage, settings, share, telemetry, upsell, window, wizard,
+ CoreError, about, agent_keys, agents, checklist, cloud_connect, devices, diagnostics,
+ drive_mount_preview, drive_page, drive_settings, driver_preview, experiments, host, login_item,
+ machines, notch, notifications, onboarding, onboarding_preview, palette, paths, persistent,
+ presence, relay_usage, settings, share, telemetry, upsell, window, wizard,
};
use serde::Serialize;
use serde::de::DeserializeOwned;
@@ -178,6 +178,9 @@ pub const METHODS: &[&str] = &[
"agentKeys.removeConfirm",
"agentKeys.nameProblem",
"about.view",
+ "diagnostics.createReport",
+ "diagnostics.reportMailto",
+ "diagnostics.redact",
"about.afterLaunch",
"about.restartDaemon",
"about.refreshNotice",
@@ -756,6 +759,12 @@ pub fn call_value(method: &str, args: Value) -> Result<Value, CoreError> {
)),
"agentKeys.nameProblem" => out(agent_keys::name_problem(&a.get::<String>("name")?)),
"about.view" => out(about::view(&a.get::<about::AboutInput>("input")?)),
+ "diagnostics.createReport" => out(diagnostics::create_report(&a.get("input")?)),
+ "diagnostics.reportMailto" => out(diagnostics::report_mailto(
+ &a.get("send")?,
+ &a.get::<Option<Vec<String>>>("names")?.unwrap_or_default(),
+ )),
+ "diagnostics.redact" => out(diagnostics::redact(&a.get::<String>("text")?)),
"about.afterLaunch" => out(about::after_launch(&a.get::<about::LaunchInput>("input")?)),
"about.restartDaemon" => out(about::restart_daemon(
&a.get::<about::DaemonCheck>("check")?,
diff --git a/libs/cua/crates/cua-spaces-app-core/src/lib.rs b/libs/cua/crates/cua-spaces-app-core/src/lib.rs
index 2b03b49488..186ef262be 100644
--- a/libs/cua/crates/cua-spaces-app-core/src/lib.rs
+++ b/libs/cua/crates/cua-spaces-app-core/src/lib.rs
@@ -60,6 +60,7 @@ pub mod billing;
pub mod checklist;
pub mod cloud_connect;
pub mod devices;
+pub mod diagnostics;
pub mod dispatch;
pub mod drive_mount_preview;
pub mod drive_page;