import { useState } from 'react'; import * as Ariakit from '@ariakit/react'; import { Check, ChevronDown, Folder, FolderSync, FolderX } from 'lucide-react'; import { TooltipAnchor, composerControlClasses, useToastContext } from '@librechat/client'; import type { CodeWorkspaceSelection, TConversation } from 'librechat-data-provider'; import type { SetterOrUpdater } from 'recoil'; import type { CodeWorkspaceEnvironmentResult, CodeWorkspaceRelocation, CodeWorkspaceResult, TranslationKeys, } from '~/hooks'; import { cn, codeWorkspaceErrorKeys, getCodeWorkspaceErrorReason, getResponseStatus, } from '~/utils'; import { useMoveConversationCodeEnvironmentMutation } from '~/data-provider'; import { useLocalize } from '~/hooks'; const stateLabels: Partial> = { loading: 'com_ui_code_workspace_loading', choose: 'com_ui_code_workspace_choose', missing: 'com_ui_code_workspace_missing', unavailable: 'com_ui_code_workspace_unavailable', unsupported: 'com_ui_code_workspace_unsupported', without_attached: 'com_ui_code_workspace_without_attached', }; const headingClasses = 'px-2.5 py-1.5 text-xs font-medium text-text-secondary'; const menuItemClasses = (selected = false) => cn( 'group flex w-full cursor-pointer items-start gap-3 rounded-lg px-2.5 py-2', 'outline-none transition-colors duration-theme-fast', 'hover:bg-surface-hover data-[active-item]:bg-surface-hover', selected && 'bg-surface-active-alt', ); /** A stale view of the decision recovers on reload; the other reasons explain themselves. */ function moveErrorKey(error: unknown): TranslationKeys { const reason = getCodeWorkspaceErrorReason(error); if (reason === 'locked') return 'com_ui_code_workspace_move_stale'; if (reason != null) return codeWorkspaceErrorKeys[reason]; if (getResponseStatus(error) === 409) return 'com_ui_code_workspace_move_busy'; return 'com_ui_code_workspace_move_error'; } function describeRelocation( relocation: CodeWorkspaceRelocation, localize: ReturnType, ): { label: string; info: string } { if (relocation.targets.some(({ state }) => state === 'missing')) { return { label: localize('com_ui_code_workspace_recover'), info: localize('com_ui_code_workspace_recover_info'), }; } const targetNames = relocation.targets .map(({ environment }) => environment.name ?? environment.id) .join(', '); const previousNames = relocation.previous.map(({ id, name }) => name ?? id).join(', '); let info = localize('com_ui_code_workspace_move_info', { 0: previousNames, 1: targetNames }); if (relocation.targets.length === 0) { info = localize('com_ui_code_workspace_move_info_removed', { 0: previousNames }); } else if (!previousNames) { info = localize('com_ui_code_workspace_move_info_added', { 0: targetNames }); } return { label: relocation.targets.length === 1 ? localize('com_ui_code_workspace_move_to', { 0: targetNames }) : localize('com_ui_code_workspace_move'), info, }; } /** A sole advertised workspace is the only valid pick, so it counts as chosen until changed. */ function chosenWorkspaceId( target: CodeWorkspaceEnvironmentResult, choices: Record, ): string | undefined { const choice = choices[target.environment.id]; if (choice != null && target.workspaces.some(({ id }) => id === choice)) return choice; return target.workspaces.length === 1 ? target.workspaces[0].id : undefined; } function EnvironmentWorkspaces({ environment, workspaces, emptyLabel, hideOnClick, isSelected, onSelect, }: { environment: CodeWorkspaceEnvironmentResult['environment']; workspaces: CodeWorkspaceEnvironmentResult['workspaces']; emptyLabel: string; hideOnClick: boolean; isSelected: (workspaceId: string) => boolean; onSelect: (selection: CodeWorkspaceSelection) => void; }) { const localize = useLocalize(); return (
} className={headingClasses}> {environment.name ?? environment.id} {workspaces.length === 0 && (
{emptyLabel}
)} {workspaces.map((descriptor) => { const selected = isSelected(descriptor.id); return ( onSelect({ environmentId: environment.id, workspaceId: descriptor.id })} className={menuItemClasses(selected)} > ); })}
); } export default function CodeWorkspaceMenu({ setConversation, workspace, disabled, }: { setConversation: SetterOrUpdater; workspace: CodeWorkspaceResult; disabled: boolean; }) { const localize = useLocalize(); const { showToast } = useToastContext(); const menuStore = Ariakit.useMenuStore({ focusLoop: true, placement: 'top-start' }); const isOpen = menuStore.useState('open'); const moveMutation = useMoveConversationCodeEnvironmentMutation(); const [moveDraft, setMoveDraft] = useState<{ conversationId: string; workspaces: Record; } | null>(null); if (!workspace.required) return null; const { relocation } = workspace; const environmentIds = new Set(workspace.environments.map(({ environment }) => environment.id)); const selectWorkspace = (selection: CodeWorkspaceSelection) => { workspace.rememberSelection(selection); setConversation((current) => { if (current == null) return current; const retained = (current.codeWorkspaces ?? workspace.selections ?? []).filter( ({ environmentId }) => environmentIds.has(environmentId) && environmentId !== selection.environmentId, ); return { ...current, codeEnvironmentMode: 'attached', codeWorkspaces: [...retained, selection].sort((a, b) => a.environmentId.localeCompare(b.environmentId), ), }; }); }; const selectWithoutAttached = () => { setConversation((current) => current == null ? current : { ...current, codeEnvironmentMode: 'without_attached', codeWorkspaces: undefined, }, ); }; const onlyEnvironment = workspace.environments.length === 1 ? workspace.environments[0] : null; const onlyDescriptor = onlyEnvironment?.workspaces.find( ({ id }) => id === onlyEnvironment.selected?.workspaceId, ); const labelKey = stateLabels[workspace.state]; let label = workspace.mode === 'without_attached' ? localize('com_ui_code_workspace_without_attached') : (onlyDescriptor?.name ?? onlyDescriptor?.id); if (label == null && workspace.state === 'ready') { label = localize('com_ui_code_workspaces_selected', { 0: workspace.selections?.length ?? 0, }); } else if (label == null) { label = labelKey ? localize(labelKey) : localize('com_ui_code_workspace_choose'); } const Icon = workspace.mode === 'without_attached' || workspace.state === 'missing' || workspace.state === 'unavailable' ? FolderX : Folder; if (workspace.locked && relocation == null) { if (workspace.canSubmit) return null; const recovery = localize('com_ui_code_workspace_locked_recovery'); return ( } > ); } const relocationText = relocation == null ? null : describeRelocation(relocation, localize); /** Choices belong to the chat they were made in; another relocatable chat starts undecided. */ const moveChoices = relocation != null && moveDraft?.conversationId === relocation.conversationId ? moveDraft.workspaces : {}; /** Every target needs a workspace, so the whole move lands in one validated write. */ const chosenTargets = relocation?.targets.flatMap((target) => { const workspaceId = chosenWorkspaceId(target, moveChoices); return workspaceId == null ? [] : [{ environmentId: target.environment.id, workspaceId }]; }) ?? []; const moveReady = relocation != null && chosenTargets.length === relocation.targets.length; const confirmMove = () => { if (relocation == null || !moveReady || disabled || moveMutation.isLoading) return; moveMutation.mutate( { conversationId: relocation.conversationId, from: relocation.from, to: [...relocation.retained, ...chosenTargets], }, { onSuccess: ({ conversationId, codeEnvironmentMode, codeWorkspaces }) => { chosenTargets.forEach((selection) => workspace.rememberSelection(selection)); setMoveDraft(null); setConversation((current) => current?.conversationId === conversationId ? { ...current, codeEnvironmentMode, codeWorkspaces } : current, ); }, onError: (error) => { showToast({ message: localize(moveErrorKey(error)), status: 'error' }); }, }, ); }; const buttonDisabled = disabled || moveMutation.isLoading; const ButtonIcon = relocationText == null ? Icon : FolderSync; return ( } > {relocation != null && relocationText != null ? ( <> } className={headingClasses}> {relocationText.label}

{relocationText.info}

{relocation.targets.map((target) => ( chosenWorkspaceId(target, moveChoices) === workspaceId} onSelect={({ environmentId, workspaceId }) => setMoveDraft({ conversationId: relocation.conversationId, workspaces: { ...moveChoices, [environmentId]: workspaceId }, }) } /> ))} ) : ( <> } className={headingClasses}> {localize('com_ui_code_environment')} {workspace.supportsEnvironmentDecisions && ( )} {workspace.environments.map(({ environment, state, workspaces, selected }) => ( workspace.mode === 'attached' && workspaceId === selected?.workspaceId } onSelect={selectWorkspace} /> ))} )}
); }