Files
Netcatty/application/state/useTerminalAiContexts.test.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

88 lines
3.0 KiB
TypeScript

import assert from "node:assert/strict";
import { readFileSync } from "node:fs";
import test from "node:test";
import { buildAllTerminalAiInfos } from "./useTerminalAiContexts.ts";
import type { Host, TerminalSession } from "../../types";
const makeSession = (overrides: Partial<TerminalSession> & { id: string }): TerminalSession => ({
hostId: "",
hostLabel: "",
username: "",
hostname: "host.example",
status: "connected",
...overrides,
} as TerminalSession);
const makeHost = (overrides: Partial<Host> & { id: string }): Host => ({
label: overrides.id,
hostname: `${overrides.id}.example`,
...overrides,
} as Host);
test("buildAllTerminalAiInfos lists every live terminal, including those without a mounted AI context", () => {
// t-1 belongs to a tab with a mounted AI panel context; t-2's tab never
// mounted one. Both must appear so the global session manager offers t-2
// as a rebind target (rebinding creates the association on demand).
const sessionHostsMap = new Map([
["t-1", makeHost({ id: "h-1" })],
]);
const infos = buildAllTerminalAiInfos(
[makeSession({ id: "t-1", hostId: "h-1" }), makeSession({ id: "t-2", hostId: "h-2", customName: "core" })],
sessionHostsMap,
[makeHost({ id: "h-1" })],
[],
"linux",
);
assert.deepEqual(infos.map((info) => info.sessionId), ["t-1", "t-2"]);
const contextless = infos.find((info) => info.sessionId === "t-2")!;
assert.equal(contextless.hostId, "h-2", "context-less terminal keeps its host linkage for the rebind");
assert.equal(contextless.label, "core");
assert.equal(contextless.connected, true);
});
test("buildAllTerminalAiInfos skips id-less entries and dedupes session ids", () => {
const infos = buildAllTerminalAiInfos(
[
makeSession({ id: "t-1" }),
makeSession({ id: "t-1", hostId: "h-9" }),
makeSession({ id: "", hostId: "h-3" }),
],
new Map(),
[],
[],
"linux",
);
assert.deepEqual(infos.map((info) => info.sessionId), ["t-1"]);
});
test("AIChatPanelsHost receives store-derived terminal infos instead of deriving them from mounted AI contexts", () => {
const supportSource = readFileSync(
new URL("../../components/terminalLayer/TerminalLayerSupport.tsx", import.meta.url),
"utf8",
);
assert.match(supportSource, /appTerminalSessions=\{appTerminalSessions\}/);
assert.doesNotMatch(
supportSource,
/for \(const context of contextsByTabId\.values\(\)\)/,
"rebind targets must not be limited to tabs with a mounted AI context",
);
const bridgeSource = readFileSync(
new URL("../../components/terminalLayer/TerminalLayerTabBridge.tsx", import.meta.url),
"utf8",
);
assert.match(bridgeSource, /appTerminalInfos/);
const contextsHookSource = readFileSync(
new URL("./useTerminalAiContexts.ts", import.meta.url),
"utf8",
);
assert.match(
contextsHookSource,
/retainStableAiTerminalSessionInfos/,
"appTerminalInfos must retain array identity across structurally identical terminal updates",
);
});