All files / src/components/chat/ChatDock target.ts

100% Statements 16/16
100% Branches 18/18
100% Functions 3/3
100% Lines 13/13

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45                      2x 193x     6x 6x 6x 6x 3x                                   61x 49x 61x 61x 2x 61x    
import type { Agent } from "@/objects/Agent";
import { isSystemManaged } from "@/objects/Doc";
import { type Model, selectableModels } from "@/objects/Model";
 
/** What the chat dock is talking to: an agent or a model, by id. */
export interface ChatTarget {
  kind: "agent" | "model";
  id: string;
}
 
/** A target as one string — the picker's radio value. */
export const targetKey = (target: ChatTarget): string =>
  `${target.kind}:${target.id}`;
 
export function parseTargetKey(key: string): ChatTarget | null {
  const at = key.indexOf(":");
  const kind = key.slice(0, at);
  const id = key.slice(at + 1);
  if (at < 0 || !id || (kind !== "agent" && kind !== "model")) return null;
  return { kind, id };
}
 
/**
 * Where the dock opens before anyone has chosen: CHAINR Bot, which every
 * workspace's agent listing carries (svc-core lists it first) — recognised
 * by its flag, as Overview recognises it, never by position or id. Failing
 * that the workspace's first agent, then the first model a chat can use.
 *
 * Nothing until the agents have been read (`agentsSettled`): falling back
 * to a model while they load would open a model chat and then swap it for
 * the bot a moment later.
 */
export function defaultTarget(
  agents: Agent[] | null | undefined,
  models: Model[] | null | undefined,
  agentsSettled: boolean,
): ChatTarget | null {
  if (!agentsSettled) return null;
  const listed = agents ?? [];
  const agent = listed.find(isSystemManaged) ?? listed[0];
  if (agent) return { kind: "agent", id: agent.id };
  const model = selectableModels(models ?? [])[0];
  return model ? { kind: "model", id: model.id } : null;
}