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.

16.4 KB
Raw Blame
import type { ChatTopic } from '@lobechat/types';
import { renderHook } from '@testing-library/react';
import { beforeEach, describe, expect, it, vi } from 'vitest';

import { useCommitWorkingDirectory } from '../useCommitWorkingDirectory';

const testState = vi.hoisted(() => ({
  agent: {
    agencyConfig: undefined as Record<string, unknown> | undefined,
    agentMap: {} as Record<string, { visibility?: string; workspaceId?: string | null }>,
    localAgentWorkingDirectoryMap: {} as Record<string, string>,
    updateAgentConfigById: vi.fn(),
    updateAgentRuntimeEnvConfigById: vi.fn(),
  },
  chat: {
    activeTopicId: undefined as string | undefined,
    pendingNewTopicDirectory: undefined as
      { agentId: string; projectWorkingDirectoryId: string } | undefined,
    topic: undefined as ChatTopic | undefined,
    updateTopicMetadata: vi.fn(),
  },
  currentDeviceId: 'this-machine' as string | undefined,
  updateDeviceCwd: vi.fn(),
  resolveGatewayDeviceId: vi.fn(async (): Promise<string | undefined> => undefined),
  effective: {
    agencyConfig: undefined as Record<string, unknown> | undefined,
    isPreferenceLoading: false,
    workspaceScoped: false,
  },
}));

vi.mock('@/hooks/useEffectiveAgencyConfig', () => ({
  useEffectiveAgencyConfig: () => testState.effective,
}));

vi.mock('@/store/agent', () => ({
  useAgentStore: (selector: (s: typeof testState.agent) => unknown) => selector(testState.agent),
}));

vi.mock('@/store/agent/selectors', () => ({
  agentByIdSelectors: { getAgencyConfigById: () => (s: typeof testState.agent) => s.agencyConfig },
}));

vi.mock('@/store/chat', () => ({
  useChatStore: (selector: (s: typeof testState.chat) => unknown) => selector(testState.chat),
}));

vi.mock('@/store/chat/selectors', () => ({
  topicSelectors: { getTopicById: () => (s: typeof testState.chat) => s.topic },
}));

vi.mock('@/store/device', () => ({
  useDeviceStore: (selector: (s: { updateDeviceCwd: unknown }) => unknown) =>
    selector({ updateDeviceCwd: testState.updateDeviceCwd }),
}));

vi.mock('@/store/electron', () => ({
  getElectronStoreState: () => ({ resolveGatewayDeviceId: testState.resolveGatewayDeviceId }),
  useElectronStore: (selector: (s: { gatewayDeviceInfo?: { deviceId?: string } }) => unknown) =>
    selector({ gatewayDeviceInfo: { deviceId: testState.currentDeviceId } }),
}));

vi.mock('@/helpers/heteroSessionByWorkingDirectory', () => ({
  getHeteroSessionIdForWorkingDirectory: () => undefined,
}));

describe('useCommitWorkingDirectory — localTarget', () => {
  beforeEach(() => {
    vi.clearAllMocks();
    testState.chat.topic = undefined;
    testState.agent.agencyConfig = undefined;
    testState.agent.agentMap = {};
    testState.agent.localAgentWorkingDirectoryMap = {};
    testState.agent.updateAgentConfigById = vi.fn();
    testState.agent.updateAgentRuntimeEnvConfigById = vi.fn();
    testState.chat.activeTopicId = undefined;
    testState.chat.pendingNewTopicDirectory = undefined;
    testState.chat.topic = undefined;
    testState.chat.updateTopicMetadata = vi.fn();
    testState.currentDeviceId = 'this-machine';
    testState.effective = {
      agencyConfig: undefined,
      isPreferenceLoading: false,
      workspaceScoped: false,
    };
  });

  it('refuses a worktree pick while a blank conversation is staged in a project directory', async () => {
    // No topic yet, so the write would otherwise land on the agent default —
    // a directory this conversation will not run in.
    testState.agent.agencyConfig = { boundDeviceId: 'this-machine', executionTarget: 'device' };
    testState.effective.agencyConfig = testState.agent.agencyConfig;
    testState.chat.pendingNewTopicDirectory = {
      agentId: 'agent-id',
      projectWorkingDirectoryId: 'directory',
    };

    const { result } = renderHook(() => useCommitWorkingDirectory('agent-id'));
    await expect(
      result.current.commit({ path: '/repo', git: { activeWorktree: '/repo-worktree' } }),
    ).rejects.toThrow();

    expect(testState.agent.updateAgentConfigById).not.toHaveBeenCalled();
    expect(testState.agent.updateAgentRuntimeEnvConfigById).not.toHaveBeenCalled();
  });

  it('keeps a project-bound source directory while allowing worktree selection', async () => {
    testState.chat.activeTopicId = 'topic';
    testState.chat.topic = {
      id: 'topic',
      projectWorkingDirectoryId: 'directory',
      metadata: { workingDirectory: '/repo', workingDirectoryConfig: { path: '/repo' } },
    } as ChatTopic;
    const { result } = renderHook(() => useCommitWorkingDirectory('agent-id'));
    await expect(result.current.commit({ path: '/elsewhere' })).rejects.toThrow();
    await expect(result.current.clear()).rejects.toThrow();
    expect(testState.chat.updateTopicMetadata).not.toHaveBeenCalled();
    await result.current.commit({ path: '/repo', git: { activeWorktree: '/repo-worktree' } });
    expect(testState.chat.updateTopicMetadata).toHaveBeenCalled();
  });

  it('files a workspace member’s first sandbox pick against their own machine', async () => {
    // The caller selects `local` as part of the same action, so the config here
    // still describes the previous (workspace-shared) target — and selecting
    // first would not re-render in time. Without `localTarget` the path lands
    // in the shared row or nowhere, and the next command refuses again for
    // want of a working directory.
    testState.agent.agentMap = { 'agent-id': { visibility: 'public', workspaceId: 'ws-1' } };
    testState.effective = {
      agencyConfig: { boundDeviceId: 'shared-device', executionTarget: 'device' },
      isPreferenceLoading: false,
      workspaceScoped: true,
    };

    const { result } = renderHook(() => useCommitWorkingDirectory('agent-id'));
    await result.current.commit(
      { path: 'C:/Users/me/LobeHub/sandbox/agent-id' },
      {
        localTarget: true,
      },
    );

    // Per-user slot — never the workspace-shared row.
    expect(testState.agent.updateAgentRuntimeEnvConfigById).toHaveBeenCalledWith('agent-id', {
      workingDirectory: 'C:/Users/me/LobeHub/sandbox/agent-id',
    });
    expect(testState.agent.updateAgentConfigById).not.toHaveBeenCalled();
  });

  it('keeps a personal agent’s write on this device', async () => {
    const { result } = renderHook(() => useCommitWorkingDirectory('agent-id'));
    await result.current.commit({ path: 'C:/work' }, { localTarget: true });

    expect(testState.agent.updateAgentConfigById).toHaveBeenCalledWith(
      'agent-id',
      { agencyConfig: { workingDirByDevice: { 'this-machine': { path: 'C:/work' } } } },
      { replaceWorkingDirDeviceIds: ['this-machine'] },
    );
  });

  it('records a local pick on this machine instead of the previous remote target', async () => {
    testState.effective.agencyConfig = {
      boundDeviceId: 'other-device',
      executionTarget: 'device',
    };
    const { result } = renderHook(() => useCommitWorkingDirectory('agent-id'));

    await result.current.commit({ path: '/local/repo' }, { localTarget: true });

    expect(testState.updateDeviceCwd).toHaveBeenCalledWith(
      'this-machine',
      { path: '/local/repo' },
      { setDefault: false },
    );
  });

  it('records the picked folder on the same newly resolved device as the topic', async () => {
    testState.currentDeviceId = undefined;
    testState.chat.activeTopicId = 'topic';
    testState.resolveGatewayDeviceId.mockResolvedValueOnce('resolved-device');
    const { result } = renderHook(() => useCommitWorkingDirectory('agent-id'));

    await result.current.commit({ path: '/repo' });

    expect(testState.chat.updateTopicMetadata).toHaveBeenCalledWith(
      'topic',
      expect.objectContaining({ boundDeviceId: 'resolved-device', workingDirectory: '/repo' }),
    );
    expect(testState.updateDeviceCwd).toHaveBeenCalledWith(
      'resolved-device',
      { path: '/repo' },
      { setDefault: false },
    );
  });

  it('keeps the selection unchanged when saving the reusable directory fails', async () => {
    testState.chat.activeTopicId = 'topic';
    testState.updateDeviceCwd.mockRejectedValueOnce(new Error('save failed'));
    const { result } = renderHook(() => useCommitWorkingDirectory('agent-id'));

    await expect(result.current.commit({ path: '/repo' })).rejects.toThrow('save failed');

    expect(testState.chat.updateTopicMetadata).not.toHaveBeenCalled();
    expect(testState.agent.updateAgentConfigById).not.toHaveBeenCalled();
  });

  it('leaves ordinary writes routed by the resolved config', async () => {
    // No override: a `device` target still files against its bound device, so
    // the new option cannot change how the directory picker behaves.
    testState.effective = {
      agencyConfig: { boundDeviceId: 'other-device', executionTarget: 'device' },
      isPreferenceLoading: false,
      workspaceScoped: false,
    };
    testState.agent.agencyConfig = { boundDeviceId: 'other-device', executionTarget: 'device' };

    const { result } = renderHook(() => useCommitWorkingDirectory('agent-id'));
    await result.current.commit({ path: 'C:/work' });

    expect(testState.agent.updateAgentConfigById).toHaveBeenCalledWith(
      'agent-id',
      { agencyConfig: { workingDirByDevice: { 'other-device': { path: 'C:/work' } } } },
      { replaceWorkingDirDeviceIds: ['other-device'] },
    );
  });

  it('writes only the selected device instead of replaying other directory choices', async () => {
    testState.agent.agencyConfig = {
      executionTarget: 'local',
      workingDirByDevice: {
        'this-machine': { git: { activeWorktree: '/titu-worktree' }, path: '/titu' },
        'other-device': '/remote/repo',
      },
    };
    const { result } = renderHook(() => useCommitWorkingDirectory('agent-id'));

    await result.current.commit({ path: '/lobehub', repoType: 'github' });
    expect(testState.agent.updateAgentConfigById).toHaveBeenLastCalledWith(
      'agent-id',
      {
        agencyConfig: {
          workingDirByDevice: { 'this-machine': { path: '/lobehub', repoType: 'github' } },
        },
      },
      { replaceWorkingDirDeviceIds: ['this-machine'] },
    );

    await result.current.clear();
    expect(testState.agent.updateAgentConfigById).toHaveBeenLastCalledWith(
      'agent-id',
      { agencyConfig: { workingDirByDevice: { 'this-machine': undefined } } },
      { replaceWorkingDirDeviceIds: ['this-machine'] },
    );

    await result.current.commitAgentDefault('/plain-folder');
    expect(testState.agent.updateAgentConfigById).toHaveBeenLastCalledWith(
      'agent-id',
      {
        agencyConfig: { workingDirByDevice: { 'this-machine': '/plain-folder' } },
      },
      { replaceWorkingDirDeviceIds: ['this-machine'] },
    );
  });
});

describe('useCommitWorkingDirectory — topic device provenance', () => {
  beforeEach(() => {
    vi.clearAllMocks();
    testState.agent.agencyConfig = { boundDeviceId: 'device-b', executionTarget: 'device' };
    testState.agent.agentMap = {};
    testState.agent.localAgentWorkingDirectoryMap = {};
    testState.chat.activeTopicId = 'topic-id';
    // A conversation first pinned on device A, now running on device B.
    testState.chat.topic = {
      metadata: { boundDeviceId: 'device-a', workingDirectory: '/Users/me/repo-a' },
    } as ChatTopic;
    testState.chat.updateTopicMetadata = vi.fn();
    testState.currentDeviceId = 'this-machine';
    testState.effective = {
      agencyConfig: { boundDeviceId: 'device-b', executionTarget: 'device' },
      isPreferenceLoading: false,
      workspaceScoped: false,
    };
  });

  it('re-stamps the topic device with the directory picked for the new device', async () => {
    // The server only honours a topic pin on the device named by
    // `boundDeviceId`; leaving device A there would make device B skip the
    // directory just chosen for it and fall back to another cwd.
    const { result } = renderHook(() => useCommitWorkingDirectory('agent-id'));
    await result.current.commit({ path: '/home/me/repo-b' });

    expect(testState.chat.updateTopicMetadata).toHaveBeenCalledWith('topic-id', {
      boundDeviceId: 'device-b',
      workingDirectory: '/home/me/repo-b',
      workingDirectoryConfig: { path: '/home/me/repo-b' },
    });
  });

  it('drops the topic device together with a cleared directory', async () => {
    const { result } = renderHook(() => useCommitWorkingDirectory('agent-id'));
    await result.current.clear();

    // Clearing is carried as explicit `undefined` keys (a merge can't drop a
    // key), so the key itself must be present — not merely unset.
    const [topicId, patch] = testState.chat.updateTopicMetadata.mock.calls[0];
    expect(topicId).toBe('topic-id');
    expect(Object.keys(patch).sort()).toEqual([
      'boundDeviceId',
      'workingDirectory',
      'workingDirectoryConfig',
    ]);
    expect(patch.boundDeviceId).toBeUndefined();
  });

  // Regression: an unresolved target wrote the new path with no machine, which
  // erased the topic's pin and left the picker on the agent default.
  it('keeps the topic pin when the target machine cannot be resolved', async () => {
    testState.effective.agencyConfig = { executionTarget: 'device' };
    const { result } = renderHook(() => useCommitWorkingDirectory('agent-id'));
    await result.current.commit({ path: '/Users/me/repo-c' });

    expect(testState.chat.updateTopicMetadata).toHaveBeenCalledWith(
      'topic-id',
      expect.objectContaining({ boundDeviceId: 'device-a', workingDirectory: '/Users/me/repo-c' }),
    );
  });

  it('pins an unbound topic to this desktop when the target cannot be resolved', async () => {
    testState.effective.agencyConfig = { executionTarget: 'device' };
    testState.chat.topic = { metadata: {} } as ChatTopic;
    testState.resolveGatewayDeviceId.mockResolvedValueOnce('this-desktop');
    const { result } = renderHook(() => useCommitWorkingDirectory('agent-id'));
    await result.current.commit({ path: '/Users/me/repo-c' });

    expect(testState.chat.updateTopicMetadata).toHaveBeenCalledWith(
      'topic-id',
      expect.objectContaining({ boundDeviceId: 'this-desktop' }),
    );
  });
});

describe('useCommitWorkingDirectory — commitAgentDefault', () => {
  beforeEach(() => {
    vi.clearAllMocks();
    testState.agent.agencyConfig = undefined;
    testState.agent.agentMap = {};
    testState.agent.localAgentWorkingDirectoryMap = {};
    testState.agent.updateAgentConfigById = vi.fn();
    testState.agent.updateAgentRuntimeEnvConfigById = vi.fn();
    testState.chat.activeTopicId = undefined;
    testState.chat.topic = undefined;
    testState.currentDeviceId = 'this-machine';
    testState.effective = {
      agencyConfig: undefined,
      isPreferenceLoading: false,
      workspaceScoped: false,
    };
  });

  it('forwards save options so callers can observe a failed shared-config write', async () => {
    // The store swallows save failures unless asked to rethrow; a caller that
    // switches topics right after must see the rejection.
    testState.agent.updateAgentConfigById = vi.fn(
      async (_id: string, _patch: unknown, options?: { rethrow?: boolean }) => {
        if (options?.rethrow) throw new Error('save failed');
      },
    );

    const { result } = renderHook(() => useCommitWorkingDirectory('agent-id'));

    await expect(
      result.current.commitAgentDefault('/work', { rethrow: true, showErrorMessage: false }),
    ).rejects.toThrow('save failed');
    expect(testState.agent.updateAgentConfigById).toHaveBeenCalledWith(
      'agent-id',
      { agencyConfig: { workingDirByDevice: { 'this-machine': '/work' } } },
      { replaceWorkingDirDeviceIds: ['this-machine'], rethrow: true, showErrorMessage: false },
    );
  });

  it('rejects a failed folder pick before the caller starts a new topic', async () => {
    testState.agent.updateAgentConfigById = vi.fn(
      async (_id: string, _patch: unknown, options?: { rethrow?: boolean }) => {
        if (options?.rethrow) throw new Error('save failed');
      },
    );
    const { result } = renderHook(() => useCommitWorkingDirectory('agent-id', null));
    const startTopic = vi.fn();

    await expect(
      result.current
        .commit({ path: '/work' }, { rethrow: true, showErrorMessage: false })
        .then(startTopic),
    ).rejects.toThrow('save failed');
    expect(startTopic).not.toHaveBeenCalled();
  });

  it('exposes the workspace preference loading state for writers to wait on', () => {
    testState.effective = { ...testState.effective, isPreferenceLoading: true };

    const { result } = renderHook(() => useCommitWorkingDirectory('agent-id'));

    expect(result.current.isPreferenceLoading).toBe(true);
  });
});