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.

2.9 KB
Raw Blame
import useSWR from 'swr';

import { gatewayKeys } from '@/libs/swr/keys';
import { useChatStore } from '@/store/chat';
import { useServerConfigStore } from '@/store/serverConfig';
import { isTrpcErrorCode } from '@/utils/trpcError';

interface RunningOperation {
  assistantMessageId: string;
  heteroType?: string | null;
  operationId: string;
  scope?: string;
  startedAt?: string;
  threadId?: string | null;
}

/**
 * Auto-reconnect to a running Gateway operation on the given topic.
 *
 * The caller sources `runningOperation` itself β€” the chat-store topic map
 * (main agent) and the task-detail activity (task drawer) live in different
 * stores, so this hook stays source-agnostic.
 *
 * Reconnect only depends on whether the server has a Gateway URL configured;
 * the user's lab toggle controls *new* requests, not resuming an op that's
 * already running on the Gateway.
 *
 * SWR key is the operationId, so the same operation deduplicates and only
 * one reconnect attempt fires per op.
 */
export const useGatewayReconnect = (
  topicId: string | null | undefined,
  runningOperation: RunningOperation | null | undefined,
  /**
   * Agent owning the rendered conversation. Required off the agent route (task
   * detail / home run drawer), where the chat store's `activeAgentId` is stale or
   * unset β€” see `reconnectToGatewayOperation`.
   */
  agentId?: string,
  /**
   * Present on the agent-share visitor surface. Routes the reconnect's token
   * refresh and cancellation through the share-authorized `shareChat`
   * procedures instead of the owner-scoped ones β€” see
   * `reconnectToGatewayOperation`'s param JSDoc.
   */
  agentShareId?: string,
) => {
  const agentGatewayUrl = useServerConfigStore((s) => s.serverConfig.agentGatewayUrl);

  useSWR(
    runningOperation && topicId && agentGatewayUrl
      ? gatewayKeys.reconnect(runningOperation.operationId)
      : null,
    async () => {
      if (!runningOperation || !topicId) return;

      await useChatStore.getState().reconnectToGatewayOperation({
        agentId,
        agentShareId,
        assistantMessageId: runningOperation.assistantMessageId,
        heteroType: runningOperation.heteroType,
        operationId: runningOperation.operationId,
        scope: runningOperation.scope,
        startedAt: runningOperation.startedAt,
        threadId: runningOperation.threadId,
        topicId,
      });
    },
    {
      revalidateIfStale: false,
      revalidateOnFocus: false,
      revalidateOnReconnect: false,
      // Never retry the stale-marker case (operation already gone β†’ NOT_FOUND) or a
      // teammate's run the gateway will not stream to this user (FORBIDDEN), even if
      // either escapes the fetcher-level catch; transient network/server errors keep
      // SWR's default retry so a live run still resumes.
      shouldRetryOnError: (error) =>
        !isTrpcErrorCode(error, 'NOT_FOUND') && !isTrpcErrorCode(error, 'FORBIDDEN'),
    },
  );
};