Skip to content

armgit / cindy

Public Imported from GitHub
0

Consider it done. The open-source AI agent that works out of the box · 想到,就能做到。开源、开箱即用的 AI Agent。

fix(design-system): DS-11 安装弹窗消费 Escape 并收紧忙碌锁与色板候选语境

Kirozeng4cf6a141f5b2
diff --git a/apps/desktop/src/renderer/features/skillhub/components/InstallTargetPicker.tsx b/apps/desktop/src/renderer/features/skillhub/components/InstallTargetPicker.tsx
index 544d2aac4f..e2b8119cad 100644
--- a/apps/desktop/src/renderer/features/skillhub/components/InstallTargetPicker.tsx
+++ b/apps/desktop/src/renderer/features/skillhub/components/InstallTargetPicker.tsx
@@ -150,11 +150,21 @@ export function InstallTargetPicker({
return null;
})();
- const handleInstall = async (installPath?: string) => {
- if (installingRef.current) return;
+ // 忙碌锁全流程覆盖:“其他目录”从原生目录选择开始就要持锁,否则快速连点
+ // 可启动两个选择请求;选择晚返回时还会在锁释放后再次执行安装。
+ const beginInstallBusy = () => {
+ if (installingRef.current) return false;
installingRef.current = true;
- setBannerError(null);
setInstalling(true);
+ return true;
+ };
+ const endInstallBusy = () => {
+ installingRef.current = false;
+ setInstalling(false);
+ };
+
+ const performInstall = async (installPath?: string) => {
+ setBannerError(null);
try {
const res = await runAction({ name: skill.name, installPath, catalogScope: skill.catalogScope });
if (res.success) {
@@ -198,17 +208,28 @@ export function InstallTargetPicker({
}
} catch (err) {
setBannerError(err instanceof Error ? err.message : String(err));
+ }
+ };
+
+ const handleInstall = async (installPath?: string) => {
+ if (!beginInstallBusy()) return;
+ try {
+ await performInstall(installPath);
} finally {
- installingRef.current = false;
- setInstalling(false);
+ endInstallBusy();
}
};
const handleOtherDirectory = async () => {
- const r = await window.electronAPI.dialog.showOpenDirectory({});
- if (!r.success || !r.path) return;
- const installPath = joinSkillInstallPath(r.path, skill.name);
- await handleInstall(installPath);
+ if (!beginInstallBusy()) return;
+ try {
+ const r = await window.electronAPI.dialog.showOpenDirectory({});
+ if (!r.success || !r.path) return;
+ const installPath = joinSkillInstallPath(r.path, skill.name);
+ await performInstall(installPath);
+ } finally {
+ endInstallBusy();
+ }
};
const versionForSubtitle = String(skill.versionLabel ?? skill.latestVersion ?? '');
@@ -235,6 +256,12 @@ export function InstallTargetPicker({
if (returnFocusRef.current?.isConnected) returnFocusRef.current.focus();
}}
onEscapeKeyDown={(event) => {
+ // Escape 只归本弹窗消费:它可能叠在自带 window 级 Escape 监听的表面
+ // (如 SkillhubMarketPreviewPanel)之上。不拦截传播会让同一次 Escape
+ // 把底层面板一起关掉——opener 被卸载后无法归还焦点,安装中的关闭锁
+ // 也会被绕过。Radix 在 document 捕获阶段回调这里,先消费再决定是否
+ // 阻止关闭。
+ event.stopPropagation();
if (installingRef.current || event.isComposing || event.keyCode === 229) event.preventDefault();
}}
onPointerDownOutside={(event) => { if (installingRef.current) event.preventDefault(); }}
diff --git a/apps/desktop/src/renderer/features/skillhub/components/__tests__/InstallTargetPicker.test.tsx b/apps/desktop/src/renderer/features/skillhub/components/__tests__/InstallTargetPicker.test.tsx
index f176f3c447..207431d2ee 100644
--- a/apps/desktop/src/renderer/features/skillhub/components/__tests__/InstallTargetPicker.test.tsx
+++ b/apps/desktop/src/renderer/features/skillhub/components/__tests__/InstallTargetPicker.test.tsx
@@ -10,12 +10,18 @@ vi.mock('../../hooks/useProjectsForPicker', () => ({ useProjectsForPicker: () =>
vi.mock('@/components/ui/confirm-dialog-provider', () => ({ useConfirmDialog: () => ({ confirm: vi.fn() }) }));
afterEach(cleanup);
-function Harness({ runAction = vi.fn() }: { runAction?: () => Promise<{ success: false }> }) {
+function Harness({
+ runAction = vi.fn(),
+ onInstallComplete = vi.fn(),
+}: {
+ runAction?: () => Promise<{ success: false }>;
+ onInstallComplete?: () => void;
+}) {
const [open, setOpen] = useState(false);
return <>
<button onClick={() => setOpen(true)}>Open picker</button>
<button>Background action</button>
- <InstallTargetPicker open={open} skill={{ name: 'demo' }} onClose={() => setOpen(false)} onInstallComplete={vi.fn()} runAction={runAction} />
+ <InstallTargetPicker open={open} skill={{ name: 'demo' }} onClose={() => setOpen(false)} onInstallComplete={onInstallComplete} runAction={runAction} />
</>;
}
@@ -46,3 +52,69 @@ it('does not dismiss or repeat installation while the selected operation is pend
expect(screen.getByRole('dialog')).not.toBeNull();
expect((screen.getByRole('button', { name: 'skillhub.detail.cancel' }) as HTMLButtonElement).disabled).toBe(true);
});
+
+it('consumes Escape so an underlying window-level handler cannot close the host surface', async () => {
+ window.electronAPI = { skillhub: { registry: { getByName: vi.fn().mockResolvedValue({ success: false }) } } } as never;
+ // SkillhubMarketPreviewPanel keeps a window-level Escape listener mounted
+ // while the picker is stacked on top; the picker must consume the key
+ // itself instead of letting it reach the host surface.
+ const underlying = vi.fn();
+ window.addEventListener('keydown', underlying);
+ try {
+ render(<Harness />);
+ await userEvent.click(screen.getByText('Open picker'));
+ await userEvent.keyboard('{Escape}');
+ await waitFor(() => expect(screen.queryByRole('dialog')).toBeNull());
+ expect(underlying).not.toHaveBeenCalled();
+ } finally {
+ window.removeEventListener('keydown', underlying);
+ }
+});
+
+it('keeps consuming Escape while installing, so the underlying close lock cannot be bypassed', async () => {
+ window.electronAPI = { skillhub: { registry: { getByName: vi.fn().mockResolvedValue({ success: false }) } } } as never;
+ const underlying = vi.fn();
+ window.addEventListener('keydown', underlying);
+ const run = vi.fn(() => new Promise<{ success: false }>(() => {}));
+ try {
+ render(<Harness runAction={run} />);
+ await userEvent.click(screen.getByText('Open picker'));
+ fireEvent.click(screen.getByRole('button', { name: /skillhub.installPicker.global/ }));
+ await userEvent.keyboard('{Escape}');
+ expect(screen.getByRole('dialog')).not.toBeNull();
+ expect(underlying).not.toHaveBeenCalled();
+ } finally {
+ window.removeEventListener('keydown', underlying);
+ }
+});
+
+it('holds the busy lock across the other-directory flow, from selection to install completion', async () => {
+ let resolvePick: (value: { success: boolean; path?: string }) => void = () => {};
+ const showOpenDirectory = vi.fn(
+ () => new Promise<{ success: boolean; path?: string }>((resolve) => { resolvePick = resolve; }),
+ );
+ window.electronAPI = {
+ skillhub: { registry: { getByName: vi.fn().mockResolvedValue({ success: false }) } },
+ dialog: { showOpenDirectory },
+ } as never;
+ const onInstallComplete = vi.fn();
+ const run = vi.fn().mockResolvedValue({ success: true, absolutePath: '/tmp/skills/.agents/skills/demo' });
+ render(<Harness runAction={run} onInstallComplete={onInstallComplete} />);
+ await userEvent.click(screen.getByText('Open picker'));
+ const other = screen.getByRole('button', { name: 'skillhub.installPicker.otherDirectory' });
+ // Rapid double click: the lock is taken before the native dialog opens, so
+ // only one selection request can ever start.
+ fireEvent.click(other);fireEvent.click(other);
+ expect(showOpenDirectory).toHaveBeenCalledOnce();
+ expect((screen.getByRole('button', { name: 'skillhub.detail.cancel' }) as HTMLButtonElement).disabled).toBe(true);
+ // Cancelling the native dialog releases the lock; the picker stays open.
+ resolvePick({ success: false });
+ await waitFor(() => expect((screen.getByRole('button', { name: 'skillhub.detail.cancel' }) as HTMLButtonElement).disabled).toBe(false));
+ expect(screen.getByRole('dialog')).not.toBeNull();
+ // A second round picks a directory and installs exactly once.
+ fireEvent.click(other);
+ resolvePick({ success: true, path: '/tmp/skills' });
+ await waitFor(() => expect(onInstallComplete).toHaveBeenCalledOnce());
+ expect(run).toHaveBeenCalledOnce();
+ expect(run).toHaveBeenCalledWith({ name: 'demo', installPath: '/tmp/skills/.agents/skills/demo', catalogScope: undefined });
+});
diff --git a/scripts/__tests__/hardcoded-color-audit.test.mjs b/scripts/__tests__/hardcoded-color-audit.test.mjs
index 531e005842..dd9402707e 100644
--- a/scripts/__tests__/hardcoded-color-audit.test.mjs
+++ b/scripts/__tests__/hardcoded-color-audit.test.mjs
@@ -20,6 +20,19 @@ test('Tailwind palette candidates report light/dark variants without expanding b
assert.deepEqual(palette.map(hit => hit.value), ['bg-red-50', 'bg-red-950/30', 'text-red-600']);
assert.ok(palette.every(hit => hit.disposition === 'report'));
assert.deepEqual(inspect(`${renderer}components/Example.tsx`, '// text-red-500\n<div className="text-[var(--error-fg)]" />'), []);
+ // Braced className expressions (cn()/ternaries) are the same style context.
+ const assembly = inspect(`${renderer}components/Example.tsx`,
+ '<div className={cn("rounded-[4px]", danger && "bg-red-50 dark:text-red-600")} />');
+ assert.deepEqual(assembly.filter(hit => hit.rule === 'named-palette-candidate').map(hit => hit.value), ['bg-red-50', 'text-red-600']);
+ // Palette-shaped prose outside a className attribute is not a candidate:
+ // plain strings, other attributes, class assembly outside an attribute, and
+ // unparseable (fail-closed) expressions all stay out of the report.
+ for (const source of [
+ "const hint = '请用 text-red-500 标出错误';",
+ '<div aria-label="text-red-500" className="text-[var(--error-fg)]" />',
+ "const overlay = cn('bg-red-50');",
+ '<div className={"bg-red-50"',
+ ]) assert.deepEqual(inspect(`${renderer}components/Example.tsx`, source).filter(hit => hit.rule === 'named-palette-candidate'), [], source);
});
test('semantic colours, PR prose, URL and comments are not literals; numeric hex still is', () => {
diff --git a/scripts/shared/design-layer-report.mjs b/scripts/shared/design-layer-report.mjs
index 18095420b4..db6bd4f037 100644
--- a/scripts/shared/design-layer-report.mjs
+++ b/scripts/shared/design-layer-report.mjs
@@ -93,12 +93,48 @@ export function classifyDesignLayer({ member, layer, radius, evidence = false })
: { classification: 'registered-value-violation', reason: `${member}: this visible layer requires ${expected} at all four corners (DESIGN §5).` };
}
+/** `className`-bearing attributes are the literal style context this reporter
+ * recognises. A palette-shaped token anywhere else in the source — help text,
+ * test data, diagnostics prose — is not a class candidate, so reporting it
+ * would only add audit noise. Spans cover the quoted value and the whole
+ * balanced braced expression (cn()/ternaries included); string-aware brace
+ * counting keeps arbitrary values like rounded-[4px] from ending the span.
+ * Unparseable attributes fail closed: nothing inside becomes a candidate. */
+function classNameValueSpans(source) {
+ const spans = [];
+ const attribute = /\b[\w$]*[Cc]lassName\s*=\s*(?:"|'|\{)|\bclass\s*=\s*(?:"|')/g;
+ for (const match of source.matchAll(attribute)) {
+ const open = match[0][match[0].length - 1];
+ const start = match.index + match[0].length;
+ if (open === '{') {
+ let depth = 1, quote = '';
+ for (let i = start; i < source.length; i++) {
+ const char = source[i];
+ if (quote) {
+ if (char === '\\') i++;
+ else if (char === quote) quote = '';
+ continue;
+ }
+ if (char === '"' || char === "'" || char === '`') { quote = char; continue; }
+ if (char === '{') depth++;
+ else if (char === '}' && --depth === 0) { spans.push([start, i]); break; }
+ }
+ } else {
+ const close = source.indexOf(open, start);
+ if (close >= 0) spans.push([start, close]);
+ }
+ }
+ return spans;
+}
+
export function reportDesignLayers(file, source, changed, locate, spacingVariables) {
const findings = [];
// Candidate reporting only: a palette utility is not proof of its rendered
// role. Leave dynamic classes, CSS named values and exemptions to review.
const paletteUtility = /(?<![\w-])(?:bg|text|border|ring|fill|stroke|outline|decoration|shadow)-(?:slate|gray|zinc|neutral|stone|red|orange|amber|yellow|lime|green|emerald|teal|cyan|sky|blue|indigo|violet|purple|fuchsia|pink|rose)-(?:50|[1-9]00|950)(?:\/(?:\d+|\[[^\]\n]+\]))?(?![\w-])/g;
+ const classSpans = classNameValueSpans(source);
for (const match of source.matchAll(paletteUtility)) {
+ if (!classSpans.some(([start, end]) => match.index >= start && match.index < end)) continue;
const pos = locate(match.index);
if (!changed.has(pos.line)) continue;
findings.push({ file, ...pos, rule: 'named-palette-candidate', value: match[0], disposition: 'report',