Skip to content

🤯 LobeHub - Super-Agents on Your Team. Add super-agents to the chats your team already uses.They take on work by themselves and get better every week.

3.0 KB
Raw Blame
import type { Dispatch, SetStateAction } from 'react';
import { useEffect } from 'react';

import { useEffectiveAgencyConfig } from '@/hooks/useEffectiveAgencyConfig';
import { useAgentStore } from '@/store/agent';
import type { DeviceListResult } from '@/store/device/useDeviceList';

import type {
  ChannelAgentDraft,
  ChannelAgentEnvironment,
  ChannelAgentIssue,
  ChannelAgentIssueOptions,
} from './agentEnvironment';
import {
  changeChannelAgentDevice,
  getChannelAgentIssue,
  isRemoteChannelAgent,
  reconcileChannelAgentDraft,
} from './agentEnvironment';

export const useChannelAgentDraft = (
  draft: ChannelAgentDraft,
  devices: DeviceListResult,
  setDrafts: Dispatch<SetStateAction<ChannelAgentDraft[]>>,
  options?: ChannelAgentIssueOptions,
) => {
  const { agentId } = draft;
  const sync = useAgentStore((s) => s.useHydrateAgentConfig)(true, agentId);
  const agent = useAgentStore((s) => s.agentMap[agentId]);
  const confirmed = useAgentStore(
    (s) => s.agentConfigReplica.entries[agentId]?.source === 'server',
  );
  const notFound = useAgentStore((s) => s.agentNotFoundMap[agentId]);
  const { agencyConfig, isPreferenceLoading } = useEffectiveAgencyConfig(agentId, {
    topicId: null,
  });
  const environment: ChannelAgentEnvironment = {
    agencyConfig,
    devices: devices.data,
    devicesConfirmed: devices.isConfirmed,
    devicesError: devices.error,
    model: agent?.model ?? undefined,
  };
  const sourceIssue: ChannelAgentIssue | undefined = sync.error
    ? 'configurationFailed'
    : notFound
      ? 'agentUnavailable'
      : !confirmed || !agent || isPreferenceLoading
        ? 'configurationLoading'
        : undefined;
  const resolved = reconcileChannelAgentDraft(draft, environment, sourceIssue, options);

  // This is a form snapshot, not another fetch/cache. Removing and re-adding an
  // Agent creates a new draft; an effect from its previous mount cannot overwrite it.
  useEffect(() => {
    if (resolved === draft) return;
    setDrafts((current) => current.map((item) => (item === draft ? resolved : item)));
  }, [draft, resolved, setDrafts]);

  const change = (patch: Partial<Pick<ChannelAgentDraft, 'deviceId' | 'workingDirectory'>>) => {
    setDrafts((current) =>
      current.map((item) => {
        if (item.agentId !== agentId) return item;
        const next =
          'deviceId' in patch
            ? { ...item, ...changeChannelAgentDevice(item, patch.deviceId, environment) }
            : { ...item, ...patch };
        return { ...next, issue: getChannelAgentIssue(next, environment, options) };
      }),
    );
  };

  const changeDevice = (deviceId: unknown) => {
    // Select emits undefined (not '') for its empty option. Clearing is an explicit
    // channel-local override and must clear the directory as well.
    if (deviceId === undefined || deviceId === null || typeof deviceId === 'string')
      change({ deviceId: deviceId || undefined });
  };

  return {
    change,
    changeDevice,
    draft: resolved,
    remote: isRemoteChannelAgent(environment),
    retry: sync.mutate,
    sync,
  };
};