diff --git a/feature-task-list.json b/feature-task-list.json index 4740678..8fff45c 100644 --- a/feature-task-list.json +++ b/feature-task-list.json @@ -83,14 +83,14 @@ { "id": "T020", "description": "Options 界面美化:优化布局、配色、输入体验,与 Popup UI 风格统一", - "status": "pending", + "status": "passed", "priority": "medium", "dependencies": ["T012"] }, { "id": "T019", "description": "Options和Popup 配置应用到 LLM 调用:将 chrome.storage.local 中的 selectedProvider/selectedPromptId/apiKeys 实际用于 llmService 的 API 请求", - "status": "pending", + "status": "passed", "priority": "high", "dependencies": ["T012"] }, diff --git a/src/pages/background/llmService.test.ts b/src/pages/background/llmService.test.ts index 55e0168..aa6c3a1 100644 --- a/src/pages/background/llmService.test.ts +++ b/src/pages/background/llmService.test.ts @@ -3,17 +3,41 @@ import { describe, it, expect, beforeEach, afterEach, vi } from 'vitest'; import { LLMService } from './llmService'; -// Mock the config -vi.mock('./config', () => ({ - apiConfig: { - baseURL: 'https://api.deepseek.com', - apiKey: 'test-api-key', - model: 'deepseek-chat', - maxTokens: 1000, - temperature: 0.7, - systemPrompt: '你是一个专业的助手,请简洁地解释用户提供的内容。', +// Mock chrome.storage.local +const mockStorageData = { + selectedProvider: 'DeepSeek', + selectedPromptId: 'default-summary', + apiKeys: [ + { + id: '1', + provider: 'DeepSeek', + name: 'DeepSeek API', + url: 'https://api.deepseek.com', + key: 'test-api-key', + displayOrder: 0, + }, + ], + prompts: [ + { + id: 'default-summary', + name: 'Summary', + content: 'Summarize: {{text}}', + createdAt: 0, + updatedAt: 0, + }, + ], +}; + +vi.stubGlobal('chrome', { + storage: { + local: { + get: vi.fn((keys, callback) => { + if (callback) callback(mockStorageData); + }), + set: vi.fn(), + }, }, -})); +}); // Mock AbortController with proper signal interface vi.stubGlobal( @@ -129,7 +153,7 @@ describe('LLMService', () => { max_tokens: 1000, messages: expect.arrayContaining([ { role: 'system', content: '你是一个专业的助手,请简洁地解释用户提供的内容。' }, - { role: 'user', content: '请简洁地解释以下内容:Hello world' }, + { role: 'user', content: 'Summarize: Hello world' }, ]), }); }); @@ -337,6 +361,11 @@ describe('LLMService', () => { onError: mockOnError, }); + // Wait for the first storage callback to be called and first fetch to be made + await vi.waitFor(() => { + expect(mockFetch).toHaveBeenCalledTimes(1); + }); + // Now make a second request const mockResponse2 = { ok: true, @@ -354,8 +383,7 @@ describe('LLMService', () => { onError: mockOnError, }); - // The first request should have been aborted - // The second request should proceed normally + // Wait for the second fetch to be called await vi.waitFor(() => { expect(mockFetch).toHaveBeenCalledTimes(2); }); diff --git a/src/pages/background/llmService.ts b/src/pages/background/llmService.ts index 17c7612..dcc4df6 100644 --- a/src/pages/background/llmService.ts +++ b/src/pages/background/llmService.ts @@ -2,7 +2,8 @@ /* global fetch, setTimeout */ import type { ErrorCode } from './messageTypes'; -import { apiConfig } from './config'; +import type { APIKeyItem, PromptTemplate, StorageSchema } from './storage.types'; +import { PROVIDER_DEFAULTS } from './storage.types'; import { SSEParser } from './sseParser'; /** @@ -48,65 +49,108 @@ export class LLMService implements LLMServiceInterface { // 如果已有请求,先中止 this.abort(); - const { text, url, prompt, onChunk, onEnd, onError } = params; - this.currentRequest = new AbortController(); + const { text, prompt, onChunk, onEnd, onError } = params; + const controller = new AbortController(); + this.currentRequest = controller; - if (apiConfig.debug) { - console.log('[LLMService] Request started:', { - textLength: text.length, - url, - model: apiConfig.model, - baseURL: apiConfig.baseURL, - }); - } + // 从 storage 读取配置 + chrome.storage.local.get( + ['selectedProvider', 'selectedPromptId', 'apiKeys', 'prompts'], + (storageResult: Partial) => { + // 检查请求是否已被新请求取代 + if (this.currentRequest !== controller) { + return; + } + + const selectedProvider = storageResult.selectedProvider || 'DeepSeek'; + const selectedPromptId = storageResult.selectedPromptId || 'default-summary'; + const apiKeys = storageResult.apiKeys || []; + const prompts = storageResult.prompts || []; + + // 根据 selectedProvider 查找对应的 APIKeyItem + // selectedProvider 可能是 id(新格式)或 provider 名称(旧格式,兼容) + let apiKeyItem = apiKeys.find((k: APIKeyItem) => k.id === selectedProvider); + if (!apiKeyItem) { + // 兼容旧格式:selectedProvider 可能是 provider 名称 + apiKeyItem = apiKeys.find((k: APIKeyItem) => k.provider === selectedProvider); + } + // 如果还是找不到,使用第一个配置好的 provider + if (!apiKeyItem && apiKeys.length > 0) { + apiKeyItem = apiKeys[0]; + } + + if (!apiKeyItem || !apiKeyItem.url || !apiKeyItem.key) { + onError({ + code: 'API_ERROR', + message: `请在设置页面配置 API Key 和 URL`, + }); + return; + } + + // 获取 model 和 endpoint(优先使用 APIKeyItem 中的值,否则使用 provider 默认值) + const defaults = PROVIDER_DEFAULTS[apiKeyItem.provider] || PROVIDER_DEFAULTS['Custom']; + const model = apiKeyItem.model || defaults.model; + const endpoint = apiKeyItem.endpoint || defaults.endpoint; + + // 根据 selectedPromptId 查找对应的 PromptTemplate + const promptTemplate = prompts.find((p: PromptTemplate) => p.id === selectedPromptId); - // 构建 messages - const userContent = prompt ? `原文:${text}\n\n${prompt}` : `请简洁地解释以下内容:${text}`; - - const messages = [ - { role: 'system' as const, content: apiConfig.systemPrompt }, - { role: 'user' as const, content: userContent }, - ]; - - // 构建请求体 - const requestBody = { - model: apiConfig.model, - messages, - stream: true, - temperature: apiConfig.temperature, - max_tokens: apiConfig.maxTokens, - }; - - // 发起请求 - this.executeRequest(requestBody, onChunk, onEnd, onError); + // 构建 messages - 使用 replaceAll 替换所有 {{text}} 占位符 + const userContent = prompt + ? `原文:${text}\n\n${prompt}` + : promptTemplate + ? promptTemplate.content.replaceAll('{{text}}', text) + : `请简洁地解释以下内容:${text}`; + + const messages = [ + { role: 'system' as const, content: '你是一个专业的助手,请简洁地解释用户提供的内容。' }, + { role: 'user' as const, content: userContent }, + ]; + + // 构建请求体 + const requestBody = { + model, + messages, + stream: true, + temperature: 0.7, + max_tokens: 1000, + }; + + // 发起请求,使用配置的 URL 和 endpoint + this.executeRequest( + apiKeyItem.url, + apiKeyItem.key, + endpoint, + requestBody, + controller.signal, + onChunk, + onEnd, + onError + ); + } + ); } private async executeRequest( + baseURL: string, + apiKey: string, + endpoint: string, requestBody: object, + signal: AbortSignal, onChunk: (chunk: string) => void, onEnd: (fullResponse: string) => void, onError: (error: { code: ErrorCode; message: string }) => void ): Promise { - const controller = this.currentRequest; - if (!controller) return; - - if (apiConfig.debug) { - console.log( - '[LLMService] Sending fetch request to:', - `${apiConfig.baseURL}/chat/completions` - ); - } - try { - const response = await fetch(`${apiConfig.baseURL}/chat/completions`, { + const response = await fetch(`${baseURL}${endpoint}`, { method: 'POST', headers: { 'Content-Type': 'application/json', - Authorization: `Bearer ${apiConfig.apiKey}`, + Authorization: `Bearer ${apiKey}`, Accept: 'text/event-stream', }, body: JSON.stringify(requestBody), - signal: controller.signal, + signal, }); if (!response.ok) { @@ -128,7 +172,7 @@ export class LLMService implements LLMServiceInterface { } // 解析 SSE 流 - await this.parseSSestream(response.body, controller.signal, onChunk, onEnd, onError); + await this.parseSSestream(response.body, signal, onChunk, onEnd, onError); } catch (error) { if (error instanceof Error && error.name === 'AbortError') { // 请求被中止,不触发错误 @@ -139,7 +183,8 @@ export class LLMService implements LLMServiceInterface { message: `网络错误: ${error instanceof Error ? error.message : 'Unknown error'}`, }); } finally { - if (this.currentRequest === controller) { + // Only clear currentRequest if this request's signal is still current + if (this.currentRequest?.signal === signal) { this.currentRequest = null; } } @@ -158,27 +203,17 @@ export class LLMService implements LLMServiceInterface { let fullResponse = ''; let chunkCount = 0; - if (apiConfig.debug) { - console.log('[LLMService] SSE stream started parsing'); - } - try { while (true) { const { done, value } = await reader.read(); if (done) break; const chunk = decoder.decode(value, { stream: true }); - if (apiConfig.debug) { - console.log('[LLMService] Raw SSE chunk received:', chunk.slice(0, 100)); - } const messages = parser.parse(chunk); for (const msg of messages) { chunkCount++; fullResponse += msg; - if (apiConfig.debug) { - console.log('[LLMService] Parsed message chunk:', chunkCount, msg.slice(0, 50)); - } // 打字机延迟 await this.delayChunk(msg, signal, onChunk); } diff --git a/src/pages/background/storage.types.test.ts b/src/pages/background/storage.types.test.ts index cbb86b9..7c3aefb 100644 --- a/src/pages/background/storage.types.test.ts +++ b/src/pages/background/storage.types.test.ts @@ -9,9 +9,12 @@ describe('storage.types', () => { }); it('should have valid providers', () => { - expect(PROVIDERS).toContain('DeepSeek'); expect(PROVIDERS).toContain('OpenAI'); - expect(PROVIDERS).toContain('Local'); + expect(PROVIDERS).toContain('DeepSeek'); + expect(PROVIDERS).toContain('SiliconFlow'); + expect(PROVIDERS).toContain('TogetherAI'); + expect(PROVIDERS).toContain('Ollama'); + expect(PROVIDERS).toContain('Custom'); }); it('should have valid prompt template structure', () => { diff --git a/src/pages/background/storage.types.ts b/src/pages/background/storage.types.ts index d971c31..c37f648 100644 --- a/src/pages/background/storage.types.ts +++ b/src/pages/background/storage.types.ts @@ -3,7 +3,12 @@ export interface APIKeyItem { id: string; provider: string; + name: string; + url: string; key: string; + displayOrder: number; + model?: string; // Optional: provider-specific model (e.g., deepseek-chat, gpt-4) + endpoint?: string; // Optional: custom endpoint path (e.g., /v1/chat/completions) } export interface PromptTemplate { @@ -39,5 +44,65 @@ export const DEFAULT_PROMPTS: PromptTemplate[] = [ }, ]; -export const PROVIDERS = ['DeepSeek', 'OpenAI', 'Local'] as const; +// Provider 服务商/品牌列表 +export const PROVIDERS = [ + 'OpenAI', + 'DeepSeek', + 'SiliconFlow', + 'TogetherAI', + 'Ollama', + 'Custom', +] as const; export type Provider = (typeof PROVIDERS)[number]; + +// Provider 默认配置 +export interface ProviderConfig { + name: string; + url: string; + model: string; + endpoint: string; +} + +export const PROVIDER_DEFAULTS: Record = { + OpenAI: { + name: 'OpenAI', + url: 'https://api.openai.com', + model: 'gpt-3.5-turbo', + endpoint: '/v1/chat/completions', + }, + DeepSeek: { + name: 'DeepSeek', + url: 'https://api.deepseek.com', + model: 'deepseek-chat', + endpoint: '/chat/completions', + }, + SiliconFlow: { + name: 'SiliconFlow', + url: 'https://api.siliconflow.cn', + model: 'deepseek-chat', + endpoint: '/v1/chat/completions', + }, + TogetherAI: { + name: 'TogetherAI', + url: 'https://api.together.xyz', + model: 'meta-llama/Llama-3-70b-chat', + endpoint: '/v1/chat/completions', + }, + Ollama: { + name: 'Ollama', + url: 'http://localhost:11434', + model: 'llama3', + endpoint: '/api/chat', + }, + Custom: { + name: 'Custom', + url: '', + model: '', + endpoint: '/v1/chat/completions', + }, +}; + +// 判断是否为内置 provider 类型 +export const isBuiltInProvider = (provider: string): boolean => { + return ['OpenAI', 'DeepSeek', 'SiliconFlow', 'TogetherAI', 'Ollama'].includes(provider); +}; diff --git a/src/pages/options/Options.test.tsx b/src/pages/options/Options.test.tsx index e49fe5a..01fc742 100644 --- a/src/pages/options/Options.test.tsx +++ b/src/pages/options/Options.test.tsx @@ -1,11 +1,32 @@ // src/pages/options/Options.test.tsx -import { describe, it, expect, vi, beforeEach } from 'vitest'; -import { render, screen, waitFor } from '@testing-library/react'; +import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest'; +import { render, screen, waitFor, fireEvent } from '@testing-library/react'; import Options from './Options'; -// Mock chrome.storage - data -const mockStorage = { - apiKeys: [{ id: '1', provider: 'DeepSeek', key: 'test-key' }], +// Mock chrome.storage - pre-populated with default providers +const mockStorageWithProviders = { + apiKeys: [ + { + id: 'provider-openai', + provider: 'OpenAI', + name: 'OpenAI', + url: 'https://api.openai.com', + key: '', + displayOrder: 0, + model: 'gpt-3.5-turbo', + endpoint: '/v1/chat/completions', + }, + { + id: 'provider-deepseek', + provider: 'DeepSeek', + name: 'DeepSeek', + url: 'https://api.deepseek.com', + key: 'test-key', + displayOrder: 1, + model: 'deepseek-chat', + endpoint: '/chat/completions', + }, + ], prompts: [ { id: '1', name: 'Summary', content: 'Summarize: {{text}}', createdAt: 0, updatedAt: 0 }, ], @@ -16,37 +37,136 @@ const mockStorage = { describe('Options', () => { beforeEach(() => { vi.clearAllMocks(); - // Setup chrome.storage.local.get mock vi.mocked(chrome.storage.local.get).mockImplementation((keys, callback) => { - if (callback) callback(mockStorage); + if (callback) callback(mockStorageWithProviders); }); vi.mocked(chrome.storage.local.set).mockImplementation((data, callback) => { if (callback) callback(); }); + vi.stubGlobal('fetch', vi.fn()); }); - it('renders API Keys section', () => { - render(); - expect(screen.getByText(/api keys/i)).toBeInTheDocument(); + afterEach(() => { + vi.restoreAllMocks(); }); - it('renders Prompt Templates section', () => { - render(); - expect(screen.getByText(/prompt templates/i)).toBeInTheDocument(); - }); + describe('API Keys Section - Card Layout', () => { + it('renders API Keys section', () => { + render(); + expect(screen.getByText(/api keys/i)).toBeInTheDocument(); + }); + + it('renders provider cards with badge labels', async () => { + render(); + await waitFor(() => { + expect(screen.getByText('OpenAI')).toBeInTheDocument(); + expect(screen.getByText('DeepSeek')).toBeInTheDocument(); + }); + }); + + it('renders API URL inputs with pre-filled values', async () => { + render(); + await waitFor(() => { + const inputs = screen.getAllByRole('textbox'); + // First provider: URL, Display Name, Model, Endpoint, API Key + // Second provider: URL, Display Name, Model, Endpoint, API Key + // Plus prompt template name = 11 textboxes total + expect(inputs.length).toBeGreaterThanOrEqual(4); + }); + }); + + it('renders Test buttons for each provider', async () => { + render(); + await waitFor(() => { + const testButtons = screen.getAllByRole('button', { name: 'Test' }); + expect(testButtons).toHaveLength(2); + }); + }); + + it('renders Delete provider buttons', async () => { + render(); + await waitFor(() => { + const deleteButtons = screen.getAllByTitle('Delete provider'); + expect(deleteButtons).toHaveLength(2); + }); + }); + + it('calls handleUpdateApiKey when API key is changed', async () => { + render(); + await waitFor(() => { + const apiKeyInputs = screen.getAllByPlaceholderText('sk-...'); + expect(apiKeyInputs).toHaveLength(2); + fireEvent.change(apiKeyInputs[0], { target: { value: 'sk-new-key-123' } }); + // Changes are tracked but not auto-saved - Save button should appear + const saveButtons = screen.getAllByText('Save'); + expect(saveButtons).toHaveLength(1); + }); + }); - it('renders existing API keys', async () => { - render(); - await waitFor(() => { - const select = screen.getByRole('combobox'); - expect(select).toHaveValue('DeepSeek'); + it('saves changes when Save button is clicked', async () => { + render(); + await waitFor(() => { + const apiKeyInputs = screen.getAllByPlaceholderText('sk-...'); + expect(apiKeyInputs).toHaveLength(2); + fireEvent.change(apiKeyInputs[0], { target: { value: 'sk-new-key-123' } }); + }); + // Click Save button + const saveButton = screen.getByText('Save'); + fireEvent.click(saveButton); + expect(chrome.storage.local.set).toHaveBeenCalledWith( + expect.objectContaining({ + apiKeys: expect.arrayContaining([expect.objectContaining({ key: 'sk-new-key-123' })]), + }) + ); + }); + + it('disables Test button when API key is empty', async () => { + render(); + await waitFor(() => { + const testButtons = screen.getAllByRole('button', { name: 'Test' }); + expect(testButtons[0]).toBeDisabled(); + }); + }); + + it('enables Test button when API key is filled', async () => { + render(); + await waitFor(() => { + const testButtons = screen.getAllByRole('button', { name: 'Test' }); + expect(testButtons[1]).not.toBeDisabled(); + }); + }); + + it('has provider badge styling', async () => { + render(); + await waitFor(() => { + const badges = document.querySelectorAll('.provider-badge'); + expect(badges).toHaveLength(2); + }); }); }); - it('renders existing prompts', async () => { - render(); - await waitFor(() => { - expect(screen.getByDisplayValue('Summary')).toBeInTheDocument(); + describe('Prompt Templates Section', () => { + it('renders Prompt Templates section', () => { + render(); + expect(screen.getByText(/prompt templates/i)).toBeInTheDocument(); + }); + + it('renders existing prompts', async () => { + render(); + await waitFor(() => { + expect(screen.getByDisplayValue('Summary')).toBeInTheDocument(); + }); + }); + + it('renders add template button', () => { + render(); + expect(screen.getByRole('button', { name: /add template/i })).toBeInTheDocument(); + }); + + it('renders variable hint', () => { + render(); + expect(screen.getByText(/use.*where you want.*selected page text/i)).toBeInTheDocument(); + expect(screen.getByText('{{text}}')).toBeInTheDocument(); }); }); }); diff --git a/src/pages/options/Options.tsx b/src/pages/options/Options.tsx index aef69c2..2be728a 100644 --- a/src/pages/options/Options.tsx +++ b/src/pages/options/Options.tsx @@ -2,7 +2,11 @@ /* global fetch */ import React, { useState, useEffect } from 'react'; import type { APIKeyItem, PromptTemplate, StorageSchema } from '@pages/background/storage.types'; -import { DEFAULT_PROMPTS, PROVIDERS } from '@pages/background/storage.types'; +import { + DEFAULT_PROMPTS, + PROVIDER_DEFAULTS, + isBuiltInProvider, +} from '@pages/background/storage.types'; const STORAGE_KEYS: (keyof StorageSchema)[] = [ 'apiKeys', @@ -51,79 +55,184 @@ const XIcon = () => ( ); +const RefreshIcon = () => ( + + + +); + +// 根据 provider 获取默认配置 +const getDefaultsForProvider = (provider: string) => { + return PROVIDER_DEFAULTS[provider] || PROVIDER_DEFAULTS['Custom']; +}; + export default function Options() { const [apiKeys, setApiKeys] = useState([]); const [prompts, setPrompts] = useState(DEFAULT_PROMPTS); const [keyValidation, setKeyValidation] = useState< Record >({}); + const [newProvider, setNewProvider] = useState(''); + const [newProviderName, setNewProviderName] = useState(''); + // Track unsaved changes per provider card + const [unsavedChanges, setUnsavedChanges] = useState>({}); + // Track unsaved changes per prompt + const [promptUnsavedChanges, setPromptUnsavedChanges] = useState>({}); + + // Sort providers by displayOrder + const sortedApiKeys = [...apiKeys].sort((a, b) => a.displayOrder - b.displayOrder); + + // Get list of already added provider names + const addedProviderNames = apiKeys.map((k) => k.name.toLowerCase()); + // Built-in providers that haven't been added yet + const availableBuiltIn = ['OpenAI', 'DeepSeek', 'SiliconFlow', 'TogetherAI', 'Ollama'].filter( + (p) => !addedProviderNames.includes(p.toLowerCase()) + ); useEffect(() => { chrome.storage.local.get(STORAGE_KEYS, (result: Partial) => { - if (result.apiKeys?.length) setApiKeys(result.apiKeys); - if (result.prompts?.length) setPrompts(result.prompts); + if (Array.isArray(result.apiKeys) && result.apiKeys.length > 0) { + setApiKeys(result.apiKeys); + } + // 不再自动初始化默认provider,让用户自己添加 + + if (Array.isArray(result.prompts) && result.prompts.length > 0) { + setPrompts(result.prompts); + } }); }, []); + // Auto-resize prompt textareas on mount + useEffect(() => { + const textareas = document.querySelectorAll('.template-textarea'); + textareas.forEach((textarea) => { + const el = textarea as HTMLTextAreaElement; + el.style.height = 'auto'; + el.style.height = el.scrollHeight + 'px'; + }); + }, [prompts]); + const saveToStorage = (updates: Partial) => { chrome.storage.local.set(updates); }; - const handleAddApiKey = () => { - const newKey: APIKeyItem = { - id: `key-${Date.now()}`, - provider: PROVIDERS[0], - key: '', - }; - const updated = [...apiKeys, newKey]; + const handleUpdateApiKey = ( + id: string, + field: 'key' | 'name' | 'url' | 'model' | 'endpoint', + value: string + ) => { + const updated = apiKeys.map((k) => (k.id === id ? { ...k, [field]: value } : k)); setApiKeys(updated); - saveToStorage({ apiKeys: updated }); + setUnsavedChanges((prev) => ({ ...prev, [id]: true })); }; - const handleUpdateApiKey = (id: string, field: 'provider' | 'key', value: string) => { - const updated = apiKeys.map((k) => (k.id === id ? { ...k, [field]: value } : k)); - setApiKeys(updated); - saveToStorage({ apiKeys: updated }); + const handleSaveProvider = (id: string) => { + const item = apiKeys.find((k) => k.id === id); + if (!item) return; + saveToStorage({ apiKeys }); + setUnsavedChanges((prev) => ({ ...prev, [id]: false })); }; const handleDeleteApiKey = (id: string) => { const updated = apiKeys.filter((k) => k.id !== id); setApiKeys(updated); saveToStorage({ apiKeys: updated }); + setUnsavedChanges((prev) => { + const next = { ...prev }; + delete next[id]; + return next; + }); + }; + + const handleResetToDefaults = (id: string, provider: string) => { + const defaults = getDefaultsForProvider(provider); + const updated = apiKeys.map((k) => + k.id === id + ? { + ...k, + name: defaults.name, + url: defaults.url, + model: defaults.model, + endpoint: defaults.endpoint, + } + : k + ); + setApiKeys(updated); + setUnsavedChanges((prev) => ({ ...prev, [id]: true })); + }; + + const handleAddProvider = () => { + if (!newProvider) return; + + let newApiKey: APIKeyItem; + + if (isBuiltInProvider(newProvider)) { + // Built-in provider with defaults + const defaults = getDefaultsForProvider(newProvider); + newApiKey = { + id: `provider-${newProvider.toLowerCase()}-${Date.now()}`, + provider: newProvider, + name: newProviderName || defaults.name, + url: defaults.url, + key: '', + displayOrder: apiKeys.length, + model: defaults.model, + endpoint: defaults.endpoint, + }; + } else { + // Custom provider with user-defined name + newApiKey = { + id: `provider-custom-${Date.now()}`, + provider: 'Custom', + name: newProviderName || 'Custom Provider', + url: '', + key: '', + displayOrder: apiKeys.length, + model: '', + endpoint: '/v1/chat/completions', + }; + } + + const updated = [...apiKeys, newApiKey]; + setApiKeys(updated); + saveToStorage({ apiKeys: updated }); + // Immediately saved, no unsaved changes + setNewProvider(''); + setNewProviderName(''); }; - const handleTestApiKey = async (id: string, provider: string, key: string) => { - if (!key) return; + const handleUpdateDisplayOrder = (id: string, value: string) => { + const order = parseInt(value) || 0; + const updated = apiKeys.map((k) => (k.id === id ? { ...k, displayOrder: order } : k)); + setApiKeys(updated); + setUnsavedChanges((prev) => ({ ...prev, [id]: true })); + }; + + const handleTestApiKey = async ( + id: string, + provider: string, + url: string, + key: string, + model?: string, + endpoint?: string + ) => { + if (!key || !url) return; setKeyValidation((prev) => ({ ...prev, [id]: 'testing' })); try { - // Determine baseURL and endpoint based on provider - let baseURL: string; - let endpoint: string; - let model: string; - - if (provider === 'DeepSeek') { - baseURL = 'https://api.deepseek.com'; - endpoint = '/chat/completions'; - model = 'deepseek-chat'; - } else if (provider === 'OpenAI') { - baseURL = 'https://api.openai.com'; - endpoint = '/v1/chat/completions'; - model = 'gpt-3.5-turbo'; - } else { - // Local provider - skip test or use configurable endpoint - setKeyValidation((prev) => ({ ...prev, [id]: 'invalid' })); - return; - } + // 优先使用用户配置的 model/endpoint,否则使用 provider 默认值 + const defaults = getDefaultsForProvider(provider); + const actualModel = model || defaults.model; + const actualEndpoint = endpoint || defaults.endpoint; - const response = await fetch(`${baseURL}${endpoint}`, { + const response = await fetch(`${url}${actualEndpoint}`, { method: 'POST', headers: { 'Content-Type': 'application/json', Authorization: `Bearer ${key}`, }, body: JSON.stringify({ - model: model, + model: actualModel, messages: [{ role: 'user', content: 'test' }], max_tokens: 10, }), @@ -153,68 +262,218 @@ export default function Options() { p.id === id ? { ...p, [field]: value, updatedAt: Date.now() } : p ); setPrompts(updated); - saveToStorage({ prompts: updated }); + setPromptUnsavedChanges((prev) => ({ ...prev, [id]: true })); + }; + + const handleSavePrompt = (id: string) => { + saveToStorage({ prompts }); + setPromptUnsavedChanges((prev) => ({ ...prev, [id]: false })); }; const handleDeletePrompt = (id: string) => { const updated = prompts.filter((p) => p.id !== id); setPrompts(updated); saveToStorage({ prompts: updated }); + setPromptUnsavedChanges((prev) => { + const next = { ...prev }; + delete next[id]; + return next; + }); }; return (
- {/* API Keys Section */} + {/* API Keys Section - Card Layout */}
API Keys
- -
- - {apiKeys.map((item) => ( -
+
-
+ {newProvider === 'Custom' && ( handleUpdateApiKey(item.id, 'key', e.target.value)} - onBlur={() => handleTestApiKey(item.id, item.provider, item.key)} - placeholder="Enter API key..." - aria-label="API Key" + type="text" + className="field-input" + value={newProviderName} + onChange={(e) => setNewProviderName(e.target.value)} + placeholder="Provider name..." + style={{ width: '160px' }} /> -
-
- {keyValidation[item.id] === 'valid' && } - {keyValidation[item.id] === 'invalid' && } -
+ )}
- ))} +
+ +
Lower number = higher priority in popup list
+ +
+ {sortedApiKeys.map((item) => ( +
+
+
+ {item.provider} + {item.provider === 'Custom' && Custom} +
+ {keyValidation[item.id] === 'valid' && } + {keyValidation[item.id] === 'invalid' && } +
+
+
+ {unsavedChanges[item.id] && ( + + )} + + +
+
+ +
+
+ + handleUpdateApiKey(item.id, 'name', e.target.value)} + placeholder="Display name..." + /> +
+ +
+ + handleUpdateApiKey(item.id, 'url', e.target.value)} + placeholder="https://api.example.com" + /> +
+ +
+
+ + handleUpdateApiKey(item.id, 'model', e.target.value)} + placeholder="gpt-3.5-turbo" + /> +
+
+ + handleUpdateApiKey(item.id, 'endpoint', e.target.value)} + placeholder="/v1/chat/completions" + /> +
+
+ +
+
+ + handleUpdateDisplayOrder(item.id, e.target.value)} + min="0" + /> +
+
+ +
+ +
+ handleUpdateApiKey(item.id, 'key', e.target.value)} + onBlur={() => + handleTestApiKey( + item.id, + item.provider, + item.url, + item.key, + item.model, + item.endpoint + ) + } + placeholder="sk-..." + /> + +
+
+
+
+ ))} +
{/* Prompt Templates Section */} @@ -233,13 +492,25 @@ export default function Options() { {prompts.map((prompt) => (
- handleUpdatePrompt(prompt.id, 'name', e.target.value)} - aria-label="Template name" - /> +
+ handleUpdatePrompt(prompt.id, 'name', e.target.value)} + aria-label="Template name" + placeholder="Template name..." + /> + {promptUnsavedChanges[prompt.id] && ( + + )} +
))} diff --git a/src/pages/options/options.css b/src/pages/options/options.css index e48b311..647b9a0 100644 --- a/src/pages/options/options.css +++ b/src/pages/options/options.css @@ -1,11 +1,11 @@ -/* src/pages/options/options.css */ +/* src/pages/options/options.css - T020: Options UI Styling (Matching Popup UI) */ /* Page Container */ .page-container { - max-width: 640px; + max-width: 900px; margin: 0 auto; padding: 32px 24px; - background: #f8fafc; + background: #ffffff; min-height: 100vh; } @@ -13,87 +13,126 @@ .section-card { background: #ffffff; border: 1px solid #e2e8f0; - border-radius: 12px; - margin-bottom: 20px; + border-radius: 16px; + margin-bottom: 24px; overflow: hidden; box-shadow: 0 1px 3px rgba(0, 0, 0, 0.04); } /* Section Header */ .section-header { - padding: 16px 20px; + padding: 20px 24px; border-bottom: 1px solid #f1f5f9; display: flex; align-items: center; justify-content: space-between; + flex-wrap: wrap; + gap: 12px; } .section-title { display: flex; align-items: center; gap: 10px; - font-size: 14px; + font-size: 15px; font-weight: 600; color: #0f172a; } .section-icon { - width: 18px; - height: 18px; + width: 20px; + height: 20px; color: #3b82f6; } -/* API Key Item */ -.api-key-item { +/* Add Provider Row */ +.add-provider-row { display: flex; align-items: center; - gap: 12px; - padding: 14px 20px; - border-bottom: 1px solid #f8fafc; - transition: background 150ms; + gap: 8px; } -.api-key-item:last-of-type { - border-bottom: none; +.add-provider-select { + padding: 8px 12px; + font-size: 13px; + color: #1e293b; + background: #f8fafc; + border: 1px solid #e2e8f0; + border-radius: 8px; + cursor: pointer; + min-width: 180px; } -.api-key-item:hover { - background: #fafbfc; +.add-provider-select:focus { + outline: none; + border-color: #3b82f6; + box-shadow: 0 0 0 3px rgba(59, 130, 246, 0.1); } -.provider-name { - width: 100px; - font-size: 13px; - font-weight: 500; - color: #475569; +/* Sort Hint */ +.sort-hint { + padding: 8px 24px; + font-size: 11px; + color: #94a3af; + background: #f8fafc; + border-bottom: 1px solid #f1f5f9; } -.key-input-wrapper { - flex: 1; - position: relative; +/* Provider Grid - Card Layout */ +.provider-grid { + display: grid; + grid-template-columns: repeat(auto-fill, minmax(360px, 1fr)); + gap: 16px; + padding: 20px 24px; } -.key-input { - width: 100%; - padding: 9px 14px; - font-size: 13px; - font-family: 'SF Mono', Monaco, monospace; - color: #1e293b; +/* Provider Card */ +.provider-card { background: #f8fafc; border: 1px solid #e2e8f0; - border-radius: 8px; - transition: border-color 150ms, background 150ms, box-shadow 150ms; + border-radius: 12px; + padding: 16px; + transition: border-color 200ms, box-shadow 200ms; } -.key-input:focus { - outline: none; - border-color: #3b82f6; - background: #ffffff; - box-shadow: 0 0 0 3px rgba(59, 130, 246, 0.1); +.provider-card:hover { + border-color: #cbd5e1; + box-shadow: 0 2px 8px rgba(0, 0, 0, 0.04); } -.key-input::placeholder { - color: #94a3af; +.provider-card-header { + display: flex; + align-items: flex-start; + justify-content: space-between; + margin-bottom: 16px; +} + +.provider-name-row { + display: flex; + align-items: center; + gap: 10px; +} + +.provider-badge { + display: inline-flex; + align-items: center; + padding: 4px 12px; + font-size: 13px; + font-weight: 600; + color: #3b82f6; + background: #eff6ff; + border-radius: 6px; +} + +.custom-badge { + display: inline-flex; + align-items: center; + padding: 4px 8px; + font-size: 11px; + font-weight: 500; + color: #8b5cf6; + background: #f5f3ff; + border-radius: 4px; } .key-status { @@ -116,54 +155,200 @@ color: #94a3af; } -/* Delete Button */ +.reset-btn { + width: 28px; + height: 28px; + display: flex; + align-items: center; + justify-content: center; + background: none; + border: 1px solid #e2e8f0; + color: #94a3b8; + border-radius: 6px; + cursor: pointer; + transition: all 150ms; +} + +.reset-btn:hover { + background: #ffffff; + border-color: #3b82f6; + color: #3b82f6; +} + .delete-btn { - width: 32px; - height: 32px; + width: 28px; + height: 28px; display: flex; align-items: center; justify-content: center; background: none; - border: none; - color: #94a3af; + border: 1px solid #e2e8f0; + color: #94a3b8; border-radius: 6px; cursor: pointer; - transition: color 150ms, background 150ms; + transition: all 150ms; } .delete-btn:hover { - color: #ef4444; background: #fef2f2; + border-color: #ef4444; + color: #ef4444; } -/* Add Button */ -.add-btn { +.provider-actions { display: flex; align-items: center; - justify-content: center; + gap: 6px; +} + +.save-btn { + padding: 6px 12px; + font-size: 12px; + font-weight: 600; + color: #ffffff; + background: #22c55e; + border: none; + border-radius: 6px; + cursor: pointer; + transition: background 150ms; +} + +.save-btn:hover { + background: #16a34a; +} + +.save-btn-sm { + padding: 5px 10px; + font-size: 11px; +} + +.provider-card-body { + display: flex; + flex-direction: column; + gap: 12px; +} + +/* Field Groups */ +.field-group { + display: flex; + flex-direction: column; + gap: 6px; +} + +.field-row { + display: flex; + gap: 12px; +} + +.flex-1 { + flex: 1; +} + +.field-label { + font-size: 11px; + font-weight: 500; + color: #64748b; + text-transform: uppercase; + letter-spacing: 0.05em; +} + +.field-input { + width: 100%; + padding: 10px 12px; + font-size: 13px; + color: #1e293b; + background: #ffffff; + border: 1px solid #e2e8f0; + border-radius: 8px; + transition: border-color 150ms, box-shadow 150ms; + box-sizing: border-box; +} + +.field-input:focus { + outline: none; + border-color: #3b82f6; + box-shadow: 0 0 0 3px rgba(59, 130, 246, 0.1); +} + +.field-input::placeholder { + color: #94a3b8; +} + +/* Order Input */ +.order-input { + width: 80px; + text-align: center; + font-weight: 500; +} + +/* API Key Row */ +.api-key-row { + display: flex; gap: 8px; - width: calc(100% - 40px); - margin: 12px 20px 16px; +} + +.api-key-input { + flex: 1; + font-family: 'SF Mono', Monaco, monospace; +} + +/* Test Button */ +.test-btn { padding: 10px 16px; font-size: 13px; font-weight: 500; - color: #64748b; - background: none; - border: 1.5px dashed #cbd5e1; + color: #ffffff; + background: #3b82f6; + border: none; + border-radius: 8px; + cursor: pointer; + transition: background 150ms, transform 100ms; + white-space: nowrap; +} + +.test-btn:hover:not(:disabled) { + background: #2563eb; +} + +.test-btn:active:not(:disabled) { + transform: scale(0.98); +} + +.test-btn:disabled { + background: #cbd5e1; + cursor: not-allowed; +} + +/* Add Button */ +.add-btn { + display: flex; + align-items: center; + gap: 6px; + padding: 8px 16px; + font-size: 13px; + font-weight: 500; + color: #ffffff; + background: linear-gradient(135deg, #3b82f6 0%, #2563eb 100%); + border: none; border-radius: 8px; cursor: pointer; - transition: border-color 150ms, color 150ms, background 150ms; + transition: transform 150ms, box-shadow 150ms; + box-shadow: 0 2px 8px rgba(59, 130, 246, 0.25); } .add-btn:hover { - border-color: #3b82f6; - color: #3b82f6; - background: #f8fafc; + transform: translateY(-1px); + box-shadow: 0 4px 12px rgba(59, 130, 246, 0.35); +} + +.add-btn:active { + transform: translateY(0); + box-shadow: 0 1px 4px rgba(59, 130, 246, 0.2); } /* Template Item */ .template-item { - padding: 16px 20px; + padding: 16px 24px; border-bottom: 1px solid #f8fafc; } @@ -173,15 +358,41 @@ .template-header { display: flex; - align-items: center; + align-items: flex-start; justify-content: space-between; - margin-bottom: 10px; + margin-bottom: 12px; + gap: 12px; } -.template-name { - font-size: 13px; +.template-name-row { + display: flex; + align-items: center; + gap: 8px; + flex: 1; +} + +.template-name-input { + flex: 1; + padding: 8px 12px; + font-size: 14px; font-weight: 500; - color: #475569; + color: #1e293b; + background: #f8fafc; + border: 1px solid #e2e8f0; + border-radius: 8px; + transition: border-color 150ms, box-shadow 150ms, background 150ms; +} + +.template-name-input:focus { + outline: none; + border-color: #3b82f6; + background: #ffffff; + box-shadow: 0 0 0 3px rgba(59, 130, 246, 0.1); +} + +.template-name-input::placeholder { + color: #94a3b8; + font-weight: 400; } .template-actions { @@ -191,16 +402,17 @@ .template-textarea { width: 100%; - min-height: 56px; - padding: 10px 14px; + min-height: 80px; + padding: 12px 14px; font-size: 13px; font-family: 'SF Mono', Monaco, monospace; - line-height: 1.5; + line-height: 1.6; color: #1e293b; background: #f8fafc; border: 1px solid #e2e8f0; border-radius: 8px; resize: vertical; + overflow: hidden; transition: border-color 150ms, background 150ms, box-shadow 150ms; box-sizing: border-box; } @@ -210,6 +422,7 @@ border-color: #3b82f6; background: #ffffff; box-shadow: 0 0 0 3px rgba(59, 130, 246, 0.1); + resize: vertical; } .template-textarea::placeholder { @@ -218,17 +431,22 @@ /* Variable Hint */ .var-hint { - font-size: 11px; - color: #94a3af; - margin-top: 6px; + font-size: 12px; + color: #64748b; + margin-top: 8px; display: flex; - align-items: center; - gap: 4px; + align-items: flex-start; + gap: 6px; + line-height: 1.4; +} + +.var-hint-icon { + flex-shrink: 0; } .var-hint code { background: #f1f5f9; - padding: 1px 5px; + padding: 2px 6px; border-radius: 4px; font-family: 'SF Mono', Monaco, monospace; font-size: 11px; @@ -261,23 +479,21 @@ } /* Responsive */ -@media (max-width: 680px) { - .page-container { - padding: 20px 16px; +@media (max-width: 800px) { + .provider-grid { + grid-template-columns: 1fr; + padding: 16px; } - .api-key-item { - flex-wrap: wrap; + .field-row { + flex-direction: column; } - .key-input-wrapper { - width: 100%; - order: 2; - margin-top: 8px; + .api-key-row { + flex-direction: column; } - .delete-btn { - order: 3; - margin-left: auto; + .test-btn { + width: 100%; } } diff --git a/src/pages/popup/Popup.test.tsx b/src/pages/popup/Popup.test.tsx index e5bd464..003fdbd 100644 --- a/src/pages/popup/Popup.test.tsx +++ b/src/pages/popup/Popup.test.tsx @@ -2,15 +2,52 @@ import { describe, it, expect, vi, beforeEach } from 'vitest'; import { render, screen, waitFor } from '@testing-library/react'; import Popup from './Popup'; -// Mock chrome.storage -const mockStorage = { - apiKeys: [], +// Mock chrome.storage with new APIKeyItem fields +const mockStorageWithApiKeys = { + apiKeys: [ + { + id: '1', + provider: 'DeepSeek', + name: 'DeepSeek API', + url: 'https://api.deepseek.com', + key: 'test-key-deepseek', + displayOrder: 2, + }, + { + id: '2', + provider: 'OpenAI', + name: 'OpenAI API', + url: 'https://api.openai.com', + key: 'test-key-openai', + displayOrder: 0, + }, + { + id: '3', + provider: 'Ollama', + name: 'Local Ollama', + url: 'http://localhost:11434', + key: 'test-key-ollama', + displayOrder: 1, + }, + ], prompts: [ { id: '1', name: 'Summary', content: 'Summarize: {{text}}', createdAt: 0, updatedAt: 0 }, { id: '2', name: 'Translate', content: 'Translate: {{text}}', createdAt: 0, updatedAt: 0 }, ], selectedProvider: 'DeepSeek', selectedPromptId: '1', + disabledSites: [], +}; + +// Mock chrome.storage without apiKeys (fallback to PROVIDERS) +const mockStorageWithoutApiKeys = { + apiKeys: [], + prompts: [ + { id: '1', name: 'Summary', content: 'Summarize: {{text}}', createdAt: 0, updatedAt: 0 }, + ], + selectedProvider: 'DeepSeek', + selectedPromptId: '1', + disabledSites: [], }; // Mock chrome.tabs @@ -29,13 +66,6 @@ const mockNotes = [ describe('Popup', () => { beforeEach(() => { vi.clearAllMocks(); - // Setup default mocks - vi.mocked(chrome.storage.local.get).mockImplementation((keys, callback) => { - callback(mockStorage); - }); - vi.mocked(chrome.storage.local.set).mockImplementation((data, callback) => { - if (callback) callback(); - }); // Mock chrome.tabs.query (chrome.tabs as unknown as Record).query = vi .fn() @@ -60,47 +90,189 @@ describe('Popup', () => { ); }); - it('renders provider and prompt selectors', async () => { - render(); + describe('Provider Selection', () => { + it('renders provider selector with sorted providers (by displayOrder)', async () => { + // Setup mock with apiKeys + vi.mocked(chrome.storage.local.get).mockImplementation((keys, callback) => { + callback(mockStorageWithApiKeys); + }); + vi.mocked(chrome.storage.local.set).mockImplementation((data, callback) => { + if (callback) callback(); + }); + + render(); + + await waitFor(() => { + const providerSelect = screen.getByLabelText(/provider/i) as HTMLSelectElement; + expect(providerSelect).toBeInTheDocument(); + + // OpenAI should be first (displayOrder: 0) + // Ollama should be second (displayOrder: 1) + // DeepSeek should be third (displayOrder: 2) + // Now uses 'id' as value, 'name' as display + const options = providerSelect.querySelectorAll('option'); + expect(options[0].textContent).toBe('OpenAI API'); + expect(options[0].value).toBe('2'); // id='2' (OpenAI) + expect(options[1].textContent).toBe('Local Ollama'); + expect(options[1].value).toBe('3'); // id='3' (Ollama) + expect(options[2].textContent).toBe('DeepSeek API'); + expect(options[2].value).toBe('1'); // id='1' (DeepSeek) + }); + }); + + it('falls back to PROVIDERS array when no apiKeys configured', async () => { + vi.mocked(chrome.storage.local.get).mockImplementation((keys, callback) => { + callback(mockStorageWithoutApiKeys); + }); + vi.mocked(chrome.storage.local.set).mockImplementation((data, callback) => { + if (callback) callback(); + }); + + render(); + + await waitFor(() => { + const providerSelect = screen.getByLabelText(/provider/i) as HTMLSelectElement; + expect(providerSelect).toBeInTheDocument(); - await waitFor(() => { - expect(screen.getByLabelText(/provider/i)).toBeInTheDocument(); - expect(screen.getByLabelText(/prompt template/i)).toBeInTheDocument(); + // Should use default PROVIDERS order: OpenAI, DeepSeek, SiliconFlow, TogetherAI, Ollama, Custom + // When no apiKeys, we use PROVIDERS array with id=name for fallback + const options = providerSelect.querySelectorAll('option'); + expect(options[0].textContent).toBe('OpenAI'); + expect(options[0].value).toBe('OpenAI'); + expect(options[1].textContent).toBe('DeepSeek'); + expect(options[1].value).toBe('DeepSeek'); + expect(options[2].textContent).toBe('SiliconFlow'); + expect(options[2].value).toBe('SiliconFlow'); + expect(options[3].textContent).toBe('TogetherAI'); + expect(options[3].value).toBe('TogetherAI'); + expect(options[4].textContent).toBe('Ollama'); + expect(options[4].value).toBe('Ollama'); + expect(options[5].textContent).toBe('Custom'); + expect(options[5].value).toBe('Custom'); + }); + }); + + it('renders provider and prompt selectors', async () => { + vi.mocked(chrome.storage.local.get).mockImplementation((keys, callback) => { + callback(mockStorageWithApiKeys); + }); + vi.mocked(chrome.storage.local.set).mockImplementation((data, callback) => { + if (callback) callback(); + }); + + render(); + + await waitFor(() => { + expect(screen.getByLabelText(/provider/i)).toBeInTheDocument(); + expect(screen.getByLabelText(/prompt template/i)).toBeInTheDocument(); + }); }); }); - it('renders export button', async () => { - render(); + describe('Prompt Template Selection', () => { + it('renders prompt selector with available templates', async () => { + vi.mocked(chrome.storage.local.get).mockImplementation((keys, callback) => { + callback(mockStorageWithApiKeys); + }); + vi.mocked(chrome.storage.local.set).mockImplementation((data, callback) => { + if (callback) callback(); + }); - await waitFor(() => { - expect(screen.getByRole('button', { name: /export/i })).toBeInTheDocument(); + render(); + + await waitFor(() => { + const promptSelect = screen.getByLabelText(/prompt template/i) as HTMLSelectElement; + expect(promptSelect).toBeInTheDocument(); + + const options = promptSelect.querySelectorAll('option'); + expect(options).toHaveLength(2); + expect(options[0].textContent).toBe('Summary'); + expect(options[1].textContent).toBe('Translate'); + }); }); }); - it('disables export button when no notes selected', async () => { - // Override the mock to return no notes - (chrome.tabs as unknown as Record).sendMessage = vi - .fn() - .mockImplementation( - ( - tabId: number, - message: unknown, - optionsOrCallback: unknown, - callback: (response: { notes: [] }) => void - ) => { - if (typeof optionsOrCallback === 'function') { - optionsOrCallback({ notes: [] }); - } else if (callback) { - callback({ notes: [] }); + describe('Export Functionality', () => { + it('renders export button', async () => { + vi.mocked(chrome.storage.local.get).mockImplementation((keys, callback) => { + callback(mockStorageWithApiKeys); + }); + vi.mocked(chrome.storage.local.set).mockImplementation((data, callback) => { + if (callback) callback(); + }); + + render(); + + await waitFor(() => { + expect(screen.getByRole('button', { name: /export/i })).toBeInTheDocument(); + }); + }); + + it('disables export button when no notes selected', async () => { + vi.mocked(chrome.storage.local.get).mockImplementation((keys, callback) => { + callback(mockStorageWithApiKeys); + }); + vi.mocked(chrome.storage.local.set).mockImplementation((data, callback) => { + if (callback) callback(); + }); + // Override sendMessage to return no notes + (chrome.tabs as unknown as Record).sendMessage = vi + .fn() + .mockImplementation( + ( + tabId: number, + message: unknown, + optionsOrCallback: unknown, + callback: (response: { notes: [] }) => void + ) => { + if (typeof optionsOrCallback === 'function') { + optionsOrCallback({ notes: [] }); + } else if (callback) { + callback({ notes: [] }); + } } - } - ); + ); + + render(); + + await waitFor(() => { + const exportBtn = screen.getByRole('button', { name: /export/i }); + expect(exportBtn).toBeDisabled(); + }); + }); + }); + + describe('Site Toggle', () => { + it('renders site toggle when url is valid', async () => { + vi.mocked(chrome.storage.local.get).mockImplementation((keys, callback) => { + callback(mockStorageWithApiKeys); + }); + vi.mocked(chrome.storage.local.set).mockImplementation((data, callback) => { + if (callback) callback(); + }); - render(); + render(); - await waitFor(() => { - const exportBtn = screen.getByRole('button', { name: /export/i }); - expect(exportBtn).toBeDisabled(); + await waitFor(() => { + expect(screen.getByText(/disable on this site/i)).toBeInTheDocument(); + }); + }); + }); + + describe('Settings Button', () => { + it('renders settings button', async () => { + vi.mocked(chrome.storage.local.get).mockImplementation((keys, callback) => { + callback(mockStorageWithApiKeys); + }); + vi.mocked(chrome.storage.local.set).mockImplementation((data, callback) => { + if (callback) callback(); + }); + + render(); + + await waitFor(() => { + expect(screen.getByRole('button', { name: /settings/i })).toBeInTheDocument(); + }); }); }); }); diff --git a/src/pages/popup/Popup.tsx b/src/pages/popup/Popup.tsx index f5f5f8d..e976149 100644 --- a/src/pages/popup/Popup.tsx +++ b/src/pages/popup/Popup.tsx @@ -1,6 +1,6 @@ import React, { useState, useEffect } from 'react'; import type { NoteData } from '@pages/background/messageTypes'; -import type { PromptTemplate, StorageSchema } from '@pages/background/storage.types'; +import type { APIKeyItem, PromptTemplate, StorageSchema } from '@pages/background/storage.types'; import { PROVIDERS, DEFAULT_PROMPTS } from '@pages/background/storage.types'; import { apiConfig } from '@pages/background/config'; @@ -14,6 +14,7 @@ const STORAGE_KEYS: (keyof StorageSchema)[] = [ export default function Popup() { const [provider, setProvider] = useState('DeepSeek'); + const [apiKeys, setApiKeys] = useState([]); const [prompts, setPrompts] = useState(DEFAULT_PROMPTS); const [selectedPromptId, setSelectedPromptId] = useState('default-summary'); const [notes, setNotes] = useState([]); @@ -23,10 +24,20 @@ export default function Popup() { // eslint-disable-next-line @typescript-eslint/no-unused-vars -- used via functional setState update const [disabledSites, setDisabledSites] = useState([]); + // Get sorted providers from apiKeys with id, fallback to PROVIDERS + const sortedProviderItems = apiKeys.length > 0 + ? [...apiKeys].sort((a, b) => a.displayOrder - b.displayOrder) + : []; + // For display, use name; for selection, use id + const providerOptions = sortedProviderItems.length > 0 + ? sortedProviderItems.map((k) => ({ id: k.id, name: k.name })) + : PROVIDERS.map((p) => ({ id: p, name: p })); + useEffect(() => { // Load settings from storage chrome.storage.local.get(STORAGE_KEYS, (result: Partial) => { if (result.selectedProvider) setProvider(result.selectedProvider); + if (result.apiKeys?.length) setApiKeys(result.apiKeys); if (result.prompts?.length) setPrompts(result.prompts); if (result.selectedPromptId) setSelectedPromptId(result.selectedPromptId); if (result.disabledSites) setDisabledSites(result.disabledSites); @@ -102,9 +113,9 @@ export default function Popup() { }, []); const handleProviderChange = (e: React.ChangeEvent) => { - const newProvider = e.target.value; - setProvider(newProvider); - chrome.storage.local.set({ selectedProvider: newProvider }); + const newProviderId = e.target.value; + setProvider(newProviderId); + chrome.storage.local.set({ selectedProvider: newProviderId }); }; const handlePromptChange = (e: React.ChangeEvent) => { @@ -227,9 +238,9 @@ export default function Popup() { aria-label="Select LLM Provider" disabled={siteDisabled} > - {PROVIDERS.map((p) => ( - ))}