Files
Netcatty/components/AIChatSidePanel.tsx
T
cc5ad3be16 perf: isolate Terminal hot props, cut memory/jank, and repay architecture debt (#2790)
* refactor: migrate architecture-debt hooks into application/state

Move SFTP Wave A stores/hooks and related vault/AI/terminal/systemManager
hooks out of components into application/state, update importers, and keep
thin deprecated re-exports at the old paths.

Co-authored-by: 陈大猫 <binaricat@users.noreply.github.com>

* refactor(sftp): align local bookmarks store API with global bookmarks

Export subscribe/get/set/rehydrate helpers from localSftpBookmarks to match
the globalSftpBookmarks external-store pattern.

Co-authored-by: 陈大猫 <binaricat@users.noreply.github.com>

* fix(electron): reduce baseline memory via spellcheck/GPU/prewarm guards

Disable spellcheck on BrowserWindows and the default session, drop spare
renderers, gate aggressive GPU switches behind NETCATTY_COMPAT_GPU, and make
settings prewarm opt-in via NETCATTY_PREWARM_SETTINGS.

Co-authored-by: 陈大猫 <binaricat@users.noreply.github.com>

* Isolate notes and customAccent from TerminalLayer hot props

Route vault notes through notesStore (shellHistoryStore pattern) and
app accent through appearanceChromeStore so note edits and accent-drag
ticks no longer rebuild TerminalLayer. Notes/AI slots and Terminal leaves
subscribe locally; VaultView and open-note callbacks stay unchanged.

Co-authored-by: 陈大猫 <binaricat@users.noreply.github.com>

* fix(ui): cut unnecessary AppView/VaultView/settings re-renders

Stabilize TopTabs close handler, memo AppHostTreeLayer, exclude accent from
settingsVersion, ignore connectionLogs off the logs section, share lastConnected
host refs, and keep rename dialog drafts local so chrome domain stays stable.

Co-authored-by: 陈大猫 <binaricat@users.noreply.github.com>

* chore: package size, dead code, and consolidation cleanup

Remove unused direct deps, exclude Vite-bundled renderer packages from
electron-builder, delete high-confidence dead code/no-op transfer warm
wiring, consolidate cloud provider IDs and KnownHost/SFTP helpers, and
land UI/AGENTS quick wins (rAF text batching, notes draft debounce,
streaming plain text, tempDirBridge, diagnostics adapter, External MCP
setters).

Co-authored-by: 陈大猫 <binaricat@users.noreply.github.com>

* fix: stabilize rAF text batching and diagnostics tests

Polyfill requestAnimationFrame for Node, flush pending text before
steer buffering, bypass rAF while steer is in flight, and stub
global localStorage for AI panel diagnostics adapter tests.

Co-authored-by: 陈大猫 <binaricat@users.noreply.github.com>

* fix: correct import paths after application/state hook migrations

Migrated vault/AI/system hooks still used components/-relative imports;
point them at repo-root domain/components/types/lib instead.

Co-authored-by: 陈大猫 <binaricat@users.noreply.github.com>

* fix: address Bugbot/Codex regressions from perf cleanup

- Keep blank Enter from closing RenameDraftDialog; only reset rename state after a non-empty submit
- Flush note drafts before vault mutations so pending title/body edits are not overwritten
- Re-apply appearanceChromeStore accent on appearanceTheme in Terminal, and keep layer themes unaccented

Co-authored-by: 陈大猫 <binaricat@users.noreply.github.com>

* fix(notes): flush draft before markdown export paths

Co-authored-by: 陈大猫 <binaricat@users.noreply.github.com>

* fix: keep editor-close hotkey ref fresh during render

Assign handleRequestCloseEditorTabRef in render instead of useEffect so
Cmd/Ctrl+W never hits the App stub before the effect runs.

Co-authored-by: 陈大猫 <binaricat@users.noreply.github.com>

* fix: keep accent in chrome themes without TerminalLayer thrash

Restore accent in globalAppearance for chrome/injection consumers.
Keep resolveFocusedAppearance identity stable across accent drag via
accent ref, while Terminal leaf still re-applies appearanceChromeStore.

Co-authored-by: 陈大猫 <binaricat@users.noreply.github.com>

* fix: keep compose chrome accent live and merge note renames

Subscribe theme-panel focusedAppearance to appearanceChromeStore so
compose-bar chrome updates during color-picker drag even when
resolveFocusedAppearance identity stays stable. Tree renames now merge
title into the post-flush note instead of replacing from a stale row.

Co-authored-by: 陈大猫 <binaricat@users.noreply.github.com>

* fix: clear terminal accent when switching back to theme mode

Re-resolve appearanceTheme by catalog id before applyCustomAccent so a
stale baked custom cursor/selection cannot stick after accentMode returns
to theme while TerminalLayer memo ignores accent props.

Co-authored-by: 陈大猫 <binaricat@users.noreply.github.com>

* fix: register unsaved prompt singleton during render

AppView close handlers call promptUnsavedChanges outside the old
render-prop. Assign the singleton during render so Cmd/Ctrl+W and tab
close never hit the pre-effect null window that auto-cancels.

Co-authored-by: 陈大猫 <binaricat@users.noreply.github.com>

* fix: keep vault import hooks UI-free and flush notes on teardown

Move ImportOptions into application/state and inject a notifier so
useVaultImportHandlers no longer imports components. Notes drafts also
flush on pagehide/beforeunload when Electron tears down without React
unmount.

Co-authored-by: 陈大猫 <binaricat@users.noreply.github.com>

* fix: move AI terminal session context builders into domain

buildAITerminalSessionInfo and AIPanelContext now live under domain/ so
application hooks no longer import TerminalLayerSupport and create a
UI → application → UI cycle.

Co-authored-by: 陈大猫 <binaricat@users.noreply.github.com>

* fix: drop duplicate AIPanelContext type from TerminalLayerSupport

The type is re-exported from domain; the local definition conflicted.

Co-authored-by: 陈大猫 <binaricat@users.noreply.github.com>

* fix: keep migrated state hooks free of UI-layer imports

Move aiChatStreamingSupport into infrastructure/ai and poll list helpers
into domain/systemManager so useAIChatStreaming / useSystemManager no
longer import from components. Leave thin re-exports at the old paths.

Co-authored-by: 陈大猫 <binaricat@users.noreply.github.com>

* fix: move remaining migrated-hook deps out of components

Host-key verification types/helpers now live in domain/, and SFTP column
layout types live in application/state/sftp/columnLayout. Application
hooks no longer import those definitions from the UI layer.

Co-authored-by: 陈大猫 <binaricat@users.noreply.github.com>

* fix: clear lint blockers and flush notes when panels hide

Move AI panel diagnostics persistence into application/state so
components stop importing localStorageAdapter. Flush note drafts when
retained NotesManager mounts become inactive, and silence related lint
warnings in theme/host-key helpers.

Co-authored-by: 陈大猫 <binaricat@users.noreply.github.com>

* fix(notes): publish notesStore sync on vault note updates

updateNotes/updateNoteGroups now publishNotesSnapshot immediately so
AI/notes consumers do not briefly read a stale catalog after a hide
flush. Flush inactive drafts in useLayoutEffect before paint.

Co-authored-by: 陈大猫 <binaricat@users.noreply.github.com>

---------

Co-authored-by: Cursor Agent <cursoragent@cursor.com>
Co-authored-by: 陈大猫 <binaricat@users.noreply.github.com>
2026-08-07 14:40:38 +08:00

1648 lines
58 KiB
TypeScript

import React, { useCallback, useEffect, useDeferredValue, useMemo, useRef, useState } from 'react';
import { Loader2 } from 'lucide-react';
import { useI18n } from '../application/i18n/I18nProvider';
import { useWindowControls } from '../application/state/useWindowControls';
import type {
AIDraft,
AIPanelView,
AgentModelPreset,
AISessionScope,
DiscoveredAgent,
ExternalAgentConfig,
} from '../infrastructure/ai/types';
import type { ExecutorContext } from '../infrastructure/ai/cattyAgent/executor';
import {
filterAgentModelPresetsForCliVersion,
getAgentModelPresets,
resolveAgentCliVersion,
resolveAgentModelSelection,
} from '../infrastructure/ai/types';
import { getExternalAgentSdkBackend, getManualAgentCommand, matchesManagedAgentConfig } from '../infrastructure/ai/managedAgents';
import { useAgentDiscovery } from '../application/state/useAgentDiscovery';
import {
getReadyUserSkillOptions,
getNextSelectedUserSkillSlugsMap,
type UserSkillOption,
} from './ai/userSkillsState';
import { subscribeUserSkillsStatusChanged } from './ai/userSkillsStatusEvents';
import {
applyDraftEntrySelection,
applyHistorySessionSelection,
panelViewsEqual,
resolveDisplayedPanelView,
resolveDisplayedSession,
} from './ai/aiPanelViewState';
import {
endDraftSend,
tryBeginDraftSend,
} from './ai/draftSendGate';
import { selectDraftForAgentSwitch } from '../application/state/aiDraftState';
import {
buildPromptWithTerminalSelectionAttachments,
isTerminalSelectionAttachment,
} from '../application/state/terminalSelectionAttachment';
import type { CodexIntegrationStatus } from './settings/tabs/ai/types';
import {
useAIChatStreaming,
getNetcattyBridge,
isAIChatSessionStreaming,
type DefaultTargetSessionHint,
} from '../application/state/useAIChatStreaming';
import { getScopedHistorySessions } from './ai/scopedHistorySessions';
import { aiSessionIdSetEqual, exactScopeAISessionsEqual } from '../domain/aiSessionsForScope';
import { buildExternalAgentHistoryMessagesForBridge } from './ai/externalAgentHistory';
import { canSendWithAgent, findEnabledExternalAgent } from './ai/agentSendEligibility';
import { registerGrantPersister } from '../infrastructure/ai/shared/approvalGate';
import { setupCodexAppServerInteractionBridge } from '../infrastructure/ai/shared/codexAppServerInteractions';
import { stopAgentTurn } from '../infrastructure/ai/harness/agentStop';
import { getAgentRuntime } from '../infrastructure/ai/harness/globalAgentRuntime';
import { useAIPermissionGrantsState } from '../application/state/useAIPermissionGrantsState';
import { useConversationExport } from './ai/hooks/useConversationExport';
import { useAgentContextUsage } from '../application/state/useAgentCompactionUi';
import type { AIChatSidePanelProps } from './AIChatSidePanel.types';
import {
buildCursorListModelsAgentEnv,
buildSdkRuntimeModelCacheKey,
sdkRuntimeModelCache,
generateId,
normalizeSdkRuntimeModelPresets,
shouldAdoptSdkCurrentModel,
shouldLoadSdkRuntimeModels,
shouldUseStoredAgentModel,
type SdkRuntimeModelCatalog,
} from './AIChatSidePanelHelpers';
import { AIChatPanelContent } from './AIChatPanelContent';
import { TERMINAL_SIDE_PANEL_INNER_HEADER_CLASS } from './terminalLayer/terminalSidePanelChrome';
import {
getAIPanelProfilerProps,
profileAIPanelCalculation,
} from './ai/aiPanelDiagnostics';
type UserSkillsStatusResult = { ok: boolean; skills?: Array<{
id: string;
slug: string;
name: string;
description: string;
status: 'ready' | 'warning';
}> } | null;
type UserSkillsStatusLoadResult = UserSkillsStatusResult | undefined;
type SdkRuntimeModelTarget = {
agentId: string;
cacheKey: string;
sdkBackend: string;
agentEnv?: Record<string, string>;
agentCommand?: string;
codexRuntime?: 'sdk' | 'app-server';
};
type SteerWarning = {
reason: 'not-steerable' | 'busy' | 'inactive' | 'unsupported' | 'cancelled' | 'failed';
turnKind?: 'review' | 'compact';
};
const USER_SKILLS_STATUS_CACHE_TTL_MS = 60_000;
let userSkillsStatusCache: {
version: number;
result: UserSkillsStatusResult;
updatedAt: number;
} | null = null;
let userSkillsStatusPromise: {
version: number;
promise: Promise<UserSkillsStatusLoadResult>;
} | null = null;
let userSkillsStatusCacheVersion = 0;
function invalidateUserSkillsStatusCache() {
userSkillsStatusCacheVersion += 1;
userSkillsStatusCache = null;
userSkillsStatusPromise = null;
}
if (typeof window !== 'undefined') {
subscribeUserSkillsStatusChanged(invalidateUserSkillsStatusCache);
}
function loadUserSkillsStatus(
bridge: ReturnType<typeof getNetcattyBridge>,
): Promise<UserSkillsStatusLoadResult> {
const requestVersion = userSkillsStatusCacheVersion;
if (!bridge?.aiUserSkillsGetStatus) {
userSkillsStatusCache = { version: requestVersion, result: null, updatedAt: Date.now() };
return Promise.resolve(null);
}
if (
userSkillsStatusCache
&& userSkillsStatusCache.version === requestVersion
&& Date.now() - userSkillsStatusCache.updatedAt < USER_SKILLS_STATUS_CACHE_TTL_MS
) {
return Promise.resolve(userSkillsStatusCache.result);
}
if (!userSkillsStatusPromise || userSkillsStatusPromise.version !== requestVersion) {
const promise = bridge.aiUserSkillsGetStatus()
.then((result) => {
if (userSkillsStatusCacheVersion !== requestVersion) return undefined;
userSkillsStatusCache = { version: requestVersion, result, updatedAt: Date.now() };
return result;
})
.catch(() => {
if (userSkillsStatusCacheVersion !== requestVersion) return undefined;
userSkillsStatusCache = { version: requestVersion, result: null, updatedAt: Date.now() };
return null;
})
.finally(() => {
if (userSkillsStatusPromise?.version === requestVersion) {
userSkillsStatusPromise = null;
}
});
userSkillsStatusPromise = { version: requestVersion, promise };
}
return userSkillsStatusPromise.promise;
}
export function hasAIChatSidePanelRetainedContent(props: Pick<
AIChatSidePanelProps,
'activeSessionIdMap' | 'draftsByScope' | 'sessions' | 'scopeTargetId' | 'scopeType'
>): boolean {
const scopeKey = `${props.scopeType}:${props.scopeTargetId ?? ''}`;
const sessionId = props.activeSessionIdMap[scopeKey] ?? null;
const activeSession = sessionId
? props.sessions.find((session) => session.id === sessionId)
: null;
if (activeSession && activeSession.messages.length > 0) {
return true;
}
const draft = props.draftsByScope[scopeKey] ?? null;
return Boolean(
draft
&& (
draft.text.trim().length > 0
|| draft.attachments.length > 0
|| draft.selectedUserSkillSlugs.length > 0
),
);
}
export function shouldKeepAIChatSidePanelMounted(props: AIChatSidePanelProps): boolean {
if (props.isVisible ?? true) {
return true;
}
const scopeKey = `${props.scopeType}:${props.scopeTargetId ?? ''}`;
const sessionId = props.activeSessionIdMap[scopeKey] ?? null;
if (hasAIChatSidePanelRetainedContent(props)) {
return true;
}
return isAIChatSessionStreaming(sessionId);
}
function shouldDelayAIChatSidePanelActivation(props: AIChatSidePanelProps): boolean {
if (!(props.isVisible ?? true)) return false;
const scopeKey = `${props.scopeType}:${props.scopeTargetId ?? ''}`;
if (props.draftsByScope[scopeKey] || props.panelViewByScope[scopeKey]?.mode === 'draft') {
return false;
}
const sessionId = props.activeSessionIdMap[scopeKey] ?? null;
if (isAIChatSessionStreaming(sessionId)) return false;
return !hasAIChatSidePanelRetainedContent(props);
}
function schedulePanelActivation(callback: () => void): () => void {
let timeoutId: number | null = null;
if (typeof requestAnimationFrame === 'function') {
const rafId = requestAnimationFrame(() => {
timeoutId = window.setTimeout(callback, 0);
});
return () => {
cancelAnimationFrame(rafId);
if (timeoutId !== null) window.clearTimeout(timeoutId);
};
}
timeoutId = window.setTimeout(callback, 0);
return () => {
if (timeoutId !== null) window.clearTimeout(timeoutId);
};
}
const AIChatSidePanelPreparing = React.memo(function AIChatSidePanelPreparing() {
const { t } = useI18n();
return (
<div className="flex h-full flex-col bg-background" data-section="ai-chat-panel-preparing">
<div className={`${TERMINAL_SIDE_PANEL_INNER_HEADER_CLASS} border-b border-border/50 px-2 flex items-center`}>
<div className="h-6 w-32 rounded-md bg-muted/45" />
</div>
<div className="flex flex-1 items-center justify-center text-xs text-muted-foreground">
<div className="flex items-center gap-2">
<Loader2 size={14} className="animate-spin" />
{t('ai.chat.preparing')}
</div>
</div>
</div>
);
});
const AIChatSidePanelActive: React.FC<AIChatSidePanelProps> = ({
sessions,
activeSessionIdMap,
draftsByScope,
panelViewByScope,
setActiveSessionId: setActiveSessionIdForScope,
ensureDraftForScope,
updateDraft,
showDraftView,
showSessionView,
clearDraftForScope,
addDraftFiles,
removeDraftFile,
createSession,
deleteSession,
updateSessionTitle,
updateSessionExternalSessionId,
addMessageToSession,
updateLastMessage,
updateMessageById,
persistContextCompaction,
providers,
activeProviderId,
activeModelId,
defaultAgentId,
toolIntegrationMode,
externalAgents,
setExternalAgents,
agentModelMap,
setAgentModel,
agentProviderMap,
setAgentProvider,
globalPermissionMode,
setGlobalPermissionMode,
commandBlocklist,
commandTimeout,
maxIterations = 20,
webSearchConfig,
quickMessages = [],
scopeType,
scopeTargetId,
scopeHostIds,
scopeLabel,
terminalSessions = [],
resolveExecutorContext,
isVisible = true,
notes = [],
hosts = [],
snippets = [],
onOpenVaultNote,
onOpenVaultHost,
onOpenVaultSnippet,
onOpenVaultSection,
}) => {
const { t } = useI18n();
const scopeKey = `${scopeType}:${scopeTargetId ?? ''}`;
const [showHistory, setShowHistory] = useState(false);
const [runtimeAgentModelPresets, setRuntimeAgentModelPresets] = useState<Record<string, AgentModelPreset[]>>({});
const [runtimeModelWarnings, setRuntimeModelWarnings] = useState<Record<string, string>>({});
const [steerWarnings, setSteerWarnings] = useState<Record<string, SteerWarning>>({});
const [steeringSessionId, setSteeringSessionId] = useState<string | null>(null);
const [userSkillOptions, setUserSkillOptions] = useState<UserSkillOption[]>([]);
const [userSkillsStatusVersion, setUserSkillsStatusVersion] = useState(0);
const { openSettingsWindow } = useWindowControls();
const terminalSessionsRef = useRef(terminalSessions);
terminalSessionsRef.current = terminalSessions;
const resolveExecutorContextRef = useRef(resolveExecutorContext);
resolveExecutorContextRef.current = resolveExecutorContext;
const {
streamingSessionIds,
setStreamingForScope,
abortControllersRef,
sendToCattyAgent,
sendToExternalAgent,
steerExternalAgent,
reportStreamError,
activeCompaction,
} = useAIChatStreaming({
maxIterations,
addMessageToSession,
updateLastMessage,
updateMessageById,
persistContextCompaction,
});
const setActiveSessionId = useCallback((id: string | null) => {
setActiveSessionIdForScope(scopeKey, id);
}, [scopeKey, setActiveSessionIdForScope]);
const activeTerminalSessionIds = useMemo(() => {
const sessionIds = new Set<string>();
const entries = Object.entries(activeSessionIdMap) as Array<[string, string | null]>;
for (const [sessionScopeKey, sessionId] of entries) {
if (!sessionScopeKey.startsWith('terminal:') || !sessionId) continue;
if (sessionScopeKey === scopeKey) continue;
sessionIds.add(sessionId);
}
return sessionIds;
}, [activeSessionIdMap, scopeKey]);
const deferredSessions = useDeferredValue(sessions);
const historySessions = useMemo(
() => profileAIPanelCalculation(
'AIChatSidePanel.historySessions',
() => getScopedHistorySessions(
deferredSessions,
scopeType,
scopeTargetId,
scopeHostIds,
activeTerminalSessionIds,
),
),
[deferredSessions, scopeType, scopeTargetId, scopeHostIds, activeTerminalSessionIds],
);
const explicitPanelView = panelViewByScope[scopeKey];
const currentDraft = draftsByScope[scopeKey] ?? null;
const persistedSessionId = activeSessionIdMap[scopeKey] ?? null;
const normalizedPanelView = useMemo<AIPanelView>(
() => resolveDisplayedPanelView(explicitPanelView, currentDraft != null, historySessions, persistedSessionId, scopeType),
[explicitPanelView, currentDraft, historySessions, persistedSessionId, scopeType],
);
const activeSession = useMemo(
() => resolveDisplayedSession(normalizedPanelView, historySessions),
[normalizedPanelView, historySessions],
);
const activeSessionId = normalizedPanelView.mode === 'session' ? normalizedPanelView.sessionId : null;
const isStreaming = activeSessionId ? streamingSessionIds.has(activeSessionId) : false;
const isSteering = activeSessionId != null && steeringSessionId === activeSessionId;
const currentAgentId = activeSession?.agentId ?? currentDraft?.agentId ?? defaultAgentId;
const observedContextUsage = useAgentContextUsage(activeSessionId);
const inputValue = currentDraft?.text ?? '';
const files = currentDraft?.attachments ?? [];
const panelViewRef = useRef(normalizedPanelView);
panelViewRef.current = normalizedPanelView;
const currentDraftRef = useRef(currentDraft);
currentDraftRef.current = currentDraft;
const activeSessionRef = useRef(activeSession);
activeSessionRef.current = activeSession;
const draftSendInFlightRef = useRef(false);
const defaultTargetSession = useMemo<DefaultTargetSessionHint | undefined>(() => {
const connectedSessions = terminalSessions.filter((session) => session.connected !== false);
if (scopeType === 'terminal' && scopeTargetId) {
const target = terminalSessions.find((session) => session.sessionId === scopeTargetId);
if (target) {
return {
...target,
source: 'scope-target',
};
}
}
if (connectedSessions.length === 1) {
return {
...connectedSessions[0],
source: 'only-connected-in-scope',
};
}
return undefined;
}, [terminalSessions, scopeType, scopeTargetId]);
useEffect(() => {
if (!isVisible) return;
const bridge = getNetcattyBridge();
if (!bridge?.aiMcpUpdateSessions) return;
const timeoutId = window.setTimeout(() => {
void bridge.aiMcpUpdateSessions(terminalSessions, activeSessionId ?? undefined);
}, 250);
return () => {
window.clearTimeout(timeoutId);
};
}, [isVisible, terminalSessions, activeSessionId]);
useEffect(() => {
if (!isVisible) return;
if (!explicitPanelView || panelViewsEqual(normalizedPanelView, explicitPanelView)) return;
showDraftView(scopeKey);
}, [isVisible, normalizedPanelView, explicitPanelView, scopeKey, showDraftView]);
useEffect(() => {
if (!activeSession) return;
if (isVisible && activeSessionIdMap[scopeKey] !== activeSession.id) {
setActiveSessionId(activeSession.id);
}
}, [
activeSession,
activeSessionIdMap,
scopeKey,
isVisible,
setActiveSessionId,
]);
useEffect(() => {
if (!isVisible) return;
if (normalizedPanelView.mode !== 'draft') return;
if (persistedSessionId == null) return;
setActiveSessionId(null);
}, [isVisible, normalizedPanelView.mode, persistedSessionId, setActiveSessionId]);
const ensureScopeDraft = useCallback((agentId: string) => {
ensureDraftForScope(scopeKey, agentId);
}, [ensureDraftForScope, scopeKey]);
const updateScopeDraft = useCallback((
fallbackAgentId: string,
updater: (draft: AIDraft) => AIDraft,
) => {
updateDraft(scopeKey, fallbackAgentId, updater);
}, [scopeKey, updateDraft]);
const showScopeDraftView = useCallback(() => {
showDraftView(scopeKey);
}, [scopeKey, showDraftView]);
const showScopeSessionView = useCallback((sessionId: string) => {
showSessionView(scopeKey, sessionId);
}, [scopeKey, showSessionView]);
const clearScopeDraft = useCallback(() => {
clearDraftForScope(scopeKey);
}, [clearDraftForScope, scopeKey]);
const enterScopeDraftMode = useCallback((agentId: string, preserveSessionView = false) => {
applyDraftEntrySelection({
ensureDraft: () => ensureScopeDraft(agentId),
showDraftView: showScopeDraftView,
preserveSessionView,
});
}, [ensureScopeDraft, showScopeDraftView]);
const setInputValue = useCallback((value: string) => {
enterScopeDraftMode(currentAgentId, panelViewRef.current.mode === 'session');
updateScopeDraft(currentAgentId, (draft) => ({
...draft,
text: value,
}));
}, [currentAgentId, enterScopeDraftMode, updateScopeDraft]);
const addFiles = useCallback(async (inputFiles: File[]) => {
enterScopeDraftMode(currentAgentId, panelViewRef.current.mode === 'session');
await addDraftFiles(scopeKey, currentAgentId, inputFiles);
}, [addDraftFiles, currentAgentId, enterScopeDraftMode, scopeKey]);
const removeFile = useCallback((fileId: string) => {
removeDraftFile(scopeKey, currentAgentId, fileId);
}, [removeDraftFile, scopeKey, currentAgentId]);
useEffect(() => {
if (!isVisible) return;
let cancelled = false;
const applyUserSkillsStatus = (result: { ok: boolean; skills?: Array<{
id: string;
slug: string;
name: string;
description: string;
status: 'ready' | 'warning';
}> } | null | undefined) => {
const nextOptions = getReadyUserSkillOptions(result);
setUserSkillOptions(nextOptions);
const draft = currentDraftRef.current;
if (!draft) {
return;
}
const nextSelectedUserSkillSlugs =
getNextSelectedUserSkillSlugsMap(
{ [scopeKey]: draft.selectedUserSkillSlugs },
result,
)[scopeKey] ?? [];
const selectedUserSkillsChanged =
nextSelectedUserSkillSlugs.length !== draft.selectedUserSkillSlugs.length
|| nextSelectedUserSkillSlugs.some((slug, index) => slug !== draft.selectedUserSkillSlugs[index]);
if (!selectedUserSkillsChanged) {
return;
}
updateScopeDraft(draft.agentId, (currentScopeDraft) => ({
...currentScopeDraft,
selectedUserSkillSlugs: nextSelectedUserSkillSlugs,
}));
};
const bridge = getNetcattyBridge();
void loadUserSkillsStatus(bridge)
.then((result) => {
if (cancelled) return;
if (result === undefined) return;
applyUserSkillsStatus(result);
})
.catch(() => {});
return () => {
cancelled = true;
};
}, [isVisible, scopeKey, toolIntegrationMode, updateScopeDraft, userSkillsStatusVersion]);
useEffect(() => {
const handleUserSkillsChanged = () => {
setUserSkillsStatusVersion((version) => version + 1);
};
return subscribeUserSkillsStatusChanged(handleUserSkillsChanged);
}, []);
useEffect(() => {
if (!isVisible) return;
const bridge = getNetcattyBridge();
if (bridge?.aiSyncProviders && providers.length > 0) {
void bridge.aiSyncProviders(providers);
}
}, [isVisible, providers]);
useEffect(() => {
if (!isVisible) return;
const bridge = getNetcattyBridge();
if (bridge?.aiSyncWebSearch) {
void bridge.aiSyncWebSearch(webSearchConfig?.apiHost || null, webSearchConfig?.apiKey || null);
}
}, [isVisible, webSearchConfig?.apiHost, webSearchConfig?.apiKey, webSearchConfig?.enabled]);
const {
discoveredAgents,
isDiscovering,
rediscover,
enableAgent,
} = useAgentDiscovery(externalAgents, setExternalAgents, { enabled: isVisible });
const handleEnableDiscoveredAgent = useCallback(
(agent: DiscoveredAgent) => {
const config = enableAgent(agent);
setExternalAgents?.((prev) => [...prev, config]);
},
[enableAgent, setExternalAgents],
);
const messages = activeSession?.messages ?? [];
const selectedUserSkillSlugs = useMemo(
() => currentDraft?.selectedUserSkillSlugs ?? [],
[currentDraft],
);
const selectedUserSkills = useMemo(
() =>
selectedUserSkillSlugs.map((slug) => {
const option = userSkillOptions.find((skill) => skill.slug === slug);
return option ?? { id: slug, slug, name: slug, description: '' };
}),
[selectedUserSkillSlugs, userSkillOptions],
);
const { handleExport } = useConversationExport(activeSession);
const activeProvider = useMemo(
() => providers.find((p) => p.id === activeProviderId),
[providers, activeProviderId],
);
const cattyAgentProvider = useMemo(() => {
const overrideId = agentProviderMap['catty'];
if (overrideId) {
const p = providers.find((cfg) => cfg.id === overrideId);
if (p) return p;
}
return activeProvider;
}, [agentProviderMap, providers, activeProvider]);
const cattyAgentModelId = useMemo(() => {
const trim = (s: string | undefined | null): string => (s ?? '').trim();
const overrideId = agentProviderMap['catty'];
const overrideProvider = overrideId
? providers.find((cfg) => cfg.id === overrideId)
: undefined;
if (overrideProvider) {
return trim(agentModelMap['catty']) || trim(overrideProvider.defaultModel);
}
return trim(cattyAgentProvider?.defaultModel) || trim(activeModelId);
}, [agentModelMap, agentProviderMap, providers, cattyAgentProvider, activeModelId]);
const effectiveActiveProvider = currentAgentId === 'catty' ? cattyAgentProvider : activeProvider;
const effectiveActiveModelId = currentAgentId === 'catty' ? cattyAgentModelId : activeModelId;
const cattyConfiguredProviders = useMemo(
() => (currentAgentId === 'catty' ? providers : []),
[currentAgentId, providers],
);
// Hide the ring until a real context_snapshot arrives. A synthetic 0% fallback
// misleads users when reopening long sessions (looks empty until the next turn).
const contextUsage = currentAgentId === 'catty' ? observedContextUsage : null;
// Catty-only manual compact. External agents own their own compaction.
// No minimum message count: short sessions may still run /compact (even if
// there is little to summarize).
const canCompact = currentAgentId === 'catty'
&& Boolean(activeSessionId)
&& !isStreaming
&& Boolean(effectiveActiveProvider)
&& Boolean(effectiveActiveModelId.trim());
const handleAgentProviderModelSelect = useCallback(
(providerId: string, modelId: string) => {
setAgentProvider(currentAgentId, providerId);
setAgentModel(currentAgentId, modelId);
},
[currentAgentId, setAgentProvider, setAgentModel],
);
const providerDisplayName = effectiveActiveProvider?.name ?? '';
const modelDisplayName = effectiveActiveModelId || effectiveActiveProvider?.defaultModel || '';
const currentAgentConfig = useMemo(
() => currentAgentId !== 'catty' ? externalAgents.find(a => a.id === currentAgentId) : undefined,
[currentAgentId, externalAgents],
);
const isCodexManagedAgent = useMemo(
() => currentAgentConfig ? matchesManagedAgentConfig(currentAgentConfig, 'codex') : false,
[currentAgentConfig],
);
const [codexConfigModel, setCodexConfigModel] = useState<string | null>(null);
const [codexCustomConfigResolved, setCodexCustomConfigResolved] = useState(false);
useEffect(() => {
if (!isVisible) return;
setCodexCustomConfigResolved(false);
if (!isCodexManagedAgent) {
setCodexConfigModel(null);
return;
}
const bridge = getNetcattyBridge();
if (!bridge?.aiCodexGetIntegration) return;
let cancelled = false;
void Promise.resolve(
bridge.aiCodexGetIntegration({ codexPath: getManualAgentCommand(currentAgentConfig) }) as Promise<CodexIntegrationStatus>,
).then((info) => {
if (cancelled) return;
const hasCustom = info?.state === 'connected_custom_config';
setCodexConfigModel(info?.customConfig?.model ?? null);
setCodexCustomConfigResolved(hasCustom);
}).catch(() => {
if (!cancelled) {
setCodexConfigModel(null);
setCodexCustomConfigResolved(false);
}
});
return () => { cancelled = true; };
}, [isVisible, isCodexManagedAgent, currentAgentId, currentAgentConfig]);
const agentModelMapRef = useRef(agentModelMap);
agentModelMapRef.current = agentModelMap;
const buildExternalAgentRuntimeModelTarget = useCallback((agent: ExternalAgentConfig | undefined): SdkRuntimeModelTarget | null => {
if (!agent) return null;
const sdkBackend = getExternalAgentSdkBackend(agent);
if (!sdkBackend) return null;
// Cursor: re-inject auth mode for list-models (same as run-turn). Persisted
// agent.env strips NETCATTY_CURSOR_*; without this, main defaults to api-key
// and the UI falls back to curated CURSOR_MODEL_PRESETS (#2562).
const agentEnv = sdkBackend === 'cursor'
? buildCursorListModelsAgentEnv(agent)
: agent.env;
return {
agentId: agent.id,
cacheKey: buildSdkRuntimeModelCacheKey({ ...agent, env: agentEnv }),
sdkBackend,
agentEnv,
agentCommand: getManualAgentCommand(agent),
codexRuntime: sdkBackend === 'codex' ? (agent.codexRuntime ?? 'sdk') : undefined,
};
}, []);
const applySdkRuntimeModelCatalog = useCallback((
agentId: string,
catalog: SdkRuntimeModelCatalog,
options: { adoptCurrentModel?: boolean } = {},
) => {
const runtimePresets = normalizeSdkRuntimeModelPresets(catalog.models, catalog.currentModelId);
const storedModelId = agentModelMapRef.current[agentId];
if (runtimePresets.length === 0) {
setRuntimeAgentModelPresets((prev) => {
if (!(agentId in prev)) return prev;
const { [agentId]: _removed, ...rest } = prev;
return rest;
});
} else {
setRuntimeAgentModelPresets((prev) => ({
...prev,
[agentId]: runtimePresets,
}));
}
if (
options.adoptCurrentModel
&& catalog.currentModelId
&& shouldAdoptSdkCurrentModel(catalog.currentModelId, storedModelId, runtimePresets)
) {
setAgentModel(agentId, catalog.currentModelId);
}
}, [setAgentModel]);
const loadSdkRuntimeModelCatalog = useCallback((
target: SdkRuntimeModelTarget,
options: { force?: boolean; logErrors?: boolean } = {},
): Promise<SdkRuntimeModelCatalog | null> => {
const bridge = getNetcattyBridge();
if (!bridge?.aiSdkAgentListModels) return Promise.resolve(null);
return sdkRuntimeModelCache.refresh(
target.cacheKey,
async () => {
const result = await bridge.aiSdkAgentListModels!(
target.sdkBackend,
undefined,
undefined,
`models_${target.agentId}`,
target.agentEnv,
target.agentCommand,
target.codexRuntime,
);
if (!result?.ok || !Array.isArray(result.models)) {
throw new Error(result?.error || 'Failed to load SDK agent models');
}
setRuntimeModelWarnings((current) => {
const next = { ...current };
if (result.warning && target.codexRuntime === 'app-server') {
next[target.agentId] = t('ai.codex.appServer.modelCatalogWarning');
console.warn('[AIChatSidePanel] Codex App Server model catalog unavailable:', result.warning);
} else {
delete next[target.agentId];
}
return next;
});
return {
currentModelId: result.currentModelId ?? null,
models: result.models,
};
},
{ force: options.force },
).catch((err) => {
if (target.codexRuntime === 'app-server') {
setRuntimeModelWarnings((current) => ({
...current,
[target.agentId]: t('ai.codex.appServer.modelCatalogWarning'),
}));
}
if (options.logErrors !== false) {
console.warn('[AIChatSidePanel] Failed to load SDK agent models:', err);
}
return null;
});
}, [t]);
useEffect(() => {
if (!isVisible) return;
if (!currentAgentConfig) return;
if (!shouldLoadSdkRuntimeModels(currentAgentConfig) && !isCodexManagedAgent) return;
const target = buildExternalAgentRuntimeModelTarget(currentAgentConfig);
if (!target) return;
const cached = sdkRuntimeModelCache.read(target.cacheKey);
if (cached) {
applySdkRuntimeModelCatalog(target.agentId, cached);
}
// Respect renderer TTL / in-flight coalescing for all SDK agents including
// OpenCode. Forced refresh used to re-spawn opencode on every effect re-run
// even when the user never selected OpenCode (#2184). Manual refresh still
// passes force via the model selector path.
let cancelled = false;
void loadSdkRuntimeModelCatalog(target).then((catalog) => {
if (cancelled || !catalog) return;
applySdkRuntimeModelCatalog(target.agentId, catalog, { adoptCurrentModel: true });
});
return () => {
cancelled = true;
};
}, [
isVisible,
currentAgentConfig,
isCodexManagedAgent,
buildExternalAgentRuntimeModelTarget,
loadSdkRuntimeModelCatalog,
applySdkRuntimeModelCatalog,
]);
const isCodexAppServer = isCodexManagedAgent && currentAgentConfig?.codexRuntime === 'app-server';
const canSteerCurrentTurn = Boolean(activeSessionId && isStreaming && isCodexAppServer);
const hasCodexCustomConfig = codexCustomConfigResolved && isCodexManagedAgent && !isCodexAppServer;
const agentModelPresets = useMemo(() => {
const runtimePresets = runtimeAgentModelPresets[currentAgentId];
if (hasCodexCustomConfig) {
if (runtimePresets) {
return runtimePresets;
}
if (codexConfigModel) {
return [{ id: codexConfigModel, name: codexConfigModel }];
}
return [];
}
if (runtimePresets) return runtimePresets;
const presets = getAgentModelPresets(
currentAgentConfig?.command,
getExternalAgentSdkBackend(currentAgentConfig),
);
// BYO Codex CLI: hide GPT-5.6 when CLI < 0.144.0 (stored probe or discovery).
const cliVersion = resolveAgentCliVersion(currentAgentConfig, discoveredAgents);
return filterAgentModelPresetsForCliVersion(presets, cliVersion);
}, [
currentAgentConfig,
currentAgentId,
runtimeAgentModelPresets,
hasCodexCustomConfig,
codexConfigModel,
discoveredAgents,
]);
const selectedAgentModel = useMemo(() => {
const stored = agentModelMap[currentAgentId];
if (shouldUseStoredAgentModel(stored, agentModelPresets, currentAgentConfig)) {
return stored;
}
if (agentModelPresets.length > 0) {
// Cursor CLI login defaults to `auto` (subscription quota routing).
if (currentAgentConfig?.cursorAuthMode === 'cli-login') {
const autoPreset = agentModelPresets.find((preset) => preset.id === 'auto');
if (autoPreset) return resolveAgentModelSelection(autoPreset);
}
// Use catalog defaultThinkingLevel — do not pick last array entry
// (that made GPT-5.6 Sol default to ultra).
return resolveAgentModelSelection(agentModelPresets[0]);
}
return undefined;
}, [currentAgentConfig, currentAgentId, agentModelMap, agentModelPresets]);
const inputAgentId = activeSession?.agentId ?? currentDraft?.agentId ?? currentAgentId;
const canSendCurrentAgent = useMemo(
() => canSendWithAgent(inputAgentId, externalAgents),
[inputAgentId, externalAgents],
);
const handleAgentModelSelect = useCallback((modelId: string) => {
setAgentModel(currentAgentId, modelId);
}, [currentAgentId, setAgentModel]);
const handleNewChat = useCallback(() => {
clearScopeDraft();
updateScopeDraft(currentAgentId, () => ({
text: '',
agentId: currentAgentId,
attachments: [],
selectedUserSkillSlugs: [],
updatedAt: Date.now(),
}));
showScopeDraftView();
setShowHistory(false);
}, [clearScopeDraft, currentAgentId, showScopeDraftView, updateScopeDraft]);
const handleOpenSettings = useCallback(() => {
void openSettingsWindow();
}, [openSettingsWindow]);
/** Ref to always access latest sessions (avoids stale closure in autoTitleSession). */
const sessionsRef = useRef(sessions);
sessionsRef.current = sessions;
/** Auto-title a session from the first user message if untitled. */
const autoTitleSession = useCallback((sessionId: string, text: string) => {
const s = sessionsRef.current.find(x => x.id === sessionId);
if (s && (!s.title || s.title === 'New Chat')) {
updateSessionTitle(sessionId, text.length > 50 ? text.slice(0, 50) + '...' : text);
}
}, [updateSessionTitle]);
const buildExecutorContextForScope = useCallback((scope: {
type: 'terminal' | 'workspace';
targetId?: string;
label?: string;
}): ExecutorContext => {
const resolved = resolveExecutorContextRef.current?.(scope);
if (resolved) return resolved;
return {
sessions: terminalSessionsRef.current,
workspaceId: scope.type === 'workspace' ? scope.targetId : undefined,
workspaceName: scope.type === 'workspace' ? scope.label : undefined,
};
}, []);
const addSelectedUserSkill = useCallback((slug: string) => {
const normalizedSlug = String(slug || '').trim().toLowerCase();
if (!normalizedSlug) return;
enterScopeDraftMode(currentAgentId, panelViewRef.current.mode === 'session');
updateScopeDraft(currentAgentId, (draft) => {
if (draft.selectedUserSkillSlugs.includes(normalizedSlug)) {
return draft;
}
return {
...draft,
selectedUserSkillSlugs: [...draft.selectedUserSkillSlugs, normalizedSlug],
};
});
}, [currentAgentId, enterScopeDraftMode, updateScopeDraft]);
const removeSelectedUserSkill = useCallback((slug: string) => {
const normalizedSlug = String(slug || '').trim().toLowerCase();
if (!normalizedSlug) return;
enterScopeDraftMode(currentAgentId, panelViewRef.current.mode === 'session');
updateScopeDraft(currentAgentId, (draft) => {
const nextSelectedUserSkillSlugs = draft.selectedUserSkillSlugs.filter(
(entry) => entry !== normalizedSlug,
);
if (nextSelectedUserSkillSlugs.length === draft.selectedUserSkillSlugs.length) {
return draft;
}
return {
...draft,
selectedUserSkillSlugs: nextSelectedUserSkillSlugs,
};
});
}, [currentAgentId, enterScopeDraftMode, updateScopeDraft]);
const handleSend = useCallback(async () => {
const draft = currentDraftRef.current;
const currentPanelView = panelViewRef.current;
const currentSessionView = activeSessionRef.current;
const trimmed = draft?.text.trim() ?? '';
const sendScopeKey = scopeKey;
const attachments = (draft?.attachments ?? []).map((file) => ({
base64Data: file.base64Data,
mediaType: file.mediaType,
filename: file.filename,
filePath: file.filePath,
terminalSelection: file.terminalSelection,
previewText: file.previewText,
lineCount: file.lineCount,
}));
const hasTerminalSelectionAttachments = attachments.some(isTerminalSelectionAttachment);
if ((!trimmed && !hasTerminalSelectionAttachments) || isStreaming) return;
const sendAgentId = currentSessionView?.agentId ?? draft?.agentId ?? currentAgentId;
const agentConfig = sendAgentId !== 'catty' ? findEnabledExternalAgent(externalAgents, sendAgentId) : undefined;
if (sendAgentId !== 'catty' && !agentConfig) return;
const selectedSkillSlugs = draft?.selectedUserSkillSlugs ?? [];
const modelPrompt = buildPromptWithTerminalSelectionAttachments(trimmed, attachments);
const modelAttachments = attachments.filter((attachment) => !isTerminalSelectionAttachment(attachment));
const isDraftMode = currentPanelView.mode === 'draft';
if (isDraftMode && !tryBeginDraftSend(draftSendInFlightRef)) {
return;
}
try {
let sessionId = currentSessionView?.id ?? null;
let currentSession = currentSessionView ?? null;
if (isDraftMode) {
const scope: AISessionScope = { type: scopeType, targetId: scopeTargetId, hostIds: scopeHostIds };
const createdSession = createSession(scope, sendAgentId);
sessionId = createdSession.id;
currentSession = createdSession;
clearScopeDraft();
showScopeSessionView(createdSession.id);
setActiveSessionId(createdSession.id);
}
if (!sessionId) {
return;
}
const isExternalAgent = sendAgentId !== 'catty';
const sendActiveProvider = isExternalAgent ? activeProvider : effectiveActiveProvider;
const sendActiveModelId = isExternalAgent ? activeModelId : effectiveActiveModelId;
if (!isExternalAgent && !sendActiveProvider) {
addMessageToSession(sessionId, {
id: generateId(), role: 'user', content: trimmed,
...(attachments.length > 0 ? { attachments } : {}),
timestamp: Date.now(),
});
addMessageToSession(sessionId, { id: generateId(), role: 'assistant', content: t('ai.chat.noProvider'), timestamp: Date.now() });
if (currentPanelView.mode === 'session') {
clearScopeDraft();
showScopeSessionView(sessionId);
}
return;
}
if (!isExternalAgent && !sendActiveModelId.trim()) {
addMessageToSession(sessionId, {
id: generateId(), role: 'user', content: trimmed,
...(attachments.length > 0 ? { attachments } : {}),
timestamp: Date.now(),
});
addMessageToSession(sessionId, { id: generateId(), role: 'assistant', content: t('ai.chat.noProviderModel'), timestamp: Date.now() });
if (currentPanelView.mode === 'session') {
clearScopeDraft();
showScopeSessionView(sessionId);
}
return;
}
addMessageToSession(sessionId, {
id: generateId(), role: 'user', content: trimmed,
...(attachments.length > 0 ? { attachments } : {}),
timestamp: Date.now(),
});
clearScopeDraft();
showScopeSessionView(sessionId);
setActiveSessionId(sessionId);
setStreamingForScope(sessionId, true);
const assistantMsgId = generateId();
addMessageToSession(sessionId, {
id: assistantMsgId, role: 'assistant', content: '', timestamp: Date.now(),
model: isExternalAgent
? (selectedAgentModel || agentConfig?.name || 'external')
: (sendActiveModelId || sendActiveProvider?.defaultModel || ''),
providerId: isExternalAgent ? undefined : sendActiveProvider?.providerId,
});
const abortController = new AbortController();
abortControllersRef.current.set(sessionId, abortController);
currentSession = currentSession ?? sessionsRef.current.find((session) => session.id === sessionId) ?? null;
if (isExternalAgent) {
if (!agentConfig) {
updateMessageById(sessionId, assistantMsgId, msg => ({ ...msg, content: 'External agent not found. Please check settings.', executionStatus: 'failed' }));
setStreamingForScope(sessionId, false);
return;
}
try {
const existingExternalSessionId = currentSession?.externalSessionId;
await sendToExternalAgent(sessionId, assistantMsgId, modelPrompt, agentConfig, abortController, modelAttachments, {
existingSessionId: existingExternalSessionId,
updateExternalSessionId: updateSessionExternalSessionId,
historyMessages: buildExternalAgentHistoryMessagesForBridge(currentSession?.messages ?? [], existingExternalSessionId),
terminalSessions,
defaultTargetSession,
providers,
selectedAgentModel,
toolIntegrationMode,
selectedUserSkillSlugs: selectedSkillSlugs,
permissionMode: globalPermissionMode,
});
} catch (err) {
reportStreamError(sessionId, abortController.signal, err);
}
updateLastMessage(sessionId, msg => msg.statusText ? { ...msg, statusText: '' } : msg);
setStreamingForScope(sessionId, false);
abortControllersRef.current.delete(sessionId);
autoTitleSession(sessionId, trimmed);
} else {
const toolScope = {
type: scopeType,
targetId: scopeTargetId,
label: scopeLabel,
} as const;
await sendToCattyAgent(sessionId, sendScopeKey, modelPrompt, abortController, currentSession ?? undefined, assistantMsgId, {
activeProvider: sendActiveProvider,
activeModelId: sendActiveModelId,
scopeType,
scopeTargetId,
scopeLabel,
globalPermissionMode,
commandBlocklist,
commandTimeout,
terminalSessions,
webSearchConfig,
getExecutorContext: () => buildExecutorContextForScope(toolScope),
autoTitleSession,
selectedUserSkillSlugs: selectedSkillSlugs,
titleText: trimmed,
}, modelAttachments.length > 0 ? modelAttachments : undefined);
}
} finally {
if (isDraftMode) {
endDraftSend(draftSendInFlightRef);
}
}
}, [
isStreaming, activeProvider, effectiveActiveProvider, effectiveActiveModelId, scopeKey, currentAgentId,
activeModelId, externalAgents,
createSession, addMessageToSession, updateMessageById, updateLastMessage,
setStreamingForScope,
sendToExternalAgent, sendToCattyAgent, reportStreamError, autoTitleSession, t,
abortControllersRef, terminalSessions, defaultTargetSession, providers, selectedAgentModel, updateSessionExternalSessionId,
scopeType, scopeTargetId, scopeHostIds, scopeLabel, globalPermissionMode, commandBlocklist, commandTimeout, webSearchConfig, buildExecutorContextForScope,
toolIntegrationMode,
clearScopeDraft, showScopeSessionView, setActiveSessionId,
]);
const handleCompact = useCallback(async () => {
const session = activeSessionRef.current;
if (
currentAgentId !== 'catty'
|| !session
|| isStreaming
|| !effectiveActiveProvider
|| !effectiveActiveModelId.trim()
) {
return;
}
const controller = new AbortController();
abortControllersRef.current.set(session.id, controller);
setStreamingForScope(session.id, true);
try {
await sendToCattyAgent(
session.id,
scopeKey,
'',
controller,
session,
'',
{
activeProvider: effectiveActiveProvider,
activeModelId: effectiveActiveModelId,
scopeType,
scopeTargetId,
scopeLabel,
globalPermissionMode,
commandBlocklist,
commandTimeout,
terminalSessions,
webSearchConfig,
getExecutorContext: () => buildExecutorContextForScope({
type: scopeType,
targetId: scopeTargetId,
label: scopeLabel,
}),
autoTitleSession: () => {},
selectedUserSkillSlugs: [],
forceCompaction: true,
},
);
} finally {
setStreamingForScope(session.id, false);
if (abortControllersRef.current.get(session.id) === controller) {
abortControllersRef.current.delete(session.id);
}
}
}, [
abortControllersRef,
buildExecutorContextForScope,
commandBlocklist,
commandTimeout,
currentAgentId,
effectiveActiveModelId,
effectiveActiveProvider,
globalPermissionMode,
isStreaming,
scopeKey,
scopeLabel,
scopeTargetId,
scopeType,
sendToCattyAgent,
setStreamingForScope,
terminalSessions,
webSearchConfig,
]);
const handleSteer = useCallback(async () => {
const sessionId = activeSessionRef.current?.id;
const draft = currentDraftRef.current;
if (!sessionId || !draft || steeringSessionId || !canSteerCurrentTurn) return;
const trimmed = draft.text.trim();
const attachments = draft.attachments.map((file) => ({
base64Data: file.base64Data,
mediaType: file.mediaType,
filename: file.filename,
filePath: file.filePath,
terminalSelection: file.terminalSelection,
previewText: file.previewText,
lineCount: file.lineCount,
}));
const hasTerminalSelectionAttachments = attachments.some(isTerminalSelectionAttachment);
if (!trimmed && !hasTerminalSelectionAttachments) return;
const userMessageId = generateId();
const modelPrompt = buildPromptWithTerminalSelectionAttachments(trimmed, attachments);
const modelAttachments = attachments.filter((attachment) => !isTerminalSelectionAttachment(attachment));
setSteerWarnings(current => {
const next = { ...current };
delete next[sessionId];
return next;
});
setSteeringSessionId(sessionId);
try {
const result = await steerExternalAgent({
chatSessionId: sessionId,
userMessageId,
userText: trimmed,
prompt: modelPrompt,
attachments,
attachedImages: modelAttachments,
});
if (result.status === 'accepted') {
if (currentDraftRef.current === draft) clearScopeDraft();
return;
}
if (result.status !== 'cancelled') {
setSteerWarnings(current => ({
...current,
[sessionId]: { reason: result.status, turnKind: result.turnKind },
}));
}
} finally {
setSteeringSessionId(current => current === sessionId ? null : current);
}
}, [canSteerCurrentTurn, clearScopeDraft, steerExternalAgent, steeringSessionId]);
const stopStreamingForSession = useCallback(async (sessionId: string) => {
const controller = abortControllersRef.current.get(sessionId);
setStreamingForScope(sessionId, false);
updateLastMessage(sessionId, (msg) => ({
...msg,
statusText: '',
executionStatus: msg.executionStatus === 'running' ? 'cancelled' : msg.executionStatus,
}));
await stopAgentTurn({
chatSessionId: sessionId,
abortController: controller,
bridge: getNetcattyBridge(),
reason: 'user',
});
await getAgentRuntime().waitForActiveTurn(sessionId);
if (controller && abortControllersRef.current.get(sessionId) === controller) {
abortControllersRef.current.delete(sessionId);
}
}, [setStreamingForScope, updateLastMessage, abortControllersRef]);
const { addGrant } = useAIPermissionGrantsState();
useEffect(() => {
return registerGrantPersister((rule) => { addGrant(rule); });
}, [addGrant]);
useEffect(() => setupCodexAppServerInteractionBridge(), []);
const handleStop = useCallback(() => {
if (!activeSessionId) return;
setSteeringSessionId(current => current === activeSessionId ? null : current);
setSteerWarnings(current => {
const next = { ...current };
delete next[activeSessionId];
return next;
});
stopStreamingForSession(activeSessionId);
}, [activeSessionId, stopStreamingForSession]);
useEffect(() => {
if (!activeSessionId || isStreaming) return;
setSteeringSessionId(current => current === activeSessionId ? null : current);
setSteerWarnings(current => {
if (!current[activeSessionId]) return current;
const next = { ...current };
delete next[activeSessionId];
return next;
});
}, [activeSessionId, isStreaming]);
const steerWarning = useMemo(() => {
if (!activeSessionId) return undefined;
const warning = steerWarnings[activeSessionId];
if (!warning) return undefined;
if (warning.reason === 'not-steerable' && warning.turnKind === 'review') {
return t('ai.codex.steer.notSteerableReview');
}
if (warning.reason === 'not-steerable' && warning.turnKind === 'compact') {
return t('ai.codex.steer.notSteerableCompact');
}
if (warning.reason === 'busy') return t('ai.codex.steer.busy');
if (warning.reason === 'inactive') return t('ai.codex.steer.inactive');
if (warning.reason === 'unsupported') return t('ai.codex.steer.unsupported');
return t('ai.codex.steer.failed');
}, [activeSessionId, steerWarnings, t]);
const handleSelectSession = useCallback(
(sessionId: string) => {
applyHistorySessionSelection(sessionId, {
showSessionView: showScopeSessionView,
setActiveSessionId,
closeHistory: () => setShowHistory(false),
});
},
[setActiveSessionId, showScopeSessionView],
);
const handleDeleteSession = useCallback(
async (e: React.MouseEvent, sessionId: string) => {
e.stopPropagation();
const deletingActiveSession =
activeSessionId === sessionId
|| persistedSessionId === sessionId
|| (
explicitPanelView?.mode === 'session'
&& explicitPanelView.sessionId === sessionId
);
const deletingLastScopedSession =
historySessions.length === 1 && historySessions[0]?.id === sessionId;
const deletedSessionAgentId =
historySessions.find((session) => session.id === sessionId)?.agentId
?? currentAgentId;
if (abortControllersRef.current.has(sessionId) || streamingSessionIds.has(sessionId)) {
await stopStreamingForSession(sessionId);
}
deleteSession(sessionId, scopeKey);
if (deletingActiveSession || deletingLastScopedSession) {
setShowHistory(false);
ensureScopeDraft(deletedSessionAgentId);
}
},
[
activeSessionId,
abortControllersRef,
currentAgentId,
deleteSession,
ensureScopeDraft,
explicitPanelView,
historySessions,
persistedSessionId,
scopeKey,
stopStreamingForSession,
streamingSessionIds,
],
);
const handleAgentChange = useCallback((agentId: string) => {
showScopeDraftView();
ensureScopeDraft(agentId);
updateScopeDraft(agentId, (draft) => ({
...selectDraftForAgentSwitch(
draft,
agentId,
Boolean(activeSessionRef.current?.messages.length),
),
}));
setShowHistory(false);
}, [ensureScopeDraft, showScopeDraftView, updateScopeDraft]);
// Warm the Streamdown/markdown chunk while the panel is visible but idle, so
// the first completed assistant reply does not pay the full parse cost mid-interaction.
useEffect(() => {
if (!isVisible) return;
let cancelled = false;
const loadMarkdown = () => {
if (cancelled) return;
void import('./ai-elements/messageResponse');
};
if (typeof requestIdleCallback === 'function') {
const idleId = requestIdleCallback(loadMarkdown, { timeout: 2500 });
return () => {
cancelled = true;
cancelIdleCallback(idleId);
};
}
const timeoutId = window.setTimeout(loadMarkdown, 0);
return () => {
cancelled = true;
window.clearTimeout(timeoutId);
};
}, [isVisible]);
// Keep streaming/session hooks alive for retained hidden panels, but do not
// mount ChatMessageList / Streamdown / ChatInput while CSS-hidden — those trees
// are the main tab-switch and cross-tab re-render cost.
if (!isVisible) {
return (
<div
className="h-full min-h-0 bg-background"
data-section="ai-chat-panel-retained"
aria-hidden="true"
/>
);
}
return (
<React.Profiler {...getAIPanelProfilerProps('AIChatSidePanel.Active')}>
<AIChatPanelContent
t={t}
currentAgentId={currentAgentId}
externalAgents={externalAgents}
discoveredAgents={discoveredAgents}
isDiscovering={isDiscovering}
handleAgentChange={handleAgentChange}
handleEnableDiscoveredAgent={handleEnableDiscoveredAgent}
rediscover={rediscover}
handleOpenSettings={handleOpenSettings}
activeSession={activeSession}
handleExport={handleExport}
showHistory={showHistory}
setShowHistory={setShowHistory}
handleNewChat={handleNewChat}
historySessions={historySessions}
activeSessionId={activeSessionId}
handleSelectSession={handleSelectSession}
handleDeleteSession={handleDeleteSession}
messages={messages}
isStreaming={isStreaming}
activeCompaction={
activeCompaction?.sessionId === activeSessionId ? activeCompaction : null
}
contextUsage={contextUsage}
canCompact={canCompact}
inputValue={inputValue}
setInputValue={setInputValue}
handleSend={handleSend}
handleCompact={handleCompact}
handleSteer={handleSteer}
handleStop={handleStop}
canSteer={canSteerCurrentTurn}
isSteering={isSteering}
steerWarning={steerWarning}
lockTurnConfiguration={Boolean(isStreaming && isCodexAppServer)}
canSendCurrentAgent={canSendCurrentAgent}
providerDisplayName={providerDisplayName}
modelDisplayName={modelDisplayName}
modelCatalogWarning={runtimeModelWarnings[currentAgentId]}
agentModelPresets={agentModelPresets}
selectedAgentModel={selectedAgentModel}
handleAgentModelSelect={handleAgentModelSelect}
cattyConfiguredProviders={cattyConfiguredProviders}
effectiveActiveProvider={effectiveActiveProvider}
effectiveActiveModelId={effectiveActiveModelId}
handleAgentProviderModelSelect={handleAgentProviderModelSelect}
files={files}
addFiles={addFiles}
removeFile={removeFile}
terminalSessions={terminalSessions}
selectedUserSkills={selectedUserSkills}
userSkillOptions={userSkillOptions}
quickMessages={quickMessages}
addSelectedUserSkill={addSelectedUserSkill}
removeSelectedUserSkill={removeSelectedUserSkill}
globalPermissionMode={globalPermissionMode}
setGlobalPermissionMode={setGlobalPermissionMode}
notes={notes}
hosts={hosts}
snippets={snippets}
onOpenVaultNote={onOpenVaultNote}
onOpenVaultHost={onOpenVaultHost}
onOpenVaultSnippet={onOpenVaultSnippet}
onOpenVaultSection={onOpenVaultSection}
/>
</React.Profiler>
);
};
const AI_CHAT_SIDE_PANEL_AI_STATE_KEYS = [
'sessions',
'activeSessionIdMap',
'draftsByScope',
'panelViewByScope',
'setActiveSessionId',
'ensureDraftForScope',
'updateDraft',
'showDraftView',
'showSessionView',
'clearDraftForScope',
'addDraftFiles',
'removeDraftFile',
'createSession',
'deleteSession',
'updateSessionTitle',
'updateSessionExternalSessionId',
'addMessageToSession',
'updateLastMessage',
'updateMessageById',
'persistContextCompaction',
'providers',
'activeProviderId',
'activeModelId',
'defaultAgentId',
'toolIntegrationMode',
'externalAgents',
'setExternalAgents',
'agentModelMap',
'setAgentModel',
'agentProviderMap',
'setAgentProvider',
'globalPermissionMode',
'setGlobalPermissionMode',
'commandBlocklist',
'commandTimeout',
'maxIterations',
'webSearchConfig',
'quickMessages',
] as const satisfies readonly (keyof AIChatSidePanelProps)[];
export function aiChatSidePanelPropsAreEqual(
prev: AIChatSidePanelProps,
next: AIChatSidePanelProps,
): boolean {
const prevKeep = shouldKeepAIChatSidePanelMounted(prev);
const nextKeep = shouldKeepAIChatSidePanelMounted(next);
if (!prevKeep && !nextKeep) {
return true;
}
if (prevKeep !== nextKeep) {
return false;
}
if (prev.scopeType !== next.scopeType) return false;
if (prev.scopeTargetId !== next.scopeTargetId) return false;
if (prev.scopeLabel !== next.scopeLabel) return false;
if ((prev.isVisible ?? true) !== (next.isVisible ?? true)) return false;
if (prev.scopeHostIds !== next.scopeHostIds) return false;
if (prev.terminalSessions !== next.terminalSessions) return false;
if (prev.resolveExecutorContext !== next.resolveExecutorContext) return false;
if (prev.notes !== next.notes) return false;
if (prev.hosts !== next.hosts) return false;
if (prev.snippets !== next.snippets) return false;
if (prev.onOpenVaultNote !== next.onOpenVaultNote) return false;
if (prev.onOpenVaultHost !== next.onOpenVaultHost) return false;
if (prev.onOpenVaultSnippet !== next.onOpenVaultSnippet) return false;
if (prev.onOpenVaultSection !== next.onOpenVaultSection) return false;
// Sibling stream thrash: full sessions array identity always changes. Only
// exact-scope session object refs matter for this panel's active chat —
// plus the currently selected session, which may be a host-matched history
// resume whose stored scope.targetId is an older terminal.
// Fuzzy history still receives the full list; drawer open forces re-render
// via isVisible / other prop paths when the user actually needs it.
const scopeKey = `${prev.scopeType}:${prev.scopeTargetId ?? ''}`;
const selectedSessionId = prev.activeSessionIdMap[scopeKey]
?? next.activeSessionIdMap[scopeKey]
?? null;
if (!exactScopeAISessionsEqual(
prev.sessions,
next.sessions,
prev.scopeType,
prev.scopeTargetId,
selectedSessionId,
)) {
return false;
}
// History drawer / recent list need create/delete/title/updatedAt chrome.
// Only when the panel is (or becomes) visible so hidden retained panels do
// not re-render on every sibling stream that bumps updatedAt.
const prevVisible = prev.isVisible ?? true;
const nextVisible = next.isVisible ?? true;
if ((prevVisible || nextVisible) && !aiSessionIdSetEqual(prev.sessions, next.sessions)) {
return false;
}
for (const key of AI_CHAT_SIDE_PANEL_AI_STATE_KEYS) {
if (key === 'sessions') continue;
if (prev[key] !== next[key]) return false;
}
return true;
}
const AIChatSidePanel = React.memo(function AIChatSidePanel(props: AIChatSidePanelProps) {
const shouldKeepMounted = shouldKeepAIChatSidePanelMounted(props);
const shouldDelayActivation = shouldKeepMounted && shouldDelayAIChatSidePanelActivation(props);
const activationKey = `${props.scopeType}:${props.scopeTargetId ?? ''}`;
const [activationReady, setActivationReady] = useState(!shouldDelayActivation);
useEffect(() => {
if (!shouldDelayActivation) {
setActivationReady(true);
return undefined;
}
setActivationReady(false);
return schedulePanelActivation(() => setActivationReady(true));
}, [activationKey, shouldDelayActivation]);
if (!shouldKeepMounted) return null;
if (shouldDelayActivation && !activationReady) {
return <AIChatSidePanelPreparing />;
}
// Keep hidden panels alive only when they contain real work (messages, draft
// content, or an active stream). Empty hidden panels can drop their heavy
// input/agent-picker subtree and remount cheaply when shown again.
return <AIChatSidePanelActive {...props} />;
}, aiChatSidePanelPropsAreEqual);
AIChatSidePanel.displayName = 'AIChatSidePanel';
export default AIChatSidePanel;
export { AIChatSidePanel };
export type { AIChatSidePanelProps };