feat: overhaul AI settings, fix Catty Agent streaming and tool execution

AI Settings:
- Remove External Agents section, add dedicated Codex/Claude Code sections
  with auto-detection and manual path override
- Add OpenRouter model list auto-fetch with searchable dropdown
- Remove standalone Default Model section, integrate into provider cards
- Provider toggle now acts as mutual-exclusive active selector
- Add cross-window state sync via storage events
- Add ErrorBoundary around AI tab for graceful error handling

Catty Agent fixes:
- Fix streaming: use .chat() instead of default Responses API, use
  getReader() pattern instead of for-await, handle text-delta/text chunk
  types correctly per SDK v6
- Fix API key: decrypt encrypted key before passing to SDK
- Fix terminal_execute: use PTY stream (visible in terminal) with MCP
  markers instead of invisible SSH exec channel
- Fix multi-turn: only pass user/assistant text history, skip tool
  messages to avoid SDK schema validation errors
- Fix tool result display: create new assistant message after tool
  results so follow-up text renders correctly

Other:
- Add netcatty:ai:resolve-cli IPC handler for CLI path validation
- Remove Gemini from agent discovery (only Codex + Claude Code)
- Fix lint errors across ChatInput, TerminalLayer, SettingsAITab
- Strip MCP markers from tool execution stdout

Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
This commit is contained in:
bincxzandClaude Opus 4.6 committed 2026-03-15 03:53:39 +08:00
1 parent 3136100514
commit f53bc05cb3
9 files changed
+864 -387

No files matched your search

+115 -19
View File
@@ -591,21 +591,51 @@ const AIChatSidePanelInner: React.FC<AIChatSidePanelProps> = ({
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<string> }).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<AIChatSidePanelProps> = ({
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<AIChatSidePanelProps> = ({
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,
+24
View File
@@ -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 (
<div style={{ padding: 32, color: "#f87171", fontFamily: "monospace", whiteSpace: "pre-wrap" }}>
<h3 style={{ marginBottom: 8 }}>AI Settings Error</h3>
<div>{this.state.error.message}</div>
<div style={{ marginTop: 8, fontSize: 12, color: "#888" }}>{this.state.error.stack}</div>
</div>
);
}
return this.props.children;
}
}
type SettingsState = ReturnType<typeof useSettingsState> & {
availableFonts: TerminalFont[];
};
@@ -238,6 +260,7 @@ const SettingsPageContent: React.FC<{ settings: SettingsState }> = ({ settings }
)}
{mountedTabs.has("ai") && (
<AITabErrorBoundary>
<React.Suspense fallback={null}>
<SettingsAITab
providers={aiState.providers}
@@ -260,6 +283,7 @@ const SettingsPageContent: React.FC<{ settings: SettingsState }> = ({ settings }
setMaxIterations={aiState.setMaxIterations}
/>
</React.Suspense>
</AITabErrorBoundary>
)}
{mountedTabs.has("sync") && (
+3 -2
View File
@@ -922,6 +922,7 @@ const TerminalLayerInner: React.FC<TerminalLayerProps> = ({
// 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<TerminalLayerProps> = ({
const activeIds = new Set<string>();
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(() => {
+1 -2
View File
@@ -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,
File diff suppressed because it is too large. Load diff