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.

6.1 KB
Raw Blame
import debug from 'debug';
import { useCallback, useSyncExternalStore } from 'react';

import { useChatStore } from '@/store/chat';
import {
  getPendingSandboxSelection,
  setPendingSandboxSelection,
  subscribePendingSandboxSelection,
} from '@/store/chat/pendingSandboxSelection';
import { topicSelectors } from '@/store/chat/selectors';

const log = debug('lobe-client:sandbox:placement');

/**
 * Where a conversation's cloud sandbox works, and what it starts from. Nothing
 * chosen is a temporary sandbox; choosing a folder IS the choice to keep files:
 *
 * - `workingDirectory` β€” a folder on the drive, relative to its root (`.` is
 *   the root itself);
 * - `environmentId` β€” a code environment to initialize the working directory
 *   from: its repository cloned and its setup run once there, whether that is
 *   a temporary sandbox or a folder on the drive. Independent of the folder;
 *   either can be set without the other.
 * - `instanceId` β€” an environment directory from before environments became
 *   one-time initializers. Read so an old conversation still shows where it
 *   runs; never written, and any new pick clears it.
 *
 * In a workspace, `drive` says which drive the folder is on β€” the public one
 * every member shares, or the member's personal one β€” and absent means public.
 */
export interface SandboxSelection {
  drive?: 'personal' | 'public';
  environmentId?: string;
  instanceId?: string;
  workingDirectory?: string;
}

/** Whether a selection keeps anything β€” a folder, or a legacy environment directory. */
export const isPersistentSelection = (selection: SandboxSelection) =>
  !!selection.instanceId || selection.workingDirectory !== undefined;

/**
 * What the current conversation's cloud sandbox keeps, read and written from
 * one place β€” the composer's chip and the working panel's file tree must see
 * the same state, or a pick in one would not move the other.
 *
 * Before a topic exists the choice is buffered by agent and carried by the
 * first send; see `pendingSandboxSelection`.
 *
 * `scopeTopicId` is the conversation the caller belongs to; `null` means it has
 * no topic yet. Omitted, it follows the global active topic.
 */
export const useSandboxPlacement = (agentId: string, scopeTopicId?: string | null) => {
  const activeTopicId = useChatStore((s) => s.activeTopicId);
  const topicId = scopeTopicId === undefined ? activeTopicId : scopeTopicId;
  const topicMetadata = useChatStore((s) =>
    topicId ? topicSelectors.getTopicById(topicId)(s)?.metadata : undefined,
  );
  // The project the conversation belongs to: the topic's, or β€” before a topic
  // exists β€” the blank draft a project sidebar "+" staged for this agent. A
  // first send mints the topic and drops the draft before this pane moves to
  // it, so for that moment the topic being created names the project: the
  // composer would otherwise read as outside it and re-seed its default just
  // as the send reads it.
  const projectId = useChatStore((s) => {
    if (topicId) return topicSelectors.getTopicById(topicId)(s)?.projectId ?? undefined;
    if (s.pendingNewTopicDirectory?.agentId === agentId)
      return s.pendingNewTopicDirectory.projectId;
    for (const creatingId of s.creatingTopicIds) {
      const creating = topicSelectors.getTopicById(creatingId)(s);
      if (creating?.sessionId === agentId && creating.projectId) return creating.projectId;
    }
    return undefined;
  });
  // A conversation no loaded list holds β€” a project conversation opened right
  // after the project home created it β€” is read by id, or the chip would show
  // a temporary sandbox while the topic works in a repository.
  const isUnlisted = useChatStore((s) => !!topicId && !topicSelectors.getTopicById(topicId)(s));
  useChatStore((s) => s.useFetchTopicDetail)(isUnlisted ? topicId : undefined);
  const refreshTopicDetail = useChatStore((s) => s.refreshTopicDetail);
  const topicInstanceId = topicMetadata?.sandboxInstanceId;
  const topicWorkingDirectory = topicMetadata?.sandboxWorkingDirectory;
  const topicDrive = topicMetadata?.sandboxDrive;
  const topicEnvironmentId = topicMetadata?.sandboxEnvironmentId;
  const updateTopicMetadata = useChatStore((s) => s.updateTopicMetadata);
  // The pending value lives outside React, so this subscribes to it the way a
  // store would be subscribed to. Every component using this hook re-renders
  // on a write, not just the one that wrote.
  const pending = useSyncExternalStore(subscribePendingSandboxSelection, () =>
    getPendingSandboxSelection(agentId),
  );

  const selection: SandboxSelection = topicId
    ? {
        drive: topicDrive,
        environmentId: topicEnvironmentId,
        instanceId: topicInstanceId,
        workingDirectory: topicWorkingDirectory,
      }
    : (pending ?? {});

  const setSelection = useCallback(
    async (next: SandboxSelection) => {
      if (!topicId) {
        setPendingSandboxSelection(agentId, next);
        return;
      }

      // Written whole, every field every time: a stale half left behind would
      // come back the moment the other was cleared. A legacy environment
      // directory is only ever carried forward as it was, never chosen anew.
      await updateTopicMetadata(topicId, {
        sandboxDrive: isPersistentSelection(next) ? next.drive : undefined,
        sandboxEnvironmentId: next.environmentId,
        sandboxInstanceId: next.instanceId,
        sandboxWorkingDirectory: next.instanceId ? undefined : next.workingDirectory,
      });
      // Written straight to the server when no list holds the topic; read it
      // back so the pick shows rather than looking ignored until a reload.
      // The save itself has landed by now; a failed read-back only delays
      // the chip showing it, and must not make the pick look failed.
      if (isUnlisted) {
        try {
          await refreshTopicDetail(topicId, true);
        } catch (error) {
          log('Failed to read back topic %s after a sandbox pick: %O', topicId, error);
        }
      }
    },
    [agentId, isUnlisted, refreshTopicDetail, topicId, updateTopicMetadata],
  );

  return { projectId, selection, setSelection, topicId: topicId ?? undefined };
};