diff --git a/.github/workflows/release.yml b/.github/workflows/release.yml new file mode 100644 index 00000000..24817651 --- /dev/null +++ b/.github/workflows/release.yml @@ -0,0 +1,117 @@ +name: Release + +on: + push: + tags: + - 'v*' + +permissions: + contents: write + +jobs: + release: + runs-on: ubuntu-latest + name: Version Sync & GitHub Release + + steps: + - name: Checkout repository + uses: actions/checkout@v4 + with: + # 需要写权限来推送版本更新 + token: ${{ secrets.GITHUB_TOKEN }} + fetch-depth: 0 # 完整历史,用于生成 changelog + + - name: Extract version from tag + id: version + run: | + TAG="${GITHUB_REF#refs/tags/}" + VERSION="${TAG#v}" + echo "tag=$TAG" >> "$GITHUB_OUTPUT" + echo "version=$VERSION" >> "$GITHUB_OUTPUT" + echo "Tag: $TAG, Version: $VERSION" + + - name: Check if release version (no pre-release suffix) + id: is_release + run: | + if [[ "${{ steps.version.outputs.tag }}" == *-* ]]; then + echo "prerelease=true" >> "$GITHUB_OUTPUT" + else + echo "prerelease=false" >> "$GITHUB_OUTPUT" + fi + + - name: Setup Node.js + uses: actions/setup-node@v4 + with: + node-version: '22' + + - name: Update package.json version + run: | + npm version "${{ steps.version.outputs.version }}" --no-git-tag-version --allow-same-version + echo "Updated package.json to ${{ steps.version.outputs.version }}" + + - name: Generate changelog + id: changelog + run: | + # 找到上一个 tag + PREV_TAG=$(git tag --sort=-v:refname | grep -E '^v[0-9]+\.[0-9]+\.[0-9]+$' | head -2 | tail -1) + + if [ -z "$PREV_TAG" ] || [ "$PREV_TAG" = "${{ steps.version.outputs.tag }}" ]; then + RANGE="HEAD" + echo "首次发版,列出所有 commit" + else + RANGE="${{ steps.version.outputs.tag }}...${PREV_TAG}" + echo "范围: $RANGE" + fi + + # 分类提取 commit + FEATS=$(git log "$RANGE" --pretty=format:"%s" --no-merges | grep -iE '^feat[:(]' | sed 's/^feat: //; s/^feat([^)]*): //' || true) + FIXES=$(git log "$RANGE" --pretty=format:"%s" --no-merges | grep -iE '^fix[:(]' | sed 's/^fix: //; s/^fix([^)]*): //' || true) + + # 组装 changelog + CHANGELOG="" + if [ -n "$FEATS" ]; then + CHANGELOG="### ✨ 新功能"$'\n' + while IFS= read -r line; do + CHANGELOG+="- ${line}"$'\n' + done <<< "$FEATS" + fi + + if [ -n "$FIXES" ]; then + [ -n "$CHANGELOG" ] && CHANGELOG+=$'\n' + CHANGELOG+="### 🛠 修复"$'\n' + while IFS= read -r line; do + CHANGELOG+="- ${line}"$'\n' + done <<< "$FIXES" + fi + + if [ -z "$CHANGELOG" ]; then + CHANGELOG="- 无重大变更" + fi + + # 写入输出 + { + echo "changelog<> "$GITHUB_OUTPUT" + + echo "Changelog:" + echo "$CHANGELOG" + + - name: Commit version update + run: | + git config user.name "github-actions[bot]" + git config user.email "github-actions[bot]@users.noreply.github.com" + git add package.json package-lock.json 2>/dev/null || true + git diff --cached --quiet || git commit -m "chore: bump version to ${{ steps.version.outputs.version }} [skip ci]" + git push origin HEAD:main + + - name: Create GitHub Release + uses: softprops/action-gh-release@v2 + with: + tag_name: ${{ steps.version.outputs.tag }} + name: ${{ steps.version.outputs.tag }} + body: | + ${{ steps.changelog.outputs.changelog }} + prerelease: ${{ steps.is_release.outputs.prerelease == 'true' }} + generate_release_notes: false diff --git a/package-lock.json b/package-lock.json index 592239a7..aec2b388 100644 --- a/package-lock.json +++ b/package-lock.json @@ -1,12 +1,12 @@ { "name": "wrong-notebook", - "version": "1.5.5", + "version": "1.5.6", "lockfileVersion": 3, "requires": true, "packages": { "": { "name": "wrong-notebook", - "version": "1.5.5", + "version": "1.5.6", "dependencies": { "@google/genai": "^1.34.0", "@next-auth/prisma-adapter": "^1.0.7", diff --git a/package.json b/package.json index a4d72a49..83d2dcf6 100644 --- a/package.json +++ b/package.json @@ -1,6 +1,6 @@ { "name": "wrong-notebook", - "version": "1.5.5", + "version": "1.5.6", "private": true, "scripts": { "dev": "next dev -H 0.0.0.0", @@ -82,4 +82,4 @@ "prisma": { "seed": "ts-node --compiler-options {\"module\":\"CommonJS\"} prisma/seed.ts" } -} \ No newline at end of file +} diff --git a/src/__tests__/unit/ai/models-route.test.ts b/src/__tests__/unit/ai/models-route.test.ts new file mode 100644 index 00000000..7725f08d --- /dev/null +++ b/src/__tests__/unit/ai/models-route.test.ts @@ -0,0 +1,205 @@ +/** + * Models Route 单元测试 + * + * 测试 /api/ai/models 端点的 Gemini 和 OpenAI 模型列表功能 + */ +import { describe, it, expect, vi, beforeEach } from 'vitest'; +import { NextRequest } from 'next/server'; + +// Mock logger +vi.mock('@/lib/logger', () => ({ + createLogger: vi.fn(() => ({ + debug: vi.fn(), + info: vi.fn(), + warn: vi.fn(), + error: vi.fn(), + box: vi.fn(), + divider: vi.fn(), + })), +})); + +const mockFetch = vi.fn(); +vi.stubGlobal('fetch', mockFetch); + +import { GET } from '@/app/api/ai/models/route'; + +function makeRequest(params: Record): NextRequest { + const url = new URL('http://localhost/api/ai/models'); + for (const [k, v] of Object.entries(params)) { + url.searchParams.set(k, v); + } + return new NextRequest(url); +} + +describe('GET /api/ai/models - Gemini provider', () => { + beforeEach(() => { + vi.clearAllMocks(); + }); + + it('应该正确获取并返回 Gemini 视觉模型列表', async () => { + mockFetch.mockResolvedValueOnce({ + ok: true, + json: async () => ({ + models: [ + { name: 'models/gemini-2.0-flash', displayName: 'Gemini 2.0 Flash' }, + { name: 'models/gemini-1.5-pro', displayName: 'Gemini 1.5 Pro' }, + { name: 'models/gemini-2.5-flash', displayName: 'Gemini 2.5 Flash' }, + ], + }), + }); + + const req = makeRequest({ provider: 'gemini', apiKey: 'test-key' }); + const res = await GET(req); + const body = await res.json(); + + expect(res.status).toBe(200); + expect(body.models).toHaveLength(3); + expect(body.models[0]).toEqual({ + id: 'gemini-2.0-flash', + name: 'gemini-2.0-flash', + owned_by: 'Google', + }); + expect(body.models[1].id).toBe('gemini-1.5-pro'); + expect(body.models[2].id).toBe('gemini-2.5-flash'); + }); + + it('应该使用自定义 baseUrl', async () => { + mockFetch.mockResolvedValueOnce({ + ok: true, + json: async () => ({ models: [] }), + }); + + const req = makeRequest({ + provider: 'gemini', + apiKey: 'my-key', + baseUrl: 'https://custom.google.com', + }); + await GET(req); + + expect(mockFetch).toHaveBeenCalledWith( + 'https://custom.google.com/v1beta/models?key=my-key', + expect.any(Object) + ); + }); + + it('应该过滤掉非视觉模型(如 embedding 和 tts 模型)', async () => { + mockFetch.mockResolvedValueOnce({ + ok: true, + json: async () => ({ + models: [ + { name: 'models/gemini-2.0-flash' }, + { name: 'models/text-embedding-004' }, + { name: 'models/gemini-1.5-pro' }, + { name: 'models/text-to-speech-01' }, + ], + }), + }); + + const req = makeRequest({ provider: 'gemini', apiKey: 'test-key' }); + const res = await GET(req); + const body = await res.json(); + + expect(body.models).toHaveLength(2); + expect(body.models.map((m: any) => m.id)).toEqual([ + 'gemini-2.0-flash', + 'gemini-1.5-pro', + ]); + }); + + it('API 返回空 models 数组时应返回空列表', async () => { + mockFetch.mockResolvedValueOnce({ + ok: true, + json: async () => ({ models: [] }), + }); + + const req = makeRequest({ provider: 'gemini', apiKey: 'test-key' }); + const res = await GET(req); + const body = await res.json(); + + expect(res.status).toBe(200); + expect(body.models).toEqual([]); + }); + + it('API 返回无 models 字段时应返回空列表', async () => { + mockFetch.mockResolvedValueOnce({ + ok: true, + json: async () => ({}), + }); + + const req = makeRequest({ provider: 'gemini', apiKey: 'test-key' }); + const res = await GET(req); + const body = await res.json(); + + expect(res.status).toBe(200); + expect(body.models).toEqual([]); + }); + + it('Gemini API 返回错误时应返回 200 和空模型列表', async () => { + mockFetch.mockResolvedValueOnce({ + ok: false, + status: 403, + text: async () => 'Forbidden', + }); + + const req = makeRequest({ provider: 'gemini', apiKey: 'bad-key' }); + const res = await GET(req); + const body = await res.json(); + + expect(res.status).toBe(200); + expect(body.models).toEqual([]); + expect(body.error).toContain('Gemini API error'); + }); + + it('缺少 apiKey 时应返回 400', async () => { + const req = makeRequest({ provider: 'gemini' }); + const res = await GET(req); + const body = await res.json(); + + expect(res.status).toBe(400); + expect(body.error).toBe('API key is required'); + }); +}); + +describe('GET /api/ai/models - OpenAI provider', () => { + beforeEach(() => { + vi.clearAllMocks(); + }); + + it('应该正确获取并返回 OpenAI 视觉模型列表', async () => { + mockFetch.mockResolvedValueOnce({ + ok: true, + json: async () => ({ + data: [ + { id: 'gpt-4o', owned_by: 'openai' }, + { id: 'gpt-4-turbo', owned_by: 'openai' }, + { id: 'text-embedding-3-small', owned_by: 'openai' }, + ], + }), + }); + + const req = makeRequest({ apiKey: 'test-key' }); + const res = await GET(req); + const body = await res.json(); + + expect(res.status).toBe(200); + expect(body.models).toHaveLength(2); + expect(body.models[0].id).toBe('gpt-4o'); + expect(body.models[1].id).toBe('gpt-4-turbo'); + }); + + it('OpenAI API 返回错误时应返回 200 和空模型列表', async () => { + mockFetch.mockResolvedValueOnce({ + ok: false, + statusText: 'Unauthorized', + status: 401, + }); + + const req = makeRequest({ apiKey: 'bad-key' }); + const res = await GET(req); + const body = await res.json(); + + expect(res.status).toBe(200); + expect(body.models).toEqual([]); + expect(body.error).toContain('API error'); + }); +}); diff --git a/src/app/api/ai/models/route.ts b/src/app/api/ai/models/route.ts index e49d753b..068426e0 100644 --- a/src/app/api/ai/models/route.ts +++ b/src/app/api/ai/models/route.ts @@ -9,6 +9,80 @@ interface ModelInfo { owned_by?: string; } +// 从模型 ID 中提取短名称 +function extractModelName(modelId: string): string { + // models/gemini-2.0-flash -> gemini-2.0-flash + return modelId.replace(/^models\//, ''); +} + +// 判断是否为支持视觉/图片输入的模型 +function isVisionModel(modelId: string): boolean { + const id = modelId.toLowerCase(); + return ( + id.includes('gemini') || // Gemini 全系列支持视觉 + id.includes('vision') || + id.includes('gpt-4o') || + id.includes('gpt-4-turbo') || + id.includes('claude-3') || + id.includes('claude-4') || + id.includes('glm-4v') + ); +} + +async function fetchGeminiModels(apiKey: string, baseUrl: string): Promise { + const url = `${baseUrl}/v1beta/models?key=${apiKey}`; + + const response = await fetch(url, { + headers: { 'Content-Type': 'application/json' }, + }); + + if (!response.ok) { + const errorText = await response.text(); + logger.error({ status: response.status, errorText }, 'Gemini models API error'); + throw new Error(`Gemini API error: ${response.status}`); + } + + const data = await response.json(); + const models = (data.models || []) + .map((m: any) => { + const id = extractModelName(m.name); + return { + id, + name: id, + owned_by: 'Google', + }; + }) + .filter((m: ModelInfo) => isVisionModel(m.id)); + + return models; +} + +async function fetchOpenAIModels(apiKey: string, baseUrl: string): Promise { + const url = `${baseUrl}/models`; + + const response = await fetch(url, { + headers: { + 'Authorization': `Bearer ${apiKey}`, + 'Content-Type': 'application/json', + }, + }); + + if (!response.ok) { + logger.error({ statusText: response.statusText }, 'OpenAI models API error'); + throw new Error(`API error: ${response.status}`); + } + + const data = await response.json(); + + return (data.data || []) + .filter((model: any) => isVisionModel(model.id)) + .map((model: any) => ({ + id: model.id, + name: model.id, + owned_by: model.owned_by, + })); +} + export async function GET(req: NextRequest) { try { const { searchParams } = new URL(req.url); @@ -23,63 +97,24 @@ export async function GET(req: NextRequest) { ); } - // Only OpenAI-compatible APIs support /v1/models - if (provider !== 'openai') { - return NextResponse.json( - { - error: 'Gemini原生API不支持模型列表功能。如果您使用OpenAI兼容的代理服务,请选择"OpenAI / Compatible"作为提供商。', - models: [] - }, - { status: 200 } // Return 200 with empty models instead of 400 - ); + let models: ModelInfo[] = []; + + if (provider === 'gemini') { + const effectiveBaseUrl = baseUrl || 'https://generativelanguage.googleapis.com'; + models = await fetchGeminiModels(apiKey, effectiveBaseUrl); + } else { + // OpenAI-compatible + const effectiveBaseUrl = baseUrl || 'https://api.openai.com/v1'; + models = await fetchOpenAIModels(apiKey, effectiveBaseUrl); } - const url = `${baseUrl || 'https://api.openai.com/v1'}/models`; + return NextResponse.json({ models }); - const response = await fetch(url, { - headers: { - 'Authorization': `Bearer ${apiKey}`, - 'Content-Type': 'application/json', - }, - }); - - if (!response.ok) { - logger.error({ statusText: response.statusText }, 'Failed to fetch models'); - return NextResponse.json( - { error: 'Failed to fetch models from API' }, - { status: response.status } - ); - } - - const data = await response.json(); - - // Filter for vision-capable models - // Common patterns: gpt-4-vision, gpt-4o, gpt-4-turbo, gemini-*-vision, claude-*-vision - const visionModels = (data.data || []) - .filter((model: any) => { - const id = model.id.toLowerCase(); - return ( - id.includes('vision') || - id.includes('gpt-4o') || - id.includes('gpt-4-turbo') || - id.includes('gemini') || - id.includes('claude-3') || - id.includes('glm-4v') - ); - }) - .map((model: any) => ({ - id: model.id, - name: model.id, - owned_by: model.owned_by, - })); - - return NextResponse.json({ models: visionModels }); - - } catch (error) { + } catch (error: any) { logger.error({ error }, 'Error fetching models'); return NextResponse.json( - { error: 'Internal server error' }, - { status: 500 } + { error: error.message || 'Internal server error', models: [] }, + { status: 200 } // Return 200 with empty models to allow manual input ); } }