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): bind Learn grants and publish Skills atomically

xd-bobo104eed4032cc
diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml
index 2265b8c2eb..8827a25809 100644
--- a/.github/workflows/ci.yml
+++ b/.github/workflows/ci.yml
@@ -231,6 +231,10 @@ jobs:
GITHUB_TOKEN: ${{ github.token }}
run: pnpm install:ripgrep
+ - name: Verify Windows atomic directory-entry replacement
+ if: matrix.shard == 1
+ run: node apps/desktop/scripts/check-windows-atomic-rename.mjs
+
# 保留 Windows 路径、进程与锁的自测覆盖,但两个分片只执行一次。
- name: Run Windows test runner self-tests
if: matrix.shard == 1
diff --git a/apps/desktop/forge.config.ts b/apps/desktop/forge.config.ts
index ab30e8a2c8..fefa31c9be 100644
--- a/apps/desktop/forge.config.ts
+++ b/apps/desktop/forge.config.ts
@@ -1155,6 +1155,30 @@ function buildWindowsTaskbarAddon(platform: ForgePlatform, arch: ForgeArch): voi
}
}
+function buildWindowsAtomicRenameHelper(platform: ForgePlatform, arch: ForgeArch): void {
+ if (process.platform !== 'win32' || platform !== 'win32') return;
+ const target = arch === 'arm64' ? 'aarch64-pc-windows-msvc' : arch === 'x64' ? 'x86_64-pc-windows-msvc' : null;
+ if (!target) throw new Error(`[forge] Unsupported Windows atomic rename architecture: ${arch}`);
+ const source = path.join(__dirname, 'native', 'windows-atomic-rename', 'main.rs');
+ const build = fs.mkdtempSync(path.join(os.tmpdir(), 'cindy-atomic-rename-build-'));
+ const output = path.join(build, 'cindy-windows-atomic-rename.exe');
+ try {
+ const userRustc = path.join(os.homedir(), '.cargo', 'bin', 'rustc.exe');
+ const result = spawnSync(fs.existsSync(userRustc) ? userRustc : 'rustc', [
+ source, '--edition=2021', '-C', 'opt-level=s', '-C', 'panic=abort',
+ '--target', target, '-o', output,
+ ], { stdio: 'inherit', windowsHide: true });
+ if (result.error || result.status !== 0) {
+ throw new Error(`[forge] Windows atomic rename build failed: ${result.error?.message ?? result.status}`);
+ }
+ const dest = path.join(__dirname, 'resources', 'tools', 'windows-atomic-rename');
+ fs.mkdirSync(dest, { recursive: true });
+ fs.copyFileSync(output, path.join(dest, 'cindy-windows-atomic-rename.exe'));
+ } finally {
+ fs.rmSync(build, { recursive: true, force: true });
+ }
+}
+
function buildWindowsInputHelper(kind: 'gamepad' | 'micro', platform: ForgePlatform, arch: ForgeArch): void {
if (process.platform !== 'win32' || platform !== 'win32') return;
const target = arch === 'arm64' ? 'aarch64-pc-windows-msvc' : arch === 'x64' ? 'x86_64-pc-windows-msvc' : null;
@@ -1701,6 +1725,7 @@ const config: ForgeConfig = {
buildMacVoiceInputTextInsertionHelper(platform, arch);
buildMacXboxGamepadHelper(platform, arch);
buildWindowsGamepadHelper(platform, arch);
+ buildWindowsAtomicRenameHelper(platform, arch);
buildWindowsTaskbarAddon(platform, arch);
buildMacVoiceInputModifierShortcutListener(platform, arch);
buildMacAgentIslandHelper(platform, arch);
diff --git a/apps/desktop/native/windows-atomic-rename/main.rs b/apps/desktop/native/windows-atomic-rename/main.rs
new file mode 100644
index 0000000000..041366f9dc
--- /dev/null
+++ b/apps/desktop/native/windows-atomic-rename/main.rs
@@ -0,0 +1,157 @@
+//! Atomically replace one Windows directory entry with another.
+//!
+//! Node's rename cannot replace an existing directory junction. FileRenameInfoEx
+//! with POSIX semantics publishes the replacement in one filesystem operation:
+//! old handles stay valid and every later open sees the new entry.
+
+#![cfg(windows)]
+
+use std::{
+ env,
+ ffi::c_void,
+ io,
+ mem::{align_of, size_of},
+ os::windows::ffi::OsStrExt,
+ path::{Path, PathBuf},
+ ptr,
+};
+
+type Handle = *mut c_void;
+
+#[link(name = "kernel32")]
+extern "system" {
+ fn CreateFileW(
+ file_name: *const u16,
+ desired_access: u32,
+ share_mode: u32,
+ security_attributes: *mut c_void,
+ creation_disposition: u32,
+ flags_and_attributes: u32,
+ template_file: Handle,
+ ) -> Handle;
+ fn SetFileInformationByHandle(
+ file: Handle,
+ information_class: i32,
+ information: *const c_void,
+ buffer_size: u32,
+ ) -> i32;
+ fn CloseHandle(object: Handle) -> i32;
+}
+
+const DELETE: u32 = 0x0001_0000;
+const FILE_SHARE_READ: u32 = 0x0000_0001;
+const FILE_SHARE_WRITE: u32 = 0x0000_0002;
+const FILE_SHARE_DELETE: u32 = 0x0000_0004;
+const OPEN_EXISTING: u32 = 3;
+const FILE_FLAG_OPEN_REPARSE_POINT: u32 = 0x0020_0000;
+const FILE_FLAG_BACKUP_SEMANTICS: u32 = 0x0200_0000;
+const FILE_RENAME_INFO_EX: i32 = 22;
+const FILE_RENAME_REPLACE_IF_EXISTS: u32 = 0x0000_0001;
+const FILE_RENAME_POSIX_SEMANTICS: u32 = 0x0000_0002;
+
+struct OwnedHandle(Handle);
+
+impl Drop for OwnedHandle {
+ fn drop(&mut self) {
+ unsafe { CloseHandle(self.0) };
+ }
+}
+
+fn align_up(value: usize, alignment: usize) -> usize {
+ (value + alignment - 1) & !(alignment - 1)
+}
+
+fn wide_null(path: &Path) -> Vec<u16> {
+ path.as_os_str().encode_wide().chain(Some(0)).collect()
+}
+
+fn absolute_same_parent(source: &Path, destination: &Path) -> io::Result<()> {
+ if !source.is_absolute() || !destination.is_absolute() {
+ return Err(io::Error::new(
+ io::ErrorKind::InvalidInput,
+ "paths must be absolute",
+ ));
+ }
+ if source == destination || source.parent() != destination.parent() {
+ return Err(io::Error::new(
+ io::ErrorKind::InvalidInput,
+ "source and destination must be distinct siblings",
+ ));
+ }
+ Ok(())
+}
+
+fn atomic_replace(source: &Path, destination: &Path) -> io::Result<()> {
+ absolute_same_parent(source, destination)?;
+ let source_wide = wide_null(source);
+ let handle = unsafe {
+ CreateFileW(
+ source_wide.as_ptr(),
+ DELETE,
+ FILE_SHARE_READ | FILE_SHARE_WRITE | FILE_SHARE_DELETE,
+ ptr::null_mut(),
+ OPEN_EXISTING,
+ FILE_FLAG_OPEN_REPARSE_POINT | FILE_FLAG_BACKUP_SEMANTICS,
+ ptr::null_mut(),
+ )
+ };
+ if handle as isize == -1 {
+ return Err(io::Error::last_os_error());
+ }
+ let _handle = OwnedHandle(handle);
+
+ let destination_wide: Vec<u16> = destination.as_os_str().encode_wide().collect();
+ let root_offset = align_up(size_of::<u32>(), align_of::<Handle>());
+ let length_offset = root_offset + size_of::<Handle>();
+ let name_offset = length_offset + size_of::<u32>();
+ let name_bytes = destination_wide
+ .len()
+ .checked_mul(size_of::<u16>())
+ .ok_or_else(|| {
+ io::Error::new(io::ErrorKind::InvalidInput, "destination path is too long")
+ })?;
+ let buffer_size = name_offset
+ .checked_add(name_bytes)
+ .ok_or_else(|| io::Error::new(io::ErrorKind::InvalidInput, "rename buffer is too large"))?;
+ let buffer_size_u32 = u32::try_from(buffer_size)
+ .map_err(|_| io::Error::new(io::ErrorKind::InvalidInput, "rename buffer is too large"))?;
+ let name_bytes_u32 = u32::try_from(name_bytes)
+ .map_err(|_| io::Error::new(io::ErrorKind::InvalidInput, "destination path is too long"))?;
+
+ let mut buffer = vec![0u8; buffer_size];
+ buffer[..4].copy_from_slice(
+ &(FILE_RENAME_REPLACE_IF_EXISTS | FILE_RENAME_POSIX_SEMANTICS).to_ne_bytes(),
+ );
+ buffer[length_offset..length_offset + 4].copy_from_slice(&name_bytes_u32.to_ne_bytes());
+ for (index, code_unit) in destination_wide.iter().enumerate() {
+ let offset = name_offset + index * 2;
+ buffer[offset..offset + 2].copy_from_slice(&code_unit.to_ne_bytes());
+ }
+
+ let succeeded = unsafe {
+ SetFileInformationByHandle(
+ handle,
+ FILE_RENAME_INFO_EX,
+ buffer.as_ptr().cast(),
+ buffer_size_u32,
+ )
+ };
+ if succeeded == 0 {
+ return Err(io::Error::last_os_error());
+ }
+ Ok(())
+}
+
+fn main() {
+ let mut args = env::args_os().skip(1);
+ let source = args.next().map(PathBuf::from);
+ let destination = args.next().map(PathBuf::from);
+ if source.is_none() || destination.is_none() || args.next().is_some() {
+ eprintln!("usage: cindy-windows-atomic-rename <source> <destination>");
+ std::process::exit(2);
+ }
+ if let Err(error) = atomic_replace(&source.unwrap(), &destination.unwrap()) {
+ eprintln!("atomic directory entry replacement failed: {error}");
+ std::process::exit(1);
+ }
+}
diff --git a/apps/desktop/scripts/check-windows-atomic-rename.mjs b/apps/desktop/scripts/check-windows-atomic-rename.mjs
new file mode 100644
index 0000000000..7f4d39f1fd
--- /dev/null
+++ b/apps/desktop/scripts/check-windows-atomic-rename.mjs
@@ -0,0 +1,65 @@
+import assert from 'node:assert/strict';
+import { spawn, spawnSync } from 'node:child_process';
+import fs from 'node:fs';
+import os from 'node:os';
+import path from 'node:path';
+import { fileURLToPath } from 'node:url';
+
+if (process.platform !== 'win32') {
+ console.log('Windows atomic rename check skipped on this platform.');
+ process.exit(0);
+}
+
+const scriptDir = path.dirname(fileURLToPath(import.meta.url));
+const source = path.join(scriptDir, '..', 'native', 'windows-atomic-rename', 'main.rs');
+const root = fs.mkdtempSync(path.join(os.tmpdir(), 'cindy-atomic-rename-check-'));
+const binary = path.join(root, 'cindy-windows-atomic-rename.exe');
+let oldHandle;
+
+try {
+ const compile = spawnSync('rustc', [
+ source,
+ '--edition=2021',
+ '-C', 'opt-level=s',
+ '-C', 'panic=abort',
+ '-o', binary,
+ ], { encoding: 'utf8', windowsHide: true });
+ assert.equal(compile.status, 0, compile.stderr || compile.stdout);
+
+ const first = path.join(root, 'first');
+ const second = path.join(root, 'second');
+ const active = path.join(root, '.active');
+ const replacement = path.join(root, '.active.next');
+ fs.mkdirSync(first);
+ fs.mkdirSync(second);
+ fs.writeFileSync(path.join(first, 'SKILL.md'), 'first');
+ fs.writeFileSync(path.join(second, 'SKILL.md'), 'second');
+ fs.symlinkSync(first, active, 'junction');
+ fs.symlinkSync(second, replacement, 'junction');
+
+ oldHandle = fs.openSync(path.join(active, 'SKILL.md'), 'r');
+ let missingObservations = 0;
+ const child = spawn(binary, [replacement, active], { windowsHide: true });
+ const poll = setInterval(() => {
+ if (!fs.existsSync(active)) missingObservations += 1;
+ }, 0);
+ const exitCode = await new Promise((resolve, reject) => {
+ child.once('error', reject);
+ child.once('exit', resolve);
+ });
+ clearInterval(poll);
+ assert.equal(exitCode, 0, 'native helper failed');
+ assert.equal(missingObservations, 0, '.active disappeared during publication');
+ assert.equal(fs.readFileSync(path.join(active, 'SKILL.md'), 'utf8'), 'second');
+ assert.equal(fs.existsSync(replacement), false);
+
+ const oldBytes = Buffer.alloc(5);
+ assert.equal(fs.readSync(oldHandle, oldBytes, 0, oldBytes.length, 0), 5);
+ assert.equal(oldBytes.toString(), 'first');
+ fs.closeSync(oldHandle);
+ oldHandle = undefined;
+ console.log('Windows atomic rename check passed.');
+} finally {
+ if (oldHandle !== undefined) fs.closeSync(oldHandle);
+ fs.rmSync(root, { recursive: true, force: true });
+}
diff --git a/apps/desktop/src/main/learn-host/__tests__/invocationGrant.test.ts b/apps/desktop/src/main/learn-host/__tests__/invocationGrant.test.ts
index 267dc79b43..49f97caf2e 100644
--- a/apps/desktop/src/main/learn-host/__tests__/invocationGrant.test.ts
+++ b/apps/desktop/src/main/learn-host/__tests__/invocationGrant.test.ts
@@ -6,18 +6,37 @@ import {
} from '../invocationGrant.js';
describe('Learn invocation grant', () => {
+ const grant = (sessionInstanceId = 'instance-1') => ({
+ version: 1 as const,
+ sessionInstanceId,
+ resolvedSkillPath: '/cindy/system-skills/v10/learn/SKILL.md',
+ });
const createPersistentConsumer = (
- readLatest: () => Promise<{ messageId: string; text: string }>,
+ readLatest: () => Promise<{
+ messageId: string;
+ text: string;
+ grant?: ReturnType<typeof grant> | null;
+ }>,
consumed = new Set<string>(),
- ) => createLearnInvocationGrantConsumer(
- readLatest,
- async (sessionId, messageId) => {
- const key = `${sessionId}\0${messageId}`;
- if (consumed.has(key)) return false;
- consumed.add(key);
- return true;
- },
- );
+ sessionInstanceId = 'instance-1',
+ ) => {
+ const consume = createLearnInvocationGrantConsumer(
+ async () => {
+ const latest = await readLatest();
+ return {
+ ...latest,
+ grant: latest.grant === undefined ? grant(sessionInstanceId) : latest.grant,
+ };
+ },
+ async (sessionId, messageId) => {
+ const key = `${sessionId}\0${messageId}`;
+ if (consumed.has(key)) return false;
+ consumed.add(key);
+ return true;
+ },
+ );
+ return (request: Parameters<typeof consume>[0]) => consume(request, sessionInstanceId);
+ };
it.each([
['/learn', { input: '', sourceKind: 'session' }],
@@ -101,6 +120,34 @@ describe('Learn invocation grant', () => {
});
});
+ it('rejects invocations without a main-attested dispatch snapshot', async () => {
+ const consume = createPersistentConsumer(async () => ({
+ messageId: 'message-1',
+ text: '/learn release flow',
+ grant: null,
+ }));
+
+ await expect(consume({
+ callerSessionId: 'session-1',
+ input: 'release flow',
+ sourceKind: 'freetext',
+ })).resolves.toMatchObject({ ok: false, errorCode: 'USER_REQUEST_REQUIRED' });
+ });
+
+ it('binds a dispatch snapshot to the exact in-memory Session instance', async () => {
+ const consume = createPersistentConsumer(async () => ({
+ messageId: 'message-1',
+ text: '/learn release flow',
+ grant: grant('old-instance'),
+ }));
+
+ await expect(consume({
+ callerSessionId: 'session-1',
+ input: 'release flow',
+ sourceKind: 'freetext',
+ })).resolves.toMatchObject({ ok: false, errorCode: 'USER_REQUEST_REQUIRED' });
+ });
+
it('rejects a persisted invocation after the consumer is recreated', async () => {
const consumed = new Set<string>();
const readLatest = async () => ({
diff --git a/apps/desktop/src/main/learn-host/invocationGrant.ts b/apps/desktop/src/main/learn-host/invocationGrant.ts
index c480c068b3..e3ffafa05d 100644
--- a/apps/desktop/src/main/learn-host/invocationGrant.ts
+++ b/apps/desktop/src/main/learn-host/invocationGrant.ts
@@ -19,6 +19,14 @@ export type LearnInvocationGrantResult =
interface LatestUserInvocation {
messageId: string;
text: string;
+ grant: CindyLearnInvocationGrant | null;
+}
+
+/** Main-owned snapshot of the Skill winner captured for one accepted user turn. */
+export interface CindyLearnInvocationGrant {
+ version: 1;
+ sessionInstanceId: string;
+ resolvedSkillPath: string;
}
type ReadLatestUserInvocation = (
@@ -28,6 +36,7 @@ type ReadLatestUserInvocation = (
type ConsumeUserInvocation = (
sessionId: string,
messageId: string,
+ sessionInstanceId: string,
) => Promise<boolean>;
const messageRowid = sql<number>`"messages"."rowid"`;
@@ -77,8 +86,11 @@ function matchesInvocation(
export function createLearnInvocationGrantConsumer(
readLatestUserInvocation: ReadLatestUserInvocation,
consumeUserInvocation: ConsumeUserInvocation,
-): (request: StartSkillLearningParams) => Promise<LearnInvocationGrantResult> {
- return async (request) => {
+): (
+ request: StartSkillLearningParams,
+ sessionInstanceId: string | undefined,
+) => Promise<LearnInvocationGrantResult> {
+ return async (request, sessionInstanceId) => {
let latest: LatestUserInvocation | null;
try {
latest = await readLatestUserInvocation(request.callerSessionId);
@@ -90,7 +102,15 @@ export function createLearnInvocationGrantConsumer(
};
}
const invocation = latest ? parseDirectLearnInvocation(latest.text) : null;
- if (!latest || !invocation || !matchesInvocation(invocation, request)) {
+ if (
+ !latest
+ || !invocation
+ || !sessionInstanceId
+ || latest.grant?.version !== 1
+ || latest.grant.sessionInstanceId !== sessionInstanceId
+ || !latest.grant.resolvedSkillPath
+ || !matchesInvocation(invocation, request)
+ ) {
return {
ok: false,
errorCode: 'USER_REQUEST_REQUIRED',
@@ -102,6 +122,7 @@ export function createLearnInvocationGrantConsumer(
consumed = await consumeUserInvocation(
request.callerSessionId,
latest.messageId,
+ sessionInstanceId,
);
} catch (error) {
return {
@@ -121,6 +142,24 @@ export function createLearnInvocationGrantConsumer(
};
}
+function parseLearnInvocationGrant(agentMeta: string | null): CindyLearnInvocationGrant | null {
+ if (!agentMeta) return null;
+ try {
+ const value = (JSON.parse(agentMeta) as { cindyLearnInvocation?: unknown }).cindyLearnInvocation;
+ if (!value || typeof value !== 'object') return null;
+ const grant = value as Partial<CindyLearnInvocationGrant>;
+ return grant.version === 1
+ && typeof grant.sessionInstanceId === 'string'
+ && grant.sessionInstanceId.length > 0
+ && typeof grant.resolvedSkillPath === 'string'
+ && grant.resolvedSkillPath.length > 0
+ ? grant as CindyLearnInvocationGrant
+ : null;
+ } catch {
+ return null;
+ }
+}
+
async function readLatestUserInvocation(
sessionId: string,
): Promise<LatestUserInvocation | null> {
@@ -129,7 +168,7 @@ async function readLatestUserInvocation(
throw Object.assign(new Error('DbClient not ready'), { code: 'HOST_NOT_READY' });
}
const [row] = await dbClient.drizzle
- .select({ id: messages.id, content: messages.content })
+ .select({ id: messages.id, content: messages.content, agentMeta: messages.agentMeta })
.from(messages)
.innerJoin(sessions, eq(messages.sessionId, sessions.id))
.where(
@@ -147,12 +186,14 @@ async function readLatestUserInvocation(
return {
messageId: row.id,
text: visibleMessageTextForConversationSearch('user', row.content),
+ grant: parseLearnInvocationGrant(row.agentMeta),
};
}
async function consumeUserInvocation(
sessionId: string,
messageId: string,
+ sessionInstanceId: string,
): Promise<boolean> {
const dbClient = tryGetDbClient();
if (!dbClient) {
@@ -175,8 +216,11 @@ async function consumeUserInvocation(
json_type(agent_meta) = 'object'
AND json_type(agent_meta, '$.cindyLearnInvocationConsumed') IS NULL
ELSE 0
- END`,
- [messageId, sessionId],
+ END
+ AND json_extract(agent_meta, '$.cindyLearnInvocation.version') = 1
+ AND json_extract(agent_meta, '$.cindyLearnInvocation.sessionInstanceId') = ?
+ AND json_type(agent_meta, '$.cindyLearnInvocation.resolvedSkillPath') = 'text'`,
+ [messageId, sessionId, sessionInstanceId],
);
return result.changes === 1;
}
diff --git a/apps/desktop/src/main/maker-host/__tests__/built-in-skills.test.ts b/apps/desktop/src/main/maker-host/__tests__/built-in-skills.test.ts
index 3bc1f75185..9a8955ef32 100644
--- a/apps/desktop/src/main/maker-host/__tests__/built-in-skills.test.ts
+++ b/apps/desktop/src/main/maker-host/__tests__/built-in-skills.test.ts
@@ -39,7 +39,29 @@ function fixture() {
_names: readonly string[],
operation: () => Promise<T>,
): Promise<T> => operation();
- return { bundledRoot, source, userDataDir, appDataDir, homeDir, withSharedMutation };
+ const replaceDirectoryEntryAtomically = process.platform === 'win32'
+ ? async (replacement: string, destination: string) => {
+ // Unit-test adapter only. The native helper has a dedicated Windows smoke
+ // test; keep these filesystem fixtures independent from Electron's app stub.
+ const previousTarget = await fs.promises.readlink(destination);
+ await fs.promises.unlink(destination);
+ try {
+ await fs.promises.rename(replacement, destination);
+ } catch (error) {
+ await fs.promises.symlink(previousTarget, destination, 'junction');
+ throw error;
+ }
+ }
+ : undefined;
+ return {
+ bundledRoot,
+ source,
+ userDataDir,
+ appDataDir,
+ homeDir,
+ withSharedMutation,
+ ...(replaceDirectoryEntryAtomically ? { replaceDirectoryEntryAtomically } : {}),
+ };
}
async function prepareAndProjectBuiltInSkills(
@@ -432,17 +454,15 @@ describe('built-in Skills', () => {
const initialCreatorBytes = fs.realpathSync(initial.descriptors[0]!.absolutePath);
fs.appendFileSync(path.join(input.source, 'SKILL.md'), '\nCreator v2\n');
- const originalRename = fs.promises.rename.bind(fs.promises);
- vi.spyOn(fs.promises, 'rename').mockImplementation(async (source, destination) => {
- if (String(destination) === activePath && String(source).includes('.active.next-')) {
- throw new Error('blocked active pointer switch');
- }
- await originalRename(source, destination);
- });
-
const failed = await prepareBuiltInSkills({
...input,
bundleVersion: BUILT_IN_SKILLS_BUNDLE_VERSION + 1,
+ replaceDirectoryEntryAtomically: async (replacement, destination) => {
+ expect(replacement).toContain('.active.next-');
+ expect(destination).toBe(activePath);
+ expect(fs.existsSync(activePath)).toBe(true);
+ throw new Error('blocked active pointer switch');
+ },
});
expect(failed.projectionSafe).toBe(true);
diff --git a/apps/desktop/src/main/maker-host/built-in-skills.ts b/apps/desktop/src/main/maker-host/built-in-skills.ts
index de78fe859f..9cbce1471f 100644
--- a/apps/desktop/src/main/maker-host/built-in-skills.ts
+++ b/apps/desktop/src/main/maker-host/built-in-skills.ts
@@ -10,6 +10,7 @@ import {
} from '../../shared/cindyBuiltInSkills';
import { withSkillMutation } from '../skillhub/sharedMutationLease';
import { atomicWriteFileSync, readAtomicFileSync } from '../utils/atomicWriteFile';
+import { atomicReplaceWindowsDirectoryEntry } from '../windowsAtomicRename.js';
export const BUILT_IN_SKILL_CREATOR_NAME = CINDY_SKILL_CREATOR_NAME;
export const BUILT_IN_LEARN_SKILL_NAME = CINDY_LEARN_NAME;
@@ -35,6 +36,7 @@ export interface PrepareBuiltInSkillsOptions {
homeDir?: string;
bundleVersion?: number;
withSharedMutation?: typeof withSkillMutation;
+ replaceDirectoryEntryAtomically?: AtomicReplaceDirectoryEntry;
}
export interface PrepareBuiltInSkillsResult {
@@ -51,6 +53,7 @@ export interface RefreshBuiltInClaudeSkillLinksOptions {
homeDir?: string;
descriptors?: readonly BuiltInSkillDescriptor[];
withSharedMutation?: typeof withSkillMutation;
+ replaceDirectoryEntryAtomically?: AtomicReplaceDirectoryEntry;
}
export interface RefreshBuiltInSharedSkillLinksOptions {
@@ -59,8 +62,11 @@ export interface RefreshBuiltInSharedSkillLinksOptions {
homeDir?: string;
descriptors?: readonly BuiltInSkillDescriptor[];
withSharedMutation?: typeof withSkillMutation;
+ replaceDirectoryEntryAtomically?: AtomicReplaceDirectoryEntry;
}
+type AtomicReplaceDirectoryEntry = (source: string, destination: string) => Promise<void>;
+
export interface RefreshBuiltInClaudeSkillLinksResult {
changed: boolean;
/** False only when a Cindy-managed projection could not be made usable. */
@@ -362,6 +368,7 @@ async function ensureSkillEntry(
appDataDir?: string,
desiredTarget = descriptor.absolutePath,
additionalManagedTargets: readonly string[] = [],
+ replaceDirectoryEntryAtomically?: AtomicReplaceDirectoryEntry,
): Promise<{ changed: boolean; warning?: string; targetPath?: string }> {
await fsp.mkdir(path.dirname(linkPath), { recursive: true });
@@ -400,25 +407,21 @@ async function ensureSkillEntry(
)
) {
const replacement = `${linkPath}.next-${randomUUID()}`;
- const backup = `${linkPath}.previous-${randomUUID()}`;
await fsp.symlink(
desiredTarget,
replacement,
process.platform === 'win32' ? 'junction' : 'dir',
);
- let movedExisting = false;
try {
- await fsp.rename(linkPath, backup);
- movedExisting = true;
- await fsp.rename(replacement, linkPath);
+ await replaceDirectoryEntry(
+ replacement,
+ linkPath,
+ replaceDirectoryEntryAtomically,
+ );
} catch (error) {
await fsp.rm(replacement, { force: true }).catch(() => undefined);
- if (movedExisting && !fs.existsSync(linkPath)) {
- await fsp.rename(backup, linkPath).catch(() => undefined);
- }
throw error;
}
- await fsp.rm(backup, { force: true });
return { changed: true, targetPath: desiredTarget };
}
return {
@@ -511,6 +514,24 @@ function samePath(left: string, right: string): boolean {
return normalizeForCompare(left) === normalizeForCompare(right);
}
+async function replaceDirectoryEntry(
+ replacement: string,
+ destination: string,
+ replaceAtomically?: AtomicReplaceDirectoryEntry,
+): Promise<void> {
+ const destinationExists = await fsp.lstat(destination)
+ .then(() => true)
+ .catch((error: NodeJS.ErrnoException) => {
+ if (error.code === 'ENOENT') return false;
+ throw error;
+ });
+ if (destinationExists && (process.platform === 'win32' || replaceAtomically)) {
+ await (replaceAtomically ?? atomicReplaceWindowsDirectoryEntry)(replacement, destination);
+ return;
+ }
+ await fsp.rename(replacement, destination);
+}
+
function activeBundleTarget(root: string, bundle: string): string {
return path.join(root, VERSIONS_DIRECTORY, bundle);
}
@@ -542,7 +563,11 @@ async function readActiveBundle(root: string): Promise<string | null> {
return segments[0];
}
-async function switchActiveBundle(root: string, bundle: string): Promise<boolean> {
+async function switchActiveBundle(
+ root: string,
+ bundle: string,
+ replaceDirectoryEntryAtomically?: AtomicReplaceDirectoryEntry,
+): Promise<boolean> {
const target = activeBundleTarget(root, bundle);
if (!(await fsp.stat(target).catch(() => null))?.isDirectory()) {
throw new Error(`built-in Skill bundle is unavailable: ${target}`);
@@ -551,35 +576,16 @@ async function switchActiveBundle(root: string, bundle: string): Promise<boolean
const activePath = path.join(root, ACTIVE_BUNDLE_LINK);
const replacement = `${activePath}.next-${randomUUID()}`;
- const backup = `${activePath}.previous-${randomUUID()}`;
await fsp.symlink(target, replacement, process.platform === 'win32' ? 'junction' : 'dir');
try {
- // POSIX replaces a symlink atomically. Windows may reject replacing an
- // existing directory junction, in which case the fallback still changes
- // every Agent through this one pointer rather than one projection at a time.
- await fsp.rename(replacement, activePath);
- } catch (firstError) {
- const activeEntryExists = await fsp.lstat(activePath).then(() => true).catch(() => false);
- if (!activeEntryExists) {
- await fsp.rm(replacement, { force: true }).catch(() => undefined);
- throw firstError;
- }
- let movedExisting = false;
- try {
- await fsp.rename(activePath, backup);
- movedExisting = true;
- await fsp.rename(replacement, activePath);
- } catch (error) {
- await fsp.rm(replacement, { force: true }).catch(() => undefined);
- const activeEntryExistsAfterFailure = await fsp.lstat(activePath)
- .then(() => true)
- .catch(() => false);
- if (movedExisting && !activeEntryExistsAfterFailure) {
- await fsp.rename(backup, activePath).catch(() => undefined);
- }
- throw error;
- }
- await fsp.rm(backup, { force: true }).catch(() => undefined);
+ await replaceDirectoryEntry(
+ replacement,
+ activePath,
+ replaceDirectoryEntryAtomically,
+ );
+ } catch (error) {
+ await fsp.rm(replacement, { force: true }).catch(() => undefined);
+ throw error;
}
return true;
}
@@ -597,6 +603,7 @@ async function ensureSharedEntry(
homeDir: string,
legacyUserDataDir: string,
appDataDir?: string,
+ replaceDirectoryEntryAtomically?: AtomicReplaceDirectoryEntry,
): Promise<{ changed: boolean; warning?: string; targetPath?: string }> {
return ensureSkillEntry(
descriptor,
@@ -604,6 +611,9 @@ async function ensureSharedEntry(
true,
legacyUserDataDir,
appDataDir,
+ undefined,
+ [],
+ replaceDirectoryEntryAtomically,
);
}
@@ -624,6 +634,7 @@ async function refreshBuiltInSharedSkillLinksUnlocked(
homeDir,
options.userDataDir,
options.appDataDir,
+ options.replaceDirectoryEntryAtomically,
);
changed = linked.changed || changed;
if (linked.warning) warnings.push(linked.warning);
@@ -746,6 +757,7 @@ async function refreshBuiltInClaudeSkillLinksUnlocked(
options.appDataDir,
claudeRuntimeTarget,
[sharedPath, claudePalettePath],
+ options.replaceDirectoryEntryAtomically,
);
changed = linked.changed || changed;
if (linked.warning) warnings.push(linked.warning);
@@ -937,6 +949,7 @@ async function projectBuiltInSkillLinksUnlocked(
appDataDir: options.appDataDir,
homeDir,
descriptors,
+ replaceDirectoryEntryAtomically: options.replaceDirectoryEntryAtomically,
});
const claude = await refreshBuiltInClaudeSkillLinksUnlocked({
userDataDir: options.userDataDir,
@@ -944,6 +957,7 @@ async function projectBuiltInSkillLinksUnlocked(
homeDir,
descriptors,
allowUnresolvedManagedSharedTarget,
+ replaceDirectoryEntryAtomically: options.replaceDirectoryEntryAtomically,
});
return {
changed: shared.changed || claude.changed,
@@ -1025,7 +1039,11 @@ export async function prepareBuiltInSkills(
}
if (committedBundleVerified) {
try {
- changed = await switchActiveBundle(root, committedBundle) || changed;
+ changed = await switchActiveBundle(
+ root,
+ committedBundle,
+ options.replaceDirectoryEntryAtomically,
+ ) || changed;
} catch (error) {
warnings.push(
`could not recover the committed built-in Skill bundle: ${error instanceof Error ? error.message : String(error)}`,
@@ -1169,7 +1187,7 @@ export async function prepareBuiltInSkills(
}
await writeManifest(root, nextManifest);
manifestAdvanced = true;
- await switchActiveBundle(root, activeBundle);
+ await switchActiveBundle(root, activeBundle, options.replaceDirectoryEntryAtomically);
changed = true;
projectionSafe = true;
} catch (error) {
@@ -1179,7 +1197,11 @@ export async function prepareBuiltInSkills(
try {
await writeManifest(root, manifest);
if (manifest.schemaVersion === 3) {
- await switchActiveBundle(root, manifest.activeBundle!);
+ await switchActiveBundle(
+ root,
+ manifest.activeBundle!,
+ options.replaceDirectoryEntryAtomically,
+ );
} else {
await removeActiveBundlePointer(root);
}
diff --git a/apps/desktop/src/main/maker-host/index.ts b/apps/desktop/src/main/maker-host/index.ts
index 70d49ff19d..8ed0a9c902 100644
--- a/apps/desktop/src/main/maker-host/index.ts
+++ b/apps/desktop/src/main/maker-host/index.ts
@@ -1,5 +1,5 @@
import { registerCodexTextOnlyPolicy } from './codex-text-only-policy.js';
-import { isCindyLearnSkillEnabled, readDisabledSkillPaths } from '../skillhub/activationPreferences';
+import { readDisabledSkillPaths } from '../skillhub/activationPreferences';
import { cindyMakeManager } from '../cindy-make/manager.js';
import { makeSourceRoot } from '../cindy-make/sourcePaths.js';
import { clearCodexAccountUsageSnapshot } from '../usageBroadcaster.js';
@@ -80,10 +80,6 @@ import {
type BotProfileRuntimeSnapshot,
} from '../maker-ipc/botProfileRuntime.js';
import { collectBotOwnSkillMounts } from '../maker-ipc/botSkillService.js';
-import {
- builtInSkillDescriptors,
- markCindyBuiltInAgentSkills,
-} from './built-in-skills.js';
import { buildBotMcpCatalog } from './botMcpCatalog.js';
import { createBotCapabilityService, type BotCapabilityServiceDeps, type BotCapabilityUpdate } from '../maker-ipc/botCapabilityService.js';
import {
@@ -938,42 +934,16 @@ export function getMaker(): Maker {
pluginRegistry,
resolveIOSSimulatorAccess,
invokeRemote: remoteInvoke,
- attestCindyLearnSkillForSession: async (
+ isCurrentLocalSessionInstance: (
sessionId: string,
sessionInstanceId: string | undefined,
) => {
const session = _maker?.getSession(sessionId);
- if (
- !sessionInstanceId
- || !session
- || session.instanceId !== sessionInstanceId
- || session.remoteHostId
- || !isCindyLearnSkillEnabled()
- ) {
- return false;
- }
- const result = session.agentKind === 'claude-code'
- ? await _maker!.listAgentRuntimeSkills(session.agentKind, {
- workingDir: session.workDir,
- sessionId,
- runtimeConfigDir: process.env.CLAUDE_CONFIG_DIR?.trim() || (
- process.env.XDT_USER_DATA_DIR && !app.isPackaged
- ? path.join(app.getPath('userData'), 'claude-home')
- : path.join(os.homedir(), '.claude')
- ),
- })
- : await _maker!.listAgentSkills(session.agentKind, {
- workingDir: session.workDir,
- sessionId,
- });
- if (result.errors?.length) return false;
- const skills = markCindyBuiltInAgentSkills(
- result.skills,
- builtInSkillDescriptors(app.getPath('userData'), app.getPath('appData')),
- );
- const learnCandidates = skills.filter((skill) => skill.name.toLowerCase() === 'learn');
- return learnCandidates.length > 0
- && learnCandidates.every((skill) => skill.builtIn === true);
+ return Boolean(sessionInstanceId
+ && session
+ && session.instanceId === sessionInstanceId
+ && session.getStatus() === 'active'
+ && !session.remoteHostId);
},
// 只读活跃 Session 的运行时真相。权限切换是 runtime-first、DB-second,
// 因此插件过户自动放行不得回退 sessions.permission_mode;会话不再 active
diff --git a/apps/desktop/src/main/maker-ipc/__tests__/makerSendTransaction.test.ts b/apps/desktop/src/main/maker-ipc/__tests__/makerSendTransaction.test.ts
index 36b8261455..bdac7850bc 100644
--- a/apps/desktop/src/main/maker-ipc/__tests__/makerSendTransaction.test.ts
+++ b/apps/desktop/src/main/maker-ipc/__tests__/makerSendTransaction.test.ts
@@ -32,6 +32,7 @@ import { createWorkingDirectoryRecovery } from '../workingDirectoryRecovery';
function createSession(overrides: Partial<MakerSendTransactionSession> = {}): MakerSendTransactionSession {
return {
id: 'session-1',
+ instanceId: 'session-instance-1',
agentKind: 'codex',
workDir: 'C:\\repo',
remoteHostId: null,
@@ -226,6 +227,68 @@ describe('maker SEND transaction', () => {
expect(deps.rollbackUserPromptPreview).not.toHaveBeenCalled();
});
+ it('persists the main-attested Learn winner on the exact accepted user turn', async () => {
+ const grant = {
+ version: 1 as const,
+ sessionInstanceId: 'session-instance-1',
+ resolvedSkillPath: '/system-skills/v10/learn/SKILL.md',
+ };
+ const captureCindyLearnInvocation = vi.fn(async () => grant);
+ const { deps, session } = createDeps({ captureCindyLearnInvocation });
+
+ await createMakerSendTransaction(deps).sendToAgentAccepted(
+ 'session-1',
+ { type: 'user', content: '/learn release flow' },
+ undefined,
+ {
+ persistUserMessage: {
+ clientId: 'learn-1',
+ content: '{"text":"/learn release flow","slashCommandRanges":[{"start":0,"end":6}]}',
+ },
+ },
+ );
+
+ expect(captureCindyLearnInvocation).toHaveBeenCalledWith(
+ session,
+ '{"text":"/learn release flow","slashCommandRanges":[{"start":0,"end":6}]}',
+ '/learn release flow',
+ );
+ expect(deps.createDbMessage).toHaveBeenCalledWith(
+ 'session-1',
+ expect.objectContaining({
+ clientId: 'learn-1',
+ agentMeta: expect.objectContaining({ cindyLearnInvocation: grant }),
+ }),
+ undefined,
+ );
+ });
+
+ it('does not mint a Learn grant when a colliding custom Skill won at dispatch', async () => {
+ const captureCindyLearnInvocation = vi.fn(async () => null);
+ const { deps } = createDeps({ captureCindyLearnInvocation });
+
+ await createMakerSendTransaction(deps).sendToAgentAccepted(
+ 'session-1',
+ { type: 'user', content: '/learn release flow' },
+ undefined,
+ {
+ persistUserMessage: {
+ clientId: 'custom-learn-1',
+ content: '{"text":"/learn release flow","slashCommandRanges":[{"start":0,"end":6}]}',
+ },
+ },
+ );
+
+ expect(captureCindyLearnInvocation).toHaveBeenCalledTimes(1);
+ expect(deps.createDbMessage).toHaveBeenCalledWith(
+ 'session-1',
+ expect.objectContaining({
+ agentMeta: expect.not.objectContaining({ cindyLearnInvocation: expect.anything() }),
+ }),
+ undefined,
+ );
+ });
+
it('restamps a trusted local queue edit for the existing Desktop command route', async () => {
const { deps, session } = createDeps();
const transaction = createMakerSendTransaction(deps);
diff --git a/apps/desktop/src/main/maker-ipc/makerSendTransaction.ts b/apps/desktop/src/main/maker-ipc/makerSendTransaction.ts
index c865de4b04..de7504eb1c 100644
--- a/apps/desktop/src/main/maker-ipc/makerSendTransaction.ts
+++ b/apps/desktop/src/main/maker-ipc/makerSendTransaction.ts
@@ -43,6 +43,7 @@ import {
validateExtraDirs,
} from './extraDirsValidator.js';
import type { MakerSessionCreateOpts } from './sessionRequest.js';
+import type { CindyLearnInvocationGrant } from '../learn-host/invocationGrant.js';
import { currentAutoReviewResourceIntent, readAutoReviewUserText, restoreAutoReviewUserIntent, type AutoReviewHistoryMessage } from './autoReviewUserIntent.js';
type CreateOpts = MakerSessionCreateOpts;
@@ -310,6 +311,8 @@ export interface MakerSendTransactionSession {
readonly stablePlanModeState?: Session['stablePlanModeState'];
hostStartupPreferences?: CreateOpts['hostStartupPreferences'];
id: string;
+ /** Exact in-memory incarnation; a reused session id must not inherit turn grants. */
+ instanceId: string;
agentKind: AgentKind;
workDir: string;
remoteHostId: string | null;
@@ -400,6 +403,12 @@ export interface MakerSendTransactionDeps {
expectedClearBoundaryMs?: number | null;
},
): Promise<unknown>;
+ /** Resolve the actual /learn Skill winner once for this exact dispatch. */
+ captureCindyLearnInvocation?: (
+ session: MakerSendTransactionSession,
+ persistedContent: unknown,
+ dispatchedText: string,
+ ) => Promise<CindyLearnInvocationGrant | null>;
/** Hide a user row that lost a clear race after accepted persistence. */
rewindPersistedUserMessageAfterClear?: (sessionId: string, clientId: string) => Promise<void>;
/** Check the clear token captured at the start of this send. */
@@ -1384,6 +1393,25 @@ export function createMakerSendTransaction(deps: MakerSendTransactionDeps): Make
await directPreDispatchHook(sessionId);
directPreDispatchHookStarted = true;
}
+ let cindyLearnInvocation: CindyLearnInvocationGrant | null = null;
+ if (persistUserMessage && deps.captureCindyLearnInvocation) {
+ try {
+ // Capture before Session.send: onAccepted persists this exact snapshot,
+ // and the provider cannot start until that durable write completes.
+ cindyLearnInvocation = await deps.captureCindyLearnInvocation(
+ sess,
+ persistUserMessage.content,
+ extractIpcUserMessageText(normalized),
+ );
+ } catch (err) {
+ // The message may still run as a normal Skill invocation, but the
+ // privileged Learn host must fail closed without a dispatch snapshot.
+ deps.log.warn('send: Learn Skill winner capture failed', {
+ sessionId,
+ err: err instanceof Error ? err.message : String(err),
+ });
+ }
+ }
// Capture on the executor immediately before vendor code. sess.send may
// synchronously publish the continuation's new started marker before it
// resolves, so the old-turn ack must use this strictly earlier value.
@@ -1488,6 +1516,9 @@ export function createMakerSendTransaction(deps: MakerSendTransactionDeps): Make
...(persistUserMessage.agentFacingWireContent
? { agentFacingWireContent: persistUserMessage.agentFacingWireContent }
: {}),
+ ...(cindyLearnInvocation
+ ? { cindyLearnInvocation }
+ : {}),
// 队列来源写入 agentMeta,不发给 maker-core。Orca 只在 persist
// 上;scheduler 直发可能只在 sendOpts.origin 上。
...((persistUserMessage.origin ?? so.origin)
diff --git a/apps/desktop/src/main/maker-ipc/register.ts b/apps/desktop/src/main/maker-ipc/register.ts
index e956725b31..06d33ab093 100644
--- a/apps/desktop/src/main/maker-ipc/register.ts
+++ b/apps/desktop/src/main/maker-ipc/register.ts
@@ -397,6 +397,10 @@ import {
builtInSkillDescriptors,
} from '../maker-host/built-in-skills.js';
import { isCindySkillEnabled } from '../skillhub/activationPreferences.js';
+import {
+ parseDirectLearnInvocation,
+ type CindyLearnInvocationGrant,
+} from '../learn-host/invocationGrant.js';
import { ensurePiManagerInstalled } from '../maker-host/pi-manager-client.js';
import {
setRemoteCodexLiveTurnChecker,
@@ -12265,6 +12269,64 @@ export function registerMakerIpc(maker: Maker, options: RegisterMakerIpcOptions)
prepareSendUserMessage: (sessionId, message) =>
prepareUserMessageForAgent(sessionId, message, 'send'),
materializeDirectSendOssAttachments,
+ captureCindyLearnInvocation: async (session, persistedContent, dispatchedText) => {
+ const invocationText = visibleMessageTextForConversationSearch(
+ 'user',
+ typeof persistedContent === 'string' ? persistedContent : JSON.stringify(persistedContent),
+ );
+ const persistedInvocation = parseDirectLearnInvocation(invocationText);
+ const dispatchedInvocation = parseDirectLearnInvocation(dispatchedText);
+ if (
+ !persistedInvocation
+ || !dispatchedInvocation
+ || JSON.stringify(persistedInvocation) !== JSON.stringify(dispatchedInvocation)
+ ) return null;
+ if (
+ session.remoteHostId
+ || maker.getSession(session.id) !== session
+ || (session.getStatus && session.getStatus() !== 'active')
+ ) return null;
+
+ const descriptors = builtInSkillDescriptors(
+ app.getPath('userData'),
+ app.getPath('appData'),
+ );
+ const learnDescriptor = descriptors.find((descriptor) => descriptor.name === 'learn');
+ if (!learnDescriptor || !isCindySkillEnabled(learnDescriptor.absolutePath)) return null;
+
+ const result = session.agentKind === 'claude-code'
+ ? await maker.listAgentRuntimeSkills(session.agentKind, {
+ workingDir: session.workDir,
+ sessionId: session.id,
+ runtimeConfigDir: process.env.CLAUDE_CONFIG_DIR?.trim() || (
+ process.env.XDT_USER_DATA_DIR && !app.isPackaged
+ ? path.join(app.getPath('userData'), 'claude-home')
+ : path.join(os.homedir(), '.claude')
+ ),
+ })
+ : await maker.listAgentSkills(session.agentKind, {
+ workingDir: session.workDir,
+ sessionId: session.id,
+ });
+ if (result.errors?.length || maker.getSession(session.id) !== session) return null;
+ const learnCandidates = activeCindyBuiltInAgentSkills(
+ result.skills,
+ descriptors,
+ isCindySkillEnabled,
+ ).filter((skill) => skill.name.toLowerCase() === 'learn');
+ if (
+ learnCandidates.length === 0
+ || learnCandidates.some((skill) => skill.builtIn !== true || !skill.path)
+ ) return null;
+
+ const resolvedSkillPath = await fsp.realpath(learnCandidates[0]!.path!);
+ if (maker.getSession(session.id) !== session) return null;
+ return {
+ version: 1,
+ sessionInstanceId: session.instanceId,
+ resolvedSkillPath,
+ } satisfies CindyLearnInvocationGrant;
+ },
createDbMessage: createUserMessageDurably,
rewindPersistedUserMessageAfterClear: (sessionId, clientId) =>
enqueueDurableWrite(`user-rewind:${sessionId}:${clientId}`, () =>
diff --git a/apps/desktop/src/main/mcp-integrations/__tests__/collabSendOutcome.test.ts b/apps/desktop/src/main/mcp-integrations/__tests__/collabSendOutcome.test.ts
index 65768b6738..28771fa22b 100644
--- a/apps/desktop/src/main/mcp-integrations/__tests__/collabSendOutcome.test.ts
+++ b/apps/desktop/src/main/mcp-integrations/__tests__/collabSendOutcome.test.ts
@@ -16,7 +16,10 @@ const mockState = vi.hoisted(() => ({
},
learnEnabled: true,
learnController: {} as object | null,
- consumeLearnInvocationGrant: vi.fn(async (_request: unknown) => ({ ok: true as const })),
+ consumeLearnInvocationGrant: vi.fn(async (
+ _request: unknown,
+ _sessionInstanceId: string | undefined,
+ ) => ({ ok: true as const })),
capturedProvidersConfig: null as null | Record<string, unknown>,
}));
@@ -101,8 +104,8 @@ vi.mock('../../learn-host/index.js', () => ({
}));
vi.mock('../../learn-host/invocationGrant.js', () => ({
- consumeLearnInvocationGrant: (request: unknown) =>
- mockState.consumeLearnInvocationGrant(request),
+ consumeLearnInvocationGrant: (request: unknown, sessionInstanceId: string | undefined) =>
+ mockState.consumeLearnInvocationGrant(request, sessionInstanceId),
}));
vi.mock('../../localDb/chatHistoryReader.js', () => ({
@@ -247,8 +250,8 @@ describe('collab send outcome semantics', () => {
});
});
- it('authorizes Learn only when the active slash-command winner is Cindy built-in Learn', async () => {
- const attestCindyLearnSkillForSession = vi.fn(async () => false);
+ it('authorizes Learn only for the live local Session instance bound to its dispatch grant', async () => {
+ const isCurrentLocalSessionInstance = vi.fn(() => false);
createDesktopMcpProviders({
botCapabilities,
getMakerMemoryManager: vi.fn(),
@@ -256,7 +259,7 @@ describe('collab send outcome semantics', () => {
pluginRegistry: { isEnabled: () => true } as never,
resolveIOSSimulatorAccess: () => ({ allowed: true }),
invokeRemote: vi.fn(),
- attestCindyLearnSkillForSession,
+ isCurrentLocalSessionInstance,
});
const xdtHelper = mockState.capturedProvidersConfig?.xdtHelper as {
authorizeSkillLearning: (input: {
@@ -276,15 +279,15 @@ describe('collab send outcome semantics', () => {
ok: false,
errorCode: 'USER_REQUEST_REQUIRED',
});
- expect(attestCindyLearnSkillForSession).toHaveBeenLastCalledWith(
+ expect(isCurrentLocalSessionInstance).toHaveBeenLastCalledWith(
'session-1',
'instance-1',
);
expect(mockState.consumeLearnInvocationGrant).not.toHaveBeenCalled();
- attestCindyLearnSkillForSession.mockResolvedValue(true);
+ isCurrentLocalSessionInstance.mockReturnValue(true);
await expect(xdtHelper.authorizeSkillLearning(request, context)).resolves.toEqual({ ok: true });
- expect(mockState.consumeLearnInvocationGrant).toHaveBeenCalledWith(request);
+ expect(mockState.consumeLearnInvocationGrant).toHaveBeenCalledWith(request, 'instance-1');
});
it('reports enable_collab_mode delegate_task created-and-dispatched distinctly', async () => {
diff --git a/apps/desktop/src/main/mcp-integrations/mcp-providers.ts b/apps/desktop/src/main/mcp-integrations/mcp-providers.ts
index ea7d9cd65e..912c9668d4 100644
--- a/apps/desktop/src/main/mcp-integrations/mcp-providers.ts
+++ b/apps/desktop/src/main/mcp-integrations/mcp-providers.ts
@@ -110,11 +110,11 @@ export interface DesktopMcpProvidersDeps {
sessionId: string,
sessionInstanceId: string,
) => GhostGrantLiveSessionState | null;
- /** Confirms that this Session's actual slash-command winner is Cindy's built-in Learn Skill. */
- attestCindyLearnSkillForSession?: (
+ /** Reject stale, remote, or already-closed Session tool contexts. */
+ isCurrentLocalSessionInstance?: (
sessionId: string,
sessionInstanceId: string | undefined,
- ) => Promise<boolean>;
+ ) => boolean;
/** 把工具结果图片转成文字描述(视觉桥,最佳努力)。缺失 = 不处理。
* 返回结构区分「有意跳过」(skipped:true, 视觉桥未开/模型不命中, 不告警)与
* 「真正尝试但失败」(skipped:false + null, 计入 attemptedCount 供告警)。 */
@@ -398,17 +398,17 @@ export function createDesktopMcpProviders(deps: DesktopMcpProvidersDeps): LiziMc
message: 'Cindy Learn is not ready yet.',
};
}
- if (!await deps.attestCindyLearnSkillForSession?.(
+ if (!deps.isCurrentLocalSessionInstance?.(
request.callerSessionId,
context.sessionInstanceId,
)) {
return {
ok: false,
errorCode: 'USER_REQUEST_REQUIRED',
- message: 'Cindy Learn is not the active /learn Skill for this task.',
+ message: 'Cindy Learn is not authorized for this task instance.',
};
}
- return consumeLearnInvocationGrant(request);
+ return consumeLearnInvocationGrant(request, context.sessionInstanceId);
},
skillLearning: async ({
callerSessionId,
diff --git a/apps/desktop/src/main/windowsAtomicRename.ts b/apps/desktop/src/main/windowsAtomicRename.ts
new file mode 100644
index 0000000000..89b4737992
--- /dev/null
+++ b/apps/desktop/src/main/windowsAtomicRename.ts
@@ -0,0 +1,79 @@
+import { execFile } from 'node:child_process';
+import { createHash } from 'node:crypto';
+import fs from 'node:fs/promises';
+import os from 'node:os';
+import path from 'node:path';
+import { promisify } from 'node:util';
+import { app } from 'electron';
+
+const exec = promisify(execFile);
+const binaryName = 'cindy-windows-atomic-rename.exe';
+let resolvingBinary: Promise<string> | undefined;
+
+function windowsTarget(): string {
+ if (process.arch === 'arm64') return 'aarch64-pc-windows-msvc';
+ if (process.arch === 'x64') return 'x86_64-pc-windows-msvc';
+ throw new Error(`Unsupported Windows atomic rename architecture: ${process.arch}`);
+}
+
+async function resolveRustc(): Promise<string> {
+ const userRustc = path.join(os.homedir(), '.cargo', 'bin', 'rustc.exe');
+ return fs.access(userRustc).then(() => userRustc, () => 'rustc');
+}
+
+async function resolveBinary(): Promise<string> {
+ if (process.platform !== 'win32') throw new Error('Windows atomic rename is Windows-only');
+ if (app.isPackaged) {
+ return path.join(process.resourcesPath, 'tools', 'windows-atomic-rename', binaryName);
+ }
+ const target = windowsTarget();
+ const source = path.join(app.getAppPath(), 'native', 'windows-atomic-rename', 'main.rs');
+ const sourceBytes = await fs.readFile(source);
+ const digest = createHash('sha256').update(target).update(sourceBytes).digest('hex');
+ const directory = path.join(app.getPath('userData'), 'windows-atomic-rename', digest);
+ const binary = path.join(directory, binaryName);
+ try {
+ await fs.access(binary);
+ return binary;
+ } catch {
+ // Development only: compile this exact source version outside the checkout.
+ }
+
+ const buildDirectory = await fs.mkdtemp(path.join(os.tmpdir(), 'cindy-atomic-rename-build-'));
+ const built = path.join(buildDirectory, binaryName);
+ try {
+ await exec(await resolveRustc(), [
+ source,
+ '--edition=2021',
+ '-C', 'opt-level=s',
+ '-C', 'panic=abort',
+ '--target', target,
+ '-o', built,
+ ], { timeout: 180_000, windowsHide: true });
+ await fs.mkdir(directory, { recursive: true });
+ const temporary = path.join(directory, `${binaryName}.${process.pid}.tmp`);
+ try {
+ await fs.copyFile(built, temporary);
+ await fs.rename(temporary, binary).catch(async (error: unknown) => {
+ await fs.access(binary).catch(() => { throw error; });
+ });
+ } finally {
+ await fs.rm(temporary, { force: true });
+ }
+ return binary;
+ } finally {
+ await fs.rm(buildDirectory, { recursive: true, force: true });
+ }
+}
+
+export async function atomicReplaceWindowsDirectoryEntry(
+ source: string,
+ destination: string,
+): Promise<void> {
+ const binary = await (resolvingBinary ??= resolveBinary());
+ await exec(binary, [source, destination], {
+ timeout: 15_000,
+ windowsHide: true,
+ maxBuffer: 64 * 1024,
+ });
+}