All files / src/apps/user/pages/knowledge RepositoryAgentsCard.tsx

100% Statements 28/28
90.32% Branches 28/31
100% Functions 12/12
100% Lines 27/27

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 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193                                                                3x       15x 15x   15x   6x   15x       9x       15x 24x   15x 7x     15x   3x 3x 2x   1x           3x     3x             15x 15x       15x 15x   15x                                     12x                                             15x 15x                                                       3x                                                                  
import { AppearanceSwatch } from "@/components/appearance/AppearancePicker";
import { AGENT_ICON_REGISTRY } from "@/components/appearance/icons";
import { encodeResourceId, SectionCard } from "@/components/detail";
import { Agent } from "@/objects/Agent";
import { isSystemManaged } from "@/objects/Doc";
import { RepositoryAgentGrant } from "@/objects/Knowledge";
import { APP_ROUTES, ROUTE_PARAMS } from "@/routes/const";
import { QUERY_KEYS } from "@/services/query_keys";
import { useApiHandler } from "@/services/useApiHandler";
import { errorDetail } from "@/util/apiError";
import { useMutation, useQuery, useQueryClient } from "@tanstack/react-query";
import { Bot, Plus } from "lucide-react";
import React from "react";
import { Link } from "react-router-dom";
 
interface GrantChange {
  agentId: string;
  on: boolean;
}
 
/**
 * Which of the user's own agents answer with a repository, and the switch to
 * change it.
 *
 * Offered on every repository, built-in or not. Granting is a *read* of the
 * repository — the agent reads through it — so a built-in one (the guide,
 * News) that nobody can edit can still be used by everyone's agents. A
 * grant is a change to the **agent**: it goes through the agent's grant
 * routes and is versioned on the agent's history, not the repository's. The
 * repository only answers which of the caller's agents hold it, and never
 * names another user's.
 */
const RepositoryAgentsCard: React.FC<{
  repositoryId: string;
  builtIn?: boolean;
}> = ({ repositoryId, builtIn = false }) => {
  const { getApiHandler } = useApiHandler();
  const queryClient = useQueryClient();
 
  const { data: agents, isLoading: agentsLoading } = useQuery({
    queryKey: [QUERY_KEYS.GET.AGENTS],
    queryFn: () => getApiHandler().agent_router.list(undefined),
  });
  const { data: grants, isLoading: grantsLoading } = useQuery<
    RepositoryAgentGrant[]
  >({
    queryKey: [QUERY_KEYS.GET.REPOSITORY_AGENTS, repositoryId],
    queryFn: () => getApiHandler().repository_router.listAgents(repositoryId),
  });
 
  // CHAINR Bot is not the user's to change, and the API refuses it.
  const own = ((agents as Agent[] | null | undefined) ?? []).filter(
    (agent) => !isSystemManaged(agent),
  );
  const granted = new Set(
    (grants ?? []).map((grant: RepositoryAgentGrant) => grant.agent_id),
  );
 
  const change = useMutation({
    mutationFn: async ({ agentId, on }: GrantChange) => {
      const api = getApiHandler().agent_router;
      if (on) {
        await api.addAgentRepository(agentId, repositoryId);
      } else {
        await api.removeAgentRepository(agentId, repositoryId);
      }
    },
    // Settled, not succeeded: a refusal (another tab already changed it)
    // still re-reads the truth, so the switch never keeps showing a guess.
    onSettled: (_data, _error, { agentId }) => {
      void queryClient.invalidateQueries({
        queryKey: [QUERY_KEYS.GET.REPOSITORY_AGENTS, repositoryId],
      });
      void queryClient.invalidateQueries({
        queryKey: [QUERY_KEYS.GET.AGENT_REPOSITORIES, agentId],
      });
    },
  });
 
  /** The switch shows the change being made until the server answers. */
  const isOn = (agentId: string) =>
    change.isPending && change.variables?.agentId === agentId
      ? change.variables.on
      : granted.has(agentId);
 
  const usedBy = own.filter((agent) => granted.has(agent.id)).length;
  const loading = agentsLoading || grantsLoading;
 
  return (
    <SectionCard
      icon={Bot}
      title="Use in your agents"
      subtitle={
        !loading && own.length > 0
          ? `${usedBy} of ${own.length} agent${own.length !== 1 ? "s" : ""}`
          : undefined
      }
      description={
        builtIn
          ? "Switch it on and the agent answers with this repository, citing its sources. Nothing is copied: your agents read it as CHAIN-R keeps it current."
          : "Switch it on and the agent answers with this repository's sources, citing them."
      }
      bodyClassName="px-0 py-0"
    >
      {loading ? (
        <div className="space-y-2 px-5 py-4">
          {[1, 2].map((i) => (
            <div
              key={i}
              className="h-10 rounded-lg bg-gray-100 dark:bg-gray-700 animate-pulse"
            />
          ))}
        </div>
      ) : own.length === 0 ? (
        <div className="flex flex-col items-center gap-3 px-5 py-8 text-center">
          <p className="text-sm text-gray-400 dark:text-gray-500">
            You have no agents yet.
          </p>
          <Link
            to={APP_ROUTES.USER.INFERENCE.AGENTS.new}
            className="flex items-center gap-1.5 px-3 py-1.5 rounded-lg border border-gray-200 dark:border-gray-600 text-xs font-medium text-gray-600 dark:text-gray-300 hover:bg-gray-50 dark:hover:bg-gray-700 transition-colors"
          >
            <Plus className="size-3.5" />
            Create an agent
          </Link>
        </div>
      ) : (
        <>
          <ul className="max-h-80 overflow-y-auto divide-y divide-gray-50 dark:divide-gray-700/50">
            {own.map((agent) => {
              const on = isOn(agent.id);
              return (
                <li
                  key={agent.id}
                  className="flex items-center justify-between gap-3 px-5 py-2.5"
                >
                  <Link
                    to={APP_ROUTES.USER.INFERENCE.AGENTS.id.replace(
                      ROUTE_PARAMS.AGENT.id,
                      encodeResourceId(agent.id),
                    )}
                    className="flex items-center gap-2.5 min-w-0 flex-1 group"
                  >
                    <AppearanceSwatch
                      registry={AGENT_ICON_REGISTRY}
                      icon={agent.icon}
                      accent={agent.accent}
                      size="sm"
                    />
                    <span className="text-sm text-gray-800 dark:text-gray-200 truncate group-hover:underline">
                      {agent.name}
                    </span>
                  </Link>
                  <button
                    type="button"
                    role="switch"
                    aria-checked={on}
                    aria-label={`Use in ${agent.name}`}
                    disabled={change.isPending}
                    onClick={() => change.mutate({ agentId: agent.id, on: !on })}
                    className={`relative shrink-0 w-10 h-5 rounded-full transition-colors focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-offset-2 focus-visible:ring-gray-400 disabled:opacity-40 disabled:cursor-not-allowed ${
                      on
                        ? "bg-gray-900 dark:bg-gray-100"
                        : "bg-gray-200 dark:bg-gray-600"
                    }`}
                  >
                    <span
                      className={`absolute top-0.5 left-0.5 size-4 rounded-full bg-white dark:bg-gray-900 shadow-sm transition-transform ${
                        on ? "translate-x-5" : "translate-x-0"
                      }`}
                    />
                  </button>
                </li>
              );
            })}
          </ul>
          <div className="border-t border-gray-100 dark:border-gray-700 px-5 py-2.5 text-[11px] text-gray-400 dark:text-gray-500">
            {change.isError ? (
              <span role="alert" className="text-red-500 dark:text-red-400">
                {errorDetail(change.error, "The change could not be saved.")}
              </span>
            ) : (
              "Each change is recorded in that agent's edit history."
            )}
          </div>
        </>
      )}
    </SectionCard>
  );
};
 
export default RepositoryAgentsCard;