diff --git a/.github/workflows/jevfish-web.yml b/.github/workflows/jevfish-web.yml
new file mode 100644
index 0000000000..37a04d9848
--- /dev/null
+++ b/.github/workflows/jevfish-web.yml
@@ -0,0 +1,25 @@
+name: JevFish web build is committed
+
+on:
+ pull_request:
+ paths: ["jevfish/web/**"]
+ push:
+ branches: [main]
+ paths: ["jevfish/web/**"]
+
+jobs:
+ dist:
+ runs-on: ubuntu-latest
+ steps:
+ - uses: actions/checkout@v4
+ - uses: actions/setup-node@v4
+ with:
+ node-version: 22
+ - run: npm ci
+ working-directory: jevfish/web
+ - run: npm run build
+ working-directory: jevfish/web
+ - name: web/dist matches the source
+ run: |
+ git status --porcelain jevfish/web/dist
+ test -z "$(git status --porcelain jevfish/web/dist)"
diff --git a/JevFish.app/Contents/Info.plist b/JevFish.app/Contents/Info.plist
new file mode 100644
index 0000000000..64c4ecfd4e
--- /dev/null
+++ b/JevFish.app/Contents/Info.plist
@@ -0,0 +1,30 @@
+
+
+
+
+ CFBundleDevelopmentRegion
+ en
+ CFBundleDisplayName
+ JevFish
+ CFBundleExecutable
+ JevFish
+ CFBundleIconFile
+ AppIcon
+ CFBundleIdentifier
+ com.markiewee.jevfish
+ CFBundleInfoDictionaryVersion
+ 6.0
+ CFBundleName
+ JevFish
+ CFBundlePackageType
+ APPL
+ CFBundleShortVersionString
+ 0.2.0
+ CFBundleVersion
+ 0.2.0
+ LSMinimumSystemVersion
+ 12.0
+ NSHighResolutionCapable
+
+
+
diff --git a/JevFish.app/Contents/MacOS/JevFish b/JevFish.app/Contents/MacOS/JevFish
new file mode 100755
index 0000000000..ceef9ac846
--- /dev/null
+++ b/JevFish.app/Contents/MacOS/JevFish
@@ -0,0 +1,33 @@
+#!/bin/bash
+# Finder runs this when JevFish.app is opened. The work happens in jevfish/launcher/launch.sh.
+here="$(cd "$(dirname "$0")" && pwd)"
+root="$(cd "$here/../../.." && pwd)"
+state="$HOME/Library/Application Support/JevFish"
+has_launcher() { [ -f "$1/jevfish/launcher/launch.sh" ]; }
+
+# Moved out of its folder: use the folder from the last good start.
+if ! has_launcher "$root" && [ -f "$state/repo-path" ]; then
+ root="$(head -n 1 "$state/repo-path")"
+fi
+# A downloaded copy can run from a temporary path (App Translocation). Ask Spotlight.
+if ! has_launcher "$root"; then
+ while IFS= read -r marker; do
+ candidate="$(cd "$(dirname "$marker")/../.." 2>/dev/null && pwd)"
+ if has_launcher "$candidate"; then
+ root="$candidate"
+ break
+ fi
+ done < <(mdfind -name jevfish-folder-marker 2>/dev/null)
+fi
+if ! has_launcher "$root"; then
+ osascript -e 'display alert "JevFish cannot find its files" message "Keep JevFish.app inside the JevFish folder you downloaded and open it from there." as critical' >/dev/null 2>&1
+ exit 1
+fi
+
+# macOS does not let an app read files in Desktop, Documents or Downloads, and gives no way
+# to ask (that needs a paid Apple developer account). Terminal has the permissions the user
+# granted it, so hand the same script to Terminal when the folder is out of reach.
+if head -c 1 "$root/jevfish/launcher/launch.sh" >/dev/null 2>&1; then
+ exec /bin/bash "$root/jevfish/launcher/launch.sh" "$root"
+fi
+exec "${JEVFISH_OPEN_CMD:-open}" -a Terminal "$root/jevfish/launcher/launch.sh"
diff --git a/JevFish.app/Contents/Resources/AppIcon.icns b/JevFish.app/Contents/Resources/AppIcon.icns
new file mode 100644
index 0000000000..e81ecae0a6
Binary files /dev/null and b/JevFish.app/Contents/Resources/AppIcon.icns differ
diff --git a/README.md b/README.md
index d05fef685c..aa2579dad7 100644
--- a/README.md
+++ b/README.md
@@ -1,4 +1,6 @@
> **This fork adds JevFish.** [`jevfish/`](jevfish/) is our own rebuild of MiroFish's five-stage pipeline. TypeSafe's Jev decides every simulated person's turn; an LLM only writes the text. The graph is local, so no Zep account is needed, and the prediction is calibrated. See [jevfish/README.md](jevfish/README.md). The original MiroFish code below is kept unchanged as reference.
+>
+> **To run it on a Mac, double-click `JevFish.app` in this folder.** The first start installs everything it needs and opens JevFish in your browser; the app then asks for your Jev and language-model keys on screen. No terminal, no Homebrew, no Node. If macOS blocks the app because you downloaded the ZIP, open System Settings, Privacy & Security, and click Open Anyway. Keep the folder in your home folder rather than Desktop, Documents or Downloads, or JevFish starts in a Terminal window instead. Full instructions: [jevfish/README.md](jevfish/README.md).
diff --git a/jevfish/.gitignore b/jevfish/.gitignore
index 4cc7026932..c422343365 100644
--- a/jevfish/.gitignore
+++ b/jevfish/.gitignore
@@ -4,6 +4,6 @@ data/
__pycache__/
*.pyc
web/node_modules/
-web/dist/
+!web/dist/
.cache/
log/
diff --git a/jevfish/README.md b/jevfish/README.md
index 5ba1647228..1969e10a13 100644
--- a/jevfish/README.md
+++ b/jevfish/README.md
@@ -30,18 +30,38 @@ Each simulated turn is a single Jev request containing seven typed questions:
## Run it
+Double-click **JevFish.app** in this folder. Nothing else is needed: no terminal, no Homebrew, no Node.
+
+- The first start installs uv and the Python packages (about 1 GB) with no admin password, then opens JevFish in your browser. It took 30 seconds on a fast connection and can take a few minutes on a slow one.
+- Later starts take a few seconds, and reuse a JevFish that is already running.
+- It uses the first free port from 5055 to 5064. Logs are in `~/Library/Logs/JevFish/`.
+- If something goes wrong, a dialog says what, with a button that opens the log.
+
+**Where you keep the folder matters.** macOS does not let an app read files in Desktop, Documents or Downloads, and an app can only ask for that with a paid Apple developer account. Keep the JevFish folder in your home folder, in Applications, or on another disk, and the app starts silently. From Desktop, Documents or Downloads it still works: the app hands the same start-up to Terminal, which uses the permissions you have already given it, and a Terminal window shows the progress.
+
+Then the app asks for two keys on its Setup screen:
+- **Jev** from [console.typesafe.ai](https://console.typesafe.ai). A typical run costs about US$0.04.
+- **A language model**: a free [Gemini key](https://aistudio.google.com/apikey), or any OpenAI-compatible service (address, model, key).
+
+"Save and check" stores them in `jevfish/.env` (readable only by you) and checks both with calls that cost nothing. There is also a **test mode** that runs every screen on deterministic fakes, so you can look around without keys. Every number it shows is made up.
+
+**If macOS blocks the app**, it came from a downloaded ZIP, which macOS quarantines. Open System Settings, Privacy & Security, scroll to the JevFish message and click Open Anyway. A `git clone` has no such block.
+
+### From the terminal
+
```sh
cd jevfish
uv sync
-cd web && npm install && npm run build && cd ..
+cd web && npm install && npm run build && cd .. # only if you change the web app; the built one is committed
-export TYPESAFE_API_KEY=... # console.typesafe.ai
+export TYPESAFE_API_KEY=... # or set the keys in the app
export GEMINI_API_KEY=... # or LLM_API_KEY + LLM_BASE_URL + LLM_MODEL for any OpenAI-compatible model
uv run jevfish serve # http://127.0.0.1:5055
```
- **Whole pipeline from the terminal:** `uv run jevfish demo` runs it on `examples/lazybee-cleaning.md`. That file uses example figures, not real Lazybee data.
-- **No keys:** `JEVFISH_FAKE_JUDGE=1 JEVFISH_FAKE_LLM=1 uv run jevfish serve` runs everything on deterministic fakes, useful for trying the UI.
+- **No keys:** `JEVFISH_FAKE_JUDGE=1 JEVFISH_FAKE_LLM=1 uv run jevfish serve` runs everything on deterministic fakes, the same as test mode.
+- The API answers only requests addressed to this computer, and refuses changing requests sent from another website. `serve --host 0.0.0.0` turns that off and warns, which also exposes the key screen to your network.
Settings:
- `JEVFISH_DATA_DIR` sets where data is stored (default `jevfish/data`).
diff --git a/jevfish/docs/api.md b/jevfish/docs/api.md
index 0b7de24eec..79846d1451 100644
--- a/jevfish/docs/api.md
+++ b/jevfish/docs/api.md
@@ -11,9 +11,17 @@ type Task = { id: string; kind: "graph"|"prepare"|"run"|"report"; project_id: st
```
## Meta
-- `GET /api/health` returns `{ok, judge: "jev"|"fake"|"missing TYPESAFE_API_KEY", jev_model, llm: ""|"fake"|"missing LLM_API_KEY", llm_fallbacks: string[], llm_base_url, data_dir}`.
+- `GET /api/health` returns `{ok, app: "jevfish", setup_needed, judge: "jev"|"fake"|"missing TYPESAFE_API_KEY", jev_model, llm: ""|"fake"|"missing LLM_API_KEY", llm_fallbacks: string[], llm_base_url, data_dir}`.
+- **Local only:** every `/api/` request must be addressed to `127.0.0.1`, `localhost` or `::1`, and requests that change something must not come from another site's `Origin`. Anything else gets 403. `jevfish serve --host` beyond loopback turns the guard off and says so.
- `GET /api/tasks/` returns a Task. `POST /api/tasks//cancel` cancels it and returns the Task.
+## Setup
+- `GET /api/settings` returns `{env_file, test_mode, setup_needed, typesafe_key, llm_provider: "gemini"|"openai", gemini_key, llm_key, llm_base_url, llm_model, active_tasks}`. Saved keys come back as the last four characters (`""` when the key is too short to hint at, `null` when none is saved). Full keys are never sent to the browser.
+- `PUT /api/settings` saves keys and returns the same shape. Fields: `typesafe_key`, `llm_provider`, `llm_key`, `llm_base_url`, `llm_model`, `test_mode`. A blank key keeps the saved one. Writes `jevfish/.env` (mode 600) and applies at once, with no restart. Jobs already running keep the keys they started with.
+- `POST /api/settings/check` checks the keys in the body, falling back to the saved ones, and returns `{jev: {ok, message}, llm: {ok, message}}`. Both checks are free: listing models for Jev and Gemini, a one-token request for other providers.
+- `GET /api/example` returns `{name, requirement, seed_text}` for the example project.
+- `POST /api/shutdown` stops the server, right after answering `{ok: true}`.
+
## Projects
```ts
type Project = { id: string; name: string; requirement: string; created_at: string; updated_at: string;
diff --git a/jevfish/docs/superpowers/plans/2026-09-17-one-click-mac-app.md b/jevfish/docs/superpowers/plans/2026-09-17-one-click-mac-app.md
new file mode 100644
index 0000000000..988c4cb54d
--- /dev/null
+++ b/jevfish/docs/superpowers/plans/2026-09-17-one-click-mac-app.md
@@ -0,0 +1,1623 @@
+# JevFish One-Click Mac App Implementation Plan
+
+> **For agentic workers:** REQUIRED SUB-SKILL: Use superpowers:subagent-driven-development (recommended) or superpowers:executing-plans to implement this plan task-by-task. Steps use checkbox (`- [ ]`) syntax for tracking.
+
+**Goal:** Anyone on a Mac can start JevFish by double-clicking `JevFish.app` and do everything else, keys included, in the web app. No terminal.
+
+**Architecture:** `JevFish.app` is a tiny shell-script bundle at the repo root. It finds the repo and runs `jevfish/launcher/launch.sh`. That script installs uv and the Python packages if they are missing, reuses or starts the Flask server on a free port, and opens the browser. The web app gains a Setup screen that saves keys to `jevfish/.env`, checks them with free API calls, and hot-reloads the running server. The built web app is committed, so Node is not needed to run it.
+
+**Tech stack:** bash and osascript for the launcher; Flask blueprint, python-dotenv, typesafe-sdk and openai for setup; Vue 3 and Vite for the screen; pytest.
+
+**Approval:** On 17 Sep 2026 Mark said "for jev fish make it with jaust a ui and one click setup". He then picked a Mac app with no Terminal window, Macs only, and keeping the upstream code, and set the goal "build jevfish". The first JevFish build used the same pattern: a build goal counted as approval, and the PRD and PR summary went to Mark inline with the result.
+
+---
+
+## PRD
+
+### Problem
+Running JevFish today means opening a terminal and typing eight commands: `uv sync`, `npm install`, `npm run build`, two key exports and `uv run jevfish serve`. Keys only come from environment variables, and without them the app shows a warning with no way to fix it. Kavi and Trisha cannot start it without help, and Mark cannot start it from Finder.
+
+### Users
+Mark, Kavi, Trisha, and anyone else on a Mac who gets the repo, either as a git clone or as the GitHub ZIP.
+
+### Requirements
+1. **One click to start.** Double-clicking `JevFish.app` in the repo folder opens JevFish in the default browser.
+ - First start: installs uv if missing, into `~/Library/Application Support/JevFish/bin`, with no admin password. Then installs the Python packages, about 1 GB. Needs internet only; no Xcode, no Homebrew, no Node.
+ - Later starts: a few seconds. If JevFish is already running, it opens the existing server instead of starting another.
+ - Picks the first free port from 5055 to 5064.
+ - Failures show a macOS alert in plain words with a "Show log" button. Logs go to `~/Library/Logs/JevFish/`.
+ - Still works when the app was moved out of the folder (it remembers the repo path) and when macOS runs a downloaded copy from a temporary path (it finds the folder with Spotlight).
+ - **Folders macOS protects.** An app may not read Desktop, Documents or Downloads, and without a paid Apple developer account it cannot even ask (tested on macOS 26.3.2: silently denied, with an ad-hoc signature and usage strings both present). From those folders the app hands the same script to Terminal, which uses the permissions the user already granted, and the window explains why it is there. Anywhere else it starts silently.
+2. **Setup in the app.** Opening the app with keys missing lands on a Setup screen.
+ - Jev: the TypeSafe API key.
+ - Language model: Gemini (key only) or any other OpenAI-compatible model (address, model name, key).
+ - One button, "Save and check". It saves to `jevfish/.env` (mode 600, gitignored), applies at once without a restart, and checks both keys with free calls: listing models for Jev and Gemini, and a one-token request for other providers.
+ - Saved keys are never sent back to the browser, only their last four characters.
+ - Test mode on or off (fake Jev and fake model), for trying the UI without keys.
+ - "Stop JevFish" shuts the server down.
+ - Settings stay reachable from the header.
+3. **Example in the app.** "Fill in the example" on the new-prediction form loads the Lazybee example that `jevfish demo` uses.
+4. **Safety.** The API only answers when the Host is the local machine, which blocks DNS rebinding. Changing requests from another website's Origin are refused. `serve --host 0.0.0.0` turns the guard off on purpose and prints a warning.
+5. **No regressions.** The CLI (`serve`, `demo`), env-var configuration and all 60 existing tests keep working.
+
+### Out of scope
+- Windows and Linux launchers.
+- Code signing and notarisation. These need a paid Apple Developer account.
+- Auto-update.
+- A native window. It opens in the browser.
+- Moving existing project data.
+
+### Known limits
+- A copy downloaded as a ZIP is quarantined by macOS. The first open is blocked with "Apple could not verify". The user goes once to System Settings, Privacy & Security, Open Anyway. The README says so. Git clones are not affected.
+- From Desktop, Documents or Downloads the start happens in a Terminal window, as above. Both are the same cause: no paid Apple developer account, and signing is out of scope.
+
+### Success check
+- On this Mac, from a fresh local clone with an empty state folder and uv hidden from PATH, a double-click (`open JevFish.app`) installs uv and the packages, opens the Setup screen, saves real keys, both checks pass, and a test-mode project runs end to end.
+- `uv run pytest -q` passes, including the new setup, env-file and launcher tests.
+- Headless Chrome QA of the Setup screen at 375, 768 and 1280 wide, in light and dark, shows no console errors and no horizontal scroll.
+
+---
+
+## File structure
+
+| File | Change | Responsibility |
+| --- | --- | --- |
+| `jevfish/src/jevfish/config.py` | modify | `env_file_path()`, health gains `app` and `setup_needed` |
+| `jevfish/src/jevfish/keys.py` | create | read and write the .env file, turn the setup form into changes, check keys |
+| `jevfish/src/jevfish/example.py` | create | the Lazybee example, shared by the CLI and the API |
+| `jevfish/src/jevfish/setup_api.py` | create | Flask blueprint for `/api/settings`, `/api/settings/check`, `/api/example`, `/api/shutdown`; the local-only guard |
+| `jevfish/src/jevfish/service.py` | modify | `Service.reload()` |
+| `jevfish/src/jevfish/api.py` | modify | use `svc.settings`, register the blueprint and guard |
+| `jevfish/src/jevfish/cli.py` | modify | use `example.py`, allow remote when host is not loopback |
+| `jevfish/tests/test_keys.py` | create | env file and form tests, key checks with fake clients |
+| `jevfish/tests/test_setup_api.py` | create | endpoint tests |
+| `jevfish/tests/test_launcher.py` | create | launcher and app bundle tests with fake uv and a fake server |
+| `jevfish/web/src/lib/api.js` | modify | new calls |
+| `jevfish/web/src/lib/health.js` | create | shared health state |
+| `jevfish/web/src/views/SetupView.vue` | create | Setup screen |
+| `jevfish/web/src/router.js` | modify | `/setup` route, first-load redirect |
+| `jevfish/web/src/App.vue` | modify | Settings link, banners link to setup |
+| `jevfish/web/src/views/ProjectsView.vue` | modify | "Fill in the example" |
+| `jevfish/web/dist/` | commit | built app |
+| `jevfish/.gitignore` | modify | stop ignoring `web/dist/` |
+| `jevfish/launcher/launch.sh` | create | install, start, open |
+| `jevfish/launcher/jevfish-folder-marker` | create | lets Spotlight find the folder |
+| `jevfish/launcher/make-icon.sh` | create | rebuilds `AppIcon.icns` from the logo |
+| `JevFish.app/Contents/{Info.plist,MacOS/JevFish,Resources/AppIcon.icns}` | create | the double-click app |
+| `.github/workflows/jevfish-web.yml` | create | fails when `web/dist` is stale |
+| `README.md`, `jevfish/README.md`, `jevfish/docs/api.md` | modify | docs |
+
+---
+
+### Task 1: Config, env file path and health fields
+
+**Files:**
+- Modify: `jevfish/src/jevfish/config.py`
+- Test: `jevfish/tests/test_keys.py`
+
+- [ ] **Step 1: Write the failing test**
+
+```python
+# jevfish/tests/test_keys.py
+from jevfish.config import env_file_path, load_settings
+from tests.test_pipeline import settings
+
+
+def test_env_file_path_follows_env(tmp_path, monkeypatch):
+ monkeypatch.setenv("JEVFISH_ENV_FILE", str(tmp_path / "x.env"))
+ assert env_file_path() == tmp_path / "x.env"
+
+
+def test_health_reports_app_and_setup_needed(tmp_path):
+ ready = settings(tmp_path).health()
+ assert ready["app"] == "jevfish" and ready["setup_needed"] is False
+ missing = settings(tmp_path, fake_judge=False, fake_llm=False).health()
+ assert missing["setup_needed"] is True
+```
+
+- [ ] **Step 2: Run it and see it fail**
+
+Run: `cd jevfish && uv run pytest tests/test_keys.py -q`
+Expected: FAIL, `ImportError: cannot import name 'env_file_path'`.
+
+- [ ] **Step 3: Implement**
+
+In `config.py`, replace `_load_env_file` with:
+
+```python
+def env_file_path() -> Path:
+ """Where keys are saved: JEVFISH_ENV_FILE, else jevfish/.env."""
+ return Path(os.environ.get("JEVFISH_ENV_FILE") or PACKAGE_ROOT / ".env")
+
+
+def _load_env_file() -> None:
+ path = env_file_path()
+ if path.exists():
+ from dotenv import load_dotenv
+
+ load_dotenv(path, override=False)
+```
+
+and make `health()` start with:
+
+```python
+ return {
+ "app": "jevfish",
+ "setup_needed": not (self.llm_ready and self.judge_ready),
+ "judge": ... # unchanged from here
+```
+
+- [ ] **Step 4: Run it and see it pass**
+
+Run: `uv run pytest tests/test_keys.py -q`. Expected: 2 passed.
+
+- [ ] **Step 5: Commit**
+
+`git commit -am "feat(jevfish): env file path and setup_needed in health"`
+
+### Task 2: keys.py, the env file and key checks
+
+**Files:**
+- Create: `jevfish/src/jevfish/keys.py`
+- Test: `jevfish/tests/test_keys.py` (append)
+
+- [ ] **Step 1: Write the failing tests**
+
+```python
+import os
+import stat
+
+import pytest
+from dotenv import dotenv_values
+
+from jevfish import keys
+from jevfish.keys import SetupError, updates_from_form, write_env
+
+
+def test_write_env_keeps_other_lines_and_round_trips(tmp_path):
+ path = tmp_path / ".env"
+ path.write_text("# mine\nOTHER=1\nTYPESAFE_API_KEY=old\nTYPESAFE_API_KEY=dupe\nJEVFISH_FAKE_LLM=1\n")
+ tricky = "k'e\\y$HOME\"x"
+ write_env(path, {"TYPESAFE_API_KEY": tricky, "JEVFISH_FAKE_LLM": None, "GEMINI_API_KEY": "g123"})
+ text = path.read_text()
+ assert text.startswith("# mine\nOTHER=1\n")
+ assert text.count("TYPESAFE_API_KEY") == 1 and "JEVFISH_FAKE_LLM" not in text
+ values = dotenv_values(path)
+ assert values["TYPESAFE_API_KEY"] == tricky and values["GEMINI_API_KEY"] == "g123" and values["OTHER"] == "1"
+ assert stat.S_IMODE(os.stat(path).st_mode) == 0o600
+
+
+def test_write_env_rejects_newlines(tmp_path):
+ with pytest.raises(SetupError):
+ write_env(tmp_path / ".env", {"TYPESAFE_API_KEY": "a\nb"})
+
+
+def test_form_gemini_blank_key_keeps_saved():
+ env = {"GEMINI_API_KEY": "saved"}
+ assert updates_from_form({"llm_provider": "gemini", "llm_key": " "}, env) == {
+ "LLM_API_KEY": None, "LLM_BASE_URL": None, "LLM_MODEL": None}
+ with pytest.raises(SetupError):
+ updates_from_form({"llm_provider": "gemini"}, {})
+
+
+def test_form_openai_needs_address_model_and_key():
+ form = {"llm_provider": "openai", "llm_base_url": "https://api.openai.com/v1", "llm_model": "gpt-4o-mini", "llm_key": "sk-1"}
+ assert updates_from_form(form, {}) == {"LLM_BASE_URL": "https://api.openai.com/v1", "LLM_MODEL": "gpt-4o-mini", "LLM_API_KEY": "sk-1"}
+ for bad in ({"llm_base_url": "ftp://x"}, {"llm_model": ""}, {"llm_key": ""}):
+ with pytest.raises(SetupError):
+ updates_from_form({**form, **bad}, {})
+
+
+def test_form_test_mode_and_jev_key():
+ assert updates_from_form({"test_mode": True, "typesafe_key": " ts "}, {}) == {
+ "JEVFISH_FAKE_JUDGE": "1", "JEVFISH_FAKE_LLM": "1", "TYPESAFE_API_KEY": "ts"}
+ assert updates_from_form({"test_mode": False}, {}) == {"JEVFISH_FAKE_JUDGE": None, "JEVFISH_FAKE_LLM": None}
+ with pytest.raises(SetupError):
+ updates_from_form({"llm_provider": "claude"}, {})
+
+
+def test_hint_shows_only_last_four():
+ assert keys.hint(None) is None
+ assert keys.hint("short") == ""
+ assert keys.hint("abcdefghijkl1234") == "1234"
+
+
+class _Models:
+ def __init__(self, result):
+ self.result = result
+
+ def list(self):
+ if isinstance(self.result, Exception):
+ raise self.result
+ return self.result
+
+
+def test_check_jev_maps_errors():
+ from typesafe_sdk import TypeSafeAuthenticationError
+
+ class Model:
+ def __init__(self, name):
+ self.name = name
+
+ class Listing:
+ models = (Model("jev-latest"),)
+
+ def factory(result):
+ class Client:
+ def __init__(self, **kw):
+ self.models = _Models(result)
+
+ def close(self):
+ pass
+ return Client
+
+ assert keys.check_jev("k", client_factory=factory(Listing()))["ok"] is True
+ assert keys.check_jev("k", "jev-9", client_factory=factory(Listing()))["ok"] is False
+ err = TypeSafeAuthenticationError.__new__(TypeSafeAuthenticationError)
+ Exception.__init__(err, "401")
+ bad = keys.check_jev("k", client_factory=factory(err))
+ assert bad == {"ok": False, "message": "TypeSafe rejected this key."}
+
+
+def test_check_llm_gemini_and_openai():
+ import httpx
+ from openai import AuthenticationError, BadRequestError
+
+ req = httpx.Request("GET", "https://x")
+
+ def err(cls, code):
+ return cls("no", response=httpx.Response(code, request=req), body=None)
+
+ class Gemini:
+ def __init__(self, result):
+ self.result = result
+
+ def __call__(self, **kw):
+ self.kw = kw
+ self.models = _Models(self.result)
+ return self
+
+ ok = keys.check_llm("gemini", "g", client_factory=Gemini([]))
+ assert ok["ok"] is True
+ assert keys.check_llm("gemini", "g", client_factory=Gemini(err(BadRequestError, 400)))["message"] == "Google rejected this key."
+
+ class Chat:
+ def __init__(self, result):
+ self.result = result
+ self.completions = self
+
+ def create(self, **kw):
+ self.kw = kw
+ if isinstance(self.result, Exception):
+ raise self.result
+ return self.result
+
+ class Other:
+ def __init__(self, result):
+ self.chat = Chat(result)
+
+ def __call__(self, **kw):
+ return self
+
+ good = Other(object())
+ assert keys.check_llm("openai", "k", "https://x/v1", "m", client_factory=good)["ok"] is True
+ assert good.chat.kw["max_tokens"] == 1 and good.chat.kw["model"] == "m"
+ assert keys.check_llm("openai", "k", "https://x/v1", "m", client_factory=Other(err(AuthenticationError, 401)))["message"] == "The provider rejected this key."
+```
+
+- [ ] **Step 2: Run them and see them fail**
+
+Run: `uv run pytest tests/test_keys.py -q`. Expected: FAIL, `ImportError: cannot import name 'keys'`.
+
+- [ ] **Step 3: Implement `keys.py`**
+
+```python
+"""Keys saved from the Setup screen, and free checks that they work.
+
+Keys live in the .env file `config` loads (jevfish/.env unless JEVFISH_ENV_FILE says
+otherwise). Saving also updates os.environ, so the running server uses them at once.
+Checks cost nothing: listing models needs a valid key, and other providers get a
+one-token request.
+"""
+
+from __future__ import annotations
+
+import os
+import re
+from collections.abc import Mapping
+from pathlib import Path
+
+from .config import GEMINI_BASE_URL
+
+_LINE = re.compile(r"^\s*(?:export\s+)?([A-Za-z_][A-Za-z0-9_]*)\s*=")
+TIMEOUT = 15
+
+
+class SetupError(ValueError):
+ pass
+
+
+def _quote(value: str) -> str:
+ if "\n" in value or "\r" in value:
+ raise SetupError("Keys cannot contain line breaks.")
+ # single quotes: python-dotenv reads them literally, so $ in a key is not expanded
+ return "'" + value.replace("\\", "\\\\").replace("'", "\\'") + "'"
+
+
+def write_env(path: Path, updates: Mapping[str, str | None]) -> None:
+ """Set (str) or remove (None) keys in a .env file. Other lines stay as they were."""
+ lines = path.read_text().splitlines() if path.exists() else []
+ pending = dict(updates)
+ out: list[str] = []
+ for line in lines:
+ m = _LINE.match(line)
+ if m and m.group(1) in updates:
+ value = pending.pop(m.group(1), None) # later duplicates find nothing and drop
+ if value is not None:
+ out.append(f"{m.group(1)}={_quote(value)}")
+ continue
+ out.append(line)
+ out += [f"{k}={_quote(v)}" for k, v in pending.items() if v is not None]
+ path.parent.mkdir(parents=True, exist_ok=True)
+ tmp = path.with_name(path.name + ".tmp")
+ fd = os.open(tmp, os.O_WRONLY | os.O_CREAT | os.O_TRUNC, 0o600)
+ with os.fdopen(fd, "w") as f:
+ f.write("\n".join(out) + ("\n" if out else ""))
+ os.chmod(tmp, 0o600)
+ os.replace(tmp, path)
+
+
+def apply(updates: Mapping[str, str | None]) -> None:
+ for key, value in updates.items():
+ if value is None:
+ os.environ.pop(key, None)
+ else:
+ os.environ[key] = value
+
+
+def hint(value: str | None) -> str | None:
+ """None when unset; otherwise the last four characters, or "" for short values."""
+ if not value:
+ return None
+ return value[-4:] if len(value) >= 12 else ""
+
+
+def provider(env: Mapping[str, str]) -> str:
+ return "openai" if env.get("LLM_API_KEY") or env.get("LLM_BASE_URL") else "gemini"
+
+
+def text(form: Mapping, name: str) -> str:
+ value = form.get(name)
+ return value.strip() if isinstance(value, str) else ""
+
+
+def updates_from_form(form: Mapping, env: Mapping[str, str]) -> dict[str, str | None]:
+ """Turn the Setup form into .env changes. A blank key field keeps the saved key."""
+ updates: dict[str, str | None] = {}
+ if form.get("test_mode") is not None:
+ on = bool(form["test_mode"])
+ updates["JEVFISH_FAKE_JUDGE"] = "1" if on else None
+ updates["JEVFISH_FAKE_LLM"] = "1" if on else None
+ if text(form, "typesafe_key"):
+ updates["TYPESAFE_API_KEY"] = text(form, "typesafe_key")
+ choice = form.get("llm_provider")
+ key = text(form, "llm_key")
+ if choice == "gemini":
+ if not (key or env.get("GEMINI_API_KEY")):
+ raise SetupError("Paste your Gemini API key.")
+ if key:
+ updates["GEMINI_API_KEY"] = key
+ updates.update(LLM_API_KEY=None, LLM_BASE_URL=None, LLM_MODEL=None)
+ elif choice == "openai":
+ base, model = text(form, "llm_base_url"), text(form, "llm_model")
+ if not base.startswith(("http://", "https://")):
+ raise SetupError("The model address must start with http:// or https://.")
+ if not model:
+ raise SetupError("Name the model to use, for example gpt-4o-mini.")
+ if not (key or env.get("LLM_API_KEY")):
+ raise SetupError("Paste the API key for this model.")
+ updates.update(LLM_BASE_URL=base, LLM_MODEL=model)
+ if key:
+ updates["LLM_API_KEY"] = key
+ elif choice is not None:
+ raise SetupError("llm_provider must be gemini or openai.")
+ return updates
+
+
+def _short(err: Exception) -> str:
+ return str(err).split(" (request_id")[0][:200]
+
+
+def check_jev(key: str, model: str = "jev-latest", client_factory=None) -> dict:
+ from typesafe_sdk import TypeSafeAuthenticationError, TypeSafeClient, TypeSafeError, TypeSafePermissionDeniedError
+
+ try:
+ client = (client_factory or TypeSafeClient)(api_key=key, timeout=TIMEOUT)
+ try:
+ names = [m.name for m in client.models.list().models]
+ finally:
+ client.close()
+ except (TypeSafeAuthenticationError, TypeSafePermissionDeniedError):
+ return {"ok": False, "message": "TypeSafe rejected this key."}
+ except TypeSafeError as e:
+ return {"ok": False, "message": f"Could not check the key with TypeSafe: {_short(e)}"}
+ if model not in names:
+ return {"ok": False, "message": f"The key works, but {model} is not available to it."}
+ return {"ok": True, "message": "Jev key works."}
+
+
+def check_llm(choice: str, key: str, base_url: str | None = None, model: str | None = None, client_factory=None) -> dict:
+ from openai import APIConnectionError, APIStatusError, OpenAI
+
+ make = client_factory or OpenAI
+ try:
+ if choice == "gemini":
+ make(api_key=key, base_url=GEMINI_BASE_URL, timeout=TIMEOUT, max_retries=0).models.list()
+ else:
+ make(api_key=key, base_url=base_url, timeout=TIMEOUT, max_retries=0).chat.completions.create(
+ model=model, messages=[{"role": "user", "content": "Say OK"}], max_tokens=1)
+ except APIStatusError as e:
+ who = "Google" if choice == "gemini" else "The provider"
+ if e.status_code in (401, 403) or (choice == "gemini" and e.status_code == 400):
+ return {"ok": False, "message": f"{who} rejected this key."}
+ if e.status_code == 404:
+ return {"ok": False, "message": f"The provider has no model called {model}."}
+ return {"ok": False, "message": f"{who} refused the test request (HTTP {e.status_code}): {_short(e)}"}
+ except APIConnectionError:
+ return {"ok": False, "message": f"Could not reach {base_url or GEMINI_BASE_URL}."}
+ return {"ok": True, "message": "Gemini key works." if choice == "gemini" else f"{model} answered."}
+```
+
+Note: `APITimeoutError` is a subclass of `APIConnectionError`, so one `except` covers both.
+
+- [ ] **Step 4: Run and pass**
+
+Run: `uv run pytest tests/test_keys.py -q`. Expected: all pass.
+
+- [ ] **Step 5: Commit**
+
+`git add src/jevfish/keys.py tests/test_keys.py && git commit -m "feat(jevfish): save keys to .env and check them for free"`
+
+### Task 3: The example module and Service.reload
+
+**Files:**
+- Create: `jevfish/src/jevfish/example.py`
+- Modify: `jevfish/src/jevfish/cli.py`, `jevfish/src/jevfish/service.py`
+- Test: `jevfish/tests/test_setup_api.py` (created in Task 4; the reload test goes there)
+
+- [ ] **Step 1: Create `example.py`**
+
+```python
+"""The example project: made-up figures for a Singapore co-living brand."""
+
+from __future__ import annotations
+
+from .config import PACKAGE_ROOT
+
+PATH = PACKAGE_ROOT / "examples" / "lazybee-cleaning.md"
+NAME = "Lazybee cleaning upgrade (example)"
+QUESTION = ("If Lazybee adds weekly professional cleaning for S$100 more a month (example figure), "
+ "will more Singapore renters book a viewing?")
+
+
+def example() -> dict:
+ return {"name": NAME, "requirement": QUESTION, "seed_text": PATH.read_text()}
+```
+
+- [ ] **Step 2: Point `cli.py` at it**
+
+Replace `EXAMPLE = PACKAGE_ROOT / "examples" / "lazybee-cleaning.md"` with `from . import example`, and use `example.PATH`, `example.NAME` and `example.QUESTION` as the `demo` defaults.
+
+- [ ] **Step 3: Add `Service.reload`**
+
+In `Service.__init__`, add `self._llm_injected = llm is not None`. Then add:
+
+```python
+ def reload(self, settings: Settings) -> None:
+ """Use new keys from now on. Tasks already running keep what they started with.
+ The data folder never changes while the server runs."""
+ self.settings = replace(settings, data_dir=self.settings.data_dir)
+ if not self._llm_injected:
+ self._llm = None
+
+ def active_tasks(self) -> int:
+ return sum(1 for t in self.tasks.list() if t.status in ("queued", "running"))
+```
+
+with `from dataclasses import replace` at the top.
+
+- [ ] **Step 4: Run the existing suite**
+
+Run: `uv run pytest -q`. Expected: all pass (60 plus Task 1 and 2 tests).
+
+- [ ] **Step 5: Commit**
+
+`git commit -am "refactor(jevfish): shared example, Service.reload"`
+
+### Task 4: Setup API and the local-only guard
+
+**Files:**
+- Create: `jevfish/src/jevfish/setup_api.py`
+- Modify: `jevfish/src/jevfish/api.py`, `jevfish/src/jevfish/cli.py`
+- Test: `jevfish/tests/test_setup_api.py`
+
+- [ ] **Step 1: Write the failing tests**
+
+```python
+import os
+
+import pytest
+
+from jevfish import keys
+from jevfish.api import create_app
+from jevfish.llm import FakeLLM
+from jevfish.service import Service
+from tests.test_pipeline import settings
+
+MANAGED = ("TYPESAFE_API_KEY", "GEMINI_API_KEY", "LLM_API_KEY", "LLM_BASE_URL", "LLM_MODEL", "LLM_MODEL_NAME",
+ "JEVFISH_FAKE_JUDGE", "JEVFISH_FAKE_LLM", "JEVFISH_DATA_DIR")
+
+
+@pytest.fixture
+def env_file(tmp_path):
+ # saving settings edits os.environ directly, so snapshot and restore all of it
+ before = dict(os.environ)
+ for k in MANAGED:
+ os.environ.pop(k, None)
+ path = tmp_path / "keys.env"
+ os.environ["JEVFISH_ENV_FILE"] = str(path)
+ yield path
+ os.environ.clear()
+ os.environ.update(before)
+
+
+@pytest.fixture
+def app(tmp_path, env_file):
+ s = settings(tmp_path, fake_judge=False, fake_llm=False)
+ stopped = []
+ app = create_app(s, Service(s, llm=FakeLLM()))
+ app.config["JEVFISH_STOP"] = lambda: stopped.append(True)
+ app.stopped = stopped
+ return app
+
+
+def test_first_run_needs_setup_then_save_applies_without_restart(app, env_file, tmp_path):
+ c = app.test_client()
+ assert c.get("/api/health").get_json()["setup_needed"] is True
+ got = c.get("/api/settings").get_json()
+ assert got["typesafe_key"] is None and got["llm_provider"] == "gemini" and got["setup_needed"] is True
+ r = c.put("/api/settings", json={"typesafe_key": "ts-abcdefgh9999", "llm_provider": "gemini", "llm_key": "gm-abcdefgh7777"})
+ assert r.status_code == 200, r.get_json()
+ body = r.get_json()
+ assert body["typesafe_key"] == "9999" and body["gemini_key"] == "7777" and body["setup_needed"] is False
+ assert "ts-abcdefgh9999" not in r.get_data(as_text=True)
+ assert "TYPESAFE_API_KEY='ts-abcdefgh9999'" in env_file.read_text()
+ health = c.get("/api/health").get_json()
+ assert health["judge"] == "jev" and health["setup_needed"] is False
+ assert health["data_dir"] == str(tmp_path / "data")
+
+
+def test_test_mode_toggle(app):
+ c = app.test_client()
+ assert c.put("/api/settings", json={"test_mode": True}).get_json()["test_mode"] is True
+ assert c.get("/api/health").get_json()["judge"] == "fake"
+ assert c.put("/api/settings", json={"test_mode": False}).get_json()["test_mode"] is False
+ assert c.get("/api/health").get_json()["setup_needed"] is True
+
+
+def test_bad_form_is_400(app):
+ r = app.test_client().put("/api/settings", json={"llm_provider": "openai", "llm_base_url": "nope"})
+ assert r.status_code == 400 and "http" in r.get_json()["error"]
+
+
+def test_check_uses_form_keys_then_saved(app, monkeypatch):
+ calls = []
+ monkeypatch.setattr(keys, "check_jev", lambda key, model="jev-latest": calls.append(("jev", key)) or {"ok": True, "message": "j"})
+ monkeypatch.setattr(keys, "check_llm", lambda choice, key, base_url=None, model=None: calls.append((choice, key)) or {"ok": False, "message": "l"})
+ c = app.test_client()
+ r = c.post("/api/settings/check", json={"typesafe_key": "typed", "llm_provider": "gemini"}).get_json()
+ assert r["jev"]["ok"] is True and r["llm"] == {"ok": False, "message": "No Gemini key yet."}
+ assert calls == [("jev", "typed")]
+ monkeypatch.setenv("GEMINI_API_KEY", "saved-g")
+ c.post("/api/settings/check", json={})
+ assert calls[-1] == ("gemini", "saved-g")
+
+
+def test_example_and_shutdown(app):
+ c = app.test_client()
+ ex = c.get("/api/example").get_json()
+ assert "Lazybee" in ex["name"] and ex["seed_text"].strip() and ex["requirement"].endswith("?")
+ assert c.post("/api/shutdown").get_json()["ok"] is True
+ import time
+ time.sleep(0.5)
+ assert app.stopped == [True]
+
+
+def test_guard_blocks_other_hosts_and_origins(app):
+ c = app.test_client()
+ assert c.get("/api/health", headers={"Host": "evil.example"}).status_code == 403
+ assert c.get("/api/health", headers={"Host": "127.0.0.1:5055"}).status_code == 200
+ assert c.put("/api/settings", json={"test_mode": True}, headers={"Origin": "https://evil.example"}).status_code == 403
+ assert c.put("/api/settings", json={"test_mode": True}, headers={"Origin": "http://localhost:5173"}).status_code == 200
+ assert c.get("/", headers={"Host": "evil.example"}).status_code == 200 # the page itself holds no data
+
+
+def test_guard_can_be_turned_off(tmp_path, env_file):
+ s = settings(tmp_path)
+ app = create_app(s, Service(s, llm=FakeLLM()), allow_remote=True)
+ assert app.test_client().get("/api/health", headers={"Host": "192.168.1.9:5055"}).status_code == 200
+```
+
+- [ ] **Step 2: Run and fail**
+
+Run: `uv run pytest tests/test_setup_api.py -q`. Expected: FAIL (404s and `allow_remote` TypeError).
+
+- [ ] **Step 3: Implement `setup_api.py`**
+
+```python
+"""Setup endpoints (keys, test mode, the example, stopping) and the local-only guard."""
+
+from __future__ import annotations
+
+import os
+import signal
+import threading
+from urllib.parse import urlsplit
+
+from flask import Blueprint, current_app, jsonify, request
+
+from . import example, keys
+from .config import env_file_path, load_settings
+from .keys import SetupError
+
+bp = Blueprint("setup", __name__)
+LOCAL_NAMES = {"127.0.0.1", "localhost", "::1"}
+
+
+def _svc():
+ return current_app.extensions["jevfish"]
+
+
+def _form() -> dict:
+ data = request.get_json(silent=True)
+ if not isinstance(data, dict):
+ raise SetupError("Send the settings as JSON.")
+ return data
+
+
+def is_local(netloc: str) -> bool:
+ return (urlsplit("//" + netloc).hostname or "") in LOCAL_NAMES
+
+
+def guard():
+ """Only this computer may use the API. Blocks DNS rebinding and other sites' forms."""
+ if not request.path.startswith("/api/") or current_app.config.get("JEVFISH_ALLOW_REMOTE"):
+ return None
+ if not is_local(request.host):
+ return jsonify(error="JevFish only answers on this computer. Open http://127.0.0.1 instead."), 403
+ origin = request.headers.get("Origin")
+ if request.method not in ("GET", "HEAD", "OPTIONS") and origin is not None and not is_local(urlsplit(origin).netloc):
+ return jsonify(error="Requests from other websites are blocked."), 403
+ return None
+
+
+@bp.errorhandler(SetupError)
+def setup_error(e):
+ return jsonify(error=str(e)), 400
+
+
+@bp.get("/api/settings")
+def get_settings():
+ env, svc = os.environ, _svc()
+ s = svc.settings
+ return jsonify(
+ env_file=str(env_file_path()),
+ test_mode=s.fake_judge or s.fake_llm,
+ setup_needed=not (s.llm_ready and s.judge_ready),
+ typesafe_key=keys.hint(env.get("TYPESAFE_API_KEY")),
+ llm_provider=keys.provider(env),
+ gemini_key=keys.hint(env.get("GEMINI_API_KEY")),
+ llm_key=keys.hint(env.get("LLM_API_KEY")),
+ llm_base_url=env.get("LLM_BASE_URL", ""),
+ llm_model=env.get("LLM_MODEL", "") or env.get("LLM_MODEL_NAME", ""),
+ active_tasks=svc.active_tasks(),
+ )
+
+
+@bp.put("/api/settings")
+def put_settings():
+ updates = keys.updates_from_form(_form(), os.environ)
+ keys.write_env(env_file_path(), updates)
+ keys.apply(updates)
+ _svc().reload(load_settings())
+ return get_settings()
+
+
+@bp.post("/api/settings/check")
+def check():
+ form, env = _form(), os.environ
+ jev_key = keys.text(form, "typesafe_key") or env.get("TYPESAFE_API_KEY", "")
+ jev = keys.check_jev(jev_key, _svc().settings.jev_model) if jev_key else {"ok": False, "message": "No Jev key yet."}
+ choice = form.get("llm_provider") or keys.provider(env)
+ typed = keys.text(form, "llm_key")
+ if choice == "gemini":
+ key = typed or env.get("GEMINI_API_KEY", "")
+ llm = keys.check_llm("gemini", key) if key else {"ok": False, "message": "No Gemini key yet."}
+ else:
+ key = typed or env.get("LLM_API_KEY", "")
+ base = keys.text(form, "llm_base_url") or env.get("LLM_BASE_URL", "")
+ model = keys.text(form, "llm_model") or env.get("LLM_MODEL", "")
+ llm = keys.check_llm("openai", key, base, model) if key and base and model else {
+ "ok": False, "message": "Fill in the address, model and key first."}
+ return jsonify(jev=jev, llm=llm)
+
+
+@bp.get("/api/example")
+def get_example():
+ return jsonify(example.example())
+
+
+def _stop_process() -> None:
+ os.kill(os.getpid(), signal.SIGTERM)
+
+
+@bp.post("/api/shutdown")
+def shutdown():
+ stop = current_app.config.get("JEVFISH_STOP") or _stop_process
+ threading.Timer(0.3, stop).start() # let the response go out first
+ return jsonify(ok=True)
+```
+
+- [ ] **Step 4: Wire it into `api.py`**
+
+- Signature: `def create_app(settings=None, service=None, allow_remote: bool = False) -> Flask:`.
+- After `app.extensions["jevfish"] = svc`, add:
+ - `app.config["JEVFISH_ALLOW_REMOTE"] = allow_remote`
+ - `app.before_request(guard)`
+ - `app.register_blueprint(setup_bp)`
+- Import with `from .setup_api import bp as setup_bp, guard`.
+- `health()` returns `jsonify(ok=True, **svc.settings.health())`.
+- `estimate()` uses `svc.settings.max_requests`.
+
+The blueprint must be registered before the catch-all `web` route is declared. Flask matches `/api/settings` over `/` either way, because static rules win, but register first for clarity.
+
+- [ ] **Step 5: `cli.py` serve**
+
+```python
+ local = args.host in ("127.0.0.1", "localhost", "::1")
+ if not local:
+ print("Warning: listening beyond this computer. Anyone who can reach it can change the keys.")
+ app = create_app(settings, allow_remote=not local)
+```
+
+- [ ] **Step 6: Run and pass**
+
+Run: `uv run pytest -q`. Expected: all pass.
+
+- [ ] **Step 7: Commit**
+
+`git add -A src tests && git commit -m "feat(jevfish): setup API (keys, test mode, example, stop) and local-only guard"`
+
+### Task 5: Web app, Setup screen and example button
+
+**Files:**
+- Create: `jevfish/web/src/lib/health.js`, `jevfish/web/src/views/SetupView.vue`
+- Modify: `jevfish/web/src/lib/api.js`, `jevfish/web/src/router.js`, `jevfish/web/src/App.vue`, `jevfish/web/src/views/ProjectsView.vue`
+
+- [ ] **Step 1: `api.js`**
+
+Add to the `api` object:
+
+```js
+ settings: () => request('GET', '/settings'),
+ saveSettings: (body) => request('PUT', '/settings', body),
+ checkKeys: (body) => request('POST', '/settings/check', body),
+ example: () => request('GET', '/example'),
+ shutdown: () => request('POST', '/shutdown'),
+```
+
+- [ ] **Step 2: `lib/health.js`**
+
+```js
+// One shared copy of /api/health, so the banner and the Setup screen agree.
+import { ref } from 'vue'
+import { api } from './api.js'
+
+export const health = ref(null)
+export const healthError = ref('')
+
+export async function refreshHealth() {
+ try {
+ health.value = await api.health()
+ healthError.value = ''
+ } catch (e) {
+ healthError.value = e.message
+ }
+ return health.value
+}
+```
+
+- [ ] **Step 3: `router.js`**
+
+- Import `SetupView`.
+- Add `{ path: '/setup', name: 'setup', component: SetupView }` before the catch-all.
+- Export the router, then add:
+
+```js
+// First load only: send people without keys to Setup.
+let firstLoad = true
+router.beforeEach(async (to) => {
+ if (!firstLoad) return true
+ firstLoad = false
+ const h = await refreshHealth()
+ if (h && h.setup_needed && to.name !== 'setup') return { name: 'setup' }
+ return true
+})
+```
+
+- [ ] **Step 4: `App.vue`**
+
+- Drop the local `health`/`healthError` refs and the `onMounted` fetch. Import them from `lib/health.js`.
+- Import `useRoute`, and hide the banners on the setup route: `const onSetup = computed(() => route.name === 'setup')`.
+- The template banners wrapper becomes `v-if="!onSetup && (warnings.length || healthError)"`.
+- Each warning gets `Open settings` after the text.
+- Add `Settings` before the theme switch.
+- Warning wording: "Jev is not set up yet." and "No language model is set up yet."
+
+- [ ] **Step 5: `SetupView.vue`**
+
+Complete file:
+
+```vue
+
+
+
+
+
JevFish has stopped
+
You can close this tab. Open JevFish.app to start it again.
+
+
+
+
{{ firstRun ? 'Set up JevFish' : 'Settings' }}
+
+ JevFish needs two keys. Jev decides what each simulated person does, and a language model writes the graph, the crowd and
+ the posts. Keys stay in a file on this computer.
+
+
+
+
{{ loadError }}
+
+
+
+
+
+
Test mode
+
Try every screen without keys. Every number it shows is made up.
+
+
+ {{ saved.test_mode ? 'On' : 'Off' }}
+
+
+
+
+
+
+
Stop JevFish
+
Shuts JevFish down on this computer. Open JevFish.app to start it again.
+
+
+
+
+
Keys are saved in {{ saved.env_file }}
+
+
+
+
+
+```
+
+- [ ] **Step 6: `ProjectsView.vue`, fill in the example**
+
+Script:
+
+```js
+const exampleNote = ref(false)
+
+async function loadExample() {
+ createError.value = ''
+ try {
+ const ex = await api.example()
+ name.value = ex.name
+ question.value = ex.requirement
+ seedText.value = ex.seed_text
+ showForm.value = true
+ exampleNote.value = true
+ } catch (e) {
+ createError.value = e.message
+ }
+}
+```
+
+In the panel head, before the Hide/Show form button, add:
+
+```html
+
+```
+
+At the top of the form, add:
+
+```html
+
The example is a Singapore co-living brand with made-up figures.
+`}tablecell(e){let t=this.parser.parseInline(e.tokens),n=e.header?"th":"td";return(e.align?`<${n} align="${e.align}">`:`<${n}>`)+t+`${n}>
+`}strong({tokens:e}){return`${this.parser.parseInline(e)}`}em({tokens:e}){return`${this.parser.parseInline(e)}`}codespan({text:e}){return`${Kt(e,!0)}`}br(e){return" "}del({tokens:e}){return`${this.parser.parseInline(e)}`}link({href:e,title:t,tokens:n}){let s=this.parser.parseInline(n),l=$a(e);if(l===null)return s;e=l;let r='"+s+"",r}image({href:e,title:t,text:n,tokens:s}){s&&(n=this.parser.parseInline(s,this.parser.textRenderer));let l=$a(e);if(l===null)return Kt(n);e=l;let r=`",r}text(e){return"tokens"in e&&e.tokens?this.parser.parseInline(e.tokens):"escaped"in e&&e.escaped?e.text:Kt(e.text)}},Yo=class{strong({text:e}){return e}em({text:e}){return e}codespan({text:e}){return e}del({text:e}){return e}html({text:e}){return e}text({text:e}){return e}link({text:e}){return""+e}image({text:e}){return""+e}br(){return""}},jt=class mo{options;renderer;textRenderer;constructor(t){this.options=t||Jn,this.options.renderer=this.options.renderer||new Hl,this.renderer=this.options.renderer,this.renderer.options=this.options,this.renderer.parser=this,this.textRenderer=new Yo}static parse(t,n){return new mo(n).parse(t)}static parseInline(t,n){return new mo(n).parseInline(t)}parse(t,n=!0){let s="";for(let l=0;l{let o=l[r].flat(1/0);n=n.concat(this.walkTokens(o,t))}):l.tokens&&(n=n.concat(this.walkTokens(l.tokens,t)))}}return n}use(...e){let t=this.defaults.extensions||{renderers:{},childTokens:{}};return e.forEach(n=>{let s={...n};if(s.async=this.defaults.async||s.async||!1,n.extensions&&(n.extensions.forEach(l=>{if(!l.name)throw new Error("extension name required");if("renderer"in l){let r=t.renderers[l.name];r?t.renderers[l.name]=function(...o){let a=l.renderer.apply(this,o);return a===!1&&(a=r.apply(this,o)),a}:t.renderers[l.name]=l.renderer}if("tokenizer"in l){if(!l.level||l.level!=="block"&&l.level!=="inline")throw new Error("extension level must be 'block' or 'inline'");let r=t[l.level];r?r.unshift(l.tokenizer):t[l.level]=[l.tokenizer],l.start&&(l.level==="block"?t.startBlock?t.startBlock.push(l.start):t.startBlock=[l.start]:l.level==="inline"&&(t.startInline?t.startInline.push(l.start):t.startInline=[l.start]))}"childTokens"in l&&l.childTokens&&(t.childTokens[l.name]=l.childTokens)}),s.extensions=t),n.renderer){let l=this.defaults.renderer||new Hl(this.defaults);for(let r in n.renderer){if(!(r in l))throw new Error(`renderer '${r}' does not exist`);if(["options","parser"].includes(r))continue;let o=r,a=n.renderer[o],u=l[o];l[o]=(...d)=>{let c=a.apply(l,d);return c===!1&&(c=u.apply(l,d)),c||""}}s.renderer=l}if(n.tokenizer){let l=this.defaults.tokenizer||new ql(this.defaults);for(let r in n.tokenizer){if(!(r in l))throw new Error(`tokenizer '${r}' does not exist`);if(["options","rules","lexer"].includes(r))continue;let o=r,a=n.tokenizer[o],u=l[o];l[o]=(...d)=>{let c=a.apply(l,d);return c===!1&&(c=u.apply(l,d)),c}}s.tokenizer=l}if(n.hooks){let l=this.defaults.hooks||new Ds;for(let r in n.hooks){if(!(r in l))throw new Error(`hook '${r}' does not exist`);if(["options","block"].includes(r))continue;let o=r,a=n.hooks[o],u=l[o];Ds.passThroughHooks.has(r)?l[o]=d=>{if(this.defaults.async&&Ds.passThroughHooksRespectAsync.has(r))return(async()=>{let f=await a.call(l,d);return u.call(l,f)})();let c=a.call(l,d);return u.call(l,c)}:l[o]=(...d)=>{if(this.defaults.async)return(async()=>{let f=await a.apply(l,d);return f===!1&&(f=await u.apply(l,d)),f})();let c=a.apply(l,d);return c===!1&&(c=u.apply(l,d)),c}}s.hooks=l}if(n.walkTokens){let l=this.defaults.walkTokens,r=n.walkTokens;s.walkTokens=function(o){let a=[];return a.push(r.call(this,o)),l&&(a=a.concat(l.call(this,o))),a}}this.defaults={...this.defaults,...s}}),this}setOptions(e){return this.defaults={...this.defaults,...e},this}lexer(e,t){return Ft.lex(e,t??this.defaults)}parser(e,t){return jt.parse(e,t??this.defaults)}parseMarkdown(e){return(t,n)=>{let s={...n},l={...this.defaults,...s},r=this.onError(!!l.silent,!!l.async);if(this.defaults.async===!0&&s.async===!1)return r(new Error("marked(): The async option was set to true by an extension. Remove async: false from the parse options object to return a Promise."));if(typeof t>"u"||t===null)return r(new Error("marked(): input parameter is undefined or null"));if(typeof t!="string")return r(new Error("marked(): input parameter is of type "+Object.prototype.toString.call(t)+", string expected"));if(l.hooks&&(l.hooks.options=l,l.hooks.block=e),l.async)return(async()=>{let o=l.hooks?await l.hooks.preprocess(t):t,a=await(l.hooks?await l.hooks.provideLexer():e?Ft.lex:Ft.lexInline)(o,l),u=l.hooks?await l.hooks.processAllTokens(a):a;l.walkTokens&&await Promise.all(this.walkTokens(u,l.walkTokens));let d=await(l.hooks?await l.hooks.provideParser():e?jt.parse:jt.parseInline)(u,l);return l.hooks?await l.hooks.postprocess(d):d})().catch(r);try{l.hooks&&(t=l.hooks.preprocess(t));let o=(l.hooks?l.hooks.provideLexer():e?Ft.lex:Ft.lexInline)(t,l);l.hooks&&(o=l.hooks.processAllTokens(o)),l.walkTokens&&this.walkTokens(o,l.walkTokens);let a=(l.hooks?l.hooks.provideParser():e?jt.parse:jt.parseInline)(o,l);return l.hooks&&(a=l.hooks.postprocess(a)),a}catch(o){return r(o)}}}onError(e,t){return n=>{if(n.message+=`
+Please report this to https://github.com/markedjs/marked.`,e){let s="
An error occurred:
"+Kt(n.message+"",!0)+"
";return t?Promise.resolve(s):s}if(t)return Promise.reject(n);throw n}}},Kn=new M0;function Be(e,t){return Kn.parse(e,t)}Be.options=Be.setOptions=function(e){return Kn.setOptions(e),Be.defaults=Kn.defaults,Ec(Be.defaults),Be};Be.getDefaults=Vo;Be.defaults=Jn;Be.use=function(...e){return Kn.use(...e),Be.defaults=Kn.defaults,Ec(Be.defaults),Be};Be.walkTokens=function(e,t){return Kn.walkTokens(e,t)};Be.parseInline=Kn.parseInline;Be.Parser=jt;Be.parser=jt.parse;Be.Renderer=Hl;Be.TextRenderer=Yo;Be.Lexer=Ft;Be.lexer=Ft.lex;Be.Tokenizer=ql;Be.Hooks=Ds;Be.parse=Be;Be.options;Be.setOptions;Be.use;Be.walkTokens;Be.parseInline;jt.parse;Ft.lex;function Ea(e,t){(t==null||t>e.length)&&(t=e.length);for(var n=0,s=Array(t);n2?s-2:0),r=2;r1?n-1:0),l=1;l"u"?null:st(BigInt.prototype.toString),Na=typeof Symbol>"u"?null:st(Symbol.prototype.toString),Ct=st(Object.prototype.hasOwnProperty),Os=st(Object.prototype.toString),dt=st(RegExp.prototype.test),Dn=Y0(TypeError);function st(e){return function(t){t instanceof RegExp&&(t.lastIndex=0);for(var n=arguments.length,s=new Array(n>1?n-1:0),l=1;l2&&arguments[2]!==void 0?arguments[2]:Fs;if(Aa&&Aa(e,null),!cs(t))return e;let s=t.length;for(;s--;){let l=t[s];if(typeof l=="string"){const r=n(l);r!==l&&(V0(t)||(t[s]=r),l=r)}e[l]=!0}return e}function J0(e){for(let t=0;t/g),sw=it(/\${[\w\W]*/g),lw=it(/^data-[\-\w.\u00B7-\uFFFF]+$/),rw=it(/^aria-[\-\w]+$/),Fa=it(/^(?:(?:(?:f|ht)tps?|mailto|tel|callto|sms|cid|xmpp|matrix):|[^a-z]|[a-z+.\-]+(?:[^a-z+.\-:]|$))/i),ow=it(/^(?:\w+script|data):/i),iw=it(/[\u0000-\u0020\u00A0\u1680\u180E\u2000-\u2029\u205F\u3000]/g),aw=it(/^html$/i),uw=it(/^[a-z][.\w]*(-[.\w]+)+$/i),ja=it(/<[/\w!]/g),Ua=it(/<[/\w]/g),cw=it(/<\/no(script|embed|frames)/i),dw=it(/\/>/i),Ot={element:1,attribute:2,text:3,cdataSection:4,entityReference:5,entityNode:6,processingInstruction:7,comment:8,document:9,documentType:10,documentFragment:11,notation:12},Uc=["style","script","xmp","iframe","noembed","noframes","plaintext","noscript"],fw=rt(Me({},Uc)),pw=(function(){const e={};return jn(Uc,t=>{e[t]=it(new RegExp(""+t+"(?=[\\t\\n\\f\\r />])","i"))}),rt(e)})(),hw=function(){return typeof window>"u"?null:window},mw=function(t,n){if(typeof t!="object"||typeof t.createPolicy!="function")return null;let s=null;const l="data-tt-policy-suffix";n&&n.hasAttribute(l)&&(s=n.getAttribute(l));const r="dompurify"+(s?"#"+s:"");try{return t.createPolicy(r,{createHTML(o){return o},createScriptURL(o){return o}})}catch{return console.warn("TrustedTypes policy "+r+" could not be created."),null}},Va=function(){return{afterSanitizeAttributes:[],afterSanitizeElements:[],afterSanitizeShadowDOM:[],beforeSanitizeAttributes:[],beforeSanitizeElements:[],beforeSanitizeShadowDOM:[],uponSanitizeAttribute:[],uponSanitizeElement:[],uponSanitizeShadowNode:[]}},Sn=function(t,n,s,l){return Ct(t,n)&&cs(t[n])?Me(l.base?Pt(l.base):{},t[n],l.transform):s},qr=function(t,n,s){const l=Ct(t,n)?t[n]:void 0;return l&&typeof l=="object"?Pt(l):s()};function Vc(){let e=arguments.length>0&&arguments[0]!==void 0?arguments[0]:hw();const t=re=>Vc(re);if(t.version="3.4.15",t.removed=[],!e||!e.document||e.document.nodeType!==Ot.document||!e.Element)return t.isSupported=!1,t;let n=e.document;const s=n,l=s.currentScript;e.DocumentFragment;const r=e.HTMLTemplateElement,o=e.Node,a=e.Element,u=e.NodeFilter,d=e.NamedNodeMap;d===void 0&&(e.NamedNodeMap||e.MozNamedAttrMap),e.HTMLFormElement;const c=e.DOMParser,f=e.trustedTypes,p=a.prototype,g=Mt(p,"cloneNode"),N=Mt(p,"remove"),x=Mt(p,"removeAttributeNode"),R=Mt(p,"nextSibling"),A=Mt(p,"childNodes"),P=Mt(p,"parentNode"),j=Mt(p,"shadowRoot"),O=Mt(p,"attributes"),C=o&&o.prototype?Mt(o.prototype,"nodeType"):null,D=o&&o.prototype?Mt(o.prototype,"nodeName"):null,k=o&&o.prototype?Mt(o.prototype,"ownerDocument"):null,_=function(v){return C?C(v):v.nodeType},w=function(v){return D?D(v):v.nodeName};if(typeof r=="function"){const re=n.createElement("template");re.content&&re.content.ownerDocument&&(n=re.content.ownerDocument)}let E,S="",I,V=!1,z=0;const ge=function(){if(z>0)throw Dn('A configured TRUSTED_TYPES_POLICY callback (createHTML or createScriptURL) must not call DOMPurify.sanitize, as that causes infinite recursion. Do not pass a policy whose callbacks wrap DOMPurify as TRUSTED_TYPES_POLICY; see the "DOMPurify and Trusted Types" section of the README.')},le=function(v){ge(),z++;try{return E.createHTML(v)}finally{z--}},F=function(v){ge(),z++;try{return E.createScriptURL(v)}finally{z--}},$=function(){return V||(I=mw(f,l),V=!0),I},W=n,oe=W.implementation,te=W.createNodeIterator,ee=W.createDocumentFragment,G=W.getElementsByTagName,Y=s.importNode;let ne=Va();t.isSupported=typeof Fc=="function"&&typeof P=="function"&&oe&&oe.createHTMLDocument!==void 0;const Ee=tw,H=nw,ae=sw,ce=lw,be=rw,Re=ow,b=iw,T=uw;let L=Fa,B=null;const X=Me({},[...Ia,...Ur,...Vr,...Br,...Ma]);let U=null;const fe=Me({},[...La,...zr,...Da,...El]);let ie=Object.seal(os(null,{tagNameCheck:{writable:!0,configurable:!1,enumerable:!0,value:null},attributeNameCheck:{writable:!0,configurable:!1,enumerable:!0,value:null},allowCustomizedBuiltInElements:{writable:!0,configurable:!1,enumerable:!0,value:!1}})),ue=null,Q=null;const ve=Object.seal(os(null,{tagCheck:{writable:!0,configurable:!1,enumerable:!0,value:null},attributeCheck:{writable:!0,configurable:!1,enumerable:!0,value:null}}));let pe=!0,_e=!0,we=!1,Ce=!0,Oe=!1,Pe=!0,qe=!1,tt=!1,mt=null,gt=null,rn=!1,on=!1,ot=!1,vt=!1,ys=!0,bs=!1;const Jo="user-content-";let pr=!0,hr=!1,Xn={},Zn=null;const Xo=Me({},["annotation-xml","audio","colgroup","desc","foreignobject","head","iframe","math","mi","mn","mo","ms","mtext","noembed","noframes","noscript","plaintext","script","selectedcontent","style","svg","template","thead","title","video","xmp"]);let Zo=null;const Qo=Me({},["audio","video","img","source","image","track"]);let ei=null;const ti=Me({},["alt","class","for","id","label","name","pattern","placeholder","role","summary","title","value","style","xmlns"]),fl="http://www.w3.org/1998/Math/MathML",pl="http://www.w3.org/2000/svg",Ht="http://www.w3.org/1999/xhtml";let Qn=Ht,mr=!1,gr=null;const zc=Me({},[fl,pl,Ht],jr),ni=rt(["mi","mo","mn","ms","mtext"]);let vr=Me({},ni);const si=rt(["annotation-xml"]);let yr=Me({},si);const qc=Me({},["title","style","font","a","script"]);let _s=null;const Hc=["application/xhtml+xml","text/html"],Gc="text/html";let nt=null,es=null;const Wc=n.createElement("form"),li=function(v){return v instanceof RegExp||v instanceof Function},br=function(){let v=arguments.length>0&&arguments[0]!==void 0?arguments[0]:{};if(es&&es===v)return;(!v||typeof v!="object")&&(v={}),v=Pt(v),_s=Hc.indexOf(v.PARSER_MEDIA_TYPE)===-1?Gc:v.PARSER_MEDIA_TYPE,nt=_s==="application/xhtml+xml"?jr:Fs,B=Sn(v,"ALLOWED_TAGS",X,{transform:nt}),U=Sn(v,"ALLOWED_ATTR",fe,{transform:nt}),gr=Sn(v,"ALLOWED_NAMESPACES",zc,{transform:jr}),ei=Sn(v,"ADD_URI_SAFE_ATTR",ti,{transform:nt,base:ti}),Zo=Sn(v,"ADD_DATA_URI_TAGS",Qo,{transform:nt,base:Qo}),Zn=Sn(v,"FORBID_CONTENTS",Xo,{transform:nt}),ue=Sn(v,"FORBID_TAGS",Pt({}),{transform:nt}),Q=Sn(v,"FORBID_ATTR",Pt({}),{transform:nt}),Xn=Ct(v,"USE_PROFILES")?v.USE_PROFILES&&typeof v.USE_PROFILES=="object"?Pt(v.USE_PROFILES):v.USE_PROFILES:!1,pe=v.ALLOW_ARIA_ATTR!==!1,_e=v.ALLOW_DATA_ATTR!==!1,we=v.ALLOW_UNKNOWN_PROTOCOLS||!1,Ce=v.ALLOW_SELF_CLOSE_IN_ATTR!==!1,Oe=v.SAFE_FOR_TEMPLATES||!1,Pe=v.SAFE_FOR_XML!==!1,qe=v.WHOLE_DOCUMENT||!1,on=v.RETURN_DOM||!1,ot=v.RETURN_DOM_FRAGMENT||!1,vt=v.RETURN_TRUSTED_TYPE||!1,rn=v.FORCE_BODY||!1,ys=v.SANITIZE_DOM!==!1,bs=v.SANITIZE_NAMED_PROPS||!1,pr=v.KEEP_CONTENT!==!1,hr=v.IN_PLACE||!1,L=Z0(v.ALLOWED_URI_REGEXP)?v.ALLOWED_URI_REGEXP:Fa,Qn=typeof v.NAMESPACE=="string"?v.NAMESPACE:Ht,vr=qr(v,"MATHML_TEXT_INTEGRATION_POINTS",()=>Me({},ni)),yr=qr(v,"HTML_INTEGRATION_POINTS",()=>Me({},si));const M=qr(v,"CUSTOM_ELEMENT_HANDLING",()=>os(null));if(ie=os(null),Ct(M,"tagNameCheck")&&li(M.tagNameCheck)&&(ie.tagNameCheck=M.tagNameCheck),Ct(M,"attributeNameCheck")&&li(M.attributeNameCheck)&&(ie.attributeNameCheck=M.attributeNameCheck),Ct(M,"allowCustomizedBuiltInElements")&&typeof M.allowCustomizedBuiltInElements=="boolean"&&(ie.allowCustomizedBuiltInElements=M.allowCustomizedBuiltInElements),it(ie),Oe&&(_e=!1),ot&&(on=!0),Xn&&(B=Me({},Ma),U=os(null),Xn.html===!0&&(Me(B,Ia),Me(U,La)),Xn.svg===!0&&(Me(B,Ur),Me(U,zr),Me(U,El)),Xn.svgFilters===!0&&(Me(B,Vr),Me(U,zr),Me(U,El)),Xn.mathMl===!0&&(Me(B,Br),Me(U,Da),Me(U,El))),ve.tagCheck=null,ve.attributeCheck=null,Ct(v,"ADD_TAGS")&&(typeof v.ADD_TAGS=="function"?ve.tagCheck=v.ADD_TAGS:cs(v.ADD_TAGS)&&(B===X&&(B=Pt(B)),Me(B,v.ADD_TAGS,nt))),Ct(v,"ADD_ATTR")&&(typeof v.ADD_ATTR=="function"?ve.attributeCheck=v.ADD_ATTR:cs(v.ADD_ATTR)&&(U===fe&&(U=Pt(U)),Me(U,v.ADD_ATTR,nt))),Ct(v,"ADD_FORBID_CONTENTS")&&cs(v.ADD_FORBID_CONTENTS)&&(Zn===Xo&&(Zn=Pt(Zn)),Me(Zn,v.ADD_FORBID_CONTENTS,nt)),pr&&(B["#text"]=!0),qe&&Me(B,["html","head","body"]),B.table&&(Me(B,["tbody"]),delete ue.tbody),v.TRUSTED_TYPES_POLICY){if(typeof v.TRUSTED_TYPES_POLICY.createHTML!="function")throw Dn('TRUSTED_TYPES_POLICY configuration option must provide a "createHTML" hook.');if(typeof v.TRUSTED_TYPES_POLICY.createScriptURL!="function")throw Dn('TRUSTED_TYPES_POLICY configuration option must provide a "createScriptURL" hook.');const Z=E;E=v.TRUSTED_TYPES_POLICY;try{S=le("")}catch(he){throw E=Z,he}}else v.TRUSTED_TYPES_POLICY===null?(E=void 0,S=""):(E===void 0&&(E=$()),E&&typeof S=="string"&&(S=le("")));rt&&rt(v),es=v},ri=Me({},[...Ur,...Vr,...Q0]),oi=Me({},[...Br,...ew]),Kc=function(v,M,Z){return M.namespaceURI===Ht?v==="svg":M.namespaceURI===fl?v==="svg"&&(Z==="annotation-xml"||vr[Z]):!!ri[v]},Yc=function(v,M,Z){return M.namespaceURI===Ht?v==="math":M.namespaceURI===pl?v==="math"&&yr[Z]:!!oi[v]},Jc=function(v,M,Z){return M.namespaceURI===pl&&!yr[Z]||M.namespaceURI===fl&&!vr[Z]?!1:!oi[v]&&(qc[v]||!ri[v])},Xc=function(v){let M=P(v);(!M||!M.tagName)&&(M={namespaceURI:Qn,tagName:"template"});const Z=Fs(v.tagName),he=Fs(M.tagName);return gr[v.namespaceURI]?v.namespaceURI===pl?Kc(Z,M,he):v.namespaceURI===fl?Yc(Z,M,he):v.namespaceURI===Ht?Jc(Z,M,he):!!(_s==="application/xhtml+xml"&&gr[v.namespaceURI]):!1},xn=function(v){Rs(t.removed,{element:v});try{P(v).removeChild(v)}catch{if(N(v),!P(v))throw Dn("a node selected for removal could not be detached from its tree and cannot be safely returned; refusing to sanitize in place")}},ii=function(v,M,Z){try{x(v,M)}catch{try{v.removeAttribute(Z)}catch{}}},hl=function(v){ml(v);const M=A(v);if(M){const he=[];jn(M,ye=>{Rs(he,ye)}),jn(he,ye=>{try{N(ye)}catch{}})}const Z=O(v);if(Z)for(let he=Z.length-1;he>=0;--he){const ye=Z[he],$e=ye&&ye.name;typeof $e=="string"&&ii(v,ye,$e)}},In=function(v,M,Z){if(!Z)try{Z=M.getAttributeNode(v)}catch{Z=null}Rs(t.removed,{attribute:Z||null,from:M});try{Z?x(M,Z):M.removeAttribute(v)}catch{try{M.removeAttribute(v)}catch{}}if(v==="is")if(on||ot)try{xn(M)}catch{}else try{M.setAttribute(v,"")}catch{}},Zc=function(v){const M=O(v);if(M)for(let Z=M.length-1;Z>=0;--Z){const he=M[Z],ye=he&&he.name;typeof ye!="string"||U[nt(ye)]||ii(v,he,ye)}},ml=function(v){const M=[v];for(;M.length>0;){const Z=M.pop();_(Z)===Ot.element&&Zc(Z);const ye=A(Z);if(ye)for(let $e=ye.length-1;$e>=0;--$e)M.push(ye[$e])}},ai=function(v,M){return Pe?v==="patchsrc"?!0:v==="for"&&M!=="label"&&M!=="output":!1},Qc=function(v){if(!Pe)return;const M=[v];for(;M.length>0;){const Z=M.pop(),he=_(Z);if(he===Ot.processingInstruction||he===Ot.comment&&dt(Ua,Z.data)){try{N(Z)}catch{}continue}if(he===Ot.element){const $e=Z,Ke=nt(w(Z));try{$e.hasAttribute&&$e.hasAttribute("patchsrc")&&$e.removeAttribute("patchsrc"),$e.hasAttribute&&$e.hasAttribute("for")&&ai("for",Ke)&&$e.removeAttribute("for")}catch{}}const ye=A(Z);if(ye)for(let $e=ye.length-1;$e>=0;--$e)M.push(ye[$e])}},ui=function(v){let M=null,Z=null;if(rn)v=""+v;else{const $e=Ca(v,/^[\r\n\t ]+/);Z=$e&&$e[0]}_s==="application/xhtml+xml"&&Qn===Ht&&(v=''+v+"");const he=E?le(v):v;if(Qn===Ht)try{M=new c().parseFromString(he,_s)}catch{}if(!M||!M.documentElement){M=oe.createDocument(Qn,"template",null);try{M.documentElement.innerHTML=mr?S:he}catch{}}const ye=M.body||M.documentElement;return v&&Z&&ye.insertBefore(n.createTextNode(Z),ye.childNodes[0]||null),Qn===Ht?G.call(M,qe?"html":"body")[0]:qe?M.documentElement:ye},ci=function(v){const M=k?k(v):v.ownerDocument;return te.call(M||v,v,u.SHOW_ELEMENT|u.SHOW_COMMENT|u.SHOW_TEXT|u.SHOW_PROCESSING_INSTRUCTION|u.SHOW_CDATA_SECTION,null)},gl=function(v){return v=Cs(v,Ee," "),v=Cs(v,H," "),v=Cs(v,ae," "),v},_r=function(v){var M;v.normalize();const Z=k?k(v):v.ownerDocument,he=te.call(Z||v,v,u.SHOW_TEXT|u.SHOW_COMMENT|u.SHOW_CDATA_SECTION|u.SHOW_PROCESSING_INSTRUCTION,null);let ye=he.nextNode();for(;ye;)ye.data=gl(ye.data),ye=he.nextNode();const $e=(M=v.querySelectorAll)===null||M===void 0?void 0:M.call(v,"template");$e&&jn($e,Ke=>{ts(Ke.content)&&_r(Ke.content)})},vl=function(v){const M=D?D(v):null;return typeof M!="string"||nt(M)!=="form"?!1:typeof v.nodeName!="string"||typeof v.textContent!="string"||typeof v.removeChild!="function"||v.attributes!==O(v)||typeof v.removeAttribute!="function"||typeof v.removeAttributeNode!="function"||typeof v.getAttributeNode!="function"||typeof v.setAttribute!="function"||typeof v.namespaceURI!="string"||typeof v.insertBefore!="function"||typeof v.hasChildNodes!="function"||v.nodeType!==C(v)||v.childNodes!==A(v)},ts=function(v){if(!C||typeof v!="object"||v===null)return!1;try{return C(v)===Ot.documentFragment}catch{return!1}},ks=function(v){if(!C||typeof v!="object"||v===null)return!1;try{return typeof C(v)=="number"}catch{return!1}};function Gt(re,v,M){re.length!==0&&jn(re,Z=>{Z.call(t,v,M,es)})}const ed=function(v,M){return!!(Pe&&v.hasChildNodes()&&!ks(v.firstElementChild)&&dt(ja,v.textContent)&&dt(ja,v.innerHTML)||Pe&&v.namespaceURI===Ht&&fw[M]&&(ks(v.firstElementChild)||typeof v.textContent=="string"&&dt(pw[M],v.textContent))||v.nodeType===Ot.processingInstruction||Pe&&v.nodeType===Ot.comment&&dt(Ua,v.data))},yl=function(v,M){if(v instanceof RegExp)return dt(v,M);if(v instanceof Function){for(var Z=arguments.length,he=new Array(Z>2?Z-2:0),ye=2;ye=0;--Ke){const Ze=v===Z?g(ye[Ke],!0):ye[Ke];he.insertBefore(Ze,R(v))}}}return xn(v),!0},di=function(v,M,Z,he){return v.length===0?M:M===Z||M===he?Pt(M):M},fi=function(v,M){return v===M||P(v)!==null?!1:(hr&&ml(v),!0)},pi=function(v,M){if(Gt(ne.beforeSanitizeElements,v,null),fi(v,M))return!0;if(vl(v))return xn(v),!0;const Z=nt(w(v));if(B=di(ne.uponSanitizeElement,B,X,mt),Gt(ne.uponSanitizeElement,v,{tagName:Z,allowedTags:B}),fi(v,M))return!0;if(ed(v,Z))return xn(v),!0;if(ue[Z]||!(ve.tagCheck instanceof Function&&ve.tagCheck(Z))&&!B[Z]){const ye=td(v,Z,M);return ye===!1&&Gt(ne.afterSanitizeElements,v,null),ye}if(_(v)===Ot.element&&!Xc(v)||(Z==="noscript"||Z==="noembed"||Z==="noframes")&&dt(cw,v.innerHTML))return xn(v),!0;if(Oe&&v.nodeType===Ot.text){const ye=gl(v.textContent);v.textContent!==ye&&(Rs(t.removed,{element:v.cloneNode()}),v.textContent=ye)}return Gt(ne.afterSanitizeElements,v,null),!1},hi=function(v,M,Z){if(Q[M]||ai(M,v)||ys&&(M==="id"||M==="name")&&(Z in n||Z in Wc))return!1;const he=U[M]||ve.attributeCheck instanceof Function&&ve.attributeCheck(M,v);return _e&&dt(ce,M)||pe&&dt(be,M)?!0:he?ei[M]||dt(L,Cs(Z,b,""))||(M==="src"||M==="xlink:href"||M==="href")&&v!=="script"&&Oa(Z,"data:")===0&&Zo[v]||we&&!dt(Re,Cs(Z,b,""))?!0:!Z:mi(v)&&yl(ie.tagNameCheck,v)&&yl(ie.attributeNameCheck,M,v)||M==="is"&&ie.allowCustomizedBuiltInElements&&yl(ie.tagNameCheck,Z)},nd=Me({},["annotation-xml","color-profile","font-face","font-face-format","font-face-name","font-face-src","font-face-uri","missing-glyph"]),mi=function(v){return!nd[Fs(v)]&&dt(T,v)},sd=function(v,M,Z,he){if(E&&typeof f=="object"&&typeof f.getAttributeType=="function"&&!Z)switch(f.getAttributeType(v,M)){case"TrustedHTML":return le(he);case"TrustedScriptURL":return F(he)}return he},ld=function(v,M,Z,he){try{return Z?v.setAttributeNS(Z,M,he):v.setAttribute(M,he),vl(v)?(xn(v),!1):!0}catch{return In(M,v),!1}},gi=function(v){Gt(ne.beforeSanitizeAttributes,v,null);const M=v.attributes;if(!M||vl(v))return;U=di(ne.uponSanitizeAttribute,U,fe,gt);const Z={attrName:"",attrValue:"",keepAttr:!0,allowedAttributes:U,forceKeepAttr:void 0};let he=M.length;const ye=nt(v.nodeName);for(;he--;){const $e=M[he],Ke=$e.name,Ze=$e.namespaceURI,At=$e.value,Rt=nt(Ke),wr=At;let yt=Ke==="value"?wr:G0(wr),vi=!1;if(Z.attrName=Rt,Z.attrValue=yt,Z.keepAttr=!0,Z.forceKeepAttr=void 0,Gt(ne.uponSanitizeAttribute,v,Z),yt=Z.attrValue,bs&&(Rt==="id"||Rt==="name")&&Oa(yt,Jo)!==0&&(In(Ke,v,$e),yt=Jo+yt,vi=!0),Pe&&dt(/((--!?|])>)|<\/(style|script|title|xmp|textarea|noscript|iframe|noembed|noframes)/i,yt)){In(Ke,v,$e);continue}if(Rt==="attributename"&&Ca(yt,"href")){In(Ke,v,$e);continue}if(!Z.forceKeepAttr){if(!Z.keepAttr){In(Ke,v,$e);continue}if(!Ce&&dt(dw,yt)){In(Ke,v,$e);continue}if(Oe&&(yt=gl(yt)),!hi(ye,Rt,yt)){In(Ke,v,$e);continue}yt=sd(ye,Rt,Ze,yt),yt!==wr&&ld(v,Ke,Ze,yt)&&vi&&Ra(t.removed)}}Gt(ne.afterSanitizeAttributes,v,null)},bl=function(v){let M=null;const Z=ci(v);for(Gt(ne.beforeSanitizeShadowDOM,v,null);M=Z.nextNode();)if(Gt(ne.uponSanitizeShadowNode,M,null),pi(M,v),gi(M),ts(M.content)&&bl(M.content),_(M)===Ot.element){const he=j(M);ts(he)&&(kr(he),bl(he))}Gt(ne.afterSanitizeShadowDOM,v,null)},kr=function(v){const M=[{node:v,shadow:null}];for(;M.length>0;){const Z=M.pop();if(Z.shadow){bl(Z.shadow);continue}const he=Z.node,$e=_(he)===Ot.element,Ke=A(he);if(Ke)for(let Ze=Ke.length-1;Ze>=0;--Ze)M.push({node:Ke[Ze],shadow:null});if($e){const Ze=D?D(he):null;if(typeof Ze=="string"&&nt(Ze)==="template"){const At=he.content;ts(At)&&M.push({node:At,shadow:null})}}if($e){const Ze=j(he);ts(Ze)&&M.push({node:null,shadow:Ze},{node:Ze,shadow:null})}}};return t.sanitize=function(re){let v=arguments.length>1&&arguments[1]!==void 0?arguments[1]:{},M=null,Z=null,he=null,ye=null;if(mr=!re,mr&&(re=""),typeof re!="string"&&!ks(re)&&(re=X0(re),typeof re!="string"))throw Dn("dirty is not a string, aborting");if(!t.isSupported)return re;tt?(B=mt,U=gt):br(v),(ne.uponSanitizeElement.length>0||ne.uponSanitizeAttribute.length>0)&&(B=Pt(B)),ne.uponSanitizeAttribute.length>0&&(U=Pt(U)),t.removed=[];const $e=hr&&typeof re!="string"&&ks(re);if($e){Qc(re);const At=w(re);if(typeof At=="string"){const Rt=nt(At);if(!B[Rt]||ue[Rt])throw hl(re),Dn("root node is forbidden and cannot be sanitized in-place")}if(vl(re))throw hl(re),Dn("root node is clobbered and cannot be sanitized in-place");try{kr(re)}catch(Rt){throw hl(re),Rt}}else if(ks(re))M=ui(""),Z=M.ownerDocument.importNode(re,!0),Z.nodeType===Ot.element&&Z.nodeName==="BODY"||Z.nodeName==="HTML"?M=Z:M.appendChild(Z),kr(M);else{if(!on&&!Oe&&!qe&&re.indexOf("<")===-1)return E&&vt?le(re):re;if(M=ui(re),!M)return on?null:vt?S:""}M&&rn&&xn(M.firstChild);const Ke=$e?re:M;try{const At=ci(Ke);for(;he=At.nextNode();)pi(he,Ke),gi(he),ts(he.content)&&bl(he.content)}catch(At){throw $e&&(hl(re),jn(t.removed,Rt=>{Rt.element&&ml(Rt.element)})),At}if($e)return jn(t.removed,At=>{At.element&&ml(At.element)}),Oe&&_r(re),re;if(on){if(Oe&&_r(M),ot)for(ye=ee.call(M.ownerDocument);M.firstChild;)ye.appendChild(M.firstChild);else ye=M;return(U.shadowroot||U.shadowrootmode)&&(ye=Y.call(s,ye,!0)),ye}let Ze=qe?M.outerHTML:M.innerHTML;return qe&&B["!doctype"]&&M.ownerDocument&&M.ownerDocument.doctype&&M.ownerDocument.doctype.name&&dt(aw,M.ownerDocument.doctype.name)&&(Ze="
+`+Ze),Oe&&(Ze=gl(Ze)),E&&vt?le(Ze):Ze},t.setConfig=function(){let re=arguments.length>0&&arguments[0]!==void 0?arguments[0]:{};br(re),tt=!0,mt=B,gt=U},t.clearConfig=function(){es=null,tt=!1,mt=null,gt=null,E=I,S=""},t.isValidAttribute=function(re,v,M){es||br({});const Z=nt(re),he=nt(v);return hi(Z,he,M)},t.addHook=function(re,v){typeof v=="function"&&Ct(ne,re)&&Rs(ne[re],v)},t.removeHook=function(re,v){if(Ct(ne,re)){if(v!==void 0){const M=q0(ne[re],v);return M===-1?void 0:H0(ne[re],M,1)[0]}return Ra(ne[re])}},t.removeHooks=function(re){Ct(ne,re)&&(ne[re]=[])},t.removeAllHooks=function(){ne=Va()},t}var gw=Vc();const vw={class:"gb"},yw={class:"gb-top"},bw={key:0,class:"legend"},_w={class:"seg",role:"group","aria-label":"Chart or table"},kw=["aria-pressed"],ww=["aria-pressed"],xw=["width","height","aria-label"],$w={class:"grid"},Sw=["x1","x2","y1","y2"],Tw=["x","y"],Ew=["x","y"],Aw=["x","dy"],Rw=["d"],Cw=["x","y","width","height","aria-label","onPointerenter","onPointermove","onFocus"],Ow=["x1","x2","y1","y2"],Pw={key:0,class:"table-scroll"},Nw={class:"data"},Iw={key:0,class:"muted"},Mw={__name:"GroupedBars",props:{categories:{type:Array,required:!0},series:{type:Array,required:!0},height:{type:Number,default:280},valueName:{type:String,default:"Share of people"},describe:{type:String,default:""}},setup(e){const t=e,{el:n,width:s}=$c(480),l=J("chart"),r={l:46,r:12,t:14,b:52},o=K(()=>s.value-r.l-r.r),a=K(()=>t.height-r.t-r.b),u=K(()=>{const D=Math.max(.05,...t.series.flatMap(k=>k.values));return Math.min(1,Math.ceil(D*10)/10)}),d=K(()=>{const D=u.value>.5?.25:u.value>.2?.1:.05,k=[];for(let _=0;_<=u.value+1e-9;_+=D)k.push(Math.round(_*100)/100);return k}),c=K(()=>Math.max(u.value,d.value[d.value.length-1])),f=D=>r.t+(1-D/c.value)*a.value,p=K(()=>o.value/Math.max(1,t.categories.length)),g=K(()=>Math.min(24,Math.max(4,(p.value*.7-2*(t.series.length-1))/Math.max(1,t.series.length))));function N(D,k){const _=t.series.length*g.value+(t.series.length-1)*2;return r.l+D*p.value+(p.value-_)/2+k*(g.value+2)}function x(D,k){const _=f(0),w=f(k),E=_-w;if(E<=0)return"";const S=g.value,I=Math.min(4,E,S/2);return`M${D},${_}V${w+I}Q${D},${w} ${D+I},${w}H${D+S-I}Q${D+S},${w} ${D+S},${w+I}V${_}Z`}function R(D,k){const _=String(D).split(/\s+/),w=[""];for(const E of _){const S=w[w.length-1];if((S+" "+E).trim().length>k&&S){if(w.length===2){w[1]=(w[1]+" "+E).trim();continue}w.push(E)}else w[w.length-1]=(S+" "+E).trim()}return w.map(E=>E.length>k+4?E.slice(0,k+3)+"…":E)}const A=D=>`${Math.round(D*100)}%`,P=J(null),j=J({x:0,y:0});function O(D,k,_){P.value={ci:k,si:_},j.value={x:D.clientX,y:D.clientY}}const C=K(()=>{if(!P.value)return[];const D=t.series[P.value.si],k=D.counts?` (${D.counts[P.value.ci]} people)`:"";return[{key:D.id,value:A(D.values[P.value.ci])+k,label:D.label,color:nn(D.index),shape:"rect"}]});return(D,k)=>(h(),m("div",vw,[i("div",yw,[e.series.length>1?(h(),m("div",bw,[(h(!0),m(se,null,me(e.series,_=>(h(),m("span",{key:_.id},[i("span",{class:"swatch",style:We({background:de(nn)(_.index)})},null,4),xe(y(_.label),1)]))),128))])):q("",!0),k[4]||(k[4]=i("span",{class:"spacer"},null,-1)),i("div",_w,[i("button",{type:"button","aria-pressed":l.value==="chart",onClick:k[0]||(k[0]=_=>l.value="chart")},"Chart",8,kw),i("button",{type:"button","aria-pressed":l.value==="table",onClick:k[1]||(k[1]=_=>l.value="table")},"Table",8,ww)])]),Se(i("div",{ref_key:"el",ref:n,class:"chart-box"},[(h(),m("svg",{width:de(s),height:e.height,role:"img","aria-label":e.describe||e.valueName},[i("g",$w,[(h(!0),m(se,null,me(d.value,_=>(h(),m("g",{key:_},[i("line",{x1:r.l,x2:de(s)-r.r,y1:f(_),y2:f(_)},null,8,Sw),i("text",{x:r.l-8,y:f(_),dy:"0.32em","text-anchor":"end"},y(A(_)),9,Tw)]))),128)),(h(!0),m(se,null,me(e.categories,(_,w)=>(h(),m("text",{key:w,x:r.l+w*p.value+p.value/2,y:e.height-r.b+18,"text-anchor":"middle"},[(h(!0),m(se,null,me(R(_,Math.max(8,Math.floor(p.value/7))),(E,S)=>(h(),m("tspan",{key:S,x:r.l+w*p.value+p.value/2,dy:S?14:0},y(E),9,Aw))),128))],8,Ew))),128))]),(h(!0),m(se,null,me(e.series,(_,w)=>(h(),m("g",{key:_.id},[(h(!0),m(se,null,me(_.values,(E,S)=>(h(),m("g",{key:S},[i("path",{d:x(N(S,w),E),class:He(["bar",{lifted:P.value&&P.value.ci===S&&P.value.si===w}]),style:We({fill:de(nn)(_.index)})},null,14,Rw),i("rect",{x:N(S,w)-1,y:r.t,width:g.value+2,height:a.value,fill:"transparent",tabindex:"0","aria-label":`${_.label}, ${e.categories[S]}: ${A(E)}`,onPointerenter:I=>O(I,S,w),onPointermove:I=>O(I,S,w),onPointerleave:k[2]||(k[2]=I=>P.value=null),onFocus:I=>{P.value={ci:S,si:w},j.value={x:I.target.getBoundingClientRect().right,y:I.target.getBoundingClientRect().top+40}},onBlur:k[3]||(k[3]=I=>P.value=null)},null,40,Cw)]))),128))]))),128)),i("line",{class:"base",x1:r.l,x2:de(s)-r.r,y1:f(0),y2:f(0)},null,8,Ow)],8,xw))],512),[[Zu,l.value==="chart"]]),l.value==="table"?(h(),m("div",Pw,[i("table",Nw,[i("thead",null,[i("tr",null,[k[5]||(k[5]=i("th",null,null,-1)),(h(!0),m(se,null,me(e.series,_=>(h(),m("th",{key:_.id,class:"num"},y(_.label),1))),128))])]),i("tbody",null,[(h(!0),m(se,null,me(e.categories,(_,w)=>(h(),m("tr",{key:w},[i("td",null,y(_),1),(h(!0),m(se,null,me(e.series,E=>(h(),m("td",{key:E.id,class:"num"},[xe(y(A(E.values[w])),1),E.counts?(h(),m("span",Iw," ("+y(E.counts[w])+")",1)):q("",!0)]))),128))]))),128))])])])):q("",!0),De(Sc,{show:!!P.value&&l.value==="chart",x:j.value.x,y:j.value.y,title:P.value?e.categories[P.value.ci]:"",rows:C.value},null,8,["show","x","y","title","rows"])]))}},Lw=ct(Mw,[["__scopeId","data-v-5f0a10de"]]),Dw={class:"stack-lg"},Fw={key:0,class:"panel empty"},jw={key:0,class:"notice error",role:"alert"},Uw={class:"report-grid"},Vw={class:"panel stack","aria-labelledby":"rep-head"},Bw={class:"panel-head"},zw={key:0},qw=["disabled"],Hw={key:0,class:"notice error",role:"alert"},Gw=["innerHTML"],Ww={key:2,class:"empty"},Kw={key:0,class:"stack-lg data-col"},Yw={class:"panel stack","aria-labelledby":"stance-head"},Jw={class:"muted small"},Xw={class:"panel stack","aria-labelledby":"seg-head"},Zw={class:"row"},Qw=["value"],ex={class:"table-scroll"},tx={class:"data"},nx={class:"th-key"},sx={class:"seg-name"},lx={class:"num"},rx={key:0,class:"muted small"},ox={key:1,class:"panel stack","aria-labelledby":"pts-head"},ix={class:"table-scroll"},ax={class:"data"},ux={class:"pt-text"},cx={class:"break"},dx={class:"muted small"},fx=["title"],px={key:2,class:"panel stack-lg","aria-labelledby":"posts-head"},hx={class:"row"},mx=["value"],gx={class:"grid-side posts-grid"},vx={class:"stack"},yx={key:0,class:"muted"},bx={class:"small"},_x={class:"break content"},kx={class:"small muted tnum"},wx={key:0,class:"comments"},xx={class:"small"},$x={class:"muted"},Sx={class:"small break"},Tx={class:"stack"},Ex={class:"table-scroll"},Ax={class:"data"},Rx={class:"break"},Cx={class:"num"},Ox={class:"num"},Px={key:0},Nx={__name:"StepReport",setup(e){const t=cl(),n=t.pid,s=K(()=>t.selectedRun.value),l=K(()=>!!s.value&&ll.has(s.value.status)),r=J(null),o=J(null),a=J(""),u=J({});async function d(){if(a.value="",r.value=null,o.value=null,!l.value)return;const I=s.value.id;try{const V=await t.loadRun(I,!0);if(s.value?.id!==I)return;r.value=V,V.report_ready&&(o.value=await Ie.report(n.value,I))}catch(V){a.value=V.message}}Je(()=>s.value?.id+":"+s.value?.status,d,{immediate:!0});const c=K(()=>{const I=t.tasks.report;if(!I)return null;const V=u.value[I.id];return V&&V!==s.value?.id||!V&&!["queued","running"].includes(I.status)?null:I}),f=K(()=>!!t.tasks.report&&["queued","running"].includes(t.tasks.report.status)),p=J("");async function g(){p.value="";const I=s.value.id;try{const V=await Ie.startReport(n.value,I);u.value={...u.value,[V.id]:I},(await t.track(V)).status==="done"&&s.value?.id===I&&(o.value=await Ie.report(n.value,I),r.value=await t.loadRun(I,!0))}catch(V){p.value=V.message}}const N=K(()=>o.value?.markdown?gw.sanitize(Be.parse(o.value.markdown,{gfm:!0,breaks:!1}),{USE_PROFILES:{html:!0}}):""),x=K(()=>r.value?.summary||null),R=K(()=>(x.value?.variants||[]).map((I,V)=>({...I,index:V}))),A=K(()=>R.value.length>1),P=K(()=>x.value?{categories:x.value.stance_levels,series:R.value.filter(I=>I.final).map(I=>{const V=I.final.stance_hist||[],z=V.reduce((ge,le)=>ge+le,0)||1;return{id:I.id,label:I.label,index:I.index,values:V.map(ge=>ge/z),counts:V}})}:null),j=K(()=>{const I=new Set;for(const z of R.value)for(const ge of Object.keys(z.segments||{}))I.add(ge);const V=["kind","group"];return[...V.filter(z=>I.has(z)),...[...I].filter(z=>!V.includes(z)).sort()]}),O=J("group");Je(j,I=>{I.length&&!I.includes(O.value)&&(O.value=I[0])},{immediate:!0});const C={kind:"Kind",group:"Group"},D=K(()=>{const I=new Map;for(const z of R.value)for(const ge of z.segments?.[O.value]||[])I.has(ge.value)||I.set(ge.value,{value:ge.value,n:ge.n,by:{}}),I.get(ge.value).by[z.id]=ge.mean_outcome;const V=R.value[0]?.id;return[...I.values()].sort((z,ge)=>(ge.by[V]??0)-(z.by[V]??0))});function k(I){return O.value==="kind"&&{stakeholder:"Stakeholders",public:"Public"}[I]||I}const _=K(()=>{const I=new Map;for(const z of R.value)for(const ge of z.points||[])I.has(ge.id)||I.set(ge.id,{id:ge.id,text:ge.text,side:ge.side,by:{}}),I.get(ge.id).by[z.id]=ge;const V=R.value[0]?.id;return[...I.values()].sort((z,ge)=>(ge.by[V]?.total??0)-(z.by[V]?.total??0))}),w={pro:"For",con:"Against",neutral:"Neutral"},E=J("");Je(R,I=>{I.length&&!I.some(V=>V.id===E.value)&&(E.value=I[0].id)},{immediate:!0});const S=K(()=>R.value.find(I=>I.id===E.value)||null);return(I,V)=>(h(),m("div",Dw,[l.value?(h(),m(se,{key:1},[a.value?(h(),m("div",jw,y(a.value),1)):q("",!0),i("div",Uw,[i("section",Vw,[i("div",Bw,[V[3]||(V[3]=i("h2",{id:"rep-head"},"Report",-1)),o.value?(h(),m("p",zw,"Written "+y(de(ar)(o.value.created_at)),1)):q("",!0),V[4]||(V[4]=i("span",{class:"spacer"},null,-1)),i("button",{class:He(["btn",{primary:!o.value}]),type:"button",disabled:f.value,onClick:g},y(o.value?"Write again":"Generate report"),11,qw)]),p.value?(h(),m("div",Hw,y(p.value),1)):q("",!0),De(cr,{task:c.value,label:f.value?"Writing the report":"","hide-done":""},null,8,["task","label"]),N.value?(h(),m("article",{key:1,class:"prose",innerHTML:N.value},null,8,Gw)):f.value?q("",!0):(h(),m("div",Ww,[...V[5]||(V[5]=[i("h3",null,"No report yet",-1),i("p",null,"The language model writes it from the run's numbers and sample posts. It can only cite those numbers.",-1)])])),V[6]||(V[6]=i("p",{class:"caveat"},"Ranges cover chance only, not model error. The crowd is synthetic.",-1))]),x.value?(h(),m("div",Kw,[i("section",Yw,[V[7]||(V[7]=i("h3",{id:"stance-head"},"How people feel at the final poll",-1)),i("p",Jw,"Share of the crowd at each stance level"+y(A.value?", by variant":"")+".",1),P.value?.series.length?(h(),ln(Lw,{key:0,categories:P.value.categories,series:P.value.series,describe:"Share of people at each stance level at the final poll"},null,8,["categories","series"])):q("",!0)]),i("section",Xw,[i("div",Zw,[V[8]||(V[8]=i("h3",{id:"seg-head"},"Chance of yes by segment",-1)),V[9]||(V[9]=i("span",{class:"spacer"},null,-1)),Se(i("select",{"onUpdate:modelValue":V[0]||(V[0]=z=>O.value=z),class:"auto","aria-label":"Segment by"},[(h(!0),m(se,null,me(j.value,z=>(h(),m("option",{key:z,value:z},y(C[z]||z),9,Qw))),128))],512),[[_n,O.value]])]),i("div",ex,[i("table",tx,[i("thead",null,[i("tr",null,[i("th",null,y(C[O.value]||O.value),1),V[10]||(V[10]=i("th",{class:"num"},"People",-1)),(h(!0),m(se,null,me(R.value,z=>(h(),m("th",{key:z.id,class:"num wrap-th"},[i("span",nx,[A.value?(h(),m("span",{key:0,class:"swatch",style:We({background:de(nn)(z.index)})},null,4)):q("",!0),xe(y(A.value?z.label:"Mean chance of yes"),1)])]))),128))])]),i("tbody",null,[(h(!0),m(se,null,me(D.value,z=>(h(),m("tr",{key:z.value},[i("td",sx,y(k(z.value)),1),i("td",lx,y(z.n),1),(h(!0),m(se,null,me(R.value,ge=>(h(),m("td",{key:ge.id,class:"num"},y(de(Qt)(z.by[ge.id])),1))),128))]))),128))])])]),A.value?(h(),m("p",rx,"Columns are the mean chance of yes under each variant.")):q("",!0)])])):q("",!0)]),x.value?(h(),m("section",ox,[V[14]||(V[14]=i("h3",{id:"pts-head"},"Which talking points spread",-1)),i("div",ix,[i("table",ax,[i("thead",null,[i("tr",null,[V[11]||(V[11]=i("th",null,"Point",-1)),V[12]||(V[12]=i("th",null,"Side",-1)),(h(!0),m(se,null,me(R.value,z=>(h(),m("th",{key:z.id,class:"num wrap-th"},y(A.value?z.label:"Uses"),1))),128))])]),i("tbody",null,[(h(!0),m(se,null,me(_.value,z=>(h(),m("tr",{key:z.id},[i("td",ux,[i("span",cx,y(z.text),1),V[13]||(V[13]=xe()),i("span",dx,y(z.id),1)]),i("td",null,y(w[z.side]||z.side),1),(h(!0),m(se,null,me(R.value,ge=>(h(),m("td",{key:ge.id,class:"num",title:z.by[ge.id]?`${z.by[ge.id].posts} posts, ${z.by[ge.id].comments} comments, ${z.by[ge.id].quotes} quotes`:""},y(z.by[ge.id]?.total??0),9,fx))),128))]))),128))])])]),V[15]||(V[15]=i("p",{class:"muted small"},"Uses count posts, comments and quotes that make the point.",-1))])):q("",!0),S.value?(h(),m("section",px,[i("div",hx,[V[16]||(V[16]=i("h2",{id:"posts-head"},"Top posts and people",-1)),V[17]||(V[17]=i("span",{class:"spacer"},null,-1)),A.value?Se((h(),m("select",{key:0,"onUpdate:modelValue":V[1]||(V[1]=z=>E.value=z),class:"auto","aria-label":"Variant"},[(h(!0),m(se,null,me(R.value,z=>(h(),m("option",{key:z.id,value:z.id},y(z.label),9,mx))),128))],512)),[[_n,E.value]]):q("",!0)]),i("div",gx,[i("div",vx,[V[19]||(V[19]=i("h3",null,"Most engaging posts",-1)),S.value.top_posts.length?q("",!0):(h(),m("p",yx,"No posts in this variant.")),(h(!0),m(se,null,me(S.value.top_posts,z=>(h(),m("article",{key:z.post_id,class:"post"},[i("p",bx,[i("strong",null,y(z.author),1)]),i("p",_x,y(z.content),1),i("p",kx,y(z.likes)+" likes, "+y(z.dislikes)+" dislikes, "+y(z.shares)+" reshares, "+y(z.comments.length)+" comments",1),z.comments.length?(h(),m("ul",wx,[(h(!0),m(se,null,me(z.comments,(ge,le)=>(h(),m("li",{key:le},[i("p",xx,[i("strong",null,y(ge.author),1),V[18]||(V[18]=xe()),i("span",$x,y(ge.likes)+" likes",1)]),i("p",Sx,y(ge.content),1)]))),128))])):q("",!0)]))),128))]),i("div",Tx,[V[22]||(V[22]=i("h3",null,"Most engaged people",-1)),i("div",Ex,[i("table",Ax,[V[21]||(V[21]=i("thead",null,[i("tr",null,[i("th",null,"Person"),i("th",{class:"num"},"Posts"),i("th",{class:"num"},"Engagement")])],-1)),i("tbody",null,[(h(!0),m(se,null,me(S.value.most_engaged,z=>(h(),m("tr",{key:z.agent_id},[i("td",Rx,y(z.name),1),i("td",Cx,y(de(Xe)(z.posts)),1),i("td",Ox,y(de(Xe)(z.engagement)),1)]))),128)),S.value.most_engaged.length?q("",!0):(h(),m("tr",Px,[...V[20]||(V[20]=[i("td",{colspan:"3",class:"muted"},"Nobody engaged.",-1)])]))])])]),V[23]||(V[23]=i("p",{class:"muted small"},"Engagement counts the likes, reshares and comments a person's posts received.",-1))])])])):q("",!0)],64)):(h(),m("div",Fw,[...V[2]||(V[2]=[i("h3",null,"Pick a finished run",-1),i("p",null,"The selected run has not finished. Choose another one in the run menu above.",-1)])]))]))}},Ix=ct(Nx,[["__scopeId","data-v-dd71796f"]]),Mx={class:"stack-lg"},Lx={key:0,class:"panel empty"},Dx={key:0,class:"notice error",role:"alert"},Fx={class:"ask-grid"},jx={class:"panel stack chat-panel","aria-labelledby":"chat-head"},Ux={class:"picker-row"},Vx={class:"field grow"},Bx={key:0,class:"field"},zx=["value"],qx={class:"people",role:"listbox","aria-label":"People"},Hx=["aria-selected","onClick"],Gx={class:"p-name break"},Wx={class:"muted small"},Kx={key:0,class:"muted small pad"},Yx={key:0,class:"convo stack"},Jx={class:"persona"},Xx={class:"break"},Zx={class:"muted small"},Qx={class:"small muted break"},e$={key:0,class:"muted small"},t$={class:"break"},n$={key:1,class:"msg assistant typing"},s$=["disabled"],l$={key:0,class:"notice error",role:"alert"},r$={key:1,class:"muted small"},o$={class:"panel stack","aria-labelledby":"ask-head"},i$={class:"field"},a$={class:"row"},u$={key:0,class:"field"},c$=["value"],d$=["disabled"],f$={key:0,class:"notice error",role:"alert"},p$={key:1,class:"result stack","aria-live":"polite"},h$={class:"r-q break"},m$={class:"muted small"},g$={class:"big"},v$={class:"figure"},y$={class:"facts"},b$={class:"tnum"},_$={class:"tnum"},k$={key:0,class:"stack"},w$={class:"table-scroll"},x$={class:"data"},$$={class:"break"},S$={class:"num"},T$={class:"num"},E$={class:"num"},A$={class:"grid-2 names"},R$={class:"break"},C$={class:"muted tnum"},O$={class:"break"},P$={class:"muted tnum"},N$={class:"muted small tnum"},I$={key:2,class:"stack"},M$={class:"asks"},L$=["onClick"],D$={class:"break"},F$={class:"muted small tnum nowrap"},j$={__name:"StepAsk",setup(e){const t=cl(),n=t.pid,s=K(()=>t.selectedRun.value),l=K(()=>!!s.value&&ll.has(s.value.status)),r=J("");Promise.all([t.loadFrame(),t.loadCrowd()]).catch(F=>r.value=F.message);const o=K(()=>t.crowd.value?.agents||[]),a=K(()=>{const F=Object.fromEntries((t.frame.value?.variants||[]).map(W=>[W.id,W.label]));return(s.value?.variants?.length?s.value.variants:(t.frame.value?.variants||[]).map(W=>W.id)).map((W,oe)=>({id:W,label:F[W]||W,index:oe}))}),u=J(""),d=J(null),c=J(""),f=J([]),p=J(""),g=J(!1),N=J(""),x=J(null);Je(a,F=>{F.length&&!F.some($=>$.id===c.value)&&(c.value=F[0].id)},{immediate:!0});const R=K(()=>{const F=u.value.trim().toLowerCase();return(F?o.value.filter(W=>`${W.name} ${W.username} ${W.segment} ${W.kind}`.toLowerCase().includes(F)):o.value).slice(0,60)}),A=K(()=>o.value.find(F=>F.agent_id===d.value)||null);async function P(){if(N.value="",f.value=[],d.value==null||!l.value)return;const F=`${s.value.id}:${d.value}:${c.value}`;try{const $=await Ie.chatHistory(n.value,s.value.id,d.value,c.value);F===`${s.value?.id}:${d.value}:${c.value}`&&(f.value=$,j())}catch($){N.value=$.message}}Je(()=>[d.value,c.value,s.value?.id],P);async function j(){await er(),x.value&&(x.value.scrollTop=x.value.scrollHeight)}async function O(){const F=p.value.trim();if(!F||d.value==null)return;g.value=!0,N.value="";const $=[...f.value,{role:"user",content:F,at:new Date().toISOString(),pending:!0}];f.value=$,p.value="",j();try{const W=await Ie.chat(n.value,s.value.id,{agent_id:d.value,message:F,variant:c.value});f.value=W.history,j()}catch(W){N.value=W.message,f.value=$.filter(oe=>!oe.pending),p.value=F}finally{g.value=!1}}function C(F){F.key==="Enter"&&!F.shiftKey&&(F.preventDefault(),O())}const D=J(""),k=J(""),_=J(!1),w=J(""),E=J([]),S=J(null);Je(a,F=>{F.length&&!F.some($=>$.id===k.value)&&(k.value=F[0].id)},{immediate:!0});async function I(){if(E.value=[],S.value=null,!!l.value)try{const F=await Ie.asked(n.value,s.value.id);E.value=[...F].reverse(),S.value=E.value[0]||null}catch(F){w.value=F.message}}Je(()=>s.value?.id+":"+l.value,I,{immediate:!0});async function V(){const F=D.value.trim();if(F){_.value=!0,w.value="";try{const $=await Ie.ask(n.value,s.value.id,{question:F,variant:k.value||void 0});E.value=[$,...E.value],S.value=$,D.value=""}catch($){w.value=$.message}finally{_.value=!1}}}const z=K(()=>Object.fromEntries(a.value.map(F=>[F.id,F.index]))),ge=K(()=>Object.fromEntries(a.value.map(F=>[F.id,F.label]))),le=K(()=>{const F=S.value?.segments||{};return[...F.group||F[Object.keys(F)[0]]||[]].sort((W,oe)=>oe.mean_outcome-W.mean_outcome)});return(F,$)=>(h(),m("div",Mx,[l.value?(h(),m(se,{key:1},[r.value?(h(),m("div",Dx,y(r.value),1)):q("",!0),i("div",Fx,[i("section",jx,[$[11]||($[11]=i("div",{class:"panel-head"},[i("h2",{id:"chat-head"},"Talk to one person"),i("p",null,"They answer in character, from their persona and what they saw in the run.")],-1)),i("div",Ux,[i("label",Vx,[$[6]||($[6]=i("span",{class:"label"},"Find a person",-1)),Se(i("input",{"onUpdate:modelValue":$[0]||($[0]=W=>u.value=W),type:"search",placeholder:"Name or group",autocomplete:"off"},null,512),[[Le,u.value]])]),a.value.length>1?(h(),m("label",Bx,[$[7]||($[7]=i("span",{class:"label"},"Variant",-1)),Se(i("select",{"onUpdate:modelValue":$[1]||($[1]=W=>c.value=W)},[(h(!0),m(se,null,me(a.value,W=>(h(),m("option",{key:W.id,value:W.id},y(W.label),9,zx))),128))],512),[[_n,c.value]])])):q("",!0)]),i("ul",qx,[(h(!0),m(se,null,me(R.value,W=>(h(),m("li",{key:W.agent_id},[i("button",{type:"button",role:"option","aria-selected":W.agent_id===d.value,class:He({on:W.agent_id===d.value}),onClick:oe=>d.value=W.agent_id},[i("span",Gx,y(W.name),1),i("span",Wx,y(W.kind==="stakeholder"?"Stakeholder":W.segment),1)],10,Hx)]))),128)),R.value.length?q("",!0):(h(),m("li",Kx,"Nobody matches."))]),A.value?(h(),m("div",Yx,[i("div",Jx,[i("p",null,[i("strong",Xx,y(A.value.name),1),$[8]||($[8]=xe()),i("span",Zx,y(A.value.segment),1)]),i("p",Qx,y(A.value.bio),1)]),i("div",{ref_key:"thread",ref:x,class:"thread","aria-live":"polite"},[f.value.length?q("",!0):(h(),m("p",e$,"No messages yet. Ask what they think and why.")),(h(!0),m(se,null,me(f.value,(W,oe)=>(h(),m("div",{key:oe,class:He(["msg",[W.role,{pending:W.pending}]])},[i("p",t$,y(W.content),1)],2))),128)),g.value?(h(),m("div",n$,[...$[9]||($[9]=[i("p",{class:"muted"},"Writing a reply",-1)])])):q("",!0)],512),i("form",{class:"composer",onSubmit:kn(O,["prevent"])},[$[10]||($[10]=i("label",{class:"sr-only",for:"chat-input"},"Message",-1)),Se(i("textarea",{id:"chat-input","onUpdate:modelValue":$[2]||($[2]=W=>p.value=W),rows:"2",placeholder:"Would you pay more for weekly cleaning?",onKeydown:C},null,544),[[Le,p.value]]),i("button",{class:"btn primary",type:"submit",disabled:g.value||!p.value.trim()},"Send",8,s$)],32),N.value?(h(),m("div",l$,y(N.value),1)):q("",!0)])):(h(),m("p",r$,"Pick someone from the list to start."))]),i("section",o$,[$[25]||($[25]=i("div",{class:"panel-head"},[i("h2",{id:"ask-head"},"Ask the whole crowd"),i("p",null,"Jev polls every person with a new yes or no question. It takes a few seconds.")],-1)),i("form",{class:"stack",onSubmit:kn(V,["prevent"])},[i("label",i$,[$[12]||($[12]=i("span",{class:"label"},"Question",-1)),Se(i("textarea",{"onUpdate:modelValue":$[3]||($[3]=W=>D.value=W),rows:"2",placeholder:"Would you recommend Lazybee to a friend?"},null,512),[[Le,D.value]])]),i("div",a$,[a.value.length>1?(h(),m("label",u$,[$[13]||($[13]=i("span",{class:"label"},"Variant",-1)),Se(i("select",{"onUpdate:modelValue":$[4]||($[4]=W=>k.value=W)},[(h(!0),m(se,null,me(a.value,W=>(h(),m("option",{key:W.id,value:W.id},y(W.label),9,c$))),128))],512),[[_n,k.value]])])):q("",!0),$[14]||($[14]=i("span",{class:"spacer"},null,-1)),i("button",{class:"btn primary ask-btn",type:"submit",disabled:_.value||!D.value.trim()},y(_.value?`Polling ${o.value.length} people`:"Ask the crowd"),9,d$)])],32),w.value?(h(),m("div",f$,y(w.value),1)):q("",!0),S.value?(h(),m("article",p$,[i("p",h$,y(S.value.question),1),i("p",m$,y(ge.value[S.value.variant]||S.value.variant)+", asked "+y(de(ar)(S.value.at)),1),i("p",g$,[i("span",v$,y(de(Cn)(S.value.summary.expected_yes)),1),i("span",null,"of "+y(S.value.summary.n)+" expected to say yes",1)]),i("dl",y$,[i("div",null,[$[15]||($[15]=i("dt",null,"90% range",-1)),i("dd",b$,y(de(Cn)(S.value.summary.low))+" to "+y(de(Cn)(S.value.summary.high)),1)]),i("div",null,[$[16]||($[16]=i("dt",null,"Mean chance of yes",-1)),i("dd",_$,y(de(Qt)(S.value.summary.mean_outcome,1)),1)])]),De(Tc,{n:S.value.summary.n,expected:S.value.summary.expected_yes,low:S.value.summary.low,high:S.value.summary.high,index:z.value[S.value.variant]??0,label:S.value.question},null,8,["n","expected","low","high","index","label"]),$[23]||($[23]=i("p",{class:"caveat"},"Ranges cover chance only, not model error. The crowd is synthetic.",-1)),le.value.length?(h(),m("div",k$,[$[18]||($[18]=i("h3",null,"By group",-1)),i("div",w$,[i("table",x$,[$[17]||($[17]=i("thead",null,[i("tr",null,[i("th",null,"Group"),i("th",{class:"num"},"People"),i("th",{class:"num"},"Chance of yes"),i("th",{class:"num"},"Expected yes")])],-1)),i("tbody",null,[(h(!0),m(se,null,me(le.value,W=>(h(),m("tr",{key:W.value},[i("td",$$,y(W.value),1),i("td",S$,y(W.n),1),i("td",T$,y(de(Qt)(W.mean_outcome)),1),i("td",E$,y(de(Cn)(W.expected_yes)),1)]))),128))])])])])):q("",!0),i("div",A$,[i("div",null,[$[20]||($[20]=i("h3",null,"Most likely yes",-1)),i("ol",null,[(h(!0),m(se,null,me(S.value.most_yes,W=>(h(),m("li",{key:W.name},[i("span",R$,y(W.name),1),$[19]||($[19]=xe()),i("span",C$,y(de(Qt)(W.p)),1)]))),128))])]),i("div",null,[$[22]||($[22]=i("h3",null,"Most likely no",-1)),i("ol",null,[(h(!0),m(se,null,me(S.value.most_no,W=>(h(),m("li",{key:W.name},[i("span",O$,y(W.name),1),$[21]||($[21]=xe()),i("span",P$,y(de(Qt)(W.p)),1)]))),128))])])]),i("p",N$,y(S.value.requests)+" Jev requests, "+y(S.value.cache_hits)+" from cache",1)])):q("",!0),E.value.length?(h(),m("div",I$,[$[24]||($[24]=i("h3",null,"Earlier questions",-1)),i("ul",M$,[(h(!0),m(se,null,me(E.value,(W,oe)=>(h(),m("li",{key:oe},[i("button",{type:"button",class:He({on:W===S.value}),onClick:te=>S.value=W},[i("span",D$,y(W.question),1),i("span",F$,y(de(Cn)(W.summary.expected_yes))+" of "+y(W.summary.n)+", "+y(de(Qt)(W.summary.mean_outcome)),1)],10,L$)]))),128))])])):q("",!0)])])],64)):(h(),m("div",Lx,[...$[5]||($[5]=[i("h3",null,"Pick a finished run",-1),i("p",null,"People remember what happened in a run, so choose a finished one in the run menu above.",-1)])]))]))}},U$=ct(j$,[["__scopeId","data-v-69a3ca99"]]),V$={key:0,class:"panel empty"},B$={key:1,class:"stack-lg setup"},z$={class:"intro"},q$={key:0,class:"notice error",role:"alert"},H$={class:"panel stack","aria-labelledby":"jev-head"},G$={class:"field"},W$=["placeholder"],K$={class:"hint"},Y$={class:"panel stack","aria-labelledby":"llm-head"},J$={class:"panel-head"},X$={class:"seg",role:"group","aria-label":"Model provider"},Z$=["aria-pressed"],Q$=["aria-pressed"],eS={key:0,class:"muted small"},tS={key:1,class:"muted small"},nS={key:2,class:"form-grid wide"},sS={class:"field"},lS={class:"field"},rS={class:"field"},oS={class:"label"},iS=["placeholder"],aS={class:"hint"},uS={key:0,class:"notice error",role:"alert"},cS={class:"row"},dS=["disabled"],fS={key:2,class:"panel stack","aria-labelledby":"test-head"},pS={class:"row"},hS=["disabled"],mS={key:3,class:"panel stack","aria-labelledby":"stop-head"},gS={class:"caveat break"},vS={__name:"SetupView",setup(e){const t=J(null),n=J(""),s=J(""),l=J("gemini"),r=J(""),o=J(""),a=J(""),u=J(""),d=J(""),c=J(null),f=J(!1);async function p(){try{const C=await Ie.settings();t.value=C,l.value=C.llm_provider,o.value=C.llm_base_url,a.value=C.llm_model}catch(C){n.value=C.message}}al(p);const g=K(()=>t.value&&t.value.setup_needed&&!t.value.test_mode),N=K(()=>t.value?l.value==="gemini"?t.value.gemini_key:t.value.llm_key:null),x=K(()=>!sl.value||sl.value.setup_needed?!1:!c.value||c.value.jev.ok&&c.value.llm.ok);function R(C){return C==null?"":C?`A key ending in ${C} is saved. Leave this blank to keep it.`:"A key is saved. Leave this blank to keep it."}function A(){const C={typesafe_key:s.value,llm_provider:l.value,llm_key:r.value};return l.value==="openai"&&Object.assign(C,{llm_base_url:o.value,llm_model:a.value}),C}async function P(){if(d.value="",c.value=null,!s.value.trim()&&!(t.value&&t.value.typesafe_key!==null)){d.value="Paste your Jev key first.";return}u.value="save";try{t.value=await Ie.saveSettings(A()),s.value="",r.value="",await ao(),u.value="check",c.value=await Ie.checkKeys({llm_provider:l.value})}catch(C){d.value=C.message}finally{u.value=""}}async function j(C){d.value="",u.value="test";try{c.value=null,t.value=await Ie.saveSettings({test_mode:C}),await ao()}catch(D){d.value=D.message}finally{u.value=""}}async function O(){const C=t.value?t.value.active_tasks:0,D=C?` ${C} running ${C===1?"job":"jobs"} will stop too.`:"";if(window.confirm(`Stop JevFish on this computer?${D}`))try{await Ie.shutdown(),f.value=!0}catch(k){d.value=k.message}}return(C,D)=>{const k=Nn("RouterLink");return f.value?(h(),m("div",V$,[...D[7]||(D[7]=[i("h3",null,"JevFish has stopped",-1),i("p",null,"You can close this tab. Open JevFish.app to start it again.",-1)])])):(h(),m("div",B$,[i("section",z$,[i("h1",null,y(g.value?"Set up JevFish":"Settings"),1),D[8]||(D[8]=i("p",{class:"muted"}," JevFish needs two keys. Jev decides what each simulated person does, and a language model writes the graph, the crowd and the posts. Keys stay in a file on this computer. ",-1))]),n.value?(h(),m("div",q$,y(n.value),1)):q("",!0),t.value?(h(),m("form",{key:1,class:"stack-lg",onSubmit:kn(P,["prevent"])},[i("section",H$,[D[10]||(D[10]=i("div",{class:"panel-head"},[i("h2",{id:"jev-head"},"Jev"),i("p",null,[xe("Get a key at "),i("a",{href:"https://console.typesafe.ai",target:"_blank",rel:"noopener"},"console.typesafe.ai"),xe(". A typical run costs about US$0.04.")])],-1)),i("label",G$,[D[9]||(D[9]=i("span",{class:"label"},"TypeSafe API key",-1)),Se(i("input",{"onUpdate:modelValue":D[0]||(D[0]=_=>s.value=_),type:"password",autocomplete:"off",spellcheck:"false",placeholder:t.value.typesafe_key!==null?"Saved":"Paste the key"},null,8,W$),[[Le,s.value]]),i("span",K$,y(R(t.value.typesafe_key)),1)]),c.value?(h(),m("div",{key:0,class:He(["notice",c.value.jev.ok?"ok":"error"]),role:"status"},y(c.value.jev.message),3)):q("",!0)]),i("section",Y$,[i("div",J$,[D[11]||(D[11]=i("h2",{id:"llm-head"},"Language model",-1)),D[12]||(D[12]=i("span",{class:"spacer"},null,-1)),i("div",X$,[i("button",{type:"button","aria-pressed":l.value==="gemini",onClick:D[1]||(D[1]=_=>l.value="gemini")},"Gemini",8,Z$),i("button",{type:"button","aria-pressed":l.value==="openai",onClick:D[2]||(D[2]=_=>l.value="openai")},"Other",8,Q$)])]),l.value==="gemini"?(h(),m("p",eS,[...D[13]||(D[13]=[xe(" Free key at ",-1),i("a",{href:"https://aistudio.google.com/apikey",target:"_blank",rel:"noopener"},"aistudio.google.com/apikey",-1),xe(". The free tier is enough for normal runs. ",-1)])])):(h(),m("p",tS,"Any service that speaks the OpenAI API: OpenAI, OpenRouter, Groq, or a local model.")),l.value==="openai"?(h(),m("div",nS,[i("label",sS,[D[14]||(D[14]=i("span",{class:"label"},"Address",-1)),Se(i("input",{"onUpdate:modelValue":D[3]||(D[3]=_=>o.value=_),type:"url",spellcheck:"false",placeholder:"https://api.openai.com/v1"},null,512),[[Le,o.value]])]),i("label",lS,[D[15]||(D[15]=i("span",{class:"label"},"Model",-1)),Se(i("input",{"onUpdate:modelValue":D[4]||(D[4]=_=>a.value=_),type:"text",spellcheck:"false",placeholder:"gpt-4o-mini"},null,512),[[Le,a.value]])])])):q("",!0),i("label",rS,[i("span",oS,y(l.value==="gemini"?"Gemini API key":"API key"),1),Se(i("input",{"onUpdate:modelValue":D[5]||(D[5]=_=>r.value=_),type:"password",autocomplete:"off",spellcheck:"false",placeholder:N.value!==null?"Saved":"Paste the key"},null,8,iS),[[Le,r.value]]),i("span",aS,y(R(N.value)),1)]),c.value?(h(),m("div",{key:3,class:He(["notice",c.value.llm.ok?"ok":"error"]),role:"status"},y(c.value.llm.message),3)):q("",!0)]),d.value?(h(),m("div",uS,y(d.value),1)):q("",!0),i("div",cS,[i("button",{class:"btn primary",type:"submit",disabled:!!u.value},y(u.value==="save"?"Saving":u.value==="check"?"Checking keys":"Save and check"),9,dS),x.value?(h(),ln(k,{key:0,to:"/",class:"btn"},{default:Vt(()=>[...D[16]||(D[16]=[xe("Start a prediction",-1)])]),_:1})):q("",!0)])],32)):q("",!0),t.value?(h(),m("section",fS,[D[17]||(D[17]=i("div",{class:"panel-head"},[i("h2",{id:"test-head"},"Test mode"),i("p",null,"Try every screen without keys. Every number it shows is made up.")],-1)),i("div",pS,[i("span",{class:He(["pill",t.value.test_mode?"warn":""])},y(t.value.test_mode?"On":"Off"),3),i("button",{class:"btn small",type:"button",disabled:!!u.value,onClick:D[6]||(D[6]=_=>j(!t.value.test_mode))},y(t.value.test_mode?"Turn off test mode":"Turn on test mode"),9,hS)])])):q("",!0),t.value?(h(),m("section",mS,[D[18]||(D[18]=i("div",{class:"panel-head"},[i("h2",{id:"stop-head"},"Stop JevFish"),i("p",null,"Shuts JevFish down on this computer. Open JevFish.app to start it again.")],-1)),i("div",{class:"row"},[i("button",{class:"btn small danger",type:"button",onClick:O},"Stop JevFish")]),i("p",gS,"Keys are saved in "+y(t.value.env_file),1)])):q("",!0)]))}}},yS=ct(vS,[["__scopeId","data-v-fc354223"]]),Bc=Nh({history:dh("/"),routes:[{path:"/",name:"projects",component:Tm},{path:"/p/:pid",component:Ym,props:!0,children:[{path:"",redirect:e=>({name:"graph",params:e.params,query:e.query})},{path:"graph",name:"graph",component:by},{path:"crowd",name:"crowd",component:r_},{path:"simulate",name:"simulate",component:Zk},{path:"report",name:"report",component:Ix},{path:"ask",name:"ask",component:U$}]},{path:"/setup",name:"setup",component:yS},{path:"/:rest(.*)*",redirect:"/"}],scrollBehavior:()=>({top:0})});let Ba=!0;Bc.beforeEach(async e=>{if(!Ba)return!0;Ba=!1;const t=await ao();return t&&t.setup_needed&&e.name!=="setup"?{name:"setup"}:!0});Sp(Gh).use(Bc).mount("#app");
diff --git a/jevfish/web/dist/index.html b/jevfish/web/dist/index.html
new file mode 100644
index 0000000000..dc011a10b0
--- /dev/null
+++ b/jevfish/web/dist/index.html
@@ -0,0 +1,18 @@
+
+
+
+
+
+
+ JevFish
+
+
+
+
+
+
+
+
+
diff --git a/jevfish/web/src/App.vue b/jevfish/web/src/App.vue
index c74048c4c6..ca3a45e40e 100644
--- a/jevfish/web/src/App.vue
+++ b/jevfish/web/src/App.vue
@@ -1,9 +1,10 @@
@@ -62,6 +55,7 @@ const warnings = computed(() => {
Swarm predictions, one Jev decision per person
+ Settings