File size: 9,209 Bytes
ba70497
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
f34cc82
ba70497
 
f34cc82
ba70497
 
 
 
 
 
f34cc82
ba70497
 
 
 
 
f34cc82
 
ba70497
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
f34cc82
ba70497
 
 
 
 
f34cc82
ba70497
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
f34cc82
ba70497
f34cc82
ba70497
 
 
 
f34cc82
ba70497
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
f34cc82
ba70497
 
 
 
 
 
 
 
 
 
 
 
 
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
// Live grade. POST /api/run starts the same suites start.py runs; the stream draws each case as it finishes.
import { useEffect, useRef, useState } from "react";
import { Icon } from "../lib/icons.jsx";
import { useData } from "../lib/data.jsx";
import { useUi } from "../lib/ui.jsx";
import { CardHead } from "./common.jsx";
import { ResetButton } from "./ResetButton.jsx";
import { tr } from "../lib/i18n.js";

const EMPTY = {
  seq: 0, running: false, reader: null, model: "", ollama: false, why: "",
  passed: 0, failed: 0, total: 0, ok: null, error: null, tail: [], suites: [],
};

function tally(job) {
  const passed = job.suites.reduce((a, s) => a + s.passed, 0);
  const failed = job.suites.reduce((a, s) => a + s.failed, 0);
  return { ...job, passed, failed };
}

export function reduceRun(job, ev) {
  if (!ev || ev.type === "ping") return job;
  if (ev.type === "reset") return ev.job || job;
  const base = job || EMPTY;
  if (ev.type === "log") return { ...base, tail: [...(base.tail || []), ev.text].slice(-12) };
  if (ev.type === "suite") {
    const suites = base.suites.map((s) => (s.id === ev.id
      ? { ...s, status: ev.status, total: ev.total ?? s.total, passed: ev.passed ?? s.passed, failed: ev.failed ?? s.failed }
      : s));
    return tally({ ...base, suites });
  }
  if (ev.type === "case") {
    const suites = base.suites.map((s) => (s.id === ev.suite
      ? { ...s, passed: ev.passed, failed: ev.failed, cases: [...s.cases, ev.case] }
      : s));
    return tally({ ...base, suites });
  }
  if (ev.type === "done") {
    return {
      ...base, running: false, ok: ev.ok, error: ev.error,
      passed: ev.passed ?? base.passed, failed: ev.failed ?? base.failed, total: ev.total ?? base.total,
    };
  }
  return base;
}

function folderFor(label) {
  return label === "rules" ? "rules" : `llm_${(label || "").replace(":", "_")}`;
}

function blurb(job, mode, demo) {
  if (job?.running) {
    const seen = job.passed + job.failed;
    const who = demo ? tr("AI model") : job.reader === "rules" ? tr("rule reader") : tr("{model} + rule check", { model: job.model });
    return tr("Running with the {who}. {seen} of {total} cases finished.", { who: who, seen: seen, total: job.total });
  }
  if (job?.suites?.length) {
    if (job.ok) return tr("Finished. {passed} passed{failed}", { passed: job.passed, failed: job.failed ? }), ${job.failed} failed` : ""}.`;
    return job.error ? tr("Stopped. {error}.", { error: job.error }) : tr("Finished with {failed} failed.", { failed: job.failed });
  }
  if (demo) return tr("Grades the {n} demo events with the AI model. Each case shows up as soon as it finishes.", { n: demo });
  if (mode === "both") return "Grades the 15 given events with the model, then checks every reading against the rules. Each case shows up when it finishes.";
  return "Grades the 15 given events with the rule reader. Each case shows up as soon as it finishes. This does not re-run the event feed.";
}

export function RunTests() {
  // Online (demoSize > 0) the grade is the visitor's own: the AI model alone, on the demo's events.
  const { reload, demoSize } = useData();
  const { toast } = useUi();
  const [job, setJob] = useState(null);
  const [mode, setMode] = useState("rules");
  const seq = useRef(-1);
  const sawRun = useRef(false);
  const feed = useRef(null);
  const stick = useRef(true);

  const accept = (data) => {
    if (!data || typeof data.seq !== "number" || data.seq <= seq.current) return;
    seq.current = data.seq;
    setJob(data);
  };

  useEffect(() => {
    let stop = false;
    const es = new EventSource("/api/run/stream");
    es.addEventListener("state", (e) => { if (!stop) accept(JSON.parse(e.data)); });
    es.addEventListener("update", (e) => {
      if (stop) return;
      const ev = JSON.parse(e.data);
      if (typeof ev.seq === "number" && ev.seq <= seq.current) return;
      if (typeof ev.seq === "number") seq.current = ev.seq;
      setJob((cur) => reduceRun(cur, ev));
    });
    const poll = setInterval(async () => {
      if (stop) return;
      try {
        const res = await fetch("/api/run", { cache: "no-store" });
        if (res.ok) accept(await res.json());
      } catch { /* the stream is the live path; the next poll retries */ }
    }, 1000);
    return () => { stop = true; clearInterval(poll); es.close(); };
  }, []);

  useEffect(() => {
    if (!job) return;
    if (job.running) sawRun.current = true;
    else if (sawRun.current) { sawRun.current = false; reload(); }
  }, [job, job?.running, reload]);

  const seen = (job?.passed || 0) + (job?.failed || 0);
  useEffect(() => {
    const el = feed.current;
    if (el && stick.current) el.scrollTop = el.scrollHeight;
  }, [seen]);

  const start = async () => {
    const body = demoSize ? { reader: "llm", suites: ["given"] } : mode === "both" ? { reader: "both", suites: ["given"] } : { reader: "rules" };
    try {
      const res = await fetch("/api/run", {
        method: "POST", headers: { "Content-Type": "application/json" }, body: JSON.stringify(body),
      });
      const data = await res.json().catch(() => ({}));
      if (!res.ok) toast(data.busy ? tr("Someone else is running the tests right now. Try again in a minute.") : data.error || "Could not start the run");
    } catch {
      toast(tr("Could not start the run"));
    }
  };

  const stop = async () => {
    try {
      const res = await fetch("/api/run/stop", { method: "POST" });
      if (!res.ok) toast(tr("Could not stop the run"));
    } catch {
      toast(tr("Could not stop the run"));
    }
  };

  const running = !!job?.running;
  const pct = job?.total ? Math.min(100, Math.round((100 * seen) / job.total)) : 0;
  const bar = job?.failed ? "var(--bad)" : running ? "var(--accent)" : "var(--good)";
  const rows = [];
  for (const suite of job?.suites || []) {
    suite.cases.forEach((c, i) => rows.push({ ...c, suite, key: `${suite.id}-${c.reader}-${c.id}-${i}` }));
  }
  const last = rows.length - 1;

  return (
    <div className="card run-card">
      <CardHead title={tr("Run tests")} sub={blurb(job, mode, demoSize)}>
        <div className="controls">
          {!demoSize && <div className="toggle" role="group" aria-label={tr("What to run")}>
            <button type="button" className={mode === "rules" ? "on" : ""} disabled={running} onClick={() => setMode("rules")}>{tr("Rules")}</button>
            <button type="button" className={mode === "both" ? "on" : ""} disabled={running || !job?.ollama}
              title={job && !job.ollama ? job.why : "Grade the 15 given events with the model and the rule check"}
              onClick={() => setMode("both")}>{tr("Model + rules")}</button>
          </div>}
          <button type="button" className="btn primary" disabled={running} onClick={start}>
            <Icon name="play" />{running ? tr("Running") : tr("Run tests")}
          </button>
          {running && <button type="button" className="btn" onClick={stop}><Icon name="x" />{tr("Stop")}</button>}
          <ResetButton kind="tests" />
        </div>
      </CardHead>

      {!!job?.suites?.length && (
        <>
          <div className="run-top">
            <div className="run-count"><b>{seen}</b><span> / {job.total}</span></div>
            <div className="run-meter" aria-hidden="true"><i style={{ width: `${pct}%`, background: bar }} /></div>
            <div className={`run-flag ${job.failed ? "bad" : running ? "go" : "ok"}`}>
              {running ? "Live" : job.failed ? tr("{failed} failed", { failed: job.failed }) : "Passed"}
            </div>
          </div>
          <div className="run-suites">
            {job.suites.map((s) => (
              <div key={s.id} className={`run-suite ${s.status}`}>
                {s.status === "running" && <span className="pulse" />}
                <b>{s.title}</b>
                <span>{s.passed + s.failed}/{s.total}</span>
              </div>
            ))}
          </div>
          <div className="run-feed" ref={feed} onScroll={(e) => {
            const el = e.currentTarget;
            stick.current = el.scrollHeight - el.scrollTop - el.clientHeight < 48;
          }}>
            {rows.map((c, i) => {
              const open = c.suite.status === "done" || c.suite.status === "failed";
              const href = `#/tests/${c.suite.id}/${folderFor(c.reader)}/${c.id}`;
              return (
                <div key={c.key} className={`run-case ${c.verdict === "PASS" ? "pass" : "fail"}${i === last ? " latest" : ""}`}>
                  <span className="mark">{c.verdict === "PASS" ? tr("PASS") : tr("FAIL")}</span>
                  {open ? <a href={href}>{c.id}</a> : <b>{c.id}</b>}
                  <span className="who">{demoSize ? tr("AI model") : c.reader}</span>
                  <span className="cat">{c.category}</span>
                  <span className="set">{c.suite.title}</span>
                </div>
              );
            })}
            {!rows.length && <div className="run-wait">{tr("Starting the grader…")}</div>}
          </div>
          {running && !!job.tail?.length && <pre className="run-tail">{job.tail[job.tail.length - 1]}</pre>}
        </>
      )}
    </div>
  );
}