Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 2 additions & 2 deletions feature-task-list.json
Original file line number Diff line number Diff line change
Expand Up @@ -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"]
},
Expand Down
54 changes: 41 additions & 13 deletions src/pages/background/llmService.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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(
Expand Down Expand Up @@ -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' },
]),
});
});
Expand Down Expand Up @@ -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,
Expand All @@ -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);
});
Expand Down
145 changes: 90 additions & 55 deletions src/pages/background/llmService.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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';

/**
Expand Down Expand Up @@ -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<StorageSchema>) => {
// 检查请求是否已被新请求取代
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<void> {
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) {
Expand All @@ -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') {
// 请求被中止,不触发错误
Expand All @@ -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;
}
}
Expand All @@ -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);
}
Expand Down
7 changes: 5 additions & 2 deletions src/pages/background/storage.types.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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', () => {
Expand Down
Loading
Loading