Refactor Extensions Install Modal (#4328)
This commit is contained in:
@@ -0,0 +1,161 @@
|
||||
/* eslint-disable @typescript-eslint/no-explicit-any */
|
||||
|
||||
import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest';
|
||||
import { render, screen, act } from '@testing-library/react';
|
||||
import { ExtensionInstallModal } from './ExtensionInstallModal';
|
||||
import { addExtensionFromDeepLink } from './settings/extensions/deeplink';
|
||||
|
||||
vi.mock('./settings/extensions/deeplink', () => ({
|
||||
addExtensionFromDeepLink: vi.fn(),
|
||||
}));
|
||||
|
||||
const mockElectron = {
|
||||
getConfig: vi.fn(),
|
||||
getAllowedExtensions: vi.fn(),
|
||||
logInfo: vi.fn(),
|
||||
on: vi.fn(),
|
||||
off: vi.fn(),
|
||||
};
|
||||
|
||||
(window as any).electron = mockElectron;
|
||||
|
||||
describe('ExtensionInstallModal', () => {
|
||||
const mockAddExtension = vi.fn();
|
||||
|
||||
const getAddExtensionEventHandler = () => {
|
||||
const addExtensionCall = mockElectron.on.mock.calls.find((call) => call[0] === 'add-extension');
|
||||
expect(addExtensionCall).toBeDefined();
|
||||
return addExtensionCall![1];
|
||||
};
|
||||
|
||||
beforeEach(() => {
|
||||
vi.clearAllMocks();
|
||||
mockElectron.getConfig.mockReturnValue({
|
||||
GOOSE_ALLOWLIST_WARNING: false,
|
||||
});
|
||||
});
|
||||
|
||||
afterEach(() => {
|
||||
vi.clearAllMocks();
|
||||
});
|
||||
|
||||
describe('Extension Request Handling', () => {
|
||||
it('should handle trusted extension (default behaviour, no allowlist)', async () => {
|
||||
mockElectron.getAllowedExtensions.mockResolvedValue([]);
|
||||
|
||||
render(<ExtensionInstallModal addExtension={mockAddExtension} />);
|
||||
|
||||
const eventHandler = getAddExtensionEventHandler();
|
||||
|
||||
await act(async () => {
|
||||
await eventHandler({}, 'goose://extension?cmd=npx&arg=test-extension&name=TestExt');
|
||||
});
|
||||
|
||||
expect(screen.getByRole('dialog')).toBeInTheDocument();
|
||||
expect(screen.getByText('Confirm Extension Installation')).toBeInTheDocument();
|
||||
expect(screen.getByText(/TestExt extension/)).toBeInTheDocument();
|
||||
expect(screen.getAllByRole('button')).toHaveLength(3);
|
||||
});
|
||||
|
||||
it('should handle trusted extension (from allowlist)', async () => {
|
||||
mockElectron.getAllowedExtensions.mockResolvedValue(['npx test-extension']);
|
||||
|
||||
render(<ExtensionInstallModal addExtension={mockAddExtension} />);
|
||||
|
||||
const eventHandler = getAddExtensionEventHandler();
|
||||
|
||||
await act(async () => {
|
||||
await eventHandler({}, 'goose://extension?cmd=npx&arg=test-extension&name=AllowedExt');
|
||||
});
|
||||
|
||||
expect(screen.getByText('Confirm Extension Installation')).toBeInTheDocument();
|
||||
expect(screen.getAllByRole('button')).toHaveLength(3);
|
||||
});
|
||||
|
||||
it('should handle warning mode', async () => {
|
||||
mockElectron.getConfig.mockReturnValue({
|
||||
GOOSE_ALLOWLIST_WARNING: true,
|
||||
});
|
||||
mockElectron.getAllowedExtensions.mockResolvedValue(['uvx allowed-package']);
|
||||
|
||||
render(<ExtensionInstallModal addExtension={mockAddExtension} />);
|
||||
|
||||
const eventHandler = getAddExtensionEventHandler();
|
||||
|
||||
await act(async () => {
|
||||
await eventHandler(
|
||||
{},
|
||||
'goose://extension?cmd=npx&arg=untrusted-extension&name=UntrustedExt'
|
||||
);
|
||||
});
|
||||
|
||||
expect(screen.getByText('Install Untrusted Extension?')).toBeInTheDocument();
|
||||
expect(screen.getByRole('button', { name: 'Install Anyway' })).toBeInTheDocument();
|
||||
expect(screen.getAllByRole('button')).toHaveLength(3);
|
||||
});
|
||||
|
||||
it('should handle blocked extension', async () => {
|
||||
mockElectron.getAllowedExtensions.mockResolvedValue(['uvx allowed-package']);
|
||||
|
||||
render(<ExtensionInstallModal addExtension={mockAddExtension} />);
|
||||
|
||||
const eventHandler = getAddExtensionEventHandler();
|
||||
|
||||
await act(async () => {
|
||||
await eventHandler({}, 'goose://extension?cmd=npx&arg=blocked-extension&name=BlockedExt');
|
||||
});
|
||||
|
||||
expect(screen.getByText('Extension Installation Blocked')).toBeInTheDocument();
|
||||
expect(screen.getByRole('button', { name: 'OK' })).toBeInTheDocument();
|
||||
expect(screen.getAllByRole('button')).toHaveLength(2);
|
||||
expect(screen.getByText(/Contact your administrator/)).toBeInTheDocument();
|
||||
});
|
||||
});
|
||||
|
||||
describe('Modal Actions', () => {
|
||||
it('should dismiss modal correctly', async () => {
|
||||
mockElectron.getAllowedExtensions.mockResolvedValue([]);
|
||||
|
||||
render(<ExtensionInstallModal addExtension={mockAddExtension} />);
|
||||
|
||||
const eventHandler = getAddExtensionEventHandler();
|
||||
|
||||
await act(async () => {
|
||||
await eventHandler({}, 'goose://extension?cmd=npx&arg=test&name=Test');
|
||||
});
|
||||
|
||||
expect(screen.getByRole('dialog')).toBeInTheDocument();
|
||||
|
||||
await act(async () => {
|
||||
screen.getByRole('button', { name: 'No' }).click();
|
||||
});
|
||||
|
||||
expect(screen.queryByRole('dialog')).not.toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('should handle successful extension installation', async () => {
|
||||
vi.mocked(addExtensionFromDeepLink).mockResolvedValue(undefined);
|
||||
mockElectron.getAllowedExtensions.mockResolvedValue([]);
|
||||
|
||||
render(<ExtensionInstallModal addExtension={mockAddExtension} />);
|
||||
|
||||
const eventHandler = getAddExtensionEventHandler();
|
||||
|
||||
await act(async () => {
|
||||
await eventHandler({}, 'goose://extension?cmd=npx&arg=test&name=Test');
|
||||
});
|
||||
|
||||
await act(async () => {
|
||||
screen.getByRole('button', { name: 'Yes' }).click();
|
||||
});
|
||||
|
||||
expect(addExtensionFromDeepLink).toHaveBeenCalledWith(
|
||||
'goose://extension?cmd=npx&arg=test&name=Test',
|
||||
mockAddExtension,
|
||||
expect.any(Function)
|
||||
);
|
||||
|
||||
expect(screen.queryByRole('dialog')).not.toBeInTheDocument();
|
||||
});
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,305 @@
|
||||
import { useState, useCallback, useEffect } from 'react';
|
||||
import { IpcRendererEvent } from 'electron';
|
||||
import {
|
||||
Dialog,
|
||||
DialogContent,
|
||||
DialogDescription,
|
||||
DialogFooter,
|
||||
DialogHeader,
|
||||
DialogTitle,
|
||||
} from './ui/dialog';
|
||||
import { Button } from './ui/button';
|
||||
import { extractExtensionName } from './settings/extensions/utils';
|
||||
import { addExtensionFromDeepLink } from './settings/extensions/deeplink';
|
||||
import type { ExtensionConfig } from '../api/types.gen';
|
||||
|
||||
type ModalType = 'blocked' | 'untrusted' | 'trusted';
|
||||
|
||||
interface ExtensionInfo {
|
||||
name: string;
|
||||
command?: string;
|
||||
remoteUrl?: string;
|
||||
link: string;
|
||||
}
|
||||
|
||||
interface ExtensionModalState {
|
||||
isOpen: boolean;
|
||||
modalType: ModalType;
|
||||
extensionInfo: ExtensionInfo | null;
|
||||
isPending: boolean;
|
||||
error: string | null;
|
||||
}
|
||||
|
||||
interface ExtensionModalConfig {
|
||||
title: string;
|
||||
message: string;
|
||||
confirmLabel: string;
|
||||
cancelLabel: string;
|
||||
showSingleButton: boolean;
|
||||
isBlocked: boolean;
|
||||
}
|
||||
|
||||
interface ExtensionInstallModalProps {
|
||||
addExtension?: (name: string, config: ExtensionConfig, enabled: boolean) => Promise<void>;
|
||||
}
|
||||
|
||||
function extractCommand(link: string): string {
|
||||
const url = new URL(link);
|
||||
const cmd = url.searchParams.get('cmd') || 'Unknown Command';
|
||||
const args = url.searchParams.getAll('arg').map(decodeURIComponent);
|
||||
return `${cmd} ${args.join(' ')}`.trim();
|
||||
}
|
||||
|
||||
function extractRemoteUrl(link: string): string | null {
|
||||
const url = new URL(link);
|
||||
return url.searchParams.get('url');
|
||||
}
|
||||
|
||||
export function ExtensionInstallModal({ addExtension }: ExtensionInstallModalProps) {
|
||||
const [modalState, setModalState] = useState<ExtensionModalState>({
|
||||
isOpen: false,
|
||||
modalType: 'trusted',
|
||||
extensionInfo: null,
|
||||
isPending: false,
|
||||
error: null,
|
||||
});
|
||||
|
||||
const [pendingLink, setPendingLink] = useState<string | null>(null);
|
||||
|
||||
const determineModalType = async (
|
||||
command: string,
|
||||
_remoteUrl: string | null
|
||||
): Promise<ModalType> => {
|
||||
try {
|
||||
const config = window.electron.getConfig();
|
||||
const ALLOWLIST_WARNING_MODE = config.GOOSE_ALLOWLIST_WARNING === true;
|
||||
|
||||
if (ALLOWLIST_WARNING_MODE) {
|
||||
return 'untrusted';
|
||||
}
|
||||
|
||||
const allowedCommands = await window.electron.getAllowedExtensions();
|
||||
|
||||
if (!allowedCommands || allowedCommands.length === 0) {
|
||||
return 'trusted';
|
||||
}
|
||||
|
||||
const isCommandAllowed = allowedCommands.some((allowedCmd: string) =>
|
||||
command.startsWith(allowedCmd)
|
||||
);
|
||||
|
||||
return isCommandAllowed ? 'trusted' : 'blocked';
|
||||
} catch (error) {
|
||||
console.error('Error checking allowlist:', error);
|
||||
return 'trusted';
|
||||
}
|
||||
};
|
||||
|
||||
const generateModalConfig = (
|
||||
modalType: ModalType,
|
||||
extensionInfo: ExtensionInfo
|
||||
): ExtensionModalConfig => {
|
||||
const { name, command, remoteUrl } = extensionInfo;
|
||||
|
||||
switch (modalType) {
|
||||
case 'blocked':
|
||||
return {
|
||||
title: 'Extension Installation Blocked',
|
||||
message: `\n\nThis extension command is not in the allowed list and its installation is blocked.\n\nExtension: ${name}\nCommand: ${command || remoteUrl}\n\nContact your administrator to request approval for this extension.`,
|
||||
confirmLabel: 'OK',
|
||||
cancelLabel: '',
|
||||
showSingleButton: true,
|
||||
isBlocked: true,
|
||||
};
|
||||
|
||||
case 'untrusted': {
|
||||
const securityMessage = `\n\nThis extension command is not in the allowed list and will be able to access your conversations and provide additional functionality.\n\nInstalling extensions from untrusted sources may pose security risks.`;
|
||||
|
||||
return {
|
||||
title: 'Install Untrusted Extension?',
|
||||
message: `${securityMessage}\n\nExtension: ${name}\n${remoteUrl ? `URL: ${remoteUrl}` : `Command: ${command}`}\n\nContact your administrator if you are unsure about this.`,
|
||||
confirmLabel: 'Install Anyway',
|
||||
cancelLabel: 'Cancel',
|
||||
showSingleButton: false,
|
||||
isBlocked: false,
|
||||
};
|
||||
}
|
||||
|
||||
case 'trusted':
|
||||
default:
|
||||
return {
|
||||
title: 'Confirm Extension Installation',
|
||||
message: `Are you sure you want to install the ${name} extension?\n\nCommand: ${command || remoteUrl}`,
|
||||
confirmLabel: 'Yes',
|
||||
cancelLabel: 'No',
|
||||
showSingleButton: false,
|
||||
isBlocked: false,
|
||||
};
|
||||
}
|
||||
};
|
||||
|
||||
const handleExtensionRequest = useCallback(async (link: string): Promise<void> => {
|
||||
try {
|
||||
console.log(`Processing extension request: ${link}`);
|
||||
|
||||
const command = extractCommand(link);
|
||||
const remoteUrl = extractRemoteUrl(link);
|
||||
const extName = extractExtensionName(link);
|
||||
|
||||
const extensionInfo: ExtensionInfo = {
|
||||
name: extName,
|
||||
command: command,
|
||||
remoteUrl: remoteUrl || undefined,
|
||||
link: link,
|
||||
};
|
||||
|
||||
const modalType = await determineModalType(command, remoteUrl);
|
||||
|
||||
setModalState({
|
||||
isOpen: true,
|
||||
modalType,
|
||||
extensionInfo,
|
||||
isPending: false,
|
||||
error: null,
|
||||
});
|
||||
|
||||
setPendingLink(modalType === 'blocked' ? null : link);
|
||||
|
||||
window.electron.logInfo(`Extension modal opened: ${modalType} for ${extName}`);
|
||||
} catch (error) {
|
||||
console.error('Error processing extension request:', error);
|
||||
setModalState((prev) => ({
|
||||
...prev,
|
||||
error: error instanceof Error ? error.message : 'Unknown error',
|
||||
}));
|
||||
}
|
||||
}, []);
|
||||
|
||||
const dismissModal = useCallback(() => {
|
||||
setModalState({
|
||||
isOpen: false,
|
||||
modalType: 'trusted',
|
||||
extensionInfo: null,
|
||||
isPending: false,
|
||||
error: null,
|
||||
});
|
||||
setPendingLink(null);
|
||||
}, []);
|
||||
|
||||
const confirmInstall = useCallback(async (): Promise<void> => {
|
||||
if (!pendingLink) {
|
||||
return;
|
||||
}
|
||||
|
||||
setModalState((prev) => ({ ...prev, isPending: true }));
|
||||
|
||||
try {
|
||||
console.log(`Confirming installation of extension from: ${pendingLink}`);
|
||||
|
||||
if (addExtension) {
|
||||
await addExtensionFromDeepLink(pendingLink, addExtension, () => {
|
||||
console.log('Extension installation completed, navigating to extensions');
|
||||
});
|
||||
} else {
|
||||
throw new Error('addExtension function not provided to component');
|
||||
}
|
||||
|
||||
// Only dismiss modal after successful installation
|
||||
dismissModal();
|
||||
} catch (error) {
|
||||
const errorMessage = error instanceof Error ? error.message : 'Installation failed';
|
||||
console.error('Extension installation failed:', error);
|
||||
|
||||
setModalState((prev) => ({
|
||||
...prev,
|
||||
error: errorMessage,
|
||||
isPending: false,
|
||||
}));
|
||||
}
|
||||
}, [pendingLink, dismissModal, addExtension]);
|
||||
|
||||
useEffect(() => {
|
||||
console.log('Setting up extension install modal handler');
|
||||
|
||||
const handleAddExtension = async (_event: IpcRendererEvent, ...args: unknown[]) => {
|
||||
const link = args[0] as string;
|
||||
await handleExtensionRequest(link);
|
||||
};
|
||||
|
||||
window.electron.on('add-extension', handleAddExtension);
|
||||
|
||||
return () => {
|
||||
window.electron.off('add-extension', handleAddExtension);
|
||||
};
|
||||
}, [handleExtensionRequest]);
|
||||
|
||||
const getModalConfig = (): ExtensionModalConfig | null => {
|
||||
if (!modalState.extensionInfo) return null;
|
||||
return generateModalConfig(modalState.modalType, modalState.extensionInfo);
|
||||
};
|
||||
|
||||
const config = getModalConfig();
|
||||
if (!config) return null;
|
||||
|
||||
const getConfirmButtonVariant = () => {
|
||||
switch (modalState.modalType) {
|
||||
case 'blocked':
|
||||
return 'outline';
|
||||
case 'untrusted':
|
||||
return 'destructive';
|
||||
case 'trusted':
|
||||
default:
|
||||
return 'default';
|
||||
}
|
||||
};
|
||||
|
||||
const getTitleClassName = () => {
|
||||
switch (modalState.modalType) {
|
||||
case 'blocked':
|
||||
return 'text-red-600 dark:text-red-400';
|
||||
case 'untrusted':
|
||||
return 'text-yellow-600 dark:text-yellow-400';
|
||||
case 'trusted':
|
||||
default:
|
||||
return '';
|
||||
}
|
||||
};
|
||||
|
||||
return (
|
||||
<Dialog open={modalState.isOpen} onOpenChange={(open) => !open && dismissModal()}>
|
||||
<DialogContent className="sm:max-w-[500px]">
|
||||
<DialogHeader>
|
||||
<DialogTitle className={getTitleClassName()}>{config.title}</DialogTitle>
|
||||
<DialogDescription className="whitespace-pre-wrap text-left">
|
||||
{config.message}
|
||||
</DialogDescription>
|
||||
</DialogHeader>
|
||||
|
||||
<DialogFooter className="pt-4">
|
||||
{config.showSingleButton ? (
|
||||
<Button
|
||||
onClick={dismissModal}
|
||||
disabled={modalState.isPending}
|
||||
variant={getConfirmButtonVariant()}
|
||||
>
|
||||
{config.confirmLabel}
|
||||
</Button>
|
||||
) : (
|
||||
<>
|
||||
<Button variant="outline" onClick={dismissModal} disabled={modalState.isPending}>
|
||||
{config.cancelLabel}
|
||||
</Button>
|
||||
<Button
|
||||
onClick={confirmInstall}
|
||||
disabled={modalState.isPending}
|
||||
variant={getConfirmButtonVariant()}
|
||||
>
|
||||
{modalState.isPending ? 'Installing...' : config.confirmLabel}
|
||||
</Button>
|
||||
</>
|
||||
)}
|
||||
</DialogFooter>
|
||||
</DialogContent>
|
||||
</Dialog>
|
||||
);
|
||||
}
|
||||
@@ -1,88 +0,0 @@
|
||||
import {
|
||||
Dialog,
|
||||
DialogContent,
|
||||
DialogDescription,
|
||||
DialogFooter,
|
||||
DialogHeader,
|
||||
DialogTitle,
|
||||
} from '../ui/dialog';
|
||||
import { Button } from '../ui/button';
|
||||
import { ModalType, ExtensionModalConfig } from '../../types/extension';
|
||||
|
||||
interface ExtensionInstallModalProps {
|
||||
isOpen: boolean;
|
||||
modalType: ModalType;
|
||||
config: ExtensionModalConfig | null;
|
||||
onConfirm: () => void;
|
||||
onCancel: () => void;
|
||||
isSubmitting?: boolean;
|
||||
}
|
||||
|
||||
export function ExtensionInstallModal({
|
||||
isOpen,
|
||||
modalType,
|
||||
config,
|
||||
onConfirm,
|
||||
onCancel,
|
||||
isSubmitting = false,
|
||||
}: ExtensionInstallModalProps) {
|
||||
if (!config) return null;
|
||||
|
||||
const getConfirmButtonVariant = () => {
|
||||
switch (modalType) {
|
||||
case 'blocked':
|
||||
return 'outline';
|
||||
case 'untrusted':
|
||||
return 'destructive';
|
||||
case 'trusted':
|
||||
default:
|
||||
return 'default';
|
||||
}
|
||||
};
|
||||
|
||||
const getTitleClassName = () => {
|
||||
switch (modalType) {
|
||||
case 'blocked':
|
||||
return 'text-red-600 dark:text-red-400';
|
||||
case 'untrusted':
|
||||
return 'text-yellow-600 dark:text-yellow-400';
|
||||
case 'trusted':
|
||||
default:
|
||||
return '';
|
||||
}
|
||||
};
|
||||
|
||||
return (
|
||||
<Dialog open={isOpen} onOpenChange={(open) => !open && onCancel()}>
|
||||
<DialogContent className="sm:max-w-[500px]">
|
||||
<DialogHeader>
|
||||
<DialogTitle className={getTitleClassName()}>{config.title}</DialogTitle>
|
||||
<DialogDescription className="whitespace-pre-wrap text-left">
|
||||
{config.message}
|
||||
</DialogDescription>
|
||||
</DialogHeader>
|
||||
|
||||
<DialogFooter className="pt-4">
|
||||
{config.showSingleButton ? (
|
||||
<Button onClick={onCancel} disabled={isSubmitting} variant={getConfirmButtonVariant()}>
|
||||
{config.confirmLabel}
|
||||
</Button>
|
||||
) : (
|
||||
<>
|
||||
<Button variant="outline" onClick={onCancel} disabled={isSubmitting}>
|
||||
{config.cancelLabel}
|
||||
</Button>
|
||||
<Button
|
||||
onClick={onConfirm}
|
||||
disabled={isSubmitting}
|
||||
variant={getConfirmButtonVariant()}
|
||||
>
|
||||
{isSubmitting ? 'Installing...' : config.confirmLabel}
|
||||
</Button>
|
||||
</>
|
||||
)}
|
||||
</DialogFooter>
|
||||
</DialogContent>
|
||||
</Dialog>
|
||||
);
|
||||
}
|
||||
Reference in New Issue
Block a user