[Extension Reloading]: Update custom commands, add enable/disable command (#12547)

This commit is contained in:
Jacob MacDonald
2025-11-05 11:36:07 -08:00
committed by GitHub
parent ca6cfaaf4e
commit fa93b56243
24 changed files with 664 additions and 187 deletions

View File

@@ -7,10 +7,16 @@
import type { GeminiCLIExtension } from '@google/gemini-cli-core';
import { createMockCommandContext } from '../../test-utils/mockCommandContext.js';
import { MessageType } from '../types.js';
import { extensionsCommand } from './extensionsCommand.js';
import { type CommandContext } from './types.js';
import {
completeExtensions,
completeExtensionsAndScopes,
extensionsCommand,
} from './extensionsCommand.js';
import { type CommandContext, type SlashCommand } from './types.js';
import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest';
import { type ExtensionUpdateAction } from '../state/extensions.js';
import { ExtensionManager } from '../../config/extension-manager.js';
import { SettingScope } from '../../config/settings.js';
import open from 'open';
vi.mock('open', () => ({
@@ -22,20 +28,72 @@ vi.mock('../../config/extensions/update.js', () => ({
checkForAllExtensionUpdates: vi.fn(),
}));
const mockDisableExtension = vi.fn();
const mockEnableExtension = vi.fn();
const mockGetExtensions = vi.fn();
const inactiveExt: GeminiCLIExtension = {
name: 'ext-one',
id: 'ext-one-id',
version: '1.0.0',
isActive: false, // should suggest disabled extensions
path: '/test/dir/ext-one',
contextFiles: [],
installMetadata: {
type: 'git',
autoUpdate: false,
source: 'https://github.com/some/extension.git',
},
};
const activeExt: GeminiCLIExtension = {
name: 'ext-two',
id: 'ext-two-id',
version: '1.0.0',
isActive: true, // should not suggest enabled extensions
path: '/test/dir/ext-two',
contextFiles: [],
installMetadata: {
type: 'git',
autoUpdate: false,
source: 'https://github.com/some/extension.git',
},
};
const allExt: GeminiCLIExtension = {
name: 'all-ext',
id: 'all-ext-id',
version: '1.0.0',
isActive: true,
path: '/test/dir/all-ext',
contextFiles: [],
installMetadata: {
type: 'git',
autoUpdate: false,
source: 'https://github.com/some/extension.git',
},
};
describe('extensionsCommand', () => {
let mockContext: CommandContext;
const mockDispatchExtensionState = vi.fn();
beforeEach(() => {
vi.resetAllMocks();
mockGetExtensions.mockReturnValue([]);
mockGetExtensions.mockReturnValue([inactiveExt, activeExt, allExt]);
vi.mocked(open).mockClear();
mockContext = createMockCommandContext({
services: {
config: {
getExtensions: mockGetExtensions,
getExtensionLoader: vi.fn().mockImplementation(() => {
const actual = Object.create(ExtensionManager.prototype);
Object.assign(actual, {
enableExtension: mockEnableExtension,
disableExtension: mockDisableExtension,
getExtensions: mockGetExtensions,
});
return actual;
}),
getWorkingDir: () => '/test/dir',
},
},
@@ -52,8 +110,9 @@ describe('extensionsCommand', () => {
describe('list', () => {
it('should add an EXTENSIONS_LIST item to the UI', async () => {
if (!extensionsCommand.action) throw new Error('Action not defined');
await extensionsCommand.action(mockContext, '');
const command = extensionsCommand();
if (!command.action) throw new Error('Action not defined');
await command.action(mockContext, '');
expect(mockContext.ui.addItem).toHaveBeenCalledWith(
{
@@ -65,8 +124,68 @@ describe('extensionsCommand', () => {
});
});
describe('completeExtensions', () => {
it.each([
{
description: 'should return matching extension names',
partialArg: 'ext',
expected: ['ext-one', 'ext-two'],
},
{
description: 'should return --all when partialArg matches',
partialArg: '--al',
expected: ['--all'],
},
{
description:
'should return both extension names and --all when both match',
partialArg: 'all',
expected: ['--all', 'all-ext'],
},
{
description: 'should return an empty array if no matches',
partialArg: 'nomatch',
expected: [],
},
{
description:
'should suggest only disabled extension names for the enable command',
partialArg: 'ext',
expected: ['ext-one'],
command: 'enable',
},
{
description:
'should suggest only enabled extension names for the disable command',
partialArg: 'ext',
expected: ['ext-two'],
command: 'disable',
},
])('$description', async ({ partialArg, expected, command }) => {
if (command) {
mockContext.invocation!.name = command;
}
const suggestions = completeExtensions(mockContext, partialArg);
expect(suggestions).toEqual(expected);
});
});
describe('completeExtensionsAndScopes', () => {
it('expands the list of suggestions with --scope args', () => {
const suggestions = completeExtensionsAndScopes(mockContext, 'ext');
expect(suggestions).toEqual([
'ext-one --scope user',
'ext-one --scope workspace',
'ext-one --scope session',
'ext-two --scope user',
'ext-two --scope workspace',
'ext-two --scope session',
]);
});
});
describe('update', () => {
const updateAction = extensionsCommand.subCommands?.find(
const updateAction = extensionsCommand().subCommands?.find(
(cmd) => cmd.name === 'update',
)?.action;
@@ -230,92 +349,10 @@ describe('extensionsCommand', () => {
expect.any(Number),
);
});
describe('completion', () => {
const updateCompletion = extensionsCommand.subCommands?.find(
(cmd) => cmd.name === 'update',
)?.completion;
if (!updateCompletion) {
throw new Error('Update completion not found');
}
const extensionOne: GeminiCLIExtension = {
name: 'ext-one',
id: 'ext-one-id',
version: '1.0.0',
isActive: true,
path: '/test/dir/ext-one',
contextFiles: [],
installMetadata: {
type: 'git',
autoUpdate: false,
source: 'https://github.com/some/extension.git',
},
};
const extensionTwo: GeminiCLIExtension = {
name: 'another-ext',
id: 'another-ext-id',
version: '1.0.0',
isActive: true,
path: '/test/dir/another-ext',
contextFiles: [],
installMetadata: {
type: 'git',
autoUpdate: false,
source: 'https://github.com/some/extension.git',
},
};
const allExt: GeminiCLIExtension = {
name: 'all-ext',
id: 'all-ext-id',
version: '1.0.0',
isActive: true,
path: '/test/dir/all-ext',
contextFiles: [],
installMetadata: {
type: 'git',
autoUpdate: false,
source: 'https://github.com/some/extension.git',
},
};
it.each([
{
description: 'should return matching extension names',
extensions: [extensionOne, extensionTwo],
partialArg: 'ext',
expected: ['ext-one'],
},
{
description: 'should return --all when partialArg matches',
extensions: [],
partialArg: '--al',
expected: ['--all'],
},
{
description:
'should return both extension names and --all when both match',
extensions: [allExt],
partialArg: 'all',
expected: ['--all', 'all-ext'],
},
{
description: 'should return an empty array if no matches',
extensions: [extensionOne],
partialArg: 'nomatch',
expected: [],
},
])('$description', async ({ extensions, partialArg, expected }) => {
mockGetExtensions.mockReturnValue(extensions);
const suggestions = await updateCompletion(mockContext, partialArg);
expect(suggestions).toEqual(expected);
});
});
});
describe('explore', () => {
const exploreAction = extensionsCommand.subCommands?.find(
const exploreAction = extensionsCommand().subCommands?.find(
(cmd) => cmd.name === 'explore',
)?.action;
@@ -398,4 +435,141 @@ describe('extensionsCommand', () => {
);
});
});
describe('when enableExtensionReloading is true', () => {
it('should include enable and disable subcommands', () => {
const command = extensionsCommand(true);
const subCommandNames = command.subCommands?.map((cmd) => cmd.name);
expect(subCommandNames).toContain('enable');
expect(subCommandNames).toContain('disable');
});
});
describe('when enableExtensionReloading is false', () => {
it('should not include enable and disable subcommands', () => {
const command = extensionsCommand(false);
const subCommandNames = command.subCommands?.map((cmd) => cmd.name);
expect(subCommandNames).not.toContain('enable');
expect(subCommandNames).not.toContain('disable');
});
});
describe('when enableExtensionReloading is not provided', () => {
it('should not include enable and disable subcommands by default', () => {
const command = extensionsCommand();
const subCommandNames = command.subCommands?.map((cmd) => cmd.name);
expect(subCommandNames).not.toContain('enable');
expect(subCommandNames).not.toContain('disable');
});
});
describe('enable', () => {
let enableAction: SlashCommand['action'];
beforeEach(() => {
enableAction = extensionsCommand(true).subCommands?.find(
(cmd) => cmd.name === 'enable',
)?.action;
expect(enableAction).not.toBeNull();
mockContext.invocation!.name = 'enable';
});
it('should show usage if no extension name is provided', async () => {
await enableAction!(mockContext, '');
expect(mockContext.ui.addItem).toHaveBeenCalledWith(
{
type: MessageType.ERROR,
text: 'Usage: /extensions enable <extension> [--scope=<user|workspace|session>]',
},
expect.any(Number),
);
});
it('should call enableExtension with the provided scope', async () => {
await enableAction!(mockContext, `${inactiveExt.name} --scope=user`);
expect(mockEnableExtension).toHaveBeenCalledWith(
inactiveExt.name,
SettingScope.User,
);
await enableAction!(mockContext, `${inactiveExt.name} --scope workspace`);
expect(mockEnableExtension).toHaveBeenCalledWith(
inactiveExt.name,
SettingScope.Workspace,
);
});
it('should support --all', async () => {
mockGetExtensions.mockReturnValue([
inactiveExt,
{ ...inactiveExt, name: 'another-inactive-ext' },
]);
await enableAction!(mockContext, '--all --scope session');
expect(mockEnableExtension).toHaveBeenCalledWith(
inactiveExt.name,
SettingScope.Session,
);
expect(mockEnableExtension).toHaveBeenCalledWith(
'another-inactive-ext',
SettingScope.Session,
);
});
});
describe('disable', () => {
let disableAction: SlashCommand['action'];
beforeEach(() => {
disableAction = extensionsCommand(true).subCommands?.find(
(cmd) => cmd.name === 'disable',
)?.action;
expect(disableAction).not.toBeNull();
mockContext.invocation!.name = 'disable';
});
it('should show usage if no extension name is provided', async () => {
await disableAction!(mockContext, '');
expect(mockContext.ui.addItem).toHaveBeenCalledWith(
{
type: MessageType.ERROR,
text: 'Usage: /extensions disable <extension> [--scope=<user|workspace|session>]',
},
expect.any(Number),
);
});
it('should call disableExtension with the provided scope', async () => {
await disableAction!(mockContext, `${activeExt.name} --scope=user`);
expect(mockDisableExtension).toHaveBeenCalledWith(
activeExt.name,
SettingScope.User,
);
await disableAction!(mockContext, `${activeExt.name} --scope workspace`);
expect(mockDisableExtension).toHaveBeenCalledWith(
activeExt.name,
SettingScope.Workspace,
);
});
it('should support --all', async () => {
mockGetExtensions.mockReturnValue([
activeExt,
{ ...activeExt, name: 'another-active-ext' },
]);
await disableAction!(mockContext, '--all --scope session');
expect(mockDisableExtension).toHaveBeenCalledWith(
activeExt.name,
SettingScope.Session,
);
expect(mockDisableExtension).toHaveBeenCalledWith(
'another-active-ext',
SettingScope.Session,
);
});
});
});

View File

@@ -4,7 +4,7 @@
* SPDX-License-Identifier: Apache-2.0
*/
import { listExtensions } from '@google/gemini-cli-core';
import { debugLogger, listExtensions } from '@google/gemini-cli-core';
import type { ExtensionUpdateInfo } from '../../config/extension.js';
import { getErrorMessage } from '../../utils/errors.js';
import { MessageType, type HistoryItemExtensionsList } from '../types.js';
@@ -15,6 +15,8 @@ import {
} from './types.js';
import open from 'open';
import process from 'node:process';
import { ExtensionManager } from '../../config/extension-manager.js';
import { SettingScope } from '../../config/settings.js';
async function listAction(context: CommandContext) {
const historyItem: HistoryItemExtensionsList = {
@@ -159,6 +161,158 @@ async function exploreAction(context: CommandContext) {
}
}
function getEnableDisableContext(
context: CommandContext,
argumentsString: string,
): {
extensionManager: ExtensionManager;
names: string[];
scope: SettingScope;
} | null {
const extensionLoader = context.services.config?.getExtensionLoader();
if (!(extensionLoader instanceof ExtensionManager)) {
debugLogger.error(
`Cannot ${context.invocation?.name} extensions in this environment`,
);
return null;
}
const parts = argumentsString.split(' ');
const name = parts[0];
if (
name === '' ||
!(
(parts.length === 2 && parts[1].startsWith('--scope=')) || // --scope=<scope>
(parts.length === 3 && parts[1] === '--scope') // --scope <scope>
)
) {
context.ui.addItem(
{
type: MessageType.ERROR,
text: `Usage: /extensions ${context.invocation?.name} <extension> [--scope=<user|workspace|session>]`,
},
Date.now(),
);
return null;
}
let scope: SettingScope;
// Transform `--scope=<scope>` to `--scope <scope>`.
if (parts.length === 2) {
parts.push(...parts[1].split('='));
parts.splice(1, 1);
}
switch (parts[2].toLowerCase()) {
case 'workspace':
scope = SettingScope.Workspace;
break;
case 'user':
scope = SettingScope.User;
break;
case 'session':
scope = SettingScope.Session;
break;
default:
context.ui.addItem(
{
type: MessageType.ERROR,
text: `Unsupported scope ${parts[2]}, should be one of "user", "workspace", or "session"`,
},
Date.now(),
);
debugLogger.error();
return null;
}
let names: string[] = [];
if (name === '--all') {
let extensions = extensionLoader.getExtensions();
if (context.invocation?.name === 'enable') {
extensions = extensions.filter((ext) => !ext.isActive);
}
if (context.invocation?.name === 'disable') {
extensions = extensions.filter((ext) => ext.isActive);
}
names = extensions.map((ext) => ext.name);
} else {
names = [name];
}
return {
extensionManager: extensionLoader,
names,
scope,
};
}
async function disableAction(context: CommandContext, args: string) {
const enableContext = getEnableDisableContext(context, args);
if (!enableContext) return;
const { names, scope, extensionManager } = enableContext;
for (const name of names) {
await extensionManager.disableExtension(name, scope);
context.ui.addItem(
{
type: MessageType.INFO,
text: `Extension "${name}" disabled for the scope "${scope}"`,
},
Date.now(),
);
}
}
async function enableAction(context: CommandContext, args: string) {
const enableContext = getEnableDisableContext(context, args);
if (!enableContext) return;
const { names, scope, extensionManager } = enableContext;
for (const name of names) {
await extensionManager.enableExtension(name, scope);
context.ui.addItem(
{
type: MessageType.INFO,
text: `Extension "${name}" enabled for the scope "${scope}"`,
},
Date.now(),
);
}
}
/**
* Exported for testing.
*/
export function completeExtensions(
context: CommandContext,
partialArg: string,
) {
let extensions = context.services.config?.getExtensions() ?? [];
if (context.invocation?.name === 'enable') {
extensions = extensions.filter((ext) => !ext.isActive);
}
if (context.invocation?.name === 'disable') {
extensions = extensions.filter((ext) => ext.isActive);
}
const extensionNames = extensions.map((ext) => ext.name);
const suggestions = extensionNames.filter((name) =>
name.startsWith(partialArg),
);
if ('--all'.startsWith(partialArg) || 'all'.startsWith(partialArg)) {
suggestions.unshift('--all');
}
return suggestions;
}
export function completeExtensionsAndScopes(
context: CommandContext,
partialArg: string,
) {
return completeExtensions(context, partialArg).flatMap((s) => [
`${s} --scope user`,
`${s} --scope workspace`,
`${s} --scope session`,
]);
}
const listExtensionsCommand: SlashCommand = {
name: 'list',
description: 'List active extensions',
@@ -171,21 +325,23 @@ const updateExtensionsCommand: SlashCommand = {
description: 'Update extensions. Usage: update <extension-names>|--all',
kind: CommandKind.BUILT_IN,
action: updateAction,
completion: async (context, partialArg) => {
const extensions = context.services.config
? listExtensions(context.services.config)
: [];
const extensionNames = extensions.map((ext) => ext.name);
const suggestions = extensionNames.filter((name) =>
name.startsWith(partialArg),
);
completion: completeExtensions,
};
if ('--all'.startsWith(partialArg) || 'all'.startsWith(partialArg)) {
suggestions.unshift('--all');
}
const disableCommand: SlashCommand = {
name: 'disable',
description: 'Disable an extension',
kind: CommandKind.BUILT_IN,
action: disableAction,
completion: completeExtensionsAndScopes,
};
return suggestions;
},
const enableCommand: SlashCommand = {
name: 'enable',
description: 'Enable an extension',
kind: CommandKind.BUILT_IN,
action: enableAction,
completion: completeExtensionsAndScopes,
};
const exploreExtensionsCommand: SlashCommand = {
@@ -195,16 +351,24 @@ const exploreExtensionsCommand: SlashCommand = {
action: exploreAction,
};
export const extensionsCommand: SlashCommand = {
name: 'extensions',
description: 'Manage extensions',
kind: CommandKind.BUILT_IN,
subCommands: [
listExtensionsCommand,
updateExtensionsCommand,
exploreExtensionsCommand,
],
action: (context, args) =>
// Default to list if no subcommand is provided
listExtensionsCommand.action!(context, args),
};
export function extensionsCommand(
enableExtensionReloading?: boolean,
): SlashCommand {
const conditionalCommands = enableExtensionReloading
? [disableCommand, enableCommand]
: [];
return {
name: 'extensions',
description: 'Manage extensions',
kind: CommandKind.BUILT_IN,
subCommands: [
listExtensionsCommand,
updateExtensionsCommand,
exploreExtensionsCommand,
...conditionalCommands,
],
action: (context, args) =>
// Default to list if no subcommand is provided
listExtensionsCommand.action!(context, args),
};
}

View File

@@ -211,7 +211,7 @@ export interface SlashCommand {
completion?: (
context: CommandContext,
partialArg: string,
) => Promise<string[]>;
) => Promise<string[]> | string[];
subCommands?: SlashCommand[];
}