All files / src/apps/user/pages/simulations NewWorld.tsx

40.47% Statements 17/42
37.5% Branches 9/24
16.66% Functions 2/12
54.83% Lines 17/31

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                    1x   1x 1x 1x 1x   1x 1x 1x 1x 1x 1x 1x   1x                                                     1x 1x   1x                                                                                               2x                                                                                                                                                                  
import MainPage from "@/components/page/MainPage/MainPage";
import { SimulationStatus } from "@/objects/Simulation";
import { APP_ROUTES } from "@/routes/const";
import { QUERY_KEYS } from "@/services/query_keys";
import { useApiHandler } from "@/services/useApiHandler";
import { useMutation, useQueryClient } from "@tanstack/react-query";
import { ChevronLeft, Globe, Loader2 } from "lucide-react";
import React, { useState } from "react";
import { Link, useNavigate } from "react-router-dom";
 
const STATUSES: SimulationStatus[] = ["draft", "active"];
 
const NewWorld: React.FC = () => {
  const { getApiHandler } = useApiHandler();
  const queryClient = useQueryClient();
  const navigate = useNavigate();
 
  const [name, setName] = useState("");
  const [description, setDescription] = useState("");
  const [status, setStatus] = useState<SimulationStatus>("draft");
  const [rules, setRules] = useState("");
  const [logic, setLogic] = useState("");
  const [rulesError, setRulesError] = useState("");
  const [logicError, setLogicError] = useState("");
 
  const createMutation = useMutation({
    mutationFn: () => {
      let parsedRules: Record<string, unknown> | undefined;
      let parsedLogic: Record<string, unknown> | undefined;
 
      if (rules.trim()) {
        try { parsedRules = JSON.parse(rules); } catch { setRulesError("Invalid JSON"); return Promise.resolve(null); }
      }
      if (logic.trim()) {
        try { parsedLogic = JSON.parse(logic); } catch { setLogicError("Invalid JSON"); return Promise.resolve(null); }
      }
 
      return getApiHandler().simulation_router.createWorld({
        name: name.trim(),
        description: description.trim() || undefined,
        status,
        rules: parsedRules,
        logic: parsedLogic,
      });
    },
    onSuccess: (world) => {
      if (!world) return;
      queryClient.invalidateQueries({ queryKey: [QUERY_KEYS.GET.SIMULATION_WORLDS] });
      navigate(APP_ROUTES.USER.INFERENCE.agents);
    },
  });
 
  const handleRulesChange = (v: string) => { setRules(v); setRulesError(""); };
  const handleLogicChange = (v: string) => { setLogic(v); setLogicError(""); };
 
  return (
    <MainPage title="New Simulation World" description="Define a game-theoretic environment for agent simulations.">
      <Link
        to={APP_ROUTES.USER.INFERENCE.agents}
        className="inline-flex items-center gap-1 text-xs text-gray-400 dark:text-gray-500 hover:text-gray-700 dark:hover:text-gray-300 transition-colors mb-6"
      >
        <ChevronLeft className="size-3" />
        Worlds
      </Link>
 
      <div className="max-w-2xl space-y-5">
        {/* Core fields */}
        <div className="rounded-xl border border-gray-200 dark:border-gray-700 bg-white dark:bg-gray-800 p-5 space-y-4">
          <div className="flex items-center gap-2 pb-2 border-b border-gray-100 dark:border-gray-700">
            <Globe className="size-4 text-gray-500 dark:text-gray-400" />
            <h3 className="text-sm font-semibold text-gray-700 dark:text-gray-300">World Details</h3>
          </div>
 
          <div>
            <label className="block text-xs font-medium text-gray-600 dark:text-gray-400 mb-1">
              Name <span className="text-red-400">*</span>
            </label>
            <input
              autoFocus
              className="w-full rounded-lg border border-gray-200 dark:border-gray-600 bg-gray-50 dark:bg-gray-700 px-3 py-2 text-sm text-gray-900 dark:text-gray-100 focus:outline-none focus:ring-2 focus:ring-gray-400 dark:focus:ring-gray-500"
              placeholder="e.g. Prisoner's Dilemma Arena"
              value={name}
              onChange={(e) => setName(e.target.value)}
            />
          </div>
 
          <div>
            <label className="block text-xs font-medium text-gray-600 dark:text-gray-400 mb-1">
              Description <span className="text-gray-400">(optional)</span>
            </label>
            <textarea
              rows={3}
              className="w-full rounded-lg border border-gray-200 dark:border-gray-600 bg-gray-50 dark:bg-gray-700 px-3 py-2 text-sm text-gray-900 dark:text-gray-100 focus:outline-none focus:ring-2 focus:ring-gray-400 dark:focus:ring-gray-500 resize-none"
              placeholder="Describe the world's purpose and context…"
              value={description}
              onChange={(e) => setDescription(e.target.value)}
            />
          </div>
 
          <div>
            <label className="block text-xs font-medium text-gray-600 dark:text-gray-400 mb-1">Status</label>
            <div className="flex gap-2">
              {STATUSES.map((s) => (
                <button
                  key={s}
                  onClick={() => setStatus(s)}
                  className={`px-3 py-1.5 rounded-lg text-xs font-medium border transition-colors capitalize ${
                    status === s
                      ? "bg-gray-900 dark:bg-white text-white dark:text-gray-900 border-gray-900 dark:border-white"
                      : "border-gray-200 dark:border-gray-600 text-gray-600 dark:text-gray-400 hover:bg-gray-50 dark:hover:bg-gray-700"
                  }`}
                >
                  {s}
                </button>
              ))}
            </div>
          </div>
        </div>
 
        {/* Rules & Logic */}
        <div className="rounded-xl border border-gray-200 dark:border-gray-700 bg-white dark:bg-gray-800 p-5 space-y-4">
          <div className="flex items-center gap-2 pb-2 border-b border-gray-100 dark:border-gray-700">
            <h3 className="text-sm font-semibold text-gray-700 dark:text-gray-300">Game Logic</h3>
            <span className="text-xs text-gray-400 dark:text-gray-500">(optional — JSON)</span>
          </div>
 
          <div>
            <label className="block text-xs font-medium text-gray-600 dark:text-gray-400 mb-1">Rules</label>
            <p className="text-xs text-gray-400 dark:text-gray-500 mb-2">
              Game-theoretic rules governing how agents interact (payoff matrices, constraints, win conditions).
            </p>
            <textarea
              rows={5}
              className={`w-full rounded-lg border font-mono bg-gray-50 dark:bg-gray-700 px-3 py-2 text-xs text-gray-900 dark:text-gray-100 focus:outline-none focus:ring-2 focus:ring-gray-400 dark:focus:ring-gray-500 resize-none ${
                rulesError ? "border-red-300 dark:border-red-700" : "border-gray-200 dark:border-gray-600"
              }`}
              placeholder={'{\n  "payoff_matrix": {},\n  "win_condition": "max_score"\n}'}
              value={rules}
              onChange={(e) => handleRulesChange(e.target.value)}
            />
            {rulesError && <p className="text-xs text-red-500 mt-1">{rulesError}</p>}
          </div>
 
          <div>
            <label className="block text-xs font-medium text-gray-600 dark:text-gray-400 mb-1">Logic</label>
            <p className="text-xs text-gray-400 dark:text-gray-500 mb-2">
              Environment constraints and world logic applied to every simulation run.
            </p>
            <textarea
              rows={5}
              className={`w-full rounded-lg border font-mono bg-gray-50 dark:bg-gray-700 px-3 py-2 text-xs text-gray-900 dark:text-gray-100 focus:outline-none focus:ring-2 focus:ring-gray-400 dark:focus:ring-gray-500 resize-none ${
                logicError ? "border-red-300 dark:border-red-700" : "border-gray-200 dark:border-gray-600"
              }`}
              placeholder={'{\n  "max_rounds": 10,\n  "turn_order": "sequential"\n}'}
              value={logic}
              onChange={(e) => handleLogicChange(e.target.value)}
            />
            {logicError && <p className="text-xs text-red-500 mt-1">{logicError}</p>}
          </div>
        </div>
 
        {/* Actions */}
        <div className="flex items-center justify-end gap-3">
          <Link
            to={APP_ROUTES.USER.INFERENCE.agents}
            className="px-4 py-2 text-sm text-gray-600 dark:text-gray-400 hover:text-gray-900 dark:hover:text-gray-100 transition-colors"
          >
            Cancel
          </Link>
          <button
            disabled={!name.trim() || createMutation.isPending}
            onClick={() => createMutation.mutate()}
            className="flex items-center gap-1.5 px-5 py-2 rounded-lg bg-gray-900 dark:bg-white text-white dark:text-gray-900 text-sm font-medium hover:opacity-80 transition-opacity disabled:opacity-40"
          >
            {createMutation.isPending && <Loader2 className="size-3.5 animate-spin" />}
            {createMutation.isPending ? "Creating…" : "Create World"}
          </button>
        </div>
      </div>
    </MainPage>
  );
};
 
export default NewWorld;