Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
117 changes: 117 additions & 0 deletions web/src/components/app/AppFeedback.command.test.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,117 @@
// @vitest-environment happy-dom
import { act } from "react";
import { createRoot, type Root } from "react-dom/client";
import { afterEach, beforeEach, describe, expect, it, vi } from "vite-plus/test";

import { useUIStore } from "../../stores/useUIStore";
import { AppFeedback } from "./AppFeedback";

vi.mock("react-i18next", () => ({ useTranslation: () => ({ t: (key: string) => key }) }));

const ACP =
"io_error: runtime_error: Antigravity ACP session initialization failed. Complete separate ACP login with `cccc setup --runtime antigravity --runtime-mode acp --login`. ACP session/new failed (code -32000): Authentication required";
const COMMAND = "cccc setup --runtime antigravity --runtime-mode acp --login";

describe("an error that names a command to run", () => {
let host: HTMLDivElement;
let root: Root;
const writeText = vi.fn();
const render = (errorMsg: string, dismissError = vi.fn()) =>
act(async () =>
root.render(
<AppFeedback
webReadOnly={false}
errorMsg={errorMsg}
notice={null}
dismissError={dismissError}
dismissNotice={vi.fn()}
/>,
),
);
const alert = () => host.querySelector<HTMLElement>('[role="alert"]')!;
const copyKey = () =>
[...alert().querySelectorAll("button")].find((button) =>
button.textContent?.startsWith("commandError.cop"),
)!;

beforeEach(() => {
Object.assign(globalThis, { IS_REACT_ACT_ENVIRONMENT: true });
writeText.mockReset().mockResolvedValue(undefined);
// The browser boundary: the clipboard is where a copied command has to arrive.
vi.stubGlobal("navigator", { ...navigator, clipboard: { writeText } });
host = document.createElement("div");
document.body.append(host);
root = createRoot(host);
});
afterEach(async () => {
await act(async () => root.unmount());
host.remove();
vi.unstubAllGlobals();
vi.useRealTimers();
useUIStore.getState().dismissError();
});

it("says what to do, shows the command on its own, and copies exactly that command", async () => {
await render(ACP);

expect(alert().querySelector("[data-command-error]")?.getAttribute("data-command-error")).toBe(
"antigravity_acp_login",
);
expect(alert().textContent).toContain("commandError.antigravityAcpLogin");
expect(alert().querySelector("code")?.textContent).toBe(COMMAND);

await act(async () => copyKey().click());

expect(writeText).toHaveBeenCalledExactlyOnceWith(COMMAND);
expect(copyKey().textContent).toBe("commandError.copied");
});

it("keeps the daemon's own words available under the summary", async () => {
await render(ACP);

const details = alert().querySelector("details")!;
expect(details.open).toBe(false);
expect(details.querySelector("p")?.textContent).toBe(ACP);
});

it("says so when the command could not be copied", async () => {
writeText.mockRejectedValue(new Error("fixture: clipboard denied"));
// The fallback copy through a hidden field is refused as well.
const execCommand = vi.fn(() => false);
Object.defineProperty(document, "execCommand", { value: execCommand, configurable: true });
await render(ACP);

await act(async () => copyKey().click());

expect(copyKey().textContent).toBe("commandError.copyFailed");
});

it("leaves an error without a command as the plain message it was", async () => {
await render("daemon unavailable");

expect(alert().querySelector("[data-command-error]")).toBeNull();
expect(alert().querySelector("details")).toBeNull();
expect(alert().textContent).toBe("daemon unavailable×");
});

it("stays on screen until dismissed, while a plain error still clears by itself", async () => {
vi.useFakeTimers();

useUIStore.getState().showError(ACP);
vi.advanceTimersByTime(60_000);
expect(useUIStore.getState().errorMsg).toBe(ACP);

// A later plain error replaces it and goes away on the usual schedule.
useUIStore.getState().showError("daemon unavailable");
vi.advanceTimersByTime(7_999);
expect(useUIStore.getState().errorMsg).toBe("daemon unavailable");
vi.advanceTimersByTime(1);
expect(useUIStore.getState().errorMsg).toBe("");

// And a command error shown after a plain one is not cleared by the plain one's timer.
useUIStore.getState().showError("daemon unavailable");
useUIStore.getState().showError(ACP);
vi.advanceTimersByTime(60_000);
expect(useUIStore.getState().errorMsg).toBe(ACP);
});
});
63 changes: 59 additions & 4 deletions web/src/components/app/AppFeedback.tsx
Original file line number Diff line number Diff line change
@@ -1,4 +1,7 @@
import { useState } from "react";
import { useTranslation } from "react-i18next";
import { type CommandError, commandInError } from "../../utils/commandError";
import { copyTextToClipboard } from "../../utils/copy";

type AppNotice = { message: string; actionLabel?: string; onAction?: () => void };

Expand Down Expand Up @@ -35,6 +38,52 @@ export function FeedbackText({ text }: { text: string }) {
);
}

/**
* An error whose fix is a command: says what to do in plain words, shows the command on its own
* line with a key that copies it, and keeps the original message one click away.
*/
function CommandErrorBody({ error, original }: { error: CommandError; original: string }) {
const { t } = useTranslation("layout");
const [copied, setCopied] = useState<"" | "done" | "failed">("");
const copy = async () => {
setCopied((await copyTextToClipboard(error.command)) ? "done" : "failed");
};
return (
<div className="flex min-w-0 flex-1 flex-col gap-2" data-command-error={error.kind}>
<p className="leading-6">
{t(
error.kind === "antigravity_acp_login"
? "commandError.antigravityAcpLogin"
: "commandError.generic",
)}
</p>
<div className="flex min-w-0 flex-wrap items-center gap-2">
<code className="min-w-0 flex-1 basis-64 rounded-lg bg-[var(--glass-tab-bg)] px-3 py-2 font-mono text-xs break-words text-[var(--color-text-primary)]">
{error.command}
</code>
<button
type="button"
className="glass-btn shrink-0 px-3 py-2 text-xs text-[var(--color-text-primary)]"
onClick={() => void copy()}
data-lcd-key
>
{t(
copied === "done"
? "commandError.copied"
: copied === "failed"
? "commandError.copyFailed"
: "commandError.copy",
)}
</button>
</div>
<details className="text-xs text-[var(--color-text-secondary)]">
<summary className="cursor-pointer">{t("commandError.details")}</summary>
<p className="mt-1 break-words leading-5">{original}</p>
</details>
</div>
);
}

type AppFeedbackProps = {
webReadOnly: boolean;
errorMsg: string;
Expand All @@ -52,6 +101,8 @@ export function AppFeedback({
}: AppFeedbackProps) {
const { t } = useTranslation(["layout", "common"]);

const commandError = errorMsg ? commandInError(errorMsg) : null;

const handleNoticeAction = () => {
if (!notice?.onAction) return;
notice.onAction();
Expand All @@ -66,12 +117,16 @@ export function AppFeedback({
<div className="pointer-events-none fixed inset-x-0 top-4 z-[1200] flex flex-col items-center gap-3 px-4">
{errorMsg ? (
<div
className="pointer-events-auto flex w-full max-w-xl items-center gap-3 px-4 py-3 text-sm text-[var(--destructive)] glass-modal"
className={`pointer-events-auto flex w-full max-w-xl gap-3 px-4 py-3 text-sm text-[var(--destructive)] glass-modal ${commandError ? "items-start" : "items-center"}`}
role="alert"
>
<span className="min-w-0 flex-1 break-words leading-6">
<FeedbackText text={errorMsg} />
</span>
{commandError ? (
<CommandErrorBody key={errorMsg} error={commandError} original={errorMsg} />
) : (
<span className="min-w-0 flex-1 break-words leading-6">
<FeedbackText text={errorMsg} />
</span>
)}
<button
type="button"
className="glass-btn flex h-10 w-10 shrink-0 items-center justify-center p-2"
Expand Down
8 changes: 8 additions & 0 deletions web/src/i18n/locales/en/layout.json
Original file line number Diff line number Diff line change
Expand Up @@ -52,6 +52,14 @@
"reconnecting": "Reconnecting…",
"disconnected": "Disconnected",
"dismissError": "Dismiss error",
"commandError": {
"antigravityAcpLogin": "Antigravity's ACP mode is not signed in yet. Run this command in a terminal on the computer that runs CCCC, finish the sign-in in the browser it opens, then try again.",
"generic": "This needs a command first. Run it in a terminal on the computer that runs CCCC, then try again.",
"copy": "Copy command",
"copied": "Copied",
"copyFailed": "Copy failed",
"details": "Original error"
},
"createNewGroup": "Create new working group",
"newGroup": "New",
"workingGroups": "Working Groups",
Expand Down
8 changes: 8 additions & 0 deletions web/src/i18n/locales/ja/layout.json
Original file line number Diff line number Diff line change
Expand Up @@ -52,6 +52,14 @@
"reconnecting": "再接続中…",
"disconnected": "接続なし",
"dismissError": "エラーを閉じる",
"commandError": {
"antigravityAcpLogin": "Antigravity の ACP モードはまだサインインされていません。CCCC を実行しているコンピューターのターミナルで次のコマンドを実行し、開いたブラウザーでサインインを完了してから、もう一度お試しください。",
"generic": "先にコマンドの実行が必要です。CCCC を実行しているコンピューターのターミナルで実行してから、もう一度お試しください。",
"copy": "コマンドをコピー",
"copied": "コピーしました",
"copyFailed": "コピーに失敗しました",
"details": "元のエラー"
},
"createNewGroup": "新しい作業グループを作成",
"newGroup": "新規",
"workingGroups": "作業グループ",
Expand Down
8 changes: 8 additions & 0 deletions web/src/i18n/locales/zh/layout.json
Original file line number Diff line number Diff line change
Expand Up @@ -52,6 +52,14 @@
"reconnecting": "重连中…",
"disconnected": "已断开",
"dismissError": "关闭错误提示",
"commandError": {
"antigravityAcpLogin": "Antigravity 的 ACP 模式还没有登录。请在运行 CCCC 的那台电脑的终端里运行下面的命令,在它打开的浏览器里完成登录,然后重试。",
"generic": "需要先运行一条命令。请在运行 CCCC 的那台电脑的终端里运行它,然后重试。",
"copy": "复制命令",
"copied": "已复制",
"copyFailed": "复制失败",
"details": "原始错误"
},
"createNewGroup": "创建新工作组",
"newGroup": "新建",
"workingGroups": "工作组",
Expand Down
5 changes: 5 additions & 0 deletions web/src/stores/useUIStore.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
// UI state store (tabs, sidebar, toasts, etc.).
import { commandInError } from "../utils/commandError";
import { create } from "zustand";
import type { VoiceSecretaryCaptureMode } from "../pages/chat/voice-secretary/voiceSecretaryTypes";
import {
Expand Down Expand Up @@ -467,7 +468,11 @@ export const useUIStore = create<UIState>((set) => ({

showError: (msg) => {
if (errorTimeoutId) window.clearTimeout(errorTimeoutId);
errorTimeoutId = null;
set({ errorMsg: msg });
// An error that names a command to run stays until dismissed: eight seconds is not
// enough to read it, switch to a terminal and come back for the command.
if (commandInError(msg)) return;
errorTimeoutId = window.setTimeout(() => {
set({ errorMsg: "" });
errorTimeoutId = null;
Expand Down
44 changes: 44 additions & 0 deletions web/src/utils/commandError.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,44 @@
import { describe, expect, it } from "vite-plus/test";

import { commandInError } from "./commandError";

const ACP =
"io_error: runtime_error: Antigravity ACP session initialization failed. Complete separate ACP login with `cccc setup --runtime antigravity --runtime-mode acp --login`. ACP session/new failed (code -32000): Authentication required";

describe("commandInError", () => {
it("finds the login command in the Antigravity ACP authentication error", () => {
expect(commandInError(ACP)).toEqual({
command: "cccc setup --runtime antigravity --runtime-mode acp --login",
kind: "antigravity_acp_login",
});
});

it("finds any other quoted CCCC command without claiming to know what it fixes", () => {
expect(commandInError("Run `cccc setup --runtime deepseek` first.")).toEqual({
command: "cccc setup --runtime deepseek",
kind: "command",
});
// Antigravity's own setup without a login is not the login fix.
expect(
commandInError("Antigravity is missing; run `cccc setup --runtime antigravity`.")?.kind,
).toBe("command");
});

it("joins a command the message wrapped over lines into one line to paste", () => {
expect(commandInError("Run `cccc setup\n --runtime deepseek`.")?.command).toBe(
"cccc setup --runtime deepseek",
);
});

it.each([
["an error with nothing quoted", "daemon unavailable"],
["a quoted ID", "Actor `a1b2c3` was not found"],
["a quoted path", "could not read `/tmp/cccc/state`"],
["another program's command", "install it with `npm i -g kimi`"],
["the bare program name", "the `cccc` command is not on PATH"],
["an unclosed quote", "run `cccc setup --runtime deepseek"],
["a word that only starts like it", "see `ccccd status`"],
])("offers nothing to copy for %s", (_label, message) => {
expect(commandInError(message)).toBeNull();
});
});
24 changes: 24 additions & 0 deletions web/src/utils/commandError.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,24 @@
/** An error that tells the user to run a CCCC command, with the command it names. */
export type CommandError = {
/** The command exactly as the error quotes it. */
command: string;
/** Which fix the command is, when CCCC can say more than "run this". */
kind: "antigravity_acp_login" | "command";
};

/**
* The CCCC command an error message asks the user to run, if it quotes one in backticks, as
* daemon errors do: "... Complete separate ACP login with `cccc setup ... --login`. ...".
* Only a `cccc` command counts; other quoted text, such as an ID or a path, is not something to
* copy into a terminal.
*/
export function commandInError(message: string): CommandError | null {
const quoted = /`(cccc(?:\s+[^`]+)?)`/.exec(String(message || ""));
const command = quoted?.[1].replace(/\s+/g, " ").trim();
if (!command || command === "cccc") return null;
const acpLogin = /antigravity/i.test(message) && /--runtime-mode acp\b/.test(command);
return {
command,
kind: acpLogin && /--login\b/.test(command) ? "antigravity_acp_login" : "command",
};
}