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(desktop): close built-in skill review gaps

xd-bobo1d1da35b8945
diff --git a/apps/desktop/resources/system-skills/cindy-skill-creator/scripts/_frontmatter.py b/apps/desktop/resources/system-skills/cindy-skill-creator/scripts/_frontmatter.py
index 84df6e2309..20034aed06 100644
--- a/apps/desktop/resources/system-skills/cindy-skill-creator/scripts/_frontmatter.py
+++ b/apps/desktop/resources/system-skills/cindy-skill-creator/scripts/_frontmatter.py
@@ -49,11 +49,15 @@ def _strip_plain_comment(value):
return value.strip()
-def _parse_flow_collection(value):
- stack = []
+def _split_flow_items(value):
+ """Split one flow collection without losing nested collections or quotes."""
+ closing = "]" if value.startswith("[") else "}"
+ stack = [closing]
quote = None
escaped = False
- index = 0
+ items = []
+ item_start = 1
+ index = 1
while index < len(value):
char = value[index]
if quote == '"':
@@ -75,15 +79,93 @@ def _parse_flow_collection(value):
elif char in "]}":
if not stack or stack.pop() != char:
raise FrontmatterError(f"Mismatched flow delimiter '{char}'")
- if not stack and value[index + 1 :].strip():
- raise FrontmatterError("Unexpected content after flow collection")
+ if not stack:
+ if value[index + 1 :].strip():
+ raise FrontmatterError("Unexpected content after flow collection")
+ final_item = value[item_start:index].strip()
+ if final_item:
+ items.append(final_item)
+ elif item_start != 1 and not items:
+ raise FrontmatterError("Empty flow collection entry")
+ return items
+ elif char == "," and len(stack) == 1:
+ item = value[item_start:index].strip()
+ if not item:
+ raise FrontmatterError("Empty flow collection entry")
+ items.append(item)
+ item_start = index + 1
index += 1
if quote is not None or escaped:
raise FrontmatterError("Unterminated quoted scalar in flow collection")
+ raise FrontmatterError(f"Unterminated flow collection, expected '{stack[-1]}'")
+
+
+def _split_flow_mapping_entry(value, required=False):
+ """Find a flow-mapping colon without mistaking nested values or URLs for it."""
+ stack = []
+ quote = None
+ escaped = False
+ index = 0
+ while index < len(value):
+ char = value[index]
+ if quote == '"':
+ if escaped:
+ escaped = False
+ elif char == "\\":
+ escaped = True
+ elif char == '"':
+ quote = None
+ elif quote == "'":
+ if char == "'" and index + 1 < len(value) and value[index + 1] == "'":
+ index += 1
+ elif char == "'":
+ quote = None
+ elif char in {'"', "'"}:
+ quote = char
+ elif char in "[{":
+ stack.append("]" if char == "[" else "}")
+ elif char in "]}":
+ if not stack or stack.pop() != char:
+ raise FrontmatterError(f"Mismatched flow delimiter '{char}'")
+ elif char == ":" and not stack and (
+ required
+ or index + 1 == len(value)
+ or value[index + 1].isspace()
+ or value.lstrip().startswith(('"', "'"))
+ ):
+ return value[:index], value[index + 1 :]
+ index += 1
+ if quote is not None or escaped:
+ raise FrontmatterError("Unterminated quoted scalar")
if stack:
raise FrontmatterError(f"Unterminated flow collection, expected '{stack[-1]}'")
- return [] if value.startswith("[") else {}
+ return None
+
+
+def _validate_flow_mapping_entry(value, required):
+ mapping_entry = _split_flow_mapping_entry(value, required)
+ if mapping_entry is None:
+ if required:
+ raise FrontmatterError("Flow mapping entry is missing ':'")
+ _parse_scalar(value)
+ return
+
+ raw_key, raw_value = mapping_entry
+ if not raw_key.strip():
+ raise FrontmatterError("Flow mapping entry is missing a key")
+ key = _parse_scalar(raw_key.strip())
+ if not isinstance(key, (str, int, float, bool)):
+ raise FrontmatterError("Invalid flow mapping key")
+ _parse_scalar(raw_value.strip())
+
+
+def _parse_flow_collection(value):
+ items = _split_flow_items(value)
+ is_mapping = value.startswith("{")
+ for item in items:
+ _validate_flow_mapping_entry(item, required=is_mapping)
+ return {} if is_mapping else []
def _parse_scalar(raw):
diff --git a/apps/desktop/src/main/__tests__/authPassiveSharedInstance.test.ts b/apps/desktop/src/main/__tests__/authPassiveSharedInstance.test.ts
index 116be7ff1c..dfeeb3a6f9 100644
--- a/apps/desktop/src/main/__tests__/authPassiveSharedInstance.test.ts
+++ b/apps/desktop/src/main/__tests__/authPassiveSharedInstance.test.ts
@@ -226,6 +226,13 @@ describe('passive shared-userData instance auth isolation', () => {
expect(beforeEnsureReady).not.toContain('continuing with cloud database');
});
+ it('启动期共享 Skill 投影通过 owner 边界保护入口执行', () => {
+ expect(bootstrapSource).toContain(
+ 'await desktopClaudeAuthAdapter.ensureSharedGlobalSkills();',
+ );
+ expect(bootstrapSource).not.toContain('await prepareSharedGlobalSkillLinks();');
+ });
+
it('relogin marker:passive 不消费整机一份的 marker,也不删 primary 的 token', () => {
const start = authSource.indexOf('const reloginFlag = readReloginFlag();');
const end = authSource.indexOf('// Old Feishu-auth refresh tokens', start);
diff --git a/apps/desktop/src/main/bootstrap-electron.ts b/apps/desktop/src/main/bootstrap-electron.ts
index e72c5a3652..5968627276 100644
--- a/apps/desktop/src/main/bootstrap-electron.ts
+++ b/apps/desktop/src/main/bootstrap-electron.ts
@@ -583,11 +583,11 @@ import {
resolveBundledSystemSkillsRoot,
} from './maker-host/built-in-skills.js';
import { isCindyLearnSkillEnabled } from './skillhub/activationPreferences';
-import { prepareSharedGlobalSkillLinks } from './maker-host/shared-global-skills.js';
// Maker Core 一阶段重构(新链路)—— 静态 import 避免 dynamic import 触发 vite chunking
// 让 imageProtocol 等需要 app.ready 前注册的模块跑在错误时机。getMaker() 是 lazy 的,
// 静态 import 不会触发 Maker / Agent 的实例化。
import {
+ desktopClaudeAuthAdapter,
getMaker as getMakerCore,
getMakerIfReady,
resetMaker,
@@ -8601,10 +8601,7 @@ app.on('ready', async () => {
for (const warning of prepared.warnings) {
createLogger('built-in-skills').warn('built-in Skill preparation warning', { warning });
}
- const shared = await prepareSharedGlobalSkillLinks();
- for (const warning of shared.warnings) {
- createLogger('built-in-skills').warn('shared Skill projection warning', { warning });
- }
+ await desktopClaudeAuthAdapter.ensureSharedGlobalSkills();
} catch (error) {
// A broken optional Skill must not block the desktop from starting.
createLogger('built-in-skills').warn('built-in Skill preparation failed', {
diff --git a/apps/desktop/src/main/skillhub/__tests__/registerIpcUsage.test.ts b/apps/desktop/src/main/skillhub/__tests__/registerIpcUsage.test.ts
index 39ec9fe85e..7027d78a71 100644
--- a/apps/desktop/src/main/skillhub/__tests__/registerIpcUsage.test.ts
+++ b/apps/desktop/src/main/skillhub/__tests__/registerIpcUsage.test.ts
@@ -6,7 +6,11 @@ import { afterAll, beforeEach, describe, expect, it, vi } from 'vitest';
const fixtureRoot = fs.mkdtempSync(path.join(os.tmpdir(), 'skillhub-ipc-management-'));
afterAll(() => fs.rmSync(fixtureRoot, { recursive: true, force: true }));
const setCindySkillEnabled = vi.fn(async () => undefined);
-vi.mock('../activationPreferences', () => ({ setCindySkillEnabled }));
+const isCindyLearnSkillEnabled = vi.fn(() => true);
+vi.mock('../activationPreferences', () => ({
+ isCindyLearnSkillEnabled,
+ setCindySkillEnabled,
+}));
const handlers = new Map<string, (...args: unknown[]) => unknown>();
const showOpenDialog = vi.fn();
@@ -147,6 +151,7 @@ describe('registerSkillhubIpc usage handlers', () => {
ownerState.generation = 1;
ownerState.pending = false;
installServiceMocks.listPendingUninstallCleanups.mockReturnValue([]);
+ isCindyLearnSkillEnabled.mockReturnValue(true);
handlers.clear();
vi.clearAllMocks();
renameLocalSkill.mockReset();
@@ -374,6 +379,20 @@ describe('registerSkillhubIpc usage handlers', () => {
expect(afterDestroy).toMatchObject({ success: false });
});
+ it('returns the Learn activation preference even when discovery fails', async () => {
+ const sender = { id: 91, on: vi.fn(), once: vi.fn() };
+ isCindyLearnSkillEnabled.mockReturnValue(false);
+ scanAllSkills.mockRejectedValueOnce(new Error('scan failed'));
+
+ await expect(
+ handlers.get('skillhub:scan')?.({ sender }, { projects: [] }),
+ ).resolves.toEqual({
+ success: false,
+ error: 'scan failed',
+ learnSkillEnabled: false,
+ });
+ });
+
it('grants read-only access to a Main-attested built-in with no discovery alias', async () => {
const builtInRoot = path.join(fixtureRoot, 'shared-system-skills', 'learn');
const builtInFile = path.join(builtInRoot, 'SKILL.md');
diff --git a/apps/desktop/src/main/skillhub/registerIpc.ts b/apps/desktop/src/main/skillhub/registerIpc.ts
index 3f41105148..5f03964873 100644
--- a/apps/desktop/src/main/skillhub/registerIpc.ts
+++ b/apps/desktop/src/main/skillhub/registerIpc.ts
@@ -1,7 +1,7 @@
import fs from 'node:fs';
import { t } from '../i18n.js';
import { throwIpcError } from '../utils/ipcValidate';
-import { setCindySkillEnabled } from './activationPreferences';
+import { isCindyLearnSkillEnabled, setCindySkillEnabled } from './activationPreferences';
import { inspectLocalSkillTarget, isLocalSkillTargetCurrent, isPluginManagedSkillPath, type LocalSkillTarget } from './localSkillTarget';
import { tryAcquireSkillInstallLock } from './installLock';
import { randomUUID } from 'node:crypto';
@@ -502,13 +502,22 @@ export function registerSkillhubIpc(options: RegisterSkillhubIpcOptions): void {
for (const { token } of pendingCleanups) {
cleanupGrants.set(cleanupGrantKey(event.sender.id, token), { ownerId: scanOwnerId, senderId: event.sender.id });
}
- return { success: true, ...result, pendingCleanups };
+ return {
+ success: true,
+ ...result,
+ pendingCleanups,
+ learnSkillEnabled: isCindyLearnSkillEnabled(),
+ };
}
- return { success: true, ...result };
+ return { success: true, ...result, learnSkillEnabled: isCindyLearnSkillEnabled() };
} catch (err) {
const message = err instanceof Error ? err.message : String(err);
log.error('[skillhub:scan] failed:', err);
- return { success: false, error: message };
+ return {
+ success: false,
+ error: message,
+ learnSkillEnabled: isCindyLearnSkillEnabled(),
+ };
}
},
);
diff --git a/apps/desktop/src/preload/preload.ts b/apps/desktop/src/preload/preload.ts
index afda73b708..c34b91bf39 100644
--- a/apps/desktop/src/preload/preload.ts
+++ b/apps/desktop/src/preload/preload.ts
@@ -3019,6 +3019,7 @@ contextBridge.exposeInMainWorld('electronAPI', {
skills?: import('../main/skillhub/scanner').Skill[];
sources?: import('../main/skillhub/scanner').SourceReport[];
pendingCleanups?: Array<{ token: string; name: string }>;
+ learnSkillEnabled?: boolean;
}> => ipcRenderer.invoke('skillhub:scan', params),
readSkill: (params: {
diff --git a/apps/desktop/src/renderer/features/skillhub/SkillhubHomeView.tsx b/apps/desktop/src/renderer/features/skillhub/SkillhubHomeView.tsx
index 03ccdde6c5..463fce5669 100644
--- a/apps/desktop/src/renderer/features/skillhub/SkillhubHomeView.tsx
+++ b/apps/desktop/src/renderer/features/skillhub/SkillhubHomeView.tsx
@@ -31,7 +31,6 @@ import {
import { buildLocalSkillRoute, findLocalSkillByPath } from './lib/localRoutes';
import {
builtInSkillDescriptionKey,
- isBuiltInLearnSkillEnabled,
prioritizeCindyBuiltInSkills,
} from './lib/builtInSkillPresentation';
import { refresh as refreshSkillhub, useSkillhub } from './hooks/useSkillhub';
@@ -81,7 +80,7 @@ export function SkillhubHomeView({
} = {}) {
const { t } = useTranslation();
const navigate = useNavigate();
- const { skills, projects, bootstrapped, syncResults } = useSkillhub();
+ const { skills, projects, bootstrapped, learnSkillEnabled, syncResults } = useSkillhub();
const [query, setQuery] = useState('');
const normalizedQuery = query.trim().toLocaleLowerCase();
@@ -482,7 +481,7 @@ export function SkillhubHomeView({
}
onClone={handleClone}
onManageAction={management.handleManageAction}
- learnSkillEnabled={isBuiltInLearnSkillEnabled(skills, bootstrapped)}
+ learnSkillEnabled={learnSkillEnabled}
/>
<MarketManagementDialogs controller={management} />
<InstallTargetPicker
diff --git a/apps/desktop/src/renderer/features/skillhub/SkillhubMarketListView.tsx b/apps/desktop/src/renderer/features/skillhub/SkillhubMarketListView.tsx
index c008ed8bdf..6421db9bf3 100644
--- a/apps/desktop/src/renderer/features/skillhub/SkillhubMarketListView.tsx
+++ b/apps/desktop/src/renderer/features/skillhub/SkillhubMarketListView.tsx
@@ -31,7 +31,6 @@ import { syncMarketPreviewSelection } from './lib/marketPreviewSync';
import { useAuth } from '@/contexts/AuthContext';
import { CATEGORY_ALL } from '../../../shared/skillhubCategory';
import { useSkillhubIdentityPolicy } from './hooks/useSkillhubIdentityPolicy';
-import { isBuiltInLearnSkillEnabled } from './lib/builtInSkillPresentation';
const FILTER_CHIP_STYLE = { height: '32px', padding: '0 12px', fontSize: '12px' };
// Must match the global native scrollbar width in styles/globals.css.
@@ -78,7 +77,7 @@ export function SkillhubMarketListView() {
function SkillhubMarketListViewInner() {
const { t } = useTranslation();
const { user, isInitializing } = useAuth();
- const { skills: localSkills, bootstrapped: skillhubBootstrapped } = useSkillhub();
+ const { skills: localSkills, learnSkillEnabled } = useSkillhub();
const identityPolicy = useSkillhubIdentityPolicy(user);
const location = useLocation();
const navigate = useNavigate();
@@ -507,7 +506,7 @@ function SkillhubMarketListViewInner() {
: 'none'}
onClone={handleClone}
onManageAction={management.handleManageAction}
- learnSkillEnabled={isBuiltInLearnSkillEnabled(localSkills, skillhubBootstrapped)}
+ learnSkillEnabled={learnSkillEnabled}
/>
<MarketManagementDialogs controller={management} />
</div>
diff --git a/apps/desktop/src/renderer/features/skillhub/hooks/__tests__/useSkillhubOwner.test.ts b/apps/desktop/src/renderer/features/skillhub/hooks/__tests__/useSkillhubOwner.test.ts
index 133094c7e1..36ad2ae82d 100644
--- a/apps/desktop/src/renderer/features/skillhub/hooks/__tests__/useSkillhubOwner.test.ts
+++ b/apps/desktop/src/renderer/features/skillhub/hooks/__tests__/useSkillhubOwner.test.ts
@@ -1,5 +1,6 @@
// @vitest-environment jsdom
+import { act, renderHook } from '@testing-library/react';
import { beforeEach, describe, expect, it, vi } from 'vitest';
import { toast, type ToastOptions } from '@/lib/toast';
@@ -13,16 +14,31 @@ vi.mock('../useSkillSync', () => ({
invalidateSkillSyncRequests: vi.fn(),
}));
-import { bootstrapSkillhub, refresh, reset, setSkillhubDataOwner } from '../useSkillhub';
+import {
+ bootstrapSkillhub,
+ refresh,
+ reset,
+ setSkillhubDataOwner,
+ useSkillhub,
+} from '../useSkillhub';
describe('SkillHub data-owner bootstrap', () => {
const scan = vi.fn();
beforeEach(() => {
vi.clearAllMocks();
- scan.mockResolvedValue({ success: true, skills: [], sources: [] });
+ scan.mockResolvedValue({
+ success: true,
+ skills: [],
+ sources: [],
+ learnSkillEnabled: true,
+ });
(window as unknown as { electronAPI: unknown }).electronAPI = {
- skillhub: { scan },
+ skillhub: {
+ scan,
+ onLocalStateChanged: vi.fn(() => vi.fn()),
+ },
+ onAuthStateChange: vi.fn(() => vi.fn()),
};
});
@@ -81,4 +97,20 @@ describe('SkillHub data-owner bootstrap', () => {
await expect(second).resolves.toEqual([latestSkill]);
await expect(first).resolves.toEqual([latestSkill]);
});
+
+ it('keeps Learn availability aligned with its preference when scanning fails', async () => {
+ reset();
+ scan.mockResolvedValue({
+ success: false,
+ error: 'scan failed',
+ learnSkillEnabled: false,
+ });
+ const { result } = renderHook(() => useSkillhub());
+
+ await act(async () => {
+ await refresh();
+ });
+
+ expect(result.current.learnSkillEnabled).toBe(false);
+ });
});
diff --git a/apps/desktop/src/renderer/features/skillhub/hooks/useSkillhub.ts b/apps/desktop/src/renderer/features/skillhub/hooks/useSkillhub.ts
index abdce633d1..d72cde3c6e 100644
--- a/apps/desktop/src/renderer/features/skillhub/hooks/useSkillhub.ts
+++ b/apps/desktop/src/renderer/features/skillhub/hooks/useSkillhub.ts
@@ -39,6 +39,8 @@ interface SkillhubState {
projects: SkillhubProject[];
/** True once a first scan has completed (success or failure). */
bootstrapped: boolean;
+ /** Device/profile-local activation preference for Cindy's built-in Learn Skill. */
+ learnSkillEnabled: boolean;
/** v0.2.1: sync results map keyed by skill name */
syncResults: Map<string, SkillhubSyncResult>;
/** v0.2.1: error from last sync attempt */
@@ -57,6 +59,7 @@ let state: SkillhubState = {
error: null,
projects: [],
bootstrapped: false,
+ learnSkillEnabled: true,
syncResults: new Map(),
syncError: null,
availableUninstalledCount: 0,
@@ -89,6 +92,9 @@ export function refresh(): Promise<SkillhubSkill[]> {
if (myId !== scanRequestId) {
return latestScan?.id === scanRequestId ? latestScan.promise : state.skills;
}
+ const learnSkillEnabled = typeof result.learnSkillEnabled === 'boolean'
+ ? result.learnSkillEnabled
+ : state.learnSkillEnabled;
if (result.success) {
syncUninstallCleanupNotices(result.pendingCleanups ?? [], refresh);
const skills = result.skills ?? [];
@@ -97,6 +103,7 @@ export function refresh(): Promise<SkillhubSkill[]> {
sources: result.sources ?? [],
loading: false,
bootstrapped: true,
+ learnSkillEnabled,
});
return skills;
}
@@ -104,6 +111,7 @@ export function refresh(): Promise<SkillhubSkill[]> {
error: result.error ?? 'scan failed with no error message',
loading: false,
bootstrapped: true,
+ learnSkillEnabled,
});
return state.skills;
} catch (err) {
@@ -210,6 +218,7 @@ export function reset(): void {
error: null,
projects: [],
bootstrapped: false,
+ learnSkillEnabled: true,
syncResults: new Map(),
syncError: null,
availableUninstalledCount: 0,
diff --git a/apps/desktop/src/renderer/features/skillhub/lib/__tests__/builtInSkillPresentation.test.ts b/apps/desktop/src/renderer/features/skillhub/lib/__tests__/builtInSkillPresentation.test.ts
index 6690633a9b..9f96c6e51d 100644
--- a/apps/desktop/src/renderer/features/skillhub/lib/__tests__/builtInSkillPresentation.test.ts
+++ b/apps/desktop/src/renderer/features/skillhub/lib/__tests__/builtInSkillPresentation.test.ts
@@ -1,10 +1,7 @@
import { describe, expect, it } from 'vitest';
import { CINDY_LEARN_SOURCE_DESCRIPTION } from '../../../../../shared/cindyBuiltInSkills';
-import {
- isBuiltInLearnSkillEnabled,
- prioritizeCindyBuiltInSkills,
-} from '../builtInSkillPresentation';
+import { prioritizeCindyBuiltInSkills } from '../builtInSkillPresentation';
describe('prioritizeCindyBuiltInSkills', () => {
it('puts Cindy official Skills first in their product order and keeps user order stable', () => {
@@ -38,30 +35,3 @@ describe('prioritizeCindyBuiltInSkills', () => {
]);
});
});
-
-describe('isBuiltInLearnSkillEnabled', () => {
- it('waits for the local scan, then follows only the official Learn entry', () => {
- expect(isBuiltInLearnSkillEnabled([], false)).toBe(true);
- expect(isBuiltInLearnSkillEnabled([], true)).toBe(false);
- expect(isBuiltInLearnSkillEnabled([{
- name: 'learn',
- description: 'My own Learn workflow',
- scope: 'global',
- cindyEnabled: true,
- }], true)).toBe(false);
- expect(isBuiltInLearnSkillEnabled([{
- name: 'learn',
- description: CINDY_LEARN_SOURCE_DESCRIPTION,
- builtIn: true,
- scope: 'global',
- cindyEnabled: false,
- }], true)).toBe(false);
- expect(isBuiltInLearnSkillEnabled([{
- name: 'learn',
- description: CINDY_LEARN_SOURCE_DESCRIPTION,
- builtIn: true,
- scope: 'global',
- cindyEnabled: true,
- }], true)).toBe(true);
- });
-});
diff --git a/apps/desktop/src/renderer/features/skillhub/lib/builtInSkillPresentation.ts b/apps/desktop/src/renderer/features/skillhub/lib/builtInSkillPresentation.ts
index 2605bdbb8c..fbefdc50dc 100644
--- a/apps/desktop/src/renderer/features/skillhub/lib/builtInSkillPresentation.ts
+++ b/apps/desktop/src/renderer/features/skillhub/lib/builtInSkillPresentation.ts
@@ -51,22 +51,3 @@ export function prioritizeCindyBuiltInSkills<Skill extends {
})
.map(({ skill }) => skill);
}
-
-/** Keep SkillHub's Learn shortcut aligned with the built-in Skill toggle. */
-export function isBuiltInLearnSkillEnabled(
- skills: ReadonlyArray<{
- builtIn?: boolean;
- cindyEnabled?: boolean;
- name: string;
- description?: string;
- scope?: string;
- }>,
- bootstrapped: boolean,
-): boolean {
- return !bootstrapped || skills.some(
- (skill) =>
- skill.name === CINDY_LEARN_NAME
- && isCindyBuiltInSkillMetadata(skill)
- && skill.cindyEnabled !== false,
- );
-}
diff --git a/apps/desktop/src/renderer/vite-env.d.ts b/apps/desktop/src/renderer/vite-env.d.ts
index 3651ba1a17..2481e3af13 100644
--- a/apps/desktop/src/renderer/vite-env.d.ts
+++ b/apps/desktop/src/renderer/vite-env.d.ts
@@ -3225,6 +3225,7 @@ interface ElectronAPI {
skills?: SkillhubSkill[];
sources?: SkillhubSourceReport[];
pendingCleanups?: Array<{ token: string; name: string }>;
+ learnSkillEnabled?: boolean;
}>;
readSkill: (params: { mdPath: string }) => Promise<{
success: boolean;