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。

feat(github): 统一下载能力并接通 gh 安装登录与账号入口

Dash09a1df4ba765
diff --git a/apps/desktop/src/main/__tests__/gitContextPrStatusService.test.ts b/apps/desktop/src/main/__tests__/gitContextPrStatusService.test.ts
index 08205e6c92..87ba9b0950 100644
--- a/apps/desktop/src/main/__tests__/gitContextPrStatusService.test.ts
+++ b/apps/desktop/src/main/__tests__/gitContextPrStatusService.test.ts
@@ -29,7 +29,9 @@ function remote(partial: Partial<PrRemoteState>): PrRemoteState {
describe('mapRemoteToStatus', () => {
it('四态映射:merged 优先于 closed,draft 仅在 open', () => {
expect(mapRemoteToStatus(remote({ state: 'closed', merged: true }))).toBe('merged');
- expect(mapRemoteToStatus(remote({ state: 'closed', merged_at: '2026-06-12T00:00:00Z' }))).toBe('merged');
+ expect(mapRemoteToStatus(remote({ state: 'closed', merged_at: '2026-06-12T00:00:00Z' }))).toBe(
+ 'merged',
+ );
expect(mapRemoteToStatus(remote({ state: 'closed' }))).toBe('closed');
expect(mapRemoteToStatus(remote({ draft: true }))).toBe('draft');
expect(mapRemoteToStatus(remote({}))).toBe('open');
@@ -51,6 +53,16 @@ describe('filterPrStatusQueriesForRefs', () => {
});
describe('PrStatusService', () => {
+ it('expired credentials offer local sign-in while remote callers retain no-token', async () => {
+ const svc = new PrStatusService({
+ readToken: TOKEN_OK,
+ fetchPr: async () => {
+ throw Object.assign(new Error('Unauthorized'), { status: 401 });
+ },
+ });
+ expect(await svc.getStatuses([Q])).toMatchObject([{ reason: 'gh-not-logged-in' }]);
+ expect(await svc.getStatuses([Q], { remote: true })).toMatchObject([{ reason: 'no-token' }]);
+ });
it('正常查询返回状态与标题', async () => {
const svc = new PrStatusService({
readToken: TOKEN_OK,
@@ -82,7 +94,10 @@ describe('PrStatusService', () => {
readToken: TOKEN_OK,
fetchPr: async () => remote({}),
});
- expect((await withoutCount.getStatuses([Q]))[0]).toMatchObject({ ok: true, unresolvedCount: null });
+ expect((await withoutCount.getStatuses([Q]))[0]).toMatchObject({
+ ok: true,
+ unresolvedCount: null,
+ });
});
it('TTL 内命中缓存,过期后重新拉取', async () => {
@@ -104,9 +119,7 @@ describe('PrStatusService', () => {
it('并发同一 PR 只发一次请求(in-flight 去重)', async () => {
let resolveFetch!: (v: PrRemoteState) => void;
- const fetchPr = vi.fn(
- () => new Promise<PrRemoteState>((res) => (resolveFetch = res)),
- );
+ const fetchPr = vi.fn(() => new Promise<PrRemoteState>((res) => (resolveFetch = res)));
const svc = new PrStatusService({ readToken: TOKEN_OK, fetchPr });
const p1 = svc.getStatuses([Q]);
const p2 = svc.getStatuses([Q]);
diff --git a/apps/desktop/src/main/__tests__/githubConnection.test.ts b/apps/desktop/src/main/__tests__/githubConnection.test.ts
new file mode 100644
index 0000000000..02d5045d46
--- /dev/null
+++ b/apps/desktop/src/main/__tests__/githubConnection.test.ts
@@ -0,0 +1,54 @@
+import { describe, expect, it, vi } from 'vitest';
+import { githubConnection } from '../git-context/githubConnection';
+
+describe('GitHub account verification', () => {
+ it('verifies the selected credential without returning secrets or unrelated user data', async () => {
+ const fallback = vi.fn(() => 'fake-fallback');
+ const fetcher = vi.fn(
+ async () => new Response(JSON.stringify({ login: 'test-user', email: 'private' })),
+ );
+ expect(
+ await githubConnection({
+ readGh: async () => 'fake-gh',
+ readFallback: fallback,
+ fetch: fetcher,
+ }),
+ ).toEqual({ status: 'connected', source: 'gh-cli', login: 'test-user' });
+ expect(fallback).not.toHaveBeenCalled();
+ expect(fetcher).toHaveBeenCalledWith(
+ 'https://api.github.com/user',
+ expect.objectContaining({ redirect: 'error' }),
+ );
+ });
+ it('uses the fallback only when no local credential is available', async () => {
+ expect(
+ await githubConnection({
+ readGh: async () => null,
+ readFallback: () => 'fake',
+ fetch: async () => new Response('{"login":"test"}'),
+ }),
+ ).toEqual({ status: 'connected', source: 'token', login: 'test' });
+ const fetcher = vi.fn();
+ expect(
+ await githubConnection({
+ readGh: async () => null,
+ readFallback: () => null,
+ fetch: fetcher,
+ }),
+ ).toEqual({ status: 'missing' });
+ expect(fetcher).not.toHaveBeenCalled();
+ });
+ it.each([
+ [401, 'auth'],
+ [403, 'forbidden'],
+ [500, 'network'],
+ ] as const)('classifies HTTP %s without exposing its body', async (code, status) => {
+ expect(
+ await githubConnection({
+ readGh: async () => 'fake',
+ readFallback: () => null,
+ fetch: async () => new Response('private server message', { status: code }),
+ }),
+ ).toEqual({ status, source: 'gh-cli' });
+ });
+});
diff --git a/apps/desktop/src/main/__tests__/githubSetup.test.ts b/apps/desktop/src/main/__tests__/githubSetup.test.ts
new file mode 100644
index 0000000000..eaa3d80e37
--- /dev/null
+++ b/apps/desktop/src/main/__tests__/githubSetup.test.ts
@@ -0,0 +1,141 @@
+import { describe, expect, it, vi } from 'vitest';
+import { GithubSetup, deviceCodeFromOutput } from '../git-context/githubSetup';
+import { systemGhBinary } from '../git-context/ghBinary';
+import { ghArtifact } from '../git-context/ghArtifact';
+import { createGhCliTokenSource } from '../git-context/ghCliTokenSource';
+import { PrStatusService } from '../git-context/prStatusService';
+
+function fixture() {
+ const deps = {
+ resolveBinary: vi.fn(async () => '/existing/gh'),
+ available: vi.fn(async () => true),
+ authenticated: vi.fn(async () => true),
+ install: vi.fn(async (_signal: AbortSignal, _update: unknown) => '/managed/gh'),
+ login: vi.fn(async (_binary: string, _signal: AbortSignal, _update: unknown) => {}),
+ connected: vi.fn(),
+ };
+ return { deps, setup: new GithubSetup(deps) };
+}
+describe('GitHub setup', () => {
+ it('reuses existing authentication and refreshes consumers without installing or logging in', async () => {
+ const { setup, deps } = fixture();
+ setup.start();
+ await vi.waitFor(() => expect(setup.snapshot().phase).toBe('connected'));
+ expect(deps.install).not.toHaveBeenCalled();
+ expect(deps.login).not.toHaveBeenCalled();
+ expect(deps.connected).toHaveBeenCalledOnce();
+ });
+ it('installs once, authorizes the selected binary and verifies before publishing success', async () => {
+ const { setup, deps } = fixture();
+ deps.available.mockResolvedValue(false);
+ deps.authenticated.mockResolvedValueOnce(false).mockResolvedValueOnce(true);
+ setup.start();
+ setup.start();
+ await vi.waitFor(() => expect(setup.snapshot().phase).toBe('connected'));
+ expect(deps.install).toHaveBeenCalledOnce();
+ expect(deps.login.mock.calls[0][0]).toBe('/managed/gh');
+ expect(deps.authenticated).toHaveBeenCalledTimes(2);
+ });
+ it('never treats successful process exit with unusable auth as connected', async () => {
+ const { setup, deps } = fixture();
+ deps.authenticated.mockResolvedValue(false);
+ setup.start();
+ await vi.waitFor(() => expect(setup.snapshot()).toEqual({ phase: 'error', error: 'login' }));
+ expect(deps.connected).not.toHaveBeenCalled();
+ });
+ it('sanitizes install errors and permits retry', async () => {
+ const { setup, deps } = fixture();
+ deps.available.mockResolvedValue(false);
+ deps.install.mockRejectedValueOnce(new Error('/private/path?token=secret'));
+ setup.start();
+ await vi.waitFor(() => expect(setup.snapshot()).toEqual({ phase: 'error', error: 'install' }));
+ setup.start();
+ await vi.waitFor(() => expect(setup.snapshot().phase).toBe('connected'));
+ });
+ it('cancellation prevents a late installer from starting login', async () => {
+ const { setup, deps } = fixture();
+ deps.available.mockResolvedValue(false);
+ let finish!: (binary: string) => void;
+ deps.install.mockImplementation(
+ () =>
+ new Promise((resolve) => {
+ finish = resolve;
+ }),
+ );
+ setup.start();
+ await vi.waitFor(() => expect(deps.install).toHaveBeenCalledOnce());
+ setup.cancel();
+ setup.start();
+ finish('/managed/gh');
+ await vi.waitFor(() => expect(setup.snapshot().phase).toBe('cancelled'));
+ expect(deps.login).not.toHaveBeenCalled();
+ expect(deps.connected).not.toHaveBeenCalled();
+ });
+ it('reads only a complete device code, including the clipboard configuration variant', () => {
+ expect(deviceCodeFromOutput('! First copy your one-time code: ABCD-123')).toBeUndefined();
+ expect(deviceCodeFromOutput('! First copy your one-time code: ABCD-1234\n')).toBe('ABCD-1234');
+ expect(deviceCodeFromOutput('! One-time code (ABCD-1234) copied to clipboard')).toBe(
+ 'ABCD-1234',
+ );
+ expect(deviceCodeFromOutput('secret gho_test')).toBeUndefined();
+ });
+ it('finds home-local gh even when the GUI PATH is stale', () => {
+ expect(systemGhBinary('darwin', (p) => p === '/home/test/.local/bin/gh', '/home/test')).toBe(
+ '/home/test/.local/bin/gh',
+ );
+ });
+ it('supports pinned macOS, Windows and Linux archives, rejects unknown hosts', () => {
+ for (const os of ['darwin', 'win32', 'linux'])
+ for (const arch of ['arm64', 'x64']) {
+ expect(ghArtifact(os, arch)?.sha256).toMatch(/^[a-f0-9]{64}$/);
+ }
+ expect(ghArtifact('linux', 'ia32')).toBeUndefined();
+ });
+ it('invalidates negative token reads without letting an old flight re-poison the cache', async () => {
+ const callbacks: Array<(err: Error | null, stdout: string, stderr: string) => void> = [];
+ const source = createGhCliTokenSource({
+ existsFn: () => false,
+ execFileFn: (_f, _a, _o, cb) => {
+ callbacks.push(cb);
+ },
+ });
+ const old = source.readToken();
+ source.invalidate();
+ const fresh = source.readToken();
+ callbacks[1](null, 'new', '');
+ expect(await fresh).toBe('new');
+ callbacks[0](new Error('not logged in'), '', '');
+ await old;
+ expect(await source.readToken()).toBe('new');
+ expect(callbacks).toHaveLength(2);
+ });
+ it('does not let a PR response started before login populate the new cache', async () => {
+ const query = { owner: 'owner', repo: 'repo', prNumber: 1 };
+ let finish!: (value: {
+ state: 'closed';
+ title: string;
+ html_url: string;
+ branch: string;
+ }) => void;
+ const fetchPr = vi
+ .fn()
+ .mockImplementationOnce(
+ () =>
+ new Promise((resolve) => {
+ finish = resolve;
+ }),
+ )
+ .mockResolvedValue({ state: 'open', title: 'fresh', html_url: '', branch: '' });
+ const service = new PrStatusService({
+ readToken: async () => ({ ok: true, token: 'test' }),
+ fetchPr,
+ });
+ const old = service.getStatuses([query]);
+ await vi.waitFor(() => expect(fetchPr).toHaveBeenCalledOnce());
+ service.invalidate();
+ expect(await service.getStatuses([query])).toMatchObject([{ title: 'fresh' }]);
+ finish({ state: 'closed', title: 'old', html_url: '', branch: '' });
+ await old;
+ expect(await service.getStatuses([query])).toMatchObject([{ title: 'fresh' }]);
+ });
+});
diff --git a/apps/desktop/src/main/__tests__/githubSetupIpc.test.ts b/apps/desktop/src/main/__tests__/githubSetupIpc.test.ts
new file mode 100644
index 0000000000..8b0160d906
--- /dev/null
+++ b/apps/desktop/src/main/__tests__/githubSetupIpc.test.ts
@@ -0,0 +1,59 @@
+import { describe, expect, it, vi } from 'vitest';
+vi.mock('../secrets/providerSecretStore', () => ({ readGhostSecret: vi.fn() }));
+vi.mock('../maker-host/outbound-fetch', () => ({ outboundFetch: vi.fn() }));
+vi.mock('../appSessionState', () => ({ activeOwnerScopeKey: () => 'test-owner' }));
+const mocks = vi.hoisted(() => ({
+ handlers: new Map<string, (...args: any[]) => unknown>(),
+ guard: vi.fn(),
+ start: vi.fn(),
+ invalidate: vi.fn(),
+ send: vi.fn(),
+ connected: undefined as undefined | (() => void),
+}));
+vi.mock('electron', () => ({
+ app: { getPath: () => '/test/userData', once: vi.fn() },
+ ipcMain: {
+ handle: (name: string, fn: (...args: any[]) => unknown) => mocks.handlers.set(name, fn),
+ },
+ BrowserWindow: {
+ getAllWindows: () => [{ isDestroyed: () => false, webContents: { send: mocks.send } }],
+ },
+}));
+vi.mock('../security/trustedAppRenderer', () => ({ assertTrustedAppRendererEvent: mocks.guard }));
+vi.mock('../git-context/ghBinary', () => ({ configureManagedGhRoot: vi.fn() }));
+vi.mock('../git-context/ghCliTokenSource', () => ({
+ getSharedGhCliTokenSource: () => ({ invalidate: mocks.invalidate }),
+}));
+vi.mock('../git-context/githubSetup', () => ({
+ createGithubSetup: (_root: string, connected: () => void) => {
+ mocks.connected = connected;
+ return { start: mocks.start, snapshot: () => ({ phase: 'idle' }), cancel: vi.fn() };
+ },
+}));
+import { registerGithubSetupIpc } from '../git-context/githubSetupIpc';
+
+describe('GitHub setup IPC boundary', () => {
+ it('rejects untrusted callers and arbitrary payloads before invoking the installer', () => {
+ registerGithubSetupIpc(vi.fn());
+ const start = mocks.handlers.get('git-context:github-setup:start')!;
+ mocks.guard.mockImplementationOnce(() => {
+ throw new Error('untrusted');
+ });
+ expect(() => start({})).toThrow('untrusted');
+ expect(() => start({}, { url: 'https://attacker.test/tool' })).toThrow();
+ expect(mocks.start).not.toHaveBeenCalled();
+ start({});
+ expect(mocks.start).toHaveBeenCalledOnce();
+ });
+ it('clears both caches before notifying every window', () => {
+ const invalidate = vi.fn();
+ registerGithubSetupIpc(invalidate);
+ mocks.connected!();
+ expect(mocks.invalidate).toHaveBeenCalledOnce();
+ expect(invalidate).toHaveBeenCalledOnce();
+ expect(mocks.send).toHaveBeenCalledWith('git-context:github-connected');
+ expect(invalidate.mock.invocationCallOrder[0]).toBeLessThan(
+ mocks.send.mock.invocationCallOrder[0],
+ );
+ });
+});
diff --git a/apps/desktop/src/main/cindy-brain/index.ts b/apps/desktop/src/main/cindy-brain/index.ts
index 8c46a25c73..a00a5f6d90 100644
--- a/apps/desktop/src/main/cindy-brain/index.ts
+++ b/apps/desktop/src/main/cindy-brain/index.ts
@@ -1,5 +1,11 @@
-import { registerGhostCardRemoteProvider, persistGhostCardWithRemoteChange } from './cardRemoteResource.js';
-import { openDeviceAuthorizationCard, openPluginAuthorizationCard } from '../plugin-oauth/deviceCard.js';
+import {
+ registerGhostCardRemoteProvider,
+ persistGhostCardWithRemoteChange,
+} from './cardRemoteResource.js';
+import {
+ openDeviceAuthorizationCard,
+ openPluginAuthorizationCard,
+} from '../plugin-oauth/deviceCard.js';
import { t as authorizationText } from '../i18n.js';
import { getBotAuthorizationService } from '../maker-ipc/botAuthorizationService.js';
import { isResidentBrowserGhost, spawnResidentGhost } from './residentGhost.js';
@@ -117,19 +123,12 @@ import {
renameBuiltinTombstone,
type ProvisionIdentity,
} from './builtinGhostProvisioner.js';
-import {
- getAccessToken,
- getAuthState,
- onAuthStateChange,
-} from '../authManager.js';
+import { getAccessToken, getAuthState, onAuthStateChange } from '../authManager.js';
import { serverApiFetch } from '../serverApiClient.js';
import { getClientEndpoint } from '../clientEndpointsService.js';
import { createGhostOauthBrokerClient } from './ghostOauthBroker.js';
import { readRefImagesWithinBudget } from './refImageBudget.js';
-import {
- resolveCachedGhostRepoRoot,
- type GhostRepoRootCacheEntry,
-} from './repoRoot.js';
+import { resolveCachedGhostRepoRoot, type GhostRepoRootCacheEntry } from './repoRoot.js';
import { takePendingCindyInstall } from './openFileInstall.js';
import { GhostRuntime } from './runtime/GhostRuntime.js';
import {
@@ -340,7 +339,10 @@ import { LibrarySqlService, defaultLibraryDbWorkerPath } from './librarySqlServi
import { trashGhostLibrary } from './libraryTrash.js';
import { migrateGhostLibrary } from './libraryMigrate.js';
import { setGhostLibraryFileResolver } from './runtime/electronSandboxAdapter.js';
-import { createBetterSqliteDatabase, resolveBetterSqliteModuleEntry } from '../localDb/betterSqliteFactory.js';
+import {
+ createBetterSqliteDatabase,
+ resolveBetterSqliteModuleEntry,
+} from '../localDb/betterSqliteFactory.js';
import { getGhostGrantConfirmBridge } from './ghostGrantConfirmBridge.js';
import { getSessionFsSnapshot, getSessionRowSnapshot } from '../localDb/ipc/sessions.js';
import { getTeamByWorkerSession } from '../localDb/orcaTeamStore.js';
@@ -440,7 +442,10 @@ import {
markGhostRecentlyUsed,
} from './ghostRecentUsageStore.js';
import { createXaiImageChannel } from './xaiImageClient.js';
-import { getCindyProxyMediaService, getCindyVideoProviderRegistry } from '../mcp-integrations/cindyProxyMedia.js';
+import {
+ getCindyProxyMediaService,
+ getCindyVideoProviderRegistry,
+} from '../mcp-integrations/cindyProxyMedia.js';
import { getCindyProxySearchService } from '../mcp-integrations/cindyProxySearch.js';
import { normalizeImageParameters } from '../cindy-media/imageParameters.js';
import { ImageChannelRegistry, decodeImageResponse } from './imageChannelRegistry.js';
@@ -448,7 +453,11 @@ import { createGeminiImageChannel } from './geminiImageClient.js';
import { createCodexImageChannel } from './codexImageClient.js';
import { getCodexImageAuthBinding } from './codexImageAuthBinding.js';
import { createGatewayImageClient } from '../cindy-proxy-media/api/gatewayImageClient.js';
-import { createByokImageChannel, pruneDynamicImageChannels, registerByokImageChannels } from './byokImageChannel.js';
+import {
+ createByokImageChannel,
+ pruneDynamicImageChannels,
+ registerByokImageChannels,
+} from './byokImageChannel.js';
import { readByokCredential, readByokInferenceBase } from '../model-access/byokCredentials.js';
import { createXaiVideoProvider } from '../cindy-proxy-media/video/providers/xai.js';
import * as blobStore from '../cindy-media/blobStore.js';
@@ -667,9 +676,9 @@ const ghostOwnerScope: GhostOwnerScope = {
isCurrent: (scope) =>
!!scope && isSameAppSession(scope as ActiveAppSession, getActiveAppSession()),
isStable: (scope) =>
- !!scope
- && !isAppSessionBoundaryPending()
- && isSameAppSession(scope as ActiveAppSession, getActiveAppSession()),
+ !!scope &&
+ !isAppSessionBoundaryPending() &&
+ isSameAppSession(scope as ActiveAppSession, getActiveAppSession()),
onInvalidated: (ghostId) => {
try {
getGhostRuntime().stop(ghostId);
@@ -709,10 +718,13 @@ function getLegacyGhostRecoveryStatusForActiveSession(): LegacyGhostRecoveryStat
// 与重试都经此)。降级为"该根无墓碑"并记录;漏掉的 builtin 排除仍由 backfill 的
// isTrustedBundledId 闸兜底,不会因此把随包 id 误迁 —— 对齐 ghosts:builtin-status
// 的降级语义,而不是让 recovery UI 整体不可用(§5 恢复入口必须可用)。
- log.warn('legacy builtin tombstone root unreadable during recovery status; treated as empty', {
- root,
- error: err instanceof Error ? err.message : String(err),
- });
+ log.warn(
+ 'legacy builtin tombstone root unreadable during recovery status; treated as empty',
+ {
+ root,
+ error: err instanceof Error ? err.message : String(err),
+ },
+ );
return [] as string[];
}
}),
@@ -856,11 +868,7 @@ async function retryLegacyGhostRecoveryForActiveSession(): Promise<LegacyGhostRe
throw error;
}
if (shouldAbort()) return getLegacyGhostRecoveryStatusForActiveSession();
- if (
- result.moved === 0 &&
- !result.provisioningStateMoved &&
- !result.recoveredIds?.length
- ) {
+ if (result.moved === 0 && !result.provisioningStateMoved && !result.recoveredIds?.length) {
restartStoppedActiveGhosts();
return getLegacyGhostRecoveryStatusForActiveSession();
}
@@ -941,9 +949,7 @@ export function isGhostAvailableForActiveSession(id: string): boolean {
}
/** Live Host capability gate shared by Agent transports and Renderer IPC. */
-export function getIOSSimulatorPluginAccessDecision(
- workingDir: string | null = null,
-) {
+export function getIOSSimulatorPluginAccessDecision(workingDir: string | null = null) {
return resolveIOSSimulatorPluginAccess(getGhostManager().list(), workingDir, {
isAvailableForActiveSession: isGhostAvailableForActiveSession,
isDisabledForWorkdir: isGhostDisabledForWorkdir,
@@ -952,9 +958,9 @@ export function getIOSSimulatorPluginAccessDecision(
function availableGhosts(): InstalledGhost[] {
if (isAppSessionBoundaryPending()) return [];
- return getGhostManager().list().filter((ghost) =>
- isGhostAvailableForActiveSession(ghost.manifest.id),
- );
+ return getGhostManager()
+ .list()
+ .filter((ghost) => isGhostAvailableForActiveSession(ghost.manifest.id));
}
function projectGhostForRenderer(ghost: InstalledGhost): InstalledGhost {
@@ -964,17 +970,14 @@ function projectGhostForRenderer(ghost: InstalledGhost): InstalledGhost {
const expiredAccountCount = (runtimeManifest.network?.secrets ?? []).reduce(
(count, secret) =>
secret.source === 'oauth' && secret.oauth
- ? count +
- oauthManager.clientMigrationExpiredAccountCount(runtimeManifest.id, secret.key)
+ ? count + oauthManager.clientMigrationExpiredAccountCount(runtimeManifest.id, secret.key)
: count,
0,
);
const suggest = getGhostOauthReauthSuggest(runtimeManifest);
return {
...ghost,
- ...(expiredAccountCount > 0
- ? { oauthAuthorizationExpired: { expiredAccountCount } }
- : {}),
+ ...(expiredAccountCount > 0 ? { oauthAuthorizationExpired: { expiredAccountCount } } : {}),
...(suggest
? {
oauthScopeStale: {
@@ -1058,12 +1061,14 @@ export async function interruptGhostCallsForAccountBoundary(): Promise<void> {
function listGhostOwnerProjectionRoots(): string[] {
const activeOwnerRoot = ownerScopedUserDataPath();
- return [...new Set([
- path.join(activeOwnerRoot, 'brain'),
- path.join(activeOwnerRoot, 'cindy-brain'),
- path.join(activeOwnerRoot, 'ghost-install-state'),
- ...listLegacyOwnerProjectionRoots(app.getPath('userData')),
- ])];
+ return [
+ ...new Set([
+ path.join(activeOwnerRoot, 'brain'),
+ path.join(activeOwnerRoot, 'cindy-brain'),
+ path.join(activeOwnerRoot, 'ghost-install-state'),
+ ...listLegacyOwnerProjectionRoots(app.getPath('userData')),
+ ]),
+ ];
}
/** Stop every sandbox and revoke global skill projections before changing the active data owner. */
@@ -1087,16 +1092,12 @@ let ipcRegistered = false;
/** 意识仓库根(userData/cindy-brain;旧 brain 目录首次解析时原地迁移)。 */
let brainRootCache: GhostRepoRootCacheEntry | null = null;
function brainRootDir(): string {
- brainRootCache = resolveCachedGhostRepoRoot(
- brainRootCache,
- activeOwnerScopeKey(),
- {
- userDataDir: ownerScopedUserDataPath(),
- exists: (p) => fs.existsSync(p),
- rename: (from, to) => fs.renameSync(from, to),
- log,
- },
- );
+ brainRootCache = resolveCachedGhostRepoRoot(brainRootCache, activeOwnerScopeKey(), {
+ userDataDir: ownerScopedUserDataPath(),
+ exists: (p) => fs.existsSync(p),
+ rename: (from, to) => fs.renameSync(from, to),
+ log,
+ });
return brainRootCache.rootDir;
}
@@ -1360,10 +1361,7 @@ async function reconcileBuiltinGhostsLocked(
if (renameBuiltinTombstone(brainRootDir(), fromId, toId, log)) {
log.info('builtin ghost tombstone carried over rename', { fromId, toId });
}
- renameDisabledCarry.set(
- toId,
- hasDisabledMarker(path.join(brainRootDir(), fromId)),
- );
+ renameDisabledCarry.set(toId, hasDisabledMarker(path.join(brainRootDir(), fromId)));
}
}
// "播种进行中"胶囊提示:只在真的动手(装/覆盖/回收)时亮起,no-op 对账
@@ -1560,8 +1558,7 @@ export function getGhostManager(): GhostManager {
// 随包批准入口的 builtin-only 边界:id 必须对应一颗随包种子。该入口不经用户
// 确认就铸出批准,不能只靠"唯一调用者是随包对账"这条纪律。
isTrustedBundledId: (id) => listBuiltinSeedIds(builtinSeedRootDirs()).includes(id),
- isTokenBrokerAuthorized: (manifest) =>
- isGhostTokenBrokerAuthorized(manifest.id, 'install'),
+ isTokenBrokerAuthorized: (manifest) => isGhostTokenBrokerAuthorized(manifest.id, 'install'),
isTrustedBundledSource,
recordBuiltinTombstone: (id) => recordBuiltinTombstone(brainRootDir(), id, log),
clearBuiltinTombstone: (id) => clearBuiltinTombstone(brainRootDir(), id, log),
@@ -1770,19 +1767,23 @@ export function getGhostNodeRuntimeBroker(): GhostNodeRuntimeBroker {
if (!nodeRuntimeBrokerSingleton) {
nodeRuntimeBrokerSingleton = new GhostNodeRuntimeBroker({
getGhost: findAvailableGhost,
- getCallSignal: (ghostId, callId) => getGhostPipeDispatcher().getPendingCallSignal(ghostId, callId),
+ getCallSignal: (ghostId, callId) =>
+ getGhostPipeDispatcher().getPendingCallSignal(ghostId, callId),
getCallSessionId: (ghostId, callId) =>
getGhostPipeDispatcher().getPendingCallSessionId(ghostId, callId),
- openSecretInput: input => {
+ openSecretInput: (input) => {
const bridge = getGhostSetupInteractionBridge();
if (!bridge) throw new Error('NODE_SECRET_INPUT_UNAVAILABLE');
- return requestNodeSecretSetup({
- bridge,
- changeBus: getGhostSetupChangeBus(),
- getManifest: ghostId => findAvailableGhost(ghostId)?.manifest ?? null,
- secretSaved: ghostSecretSaved,
- storeSecret: storeGhostSecret,
- }, input);
+ return requestNodeSecretSetup(
+ {
+ bridge,
+ changeBus: getGhostSetupChangeBus(),
+ getManifest: (ghostId) => findAvailableGhost(ghostId)?.manifest ?? null,
+ secretSaved: ghostSecretSaved,
+ storeSecret: storeGhostSecret,
+ },
+ input,
+ );
},
openDeviceAuthorization: (input) => {
const bridge = getGhostSetupInteractionBridge();
@@ -1796,14 +1797,17 @@ export function getGhostNodeRuntimeBroker(): GhostNodeRuntimeBroker {
},
});
},
- openAuthorization: input => {
+ openAuthorization: (input) => {
const bridge = getGhostSetupInteractionBridge();
if (!bridge) throw new Error('PLUGIN_AUTHORIZATION_UNAVAILABLE');
return openPluginAuthorizationCard(input, {
- bridge, openExternal: url => shell.openExternal(url),
- copyDeviceCode: code => copyPrivateDeviceCode(clipboard, code),
- copy: { title: authorizationText('pluginDeviceAuthorization.title'),
- description: authorizationText('pluginDeviceAuthorization.description') },
+ bridge,
+ openExternal: (url) => shell.openExternal(url),
+ copyDeviceCode: (code) => copyPrivateDeviceCode(clipboard, code),
+ copy: {
+ title: authorizationText('pluginDeviceAuthorization.title'),
+ description: authorizationText('pluginDeviceAuthorization.description'),
+ },
});
},
ownerScope: ghostOwnerScope,
@@ -1812,10 +1816,18 @@ export function getGhostNodeRuntimeBroker(): GhostNodeRuntimeBroker {
resolveOauthSecret: async (ghostId, secretKey, accountId) => {
const ghost = findAvailableGhost(ghostId);
const source = ghost
- ? withRuntimeFiloGoogleClient(ghost.manifest).network?.secrets?.find((s) => s.key === secretKey)
+ ? withRuntimeFiloGoogleClient(ghost.manifest).network?.secrets?.find(
+ (s) => s.key === secretKey,
+ )
: undefined;
- if (source?.source !== 'oauth' || !source.oauth) return { ok: false, error: 'INVALID_DECLARATION' };
- return getGhostOauthAccountManager().getFreshAccessToken(ghostId, secretKey, source.oauth, accountId);
+ if (source?.source !== 'oauth' || !source.oauth)
+ return { ok: false, error: 'INVALID_DECLARATION' };
+ return getGhostOauthAccountManager().getFreshAccessToken(
+ ghostId,
+ secretKey,
+ source.oauth,
+ accountId,
+ );
},
sendToGhost: (ghostId, payload) => {
sendToGhostLogic(ghostId, payload);
@@ -2696,10 +2708,7 @@ function readInstalledGhostManifestIdentity(
.list()
.find((candidate) => candidate.manifest.id === ghostId);
if (!ghost) return null;
- const result = readInstalledGhostManifestSnapshot(
- ghost.dir,
- GHOST_INSTALL_MANIFEST_MAX_BYTES,
- );
+ const result = readInstalledGhostManifestSnapshot(ghost.dir, GHOST_INSTALL_MANIFEST_MAX_BYTES);
return result.ok ? installedMarketManifestIdentity(result.snapshot) : null;
}
@@ -2739,8 +2748,9 @@ function getGhostFirstPartyFactsLoader(): GhostFirstPartyFactsLoader {
if (!ghostFirstPartyFactsLoaderSingleton) {
ghostFirstPartyFactsLoaderSingleton = loadGhostFirstPartyFactsLoader({
readInstalledBuiltin: (ghostId) =>
- getGhostManager().list().find((candidate) => candidate.manifest.id === ghostId)?.builtin ===
- true,
+ getGhostManager()
+ .list()
+ .find((candidate) => candidate.manifest.id === ghostId)?.builtin === true,
readMarketInstallation: (ghostId) => getPluginMarketLedger().installationForGhost(ghostId),
readApprovedPackageSha256: (ghostId) =>
getGhostManager().approvedInstallEvidence(ghostId)?.packageSha256 ?? null,
@@ -3111,7 +3121,12 @@ export function createWindowGhostInstallConsentPrompt(
id: contents.id,
send: (payload) => {
if (contents.isDestroyed()) return false;
- sendGhostContentsPush(contents, GHOST_INSTALL_CONSENT_REQUEST_CHANNEL, payload, ownerStamp);
+ sendGhostContentsPush(
+ contents,
+ GHOST_INSTALL_CONSENT_REQUEST_CHANNEL,
+ payload,
+ ownerStamp,
+ );
return true;
},
dismiss: (requestId) => {
@@ -3309,9 +3324,7 @@ let libraryExtraDirSync: LibraryExtraDirSyncFn | null = null;
let libraryExtraDirOwnerGhostId: string | null = null;
/** maker-ipc 注入:把 library 根同步进当前 Mivo 会话 extraDirs。cindy-brain 不反向依赖 register。 */
-export function setGhostLibraryExtraDirSync(
- sync: LibraryExtraDirSyncFn | null,
-): void {
+export function setGhostLibraryExtraDirSync(sync: LibraryExtraDirSyncFn | null): void {
libraryExtraDirSync = sync;
}
@@ -3465,21 +3478,15 @@ export function getGhostScheduleSlot(): GhostScheduleSlot {
function getVideoProviderRegistry() {
const registry = getCindyVideoProviderRegistry();
if (!registry) return null;
- const xaiCatalogProvider = getActiveCatalog().providers.find(
- (provider) => provider.id === 'xai',
- );
+ const xaiCatalogProvider = getActiveCatalog().providers.find((provider) => provider.id === 'xai');
const xaiCatalogProviderId = xaiCatalogProvider?.id;
const xaiAliases = xaiCatalogProvider?.videoModels?.map((model) => model.id) ?? [];
const routableXaiAliases = xaiCatalogProviderId
? xaiAliases.filter(
- (alias) =>
- !registry.hasAlias(alias) || registry.hasAlias(alias, xaiCatalogProviderId),
+ (alias) => !registry.hasAlias(alias) || registry.hasAlias(alias, xaiCatalogProviderId),
)
: [];
- if (
- xaiCatalogProviderId &&
- routableXaiAliases.some((alias) => !registry.hasAlias(alias))
- ) {
+ if (xaiCatalogProviderId && routableXaiAliases.some((alias) => !registry.hasAlias(alias))) {
registry.registerOrExtend(
createXaiVideoProvider({
modelAliases: routableXaiAliases,
@@ -3530,11 +3537,7 @@ function isXdMediaModelExecutableForCatalog(
LEGACY_CINDY_REQUEST_IMAGE_GUIDE_ID,
'image.generate',
) ||
- isMediaModelExecutableForGuide(
- modelId,
- LEGACY_CINDY_REQUEST_IMAGE_GUIDE_ID,
- 'image.edit',
- )
+ isMediaModelExecutableForGuide(modelId, LEGACY_CINDY_REQUEST_IMAGE_GUIDE_ID, 'image.edit')
);
}
if (kind === 'video') {
@@ -3575,10 +3578,7 @@ function getCatalogMediaConfig(
const access = readModelDisableOverrides();
const catalog = getActiveCatalog();
const xdMediaModelIds = getXdGatewayModels()
- .filter(
- (model) =>
- model.mode === 'image_generation' || model.mode === 'video_generation',
- )
+ .filter((model) => model.mode === 'image_generation' || model.mode === 'video_generation')
.map((model) => model.id);
// 旧 cindy-request 偏好不携带 providerId;同一完整 modelId 同时来自 XD 与
// 第三方时必须让托管默认来源先参与 first-wins,避免静默改用第三方凭证计费。
@@ -3599,12 +3599,7 @@ function getCatalogMediaConfig(
(providerId, modelId) =>
isProviderDisabled(access, providerId) ||
(providerId === 'xd' && kind !== 'embed'
- ? isModelDisabledWithUniqueLegacyBasename(
- access,
- providerId,
- modelId,
- xdMediaModelIds,
- )
+ ? isModelDisabledWithUniqueLegacyBasename(access, providerId, modelId, xdMediaModelIds)
: isModelDisabled(access, providerId, modelId)) ||
// active catalog 保留 Gateway 原始媒体事实源;旧 cindy-request 的同步目录
// 必须在消费边界复用已缓存的 Guide 预检结果,不能暴露这版客户端不可执行的型号。
@@ -3688,9 +3683,7 @@ interface CindyMediaPreferenceConfig {
}
/** Art 等插件的媒体偏好统一合并已就绪 Provider 与 Gateway 可执行模型。 */
-function getMediaPreferenceConfig(
- capability: GhostMediaCapability,
-): CindyMediaPreferenceConfig {
+function getMediaPreferenceConfig(capability: GhostMediaCapability): CindyMediaPreferenceConfig {
const kind = capability.startsWith('image.') ? 'image' : 'video';
const coreCapability: MediaCapability =
capability === 'video.edit' ? 'video.image_to_video' : capability;
@@ -3701,22 +3694,21 @@ function getMediaPreferenceConfig(
kind === 'video' ? listLocalProviderVideoModels(true) : listProviderMediaModels(),
kind,
(model) => supportsMediaCapability(model.modalities, coreCapability),
- )
- .map((model) => {
- const provider = providers.get(model.providerId);
- const providerName = provider?.name ?? model.providerId;
- return {
- id: encodeMediaPreference(model.providerId, model.id),
- modelId: model.id,
- label: model.name,
- modelName: model.name,
- providerId: model.providerId,
- providerName,
- group: providerName,
- ...(provider?.routing ? { routing: provider.routing } : {}),
- supportsEdit: supportsMediaCapability(model.modalities, 'image.edit'),
- };
- });
+ ).map((model) => {
+ const provider = providers.get(model.providerId);
+ const providerName = provider?.name ?? model.providerId;
+ return {
+ id: encodeMediaPreference(model.providerId, model.id),
+ modelId: model.id,
+ label: model.name,
+ modelName: model.name,
+ providerId: model.providerId,
+ providerName,
+ group: providerName,
+ ...(provider?.routing ? { routing: provider.routing } : {}),
+ supportsEdit: supportsMediaCapability(model.modalities, 'image.edit'),
+ };
+ });
const gatewayModels: CindyMediaPreferenceModel[] = selectExecutableCoreMediaModels(
filterEnabledGatewayMediaModels(
getXdGatewayModels(),
@@ -3731,26 +3723,25 @@ function getMediaPreferenceConfig(
),
kind,
(model) => isMediaModelExecutable(model.id, coreCapability),
- )
- .map((model) => {
- const provider = providers.get('xd');
- const providerName = provider?.name ?? 'Cindy AI';
- const modelName = model.name ?? model.id;
- return {
- id: encodeMediaPreference('xd', model.id),
- modelId: model.id,
- label: modelName,
- modelName,
- providerId: 'xd',
- providerName,
- group: providerName,
- ...(provider?.routing ? { routing: provider.routing } : {}),
- supportsEdit: isMediaModelExecutable(
- model.id,
- kind === 'image' ? 'image.edit' : 'video.image_to_video',
- ),
- };
- });
+ ).map((model) => {
+ const provider = providers.get('xd');
+ const providerName = provider?.name ?? 'Cindy AI';
+ const modelName = model.name ?? model.id;
+ return {
+ id: encodeMediaPreference('xd', model.id),
+ modelId: model.id,
+ label: modelName,
+ modelName,
+ providerId: 'xd',
+ providerName,
+ group: providerName,
+ ...(provider?.routing ? { routing: provider.routing } : {}),
+ supportsEdit: isMediaModelExecutable(
+ model.id,
+ kind === 'image' ? 'image.edit' : 'video.image_to_video',
+ ),
+ };
+ });
const models = [...gatewayModels, ...providerModels];
const standard = gatewayModels[0]?.id ?? providerModels[0]?.id;
return {
@@ -3830,7 +3821,9 @@ function getGhostMediaPreferenceConfig(
capability: GhostMediaCapability,
): CindyMediaPreferenceConfig {
const config = getMediaPreferenceConfig(capability);
- const ghost = getGhostManager().list().find((candidate) => candidate.manifest.id === ghostId);
+ const ghost = getGhostManager()
+ .list()
+ .find((candidate) => candidate.manifest.id === ghostId);
if (!ghost || !isProviderBlindCoreArt(ghost)) return config;
const models = collapseProviderBlindMediaModels(config.models, (model) => model.modelId);
const standard = models[0]?.id;
@@ -3898,31 +3891,28 @@ async function getGhostConfigurableMediaModels(
// registry executes them), so add their local projection explicitly and do
// not let an unavailable Gateway snapshot hide an otherwise ready xAI list.
const localVideoModels = type === 'video' ? listLocalProviderVideoModels(true) : [];
- const availability = await loadPluginMediaAvailability(
- type,
- localVideoModels.length,
- () => listExecutableMediaModels(),
- );
- const allModels = [...availability.models, ...localVideoModels].filter(
- (model, index, models) =>
- models.findIndex(
- (candidate) => candidate.id === model.id && candidate.providerId === model.providerId,
- ) === index,
- ).filter((model) =>
- isCatalogMediaModelVisible(
- model.providerId,
- model.id,
- 'defaultEnabled' in model ? model.defaultEnabled : undefined,
- ),
+ const availability = await loadPluginMediaAvailability(type, localVideoModels.length, () =>
+ listExecutableMediaModels(),
);
+ const allModels = [...availability.models, ...localVideoModels]
+ .filter(
+ (model, index, models) =>
+ models.findIndex(
+ (candidate) => candidate.id === model.id && candidate.providerId === model.providerId,
+ ) === index,
+ )
+ .filter((model) =>
+ isCatalogMediaModelVisible(
+ model.providerId,
+ model.id,
+ 'defaultEnabled' in model ? model.defaultEnabled : undefined,
+ ),
+ );
const candidates = selectExecutableCoreMediaModels(allModels, type);
const models = isProviderBlindCoreArt(ghost)
? collapseProviderBlindMediaModels(candidates, (model) => model.id)
: candidates;
- if (
- models.length === 0 &&
- availability.unavailable.some((model) => model.retryable)
- ) {
+ if (models.length === 0 && availability.unavailable.some((model) => model.retryable)) {
return {
ok: false,
errorCode: 'NOT_AVAILABLE',
@@ -3952,7 +3942,8 @@ async function getGhostConfigurableMediaModels(
}
: {}),
})),
- defaultModelId: models.find((model) => model.providerId === 'xd')?.id ?? models[0]?.id ?? null,
+ defaultModelId:
+ models.find((model) => model.providerId === 'xd')?.id ?? models[0]?.id ?? null,
defaultProviderId:
models.find((model) => model.providerId === 'xd')?.providerId ??
models[0]?.providerId ??
@@ -4217,9 +4208,8 @@ function getImageChannelRegistry(): ImageChannelRegistry {
return null;
};
const hasXaiApiImageKey = (): boolean =>
- getActiveCatalog().providers.some(
- (provider) => provider.id === XAI_API_CUSTOM_PROVIDER_ID,
- ) && readXaiApiImageKey() !== null;
+ getActiveCatalog().providers.some((provider) => provider.id === XAI_API_CUSTOM_PROVIDER_ID) &&
+ readXaiApiImageKey() !== null;
registry.register(
'xai-api',
createXaiImageChannel({
@@ -4276,8 +4266,7 @@ function getImageChannelRegistry(): ImageChannelRegistry {
},
brandLabel: 'OpenAI',
missingKeyMessage: 'OpenAI 图像 API key 未配置,请到「设置 → 模型供应商 → OpenAI」填入后重试',
- beforeDispatch: (model) =>
- assertMediaModelStillEnabled('image', `openai/${model}`, 'openai'),
+ beforeDispatch: (model) => assertMediaModelStillEnabled('image', `openai/${model}`, 'openai'),
});
const stripOpenaiPrefix = (id: string) =>
id.startsWith('openai/') ? id.slice('openai/'.length) : id;
@@ -4324,18 +4313,33 @@ function getImageChannelRegistry(): ImageChannelRegistry {
imageChannelRegistrySingleton = registry;
}
const imageProviders = getActiveCatalog().providers;
- pruneDynamicImageChannels(imageChannelRegistrySingleton, imageProviders, registeredCodexImageAccounts, registeredByokImageAccounts);
+ pruneDynamicImageChannels(
+ imageChannelRegistrySingleton,
+ imageProviders,
+ registeredCodexImageAccounts,
+ registeredByokImageAccounts,
+ );
for (const provider of imageProviders) {
- if (isOrganizationManagedProvider(provider) || provider.auth.native !== 'codex' || registeredCodexImageAccounts.has(provider.id)) continue;
+ if (
+ isOrganizationManagedProvider(provider) ||
+ provider.auth.native !== 'codex' ||
+ registeredCodexImageAccounts.has(provider.id)
+ )
+ continue;
const providerId = provider.id;
- imageChannelRegistrySingleton.register(providerId, createCodexImageChannel({
+ imageChannelRegistrySingleton.register(
providerId,
- hasOAuthLogin: () => getCodexImageAuthBinding().hasAuth?.(providerId) === true,
- getAuth: () => getCodexImageAuthBinding().getAuth(providerId),
- onAuthFailure: async (failure) => { await getCodexImageAuthBinding().onAuthFailure(failure, providerId); },
- fetchImplementation: ((url, init) => outboundFetch(url as string, init)) as typeof fetch,
- beforeDispatch: (model) => assertMediaModelStillEnabled('image', model, providerId),
- }));
+ createCodexImageChannel({
+ providerId,
+ hasOAuthLogin: () => getCodexImageAuthBinding().hasAuth?.(providerId) === true,
+ getAuth: () => getCodexImageAuthBinding().getAuth(providerId),
+ onAuthFailure: async (failure) => {
+ await getCodexImageAuthBinding().onAuthFailure(failure, providerId);
+ },
+ fetchImplementation: ((url, init) => outboundFetch(url as string, init)) as typeof fetch,
+ beforeDispatch: (model) => assertMediaModelStillEnabled('image', model, providerId),
+ }),
+ );
registeredCodexImageAccounts.add(providerId);
}
// Organization BYOK image models get their own channel. Do not reuse xd /
@@ -4353,8 +4357,12 @@ function getImageChannelRegistry(): ImageChannelRegistry {
getApiKey: () => readByokCredential(providerId, 'image'),
getBaseUrl: () => readByokInferenceBase(providerId),
getSupportsEdit: () => {
- const current = getActiveCatalog().providers.find((candidate) => candidate.id === providerId);
- return (current?.imageModels ?? []).some((model) => model.modalities?.input.includes('image') === true);
+ const current = getActiveCatalog().providers.find(
+ (candidate) => candidate.id === providerId,
+ );
+ return (current?.imageModels ?? []).some(
+ (model) => model.modalities?.input.includes('image') === true,
+ );
},
fetchImplementation: ((url, init) => outboundFetch(url as string, init)) as typeof fetch,
beforeDispatch: (model) => assertMediaModelStillEnabled('image', model, providerId),
@@ -4754,21 +4762,8 @@ export function getGhostCindySlot(): GhostCindySlot {
getGhostPipeDispatcher().holdCall(ghostId, callId, budgetMs),
releasePipeCall: (ghostId, callId) => getGhostPipeDispatcher().releaseCall(ghostId, callId),
claimPipeCall: (ghostId, callId, callerTool, binding, requestKey) =>
- getGhostPipeDispatcher().claimPendingCall(
- ghostId,
- callId,
- callerTool,
- binding,
- requestKey,
- ),
- settlePipeCallClaim: (
- ghostId,
- callId,
- callerTool,
- binding,
- requestKey,
- allowRetry,
- ) =>
+ getGhostPipeDispatcher().claimPendingCall(ghostId, callId, callerTool, binding, requestKey),
+ settlePipeCallClaim: (ghostId, callId, callerTool, binding, requestKey, allowRetry) =>
getGhostPipeDispatcher().settlePendingCallClaim(
ghostId,
callId,
@@ -4954,9 +4949,7 @@ export async function reconcileGhostOauthAccountsForActiveOwner(): Promise<boole
if (reconciliation.retryPending) retryPending = true;
});
}
- return !retryPending
- && !isAppSessionBoundaryPending()
- && activeOwnerScopeKey() === ownerScope;
+ return !retryPending && !isAppSessionBoundaryPending() && activeOwnerScopeKey() === ownerScope;
});
}
@@ -5182,7 +5175,13 @@ export async function executeGhostSetupAction(args: {
args.ghostId,
secretKey,
decl,
- { deliveryHosts: runtimeManifest.network?.hosts, remote, onAuthorizationUrl: remote ? undefined : args.onAuthorizationUrl, assertCurrent: args.assertCurrent, beforeCommit: args.beforeCommit },
+ {
+ deliveryHosts: runtimeManifest.network?.hosts,
+ remote,
+ onAuthorizationUrl: remote ? undefined : args.onAuthorizationUrl,
+ assertCurrent: args.assertCurrent,
+ beforeCommit: args.beforeCommit,
+ },
);
remote?.finish(connected.ok);
return connected.ok
@@ -5196,7 +5195,8 @@ export async function executeGhostSetupAction(args: {
};
} catch (error) {
remote?.finish(false);
- if (remote) return { ok: false, errorCode: 'AUTH_FAILED', message: 'Remote authorization unavailable' };
+ if (remote)
+ return { ok: false, errorCode: 'AUTH_FAILED', message: 'Remote authorization unavailable' };
throw error;
}
}
@@ -5228,7 +5228,9 @@ export async function executeGhostSetupAction(args: {
* 仅供 trusted Desktop inline-setup IPC 调用。Secret 值不经过通用
* InteractionDecision,也不进入 assessment、snapshot 或日志。
*/
-export async function executeGhostSetupInlineAction(args: GhostSetupInlineActionInput): Promise<GhostSetupActionResult> {
+export async function executeGhostSetupInlineAction(
+ args: GhostSetupInlineActionInput,
+): Promise<GhostSetupActionResult> {
return executeGhostSetupInlineSubmission(
{
getAssessment: getGhostSetupAssessment,
@@ -5256,19 +5258,26 @@ export async function executeGhostSetupInlineAction(args: GhostSetupInlineAction
}
/** Only called under the authenticated remote connection-card context. */
-export function bindGhostSetupConnectionAction(args: { ghostId: string; actionId: string; onCommitted(): void }):
- ((value: import('@cindy/device-link').PluginConnectionInput) => boolean) | null {
+export function bindGhostSetupConnectionAction(args: {
+ ghostId: string;
+ actionId: string;
+ onCommitted(): void;
+}): ((value: import('@cindy/device-link').PluginConnectionInput) => boolean) | null {
const manifest = findAvailableGhost(args.ghostId)?.manifest;
if (!manifest) return null;
const expectedManifest = JSON.stringify(manifest);
- return value => executeGhostSetupConnectionSubmission({
- getAssessment: getGhostSetupAssessment,
- getManifest: ghostId => findAvailableGhost(ghostId)?.manifest ?? null,
- manager: getGhostConnectionManager(),
- emitChange: (ghostId, key) => {
- getGhostSetupChangeBus().emit(ghostId, { source: 'connection', ref: key });
- },
- }, { ...args, value, expectedManifest });
+ return (value) =>
+ executeGhostSetupConnectionSubmission(
+ {
+ getAssessment: getGhostSetupAssessment,
+ getManifest: (ghostId) => findAvailableGhost(ghostId)?.manifest ?? null,
+ manager: getGhostConnectionManager(),
+ emitChange: (ghostId, key) => {
+ getGhostSetupChangeBus().emit(ghostId, { source: 'connection', ref: key });
+ },
+ },
+ { ...args, value, expectedManifest },
+ );
}
/**
@@ -5528,7 +5537,9 @@ export function getGhostLibrarySlot(): GhostLibrarySlot {
// 面板只读投影(cindy-ghost://<id>/library/<relPath>)的解析器:与电子脑
// read 同源校验(binding 根 + vault 路径纪律),失败折叠 404。
setGhostLibraryFileResolver((ghostId, relPath) =>
- librarySlotSingleton ? librarySlotSingleton.resolvePanelFilePath(ghostId, relPath) : Promise.resolve(null),
+ librarySlotSingleton
+ ? librarySlotSingleton.resolvePanelFilePath(ghostId, relPath)
+ : Promise.resolve(null),
);
}
return librarySlotSingleton;
@@ -5550,9 +5561,10 @@ async function relocateGhostLibraryTo(
try {
await slot.disposeGhost(id);
const resolution = await getGhostLibraryBindingStore().resolveLibraryRoot(id);
- const fromRoot = resolution.kind === 'custom' && resolution.root !== null
- ? resolution.root
- : ownerScopedUserDataPath('libraries', id);
+ const fromRoot =
+ resolution.kind === 'custom' && resolution.root !== null
+ ? resolution.root
+ : ownerScopedUserDataPath('libraries', id);
let fromExists = true;
try {
await fs.promises.stat(fromRoot);
@@ -5561,9 +5573,14 @@ async function relocateGhostLibraryTo(
}
if (!fromExists) {
// 无数据迁移:直接改 binding(等价 bind)。
- const set = await getGhostLibraryBindingStore().setBinding(id, candidate, (root) => statfsFreeBytes(root), {
- allowInsideManagedRoot: opts?.allowInsideManagedRoot,
- });
+ const set = await getGhostLibraryBindingStore().setBinding(
+ id,
+ candidate,
+ (root) => statfsFreeBytes(root),
+ {
+ allowInsideManagedRoot: opts?.allowInsideManagedRoot,
+ },
+ );
await slot.disposeGhost(id);
await refreshMivoLibraryExtraDirGrant();
return set.ok ? { ok: true } : { ok: false, message: set.message };
@@ -5589,7 +5606,8 @@ async function relocateGhostLibraryTo(
checkSqliteHealthy: async (abs) => {
const db = createBetterSqliteDatabase(abs, { readonly: true });
try {
- const row = db.prepare('PRAGMA quick_check').get() as { quick_check?: string } | undefined;
+ const row = db.prepare('PRAGMA quick_check').get() as
+ { quick_check?: string } | undefined;
return row?.quick_check === 'ok';
} finally {
db.close();
@@ -5624,9 +5642,10 @@ export async function getGhostLibraryOverview(ghostId: string): Promise<GhostLib
const store = getGhostLibraryBindingStore();
const binding = await store.getBinding(ghostId);
const resolution = await store.resolveLibraryRoot(ghostId);
- const root = resolution.kind === 'custom' && resolution.root !== null
- ? resolution.root
- : ownerScopedUserDataPath('libraries', ghostId);
+ const root =
+ resolution.kind === 'custom' && resolution.root !== null
+ ? resolution.root
+ : ownerScopedUserDataPath('libraries', ghostId);
let usedBytes = 0;
let fileCount = 0;
let orphaned = false;
@@ -5637,12 +5656,16 @@ export async function getGhostLibraryOverview(ghostId: string): Promise<GhostLib
reason = resolution.drift;
} else {
try {
- const meta = JSON.parse(await fs.promises.readFile(path.join(root, '.cindy-library', 'meta.json'), 'utf8')) as {
+ const meta = JSON.parse(
+ await fs.promises.readFile(path.join(root, '.cindy-library', 'meta.json'), 'utf8'),
+ ) as {
orphaned?: unknown;
};
orphaned = meta.orphaned !== undefined;
try {
- const usage = JSON.parse(await fs.promises.readFile(path.join(root, '.cindy-library', 'usage.json'), 'utf8')) as {
+ const usage = JSON.parse(
+ await fs.promises.readFile(path.join(root, '.cindy-library', 'usage.json'), 'utf8'),
+ ) as {
files?: number;
bytes?: number;
};
@@ -5681,7 +5704,9 @@ export async function getGhostLibraryOverview(ghostId: string): Promise<GhostLib
* 库根 rename 进 owner 级回收站(30 天回滚窗),撤销 binding。调用方(设置页
* IPC,后续 commit 接线)必须先取得用户对「删除作品数据」的独立破坏性确认。
*/
-export async function deleteGhostLibraryForActiveOwner(ghostId: string): Promise<{ ok: boolean; message?: string }> {
+export async function deleteGhostLibraryForActiveOwner(
+ ghostId: string,
+): Promise<{ ok: boolean; message?: string }> {
if (!isValidGhostId(ghostId)) return { ok: false, message: '非法插件 id' };
const slot = getGhostLibrarySlot();
slot.setRelocating(ghostId, true);
@@ -5692,7 +5717,9 @@ export async function deleteGhostLibraryForActiveOwner(ghostId: string): Promise
// 引导恢复位置,不误删)。
resolveLibraryRoot: async (id) => {
const resolution = await getGhostLibraryBindingStore().resolveLibraryRoot(id);
- return resolution.kind === 'custom' ? resolution.root : ownerScopedUserDataPath('libraries', id);
+ return resolution.kind === 'custom'
+ ? resolution.root
+ : ownerScopedUserDataPath('libraries', id);
},
trashRoot: () => ownerScopedUserDataPath('libraries-trash'),
removeBinding: async (id) => {
@@ -5741,10 +5768,7 @@ export function getGhostLibraryBindingStore(): LibraryBindingStore {
*/
function rejectReservedPublisherSlug(id: string): void {
if (!isReservedConnectionPluginSlug(id)) return;
- throwIpcError(
- 'GHOST_ID_RESERVED',
- `id "${id}" 是主机保留的发布者身份,不可装入`,
- );
+ throwIpcError('GHOST_ID_RESERVED', `id "${id}" 是主机保留的发布者身份,不可装入`);
}
function rejectReservedGhostId(id: string): void {
@@ -5944,7 +5968,10 @@ async function updateLocalGhostPackageLocked(
isCurrent?: () => boolean,
): Promise<InstalledGhost> {
if (isCurrent?.() === false) {
- throwIpcError('PRECONDITION_FAILED', '任务权限已变化,这次插件安装授权已失效。请用当前任务权限重试。');
+ throwIpcError(
+ 'PRECONDITION_FAILED',
+ '任务权限已变化,这次插件安装授权已失效。请用当前任务权限重试。',
+ );
}
const runtime = getGhostRuntime();
const marketLedger = getPluginMarketLedger().bind(
@@ -6094,10 +6121,7 @@ export async function installOrUpdateLocalGhostPackageFromForge(
const user = authState.isAuthenticated ? authState.user : null;
const membershipKind = user?.membershipKind ?? 'personal';
const installOrigin = forgeInstallOriginForMembership(membershipKind);
- rejectUnauthorizedTokenBroker(
- inspected.manifest,
- installOrigin ? { installOrigin } : undefined,
- );
+ rejectUnauthorizedTokenBroker(inspected.manifest, installOrigin ? { installOrigin } : undefined);
// 首装与扩权更新先在任务里请用户确认;权限没变多的更新不打扰。
const consent = await obtainGhostInstallConsent(
{ mode: 'prompt', prompt: expected.consentPrompt, initiator: 'agent', origin: 'forge' },
@@ -6118,12 +6142,18 @@ export async function installOrUpdateLocalGhostPackageFromForge(
}
}
if (expected.isCurrent?.() === false) {
- throwIpcError('PRECONDITION_FAILED', '任务权限已变化,这次插件安装授权已失效。请用当前任务权限重试。');
+ throwIpcError(
+ 'PRECONDITION_FAILED',
+ '任务权限已变化,这次插件安装授权已失效。请用当前任务权限重试。',
+ );
}
return withGhostInstallLock(inspected.manifest.id, async () => {
if (expected.isCurrent?.() === false) {
- throwIpcError('PRECONDITION_FAILED', '任务权限已变化,这次插件安装授权已失效。请用当前任务权限重试。');
+ throwIpcError(
+ 'PRECONDITION_FAILED',
+ '任务权限已变化,这次插件安装授权已失效。请用当前任务权限重试。',
+ );
}
// 确认已在 owner 租约外完成;落位再用 packing 时钉住的 owner 取租约。
const releaseMutation = beginGhostMutation(expected.mutationOwner);
@@ -6282,10 +6312,7 @@ async function installOrUpdateMarketGhostPackageLocked(
if (
undeclaredCapabilities.length > 0 ||
!ghostNetworkAuthorizationWithinCap(expected.manifestCap, inspected.canonicalManifest) ||
- !ghostNodeSecretAuthorizationWithinCap(
- expected.manifestCap,
- inspected.canonicalManifest,
- ) ||
+ !ghostNodeSecretAuthorizationWithinCap(expected.manifestCap, inspected.canonicalManifest) ||
!ghostSetupAuthorizationWithinCap(expected.manifestCap, inspected.canonicalManifest) ||
!ghostSettingsUiWithinCap(expected.manifestCap, inspected.canonicalManifest) ||
!ghostSubscribeAuthorizationWithinCap(expected.manifestCap, inspected.canonicalManifest) ||
@@ -6600,9 +6627,7 @@ function readLegacyJson<T>(
): LegacyMigrationRead<T> {
try {
const parsed = parse(JSON.parse(fs.readFileSync(file, 'utf-8')) as unknown);
- return parsed === null
- ? LEGACY_MIGRATION_RETRYABLE_FAILURE
- : legacyMigrationAvailable(parsed);
+ return parsed === null ? LEGACY_MIGRATION_RETRYABLE_FAILURE : legacyMigrationAvailable(parsed);
} catch (error) {
return (error as NodeJS.ErrnoException).code === 'ENOENT'
? LEGACY_MIGRATION_MISSING
@@ -6680,7 +6705,9 @@ export function registerGhostIpc(): void {
const ghost = findAvailableGhost(ghostId);
if (!ghost) return { status: 404 };
const networkSecretDecls = ghost.manifest.network?.secrets ?? [];
- const nodeSecretDecls = (ghost.manifest.node?.secretBindings ?? []).filter((s) => !s.oauthSecret);
+ const nodeSecretDecls = (ghost.manifest.node?.secretBindings ?? []).filter(
+ (s) => !s.oauthSecret,
+ );
const userSecretKeys = networkSecretDecls
// Host 派生与 oauth(主机托管授权)都没有"用户填值"这回事,
// 不进 /secrets 收单键集(oauth 的 client 凭证走 /oauth 端点)。
@@ -6716,9 +6743,7 @@ export function registerGhostIpc(): void {
? networkSecretDecls.filter((s) => s.source === 'gh-cli')
: [];
const ghCliAvailable =
- ghCliSecretDecls.length > 0
- ? await getSharedGhCliTokenSource().probeAvailability()
- : false;
+ ghCliSecretDecls.length > 0 ? await getSharedGhCliTokenSource().probeAvailability() : false;
return handleGhostSecretsRequest({
method,
pathname,
@@ -6730,6 +6755,7 @@ export function registerGhostIpc(): void {
key: s.key,
source: 'gh-cli' as const,
available: ghCliAvailable,
+ managedSetup: true,
})),
getLoginEmail: () => getAuthState().user?.email ?? null,
ghostId,
@@ -7058,8 +7084,8 @@ export function registerGhostIpc(): void {
const outcome = await scheduleBuiltinReconcile(reason, scope);
if (outcome === 'deferred') return outcome;
if (
- activeOwnerScopeKey() !== scope.scopeKey
- || getActiveAppSession().dataOwnerId !== scope.dataOwnerId
+ activeOwnerScopeKey() !== scope.scopeKey ||
+ getActiveAppSession().dataOwnerId !== scope.dataOwnerId
) {
return 'deferred';
}
@@ -7070,8 +7096,8 @@ export function registerGhostIpc(): void {
return outcome === 'failed'
? 'failed'
: outcome === 'retry-pending' || activationOutcome === 'retry-pending'
- ? 'retry-pending'
- : 'completed';
+ ? 'retry-pending'
+ : 'completed';
};
// ── 管子(脑机接口)main 侧 handler(docs/dev-rules/plugin-security-and-authoring.md)──────────────
@@ -7190,9 +7216,25 @@ export function registerGhostIpc(): void {
// 资格审/净化/频率钳制/限速在 scheduleSlot,落地在 renderer。
if (type === 'routine-request') {
const owner = activeOwnerScopeKey();
- const ghost = getGhostManager().list().find((item) => item.manifest.id === id);
- return handleRoutineRequest(ghost, payload, getRoutineEngine, () =>
- activeOwnerScopeKey() === owner && getGhostManager().list().some((item) => item.manifest.id === id && item.enabled && ghostInstallApprovalToken(item.approval) === ghostInstallApprovalToken(ghost?.approval)));
+ const ghost = getGhostManager()
+ .list()
+ .find((item) => item.manifest.id === id);
+ return handleRoutineRequest(
+ ghost,
+ payload,
+ getRoutineEngine,
+ () =>
+ activeOwnerScopeKey() === owner &&
+ getGhostManager()
+ .list()
+ .some(
+ (item) =>
+ item.manifest.id === id &&
+ item.enabled &&
+ ghostInstallApprovalToken(item.approval) ===
+ ghostInstallApprovalToken(ghost?.approval),
+ ),
+ );
}
if (type === 'schedule-request') {
return getGhostScheduleSlot().handleRequest(id, payload);
@@ -7561,9 +7603,8 @@ export function registerGhostIpc(): void {
// 行如实说出当前实际跟的是谁。
const textChain = getEffectiveAuxiliaryModelChain();
const textDefaultId = textChain.refs[0] ?? null;
- const textDefaultLabel = textDefaultId === null
- ? null
- : formatAuxiliaryModelRefLabel(textDefaultId);
+ const textDefaultLabel =
+ textDefaultId === null ? null : formatAuxiliaryModelRefLabel(textDefaultId);
const textOptions = buildTextOneshotPinOptions(
getActiveCatalog(),
readModelDisableOverrides(),
@@ -7572,9 +7613,12 @@ export function registerGhostIpc(): void {
);
// 纯展示口径,不走 findAvailableGhost 的"当前会话可用"闸:插件被当前项目
// 停用时卡片的其余部分(overrides/options)照常渲染,声明偏好也不该凭空消失。
- const declaredRaw = typeof ghostId === 'string'
- ? getGhostManager().list().find((g) => g.manifest.id === ghostId)?.manifest.cindy?.oneshotModel
- : undefined;
+ const declaredRaw =
+ typeof ghostId === 'string'
+ ? getGhostManager()
+ .list()
+ .find((g) => g.manifest.id === ghostId)?.manifest.cindy?.oneshotModel
+ : undefined;
const declaredResolved = declaredRaw
? resolveOneshotCatalogModel(
getActiveCatalog(),
@@ -7945,10 +7989,7 @@ export function registerGhostIpc(): void {
const brokered = (probe.manifest.network?.secrets ?? []).some(
(s) => s.oauth?.tokenBroker !== undefined,
);
- if (
- brokered &&
- !isGhostTokenBrokerAuthorized(probe.manifest.id, 'install')
- ) {
+ if (brokered && !isGhostTokenBrokerAuthorized(probe.manifest.id, 'install')) {
return false;
}
// 指令查重(同 install/update):与当前已装撞名即拒,排除自身。
@@ -8106,12 +8147,14 @@ export function registerGhostIpc(): void {
* 共用同一裁决链(原生选择器 → 候选校验 → binding/迁移)。 */
ipcMain.handle('ghosts:library-overview', async (event, id: unknown) => {
assertTrustedAppRendererEvent(event);
- if (typeof id !== 'string' || !isValidGhostId(id)) throwIpcError('INVALID_PARAMS', '非法插件 id');
+ if (typeof id !== 'string' || !isValidGhostId(id))
+ throwIpcError('INVALID_PARAMS', '非法插件 id');
return getGhostLibraryOverview(id);
});
ipcMain.handle('ghosts:library-pick-location', async (event, id: unknown) => {
assertTrustedAppRendererEvent(event);
- if (typeof id !== 'string' || !isValidGhostId(id)) throwIpcError('INVALID_PARAMS', '非法插件 id');
+ if (typeof id !== 'string' || !isValidGhostId(id))
+ throwIpcError('INVALID_PARAMS', '非法插件 id');
const win = BrowserWindow.fromWebContents(event.sender);
const picked = win
? await dialog.showOpenDialog(win, { properties: ['openDirectory', 'createDirectory'] })
@@ -8130,7 +8173,8 @@ export function registerGhostIpc(): void {
},
getDiskFreeBytes: (root) => statfsFreeBytes(root),
});
- if (!validation.ok) return { ok: false as const, cancelled: false as const, message: validation.message };
+ if (!validation.ok)
+ return { ok: false as const, cancelled: false as const, message: validation.message };
return { ok: true as const, candidate, warnings: validation.warnings };
});
// 装入确认时的「更改位置」:空库(或首次启用),直接记 binding,无需迁移。
@@ -8168,7 +8212,8 @@ export function registerGhostIpc(): void {
// 撤销自定义位置:迁回系统默认并清 binding(反向同一状态机)。
ipcMain.handle('ghosts:library-revert-default', async (event, id: unknown) => {
assertTrustedAppRendererEvent(event);
- if (typeof id !== 'string' || !isValidGhostId(id)) throwIpcError('INVALID_PARAMS', '非法插件 id');
+ if (typeof id !== 'string' || !isValidGhostId(id))
+ throwIpcError('INVALID_PARAMS', '非法插件 id');
const defaultParent = path.dirname(ownerScopedUserDataPath('libraries', id));
try {
await fs.promises.mkdir(defaultParent, { recursive: true });
@@ -8187,7 +8232,8 @@ export function registerGhostIpc(): void {
// 用户可手工找回;不自动猜测)。
ipcMain.handle('ghosts:library-unbind', async (event, id: unknown) => {
assertTrustedAppRendererEvent(event);
- if (typeof id !== 'string' || !isValidGhostId(id)) throwIpcError('INVALID_PARAMS', '非法插件 id');
+ if (typeof id !== 'string' || !isValidGhostId(id))
+ throwIpcError('INVALID_PARAMS', '非法插件 id');
const releaseMutation = beginGhostMutation();
const slot = getGhostLibrarySlot();
try {
@@ -8204,7 +8250,8 @@ export function registerGhostIpc(): void {
});
ipcMain.handle('ghosts:library-delete', async (event, id: unknown) => {
assertTrustedAppRendererEvent(event);
- if (typeof id !== 'string' || !isValidGhostId(id)) throwIpcError('INVALID_PARAMS', '非法插件 id');
+ if (typeof id !== 'string' || !isValidGhostId(id))
+ throwIpcError('INVALID_PARAMS', '非法插件 id');
// **唯一有效的删除确认在 Main**:preload 即使被其它 trusted renderer
// 调用也绕不过用户点击(review:Renderer 确认可被内部调用方绕过)。文案走
// main i18n(与 Renderer 五语同一资源),壳由系统绘制;取消不取得 mutation
@@ -8535,20 +8582,17 @@ function scheduleGhostSkillReconcile(): void {
skillReconcileInFlight = false;
return;
}
- const result = await withGhostSkillProjectionReconcile(
- owner.dataOwnerId,
- async () => {
- releaseLease = beginGhostMutation(owner);
- return reconcileGhostSkillLinks({
- ghosts: getGhostManager().list(),
- brainRoot: brainRootDir(),
- approvalStateRoot: getGhostManager().approvalStateRoot(),
- assertOwnerStable: () => assertGhostSkillProjectionStableOwner(owner.dataOwnerId!),
- validateApprovedSkillSnapshot: (ghost) =>
- getGhostManager().verifyApprovedSkillSnapshot(ghost),
- });
- },
- );
+ const result = await withGhostSkillProjectionReconcile(owner.dataOwnerId, async () => {
+ releaseLease = beginGhostMutation(owner);
+ return reconcileGhostSkillLinks({
+ ghosts: getGhostManager().list(),
+ brainRoot: brainRootDir(),
+ approvalStateRoot: getGhostManager().approvalStateRoot(),
+ assertOwnerStable: () => assertGhostSkillProjectionStableOwner(owner.dataOwnerId!),
+ validateApprovedSkillSnapshot: (ghost) =>
+ getGhostManager().verifyApprovedSkillSnapshot(ghost),
+ });
+ });
if (result.warnings.length > 0) {
log.warn('ghost skill reconcile warnings', { warnings: result.warnings });
}
@@ -8560,9 +8604,9 @@ function scheduleGhostSkillReconcile(): void {
} catch (err) {
const message = err instanceof Error ? err.message : String(err);
if (
- isAppSessionBoundaryPending()
- || message.includes('projection is not stable')
- || message.includes('boundary lock is busy or unavailable')
+ isAppSessionBoundaryPending() ||
+ message.includes('projection is not stable') ||
+ message.includes('boundary lock is busy or unavailable')
) {
// 账号边界期:本轮不动盘,保留 pending 等换号完成后的广播重跑。
scheduleGhostSkillReconcileRetry();
diff --git a/apps/desktop/src/main/cindy-brain/runtime/__tests__/ghostSecretsEndpoint.test.ts b/apps/desktop/src/main/cindy-brain/runtime/__tests__/ghostSecretsEndpoint.test.ts
index 52acbfc4b4..9f0840afef 100644
--- a/apps/desktop/src/main/cindy-brain/runtime/__tests__/ghostSecretsEndpoint.test.ts
+++ b/apps/desktop/src/main/cindy-brain/runtime/__tests__/ghostSecretsEndpoint.test.ts
@@ -132,7 +132,7 @@ describe('cindy-brain · ghostSecretsEndpoint(user 凭证只写通道,意识收
readBodyText: () => Promise.resolve(''),
userSecretKeys: ['github_pat'],
hostCredentialStates: [
- { key: 'github_pat', source: 'gh-cli' as const, available: true },
+ { key: 'github_pat', source: 'gh-cli' as const, available: true, managedSetup: true },
],
vault,
ghostId: 'cindy-github',
@@ -145,6 +145,7 @@ describe('cindy-brain · ghostSecretsEndpoint(user 凭证只写通道,意识收
tail: '1234',
hostSource: 'gh-cli',
hostAvailable: true,
+ hostManagedSetup: true,
},
]);
expect(list.body).not.toContain('github_pat_abcdefgh');
@@ -217,7 +218,12 @@ describe('cindy-brain · ghostSecretsEndpoint(user 凭证只写通道,意识收
// 写失败 → 不触发
const onStoredFail = vi.fn();
- const failing: GhostSecretsVault = { saved: () => false, tail: () => null, store: () => false, remove: () => {} };
+ const failing: GhostSecretsVault = {
+ saved: () => false,
+ tail: () => null,
+ store: () => false,
+ remove: () => {},
+ };
await handleGhostSecretsRequest({
method: 'PUT',
pathname: '/secrets/api_key',
@@ -259,7 +265,10 @@ describe('cindy-brain · ghostSecretsEndpoint(user 凭证只写通道,意识收
it('未声明 / 带子路径的 key → 统一 404,不给区分面', async () => {
for (const pathname of ['/secrets/unknown', '/secrets/', '/secrets/a/b']) {
- expect((await call({ method: 'PUT', pathname, body: '{"value":"x"}' })).status, pathname).toBe(404);
+ expect(
+ (await call({ method: 'PUT', pathname, body: '{"value":"x"}' })).status,
+ pathname,
+ ).toBe(404);
}
});
@@ -272,7 +281,9 @@ describe('cindy-brain · ghostSecretsEndpoint(user 凭证只写通道,意识收
it('值超长 → 413;有界读取器抛 TOO_LARGE → 413', async () => {
const long = JSON.stringify({ value: 'x'.repeat(GHOST_SECRET_VALUE_MAX_CHARS + 1) });
- expect((await call({ method: 'PUT', pathname: '/secrets/api_key', body: long })).status).toBe(413);
+ expect((await call({ method: 'PUT', pathname: '/secrets/api_key', body: long })).status).toBe(
+ 413,
+ );
const out = await handleGhostSecretsRequest({
method: 'PUT',
@@ -287,12 +298,18 @@ describe('cindy-brain · ghostSecretsEndpoint(user 凭证只写通道,意识收
it('DELETE → 204 幂等;方法不符 → 405', async () => {
const vault = memVault({ api_key: 'v' });
- expect((await call({ method: 'DELETE', pathname: '/secrets/api_key', vault })).status).toBe(204);
+ expect((await call({ method: 'DELETE', pathname: '/secrets/api_key', vault })).status).toBe(
+ 204,
+ );
expect(vault.data.api_key).toBeUndefined();
- expect((await call({ method: 'DELETE', pathname: '/secrets/api_key', vault })).status).toBe(204);
+ expect((await call({ method: 'DELETE', pathname: '/secrets/api_key', vault })).status).toBe(
+ 204,
+ );
expect((await call({ method: 'POST', pathname: '/secrets' })).status).toBe(405);
- expect((await call({ method: 'PATCH', pathname: '/secrets/api_key', body: '{"value":"x"}' })).status).toBe(405);
+ expect(
+ (await call({ method: 'PATCH', pathname: '/secrets/api_key', body: '{"value":"x"}' })).status,
+ ).toBe(405);
expect((await call({ method: 'GET', pathname: '/secrets/api_key' })).status).toBe(405);
});
@@ -304,7 +321,14 @@ describe('cindy-brain · ghostSecretsEndpoint(user 凭证只写通道,意识收
remove: () => {},
};
expect(
- (await call({ method: 'PUT', pathname: '/secrets/api_key', body: '{"value":"x"}', vault: failing })).status,
+ (
+ await call({
+ method: 'PUT',
+ pathname: '/secrets/api_key',
+ body: '{"value":"x"}',
+ vault: failing,
+ })
+ ).status,
).toBe(500);
const boom: GhostSecretsVault = {
@@ -325,8 +349,17 @@ describe('cindy-brain · ghostSecretsEndpoint(user 凭证只写通道,意识收
expect(got.status).toBe(500);
expect(got.body).toBeUndefined();
expect(
- (await call({ method: 'PUT', pathname: '/secrets/api_key', body: '{"value":"x"}', vault: boom })).status,
+ (
+ await call({
+ method: 'PUT',
+ pathname: '/secrets/api_key',
+ body: '{"value":"x"}',
+ vault: boom,
+ })
+ ).status,
+ ).toBe(500);
+ expect(
+ (await call({ method: 'DELETE', pathname: '/secrets/api_key', vault: boom })).status,
).toBe(500);
- expect((await call({ method: 'DELETE', pathname: '/secrets/api_key', vault: boom })).status).toBe(500);
});
});
diff --git a/apps/desktop/src/main/cindy-brain/runtime/ghostSecretsEndpoint.ts b/apps/desktop/src/main/cindy-brain/runtime/ghostSecretsEndpoint.ts
index 64f8befda1..bbde4b7d53 100644
--- a/apps/desktop/src/main/cindy-brain/runtime/ghostSecretsEndpoint.ts
+++ b/apps/desktop/src/main/cindy-brain/runtime/ghostSecretsEndpoint.ts
@@ -78,6 +78,7 @@ export async function handleGhostSecretsRequest(args: {
key: string;
source: 'gh-cli';
available: boolean;
+ managedSetup?: boolean;
}>;
vault: GhostSecretsVault;
ghostId: string;
@@ -106,11 +107,13 @@ export async function handleGhostSecretsRequest(args: {
const tail = saved ? vault.tail(ghostId, key) : null;
const hostState = hostCredentialStates.get(key);
const hostFields = hostState
- ? { hostSource: hostState.source, hostAvailable: hostState.available }
+ ? {
+ hostSource: hostState.source,
+ hostAvailable: hostState.available,
+ ...(hostState.managedSetup ? { hostManagedSetup: true } : {}),
+ }
: {};
- return tail
- ? { key, saved, tail, ...hostFields }
- : { key, saved, ...hostFields };
+ return tail ? { key, saved, tail, ...hostFields } : { key, saved, ...hostFields };
});
// 身份凭证:现读登录邮箱只读展示;identityKeys 为空时不碰登录态。
const email = identityKeys.length > 0 ? (args.getLoginEmail?.()?.trim() ?? '') : '';
diff --git a/apps/desktop/src/main/cindy-make/toolArchive.ts b/apps/desktop/src/main/cindy-make/toolArchive.ts
index 27ad3be3c1..f97ec8523f 100644
--- a/apps/desktop/src/main/cindy-make/toolArchive.ts
+++ b/apps/desktop/src/main/cindy-make/toolArchive.ts
@@ -1,126 +1,6 @@
-import { createReadStream, createWriteStream } from 'node:fs';
-import { copyFile, mkdir, readFile, stat } from 'node:fs/promises';
-import path from 'node:path';
-import { Transform } from 'node:stream';
-import { pipeline } from 'node:stream/promises';
-import JSZip from 'jszip';
-import * as tar from 'tar';
-import type { MakeToolArtifact } from './toolCatalog.js';
-
-const MAX_ARCHIVE_BYTES = 160 * 1024 ** 2;
-const MAX_FILE_BYTES = 256 * 1024 ** 2;
-const MAX_EXPANDED_BYTES = 1024 ** 3;
-const MAX_ENTRIES = 30_000;
-
-/** Publisher paths are POSIX paths, independent of the host extracting the archive. */
-export function safeArchivePath(name: string): string {
- const clean = name.replace(/^(\.\/)+/, '').replace(/\/$/, '');
- if (
- !clean ||
- /[\\:\0]/.test(clean) ||
- path.posix.isAbsolute(clean) ||
- clean.split('/').some((part) => part === '..' || part === '.' || !part)
- ) {
- throw new Error('Unsafe tool archive path');
- }
- return clean;
-}
-
-export function safeArchiveLink(name: string, link: string, hard: boolean): void {
- safeArchivePath(name);
- if (!link || /[\\:\0]/.test(link) || path.posix.isAbsolute(link))
- throw new Error('Unsafe tool archive link');
- safeArchivePath(path.posix.join(hard ? '' : path.posix.dirname(name), link));
-}
-
-/** Extract only hash-verified publisher artifacts into a fresh, unreferenced directory.
- * tar handles internal symlinks (Python/Node); ZIP symlinks are not needed by our catalog.
- * Preflight tar entries before any write; bound ZIP expansion while streaming each file.
- */
-export async function extractMakeToolArchive(
- archive: string,
- destination: string,
- artifact: Pick<MakeToolArtifact, 'format' | 'executable'>,
- signal: AbortSignal,
-): Promise<void> {
- signal.throwIfAborted();
- if ((await stat(archive)).size > MAX_ARCHIVE_BYTES) throw new Error('Tool archive too large');
- if (artifact.format === 'binary') {
- await copyFile(archive, path.join(destination, artifact.executable));
- } else if (artifact.format === 'zip') {
- const zip = await JSZip.loadAsync(await readFile(archive));
- const entries = Object.values(zip.files);
- if (entries.length > MAX_ENTRIES) throw new Error('Too many tool archive entries');
- let expanded = 0;
- for (const entry of entries) {
- signal.throwIfAborted();
- const name = safeArchivePath(entry.name);
- const original = (entry as typeof entry & { unsafeOriginalName?: string }).unsafeOriginalName;
- if (original && safeArchivePath(original) !== name)
- throw new Error('Unsafe tool archive path');
- if (
- typeof entry.unixPermissions === 'number' &&
- (entry.unixPermissions & 0o170000) === 0o120000
- )
- throw new Error('Unsupported ZIP link');
- const target = path.join(destination, ...name.split('/'));
- if (entry.dir) {
- await mkdir(target, { recursive: true });
- continue;
- }
- await mkdir(path.dirname(target), { recursive: true });
- let size = 0;
- const limit = new Transform({
- transform(chunk: Buffer, _encoding, callback) {
- size += chunk.length;
- expanded += chunk.length;
- callback(
- size > MAX_FILE_BYTES || expanded > MAX_EXPANDED_BYTES
- ? new Error('Tool archive too large')
- : null,
- chunk,
- );
- },
- });
- await pipeline(
- entry.nodeStream(),
- limit,
- createWriteStream(target, { flags: 'wx', mode: 0o644 }),
- { signal },
- );
- }
- } else {
- let count = 0;
- let expanded = 0;
- let invalid: Error | undefined;
- const listing = tar.t({
- strict: true,
- onReadEntry(entry) {
- try {
- // A harmless top-level './' directory is used by some tar publishers.
- if (entry.type === 'Directory' && /^\.(\/)?$/.test(entry.path)) return;
- safeArchivePath(entry.path);
- if (!['File', 'Directory', 'SymbolicLink', 'Link'].includes(entry.type))
- throw new Error('Unsupported tool archive entry');
- if (entry.type === 'SymbolicLink' || entry.type === 'Link')
- safeArchiveLink(entry.path, entry.linkpath ?? '', entry.type === 'Link');
- expanded += entry.size;
- if (++count > MAX_ENTRIES || entry.size > MAX_FILE_BYTES || expanded > MAX_EXPANDED_BYTES)
- throw new Error('Tool archive too large');
- } catch (error) {
- invalid = error as Error;
- }
- },
- });
- await pipeline(createReadStream(archive), listing, { signal });
- if (invalid) throw invalid;
- const extracting = tar.x({
- cwd: destination,
- strict: true,
- preservePaths: false,
- noMtime: true,
- });
- await pipeline(createReadStream(archive), extracting, { signal });
- }
- signal.throwIfAborted();
-}
+// Compatibility exports: existing Make callers keep the same API.
+export {
+ extractToolArchive as extractMakeToolArchive,
+ safeArchivePath,
+ safeArchiveLink,
+} from '../managed-tools/archive.js';
diff --git a/apps/desktop/src/main/cindy-make/toolCatalog.ts b/apps/desktop/src/main/cindy-make/toolCatalog.ts
index f3747e4f21..219dd80dde 100644
--- a/apps/desktop/src/main/cindy-make/toolCatalog.ts
+++ b/apps/desktop/src/main/cindy-make/toolCatalog.ts
@@ -1,3 +1,4 @@
+import type { ToolArtifact } from '../managed-tools/types.js';
import type { MakeToolId } from '../../shared/cindyMakeDoctor.js';
import { isSupportedMakeHost } from './doctor.js';
@@ -5,15 +6,8 @@ import { isSupportedMakeHost } from './doctor.js';
* Node: nodejs.org SHASUMS256.txt; other hashes: publisher release asset digests.
* Refresh these together with the repository's engine/packageManager requirements.
*/
-export interface MakeToolArtifact {
+export interface MakeToolArtifact extends ToolArtifact {
id: MakeToolId;
- version: string;
- host: string;
- url: string;
- sha256: string;
- format: 'binary' | 'zip' | 'tar.gz';
- /** POSIX archive-relative path, including the publisher's top-level directory. */
- executable: string;
}
const nodeHashes: Record<string, string> = {
diff --git a/apps/desktop/src/main/cindy-make/toolInstaller.ts b/apps/desktop/src/main/cindy-make/toolInstaller.ts
index 417a9918e9..ce50a1721e 100644
--- a/apps/desktop/src/main/cindy-make/toolInstaller.ts
+++ b/apps/desktop/src/main/cindy-make/toolInstaller.ts
@@ -1,133 +1,9 @@
-import { randomUUID } from 'node:crypto';
-import { chmod, mkdir, mkdtemp, readFile, rename, rm, stat, writeFile } from 'node:fs/promises';
import path from 'node:path';
-import { download, type DownloadOptions } from '../downloader/index.js';
-import { createLogger } from '../logger.js';
-import type { MakeDoctorCheck } from '../../shared/cindyMakeDoctor.js';
-import type { MakeToolArtifact } from './toolCatalog.js';
-import { extractMakeToolArchive } from './toolArchive.js';
-const log = createLogger('cindy-make');
-export type InstallProgress = Pick<MakeDoctorCheck, 'status' | 'progress'>;
+// Preserve existing installation roots and records; no user-data migration.
export const makeToolRoot = (userData: string) => path.join(userData, 'cindy-make');
-const key = (artifact: MakeToolArtifact) =>
- `${artifact.id}-${artifact.version}-${artifact.host}-${artifact.sha256.slice(0, 12)}`;
-const recordPath = (root: string, artifact: MakeToolArtifact) =>
- path.join(root, 'tools', key(artifact), 'current.json');
-
-/** A record references only a complete immutable generation, never an in-progress extraction. */
-export async function installedMakeTool(
- root: string,
- artifact: MakeToolArtifact,
-): Promise<string | undefined> {
- try {
- const record = JSON.parse(await readFile(recordPath(root, artifact), 'utf8'));
- if (
- record.sha256 !== artifact.sha256 ||
- typeof record.generation !== 'string' ||
- !/^[a-f0-9-]{36}$/.test(record.generation)
- )
- return;
- const executable = path.join(
- root,
- 'tools',
- key(artifact),
- record.generation,
- ...artifact.executable.split('/'),
- );
- if ((await stat(executable)).isFile()) return executable;
- } catch {
- /* Missing/corrupt records are not installed tools. */
- }
-}
-
-/** Installs to Cindy's private directory; never invokes a system installer or writes global config.
- * Generations stay immutable so a failed repair cannot break an existing consumer. A concurrent
- * instance may promote another valid generation; either result has the same pinned contents.
- */
-export async function installMakeTool(
- input: {
- root: string;
- artifact: MakeToolArtifact;
- signal: AbortSignal;
- onProgress: (progress: InstallProgress) => void;
- validate: (executable: string) => Promise<boolean>;
- },
- deps: {
- download?: (options: DownloadOptions) => Promise<unknown>;
- extract?: typeof extractMakeToolArchive;
- } = {},
-): Promise<string> {
- const { root, artifact, signal, onProgress } = input;
- signal.throwIfAborted();
- const parent = path.join(root, 'tools', key(artifact));
- await mkdir(parent, { recursive: true });
- const staging = await mkdtemp(path.join(parent, '.staging-'));
- const payload = path.join(staging, 'payload');
- const generation = randomUUID();
- const target = path.join(parent, generation);
- const recordTemp = path.join(parent, `${generation}.json.tmp`);
- let promoted = false;
- let lastProgressAt = 0;
- try {
- onProgress({ status: 'downloading' });
- // Each attempt has its own writable archive. The downloader retries/resumes in this
- // attempt without sharing mutable .part files with another Cindy process.
- await (deps.download ?? download)({
- url: artifact.url,
- sha256: artifact.sha256,
- targetPath: path.join(staging, 'archive'),
- signal,
- logger: log,
- onProgress: ({ loaded, total, percent }) => {
- const now = Date.now();
- // A fast connection must not produce thousands of chat-store updates per second.
- if (signal.aborted || (now - lastProgressAt < 150 && loaded !== total)) return;
- lastProgressAt = now;
- onProgress({
- status: 'downloading',
- progress: {
- loaded,
- total,
- percent: percent === null ? null : Math.max(0, Math.min(100, percent)),
- },
- });
- },
- retry: { maxAttempts: 4 },
- });
- signal.throwIfAborted();
- onProgress({ status: 'installing' });
- await mkdir(payload);
- await (deps.extract ?? extractMakeToolArchive)(
- path.join(staging, 'archive'),
- payload,
- artifact,
- signal,
- );
- const executable = path.join(payload, ...artifact.executable.split('/'));
- if (!(await stat(executable)).isFile()) throw new Error('Tool executable missing');
- await chmod(executable, 0o755);
- if (!(await input.validate(executable)))
- throw new Error('Installed tool did not pass its version check');
- signal.throwIfAborted();
- await rename(payload, target);
- await writeFile(recordTemp, JSON.stringify({ generation, sha256: artifact.sha256 }), {
- flag: 'wx',
- });
- signal.throwIfAborted();
- await rename(recordTemp, recordPath(root, artifact));
- promoted = true;
- return path.join(target, ...artifact.executable.split('/'));
- } finally {
- // Only paths created by this attempt are removed; previous generations are untouched.
- for (const file of [staging, recordTemp, ...(!promoted ? [target] : [])]) {
- try {
- await rm(file, { recursive: true, force: true, maxRetries: 3, retryDelay: 100 });
- } catch {
- // Antivirus/file locks may briefly keep a temp file open on Windows. An unused
- // staging folder is never a valid install and must not mask the real outcome.
- log.warn('Tool staging cleanup deferred', { tool: artifact.id });
- }
- }
- }
-}
+export {
+ installTool as installMakeTool,
+ installedTool as installedMakeTool,
+} from '../managed-tools/installer.js';
+export type { ToolInstallProgress as InstallProgress } from '../managed-tools/types.js';
diff --git a/apps/desktop/src/main/downloader/__tests__/download.test.ts b/apps/desktop/src/main/downloader/__tests__/download.test.ts
new file mode 100644
index 0000000000..8652047baa
--- /dev/null
+++ b/apps/desktop/src/main/downloader/__tests__/download.test.ts
@@ -0,0 +1,251 @@
+import fs from 'node:fs';
+import os from 'node:os';
+import path from 'node:path';
+import { createHash } from 'node:crypto';
+import { afterEach, describe, expect, it, vi } from 'vitest';
+const fetchMock = vi.hoisted(() => vi.fn());
+vi.mock('../http', () => ({ requestResponse: fetchMock }));
+vi.mock('../../logger', () => ({ createLogger: () => ({ warn: vi.fn(), debug: vi.fn() }) }));
+import { download, getActive } from '../index';
+import { writeMeta } from '../resume';
+
+const roots: string[] = [];
+const hash = (body: string) => createHash('sha256').update(body).digest('hex');
+function options(body = 'abcdef') {
+ const root = fs.mkdtempSync(path.join(os.tmpdir(), 'cindy-downloader-'));
+ roots.push(root);
+ return {
+ url: 'https://publisher.test/file',
+ targetPath: path.join(root, 'archive'),
+ sha256: hash(body),
+ expectedSize: body.length,
+ retry: { maxAttempts: 1 },
+ };
+}
+function partial(opts: ReturnType<typeof options>, body = 'abc') {
+ fs.writeFileSync(`${opts.targetPath}.part`, body);
+ writeMeta(opts.targetPath, {
+ url: opts.url,
+ expectedSize: opts.expectedSize,
+ expectedSha256: opts.sha256,
+ downloadedBytes: body.length,
+ etag: 'v1',
+ lastModified: null,
+ createdAt: '',
+ updatedAt: '',
+ });
+}
+afterEach(() => {
+ vi.useRealTimers();
+ fetchMock.mockReset();
+ for (const root of roots.splice(0)) fs.rmSync(root, { recursive: true, force: true });
+});
+describe('shared verified downloads', () => {
+ it('resumes and hashes the prior bytes exactly once', async () => {
+ const opts = options();
+ partial(opts);
+ fetchMock.mockResolvedValue(
+ new Response('def', {
+ status: 206,
+ headers: { 'content-range': 'bytes 3-5/6', 'content-length': '3' },
+ }),
+ );
+ await expect(download(opts)).resolves.toMatchObject({ resumedFromBytes: 3, size: 6 });
+ expect(fs.readFileSync(opts.targetPath, 'utf8')).toBe('abcdef');
+ expect(fetchMock).toHaveBeenCalledWith(
+ opts.url,
+ expect.objectContaining({
+ headers: expect.objectContaining({ Range: 'bytes=3-', 'If-Range': 'v1' }),
+ }),
+ );
+ expect(fs.existsSync(`${opts.targetPath}.meta.json`)).toBe(false);
+ });
+ it('uses a full response when the server ignores Range', async () => {
+ const opts = options();
+ partial(opts);
+ fetchMock.mockResolvedValue(new Response('abcdef'));
+ await expect(download(opts)).resolves.toMatchObject({ resumedFromBytes: 0 });
+ expect(fs.readFileSync(opts.targetPath, 'utf8')).toBe('abcdef');
+ });
+ it('rejects wrong resume offsets before appending', async () => {
+ const opts = options();
+ partial(opts);
+ fetchMock.mockResolvedValue(
+ new Response('def', { status: 206, headers: { 'content-range': 'bytes 2-4/6' } }),
+ );
+ await expect(download(opts)).rejects.toMatchObject({ code: 'NETWORK' });
+ expect(fs.existsSync(opts.targetPath)).toBe(false);
+ expect(fs.existsSync(`${opts.targetPath}.part`)).toBe(false);
+ });
+ it('checks every redirect before contacting the destination', async () => {
+ const opts = options();
+ fetchMock.mockResolvedValue(
+ new Response(null, { status: 302, headers: { location: 'https://untrusted.test/file' } }),
+ );
+ await expect(
+ download({ ...opts, isUrlAllowed: (url) => new URL(url).hostname === 'publisher.test' }),
+ ).rejects.toMatchObject({ code: 'URL_POLICY' });
+ expect(fetchMock).toHaveBeenCalledOnce();
+ });
+ it('follows allowed redirects and rejects redirect loops', async () => {
+ const opts = options();
+ fetchMock
+ .mockResolvedValueOnce(new Response(null, { status: 302, headers: { location: '/asset' } }))
+ .mockResolvedValueOnce(new Response('abcdef'));
+ await download({ ...opts, isUrlAllowed: (url) => new URL(url).hostname === 'publisher.test' });
+ expect(fetchMock.mock.calls[1][0]).toBe('https://publisher.test/asset');
+ fetchMock.mockClear();
+ fetchMock.mockImplementation(
+ async () => new Response(null, { status: 302, headers: { location: '/loop' } }),
+ );
+ await expect(download(options())).rejects.toMatchObject({ code: 'URL_POLICY' });
+ expect(fetchMock).toHaveBeenCalledTimes(6);
+ });
+ it('does not allow a forbidden URL to use a cached file', async () => {
+ const opts = options();
+ fs.writeFileSync(opts.targetPath, 'abcdef');
+ await expect(download({ ...opts, isUrlAllowed: () => false })).rejects.toMatchObject({
+ code: 'URL_POLICY',
+ });
+ expect(fetchMock).not.toHaveBeenCalled();
+ });
+ it('checks cache size as well as hash', async () => {
+ const opts = options();
+ fs.writeFileSync(opts.targetPath, 'abcdef');
+ await expect(download(opts)).resolves.toMatchObject({ fromCache: true });
+ fetchMock.mockResolvedValue(new Response('abcdef'));
+ await expect(download({ ...opts, expectedSize: 3 })).rejects.toMatchObject({ code: 'SIZE' });
+ expect(fetchMock).toHaveBeenCalledOnce();
+ expect(fs.readFileSync(opts.targetPath, 'utf8')).toBe('abcdef');
+ });
+ it('preserves an existing valid target on corrupt replacement', async () => {
+ const opts = options();
+ fs.writeFileSync(opts.targetPath, 'old');
+ fetchMock.mockResolvedValue(new Response('xxxxxx'));
+ await expect(download(opts)).rejects.toMatchObject({ code: 'CHECKSUM' });
+ expect(fs.readFileSync(opts.targetPath, 'utf8')).toBe('old');
+ expect(fs.existsSync(`${opts.targetPath}.part`)).toBe(false);
+ });
+ it('does not overwrite a target created during an exclusive download', async () => {
+ const opts = options();
+ fetchMock.mockImplementation(async () => {
+ fs.writeFileSync(opts.targetPath, 'other');
+ return new Response('abcdef');
+ });
+ await expect(
+ download({ ...opts, existingTarget: 'error', resume: false }),
+ ).rejects.toMatchObject({ code: 'EXISTS' });
+ expect(fs.readFileSync(opts.targetPath, 'utf8')).toBe('other');
+ expect(fs.existsSync(`${opts.targetPath}.part`)).toBe(false);
+ });
+ it('stops an oversized chunk before writing it', async () => {
+ const opts = options();
+ fetchMock.mockResolvedValue(new Response('abcdefg'));
+ await expect(download({ ...opts, expectedSize: undefined, maxBytes: 6 })).rejects.toMatchObject(
+ { code: 'SIZE' },
+ );
+ expect(fs.existsSync(`${opts.targetPath}.part`)).toBe(false);
+ expect(fs.existsSync(opts.targetPath)).toBe(false);
+ });
+ it('cancels an active stream, then resumes from the completed writes', async () => {
+ const opts = options();
+ const controller = new AbortController();
+ let pulls = 0;
+ fetchMock.mockImplementation((_url, { signal }) =>
+ Promise.resolve(
+ new Response(
+ new ReadableStream(
+ {
+ start(stream) {
+ signal.addEventListener('abort', () => stream.error(new Error('aborted')), {
+ once: true,
+ });
+ },
+ pull(stream) {
+ if (++pulls === 1) stream.enqueue(Buffer.from('abc'));
+ },
+ },
+ { highWaterMark: 0 },
+ ),
+ ),
+ ),
+ );
+ const pending = download({ ...opts, signal: controller.signal });
+ const rejection = expect(pending).rejects.toMatchObject({ code: 'ABORTED' });
+ await vi.waitFor(() => expect(pulls).toBe(2));
+ controller.abort();
+ await rejection;
+ expect(fs.readFileSync(`${opts.targetPath}.part`, 'utf8')).toBe('abc');
+ fetchMock.mockResolvedValue(
+ new Response('def', { status: 206, headers: { 'content-range': 'bytes 3-5/6' } }),
+ );
+ await expect(download(opts)).resolves.toMatchObject({ resumedFromBytes: 3 });
+ });
+ it('never publishes after cancellation during streaming progress', async () => {
+ const body = 'a'.repeat(300 * 1024);
+ const opts = options(body);
+ const controller = new AbortController();
+ fetchMock.mockResolvedValue(new Response(body));
+ await expect(
+ download({
+ ...opts,
+ signal: controller.signal,
+ onProgress: (p) => {
+ if (p.loaded === body.length) controller.abort();
+ },
+ }),
+ ).rejects.toMatchObject({ code: 'ABORTED' });
+ expect(fs.existsSync(opts.targetPath)).toBe(false);
+ });
+ it('applies a total deadline while queued without cancelling the active download', async () => {
+ vi.useFakeTimers();
+ let release!: (response: Response) => void;
+ fetchMock.mockImplementationOnce(
+ () =>
+ new Promise<Response>((resolve) => {
+ release = resolve;
+ }),
+ );
+ const first = download(options());
+ await vi.waitFor(() => expect(fetchMock).toHaveBeenCalledOnce());
+ const second = expect(
+ download({ ...options(), timeout: { totalMs: 100 } }),
+ ).rejects.toMatchObject({ code: 'TIMEOUT' });
+ await vi.advanceTimersByTimeAsync(100);
+ await second;
+ expect(fetchMock).toHaveBeenCalledOnce();
+ release(new Response('abcdef'));
+ await first;
+ expect(getActive()).toEqual([]);
+ expect(vi.getTimerCount()).toBe(0);
+ });
+ it('does not share a target with different URL policy or cancellation ownership', async () => {
+ let release!: (response: Response) => void;
+ const opts = options();
+ fetchMock.mockImplementationOnce(
+ () =>
+ new Promise<Response>((resolve) => {
+ release = resolve;
+ }),
+ );
+ const first = download(opts);
+ const same = download(opts);
+ expect(same).toBe(first);
+ await vi.waitFor(() => expect(fetchMock).toHaveBeenCalledOnce());
+ await expect(download({ ...opts, redirect: 'error' })).rejects.toMatchObject({
+ code: 'INVALID_ARG',
+ });
+ await expect(download({ ...opts, signal: new AbortController().signal })).rejects.toMatchObject(
+ { code: 'INVALID_ARG' },
+ );
+ release(new Response('abcdef'));
+ await first;
+ });
+ it('retries a server failure using the common retry policy', async () => {
+ fetchMock
+ .mockResolvedValueOnce(new Response(null, { status: 503 }))
+ .mockResolvedValueOnce(new Response('abcdef'));
+ await download({ ...options(), retry: { maxAttempts: 2, baseDelayMs: 1, jitterRatio: 0 } });
+ expect(fetchMock).toHaveBeenCalledTimes(2);
+ });
+});
diff --git a/apps/desktop/src/main/downloader/__tests__/http.test.ts b/apps/desktop/src/main/downloader/__tests__/http.test.ts
new file mode 100644
index 0000000000..fe9fe2613e
--- /dev/null
+++ b/apps/desktop/src/main/downloader/__tests__/http.test.ts
@@ -0,0 +1,85 @@
+import { EventEmitter, getEventListeners } from 'node:events';
+import { PassThrough } from 'node:stream';
+import { afterEach, describe, expect, it, vi } from 'vitest';
+const requestMock = vi.hoisted(() => vi.fn());
+vi.mock('electron', () => ({ net: { request: requestMock } }));
+import { requestResponse } from '../http';
+
+function nativeRequest() {
+ const request = Object.assign(new EventEmitter(), {
+ setHeader: vi.fn(),
+ abort: vi.fn(),
+ end: vi.fn(),
+ });
+ requestMock.mockReturnValue(request);
+ return request;
+}
+afterEach(() => vi.resetAllMocks());
+describe('Electron HTTP stream adapter', () => {
+ it('returns redirect metadata without following it or waiting for a body', async () => {
+ const request = nativeRequest();
+ const signal = new AbortController().signal;
+ const pending = requestResponse('https://publisher.test/file', { signal });
+ request.emit('redirect', 302, 'GET', 'https://asset.test/file');
+ const response = await pending;
+ expect(response.status).toBe(302);
+ expect(response.headers.get('location')).toBe('https://asset.test/file');
+ expect(request.abort).toHaveBeenCalledOnce();
+ expect(getEventListeners(signal, 'abort')).toHaveLength(0);
+ });
+ it('streams bytes and releases the abort subscription after completion', async () => {
+ const request = nativeRequest();
+ const signal = new AbortController().signal;
+ const incoming = Object.assign(new PassThrough(), {
+ statusCode: 200,
+ headers: { 'content-length': '6' },
+ });
+ const pending = requestResponse('https://publisher.test/file', {
+ signal,
+ headers: { Range: 'bytes=3-' },
+ });
+ request.emit('response', incoming);
+ incoming.end(Buffer.from('abcdef'));
+ expect(await (await pending).text()).toBe('abcdef');
+ expect(request.setHeader).toHaveBeenCalledWith('range', 'bytes=3-');
+ expect(getEventListeners(signal, 'abort')).toHaveLength(0);
+ });
+ it('propagates consumer cancellation to the native request', async () => {
+ const request = nativeRequest();
+ const signal = new AbortController().signal;
+ const incoming = Object.assign(new PassThrough(), { statusCode: 200, headers: {} });
+ const pending = requestResponse('https://publisher.test/file', { signal });
+ request.emit('response', incoming);
+ await (await pending).body!.cancel();
+ await vi.waitFor(() => expect(request.abort).toHaveBeenCalledOnce());
+ expect(getEventListeners(signal, 'abort')).toHaveLength(0);
+ });
+ it('bounds buffered bytes while the caller is not reading', async () => {
+ const request = nativeRequest();
+ const incoming = Object.assign(new PassThrough({ highWaterMark: 64 * 1024 }), {
+ statusCode: 200,
+ headers: {},
+ });
+ const pending = requestResponse('https://publisher.test/file', {});
+ request.emit('response', incoming);
+ const response = await pending;
+ // Yield between chunks so the web-stream adapter can pull from the source.
+ let accepted = 0;
+ for (; accepted < 100; accepted++) {
+ const more = incoming.write(Buffer.alloc(16 * 1024));
+ await new Promise((resolve) => setImmediate(resolve));
+ if (!more) break;
+ }
+ expect(accepted).toBeLessThan(20);
+ await response.body!.cancel();
+ });
+ it('aborts while waiting for headers without retaining a signal listener', async () => {
+ const request = nativeRequest();
+ const controller = new AbortController();
+ const pending = requestResponse('https://publisher.test/file', { signal: controller.signal });
+ controller.abort();
+ await expect(pending).rejects.toThrow('aborted');
+ expect(request.abort).toHaveBeenCalledOnce();
+ expect(getEventListeners(controller.signal, 'abort')).toHaveLength(0);
+ });
+});
diff --git a/apps/desktop/src/main/downloader/__tests__/scheduler.test.ts b/apps/desktop/src/main/downloader/__tests__/scheduler.test.ts
index 0dcb78ee4b..c4ab6c66f1 100644
--- a/apps/desktop/src/main/downloader/__tests__/scheduler.test.ts
+++ b/apps/desktop/src/main/downloader/__tests__/scheduler.test.ts
@@ -1,4 +1,7 @@
-import { beforeEach, describe, expect, it, vi } from 'vitest';
+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
+import fs from 'node:fs';
+import os from 'node:os';
+import path from 'node:path';
const mocks = vi.hoisted(() => ({
computeHash: vi.fn(),
@@ -7,7 +10,7 @@ const mocks = vi.hoisted(() => ({
}));
vi.mock('../integrity', () => ({ computeHash: mocks.computeHash }));
-vi.mock('../transport', () => ({ executeOnce: mocks.executeOnce }));
+vi.mock('../transport', () => ({ executeOnce: mocks.executeOnce, assertDownloadUrl: vi.fn() }));
vi.mock('../retry', () => ({ withRetry: mocks.withRetry }));
vi.mock('../resume', () => ({ deletePart: vi.fn(), deleteMeta: vi.fn() }));
vi.mock('../../logger', () => ({
@@ -16,6 +19,9 @@ vi.mock('../../logger', () => ({
import { Scheduler } from '../scheduler';
+let root: string;
+afterEach(() => fs.rmSync(root, { recursive: true, force: true }));
+
const HASH_A = 'a'.repeat(64);
const HASH_B = 'b'.repeat(64);
@@ -25,6 +31,7 @@ function options(url: string, targetPath: string, sha256: string, signal?: Abort
describe('downloader scheduler queued cancellation', () => {
beforeEach(() => {
+ root = fs.mkdtempSync(path.join(os.tmpdir(), 'cindy-scheduler-'));
vi.resetAllMocks();
mocks.computeHash.mockResolvedValue('not-the-expected-hash');
mocks.withRetry.mockImplementation(async (run: () => Promise<unknown>) => run());
@@ -32,7 +39,9 @@ describe('downloader scheduler queued cancellation', () => {
it('rejects an aborted queued task immediately instead of waiting behind an active download', async () => {
let releaseFirst!: () => void;
- const firstGate = new Promise<void>((resolve) => { releaseFirst = resolve; });
+ const firstGate = new Promise<void>((resolve) => {
+ releaseFirst = resolve;
+ });
let executeCount = 0;
mocks.executeOnce.mockImplementation(async (ctx: { opts: { sha256: string } }) => {
executeCount += 1;
@@ -41,12 +50,14 @@ describe('downloader scheduler queued cancellation', () => {
});
const scheduler = new Scheduler({ maxConcurrent: 1 });
- const first = scheduler.enqueue(options('https://first.invalid', '/tmp/cindy-first', HASH_A));
+ const first = scheduler.enqueue(
+ options('https://first.invalid', path.join(root, 'first'), HASH_A),
+ );
await vi.waitFor(() => expect(mocks.executeOnce).toHaveBeenCalledTimes(1));
const controller = new AbortController();
const second = scheduler.enqueue(
- options('https://second.invalid', '/tmp/cindy-second', HASH_B, controller.signal),
+ options('https://second.invalid', path.join(root, 'second'), HASH_B, controller.signal),
);
controller.abort();
@@ -56,4 +67,27 @@ describe('downloader scheduler queued cancellation', () => {
releaseFirst();
await expect(first).resolves.toMatchObject({ sha256: HASH_A });
});
+ it('holds its slot during cache hashing and starts the queue after a cache hit', async () => {
+ const scheduler = new Scheduler({ maxConcurrent: 1 });
+ const cached = path.join(root, 'cached');
+ fs.writeFileSync(cached, 'cached');
+ let finishHash!: (hash: string) => void;
+ mocks.computeHash.mockImplementationOnce(
+ () =>
+ new Promise((resolve) => {
+ finishHash = resolve;
+ }),
+ );
+ mocks.executeOnce.mockResolvedValue({ size: 1, sha256: HASH_B });
+ const first = scheduler.enqueue(options('https://first.invalid', cached, HASH_A));
+ const second = scheduler.enqueue(
+ options('https://second.invalid', path.join(root, 'next'), HASH_B),
+ );
+ expect(mocks.executeOnce).not.toHaveBeenCalled();
+ expect(scheduler.listActive()).toHaveLength(1);
+ finishHash(HASH_A);
+ await expect(first).resolves.toMatchObject({ fromCache: true });
+ await expect(second).resolves.toMatchObject({ sha256: HASH_B });
+ expect(scheduler.listActive()).toEqual([]);
+ });
});
diff --git a/apps/desktop/src/main/downloader/cancel.ts b/apps/desktop/src/main/downloader/cancel.ts
index 342d912656..680a0c8dc3 100644
--- a/apps/desktop/src/main/downloader/cancel.ts
+++ b/apps/desktop/src/main/downloader/cancel.ts
@@ -4,13 +4,11 @@
* Cancellation cleanup and error semantics are maintained in this module.
*
* The cancel logic lives where it actually fires:
- * - In-flight cancel → transport.ts (AbortSignal handler aborts net.request)
+ * - In-flight cancel → transport.ts (AbortSignal handler aborts the native HTTP request)
* - Backoff cancel → retry.ts (sleepInterruptible)
* - Queued cancel → scheduler.ts (tryStart short-circuits aborted tasks)
*
- * cleanup() lives on the scheduler; this file simply re-exports the
- * conceptual seam so callers can `import { cleanup } from './downloader/cancel'`
- * if they ever need to. Most callers just use the Facade in index.ts.
+ * cleanup() lives on the scheduler; callers use the public facade in index.ts.
*/
-export { } ; // intentional empty namespace — see header
+export {}; // intentional empty namespace — see header
diff --git a/apps/desktop/src/main/downloader/http.ts b/apps/desktop/src/main/downloader/http.ts
new file mode 100644
index 0000000000..4d61ca80ab
--- /dev/null
+++ b/apps/desktop/src/main/downloader/http.ts
@@ -0,0 +1,71 @@
+import { net } from 'electron';
+import { Readable } from 'node:stream';
+
+/** Electron fetch rejects manual redirects instead of returning their response.
+ * Keep redirect decisions in transport, and expose the native Readable as a Web
+ * stream so awaited disk writes propagate backpressure to Chromium.
+ */
+export function requestResponse(url: string, init: RequestInit): Promise<Response> {
+ return new Promise((resolve, reject) => {
+ const request = net.request({ url, method: 'GET', redirect: 'manual' });
+ new Headers(init.headers).forEach((value, name) => request.setHeader(name, value));
+ let settled = false;
+ const signal = init.signal;
+ const detach = () => signal?.removeEventListener('abort', abort);
+ const fail = (error: Error) => {
+ if (settled) return;
+ settled = true;
+ detach();
+ reject(error);
+ };
+ const abort = () => {
+ fail(new Error('Request aborted'));
+ request.abort();
+ };
+ request.on('error', fail);
+ request.on('redirect', (status, _method, location) => {
+ if (settled) return;
+ settled = true;
+ detach();
+ // Do not follow here: transport validates the next URL before requesting it.
+ resolve(new Response(null, { status, headers: { location } }));
+ request.abort();
+ });
+ request.on('response', (incoming) => {
+ if (settled) return;
+ settled = true;
+ // Electron IncomingMessage implements Readable; its typings omit stream methods.
+ const stream = incoming as unknown as Readable;
+ const headers = new Headers();
+ for (const [name, values] of Object.entries(incoming.headers)) {
+ for (const value of Array.isArray(values) ? values : [values]) headers.append(name, value);
+ }
+ stream.once('end', detach);
+ stream.once('close', () => {
+ detach();
+ if (!stream.readableEnded) request.abort();
+ });
+ const body = [204, 205, 304].includes(incoming.statusCode)
+ ? null
+ : Readable.toWeb(stream, {
+ strategy: { highWaterMark: 64 * 1024, size: (chunk: Buffer) => chunk.byteLength },
+ });
+ if (body === null) {
+ stream.once('error', detach);
+ stream.resume();
+ }
+ resolve(
+ new Response(body as ReadableStream<Uint8Array> | null, {
+ status: incoming.statusCode,
+ headers,
+ }),
+ );
+ });
+ if (signal?.aborted) {
+ abort();
+ return;
+ }
+ signal?.addEventListener('abort', abort, { once: true });
+ request.end();
+ });
+}
diff --git a/apps/desktop/src/main/downloader/index.ts b/apps/desktop/src/main/downloader/index.ts
index 8bc8772b98..ccc5ff34c4 100644
--- a/apps/desktop/src/main/downloader/index.ts
+++ b/apps/desktop/src/main/downloader/index.ts
@@ -8,17 +8,13 @@
*
* Contract invariants (re-stated; full version in tech spec):
* 1. download() resolves DownloadResult or rejects DownloadError, no other types.
- * 2. onProgress.loaded is monotonic non-decreasing within a single download.
+ * 2. Progress describes the current attempt (a fresh retry may restart at zero).
* 3. resolve implies SHA256 already verified — no need to re-check.
*/
import path from 'node:path';
import { Scheduler } from './scheduler';
-import {
- DownloadError,
- type DownloadOptions,
- type DownloadResult,
-} from './types';
+import { DownloadError, type DownloadOptions, type DownloadResult } from './types';
let _scheduler: Scheduler | null = null;
function getScheduler(): Scheduler {
@@ -38,6 +34,18 @@ function validate(opts: DownloadOptions): void {
if (typeof opts?.sha256 !== 'string' || !/^[0-9a-fA-F]{64}$/.test(opts.sha256)) {
throw new DownloadError('INVALID_ARG', 'sha256 must be 64-char hex');
}
+ for (const value of [opts.expectedSize, opts.maxBytes]) {
+ if (value !== undefined && (!Number.isSafeInteger(value) || value < 0)) {
+ throw new DownloadError('INVALID_ARG', 'Download size must be a nonnegative integer');
+ }
+ }
+ if ((opts.expectedSize ?? 0) > (opts.maxBytes ?? Infinity)) {
+ throw new DownloadError('SIZE', 'Expected download exceeds allowed size');
+ }
+ for (const value of Object.values(opts.timeout ?? {})) {
+ if (!Number.isSafeInteger(value) || value <= 0)
+ throw new DownloadError('INVALID_ARG', 'Invalid download timeout');
+ }
}
/**
@@ -48,7 +56,31 @@ function validate(opts: DownloadOptions): void {
*/
export function download(opts: DownloadOptions): Promise<DownloadResult> {
validate(opts);
- return getScheduler().enqueue({ ...opts, sha256: opts.sha256.toLowerCase() });
+ const normalized = {
+ ...opts,
+ targetPath: path.resolve(opts.targetPath),
+ sha256: opts.sha256.toLowerCase(),
+ };
+ if (!opts.timeout?.totalMs) return getScheduler().enqueue(normalized);
+ const controller = new AbortController();
+ let timedOut = false;
+ const abort = () => controller.abort();
+ opts.signal?.addEventListener('abort', abort, { once: true });
+ if (opts.signal?.aborted) abort();
+ const timer = setTimeout(() => {
+ timedOut = true;
+ controller.abort();
+ }, opts.timeout.totalMs);
+ return getScheduler()
+ .enqueue({ ...normalized, signal: controller.signal })
+ .catch((error) => {
+ if (timedOut) throw new DownloadError('TIMEOUT', 'Download total time limit exceeded');
+ throw error;
+ })
+ .finally(() => {
+ clearTimeout(timer);
+ opts.signal?.removeEventListener('abort', abort);
+ });
}
/**
@@ -57,9 +89,7 @@ export function download(opts: DownloadOptions): Promise<DownloadResult> {
*/
export function cleanup(targetPath: string): Promise<void> {
if (!path.isAbsolute(targetPath)) {
- return Promise.reject(
- new DownloadError('INVALID_ARG', 'targetPath must be absolute'),
- );
+ return Promise.reject(new DownloadError('INVALID_ARG', 'targetPath must be absolute'));
}
return getScheduler().cleanup(targetPath);
}
diff --git a/apps/desktop/src/main/downloader/retry.ts b/apps/desktop/src/main/downloader/retry.ts
index cc8a3668cb..81d5b3e170 100644
--- a/apps/desktop/src/main/downloader/retry.ts
+++ b/apps/desktop/src/main/downloader/retry.ts
@@ -5,8 +5,7 @@
*
* Backoff: 1s, 2s, 4s, 8s, 16s, 30s (capped at maxDelayMs, ±25% jitter).
*
- * Retryable codes: NETWORK, HTTP_5XX
- * Non-retryable: HTTP_4XX, CHECKSUM, DISK, ABORTED, INVALID_ARG
+ * Retryable codes: NETWORK, HTTP_5XX, per-attempt TIMEOUT. Other failures are permanent.
*
* The sleep between attempts is interruptible — if the AbortSignal fires while
* we're backing off, we throw `ABORTED` immediately without waiting out the
@@ -29,15 +28,13 @@ export interface RetryOptions {
onRetry?: (e: { attempt: number; delayMs: number; cause: Error }) => void;
}
-export async function withRetry<T>(
- task: () => Promise<T>,
- opts: RetryOptions,
-): Promise<T> {
+export async function withRetry<T>(task: () => Promise<T>, opts: RetryOptions): Promise<T> {
const cfg: RetryConfig = { ...DEFAULT_RETRY, ...(opts.config ?? {}) };
let attempt = 0;
let lastError: Error | null = null;
while (attempt < cfg.maxAttempts) {
+ if (opts.signal?.aborted) throw new DownloadError('ABORTED', 'Download aborted');
attempt++;
try {
return await task();
@@ -69,7 +66,7 @@ export async function withRetry<T>(
function isRetryable(err: unknown): boolean {
if (!(err instanceof DownloadError)) return false;
- return err.code === 'NETWORK' || err.code === 'HTTP_5XX';
+ return err.code === 'NETWORK' || err.code === 'HTTP_5XX' || err.code === 'TIMEOUT';
}
/** Backoff: min(base * 2^(attempt-1), max) * (1 ± jitterRatio) */
diff --git a/apps/desktop/src/main/downloader/scheduler.ts b/apps/desktop/src/main/downloader/scheduler.ts
index 89daeac5a4..5a3f29b663 100644
--- a/apps/desktop/src/main/downloader/scheduler.ts
+++ b/apps/desktop/src/main/downloader/scheduler.ts
@@ -4,22 +4,17 @@
* Concurrency and queue-ordering invariants are maintained in this module.
*
* Responsibilities:
- * - Single-flight: identical (url|targetPath|sha256) tuples share one Promise.
+ * - Single-flight: identical inputs share one Promise; conflicting target owners are rejected.
* - Concurrency cap (default 1) + FIFO queue.
* - fromCache short-circuit: if targetPath already exists & sha256 matches,
- * resolve immediately without entering the queue work.
+ * resolve without HTTP while holding the queue slot during hashing.
* - Wraps executeOnce() with withRetry().
*/
import fs from 'node:fs';
-import {
- DownloadError,
- type DownloadOptions,
- type DownloadResult,
- type Logger,
-} from './types';
+import { DownloadError, type DownloadOptions, type DownloadResult, type Logger } from './types';
import { computeHash } from './integrity';
-import { executeOnce, type TransportContext } from './transport';
+import { assertDownloadUrl, executeOnce, type TransportContext } from './transport';
import { withRetry } from './retry';
import { deletePart, deleteMeta } from './resume';
@@ -49,12 +44,15 @@ const defaultLogger: Logger = {
warn: (msg, meta) => log.warn(msg, meta ?? ''),
info: (msg, meta) => log.info(msg, meta ?? ''),
error: (msg, meta) => log.error(msg, meta ?? ''),
- debug: () => { /* silent by default */ },
+ debug: () => {
+ /* silent by default */
+ },
};
export class Scheduler {
private readonly maxConcurrent: number;
private inflight = new Map<string, Promise<DownloadResult>>();
+ private inputs = new Map<string, DownloadOptions>();
private active = new Map<string, ActiveTask>();
private queue: QueuedTask[] = [];
@@ -64,9 +62,24 @@ export class Scheduler {
enqueue(opts: DownloadOptions): Promise<DownloadResult> {
const key = this.makeKey(opts);
-
+ if (opts.signal?.aborted)
+ return Promise.reject(new DownloadError('ABORTED', 'Download aborted'));
const existing = this.inflight.get(key);
- if (existing !== undefined) return existing;
+ if (existing !== undefined) {
+ const prior = this.inputs.get(key)!;
+ // Different policies/cancellation owners must never borrow an in-flight result.
+ const same = new Set([...Object.keys(prior), ...Object.keys(opts)]);
+ if (
+ [...same].every((name) => {
+ const field = name as keyof DownloadOptions;
+ return field === 'timeout' || field === 'retry'
+ ? JSON.stringify(prior[field]) === JSON.stringify(opts[field])
+ : prior[field] === opts[field];
+ })
+ )
+ return existing;
+ return Promise.reject(new DownloadError('INVALID_ARG', 'Download target is already in use'));
+ }
const promise = new Promise<DownloadResult>((resolve, reject) => {
const task: QueuedTask = { key, opts, resolve, reject };
@@ -76,11 +89,18 @@ export class Scheduler {
this.tryStart();
});
this.inflight.set(key, promise);
+ this.inputs.set(key, opts);
// 用双分支 then 做清理,避免 finally 返回的 rejected Promise 在调用方
// 尚未来得及接住时触发 unhandledRejection。
void promise.then(
- () => this.inflight.delete(key),
- () => this.inflight.delete(key),
+ () => {
+ this.inflight.delete(key);
+ this.inputs.delete(key);
+ },
+ () => {
+ this.inflight.delete(key);
+ this.inputs.delete(key);
+ },
);
return promise;
}
@@ -99,7 +119,7 @@ export class Scheduler {
}
private makeKey(opts: DownloadOptions): string {
- return `${opts.url}|${opts.targetPath}|${opts.sha256}`;
+ return opts.targetPath;
}
private tryStart(): void {
@@ -137,42 +157,56 @@ export class Scheduler {
const startedAt = Date.now();
const logger: Logger = task.opts.logger ?? defaultLogger;
- // ── fromCache short-circuit ──
+ // Reserve the slot BEFORE asynchronous cache hashing, including cache hits.
+ this.active.set(task.key, { url: task.opts.url, targetPath: task.opts.targetPath, loaded: 0 });
try {
- if (fs.existsSync(task.opts.targetPath)) {
- const hash = await computeHash(task.opts.targetPath);
- if (hash === task.opts.sha256) {
- task.resolve({
- path: task.opts.targetPath,
- size: fs.statSync(task.opts.targetPath).size,
- sha256: hash,
- fromCache: true,
- durationMs: Date.now() - startedAt,
- resumedFromBytes: 0,
- });
- return;
+ assertDownloadUrl(task.opts.url, task.opts);
+ // ── fromCache short-circuit ──
+ if (task.opts.existingTarget === 'error' && fs.existsSync(task.opts.targetPath)) {
+ throw new DownloadError('EXISTS', 'Download target already exists');
+ }
+ try {
+ if (fs.existsSync(task.opts.targetPath)) {
+ const hash = await computeHash(task.opts.targetPath);
+ const size = fs.statSync(task.opts.targetPath).size;
+ if (task.opts.signal?.aborted) throw new DownloadError('ABORTED', 'Download aborted');
+ if (
+ hash === task.opts.sha256 &&
+ size <= (task.opts.maxBytes ?? Infinity) &&
+ (task.opts.expectedSize === undefined || size === task.opts.expectedSize)
+ ) {
+ task.resolve({
+ path: task.opts.targetPath,
+ size: fs.statSync(task.opts.targetPath).size,
+ sha256: hash,
+ fromCache: true,
+ durationMs: Date.now() - startedAt,
+ resumedFromBytes: 0,
+ });
+ return;
+ }
}
+ } catch (err) {
+ if (err instanceof DownloadError) throw err;
+ logger.debug?.('[downloader] fromCache check failed; falling through', {
+ err: (err as Error).message,
+ });
}
- } catch (err) {
- logger.debug?.('[downloader] fromCache check failed; falling through', {
- err: (err as Error).message,
- });
- }
- const ctx: TransportContext = {
- opts: task.opts,
- logger,
- signal: task.opts.signal,
- resumedFromBytes: 0,
- };
-
- this.active.set(task.key, {
- url: task.opts.url,
- targetPath: task.opts.targetPath,
- loaded: 0,
- });
+ const ctx: TransportContext = {
+ opts: {
+ ...task.opts,
+ onProgress: (event) => {
+ const active = this.active.get(task.key);
+ if (active) active.loaded = event.loaded;
+ task.opts.onProgress?.(event);
+ },
+ },
+ logger,
+ signal: task.opts.signal,
+ resumedFromBytes: 0,
+ };
- try {
const result = await withRetry(() => executeOnce(ctx), {
config: task.opts.retry,
signal: task.opts.signal,
diff --git a/apps/desktop/src/main/downloader/transport.ts b/apps/desktop/src/main/downloader/transport.ts
index 9fd1c486d6..3e7954ad10 100644
--- a/apps/desktop/src/main/downloader/transport.ts
+++ b/apps/desktop/src/main/downloader/transport.ts
@@ -1,27 +1,9 @@
-/**
- * unified-downloader — M2: HTTP transport + resumable download.
- * ---------------------------------------------------------------------------
- * This module owns one resumable HTTP attempt; retry policy lives in retry.ts.
- *
- * Single-attempt execution. The retry/backoff loop lives in retry.ts. This
- * file is responsible for ONE network round-trip:
- * - Decide resume vs fresh based on .meta.json + .part.
- * - Send GET (with Range + If-Range when resuming).
- * - Stream chunks → write to .part, feed SHA256 hasher, advance progress.
- * - On EOF: verify SHA256, rename .part → targetPath, delete .meta.json.
- *
- * Cleanup invariants on reject:
- * - CHECKSUM → delete .part + .meta.json (corrupt, retry would loop).
- * - HTTP_4XX → keep .part + .meta.json (caller may want to inspect).
- * - NETWORK / HTTP_5XX → keep .part + .meta.json (resumable next time).
- * - ABORTED → keep .part + .meta.json (caller asked to pause).
- * - DISK → keep .part + .meta.json (caller decides; cleanup() exists).
- */
-
-import { net } from 'electron';
+/** One HTTP attempt. Callers supply policy; queueing/retries live in scheduler.
+ * Await disk writes to bound memory even for multi-gigabyte runtime archives. */
+import { requestResponse } from './http';
import fs from 'node:fs';
import path from 'node:path';
-import { DownloadError, type DownloadOptions, type Logger, type TimeoutConfig } from './types';
+import { DownloadError, type DownloadOptions, type Logger } from './types';
import {
partPath,
readMeta,
@@ -31,358 +13,281 @@ import {
decideResumeOffset,
type MetaJson,
} from './resume';
-import { createStreamingHasher, computeHash } from './integrity';
+import { createStreamingHasher } from './integrity';
import { ProgressTracker } from './progress';
-const DEFAULT_TIMEOUT: TimeoutConfig = { connectMs: 10_000, idleMs: 30_000 };
-const META_WRITE_INTERVAL_MS = 2000;
-
export interface TransportContext {
opts: DownloadOptions;
logger: Logger;
signal?: AbortSignal;
- /** Bytes restored from `.part`. Set by executeOnce(); caller reads after success. */
resumedFromBytes: number;
}
-
export interface TransportResult {
size: number;
sha256: string;
}
-/**
- * Headers returned by Electron's net.request can be either a string or string[].
- * We normalize via this helper.
- */
-function pickHeader(headers: Record<string, string | string[]>, key: string): string | null {
- const v = headers[key.toLowerCase()];
- if (v === undefined) return null;
- return Array.isArray(v) ? (v[0] ?? null) : v;
-}
-
-function parseContentLength(
- headers: Record<string, string | string[]>,
- status: number,
- resumeOffset: number | null,
-): number | null {
- // 206 Partial Content: prefer Content-Range total, else Content-Length + offset.
- if (status === 206) {
- const range = pickHeader(headers, 'content-range');
- if (range !== null) {
- const m = /\/(\d+)$/.exec(range);
- if (m !== null) return Number(m[1]);
- }
- const cl = pickHeader(headers, 'content-length');
- if (cl !== null && resumeOffset !== null) return Number(cl) + resumeOffset;
+export function assertDownloadUrl(url: string, opts: DownloadOptions): void {
+ let parsed: URL;
+ try {
+ parsed = new URL(url);
+ } catch {
+ throw new DownloadError('URL_POLICY', 'Invalid download URL');
+ }
+ if (
+ !['http:', 'https:'].includes(parsed.protocol) ||
+ parsed.username ||
+ parsed.password ||
+ (opts.isUrlAllowed && !opts.isUrlAllowed(url))
+ ) {
+ throw new DownloadError('URL_POLICY', 'Download URL is not allowed');
}
- const cl = pickHeader(headers, 'content-length');
- if (cl === null) return null;
- return Number(cl);
}
export async function executeOnce(ctx: TransportContext): Promise<TransportResult> {
- const { opts, logger } = ctx;
- const timeout: TimeoutConfig = { ...DEFAULT_TIMEOUT, ...(opts.timeout ?? {}) };
-
- // ── Step 0: target file already exists & matches sha256 → fast path ──
- // (Scheduler also short-circuits this; the duplicate check here protects
- // against scheduler bypass paths and is cheap when the file is missing.)
- if (fs.existsSync(opts.targetPath)) {
+ const { opts } = ctx;
+ const signal = ctx.signal ?? opts.signal;
+ const controller = new AbortController();
+ let timedOut = false;
+ let timer: ReturnType<typeof setTimeout> | undefined;
+ let response: Response | undefined;
+ let reader: ReadableStreamDefaultReader<Uint8Array> | undefined;
+ let file: fs.promises.FileHandle | undefined;
+ let meta: MetaJson | undefined;
+ let loaded = 0;
+ let complete = false;
+ let discard = opts.resume === false;
+ const abort = () => controller.abort();
+ const checkAbort = () => {
+ if (controller.signal.aborted)
+ throw new DownloadError(
+ timedOut ? 'TIMEOUT' : 'ABORTED',
+ timedOut ? 'Download timed out' : 'Download aborted',
+ );
+ };
+ const armTimer = (ms: number) => {
+ clearTimeout(timer);
+ timer = setTimeout(() => {
+ timedOut = true;
+ controller.abort();
+ }, ms);
+ };
+ const network = async <T>(operation: Promise<T>): Promise<T> => {
try {
- const existingHash = await computeHash(opts.targetPath);
- if (existingHash === opts.sha256) {
- return { size: fs.statSync(opts.targetPath).size, sha256: existingHash };
- }
- try { fs.unlinkSync(opts.targetPath); } catch { /* ignore */ }
+ return await operation;
} catch {
- try { fs.unlinkSync(opts.targetPath); } catch { /* ignore */ }
+ checkAbort();
+ // Native errors may contain signed URLs. Never expose those to callers/logs.
+ throw new DownloadError('NETWORK', 'Download network request failed');
}
- }
-
- // ── Step 1: decide resume vs fresh ──
- const resumeOffset = decideResumeOffset(
- opts.targetPath,
- opts.url,
- opts.expectedSize,
- opts.sha256,
- );
- if (resumeOffset === null) {
- deletePart(opts.targetPath);
- deleteMeta(opts.targetPath);
- } else {
- ctx.resumedFromBytes = resumeOffset;
- opts.onResume?.({ fromBytes: resumeOffset, totalBytes: opts.expectedSize ?? null });
- }
-
- fs.mkdirSync(path.dirname(opts.targetPath), { recursive: true });
-
- // ── Step 2: build headers ──
- const headers: Record<string, string> = {};
- if (resumeOffset !== null) {
- headers['Range'] = `bytes=${resumeOffset}-`;
- const meta = readMeta(opts.targetPath);
- if (meta?.etag) headers['If-Range'] = meta.etag;
- else if (meta?.lastModified) headers['If-Range'] = meta.lastModified;
- }
-
- // ── Step 3: HTTP request via Electron net (auto-respects system proxy) ──
- return await new Promise<TransportResult>((resolve, reject) => {
- const request = net.request({ url: opts.url, method: 'GET', redirect: 'follow' });
- Object.entries(headers).forEach(([k, v]) => request.setHeader(k, v));
-
- let connectTimer: ReturnType<typeof setTimeout> | null = null;
- let idleTimer: ReturnType<typeof setTimeout> | null = null;
- let settled = false;
-
- const cleanupTimers = (): void => {
- if (connectTimer !== null) { clearTimeout(connectTimer); connectTimer = null; }
- if (idleTimer !== null) { clearTimeout(idleTimer); idleTimer = null; }
- };
-
- const safeReject = (err: DownloadError): void => {
- if (settled) return;
- settled = true;
- cleanupTimers();
- if (opts.signal !== undefined) opts.signal.removeEventListener('abort', onAbort);
- reject(err);
- };
-
- const safeResolve = (r: TransportResult): void => {
- if (settled) return;
- settled = true;
- cleanupTimers();
- if (opts.signal !== undefined) opts.signal.removeEventListener('abort', onAbort);
- resolve(r);
- };
-
- const onAbort = (): void => {
- try { request.abort(); } catch { /* ignore */ }
- // Keep .part + .meta — caller asked to pause.
- safeReject(new DownloadError('ABORTED', 'download aborted by caller'));
- };
-
- if (opts.signal !== undefined) {
- if (opts.signal.aborted) {
- onAbort();
- return;
- }
- opts.signal.addEventListener('abort', onAbort, { once: true });
+ };
+ signal?.addEventListener('abort', abort, { once: true });
+ if (signal?.aborted) abort();
+ try {
+ checkAbort();
+ assertDownloadUrl(opts.url, opts);
+ if (opts.existingTarget === 'error' && fs.existsSync(opts.targetPath)) {
+ throw new DownloadError('EXISTS', 'Download target already exists');
}
-
- connectTimer = setTimeout(() => {
- try { request.abort(); } catch { /* ignore */ }
- safeReject(new DownloadError('NETWORK', `connect timeout after ${timeout.connectMs}ms`));
- }, timeout.connectMs);
-
- const resetIdleTimer = (): void => {
- if (idleTimer !== null) clearTimeout(idleTimer);
- idleTimer = setTimeout(() => {
- try { request.abort(); } catch { /* ignore */ }
- safeReject(new DownloadError('NETWORK', `idle timeout after ${timeout.idleMs}ms`));
- }, timeout.idleMs);
- };
-
- request.on('response', (response) => {
- if (connectTimer !== null) { clearTimeout(connectTimer); connectTimer = null; }
-
- const status = response.statusCode;
- const responseHeaders = response.headers as Record<string, string | string[]>;
-
- // 4xx → permanent failure for this URL (not retried).
- if (status >= 400 && status < 500) {
- try { request.abort(); } catch { /* ignore */ }
- safeReject(new DownloadError('HTTP_4XX', `HTTP ${status}`, undefined, status));
- return;
+ let offset =
+ opts.resume === false
+ ? null
+ : decideResumeOffset(opts.targetPath, opts.url, opts.expectedSize, opts.sha256);
+ if (
+ offset !== null &&
+ (offset >= (opts.expectedSize ?? Infinity) || offset > (opts.maxBytes ?? Infinity))
+ )
+ offset = null;
+ if (offset === null) {
+ deletePart(opts.targetPath);
+ deleteMeta(opts.targetPath);
+ }
+ ctx.resumedFromBytes = offset ?? 0;
+ loaded = offset ?? 0;
+ await fs.promises.mkdir(path.dirname(opts.targetPath), { recursive: true });
+ checkAbort();
+ const headers: Record<string, string> = { 'Accept-Encoding': 'identity' };
+ if (offset !== null) {
+ headers.Range = `bytes=${offset}-`;
+ const prior = readMeta(opts.targetPath);
+ if (prior?.etag) headers['If-Range'] = prior.etag;
+ else if (prior?.lastModified) headers['If-Range'] = prior.lastModified;
+ }
+ armTimer(opts.timeout?.connectMs ?? 10_000);
+ let url = opts.url;
+ for (let hops = 0; ; hops++) {
+ assertDownloadUrl(url, opts);
+ response = await network(
+ requestResponse(url, {
+ method: 'GET',
+ cache: 'no-store',
+ redirect: opts.redirect === 'error' ? 'error' : 'manual',
+ headers,
+ signal: controller.signal,
+ }),
+ );
+ checkAbort();
+ if (![301, 302, 303, 307, 308].includes(response.status)) break;
+ const location = response.headers.get('location');
+ await response.body?.cancel();
+ response = undefined;
+ if (opts.redirect === 'error' || !location || hops >= 5) {
+ throw new DownloadError('URL_POLICY', 'Download redirect is not allowed');
}
- // 5xx → transient; retry layer decides.
- if (status >= 500) {
- try { request.abort(); } catch { /* ignore */ }
- safeReject(new DownloadError('HTTP_5XX', `HTTP ${status}`, undefined, status));
- return;
+ try {
+ url = new URL(location, url).href;
+ } catch {
+ throw new DownloadError('URL_POLICY', 'Invalid redirect URL');
}
-
- // We asked for Range but server returned full body → restart fresh next attempt.
- if (resumeOffset !== null && status === 200) {
- try { request.abort(); } catch { /* ignore */ }
- deletePart(opts.targetPath);
- deleteMeta(opts.targetPath);
- safeReject(new DownloadError('NETWORK', 'server does not support Range, restarting'));
- return;
+ }
+ if (response.status >= 500)
+ throw new DownloadError('HTTP_5XX', `HTTP ${response.status}`, undefined, response.status);
+ if (response.status >= 400) {
+ if (response.status === 416 && offset !== null) {
+ discard = true;
+ throw new DownloadError('NETWORK', 'Invalid resume range; restarting');
}
-
- const totalBytes = parseContentLength(responseHeaders, status, resumeOffset);
- const etag = pickHeader(responseHeaders, 'etag');
- const lastModified = pickHeader(responseHeaders, 'last-modified');
-
- // For fresh downloads, Content-Length must match expectedSize when both known.
+ throw new DownloadError('HTTP_4XX', `HTTP ${response.status}`, undefined, response.status);
+ }
+ if (offset !== null && response.status === 200) {
+ // Server ignored Range (or If-Range changed): use this full response fresh.
+ offset = null;
+ loaded = 0;
+ ctx.resumedFromBytes = 0;
+ deletePart(opts.targetPath);
+ deleteMeta(opts.targetPath);
+ }
+ if (response.status !== (offset === null ? 200 : 206)) {
+ discard = true;
+ throw new DownloadError('NETWORK', 'Unexpected download response');
+ }
+ const lengthHeader = response.headers.get('content-length');
+ const length = lengthHeader === null ? null : Number(lengthHeader);
+ if (length !== null && (!Number.isSafeInteger(length) || length < 0))
+ throw new DownloadError('SIZE', 'Invalid Content-Length');
+ let total = length === null ? null : length + (offset ?? 0);
+ if (offset !== null) {
+ const range = /^bytes (\d+)-(\d+)\/(\d+)$/.exec(response.headers.get('content-range') ?? '');
if (
- resumeOffset === null &&
- opts.expectedSize !== undefined &&
- totalBytes !== null &&
- totalBytes !== opts.expectedSize
+ !range ||
+ Number(range[1]) !== offset ||
+ Number(range[2]) < offset ||
+ Number(range[2]) + 1 !== Number(range[3]) ||
+ !Number.isSafeInteger(Number(range[3])) ||
+ (length !== null && length !== Number(range[2]) - offset + 1)
) {
- try { request.abort(); } catch { /* ignore */ }
- deletePart(opts.targetPath);
- deleteMeta(opts.targetPath);
- safeReject(
- new DownloadError(
- 'NETWORK',
- `Content-Length ${totalBytes} != expectedSize ${opts.expectedSize}`,
- ),
- );
- return;
+ discard = true;
+ throw new DownloadError('NETWORK', 'Invalid Content-Range; restarting');
}
-
- // ── Open .part for append (resume) or truncate (fresh) ──
- const isResume = resumeOffset !== null && status === 206;
- const writeStream = fs.createWriteStream(partPath(opts.targetPath), {
- flags: isResume ? 'a' : 'w',
- });
-
- const tracker = new ProgressTracker({
- initialLoaded: isResume ? resumeOffset : 0,
- total: totalBytes,
- onProgress: opts.onProgress,
- });
-
- const hasher = createStreamingHasher(isResume ? partPath(opts.targetPath) : null);
-
- const meta: MetaJson = {
- url: opts.url,
- expectedSize: opts.expectedSize ?? totalBytes,
- expectedSha256: opts.sha256,
- downloadedBytes: tracker.getLoaded(),
- etag,
- lastModified,
- createdAt: new Date().toISOString(),
- updatedAt: new Date().toISOString(),
- };
- try {
- writeMeta(opts.targetPath, meta);
- } catch (err) {
- logger.warn?.('[downloader] writeMeta failed (non-fatal)', { err: (err as Error).message });
+ total = Number(range[3]);
+ opts.onResume?.({ fromBytes: offset, totalBytes: total });
+ }
+ if (
+ (opts.expectedSize !== undefined && total !== null && total !== opts.expectedSize) ||
+ (total !== null && total > (opts.maxBytes ?? Infinity))
+ ) {
+ throw new DownloadError('SIZE', 'Content-Length does not match the allowed size');
+ }
+ if (!response.body) throw new DownloadError('NETWORK', 'Download response body is empty');
+ reader = response.body.getReader();
+ const hasher = createStreamingHasher(offset === null ? null : partPath(opts.targetPath));
+ await hasher.update(Buffer.alloc(0));
+ file = await fs.promises.open(partPath(opts.targetPath), offset === null ? 'w' : 'a', 0o600);
+ const tracker = new ProgressTracker({
+ initialLoaded: loaded,
+ total: opts.expectedSize ?? total,
+ onProgress: opts.onProgress,
+ });
+ meta = {
+ url: opts.url,
+ expectedSize: opts.expectedSize ?? total,
+ expectedSha256: opts.sha256,
+ downloadedBytes: loaded,
+ etag: response.headers.get('etag'),
+ lastModified: response.headers.get('last-modified'),
+ createdAt: new Date().toISOString(),
+ updatedAt: new Date().toISOString(),
+ };
+ let lastMetaWriteAt = 0;
+ armTimer(opts.timeout?.idleMs ?? 30_000);
+ while (true) {
+ checkAbort();
+ const { done, value } = await network(reader.read());
+ checkAbort();
+ if (done) break;
+ if (!value.byteLength) continue;
+ if (
+ loaded + value.byteLength >
+ Math.min(opts.expectedSize ?? Infinity, opts.maxBytes ?? Infinity)
+ ) {
+ throw new DownloadError('SIZE', 'Download exceeds allowed size');
}
-
- let lastMetaWriteAt = Date.now();
-
- writeStream.on('error', (err) => {
- try { request.abort(); } catch { /* ignore */ }
- safeReject(new DownloadError('DISK', `write stream failed: ${err.message}`, err));
- });
-
- response.on('data', (chunk: Buffer) => {
- resetIdleTimer();
- // 1. Persist to disk. Electron's IncomingMessage isn't a Node Readable
- // stream (no pause/resume/destroy on it directly), so we can't apply
- // Node-style backpressure here; we accept the buffer and let the
- // fs.WriteStream queue it. For the tens-of-MB payloads we ship
- // (app patch / claude bin), this stays well within the default
- // highWaterMark budget.
- writeStream.write(chunk);
- // 2. Feed hasher (async because of priming, but we don't await here —
- // the write order is preserved by hasher's internal `await primed`).
- void hasher.update(chunk).catch((err: Error) => {
- try { request.abort(); } catch { /* ignore */ }
- try { writeStream.destroy(); } catch { /* ignore */ }
- safeReject(new DownloadError('DISK', `hash update failed: ${err.message}`, err));
+ armTimer(opts.timeout?.idleMs ?? 30_000);
+ await file.writeFile(value);
+ await hasher.update(Buffer.from(value));
+ loaded += value.byteLength;
+ tracker.advance(value.byteLength);
+ if (Date.now() - lastMetaWriteAt >= 2000) {
+ writeMeta(opts.targetPath, {
+ ...meta,
+ downloadedBytes: loaded,
+ updatedAt: new Date().toISOString(),
});
- // 3. Advance progress.
- tracker.advance(chunk.length);
- // 4. Throttled meta update.
- const now = Date.now();
- if (now - lastMetaWriteAt > META_WRITE_INTERVAL_MS) {
- lastMetaWriteAt = now;
- try {
- writeMeta(opts.targetPath, {
- ...meta,
- downloadedBytes: tracker.getLoaded(),
- updatedAt: new Date().toISOString(),
- });
- } catch (err) {
- logger.debug?.('[downloader] writeMeta tick failed', { err: (err as Error).message });
- }
+ lastMetaWriteAt = Date.now();
+ }
+ }
+ clearTimeout(timer);
+ if (loaded !== (opts.expectedSize ?? total ?? loaded))
+ throw new DownloadError('SIZE', 'Download size mismatch');
+ const sha256 = await hasher.digest();
+ if (sha256 !== opts.sha256) throw new DownloadError('CHECKSUM', 'Download SHA-256 mismatch');
+ await file.close();
+ file = undefined;
+ checkAbort();
+ if (opts.existingTarget === 'error') {
+ // Atomic no-clobber publication, even if another process created the target meanwhile.
+ await fs.promises.link(partPath(opts.targetPath), opts.targetPath);
+ deletePart(opts.targetPath);
+ } else {
+ await fs.promises.rename(partPath(opts.targetPath), opts.targetPath);
+ }
+ complete = true;
+ deleteMeta(opts.targetPath);
+ tracker.flush();
+ return { size: loaded, sha256 };
+ } catch (error) {
+ const failure =
+ error instanceof DownloadError
+ ? error
+ : new DownloadError(
+ (error as NodeJS.ErrnoException).code === 'EEXIST' ? 'EXISTS' : 'DISK',
+ 'Download file operation failed',
+ );
+ if (['SIZE', 'CHECKSUM', 'URL_POLICY'].includes(failure.code)) discard = true;
+ throw failure;
+ } finally {
+ clearTimeout(timer);
+ signal?.removeEventListener('abort', abort);
+ if (!complete) controller.abort();
+ await reader?.cancel().catch(() => undefined);
+ reader?.releaseLock();
+ if (!reader) await response?.body?.cancel().catch(() => undefined);
+ await file?.close().catch(() => undefined);
+ if (!complete) {
+ if (discard) {
+ deletePart(opts.targetPath);
+ deleteMeta(opts.targetPath);
+ } else if (meta) {
+ try {
+ writeMeta(opts.targetPath, {
+ ...meta,
+ downloadedBytes: loaded,
+ updatedAt: new Date().toISOString(),
+ });
+ } catch {
+ /* A failed checkpoint only disables resume. */
}
- });
-
- response.on('end', () => {
- // close the stream and finalize
- writeStream.end(() => {
- (async () => {
- try {
- const finalHash = await hasher.digest();
- const finalSize = tracker.getLoaded();
-
- if (finalHash !== opts.sha256) {
- // Corrupt body — wipe both .part and .meta so a future attempt
- // starts truly fresh (CHECKSUM is not retried inside withRetry).
- deletePart(opts.targetPath);
- deleteMeta(opts.targetPath);
- safeReject(
- new DownloadError(
- 'CHECKSUM',
- `sha256 mismatch: got ${finalHash}, expected ${opts.sha256}`,
- ),
- );
- return;
- }
-
- // Good. Move .part into place and drop the sidecar.
- try {
- if (fs.existsSync(opts.targetPath)) fs.unlinkSync(opts.targetPath);
- fs.renameSync(partPath(opts.targetPath), opts.targetPath);
- } catch (err) {
- safeReject(
- new DownloadError(
- 'DISK',
- `rename .part failed: ${(err as Error).message}`,
- err as Error,
- ),
- );
- return;
- }
- deleteMeta(opts.targetPath);
- tracker.flush();
- safeResolve({ size: finalSize, sha256: finalHash });
- } catch (err) {
- safeReject(
- new DownloadError(
- 'DISK',
- `finalize failed: ${(err as Error).message}`,
- err as Error,
- ),
- );
- }
- })();
- });
- });
-
- response.on('error', (err: Error) => {
- try { writeStream.destroy(); } catch { /* ignore */ }
- safeReject(new DownloadError('NETWORK', `stream error: ${err.message}`, err));
- });
-
- // Net response sometimes emits 'aborted' on socket reset rather than 'error'.
- // Cast: Electron typings don't list 'aborted' but it's a real event.
- (response as unknown as { on(ev: string, cb: () => void): void }).on('aborted', () => {
- try { writeStream.destroy(); } catch { /* ignore */ }
- if (settled) return;
- safeReject(new DownloadError('NETWORK', 'response aborted mid-stream'));
- });
-
- // Kick off the idle timer once the response stream begins.
- resetIdleTimer();
- });
-
- request.on('error', (err: Error) => {
- safeReject(new DownloadError('NETWORK', `request error: ${err.message}`, err));
- });
-
- // Guard: an abort that sneaks in before request.end() finished.
- request.on('abort' as 'error', () => {
- if (settled) return;
- safeReject(new DownloadError('ABORTED', 'request aborted'));
- });
-
- request.end();
- });
+ }
+ }
+ }
}
diff --git a/apps/desktop/src/main/downloader/types.ts b/apps/desktop/src/main/downloader/types.ts
index 58974ca2ec..3d5bcbe078 100644
--- a/apps/desktop/src/main/downloader/types.ts
+++ b/apps/desktop/src/main/downloader/types.ts
@@ -17,6 +17,15 @@ export interface DownloadOptions {
sha256: string;
/** Optional. When provided, Content-Length must match for fresh downloads. */
expectedSize?: number;
+ /** Reject before writing beyond this limit (also enforced for cache/resume). */
+ maxBytes?: number;
+ /** Defaults to follow. A predicate is checked before every redirect request. */
+ redirect?: 'follow' | 'error';
+ isUrlAllowed?: (url: string) => boolean;
+ /** Defaults to true. False discards partial data after failure/cancellation. */
+ resume?: boolean;
+ /** Defaults to replace. Exclusive publication never overwrites an existing file. */
+ existingTarget?: 'replace' | 'error';
/** Raw progress events (no clamping / no smoothing — caller-side concern). */
onProgress?: (e: ProgressEvent) => void;
/** Fired before each backoff sleep. Use for logging/telemetry. */
@@ -80,6 +89,10 @@ export type DownloadErrorCode =
| 'HTTP_4XX'
| 'HTTP_5XX'
| 'CHECKSUM'
+ | 'SIZE'
+ | 'TIMEOUT'
+ | 'URL_POLICY'
+ | 'EXISTS'
| 'DISK'
| 'ABORTED'
| 'INVALID_ARG';
@@ -89,12 +102,7 @@ export class DownloadError extends Error {
public readonly cause?: Error;
public readonly httpStatus?: number;
- constructor(
- code: DownloadErrorCode,
- message: string,
- cause?: Error,
- httpStatus?: number,
- ) {
+ constructor(code: DownloadErrorCode, message: string, cause?: Error, httpStatus?: number) {
super(message);
this.name = 'DownloadError';
this.code = code;
@@ -119,6 +127,8 @@ export interface TimeoutConfig {
connectMs: number;
/** Default 30000 — max gap between data chunks before treating as dead. */
idleMs: number;
+ /** Optional total budget, including queue and retry waits. */
+ totalMs?: number;
}
export interface Logger {
diff --git a/apps/desktop/src/main/git-context/ghArtifact.ts b/apps/desktop/src/main/git-context/ghArtifact.ts
new file mode 100644
index 0000000000..11e11c78f2
--- /dev/null
+++ b/apps/desktop/src/main/git-context/ghArtifact.ts
@@ -0,0 +1,30 @@
+import type { ToolArtifact } from '../managed-tools/types.js';
+
+// Official cli/cli v2.101.0 release asset SHA-256 digests. Update version,
+// digests and archive layouts together; Renderer cannot select an executable.
+export const GH_VERSION = '2.101.0';
+const hashes: Record<string, string> = {
+ 'darwin-arm64': 'e4303e39d8f07141c4bad4b99b01079f05029c59b27076e8fbc825c985ecdd8b',
+ 'darwin-x64': 'a6fd66c88e2f07d6e4e058173db341d07dd74d58cf8f19ae668293d2bb614ca3',
+ 'linux-arm64': 'b57e8063f18862647c9d22727c32e9da1b963f8bf9db648fe123a6975695640f',
+ 'linux-x64': '9bca2d1c16825f109907a23307628a2f0698fbf99662b73a5cf0b020293072b8',
+ 'win32-arm64': 'e6cbb2d4afdad3e70f3d38b8d1ebaa3a0870a897cfc0e4cf569826710b96b4fd',
+ 'win32-x64': 'bc6c814367b193cd8e713611d61e36013c0ef843b8f516458fe3eda039192794',
+};
+export function ghArtifact(platform: string, arch: string): ToolArtifact | undefined {
+ const host = `${platform}-${arch}`;
+ const sha256 = hashes[host];
+ if (!sha256) return;
+ const os = platform === 'darwin' ? 'macOS' : platform === 'win32' ? 'windows' : 'linux';
+ const name = `gh_${GH_VERSION}_${os}_${arch === 'x64' ? 'amd64' : arch}`;
+ const format = platform === 'linux' ? 'tar.gz' : 'zip';
+ return {
+ id: 'gh',
+ version: GH_VERSION,
+ host,
+ sha256,
+ format,
+ url: `https://github.com/cli/cli/releases/download/v${GH_VERSION}/${name}.${format}`,
+ executable: platform === 'win32' ? 'bin/gh.exe' : `${name}/bin/gh`,
+ };
+}
diff --git a/apps/desktop/src/main/git-context/ghBinary.ts b/apps/desktop/src/main/git-context/ghBinary.ts
new file mode 100644
index 0000000000..dbba1eb3bc
--- /dev/null
+++ b/apps/desktop/src/main/git-context/ghBinary.ts
@@ -0,0 +1,41 @@
+import { existsSync } from 'node:fs';
+import { homedir } from 'node:os';
+import path from 'node:path';
+import { installedTool } from '../managed-tools/installer.js';
+import { ghArtifact } from './ghArtifact.js';
+
+let managedRoot: string | undefined;
+export function configureManagedGhRoot(root: string): void {
+ managedRoot = root;
+}
+
+export function systemGhBinary(
+ platform: string = process.platform,
+ exists: (candidate: string) => boolean = existsSync,
+ home = homedir(),
+): string {
+ const candidates: Record<string, string[]> = {
+ darwin: ['/opt/homebrew/bin/gh', '/usr/local/bin/gh', path.join(home, '.local/bin/gh')],
+ linux: [
+ '/usr/bin/gh',
+ '/usr/local/bin/gh',
+ '/home/linuxbrew/.linuxbrew/bin/gh',
+ path.join(home, '.local/bin/gh'),
+ ],
+ win32: [
+ 'C:\\Program Files\\GitHub CLI\\gh.exe',
+ 'C:\\Program Files (x86)\\GitHub CLI\\gh.exe',
+ path.join(home, '.local', 'bin', 'gh.exe'),
+ ],
+ };
+ return candidates[platform]?.find(exists) ?? (platform === 'win32' ? 'gh.exe' : 'gh');
+}
+
+export async function resolveGhBinary(): Promise<string> {
+ const artifact = ghArtifact(process.platform, process.arch);
+ if (managedRoot && artifact) {
+ const installed = await installedTool(managedRoot, artifact);
+ if (installed) return installed;
+ }
+ return systemGhBinary();
+}
diff --git a/apps/desktop/src/main/git-context/ghCliTokenSource.ts b/apps/desktop/src/main/git-context/ghCliTokenSource.ts
index afaa4bf4e3..95f2ae30fa 100644
--- a/apps/desktop/src/main/git-context/ghCliTokenSource.ts
+++ b/apps/desktop/src/main/git-context/ghCliTokenSource.ts
@@ -8,10 +8,9 @@
* 实现要点:
* - `gh auth token` 输出当前登录 token(通常 gho_ 前缀 OAuth token),
* 对 REST 只读查询(PR 状态)权限足够。
- * - GUI app(packaged Electron)的 PATH 不含 homebrew 等目录,先探测各平台
- * 常见绝对路径,找不到再退回裸 'gh' 走 PATH。
- * - 正缓存默认 5 min;**负缓存默认 30s**——UI 提示用户跑 gh auth login,
- * 登录完成后最迟 30s 内生效,不能让"未登录"被钉死 5 分钟(Codex review P2)。
+ * - 共享来源优先使用 Cindy 受管安装,其次系统目录及 ~/.local/bin,最后走 PATH。
+ * - 正缓存默认 5 min,负缓存默认 30s;内置登录完成时主动 invalidate,
+ * 并隔离登录前的在途读取,不需要重启或等待 TTL。
* 没有缓存的话每次徽标刷新都会 spawn 一次 gh。
* - 依赖注入(execFile / exists / platform / now),单测零子进程。
*/
@@ -20,22 +19,17 @@ import { execFile } from 'node:child_process';
import * as fs from 'node:fs';
import { createLogger } from '../logger.js';
+import { resolveGhBinary as resolveSharedGhBinary, systemGhBinary } from './ghBinary.js';
const log = createLogger('git-context/gh-cli');
-/** 各平台 gh 常见安装位置(按命中概率排序);都不存在则退回裸 'gh' 走 PATH。 */
-const GH_CANDIDATES: Record<string, string[]> = {
- darwin: ['/opt/homebrew/bin/gh', '/usr/local/bin/gh'],
- linux: ['/usr/bin/gh', '/usr/local/bin/gh', '/home/linuxbrew/.linuxbrew/bin/gh'],
- win32: ['C:\\Program Files\\GitHub CLI\\gh.exe', 'C:\\Program Files (x86)\\GitHub CLI\\gh.exe'],
-};
-
const DEFAULT_CACHE_TTL_MS = 5 * 60_000;
const DEFAULT_NEGATIVE_CACHE_TTL_MS = 30_000;
const GH_TIMEOUT_MS = 3_000;
const GH_PROBE_TIMEOUT_MS = 800;
export interface GhCliTokenSourceDeps {
+ resolveBinary?: () => Promise<string>;
execFileFn?: (
file: string,
args: string[],
@@ -64,6 +58,7 @@ export type GhCliTokenReadResult =
{ ok: true; token: string } | { ok: false; reason: GhCliTokenUnavailableReason };
export interface GhCliTokenSource {
+ invalidate(): void;
/** 返回本地 gh 登录 token;未安装 / 未登录 / 超时返回 null,永不抛错。 */
readToken(): Promise<string | null>;
/** 同 readToken,但保留拿不到 token 的原因(共享同一份缓存)。永不抛错。 */
@@ -95,31 +90,34 @@ export function createGhCliTokenSource(deps: GhCliTokenSourceDeps = {}): GhCliTo
let cached: { result: GhCliTokenReadResult; expiresAt: number } | null = null;
let inFlight: Promise<GhCliTokenReadResult> | null = null;
+ let generation = 0;
function resolveGhBinary(): string {
- for (const candidate of GH_CANDIDATES[platform] ?? []) {
- if (existsFn(candidate)) return candidate;
- }
- return platform === 'win32' ? 'gh.exe' : 'gh';
+ return systemGhBinary(platform, existsFn);
}
async function fetchToken(): Promise<GhCliTokenReadResult> {
- const bin = resolveGhBinary();
+ const bin = deps.resolveBinary ? await deps.resolveBinary() : resolveGhBinary();
return new Promise<GhCliTokenReadResult>((resolve) => {
try {
- execFileFn(bin, ['auth', 'token'], { timeout: GH_TIMEOUT_MS }, (err, stdout) => {
- if (err) {
- // 失败只 debug 级记录;原因分类留给 UI 决定引导动作。
- const reason = classifyExecError(err);
- log.debug('gh auth token unavailable', { bin, reason, err: String(err) });
- resolve({ ok: false, reason });
- return;
- }
- const token = stdout.trim();
- resolve(
- token.length > 0 ? { ok: true, token } : { ok: false, reason: 'gh-not-logged-in' },
- );
- });
+ execFileFn(
+ bin,
+ ['auth', 'token', '--hostname', 'github.com'],
+ { timeout: GH_TIMEOUT_MS },
+ (err, stdout) => {
+ if (err) {
+ // 失败只 debug 级记录;原因分类留给 UI 决定引导动作。
+ const reason = classifyExecError(err);
+ log.debug('gh auth token unavailable', { reason });
+ resolve({ ok: false, reason });
+ return;
+ }
+ const token = stdout.trim();
+ resolve(
+ token.length > 0 ? { ok: true, token } : { ok: false, reason: 'gh-not-logged-in' },
+ );
+ },
+ );
} catch (err) {
log.debug('gh spawn threw', { err: String(err) });
resolve({ ok: false, reason: 'gh-missing' });
@@ -130,19 +128,22 @@ export function createGhCliTokenSource(deps: GhCliTokenSourceDeps = {}): GhCliTo
async function readTokenDetailed(): Promise<GhCliTokenReadResult> {
if (cached && cached.expiresAt > now()) return cached.result;
if (inFlight) return inFlight;
+ const gen = generation;
inFlight = fetchToken()
.then((result) => {
- cached = { result, expiresAt: now() + (result.ok ? ttl : negativeTtl) };
+ if (gen === generation) {
+ cached = { result, expiresAt: now() + (result.ok ? ttl : negativeTtl) };
+ }
return result;
})
.finally(() => {
- inFlight = null;
+ if (gen === generation) inFlight = null;
});
return inFlight;
}
async function probeAvailability(): Promise<boolean> {
- const bin = resolveGhBinary();
+ const bin = deps.resolveBinary ? await deps.resolveBinary() : resolveGhBinary();
return new Promise<boolean>((resolve) => {
try {
// stdout/stderr 都不进入日志;该调用只消费退出码,绝不取得 token。
@@ -159,6 +160,11 @@ export function createGhCliTokenSource(deps: GhCliTokenSourceDeps = {}): GhCliTo
}
return {
+ invalidate() {
+ generation += 1;
+ cached = null;
+ inFlight = null;
+ },
probeAvailability,
readTokenDetailed,
async readToken(): Promise<string | null> {
@@ -175,6 +181,7 @@ let sharedSource: GhCliTokenSource | null = null;
* 缓存互不可见 —— 同一段时间会重复 spawn `gh`,负缓存也各算一套。
*/
export function getSharedGhCliTokenSource(): GhCliTokenSource {
- if (!sharedSource) sharedSource = createGhCliTokenSource();
+ if (!sharedSource)
+ sharedSource = createGhCliTokenSource({ resolveBinary: resolveSharedGhBinary });
return sharedSource;
}
diff --git a/apps/desktop/src/main/git-context/githubConnection.ts b/apps/desktop/src/main/git-context/githubConnection.ts
new file mode 100644
index 0000000000..9237f08700
--- /dev/null
+++ b/apps/desktop/src/main/git-context/githubConnection.ts
@@ -0,0 +1,37 @@
+import type { GithubConnectionState } from '../../shared/githubSetup.js';
+
+/** Verify the effective credential without returning credentials or remote error bodies. */
+export async function githubConnection(deps: {
+ readGh(): Promise<string | null>;
+ readFallback(): string | null;
+ fetch: typeof fetch;
+}): Promise<GithubConnectionState> {
+ let source: 'gh-cli' | 'token' = 'gh-cli';
+ try {
+ let token = await deps.readGh();
+ if (!token) {
+ source = 'token';
+ token = deps.readFallback();
+ }
+ if (!token) return { status: 'missing' };
+ const response = await deps.fetch('https://api.github.com/user', {
+ headers: { Authorization: `Bearer ${token}`, Accept: 'application/vnd.github+json' },
+ redirect: 'error',
+ signal: AbortSignal.timeout(15_000),
+ });
+ if (!response.ok) {
+ await response.body?.cancel();
+ return {
+ status:
+ response.status === 401 ? 'auth' : response.status === 403 ? 'forbidden' : 'network',
+ source,
+ };
+ }
+ const data = (await response.json()) as { login?: unknown };
+ return typeof data.login === 'string' && /^[a-zA-Z0-9-]{1,39}$/.test(data.login)
+ ? { status: 'connected', login: data.login, source }
+ : { status: 'network', source };
+ } catch {
+ return { status: 'network', source };
+ }
+}
diff --git a/apps/desktop/src/main/git-context/githubSetup.ts b/apps/desktop/src/main/git-context/githubSetup.ts
new file mode 100644
index 0000000000..545d673819
--- /dev/null
+++ b/apps/desktop/src/main/git-context/githubSetup.ts
@@ -0,0 +1,189 @@
+import { execFile, spawn } from 'node:child_process';
+import type { GithubSetupState } from '../../shared/githubSetup.js';
+import { installTool } from '../managed-tools/installer.js';
+import { ghArtifact, GH_VERSION } from './ghArtifact.js';
+import { resolveGhBinary } from './ghBinary.js';
+
+interface SetupDeps {
+ resolveBinary(): Promise<string>;
+ available(binary: string): Promise<boolean>;
+ authenticated(binary: string): Promise<boolean>;
+ install(signal: AbortSignal, update: (state: GithubSetupState) => void): Promise<string>;
+ login(
+ binary: string,
+ signal: AbortSignal,
+ update: (state: GithubSetupState) => void,
+ ): Promise<void>;
+ connected(): void;
+}
+
+/** One host-owned operation shared by all local windows. Closing a dialog does
+ * not lose the device code or stop an installation. Cancellation waits for the
+ * child to exit before another operation may start. */
+export class GithubSetup {
+ private state: GithubSetupState = { phase: 'idle' };
+ private controller?: AbortController;
+ constructor(private readonly deps: SetupDeps) {}
+ snapshot(): GithubSetupState {
+ return { ...this.state };
+ }
+ start(): GithubSetupState {
+ if (this.controller) return this.snapshot();
+ const controller = new AbortController();
+ this.controller = controller;
+ this.state = { phase: 'checking' };
+ void this.run(controller).finally(() => {
+ this.controller = undefined;
+ });
+ return this.snapshot();
+ }
+ cancel(): GithubSetupState {
+ this.controller?.abort();
+ return this.snapshot();
+ }
+ private async run(controller: AbortController): Promise<void> {
+ const { signal } = controller;
+ let stage: 'install' | 'login' = 'install';
+ const update = (state: GithubSetupState) => {
+ if (!signal.aborted) this.state = state;
+ };
+ try {
+ let binary = await this.deps.resolveBinary();
+ if (!(await this.deps.available(binary))) {
+ signal.throwIfAborted();
+ binary = await this.deps.install(signal, update);
+ }
+ signal.throwIfAborted();
+ stage = 'login';
+ this.state = { phase: 'checking' };
+ if (!(await this.deps.authenticated(binary))) {
+ signal.throwIfAborted();
+ this.state = { phase: 'authorizing' };
+ await this.deps.login(binary, signal, update);
+ signal.throwIfAborted();
+ this.state = { phase: 'checking' };
+ if (!(await this.deps.authenticated(binary))) throw new Error('login');
+ }
+ signal.throwIfAborted();
+ this.deps.connected();
+ this.state = { phase: 'connected' };
+ } catch (error) {
+ const code = error instanceof Error ? error.message : '';
+ this.state = signal.aborted
+ ? { phase: 'cancelled' }
+ : {
+ phase: 'error',
+ error: code === 'unsupported' || code === 'timeout' ? code : stage,
+ };
+ }
+ }
+}
+
+function check(binary: string, args: string[], expected?: string): Promise<boolean> {
+ return new Promise((resolve) => {
+ execFile(binary, args, { timeout: 15_000, windowsHide: true }, (err, stdout) => {
+ resolve(!err && (!expected || stdout.startsWith(`gh version ${expected} `)));
+ });
+ });
+}
+
+/** Parse only the documented device-code line. Never forward raw CLI output. */
+export function deviceCodeFromOutput(output: string): string | undefined {
+ return /(?:one-time code:\s*|One-time code \()([A-Z0-9]{4}-[A-Z0-9]{4})(?=[\s)]|$)/.exec(
+ output,
+ )?.[1];
+}
+
+export function loginWithGh(
+ binary: string,
+ signal: AbortSignal,
+ update: (state: GithubSetupState) => void,
+): Promise<void> {
+ signal.throwIfAborted();
+ return new Promise((resolve, reject) => {
+ // Pipes make gh noninteractive: it prints the code and URL and polls GitHub,
+ // without opening a browser or prompting for Enter/SSH/git configuration.
+ const child = spawn(
+ binary,
+ // gh's repo/read:org/gist defaults plus everyday workflow, project,
+ // notification and package operations. Approval stays on GitHub's page.
+ [
+ 'auth',
+ 'login',
+ '--hostname',
+ 'github.com',
+ '--web',
+ '--git-protocol',
+ 'https',
+ '--scopes',
+ 'workflow,project,notifications,read:packages,write:packages',
+ ],
+ {
+ stdio: ['ignore', 'pipe', 'pipe'],
+ windowsHide: true,
+ env: { ...process.env, NO_COLOR: '1', GH_PROMPT_DISABLED: '1' },
+ },
+ );
+ let output = '';
+ let timedOut = false;
+ const read = (chunk: Buffer) => {
+ output = (output + chunk.toString('utf8')).slice(-8192);
+ const userCode = deviceCodeFromOutput(output);
+ if (userCode)
+ update({
+ phase: 'authorizing',
+ userCode,
+ verificationUrl: 'https://github.com/login/device',
+ });
+ };
+ child.stderr.on('data', read);
+ // Drain stdout too, but do not store or expose it (may contain sensitive data).
+ child.stdout.resume();
+ const stop = () => {
+ child.kill();
+ };
+ signal.addEventListener('abort', stop, { once: true });
+ const timeout = setTimeout(() => {
+ timedOut = true;
+ stop();
+ }, 15 * 60_000);
+ const clean = () => {
+ clearTimeout(timeout);
+ signal.removeEventListener('abort', stop);
+ output = '';
+ };
+ child.once('error', () => {
+ clean();
+ reject(new Error('login'));
+ });
+ child.once('close', (code) => {
+ clean();
+ if (signal.aborted || timedOut || code !== 0)
+ reject(new Error(timedOut ? 'timeout' : 'login'));
+ else resolve();
+ });
+ if (signal.aborted) stop();
+ });
+}
+
+export function createGithubSetup(root: string, connected: () => void): GithubSetup {
+ return new GithubSetup({
+ resolveBinary: resolveGhBinary,
+ available: (binary) => check(binary, ['--version']),
+ authenticated: (binary) => check(binary, ['auth', 'status', '--hostname', 'github.com']),
+ login: loginWithGh,
+ connected,
+ async install(signal, update) {
+ const artifact = ghArtifact(process.platform, process.arch);
+ if (!artifact) throw new Error('unsupported');
+ return installTool({
+ root,
+ artifact,
+ signal,
+ onProgress: ({ status, progress }) =>
+ update({ phase: status, percent: progress?.percent ?? undefined }),
+ validate: (binary) => check(binary, ['--version'], GH_VERSION),
+ });
+ },
+ });
+}
diff --git a/apps/desktop/src/main/git-context/githubSetupIpc.ts b/apps/desktop/src/main/git-context/githubSetupIpc.ts
new file mode 100644
index 0000000000..67ffa3cfb5
--- /dev/null
+++ b/apps/desktop/src/main/git-context/githubSetupIpc.ts
@@ -0,0 +1,60 @@
+import path from 'node:path';
+import { app, BrowserWindow, ipcMain } from 'electron';
+import { assertTrustedAppRendererEvent } from '../security/trustedAppRenderer.js';
+import { throwIpcError } from '../utils/ipcValidate.js';
+import { configureManagedGhRoot } from './ghBinary.js';
+import { createGithubSetup } from './githubSetup.js';
+import { getSharedGhCliTokenSource } from './ghCliTokenSource.js';
+import { githubConnection } from './githubConnection.js';
+import { readGhostSecret } from '../secrets/providerSecretStore.js';
+import { outboundFetch } from '../maker-host/outbound-fetch.js';
+import { activeOwnerScopeKey } from '../appSessionState.js';
+import { getGhostSetupChangeBus } from '../cindy-brain/ghostSetupChangeBus.js';
+
+/** Local app UI only. These channels intentionally have no device-link grant:
+ * authorizing this machine's GitHub identity is not a shared-task capability. */
+export function registerGithubSetupIpc(invalidateStatuses: () => void): void {
+ const root = path.join(app.getPath('userData'), 'managed-tools');
+ configureManagedGhRoot(root);
+ const changed = () => {
+ getSharedGhCliTokenSource().invalidate();
+ invalidateStatuses();
+ for (const win of BrowserWindow.getAllWindows()) {
+ if (!win.isDestroyed()) win.webContents.send('git-context:github-connected');
+ }
+ };
+ const setup = createGithubSetup(root, changed);
+ const unsubscribe = getGhostSetupChangeBus().subscribe('cindy-github', (event) => {
+ if (event.source === 'secret') changed();
+ });
+ for (const [channel, handle] of [
+ [
+ 'git-context:github-setup:connection',
+ async () => {
+ const owner = activeOwnerScopeKey();
+ const source = getSharedGhCliTokenSource();
+ source.invalidate();
+ const result = await githubConnection({
+ readGh: () => source.readToken(),
+ readFallback: () =>
+ owner === activeOwnerScopeKey() ? readGhostSecret('cindy-github', 'github_pat') : null,
+ fetch: outboundFetch,
+ });
+ return owner === activeOwnerScopeKey() ? result : { status: 'missing' as const };
+ },
+ ],
+ ['git-context:github-setup:status', () => setup.snapshot()],
+ ['git-context:github-setup:start', () => setup.start()],
+ ['git-context:github-setup:cancel', () => setup.cancel()],
+ ] as const) {
+ ipcMain.handle(channel, (event, ...args: unknown[]) => {
+ assertTrustedAppRendererEvent(event);
+ if (args.length) throwIpcError('INVALID_PARAMS', 'No arguments expected');
+ return handle();
+ });
+ }
+ app.once('before-quit', () => {
+ unsubscribe();
+ setup.cancel();
+ });
+}
diff --git a/apps/desktop/src/main/git-context/ipc.ts b/apps/desktop/src/main/git-context/ipc.ts
index 30efb540d6..690c03be7b 100644
--- a/apps/desktop/src/main/git-context/ipc.ts
+++ b/apps/desktop/src/main/git-context/ipc.ts
@@ -15,7 +15,7 @@
*
* GitHub token 只用本地 gh CLI 登录态(`gh auth token`,零配置)——agent 干活
* 本来就靠 gh,凭证天然就有;拿不到时按原因降级 gh-missing / gh-not-logged-in,
- * 徽标点击引导 agent 安装或登录。不做 app 级 PAT 绑定(设计收敛,见 PR #94 讨论)。
+ * 徽标点击打开内置 gh 安装和设备码登录。不做 app 级 PAT 绑定。
*/
import { BrowserWindow, ipcMain } from 'electron';
@@ -28,6 +28,7 @@ import { sessions } from '../localDb/schema.js';
import { outboundFetch } from '../maker-host/outbound-fetch.js';
import { optionalNullableString, requireString, throwIpcError } from '../utils/ipcValidate';
import { getSharedGhCliTokenSource } from './ghCliTokenSource.js';
+import { registerGithubSetupIpc } from './githubSetupIpc.js';
import { GitContextService } from './GitContextService.js';
import {
findLiveLinkedWorktreeLive,
@@ -153,6 +154,7 @@ export function registerGitContextIpc(): void {
readToken: readGithubToken,
fetchPr: fetchPrRemote,
});
+ registerGithubSetupIpc(() => prStatusService?.invalidate());
setPrRefsChangedListener((sessionId) =>
broadcastToAllWindows(GIT_CONTEXT_PUSH.PR_REFS_CHANGED, { sessionId }),
);
diff --git a/apps/desktop/src/main/git-context/prStatusService.ts b/apps/desktop/src/main/git-context/prStatusService.ts
index 8d3aefbe19..fd4bcff897 100644
--- a/apps/desktop/src/main/git-context/prStatusService.ts
+++ b/apps/desktop/src/main/git-context/prStatusService.ts
@@ -127,6 +127,13 @@ export class PrStatusService {
private readonly now: () => number;
private readonly cache = new Map<string, CacheEntry>();
private readonly inFlight = new Map<string, Promise<PrStatusResult>>();
+ private generation = 0;
+
+ invalidate(): void {
+ this.generation += 1;
+ this.cache.clear();
+ this.inFlight.clear();
+ }
constructor(deps: PrStatusServiceDeps) {
this.deps = deps;
@@ -161,6 +168,7 @@ export class PrStatusService {
const inflight = this.inFlight.get(key);
if (inflight) return inflight;
+ const generation = this.generation;
const p = this.fetchOne(q)
.then((result) => {
// 只缓存确定性结果(ok / not-found)。其余失败都不缓存:
@@ -168,13 +176,13 @@ export class PrStatusService {
// 下一次查询应立即生效(token source 自带 30s 负缓存兜底);
// - fetch-failed:瞬时网络抖动 / 临时 5xx 不该把失败钉死满 TTL,
// 下次渲染触发查询时立即重试(review 反馈)。
- if (result.ok || result.reason === 'not-found') {
+ if (generation === this.generation && (result.ok || result.reason === 'not-found')) {
this.cache.set(key, { result, expiresAt: this.now() + this.ttlMs });
}
return result;
})
.finally(() => {
- this.inFlight.delete(key);
+ if (this.inFlight.get(key) === p) this.inFlight.delete(key);
});
this.inFlight.set(key, p);
return p;
@@ -215,8 +223,12 @@ export class PrStatusService {
};
} catch (err) {
const status = (err as { status?: unknown })?.status;
+ if (status === 401) return { ok: false, ...base, reason: 'gh-not-logged-in' };
if (status === 404) return { ok: false, ...base, reason: 'not-found' };
- log.warn('fetch pr status failed', { key: `${q.owner}/${q.repo}#${q.prNumber}`, err: String(err) });
+ log.warn('fetch pr status failed', {
+ key: `${q.owner}/${q.repo}#${q.prNumber}`,
+ err: String(err),
+ });
return { ok: false, ...base, reason: 'fetch-failed' };
}
}
diff --git a/apps/desktop/src/main/local-model-runtime/__tests__/ollamaDownload.test.ts b/apps/desktop/src/main/local-model-runtime/__tests__/ollamaDownload.test.ts
new file mode 100644
index 0000000000..3d1d236c94
--- /dev/null
+++ b/apps/desktop/src/main/local-model-runtime/__tests__/ollamaDownload.test.ts
@@ -0,0 +1,38 @@
+import { describe, expect, it, vi } from 'vitest';
+import path from 'node:path';
+import os from 'node:os';
+const mocks = vi.hoisted(() => ({ download: vi.fn(), cleanup: vi.fn() }));
+vi.mock('../../downloader/index.js', () => mocks);
+import { downloadOfficialAsset } from '../ollamaInstall';
+import { isAllowedOllamaDownloadUrl } from '../ollamaRelease';
+
+describe('Ollama shared download adapter', () => {
+ it('delegates official URL policy, byte limits, cancellation and progress', async () => {
+ const asset = {
+ version: '0.32.14',
+ url: 'https://github.com/ollama/ollama/releases/download/v0.32.14/ollama-darwin.tgz',
+ sha256: 'a'.repeat(64),
+ sizeBytes: 100,
+ assetName: 'ollama-darwin.tgz',
+ };
+ const signal = new AbortController().signal;
+ const progress = vi.fn();
+ const target = path.join(os.tmpdir(), 'no-actual-download');
+ mocks.download.mockImplementation(async (opts) => {
+ opts.onProgress({ loaded: 50, total: 100, speedBps: 10 });
+ });
+ await downloadOfficialAsset(asset, target, { signal, onProgress: progress });
+ expect(mocks.download).toHaveBeenCalledWith(
+ expect.objectContaining({
+ url: asset.url,
+ targetPath: target,
+ expectedSize: 100,
+ maxBytes: 100,
+ sha256: asset.sha256,
+ isUrlAllowed: isAllowedOllamaDownloadUrl,
+ signal,
+ }),
+ );
+ expect(progress).toHaveBeenCalledWith(50, 100, 10);
+ });
+});
diff --git a/apps/desktop/src/main/local-model-runtime/ollamaInstall.ts b/apps/desktop/src/main/local-model-runtime/ollamaInstall.ts
index 1ef9c3ca82..180d510417 100644
--- a/apps/desktop/src/main/local-model-runtime/ollamaInstall.ts
+++ b/apps/desktop/src/main/local-model-runtime/ollamaInstall.ts
@@ -1,10 +1,9 @@
-import { createHash } from 'node:crypto';
-import { createWriteStream } from 'node:fs';
import { chmod, mkdir, readFile, rename, rm, writeFile } from 'node:fs/promises';
import { execFile } from 'node:child_process';
-import https from 'node:https';
import path from 'node:path';
+import { download as downloadFile, cleanup as cleanupDownload } from '../downloader/index.js';
+
import type { LocalRuntimeInstallProgress } from '../../shared/localModelRuntime.js';
import {
isAllowedOllamaDownloadUrl,
@@ -12,11 +11,9 @@ import {
pickOfficialSidecarAsset,
type OfficialOllamaAsset,
} from './ollamaRelease.js';
-import { createPullSpeedTracker } from './pullProgress.js';
import { findOllamaBinary, ollamaRuntimeRoot, sidecarManifestPath } from './ollamaSidecar.js';
const TAR_BIN_DARWIN = '/usr/bin/tar';
-const MAX_REDIRECTS = 5;
const EXTRACT_TIMEOUT_MS = 60_000;
const WINDOWS_EXTRACT_TIMEOUT_MS = 15 * 60_000;
@@ -33,7 +30,9 @@ export interface SidecarManifest {
export async function readSidecarManifest(userDataDir: string): Promise<SidecarManifest | null> {
try {
- const raw = JSON.parse(await readFile(sidecarManifestPath(userDataDir), 'utf8')) as SidecarManifest;
+ const raw = JSON.parse(
+ await readFile(sidecarManifestPath(userDataDir), 'utf8'),
+ ) as SidecarManifest;
if (
typeof raw.version !== 'string' ||
typeof raw.binary !== 'string' ||
@@ -82,74 +81,20 @@ export async function downloadOfficialAsset(
destPath: string,
opts: {
signal?: AbortSignal;
- onProgress?: (completed: number, total: number) => void;
- get?: typeof https.get;
+ onProgress?: (completed: number, total: number, speedBps?: number) => void;
} = {},
): Promise<void> {
- if (!isAllowedOllamaDownloadUrl(asset.url)) {
- throw new Error('blocked unofficial ollama download url');
- }
- const get = opts.get ?? https.get;
- await mkdir(path.dirname(destPath), { recursive: true });
- const tmp = `${destPath}.tmp`;
- await rm(tmp, { force: true });
- const hash = createHash('sha256');
- let completed = 0;
-
- await new Promise<void>((resolve, reject) => {
- const follow = (url: string, hops: number) => {
- if (hops > MAX_REDIRECTS) {
- reject(new Error('too many redirects'));
- return;
- }
- if (!isAllowedOllamaDownloadUrl(url)) {
- reject(new Error('blocked unofficial ollama download url'));
- return;
- }
- const request = get(url, { headers: { 'User-Agent': 'Cindy-Desktop' } }, (response) => {
- const status = response.statusCode ?? 0;
- if (status >= 300 && status < 400 && response.headers.location) {
- response.resume();
- follow(new URL(response.headers.location, url).toString(), hops + 1);
- return;
- }
- if (status !== 200) {
- response.resume();
- reject(new Error(`ollama download failed (${status})`));
- return;
- }
- const total = Number(response.headers['content-length'] ?? asset.sizeBytes);
- const out = createWriteStream(tmp);
- const fail = (error: Error) => {
- response.destroy();
- out.destroy();
- reject(error);
- };
- opts.signal?.addEventListener('abort', () => fail(new Error('aborted')), { once: true });
- response.on('data', (chunk: Buffer) => {
- hash.update(chunk);
- completed += chunk.length;
- opts.onProgress?.(completed, total);
- });
- response.on('error', fail);
- out.on('error', fail);
- response.pipe(out);
- out.on('finish', () => resolve());
- });
- request.on('error', reject);
- opts.signal?.addEventListener('abort', () => request.destroy(new Error('aborted')), {
- once: true,
- });
- };
- follow(asset.url, 0);
+ await downloadFile({
+ url: asset.url,
+ targetPath: destPath,
+ sha256: asset.sha256,
+ expectedSize: asset.sizeBytes,
+ maxBytes: asset.sizeBytes,
+ isUrlAllowed: isAllowedOllamaDownloadUrl,
+ signal: opts.signal,
+ onProgress: ({ loaded, total, speedBps }) =>
+ opts.onProgress?.(loaded, total ?? asset.sizeBytes, speedBps),
});
-
- const digest = hash.digest('hex');
- if (digest !== asset.sha256) {
- await rm(tmp, { force: true });
- throw new Error('ollama download checksum mismatch');
- }
- await rename(tmp, destPath);
}
function runTar(
@@ -188,12 +133,7 @@ export async function extractOfficialArchive(
const args = isWindows
? ['-xf', archivePath, '-C', destDir]
: ['-xzf', archivePath, '-C', destDir];
- await runTar(
- tarBin,
- args,
- isWindows ? WINDOWS_EXTRACT_TIMEOUT_MS : EXTRACT_TIMEOUT_MS,
- signal,
- );
+ await runTar(tarBin, args, isWindows ? WINDOWS_EXTRACT_TIMEOUT_MS : EXTRACT_TIMEOUT_MS, signal);
if (signal?.aborted) throw new Error('aborted');
const binary = findOllamaBinary(destDir);
if (!binary) throw new Error('extracted ollama binary missing');
@@ -229,56 +169,53 @@ export async function installOfficialSidecar(
const archivePath = path.join(root, 'downloads', asset.assetName);
const destDir = path.join(root, `v${asset.version}`);
try {
- emit({
- phase: 'downloading',
- version: asset.version,
- total: asset.sizeBytes,
- completed: 0,
- percent: 0,
- done: false,
- });
- const download = opts.download ?? downloadOfficialAsset;
- const speed = createPullSpeedTracker();
- const layers = new Map<string, { completed: number; total: number }>();
- await download(asset, archivePath, {
- signal: opts.signal,
- onProgress: (completed, total) => {
- layers.set('sidecar', { completed, total });
- const bytesPerSecond = speed.update(layers);
- emit({
- phase: 'downloading',
- version: asset.version,
- completed,
- total,
- percent: total > 0 ? Math.min(100, Math.round((completed / total) * 100)) : 0,
- ...(bytesPerSecond && bytesPerSecond > 0 ? { bytesPerSecond } : {}),
- done: false,
- });
- },
- });
- emit({ phase: 'verifying', version: asset.version, percent: 100, done: false });
- if (opts.signal?.aborted) throw new Error('aborted');
- emit({ phase: 'extracting', version: asset.version, done: false });
- const extract = opts.extract ?? extractOfficialArchive;
- const binary = await extract(archivePath, destDir, platform, opts.signal);
- if (opts.signal?.aborted) throw new Error('aborted');
- const manifest: SidecarManifest = {
- version: asset.version,
- binary,
- sha256: asset.sha256,
- };
- const manifestPath = sidecarManifestPath(userDataDir);
- await mkdir(path.dirname(manifestPath), { recursive: true });
- await writeFile(`${manifestPath}.tmp`, `${JSON.stringify(manifest)}\n`, 'utf8');
- await rename(`${manifestPath}.tmp`, manifestPath);
- await rm(archivePath, { force: true });
- return { version: asset.version, binary };
-} catch (error) {
- await rm(`${archivePath}.tmp`, { force: true });
- await rm(archivePath, { force: true });
- await rm(destDir, { recursive: true, force: true });
- throw error;
-}
+ emit({
+ phase: 'downloading',
+ version: asset.version,
+ total: asset.sizeBytes,
+ completed: 0,
+ percent: 0,
+ done: false,
+ });
+ const download = opts.download ?? downloadOfficialAsset;
+ await download(asset, archivePath, {
+ signal: opts.signal,
+ onProgress: (completed, total, bytesPerSecond) => {
+ emit({
+ phase: 'downloading',
+ version: asset.version,
+ completed,
+ total,
+ percent: total > 0 ? Math.min(100, Math.round((completed / total) * 100)) : 0,
+ ...(bytesPerSecond && bytesPerSecond > 0 ? { bytesPerSecond } : {}),
+ done: false,
+ });
+ },
+ });
+ emit({ phase: 'verifying', version: asset.version, percent: 100, done: false });
+ if (opts.signal?.aborted) throw new Error('aborted');
+ emit({ phase: 'extracting', version: asset.version, done: false });
+ const extract = opts.extract ?? extractOfficialArchive;
+ const binary = await extract(archivePath, destDir, platform, opts.signal);
+ if (opts.signal?.aborted) throw new Error('aborted');
+ const manifest: SidecarManifest = {
+ version: asset.version,
+ binary,
+ sha256: asset.sha256,
+ };
+ const manifestPath = sidecarManifestPath(userDataDir);
+ await mkdir(path.dirname(manifestPath), { recursive: true });
+ await writeFile(`${manifestPath}.tmp`, `${JSON.stringify(manifest)}\n`, 'utf8');
+ await rename(`${manifestPath}.tmp`, manifestPath);
+ await rm(archivePath, { force: true });
+ return { version: asset.version, binary };
+ } catch (error) {
+ await cleanupDownload(archivePath);
+ await rm(`${archivePath}.tmp`, { force: true });
+ await rm(archivePath, { force: true });
+ await rm(destDir, { recursive: true, force: true });
+ throw error;
+ }
}
export async function installOfficialDarwinSidecar(
diff --git a/apps/desktop/src/main/managed-tools/__tests__/installer.test.ts b/apps/desktop/src/main/managed-tools/__tests__/installer.test.ts
new file mode 100644
index 0000000000..f055586298
--- /dev/null
+++ b/apps/desktop/src/main/managed-tools/__tests__/installer.test.ts
@@ -0,0 +1,67 @@
+import { afterEach, describe, expect, it, vi } from 'vitest';
+import { mkdtemp, mkdir, readFile, readdir, rm, writeFile } from 'node:fs/promises';
+import path from 'node:path';
+import os from 'node:os';
+import JSZip from 'jszip';
+import { installTool, installedTool } from '../installer';
+import type { ToolArtifact } from '../types';
+vi.mock('../../logger.js', () => ({ createLogger: () => ({ warn: vi.fn() }) }));
+const roots: string[] = [];
+afterEach(async () => {
+ for (const root of roots.splice(0)) await rm(root, { recursive: true, force: true });
+});
+async function setup() {
+ const root = await mkdtemp(path.join(os.tmpdir(), 'cindy-managed-tools-'));
+ roots.push(root);
+ const artifact: ToolArtifact = {
+ id: 'gh',
+ version: '1.2.3',
+ host: 'darwin-arm64',
+ url: 'https://publisher.test/gh.zip',
+ sha256: 'a'.repeat(64),
+ format: 'zip',
+ executable: 'gh/bin/gh',
+ };
+ return {
+ root,
+ artifact,
+ signal: new AbortController().signal,
+ onProgress: vi.fn(),
+ validate: vi.fn(async () => true),
+ };
+}
+describe('shared tool installer', () => {
+ 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()
+ .file('gh/bin/gh', 'executable')
+ .generateAsync({ type: 'nodebuffer' });
+ const executable = await installTool(input, {
+ download: async (opts) => {
+ await writeFile(opts.targetPath, archive);
+ },
+ });
+ expect(path.isAbsolute(executable)).toBe(true);
+ expect(await installedTool(input.root, input.artifact)).toBe(executable);
+ expect(await readFile(executable, 'utf8')).toBe('executable');
+ expect(input.validate).toHaveBeenCalledOnce();
+ });
+ it.each(['../outside', '/absolute', 'a/b'])(
+ 'rejects unsafe tool identity %s before downloading',
+ async (id) => {
+ const input = await setup();
+ const download = vi.fn();
+ await expect(
+ installTool({ ...input, artifact: { ...input.artifact, id } }, { download }),
+ ).rejects.toThrow('identity');
+ expect(download).not.toHaveBeenCalled();
+ expect(await readdir(input.root)).toEqual([]);
+ },
+ );
+ it('rejects an executable outside the archive', async () => {
+ const input = await setup();
+ await expect(
+ installTool({ ...input, artifact: { ...input.artifact, executable: '../outside' } }),
+ ).rejects.toThrow('archive path');
+ });
+});
diff --git a/apps/desktop/src/main/managed-tools/archive.ts b/apps/desktop/src/main/managed-tools/archive.ts
new file mode 100644
index 0000000000..01c8ba71bb
--- /dev/null
+++ b/apps/desktop/src/main/managed-tools/archive.ts
@@ -0,0 +1,126 @@
+import { createReadStream, createWriteStream } from 'node:fs';
+import { copyFile, mkdir, readFile, stat } from 'node:fs/promises';
+import path from 'node:path';
+import { Transform } from 'node:stream';
+import { pipeline } from 'node:stream/promises';
+import JSZip from 'jszip';
+import * as tar from 'tar';
+import type { ToolArtifact } from './types.js';
+
+const MAX_ARCHIVE_BYTES = 160 * 1024 ** 2;
+const MAX_FILE_BYTES = 256 * 1024 ** 2;
+const MAX_EXPANDED_BYTES = 1024 ** 3;
+const MAX_ENTRIES = 30_000;
+
+/** Publisher paths are POSIX paths, independent of the host extracting the archive. */
+export function safeArchivePath(name: string): string {
+ const clean = name.replace(/^(\.\/)+/, '').replace(/\/$/, '');
+ if (
+ !clean ||
+ /[\\:\0]/.test(clean) ||
+ path.posix.isAbsolute(clean) ||
+ clean.split('/').some((part) => part === '..' || part === '.' || !part)
+ ) {
+ throw new Error('Unsafe tool archive path');
+ }
+ return clean;
+}
+
+export function safeArchiveLink(name: string, link: string, hard: boolean): void {
+ safeArchivePath(name);
+ if (!link || /[\\:\0]/.test(link) || path.posix.isAbsolute(link))
+ throw new Error('Unsafe tool archive link');
+ safeArchivePath(path.posix.join(hard ? '' : path.posix.dirname(name), link));
+}
+
+/** Extract only hash-verified publisher artifacts into a fresh, unreferenced directory.
+ * tar handles internal symlinks (Python/Node); ZIP symlinks are not needed by our catalog.
+ * Preflight tar entries before any write; bound ZIP expansion while streaming each file.
+ */
+export async function extractToolArchive(
+ archive: string,
+ destination: string,
+ artifact: Pick<ToolArtifact, 'format' | 'executable'>,
+ signal: AbortSignal,
+): Promise<void> {
+ signal.throwIfAborted();
+ if ((await stat(archive)).size > MAX_ARCHIVE_BYTES) throw new Error('Tool archive too large');
+ if (artifact.format === 'binary') {
+ await copyFile(archive, path.join(destination, artifact.executable));
+ } else if (artifact.format === 'zip') {
+ const zip = await JSZip.loadAsync(await readFile(archive));
+ const entries = Object.values(zip.files);
+ if (entries.length > MAX_ENTRIES) throw new Error('Too many tool archive entries');
+ let expanded = 0;
+ for (const entry of entries) {
+ signal.throwIfAborted();
+ const name = safeArchivePath(entry.name);
+ const original = (entry as typeof entry & { unsafeOriginalName?: string }).unsafeOriginalName;
+ if (original && safeArchivePath(original) !== name)
+ throw new Error('Unsafe tool archive path');
+ if (
+ typeof entry.unixPermissions === 'number' &&
+ (entry.unixPermissions & 0o170000) === 0o120000
+ )
+ throw new Error('Unsupported ZIP link');
+ const target = path.join(destination, ...name.split('/'));
+ if (entry.dir) {
+ await mkdir(target, { recursive: true });
+ continue;
+ }
+ await mkdir(path.dirname(target), { recursive: true });
+ let size = 0;
+ const limit = new Transform({
+ transform(chunk: Buffer, _encoding, callback) {
+ size += chunk.length;
+ expanded += chunk.length;
+ callback(
+ size > MAX_FILE_BYTES || expanded > MAX_EXPANDED_BYTES
+ ? new Error('Tool archive too large')
+ : null,
+ chunk,
+ );
+ },
+ });
+ await pipeline(
+ entry.nodeStream(),
+ limit,
+ createWriteStream(target, { flags: 'wx', mode: 0o644 }),
+ { signal },
+ );
+ }
+ } else {
+ let count = 0;
+ let expanded = 0;
+ let invalid: Error | undefined;
+ const listing = tar.t({
+ strict: true,
+ onReadEntry(entry) {
+ try {
+ // A harmless top-level './' directory is used by some tar publishers.
+ if (entry.type === 'Directory' && /^\.(\/)?$/.test(entry.path)) return;
+ safeArchivePath(entry.path);
+ if (!['File', 'Directory', 'SymbolicLink', 'Link'].includes(entry.type))
+ throw new Error('Unsupported tool archive entry');
+ if (entry.type === 'SymbolicLink' || entry.type === 'Link')
+ safeArchiveLink(entry.path, entry.linkpath ?? '', entry.type === 'Link');
+ expanded += entry.size;
+ if (++count > MAX_ENTRIES || entry.size > MAX_FILE_BYTES || expanded > MAX_EXPANDED_BYTES)
+ throw new Error('Tool archive too large');
+ } catch (error) {
+ invalid = error as Error;
+ }
+ },
+ });
+ await pipeline(createReadStream(archive), listing, { signal });
+ if (invalid) throw invalid;
+ const extracting = tar.x({
+ cwd: destination,
+ strict: true,
+ preservePaths: false,
+ noMtime: true,
+ });
+ await pipeline(createReadStream(archive), extracting, { signal });
+ }
+ signal.throwIfAborted();
+}
diff --git a/apps/desktop/src/main/managed-tools/installer.ts b/apps/desktop/src/main/managed-tools/installer.ts
new file mode 100644
index 0000000000..9719e6865a
--- /dev/null
+++ b/apps/desktop/src/main/managed-tools/installer.ts
@@ -0,0 +1,136 @@
+import { randomUUID } from 'node:crypto';
+import { chmod, mkdir, mkdtemp, readFile, rename, rm, stat, writeFile } from 'node:fs/promises';
+import path from 'node:path';
+import { download, type DownloadOptions } from '../downloader/index.js';
+import { createLogger } from '../logger.js';
+import type { ToolArtifact, ToolInstallProgress } from './types.js';
+import { extractToolArchive, safeArchivePath } from './archive.js';
+
+const log = createLogger('managed-tools');
+const key = (artifact: ToolArtifact) => {
+ for (const part of [artifact.id, artifact.version, artifact.host]) {
+ if (!/^[a-zA-Z0-9][a-zA-Z0-9._-]*$/.test(part)) throw new Error('Invalid tool identity');
+ }
+ if (!/^[a-f0-9]{64}$/.test(artifact.sha256)) throw new Error('Invalid tool digest');
+ safeArchivePath(artifact.executable);
+ return `${artifact.id}-${artifact.version}-${artifact.host}-${artifact.sha256.slice(0, 12)}`;
+};
+const recordPath = (root: string, artifact: ToolArtifact) =>
+ path.join(root, 'tools', key(artifact), 'current.json');
+
+/** A record references only a complete immutable generation, never an in-progress extraction. */
+export async function installedTool(
+ root: string,
+ artifact: ToolArtifact,
+): Promise<string | undefined> {
+ try {
+ const record = JSON.parse(await readFile(recordPath(root, artifact), 'utf8'));
+ if (
+ record.sha256 !== artifact.sha256 ||
+ typeof record.generation !== 'string' ||
+ !/^[a-f0-9-]{36}$/.test(record.generation)
+ )
+ return;
+ const executable = path.join(
+ root,
+ 'tools',
+ key(artifact),
+ record.generation,
+ ...artifact.executable.split('/'),
+ );
+ if ((await stat(executable)).isFile()) return executable;
+ } catch {
+ /* Missing/corrupt records are not installed tools. */
+ }
+}
+
+/** Installs to Cindy's private directory; never invokes a system installer or writes global config.
+ * Generations stay immutable so a failed repair cannot break an existing consumer. A concurrent
+ * instance may promote another valid generation; either result has the same pinned contents.
+ */
+export async function installTool(
+ input: {
+ root: string;
+ artifact: ToolArtifact;
+ signal: AbortSignal;
+ onProgress: (progress: ToolInstallProgress) => void;
+ validate: (executable: string) => Promise<boolean>;
+ },
+ deps: {
+ download?: (options: DownloadOptions) => Promise<unknown>;
+ extract?: typeof extractToolArchive;
+ } = {},
+): Promise<string> {
+ const { root, artifact, signal, onProgress } = input;
+ signal.throwIfAborted();
+ const parent = path.join(root, 'tools', key(artifact));
+ await mkdir(parent, { recursive: true });
+ const staging = await mkdtemp(path.join(parent, '.staging-'));
+ const payload = path.join(staging, 'payload');
+ const generation = randomUUID();
+ const target = path.join(parent, generation);
+ const recordTemp = path.join(parent, `${generation}.json.tmp`);
+ let promoted = false;
+ let lastProgressAt = 0;
+ try {
+ onProgress({ status: 'downloading' });
+ // Each attempt has its own writable archive. The downloader retries/resumes in this
+ // attempt without sharing mutable .part files with another Cindy process.
+ await (deps.download ?? download)({
+ url: artifact.url,
+ sha256: artifact.sha256,
+ targetPath: path.join(staging, 'archive'),
+ signal,
+ logger: log,
+ onProgress: ({ loaded, total, percent }) => {
+ const now = Date.now();
+ // A fast connection must not produce thousands of chat-store updates per second.
+ if (signal.aborted || (now - lastProgressAt < 150 && loaded !== total)) return;
+ lastProgressAt = now;
+ onProgress({
+ status: 'downloading',
+ progress: {
+ loaded,
+ total,
+ percent: percent === null ? null : Math.max(0, Math.min(100, percent)),
+ },
+ });
+ },
+ retry: { maxAttempts: 4 },
+ });
+ signal.throwIfAborted();
+ onProgress({ status: 'installing' });
+ await mkdir(payload);
+ await (deps.extract ?? extractToolArchive)(
+ path.join(staging, 'archive'),
+ payload,
+ artifact,
+ signal,
+ );
+ const executable = path.join(payload, ...artifact.executable.split('/'));
+ if (!(await stat(executable)).isFile()) throw new Error('Tool executable missing');
+ await chmod(executable, 0o755);
+ if (!(await input.validate(executable)))
+ throw new Error('Installed tool did not pass its version check');
+ signal.throwIfAborted();
+ await rename(payload, target);
+ await writeFile(recordTemp, JSON.stringify({ generation, sha256: artifact.sha256 }), {
+ flag: 'wx',
+ });
+ signal.throwIfAborted();
+ await rename(recordTemp, recordPath(root, artifact));
+ promoted = true;
+ return path.join(target, ...artifact.executable.split('/'));
+ } finally {
+ // Only paths created by this attempt are removed; previous generations are untouched.
+ for (const file of [staging, recordTemp, ...(!promoted ? [target] : [])]) {
+ try {
+ await rm(file, { recursive: true, force: true, maxRetries: 3, retryDelay: 100 });
+ } catch {
+ // Antivirus/file locks may briefly keep a temp file open on Windows. An unused
+ // staging folder is never a valid install and must not mask the real outcome.
+ log.warn('Tool staging cleanup deferred', { tool: artifact.id });
+ }
+ }
+ }
+}
diff --git a/apps/desktop/src/main/managed-tools/types.ts b/apps/desktop/src/main/managed-tools/types.ts
new file mode 100644
index 0000000000..e1e56436e8
--- /dev/null
+++ b/apps/desktop/src/main/managed-tools/types.ts
@@ -0,0 +1,17 @@
+import type { ProgressEvent } from '../downloader/index.js';
+
+/** Publisher metadata supplied by trusted host code, never by Renderer. */
+export interface ToolArtifact {
+ id: string;
+ version: string;
+ host: string;
+ url: string;
+ sha256: string;
+ format: 'binary' | 'zip' | 'tar.gz';
+ /** POSIX path relative to the publisher archive root. */
+ executable: string;
+}
+export interface ToolInstallProgress {
+ status: 'downloading' | 'installing';
+ progress?: Pick<ProgressEvent, 'loaded' | 'total' | 'percent'>;
+}
diff --git a/apps/desktop/src/main/plugin-market/__tests__/download.test.ts b/apps/desktop/src/main/plugin-market/__tests__/download.test.ts
index 25018cbd7a..12c7886fc2 100644
--- a/apps/desktop/src/main/plugin-market/__tests__/download.test.ts
+++ b/apps/desktop/src/main/plugin-market/__tests__/download.test.ts
@@ -7,7 +7,7 @@ import { afterEach, describe, expect, it, vi } from 'vitest';
import { PLUGIN_MEMBER_UPLOAD_MAX_ARCHIVE_BYTES } from '@cindy/plugin-protocol';
const fetchMock = vi.hoisted(() => vi.fn());
-vi.mock('electron', () => ({ net: { fetch: fetchMock } }));
+vi.mock('../../downloader/http', () => ({ requestResponse: fetchMock }));
import { downloadVerifiedPlugin } from '../download';
@@ -132,6 +132,7 @@ describe('downloadVerifiedPlugin', () => {
const result = expect(
downloadVerifiedPlugin('https://downloads.example.test/a', expected(Buffer.from('a')), file),
).rejects.toMatchObject({ code: 'GHOST_DOWNLOAD_TIMEOUT' });
+ await vi.waitFor(() => expect(fetchMock).toHaveBeenCalledOnce());
await vi.advanceTimersByTimeAsync(60_000);
await result;
expect(fs.existsSync(file)).toBe(false);
diff --git a/apps/desktop/src/main/plugin-market/download.ts b/apps/desktop/src/main/plugin-market/download.ts
index 4180be8e7e..d32c7afa09 100644
--- a/apps/desktop/src/main/plugin-market/download.ts
+++ b/apps/desktop/src/main/plugin-market/download.ts
@@ -1,104 +1,48 @@
-import crypto from 'node:crypto';
-import fs from 'node:fs';
-
-import { net } from 'electron';
import { PLUGIN_MEMBER_UPLOAD_MAX_ARCHIVE_BYTES } from '@cindy/plugin-protocol';
-
+import { download, DownloadError } from '../downloader/index.js';
import { createIpcError } from '../../shared/ipc-errors.js';
-const PLUGIN_DOWNLOAD_IDLE_TIMEOUT_MS = 60_000;
-const PLUGIN_DOWNLOAD_TOTAL_TIMEOUT_MS = 120_000;
-
-/** 下载并校验 `.cindy` 原始字节,写入调用方提供的临时路径。 */
+/** Plugin policy only; transport, timeouts, byte limits and hashing are shared. */
export async function downloadVerifiedPlugin(
url: string,
expected: { sizeBytes: number; sha256: string },
targetPath: string,
): Promise<void> {
- if (!Number.isSafeInteger(expected.sizeBytes) || expected.sizeBytes <= 0) {
- throw createIpcError('GHOST_FILE_INVALID', 'Plugin Release size is invalid');
+ if (
+ !Number.isSafeInteger(expected.sizeBytes) ||
+ expected.sizeBytes <= 0 ||
+ expected.sizeBytes > PLUGIN_MEMBER_UPLOAD_MAX_ARCHIVE_BYTES ||
+ !/^[a-f0-9]{64}$/i.test(expected.sha256)
+ ) {
+ throw createIpcError('GHOST_FILE_INVALID', 'Plugin Release size or SHA-256 is invalid');
}
- if (expected.sizeBytes > PLUGIN_MEMBER_UPLOAD_MAX_ARCHIVE_BYTES) {
- throw createIpcError('GHOST_FILE_INVALID', 'Plugin archive exceeds 128 MiB');
- }
- const controller = new AbortController();
- const totalTimer = setTimeout(() => controller.abort(), PLUGIN_DOWNLOAD_TOTAL_TIMEOUT_MS);
- let timer: ReturnType<typeof setTimeout> | undefined;
- const resetIdleTimer = () => {
- clearTimeout(timer);
- timer = setTimeout(() => controller.abort(), PLUGIN_DOWNLOAD_IDLE_TIMEOUT_MS);
- };
- const network = async <T>(operation: Promise<T>): Promise<T> => {
- try {
- return await operation;
- } catch {
- throw createIpcError(
- controller.signal.aborted ? 'GHOST_DOWNLOAD_TIMEOUT' : 'GHOST_DOWNLOAD_FAILED',
- controller.signal.aborted ? 'Plugin download timed out' : 'Plugin download failed',
- );
- }
- };
- resetIdleTimer();
- let reader: ReadableStreamDefaultReader<Uint8Array> | undefined;
- let file: fs.promises.FileHandle | undefined;
- let complete = false;
try {
- const response = await network(
- net.fetch(url, {
- method: 'GET',
- cache: 'no-store',
- redirect: 'error',
- signal: controller.signal,
- }),
- );
- if (!response.ok) {
- await response.body?.cancel().catch(() => undefined);
- throw createIpcError('GHOST_DOWNLOAD_FAILED', `Plugin download HTTP ${response.status}`);
- }
- if (!response.body)
- throw createIpcError('GHOST_DOWNLOAD_FAILED', 'Plugin response body is empty');
- const contentLength = response.headers.get('content-length');
- if (contentLength !== null && Number(contentLength) !== expected.sizeBytes) {
- await response.body.cancel().catch(() => undefined);
- throw createIpcError('GHOST_FILE_INVALID', 'Plugin 下载 Content-Length 与 Release 不一致');
- }
-
- reader = response.body.getReader();
- resetIdleTimer();
- file = await fs.promises.open(targetPath, 'wx', 0o600);
- const hash = crypto.createHash('sha256');
- let size = 0;
- while (true) {
- if (controller.signal.aborted)
+ await download({
+ url,
+ targetPath,
+ sha256: expected.sha256,
+ expectedSize: expected.sizeBytes,
+ maxBytes: PLUGIN_MEMBER_UPLOAD_MAX_ARCHIVE_BYTES,
+ redirect: 'error',
+ resume: false,
+ existingTarget: 'error',
+ retry: { maxAttempts: 1 },
+ timeout: { connectMs: 60_000, idleMs: 60_000, totalMs: 120_000 },
+ });
+ } catch (error) {
+ if (error instanceof DownloadError) {
+ if (error.code === 'EXISTS')
+ throw Object.assign(new Error('Download target already exists'), { code: 'EEXIST' });
+ if (error.code === 'TIMEOUT')
throw createIpcError('GHOST_DOWNLOAD_TIMEOUT', 'Plugin download timed out');
- const { done, value } = await network(reader.read());
- if (done) break;
- size += value.byteLength;
- if (size > expected.sizeBytes) {
- throw createIpcError('GHOST_FILE_INVALID', 'Plugin 下载字节数超过 Release 声明');
- }
- if (value.byteLength > 0) {
- resetIdleTimer();
- hash.update(value);
- await file.writeFile(value);
- }
- }
- if (controller.signal.aborted)
- throw createIpcError('GHOST_DOWNLOAD_TIMEOUT', 'Plugin download timed out');
- if (size !== expected.sizeBytes)
- throw createIpcError('GHOST_FILE_INVALID', 'Plugin 下载字节数与 Release 不一致');
- if (hash.digest('hex') !== expected.sha256)
- throw createIpcError('GHOST_FILE_INVALID', 'Plugin 下载 SHA-256 校验失败');
- await file.close();
- complete = true;
- } finally {
- clearTimeout(totalTimer);
- clearTimeout(timer);
- await reader?.cancel().catch(() => undefined);
- reader?.releaseLock();
- if (file && !complete) {
- await file.close().catch(() => undefined);
- await fs.promises.rm(targetPath, { force: true });
+ if (error.code === 'SIZE')
+ throw createIpcError(
+ 'GHOST_FILE_INVALID',
+ 'Plugin 下载字节数或 Content-Length 与 Release 不一致,可能超过声明大小',
+ );
+ if (error.code === 'CHECKSUM')
+ throw createIpcError('GHOST_FILE_INVALID', 'Plugin 下载 SHA-256 校验失败');
}
+ throw createIpcError('GHOST_DOWNLOAD_FAILED', 'Plugin download failed');
}
}
diff --git a/apps/desktop/src/main/skillhub/__tests__/installService.test.ts b/apps/desktop/src/main/skillhub/__tests__/installService.test.ts
index f71e322f87..24978c8e2d 100644
--- a/apps/desktop/src/main/skillhub/__tests__/installService.test.ts
+++ b/apps/desktop/src/main/skillhub/__tests__/installService.test.ts
@@ -1,3 +1,7 @@
+vi.mock('../../downloader/http', async () => {
+ const { net } = await import('electron');
+ return { requestResponse: (url: string, init: RequestInit) => net.fetch(url, init) };
+});
import crypto from 'node:crypto';
import fs from 'node:fs';
import os from 'node:os';
@@ -102,33 +106,15 @@ function sha256(buf: Uint8Array): string {
}
function mockDownload(zipBuf: Uint8Array) {
- return {
- ok: true,
- status: 200,
- headers: {
- get: (name: string) => name.toLowerCase() === 'content-length' ? String(zipBuf.byteLength) : null,
- },
- body: {
- getReader: () => {
- let done = false;
- return {
- read: async () => {
- if (done) return { done: true, value: undefined };
- done = true;
- return { done: false, value: zipBuf };
- },
- cancel: vi.fn(),
- };
- },
- },
- } as unknown as Response;
+ return new Response(Buffer.from(zipBuf), {
+ headers: { 'content-length': String(zipBuf.byteLength) },
+ });
}
function makeDirectoryLink(linkPath: string, targetPath: string) {
fs.mkdirSync(path.dirname(linkPath), { recursive: true });
- const linkTarget = process.platform === 'win32'
- ? targetPath
- : path.relative(path.dirname(linkPath), targetPath);
+ const linkTarget =
+ process.platform === 'win32' ? targetPath : path.relative(path.dirname(linkPath), targetPath);
fs.symlinkSync(linkTarget, linkPath, process.platform === 'win32' ? 'junction' : 'dir');
}
@@ -162,12 +148,17 @@ describe('skillhub/installService', () => {
vi.resetAllMocks();
removeTestRoot();
fs.mkdirSync(TEST_ROOT, { recursive: true });
- const { projectWorkingDirFromSkillPath } = await import('../../maker-host/shared-global-skills.js');
+ const { projectWorkingDirFromSkillPath } =
+ await import('../../maker-host/shared-global-skills.js');
vi.mocked(projectWorkingDirFromSkillPath).mockReturnValue(null);
const { getAppCapabilities } = await import('../../appCapabilities.js');
vi.mocked(getAppCapabilities).mockReturnValue({
- canUseCindyAccountServices: true, canUseCindyGateway: true, canUseDeviceLink: true,
- canUseSkillHubCloud: true, canUseCindyOAuthBroker: true, canUseCindyHeartbeat: true,
+ canUseCindyAccountServices: true,
+ canUseCindyGateway: true,
+ canUseDeviceLink: true,
+ canUseSkillHubCloud: true,
+ canUseCindyOAuthBroker: true,
+ canUseCindyHeartbeat: true,
});
});
@@ -203,22 +194,35 @@ describe('skillhub/installService', () => {
const { reconcileScannedInstall } = await import('../registryReconciliation');
const { uninstall } = await import('../installService');
const { shell } = await import('electron');
- const entry = { version: '1.0.0', catalogScope: 'market' } as import('../registry').StoredInstall;
+ const entry = {
+ version: '1.0.0',
+ catalogScope: 'market',
+ } as import('../registry').StoredInstall;
let entered!: () => void;
- const checking = new Promise<void>((resolve) => { entered = resolve; });
+ const checking = new Promise<void>((resolve) => {
+ entered = resolve;
+ });
let resume!: () => void;
- const waiting = new Promise<void>((resolve) => { resume = resolve; });
+ const waiting = new Promise<void>((resolve) => {
+ resume = resolve;
+ });
vi.mocked(registryService.getInstall).mockImplementationOnce(async () => {
entered();
await waiting;
return entry;
});
- const repair = reconcileScannedInstall({ skillName: 'scanner-race', installPath: source, entry }, false);
+ const repair = reconcileScannedInstall(
+ { skillName: 'scanner-race', installPath: source, entry },
+ false,
+ );
await checking;
try {
expect((await uninstall(source, target)).success).toBe(false);
expect(shell.trashItem).not.toHaveBeenCalled();
- } finally { resume(); await repair; }
+ } finally {
+ resume();
+ await repair;
+ }
const link = path.join(TEST_ROOT, '.claude', 'skills', 'scanner-race');
expect(fs.existsSync(link)).toBe(true);
expect(await uninstall(source, target)).toEqual({ success: true });
@@ -241,71 +245,86 @@ describe('skillhub/installService', () => {
expect(isCindySkillEnabled(source)).toBe(false);
});
- it.each(['ordinary', 'skill-shaped'])('removes only an external import link and leaves its source untouched (%s)', async (layout) => {
- const source = layout === 'ordinary' ? path.join(TEST_ROOT, 'external', 'shared')
- : path.join(TEST_ROOT, 'checkout', '.agents', 'skills', 'shared');
- const alias = path.join(TEST_ROOT, '.agents', 'skills', 'shared');
- fs.mkdirSync(source, { recursive: true });
- fs.writeFileSync(path.join(source, 'SKILL.md'), 'external content');
- makeDirectoryLink(alias, source);
- const { inspectLocalSkillTarget } = await import('../localSkillTarget');
- const { registryService } = await import('../registry');
- vi.mocked(registryService.getInstall).mockResolvedValue(null);
- vi.mocked(registryService.readManifest).mockResolvedValue(null);
- vi.mocked(registryService.listAllInstalls).mockResolvedValue([]);
- const { uninstall } = await import('../installService');
- const { shell } = await import('electron');
- const target = inspectLocalSkillTarget(source, [alias])!;
- expect(target.linkOnly).toBe(true);
- expect(await uninstall(source, target)).toEqual({ success: true });
- expect(shell.trashItem).toHaveBeenCalledWith(alias);
- expect(fs.existsSync(alias)).toBe(false);
- expect(fs.readFileSync(path.join(source, 'SKILL.md'), 'utf8')).toBe('external content');
- });
+ it.each(['ordinary', 'skill-shaped'])(
+ 'removes only an external import link and leaves its source untouched (%s)',
+ async (layout) => {
+ const source =
+ layout === 'ordinary'
+ ? path.join(TEST_ROOT, 'external', 'shared')
+ : path.join(TEST_ROOT, 'checkout', '.agents', 'skills', 'shared');
+ const alias = path.join(TEST_ROOT, '.agents', 'skills', 'shared');
+ fs.mkdirSync(source, { recursive: true });
+ fs.writeFileSync(path.join(source, 'SKILL.md'), 'external content');
+ makeDirectoryLink(alias, source);
+ const { inspectLocalSkillTarget } = await import('../localSkillTarget');
+ const { registryService } = await import('../registry');
+ vi.mocked(registryService.getInstall).mockResolvedValue(null);
+ vi.mocked(registryService.readManifest).mockResolvedValue(null);
+ vi.mocked(registryService.listAllInstalls).mockResolvedValue([]);
+ const { uninstall } = await import('../installService');
+ const { shell } = await import('electron');
+ const target = inspectLocalSkillTarget(source, [alias])!;
+ expect(target.linkOnly).toBe(true);
+ expect(await uninstall(source, target)).toEqual({ success: true });
+ expect(shell.trashItem).toHaveBeenCalledWith(alias);
+ expect(fs.existsSync(alias)).toBe(false);
+ expect(fs.readFileSync(path.join(source, 'SKILL.md'), 'utf8')).toBe('external content');
+ },
+ );
- it.each(['complete', 'retry'])('preserves shared disabled state after removing one external scope (%s)', async (outcome) => {
- const source = path.join(TEST_ROOT, 'external', 'shared');
- const alias = path.join(TEST_ROOT, '.agents', 'skills', 'global-import');
- const otherAlias = path.join(TEST_ROOT, 'project', '.agents', 'skills', 'project-import');
- fs.mkdirSync(source, { recursive: true });
- fs.writeFileSync(path.join(source, 'SKILL.md'), 'external content');
- for (const entry of [alias, otherAlias]) makeDirectoryLink(entry, source);
- const { inspectLocalSkillTarget } = await import('../localSkillTarget');
- const target = inspectLocalSkillTarget(source, [alias])!;
- const { registryService } = await import('../registry');
- vi.mocked(registryService.getInstall).mockResolvedValue(null);
- vi.mocked(registryService.readManifest).mockResolvedValue(null);
- vi.mocked(registryService.listAllInstalls).mockResolvedValue([]);
- const { setCindySkillEnabled, isCindySkillEnabled } = await import('../activationPreferences');
- await setCindySkillEnabled(source, false);
- const { shell } = await import('electron');
- let cleanupBlocked = false;
- vi.mocked(shell.trashItem).mockImplementationOnce(async (entry) => {
- await fs.promises.rename(entry, path.join(TEST_ROOT, 'removed-import'));
- cleanupBlocked = outcome === 'retry';
- });
- const { uninstall, retryUninstallCleanup } = await import('../installService');
- const result = await uninstall(source, target, () => !cleanupBlocked);
- expect(result).toMatchObject({ success: true });
- if (outcome === 'retry') {
- expect(result).toHaveProperty('cleanupToken');
- if (result.success && result.cleanupToken) {
- expect(await retryUninstallCleanup(result.cleanupToken, () => true)).toBe(true);
+ it.each(['complete', 'retry'])(
+ 'preserves shared disabled state after removing one external scope (%s)',
+ async (outcome) => {
+ const source = path.join(TEST_ROOT, 'external', 'shared');
+ const alias = path.join(TEST_ROOT, '.agents', 'skills', 'global-import');
+ const otherAlias = path.join(TEST_ROOT, 'project', '.agents', 'skills', 'project-import');
+ fs.mkdirSync(source, { recursive: true });
+ fs.writeFileSync(path.join(source, 'SKILL.md'), 'external content');
+ for (const entry of [alias, otherAlias]) makeDirectoryLink(entry, source);
+ const { inspectLocalSkillTarget } = await import('../localSkillTarget');
+ const target = inspectLocalSkillTarget(source, [alias])!;
+ const { registryService } = await import('../registry');
+ vi.mocked(registryService.getInstall).mockResolvedValue(null);
+ vi.mocked(registryService.readManifest).mockResolvedValue(null);
+ vi.mocked(registryService.listAllInstalls).mockResolvedValue([]);
+ const { setCindySkillEnabled, isCindySkillEnabled } =
+ await import('../activationPreferences');
+ await setCindySkillEnabled(source, false);
+ const { shell } = await import('electron');
+ let cleanupBlocked = false;
+ vi.mocked(shell.trashItem).mockImplementationOnce(async (entry) => {
+ await fs.promises.rename(entry, path.join(TEST_ROOT, 'removed-import'));
+ cleanupBlocked = outcome === 'retry';
+ });
+ const { uninstall, retryUninstallCleanup } = await import('../installService');
+ const result = await uninstall(source, target, () => !cleanupBlocked);
+ expect(result).toMatchObject({ success: true });
+ if (outcome === 'retry') {
+ expect(result).toHaveProperty('cleanupToken');
+ if (result.success && result.cleanupToken) {
+ expect(await retryUninstallCleanup(result.cleanupToken, () => true)).toBe(true);
+ }
}
- }
- expect(fs.lstatSync(alias, { throwIfNoEntry: false })).toBeUndefined();
- expect(fs.readFileSync(path.join(otherAlias, 'SKILL.md'), 'utf8')).toBe('external content');
- expect(isCindySkillEnabled(otherAlias)).toBe(false);
- });
+ expect(fs.lstatSync(alias, { throwIfNoEntry: false })).toBeUndefined();
+ expect(fs.readFileSync(path.join(otherAlias, 'SKILL.md'), 'utf8')).toBe('external content');
+ expect(isCindySkillEnabled(otherAlias)).toBe(false);
+ },
+ );
it('cleans cross-scope aliases after physical removal and preserves a retargeted link', async () => {
const { source } = await localFixture('foo');
const globalAlias = path.join(TEST_ROOT, 'home', '.agents', 'skills', 'global-alias');
const projectAlias = path.join(TEST_ROOT, 'project', '.agents', 'skills', 'project-alias');
const replacedAlias = path.join(TEST_ROOT, 'other', '.agents', 'skills', 'replaced-alias');
- for (const alias of [globalAlias, projectAlias, replacedAlias]) makeDirectoryLink(alias, source);
+ for (const alias of [globalAlias, projectAlias, replacedAlias])
+ makeDirectoryLink(alias, source);
const { inspectLocalSkillTarget } = await import('../localSkillTarget');
- const target = inspectLocalSkillTarget(source, [source, globalAlias, projectAlias, replacedAlias])!;
+ const target = inspectLocalSkillTarget(source, [
+ source,
+ globalAlias,
+ projectAlias,
+ replacedAlias,
+ ])!;
const otherSource = path.join(TEST_ROOT, 'unrelated');
fs.mkdirSync(otherSource);
fs.unlinkSync(replacedAlias);
@@ -340,9 +359,16 @@ describe('skillhub/installService', () => {
const { source, target } = await localFixture('cleanup-retry');
const { registryService } = await import('../registry');
vi.mocked(registryService.getInstall).mockResolvedValue({
- origin: 'imported', version: '1', authorId: '', folderHash: 'hash', installedAt: 1, updatedAt: 1,
+ origin: 'imported',
+ version: '1',
+ authorId: '',
+ folderHash: 'hash',
+ installedAt: 1,
+ updatedAt: 1,
});
- vi.mocked(registryService.removeInstall).mockRejectedValueOnce(new Error('disk unavailable')).mockResolvedValue(undefined);
+ vi.mocked(registryService.removeInstall)
+ .mockRejectedValueOnce(new Error('disk unavailable'))
+ .mockResolvedValue(undefined);
const { uninstall, retryUninstallCleanup } = await import('../installService');
const { shell } = await import('electron');
const result = await uninstall(source, target);
@@ -358,7 +384,12 @@ describe('skillhub/installService', () => {
const { source, target } = await localFixture('cleanup-restored');
const { registryService } = await import('../registry');
vi.mocked(registryService.getInstall).mockResolvedValue({
- origin: 'imported', version: '1', authorId: '', folderHash: 'hash', installedAt: 1, updatedAt: 1,
+ origin: 'imported',
+ version: '1',
+ authorId: '',
+ folderHash: 'hash',
+ installedAt: 1,
+ updatedAt: 1,
});
vi.mocked(registryService.removeInstall).mockRejectedValueOnce(new Error('disk unavailable'));
const { uninstall, retryUninstallCleanup } = await import('../installService');
@@ -375,7 +406,12 @@ describe('skillhub/installService', () => {
const { source, target } = await localFixture('cleanup-restarted');
const { registryService } = await import('../registry');
vi.mocked(registryService.getInstall).mockResolvedValue({
- origin: 'imported', version: '1', authorId: '', folderHash: 'hash', installedAt: 1, updatedAt: 1,
+ origin: 'imported',
+ version: '1',
+ authorId: '',
+ folderHash: 'hash',
+ installedAt: 1,
+ updatedAt: 1,
});
vi.mocked(registryService.removeInstall).mockRejectedValueOnce(new Error('disk unavailable'));
const { uninstall } = await import('../installService');
@@ -383,9 +419,12 @@ describe('skillhub/installService', () => {
const result = await uninstall(source, target);
if (!result.success || !result.cleanupToken) throw new Error('expected receipt');
vi.resetModules();
- const { retryUninstallCleanup, listPendingUninstallCleanups } = await import('../installService');
+ const { retryUninstallCleanup, listPendingUninstallCleanups } =
+ await import('../installService');
const { acquireSharedSkillMutationLease } = await import('../sharedMutationLease');
- expect(listPendingUninstallCleanups()).toEqual([{ token: result.cleanupToken, name: 'cleanup-restarted' }]);
+ expect(listPendingUninstallCleanups()).toEqual([
+ { token: result.cleanupToken, name: 'cleanup-restarted' },
+ ]);
expect(await acquireSharedSkillMutationLease(['cleanup-restarted'])).toBeNull();
expect(await retryUninstallCleanup(result.cleanupToken, () => true)).toBe(true);
expect(listPendingUninstallCleanups()).toEqual([]);
@@ -395,54 +434,62 @@ describe('skillhub/installService', () => {
expect(shell.trashItem).toHaveBeenCalledOnce();
});
- it.each(['retry-then-install', 'external-replacement'] as const)('finishes old imported aliases without losing the source (%s)', async (scenario) => {
- const source = path.join(TEST_ROOT, 'external', 'old-source');
- const alias = path.join(TEST_ROOT, '.agents', 'skills', 'reinstalled-alias');
- const compatibilityAlias = path.join(TEST_ROOT, '.claude', 'skills', 'different-alias');
- fs.mkdirSync(source, { recursive: true });
- fs.writeFileSync(path.join(source, 'SKILL.md'), 'old external skill');
- for (const entry of [alias, compatibilityAlias]) makeDirectoryLink(entry, source);
- const { inspectLocalSkillTarget } = await import('../localSkillTarget');
- const { registryService } = await import('../registry');
- vi.mocked(registryService.listAllInstalls).mockResolvedValue([]);
- const target = inspectLocalSkillTarget(source, [alias, compatibilityAlias])!;
- expect(target.linkOnly).toBe(true);
- const originalUnlink = fs.unlinkSync;
- const unlink = vi.spyOn(fs, 'unlinkSync').mockImplementation((entry) => {
- if (entry === compatibilityAlias) throw Object.assign(new Error('fixture link is busy'), { code: 'EPERM' });
- return originalUnlink(entry);
- });
- const { uninstall, install } = await import('../installService');
- const { shell } = await import('electron');
- let result: Awaited<ReturnType<typeof uninstall>>;
- try { result = await uninstall(source, target); }
- finally { unlink.mockRestore(); }
- if (!result.success || !result.cleanupToken) throw new Error('expected unfinished cleanup');
- vi.resetModules();
- const { acquireSharedSkillMutationLease } = await import('../sharedMutationLease');
- for (const name of ['old-source', 'reinstalled-alias', 'different-alias']) {
- expect(await acquireSharedSkillMutationLease([name])).toBeNull();
- }
- const unrelated = await acquireSharedSkillMutationLease(['unrelated-skill']);
- expect(unrelated).not.toBeNull();
- await unrelated!();
- const zip = await makeZip({ 'SKILL.md': 'new installed skill' });
- await setupInstallDownload('reinstalled-alias', zip);
- const params = { name: 'reinstalled-alias', installPath: alias, version: '1.0.0' };
- expect((await install(params, () => {})).success).toBe(false);
- if (scenario === 'external-replacement') {
- // External CLIs do not participate in Cindy's shared mutation protocol.
- fs.mkdirSync(alias);
- fs.writeFileSync(path.join(alias, 'SKILL.md'), 'new installed skill');
- }
- const { retryUninstallCleanup } = await import('../installService');
- expect(await retryUninstallCleanup(result.cleanupToken, () => true)).toBe(true);
- expect(fs.lstatSync(compatibilityAlias, { throwIfNoEntry: false })).toBeUndefined();
- if (scenario === 'retry-then-install') expect((await install(params, () => {})).success).toBe(true);
- expect(fs.readFileSync(path.join(alias, 'SKILL.md'), 'utf8')).toBe('new installed skill');
- expect(fs.readFileSync(path.join(source, 'SKILL.md'), 'utf8')).toBe('old external skill');
- expect(shell.trashItem).toHaveBeenCalledOnce();
- });
+ it.each(['retry-then-install', 'external-replacement'] as const)(
+ 'finishes old imported aliases without losing the source (%s)',
+ async (scenario) => {
+ const source = path.join(TEST_ROOT, 'external', 'old-source');
+ const alias = path.join(TEST_ROOT, '.agents', 'skills', 'reinstalled-alias');
+ const compatibilityAlias = path.join(TEST_ROOT, '.claude', 'skills', 'different-alias');
+ fs.mkdirSync(source, { recursive: true });
+ fs.writeFileSync(path.join(source, 'SKILL.md'), 'old external skill');
+ for (const entry of [alias, compatibilityAlias]) makeDirectoryLink(entry, source);
+ const { inspectLocalSkillTarget } = await import('../localSkillTarget');
+ const { registryService } = await import('../registry');
+ vi.mocked(registryService.listAllInstalls).mockResolvedValue([]);
+ const target = inspectLocalSkillTarget(source, [alias, compatibilityAlias])!;
+ expect(target.linkOnly).toBe(true);
+ const originalUnlink = fs.unlinkSync;
+ const unlink = vi.spyOn(fs, 'unlinkSync').mockImplementation((entry) => {
+ if (entry === compatibilityAlias)
+ throw Object.assign(new Error('fixture link is busy'), { code: 'EPERM' });
+ return originalUnlink(entry);
+ });
+ const { uninstall, install } = await import('../installService');
+ const { shell } = await import('electron');
+ let result: Awaited<ReturnType<typeof uninstall>>;
+ try {
+ result = await uninstall(source, target);
+ } finally {
+ unlink.mockRestore();
+ }
+ if (!result.success || !result.cleanupToken) throw new Error('expected unfinished cleanup');
+ vi.resetModules();
+ const { acquireSharedSkillMutationLease } = await import('../sharedMutationLease');
+ for (const name of ['old-source', 'reinstalled-alias', 'different-alias']) {
+ expect(await acquireSharedSkillMutationLease([name])).toBeNull();
+ }
+ const unrelated = await acquireSharedSkillMutationLease(['unrelated-skill']);
+ expect(unrelated).not.toBeNull();
+ await unrelated!();
+ const zip = await makeZip({ 'SKILL.md': 'new installed skill' });
+ await setupInstallDownload('reinstalled-alias', zip);
+ const params = { name: 'reinstalled-alias', installPath: alias, version: '1.0.0' };
+ expect((await install(params, () => {})).success).toBe(false);
+ if (scenario === 'external-replacement') {
+ // External CLIs do not participate in Cindy's shared mutation protocol.
+ fs.mkdirSync(alias);
+ fs.writeFileSync(path.join(alias, 'SKILL.md'), 'new installed skill');
+ }
+ const { retryUninstallCleanup } = await import('../installService');
+ expect(await retryUninstallCleanup(result.cleanupToken, () => true)).toBe(true);
+ expect(fs.lstatSync(compatibilityAlias, { throwIfNoEntry: false })).toBeUndefined();
+ if (scenario === 'retry-then-install')
+ expect((await install(params, () => {})).success).toBe(true);
+ expect(fs.readFileSync(path.join(alias, 'SKILL.md'), 'utf8')).toBe('new installed skill');
+ expect(fs.readFileSync(path.join(source, 'SKILL.md'), 'utf8')).toBe('old external skill');
+ expect(shell.trashItem).toHaveBeenCalledOnce();
+ },
+ );
it('preserves restored source links and newer disabled intent during delayed cleanup', async () => {
const { source } = await localFixture('restored-source');
@@ -459,8 +506,11 @@ describe('skillhub/installService', () => {
});
const { uninstall, retryUninstallCleanup } = await import('../installService');
let result: Awaited<ReturnType<typeof uninstall>>;
- try { result = await uninstall(source, target); }
- finally { unlink.mockRestore(); }
+ try {
+ result = await uninstall(source, target);
+ } finally {
+ unlink.mockRestore();
+ }
if (!result.success || !result.cleanupToken) throw new Error('expected receipt');
fs.mkdirSync(source);
fs.writeFileSync(path.join(source, 'SKILL.md'), 'restored source');
@@ -471,47 +521,67 @@ describe('skillhub/installService', () => {
expect(prefs.isCindySkillEnabled(source)).toBe(false);
});
- it.each(['before-trash', 'after-trash', 'barrier-release'] as const)('recovers interrupted persistence without replaying trash (%s)', async (failure) => {
- const { source, target } = await localFixture('persistence-failure');
- const { shell } = await import('electron');
- const journal = await import('../uninstallJournal');
- const realWrite = journal.writeUninstallCleanup;
- const write = vi.spyOn(journal, 'writeUninstallCleanup').mockImplementation((record) => {
- if (failure === 'before-trash' || (failure === 'after-trash' && record.phase !== 'prepared')) throw new Error('disk full');
- realWrite(record);
- });
- const originalUnlink = fs.unlinkSync;
- const unlink = vi.spyOn(fs, 'unlinkSync').mockImplementation((entry) => {
- if (failure === 'barrier-release' && String(entry).includes('shared-skill-mutation-locks') && String(entry).endsWith('.json')) {
- throw Object.assign(new Error('busy'), { code: 'EPERM' });
+ it.each(['before-trash', 'after-trash', 'barrier-release'] as const)(
+ 'recovers interrupted persistence without replaying trash (%s)',
+ async (failure) => {
+ const { source, target } = await localFixture('persistence-failure');
+ const { shell } = await import('electron');
+ const journal = await import('../uninstallJournal');
+ const realWrite = journal.writeUninstallCleanup;
+ const write = vi.spyOn(journal, 'writeUninstallCleanup').mockImplementation((record) => {
+ if (
+ failure === 'before-trash' ||
+ (failure === 'after-trash' && record.phase !== 'prepared')
+ )
+ throw new Error('disk full');
+ realWrite(record);
+ });
+ const originalUnlink = fs.unlinkSync;
+ const unlink = vi.spyOn(fs, 'unlinkSync').mockImplementation((entry) => {
+ if (
+ failure === 'barrier-release' &&
+ String(entry).includes('shared-skill-mutation-locks') &&
+ String(entry).endsWith('.json')
+ ) {
+ throw Object.assign(new Error('busy'), { code: 'EPERM' });
+ }
+ return originalUnlink(entry);
+ });
+ const { uninstall } = await import('../installService');
+ let result: Awaited<ReturnType<typeof uninstall>>;
+ try {
+ result = await uninstall(source, target);
+ } finally {
+ write.mockRestore();
+ unlink.mockRestore();
}
- return originalUnlink(entry);
- });
- const { uninstall } = await import('../installService');
- let result: Awaited<ReturnType<typeof uninstall>>;
- try { result = await uninstall(source, target); }
- finally { write.mockRestore(); unlink.mockRestore(); }
- if (failure === 'before-trash') {
- expect(result.success).toBe(false);
- expect(shell.trashItem).not.toHaveBeenCalled();
- expect(fs.existsSync(source)).toBe(true);
- return;
- }
- if (!result.success || !result.cleanupToken) throw new Error('expected durable receipt');
- vi.resetModules();
- const { retryUninstallCleanup } = await import('../installService');
- const { acquireSharedSkillMutationLease } = await import('../sharedMutationLease');
- expect(await acquireSharedSkillMutationLease(['persistence-failure'])).toBeNull();
- expect(await retryUninstallCleanup(result.cleanupToken, () => true)).toBe(true);
- expect(shell.trashItem).toHaveBeenCalledOnce();
- expect(fs.existsSync(source)).toBe(false);
- });
+ if (failure === 'before-trash') {
+ expect(result.success).toBe(false);
+ expect(shell.trashItem).not.toHaveBeenCalled();
+ expect(fs.existsSync(source)).toBe(true);
+ return;
+ }
+ if (!result.success || !result.cleanupToken) throw new Error('expected durable receipt');
+ vi.resetModules();
+ const { retryUninstallCleanup } = await import('../installService');
+ const { acquireSharedSkillMutationLease } = await import('../sharedMutationLease');
+ expect(await acquireSharedSkillMutationLease(['persistence-failure'])).toBeNull();
+ expect(await retryUninstallCleanup(result.cleanupToken, () => true)).toBe(true);
+ expect(shell.trashItem).toHaveBeenCalledOnce();
+ expect(fs.existsSync(source)).toBe(false);
+ },
+ );
it('retries only finalization after completed journal deletion fails', async () => {
const { source, target } = await localFixture('completed-receipt');
const { registryService } = await import('../registry');
vi.mocked(registryService.getInstall).mockResolvedValue({
- origin: 'imported', version: '1', authorId: '', folderHash: 'hash', installedAt: 1, updatedAt: 1,
+ origin: 'imported',
+ version: '1',
+ authorId: '',
+ folderHash: 'hash',
+ installedAt: 1,
+ updatedAt: 1,
});
const originalUnlink = fs.unlinkSync;
const unlink = vi.spyOn(fs, 'unlinkSync').mockImplementation((entry) => {
@@ -522,8 +592,11 @@ describe('skillhub/installService', () => {
});
const { uninstall, retryUninstallCleanup } = await import('../installService');
let result: Awaited<ReturnType<typeof uninstall>>;
- try { result = await uninstall(source, target); }
- finally { unlink.mockRestore(); }
+ try {
+ result = await uninstall(source, target);
+ } finally {
+ unlink.mockRestore();
+ }
if (!result.success || !result.cleanupToken) throw new Error('expected receipt');
const { readUninstallCleanup } = await import('../uninstallJournal');
expect(readUninstallCleanup(result.cleanupToken)?.phase).toBe('completed');
@@ -540,19 +613,29 @@ describe('skillhub/installService', () => {
const { source, target } = await localFixture('unreadable-source');
const { registryService } = await import('../registry');
vi.mocked(registryService.getInstall).mockResolvedValue({
- origin: 'imported', version: '1', authorId: '', folderHash: 'hash', installedAt: 1, updatedAt: 1,
+ origin: 'imported',
+ version: '1',
+ authorId: '',
+ folderHash: 'hash',
+ installedAt: 1,
+ updatedAt: 1,
});
vi.mocked(registryService.removeInstall).mockRejectedValueOnce(new Error('busy registry'));
- const { uninstall, retryUninstallCleanup, listPendingUninstallCleanups } = await import('../installService');
+ const { uninstall, retryUninstallCleanup, listPendingUninstallCleanups } =
+ await import('../installService');
const result = await uninstall(source, target);
if (!result.success || !result.cleanupToken) throw new Error('expected receipt');
const originalStat = fs.lstatSync;
const stat = vi.spyOn(fs, 'lstatSync').mockImplementation((...args) => {
- if (String(args[0]) === target.sourcePath) throw Object.assign(new Error('permission denied'), { code: 'EACCES' });
+ if (String(args[0]) === target.sourcePath)
+ throw Object.assign(new Error('permission denied'), { code: 'EACCES' });
return originalStat(...args);
});
- try { expect(await retryUninstallCleanup(result.cleanupToken, () => true)).toBe(false); }
- finally { stat.mockRestore(); }
+ try {
+ expect(await retryUninstallCleanup(result.cleanupToken, () => true)).toBe(false);
+ } finally {
+ stat.mockRestore();
+ }
expect(listPendingUninstallCleanups()).toHaveLength(1);
const { acquireSharedSkillMutationLease } = await import('../sharedMutationLease');
expect(await acquireSharedSkillMutationLease(['unreadable-source'])).toBeNull();
@@ -567,7 +650,8 @@ describe('skillhub/installService', () => {
await fs.promises.rename(entry, source + '-trash');
vi.mocked(getCurrentDataOwnerId).mockReturnValue('other-owner');
});
- const { uninstall, retryUninstallCleanup, listPendingUninstallCleanups } = await import('../installService');
+ const { uninstall, retryUninstallCleanup, listPendingUninstallCleanups } =
+ await import('../installService');
const result = await uninstall(source, target);
if (!result.success || !result.cleanupToken) throw new Error('expected durable receipt');
expect(listPendingUninstallCleanups()).toEqual([]);
@@ -582,30 +666,58 @@ describe('skillhub/installService', () => {
{ scope: undefined, origin: 'published', expectedOrigin: 'published' },
{ scope: 'market', origin: 'published', expectedOrigin: 'installed' },
{ scope: undefined, origin: 'installed', expectedOrigin: 'installed' },
- ] as const)('preserves publication provenance only when updating the same catalog ($scope/$origin)', async ({ scope, origin, expectedOrigin }) => {
- const name = 'google-play-console';
- const finalDir = path.join(TEST_ROOT, 'skills', name);
- fs.mkdirSync(finalDir, { recursive: true });
- fs.writeFileSync(path.join(finalDir, 'SKILL.md'), 'old content');
- const zipBuf = await makeZip({ 'SKILL.md': 'new content' });
- await setupInstallDownload(name, zipBuf);
- const { registryService } = await import('../registry');
- const { serverApiFetch } = await import('../../serverApiClient');
- const fetch = vi.mocked(serverApiFetch).getMockImplementation()!;
- vi.mocked(serverApiFetch).mockImplementation(async (url, options) => url.includes('/batch-detail')
- ? { items: [{ slug: name, owner: { slug: 'org-owner' }, isMine: true }] }
- : fetch(url, options));
- vi.mocked(registryService.getInstall).mockResolvedValue({
- version: '1.0.0', origin, authorId: 'org-owner', folderHash: 'old-hash', installedAt: 1, updatedAt: 1,
- });
- const { install } = await import('../installService');
- expect(await install({ name, installPath: finalDir, version: '1.0.1', catalogScope: scope, force: true, skipBackup: false }, () => {}))
- .toMatchObject({ success: true, version: '1.0.1' });
- expect(registryService.addInstall).toHaveBeenCalledWith(name, finalDir, expect.objectContaining({
- version: '1.0.1', origin: expectedOrigin, authorId: 'org-owner', ...(scope ? { catalogScope: scope } : {}),
- }));
- expect(fs.readFileSync(path.join(finalDir, 'SKILL.md'), 'utf8')).toBe('new content');
- });
+ ] as const)(
+ 'preserves publication provenance only when updating the same catalog ($scope/$origin)',
+ async ({ scope, origin, expectedOrigin }) => {
+ const name = 'google-play-console';
+ const finalDir = path.join(TEST_ROOT, 'skills', name);
+ fs.mkdirSync(finalDir, { recursive: true });
+ fs.writeFileSync(path.join(finalDir, 'SKILL.md'), 'old content');
+ const zipBuf = await makeZip({ 'SKILL.md': 'new content' });
+ await setupInstallDownload(name, zipBuf);
+ const { registryService } = await import('../registry');
+ const { serverApiFetch } = await import('../../serverApiClient');
+ const fetch = vi.mocked(serverApiFetch).getMockImplementation()!;
+ vi.mocked(serverApiFetch).mockImplementation(async (url, options) =>
+ url.includes('/batch-detail')
+ ? { items: [{ slug: name, owner: { slug: 'org-owner' }, isMine: true }] }
+ : fetch(url, options),
+ );
+ vi.mocked(registryService.getInstall).mockResolvedValue({
+ version: '1.0.0',
+ origin,
+ authorId: 'org-owner',
+ folderHash: 'old-hash',
+ installedAt: 1,
+ updatedAt: 1,
+ });
+ const { install } = await import('../installService');
+ expect(
+ await install(
+ {
+ name,
+ installPath: finalDir,
+ version: '1.0.1',
+ catalogScope: scope,
+ force: true,
+ skipBackup: false,
+ },
+ () => {},
+ ),
+ ).toMatchObject({ success: true, version: '1.0.1' });
+ expect(registryService.addInstall).toHaveBeenCalledWith(
+ name,
+ finalDir,
+ expect.objectContaining({
+ version: '1.0.1',
+ origin: expectedOrigin,
+ authorId: 'org-owner',
+ ...(scope ? { catalogScope: scope } : {}),
+ }),
+ );
+ expect(fs.readFileSync(path.join(finalDir, 'SKILL.md'), 'utf8')).toBe('new content');
+ },
+ );
it('keeps the previous install intact when extraction fails during forced update', async () => {
const finalDir = path.join(TEST_ROOT, 'skills', 'broken-skill');
@@ -718,7 +830,11 @@ describe('skillhub/installService', () => {
expect(registryService.removeInstall).toHaveBeenCalledWith(
'imported-offline',
expect.stringMatching(/[/\\]imported-offline$/),
- expect.objectContaining({ expected: expect.any(Object), canMutate: expect.any(Function), shouldRemove: expect.any(Function) }),
+ expect.objectContaining({
+ expected: expect.any(Object),
+ canMutate: expect.any(Function),
+ shouldRemove: expect.any(Function),
+ }),
);
} finally {
vi.mocked(getAppCapabilities).mockImplementation(() => ({
@@ -789,42 +905,53 @@ describe('skillhub/installService', () => {
}
});
- it.each(['success', 'registry-failure', 'owner-before-registry', 'owner-during-registry', 'preference-failure'])(
- 'preserves a missing installation’s disabled override until commit (%s)', async (outcome) => {
- const skillName = 'stale-disabled';
- const finalDir = path.join(fs.realpathSync.native(TEST_ROOT), 'skills', skillName);
- const zipBuf = await makeZip({ 'SKILL.md': 'new content' });
- await setupInstallDownload(skillName, zipBuf);
- const activation = await import('../activationPreferences');
- await activation.setCindySkillEnabled(finalDir, false);
- const { getCurrentDataOwnerId } = await import('../../authManager');
- vi.mocked(getCurrentDataOwnerId).mockReturnValue('owner-1');
- const { registryService } = await import('../registry');
- vi.mocked(registryService.addInstall).mockImplementation(async () => {
- if (outcome === 'registry-failure') throw new Error('registry unavailable');
- if (outcome === 'owner-during-registry') vi.mocked(getCurrentDataOwnerId).mockReturnValue('owner-2');
- });
- const reset = outcome === 'preference-failure'
- ? vi.spyOn(activation, 'setCindySkillEnabled').mockRejectedValueOnce(new Error('settings unavailable'))
+ it.each([
+ 'success',
+ 'registry-failure',
+ 'owner-before-registry',
+ 'owner-during-registry',
+ 'preference-failure',
+ ])('preserves a missing installation’s disabled override until commit (%s)', async (outcome) => {
+ const skillName = 'stale-disabled';
+ const finalDir = path.join(fs.realpathSync.native(TEST_ROOT), 'skills', skillName);
+ const zipBuf = await makeZip({ 'SKILL.md': 'new content' });
+ await setupInstallDownload(skillName, zipBuf);
+ const activation = await import('../activationPreferences');
+ await activation.setCindySkillEnabled(finalDir, false);
+ const { getCurrentDataOwnerId } = await import('../../authManager');
+ vi.mocked(getCurrentDataOwnerId).mockReturnValue('owner-1');
+ const { registryService } = await import('../registry');
+ vi.mocked(registryService.addInstall).mockImplementation(async () => {
+ if (outcome === 'registry-failure') throw new Error('registry unavailable');
+ if (outcome === 'owner-during-registry')
+ vi.mocked(getCurrentDataOwnerId).mockReturnValue('owner-2');
+ });
+ const reset =
+ outcome === 'preference-failure'
+ ? vi
+ .spyOn(activation, 'setCindySkillEnabled')
+ .mockRejectedValueOnce(new Error('settings unavailable'))
: undefined;
- try {
- const { install } = await import('../installService');
- const result = await install({ name: skillName, installPath: finalDir, version: '1.0.0' }, (progress) => {
+ try {
+ const { install } = await import('../installService');
+ const result = await install(
+ { name: skillName, installPath: finalDir, version: '1.0.0' },
+ (progress) => {
if (outcome === 'owner-before-registry' && progress.phase === 'registering') {
vi.mocked(getCurrentDataOwnerId).mockReturnValue('owner-2');
}
- });
- expect(result.success).toBe(outcome === 'success');
- expect(fs.existsSync(finalDir)).toBe(outcome === 'success');
- expect(activation.isCindySkillEnabled(finalDir)).toBe(outcome === 'success');
- if (outcome === 'owner-during-registry' || outcome === 'preference-failure') {
- expect(registryService.removeInstall).toHaveBeenCalledWith(skillName, finalDir);
- }
- } finally {
- reset?.mockRestore();
+ },
+ );
+ expect(result.success).toBe(outcome === 'success');
+ expect(fs.existsSync(finalDir)).toBe(outcome === 'success');
+ expect(activation.isCindySkillEnabled(finalDir)).toBe(outcome === 'success');
+ if (outcome === 'owner-during-registry' || outcome === 'preference-failure') {
+ expect(registryService.removeInstall).toHaveBeenCalledWith(skillName, finalDir);
}
- },
- );
+ } finally {
+ reset?.mockRestore();
+ }
+ });
it('removes a fresh install directory when registry registration fails', async () => {
const finalDir = path.join(TEST_ROOT, 'skills', 'registry-fail-skill');
@@ -847,7 +974,9 @@ describe('skillhub/installService', () => {
};
}
if (apiPath.includes('/batch-detail')) {
- return { items: [{ slug: 'registry-fail-skill', owner: { slug: 'owner' }, isMine: false }] };
+ return {
+ items: [{ slug: 'registry-fail-skill', owner: { slug: 'owner' }, isMine: false }],
+ };
}
throw new Error(`unexpected api path ${apiPath}`);
});
@@ -913,7 +1042,9 @@ describe('skillhub/installService', () => {
expect(result.success).toBe(false);
if (!result.success) expect(result.errorCode).toBe('WRITE_FAILED');
expect(fs.readFileSync(path.join(finalDir, 'SKILL.md'), 'utf-8')).toBe('old content');
- expect(fs.readdirSync(path.dirname(finalDir)).filter((name) => name.includes('.replacing.'))).toEqual([]);
+ expect(
+ fs.readdirSync(path.dirname(finalDir)).filter((name) => name.includes('.replacing.')),
+ ).toEqual([]);
});
it('restores the previous install when registry registration fails during backed-up update', async () => {
@@ -940,7 +1071,9 @@ describe('skillhub/installService', () => {
};
}
if (apiPath.includes('/batch-detail')) {
- return { items: [{ slug: 'backup-restore-skill', owner: { slug: 'owner' }, isMine: false }] };
+ return {
+ items: [{ slug: 'backup-restore-skill', owner: { slug: 'owner' }, isMine: false }],
+ };
}
throw new Error(`unexpected api path ${apiPath}`);
});
@@ -960,7 +1093,9 @@ describe('skillhub/installService', () => {
expect(result.success).toBe(false);
if (!result.success) expect(result.errorCode).toBe('WRITE_FAILED');
expect(fs.readFileSync(path.join(finalDir, 'SKILL.md'), 'utf-8')).toBe('old content');
- expect(fs.readdirSync(path.dirname(finalDir)).filter((name) => name.includes('.bak.'))).toEqual([]);
+ expect(fs.readdirSync(path.dirname(finalDir)).filter((name) => name.includes('.bak.'))).toEqual(
+ [],
+ );
});
it('moves persistent backups outside agent skill roots after a backed-up update succeeds', async () => {
@@ -987,7 +1122,9 @@ describe('skillhub/installService', () => {
};
}
if (apiPath.includes('/batch-detail')) {
- return { items: [{ slug: 'backup-success-skill', owner: { slug: 'owner' }, isMine: false }] };
+ return {
+ items: [{ slug: 'backup-success-skill', owner: { slug: 'owner' }, isMine: false }],
+ };
}
throw new Error(`unexpected api path ${apiPath}`);
});
@@ -1010,10 +1147,18 @@ describe('skillhub/installService', () => {
expect(skillRootEntries.filter((name) => name.includes('.bak.'))).toEqual([]);
expect(skillRootEntries.filter((name) => name.includes('.xdt-replacing-'))).toEqual([]);
- const backupRoot = path.join(TEST_ROOT, 'userData', 'skillhub', 'backups', 'backup-success-skill');
+ const backupRoot = path.join(
+ TEST_ROOT,
+ 'userData',
+ 'skillhub',
+ 'backups',
+ 'backup-success-skill',
+ );
const backups = fs.readdirSync(backupRoot);
expect(backups).toHaveLength(1);
- expect(fs.readFileSync(path.join(backupRoot, backups[0], 'SKILL.md'), 'utf-8')).toBe('old content');
+ expect(fs.readFileSync(path.join(backupRoot, backups[0], 'SKILL.md'), 'utf-8')).toBe(
+ 'old content',
+ );
});
it('prepares the Claude compatibility link after installing a project skill', async () => {
@@ -1419,8 +1564,14 @@ describe('skillhub/installService', () => {
const { inspectLocalSkillTarget } = await import('../localSkillTarget');
const { registryService } = await import('../registry');
const { uninstall } = await import('../installService');
- const entry = { version: '1.0.0', authorId: 'owner', folderHash: 'hash',
- installedAt: 1, updatedAt: 1, origin: 'installed' as const };
+ const entry = {
+ version: '1.0.0',
+ authorId: 'owner',
+ folderHash: 'hash',
+ installedAt: 1,
+ updatedAt: 1,
+ origin: 'installed' as const,
+ };
vi.mocked(registryService.getInstall).mockResolvedValue(entry);
vi.mocked(registryService.listAllInstalls).mockResolvedValue([
{ skillName: 'foo', installPath: globalAlias, entry },
@@ -1433,8 +1584,18 @@ describe('skillhub/installService', () => {
expect(fs.existsSync(projectAlias)).toBe(false);
expect(fs.existsSync(globalAlias)).toBe(true);
expect(fs.readFileSync(path.join(source, 'SKILL.md'), 'utf8')).toBe('fixture');
- expect(registryService.removeInstall).toHaveBeenCalledExactlyOnceWith('foo', projectAlias, expect.objectContaining({ expected: expect.any(Object), canMutate: expect.any(Function), shouldRemove: expect.any(Function) }));
- } finally { home.mockRestore(); }
+ expect(registryService.removeInstall).toHaveBeenCalledExactlyOnceWith(
+ 'foo',
+ projectAlias,
+ expect.objectContaining({
+ expected: expect.any(Object),
+ canMutate: expect.any(Function),
+ shouldRemove: expect.any(Function),
+ }),
+ );
+ } finally {
+ home.mockRestore();
+ }
});
it('refreshes the importing project when removing an external skill alias', async () => {
@@ -1451,7 +1612,9 @@ describe('skillhub/installService', () => {
vi.mocked(registryService.getInstall).mockResolvedValue(null);
vi.mocked(registryService.readManifest).mockResolvedValue(null);
vi.mocked(registryService.listAllInstalls).mockResolvedValue([]);
- vi.mocked(sharedSkills.projectWorkingDirFromSkillPath).mockImplementation((entry) => entry === alias ? projectRoot : null);
+ vi.mocked(sharedSkills.projectWorkingDirFromSkillPath).mockImplementation((entry) =>
+ entry === alias ? projectRoot : null,
+ );
const { uninstall } = await import('../installService');
const result = await uninstall(target.sourcePath, target);
expect(result).toEqual({ success: true, projectWorkingDir: projectRoot });
@@ -1530,8 +1693,14 @@ describe('skillhub/installService', () => {
fs.mkdirSync(physicalDir, { recursive: true });
fs.writeFileSync(path.join(physicalDir, 'SKILL.md'), 'fixture');
makeDirectoryLink(logicalDir, physicalDir);
- const entry = { version: '1.0.0', authorId: 'owner', folderHash: 'hash',
- installedAt: 1, updatedAt: 1, origin: 'installed' as const };
+ const entry = {
+ version: '1.0.0',
+ authorId: 'owner',
+ folderHash: 'hash',
+ installedAt: 1,
+ updatedAt: 1,
+ origin: 'installed' as const,
+ };
const { registryService } = await import('../registry');
const { uninstall } = await import('../installService');
vi.mocked(registryService.getInstall).mockImplementation(async (name) => {
@@ -1546,7 +1715,15 @@ describe('skillhub/installService', () => {
const result = await uninstall(physicalDir);
expect(result).toEqual({ success: true });
expect(fs.existsSync(physicalDir)).toBe(false);
- expect(registryService.removeInstall).toHaveBeenCalledWith('foo', logicalDir, expect.objectContaining({ expected: expect.any(Object), canMutate: expect.any(Function), shouldRemove: expect.any(Function) }));
+ expect(registryService.removeInstall).toHaveBeenCalledWith(
+ 'foo',
+ logicalDir,
+ expect.objectContaining({
+ expected: expect.any(Object),
+ canMutate: expect.any(Function),
+ shouldRemove: expect.any(Function),
+ }),
+ );
});
it('uninstalls a linked install when the scanner passes its physical path', async () => {
@@ -1570,7 +1747,9 @@ describe('skillhub/installService', () => {
const { registryService } = await import('../registry');
const { uninstall } = await import('../installService');
vi.mocked(getCurrentUserId).mockReturnValue('user-1');
- vi.mocked(registryService.getInstall).mockImplementation(async (_name, installPath) => installPath === logicalDir ? registryEntry : null);
+ vi.mocked(registryService.getInstall).mockImplementation(async (_name, installPath) =>
+ installPath === logicalDir ? registryEntry : null,
+ );
vi.mocked(registryService.readManifest).mockResolvedValue({
schemaVersion: 1,
skillName,
@@ -1582,7 +1761,15 @@ describe('skillhub/installService', () => {
expect(result.success).toBe(true);
expect(fs.existsSync(physicalDir)).toBe(false);
- expect(registryService.removeInstall).toHaveBeenCalledWith(skillName, logicalDir, expect.objectContaining({ expected: expect.any(Object), canMutate: expect.any(Function), shouldRemove: expect.any(Function) }));
+ expect(registryService.removeInstall).toHaveBeenCalledWith(
+ skillName,
+ logicalDir,
+ expect.objectContaining({
+ expected: expect.any(Object),
+ canMutate: expect.any(Function),
+ shouldRemove: expect.any(Function),
+ }),
+ );
});
it('clears a previous auto-sync ignore marker after a successful manual install', async () => {
@@ -1720,7 +1907,9 @@ describe('skillhub/installService', () => {
};
}
if (apiPath.includes('/batch-detail')) {
- return { items: [{ slug: 'auto-installed-skill', owner: { slug: 'owner' }, isMine: false }] };
+ return {
+ items: [{ slug: 'auto-installed-skill', owner: { slug: 'owner' }, isMine: false }],
+ };
}
throw new Error(`unexpected api path ${apiPath}`);
});
@@ -1753,9 +1942,7 @@ describe('skillhub/installService', () => {
prefPath,
JSON.stringify({
schemaVersion: 1,
- ignoredSkills: [
- { name: 'auto-installed-skill', userId: 'user-1', ignoredAt: 1 },
- ],
+ ignoredSkills: [{ name: 'auto-installed-skill', userId: 'user-1', ignoredAt: 1 }],
}),
'utf-8',
);
@@ -1779,7 +1966,9 @@ describe('skillhub/installService', () => {
};
}
if (apiPath.includes('/batch-detail')) {
- return { items: [{ slug: 'auto-installed-skill', owner: { slug: 'owner' }, isMine: false }] };
+ return {
+ items: [{ slug: 'auto-installed-skill', owner: { slug: 'owner' }, isMine: false }],
+ };
}
throw new Error(`unexpected api path ${apiPath}`);
});
@@ -1800,7 +1989,9 @@ describe('skillhub/installService', () => {
const stored = JSON.parse(fs.readFileSync(prefPath, 'utf-8')) as {
ignoredSkills: Array<{ name: string; userId: string }>;
};
- expect(stored.ignoredSkills).toMatchObject([{ name: 'auto-installed-skill', userId: 'user-1' }]);
+ expect(stored.ignoredSkills).toMatchObject([
+ { name: 'auto-installed-skill', userId: 'user-1' },
+ ]);
});
it('preserves auto-sync ownership when manually updating an auto-synced skill', async () => {
@@ -1861,26 +2052,36 @@ describe('skillhub/installService', () => {
);
});
- it.each([true, undefined])('persists offline auto-sync opt-out across restart (autoSynced=%s)', async (autoSynced) => {
- const { source, target } = await localFixture('offline-auto');
- const { getCurrentUserId } = await import('../../authManager');
- const { registryService } = await import('../registry');
- const { recordAutoSyncCandidateSkills } = await import('../autoSyncPreferences');
- await recordAutoSyncCandidateSkills('original-user', ['offline-auto']);
- vi.mocked(getCurrentUserId).mockReturnValue(null);
- vi.mocked(registryService.getInstall).mockResolvedValue({
- origin: 'installed', autoSynced, version: '1', authorId: '', folderHash: 'hash', installedAt: 1, updatedAt: 1,
- });
- const { uninstall } = await import('../installService');
- expect(await uninstall(source, target)).toEqual({ success: true });
- vi.resetModules();
- const { listIgnoredAutoSyncSkills, clearIgnoredAutoSyncSkill } = await import('../autoSyncPreferences');
- expect(await listIgnoredAutoSyncSkills('original-user')).toContain('offline-auto');
- expect(await listIgnoredAutoSyncSkills('another-user')).toContain('offline-auto');
- // Manual installation is the existing explicit reset of this device-level opt-out.
- await clearIgnoredAutoSyncSkill('offline-auto', 'original-user');
- expect(await listIgnoredAutoSyncSkills('original-user')).not.toContain('offline-auto');
- });
+ it.each([true, undefined])(
+ 'persists offline auto-sync opt-out across restart (autoSynced=%s)',
+ async (autoSynced) => {
+ const { source, target } = await localFixture('offline-auto');
+ const { getCurrentUserId } = await import('../../authManager');
+ const { registryService } = await import('../registry');
+ const { recordAutoSyncCandidateSkills } = await import('../autoSyncPreferences');
+ await recordAutoSyncCandidateSkills('original-user', ['offline-auto']);
+ vi.mocked(getCurrentUserId).mockReturnValue(null);
+ vi.mocked(registryService.getInstall).mockResolvedValue({
+ origin: 'installed',
+ autoSynced,
+ version: '1',
+ authorId: '',
+ folderHash: 'hash',
+ installedAt: 1,
+ updatedAt: 1,
+ });
+ const { uninstall } = await import('../installService');
+ expect(await uninstall(source, target)).toEqual({ success: true });
+ vi.resetModules();
+ const { listIgnoredAutoSyncSkills, clearIgnoredAutoSyncSkill } =
+ await import('../autoSyncPreferences');
+ expect(await listIgnoredAutoSyncSkills('original-user')).toContain('offline-auto');
+ expect(await listIgnoredAutoSyncSkills('another-user')).toContain('offline-auto');
+ // Manual installation is the existing explicit reset of this device-level opt-out.
+ await clearIgnoredAutoSyncSkill('offline-auto', 'original-user');
+ expect(await listIgnoredAutoSyncSkills('original-user')).not.toContain('offline-auto');
+ },
+ );
it('rolls back an offline opt-out when trash fails', async () => {
const { source, target } = await localFixture('offline-trash-failure');
@@ -1889,7 +2090,13 @@ describe('skillhub/installService', () => {
const { shell } = await import('electron');
vi.mocked(getCurrentUserId).mockReturnValue(null);
vi.mocked(registryService.getInstall).mockResolvedValue({
- origin: 'installed', autoSynced: true, version: '1', authorId: '', folderHash: 'hash', installedAt: 1, updatedAt: 1,
+ origin: 'installed',
+ autoSynced: true,
+ version: '1',
+ authorId: '',
+ folderHash: 'hash',
+ installedAt: 1,
+ updatedAt: 1,
});
vi.mocked(shell.trashItem).mockRejectedValueOnce(new Error('trash unavailable'));
const { uninstall } = await import('../installService');
@@ -1941,9 +2148,7 @@ describe('skillhub/installService', () => {
JSON.stringify({
schemaVersion: 1,
ignoredSkills: [],
- autoSyncCandidates: [
- { name: 'remote-auto-skill', userId: 'user-1', updatedAt: 1 },
- ],
+ autoSyncCandidates: [{ name: 'remote-auto-skill', userId: 'user-1', updatedAt: 1 }],
}),
'utf-8',
);
@@ -1995,11 +2200,13 @@ describe('skillhub/installService', () => {
const stored = JSON.parse(fs.readFileSync(prefPath, 'utf-8')) as {
autoSyncCandidates: Array<{ name: string; userId: string }>;
};
- expect(stored.autoSyncCandidates).toEqual(expect.arrayContaining([
- expect.objectContaining({ name: 'remote-auto-skill', userId: 'user-1' }),
- expect.objectContaining({ name: 'demo-oa-skill', userId: 'user-1' }),
- expect.objectContaining({ name: 'other-user-skill', userId: 'user-2' }),
- ]));
+ expect(stored.autoSyncCandidates).toEqual(
+ expect.arrayContaining([
+ expect.objectContaining({ name: 'remote-auto-skill', userId: 'user-1' }),
+ expect.objectContaining({ name: 'demo-oa-skill', userId: 'user-1' }),
+ expect.objectContaining({ name: 'other-user-skill', userId: 'user-2' }),
+ ]),
+ );
});
it('repairs a corrupt auto-sync preferences file when listing ignored skills', async () => {
@@ -2026,9 +2233,7 @@ describe('skillhub/installService', () => {
JSON.stringify({
schemaVersion: 1,
ignoredSkills: [],
- autoSyncCandidates: [
- { name: 'remote-auto-skill', userId: 'user-1', updatedAt: 1 },
- ],
+ autoSyncCandidates: [{ name: 'remote-auto-skill', userId: 'user-1', updatedAt: 1 }],
}),
'utf-8',
);
@@ -2040,10 +2245,12 @@ describe('skillhub/installService', () => {
const stored = JSON.parse(fs.readFileSync(prefPath, 'utf-8')) as {
autoSyncCandidates: Array<{ name: string; userId: string }>;
};
- expect(stored.autoSyncCandidates).toEqual(expect.arrayContaining([
- expect.objectContaining({ name: 'remote-auto-skill', userId: 'user-1' }),
- expect.objectContaining({ name: 'demo-oa-skill', userId: 'user-1' }),
- ]));
+ expect(stored.autoSyncCandidates).toEqual(
+ expect.arrayContaining([
+ expect.objectContaining({ name: 'remote-auto-skill', userId: 'user-1' }),
+ expect.objectContaining({ name: 'demo-oa-skill', userId: 'user-1' }),
+ ]),
+ );
});
it('does not record an auto-sync ignore marker when uninstalling a regular installed skill', async () => {
@@ -2110,9 +2317,7 @@ describe('skillhub/installService', () => {
prefPath,
JSON.stringify({
schemaVersion: 1,
- ignoredSkills: [
- { name: 'backup-fail-skill', userId: 'user-1', ignoredAt: 1 },
- ],
+ ignoredSkills: [{ name: 'backup-fail-skill', userId: 'user-1', ignoredAt: 1 }],
}),
'utf-8',
);
@@ -2152,13 +2357,15 @@ describe('skillhub/installService', () => {
vi.mocked(registryService.getInstall).mockResolvedValue(previousEntry);
vi.mocked(registryService.addInstall).mockResolvedValue(undefined);
const originalMkdir = fs.promises.mkdir.bind(fs.promises);
- const mkdirSpy = vi.spyOn(fs.promises, 'mkdir').mockImplementation(async (...args: Parameters<typeof fs.promises.mkdir>) => {
- const [target] = args;
- if (String(target).includes(`${path.sep}skillhub${path.sep}backups${path.sep}`)) {
- throw new Error('backup disk full');
- }
- return originalMkdir(...args);
- });
+ const mkdirSpy = vi
+ .spyOn(fs.promises, 'mkdir')
+ .mockImplementation(async (...args: Parameters<typeof fs.promises.mkdir>) => {
+ const [target] = args;
+ if (String(target).includes(`${path.sep}skillhub${path.sep}backups${path.sep}`)) {
+ throw new Error('backup disk full');
+ }
+ return originalMkdir(...args);
+ });
try {
const result = await install(
@@ -2174,8 +2381,14 @@ describe('skillhub/installService', () => {
expect(result.success).toBe(false);
if (!result.success) expect(result.errorCode).toBe('WRITE_FAILED');
expect(fs.readFileSync(path.join(finalDir, 'SKILL.md'), 'utf-8')).toBe('old content');
- expect(registryService.addInstall).toHaveBeenLastCalledWith('backup-fail-skill', finalDir, previousEntry);
- expect(fs.readdirSync(path.dirname(finalDir)).filter((name) => name.includes('.xdt-replacing-'))).toEqual([]);
+ expect(registryService.addInstall).toHaveBeenLastCalledWith(
+ 'backup-fail-skill',
+ finalDir,
+ previousEntry,
+ );
+ expect(
+ fs.readdirSync(path.dirname(finalDir)).filter((name) => name.includes('.xdt-replacing-')),
+ ).toEqual([]);
const stored = JSON.parse(fs.readFileSync(prefPath, 'utf-8')) as {
ignoredSkills: Array<{ name: string; userId: string }>;
};
@@ -2217,7 +2430,11 @@ describe('skillhub/installService', () => {
};
}
if (apiPath.includes('/batch-detail')) {
- return { items: [{ slug: 'backup-registry-restore-fail-skill', owner: { slug: 'owner' }, isMine: false }] };
+ return {
+ items: [
+ { slug: 'backup-registry-restore-fail-skill', owner: { slug: 'owner' }, isMine: false },
+ ],
+ };
}
throw new Error(`unexpected api path ${apiPath}`);
});
@@ -2228,13 +2445,15 @@ describe('skillhub/installService', () => {
.mockResolvedValueOnce(undefined)
.mockRejectedValueOnce(new Error('registry locked'));
const originalMkdir = fs.promises.mkdir.bind(fs.promises);
- const mkdirSpy = vi.spyOn(fs.promises, 'mkdir').mockImplementation(async (...args: Parameters<typeof fs.promises.mkdir>) => {
- const [target] = args;
- if (String(target).includes(`${path.sep}skillhub${path.sep}backups${path.sep}`)) {
- throw new Error('backup disk full');
- }
- return originalMkdir(...args);
- });
+ const mkdirSpy = vi
+ .spyOn(fs.promises, 'mkdir')
+ .mockImplementation(async (...args: Parameters<typeof fs.promises.mkdir>) => {
+ const [target] = args;
+ if (String(target).includes(`${path.sep}skillhub${path.sep}backups${path.sep}`)) {
+ throw new Error('backup disk full');
+ }
+ return originalMkdir(...args);
+ });
try {
const result = await install(
@@ -2253,13 +2472,21 @@ describe('skillhub/installService', () => {
expect(result.message).toContain('registry 回滚失败');
}
expect(fs.existsSync(finalDir)).toBe(false);
- const quarantines = fs.readdirSync(path.dirname(finalDir))
- .filter((name) => name.includes('.xdt-rollback-registry-failed-backup-registry-restore-fail-skill-'));
+ const quarantines = fs
+ .readdirSync(path.dirname(finalDir))
+ .filter((name) =>
+ name.includes('.xdt-rollback-registry-failed-backup-registry-restore-fail-skill-'),
+ );
expect(quarantines).toHaveLength(1);
- expect(fs.readFileSync(path.join(path.dirname(finalDir), quarantines[0], 'SKILL.md'), 'utf-8')).toBe('old content');
+ expect(
+ fs.readFileSync(path.join(path.dirname(finalDir), quarantines[0], 'SKILL.md'), 'utf-8'),
+ ).toBe('old content');
const removeInstallMock = vi.mocked(registryService.removeInstall);
const addInstallMock = vi.mocked(registryService.addInstall);
- expect(removeInstallMock).toHaveBeenCalledWith('backup-registry-restore-fail-skill', finalDir);
+ expect(removeInstallMock).toHaveBeenCalledWith(
+ 'backup-registry-restore-fail-skill',
+ finalDir,
+ );
expect(removeInstallMock.mock.invocationCallOrder[0]).toBeLessThan(
addInstallMock.mock.invocationCallOrder[1],
);
@@ -2306,7 +2533,11 @@ describe('skillhub/installService', () => {
};
}
if (apiPath.includes('/batch-detail')) {
- return { items: [{ slug: 'backup-registry-remove-fail-skill', owner: { slug: 'owner' }, isMine: false }] };
+ return {
+ items: [
+ { slug: 'backup-registry-remove-fail-skill', owner: { slug: 'owner' }, isMine: false },
+ ],
+ };
}
throw new Error(`unexpected api path ${apiPath}`);
});
@@ -2315,13 +2546,15 @@ describe('skillhub/installService', () => {
vi.mocked(registryService.addInstall).mockResolvedValue(undefined);
vi.mocked(registryService.removeInstall).mockRejectedValue(new Error('registry remove locked'));
const originalMkdir = fs.promises.mkdir.bind(fs.promises);
- const mkdirSpy = vi.spyOn(fs.promises, 'mkdir').mockImplementation(async (...args: Parameters<typeof fs.promises.mkdir>) => {
- const [target] = args;
- if (String(target).includes(`${path.sep}skillhub${path.sep}backups${path.sep}`)) {
- throw new Error('backup disk full');
- }
- return originalMkdir(...args);
- });
+ const mkdirSpy = vi
+ .spyOn(fs.promises, 'mkdir')
+ .mockImplementation(async (...args: Parameters<typeof fs.promises.mkdir>) => {
+ const [target] = args;
+ if (String(target).includes(`${path.sep}skillhub${path.sep}backups${path.sep}`)) {
+ throw new Error('backup disk full');
+ }
+ return originalMkdir(...args);
+ });
try {
const result = await install(
@@ -2340,11 +2573,19 @@ describe('skillhub/installService', () => {
expect(result.message).toContain('registry 回滚失败');
}
expect(fs.existsSync(finalDir)).toBe(false);
- const quarantines = fs.readdirSync(path.dirname(finalDir))
- .filter((name) => name.includes('.xdt-rollback-registry-failed-backup-registry-remove-fail-skill-'));
+ const quarantines = fs
+ .readdirSync(path.dirname(finalDir))
+ .filter((name) =>
+ name.includes('.xdt-rollback-registry-failed-backup-registry-remove-fail-skill-'),
+ );
expect(quarantines).toHaveLength(1);
- expect(fs.readFileSync(path.join(path.dirname(finalDir), quarantines[0], 'SKILL.md'), 'utf-8')).toBe('old content');
- expect(registryService.removeInstall).toHaveBeenCalledWith('backup-registry-remove-fail-skill', finalDir);
+ expect(
+ fs.readFileSync(path.join(path.dirname(finalDir), quarantines[0], 'SKILL.md'), 'utf-8'),
+ ).toBe('old content');
+ expect(registryService.removeInstall).toHaveBeenCalledWith(
+ 'backup-registry-remove-fail-skill',
+ finalDir,
+ );
} finally {
mkdirSpy.mockRestore();
}
@@ -2365,10 +2606,19 @@ describe('skillhub/installService', () => {
expect(release).not.toBeNull();
try {
expect((await uninstall(finalDir, target)).success).toBe(false);
- expect((await install({ name: 'external-client', installPath: finalDir, version: '1.0.0' }, () => {})).success).toBe(false);
+ expect(
+ (
+ await install(
+ { name: 'external-client', installPath: finalDir, version: '1.0.0' },
+ () => {},
+ )
+ ).success,
+ ).toBe(false);
expect(shell.trashItem).not.toHaveBeenCalled();
expect(fs.readFileSync(path.join(finalDir, 'SKILL.md'), 'utf8')).toBe('original');
- } finally { await release!(); }
+ } finally {
+ await release!();
+ }
});
it('rejects install while a learn apply holds the shared lock; other names unaffected', async () => {
@@ -2383,7 +2633,11 @@ describe('skillhub/installService', () => {
const lstatSpy = vi.spyOn(fs.promises, 'lstat');
try {
const result = await install(
- { name: 'locked-skill', installPath: path.join(TEST_ROOT, 'skills', 'locked-skill'), version: '1.0.0' },
+ {
+ name: 'locked-skill',
+ installPath: path.join(TEST_ROOT, 'skills', 'locked-skill'),
+ version: '1.0.0',
+ },
() => {},
);
expect(result.success).toBe(false);
@@ -2416,7 +2670,11 @@ describe('skillhub/installService', () => {
});
vi.mocked(net.fetch).mockResolvedValue(mockDownload(zipBuf));
const ok = await install(
- { name: 'other-skill', installPath: path.join(TEST_ROOT, 'skills', 'other-skill'), version: '1.0.0' },
+ {
+ name: 'other-skill',
+ installPath: path.join(TEST_ROOT, 'skills', 'other-skill'),
+ version: '1.0.0',
+ },
() => {},
);
expect(ok.success).toBe(true);
@@ -2459,7 +2717,11 @@ describe('skillhub/installService', () => {
});
const installing = install(
- { name: 'race-skill', installPath: path.join(TEST_ROOT, 'skills', 'race-skill'), version: '1.0.0' },
+ {
+ name: 'race-skill',
+ installPath: path.join(TEST_ROOT, 'skills', 'race-skill'),
+ version: '1.0.0',
+ },
() => {},
);
await vi.waitFor(() => {
@@ -2510,7 +2772,10 @@ describe('skillhub/installService', () => {
});
const finalDir = path.join(TEST_ROOT, 'skills', 'owner-race');
- const installing = install({ name: 'owner-race', installPath: finalDir, version: '1.0.0' }, () => {});
+ const installing = install(
+ { name: 'owner-race', installPath: finalDir, version: '1.0.0' },
+ () => {},
+ );
await vi.waitFor(() => expect(releaseDownload).toBeDefined());
vi.mocked(getCurrentDataOwnerId).mockReturnValue('owner-2');
@@ -2522,8 +2787,12 @@ describe('skillhub/installService', () => {
expect(vi.mocked(registryService.addInstall)).not.toHaveBeenCalled();
});
- it.each([['install-first', 'source', 'alias'], ['uninstall-first', 'source', 'alias'],
- ['install-first', 'Foo', 'foo'], ['uninstall-first', 'Foo', 'foo']])('locks import entries against install (%s, %s, %s)', async (order, sourceName, aliasName) => {
+ it.each([
+ ['install-first', 'source', 'alias'],
+ ['uninstall-first', 'source', 'alias'],
+ ['install-first', 'Foo', 'foo'],
+ ['uninstall-first', 'Foo', 'foo'],
+ ])('locks import entries against install (%s, %s, %s)', async (order, sourceName, aliasName) => {
const source = path.join(TEST_ROOT, 'checkout', sourceName);
const alias = path.join(TEST_ROOT, '.agents', 'skills', aliasName);
fs.mkdirSync(source, { recursive: true });
@@ -2545,23 +2814,33 @@ describe('skillhub/installService', () => {
try {
expect((await uninstall(source, target)).success).toBe(false);
expect(shell.trashItem).not.toHaveBeenCalled();
- expect(getSkillInstallLockOwner(sourceName)).toBe(sourceName.toLowerCase() === aliasName.toLowerCase() ? 'market-install' : null);
- } finally { releaseInstall(); }
+ expect(getSkillInstallLockOwner(sourceName)).toBe(
+ sourceName.toLowerCase() === aliasName.toLowerCase() ? 'market-install' : null,
+ );
+ } finally {
+ releaseInstall();
+ }
} else {
let finishTrash: (() => void) | undefined;
vi.mocked(shell.trashItem).mockImplementationOnce(async (entry) => {
const { acquireSharedSkillMutationLease } = await import('../sharedMutationLease');
expect(await acquireSharedSkillMutationLease([aliasName])).toBeNull();
expect(await acquireSharedSkillMutationLease([sourceName])).toBeNull();
- await new Promise<void>((resolve) => { finishTrash = resolve; });
+ await new Promise<void>((resolve) => {
+ finishTrash = resolve;
+ });
await fs.promises.rename(entry, path.join(TEST_ROOT, 'trashed-alias'));
});
const removing = uninstall(source, target);
await vi.waitFor(() => expect(finishTrash).toBeDefined());
try {
- expect((await install({ name: aliasName, installPath: alias, version: '1' }, () => {})).success).toBe(false);
+ expect(
+ (await install({ name: aliasName, installPath: alias, version: '1' }, () => {})).success,
+ ).toBe(false);
expect(getSkillInstallLockOwner(aliasName)).toBe('market-uninstall');
- } finally { finishTrash!(); }
+ } finally {
+ finishTrash!();
+ }
expect(await removing).toEqual({ success: true });
}
expect(fs.readFileSync(path.join(source, 'SKILL.md'), 'utf8')).toBe('external content');
@@ -2579,7 +2858,9 @@ describe('skillhub/installService', () => {
expect((await uninstall(source, target)).success).toBe(false);
expect(shell.trashItem).not.toHaveBeenCalled();
expect(fs.existsSync(source)).toBe(true);
- } finally { release(); }
+ } finally {
+ release();
+ }
});
it('rejects uninstall while a learn apply holds the shared lock', async () => {
diff --git a/apps/desktop/src/main/skillhub/installService.ts b/apps/desktop/src/main/skillhub/installService.ts
index 29ea4f35ea..5ab8e71a1f 100644
--- a/apps/desktop/src/main/skillhub/installService.ts
+++ b/apps/desktop/src/main/skillhub/installService.ts
@@ -26,10 +26,23 @@ import crypto from 'node:crypto';
import fs from 'node:fs';
import os from 'node:os';
import path from 'node:path';
-import { app, net, shell } from 'electron';
+import { app, shell } from 'electron';
+import { download, DownloadError } from '../downloader/index.js';
import { isLocalSkillTargetCurrent, type LocalSkillTarget } from './localSkillTarget';
-import { isCindySkillEnabled, setCindySkillEnabled, snapshotSkillActivation, clearSkillActivationSnapshot } from './activationPreferences';
-import { fileIdentity, writeUninstallCleanup, readUninstallCleanup, listUninstallCleanups, deleteUninstallCleanup, type UninstallCleanup } from './uninstallJournal';
+import {
+ isCindySkillEnabled,
+ setCindySkillEnabled,
+ snapshotSkillActivation,
+ clearSkillActivationSnapshot,
+} from './activationPreferences';
+import {
+ fileIdentity,
+ writeUninstallCleanup,
+ readUninstallCleanup,
+ listUninstallCleanups,
+ deleteUninstallCleanup,
+ type UninstallCleanup,
+} from './uninstallJournal';
import JSZip from 'jszip';
import { skillhubApiFetch } from './hubApi';
import { getCurrentDataOwnerId, getCurrentUserId } from '../authManager';
@@ -41,14 +54,27 @@ import {
import { registryService } from './registry';
import type { StoredInstall } from './registry/types';
import { computeFolderHash } from './folderHash';
-import { getSkillInstallLockOwner, skillInstallLockKey, tryAcquireSkillInstallLock } from './installLock';
-import { acquireSharedSkillMutationLease, skillMutationNames, type SkillMutationRelease } from './sharedMutationLease';
+import {
+ getSkillInstallLockOwner,
+ skillInstallLockKey,
+ tryAcquireSkillInstallLock,
+} from './installLock';
+import {
+ acquireSharedSkillMutationLease,
+ skillMutationNames,
+ type SkillMutationRelease,
+} from './sharedMutationLease';
import {
prepareSharedGlobalSkillLinks,
prepareSharedProjectSkillLinks,
projectWorkingDirFromSkillPath,
} from '../maker-host/shared-global-skills.js';
-import { clearIgnoredAutoSyncSkill, ignoreAutoSyncSkill, listIgnoredAutoSyncSkills, isKnownAutoSyncCandidateSkill } from './autoSyncPreferences';
+import {
+ clearIgnoredAutoSyncSkill,
+ ignoreAutoSyncSkill,
+ listIgnoredAutoSyncSkills,
+ isKnownAutoSyncCandidateSkill,
+} from './autoSyncPreferences';
import { withSkillhubCatalogScope, type SkillhubCatalogScope } from '../../shared/skillhubCatalog';
import { createLogger } from '../logger';
@@ -162,12 +188,6 @@ export function cancelInstall(name: string): boolean {
// ── 工具 ─────────────────────────────────────────────────────────────────────
-function sha256Hex(buf: ArrayBuffer | Uint8Array): string {
- const h = crypto.createHash('sha256');
- h.update(buf instanceof Uint8Array ? buf : new Uint8Array(buf));
- return h.digest('hex');
-}
-
async function pathExists(p: string): Promise<boolean> {
try {
await fs.promises.access(p);
@@ -191,7 +211,9 @@ function projectWorkingDirForSkillPaths(...skillPaths: string[]): string | undef
return projectWorkingDir;
}
-async function reconcileProjectSkillLinksForPaths(...skillPaths: string[]): Promise<string | undefined> {
+async function reconcileProjectSkillLinksForPaths(
+ ...skillPaths: string[]
+): Promise<string | undefined> {
const projectWorkingDir = projectWorkingDirForSkillPaths(...skillPaths);
if (!projectWorkingDir) return undefined;
@@ -228,7 +250,10 @@ async function movePersistentBackup(tempDir: string, skillName: string): Promise
return dest;
}
-async function rollbackFinalSwitch(finalDir: string, state: FinalSwitchRollbackState): Promise<void> {
+async function rollbackFinalSwitch(
+ finalDir: string,
+ state: FinalSwitchRollbackState,
+): Promise<void> {
if (!state.finalDirCreated && !state.backupDir) return;
if (state.finalDirCreated || state.backupDir) {
@@ -255,7 +280,10 @@ async function restoreRegistryAfterFinalSwitchRollback(
} catch (err) {
try {
const quarantinePath = await quarantineRolledBackInstall(physicalFinalDir, skillName);
- log.warn('[skillInstall] quarantined rolled back install after registry restore failed:', quarantinePath);
+ log.warn(
+ '[skillInstall] quarantined rolled back install after registry restore failed:',
+ quarantinePath,
+ );
} catch (quarantineErr) {
log.error('[skillInstall] quarantine after registry restore failed:', quarantineErr);
}
@@ -265,7 +293,10 @@ async function restoreRegistryAfterFinalSwitchRollback(
async function quarantineRolledBackInstall(finalDir: string, skillName: string): Promise<string> {
if (!(await pathExists(finalDir))) return finalDir;
- const dest = path.join(path.dirname(finalDir), `.xdt-rollback-registry-failed-${skillName}-${Date.now()}-${rand()}`);
+ const dest = path.join(
+ path.dirname(finalDir),
+ `.xdt-rollback-registry-failed-${skillName}-${Date.now()}-${rand()}`,
+ );
await fs.promises.rename(finalDir, dest);
return dest;
}
@@ -356,7 +387,10 @@ async function hasUnlinkedDiscoveryRoot(shape: DirectSkillDiscoveryPath): Promis
* a user symlink, the final switch replaces that symlink rather than touching
* its external target.
*/
-async function resolvePhysicalInstallDir(logicalFinalDir: string, skillName: string): Promise<string> {
+async function resolvePhysicalInstallDir(
+ logicalFinalDir: string,
+ skillName: string,
+): Promise<string> {
let stat: fs.Stats;
try {
stat = await fs.promises.lstat(logicalFinalDir);
@@ -397,14 +431,18 @@ async function readRegistryInstallSnapshots(
const candidates = [logicalFinalDir];
if (!pathTextEquals(path.normalize(logicalFinalDir), path.normalize(physicalFinalDir))) {
candidates.push(physicalFinalDir);
- const realPhysicalDir = await fs.promises.realpath(physicalFinalDir).catch(() => physicalFinalDir);
+ const realPhysicalDir = await fs.promises
+ .realpath(physicalFinalDir)
+ .catch(() => physicalFinalDir);
candidates.push(realPhysicalDir);
if (preSwitchPhysicalRealDir) candidates.push(preSwitchPhysicalRealDir);
}
const snapshots: RegistryInstallSnapshot[] = [];
for (const installPath of uniqueNormalizedPaths(candidates)) {
- const entry = await Promise.resolve(registryService.getInstall(skillName, installPath)).catch(() => null);
+ const entry = await Promise.resolve(registryService.getInstall(skillName, installPath)).catch(
+ () => null,
+ );
if (entry) snapshots.push({ installPath, entry });
}
return snapshots;
@@ -477,10 +515,7 @@ function safeJoin(dest: string, relPath: string): string | null {
// ── 主入口:install ─────────────────────────────────────────────────────────
-export async function install(
- p: InstallParams,
- onProgress: ProgressCb,
-): Promise<InstallResult> {
+export async function install(p: InstallParams, onProgress: ProgressCb): Promise<InstallResult> {
const userId = getCurrentUserId();
if (!userId) {
onProgress({ phase: 'failed', name: p.name, errorCode: 'AUTH_REQUIRED', message: '未登录' });
@@ -488,14 +523,24 @@ export async function install(
}
const installOwnerId = getCurrentDataOwnerId();
if (!installOwnerId) {
- onProgress({ phase: 'failed', name: p.name, errorCode: 'AUTH_REQUIRED', message: '无可用数据空间' });
+ onProgress({
+ phase: 'failed',
+ name: p.name,
+ errorCode: 'AUTH_REQUIRED',
+ message: '无可用数据空间',
+ });
return { success: false, errorCode: 'AUTH_REQUIRED', message: '无可用数据空间' };
}
// 推导目标目录
const resolved = resolveTargetDir(p);
if ('error' in resolved) {
- onProgress({ phase: 'failed', name: p.name, errorCode: resolved.error, message: resolved.message });
+ onProgress({
+ phase: 'failed',
+ name: p.name,
+ errorCode: resolved.error,
+ message: resolved.message,
+ });
return { success: false, errorCode: resolved.error, message: resolved.message };
}
const logicalFinalDir = resolved.finalDir;
@@ -547,90 +592,73 @@ export async function install(
// 如果没传版本号,先查 hub 拿最新版本
if (!downloadVersion) {
const detail = await skillhubApiFetch<{ version: string }>(
- withSkillhubCatalogScope(`/api/skills-hub/skills/${encodeURIComponent(p.name)}`, p.catalogScope),
+ withSkillhubCatalogScope(
+ `/api/skills-hub/skills/${encodeURIComponent(p.name)}`,
+ p.catalogScope,
+ ),
);
downloadVersion = detail.version;
}
const versionQs = downloadVersion ? `?version=${encodeURIComponent(downloadVersion)}` : '';
info = await skillhubApiFetch<DownloadInfoResponse>(
- withSkillhubCatalogScope(`/api/skills-hub/skills/${encodeURIComponent(p.name)}/download${versionQs}`, p.catalogScope),
+ withSkillhubCatalogScope(
+ `/api/skills-hub/skills/${encodeURIComponent(p.name)}/download${versionQs}`,
+ p.catalogScope,
+ ),
);
} catch (err) {
const message = err instanceof Error ? err.message : String(err);
- const code: InstallErrorCode = (err as { statusCode?: number }).statusCode === 404 ? 'NOT_FOUND' : 'DOWNLOAD_FAILED';
+ const code: InstallErrorCode =
+ (err as { statusCode?: number }).statusCode === 404 ? 'NOT_FOUND' : 'DOWNLOAD_FAILED';
onProgress({ phase: 'failed', name: p.name, errorCode: code, message });
return { success: false, errorCode: code, message };
}
if (checkAbort()) return { success: false, errorCode: 'CANCELLED', message: '已取消' };
- // 2) 下载 zip(流式 + 字节上限,防 OOM)
- if (info.fileSize > MAX_SKILL_ZIP) {
- const msg = `文件过大:${info.fileSize} bytes(上限 ${MAX_SKILL_ZIP})`;
- onProgress({ phase: 'failed', name: p.name, errorCode: 'DOWNLOAD_FAILED', message: msg });
- return { success: false, errorCode: 'DOWNLOAD_FAILED', message: msg };
+ // 2) Shared verified download; unpacking and install ownership stay here.
+ if (
+ !Number.isSafeInteger(info.fileSize) ||
+ info.fileSize <= 0 ||
+ info.fileSize > MAX_SKILL_ZIP
+ ) {
+ const message = 'Skill archive size is invalid';
+ onProgress({ phase: 'failed', name: p.name, errorCode: 'DOWNLOAD_FAILED', message });
+ return { success: false, errorCode: 'DOWNLOAD_FAILED', message };
}
-
onProgress({ phase: 'downloading', name: p.name });
let zipBuf: Uint8Array;
+ let downloadDir: string | undefined;
try {
- const resp = await net.fetch(info.url, { method: 'GET', signal });
- if (!resp.ok) {
- throw new Error(`下载失败:HTTP ${resp.status}`);
- }
-
- const cl = resp.headers.get('Content-Length');
- if (cl !== null && Number(cl) > MAX_SKILL_ZIP) {
- throw new Error(`Content-Length 过大:${cl} bytes`);
- }
-
- const reader = resp.body!.getReader();
- const chunks: Uint8Array[] = [];
- let received = 0;
- const hardLimit = Math.max(info.fileSize * 1.1, info.fileSize + 4096);
-
- for (;;) {
- const { done, value } = await reader.read();
- if (done) break;
- received += value.byteLength;
- if (received > hardLimit || received > MAX_SKILL_ZIP) {
- await reader.cancel();
- throw new Error(`下载超出大小限制:已接收 ${received} bytes`);
- }
- chunks.push(value);
- }
-
- zipBuf = new Uint8Array(received);
- let offset = 0;
- for (const chunk of chunks) {
- zipBuf.set(chunk, offset);
- offset += chunk.byteLength;
- }
- } catch (err) {
- const message = err instanceof Error ? err.message : String(err);
- const safeUrl = (() => { try { const u = new URL(info.url); return `${u.origin}${u.pathname}`; } catch { return '(invalid url)'; } })();
- log.error('[skillInstall] download failed url=%s err=%s', safeUrl, message);
- onProgress({ phase: 'failed', name: p.name, errorCode: 'DOWNLOAD_FAILED', message });
- return { success: false, errorCode: 'DOWNLOAD_FAILED', message };
+ downloadDir = await fs.promises.mkdtemp(path.join(os.tmpdir(), 'cindy-skill-download-'));
+ const archive = path.join(downloadDir, 'skill.zip');
+ await download({
+ url: info.url,
+ targetPath: archive,
+ sha256: info.zipSha256,
+ expectedSize: info.fileSize,
+ maxBytes: MAX_SKILL_ZIP,
+ signal,
+ resume: false,
+ retry: { maxAttempts: 1 },
+ });
+ zipBuf = await fs.promises.readFile(archive);
+ } catch (error) {
+ if (checkAbort()) return { success: false, errorCode: 'CANCELLED', message: '已取消' };
+ const checksum = error instanceof DownloadError && ['CHECKSUM', 'SIZE'].includes(error.code);
+ const errorCode = checksum ? 'CHECKSUM_MISMATCH' : 'DOWNLOAD_FAILED';
+ const message = checksum ? '下载校验失败:大小或 sha256 不匹配' : 'Skill download failed';
+ if (checksum) onProgress({ phase: 'verifying', name: p.name });
+ log.warn('[skillInstall] download failed', { errorCode });
+ onProgress({ phase: 'failed', name: p.name, errorCode, message });
+ return { success: false, errorCode, message };
+ } finally {
+ if (downloadDir)
+ await fs.promises.rm(downloadDir, { recursive: true, force: true }).catch(() => undefined);
}
-
if (checkAbort()) return { success: false, errorCode: 'CANCELLED', message: '已取消' };
-
- // 3) 校验阶段保留给 UI 进度;下载后在本函数内校验 size/sha。
+ // A resolved download has already passed size and SHA-256 verification.
onProgress({ phase: 'verifying', name: p.name });
- if (zipBuf.byteLength !== info.fileSize) {
- const msg = `下载大小不符:期望 ${info.fileSize},实际 ${zipBuf.byteLength}`;
- onProgress({ phase: 'failed', name: p.name, errorCode: 'CHECKSUM_MISMATCH', message: msg });
- return { success: false, errorCode: 'CHECKSUM_MISMATCH', message: msg };
- }
- const actualSha = sha256Hex(zipBuf);
- if (actualSha !== info.zipSha256) {
- const msg = `下载校验失败:sha256 不匹配`;
- onProgress({ phase: 'failed', name: p.name, errorCode: 'CHECKSUM_MISMATCH', message: msg });
- return { success: false, errorCode: 'CHECKSUM_MISMATCH', message: msg };
- }
-
- if (checkAbort()) return { success: false, errorCode: 'CANCELLED', message: '已取消' };
// 4) 同名冲突判定(F-DATA-4):
// - finalDir 不存在 → 直接装
@@ -638,7 +666,12 @@ export async function install(
if (await pathExists(finalDir)) {
if (!p.force) {
const msg = `目标位置已存在 ${p.name}/`;
- onProgress({ phase: 'failed', name: p.name, errorCode: 'CONFLICT_USER_OWNED', message: msg });
+ onProgress({
+ phase: 'failed',
+ name: p.name,
+ errorCode: 'CONFLICT_USER_OWNED',
+ message: msg,
+ });
return { success: false, errorCode: 'CONFLICT_USER_OWNED', message: msg };
}
}
@@ -772,25 +805,25 @@ export async function install(
const logicalRegistrySnapshot = registrySnapshots.find(({ installPath }) =>
pathTextEquals(path.normalize(installPath), path.normalize(logicalFinalDir)),
);
- const physicalRegistrySnapshots = registrySnapshots.filter(({ installPath }) =>
- !pathTextEquals(path.normalize(installPath), path.normalize(logicalFinalDir)),
+ const physicalRegistrySnapshots = registrySnapshots.filter(
+ ({ installPath }) =>
+ !pathTextEquals(path.normalize(installPath), path.normalize(logicalFinalDir)),
);
- const existingRegistryEntry = logicalRegistrySnapshot?.entry ?? physicalRegistrySnapshots[0]?.entry ?? null;
+ const existingRegistryEntry =
+ logicalRegistrySnapshot?.entry ?? physicalRegistrySnapshots[0]?.entry ?? null;
// Replacing the same catalog record updates its content baseline, not its publication provenance.
// This local metadata never grants publish rights; those still require fresh server authority.
- const preservePublication = existingRegistryEntry?.origin === 'published'
- && existingRegistryEntry.catalogScope === p.catalogScope;
+ const preservePublication =
+ existingRegistryEntry?.origin === 'published' &&
+ existingRegistryEntry.catalogScope === p.catalogScope;
if (preservePublication && !authorId) authorId = existingRegistryEntry.authorId;
const previousRegistrySnapshots = registrySnapshots;
const mutatedRegistryPaths = uniqueNormalizedPaths([
logicalFinalDir,
...physicalRegistrySnapshots.map(({ installPath }) => installPath),
]);
- const nextAutoSynced = p.autoSync === true
- ? true
- : existingRegistryEntry
- ? existingRegistryEntry.autoSynced
- : false;
+ const nextAutoSynced =
+ p.autoSync === true ? true : existingRegistryEntry ? existingRegistryEntry.autoSynced : false;
if (checkAbort()) {
await rollbackFinalSwitch(finalDir, rollbackState).catch((rollbackErr) => {
@@ -845,7 +878,10 @@ export async function install(
message = fileRollbackFailed
? `注册失败,且安装文件 / registry 回滚失败:${registryMessage};registry 错误:${restoreErr instanceof Error ? restoreErr.message : String(restoreErr)}`
: `注册失败,已回滚安装文件,但 registry 回滚失败:${registryMessage};registry 错误:${restoreErr instanceof Error ? restoreErr.message : String(restoreErr)}`;
- log.error('[skillInstall] registry rollback after registry migration failed:', restoreErr);
+ log.error(
+ '[skillInstall] registry rollback after registry migration failed:',
+ restoreErr,
+ );
}
}
onProgress({ phase: 'failed', name: p.name, errorCode: 'WRITE_FAILED', message });
@@ -855,9 +891,11 @@ export async function install(
let replacedBackupPath: string | undefined;
if (rollbackState.backupDir) {
if (p.skipBackup) {
- await fs.promises.rm(rollbackState.backupDir, { recursive: true, force: true }).catch((cleanupErr) => {
- log.warn('[skillInstall] cleanup replaced dir failed:', cleanupErr);
- });
+ await fs.promises
+ .rm(rollbackState.backupDir, { recursive: true, force: true })
+ .catch((cleanupErr) => {
+ log.warn('[skillInstall] cleanup replaced dir failed:', cleanupErr);
+ });
} else {
try {
replacedBackupPath = await movePersistentBackup(rollbackState.backupDir, p.name);
@@ -908,14 +946,17 @@ export async function install(
log.warn('[skillInstall] claude symlink failed (non-fatal):', claudeLink, err);
}
}
- const projectWorkingDir = await releaseShared.run(() => reconcileProjectSkillLinksForPaths(logicalFinalDir, finalDir));
+ const projectWorkingDir = await releaseShared.run(() =>
+ reconcileProjectSkillLinksForPaths(logicalFinalDir, finalDir),
+ );
try {
const ownerId = getCurrentDataOwnerId();
const linkResult = await withSharedGlobalSkillProjectionMutation(ownerId, () =>
- releaseShared!.run(() => prepareSharedGlobalSkillLinks({
- assertOwnerStable: () =>
- assertGhostSkillProjectionBoundaryStableForOwner(ownerId),
- })),
+ releaseShared!.run(() =>
+ prepareSharedGlobalSkillLinks({
+ assertOwnerStable: () => assertGhostSkillProjectionBoundaryStableForOwner(ownerId),
+ }),
+ ),
);
for (const warning of linkResult.warnings) {
log.warn('[skillInstall] shared global skill link warning:', warning);
@@ -960,7 +1001,10 @@ export async function uninstall(
}
const normResolved = resolved.replace(/\\/g, '/');
// 必须匹配 <prefix>/.{claude,agents,codex}/skills/<slug> 形式,slug 不含 /
- if (!target && !/\/(\.(claude|agents|codex)\/skills|codex-home\/skills)\/[^/.][^/]*$/.test(normResolved)) {
+ if (
+ !target &&
+ !/\/(\.(claude|agents|codex)\/skills|codex-home\/skills)\/[^/.][^/]*$/.test(normResolved)
+ ) {
return { success: false, errorCode: 'INTERNAL', message: 'absolutePath 不在合法 skill 目录下' };
}
@@ -970,8 +1014,12 @@ export async function uninstall(
// 共享安装锁:同名 install / learn apply 的 final-switch 进行中时拒绝删除,
// 避免 rm 掉对方刚切入的目录、registry 写入交错。
const releaseLocks: Array<() => void> = [];
- const lockNames = skillMutationNames([skillName, path.basename(absolutePath),
- path.basename(target?.operationPath ?? absolutePath), ...(target?.aliases ?? []).map((alias) => path.basename(alias))]);
+ const lockNames = skillMutationNames([
+ skillName,
+ path.basename(absolutePath),
+ path.basename(target?.operationPath ?? absolutePath),
+ ...(target?.aliases ?? []).map((alias) => path.basename(alias)),
+ ]);
// An imported discovery link can have a different name from its source. Install
// replaces that entry under its discovery name, so hold both locks through trash.
for (const lockName of lockNames) {
@@ -985,18 +1033,33 @@ export async function uninstall(
let releaseShared: SkillMutationRelease | null = null;
try {
releaseShared = await acquireSharedSkillMutationLease(lockNames);
- if (!releaseShared) return { success: false, errorCode: 'INTERNAL', message: skillLockBusyMessage(skillName) };
+ if (!releaseShared)
+ return { success: false, errorCode: 'INTERNAL', message: skillLockBusyMessage(skillName) };
// Keep the exact registry identity for metadata cleanup after trash succeeds.
const registryMatch = target?.linkOnly
- ? (await registryService.listAllInstalls()).find((record) =>
- [skillName, path.basename(target.operationPath)].some((name) => skillInstallLockKey(name) === skillInstallLockKey(record.skillName))
- && target.aliases.some((alias) => pathTextEquals(path.resolve(alias), path.resolve(record.installPath)))) ?? null
+ ? ((await registryService.listAllInstalls()).find(
+ (record) =>
+ [skillName, path.basename(target.operationPath)].some(
+ (name) => skillInstallLockKey(name) === skillInstallLockKey(record.skillName),
+ ) &&
+ target.aliases.some((alias) =>
+ pathTextEquals(path.resolve(alias), path.resolve(record.installPath)),
+ ),
+ ) ?? null)
: await findRegistryInstallForPath(skillName, absolutePath, resolved);
if (!registryMatch && !target) {
- return { success: false, errorCode: 'INTERNAL', message: 'No installation record or current local Skill grant' };
+ return {
+ success: false,
+ errorCode: 'INTERNAL',
+ message: 'No installation record or current local Skill grant',
+ };
}
if (target && (target.sourcePath !== resolved || !isLocalSkillTargetCurrent(target))) {
- return { success: false, errorCode: 'INTERNAL', message: 'Skill source changed; refresh and retry' };
+ return {
+ success: false,
+ errorCode: 'INTERNAL',
+ message: 'Skill source changed; refresh and retry',
+ };
}
const cloudUserId = getCurrentUserId();
@@ -1057,7 +1120,9 @@ async function findRegistryInstallForPath(
realInstallPath = fs.realpathSync(installPath);
} catch {
// 目录已删时仍允许用规范化路径与候选路径直接比对
- if (candidatePaths.some((candidate) => pathTextEquals(path.normalize(installPath), candidate))) {
+ if (
+ candidatePaths.some((candidate) => pathTextEquals(path.normalize(installPath), candidate))
+ ) {
return { skillName, installPath, entry };
}
continue;
@@ -1073,7 +1138,9 @@ async function findRegistryInstallForPath(
if (skillInstallLockKey(record.skillName) !== skillInstallLockKey(skillName)) continue;
try {
if (fs.realpathSync.native(record.installPath) === resolved) return record;
- } catch { /* Missing records do not prove ownership of a live source. */ }
+ } catch {
+ /* Missing records do not prove ownership of a live source. */
+ }
}
return null;
}
@@ -1091,84 +1158,145 @@ async function uninstallLocked(
canMutate: () => boolean = () => true,
): Promise<UninstallResult> {
const ownerId = getCurrentDataOwnerId();
- if (!ownerId || !canMutate()) return { success: false, errorCode: 'CANCELLED', message: 'Skill mutation context changed' };
+ if (!ownerId || !canMutate())
+ return { success: false, errorCode: 'CANCELLED', message: 'Skill mutation context changed' };
const allowed = () => ownerId === getCurrentDataOwnerId() && canMutate();
- const recordIgnore = !!(registryMatch && await shouldRecordAutoSyncIgnore(skillName, registryMatch.entry, cloudUserId ?? undefined));
- const wasIgnored = recordIgnore && (await listIgnoredAutoSyncSkills(cloudUserId ?? undefined)).has(skillName);
- const knownEntries = [...(target?.aliases ?? []), absolutePath, resolved,
- ...(registryMatch ? [registryMatch.installPath] : [])];
+ const recordIgnore = !!(
+ registryMatch &&
+ (await shouldRecordAutoSyncIgnore(skillName, registryMatch.entry, cloudUserId ?? undefined))
+ );
+ const wasIgnored =
+ recordIgnore && (await listIgnoredAutoSyncSkills(cloudUserId ?? undefined)).has(skillName);
+ const knownEntries = [
+ ...(target?.aliases ?? []),
+ absolutePath,
+ resolved,
+ ...(registryMatch ? [registryMatch.installPath] : []),
+ ];
// A repair can finish after the UI scan but before this lease. Include the
// sibling discovery entries for each known scope in the locked snapshot.
const compatibilityEntries = knownEntries.flatMap((entry) => {
if (!/\/\.(?:agents|claude|codex)\/skills\/[^/]+$/.test(entry.replace(/\\/g, '/'))) return [];
const base = path.dirname(path.dirname(path.dirname(entry)));
- return ['.agents', '.claude', '.codex'].map((root) => path.join(base, root, 'skills', path.basename(entry)));
+ return ['.agents', '.claude', '.codex'].map((root) =>
+ path.join(base, root, 'skills', path.basename(entry)),
+ );
});
- const candidates = target?.linkOnly ? [...new Set([...target.aliases, target.operationPath])] : [...new Set([
- ...knownEntries, ...compatibilityEntries,
- path.join(os.homedir(), '.claude', 'skills', skillName),
- path.join(os.homedir(), '.codex', 'skills', skillName),
- path.join(os.homedir(), '.agents', 'skills', skillName),
- ])];
+ const candidates = target?.linkOnly
+ ? [...new Set([...target.aliases, target.operationPath])]
+ : [
+ ...new Set([
+ ...knownEntries,
+ ...compatibilityEntries,
+ path.join(os.homedir(), '.claude', 'skills', skillName),
+ path.join(os.homedir(), '.codex', 'skills', skillName),
+ path.join(os.homedir(), '.agents', 'skills', skillName),
+ ]),
+ ];
const operationPath = target?.operationPath ?? resolved;
let cleanup: UninstallCleanup;
try {
const sourceIdentity = fileIdentity(resolved, true);
const operationIdentity = fileIdentity(operationPath);
- if (!allowed() || !sourceIdentity || !operationIdentity || (target && !isLocalSkillTargetCurrent(target))
- || candidates.some((candidate) => !lockNames.includes(skillInstallLockKey(path.basename(candidate))))) {
+ if (
+ !allowed() ||
+ !sourceIdentity ||
+ !operationIdentity ||
+ (target && !isLocalSkillTargetCurrent(target)) ||
+ candidates.some(
+ (candidate) => !lockNames.includes(skillInstallLockKey(path.basename(candidate))),
+ )
+ ) {
throw new Error('Skill source changed; refresh and retry');
}
const links = candidates.flatMap((candidate) => {
try {
- return fs.lstatSync(candidate).isSymbolicLink() && fs.realpathSync.native(candidate) === resolved
- ? [{ path: candidate, value: fs.readlinkSync(candidate), identity: fileIdentity(candidate)! }] : [];
+ return fs.lstatSync(candidate).isSymbolicLink() &&
+ fs.realpathSync.native(candidate) === resolved
+ ? [
+ {
+ path: candidate,
+ value: fs.readlinkSync(candidate),
+ identity: fileIdentity(candidate)!,
+ },
+ ]
+ : [];
} catch (error) {
if ((error as NodeJS.ErrnoException).code === 'ENOENT') return [];
throw error;
}
});
cleanup = {
- version: 1, token: crypto.randomUUID(), ownerId, phase: 'prepared', lockNames,
- skillName, resolved, sourceIdentity, operationPath, operationIdentity,
- registryMatch, links, linkOnly: target?.linkOnly ?? false,
+ version: 1,
+ token: crypto.randomUUID(),
+ ownerId,
+ phase: 'prepared',
+ lockNames,
+ skillName,
+ resolved,
+ sourceIdentity,
+ operationPath,
+ operationIdentity,
+ registryMatch,
+ links,
+ linkOnly: target?.linkOnly ?? false,
activation: target?.linkOnly ? null : snapshotSkillActivation(resolved),
- undoIgnore: recordIgnore && !wasIgnored, cloudUserId,
+ undoIgnore: recordIgnore && !wasIgnored,
+ cloudUserId,
};
// Journal first, then the shared barrier, then side effects. A crash in any
// gap leaves either no effects or enough information to finish without trashing twice.
writeUninstallCleanup(cleanup);
lease.retainUntilComplete(cleanup.token);
} catch (error) {
- return { success: false, errorCode: 'WRITE_FAILED', message: error instanceof Error ? error.message : String(error) };
+ return {
+ success: false,
+ errorCode: 'WRITE_FAILED',
+ message: error instanceof Error ? error.message : String(error),
+ };
}
let trashError: unknown;
try {
if (cleanup.undoIgnore) await ignoreAutoSyncSkill(skillName, cloudUserId ?? undefined);
- if (!allowed() || (target && !isLocalSkillTargetCurrent(target))) throw new Error('Skill source changed; refresh and retry');
+ if (!allowed() || (target && !isLocalSkillTargetCurrent(target)))
+ throw new Error('Skill source changed; refresh and retry');
await shell.trashItem(operationPath);
cleanup.phase = 'removed';
writeUninstallCleanup(cleanup);
- } catch (error) { trashError = error; }
+ } catch (error) {
+ trashError = error;
+ }
// Even a rejected trash call can have removed its entry. Recovery inspects
// the original identity; it never repeats the destructive operation.
const complete = await finishUninstallCleanup(cleanup, lease, allowed);
- if (trashError && cleanup.phase === 'completed' && fileIdentity(operationPath) === cleanup.operationIdentity) {
- return { success: false, errorCode: 'WRITE_FAILED', message: trashError instanceof Error ? trashError.message : String(trashError) };
+ if (
+ trashError &&
+ cleanup.phase === 'completed' &&
+ fileIdentity(operationPath) === cleanup.operationIdentity
+ ) {
+ return {
+ success: false,
+ errorCode: 'WRITE_FAILED',
+ message: trashError instanceof Error ? trashError.message : String(trashError),
+ };
}
// Cache invalidation needs the cwd, not a broad link reconciliation: that
// would project a remaining import back into an entry we just removed.
const projectWorkingDir = projectWorkingDirForSkillPaths(operationPath, resolved, absolutePath);
- return { success: true, ...(!complete ? { cleanupToken: cleanup.token } : {}),
- ...(projectWorkingDir ? { projectWorkingDir } : {}) };
+ return {
+ success: true,
+ ...(!complete ? { cleanupToken: cleanup.token } : {}),
+ ...(projectWorkingDir ? { projectWorkingDir } : {}),
+ };
}
/** Only the current profile/data owner can receive a new window grant. */
export function listPendingUninstallCleanups(): Array<{ token: string; name: string }> {
const ownerId = getCurrentDataOwnerId();
- return listUninstallCleanups().filter((record) => record.ownerId === ownerId)
+ return listUninstallCleanups()
+ .filter((record) => record.ownerId === ownerId)
.map((record) => ({ token: record.token, name: record.skillName }));
}
@@ -1180,30 +1308,45 @@ async function finishUninstallCleanup(
if (!canMutate()) return false;
try {
if (cleanup.phase !== 'completed') {
- if (cleanup.phase === 'prepared' && fileIdentity(cleanup.operationPath) === cleanup.operationIdentity) {
+ if (
+ cleanup.phase === 'prepared' &&
+ fileIdentity(cleanup.operationPath) === cleanup.operationIdentity
+ ) {
// The trash operation never committed (or the original was restored).
- if (cleanup.undoIgnore) await clearIgnoredAutoSyncSkill(cleanup.skillName, cleanup.cloudUserId ?? undefined);
+ if (cleanup.undoIgnore)
+ await clearIgnoredAutoSyncSkill(cleanup.skillName, cleanup.cloudUserId ?? undefined);
} else {
for (const link of cleanup.links) {
if (!canMutate()) return false;
- if (fileIdentity(link.path) !== link.identity || fs.readlinkSync(link.path) !== link.value) continue;
+ if (
+ fileIdentity(link.path) !== link.identity ||
+ fs.readlinkSync(link.path) !== link.value
+ )
+ continue;
const currentTarget = fileIdentity(link.path, true);
// Remove only links still serving the old source (external imports),
// or broken links whose source is still absent. A replaced source wins.
- if ((cleanup.linkOnly && currentTarget === cleanup.sourceIdentity
- && fileIdentity(cleanup.operationPath) !== cleanup.operationIdentity)
- || (currentTarget === null && fileIdentity(cleanup.resolved, true) === null)) fs.unlinkSync(link.path);
+ if (
+ (cleanup.linkOnly &&
+ currentTarget === cleanup.sourceIdentity &&
+ fileIdentity(cleanup.operationPath) !== cleanup.operationIdentity) ||
+ (currentTarget === null && fileIdentity(cleanup.resolved, true) === null)
+ )
+ fs.unlinkSync(link.path);
}
const { registryMatch } = cleanup;
if (registryMatch && fileIdentity(registryMatch.installPath) === null) {
await registryService.removeInstall(registryMatch.skillName, registryMatch.installPath, {
- expected: registryMatch.entry, canMutate,
+ expected: registryMatch.entry,
+ canMutate,
shouldRemove: () => fileIdentity(registryMatch.installPath) === null,
});
}
if (cleanup.activation && fileIdentity(cleanup.resolved, true) === null) {
- await clearSkillActivationSnapshot(cleanup.activation,
- () => canMutate() && fileIdentity(cleanup.resolved, true) === null);
+ await clearSkillActivationSnapshot(
+ cleanup.activation,
+ () => canMutate() && fileIdentity(cleanup.resolved, true) === null,
+ );
}
}
if (!canMutate()) return false;
@@ -1221,7 +1364,10 @@ async function finishUninstallCleanup(
}
}
-export async function retryUninstallCleanup(token: string, canMutate: () => boolean): Promise<boolean> {
+export async function retryUninstallCleanup(
+ token: string,
+ canMutate: () => boolean,
+): Promise<boolean> {
const cleanup = readUninstallCleanup(token);
if (!cleanup) return true;
const allowed = () => cleanup.ownerId === getCurrentDataOwnerId() && canMutate();
@@ -1247,7 +1393,11 @@ export async function retryUninstallCleanup(token: string, canMutate: () => bool
}
}
-async function shouldRecordAutoSyncIgnore(skillName: string, registryEntry: StoredInstall, userId?: string): Promise<boolean> {
+async function shouldRecordAutoSyncIgnore(
+ skillName: string,
+ registryEntry: StoredInstall,
+ userId?: string,
+): Promise<boolean> {
if (registryEntry.autoSynced === true) return true;
if (registryEntry.origin !== 'installed' || registryEntry.autoSynced !== undefined) return false;
// 兼容 auto-sync 首版:当时 registry 没有 autoSynced 字段,候选集合来自最近一次 auto-sync 配置。
diff --git a/apps/desktop/src/preload/preload.ts b/apps/desktop/src/preload/preload.ts
index 4360b1deaf..9208af6f90 100644
--- a/apps/desktop/src/preload/preload.ts
+++ b/apps/desktop/src/preload/preload.ts
@@ -1,7 +1,16 @@
import type { WorktreeRecycleAction, WorktreeRecycleStatus } from '../shared/worktreeRecycle';
-import { FAVORITE_HOST_READY, FAVORITE_HOST_REQUEST, FAVORITE_HOST_REPLY, FAVORITE_HOST_CHANGED, type ModelFavoritesHostApi } from '../shared/modelFavoritesSync';
+import {
+ FAVORITE_HOST_READY,
+ FAVORITE_HOST_REQUEST,
+ FAVORITE_HOST_REPLY,
+ FAVORITE_HOST_CHANGED,
+ type ModelFavoritesHostApi,
+} from '../shared/modelFavoritesSync';
import { invokeOpenPath } from './openPath';
-import { COPY_PNG_TO_CLIPBOARD_CHANNEL, type CopyPngToClipboardParams } from '../shared/pngClipboard';
+import {
+ COPY_PNG_TO_CLIPBOARD_CHANNEL,
+ type CopyPngToClipboardParams,
+} from '../shared/pngClipboard';
import type { ByokStatus } from '../shared/modelAccess.js';
import type { LocalPluginOauthRequest, LocalPluginSecretRequest } from '../shared/pluginOauth';
import { REMOTE_VIEWER } from '../shared/remoteDesktopViewer';
@@ -126,7 +135,10 @@ import {
type TerminateAgentProcessResult,
} from '../shared/processMonitor';
import { RESOURCE_USAGE_WINDOW_OPEN_CHANNEL } from '../shared/resourceUsageWindow';
-import { APP_ATTENTION_COUNT_CHANNEL, SESSION_ATTENTION_CLEARED_CHANNEL } from '../shared/sessionAttention';
+import {
+ APP_ATTENTION_COUNT_CHANNEL,
+ SESSION_ATTENTION_CLEARED_CHANNEL,
+} from '../shared/sessionAttention';
import { VOICE_INPUT_POWER_STATE_CHANNEL } from '../shared/voiceInputPowerIpc';
import {
VOICE_INPUT_TEST_CONNECTION_CHANNEL,
@@ -618,6 +630,7 @@ const fanOutRsbBrowserBridgeTabOpRequest = createIpcFanOut('rsb-browser-bridge:t
// session-git-pr-context: HEAD 分支变化 / session PR 引用变化推送
const fanOutGitContextChanged = createIpcFanOut('git-context:changed');
const fanOutGitContextPrRefsChanged = createIpcFanOut('git-context:pr-refs-changed');
+const fanOutGithubConnected = createIpcFanOut('git-context:github-connected');
// 系统级瞬时网络错误 tip:lifecycle 兜底 catch 到 ETIMEDOUT/ECONNRESET 等不杀进程时,
// 把 err.code / address / port 推给 renderer, renderer 自己 toast (带节流) 让用户感知。
const fanOutSystemTransientNetworkError = createIpcFanOut('system:transient-network-error');
@@ -794,10 +807,16 @@ const fanOutMakerUsageReferenceModelPricing = createIpcFanOut(
'usage:reference-model-pricing-changed',
);
const fanOutMakerUsageClaudeAccount = createIpcFanOut('usage:claude-account-changed'); // Claude 月度配额
-const fanOutMakerUsageCodexProviderAccount = createIpcFanOut('usage:codex-provider-account-changed');
-const fanOutSubscriptionProviderAccount = createIpcFanOut('usage:subscription-provider-account-changed');
+const fanOutMakerUsageCodexProviderAccount = createIpcFanOut(
+ 'usage:codex-provider-account-changed',
+);
+const fanOutSubscriptionProviderAccount = createIpcFanOut(
+ 'usage:subscription-provider-account-changed',
+);
const fanOutMakerUsageCodexAccount = createIpcFanOut('usage:codex-account-changed'); // Codex 订阅用量
-const fanOutMakerUsageXaiProviderRateLimit = createIpcFanOut('usage:xai-provider-rate-limit-changed');
+const fanOutMakerUsageXaiProviderRateLimit = createIpcFanOut(
+ 'usage:xai-provider-rate-limit-changed',
+);
const fanOutMakerUsageXaiRateLimit = createIpcFanOut('usage:xai-rate-limit-changed'); // xAI bridge 限流快照
const fanOutMakerUsageClaudeSubscription = createIpcFanOut('usage:claude-subscription-changed'); // Claude 订阅余量
const fanOutMakerUsageXaiSubscription = createIpcFanOut('usage:xai-subscription-changed'); // SuperGrok 周用量
@@ -1028,17 +1047,23 @@ type CindyMediaPreferenceKind = {
contextBridge.exposeInMainWorld('electronAPI', {
modelFavoritesHost: {
ready: () => ipcRenderer.send(FAVORITE_HOST_READY),
- changed: stamp => ipcRenderer.send(FAVORITE_HOST_CHANGED, stamp),
- reply: reply => ipcRenderer.send(FAVORITE_HOST_REPLY, reply),
- onRequest: listener => {
- const receive = (_event: Electron.IpcRendererEvent, request: Parameters<typeof listener>[0]) => listener(request);
+ changed: (stamp) => ipcRenderer.send(FAVORITE_HOST_CHANGED, stamp),
+ reply: (reply) => ipcRenderer.send(FAVORITE_HOST_REPLY, reply),
+ onRequest: (listener) => {
+ const receive = (
+ _event: Electron.IpcRendererEvent,
+ request: Parameters<typeof listener>[0],
+ ) => listener(request);
ipcRenderer.on(FAVORITE_HOST_REQUEST, receive);
- return () => { ipcRenderer.removeListener(FAVORITE_HOST_REQUEST, receive); };
+ return () => {
+ ipcRenderer.removeListener(FAVORITE_HOST_REQUEST, receive);
+ };
},
} satisfies ModelFavoritesHostApi,
routines: {
list: (botId: string) => ipcRenderer.invoke('routines:list', botId),
- save: (botId: string, input: RoutineInput, id?: string) => ipcRenderer.invoke('routines:save', botId, input, id),
+ save: (botId: string, input: RoutineInput, id?: string) =>
+ ipcRenderer.invoke('routines:save', botId, input, id),
remove: (botId: string, id: string) => ipcRenderer.invoke('routines:remove', botId, id),
runNow: (botId: string, id: string) => ipcRenderer.invoke('routines:run-now', botId, id),
history: (botId: string, id: string) => ipcRenderer.invoke('routines:history', botId, id),
@@ -1403,10 +1428,7 @@ contextBridge.exposeInMainWorld('electronAPI', {
ipcRenderer.invoke('forge-oidc-install:resolve-confirm', { requestId, confirmed }),
onInstallConsentRequest: fanOutGhostInstallConsentRequest,
onInstallConsentDismissed: fanOutGhostInstallConsentDismissed,
- resolveInstallConsent: (
- requestId: string,
- confirmed: boolean,
- ): Promise<{ handled: boolean }> =>
+ resolveInstallConsent: (requestId: string, confirmed: boolean): Promise<{ handled: boolean }> =>
ipcRenderer.invoke('ghosts:install-consent:resolve', { requestId, confirmed }),
onPreviewOpen: fanOutGhostPreviewOpen,
onScheduleDraft: fanOutGhostScheduleDraft,
@@ -2020,8 +2042,10 @@ contextBridge.exposeInMainWorld('electronAPI', {
ipcRenderer.invoke('builtin-api-key-has', providerId),
builtinApiKeyStore: (providerId: string, value: string): Promise<void> =>
ipcRenderer.invoke('builtin-api-key-store', providerId, value),
- builtinApiKeyRemove: (providerId: string, ownerScope?: { dataOwnerId: string | null; ownerGeneration: number }): Promise<void> =>
- ipcRenderer.invoke('builtin-api-key-remove', providerId, ownerScope),
+ builtinApiKeyRemove: (
+ providerId: string,
+ ownerScope?: { dataOwnerId: string | null; ownerGeneration: number },
+ ): Promise<void> => ipcRenderer.invoke('builtin-api-key-remove', providerId, ownerScope),
// ── 网关凭据自动下发(model-access,shared/modelAccess.ts) ──
modelAccess: {
@@ -2489,10 +2513,13 @@ contextBridge.exposeInMainWorld('electronAPI', {
modelChosenByVendor: Partial<Record<'cc' | 'codex' | 'pi', boolean>>;
fastModeByModel: Record<string, boolean>;
effortByModel: Record<string, string>;
- providerModelMemory?: Record<string, {
- effortByModel: Record<string, string>;
- fastByModel: Record<string, boolean>;
- }>;
+ providerModelMemory?: Record<
+ string,
+ {
+ effortByModel: Record<string, string>;
+ fastByModel: Record<string, boolean>;
+ }
+ >;
/** 「新建会话默认启用 worktree」勾选记忆(vendor 无关根字段,远程草稿播种用)。 */
worktreeEnabled: boolean;
}): void => ipcRenderer.send('maker:sync-new-maker-draft', snapshot),
@@ -2868,8 +2895,7 @@ contextBridge.exposeInMainWorld('electronAPI', {
| { kind: 'ssh'; remoteHostId: string };
workdir: string;
absPath: string;
- }): Promise<{ ok: true; url: string }> =>
- ipcRenderer.invoke('maker:html-preview:open', params),
+ }): Promise<{ ok: true; url: string }> => ipcRenderer.invoke('maker:html-preview:open', params),
chatFetch: (params: {
origin: { kind: 'device'; deviceId: string } | { kind: 'ssh'; remoteHostId: string };
workdir: string;
@@ -3034,8 +3060,11 @@ contextBridge.exposeInMainWorld('electronAPI', {
// ~/.claude/{skills,commands,agents},project 来源由调用方传入的 projectRoot 决定。
// 返回商店层 Skill[] 与兼容用 sources[];scan 本身只读。
skillhub: {
- setEnabled: (params: { absolutePath: string; skillId?: string; enabled: boolean }): Promise<{ cindyEnabled: boolean }> =>
- ipcRenderer.invoke('skillhub:set-enabled', params),
+ setEnabled: (params: {
+ absolutePath: string;
+ skillId?: string;
+ enabled: boolean;
+ }): Promise<{ cindyEnabled: boolean }> => ipcRenderer.invoke('skillhub:set-enabled', params),
onLocalStateChanged: fanOutSkillhubLocalStateChanged,
scan: (params: {
projects?: import('../main/skillhub/scanner').ProjectInput[];
@@ -3331,7 +3360,10 @@ contextBridge.exposeInMainWorld('electronAPI', {
// 计算本地 skill 文件夹 hash(30s 缓存在 renderer 侧)
// manifest 是参与 hash 的文件清单(path + sha256),用于 dirty 排查
- comparePublished: (params: import('../shared/skillhubPublishComparison').SkillhubPublishComparisonParams): Promise<import('../shared/skillhubPublishComparison').SkillhubPublishComparison> => ipcRenderer.invoke('skillhub:compare-published', params),
+ comparePublished: (
+ params: import('../shared/skillhubPublishComparison').SkillhubPublishComparisonParams,
+ ): Promise<import('../shared/skillhubPublishComparison').SkillhubPublishComparison> =>
+ ipcRenderer.invoke('skillhub:compare-published', params),
getFolderHash: (
absolutePath: string,
@@ -3472,8 +3504,9 @@ contextBridge.exposeInMainWorld('electronAPI', {
absolutePath: string,
skillId?: string,
): Promise<
- | { success: true; cleanupToken?: string } | { success: false; errorCode: string; message: string }> =>
- ipcRenderer.invoke('skillhub:uninstall', { absolutePath, skillId }),
+ | { success: true; cleanupToken?: string }
+ | { success: false; errorCode: string; message: string }
+ > => ipcRenderer.invoke('skillhub:uninstall', { absolutePath, skillId }),
retryUninstallCleanup: (token: string): Promise<{ complete: boolean }> =>
ipcRenderer.invoke('skillhub:retry-uninstall-cleanup', token),
@@ -3630,8 +3663,9 @@ contextBridge.exposeInMainWorld('electronAPI', {
clear: (): Promise<{ configured: boolean; enabled: boolean }> =>
ipcRenderer.invoke('wecomGroupNotification:clear'),
},
- notificationSetAppAttentionCount: (snapshot: import('../shared/sessionAttention').AppAttentionSnapshot): Promise<void> =>
- ipcRenderer.invoke(APP_ATTENTION_COUNT_CHANNEL, snapshot),
+ notificationSetAppAttentionCount: (
+ snapshot: import('../shared/sessionAttention').AppAttentionSnapshot,
+ ): Promise<void> => ipcRenderer.invoke(APP_ATTENTION_COUNT_CHANNEL, snapshot),
notificationMarkSessionAttention: (sessionId: string): Promise<void> =>
ipcRenderer.invoke('notification:mark-session-attention', sessionId),
// intent:'explicit' = 用户真实看到了内容(报错 banner 聚焦驻留 / 全部标为已读等);
@@ -3819,7 +3853,8 @@ contextBridge.exposeInMainWorld('electronAPI', {
// Open a local absolute path or a main-resolved cindy-media reference with
// the OS default application (the renderer never receives the blob path).
- openPath: (filePathOrUrl: string) => invokeOpenPath(ipcRenderer.invoke.bind(ipcRenderer), filePathOrUrl),
+ openPath: (filePathOrUrl: string) =>
+ invokeOpenPath(ipcRenderer.invoke.bind(ipcRenderer), filePathOrUrl),
// 文件 chip 右键「打开方式」。appId 只能是 listOpenWithApps 返回的 id,
// main 侧反查可执行体;renderer 无法让 main 执行任意路径。
@@ -4219,16 +4254,20 @@ contextBridge.exposeInMainWorld('electronAPI', {
// ── 媒体总仓存储管理(关于页存储空间卡片)──
worktreeRecycle: {
list: (): Promise<WorktreeRecycleStatus[]> => ipcRenderer.invoke('worktree-recycle:list'),
- control: (input: WorktreeRecycleAction): Promise<void> => ipcRenderer.invoke('worktree-recycle:control', input),
+ control: (input: WorktreeRecycleAction): Promise<void> =>
+ ipcRenderer.invoke('worktree-recycle:control', input),
},
// 占用统计 / 清理预检(报数)/ 执行清理 / 对账体检。scan 与 cleanup 的
// draftUrls 由 renderer 从 composerDraftStore 现场收集(main 读不到
// renderer 内存,草稿附件是合法的零引用 blob,必须随参取证防误删)。
dialogueWorkspace: {
open: (): Promise<{ success: boolean }> => ipcRenderer.invoke('dialogue-workspace:open'),
- get: (): Promise<DialogueWorkspaceSettingsState> => ipcRenderer.invoke('dialogue-workspace:get'),
- choose: (): Promise<DialogueWorkspaceSettingsState> => ipcRenderer.invoke('dialogue-workspace:choose'),
- reset: (): Promise<DialogueWorkspaceSettingsState> => ipcRenderer.invoke('dialogue-workspace:reset'),
+ get: (): Promise<DialogueWorkspaceSettingsState> =>
+ ipcRenderer.invoke('dialogue-workspace:get'),
+ choose: (): Promise<DialogueWorkspaceSettingsState> =>
+ ipcRenderer.invoke('dialogue-workspace:choose'),
+ reset: (): Promise<DialogueWorkspaceSettingsState> =>
+ ipcRenderer.invoke('dialogue-workspace:reset'),
},
cindyMediaStorage: {
@@ -4411,7 +4450,8 @@ contextBridge.exposeInMainWorld('electronAPI', {
// ── Device Link (设备互联/跨设备远程控制) ─────────────────────────────
// 同账号设备经 server relay 互联;此处只暴露开关 + 设备列表管理面,
// 隧道(远程会话控制)在 M3 接入。
- openRemoteDesktop: (target: {deviceId: string; name: string}): Promise<void> => ipcRenderer.invoke(REMOTE_VIEWER.OPEN, target),
+ openRemoteDesktop: (target: { deviceId: string; name: string }): Promise<void> =>
+ ipcRenderer.invoke(REMOTE_VIEWER.OPEN, target),
remoteDesktop: {
state: (checkWindowsSupport) => ipcRenderer.invoke(DESKTOP_LOCAL.STATE, checkWindowsSupport),
permissions: () => ipcRenderer.invoke(DESKTOP_LOCAL.PERMISSIONS),
@@ -5010,6 +5050,15 @@ contextBridge.exposeInMainWorld('electronAPI', {
// ── session-git-pr-context: 会话分支感知 + PR 关联状态 ──
gitContext: {
+ githubConnection: (): Promise<import('../shared/githubSetup').GithubConnectionState> =>
+ ipcRenderer.invoke('git-context:github-setup:connection'),
+ githubSetupStatus: (): Promise<import('../shared/githubSetup').GithubSetupState> =>
+ ipcRenderer.invoke('git-context:github-setup:status'),
+ startGithubSetup: (): Promise<import('../shared/githubSetup').GithubSetupState> =>
+ ipcRenderer.invoke('git-context:github-setup:start'),
+ cancelGithubSetup: (): Promise<import('../shared/githubSetup').GithubSetupState> =>
+ ipcRenderer.invoke('git-context:github-setup:cancel'),
+ onGithubConnected: fanOutGithubConnected,
/** 读 workdir 当前分支(非 git 目录返回 head=null)。 */
get: (workdir: string): Promise<unknown> => ipcRenderer.invoke('git-context:get', workdir),
/** 按 session 解析「对话真实工作目录」+ HEAD + 来源(含 SSH 远端)。 */
@@ -5365,7 +5414,8 @@ contextBridge.exposeInMainWorld('electronAPI', {
create: (body?: unknown): Promise<unknown> =>
ipcRenderer.invoke('local-db:sessions:create', body),
get: (id: string): Promise<unknown> => ipcRenderer.invoke('local-db:sessions:get', id),
- getMany: (ids: string[]): Promise<unknown> => ipcRenderer.invoke('local-db:sessions:get-many', ids),
+ getMany: (ids: string[]): Promise<unknown> =>
+ ipcRenderer.invoke('local-db:sessions:get-many', ids),
resolveReferences: (sessionIds: string[]): Promise<unknown> =>
ipcRenderer.invoke('local-db:sessions:resolve-references', sessionIds),
restoreIfArchived: (id: string, expected: unknown): Promise<unknown> =>
@@ -5396,8 +5446,12 @@ contextBridge.exposeInMainWorld('electronAPI', {
// Stage 2 C2: fork 已迁到 electronAPI.maker.fork (走 maker:fork IPC)。
},
bots: {
- generateAvatar: (token: string): Promise<{ avatarImageBase64: string }> => ipcRenderer.invoke('local-db:bots:generate-avatar', token),
- generateDraft: (body: import('../shared/botCreation').BotCreationRequest): Promise<import('../shared/botCreation').BotCreationDraft> => ipcRenderer.invoke('local-db:bots:generate-draft', body),
+ generateAvatar: (token: string): Promise<{ avatarImageBase64: string }> =>
+ ipcRenderer.invoke('local-db:bots:generate-avatar', token),
+ generateDraft: (
+ body: import('../shared/botCreation').BotCreationRequest,
+ ): Promise<import('../shared/botCreation').BotCreationDraft> =>
+ ipcRenderer.invoke('local-db:bots:generate-draft', body),
getModelChainSettings: (): Promise<{
modelChain: import('../shared/botModelChain').BotModelRoute[];
isCustomized: boolean;
@@ -5412,8 +5466,11 @@ contextBridge.exposeInMainWorld('electronAPI', {
modelChain: import('../shared/botModelChain').BotModelRoute[];
isCustomized: boolean;
}> => ipcRenderer.invoke('local-db:bots:model-chain-settings-set', body),
- list: (body?: { lastReadAtByBotId?: Record<string, number>; welcomeContext?: import('../shared/botWelcomeContext').BotWelcomeContext; locale?: import('../shared/locale').SupportedLocale }): Promise<unknown[]> =>
- ipcRenderer.invoke('local-db:bots:list', body),
+ list: (body?: {
+ lastReadAtByBotId?: Record<string, number>;
+ welcomeContext?: import('../shared/botWelcomeContext').BotWelcomeContext;
+ locale?: import('../shared/locale').SupportedLocale;
+ }): Promise<unknown[]> => ipcRenderer.invoke('local-db:bots:list', body),
get: (botId: string): Promise<unknown> => ipcRenderer.invoke('local-db:bots:get', botId),
chooseAvatar: (body: { botId: string; avatarImageBase64?: string }): Promise<unknown> =>
ipcRenderer.invoke('local-db:bots:choose-avatar', body),
@@ -5597,9 +5654,15 @@ contextBridge.exposeInMainWorld('electronAPI', {
ipcRenderer.invoke('maker:collaboration-settings:reset'),
},
messages: {
- historyView: (sessionId: string, opts?: { before?: string | null; lazyDetails?: boolean }): Promise<unknown> =>
- ipcRenderer.invoke('local-db:messages:view', sessionId, opts),
- workDetails: (sessionId: string, ref: unknown, opts?: { after?: string | null }): Promise<unknown> =>
+ historyView: (
+ sessionId: string,
+ opts?: { before?: string | null; lazyDetails?: boolean },
+ ): Promise<unknown> => ipcRenderer.invoke('local-db:messages:view', sessionId, opts),
+ workDetails: (
+ sessionId: string,
+ ref: unknown,
+ opts?: { after?: string | null },
+ ): Promise<unknown> =>
ipcRenderer.invoke('local-db:messages:work-details', sessionId, ref, opts),
list: (
sessionId: string,
@@ -5830,7 +5893,13 @@ contextBridge.exposeInMainWorld('electronAPI', {
ipcRenderer.invoke('maker:get-workflow-progress', sessionId, taskId),
// 模型供应商目录(只读)—— 内置目录元数据 + 各供应商实时连接状态。
- setProviderPresentation: (input: { providerId?: string; action: 'rename' | 'remove' | 'restore'; name?: string; dataOwnerId: string | null; ownerGeneration: number }): Promise<void> => ipcRenderer.invoke('maker:provider:presentation:set', input),
+ setProviderPresentation: (input: {
+ providerId?: string;
+ action: 'rename' | 'remove' | 'restore';
+ name?: string;
+ dataOwnerId: string | null;
+ ownerGeneration: number;
+ }): Promise<void> => ipcRenderer.invoke('maker:provider:presentation:set', input),
listProviders: (): Promise<{
dataOwnerId: string | null;
ownerGeneration: number;
@@ -5861,8 +5930,17 @@ contextBridge.exposeInMainWorld('electronAPI', {
options?: CustomProviderUpdateOptions,
): Promise<CustomProviderUpdateResult> =>
ipcRenderer.invoke('maker:provider:custom:update', config, keys, options),
- disconnectCustomProvider: (providerId: string, ownerScope?: { dataOwnerId: string | null; ownerGeneration: number }, options?: CustomProviderUpdateOptions): Promise<CustomProviderUpdateResult> => ipcRenderer.invoke('maker:provider:custom:disconnect', providerId, ownerScope, options),
- deleteCustomProvider: (providerId: string, ownerScope?: { dataOwnerId: string | null; ownerGeneration: number }, options?: CustomProviderUpdateOptions): Promise<CustomProviderUpdateResult> =>
+ disconnectCustomProvider: (
+ providerId: string,
+ ownerScope?: { dataOwnerId: string | null; ownerGeneration: number },
+ options?: CustomProviderUpdateOptions,
+ ): Promise<CustomProviderUpdateResult> =>
+ ipcRenderer.invoke('maker:provider:custom:disconnect', providerId, ownerScope, options),
+ deleteCustomProvider: (
+ providerId: string,
+ ownerScope?: { dataOwnerId: string | null; ownerGeneration: number },
+ options?: CustomProviderUpdateOptions,
+ ): Promise<CustomProviderUpdateResult> =>
ipcRenderer.invoke('maker:provider:custom:delete', providerId, ownerScope, options),
/** 自定义供应商创建模板(目录 presets 段,纯 UI 模板数据)。 */
listProviderPresets: (): Promise<{
@@ -5990,9 +6068,12 @@ contextBridge.exposeInMainWorld('electronAPI', {
onLocalModelInstallProgress: fanOutMakerLocalModelInstallProgress,
// 自定义 MCP 服务器配置 CRUD(可选 bearer token 另走通用 safeStorage IPC,不经这里)。
- listCustomMcpServers: (context?: import('../shared/customMcp').CustomMcpListContext): Promise<import('../shared/customMcp').CustomMcpListResult> => context === undefined
- ? ipcRenderer.invoke('maker:mcp:custom:list')
- : ipcRenderer.invoke('maker:mcp:custom:list', context),
+ listCustomMcpServers: (
+ context?: import('../shared/customMcp').CustomMcpListContext,
+ ): Promise<import('../shared/customMcp').CustomMcpListResult> =>
+ context === undefined
+ ? ipcRenderer.invoke('maker:mcp:custom:list')
+ : ipcRenderer.invoke('maker:mcp:custom:list', context),
createCustomMcpServer: (
config: import('../shared/customMcp').CustomMcpConfig,
): Promise<{ ok: true }> => ipcRenderer.invoke('maker:mcp:custom:create', config),
@@ -6052,7 +6133,11 @@ contextBridge.exposeInMainWorld('electronAPI', {
options?: { ownerId?: string; method?: 'browser' | 'device' },
): Promise<{ ok: boolean; reason?: string }> =>
ipcRenderer.invoke('maker:provider:oauth:login', providerId, options),
- providerOAuthLogout: (providerId: string, ownerScope?: { dataOwnerId: string | null; ownerGeneration: number }, options?: CustomProviderUpdateOptions): Promise<CustomProviderUpdateResult> =>
+ providerOAuthLogout: (
+ providerId: string,
+ ownerScope?: { dataOwnerId: string | null; ownerGeneration: number },
+ options?: CustomProviderUpdateOptions,
+ ): Promise<CustomProviderUpdateResult> =>
ipcRenderer.invoke('maker:provider:oauth:logout', providerId, ownerScope, options),
providerOAuthCancel: (
providerId: string,
@@ -6182,7 +6267,9 @@ contextBridge.exposeInMainWorld('electronAPI', {
// Renderer 通过这四个调用合并三路数据 + 触发 desktop 命令 execute。
// 老 scanSlashCommands 已下线 —— 数据等价于 listAgentSkills, 改名是为了和
// listAgentCommands / listDesktopCommands 形成清晰的 "三源 + execute" 命名族。
- listDesktopCommands: (ctx?: { deviceId?: string }): Promise<{
+ listDesktopCommands: (ctx?: {
+ deviceId?: string;
+ }): Promise<{
success: boolean;
error?: string;
commands?: Array<{ kind: 'desktop'; name: string; description: string }>;
@@ -6600,11 +6687,15 @@ contextBridge.exposeInMainWorld('electronAPI', {
/** Dedicated signed input transport; never uses the ordinary remote invoke API. */
submitRemotePluginSecret: (request: LocalPluginSecretRequest): Promise<{ accepted: boolean }> =>
ipcRenderer.invoke('plugin-oauth:submit-secret', request),
- submitRemotePluginConnection: (request: import('../shared/pluginOauth').LocalPluginConnectionRequest): Promise<{ accepted: boolean }> =>
+ submitRemotePluginConnection: (
+ request: import('../shared/pluginOauth').LocalPluginConnectionRequest,
+ ): Promise<{ accepted: boolean }> =>
ipcRenderer.invoke('plugin-oauth:submit-connection', request),
/** Ephemeral user-entered device code for this frame's active card; no callback code or token. */
- pluginOauthDeviceCode: (request: import('../shared/pluginOauthDeviceCode').PluginOauthDeviceCodeRequest): Promise<import('../shared/pluginOauthDeviceCode').PluginOauthDeviceCodeView | null> =>
+ pluginOauthDeviceCode: (
+ request: import('../shared/pluginOauthDeviceCode').PluginOauthDeviceCodeRequest,
+ ): Promise<import('../shared/pluginOauthDeviceCode').PluginOauthDeviceCodeView | null> =>
ipcRenderer.invoke('plugin-oauth:device-code', request),
/** Local-only Secret handoff; Main verifies this is Cindy's trusted top-level frame. */
@@ -7079,17 +7170,27 @@ contextBridge.exposeInMainWorld('electronAPI', {
// 可选 loginKey 将取消限定到对应尝试;省略时兼容已有调用。
claudeOAuthStatus: (): Promise<{ authorized: boolean }> =>
ipcRenderer.invoke('maker:claude-oauth:status'),
- claudeOAuthLogin: (loginKey?: string): Promise<{ ok: boolean; authorized: boolean; reason?: string }> =>
+ claudeOAuthLogin: (
+ loginKey?: string,
+ ): Promise<{ ok: boolean; authorized: boolean; reason?: string }> =>
ipcRenderer.invoke('maker:claude-oauth:login', loginKey),
- claudeOAuthLogout: (ownerScope?: { dataOwnerId: string | null; ownerGeneration: number }): Promise<{ authorized: boolean }> =>
+ claudeOAuthLogout: (ownerScope?: {
+ dataOwnerId: string | null;
+ ownerGeneration: number;
+ }): Promise<{ authorized: boolean }> =>
ipcRenderer.invoke('maker:claude-oauth:logout', ownerScope),
claudeOAuthCancel: (loginKey?: string): Promise<{ authorized: boolean }> =>
ipcRenderer.invoke('maker:claude-oauth:cancel', loginKey),
// xAI(SuperGrok 订阅)OAuth —— 与 claudeOAuth* 同形态。
- xaiOAuthLogin: (method?: 'browser' | 'device'): Promise<{ ok: boolean; authorized: boolean; reason?: string }> =>
+ xaiOAuthLogin: (
+ method?: 'browser' | 'device',
+ ): Promise<{ ok: boolean; authorized: boolean; reason?: string }> =>
ipcRenderer.invoke('maker:xai-oauth:login', method),
- xaiOAuthLogout: (ownerScope?: { dataOwnerId: string | null; ownerGeneration: number }): Promise<{ authorized: boolean }> =>
+ xaiOAuthLogout: (ownerScope?: {
+ dataOwnerId: string | null;
+ ownerGeneration: number;
+ }): Promise<{ authorized: boolean }> =>
ipcRenderer.invoke('maker:xai-oauth:logout', ownerScope),
xaiOAuthCancel: (): Promise<{ authorized: boolean }> =>
ipcRenderer.invoke('maker:xai-oauth:cancel'),
@@ -7249,8 +7350,9 @@ contextBridge.exposeInMainWorld('electronAPI', {
): Promise<{ title: string | null }> =>
ipcRenderer.invoke('maker:generate-title', { message, agentKind, sessionId }),
// Optional status copy: only public semantic phases cross this boundary.
- polishWorkingStatus: (request: import('../shared/workingStatus').WorkingStatusRequest): Promise<{ text: string | null }> =>
- ipcRenderer.invoke('maker:working-status', request),
+ polishWorkingStatus: (
+ request: import('../shared/workingStatus').WorkingStatusRequest,
+ ): Promise<{ text: string | null }> => ipcRenderer.invoke('maker:working-status', request),
// 重命名输入框 Magic 按钮:按会话最新对话内容重新生成标题(素材由 main 读 DB)
regenerateSessionTitle: (sessionId: string): Promise<{ title: string | null }> =>
ipcRenderer.invoke('maker:regenerate-title', { sessionId }),
@@ -7338,8 +7440,10 @@ contextBridge.exposeInMainWorld('electronAPI', {
agentKind: 'claude-code' | 'codex' | 'pi',
options?: { releaseOwner?: boolean; ownerId?: string },
): Promise<void> => ipcRenderer.invoke('maker:auth:cancel-login', agentKind, options),
- logout: (agentKind: 'claude-code' | 'codex' | 'pi', ownerScope?: { dataOwnerId: string | null; ownerGeneration: number }): Promise<void> =>
- ipcRenderer.invoke('maker:auth:logout', agentKind, ownerScope),
+ logout: (
+ agentKind: 'claude-code' | 'codex' | 'pi',
+ ownerScope?: { dataOwnerId: string | null; ownerGeneration: number },
+ ): Promise<void> => ipcRenderer.invoke('maker:auth:logout', agentKind, ownerScope),
onStateChanged: fanOutMakerAuthStateChanged,
onLoginProgress: fanOutMakerAuthLoginProgress,
},
@@ -7347,7 +7451,9 @@ contextBridge.exposeInMainWorld('electronAPI', {
piKernel: {
getState: (check = false): Promise<import('../shared/piKernel').PiKernelState> =>
ipcRenderer.invoke('maker:agent:pi-kernel-state', check),
- install: (request: import('../shared/piKernel').PiKernelInstallRequest): Promise<import('../shared/piKernel').PiKernelState> =>
+ install: (
+ request: import('../shared/piKernel').PiKernelInstallRequest,
+ ): Promise<import('../shared/piKernel').PiKernelState> =>
ipcRenderer.invoke('maker:agent:pi-kernel-install', request),
},
@@ -7374,8 +7480,10 @@ contextBridge.exposeInMainWorld('electronAPI', {
usage: {
getToday: (agentKind: 'claude-code' | 'codex' | 'pi'): Promise<unknown> =>
ipcRenderer.invoke('maker:usage:today', agentKind),
- getAccount: (agentKind: 'claude-code' | 'codex' | 'pi', providerId?: string): Promise<unknown> =>
- ipcRenderer.invoke('maker:usage:account', agentKind, providerId),
+ getAccount: (
+ agentKind: 'claude-code' | 'codex' | 'pi',
+ providerId?: string,
+ ): Promise<unknown> => ipcRenderer.invoke('maker:usage:account', agentKind, providerId),
/** Codex app-server authoritative windows and banked reset-credit metadata. */
getCodexRateLimits: (providerId?: string): Promise<MobileCodexRateLimitsResult> =>
ipcRenderer.invoke('maker:usage:codex-rate-limits', providerId),
@@ -7406,27 +7514,35 @@ contextBridge.exposeInMainWorld('electronAPI', {
onClaudeAccountChanged: fanOutMakerUsageClaudeAccount,
/** Codex 订阅用量推送 (WHAM 后台刷新成功后 best-effort 推送)。 */
onCodexAccountChanged: (cb: (payload: unknown) => void, providerId = 'openai') =>
- providerId === 'openai' ? fanOutMakerUsageCodexAccount(cb) : fanOutMakerUsageCodexProviderAccount((payload: unknown) => {
- const scoped = payload as { providerId?: string; snapshot?: unknown };
- if (scoped?.providerId === providerId) cb(scoped.snapshot);
- }),
+ providerId === 'openai'
+ ? fanOutMakerUsageCodexAccount(cb)
+ : fanOutMakerUsageCodexProviderAccount((payload: unknown) => {
+ const scoped = payload as { providerId?: string; snapshot?: unknown };
+ if (scoped?.providerId === providerId) cb(scoped.snapshot);
+ }),
/** xAI(SuperGrok bridge)限流快照推送 (bridge 每个成功上游响应解析 x-ratelimit-* 后推送)。 */
onXaiRateLimitChanged: (cb: (payload: unknown) => void, providerId = 'xai') =>
- providerId === 'xai' ? fanOutMakerUsageXaiRateLimit(cb) : fanOutMakerUsageXaiProviderRateLimit((payload: unknown) => {
- const scoped = payload as { providerId?: string; snapshot?: unknown };
- if (scoped?.providerId === providerId) cb(scoped.snapshot);
- }),
+ providerId === 'xai'
+ ? fanOutMakerUsageXaiRateLimit(cb)
+ : fanOutMakerUsageXaiProviderRateLimit((payload: unknown) => {
+ const scoped = payload as { providerId?: string; snapshot?: unknown };
+ if (scoped?.providerId === providerId) cb(scoped.snapshot);
+ }),
/** Claude 订阅余量推送 (端点后台刷新 / proxy 旁路 headers 更新时推送)。 */
onClaudeSubscriptionChanged: (cb: (payload: unknown) => void, providerId = 'anthropic') =>
- providerId === 'anthropic' ? fanOutMakerUsageClaudeSubscription(cb) : fanOutSubscriptionProviderAccount((payload: unknown) => {
- const scoped = payload as { providerId?: string; snapshot?: unknown };
- if (scoped?.providerId === providerId) cb(scoped.snapshot);
- }),
+ providerId === 'anthropic'
+ ? fanOutMakerUsageClaudeSubscription(cb)
+ : fanOutSubscriptionProviderAccount((payload: unknown) => {
+ const scoped = payload as { providerId?: string; snapshot?: unknown };
+ if (scoped?.providerId === providerId) cb(scoped.snapshot);
+ }),
onXaiSubscriptionChanged: (cb: (payload: unknown) => void, providerId = 'xai') =>
- providerId === 'xai' ? fanOutMakerUsageXaiSubscription(cb) : fanOutSubscriptionProviderAccount((payload: unknown) => {
- const scoped = payload as { providerId?: string; snapshot?: unknown };
- if (scoped?.providerId === providerId) cb(scoped.snapshot);
- }),
+ providerId === 'xai'
+ ? fanOutMakerUsageXaiSubscription(cb)
+ : fanOutSubscriptionProviderAccount((payload: unknown) => {
+ const scoped = payload as { providerId?: string; snapshot?: unknown };
+ if (scoped?.providerId === providerId) cb(scoped.snapshot);
+ }),
},
// ── Scheduler (Phase 4) ────────────────────────────────────────────────
@@ -7592,7 +7708,11 @@ contextBridge.exposeInMainWorld('electronAPI', {
// ── Plugin system (Phase 1) ──────────────────────────────────────────
plugins: {
- list: (workingDir?: string, includeHidden?: boolean, botContext?: Omit<BotToolsetContext, 'workingDir'>): Promise<PluginListItem[]> =>
+ list: (
+ workingDir?: string,
+ includeHidden?: boolean,
+ botContext?: Omit<BotToolsetContext, 'workingDir'>,
+ ): Promise<PluginListItem[]> =>
ipcRenderer.invoke('maker:plugins:list', workingDir, includeHidden, botContext),
getState: (
id: string,
diff --git a/apps/desktop/src/renderer/__tests__/githubAccountCard.test.tsx b/apps/desktop/src/renderer/__tests__/githubAccountCard.test.tsx
new file mode 100644
index 0000000000..f019a8235a
--- /dev/null
+++ b/apps/desktop/src/renderer/__tests__/githubAccountCard.test.tsx
@@ -0,0 +1,72 @@
+// @vitest-environment jsdom
+import { act, cleanup, render, screen, waitFor } from '@testing-library/react';
+import { afterEach, expect, it, vi } from 'vitest';
+import { GithubAccountCard } from '../features/cc-agent/GithubAccountCard';
+
+vi.mock('react-i18next', () => ({
+ useTranslation: () => ({
+ t: (key: string, args?: { login?: string }) => key + (args?.login ? ':' + args.login : ''),
+ }),
+}));
+vi.mock('../features/cc-agent/GithubConnectButton', () => ({
+ GithubConnectButton: ({ visible }: { visible: boolean }) =>
+ visible ? <button>connect</button> : null,
+}));
+afterEach(cleanup);
+const prefix = 'ccAgent.gitContext.pr.setup.account.';
+
+it('shows verified identity without asking an already connected user to connect', async () => {
+ window.electronAPI = {
+ gitContext: {
+ githubConnection: async () => ({ status: 'connected', login: 'dashhuang', source: 'gh-cli' }),
+ onGithubConnected: () => () => {},
+ },
+ } as any;
+ render(<GithubAccountCard onConnected={() => {}} />);
+ expect(await screen.findByText(prefix + 'connected:dashhuang')).toBeTruthy();
+ expect(screen.queryByText('connect')).toBeNull();
+ expect(screen.queryByText(prefix + 'recheck')).toBeNull();
+ expect(screen.getByText(prefix + 'gh-cli')).toBeTruthy();
+});
+
+it('refreshes credential changes and ignores an older in-flight response', async () => {
+ let changed = () => {};
+ let finishOld!: (value: any) => void;
+ const request = vi
+ .fn()
+ .mockImplementationOnce(
+ () =>
+ new Promise((resolve) => {
+ finishOld = resolve;
+ }),
+ )
+ .mockResolvedValue({ status: 'connected', login: 'new-account', source: 'token' });
+ window.electronAPI = {
+ gitContext: {
+ githubConnection: request,
+ onGithubConnected: (callback: () => void) => {
+ changed = callback;
+ return () => {};
+ },
+ },
+ } as any;
+ render(<GithubAccountCard onConnected={() => {}} />);
+ await act(async () => changed());
+ expect(await screen.findByText(prefix + 'connected:new-account')).toBeTruthy();
+ await act(async () => finishOld({ status: 'missing' }));
+ expect(screen.queryByText('connect')).toBeNull();
+ expect(screen.getByText(prefix + 'token')).toBeTruthy();
+});
+
+it('does not misrepresent a network failure as a request to log in', async () => {
+ window.electronAPI = {
+ gitContext: {
+ githubConnection: async () => ({ status: 'network', source: 'gh-cli' }),
+ onGithubConnected: () => () => {},
+ },
+ } as any;
+ render(<GithubAccountCard onConnected={() => {}} />);
+ await waitFor(() => expect(screen.getByText(prefix + 'network')).toBeTruthy());
+ expect(screen.queryByText('connect')).toBeNull();
+ expect(screen.getByText(prefix + 'recheck')).toBeTruthy();
+});
diff --git a/apps/desktop/src/renderer/__tests__/githubSetup.test.tsx b/apps/desktop/src/renderer/__tests__/githubSetup.test.tsx
new file mode 100644
index 0000000000..0ded7b33b8
--- /dev/null
+++ b/apps/desktop/src/renderer/__tests__/githubSetup.test.tsx
@@ -0,0 +1,204 @@
+// @vitest-environment jsdom
+import { useEffect } from 'react';
+import { act, cleanup, fireEvent, render, screen, waitFor } from '@testing-library/react';
+import { afterEach, describe, expect, it, vi } from 'vitest';
+import { GithubSetupDialog } from '../features/cc-agent/GithubSetupDialog';
+import { GitContextBadge } from '../features/cc-agent/GitContextBadge';
+import { Tooltip } from '../components/ui/tooltip';
+import { PrRefsProvider, usePrActions, usePrStatus } from '../contexts/PrRefsContext';
+
+vi.mock('react-i18next', () => ({ useTranslation: () => ({ t: (key: string) => key }) }));
+vi.mock('@/contexts/AuthContext', () => ({ useAuth: () => ({ dataOwnerId: 'local-v1' }) }));
+vi.mock('@/hooks/useSessionGitContext', () => ({
+ useSessionGitContext: () => ({
+ head: null,
+ branchSource: null,
+ prRefs: [
+ { id: 'ref', owner: 'o', repo: 'r', prNumber: 1, url: 'https://github.com/o/r/pull/1' },
+ ],
+ prStatuses: new Map([['o/r#1', { ok: false, reason: 'gh-missing' }]]),
+ }),
+}));
+afterEach(cleanup);
+const key = 'ccAgent.gitContext.pr.setup';
+
+describe('GitHub setup UI', () => {
+ it('ignores outside clicks during authorization but still allows explicit cancellation', async () => {
+ const close = vi.fn();
+ const cancel = vi.fn(async () => ({ phase: 'cancelled' }));
+ window.electronAPI = {
+ gitContext: {
+ githubSetupStatus: async () => ({ phase: 'authorizing', userCode: 'ABCD-1234' }),
+ cancelGithubSetup: cancel,
+ },
+ } as any;
+ render(<GithubSetupDialog onClose={close} />);
+ await screen.findByText('ABCD-1234');
+ // Radix installs its document pointer listener after mount.
+ await act(async () => {
+ await new Promise((resolve) => setTimeout(resolve, 10));
+ });
+ fireEvent.pointerDown(document.body, { pointerType: 'mouse', button: 0 });
+ fireEvent.click(document.body);
+ expect(close).not.toHaveBeenCalled();
+ expect(cancel).not.toHaveBeenCalled();
+ fireEvent.click(screen.getByText(`${key}.cancel`));
+ await waitFor(() => expect(close).toHaveBeenCalledOnce());
+ expect(cancel).toHaveBeenCalledOnce();
+ });
+ it('opens setup from a missing-gh PR badge without depending on a composer', async () => {
+ window.electronAPI = {
+ gitContext: { githubSetupStatus: async () => ({ phase: 'idle' }) },
+ } as any;
+ render(
+ <Tooltip.Provider>
+ <GitContextBadge session={{ id: 'task' } as any} />
+ </Tooltip.Provider>,
+ );
+ fireEvent.click(screen.getByText('#1'));
+ expect(await screen.findByRole('dialog')).toBeTruthy();
+ expect(screen.getByText(`${key}.install`)).toBeTruthy();
+ });
+ it('requires the connect action, shows the code and opens only GitHub device authorization', async () => {
+ const start = vi.fn(async () => ({ phase: 'authorizing', userCode: 'ABCD-1234' }));
+ const status = vi.fn(async () => ({ phase: 'idle' }));
+ const openExternal = vi.fn();
+ window.electronAPI = {
+ gitContext: { githubSetupStatus: status, startGithubSetup: start },
+ openExternal,
+ } as any;
+ render(<GithubSetupDialog onClose={() => {}} />);
+ await waitFor(() => expect(status).toHaveBeenCalled());
+ expect(start).not.toHaveBeenCalled();
+ status.mockResolvedValue({ phase: 'authorizing', userCode: 'ABCD-1234' } as any);
+ fireEvent.click(screen.getByText(`${key}.connect`));
+ expect(await screen.findByText('ABCD-1234')).toBeTruthy();
+ await act(async () => {
+ fireEvent.click(screen.getByText(`${key}.openBrowser`));
+ });
+ expect(openExternal).toHaveBeenCalledWith('https://github.com/login/device');
+ });
+
+ it('uses the shared download meter and cancels before closing a running download', async () => {
+ const close = vi.fn();
+ const cancel = vi.fn(async () => ({ phase: 'cancelled' }));
+ window.electronAPI = {
+ gitContext: {
+ githubSetupStatus: async () => ({ phase: 'downloading', percent: 42 }),
+ cancelGithubSetup: cancel,
+ },
+ } as any;
+ render(<GithubSetupDialog onClose={close} initialAction="install" />);
+ expect((await screen.findByRole('progressbar')).getAttribute('aria-valuenow')).toBe('42');
+ expect(document.querySelector('progress')).toBeNull();
+ fireEvent.click(screen.getByText(`${key}.cancel`));
+ await waitFor(() => expect(close).toHaveBeenCalledOnce());
+ expect(cancel).toHaveBeenCalledOnce();
+ expect(cancel.mock.invocationCallOrder[0]).toBeLessThan(close.mock.invocationCallOrder[0]);
+ });
+
+ it('shows only Done after successful connection, and ignores stale success when reopened', async () => {
+ const close = vi.fn();
+ window.electronAPI = {
+ gitContext: {
+ githubSetupStatus: async () => ({ phase: 'connected' }),
+ startGithubSetup: async () => ({ phase: 'connected' }),
+ },
+ } as any;
+ render(<GithubSetupDialog onClose={close} />);
+ expect(screen.queryByText(`${key}.done`)).toBeNull();
+ fireEvent.click(screen.getByText(`${key}.connect`));
+ fireEvent.click(await screen.findByText(`${key}.done`));
+ expect(close).toHaveBeenCalledOnce();
+ expect(screen.queryByText(`${key}.cancel`)).toBeNull();
+ expect(screen.queryByText(`${key}.connect`)).toBeNull();
+ });
+
+ it('keeps action failures visible and offers a retry', async () => {
+ window.electronAPI = {
+ gitContext: {
+ githubSetupStatus: async () => ({ phase: 'idle' }),
+ startGithubSetup: async () => {
+ throw new Error('unavailable');
+ },
+ },
+ } as any;
+ render(<GithubSetupDialog onClose={() => {}} />);
+ fireEvent.click(screen.getByText(`${key}.connect`));
+ expect(await screen.findByText(`${key}.stages.unavailable.title`)).toBeTruthy();
+ expect(screen.getByText(`${key}.retry`)).toBeTruthy();
+ });
+
+ it('does not ask users to open GitHub until a device code is available', async () => {
+ window.electronAPI = {
+ gitContext: {
+ githubSetupStatus: async () => ({ phase: 'authorizing' }),
+ },
+ } as any;
+ render(<GithubSetupDialog onClose={() => {}} />);
+ expect(await screen.findByText(`${key}.stages.preparing.title`)).toBeTruthy();
+ expect(screen.queryByText(`${key}.openBrowser`)).toBeNull();
+ });
+
+ it('refreshes mounted PR consumers immediately and rejects a pre-login response', async () => {
+ const ref = {
+ id: 'ref',
+ sessionId: 'task',
+ owner: 'o',
+ repo: 'r',
+ prNumber: 1,
+ url: '',
+ firstSeenAt: 1,
+ lastSeenAt: 1,
+ };
+ let connected!: () => void;
+ let finishOld!: (result: unknown[]) => void;
+ const getPrStatuses = vi
+ .fn()
+ .mockImplementationOnce(
+ () =>
+ new Promise((resolve) => {
+ finishOld = resolve;
+ }),
+ )
+ .mockResolvedValue([
+ {
+ ...ref,
+ ok: true,
+ status: 'merged',
+ title: 'Merged',
+ branch: 'branch',
+ htmlUrl: '',
+ unresolvedCount: 0,
+ },
+ ]);
+ window.electronAPI = {
+ gitContext: {
+ listAllPrRefs: async () => [ref],
+ listPrRefs: async () => [ref],
+ getPrStatuses,
+ onPrRefsChanged: () => () => {},
+ onGithubConnected: (cb: () => void) => {
+ connected = cb;
+ return () => {};
+ },
+ },
+ } as any;
+ function BadgeConsumer() {
+ const { registerPrConsumer } = usePrActions();
+ useEffect(() => registerPrConsumer('task'), [registerPrConsumer]);
+ const status = usePrStatus('task', 'o/r#1');
+ return <span>{status?.ok ? status.status : 'unknown'}</span>;
+ }
+ render(
+ <PrRefsProvider>
+ <BadgeConsumer />
+ </PrRefsProvider>,
+ );
+ await waitFor(() => expect(getPrStatuses).toHaveBeenCalledOnce());
+ act(() => connected());
+ expect(await screen.findByText('merged')).toBeTruthy();
+ await act(async () => finishOld([{ ...ref, ok: false, reason: 'gh-missing' }]));
+ expect(screen.getByText('merged')).toBeTruthy();
+ });
+});
diff --git a/apps/desktop/src/renderer/cindy-brain/GhostSettingsWebview.tsx b/apps/desktop/src/renderer/cindy-brain/GhostSettingsWebview.tsx
index c8e80e0bdd..da21ebd826 100644
--- a/apps/desktop/src/renderer/cindy-brain/GhostSettingsWebview.tsx
+++ b/apps/desktop/src/renderer/cindy-brain/GhostSettingsWebview.tsx
@@ -1,5 +1,5 @@
import { Button } from '@/components/ui/button';
-import { useEffect, useRef, useState, type ReactNode } from 'react';
+import { Fragment, useEffect, useRef, useState, type ReactNode } from 'react';
import { useTranslation } from 'react-i18next';
import { CircleAlert, LayoutGrid, MoonStar } from 'lucide-react';
import type { WebviewTag } from 'electron';
@@ -132,10 +132,12 @@ function SettingsWebviewBody({
ghost,
appearance,
dataOwnerId,
+ hostAccount = false,
}: {
ghost: InstalledGhost;
appearance: 'settings' | 'plugin';
dataOwnerId: string | null;
+ hostAccount?: boolean;
}): ReactNode {
const [crashed, setCrashed] = useState(false);
const [generation, setGeneration] = useState(0);
@@ -226,6 +228,18 @@ function SettingsWebviewBody({
}
const prepareResponsiveLayout = webview
.executeJavaScript(RESPONSIVE_STYLE_SCRIPT)
+ .then(() => {
+ if (!hostAccount || manifest.id !== 'cindy-github') return;
+ // Compatibility with the official 1.2.7 settings page: the host owns
+ // account status and disclosure; keep the plugin's write-only PAT form.
+ return webview.executeJavaScript(`(() => {
+ const style = document.createElement('style');
+ style.textContent = '#legacy-account,#host-account,body>.label-row,body>.hint,#test{display:none!important} #other-methods>summary{display:none!important}';
+ document.head.appendChild(style);
+ const methods = document.getElementById('other-methods');
+ if (methods) methods.open = true;
+ })()`);
+ })
.catch(() => {});
// 结构 CSS 先落地再量(html/body 钉 auto 会改变 body 高,顺序反了首量
// 就是错值);脚本自带 id 守卫,dom-ready 因 guest 内跳转重入时幂等。
@@ -272,6 +286,7 @@ function SettingsWebviewBody({
fixedHeight,
dataOwnerId,
partitionClaim,
+ hostAccount,
]);
if (crashed) {
@@ -303,12 +318,16 @@ export function GhostSettingsWebview({
ghost,
title,
appearance = 'settings',
+ account,
+ reloadKey = 0,
}: {
ghost: InstalledGhost;
/** Product-facing section title; settings keeps the legacy fallback. */
title?: string;
/** Plugin detail uses the same shared surface as Tool and Permission cards. */
appearance?: 'settings' | 'plugin';
+ account?: ReactNode;
+ reloadKey?: number;
}): ReactNode {
const { t } = useTranslation();
const { mode, dataOwnerId } = useAuth();
@@ -324,20 +343,36 @@ export function GhostSettingsWebview({
: 'border-[var(--settings-theme-card-border)] bg-[var(--settings-theme-card-bg)]',
)}
>
- <div className="flex items-center gap-2">
- <LayoutGrid size={14} className="text-[var(--text-tertiary)]" />
- <p
- className={cn(
- 'font-medium text-[var(--text-primary)]',
- appearance === 'plugin' ? 'text-14 leading-[1.571]' : 'text-13',
- )}
- >
- {title ?? t('settings.ghosts.detail.customSlotTitle')}
- </p>
- </div>
- {ghost.enabled ? (
+ {!account && (
+ <div className="flex items-center gap-2">
+ <LayoutGrid size={14} className="text-[var(--text-tertiary)]" />
+ <p
+ className={cn(
+ 'font-medium text-[var(--text-primary)]',
+ appearance === 'plugin' ? 'text-14 leading-[1.571]' : 'text-13',
+ )}
+ >
+ {title ?? t('settings.ghosts.detail.customSlotTitle')}
+ </p>
+ </div>
+ )}
+ {ghost.enabled && <Fragment key={`account:${ownerKey}`}>{account}</Fragment>}
+ {ghost.enabled && account ? (
+ <details key={`methods:${ownerKey}`} className="group">
+ <summary className="w-fit cursor-pointer rounded-full py-2 text-12 text-[var(--text-secondary)] outline-none focus-visible:ring-2 focus-visible:ring-[var(--focus-ring)]">
+ {t('ccAgent.gitContext.pr.setup.account.otherMethods')}
+ </summary>
+ <SettingsWebviewBody
+ key={JSON.stringify([ownerKey, manifest.id, manifest.version, reloadKey])}
+ ghost={ghost}
+ appearance={appearance}
+ dataOwnerId={dataOwnerId}
+ hostAccount
+ />
+ </details>
+ ) : ghost.enabled ? (
<SettingsWebviewBody
- key={JSON.stringify([ownerKey, manifest.id, manifest.version])}
+ key={JSON.stringify([ownerKey, manifest.id, manifest.version, reloadKey])}
ghost={ghost}
appearance={appearance}
dataOwnerId={dataOwnerId}
diff --git a/apps/desktop/src/renderer/cindy-brain/__tests__/GhostSettingsWebview.test.tsx b/apps/desktop/src/renderer/cindy-brain/__tests__/GhostSettingsWebview.test.tsx
index 151778bbe4..6d007c17d5 100644
--- a/apps/desktop/src/renderer/cindy-brain/__tests__/GhostSettingsWebview.test.tsx
+++ b/apps/desktop/src/renderer/cindy-brain/__tests__/GhostSettingsWebview.test.tsx
@@ -96,6 +96,22 @@ function renderSettings(settingsHeight?: number, measuredHeight?: number) {
}
describe('GhostSettingsWebview layout ownership', () => {
+ it('keeps account status visible and the plugin form collapsed without a duplicate title', () => {
+ const { ghost, view } = renderSettings();
+ view.rerender(
+ <GhostSettingsWebview
+ ghost={ghost}
+ title="Duplicate title"
+ account={<span>Connected account</span>}
+ />,
+ );
+ expect(view.queryByText('Duplicate title')).toBeNull();
+ expect(view.getByText('Connected account')).toBeTruthy();
+ const disclosure = view.container.querySelector('details');
+ expect(disclosure).toBeTruthy();
+ expect(disclosure?.open).toBe(false);
+ expect(disclosure?.querySelector('webview')).toBeTruthy();
+ });
it('does not inject responsive width rules into fixed-height guests', async () => {
const { executeJavaScript, host } = renderSettings(360);
@@ -106,6 +122,24 @@ describe('GhostSettingsWebview layout ownership', () => {
expect(host.classList.contains('overflow-hidden')).toBe(false);
});
+ it('keeps exactly one account row across owner changes and repeated refreshes', () => {
+ const { ghost, view } = renderSettings();
+ for (const owner of ['owner-a', 'owner-b', 'owner-a', 'owner-c']) {
+ authState.dataOwnerId = owner;
+ for (let reloadKey = 0; reloadKey < 3; reloadKey++) {
+ view.rerender(
+ <GhostSettingsWebview
+ ghost={ghost}
+ reloadKey={reloadKey}
+ account={<span>Connected account</span>}
+ />,
+ );
+ expect(view.getAllByText('Connected account')).toHaveLength(1);
+ expect(view.container.querySelectorAll('details')).toHaveLength(1);
+ }
+ }
+ });
+
it('keeps responsive containment for auto-height guests', async () => {
const { executeJavaScript, host } = renderSettings();
@@ -149,7 +183,10 @@ describe('GhostSettingsWebview layout ownership', () => {
});
it.each([
- ['version', false], ['version', true], ['id', false], ['id', true],
+ ['version', false],
+ ['version', true],
+ ['id', false],
+ ['id', true],
] as const)('resets guest state when %s changes in place (cached: %s)', async (field, cached) => {
const { ghost, host, view, webview } = renderSettings(undefined, 432);
await waitFor(() => expect(host.style.height).toBe('432px'));
@@ -166,8 +203,9 @@ describe('GhostSettingsWebview layout ownership', () => {
expect(webview.isConnected).toBe(false);
expect(view.container.querySelector('webview')).not.toBe(webview);
// 新 guest 尚未 dom-ready,首帧也不能复用旧组件的高度。
- expect(view.container.querySelector<HTMLElement>('[data-ghost-webview]')?.style.height)
- .toBe(cached ? '240px' : '160px');
+ expect(view.container.querySelector<HTMLElement>('[data-ghost-webview]')?.style.height).toBe(
+ cached ? '240px' : '160px',
+ );
});
it('reopens a fresh guest with height-only spacing, without replaying or capturing old UI', async () => {
diff --git a/apps/desktop/src/renderer/components/settings/DownloadMeter.tsx b/apps/desktop/src/renderer/components/settings/DownloadMeter.tsx
index a7905a0cb6..51b8271b24 100644
--- a/apps/desktop/src/renderer/components/settings/DownloadMeter.tsx
+++ b/apps/desktop/src/renderer/components/settings/DownloadMeter.tsx
@@ -32,11 +32,15 @@ export function downloadPercent(progress: {
completed?: number;
total?: number;
}): number | null {
- if (progress.percent != null) return Math.min(100, Math.max(0, progress.percent));
- if (progress.total && progress.total > 0) {
- return Math.min(100, Math.round(((progress.completed ?? 0) / progress.total) * 100));
- }
- return null;
+ const raw =
+ progress.percent != null && Number.isFinite(progress.percent)
+ ? progress.percent
+ : progress.total && progress.total > 0
+ ? ((progress.completed ?? 0) / progress.total) * 100
+ : null;
+ if (raw === null || !Number.isFinite(raw)) return null;
+ // Keep raw transfer precision out of the label; only completed transfers show 100%.
+ return raw >= 100 ? 100 : Math.min(99, Math.max(0, Math.round(raw)));
}
export function DownloadMeter({ progress }: { progress: DownloadMeterProgress }) {
diff --git a/apps/desktop/src/renderer/components/settings/__tests__/DownloadMeter.test.ts b/apps/desktop/src/renderer/components/settings/__tests__/DownloadMeter.test.ts
index 89fa1c8c02..091dc05e58 100644
--- a/apps/desktop/src/renderer/components/settings/__tests__/DownloadMeter.test.ts
+++ b/apps/desktop/src/renderer/components/settings/__tests__/DownloadMeter.test.ts
@@ -21,4 +21,16 @@ describe('DownloadMeter formatters', () => {
expect(downloadPercent({ completed: 25, total: 100 })).toBe(25);
expect(downloadPercent({})).toBeNull();
});
+
+ it('displays whole percentages without claiming completion early', () => {
+ expect(downloadPercent({ percent: 43.123456789 })).toBe(43);
+ expect(downloadPercent({ percent: 99.99 })).toBe(99);
+ expect(downloadPercent({ completed: 9999, total: 10000 })).toBe(99);
+ expect(downloadPercent({ percent: 100 })).toBe(100);
+ expect(downloadPercent({ percent: 120 })).toBe(100);
+ expect(downloadPercent({ percent: -5 })).toBe(0);
+ expect(downloadPercent({ percent: NaN })).toBeNull();
+ expect(downloadPercent({ percent: Infinity })).toBeNull();
+ expect(downloadPercent({ percent: NaN, completed: 25, total: 100 })).toBe(25);
+ });
});
diff --git a/apps/desktop/src/renderer/contexts/PrRefsContext.tsx b/apps/desktop/src/renderer/contexts/PrRefsContext.tsx
index e163f6c0f4..3a0c2f8a17 100644
--- a/apps/desktop/src/renderer/contexts/PrRefsContext.tsx
+++ b/apps/desktop/src/renderer/contexts/PrRefsContext.tsx
@@ -188,7 +188,8 @@ function createPrCacheStore(): PrCacheStore {
notify();
},
clearAll() {
- if (refsBySession.size === 0 && statusesBySession.size === 0 && refreshErrors.size === 0) return;
+ if (refsBySession.size === 0 && statusesBySession.size === 0 && refreshErrors.size === 0)
+ return;
refreshErrors.clear();
refsBySession.clear();
statusesBySession.clear();
@@ -504,7 +505,11 @@ export function PrRefsProvider({ children }: { children: ReactNode }) {
const gen = ownerGenRef.current;
if (localRefsInFlight.current.get(sessionId) === gen) return;
const fetchedAt = localRefsFetchedAt.current.get(sessionId);
- if (!refsFailed && fetchedAt !== undefined && Date.now() - fetchedAt < PR_STATUS_REFRESH_INTERVAL_MS - 5_000) {
+ if (
+ !refsFailed &&
+ fetchedAt !== undefined &&
+ Date.now() - fetchedAt < PR_STATUS_REFRESH_INTERVAL_MS - 5_000
+ ) {
return;
}
localRefsInFlight.current.set(sessionId, gen);
@@ -559,6 +564,14 @@ export function PrRefsProvider({ children }: { children: ReactNode }) {
// 与聊天顶栏同一节拍的兜底刷新:周期 + 窗口聚焦。首查失败自愈;merged/closed
// 等远端状态变化也随节拍收敛(main / 被控端各有 60s TTL,重复查询便宜)。
useEffect(() => {
+ const unsubscribe = window.electronAPI.gitContext.onGithubConnected?.(() => {
+ // Discard pre-login responses, including requests still in flight. Both
+ // sidebar and header consumers immediately read the new identity.
+ ownerGenRef.current += 1;
+ for (const [sessionId, entry] of prConsumers.current) {
+ refreshConsumer(sessionId, entry.deviceId);
+ }
+ });
const refreshAll = () => {
// 失焦/隐藏时跳过周期刷新:没人在看,后台空转的查询(GitHub 配额 +
// device-link 隧道)纯属浪费;下面的 focus 监听会在回到前台的瞬间全量补一次,
@@ -572,6 +585,7 @@ export function PrRefsProvider({ children }: { children: ReactNode }) {
const interval = setInterval(refreshAll, PR_STATUS_REFRESH_INTERVAL_MS);
window.addEventListener('focus', refreshAll);
return () => {
+ unsubscribe?.();
clearInterval(interval);
window.removeEventListener('focus', refreshAll);
};
diff --git a/apps/desktop/src/renderer/features/cc-agent/GitContextBadge.tsx b/apps/desktop/src/renderer/features/cc-agent/GitContextBadge.tsx
index d159cb5614..937e658b7b 100644
--- a/apps/desktop/src/renderer/features/cc-agent/GitContextBadge.tsx
+++ b/apps/desktop/src/renderer/features/cc-agent/GitContextBadge.tsx
@@ -16,13 +16,14 @@
* closed GitPullRequestClosed --error-fg(语义红)
* 未知(查询失败) GitPullRequest + --text-tertiary,tooltip 给原因
*
- * 本机 gh 缺失 / 未登录时(prGuidanceFor):点击把安装 / 登录提示词填进当前任务
- * 输入框交给 Agent;tooltip 写明点击后果。不复用 unresolved 的
+ * 本机 gh 缺失 / 未登录时(prGuidanceFor):点击打开内置安装和设备码登录界面。
+ * 授权成功立即刷新状态。不复用 unresolved 的
* `--status-bar-accent` 5px 角点(DESIGN.md 该点只表示未解决 review)。
* SSH / device-link / review 只读任务不提供引导——点击无法兑现时仍打开 PR。
*/
import { GitBranch, GitPullRequest, MessageSquare } from 'lucide-react';
+import { useState } from 'react';
import { useTranslation } from 'react-i18next';
import { cn } from '@/lib/utils';
@@ -31,7 +32,7 @@ import { WINDOW_NO_DRAG_STYLE } from '@/components/layout/windowDrag';
import type { Session } from '@/lib/ccAgent.types';
import type { PrStatusKind, PrStatusResult, SessionPrRef } from '@/lib/gitContext.types';
import { useSessionGitContext } from '@/hooks/useSessionGitContext';
-import { hasPromptInsertSubscriber, insertPromptIntoComposer } from '@/lib/composerActionsBus';
+import { GithubSetupDialog } from './GithubSetupDialog';
import { prStatusKey, MAX_STATUS_QUERIES } from '@/lib/prStatus';
import {
PR_STATUS_COLOR,
@@ -92,7 +93,6 @@ export function GitContextBadge({ session }: { session: Session }) {
{prRefs.slice(0, MAX_STATUS_QUERIES).map((ref) => (
<PrChip
key={ref.id}
- sessionId={session.id}
remoteHostId={session.remoteHostId}
deviceLinkDeviceId={session.deviceLinkDeviceId}
readOnly={session.source === 'review'}
@@ -105,14 +105,12 @@ export function GitContextBadge({ session }: { session: Session }) {
}
function PrChip({
- sessionId,
remoteHostId,
deviceLinkDeviceId,
readOnly,
prRef,
status,
}: {
- sessionId: string;
remoteHostId?: string | null;
deviceLinkDeviceId?: string | null;
readOnly?: boolean;
@@ -120,6 +118,7 @@ function PrChip({
status: PrStatusResult | undefined;
}) {
const { t } = useTranslation();
+ const [setupOpen, setSetupOpen] = useState(false);
const kind: PrStatusKind | null = status?.ok ? status.status : null;
const Icon = kind ? PR_STATUS_ICON[kind] : GitPullRequest;
@@ -132,8 +131,7 @@ function PrChip({
: failureCopyKey
? t(failureCopyKey)
: t('ccAgent.gitContext.pr.statusUnknown');
- // 引导只在 Composer 真正写入后独占点击;没人接住(确认卡/接管/准备 worktree 等
- // 把 ChatInput 卸掉)必须退回打开 PR,不能空点。
+ // Installation and login are host-owned and independent of the task composer.
const actionLine = guidance
? t(`ccAgent.gitContext.pr.guidance.${guidance}.hint`)
: t('ccAgent.gitContext.pr.clickToOpen');
@@ -143,13 +141,8 @@ function PrChip({
const handleClick = () => {
if (guidance) {
- const accepted = insertPromptIntoComposer({
- targetSessionId: sessionId,
- text: t(`ccAgent.gitContext.pr.guidance.${guidance}.prompt`),
- });
- if (accepted) return;
- // Composer 挂着但拒绝写入(发送中 / 语音占用):保持已广告的引导动作,不改打开 PR。
- if (hasPromptInsertSubscriber(sessionId)) return;
+ setSetupOpen(true);
+ return;
}
void window.electronAPI.openExternal(prRef.url);
};
@@ -158,49 +151,57 @@ function PrChip({
const unresolved = status?.ok && status.unresolvedCount ? status.unresolvedCount : 0;
return (
- <Tooltip.Root>
- <Tooltip.Trigger asChild>
- <button
- type="button"
- onClick={handleClick}
- aria-label={ariaLabel}
- data-pr-guidance={guidance ?? undefined}
- style={WINDOW_NO_DRAG_STYLE}
- className={cn(
- 'inline-flex shrink-0 items-center gap-1 rounded-md px-1.5 py-0.5',
- 'text-xs text-[var(--cmd-palette-item-meta)]',
- 'hover:bg-titlebar-button-hover hover:text-foreground',
- 'transition-colors focus-visible:outline-none',
- )}
- >
- <Icon size={12} strokeWidth={1.5} className="shrink-0" style={{ color }} />
- <span>#{prRef.prNumber}</span>
- {unresolved > 0 && (
- <span
- className="inline-flex items-center gap-0.5 text-10 font-medium leading-none"
- style={{ color: 'var(--status-bar-accent)' }}
- aria-label={t('ccAgent.gitContext.pr.unresolved', { count: unresolved })}
- >
- <MessageSquare size={9} strokeWidth={2} className="shrink-0" />
- {unresolved > 99 ? '99+' : unresolved}
+ <>
+ {setupOpen && (
+ <GithubSetupDialog
+ initialAction={guidance ?? 'login'}
+ onClose={() => setSetupOpen(false)}
+ />
+ )}
+ <Tooltip.Root>
+ <Tooltip.Trigger asChild>
+ <button
+ type="button"
+ onClick={handleClick}
+ aria-label={ariaLabel}
+ data-pr-guidance={guidance ?? undefined}
+ style={WINDOW_NO_DRAG_STYLE}
+ className={cn(
+ 'inline-flex shrink-0 items-center gap-1 rounded-md px-1.5 py-0.5',
+ 'text-xs text-[var(--cmd-palette-item-meta)]',
+ 'hover:bg-titlebar-button-hover hover:text-foreground',
+ 'transition-colors focus-visible:outline-none',
+ )}
+ >
+ <Icon size={12} strokeWidth={1.5} className="shrink-0" style={{ color }} />
+ <span>#{prRef.prNumber}</span>
+ {unresolved > 0 && (
+ <span
+ className="inline-flex items-center gap-0.5 text-10 font-medium leading-none"
+ style={{ color: 'var(--status-bar-accent)' }}
+ aria-label={t('ccAgent.gitContext.pr.unresolved', { count: unresolved })}
+ >
+ <MessageSquare size={9} strokeWidth={2} className="shrink-0" />
+ {unresolved > 99 ? '99+' : unresolved}
+ </span>
+ )}
+ </button>
+ </Tooltip.Trigger>
+ <Tooltip.Content side="bottom" variant="mono">
+ <div className="flex max-w-72 flex-col gap-0.5">
+ <span className="truncate">
+ {prRef.owner}/{prRef.repo}#{prRef.prNumber}
+ {status?.ok ? ` · ${status.title}` : ''}
</span>
- )}
- </button>
- </Tooltip.Trigger>
- <Tooltip.Content side="bottom" variant="mono">
- <div className="flex max-w-72 flex-col gap-0.5">
- <span className="truncate">
- {prRef.owner}/{prRef.repo}#{prRef.prNumber}
- {status?.ok ? ` · ${status.title}` : ''}
- </span>
- <span>{statusLine}</span>
- {unresolved > 0 && (
- <span>{t('ccAgent.gitContext.pr.unresolved', { count: unresolved })}</span>
- )}
- {/* tooltip 两模式都是深底白字(--tooltip-text),次级信息用透明度而不是页面级 token。 */}
- <span className="opacity-70">{actionLine}</span>
- </div>
- </Tooltip.Content>
- </Tooltip.Root>
+ <span>{statusLine}</span>
+ {unresolved > 0 && (
+ <span>{t('ccAgent.gitContext.pr.unresolved', { count: unresolved })}</span>
+ )}
+ {/* tooltip 两模式都是深底白字(--tooltip-text),次级信息用透明度而不是页面级 token。 */}
+ <span className="opacity-70">{actionLine}</span>
+ </div>
+ </Tooltip.Content>
+ </Tooltip.Root>
+ </>
);
}
diff --git a/apps/desktop/src/renderer/features/cc-agent/GithubAccountCard.tsx b/apps/desktop/src/renderer/features/cc-agent/GithubAccountCard.tsx
new file mode 100644
index 0000000000..37dff6c4a6
--- /dev/null
+++ b/apps/desktop/src/renderer/features/cc-agent/GithubAccountCard.tsx
@@ -0,0 +1,65 @@
+import { useCallback, useEffect, useRef, useState } from 'react';
+import { useTranslation } from 'react-i18next';
+import { Button } from '@/components/ui/button';
+import { GithubConnectButton } from './GithubConnectButton';
+import type { GithubConnectionState } from '../../../shared/githubSetup';
+
+/** Account verification belongs to the trusted host, not the plugin webview. */
+export function GithubAccountCard({ onConnected }: { onConnected(): void }) {
+ const { t } = useTranslation();
+ const [state, setState] = useState<GithubConnectionState>();
+ const [busy, setBusy] = useState(false);
+ const generation = useRef(0);
+ const refresh = useCallback(async () => {
+ const current = ++generation.current;
+ setBusy(true);
+ try {
+ const result = await window.electronAPI.gitContext.githubConnection();
+ if (current === generation.current) setState(result);
+ } catch {
+ if (current === generation.current) setState({ status: 'network' });
+ } finally {
+ if (current === generation.current) setBusy(false);
+ }
+ }, []);
+ useEffect(() => {
+ void refresh();
+ const onFocus = () => void refresh();
+ window.addEventListener('focus', onFocus);
+ const unsubscribe = window.electronAPI.gitContext.onGithubConnected(onFocus);
+ return () => {
+ generation.current++;
+ unsubscribe();
+ window.removeEventListener('focus', onFocus);
+ };
+ }, [refresh]);
+ const key = 'ccAgent.gitContext.pr.setup.account.';
+ return (
+ <div className="flex flex-wrap items-center gap-x-4 gap-y-2" aria-live="polite">
+ <div className="text-13 text-[var(--text-primary)]">
+ {t(key + (state?.status ?? 'checking'), {
+ login: state?.status === 'connected' ? state.login : '',
+ })}
+ </div>
+ {state?.source && (
+ <p className="text-12 text-[var(--text-secondary)]">{t(key + state.source)}</p>
+ )}
+ <div className="flex gap-2">
+ <GithubConnectButton
+ visible={
+ state?.status === 'missing' || (state?.status === 'auth' && state.source !== 'token')
+ }
+ onConnected={() => {
+ void refresh();
+ onConnected();
+ }}
+ />
+ {state && state.status !== 'missing' && state.status !== 'connected' && (
+ <Button variant="secondary" disabled={busy} onClick={() => void refresh()}>
+ {t(key + 'recheck')}
+ </Button>
+ )}
+ </div>
+ </div>
+ );
+}
diff --git a/apps/desktop/src/renderer/features/cc-agent/GithubConnectButton.tsx b/apps/desktop/src/renderer/features/cc-agent/GithubConnectButton.tsx
new file mode 100644
index 0000000000..46d050e0e4
--- /dev/null
+++ b/apps/desktop/src/renderer/features/cc-agent/GithubConnectButton.tsx
@@ -0,0 +1,26 @@
+import { useState } from 'react';
+import { useTranslation } from 'react-i18next';
+import { Button } from '@/components/ui/button';
+import { GithubSetupDialog } from './GithubSetupDialog';
+
+/** Local GitHub connection entry shared by feature pages. */
+export function GithubConnectButton({
+ onConnected,
+ visible = true,
+}: {
+ onConnected(): void;
+ visible?: boolean;
+}) {
+ const { t } = useTranslation();
+ const [open, setOpen] = useState(false);
+ return (
+ <>
+ {visible && (
+ <Button variant="secondary" onClick={() => setOpen(true)}>
+ {t('ccAgent.gitContext.pr.setup.stages.login.title')}
+ </Button>
+ )}
+ {open && <GithubSetupDialog onClose={() => setOpen(false)} onConnected={onConnected} />}
+ </>
+ );
+}
diff --git a/apps/desktop/src/renderer/features/cc-agent/GithubSetupDialog.tsx b/apps/desktop/src/renderer/features/cc-agent/GithubSetupDialog.tsx
new file mode 100644
index 0000000000..32a970e61d
--- /dev/null
+++ b/apps/desktop/src/renderer/features/cc-agent/GithubSetupDialog.tsx
@@ -0,0 +1,233 @@
+import { useEffect, useRef, useState } from 'react';
+import * as Dialog from '@radix-ui/react-dialog';
+import { Check, Copy } from 'lucide-react';
+import { useTranslation } from 'react-i18next';
+import { Button } from '@/components/ui/button';
+import { Spinner } from '@/components/ui/spinner';
+import { DownloadMeter } from '@/components/settings/DownloadMeter';
+import type { GithubSetupState } from '../../../shared/githubSetup';
+
+const isRunning = (phase: GithubSetupState['phase']) =>
+ ['checking', 'downloading', 'installing', 'authorizing'].includes(phase);
+
+export function GithubSetupDialog({
+ onClose,
+ onConnected,
+ initialAction = 'login',
+}: {
+ onClose(): void;
+ onConnected?(): void;
+ initialAction?: 'install' | 'login';
+}) {
+ const { t } = useTranslation();
+ // The badge changes during setup; keep the original entry reason.
+ const [entryAction] = useState(initialAction);
+ const [state, setState] = useState<GithubSetupState>({ phase: 'idle' });
+ const [pending, setPending] = useState(false);
+ const [failed, setFailed] = useState(false);
+ const [copiedCode, setCopiedCode] = useState<string>();
+ const [feedback, setFeedback] = useState<'copyFailed' | 'openFailed'>();
+ const [opening, setOpening] = useState(false);
+ const tracking = useRef(false);
+ const notified = useRef(false);
+ useEffect(() => {
+ if (state.phase === 'connected' && !notified.current) {
+ notified.current = true;
+ onConnected?.();
+ }
+ }, [state.phase, onConnected]);
+ const key = 'ccAgent.gitContext.pr.setup';
+ const copy = (name: string) => t(key + '.' + name);
+
+ useEffect(() => {
+ let stopped = false;
+ let timer: ReturnType<typeof setTimeout>;
+ const poll = async () => {
+ try {
+ const next = await window.electronAPI.gitContext.githubSetupStatus();
+ if (stopped) return;
+ if (isRunning(next.phase)) tracking.current = true;
+ // A previous run's terminal state does not validate a new attempt.
+ if (tracking.current) setState(next);
+ setFailed(false);
+ if (isRunning(next.phase)) timer = setTimeout(() => void poll(), 750);
+ } catch {
+ if (!stopped) setFailed(true);
+ }
+ };
+ if (!pending && !failed) void poll();
+ return () => {
+ stopped = true;
+ clearTimeout(timer);
+ };
+ }, [pending, failed]);
+
+ const start = async () => {
+ tracking.current = true;
+ setPending(true);
+ setFailed(false);
+ setFeedback(undefined);
+ setCopiedCode(undefined);
+ setState({ phase: 'checking' });
+ try {
+ setState(await window.electronAPI.gitContext.startGithubSetup());
+ } catch {
+ setFailed(true);
+ } finally {
+ setPending(false);
+ }
+ };
+ const active = isRunning(state.phase);
+ const dismiss = async () => {
+ if (pending) return;
+ if (!active) {
+ onClose();
+ return;
+ }
+ setPending(true);
+ try {
+ await window.electronAPI.gitContext.cancelGithubSetup();
+ onClose();
+ } catch {
+ setFailed(true);
+ } finally {
+ setPending(false);
+ }
+ };
+ const copyCode = async () => {
+ if (!state.userCode) return;
+ try {
+ await navigator.clipboard.writeText(state.userCode);
+ setCopiedCode(state.userCode);
+ setFeedback(undefined);
+ } catch {
+ setFeedback('copyFailed');
+ }
+ };
+ const openBrowser = async () => {
+ setOpening(true);
+ try {
+ await window.electronAPI.openExternal('https://github.com/login/device');
+ setFeedback(undefined);
+ } catch {
+ setFeedback('openFailed');
+ } finally {
+ setOpening(false);
+ }
+ };
+
+ const stage = failed
+ ? 'unavailable'
+ : state.phase === 'idle'
+ ? entryAction
+ : state.phase === 'authorizing' && !state.userCode
+ ? 'preparing'
+ : state.phase;
+ const description =
+ stage === 'error'
+ ? copy('errors.' + (state.error ?? 'login'))
+ : copy('stages.' + stage + '.description');
+ const readyToAuthorize = stage === 'authorizing' && Boolean(state.userCode);
+ const completed = stage === 'connected';
+ const retry = ['error', 'cancelled', 'unavailable'].includes(stage);
+ const unsupported = stage === 'error' && state.error === 'unsupported';
+
+ return (
+ <Dialog.Root
+ open
+ onOpenChange={(open) => {
+ if (!open) void dismiss();
+ }}
+ >
+ <Dialog.Portal>
+ <Dialog.Overlay className="fixed inset-0 z-[10000] bg-[var(--overlay-modal)]" />
+ <Dialog.Content
+ onInteractOutside={(event) => event.preventDefault()}
+ className="fixed left-1/2 top-1/2 z-[10001] flex max-h-[85vh] w-[min(400px,calc(100vw-32px))] -translate-x-1/2 -translate-y-1/2 flex-col gap-4 overflow-y-auto rounded-xl bg-[var(--confirm-bg)] p-4 shadow-[var(--confirm-shadow)] outline-none"
+ >
+ <div className="flex items-center gap-2" aria-live="polite">
+ {completed ? (
+ <Check size={18} className="text-[var(--confirm-title)]" aria-hidden="true" />
+ ) : (
+ active &&
+ !readyToAuthorize &&
+ !failed && <Spinner size={16} className="text-[var(--confirm-desc)]" />
+ )}
+ <Dialog.Title className="text-16 font-medium text-[var(--confirm-title)]">
+ {copy('stages.' + stage + '.title')}
+ </Dialog.Title>
+ </div>
+ <Dialog.Description className="text-13 leading-relaxed text-[var(--confirm-desc)]">
+ {description}
+ </Dialog.Description>
+ {stage === 'downloading' && (
+ <DownloadMeter progress={{ label: 'GitHub CLI', percent: state.percent }} />
+ )}
+ {readyToAuthorize && (
+ <div className="flex flex-col gap-3">
+ <div className="rounded-lg bg-[var(--surface-chip)] px-4 py-3">
+ <div className="mb-2 text-12 text-[var(--text-secondary)]">
+ {copy('deviceCode')}
+ </div>
+ <div className="flex items-center justify-between gap-3">
+ <code className="select-all whitespace-nowrap font-mono text-xl tracking-widest text-[var(--text-primary)]">
+ {state.userCode}
+ </code>
+ <button
+ type="button"
+ onClick={() => void copyCode()}
+ aria-label={copy(copiedCode === state.userCode ? 'copied' : 'copyCode')}
+ className="flex size-8 shrink-0 items-center justify-center rounded-full text-[var(--text-secondary)] hover:bg-[var(--surface-hover)] focus-visible:outline focus-visible:outline-2 focus-visible:outline-[var(--focus-ring)]"
+ >
+ {copiedCode === state.userCode ? <Check size={16} /> : <Copy size={16} />}
+ </button>
+ </div>
+ </div>
+ <span className="select-text text-12 text-[var(--text-tertiary)]">
+ github.com/login/device
+ </span>
+ </div>
+ )}
+ {feedback && (
+ <p role="alert" className="text-12 text-[var(--error-fg)]">
+ {copy(feedback)}
+ </p>
+ )}
+ <div className="flex justify-end gap-2 pt-1">
+ {completed || unsupported ? (
+ <Button palette="confirmation" onClick={onClose}>
+ {copy('done')}
+ </Button>
+ ) : (
+ <>
+ <Button
+ palette="confirmation"
+ variant="secondary"
+ disabled={pending}
+ onClick={() => void dismiss()}
+ >
+ {copy('cancel')}
+ </Button>
+ {readyToAuthorize ? (
+ <Button
+ palette="confirmation"
+ disabled={opening || pending}
+ onClick={() => void openBrowser()}
+ >
+ {copy('openBrowser')}
+ </Button>
+ ) : (
+ (!active || failed) && (
+ <Button palette="confirmation" disabled={pending} onClick={() => void start()}>
+ {copy(retry ? 'retry' : entryAction === 'install' ? 'install' : 'connect')}
+ </Button>
+ )
+ )}
+ </>
+ )}
+ </div>
+ </Dialog.Content>
+ </Dialog.Portal>
+ </Dialog.Root>
+ );
+}
diff --git a/apps/desktop/src/renderer/features/cc-agent/gitContextPrVisuals.ts b/apps/desktop/src/renderer/features/cc-agent/gitContextPrVisuals.ts
index b7ef624292..e6dd5104fa 100644
--- a/apps/desktop/src/renderer/features/cc-agent/gitContextPrVisuals.ts
+++ b/apps/desktop/src/renderer/features/cc-agent/gitContextPrVisuals.ts
@@ -25,14 +25,14 @@ export type PrGuidanceSessionOpts = {
remoteHostId?: string | null;
/** device-link:本 session 归属被控设备。与 remoteHostId 互不相干,必须同时钳。 */
deviceLinkDeviceId?: string | null;
- /** review 等只读任务:ChatInput 永久 disabled,插入会被静默丢掉。 */
+ /** review 等只读任务保留浏览 PR 的动作。 */
readOnly?: boolean;
};
/**
* 点击会独占 chip(不再打开 PR),所以只有动作能兑现才引导:
* 1. 当前任务的 Agent 就在本机(非 SSH / 非 device-link)
- * 2. 输入框能收下提示词(非 review 只读)
+ * 2. 非 review 只读任务
* 任一不成立 → 不引导,点击仍打开 PR。
*/
export function prGuidanceFor(
diff --git a/apps/desktop/src/renderer/features/issue-tracker/IssueTrackerFeatureLayout.tsx b/apps/desktop/src/renderer/features/issue-tracker/IssueTrackerFeatureLayout.tsx
index 8033f00ce7..4694e54352 100644
--- a/apps/desktop/src/renderer/features/issue-tracker/IssueTrackerFeatureLayout.tsx
+++ b/apps/desktop/src/renderer/features/issue-tracker/IssueTrackerFeatureLayout.tsx
@@ -1,4 +1,5 @@
import { Button } from '@/components/ui/button';
+import { GithubConnectButton } from '@/features/cc-agent/GithubConnectButton';
/**
* IssueTrackerFeatureLayout — 「我的 Issue」页
* ---------------------------------------------------------------------------
@@ -7,7 +8,7 @@ import { Button } from '@/components/ui/button';
* 口径:看自己的 issue 与提交 issue 走**同一条公共能力**,只要 Cindy 登录态,
* 不要求用户有 GitHub 账号 —— 所以本页任何状态下都**不得**提示「你需要连接
* GitHub」。用户自己的 GitHub 身份只是可选增强(把他直接在 GitHub 上提的也并进来),
- * 没有它页面照常工作,界面上也不提。
+ * 没有它页面照常工作;连接入口仅用于可选的 GitHub 账号增强。
*
* 一条都没有时,页面退回原来的引导形态(告诉用户怎么用 /issue 提交)。
*
@@ -66,6 +67,10 @@ 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)}
+ onConnected={refresh}
+ />
<button
type="button"
onClick={refresh}
@@ -119,13 +124,7 @@ export function IssueTrackerFeatureLayout() {
* 两处说明(顶部条与空态)共用它,避免样式与行为各写一套;`size` 只差内边距,
* 视觉语言(等宽字 + 浅底 + hover 加深)一致。
*/
-function IssueCommandButton({
- onClick,
- size = 'sm',
-}: {
- onClick: () => void;
- size?: 'sm' | 'lg';
-}) {
+function IssueCommandButton({ onClick, size = 'sm' }: { onClick: () => void; size?: 'sm' | 'lg' }) {
const { t } = useTranslation();
return (
<button
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 2b8ea7dff9..fcf06ef168 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
@@ -7,7 +7,7 @@
* 但 error 分支一旦优先于 hasItems,用户点一次刷新就会丢失整页内容。
*/
-import { cleanup, render, screen } from '@testing-library/react';
+import { cleanup, fireEvent, render, screen, waitFor } from '@testing-library/react';
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
import type { MyIssueItem, MyIssuesResult } from '@/../shared/myIssues';
@@ -91,10 +91,46 @@ afterEach(() => {
});
describe('IssueTrackerFeatureLayout 内容区分支', () => {
- it('刷新失败但已有数据:保留列表,错误降级成提示条', () => {
+ it('hides connect for a working GitHub account and restores it when the connection fails', () => {
+ const connected = result([], { githubEnhancement: { login: 'test', source: 'gh-cli' } });
+ useMyIssuesMock.mockReturnValue(state({ data: connected }));
+ const { rerender } = render(<IssueTrackerFeatureLayout />);
+ expect(screen.queryByText('ccAgent.gitContext.pr.setup.stages.login.title')).toBeNull();
useMyIssuesMock.mockReturnValue(
- state({ data: result([item()]), error: 'ECONNRESET' }),
+ state({ data: { ...connected, 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 () => {
+ const refresh = vi.fn();
+ useMyIssuesMock.mockReturnValue(state({ data: result([item()]), refresh }));
+ Object.assign(window.electronAPI, {
+ gitContext: {
+ githubSetupStatus: async () => ({ phase: 'connected' }),
+ startGithubSetup: async () => ({ phase: 'connected' }),
+ },
+ });
+ const { rerender } = render(<IssueTrackerFeatureLayout />);
+ fireEvent.click(screen.getByText('ccAgent.gitContext.pr.setup.stages.login.title'));
+ fireEvent.click(await screen.findByText('ccAgent.gitContext.pr.setup.connect'));
+ await waitFor(() => expect(refresh).toHaveBeenCalledOnce());
+ expect(screen.getByText('已经加载出来的那条 issue')).toBeTruthy();
+ useMyIssuesMock.mockReturnValue(
+ state({
+ data: result([item()], { githubEnhancement: { source: 'gh-cli', login: 'test' } }),
+ refresh,
+ }),
);
+ rerender(<IssueTrackerFeatureLayout />);
+ expect(screen.queryByText('ccAgent.gitContext.pr.setup.stages.login.title')).toBeNull();
+ // Hiding the entry must not tear down the success dialog before Done is clicked.
+ fireEvent.click(screen.getByText('ccAgent.gitContext.pr.setup.done'));
+ expect(screen.queryByRole('dialog')).toBeNull();
+ expect(refresh).toHaveBeenCalledOnce();
+ });
+ it('刷新失败但已有数据:保留列表,错误降级成提示条', () => {
+ useMyIssuesMock.mockReturnValue(state({ data: result([item()]), error: 'ECONNRESET' }));
render(<IssueTrackerFeatureLayout />);
// 列表还在,用户不丢内容。
@@ -127,9 +163,7 @@ describe('IssueTrackerFeatureLayout 内容区分支', () => {
it('首屏取数期间保留引导内容,不换成 loading 文案(engineering-conventions §7)', () => {
// 平台通道总 deadline 可达 12s。换成一行「加载中」会造成 引导 → loading → 列表
// 两次跳变;而一条都没有的用户(最常见)看到的引导页本该从头到尾没动过。
- useMyIssuesMock.mockReturnValue(
- state({ loading: true, data: null, hasFreshData: false }),
- );
+ useMyIssuesMock.mockReturnValue(state({ loading: true, data: null, hasFreshData: false }));
render(<IssueTrackerFeatureLayout />);
// 引导正文与 CTA 在场,但**一个标题都不渲染** —— 标题是结论,这时还没查完。
@@ -151,9 +185,7 @@ describe('IssueTrackerFeatureLayout 内容区分支', () => {
});
it('首屏取数完成后引导原子切成列表 —— 中间不经过第三种形态', () => {
- useMyIssuesMock.mockReturnValue(
- state({ loading: true, data: null, hasFreshData: false }),
- );
+ useMyIssuesMock.mockReturnValue(state({ loading: true, data: null, hasFreshData: false }));
const view = render(<IssueTrackerFeatureLayout />);
expect(screen.getByRole('button', { name: 'issueTracker.mine.startIssueChat' })).toBeTruthy();
diff --git a/apps/desktop/src/renderer/features/issue-tracker/__tests__/useMyIssues.test.tsx b/apps/desktop/src/renderer/features/issue-tracker/__tests__/useMyIssues.test.tsx
new file mode 100644
index 0000000000..b96bda892c
--- /dev/null
+++ b/apps/desktop/src/renderer/features/issue-tracker/__tests__/useMyIssues.test.tsx
@@ -0,0 +1,37 @@
+// @vitest-environment jsdom
+import { act, cleanup, renderHook, waitFor } from '@testing-library/react';
+import { afterEach, expect, it, vi } from 'vitest';
+import { useMyIssues } from '../hooks/useMyIssues';
+
+afterEach(cleanup);
+
+it('rechecks after connection when an older issues request is still running', async () => {
+ const response = {
+ success: true,
+ items: [],
+ githubEnhancement: null,
+ githubEnhancementFailed: false,
+ degraded: null,
+ truncated: false,
+ };
+ let finish!: (value: unknown) => void;
+ const list = vi
+ .fn()
+ .mockImplementationOnce(
+ () =>
+ new Promise((resolve) => {
+ finish = resolve;
+ }),
+ )
+ .mockResolvedValue({ ...response, githubEnhancement: { source: 'gh-cli', login: 'test' } });
+ window.electronAPI = {
+ maker: { listMyIssues: list, getMyIssuesSnapshot: async () => null },
+ } as any;
+ const { result } = renderHook(() => useMyIssues());
+ await waitFor(() => expect(list).toHaveBeenCalledOnce());
+ act(() => result.current.refresh());
+ await act(async () => finish(response));
+ await waitFor(() => expect(result.current.data?.githubEnhancement?.login).toBe('test'));
+ expect(list).toHaveBeenCalledTimes(2);
+ expect(list).toHaveBeenLastCalledWith({ force: true });
+});
diff --git a/apps/desktop/src/renderer/features/issue-tracker/hooks/useMyIssues.ts b/apps/desktop/src/renderer/features/issue-tracker/hooks/useMyIssues.ts
index 0d29509954..b05bd0fdcc 100644
--- a/apps/desktop/src/renderer/features/issue-tracker/hooks/useMyIssues.ts
+++ b/apps/desktop/src/renderer/features/issue-tracker/hooks/useMyIssues.ts
@@ -14,11 +14,7 @@
import { useCallback, useEffect, useRef, useState } from 'react';
-import type {
- MyIssuesErrorCode,
- MyIssuesResult,
- MyIssuesSnapshot,
-} from '@/../shared/myIssues';
+import type { MyIssuesErrorCode, MyIssuesResult, MyIssuesSnapshot } from '@/../shared/myIssues';
import { createLogger } from '@/lib/logger';
const log = createLogger('useMyIssues');
@@ -64,9 +60,13 @@ export function useMyIssues(): UseMyIssuesState {
const [error, setError] = useState<MyIssuesErrorCode | null>(null);
const disposed = useRef(false);
const inFlight = useRef(false);
+ const refreshPending = useRef(false);
const load = useCallback(async (force: boolean) => {
- if (inFlight.current) return;
+ if (inFlight.current) {
+ if (force) refreshPending.current = true;
+ return;
+ }
inFlight.current = true;
if (force) setRefreshing(true);
try {
@@ -102,6 +102,10 @@ export function useMyIssues(): UseMyIssuesState {
if (!disposed.current) {
setLoading(false);
setRefreshing(false);
+ if (refreshPending.current) {
+ refreshPending.current = false;
+ void load(true);
+ }
}
}
}, []);
diff --git a/apps/desktop/src/renderer/features/plugin/GhostPluginDetailView.tsx b/apps/desktop/src/renderer/features/plugin/GhostPluginDetailView.tsx
index 116575861b..3070a3c1f9 100644
--- a/apps/desktop/src/renderer/features/plugin/GhostPluginDetailView.tsx
+++ b/apps/desktop/src/renderer/features/plugin/GhostPluginDetailView.tsx
@@ -1,4 +1,5 @@
import { Button } from '@/components/ui/button';
+import { GithubAccountCard } from '@/features/cc-agent/GithubAccountCard';
import { shouldShowOpenPathError } from '../../../shared/openPathResult';
/**
* Plugin detail presentation for configuration, Tools, permissions, and factual metadata.
@@ -123,6 +124,7 @@ export function GhostPluginDetailView({
const { scrolled, onScroll } = usePluginDetailScrolled();
const enableSwitchId = useId();
const [descriptionExpanded, setDescriptionExpanded] = useState(false);
+ const [githubConnectionVersion, setGithubConnectionVersion] = useState(0);
const [descriptionOverflows, setDescriptionOverflows] = useState(false);
const descriptionRef = useRef<HTMLParagraphElement>(null);
// 安装记录不完整时不可运行:enabled 直接门控为 false(说明现状 + 给恢复入口,不让它
@@ -136,13 +138,26 @@ export function GhostPluginDetailView({
primaryAction === 'capability' ||
(primaryAction === 'command' && detail.canUse));
const cindyCapabilities = detail.cindyCapabilities;
+ // Local imports with the same id cannot use the host gh credential. Match the
+ // official receipt before advertising that connection in this plugin's UI.
+ const hasGithubConnection =
+ detail.id === 'cindy-github' &&
+ Boolean(ghost) &&
+ ghost?.trust?.level === 'cindy-official' &&
+ ghost.trust.publisherSigned &&
+ ghost.trust.publisherVerified &&
+ ghost.trust.reviewed &&
+ ghost.trust.publisherName === 'Cindy Plugin Market';
const hasConfiguration =
+ hasGithubConnection ||
detail.hasMainView ||
detail.hasSettingsUi ||
detail.hostCapability === 'ios-simulator' ||
cindyCapabilities.length > 0 ||
detail.hasErrand;
- const summary = ghostPluginSummary(detail.description, detail.id);
+ const summary = hasGithubConnection
+ ? t('ccAgent.gitContext.pr.setup.account.summary')
+ : ghostPluginSummary(detail.description, detail.id);
/**
* 「从 .cindy 文件更新」是否可用。官方保留前缀(cindy- / filo- / xd-)在**非 dev
* 构建**上会被 Main 的用户装入通道以 GHOST_ID_RESERVED 直接拒绝(见
@@ -256,12 +271,12 @@ export function GhostPluginDetailView({
}
aria-busy={updateBusy || undefined}
>
- <>
- <ArrowUp size={14} aria-hidden="true" />
- {updateVersion === detail.version
- ? t('settings.ghosts.market.update')
- : t('settings.ghosts.market.updateTo', { version: updateVersion })}
- </>
+ <>
+ <ArrowUp size={14} aria-hidden="true" />
+ {updateVersion === detail.version
+ ? t('settings.ghosts.market.update')
+ : t('settings.ghosts.market.updateTo', { version: updateVersion })}
+ </>
</Button>
) : null}
{primaryAction !== 'manage' ? (
@@ -407,12 +422,22 @@ export function GhostPluginDetailView({
</header>
{hasConfiguration ? (
- <section className={DETAIL_SECTION_CLASS} aria-labelledby="ghost-configuration-title">
- <DetailSectionHeader
- id="ghost-configuration-title"
- title={t('settings.ghosts.detail.configurationTitle')}
- />
- <div className={cn(DETAIL_SECTION_CONTENT_CLASS, 'space-y-3')}>
+ <section
+ className={hasGithubConnection ? 'mt-6' : DETAIL_SECTION_CLASS}
+ aria-labelledby={hasGithubConnection ? undefined : 'ghost-configuration-title'}
+ >
+ {!hasGithubConnection && (
+ <DetailSectionHeader
+ id="ghost-configuration-title"
+ title={t('settings.ghosts.detail.configurationTitle')}
+ />
+ )}
+ <div
+ className={cn(
+ hasGithubConnection ? 'max-w-[760px]' : DETAIL_SECTION_CONTENT_CLASS,
+ 'space-y-3',
+ )}
+ >
{detail.hostCapability === 'ios-simulator' ? <IOSSimulatorPreferences /> : null}
{detail.hasMainView ? (
<div
@@ -448,6 +473,14 @@ export function GhostPluginDetailView({
<>
{ghost.oauthScopeStale ? <OauthScopeStaleBadge /> : null}
<GhostSettingsWebview
+ reloadKey={githubConnectionVersion}
+ account={
+ hasGithubConnection ? (
+ <GithubAccountCard
+ onConnected={() => setGithubConnectionVersion((version) => version + 1)}
+ />
+ ) : undefined
+ }
ghost={ghost}
title={t('settings.ghosts.detail.settingsTitle', { name: detail.name })}
appearance="plugin"
@@ -476,7 +509,11 @@ export function GhostPluginDetailView({
</div>
)
) : null}
- {ghost?.manifest.routineEvents ? <p className="text-13 text-[var(--text-secondary)]">{t('routines.pluginCapability')}</p> : null}
+ {ghost?.manifest.routineEvents ? (
+ <p className="text-13 text-[var(--text-secondary)]">
+ {t('routines.pluginCapability')}
+ </p>
+ ) : null}
{cindyCapabilities.length > 0 ? (
<CindyCapabilityPrefs
ghostId={detail.id}
@@ -853,7 +890,8 @@ export function DetailsSection({
if (!installDir) return;
void window.electronAPI.openPath(installDir).then(
(result) => {
- if (shouldShowOpenPathError(result)) toast.error(t('settings.ghosts.errors.generic'));
+ if (shouldShowOpenPathError(result))
+ toast.error(t('settings.ghosts.errors.generic'));
},
() => toast.error(t('settings.ghosts.errors.generic')),
);
diff --git a/apps/desktop/src/renderer/features/plugin/__tests__/GhostPluginDetailSections.test.tsx b/apps/desktop/src/renderer/features/plugin/__tests__/GhostPluginDetailSections.test.tsx
index 8e32defe59..21df54bab3 100644
--- a/apps/desktop/src/renderer/features/plugin/__tests__/GhostPluginDetailSections.test.tsx
+++ b/apps/desktop/src/renderer/features/plugin/__tests__/GhostPluginDetailSections.test.tsx
@@ -9,19 +9,33 @@ import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
const toastMocks = vi.hoisted(() => ({ success: vi.fn(), error: vi.fn() }));
-vi.mock('@/hooks/useModelPricing', () => ({ useGatewayModelPricing: () => null, useReferenceModelPricing: () => null }));
-vi.mock('@/hooks/useProviders', () => ({ useProviders: () => ({ providers: [], providerOrder: [], loading: false }) }));
-vi.mock('@/hooks/useDeviceProviders', () => ({ useDeviceProviders: () => ({ providers: [], loading: false, unsupported: false }) }));
+vi.mock('@/hooks/useModelPricing', () => ({
+ useGatewayModelPricing: () => null,
+ useReferenceModelPricing: () => null,
+}));
+vi.mock('@/hooks/useProviders', () => ({
+ useProviders: () => ({ providers: [], providerOrder: [], loading: false }),
+}));
+vi.mock('@/hooks/useDeviceProviders', () => ({
+ useDeviceProviders: () => ({ providers: [], loading: false, unsupported: false }),
+}));
vi.mock('@/hooks/useAgentCapabilities', async (importOriginal) => ({
...(await importOriginal<typeof import('@/hooks/useAgentCapabilities')>()),
useAgentCapabilities: () => ({ capabilities: null, loading: false }),
}));
vi.mock('@/hooks/useApiKey', () => ({ useApiKey: () => ({ hasSavedKey: true }) }));
-vi.mock('@/hooks/useConnectedSource', () => ({ useConnectedSource: () => ({ hasConnectedSource: true, loading: false }) }));
+vi.mock('@/hooks/useConnectedSource', () => ({
+ useConnectedSource: () => ({ hasConnectedSource: true, loading: false }),
+}));
vi.mock('@/lib/toast', () => ({ toast: toastMocks }));
vi.mock('@/cindy-brain/GhostSettingsWebview', () => ({
- GhostSettingsWebview: () => <div data-testid="ghost-settings-webview" />,
+ GhostSettingsWebview: ({ account, reloadKey }: any) => (
+ <>
+ {account}
+ <div key={reloadKey} data-testid="ghost-settings-webview" />
+ </>
+ ),
}));
vi.mock('react-i18next', () => ({
@@ -179,6 +193,81 @@ afterEach(() => {
});
describe('Ghost plugin detail sections', () => {
+ it('does not advertise host login for a locally imported unverified GitHub plugin', () => {
+ vi.stubGlobal(
+ 'ResizeObserver',
+ class {
+ observe() {}
+ unobserve() {}
+ disconnect() {}
+ },
+ );
+ const verify = vi.fn();
+ Object.assign(window.electronAPI, { gitContext: { githubConnection: verify } });
+ render(
+ <GhostPluginDetailView
+ ghost={
+ { manifest: { id: 'cindy-github' }, enabled: true, trust: { level: 'unverified' } } as any
+ }
+ detail={{ ...detail, id: 'cindy-github', hasSettingsUi: true }}
+ panelStatus={null}
+ onBack={vi.fn()}
+ onToggle={vi.fn()}
+ onUse={vi.fn()}
+ onUpdate={vi.fn()}
+ onUpdateFromFile={vi.fn()}
+ onUninstall={vi.fn()}
+ toggleDisabled={false}
+ />,
+ );
+ expect(verify).not.toHaveBeenCalled();
+ });
+ it('connects GitHub and reloads the installed plugin settings after authorization', async () => {
+ vi.stubGlobal(
+ 'ResizeObserver',
+ class {
+ observe() {}
+ unobserve() {}
+ disconnect() {}
+ },
+ );
+ Object.assign(window.electronAPI, {
+ gitContext: {
+ githubConnection: async () => ({ status: 'missing' }),
+ onGithubConnected: () => () => {},
+ githubSetupStatus: async () => ({ phase: 'connected' }),
+ startGithubSetup: async () => ({ phase: 'connected' }),
+ },
+ });
+ const { unmount } = render(
+ <GhostPluginDetailView
+ ghost={
+ {
+ manifest: { id: 'cindy-github' },
+ enabled: true,
+ trust: { ...detail.trust, publisherName: 'Cindy Plugin Market' },
+ } as any
+ }
+ detail={{ ...detail, id: 'cindy-github', hasSettingsUi: true }}
+ panelStatus={null}
+ onBack={vi.fn()}
+ onToggle={vi.fn()}
+ onUse={vi.fn()}
+ onUpdate={vi.fn()}
+ onUpdateFromFile={vi.fn()}
+ onUninstall={vi.fn()}
+ toggleDisabled={false}
+ />,
+ );
+ const previousSettings = screen.getByTestId('ghost-settings-webview');
+ fireEvent.click(await screen.findByText('ccAgent.gitContext.pr.setup.stages.login.title'));
+ fireEvent.click(await screen.findByText('ccAgent.gitContext.pr.setup.connect'));
+ await waitFor(() =>
+ expect(screen.getByTestId('ghost-settings-webview')).not.toBe(previousSettings),
+ );
+ expect(screen.getByText('ccAgent.gitContext.pr.setup.done')).toBeTruthy();
+ unmount();
+ });
it('uses the shared Cindy Switch for the plugin enabled control', () => {
vi.stubGlobal(
'ResizeObserver',
@@ -996,24 +1085,38 @@ describe('Ghost plugin detail sections', () => {
expect(within(listbox).getByRole('group', { name: 'OpenAI' })).toBeTruthy();
expect(listbox.querySelector('[data-row-customize]')).not.toBeNull();
expect(listbox.querySelector('[data-agent-kind]')).toBeNull();
- const plainRow = within(listbox).getByText('GPT 5.5', { exact: true }).closest<HTMLElement>('[role="option"]')!;
+ const plainRow = within(listbox)
+ .getByText('GPT 5.5', { exact: true })
+ .closest<HTMLElement>('[role="option"]')!;
expect(within(plainRow).queryByText('settings.providers.models.subscription')).toBeNull();
fireEvent.click(plainRow);
- await waitFor(() => expect(setCindyPref).toHaveBeenCalledWith(
- 'xdt-knowledge', 'text.oneshot', 'cat:openai:codex:gpt-5.5',
- ));
+ await waitFor(() =>
+ expect(setCindyPref).toHaveBeenCalledWith(
+ 'xdt-knowledge',
+ 'text.oneshot',
+ 'cat:openai:codex:gpt-5.5',
+ ),
+ );
// A different supported Harness must remain reachable after replacing the old Agent step.
- fireEvent.click(screen.getByRole('button', { name: /settings.ghosts.detail.cindyPrefs.cap.text.oneshot/ }));
+ fireEvent.click(
+ screen.getByRole('button', { name: /settings.ghosts.detail.cindyPrefs.cap.text.oneshot/ }),
+ );
const reopened = await screen.findByRole('listbox');
- const routeRow = within(reopened).getByText('GPT 5.5', { exact: true }).closest<HTMLElement>('[role="option"]')!;
+ const routeRow = within(reopened)
+ .getByText('GPT 5.5', { exact: true })
+ .closest<HTMLElement>('[role="option"]')!;
fireEvent.click(routeRow.querySelector('[data-row-customize]')!);
const flyout = await screen.findByTestId('unified-model-config-flyout');
expect(flyout.querySelector('[role="slider"], [data-fast-toggle]')).toBeNull();
fireEvent.click(flyout.querySelector('[data-engine-capsule="cc"]')!);
fireEvent.click(routeRow);
- await waitFor(() => expect(setCindyPref).toHaveBeenLastCalledWith(
- 'xdt-knowledge', 'text.oneshot', 'cat:openai:claude-code:chatgpt/gpt-5.5',
- ));
+ await waitFor(() =>
+ expect(setCindyPref).toHaveBeenLastCalledWith(
+ 'xdt-knowledge',
+ 'text.oneshot',
+ 'cat:openai:claude-code:chatgpt/gpt-5.5',
+ ),
+ );
vi.unstubAllEnvs();
});
@@ -1134,11 +1237,16 @@ describe('Ghost plugin detail sections', () => {
);
const listbox = await screen.findByRole('listbox');
// Retired pins remain visible on the trigger, but never become selectable routes.
- expect(screen.getByRole('button', { name: /settings.ghosts.detail.cindyPrefs.cap.text.oneshot/ }).textContent).toContain('retired-model');
+ expect(
+ screen.getByRole('button', { name: /settings.ghosts.detail.cindyPrefs.cap.text.oneshot/ })
+ .textContent,
+ ).toContain('retired-model');
expect(within(listbox).queryByText('cat:gone:codex:retired-model')).toBeNull();
expect(setCindyPref).not.toHaveBeenCalled();
fireEvent.click(within(listbox).getAllByRole('option')[0]!);
- await waitFor(() => expect(setCindyPref).toHaveBeenCalledWith('xdt-knowledge', 'text.oneshot', null));
+ await waitFor(() =>
+ expect(setCindyPref).toHaveBeenCalledWith('xdt-knowledge', 'text.oneshot', null),
+ );
vi.unstubAllEnvs();
});
diff --git a/apps/desktop/src/renderer/i18n/locales/en/common.json b/apps/desktop/src/renderer/i18n/locales/en/common.json
index 5df5496c8a..13f82d442c 100644
--- a/apps/desktop/src/renderer/i18n/locales/en/common.json
+++ b/apps/desktop/src/renderer/i18n/locales/en/common.json
@@ -10419,14 +10419,89 @@
"clickToOpen": "Click to open the PR in your browser",
"guidance": {
"login": {
- "hint": "Click to have the agent sign you in",
- "aria": "PR #{{number}} status unavailable: have the agent sign in to GitHub",
- "prompt": "Please sign me in to the GitHub CLI: run `gh auth login -h github.com -w`, tell me the one-time device code and URL it shows, and after I authorize in the browser, confirm with `gh auth status` that the login succeeded."
+ "hint": "Click to connect GitHub",
+ "aria": "PR #{{number}} status unavailable: connect GitHub"
},
"install": {
- "hint": "Click to have the agent install it and sign you in",
- "aria": "PR #{{number}} status unavailable: have the agent install and sign in to GitHub CLI",
- "prompt": "Please install the GitHub CLI (gh; `brew install gh` on macOS, `winget install GitHub.cli` on Windows), then run `gh auth login -h github.com -w` to sign in, tell me the one-time device code and URL it shows, and after I authorize in the browser, confirm with `gh auth status` that the login succeeded."
+ "hint": "Click to connect GitHub",
+ "aria": "PR #{{number}} status unavailable: connect GitHub"
+ }
+ },
+ "setup": {
+ "install": "Install and continue",
+ "connect": "Sign in to GitHub",
+ "cancel": "Cancel",
+ "retry": "Try again",
+ "done": "Done",
+ "openBrowser": "Open GitHub to authorize",
+ "deviceCode": "Device code",
+ "copyCode": "Copy code",
+ "copied": "Copied",
+ "copyFailed": "Could not copy. Select and copy the code manually.",
+ "openFailed": "Could not open your browser. Open github.com/login/device manually.",
+ "stages": {
+ "install": {
+ "title": "Install GitHub CLI",
+ "description": "Install GitHub CLI to connect your GitHub account."
+ },
+ "login": {
+ "title": "Connect GitHub",
+ "description": "Connect your GitHub account. GitHub CLI will be installed if needed."
+ },
+ "checking": {
+ "title": "Checking connection…",
+ "description": "Checking your GitHub sign-in."
+ },
+ "downloading": {
+ "title": "Downloading GitHub CLI…",
+ "description": "Installation will start when the download finishes."
+ },
+ "installing": {
+ "title": "Installing GitHub CLI…",
+ "description": "Download complete."
+ },
+ "preparing": {
+ "title": "Preparing sign-in…",
+ "description": "Getting a one-time device code."
+ },
+ "authorizing": {
+ "title": "Sign in to GitHub",
+ "description": "Copy this code, then enter it on GitHub to authorize."
+ },
+ "connected": {
+ "title": "GitHub connected",
+ "description": "You can close this window and continue."
+ },
+ "cancelled": {
+ "title": "Connection cancelled",
+ "description": "You can try again whenever you are ready."
+ },
+ "unavailable": {
+ "title": "Progress unavailable",
+ "description": "Could not read the current progress. Try again."
+ },
+ "error": {
+ "title": "Connection not completed"
+ }
+ },
+ "errors": {
+ "unsupported": "This operating system or processor is not supported yet.",
+ "install": "Installation failed. Check your connection and available disk space, then try again.",
+ "login": "Sign-in failed or was denied. Try again to get a new code.",
+ "timeout": "The code expired. Try again to get a new code."
+ },
+ "account": {
+ "checking": "Checking GitHub connection…",
+ "connected": "Connected · @{{login}}",
+ "missing": "Connect GitHub to get started.",
+ "auth": "Authorization has expired. Sign in again or replace the fallback token below.",
+ "network": "Could not reach GitHub. Check your network and retry.",
+ "forbidden": "GitHub could not verify this connection. Check permissions or rate limits, then retry.",
+ "gh-cli": "Using this computer’s GitHub login",
+ "token": "Using fallback token",
+ "recheck": "Check connection",
+ "summary": "Manage GitHub repositories, issues, pull requests, and Actions.",
+ "otherMethods": "Other connection methods"
}
},
"unresolved": "Unresolved review threads: {{count}}"
diff --git a/apps/desktop/src/renderer/i18n/locales/ja/common.json b/apps/desktop/src/renderer/i18n/locales/ja/common.json
index d2be06d00d..5ea8abfedf 100644
--- a/apps/desktop/src/renderer/i18n/locales/ja/common.json
+++ b/apps/desktop/src/renderer/i18n/locales/ja/common.json
@@ -10404,14 +10404,89 @@
"clickToOpen": "クリックしてブラウザで PR を開く",
"guidance": {
"login": {
- "hint": "クリックすると Agent がログインを手伝います",
- "aria": "PR #{{number}} の状態を取得できません:Agent に GitHub へのログインを任せる",
- "prompt": "GitHub CLI にログインしてください:`gh auth login -h github.com -w` を実行し、表示されたワンタイムのデバイスコードと URL を教えてください。ブラウザで認可したら、`gh auth status` でログイン成功を確認してください。"
+ "hint": "クリックして GitHub に接続",
+ "aria": "PR #{{number}} の状態を取得できません:GitHub に接続"
},
"install": {
- "hint": "クリックすると Agent がインストールとログインを手伝います",
- "aria": "PR #{{number}} の状態を取得できません:Agent に GitHub CLI のインストールとログインを任せる",
- "prompt": "GitHub CLI(gh)をインストールしてください(macOS は `brew install gh`、Windows は `winget install GitHub.cli`)。その後 `gh auth login -h github.com -w` を実行してログインし、表示されたワンタイムのデバイスコードと URL を教えてください。ブラウザで認可したら、`gh auth status` でログイン成功を確認してください。"
+ "hint": "クリックして GitHub に接続",
+ "aria": "PR #{{number}} の状態を取得できません:GitHub に接続"
+ }
+ },
+ "setup": {
+ "install": "インストールして続行",
+ "connect": "GitHub にログイン",
+ "cancel": "キャンセル",
+ "retry": "再試行",
+ "done": "完了",
+ "openBrowser": "GitHub を開いて認可",
+ "deviceCode": "ワンタイムデバイスコード",
+ "copyCode": "コードをコピー",
+ "copied": "コピーしました",
+ "copyFailed": "コピーできませんでした。コードを選択して手動でコピーしてください。",
+ "openFailed": "ブラウザを開けませんでした。github.com/login/device を手動で開いてください。",
+ "stages": {
+ "install": {
+ "title": "GitHub CLI をインストール",
+ "description": "GitHub CLI をインストールして GitHub アカウントに接続します。"
+ },
+ "login": {
+ "title": "GitHub に接続",
+ "description": "GitHub アカウントに接続します。GitHub CLI が未インストールの場合は自動でインストールします。"
+ },
+ "checking": {
+ "title": "接続を確認中…",
+ "description": "GitHub のログイン状態を確認しています。"
+ },
+ "downloading": {
+ "title": "GitHub CLI をダウンロード中…",
+ "description": "ダウンロードが終わると自動でインストールします。"
+ },
+ "installing": {
+ "title": "GitHub CLI をインストール中…",
+ "description": "ダウンロードが完了しました。"
+ },
+ "preparing": {
+ "title": "ログインを準備中…",
+ "description": "ワンタイムデバイスコードを取得しています。"
+ },
+ "authorizing": {
+ "title": "GitHub にログイン",
+ "description": "このコードをコピーし、GitHub のページに入力して認可してください。"
+ },
+ "connected": {
+ "title": "GitHub に接続しました",
+ "description": "この画面を閉じて操作を続けられます。"
+ },
+ "cancelled": {
+ "title": "接続をキャンセルしました",
+ "description": "準備ができたら再試行できます。"
+ },
+ "unavailable": {
+ "title": "進捗を取得できません",
+ "description": "現在の進捗を取得できません。再試行してください。"
+ },
+ "error": {
+ "title": "接続が完了していません"
+ }
+ },
+ "errors": {
+ "unsupported": "この OS またはプロセッサにはまだ対応していません。",
+ "install": "インストールに失敗しました。ネットワークと空き容量を確認して再試行してください。",
+ "login": "ログインに失敗したか、認可が拒否されました。再試行して新しいコードを取得してください。",
+ "timeout": "コードの有効期限が切れました。再試行してください。"
+ },
+ "account": {
+ "checking": "GitHub への接続を確認中…",
+ "connected": "接続済み · @{{login}}",
+ "missing": "GitHub に接続すると利用できます。",
+ "auth": "認証が失効しました。再ログインするか、下の予備トークンを変更してください。",
+ "network": "GitHub に接続できません。ネットワークを確認して再試行してください。",
+ "forbidden": "接続を確認できません。権限や API の利用制限を確認して再試行してください。",
+ "gh-cli": "この端末の GitHub ログインを使用中",
+ "token": "予備トークンを使用中",
+ "recheck": "接続を確認",
+ "summary": "GitHub のリポジトリ、Issue、PR、Actions を管理。",
+ "otherMethods": "その他の接続方法"
}
},
"unresolved": "未解決のレビューコメント: {{count}} 件"
diff --git a/apps/desktop/src/renderer/i18n/locales/ko/common.json b/apps/desktop/src/renderer/i18n/locales/ko/common.json
index e69b376546..d22aa2e12b 100644
--- a/apps/desktop/src/renderer/i18n/locales/ko/common.json
+++ b/apps/desktop/src/renderer/i18n/locales/ko/common.json
@@ -10404,14 +10404,89 @@
"clickToOpen": "클릭하여 브라우저에서 PR 열기",
"guidance": {
"login": {
- "hint": "클릭하면 Agent가 로그인을 도와줍니다",
- "aria": "PR #{{number}} 상태를 가져올 수 없음: Agent에게 GitHub 로그인 맡기기",
- "prompt": "GitHub CLI에 로그인해 주세요: `gh auth login -h github.com -w`를 실행하고 표시되는 일회용 기기 코드와 URL을 알려 주세요. 제가 브라우저에서 승인한 뒤 `gh auth status`로 로그인 성공 여부를 확인해 주세요."
+ "hint": "클릭하여 GitHub 연결",
+ "aria": "PR #{{number}} 상태를 가져올 수 없음: GitHub 연결"
},
"install": {
- "hint": "클릭하면 Agent가 설치와 로그인을 도와줍니다",
- "aria": "PR #{{number}} 상태를 가져올 수 없음: Agent에게 GitHub CLI 설치와 로그인 맡기기",
- "prompt": "GitHub CLI(gh)를 설치해 주세요(macOS는 `brew install gh`, Windows는 `winget install GitHub.cli`). 그다음 `gh auth login -h github.com -w`를 실행해 로그인하고, 표시되는 일회용 기기 코드와 URL을 알려 주세요. 제가 브라우저에서 승인한 뒤 `gh auth status`로 로그인 성공 여부를 확인해 주세요."
+ "hint": "클릭하여 GitHub 연결",
+ "aria": "PR #{{number}} 상태를 가져올 수 없음: GitHub 연결"
+ }
+ },
+ "setup": {
+ "install": "설치하고 계속",
+ "connect": "GitHub 로그인",
+ "cancel": "취소",
+ "retry": "다시 시도",
+ "done": "완료",
+ "openBrowser": "GitHub에서 승인",
+ "deviceCode": "일회용 기기 코드",
+ "copyCode": "코드 복사",
+ "copied": "복사됨",
+ "copyFailed": "복사하지 못했습니다. 코드를 선택하여 직접 복사해 주세요.",
+ "openFailed": "브라우저를 열지 못했습니다. github.com/login/device를 직접 열어 주세요.",
+ "stages": {
+ "install": {
+ "title": "GitHub CLI 설치",
+ "description": "GitHub CLI를 설치하여 GitHub 계정에 연결하세요."
+ },
+ "login": {
+ "title": "GitHub 연결",
+ "description": "GitHub 계정에 연결하세요. GitHub CLI가 없으면 자동으로 설치합니다."
+ },
+ "checking": {
+ "title": "연결 확인 중…",
+ "description": "GitHub 로그인 상태를 확인하고 있습니다."
+ },
+ "downloading": {
+ "title": "GitHub CLI 다운로드 중…",
+ "description": "다운로드가 끝나면 자동으로 설치합니다."
+ },
+ "installing": {
+ "title": "GitHub CLI 설치 중…",
+ "description": "다운로드가 완료되었습니다."
+ },
+ "preparing": {
+ "title": "로그인 준비 중…",
+ "description": "일회용 기기 코드를 가져오고 있습니다."
+ },
+ "authorizing": {
+ "title": "GitHub 로그인",
+ "description": "아래 코드를 복사한 뒤 GitHub 페이지에 입력하여 승인하세요."
+ },
+ "connected": {
+ "title": "GitHub에 연결되었습니다",
+ "description": "이 창을 닫고 계속 사용할 수 있습니다."
+ },
+ "cancelled": {
+ "title": "연결이 취소되었습니다",
+ "description": "준비되면 다시 연결할 수 있습니다."
+ },
+ "unavailable": {
+ "title": "진행 상황을 읽을 수 없음",
+ "description": "현재 진행 상황을 가져올 수 없습니다. 다시 시도해 주세요."
+ },
+ "error": {
+ "title": "연결이 완료되지 않음"
+ }
+ },
+ "errors": {
+ "unsupported": "아직 지원하지 않는 운영 체제 또는 프로세서입니다.",
+ "install": "설치에 실패했습니다. 네트워크와 디스크 공간을 확인하고 다시 시도하세요.",
+ "login": "로그인에 실패했거나 승인이 거부되었습니다. 다시 시도하여 새 코드를 받으세요.",
+ "timeout": "코드가 만료되었습니다. 다시 시도하여 새 코드를 받으세요."
+ },
+ "account": {
+ "checking": "GitHub 연결 확인 중…",
+ "connected": "연결됨 · @{{login}}",
+ "missing": "GitHub에 연결하여 시작하세요.",
+ "auth": "인증이 만료되었습니다. 다시 로그인하거나 아래 예비 토큰을 변경하세요.",
+ "network": "GitHub에 연결할 수 없습니다. 네트워크를 확인하고 다시 시도하세요.",
+ "forbidden": "연결을 확인할 수 없습니다. 권한이나 요청 한도를 확인하고 다시 시도하세요.",
+ "gh-cli": "이 컴퓨터의 GitHub 로그인 사용 중",
+ "token": "예비 토큰 사용 중",
+ "recheck": "연결 확인",
+ "summary": "GitHub 저장소, 이슈, PR 및 Actions를 관리합니다.",
+ "otherMethods": "다른 연결 방법"
}
},
"unresolved": "미해결 리뷰 코멘트: {{count}}건"
diff --git a/apps/desktop/src/renderer/i18n/locales/zh-CN/common.json b/apps/desktop/src/renderer/i18n/locales/zh-CN/common.json
index ed137eb89c..d285ec3b0d 100644
--- a/apps/desktop/src/renderer/i18n/locales/zh-CN/common.json
+++ b/apps/desktop/src/renderer/i18n/locales/zh-CN/common.json
@@ -10404,14 +10404,89 @@
"clickToOpen": "点击在浏览器打开 PR",
"guidance": {
"login": {
- "hint": "点击让 Agent 帮你登录",
- "aria": "PR #{{number}} 状态不可用:让 Agent 登录 GitHub",
- "prompt": "请帮我登录 GitHub CLI:运行 `gh auth login -h github.com -w`,把出现的一次性设备码和网址告诉我;我在浏览器完成授权后,你再用 `gh auth status` 确认登录成功。"
+ "hint": "点击连接 GitHub",
+ "aria": "PR #{{number}} 状态不可用:连接 GitHub"
},
"install": {
- "hint": "点击让 Agent 帮你安装并登录",
- "aria": "PR #{{number}} 状态不可用:让 Agent 安装并登录 GitHub CLI",
- "prompt": "请帮我安装 GitHub CLI(gh,macOS 用 `brew install gh`,Windows 用 `winget install GitHub.cli`),然后运行 `gh auth login -h github.com -w` 登录,把出现的一次性设备码和网址告诉我;我在浏览器完成授权后,你再用 `gh auth status` 确认登录成功。"
+ "hint": "点击连接 GitHub",
+ "aria": "PR #{{number}} 状态不可用:连接 GitHub"
+ }
+ },
+ "setup": {
+ "install": "安装并继续",
+ "connect": "登录 GitHub",
+ "cancel": "取消",
+ "retry": "重试",
+ "done": "完成",
+ "openBrowser": "打开 GitHub 授权",
+ "deviceCode": "一次性设备码",
+ "copyCode": "复制设备码",
+ "copied": "已复制",
+ "copyFailed": "未能复制,请手动选中并复制设备码。",
+ "openFailed": "未能打开浏览器,请手动访问 github.com/login/device。",
+ "stages": {
+ "install": {
+ "title": "安装 GitHub CLI",
+ "description": "安装 GitHub CLI,以连接你的 GitHub 账号。"
+ },
+ "login": {
+ "title": "连接 GitHub",
+ "description": "连接你的 GitHub 账号;尚未安装 GitHub CLI 时会自动安装。"
+ },
+ "checking": {
+ "title": "正在检查连接…",
+ "description": "正在确认 GitHub 登录状态。"
+ },
+ "downloading": {
+ "title": "正在下载 GitHub CLI…",
+ "description": "下载完成后会自动安装。"
+ },
+ "installing": {
+ "title": "正在安装 GitHub CLI…",
+ "description": "下载已完成。"
+ },
+ "preparing": {
+ "title": "正在准备登录…",
+ "description": "正在获取一次性设备码。"
+ },
+ "authorizing": {
+ "title": "登录 GitHub",
+ "description": "复制下方设备码,在 GitHub 页面输入并授权。"
+ },
+ "connected": {
+ "title": "GitHub 已连接",
+ "description": "可以关闭此窗口,继续使用。"
+ },
+ "cancelled": {
+ "title": "已取消连接",
+ "description": "准备好后可以重新连接。"
+ },
+ "unavailable": {
+ "title": "无法读取进度",
+ "description": "暂时无法获取当前进度,请重试。"
+ },
+ "error": {
+ "title": "连接未完成"
+ }
+ },
+ "errors": {
+ "unsupported": "暂不支持此操作系统或处理器。",
+ "install": "安装失败,请检查网络和磁盘空间后重试。",
+ "login": "登录失败或授权被拒绝,请重试获取新设备码。",
+ "timeout": "设备码已过期,请重试获取新设备码。"
+ },
+ "account": {
+ "checking": "正在检查 GitHub 连接…",
+ "connected": "已连接 · @{{login}}",
+ "missing": "连接 GitHub 后即可使用。",
+ "auth": "授权已失效,请重新登录或更换下方备用 Token。",
+ "network": "暂时无法连接 GitHub,请检查网络后重试。",
+ "forbidden": "GitHub 暂时无法验证此连接,请检查权限或请求额度后重试。",
+ "gh-cli": "当前使用本机 GitHub 登录",
+ "token": "当前使用备用 Token",
+ "recheck": "检查连接",
+ "summary": "管理 GitHub 仓库、Issues、PR 和 Actions。",
+ "otherMethods": "其他连接方式"
}
},
"unresolved": "{{count}} 条未解决的 review 评论"
diff --git a/apps/desktop/src/renderer/i18n/locales/zh-TW/common.json b/apps/desktop/src/renderer/i18n/locales/zh-TW/common.json
index a0a3ff99a2..23f0e67590 100644
--- a/apps/desktop/src/renderer/i18n/locales/zh-TW/common.json
+++ b/apps/desktop/src/renderer/i18n/locales/zh-TW/common.json
@@ -10404,14 +10404,89 @@
"clickToOpen": "點擊在瀏覽器開啟 PR",
"guidance": {
"login": {
- "hint": "點擊讓 Agent 幫你登入",
- "aria": "PR #{{number}} 狀態不可用:讓 Agent 登入 GitHub",
- "prompt": "請幫我登入 GitHub CLI:執行 `gh auth login -h github.com -w`,把出現的一次性裝置碼和網址告訴我;我在瀏覽器完成授權後,你再用 `gh auth status` 確認登入成功。"
+ "hint": "點擊連接 GitHub",
+ "aria": "PR #{{number}} 狀態不可用:連接 GitHub"
},
"install": {
- "hint": "點擊讓 Agent 幫你安裝並登入",
- "aria": "PR #{{number}} 狀態不可用:讓 Agent 安裝並登入 GitHub CLI",
- "prompt": "請幫我安裝 GitHub CLI(gh,macOS 用 `brew install gh`,Windows 用 `winget install GitHub.cli`),然後執行 `gh auth login -h github.com -w` 登入,把出現的一次性裝置碼和網址告訴我;我在瀏覽器完成授權後,你再用 `gh auth status` 確認登入成功。"
+ "hint": "點擊連接 GitHub",
+ "aria": "PR #{{number}} 狀態不可用:連接 GitHub"
+ }
+ },
+ "setup": {
+ "install": "安裝並繼續",
+ "connect": "登入 GitHub",
+ "cancel": "取消",
+ "retry": "重試",
+ "done": "完成",
+ "openBrowser": "開啟 GitHub 授權",
+ "deviceCode": "一次性裝置碼",
+ "copyCode": "複製裝置碼",
+ "copied": "已複製",
+ "copyFailed": "無法複製,請手動選取並複製裝置碼。",
+ "openFailed": "無法開啟瀏覽器,請手動前往 github.com/login/device。",
+ "stages": {
+ "install": {
+ "title": "安裝 GitHub CLI",
+ "description": "安裝 GitHub CLI,以連接你的 GitHub 帳號。"
+ },
+ "login": {
+ "title": "連接 GitHub",
+ "description": "連接你的 GitHub 帳號;尚未安裝 GitHub CLI 時會自動安裝。"
+ },
+ "checking": {
+ "title": "正在檢查連接…",
+ "description": "正在確認 GitHub 登入狀態。"
+ },
+ "downloading": {
+ "title": "正在下載 GitHub CLI…",
+ "description": "下載完成後會自動安裝。"
+ },
+ "installing": {
+ "title": "正在安裝 GitHub CLI…",
+ "description": "下載已完成。"
+ },
+ "preparing": {
+ "title": "正在準備登入…",
+ "description": "正在取得一次性裝置碼。"
+ },
+ "authorizing": {
+ "title": "登入 GitHub",
+ "description": "複製下方裝置碼,在 GitHub 頁面輸入並授權。"
+ },
+ "connected": {
+ "title": "GitHub 已連接",
+ "description": "可以關閉此視窗,繼續使用。"
+ },
+ "cancelled": {
+ "title": "已取消連接",
+ "description": "準備好後可以重新連接。"
+ },
+ "unavailable": {
+ "title": "無法讀取進度",
+ "description": "暫時無法取得目前進度,請重試。"
+ },
+ "error": {
+ "title": "連接未完成"
+ }
+ },
+ "errors": {
+ "unsupported": "暫不支援此作業系統或處理器。",
+ "install": "安裝失敗,請檢查網路和磁碟空間後重試。",
+ "login": "登入失敗或授權遭拒,請重試取得新裝置碼。",
+ "timeout": "裝置碼已過期,請重試取得新裝置碼。"
+ },
+ "account": {
+ "checking": "正在檢查 GitHub 連接…",
+ "connected": "已連接 · @{{login}}",
+ "missing": "連接 GitHub 後即可使用。",
+ "auth": "授權已失效,請重新登入或更換下方備用 Token。",
+ "network": "暫時無法連接 GitHub,請檢查網路後重試。",
+ "forbidden": "GitHub 暫時無法驗證此連接,請檢查權限或請求額度後重試。",
+ "gh-cli": "目前使用本機 GitHub 登入",
+ "token": "目前使用備用 Token",
+ "recheck": "檢查連接",
+ "summary": "管理 GitHub 儲存庫、Issues、PR 和 Actions。",
+ "otherMethods": "其他連線方式"
}
},
"unresolved": "{{count}} 條未解決的 review 評論"
diff --git a/apps/desktop/src/renderer/vite-env.d.ts b/apps/desktop/src/renderer/vite-env.d.ts
index 94aba2960a..f90c51e205 100644
--- a/apps/desktop/src/renderer/vite-env.d.ts
+++ b/apps/desktop/src/renderer/vite-env.d.ts
@@ -1321,10 +1321,7 @@ interface ElectronAPI {
) => () => void;
/** Main 已结算(超时、取消或账号切换)某次确认,窗口应收起对应确认框。 */
onInstallConsentDismissed: (callback: (payload: { requestId: string }) => void) => () => void;
- resolveInstallConsent: (
- requestId: string,
- confirmed: boolean,
- ) => Promise<{ handled: boolean }>;
+ resolveInstallConsent: (requestId: string, confirmed: boolean) => Promise<{ handled: boolean }>;
/** Plugin 快捷行最近使用顺序(最新在前,首帧同步读取避免排序跳变)。 */
recentUsageSync: () => { ids: string[] };
/** 成功发送一次 Plugin 指令后记录最近使用。 */
@@ -4357,6 +4354,11 @@ interface ElectronAPI {
// ── session-git-pr-context: 会话分支感知 + PR 关联状态 ──
gitContext: {
+ githubSetupStatus: () => Promise<import('../shared/githubSetup').GithubSetupState>;
+ githubConnection: () => Promise<import('../shared/githubSetup').GithubConnectionState>;
+ startGithubSetup: () => Promise<import('../shared/githubSetup').GithubSetupState>;
+ cancelGithubSetup: () => Promise<import('../shared/githubSetup').GithubSetupState>;
+ onGithubConnected: (cb: () => void) => () => void;
get: (workdir: string) => Promise<import('@/lib/gitContext.types').GitContextSnapshot>;
getForSession: (input: {
sessionId: string;
@@ -5005,8 +5007,23 @@ interface ElectronAPI {
resetCollaborationSettings: () => Promise<unknown>;
};
messages: {
- historyView: (sessionId: string, opts?: { before?: string | null; lazyDetails?: boolean }) => Promise<import('@cindy/maker-shared/message-window').HistoryViewPage<import('@/lib/ccAgent.types').Message>>;
- workDetails: (sessionId: string, ref: import('@cindy/maker-shared/message-window').HistoryWorkReference, opts?: { after?: string | null }) => Promise<import('@cindy/maker-shared/message-window').HistoryDetailPage<import('@/lib/ccAgent.types').Message>>;
+ historyView: (
+ sessionId: string,
+ opts?: { before?: string | null; lazyDetails?: boolean },
+ ) => Promise<
+ import('@cindy/maker-shared/message-window').HistoryViewPage<
+ import('@/lib/ccAgent.types').Message
+ >
+ >;
+ workDetails: (
+ sessionId: string,
+ ref: import('@cindy/maker-shared/message-window').HistoryWorkReference,
+ opts?: { after?: string | null },
+ ) => Promise<
+ import('@cindy/maker-shared/message-window').HistoryDetailPage<
+ import('@/lib/ccAgent.types').Message
+ >
+ >;
list: (
sessionId: string,
opts?: { limit?: number; before?: string; beforeTs?: number },
@@ -6049,10 +6066,18 @@ interface ElectronAPI {
decision: Record<string, unknown>,
) => Promise<{ accepted: boolean }>;
- assistPluginOauth: (request: import('../shared/pluginOauth').LocalPluginOauthRequest) => Promise<{ accepted: boolean }>;
- submitRemotePluginSecret: (request: import('../shared/pluginOauth').LocalPluginSecretRequest) => Promise<{ accepted: boolean }>;
- submitRemotePluginConnection: (request: import('../shared/pluginOauth').LocalPluginConnectionRequest) => Promise<{ accepted: boolean }>;
- pluginOauthDeviceCode: (request: import('../shared/pluginOauthDeviceCode').PluginOauthDeviceCodeRequest) => Promise<import('../shared/pluginOauthDeviceCode').PluginOauthDeviceCodeView | null>;
+ assistPluginOauth: (
+ request: import('../shared/pluginOauth').LocalPluginOauthRequest,
+ ) => Promise<{ accepted: boolean }>;
+ submitRemotePluginSecret: (
+ request: import('../shared/pluginOauth').LocalPluginSecretRequest,
+ ) => Promise<{ accepted: boolean }>;
+ submitRemotePluginConnection: (
+ request: import('../shared/pluginOauth').LocalPluginConnectionRequest,
+ ) => Promise<{ accepted: boolean }>;
+ pluginOauthDeviceCode: (
+ request: import('../shared/pluginOauthDeviceCode').PluginOauthDeviceCodeRequest,
+ ) => Promise<import('../shared/pluginOauthDeviceCode').PluginOauthDeviceCodeView | null>;
/** Submit one inline plugin Secret through the local trusted-frame-only IPC. */
submitPluginSetupInline: (request: {
@@ -6442,7 +6467,9 @@ interface ElectronAPI {
/** 取消对应登录尝试。 */
claudeOAuthCancel: (loginKey?: string) => Promise<{ authorized: boolean }>;
/** 启动 xAI 浏览器或设备码 OAuth 登录;成功写 safeStorage。 */
- xaiOAuthLogin: (method?: 'browser' | 'device') => Promise<{ ok: boolean; authorized: boolean; reason?: string }>;
+ xaiOAuthLogin: (
+ method?: 'browser' | 'device',
+ ) => Promise<{ ok: boolean; authorized: boolean; reason?: string }>;
/** 登出 xAI(清本机 safeStorage 的 xai 凭证) */
xaiOAuthLogout: (ownerScope?: {
dataOwnerId: string | null;
@@ -6600,7 +6627,9 @@ interface ElectronAPI {
piKernel: {
getState: (check?: boolean) => Promise<import('../shared/piKernel').PiKernelState>;
- install: (request: import('../shared/piKernel').PiKernelInstallRequest) => Promise<import('../shared/piKernel').PiKernelState>;
+ install: (
+ request: import('../shared/piKernel').PiKernelInstallRequest,
+ ) => Promise<import('../shared/piKernel').PiKernelState>;
};
/* ── Agent 联合状态 (binary + auth, 取代老 codex.binary.getStatus) ── */
diff --git a/apps/desktop/src/shared/githubSetup.ts b/apps/desktop/src/shared/githubSetup.ts
new file mode 100644
index 0000000000..66de8e8963
--- /dev/null
+++ b/apps/desktop/src/shared/githubSetup.ts
@@ -0,0 +1,20 @@
+/** No credentials, process output or local paths cross this boundary. */
+export type GithubConnectionState =
+ | { status: 'connected'; login: string; source: 'gh-cli' | 'token' }
+ | { status: 'missing' | 'auth' | 'network' | 'forbidden'; source?: 'gh-cli' | 'token' };
+
+export interface GithubSetupState {
+ phase:
+ | 'idle'
+ | 'checking'
+ | 'downloading'
+ | 'installing'
+ | 'authorizing'
+ | 'connected'
+ | 'error'
+ | 'cancelled';
+ percent?: number;
+ userCode?: string;
+ verificationUrl?: 'https://github.com/login/device';
+ error?: 'unsupported' | 'install' | 'login' | 'timeout';
+}
diff --git a/docs/dev-rules/plugin-security-and-authoring.md b/docs/dev-rules/plugin-security-and-authoring.md
index 2432605e5b..02433be047 100644
--- a/docs/dev-rules/plugin-security-and-authoring.md
+++ b/docs/dev-rules/plugin-security-and-authoring.md
@@ -24,19 +24,19 @@
## 事实来源
-| 内容 | 权威来源 |
-| ---------------------------------------------------- | -------- |
-| 编写手册(作者唯一教材,现拿现读) | `apps/desktop/src/main/cindy-brain/forge.ts` 的 `FORGE_GUIDE`,经 `ghost_forge_guide` 工具下发 |
-| `ghost.json` 身份卡字段与校验 | `packages/plugin-protocol/src/manifest.ts` 是跨消费者协议正本;`apps/desktop/src/shared/ghost.ts` 是 Desktop 运行时 validator。除下文登记的 Desktop-only 能力外,两端必须同步维护 |
-| 管子协议类型 | `apps/desktop/src/shared/ghost.ts`(`cindy.send` / `cindy.onHostMessage` 类型) |
-| 打包限制 | `apps/desktop/src/main/cindy-brain/forge.ts` 的 `packGhostDir` |
-| 运行时、沙箱进程与生命周期 | `apps/desktop/src/main/cindy-brain/runtime/GhostRuntime.ts`、`GhostManager.ts` |
-| 安装事务状态、内容摘要与技能快照 receipt | `apps/desktop/src/main/cindy-brain/ghostInstallReceipt.ts`,状态投影见 `shared/ghost.ts` 的 `GhostInstallApproval` |
+| 内容 | 权威来源 |
+| ---------------------------------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
+| 编写手册(作者唯一教材,现拿现读) | `apps/desktop/src/main/cindy-brain/forge.ts` 的 `FORGE_GUIDE`,经 `ghost_forge_guide` 工具下发 |
+| `ghost.json` 身份卡字段与校验 | `packages/plugin-protocol/src/manifest.ts` 是跨消费者协议正本;`apps/desktop/src/shared/ghost.ts` 是 Desktop 运行时 validator。除下文登记的 Desktop-only 能力外,两端必须同步维护 |
+| 管子协议类型 | `apps/desktop/src/shared/ghost.ts`(`cindy.send` / `cindy.onHostMessage` 类型) |
+| 打包限制 | `apps/desktop/src/main/cindy-brain/forge.ts` 的 `packGhostDir` |
+| 运行时、沙箱进程与生命周期 | `apps/desktop/src/main/cindy-brain/runtime/GhostRuntime.ts`、`GhostManager.ts` |
+| 安装事务状态、内容摘要与技能快照 receipt | `apps/desktop/src/main/cindy-brain/ghostInstallReceipt.ts`,状态投影见 `shared/ghost.ts` 的 `GhostInstallApproval` |
| 能力实现(网络/通知/确认/文件系统/技能/宿主等) | `networkSlot.ts`、`notifySlot.ts`、`badgeSlot.ts`、`confirmSlot.ts`、`fsSlot.ts`、`cindySlot.ts`、`skillSlot.ts`、`agentSlot.ts`、`errandSlot.ts`、`iosSimulatorSlot.ts`;持久作品库见 [`plugin-library-storage.md`](plugin-library-storage.md),主实现在 `libraryVault.ts`、`librarySlot.ts`、`libraryDbCore.ts` |
-| 面板供片、注入主题 token 与协议 | `apps/desktop/src/renderer/cindy-brain/ghostPanelTheme.ts`、`cindy-ghost://` 分支 |
-| 插件详情能力说明 UI | `apps/desktop/src/renderer/features/plugin/GhostPluginDetailView.tsx` |
-| 远程/手机版能力准入白名单 | `packages/device-link/src/allowlist.ts` |
-| 行为与安全不变量 | `apps/desktop/src/main/cindy-brain/__tests__/`、`forge.test.ts` |
+| 面板供片、注入主题 token 与协议 | `apps/desktop/src/renderer/cindy-brain/ghostPanelTheme.ts`、`cindy-ghost://` 分支 |
+| 插件详情能力说明 UI | `apps/desktop/src/renderer/features/plugin/GhostPluginDetailView.tsx` |
+| 远程/手机版能力准入白名单 | `packages/device-link/src/allowlist.ts` |
+| 行为与安全不变量 | `apps/desktop/src/main/cindy-brain/__tests__/`、`forge.test.ts` |
文档与实现冲突时以代码为准,但必须在同一改动内同步修正本文与手册。
@@ -258,7 +258,7 @@
能在其中一处找到没覆盖的角落,补一处、下一轮换另一处。
- 新增任何"读插件内容目录"的代码一律从这里取判据,**不要就地 `readdir` + `isDirectory()`
或 `stat` 直读**。只 `lstat` 最终段等于没判:中间段被换成软链/junction 时 OS 会
- 静默穿透,最终段报的是"真目录、非链接",字节却来自插件目录之外。
+ 静默穿透,最终段报的是"真目录、非链接",字节却来自插件目录之外。
- `hashGhostContentFiles` 的摘要编码必须保持无歧义 framing(当前为
`cindy-ghost-content-v2` + UTF-8 路径长度前缀 + 每文件摘要),不得恢复成
`path + NUL + bytes + NUL`;文件内容本身允许包含 NUL,分隔符编码会产生不同文件树
@@ -268,8 +268,8 @@
receipt(安全水位与旧版本已提供的保证等价),只有对不上(真漂移)才 fail closed 并
要求重新安装合法包——不得把一次纯格式升级直接变成全体用户的重新安装操作。
- 同理,"源目录与受管根的包含关系"必须**双向**判(既不能落在受管根内,也不能是受管
- 根的祖先):单向判定下只要在 owner 数据目录里放一个 `ghost.json`,递归打包就会把
- 已安装插件字节、批准 receipt 与技能快照打进 `.cindy`。
+ 根的祖先):单向判定下只要在 owner 数据目录里放一个 `ghost.json`,递归打包就会把
+ 已安装插件字节、批准 receipt 与技能快照打进 `.cindy`。
- 随包种子是第一方输入;发现链接、junction、FIFO 等非普通条目必须整颗跳过并告警,
不得在复制时静默丢弃后继续写批准 receipt。
@@ -281,9 +281,11 @@
未命中目标 host 的托管凭证。
- `source: "gh-cli"` 是只为官方 `cindy-github` 保留的宿主凭证来源:Host 优先读取
本机 `gh auth token`,不可用时才回落到同 key 经 `/secrets` 保存的 PAT。两种 token
- 均只在 Main 的 networkSlot 内存中注入 `api.github.com` 的
+ 均只在 Main 的 networkSlot 或受信本机账号检查中注入 `api.github.com` 的
`Authorization: Bearer` 请求头,不得进入插件、Renderer、Agent、KV、日志或 Node
- Worker。设置页只能读取 `hostAvailable` 布尔与备用 PAT 的 `saved/tail` 状态。该来源
+ Worker。本机账号检查仅允许固定 GET `/user`,拒绝重定向,限时 15 秒;只返回
+ 连接分类、用户名和来源,不返回响应原文。插件设置页只能读取 `hostAvailable`、
+ `hostManagedSetup` 布尔与备用 PAT 的 `saved/tail` 状态。该来源
不允许 `exchange` 或 `setup.requires` 引用,第三方插件不得声明。
- `source: "oidc-token"` 是 Host 托管的短时 Cindy Connection JWT:只对当前企业
Membership 生效。资格有两条默认基座:当前组织的 Plugin Market organization 安装记录仍有效、
@@ -360,7 +362,7 @@
close/detach 已开始、会话缺失、实例不匹配、查询失败、远程会话均 fail closed。
对 Codex、Pi 与远端 Claude Code 这类进程外 harness,instance 只作为 opaque MCP route
identity 写入 Host 生成的 loopback URL;桥接层必须将 URL identity 与注册表中的当前实例
- 严格比对,不匹配直接 401。 兼容旧客户端时,缺 instance 的 URL 可继续获得普通会话上下文,
+ 严格比对,不匹配直接 401。 兼容旧客户端时,缺 instance 的 URL 可继续获得普通会话上下文,
但必须剥除 instance 能力,使 Full Access 自动交接继续 fail closed。
越界文件系统副作用(cindy-docs / 电脑工具的 `outside_workdir`,以及 Forge 的
`forge_source`)在缺少 instance、live grant 读不到或实例已失效时直接拒绝,
@@ -605,7 +607,7 @@ topic 路由;产品层多端语义见
3. receipt 是否仍只由 Main 的合法安装/更新/迁移事务写入?跨进程更新是否回传
`ghostInstallApprovalToken()` 并在锁内重读比对?缺失或损坏状态是否优先无感迁移,
而不是用安装确认充当恢复方案?停用方向是否始终可成功?技能快照与字节指纹是否仍受保护?
-3.5. 新增或改动的装入路径是否显式交出安装确认策略,并在锁内用真实包复核
+ 3.5. 新增或改动的装入路径是否显式交出安装确认策略,并在锁内用真实包复核
(`assertGhostInstallConsent`)?确认等待是否在所有安装锁与 owner 租约之外?后台路径是否
只会 `automatic` 放弃、从不替用户确认?Agent 路径是否不受任务权限档影响、始终确认?
4. Agent 在途网络是否仍通过 URL/SSRF/重定向等 Host 守门,自主网络是否限 manifest
@@ -616,9 +618,9 @@ topic 路由;产品层多端语义见
6. Forge(scaffold/pack/install)是否排除了 Host 受管根,按 realpath 双向判定并挡住
大小写与软链/junction 别名?`ghost_forge_pack` 是否仍然只产出 `.cindy`,没有隐式安装;
`ghost_forge_install` 是否只在用户明确要求时调用并复用本地安装/更新事务?
-6.5. 新增的“读插件内容目录”代码是否走 `ghostContentTree.ts` 的统一分类、逐段路径解析和
+ 6.5. 新增的“读插件内容目录”代码是否走 `ghostContentTree.ts` 的统一分类、逐段路径解析和
指纹格式,而不是就地复制一份 `readdir`/`stat` 实现?
-6.6. **存量插件升级后还能不能用(第 5 节红线)**:改动安装状态记录、manifest、能力字段、
+ 6.6. **存量插件升级后还能不能用(第 5 节红线)**:改动安装状态记录、manifest、能力字段、
快照、安装根、包格式或管子协议时,是否提供无感 backfill,保留已装、启停、凭证与偏好,
并覆盖旧布局 fixture?让存量插件失效且无迁移 = P0。
7. 改动是否命中作者可见契约(身份卡/管子/模型代办能力/面板供片/打包)?命中就必须
diff --git a/docs/dev-rules/repo-map.md b/docs/dev-rules/repo-map.md
index 361d7b1e9e..8296ecd8ed 100644
--- a/docs/dev-rules/repo-map.md
+++ b/docs/dev-rules/repo-map.md
@@ -9,53 +9,59 @@
## 顶层结构
-| 路径 | 说明 |
-|---|---|
-| `apps/` | 终端产品(desktop、mobile)与随包分发的二进制资产 |
-| `packages/` | 客户端共享能力包(与 render/main 解耦,详见下表) |
-| `config/` | 运行期端点清单(`endpoint.json` / `endpoint.dev.json` / `endpoint.global.json`:auth、device-link 等线上 base URL) |
-| `scripts/` | 仓库级工程脚本:dev 启动包装、agent 二进制拉取(`ensure-agent-binaries.mjs`)、i18n/endpoint/文档等校验 guard、worktree 管理 |
-| `tools/` | claude/codex/ripgrep/pi 四个 Desktop runtime 的版本 pin(`latest.json`)与更新器(`update.mjs`) |
-| `docs/` | 规则文档:`dev-rules/`(工程)、`product-rules/`(产品)、`design-rules/`(设计入口)、`legal/` 等 |
+| 路径 | 说明 |
+| ----------- | ------------------------------------------------------------------------------------------------------------------------------ |
+| `apps/` | 终端产品(desktop、mobile)与随包分发的二进制资产 |
+| `packages/` | 客户端共享能力包(与 render/main 解耦,详见下表) |
+| `config/` | 运行期端点清单(`endpoint.json` / `endpoint.dev.json` / `endpoint.global.json`:auth、device-link 等线上 base URL) |
+| `scripts/` | 仓库级工程脚本:dev 启动包装、agent 二进制拉取(`ensure-agent-binaries.mjs`)、i18n/endpoint/文档等校验 guard、worktree 管理 |
+| `tools/` | claude/codex/ripgrep/pi 四个 Desktop runtime 的版本 pin(`latest.json`)与更新器(`update.mjs`) |
+| `docs/` | 规则文档:`dev-rules/`(工程)、`product-rules/`(产品)、`design-rules/`(设计入口)、`legal/` 等 |
## apps/
-| 路径 | 说明 |
-|---|---|
-| `apps/desktop` | Cindy 桌面客户端(Electron + Vite),源码分 `main/`(主进程:业务逻辑、maker-host/maker-ipc、localDb、device-link、mcp-integrations、cindy-brain 等)、`renderer/`(纯渲染 UI:features、panels、themes、i18n 等)、`preload/`(最小桥接层)、`shared/`(主/渲染共享类型与常量);SQLite migration 在 `apps/desktop/drizzle/` |
-| `apps/mobile` | Cindy 手机客户端(Expo / React Native):同账号登录、发现并远程控制桌面设备、镜像会话 |
-| `apps/claude-code-bin`、`apps/codex-bin`、`apps/ripgrep-bin` | 随桌面端分发的预编译 CLI 二进制(按平台分目录)。不是构建包、不进 git 历史;版本由 `tools/<kind>/latest.json` pin,`pnpm install` postinstall 按需下载 |
-| `apps/android-platform-tools-bin` | Android platform-tools(adb 等)二进制,当前仅 win32-x64,用于连接安卓设备 |
+| 路径 | 说明 |
+| ------------------------------------------------------------ | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
+| `apps/desktop` | Cindy 桌面客户端(Electron + Vite),源码分 `main/`(主进程:业务逻辑、maker-host/maker-ipc、localDb、device-link、mcp-integrations、cindy-brain 等)、`renderer/`(纯渲染 UI:features、panels、themes、i18n 等)、`preload/`(最小桥接层)、`shared/`(主/渲染共享类型与常量);SQLite migration 在 `apps/desktop/drizzle/` |
+| `apps/mobile` | Cindy 手机客户端(Expo / React Native):同账号登录、发现并远程控制桌面设备、镜像会话 |
+| `apps/claude-code-bin`、`apps/codex-bin`、`apps/ripgrep-bin` | 随桌面端分发的预编译 CLI 二进制(按平台分目录)。不是构建包、不进 git 历史;版本由 `tools/<kind>/latest.json` pin,`pnpm install` postinstall 按需下载 |
+| `apps/android-platform-tools-bin` | Android platform-tools(adb 等)二进制,当前仅 win32-x64,用于连接安卓设备 |
## packages/
「主要使用方」按各 `package.json` 的 workspace 依赖核对;mobile 只直接依赖其中
5 个(auth-client、device-link、maker-shared、model-providers、voice-input-core)。
-| 包 | 一句话用途 | 主要使用方 |
-|---|---|---|
-| `maker-core` | Cindy 核心:agent 抽象(BaseAgent)、session 编排与事件流,零 Electron 依赖;改动前必读 [`maker-core-and-agent-behavior.md`](maker-core-and-agent-behavior.md) | desktop、lizi-mcps、orca-workflow |
-| [`design-tokens`](../../packages/design-tokens/README.md) | DTCG reference / semantic / 薄 component 字典与 Terrazzo 生成合同 | DS-8 已接 Desktop 生产颜色、主题与通用基础;DS-9 消费现有链路,Mobile 后续独立接管 |
-| `maker-shared` | 桌面与手机共享的展示层契约模型,零 React/Electron/Expo 依赖 | desktop + mobile |
-| `maker-cc-manager` | cc-remote:跑在远程 SSH 机器上的 NDJSON RPC 守护进程,封装 Claude Agent SDK,向本地桌面暴露多会话/detach-reattach 能力 | desktop(remote-ssh) |
-| `maker-pi-manager` | pi-remote:跑在远程 SSH 机器上的 PI 单例 daemon(TS NDJSON RPC + unix socket bridge),持有 pi 会话、条件 restart、空闲回收 | desktop(remote-ssh) |
-| `maker-remote-ssh` | SSH remote:连接池、`~/.ssh/config` 读写、凭据解析,零 Electron 依赖 | desktop |
-| `maker-scheduler` | 定时任务:cron 引擎 + storage/runner/notifier 接口 | desktop、lizi-mcps |
-| `orca-workflow` | Orca 多 worker 协同的 lead 侧:MCP 桥接 + lead prompt;改动前必读 [`orca-team-architecture.md`](orca-team-architecture.md) | desktop |
-| `device-link` | 跨设备远程控制(同账号互联):envelope 协议、IPC 隧道 allowlist、重连/心跳;零依赖,WS 实现由 host 注入 | desktop + mobile |
-| `auth-client` | 平台无关的 Cindy auth-server 客户端契约(zod) | desktop + mobile |
-| `model-providers` | 模型供应商目录、Registry 资料合并与路由抽象;先读 [模型配置与下发](model-catalog-maintenance.md) 获取代码导航 | desktop + mobile |
-| `anthropic-compat-proxy` | 本地回环 HTTP 代理:剥离 Anthropic 专有字段,让 Claude Code SDK 可经网关访问非 Anthropic 后端 | desktop |
-| `anthropic-responses-bridge` | 挂载在 `anthropic-compat-proxy` 回环 HTTP 代理内部的进程内协议转换处理器:作为 `RoutingDecision.localHandler` 完成 Anthropic Messages API ↔ OpenAI Responses API 转换 | desktop |
-| `responses-anthropic-bridge` | 本地 Responses → Anthropic Messages 桥:请求、图片/工具/thinking 转换与 Responses SSE 回译 | desktop |
-| `lizi-mcps` | 可复用 MCP server 集合(Google 套件、GitHub/GitLab、浏览器、scheduler 等) | desktop |
-| `cindy-tools` | 意识(Ghost)系统内部工具集(MCP),含 ghost 总机(`ghost_list` / `ghost_info` / `ghost_call`) | desktop |
-| `browser-control-runtime` | 浏览器自动化运行时适配层(playwright-core + MCP) | desktop、lizi-mcps |
-| `file-browser-core` | 文件浏览核心:workdir 扫描、ignore 匹配、ripgrep 搜索;本地后端与远程守护进程共享 | desktop、remote-file-service |
-| `remote-file-service` | 远程文件服务:跑在远程 SSH 机器上的 NDJSON RPC 守护进程,封装 file-browser-core | desktop |
-| `github-client` / `gitlab-client` | GitHub REST v3 / GitLab REST v4 客户端,零运行时依赖 | desktop/lizi-mcps |
-| `embedding-client` | OpenAI `/v1/embeddings` 兼容客户端(走网关) | desktop |
-| `heartbeat-client` | 在线心跳:周期上报维持在线状态,零依赖 | desktop |
-| `lizi-im` | IM 传输层(飞书等 WS 通道):凭据存储、附件下载、统一发送 API;host 注入适配 | desktop |
-| `project-context` | agent 维护的项目知识层(commit 驱动的 markdown CLI) | desktop(maker-ipc) |
-| `voice-input-core` | 语音输入核心:供应商无关的听写状态机与润色守卫 | desktop + mobile |
+| 包 | 一句话用途 | 主要使用方 |
+| --------------------------------------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ---------------------------------------------------------------------------------- |
+| `maker-core` | Cindy 核心:agent 抽象(BaseAgent)、session 编排与事件流,零 Electron 依赖;改动前必读 [`maker-core-and-agent-behavior.md`](maker-core-and-agent-behavior.md) | desktop、lizi-mcps、orca-workflow |
+| [`design-tokens`](../../packages/design-tokens/README.md) | DTCG reference / semantic / 薄 component 字典与 Terrazzo 生成合同 | DS-8 已接 Desktop 生产颜色、主题与通用基础;DS-9 消费现有链路,Mobile 后续独立接管 |
+| `maker-shared` | 桌面与手机共享的展示层契约模型,零 React/Electron/Expo 依赖 | desktop + mobile |
+| `maker-cc-manager` | cc-remote:跑在远程 SSH 机器上的 NDJSON RPC 守护进程,封装 Claude Agent SDK,向本地桌面暴露多会话/detach-reattach 能力 | desktop(remote-ssh) |
+| `maker-pi-manager` | pi-remote:跑在远程 SSH 机器上的 PI 单例 daemon(TS NDJSON RPC + unix socket bridge),持有 pi 会话、条件 restart、空闲回收 | desktop(remote-ssh) |
+| `maker-remote-ssh` | SSH remote:连接池、`~/.ssh/config` 读写、凭据解析,零 Electron 依赖 | desktop |
+| `maker-scheduler` | 定时任务:cron 引擎 + storage/runner/notifier 接口 | desktop、lizi-mcps |
+| `orca-workflow` | Orca 多 worker 协同的 lead 侧:MCP 桥接 + lead prompt;改动前必读 [`orca-team-architecture.md`](orca-team-architecture.md) | desktop |
+| `device-link` | 跨设备远程控制(同账号互联):envelope 协议、IPC 隧道 allowlist、重连/心跳;零依赖,WS 实现由 host 注入 | desktop + mobile |
+| `auth-client` | 平台无关的 Cindy auth-server 客户端契约(zod) | desktop + mobile |
+| `model-providers` | 模型供应商目录、Registry 资料合并与路由抽象;先读 [模型配置与下发](model-catalog-maintenance.md) 获取代码导航 | desktop + mobile |
+| `anthropic-compat-proxy` | 本地回环 HTTP 代理:剥离 Anthropic 专有字段,让 Claude Code SDK 可经网关访问非 Anthropic 后端 | desktop |
+| `anthropic-responses-bridge` | 挂载在 `anthropic-compat-proxy` 回环 HTTP 代理内部的进程内协议转换处理器:作为 `RoutingDecision.localHandler` 完成 Anthropic Messages API ↔ OpenAI Responses API 转换 | desktop |
+| `responses-anthropic-bridge` | 本地 Responses → Anthropic Messages 桥:请求、图片/工具/thinking 转换与 Responses SSE 回译 | desktop |
+| `lizi-mcps` | 可复用 MCP server 集合(Google 套件、GitHub/GitLab、浏览器、scheduler 等) | desktop |
+| `cindy-tools` | 意识(Ghost)系统内部工具集(MCP),含 ghost 总机(`ghost_list` / `ghost_info` / `ghost_call`) | desktop |
+| `browser-control-runtime` | 浏览器自动化运行时适配层(playwright-core + MCP) | desktop、lizi-mcps |
+| `file-browser-core` | 文件浏览核心:workdir 扫描、ignore 匹配、ripgrep 搜索;本地后端与远程守护进程共享 | desktop、remote-file-service |
+| `remote-file-service` | 远程文件服务:跑在远程 SSH 机器上的 NDJSON RPC 守护进程,封装 file-browser-core | desktop |
+| `github-client` / `gitlab-client` | GitHub REST v3 / GitLab REST v4 客户端,零运行时依赖 | desktop/lizi-mcps |
+| `embedding-client` | OpenAI `/v1/embeddings` 兼容客户端(走网关) | desktop |
+| `heartbeat-client` | 在线心跳:周期上报维持在线状态,零依赖 | desktop |
+| `lizi-im` | IM 传输层(飞书等 WS 通道):凭据存储、附件下载、统一发送 API;host 注入适配 | desktop |
+| `project-context` | agent 维护的项目知识层(commit 驱动的 markdown CLI) | desktop(maker-ipc) |
+| `voice-input-core` | 语音输入核心:供应商无关的听写状态机与润色守卫 | desktop + mobile |
+
+## 校验下载与工具安装
+
+Desktop 发行资产统一走 `main/downloader/index.ts`;通用工具安装位于
+`main/managed-tools/`。接入方法和各业务保留的边界见
+[校验下载与受管工具安装](verified-downloads.md)。
diff --git a/docs/dev-rules/verified-downloads.md b/docs/dev-rules/verified-downloads.md
new file mode 100644
index 0000000000..d14b948a4f
--- /dev/null
+++ b/docs/dev-rules/verified-downloads.md
@@ -0,0 +1,78 @@
+# 校验下载与受管工具安装
+
+Desktop 下载已知大小/SHA-256 的发行资产,统一调用
+`apps/desktop/src/main/downloader/index.ts` 的 `download()`。
+Agent runtime、Cindy Make 工具、Ollama runtime、插件包、Skill 包及更新包共用该入口。
+业务模块保留来源选择、包格式、授权、安装和 UI 错误映射;不再复制 HTTP、写盘、哈希、
+进度、超时、重试或断点续传实现。
+
+## 调用约定
+
+- `sha256` 必填。`expectedSize` 同时检查响应头与实际字节;`maxBytes` 在写盘前限制流大小。
+- `isUrlAllowed` 检查初始 URL 和每次重定向。插件包继续 `redirect: 'error'`;
+ Ollama 使用其官方发行资产白名单。统一下载不得放宽调用方已有来源限制。
+- `signal` 取消排队、请求和重试等待;连接/闲置超时可重试,`timeout.totalMs`
+ 限制含排队的整体时长。业务取消与超时分别返回 `ABORTED` 和 `TIMEOUT`。
+- 默认保留部分文件以续传;一次性安装暂存目录可用 `resume: false`。
+ 调用方只有在下载 Promise 结束后才可 `cleanup()` 或删除暂存目录。
+- 默认校验成功后替换目标,下载失败保留原目标;`existingTarget: 'error'`
+ 原子地拒绝覆盖已有文件。不要让多个进程共写同一个暂存路径。
+- 同一目标同时只能有一份下载;完全相同的参数可复用在途 Promise,来源、策略、回调或
+ 取消信号不同则拒绝冲突,不能共享另一调用方更宽松的校验结果。
+- `download()` resolve 表示大小和 SHA-256 已通过且文件已就位。
+ 最终完成通知之后的取消不撤销已经发布的文件。缓存命中同样检查来源策略、大小与哈希。
+- 进度描述当前尝试;服务器忽略 Range 时重新从零下载,UI 应保留自身已有的显示平滑策略。
+ 速度和节流由公共下载器计算,不再在资产安装入口复制。
+- HTTP 走 Electron `net.request`(逐跳检查重定向),沿用系统代理;流按块等待落盘,避免大资产无限堆积内存。
+ 网络错误不回传可能含签名 URL 的原始异常。
+
+## 受管工具安装
+
+`main/managed-tools/installer.ts` 和 `archive.ts` 提供通用的发行包解压、版本检查、
+完整代次发布及安装路径发现。调用方传入可信的 `ToolArtifact` 与用户数据根目录,
+成功取得绝对执行路径,直接用它启动工具,不依赖系统 PATH 或 Homebrew。
+
+Cindy Make 保留旧导出和安装目录,旧 `current.json` 不需迁移。GitHub CLI 使用
+`git-context/ghArtifact.ts` 中固定版本的官方发行包和摘要,安装到
+`userData/managed-tools`。新工具应复用这里;发行版选择、登录和产品入口不进入下载器。
+Ollama 本次共用下载层,仍保留其现有 runtime 解压和启动布局。
+
+## GitHub 连接
+
+本机 PR 徽标缺少 gh/登录态时,点击打开 `GithubSetupDialog`。主进程统一发现
+受管安装、系统安装和 `~/.local/bin`,使用绝对路径调用 gh,不要求刷新 PATH 或重启。
+GitHub 插件详情与「我的 Issues」通过 `GithubConnectButton` 复用同一窗口。
+连接成功后分别重新加载插件配置区与强制刷新 Issues;列表已有请求时排队刷新,避免漏掉新登录态。
+Issues 连接入口是可选增强,不作为原有 Cindy Issue 列表和提交能力的前置条件。
+GitHub 插件由宿主显示单一账号区,通过固定 GitHub `/user` 请求验证用户名与当前来源;
+优先 gh,取不到凭证时才使用备用 PAT,不把网络或单项操作权限错误当作退出登录。
+插件 1.2.8 起在 `/secrets` 的 `hostManagedSetup` 为 true 时仅显示折叠的备用 Token 区,
+旧宿主仍保留插件自带状态和测试连接。保存/清除 PAT、登录完成、窗口重新聚焦时刷新
+宿主账号状态;账号切换重挂载,丢弃旧请求,凭证明文不进入渲染进程。
+宿主统一折叠「其他连接方式」,并兼容官方插件 1.2.7 的旧设置页:仅隐藏重复的账号说明
+和测试按钮,保留插件的只写 Token 表单;不更改插件安装内容或官方来源校验。
+账号行与折叠区使用不同的 React key,避免账号切换或刷新时遗留重复行。
+`githubSetup.ts` 先检查现有安装和登录,必要时安装并用非交互管道启动官方设备码流程。
+Renderer 只接收阶段、进度、设备码和固定 GitHub 授权地址,不接收 token 或 CLI 原始输出。
+点击遮罩不会关闭窗口或取消操作;取消按钮或 Esc 会请求中止下载/登录,已安装的工具保留。
+新登录在 gh 默认的 `repo/read:org/gist` 外申请 `workflow/project/notifications/read:packages/write:packages`,
+覆盖日常工作流、Projects、通知和包发布;最终授权由用户在 GitHub 页面确认,已有登录不强制重新授权。
+安装、下载、授权和完成各有独立文案与操作。下载复用 `DownloadMeter`,
+成功后只提供「完成」,并停止轮询;再次打开不把上一次成功当作新的登录检查结果。
+
+登录成功用 `gh auth status --hostname github.com` 复核,然后清除 token 和 PR 缓存,
+通过 `git-context:github-connected` 立即刷新顶栏及侧栏。缓存代数隔离登录前的在途响应。
+安装/登录 IPC 仅限受信本机主窗口,不开放给共享任务或 device-link;SSH/手机远程查看
+继续使用被控端现有 PR 查询和刷新通道,不会误操作控制端的 GitHub 账号。
+
+## 边界
+
+本模块处理有发布者摘要的文件资产,不承担凭证获取、模型服务的 pull 协议、
+设备直传或媒体资源归属授权。它们可保留专用协议;不能为统一形式取消摘要要求,
+也不能把远端 SSH 下载静默改为本机写盘。
+
+应用更新复用底层传输,本次不改变更新包选择、签名验证、安装替换和重启流程。
+底层改动仍需覆盖更新包调用方式;更新器本体遵守 `cindy-updater.md`。
+
+回归入口:`main/downloader/__tests__`、`main/managed-tools/__tests__`,以及
+Ollama、plugin-market、SkillHub、Cindy Make 和 agent-binaries 的相关测试。