Files
Netcatty/components/ai/GlobalAIChatSessionManager.tsx
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

398 lines
17 KiB
TypeScript

import React, { useEffect, useMemo, useState } from 'react';
import { Download, FolderInput, Play, Search, Trash2, X } from 'lucide-react';
import type { AISession, ExternalAgentConfig } from '../../infrastructure/ai/types';
import { useI18n } from '../../application/i18n/I18nProvider';
import { cn } from '../../lib/utils';
import { Input } from '../ui/input';
import { ScrollArea } from '../ui/scroll-area';
import {
Select,
SelectContent,
SelectItem,
SelectTrigger,
SelectValue,
} from '../ui/select';
import { Tooltip, TooltipContent, TooltipTrigger } from '../ui/tooltip';
import { ConfirmDialog } from '../ui/confirm-dialog';
import { SESSION_HISTORY_ROW_CLASSNAMES } from './sessionHistoryLayout';
import { formatRelativeTime } from '../AIChatSessionHistoryDrawer';
import {
buildGlobalManagerRows,
collectGlobalManagerAgentIds,
filterGlobalManagerRows,
type GlobalManagerScopeTarget,
type GlobalManagerTerminalInfo,
} from './globalSessionManagerRows';
// -------------------------------------------------------------------
// Global AI Session Manager (issue #4098 phases 4-5)
// -------------------------------------------------------------------
// A scope-agnostic view over every AI chat in the store with per-chat
// actions: open/switch (current scope only), rebind (dangling → here, or
// to any open workspace/terminal), per-chat export, and confirm-gated
// delete. Deliberately NOT part of this surface: cleanup/eviction semantics
// (#4015 R2) and cross-scope activation.
// -------------------------------------------------------------------
interface GlobalAIChatSessionManagerProps {
sessions: AISession[];
activeSessionIdMap: Readonly<Record<string, string | null>>;
currentScopeType: 'terminal' | 'workspace';
currentScopeTargetId?: string;
/**
* Host ids of the viewing panel's own scope; carried onto chats rebound
* with "This panel" so the destination's host association survives the
* scope rewrite instead of being orphaned.
*/
currentScopeHostIds?: ReadonlyArray<string>;
workspaces: ReadonlyArray<{ id: string; title: string }>;
terminalInfos: ReadonlyArray<GlobalManagerTerminalInfo>;
externalAgents: ExternalAgentConfig[];
rebindTargets: GlobalManagerScopeTarget[];
onSelect: (sessionId: string) => void;
onRebind: (sessionId: string, target: GlobalManagerScopeTarget) => void;
onDelete: (sessionId: string) => void;
onExport: (sessionId: string) => void;
}
// Render guard, mirroring the scoped drawer. The store is capped well below
// this by retention (MAX_STORED_SESSIONS), but the manager must stay cheap
// even on stores grown before the cap existed (~2k sessions).
const MANAGER_RENDER_BATCH = 80;
const MANAGER_RENDER_STEP = 60;
export const GlobalAIChatSessionManager: React.FC<GlobalAIChatSessionManagerProps> = ({
sessions,
activeSessionIdMap,
currentScopeType,
currentScopeTargetId,
currentScopeHostIds,
workspaces,
terminalInfos,
externalAgents,
rebindTargets,
onSelect,
onRebind,
onDelete,
onExport,
}) => {
const { t } = useI18n();
const [searchQuery, setSearchQuery] = useState('');
const [agentFilter, setAgentFilter] = useState<string>('all');
const [renderCount, setRenderCount] = useState(MANAGER_RENDER_BATCH);
const [deleteTarget, setDeleteTarget] = useState<AISession | null>(null);
const [rebindSession, setRebindSession] = useState<AISession | null>(null);
const rows = useMemo(
() => buildGlobalManagerRows({
sessions,
activeSessionIdMap,
currentScopeType,
currentScopeTargetId,
workspaces,
terminalInfos,
externalAgents,
t,
}),
[sessions, activeSessionIdMap, currentScopeType, currentScopeTargetId, workspaces, terminalInfos, externalAgents, t],
);
const agentIds = useMemo(() => collectGlobalManagerAgentIds(rows), [rows]);
const effectiveAgentFilter = agentFilter !== 'all' && agentIds.includes(agentFilter)
? agentFilter
: 'all';
const filteredRows = useMemo(
() => filterGlobalManagerRows(rows, { query: searchQuery, agentId: effectiveAgentFilter }),
[rows, searchQuery, effectiveAgentFilter],
);
useEffect(() => {
setRenderCount(MANAGER_RENDER_BATCH);
}, [searchQuery, agentFilter]);
// Deleting the last chat of the filtered agent must not leave the manager
// pointing at an agent with no rows (the select would show a blank value
// and the list a permanent "no matches"). Reset to "all"; the select's
// built-in "all" option stays the manual clear affordance.
useEffect(() => {
if (agentFilter !== 'all' && !agentIds.includes(agentFilter)) {
setAgentFilter('all');
}
}, [agentFilter, agentIds]);
const displayedRows = filteredRows.slice(0, renderCount);
const hiddenRowCount = Math.max(0, filteredRows.length - renderCount);
const commitDelete = () => {
if (!deleteTarget) return;
onDelete(deleteTarget.id);
setDeleteTarget(null);
};
const chooseRebindTarget = (value: string) => {
if (!rebindSession || !value) return;
if (value === 'here') {
if (!currentScopeTargetId) return;
// Preserve the destination's host association: rewriting the scope
// without hostIds would orphan the host linkage the panel maintains
// for terminal-scope reconnection.
onRebind(rebindSession.id, {
type: currentScopeType,
targetId: currentScopeTargetId,
label: '',
hostIds: currentScopeHostIds && currentScopeHostIds.length > 0
? [...currentScopeHostIds]
: undefined,
});
} else {
const target = rebindTargets.find((candidate) => `${candidate.type}:${candidate.targetId}` === value);
if (target) onRebind(rebindSession.id, target);
}
setRebindSession(null);
};
return (
<div className="flex-1 flex flex-col min-h-0" data-section="ai-global-session-manager">
<div className="px-3 py-2 shrink-0 border-b border-border/30 space-y-2">
<div className="relative">
<Search
size={13}
className="absolute left-2.5 top-1/2 -translate-y-1/2 text-muted-foreground/50 pointer-events-none"
/>
<Input
type="text"
value={searchQuery}
maxLength={200}
placeholder={t('ai.chat.managerSearchPlaceholder')}
aria-label={t('ai.chat.managerSearchPlaceholder')}
onChange={(event) => setSearchQuery(event.target.value)}
className="h-8 pl-8 pr-7 text-[12px]"
/>
{searchQuery && (
<button
type="button"
aria-label={t('ai.chat.clearSessionSearch')}
onClick={() => setSearchQuery('')}
className="absolute right-2 top-1/2 -translate-y-1/2 text-muted-foreground/50 hover:text-muted-foreground transition-colors cursor-pointer"
>
<X size={12} />
</button>
)}
</div>
{agentIds.length > 1 && (
<Select value={effectiveAgentFilter} onValueChange={setAgentFilter}>
<SelectTrigger
aria-label={t('ai.chat.managerFilterAllAgents')}
className="h-7 w-full px-2 text-[12px]"
>
<SelectValue />
</SelectTrigger>
<SelectContent>
<SelectItem value="all" className="text-[12px]">
{t('ai.chat.managerFilterAllAgents')}
</SelectItem>
{agentIds.map((agentId) => (
<SelectItem key={agentId} value={agentId} className="text-[12px]">
{rows.find((row) => row.agentId === agentId)?.agentLabel ?? agentId}
</SelectItem>
))}
</SelectContent>
</Select>
)}
</div>
<ScrollArea className="flex-1">
<div className="px-3">
{filteredRows.length === 0 ? (
<div className="py-12 text-center">
<p className="text-[13px] text-muted-foreground/40">
{rows.length === 0 ? t('ai.chat.noSessions') : t('ai.chat.noMatchingSessions')}
</p>
</div>
) : (
<>
{hiddenRowCount > 0 && (
<button
type="button"
onClick={() => setRenderCount((count) => count + MANAGER_RENDER_STEP)}
className="w-full py-2 text-center text-[12px] text-muted-foreground/50 hover:text-muted-foreground transition-colors cursor-pointer"
>
{t('ai.chat.loadMoreSessions').replace('{n}', String(hiddenRowCount))}
</button>
)}
{displayedRows.map((row) => (
<React.Fragment key={row.session.id}>
<div
className={cn(SESSION_HISTORY_ROW_CLASSNAMES.row, 'cursor-default')}
data-session-id={row.session.id}
data-scope-state={row.scopeState}
>
<div className="min-w-0">
<div className="flex items-center gap-1.5 min-w-0">
<span className={cn(SESSION_HISTORY_ROW_CLASSNAMES.title, 'shrink')}>
{row.title}
</span>
<span
className={cn(
'shrink-0 rounded px-1 text-[10px] leading-4',
row.scopeState === 'dangling'
? 'bg-amber-500/15 text-amber-600 dark:text-amber-400'
: row.scopeState === 'active'
? 'bg-primary/15 text-primary'
: 'bg-muted text-muted-foreground/70',
)}
>
{t(row.scopeState === 'dangling'
? 'ai.chat.chatsScopeDangling'
: row.scopeState === 'active'
? 'ai.chat.managerBadgeActive'
: 'ai.chat.managerBadgeIdle')}
</span>
</div>
<div className="mt-0.5 flex items-center gap-1.5 text-[11px] text-muted-foreground/50 min-w-0">
<span className="truncate">{row.agentLabel}</span>
<span aria-hidden>·</span>
<span className="truncate">{row.scopeLabel}</span>
<span aria-hidden>·</span>
<span className="shrink-0">
{t('ai.chat.managerMessagesCount').replace('{n}', String(row.messageCount))}
</span>
<span aria-hidden>·</span>
<span className="shrink-0">{formatRelativeTime(new Date(row.session.updatedAt), t)}</span>
</div>
</div>
<div className="flex items-center gap-1 shrink-0">
{row.canActivate ? (
<Tooltip>
<TooltipTrigger asChild>
<button
type="button"
onClick={() => onSelect(row.session.id)}
aria-label={t('ai.chat.managerOpen')}
className={SESSION_HISTORY_ROW_CLASSNAMES.deleteButton}
>
<Play size={12} />
</button>
</TooltipTrigger>
<TooltipContent>{t('ai.chat.managerOpen')}</TooltipContent>
</Tooltip>
) : (
<Tooltip>
<TooltipTrigger asChild>
<span className="inline-flex cursor-not-allowed">
<button
type="button"
disabled
aria-disabled="true"
aria-label={t('ai.chat.managerOpenDisabled')}
className={cn(SESSION_HISTORY_ROW_CLASSNAMES.deleteButton, 'opacity-30 pointer-events-none')}
>
<Play size={12} />
</button>
</span>
</TooltipTrigger>
<TooltipContent>{t('ai.chat.managerOpenDisabled')}</TooltipContent>
</Tooltip>
)}
<Tooltip>
<TooltipTrigger asChild>
<button
type="button"
onClick={() => onExport(row.session.id)}
aria-label={t('ai.chat.managerExportOne')}
className={SESSION_HISTORY_ROW_CLASSNAMES.deleteButton}
>
<Download size={12} />
</button>
</TooltipTrigger>
<TooltipContent>{t('ai.chat.managerExportOne')}</TooltipContent>
</Tooltip>
<Tooltip>
<TooltipTrigger asChild>
<button
type="button"
onClick={() => setRebindSession(
rebindSession?.id === row.session.id ? null : row.session,
)}
aria-label={t('ai.chat.managerRebind')}
className={SESSION_HISTORY_ROW_CLASSNAMES.deleteButton}
>
<FolderInput size={12} />
</button>
</TooltipTrigger>
<TooltipContent>{t('ai.chat.managerRebind')}</TooltipContent>
</Tooltip>
<Tooltip>
<TooltipTrigger asChild>
<button
type="button"
onClick={() => setDeleteTarget(row.session)}
aria-label={t('common.delete')}
className={SESSION_HISTORY_ROW_CLASSNAMES.deleteButton}
>
<Trash2 size={12} />
</button>
</TooltipTrigger>
<TooltipContent>{t('common.delete')}</TooltipContent>
</Tooltip>
</div>
</div>
{rebindSession?.id === row.session.id && (
<div className="py-1.5 pl-1 border-b border-border/20" data-section="ai-manager-rebind-picker">
<Select value="" onValueChange={chooseRebindTarget}>
<SelectTrigger
aria-label={t('ai.chat.managerRebindPick')}
className="h-7 w-full px-2 text-[12px]"
>
<SelectValue placeholder={t('ai.chat.managerRebindPick')} />
</SelectTrigger>
<SelectContent>
{currentScopeTargetId
&& (
row.session.scopeDangling
|| row.session.scope.type !== currentScopeType
|| row.session.scope.targetId !== currentScopeTargetId
) && (
<SelectItem value="here" className="text-[12px]">
{t('ai.chat.managerRebindHere')}
</SelectItem>
)}
{rebindTargets.map((target) => (
<SelectItem
key={`${target.type}:${target.targetId}`}
value={`${target.type}:${target.targetId}`}
className="text-[12px]"
>
{target.type === 'workspace'
? `${t('ai.chat.chatsScopeWorkspace')}: ${target.label}`
: `${t('ai.chat.chatsScopeTerminal')}: ${target.label}`}
</SelectItem>
))}
</SelectContent>
</Select>
</div>
)}
</React.Fragment>
))}
</>
)}
</div>
</ScrollArea>
<ConfirmDialog
open={deleteTarget != null}
title={t('ai.chat.managerDeleteTitle')}
message={deleteTarget
? t('ai.chat.managerDeleteMessage').replace(
'{title}',
deleteTarget.title || t('ai.chat.untitled'),
)
: undefined}
confirmLabel={t('common.delete')}
destructive
onOpenChange={(open) => {
if (!open) setDeleteTarget(null);
}}
onConfirm={commitDelete}
/>
</div>
);
};