Skip to content

Enhanced ChatGPT Clone: Features Agents, MCP, Skills, DeepSeek, Anthropic, AWS, OpenAI, Responses API, Azure, Groq, o1, GPT-5, Mistral, OpenRouter, Vertex AI, Gemini, Artifacts, AI model switching, message search, Code Interpreter, langchain, DALL-E-3, OpenAPI Actions, Functions, Secure Multi-User Auth, Presets, open-source for self-hosting. Active

9.4 KB
Raw Blame
import { useMemo } from 'react';
import { useLocalize } from '@librechat/client';
import {
  isMacPlatform,
  bindingDisplayString,
  resolveComposerKeyDown,
} from '../../../core/shortcuts';
import { useComposerHost } from '../../../react/input';

type LocalizeFunction = ReturnType<typeof useLocalize>;

/** The effective `submitMessage` binding, reduced to what the hints need.
 *  `customized` false means the stock modifier chord applies; a customized
 *  binding replaces it, and a cleared one leaves no chord at all. */
export interface SendBinding {
  customized: boolean;
  display: string;
}

const DEFAULT_SEND_BINDING: SendBinding = { customized: false, display: '' };

export interface ComposerHintState {
  hasText: boolean;
  isSubmitting: boolean;
  /** Enter steers or queues instead of starting a turn. */
  duringRunActive: boolean;
  /** Whether the run can be reached yet. `isSubmitting` flips as soon as the
   *  user sends, but the start POST installs the generation epoch a moment
   *  later, and until it lands every chord that touches the live run refuses.
   *  Queueing is local, so it works throughout. */
  canControlGeneration: boolean;
  /** Which action Enter takes during a run, per the effective setting. */
  duringRunAction: 'steer' | 'interrupt' | 'queue';
  /** Whether the steer route can accept input right now. A paused tool
   *  approval forces the effective action to queue and refuses steers, so the
   *  live-send alternate must not be advertised through it. */
  canSteer: boolean;
  /** The composer is the answer box for a paused `ask_user_question`. */
  answerModeActive: boolean;
  uploadingCount: number;
  /** Plain Enter submits. When off, Enter inserts a newline and the modifier
   *  chord is what submits, which inverts every shortcut named below. */
  enterToSend: boolean;
  /** Which idle affordances act right now: `/` opens prompts, `@` opens the
   *  model mention, `+` attaches. The host resolves them from the same settings,
   *  permissions and attach target the composer obeys. */
  idleActions: { prompts: boolean; mentions: boolean; attach: boolean };
}

/**
 * `tip` is ambient discovery copy, true of the composer at all times. `state`
 * reports something happening right now. Only the first is worth permanent
 * space, so the two are distinguished here rather than at the call site.
 */
export type ComposerHintKind = 'tip' | 'state';

export interface ComposerHint {
  text: string;
  kind: ComposerHintKind;
}

const SEPARATOR = ' · ';

/**
 * Resolves the one line shown under the composer. Ordered most-specific first:
 * a paused question owns the composer outright, an in-flight upload is the most
 * urgent transient state, and the during-run modifiers only matter once there
 * is text for them to act on.
 *
 * Exported separately from the hook so the state matrix is testable without
 * rendering.
 */
export function composeHint(
  state: ComposerHintState,
  localize: LocalizeFunction,
  isMac: boolean,
  /** The live `submitMessage` binding, for the same reason: the send chords
   *  named below follow the customization instead of asserting the stock one. */
  sendBinding: SendBinding = DEFAULT_SEND_BINDING,
  /** Whether the keydown resolver still returns the interrupt action for the
   *  Alt+Enter chord; when a rebound submit or disabled shortcuts claim it,
   *  the hint must not name a key that does something else. */
  altEnterInterrupt: boolean = true,
): ComposerHint {
  if (state.answerModeActive) {
    return { text: localize('com_ui_composer_hint_answer'), kind: 'state' };
  }

  if (state.uploadingCount > 0) {
    return {
      text: localize(
        state.uploadingCount === 1
          ? 'com_ui_composer_hint_uploading_one'
          : 'com_ui_composer_hint_uploading',
        { count: state.uploadingCount },
      ),
      kind: 'state',
    };
  }

  if (state.duringRunActive && state.hasText) {
    const mod = isMac ? '⌘⏎' : 'Ctrl+⏎';
    const alt = isMac ? '⌥⏎' : 'Alt+⏎';
    /* A customized binding replaces the stock chord as what triggers the
       default action; it also makes the modifier's alternate route unreachable
       (`resolveComposerKeyDown` only maps it with the stock binding), so the
       alternate is named only while the stock chord still works. */
    const sendChord = sendBinding.customized ? sendBinding.display : mod;
    const isSteer = state.duringRunAction === 'steer';
    const interruptByDefault = state.duringRunAction === 'interrupt';
    /* The default action and the live submit route share this preference:
       naming plain Enter as Steer while it preempts is materially misleading. */
    let defaultAction: string;
    if (interruptByDefault) {
      defaultAction = localize('com_ui_interrupt_steer');
    } else if (isSteer) {
      defaultAction = localize('com_ui_composer_hint_steer');
    } else {
      defaultAction = localize('com_ui_composer_hint_queue_default');
    }
    const alternateAction =
      state.duringRunAction !== 'queue'
        ? `${mod} ${localize('com_ui_composer_hint_queue')}`
        : `${mod} ${localize('com_ui_composer_hint_send_now')}`;
    let chordVerb: Parameters<typeof localize>[0];
    if (interruptByDefault) {
      chordVerb = 'com_ui_interrupt_steer';
    } else if (isSteer) {
      chordVerb = 'com_ui_composer_hint_steer_verb';
    } else {
      chordVerb = 'com_ui_composer_hint_queue_verb';
    }
    const parts: string[] = [];
    if (state.enterToSend) {
      parts.push(defaultAction);
      /* The queue alternate is local and always lands; the send-now alternate
         rides the steer route, which a paused approval refuses. */
      if (!sendBinding.customized && (state.duringRunAction !== 'queue' || state.canSteer)) {
        parts.push(alternateAction);
      }
    } else if (sendChord) {
      parts.push(`${sendChord} ${localize(chordVerb)}`);
    }
    /* Until the start POST installs the generation epoch, every chord that
       reaches the live run refuses; only the default action survives, because
       queueing is local. Naming the others through that window advertises keys
       that do nothing, the same failure as pointing at an unbound shortcut. */
    if (!state.canControlGeneration) {
      return {
        text: parts[0] ?? localize('com_ui_composer_hint_running'),
        kind: 'state',
      };
    }
    /* The interrupt chord is named only while the keydown resolver still hands
       it back and the run accepts steering. Approval pauses and staged reasoning
       refuse Interrupt just like the disabled menu row. */
    const text =
      altEnterInterrupt && state.canSteer
        ? [...parts, `${alt} ${localize('com_ui_composer_hint_interrupt')}`].join(SEPARATOR)
        : parts.join(SEPARATOR);
    return {
      text: text || localize('com_ui_composer_hint_running'),
      kind: 'state',
    };
  }

  if (state.isSubmitting) {
    /* The stop button is right there, so a plain running reply advertises
       nothing under the composer; the line stays as ambient copy for screen
       readers and for users who keep tips on. */
    return { text: localize('com_ui_composer_hint_running'), kind: 'tip' };
  }

  if (state.hasText) {
    if (!state.enterToSend) {
      const mod = isMac ? '⌘⏎' : 'Ctrl+⏎';
      const sendChord = sendBinding.customized ? sendBinding.display : mod;
      /* A cleared binding leaves no key that sends: name only what Enter does
         rather than a send key that does nothing. */
      const newline = `⏎ ${localize('com_ui_composer_hint_newline')}`;
      return {
        text: sendChord
          ? [`${sendChord} ${localize('com_ui_composer_hint_send')}`, newline].join(SEPARATOR)
          : newline,
        kind: 'tip',
      };
    }
    return { text: localize('com_ui_composer_hint_typing'), kind: 'tip' };
  }

  const { prompts, mentions, attach } = state.idleActions;
  const idle = [
    prompts && localize('com_ui_composer_hint_prompts'),
    mentions && localize('com_ui_composer_hint_mentions'),
    attach && localize('com_ui_composer_hint_attach'),
  ].filter((part): part is string => typeof part === 'string');
  return { text: idle.join(SEPARATOR), kind: 'tip' };
}

export default function useComposerHint(state: ComposerHintState): ComposerHint {
  const localize = useLocalize();
  const { useComposerBindings } = useComposerHost();
  const { shortcutsEnabled, submitOverride, yieldedChords } = useComposerBindings();
  const sendBinding = useMemo<SendBinding>(
    () => ({
      customized: submitOverride !== undefined,
      display: submitOverride ? bindingDisplayString(submitOverride, isMacPlatform) : '',
    }),
    [submitOverride],
  );
  /* The same verdict the during-run send button reads, so the hint and the
     button can never disagree about whether Alt+Enter still interrupts. */
  const altEnterInterrupt = useMemo(
    () =>
      resolveComposerKeyDown(
        {
          key: 'Enter',
          altKey: true,
          ctrlKey: false,
          metaKey: false,
          shiftKey: false,
        },
        {
          isComposing: false,
          isSubmitting: true,
          allowSubmitWhileGenerating: true,
          hasDuringRunModifier: true,
          shortcutsEnabled,
          enterToSend: state.enterToSend,
          submitOverride,
          yieldedChords,
        },
      ) === 'interrupt',
    [shortcutsEnabled, state.enterToSend, submitOverride, yieldedChords],
  );
  return composeHint(state, localize, isMacPlatform, sendBinding, altEnterInterrupt);
}