All files / src/apps/user/pages/settings ScenarioRuns.tsx

88.88% Statements 64/72
77.02% Branches 57/74
95.65% Functions 22/23
92.42% Lines 61/66

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                                                      2x     2x           2x                     2x       9x 9x 9x 1x 9x   1x 1x       9x   1x         9x 9x 9x       9x                                   1x                               1x             1x                                                           7x                           2x 33x 33x 33x 33x 33x 33x   33x   13x   79x       33x 2x   33x   2x 2x 2x 1x 1x   1x 1x 1x 1x     33x   1x 1x     1x 1x       33x 3x 3x       3x 3x           33x 33x 33x   33x                                                               3x                                 2x                                                     7x                                   1x                  
import React, { useRef, useState } from "react";
import { Link } from "react-router-dom";
import { useMutation, useQuery, useQueryClient } from "@tanstack/react-query";
import { Download, FolderOpen, Play, Square, Trash2, Upload } from "lucide-react";
import SubPage from "@/components/page/SubPage/SubPage";
import {
  ConfirmDialog,
  MeterBar,
  RUN_STATUS,
  SkeletonLines,
  StatusBadge,
  Strong,
} from "@/components/detail";
import type { ScenarioRun } from "@/objects/ScenarioRun";
import { APP_ROUTES } from "@/routes/const";
import { pathIn, workspaceRef } from "@/routes/workspace";
import {
  isRefused,
  type ScenarioRunList,
} from "@/services/api/routers/ScenarioRunRouter";
import { QUERY_KEYS } from "@/services/query_keys";
import { useApiHandler } from "@/services/useApiHandler";
import { formatLocalDate, parseServerDate } from "@/util/time";
import { fileText, readScenario, runLine, type ReadScenario } from "./scenarioFile";
import { InfoRow, SettingsSection, SettingsTabs } from "./SettingsTabs";
 
/** How often the list is read again while a run is going. */
const POLL_MS = 5000;
 
const BUTTON =
  "inline-flex items-center gap-1.5 px-2.5 py-1 rounded-lg border border-gray-300 dark:border-gray-600 text-xs text-gray-700 dark:text-gray-300 hover:bg-gray-50 dark:hover:bg-gray-700 disabled:opacity-60 transition-colors";
 
/** Why the page has nothing to offer, in the API's own terms. */
const UNAVAILABLE: Record<
  NonNullable<ScenarioRunList["unavailable"]>,
  { title: string; body: string }
> = {
  off: {
    title: "Scenario runs are switched off here",
    body: "This deployment does not run them. They are turned on per deployment with SCENARIO_RUNS_ENABLED (docs/guides/scenario-runs.md).",
  },
  forbidden: {
    title: "Scenario runs need the Developer role",
    body: "The Developer platform role is assigned in Auth0. Once it is, sign out and back in.",
  },
};
 
const RunRow: React.FC<{
  run: ScenarioRun;
  onDelete: (run: ScenarioRun) => void;
}> = ({ run, onDelete }) => {
  const { getApiHandler } = useApiHandler();
  const queryClient = useQueryClient();
  const refresh = () =>
    queryClient.invalidateQueries({ queryKey: [QUERY_KEYS.GET.SCENARIO_RUNS] });
  const cancel = useMutation({
    mutationFn: async () => {
      const result = await getApiHandler().scenario_run_router.cancel(run.id);
      Iif (isRefused(result)) throw new Error(result.refused);
    },
    onSuccess: refresh,
  });
  const download = useMutation({
    mutationFn: async () => {
      Iif (!(await getApiHandler().scenario_run_router.downloadExport(run.id))) {
        throw new Error("export failed");
      }
    },
  });
  const running = run.status === "running";
  const total = run.progress?.total ?? 0;
  const project = run.project_id
    ? pathIn(workspaceRef("project", run.project_id), APP_ROUTES.USER.INFERENCE.agents)
    : null;
 
  return (
    <div className="px-5 py-4 space-y-2" data-testid="scenario-run">
      <div className="flex flex-wrap items-center justify-between gap-2">
        <div className="min-w-0">
          <div className="flex items-center gap-2">
            <span className="text-sm font-medium text-gray-800 dark:text-gray-200 truncate">
              {run.name}
            </span>
            <StatusBadge status={run.status} scale={RUN_STATUS} size="xs" />
          </div>
          <div className="text-xs text-gray-400 dark:text-gray-500 mt-0.5">
            {formatLocalDate(parseServerDate(run.created_at))} · {runLine(run)}
          </div>
        </div>
        <div className="flex flex-wrap gap-1.5">
          <button
            type="button"
            className={BUTTON}
            onClick={() => download.mutate()}
            disabled={download.isPending}
          >
            <Download className="size-3.5" />
            {download.isPending ? "Preparing…" : "Export"}
          </button>
          {project && (
            <Link to={project} className={BUTTON}>
              <FolderOpen className="size-3.5" />
              Open project
            </Link>
          )}
          {running ? (
            <button
              type="button"
              className={BUTTON}
              onClick={() => cancel.mutate()}
              disabled={cancel.isPending || run.cancel_requested}
            >
              <Square className="size-3.5" />
              {run.cancel_requested ? "Stopping…" : "Cancel"}
            </button>
          ) : (
            <button type="button" className={BUTTON} onClick={() => onDelete(run)}>
              <Trash2 className="size-3.5" />
              Delete
            </button>
          )}
        </div>
      </div>
      {running && total > 0 && (
        <MeterBar
          share={(run.progress?.done ?? 0) / total}
          tone="ok"
          label={`${run.name}: turns done`}
        />
      )}
      {run.error && (
        <p className="text-xs text-red-600 dark:text-red-400">{run.error}</p>
      )}
      {cancel.isError && (
        <p className="text-xs text-red-600 dark:text-red-400">
          {(cancel.error as Error).message}
        </p>
      )}
      {download.isError && (
        <p className="text-xs text-red-600 dark:text-red-400">
          The export could not be downloaded. Try again.
        </p>
      )}
      {!running && (run.summary?.checks_failed.length ?? 0) > 0 && (
        <ul className="text-xs text-gray-500 dark:text-gray-400 list-disc pl-5">
          {run.summary!.checks_failed.slice(0, 5).map((c, i) => (
            <li key={`${c.where}-${c.check}-${i}`}>
              {c.where}: {c.check} expected {JSON.stringify(c.expected)}, was{" "}
              {JSON.stringify(c.actual)}
            </li>
          ))}
          {run.summary!.checks_failed.length > 5 && (
            <li>…and {run.summary!.checks_failed.length - 5} more, in the export</li>
          )}
        </ul>
      )}
    </div>
  );
};
 
const ScenarioRuns: React.FC = () => {
  const { getApiHandler } = useApiHandler();
  const queryClient = useQueryClient();
  const input = useRef<HTMLInputElement>(null);
  const [picked, setPicked] = useState<(ReadScenario & { file: string }) | null>(null);
  const [startError, setStartError] = useState<string | null>(null);
  const [deleting, setDeleting] = useState<ScenarioRun | null>(null);
 
  const listed = useQuery<ScenarioRunList>({
    queryKey: [QUERY_KEYS.GET.SCENARIO_RUNS],
    queryFn: () => getApiHandler().scenario_run_router.list(),
    refetchInterval: (query) =>
      query.state.data?.runs.some((r: ScenarioRun) => r.status === "running")
        ? POLL_MS
        : false,
  });
  const refresh = () =>
    queryClient.invalidateQueries({ queryKey: [QUERY_KEYS.GET.SCENARIO_RUNS] });
 
  const start = useMutation({
    mutationFn: async () => {
      Iif (!picked || picked.error !== null) return;
      const result = await getApiHandler().scenario_run_router.start(picked.document);
      if (isRefused(result)) {
        setStartError(result.refused);
        return;
      }
      setStartError(null);
      setPicked(null);
      Eif (input.current) input.current.value = "";
      await refresh();
    },
  });
  const remove = useMutation({
    mutationFn: async (run: ScenarioRun) => {
      const result = await getApiHandler().scenario_run_router.remove(run.id);
      Iif (isRefused(result)) throw new Error(result.refused);
    },
    onSuccess: async () => {
      setDeleting(null);
      await refresh();
    },
  });
 
  const choose = async (file: File | undefined) => {
    setStartError(null);
    Iif (!file) {
      setPicked(null);
      return;
    }
    try {
      setPicked({ ...readScenario(await fileText(file)), file: file.name });
    } catch {
      setPicked({ error: "This file could not be read.", file: file.name });
    }
  };
 
  const unavailable: ScenarioRunList["unavailable"] = listed.data?.unavailable ?? null;
  const runs: ScenarioRun[] = listed.data?.runs ?? [];
  const busy = runs.some((r) => r.status === "running");
 
  return (
    <SubPage
      title="Scenario runs"
      links={[<SettingsTabs key="tabs" active="scenarios" />]}
    >
      <div className="max-w-2xl space-y-6">
        {unavailable ? (
          <SettingsSection
            title={UNAVAILABLE[unavailable].title}
            description={UNAVAILABLE[unavailable].body}
          >
            <InfoRow
              label="What they are"
              description="Scripted agent chats, run on the real chat path in a project of their own, and exported whole for review."
            />
          </SettingsSection>
        ) : (
          <>
            <SettingsSection
              title="Run a scenario"
              description="A scenario file names the agents to make, the built-in knowledge to grant them, the conversations to have and what each turn should do. Each turn is an ordinary chat turn: it is governed and costs what that chat would."
            >
              <div className="px-5 py-4 space-y-3">
                <label className={`${BUTTON} cursor-pointer w-fit`}>
                  <Upload className="size-3.5" />
                  Choose a scenario file
                  <input
                    ref={input}
                    type="file"
                    accept=".json,application/json"
                    className="sr-only"
                    aria-label="Scenario file"
                    onChange={(e) => void choose(e.target.files?.[0])}
                  />
                </label>
                {picked &&
                  (picked.error !== null ? (
                    <p className="text-xs text-red-600 dark:text-red-400">
                      {picked.file}: {picked.error}
                    </p>
                  ) : (
                    <div className="flex flex-wrap items-center justify-between gap-2">
                      <p className="text-xs text-gray-500 dark:text-gray-400">
                        <Strong>{picked.name}</Strong> · {picked.agents} agents ·{" "}
                        {picked.conversations} conversations · {picked.turns} turns
                      </p>
                      <button
                        type="button"
                        className={BUTTON}
                        onClick={() => start.mutate()}
                        disabled={start.isPending || busy}
                        title={busy ? "Another run is still going" : undefined}
                      >
                        <Play className="size-3.5" />
                        {start.isPending ? "Starting…" : "Start the run"}
                      </button>
                    </div>
                  ))}
                {startError && (
                  <p className="text-xs text-red-600 dark:text-red-400">{startError}</p>
                )}
              </div>
            </SettingsSection>
 
            <SettingsSection
              title="Your runs"
              description="Each runs in a project of its own, which shows in the workspace menu. Download a run's export to review it; deleting a run deletes its project."
            >
              {listed.isLoading ? (
                <div className="px-5 py-4">
                  <SkeletonLines count={3} />
                </div>
              ) : runs.length === 0 ? (
                <InfoRow label="No runs yet" />
              ) : (
                runs.map((run) => (
                  <RunRow key={run.id} run={run} onDelete={setDeleting} />
                ))
              )}
            </SettingsSection>
          </>
        )}
      </div>
      {deleting && (
        <ConfirmDialog
          title="Delete the run"
          body={
            <>
              Delete <Strong>{deleting.name}</Strong> and its project, with the
              agents and conversations in it? The export goes too.
            </>
          }
          loading={remove.isPending}
          error={remove.isError ? (remove.error as Error).message : null}
          onConfirm={() => remove.mutate(deleting)}
          onCancel={() => setDeleting(null)}
        />
      )}
    </SubPage>
  );
};
 
export default ScenarioRuns;