mirror of
https://github.com/binaricat/Netcatty.git
synced 2026-11-25 18:16:32 +00:00
* 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>
191 lines
7.1 KiB
TypeScript
191 lines
7.1 KiB
TypeScript
import type React from 'react';
|
|
import { useCallback, useMemo, useRef } from 'react';
|
|
|
|
import {
|
|
retainStableAiPanelContexts,
|
|
retainStableAiTerminalSessionInfos,
|
|
} from '../../domain/aiPanelContextsEqual';
|
|
import {
|
|
buildAITerminalSessionInfo,
|
|
type AIPanelContext,
|
|
type AITerminalSessionInfo,
|
|
} from '../../domain/buildAITerminalSessionInfo';
|
|
import { collectSessionIds } from '../../domain/workspace';
|
|
import type { TerminalContextReader } from '../../domain/terminalContextRead';
|
|
import { detectLocalOs } from '../../lib/localShell';
|
|
import type { Host, PortForwardingRule, TerminalSession, Workspace } from '../../types';
|
|
|
|
interface UseTerminalAiContextsOptions {
|
|
hosts: Host[];
|
|
hostsRef: React.MutableRefObject<Host[]>;
|
|
portForwardingRules: PortForwardingRule[];
|
|
portForwardingRulesRef: React.MutableRefObject<PortForwardingRule[]>;
|
|
mountedAiTabIds: string[];
|
|
sessionHostsMap: Map<string, Host>;
|
|
sessions: TerminalSession[];
|
|
sessionsRef: React.MutableRefObject<TerminalSession[]>;
|
|
terminalContextReadersRef: React.MutableRefObject<Map<string, TerminalContextReader>>;
|
|
workspaces: Workspace[];
|
|
workspacesRef: React.MutableRefObject<Workspace[]>;
|
|
}
|
|
|
|
/**
|
|
* Per-session AI info for EVERY live terminal in the session store, not only
|
|
* those reachable through `aiContextsByTabId` (which covers just the tabs
|
|
* whose AI panel context was mounted — a terminal there is missing as a
|
|
* global session manager rebind target until its tab opens the AI panel).
|
|
* Rebinding to a context-less terminal is still valid: the association is
|
|
* created on demand. Uses the same `buildAITerminalSessionInfo` as the
|
|
* per-tab contexts, so infos merge seamlessly where a context exists.
|
|
*/
|
|
export function buildAllTerminalAiInfos(
|
|
sessions: TerminalSession[],
|
|
sessionHostsMap: Map<string, Host>,
|
|
hosts: Host[],
|
|
portForwardingRules: PortForwardingRule[],
|
|
localOs: 'linux' | 'macos' | 'windows',
|
|
): AITerminalSessionInfo[] {
|
|
const infos: AITerminalSessionInfo[] = [];
|
|
const seen = new Set<string>();
|
|
for (const session of sessions) {
|
|
if (!session.id || seen.has(session.id)) continue;
|
|
seen.add(session.id);
|
|
infos.push(buildAITerminalSessionInfo(session, sessionHostsMap.get(session.id), localOs, {
|
|
allHosts: hosts,
|
|
portForwardingRules,
|
|
}));
|
|
}
|
|
return infos;
|
|
}
|
|
|
|
export function useTerminalAiContexts({
|
|
hosts,
|
|
hostsRef,
|
|
portForwardingRules,
|
|
portForwardingRulesRef,
|
|
mountedAiTabIds,
|
|
sessionHostsMap,
|
|
sessions,
|
|
sessionsRef,
|
|
terminalContextReadersRef,
|
|
workspaces,
|
|
workspacesRef,
|
|
}: UseTerminalAiContextsOptions) {
|
|
const previousAiContextsRef = useRef<Map<string, AIPanelContext> | null>(null);
|
|
const aiContextsByTabId = useMemo(() => {
|
|
const localOs = detectLocalOs(navigator.userAgent || navigator.platform);
|
|
const sessionById = new Map<string, TerminalSession>(sessions.map((session) => [session.id, session]));
|
|
const workspaceById = new Map<string, Workspace>(workspaces.map((workspace) => [workspace.id, workspace]));
|
|
const allHosts = hosts;
|
|
const tabIds = new Set<string>(mountedAiTabIds);
|
|
|
|
const contexts = new Map<string, AIPanelContext>();
|
|
|
|
for (const tabId of tabIds) {
|
|
const workspace = workspaceById.get(tabId);
|
|
if (workspace) {
|
|
const sessionIds = collectSessionIds(workspace.root);
|
|
contexts.set(tabId, {
|
|
scopeType: 'workspace',
|
|
scopeTargetId: workspace.id,
|
|
scopeHostIds: sessionIds
|
|
.map((sessionId) => sessionById.get(sessionId)?.hostId)
|
|
.filter((hostId): hostId is string => !!hostId),
|
|
scopeLabel: workspace.title,
|
|
focusedSessionId: workspace.focusedSessionId,
|
|
terminalSessions: sessionIds.map((sessionId) =>
|
|
buildAITerminalSessionInfo(
|
|
sessionById.get(sessionId),
|
|
sessionHostsMap.get(sessionId),
|
|
localOs,
|
|
{ allHosts, portForwardingRules },
|
|
),
|
|
),
|
|
});
|
|
continue;
|
|
}
|
|
|
|
const session = sessionById.get(tabId);
|
|
if (!session) continue;
|
|
|
|
contexts.set(tabId, {
|
|
scopeType: 'terminal',
|
|
scopeTargetId: session.id,
|
|
scopeHostIds: session.hostId ? [session.hostId] : [],
|
|
scopeLabel: session.hostLabel ?? '',
|
|
terminalSessions: [
|
|
buildAITerminalSessionInfo(
|
|
session,
|
|
sessionHostsMap.get(session.id),
|
|
localOs,
|
|
{ allHosts, portForwardingRules },
|
|
),
|
|
],
|
|
});
|
|
}
|
|
|
|
const retained = retainStableAiPanelContexts(previousAiContextsRef.current, contexts);
|
|
previousAiContextsRef.current = retained;
|
|
return retained;
|
|
}, [sessions, workspaces, mountedAiTabIds, sessionHostsMap, hosts, portForwardingRules]);
|
|
|
|
const previousAppTerminalInfosRef = useRef<AITerminalSessionInfo[] | null>(null);
|
|
const appTerminalInfos = useMemo(() => {
|
|
const localOs = detectLocalOs(navigator.userAgent || navigator.platform);
|
|
const next = buildAllTerminalAiInfos(sessions, sessionHostsMap, hosts, portForwardingRules, localOs);
|
|
const retained = retainStableAiTerminalSessionInfos(previousAppTerminalInfosRef.current, next);
|
|
previousAppTerminalInfosRef.current = retained;
|
|
return retained;
|
|
}, [sessions, sessionHostsMap, hosts, portForwardingRules]);
|
|
|
|
const resolveAIExecutorContext = useCallback((scope: {
|
|
type: 'terminal' | 'workspace';
|
|
targetId?: string;
|
|
label?: string;
|
|
}) => {
|
|
const latestWorkspaces = workspacesRef.current;
|
|
const latestSessions = sessionsRef.current;
|
|
const latestHosts = hostsRef.current;
|
|
const localOs = detectLocalOs(navigator.userAgent || navigator.platform);
|
|
const sessionIds = scope.type === 'workspace'
|
|
? (() => {
|
|
const workspace = scope.targetId ? latestWorkspaces.find((w) => w.id === scope.targetId) : undefined;
|
|
return workspace?.root ? collectSessionIds(workspace.root) : [];
|
|
})()
|
|
: scope.targetId ? [scope.targetId] : [];
|
|
|
|
const workspaceName = scope.type === 'workspace'
|
|
? latestWorkspaces.find((w) => w.id === scope.targetId)?.title ?? scope.label
|
|
: undefined;
|
|
|
|
return {
|
|
sessions: sessionIds.map((sid) => {
|
|
const session = latestSessions.find((s) => s.id === sid);
|
|
const host = session ? sessionHostsMap.get(session.id) : undefined;
|
|
return buildAITerminalSessionInfo(session, host, localOs, {
|
|
allHosts: latestHosts,
|
|
portForwardingRules: portForwardingRulesRef.current,
|
|
});
|
|
}),
|
|
workspaceId: scope.type === 'workspace' ? scope.targetId : undefined,
|
|
workspaceName,
|
|
readTerminalContext: (request: Parameters<TerminalContextReader>[0]) => {
|
|
const reader = terminalContextReadersRef.current.get(request.sessionId);
|
|
if (!reader) {
|
|
return Promise.resolve({
|
|
ok: false as const,
|
|
error: `Terminal session "${request.sessionId}" has no readable terminal buffer.`,
|
|
});
|
|
}
|
|
return reader(request);
|
|
},
|
|
};
|
|
}, [hostsRef, portForwardingRulesRef, sessionHostsMap, sessionsRef, terminalContextReadersRef, workspacesRef]);
|
|
|
|
return {
|
|
aiContextsByTabId,
|
|
appTerminalInfos,
|
|
resolveAIExecutorContext,
|
|
};
|
|
}
|