🤯 LobeHub - Super-Agents on Your Team. Add super-agents to the chats your team already uses.They take on work by themselves and get better every week.
TypeScript agentagent-collaborationagent-harnessloop-engineeringmcppersonal-assistantproactive-agentskillssuper-agenttask-management
✨ feat: GitHub Copilot Provider (#11997)
Innei8676c2234849
diff --git a/locales/en-US/modelProvider.json b/locales/en-US/modelProvider.jsonindex 1e544637617..ce6806bc634 100644--- a/locales/en-US/modelProvider.json+++ b/locales/en-US/modelProvider.json@@ -176,6 +176,26 @@"providerModels.config.fetchOnClient.desc": "Client request mode will initiate session requests directly from the browser, which can improve response speed","providerModels.config.fetchOnClient.title": "Use Client Request Mode","providerModels.config.helpDoc": "Configuration Guide",+ "providerModels.config.oauth.authError": "Authorization failed. Please try again.",+ "providerModels.config.oauth.authorized": "Authorized",+ "providerModels.config.oauth.authorizedDesc": "You have connected to {{name}}. Click to disconnect.",+ "providerModels.config.oauth.cancel": "Cancel",+ "providerModels.config.oauth.codeExpired": "Authorization code has expired. Please try again.",+ "providerModels.config.oauth.connect": "Connect with {{name}}",+ "providerModels.config.oauth.connectDesc": "Click to authorize via browser. No API key required.",+ "providerModels.config.oauth.connected": "Connected",+ "providerModels.config.oauth.connecting": "Connecting...",+ "providerModels.config.oauth.copyCode": "Copy code",+ "providerModels.config.oauth.denied": "Authorization was denied. Please try again.",+ "providerModels.config.oauth.desc": "Authorize with your {{name}} account to access models through your subscription.",+ "providerModels.config.oauth.disconnect": "Disconnect",+ "providerModels.config.oauth.disconnectConfirm": "Are you sure you want to disconnect? You will need to re-authorize to use this provider.",+ "providerModels.config.oauth.enterCode": "Enter the code on the opened page:",+ "providerModels.config.oauth.openBrowser": "Open browser to authorize",+ "providerModels.config.oauth.polling": "Waiting for authorization...",+ "providerModels.config.oauth.retry": "Retry",+ "providerModels.config.oauth.serviceNote": "Service provided by {{name}}",+ "providerModels.config.oauth.title": "OAuth Authorization","providerModels.config.responsesApi.desc": "Uses OpenAI's next-generation request format specification to unlock advanced features like chain-of-thought (supported by OpenAI models only)","providerModels.config.responsesApi.title": "Use Responses API Specification","providerModels.config.waitingForMore": "More models are currently <1>planned for integration</1>, please stay tuned",diff --git a/locales/zh-CN/modelProvider.json b/locales/zh-CN/modelProvider.jsonindex 42e4d35e989..914580137cd 100644--- a/locales/zh-CN/modelProvider.json+++ b/locales/zh-CN/modelProvider.json@@ -176,6 +176,26 @@"providerModels.config.fetchOnClient.desc": "客户端请求模式将从浏览器直接发起会话请求,可提升响应速度","providerModels.config.fetchOnClient.title": "使用客户端请求模式","providerModels.config.helpDoc": "配置教程",+ "providerModels.config.oauth.authError": "授权失败,请重试。",+ "providerModels.config.oauth.authorized": "已授权",+ "providerModels.config.oauth.authorizedDesc": "你已连接到 {{name}}。点击断开连接。",+ "providerModels.config.oauth.cancel": "取消",+ "providerModels.config.oauth.codeExpired": "授权码已过期,请重试。",+ "providerModels.config.oauth.connect": "连接 {{name}}",+ "providerModels.config.oauth.connectDesc": "点击通过浏览器授权,无需 API Key。",+ "providerModels.config.oauth.connected": "已连接",+ "providerModels.config.oauth.connecting": "连接中...",+ "providerModels.config.oauth.copyCode": "复制验证码",+ "providerModels.config.oauth.denied": "授权被拒绝,请重试。",+ "providerModels.config.oauth.desc": "通过你的 {{name}} 账号授权,使用你的订阅访问模型。",+ "providerModels.config.oauth.disconnect": "断开连接",+ "providerModels.config.oauth.disconnectConfirm": "确定要断开连接吗?你需要重新授权才能使用此服务商。",+ "providerModels.config.oauth.enterCode": "请在打开的页面中输入以下验证码:",+ "providerModels.config.oauth.openBrowser": "打开浏览器授权",+ "providerModels.config.oauth.polling": "等待授权中...",+ "providerModels.config.oauth.retry": "重试",+ "providerModels.config.oauth.serviceNote": "服务由 {{name}} 提供",+ "providerModels.config.oauth.title": "OAuth 授权","providerModels.config.responsesApi.desc": "采用 OpenAI 新一代请求格式规范,解锁思维链等进阶特性 (仅 OpenAI 模型支持)","providerModels.config.responsesApi.title": "使用 Responses API 规范","providerModels.config.waitingForMore": "更多模型正在 <1>计划接入</1> 中,敬请期待",diff --git a/package.json b/package.jsonindex f375b5f5945..46abc5a09af 100644--- a/package.json+++ b/package.json@@ -215,7 +215,7 @@"@lobehub/chat-plugins-gateway": "^1.9.0","@lobehub/desktop-ipc-typings": "workspace:*","@lobehub/editor": "^3.14.0",- "@lobehub/icons": "^4.0.3",+ "@lobehub/icons": "^4.1.0","@lobehub/market-sdk": "0.29.2","@lobehub/tts": "^4.0.2","@lobehub/ui": "4.33.4",diff --git a/packages/database/src/models/__tests__/aiProvider.test.ts b/packages/database/src/models/__tests__/aiProvider.test.tsindex 9c3f4042231..e781d0a9ecd 100644--- a/packages/database/src/models/__tests__/aiProvider.test.ts+++ b/packages/database/src/models/__tests__/aiProvider.test.ts@@ -5,10 +5,10 @@ import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';import { sleep } from '@/utils/sleep';+import { getTestDB } from '../../core/getTestDB';import { aiProviders, users } from '../../schemas';import { LobeChatDatabase } from '../../type';import { AiProviderModel } from '../aiProvider';-import { getTestDB } from '../../core/getTestDB';const serverDB: LobeChatDatabase = await getTestDB();@@ -204,7 +204,7 @@ describe('AiProviderModel', () => {});describe('updateConfig', () => {- it('should update provider config with encryption', async () => {+ it('should update provider config with encryption and merge keyVaults', async () => {const providerId = 'aihubmix';await serverDB.insert(aiProviders).values({id: providerId,@@ -228,7 +228,10 @@ describe('AiProviderModel', () => {where: eq(aiProviders.id, providerId),});- expect(mockEncryptor).toHaveBeenCalledWith(JSON.stringify({ newKey: 'newValue' }));+ // Should merge existing keyVaults with new values+ expect(mockEncryptor).toHaveBeenCalledWith(+ JSON.stringify({ key: 'value', newKey: 'newValue' }),+ );expect(updated?.keyVaults).toBe('encrypted-data');expect(updated?.fetchOnClient).toBeTruthy();});@@ -251,8 +254,169 @@ describe('AiProviderModel', () => {where: eq(aiProviders.id, providerId),});+ expect(updated?.keyVaults).toBe(JSON.stringify({ key: 'value', newKey: 'newValue' }));+ });++ it('should merge keyVaults with existing values when decryptor is provided', async () => {+ const providerId = 'aihubmix';+ const existingKeyVaults = {+ apiKey: 'existing-api-key',+ oauthAccessToken: 'existing-oauth-token',+ bearerToken: 'existing-bearer-token',+ };++ await serverDB.insert(aiProviders).values({+ id: providerId,+ keyVaults: JSON.stringify(existingKeyVaults),+ name: 'AiHubMix',+ source: 'custom',+ userId,+ });++ const mockEncryptor = vi.fn().mockImplementation((s: string) => Promise.resolve(s));+ const mockDecryptor = vi+ .fn()+ .mockImplementation((s: string) => Promise.resolve(JSON.parse(s)));++ // Update only apiKey, should preserve oauthAccessToken and bearerToken+ await aiProviderModel.updateConfig(+ providerId,+ {+ keyVaults: { apiKey: 'new-api-key' },+ },+ mockEncryptor,+ mockDecryptor,+ );++ const updated = await serverDB.query.aiProviders.findFirst({+ where: eq(aiProviders.id, providerId),+ });++ const updatedKeyVaults = JSON.parse(updated?.keyVaults || '{}');+ expect(updatedKeyVaults).toEqual({+ apiKey: 'new-api-key',+ bearerToken: 'existing-bearer-token',+ oauthAccessToken: 'existing-oauth-token',+ });+ });++ it('should preserve OAuth tokens when updating non-OAuth fields', async () => {+ const providerId = 'aihubmix';+ const existingKeyVaults = {+ bearerToken: 'copilot-bearer-token',+ bearerTokenExpiresAt: '1700000000000',+ oauthAccessToken: 'ghu_oauth_token',+ };++ await serverDB.insert(aiProviders).values({+ id: providerId,+ keyVaults: JSON.stringify(existingKeyVaults),+ name: 'AiHubMix',+ source: 'custom',+ userId,+ });++ const mockEncryptor = vi.fn().mockImplementation((s: string) => Promise.resolve(s));+ const mockDecryptor = vi+ .fn()+ .mockImplementation((s: string) => Promise.resolve(JSON.parse(s)));++ // Update with empty keyVaults (simulating form submit without OAuth fields)+ await aiProviderModel.updateConfig(+ providerId,+ {+ keyVaults: {},+ fetchOnClient: true,+ },+ mockEncryptor,+ mockDecryptor,+ );++ const updated = await serverDB.query.aiProviders.findFirst({+ where: eq(aiProviders.id, providerId),+ });++ const updatedKeyVaults = JSON.parse(updated?.keyVaults || '{}');+ expect(updatedKeyVaults).toEqual(existingKeyVaults);+ expect(updated?.fetchOnClient).toBe(true);+ });++ it('should handle decryption errors gracefully and use new values only', async () => {+ const providerId = 'aihubmix';++ await serverDB.insert(aiProviders).values({+ id: providerId,+ keyVaults: 'invalid-encrypted-data',+ name: 'AiHubMix',+ source: 'custom',+ userId,+ });++ const mockEncryptor = vi.fn().mockImplementation((s: string) => Promise.resolve(s));+ const mockDecryptor = vi.fn().mockImplementation(() => {+ throw new Error('Decryption failed');+ });++ await aiProviderModel.updateConfig(+ providerId,+ {+ keyVaults: { newKey: 'newValue' },+ },+ mockEncryptor,+ mockDecryptor,+ );++ const updated = await serverDB.query.aiProviders.findFirst({+ where: eq(aiProviders.id, providerId),+ });+expect(updated?.keyVaults).toBe(JSON.stringify({ newKey: 'newValue' }));});++ it('should allow clearing OAuth tokens explicitly', async () => {+ const providerId = 'aihubmix';+ const existingKeyVaults = {+ apiKey: 'api-key',+ bearerToken: 'bearer-token',+ oauthAccessToken: 'oauth-token',+ };++ await serverDB.insert(aiProviders).values({+ id: providerId,+ keyVaults: JSON.stringify(existingKeyVaults),+ name: 'AiHubMix',+ source: 'custom',+ userId,+ });++ const mockEncryptor = vi.fn().mockImplementation((s: string) => Promise.resolve(s));+ const mockDecryptor = vi+ .fn()+ .mockImplementation((s: string) => Promise.resolve(JSON.parse(s)));++ // Explicitly set OAuth tokens to undefined to clear them+ await aiProviderModel.updateConfig(+ providerId,+ {+ keyVaults: {+ apiKey: 'api-key',+ bearerToken: undefined,+ oauthAccessToken: undefined,+ },+ },+ mockEncryptor,+ mockDecryptor,+ );++ const updated = await serverDB.query.aiProviders.findFirst({+ where: eq(aiProviders.id, providerId),+ });++ const updatedKeyVaults = JSON.parse(updated?.keyVaults || '{}');+ expect(updatedKeyVaults.apiKey).toBe('api-key');+ expect(updatedKeyVaults.bearerToken).toBeUndefined();+ expect(updatedKeyVaults.oauthAccessToken).toBeUndefined();+ });});describe('toggleProviderEnabled', () => {diff --git a/packages/database/src/models/aiProvider.ts b/packages/database/src/models/aiProvider.tsindex 460bd83a56f..7e542732794 100644--- a/packages/database/src/models/aiProvider.ts+++ b/packages/database/src/models/aiProvider.ts@@ -111,11 +111,29 @@ export class AiProviderModel {id: string,value: UpdateAiProviderConfigParams,encryptor?: EncryptUserKeyVaults,+ decryptor?: DecryptUserKeyVaults,) => {// eslint-disable-next-line unicorn/consistent-function-scopingconst defaultSerialize = (s: string) => s;const encrypt = encryptor ?? defaultSerialize;- const keyVaults = await encrypt(JSON.stringify(value.keyVaults));+ const decrypt = decryptor ?? JSON.parse;++ // Merge keyVaults with existing values to preserve OAuth tokens+ // when updating from form values that don't include them+ let mergedKeyVaults = value.keyVaults || {};++ const existing = await this.findById(id);+ if (existing?.keyVaults) {+ try {+ const existingKeyVaults = await decrypt(existing.keyVaults);+ // Merge: new values override existing, but preserve fields not in new values+ mergedKeyVaults = { ...existingKeyVaults, ...value.keyVaults };+ } catch {+ // Ignore decryption errors, use new values only+ }+ }++ const keyVaults = await encrypt(JSON.stringify(mergedKeyVaults));const commonFields = {checkModel: value.checkModel,diff --git a/packages/model-bank/package.json b/packages/model-bank/package.jsonindex ec60c01869e..56fc1bfb5b0 100644--- a/packages/model-bank/package.json+++ b/packages/model-bank/package.json@@ -27,6 +27,7 @@"./fireworksai": "./src/aiModels/fireworksai.ts","./giteeai": "./src/aiModels/giteeai.ts","./github": "./src/aiModels/github.ts",+ "./githubCopilot": "./src/aiModels/githubCopilot.ts","./google": "./src/aiModels/google.ts","./groq": "./src/aiModels/groq.ts","./lobehub": "./src/aiModels/lobehub/index.ts",diff --git a/packages/model-bank/src/aiModels/githubCopilot.ts b/packages/model-bank/src/aiModels/githubCopilot.tsnew file mode 100644index 00000000000..a4d41aa3206--- /dev/null+++ b/packages/model-bank/src/aiModels/githubCopilot.ts@@ -0,0 +1,406 @@+import { AIChatModelCard } from '../types/aiModel';++const githubCopilotChatModels: AIChatModelCard[] = [+ // OpenAI Models+ {+ abilities: {+ functionCall: true,+ vision: true,+ },+ contextWindowTokens: 128_000,+ description: 'GPT-5 mini is a compact and efficient model for various tasks.',+ displayName: 'GPT-5 mini',+ enabled: true,+ id: 'gpt-5-mini',+ maxOutput: 16_384,+ type: 'chat',+ },+ {+ abilities: {+ functionCall: true,+ vision: true,+ },+ contextWindowTokens: 128_000,+ description:+ 'GPT-4o mini is a cost-effective solution for a wide range of text and image tasks.',+ displayName: 'GPT-4o mini',+ enabled: true,+ id: 'gpt-4o-mini-2024-07-18',+ maxOutput: 4096,+ type: 'chat',+ },+ {+ abilities: {+ functionCall: true,+ vision: true,+ },+ contextWindowTokens: 128_000,+ description: 'GPT-4o is the most advanced multimodal model, handling text and image inputs.',+ displayName: 'GPT-4o',+ enabled: true,+ id: 'gpt-4o-2024-11-20',+ maxOutput: 16_384,+ type: 'chat',+ },+ {+ abilities: {+ functionCall: true,+ vision: true,+ },+ contextWindowTokens: 128_000,+ description: 'GPT-4o is the most advanced multimodal model, handling text and image inputs.',+ displayName: 'GPT-4o',+ enabled: true,+ id: 'gpt-4o-2024-08-06',+ maxOutput: 16_384,+ type: 'chat',+ },+ {+ abilities: {+ functionCall: true,+ vision: true,+ },+ contextWindowTokens: 128_000,+ description: 'GPT-4o is the most advanced multimodal model, handling text and image inputs.',+ displayName: 'GPT-4o',+ enabled: true,+ id: 'gpt-4o-2024-05-13',+ maxOutput: 16_384,+ type: 'chat',+ },+ {+ abilities: {+ functionCall: true,+ vision: true,+ },+ contextWindowTokens: 128_000,+ description: 'GPT-4o is the most advanced multimodal model, handling text and image inputs.',+ displayName: 'GPT-4o',+ enabled: true,+ id: 'gpt-4-o-preview',+ maxOutput: 16_384,+ type: 'chat',+ },+ {+ abilities: {+ functionCall: true,+ vision: true,+ },+ contextWindowTokens: 128_000,+ description: 'GPT-4o is the most advanced multimodal model, handling text and image inputs.',+ displayName: 'GPT-4o',+ enabled: true,+ id: 'gpt-4o',+ maxOutput: 16_384,+ type: 'chat',+ },+ {+ abilities: {+ functionCall: true,+ vision: true,+ },+ contextWindowTokens: 128_000,+ description:+ 'GPT-4o mini is a cost-effective solution for a wide range of text and image tasks.',+ displayName: 'GPT-4o mini',+ enabled: true,+ id: 'gpt-4o-mini',+ maxOutput: 4096,+ type: 'chat',+ },+ {+ abilities: {+ functionCall: true,+ vision: true,+ },+ contextWindowTokens: 1_047_576,+ description:+ 'GPT-4.1 is the flagship model for complex tasks, ideal for cross-domain problem solving.',+ displayName: 'GPT-4.1',+ enabled: true,+ id: 'gpt-4.1-2025-04-14',+ maxOutput: 32_768,+ type: 'chat',+ },+ {+ abilities: {+ functionCall: true,+ vision: true,+ },+ contextWindowTokens: 1_047_576,+ description:+ 'GPT-4.1 is the flagship model for complex tasks, ideal for cross-domain problem solving.',+ displayName: 'GPT-4.1',+ enabled: true,+ id: 'gpt-4.1',+ maxOutput: 32_768,+ type: 'chat',+ },+ {+ abilities: {+ functionCall: true,+ vision: true,+ },+ contextWindowTokens: 16_385,+ description: 'GPT 4 Turbo is an enhanced version with improved performance.',+ displayName: 'GPT 4 Turbo',+ enabled: true,+ id: 'gpt-4-0125-preview',+ maxOutput: 4096,+ type: 'chat',+ },+ {+ abilities: {+ functionCall: true,+ vision: true,+ },+ contextWindowTokens: 8192,+ description: 'GPT 4 is a powerful model for complex reasoning tasks.',+ displayName: 'GPT 4',+ enabled: true,+ id: 'gpt-4-0613',+ maxOutput: 4096,+ type: 'chat',+ },+ {+ abilities: {+ functionCall: true,+ vision: true,+ },+ contextWindowTokens: 8192,+ description: 'GPT 4 is a powerful model for complex reasoning tasks.',+ displayName: 'GPT 4',+ enabled: true,+ id: 'gpt-4',+ maxOutput: 4096,+ type: 'chat',+ },+ {+ abilities: {+ functionCall: true,+ },+ contextWindowTokens: 4096,+ description: 'GPT 3.5 Turbo is a fast and efficient model for various tasks.',+ displayName: 'GPT 3.5 Turbo',+ enabled: true,+ id: 'gpt-3.5-turbo-0613',+ maxOutput: 4096,+ type: 'chat',+ },+ {+ abilities: {+ functionCall: true,+ },+ contextWindowTokens: 4096,+ description: 'GPT 3.5 Turbo is a fast and efficient model for various tasks.',+ displayName: 'GPT 3.5 Turbo',+ enabled: true,+ id: 'gpt-3.5-turbo',+ maxOutput: 4096,+ type: 'chat',+ },+ {+ abilities: {+ reasoning: true,+ vision: true,+ },+ contextWindowTokens: 200_000,+ description: 'o1 is OpenAI reasoning model for complex tasks requiring broad knowledge.',+ displayName: 'o1',+ id: 'o1',+ maxOutput: 100_000,+ type: 'chat',+ },+ {+ abilities: {+ functionCall: true,+ reasoning: true,+ },+ contextWindowTokens: 200_000,+ description:+ 'o3-mini is the newest small reasoning model, delivering high intelligence at low cost.',+ displayName: 'o3-mini',+ id: 'o3-mini',+ maxOutput: 100_000,+ type: 'chat',+ },+ {+ abilities: {+ functionCall: true,+ reasoning: true,+ vision: true,+ },+ contextWindowTokens: 128_000,+ description:+ 'o4-mini is the latest small o-series model, optimized for fast, efficient reasoning.',+ displayName: 'o4-mini',+ enabled: true,+ id: 'o4-mini',+ maxOutput: 16_384,+ type: 'chat',+ },++ // Grok Models+ {+ abilities: {+ functionCall: true,+ },+ contextWindowTokens: 128_000,+ description: 'Grok Code Fast 1 is optimized for fast code generation and understanding.',+ displayName: 'Grok Code Fast 1',+ enabled: true,+ id: 'grok-code-fast-1',+ maxOutput: 8192,+ type: 'chat',+ },++ // Embedding Models (marked as chat in API)+ {+ contextWindowTokens: 8192,+ description: 'Embedding V3 small model for text embeddings.',+ displayName: 'Embedding V3 small',+ enabled: true,+ id: 'text-embedding-3-small',+ type: 'chat',+ },+ {+ contextWindowTokens: 8192,+ description: 'Embedding V3 small (Inference) model for text embeddings.',+ displayName: 'Embedding V3 small (Inference)',+ enabled: true,+ id: 'text-embedding-3-small-inference',+ type: 'chat',+ },+ {+ contextWindowTokens: 8192,+ description: 'Embedding V2 Ada model for text embeddings.',+ displayName: 'Embedding V2 Ada',+ enabled: true,+ id: 'text-embedding-ada-002',+ type: 'chat',+ },++ // Anthropic Models+ {+ abilities: {+ functionCall: true,+ vision: true,+ },+ contextWindowTokens: 200_000,+ description: 'Claude Haiku 4.5 is a fast and efficient model for various tasks.',+ displayName: 'Claude Haiku 4.5',+ enabled: true,+ id: 'claude-haiku-4.5',+ maxOutput: 8192,+ type: 'chat',+ },+ {+ abilities: {+ functionCall: true,+ vision: true,+ },+ contextWindowTokens: 90_000,+ description: 'Claude 3.5 Sonnet excels at coding, writing, and complex reasoning.',+ displayName: 'Claude 3.5 Sonnet',+ id: 'claude-3.5-sonnet',+ maxOutput: 8192,+ type: 'chat',+ },+ {+ abilities: {+ functionCall: true,+ vision: true,+ },+ contextWindowTokens: 200_000,+ description: 'Claude 3.7 Sonnet is an upgraded version with extended context and capabilities.',+ displayName: 'Claude 3.7 Sonnet',+ id: 'claude-3.7-sonnet',+ maxOutput: 16_384,+ type: 'chat',+ },+ {+ abilities: {+ functionCall: true,+ reasoning: true,+ vision: true,+ },+ contextWindowTokens: 200_000,+ description: 'Claude 3.7 Sonnet with extended thinking for complex reasoning tasks.',+ displayName: 'Claude 3.7 Sonnet (Thinking)',+ id: 'claude-3.7-sonnet-thought',+ maxOutput: 16_384,+ type: 'chat',+ },+ {+ abilities: {+ functionCall: true,+ vision: true,+ },+ contextWindowTokens: 200_000,+ description:+ 'Claude Sonnet 4 is the latest generation with improved performance across all tasks.',+ displayName: 'Claude Sonnet 4',+ enabled: true,+ id: 'claude-sonnet-4',+ maxOutput: 16_000,+ type: 'chat',+ },++ // Raptor Models+ {+ abilities: {+ functionCall: true,+ },+ contextWindowTokens: 128_000,+ description: 'Raptor mini is a preview model optimized for code-related tasks.',+ displayName: 'Raptor mini (Preview)',+ enabled: true,+ id: 'oswe-vscode-prime',+ maxOutput: 8192,+ type: 'chat',+ },+ {+ abilities: {+ functionCall: true,+ },+ contextWindowTokens: 128_000,+ description: 'Raptor mini is a preview model optimized for code-related tasks.',+ displayName: 'Raptor mini (Preview)',+ enabled: true,+ id: 'oswe-vscode-secondary',+ maxOutput: 8192,+ type: 'chat',+ },++ // Google Models+ {+ abilities: {+ functionCall: true,+ vision: true,+ },+ contextWindowTokens: 1_000_000,+ description: 'Gemini 2.0 Flash delivers fast, efficient multimodal understanding.',+ displayName: 'Gemini 2.0 Flash',+ enabled: true,+ id: 'gemini-2.0-flash-001',+ maxOutput: 8192,+ type: 'chat',+ },+ {+ abilities: {+ functionCall: true,+ reasoning: true,+ vision: true,+ },+ contextWindowTokens: 1_000_000,+ description: 'Gemini 2.5 Pro is the most capable Gemini model with advanced reasoning.',+ displayName: 'Gemini 2.5 Pro',+ id: 'gemini-2.5-pro',+ maxOutput: 64_000,+ type: 'chat',+ },+];++export const allModels = [...githubCopilotChatModels];++export default allModels;diff --git a/packages/model-bank/src/aiModels/index.ts b/packages/model-bank/src/aiModels/index.tsindex c66c3906589..7c623f22bb2 100644--- a/packages/model-bank/src/aiModels/index.ts+++ b/packages/model-bank/src/aiModels/index.ts@@ -22,6 +22,7 @@ import { default as fal } from './fal';import { default as fireworksai } from './fireworksai';import { default as giteeai } from './giteeai';import { default as github } from './github';+import { default as githubcopilot } from './githubCopilot';import { default as google } from './google';import { default as groq } from './groq';import { default as higress } from './higress';@@ -113,6 +114,7 @@ export const LOBE_DEFAULT_MODEL_LIST = buildDefaultModelList({fireworksai,giteeai,github,+ githubcopilot,google,groq,higress,@@ -185,6 +187,7 @@ export { default as fal, fluxSchnellParamsSchema } from './fal';export { default as fireworksai } from './fireworksai';export { default as giteeai } from './giteeai';export { default as github } from './github';+export { default as githubcopilot } from './githubCopilot';export { default as google } from './google';export { default as groq } from './groq';export { default as higress } from './higress';diff --git a/packages/model-bank/src/const/modelProvider.ts b/packages/model-bank/src/const/modelProvider.tsindex 18bdc52e55c..1997069656f 100644--- a/packages/model-bank/src/const/modelProvider.ts+++ b/packages/model-bank/src/const/modelProvider.ts@@ -20,6 +20,7 @@ export enum ModelProvider {FireworksAI = 'fireworksai',GiteeAI = 'giteeai',Github = 'github',+ GithubCopilot = 'githubcopilot',Google = 'google',Groq = 'groq',Higress = 'higress',diff --git a/packages/model-bank/src/modelProviders/githubCopilot.ts b/packages/model-bank/src/modelProviders/githubCopilot.tsnew file mode 100644index 00000000000..f839ba7df85--- /dev/null+++ b/packages/model-bank/src/modelProviders/githubCopilot.ts@@ -0,0 +1,26 @@+import { type ModelProviderCard } from '@/types/llm';++const GithubCopilot: ModelProviderCard = {+ chatModels: [],+ checkModel: 'gpt-4o',+ description: 'Access Claude, GPT, and Gemini models through your GitHub Copilot subscription.',+ id: 'githubcopilot',+ name: 'GitHub Copilot',+ settings: {+ authType: 'oauthDeviceFlow',+ oauthDeviceFlow: {+ clientId: 'Iv1.b507a08c87ecfe98',+ defaultPollingInterval: 5,+ deviceCodeEndpoint: 'https://github.com/login/device/code',+ scopes: ['read:user'],+ tokenEndpoint: 'https://github.com/login/oauth/access_token',+ tokenExchangeEndpoint: 'https://api.github.com/copilot_internal/v2/token',+ },+ sdkType: 'openai',+ showApiKey: false,+ showChecker: true,+ },+ url: 'https://github.com/features/copilot',+};++export default GithubCopilot;diff --git a/packages/model-bank/src/modelProviders/index.ts b/packages/model-bank/src/modelProviders/index.tsindex 00fe2cc8251..dc43a8903cd 100644--- a/packages/model-bank/src/modelProviders/index.ts+++ b/packages/model-bank/src/modelProviders/index.ts@@ -23,6 +23,7 @@ import FalProvider from './fal';import FireworksAIProvider from './fireworksai';import GiteeAIProvider from './giteeai';import GithubProvider from './github';+import GithubCopilotProvider from './githubCopilot';import GoogleProvider from './google';import GroqProvider from './groq';import HigressProvider from './higress';@@ -151,6 +152,7 @@ export const DEFAULT_MODEL_PROVIDER_LIST = [HuggingFaceProvider,CloudflareProvider,GithubProvider,+ GithubCopilotProvider,NewAPIProvider,BflProvider,NovitaProvider,@@ -232,6 +234,7 @@ export { default as FalProviderCard } from './fal';export { default as FireworksAIProviderCard } from './fireworksai';export { default as GiteeAIProviderCard } from './giteeai';export { default as GithubProviderCard } from './github';+export { default as GithubCopilotProviderCard } from './githubCopilot';export { default as GoogleProviderCard } from './google';export { default as GroqProviderCard } from './groq';export { default as HigressProviderCard } from './higress';diff --git a/packages/model-runtime/src/providers/githubCopilot/index.test.ts b/packages/model-runtime/src/providers/githubCopilot/index.test.tsnew file mode 100644index 00000000000..701404d4ee8--- /dev/null+++ b/packages/model-runtime/src/providers/githubCopilot/index.test.ts@@ -0,0 +1,188 @@+// @vitest-environment node+import { afterEach, describe, expect, it, vi } from 'vitest';++import { LobeGithubCopilotAI } from './index';++// Mock console.error to avoid polluting test output+vi.spyOn(console, 'error').mockImplementation(() => {});++// Mock fetch+const mockFetch = vi.fn();+global.fetch = mockFetch;++describe('LobeGithubCopilotAI', () => {+ afterEach(() => {+ vi.clearAllMocks();+ mockFetch.mockReset();+ });++ describe('constructor', () => {+ it('should throw error if no token is provided', () => {+ expect(() => new LobeGithubCopilotAI({})).toThrow();+ });++ it('should accept apiKey as PAT', () => {+ const instance = new LobeGithubCopilotAI({ apiKey: 'ghp_test_pat' });+ expect(instance.baseURL).toBe('https://api.githubcopilot.com');+ });++ it('should accept oauthAccessToken', () => {+ const instance = new LobeGithubCopilotAI({ oauthAccessToken: 'ghu_test_oauth' });+ expect(instance.baseURL).toBe('https://api.githubcopilot.com');+ });++ it('should use cached bearer token if still valid', () => {+ const futureTime = Date.now() + 600_000; // 10 minutes from now+ const instance = new LobeGithubCopilotAI({+ bearerToken: 'cached-bearer-token',+ bearerTokenExpiresAt: futureTime,+ oauthAccessToken: 'ghu_test_oauth',+ });+ expect(instance.baseURL).toBe('https://api.githubcopilot.com');+ });++ it('should not use cached bearer token if expired', () => {+ const pastTime = Date.now() - 600_000; // 10 minutes ago+ const instance = new LobeGithubCopilotAI({+ apiKey: 'ghp_fallback',+ bearerToken: 'expired-bearer-token',+ bearerTokenExpiresAt: pastTime,+ });+ expect(instance.baseURL).toBe('https://api.githubcopilot.com');+ });++ it('should prefer oauthAccessToken over apiKey', () => {+ const instance = new LobeGithubCopilotAI({+ apiKey: 'ghp_pat',+ oauthAccessToken: 'ghu_oauth',+ });+ expect(instance.baseURL).toBe('https://api.githubcopilot.com');+ });+ });++ describe('models', () => {+ it('should fetch available models successfully', async () => {+ // Mock token exchange+ mockFetch.mockResolvedValueOnce({+ json: () =>+ Promise.resolve({+ expires_at: Math.floor(Date.now() / 1000) + 3600,+ token: 'bearer-token-123',+ }),+ ok: true,+ status: 200,+ });++ // Mock models endpoint+ mockFetch.mockResolvedValueOnce({+ json: () =>+ Promise.resolve({+ data: [+ { id: 'gpt-4o', name: 'GPT-4o' },+ { id: 'claude-3.5-sonnet', name: 'Claude 3.5 Sonnet' },+ ],+ }),+ ok: true,+ status: 200,+ });++ const instance = new LobeGithubCopilotAI({ apiKey: 'ghp_test' });+ const models = await instance.models();++ expect(models).toHaveLength(2);+ expect(models[0]).toMatchObject({+ displayName: 'GPT-4o',+ enabled: true,+ id: 'gpt-4o',+ type: 'chat',+ });+ expect(models[1]).toMatchObject({+ displayName: 'Claude 3.5 Sonnet',+ enabled: true,+ id: 'claude-3.5-sonnet',+ type: 'chat',+ });+ });++ it('should use cached bearer token for models request', async () => {+ const futureTime = Date.now() + 600_000;++ // Mock models endpoint only (no token exchange needed)+ mockFetch.mockResolvedValueOnce({+ json: () =>+ Promise.resolve({+ data: [{ id: 'gpt-4o', name: 'GPT-4o' }],+ }),+ ok: true,+ status: 200,+ });++ const instance = new LobeGithubCopilotAI({+ bearerToken: 'cached-bearer-token',+ bearerTokenExpiresAt: futureTime,+ oauthAccessToken: 'ghu_oauth',+ });++ const models = await instance.models();++ // Should only call fetch once for models (no token exchange)+ expect(mockFetch).toHaveBeenCalledTimes(1);+ expect(mockFetch).toHaveBeenCalledWith(+ 'https://api.githubcopilot.com/models',+ expect.objectContaining({+ headers: expect.objectContaining({+ Authorization: 'Bearer cached-bearer-token',+ }),+ }),+ );+ expect(models).toHaveLength(1);+ });++ it('should handle empty models response', async () => {+ // Mock token exchange+ mockFetch.mockResolvedValueOnce({+ json: () =>+ Promise.resolve({+ expires_at: Math.floor(Date.now() / 1000) + 3600,+ token: 'bearer-token-123',+ }),+ ok: true,+ status: 200,+ });++ // Mock empty models response+ mockFetch.mockResolvedValueOnce({+ json: () => Promise.resolve({}),+ ok: true,+ status: 200,+ });++ const instance = new LobeGithubCopilotAI({ apiKey: 'ghp_test' });+ const models = await instance.models();++ expect(models).toEqual([]);+ });+ });++ describe('error handling in constructor', () => {+ it('should throw InvalidGithubCopilotToken when no credentials provided', () => {+ expect(() => new LobeGithubCopilotAI({})).toThrow();+ });++ it('should throw with descriptive message', () => {+ try {+ new LobeGithubCopilotAI({});+ expect.fail('Should have thrown');+ } catch (error: any) {+ expect(error.errorType).toBe('InvalidGithubCopilotToken');+ }+ });+ });++ describe('baseURL', () => {+ it('should have correct base URL', () => {+ const instance = new LobeGithubCopilotAI({ apiKey: 'test' });+ expect(instance.baseURL).toBe('https://api.githubcopilot.com');+ });+ });+});diff --git a/packages/model-runtime/src/providers/githubCopilot/index.ts b/packages/model-runtime/src/providers/githubCopilot/index.tsnew file mode 100644index 00000000000..cdeb5fdfc5a--- /dev/null+++ b/packages/model-runtime/src/providers/githubCopilot/index.ts@@ -0,0 +1,321 @@+import type { ChatModelCard } from '@lobechat/types';+import { ModelProvider } from 'model-bank';+import OpenAI from 'openai';++import { LobeRuntimeAI } from '../../core/BaseAI';+import { pruneReasoningPayload } from '../../core/contextBuilders/openai';+import { OpenAIStream } from '../../core/streams';+import { ChatMethodOptions, ChatStreamPayload } from '../../types';+import { AgentRuntimeErrorType } from '../../types/error';+import { AgentRuntimeError } from '../../utils/createError';+import { StreamingResponse } from '../../utils/response';++const COPILOT_BASE_URL = 'https://api.githubcopilot.com';+const TOKEN_EXCHANGE_URL = 'https://api.github.com/copilot_internal/v2/token';++const MAX_TOTAL_ATTEMPTS = 5;+const MAX_AUTH_REFRESH = 1;+const MAX_RATE_LIMIT_RETRIES = 3;++interface CachedToken {+ expiresAt: number;+ token: string;+}++class CopilotTokenManager {+ private cache = new Map<string, CachedToken>();+ private pendingRefresh = new Map<string, Promise<string>>();++ async getToken(githubToken: string): Promise<string> {+ const cacheKey = this.hashToken(githubToken);+ const cached = this.cache.get(cacheKey);++ // Check if cache is valid (refresh 5 minutes early)+ if (cached && Date.now() < cached.expiresAt - 300_000) {+ return cached.token;+ }++ // Avoid concurrent refresh for the same PAT+ const pending = this.pendingRefresh.get(cacheKey);+ if (pending) return pending;++ const refreshPromise = this.exchangeToken(githubToken, cacheKey);+ this.pendingRefresh.set(cacheKey, refreshPromise);++ try {+ return await refreshPromise;+ } finally {+ this.pendingRefresh.delete(cacheKey);+ }+ }++ invalidate(githubToken: string): void {+ const cacheKey = this.hashToken(githubToken);+ this.cache.delete(cacheKey);+ }++ private hashToken(token: string): string {+ // Simple hash using last 8 characters to avoid storing full token+ return token.slice(-8);+ }++ private async exchangeToken(githubToken: string, cacheKey: string): Promise<string> {+ const response = await fetch(TOKEN_EXCHANGE_URL, {+ headers: {+ 'Accept': 'application/json',+ 'Authorization': `Token ${githubToken}`,+ 'User-Agent': 'LobeChat/1.0',+ },+ method: 'GET',+ });++ if (response.status === 401) {+ throw AgentRuntimeError.createError(AgentRuntimeErrorType.InvalidGithubCopilotToken, {+ message: 'Invalid GitHub Personal Access Token',+ });+ }+ if (response.status === 403) {+ throw AgentRuntimeError.createError(AgentRuntimeErrorType.PermissionDenied, {+ message: 'No GitHub Copilot subscription or access denied',+ });+ }+ if (!response.ok) {+ throw AgentRuntimeError.createError(AgentRuntimeErrorType.ProviderBizError, {+ message: `Token exchange failed: ${response.status} ${response.statusText}`,+ });+ }++ const data = await response.json();+ if (!data?.token || typeof data.expires_at !== 'number') {+ throw AgentRuntimeError.createError(AgentRuntimeErrorType.ProviderBizError, {+ message: 'Invalid token response format',+ });+ }++ this.cache.set(cacheKey, {+ expiresAt: data.expires_at * 1000,+ token: data.token,+ });++ return data.token;+ }+}++// Singleton token manager+const tokenManager = new CopilotTokenManager();++export interface LobeGithubCopilotAIParams {+ apiKey?: string;+ /**+ * Cached bearer token from previous OAuth exchange+ */+ bearerToken?: string;+ /**+ * Bearer token expiration timestamp (ms)+ */+ bearerTokenExpiresAt?: number;+ /**+ * OAuth access token (e.g., GitHub's ghu_xxx)+ */+ oauthAccessToken?: string;+}++export class LobeGithubCopilotAI implements LobeRuntimeAI {+ baseURL = COPILOT_BASE_URL;+ private cachedBearerToken?: string;+ private githubToken: string;++ constructor({+ apiKey,+ oauthAccessToken,+ bearerToken,+ bearerTokenExpiresAt,+ }: LobeGithubCopilotAIParams = {}) {+ // Priority 1: Use cached bearer token if still valid (refresh 5 minutes early)+ if (bearerToken && bearerTokenExpiresAt && Date.now() < bearerTokenExpiresAt - 300_000) {+ this.cachedBearerToken = bearerToken;+ this.githubToken = oauthAccessToken || apiKey || '';+ }+ // Priority 2: Use OAuth access token for exchange+ else if (oauthAccessToken) {+ this.githubToken = oauthAccessToken;+ }+ // Priority 3: Use traditional PAT+ else if (apiKey) {+ this.githubToken = apiKey;+ } else {+ throw AgentRuntimeError.createError(AgentRuntimeErrorType.InvalidGithubCopilotToken, {+ message: 'GitHub Personal Access Token or OAuth token is required',+ });+ }+ }++ async chat(payload: ChatStreamPayload, options?: ChatMethodOptions) {+ return this.executeWithRetry(async () => {+ // Use cached bearer token if available, otherwise exchange+ const bearerToken = this.cachedBearerToken || (await tokenManager.getToken(this.githubToken));++ const client = new OpenAI({+ apiKey: bearerToken,+ baseURL: COPILOT_BASE_URL,+ defaultHeaders: {+ 'Copilot-Integration-Id': 'vscode-chat',+ 'Editor-Plugin-Version': 'LobeChat/1.0',+ 'Editor-Version': 'LobeChat/1.0',+ },+ });++ const { model, ...rest } = this.handlePayload(payload);+ const shouldStream = rest.stream !== false;++ const response = await client.chat.completions.create(+ { ...rest, model, stream: shouldStream } as OpenAI.ChatCompletionCreateParamsStreaming,+ { signal: options?.signal },+ );++ return StreamingResponse(+ OpenAIStream(response, {+ callbacks: options?.callback,+ payload: { model, provider: ModelProvider.GithubCopilot },+ }),+ { headers: options?.headers },+ );+ });+ }++ async models(): Promise<ChatModelCard[]> {+ return this.executeWithRetry(async () => {+ const bearerToken = this.cachedBearerToken || (await tokenManager.getToken(this.githubToken));++ const response = await fetch(`${COPILOT_BASE_URL}/models`, {+ headers: {+ 'Accept': 'application/json',+ 'Authorization': `Bearer ${bearerToken}`,+ 'Copilot-Integration-Id': 'vscode-chat',+ 'Editor-Plugin-Version': 'LobeChat/1.0',+ 'Editor-Version': 'LobeChat/1.0',+ },+ method: 'GET',+ });++ if (!response.ok) {+ throw { status: response.status };+ }++ const data = await response.json();++ // Transform Copilot models to ChatModelCard format+ return (data.models || data.data || []).map((model: any) => ({+ displayName: model.name || model.id,+ enabled: true,+ id: model.id || model.name,+ type: 'chat',+ }));+ });+ }++ private handlePayload(payload: ChatStreamPayload) {+ const { model } = payload;++ // Reasoning models: disable stream, prune unsupported params+ if (model.startsWith('o1') || model.startsWith('o3') || model.startsWith('o4')) {+ return { ...pruneReasoningPayload(payload), stream: false };+ }++ return { ...payload, stream: true };+ }++ private async executeWithRetry<T>(fn: () => Promise<T>): Promise<T> {+ let totalAttempts = 0;+ let authRefreshAttempts = 0;+ let rateLimitAttempts = 0;++ while (totalAttempts < MAX_TOTAL_ATTEMPTS) {+ totalAttempts++;++ try {+ return await fn();+ } catch (error: any) {+ const status = error?.status ?? error?.error?.status ?? error?.response?.status;++ // 401: Refresh token once+ if (status === 401 && authRefreshAttempts < MAX_AUTH_REFRESH) {+ authRefreshAttempts++;+ tokenManager.invalidate(this.githubToken);+ continue;+ }++ // 429: Rate limit retry with exponential backoff+ if (status === 429 && rateLimitAttempts < MAX_RATE_LIMIT_RETRIES) {+ rateLimitAttempts++;+ const retryAfter = this.getRetryAfterMs(error) ?? 1000 * Math.pow(2, rateLimitAttempts);++ await new Promise<void>((resolve) => {+ setTimeout(resolve, Math.min(retryAfter, 10_000));+ });+ continue;+ }++ // Map and throw+ throw this.mapError(error);+ }+ }++ throw AgentRuntimeError.chat({+ endpoint: this.baseURL,+ error: { message: 'Max retry attempts exceeded' },+ errorType: AgentRuntimeErrorType.ProviderBizError,+ provider: ModelProvider.GithubCopilot,+ });+ }++ private getRetryAfterMs(error: any): number | undefined {+ const header = error?.response?.headers?.get?.('Retry-After');+ if (header) {+ const seconds = parseInt(header, 10);+ if (!isNaN(seconds)) return seconds * 1000;+ }+ return undefined;+ }++ private mapError(error: any) {+ const status = error?.status ?? error?.error?.status;++ switch (status) {+ case 401: {+ return AgentRuntimeError.chat({+ endpoint: this.baseURL,+ error,+ errorType: AgentRuntimeErrorType.InvalidGithubCopilotToken,+ provider: ModelProvider.GithubCopilot,+ });+ }+ case 403: {+ return AgentRuntimeError.chat({+ endpoint: this.baseURL,+ error,+ errorType: AgentRuntimeErrorType.PermissionDenied,+ provider: ModelProvider.GithubCopilot,+ });+ }+ case 429: {+ return AgentRuntimeError.chat({+ endpoint: this.baseURL,+ error,+ errorType: AgentRuntimeErrorType.QuotaLimitReached,+ provider: ModelProvider.GithubCopilot,+ });+ }+ default: {+ return AgentRuntimeError.chat({+ endpoint: this.baseURL,+ error,+ errorType: AgentRuntimeErrorType.ProviderBizError,+ provider: ModelProvider.GithubCopilot,+ });+ }+ }+ }+}++export default LobeGithubCopilotAI;diff --git a/packages/model-runtime/src/providers/openai/__snapshots__/index.test.ts.snap b/packages/model-runtime/src/providers/openai/__snapshots__/index.test.ts.snapindex 5402761e24d..418d9aabfea 100644--- a/packages/model-runtime/src/providers/openai/__snapshots__/index.test.ts.snap+++ b/packages/model-runtime/src/providers/openai/__snapshots__/index.test.ts.snap@@ -274,14 +274,14 @@ exports[`LobeOpenAI > models > should get models 1`] = `"vision": false,},{- "contextWindowTokens": undefined,- "description": "",- "displayName": "gpt-3.5-turbo-0613",+ "contextWindowTokens": 4096,+ "description": "GPT 3.5 Turbo is a fast and efficient model for various tasks.",+ "displayName": "GPT 3.5 Turbo","enabled": false,- "functionCall": false,+ "functionCall": true,"id": "gpt-3.5-turbo-0613","imageOutput": false,- "maxOutput": undefined,+ "maxOutput": 4096,"pricing": undefined,"reasoning": false,"releasedAt": "2023-06-12",@@ -464,9 +464,9 @@ exports[`LobeOpenAI > models > should get models 1`] = `"vision": false,},{- "contextWindowTokens": undefined,- "description": "",- "displayName": "text-embedding-ada-002",+ "contextWindowTokens": 8192,+ "description": "Embedding V2 Ada model for text embeddings.",+ "displayName": "Embedding V2 Ada","enabled": false,"functionCall": false,"id": "text-embedding-ada-002",@@ -476,7 +476,7 @@ exports[`LobeOpenAI > models > should get models 1`] = `"reasoning": false,"releasedAt": "2022-12-16","search": false,- "type": "embedding",+ "type": "chat","video": false,"vision": false,},diff --git a/packages/model-runtime/src/runtimeMap.ts b/packages/model-runtime/src/runtimeMap.tsindex addb8da8bd6..6720ff1c969 100644--- a/packages/model-runtime/src/runtimeMap.ts+++ b/packages/model-runtime/src/runtimeMap.ts@@ -19,6 +19,7 @@ import { LobeFalAI } from './providers/fal';import { LobeFireworksAI } from './providers/fireworksai';import { LobeGiteeAI } from './providers/giteeai';import { LobeGithubAI } from './providers/github';+import { LobeGithubCopilotAI } from './providers/githubCopilot';import { LobeGoogleAI } from './providers/google';import { LobeGroq } from './providers/groq';import { LobeHigressAI } from './providers/higress';@@ -90,6 +91,7 @@ export const providerRuntimeMap = {fireworksai: LobeFireworksAI,giteeai: LobeGiteeAI,github: LobeGithubAI,+ githubcopilot: LobeGithubCopilotAI,google: LobeGoogleAI,groq: LobeGroq,higress: LobeHigressAI,diff --git a/packages/types/src/agentRuntime.ts b/packages/types/src/agentRuntime.tsindex 6dc51f26d89..7c4f63e475e 100644--- a/packages/types/src/agentRuntime.ts+++ b/packages/types/src/agentRuntime.ts@@ -24,6 +24,7 @@ export const AgentRuntimeErrorType = {StreamChunkError: 'StreamChunkError',InvalidGithubToken: 'InvalidGithubToken',+ InvalidGithubCopilotToken: 'InvalidGithubCopilotToken',ConnectionCheckFailed: 'ConnectionCheckFailed',diff --git a/packages/types/src/aiProvider.ts b/packages/types/src/aiProvider.tsindex af705e4a2b1..6a1cbb71688 100644--- a/packages/types/src/aiProvider.ts+++ b/packages/types/src/aiProvider.ts@@ -15,6 +15,70 @@ export const AiProviderSourceEnum = {} as const;export type AiProviderSourceType = (typeof AiProviderSourceEnum)[keyof typeof AiProviderSourceEnum];+/**+ * Authentication type for AI providers+ */+export const AiProviderAuthTypeEnum = {+ ApiKey: 'apiKey',+ OAuthDeviceFlow: 'oauthDeviceFlow',+} as const;++export type AiProviderAuthType =+ (typeof AiProviderAuthTypeEnum)[keyof typeof AiProviderAuthTypeEnum];++/**+ * OAuth Device Flow configuration+ */+export interface OAuthDeviceFlowConfig {+ /**+ * OAuth client ID+ */+ clientId: string;+ /**+ * Default polling interval in seconds+ * @default 5+ */+ defaultPollingInterval?: number;+ /**+ * URL to request device code+ */+ deviceCodeEndpoint: string;+ /**+ * OAuth scopes+ */+ scopes: string[];+ /**+ * URL to exchange device code for access token+ */+ tokenEndpoint: string;+ /**+ * Optional: Provider-specific token exchange endpoint (e.g., GitHub Copilot)+ */+ tokenExchangeEndpoint?: string;+}++/**+ * OAuth Device Flow tokens stored in keyVaults+ */+export interface OAuthDeviceFlowKeyVault {+ /**+ * Provider-specific bearer token (e.g., Copilot token)+ */+ bearerToken?: string;+ /**+ * Bearer token expiration timestamp (ms)+ */+ bearerTokenExpiresAt?: number;+ /**+ * OAuth access token (e.g., GitHub's ghu_xxx)+ */+ oauthAccessToken?: string;+ /**+ * OAuth token expiration timestamp (ms)+ */+ oauthTokenExpiresAt?: number;+}+/*** only when provider use different sdk* we will add a type@@ -56,6 +120,11 @@ const AiProviderSdkTypes = [] as const satisfies readonly AiProviderSDKType[];export interface AiProviderSettings {+ /**+ * Authentication type for the provider+ * @default 'apiKey'+ */+ authType?: AiProviderAuthType;/*** whether provider show browser request option by default*@@ -76,6 +145,12 @@ export interface AiProviderSettings {*/modelEditable?: boolean;+ /**+ * OAuth Device Flow configuration+ * Only used when authType is 'oauthDeviceFlow'+ */+ oauthDeviceFlow?: OAuthDeviceFlowConfig;+proxyUrl?:| {desc?: string;@@ -107,10 +182,23 @@ export interface AiProviderSettings {const ResponseAnimationType = z.enum(['smooth', 'fadeIn', 'none']);+const AiProviderAuthTypes = ['apiKey', 'oauthDeviceFlow'] as const;++const OAuthDeviceFlowConfigSchema = z.object({+ clientId: z.string(),+ defaultPollingInterval: z.number().optional(),+ deviceCodeEndpoint: z.string(),+ scopes: z.array(z.string()),+ tokenEndpoint: z.string(),+ tokenExchangeEndpoint: z.string().optional(),+});+const AiProviderSettingsSchema = z.object({+ authType: z.enum(AiProviderAuthTypes).optional(),defaultShowBrowserRequest: z.boolean().optional(),disableBrowserRequest: z.boolean().optional(),modelEditable: z.boolean().optional(),+ oauthDeviceFlow: OAuthDeviceFlowConfigSchema.optional(),proxyUrl: z.object({desc: z.string().optional(),diff --git a/packages/types/src/auth.ts b/packages/types/src/auth.tsindex a0522ba076f..3b092220991 100644--- a/packages/types/src/auth.ts+++ b/packages/types/src/auth.ts@@ -33,6 +33,13 @@ export interface ClientSecretPayload {password?: string;customHeaders?: Record<string, string>;+ /**+ * GitHub Copilot OAuth fields+ */+ oauthAccessToken?: string;+ bearerToken?: string;+ bearerTokenExpiresAt?: number;+/*** user id* in client db mode it's a uuiddiff --git a/packages/types/src/user/settings/keyVaults.ts b/packages/types/src/user/settings/keyVaults.tsindex 7467cde520d..b691361e94a 100644--- a/packages/types/src/user/settings/keyVaults.ts+++ b/packages/types/src/user/settings/keyVaults.ts@@ -43,6 +43,25 @@ export interface ComfyUIKeyVault {username?: string;}+export interface GithubCopilotKeyVault {+ /**+ * Traditional PAT (Personal Access Token)+ */+ apiKey?: string;+ /**+ * Provider-specific bearer token (Copilot API token)+ */+ bearerToken?: string;+ /**+ * Bearer token expiration timestamp (ms)+ */+ bearerTokenExpiresAt?: string;+ /**+ * OAuth access token (e.g., GitHub's ghu_xxx)+ */+ oauthAccessToken?: string;+}+export interface SearchEngineKeyVaults {searchxng?: {apiKey?: string;diff --git a/src/app/[variants]/(main)/settings/provider/features/ProviderConfig/OAuthDeviceFlowAuth/index.tsx b/src/app/[variants]/(main)/settings/provider/features/ProviderConfig/OAuthDeviceFlowAuth/index.tsxnew file mode 100644index 00000000000..4af11c8cb00--- /dev/null+++ b/src/app/[variants]/(main)/settings/provider/features/ProviderConfig/OAuthDeviceFlowAuth/index.tsx@@ -0,0 +1,369 @@+'use client';++import { CheckCircleFilled } from '@ant-design/icons';+import { ProviderIcon } from '@lobehub/icons';+import { CopyButton, Flexbox, Icon } from '@lobehub/ui';+import { App, Avatar, Button, Typography } from 'antd';+import { createStyles, cssVar } from 'antd-style';+import { ExternalLinkIcon, Loader2Icon, LogOutIcon, UnplugIcon } from 'lucide-react';+import { type ReactNode, memo, useCallback, useEffect, useRef, useState } from 'react';+import { useTranslation } from 'react-i18next';++import { lambdaQuery } from '@/libs/trpc/client';++import { useOAuthDeviceFlow } from './useOAuthDeviceFlow';++const { Text, Link } = Typography;++const useStyles = createStyles(({ css, token }) => ({+ card: css`+ overflow: hidden;++ width: 100%;+ margin-block-end: 24px;+ border: 1px solid ${token.colorBorderSecondary};+ border-radius: 12px;+ `,+ codeBox: css`+ display: flex;+ flex: 1;+ align-items: center;+ justify-content: center;++ padding-block: 16px;+ padding-inline: 24px;+ border-radius: 12px;++ font-family: monospace;+ font-size: 28px;+ font-weight: 600;+ letter-spacing: 6px;++ background: ${token.colorFillTertiary};+ `,+ content: css`+ display: flex;+ flex-direction: column;+ gap: 20px;+ align-items: center;++ margin-block: 0 40px;+ padding-inline: 48px;+ `,+ errorText: css`+ color: ${token.colorError};+ `,+ header: css`+ display: flex;+ align-items: center;+ justify-content: space-between;++ padding-block: 16px;+ padding-inline: 24px;+ border-block-end: 1px solid ${token.colorBorderSecondary};+ `,+ hero: css`+ display: flex;+ flex-direction: column;+ gap: 16px;+ align-items: center;+ justify-content: center;++ padding-block: 48px 32px;+ padding-inline: 24px;+ border-radius: 16px 16px 0 0;+ `,+ pollingHint: css`+ display: flex;+ gap: 8px;+ align-items: center;+ justify-content: center;++ padding-block: 12px;+ padding-inline: 16px;+ border-radius: 8px;++ font-size: 13px;+ color: ${token.colorTextSecondary};++ background: ${token.colorFillQuaternary};+ `,+ serviceNote: css`+ font-size: 13px;+ color: ${token.colorTextDescription};+ text-align: center;+ `,+ successBadge: css`+ display: flex;+ gap: 6px;+ align-items: center;++ font-size: 13px;+ color: ${token.colorSuccess};+ `,+ userAvatar: css`+ border: 2px solid ${token.colorBorderSecondary};+ box-shadow: 0 4px 12px ${token.colorFillSecondary};+ `,+ userInfo: css`+ display: flex;+ flex-direction: column;+ gap: 6px;+ align-items: center;+ `,+ username: css`+ font-size: 16px;+ font-weight: 600;+ color: ${token.colorText};+ `,+}));++export interface OAuthDeviceFlowAuthProps {+ extra?: ReactNode;+ name: string;+ onAuthChange?: () => void;+ providerId: string;+ title?: ReactNode;+}++const OAuthDeviceFlowAuth = memo<OAuthDeviceFlowAuthProps>(+ ({ providerId, name, onAuthChange, title, extra }) => {+ const { t } = useTranslation('modelProvider');+ const { modal } = App.useApp();+ const { styles } = useStyles();++ const [isAuthenticating, setIsAuthenticating] = useState(false);+ const hasAutoClosedRef = useRef(false);++ const utils = lambdaQuery.useUtils();++ const { data: authStatus } = lambdaQuery.oauthDeviceFlow.getAuthStatus.useQuery(+ { providerId },+ { refetchOnWindowFocus: true },+ );+ const isAuthenticated = authStatus?.isAuthenticated ?? false;+ const username = authStatus?.username;+ const avatarUrl = authStatus?.avatarUrl;++ const revokeAuth = lambdaQuery.oauthDeviceFlow.revokeAuth.useMutation({+ onSuccess: () => {+ utils.oauthDeviceFlow.getAuthStatus.invalidate({ providerId });+ onAuthChange?.();+ },+ });++ const handleSuccess = useCallback(async () => {+ // First invalidate and refetch the auth status+ await utils.oauthDeviceFlow.getAuthStatus.invalidate({ providerId });+ // Then notify parent and reset authenticating state+ onAuthChange?.();+ setIsAuthenticating(false);+ }, [onAuthChange, providerId, utils.oauthDeviceFlow.getAuthStatus]);++ const { state, deviceCodeInfo, error, startAuth, cancelAuth } = useOAuthDeviceFlow({+ onSuccess: handleSuccess,+ providerId,+ });++ const handleDisconnect = useCallback(() => {+ modal.confirm({+ centered: true,+ content: t('providerModels.config.oauth.disconnectConfirm'),+ okButtonProps: { danger: true },+ okText: t('providerModels.config.oauth.disconnect'),+ onOk: async () => {+ await revokeAuth.mutateAsync({ providerId });+ },+ title: t('providerModels.config.oauth.disconnect'),+ });+ }, [modal, providerId, revokeAuth, t]);++ const handleStartAuth = useCallback(async () => {+ hasAutoClosedRef.current = false;+ setIsAuthenticating(true);+ await startAuth();+ }, [startAuth]);++ const handleCancelAuth = useCallback(() => {+ setIsAuthenticating(false);+ cancelAuth();+ }, [cancelAuth]);++ const handleOpenBrowser = useCallback(() => {+ if (deviceCodeInfo?.verificationUri) {+ window.open(deviceCodeInfo.verificationUri, '_blank');+ }+ }, [deviceCodeInfo?.verificationUri]);++ // Reset hasAutoClosedRef when starting new auth+ useEffect(() => {+ if (state === 'success' && !hasAutoClosedRef.current) {+ hasAutoClosedRef.current = true;+ }+ }, [state]);++ // Render Hero section with provider logo+ const renderHero = () => (+ <div className={styles.hero}>+ <ProviderIcon provider={providerId} size={72} type={'avatar'} />+ </div>+ );++ // Render content based on authentication state+ const renderContent = () => {+ // Authenticated state - show user info+ // Show when authenticated and not in the middle of authenticating process+ if (isAuthenticated && !isAuthenticating) {+ return (+ <div className={styles.content}>+ <Flexbox align="center" gap={16}>+ {avatarUrl && <Avatar className={styles.userAvatar} size={56} src={avatarUrl} />}+ <div className={styles.userInfo}>+ {username && <span className={styles.username}>{username}</span>}+ <div className={styles.successBadge}>+ <CheckCircleFilled />+ <span>{t('providerModels.config.oauth.connected')}</span>+ </div>+ </div>+ </Flexbox>+ <Button+ icon={<Icon icon={LogOutIcon} />}+ loading={revokeAuth.isPending}+ onClick={handleDisconnect}+ >+ {t('providerModels.config.oauth.disconnect')}+ </Button>+ <div className={styles.serviceNote}>+ {t('providerModels.config.oauth.serviceNote', { name })}+ </div>+ </div>+ );+ }++ // Authenticating state - show device code+ if (isAuthenticating) {+ // Loading state+ if (state === 'requesting' || !deviceCodeInfo) {+ return (+ <div className={styles.content}>+ <Icon icon={Loader2Icon} size={24} spin />+ <Text type="secondary">{t('providerModels.config.oauth.connecting')}</Text>+ </div>+ );+ }++ // Error state+ if (state === 'error' && error) {+ const errorKey = `providerModels.config.oauth.${error}`;+ return (+ <div className={styles.content}>+ <Flexbox align="center" gap={8} horizontal>+ <Icon color={cssVar.colorError} icon={UnplugIcon} size={20} />+ <Text className={styles.errorText}>{t(errorKey as any)}</Text>+ </Flexbox>+ <Flexbox gap={12} style={{ width: '100%' }} width={280}>+ <Button block onClick={handleStartAuth} type="primary">+ {t('providerModels.config.oauth.retry')}+ </Button>+ <Button block onClick={handleCancelAuth} type="text">+ {t('providerModels.config.oauth.cancel')}+ </Button>+ </Flexbox>+ </div>+ );+ }++ // Device code display+ return (+ <div className={styles.content}>+ <Flexbox align="center" gap={12} style={{ width: '100%' }} width={320}>+ <Text type="secondary">{t('providerModels.config.oauth.enterCode')}</Text>+ <Flexbox align="center" gap={12} horizontal style={{ width: '100%' }}>+ <div className={styles.codeBox}>{deviceCodeInfo.userCode}</div>+ <CopyButton content={deviceCodeInfo.userCode} />+ </Flexbox>+ </Flexbox>++ <Flexbox gap={12} style={{ width: '100%' }} width={280}>+ <Button+ block+ icon={<Icon icon={ExternalLinkIcon} />}+ onClick={handleOpenBrowser}+ size="large"+ type="primary"+ >+ {t('providerModels.config.oauth.openBrowser')}+ </Button>+ </Flexbox>++ <Link+ href={deviceCodeInfo.verificationUri}+ style={{ fontSize: 13 }}+ target="_blank"+ type="secondary"+ >+ {deviceCodeInfo.verificationUri}+ </Link>++ <div className={styles.pollingHint}>+ <Icon icon={Loader2Icon} spin />+ <span>{t('providerModels.config.oauth.polling')}</span>+ </div>++ <Button onClick={handleCancelAuth} type="text">+ {t('providerModels.config.oauth.cancel')}+ </Button>+ </div>+ );+ }++ // Error state (not authenticating)+ if (state === 'error' && error) {+ const errorKey = `providerModels.config.oauth.${error}`;+ return (+ <div className={styles.content}>+ <Flexbox align="center" gap={8} horizontal>+ <Icon color={cssVar.colorError} icon={UnplugIcon} size={18} />+ <Text className={styles.errorText}>{t(errorKey as any)}</Text>+ </Flexbox>+ <Button onClick={handleStartAuth} size="large" type="primary">+ {t('providerModels.config.oauth.connect', { name })}+ </Button>+ <div className={styles.serviceNote}>+ {t('providerModels.config.oauth.serviceNote', { name })}+ </div>+ </div>+ );+ }++ // Default state - show connect button+ return (+ <div className={styles.content}>+ <Button onClick={handleStartAuth} size="large" type="primary">+ {t('providerModels.config.oauth.connect', { name })}+ </Button>+ <div className={styles.serviceNote}>+ {t('providerModels.config.oauth.serviceNote', { name })}+ </div>+ </div>+ );+ };++ return (+ <div className={styles.card}>+ {(title || extra) && (+ <div className={styles.header}>+ <div>{title}</div>+ <div>{extra}</div>+ </div>+ )}+ {renderHero()}+ {renderContent()}+ </div>+ );+ },+);++OAuthDeviceFlowAuth.displayName = 'OAuthDeviceFlowAuth';++export default OAuthDeviceFlowAuth;diff --git a/src/app/[variants]/(main)/settings/provider/features/ProviderConfig/OAuthDeviceFlowAuth/useOAuthDeviceFlow.ts b/src/app/[variants]/(main)/settings/provider/features/ProviderConfig/OAuthDeviceFlowAuth/useOAuthDeviceFlow.tsnew file mode 100644index 00000000000..fb49b719ca1--- /dev/null+++ b/src/app/[variants]/(main)/settings/provider/features/ProviderConfig/OAuthDeviceFlowAuth/useOAuthDeviceFlow.ts@@ -0,0 +1,175 @@+'use client';++import { useCallback, useEffect, useRef, useState } from 'react';++import { lambdaQuery } from '@/libs/trpc/client';++type AuthState = 'idle' | 'requesting' | 'pending_user_auth' | 'polling' | 'success' | 'error';+type PollStatus = 'pending' | 'success' | 'expired' | 'denied' | 'slow_down';++interface DeviceCodeInfo {+ deviceCode: string;+ expiresIn: number;+ interval: number;+ userCode: string;+ verificationUri: string;+}++interface UseOAuthDeviceFlowOptions {+ onSuccess?: () => void;+ providerId: string;+}++interface UseOAuthDeviceFlowResult {+ cancelAuth: () => void;+ deviceCodeInfo?: DeviceCodeInfo;+ error?: string;+ startAuth: () => Promise<void>;+ state: AuthState;+}++export function useOAuthDeviceFlow({+ providerId,+ onSuccess,+}: UseOAuthDeviceFlowOptions): UseOAuthDeviceFlowResult {+ const [state, setState] = useState<AuthState>('idle');+ const [deviceCodeInfo, setDeviceCodeInfo] = useState<DeviceCodeInfo | undefined>();+ const [error, setError] = useState<string | undefined>();++ const pollingRef = useRef<ReturnType<typeof setInterval> | null>(null);+ const expiryRef = useRef<ReturnType<typeof setTimeout> | null>(null);+ const deviceCodeRef = useRef<string | null>(null);++ const initiateDeviceCode = lambdaQuery.oauthDeviceFlow.initiateDeviceCode.useMutation();+ const pollAuthStatus = lambdaQuery.oauthDeviceFlow.pollAuthStatus.useMutation();++ const clearTimers = useCallback(() => {+ if (pollingRef.current) {+ clearInterval(pollingRef.current);+ pollingRef.current = null;+ }+ if (expiryRef.current) {+ clearTimeout(expiryRef.current);+ expiryRef.current = null;+ }+ }, []);++ const cancelAuth = useCallback(() => {+ clearTimers();+ setState('idle');+ setDeviceCodeInfo(undefined);+ setError(undefined);+ deviceCodeRef.current = null;+ }, [clearTimers]);++ const startPolling = useCallback(+ (deviceCode: string, interval: number) => {+ setState('polling');++ const poll = async () => {+ try {+ const result = await pollAuthStatus.mutateAsync({+ deviceCode,+ providerId,+ });++ const status = result.status as PollStatus;++ switch (status) {+ case 'success': {+ clearTimers();+ setState('success');+ onSuccess?.();+ break;+ }+ case 'expired': {+ clearTimers();+ setState('error');+ setError('codeExpired');+ break;+ }+ case 'denied': {+ clearTimers();+ setState('error');+ setError('denied');+ break;+ }+ case 'slow_down': {+ // Increase polling interval+ if (pollingRef.current) {+ clearInterval(pollingRef.current);+ pollingRef.current = setInterval(poll, (interval + 5) * 1000);+ }+ break;+ }+ // 'pending' - continue polling+ }+ } catch {+ clearTimers();+ setState('error');+ setError('authError');+ }+ };++ // Start polling+ pollingRef.current = setInterval(poll, interval * 1000);++ // Also poll immediately+ poll();+ },+ [clearTimers, onSuccess, pollAuthStatus, providerId],+ );++ const startAuth = useCallback(async () => {+ setError(undefined);+ setState('requesting');++ try {+ const response = await initiateDeviceCode.mutateAsync({ providerId });++ const info: DeviceCodeInfo = {+ deviceCode: response.deviceCode,+ expiresIn: response.expiresIn,+ interval: response.interval,+ userCode: response.userCode,+ verificationUri: response.verificationUri,+ };++ setDeviceCodeInfo(info);+ deviceCodeRef.current = info.deviceCode;+ setState('pending_user_auth');++ // Set expiry timer+ expiryRef.current = setTimeout(() => {+ clearTimers();+ setState('error');+ setError('codeExpired');+ }, info.expiresIn * 1000);++ // Start polling after a brief delay to give user time to see the code+ setTimeout(() => {+ if (deviceCodeRef.current === info.deviceCode) {+ startPolling(info.deviceCode, info.interval);+ }+ }, 2000);+ } catch {+ setState('error');+ setError('authError');+ }+ }, [clearTimers, initiateDeviceCode, providerId, startPolling]);++ // Cleanup on unmount+ useEffect(() => {+ return () => {+ clearTimers();+ };+ }, [clearTimers]);++ return {+ cancelAuth,+ deviceCodeInfo,+ error,+ startAuth,+ state,+ };+}diff --git a/src/app/[variants]/(main)/settings/provider/features/ProviderConfig/index.tsx b/src/app/[variants]/(main)/settings/provider/features/ProviderConfig/index.tsxindex 2f9a841aea5..bae0c45b1bb 100644--- a/src/app/[variants]/(main)/settings/provider/features/ProviderConfig/index.tsx+++ b/src/app/[variants]/(main)/settings/provider/features/ProviderConfig/index.tsx@@ -23,6 +23,7 @@ import { z } from 'zod';import { FormInput, FormPassword } from '@/components/FormInput';import { SkeletonInput, SkeletonSwitch } from '@/components/Skeleton';+import { lambdaQuery } from '@/libs/trpc/client';import { aiProviderSelectors, useAiInfraStore } from '@/store/aiInfra';import {type AiProviderDetailItem,@@ -33,6 +34,7 @@ import {import { KeyVaultsConfigKey, LLMProviderApiTokenKey, LLMProviderBaseUrlKey } from '../../const';import Checker, { type CheckErrorRender } from './Checker';import EnableSwitch from './EnableSwitch';+import OAuthDeviceFlowAuth from './OAuthDeviceFlowAuth';import UpdateProviderInfo from './UpdateProviderInfo';const prefixCls = 'ant';@@ -131,6 +133,7 @@ const ProviderConfig = memo<ProviderConfigProps>(title,}) => {const {+ authType,proxyUrl,showApiKey = true,defaultShowBrowserRequest,@@ -141,6 +144,15 @@ const ProviderConfig = memo<ProviderConfigProps>(const { t } = useTranslation('modelProvider');const [form] = Form.useForm();+ const isOAuthProvider = authType === 'oauthDeviceFlow';++ // Query OAuth authentication status (only for OAuth providers)+ const { data: oauthStatus } = lambdaQuery.oauthDeviceFlow.getAuthStatus.useQuery(+ { providerId: id },+ { enabled: isOAuthProvider, refetchOnWindowFocus: true },+ );+ const isOAuthAuthenticated = oauthStatus?.isAuthenticated ?? false;+const [data,updateAiProviderConfig,@@ -235,42 +247,51 @@ const ProviderConfig = memo<ProviderConfigProps>(const isCustom = source === AiProviderSourceEnum.Custom;- const apiKeyItem: FormItemProps[] = !showApiKey- ? []- : (apiKeyItems ?? [- {- children: isLoading ? (- <SkeletonInput />- ) : (- <FormPassword- autoComplete={'new-password'}- placeholder={t('providerModels.config.apiKey.placeholder', { name })}- suffix={- configUpdating && (- <Icon icon={Loader2Icon} spin style={{ color: cssVar.colorTextTertiary }} />- )- }- />- ),- desc: apiKeyUrl ? (- <Trans- components={[- <span key="0" />,- <span key="1" />,- <span key="2" />,- <a href={apiKeyUrl} key="3" rel="noreferrer" target="_blank" />,- ]}- i18nKey="providerModels.config.apiKey.descWithUrl"- ns={'modelProvider'}- values={{ name }}- />- ) : (- t(`providerModels.config.apiKey.desc`, { name })- ),- label: t(`providerModels.config.apiKey.title`),- name: [KeyVaultsConfigKey, LLMProviderApiTokenKey],- },- ]);+ // OAuth auth change handler+ const handleOAuthChange = useCallback(async () => {+ // Only refresh provider data, don't update with form values+ // OAuth tokens are saved directly to DB by the tRPC endpoint+ await useAiInfraStore.getState().refreshAiProviderDetail();+ await useAiInfraStore.getState().refreshAiProviderRuntimeState();+ }, []);++ const apiKeyItem: FormItemProps[] =+ !showApiKey || isOAuthProvider+ ? []+ : (apiKeyItems ?? [+ {+ children: isLoading ? (+ <SkeletonInput />+ ) : (+ <FormPassword+ autoComplete={'new-password'}+ placeholder={t('providerModels.config.apiKey.placeholder', { name })}+ suffix={+ configUpdating && (+ <Icon icon={Loader2Icon} spin style={{ color: cssVar.colorTextTertiary }} />+ )+ }+ />+ ),+ desc: apiKeyUrl ? (+ <Trans+ components={[+ <span key="0" />,+ <span key="1" />,+ <span key="2" />,+ <a href={apiKeyUrl} key="3" rel="noreferrer" target="_blank" />,+ ]}+ i18nKey="providerModels.config.apiKey.descWithUrl"+ ns={'modelProvider'}+ values={{ name }}+ />+ ) : (+ t(`providerModels.config.apiKey.desc`, { name })+ ),+ label: t(`providerModels.config.apiKey.title`),+ name: [KeyVaultsConfigKey, LLMProviderApiTokenKey],+ },+ ]);const aceGcmItem: FormItemProps = {children: (@@ -400,73 +421,92 @@ const ProviderConfig = memo<ProviderConfigProps>(].filter(Boolean) as FormItemProps[];const logoUrl = data?.logo ?? logo;- const model: FormGroupItemType = {- children: configItems,- defaultActive: true,+ // Header components - shared between OAuth card and Form+ const headerTitle = (+ <Flexbox+ align={'center'}+ gap={4}+ horizontal+ style={{+ height: 24,+ maxHeight: 24,+ ...(enabled ? {} : { filter: 'grayscale(100%)', maxHeight: 24, opacity: 0.66 }),+ }}+ >+ {isCustom ? (+ <Flexbox align={'center'} gap={8} horizontal>+ {logoUrl ? (+ <Avatar avatar={logoUrl} shape={'circle'} size={32} title={name || id} />+ ) : (+ <ProviderCombine provider={'not-exist-provider'} size={24} />+ )}+ {name}+ </Flexbox>+ ) : (+ <>+ {title ?? <ProviderCombine provider={id} size={24} />}+ <Tooltip title={t('providerModels.config.helpDoc')}>+ <a+ href={urlJoin(BASE_PROVIDER_DOC_URL, id)}+ onClick={(e) => e.stopPropagation()}+ rel="noreferrer"+ target="_blank"+ >+ <Center className={styles.help} height={20} width={20}>+ ?+ </Center>+ </a>+ </Tooltip>+ </>+ )}+ </Flexbox>+ );- extra: (- <Flexbox align={'center'} gap={8} horizontal>- {extra}+ const headerExtra = (+ <Flexbox align={'center'} gap={8} horizontal>+ {extra}+ {isCustom && <UpdateProviderInfo />}+ {canDeactivate && !(ENABLE_BUSINESS_FEATURES && id === 'lobehub') && (+ <EnableSwitch id={id} key={id} />+ )}+ </Flexbox>+ );- {isCustom && <UpdateProviderInfo />}- {canDeactivate && !(ENABLE_BUSINESS_FEATURES && id === 'lobehub') && (- <EnableSwitch id={id} key={id} />- )}- </Flexbox>- ),- title: (- <Flexbox- align={'center'}- gap={4}- horizontal- style={{- height: 24,- maxHeight: 24,- ...(enabled ? {} : { filter: 'grayscale(100%)', maxHeight: 24, opacity: 0.66 }),- }}- >- {isCustom ? (- <Flexbox align={'center'} gap={8} horizontal>- {logoUrl ? (- <Avatar avatar={logoUrl} shape={'circle'} size={32} title={name || id} />- ) : (- <ProviderCombine provider={'not-exist-provider'} size={24} />- )}- {name}- </Flexbox>- ) : (- <>- {title ?? <ProviderCombine provider={id} size={24} />}- <Tooltip title={t('providerModels.config.helpDoc')}>- <a- href={urlJoin(BASE_PROVIDER_DOC_URL, id)}- onClick={(e) => e.stopPropagation()}- rel="noreferrer"- target="_blank"- >- <Center className={styles.help} height={20} width={20}>- ?- </Center>- </a>- </Tooltip>- </>- )}- </Flexbox>- ),+ const model: FormGroupItemType = {+ children: configItems,+ defaultActive: true,+ extra: isOAuthProvider ? undefined : headerExtra,+ title: isOAuthProvider ? '' : headerTitle,};+ // For OAuth providers, only show Form when authenticated+ const shouldShowForm = !isOAuthProvider || isOAuthAuthenticated;+return (- <Form- className={cx(styles.form, className)}- form={form}- items={[model]}- onValuesChange={(_, values) => {- debouncedHandleValueChange(id, values);- }}- variant={'borderless'}- {...FORM_STYLE}- />+ <>+ {isOAuthProvider && (+ <OAuthDeviceFlowAuth+ extra={headerExtra}+ name={name || id}+ onAuthChange={handleOAuthChange}+ providerId={id}+ title={headerTitle}+ />+ )}+ {shouldShowForm && (+ <Form+ className={cx(styles.form, className)}+ form={form}+ items={[model]}+ onValuesChange={(_, values) => {+ debouncedHandleValueChange(id, values);+ }}+ variant={'borderless'}+ {...FORM_STYLE}+ />+ )}+ </>);},);diff --git a/src/locales/default/modelProvider.ts b/src/locales/default/modelProvider.tsindex 0fc9a84f575..413f06cca4b 100644--- a/src/locales/default/modelProvider.ts+++ b/src/locales/default/modelProvider.ts@@ -194,6 +194,29 @@ export default {'Client request mode will initiate session requests directly from the browser, which can improve response speed','providerModels.config.fetchOnClient.title': 'Use Client Request Mode','providerModels.config.helpDoc': 'Configuration Guide',+ 'providerModels.config.oauth.authError': 'Authorization failed. Please try again.',+ 'providerModels.config.oauth.authorized': 'Authorized',+ 'providerModels.config.oauth.authorizedDesc':+ 'You have connected to {{name}}. Click to disconnect.',+ 'providerModels.config.oauth.cancel': 'Cancel',+ 'providerModels.config.oauth.codeExpired': 'Authorization code has expired. Please try again.',+ 'providerModels.config.oauth.connect': 'Connect with {{name}}',+ 'providerModels.config.oauth.connectDesc': 'Click to authorize via browser. No API key required.',+ 'providerModels.config.oauth.connected': 'Connected',+ 'providerModels.config.oauth.connecting': 'Connecting...',+ 'providerModels.config.oauth.copyCode': 'Copy code',+ 'providerModels.config.oauth.denied': 'Authorization was denied. Please try again.',+ 'providerModels.config.oauth.desc':+ 'Authorize with your {{name}} account to access models through your subscription.',+ 'providerModels.config.oauth.disconnect': 'Disconnect',+ 'providerModels.config.oauth.disconnectConfirm':+ 'Are you sure you want to disconnect? You will need to re-authorize to use this provider.',+ 'providerModels.config.oauth.enterCode': 'Enter the code on the opened page:',+ 'providerModels.config.oauth.openBrowser': 'Open browser to authorize',+ 'providerModels.config.oauth.polling': 'Waiting for authorization...',+ 'providerModels.config.oauth.retry': 'Retry',+ 'providerModels.config.oauth.serviceNote': 'Service provided by {{name}}',+ 'providerModels.config.oauth.title': 'OAuth Authorization','providerModels.config.responsesApi.desc':"Uses OpenAI's next-generation request format specification to unlock advanced features like chain-of-thought (supported by OpenAI models only)",'providerModels.config.responsesApi.title': 'Use Responses API Specification',diff --git a/src/server/modules/ModelRuntime/index.ts b/src/server/modules/ModelRuntime/index.tsindex fe07cbe06d9..f3fec3aaffe 100644--- a/src/server/modules/ModelRuntime/index.ts+++ b/src/server/modules/ModelRuntime/index.ts@@ -7,6 +7,7 @@ import {type ClientSecretPayload,type CloudflareKeyVault,type ComfyUIKeyVault,+ type GithubCopilotKeyVault,type OpenAICompatibleKeyVault,type VertexAIKeyVault,} from '@lobechat/types';@@ -30,6 +31,7 @@ type ProviderKeyVaults = OpenAICompatibleKeyVault &AWSBedrockKeyVault &CloudflareKeyVault &ComfyUIKeyVault &+ GithubCopilotKeyVault &VertexAIKeyVault;/**@@ -128,6 +130,19 @@ export const buildPayloadFromKeyVaults = (};}+ case ModelProvider.GithubCopilot: {+ // Support both traditional PAT (apiKey) and OAuth tokens+ return {+ apiKey: keyVaults.apiKey,+ bearerToken: keyVaults.bearerToken,+ bearerTokenExpiresAt: keyVaults.bearerTokenExpiresAt+ ? Number(keyVaults.bearerTokenExpiresAt)+ : undefined,+ oauthAccessToken: keyVaults.oauthAccessToken,+ runtimeProvider,+ };+ }+default: {return {apiKey: keyVaults.apiKey,@@ -220,6 +235,16 @@ const getParamsFromPayload = (provider: string, payload: ClientSecretPayload) =>return { apiKey, baseURLOrAccountID };}+ case ModelProvider.GithubCopilot: {+ // Support both traditional PAT (apiKey) and OAuth tokens+ return {+ apiKey: payload.apiKey,+ bearerToken: payload.bearerToken,+ bearerTokenExpiresAt: payload.bearerTokenExpiresAt,+ oauthAccessToken: payload.oauthAccessToken,+ };+ }+case ModelProvider.ComfyUI: {const {COMFYUI_BASE_URL,diff --git a/src/server/routers/lambda/__tests__/aiProvider.test.ts b/src/server/routers/lambda/__tests__/aiProvider.test.tsindex 0d4670ded78..4a02f196bb4 100644--- a/src/server/routers/lambda/__tests__/aiProvider.test.ts+++ b/src/server/routers/lambda/__tests__/aiProvider.test.ts@@ -181,6 +181,7 @@ describe('aiProviderRouter', () => {mockProviderId,{ checkModel: 'gpt-4' },mockGateKeeper.encrypt,+ KeyVaultsGateKeeper.getUserKeyVaults,);});});diff --git a/src/server/routers/lambda/aiProvider.ts b/src/server/routers/lambda/aiProvider.tsindex 55f178322cc..fb85e9e4cff 100644--- a/src/server/routers/lambda/aiProvider.ts+++ b/src/server/routers/lambda/aiProvider.ts@@ -98,7 +98,12 @@ export const aiProviderRouter = router({}),).mutation(async ({ input, ctx }) => {- return ctx.aiProviderModel.updateConfig(input.id, input.value, ctx.gateKeeper.encrypt);+ return ctx.aiProviderModel.updateConfig(+ input.id,+ input.value,+ ctx.gateKeeper.encrypt,+ KeyVaultsGateKeeper.getUserKeyVaults,+ );}),updateAiProviderOrder: aiProviderProcedurediff --git a/src/server/routers/lambda/index.ts b/src/server/routers/lambda/index.tsindex dc0973bf537..73ba0402ebb 100644--- a/src/server/routers/lambda/index.ts+++ b/src/server/routers/lambda/index.ts@@ -33,6 +33,7 @@ import { knowledgeBaseRouter } from './knowledgeBase';import { marketRouter } from './market';import { messageRouter } from './message';import { notebookRouter } from './notebook';+import { oauthDeviceFlowRouter } from './oauthDeviceFlow';import { pluginRouter } from './plugin';import { ragEvalRouter } from './ragEval';import { searchRouter } from './search';@@ -74,6 +75,7 @@ export const lambdaRouter = router({market: marketRouter,message: messageRouter,notebook: notebookRouter,+ oauthDeviceFlow: oauthDeviceFlowRouter,plugin: pluginRouter,ragEval: ragEvalRouter,search: searchRouter,diff --git a/src/server/routers/lambda/oauthDeviceFlow.ts b/src/server/routers/lambda/oauthDeviceFlow.tsnew file mode 100644index 00000000000..d50f7aa6b33--- /dev/null+++ b/src/server/routers/lambda/oauthDeviceFlow.ts@@ -0,0 +1,204 @@+import { TRPCError } from '@trpc/server';+import { DEFAULT_MODEL_PROVIDER_LIST } from 'model-bank/modelProviders';+import { z } from 'zod';++import { AiProviderModel } from '@/database/models/aiProvider';+import { authedProcedure, router } from '@/libs/trpc/lambda';+import { serverDatabase } from '@/libs/trpc/lambda/middleware';+import { KeyVaultsGateKeeper } from '@/server/modules/KeyVaultsEncrypt';+import {+ GithubCopilotOAuthService,+ getOAuthService,+} from '@/server/services/oauthDeviceFlow/providers/githubCopilot';++const oauthProcedure = authedProcedure.use(serverDatabase).use(async (opts) => {+ const { ctx } = opts;+ const gateKeeper = await KeyVaultsGateKeeper.initWithEnvKey();++ return opts.next({+ ctx: {+ aiProviderModel: new AiProviderModel(ctx.serverDB, ctx.userId),+ gateKeeper,+ },+ });+});++/**+ * Get OAuth Device Flow config for a provider+ */+function getOAuthConfig(providerId: string) {+ const provider = DEFAULT_MODEL_PROVIDER_LIST.find((p) => p.id === providerId);++ if (!provider?.settings?.oauthDeviceFlow) {+ return null;+ }++ return provider.settings.oauthDeviceFlow;+}++export const oauthDeviceFlowRouter = router({+ /**+ * Get current OAuth authentication status for a provider+ */+ getAuthStatus: oauthProcedure+ .input(z.object({ providerId: z.string() }))+ .query(async ({ input, ctx }) => {+ const providerDetail = await ctx.aiProviderModel.getAiProviderById(+ input.providerId,+ KeyVaultsGateKeeper.getUserKeyVaults,+ );++ if (!providerDetail?.keyVaults) {+ return { isAuthenticated: false };+ }++ const keyVaults = providerDetail.keyVaults as Record<string, any>;++ // Check for OAuth token+ if (keyVaults.oauthAccessToken) {+ return {+ avatarUrl: keyVaults.githubAvatarUrl as string | undefined,+ expiresAt: keyVaults.oauthTokenExpiresAt || keyVaults.bearerTokenExpiresAt,+ isAuthenticated: true,+ username: keyVaults.githubUsername as string | undefined,+ };+ }++ return { isAuthenticated: false };+ }),++ /**+ * Initiate OAuth Device Flow - request a device code+ */+ initiateDeviceCode: oauthProcedure+ .input(z.object({ providerId: z.string() }))+ .mutation(async ({ input }) => {+ const config = getOAuthConfig(input.providerId);++ if (!config) {+ throw new TRPCError({+ code: 'BAD_REQUEST',+ message: `Provider ${input.providerId} does not support OAuth Device Flow`,+ });+ }++ const service = getOAuthService(input.providerId);+ const deviceCodeResponse = await service.initiateDeviceCode(config);++ return {+ deviceCode: deviceCodeResponse.deviceCode,+ expiresIn: deviceCodeResponse.expiresIn,+ interval: deviceCodeResponse.interval,+ userCode: deviceCodeResponse.userCode,+ verificationUri: deviceCodeResponse.verificationUri,+ };+ }),++ /**+ * Poll for authorization status and exchange tokens if authorized+ */+ pollAuthStatus: oauthProcedure+ .input(+ z.object({+ deviceCode: z.string(),+ providerId: z.string(),+ }),+ )+ .mutation(async ({ input, ctx }) => {+ const config = getOAuthConfig(input.providerId);++ if (!config) {+ throw new TRPCError({+ code: 'BAD_REQUEST',+ message: `Provider ${input.providerId} does not support OAuth Device Flow`,+ });+ }++ const service = getOAuthService(input.providerId);++ // For GitHub Copilot, use the specialized service+ if (input.providerId === 'githubcopilot' && service instanceof GithubCopilotOAuthService) {+ try {+ const tokens = await service.completeAuthFlow(config, input.deviceCode);++ if (!tokens) {+ // Still pending+ const pollResult = await service.pollForToken(config, input.deviceCode);+ return { status: pollResult.status };+ }++ // Save tokens and user info to keyVaults+ await ctx.aiProviderModel.updateConfig(+ input.providerId,+ {+ keyVaults: {+ bearerToken: tokens.bearerToken,+ bearerTokenExpiresAt: String(tokens.bearerTokenExpiresAt),+ githubAvatarUrl: tokens.userInfo.avatarUrl,+ githubUsername: tokens.userInfo.username,+ oauthAccessToken: tokens.oauthAccessToken,+ },+ },+ ctx.gateKeeper.encrypt,+ KeyVaultsGateKeeper.getUserKeyVaults,+ );++ return { status: 'success' as const };+ } catch {+ // Probably still pending or error+ const pollResult = await service.pollForToken(config, input.deviceCode);+ return { status: pollResult.status };+ }+ }++ // Generic OAuth flow+ const pollResult = await service.pollForToken(config, input.deviceCode);++ if (pollResult.status === 'success' && pollResult.tokens) {+ // Save tokens to keyVaults+ await ctx.aiProviderModel.updateConfig(+ input.providerId,+ {+ keyVaults: {+ oauthAccessToken: pollResult.tokens.accessToken,+ oauthTokenExpiresAt: pollResult.tokens.expiresIn+ ? String(Date.now() + pollResult.tokens.expiresIn * 1000)+ : undefined,+ },+ },+ ctx.gateKeeper.encrypt,+ KeyVaultsGateKeeper.getUserKeyVaults,+ );+ }++ return { status: pollResult.status };+ }),++ /**+ * Revoke OAuth authorization for a provider+ */+ revokeAuth: oauthProcedure+ .input(z.object({ providerId: z.string() }))+ .mutation(async ({ input, ctx }) => {+ // Clear OAuth tokens and user info from keyVaults+ await ctx.aiProviderModel.updateConfig(+ input.providerId,+ {+ keyVaults: {+ bearerToken: undefined,+ bearerTokenExpiresAt: undefined,+ githubAvatarUrl: undefined,+ githubUsername: undefined,+ oauthAccessToken: undefined,+ oauthTokenExpiresAt: undefined,+ },+ },+ ctx.gateKeeper.encrypt,+ KeyVaultsGateKeeper.getUserKeyVaults,+ );++ return { success: true };+ }),+});++export type OAuthDeviceFlowRouter = typeof oauthDeviceFlowRouter;diff --git a/src/server/services/oauthDeviceFlow/__tests__/index.test.ts b/src/server/services/oauthDeviceFlow/__tests__/index.test.tsnew file mode 100644index 00000000000..e2ee9c721b4--- /dev/null+++ b/src/server/services/oauthDeviceFlow/__tests__/index.test.ts@@ -0,0 +1,240 @@+// @vitest-environment node+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';++import { OAuthDeviceFlowService } from '../index';++// Mock fetch+const mockFetch = vi.fn();+global.fetch = mockFetch;++describe('OAuthDeviceFlowService', () => {+ let service: OAuthDeviceFlowService;++ const mockConfig = {+ clientId: 'test-client-id',+ defaultPollingInterval: 5,+ deviceCodeEndpoint: 'https://example.com/device/code',+ scopes: ['read:user'],+ tokenEndpoint: 'https://example.com/oauth/token',+ };++ beforeEach(() => {+ service = new OAuthDeviceFlowService();+ vi.clearAllMocks();+ });++ afterEach(() => {+ vi.resetAllMocks();+ });++ describe('initiateDeviceCode', () => {+ it('should successfully initiate device code flow', async () => {+ const mockResponse = {+ device_code: 'device-code-123',+ expires_in: 900,+ interval: 5,+ user_code: 'ABCD-1234',+ verification_uri: 'https://example.com/device',+ };++ mockFetch.mockResolvedValueOnce({+ json: () => Promise.resolve(mockResponse),+ ok: true,+ });++ const result = await service.initiateDeviceCode(mockConfig);++ expect(mockFetch).toHaveBeenCalledWith(+ mockConfig.deviceCodeEndpoint,+ expect.objectContaining({+ body: expect.stringContaining('client_id=test-client-id'),+ headers: {+ 'Accept': 'application/json',+ 'Content-Type': 'application/x-www-form-urlencoded',+ },+ method: 'POST',+ }),+ );++ expect(result).toEqual({+ deviceCode: 'device-code-123',+ expiresIn: 900,+ interval: 5,+ userCode: 'ABCD-1234',+ verificationUri: 'https://example.com/device',+ });+ });++ it('should use verification_url if verification_uri is not present', async () => {+ const mockResponse = {+ device_code: 'device-code-123',+ expires_in: 900,+ interval: 5,+ user_code: 'ABCD-1234',+ verification_url: 'https://example.com/device-alt',+ };++ mockFetch.mockResolvedValueOnce({+ json: () => Promise.resolve(mockResponse),+ ok: true,+ });++ const result = await service.initiateDeviceCode(mockConfig);++ expect(result.verificationUri).toBe('https://example.com/device-alt');+ });++ it('should use default polling interval if not provided', async () => {+ const mockResponse = {+ device_code: 'device-code-123',+ expires_in: 900,+ user_code: 'ABCD-1234',+ verification_uri: 'https://example.com/device',+ };++ mockFetch.mockResolvedValueOnce({+ json: () => Promise.resolve(mockResponse),+ ok: true,+ });++ const result = await service.initiateDeviceCode(mockConfig);++ expect(result.interval).toBe(5);+ });++ it('should throw error on failed request', async () => {+ mockFetch.mockResolvedValueOnce({+ ok: false,+ status: 400,+ text: () => Promise.resolve('Bad Request'),+ });++ await expect(service.initiateDeviceCode(mockConfig)).rejects.toThrow(+ 'Failed to initiate device code: 400 Bad Request',+ );+ });+ });++ describe('pollForToken', () => {+ it('should return success status with tokens on successful authorization', async () => {+ const mockResponse = {+ access_token: 'access-token-123',+ expires_in: 3600,+ refresh_token: 'refresh-token-456',+ scope: 'read:user',+ token_type: 'bearer',+ };++ mockFetch.mockResolvedValueOnce({+ json: () => Promise.resolve(mockResponse),+ ok: true,+ });++ const result = await service.pollForToken(mockConfig, 'device-code-123');++ expect(mockFetch).toHaveBeenCalledWith(+ mockConfig.tokenEndpoint,+ expect.objectContaining({+ body: expect.stringContaining('device_code=device-code-123'),+ method: 'POST',+ }),+ );++ expect(result).toEqual({+ status: 'success',+ tokens: {+ accessToken: 'access-token-123',+ expiresIn: 3600,+ refreshToken: 'refresh-token-456',+ scope: 'read:user',+ tokenType: 'bearer',+ },+ });+ });++ it('should return pending status when authorization is pending', async () => {+ mockFetch.mockResolvedValueOnce({+ json: () => Promise.resolve({ error: 'authorization_pending' }),+ ok: true,+ });++ const result = await service.pollForToken(mockConfig, 'device-code-123');++ expect(result).toEqual({ status: 'pending' });+ });++ it('should return slow_down status', async () => {+ mockFetch.mockResolvedValueOnce({+ json: () => Promise.resolve({ error: 'slow_down' }),+ ok: true,+ });++ const result = await service.pollForToken(mockConfig, 'device-code-123');++ expect(result).toEqual({ status: 'slow_down' });+ });++ it('should return expired status when token expires', async () => {+ mockFetch.mockResolvedValueOnce({+ json: () => Promise.resolve({ error: 'expired_token' }),+ ok: true,+ });++ const result = await service.pollForToken(mockConfig, 'device-code-123');++ expect(result).toEqual({ status: 'expired' });+ });++ it('should return denied status when access is denied', async () => {+ mockFetch.mockResolvedValueOnce({+ json: () => Promise.resolve({ error: 'access_denied' }),+ ok: true,+ });++ const result = await service.pollForToken(mockConfig, 'device-code-123');++ expect(result).toEqual({ status: 'denied' });+ });++ it('should throw error for unknown OAuth error', async () => {+ mockFetch.mockResolvedValueOnce({+ json: () =>+ Promise.resolve({+ error: 'unknown_error',+ error_description: 'Something went wrong',+ }),+ ok: true,+ });++ await expect(service.pollForToken(mockConfig, 'device-code-123')).rejects.toThrow(+ 'OAuth error: unknown_error - Something went wrong',+ );+ });++ it('should throw error when response has no access_token and no error', async () => {+ mockFetch.mockResolvedValueOnce({+ json: () => Promise.resolve({}),+ ok: true,+ });++ await expect(service.pollForToken(mockConfig, 'device-code-123')).rejects.toThrow(+ 'Unexpected response from token endpoint',+ );+ });++ it('should use default token_type as bearer if not provided', async () => {+ const mockResponse = {+ access_token: 'access-token-123',+ };++ mockFetch.mockResolvedValueOnce({+ json: () => Promise.resolve(mockResponse),+ ok: true,+ });++ const result = await service.pollForToken(mockConfig, 'device-code-123');++ expect(result.tokens?.tokenType).toBe('bearer');+ });+ });+});diff --git a/src/server/services/oauthDeviceFlow/__tests__/providers/githubCopilot.test.ts b/src/server/services/oauthDeviceFlow/__tests__/providers/githubCopilot.test.tsnew file mode 100644index 00000000000..fbc7ba24198--- /dev/null+++ b/src/server/services/oauthDeviceFlow/__tests__/providers/githubCopilot.test.ts@@ -0,0 +1,239 @@+// @vitest-environment node+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';++import { OAuthDeviceFlowService } from '../../index';+import { GithubCopilotOAuthService, getOAuthService } from '../../providers/githubCopilot';++// Mock fetch+const mockFetch = vi.fn();+global.fetch = mockFetch;++describe('GithubCopilotOAuthService', () => {+ let service: GithubCopilotOAuthService;++ const mockConfig = {+ clientId: 'Iv1.b507a08c87ecfe98',+ defaultPollingInterval: 5,+ deviceCodeEndpoint: 'https://github.com/login/device/code',+ scopes: ['read:user'],+ tokenEndpoint: 'https://github.com/login/oauth/access_token',+ tokenExchangeEndpoint: 'https://api.github.com/copilot_internal/v2/token',+ };++ beforeEach(() => {+ service = new GithubCopilotOAuthService();+ vi.clearAllMocks();+ });++ afterEach(() => {+ vi.resetAllMocks();+ });++ describe('exchangeForCopilotToken', () => {+ it('should successfully exchange OAuth token for Copilot token', async () => {+ const mockResponse = {+ expires_at: 1700000000,+ token: 'copilot-bearer-token-123',+ };++ mockFetch.mockResolvedValueOnce({+ json: () => Promise.resolve(mockResponse),+ ok: true,+ status: 200,+ });++ const result = await service.exchangeForCopilotToken('oauth-token-123');++ expect(mockFetch).toHaveBeenCalledWith(+ 'https://api.github.com/copilot_internal/v2/token',+ expect.objectContaining({+ headers: {+ 'Accept': 'application/json',+ 'Authorization': 'token oauth-token-123',+ 'User-Agent': 'LobeChat/1.0',+ },+ method: 'GET',+ }),+ );++ expect(result).toEqual({+ expiresAt: 1700000000 * 1000,+ token: 'copilot-bearer-token-123',+ });+ });++ it('should throw error for invalid OAuth token (401)', async () => {+ mockFetch.mockResolvedValueOnce({+ ok: false,+ status: 401,+ });++ await expect(service.exchangeForCopilotToken('invalid-token')).rejects.toThrow(+ 'Invalid GitHub OAuth token',+ );+ });++ it('should throw error for no Copilot subscription (403)', async () => {+ mockFetch.mockResolvedValueOnce({+ ok: false,+ status: 403,+ });++ await expect(service.exchangeForCopilotToken('oauth-token')).rejects.toThrow(+ 'No GitHub Copilot subscription or access denied',+ );+ });++ it('should throw error for other HTTP errors', async () => {+ mockFetch.mockResolvedValueOnce({+ ok: false,+ status: 500,+ text: () => Promise.resolve('Internal Server Error'),+ });++ await expect(service.exchangeForCopilotToken('oauth-token')).rejects.toThrow(+ 'Failed to exchange for Copilot token: 500 Internal Server Error',+ );+ });++ it('should throw error for invalid response format', async () => {+ mockFetch.mockResolvedValueOnce({+ json: () => Promise.resolve({ invalid: 'response' }),+ ok: true,+ status: 200,+ });++ await expect(service.exchangeForCopilotToken('oauth-token')).rejects.toThrow(+ 'Invalid Copilot token response format',+ );+ });++ it('should throw error if expires_at is not a number', async () => {+ mockFetch.mockResolvedValueOnce({+ json: () => Promise.resolve({ expires_at: 'not-a-number', token: 'token' }),+ ok: true,+ status: 200,+ });++ await expect(service.exchangeForCopilotToken('oauth-token')).rejects.toThrow(+ 'Invalid Copilot token response format',+ );+ });+ });++ describe('completeAuthFlow', () => {+ it('should complete full auth flow successfully', async () => {+ // Mock pollForToken response+ mockFetch.mockResolvedValueOnce({+ json: () =>+ Promise.resolve({+ access_token: 'oauth-access-token-123',+ token_type: 'bearer',+ }),+ ok: true,+ });++ // Mock exchangeForCopilotToken response+ mockFetch.mockResolvedValueOnce({+ json: () =>+ Promise.resolve({+ expires_at: 1700000000,+ token: 'copilot-bearer-token-123',+ }),+ ok: true,+ status: 200,+ });++ // Mock fetchUserInfo response+ mockFetch.mockResolvedValueOnce({+ json: () =>+ Promise.resolve({+ avatar_url: 'https://avatars.githubusercontent.com/u/123',+ login: 'testuser',+ }),+ ok: true,+ status: 200,+ });++ const result = await service.completeAuthFlow(mockConfig, 'device-code-123');++ expect(result).toEqual({+ bearerToken: 'copilot-bearer-token-123',+ bearerTokenExpiresAt: 1700000000 * 1000,+ oauthAccessToken: 'oauth-access-token-123',+ userInfo: {+ avatarUrl: 'https://avatars.githubusercontent.com/u/123',+ username: 'testuser',+ },+ });+ });++ it('should return null when poll returns pending status', async () => {+ mockFetch.mockResolvedValueOnce({+ json: () => Promise.resolve({ error: 'authorization_pending' }),+ ok: true,+ });++ const result = await service.completeAuthFlow(mockConfig, 'device-code-123');++ expect(result).toBeNull();+ });++ it('should return null when poll returns expired status', async () => {+ mockFetch.mockResolvedValueOnce({+ json: () => Promise.resolve({ error: 'expired_token' }),+ ok: true,+ });++ const result = await service.completeAuthFlow(mockConfig, 'device-code-123');++ expect(result).toBeNull();+ });++ it('should return null when poll returns denied status', async () => {+ mockFetch.mockResolvedValueOnce({+ json: () => Promise.resolve({ error: 'access_denied' }),+ ok: true,+ });++ const result = await service.completeAuthFlow(mockConfig, 'device-code-123');++ expect(result).toBeNull();+ });+ });++ describe('refreshCopilotToken', () => {+ it('should refresh Copilot token using existing OAuth token', async () => {+ const mockResponse = {+ expires_at: 1700000000,+ token: 'new-copilot-bearer-token',+ };++ mockFetch.mockResolvedValueOnce({+ json: () => Promise.resolve(mockResponse),+ ok: true,+ status: 200,+ });++ const result = await service.refreshCopilotToken('oauth-token-123');++ expect(result).toEqual({+ expiresAt: 1700000000 * 1000,+ token: 'new-copilot-bearer-token',+ });+ });+ });+});++describe('getOAuthService', () => {+ it('should return GithubCopilotOAuthService for githubcopilot provider', () => {+ const service = getOAuthService('githubcopilot');+ expect(service).toBeInstanceOf(GithubCopilotOAuthService);+ });++ it('should return base OAuthDeviceFlowService for other providers', () => {+ const service = getOAuthService('other-provider');+ expect(service).toBeInstanceOf(OAuthDeviceFlowService);+ expect(service).not.toBeInstanceOf(GithubCopilotOAuthService);+ });+});diff --git a/src/server/services/oauthDeviceFlow/index.ts b/src/server/services/oauthDeviceFlow/index.tsnew file mode 100644index 00000000000..bb8299a54c6--- /dev/null+++ b/src/server/services/oauthDeviceFlow/index.ts@@ -0,0 +1,115 @@+import { type OAuthDeviceFlowConfig } from '@/types/aiProvider';++export interface DeviceCodeResponse {+ deviceCode: string;+ expiresIn: number;+ interval: number;+ userCode: string;+ verificationUri: string;+}++export interface TokenResponse {+ accessToken: string;+ expiresIn?: number;+ refreshToken?: string;+ scope?: string;+ tokenType: string;+}++export type PollStatus = 'pending' | 'success' | 'expired' | 'denied' | 'slow_down';++export interface PollResult {+ status: PollStatus;+ tokens?: TokenResponse;+}++export class OAuthDeviceFlowService {+ /**+ * Initiate OAuth Device Flow by requesting a device code+ */+ async initiateDeviceCode(config: OAuthDeviceFlowConfig): Promise<DeviceCodeResponse> {+ const response = await fetch(config.deviceCodeEndpoint, {+ body: new URLSearchParams({+ client_id: config.clientId,+ scope: config.scopes.join(' '),+ }).toString(),+ headers: {+ 'Accept': 'application/json',+ 'Content-Type': 'application/x-www-form-urlencoded',+ },+ method: 'POST',+ });++ if (!response.ok) {+ const errorText = await response.text();+ throw new Error(`Failed to initiate device code: ${response.status} ${errorText}`);+ }++ const data = await response.json();++ return {+ deviceCode: data.device_code,+ expiresIn: data.expires_in,+ interval: data.interval ?? config.defaultPollingInterval ?? 5,+ userCode: data.user_code,+ verificationUri: data.verification_uri || data.verification_url,+ };+ }++ /**+ * Poll for authorization status+ */+ async pollForToken(config: OAuthDeviceFlowConfig, deviceCode: string): Promise<PollResult> {+ const response = await fetch(config.tokenEndpoint, {+ body: new URLSearchParams({+ client_id: config.clientId,+ device_code: deviceCode,+ grant_type: 'urn:ietf:params:oauth:grant-type:device_code',+ }).toString(),+ headers: {+ 'Accept': 'application/json',+ 'Content-Type': 'application/x-www-form-urlencoded',+ },+ method: 'POST',+ });++ const data = await response.json();++ // Handle OAuth error responses+ if (data.error) {+ switch (data.error) {+ case 'authorization_pending': {+ return { status: 'pending' };+ }+ case 'slow_down': {+ return { status: 'slow_down' };+ }+ case 'expired_token': {+ return { status: 'expired' };+ }+ case 'access_denied': {+ return { status: 'denied' };+ }+ default: {+ throw new Error(`OAuth error: ${data.error} - ${data.error_description || ''}`);+ }+ }+ }++ // Success: access_token received+ if (data.access_token) {+ return {+ status: 'success',+ tokens: {+ accessToken: data.access_token,+ expiresIn: data.expires_in,+ refreshToken: data.refresh_token,+ scope: data.scope,+ tokenType: data.token_type || 'bearer',+ },+ };+ }++ throw new Error('Unexpected response from token endpoint');+ }+}diff --git a/src/server/services/oauthDeviceFlow/providers/githubCopilot.ts b/src/server/services/oauthDeviceFlow/providers/githubCopilot.tsnew file mode 100644index 00000000000..e08a0f5f709--- /dev/null+++ b/src/server/services/oauthDeviceFlow/providers/githubCopilot.ts@@ -0,0 +1,135 @@+import { type OAuthDeviceFlowConfig } from '@/types/aiProvider';++import { OAuthDeviceFlowService } from '../index';++export interface CopilotTokenResponse {+ expiresAt: number;+ token: string;+}++export interface GithubUserInfo {+ avatarUrl: string;+ username: string;+}++export interface GithubCopilotTokens {+ bearerToken: string;+ bearerTokenExpiresAt: number;+ oauthAccessToken: string;+ userInfo: GithubUserInfo;+}++export class GithubCopilotOAuthService extends OAuthDeviceFlowService {+ private static readonly GITHUB_USER_API = 'https://api.github.com/user';+ private static readonly TOKEN_EXCHANGE_URL = 'https://api.github.com/copilot_internal/v2/token';++ /**+ * Fetch GitHub user info using OAuth access token+ */+ async fetchUserInfo(oauthToken: string): Promise<GithubUserInfo> {+ const response = await fetch(GithubCopilotOAuthService.GITHUB_USER_API, {+ headers: {+ 'Accept': 'application/json',+ 'Authorization': `token ${oauthToken}`,+ 'User-Agent': 'LobeChat/1.0',+ },+ method: 'GET',+ });++ if (!response.ok) {+ throw new Error(`Failed to fetch GitHub user info: ${response.status}`);+ }++ const data = await response.json();++ return {+ avatarUrl: data.avatar_url || '',+ username: data.login || '',+ };+ }++ /**+ * Exchange OAuth access token for GitHub Copilot bearer token+ */+ async exchangeForCopilotToken(oauthToken: string): Promise<CopilotTokenResponse> {+ const response = await fetch(GithubCopilotOAuthService.TOKEN_EXCHANGE_URL, {+ headers: {+ 'Accept': 'application/json',+ 'Authorization': `token ${oauthToken}`,+ 'User-Agent': 'LobeChat/1.0',+ },+ method: 'GET',+ });++ if (response.status === 401) {+ throw new Error('Invalid GitHub OAuth token');+ }++ if (response.status === 403) {+ throw new Error('No GitHub Copilot subscription or access denied');+ }++ if (!response.ok) {+ const errorText = await response.text();+ throw new Error(`Failed to exchange for Copilot token: ${response.status} ${errorText}`);+ }++ const data = await response.json();++ if (!data?.token || typeof data.expires_at !== 'number') {+ throw new Error('Invalid Copilot token response format');+ }++ return {+ expiresAt: data.expires_at * 1000,+ token: data.token,+ };+ }++ /**+ * Complete the full OAuth flow for GitHub Copilot:+ * 1. Poll for OAuth token+ * 2. Exchange for Copilot bearer token+ * 3. Fetch GitHub user info+ */+ async completeAuthFlow(+ config: OAuthDeviceFlowConfig,+ deviceCode: string,+ ): Promise<GithubCopilotTokens | null> {+ const pollResult = await this.pollForToken(config, deviceCode);++ if (pollResult.status !== 'success' || !pollResult.tokens) {+ return null;+ }++ const oauthToken = pollResult.tokens.accessToken;+ const [copilotToken, userInfo] = await Promise.all([+ this.exchangeForCopilotToken(oauthToken),+ this.fetchUserInfo(oauthToken),+ ]);++ return {+ bearerToken: copilotToken.token,+ bearerTokenExpiresAt: copilotToken.expiresAt,+ oauthAccessToken: oauthToken,+ userInfo,+ };+ }++ /**+ * Refresh the Copilot bearer token using the existing OAuth token+ */+ async refreshCopilotToken(oauthToken: string): Promise<CopilotTokenResponse> {+ return this.exchangeForCopilotToken(oauthToken);+ }+}++/**+ * Factory function to get the appropriate OAuth service based on provider+ */+export function getOAuthService(providerId: string): OAuthDeviceFlowService {+ if (providerId === 'githubcopilot') {+ return new GithubCopilotOAuthService();+ }+ return new OAuthDeviceFlowService();+}