feat(settings): data-safe editors, deep-linked search, Data/About/Cost pages

- EditorModal loads once per path (a parent re-render no longer reloads the
  file over the user's typing), refuses Save after a failed load, opens a
  truncated (>256 KB) file read-only, and asks before overwriting a file
  that changed on disk or could not be re-read.
- Settings/Hooks editors unset only keys from the snapshot taken at Edit,
  warn when the file changed underneath, keep a renamed key's value, and
  refuse a new key named like a redacted one (env) or a read-only hook
  event, which used to replace the secret/hooks.
- Project scope shows its resolved folder and is disabled inside the
  plugin cache. Account-profile, pricing-row and pet deletes confirm;
  two-click actions disarm after 3 s; unsaved drafts ask before closing.
- Search indexes every Claude Code / Codex sub-tab, opens it via ?tab= and
  scrolls to + highlights the row; the active config tab is in the URL.
- General splits into General / Data / About; Pricing moves to a Cost
  group with one shared load; config tabs group as Content / Extensions /
  Config with arrow-key roving; Promise.allSettled per tab.
- Data: browser-preferences export/import (allowlisted keys), per-section
  reset, housekeeping dry-run first, clear-all behind a typed phrase.
  Server: purge days must be a whole number >= 1 (INVALID_PURGE_DAYS) and
  dry_run returns exactly what the real run would delete.
- Alerts can be edited; webhooks/alerts/remote-source failures toast;
  copies go through copyText; modals get dialog roles and useDialog.
- Sagi: Ctrl/Cmd+B only when shown and not typing, default spot clear of
  row controls, arrow keys move it, reduced motion honoured; the dead
  /run launch link goes to the workspace.
This commit is contained in:
2026-10-05 13:22:08 +07:00
parent 03f1673fce
commit 6715fbd971
68 changed files with 4817 additions and 1374 deletions
+144 -38
View File
@@ -3,14 +3,27 @@
* @description Create/edit modal for text-file config artifacts (skills,
* agents, commands, output styles, memory). Tool-agnostic: it takes a
* `fetchContent` callback instead of reaching for any particular tool's API,
* so the same modal serves both the Claude Code and Codex config pages.
* so the same modal serves both the Claude Code and Codex config pages. It
* loads a file ONCE per path (never over the user's typing), refuses to save
* over a failed or truncated read, asks before discarding edits or overwriting
* a file changed on disk, and is a real dialog (focus trap, Escape).
* @author Nguyễn Ngọc Trí Vĩ <vinnt@smartgift.vn>
*/
import { useCallback, useEffect, useState } from "react";
import { useCallback, useEffect, useRef, useState } from "react";
import { useTranslation } from "react-i18next";
import { Pencil, X, Save, AlertCircle } from "lucide-react";
import type { CcArtifactType } from "../../lib/api";
import { confirmDialog, confirmDiscard } from "../../lib/confirm";
import { useDialog } from "../../hooks/useDialog";
import { useUnsavedGuard } from "../../hooks/useUnsavedGuard";
/** What a fetcher may answer: the text, or the API's `{text, truncated}`. */
type Fetched = string | { text: string; truncated?: boolean };
const textOf = (r: Fetched) => (typeof r === "string" ? r : r.text);
/** Same rule the server applies to an artifact name. */
const NAME_RE = /^[A-Za-z0-9][A-Za-z0-9._-]{0,63}$/;
/** Claude Code's own scope union, kept as the default so existing callers
* (CcConfig.tsx) don't need to name it. Codex has no `auto-memory` scope —
@@ -48,7 +61,7 @@ interface EditorModalProps<
TScope extends string = DefaultScope,
> {
state: NonNullable<EditorState<TType, TScope>>;
fetchContent: (filePath: string) => Promise<string>;
fetchContent: (filePath: string) => Promise<Fetched>;
onClose: () => void;
onSave: (args: {
type: TType;
@@ -60,6 +73,8 @@ interface EditorModalProps<
/** Which `state.type` values are nameless singleton files. Defaults to
* Claude Code's own `["memory"]` so existing callers are unaffected. */
namelessTypes?: readonly string[];
/** Refuse the Project target (its folder is the plugin cache, wiped on update). */
projectDisabled?: boolean;
}
export function EditorModal<
@@ -71,6 +86,7 @@ export function EditorModal<
onClose,
onSave,
namelessTypes = DEFAULT_NAMELESS_TYPES,
projectDisabled = false,
}: EditorModalProps<TType, TScope>) {
const { t } = useTranslation("ccConfig");
const isCreate = state.mode === "create";
@@ -88,41 +104,110 @@ export function EditorModal<
const [loading, setLoading] = useState(!isCreate);
const [saving, setSaving] = useState(false);
const [error, setError] = useState<string | null>(null);
// "ok" once an edit's text is in; a failed or truncated load never saves —
// Save over a failed load wrote an EMPTY file, over a truncated one a cut file.
const [loadState, setLoadState] = useState<"ok" | "failed" | "truncated">(
isCreate ? "ok" : "failed"
);
// The text as opened; `dirty` and the changed-on-disk check compare to it.
const original = useRef<string>(isCreate ? state.template : "");
const panelRef = useRef<HTMLDivElement>(null);
const titleId = "cc-editor-title";
const dirty = !loading && content !== original.current;
useUnsavedGuard(dirty);
// For edit mode, fetch the actual file content
useEffect(() => {
if (state.mode === "edit") {
setLoading(true);
fetchContent(state.filePath)
.then((text) => {
setContent(text);
setLoading(false);
})
.catch((err: unknown) => {
const msg = err instanceof Error ? err.message : "unknown";
setError(msg);
setLoading(false);
});
}
}, [state, fetchContent]);
// Read through a ref: callers pass an inline fetcher, and a dependency on it
// reloaded the file on every parent render — overwriting the user's typing.
const fetchRef = useRef(fetchContent);
fetchRef.current = fetchContent;
const editPath = state.mode === "edit" ? state.filePath : null;
// Esc to close
// `t` through a ref too: a language switch must not re-run the load below.
const tRef = useRef(t);
tRef.current = t;
// For edit mode, fetch the file once per path.
useEffect(() => {
const onKey = (e: KeyboardEvent) => {
if (e.key === "Escape") onClose();
if (editPath === null) return;
let live = true;
setLoading(true);
fetchRef
.current(editPath)
.then((r) => {
if (!live) return;
const text = textOf(r);
original.current = text;
setContent(text);
const cut = typeof r !== "string" && !!r.truncated;
setLoadState(cut ? "truncated" : "ok");
if (cut) setError(tRef.current("edit.truncatedReadOnly"));
setLoading(false);
})
.catch((err: unknown) => {
if (!live) return;
const msg = err instanceof Error ? err.message : "unknown";
setLoadState("failed");
setError(tRef.current("edit.loadError", { message: msg }));
setLoading(false);
});
return () => {
live = false;
};
window.addEventListener("keydown", onKey);
return () => window.removeEventListener("keydown", onKey);
}, [onClose]);
}, [editPath]);
const requestClose = useCallback(async () => {
if (dirty && !(await confirmDiscard())) return;
onClose();
}, [dirty, onClose]);
// Escape closes — but not while typing in the textarea, where it only leaves
// the field (an editor's Escape must never cost a draft).
useDialog(true, panelRef, () => {
const el = document.activeElement;
if (el instanceof HTMLTextAreaElement) {
el.blur();
return;
}
void requestClose();
});
const handleSave = useCallback(async () => {
setSaving(true);
setError(null);
try {
if (!isNameless && state.mode === "create" && !name) {
setError(t("edit.nameLabel"));
setSaving(false);
return;
if (!isNameless && state.mode === "create") {
if (!name.trim()) {
setError(t("edit.nameRequired"));
return;
}
if (!isAutoMemory && !NAME_RE.test(name)) {
setError(t("edit.nameInvalid"));
return;
}
}
// The file changed on disk since it was opened (a running session, a
// terminal): say so instead of silently overwriting that change.
if (state.mode === "edit") {
const fresh = await fetchRef
.current(state.filePath)
.then(textOf)
.catch(() => null);
// Could not re-read it: say so rather than saving blind.
const ask =
fresh === null
? {
title: t("edit.unverifiedTitle"),
message: t("edit.unverifiedBody"),
confirmLabel: t("edit.saveAnyway"),
}
: fresh !== original.current
? {
title: t("edit.changedOnDiskTitle"),
message: t("edit.changedOnDiskBody"),
confirmLabel: t("edit.overwrite"),
}
: null;
if (ask && !(await confirmDialog(ask))) return;
}
// For auto-memory creates, append a .md extension when the user omits it.
const createName = isAutoMemory && !/\.md$/i.test(name) ? `${name}.md` : name;
@@ -140,13 +225,14 @@ export function EditorModal<
content,
project: state.project,
});
original.current = content;
} catch (err: unknown) {
const msg = err instanceof Error ? err.message : "unknown";
setError(t("edit.writeError", { message: msg }));
} finally {
setSaving(false);
}
}, [state, targetScope, name, content, isAutoMemory, onSave, t]);
}, [state, targetScope, name, content, isAutoMemory, isNameless, onSave, t]);
const titleText = isCreate
? isAutoMemory
@@ -156,18 +242,25 @@ export function EditorModal<
return (
<div
className="fixed inset-0 bg-black/60 z-40 flex items-center justify-center p-4"
onClick={onClose}
className="fixed inset-0 bg-surface-0/70 z-50 flex items-center justify-center p-4"
onClick={() => void requestClose()}
>
<div
ref={panelRef}
role="dialog"
aria-modal="true"
aria-labelledby={titleId}
className="relative w-full max-w-4xl max-h-[90vh] rounded-xl border border-border bg-surface-1 flex flex-col"
onClick={(e) => e.stopPropagation()}
>
<div className="flex items-center gap-2 border-b border-border px-4 py-2.5">
<Pencil className="w-4 h-4 text-fg-muted" />
<span className="text-sm font-medium text-fg-primary flex-1 truncate">{titleText}</span>
<span id={titleId} className="text-sm font-medium text-fg-primary flex-1 truncate">
{titleText}
</span>
<button
onClick={onClose}
type="button"
onClick={() => void requestClose()}
className="text-fg-secondary hover:text-fg-primary p-1 rounded-md hover:bg-surface-3"
aria-label={t("common.close")}
>
@@ -214,8 +307,14 @@ export function EditorModal<
{(["user", "project"] as const).map((s) => (
<button
key={s}
type="button"
aria-pressed={targetScope === s}
disabled={s === "project" && projectDisabled}
title={
s === "project" && projectDisabled ? t("scope.projectInCache") : undefined
}
onClick={() => setTargetScope(s)}
className={`px-3 py-1 text-[11px] font-medium rounded ${
className={`px-3 py-1 text-[11px] font-medium rounded disabled:opacity-40 disabled:cursor-not-allowed ${
targetScope === s
? "bg-accent/20 text-accent border border-accent/30"
: "text-fg-secondary hover:text-fg-primary"
@@ -240,6 +339,8 @@ export function EditorModal<
<textarea
value={content}
onChange={(e) => setContent(e.target.value)}
readOnly={loadState !== "ok"}
aria-label={t("edit.contentLabel")}
spellCheck={false}
className="w-full h-72 bg-surface-2 border border-border rounded-md px-3 py-2 text-[11px] font-mono text-fg-primary placeholder:text-fg-muted focus:outline-none focus:border-accent/50 resize-y"
/>
@@ -247,7 +348,10 @@ export function EditorModal<
</div>
{error && (
<div className="rounded-md border border-status-danger/40 bg-status-danger/10 px-3 py-2 text-xs text-status-danger inline-flex items-center gap-2">
<div
role="alert"
className="rounded-md border border-status-danger/40 bg-status-danger/10 px-3 py-2 text-xs text-status-danger inline-flex items-center gap-2"
>
<AlertCircle className="w-3.5 h-3.5" />
{error}
</div>
@@ -256,14 +360,16 @@ export function EditorModal<
<div className="border-t border-border px-4 py-3 flex items-center justify-end gap-2">
<button
onClick={onClose}
type="button"
onClick={() => void requestClose()}
className="text-[12px] font-medium px-3 py-1.5 rounded-md border border-border bg-surface-2 hover:bg-surface-3 text-fg-secondary"
>
{t("edit.cancel")}
</button>
<button
type="button"
onClick={handleSave}
disabled={saving || loading}
disabled={saving || loading || loadState !== "ok"}
className="text-[12px] font-medium px-3 py-1.5 rounded-md border border-accent/40 bg-accent/15 hover:bg-accent/25 text-accent inline-flex items-center gap-1.5 disabled:opacity-60"
>
<Save className="w-3.5 h-3.5" />