File size: 41,645 Bytes
52efc7b | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 | /**
* @license
* Copyright 2025 Google LLC
* SPDX-License-Identifier: Apache-2.0
*/
import { type ReactElement } from 'react';
import type {
ExtensionLoader,
GeminiCLIExtension,
} from '@google/gemini-cli-core';
import { createMockCommandContext } from '../../test-utils/mockCommandContext.js';
import { MessageType } from '../types.js';
import {
completeExtensions,
completeExtensionsAndScopes,
extensionsCommand,
} from './extensionsCommand.js';
import {
ConfigExtensionDialog,
type ConfigExtensionDialogProps,
} from '../components/ConfigExtensionDialog.js';
import {
ExtensionRegistryView,
type ExtensionRegistryViewProps,
} from '../components/views/ExtensionRegistryView.js';
import { type CommandContext, type SlashCommand } from './types.js';
import {
describe,
it,
expect,
vi,
beforeEach,
afterEach,
type MockedFunction,
} from 'vitest';
import { type ExtensionUpdateAction } from '../state/extensions.js';
import {
ExtensionManager,
inferInstallMetadata,
} from '../../config/extension-manager.js';
import { SettingScope } from '../../config/settings.js';
import { stat } from 'node:fs/promises';
import { type RegistryExtension } from '../../config/extensionRegistryClient.js';
import { waitFor } from '../../test-utils/async.js';
vi.mock('../../config/extension-manager.js', async (importOriginal) => {
const actual =
await importOriginal<typeof import('../../config/extension-manager.js')>();
return {
...actual,
inferInstallMetadata: vi.fn(),
};
});
import open from 'open';
import type { Stats } from 'node:fs';
vi.mock('open', () => ({
default: vi.fn(),
}));
vi.mock('node:fs/promises', () => ({
stat: vi.fn(),
}));
vi.mock('../../config/extensions/extensionSettings.js', () => ({
ExtensionSettingScope: {
USER: 'user',
WORKSPACE: 'workspace',
},
getScopedEnvContents: vi.fn().mockResolvedValue({}),
promptForSetting: vi.fn(),
updateSetting: vi.fn(),
}));
vi.mock('prompts', () => ({
default: vi.fn(),
}));
vi.mock('../../config/extensions/update.js', () => ({
updateExtension: vi.fn(),
checkForAllExtensionUpdates: vi.fn(),
}));
const mockDisableExtension = vi.fn();
const mockEnableExtension = vi.fn();
const mockInstallExtension = vi.fn();
const mockUninstallExtension = 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();
let mockExtensionLoader: unknown;
let mockReloadSkills: MockedFunction<() => Promise<void>>;
let mockReloadAgents: MockedFunction<() => Promise<void>>;
beforeEach(() => {
vi.resetAllMocks();
mockExtensionLoader = Object.create(ExtensionManager.prototype);
Object.assign(mockExtensionLoader as object, {
enableExtension: mockEnableExtension,
disableExtension: mockDisableExtension,
installOrUpdateExtension: mockInstallExtension,
uninstallExtension: mockUninstallExtension,
getExtensions: mockGetExtensions,
loadExtensionConfig: vi.fn().mockResolvedValue({
name: 'test-ext',
settings: [{ name: 'setting1', envVar: 'SETTING1' }],
}),
});
mockGetExtensions.mockReturnValue([inactiveExt, activeExt, allExt]);
vi.mocked(open).mockClear();
mockReloadAgents = vi.fn().mockResolvedValue(undefined);
mockReloadSkills = vi.fn().mockResolvedValue(undefined);
mockContext = createMockCommandContext({
services: {
agentContext: {
config: {
getExtensions: mockGetExtensions,
getExtensionLoader: vi.fn().mockReturnValue(mockExtensionLoader),
getWorkingDir: () => '/test/dir',
reloadSkills: mockReloadSkills,
getAgentRegistry: vi.fn().mockReturnValue({
reload: mockReloadAgents,
}),
},
},
},
ui: {
dispatchExtensionStateUpdate: mockDispatchExtensionState,
removeComponent: vi.fn(),
},
});
});
afterEach(() => {
// Restore any stubbed environment variables, similar to docsCommand.test.ts
vi.unstubAllEnvs();
});
describe('list', () => {
it('should add an EXTENSIONS_LIST item to the UI', async () => {
const command = extensionsCommand();
if (!command.action) throw new Error('Action not defined');
await command.action(mockContext, '');
expect(mockContext.ui.addItem).toHaveBeenCalledWith({
type: MessageType.EXTENSIONS_LIST,
extensions: expect.any(Array),
});
});
it('should show a message if no extensions are installed', async () => {
mockGetExtensions.mockReturnValue([]);
const command = extensionsCommand();
if (!command.action) throw new Error('Action not defined');
await command.action(mockContext, '');
expect(mockContext.ui.addItem).toHaveBeenCalledWith({
type: MessageType.INFO,
text: 'No extensions installed. Run `/extensions explore` to check out the gallery.',
});
});
});
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(
(cmd) => cmd.name === 'update',
)?.action;
if (!updateAction) {
throw new Error('Update action not found');
}
it('should show usage if no args are provided', async () => {
await updateAction(mockContext, '');
expect(mockContext.ui.addItem).toHaveBeenCalledWith({
type: MessageType.ERROR,
text: 'Usage: /extensions update <extension-names>|--all',
});
});
it('should show a message if no extensions are installed', async () => {
mockGetExtensions.mockReturnValue([]);
await updateAction(mockContext, 'ext-one');
expect(mockContext.ui.addItem).toHaveBeenCalledWith({
type: MessageType.INFO,
text: 'No extensions installed. Run `/extensions explore` to check out the gallery.',
});
});
it('should inform user if there are no extensions to update with --all', async () => {
mockDispatchExtensionState.mockImplementationOnce(
async (action: ExtensionUpdateAction) => {
if (action.type === 'SCHEDULE_UPDATE') {
action.payload.onComplete([]);
}
},
);
await updateAction(mockContext, '--all');
expect(mockContext.ui.addItem).toHaveBeenCalledWith({
type: MessageType.INFO,
text: 'No extensions to update.',
});
});
it('should call setPendingItem and addItem in a finally block on success', async () => {
mockDispatchExtensionState.mockImplementationOnce(
async (action: ExtensionUpdateAction) => {
if (action.type === 'SCHEDULE_UPDATE') {
action.payload.onComplete([
{
name: 'ext-one',
originalVersion: '1.0.0',
updatedVersion: '1.0.1',
},
{
name: 'ext-two',
originalVersion: '2.0.0',
updatedVersion: '2.0.1',
},
]);
}
},
);
await updateAction(mockContext, '--all');
expect(mockContext.ui.setPendingItem).toHaveBeenCalledWith({
type: MessageType.EXTENSIONS_LIST,
extensions: expect.any(Array),
});
expect(mockContext.ui.setPendingItem).toHaveBeenCalledWith(null);
expect(mockContext.ui.addItem).toHaveBeenCalledWith({
type: MessageType.EXTENSIONS_LIST,
extensions: expect.any(Array),
});
});
it('should call setPendingItem and addItem in a finally block on failure', async () => {
mockDispatchExtensionState.mockImplementationOnce((_) => {
throw new Error('Something went wrong');
});
await updateAction(mockContext, '--all');
expect(mockContext.ui.setPendingItem).toHaveBeenCalledWith({
type: MessageType.EXTENSIONS_LIST,
extensions: expect.any(Array),
});
expect(mockContext.ui.setPendingItem).toHaveBeenCalledWith(null);
expect(mockContext.ui.addItem).toHaveBeenCalledWith({
type: MessageType.EXTENSIONS_LIST,
extensions: expect.any(Array),
});
expect(mockContext.ui.addItem).toHaveBeenCalledWith({
type: MessageType.ERROR,
text: 'Something went wrong',
});
});
it('should update a single extension by name', async () => {
mockDispatchExtensionState.mockImplementationOnce(
async (action: ExtensionUpdateAction) => {
if (action.type === 'SCHEDULE_UPDATE') {
action.payload.onComplete([
{
name: 'ext-one',
originalVersion: '1.0.0',
updatedVersion: '1.0.1',
},
]);
}
},
);
await updateAction(mockContext, 'ext-one');
expect(mockDispatchExtensionState).toHaveBeenCalledWith({
type: 'SCHEDULE_UPDATE',
payload: {
all: false,
names: ['ext-one'],
onComplete: expect.any(Function),
},
});
});
it('should update multiple extensions by name', async () => {
mockDispatchExtensionState.mockImplementationOnce(
async (action: ExtensionUpdateAction) => {
if (action.type === 'SCHEDULE_UPDATE') {
action.payload.onComplete([
{
name: 'ext-one',
originalVersion: '1.0.0',
updatedVersion: '1.0.1',
},
{
name: 'ext-two',
originalVersion: '1.0.0',
updatedVersion: '1.0.1',
},
]);
}
},
);
await updateAction(mockContext, 'ext-one ext-two');
expect(mockDispatchExtensionState).toHaveBeenCalledWith({
type: 'SCHEDULE_UPDATE',
payload: {
all: false,
names: ['ext-one', 'ext-two'],
onComplete: expect.any(Function),
},
});
expect(mockContext.ui.setPendingItem).toHaveBeenCalledWith({
type: MessageType.EXTENSIONS_LIST,
extensions: expect.any(Array),
});
expect(mockContext.ui.setPendingItem).toHaveBeenCalledWith(null);
expect(mockContext.ui.addItem).toHaveBeenCalledWith({
type: MessageType.EXTENSIONS_LIST,
extensions: expect.any(Array),
});
});
});
describe('explore', () => {
const exploreAction = extensionsCommand().subCommands?.find(
(cmd) => cmd.name === 'explore',
)?.action;
if (!exploreAction) {
throw new Error('Explore action not found');
}
it('should return ExtensionRegistryView custom dialog when experimental.extensionRegistry is true', async () => {
mockContext.services.settings.merged.experimental.extensionRegistry =
true;
const result = await exploreAction(mockContext, '');
expect(result).toBeDefined();
if (result?.type !== 'custom_dialog') {
throw new Error('Expected custom_dialog');
}
const component =
result.component as ReactElement<ExtensionRegistryViewProps>;
expect(component.type).toBe(ExtensionRegistryView);
expect(component.props.extensionManager).toBe(mockExtensionLoader);
});
it('should handle onSelect and onClose in ExtensionRegistryView', async () => {
mockContext.services.settings.merged.experimental.extensionRegistry =
true;
const result = await exploreAction(mockContext, '');
if (result?.type !== 'custom_dialog') {
throw new Error('Expected custom_dialog');
}
const component =
result.component as ReactElement<ExtensionRegistryViewProps>;
const extension = {
extensionName: 'test-ext',
url: 'https://github.com/test/ext.git',
} as RegistryExtension;
vi.mocked(inferInstallMetadata).mockResolvedValue({
source: extension.url,
type: 'git',
});
mockInstallExtension.mockResolvedValue({ name: extension.url });
// Call onSelect
await component.props.onSelect?.(extension);
await waitFor(() => {
expect(inferInstallMetadata).toHaveBeenCalledWith(extension.url);
expect(mockInstallExtension).toHaveBeenCalledWith(
{
source: extension.url,
type: 'git',
},
undefined,
undefined,
);
});
expect(mockContext.ui.removeComponent).toHaveBeenCalledTimes(1);
// Call onClose
component.props.onClose?.();
expect(mockContext.ui.removeComponent).toHaveBeenCalledTimes(2);
});
it("should add an info message and call 'open' in a non-sandbox environment", async () => {
// Ensure no special environment variables that would affect behavior
vi.stubEnv('NODE_ENV', '');
vi.stubEnv('SANDBOX', '');
await exploreAction(mockContext, '');
const extensionsUrl = 'https://geminicli.com/extensions/';
expect(mockContext.ui.addItem).toHaveBeenCalledWith({
type: MessageType.INFO,
text: `Opening extensions page in your browser: ${extensionsUrl}`,
});
expect(open).toHaveBeenCalledWith(extensionsUrl);
});
it('should only add an info message in a sandbox environment', async () => {
// Simulate a sandbox environment
vi.stubEnv('NODE_ENV', '');
vi.stubEnv('SANDBOX', 'gemini-sandbox');
const extensionsUrl = 'https://geminicli.com/extensions/';
await exploreAction(mockContext, '');
expect(mockContext.ui.addItem).toHaveBeenCalledWith({
type: MessageType.INFO,
text: `View available extensions at ${extensionsUrl}`,
});
// Ensure 'open' was not called in the sandbox
expect(open).not.toHaveBeenCalled();
});
it('should add an info message and not call open in NODE_ENV test environment', async () => {
vi.stubEnv('NODE_ENV', 'test');
vi.stubEnv('SANDBOX', '');
const extensionsUrl = 'https://geminicli.com/extensions/';
await exploreAction(mockContext, '');
expect(mockContext.ui.addItem).toHaveBeenCalledWith({
type: MessageType.INFO,
text: `Would open extensions page in your browser: ${extensionsUrl} (skipped in test environment)`,
});
// Ensure 'open' was not called in test environment
expect(open).not.toHaveBeenCalled();
});
it('should handle errors when opening the browser', async () => {
vi.stubEnv('NODE_ENV', '');
const extensionsUrl = 'https://geminicli.com/extensions/';
const errorMessage = 'Failed to open browser';
vi.mocked(open).mockRejectedValue(new Error(errorMessage));
await exploreAction(mockContext, '');
expect(mockContext.ui.addItem).toHaveBeenCalledWith({
type: MessageType.ERROR,
text: `Failed to open browser. Check out the extensions gallery at ${extensionsUrl}`,
});
});
});
describe('when enableExtensionReloading is true', () => {
it('should include enable, disable, install, link, and uninstall subcommands', () => {
const command = extensionsCommand(true);
const subCommandNames = command.subCommands?.map((cmd) => cmd.name);
expect(subCommandNames).toContain('enable');
expect(subCommandNames).toContain('disable');
expect(subCommandNames).toContain('install');
expect(subCommandNames).toContain('link');
expect(subCommandNames).toContain('uninstall');
});
});
describe('when enableExtensionReloading is false', () => {
it('should not include enable, disable, install, link, and uninstall subcommands', () => {
const command = extensionsCommand(false);
const subCommandNames = command.subCommands?.map((cmd) => cmd.name);
expect(subCommandNames).not.toContain('enable');
expect(subCommandNames).not.toContain('disable');
expect(subCommandNames).not.toContain('install');
expect(subCommandNames).not.toContain('link');
expect(subCommandNames).not.toContain('uninstall');
});
});
describe('when enableExtensionReloading is not provided', () => {
it('should not include enable, disable, install, link, and uninstall subcommands by default', () => {
const command = extensionsCommand();
const subCommandNames = command.subCommands?.map((cmd) => cmd.name);
expect(subCommandNames).not.toContain('enable');
expect(subCommandNames).not.toContain('disable');
expect(subCommandNames).not.toContain('install');
expect(subCommandNames).not.toContain('link');
expect(subCommandNames).not.toContain('uninstall');
});
});
describe('install', () => {
let installAction: SlashCommand['action'];
beforeEach(() => {
installAction = extensionsCommand(true).subCommands?.find(
(cmd) => cmd.name === 'install',
)?.action;
expect(installAction).not.toBeNull();
mockContext.invocation!.name = 'install';
});
it('should show usage if no extension name is provided', async () => {
await installAction!(mockContext, '');
expect(mockContext.ui.addItem).toHaveBeenCalledWith({
type: MessageType.ERROR,
text: 'Usage: /extensions install <source>',
});
expect(mockInstallExtension).not.toHaveBeenCalled();
});
it('should call installExtension and show success message', async () => {
const packageName = 'test-extension-package';
vi.mocked(inferInstallMetadata).mockResolvedValue({
source: packageName,
type: 'git',
});
mockInstallExtension.mockResolvedValue({ name: packageName });
await installAction!(mockContext, packageName);
expect(inferInstallMetadata).toHaveBeenCalledWith(packageName);
expect(mockInstallExtension).toHaveBeenCalledWith(
{
source: packageName,
type: 'git',
},
undefined,
undefined,
);
expect(mockContext.ui.addItem).toHaveBeenCalledWith({
type: MessageType.INFO,
text: `Installing extension from "${packageName}"...`,
});
expect(mockContext.ui.addItem).toHaveBeenCalledWith({
type: MessageType.INFO,
text: `Extension "${packageName}" installed successfully.`,
});
});
it('should show error message on installation failure', async () => {
const packageName = 'failed-extension';
const errorMessage = 'install failed';
vi.mocked(inferInstallMetadata).mockResolvedValue({
source: packageName,
type: 'git',
});
mockInstallExtension.mockRejectedValue(new Error(errorMessage));
await installAction!(mockContext, packageName);
expect(inferInstallMetadata).toHaveBeenCalledWith(packageName);
expect(mockInstallExtension).toHaveBeenCalledWith(
{
source: packageName,
type: 'git',
},
undefined,
undefined,
);
expect(mockContext.ui.addItem).toHaveBeenCalledWith({
type: MessageType.ERROR,
text: `Failed to install extension from "${packageName}": ${errorMessage}`,
});
});
it('should show error message for invalid source', async () => {
const invalidSource = 'a;b';
await installAction!(mockContext, invalidSource);
expect(mockContext.ui.addItem).toHaveBeenCalledWith({
type: MessageType.ERROR,
text: `Invalid source: ${invalidSource}`,
});
expect(mockInstallExtension).not.toHaveBeenCalled();
});
});
describe('link', () => {
let linkAction: SlashCommand['action'];
beforeEach(() => {
linkAction = extensionsCommand(true).subCommands?.find(
(cmd) => cmd.name === 'link',
)?.action;
expect(linkAction).not.toBeNull();
mockContext.invocation!.name = 'link';
});
it('should show usage if no extension is provided', async () => {
await linkAction!(mockContext, '');
expect(mockContext.ui.addItem).toHaveBeenCalledWith({
type: MessageType.ERROR,
text: 'Usage: /extensions link <source>',
});
expect(mockInstallExtension).not.toHaveBeenCalled();
});
it('should call installExtension and show success message', async () => {
const packageName = 'test-extension-package';
mockInstallExtension.mockResolvedValue({ name: packageName });
vi.mocked(stat).mockResolvedValue({
size: 100,
} as Stats);
await linkAction!(mockContext, packageName);
expect(mockInstallExtension).toHaveBeenCalledWith(
{
source: packageName,
type: 'link',
},
undefined,
undefined,
);
expect(mockContext.ui.addItem).toHaveBeenCalledWith({
type: MessageType.INFO,
text: `Linking extension from "${packageName}"...`,
});
expect(mockContext.ui.addItem).toHaveBeenCalledWith({
type: MessageType.INFO,
text: `Extension "${packageName}" linked successfully.`,
});
});
it('should show error message on linking failure', async () => {
const packageName = 'test-extension-package';
const errorMessage = 'link failed';
mockInstallExtension.mockRejectedValue(new Error(errorMessage));
vi.mocked(stat).mockResolvedValue({
size: 100,
} as Stats);
await linkAction!(mockContext, packageName);
expect(mockInstallExtension).toHaveBeenCalledWith(
{
source: packageName,
type: 'link',
},
undefined,
undefined,
);
expect(mockContext.ui.addItem).toHaveBeenCalledWith({
type: MessageType.ERROR,
text: `Failed to link extension from "${packageName}": ${errorMessage}`,
});
});
it('should show error message for invalid source', async () => {
const packageName = 'test-extension-package';
const errorMessage = 'invalid path';
vi.mocked(stat).mockRejectedValue(new Error(errorMessage));
await linkAction!(mockContext, packageName);
expect(mockInstallExtension).not.toHaveBeenCalled();
});
});
describe('uninstall', () => {
let uninstallAction: SlashCommand['action'];
beforeEach(() => {
uninstallAction = extensionsCommand(true).subCommands?.find(
(cmd) => cmd.name === 'uninstall',
)?.action;
expect(uninstallAction).not.toBeNull();
mockContext.invocation!.name = 'uninstall';
});
it('should show usage if no extension name is provided', async () => {
await uninstallAction!(mockContext, '');
expect(mockContext.ui.addItem).toHaveBeenCalledWith({
type: MessageType.ERROR,
text: 'Usage: /extensions uninstall <extension-names...>|--all',
});
expect(mockUninstallExtension).not.toHaveBeenCalled();
});
it('should expose "delete" as an alias', () => {
const uninstallCmd = extensionsCommand(true).subCommands?.find(
(cmd) => cmd.name === 'uninstall',
);
expect(uninstallCmd?.altNames).toContain('delete');
});
it('should call uninstallExtension and show success message', async () => {
const extensionName = 'test-extension';
await uninstallAction!(mockContext, extensionName);
expect(mockUninstallExtension).toHaveBeenCalledWith(extensionName, false);
expect(mockContext.ui.addItem).toHaveBeenCalledWith({
type: MessageType.INFO,
text: `Uninstalling extension "${extensionName}"...`,
});
expect(mockContext.ui.addItem).toHaveBeenCalledWith({
type: MessageType.INFO,
text: `Extension "${extensionName}" uninstalled successfully.`,
});
});
it('should show error message on uninstallation failure', async () => {
const extensionName = 'failed-extension';
const errorMessage = 'uninstall failed';
mockUninstallExtension.mockRejectedValue(new Error(errorMessage));
await uninstallAction!(mockContext, extensionName);
expect(mockUninstallExtension).toHaveBeenCalledWith(extensionName, false);
expect(mockContext.ui.addItem).toHaveBeenCalledWith({
type: MessageType.ERROR,
text: `Failed to uninstall extension "${extensionName}": ${errorMessage}`,
});
});
});
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>]',
});
});
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>]',
});
});
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,
);
});
});
describe('reload', () => {
let restartAction: SlashCommand['action'];
let mockRestartExtension: MockedFunction<
typeof ExtensionLoader.prototype.restartExtension
>;
beforeEach(() => {
restartAction = extensionsCommand().subCommands?.find(
(c) => c.name === 'reload',
)?.action;
expect(restartAction).not.toBeNull();
mockRestartExtension = vi.fn();
mockContext.services.agentContext!.config.getExtensionLoader = vi
.fn()
.mockImplementation(() => ({
getExtensions: mockGetExtensions,
restartExtension: mockRestartExtension,
}));
mockContext.invocation!.name = 'reload';
});
it('should show a message if no extensions are installed', async () => {
mockContext.services.agentContext!.config.getExtensionLoader = vi
.fn()
.mockImplementation(() => ({
getExtensions: () => [],
restartExtension: mockRestartExtension,
}));
await restartAction!(mockContext, '--all');
expect(mockContext.ui.addItem).toHaveBeenCalledWith({
type: MessageType.INFO,
text: 'No extensions installed. Run `/extensions explore` to check out the gallery.',
});
});
it('reloads all active extensions when --all is provided', async () => {
const mockExtensions = [
{ name: 'ext1', isActive: true },
{ name: 'ext2', isActive: true },
{ name: 'ext3', isActive: false },
] as GeminiCLIExtension[];
mockGetExtensions.mockReturnValue(mockExtensions);
await restartAction!(mockContext, '--all');
expect(mockRestartExtension).toHaveBeenCalledTimes(2);
expect(mockRestartExtension).toHaveBeenCalledWith(mockExtensions[0]);
expect(mockRestartExtension).toHaveBeenCalledWith(mockExtensions[1]);
expect(mockContext.ui.addItem).toHaveBeenCalledWith(
expect.objectContaining({
type: MessageType.INFO,
text: 'Reloading 2 extensions...',
}),
);
expect(mockContext.ui.addItem).toHaveBeenCalledWith(
expect.objectContaining({
type: MessageType.INFO,
text: '2 extensions reloaded successfully',
}),
);
expect(mockContext.ui.dispatchExtensionStateUpdate).toHaveBeenCalledWith({
type: 'RESTARTED',
payload: { name: 'ext1' },
});
expect(mockContext.ui.dispatchExtensionStateUpdate).toHaveBeenCalledWith({
type: 'RESTARTED',
payload: { name: 'ext2' },
});
expect(mockReloadSkills).toHaveBeenCalled();
expect(mockReloadAgents).toHaveBeenCalled();
});
it('handles errors during skill or agent reload', async () => {
const mockExtensions = [
{ name: 'ext1', isActive: true },
] as GeminiCLIExtension[];
mockGetExtensions.mockReturnValue(mockExtensions);
mockReloadSkills.mockRejectedValue(new Error('Failed to reload skills'));
await restartAction!(mockContext, '--all');
expect(mockRestartExtension).toHaveBeenCalledWith(mockExtensions[0]);
expect(mockReloadSkills).toHaveBeenCalled();
expect(mockContext.ui.addItem).toHaveBeenCalledWith(
expect.objectContaining({
type: MessageType.ERROR,
text: 'Failed to reload skills or agents: Failed to reload skills',
}),
);
});
it('reloads only specified active extensions', async () => {
const mockExtensions = [
{ name: 'ext1', isActive: false },
{ name: 'ext2', isActive: true },
{ name: 'ext3', isActive: true },
] as GeminiCLIExtension[];
mockGetExtensions.mockReturnValue(mockExtensions);
await restartAction!(mockContext, 'ext1 ext3');
expect(mockRestartExtension).toHaveBeenCalledTimes(1);
expect(mockRestartExtension).toHaveBeenCalledWith(mockExtensions[2]);
expect(mockContext.ui.dispatchExtensionStateUpdate).toHaveBeenCalledWith({
type: 'RESTARTED',
payload: { name: 'ext3' },
});
});
it('shows an error if no extension loader is available', async () => {
mockContext.services.agentContext!.config.getExtensionLoader = vi.fn();
await restartAction!(mockContext, '--all');
expect(mockContext.ui.addItem).toHaveBeenCalledWith(
expect.objectContaining({
type: MessageType.ERROR,
text: "Extensions are not yet loaded, can't restart yet",
}),
);
expect(mockRestartExtension).not.toHaveBeenCalled();
});
it('shows usage error for no arguments', async () => {
await restartAction!(mockContext, '');
expect(mockContext.ui.addItem).toHaveBeenCalledWith(
expect.objectContaining({
type: MessageType.ERROR,
text: 'Usage: /extensions reload <extension-names>|--all',
}),
);
expect(mockRestartExtension).not.toHaveBeenCalled();
});
it('handles errors during extension reload', async () => {
const mockExtensions = [
{ name: 'ext1', isActive: true },
] as GeminiCLIExtension[];
mockGetExtensions.mockReturnValue(mockExtensions);
mockRestartExtension.mockRejectedValue(new Error('Failed to restart'));
await restartAction!(mockContext, '--all');
expect(mockRestartExtension).toHaveBeenCalledWith(mockExtensions[0]);
expect(mockContext.ui.addItem).toHaveBeenCalledWith(
expect.objectContaining({
type: MessageType.ERROR,
text: 'Failed to reload some extensions:\n ext1: Failed to restart',
}),
);
});
it('shows a warning if an extension is not found', async () => {
const mockExtensions = [
{ name: 'ext1', isActive: true },
] as GeminiCLIExtension[];
mockGetExtensions.mockReturnValue(mockExtensions);
await restartAction!(mockContext, 'ext1 ext2');
expect(mockRestartExtension).toHaveBeenCalledTimes(1);
expect(mockRestartExtension).toHaveBeenCalledWith(mockExtensions[0]);
expect(mockContext.ui.addItem).toHaveBeenCalledWith(
expect.objectContaining({
type: MessageType.WARNING,
text: 'Extension(s) not found or not active: ext2',
}),
);
});
it('does not reload any extensions if none are found', async () => {
const mockExtensions = [
{ name: 'ext1', isActive: true },
] as GeminiCLIExtension[];
mockGetExtensions.mockReturnValue(mockExtensions);
await restartAction!(mockContext, 'ext2 ext3');
expect(mockRestartExtension).not.toHaveBeenCalled();
expect(mockContext.ui.addItem).toHaveBeenCalledWith(
expect.objectContaining({
type: MessageType.WARNING,
text: 'Extension(s) not found or not active: ext2, ext3',
}),
);
});
it('should suggest only enabled extension names for the reload command', async () => {
mockContext.invocation!.name = 'reload';
const mockExtensions = [
{ name: 'ext1', isActive: true },
{ name: 'ext2', isActive: false },
] as GeminiCLIExtension[];
mockGetExtensions.mockReturnValue(mockExtensions);
const suggestions = completeExtensions(mockContext, 'ext');
expect(suggestions).toEqual(['ext1']);
});
});
describe('config', () => {
let configAction: SlashCommand['action'];
beforeEach(async () => {
configAction = extensionsCommand(true).subCommands?.find(
(cmd) => cmd.name === 'config',
)?.action;
expect(configAction).not.toBeNull();
mockContext.invocation!.name = 'config';
const prompts = (await import('prompts')).default;
vi.mocked(prompts).mockResolvedValue({ overwrite: true });
const { getScopedEnvContents } = await import(
'../../config/extensions/extensionSettings.js'
);
vi.mocked(getScopedEnvContents).mockResolvedValue({});
});
it('should return dialog to configure all extensions if no args provided', async () => {
const result = await configAction!(mockContext, '');
if (result?.type !== 'custom_dialog') {
throw new Error('Expected custom_dialog');
}
const dialogResult = result;
const component =
dialogResult.component as ReactElement<ConfigExtensionDialogProps>;
expect(component.type).toBe(ConfigExtensionDialog);
expect(component.props.configureAll).toBe(true);
expect(component.props.extensionManager).toBeDefined();
});
it('should return dialog to configure specific extension', async () => {
const result = await configAction!(mockContext, 'ext-one');
if (result?.type !== 'custom_dialog') {
throw new Error('Expected custom_dialog');
}
const dialogResult = result;
const component =
dialogResult.component as ReactElement<ConfigExtensionDialogProps>;
expect(component.type).toBe(ConfigExtensionDialog);
expect(component.props.extensionName).toBe('ext-one');
expect(component.props.settingKey).toBeUndefined();
expect(component.props.configureAll).toBe(false);
});
it('should return dialog to configure specific setting for an extension', async () => {
const result = await configAction!(mockContext, 'ext-one SETTING1');
if (result?.type !== 'custom_dialog') {
throw new Error('Expected custom_dialog');
}
const dialogResult = result;
const component =
dialogResult.component as ReactElement<ConfigExtensionDialogProps>;
expect(component.type).toBe(ConfigExtensionDialog);
expect(component.props.extensionName).toBe('ext-one');
expect(component.props.settingKey).toBe('SETTING1');
expect(component.props.scope).toBe('user'); // Default scope
});
it('should respect scope argument passed to dialog', async () => {
const result = await configAction!(
mockContext,
'ext-one SETTING1 --scope=workspace',
);
if (result?.type !== 'custom_dialog') {
throw new Error('Expected custom_dialog');
}
const dialogResult = result;
const component =
dialogResult.component as ReactElement<ConfigExtensionDialogProps>;
expect(component.props.scope).toBe('workspace');
});
it('should show error for invalid extension name', async () => {
await configAction!(mockContext, '../invalid');
expect(mockContext.ui.addItem).toHaveBeenCalledWith({
type: MessageType.ERROR,
text: 'Invalid extension name. Names cannot contain path separators or "..".',
});
});
// "should inform if extension has no settings" - This check is now inside ConfigExtensionDialog logic.
// We can test that we still return a dialog, and the dialog will handle logical checks via utils.ts
// For unit testing extensionsCommand, we just ensure delegation.
it('should return dialog even if extension has no settings (dialog handles logic)', async () => {
const result = await configAction!(mockContext, 'ext-one');
if (result?.type !== 'custom_dialog') {
throw new Error('Expected custom_dialog');
}
const dialogResult = result;
const component =
dialogResult.component as ReactElement<ConfigExtensionDialogProps>;
expect(component.type).toBe(ConfigExtensionDialog);
});
});
});
|