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。

52.1 KB
Raw Blame
/**
 * Regression coverage for Plugin detail sections, optional Host task settings and interaction behavior.
 * [PROTOCOL]: 变更时更新此头部,然后检查 CLAUDE.md
 * @vitest-environment jsdom
 */

import { fireEvent, render, screen, waitFor, within } from '@testing-library/react';
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
import type { ReactNode } from 'react';
import path from 'node:path';
import type { InstalledGhost } from '../../../../shared/ghost';
import type { PreparedPluginContribution } from '../../../../shared/pluginContributions';

const toastMocks = vi.hoisted(() => ({ success: vi.fn(), error: vi.fn() }));

vi.mock('@/hooks/useModelPricing', () => ({
  useGatewayModelPricing: () => null,
  useReferenceModelPricing: () => null,
}));
vi.mock('@/hooks/useProviders', () => ({
  useProviders: () => ({ providers: [], providerOrder: [], loading: false }),
}));
vi.mock('@/hooks/useDeviceProviders', () => ({
  useDeviceProviders: () => ({ providers: [], loading: false, unsupported: false }),
}));
vi.mock('@/hooks/useAgentCapabilities', async (importOriginal) => ({
  ...(await importOriginal<typeof import('@/hooks/useAgentCapabilities')>()),
  useAgentCapabilities: () => ({ capabilities: null, loading: false }),
}));
vi.mock('@/hooks/useApiKey', () => ({ useApiKey: () => ({ hasSavedKey: true }) }));
vi.mock('@/hooks/useConnectedSource', () => ({
  useConnectedSource: () => ({ hasConnectedSource: true, loading: false }),
}));

vi.mock('@/lib/toast', () => ({ toast: toastMocks }));
vi.mock('@/cindy-brain/GhostSettingsWebview', () => ({
  GhostSettingsWebview: ({ account, reloadKey }: { account?: ReactNode; reloadKey?: number }) => (
    <>
      {account}
      <div key={reloadKey} data-testid="ghost-settings-webview" />
    </>
  ),
}));

// The shared-quota rail observes auth; this component fixture has no auth host.
vi.mock('@/contexts/AuthContext', () => ({ useOptionalAuthUser: () => null }));

vi.mock('react-i18next', () => ({
  useTranslation: () => ({
    t: (key: string, options?: Record<string, unknown>) => {
      const labels: Record<string, string> = {
        'settings.ghosts.detail.openTool': `Open ${String(options?.name ?? '')}`,
        'settings.ghosts.detail.toolsTitle': 'Tools',
        'settings.ghosts.detail.viewAllTools': 'See All',
        'settings.ghosts.detail.collapseTools': 'Show Less',
        'settings.ghosts.detail.noToolDescription': 'No description',
        'settings.ghosts.detail.permissionsTitle': 'Permissions',
        'settings.ghosts.detail.viewAllPermissions': 'See All',
        'settings.ghosts.detail.permissionsDialogDescription': `${String(options?.count ?? '')} permissions`,
        'settings.ghosts.detail.closeDialog': 'Close dialog',
        'settings.ghosts.perm.networkHost': `Access ${String(options?.host ?? '')}`,
        'settings.ghosts.perm.networkHostDetail': 'Can access this declared domain.',
        'settings.ghosts.perm.cindyTextOneshotModelDetail': `Takes effect when the model (${String(options?.model ?? '')}) is available in the catalog.`,
        'settings.ghosts.perm.command': `Command ${String(options?.command ?? '')}`,
        'settings.ghosts.perm.tool': `Tool ${String(options?.name ?? '')}`,
        'settings.ghosts.perm.cindyImageGenerate': 'Generate images',
        'settings.ghosts.perm.cindyTextOneshot': 'Quick Q&A',
        'settings.ghosts.detail.infoTitle': 'Details',
        'settings.ghosts.detail.byAuthor': `By ${String(options?.author ?? '')}`,
        'settings.ghosts.detail.infoVersion': 'Version',
        'settings.ghosts.detail.infoAuthor': 'Author',
        'settings.ghosts.detail.infoId': 'Identifier',
        'settings.ghosts.detail.infoContents': 'Contents',
        'settings.ghosts.contents.code': 'Executable Code',
        'settings.ghosts.detail.infoPanel': 'Panel',
        'settings.ghosts.detail.infoLocation': 'Install Location',
        'settings.ghosts.detail.copyLocation': 'Copy Install Location',
        'settings.ghosts.detail.locationCopied': 'Install location copied',
        'settings.ghosts.detail.locationCopyFailed': 'Could not copy install location',
        'settings.ghosts.detail.openLocation': 'Open Install Location',
        'settings.ghosts.detail.expandInfoValue': `Show full ${String(options?.label ?? '')}`,
        'settings.ghosts.detail.collapseInfoValue': `Collapse ${String(options?.label ?? '')}`,
        'settings.ghosts.detail.panelDismissed': 'Not docked',
        'settings.providers.openai.title': 'OpenAI',
        'settings.providers.xd.title': 'Cindy AI',
        'settings.defaults.restore': 'Restore default',
        'settings.ghosts.detail.oauthScopeStale':
          'This authorization does not include newly added permissions. Reconnect to enable them.',
      };
      return labels[key] ?? (options?.value !== undefined ? `${options.value} ${key}` : key);
    },
    i18n: { language: 'en' },
  }),
}));

import type { GhostPermissionItem } from '../../../../shared/ghost';
import {
  DetailsSection,
  GhostPluginDetailView,
  GhostPluginMetadata,
  PermissionSummary,
  ToolDescriptionChip,
  ToolsSection,
} from '../GhostPluginDetailView';
import { toGhostPluginDetail, type GhostPluginDetail } from '../lib/ghostPluginViewModel';
import { RemotePluginReadOnlyDetail } from '../RemotePluginReadOnlyDetail';

const permissions: GhostPermissionItem[] = [
  {
    key: 'network:api.example.com',
    kind: 'network',
    labelKey: 'networkHost',
    labelArgs: { host: 'api.example.com' },
    detailKey: 'networkHostDetail',
  },
  {
    key: 'command:render',
    kind: 'command',
    labelKey: 'command',
    labelArgs: { command: 'render' },
  },
  {
    key: 'tool:render',
    kind: 'tool',
    labelKey: 'tool',
    labelArgs: { name: 'render' },
    detail: 'Render an image.',
  },
  {
    key: 'cindy:image.generate',
    kind: 'cindy',
    labelKey: 'cindyImageGenerate',
  },
  {
    key: 'cindy:text.oneshot',
    kind: 'cindy',
    labelKey: 'cindyTextOneshot',
    detailKey: 'cindyTextOneshotModelDetail',
    detailArgs: { model: 'codex/gpt-5.5' },
  },
];

const detail: GhostPluginDetail = {
  id: 'builtin.example',
  ghostId: 'builtin.example',
  name: 'Example',
  description: 'Example plugin',
  version: '1.2.3',
  enabled: true,
  canUse: true,
  approvalState: 'approved',
  builtin: false,
  tabPanel: false,
  hasMainView: false,
  mainViewTitle: null,
  author: 'XD',
  contents: ['code'],
  permissions: [],
  tools: [],
  hasSettingsUi: false,
  hasTaskPreferences: false,
  hasPluginTasks: false,
  panelMinWidth: 320,
  installDir: '/tmp/cindy-brain/builtin.example',
  trust: {
    level: 'cindy-official',
    publisherSigned: true,
    publisherVerified: true,
    reviewed: true,
    publisherName: 'Cindy',
  },
};

beforeEach(() => {
  Object.defineProperty(window, 'electronAPI', {
    configurable: true,
    value: {

    },
  });
});

afterEach(() => {
  vi.restoreAllMocks();
  vi.unstubAllGlobals();
  toastMocks.success.mockReset();
  toastMocks.error.mockReset();
  Reflect.deleteProperty(window, 'electronAPI');
});

describe('Ghost plugin detail sections', () => {
  it('shows target shared counts without reading local personal usage for a remote installation', () => {
    vi.stubGlobal(
      'ResizeObserver',
      class {
        observe() {}
        disconnect() {}
      },
    );
    const usageSummary = vi.fn();
    Object.assign(window.electronAPI, { ghosts: { usageSummary } });
    render(
      <GhostPluginDetailView
        remote
        ghost={{ manifest: { id: detail.ghostId }, enabled: true } as InstalledGhost}
        detail={detail}
        marketItem={
          {
            sourceType: 'server',
            scope: 'organization',
            downloadStatistics: { requestCount: '1284' },
          } as import('../../../../shared/pluginMarket').PluginMarketItem
        }
        panelStatus={null}
        onBack={vi.fn()}
        onToggle={vi.fn()}
        onUse={vi.fn()}
        onUpdate={vi.fn()}
        onUpdateFromFile={vi.fn()}
        onUninstall={vi.fn()}
        toggleDisabled={false}
      />,
    );
    expect(screen.getByText('1,284 settings.ghosts.usage.downloadsValue')).toBeTruthy();
    expect(screen.queryByText('settings.ghosts.usage.title')).toBeNull();
    expect(usageSummary).not.toHaveBeenCalled();
  });

  it('keeps unknown older-Host details honest and renders no local configuration or file actions', () => {
    vi.stubGlobal('ResizeObserver', class { observe() {} disconnect() {} });
    const { container } = render(<RemotePluginReadOnlyDetail
      detail={{ id: '_ns__team__notes', name: 'Team notes', description: 'Installed on A' }}
      notice={<p>Read only on A</p>} loading={false} failed={false} online
      onBack={vi.fn()} onRetry={vi.fn()}
    />);
    expect(screen.getByRole('heading', { name: 'Team notes' })).toBeTruthy();
    expect(screen.getByText('_ns__team__notes')).toBeTruthy();
    expect(screen.getByText('settings.ghosts.remote.detailUnavailable')).toBeTruthy();
    expect(screen.queryByRole('switch')).toBeNull();
    expect(screen.queryByText('settings.ghosts.detail.configurationTitle')).toBeNull();
    expect(screen.queryByLabelText('Open Install Location')).toBeNull();
    expect(container.textContent).not.toMatch(/undefined|unverified|已停用|Disabled/);
  });
  it('renders Host permission descriptions through the existing permission dialog and disables retry offline', async () => {
    vi.stubGlobal('ResizeObserver', class { observe() {} disconnect() {} });
    render(<RemotePluginReadOnlyDetail
      detail={{ id: 'notes', name: 'Notes', description: '', permissions: [{ title: 'Read service', description: 'Only the declared service' }] }}
      notice={<p>Offline</p>} loading={false} failed online={false}
      onBack={vi.fn()} onRetry={vi.fn()}
    />);
    expect((screen.getByRole('button', { name: 'settings.ghosts.remote.refreshDetail' }) as HTMLButtonElement).disabled).toBe(true);
    fireEvent.click(screen.getByRole('button', { name: 'Permissions: Read service' }));
    expect(within(await screen.findByRole('dialog')).getByText('Only the declared service')).toBeTruthy();
  });
  it('keeps installed use details focused on the plugin without a version and publishing section', () => {
    vi.stubGlobal('ResizeObserver', class { observe() {} disconnect() {} });
    render(<GhostPluginDetailView ghost={null} detail={{ ...detail, releaseNotes: 'Only version changes', tools: [{ name: 'example', description: 'Example tool' }] }} panelStatus={null}
      onBack={vi.fn()} onToggle={vi.fn()} onUse={vi.fn()} onUpdate={vi.fn()} onUpdateFromFile={vi.fn()}
      onUninstall={vi.fn()} toggleDisabled={false} />);
    expect(screen.getByText(detail.description)).toBeTruthy();
    expect(screen.getByRole('heading', { name: 'Tools' })).toBeTruthy();
    expect(screen.queryByText('settings.ghosts.contribution.versionUpdates')).toBeNull();
    expect(screen.queryByText('Only version changes')).toBeNull();
  });


  it.each(['pending', 'approved', 'rejected', 'cancelled'] as const)(
    'hides a submission that cannot be repeated for the %s version without showing publishing details', (status) => {
      vi.stubGlobal('ResizeObserver', class { observe() {} disconnect() {} });
      const publish = vi.fn();
      const preview: PreparedPluginContribution = {
        preparedId: 'preview', instanceId: 'instance', pluginId: 'plugin', ghostId: 'example',
        name: detail.name, description: detail.description, version: '1.0.0', sha256: 'a'.repeat(64),
        sizeBytes: 100, releaseNotes: 'Complete package release notes', expiresAt: '2026-10-16T00:00:00.000Z',
        preflight: {
          subject: { authority: 'https://auth.example', membershipId: 'member' },
          queriedAt: '2026-10-16T00:00:00.000Z', policyVersion: 2,
          target: { pluginId: 'plugin', ghostId: 'example', version: '1.0.0', expectedRelease: null },
          pendingRelease: status === 'pending' ? { releaseId: 'release', version: '1.0.0' } : null,
          blockers: [{ code: 'VERSION_ALREADY_SUBMITTED', message: 'Change the version before publishing again' }],
          actions: { canSubmit: false },
        },
      };
      const view = (prepared: PreparedPluginContribution) => <GhostPluginDetailView
        ghost={null} detail={detail} panelStatus={null} onBack={vi.fn()} onToggle={vi.fn()} onUse={vi.fn()}
        onUpdate={vi.fn()} onUpdateFromFile={vi.fn()} onUninstall={vi.fn()} toggleDisabled={false}
        onContribute={publish} publishingPreview={prepared}
        contributionUnavailableReason={prepared.preflight?.actions.canSubmit ? undefined : 'Change the version before publishing again'} />;
      const { rerender } = render(view(preview));
      expect(screen.queryByRole('button', { name: 'settings.ghosts.contribution.publishPlugin' })).toBeNull();
      expect(screen.queryByText('settings.ghosts.contribution.versionUpdates')).toBeNull();
      expect(screen.queryByText('Change the version before publishing again')).toBeNull();
      expect(screen.queryByText('settings.ghosts.contribution.versionConsumedHint')).toBeNull();
      expect(screen.queryByText('Complete package release notes')).toBeNull();
      expect(publish).not.toHaveBeenCalled();
      // A previous cancelled/rejected/approved result does not hide a new eligible version.
      rerender(view({ ...preview, version: '1.1.0', preflight: { ...preview.preflight!, target: { ...preview.preflight!.target, version: '1.1.0' }, pendingRelease: null, blockers: [], actions: { canSubmit: true } } }));
      const submit = screen.getByRole('button', { name: 'settings.ghosts.contribution.publishPlugin' });
      expect(submit).toHaveProperty('disabled', false);
      fireEvent.click(submit);
      expect(publish).toHaveBeenCalledOnce();
    },
  );

  it('keeps the local publishing entry in the use header without a publishing section', () => {
    vi.stubGlobal('ResizeObserver', class { observe() {} disconnect() {} });
    const publish = vi.fn();
    render(<GhostPluginDetailView ghost={null} detail={detail} panelStatus={null}
      onBack={vi.fn()} onToggle={vi.fn()} onUse={vi.fn()} onUpdate={vi.fn()}
      onUpdateFromFile={vi.fn()} onUninstall={vi.fn()} toggleDisabled={false}
      onContribute={publish} />);
    expect(screen.queryByText('settings.ghosts.contribution.versionUpdates')).toBeNull();
    expect(screen.getByRole('button', { name: 'settings.ghosts.contribution.publishPlugin' }).closest('header')).toBeTruthy();
    const chat = screen.getByRole('button', { name: 'settings.ghosts.detail.chatAction' });
    expect(within(chat.closest('.plugin-detail-actions') as HTMLElement).getByRole('switch')).toBeTruthy();
    expect(screen.getByText('Example plugin')).toBeTruthy();
    const action = screen.getByRole('button', { name: 'settings.ghosts.contribution.publishPlugin' });
    fireEvent.click(action);
    expect(publish).toHaveBeenCalledOnce();
  });

  it('does not advertise host login for a locally imported unverified GitHub plugin', () => {
    vi.stubGlobal(
      'ResizeObserver',
      class {
        observe() {}
        unobserve() {}
        disconnect() {}
      },
    );
    const verify = vi.fn();
    Object.assign(window.electronAPI, { gitContext: { githubConnection: verify } });
    render(
      <GhostPluginDetailView
        ghost={
          { manifest: { id: 'cindy-github' }, enabled: true, trust: { level: 'unverified' } } as InstalledGhost
        }
        detail={{ ...detail, id: 'cindy-github', ghostId: 'cindy-github', hasSettingsUi: true }}
        panelStatus={null}
        onBack={vi.fn()}
        onToggle={vi.fn()}
        onUse={vi.fn()}
        onUpdate={vi.fn()}
        onUpdateFromFile={vi.fn()}
        onUninstall={vi.fn()}
        toggleDisabled={false}
      />,
    );
    expect(verify).not.toHaveBeenCalled();
  });
  it.each([
    { layout: 'legacy', connection: { status: 'missing' } },
    { layout: 'root', connection: { status: 'auth', source: 'token' } },
  ])(
    'connects GitHub in $layout layout and reloads settings after authorization',
    async ({ layout, connection }) => {
      vi.stubGlobal(
        'ResizeObserver',
        class {
          observe() {}
          unobserve() {}
          disconnect() {}
        },
      );
      Object.assign(window.electronAPI, {
        gitContext: {
          githubConnection: async () => connection,
          onGithubConnected: () => () => {},
          githubSetupStatus: async () => ({ phase: 'connected' }),
          startGithubSetup: async () => ({ phase: 'connected' }),
        },
      });
      const ghost: InstalledGhost = {
        manifest: { schemaVersion: 3, minCindyVersion: '0.1.0', kind: 'chip',
          id: 'cindy-github', name: 'GitHub', version: '1.0.0', entry: 'main.js', settingsHtml: 'settings.html' },
        dir: path.join('plugins', ...(layout === 'root' ? ['_ns', '_root'] : []), 'cindy-github'),
        namespace: null,
        enabled: true,
        approval: { state: 'approved', revision: '00000000-0000-4000-8000-000000000001' },
        trust: { ...detail.trust, publisherName: 'Cindy Plugin Market' },
      };
      const { unmount } = render(
        <GhostPluginDetailView
          ghost={ghost}
          detail={toGhostPluginDetail(ghost)}
          panelStatus={null}
          onBack={vi.fn()}
          onToggle={vi.fn()}
          onUse={vi.fn()}
          onUpdate={vi.fn()}
          onUpdateFromFile={vi.fn()}
          onUninstall={vi.fn()}
          toggleDisabled={false}
        />,
      );
      const previousSettings = screen.getByTestId('ghost-settings-webview');
      fireEvent.click(await screen.findByText('ccAgent.gitContext.pr.setup.stages.login.title'));
      fireEvent.click(await screen.findByText('ccAgent.gitContext.pr.setup.connect'));
      await waitFor(() =>
        expect(screen.getByTestId('ghost-settings-webview')).not.toBe(previousSettings),
      );
      expect(screen.getByText('ccAgent.gitContext.pr.setup.done')).toBeTruthy();
      unmount();
    },
  );
  it('places Background Tasks after settings and before Tools for plugins declaring hiddenTasks', async () => {
    vi.stubGlobal('ResizeObserver', class { observe() {} unobserve() {} disconnect() {} });
    const listBackgroundTasks = vi.fn(async () => ({ items: [
      { taskId: 'bg-1', title: 'Hidden grading', status: 'active' as const, updatedAt: Date.now(), running: false },
    ] }));
    Object.assign(window.electronAPI, { ghosts: { listBackgroundTasks, revealBackgroundTask: vi.fn() } });
    const ghost = { manifest: { agent: { tasks: true, hiddenTasks: true } }, enabled: true, taskCapabilityApproved: true } as InstalledGhost;
    render(<GhostPluginDetailView ghost={ghost} detail={{ ...detail, tools: [{ name: 'render', description: 'Render.' }] }} panelStatus="Docked" onBack={vi.fn()} onToggle={vi.fn()} onUse={vi.fn()} onUpdate={vi.fn()} onUpdateFromFile={vi.fn()} onUninstall={vi.fn()} toggleDisabled={false} />);
    expect(await screen.findByText('Hidden grading')).toBeTruthy();
    expect(listBackgroundTasks).toHaveBeenCalledWith(detail.id);
    const heading = screen.getByRole('heading', { name: 'settings.ghosts.backgroundTasks.title' });
    const tools = screen.getByRole('heading', { name: 'Tools' });
    expect(heading.compareDocumentPosition(tools) & Node.DOCUMENT_POSITION_FOLLOWING).toBeTruthy();
    // Outside a router the open action is omitted; showing in the task list stays available.
    expect(screen.queryByRole('button', { name: 'settings.ghosts.backgroundTasks.open' })).toBeNull();
    expect(screen.getByRole('button', { name: 'settings.ghosts.backgroundTasks.reveal' })).toBeTruthy();
  });
  it('lets the user retry task permission, disables duplicate clicks, and hides after approval', async () => {
    vi.stubGlobal('ResizeObserver', class { observe() {} unobserve() {} disconnect() {} });
    let finish!: (value: { granted: boolean }) => void;
    const requestTaskApproval = vi.fn(() => new Promise<{ granted: boolean }>(resolve => { finish = resolve; }));
    Object.assign(window.electronAPI, { ghosts: { requestTaskApproval } });
    const ghost = { manifest: { agent: { tasks: true } }, enabled: true } as InstalledGhost;
    const view = (approved = false) => <GhostPluginDetailView ghost={{ ...ghost, ...(approved ? { taskCapabilityApproved: true as const } : {}) }} detail={detail} panelStatus="Docked" onBack={vi.fn()} onToggle={vi.fn()} onUse={vi.fn()} onUpdate={vi.fn()} onUpdateFromFile={vi.fn()} onUninstall={vi.fn()} toggleDisabled={false} />;
    const { rerender } = render(view());
    const button = screen.getByRole('button', { name: 'settings.ghosts.perm.agentTasksRequest' }) as HTMLButtonElement;
    fireEvent.click(button); fireEvent.click(button);
    expect(requestTaskApproval).toHaveBeenCalledOnce();
    expect(requestTaskApproval).toHaveBeenCalledWith(detail.id);
    expect(button.disabled).toBe(true);
    finish({ granted: false });
    await waitFor(() => expect(button.disabled).toBe(false));
    rerender(view(true));
    expect(screen.queryByRole('button', { name: 'settings.ghosts.perm.agentTasksRequest' })).toBeNull();
  });
  it('uses the shared Cindy Switch for the plugin enabled control', () => {
    vi.stubGlobal(
      'ResizeObserver',
      class {
        observe() {}
        unobserve() {}
        disconnect() {}
      },
    );
    const onToggle = vi.fn();
    const view = (disabled = false) => (
      <GhostPluginDetailView
        ghost={null}
        detail={detail}
        panelStatus="Docked"
        onBack={vi.fn()}
        onToggle={onToggle}
        onUse={vi.fn()}
        onUpdate={vi.fn()}
        onUpdateFromFile={vi.fn()}
        onUninstall={vi.fn()}
        toggleDisabled={disabled}
      />
    );
    const { rerender } = render(view());

    const toggle = screen.getByRole('switch', {
      name: 'settings.ghosts.enableAria',
    });
    expect(toggle.className).toContain('cindy-switch');
    expect(toggle.className).toContain('data-[state=checked]:bg-[var(--switch-track-on)]');
    expect(toggle.firstElementChild?.className).toContain(
      'data-[state=checked]:bg-[var(--switch-thumb-on)]',
    );
    fireEvent.click(toggle);
    expect(onToggle.mock.calls).toEqual([[false]]);
    fireEvent.click(screen.getByText('settings.ghosts.detail.enabledLabel'));
    expect(onToggle.mock.calls).toEqual([[false], [false]]);
    rerender(view(true));
    fireEvent.click(toggle);
    fireEvent.click(screen.getByText('settings.ghosts.detail.enabledLabel'));
    expect(onToggle).toHaveBeenCalledTimes(2);
  });

  it('renders a remote disabled notice without a configuration heading or local settings', () => {
    vi.stubGlobal('ResizeObserver', class { observe() {} unobserve() {} disconnect() {} });
    render(
      <GhostPluginDetailView
        remote
        remoteConfiguration={<p>Enable this plugin before configuring.</p>}
        ghost={null}
        detail={{ ...detail, enabled: false, hasSettingsUi: true }}
        panelStatus={null}
        onBack={vi.fn()}
        onToggle={vi.fn()}
        onUse={vi.fn()}
        onUpdate={vi.fn()}
        onUpdateFromFile={vi.fn()}
        onUninstall={vi.fn()}
        toggleDisabled={false}
      />,
    );

    expect(screen.getByText('Enable this plugin before configuring.')).toBeTruthy();
    expect(screen.queryByRole('heading', { name: 'settings.ghosts.detail.configurationTitle' })).toBeNull();
    expect(screen.queryByTestId('ghost-settings-webview')).toBeNull();
  });

  it('shows the main-view preference alongside the plugin settings UI', () => {
    vi.stubGlobal(
      'ResizeObserver',
      class {
        observe() {}
        unobserve() {}
        disconnect() {}
      },
    );
    const onVisibilityChange = vi.fn();
    render(
      <GhostPluginDetailView
        ghost={{
          manifest: {
            schemaVersion: 2,
            id: detail.id,
            name: detail.name,
            version: detail.version,
            kind: 'chip',
            entry: 'main.js',
            minCindyVersion: '1.2.3',
            slots: ['main-view'],
            settingsHtml: 'settings.html',
            mainView: { html: 'main-view.html', title: 'Workspace' },
          },
          dir: detail.installDir ?? '/tmp/plugin',
          enabled: true,
          approval: { state: 'approved', revision: 'rev-1' },
        }}
        detail={{
          ...detail,
          hasMainView: true,
          mainViewTitle: 'Workspace',
          hasSettingsUi: true,
        }}
        panelStatus={null}
        mainViewSidebarVisible
        onMainViewSidebarVisibleChange={onVisibilityChange}
        onBack={vi.fn()}
        onToggle={vi.fn()}
        onUse={vi.fn()}
        onUpdate={vi.fn()}
        onUpdateFromFile={vi.fn()}
        onUninstall={vi.fn()}
        toggleDisabled={false}
      />,
    );

    const toggle = screen.getByRole('switch', {
      name: 'settings.ghosts.detail.showInSidebar',
    });
    expect(toggle.getAttribute('data-state')).toBe('checked');
    fireEvent.click(toggle);
    expect(onVisibilityChange).toHaveBeenCalledWith(false);
    expect(screen.getByText('settings.ghosts.detail.sidebarEntryTitle')).toBeTruthy();
    expect(screen.getByTestId('ghost-settings-webview')).toBeTruthy();
  });

  it('keeps the existing command action when the plugin also declares main-view', () => {
    vi.stubGlobal(
      'ResizeObserver',
      class {
        observe() {}
        unobserve() {}
        disconnect() {}
      },
    );
    const onUse = vi.fn();
    render(
      <GhostPluginDetailView
        ghost={null}
        detail={{ ...detail, hasMainView: true, mainViewTitle: 'Workspace' }}
        panelStatus={null}
        onBack={vi.fn()}
        onToggle={vi.fn()}
        onUse={onUse}
        onUpdate={vi.fn()}
        onUpdateFromFile={vi.fn()}
        onUninstall={vi.fn()}
        toggleDisabled={false}
      />,
    );

    const chat = screen.getByRole('button', { name: 'settings.ghosts.detail.chatAction' });
    expect((chat as HTMLButtonElement).disabled).toBe(false);
    expect(screen.queryByRole('button', { name: 'settings.ghosts.detail.openAction' })).toBeNull();
    fireEvent.click(chat);
    expect(onUse).toHaveBeenCalledTimes(1);
  });

  it('shows a non-blocking stale OAuth scope badge inside the configuration section', () => {
    vi.stubGlobal(
      'ResizeObserver',
      class {
        observe() {}
        unobserve() {}
        disconnect() {}
      },
    );
    render(
      <GhostPluginDetailView
        ghost={{
          manifest: {
            schemaVersion: 2,
            id: detail.id,
            name: detail.name,
            version: detail.version,
            kind: 'chip',
            entry: 'main.js',
            settingsHtml: 'settings.html',
          },
          dir: detail.installDir ?? '/tmp/plugin',
          enabled: true,
          approval: { state: 'approved', revision: 'rev-1' },
          oauthScopeStale: { secretKey: 'account', missingScopeCount: 2 },
        }}
        detail={{ ...detail, hasSettingsUi: true }}
        panelStatus="Docked"
        onBack={vi.fn()}
        onToggle={vi.fn()}
        onUse={vi.fn()}
        onUpdate={vi.fn()}
        onUpdateFromFile={vi.fn()}
        onUninstall={vi.fn()}
        toggleDisabled={false}
      />,
    );

    const badge = screen.getByRole('status');
    expect(badge.textContent).toContain('newly added permissions');
    expect(badge.className).toContain('bg-[var(--warning-bg-soft)]');
    expect(screen.getByTestId('ghost-settings-webview')).toBeTruthy();
  });

  it('keeps the detail surface on one centered content grid', () => {
    vi.stubGlobal(
      'ResizeObserver',
      class {
        observe() {}
        unobserve() {}
        disconnect() {}
      },
    );

    const { container } = render(
      <GhostPluginDetailView
        ghost={null}
        detail={detail}
        panelStatus="Docked"
        onBack={vi.fn()}
        onToggle={vi.fn()}
        onUse={vi.fn()}
        onUpdate={vi.fn()}
        onReapprove={vi.fn()}
        onUpdateFromFile={vi.fn()}
        onUninstall={vi.fn()}
        toggleDisabled={false}
      />,
    );

    const scrollSurface = container.querySelector('main');
    const detailFrame = container.querySelector('article');
    // 返回按钮住在吸顶顶栏里(mac 的窗口拖拽区)。顶栏内层复用同一条 824px
    // 内容框,与正文左缘对齐。
    const topBar = container.querySelector('[data-testid="plugin-detail-top-bar"]');
    const topBarFrame = topBar?.querySelector(':scope > div');
    const backButton = topBar?.querySelector('button');
    const detailHero = detailFrame?.querySelector('.plugin-detail-hero');
    const detailActions = detailFrame?.querySelector('.plugin-detail-actions');
    expect(scrollSurface?.className).toContain('[scrollbar-gutter:stable_both-edges]');
    expect(detailFrame?.className).toContain('plugin-detail-frame');
    expect(detailFrame?.className).toContain('mx-auto');
    expect(detailFrame?.className).toContain('max-w-[824px]');
    expect(topBar?.className).toContain('sticky');
    expect(topBarFrame?.className).toContain('mx-auto');
    expect(topBarFrame?.className).toContain('max-w-[824px]');
    expect(backButton?.className).toContain('-ml-3');
    expect(detailHero?.className).toContain('grid-cols-[64px_minmax(0,1fr)_auto]');
    expect(detailActions?.className).toContain('flex-wrap');
  });

  it('routes a projected detail icon failure to market recovery', () => {
    vi.stubGlobal(
      'ResizeObserver',
      class {
        observe() {}
        unobserve() {}
        disconnect() {}
      },
    );
    const onIconLoadError = vi.fn();
    const { container } = render(
      <GhostPluginDetailView
        ghost={null}
        detail={{
          ...detail,
          iconDataUrl: 'https://plugins.example.invalid/icon.png?signature=current',
        }}
        panelStatus="Docked"
        onBack={vi.fn()}
        onToggle={vi.fn()}
        onUse={vi.fn()}
        onUpdate={vi.fn()}
        onReapprove={vi.fn()}
        onUpdateFromFile={vi.fn()}
        onUninstall={vi.fn()}
        toggleDisabled={false}
        onIconLoadError={onIconLoadError}
      />,
    );

    fireEvent.error(container.querySelector('img') as HTMLImageElement);

    expect(onIconLoadError).toHaveBeenCalledTimes(1);
  });

  it('keeps the market replacement action for a same-version legacy install', () => {
    vi.stubGlobal(
      'ResizeObserver',
      class {
        observe() {}
        unobserve() {}
        disconnect() {}
      },
    );
    const onUpdate = vi.fn();
    render(
      <GhostPluginDetailView
        ghost={null}
        detail={detail}
        panelStatus="Docked"
        onBack={vi.fn()}
        onToggle={vi.fn()}
        onUse={vi.fn()}
        onUpdate={onUpdate}
        onReapprove={vi.fn()}
        onUpdateFromFile={vi.fn()}
        updateVersion={detail.version}
        onUninstall={vi.fn()}
        toggleDisabled={false}
      />,
    );

    const updateButton = screen.getByRole('button', {
      name: 'settings.ghosts.market.update',
    });
    fireEvent.click(updateButton);

    expect(onUpdate).toHaveBeenCalledTimes(1);
    expect(screen.queryByRole('button', { name: 'settings.ghosts.market.updateTo' })).toBeNull();
  });

  it.each([
    ['legacy-unapproved', 'settings.ghosts.reapproval.bodyLegacy'],
    ['invalid', 'settings.ghosts.reapproval.bodyInvalid'],
  ] as const)(
    'explains the %s approval state and routes to a fresh review',
    (approvalState, bodyKey) => {
      vi.stubGlobal(
        'ResizeObserver',
        class {
          observe() {}
          unobserve() {}
          disconnect() {}
        },
      );
      const onReapprove = vi.fn();
      const onUpdate = vi.fn();
      const onToggle = vi.fn();
      render(
        <GhostPluginDetailView
          ghost={null}
          detail={{ ...detail, approvalState }}
          panelStatus="Docked"
          onBack={vi.fn()}
          onToggle={onToggle}
          onUse={vi.fn()}
          onUpdate={onUpdate}
          onReapprove={onReapprove}
          onUpdateFromFile={vi.fn()}
          updateVersion="1.2.4"
          onUninstall={vi.fn()}
          toggleDisabled={false}
        />,
      );

      expect(screen.getByText('settings.ghosts.reapproval.noticeTitle')).toBeTruthy();
      expect(screen.getByText(bodyKey)).toBeTruthy();
      // 缺批准时"使用"与"更新"都不该顶在最前面,主动作是重新确认。
      expect(screen.queryByRole('button', { name: 'settings.ghosts.market.updateTo' })).toBeNull();
      // detail fixture 是指令型插件(canUse:true / tabPanel:false → 'command'),主动作按钮
      // 标 chatAction;缺批准时 primaryEnabled=false → 禁用。
      expect(
        (
          screen.getByRole('button', {
            name: 'settings.ghosts.detail.chatAction',
          }) as HTMLButtonElement
        ).disabled,
      ).toBe(true);

      // 共享 Switch 和关联文字标签遵循同一禁用门控。
      const toggle = screen.getByRole('switch', {
        name: 'settings.ghosts.enableAria',
      }) as HTMLButtonElement;
      expect(toggle.disabled).toBe(true);
      fireEvent.click(toggle);
      expect(onToggle).not.toHaveBeenCalled();

      fireEvent.click(screen.getByRole('button', { name: 'settings.ghosts.reapproval.action' }));
      expect(onReapprove).toHaveBeenCalledTimes(1);
      expect(onUpdate).not.toHaveBeenCalled();
    },
  );

  it('disables every market update entry while an update is busy', async () => {
    vi.stubGlobal(
      'ResizeObserver',
      class {
        observe() {}
        unobserve() {}
        disconnect() {}
      },
    );
    const onUpdate = vi.fn();

    render(
      <GhostPluginDetailView
        ghost={null}
        detail={detail}
        panelStatus="Docked"
        onBack={vi.fn()}
        onToggle={vi.fn()}
        onUse={vi.fn()}
        onUpdate={onUpdate}
        onReapprove={vi.fn()}
        onUpdateFromFile={vi.fn()}
        updateVersion="1.2.4"
        updateBusy
        onUninstall={vi.fn()}
        toggleDisabled={false}
      />,
    );

    expect(
      (
        screen.getByRole('button', {
          name: 'settings.ghosts.market.updateTo',
        }) as HTMLButtonElement
      ).disabled,
    ).toBe(true);
    fireEvent.pointerDown(
      screen.getByRole('button', { name: 'settings.ghosts.detail.moreActions' }),
      { button: 0, ctrlKey: false },
    );
    // ⋮ 菜单固定为「从文件更新」兜底路径(市场更新已提级到头部 CTA),
    // 更新进行中同样置灰。
    const menuUpdate = screen.getByRole('menuitem', {
      name: 'settings.ghosts.detail.updateFromFile',
    });
    expect(menuUpdate.getAttribute('aria-disabled')).toBe('true');
    fireEvent.click(menuUpdate);
    expect(onUpdate).not.toHaveBeenCalled();
  });

  it('hides the local .cindy update entry for reserved official ids outside dev builds', async () => {
    vi.stubGlobal(
      'ResizeObserver',
      class {
        observe() {}
        unobserve() {}
        disconnect() {}
      },
    );
    // vitest 默认 DEV=true,这里显式模拟打包产物(DEV=false)。
    vi.stubEnv('DEV', false);
    // 显式标注类型:JSX prop 位置的内联展开会让 tsc 现推一个巨大的匿名类型,
    // desktop 的 typecheck 本就贴着 CI 的 4GB 堆上限跑,能省则省。
    const officialDetail: GhostPluginDetail = { ...detail, id: 'cindy-art', ghostId: 'cindy-art' };
    render(
      <GhostPluginDetailView
        ghost={null}
        detail={officialDetail}
        panelStatus={null}
        onBack={vi.fn()}
        onToggle={vi.fn()}
        onUse={vi.fn()}
        onUpdate={vi.fn()}
        onUpdateFromFile={vi.fn()}
        onUninstall={vi.fn()}
        toggleDisabled={false}
      />,
    );

    fireEvent.pointerDown(
      screen.getByRole('button', { name: 'settings.ghosts.detail.moreActions' }),
      { button: 0, ctrlKey: false },
    );
    expect(
      screen.queryByRole('menuitem', { name: 'settings.ghosts.detail.updateFromFile' }),
    ).toBeNull();
    // 只剩卸载一项时不画悬空分割线。
    expect(screen.queryByRole('separator')).toBeNull();
    expect(screen.getByRole('menuitem', { name: 'settings.ghosts.uninstall' })).toBeTruthy();
    vi.unstubAllEnvs();
  });

  it.each(['builtin.example', 'xd-ordinary', 'filo-ordinary'])(
    'keeps the local .cindy update entry actionable for ordinary root %s',
    async (ghostId) => {
      vi.stubGlobal(
        'ResizeObserver',
        class {
          observe() {}
          unobserve() {}
          disconnect() {}
        },
      );
      vi.stubEnv('DEV', false);
      const onUpdateFromFile = vi.fn();
      const ordinaryDetail: GhostPluginDetail = { ...detail, id: ghostId, ghostId };
      render(
        <GhostPluginDetailView
          ghost={null}
          detail={ordinaryDetail}
          panelStatus={null}
          onBack={vi.fn()}
          onToggle={vi.fn()}
          onUse={vi.fn()}
          onUpdate={vi.fn()}
          onUpdateFromFile={onUpdateFromFile}
          onUninstall={vi.fn()}
          toggleDisabled={false}
        />,
      );

      fireEvent.pointerDown(
        screen.getByRole('button', { name: 'settings.ghosts.detail.moreActions' }),
        { button: 0, ctrlKey: false },
      );
      const updateItem = screen.getByRole('menuitem', {
        name: 'settings.ghosts.detail.updateFromFile',
      });
      expect(screen.getByRole('separator')).toBeTruthy();
      fireEvent.click(updateItem);
      expect(onUpdateFromFile).toHaveBeenCalledOnce();
      vi.unstubAllEnvs();
    },
  );

  it('renders an export menu item only when onExport is provided', async () => {
    vi.stubGlobal(
      'ResizeObserver',
      class {
        observe() {}
        unobserve() {}
        disconnect() {}
      },
    );
    const baseProps = {
      ghost: null,
      detail,
      panelStatus: 'Docked',
      onBack: vi.fn(),
      onToggle: vi.fn(),
      onUse: vi.fn(),
      onUpdate: vi.fn(),
      onUpdateFromFile: vi.fn(),
      onUninstall: vi.fn(),
      onReapprove: vi.fn(),
      toggleDisabled: false,
    };

    // 未提供 onExport(纯市场视图):菜单里不出现导出项。
    const { unmount } = render(<GhostPluginDetailView {...baseProps} />);
    fireEvent.pointerDown(
      screen.getByRole('button', { name: 'settings.ghosts.detail.moreActions' }),
      { button: 0, ctrlKey: false },
    );
    expect(
      screen.queryByRole('menuitem', { name: 'settings.ghosts.detail.exportPackage' }),
    ).toBeNull();
    unmount();

    // 提供 onExport(已装插件):点击触发导出回调。
    const onExport = vi.fn();
    render(<GhostPluginDetailView {...baseProps} onExport={onExport} />);
    fireEvent.pointerDown(
      screen.getByRole('button', { name: 'settings.ghosts.detail.moreActions' }),
      { button: 0, ctrlKey: false },
    );
    fireEvent.click(screen.getByRole('menuitem', { name: 'settings.ghosts.detail.exportPackage' }));
    expect(onExport).toHaveBeenCalledTimes(1);
  });

  it('uses one metadata color and orders author, then version', () => {
    const { container } = render(<GhostPluginMetadata author="Cindy" version="1.1.4" />);

    const metadata = container.firstElementChild as HTMLElement;
    expect(metadata.textContent).toBe('By Cindy·v1.1.4');
    expect(metadata.className).toContain('text-[var(--text-tertiary)]');
    expect(metadata.innerHTML).not.toContain('text-[var(--text-secondary)]');
    expect(screen.getByText('By Cindy').className).toContain('min-w-0');
    expect(screen.getByText('By Cindy').className).toContain('truncate');
  });

  it.each([
    { name: 'quick answers only', manifest: { cindy: { text: ['oneshot'] } }, taskRows: false, showCard: true },
    { name: 'plugin tasks', manifest: { agent: { tasks: true } }, taskRows: true, showCard: true },
    { name: 'legacy errands', manifest: { agent: { errand: true } }, taskRows: true, showCard: true },
    { name: 'workspaces', manifest: { workspace: true }, taskRows: true, showCard: true },
    { name: 'explicitly enabled tasks', manifest: { agent: { tasks: true }, showTaskPreferences: true }, taskRows: true, showCard: true },
    { name: 'opted-out tasks', manifest: { agent: { tasks: true }, showTaskPreferences: false }, taskRows: true, showCard: false },
    { name: 'opted-out quick answers', manifest: { cindy: { text: ['oneshot'] }, showTaskPreferences: false }, taskRows: false, showCard: false },
    { name: 'opted-out legacy errands', manifest: { agent: { errand: true }, showTaskPreferences: false }, taskRows: true, showCard: false },
    { name: 'opted-out workspaces', manifest: { workspace: true, showTaskPreferences: false }, taskRows: true, showCard: false },
  ])('respects Host task card visibility for $name', ({ manifest, taskRows, showCard }) => {
    vi.stubGlobal('ResizeObserver', class { observe() {} unobserve() {} disconnect() {} });
    Object.assign(window.electronAPI, {
      ghosts: {
        errandPrefsSync: () => ({ config: {}, auxiliaryModelLabel: 'Grok 4.6' }),
        setErrandConfig: vi.fn(async () => ({ config: {} })),
      },
      showOpenDirectoryDialog: vi.fn(),
    });
    const ghost: InstalledGhost = {
      manifest: {
        schemaVersion: 3, minCindyVersion: '0.1.0', kind: 'chip', id: 'model-plugin',
        name: 'Model plugin', version: '1.0.0', entry: 'main.js',
        ...(manifest as Partial<InstalledGhost['manifest']>),
      },
      dir: '/plugins/model-plugin',
      namespace: null,
      enabled: true,
      approval: { state: 'approved', revision: '00000000-0000-4000-8000-000000000002' },
      ...(taskRows ? { taskCapabilityApproved: true as const } : {}),
      trust: detail.trust,
    };
    const projected = toGhostPluginDetail(ghost);
    expect(projected).toMatchObject({ hasTaskPreferences: showCard, hasPluginTasks: taskRows });
    render(
      <GhostPluginDetailView
        ghost={ghost}
        detail={projected}
        panelStatus={null}
        onBack={vi.fn()}
        onToggle={vi.fn()}
        onUse={vi.fn()}
        onUpdate={vi.fn()}
        onUpdateFromFile={vi.fn()}
        onUninstall={vi.fn()}
        toggleDisabled={false}
      />,
    );
    expect(screen.queryByText('settings.ghosts.detail.cindyPrefs.title')).toBeNull();
    if (!showCard) {
      expect(screen.queryByText('settings.ghosts.detail.errandPrefs.title')).toBeNull();
      expect(screen.queryByText('settings.ghosts.detail.errandPrefs.model')).toBeNull();
      expect(screen.queryByText('settings.ghosts.detail.errandPrefs.permission')).toBeNull();
      expect(screen.queryByText('settings.ghosts.detail.errandPrefs.workdir')).toBeNull();
      return;
    }
    expect(screen.getByText('settings.ghosts.detail.errandPrefs.title')).toBeTruthy();
    expect(screen.getAllByText('settings.ghosts.detail.errandPrefs.model')).toHaveLength(1);
    expect(screen.getByText(`settings.ghosts.detail.errandPrefs.${taskRows ? 'desc' : 'descModelOnly'}`)).toBeTruthy();
    expect(Boolean(screen.queryByText('settings.ghosts.detail.errandPrefs.permission'))).toBe(taskRows);
    expect(Boolean(screen.queryByText('settings.ghosts.detail.errandPrefs.workdir'))).toBe(taskRows);
  });

  it('does not show the model card for media-only plugins (media always follows the system default)', () => {
    const ghost: InstalledGhost = {
      manifest: {
        schemaVersion: 3, minCindyVersion: '0.1.0', kind: 'chip', id: 'art', name: 'Art',
        version: '1.0.0', entry: 'main.js', cindy: { image: ['generate', 'edit'], embed: ['text'] },
        showTaskPreferences: true,
      },
      dir: '/plugins/art',
      namespace: null,
      enabled: true,
      approval: { state: 'approved', revision: '00000000-0000-4000-8000-000000000003' },
      trust: detail.trust,
    };
    expect(toGhostPluginDetail(ghost)).toMatchObject({ hasTaskPreferences: false, hasPluginTasks: false });
  });

  it('shows only the Tool description after an explicit click', async () => {
    render(
      <ToolDescriptionChip
        tool={{
          name: 'render_image',
          description: 'Render an image from the current prompt.',
          parameters: {
            type: 'object',
            properties: { prompt: { type: 'string' } },
          },
        }}
      />,
    );

    const trigger = screen.getByRole('button', { name: 'Open render_image' });
    fireEvent.mouseEnter(trigger);
    fireEvent.focus(trigger);
    expect(screen.queryByText('Render an image from the current prompt.')).toBeNull();

    fireEvent.click(trigger);

    expect(await screen.findByText('Render an image from the current prompt.')).toBeTruthy();
    expect(screen.queryByText('prompt')).toBeNull();
    expect(screen.queryByText('JSON Schema')).toBeNull();
  });

  it('keeps the Tools title count-free and puts See All beside the title', () => {
    render(
      <ToolsSection
        tools={Array.from({ length: 7 }, (_, index) => ({
          name: `tool_${index}`,
          description: `Tool ${index}`,
        }))}
      />,
    );

    const heading = screen.getByRole('heading', { name: 'Tools' });
    expect(heading).toBeTruthy();
    expect(heading.closest('section')?.className).not.toContain('border-t');
    expect(screen.queryByRole('heading', { name: /Tools.*7/ })).toBeNull();
    expect(screen.getByRole('button', { name: 'See All' })).toBeTruthy();
  });

  it('shows every host permission except Tools and opens the same complete details', async () => {
    render(<PermissionSummary items={permissions} />);

    const networkLabel = screen.getByText('Access api.example.com');
    const permissionCard = networkLabel.closest('button');
    const commandLabel = screen.getByText('Command render');
    const cindyLabel = screen.getByText('Generate images');
    expect(permissionCard).toBeTruthy();
    expect(commandLabel.closest('button')).toBe(permissionCard);
    expect(cindyLabel.closest('button')).toBe(permissionCard);
    expect(within(permissionCard as HTMLButtonElement).queryByText('Tool render')).toBeNull();
    expect(permissionCard?.className).toContain('grid-cols-2');
    expect(permissionCard?.className).toContain('var(--surface-elevated)');
    expect(permissionCard?.className).toContain('p-4');
    expect(permissionCard?.className).toContain('gap-y-0');
    expect(networkLabel.parentElement?.className).toContain('min-h-9');
    expect(networkLabel.className).toContain('text-13');
    expect(networkLabel.className).toContain('font-normal');
    expect(networkLabel.className).toContain('break-words');
    expect(networkLabel.className).not.toContain('truncate');
    expect(networkLabel.className).not.toContain('font-medium');

    fireEvent.click(permissionCard as HTMLButtonElement);

    const dialog = await screen.findByRole('dialog');
    expect(dialog.querySelector('.lucide-globe')).toBeTruthy();
    expect(dialog.innerHTML).toContain('border-b-[0.5px]');
    expect(dialog.innerHTML).toContain('divide-y-[0.5px]');
    expect(within(dialog).getByText('Access api.example.com')).toBeTruthy();
    expect(within(dialog).getByText('Can access this declared domain.')).toBeTruthy();
    expect(within(dialog).getByText('Command render')).toBeTruthy();
    expect(within(dialog).queryByText('Tool render')).toBeNull();
    expect(within(dialog).getByText('Generate images')).toBeTruthy();
    // detailArgs 的 model 插值必须替换占位符,不能显示裸 {{model}}(Greptile 2026-08-07)。
    expect(
      within(dialog).getByText(
        'Takes effect when the model (codex/gpt-5.5) is available in the catalog.',
      ),
    ).toBeTruthy();
    expect(within(dialog).queryByText(/Takes effect when the model \(\{\{model\}\}\)/)).toBeNull();
  });

  it('uses the same elevated theme surface for Tool bubbles and Permission cards', () => {
    render(
      <>
        <ToolDescriptionChip tool={{ name: 'render_image', description: 'Render an image.' }} />
        <PermissionSummary items={permissions} />
      </>,
    );

    expect(screen.getByRole('button', { name: 'Open render_image' }).className).toContain(
      'var(--surface-elevated)',
    );
    expect(screen.getByText('Access api.example.com').closest('button')?.className).toContain(
      'var(--surface-elevated)',
    );
  });

  it('lets the install location use the full details row and preserves its actions', async () => {
    vi.spyOn(HTMLElement.prototype, 'clientWidth', 'get').mockReturnValue(100);
    vi.spyOn(HTMLElement.prototype, 'scrollWidth', 'get').mockReturnValue(300);
    const writeText = vi.fn().mockResolvedValue(undefined);
    Object.defineProperty(navigator, 'clipboard', {
      configurable: true,
      value: { writeText },
    });
    render(<DetailsSection detail={detail} panelStatus="Docked" />);

    expect(screen.getByRole('heading', { name: 'Details' })).toBeTruthy();
    expect(screen.getByText('Version')).toBeTruthy();
    expect(screen.getByText('Author')).toBeTruthy();
    expect(screen.getByText('Identifier')).toBeTruthy();
    const detailsGrid = screen.getByText('Version').parentElement?.parentElement;
    expect(detailsGrid?.className).toContain('grid-cols-3');
    expect(detailsGrid?.className).not.toContain('border');
    expect(screen.getByText('v1.2.3').className).toContain('truncate');
    expect(screen.getByText('Contents')).toBeTruthy();
    expect(screen.queryByText('Source')).toBeNull();
    expect(screen.getByText('Panel')).toBeTruthy();
    expect(screen.getByText('Install Location')).toBeTruthy();
    const installLocation = screen.getByText('/tmp/cindy-brain/builtin.example');
    expect(installLocation.closest('.col-span-full')).toBeTruthy();
    expect(installLocation.className).toContain('truncate');
    expect(installLocation.className).toContain('whitespace-nowrap');
    expect(screen.queryByRole('button', { name: 'See All' })).toBeNull();

    const expandButton = screen.getByRole('button', { name: 'Show full Install Location' });
    expect(expandButton.getAttribute('aria-expanded')).toBe('false');
    fireEvent.click(expandButton);
    expect(installLocation.className).toContain('whitespace-pre-wrap');
    expect(installLocation.className).not.toContain('truncate');
    const collapseButton = screen.getByRole('button', { name: 'Collapse Install Location' });
    expect(collapseButton.getAttribute('aria-expanded')).toBe('true');
    fireEvent.click(collapseButton);
    expect(installLocation.className).toContain('truncate');
    expect(installLocation.className).toContain('whitespace-nowrap');

    fireEvent.click(screen.getByRole('button', { name: 'Copy Install Location' }));
    await waitFor(() => expect(writeText).toHaveBeenCalledWith('/tmp/cindy-brain/builtin.example'));

    const openPath = vi.fn().mockResolvedValue({ success: false, error: 'file locked' });
    Object.defineProperty(window, 'electronAPI', {
      configurable: true,
      value: { openPath },
    });
    fireEvent.click(screen.getByRole('button', { name: 'Open Install Location' }));
    await waitFor(() => expect(openPath).toHaveBeenCalledWith('/tmp/cindy-brain/builtin.example'));
    expect(toastMocks.error).toHaveBeenCalledWith('settings.ghosts.errors.generic');
  });

  it('does not add expand controls when detail values fit on one line', () => {
    vi.spyOn(HTMLElement.prototype, 'clientWidth', 'get').mockReturnValue(300);
    vi.spyOn(HTMLElement.prototype, 'scrollWidth', 'get').mockReturnValue(100);

    render(<DetailsSection detail={detail} panelStatus="Docked" />);

    expect(screen.queryByRole('button', { name: /Show full/ })).toBeNull();
  });

  it('keeps host permission guidance and author-provided OAuth scopes together', async () => {
    render(
      <PermissionSummary
        items={[
          permissions[0],
          {
            key: 'network:oauth',
            kind: 'network',
            labelKey: 'networkSecretOauth',
            detailKey: 'networkHostDetail',
            detail: 'scope.read\nscope.write',
          },
        ]}
      />,
    );

    fireEvent.click(
      screen.getByText('Access api.example.com').closest('button') as HTMLButtonElement,
    );
    const dialog = await screen.findByRole('dialog');
    expect(within(dialog).getAllByText('Can access this declared domain.')).toHaveLength(2);
    expect(
      within(dialog).getByText((_, element) => element?.textContent === 'scope.read\nscope.write'),
    ).toBeTruthy();
  });
});

it('adds shared counts to installed detail metadata while preserving author and version', () => {
  const { container } = render(<GhostPluginMetadata author="Cindy" version="1.7.5" marketItem={{
    sourceType: 'server', scope: 'organization',
    downloadStatistics: { requestCount: '1284' },
    usageStatistics: { usageCount: '8932', usageCountLast7Days: '12', asOf: '2026-10-13T00:00:00Z' },
  } as import('../../../../shared/pluginMarket').PluginMarketItem} />);
  expect(container.textContent).toContain('By Cindy·v1.7.5');
  expect(container.textContent).toContain('1,284 settings.ghosts.usage.downloadsValue');
  expect(container.textContent).toContain('8,932 settings.ghosts.usage.usesValue');
});