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(downloads): reuse Windows atomic replacement for verified files

Dash8c9faccca99f
diff --git a/apps/desktop/src/main/downloader/transport.ts b/apps/desktop/src/main/downloader/transport.ts
index 54c7e3c331..2dc44caa4f 100644
--- a/apps/desktop/src/main/downloader/transport.ts
+++ b/apps/desktop/src/main/downloader/transport.ts
@@ -15,6 +15,7 @@ import {
} from './resume';
import { createStreamingHasher } from './integrity';
import { ProgressTracker } from './progress';
+import { replaceFile } from '../utils/replaceFile';
export interface TransportContext {
opts: DownloadOptions;
@@ -258,7 +259,7 @@ export async function executeOnce(ctx: TransportContext): Promise<TransportResul
await fs.promises.link(partPath(opts.targetPath), opts.targetPath);
deletePart(opts.targetPath);
} else {
- await fs.promises.rename(partPath(opts.targetPath), opts.targetPath);
+ await replaceFile(partPath(opts.targetPath), opts.targetPath);
}
complete = true;
deleteMeta(opts.targetPath);
diff --git a/apps/desktop/src/main/managed-tools/__tests__/installer.test.ts b/apps/desktop/src/main/managed-tools/__tests__/installer.test.ts
index 62206db807..de35523424 100644
--- a/apps/desktop/src/main/managed-tools/__tests__/installer.test.ts
+++ b/apps/desktop/src/main/managed-tools/__tests__/installer.test.ts
@@ -31,6 +31,29 @@ async function setup() {
};
}
describe('shared tool installer', () => {
+ it('keeps the previous generation until a repair passes validation and publishes its record', async () => {
+ const input = await setup();
+ const archive = await new JSZip()
+ .file('gh/bin/gh', 'executable')
+ .generateAsync({ type: 'nodebuffer' });
+ const deps = {
+ download: async (opts: { targetPath: string }) => {
+ await writeFile(opts.targetPath, archive);
+ },
+ };
+ const previous = await installTool(input, deps);
+ input.validate.mockImplementation(async () => {
+ expect(await installedTool(input.root, input.artifact)).toBe(previous);
+ return false;
+ });
+ await expect(installTool(input, deps)).rejects.toThrow('version check');
+ expect(await installedTool(input.root, input.artifact)).toBe(previous);
+ input.validate.mockResolvedValue(true);
+ const repaired = await installTool(input, deps);
+ expect(repaired).not.toBe(previous);
+ expect(await installedTool(input.root, input.artifact)).toBe(repaired);
+ expect(await readFile(previous, 'utf8')).toBe('executable');
+ });
it('installs a non-Make CLI to an absolute path and can rediscover it without PATH', async () => {
const input = await setup();
const archive = await new JSZip()
diff --git a/apps/desktop/src/main/managed-tools/installer.ts b/apps/desktop/src/main/managed-tools/installer.ts
index b285664d7a..53a96c0cc1 100644
--- a/apps/desktop/src/main/managed-tools/installer.ts
+++ b/apps/desktop/src/main/managed-tools/installer.ts
@@ -3,6 +3,7 @@ import { chmod, mkdir, mkdtemp, readFile, rename, rm, stat, writeFile } from 'no
import path from 'node:path';
import { download, type DownloadOptions } from '../downloader/index.js';
import { createLogger } from '../logger.js';
+import { replaceFile } from '../utils/replaceFile.js';
import type { ToolArtifact, ToolInstallProgress } from './types.js';
import { extractToolArchive, safeArchivePath, MAX_ARCHIVE_BYTES } from './archive.js';
@@ -119,7 +120,7 @@ export async function installTool(
flag: 'wx',
});
signal.throwIfAborted();
- await rename(recordTemp, recordPath(root, artifact));
+ await replaceFile(recordTemp, recordPath(root, artifact));
promoted = true;
return path.join(target, ...artifact.executable.split('/'));
} finally {
diff --git a/apps/desktop/src/main/utils/__tests__/replaceFile.test.ts b/apps/desktop/src/main/utils/__tests__/replaceFile.test.ts
new file mode 100644
index 0000000000..3b5677eeec
--- /dev/null
+++ b/apps/desktop/src/main/utils/__tests__/replaceFile.test.ts
@@ -0,0 +1,45 @@
+import { afterEach, describe, expect, it, vi } from 'vitest';
+import path from 'node:path';
+
+const mocks = vi.hoisted(() => ({ rename: vi.fn(), replace: vi.fn() }));
+vi.mock('node:fs/promises', () => ({ rename: mocks.rename }));
+vi.mock('../../windowsAtomicRename.js', () => ({
+ atomicReplaceWindowsDirectoryEntry: mocks.replace,
+}));
+import { replaceFile } from '../replaceFile';
+
+afterEach(() => {
+ vi.restoreAllMocks();
+ vi.resetAllMocks();
+});
+
+describe('verified file publication', () => {
+ it.each(['EEXIST', 'EPERM'])('uses native replacement for Windows %s', async (code) => {
+ vi.spyOn(process, 'platform', 'get').mockReturnValue('win32');
+ mocks.rename.mockRejectedValue(Object.assign(new Error('cannot overwrite'), { code }));
+ await replaceFile('archive.part', 'archive');
+ expect(mocks.replace).toHaveBeenCalledWith(
+ path.resolve('archive.part'),
+ path.resolve('archive'),
+ );
+ });
+ it.each(['darwin', 'win32'] as const)(
+ 'uses normal rename on %s when it succeeds',
+ async (platform) => {
+ vi.spyOn(process, 'platform', 'get').mockReturnValue(platform);
+ await replaceFile('current.tmp', 'current.json');
+ expect(mocks.replace).not.toHaveBeenCalled();
+ },
+ );
+ it('does not mask permission errors or attempt a destructive fallback', async () => {
+ vi.spyOn(process, 'platform', 'get').mockReturnValue('win32');
+ const failure = Object.assign(new Error('denied'), { code: 'EACCES' });
+ mocks.rename.mockRejectedValue(failure);
+ await expect(replaceFile('a.part', 'a')).rejects.toBe(failure);
+ expect(mocks.replace).not.toHaveBeenCalled();
+ mocks.rename.mockRejectedValue(Object.assign(new Error('exists'), { code: 'EEXIST' }));
+ mocks.replace.mockRejectedValue(failure);
+ await expect(replaceFile('a.part', 'a')).rejects.toBe(failure);
+ expect(mocks.rename).toHaveBeenCalledTimes(2);
+ });
+});
diff --git a/apps/desktop/src/main/utils/replaceFile.ts b/apps/desktop/src/main/utils/replaceFile.ts
new file mode 100644
index 0000000000..7d0ed0c54c
--- /dev/null
+++ b/apps/desktop/src/main/utils/replaceFile.ts
@@ -0,0 +1,14 @@
+import { rename } from 'node:fs/promises';
+import path from 'node:path';
+
+/** Publish a verified sibling file without deleting the previous destination. */
+export async function replaceFile(source: string, destination: string): Promise<void> {
+ try {
+ await rename(source, destination);
+ } catch (error) {
+ const code = (error as NodeJS.ErrnoException).code;
+ if (process.platform !== 'win32' || (code !== 'EEXIST' && code !== 'EPERM')) throw error;
+ const { atomicReplaceWindowsDirectoryEntry } = await import('../windowsAtomicRename.js');
+ await atomicReplaceWindowsDirectoryEntry(path.resolve(source), path.resolve(destination));
+ }
+}
diff --git a/apps/desktop/src/renderer/features/issue-tracker/IssueTrackerFeatureLayout.tsx b/apps/desktop/src/renderer/features/issue-tracker/IssueTrackerFeatureLayout.tsx
index 2fda74a318..1a69d63de4 100644
--- a/apps/desktop/src/renderer/features/issue-tracker/IssueTrackerFeatureLayout.tsx
+++ b/apps/desktop/src/renderer/features/issue-tracker/IssueTrackerFeatureLayout.tsx
@@ -67,9 +67,7 @@ export function IssueTrackerFeatureLayout() {
<h1 className="text-15 font-medium text-foreground">{t('issueTracker.list.header')}</h1>
{data ? <ViewerLine data={data} /> : null}
<div className="flex-1" />
- <GithubConnectButton
- visible={!loading && (!data?.githubEnhancement || data.githubEnhancementFailed)}
- />
+ <GithubConnectButton visible={!loading && !data?.githubEnhancement} />
<button
type="button"
onClick={refresh}
diff --git a/apps/desktop/src/renderer/features/issue-tracker/__tests__/IssueTrackerFeatureLayout.test.tsx b/apps/desktop/src/renderer/features/issue-tracker/__tests__/IssueTrackerFeatureLayout.test.tsx
index 1e724506c7..88d24c03a5 100644
--- a/apps/desktop/src/renderer/features/issue-tracker/__tests__/IssueTrackerFeatureLayout.test.tsx
+++ b/apps/desktop/src/renderer/features/issue-tracker/__tests__/IssueTrackerFeatureLayout.test.tsx
@@ -93,7 +93,7 @@ afterEach(() => {
});
describe('IssueTrackerFeatureLayout 内容区分支', () => {
- it('hides connect for a working GitHub account and restores it when the connection fails', () => {
+ it('keeps connect hidden when search fails for a resolved GitHub account', () => {
const connected = result([], { githubEnhancement: { login: 'test', source: 'gh-cli' } });
useMyIssuesMock.mockReturnValue(state({ data: connected }));
const { rerender } = render(<IssueTrackerFeatureLayout />);
@@ -102,6 +102,9 @@ describe('IssueTrackerFeatureLayout 内容区分支', () => {
state({ data: { ...connected, githubEnhancementFailed: true } }),
);
rerender(<IssueTrackerFeatureLayout />);
+ expect(screen.queryByText('ccAgent.gitContext.pr.setup.stages.login.title')).toBeNull();
+ useMyIssuesMock.mockReturnValue(state({ data: result([], { githubEnhancementFailed: true }) }));
+ rerender(<IssueTrackerFeatureLayout />);
expect(screen.getByText('ccAgent.gitContext.pr.setup.stages.login.title')).toBeTruthy();
});
it('connects GitHub without hiding existing issues and refreshes after success', async () => {
diff --git a/docs/dev-rules/verified-downloads.md b/docs/dev-rules/verified-downloads.md
index 7e5c53751e..e6e0f07020 100644
--- a/docs/dev-rules/verified-downloads.md
+++ b/docs/dev-rules/verified-downloads.md
@@ -18,6 +18,8 @@ Agent runtime、Cindy Make 工具、Ollama runtime、插件包、Skill 包及更
调用方只有在下载 Promise 结束后才可 `cleanup()` 或删除暂存目录。
- 默认校验成功后替换目标,下载失败保留原目标;`existingTarget: 'error'`
原子地拒绝覆盖已有文件。不要让多个进程共写同一个暂存路径。
+ 下载成品与工具 `current.json` 共用 `replaceFile` 发布;Windows 拒绝 rename 覆盖时
+ 复用原生原子替换工具,不先删除旧目标。校验失败或发布失败不能主动删除旧目标。
- 同一目标同时只能有一份下载;完全相同的参数可复用在途 Promise,来源、策略、回调或
取消信号不同则拒绝冲突,不能共享另一调用方更宽松的校验结果。
- `download()` resolve 表示大小和 SHA-256 已通过且文件已就位。
@@ -46,6 +48,7 @@ Ollama 本次共用下载层,仍保留其现有 runtime 解压和启动布局
GitHub 插件详情与「我的 Issues」通过 `GithubConnectButton` 复用同一窗口。
连接成功后分别重新加载插件配置区与强制刷新 Issues;列表已有请求时排队刷新,避免漏掉新登录态。
Issues 连接入口是可选增强,不作为原有 Cindy Issue 列表和提交能力的前置条件。
+已解析到 GitHub 身份时,搜索失败保留账号并使用刷新入口,不再次显示连接按钮。
GitHub 插件由宿主显示单一账号区,通过固定 GitHub `/user` 请求验证用户名与当前来源;
优先 gh,取不到凭证时才使用备用 PAT,不把网络或单项操作权限错误当作退出登录。
插件 1.2.8 起在 `/secrets` 的 `hostManagedSetup` 为 true 时仅显示折叠的备用 Token 区,