diff --git a/bench/computer-use/run.py b/bench/computer-use/run.py index f76a266..a3d1e4f 100644 --- a/bench/computer-use/run.py +++ b/bench/computer-use/run.py @@ -13,6 +13,112 @@ own (cloudbox.rs own_volume), and a data folder that is a copy, not the real one --out results.json [--tasks T1,T4] [--runs 1] """ import argparse, json, os, re, shutil, subprocess, sys, time +import http.client, http.server, threading, urllib.parse + + +class Meter: + """A pass-through to the model service that counts what each task cost: requests, tokens in + and out (cached and reasoning too), pictures sent, request bytes. AnyBot keeps no usage of its + own for OpenAI-style services, so the bot's provider points here (--meter); streamed requests + are asked to report their usage (stream_options.include_usage).""" + + def __init__(self, upstream): + u = urllib.parse.urlparse(upstream) + self.scheme, self.host, self.base = u.scheme, u.netloc, u.path.rstrip("/") + self.lock = threading.Lock() + self.reset() + + def reset(self, dump=""): + with self.lock: + self.stats = {"requests": 0, "tokens_in": 0, "tokens_out": 0, "cached_in": 0, "reasoning": 0, "images": 0, "req_bytes": 0} + # The task's first request is kept here (what a call is made of: instructions, tools, chat). + self.dump = dump + + def take(self): + with self.lock: + return dict(self.stats) + + def add(self, **kw): + with self.lock: + for k, v in kw.items(): + self.stats[k] = self.stats.get(k, 0) + (v or 0) + + def usage(self, u): + if not isinstance(u, dict): + return + self.add(tokens_in=u.get("prompt_tokens") or u.get("input_tokens"), tokens_out=u.get("completion_tokens") or u.get("output_tokens"), + cached_in=(u.get("prompt_tokens_details") or {}).get("cached_tokens"), reasoning=(u.get("completion_tokens_details") or {}).get("reasoning_tokens")) + + def start(self): + meter = self + + class H(http.server.BaseHTTPRequestHandler): + def log_message(self, *a): + pass + + def forward(self, method): + body = self.rfile.read(int(self.headers.get("Content-Length") or 0)) if method == "POST" else b"" + if body: + try: + j = json.loads(body) + if j.get("stream"): + j.setdefault("stream_options", {})["include_usage"] = True + pics = sum(1 for m in j.get("messages") or [] for c in (m.get("content") if isinstance(m.get("content"), list) else []) if isinstance(c, dict) and c.get("type") in ("image_url", "input_image", "image")) + body = json.dumps(j).encode() + meter.add(requests=1, images=pics, req_bytes=len(body)) + with meter.lock: + dump, meter.dump = meter.dump, "" + if dump: + open(dump, "wb").write(body) + except ValueError: + pass + path = meter.base + self.path[len("/v1"):] if self.path.startswith("/v1") else self.path + conn = (http.client.HTTPSConnection if meter.scheme == "https" else http.client.HTTPConnection)(meter.host, timeout=900) + headers = {k: v for k, v in self.headers.items() if k.lower() not in ("host", "content-length", "accept-encoding", "connection")} + headers["Accept-Encoding"] = "identity" + conn.request(method, path, body=body or None, headers=headers) + r = conn.getresponse() + self.send_response(r.status) + for k, v in r.getheaders(): + if k.lower() not in ("transfer-encoding", "content-length", "connection", "content-encoding"): + self.send_header(k, v) + self.send_header("Connection", "close") + self.end_headers() + buf, whole = b"", b"" + while True: + chunk = r.read1(65536) if hasattr(r, "read1") else r.read(65536) + if not chunk: + break + try: + self.wfile.write(chunk) + self.wfile.flush() + except OSError: + break + buf += chunk + whole += chunk if len(whole) < 4_000_000 else b"" + while b"\n" in buf: + line, buf = buf.split(b"\n", 1) + if line.startswith(b"data:") and b'"usage"' in line: + try: + meter.usage(json.loads(line[5:].strip()).get("usage")) + except ValueError: + pass + if not whole.lstrip().startswith(b"data:") and b'"usage"' in whole: + try: + meter.usage(json.loads(whole).get("usage")) + except ValueError: + pass + conn.close() + + def do_POST(self): + self.forward("POST") + + def do_GET(self): + self.forward("GET") + + srv = http.server.ThreadingHTTPServer(("127.0.0.1", 0), H) + threading.Thread(target=srv.serve_forever, daemon=True).start() + return srv.server_address[1] BOX = os.environ.get("ANYBOT_BOX_NAME", "") VOL = os.environ.get("ANYBOT_BOX_VOLUME", "") @@ -81,14 +187,17 @@ TASKS = [ "check": lambda dh, ans: "7006652" in digits(ans) and dx("pgrep -x galculator", dh)[0] == 0}, {"id": "T3", "route": "screen-or-browser", "name": "Chromium 預設搜尋引擎", # Back to Chromium's own default (an earlier run may have set Bing): browser closed, the - # saved choice removed from its preferences. - "setup": "pkill -f '^/usr/lib/chromium/chromium' ; sleep 2; python3 - <<'PY'\n" - "import json\nfor p in ['/home/bot/.config/anybot-profile/Default/Preferences', '/home/bot/.config/chromium/Default/Preferences']:\n" + # saved choice removed from its preferences, and no policy file forcing one (a bot once + # wrote /etc/chromium/policies/managed/default_search.json instead: it outlives the task). + "setup": "pkill -f '^/usr/lib/chromium/chromium' ; rm -rf /etc/chromium/policies/managed /etc/chromium/policies/recommended; sleep 2; python3 - <<'PY'\n" + "import json, glob\nfor p in ['/home/bot/.config/anybot-profile/Default/Preferences', '/home/bot/.config/chromium/Default/Preferences'] + glob.glob('/home/bot/.config/anybot-profiles/*/Default/Preferences'):\n" " try:\n d = json.load(open(p))\n except Exception:\n continue\n" " d.pop('default_search_provider_data', None); d.pop('default_search_provider', None)\n json.dump(d, open(p, 'w'))\n print('reset', p)\nPY", "ask": "把你電腦上 Chromium 瀏覽器的預設搜尋引擎改成 Bing。", - # Chromium writes its preferences up to ~10 s after a change: look for 15 s. - "check": lambda dh, ans: "bing" in dx("for i in $(seq 15); do python3 - <<'PY' && break\nimport json, sys\np='/home/bot/.config/anybot-profile/Default/Preferences'\ntry:\n t=json.dumps(json.load(open(p)).get('default_search_provider_data',{})).lower()\nexcept Exception as e: t=str(e)\nprint(t)\nsys.exit(0 if 'bing' in t else 1)\nPY\nsleep 1; done", dh)[1]}, + # Chromium writes its preferences up to ~10 s after a change: look for 15 s. The desktop's + # own Chromium (~/.config/chromium) counts too: on a box from version 10 on, AnyBot's profile + # is a folder of its own, no longer a link to it (a bot that set Bing there was marked wrong). + "check": lambda dh, ans: "bing" in dx("for i in $(seq 15); do python3 - <<'PY' && break\nimport json, sys, glob\nt=''\nfor p in ['/home/bot/.config/anybot-profile/Default/Preferences', '/home/bot/.config/chromium/Default/Preferences'] + glob.glob('/home/bot/.config/anybot-profiles/*/Default/Preferences'):\n try:\n t+=json.dumps(json.load(open(p)).get('default_search_provider_data',{})).lower()\n except Exception as e: t+=str(e)\nprint(t)\nsys.exit(0 if 'bing' in t else 1)\nPY\nsleep 1; done", dh)[1]}, {"id": "T4", "route": "command", "name": "照片依月份分類", "setup": "rm -rf ~/bench/photos && mkdir -p ~/bench/photos && cd ~/bench/photos && " "for m in 2026-08 2026-09 2026-10; do for i in 1 2 3 4; do f=IMG_${m}_$i.jpg; echo x > $f; touch -d ${m}-1${i}T10:00:00 $f; done; done; " @@ -295,7 +404,11 @@ def main(): ap.add_argument("--runs", type=int, default=1) ap.add_argument("--secs", type=int, default=600) ap.add_argument("--keep-skills", action="store_true", help="carry skills learned in one run into the next (to measure replay)") + ap.add_argument("--meter", default="", help="the bot's model service (e.g. https://api.x.ai/v1): count each task's tokens through a local pass-through") + ap.add_argument("--label", default="", help="a name for this variant in the results (e.g. baseline, text-looks)") a = ap.parse_args() + meter = Meter(a.meter) if a.meter else None + meter_port = meter.start() if meter else 0 if not BOX or not VOL or BOX == "anybot-box" or VOL == "anybot-box-home": sys.exit("set ANYBOT_BOX_NAME and ANYBOT_BOX_VOLUME to a throwaway box of its own") real = os.path.realpath(os.path.expanduser("~/Library/Application Support/AnyBot")) @@ -306,6 +419,22 @@ def main(): results = json.load(open(a.out)) if os.path.exists(a.out) else [] env = dict(os.environ, ANYBOT_DATA_DIR=a.data, ANYBOT_ASK_SECS=str(a.secs)) kept_skills = [] + # What a bot learns in one task must not reach the next (the skills and memories live in the + # data folder, outside state.json): each task starts from none — except the skills of this + # round under --keep-skills, which measures exactly that. + def forget(skills: bool) -> None: + for name in ["chats", "oplog"] + (["skills"] if skills else []): + shutil.rmtree(os.path.join(a.data, name), ignore_errors=True) + for name in os.listdir(a.data): + if name.startswith("memory.db"): + os.remove(os.path.join(a.data, name)) + forget(skills=True) + # A box of its own that doesn't exist yet: one plain question first makes it (the first task's + # setup needs it running). + if subprocess.run(["docker", "inspect", BOX], capture_output=True, env=dict(os.environ, DOCKER_HOST=a.docker_host)).returncode != 0: + print("== making the bench box", flush=True) + shutil.copyfile(a.template, os.path.join(a.data, "state.json")) + subprocess.run([a.bin, "--ask", "在你自己的電腦上執行 true,然後回答好了"], capture_output=True, text=True, env=env, timeout=1800) for run in range(a.runs): for t in tasks: print(f"== {t['id']} {t['name']} (run {run + 1})", flush=True) @@ -313,10 +442,21 @@ def main(): # makes in the bot's home is handed back to the bot. # Every task starts on a clear desktop: apps a previous task left open are closed. dx("for a in galculator xterm mousepad lxappearance pcmanfm; do pkill -x $a; done; pkill -f '^/usr/lib/chromium/chromium'; sleep 1; true", a.docker_host, user="root") - rc, out = dx(t["setup"].replace("sudo ", "") + "; chown -R bot:bot /home/bot/bench 2>/dev/null; true", a.docker_host, check=False, timeout=900, user="root") + rc, out = dx(t["setup"].replace("sudo ", "") + "\nchown -R bot:bot /home/bot/bench 2>/dev/null; true", a.docker_host, check=False, timeout=900, user="root") print(" setup:", out.strip().replace("\n", " ")[-160:], flush=True) shutil.copyfile(a.template, os.path.join(a.data, "state.json")) os.chmod(os.path.join(a.data, "state.json"), 0o600) + # Each chat is a file of its own (data/chats/bot-.json): a clean start each task, + # with no memories, work log or (unless kept) skills from the tasks before. + forget(skills=not a.keep_skills) + if meter: + # The bot's provider goes through the meter (this task's count starts at zero). + st0 = json.load(open(os.path.join(a.data, "state.json"))) + kind = str(st0["bots"][0].get("provider", "")).lower() + provs = st0.setdefault("providers", {}) + provs.setdefault(kind, {})["base_url"] = f"http://127.0.0.1:{meter_port}/v1" + json.dump(st0, open(os.path.join(a.data, "state.json"), "w"), ensure_ascii=False) + meter.reset(dump=os.path.join(os.path.dirname(os.path.abspath(a.out)), f"request-{a.label or 'run'}-{t['id']}.json")) if a.keep_skills and kept_skills: st0 = json.load(open(os.path.join(a.data, "state.json"))) st0["skills"] = kept_skills @@ -331,7 +471,9 @@ def main(): st = json.load(open(os.path.join(a.data, "state.json"))) if a.keep_skills: kept_skills = st.get("skills", []) - msgs = st["bots"][0]["messages"] + bot_id = st["bots"][0]["id"] + chat = os.path.join(a.data, "chats", f"bot-{bot_id}.json") + msgs = json.load(open(chat)).get("messages", []) if os.path.exists(chat) else st["bots"][0].get("messages", []) r = analyze(msgs) try: ok = bool(t["check"](a.docker_host, r.get("answer", ""))) @@ -340,12 +482,15 @@ def main(): r["check_error"] = str(e) r["skills"] = [{"name": k.get("name"), "steps": len(k.get("steps", []))} for k in st.get("skills", [])] r["replayed"] = "replay_skill" in r.get("tools", []) - r.update({"id": t["id"], "name": t["name"], "expected_route": t["route"], "ok": ok, "run": run + 1, + if meter: + r["usage"] = meter.take() + r.update({"id": t["id"], "name": t["name"], "expected_route": t["route"], "ok": ok, "run": run + 1, "label": a.label, "process_s": wall, "at": time.strftime("%Y-%m-%d %H:%M"), "log_tail": log[-1500:]}) results.append(r) json.dump(results, open(a.out, "w"), ensure_ascii=False, indent=1) + u = r.get("usage") or {} print(f" ok={ok} steps={r.get('steps')} total={r.get('total_s')}s model={r.get('model_s')}s tool={r.get('tool_s')}s " - f"routes={r.get('by_route')} switches={r.get('switches')}", flush=True) + f"routes={r.get('by_route')} switches={r.get('switches')} tokens_in={u.get('tokens_in')} out={u.get('tokens_out')} pics={u.get('images')}", flush=True) if __name__ == "__main__": diff --git a/box/Dockerfile b/box/Dockerfile index 3ba7703..ed78ed3 100644 --- a/box/Dockerfile +++ b/box/Dockerfile @@ -18,11 +18,12 @@ RUN apt-get update && apt-get install -y --no-install-recommends \ COPY start.sh /usr/local/bin/anybot-box-start COPY a11y /usr/local/bin/anybot-a11y COPY browser /usr/local/bin/anybot-browser +COPY screen /usr/local/bin/anybot-screen COPY fluxbox-init /etc/anybot/fluxbox-init COPY overlay /etc/anybot/overlay COPY Xresources /etc/anybot/Xresources COPY menu /etc/anybot/menu -RUN chmod +x /usr/local/bin/anybot-box-start /usr/local/bin/anybot-a11y /usr/local/bin/anybot-browser \ +RUN chmod +x /usr/local/bin/anybot-box-start /usr/local/bin/anybot-a11y /usr/local/bin/anybot-browser /usr/local/bin/anybot-screen \ # Chromium has no sandbox inside a plain container (no user namespaces); the box itself is # the sandbox. Under gVisor (容器隔離=runsc) the box has its own virtualized kernel and # Chromium's sandbox works: AnyBot then starts the box with ANYBOT_BOX_SANDBOX=1 and the @@ -39,6 +40,6 @@ RUN chmod +x /usr/local/bin/anybot-box-start /usr/local/bin/anybot-a11y /usr/loc # without it — no numbers at all, only a picture to guess at. GTK 3 apps ignore it. ENV DISPLAY=:1 SCREEN_SIZE=1280x800x24 GTK_MODULES=gail:atk-bridge GTK_A11Y=atspi GNOME_ACCESSIBILITY=1 NO_AT_BRIDGE=0 EXPOSE 6080 -LABEL anybot.box.version="9" +LABEL anybot.box.version="10" ENTRYPOINT ["/usr/bin/tini", "--"] CMD ["/usr/local/bin/anybot-box-start"] diff --git a/box/browser b/box/browser index 117c179..245514d 100644 --- a/box/browser +++ b/box/browser @@ -16,7 +16,39 @@ fi # browser tools opened), so a site could be logged in in one and not the other. Chromium's own # is the one now (the other stays as it was); a box that only has AnyBot's keeps that. PROFILE=/home/bot/.config/anybot-profile -if [[ ! -e "$PROFILE" ]]; then +PORT=9222 +LOCK=/tmp/.anybot-browser.lock +LOG=/tmp/anybot-browser.log +# 每個 Bot 一個螢幕 (anybot-screen): ANYBOT_SCREEN= starts that bot's own browser on its own +# screen, with a profile of its own and its own DevTools port. The first time, the profile starts +# as a copy of the shared one, so the sites logged in there are logged in here too (the box keeps +# its cookies with --password-store=basic, readable by any profile of the same user). A 支線's +# temporary screen copies its main bot's instead (the logins that bot has now). +if [[ -n "${ANYBOT_SCREEN:-}" ]]; then + [[ "$ANYBOT_SCREEN" =~ ^[A-Za-z0-9_-]{1,48}$ ]] || { echo "bad screen" >&2; exit 2; } + ENV=/tmp/anybot-screens/$ANYBOT_SCREEN/env + [[ -r "$ENV" ]] || { echo "no screen $ANYBOT_SCREEN: anybot-screen up first" >&2; exit 2; } + # shellcheck disable=SC1090 + set -a; source "$ENV"; set +a + PORT=$CDP_PORT + LOCK=/tmp/.anybot-browser-$ANYBOT_SCREEN.lock + LOG=/tmp/anybot-browser-$ANYBOT_SCREEN.log + if [[ ! -d "$PROFILE/Default" ]]; then + SHARED=$(readlink -f /home/bot/.config/anybot-profile 2>/dev/null || true) + # A 支線's temporary screen (-t) starts from its main bot's browser when it has one. + if [[ "$ANYBOT_SCREEN" =~ ^(.+)-t[0-9]+$ && -d "/home/bot/.config/anybot-profiles/${BASH_REMATCH[1]}/Default" ]]; then + SHARED=/home/bot/.config/anybot-profiles/${BASH_REMATCH[1]} + fi + mkdir -p "$PROFILE/Default" + if [[ -n "$SHARED" && -d "$SHARED/Default" ]]; then + cp -a "$SHARED/Local State" "$PROFILE/" 2>/dev/null || true + for f in Cookies Cookies-journal "Login Data" "Login Data-journal" "Web Data" "Web Data-journal" Preferences "Secure Preferences" "Local Storage" "Session Storage" IndexedDB; do + [[ -e "$SHARED/Default/$f" ]] && cp -a "$SHARED/Default/$f" "$PROFILE/Default/" 2>/dev/null || true + done + fi + fi +fi +if [[ -z "${ANYBOT_SCREEN:-}" && ! -e "$PROFILE" ]]; then if [[ -d /home/bot/.config/chromium/Default || ! -d /home/bot/.config/anybot-browser/Default ]]; then mkdir -p /home/bot/.config/chromium && ln -s /home/bot/.config/chromium "$PROFILE" else @@ -28,14 +60,14 @@ fi # ANYBOT_BOX_SANDBOX=1 — Chromium's own sandbox works there, so keep it as a second wall. SANDBOX=(--no-sandbox --test-type) [ "${ANYBOT_BOX_SANDBOX:-0}" = 1 ] && SANDBOX=() -FLAGS=("${SANDBOX[@]}" --user-data-dir="$PROFILE" --remote-debugging-address=127.0.0.1 --remote-debugging-port=9222 +FLAGS=("${SANDBOX[@]}" --user-data-dir="$PROFILE" --remote-debugging-address=127.0.0.1 --remote-debugging-port=$PORT --remote-allow-origins=http://127.0.0.1 --force-renderer-accessibility --disable-blink-features=AutomationControlled --disable-dev-shm-usage --disable-gpu --use-angle=swiftshader --enable-unsafe-swiftshader --password-store=basic --no-first-run --no-default-browser-check --disable-session-crashed-bubble --hide-crash-restore-bubble --disable-features=TranslateUI --start-maximized) # Two starts in the same second (the bot and the person) would both find no browser and fight # over the profile ("in use"): one at a time until the first is listening. -exec 9>/tmp/.anybot-browser.lock +exec 9>"$LOCK" flock -w 30 9 || true if pgrep -u bot -f -- "--user-data-dir=$PROFILE" >/dev/null || pgrep -u bot -f -- "--user-data-dir=$(readlink -f "$PROFILE")" >/dev/null; then flock -u 9 @@ -45,8 +77,8 @@ fi rm -f "$PROFILE"/SingletonLock "$PROFILE"/SingletonSocket "$PROFILE"/SingletonCookie # (The lock's fd is not handed to the browser: it would hold the lock for its whole life, and the # next start would wait on it.) -setsid chromium "${FLAGS[@]}" "${@:-about:blank}" >/tmp/anybot-browser.log 2>&1 < /dev/null 9>&- & +setsid chromium "${FLAGS[@]}" "${@:-about:blank}" >"$LOG" 2>&1 < /dev/null 9>&- & for _ in $(seq 1 100); do - python3 -c "import urllib.request; urllib.request.urlopen('http://127.0.0.1:9222/json/version', timeout=1).close()" 2>/dev/null && break + python3 -c "import urllib.request; urllib.request.urlopen('http://127.0.0.1:$PORT/json/version', timeout=1).close()" 2>/dev/null && break sleep 0.25 done diff --git a/box/screen b/box/screen new file mode 100755 index 0000000..c146f3f --- /dev/null +++ b/box/screen @@ -0,0 +1,147 @@ +#!/bin/bash +# 每個 Bot 一個螢幕 (Grok Bot's split: one computer per account, a screen of its own per bot, so +# bots use the desktop and the browser side by side instead of waiting for each other on :1). +# The box's own screen :1 stays as it is (the person's shared desktop). +# +# anybot-screen up the screen of (a bot), made when it isn't there; prints +# KEY=VALUE lines: DISPLAY, DBUS_SESSION_BUS_ADDRESS, VNC_PORT, CDP_PORT, +# PROFILE. Using it marks it used (see reap). +# anybot-screen down close it (its browser too); the browser profile stays on disk +# anybot-screen list one line per open screen: key display seconds-since-used +# anybot-screen reap close the screens nobody used for that long +# +# Exit 3 when ANYBOT_MAX_SCREENS screens are open already: the keys holding them are printed. +# (What it starts in the background never keeps the lock: each gets 8>&-.) +# Runs as the bot user (how AnyBot calls it) or as root (the desktop is the bot user's either way). +# Each open screen is in /tmp/anybot-vnc-tokens, so the box's one web viewer (port 6080) shows any +# of them: ?path=websockify%3Ftoken%3D ("main" is the shared screen). +# -t is a temporary screen (a 支線's, beside its main bot ): its browser starts as a +# copy of 's (box/browser), and that copy is removed with the screen. +set -u +DIR=/tmp/anybot-screens +MAX=${ANYBOT_MAX_SCREENS:-6} +# Displays :10, :11, … — VNC on 5900+n and the browser's DevTools on 9300+n, both on 127.0.0.1. +FIRST=10 +mkdir -p "$DIR" 2>/dev/null; chmod 1777 "$DIR" 2>/dev/null + +TOKENS=/tmp/anybot-vnc-tokens + +key_ok() { [[ "$1" =~ ^[A-Za-z0-9_-]{1,48}$ ]]; } +# The bot user's side of the desktop (fluxbox, the buses): as is when we are the bot user. +as_bot() { if [ "$(id -u)" = 0 ]; then su bot -c "$1"; else sh -c "$1"; fi; } +token_set() { { grep -v "^$1: " "$TOKENS" 2>/dev/null; [ -n "${2:-}" ] && echo "$1: localhost:$2"; } > "$TOKENS.new"; mv -f "$TOKENS.new" "$TOKENS"; } +alive() { [ -n "${1:-}" ] && kill -0 "$1" 2>/dev/null; } + +# The screen's processes (Xtigervnc, its dbus, fluxbox, the accessibility bus, the browser), killed +# youngest first. +close() { + local d=$DIR/$1 + [ -d "$d" ] || return 0 + local disp; disp=$(cat "$d/display" 2>/dev/null) + if [ -n "$disp" ]; then + # (The browser gets a moment to write its profile before it is killed.) + local prof="--user-data-dir=/home/bot/.config/anybot-profiles/$1( |\$)" + if pkill -u bot -f -- "$prof" 2>/dev/null; then + for _ in $(seq 1 20); do pgrep -u bot -f -- "$prof" >/dev/null || break; sleep 0.1; done + pkill -9 -u bot -f -- "$prof" 2>/dev/null + fi + for p in $(cat "$d/pids" 2>/dev/null | tac); do kill "$p" 2>/dev/null; done + sleep 0.3 + for p in $(cat "$d/pids" 2>/dev/null); do kill -9 "$p" 2>/dev/null; done + rm -f "/tmp/.X$disp-lock" "/tmp/.X11-unix/X$disp" + fi + token_set "$1" + rm -rf "$d" + [[ "$1" =~ -t[0-9]+$ ]] && rm -rf "/home/bot/.config/anybot-profiles/$1" + return 0 +} + +print_env() { + local d=$DIR/$1 + touch "$d/last" + cat "$d/env" +} + +up() { + local key=$1 d=$DIR/$1 + # Already there and its X server alive: just say where. + if [ -f "$d/env" ] && alive "$(head -1 "$d/pids" 2>/dev/null)"; then + print_env "$key" + return 0 + fi + close "$key" + local open=() n disp="" + for s in "$DIR"/*/; do [ -f "$s/env" ] && open+=("$(basename "$s")"); done + if [ "${#open[@]}" -ge "$MAX" ]; then + printf 'FULL=%s\n' "${open[*]}" + exit 3 + fi + for ((n = FIRST; n < FIRST + 64; n++)); do + [ -e "/tmp/.X$n-lock" ] || [ -e "/tmp/.X11-unix/X$n" ] || grep -qx "$n" "$DIR"/*/display 2>/dev/null || { disp=$n; break; } + done + [ -n "$disp" ] || { echo "ERROR=no free display" ; exit 1; } + mkdir -p "$d" + echo "$disp" > "$d/display" + local geom="${SCREEN_SIZE:-1440x900x24}"; geom="${geom%x*}" + local sec="-SecurityTypes None" + [ -r /home/bot/.vnc/passwd ] && sec="-SecurityTypes VncAuth -rfbauth /home/bot/.vnc/passwd" + # shellcheck disable=SC2086 + Xtigervnc ":$disp" -geometry "$geom" -depth 24 -rfbport $((5900 + disp)) -localhost $sec -AlwaysShared -AcceptCutText -SendCutText \ + -UseBlacklist 0 -IdleTimeout 0 -MaxIdleTime 0 -MaxDisconnectionTime 0 -MaxConnectionTime 0 -s 0 -dpms -desktop "Bot 的電腦 · $key" -ac -noreset \ + >"$d/xvnc.log" 2>&1 8>&- & + echo $! > "$d/pids" + for _ in $(seq 1 50); do xdpyinfo -display ":$disp" >/dev/null 2>&1 && break; sleep 0.1; done + xdpyinfo -display ":$disp" >/dev/null 2>&1 || { echo "ERROR=the screen did not start"; close "$key"; exit 1; } + # A session bus and an accessibility registry of its own: the controls listed for this screen + # are this screen's apps only. + local out bus buspid + out=$(as_bot 'cd /home/bot && dbus-launch --sh-syntax' 8>&-) + bus=$(printf '%s\n' "$out" | sed -n "s/^DBUS_SESSION_BUS_ADDRESS='\(.*\)';\$/\1/p") + buspid=$(printf '%s\n' "$out" | sed -n 's/^DBUS_SESSION_BUS_PID=\([0-9]*\);$/\1/p') + [ -n "$buspid" ] && echo "$buspid" >> "$d/pids" + for c in /usr/libexec/at-spi-bus-launcher /usr/lib/at-spi2-core/at-spi-bus-launcher; do + [ -x "$c" ] && { as_bot "DISPLAY=:$disp DBUS_SESSION_BUS_ADDRESS=$bus setsid $c --launch-immediately >/dev/null 2>&1 & echo \$!" 8>&- >> "$d/pids"; break; } + done + for c in /usr/libexec/at-spi2-registryd /usr/lib/at-spi2-core/at-spi2-registryd; do + [ -x "$c" ] && { as_bot "DISPLAY=:$disp DBUS_SESSION_BUS_ADDRESS=$bus setsid $c >/dev/null 2>&1 & echo \$!" 8>&- >> "$d/pids"; break; } + done + as_bot "DISPLAY=:$disp xrdb -nocpp -merge /home/bot/.Xresources" 2>/dev/null + as_bot "DISPLAY=:$disp DBUS_SESSION_BUS_ADDRESS=$bus setsid fluxbox >/dev/null 2>&1 & echo \$!" 8>&- >> "$d/pids" + xsetroot -display ":$disp" -solid '#2b2f36' + { + echo "DISPLAY=:$disp" + echo "DBUS_SESSION_BUS_ADDRESS=$bus" + echo "VNC_PORT=$((5900 + disp))" + echo "CDP_PORT=$((9300 + disp))" + echo "PROFILE=/home/bot/.config/anybot-profiles/$key" + } > "$d/env" + chmod 644 "$d/env" "$d/display" + token_set "$key" $((5900 + disp)) + print_env "$key" +} + +reap() { + local limit=$1 now; now=$(date +%s) + for s in "$DIR"/*/; do + [ -d "$s" ] || continue + local k; k=$(basename "$s") + local last; last=$(stat -c %Y "$s/last" 2>/dev/null || echo 0) + if [ $((now - last)) -ge "$limit" ] || ! alive "$(head -1 "$s/pids" 2>/dev/null)"; then close "$k"; echo "closed $k"; fi + done +} + +cmd=${1:-}; arg=${2:-} +exec 8>"$DIR/.lock" +flock -w 20 8 || { echo "ERROR=busy"; exit 1; } +case "$cmd" in + up) key_ok "$arg" || { echo "ERROR=bad key"; exit 2; }; up "$arg" ;; + down) key_ok "$arg" || { echo "ERROR=bad key"; exit 2; }; close "$arg" ;; + list) + now=$(date +%s) + for s in "$DIR"/*/; do + [ -f "$s/env" ] || continue + echo "$(basename "$s") :$(cat "$s/display") $((now - $(stat -c %Y "$s/last" 2>/dev/null || echo "$now")))" + done ;; + reap) [[ "$arg" =~ ^[0-9]+$ ]] || { echo "ERROR=seconds"; exit 2; }; reap "$arg" ;; + *) sed -n '2,15p' "$0"; exit 2 ;; +esac diff --git a/box/start.sh b/box/start.sh index 1fdad23..7b6ab78 100644 --- a/box/start.sh +++ b/box/start.sh @@ -14,6 +14,8 @@ GEOM="${SCREEN_SIZE%x*}" if [ -n "${VNC_PASSWORD:-}" ]; then mkdir -p /home/bot/.vnc printf '%s\n' "$VNC_PASSWORD" | vncpasswd -f > /home/bot/.vnc/passwd && chmod 600 /home/bot/.vnc/passwd + # (The bot user opens the bots' own screens with the same password: anybot-screen.) + chown bot:bot /home/bot/.vnc /home/bot/.vnc/passwd VNC_SEC="-SecurityTypes VncAuth -rfbauth /home/bot/.vnc/passwd" else VNC_SEC="-SecurityTypes None" @@ -41,7 +43,11 @@ su bot -c "DISPLAY=:1 DBUS_SESSION_BUS_ADDRESS=$DBUS_SESSION_BUS_ADDRESS xrdb -n su bot -c "DISPLAY=:1 DBUS_SESSION_BUS_ADDRESS=$DBUS_SESSION_BUS_ADDRESS fluxbox >/tmp/fluxbox.log 2>&1 &" (sleep 1.5; xsetroot -display :1 -solid '#2b2f36') & xsetroot -display :1 -solid '#2b2f36' -websockify --web /usr/share/novnc 6080 localhost:5900 >/tmp/novnc.log 2>&1 & +# One web viewer for every screen: the shared one is "main"; anybot-screen adds each bot's own +# (每個 Bot 一個螢幕). A viewer picks one with ?path=websockify%3Ftoken%3D. +rm -rf /tmp/anybot-screens; mkdir -p /tmp/anybot-screens && chmod 1777 /tmp/anybot-screens +echo "main: localhost:5900" > /tmp/anybot-vnc-tokens && chown bot:bot /tmp/anybot-vnc-tokens +websockify --web /usr/share/novnc --token-plugin TokenFile --token-source /tmp/anybot-vnc-tokens 6080 >/tmp/novnc.log 2>&1 & WEBSOCKIFY_PID=$! # Say ready only once the viewer's port listens: the app opens noVNC on this flag, and a too # early file meant the first viewer load 404'd. diff --git a/docs/feature-map/browser.md b/docs/feature-map/browser.md index bdd5e94..36bc8c7 100644 --- a/docs/feature-map/browser.md +++ b/docs/feature-map/browser.md @@ -11,6 +11,7 @@ Bot 用 AnyBot 自己的瀏覽器上網、登入網站、點按、打字、送 - 打字:`type` 的換行會整段放進去(像貼上),結果會說欄位現在裝了什麼。 - 間隔:`wait` 加 `after_send: true`,從上一次送出起算(最多 900 秒),下一則可以先打好再等。 - 發布關卡(Bot 自己的瀏覽器送出時):送出前讀頁面,看是哪個帳號、回哪一篇;同一帳號回過同一篇就擋下(已送帳本,記 60 天);發布前檢查請另一個模型看過文字;送出後重讀頁面,確認文字出現、抓留言網址,結果寫「【系統】已送出…」。 +- Bot 自己的電腦上:每個 Bot 在自己的螢幕上有自己的瀏覽器;第一次開時從共用的那份複製登入過來,之後各自登入、互不影響。支線的瀏覽器從主線那份複製,支線結束就刪掉。 - 做完就關掉瀏覽器:一輪結束就把它用過的視窗關掉(別的 Bot 還在用的不關)。 ## 使用者怎麼到 @@ -29,6 +30,8 @@ Bot 用 AnyBot 自己的瀏覽器上網、登入網站、點按、打字、送 - 同一個網站在不同電腦、不同設定檔的登入不共用;沒帶 `profile` 會用到別的設定檔。 - 使用者自己的 Firefox 設定檔,如果他已經用平常的方式開著,要先請他關掉那個視窗,AnyBot 才開得起來。 - 一模一樣的按鈕(例如每篇貼文都有的「回覆」)在清單裡只列一次;要點第二篇的,先 `open` 那篇貼文的網址再點。 +- 下拉選單用 `select`,`option` 填選項上看得到的字(給 `value` 也行,對下拉選單 `type` 也會改成選選項);什麼都沒給會報錯。 +- `fill` 是保險庫的填入;指著頁面上一個欄位(有 `ref`/`text`、沒有 kind/id/site)時當成 `type`(有 `option` 時當 `select`),不會跑去保險庫。 - `eval` 只能讀頁面:不能發請求、讀 cookie 或儲存、送出表單、換頁(會被拒絕);直接呼叫網站內部 API 會被當成機器人。 - 雲端中繼資料位址永遠打不開;本機或內部網路的網址要使用者允許(直接操作模式除外)。 - 發布關卡、已送帳本、送出後確認只管 AnyBot 自己的瀏覽器;用螢幕操作送出的,只能從步驟推算。頁面看不出回哪一篇時,只擋 24 小時內同一頁一模一樣的內容。 diff --git a/docs/feature-map/computers.md b/docs/feature-map/computers.md index 2141a63..388fe79 100644 --- a/docs/feature-map/computers.md +++ b/docs/feature-map/computers.md @@ -5,7 +5,7 @@ ## 子功能 - 四種電腦,每台都用自己的名字稱呼: - - Bot 自己的電腦(「 的電腦」):一台 Linux(Debian,有桌面和 Chromium,可以 sudo 裝套件),跑在 Docker 裡,所有 Bot 共用、各有自己的資料夾,一直開著。沒有 Docker 時退回成一個封閉的資料夾,沒有桌面。 + - Bot 自己的電腦(「 的電腦」):一台 Linux(Debian,有桌面和 Chromium,可以 sudo 裝套件),跑在 Docker 裡,所有 Bot 共用一台,各有自己的資料夾、自己的螢幕和自己的瀏覽器(見 [screen](screen.md)),一直開著。沒有 Docker 時退回成一個封閉的資料夾,沒有桌面。 - 這台電腦(AnyBot 開著的這台,名字可以改):從 Bot 的「起始資料夾」開始。大腦放在伺服器上時,伺服器本身不在清單裡。 - SSH 電腦:自己加的,一個名稱加一個位址(例如 me@studio.local)。 - 帳號裡的其他電腦:登入同一個帳號、打開「讓帳號裡的其他電腦使用這台」、而且現在在線上的 AnyBot(螢幕電腦、手腳電腦),經過帳號伺服器操作檔案、指令、瀏覽器、看畫面和點擊。 diff --git a/docs/feature-map/connectors.md b/docs/feature-map/connectors.md index 86aa287..0e54d98 100644 --- a/docs/feature-map/connectors.md +++ b/docs/feature-map/connectors.md @@ -33,3 +33,5 @@ - 要登入帳號(OAuth)的連接器 AnyBot 還不支援,連線時狀態會說;它若也收 API 金鑰,填在「標頭」。公用市集裡舊式 SSE 的會標「舊式 SSE 連線,AnyBot 還不支援」。 - 公用市集只列用網址連的;要在大腦上跑 npm/PyPI 套件的不列。本機連接器要大腦那台裝了 Node.js(npx)或 uv(uvx)。 - 在螢幕上改了指令或網址,大腦會清掉密碼(免得送到新的位址),要重新填。 +- 參數裡的資料夾在這台找不到(在別台電腦設定的),連接器不連,狀態寫「這台電腦上沒有…」;指令是 `docker`、`ssh` 這類在別處執行的,不檢查(路徑在容器或那台主機上)。 +- `anybot --ask` 沒有視窗,也會先連好連接器再開始。 diff --git a/docs/feature-map/files.md b/docs/feature-map/files.md index d800ec1..b5c5d5d 100644 --- a/docs/feature-map/files.md +++ b/docs/feature-map/files.md @@ -29,7 +29,7 @@ Bot 在它能用的電腦上跑指令、讀寫和搜尋檔案、開背景指令 - 機密檔案一律不能讀、改、傳、打開或發佈:AnyBot 自己的資料資料夾、.git、.ssh、.gnupg、.aws、Keychains、.env、.pem、.key、id_rsa 開頭的檔案等。 - 在這台電腦上:工作資料夾外讀東西先問(可以一律允許);改檔案會問,工作資料夾外的每次都問、不能一律允許;指令除了唯讀的都會問;sudo、rm -rf /、mkfs、dd、shutdown 這類一律拒絕。完整規則見 [safety](safety.md)。 -- 在 Bot 自己的電腦上,指令和檔案都不用問(可以 sudo,但後面接的一律拒絕指令照樣擋);檔案工具只碰得到它自己的資料夾。 +- 在 Bot 自己的電腦上,指令和檔案都不用問(可以 sudo,但後面接的一律拒絕指令照樣擋);檔案工具只碰得到它自己的資料夾。有 sudo 的指令整條用 root 跑,跑完它在 Bot 家目錄裡新留下的檔案會交還給 Bot(不只它的資料夾)。 - SSH 電腦和帳號裡的其他電腦:讀不用問,改檔案和會改變東西的指令會問。 - 開互動的 shell(bash、zsh、PowerShell…)每次都問、沒有一律允許:之後在裡面打的指令不會再一條一條檢查。 - 一般指令的輸入是關的,`write_terminal` 打不進去:要互動就用 interactive 重跑,或用參數答掉(-y、--yes)。 diff --git a/docs/feature-map/screen.md b/docs/feature-map/screen.md index d90b126..257e62d 100644 --- a/docs/feature-map/screen.md +++ b/docs/feature-map/screen.md @@ -11,7 +11,8 @@ Bot 用一個 `computer` 工具看一台電腦的螢幕、動滑鼠和鍵盤: - `intent`:系統捷徑(音量、Wi-Fi、鎖螢幕、深淺色、清空垃圾桶,Mac 還有退出磁碟)一步做完。電腦現況列了「系統捷徑」才有:macOS 和 Linux 桌面有,Windows 和 Bot 自己的電腦沒有。 - 交給使用者:`hand_over_computer` 在聊天放一張「需要處理」卡和那台電腦的畫面,使用者做完按「我完成了」或「跳過」。 - 示範教學(macOS、Linux X11):使用者自己做一次,AnyBot 記成步驟和每一步的畫面;Bot 用 `view_demo_step` 看某一步當時的畫面。 -- 同一個螢幕一次只給一個 Bot 操作;別人在用時會被擋下,對方停手 120 秒後輪到。只看畫面不受影響。 +- Bot 自己的電腦:每個 Bot 有自己的螢幕(照 Grok Bot 的分法:一台電腦、每個 Bot 一個螢幕),Bot 第一次看畫面或用瀏覽器時才開,大家同時做互不干擾。支線另開一個暫時的螢幕(瀏覽器從主線那份複製),支線結束就關掉、複製的那份也刪掉。同時最多開 6 個,閒置 10 分鐘的會自己關掉(瀏覽器的登入留著)。原本那個共用的桌面還在。 +- 使用者自己的電腦只有一個實體螢幕:一次只給一個 Bot 操作,別人在用時會被擋下,對方停手 120 秒後輪到。只看畫面不受影響。 - 截圖上的卡號和驗證碼會先塗黑,才交給模型。 ## 使用者怎麼到 @@ -20,7 +21,9 @@ Bot 用一個 `computer` 工具看一台電腦的螢幕、動滑鼠和鍵盤: - 同一處的「一律允許的應用程式」(有授權才出現):每個 Bot 不用問就能操作的 App,可以逐一移除;「整個螢幕(看不出是哪個 App 時)」就是 `computer:control`。 - Bot 在這台電腦上動滑鼠鍵盤時,螢幕上方有「{Bot} 正在操作你的電腦」:按「取得控制權」Bot 先停手(變成「你正在操作,Bot 已暫停」,按「交還給 Bot」還它);按「停止」停掉那一輪。 - 設定 ›「電腦」›「示範教學」:替目前選的 Bot 輸入任務名稱,按「開始錄製」,照平常做,做完按上方「{Bot} 正在觀看並學習」的「完成」。之後跟 Bot 說「照示範做 名稱」。每個示範可以「播放錄影」、展開「步驟」看每一步的「畫面」、「刪除」。 -- 「需要處理」卡:Bot 自己的電腦可以在卡上按「接管」直接做;其他電腦要到那台去做。手機上也有同一張卡。 +- 「需要處理」卡:Bot 自己的電腦可以在卡上按「接管」直接做,打開的是那個 Bot 自己的螢幕,接管時只有它停手,別的 Bot 照做;其他電腦要到那台去做。手機上也有同一張卡。 +- 右側面板的「電腦」畫面和「開啟電腦」:顯示目前選的 Bot 自己的螢幕(還沒開過就顯示共用的桌面);群組聊天顯示正在回答的成員的螢幕,「成員」卡片上點某個成員的小畫面就改顯示它的(再點一次回到跟著回答的人)。 +- 「電腦」卡片下的「全部螢幕(N)」(有 Bot 開著自己的螢幕才出現):每個螢幕一格小畫面,寫是誰的、閒置多久;點一格打開那個螢幕看或接手。 - Bot 設定 ›「能力」›「看螢幕與操作」沒開,Bot 就沒有 `computer`。 ## 怎麼操作 @@ -36,6 +39,7 @@ Bot 用一個 `computer` 工具看一台電腦的螢幕、動滑鼠和鍵盤: - 按鍵和沒指定欄位的 `typing` 只送到上次截圖時在最前面的 App;中途換了 App 會「沒有按」:先截圖或 `open_app`。 - 結果說「畫面和上一步完全一樣」就是沒點到:換編號或換方法,不要重複同一步。 - Linux 上開著 IBus 輸入法(注音、拼音)時,`typing` 可能回「已打字(N 個字)」但字沒進去:N 是送出的字數,不是欄位裡的內容。一定看截圖確認;長字或中文改用剪貼簿貼上比較可靠。(Mac 會先直接寫進欄位或用貼上;Bot 自己的電腦中文和長字會自動貼上。) +- 「全部螢幕」和成員的小畫面每 3 秒更新一次,不是即時畫面;要看即時的點進去。 - `batch` 裡不能 `open_app`,也不能用 cmd+tab 這類切換 App 的鍵。 - 塗黑的卡號、驗證碼 Bot 讀不到:要碼的步驟用 `hand_over_computer`。 - Mac 沒開「螢幕與系統錄音」時 `screenshot` 只有清單沒有圖;沒開「輔助使用」不能點也不能打字。系統詢問最多每 10 分鐘跳一次。 diff --git a/docs/feature-map/team.md b/docs/feature-map/team.md index ecb3a18..bad8d3d 100644 --- a/docs/feature-map/team.md +++ b/docs/feature-map/team.md @@ -16,7 +16,7 @@ Bot 之間可以問問題、交辦工作、教技能;好幾個 Bot 可以在 ## 使用者怎麼到 -- 群組聊天:側邊欄 +(「新增」)›「群組聊天」,先放前三個 Bot 並打開設定,在「群組成員」勾選。群組的輸入框 + 裡寫「成員:…」,右側面板有「成員」。 +- 群組聊天:側邊欄 +(「新增」)›「群組聊天」,先放前三個 Bot 並打開設定,在「群組成員」勾選。群組的輸入框 + 裡寫「成員:…」,右側面板有「成員」;右側的「電腦」畫面跟著正在回答的成員,顯示它自己的螢幕;「成員」卡片上點某個成員的小畫面,改成固定顯示它的。 - 分區:+ ›「新增分區」;Bot 選單「移至」(還沒有分區時是「移至新分區」)。分區標題點一下收合、雙擊改名,右鍵或 ⋯(「分區操作」)有「重新命名」「上移」「下移」「刪除」。 - 支線:輸入框打「/」選 /btw。主聊天出現支線卡:狀態、「停止支線」、「看過程」,支線要你核准的步驟直接在卡上按;沒做完時有「重開這條支線」。 @@ -32,5 +32,6 @@ Bot 之間可以問問題、交辦工作、教技能;好幾個 Bot 可以在 - 一件事從使用者開始,最多在 Bot 之間轉 3 手;A 在等 B 時,B 不能反過來問 A(會說「正在等你」)。使用者停止 A,替 A 回答的 B 也會停。 - 不能問自己,不能問群組或把技能教給群組(改找裡面的成員);自己不會的技能不能教,對方已經會的不用教。 - 別的 Bot 問或交辦的那一輪不算使用者的話:B 不能因此改自己的設定。答案在發問的聊天裡整理給使用者,不要叫他自己去看別的 Bot 的聊天。被點名同事、卻沒有「和其他 Bot 合作」能力的 Bot,只能照實說,請使用者打開。 +- 群組成員在 Bot 的電腦上各有自己的螢幕和瀏覽器,看不到彼此開著的網頁:交棒時要把網址、檔案或頁面寫進回覆(系統指示會提醒成員這樣做)。 - 群組成員互相 @ 交棒時,兩則使用者訊息之間到 8 個回答就停,交還給使用者。群組自己的模型不會用到;群組不能開支線,輸入框上沒有記憶小卡片;成員至少留一個。 -- 支線:一個 Bot 同時最多 3 條;支線不能再開支線,也不能改設定;支線記的、做的頁面和例行任務都算主 Bot 的。主線在忙時,先用執行步驟用的模型判斷會不會衝突,會就等主線這一輪做完。AnyBot 重新啟動時,沒做完的支線會停掉(「AnyBot 重新啟動,這條支線停了」);被停止的支線不回報。 +- 支線:一個 Bot 同時最多 3 條;支線不能再開支線,也不能改設定;支線記的、做的頁面和例行任務都算主 Bot 的。主線在忙時,先用執行步驟用的模型判斷會不會衝突,會就等主線這一輪做完。在 Bot 的電腦上支線有自己的暫時螢幕和瀏覽器(登入從主線複製),看不到主線開著的網頁;在使用者的電腦上還是一次一個。AnyBot 重新啟動時,沒做完的支線會停掉(「AnyBot 重新啟動,這條支線停了」);被停止的支線不回報。 diff --git a/mobile/index.html b/mobile/index.html index 17aa896..81f93d1 100644 --- a/mobile/index.html +++ b/mobile/index.html @@ -2615,7 +2615,7 @@ function openBox(control) { const at = S.relay ? "host=" + encodeURIComponent(S.host) : "lan=1"; boxOpen = true; history.pushState({box: 1}, ""); - $("boxframe").src = "screen#" + at + "&name=" + encodeURIComponent(own ? own.name : "Bot 的電腦") + (control ? "&control=1" : "") + "&embed=1"; + $("boxframe").src = "screen#" + at + "&name=" + encodeURIComponent(own ? own.name : "Bot 的電腦") + (b.id ? "&bot=" + b.id : "") + (control ? "&control=1" : "") + "&embed=1"; $("boxwrap").style.display = "block"; } function closeBox() { diff --git a/mobile/screen.html b/mobile/screen.html index 9009dd7..6b5ffa4 100644 --- a/mobile/screen.html +++ b/mobile/screen.html @@ -116,7 +116,9 @@ async function ticketFor(path, body) { const lan = q.get("lan") === "1"; const given = q.get("ticket") || await ticketFor(lan ? "api/vnc/ticket" : "relay/screen-ticket", lan ? {} : {host: q.get("host") || ""}); const auth = given ? "ticket=" + encodeURIComponent(given) : "t=" + encodeURIComponent(token); -const url = lan ? `${wsBase}/api/vnc?${auth}` : `${wsBase}/relay/vnc/${encodeURIComponent(q.get("host") || "")}?${auth}`; +// 每個 Bot 一個螢幕: the bot whose screen this is (the AnyBot shows its own screen, or the shared one). +const botq = /^\d+$/.test(q.get("bot") || "") ? "&bot=" + q.get("bot") : ""; +const url = lan ? `${wsBase}/api/vnc?${auth}${botq}` : `${wsBase}/relay/vnc/${encodeURIComponent(q.get("host") || "")}?${auth}${botq}`; const $ = (id) => document.getElementById(id); document.title = name; diff --git a/relay/src/main.rs b/relay/src/main.rs index 8d4bacd..d5e2a2f 100644 --- a/relay/src/main.rs +++ b/relay/src/main.rs @@ -492,7 +492,9 @@ impl Relay { let sid = httpd::random_hex(8); let (tx, rx) = std::sync::mpsc::sync_channel::>(256); self.streams.lock().unwrap().insert(sid.clone(), (tx, host.to_string(), on)); - if to_host.send(wire::pack(&json!({"t": "vopen", "sid": sid}), &[])).is_err() { + // 每個 Bot 一個螢幕: which bot's screen (digits only; the AnyBot picks the screen). + let bot: String = req.query.get("bot").map(|b| b.chars().filter(|c| c.is_ascii_digit()).take(20).collect()).unwrap_or_default(); + if to_host.send(wire::pack(&json!({"t": "vopen", "sid": sid, "bot": bot}), &[])).is_err() { self.streams.lock().unwrap().remove(&sid); return; } diff --git a/src/agent.rs b/src/agent.rs index d84fee4..62b2d7b 100644 --- a/src/agent.rs +++ b/src/agent.rs @@ -359,6 +359,8 @@ enum BotBrowser { /// another job's, and the person's, stay (see botbrowser's "each job its own tabs"). struct UsedBrowsers { list: Vec, + /// The bot's screen on the bots' computer (its box browser is there). + screen: String, via_name: String, /// Close each browser when done (not only the tabs). close: bool, @@ -382,7 +384,7 @@ fn with_job(args: &str, job: &str) -> String { impl UsedBrowsers { fn new(via_name: &str, bot_id: u64, close: bool) -> Self { let n = JOB_SEQ.fetch_add(1, Ordering::Relaxed); - UsedBrowsers { list: vec![], via_name: via_name.to_string(), close, job: format!("{bot_id}-{}-{n}", crate::model::now_ms()) } + UsedBrowsers { list: vec![], screen: String::new(), via_name: via_name.to_string(), close, job: format!("{bot_id}-{}-{n}", crate::model::now_ms()) } } fn add(&mut self, b: BotBrowser) { @@ -407,7 +409,8 @@ impl UsedBrowsers { let _ = web::run_full("browser_tabs", &args(p), &never); } BotBrowser::Box(p) => { - let _ = crate::botbrowser::in_box(|| web::run_full("browser_tabs", &args(p), &never)); + // (Its own browser on its own screen: 每個 Bot 一個螢幕.) + let _ = crate::cloudbox::on_screen(&self.screen, || crate::botbrowser::in_box(|| web::run_full("browser_tabs", &args(p), &never))); } BotBrowser::Device(host, p) => { let _ = crate::remote::run_on_device(host, "browser_tabs", &args(p), &self.via_name); @@ -605,10 +608,11 @@ fn screen_leases() -> &'static Mutex { /// other work, or forgot to finish), or as soon as that turn ends. pub const SCREEN_IDLE: Duration = Duration::from_secs(120); -/// Which physical screen a computer is: the bots' computer is one desktop for all of them. +/// Which screen a computer is. The bots' computer has a screen for each bot (cloudbox: 每個 Bot +/// 一個螢幕), so bots there don't wait for each other; a person's computer has the one. fn screen_key(place: &tools::Place) -> Option { match place { - tools::Place::Box { .. } => Some("box".into()), + tools::Place::Box { dir } => Some(format!("box:{}", crate::cloudbox::screen_of_dir(dir))), tools::Place::Local { .. } => Some("local".into()), tools::Place::Device { host, .. } => Some(format!("device:{host}")), _ => None, @@ -1423,6 +1427,30 @@ fn untrusted_refusal(job: &Job, name: &str) -> Option<&'static str> { (job.untrusted && crate::profile::ability_of(name) == Some("browser")).then_some(UNTRUSTED_BROWSER) } +/// The screen of this turn's bot on the bots' computer (its own folder's; cloudbox::screen_of_dir). +fn box_screen_of(job: &Job, bot_id: u64) -> String { + job.computers.iter().find_map(|t| match &t.place { + tools::Place::Box { dir } => Some(box_screen_in(job, bot_id, dir)), + _ => None, + }).unwrap_or_default() +} + +/// The screen a turn uses in the box folder `dir`: that bot's own; a 支線 (it works in its main +/// bot's folder) gets a temporary one beside it. +fn box_screen_in(job: &Job, bot_id: u64, dir: &str) -> String { + let own = crate::cloudbox::screen_of_dir(dir); + if job.home != 0 { crate::cloudbox::branch_screen(&own, bot_id) } else { own } +} + +/// Which screen a step of this turn takes on `place` (screen_key; a 支線 on the bots' computer has +/// its own, so it doesn't wait for its main line there). +fn turn_screen_key(job: &Job, bot_id: u64, place: &tools::Place) -> Option { + match place { + tools::Place::Box { dir } => Some(format!("box:{}", box_screen_in(job, bot_id, dir))), + _ => screen_key(place), + } +} + /// Runs one browser step where the bot's browser is (name, arguments) → (text, ok, picture). type Look<'a> = &'a dyn Fn(&str, &str) -> (String, bool, Option); @@ -1566,6 +1594,7 @@ pub fn spawn(job: Job, bot_id: u64, tx: Sender<(u64, StreamEvent)>, cancel: Arc< let mut tools_once = false; let mut local_once = false; let mut browsers = UsedBrowsers::new(&job.via_name, bot_id, job.close_browsers); + browsers.screen = box_screen_of(&job, bot_id); // 電腦現況: what someone at each computer already knows (system, sudo, network, apps…). // Added ONCE here, before the step loop: the turn's system prefix (instructions + facts) // and its tool list (and the deterministic `quick_tools` map of it) never change between @@ -2192,7 +2221,8 @@ pub fn spawn(job: Job, bot_id: u64, tx: Sender<(u64, StreamEvent)>, cancel: Arc< Ok(v) => (v["text"].as_str().unwrap_or("").to_string(), v["ok"].as_bool().unwrap_or(false), v["image"].as_str().map(String::from)), Err(e) => (e, false, None), }, - BrowserAt::Box => crate::botbrowser::in_box(|| web::run_full(name, args, &cancel)), + // 每個 Bot 一個螢幕: its own browser, on its own screen. + BrowserAt::Box => crate::cloudbox::on_screen(&box_screen_of(&job, bot_id), || crate::botbrowser::in_box(|| web::run_full(name, args, &cancel))), BrowserAt::Here => web::run_full(name, args, &cancel), } }; @@ -2690,7 +2720,7 @@ pub fn spawn(job: Job, bot_id: u64, tx: Sender<(u64, StreamEvent)>, cancel: Arc< } // (On this job's own tab, like its other browser steps: planned outside // it, every tab looked like another job's — "no open tab".) - BrowserAt::Box => crate::botbrowser::as_job(&tag, || crate::botbrowser::in_box(plan_here)), + BrowserAt::Box => crate::cloudbox::on_screen(&box_screen_of(&job, bot_id), || crate::botbrowser::as_job(&tag, || crate::botbrowser::in_box(plan_here))), BrowserAt::Here => crate::botbrowser::as_job(&tag, plan_here), }; let (output, status) = match planned { @@ -2732,7 +2762,7 @@ pub fn spawn(job: Job, bot_id: u64, tx: Sender<(u64, StreamEvent)>, cancel: Arc< let a = serde_json::json!({"kind": "form", "values": crate::vault::contact_values(c), "site": host, "profile": profile}).to_string(); remote_vault_page(h, &job, &with_job(&a, &tag)).and_then(|page| crate::vault::contact_fill_text(c, &page)) } - (_, BrowserAt::Box) => crate::botbrowser::as_job(&tag, || crate::botbrowser::in_box(fill_here)), + (_, BrowserAt::Box) => crate::cloudbox::on_screen(&box_screen_of(&job, bot_id), || crate::botbrowser::as_job(&tag, || crate::botbrowser::in_box(fill_here))), (_, BrowserAt::Here) => crate::botbrowser::as_job(&tag, fill_here), }; match r { @@ -2820,6 +2850,11 @@ pub fn spawn(job: Job, bot_id: u64, tx: Sender<(u64, StreamEvent)>, cancel: Arc< target_for(&job, &call.args) }; let on_box = matches!(target.as_ref().map(|t| &t.place), Ok(tools::Place::Box { .. })); + // 每個 Bot 一個螢幕: the screen of the bot whose folder this is (a 支線's own). + let box_screen = match target.as_ref().map(|t| &t.place) { + Ok(tools::Place::Box { dir }) => box_screen_in(&job, bot_id, dir), + _ => String::new(), + }; let on_device = match target.as_ref().map(|t| &t.place) { Ok(tools::Place::Device { host, .. }) => Some(host.clone()), _ => None, @@ -3073,7 +3108,7 @@ pub fn spawn(job: Job, bot_id: u64, tx: Sender<(u64, StreamEvent)>, cancel: Arc< let mut image = None; // 螢幕一次給一個: acting on a screen another turn is working (not just looking). let busy_screen = match (&approved, &target) { - (Ok(()), Ok(t)) if is_screen && !only_looks(&call.name) => screen_key(&t.place).and_then(|k| lease_screen(&mut screen_leases().lock().unwrap(), &k, bot_id, &job.via_name, Instant::now()).err().map(|e| (t.name.clone(), e))), + (Ok(()), Ok(t)) if is_screen && !only_looks(&call.name) => turn_screen_key(&job, bot_id, &t.place).and_then(|k| lease_screen(&mut screen_leases().lock().unwrap(), &k, bot_id, &job.via_name, Instant::now()).err().map(|e| (t.name.clone(), e))), _ => None, }; let approved = match busy_screen { @@ -3098,7 +3133,7 @@ pub fn spawn(job: Job, bot_id: u64, tx: Sender<(u64, StreamEvent)>, cancel: Arc< Err(e) => (e, false), } } else if is_screen && on_box { - match crate::cloudbox::computer_run(&call.name, &tools::args_of(&call.args)) { + match crate::cloudbox::on_screen(&box_screen, || crate::cloudbox::computer_run(&call.name, &tools::args_of(&call.args))) { Ok((out, img)) => { image = img; (out, true) @@ -3111,6 +3146,9 @@ pub fn spawn(job: Job, bot_id: u64, tx: Sender<(u64, StreamEvent)>, cancel: Arc< (out, ok) } else if is_web { web::run(&call.name, &call.args, &cancel) + } else if on_box { + // (A window a command opens goes to this turn's screen.) + crate::cloudbox::on_screen(&box_screen, || tools::run_on(&call.name, &call.args, t, &cancel, &ids)) } else { tools::run_on(&call.name, &call.args, t, &cancel, &ids) }; @@ -3340,6 +3378,21 @@ mod tests { assert!(lease_screen(&mut l, "local", 2, "Bot(支線)", t0 + SCREEN_IDLE).is_ok(), "idle long enough: its turn"); assert_eq!(screen_key(&tools::Place::Device { host: "h1".into(), dir: String::new() }).as_deref(), Some("device:h1")); assert_eq!(screen_key(&tools::Place::Ssh { target: "x".into(), dir: String::new() }), None); + // The bots' computer: a screen for each bot, so two bots there never wait for each other. + let a = screen_key(&tools::Place::Box { dir: crate::cloudbox::bot_dir(3) }).unwrap(); + let b = screen_key(&tools::Place::Box { dir: crate::cloudbox::bot_dir(4) }).unwrap(); + assert_ne!(a, b); + let mut l = Leases::new(); + let t0 = Instant::now(); + assert!(lease_screen(&mut l, &a, 3, "甲", t0).is_ok() && lease_screen(&mut l, &b, 4, "乙", t0).is_ok()); + // A 支線 works in its main bot's folder but on a temporary screen of its own there: it + // doesn't wait for its main line (on the person's computer it still does). + let place = tools::Place::Box { dir: crate::cloudbox::bot_dir(3) }; + let main = turn_screen_key(&test_job(), 3, &place).unwrap(); + let branch = turn_screen_key(&Job { home: 3, ..test_job() }, 57, &place).unwrap(); + assert_eq!((main.as_str(), branch.as_str()), ("box:bot3", "box:bot3-t57")); + assert!(lease_screen(&mut l, &branch, 57, "甲(支線)", t0).is_ok(), "beside its main line"); + assert_eq!(turn_screen_key(&Job { home: 3, ..test_job() }, 57, &tools::Place::Local { workdir: std::path::PathBuf::new() }).as_deref(), Some("local")); } #[test] diff --git a/src/app.rs b/src/app.rs index b7a7d64..4b162b3 100644 --- a/src/app.rs +++ b/src/app.rs @@ -25,6 +25,7 @@ use crate::theme::{Palette, DARK, LIGHT}; mod attach_ui; mod channels_ui; mod computers_ui; +mod screens_ui; mod chat_ui; mod files_ui; mod panel_ui; @@ -1566,6 +1567,10 @@ impl App { if speaker.is_some() { let names: Vec = conv.members.iter().filter_map(|m| self.state.bot(*m)).map(|x| x.name.clone()).collect(); sys.push_str(&format!("\n\n你在群組聊天「{}」裡,成員:{}。其他成員的發言以【名字】標示。使用者用「@名字」點名時,只有被點到的成員回答;沒點名就輪流回答。只回答你擅長的部分,補充不同的觀點,不要重複別人說過的;沒有要補充就簡短說一句。要某位成員接著回答(問它、請它補充或檢查),在回覆裡寫「@它的名字」,它會接在你後面說;不要 @ 自己,沒必要就別 @,來回幾次後就交還給使用者。", conv.name, names.join("、"))); + // 每個 Bot 一個螢幕: a member handing work on can't show its screen to the next. + if computers.iter().any(|c| matches!(c.place, crate::tools::Place::Box { .. })) { + sys.push_str("在 Bot 的電腦上每個成員有自己的螢幕和瀏覽器(登入一樣),看不到彼此開著的畫面和網頁:交棒給別的成員時,把網址、檔案路徑或頁面名稱寫進回覆,讓它自己打開;不要只說「我開好了」。"); + } } sys }, @@ -2117,6 +2122,7 @@ impl App { } self.last_tick = Instant::now(); self.tend_garden(); + self.tend_screens(); self.resume_interrupted(ctx); let now = crate::routines::now(); let mut fire = vec![]; @@ -5505,6 +5511,11 @@ impl App { let mut app = App::new(ctx, None); app.headless = true; app.asking = true; + // 連接器: the window connects them as it draws (there is no drawing here), so a question + // asked here had none of them. Connected before it starts. + for (name, why) in crate::mcp::sync(&app.state.mcp_servers) { + eprintln!("連接器「{name}」連不上:{why}"); + } let id = app.state.primary_bot; let start = app.state.bot(id).map(|b| b.messages.len()).unwrap_or(0); app.drafts.insert(id, text.to_string()); @@ -5853,6 +5864,7 @@ impl eframe::App for App { self.delete_dialog(ctx); self.delete_routine_dialog(ctx); self.routines_window(ctx); + self.screens_frame(ctx); self.rebuild_dialog(ctx); self.local_control_bar(ctx); self.teach_bar(ctx); @@ -6241,7 +6253,7 @@ fn system_prompt(b: &Bot, st: &State, computers: &[tools::Target], default_compu } // 支線: a copy of the bot doing one more thing alongside its main line. if b.branch_of != 0 { - s.push_str("\n\n你現在是一條支線:使用者用 /btw 開的分身,帶著同一段對話和記憶,跟主線(你的本尊)同時做對話最後交代的那件事。只做那件事,不要接手或重做主線正在做的事。做完用一段話寫清楚結果,它會原封不動送回主線的聊天。要使用者核准的步驟一樣會問他。同一個螢幕主線或別的 Bot 正在用時,那一步會被擋下:先做不用螢幕的部分、改用別台電腦,或晚點再試。不能再開支線,也不能改自己的設定。"); + s.push_str("\n\n你現在是一條支線:使用者用 /btw 開的分身,帶著同一段對話和記憶,跟主線(你的本尊)同時做對話最後交代的那件事。只做那件事,不要接手或重做主線正在做的事。做完用一段話寫清楚結果,它會原封不動送回主線的聊天。要使用者核准的步驟一樣會問他。在「Bot 的電腦」上你有自己的暫時螢幕和瀏覽器(登入從主線的瀏覽器複製過來,支線結束就關掉),不會跟主線搶,但看不到主線開著的網頁,要用就自己打開。在使用者的電腦上,同一個螢幕主線或別的 Bot 正在用時,那一步會被擋下:先做不用螢幕的部分、改用別台電腦,或晚點再試。不能再開支線,也不能改自己的設定。"); } // 個人檔案: what it is good at and what it leaves to others; then who the others are. // (Its soul — the 指示 — comes last, where it weighs most.) diff --git a/src/app/branch.rs b/src/app/branch.rs index 153c3bc..1c824e6 100644 --- a/src/app/branch.rs +++ b/src/app/branch.rs @@ -8,7 +8,9 @@ // same files or data, an account they'd both act on, a result the main line is waiting for). // No clash: it starts now. A clash: it waits for the main line's turn to end, saying why. // - While both work, a screen is one turn's at a time (agent::lease_screen): a step that would -// click on a screen another turn is using isn't run, and the bot is told who has it. +// click on a screen another turn is using isn't run, and the bot is told who has it. On the +// bots' computer a branch has a temporary screen of its own (cloudbox::branch_screen; its +// browser a copy of the main bot's), closed when the branch ends. // - Its report goes to the main line: into the turn that is running (it reads it at its next // step), or into the chat as the branch's words when nothing is running. // @@ -328,8 +330,15 @@ impl App { } } self.state.branch_bots.retain(|x| x.id != id); - // (Its background commands stop with it: nobody could reach them again.) + // (Its background commands stop with it: nobody could reach them again. So does its + // temporary screen on the bots' computer, with its copy of the browser.) self.forget_bot(id, false); + if !self.demo { + let key = crate::cloudbox::branch_screen(&crate::cloudbox::screen_of_bot(self.state.home_of(main)), id); + if !key.is_empty() { + std::thread::spawn(move || crate::cloudbox::close_screen(&key)); + } + } // The report: into the main line's running turn, or into the chat as the branch's words. if state != BranchState::Stopped { let text = match state { diff --git a/src/app/computers_ui.rs b/src/app/computers_ui.rs index 34136b3..734e881 100644 --- a/src/app/computers_ui.rs +++ b/src/app/computers_ui.rs @@ -61,6 +61,10 @@ pub struct ComputerUi { thumb_img: Arc>>, thumb_busy: Arc, thumb_at: Option, + /// Whose screen the picture is (每個 Bot 一個螢幕: the selected bot's own, else the shared one). + thumb_bot: u64, + /// 每個 Bot 一個螢幕: 全部螢幕, the member picked in a group chat, the small pictures. + pub(super) screens: super::screens_ui::ScreensUi, } /// (the Docker host has gVisor, the runtime the box runs on now) @@ -962,13 +966,19 @@ impl App { let brain = self.mir.on.then(|| self.state.remote.clone()); let running = if brain.is_some() { self.mir.box_state["running"].as_bool().unwrap_or(false) } else { cloudbox::run_state().is_running() }; let every = if running { 3 } else { 30 }; - if !self.cu.thumb_at.map(|t| t.elapsed().as_secs() < every).unwrap_or(false) && !self.cu.thumb_busy.swap(true, Ordering::SeqCst) { + // The selected bot's own screen (another bot picked: a new picture at once; in a group + // chat the member the person picked). + let bot = self.shown_bot(self.state.selected); + let fresh = self.cu.thumb_bot != bot; + if (fresh || !self.cu.thumb_at.map(|t| t.elapsed().as_secs() < every).unwrap_or(false)) && !self.cu.thumb_busy.swap(true, Ordering::SeqCst) { self.cu.thumb_at = Some(Instant::now()); + self.cu.thumb_bot = bot; + let key = self.screen_key_for(bot); let (slot, busy, c) = (self.cu.thumb_img.clone(), self.cu.thumb_busy.clone(), ctx.clone()); std::thread::spawn(move || { let img = match &brain { - Some(s) => crate::remote::sync_screen(s, true).ok().and_then(|b| image::load_from_memory(&b).ok()).map(|i| i.to_rgba8()), - None => cloudbox::thumbnail(320), + Some(s) => crate::remote::sync_screen(s, true, bot).ok().and_then(|b| image::load_from_memory(&b).ok()).map(|i| i.to_rgba8()), + None => cloudbox::thumbnail_of(&key, 320).or_else(|| cloudbox::thumbnail(320)), }; if let Some(img) = img { let size = [img.width() as usize, img.height() as usize]; @@ -990,13 +1000,19 @@ impl App { } fn open_screen(&mut self, control: bool) { + // 每個 Bot 一個螢幕: the selected bot's own screen (the shared one when it has none open). + self.open_screen_of(self.shown_bot(self.state.selected), control); + } + + /// `bot`'s own screen to watch (or take over), the shared one when it has none open. + pub(super) fn open_screen_of(&mut self, bot: u64, control: bool) { self.show_settings = false; - let name = self.state.bots.iter().find(|b| b.id == self.state.selected).map(|b| format!("{} 的電腦", b.name)).unwrap_or_else(|| "Bot 的電腦".into()); + let name = self.state.bot(bot).map(|b| format!("{} 的電腦", b.name)).unwrap_or_else(|| "Bot 的電腦".into()); if self.mir.on { let s = self.state.remote.clone(); self.box_task(move || { let ticket = crate::remote::screen_ticket(&s)?; - let url = format!("{}/screen#host={}&ticket={ticket}&name={}{}", s.relay_url.trim_end_matches('/'), s.brain_id, crate::httpd::url_encode(&name), if control { "&control=1" } else { "" }); + let url = format!("{}/screen#host={}&ticket={ticket}&name={}&bot={bot}{}", s.relay_url.trim_end_matches('/'), s.brain_id, crate::httpd::url_encode(&name), if control { "&control=1" } else { "" }); crate::preview::open_with_system(&url); Ok(String::new()) }); @@ -1005,8 +1021,10 @@ impl App { if self.demo { return; } + let key = self.screen_key_for(bot); + let key = if cloudbox::open_screens().iter().any(|(k, _)| *k == key) { key } else { String::new() }; self.box_task(move || { - let url = cloudbox::viewer_url(control)?; + let url = cloudbox::viewer_url_of(&key, control)?; crate::preview::open_with_system(&url); Ok(String::new()) }); @@ -1031,14 +1049,26 @@ impl App { self.hold_computer(false); } - fn hold_computer(&self, on: bool) { + fn hold_computer(&mut self, on: bool) { + // (The selected bot's screen: the bots on their own screens go on meanwhile. Given back + // is the screen taken, whichever bot is selected by then.) + let (bot, key) = match (on, self.cu.screens.held.take()) { + (false, Some(h)) => h, + _ => { + let bot = self.shown_bot(self.state.selected); + (bot, self.screen_key_for(bot)) + } + }; + if on { + self.cu.screens.held = Some((bot, key.clone())); + } if self.mir.on { let s = self.state.remote.clone(); std::thread::spawn(move || { - let _ = crate::remote::sync_post(&s, "screen", &serde_json::json!({"kind": "hold", "on": on})); + let _ = crate::remote::sync_post(&s, "screen", &serde_json::json!({"kind": "hold", "on": on, "bot": bot})); }); } else { - cloudbox::HELD_BY_PERSON.store(on, Ordering::SeqCst); + cloudbox::hold(&key, on); } } diff --git a/src/app/mirror_ui.rs b/src/app/mirror_ui.rs index 067434b..96c4a7f 100644 --- a/src/app/mirror_ui.rs +++ b/src/app/mirror_ui.rs @@ -655,7 +655,7 @@ impl App { out["mcp"] = self.mcp_state(); // The bots' computer lives here; a screen shows its state, not its own computer's. let run = crate::cloudbox::run_state(); - out["box"] = json!({"label": run.label(), "running": run.is_running(), "available": crate::cloudbox::available(), "busy": crate::cloudbox::is_busy()}); + out["box"] = json!({"label": run.label(), "running": run.is_running(), "available": crate::cloudbox::available(), "busy": crate::cloudbox::is_busy(), "screens": self.tiles_json()}); // Which computers each bot has (only the brain knows the account's other computers). out["computers"] = self .state diff --git a/src/app/panel_ui.rs b/src/app/panel_ui.rs index 88d5563..af70702 100644 --- a/src/app/panel_ui.rs +++ b/src/app/panel_ui.rs @@ -251,6 +251,17 @@ impl App { if let Some(n) = pick { self.set_computer(bot.id, &n); } + // 全部螢幕: every bot's own screen at once (when any is open). + let open = if available { self.screen_tiles().len() } else { 0 }; + if open > 0 { + let label = t("全部螢幕({n})").replace("{n}", &open.to_string()); + ui.horizontal(|ui| { + ui.add_space(10.0); + if ui.add(egui::Label::new(RichText::new(label).size(12.0).color(p.accent)).sense(egui::Sense::click())).on_hover_cursor(egui::CursorIcon::PointingHand).on_hover_text(t("每個 Bot 自己的螢幕,一次看")).clicked() { + self.cu.screens.open = true; + } + }); + } if view { if available { self.open_viewer(); @@ -265,8 +276,15 @@ impl App { let mut edit = false; let members: Vec = bot.members.iter().filter_map(|m| self.state.bot(*m).cloned()).collect(); let colors: Vec = members.iter().map(|b| self.bot_color(b)).collect(); + // 每個 Bot 一個螢幕: a member's own screen, small, when it has one open; a click + // shows it in the 電腦 card (again: back to the member speaking). + let pictures: Vec<_> = members.iter().map(|b| self.screen_tile(b.id)).collect(); + let shown = self.screen_key_for(self.shown_bot(bot.id)); + let keys: Vec = members.iter().map(|b| self.screen_key_for(b.id)).collect(); + let picked = self.cu.screens.pick.get(&bot.id).copied(); + let mut pick: Option> = None; panel_card(ui, p, |ui| { - for (b, col) in members.iter().zip(colors) { + for (((b, col), pic), key) in members.iter().zip(colors).zip(&pictures).zip(&keys) { let (rect, r) = ui.allocate_exact_size(vec2(ui.available_width(), ROW_H), egui::Sense::click()); if r.hovered() { ui.painter().rect_filled(rect, 9, p.hover); @@ -274,9 +292,30 @@ impl App { let mut child = ui.new_child(egui::UiBuilder::new().max_rect(rect.shrink2(vec2(10.0, 0.0))).layout(Layout::left_to_right(Align::Center))); avatar::avatar(&mut child, 20.0, &b.shape, col); child.label(RichText::new(&b.name).size(13.0).color(p.text)); + if let Some((tex, size)) = pic { + let at = egui::Rect::from_min_size(egui::pos2(rect.right() - 10.0 - 40.0, rect.center().y - 12.5), vec2(40.0, 25.0)); + let on = *key == shown; + let tr = ui.interact(at, egui::Id::unique(("member-screen", b.id)), egui::Sense::click()); + egui::Image::new((*tex, *size)).fit_to_exact_size(at.size()).corner_radius(4).paint_at(ui, at); + ui.painter().rect_stroke(at, 4, Stroke::new(if on { 2.0 } else { 1.0 }, if on { p.accent } else { p.border }), egui::StrokeKind::Inside); + let tip = if on { t("右側正在顯示「{name}」的螢幕") } else { t("在右側顯示「{name}」的螢幕") }.replace("{name}", &b.name); + if tr.on_hover_cursor(egui::CursorIcon::PointingHand).on_hover_text(tip).clicked() { + pick = Some(if picked == Some(b.id) { None } else { Some(b.id) }); + continue; + } + } edit |= r.clicked(); } }); + match pick { + Some(Some(m)) => { + self.cu.screens.pick.insert(bot.id, m); + } + Some(None) => { + self.cu.screens.pick.remove(&bot.id); + } + None => {} + } if edit { self.edit_bot = Some((bot.clone(), false)); } diff --git a/src/app/screens_ui.rs b/src/app/screens_ui.rs new file mode 100644 index 0000000..1970dc2 --- /dev/null +++ b/src/app/screens_ui.rs @@ -0,0 +1,279 @@ +// 每個 Bot 一個螢幕, as the window shows it (Grok Bot's split: one computer for the account, a +// screen of its own for each bot; cloudbox has the box's side). +// +// - The 電腦 card shows the selected bot's own screen. In a group chat it is the member speaking, +// unless the person picked a member (the small pictures in the 成員 card). +// - 全部螢幕: every screen open on the bots' computer, a small live picture each; a click opens +// that screen to watch or take over. +// - On the brain, every few seconds: which bot is on which screen (what viewers from the phone, +// a screen computer or the account server go by), the screens open now, and the idle ones closed. + +use super::*; +use crate::cloudbox; + +/// A bot's own screen on the bots' computer nobody used this long is closed (its browser too). +const SCREEN_IDLE_SECS: u64 = 600; +/// How often the small pictures of 全部螢幕 and the 成員 card are taken again. +const TILE_EVERY: u64 = 3; +/// Their width in pixels. +const TILE_W: u32 = 240; + +#[derive(Default)] +pub struct ScreensUi { + /// 全部螢幕 is open. + pub(super) open: bool, + /// In a group chat (its id), the member whose screen the 電腦 card shows: picked by the + /// person; none, the member speaking. + pub(super) pick: HashMap, + /// The screen the person took over (bot, screen), to give that one back. + pub(super) held: Option<(u64, String)>, + /// The small pictures, by bot. + tiles: HashMap, + fresh: Arc>>, + busy: Arc, + tiles_at: Option, + /// When the brain last told the box which bot is on which screen, looked at the screens open, + /// and swept idle ones. + mapped_at: Option, + listed_at: Option, + listing: Arc, + reaped_at: Option, +} + +/// One open screen: whose it is, and how long since a bot used it. +#[derive(Clone, Debug, PartialEq)] +pub(super) struct Tile { + pub bot: u64, + pub name: String, + pub idle: u64, +} + +impl App { + /// The screen to show for `bot_id` on the bots' computer: its own, by the folder it works in; + /// a 支線's temporary one; in a group chat the member speaking now, else the first member. + /// "" when it isn't a bot. + pub(super) fn screen_key_for(&self, bot_id: u64) -> String { + let Some(b) = self.state.bot(bot_id) else { return String::new() }; + if b.branch_of != 0 { + return cloudbox::branch_screen(&cloudbox::screen_of_bot(b.branch_of), bot_id); + } + let who = if b.members.is_empty() { + bot_id + } else { + b.messages.iter().rev().find(|m| m.role == Role::Assistant && m.author != 0).map(|m| m.author).or_else(|| b.members.first().copied()).unwrap_or(bot_id) + }; + cloudbox::screen_of_bot(self.state.home_of(who)) + } + + /// Whose screen the 電腦 card shows for `bot_id`: in a group chat the member the person + /// picked (when still a member), else `bot_id` itself (screen_key_for goes on from there). + pub(super) fn shown_bot(&self, bot_id: u64) -> u64 { + let members = self.state.bot(bot_id).map(|b| b.members.clone()).unwrap_or_default(); + self.cu.screens.pick.get(&bot_id).copied().filter(|m| members.contains(m)).unwrap_or(bot_id) + } + + /// On the brain: tell the box side which bot is on which screen, look at the screens open, + /// and close the screens no bot used for 10 minutes (their browsers too; the profiles stay). + pub(super) fn tend_screens(&mut self) { + if self.mir.on || self.demo { + return; + } + let s = &mut self.cu.screens; + if !s.mapped_at.is_some_and(|t| t.elapsed().as_secs() < 2) { + s.mapped_at = Some(Instant::now()); + let ids: Vec = self.state.bots.iter().chain(self.state.branch_bots.iter()).map(|b| b.id).collect(); + let map = ids.into_iter().map(|id| (id, self.screen_key_for(id))).collect(); + cloudbox::set_bot_screens(map); + } + // (A box that stopped has none open: the list empties without asking it.) + let s = &mut self.cu.screens; + if !s.listed_at.is_some_and(|t| t.elapsed().as_secs() < 5) && !s.listing.swap(true, Ordering::SeqCst) { + s.listed_at = Some(Instant::now()); + let busy = s.listing.clone(); + std::thread::spawn(move || { + cloudbox::refresh_open_screens(); + busy.store(false, Ordering::SeqCst); + }); + } + if !s.reaped_at.is_some_and(|t| t.elapsed().as_secs() < 60) && cloudbox::run_state().is_running() { + s.reaped_at = Some(Instant::now()); + std::thread::spawn(|| cloudbox::reap_screens(SCREEN_IDLE_SECS)); + } + } + + /// The screens open on the bots' computer here, by bot (a 支線's under its bot's name). + pub(super) fn local_tiles(&self) -> Vec { + cloudbox::open_screens_seen() + .into_iter() + .filter_map(|(key, idle)| { + let (own, branch) = cloudbox::bot_of_screen(&key)?; + let (bot, name) = if branch != 0 { + (branch, format!("{}(支線)", self.state.bot(branch)?.name)) + } else { + (own, self.state.bots.iter().find(|b| b.id == own && b.members.is_empty())?.name.clone()) + }; + Some(Tile { bot, name, idle }) + }) + .collect() + } + + /// The screens open on the bots' computer (on a screen of a brain: the brain's, as it said). + pub(super) fn screen_tiles(&self) -> Vec { + if !self.mir.on { + return self.local_tiles(); + } + self.mir.box_state["screens"] + .as_array() + .map(|a| a.iter().filter_map(|t| Some(Tile { bot: t["bot"].as_u64()?, name: t["name"].as_str()?.to_string(), idle: t["idle"].as_u64().unwrap_or(0) })).collect()) + .unwrap_or_default() + } + + /// What a screen of this brain is told about the screens open (its 全部螢幕). + pub(super) fn tiles_json(&self) -> serde_json::Value { + self.local_tiles().iter().map(|t| serde_json::json!({"bot": t.bot, "name": t.name, "idle": t.idle})).collect() + } + + /// The small picture of `bot`'s screen, when there is one (screens_frame keeps it fresh). + pub(super) fn screen_tile(&self, bot: u64) -> Option<(egui::TextureId, egui::Vec2)> { + self.cu.screens.tiles.get(&bot).map(|t| (t.id(), t.size_vec2())) + } + + /// Pictures of the bots in `wanted` taken again every few seconds (in the background; on a + /// screen of a brain, from it). + fn refresh_tiles(&mut self, ctx: &egui::Context, wanted: &[u64]) { + let s = &mut self.cu.screens; + for (bot, img) in std::mem::take(&mut *s.fresh.lock().unwrap()) { + match s.tiles.get_mut(&bot) { + Some(t) => t.set(img, egui::TextureOptions::LINEAR), + None => { + s.tiles.insert(bot, ctx.load_texture(format!("screen-tile-{bot}"), img, egui::TextureOptions::LINEAR)); + } + } + } + if wanted.is_empty() { + return; + } + ctx.request_repaint_after(std::time::Duration::from_secs(TILE_EVERY)); + if s.tiles_at.is_some_and(|t| t.elapsed().as_secs() < TILE_EVERY) || s.busy.swap(true, Ordering::SeqCst) { + return; + } + s.tiles_at = Some(Instant::now()); + let (fresh, busy, c) = (s.fresh.clone(), s.busy.clone(), ctx.clone()); + let brain = self.mir.on.then(|| self.state.remote.clone()); + let jobs: Vec<(u64, String)> = wanted.iter().map(|&b| (b, self.screen_key_for(b))).collect(); + std::thread::spawn(move || { + for (bot, key) in jobs { + let img = match &brain { + Some(s) => crate::remote::sync_screen(s, true, bot).ok().and_then(|b| image::load_from_memory(&b).ok()).map(|i| i.to_rgba8()), + None if key.is_empty() => None, + None => cloudbox::thumbnail_of(&key, TILE_W), + }; + if let Some(img) = img { + let size = [img.width() as usize, img.height() as usize]; + fresh.lock().unwrap().push((bot, egui::ColorImage::from_rgba_unmultiplied(size, img.as_raw()))); + c.request_repaint(); + } + } + busy.store(false, Ordering::SeqCst); + }); + } + + /// Every frame: the pictures shown now (全部螢幕, the 成員 card of the group chat open) kept + /// fresh, and 全部螢幕 itself. + pub(super) fn screens_frame(&mut self, ctx: &egui::Context) { + let tiles = self.screen_tiles(); + let mut wanted: Vec = vec![]; + if self.cu.screens.open { + wanted.extend(tiles.iter().map(|t| t.bot)); + } + if let Some(b) = self.state.bot(self.state.selected).filter(|b| !b.members.is_empty()) { + wanted.extend(b.members.iter().filter(|m| tiles.iter().any(|t| t.bot == **m))); + } + wanted.sort_unstable(); + wanted.dedup(); + self.refresh_tiles(ctx, &wanted); + if self.cu.screens.open { + self.screens_window(ctx, &tiles); + } + } + + /// 全部螢幕: a small live picture of each screen open; a click opens it. + fn screens_window(&mut self, ctx: &egui::Context, tiles: &[Tile]) { + let p = self.pal; + let mut view: Option = None; + let pictures: Vec> = tiles.iter().map(|t| self.screen_tile(t.bot)).collect(); + let dismissed = dialog(ctx, "all-screens", &t("全部螢幕"), 560.0, true, p, |ui| { + if tiles.is_empty() { + ui.label(RichText::new(t("現在沒有 Bot 開著自己的螢幕。Bot 第一次看畫面或用瀏覽器時才會開,閒置 10 分鐘自動關掉。")).color(p.text2)); + return; + } + hint(ui, t("每個 Bot 在 Bot 的電腦上有自己的螢幕,互不干擾。點一格看它的畫面,也可以在那裡接手。"), p); + ui.add_space(6.0); + let w = 256.0; + let cols = ((ui.available_width() + 12.0) / (w + 12.0)).floor().max(1.0) as usize; + egui::Grid::new("all-screens-grid").spacing(vec2(12.0, 12.0)).show(ui, |ui| { + for (i, (tile, pic)) in tiles.iter().zip(&pictures).enumerate() { + let (rect, r) = ui.allocate_exact_size(vec2(w, w * 10.0 / 16.0 + 40.0), egui::Sense::click()); + let shot = egui::Rect::from_min_size(rect.min, vec2(w, w * 10.0 / 16.0)); + match pic { + Some((tex, size)) => egui::Image::new((*tex, *size)).fit_to_exact_size(shot.size()).corner_radius(8).paint_at(ui, shot), + None => { + ui.painter().rect_filled(shot, 8, p.active); + } + } + ui.painter().rect_stroke(shot, 8, Stroke::new(if r.hovered() { 2.0 } else { 1.0 }, if r.hovered() { p.accent } else { p.border }), egui::StrokeKind::Inside); + let when = if tile.idle < 60 { t("剛剛還在用") } else { t("閒置 {n} 分鐘").replace("{n}", &(tile.idle / 60).to_string()) }; + ui.painter().text(shot.left_bottom() + vec2(2.0, 8.0), egui::Align2::LEFT_TOP, super::sidebar_ui::shorten_width(ui, &tile.name, w - 4.0, 13.0), egui::FontId::proportional(13.0), p.text); + ui.painter().text(shot.left_bottom() + vec2(2.0, 25.0), egui::Align2::LEFT_TOP, when, egui::FontId::proportional(11.5), p.text3); + if r.on_hover_cursor(egui::CursorIcon::PointingHand).on_hover_text(t("看「{name}」的螢幕,也可以取得控制權自己操作").replace("{name}", &tile.name)).clicked() { + view = Some(tile.bot); + } + if (i + 1) % cols == 0 { + ui.end_row(); + } + } + }); + }); + if dismissed { + self.cu.screens.open = false; + } + if let Some(bot) = view { + self.open_screen_of(bot, false); + } + } +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn a_branch_and_a_picked_member_have_their_own_screens() { + let ctx = egui::Context::default(); + let mut app = super::super::App::new(&ctx, Some(std::env::temp_dir().join("anybot-screens-ui.png"))); + let (a, b) = (app.state.bots[0].id, app.state.bots[1].id); + let mut branch = app.state.bot(a).cloned().unwrap(); + branch.id = 9_001; + branch.branch_of = a; + app.state.branch_bots.push(branch); + assert_eq!(app.screen_key_for(a), format!("bot{a}")); + assert_eq!(app.screen_key_for(9_001), format!("bot{a}-t9001"), "a branch beside its main bot"); + assert_eq!(cloudbox::bot_of_screen(&format!("bot{a}-t9001")), Some((a, 9_001))); + assert_eq!(cloudbox::bot_of_screen(&format!("bot{b}")), Some((b, 0))); + assert_eq!(cloudbox::bot_of_screen("main"), None); + // A group chat shows the member speaking; one the person picked instead. + let mut group = app.state.bots[0].clone(); + group.id = 9_002; + group.members = vec![a, b]; + group.messages = vec![Message { author: b, ..Message::assistant("我來", "") }]; + app.state.bots.push(group); + let g = 9_002; + assert_eq!(app.screen_key_for(g), format!("bot{b}")); + assert_eq!(app.shown_bot(g), g); + app.cu.screens.pick.insert(g, a); + assert_eq!(app.screen_key_for(app.shown_bot(g)), format!("bot{a}")); + // (Not a member any more: back to the one speaking.) + app.state.bot_mut(g).unwrap().members.retain(|m| *m != a); + assert_eq!(app.shown_bot(g), g); + } +} diff --git a/src/browser.rs b/src/browser.rs index def0b9e..a4cef93 100644 --- a/src/browser.rs +++ b/src/browser.rs @@ -583,6 +583,21 @@ pub fn wait_loaded(profile: Option<&str>, max_ms: u64) -> bool { // ---------- the tools ---------- +/// The option a select names: `option`, or what models trained on Playwright give instead +/// (`value`, `values`). It used to read only `option`, and with `value` it chose the empty +/// 「請選擇」 and said 「已選「」」: the form went out without its city. +fn select_option(args: &Value) -> String { + let o = s(args, "option"); + if !o.is_empty() { + return o; + } + let v = s(args, "value"); + if !v.is_empty() { + return v; + } + args["values"].as_array().and_then(|a| a.first()).map(|v| v.as_str().map(String::from).unwrap_or_else(|| v.to_string())).unwrap_or_default().trim().to_string() +} + fn s(args: &Value, k: &str) -> String { args.get(k).map(|v| v.as_str().map(String::from).unwrap_or_else(|| if v.is_null() { String::new() } else { v.to_string() })).unwrap_or_default().trim().to_string() } @@ -655,7 +670,7 @@ pub fn describe(name: &str, args: &str) -> String { let target = if !s(&v, "ref").is_empty() { format!("[{}]", s(&v, "ref")) } else { s(&v, "text") }; match name { "browser_type" => format!("{target} ← {}", s(&v, "value").chars().take(40).collect::()), - "browser_select" => format!("{target} → {}", s(&v, "option")), + "browser_select" => format!("{target} → {}", select_option(&v)), "browser_press" => s(&v, "key"), "browser_scroll" => if target.is_empty() { s(&v, "direction") } else { target }, "browser_wait" => if s(&v, "text").is_empty() { format!("{} 秒", s(&v, "seconds")) } else { format!("等「{}」", s(&v, "text")) }, @@ -730,7 +745,7 @@ actions: - dialog {accept, text}: answer a pop-up dialog the page opened - eval {script}: short read-only JavaScript for data the other actions can't reach; it can't send requests, navigate or submit (site APIs get accounts flagged) - sent {profile, days}: what an account already sent through this browser — AnyBot's own record (which posts, which accounts it answered, kept 60 days); much cheaper than reading a site's own replies page to the end. Sending to a post the same account already answered is refused anyway -- fill {kind: login|card|contact, id, site, submit}: sign in / pay card / address from the person's 保險庫 — you never see the secret; the person approves every use (login_id/card_id/contact_id come from vault_list; default login: the current site's)", +- fill {kind: login|card|contact, id, site, submit}: sign in / pay card / address from the person's 保險庫 (not for ordinary fields: those are type/select) — you never see the secret; the person approves every use (login_id/card_id/contact_id come from vault_list; default login: the current site's)", "parameters": {"type": "object", "properties": { "action": {"type": "string", "enum": ["open","read","elements","find","table","screenshot","click","hover","type","press","select","scroll","wait","tabs","back","upload","download","pdf","dialog","eval","sent","profiles","fill"]}, "url": {"type": "string"}, @@ -748,7 +763,7 @@ actions: "append": {"type": "boolean", "description": "type: keep what's in the field"}, "submit": {"type": "boolean", "description": "type/fill: press Enter / sign in afterwards"}, "key": {"type": "string", "description": "press: Enter, Tab, Escape, ctrl+a…"}, - "option": {"type": "string", "description": "select: the option's visible text"}, + "option": {"type": "string", "description": "select: the option's visible text (value works too)"}, "direction": {"type": "string", "enum": ["down", "up", "top", "bottom", "back", "forward", "reload"], "description": "scroll: down/up/top/bottom; back: back/forward/reload"}, "seconds": {"type": "number"}, "days": {"type": "integer", "description": "sent: how far back (default 30, up to 60)"}, @@ -802,6 +817,13 @@ pub fn expand_call(c: &mut crate::model::ToolCall) { let mut name = action.to_string(); if let Some(o) = v.as_object_mut() { o.remove("action"); + // 「fill」 with a control on the page and the words for it is Playwright's fill (type + // into a field), what models trained on it mean more often than the 保險庫: it went to + // the vault, was refused, and the bot tried again and again (the form never went out). + let on_page = (o.contains_key("ref") || o.contains_key("text")) && !["kind", "id", "site"].iter().any(|k| o.contains_key(*k)); + if name == "browser_fill_login" && on_page { + name = if o.contains_key("option") || o.contains_key("values") { "browser_select" } else { "browser_type" }.to_string(); + } if name == "browser_fill_login" { // fill {kind, id} names the exact vault tool and its id field. let kind = o.remove("kind").and_then(|k| k.as_str().map(|s| s.to_string())).unwrap_or_else(|| "login".into()); @@ -855,6 +877,12 @@ pub fn run(name: &str, args: &Value) -> Result<(String, Option), String> } let mut tab = Tab::current(profile)?; let r = (|| -> Result<(String, Option), String> { + // Typing into a dropdown (a +
商品分潤率
手機殼8%
乳液12%

點擊 0

匯出報表