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.

6.4 KB
Raw Blame
import {
  type MessageContextAccounting,
  type OpenAIChatMessage,
  type UIChatMessage,
  type VoiceMessageRecording,
} from '@lobechat/types';
import { type IEditor, type SlashOptions } from '@lobehub/editor';
import { type ChatInputProps } from '@lobehub/editor/react';

import { type ActionKeys } from '@/features/ChatInput';

export type SendButtonHandler = (params: {
  clearContent: () => void;
  editor: IEditor;
  getEditorData: () => Record<string, any> | undefined;
  getMarkdownContent: () => string;
}) => Promise<void> | void;

export type VoiceMessageSendHandler = (recording: VoiceMessageRecording) => boolean;

export interface SendButtonProps {
  disabled?: boolean;
  generating: boolean;
  /**
   * The host already shows the run elsewhere (e.g. the conversation status tray),
   * so the send area skips its own running spinner.
   */
  hideRunningIndicator?: boolean;
  /**
   * A send was committed but has not reached the agent yet (the message and its
   * topic are still being created). Send shows as loading instead of Stop: there
   * is no run to stop until the message is accepted.
   */
  loading?: boolean;
  onStop: (params: { editor: IEditor }) => void;
  shape?: 'round' | 'default';
  /**
   * While `generating`, render a Send button beside Stop so a follow-up can be
   * sent without hiding the running indicator. Only hosts whose `onSend`
   * accepts sends during generation (e.g. by queueing) should enable this.
   */
  showSendWhileGenerating?: boolean;
  size?: number;
}

export const initialSendButtonState: SendButtonProps = {
  disabled: false,
  generating: false,
  onStop: () => {},
};

export type SlashPlacement = 'top' | 'bottom';

/**
 * What the conversation's next request carries before the composer draft, for
 * the context breakdown (see `getContextWindow`).
 */
export interface ContextWindow {
  /** The history window the next request includes, as the history count slices it. */
  history: UIChatMessage[];
  /** The latest request the agent runtime recorded in this conversation. */
  request?: {
    accounting: MessageContextAccounting;
    /** Provider-reported input tokens of that request, when known. */
    inputTokens?: number;
    /**
     * Messages added since: the recorded reply itself and everything after it.
     * Absent when a history count re-truncates every request; the recorded
     * messages may then drop out, so count `history` instead.
     */
    messages?: UIChatMessage[];
    /** Model and provider that request went to. */
    model?: string;
    provider?: string;
  };
}

export interface ChatInputFeature {
  inputCompletion?: boolean;
  inputHistory?: boolean;
  mention?: boolean;
  slash?: boolean;
}

export interface InputCompletionError {
  body?: unknown;
  errorType?: string;
  httpStatus?: number;
  message: string;
}

export const DEFAULT_CHAT_INPUT_FEATURE = {
  inputCompletion: true,
  inputHistory: true,
  mention: true,
  slash: true,
} as const satisfies Required<ChatInputFeature>;

export interface PublicState {
  activeAudioInputMode?: 'dictation' | 'voiceMessage';
  agentId?: string;
  allowExpand?: boolean;
  canRecordVoiceMessage?: boolean;
  contextSelectionKey?: string;
  contextWindow?: ContextWindow;
  draftKey?: string;
  expand?: boolean;
  feature?: ChatInputFeature;
  getMessages?: () => OpenAIChatMessage[];
  leftActions: ActionKeys[];
  mentionItems?: SlashOptions['items'];
  mobile?: boolean;
  onMarkdownContentChange?: (content: string) => void;
  onSend?: SendButtonHandler;
  onVoiceMessageSend?: VoiceMessageSendHandler;
  /**
   * Accept a send while this composer's attachments are still uploading: the
   * send is queued (Send shows loading) and commits once every upload settles,
   * with whatever the composer holds by then. Only hosts whose `onSend` leaves
   * failed uploads out of the message should enable this.
   */
  queueSendWhileUploading?: boolean;
  /**
   * Live send gate consulted by `handleSendButton` instead of
   * `sendButtonProps.disabled`. The disabled flag mirrors editor content
   * through the editor's debounced onChange, so a fast type→Enter arrives
   * while the mirror still reads "empty" and the send would be silently
   * dropped. Only hosts whose onSend re-validates its own gates should
   * provide this.
   */
  resolveSendBlocked?: () => boolean;
  rightActions: ActionKeys[];
  sendButtonProps?: SendButtonProps;
  showTypoBar?: boolean;
  /**
   * Slash menu placement: 'bottom' for home page (input in center), 'top' for page input (at bottom)
   */
  slashPlacement?: SlashPlacement;
  /**
   * The topic this composer belongs to, as its host conversation resolves it —
   * `null` when the host has a conversation with no topic (a page copilot
   * embedded beside another chat, a not-yet-created topic). Left `undefined` by
   * hosts that have no conversation of their own, which fall back to the global
   * `activeTopicId` (see `useTopicId`). Never read the global id directly from
   * a composer control: an embedded conversation can run against a different
   * topic than the surrounding page.
   */
  topicId?: string | null;
  /**
   * Key of this composer's upload list in the file store. Defaults to
   * `contextSelectionKey`; a host whose text draft outlives that key (Home
   * keeps its text across mode and agent switches) passes a steadier one so
   * attachments stay alongside the text.
   */
  uploadContextKey?: string;
}

export interface State extends PublicState {
  _savedEditorState?: Record<string, any>;
  editor?: IEditor;
  inputCompletionError?: InputCompletionError;
  inputCompletionErrorDismissed: boolean;
  /** Market agents/skills picked from the @ menu are being installed before the send commits. */
  installingMarketMentions: boolean;
  isContentEmpty: boolean;
  markdownContent: string;
  slashMenuRef: ChatInputProps['slashMenuRef'];
  /**
   * The send queued until the composer's uploads settle (see
   * `queueSendWhileUploading`), tagged with the draft it was made from: the
   * composer outlives a conversation switch, and the conversation it shows next
   * has nothing queued.
   */
  uploadQueuedSend?: { draftKey?: string; unsubscribe: () => void };
}

export const initialState: State = {
  activeAudioInputMode: undefined,
  allowExpand: true,
  expand: false,
  feature: DEFAULT_CHAT_INPUT_FEATURE,
  inputCompletionErrorDismissed: false,
  installingMarketMentions: false,
  isContentEmpty: false,
  leftActions: [],
  markdownContent: '',
  rightActions: [],
  slashMenuRef: { current: null },
  slashPlacement: 'top',
};