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.

19.2 KB
Raw Blame
import type { WorkingDirConfig, WorkingDirEntry } from '@lobechat/types';
import { getWorkingDirEffectivePath, getWorkingDirSourcePath } from '@lobechat/types';
import { confirmModal } from '@lobehub/ui';
import { useCallback } from 'react';
import { useTranslation } from 'react-i18next';

import { resolveTargetDeviceId } from '@/helpers/agentWorkingDirectory';
import { getHeteroSessionIdForWorkingDirectory } from '@/helpers/heteroSessionByWorkingDirectory';
import { useEffectiveAgencyConfig } from '@/hooks/useEffectiveAgencyConfig';
import { useAgentStore } from '@/store/agent';
import { agentByIdSelectors } from '@/store/agent/selectors';
import { useChatStore } from '@/store/chat';
import { topicSelectors } from '@/store/chat/selectors';
import { useDeviceStore } from '@/store/device';
import { getElectronStoreState, useElectronStore } from '@/store/electron';

import { stagedProjectDirectoryIdSelector } from './useProjectTopicDirectory';

export interface CommitWorkingDirectoryOptions extends CommitAgentDefaultOptions {
  /**
   * Persist against the `local` execution target on this machine, regardless of
   * what the agent's config currently says. For callers that select the local
   * target as part of the same action β€” the resolved config still describes the
   * previous target at that point, and selecting first does not re-render in
   * time to help.
   */
  localTarget?: boolean;
}

export interface CommitAgentDefaultOptions {
  /**
   * Reject when persisting the shared agent config fails. The store otherwise
   * swallows the error (and rolls the optimistic value back), so a caller that
   * acts on the saved directory right after β€” e.g. switching to a fresh topic β€”
   * must opt in to learn the write never landed.
   */
  rethrow?: boolean;
  /** Keep the store's generic save-failure toast. @default true */
  showErrorMessage?: boolean;
}

const normalizeWorkingDirEntry = (entry: WorkingDirEntry): WorkingDirEntry | undefined => {
  const path = entry.path.trim();
  if (!path) return undefined;

  const activeWorktree = entry.git?.activeWorktree?.trim();
  const branch = entry.git?.branch?.trim();
  const next: WorkingDirEntry = { ...entry, path };

  if (entry.git) {
    const git = { ...entry.git };
    if (activeWorktree) git.activeWorktree = activeWorktree;
    else delete git.activeWorktree;

    if (branch) git.branch = branch;
    else delete git.branch;

    if (Object.keys(git).length > 0) next.git = git;
    else delete next.git;
  }

  return next;
};

const toAgentWorkingDirConfig = (entry: WorkingDirEntry): WorkingDirConfig => ({
  // Metadata only: the code environment the folder was picked with. Nothing
  // runs it on a device yet; it travels so the association is not lost.
  ...(entry.environmentId ? { environmentId: entry.environmentId } : {}),
  ...(entry.git ? { git: entry.git } : {}),
  path: entry.path,
  ...(entry.repoType ? { repoType: entry.repoType } : {}),
});

/**
 * Unified working-directory writes, shared by the directory picker for both
 * local and remote runs.
 *
 * **Set** rules:
 * - **active topic**     β†’ `topic.metadata.workingDirectory` (per-topic override)
 * - **no topic yet**     β†’ `agencyConfig.workingDirByDevice[targetDeviceId]`
 * - **always**           β†’ upsert the target device's `workingDirs` recent list
 *
 * **Clear** cascades to whichever precedence level currently supplies the cwd
 * (topic override first, then the agent-level default), instead of only the
 * active topic. Built-in agents never bake the cwd into the topic the way the
 * hetero flow does (see `conversationLifecycle` newTopic metadata), so a
 * topic-only clear would leave the agent-level value re-supplying the directory
 * and Clear would look dead.
 *
 * Changing a topic's cwd invalidates its pinned CC session (sessions are keyed
 * per-cwd), so warn before the reset and clear the stale session id as part of
 * the same metadata write β€” same as the legacy pickers.
 */
export const useCommitWorkingDirectory = (agentId: string, routeTopicId?: string | null) => {
  const { t } = useTranslation(['plugin', 'chat', 'project']);

  // The RAW shared config identifies agent-owned state. Directory writes patch
  // only their target device, never the member's effective device override.
  const agencyConfig = useAgentStore(agentByIdSelectors.getAgencyConfigById(agentId));
  // The EFFECTIVE config (override merged) β€” only for resolving
  // which device the cwd write should target, keeping it on the same machine
  // the picker/GitStatus/`useEffectiveWorkingDirectory` operate on.
  const {
    agencyConfig: effectiveAgencyConfig,
    isPreferenceLoading,
    workspaceScoped,
  } = useEffectiveAgencyConfig(agentId, { topicId: routeTopicId });
  // Heterogeneous CLI agents (Claude Code, Codex, …) store sessions per-cwd, so
  // their session cwd anchors to the SOURCE repo β€” a worktree switch (same repo,
  // different activeWorktree) must NOT change the session cwd or reset the
  // session. Non-hetero agents keep running in the effective (worktree) cwd.
  const isHetero = !!agencyConfig?.heterogeneousProvider;
  const updateAgentConfigById = useAgentStore((s) => s.updateAgentConfigById);
  const updateAgentRuntimeEnvConfigById = useAgentStore((s) => s.updateAgentRuntimeEnvConfigById);
  const legacyAgentWorkingDirectory = useAgentStore(
    (s) => s.localAgentWorkingDirectoryMap[agentId],
  );

  const globalActiveTopicId = useChatStore((s) => s.activeTopicId);
  const activeTopicId = routeTopicId === undefined ? globalActiveTopicId : routeTopicId;
  const activeTopic = useChatStore((s) =>
    activeTopicId ? topicSelectors.getTopicById(activeTopicId)(s) : undefined,
  );
  // A blank conversation staged in a project directory has no topic to record
  // a pick on, and the agent default is not where it will run.
  const stagedDirectoryId = useChatStore(stagedProjectDirectoryIdSelector(agentId, activeTopicId));
  const updateTopicMetadata = useChatStore((s) => s.updateTopicMetadata);

  const updateDeviceCwd = useDeviceStore((s) => s.updateDeviceCwd);
  const currentDeviceId = useElectronStore((s) => s.gatewayDeviceInfo?.deviceId);
  const targetDeviceId = resolveTargetDeviceId(effectiveAgencyConfig, currentDeviceId, {
    workspaceScoped,
  });

  // A workspace agent resolving to THIS member's personal machine (a `local`
  // override) must not persist its cwd into the workspace-shared
  // `agents.agencyConfig.workingDirByDevice` β€” that would leak the member's
  // personal device id and an absolute local path to every other member. Route
  // those writes to the per-user legacy slot instead (a `local` pick only
  // exists on desktop, where that slot works). Workspace-pool devices keep the
  // shared per-device map: the path lives on a machine the workspace shares.
  const isWorkspaceAgent = useAgentStore((s) => Boolean(s.agentMap[agentId]?.workspaceId));
  // A `local` target always denotes the member's own machine β€” its
  // `boundDeviceId` is that machine's personal gateway id even when viewed
  // from web (`currentDeviceId` undefined there, so an id-equality check alone
  // would miss it). The equality arm still covers a desktop default target
  // (no stored target β†’ `resolveTargetDeviceId` falls back to this machine).
  const isPersonalDeviceTarget =
    isWorkspaceAgent &&
    !workspaceScoped &&
    !!targetDeviceId &&
    (effectiveAgencyConfig?.executionTarget === 'local' || targetDeviceId === currentDeviceId);

  const writeCwd = useCallback(
    async (entry?: WorkingDirEntry, options?: CommitWorkingDirectoryOptions) => {
      // A caller that is *about to* select the local target cannot rely on the
      // resolved config yet: this callback closes over the config as it is now,
      // and selecting first would not re-render in time either. `localTarget`
      // lets it state the destination it is creating, so the cwd lands in the
      // same slot the pending `local` pick will read from.
      const localTarget = options?.localTarget === true;
      const writeDeviceId = localTarget
        ? currentDeviceId
        : (targetDeviceId ??
          activeTopic?.metadata?.boundDeviceId ??
          (entry && activeTopicId
            ? await getElectronStoreState().resolveGatewayDeviceId()
            : undefined));
      // A `local` pick on a workspace agent always means this member's own
      // machine, which routes to the per-user slot rather than the shared row.
      const writePersonalSlot = localTarget
        ? isWorkspaceAgent && !!currentDeviceId
        : isPersonalDeviceTarget;
      const effectivePath = getWorkingDirEffectivePath(entry);
      // The session cwd anchors to the source repo for hetero (stable across
      // worktree switches) and to the effective/worktree path otherwise.
      const sessionCwd = isHetero ? getWorkingDirSourcePath(entry) : effectivePath;
      // Save the reusable device entry before changing the selection. A failed
      // recent-directory write must not leave a chip that looks successfully saved.
      if (entry && effectivePath && writeDeviceId) {
        await updateDeviceCwd(writeDeviceId, entry, { setDefault: false });
      }
      // Topic override wins once a conversation exists; otherwise persist the
      // agent's per-device choice so a new topic inherits it.
      if (activeTopicId) {
        const priorSessionCwd = isHetero
          ? (getWorkingDirSourcePath(activeTopic?.metadata?.workingDirectoryConfig) ??
            activeTopic?.metadata?.workingDirectory)
          : activeTopic?.metadata?.workingDirectory;
        const scopedHeteroSessionId = getHeteroSessionIdForWorkingDirectory(
          activeTopic?.metadata,
          sessionCwd,
        );
        // Only a change of session cwd (repo for hetero) invalidates the session;
        // a worktree switch within the same repo keeps it.
        const shouldUpdateHeteroSession =
          priorSessionCwd !== sessionCwd &&
          (!!activeTopic?.metadata?.heteroSessionId || !!scopedHeteroSessionId);
        await updateTopicMetadata(activeTopicId, {
          // The pin is a bare path that only holds on the machine it was picked
          // for, and the server skips a topic pin whose `boundDeviceId` names a
          // different device. Re-stamp it with every write so a conversation
          // moved to another device keeps the directory just chosen there. An
          // unresolved target keeps the topic's own pin (or this desktop's id)
          // rather than leaving the new path with no machine at all.
          boundDeviceId: entry ? writeDeviceId : undefined,
          ...(shouldUpdateHeteroSession ? { heteroSessionId: scopedHeteroSessionId } : {}),
          workingDirectory: sessionCwd,
          workingDirectoryConfig: entry ? toAgentWorkingDirConfig(entry) : undefined,
        });
      } else {
        if (writeDeviceId && writePersonalSlot) {
          // Per-user slot (see `isPersonalDeviceTarget`) β€” never the shared row.
          // The legacy slot stores a plain path, so persist the SESSION cwd
          // (source repo for hetero β€” anchoring a CLI session to a worktree
          // path would break resume; effective path otherwise). The worktree
          // pick itself is carried by topic metadata once a conversation
          // starts; full-fidelity pre-topic persistence needs a per-user
          // server-side slot (deferred).
          await updateAgentRuntimeEnvConfigById(agentId, {
            workingDirectory: sessionCwd || undefined,
          });
        } else if (writeDeviceId) {
          await updateAgentConfigById(
            agentId,
            {
              agencyConfig: {
                workingDirByDevice: {
                  [writeDeviceId]: entry ? toAgentWorkingDirConfig(entry) : undefined,
                },
              },
            },
            {
              replaceWorkingDirDeviceIds: [writeDeviceId],
              rethrow: options?.rethrow,
              showErrorMessage: options?.showErrorMessage,
            },
          );
        }
        // Clearing the agent default must also drop the legacy per-agent value β€”
        // otherwise it keeps re-supplying a stale cwd from a lower precedence
        // level and Clear looks dead. (Only clears the localStorage map; no
        // network round-trip since `workingDirectory` is stripped before send.)
        // The personal-device branch above already wrote that same slot.
        if (!writePersonalSlot && !effectivePath && legacyAgentWorkingDirectory) {
          await updateAgentRuntimeEnvConfigById(agentId, { workingDirectory: undefined });
        }
      }
    },
    [
      agentId,
      activeTopic,
      activeTopicId,
      currentDeviceId,
      isHetero,
      isPersonalDeviceTarget,
      targetDeviceId,
      legacyAgentWorkingDirectory,
      updateAgentConfigById,
      updateAgentRuntimeEnvConfigById,
      updateTopicMetadata,
      updateDeviceCwd,
    ],
  );

  // Clear whichever precedence level currently supplies the cwd, so the picker
  // falls back to the next level (agent default β†’ device default β†’ "not set").
  const clearCwd = useCallback(async () => {
    if (activeTopic?.projectWorkingDirectoryId)
      throw new Error(t('directories.boundRoot', { ns: 'project' }));
    // A topic override (when present) is the effective source β€” drop it first so
    // we fall back to the agent default rather than nuking everything.
    if (activeTopicId && activeTopic?.metadata?.workingDirectory) {
      await updateTopicMetadata(activeTopicId, {
        // No pin left, so no device it belongs to β€” the next run stamps its own.
        boundDeviceId: undefined,
        ...(activeTopic.metadata.heteroSessionId ? { heteroSessionId: undefined } : {}),
        workingDirectory: undefined,
        workingDirectoryConfig: undefined,
      });
      return;
    }
    // No topic override: clear the agent-level default(s). An explicit
    // `undefined` entry carries deletion through the client and server. The user
    // can't tell the
    // per-device map from the legacy slot, so clear both together to avoid a
    // dead second click.
    if (targetDeviceId && agencyConfig?.workingDirByDevice?.[targetDeviceId]) {
      await updateAgentConfigById(
        agentId,
        { agencyConfig: { workingDirByDevice: { [targetDeviceId]: undefined } } },
        { replaceWorkingDirDeviceIds: [targetDeviceId] },
      );
    }
    // (Only clears the localStorage map; no network round-trip since
    // `workingDirectory` is stripped before send.)
    if (legacyAgentWorkingDirectory) {
      await updateAgentRuntimeEnvConfigById(agentId, { workingDirectory: undefined });
    }
  }, [
    agentId,
    agencyConfig,
    activeTopic,
    activeTopicId,
    targetDeviceId,
    legacyAgentWorkingDirectory,
    updateAgentConfigById,
    updateAgentRuntimeEnvConfigById,
    updateTopicMetadata,
    t,
  ]);

  /** Pick a directory (with the CC-session-reset guard). */
  const commit = useCallback(
    async (entry: WorkingDirEntry, options?: CommitWorkingDirectoryOptions) => {
      const normalizedEntry = normalizeWorkingDirEntry(entry);
      const effectivePath = getWorkingDirEffectivePath(normalizedEntry);
      if (!normalizedEntry || !effectivePath) return;

      if (stagedDirectoryId) throw new Error(t('directories.boundRoot', { ns: 'project' }));
      if (activeTopic?.projectWorkingDirectoryId) {
        const source = getWorkingDirSourcePath(
          activeTopic.metadata?.workingDirectoryConfig ?? activeTopic.metadata?.workingDirectory,
        );
        if (getWorkingDirSourcePath(normalizedEntry) !== source)
          throw new Error(t('directories.boundRoot', { ns: 'project' }));
      }
      const run = () => writeCwd(normalizedEntry, options);

      // Warn about losing the CLI session only when the SESSION cwd changes.
      // For hetero that's the source repo β€” a worktree switch within the same
      // repo keeps the session, so it must not trigger the reset warning.
      const priorSessionId = activeTopic?.metadata?.heteroSessionId;
      const sessionCwd = isHetero ? getWorkingDirSourcePath(normalizedEntry) : effectivePath;
      const priorSessionCwd = isHetero
        ? (getWorkingDirSourcePath(activeTopic?.metadata?.workingDirectoryConfig) ??
          activeTopic?.metadata?.workingDirectory)
        : activeTopic?.metadata?.workingDirectory;
      if (priorSessionId && priorSessionCwd && priorSessionCwd !== sessionCwd) {
        confirmModal({
          cancelText: t('heteroAgent.switchCwd.cancel', { ns: 'chat' }),
          content: t('heteroAgent.switchCwd.content', { ns: 'chat' }),
          okText: t('heteroAgent.switchCwd.ok', { ns: 'chat' }),
          onOk: run,
          title: t('heteroAgent.switchCwd.title', { ns: 'chat' }),
        });
        return;
      }
      await run();
    },
    [activeTopic, isHetero, stagedDirectoryId, t, writeCwd],
  );

  /**
   * Set the agent's per-device default cwd, ignoring any active topic. Used by
   * the sidebar "new topic in this directory" (+) action, which always targets
   * a fresh topic regardless of what conversation is currently open β€” so it must
   * write the same high-precedence slot the picker uses for new topics
   * (`workingDirByDevice`), not the legacy per-agent fallback. The new topic
   * bakes this value into its own `metadata.workingDirectory` on first send.
   */
  const commitAgentDefault = useCallback(
    async (newPath: string, options?: CommitAgentDefaultOptions) => {
      const path = newPath.trim();
      if (!path) return;
      if (targetDeviceId && !isPersonalDeviceTarget) {
        await updateAgentConfigById(
          agentId,
          {
            agencyConfig: {
              workingDirByDevice: { [targetDeviceId]: path },
            },
          },
          { ...options, replaceWorkingDirDeviceIds: [targetDeviceId] },
        );
      } else {
        // No resolvable device (e.g. gateway id unavailable), or a workspace
        // agent targeting this member's own machine (`isPersonalDeviceTarget`,
        // which must never persist into the shared row) β€” fall back to the
        // per-user legacy slot so the action still takes effect.
        await updateAgentRuntimeEnvConfigById(agentId, { workingDirectory: path });
      }
    },
    [
      agentId,
      isPersonalDeviceTarget,
      targetDeviceId,
      updateAgentConfigById,
      updateAgentRuntimeEnvConfigById,
    ],
  );

  /** Clear the current selection (falls back to the next precedence level). */
  const clear = useCallback(async () => {
    const run = () => clearCwd();

    const priorSessionId = activeTopic?.metadata?.heteroSessionId;
    const priorCwd = activeTopic?.metadata?.workingDirectory;
    if (priorSessionId && priorCwd) {
      confirmModal({
        cancelText: t('heteroAgent.switchCwd.cancel', { ns: 'chat' }),
        content: t('heteroAgent.switchCwd.content', { ns: 'chat' }),
        okText: t('heteroAgent.switchCwd.ok', { ns: 'chat' }),
        onOk: run,
        title: t('heteroAgent.switchCwd.title', { ns: 'chat' }),
      });
      return;
    }
    await run();
  }, [activeTopic, t, clearCwd]);

  return {
    clear,
    commit,
    commitAgentDefault,
    /**
     * A workspace agent's device routing (shared row vs. this member's personal
     * slot) is still resolving. Writers should wait: acting now can file a local
     * path under the shared device instead of the member's own slot.
     */
    isPreferenceLoading,
  };
};