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.4 KB
Raw Blame
import type { DeviceListItem } from '@lobechat/types';
import { useCallback } from 'react';

import { useIsWorkspaceOwner } from '@/business/client/hooks/useIsWorkspaceOwner';
import { useIsWorkspaceViewer } from '@/business/client/hooks/useIsWorkspaceViewer';
import { useUserStore } from '@/store/user';
import { userProfileSelectors } from '@/store/user/selectors';

/**
 * Predicate for "can the current user mutate this device row?". Mirrors the
 * server-side `canEditWorkspaceDevice` gate (see
 * `apps/server/src/routers/lambda/device.ts`) so the UI only exposes
 * rename / remove / working-dir controls when the matching request would
 * actually succeed.
 *
 * Rules:
 *   - Personal devices belong solely to the caller β†’ always editable.
 *   - Workspace ghost rows (gateway-only, not yet auto-registered β†’ no
 *     persisted enroller) are fail-closed for everyone, owners included: the
 *     workspace update / remove mutations look the device up by id first and
 *     would throw NOT_FOUND, so exposing the controls only sets up a failing
 *     action. Wait for the row to materialise.
 *   - Workspace persisted rows are editable by any workspace owner, OR by the
 *     member whose `enrollerUserId` matches the current user.
 */
export const useCanEditDevice = () => {
  const isOwner = useIsWorkspaceOwner();
  const currentUserId = useUserStore(userProfileSelectors.userId);

  return useCallback(
    (device: DeviceListItem): boolean => {
      if (device.scope === 'personal') return true;
      if (!device.enroller) return false;
      if (isOwner) return true;
      if (!currentUserId) return false;
      return device.enroller.userId === currentUserId;
    },
    [isOwner, currentUserId],
  );
};

/**
 * Predicate for "can the current user operate this machine?" β€” update its app
 * or CLI, open a terminal, browse folders. Mirrors the server-side
 * `canOperateWorkspaceDevice` gate: a public workspace device is shared infra
 * every member works on, so any non-viewer member may operate it; otherwise it
 * falls back to {@link useCanEditDevice}.
 */
export const useCanOperateDevice = () => {
  const canEdit = useCanEditDevice();
  const isViewer = useIsWorkspaceViewer();

  return useCallback(
    (device: DeviceListItem): boolean =>
      (!isViewer &&
        device.scope === 'workspace' &&
        device.registered &&
        device.visibility === 'public') ||
      canEdit(device),
    [canEdit, isViewer],
  );
};