mirror of
https://github.com/chriswritescode-dev/opencode-manager.git
synced 2026-12-06 12:54:20 +01:00
Add config sync mode to prevent config file overwrites on startup (#63)
Fixes #62 - Config file in workspace volume is now the source of truth * Preserve raw config content with comments instead of re-stringifying parsed JSON * Sync provider credentials to OpenCode server when adding or removing API keys * Add error handling for session errors with toast notifications and inline message display * Refactor provider settings to manage API keys directly with edit/delete support
This commit is contained in:
1 parent
f3505de0e1
commit
078fbd1a05
13 files changed
+605
-240
No files matched your search
+77
-75
@@ -31,6 +31,7 @@ import {
|
||||
ENV
|
||||
} from '@opencode-manager/shared/config/env'
|
||||
import { OpenCodeConfigSchema } from '@opencode-manager/shared/schemas'
|
||||
import stripJsonComments from 'strip-json-comments'
|
||||
|
||||
const { PORT, HOST } = ENV.SERVER
|
||||
const DB_PATH = getDatabasePath()
|
||||
@@ -104,89 +105,91 @@ Prefer **pnpm** or **bun** over npm for installing dependencies to save disk spa
|
||||
|
||||
async function ensureDefaultConfigExists(): Promise<void> {
|
||||
const settingsService = new SettingsService(db)
|
||||
const existingDbConfigs = settingsService.getOpenCodeConfigs()
|
||||
const workspaceConfigPath = getOpenCodeConfigFilePath()
|
||||
|
||||
// Config already exists in database - nothing to do
|
||||
if (await fileExists(workspaceConfigPath)) {
|
||||
logger.info(`Found workspace config at ${workspaceConfigPath}, syncing to database...`)
|
||||
try {
|
||||
const rawContent = await readFileContent(workspaceConfigPath)
|
||||
const parsed = JSON.parse(stripJsonComments(rawContent))
|
||||
const validation = OpenCodeConfigSchema.safeParse(parsed)
|
||||
|
||||
if (!validation.success) {
|
||||
logger.warn('Workspace config has invalid structure', validation.error)
|
||||
} else {
|
||||
const existingDefault = settingsService.getOpenCodeConfigByName('default')
|
||||
if (existingDefault) {
|
||||
settingsService.updateOpenCodeConfig('default', {
|
||||
content: rawContent,
|
||||
isDefault: true,
|
||||
})
|
||||
logger.info('Updated database config from workspace file')
|
||||
} else {
|
||||
settingsService.createOpenCodeConfig({
|
||||
name: 'default',
|
||||
content: rawContent,
|
||||
isDefault: true,
|
||||
})
|
||||
logger.info('Created database config from workspace file')
|
||||
}
|
||||
return
|
||||
}
|
||||
} catch (error) {
|
||||
logger.warn('Failed to read workspace config', error)
|
||||
}
|
||||
}
|
||||
|
||||
const homeConfigPath = path.join(os.homedir(), '.config/opencode/opencode.json')
|
||||
if (await fileExists(homeConfigPath)) {
|
||||
logger.info(`Found home config at ${homeConfigPath}, importing...`)
|
||||
try {
|
||||
const rawContent = await readFileContent(homeConfigPath)
|
||||
const parsed = JSON.parse(stripJsonComments(rawContent))
|
||||
const validation = OpenCodeConfigSchema.safeParse(parsed)
|
||||
|
||||
if (validation.success) {
|
||||
const existingDefault = settingsService.getOpenCodeConfigByName('default')
|
||||
if (existingDefault) {
|
||||
settingsService.updateOpenCodeConfig('default', {
|
||||
content: rawContent,
|
||||
isDefault: true,
|
||||
})
|
||||
} else {
|
||||
settingsService.createOpenCodeConfig({
|
||||
name: 'default',
|
||||
content: rawContent,
|
||||
isDefault: true,
|
||||
})
|
||||
}
|
||||
|
||||
await writeFileContent(workspaceConfigPath, rawContent)
|
||||
logger.info('Imported home config to workspace')
|
||||
return
|
||||
}
|
||||
} catch (error) {
|
||||
logger.warn('Failed to import home config', error)
|
||||
}
|
||||
}
|
||||
|
||||
const existingDbConfigs = settingsService.getOpenCodeConfigs()
|
||||
if (existingDbConfigs.configs.length > 0) {
|
||||
logger.info('OpenCode config already exists in database')
|
||||
const defaultConfig = settingsService.getDefaultOpenCodeConfig()
|
||||
if (defaultConfig) {
|
||||
await writeFileContent(workspaceConfigPath, defaultConfig.rawContent)
|
||||
logger.info('Wrote existing database config to workspace file')
|
||||
}
|
||||
return
|
||||
}
|
||||
|
||||
// Try to import from existing OpenCode installation (highest priority)
|
||||
const homeConfigPath = path.join(os.homedir(), '.config/opencode/opencode.json')
|
||||
if (await fileExists(homeConfigPath)) {
|
||||
logger.info(`Found existing OpenCode config at ${homeConfigPath}, importing...`)
|
||||
try {
|
||||
const content = await readFileContent(homeConfigPath)
|
||||
const parsed = JSON.parse(content)
|
||||
const validation = OpenCodeConfigSchema.safeParse(parsed)
|
||||
|
||||
if (!validation.success) {
|
||||
logger.warn('Existing config has invalid structure, will try other sources', validation.error)
|
||||
} else {
|
||||
settingsService.createOpenCodeConfig({
|
||||
name: 'default',
|
||||
content: validation.data,
|
||||
isDefault: true,
|
||||
})
|
||||
logger.info('Successfully imported existing OpenCode config')
|
||||
return
|
||||
}
|
||||
} catch (error) {
|
||||
logger.warn('Failed to import existing config, will try other sources', error)
|
||||
}
|
||||
}
|
||||
|
||||
// Try to import from workspace config (if user reinstalls and workspace persists)
|
||||
const workspaceConfigPath = getOpenCodeConfigFilePath()
|
||||
if (await fileExists(workspaceConfigPath)) {
|
||||
logger.info(`Found workspace config, importing...`)
|
||||
try {
|
||||
const content = await readFileContent(workspaceConfigPath)
|
||||
const parsed = JSON.parse(content)
|
||||
const validation = OpenCodeConfigSchema.safeParse(parsed)
|
||||
|
||||
if (!validation.success) {
|
||||
logger.warn('Workspace config has invalid structure, will use defaults', validation.error)
|
||||
} else {
|
||||
settingsService.createOpenCodeConfig({
|
||||
name: 'default',
|
||||
content: validation.data,
|
||||
isDefault: true,
|
||||
})
|
||||
logger.info('Successfully imported workspace config')
|
||||
return
|
||||
}
|
||||
} catch (error) {
|
||||
logger.warn('Failed to import workspace config, will use defaults', error)
|
||||
}
|
||||
}
|
||||
|
||||
// No existing config found - create minimal seed config
|
||||
logger.info('No existing OpenCode config found, creating minimal seed config')
|
||||
logger.info('No existing config found, creating minimal seed config')
|
||||
const seedConfig = JSON.stringify({ $schema: 'https://opencode.ai/config.json' }, null, 2)
|
||||
settingsService.createOpenCodeConfig({
|
||||
name: 'default',
|
||||
content: {
|
||||
$schema: 'https://opencode.ai/config.json',
|
||||
// Minimal seed - users can configure through Manager UI
|
||||
},
|
||||
content: seedConfig,
|
||||
isDefault: true,
|
||||
})
|
||||
logger.info('Created minimal seed OpenCode config')
|
||||
}
|
||||
|
||||
async function syncDefaultConfigToDisk(): Promise<void> {
|
||||
const settingsService = new SettingsService(db)
|
||||
const defaultConfig = settingsService.getDefaultOpenCodeConfig()
|
||||
|
||||
if (defaultConfig) {
|
||||
const configPath = getOpenCodeConfigFilePath()
|
||||
const configContent = JSON.stringify(defaultConfig.content, null, 2)
|
||||
await writeFileContent(configPath, configContent)
|
||||
logger.info(`Synced default config '${defaultConfig.name}' to: ${configPath}`)
|
||||
} else {
|
||||
logger.info('No default OpenCode config found in database')
|
||||
}
|
||||
await writeFileContent(workspaceConfigPath, seedConfig)
|
||||
logger.info('Created minimal seed config')
|
||||
}
|
||||
|
||||
async function ensureDefaultAgentsMdExists(): Promise<void> {
|
||||
@@ -211,7 +214,6 @@ try {
|
||||
await cleanupExpiredCache()
|
||||
|
||||
await ensureDefaultConfigExists()
|
||||
await syncDefaultConfigToDisk()
|
||||
await ensureDefaultAgentsMdExists()
|
||||
|
||||
const settingsService = new SettingsService(db)
|
||||
|
||||
@@ -3,6 +3,7 @@ import { z } from 'zod'
|
||||
import { AuthService } from '../services/auth'
|
||||
import { SetCredentialRequestSchema } from '../../../shared/src/schemas/auth'
|
||||
import { logger } from '../utils/logger'
|
||||
import { setOpenCodeAuth, deleteOpenCodeAuth } from '../services/proxy'
|
||||
|
||||
export function createProvidersRoutes() {
|
||||
const app = new Hono()
|
||||
@@ -35,6 +36,11 @@ export function createProvidersRoutes() {
|
||||
const body = await c.req.json()
|
||||
const validated = SetCredentialRequestSchema.parse(body)
|
||||
|
||||
const openCodeSuccess = await setOpenCodeAuth(providerId, validated.apiKey)
|
||||
if (!openCodeSuccess) {
|
||||
logger.warn(`Failed to set OpenCode auth for ${providerId}, saving locally only`)
|
||||
}
|
||||
|
||||
await authService.set(providerId, validated.apiKey)
|
||||
return c.json({ success: true })
|
||||
} catch (error) {
|
||||
@@ -49,6 +55,12 @@ export function createProvidersRoutes() {
|
||||
app.delete('/:id/credentials', async (c) => {
|
||||
try {
|
||||
const providerId = c.req.param('id')
|
||||
|
||||
const openCodeSuccess = await deleteOpenCodeAuth(providerId)
|
||||
if (!openCodeSuccess) {
|
||||
logger.warn(`Failed to delete OpenCode auth for ${providerId}, removing locally only`)
|
||||
}
|
||||
|
||||
await authService.delete(providerId)
|
||||
return c.json({ success: true })
|
||||
} catch (error) {
|
||||
|
||||
@@ -150,8 +150,7 @@ export function createSettingsRoutes(db: Database) {
|
||||
|
||||
if (config.isDefault) {
|
||||
const configPath = getOpenCodeConfigFilePath()
|
||||
const configContent = JSON.stringify(config.content, null, 2)
|
||||
await writeFileContent(configPath, configContent)
|
||||
await writeFileContent(configPath, config.rawContent)
|
||||
logger.info(`Wrote default config to: ${configPath}`)
|
||||
|
||||
await patchOpenCodeConfig(config.content)
|
||||
@@ -184,8 +183,7 @@ export function createSettingsRoutes(db: Database) {
|
||||
|
||||
if (config.isDefault) {
|
||||
const configPath = getOpenCodeConfigFilePath()
|
||||
const configContent = JSON.stringify(config.content, null, 2)
|
||||
await writeFileContent(configPath, configContent)
|
||||
await writeFileContent(configPath, config.rawContent)
|
||||
logger.info(`Wrote default config to: ${configPath}`)
|
||||
|
||||
await patchOpenCodeConfig(config.content)
|
||||
@@ -231,8 +229,7 @@ export function createSettingsRoutes(db: Database) {
|
||||
}
|
||||
|
||||
const configPath = getOpenCodeConfigFilePath()
|
||||
const configContent = JSON.stringify(config.content, null, 2)
|
||||
await writeFileContent(configPath, configContent)
|
||||
await writeFileContent(configPath, config.rawContent)
|
||||
logger.info(`Wrote default config '${configName}' to: ${configPath}`)
|
||||
|
||||
await patchOpenCodeConfig(config.content)
|
||||
@@ -292,8 +289,7 @@ export function createSettingsRoutes(db: Database) {
|
||||
return c.json({ error: 'Failed to get default config after rollback' }, 500)
|
||||
}
|
||||
|
||||
const configContent = JSON.stringify(config.content, null, 2)
|
||||
await writeFileContent(configPath, configContent)
|
||||
await writeFileContent(configPath, config.rawContent)
|
||||
logger.info(`Rolled back to config '${rollbackConfig}'`)
|
||||
|
||||
opencodeServerManager.clearStartupError()
|
||||
|
||||
@@ -3,6 +3,46 @@ import { ENV } from '@opencode-manager/shared/config/env'
|
||||
|
||||
const OPENCODE_SERVER_URL = `http://127.0.0.1:${ENV.OPENCODE.PORT}`
|
||||
|
||||
export async function setOpenCodeAuth(providerId: string, apiKey: string): Promise<boolean> {
|
||||
try {
|
||||
const response = await fetch(`${OPENCODE_SERVER_URL}/auth/${providerId}`, {
|
||||
method: 'PUT',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify({ type: 'api', key: apiKey }),
|
||||
})
|
||||
|
||||
if (response.ok) {
|
||||
logger.info(`Set OpenCode auth for provider: ${providerId}`)
|
||||
return true
|
||||
}
|
||||
|
||||
logger.error(`Failed to set OpenCode auth: ${response.status} ${response.statusText}`)
|
||||
return false
|
||||
} catch (error) {
|
||||
logger.error('Failed to set OpenCode auth:', error)
|
||||
return false
|
||||
}
|
||||
}
|
||||
|
||||
export async function deleteOpenCodeAuth(providerId: string): Promise<boolean> {
|
||||
try {
|
||||
const response = await fetch(`${OPENCODE_SERVER_URL}/auth/${providerId}`, {
|
||||
method: 'DELETE',
|
||||
})
|
||||
|
||||
if (response.ok) {
|
||||
logger.info(`Deleted OpenCode auth for provider: ${providerId}`)
|
||||
return true
|
||||
}
|
||||
|
||||
logger.error(`Failed to delete OpenCode auth: ${response.status} ${response.statusText}`)
|
||||
return false
|
||||
} catch (error) {
|
||||
logger.error('Failed to delete OpenCode auth:', error)
|
||||
return false
|
||||
}
|
||||
}
|
||||
|
||||
export async function patchOpenCodeConfig(config: Record<string, unknown>): Promise<boolean> {
|
||||
try {
|
||||
const response = await fetch(`${OPENCODE_SERVER_URL}/config`, {
|
||||
|
||||
@@ -167,6 +167,18 @@ export interface SSESessionStatusEvent {
|
||||
}
|
||||
}
|
||||
|
||||
export interface SSESessionErrorEvent {
|
||||
type: 'session.error'
|
||||
properties: {
|
||||
sessionID?: string
|
||||
error?: components['schemas']['ProviderAuthError']
|
||||
| components['schemas']['UnknownError']
|
||||
| components['schemas']['MessageOutputLengthError']
|
||||
| components['schemas']['MessageAbortedError']
|
||||
| components['schemas']['APIError']
|
||||
}
|
||||
}
|
||||
|
||||
export type SSEEvent =
|
||||
| SSEMessagePartUpdatedEvent
|
||||
| SSEMessageUpdatedEvent
|
||||
@@ -177,6 +189,7 @@ export type SSEEvent =
|
||||
| SSESessionCompactedEvent
|
||||
| SSESessionIdleEvent
|
||||
| SSESessionStatusEvent
|
||||
| SSESessionErrorEvent
|
||||
| SSETodoUpdatedEvent
|
||||
| SSEPermissionAskedEvent
|
||||
| SSEPermissionRepliedEvent
|
||||
|
||||
@@ -0,0 +1,37 @@
|
||||
import { memo } from 'react'
|
||||
import { AlertCircle, KeyRound, XCircle, Clock } from 'lucide-react'
|
||||
import { parseOpenCodeError, type OpenCodeError } from '@/lib/opencode-errors'
|
||||
|
||||
interface MessageErrorProps {
|
||||
error: OpenCodeError
|
||||
}
|
||||
|
||||
const getErrorIcon = (errorName: string) => {
|
||||
switch (errorName) {
|
||||
case 'ProviderAuthError':
|
||||
return KeyRound
|
||||
case 'MessageAbortedError':
|
||||
return XCircle
|
||||
case 'MessageOutputLengthError':
|
||||
return Clock
|
||||
default:
|
||||
return AlertCircle
|
||||
}
|
||||
}
|
||||
|
||||
export const MessageError = memo(function MessageError({ error }: MessageErrorProps) {
|
||||
const parsed = parseOpenCodeError(error)
|
||||
if (!parsed) return null
|
||||
|
||||
const Icon = getErrorIcon(error.name)
|
||||
|
||||
return (
|
||||
<div className="flex items-start gap-2 p-3 rounded-md bg-destructive/10 border border-destructive/30 text-destructive">
|
||||
<Icon className="h-4 w-4 mt-0.5 flex-shrink-0" />
|
||||
<div className="flex-1 min-w-0">
|
||||
<div className="font-medium text-sm">{parsed.title}</div>
|
||||
<div className="text-xs text-destructive/80 mt-0.5">{parsed.message}</div>
|
||||
</div>
|
||||
</div>
|
||||
)
|
||||
})
|
||||
@@ -4,11 +4,13 @@ import { MessageActionButtons } from './MessageActionButtons'
|
||||
import { UserMessageActionButtons } from './UserMessageActionButtons'
|
||||
import { EditableUserMessage, ClickableUserMessage } from './EditableUserMessage'
|
||||
import { SessionTodoDisplay } from './SessionTodoDisplay'
|
||||
import { MessageError } from './MessageError'
|
||||
import type { MessageWithParts } from '@/api/types'
|
||||
import { useSessionStatusForSession } from '@/stores/sessionStatusStore'
|
||||
import { useSessionTodos } from '@/stores/sessionTodosStore'
|
||||
import type { components } from '@/api/opencode-types'
|
||||
import type { Todo } from '@/components/message/SessionTodoDisplay'
|
||||
import type { OpenCodeError } from '@/lib/opencode-errors'
|
||||
|
||||
function getMessageTextContent(msg: MessageWithParts): string {
|
||||
return msg.parts
|
||||
@@ -255,6 +257,9 @@ const state = latestTodoPart.state
|
||||
</div>
|
||||
))
|
||||
)}
|
||||
{msg.info.role === 'assistant' && 'error' in msg.info && msg.info.error && (
|
||||
<MessageError error={msg.info.error as OpenCodeError} />
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
@@ -19,6 +19,7 @@ interface ApiKeyDialogProps {
|
||||
onOpenChange: (open: boolean) => void;
|
||||
provider: ProviderWithModels | null;
|
||||
onSuccess: () => void;
|
||||
mode?: 'add' | 'edit';
|
||||
}
|
||||
|
||||
export function ApiKeyDialog({
|
||||
@@ -26,6 +27,7 @@ export function ApiKeyDialog({
|
||||
onOpenChange,
|
||||
provider,
|
||||
onSuccess,
|
||||
mode = 'add',
|
||||
}: ApiKeyDialogProps) {
|
||||
const [apiKey, setApiKey] = useState("");
|
||||
const [isSubmitting, setIsSubmitting] = useState(false);
|
||||
@@ -58,6 +60,7 @@ export function ApiKeyDialog({
|
||||
if (!provider) return null;
|
||||
|
||||
const envVarName = provider.env?.[0] || `${provider.id.toUpperCase()}_API_KEY`;
|
||||
const isEditMode = mode === 'edit';
|
||||
|
||||
return (
|
||||
<Dialog open={open} onOpenChange={handleClose}>
|
||||
@@ -65,10 +68,13 @@ export function ApiKeyDialog({
|
||||
<DialogHeader>
|
||||
<DialogTitle className="flex items-center gap-2">
|
||||
<Key className="h-5 w-5" />
|
||||
Connect {provider.name}
|
||||
{isEditMode ? `Update ${provider.name} API Key` : `Connect ${provider.name}`}
|
||||
</DialogTitle>
|
||||
<DialogDescription>
|
||||
Enter your API key to use models from {provider.name}.
|
||||
{isEditMode
|
||||
? `Enter a new API key for ${provider.name}.`
|
||||
: `Enter your API key to use models from ${provider.name}.`
|
||||
}
|
||||
</DialogDescription>
|
||||
</DialogHeader>
|
||||
|
||||
@@ -118,10 +124,10 @@ export function ApiKeyDialog({
|
||||
{isSubmitting ? (
|
||||
<>
|
||||
<Loader2 className="h-4 w-4 mr-2 animate-spin" />
|
||||
Connecting...
|
||||
{isEditMode ? 'Updating...' : 'Connecting...'}
|
||||
</>
|
||||
) : (
|
||||
"Connect"
|
||||
isEditMode ? 'Update' : 'Connect'
|
||||
)}
|
||||
</Button>
|
||||
</DialogFooter>
|
||||
|
||||
@@ -8,17 +8,16 @@ import {
|
||||
import { Button } from "@/components/ui/button";
|
||||
import { Input } from "@/components/ui/input";
|
||||
import { Badge } from "@/components/ui/badge";
|
||||
import { Select, SelectContent, SelectGroup, SelectItem, SelectLabel, SelectTrigger, SelectValue } from "@/components/ui/select";
|
||||
import { Loader2, Search, Check, PlugZap, Key, Star } from "lucide-react";
|
||||
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from "@/components/ui/select";
|
||||
import { Loader2, Search, Check, Star } from "lucide-react";
|
||||
import {
|
||||
getProvidersWithModels,
|
||||
formatModelName,
|
||||
formatProviderName,
|
||||
} from "@/api/providers";
|
||||
import { useModelSelection } from "@/hooks/useModelSelection";
|
||||
import { useQuery, useQueryClient } from "@tanstack/react-query";
|
||||
import { useQuery } from "@tanstack/react-query";
|
||||
import type { Model, ProviderWithModels } from "@/api/providers";
|
||||
import { ApiKeyDialog } from "./ApiKeyDialog";
|
||||
|
||||
interface ModelSelectDialogProps {
|
||||
open: boolean;
|
||||
@@ -94,18 +93,6 @@ const ModelCard = memo(function ModelCard({
|
||||
return null;
|
||||
}, [model.experimental, model.status]);
|
||||
|
||||
const connectionBadge = useMemo(() => {
|
||||
if (!provider.isConnected) {
|
||||
return (
|
||||
<Badge variant="outline" className="text-xs px-1.5 py-0 border-orange-500/30 text-orange-500">
|
||||
<Key className="h-2.5 w-2.5 mr-0.5" />
|
||||
Setup
|
||||
</Badge>
|
||||
);
|
||||
}
|
||||
return null;
|
||||
}, [provider.isConnected]);
|
||||
|
||||
return (
|
||||
<div
|
||||
className={`p-3 sm:p-4 rounded-lg border cursor-pointer transition-colors ${
|
||||
@@ -121,7 +108,6 @@ const ModelCard = memo(function ModelCard({
|
||||
<h4 className="font-semibold text-sm truncate">
|
||||
{formatModelName(model)}
|
||||
</h4>
|
||||
{connectionBadge}
|
||||
</div>
|
||||
<p className="text-xs text-muted-foreground truncate">
|
||||
{formatProviderName(provider)}
|
||||
@@ -258,16 +244,13 @@ const ModelGrid = memo(function ModelGrid({
|
||||
});
|
||||
|
||||
interface ProviderSidebarProps {
|
||||
groupedProviders: {
|
||||
connected: ProviderWithModels[];
|
||||
available: ProviderWithModels[];
|
||||
};
|
||||
providers: ProviderWithModels[];
|
||||
selectedProvider: string;
|
||||
onSelect: (providerId: string) => void;
|
||||
}
|
||||
|
||||
const ProviderSidebar = memo(function ProviderSidebar({
|
||||
groupedProviders,
|
||||
providers,
|
||||
selectedProvider,
|
||||
onSelect,
|
||||
}: ProviderSidebarProps) {
|
||||
@@ -283,47 +266,19 @@ const ProviderSidebar = memo(function ProviderSidebar({
|
||||
All Providers
|
||||
</Button>
|
||||
|
||||
{groupedProviders.connected.length > 0 && (
|
||||
<div>
|
||||
<h3 className="text-xs font-semibold text-green-600 mb-2 flex items-center gap-1.5">
|
||||
<PlugZap className="h-3 w-3" />
|
||||
Connected
|
||||
</h3>
|
||||
<div className="space-y-1">
|
||||
{groupedProviders.connected.map((provider) => (
|
||||
<Button
|
||||
key={provider.id}
|
||||
variant={selectedProvider === provider.id ? "secondary" : "ghost"}
|
||||
size="sm"
|
||||
onClick={() => onSelect(provider.id)}
|
||||
className="w-full justify-start text-sm"
|
||||
>
|
||||
{formatProviderName(provider)}
|
||||
</Button>
|
||||
))}
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
|
||||
{groupedProviders.available.length > 0 && (
|
||||
<div>
|
||||
<h3 className="text-xs font-semibold text-muted-foreground mb-2 flex items-center gap-1.5">
|
||||
<Key className="h-3 w-3" />
|
||||
Available
|
||||
</h3>
|
||||
<div className="space-y-1">
|
||||
{groupedProviders.available.map((provider) => (
|
||||
<Button
|
||||
key={provider.id}
|
||||
variant={selectedProvider === provider.id ? "secondary" : "ghost"}
|
||||
size="sm"
|
||||
onClick={() => onSelect(provider.id)}
|
||||
className="w-full justify-start text-sm text-muted-foreground"
|
||||
>
|
||||
{formatProviderName(provider)}
|
||||
</Button>
|
||||
))}
|
||||
</div>
|
||||
{providers.length > 0 && (
|
||||
<div className="space-y-1">
|
||||
{providers.map((provider) => (
|
||||
<Button
|
||||
key={provider.id}
|
||||
variant={selectedProvider === provider.id ? "secondary" : "ghost"}
|
||||
size="sm"
|
||||
onClick={() => onSelect(provider.id)}
|
||||
className="w-full justify-start text-sm"
|
||||
>
|
||||
{formatProviderName(provider)}
|
||||
</Button>
|
||||
))}
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
@@ -339,15 +294,11 @@ export function ModelSelectDialog({
|
||||
}: ModelSelectDialogProps) {
|
||||
const [searchQuery, setSearchQuery] = useState("");
|
||||
const [selectedProvider, setSelectedProvider] = useState<string>("");
|
||||
const [apiKeyDialogOpen, setApiKeyDialogOpen] = useState(false);
|
||||
const [pendingSelection, setPendingSelection] = useState<{ providerId: string; modelId: string } | null>(null);
|
||||
const [providerForApiKey, setProviderForApiKey] = useState<ProviderWithModels | null>(null);
|
||||
|
||||
const queryClient = useQueryClient();
|
||||
const { modelString, setModel, recentModels } = useModelSelection(opcodeUrl, directory);
|
||||
const currentModel = modelString || "";
|
||||
|
||||
const { data: providers = [], isLoading: loading } = useQuery({
|
||||
const { data: allProviders = [], isLoading: loading } = useQuery({
|
||||
queryKey: ["providers-with-models"],
|
||||
queryFn: () => getProvidersWithModels(),
|
||||
enabled: open,
|
||||
@@ -355,6 +306,10 @@ export function ModelSelectDialog({
|
||||
gcTime: 10 * 60 * 1000,
|
||||
});
|
||||
|
||||
const connectedProviders = useMemo(() => {
|
||||
return allProviders.filter(p => p.isConnected);
|
||||
}, [allProviders]);
|
||||
|
||||
useEffect(() => {
|
||||
if (open) {
|
||||
setSelectedProvider("");
|
||||
@@ -362,14 +317,14 @@ export function ModelSelectDialog({
|
||||
}, [open]);
|
||||
|
||||
const flatModels = useMemo((): FlatModel[] => {
|
||||
return providers.flatMap((provider) =>
|
||||
return connectedProviders.flatMap((provider) =>
|
||||
provider.models.map((model) => ({
|
||||
model,
|
||||
provider,
|
||||
modelKey: `${provider.id}/${model.id}`,
|
||||
}))
|
||||
);
|
||||
}, [providers]);
|
||||
}, [connectedProviders]);
|
||||
|
||||
const recentFlatModels = useMemo((): FlatModel[] => {
|
||||
return recentModels
|
||||
@@ -400,15 +355,9 @@ export function ModelSelectDialog({
|
||||
return filtered;
|
||||
}, [flatModels, selectedProvider, searchQuery]);
|
||||
|
||||
const groupedProviders = useMemo(() => {
|
||||
const connected = providers.filter(p => p.isConnected);
|
||||
const available = providers.filter(p => !p.isConnected);
|
||||
return { connected, available };
|
||||
}, [providers]);
|
||||
|
||||
const selectedProviderData = useMemo(
|
||||
() => providers.find(p => p.id === selectedProvider),
|
||||
[providers, selectedProvider]
|
||||
() => connectedProviders.find(p => p.id === selectedProvider),
|
||||
[connectedProviders, selectedProvider]
|
||||
);
|
||||
|
||||
const handleProviderSelect = useCallback((providerId: string) => {
|
||||
@@ -421,38 +370,9 @@ export function ModelSelectDialog({
|
||||
}, []);
|
||||
|
||||
const handleModelSelect = useCallback((providerId: string, modelId: string) => {
|
||||
const provider = providers.find(p => p.id === providerId);
|
||||
|
||||
if (provider && !provider.isConnected) {
|
||||
setPendingSelection({ providerId, modelId });
|
||||
setProviderForApiKey(provider);
|
||||
setApiKeyDialogOpen(true);
|
||||
return;
|
||||
}
|
||||
|
||||
setModel({ providerID: providerId, modelID: modelId });
|
||||
onOpenChange(false);
|
||||
}, [setModel, onOpenChange, providers]);
|
||||
|
||||
const handleApiKeySuccess = useCallback(async () => {
|
||||
setApiKeyDialogOpen(false);
|
||||
await queryClient.invalidateQueries({ queryKey: ["providers-with-models"] });
|
||||
|
||||
if (pendingSelection) {
|
||||
setModel({ providerID: pendingSelection.providerId, modelID: pendingSelection.modelId });
|
||||
setPendingSelection(null);
|
||||
setProviderForApiKey(null);
|
||||
onOpenChange(false);
|
||||
}
|
||||
}, [queryClient, pendingSelection, setModel, onOpenChange]);
|
||||
|
||||
const handleApiKeyDialogClose = useCallback((open: boolean) => {
|
||||
setApiKeyDialogOpen(open);
|
||||
if (!open) {
|
||||
setPendingSelection(null);
|
||||
setProviderForApiKey(null);
|
||||
}
|
||||
}, []);
|
||||
}, [setModel, onOpenChange]);
|
||||
|
||||
const searchResetKey = selectedProvider;
|
||||
|
||||
@@ -467,7 +387,7 @@ export function ModelSelectDialog({
|
||||
|
||||
<div className="flex flex-1 overflow-hidden">
|
||||
<ProviderSidebar
|
||||
groupedProviders={groupedProviders}
|
||||
providers={connectedProviders}
|
||||
selectedProvider={selectedProvider}
|
||||
onSelect={handleProviderSelect}
|
||||
/>
|
||||
@@ -479,32 +399,11 @@ export function ModelSelectDialog({
|
||||
<SelectValue placeholder="Select a provider..." />
|
||||
</SelectTrigger>
|
||||
<SelectContent>
|
||||
{groupedProviders.connected.length > 0 && (
|
||||
<SelectGroup>
|
||||
<SelectLabel className="flex items-center gap-1.5 text-green-600">
|
||||
<PlugZap className="h-3 w-3" />
|
||||
Connected
|
||||
</SelectLabel>
|
||||
{groupedProviders.connected.map((provider) => (
|
||||
<SelectItem key={provider.id} value={provider.id}>
|
||||
{formatProviderName(provider)} ({provider.models.length})
|
||||
</SelectItem>
|
||||
))}
|
||||
</SelectGroup>
|
||||
)}
|
||||
{groupedProviders.available.length > 0 && (
|
||||
<SelectGroup>
|
||||
<SelectLabel className="flex items-center gap-1.5 text-muted-foreground">
|
||||
<Key className="h-3 w-3" />
|
||||
Available
|
||||
</SelectLabel>
|
||||
{groupedProviders.available.map((provider) => (
|
||||
<SelectItem key={provider.id} value={provider.id}>
|
||||
{formatProviderName(provider)} ({provider.models.length})
|
||||
</SelectItem>
|
||||
))}
|
||||
</SelectGroup>
|
||||
)}
|
||||
{connectedProviders.map((provider) => (
|
||||
<SelectItem key={provider.id} value={provider.id}>
|
||||
{formatProviderName(provider)} ({provider.models.length})
|
||||
</SelectItem>
|
||||
))}
|
||||
</SelectContent>
|
||||
</Select>
|
||||
</div>
|
||||
@@ -536,13 +435,6 @@ export function ModelSelectDialog({
|
||||
</div>
|
||||
</div>
|
||||
</DialogContent>
|
||||
|
||||
<ApiKeyDialog
|
||||
open={apiKeyDialogOpen}
|
||||
onOpenChange={handleApiKeyDialogClose}
|
||||
provider={providerForApiKey}
|
||||
onSuccess={handleApiKeySuccess}
|
||||
/>
|
||||
</Dialog>
|
||||
);
|
||||
}
|
||||
@@ -2,18 +2,27 @@ import { useState, useMemo, useCallback } from 'react'
|
||||
import { Button } from '@/components/ui/button'
|
||||
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from '@/components/ui/card'
|
||||
import { Badge } from '@/components/ui/badge'
|
||||
import { Loader2, Check, X, Shield } from 'lucide-react'
|
||||
import { Input } from '@/components/ui/input'
|
||||
import { Loader2, Check, X, Shield, ChevronDown, ChevronRight, Key, Search, Pencil, Trash2 } from 'lucide-react'
|
||||
import { providerCredentialsApi, getProviders } from '@/api/providers'
|
||||
import type { Provider } from '@/api/providers'
|
||||
import { oauthApi, type OAuthAuthorizeResponse } from '@/api/oauth'
|
||||
import { useMutation, useQuery, useQueryClient } from '@tanstack/react-query'
|
||||
import { OAuthAuthorizeDialog } from './OAuthAuthorizeDialog'
|
||||
import { OAuthCallbackDialog } from './OAuthCallbackDialog'
|
||||
import { ApiKeyDialog } from '@/components/model/ApiKeyDialog'
|
||||
|
||||
export function ProviderSettings() {
|
||||
const [selectedProvider, setSelectedProvider] = useState<string | null>(null)
|
||||
const [oauthDialogOpen, setOauthDialogOpen] = useState(false)
|
||||
const [oauthCallbackDialogOpen, setOauthCallbackDialogOpen] = useState(false)
|
||||
const [oauthResponse, setOauthResponse] = useState<OAuthAuthorizeResponse | null>(null)
|
||||
const [connectedExpanded, setConnectedExpanded] = useState(true)
|
||||
const [availableExpanded, setAvailableExpanded] = useState(false)
|
||||
const [availableSearch, setAvailableSearch] = useState('')
|
||||
const [apiKeyDialogOpen, setApiKeyDialogOpen] = useState(false)
|
||||
const [apiKeyProvider, setApiKeyProvider] = useState<Provider | null>(null)
|
||||
const [apiKeyMode, setApiKeyMode] = useState<'add' | 'edit'>('add')
|
||||
const queryClient = useQueryClient()
|
||||
|
||||
const { data: providersData, isLoading: providersLoading } = useQuery({
|
||||
@@ -38,6 +47,8 @@ export function ProviderSettings() {
|
||||
mutationFn: (providerId: string) => providerCredentialsApi.delete(providerId),
|
||||
onSuccess: () => {
|
||||
queryClient.invalidateQueries({ queryKey: ['provider-credentials'] })
|
||||
queryClient.invalidateQueries({ queryKey: ['providers'] })
|
||||
queryClient.invalidateQueries({ queryKey: ['providers-with-models'] })
|
||||
},
|
||||
})
|
||||
|
||||
@@ -70,20 +81,64 @@ export function ProviderSettings() {
|
||||
return methods.some(method => method.type === 'oauth')
|
||||
}, [authMethods])
|
||||
|
||||
const hasCredentials = (providerId: string) => {
|
||||
const hasCredentials = useCallback((providerId: string) => {
|
||||
return credentialsList?.includes(providerId) || false
|
||||
}
|
||||
}, [credentialsList])
|
||||
|
||||
const oauthProviders = useMemo(() => {
|
||||
if (!providers || !authMethods) return []
|
||||
return providers.filter(provider => supportsOAuth(provider.id))
|
||||
}, [providers, authMethods, supportsOAuth])
|
||||
|
||||
const apiKeyProviders = useMemo(() => {
|
||||
if (!providers || !authMethods) return { connected: [], available: [] }
|
||||
const nonOAuthProviders = providers.filter(provider => !supportsOAuth(provider.id))
|
||||
const connected = nonOAuthProviders.filter(provider => hasCredentials(provider.id))
|
||||
const available = nonOAuthProviders.filter(provider => !hasCredentials(provider.id))
|
||||
return { connected, available }
|
||||
}, [providers, authMethods, supportsOAuth, hasCredentials])
|
||||
|
||||
const filteredAvailableProviders = useMemo(() => {
|
||||
if (!availableSearch.trim()) return apiKeyProviders.available
|
||||
const search = availableSearch.toLowerCase()
|
||||
return apiKeyProviders.available.filter(provider =>
|
||||
provider.name.toLowerCase().includes(search) ||
|
||||
provider.id.toLowerCase().includes(search)
|
||||
)
|
||||
}, [apiKeyProviders.available, availableSearch])
|
||||
|
||||
const selectedProviderName = useMemo(() => {
|
||||
if (!selectedProvider) return ''
|
||||
return providers?.find(p => p.id === selectedProvider)?.name || selectedProvider
|
||||
}, [selectedProvider, providers])
|
||||
|
||||
const handleAddApiKey = useCallback((provider: Provider) => {
|
||||
setApiKeyProvider(provider)
|
||||
setApiKeyMode('add')
|
||||
setApiKeyDialogOpen(true)
|
||||
}, [])
|
||||
|
||||
const handleEditApiKey = useCallback((provider: Provider) => {
|
||||
setApiKeyProvider(provider)
|
||||
setApiKeyMode('edit')
|
||||
setApiKeyDialogOpen(true)
|
||||
}, [])
|
||||
|
||||
const handleApiKeySuccess = useCallback(() => {
|
||||
setApiKeyDialogOpen(false)
|
||||
setApiKeyProvider(null)
|
||||
queryClient.invalidateQueries({ queryKey: ['provider-credentials'] })
|
||||
queryClient.invalidateQueries({ queryKey: ['providers'] })
|
||||
queryClient.invalidateQueries({ queryKey: ['providers-with-models'] })
|
||||
}, [queryClient])
|
||||
|
||||
const handleApiKeyDialogClose = useCallback((open: boolean) => {
|
||||
setApiKeyDialogOpen(open)
|
||||
if (!open) {
|
||||
setApiKeyProvider(null)
|
||||
}
|
||||
}, [])
|
||||
|
||||
if (providersLoading || credentialsLoading) {
|
||||
return (
|
||||
<div className="flex items-center justify-center py-12">
|
||||
@@ -93,13 +148,14 @@ export function ProviderSettings() {
|
||||
}
|
||||
|
||||
return (
|
||||
<div className="space-y-4">
|
||||
<div>
|
||||
<h2 className="text-lg font-semibold text-foreground mb-2">OAuth Providers</h2>
|
||||
<p className="text-sm text-muted-foreground">
|
||||
Connect to AI providers using OAuth. For API keys, configure them in your OpenCode config file.
|
||||
</p>
|
||||
</div>
|
||||
<div className="space-y-8">
|
||||
<div className="space-y-4">
|
||||
<div>
|
||||
<h2 className="text-lg font-semibold text-foreground mb-2">OAuth Providers</h2>
|
||||
<p className="text-sm text-muted-foreground">
|
||||
Connect to AI providers using OAuth authentication.
|
||||
</p>
|
||||
</div>
|
||||
|
||||
{oauthProviders.length === 0 ? (
|
||||
<Card className="bg-card border-border">
|
||||
@@ -191,6 +247,179 @@ export function ProviderSettings() {
|
||||
onSuccess={handleOAuthSuccess}
|
||||
/>
|
||||
)}
|
||||
</div>
|
||||
|
||||
<div className="space-y-4">
|
||||
<div>
|
||||
<h2 className="text-lg font-semibold text-foreground mb-2">API Keys</h2>
|
||||
<p className="text-sm text-muted-foreground">
|
||||
Manage API keys for AI providers.
|
||||
</p>
|
||||
</div>
|
||||
|
||||
<div className="space-y-3">
|
||||
<button
|
||||
onClick={() => setConnectedExpanded(!connectedExpanded)}
|
||||
className="flex items-center gap-2 w-full text-left py-2 px-1 hover:bg-accent/50 rounded-md transition-colors"
|
||||
>
|
||||
{connectedExpanded ? (
|
||||
<ChevronDown className="h-4 w-4 text-muted-foreground" />
|
||||
) : (
|
||||
<ChevronRight className="h-4 w-4 text-muted-foreground" />
|
||||
)}
|
||||
<span className="font-medium text-sm">Connected</span>
|
||||
<Badge variant="secondary" className="ml-auto">
|
||||
{apiKeyProviders.connected.length}
|
||||
</Badge>
|
||||
</button>
|
||||
|
||||
{connectedExpanded && (
|
||||
<div className="pl-6 space-y-2">
|
||||
{apiKeyProviders.connected.length === 0 ? (
|
||||
<p className="text-sm text-muted-foreground py-2">
|
||||
No providers configured. Add an API key below to get started.
|
||||
</p>
|
||||
) : (
|
||||
apiKeyProviders.connected.map((provider) => {
|
||||
const modelCount = Object.keys(provider.models || {}).length
|
||||
return (
|
||||
<Card key={provider.id} className="bg-card border-border">
|
||||
<CardHeader className="p-3">
|
||||
<div className="flex items-center justify-between gap-2">
|
||||
<div className="flex-1 min-w-0">
|
||||
<CardTitle className="text-sm truncate">
|
||||
{provider.name || provider.id}
|
||||
</CardTitle>
|
||||
{modelCount > 0 && (
|
||||
<CardDescription className="text-xs">
|
||||
{modelCount} model{modelCount !== 1 ? 's' : ''}
|
||||
</CardDescription>
|
||||
)}
|
||||
</div>
|
||||
<div className="flex items-center gap-1">
|
||||
<Badge variant="default" className="bg-green-600 hover:bg-green-700 shrink-0 text-xs">
|
||||
<Check className="h-3 w-3 mr-1" />
|
||||
Connected
|
||||
</Badge>
|
||||
<Button
|
||||
size="sm"
|
||||
variant="ghost"
|
||||
onClick={() => handleEditApiKey(provider)}
|
||||
className="h-8 w-8 p-0"
|
||||
>
|
||||
<Pencil className="h-3.5 w-3.5" />
|
||||
</Button>
|
||||
<Button
|
||||
size="sm"
|
||||
variant="ghost"
|
||||
onClick={() => handleDeleteCredential(provider.id)}
|
||||
disabled={deleteCredentialMutation.isPending}
|
||||
className="h-8 w-8 p-0 text-destructive hover:text-destructive"
|
||||
>
|
||||
<Trash2 className="h-3.5 w-3.5" />
|
||||
</Button>
|
||||
</div>
|
||||
</div>
|
||||
</CardHeader>
|
||||
</Card>
|
||||
)
|
||||
})
|
||||
)}
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
|
||||
<div className="space-y-3">
|
||||
<button
|
||||
onClick={() => setAvailableExpanded(!availableExpanded)}
|
||||
className="flex items-center gap-2 w-full text-left py-2 px-1 hover:bg-accent/50 rounded-md transition-colors"
|
||||
>
|
||||
{availableExpanded ? (
|
||||
<ChevronDown className="h-4 w-4 text-muted-foreground" />
|
||||
) : (
|
||||
<ChevronRight className="h-4 w-4 text-muted-foreground" />
|
||||
)}
|
||||
<span className="font-medium text-sm">Available Providers</span>
|
||||
<Badge variant="secondary" className="ml-auto">
|
||||
{apiKeyProviders.available.length}
|
||||
</Badge>
|
||||
</button>
|
||||
|
||||
{availableExpanded && (
|
||||
<div className="pl-6 space-y-3">
|
||||
<div className="relative">
|
||||
<Search className="absolute left-3 top-1/2 transform -translate-y-1/2 h-4 w-4 text-muted-foreground" />
|
||||
<Input
|
||||
placeholder="Search providers..."
|
||||
value={availableSearch}
|
||||
onChange={(e) => setAvailableSearch(e.target.value)}
|
||||
className="pl-9 text-sm"
|
||||
/>
|
||||
</div>
|
||||
|
||||
<div className="space-y-2 max-h-64 overflow-y-auto">
|
||||
{filteredAvailableProviders.length === 0 ? (
|
||||
<p className="text-sm text-muted-foreground py-2">
|
||||
{availableSearch ? 'No providers match your search.' : 'No available providers.'}
|
||||
</p>
|
||||
) : (
|
||||
filteredAvailableProviders.map((provider) => {
|
||||
const modelCount = Object.keys(provider.models || {}).length
|
||||
return (
|
||||
<Card key={provider.id} className="bg-card border-border">
|
||||
<CardHeader className="p-3">
|
||||
<div className="flex items-center justify-between gap-2">
|
||||
<div className="flex-1 min-w-0">
|
||||
<CardTitle className="text-sm truncate">
|
||||
{provider.name || provider.id}
|
||||
</CardTitle>
|
||||
{modelCount > 0 && (
|
||||
<CardDescription className="text-xs">
|
||||
{modelCount} model{modelCount !== 1 ? 's' : ''}
|
||||
</CardDescription>
|
||||
)}
|
||||
</div>
|
||||
<Button
|
||||
size="sm"
|
||||
variant="outline"
|
||||
onClick={() => handleAddApiKey(provider)}
|
||||
>
|
||||
<Key className="h-3.5 w-3.5 mr-1" />
|
||||
Add Key
|
||||
</Button>
|
||||
</div>
|
||||
</CardHeader>
|
||||
</Card>
|
||||
)
|
||||
})
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{apiKeyProvider && (
|
||||
<ApiKeyDialog
|
||||
open={apiKeyDialogOpen}
|
||||
onOpenChange={handleApiKeyDialogClose}
|
||||
provider={{
|
||||
id: apiKeyProvider.id,
|
||||
name: apiKeyProvider.name,
|
||||
api: apiKeyProvider.api,
|
||||
env: apiKeyProvider.env || [],
|
||||
npm: apiKeyProvider.npm,
|
||||
models: Object.entries(apiKeyProvider.models || {}).map(([id, model]) => ({
|
||||
id,
|
||||
name: model.name || id,
|
||||
})),
|
||||
source: 'builtin',
|
||||
isConnected: hasCredentials(apiKeyProvider.id),
|
||||
}}
|
||||
onSuccess={handleApiKeySuccess}
|
||||
mode={apiKeyMode}
|
||||
/>
|
||||
)}
|
||||
</div>
|
||||
)
|
||||
}
|
||||
@@ -8,6 +8,8 @@ import type {
|
||||
ContentPart,
|
||||
} from "../api/types";
|
||||
import type { paths, components } from "../api/opencode-types";
|
||||
import { parseNetworkError } from "../lib/opencode-errors";
|
||||
import { showToast } from "../lib/toast";
|
||||
|
||||
const titleGeneratingSessionsState = new Set<string>();
|
||||
const titleGeneratingListeners = new Set<() => void>();
|
||||
@@ -322,12 +324,18 @@ export const useSendPrompt = (opcodeUrl: string | null | undefined, directory?:
|
||||
|
||||
return { optimisticUserID, response, userPromptText };
|
||||
},
|
||||
onError: (_, variables) => {
|
||||
onError: (error, variables) => {
|
||||
const { sessionID } = variables;
|
||||
queryClient.setQueryData<MessageListResponse>(
|
||||
["opencode", "messages", opcodeUrl, sessionID, directory],
|
||||
(old) => old?.filter((msg) => !msg.info.id.startsWith("optimistic_")),
|
||||
);
|
||||
|
||||
const parsed = parseNetworkError(error);
|
||||
showToast.error(parsed.title, {
|
||||
description: parsed.message,
|
||||
duration: 5000,
|
||||
});
|
||||
},
|
||||
onSuccess: async (data, variables) => {
|
||||
const { sessionID } = variables;
|
||||
|
||||
@@ -7,6 +7,7 @@ import { settingsApi } from '@/api/settings'
|
||||
import { useSessionStatus } from '@/stores/sessionStatusStore'
|
||||
import { useSessionTodos } from '@/stores/sessionTodosStore'
|
||||
import { subscribeToSSE, reconnectSSE, addSSEDirectory, removeSSEDirectory } from '@/lib/sseManager'
|
||||
import { parseOpenCodeError } from '@/lib/opencode-errors'
|
||||
|
||||
const handleRestartServer = async () => {
|
||||
showToast.loading('Restarting OpenCode server...', {
|
||||
@@ -289,6 +290,19 @@ export const useSSE = (opcodeUrl: string | null | undefined, directory?: string)
|
||||
}
|
||||
break
|
||||
|
||||
case 'session.error': {
|
||||
if (!('error' in event.properties)) break
|
||||
|
||||
const parsed = parseOpenCodeError(event.properties.error)
|
||||
if (parsed) {
|
||||
showToast.error(parsed.title, {
|
||||
description: parsed.message,
|
||||
duration: 6000,
|
||||
})
|
||||
}
|
||||
break
|
||||
}
|
||||
|
||||
default:
|
||||
break
|
||||
}
|
||||
|
||||
@@ -0,0 +1,111 @@
|
||||
import type { components } from '@/api/opencode-types'
|
||||
|
||||
export type OpenCodeError =
|
||||
| components['schemas']['ProviderAuthError']
|
||||
| components['schemas']['UnknownError']
|
||||
| components['schemas']['MessageOutputLengthError']
|
||||
| components['schemas']['MessageAbortedError']
|
||||
| components['schemas']['APIError']
|
||||
|
||||
export interface ParsedError {
|
||||
title: string
|
||||
message: string
|
||||
isRetryable: boolean
|
||||
statusCode?: number
|
||||
providerID?: string
|
||||
}
|
||||
|
||||
export function parseOpenCodeError(error: OpenCodeError | undefined | null): ParsedError | null {
|
||||
if (!error) return null
|
||||
|
||||
switch (error.name) {
|
||||
case 'ProviderAuthError':
|
||||
return {
|
||||
title: 'Authentication Failed',
|
||||
message: error.data.message || `Authentication failed for provider: ${error.data.providerID}`,
|
||||
isRetryable: false,
|
||||
providerID: error.data.providerID,
|
||||
}
|
||||
|
||||
case 'UnknownError':
|
||||
return {
|
||||
title: 'Error',
|
||||
message: error.data.message || 'An unknown error occurred',
|
||||
isRetryable: true,
|
||||
}
|
||||
|
||||
case 'MessageOutputLengthError':
|
||||
return {
|
||||
title: 'Response Too Long',
|
||||
message: 'The model response exceeded the maximum allowed length',
|
||||
isRetryable: false,
|
||||
}
|
||||
|
||||
case 'MessageAbortedError':
|
||||
return {
|
||||
title: 'Message Aborted',
|
||||
message: error.data.message || 'The message was aborted',
|
||||
isRetryable: false,
|
||||
}
|
||||
|
||||
case 'APIError':
|
||||
return {
|
||||
title: `API Error${error.data.statusCode ? ` (${error.data.statusCode})` : ''}`,
|
||||
message: error.data.message || 'An API error occurred',
|
||||
isRetryable: error.data.isRetryable,
|
||||
statusCode: error.data.statusCode,
|
||||
}
|
||||
|
||||
default:
|
||||
return {
|
||||
title: 'Error',
|
||||
message: 'An unexpected error occurred',
|
||||
isRetryable: true,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
export function parseNetworkError(error: unknown): ParsedError {
|
||||
if (error instanceof Error) {
|
||||
if (error.message.includes('timeout') || error.message.includes('ETIMEDOUT')) {
|
||||
return {
|
||||
title: 'Request Timeout',
|
||||
message: 'The request took too long to complete. Please try again.',
|
||||
isRetryable: true,
|
||||
}
|
||||
}
|
||||
|
||||
if (error.message.includes('Network Error') || error.message.includes('ECONNREFUSED')) {
|
||||
return {
|
||||
title: 'Connection Failed',
|
||||
message: 'Could not connect to the server. Please check your connection.',
|
||||
isRetryable: true,
|
||||
}
|
||||
}
|
||||
|
||||
if (error.message.includes('502') || error.message.includes('Bad Gateway')) {
|
||||
return {
|
||||
title: 'Server Unavailable',
|
||||
message: 'The OpenCode server is not responding. It may need to be restarted.',
|
||||
isRetryable: true,
|
||||
}
|
||||
}
|
||||
|
||||
return {
|
||||
title: 'Error',
|
||||
message: error.message,
|
||||
isRetryable: true,
|
||||
}
|
||||
}
|
||||
|
||||
return {
|
||||
title: 'Error',
|
||||
message: 'An unexpected error occurred',
|
||||
isRetryable: true,
|
||||
}
|
||||
}
|
||||
|
||||
export function getErrorMessage(error: OpenCodeError | undefined | null): string {
|
||||
const parsed = parseOpenCodeError(error)
|
||||
return parsed ? `${parsed.title}: ${parsed.message}` : ''
|
||||
}
|
||||
Reference in new issue
Block a user