diff --git a/application/state/useAIState.ts b/application/state/useAIState.ts index c9323d784..d17bdcd8f 100644 --- a/application/state/useAIState.ts +++ b/application/state/useAIState.ts @@ -1,4 +1,4 @@ -import { useCallback, useState } from 'react'; +import { useCallback, useEffect, useState } from 'react'; import { localStorageAdapter } from '../../infrastructure/persistence/localStorageAdapter'; import { STORAGE_KEY_AI_PROVIDERS, @@ -131,6 +131,45 @@ export function useAIState() { localStorageAdapter.writeNumber(STORAGE_KEY_AI_MAX_ITERATIONS, value); }, []); + // ── Cross-window sync via storage events ── + // When the settings window updates localStorage, the main window picks up changes. + useEffect(() => { + const handleStorage = (e: StorageEvent) => { + switch (e.key) { + case STORAGE_KEY_AI_PROVIDERS: + setProvidersRaw(localStorageAdapter.read(STORAGE_KEY_AI_PROVIDERS) ?? []); + break; + case STORAGE_KEY_AI_ACTIVE_PROVIDER: + setActiveProviderIdRaw(localStorageAdapter.readString(STORAGE_KEY_AI_ACTIVE_PROVIDER) ?? ''); + break; + case STORAGE_KEY_AI_ACTIVE_MODEL: + setActiveModelIdRaw(localStorageAdapter.readString(STORAGE_KEY_AI_ACTIVE_MODEL) ?? ''); + break; + case STORAGE_KEY_AI_PERMISSION_MODE: { + const mode = localStorageAdapter.readString(STORAGE_KEY_AI_PERMISSION_MODE); + if (mode === 'observer' || mode === 'confirm' || mode === 'autonomous') { + setGlobalPermissionModeRaw(mode); + } + break; + } + case STORAGE_KEY_AI_EXTERNAL_AGENTS: + setExternalAgentsRaw(localStorageAdapter.read(STORAGE_KEY_AI_EXTERNAL_AGENTS) ?? []); + break; + case STORAGE_KEY_AI_DEFAULT_AGENT: + setDefaultAgentIdRaw(localStorageAdapter.readString(STORAGE_KEY_AI_DEFAULT_AGENT) ?? 'catty'); + break; + case STORAGE_KEY_AI_COMMAND_TIMEOUT: + setCommandTimeoutRaw(localStorageAdapter.readNumber(STORAGE_KEY_AI_COMMAND_TIMEOUT) ?? 60); + break; + case STORAGE_KEY_AI_MAX_ITERATIONS: + setMaxIterationsRaw(localStorageAdapter.readNumber(STORAGE_KEY_AI_MAX_ITERATIONS) ?? 20); + break; + } + }; + window.addEventListener('storage', handleStorage); + return () => window.removeEventListener('storage', handleStorage); + }, []); + // ── Session CRUD ── const persistSessions = useCallback((next: AISession[]) => { localStorageAdapter.write(STORAGE_KEY_AI_SESSIONS, next); diff --git a/components/AIChatSidePanel.tsx b/components/AIChatSidePanel.tsx index ee346ab4c..e9dbac09c 100644 --- a/components/AIChatSidePanel.tsx +++ b/components/AIChatSidePanel.tsx @@ -591,21 +591,51 @@ const AIChatSidePanelInner: React.FC = ({ permissionMode: globalPermissionMode, }); + // Decrypt API key before passing to SDK + let decryptedApiKey = activeProvider.apiKey; + if (decryptedApiKey && bridge?.credentialsDecrypt) { + try { + decryptedApiKey = await (bridge as { credentialsDecrypt: (v: string) => Promise }).credentialsDecrypt(decryptedApiKey) ?? decryptedApiKey; + } catch (e) { + console.warn('[Catty] API key decryption failed:', e); + } + } + + console.log('[Catty] Creating model:', { + providerId: activeProvider.providerId, + baseURL: activeProvider.baseURL, + hasApiKey: !!decryptedApiKey, + model: activeModelId || activeProvider.defaultModel || '', + }); + const model = createModelFromConfig({ ...activeProvider, + apiKey: decryptedApiKey, defaultModel: activeModelId || activeProvider.defaultModel || '', }); try { - // Build message array for the SDK - const sdkMessages = (currentSession?.messages ?? []) - .filter(m => m.role !== 'system') - .map(m => ({ - role: m.role as 'user' | 'assistant', - content: m.content, - })); + // Build message array for the SDK. + // Only include user and assistant TEXT messages — tool call/result + // history is managed internally by each streamText invocation. + const sdkMessages: Array<{ role: 'user' | 'assistant'; content: string }> = []; + for (const m of (currentSession?.messages ?? [])) { + if (m.role === 'user') { + sdkMessages.push({ role: 'user', content: m.content }); + } else if (m.role === 'assistant' && m.content) { + sdkMessages.push({ role: 'assistant', content: m.content }); + } + // Skip tool messages and empty assistant messages (tool-call-only) + } sdkMessages.push({ role: 'user', content: trimmed }); + console.log('[Catty] streamText request:', { + modelId: model.modelId, + messageCount: sdkMessages.length, + hasTools: Object.keys(tools).length, + systemPromptLength: systemPrompt.length, + }); + const result = streamText({ model, messages: sdkMessages, @@ -615,42 +645,103 @@ const AIChatSidePanelInner: React.FC = ({ abortSignal: abortController.signal, }); - // Stream the response - for await (const chunk of result.fullStream) { + // Stream the response using getReader() to avoid Electron stream hanging issues + let chunkIndex = 0; + // Track last message role locally (React state is stale in async closures) + let lastAddedRole: 'assistant' | 'tool' = 'assistant'; + const reader = result.fullStream.getReader(); + while (true) { + const { done, value: chunk } = await reader.read(); + if (done) break; + if (chunkIndex < 10) { + console.log(`[Catty] chunk[${chunkIndex}]:`, JSON.stringify(chunk).slice(0, 200)); + } + chunkIndex++; switch (chunk.type) { - case 'text-delta': - updateLastMessage(sessionId!, msg => ({ - ...msg, - content: msg.content + chunk.textDelta, - })); + case 'text': + case 'text-delta': { + const text = (chunk as unknown as { text?: string; textDelta?: string }).text + ?? (chunk as unknown as { textDelta?: string }).textDelta; + if (text) { + // If last message was a tool result, create a new assistant message first + if (lastAddedRole === 'tool') { + addMessageToSession(sessionId!, { + id: generateId(), + role: 'assistant', + content: '', + timestamp: Date.now(), + }); + lastAddedRole = 'assistant'; + } + updateLastMessage(sessionId!, msg => ({ + ...msg, + content: msg.content + text, + })); + } + break; + } + case 'reasoning': + case 'reasoning-start': + case 'reasoning-delta': { + const rText = (chunk as unknown as { text?: string }).text; + if (rText) { + if (lastAddedRole === 'tool') { + addMessageToSession(sessionId!, { + id: generateId(), + role: 'assistant', + content: '', + timestamp: Date.now(), + }); + lastAddedRole = 'assistant'; + } + updateLastMessage(sessionId!, msg => ({ + ...msg, + thinking: (msg.thinking || '') + rText, + })); + } + break; + } + case 'reasoning-end': + case 'text-start': + case 'text-end': + case 'start': + case 'finish': + case 'start-step': + case 'finish-step': + // Lifecycle events, no action needed break; case 'tool-call': + console.log(`[Catty] tool-call: ${chunk.toolName}`); updateLastMessage(sessionId!, msg => ({ ...msg, toolCalls: [...(msg.toolCalls || []), { id: chunk.toolCallId, name: chunk.toolName, - arguments: chunk.args, + arguments: (chunk as unknown as { input?: unknown; args?: unknown }).input ?? (chunk as unknown as { args?: unknown }).args, }], executionStatus: 'running', })); break; - case 'tool-result': + case 'tool-result': { + const toolOutput = (chunk as unknown as { output?: unknown; result?: unknown }).output ?? (chunk as unknown as { result?: unknown }).result; + console.log(`[Catty] tool-result: ${chunk.toolCallId}`); addMessageToSession(sessionId!, { id: generateId(), role: 'tool', content: '', toolResults: [{ toolCallId: chunk.toolCallId, - content: typeof chunk.result === 'string' - ? chunk.result - : JSON.stringify(chunk.result), + content: typeof toolOutput === 'string' + ? toolOutput + : JSON.stringify(toolOutput), isError: false, }], timestamp: Date.now(), executionStatus: 'completed', }); + lastAddedRole = 'tool'; break; + } case 'error': updateLastMessage(sessionId!, msg => ({ ...msg, @@ -658,9 +749,14 @@ const AIChatSidePanelInner: React.FC = ({ executionStatus: 'failed', })); break; + default: + // tool-input-start/delta/end and other unknown types + break; } } + console.log(`[Catty] stream finished, total chunks: ${chunkIndex}`); } catch (err) { + console.error('[Catty] streamText error:', err); if (!abortController.signal.aborted) { updateLastMessage(sessionId!, msg => ({ ...msg, diff --git a/components/SettingsPage.tsx b/components/SettingsPage.tsx index f7795e7f2..9ca969b9c 100644 --- a/components/SettingsPage.tsx +++ b/components/SettingsPage.tsx @@ -23,6 +23,28 @@ import type { TerminalFont } from "../infrastructure/config/fonts"; const isMac = typeof navigator !== "undefined" && /Mac|iPhone|iPad/.test(navigator.platform); +class AITabErrorBoundary extends React.Component< + { children: React.ReactNode }, + { error: Error | null } +> { + state: { error: Error | null } = { error: null }; + static getDerivedStateFromError(error: Error) { + return { error }; + } + render() { + if (this.state.error) { + return ( +
+

AI Settings Error

+
{this.state.error.message}
+
{this.state.error.stack}
+
+ ); + } + return this.props.children; + } +} + type SettingsState = ReturnType & { availableFonts: TerminalFont[]; }; @@ -238,6 +260,7 @@ const SettingsPageContent: React.FC<{ settings: SettingsState }> = ({ settings } )} {mountedTabs.has("ai") && ( + = ({ settings } setMaxIterations={aiState.setMaxIterations} /> + )} {mountedTabs.has("sync") && ( diff --git a/components/TerminalLayer.tsx b/components/TerminalLayer.tsx index f401ca5a9..35665bb90 100644 --- a/components/TerminalLayer.tsx +++ b/components/TerminalLayer.tsx @@ -922,6 +922,7 @@ const TerminalLayerInner: React.FC = ({ // AI Chat state const aiState = useAIState(); + const { cleanupOrphanedSessions } = aiState; // On mount: clean up orphaned AI sessions after a short delay // (allows sessions/workspaces to fully initialize) @@ -933,8 +934,8 @@ const TerminalLayerInner: React.FC = ({ const activeIds = new Set(); for (const s of sessions) activeIds.add(s.id); for (const w of workspaces) activeIds.add(w.id); - aiState.cleanupOrphanedSessions(activeIds); - }, [sessions, workspaces, aiState.cleanupOrphanedSessions]); + cleanupOrphanedSessions(activeIds); + }, [sessions, workspaces, cleanupOrphanedSessions]); // Build terminal session context for the AI chat panel const aiTerminalSessions = useMemo(() => { diff --git a/components/ai/ChatInput.tsx b/components/ai/ChatInput.tsx index d09a9a3e2..aa25ec0e7 100644 --- a/components/ai/ChatInput.tsx +++ b/components/ai/ChatInput.tsx @@ -6,14 +6,13 @@ * and a bottom toolbar with muted controls + subtle send button. */ -import { AtSign, Check, ChevronDown, ChevronRight, Cpu, Expand, FileText, FolderOpen, ImageIcon, Plus, X } from 'lucide-react'; +import { AtSign, Check, ChevronDown, ChevronRight, Cpu, Expand, FileText, ImageIcon, Plus, X } from 'lucide-react'; import React, { useCallback, useRef, useState } from 'react'; import { createPortal } from 'react-dom'; import type { FormEvent } from 'react'; import type { UploadedImage } from '../../application/state/useImageUpload'; import { PromptInput, - PromptInputButton, PromptInputFooter, PromptInputSubmit, PromptInputTextarea, diff --git a/components/settings/tabs/SettingsAITab.tsx b/components/settings/tabs/SettingsAITab.tsx index f86309c02..2f0e5e883 100644 --- a/components/settings/tabs/SettingsAITab.tsx +++ b/components/settings/tabs/SettingsAITab.tsx @@ -1,5 +1,5 @@ /** - * Settings AI Tab - AI provider configuration, external agents, and safety settings + * Settings AI Tab - AI provider configuration, agent CLI detection, and safety settings */ import { Bot, @@ -14,16 +14,14 @@ import { Pencil, Plus, RefreshCw, - ScanSearch, Shield, Trash2, X, } from "lucide-react"; -import React, { useCallback, useEffect, useState } from "react"; +import React, { useCallback, useEffect, useMemo, useState } from "react"; import type { AIPermissionMode, AIProviderId, - DiscoveredAgent, ExternalAgentConfig, ProviderConfig, } from "../../../infrastructure/ai/types"; @@ -84,12 +82,19 @@ interface CodexLoginSession { exitCode: number | null; } +interface AgentPathInfo { + path: string | null; + version: string | null; + available: boolean; +} + interface NetcattyAiBridge { aiCodexGetIntegration?: () => Promise; aiCodexStartLogin?: () => Promise<{ ok: boolean; session?: CodexLoginSession; error?: string }>; aiCodexGetLoginSession?: (sessionId: string) => Promise<{ ok: boolean; session?: CodexLoginSession; error?: string }>; aiCodexCancelLogin?: (sessionId: string) => Promise<{ ok: boolean; found?: boolean; session?: CodexLoginSession; error?: string }>; aiCodexLogout?: () => Promise<{ ok: boolean; state?: CodexIntegrationState; isConnected?: boolean; rawOutput?: string; logoutOutput?: string; error?: string }>; + aiResolveCli?: (params: { command: string; customPath?: string }) => Promise; openExternal?: (url: string) => Promise; } @@ -105,22 +110,44 @@ function normalizeCodexBridgeError(error: unknown): string { return message; } +// Agent default configs for registration in externalAgents +const AGENT_DEFAULTS: Record> = { + codex: { + name: "Codex CLI", + args: ["exec", "--full-auto", "--json", "{prompt}"], + icon: "openai", + acpCommand: "codex-acp", + acpArgs: [], + }, + claude: { + name: "Claude Code", + args: ["-p", "--output-format", "text", "{prompt}"], + icon: "claude", + acpCommand: "claude-code-acp", + acpArgs: [], + }, +}; + // --------------------------------------------------------------------------- // Provider icon helper // --------------------------------------------------------------------------- -const PROVIDER_ICON_PATHS: Record = { +type SettingsIconId = AIProviderId | "claude"; + +const SETTINGS_ICON_PATHS: Record = { openai: "/ai/providers/openai.svg", anthropic: "/ai/providers/anthropic.svg", + claude: "/ai/agents/claude.svg", google: "/ai/providers/google.svg", ollama: "/ai/providers/ollama.svg", openrouter: "/ai/providers/openrouter.svg", custom: "/ai/providers/custom.svg", }; -const PROVIDER_COLORS: Record = { +const SETTINGS_ICON_COLORS: Record = { openai: "bg-emerald-600", anthropic: "bg-orange-600", + claude: "bg-orange-600", google: "bg-blue-600", ollama: "bg-purple-600", openrouter: "bg-pink-600", @@ -128,18 +155,18 @@ const PROVIDER_COLORS: Record = { }; const ProviderIconBadge: React.FC<{ - providerId: AIProviderId; + providerId: SettingsIconId; size?: "sm" | "md"; }> = ({ providerId, size = "md" }) => (
, body?: string) => Promise<{ ok: boolean; data: string; error?: string }>; +} + +function getFetchBridge(): FetchBridge | undefined { + return (window as unknown as { netcatty?: FetchBridge }).netcatty; +} + +// --------------------------------------------------------------------------- +// Model Selector (searchable dropdown with remote fetch) +// --------------------------------------------------------------------------- + +const ModelSelector: React.FC<{ + value: string; + onChange: (value: string) => void; + baseURL: string; + modelsEndpoint: string; +}> = ({ value, onChange, baseURL, modelsEndpoint }) => { + const [models, setModels] = useState([]); + const [isLoading, setIsLoading] = useState(false); + const [error, setError] = useState(null); + const [search, setSearch] = useState(""); + const [isOpen, setIsOpen] = useState(false); + const [hasFetched, setHasFetched] = useState(false); + + const fetchModels = useCallback(async () => { + const bridge = getFetchBridge(); + if (!bridge?.aiFetch) return; + + setIsLoading(true); + setError(null); + try { + const url = `${baseURL.replace(/\/+$/, "")}${modelsEndpoint}`; + const result = await bridge.aiFetch(url, "GET"); + if (!result.ok) { + setError(`Failed to fetch models (${result.error || "unknown error"})`); + return; + } + const parsed = JSON.parse(result.data); + const list: FetchedModel[] = (parsed.data || parsed.models || []).map((m: { id: string; name?: string }) => ({ + id: m.id, + name: m.name, + })); + // Sort by name/id + list.sort((a, b) => (a.name || a.id).localeCompare(b.name || b.id)); + setModels(list); + setHasFetched(true); + } catch (err) { + setError(err instanceof Error ? err.message : "Failed to parse response"); + } finally { + setIsLoading(false); + } + }, [baseURL, modelsEndpoint]); + + // Fetch on first open + useEffect(() => { + if (isOpen && !hasFetched && !isLoading) { + void fetchModels(); + } + }, [isOpen, hasFetched, isLoading, fetchModels]); + + const filtered = useMemo(() => { + if (!search.trim()) return models; + const q = search.toLowerCase(); + return models.filter((m) => + m.id.toLowerCase().includes(q) || (m.name && m.name.toLowerCase().includes(q)), + ); + }, [models, search]); + + return ( +
+ {/* Input with dropdown toggle */} +
+
+ onChange(e.target.value)} + onFocus={() => setIsOpen(true)} + placeholder="Search or type model ID..." + className="w-full h-8 rounded-md border border-input bg-background px-3 pr-8 text-sm placeholder:text-muted-foreground focus-visible:outline-none focus-visible:ring-1 focus-visible:ring-ring" + /> + +
+ +
+ + {/* Dropdown */} + {isOpen && ( + <> +
setIsOpen(false)} /> +
+ {/* Search within dropdown */} +
+ setSearch(e.target.value)} + placeholder="Filter models..." + autoFocus + className="w-full h-7 rounded border border-input bg-background px-2 text-xs placeholder:text-muted-foreground focus-visible:outline-none focus-visible:ring-1 focus-visible:ring-ring" + /> +
+ +
+ {isLoading ? ( +
+ + Loading models... +
+ ) : error ? ( +
{error}
+ ) : filtered.length === 0 ? ( +
+ {hasFetched ? "No matching models" : "Click to load models"} +
+ ) : ( + filtered.slice(0, 100).map((m) => ( + + )) + )} + {filtered.length > 100 && ( +
+ Showing first 100 of {filtered.length} models. Type to filter. +
+ )} +
+
+ + )} +
+ ); +}; + const ProviderConfigForm: React.FC<{ provider: ProviderConfig; onSave: (updates: Partial) => void; @@ -174,6 +370,9 @@ const ProviderConfigForm: React.FC<{ const [showApiKey, setShowApiKey] = useState(false); const [isDecrypting, setIsDecrypting] = useState(false); + const preset = PROVIDER_PRESETS[provider.providerId]; + const hasModelsEndpoint = !!preset?.modelsEndpoint; + // Decrypt and load existing API key on mount useEffect(() => { if (provider.apiKey) { @@ -239,7 +438,7 @@ const ProviderConfigForm: React.FC<{ type="text" value={form.baseURL} onChange={(e) => setForm((prev) => ({ ...prev, baseURL: e.target.value }))} - placeholder={PROVIDER_PRESETS[provider.providerId]?.defaultBaseURL || "https://"} + placeholder={preset?.defaultBaseURL || "https://"} className="w-full h-8 rounded-md border border-input bg-background px-3 text-sm placeholder:text-muted-foreground focus-visible:outline-none focus-visible:ring-1 focus-visible:ring-ring" />
@@ -247,13 +446,22 @@ const ProviderConfigForm: React.FC<{ {/* Default Model */}
- setForm((prev) => ({ ...prev, defaultModel: e.target.value }))} - placeholder="e.g. gpt-4o, claude-sonnet-4-20250514" - className="w-full h-8 rounded-md border border-input bg-background px-3 text-sm placeholder:text-muted-foreground focus-visible:outline-none focus-visible:ring-1 focus-visible:ring-ring" - /> + {hasModelsEndpoint ? ( + setForm((prev) => ({ ...prev, defaultModel: val }))} + baseURL={form.baseURL || preset.defaultBaseURL} + modelsEndpoint={preset.modelsEndpoint!} + /> + ) : ( + setForm((prev) => ({ ...prev, defaultModel: e.target.value }))} + placeholder="e.g. gpt-4o, claude-sonnet-4-20250514" + className="w-full h-8 rounded-md border border-input bg-background px-3 text-sm placeholder:text-muted-foreground focus-visible:outline-none focus-visible:ring-1 focus-visible:ring-ring" + /> + )}
{/* Actions */} @@ -411,77 +619,15 @@ const AddProviderDropdown: React.FC<{ }; // --------------------------------------------------------------------------- -// External Agent Card +// Codex Connection Card (with path detection) // --------------------------------------------------------------------------- -const ExternalAgentCard: React.FC<{ - agent: ExternalAgentConfig; - isDefault: boolean; - onToggleEnabled: (enabled: boolean) => void; - onSetDefault: () => void; - onRemove: () => void; -}> = ({ agent, isDefault, onToggleEnabled, onSetDefault, onRemove }) => ( -
-
- -
-
-
- {agent.name} - {isDefault && ( - - Default - - )} -
-
- {agent.command} {agent.args?.join(" ") ?? ""} -
-
-
- {!isDefault && ( - - )} - - -
-
-); - -const DetectedAgentCard: React.FC<{ - agent: DiscoveredAgent; - onAdd: () => void; -}> = ({ agent, onAdd }) => ( -
-
- -
-
-
{agent.name}
-
- {agent.version || agent.path} -
-
- -
-); - const CodexConnectionCard: React.FC<{ + pathInfo: AgentPathInfo | null; + isResolvingPath: boolean; + customPath: string; + onCustomPathChange: (path: string) => void; + onRecheckPath: () => void; integration: CodexIntegrationStatus | null; loginSession: CodexLoginSession | null; isLoading: boolean; @@ -493,6 +639,11 @@ const CodexConnectionCard: React.FC<{ onOpenUrl: () => void; onLogout: () => void; }> = ({ + pathInfo, + isResolvingPath, + customPath, + onCustomPathChange, + onRecheckPath, integration, loginSession, isLoading, @@ -504,21 +655,31 @@ const CodexConnectionCard: React.FC<{ onOpenUrl, onLogout, }) => { - const status = loginSession?.state === "running" - ? "Awaiting login" - : integration?.state === "connected_chatgpt" - ? "Connected via ChatGPT" - : integration?.state === "connected_api_key" - ? "Connected via API key" - : integration?.state === "not_logged_in" - ? "Not connected" - : "Status unknown"; + const found = pathInfo?.available; - const statusClassName = loginSession?.state === "running" - ? "text-amber-500" - : integration?.isConnected - ? "text-emerald-500" - : "text-muted-foreground"; + const status = isResolvingPath + ? "Detecting..." + : !found + ? "Not found" + : loginSession?.state === "running" + ? "Awaiting login" + : integration?.state === "connected_chatgpt" + ? "Connected via ChatGPT" + : integration?.state === "connected_api_key" + ? "Connected via API key" + : integration?.state === "not_logged_in" + ? "Not connected" + : "Status unknown"; + + const statusClassName = isResolvingPath + ? "text-muted-foreground" + : !found + ? "text-amber-500" + : loginSession?.state === "running" + ? "text-amber-500" + : integration?.isConnected + ? "text-emerald-500" + : "text-muted-foreground"; const outputText = loginSession?.error ? loginSession.error @@ -546,40 +707,78 @@ const CodexConnectionCard: React.FC<{
-
- {loginSession?.state === "running" ? ( - <> - -
+ + ) : null} + + {/* Connection & login UI – only when codex is detected */} + {found && ( + <> +
+ {loginSession?.state === "running" ? ( + <> + + + + ) : integration?.isConnected ? ( + + ) : ( + + )} + + - - ) : integration?.isConnected ? ( - - ) : ( - - )} +
- - - - {hasOpenAiProviderKey && ( -

- Enabled OpenAI provider API key detected. Codex ACP can also authenticate without ChatGPT login. -

+ {hasOpenAiProviderKey && ( +

+ Enabled OpenAI provider API key detected. Codex ACP can also authenticate without ChatGPT login. +

+ )} + )} {error && ( @@ -588,7 +787,7 @@ const CodexConnectionCard: React.FC<{

)} - {outputText && ( + {found && outputText && (
           {outputText}
         
@@ -598,69 +797,85 @@ const CodexConnectionCard: React.FC<{ }; // --------------------------------------------------------------------------- -// Add Agent Form +// Claude Code Card (with path detection) // --------------------------------------------------------------------------- -const AddAgentForm: React.FC<{ - onAdd: (agent: ExternalAgentConfig) => void; - onCancel: () => void; -}> = ({ onAdd, onCancel }) => { - const [name, setName] = useState(""); - const [command, setCommand] = useState(""); - const [args, setArgs] = useState(""); +const ClaudeCodeCard: React.FC<{ + pathInfo: AgentPathInfo | null; + isResolvingPath: boolean; + customPath: string; + onCustomPathChange: (path: string) => void; + onRecheckPath: () => void; +}> = ({ + pathInfo, + isResolvingPath, + customPath, + onCustomPathChange, + onRecheckPath, +}) => { + const found = pathInfo?.available; - const handleSubmit = useCallback(() => { - if (!name.trim() || !command.trim()) return; - onAdd({ - id: `agent_${Date.now()}_${Math.random().toString(36).slice(2, 6)}`, - name: name.trim(), - command: command.trim(), - args: args.trim() ? args.trim().split(/\s+/) : undefined, - enabled: true, - }); - }, [name, command, args, onAdd]); + const statusText = isResolvingPath + ? "Detecting..." + : found + ? "Detected" + : "Not found"; + + const statusClassName = isResolvingPath + ? "text-muted-foreground" + : found + ? "text-emerald-500" + : "text-amber-500"; return (
-
- - setName(e.target.value)} - placeholder="Agent name" - className="w-full h-8 rounded-md border border-input bg-background px-3 text-sm placeholder:text-muted-foreground focus-visible:outline-none focus-visible:ring-1 focus-visible:ring-ring" - /> -
-
- - setCommand(e.target.value)} - placeholder="e.g. /usr/local/bin/my-agent" - className="w-full h-8 rounded-md border border-input bg-background px-3 text-sm font-mono placeholder:text-muted-foreground focus-visible:outline-none focus-visible:ring-1 focus-visible:ring-ring" - /> -
-
- - setArgs(e.target.value)} - placeholder="e.g. --stdio --verbose" - className="w-full h-8 rounded-md border border-input bg-background px-3 text-sm font-mono placeholder:text-muted-foreground focus-visible:outline-none focus-visible:ring-1 focus-visible:ring-ring" - /> -
-
- - +
+
+
+ + Claude Code +
+

+ Anthropic's agentic coding assistant. Uses claude-code-acp for ACP protocol streaming. +

+
+
+ {statusText} +
+ + {/* Path detection info */} + {found ? ( +
+ Path: + {pathInfo.path} + {pathInfo.version && ( + <> + | + {pathInfo.version} + + )} +
+ ) : !isResolvingPath ? ( +
+

+ Could not find claude in PATH. Install it or specify the executable path below. +

+
+ onCustomPathChange(e.target.value)} + placeholder="e.g. /usr/local/bin/claude" + className="flex-1 h-8 rounded-md border border-input bg-background px-3 text-sm font-mono placeholder:text-muted-foreground focus-visible:outline-none focus-visible:ring-1 focus-visible:ring-ring" + /> + +
+
+ ) : null}
); }; @@ -676,7 +891,7 @@ const SettingsAITab: React.FC = ({ removeProvider, activeProviderId, setActiveProviderId, - activeModelId, + activeModelId: _activeModelId, setActiveModelId, globalPermissionMode, setGlobalPermissionMode, @@ -690,19 +905,107 @@ const SettingsAITab: React.FC = ({ setMaxIterations, }) => { const [editingProviderId, setEditingProviderId] = useState(null); - const [showAddAgent, setShowAddAgent] = useState(false); const [codexIntegration, setCodexIntegration] = useState(null); const [codexLoginSession, setCodexLoginSession] = useState(null); const [isCodexLoading, setIsCodexLoading] = useState(false); const [codexError, setCodexError] = useState(null); + // Path detection state + const [codexPathInfo, setCodexPathInfo] = useState(null); + const [codexCustomPath, setCodexCustomPath] = useState(""); + const [isResolvingCodex, setIsResolvingCodex] = useState(false); + + const [claudePathInfo, setClaudePathInfo] = useState(null); + const [claudeCustomPath, setClaudeCustomPath] = useState(""); + const [isResolvingClaude, setIsResolvingClaude] = useState(false); + const { - unconfiguredAgents, + discoveredAgents, isDiscovering, - rediscover, enableAgent, } = useAgentDiscovery(externalAgents, setExternalAgents); + // Derive path info from discovery results + useEffect(() => { + if (isDiscovering) return; + + const codex = discoveredAgents.find((a) => a.command === "codex"); + setCodexPathInfo( + codex + ? { path: codex.path, version: codex.version, available: true } + : { path: null, version: null, available: false }, + ); + + const claude = discoveredAgents.find((a) => a.command === "claude"); + setClaudePathInfo( + claude + ? { path: claude.path, version: claude.version, available: true } + : { path: null, version: null, available: false }, + ); + }, [isDiscovering, discoveredAgents]); + + // Auto-register discovered agents in externalAgents + useEffect(() => { + if (isDiscovering || discoveredAgents.length === 0) return; + + setExternalAgents((prev) => { + const agentsToRegister: ExternalAgentConfig[] = []; + + for (const da of discoveredAgents) { + if (da.command !== "codex" && da.command !== "claude") continue; + const agentId = `discovered_${da.command}`; + if (prev.some((ea) => ea.id === agentId)) continue; + agentsToRegister.push(enableAgent(da)); + } + + return agentsToRegister.length > 0 ? [...prev, ...agentsToRegister] : prev; + }); + }, [isDiscovering, discoveredAgents, enableAgent, setExternalAgents]); + + // Validate a custom path for an agent + const handleCheckCustomPath = useCallback(async (agentKey: "codex" | "claude") => { + const bridge = getBridge(); + if (!bridge?.aiResolveCli) return; + + const customPath = agentKey === "codex" ? codexCustomPath : claudeCustomPath; + const setInfo = agentKey === "codex" ? setCodexPathInfo : setClaudePathInfo; + const setResolving = agentKey === "codex" ? setIsResolvingCodex : setIsResolvingClaude; + + setResolving(true); + try { + const result = await bridge.aiResolveCli({ + command: agentKey, + customPath: customPath.trim(), + }); + setInfo(result); + + // Register/update in externalAgents if valid + if (result.available && result.path) { + const agentId = `discovered_${agentKey}`; + const defaults = AGENT_DEFAULTS[agentKey]; + setExternalAgents((prev) => { + const idx = prev.findIndex((a) => a.id === agentId); + const config: ExternalAgentConfig = { + id: agentId, + command: result.path!, + enabled: true, + ...defaults, + }; + if (idx >= 0) { + const updated = [...prev]; + updated[idx] = { ...updated[idx], command: result.path! }; + return updated; + } + return [...prev, config]; + }); + } + } catch (err) { + console.error("Path resolution failed:", err); + } finally { + setResolving(false); + } + }, [codexCustomPath, claudeCustomPath, setExternalAgents]); + // Add a new provider from preset const handleAddProvider = useCallback( (providerId: AIProviderId) => { @@ -732,10 +1035,6 @@ const SettingsAITab: React.FC = ({ [removeProvider, editingProviderId], ); - // Provider options for default model select - const enabledProviders = providers.filter((p) => p.enabled); - const providerOptions = enabledProviders.map((p) => ({ value: p.id, label: p.name })); - // Permission mode options const permissionModeOptions = [ { value: "observer", label: "Observer - Read only, no actions" }, @@ -744,12 +1043,12 @@ const SettingsAITab: React.FC = ({ ]; // Agent options for default agent - const agentOptions = [ + const agentOptions = useMemo(() => [ { value: "catty", label: "Catty (Built-in)" }, ...externalAgents .filter((a) => a.enabled) .map((a) => ({ value: a.id, label: a.name })), - ]; + ], [externalAgents]); const hasOpenAiProviderKey = providers.some( (provider) => provider.providerId === "openai" && provider.enabled && !!provider.apiKey, @@ -809,41 +1108,6 @@ const SettingsAITab: React.FC = ({ }; }, [codexLoginSession, refreshCodexIntegration]); - // Add external agent - const handleAddAgent = useCallback( - (agent: ExternalAgentConfig) => { - setExternalAgents((prev) => [...prev, agent]); - setShowAddAgent(false); - }, - [setExternalAgents], - ); - - const handleAddDiscoveredAgent = useCallback((agent: DiscoveredAgent) => { - const config = enableAgent(agent); - setExternalAgents((prev) => [...prev, config]); - }, [enableAgent, setExternalAgents]); - - // Remove external agent - const handleRemoveAgent = useCallback( - (id: string) => { - setExternalAgents((prev) => prev.filter((a) => a.id !== id)); - if (defaultAgentId === id) { - setDefaultAgentId("catty"); - } - }, - [setExternalAgents, defaultAgentId, setDefaultAgentId], - ); - - // Toggle agent enabled - const handleToggleAgent = useCallback( - (id: string, enabled: boolean) => { - setExternalAgents((prev) => - prev.map((a) => (a.id === id ? { ...a, enabled } : a)), - ); - }, - [setExternalAgents], - ); - const handleStartCodexLogin = useCallback(async () => { const bridge = getBridge(); if (!bridge?.aiCodexStartLogin) return; @@ -944,16 +1208,39 @@ const SettingsAITab: React.FC = ({ key={provider.id} provider={provider} isActive={provider.id === activeProviderId} - onToggleEnabled={(enabled) => - updateProvider(provider.id, { enabled }) - } + onToggleEnabled={(enabled) => { + if (enabled) { + // Activate this provider, deactivate others + setActiveProviderId(provider.id); + if (provider.defaultModel) { + setActiveModelId(provider.defaultModel); + } + // Ensure it's enabled + if (!provider.enabled) { + updateProvider(provider.id, { enabled: true }); + } + } else { + // Deactivate: clear active provider if this was it + if (activeProviderId === provider.id) { + setActiveProviderId(""); + setActiveModelId(""); + } + updateProvider(provider.id, { enabled: false }); + } + }} onEdit={() => setEditingProviderId( editingProviderId === provider.id ? null : provider.id, ) } onRemove={() => handleRemoveProvider(provider.id)} - onUpdate={(updates) => updateProvider(provider.id, updates)} + onUpdate={(updates) => { + updateProvider(provider.id, updates); + // If this is the active provider and model changed, update activeModelId + if (provider.id === activeProviderId && updates.defaultModel !== undefined) { + setActiveModelId(updates.defaultModel || ""); + } + }} isEditing={editingProviderId === provider.id} onCancelEdit={() => setEditingProviderId(null)} /> @@ -962,42 +1249,6 @@ const SettingsAITab: React.FC = ({ )}
- {/* ── Default Model Section ── */} -
-
- -

Default Model

-
- -
- - setActiveModelId(e.target.value)} - placeholder="e.g. gpt-4o" - className="w-48 h-9 rounded-md border border-input bg-background px-3 text-sm placeholder:text-muted-foreground focus-visible:outline-none focus-visible:ring-1 focus-visible:ring-ring" - /> - -
-
- {/* ── Codex Section ── */}
@@ -1006,6 +1257,11 @@ const SettingsAITab: React.FC = ({
void handleCheckCustomPath("codex")} integration={codexIntegration} loginSession={codexLoginSession} isLoading={isCodexLoading} @@ -1019,82 +1275,30 @@ const SettingsAITab: React.FC = ({ />
- {/* ── External Agents Section ── */} + {/* ── Claude Code Section ── */}
-
-
- -

External Agents

-
-
- - -
+
+ +

Claude Code

- {showAddAgent && ( - setShowAddAgent(false)} - /> - )} + void handleCheckCustomPath("claude")} + /> +
- {unconfiguredAgents.length > 0 && ( -
-
- Detected on this machine -
- {unconfiguredAgents.map((agent) => ( - handleAddDiscoveredAgent(agent)} - /> - ))} + {/* ── Default Agent Section ── */} + {agentOptions.length > 1 && ( +
+
+ +

Default Agent

- )} - {externalAgents.length === 0 && unconfiguredAgents.length === 0 && !showAddAgent ? ( -
- -

- No external agents configured. Scan for agents or add one manually. -

-
- ) : ( -
- {externalAgents.map((agent) => ( - handleToggleAgent(agent.id, enabled)} - onSetDefault={() => setDefaultAgentId(agent.id)} - onRemove={() => handleRemoveAgent(agent.id)} - /> - ))} -
- )} - - {/* Default Agent selection */} - {agentOptions.length > 1 && (
= ({ />
- )} -
+
+ )} {/* ── Safety Section ── */}
diff --git a/electron/bridges/aiBridge.cjs b/electron/bridges/aiBridge.cjs index e6901a5b4..c6626aef8 100644 --- a/electron/bridges/aiBridge.cjs +++ b/electron/bridges/aiBridge.cjs @@ -455,6 +455,86 @@ function streamRequest(url, options, event, requestId) { }); } +/** + * Execute command through the terminal PTY stream (visible in terminal). + * Uses unique markers to detect when the command finishes and capture output. + * Same approach as MCP server's execViaPty. + */ +function execViaPtyForCatty(ptyStream, command) { + const marker = `__NCMCP_${Date.now().toString(36)}_${Math.random().toString(36).slice(2, 6)}__`; + + return new Promise((resolve) => { + let output = ""; + let foundStart = false; + let timeoutId = null; + + const MAX_TIMEOUT = 300000; // 5 min + + const onData = (data) => { + const text = data.toString(); + + if (!foundStart) { + const startIdx = text.indexOf(marker + "_S"); + if (startIdx !== -1) { + foundStart = true; + const afterMarker = text.slice(startIdx); + const nlIdx = afterMarker.indexOf("\n"); + if (nlIdx !== -1) { + output += afterMarker.slice(nlIdx + 1); + } + } + if (foundStart) checkEnd(); + return; + } + + output += text; + checkEnd(); + }; + + function checkEnd() { + const endPattern = marker + "_E:"; + const endIdx = output.indexOf(endPattern); + if (endIdx === -1) return; + + const afterEnd = output.slice(endIdx + endPattern.length); + const codeMatch = afterEnd.match(/^(\d+)/); + const exitCode = codeMatch ? parseInt(codeMatch[1], 10) : null; + + const stdout = output.slice(0, endIdx); + finish(stdout, exitCode); + } + + function finish(stdout, exitCode) { + clearTimeout(timeoutId); + ptyStream.removeListener("data", onData); + // Strip ANSI codes and any leaked MCP markers + let cleaned = stripAnsi(stdout || "").trim(); + cleaned = cleaned.replace(/__NCMCP_[^\r\n]*[\r\n]*/g, "").trim(); + resolve({ + ok: exitCode === 0 || exitCode === null, + stdout: cleaned, + stderr: "", + exitCode: exitCode ?? 0, + }); + } + + timeoutId = setTimeout(() => { + ptyStream.removeListener("data", onData); + if (typeof ptyStream.write === "function") ptyStream.write("\x03"); + const cleaned = stripAnsi(output).trim(); + resolve({ ok: false, stdout: cleaned, stderr: "", exitCode: -1, error: "Command timed out (5min)" }); + }, MAX_TIMEOUT); + + ptyStream.on("data", onData); + + const noPager = "PAGER=cat SYSTEMD_PAGER= GIT_PAGER=cat LESS= "; + ptyStream.write( + `printf '${marker}_S\\n';${noPager}${command}\n` + + `__nc=$?;printf '${marker}_E:'$__nc'\\n';(exit $__nc)\n` + ); + }); +} + function registerHandlers(ipcMain) { // Start a streaming chat request (proxied through main process) ipcMain.handle("netcatty:ai:chat:stream", async (event, { requestId, url, headers, body }) => { @@ -514,6 +594,8 @@ function registerHandlers(ipcMain) { }); // Execute a command on a terminal session (for Catty Agent) + // Uses PTY-based execution so commands are visible in the terminal, + // matching the MCP server approach with start/end markers. ipcMain.handle("netcatty:ai:exec", async (_event, { sessionId, command }) => { const session = sessions?.get(sessionId); if (!session) { @@ -521,10 +603,17 @@ function registerHandlers(ipcMain) { } try { - // Use SSH exec for remote sessions - if (session.sshClient) { + // Prefer PTY stream (visible in terminal) — same approach as MCP server + const ptyStream = session.stream || session.pty; + if (ptyStream && typeof ptyStream.write === "function") { + return execViaPtyForCatty(ptyStream, command); + } + + // Fallback: SSH exec channel (invisible to terminal) + const sshClient = session.sshClient || session.conn; + if (sshClient && typeof sshClient.exec === "function") { return new Promise((resolve) => { - session.sshClient.exec(command, (err, stream) => { + sshClient.exec(command, (err, stream) => { if (err) { resolve({ ok: false, error: err.message }); return; @@ -540,8 +629,7 @@ function registerHandlers(ipcMain) { }); } - // For local sessions, we can't easily exec - return info about session type - return { ok: false, error: "Command execution only supported for SSH sessions" }; + return { ok: false, error: "No terminal stream or SSH client available for this session" }; } catch (err) { return { ok: false, error: err?.message || String(err) }; } @@ -918,15 +1006,6 @@ function registerHandlers(ipcMain) { acpArgs: [], args: ["exec", "--full-auto", "--json", "{prompt}"], }, - { - command: "gemini", - name: "Gemini CLI", - icon: "gemini", - description: "Google's Gemini CLI agent", - acpCommand: "gemini", - acpArgs: ["--experimental-acp"], - args: ["{prompt}"], - }, ]; const shellEnv = await getShellEnv(); @@ -977,6 +1056,35 @@ function registerHandlers(ipcMain) { return agents; }); + // Resolve a CLI binary path (auto-detect or validate custom path) + ipcMain.handle("netcatty:ai:resolve-cli", async (_event, { command, customPath }) => { + const shellEnv = await getShellEnv(); + let resolvedPath = null; + + if (customPath) { + // User provided a custom path – validate it exists + if (existsSync(customPath)) { + resolvedPath = customPath; + } + } else { + resolvedPath = resolveCliFromPath(command, shellEnv); + } + + if (!resolvedPath) { + return { path: null, version: null, available: false }; + } + + let version = ""; + try { + const result = await runCommand(resolvedPath, ["--version"], { env: shellEnv }); + version = (result.stdout || result.stderr || "").trim().split("\n")[0]; + } catch { + version = ""; + } + + return { path: resolvedPath, version, available: true }; + }); + ipcMain.handle("netcatty:ai:codex:get-integration", async () => { try { const result = await runCodexCli(["login", "status"]); diff --git a/electron/preload.cjs b/electron/preload.cjs index a998964d9..17b7ed0cf 100644 --- a/electron/preload.cjs +++ b/electron/preload.cjs @@ -1007,6 +1007,9 @@ const api = { aiDiscoverAgents: async () => { return ipcRenderer.invoke("netcatty:ai:agents:discover"); }, + aiResolveCli: async (params) => { + return ipcRenderer.invoke("netcatty:ai:resolve-cli", params); + }, aiCodexGetIntegration: async () => { return ipcRenderer.invoke("netcatty:ai:codex:get-integration"); }, diff --git a/infrastructure/ai/sdk/providers.ts b/infrastructure/ai/sdk/providers.ts index 3c0649018..6226fa445 100644 --- a/infrastructure/ai/sdk/providers.ts +++ b/infrastructure/ai/sdk/providers.ts @@ -198,11 +198,12 @@ export function createModelFromConfig(config: ProviderConfig) { switch (config.providerId) { case 'openai': + // Use .chat() to force Chat Completions API (not Responses API) return createOpenAI({ apiKey: config.apiKey, baseURL: config.baseURL, fetch: customFetch, - })(modelId); + }).chat(modelId); case 'anthropic': return createAnthropic({ @@ -219,25 +220,27 @@ export function createModelFromConfig(config: ProviderConfig) { })(modelId); case 'ollama': - // Ollama uses OpenAI-compatible API + // Ollama uses OpenAI-compatible Chat Completions API return createOpenAI({ apiKey: 'ollama', baseURL: config.baseURL || 'http://localhost:11434/v1', fetch: customFetch, - })(modelId); + }).chat(modelId); case 'openrouter': + // OpenRouter uses OpenAI-compatible Chat Completions API return createOpenAI({ apiKey: config.apiKey, baseURL: config.baseURL || 'https://openrouter.ai/api/v1', fetch: customFetch, - })(modelId); + }).chat(modelId); case 'custom': + // Custom providers use OpenAI-compatible Chat Completions API return createOpenAI({ apiKey: config.apiKey, baseURL: config.baseURL, fetch: customFetch, - })(modelId); + }).chat(modelId); } }