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

368 lines
12 KiB
TypeScript

import assert from "node:assert/strict";
import test from "node:test";
import type {
AIPanelView,
AISession,
} from "../../infrastructure/ai/types.ts";
import {
applyDraftEntrySelection,
applyHistorySessionSelection,
normalizePanelView,
panelViewsEqual,
resolveDisplayedPanelView,
resolveDisplayedSession,
shouldForceDraftViewSync,
} from "./aiPanelViewState.ts";
import { getSessionScopeMatchRank } from "./sessionScopeMatch.ts";
function createSession(id: string, updatedAt = 1): AISession {
return {
id,
title: `Session ${id}`,
messages: [],
createdAt: 1,
updatedAt,
agentId: "catty",
scope: {
type: "terminal",
targetId: "terminal-1",
},
};
}
test("panelViewsEqual treats draft views as equal even when refs differ", () => {
assert.equal(
panelViewsEqual({ mode: "draft" }, { mode: "draft" }),
true,
);
});
test("panelViewsEqual distinguishes session targets", () => {
assert.equal(
panelViewsEqual(
{ mode: "session", sessionId: "session-1" },
{ mode: "session", sessionId: "session-2" },
),
false,
);
});
test("draft view never falls back to most recent history", () => {
const panelView: AIPanelView = { mode: "draft" };
const sessions = [createSession("session-2"), createSession("session-1")];
assert.equal(resolveDisplayedSession(panelView, sessions), null);
});
test("session view returns the selected session", () => {
const selectedSession = createSession("session-2");
const panelView: AIPanelView = { mode: "session", sessionId: selectedSession.id };
const sessions = [createSession("session-1"), selectedSession];
assert.equal(resolveDisplayedSession(panelView, sessions), selectedSession);
});
test("missing session target resolves to null instead of history fallback", () => {
const panelView: AIPanelView = { mode: "session", sessionId: "missing-session" };
const sessions = [createSession("session-2"), createSession("session-1")];
assert.equal(resolveDisplayedSession(panelView, sessions), null);
});
test("missing session target normalizes back to draft view", () => {
const panelView: AIPanelView = { mode: "session", sessionId: "missing-session" };
const sessions = [createSession("session-2"), createSession("session-1")];
assert.deepEqual(normalizePanelView(panelView, sessions), { mode: "draft" });
});
test("shouldForceDraftViewSync keeps explicit session while it is still in scoped history", () => {
const explicit: AIPanelView = { mode: "session", sessionId: "just-created" };
const normalized: AIPanelView = { mode: "draft" };
// Predicate mirrors scoped historySessions (not the global store).
const scopedHistory = new Set(["just-created"]);
assert.equal(
shouldForceDraftViewSync(explicit, normalized, (id) => scopedHistory.has(id)),
false,
);
});
test("shouldForceDraftViewSync forces draft when explicit session is gone", () => {
const explicit: AIPanelView = { mode: "session", sessionId: "deleted" };
const normalized: AIPanelView = { mode: "draft" };
assert.equal(
shouldForceDraftViewSync(explicit, normalized, () => false),
true,
);
});
test("shouldForceDraftViewSync demotes when session is only in global store, not scoped history", () => {
const explicit: AIPanelView = { mode: "session", sessionId: "other-scope" };
const normalized: AIPanelView = { mode: "draft" };
// Global store still has it; scoped history (what normalize uses) does not.
const globalStore = new Set(["other-scope"]);
const scopedHistory = new Set<string>();
assert.equal(
shouldForceDraftViewSync(explicit, normalized, (id) => scopedHistory.has(id)),
true,
);
assert.equal(
shouldForceDraftViewSync(explicit, normalized, (id) => globalStore.has(id)),
false,
);
});
test("shouldForceDraftViewSync is a no-op when views already match", () => {
const view: AIPanelView = { mode: "session", sessionId: "session-1" };
assert.equal(
shouldForceDraftViewSync(view, view, () => true),
false,
);
});
test("missing explicit panel view resumes the most recent matching history when no draft exists", () => {
const sessions = [createSession("session-2"), createSession("session-1")];
assert.deepEqual(
resolveDisplayedPanelView(undefined, false, sessions, undefined, "workspace"),
{ mode: "session", sessionId: "session-2" },
);
});
test("auto-resume prefers the anchored chat over recency and position (#4098 phase 2)", () => {
const sessions = [createSession("session-2", 9), createSession("session-1", 4)];
assert.deepEqual(
resolveDisplayedPanelView(undefined, false, sessions, undefined, "workspace", "session-1"),
{ mode: "session", sessionId: "session-1" },
);
});
test("auto-resume without an anchor picks the most recently updated chat, not sessions[0]", () => {
const sessions = [createSession("session-2", 4), createSession("session-1", 9)];
assert.deepEqual(
resolveDisplayedPanelView(undefined, false, sessions, undefined, "workspace"),
{ mode: "session", sessionId: "session-1" },
);
});
test("a stale anchor that left the scope falls through to recency", () => {
const sessions = [createSession("session-2", 4), createSession("session-1", 9)];
assert.deepEqual(
resolveDisplayedPanelView(undefined, false, sessions, undefined, "workspace", "deleted-chat"),
{ mode: "session", sessionId: "session-1" },
);
});
test("missing explicit panel view restores the persisted active session instead of the newest", () => {
const sessions = [createSession("session-2"), createSession("session-1")];
assert.deepEqual(
resolveDisplayedPanelView(undefined, false, sessions, "session-1", "workspace"),
{ mode: "session", sessionId: "session-1" },
);
});
test("persisted session id that no longer exists in history falls back to newest", () => {
const sessions = [createSession("session-2"), createSession("session-1")];
assert.deepEqual(
resolveDisplayedPanelView(undefined, false, sessions, "deleted-session", "workspace"),
{ mode: "session", sessionId: "session-2" },
);
});
test("null persisted session id falls back to newest history entry", () => {
const sessions = [createSession("session-2"), createSession("session-1")];
assert.deepEqual(
resolveDisplayedPanelView(undefined, false, sessions, null, "workspace"),
{ mode: "session", sessionId: "session-2" },
);
});
test("terminal scope without explicit view always starts from draft even when history exists", () => {
const sessions = [createSession("session-2"), createSession("session-1")];
assert.deepEqual(
resolveDisplayedPanelView(undefined, false, sessions, "session-1", "terminal"),
{ mode: "draft" },
);
});
test("missing explicit panel view prefers the draft when unsent input exists without an active chat", () => {
const sessions = [createSession("session-2"), createSession("session-1")];
assert.deepEqual(
resolveDisplayedPanelView(undefined, true, sessions, null, "workspace"),
{ mode: "draft" },
);
});
test("workspace unsent draft keeps the persisted active chat after merge seed", () => {
// Merge often seeds activeSessionIdMap without writing panelView. Typing a
// follow-up must not demote to draft or send will createSession().
const sessions = [createSession("session-2"), createSession("session-1")];
assert.deepEqual(
resolveDisplayedPanelView(undefined, true, sessions, "session-1", "workspace"),
{ mode: "session", sessionId: "session-1" },
);
});
test("explicit new-chat draft still wins over a stale persisted id", () => {
const sessions = [createSession("session-2"), createSession("session-1")];
assert.deepEqual(
resolveDisplayedPanelView(
{ mode: "draft" },
true,
sessions,
"session-1",
"workspace",
),
{ mode: "draft" },
);
});
test("draft state is used when there is no implicit history to resume", () => {
assert.deepEqual(
resolveDisplayedPanelView(undefined, true, [], null, "workspace"),
{ mode: "draft" },
);
});
test("history selection switches to the chosen session without touching draft state", () => {
const calls: string[] = [];
applyHistorySessionSelection("session-2", {
showSessionView: (sessionId) => {
calls.push(`view:${sessionId}`);
},
setActiveSessionId: (sessionId) => {
calls.push(`active:${sessionId}`);
},
closeHistory: () => {
calls.push("close-history");
},
});
assert.deepEqual(calls, [
"view:session-2",
"active:session-2",
"close-history",
]);
});
test("draft entry ensures a draft exists before switching the panel to draft mode", () => {
const calls: string[] = [];
applyDraftEntrySelection({
ensureDraft: () => {
calls.push("ensure-draft");
},
showDraftView: () => {
calls.push("show-draft");
},
});
assert.deepEqual(calls, [
"ensure-draft",
"show-draft",
]);
});
test("draft entry can preserve the current session view while ensuring draft state", () => {
const calls: string[] = [];
applyDraftEntrySelection({
ensureDraft: () => {
calls.push("ensure-draft");
},
showDraftView: () => {
calls.push("show-draft");
},
preserveSessionView: true,
});
assert.deepEqual(calls, [
"ensure-draft",
]);
});
test("cleared source view resolves to draft even while the rebound chat stays rank-1 visible", () => {
// PR #4159 round 3: rebinding chat-x from workspace A to B demotes A's
// explicit view to draft (clearSessionViewsForSession). The moved chat stays
// visible in A's scoped history at rank 1 (same scope type, different
// targetId), so a surviving explicit session view would keep it as
// activeSession and the active-session effect would recreate A's pointer.
const moved: AISession = {
...createSession("chat-x"),
scope: { type: "workspace", targetId: "workspace-B" },
};
const other: AISession = {
...createSession("chat-keep"),
scope: { type: "workspace", targetId: "workspace-A" },
};
// Precondition: the cross-workspace chat is still rank-1 visible in A.
assert.equal(getSessionScopeMatchRank(moved, "workspace", "workspace-A"), 1);
const clearedView: AIPanelView = { mode: "draft" };
const historySessions = [other, moved];
const view = resolveDisplayedPanelView(clearedView, false, historySessions, null, "workspace");
assert.deepEqual(view, { mode: "draft" });
assert.equal(
resolveDisplayedSession(view, historySessions),
null,
"A's activeSession is null, so the active-session effect cannot recreate the moved chat pointer",
);
});
test("round 4 RESTORED: an explicit draft view blocks the rank-1 fallback for a restored chat with no source view", () => {
// PR #4159 round 4: after a restart panelViewByScope starts EMPTY (memory
// only) while the active map still names chat-x as A's session. If rebound
// to B demotes only explicit views (round 3), A has no panel view at all and
// resolveDisplayedPanelView falls through to sessions[0] — the rank-1
// cross-workspace chat — letting the active-session effect recreate A's
// pointer. The round-4 fix writes an explicit draft view for A so the
// fallback is short-circuited even though no source view ever existed.
const moved: AISession = {
...createSession("chat-x"),
scope: { type: "workspace", targetId: "workspace-B" },
updatedAt: 999, // rebind touches updatedAt, so it becomes sessions[0]
};
const other: AISession = {
...createSession("chat-keep"),
scope: { type: "workspace", targetId: "workspace-A" },
updatedAt: 1,
};
const historySessions = [moved, other];
assert.equal(getSessionScopeMatchRank(moved, "workspace", "workspace-A"), 1);
// Precondition: with NO explicit view (the restored, empty-map case) the
// fallback selects the moved chat — this is the bug the fix must prevent.
const fallback = resolveDisplayedPanelView(undefined, false, historySessions, null, "workspace");
assert.deepEqual(fallback, { mode: "session", sessionId: "chat-x" });
// The round-4 draft view (written by demoteImplicitSourceViewsForSession for
// A) short-circuits the fallback: no session is displayed, so A's active
// pointer is not recreated and follow-up turns cannot run in the old scope.
const demotedView: AIPanelView = { mode: "draft" };
const view = resolveDisplayedPanelView(demotedView, false, historySessions, null, "workspace");
assert.deepEqual(view, { mode: "draft" });
assert.equal(
resolveDisplayedSession(view, historySessions),
null,
"restored A shows a draft, so the active-session effect cannot recreate the moved chat pointer",
);
});