All files / src/apps/user/pages/swarms RequestForm.tsx

47.22% Statements 34/72
59.01% Branches 36/61
33.33% Functions 12/36
55.17% Lines 32/58

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                                      3x     3x                                     3x                       34x 34x 34x 34x 34x 34x     34x 34x 34x 34x 34x 34x   34x   10x   34x 34x 34x 9x     34x 1x 1x         34x                                             34x 4x         1x       34x               4x                                                   3x                                                                                                                                                                                                                       1x                                                                      
import AttachMenu from "@/components/chat/ChatPanel/AttachMenu";
import type { SwarmDefaults, SwarmFollowUp, SwarmRefusal } from "@/objects/Swarm";
import type { UploadedFileRef } from "@/services/api/routers/FileRouter";
import { QUERY_KEYS } from "@/services/query_keys";
import { useApiHandler } from "@/services/useApiHandler";
import { uploadAndRead } from "@/util/chatAttachments";
import { useQuery, useQueryClient } from "@tanstack/react-query";
import { AlertCircle, FileText, Loader2, Send, X } from "lucide-react";
import React, { useMemo, useRef, useState } from "react";
 
/**
 * What a swarm is sent on — a first request, or a follow-up of a run: the
 * request, the person's documents (uploaded, or from the workspace's
 * library), a run's settings starting from the swarm's defaults, and for a
 * follow-up whether the earlier requests' documents go too. One form for
 * both, so sending and following up never differ.
 */
 
/** The documents one request may carry (svc-core `engine.MAX_FILES`). */
export const MAX_FILES = 10;
 
const inputBase =
  "w-full px-3 py-2 text-sm rounded-lg border border-gray-200 dark:border-gray-600 bg-white dark:bg-gray-800 text-gray-800 dark:text-gray-200 placeholder-gray-400 focus:outline-none focus:ring-2 focus:ring-gray-300 dark:focus:ring-gray-500";
 
export interface RequestFormProps {
  defaults: Partial<SwarmDefaults>;
  /** Whether the swarm's shape plans, so a plan may wait for approval. */
  plans: boolean;
  /** The request box's name, for a screen reader and a test. */
  label: string;
  placeholder: string;
  sendLabel: string;
  /** For a follow-up: how many documents the earlier requests carried,
   *  which it may keep. */
  carried?: number;
  pending: boolean;
  refusal: SwarmRefusal | null;
  onSend: (body: SwarmFollowUp) => void;
  note?: React.ReactNode;
}
 
const RequestForm: React.FC<RequestFormProps> = ({
  defaults,
  plans,
  label,
  placeholder,
  sendLabel,
  carried,
  pending,
  refusal,
  onSend,
  note,
}) => {
  const { getApiHandler } = useApiHandler();
  const queryClient = useQueryClient();
  const picker = useRef<HTMLInputElement>(null);
  const [task, setTask] = useState("");
  const [budget, setBudget] = useState(String(defaults.budget_usd ?? 2));
  const [minutes, setMinutes] = useState(
    String(Math.round((defaults.time_cap_s ?? 1800) / 60)),
  );
  const [approval, setApproval] = useState(defaults.require_approval ?? true);
  const [keep, setKeep] = useState(true);
  const [files, setFiles] = useState<UploadedFileRef[]>([]);
  const [uploading, setUploading] = useState<string[]>([]);
  const [uploadError, setUploadError] = useState<string | null>(null);
  const [libraryOpen, setLibraryOpen] = useState(false);
 
  const { data: library = [] } = useQuery<UploadedFileRef[]>({
    queryKey: [QUERY_KEYS.GET.UPLOADED_FILES],
    queryFn: () => getApiHandler().file_router.listFiles(),
  });
  const attachedIds = useMemo(() => new Set(files.map((f) => f.id)), [files]);
  const full = files.length + uploading.length >= MAX_FILES;
  const offered = library.filter(
    (doc: UploadedFileRef) => (doc.status ?? "ready") === "ready" && !attachedIds.has(doc.id),
  );
 
  const attach = (doc: UploadedFileRef) =>
    setFiles((current) =>
      current.some((f) => f.id === doc.id) || current.length >= MAX_FILES
        ? current
        : [...current, doc],
    );
 
  const upload = async (chosen: File[]) => {
    setUploadError(null);
    const room = Math.max(MAX_FILES - files.length - uploading.length, 0);
    const taken = chosen.slice(0, room);
    setUploading((names) => [...names, ...taken.map((f) => f.name)]);
    const results = await Promise.allSettled(
      taken.map((file) => uploadAndRead(getApiHandler().file_router, file)),
    );
    setUploading((names) => names.filter((n) => !taken.some((f) => f.name === n)));
    results.forEach((result) => {
      if (result.status === "fulfilled" && result.value) attach(result.value);
    });
    const failed = results.filter((r) => r.status === "rejected").length;
    if (failed || chosen.length > taken.length) {
      setUploadError(
        failed
          ? `${failed === 1 ? "One document" : `${failed} documents`} could not be read.`
          : `A request takes ${MAX_FILES} documents at most.`,
      );
    }
    void queryClient.invalidateQueries({ queryKey: [QUERY_KEYS.GET.UPLOADED_FILES] });
  };
 
  const send = () =>
    onSend({
      task: task.trim(),
      budget_usd: Number(budget),
      time_cap_s: Math.round(Number(minutes) * 60),
      ...(plans ? { require_approval: approval } : {}),
      ...(files.length ? { file_ids: files.map((f) => f.id) } : {}),
      ...(carried ? { carry_files: keep } : {}),
    });
 
  return (
    <div className="space-y-3">
      <textarea
        aria-label={label}
        rows={4}
        className={`${inputBase} resize-y`}
        placeholder={placeholder}
        value={task}
        onChange={(e) => setTask(e.target.value)}
      />
 
      <div className="flex flex-wrap items-center gap-2">
        <AttachMenu
          onUpload={() => picker.current?.click()}
          canUpload={!full}
          documents={full ? [] : library}
          attachedIds={attachedIds}
          onAttach={attach}
          documentsOpen={libraryOpen}
          onToggleDocuments={() => setLibraryOpen((open) => !open)}
        />
        <input
          ref={picker}
          type="file"
          multiple
          hidden
          aria-label="Upload documents"
          onChange={(e) => {
            const chosen = Array.from(e.target.files ?? []);
            e.target.value = "";
            if (chosen.length) void upload(chosen);
          }}
        />
        {files.map((file) => (
          <span
            key={file.id}
            className="flex items-center gap-1 rounded-md border border-gray-200 dark:border-gray-600 bg-gray-50 dark:bg-gray-700/50 px-2 py-1 text-xs text-gray-700 dark:text-gray-200"
          >
            <FileText className="size-3 text-gray-400" />
            <span className="max-w-[12rem] truncate">{file.name}</span>
            <button
              type="button"
              aria-label={`Remove ${file.name}`}
              onClick={() => setFiles((current) => current.filter((f) => f.id !== file.id))}
              className="text-gray-400 hover:text-gray-700 dark:hover:text-gray-200"
            >
              <X className="size-3" />
            </button>
          </span>
        ))}
        {uploading.map((name) => (
          <span
            key={name}
            className="flex items-center gap-1 rounded-md border border-dashed border-gray-200 dark:border-gray-600 px-2 py-1 text-xs text-gray-500"
          >
            <Loader2 className="size-3 animate-spin" />
            <span className="max-w-[12rem] truncate">{name}</span>
          </span>
        ))}
        {files.length === 0 && uploading.length === 0 && (
          <span className="text-xs text-gray-400 dark:text-gray-500">
            Attach documents every agent in the team reads.
          </span>
        )}
      </div>
 
      {libraryOpen && (
        <div
          role="region"
          aria-label="Your documents"
          className="max-h-48 overflow-y-auto rounded-lg border border-gray-100 dark:border-gray-700 divide-y divide-gray-100 dark:divide-gray-700"
        >
          {offered.length === 0 ? (
            <p className="px-3 py-2 text-xs italic text-gray-400">
              No other documents in this workspace.
            </p>
          ) : (
            offered.map((doc: UploadedFileRef) => (
              <div key={doc.id} className="flex items-center gap-2 px-3 py-1.5 text-xs">
                <FileText className="size-3 shrink-0 text-gray-400" />
                <span className="min-w-0 flex-1 truncate text-gray-700 dark:text-gray-200">
                  {doc.name}
                </span>
                <button
                  type="button"
                  disabled={full}
                  onClick={() => attach(doc)}
                  className="rounded-md border border-gray-200 dark:border-gray-600 px-2 py-0.5 text-gray-600 dark:text-gray-300 hover:bg-gray-50 dark:hover:bg-gray-700 disabled:opacity-50"
                >
                  Attach
                </button>
              </div>
            ))
          )}
        </div>
      )}
 
      {uploadError && (
        <p role="alert" className="text-xs text-red-600 dark:text-red-400">
          {uploadError}
        </p>
      )}
 
      <div className="flex flex-wrap items-end gap-3">
        <label className="text-xs text-gray-600 dark:text-gray-300">
          Budget ($)
          <input
            type="number"
            min={0.05}
            step={0.05}
            className={`${inputBase} mt-1 w-28`}
            value={budget}
            onChange={(e) => setBudget(e.target.value)}
          />
        </label>
        <label className="text-xs text-gray-600 dark:text-gray-300">
          Time cap (minutes)
          <input
            type="number"
            min={5}
            max={480}
            className={`${inputBase} mt-1 w-28`}
            value={minutes}
            onChange={(e) => setMinutes(e.target.value)}
          />
        </label>
        <div className="flex flex-col gap-1.5 pb-2">
          {plans && (
            <label className="flex items-center gap-2 text-xs text-gray-600 dark:text-gray-300">
              <input
                type="checkbox"
                checked={approval}
                onChange={(e) => setApproval(e.target.checked)}
              />
              Approve the plan first
            </label>
          )}
          {!!carried && (
            <label className="flex items-center gap-2 text-xs text-gray-600 dark:text-gray-300">
              <input
                type="checkbox"
                checked={keep}
                onChange={(e) => setKeep(e.target.checked)}
              />
              Keep the documents from earlier requests ({carried})
            </label>
          )}
        </div>
        <button
          type="button"
          disabled={!task.trim() || pending || uploading.length > 0}
          onClick={send}
          className="ml-auto flex items-center gap-1.5 px-4 py-2 rounded-lg bg-gray-900 dark:bg-white text-white dark:text-gray-900 text-sm font-medium hover:opacity-80 disabled:opacity-50"
        >
          {pending ? <Loader2 className="size-4 animate-spin" /> : <Send className="size-4" />}
          {sendLabel}
        </button>
      </div>
      {note && <p className="text-[11px] text-gray-400 dark:text-gray-500">{note}</p>}
      {refusal && (
        <div className="flex items-start gap-2 px-3 py-2 rounded-lg bg-red-50 dark:bg-red-950/40 border border-red-200 dark:border-red-800 text-red-700 dark:text-red-300 text-xs">
          <AlertCircle className="size-3.5 shrink-0 mt-0.5" />
          <div>
            {refusal.message}
            {Object.entries(refusal.fields).map(([field, reason]) => (
              <div key={field}>
                <span className="font-mono">{field}</span>: {reason}
              </div>
            ))}
          </div>
        </div>
      )}
    </div>
  );
};
 
export default RequestForm;