Support tab (agents:support on a range with a question, instructions/support.md, its answer in labeling/auto/support/); the weather read from data/<STATION>/weather/ (pumped), no call to MeteoSwiss from the app; plots in mm (corr_x_mm, corr_y_mm); analyst instructions: the weather pumped, the targets in mm and their distance

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
maximeandClaude Opus 5.5 committed 2026-11-18 07:17:51 +01:00
1 parent 60d10a282c
commit 161fb0212f
12 files changed
+414 -104

No files matched your search

+12 -5
View File
@@ -8,19 +8,20 @@ The tool of the manual diagnostic: two pages, **Data** and **Stations**.
- **The labels**, under the plots, and their bar, according to the chosen source:
- **Detectors** (default): the detectors' events (`detectors/scripts/categories.py`, `window`: the range with its 3 days of history), read-only. The bar carries only their family, the tooltip their targets; on click: their dates, their sensors (targets and references), the message and the action (`labeling/scripts/client.py`: the first sentence of the text of the event; the "For the client" columns of `labeling/families.md`, per family, refined per variety);
- **LLM**: `labeling/auto/<STATION>.jsonl`, read-only;
- **Analysis**: the same labels, to edit or delete; writes in `labeling/auto/<STATION>.jsonl`, each label checked by the rules of labeling (`labeling/scripts/validate.py`, `check`: one of the six families, no numeric value…) and given its id (`ids.py`, `assign`).
- **Analysis**: the same labels, to edit or delete; writes in `labeling/auto/<STATION>.jsonl`, each label checked by the rules of labeling (`labeling/scripts/validate.py`, `check`: one of the six families, no numeric value…) and given its id (`ids.py`, `assign`);
- **Support**: the same labels, read-only, to ask the support a question on a range.
With Detectors and LLM, dragging on the bar zooms in time; with Analysis, it selects a range to analyze. A click highlights a label on the plots and the bar, sets the images to its start and opens it (with Analysis: bounds, family, text, Save, Delete); a click elsewhere on the bar closes it. The page does not show `labeling/manual/`.
With Detectors and LLM, dragging on the bar zooms in time; with Analysis and Support, it selects a range to analyze, or to ask about. A click highlights a label on the plots and the bar, sets the images to its start and opens it (with Analysis: bounds, family, text, Save, Delete); a click elsewhere on the bar closes it. The page does not show `labeling/manual/`.
- **The camera images**, on the right, on the same station and the same range: slider, ◀ ▶ and keyboard arrows; wheel to zoom, drag to move, double click for the whole image; Names box; a range on the bar under the slider draws the displacement arrow of each sensor. An arrow at the top left enlarges the image and pushes the plots to the left; the reverse arrow brings it back.
- **The diagnostic settings**, under the image: "Focus on event curves" (with an event open, the plots show only its sensors: those of the detectors, or those the text of a label names), the families shown and, for Detectors only, the targets considered, the others removed before the detectors ("Rerun the detectors", parameter `targets` of `/api/detectors`).
- **The weather**: a station with a position gets, at Load, the hourly measurements of the nearest MeteoSwiss station (`weather/meteoswiss.py` of `~/aimsight-data`, `hourly`) as plots "Weather: …", next to the "System: …" ones; the place found and the station chosen are written under the selector (check them: the search of a place always returns its best match).
- **The weather**: a station with a position gets, at Load, the hourly measurements of the nearest MeteoSwiss station, pumped with its data (`data/<STATION>/weather/`, `data.load_weather`), as plots "Weather: …", next to the "System: …" ones; the place found and the station chosen are written under the selector. No call to MeteoSwiss from the app: a range not pumped has no weather.
The address keeps the station and the range (UTC, `end` excluded): `#/data?station=NIEDERHORN&start=2026-09-25&end=2026-10-08`; without dates, the last 5 UTC days, today included.
## The Stations page
The tracked stations, `extraction/stations.txt` of `~/aimsight-data` (`SERIAL [position]`), to edit (serial, position: `lat,lon` or a Swiss place, for the weather of Data; empty for an indoor site: no weather), and the checked ones pumped (`extraction/pump.sh`, `--delay 300`; the list and the pumping through `extraction/pumping.py` of `~/aimsight-data`, the app only calls it) over a range (by default every station, over the range of the address, from 3 days before: the history of the detectors) or, without dates, their missing days up to now; the end of `out/pump.log` follows. The end of a pumping launched by the app empties the cache of the detectors' events.
The tracked stations, `extraction/stations.txt` of `~/aimsight-data` (`SERIAL [position]`), to edit (serial, position: `lat,lon` or a Swiss place, for the weather pumped with the data; empty for an indoor site: no weather), and the checked ones pumped (`extraction/pump.sh`, `--delay 300`; the list and the pumping through `extraction/pumping.py` of `~/aimsight-data`, the app only calls it) over a range (by default every station, over the range of the address, from 3 days before: the history of the detectors) or, without dates, their missing days up to now; the end of `out/pump.log` follows. The end of a pumping launched by the app empties the cache of the detectors' events.
## The Analysis tab
@@ -29,6 +30,11 @@ The tracked stations, `extraction/stations.txt` of `~/aimsight-data` (`SERIAL [p
- **The messages**: after the report, the user writes to the analyst, the same session resumes (`--resume`). An analysis stops with the server ("interrupted"); "continue" in the message field resumes it.
- **Optimize the detectors**, on a finished analysis: `/optimize` in Optimizer (`optimizer/`, with the plugin `agents/`) on the analysis: the detectors, then the reading tools; the detectors committed in `detectors/`, the reading tools in `tools/`, each on its current branch. The page follows the thread of the session (`work/optimization.jsonl`), then shows its summary under the report (`optimizer/sessions/<analysis>_<time>/summary.md`, and the `<analysis>/tools.md` of an older session). One optimization at a time; meanwhile, no analysis and no message to the analyst; an optimization cut by the server stopping is rerun with the button. The detectors' events are kept in memory until the end of an optimization: after an `/optimize` run outside the app, restart the server.
## The Support tab
- **Ask the support**: a range selected, a question (required), then `server/support.py` launches the support of the agents repository by `claude -p`, with its instructions (`instructions/support.md`): free to answer as it judges best, itself (the labels, the analyses, a short reading of the data, the knowledge base) or through the analyst it launches on the range or a wider one (`DETECTORS: yes`, in the foreground: up to 3 h per command, `BASH_MAX_TIMEOUT_MS`). It writes in `labeling/auto/support/<STATION>_<start>_<end>/` its answer (`answer.md` and its figures), `request.md`, and its analyst's work in `analyst/`, whose labels are submitted nowhere. The page follows its progress, then shows the answer.
- **The sidebar**, **the messages**, the stop with the server: as for an analysis (`labeling/auto/support/`; only the requests of the app, which carry `request.json`). No support while an optimization runs.
## Launch
The VS Code task **Run app** (`.vscode/tasks.json`), or by hand (Node 22 for the front end):
@@ -42,9 +48,10 @@ The page opens on `http://127.0.0.1:8770`. Settings by variables: `AIMSIGHT_DATA
## The folders
- `server/server.py`: FastAPI; serves the built page and the API under `/api` (stations, images, curves, detectors, labels, analyses); answers only the pages of the workstation (local Host, declared JSON).
- `server/server.py`: FastAPI; serves the built page and the API under `/api` (stations, images, curves, detectors, labels, analyses, support); answers only the pages of the workstation (local Host, declared JSON).
- `server/station.py`: the data of the Data page; read-only on `data/` (through `tools/scripts/data.py`), writes only in `labeling/{auto,manual}/`.
- `server/analysis.py`: the Analysis tab; launches `claude` with the agent `agents:analyst` (Read, Write, Bash allowed without asking); and the optimization, `/optimize` in Optimizer (Read, Write, Edit, Bash, Agent).
- `server/support.py`: the Support tab; launches `claude` with the agent `agents:support` (Read, Write, Edit, Bash, Glob, Grep allowed without asking), through `analysis.run`.
- `server/check.py`: checks, without calling claude: `.venv/bin/python app/server/check.py`.
- `web/`: React (Vite) and Mantine; `src/App.jsx` (header, sidebar, address), `src/pages/Data.jsx` (the page), `src/pages/Images.jsx` (the images, in Data), `src/common.jsx` (requests, selector), `src/main.jsx` (theme). Plotly, dressed in Mantine's colours, loads only with Data. `dist/` and `node_modules/` outside git.
+25 -17
View File
@@ -81,23 +81,30 @@ def launch(body):
return {"name": name}
def run(a, out, prompt, resume, agent, tools, env=None):
"""A turn of an agent of the plugin by claude -p, from the root: its stream in work/log.jsonl and in a["lines"], its
session in work/session (resume: its id)."""
p = subprocess.Popen(["claude", "-p", prompt, "--plugin-dir", str(AGENTS), "--agent", f"agents:{agent}", *ISOLATED,
"--output-format", "stream-json", "--verbose",
"--allowedTools", tools, "--permission-mode", "acceptEdits", *station.links()]
+ (["--resume", resume] if resume else []),
cwd=station.ROOT, env=_env() | (env or {}), stdout=subprocess.PIPE, stderr=subprocess.STDOUT,
text=True)
with open(out / "work" / "log.jsonl", "a", encoding="utf-8") as log:
for line in p.stdout:
log.write(line)
a["lines"] += digest(line)
if '"subtype":"init"' in line: # the session, for the next messages
(out / "work" / "session").write_text(json.loads(line)["session_id"])
if p.wait():
raise RuntimeError(f"claude ended with code {p.returncode}")
def work(name, out, prompt, resume=None):
"""A turn of the analyst: the request, or a message of the user in the same session (resume: its id)."""
a = analyses[name]
try:
p = subprocess.Popen(["claude", "-p", prompt, "--plugin-dir", str(AGENTS), "--agent", "agents:analyst", *ISOLATED,
"--output-format", "stream-json", "--verbose",
"--allowedTools", "Read,Write,Bash", "--permission-mode", "acceptEdits", *station.links()]
+ (["--resume", resume] if resume else []),
cwd=station.ROOT, env=_env(), stdout=subprocess.PIPE, stderr=subprocess.STDOUT, text=True)
with open(out / "work" / "log.jsonl", "a", encoding="utf-8") as log:
for line in p.stdout:
log.write(line)
a["lines"] += digest(line)
if '"subtype":"init"' in line: # the session, for the next messages
(out / "work" / "session").write_text(json.loads(line)["session_id"])
if p.wait():
raise RuntimeError(f"claude ended with code {p.returncode}")
run(a, out, prompt, resume, "analyst", "Read,Write,Bash")
a["submitted"] = submit(a["station"], name, out)
a["state"] = "done"
except Exception as e: # noqa: BLE001 — the error shows in the page, the server goes on
@@ -234,10 +241,11 @@ def list_analyses():
return out
def file(name, path):
"""A file of the folder of the analysis (the report, its figures), never outside."""
f = (FOLDER / name / path).resolve()
if not f.is_file() or not f.is_relative_to(FOLDER.resolve()):
def file(name, path, folder=None):
"""A file of the folder of the analysis (the report, its figures; or of a support request), never outside."""
folder = folder or FOLDER
f = (folder / name / path).resolve()
if not f.is_file() or not f.is_relative_to(folder.resolve()):
raise station.Refusal("unknown file")
return f
+70 -1
View File
@@ -46,6 +46,8 @@ def check_server():
assert call("/api/labels", {"station": "x"}, {"Content-Type": "text/plain"}) == 403
assert call("/api/stations") == 200
assert call("/api/analyses") == 200
assert call("/api/support") == 200
assert call("/api/support", {"station": "x"}) == 400
assert call("/api/analyses/UNKNOWN/optimize", {}) == 400
finally:
srv.should_exit = True
@@ -308,7 +310,74 @@ def check_validation():
analysis.analyses.clear()
CHECKS = [check_server, check_station, check_optimization, check_analysis, check_validation]
def check_support():
# "Ask the support" then a message (support.launch, support.message), without claude: the support of the agents
# repository, its request (the question, its instructions, its absolute folder), the long commands it is given, the
# resumption of its session, its answer in the page; the state read again after a restart
import analysis
import support
launched = []
class FakeProcess:
returncode = 0
def __init__(self, args, *a, **k):
launched.append((args, k))
self.stdout = iter(['{"type":"system","subtype":"init","session_id":"s-1"}\n'])
def wait(self):
return 0
root = temp_folder()
before = support.FOLDER, analysis.subprocess.Popen, analysis.AGENTS
support.FOLDER, analysis.AGENTS, analysis.subprocess.Popen = root / "support", root / "agents", FakeProcess
key = os.environ.get("ANTHROPIC_API_KEY")
os.environ["ANTHROPIC_API_KEY"] = "test-key"
ask = {"station": "NORDEND", "start": "2026-11-05T06:00Z", "end": "2026-11-05T12:00Z", "question": "Why the jump?"}
try:
assert "agents/" in refuses(support.launch, ask)
(analysis.AGENTS / "agents").mkdir(parents=True)
(analysis.AGENTS / "agents" / "support.md").write_text("support")
assert "question" in refuses(support.launch, ask | {"question": " "})
name = support.launch(ask)["name"]
while support.supports[name]["state"] == "running":
time.sleep(0.05)
assert support.state(name)["state"] == "done" and support.state(name)["report"] is None, support.state(name)
args, k = launched[0]
assert args[args.index("--agent") + 1] == "agents:support" and "Edit" in args[args.index("--allowedTools") + 1], args
assert "ANTHROPIC_API_KEY" not in k["env"] and k["env"]["BASH_MAX_TIMEOUT_MS"] == "10800000", sorted(k["env"])
out = support.FOLDER / name
assert f"Output folder: {out}/." in args[2] and f"INSTRUCTIONS: {support.INSTRUCTIONS}." in args[2] \
and args[2].endswith("Question: Why the jump?") and support.INSTRUCTIONS.is_file(), args[2]
assert (out / "work" / "session").read_text() == "s-1"
assert support.launch(ask)["name"].startswith(name + "_") # another question on the same range, next to it
(out / "answer.md").write_text("# NORDEND: a jump\n\n![curves](fig.png)")
(out / "fig.png").write_bytes(b"png")
assert support.state(name)["report"] and "<h1>NORDEND: a jump</h1>" in support.answer(name, False)
assert analysis.file(name, "fig.png", support.FOLDER).is_file()
refuses(analysis.file, name, "../../agents/agents/support.md", support.FOLDER)
while any(s["state"] == "running" for s in support.supports.values()):
time.sleep(0.05)
support.message(name, {"text": "And the night before?"})
while support.supports[name]["state"] == "running":
time.sleep(0.05)
args = launched[-1][0]
assert args[args.index("--resume") + 1] == "s-1" and args[2].startswith("And the night before?"), args
support.supports.clear() # after a restart: the thread read again in the log, done with its answer
s = support.state(name)
assert s["state"] == "done" and s["lines"] == ["› And the night before?"], s
assert {x["name"]: x["state"] for x in support.list_supports()}[name] == "done" # the sidebar
refuses(support.state, "../analyses")
finally:
os.environ.pop("ANTHROPIC_API_KEY")
if key is not None:
os.environ["ANTHROPIC_API_KEY"] = key
shutil.rmtree(root)
support.FOLDER, analysis.subprocess.Popen, analysis.AGENTS = before
support.supports.clear()
CHECKS = [check_server, check_station, check_optimization, check_analysis, check_validation, check_support]
if __name__ == "__main__":
name = sys.argv[1] if len(sys.argv) > 1 else None
+34 -1
View File
@@ -2,7 +2,7 @@
The FastAPI server serves the built React page (app/web/dist, `npm run build` in app/web) and the API under /api.
The Data page reads data/ and the labels of labeling/ (station.py); its Analysis tab launches the analyst, and the
optimization of the detectors (analysis.py).
optimization of the detectors (analysis.py); its Support tab, the support (support.py).
Settings: AIMSIGHT_DATA (data), AIMSIGHT_LABELS (labels), AIMSIGHT_PORT (port, 8770).
"""
import json
@@ -20,6 +20,7 @@ from fastapi.responses import FileResponse, HTMLResponse, JSONResponse
import analysis
import station
import support
from fastapi.staticfiles import StaticFiles
APP = Path(__file__).resolve().parents[1]
@@ -167,6 +168,38 @@ def analysis_file(name: str, path: str):
return FileResponse(analysis.file(name, path))
# --- the Support tab of the Data page (support.py): the support launched by claude -p on a range, with a question
@app.post("/api/support")
def launch_support(body: dict):
return support.launch(body)
@app.get("/api/support")
def supports():
return support.list_supports()
@app.get("/api/support/{name}")
def support_state(name: str):
return support.state(name)
@app.post("/api/support/{name}/message")
def support_message(name: str, body: dict):
return support.message(name, body)
@app.get("/api/support/{name}/report.html")
def support_answer(name: str, dark: bool = False):
return HTMLResponse(support.answer(name, dark))
@app.get("/api/support/{name}/{path:path}")
def support_file(name: str, path: str):
return FileResponse(analysis.file(name, path, support.FOLDER))
if PAGE.is_dir():
app.mount("/", StaticFiles(directory=PAGE, html=True), name="page")
else:
+21 -30
View File
@@ -3,8 +3,8 @@
Data are read as the agents read them, tools/scripts/data.py (the tools repository, through the tools/ link); the detectors'
events are those of detectors/scripts/categories.py (window); the rules of the labels and what the client is told, those of
labeling/scripts (validate, ids, client). Read-only on data/, filled only by pump.sh; writes only in
labeling/auto/. What brings data in (the pumping, the list of the tracked stations, the weather) is in
~/aimsight-data, called as it is (extraction/pumping.py, weather/meteoswiss.py).
labeling/auto/. What brings data in (the pumping, the list of the tracked stations) is in ~/aimsight-data, called as it
is (extraction/pumping.py); the weather is pumped with the data, data/<STATION>/weather/ (data.load_weather).
"""
import bisect
import functools
@@ -18,15 +18,14 @@ from datetime import datetime, timedelta
from pathlib import Path
ROOT = Path(__file__).resolve().parents[2]
# ~/aimsight-data, the repository of data/: the methods that bring data in (the pumping, the weather), called as they are
# ~/aimsight-data, the repository of data/: the method that brings data in (the pumping, the weather with it), called as it is
DATA_REPOSITORY = Path(os.environ.get("AIMSIGHT_DATA", ROOT / "data")).resolve().parent
sys.path[:0] = [str(ROOT / "tools" / "scripts"), str(ROOT / "detectors" / "scripts"), str(ROOT / "labeling" / "scripts"),
str(DATA_REPOSITORY / "extraction"), str(DATA_REPOSITORY / "weather")]
str(DATA_REPOSITORY / "extraction")]
import categories # noqa: E402
import client # noqa: E402 (labeling: what the client is told of an event)
import data # noqa: E402
import ids # noqa: E402 (labeling: the stable id of the labels)
import meteoswiss # noqa: E402
import pumping # noqa: E402
import validate # noqa: E402 (labeling: the rules of a label)
@@ -49,6 +48,7 @@ POSE = (("pan", "#1a1a19"), ("tilt", "#8a8a85"), ("rotation", "#b5651d"))
PLOTS = (("error_value", "Error value"), ("x", "X [px]"), ("y", "Y [px]"),
("relative_x", "Relative Horizontal Shift"), ("relative_y", "Relative Vertical Shift"),
("corr_x", "Relative Corrected Horizontal Shift"), ("corr_y", "Relative Corrected Vertical Shift"),
("corr_x_mm", "Relative Corrected Horizontal Shift [mm]"), ("corr_y_mm", "Relative Corrected Vertical Shift [mm]"),
("reproj_err", "References (reproj. error)"))
QUALITY = (("peak", "Quality: Peak"), ("flux", "Quality: Flux"), ("sharpness", "Quality: Sharpness"),
("fwhm", "Quality: FWHM [px]"), ("dominance", "Quality: Dominance"), ("snr", "Quality: SNR"))
@@ -177,18 +177,17 @@ def curves(station, start, end):
if not out:
raise Refusal(f"no measurement of {station} in this range")
result = {"A": data.iso(a), "B": data.iso(b), "T": T, "plots": out}
if place := pumping.tracked().get(station): # the weather at the position of the station (stations.txt), if it has one
try:
label, times, plots = weather(place, a, b)
T.update(times)
out += plots
result["weather"] = label
except Refusal as e:
result["weather"] = f"unavailable ({e})"
if hours := [h for h in data.load_weather(d) if a <= h["t"] < b]: # the weather pumped with the data, if any
label, times, plots = weather(hours)
T.update(times)
out += plots
result["weather"] = label
elif pumping.tracked().get(station):
result["weather"] = "none pumped in this range (see the pumping log)"
return result
# --- the Data page, the weather at a place (weather/meteoswiss.py of ~/aimsight-data): plots "Weather: …" on the range of the curves
# --- the Data page, the weather pumped in data/<STATION>/weather/ (extraction/weather.py of ~/aimsight-data): plots "Weather: …"
WEATHER = (("Precipitation (mm/h)", "precipitation_mm"), ("Temperature (°C)", "temperature_c"), ("Humidity (%)", "humidity_pct"),
("Wind (km/h)", "wind_speed_kmh", "wind_gust_kmh"), ("Wind direction (deg)", "wind_direction_deg"),
@@ -196,29 +195,21 @@ WEATHER = (("Precipitation (mm/h)", "precipitation_mm"), ("Temperature (°C)", "
("Global radiation (W/m²)", "global_radiation_wm2"), ("Snow depth (cm)", "snow_depth_cm"))
def weather(place, a, b):
"""-> (label, T, plots) as curves(): the hourly values of the MeteoSwiss station nearest to the place ("lat,lon" or
a Swiss place name), over [a, b); their times under T["system:weather"], so that the target filters ignore them."""
try:
where, hours = meteoswiss.hourly(place, a, b)
except LookupError as e:
raise Refusal(str(e))
except OSError as e:
raise Refusal(f"MeteoSwiss unreachable: {e}")
times = list(hours)
def weather(hours):
"""[hour] of data.load_weather, not empty -> (label, T, plots) as curves(); their times under T["system:weather"], so
that the target filters ignore them; the label: where the last hour was measured."""
plots = []
for title, *columns in WEATHER:
traces = [{"name": c.rsplit("_", 1)[0].replace("_", " "), "t": "system:weather", "y": y,
"mode": "markers" if "direction" in c else "lines",
"line": {"width": 1.2, "color": COLORS[i], "shape": "hv" if c == "precipitation_mm" else "linear"}}
for i, (c, y) in enumerate((c, [hours[t][c] for t in times]) for c in columns) if any(v is not None for v in y)]
for i, (c, y) in enumerate((c, [h.get(c) for h in hours]) for c in columns) if any(v is not None for v in y)]
if traces:
plots.append({"title": "Weather: " + title, "traces": traces})
if not plots:
raise Refusal(f"no MeteoSwiss measurement at {where['name']} in this range")
return (f"{where['place']} → MeteoSwiss {where['station']} {where['name']}, {where['distance_km']:.1f} km, "
f"{where['height_m']:.0f} m",
{"system:weather": [t.strftime("%Y-%m-%d %H:%M") for t in times]}, plots)
w = hours[-1]
return (f"{w['place']} → MeteoSwiss {w['station']} {w['station_name']}, {w['distance_km']} km, {w['height_m']} m"
+ " (no measurement in this range)" * (not plots),
{"system:weather": [h["t"].strftime("%Y-%m-%d %H:%M") for h in hours]}, plots)
# --- the tracked stations and the pumping: extraction/pumping.py of ~/aimsight-data
+118
View File
@@ -0,0 +1,118 @@
"""The Support tab of the Data page: the support of the agents repository (agents/, --agent agents:support), launched by
`claude -p` on a range chosen in the page, with the user's question and its instructions (instructions/support.md). It
answers as it judges best: itself, or through the analyst it launches on the range or a wider one. It writes in
labeling/auto/support/<STATION>_<start>_<end>/ its answer (answer.md, its figures next to it); the labels of its analyst
stay there, submitted nowhere. Then the user can write to it: the same session resumes (`claude -p --resume`).
"""
import json
import threading
from datetime import datetime, timezone
import analysis
import station
FOLDER = station.LABELS / "auto" / "support"
INSTRUCTIONS = station.ROOT / "instructions" / "support.md"
REQUEST = """Station: data/{station}/. Range: {start} → {end} (UTC). Output folder: {out}/. INSTRUCTIONS: {instructions}.
Question: {question}"""
TOOLS = "Read,Write,Edit,Bash,Glob,Grep"
# the analyst it launches runs in the foreground, inside one of its commands: up to 3 h (claude -p ends with its turn)
ENV = {"BASH_DEFAULT_TIMEOUT_MS": "10800000", "BASH_MAX_TIMEOUT_MS": "10800000"}
# name -> {"state": "running" | "done" | "error", "lines": [...], "request": {...}}
supports = {}
def launch(body):
st, start, end = body.get("station"), body.get("start"), body.get("end")
question = (body.get("question") or "").strip()
station.checked_range(start, end)
station.folder(st)
if not question:
raise station.Refusal("no question for the support")
if not (analysis.AGENTS / "agents" / "support.md").exists():
raise station.Refusal("no support in agents/ (the link: README.md)")
name = f"{st}_{start[:16].replace(':', '')}_{end[:16].replace(':', '')}"
with analysis.lock:
if analysis._optimizing():
raise station.Refusal(analysis.BUSY)
out = FOLDER / name
if out.exists(): # another question on the same range: the earlier one stays, next to it
name += datetime.now(timezone.utc).strftime("_%H%M%S")
out = FOLDER / name
request = {"station": st, "start": start, "end": end, "question": question}
supports[name] = {"state": "running", "lines": [], "request": request}
(out / "work").mkdir(parents=True)
(out / "request.json").write_text(json.dumps(request, ensure_ascii=False, indent=1), encoding="utf-8")
prompt = REQUEST.format(station=st, start=start, end=end, out=out, instructions=INSTRUCTIONS, question=question)
threading.Thread(target=work, args=(name, out, prompt), daemon=True).start()
return {"name": name}
def work(name, out, prompt, resume=None):
"""A turn of the support: the request, or a message of the user in the same session (resume: its id)."""
s = supports[name]
try:
analysis.run(s, out, prompt, resume, "support", TOOLS, ENV)
s["state"] = "done"
except Exception as e: # noqa: BLE001 — the error shows in the page, the server goes on
s["lines"].append(f"Error: {e}")
s["state"] = "error"
def message(name, body):
"""A message of the user to the support: the same session resumes (claude -p --resume)."""
text, out = (body.get("text") or "").strip(), FOLDER / name
state(name) # the name checked, the state read again after a restart
s, session = supports[name], out / "work" / "session"
if not text or not session.exists():
raise station.Refusal("empty message, or the support has no session to resume")
with analysis.lock:
if analysis._optimizing():
raise station.Refusal(analysis.BUSY)
if s["state"] == "running":
raise station.Refusal("the support is still working")
s["state"] = "running"
line = json.dumps({"type": "page", "text": text}, ensure_ascii=False) + "\n"
with open(out / "work" / "log.jsonl", "a", encoding="utf-8") as log:
log.write(line)
s["lines"] += analysis.digest(line)
prompt = f"{text}\n\n(If your answer changes, rewrite {out}/answer.md in full: the page shows it again.)"
threading.Thread(target=work, args=(name, out, prompt, session.read_text()), daemon=True).start()
return {}
def _ended(out):
"""The state of a request the server does not hold (after a restart): done with an answer, otherwise interrupted."""
return "done" if (out / "answer.md").exists() else "interrupted"
def state(name):
out = FOLDER / name
if "/" in name or name.startswith(".") or not (out / "request.json").is_file():
raise station.Refusal("unknown support request")
if name not in supports: # after a restart of the server, only the folder is left: the thread is read again in the log
log = out / "work" / "log.jsonl"
supports[name] = {"state": _ended(out), "request": json.loads((out / "request.json").read_text(encoding="utf-8")),
"lines": [r for l in open(log, encoding="utf-8") for r in analysis.digest(l)] if log.exists() else []}
s, r = supports[name], out / "answer.md"
# report and submitted: the names of the Analysis panel, which the page reuses (no labels submitted here)
return {"name": name, "state": s["state"], "lines": s["lines"], "submitted": None, "request": s["request"],
"report": int(r.stat().st_mtime) if r.exists() else None, "dialogue": (out / "work" / "session").exists()}
def list_supports():
"""The history of the requests (the sidebar), the most recent first. Only those of the app: a folder of the support
launched elsewhere has no request.json."""
out = []
for f in sorted(FOLDER.glob("*/request.json"), key=lambda f: f.parent.stat().st_mtime, reverse=True):
name = f.parent.name
s = supports.get(name) or {"state": _ended(f.parent), "request": json.loads(f.read_text(encoding="utf-8"))}
out.append({"name": name, "state": s["state"]} | s["request"])
return out
def answer(name, dark):
"""answer.md in HTML, served in the folder of the request: its relative images are found there."""
return analysis._page(analysis.file(name, "answer.md", FOLDER).read_text(encoding="utf-8"), name, dark)
+17 -12
View File
@@ -50,7 +50,8 @@ function Header({ mobile, desktop, toggle }) {
// The analyses of the Data page (labeling/auto/analyses/), read again every 3 s: one folder per station, open by default if
// it has one running, and inside one analysis per range (a green tick: its labels validated); a click opens Data on its
// station and its days, and shows its report there
// station and its days, and shows its report there. kind "support": the requests of the Support tab (labeling/auto/support/),
// the same without labels to validate
// The range of an analysis on two lines, too wide for the sidebar on one: the days "04.11 – 07.11" ("01.11" within the day),
// under them the hours "21:12 – 14:12" (UTC)
const dayMonth = t => `${t.slice(8, 10)}.${t.slice(5, 7)}`, hour = t => t.slice(11, 16);
@@ -60,10 +61,10 @@ const STATE_COLOR = { done: "teal", error: "red", interrupted: "gray" };
// The state: a spinning wheel while running, otherwise a coloured dot (its name in the tooltip)
const Dot = ({ state }) => (state === "running" ? <Loader size={10} color="orange" />
: <Tooltip label={state}><ColorSwatch size={8} color={`var(--mantine-color-${STATE_COLOR[state] || "gray"}-6)`} withShadow={false} /></Tooltip>);
function Analyses({ open }) {
const [list, setList] = useState([]);
function Analyses({ kind = "analyses", open }) {
const [list, setList] = useState([]), labels = kind === "analyses";
useEffect(() => {
const read = () => fetch("/api/analyses").then(r => r.ok && r.json()).then(l => l && setList(l)).catch(() => {}); // silently: every 3 s
const read = () => fetch(`/api/${kind}`).then(r => r.ok && r.json()).then(l => l && setList(l)).catch(() => {}); // silently: every 3 s
read();
const timer = setInterval(read, 3000);
return () => clearInterval(timer);
@@ -71,19 +72,19 @@ function Analyses({ open }) {
if (!list.length) return null;
const stations = [...new Set(list.map(a => a.station))].sort();
return <>
<Text size="xs" fw={700} tt="uppercase" c="dimmed" px="sm" pt="lg" pb="xs">Analyses (UTC)</Text>
<Text size="xs" fw={700} tt="uppercase" c="dimmed" px="sm" pt="lg" pb="xs">{labels ? "Analyses" : "Support"} (UTC)</Text>
{stations.map(st => {
const its = list.filter(a => a.station === st), busy = its.some(a => a.state === "running");
const validated = its.filter(a => a.validated).length;
// the chevron of the folder stays Mantine's: a rightSection would take its place, and rotate with it
return (
<NavLink key={st} defaultOpened={busy} childrenOffset={22} leftSection={<IconFolder size={16} />}
label={<Group gap={6} wrap="nowrap">{st}<Tooltip label={`${validated} of ${its.length} validated`}><Text span size="xs" c="dimmed">{validated}/{its.length}</Text></Tooltip>{busy && <Loader size={10} color="orange" />}</Group>}>
label={<Group gap={6} wrap="nowrap">{st}{labels && <Tooltip label={`${validated} of ${its.length} validated`}><Text span size="xs" c="dimmed">{validated}/{its.length}</Text></Tooltip>}{busy && <Loader size={10} color="orange" />}</Group>}>
{its.map(a => (
<NavLink key={a.name} py={4} onClick={() => open(a)} leftSection={<Dot state={a.state} />}
rightSection={a.validated ? <Tooltip label={`labels validated ${a.validated}`}>
rightSection={labels && (a.validated ? <Tooltip label={`labels validated ${a.validated}`}>
<IconCircleCheck size={14} color="var(--mantine-color-green-6)" /></Tooltip>
: a.state === "done" && <Tooltip label="labels to validate"><IconCircleDashed size={14} color="var(--mantine-color-dimmed)" /></Tooltip>}
: a.state === "done" && <Tooltip label="labels to validate"><IconCircleDashed size={14} color="var(--mantine-color-dimmed)" /></Tooltip>)}
label={<Text size="xs" ff="monospace" style={{ whiteSpace: "nowrap" }}>{days(a)}</Text>}
description={<Text span size="xs" ff="monospace" c="dimmed" style={{ whiteSpace: "nowrap" }}>{hours(a)}</Text>} />
))}
@@ -104,6 +105,7 @@ function Sidebar({ page, selection, close, open }) {
href={address(n, selection)} />
))}
<Analyses open={a => { close(); open(a); }} />
<Analyses kind="support" open={a => { close(); open(a, "support"); }} />
</ScrollArea>
</AppShell.Navbar>
);
@@ -114,6 +116,7 @@ export default function App() {
const [mobile, { toggle: toggleMobile, close: closeMobile }] = useDisclosure(false);
const [desktop, { toggle: toggleDesktop }] = useDisclosure(true);
const [analysis, setAnalysis] = useState(null); // the analysis whose report Data shows
const [support, setSupport] = useState(null); // the support request whose answer Data shows
useEffect(() => {
const follow = () => setPlace(readAddress());
@@ -123,11 +126,12 @@ export default function App() {
// the same address again (Load): read again, a new selection loads the data again
const choose = s => { const a = address(page, s); if (location.hash === a) setPlace(readAddress()); else location.hash = a; };
// An analysis of the sidebar: Data on its station, days that cover its range (unless the range shown already covers them)
function openAnalysis(a) {
// An analysis (or a support request) of the sidebar: Data on its station, days that cover its range (unless the range
// shown already covers them)
function openAnalysis(a, kind) {
const s = selection, covers = s.station === a.station && s.start <= a.start.slice(0, 10) && a.end < s.end;
const end = new Date(Date.parse(a.end.slice(0, 10)) + 864e5).toISOString().slice(0, 10);
setAnalysis(a.name);
(kind === "support" ? setSupport : setAnalysis)(a.name);
location.hash = address("data", covers ? s : { station: a.station, start: a.start.slice(0, 10), end });
}
return (
@@ -138,7 +142,8 @@ export default function App() {
<AppShell.Main bg="var(--mantine-color-default-hover)">
<Suspense fallback={<Loader m="xl" />}>
{page === "stations" ? <Stations selection={selection} />
: <Data selection={selection} choose={choose} analysis={analysis} setAnalysis={setAnalysis} />}
: <Data selection={selection} choose={choose} analysis={analysis} setAnalysis={setAnalysis}
support={support} setSupport={setSupport} />}
</Suspense>
</AppShell.Main>
</AppShell>
+42 -29
View File
@@ -10,7 +10,8 @@ import { StationImages } from "./Images.jsx";
// Data, the curve viewer and the labelling: one plot at the start, others to add or remove,
// all aligned in time; under them the labels: Detectors (the events of the journal), LLM (labeling/auto/, read-only)
// or Analysis (the same, to edit, delete; dragging on the bar selects a range, which the analyst diagnoses and
// labels; elsewhere, dragging zooms); a click opens a
// labels), or Support (LLM's labels; dragging selects a range, on which the support answers a question); elsewhere,
// dragging zooms; a click opens a
// label and highlights it. On the right, the images of the station, and under them the diagnostic settings.
const FAMILIES = { "Visibility": "#8ec5e8", "Obstruction": "#f0b072", "Thermal displacement": "#f08a7e", "Displacement": "#b39ddb",
"Target issue": "#e6d46a", "No data": "#c4c4be", "None": "#a8d5a2" };
@@ -19,8 +20,9 @@ const FAMILY_NAME = f => (f === "None" ? "None (curves intact)" : f);
const FAMILY_CHOICES = [{ value: "", label: "(choose a family)" },
...Object.keys(FAMILIES).filter(f => f !== "None").map(f => ({ value: f, label: f }))];
// LLM and Analysis: the same labels, labeling/auto/; LLM reads them, Analysis edits, deletes them, and has the analyst make
// some on a range (app/server/analysis.py)
const SOURCES = [{ value: "detectors", label: "Detectors" }, { value: "auto", label: "LLM" }, { value: "analysis", label: "Analysis" }];
// some on a range (app/server/analysis.py); Support reads them, and asks the support a question on a range (support.py)
const SOURCES = [{ value: "detectors", label: "Detectors" }, { value: "auto", label: "LLM" }, { value: "analysis", label: "Analysis" },
{ value: "support", label: "Support" }];
const GREY = "#b0b0aa", BLUE = "#2a78d6", LANE = 26, HEIGHT = 330; // LANE: px per row of labels; HEIGHT: of a plot
const color = l => FAMILIES[l.family] || GREY;
const readable = s => s.slice(0, 16).replace("T", " ");
@@ -40,7 +42,7 @@ const wrap = s => s.replace(/(.{1,80})(\s|$)/g, "$1<br>"); // the tooltip: line
const DETECTED = Object.keys(FAMILIES).filter(f => f !== "None"); // the families of the detectors (categories.py)
export default function Data({ selection, choose, analysis, setAnalysis }) {
export default function Data({ selection, choose, analysis, setAnalysis, support, setSupport }) {
const [data, setData] = useState(null), [loading, setLoading] = useState(false), [wide, setWide] = useState(false);
const left = useRef(), [moment, setMoment] = useState(null); // moment: where to set the images (the start of the clicked event)
// The diagnostic settings, under the image (Detectors and LLM): families shown (filter of the page); targets kept ("":
@@ -73,7 +75,7 @@ export default function Data({ selection, choose, analysis, setAnalysis }) {
{data && <TargetFilter d={data} hidden={hidden} setHidden={setHidden} />}
{data && <Curves key={`${station}${start}${end}`} selection={selection} d={data} setImage={(t, nearest) => setMoment({ t, nearest })}
source={source} setSource={setSource} families={families} targets={targets} focus={focus} hidden={hidden}
analysis={analysis} setAnalysis={setAnalysis} />}
analysis={analysis} setAnalysis={setAnalysis} support={support} setSupport={setSupport} />}
</Stack>
</Grid.Col>
<Grid.Col span={{ base: 12, lg: wide ? 7 : 4 }}>
@@ -157,8 +159,9 @@ const Field = ({ name, children }) => (
const mentions = (text, s) => new RegExp(`(^|[^\\w])${s.replace(/[^\w]/g, "\\$&")}(?![\\w])`).test(text);
const sensorsOf = (l, names) => l.sensors ?? names.filter(s => mentions(l.description, s));
// analysis: the folder of the analysis shown, held by App (the sidebar opens one)
function Curves({ selection: { station, start, end }, d, setImage, source, setSource, families, targets, focus, hidden, analysis, setAnalysis }) {
// analysis, support: the folder of the analysis, of the support request shown, held by App (the sidebar opens one)
function Curves({ selection: { station, start, end }, d, setImage, source, setSource, families, targets, focus, hidden, analysis, setAnalysis,
support, setSupport }) {
const { A, B, T, plots: PLOTS } = d;
const plotIndex = (title, otherwise) => { const i = PLOTS.findIndex(p => p.title === title); return i < 0 ? otherwise : i; };
const [Plotly, setPlotly] = useState(null), [ready, setReady] = useState(false);
@@ -171,7 +174,8 @@ function Curves({ selection: { station, start, end }, d, setImage, source, setSo
const labels = useMemo(() => allLabels.filter(x => x.start < B && x.end > A
&& (!DETECTED.includes(x.family) || families.includes(x.family))), [allLabels, families]);
const detect = source === "detectors", readOnly = source !== "analysis"; // only Analysis writes
const folder = source === "analysis" ? "auto" : source; // the labeling/ folder of the labels
const asking = source === "support", select = asking || !readOnly; // select: dragging on the bar selects a range
const folder = "auto"; // the labeling/ folder of the labels
// figs: id -> div of the plot; drawn: id -> plot it shows; viewKey: the range and the width where the text of the labels was truncated
const figs = useRef({}), drawn = useRef({}), nextId = useRef(2), bar = useRef(), sorted = useRef([]), viewKey = useRef(""), current = useRef({});
// the focus: the sensors of the open event (none: all, as for No data); shown, their key
@@ -290,7 +294,7 @@ function Curves({ selection: { station, start, end }, d, setImage, source, setSo
? l.references.map(s => s + " (ref.)").join(", ") : "All sensors")
: (l.family ? `<b>${FAMILY_NAME(l.family)}</b><br>` : "") + wrap(l.description))),
hovertemplate: "%{customdata}<extra></extra>" }],
{ ...skin(c), height: 40 + LANE * n, dragmode: readOnly ? "zoom" : "select", selectdirection: "h", hovermode: "closest", plot_bgcolor: c.bg, showlegend: false,
{ ...skin(c), height: 40 + LANE * n, dragmode: select ? "select" : "zoom", selectdirection: "h", hovermode: "closest", plot_bgcolor: c.bg, showlegend: false,
margin: { ...margin(), l: Math.max(...gs.map(g => g._fullLayout._size.l)), r: Math.max(...gs.map(g => g._fullLayout._size.r)) },
xaxis: { type: "date", range: f.xaxis.range.slice(), showgrid: false, ticks: "", color: c.text },
yaxis: { range: [n - 0.5, -0.5], fixedrange: true, showticklabels: false, showgrid: false, zeroline: false },
@@ -323,8 +327,8 @@ function Curves({ selection: { station, start, end }, d, setImage, source, setSo
useEffect(() => { if (ready) drawPlots().then(() => align(bar.current)); }, [views]);
useEffect(() => { if (ready) drawBar(); }, [ready, labels]);
// Drag on the bar: select a range (Analysis), otherwise zoom in time
useEffect(() => { if (ready) Plotly.relayout(bar.current, { dragmode: readOnly ? "zoom" : "select", selections: [] }); }, [ready, readOnly]);
// Drag on the bar: select a range (Analysis, Support), otherwise zoom in time
useEffect(() => { if (ready) Plotly.relayout(bar.current, { dragmode: select ? "select" : "zoom", selections: [] }); }, [ready, select]);
useEffect(() => { if (ready) drawPlots(true).then(drawBar); }, [dark]);
useEffect(() => { if (ready) drawPlots(true); }, [shown, hidden]);
useEffect(() => { if (ready) plotDivs().forEach(g => Plotly.relayout(g, { shapes: zones() })); }, [ready, labels, choice, opened]);
@@ -373,10 +377,12 @@ function Curves({ selection: { station, start, end }, d, setImage, source, setSo
return true;
}
// The analyst on the range (Analysis, hints optional), or the support (Support, a question)
async function runAnalysis() {
const r = await call("/api/analyses", "POST", { station, start: choice[0], end: choice[1], hints });
const r = await call(asking ? "/api/support" : "/api/analyses", "POST",
{ station, start: choice[0], end: choice[1], ...(asking ? { question: hints } : { hints }) });
if (!r) return; // nothing is lost: the hints and the range stay in the page
setAnalysis(r.name); setHints("");
(asking ? setSupport : setAnalysis)(r.name); setHints("");
await Plotly.relayout(bar.current, { selections: [] });
setChoice(null);
}
@@ -478,13 +484,18 @@ function Curves({ selection: { station, start, end }, d, setImage, source, setSo
</Card>
)}
</div>
{!readOnly && <>
<Text size="sm">{choice ? `${readable(choice[0])} → ${readable(choice[1])} UTC` : "Drag on the label bar to select the range to analyze."}</Text>
<Textarea autosize minRows={2} placeholder="Hints for the analyst (optional): what you saw, what to look at"
value={hints} onChange={e => setHints(e.currentTarget.value)} />
<Group><Button onClick={runAnalysis} disabled={!(choice && choice[0] < choice[1])}>Analyze the range</Button></Group>
{select && <>
<Text size="sm">{choice ? `${readable(choice[0])} → ${readable(choice[1])} UTC`
: `Drag on the label bar to select the range ${asking ? "of your question" : "to analyze"}.`}</Text>
<Textarea autosize minRows={2} value={hints} onChange={e => setHints(e.currentTarget.value)}
placeholder={asking ? "Your question to the support: what you want to know about this range, or what to answer a client"
: "Hints for the analyst (optional): what you saw, what to look at"} />
<Group><Button onClick={runAnalysis} disabled={!(choice && choice[0] < choice[1]) || (asking && !hints.trim())}>
{asking ? "Ask the support" : "Analyze the range"}</Button></Group>
</>}
{analysis && <Analysis key={analysis} name={analysis} dark={dark} done={() => setRev(r => r + 1)} close={() => setAnalysis(null)} />}
{support && <Analysis kind="support" key={`support/${support}`} name={support} dark={dark} done={() => setRev(r => r + 1)}
close={() => setSupport(null)} />}
</Stack>
</Card>
);
@@ -516,14 +527,15 @@ const STATE_COLOR = { running: "blue", done: "teal", error: "red", interrupted:
// An analysis of the Analysis tab: its thread (read again every 3 s while it works), its report, and a message to the
// analyst, which resumes its session; at the end of each turn, the labels are read again. A finished analysis can be
// optimized (/improve of Optimizer on the range of the analysis, then the tool-builder): the thread of the session, then
// its summaries under the report
function Analysis({ name, dark, done, close }) {
// its summaries under the report. kind "support": a request of the Support tab, the same without labels: its question,
// its thread, its answer, the messages
function Analysis({ kind = "analyses", name, dark, done, close }) {
const [a, setA] = useState(null), [turn, setTurn] = useState(0), [text, setText] = useState("");
const box = useRef(), loaded = !!a;
useEffect(() => { if (loaded) box.current?.scrollIntoView({ behavior: "smooth", block: "start" }); }, [name, loaded]); // opened: it is in view
useEffect(() => {
let alive = true, timer;
const read = () => call(`/api/analyses/${name}`).then(r => {
const read = () => call(`/api/${kind}/${name}`).then(r => {
if (!alive || !r) return;
setA(r);
if (r.state === "running" || r.optimization?.state === "running") timer = setTimeout(read, 3000);
@@ -533,7 +545,7 @@ function Analysis({ name, dark, done, close }) {
return () => { alive = false; clearTimeout(timer); };
}, [name, turn]);
async function send() {
if (await call(`/api/analyses/${name}/message`, "POST", { text }) == null) return; // the text stays in the field
if (await call(`/api/${kind}/${name}/message`, "POST", { text }) == null) return; // the text stays in the field
setText(""); setTurn(t => t + 1);
}
async function optimize() {
@@ -543,35 +555,36 @@ function Analysis({ name, dark, done, close }) {
if (await call(`/api/analyses/${name}/validate`, "POST") != null) { setTurn(t => t + 1); done(); }
}
if (!a) return <Loader size="sm" />;
const d = a.request, o = a.optimization, busy = a.state === "running", optimizing = o?.state === "running";
const d = a.request, o = a.optimization, busy = a.state === "running", optimizing = o?.state === "running", labels = kind === "analyses";
const end = new Date(Date.parse(d.end.slice(0, 10)) + 864e5).toISOString().slice(0, 10);
return (
<Card withBorder ref={box}>
<Stack gap="xs">
<Group justify="space-between">
<Group gap="xs">
<Title order={5}>Analysis {readable(d.start)} → {readable(d.end)} UTC</Title>
<Title order={5}>{labels ? "Analysis" : "Support"} {readable(d.start)} → {readable(d.end)} UTC</Title>
<Badge color={STATE_COLOR[a.state] || "gray"}>{a.state}</Badge>
{busy && <Loader size="xs" />}
</Group>
<Group gap="xs">
{a.validated ? <Badge color="green" variant="light">labels validated {a.validated}</Badge>
{!labels ? null : a.validated ? <Badge color="green" variant="light">labels validated {a.validated}</Badge>
: a.state === "done" && <Tooltip label="I agree with all the labels of this analysis: they become reference labels">
<Button size="xs" color="green" variant="light" onClick={validate} disabled={optimizing}>Validate labels</Button></Tooltip>}
{a.state === "done" && <Tooltip label="Improve the detectors (Optimizer), then the reading tools (tool-builder), from this analysis">
{labels && a.state === "done" && <Tooltip label="Improve the detectors (Optimizer), then the reading tools (tool-builder), from this analysis">
<Button size="xs" variant="light" onClick={optimize} disabled={optimizing}>Optimize the detectors</Button></Tooltip>}
<ActionIcon variant="subtle" color="gray" aria-label="Close the report" onClick={close}><IconX size={16} /></ActionIcon>
</Group>
</Group>
{d.hints && <Text size="sm" c="dimmed">Hints: {d.hints}</Text>}
{d.question && <Text size="sm" c="dimmed" style={{ whiteSpace: "pre-wrap" }}>Question: {d.question}</Text>}
{a.state === "interrupted" && <Text size="sm" c="orange">Stopped with the server before the end.{a.dialogue
? " Its session is kept: write “continue” below to resume it where it left off." : ""}</Text>}
{a.submitted !== null && a.state === "done" && <Text size="sm">{a.submitted} label(s) of this analysis in labeling/auto/{d.station}.jsonl{a.validated ? ", validated" : ", to validate"}.</Text>}
{a.report && <Page title="Report" src={`/api/analyses/${name}/report.html?dark=${dark}&v=${a.report}`} />}
{a.report && <Page title="Report" src={`/api/${kind}/${name}/report.html?dark=${dark}&v=${a.report}`} />}
<Thread lines={a.lines} />
{a.dialogue && (
<Group align="flex-end" gap="sm" wrap="nowrap">
<Textarea autosize minRows={1} style={{ flex: 1 }} placeholder="A question, a correction for the analyst"
<Textarea autosize minRows={1} style={{ flex: 1 }} placeholder={`A question, a correction for the ${labels ? "analyst" : "support"}`}
value={text} onChange={e => setText(e.currentTarget.value)} />
<Button onClick={send} disabled={busy || optimizing || !text.trim()}>Send</Button>
</Group>
@@ -589,7 +602,7 @@ function Analysis({ name, dark, done, close }) {
{o.summary && <Text size="xs" c="dimmed" ff="monospace">python3 detectors/bench/score.py data/{d.station} --labels labeling/auto/{d.station}.jsonl --from {d.start.slice(0, 10)} --to {end}</Text>}
</Stack>
)}
<Text size="xs" c="dimmed">labeling/auto/analyses/{name}/</Text>
<Text size="xs" c="dimmed">labeling/auto/{kind}/{name}/</Text>
</Stack>
</Card>
);