Files
Netcatty/application/state/useAIState.exportSubset.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

67 lines
2.9 KiB
TypeScript

import assert from 'node:assert/strict';
import test from 'node:test';
import React, { act } from 'react';
import { createRoot } from 'react-dom/client';
import { JSDOM } from 'jsdom';
import type { AISession } from '../../infrastructure/ai/types';
import { useAIState } from './useAIState';
import { setLatestAISessionsSnapshot } from './aiStateSnapshots';
// Global session manager (issue #4098 phase 4): exportSessionsBackup with a
// session-id subset exports only those chats; without one it exports the
// whole store as before (#4018).
test('exportSessionsBackup exports a single-chat subset or the whole store', async () => {
const dom = new JSDOM('<!doctype html><html><body></body></html>', { url: 'http://localhost' });
for (const name of ['window', 'document', 'localStorage', 'CustomEvent', 'Event'] as const) {
Object.defineProperty(globalThis, name, { configurable: true, value: name === 'window' ? dom.window : dom.window[name] });
}
Object.defineProperty(globalThis, 'IS_REACT_ACT_ENVIRONMENT', { configurable: true, value: true });
const sessions: AISession[] = [
{ id: 'chat-a', title: 'A', agentId: 'catty', scope: { type: 'terminal', targetId: 't-1' }, messages: [], createdAt: 1, updatedAt: 10 },
{ id: 'chat-b', title: 'B', agentId: 'codex', scope: { type: 'workspace', targetId: 'w-1' }, messages: [], createdAt: 2, updatedAt: 20 },
] as AISession[];
// Seed the module snapshot so useAIState boots with the live store.
setLatestAISessionsSnapshot(sessions);
const exportCalls: string[] = [];
(dom.window as unknown as { netcatty: unknown }).netcatty = {
aiSessionsBackupExport: async ({ json }: { json: string }) => {
exportCalls.push(json);
return { success: true, filePath: '/tmp/export.json' };
},
};
let ai: ReturnType<typeof useAIState>;
function Harness() {
ai = useAIState();
return null;
}
const container = document.createElement('div');
document.body.appendChild(container);
const root = createRoot(container);
try {
await act(async () => { root.render(React.createElement(Harness)); });
await act(async () => {
// Hydration completes asynchronously; the export path reads the live ref.
await Promise.resolve();
});
const subsetPath = await ai!.exportSessionsBackup(['chat-b']);
assert.equal(subsetPath, '/tmp/export.json');
assert.equal(exportCalls.length, 1);
const subset = JSON.parse(exportCalls[0]) as AISession[];
assert.deepEqual(subset.map((session) => session.id), ['chat-b']);
const wholePath = await ai!.exportSessionsBackup();
assert.equal(wholePath, '/tmp/export.json');
const whole = JSON.parse(exportCalls[1]) as AISession[];
assert.deepEqual(whole.map((session) => session.id).sort(), ['chat-a', 'chat-b']);
} finally {
await act(async () => { root.unmount(); });
container.remove();
dom.window.close();
}
});