Files
Netcatty/components/AIChatSidePanel.types.ts
T
GOUKI9999andbincxz 00e63be4f1 feat(ai): global AI session manager with cross-scope rebind (#4098 phases 4-5) (#4159)
* feat(ai): global AI session manager with cross-scope rebind

Scope-agnostic view over every AI chat regardless of panel scope
(issue #4098 phases 4-5), hosted as a scoped/global toggle inside the
existing session history drawer.

- Global list: title, agent, resolved scope (workspace title / terminal
  label / global / dangling), state badge (active / idle / dissociated),
  message count, relative time; title-substring search, agent filter,
  newest-first ordering and a render batch guard. Titles only, never
  message bodies.
- Per-row actions: open/switch (exact-scope chats only; other-scope rows
  offer rebind instead of faking activation), rebind to the current
  panel (issue #4019 path) or to any open workspace/terminal via an
  explicit target picker, confirm-gated per-record delete, and
  single-chat export (exportSessionsBackup now takes an optional
  session-id subset; import merges by id).
- App-wide open terminals are threaded to every AI panel so the manager
  resolves scopes and rebind targets across tabs.
- Deletion safety: no scopeKey is passed, stale pointers of any panel
  are repaired by the #4125 validation effect; deleting the last chat
  cannot resurrect on reboot (intentionally-deleted ids + migration
  marker). No cleanup/eviction semantics are touched (#4015 R2).

* fix(ai): stop active turns before scope rebind

Rebinding a chat while a turn streams into it corrupts streaming state
(the stream targets the old scope while the active map/panel pointer move
underneath it). Both rebind paths — the global session manager and the
/rebind <n> panel command — now await stopStreamingForSession first,
chosen over rejecting the rebind because it cleanly awaits termination
(stopAgentTurn + waitForActiveTurn) and preserves the user's rebind
intent. stopStreamingForSession moves above the /rebind handler to avoid
a TDZ reference; the guard lives in AIChatSidePanelHelpers so both call
sites share it. Also passes the panel scope host ids to the manager for
the 'This panel' rebind target.

* fix(ai): derive session manager rebind targets from all live terminals

The global AI session manager built its app-wide terminal list from
contextsByTabId, which only covers tabs whose AI panel context is
mounted - a live terminal without one was missing as a rebind target.
useTerminalAiContexts now also exposes buildAllTerminalAiInfos over the
full terminal session store (same buildAITerminalSessionInfo per
session, so infos merge seamlessly where a context exists) and threads
it to AIChatPanelsHost as appTerminalSessions.

* fix(ai): preserve host ids on panel rebind and reset stale agent filters

- 'This panel' rebind now carries the viewing panel's scope host ids
  (currentScopeHostIds) onto the rewritten scope, so the destination
  host association is not orphaned; explicit picker targets already
  forwarded their hostIds.
- The agent filter no longer survives its agent: when the filtered
  agent's last chat is deleted the filter resets to 'all' instead of
  leaving a permanently empty list with a blank select; the select's
  built-in 'all' option stays the manual clear affordance.

* fix(ai): clear source workspace views when rebinding a chat

* fix(ai): demote implicit source views when rebinding restored chats

* fix(ai): stabilize appTerminalInfos identity and polish global session manager UI

- Retain appTerminalInfos array identity across structurally equal terminal updates so unrelated tab state churn does not re-render every mounted AIChatSidePanel.
- Replace native <select> elements in GlobalAIChatSessionManager with the shared Radix Select component for consistent dark/light theme rendering.
- Wrap the disabled cross-scope open button in a <span> inside TooltipTrigger (and add type="button" to row action buttons) so hover tooltips fire reliably.

* fix(ai): carry member host IDs on explicit workspace rebind targets

* fix(ai): remove redundant title beside history drawer scope switcher

* fix(ai): guard optional appTerminalSessions in AIChatPanelsHost

* fix(ai): clear persisted source workspace anchors when rebinding chats

* fix(ai): exclude non-exact workspace matches from implicit auto-resume

---------

Co-authored-by: bincxz <16399091+binaricat@users.noreply.github.com>
2026-11-22 11:53:02 +08:00

166 lines
6.5 KiB
TypeScript

import type {
AIDraft,
AIPanelView,
AIPermissionMode,
AIToolIntegrationMode,
AISession,
AISessionScope,
ChatMessage,
ExternalAgentConfig,
ProviderConfig,
WebSearchConfig,
} from '../infrastructure/ai/types';
import type { AIQuickMessage } from '../infrastructure/ai/quickMessages';
import type { ExecutorContext } from '../infrastructure/ai/cattyAgent/executor';
import type { Host, Snippet, VaultNote } from '../types';
// -------------------------------------------------------------------
// Props
// -------------------------------------------------------------------
export interface AIChatSidePanelProps {
// Session state (per-scope)
sessions: AISession[];
activeSessionIdMap: Record<string, string | null>;
draftsByScope: Partial<Record<string, AIDraft>>;
panelViewByScope: Partial<Record<string, AIPanelView>>;
setActiveSessionId: (scopeKey: string, id: string | null) => void;
ensureDraftForScope: (scopeKey: string, agentId: string) => void;
updateDraft: (
scopeKey: string,
fallbackAgentId: string,
updater: (draft: AIDraft) => AIDraft,
) => void;
showDraftView: (scopeKey: string) => void;
showSessionView: (scopeKey: string, sessionId: string) => void;
clearDraftForScope: (scopeKey: string) => void;
addDraftFiles: (scopeKey: string, fallbackAgentId: string, inputFiles: File[]) => Promise<void>;
removeDraftFile: (scopeKey: string, fallbackAgentId: string, fileId: string) => void;
createSession: (scope: AISessionScope, agentId?: string) => AISession;
/** Non-destructively branch before the last user turn; returns the branch id + restored composer content. */
undoLastTurnInSession?: (
sessionId: string,
viewingScope?: Pick<AISessionScope, 'type' | 'targetId'>,
) => Promise<{ sessionId: string; restored: { text: string; attachments: import('../infrastructure/ai/types').UploadedFile[]; selectedUserSkillSlugs: string[] } } | null>;
deleteSession: (sessionId: string, scopeKey?: string) => void;
updateSessionTitle: (sessionId: string, title: string) => void;
/** Issue #4015 R2: rebind a dangling chat to this panel's scope (panel action, never agent content). */
rebindSessionScope?: (sessionId: string, scope: { type: 'terminal' | 'workspace'; targetId: string; hostIds?: string[] }) => void;
/** Manual durability escape hatch: export the store to a JSON file (returns the path, '' when fixed-path). With `sessionIds`, exports only those chats. */
exportSessionsBackup?: (sessionIds?: readonly string[]) => Promise<string | null>;
/** Import sessions from a JSON export; merges by id. Returns the imported count. */
importSessionsBackup?: () => Promise<number>;
updateSessionExternalSessionId: (sessionId: string, externalSessionId: string | undefined) => void;
addMessageToSession: (sessionId: string, message: ChatMessage) => void;
updateLastMessage: (
sessionId: string,
updater: (msg: ChatMessage) => ChatMessage,
) => void;
updateMessageById: (
sessionId: string,
messageId: string,
updater: (msg: ChatMessage) => ChatMessage,
) => void;
persistContextCompaction: (
sessionId: string,
compaction: import('../infrastructure/ai/types').AISessionContextCompaction,
) => void;
forkSessionFromMessage?: (
sessionId: string,
messageId: string,
viewingScope?: Pick<AISessionScope, 'type' | 'targetId'>,
) => Promise<AISession | null>;
// Provider config
providers: ProviderConfig[];
activeProviderId: string;
activeModelId: string;
// Agent info
defaultAgentId: string;
toolIntegrationMode: AIToolIntegrationMode;
externalAgents: ExternalAgentConfig[];
setExternalAgents?: (value: ExternalAgentConfig[] | ((prev: ExternalAgentConfig[]) => ExternalAgentConfig[])) => void;
agentModelMap: Record<string, string>;
setAgentModel: (agentId: string, modelId: string) => void;
agentProviderMap: Record<string, string>;
setAgentProvider: (agentId: string, providerId: string) => void;
agentThinkingMap: Record<string, string>;
setAgentThinking: (agentId: string, thinkingLevel: string) => void;
updateProvider?: (id: string, updates: Partial<ProviderConfig>) => void;
// Safety
globalPermissionMode: AIPermissionMode;
setGlobalPermissionMode?: (mode: AIPermissionMode) => void;
commandBlocklist?: string[];
commandTimeout?: number;
responseIdleTimeout?: number;
maxIterations?: number;
// Web search
webSearchConfig?: WebSearchConfig | null;
// Quick messages (slash prompts)
quickMessages?: AIQuickMessage[];
// Context
scopeType: 'terminal' | 'workspace';
scopeTargetId?: string;
scopeHostIds?: string[];
scopeLabel?: string;
/** Workspace focused pane; preferred when inheriting AI chat after merge. */
focusedSessionId?: string;
/** Issue #4098 phase 2: pin the AI chat a workspace scope is anchored to. */
onSetWorkspaceAnchorChat?: (workspaceId: string, chatId: string | null) => void;
/** Live workspaces (with their anchor chat and member host IDs), used for scope titles, anchor resolution, and explicit workspace rebinds. */
workspaces?: Array<{ id: string; title: string; anchorChatId?: string; hostIds?: string[] }>;
/** All currently live terminal (and workspace) scope target ids. */
liveScopeTargetIds?: Set<string>;
/** App-wide open terminal infos (all tabs), for the global session manager's rebind targets and dangling detection. */
appTerminalSessions?: Array<{
sessionId: string;
hostId: string;
hostname: string;
label: string;
connected: boolean;
}>;
// Terminal session context (from parent)
terminalSessions?: Array<{
sessionId: string;
hostId: string;
hostname: string;
label: string;
os?: string;
username?: string;
protocol?: string;
shellType?: string;
deviceType?: string;
connected: boolean;
}>;
resolveExecutorContext?: (scope: {
type: 'terminal' | 'workspace';
targetId?: string;
label?: string;
}) => ExecutorContext;
// Visibility
isVisible?: boolean;
// Vault artifact navigation (from AI chat tool results)
notes?: VaultNote[];
hosts?: Host[];
snippets?: Snippet[];
onOpenVaultNote?: (noteId: string) => void;
onOpenVaultHost?: (hostId: string) => void;
onOpenVaultSnippet?: (snippetId: string) => void;
onOpenVaultSection?: (section: 'notes' | 'hosts' | 'snippets') => void;
}
// -------------------------------------------------------------------
// Helpers
// -------------------------------------------------------------------
// -------------------------------------------------------------------
// Component
// -------------------------------------------------------------------