From 393328f93c8d6ac04153ec22d898bd8dedfff649 Mon Sep 17 00:00:00 2001 From: Marco Beretta <81851188+berry-13@users.noreply.github.com> Date: Sat, 14 Nov 2026 16:12:45 +0100 Subject: [PATCH] =?UTF-8?q?=F0=9F=A7=AD=20refactor:=20Move=20the=20Code=20?= =?UTF-8?q?Workspace=20Menu=20Into=20@librechat/chat=20(#18138)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - refactor: Move the Code Workspace Menu Into the Chat Package - refactor: Share the Composer Chip Classes From the Chat Package - test: Provide the Shared Composer Class Helpers to the Workspace Menu Spec --- .../Chat/Input/CodeWorkspaceMenu.tsx | 1083 +-------------- .../__tests__/CodeWorkspaceMenu.spec.tsx | 12 +- .../Input/__tests__/appearanceTokens.spec.ts | 2 +- client/src/components/Chat/Input/chip.ts | 48 +- eslint-suppressions.json | 10 - packages/chat/src/components.ts | 9 + .../src/components/composer/Workspace.tsx | 1158 +++++++++++++++++ .../chat/src/components/composer/chip.spec.ts | 38 + packages/chat/src/components/composer/chip.ts | 58 + packages/client/src/utils/composer.ts | 8 + 10 files changed, 1328 insertions(+), 1098 deletions(-) create mode 100644 packages/chat/src/components/composer/Workspace.tsx create mode 100644 packages/chat/src/components/composer/chip.spec.ts create mode 100644 packages/chat/src/components/composer/chip.ts diff --git a/client/src/components/Chat/Input/CodeWorkspaceMenu.tsx b/client/src/components/Chat/Input/CodeWorkspaceMenu.tsx index 2adce34a77..cd85cf3bf3 100644 --- a/client/src/components/Chat/Input/CodeWorkspaceMenu.tsx +++ b/client/src/components/Chat/Input/CodeWorkspaceMenu.tsx @@ -1,97 +1,18 @@ -import { Fragment, useId, useState } from 'react'; -import * as Ariakit from '@ariakit/react'; -import { TooltipAnchor, useToastContext } from '@librechat/client'; -import { - isCodeWorkspaceCheckoutAvailable, - isLinkedWorktreeRoutingAllowed, -} from 'librechat-data-provider'; -import { - Check, - ChevronDown, - Folder, - FolderSync, - FolderX, - RefreshCw, - Monitor, - GitBranch, - GitFork, - FolderGit2, - WandSparkles, - GitBranchPlus, -} from 'lucide-react'; -import type { CodeWorkspaceSelection, TConversation } from 'librechat-data-provider'; -import type { LucideIcon } from 'lucide-react'; +import { useToastContext } from '@librechat/client'; +import { CodeWorkspaceMenu as WorkspaceMenu } from '@librechat/chat/components'; +import type { WorkspaceMachineQuery } from '@librechat/chat/components'; +import type { TConversation } from 'librechat-data-provider'; import type { SetterOrUpdater } from 'recoil'; -import type { - CodeWorkspaceEnvironmentResult, - CodeWorkspaceResult, - CodeWorkspaceTransition, - TranslationKeys, -} from '~/hooks'; +import type { CodeWorkspaceResult, TranslationKeys } from '~/hooks'; import { useCodeWorkspaceRefresh, + useCodeEnvironmentStatusQueries, useMoveConversationCodeEnvironmentMutation, useReconcileConversationCodeEnvironmentMutation, - useCodeEnvironmentStatusQueries, } from '~/data-provider'; -import { - chipClasses, - infoChipClasses, - chipMenuClasses as menuClasses, - chipMenuItemClasses as menuItemClasses, - chipMenuHeadingClasses as headingClasses, -} from './chip'; -import { - cn, - codeWorkspaceErrorKeys, - getCodeWorkspaceErrorReason, - getResponseStatus, -} from '~/utils'; +import { codeWorkspaceErrorKeys, getCodeWorkspaceErrorReason, getResponseStatus } from '~/utils'; import { useLocalize } from '~/hooks'; -const stateLabels: Partial> = { - not_required: 'com_ui_code_workspace', - 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', -}; - -type CheckoutChoice = 'auto' | NonNullable; - -/** `auto` leaves the checkout to the worker's policy, so it is a choice the reader can return to. */ -const checkoutModes: { - value: CheckoutChoice; - icon: LucideIcon; - label: TranslationKeys; - info: TranslationKeys; - chip: TranslationKeys; -}[] = [ - { - value: 'auto', - icon: WandSparkles, - label: 'com_ui_code_checkout_automatic', - info: 'com_ui_code_checkout_automatic_info', - chip: 'com_ui_code_checkout_automatic_chip', - }, - { - value: 'isolated', - icon: GitBranchPlus, - label: 'com_ui_code_checkout_isolated', - info: 'com_ui_code_checkout_isolated_info', - chip: 'com_ui_code_worktree', - }, - { - value: 'source', - icon: FolderGit2, - label: 'com_ui_code_checkout_source', - info: 'com_ui_code_checkout_source_info', - chip: 'com_ui_code_checkout_source', - }, -]; - /** Conflicts refresh the decision; definitive rejections keep their specific explanation. */ function transitionErrorKey(error: unknown): TranslationKeys { const reason = getCodeWorkspaceErrorReason(error); @@ -101,351 +22,19 @@ function transitionErrorKey(error: unknown): TranslationKeys { return 'com_ui_code_workspace_move_error'; } -function describeTransition( - transition: CodeWorkspaceTransition, - localize: ReturnType, -): { label: string; info: string } { - if (transition.kind === 'detach') { - return { - label: localize('com_ui_code_workspace_detach'), - info: localize('com_ui_code_workspace_detach_info'), - }; - } - if (transition.targets.some(({ state }) => state === 'missing')) { - return { - label: localize('com_ui_code_workspace_recover'), - info: localize('com_ui_code_workspace_recover_info'), - }; - } - const targetNames = transition.targets - .map(({ environment }) => environment.name ?? environment.id) - .join(', '); - if (transition.kind === 'attach') { - return { - label: - transition.targets.length === 1 - ? localize('com_ui_code_workspace_attach_to', { 0: targetNames }) - : localize('com_ui_code_workspace_attach'), - info: localize('com_ui_code_workspace_attach_info'), - }; - } - const previousNames = transition.previous.map(({ id, name }) => name ?? id).join(', '); - let info = localize('com_ui_code_workspace_move_info', { 0: previousNames, 1: targetNames }); - if (transition.targets.length === 0 && !previousNames) { - /** Nothing to move onto and nothing the agents dropped: the machine itself is the problem. */ - info = localize('com_ui_code_workspace_detach_prompt'); - } else if (transition.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 }); - } +/** One machine's workspace list, read while its menu is open. An idle machine is not queried. */ +function useMachineStatus(id: string | null, enabled: boolean): WorkspaceMachineQuery { + const queries = useCodeEnvironmentStatusQueries(id != null ? [id] : [], enabled && id != null); + const query = queries[0]; return { - label: - transition.targets.length === 1 - ? localize('com_ui_code_workspace_move_to', { 0: targetNames }) - : localize('com_ui_code_workspace_move'), - info, + data: query?.data, + isLoading: query?.isLoading === true, + refetch: () => { + void query?.refetch(); + }, }; } -/** 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.workspaceId)) - return choice.workspaceId; - return target.workspaces.length === 1 ? target.workspaces[0].id : undefined; -} - -function EnvironmentWorkspaces({ - environment, - requiredBy, - workspaces, - emptyLabel, - hideOnClick, - isSelected, - onSelect, - checkout, - allowCheckoutSelection = false, - allowAutoCheckout = false, -}: { - environment: CodeWorkspaceEnvironmentResult['environment']; - requiredBy?: CodeWorkspaceEnvironmentResult['requiredBy']; - workspaces: CodeWorkspaceEnvironmentResult['workspaces']; - emptyLabel: string; - hideOnClick: boolean; - isSelected: (workspaceId: string) => boolean; - onSelect: (selection: CodeWorkspaceSelection, inheritCheckout?: boolean) => void; - checkout?: CodeWorkspaceSelection['checkout']; - allowCheckoutSelection?: boolean; - /** Offers Auto, which clears an override back to the worker's policy. */ - allowAutoCheckout?: boolean; -}) { - const localize = useLocalize(); - const owners = requiredBy?.map(({ id, name }) => name || id).join(', '); - const currentCheckout: CheckoutChoice | undefined = allowAutoCheckout - ? (checkout ?? 'auto') - : checkout; - const names = workspaces.map(({ id, name }) => name ?? id); - const sharedNames = new Set(names.filter((name, index) => names.indexOf(name) !== index)); - return ( -
- } - className={cn(headingClasses, 'flex min-w-0 items-baseline gap-1.5')} - > - {environment.name ?? environment.id} - {owners && ( - - {localize('com_ui_code_workspace_used_by', { 0: owners })} - - )} - - {workspaces.length === 0 && ( -
{emptyLabel}
- )} - {workspaces.map((descriptor) => { - const selected = isSelected(descriptor.id); - /** A sibling with the same name keeps its id visible, so the two rows never read alike. */ - const source = [ - descriptor.environment?.repo, - descriptor.environment?.ref, - sharedNames.has(descriptor.name ?? descriptor.id) ? descriptor.id : undefined, - ] - .filter(Boolean) - .join(' · '); - return ( - - - onSelect({ environmentId: environment.id, workspaceId: descriptor.id }) - } - className={menuItemClasses(selected)} - > - - {selected && - allowCheckoutSelection && - environment.configSchema?.workspaces?.allowCheckoutSelection === true && - checkoutModes - .filter( - ({ value }) => - value === 'source' || - (value === 'auto' && allowAutoCheckout) || - (value === 'isolated' && - descriptor.workspaceInstances?.includes('git_worktree')), - ) - .map(({ value, icon: ModeIcon, label }) => ( - - value === 'auto' - ? onSelect( - { environmentId: environment.id, workspaceId: descriptor.id }, - false, - ) - : onSelect({ - environmentId: environment.id, - workspaceId: descriptor.id, - checkout: value, - }) - } - > - - ))} - - ); - })} -
- ); -} - -function GitContext({ - target, - disabled, - locked, - onSelect, -}: { - target: CodeWorkspaceEnvironmentResult; - disabled: boolean; - locked: boolean; - onSelect?: (selection: CodeWorkspaceSelection, inheritCheckout?: boolean) => void; -}) { - const localize = useLocalize(); - const checkoutStore = Ariakit.useMenuStore({ focusLoop: true, placement: 'top-start' }); - const checkoutOpen = checkoutStore.useState('open'); - const descriptor = target.workspaces.find(({ id }) => id === target.selected?.workspaceId); - if (descriptor == null) return null; - const supportsWorktree = descriptor.workspaceInstances?.includes('git_worktree') === true; - const checkout = target.selected?.checkout; - const checkoutSelectionAllowed = - target.environment.configSchema?.workspaces?.allowCheckoutSelection === true; - /** The registered checkout needs no worker capability, so a workspace without worktrees still - * lets the reader override Auto with it; only the isolated option depends on support. */ - const checkoutEditable = !locked && checkoutSelectionAllowed; - const usesIsolation = checkout !== 'source' && supportsWorktree; - const showLinkedWorktrees = - !usesIsolation && - descriptor.workspaceScopes?.includes('git_linked_worktree') && - isLinkedWorktreeRoutingAllowed(target.environment.configSchema?.workspaces?.linkedWorktrees) && - isCodeWorkspaceCheckoutAvailable({ checkout }, descriptor, checkoutSelectionAllowed); - const current = checkoutModes.find(({ value }) => value === (checkout ?? 'auto')); - const options = checkoutModes.filter(({ value }) => value !== 'isolated' || supportsWorktree); - const chooseCheckout = (choice: CheckoutChoice) => { - if (target.selected == null || !checkoutEditable || disabled) return; - const { checkout: _previous, ...selection } = target.selected; - onSelect?.(choice === 'auto' ? selection : { ...selection, checkout: choice }, false); - }; - const CurrentIcon = current?.icon ?? WandSparkles; - return ( - <> - {descriptor.environment?.ref && ( - } - > - - )} - {(supportsWorktree || checkout != null || checkoutEditable) && current != null && ( - - - } - > - - - } className={headingClasses}> - {localize('com_ui_code_checkout_mode')} - - {options.map(({ value, icon: ModeIcon, label, info }) => { - const selected = value === current.value; - return ( - chooseCheckout(value)} - className={cn(menuItemClasses(selected), 'items-start')} - > - - ); - })} - - - )} - {showLinkedWorktrees && ( - } - > - - )} - - ); -} - -function WorkspaceRequirements({ - id, - requirements, - visible = false, -}: { - id: string; - requirements: string[]; - visible?: boolean; -}) { - if (requirements.length === 0) return null; - return ( -
- {requirements.map((requirement) => ( -

{requirement}

- ))} -
- ); -} - export default function CodeWorkspaceMenu({ setConversation, workspace, @@ -455,636 +44,26 @@ export default function CodeWorkspaceMenu({ workspace: CodeWorkspaceResult; disabled: boolean; }) { - const requirementsId = useId(); const localize = useLocalize(); const { showToast } = useToastContext(); - const menuStore = Ariakit.useMenuStore({ focusLoop: true, placement: 'top-start' }); - const isOpen = menuStore.useState('open'); - const machineMenuStore = Ariakit.useMenuStore({ focusLoop: true, placement: 'top-start' }); - const machineMenuOpen = machineMenuStore.useState('open'); - const [machineId, setMachineId] = useState(null); - const machine = workspace.machineOptions?.find( - ({ id }) => - id === machineId && !workspace.environments.some(({ environment }) => environment.id === id), - ); - const machineQueries = useCodeEnvironmentStatusQueries( - machine ? [machine.id] : [], - isOpen && machine != null && !workspace.locked, - ); - const machineQuery = machineQueries[0]; - const machineStatus = machineQuery?.data; - const machineReady = - machine != null && - machineStatus?.environmentId === machine.id && - machineStatus.status === 'ready' && - machineStatus.workspaces != null && - machineStatus.operations != null; const moveMutation = useMoveConversationCodeEnvironmentMutation(setConversation); const reconcileMutation = useReconcileConversationCodeEnvironmentMutation(setConversation); const { refresh, isRefreshing } = useCodeWorkspaceRefresh(); - const [moveDraft, setMoveDraft] = useState<{ - conversationId: string; - workspaces: Record; - } | null>(null); - - if (!workspace.visible) return null; - - if (workspace.recovery != null) { - const { request, status } = workspace.recovery; - const pending = status === 'pending'; - return ( -
- - {localize( - pending - ? 'com_ui_code_workspace_reconciling' - : 'com_ui_code_workspace_reconcile_failed', - )} - - -
- ); - } - - const { transition } = workspace; - const environmentIds = new Set(workspace.environments.map(({ environment }) => environment.id)); - const selectWorkspace = (selection: CodeWorkspaceSelection, inheritCheckout = true) => { - if (disabled || workspace.locked) return; - const previous = workspace.environments.find( - ({ environment }) => environment.id === selection.environmentId, - )?.selected; - if (inheritCheckout && selection.checkout == null && previous?.checkout != null) { - selection = { ...selection, checkout: previous.checkout }; - } - workspace.rememberSelection(selection); - const replacedIds = new Set( - workspace.machineOptionGroups?.filter((ids) => ids.includes(selection.environmentId)).flat(), - ); - const owners = workspace.machineChoiceOwners - ?.filter(({ environmentIds }) => environmentIds.includes(selection.environmentId)) - .map(({ agentId }) => agentId); - setConversation((current) => { - if (current == null) return current; - const retained = (current.codeWorkspaces ?? workspace.selections ?? []).flatMap( - ({ agentIds, ...existing }) => { - if ( - !environmentIds.has(existing.environmentId) || - existing.environmentId === selection.environmentId - ) - return []; - const remaining = agentIds?.filter((id) => !owners?.includes(id)); - const fixed = workspace.fixedMachineIds?.includes(existing.environmentId); - if ( - !fixed && - (agentIds == null ? replacedIds.has(existing.environmentId) : remaining?.length === 0) - ) - return []; - return [{ ...existing, ...(remaining?.length ? { agentIds: remaining } : {}) }]; - }, - ); - return { - ...current, - codeEnvironmentMode: 'attached', - codeWorkspaces: [ - ...retained, - { ...selection, ...(owners?.length ? { agentIds: owners } : {}) }, - ].sort((a, b) => a.environmentId.localeCompare(b.environmentId)), - }; - }); - }; - const selectWithoutAttached = () => { - if (disabled || workspace.locked) return; - setConversation((current) => - current == null - ? current - : { - ...current, - codeEnvironmentMode: 'without_attached', - codeWorkspaces: undefined, - }, - ); - }; - const transitionText = transition == null ? null : describeTransition(transition, localize); - /** Choices belong to the chat they were made in; another transitionable chat starts undecided. */ - const moveChoices = - transition != null && moveDraft?.conversationId === transition.conversationId - ? moveDraft.workspaces - : {}; - /** Every target needs a workspace, so the whole transition lands in one validated write. */ - const chosenTargets = - transition?.targets.flatMap((target) => { - const workspaceId = chosenWorkspaceId(target, moveChoices); - const previous = transition.from?.filter( - ({ environmentId, agentIds }) => - environmentId === target.environment.id || - agentIds?.some((id) => target.selectionOwners?.includes(id)), - ); - const priorModes = new Set( - (previous?.length ? previous : (transition.from ?? [])).map(({ checkout }) => checkout), - ); - const inheritedCheckout = priorModes.size === 1 ? [...priorModes][0] : undefined; - /** A mixed predecessor decision requires a deliberate mode, never an automatic fallback. */ - return workspaceId == null || - (priorModes.size > 1 && moveChoices[target.environment.id]?.checkout == null) - ? [] - : [ - { - environmentId: target.environment.id, - workspaceId, - checkout: moveChoices[target.environment.id]?.checkout ?? inheritedCheckout, - ...(target.selectionOwners?.length ? { agentIds: target.selectionOwners } : {}), - }, - ]; - }) ?? []; - /** A transition replaces the whole decision, so an empty target set is the detach and gets its - * own item: this one only confirms a decision that still names at least one workspace. */ - const proposed = transition == null ? [] : [...transition.retained, ...chosenTargets]; - const offersMove = - transition != null && - transition.kind !== 'detach' && - (transition.targets.length > 0 || transition.retained.length > 0); - const moveReady = - transition != null && - chosenTargets.length === transition.targets.length && - proposed.length > 0 && - chosenTargets.every((selection) => { - const target = transition.targets.find( - ({ environment }) => environment.id === selection.environmentId, - ); - return isCodeWorkspaceCheckoutAvailable( - selection, - target?.workspaces.find(({ id }) => id === selection.workspaceId), - target?.environment.configSchema?.workspaces?.allowCheckoutSelection === true, - ); - }); - const applyTransition = (to: CodeWorkspaceSelection[]) => { - if (transition == null || disabled || moveMutation.isLoading) return; - moveMutation.mutate( - { conversationId: transition.conversationId, from: transition.from, to }, - { - onSuccess: () => { - to.forEach((selection) => workspace.rememberSelection(selection)); - setMoveDraft(null); - }, - onError: (error) => { - showToast({ message: localize(transitionErrorKey(error)), status: 'error' }); - }, - }, - ); - }; - const confirmMove = () => { - if (!moveReady) return; - applyTransition(proposed); - }; - /** An empty target set is the detach: the chat keeps its history and continues without a - * workspace, instead of waiting on a machine it cannot reach. */ - const confirmDetach = () => applyTransition([]); - 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.state === '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 checkoutSummaries = workspace.environments.flatMap( - ({ environment, selected, workspaces }) => { - if (selected?.checkout == null) return []; - const descriptor = workspaces.find(({ id }) => id === selected.workspaceId); - return [ - `${environment.name ?? environment.id} · ${descriptor?.name ?? selected.workspaceId} · ${localize(selected.checkout === 'isolated' ? 'com_ui_code_checkout_isolated' : 'com_ui_code_checkout_source')}`, - ]; - }, - ); - const Icon = - workspace.mode === 'without_attached' || - workspace.state === 'missing' || - workspace.state === 'unavailable' - ? FolderX - : Folder; - const pendingRequirements = - workspace.state === 'without_attached' - ? [] - : workspace.environments.flatMap(({ environment, state, requiredBy }) => { - if (state === 'ready' || !requiredBy?.length) return []; - const agents = requiredBy.map(({ id, name }) => name || id).join(', '); - return [ - state === 'choose' - ? localize('com_ui_code_workspace_required_for', { - 0: agents, - 1: environment.name ?? environment.id, - }) - : localize('com_ui_code_workspace_agent_status', { - 0: agents, - 1: environment.name ?? environment.id, - 2: localize(stateLabels[state] ?? 'com_ui_code_workspace_unavailable'), - }), - ]; - }); - const requirements = - pendingRequirements.length === 0 && workspace.state === 'choose' && !workspace.canSubmit - ? [localize('com_ui_code_workspace_graph_selection_conflict')] - : pendingRequirements; - if ( - requirements.length > 0 && - new Set( - workspace.environments.flatMap(({ requiredBy }) => requiredBy?.map(({ id }) => id) ?? []), - ).size > 1 - ) { - requirements.unshift(localize('com_ui_code_workspace_graph_requirement')); - } - const details = [...requirements, ...checkoutSummaries]; - const description = details.join(' '); - - if (workspace.locked && transition == null) { - /** A sealed decision with no transition on offer only reports where this chat runs: without a - * workspace by its own recorded choice, or on a machine that needs attention. Whether that is - * worth showing at all is `visible`, above. */ - const recovery = - workspace.mode === 'without_attached' - ? localize('com_ui_code_workspace_without_attached_info') - : localize('com_ui_code_workspace_locked_recovery'); - return ( -
- {onlyEnvironment != null && workspace.mode !== 'without_attached' && ( - - - )} -
- 0 ? description : [recovery, ...checkoutSummaries].join(' ') - } - render={ - void refresh()} - aria-label={`${label}. ${recovery}. ${localize('com_ui_retry')}`} - aria-describedby={requirements.length > 0 ? requirementsId : undefined} - aria-busy={isRefreshing} - className={cn(chipClasses, 'max-w-full min-w-0')} - /> - } - > - - -
- {onlyEnvironment != null && workspace.mode !== 'without_attached' && ( - - )} - {workspace.environments.length > 1 && ( - - )} -
- ); - } - - const buttonDisabled = disabled || moveMutation.isLoading; - /** Only a move renames the control, because it replaces the machine the chat already runs on. - * Attaching and detaching keep naming the current state, which is what their menu changes. */ - const renamesForMove = transition?.kind === 'move' && offersMove && transitionText != null; - const ButtonIcon = renamesForMove ? FolderSync : Icon; - const ConfirmIcon = transition?.kind === 'attach' ? Folder : FolderSync; - const buttonLabel = renamesForMove ? transitionText.label : label; - const machines = new Map( - workspace.environments.map(({ environment }) => [environment.id, environment]), - ); - workspace.machineOptions?.forEach((candidate) => machines.set(candidate.id, candidate)); - const showMachinePicker = !workspace.locked && machines.size > 0; - const machineLabel = - workspace.mode === 'without_attached' || workspace.environments.length === 0 - ? localize('com_ui_code_machine_choose') - : (onlyEnvironment?.environment.name ?? - onlyEnvironment?.environment.id ?? - localize('com_ui_code_machines_selected', { 0: workspace.environments.length })); - return ( -
- {workspace.locked && onlyEnvironment != null && workspace.mode !== 'without_attached' && ( - - - )} - {showMachinePicker && ( - - - } - > - - !menuStore.getState().open} - className={menuClasses} - > - } className={headingClasses}> - {localize('com_ui_code_machine')} - - {[...machines.values()].map((candidate) => ( - { - setMachineId(candidate.id); - menuStore.setAutoFocusOnShow(true); - menuStore.show(); - }} - > - - ))} - - - )} - -
- setMachineId(null)} - onKeyDown={(event) => { - if (event.key === 'ArrowDown' || event.key === 'ArrowUp') setMachineId(null); - }} - data-testid={renamesForMove ? 'code-workspace-move' : 'code-workspace'} - aria-describedby={requirements.length > 0 ? requirementsId : undefined} - aria-label={ - transitionText == null - ? `${localize('com_ui_code_workspace')}: ${label}` - : `${buttonLabel}. ${transitionText.info}` - } - className={cn( - chipClasses, - 'max-w-full min-w-0', - isOpen && 'bg-surface-hover', - buttonDisabled && 'cursor-not-allowed opacity-50', - )} - /> - } - > - - -
- - {transition != null && transitionText != null ? ( - <> - } className={headingClasses}> - {transitionText.label} - -

{transitionText.info}

- {transition.targets.map((target) => ( - - chosenWorkspaceId(target, moveChoices) === workspaceId - } - allowCheckoutSelection={true} - checkout={ - chosenTargets.find( - ({ environmentId }) => environmentId === target.environment.id, - )?.checkout - } - onSelect={(selection) => - setMoveDraft({ - conversationId: transition.conversationId, - workspaces: { - ...moveChoices, - [selection.environmentId]: { - ...selection, - checkout: - selection.checkout ?? - chosenTargets.find( - ({ environmentId }) => environmentId === selection.environmentId, - )?.checkout, - }, - }, - }) - } - /> - ))} - - {offersMove && ( - - - )} - {transition.detachable && ( - - - )} - - ) : ( - <> - {workspace.supportsEnvironmentDecisions && ( - - - )} - {workspace.environments - .filter(({ environment }) => machineId == null || environment.id === machineId) - .map(({ environment, state, workspaces, selected, requiredBy }) => ( - - workspace.mode === 'attached' && workspaceId === selected?.workspaceId - } - onSelect={selectWorkspace} - checkout={selected?.checkout} - /** One environment gets the checkout chip in the rail; several share it here, - * one set of choices under each environment's selected workspace. */ - allowCheckoutSelection={!workspace.locked && workspace.environments.length > 1} - allowAutoCheckout={true} - /> - ))} - {machine != null && - (machineReady ? ( - false} - onSelect={selectWorkspace} - /> - ) : ( - void machineQuery?.refetch()} - > - - ))} - - )} - - - void refresh()} - aria-busy={isRefreshing} - className={menuItemClasses()} - > - -
- {workspace.environments.length > 1 && ( - - )} -
- {onlyEnvironment != null && workspace.mode !== 'without_attached' && ( - - )} -
+ localize(phraseKey as TranslationKeys, options)} + showToast={showToast} + refresh={refresh} + isRefreshing={isRefreshing} + movePending={moveMutation.isLoading} + reconcilePending={reconcileMutation.isLoading} + applyMove={(request, handlers) => moveMutation.mutate(request, handlers)} + reconcile={(request) => reconcileMutation.mutate(request)} + useMachineStatus={useMachineStatus} + moveErrorMessage={(error) => localize(transitionErrorKey(error))} + /> ); } diff --git a/client/src/components/Chat/Input/__tests__/CodeWorkspaceMenu.spec.tsx b/client/src/components/Chat/Input/__tests__/CodeWorkspaceMenu.spec.tsx index 544523f2cd..7653c93fd6 100644 --- a/client/src/components/Chat/Input/__tests__/CodeWorkspaceMenu.spec.tsx +++ b/client/src/components/Chat/Input/__tests__/CodeWorkspaceMenu.spec.tsx @@ -33,10 +33,20 @@ jest.mock('~/hooks', () => ({ })); jest.mock('@librechat/client', () => { - const { CheckboxGlyph, TooltipAnchor, cn } = jest.requireActual('@librechat/client'); + const { + CheckboxGlyph, + TooltipAnchor, + cn, + mergeComposerClasses, + disabledFillClasses, + disabledInkClasses, + } = jest.requireActual('@librechat/client'); return { cn, CheckboxGlyph, + mergeComposerClasses, + disabledFillClasses, + disabledInkClasses, composerControlClasses: () => 'composer-control', useToastContext: () => ({ showToast: mockShowToast }), TooltipAnchor, diff --git a/client/src/components/Chat/Input/__tests__/appearanceTokens.spec.ts b/client/src/components/Chat/Input/__tests__/appearanceTokens.spec.ts index ef6d18cd3e..59586580d6 100644 --- a/client/src/components/Chat/Input/__tests__/appearanceTokens.spec.ts +++ b/client/src/components/Chat/Input/__tests__/appearanceTokens.spec.ts @@ -21,7 +21,7 @@ const themedControls = [ /** The context rail's pills share one recipe built on the composer control classes. */ ['chip.ts', ['composerControlClasses()']], ['CodeApprovalMenu.tsx', ['chipClasses']], - ['CodeWorkspaceMenu.tsx', ['chipClasses', 'infoChipClasses']], + ['Workspace.tsx', ['chipClasses', 'infoChipClasses']], /** The dictation mic and its send share the submit slot's corner. */ ['Composer/Bar.tsx', ['shape="composer"']], ] as const; diff --git a/client/src/components/Chat/Input/chip.ts b/client/src/components/Chat/Input/chip.ts index 4b888536bc..ab430ec154 100644 --- a/client/src/components/Chat/Input/chip.ts +++ b/client/src/components/Chat/Input/chip.ts @@ -1,37 +1,17 @@ -import { cn, composerControlClasses } from '@librechat/client'; +import { composerChipClasses } from '@librechat/chat/components'; -/** One compact pill for every control in the composer's context rail (project, machine, - * workspace, branch, worktree, approval mode), so the rail reads as a single set. */ -export const chipClasses = cn( - composerControlClasses(), - 'h-8 max-w-full min-w-0 gap-1.5 px-2.5 text-xs', - 'focus-visible:ring-2 focus-visible:ring-text-primary focus-visible:outline-hidden', -); - -/** Read-only facts (branch) drop the border and sit on a quiet fill so they do not look pressable. */ -export const infoChipClasses = cn( +const { chipClasses, - 'border-transparent bg-surface-tertiary text-text-secondary hover:bg-surface-tertiary', -); + infoChipClasses, + chipMenuClasses, + chipMenuHeadingClasses, + chipMenuItemClasses, +} = composerChipClasses(); -/** The popover the rail's chips open. Menus open above their chip, so they rise a few pixels - * from its edge while fading and scaling in, and leave on the faster theme step. */ -export const chipMenuClasses = cn( - 'z-50 flex max-w-[min(340px,calc(100vw-2rem))] min-w-[240px] flex-col rounded-theme-popover', - 'border-border-menu bg-surface-menu max-h-[var(--popover-available-height)] overflow-y-auto border p-1 shadow-lg', - 'origin-bottom-left translate-y-1 scale-95 opacity-0', - 'transition duration-theme-normal ease-out motion-reduce:transition-none', - 'data-[enter]:translate-y-0 data-[enter]:scale-100 data-[enter]:opacity-100', - 'data-[leave]:duration-theme-fast data-[leave]:ease-in', -); - -export const chipMenuHeadingClasses = 'px-2.5 pt-2 pb-1 text-xs font-semibold text-text-secondary'; - -export const chipMenuItemClasses = (selected = false) => - cn( - 'group flex w-full cursor-pointer items-center gap-2.5 rounded-lg px-2.5 py-1.5', - 'outline-hidden transition-colors duration-theme-fast', - 'hover:bg-surface-hover data-[active-item]:bg-surface-hover', - 'aria-disabled:cursor-not-allowed aria-disabled:opacity-50', - selected && 'bg-surface-active-alt', - ); +export { + chipClasses, + infoChipClasses, + chipMenuClasses, + chipMenuHeadingClasses, + chipMenuItemClasses, +}; diff --git a/eslint-suppressions.json b/eslint-suppressions.json index a177a78dc8..a1869b87b5 100644 --- a/eslint-suppressions.json +++ b/eslint-suppressions.json @@ -65,11 +65,6 @@ "count": 1 } }, - "client/src/components/Chat/Input/CodeWorkspaceMenu.tsx": { - "design/disabled-recipe": { - "count": 2 - } - }, "client/src/components/Chat/Input/Composer/Files.tsx": { "design/disabled-recipe": { "count": 1 @@ -111,11 +106,6 @@ "count": 3 } }, - "client/src/components/Chat/Input/chip.ts": { - "design/disabled-recipe": { - "count": 1 - } - }, "client/src/components/Chat/Landing.tsx": { "shadcn/no-restyle": { "count": 14 diff --git a/packages/chat/src/components.ts b/packages/chat/src/components.ts index bff75ca4cc..05c0f255e9 100644 --- a/packages/chat/src/components.ts +++ b/packages/chat/src/components.ts @@ -75,6 +75,15 @@ export { getFileType } from './components/composer/files/kinds'; export type { FileKind } from './components/composer/files/kinds'; export type { SubtitleAction } from './components/composer/files/FileContainer'; export type { PastedTextEdit } from './components/composer/files/PastedTextDialog'; +export { composerChipClasses } from './components/composer/chip'; +export type { ComposerChipClasses } from './components/composer/chip'; +export { default as CodeWorkspaceMenu } from './components/composer/Workspace'; +export type { + WorkspaceLocalize, + WorkspaceMachineQuery, + CodeWorkspaceMenuProps, + CodeWorkspaceMenuWorkspace, +} from './components/composer/Workspace'; /** Message list building blocks: rows, headers, sibling navigation and the streaming timer. */ export { default as SubRow } from './components/messages/SubRow'; diff --git a/packages/chat/src/components/composer/Workspace.tsx b/packages/chat/src/components/composer/Workspace.tsx new file mode 100644 index 0000000000..3e4c64d8a5 --- /dev/null +++ b/packages/chat/src/components/composer/Workspace.tsx @@ -0,0 +1,1158 @@ +import { Fragment, useId, useState } from 'react'; +import * as Ariakit from '@ariakit/react'; +import { cn, TooltipAnchor, disabledFillClasses } from '@librechat/client'; +import { + isCodeWorkspaceCheckoutAvailable, + isLinkedWorktreeRoutingAllowed, +} from 'librechat-data-provider'; +import { + Check, + Folder, + Monitor, + FolderX, + GitFork, + RefreshCw, + FolderSync, + GitBranch, + FolderGit2, + ChevronDown, + WandSparkles, + GitBranchPlus, +} from 'lucide-react'; +import type { + TConversation, + TPublicCodeEnvironment, + CodeWorkspaceSelection, + TCodeEnvironmentStatusResponse, +} from 'librechat-data-provider'; +import type { Dispatch, KeyboardEvent, SetStateAction } from 'react'; +import type { LucideIcon } from 'lucide-react'; +import type { + CodeWorkspaceState, + CodeWorkspaceTransition, + CodeWorkspaceEnvironmentResult, +} from '../../core'; +import { composerChipClasses } from './chip'; + +export type WorkspaceLocalize = ( + phraseKey: string, + options?: Record, +) => string; + +export type WorkspaceMachineQuery = { + data?: TCodeEnvironmentStatusResponse; + isLoading: boolean; + refetch: () => void; +}; + +/** The workspace decision the menu draws. The app computes it; this view only reads it. */ +export type CodeWorkspaceMenuWorkspace = { + visible: boolean; + recovery?: { + status: 'pending' | 'error'; + request: { + conversationId: string; + attempted: Pick; + }; + }; + supportsEnvironmentDecisions: boolean; + locked: boolean; + mode?: TConversation['codeEnvironmentMode']; + state: CodeWorkspaceState; + canSubmit: boolean; + environments: CodeWorkspaceEnvironmentResult[]; + machineOptions?: TPublicCodeEnvironment[]; + machineOptionGroups?: string[][]; + machineChoiceOwners?: Array<{ agentId: string; environmentIds: string[] }>; + fixedMachineIds?: string[]; + transition?: CodeWorkspaceTransition; + selections?: CodeWorkspaceSelection[]; + rememberSelection: (selection: CodeWorkspaceSelection) => void; +}; + +export type CodeWorkspaceMenuProps = { + setConversation: Dispatch>; + workspace: CodeWorkspaceMenuWorkspace; + disabled: boolean; + localize: WorkspaceLocalize; + showToast: (toast: { message: string; status: 'error' }) => void; + refresh: () => unknown; + isRefreshing: boolean; + movePending: boolean; + reconcilePending: boolean; + applyMove: ( + request: { + conversationId: string; + from: CodeWorkspaceSelection[]; + to: CodeWorkspaceSelection[]; + }, + handlers: { onSuccess?: () => void; onError?: (error: unknown) => void }, + ) => void; + reconcile: (request: { + conversationId: string; + attempted: Pick; + }) => void; + /** Called on every render. Reads one machine's workspaces while its menu is open. */ + useMachineStatus: (id: string | null, enabled: boolean) => WorkspaceMachineQuery; + /** A failed move's message, already safe to show. */ + moveErrorMessage: (error: unknown) => string; +}; + +const stateLabels: Partial> = { + not_required: 'com_ui_code_workspace', + 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', +}; + +type CheckoutChoice = 'auto' | NonNullable; + +/** `auto` leaves the checkout to the worker's policy, so it is a choice the reader can return to. */ +const checkoutModes: { + value: CheckoutChoice; + icon: LucideIcon; + label: string; + info: string; + chip: string; +}[] = [ + { + value: 'auto', + icon: WandSparkles, + label: 'com_ui_code_checkout_automatic', + info: 'com_ui_code_checkout_automatic_info', + chip: 'com_ui_code_checkout_automatic_chip', + }, + { + value: 'isolated', + icon: GitBranchPlus, + label: 'com_ui_code_checkout_isolated', + info: 'com_ui_code_checkout_isolated_info', + chip: 'com_ui_code_worktree', + }, + { + value: 'source', + icon: FolderGit2, + label: 'com_ui_code_checkout_source', + info: 'com_ui_code_checkout_source_info', + chip: 'com_ui_code_checkout_source', + }, +]; + +function describeTransition( + transition: CodeWorkspaceTransition, + localize: WorkspaceLocalize, +): { label: string; info: string } { + if (transition.kind === 'detach') { + return { + label: localize('com_ui_code_workspace_detach'), + info: localize('com_ui_code_workspace_detach_info'), + }; + } + if (transition.targets.some(({ state }) => state === 'missing')) { + return { + label: localize('com_ui_code_workspace_recover'), + info: localize('com_ui_code_workspace_recover_info'), + }; + } + const targetNames = transition.targets + .map(({ environment }) => environment.name ?? environment.id) + .join(', '); + if (transition.kind === 'attach') { + return { + label: + transition.targets.length === 1 + ? localize('com_ui_code_workspace_attach_to', { 0: targetNames }) + : localize('com_ui_code_workspace_attach'), + info: localize('com_ui_code_workspace_attach_info'), + }; + } + const previousNames = transition.previous.map(({ id, name }) => name ?? id).join(', '); + let info = localize('com_ui_code_workspace_move_info', { 0: previousNames, 1: targetNames }); + if (transition.targets.length === 0 && !previousNames) { + /** Nothing to move onto and nothing the agents dropped: the machine itself is the problem. */ + info = localize('com_ui_code_workspace_detach_prompt'); + } else if (transition.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: + transition.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.workspaceId)) + return choice.workspaceId; + return target.workspaces.length === 1 ? target.workspaces[0].id : undefined; +} + +function EnvironmentWorkspaces({ + environment, + requiredBy, + workspaces, + emptyLabel, + hideOnClick, + isSelected, + onSelect, + checkout, + allowCheckoutSelection = false, + allowAutoCheckout = false, + localize, +}: { + environment: CodeWorkspaceEnvironmentResult['environment']; + requiredBy?: CodeWorkspaceEnvironmentResult['requiredBy']; + workspaces: CodeWorkspaceEnvironmentResult['workspaces']; + emptyLabel: string; + hideOnClick: boolean; + isSelected: (workspaceId: string) => boolean; + onSelect: (selection: CodeWorkspaceSelection, inheritCheckout?: boolean) => void; + checkout?: CodeWorkspaceSelection['checkout']; + allowCheckoutSelection?: boolean; + /** Offers Auto, which clears an override back to the worker's policy. */ + allowAutoCheckout?: boolean; + localize: WorkspaceLocalize; +}) { + const { chipMenuHeadingClasses: headingClasses, chipMenuItemClasses: menuItemClasses } = + composerChipClasses(); + const owners = requiredBy?.map(({ id, name }) => name || id).join(', '); + const currentCheckout: CheckoutChoice | undefined = allowAutoCheckout + ? (checkout ?? 'auto') + : checkout; + const names = workspaces.map(({ id, name }) => name ?? id); + const sharedNames = new Set(names.filter((name, index) => names.indexOf(name) !== index)); + return ( +
+ } + className={cn(headingClasses, 'flex min-w-0 items-baseline gap-1.5')} + > + {environment.name ?? environment.id} + {owners && ( + + {localize('com_ui_code_workspace_used_by', { 0: owners })} + + )} + + {workspaces.length === 0 && ( +
{emptyLabel}
+ )} + {workspaces.map((descriptor) => { + const selected = isSelected(descriptor.id); + /** A sibling with the same name keeps its id visible, so the two rows never read alike. */ + const source = [ + descriptor.environment?.repo, + descriptor.environment?.ref, + sharedNames.has(descriptor.name ?? descriptor.id) ? descriptor.id : undefined, + ] + .filter(Boolean) + .join(' · '); + return ( + + + onSelect({ environmentId: environment.id, workspaceId: descriptor.id }) + } + className={menuItemClasses(selected)} + > + + {selected && + allowCheckoutSelection && + environment.configSchema?.workspaces?.allowCheckoutSelection === true && + checkoutModes + .filter( + ({ value }) => + value === 'source' || + (value === 'auto' && allowAutoCheckout) || + (value === 'isolated' && + descriptor.workspaceInstances?.includes('git_worktree')), + ) + .map(({ value, icon: ModeIcon, label }) => ( + + value === 'auto' + ? onSelect( + { environmentId: environment.id, workspaceId: descriptor.id }, + false, + ) + : onSelect({ + environmentId: environment.id, + workspaceId: descriptor.id, + checkout: value, + }) + } + > + + ))} + + ); + })} +
+ ); +} + +function GitContext({ + target, + disabled, + locked, + onSelect, + localize, +}: { + target: CodeWorkspaceEnvironmentResult; + disabled: boolean; + locked: boolean; + onSelect?: (selection: CodeWorkspaceSelection, inheritCheckout?: boolean) => void; + localize: WorkspaceLocalize; +}) { + const { + chipClasses, + infoChipClasses, + chipMenuClasses: menuClasses, + chipMenuHeadingClasses: headingClasses, + chipMenuItemClasses: menuItemClasses, + } = composerChipClasses(); + const checkoutStore = Ariakit.useMenuStore({ focusLoop: true, placement: 'top-start' }); + const checkoutOpen = checkoutStore.useState('open'); + const descriptor = target.workspaces.find(({ id }) => id === target.selected?.workspaceId); + if (descriptor == null) return null; + const supportsWorktree = descriptor.workspaceInstances?.includes('git_worktree') === true; + const checkout = target.selected?.checkout; + const checkoutSelectionAllowed = + target.environment.configSchema?.workspaces?.allowCheckoutSelection === true; + /** The registered checkout needs no worker capability, so a workspace without worktrees still + * lets the reader override Auto with it; only the isolated option depends on support. */ + const checkoutEditable = !locked && checkoutSelectionAllowed; + const usesIsolation = checkout !== 'source' && supportsWorktree; + const showLinkedWorktrees = + !usesIsolation && + descriptor.workspaceScopes?.includes('git_linked_worktree') && + isLinkedWorktreeRoutingAllowed(target.environment.configSchema?.workspaces?.linkedWorktrees) && + isCodeWorkspaceCheckoutAvailable({ checkout }, descriptor, checkoutSelectionAllowed); + const current = checkoutModes.find(({ value }) => value === (checkout ?? 'auto')); + const options = checkoutModes.filter(({ value }) => value !== 'isolated' || supportsWorktree); + const chooseCheckout = (choice: CheckoutChoice) => { + if (target.selected == null || !checkoutEditable || disabled) return; + const { checkout: _previous, ...selection } = target.selected; + onSelect?.(choice === 'auto' ? selection : { ...selection, checkout: choice }, false); + }; + const CurrentIcon = current?.icon ?? WandSparkles; + return ( + <> + {descriptor.environment?.ref && ( + } + > + + )} + {(supportsWorktree || checkout != null || checkoutEditable) && current != null && ( + + + } + > + + + } className={headingClasses}> + {localize('com_ui_code_checkout_mode')} + + {options.map(({ value, icon: ModeIcon, label, info }) => { + const selected = value === current.value; + return ( + chooseCheckout(value)} + className={cn(menuItemClasses(selected), 'items-start')} + > + + ); + })} + + + )} + {showLinkedWorktrees && ( + } + > + + )} + + ); +} + +function WorkspaceRequirements({ + id, + requirements, + visible = false, +}: { + id: string; + requirements: string[]; + visible?: boolean; +}) { + if (requirements.length === 0) return null; + return ( +
+ {requirements.map((requirement) => ( +

{requirement}

+ ))} +
+ ); +} + +export default function CodeWorkspaceMenu({ + setConversation, + workspace, + disabled, + localize, + showToast, + refresh, + isRefreshing, + movePending, + reconcilePending, + applyMove, + reconcile, + useMachineStatus, + moveErrorMessage, +}: CodeWorkspaceMenuProps): JSX.Element | null { + const requirementsId = useId(); + const { + chipClasses, + chipMenuClasses: menuClasses, + chipMenuHeadingClasses: headingClasses, + chipMenuItemClasses: menuItemClasses, + } = composerChipClasses(); + const menuStore = Ariakit.useMenuStore({ focusLoop: true, placement: 'top-start' }); + const isOpen = menuStore.useState('open'); + const machineMenuStore = Ariakit.useMenuStore({ focusLoop: true, placement: 'top-start' }); + const machineMenuOpen = machineMenuStore.useState('open'); + const [machineId, setMachineId] = useState(null); + const machine = workspace.machineOptions?.find( + ({ id }) => + id === machineId && !workspace.environments.some(({ environment }) => environment.id === id), + ); + const machineQuery = useMachineStatus( + machine?.id ?? null, + isOpen && machine != null && !workspace.locked, + ); + const machineStatus = machineQuery.data; + const machineReady = + machine != null && + machineStatus?.environmentId === machine.id && + machineStatus.status === 'ready' && + machineStatus.workspaces != null && + machineStatus.operations != null; + const [moveDraft, setMoveDraft] = useState<{ + conversationId: string; + workspaces: Record; + } | null>(null); + + if (!workspace.visible) return null; + + if (workspace.recovery != null) { + const { request, status } = workspace.recovery; + const pending = status === 'pending'; + return ( +
+ + {localize( + pending + ? 'com_ui_code_workspace_reconciling' + : 'com_ui_code_workspace_reconcile_failed', + )} + + +
+ ); + } + + const { transition } = workspace; + const environmentIds = new Set(workspace.environments.map(({ environment }) => environment.id)); + const selectWorkspace = (selection: CodeWorkspaceSelection, inheritCheckout = true) => { + if (disabled || workspace.locked) return; + const previous = workspace.environments.find( + ({ environment }) => environment.id === selection.environmentId, + )?.selected; + if (inheritCheckout && selection.checkout == null && previous?.checkout != null) { + selection = { ...selection, checkout: previous.checkout }; + } + workspace.rememberSelection(selection); + const replacedIds = new Set( + workspace.machineOptionGroups?.filter((ids) => ids.includes(selection.environmentId)).flat(), + ); + const owners = workspace.machineChoiceOwners + ?.filter(({ environmentIds }) => environmentIds.includes(selection.environmentId)) + .map(({ agentId }) => agentId); + setConversation((current) => { + if (current == null) return current; + const retained = (current.codeWorkspaces ?? workspace.selections ?? []).flatMap( + ({ agentIds, ...existing }) => { + if ( + !environmentIds.has(existing.environmentId) || + existing.environmentId === selection.environmentId + ) + return []; + const remaining = agentIds?.filter((id) => !owners?.includes(id)); + const fixed = workspace.fixedMachineIds?.includes(existing.environmentId); + if ( + !fixed && + (agentIds == null ? replacedIds.has(existing.environmentId) : remaining?.length === 0) + ) + return []; + return [{ ...existing, ...(remaining?.length ? { agentIds: remaining } : {}) }]; + }, + ); + return { + ...current, + codeEnvironmentMode: 'attached', + codeWorkspaces: [ + ...retained, + { ...selection, ...(owners?.length ? { agentIds: owners } : {}) }, + ].sort((a, b) => a.environmentId.localeCompare(b.environmentId)), + }; + }); + }; + const selectWithoutAttached = () => { + if (disabled || workspace.locked) return; + setConversation((current) => + current == null + ? current + : { + ...current, + codeEnvironmentMode: 'without_attached', + codeWorkspaces: undefined, + }, + ); + }; + const transitionText = transition == null ? null : describeTransition(transition, localize); + /** Choices belong to the chat they were made in; another transitionable chat starts undecided. */ + const moveChoices = + transition != null && moveDraft?.conversationId === transition.conversationId + ? moveDraft.workspaces + : {}; + /** Every target needs a workspace, so the whole transition lands in one validated write. */ + const chosenTargets = + transition?.targets.flatMap((target) => { + const workspaceId = chosenWorkspaceId(target, moveChoices); + const previous = transition.from?.filter( + ({ environmentId, agentIds }) => + environmentId === target.environment.id || + agentIds?.some((id) => target.selectionOwners?.includes(id)), + ); + const priorModes = new Set( + (previous?.length ? previous : (transition.from ?? [])).map(({ checkout }) => checkout), + ); + const inheritedCheckout = priorModes.size === 1 ? [...priorModes][0] : undefined; + /** A mixed predecessor decision requires a deliberate mode, never an automatic fallback. */ + return workspaceId == null || + (priorModes.size > 1 && moveChoices[target.environment.id]?.checkout == null) + ? [] + : [ + { + environmentId: target.environment.id, + workspaceId, + checkout: moveChoices[target.environment.id]?.checkout ?? inheritedCheckout, + ...(target.selectionOwners?.length ? { agentIds: target.selectionOwners } : {}), + }, + ]; + }) ?? []; + /** A transition replaces the whole decision, so an empty target set is the detach and gets its + * own item: this one only confirms a decision that still names at least one workspace. */ + const proposed = transition == null ? [] : [...transition.retained, ...chosenTargets]; + const offersMove = + transition != null && + transition.kind !== 'detach' && + (transition.targets.length > 0 || transition.retained.length > 0); + const moveReady = + transition != null && + chosenTargets.length === transition.targets.length && + proposed.length > 0 && + chosenTargets.every((selection) => { + const target = transition.targets.find( + ({ environment }) => environment.id === selection.environmentId, + ); + return isCodeWorkspaceCheckoutAvailable( + selection, + target?.workspaces.find(({ id }) => id === selection.workspaceId), + target?.environment.configSchema?.workspaces?.allowCheckoutSelection === true, + ); + }); + const applyTransition = (to: CodeWorkspaceSelection[]) => { + if (transition == null || disabled || movePending) return; + applyMove( + { conversationId: transition.conversationId, from: transition.from, to }, + { + onSuccess: () => { + to.forEach((selection) => workspace.rememberSelection(selection)); + setMoveDraft(null); + }, + onError: (error) => { + showToast({ message: moveErrorMessage(error), status: 'error' }); + }, + }, + ); + }; + const confirmMove = () => { + if (!moveReady) return; + applyTransition(proposed); + }; + /** An empty target set is the detach: the chat keeps its history and continues without a + * workspace, instead of waiting on a machine it cannot reach. */ + const confirmDetach = () => applyTransition([]); + 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.state === '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 checkoutSummaries = workspace.environments.flatMap( + ({ environment, selected, workspaces }) => { + if (selected?.checkout == null) return []; + const descriptor = workspaces.find(({ id }) => id === selected.workspaceId); + return [ + `${environment.name ?? environment.id} · ${descriptor?.name ?? selected.workspaceId} · ${localize(selected.checkout === 'isolated' ? 'com_ui_code_checkout_isolated' : 'com_ui_code_checkout_source')}`, + ]; + }, + ); + const Icon = + workspace.mode === 'without_attached' || + workspace.state === 'missing' || + workspace.state === 'unavailable' + ? FolderX + : Folder; + const pendingRequirements = + workspace.state === 'without_attached' + ? [] + : workspace.environments.flatMap(({ environment, state, requiredBy }) => { + if (state === 'ready' || !requiredBy?.length) return []; + const agents = requiredBy.map(({ id, name }) => name || id).join(', '); + return [ + state === 'choose' + ? localize('com_ui_code_workspace_required_for', { + 0: agents, + 1: environment.name ?? environment.id, + }) + : localize('com_ui_code_workspace_agent_status', { + 0: agents, + 1: environment.name ?? environment.id, + 2: localize(stateLabels[state] ?? 'com_ui_code_workspace_unavailable'), + }), + ]; + }); + const requirements = + pendingRequirements.length === 0 && workspace.state === 'choose' && !workspace.canSubmit + ? [localize('com_ui_code_workspace_graph_selection_conflict')] + : pendingRequirements; + if ( + requirements.length > 0 && + new Set( + workspace.environments.flatMap(({ requiredBy }) => requiredBy?.map(({ id }) => id) ?? []), + ).size > 1 + ) { + requirements.unshift(localize('com_ui_code_workspace_graph_requirement')); + } + const details = [...requirements, ...checkoutSummaries]; + const description = details.join(' '); + + if (workspace.locked && transition == null) { + /** A sealed decision with no transition on offer only reports where this chat runs: without a + * workspace by its own recorded choice, or on a machine that needs attention. Whether that is + * worth showing at all is `visible`, above. */ + const recovery = + workspace.mode === 'without_attached' + ? localize('com_ui_code_workspace_without_attached_info') + : localize('com_ui_code_workspace_locked_recovery'); + return ( +
+ {onlyEnvironment != null && workspace.mode !== 'without_attached' && ( + + + )} +
+ 0 ? description : [recovery, ...checkoutSummaries].join(' ') + } + render={ + void refresh()} + aria-label={`${label}. ${recovery}. ${localize('com_ui_retry')}`} + aria-describedby={requirements.length > 0 ? requirementsId : undefined} + aria-busy={isRefreshing} + className={cn(chipClasses, 'max-w-full min-w-0')} + /> + } + > + + +
+ {onlyEnvironment != null && workspace.mode !== 'without_attached' && ( + + )} + {workspace.environments.length > 1 && ( + + )} +
+ ); + } + + const buttonDisabled = disabled || movePending; + /** Only a move renames the control, because it replaces the machine the chat already runs on. + * Attaching and detaching keep naming the current state, which is what their menu changes. */ + const renamesForMove = transition?.kind === 'move' && offersMove && transitionText != null; + const ButtonIcon = renamesForMove ? FolderSync : Icon; + const ConfirmIcon = transition?.kind === 'attach' ? Folder : FolderSync; + const buttonLabel = renamesForMove ? transitionText.label : label; + const machines = new Map( + workspace.environments.map(({ environment }) => [environment.id, environment]), + ); + workspace.machineOptions?.forEach((candidate) => machines.set(candidate.id, candidate)); + const showMachinePicker = !workspace.locked && machines.size > 0; + const machineLabel = + workspace.mode === 'without_attached' || workspace.environments.length === 0 + ? localize('com_ui_code_machine_choose') + : (onlyEnvironment?.environment.name ?? + onlyEnvironment?.environment.id ?? + localize('com_ui_code_machines_selected', { 0: workspace.environments.length })); + + return ( +
+ {workspace.locked && onlyEnvironment != null && workspace.mode !== 'without_attached' && ( + + + )} + {showMachinePicker && ( + + + } + > + + !menuStore.getState().open} + className={menuClasses} + > + } className={headingClasses}> + {localize('com_ui_code_machine')} + + {[...machines.values()].map((candidate) => ( + { + setMachineId(candidate.id); + menuStore.setAutoFocusOnShow(true); + menuStore.show(); + }} + > + + ))} + + + )} + +
+ setMachineId(null)} + onKeyDown={(event: KeyboardEvent) => { + if (event.key === 'ArrowDown' || event.key === 'ArrowUp') setMachineId(null); + }} + data-testid={renamesForMove ? 'code-workspace-move' : 'code-workspace'} + aria-describedby={requirements.length > 0 ? requirementsId : undefined} + aria-label={ + transitionText == null + ? `${localize('com_ui_code_workspace')}: ${label}` + : `${buttonLabel}. ${transitionText.info}` + } + className={cn( + chipClasses, + 'max-w-full min-w-0', + isOpen && 'bg-surface-hover', + buttonDisabled && 'cursor-not-allowed opacity-50', + buttonDisabled && disabledFillClasses, + )} + /> + } + > + + +
+ + {transition != null && transitionText != null ? ( + <> + } className={headingClasses}> + {transitionText.label} + +

{transitionText.info}

+ {transition.targets.map((target) => ( + + chosenWorkspaceId(target, moveChoices) === workspaceId + } + allowCheckoutSelection={true} + checkout={ + chosenTargets.find( + ({ environmentId }) => environmentId === target.environment.id, + )?.checkout + } + onSelect={(selection) => + setMoveDraft({ + conversationId: transition.conversationId, + workspaces: { + ...moveChoices, + [selection.environmentId]: { + ...selection, + checkout: + selection.checkout ?? + chosenTargets.find( + ({ environmentId }) => environmentId === selection.environmentId, + )?.checkout, + }, + }, + }) + } + /> + ))} + + {offersMove && ( + + + )} + {transition.detachable && ( + + + )} + + ) : ( + <> + {workspace.supportsEnvironmentDecisions && ( + + + )} + {workspace.environments + .filter(({ environment }) => machineId == null || environment.id === machineId) + .map(({ environment, state, workspaces, selected, requiredBy }) => ( + + workspace.mode === 'attached' && workspaceId === selected?.workspaceId + } + onSelect={selectWorkspace} + checkout={selected?.checkout} + /** One environment gets the checkout chip in the rail; several share it here, + * one set of choices under each environment's selected workspace. */ + allowCheckoutSelection={!workspace.locked && workspace.environments.length > 1} + allowAutoCheckout={true} + /> + ))} + {machine != null && + (machineReady ? ( + false} + onSelect={selectWorkspace} + /> + ) : ( + void machineQuery?.refetch()} + > + + ))} + + )} + + + void refresh()} + aria-busy={isRefreshing} + className={menuItemClasses()} + > + +
+ {workspace.environments.length > 1 && ( + + )} +
+ {onlyEnvironment != null && workspace.mode !== 'without_attached' && ( + + )} +
+ ); +} diff --git a/packages/chat/src/components/composer/chip.spec.ts b/packages/chat/src/components/composer/chip.spec.ts new file mode 100644 index 0000000000..d34936fe50 --- /dev/null +++ b/packages/chat/src/components/composer/chip.spec.ts @@ -0,0 +1,38 @@ +import { composerChipClasses } from './chip'; + +describe('composerChipClasses', () => { + it('replaces the control recipe height, gap, and type on the rail pill', () => { + const { chipClasses } = composerChipClasses(); + + expect(chipClasses).toContain('h-8'); + expect(chipClasses).toContain('gap-1.5'); + expect(chipClasses).toContain('text-xs'); + expect(chipClasses).not.toContain('h-theme-control'); + expect(chipClasses).not.toContain('gap-theme-control-gap'); + expect(chipClasses).not.toContain('text-sm'); + expect(chipClasses).toContain('rounded-theme-control-round'); + }); + + it('keeps a read-only chip quiet by replacing the pressable border and fill', () => { + const { infoChipClasses } = composerChipClasses(); + + expect(infoChipClasses).toContain('border-transparent'); + expect(infoChipClasses).toContain('bg-surface-tertiary'); + expect(infoChipClasses).toContain('text-text-secondary'); + expect(infoChipClasses).toContain('hover:bg-surface-tertiary'); + expect(infoChipClasses).not.toContain('border-border-medium'); + expect(infoChipClasses).not.toContain('bg-transparent'); + expect(infoChipClasses).not.toContain('text-text-primary'); + expect(infoChipClasses).not.toContain('hover:bg-surface-hover'); + }); + + it('dims a disabled menu row with the shared ink recipe', () => { + const { chipMenuItemClasses } = composerChipClasses(); + const classes = chipMenuItemClasses(true); + + expect(classes).toContain('aria-disabled:opacity-50'); + expect(classes).toContain('theme-disabled:opacity-100'); + expect(classes).toContain('bg-surface-active-alt'); + expect(chipMenuItemClasses()).not.toContain('bg-surface-active-alt'); + }); +}); diff --git a/packages/chat/src/components/composer/chip.ts b/packages/chat/src/components/composer/chip.ts new file mode 100644 index 0000000000..af523abc5c --- /dev/null +++ b/packages/chat/src/components/composer/chip.ts @@ -0,0 +1,58 @@ +import { + disabledInkClasses, + composerControlClasses, + mergeComposerClasses, +} from '@librechat/client'; + +export type ComposerChipClasses = { + chipClasses: string; + infoChipClasses: string; + chipMenuClasses: string; + chipMenuHeadingClasses: string; + chipMenuItemClasses: (selected?: boolean) => string; +}; + +/** + * Pills and menus for the composer's context rail. Built per call: the control recipe + * is read then, and the pill's height, gap, and type replace that recipe's own. + */ +export function composerChipClasses(): ComposerChipClasses { + const chipClasses = mergeComposerClasses( + composerControlClasses(), + 'h-8 max-w-full min-w-0 gap-1.5 px-2.5 text-xs', + 'focus-visible:ring-2 focus-visible:ring-text-primary focus-visible:outline-hidden', + ); + const infoChipClasses = mergeComposerClasses( + chipClasses, + 'border-transparent bg-surface-tertiary text-text-secondary hover:bg-surface-tertiary', + ); + const chipMenuClasses = [ + 'z-50 flex max-w-[min(340px,calc(100vw-2rem))] min-w-[240px] flex-col rounded-theme-popover', + 'border-border-menu bg-surface-menu max-h-[var(--popover-available-height)] overflow-y-auto border p-1 shadow-lg', + 'origin-bottom-left translate-y-1 scale-95 opacity-0', + 'transition duration-theme-normal ease-out motion-reduce:transition-none', + 'data-[enter]:translate-y-0 data-[enter]:scale-100 data-[enter]:opacity-100', + 'data-[leave]:duration-theme-fast data-[leave]:ease-in', + ].join(' '); + const chipMenuHeadingClasses = 'px-2.5 pt-2 pb-1 text-xs font-semibold text-text-secondary'; + const chipMenuItemClasses = (selected = false): string => { + const classes = [ + 'group flex w-full cursor-pointer items-center gap-2.5 rounded-lg px-2.5 py-1.5', + 'outline-hidden transition-colors duration-theme-fast', + 'hover:bg-surface-hover data-[active-item]:bg-surface-hover', + 'aria-disabled:cursor-not-allowed aria-disabled:opacity-50', + disabledInkClasses, + ]; + if (selected) { + classes.push('bg-surface-active-alt'); + } + return classes.join(' '); + }; + return { + chipClasses, + infoChipClasses, + chipMenuClasses, + chipMenuHeadingClasses, + chipMenuItemClasses, + }; +} diff --git a/packages/client/src/utils/composer.ts b/packages/client/src/utils/composer.ts index 1af92def2a..a4345798cd 100644 --- a/packages/client/src/utils/composer.ts +++ b/packages/client/src/utils/composer.ts @@ -1,3 +1,4 @@ +import type { ClassValue } from 'clsx'; import { disabledFillClasses } from './theme'; import { cn } from './utils'; @@ -70,3 +71,10 @@ export const composerControlClasses = (): string => * surface is under 1.2:1 and would leave the control with no visible boundary. */ 'hover:bg-surface-hover', ); + +/** + * Merges composer class names so a later utility replaces one from the same theme group + * (`h-8` takes the place of `h-theme-control`, `gap-1.5` of `gap-theme-control-gap`). + * Chat components call this where they extend `composerControlClasses()`. + */ +export const mergeComposerClasses = (...inputs: ClassValue[]): string => cn(...inputs);