All files / src/components/chat/ClarifyForm ClarifyForm.tsx

90% Statements 72/80
81.3% Branches 87/107
77.77% Functions 21/27
90.27% Lines 65/72

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 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391                                                                  22x           11x 113x     11x 39x 39x 39x       11x       8x 8x 8x 5x 5x   3x 2x   1x       11x 13x 13x       11x         11x   11x 12x                             11x             15x 22x   15x   15x 5x         78x     15x 13x 13x 35x 35x 17x     17x   18x 3x 3x     13x       15x 3x 1x 1x   2x 2x 4x 4x   2x     15x 2x   15x                 15x             15x   15x                                                       39x   39x   39x 39x   39x                                                                                                     3x                     24x       24x                                   2x                                                                                                                                                                                                          
import {
  ClarifyAnswers,
  ClarifyQuestion,
  ClarifyRequest,
} from "@/objects/Hitl";
import { Sparkles } from "lucide-react";
import React, { useMemo, useState } from "react";
 
export type { ClarifyAnswers, ClarifyQuestion, ClarifyRequest };
 
/**
 * Renders the questions an agent asks before it answers, as real controls
 * rather than a "what did you mean?" message the user has to compose a reply
 * to: radio buttons (the agent's recommended option first, marked), check
 * boxes, and typed form fields (text, number, date).
 *
 * One question and a multi-question form are the same thing — a form is just a
 * longer `questions` list — so there is no separate single-question path.
 *
 * The server re-validates every answer (svc-core `hitl.validate_response`);
 * what it refuses comes back as `serverErrors`, keyed by question id, and is
 * shown against the question it concerns.
 */
 
interface QuestionState {
  /** Selected option values (never includes the free-text entry). */
  selected: string[];
  /** Free-text entry — the "Other" box, or the whole answer for a field. */
  other: string;
  /** Whether "Other" is engaged, so an empty box still counts as chosen. */
  otherActive: boolean;
}
 
const emptyState = (): QuestionState => ({
  selected: [],
  other: "",
  otherActive: false,
});
 
const isField = (q: ClarifyQuestion) =>
  q.kind === "text" || q.kind === "number" || q.kind === "date";
 
/** Flatten one question's state into the answer list sent to the agent. */
const toAnswer = (state: QuestionState): string[] => {
  const answer = [...state.selected];
  if (state.otherActive && state.other.trim()) answer.push(state.other.trim());
  return answer;
};
 
/** Why a typed field's value will be refused, checked before sending. */
export const fieldProblem = (
  question: ClarifyQuestion,
  value: string,
): string | null => {
  const v = value.trim();
  Iif (!v) return null;
  if (question.kind === "number") {
    const n = Number(v.replace(/,/g, ""));
    return Number.isFinite(n) ? null : "Enter a number.";
  }
  if (question.kind === "date") {
    return /^\d{4}-\d{2}-\d{2}$/.test(v) ? null : "Enter a date.";
  }
  return null;
};
 
/** Options with the recommended one(s) first, order otherwise kept. */
export const orderOptions = (question: ClarifyQuestion) =>
  [...(question.options ?? [])].sort(
    (a, b) => Number(!!b.recommended) - Number(!!a.recommended),
  );
 
const inputBase =
  "rounded-lg border border-indigo-200 dark:border-indigo-800 bg-white dark:bg-gray-900 " +
  "p-2 text-sm text-gray-700 dark:text-gray-300 placeholder:text-gray-400 " +
  "dark:placeholder:text-gray-600 focus:outline-none focus:ring-2 focus:ring-indigo-400";
 
const optionRow =
  "flex items-start gap-2.5 rounded-lg border px-2 py-1.5 cursor-pointer transition-colors";
 
const RecommendedBadge: React.FC = () => (
  <span className="inline-flex items-center gap-0.5 ml-1.5 px-1.5 py-px rounded-full text-[10px] font-semibold uppercase tracking-wide bg-indigo-100 dark:bg-indigo-900/60 text-indigo-700 dark:text-indigo-300 align-middle">
    <Sparkles className="w-2.5 h-2.5" aria-hidden />
    Recommended
  </span>
);
 
interface ClarifyFormProps {
  request: ClarifyRequest;
  onSubmit: (answers: ClarifyAnswers) => void;
  onSkip: () => void;
  disabled?: boolean;
  /** Refusals from the server, keyed by question id. */
  serverErrors?: Record<string, string>;
}
 
const ClarifyForm: React.FC<ClarifyFormProps> = ({
  request,
  onSubmit,
  onSkip,
  disabled = false,
  serverErrors = {},
}) => {
  const [states, setStates] = useState<Record<string, QuestionState>>(() =>
    Object.fromEntries(request.questions.map((q) => [q.id, emptyState()])),
  );
  const [showErrors, setShowErrors] = useState(false);
 
  const update = (id: string, patch: Partial<QuestionState>) =>
    setStates((prev) => ({
      ...prev,
      [id]: { ...(prev[id] ?? emptyState()), ...patch },
    }));
 
  const stateFor = (id: string) => states[id] ?? emptyState();
 
  /** Question id → what is wrong with it right now, if anything. */
  const problems = useMemo(() => {
    const found: Record<string, string> = {};
    for (const q of request.questions) {
      const answer = toAnswer(stateFor(q.id));
      if (q.required && answer.length === 0) {
        found[q.id] = isField(q)
          ? "Fill this in to continue, or skip the questions entirely."
          : "Choose an answer to continue, or skip the questions entirely.";
        continue;
      }
      if (isField(q) && answer[0]) {
        const problem = fieldProblem(q, answer[0]);
        if (problem) found[q.id] = problem;
      }
    }
    return found;
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [request.questions, states]);
 
  const handleSubmit = () => {
    if (Object.keys(problems).length > 0) {
      setShowErrors(true);
      return;
    }
    const answers: ClarifyAnswers = {};
    request.questions.forEach((q) => {
      const answer = toAnswer(stateFor(q.id));
      if (answer.length > 0) answers[q.id] = answer;
    });
    onSubmit(answers);
  };
 
  const selectSingle = (id: string, value: string) =>
    update(id, { selected: [value], otherActive: false });
 
  const toggleMulti = (id: string, value: string) => {
    const current = stateFor(id).selected;
    update(id, {
      selected: current.includes(value)
        ? current.filter((v) => v !== value)
        : [...current, value],
    });
  };
 
  const chooseOther = (id: string, question: ClarifyQuestion) =>
    update(id, {
      otherActive: true,
      // Radio semantics: choosing "Other" clears the options it replaces.
      ...(question.kind === "single" ? { selected: [] } : {}),
    });
 
  const scopeCheck = request.source === "scope";
 
  return (
    <div
      role="group"
      aria-label={request.title?.trim() || "Questions from the agent"}
      className="rounded-xl border border-indigo-300 dark:border-indigo-700 bg-indigo-50 dark:bg-indigo-950/40 p-4 flex flex-col gap-4 shadow-sm"
    >
      <div className="flex items-start gap-2">
        <span className="mt-0.5 flex h-5 w-5 shrink-0 items-center justify-center rounded-full bg-indigo-500 dark:bg-indigo-600 text-white text-xs font-bold">
          ?
        </span>
        <div className="flex-1 min-w-0">
          <p className="text-sm font-semibold text-indigo-800 dark:text-indigo-300 flex flex-wrap items-center gap-x-2 gap-y-1">
            {request.title?.trim() || "A couple of questions first"}
            {scopeCheck && (
              <span className="px-1.5 py-px rounded-full text-[10px] font-semibold uppercase tracking-wide bg-white/70 dark:bg-indigo-900/60 text-indigo-600 dark:text-indigo-300 border border-indigo-200 dark:border-indigo-800">
                Before starting
              </span>
            )}
          </p>
          <p className="text-xs text-indigo-700 dark:text-indigo-400 mt-0.5">
            {request.intro?.trim() ||
              "Answering these helps the agent give you the right answer."}
          </p>
        </div>
      </div>
 
      <div className="flex flex-col gap-4">
        {request.questions.map((question) => {
          const state = stateFor(question.id);
          const error =
            serverErrors[question.id] ??
            (showErrors ? problems[question.id] : undefined);
          const errorId = `${question.id}-error`;
          const fieldId = `${question.id}-field`;
 
          return (
            <fieldset
              key={question.id}
              className="flex flex-col gap-2 min-w-0"
              aria-describedby={error ? errorId : undefined}
              aria-invalid={error ? true : undefined}
            >
              <legend className="text-sm font-medium text-gray-800 dark:text-gray-200 mb-1">
                {isField(question) ? (
                  <label htmlFor={fieldId}>{question.question}</label>
                ) : (
                  question.question
                )}
                {!question.required && (
                  <span className="ml-1.5 text-xs font-normal text-gray-500 dark:text-gray-500">
                    (optional)
                  </span>
                )}
              </legend>
 
              {isField(question) ? (
                question.kind === "text" && question.multiline ? (
                  <textarea
                    id={fieldId}
                    className={`w-full resize-y ${inputBase}`}
                    rows={3}
                    placeholder={question.placeholder || "Type your answer…"}
                    value={state.other}
                    disabled={disabled}
                    onChange={(e) =>
                      update(question.id, {
                        other: e.target.value,
                        otherActive: true,
                      })
                    }
                  />
                ) : (
                  <input
                    id={fieldId}
                    // A number field is text with a decimal keypad: the
                    // browser's number input silently empties "5,000".
                    type={question.kind === "date" ? "date" : "text"}
                    inputMode={question.kind === "number" ? "decimal" : undefined}
                    className={`w-full ${question.kind === "text" ? "" : "sm:max-w-xs"} ${inputBase}`}
                    placeholder={
                      question.placeholder ||
                      (question.kind === "number" ? "0" : "Type your answer…")
                    }
                    value={state.other}
                    disabled={disabled}
                    onChange={(e) =>
                      update(question.id, {
                        other: e.target.value,
                        otherActive: true,
                      })
                    }
                  />
                )
              ) : (
                <div className="flex flex-col gap-1.5">
                  {orderOptions(question).map((option) => {
                    const checked =
                      question.kind === "single"
                        ? state.selected[0] === option.value &&
                          !state.otherActive
                        : state.selected.includes(option.value);
                    return (
                      <label
                        key={option.value}
                        className={`${optionRow} ${
                          option.recommended
                            ? "border-indigo-200 dark:border-indigo-800 bg-white/60 dark:bg-indigo-950/40"
                            : "border-transparent"
                        } hover:bg-indigo-100/60 dark:hover:bg-indigo-900/30`}
                      >
                        <input
                          type={
                            question.kind === "single" ? "radio" : "checkbox"
                          }
                          name={question.id}
                          className="mt-0.5 size-4 shrink-0 accent-indigo-600"
                          checked={checked}
                          disabled={disabled}
                          onChange={() =>
                            question.kind === "single"
                              ? selectSingle(question.id, option.value)
                              : toggleMulti(question.id, option.value)
                          }
                        />
                        <span className="min-w-0">
                          <span className="block text-sm text-gray-800 dark:text-gray-200">
                            {option.label}
                            {option.recommended && <RecommendedBadge />}
                          </span>
                          {option.description && (
                            <span className="block text-xs text-gray-500 dark:text-gray-400">
                              {option.description}
                            </span>
                          )}
                        </span>
                      </label>
                    );
                  })}
 
                  {question.allow_other && (
                    <div className="flex flex-col gap-1.5">
                      <label
                        className={`${optionRow} border-transparent hover:bg-indigo-100/60 dark:hover:bg-indigo-900/30`}
                      >
                        <input
                          type={
                            question.kind === "single" ? "radio" : "checkbox"
                          }
                          name={question.id}
                          className="mt-0.5 size-4 shrink-0 accent-indigo-600"
                          checked={state.otherActive}
                          disabled={disabled}
                          onChange={() =>
                            state.otherActive
                              ? update(question.id, {
                                  otherActive: false,
                                  other: "",
                                })
                              : chooseOther(question.id, question)
                          }
                        />
                        <span className="text-sm text-gray-800 dark:text-gray-200">
                          Other
                        </span>
                      </label>
                      {state.otherActive && (
                        <input
                          type="text"
                          autoFocus
                          aria-label={`${question.question} — other`}
                          className={`w-[calc(100%-1.75rem)] ml-7 ${inputBase}`}
                          placeholder="Tell the agent what you need…"
                          value={state.other}
                          disabled={disabled}
                          onChange={(e) =>
                            update(question.id, { other: e.target.value })
                          }
                        />
                      )}
                    </div>
                  )}
                </div>
              )}
 
              {error && (
                <p
                  id={errorId}
                  className="text-xs text-rose-600 dark:text-rose-400"
                >
                  {error}
                </p>
              )}
            </fieldset>
          );
        })}
      </div>
 
      <div className="flex flex-wrap gap-2 justify-end items-center">
        <button
          type="button"
          className="px-3 py-1.5 rounded-lg text-sm font-medium text-gray-600 dark:text-gray-400 hover:bg-gray-100 dark:hover:bg-gray-800 transition-colors disabled:opacity-50"
          disabled={disabled}
          onClick={onSkip}
        >
          Skip &amp; answer anyway
        </button>
        <button
          type="button"
          className="px-3 py-1.5 rounded-lg text-sm font-medium bg-indigo-600 hover:bg-indigo-700 text-white transition-colors disabled:opacity-50"
          disabled={disabled}
          onClick={handleSubmit}
        >
          Continue
        </button>
      </div>
    </div>
  );
};
 
export default ClarifyForm;