All files / src/components/chat ChatInput.tsx

64.15% Statements 34/53
63.63% Branches 21/33
69.23% Functions 9/13
63.46% Lines 33/52

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301                                8x                 138x 6x   132x 132x                                                                                                                               138x     138x 138x 138x     138x 138x     138x     99x 1x 1x       138x         97x                                                                                                               138x 138x   138x     138x 1x       1x 1x     1x 1x                                     138x           138x 13x                                       13x                                   125x 61x                                   64x                                                    
import {
  useState,
  useLayoutEffect,
  useRef,
  type FormEvent,
  type KeyboardEvent,
  type JSX,
} from "react";
import type { ToastVariant } from "../../context/ToastContext.js";
import type { Environment, PersonaData } from "../../hooks/types.js";
import styles from "./ChatInput.module.scss";
 
/**
 * Maximum height (px) the composer grows to before scrolling internally.
 * Must stay in sync with `max-height` on `.textarea` in ChatInput.module.scss.
 */
const MAX_COMPOSER_HEIGHT_PX: number = 200;
 
// --- Helpers ---
 
/** Returns true when the environment with the given ID is disconnected or in error. */
function isEnvDisconnected(
  environmentId: string | undefined,
  environments: Environment[],
): boolean {
  if (!environmentId) {
    return false;
  }
  const env = environments.find((e) => e.id === environmentId);
  return env !== undefined && (env.status === "disconnected" || env.status === "error");
}
 
// --- Subcomponents ---
 
interface DisconnectedBannerProps {
  environmentId: string;
  onReconnect: (envId: string) => void;
}
 
/** Hint + Reconnect button shown when the task/session environment is unreachable. */
function DisconnectedBanner({ environmentId, onReconnect }: DisconnectedBannerProps): JSX.Element {
  return (
    <>
      <span className={styles.disconnectHint} data-testid="env-disconnect-hint">
        Environment unavailable
      </span>
      <button
        type="button"
        onClick={() => onReconnect(environmentId)}
        className={styles.btnGhost}
        data-testid="reconnect-btn"
        title="Reconnect the environment to resume messaging"
      >
        Reconnect
      </button>
    </>
  );
}
 
/** Props for the auto-resizing chat composer textarea. */
interface ComposerTextAreaProps {
  /** Current text value. */
  value: string;
  /** Called on every keystroke with the new value. */
  onChange: (value: string) => void;
  /** Called when the user submits via Ctrl/Cmd+Enter. */
  onSubmit: () => void;
  /** Placeholder text shown when empty. */
  placeholder: string;
  /** Whether the textarea is disabled. */
  disabled?: boolean;
  /** Whether to auto-focus the textarea on mount. */
  autoFocus?: boolean;
  /** Accessible label for the textarea. */
  ariaLabel: string;
}
 
/**
 * Auto-resizing multiline chat composer.
 *
 * Enter inserts a newline; Ctrl/Cmd+Enter submits (the Send button submits too).
 * The textarea grows with its content up to {@link MAX_COMPOSER_HEIGHT_PX}, then
 * scrolls internally.
 */
function ComposerTextArea({
  value,
  onChange,
  onSubmit,
  placeholder,
  disabled,
  autoFocus,
  ariaLabel,
}: ComposerTextAreaProps): JSX.Element {
  const ref = useRef<HTMLTextAreaElement>(null);
 
  // Auto-resize: collapse to measure natural height, then grow to fit (capped).
  useLayoutEffect(() => {
    const el = ref.current;
    Iif (!el) {
      return;
    }
    el.style.height = "auto";
    el.style.height = `${Math.min(el.scrollHeight, MAX_COMPOSER_HEIGHT_PX)}px`;
  }, [value]);
 
  const handleKeyDown = (e: KeyboardEvent<HTMLTextAreaElement>): void => {
    // Ctrl/Cmd+Enter submits; plain Enter falls through to insert a newline.
    // The isComposing guard avoids submitting mid-IME composition (e.g. CJK input).
    if (e.key === "Enter" && (e.metaKey || e.ctrlKey) && !e.nativeEvent.isComposing) {
      e.preventDefault();
      onSubmit();
    }
  };
 
  return (
    <textarea
      ref={ref}
      rows={1}
      value={value}
      onChange={(e) => onChange(e.target.value)}
      onKeyDown={handleKeyDown}
      placeholder={placeholder}
      disabled={disabled}
      autoFocus={autoFocus}
      className={styles.textarea}
      aria-label={ariaLabel}
    />
  );
}
 
// --- Main component ---
 
/** Chat input mode determines the action performed on submit. */
export interface ChatInputProps {
  /** "send" = sendInput to existing session, "spawn" = create new session, "start" = start a task */
  mode: "send" | "spawn" | "start";
  /** Session ID to send input to (mode="send") */
  sessionId?: string;
  /** Environment ID (mode="spawn" and "start") */
  environmentId?: string;
  /** Task ID to start (mode="start") */
  taskId?: string;
  /** Show persona selector dropdown (mode="spawn") */
  showPersonaSelect?: boolean;
  /** All personas (for persona selector in spawn mode). */
  personas: PersonaData[];
  /** All environments (for disconnect detection). */
  environments: Environment[];
  /** Send text input to an existing session. */
  onSendInput: (sessionId: string, text: string) => void;
  /** Spawn a new session. */
  onSpawn: (environmentId: string, prompt: string, personaId?: string) => void;
  /** Start a task. */
  onStartTask: (taskId: string, personaId?: string, environmentId?: string, notes?: string) => void;
  /** Reconnect a disconnected environment. */
  onProvisionEnvironment: (environmentId: string) => void;
  /** Display a toast notification. */
  onShowToast?: (message: string, variant?: ToastVariant) => void;
}
 
/** Reusable form component for sending messages to agent sessions. */
export function ChatInput({
  mode,
  sessionId,
  environmentId,
  taskId,
  showPersonaSelect,
  personas,
  environments,
  onSendInput,
  onSpawn,
  onStartTask,
  onProvisionEnvironment,
  onShowToast,
}: ChatInputProps): JSX.Element {
  const [text, setText] = useState("");
  const [spawnPersonaId, setSpawnPersonaId] = useState("");
 
  const envDisconnected = isEnvDisconnected(environmentId, environments);
 
  /** Performs the mode-specific submit action. Called by the form and Ctrl/Cmd+Enter. */
  const submit = (): void => {
    Iif (!text.trim()) {
      return;
    }
 
    if (mode === "send") {
      Iif (!sessionId || envDisconnected) {
        return;
      }
      onSendInput(sessionId, text);
      setText("");
    E} else if (mode === "spawn") {
      Iif (!environmentId) {
        return;
      }
      onSpawn(environmentId, text, spawnPersonaId);
      onShowToast?.("Session started", "success");
      setText("");
      setSpawnPersonaId("");
    } else {
      // mode === "start"
      Iif (!taskId) {
        return;
      }
      onStartTask(taskId, undefined, environmentId, text);
      setText("");
    }
  };
 
  const handleSubmit = (e: FormEvent): void => {
    e.preventDefault();
    submit();
  };
 
  // --- spawn mode ---
  if (mode === "spawn") {
    return (
      <form onSubmit={handleSubmit} className={styles.bar}>
        <span className={styles.badge}>new chat</span>
        <ComposerTextArea
          value={text}
          onChange={setText}
          onSubmit={submit}
          placeholder="Enter prompt..."
          autoFocus
          ariaLabel="Enter prompt"
        />
        {showPersonaSelect && (
          <select
            value={spawnPersonaId}
            onChange={(e) => setSpawnPersonaId(e.target.value)}
            className={styles.select}
            aria-label="Select persona"
          >
            <option value="">(Default)</option>
            {personas.map((p) => (
              <option key={p.id} value={p.id}>
                {p.name}
              </option>
            ))}
          </select>
        )}
        <button
          type="submit"
          disabled={!text.trim() || !environmentId}
          className={styles.btnPrimary}
        >
          Go
        </button>
      </form>
    );
  }
 
  // --- start mode ---
  if (mode === "start") {
    return (
      <form onSubmit={handleSubmit} className={styles.bar}>
        <ComposerTextArea
          value={text}
          onChange={setText}
          onSubmit={submit}
          placeholder="Type a message..."
          autoFocus
          ariaLabel="Type a message"
        />
        <button type="submit" disabled={!text.trim()} className={styles.btnPrimary}>
          Send
        </button>
      </form>
    );
  }
 
  // --- send mode ---
  return (
    <form onSubmit={handleSubmit} className={styles.bar}>
      {envDisconnected && environmentId && (
        <DisconnectedBanner environmentId={environmentId} onReconnect={onProvisionEnvironment} />
      )}
      <ComposerTextArea
        value={text}
        onChange={setText}
        onSubmit={submit}
        placeholder="Type a message..."
        autoFocus={!envDisconnected}
        disabled={envDisconnected}
        ariaLabel="Type a message"
      />
      <span title={envDisconnected ? "Environment is unavailable — reconnect first" : undefined}>
        <button
          type="submit"
          disabled={!text.trim() || envDisconnected}
          className={styles.btnPrimary}
        >
          Send
        </button>
      </span>
    </form>
  );
}