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.

8.0 KB
Raw Blame
import type { ChatTopicMetadata } from '@lobechat/types';
import debug from 'debug';

import type { SandboxSelection } from '@/features/ChatInput/ControlBar/useSandboxPlacement';
import { sandboxStorageService } from '@/services/sandboxStorage';
import { sandboxSelectors, useSandboxStore } from '@/store/sandbox';

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

/**
 * Module-level singleton for a sandbox selection made before the topic exists.
 *
 * The composer's picker is offered on a conversation that has not been created
 * yet, so there is nothing to write the choice to. Buffering it here keyed by
 * agentId lets the first send carry it: `conversationLifecycle` reads it into
 * the optimistic topic's metadata and `gateway.ts` sends it as
 * `initialTopicMetadata`, so the SERVER topic is born with it.
 *
 * Deliberately not the agent's `agencyConfig`, which is where the device picker
 * keeps its equivalent pre-topic choice. That row is shared by every member of a
 * workspace agent, while a folder choice belongs to one member β€” writing it there
 * would point other members at storage that is not theirs.
 *
 * Deliberately not persisted either: this is a choice about the conversation
 * being started right now, and a reload before the first message is a new start.
 *
 * Shaped after `pendingTopicRepos`, which solves the same problem for GitHub
 * repositories. Kept separate rather than generalized so that path, which
 * already works, is not disturbed.
 */

const map = new Map<string, SandboxSelection>();

// More than one component reads this β€” the execution-device switch and the
// working-directory chip β€” and a Map cannot tell React that it changed. A
// write notifies every subscriber, so a flip in one place moves the other;
// without this, whichever component did not do the writing kept rendering the
// old value until something unrelated re-rendered it.
const listeners = new Set<() => void>();

const emit = () => {
  for (const listener of listeners) listener();
};

/** Subscribe to writes; returns the unsubscribe. Shaped for `useSyncExternalStore`. */
export const subscribePendingSandboxSelection = (listener: () => void): (() => void) => {
  listeners.add(listener);
  return () => {
    listeners.delete(listener);
  };
};

/** Record the pending selection for an agent; `undefined` clears it. */
export const setPendingSandboxSelection = (agentId: string, selection?: SandboxSelection): void => {
  if (selection) map.set(agentId, selection);
  else map.delete(agentId);
  emit();
};

/**
 * Selections the composer filled in itself rather than the person choosing
 * them: the plan's default placement. Kept by identity, so a pick β€” always a
 * new object β€” is never mistaken for one. The server needs the difference: a
 * project conversation started on the default is given the project's
 * repository checkout instead, while one the person placed keeps their choice.
 */
const seeded = new WeakSet<SandboxSelection>();

/** Whether a selection is the composer's default rather than anyone's pick. */
export const isSeededSandboxSelection = (selection: SandboxSelection): boolean =>
  seeded.has(selection);

/** Fill an agent's empty slot with the default placement, marked as not chosen by anyone. */
export const seedPendingSandboxSelection = (agentId: string, selection: SandboxSelection): void => {
  seeded.add(selection);
  setPendingSandboxSelection(agentId, selection);
};

/**
 * The place an agent's next conversation starts when nobody picks one, and
 * the plan turns out to include a drive. Registered by the composer as soon as
 * it knows the agent runs in the sandbox β€” before the entitlement has loaded β€”
 * so a message sent while that request is still in flight is not born without
 * a folder. Kept apart from the pending pick: it is a candidate, and only
 * becomes the pick once the entitlement is confirmed.
 */
const defaults = new Map<string, SandboxSelection>();

/** Register an agent's default placement; `undefined` clears it. */
export const setSandboxDefaultSelection = (agentId: string, selection?: SandboxSelection): void => {
  if (selection) seeded.add(selection);
  if (selection) defaults.set(agentId, selection);
  else defaults.delete(agentId);
};

/**
 * Where an agent's next conversation starts when it runs in the temporary
 * sandbox β€” the repository its last temporary sandbox used. Registered beside
 * the drive default so a first send made before the entitlement is known
 * still carries it once the plan turns out to have no drive.
 */
const temporaryDefaults = new Map<string, SandboxSelection>();

/** Register an agent's temporary-sandbox default; `undefined` clears it. */
export const setSandboxTemporaryDefaultSelection = (
  agentId: string,
  selection?: SandboxSelection,
): void => {
  if (selection) seeded.add(selection);
  if (selection) temporaryDefaults.set(agentId, selection);
  else temporaryDefaults.delete(agentId);
};

/**
 * Whether the active workspace's plan includes a drive. A cached yes is taken
 * as is; a cached no is confirmed with the server first, because the cache is
 * persisted β€” an account that has just upgraded still reads no until its
 * revalidation lands, and its first conversation would otherwise lose the
 * drive. A failed lookup reads as no β€” the run goes to the temporary sandbox,
 * as it would have anyway.
 */
const isDriveEntitled = async (): Promise<boolean> => {
  const cached = sandboxSelectors.entitlement(useSandboxStore.getState());
  if (cached?.entitled) return true;

  try {
    return (await sandboxStorageService.getEntitlement()).entitled;
  } catch (error) {
    log('Failed to resolve the drive entitlement for a first send: %O', error);
    return false;
  }
};

/**
 * The selection the first send carries: the pick, if one was made; otherwise
 * the registered drive default, once the plan is confirmed to include a drive;
 * otherwise the registered temporary-sandbox default. That default then
 * becomes the pick, so every later reader of this send sees it.
 */
export const resolvePendingSandboxSelection = async (
  agentId: string,
): Promise<SandboxSelection | undefined> => {
  const picked = map.get(agentId);
  if (picked) return picked;

  const drive = defaults.get(agentId);
  const fallback = drive && (await isDriveEntitled()) ? drive : temporaryDefaults.get(agentId);
  if (!fallback) return map.get(agentId);

  // A pick made while the entitlement was in flight wins over the default.
  if (!map.has(agentId)) setPendingSandboxSelection(agentId, fallback);

  return map.get(agentId);
};

/** Read without consuming β€” what the closed chip names itself after. */
export const getPendingSandboxSelection = (agentId: string): SandboxSelection | undefined =>
  map.get(agentId);

/**
 * Consume the pending selection for an agent. Cleared so the NEXT conversation
 * starts at the default: the choice was made for the topic that has now been
 * created, and carrying it forward would silently bind conversations nobody
 * chose it for.
 */
export const consumePendingSandboxSelection = (agentId: string): SandboxSelection | undefined => {
  const selection = map.get(agentId);
  map.delete(agentId);
  emit();
  return selection;
};

/**
 * The topic metadata a pending selection becomes when the topic is created with
 * it. An empty selection is the temporary sandbox picked on purpose, and says so:
 * otherwise it would arrive as nothing picked, and a project conversation would
 * be given the project's checkout instead. A default nobody picked says that
 * too, so the project's checkout can take its place.
 */
export const toSandboxTopicMetadata = (
  selection: SandboxSelection | undefined,
): ChatTopicMetadata | undefined =>
  selection && {
    sandboxDrive: selection.drive,
    sandboxEnvironmentId: selection.environmentId,
    sandboxInstanceId: selection.instanceId,
    sandboxWorkingDirectory: selection.workingDirectory,
    ...(seeded.has(selection) && { sandboxSeeded: true }),
    ...(!selection.environmentId &&
      !selection.instanceId &&
      selection.workingDirectory === undefined && { sandboxTemporary: true }),
  };