queries.ts1.8 KBView on GitHub
'use client';

import { useQuery } from '@tanstack/react-query';

import { useTRPC } from '@/providers/query-provider';

/**
 * How long an agent's CONFIG survives in the react-query cache once nothing is
 * rendering it: 30 days.
 *
 * `gcTime`, not `staleTime`, and the difference is the whole point. Stale-time
 * would mean "don't refetch", which for a playbook two people (and the agent
 * itself) can edit is a lie waiting to be shown on screen. GC-time means "keep
 * the last answer", so re-opening an agent paints its triggers and connections
 * from cache in the same frame the tab does, while a background refetch corrects
 * it if anything moved. The payloads are a few kB of already-resolved rows, so
 * the memory cost of holding them is nothing next to a spinner on every visit.
 */
export const AGENT_CONFIG_GC_TIME = 30 * 24 * 60 * 60 * 1000;

/**
 * The playbook's optimistic-concurrency token.
 *
 * A hook, in this file, because TWO callers want it and they want it for
 * different reasons: `AgentSourcesPanel` cannot write without a version, and
 * `AgentView` fetches it on mount purely so the panel has one the instant
 * the Config tab opens. One definition means both get the same key, the same
 * retry policy, and the same cache entry — a second copy of these options is a
 * second fetch of the same row.
 *
 * `retry: false` + `noGlobalError`: a playbook this user cannot read is not an
 * error worth a toast, it just leaves the editing affordances withheld.
 */
export function useAgentPlaybookVersion(agentId: string, targetUserId?: string) {
  const trpc = useTRPC();
  return useQuery({
    ...trpc.agent.getPlaybookVersion.queryOptions({ agentId, targetUserId }),
    enabled: !!agentId,
    gcTime: AGENT_CONFIG_GC_TIME,
    retry: false,
    meta: { noGlobalError: true },
  });
}