Skip to content

armgit / cindy

Public Imported from GitHub
0

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

fix(pi): 简化包安装与启用流程 (#3138)

Chris Zhang489c575eb04d
diff --git a/apps/desktop/src/main/maker-host/__tests__/pi-package-store-security.test.ts b/apps/desktop/src/main/maker-host/__tests__/pi-package-store-security.test.ts
index 6956fab10f..7beb5d6aa0 100644
--- a/apps/desktop/src/main/maker-host/__tests__/pi-package-store-security.test.ts
+++ b/apps/desktop/src/main/maker-host/__tests__/pi-package-store-security.test.ts
@@ -439,7 +439,7 @@ describe('Pi package executable-code boundary', () => {
await expect(store.mutatePiPackage(request, fresh)).rejects.toThrow(/invalid or expired/i);
});
- it('holds Extension packages disabled until explicit approval and revokes approval on update', async () => {
+ it('holds Extension packages disabled until explicit approval and re-enables them after a confirmed update', async () => {
const { root, source } = await createPackage();
await fs.mkdir(path.join(root, 'skills', 'sample'), { recursive: true });
await fs.writeFile(
@@ -502,9 +502,9 @@ describe('Pi package executable-code boundary', () => {
const updated = await mutateAuthorized(store, { action: 'update', source });
expect(updated.affectedPackage).toMatchObject({
source,
- enabled: false,
- requiresExtensionApproval: true,
+ enabled: true,
});
+ expect(updated.affectedPackage?.requiresExtensionApproval).toBeUndefined();
await fs.rm(root, { recursive: true, force: true });
await expect(Promise.all([
fs.readFile(snapshotExtension, 'utf8'),
@@ -513,6 +513,179 @@ describe('Pi package executable-code boundary', () => {
])).resolves.toEqual(frozenResources);
});
+ it('enables an Extension package from the same confirmed install', async () => {
+ const { source } = await createPackage();
+ const store = await import('../pi-package-store.js');
+
+ const installed = await mutateAuthorized(store, { action: 'install', source });
+
+ expect(installed.affectedPackage).toMatchObject({
+ source,
+ enabled: true,
+ });
+ expect(installed.affectedPackage?.requiresExtensionApproval).toBeUndefined();
+ expect(installed.packages).toMatchObject([{ source, enabled: true }]);
+ });
+
+ it('keeps an explicitly disabled Extension package disabled after a confirmed update', async () => {
+ const { source } = await createPackage();
+ const store = await import('../pi-package-store.js');
+ await mutateAuthorized(store, { action: 'set-enabled', source, enabled: true });
+ await mutateAuthorized(store, { action: 'set-enabled', source, enabled: false });
+
+ const updated = await mutateAuthorized(store, { action: 'update', source });
+
+ expect(updated.affectedPackage).toMatchObject({
+ source,
+ enabled: false,
+ requiresExtensionApproval: true,
+ });
+ });
+
+ it('does not disable an already-enabled npm Extension when another package is installed', async () => {
+ const firstSource = 'npm:first-shared-extension';
+ const secondSource = 'npm:second-shared-extension';
+ const npmRoot = path.join(runtime.userData, 'pi-package-home', 'npm');
+ const nodeModulesRoot = path.join(npmRoot, 'node_modules');
+ const firstRoot = path.join(nodeModulesRoot, 'first-shared-extension');
+ const secondRoot = path.join(nodeModulesRoot, 'second-shared-extension');
+ const writeExtension = async (packageRoot: string, name: string) => {
+ await fs.mkdir(path.join(packageRoot, 'extensions'), { recursive: true });
+ await fs.writeFile(path.join(packageRoot, 'package.json'), JSON.stringify({
+ name,
+ version: '1.0.0',
+ pi: { extensions: ['./extensions/index.js'] },
+ }));
+ await fs.writeFile(
+ path.join(packageRoot, 'extensions', 'index.js'),
+ `module.exports = function setup${name.replace(/\W/g, '')}() {};\n`,
+ );
+ };
+ await writeExtension(firstRoot, 'first-shared-extension');
+ runtime.listOutput = `User packages:\n ${firstSource}\n ${firstRoot}\n`;
+ const store = await import('../pi-package-store.js');
+ await mutateAuthorized(store, {
+ action: 'set-enabled',
+ source: firstSource,
+ enabled: true,
+ });
+
+ runtime.holdMutationCommand = true;
+ const installing = mutateAuthorized(store, {
+ action: 'install',
+ source: secondSource,
+ });
+ await vi.waitFor(() => {
+ expect(runtime.spawns.at(-1)?.args).toEqual(
+ expect.arrayContaining(['install', secondSource]),
+ );
+ });
+ await writeExtension(secondRoot, 'second-shared-extension');
+ runtime.listOutput = [
+ 'User packages:',
+ ` ${firstSource}`,
+ ` ${firstRoot}`,
+ ` ${secondSource}`,
+ ` ${secondRoot}`,
+ '',
+ ].join('\n');
+ runtime.holdMutationCommand = false;
+ runtime.pendingClose?.(0);
+ const installed = await installing;
+
+ expect(installed.packages).toEqual(expect.arrayContaining([
+ expect.objectContaining({ source: firstSource, enabled: true }),
+ expect.objectContaining({ source: secondSource, enabled: true }),
+ ]));
+ expect(installed.packages.every((pkg) => pkg.requiresExtensionApproval !== true)).toBe(true);
+ });
+
+ it('does not reapprove a sibling whose scoped hoisted dependency changes during install', async () => {
+ const firstSource = 'npm:@scope/stale-shared-extension';
+ const secondSource = 'npm:new-shared-extension';
+ const npmRoot = path.join(runtime.userData, 'pi-package-home', 'npm');
+ const nodeModulesRoot = path.join(npmRoot, 'node_modules');
+ const firstRoot = path.join(nodeModulesRoot, '@scope', 'stale-shared-extension');
+ const secondRoot = path.join(nodeModulesRoot, 'new-shared-extension');
+ const dependencyRoot = path.join(nodeModulesRoot, '@scope', 'node_modules', 'shared-runtime-dependency');
+ const writeExtension = async (packageRoot: string, name: string) => {
+ await fs.mkdir(path.join(packageRoot, 'extensions'), { recursive: true });
+ await fs.writeFile(path.join(packageRoot, 'package.json'), JSON.stringify({
+ name,
+ version: '1.0.0',
+ pi: { extensions: ['./extensions/index.js'] },
+ }));
+ await fs.writeFile(
+ path.join(packageRoot, 'extensions', 'index.js'),
+ `module.exports = function setup${name.replace(/\W/g, '')}() {};\n`,
+ );
+ };
+ await writeExtension(firstRoot, 'stale-shared-extension');
+ await fs.writeFile(path.join(firstRoot, 'package.json'), JSON.stringify({
+ name: '@scope/stale-shared-extension', version: '1.0.0',
+ dependencies: { 'shared-runtime-dependency': '^1.0.0' },
+ pi: { extensions: ['./extensions/index.js'] },
+ }));
+ await fs.writeFile(
+ path.join(firstRoot, 'extensions', 'index.js'),
+ "require('shared-runtime-dependency');\nmodule.exports = function setupStale() {};\n",
+ );
+ await fs.mkdir(dependencyRoot, { recursive: true });
+ await fs.writeFile(path.join(dependencyRoot, 'package.json'), JSON.stringify({ name: 'shared-runtime-dependency', version: '1.0.0', main: './index.js' }));
+ await fs.writeFile(path.join(dependencyRoot, 'index.js'), 'module.exports = "approved";\n');
+ runtime.listOutput = `User packages:\n ${firstSource}\n ${firstRoot}\n`;
+ const store = await import('../pi-package-store.js');
+ await mutateAuthorized(store, {
+ action: 'set-enabled',
+ source: firstSource,
+ enabled: true,
+ });
+ runtime.holdMutationCommand = true;
+ const installing = mutateAuthorized(store, {
+ action: 'install',
+ source: secondSource,
+ });
+ await vi.waitFor(() => {
+ expect(runtime.spawns.at(-1)?.args).toEqual(
+ expect.arrayContaining(['install', secondSource]),
+ );
+ });
+ await fs.writeFile(
+ path.join(dependencyRoot, 'index.js'),
+ 'module.exports = "changed-during-sibling-install";\n',
+ );
+ await writeExtension(secondRoot, 'new-shared-extension');
+ runtime.listOutput = [
+ 'User packages:',
+ ` ${firstSource}`,
+ ` ${firstRoot}`,
+ ` ${secondSource}`,
+ ` ${secondRoot}`,
+ '',
+ ].join('\n');
+ runtime.holdMutationCommand = false;
+ runtime.pendingClose?.(0);
+ const installed = await installing;
+
+ expect(installed.packages).toEqual(expect.arrayContaining([
+ expect.objectContaining({
+ source: firstSource,
+ enabled: false,
+ requiresExtensionApproval: true,
+ }),
+ expect.objectContaining({ source: secondSource, enabled: true }),
+ ]));
+ const state = JSON.parse(await fs.readFile(
+ path.join(runtime.userData, 'pi-package-home', 'cindy-package-state.json'),
+ 'utf8',
+ )) as {
+ approvedExtensionSources: string[];
+ approvedExtensionFingerprints: Record<string, string>;
+ };
+ expect(state.approvedExtensionSources).toEqual([secondSource]);
+ expect(Object.keys(state.approvedExtensionFingerprints)).toEqual([secondSource]);
+ });
+
it.skipIf(process.platform === 'win32')(
'stages a read-only package directory before restoring its source mode',
async () => {
@@ -1925,7 +2098,7 @@ describe('Pi package executable-code boundary', () => {
await vi.waitFor(() => expect(listener).toHaveBeenCalled(), { timeout: 2_000 });
await expect(firstStore.listPiPackages()).resolves.toMatchObject({
- packages: [{ source, enabled: false, requiresExtensionApproval: true }],
+ packages: [{ source, enabled: true }],
});
unsubscribe();
});
@@ -2023,15 +2196,14 @@ describe('Pi package executable-code boundary', () => {
await mutateAuthorized(secondStore, { action: 'update', source });
const snapshotRoot = path.join(runtime.userData, 'cross-process-session', 'managed-packages');
- await expect(firstStore.resolveManagedPiPackageResources({ snapshotRoot })).resolves.toEqual({
- extensions: [],
- skills: [],
- promptTemplates: [],
- packageRoots: [],
+ const snapshotExtension = path.join(snapshotRoot, '0', 'extensions', 'index.ts');
+ await expect(firstStore.resolveManagedPiPackageResources({ snapshotRoot })).resolves.toMatchObject({
+ extensions: [snapshotExtension],
+ packageRoots: [path.join(snapshotRoot, '0')],
});
- await expect(fs.readdir(snapshotRoot)).resolves.toEqual([]);
+ await expect(fs.readFile(snapshotExtension, 'utf8')).resolves.toContain('replacedAfterApproval');
await expect(firstStore.listPiPackages()).resolves.toMatchObject({
- packages: [{ source, enabled: false, requiresExtensionApproval: true }],
+ packages: [{ source, enabled: true }],
});
});
@@ -2118,9 +2290,9 @@ describe('Pi package executable-code boundary', () => {
expect(reinstalled.affectedPackage).toMatchObject({
source: normalizedSource,
- enabled: false,
- requiresExtensionApproval: true,
+ enabled: true,
});
+ expect(reinstalled.affectedPackage?.requiresExtensionApproval).toBeUndefined();
await mutateAuthorized(store, { action: 'update', source: normalizedSource });
await mutateAuthorized(store, { action: 'remove', source: normalizedSource });
diff --git a/apps/desktop/src/main/maker-host/pi-package-store.ts b/apps/desktop/src/main/maker-host/pi-package-store.ts
index 42561ec3a6..1438f6537a 100644
--- a/apps/desktop/src/main/maker-host/pi-package-store.ts
+++ b/apps/desktop/src/main/maker-host/pi-package-store.ts
@@ -206,6 +206,8 @@ interface PackageManifest {
name?: string;
version?: string;
pi?: Partial<Record<'extensions' | 'skills' | 'prompts' | 'themes', unknown>>;
+ dependencies?: Record<string, string>;
+ optionalDependencies?: Record<string, string>;
peerDependencies?: Record<string, string>;
scripts?: Record<string, unknown>;
}
@@ -251,6 +253,12 @@ interface PackageSourceProjection {
unsafe: boolean;
}
+interface FreshExtensionApprovalIdentity {
+ closureFingerprint: string;
+ installedRoot: string;
+ snapshotRoot: string;
+}
+
interface InspectionBudget {
startedAt: number;
entries: number;
@@ -2376,6 +2384,61 @@ async function revokeExtensionApproval(sources: Iterable<string>): Promise<void>
});
}
+/**
+ * One confirmed install/update is enough to run the affected package.
+ * Sibling npm packages share one copy-root, so their fingerprints change when
+ * another package is added. Rebase only identities that still matched before
+ * the mutation; stale or uninspectable approvals must remain fail closed.
+ */
+async function persistEnabledExtensionApprovals(options: {
+ inspected: InspectedPackage[];
+ rebaseSources: ReadonlySet<string>;
+ enable?: InspectedPackage;
+}): Promise<void> {
+ const state = await requireState();
+ const disabled = new Set(state.disabledSources);
+ const approved = new Set(state.approvedExtensionSources);
+ const fingerprints = { ...state.approvedExtensionFingerprints };
+ const inspectedBySource = new Map(
+ options.inspected.map((pkg) => [pkg.rawSource, pkg]),
+ );
+
+ for (const source of approved) {
+ const pkg = inspectedBySource.get(source);
+ if (!options.rebaseSources.has(source) || !pkg?.contentFingerprint) {
+ approved.delete(source);
+ delete fingerprints[source];
+ continue;
+ }
+ fingerprints[source] = pkg.contentFingerprint;
+ }
+
+ if (options.enable) {
+ const pkg = options.enable;
+ if (pkg.view.resources.some((resource) => resource.kind === 'extension')) {
+ if (pkg.contentFingerprint) {
+ approved.add(pkg.rawSource);
+ fingerprints[pkg.rawSource] = pkg.contentFingerprint;
+ disabled.delete(pkg.rawSource);
+ }
+ } else {
+ approved.delete(pkg.rawSource);
+ delete fingerprints[pkg.rawSource];
+ disabled.delete(pkg.rawSource);
+ }
+ }
+
+ await writeState({
+ version: STATE_VERSION,
+ disabledSources: [...disabled].sort(),
+ approvedExtensionSources: [...approved].sort(),
+ approvedExtensionFingerprints: Object.fromEntries(
+ Object.entries(fingerprints).sort(([left], [right]) => left.localeCompare(right)),
+ ),
+ snapshotUnavailableRoots: state.snapshotUnavailableRoots,
+ });
+}
+
function sourceAliases(source: string): string[] {
return source.includes(':') || source.includes('://') || isLocalPackageSource(source)
? [source]
@@ -2391,6 +2454,123 @@ function mutationCommandSource(
: requestedSource;
}
+async function resolveClosureDependency(
+ packageRoot: string,
+ name: string,
+ nodeModulesRoot: string,
+): Promise<string | undefined> {
+ if (!/^(?:@[^/\\\0]+\/)?[^/\\\0]+$/.test(name)
+ || name.split('/').some((part) => part === '.' || part === '..')) {
+ throw new Error('Invalid npm dependency name');
+ }
+ const candidates = new Set<string>();
+ let cursor = packageRoot;
+ for (;;) {
+ candidates.add(path.basename(cursor) === 'node_modules'
+ ? path.join(cursor, name)
+ : path.join(cursor, 'node_modules', name));
+ if (cursor === nodeModulesRoot) break;
+ const parent = path.dirname(cursor);
+ if (parent === cursor || !isWithinConfinement(nodeModulesRoot, parent)) break;
+ cursor = parent;
+ }
+ for (const candidate of candidates) {
+ try {
+ const { canonicalPath, stat } = await resolveStablePackagePath(candidate,
+ 'Pi extension dependency changed while proving approval identity');
+ if (!stat.isDirectory() || !isWithinConfinement(nodeModulesRoot, canonicalPath)) {
+ throw new Error('Pi extension dependency escaped the shared npm root');
+ }
+ return canonicalPath;
+ } catch (error) {
+ if ((error as NodeJS.ErrnoException).code !== 'ENOENT') throw error;
+ }
+ }
+ return undefined;
+}
+
+async function fingerprintExtensionClosure(
+ installedRoot: string,
+ snapshotRoot: string,
+): Promise<string> {
+ const nodeModulesRoot = await fs.realpath(path.join(snapshotRoot, 'node_modules'));
+ if (!isWithinConfinement(nodeModulesRoot, installedRoot)) {
+ throw new Error('Pi extension escaped the shared npm root');
+ }
+ const pending = [installedRoot];
+ const roots = new Set<string>();
+ let metadataBytes = 0;
+ while (pending.length > 0) {
+ if (roots.size >= MAX_INSPECTION_ENTRIES) throw new PiPackageInspectionLimitError();
+ const root = await fs.realpath(pending.shift()!);
+ if (roots.has(root)) continue;
+ roots.add(root);
+ const manifestResult = await readUtf8FileBounded(
+ path.join(root, 'package.json'), MAX_PACKAGE_JSON_BYTES, root);
+ metadataBytes += manifestResult.bytes;
+ if (metadataBytes > MAX_INSPECTION_METADATA_BYTES) throw new PiPackageInspectionLimitError();
+ const manifest = JSON.parse(manifestResult.text) as PackageManifest;
+ const dependencyNames = new Set(Object.keys({ ...manifest.peerDependencies,
+ ...manifest.optionalDependencies, ...manifest.dependencies }));
+ for (const name of [...dependencyNames].sort()) {
+ const dependency = await resolveClosureDependency(root, name, nodeModulesRoot);
+ if (dependency && !roots.has(dependency)) pending.push(dependency);
+ }
+ }
+
+ const selectedRoots: string[] = [];
+ for (const root of [...roots].sort((left, right) => left.length - right.length)) {
+ if (!selectedRoots.some((ancestor) => isWithinConfinement(ancestor, root))) selectedRoots.push(root);
+ }
+ const aggregate = createSnapshotBudgetCounters(DEFAULT_SNAPSHOT_LIMITS);
+ const hash = createHash('sha256');
+ updatePackageFingerprintField(hash, 'cindy-pi-extension-closure-v1');
+ for (const root of selectedRoots.sort()) {
+ updatePackageFingerprintField(hash, path.relative(snapshotRoot, root));
+ updatePackageFingerprintField(hash, await fingerprintPiPackageTree(
+ root, DEFAULT_SNAPSHOT_LIMITS, aggregate));
+ }
+ return hash.digest('hex');
+}
+
+async function captureExtensionApprovalIdentities(
+ packages: InspectedPackage[],
+): Promise<Map<string, FreshExtensionApprovalIdentity>> {
+ const identities = new Map<string, FreshExtensionApprovalIdentity>();
+ for (const pkg of packages) {
+ if (!pkg.contentFingerprint || !pkg.installedRoot) continue;
+ try {
+ const snapshotRoot = await snapshotRootForInstalledPackage(pkg.rawSource, pkg.installedRoot);
+ const closureFingerprint = snapshotRoot === pkg.installedRoot
+ ? pkg.contentFingerprint
+ : await fingerprintExtensionClosure(pkg.installedRoot, snapshotRoot);
+ if (await fingerprintPiPackageTree(snapshotRoot) !== pkg.contentFingerprint) continue;
+ identities.set(pkg.rawSource, {
+ closureFingerprint,
+ installedRoot: pkg.installedRoot,
+ snapshotRoot,
+ });
+ } catch {
+ // Unprovable closures are not eligible for rebasing.
+ }
+ }
+ return identities;
+}
+
+async function unchangedExtensionClosureSources(
+ before: ReadonlyMap<string, FreshExtensionApprovalIdentity>,
+ inspectedAfter: InspectedPackage[],
+): Promise<Set<string>> {
+ const after = await captureExtensionApprovalIdentities(
+ inspectedAfter.filter((pkg) => before.has(pkg.rawSource)));
+ return new Set([...before].filter(([source, identity]) => {
+ const current = after.get(source);
+ return current?.installedRoot === identity.installedRoot
+ && current.snapshotRoot === identity.snapshotRoot
+ && current.closureFingerprint === identity.closureFingerprint;
+ }).map(([source]) => source));
+}
+
export async function mutatePiPackage(
request: PiPackageMutationRequest,
grant?: PiPackageMutationGrant,
@@ -2418,12 +2598,19 @@ export async function mutatePiPackage(
// process populated its cache; no mutation may persist decisions derived
// from that lock-external snapshot.
const inspectedBeforeMutation = await inspectAllPackagesFreshUnderMutationLock();
+ const preMutationFreshApprovals = await captureExtensionApprovalIdentities(
+ inspectedBeforeMutation.filter((pkg) => (
+ pkg.view.requiresExtensionApproval !== true
+ && pkg.view.resources.some((resource) => resource.kind === 'extension')
+ )),
+ );
let affectedSource: string | undefined;
if (request.action === 'install') {
mutationMayHaveChangedState = true;
// Reinstalling an existing source can replace executable code. Revoke
// before invoking Pi so even a partially failed install cannot inherit a
- // stale approval on the next runtime.
+ // stale approval on the next runtime. A successful install is itself the
+ // user decision to enable the new bytes.
const previous = await findAffectedInspectedPackage(inspectedBeforeMutation, source);
await revokeExtensionApproval([
...sourceAliases(source),
@@ -2432,12 +2619,17 @@ export async function mutatePiPackage(
invalidateInspectionCache();
await runPiPackageCommand(['install', source, '--no-approve']);
invalidateInspectionCache();
- const affected = await findAffectedInspectedPackage(await inspectAllPackages(), source);
+ const inspectedAfterInstall = await inspectAllPackages();
+ const affected = await findAffectedInspectedPackage(inspectedAfterInstall, source);
affectedSource = affected?.rawSource;
- await revokeExtensionApproval([
- ...sourceAliases(source),
- ...(affectedSource ? sourceAliases(affectedSource) : []),
- ]);
+ await persistEnabledExtensionApprovals({
+ inspected: inspectedAfterInstall,
+ rebaseSources: await unchangedExtensionClosureSources(
+ preMutationFreshApprovals,
+ inspectedAfterInstall,
+ ),
+ ...(affected ? { enable: affected } : {}),
+ });
} else if (request.action === 'remove') {
mutationMayHaveChangedState = true;
const previous = await findAffectedInspectedPackage(inspectedBeforeMutation, source);
@@ -2464,10 +2656,15 @@ export async function mutatePiPackage(
} else if (request.action === 'update') {
mutationMayHaveChangedState = true;
const previous = await findAffectedInspectedPackage(inspectedBeforeMutation, source);
- await revokeExtensionApproval([
+ const updateAliases = [
...sourceAliases(source),
...(previous ? sourceAliases(previous.rawSource) : []),
- ]);
+ ];
+ const stateBeforeUpdate = await requireState();
+ const wasExplicitlyDisabled = updateAliases.some((item) => (
+ stateBeforeUpdate.disabledSources.includes(item)
+ ));
+ await revokeExtensionApproval(updateAliases);
invalidateInspectionCache();
await runPiPackageCommand([
'update',
@@ -2475,14 +2672,19 @@ export async function mutatePiPackage(
'--no-approve',
]);
invalidateInspectionCache();
- const affected = await findAffectedInspectedPackage(await inspectAllPackages(), source);
+ const inspectedAfterUpdate = await inspectAllPackages();
+ const affected = await findAffectedInspectedPackage(inspectedAfterUpdate, source);
affectedSource = affected?.rawSource ?? previous?.rawSource ?? source;
- // An update changes executable code. Require a fresh, post-inspection
- // approval before any extension from that source can run again.
- await revokeExtensionApproval([
- ...sourceAliases(source),
- ...sourceAliases(affectedSource),
- ]);
+ // A confirmed update is enough to keep running the new bytes, unless the
+ // user had already turned this package off.
+ await persistEnabledExtensionApprovals({
+ inspected: inspectedAfterUpdate,
+ rebaseSources: await unchangedExtensionClosureSources(
+ preMutationFreshApprovals,
+ inspectedAfterUpdate,
+ ),
+ ...(!wasExplicitlyDisabled && affected ? { enable: affected } : {}),
+ });
} else if (request.action === 'set-enabled') {
if (typeof request.enabled !== 'boolean') throw new Error('enabled must be a boolean');
const target = await findAffectedInspectedPackage(inspectedBeforeMutation, source);
diff --git a/apps/desktop/src/renderer/components/settings/PiPackagesSection.tsx b/apps/desktop/src/renderer/components/settings/PiPackagesSection.tsx
index ff28f5972f..c0fafc2741 100644
--- a/apps/desktop/src/renderer/components/settings/PiPackagesSection.tsx
+++ b/apps/desktop/src/renderer/components/settings/PiPackagesSection.tsx
@@ -209,7 +209,11 @@ export function PiPackagesSection() {
}
// Toasts are app-level feedback: even if the user leaves this panel while
// the host mutation is running, they still need the final outcome.
- toast.success(t(`settings.piPackages.success.${action}`));
+ const successKey =
+ action === 'install' && result.affectedPackage?.enabled
+ ? 'settings.piPackages.success.installEnabled'
+ : `settings.piPackages.success.${action}`;
+ toast.success(t(successKey));
return true;
} catch (error) {
if (extractIpcError(error)?.code === 'MUTATION_CANCELLED') return false;
diff --git a/apps/desktop/src/renderer/components/settings/__tests__/PiPackagesSection.interactions.test.tsx b/apps/desktop/src/renderer/components/settings/__tests__/PiPackagesSection.interactions.test.tsx
index 9dcd2edc93..c09094f769 100644
--- a/apps/desktop/src/renderer/components/settings/__tests__/PiPackagesSection.interactions.test.tsx
+++ b/apps/desktop/src/renderer/components/settings/__tests__/PiPackagesSection.interactions.test.tsx
@@ -148,10 +148,15 @@ describe('PiPackagesSection interaction state machine', () => {
it('routes install directly into the Main-owned confirmation flow and keeps retry state on failure', async () => {
const firstMutation = deferred<{ available: boolean; packages: PiPackageView[] }>();
+ const enabledPackage = { ...packageView(1), enabled: true };
const mutatePiPackage = vi
.fn()
.mockImplementationOnce(() => firstMutation.promise)
- .mockResolvedValueOnce({ available: true, packages: [packageView(1)] });
+ .mockResolvedValueOnce({
+ available: true,
+ packages: [enabledPackage],
+ affectedPackage: enabledPackage,
+ });
installElectronApi({
listPiPackages: vi.fn(async () => ({ available: true, packages: [] })),
mutatePiPackage,
@@ -189,6 +194,41 @@ describe('PiPackagesSection interaction state machine', () => {
fireEvent.click(screen.getByRole('button', { name: 'settings.piPackages.install' }));
await waitFor(() => expect(screen.getByText('sample-extension-1')).toBeTruthy());
expect(mutatePiPackage).toHaveBeenCalledTimes(2);
+ expect(toastMocks.success).toHaveBeenCalledWith(
+ 'settings.piPackages.success.installEnabled',
+ );
+ });
+
+ it('does not claim enablement when an installed package remains disabled', async () => {
+ const disabledPackage: PiPackageView = {
+ ...packageView(1),
+ enabled: false,
+ canToggle: false,
+ resources: [],
+ warning: 'inspection-failed',
+ };
+ installElectronApi({
+ listPiPackages: vi.fn(async () => ({ available: true, packages: [] })),
+ mutatePiPackage: vi.fn(async () => ({
+ available: true,
+ packages: [disabledPackage],
+ affectedPackage: disabledPackage,
+ })),
+ });
+ render(<PiPackagesSection />);
+ await screen.findByText('settings.piPackages.empty');
+
+ fireEvent.change(screen.getByPlaceholderText('settings.piPackages.sourcePlaceholder'), {
+ target: { value: disabledPackage.source },
+ });
+ fireEvent.click(screen.getByRole('button', { name: 'settings.piPackages.install' }));
+
+ await waitFor(() =>
+ expect(toastMocks.success).toHaveBeenCalledWith('settings.piPackages.success.install'),
+ );
+ expect(toastMocks.success).not.toHaveBeenCalledWith(
+ 'settings.piPackages.success.installEnabled',
+ );
});
it('routes remove directly into the Main-owned confirmation flow and retries after failure', async () => {
diff --git a/apps/desktop/src/renderer/i18n/locales/en/common.json b/apps/desktop/src/renderer/i18n/locales/en/common.json
index e13a1da75c..f1cb168464 100644
--- a/apps/desktop/src/renderer/i18n/locales/en/common.json
+++ b/apps/desktop/src/renderer/i18n/locales/en/common.json
@@ -2715,7 +2715,7 @@
"installSectionDescription": "Paste the install source from a pi.dev page, or enter an npm package name, Git URL, or absolute local path.",
"installedSectionTitle": "Installed",
"sourcePlaceholder": "npm package, Git URL, or absolute local path",
- "inspectionHint": "After installation, Cindy checks resources and compatibility. Executable extension code stays disabled until you trust the source and enable it.",
+ "inspectionHint": "Cindy warns you once about the risk. After you confirm, Cindy installs it, checks its resources, and automatically enables runnable resources when inspection succeeds.",
"install": "Install",
"update": "Update",
"remove": "Uninstall",
@@ -2737,12 +2737,12 @@
"retry": "Retry",
"operationInProgress": "Working on {{name}}…",
"relativePathUnsupported": "Use an absolute path for local extensions in Settings. Relative paths such as ./extension can be installed from a Pi task.",
- "confirmTitle": "Install a third-party Pi extension?",
- "confirmDescription": "{{source}} may contain third-party code. Install and update do not run npm lifecycle scripts. If executable extension code is found, it stays disabled until you review the inspection and explicitly enable it.",
- "confirmInstall": "Accept risk and install",
- "updateConfirmTitle": "Update a third-party Pi extension?",
- "updateConfirmDescription": "{{source}} may replace installed code with a new third-party version. Update does not run npm lifecycle scripts, and executable extension code must be approved again before it can run.",
- "confirmUpdate": "Accept risk and update",
+ "confirmTitle": "Install This Pi Extension?",
+ "confirmDescription": "{{source}} is third-party code. It will run in the same process as Cindy's Pi and may read files and credentials Pi can access. Install does not run npm lifecycle scripts. Confirming installs it. Cindy automatically enables runnable resources after a successful inspection, even when it reports compatibility limits.",
+ "confirmInstall": "Accept Risk, Install",
+ "updateConfirmTitle": "Update This Pi Extension?",
+ "updateConfirmDescription": "{{source}} will download a new third-party version and replace the installed code. Update does not run npm lifecycle scripts. The code runs in the same process as Pi and may read files and credentials. Confirming updates it. If you turned it off, it stays off; otherwise, Cindy enables it after a successful inspection.",
+ "confirmUpdate": "Accept Risk, Update",
"uninstallTitle": "Uninstall Pi extension?",
"uninstallDescription": "{{name}} will be removed from this device. Pi tasks that are already open keep the old extension until they are closed.",
"confirmUninstall": "Uninstall",
@@ -2805,7 +2805,8 @@
"lifecycle-scripts-disabled": "This extension declares install scripts, but Cindy did not run them for safety. Features that depend on generated files may not work."
},
"success": {
- "install": "Pi extension installed. The current task is unchanged; start or restart a Pi task to use it.",
+ "install": "Pi extension installed. Check its enabled state below; the current task is unchanged.",
+ "installEnabled": "Pi extension installed and enabled. The current task is unchanged; start or restart a Pi task to use it.",
"remove": "Pi extension removed. The current task keeps the old extension until it is closed.",
"update": "Pi extension updated. The current task keeps the old version; start or restart a Pi task to use the update.",
"set-enabled": "Pi extension state saved. The current task is unchanged; start or restart a Pi task to apply it."
diff --git a/apps/desktop/src/renderer/i18n/locales/ja/common.json b/apps/desktop/src/renderer/i18n/locales/ja/common.json
index b3f1e52402..a9e203a67e 100644
--- a/apps/desktop/src/renderer/i18n/locales/ja/common.json
+++ b/apps/desktop/src/renderer/i18n/locales/ja/common.json
@@ -2714,7 +2714,7 @@
"installSectionDescription": "pi.dev ページのインストール元を貼り付けるか、npm パッケージ名、Git URL、ローカルの絶対パスを入力します。",
"installedSectionTitle": "インストール済み",
"sourcePlaceholder": "npm パッケージ、Git URL、ローカルの絶対パス",
- "inspectionHint": "インストール後に Cindy がリソースと互換性を確認します。実行可能な拡張コードは、信頼できる配布元だと確認して有効にするまで無効のままです。",
+ "inspectionHint": "インストール時にリスクを一度だけ確認します。承認後、Cindy が拡張機能をインストールしてリソースを検査し、検査に成功した実行可能リソースを自動的に有効にします。",
"install": "インストール",
"update": "更新",
"remove": "アンインストール",
@@ -2735,11 +2735,11 @@
"loadFailed": "Pi 拡張機能を読み込めませんでした。接続を確認して再試行してください。",
"retry": "再試行",
"operationInProgress": "{{name}} を処理しています…",
- "confirmTitle": "サードパーティの Pi 拡張機能をインストールしますか?",
- "confirmDescription": "{{source}} には第三者コードが含まれる場合があります。インストールと更新では npm ライフサイクルスクリプトを実行しません。実行可能な拡張コードが見つかった場合は、検査結果を確認して明示的に有効にするまで無効のままです。",
+ "confirmTitle": "この Pi 拡張機能をインストールしますか?",
+ "confirmDescription": "{{source}} は第三者コードです。Cindy の Pi と同じプロセスで実行され、Pi がアクセスできるファイルや認証情報を読み取る可能性があります。インストール時に npm ライフサイクルスクリプトは実行しません。承認するとインストールされます。検査に成功した実行可能リソースは、互換性の制限が報告された場合でも自動的に有効になります。",
"confirmInstall": "リスクを理解してインストール",
- "updateConfirmTitle": "サードパーティ製 Pi 拡張機能を更新しますか?",
- "updateConfirmDescription": "{{source}} は新しいサードパーティ版をダウンロードし、インストール済みコードを置き換えます。更新時に npm ライフサイクルスクリプトは実行されず、実行可能な拡張コードは再承認するまで動作しません。",
+ "updateConfirmTitle": "この Pi 拡張機能を更新しますか?",
+ "updateConfirmDescription": "{{source}} は新しいサードパーティ版をダウンロードし、インストール済みコードを置き換えます。更新時に npm ライフサイクルスクリプトは実行しません。コードは Pi と同じプロセスで実行され、ファイルや認証情報を読み取る可能性があります。承認すると更新されます。自分で無効にした拡張機能は無効のままになり、それ以外は検査に成功すると有効になります。",
"confirmUpdate": "リスクを理解して更新",
"uninstallTitle": "Pi 拡張機能をアンインストールしますか?",
"uninstallDescription": "{{name}} をこのデバイスから削除します。すでに開いている Pi タスクは、閉じるまで古い拡張機能を保持します。",
@@ -2804,7 +2804,8 @@
"lifecycle-scripts-disabled": "この拡張機能にはインストールスクリプトがありますが、安全のため Cindy は実行していません。生成ファイルに依存する機能は動作しない可能性があります。"
},
"success": {
- "install": "Pi 拡張機能をインストールしました。現在のタスクは変わりません。Pi タスクを新規作成または再起動すると有効になります。",
+ "install": "Pi 拡張機能をインストールしました。下の有効状態を確認してください。現在のタスクは変わりません。",
+ "installEnabled": "Pi 拡張機能をインストールして有効にしました。現在のタスクは変わりません。Pi タスクを新規作成または再起動すると使えます。",
"remove": "Pi 拡張機能を削除しました。現在のタスクは閉じるまで古い拡張機能を保持します。",
"update": "Pi 拡張機能を更新しました。現在のタスクは古いバージョンを保持します。新規作成または再起動後に反映されます。",
"set-enabled": "Pi 拡張機能の状態を保存しました。現在のタスクは変わりません。新規作成または再起動後に反映されます。"
diff --git a/apps/desktop/src/renderer/i18n/locales/ko/common.json b/apps/desktop/src/renderer/i18n/locales/ko/common.json
index b73c97cf24..8df1971aa1 100644
--- a/apps/desktop/src/renderer/i18n/locales/ko/common.json
+++ b/apps/desktop/src/renderer/i18n/locales/ko/common.json
@@ -2714,7 +2714,7 @@
"installSectionDescription": "pi.dev 페이지의 설치 소스를 붙여넣거나 npm 패키지명, Git URL, 로컬 절대 경로를 입력하세요.",
"installedSectionTitle": "설치됨",
"sourcePlaceholder": "npm 패키지, Git URL 또는 로컬 절대 경로",
- "inspectionHint": "설치 후 Cindy가 리소스와 호환성을 확인합니다. 실행 가능한 확장 코드는 신뢰할 수 있는 소스인지 확인하고 활성화할 때까지 비활성 상태로 유지됩니다.",
+ "inspectionHint": "설치 시 위험을 한 번만 안내합니다. 확인하면 확장을 설치하고 리소스를 검사하며, 검사가 성공한 실행 가능 리소스를 자동으로 활성화합니다.",
"install": "설치",
"update": "업데이트",
"remove": "제거",
@@ -2735,11 +2735,11 @@
"loadFailed": "Pi 확장을 불러오지 못했습니다. 연결을 확인한 뒤 다시 시도하세요.",
"retry": "다시 시도",
"operationInProgress": "{{name}} 처리 중…",
- "confirmTitle": "타사 Pi 확장을 설치할까요?",
- "confirmDescription": "{{source}}에는 타사 코드가 포함될 수 있습니다. 설치와 업데이트는 npm 수명 주기 스크립트를 실행하지 않습니다. 실행 가능한 확장 코드가 발견되면 검사 결과를 확인하고 명시적으로 활성화할 때까지 비활성 상태로 유지됩니다.",
+ "confirmTitle": "이 Pi 확장을 설치할까요?",
+ "confirmDescription": "{{source}}는 타사 코드입니다. Cindy의 Pi와 같은 프로세스에서 실행되며 Pi가 접근할 수 있는 파일과 자격 증명을 읽을 수 있습니다. 설치 시 npm 수명 주기 스크립트는 실행되지 않습니다. 확인하면 설치됩니다. 검사가 성공한 실행 가능 리소스는 호환성 제한이 함께 표시되어도 자동으로 활성화됩니다.",
"confirmInstall": "위험을 이해하고 설치",
- "updateConfirmTitle": "서드파티 Pi 확장 프로그램을 업데이트할까요?",
- "updateConfirmDescription": "{{source}}의 새 서드파티 버전을 내려받아 설치된 코드를 교체합니다. 업데이트는 npm 수명 주기 스크립트를 실행하지 않으며, 실행 가능한 확장 코드는 다시 승인하기 전까지 실행되지 않습니다.",
+ "updateConfirmTitle": "이 Pi 확장을 업데이트할까요?",
+ "updateConfirmDescription": "{{source}}의 새 타사 버전을 내려받아 설치된 코드를 교체합니다. 업데이트는 npm 수명 주기 스크립트를 실행하지 않습니다. 코드는 Pi와 같은 프로세스에서 실행되며 파일과 자격 증명을 읽을 수 있습니다. 확인하면 업데이트됩니다. 직접 비활성화한 확장은 비활성화 상태로 유지되며, 그 외 확장은 검사가 성공하면 활성화됩니다.",
"confirmUpdate": "위험을 이해하고 업데이트",
"uninstallTitle": "Pi 확장을 제거할까요?",
"uninstallDescription": "{{name}}을(를) 이 기기에서 제거합니다. 이미 열려 있는 Pi 작업은 닫을 때까지 이전 확장을 유지합니다.",
@@ -2804,7 +2804,8 @@
"lifecycle-scripts-disabled": "이 확장은 설치 스크립트를 선언하지만 Cindy는 안전을 위해 실행하지 않았습니다. 생성 파일에 의존하는 기능은 작동하지 않을 수 있습니다."
},
"success": {
- "install": "Pi 확장을 설치했습니다. 현재 작업은 바뀌지 않으며 새로 만들거나 다시 시작한 Pi 작업부터 적용됩니다.",
+ "install": "Pi 확장을 설치했습니다. 아래에서 활성화 상태를 확인하세요. 현재 작업은 바뀌지 않습니다.",
+ "installEnabled": "Pi 확장을 설치하고 활성화했습니다. 현재 작업은 바뀌지 않으며 새로 만들거나 다시 시작한 Pi 작업부터 적용됩니다.",
"remove": "Pi 확장을 제거했습니다. 현재 작업은 닫을 때까지 이전 확장을 유지합니다.",
"update": "Pi 확장을 업데이트했습니다. 현재 작업은 이전 버전을 유지하며 새로 만들거나 다시 시작한 뒤 적용됩니다.",
"set-enabled": "Pi 확장 상태를 저장했습니다. 현재 작업은 바뀌지 않으며 새로 만들거나 다시 시작한 뒤 적용됩니다."
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 ec9bd40af5..49d9adf01c 100644
--- a/apps/desktop/src/renderer/i18n/locales/zh-CN/common.json
+++ b/apps/desktop/src/renderer/i18n/locales/zh-CN/common.json
@@ -2714,7 +2714,7 @@
"installSectionDescription": "粘贴 pi.dev 页面上的安装来源,或输入 npm 包名、Git 地址、本地绝对路径。",
"installedSectionTitle": "已安装",
"sourcePlaceholder": "npm 包名、Git 地址或本地绝对路径",
- "inspectionHint": "安装后 Cindy 会检查资源和兼容性。可执行扩展代码默认保持停用,确认来源可信后再启用。",
+ "inspectionHint": "安装时只提示一次风险。确认后会安装扩展并检查资源;检查成功时,可运行资源会自动启用。",
"install": "安装",
"update": "更新",
"remove": "卸载",
@@ -2736,11 +2736,11 @@
"retry": "重试",
"operationInProgress": "正在处理 {{name}}…",
"relativePathUnsupported": "在设置中安装本地扩展时请使用绝对路径;./extension 这类相对路径可在 Pi 任务中安装。",
- "confirmTitle": "安装第三方 Pi 扩展?",
- "confirmDescription": "{{source}} 可能包含第三方代码。安装和更新不会执行 npm 生命周期脚本;检测到可执行扩展代码时会先保持停用,等你看完检查结果后再决定是否启用。",
+ "confirmTitle": "安装这个 Pi 扩展?",
+ "confirmDescription": "{{source}} 是第三方代码,会与 Cindy 的 Pi 在同一进程中运行,可能读取 Pi 能访问的文件和凭证。安装不会执行 npm 生命周期脚本。确认后将安装扩展。检查成功后,可运行资源会自动启用,即使 Cindy 同时提示兼容性限制。",
"confirmInstall": "了解风险并安装",
- "updateConfirmTitle": "更新第三方 Pi 扩展?",
- "updateConfirmDescription": "{{source}} 会下载第三方新版本并替换已安装代码。更新不会执行 npm 生命周期脚本;可执行扩展代码必须重新确认后才能运行。",
+ "updateConfirmTitle": "更新这个 Pi 扩展?",
+ "updateConfirmDescription": "{{source}} 会下载第三方新版本并替换已安装代码。更新不会执行 npm 生命周期脚本。扩展代码与 Pi 在同一进程中运行,可能读取文件和凭证。确认后将更新扩展。你主动关闭的扩展会保持关闭;其他扩展会在检查成功后启用。",
"confirmUpdate": "了解风险并更新",
"uninstallTitle": "卸载 Pi 扩展?",
"uninstallDescription": "将从这台设备移除 {{name}}。当前已打开的 Pi 任务仍会保留旧扩展,关闭后才会彻底卸载。",
@@ -2804,7 +2804,8 @@
"lifecycle-scripts-disabled": "这个扩展声明了安装脚本,但 Cindy 为安全起见没有执行。依赖安装脚本生成文件的功能可能不可用。"
},
"success": {
- "install": "Pi 扩展已安装。当前任务不会变化;新建或重启 Pi 任务后生效。",
+ "install": "Pi 扩展已安装,请在下方查看启用状态。当前任务不会变化。",
+ "installEnabled": "Pi 扩展已安装并启用。当前任务不会变化;新建或重启 Pi 任务后生效。",
"remove": "Pi 扩展已移除。当前任务仍保留旧扩展,关闭后才会彻底卸载。",
"update": "Pi 扩展已更新。当前任务仍使用旧版本;新建或重启后生效。",
"set-enabled": "Pi 扩展启用状态已保存。当前任务不会变化;新建或重启后生效。"
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 9d53f09fb9..bd303ba912 100644
--- a/apps/desktop/src/renderer/i18n/locales/zh-TW/common.json
+++ b/apps/desktop/src/renderer/i18n/locales/zh-TW/common.json
@@ -2714,7 +2714,7 @@
"installSectionDescription": "貼上 pi.dev 頁面提供的安裝來源,或輸入 npm 套件名稱、Git 位址、本機絕對路徑。",
"installedSectionTitle": "已安裝",
"sourcePlaceholder": "npm 套件名稱、Git 位址或本機絕對路徑",
- "inspectionHint": "安裝後 Cindy 會檢查資源與相容性。可執行的擴充程式碼預設保持停用,確認來源可信後再啟用。",
+ "inspectionHint": "安裝時只提示一次風險。確認後會安裝擴充功能並檢查資源;檢查成功時,可執行資源會自動啟用。",
"install": "安裝",
"update": "更新",
"remove": "解除安裝",
@@ -2735,11 +2735,11 @@
"loadFailed": "暫時無法讀取 Pi 擴充功能,請檢查連線後重試。",
"retry": "重試",
"operationInProgress": "正在處理 {{name}}…",
- "confirmTitle": "安裝第三方 Pi 擴充功能?",
- "confirmDescription": "{{source}} 可能包含第三方程式碼。安裝與更新不會執行 npm 生命週期腳本;若發現可執行的擴充程式碼,會先保持停用,等你看完檢查結果後再明確啟用。",
+ "confirmTitle": "安裝這個 Pi 擴充功能?",
+ "confirmDescription": "{{source}} 是第三方程式碼,會與 Cindy 的 Pi 在同一行程中執行,可能讀取 Pi 能存取的檔案和憑證。安裝不會執行 npm 生命週期指令碼。確認後將安裝擴充功能。檢查成功後,可執行資源會自動啟用,即使 Cindy 同時提示相容性限制。",
"confirmInstall": "了解風險並安裝",
- "updateConfirmTitle": "更新第三方 Pi 擴充功能?",
- "updateConfirmDescription": "{{source}} 會下載第三方新版本並取代已安裝程式碼。更新不會執行 npm 生命週期指令碼;可執行擴充功能程式碼必須重新確認後才能執行。",
+ "updateConfirmTitle": "更新這個 Pi 擴充功能?",
+ "updateConfirmDescription": "{{source}} 會下載第三方新版本並取代已安裝程式碼。更新不會執行 npm 生命週期指令碼。擴充程式碼與 Pi 在同一行程中執行,可能讀取檔案和憑證。確認後將更新擴充功能。你主動關閉的擴充功能會保持關閉;其他擴充功能會在檢查成功後啟用。",
"confirmUpdate": "了解風險並更新",
"uninstallTitle": "解除安裝 Pi 擴充功能?",
"uninstallDescription": "將從這台裝置移除 {{name}}。目前已開啟的 Pi 任務仍會保留舊擴充功能,關閉後才會徹底卸載。",
@@ -2804,7 +2804,8 @@
"lifecycle-scripts-disabled": "這個擴充功能宣告了安裝指令碼,但 Cindy 為了安全並未執行。依賴安裝指令碼產生檔案的功能可能無法使用。"
},
"success": {
- "install": "Pi 擴充功能已安裝。目前任務不會改變;新建或重新啟動 Pi 任務後生效。",
+ "install": "Pi 擴充功能已安裝,請在下方查看啟用狀態。目前任務不會改變。",
+ "installEnabled": "Pi 擴充功能已安裝並啟用。目前任務不會改變;新建或重新啟動 Pi 任務後生效。",
"remove": "Pi 擴充功能已移除。目前任務仍保留舊擴充功能,關閉後才會徹底卸載。",
"update": "Pi 擴充功能已更新。目前任務仍使用舊版本;新建或重新啟動後生效。",
"set-enabled": "Pi 擴充功能啟用狀態已儲存。目前任務不會改變;新建或重新啟動後生效。"