Files
Netcatty/domain/aiSessionRecency.ts
T
GOUKI9999 98d75c13fe feat(ai): anchor workspace AI chats by id, not position
Phase 2 of #4098: every remaining positional fallback in the workspace
AI scope is replaced with id-based resolution.

- Workspace gains anchorChatId: pinned by the AI side panel whenever a
  chat becomes active in the workspace scope, persisted through the
  session restore snapshot, and validated lazily by consumers.
- resolveDisplayedPanelView: the auto-resume fallback now resolves the
  anchored chat first, then the most recently updated chat (updatedAt),
  else draft; sessions[0] is gone.
- retargetWorkspaceActiveChatAfterMemberLoss: when the focused member
  did not survive, the retarget lands on the most-recently-active
  survivor by chat recency, not the first positional member.
- plugin keybinding context: focused member, then the terminal member
  owning the anchored chat, then the most-recently-active member; a
  single-member workspace uses its only member.
- New domain/aiSessionRecency helper shared by all survivor rankings.
- /rebind and session_recover semantics (#4019) are unchanged.
2026-11-06 15:34:15 +08:00

52 lines
1.9 KiB
TypeScript

/**
* Recency ranking for workspace member terminals, driven by the AI session
* store (issue #4098 phase 2). All former "first member" positional fallbacks
* resolve through this: when a decision has to pick one member out of the
* survivors, the most recently active member's chat wins — never the first
* element of an array.
*/
export type AIChatRecencyEntry = {
id?: string;
scope: {
type: string;
targetId?: string;
};
updatedAt?: number;
};
/**
* Return the member terminal id whose terminal-scoped AI chat has the highest
* `updatedAt`, or null when no member owns a chat (no recency signal exists —
* callers must then use their own documented deterministic fallback, not a
* positional one). Members without a chat rank after members with one.
*/
export function resolveMostRecentlyActiveMemberTerminalId(input: {
memberTerminalIds: readonly string[];
aiSessions?: readonly AIChatRecencyEntry[];
}): string | null {
const recencyByMember = new Map<string, number>();
for (const session of input.aiSessions ?? []) {
if (session.scope?.type !== 'terminal' || !session.scope.targetId) continue;
if (!input.memberTerminalIds.includes(session.scope.targetId)) continue;
const updatedAt = session.updatedAt ?? 0;
const current = recencyByMember.get(session.scope.targetId) ?? 0;
if (updatedAt > current) {
recencyByMember.set(session.scope.targetId, updatedAt);
}
}
let bestId: string | null = null;
let bestRecency = 0;
for (const memberId of input.memberTerminalIds) {
if (!memberId) continue;
const recency = recencyByMember.get(memberId) ?? 0;
if (bestId === null || recency > bestRecency) {
bestId = memberId;
bestRecency = recency;
}
}
// All-zero recency means no survivor owns a chat: there is no non-positional
// signal, so the caller decides.
return bestRecency > 0 ? bestId : null;
}