合併: 每個 Bot 一個螢幕、電腦操作量測時找到的 bug 修正、量測腳本每題從乾淨的狀態開始

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01Uirha4mzWbjJAWAsDVuBun
This commit is contained in:
王性驊 2026-11-15 16:12:09 +08:00
commit 84554b5b4c
27 changed files with 1357 additions and 154 deletions

View File

@ -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] --out results.json [--tasks T1,T4] [--runs 1]
""" """
import argparse, json, os, re, shutil, subprocess, sys, time 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", "") BOX = os.environ.get("ANYBOT_BOX_NAME", "")
VOL = os.environ.get("ANYBOT_BOX_VOLUME", "") 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}, "check": lambda dh, ans: "7006652" in digits(ans) and dx("pgrep -x galculator", dh)[0] == 0},
{"id": "T3", "route": "screen-or-browser", "name": "Chromium 預設搜尋引擎", {"id": "T3", "route": "screen-or-browser", "name": "Chromium 預設搜尋引擎",
# Back to Chromium's own default (an earlier run may have set Bing): browser closed, the # Back to Chromium's own default (an earlier run may have set Bing): browser closed, the
# saved choice removed from its preferences. # saved choice removed from its preferences, and no policy file forcing one (a bot once
"setup": "pkill -f '^/usr/lib/chromium/chromium' ; sleep 2; python3 - <<'PY'\n" # wrote /etc/chromium/policies/managed/default_search.json instead: it outlives the task).
"import json\nfor p in ['/home/bot/.config/anybot-profile/Default/Preferences', '/home/bot/.config/chromium/Default/Preferences']:\n" "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" " 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", " 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。", "ask": "把你電腦上 Chromium 瀏覽器的預設搜尋引擎改成 Bing。",
# Chromium writes its preferences up to ~10 s after a change: look for 15 s. # Chromium writes its preferences up to ~10 s after a change: look for 15 s. The desktop'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]}, # 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": "照片依月份分類", {"id": "T4", "route": "command", "name": "照片依月份分類",
"setup": "rm -rf ~/bench/photos && mkdir -p ~/bench/photos && cd ~/bench/photos && " "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; " "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("--runs", type=int, default=1)
ap.add_argument("--secs", type=int, default=600) 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("--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() 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": 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") 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")) 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 [] 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)) env = dict(os.environ, ANYBOT_DATA_DIR=a.data, ANYBOT_ASK_SECS=str(a.secs))
kept_skills = [] 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 run in range(a.runs):
for t in tasks: for t in tasks:
print(f"== {t['id']} {t['name']} (run {run + 1})", flush=True) 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. # 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. # 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") 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) print(" setup:", out.strip().replace("\n", " ")[-160:], flush=True)
shutil.copyfile(a.template, os.path.join(a.data, "state.json")) shutil.copyfile(a.template, os.path.join(a.data, "state.json"))
os.chmod(os.path.join(a.data, "state.json"), 0o600) os.chmod(os.path.join(a.data, "state.json"), 0o600)
# Each chat is a file of its own (data/chats/bot-<id>.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: if a.keep_skills and kept_skills:
st0 = json.load(open(os.path.join(a.data, "state.json"))) st0 = json.load(open(os.path.join(a.data, "state.json")))
st0["skills"] = kept_skills st0["skills"] = kept_skills
@ -331,7 +471,9 @@ def main():
st = json.load(open(os.path.join(a.data, "state.json"))) st = json.load(open(os.path.join(a.data, "state.json")))
if a.keep_skills: if a.keep_skills:
kept_skills = st.get("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) r = analyze(msgs)
try: try:
ok = bool(t["check"](a.docker_host, r.get("answer", ""))) ok = bool(t["check"](a.docker_host, r.get("answer", "")))
@ -340,12 +482,15 @@ def main():
r["check_error"] = str(e) r["check_error"] = str(e)
r["skills"] = [{"name": k.get("name"), "steps": len(k.get("steps", []))} for k in st.get("skills", [])] 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["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:]}) "process_s": wall, "at": time.strftime("%Y-%m-%d %H:%M"), "log_tail": log[-1500:]})
results.append(r) results.append(r)
json.dump(results, open(a.out, "w"), ensure_ascii=False, indent=1) 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 " 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__": if __name__ == "__main__":

View File

@ -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 start.sh /usr/local/bin/anybot-box-start
COPY a11y /usr/local/bin/anybot-a11y COPY a11y /usr/local/bin/anybot-a11y
COPY browser /usr/local/bin/anybot-browser COPY browser /usr/local/bin/anybot-browser
COPY screen /usr/local/bin/anybot-screen
COPY fluxbox-init /etc/anybot/fluxbox-init COPY fluxbox-init /etc/anybot/fluxbox-init
COPY overlay /etc/anybot/overlay COPY overlay /etc/anybot/overlay
COPY Xresources /etc/anybot/Xresources COPY Xresources /etc/anybot/Xresources
COPY menu /etc/anybot/menu 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 # 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 # 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 # 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. # 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 ENV DISPLAY=:1 SCREEN_SIZE=1280x800x24 GTK_MODULES=gail:atk-bridge GTK_A11Y=atspi GNOME_ACCESSIBILITY=1 NO_AT_BRIDGE=0
EXPOSE 6080 EXPOSE 6080
LABEL anybot.box.version="9" LABEL anybot.box.version="10"
ENTRYPOINT ["/usr/bin/tini", "--"] ENTRYPOINT ["/usr/bin/tini", "--"]
CMD ["/usr/local/bin/anybot-box-start"] CMD ["/usr/local/bin/anybot-box-start"]

View File

@ -16,7 +16,39 @@ fi
# browser tools opened), so a site could be logged in in one and not the other. Chromium's own # 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. # 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 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=<key> 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 (<key>-t<n>) 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 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" mkdir -p /home/bot/.config/chromium && ln -s /home/bot/.config/chromium "$PROFILE"
else else
@ -28,14 +60,14 @@ fi
# ANYBOT_BOX_SANDBOX=1 — Chromium's own sandbox works there, so keep it as a second wall. # ANYBOT_BOX_SANDBOX=1 — Chromium's own sandbox works there, so keep it as a second wall.
SANDBOX=(--no-sandbox --test-type) SANDBOX=(--no-sandbox --test-type)
[ "${ANYBOT_BOX_SANDBOX:-0}" = 1 ] && SANDBOX=() [ "${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 --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 --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 --no-first-run --no-default-browser-check --disable-session-crashed-bubble --hide-crash-restore-bubble
--disable-features=TranslateUI --start-maximized) --disable-features=TranslateUI --start-maximized)
# Two starts in the same second (the bot and the person) would both find no browser and fight # 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. # 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 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 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 flock -u 9
@ -45,8 +77,8 @@ fi
rm -f "$PROFILE"/SingletonLock "$PROFILE"/SingletonSocket "$PROFILE"/SingletonCookie 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 # (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.) # 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 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 sleep 0.25
done done

147
box/screen Executable file
View File

@ -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 <key> the screen of <key> (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 <key> 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 <secs> 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<key> ("main" is the shared screen).
# <key>-t<n> is a temporary screen (a 支線's, beside its main bot <key>): its browser starts as a
# copy of <key>'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

View File

@ -14,6 +14,8 @@ GEOM="${SCREEN_SIZE%x*}"
if [ -n "${VNC_PASSWORD:-}" ]; then if [ -n "${VNC_PASSWORD:-}" ]; then
mkdir -p /home/bot/.vnc mkdir -p /home/bot/.vnc
printf '%s\n' "$VNC_PASSWORD" | vncpasswd -f > /home/bot/.vnc/passwd && chmod 600 /home/bot/.vnc/passwd 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" VNC_SEC="-SecurityTypes VncAuth -rfbauth /home/bot/.vnc/passwd"
else else
VNC_SEC="-SecurityTypes None" 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 &" 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') & (sleep 1.5; xsetroot -display :1 -solid '#2b2f36') &
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<key>.
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=$! WEBSOCKIFY_PID=$!
# Say ready only once the viewer's port listens: the app opens noVNC on this flag, and a too # 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. # early file meant the first viewer load 404'd.

View File

@ -11,6 +11,7 @@ Bot 用 AnyBot 自己的瀏覽器上網、登入網站、點按、打字、送
- 打字:`type` 的換行會整段放進去(像貼上),結果會說欄位現在裝了什麼。 - 打字:`type` 的換行會整段放進去(像貼上),結果會說欄位現在裝了什麼。
- 間隔:`wait` 加 `after_send: true`,從上一次送出起算(最多 900 秒),下一則可以先打好再等。 - 間隔:`wait` 加 `after_send: true`,從上一次送出起算(最多 900 秒),下一則可以先打好再等。
- 發布關卡(Bot 自己的瀏覽器送出時):送出前讀頁面,看是哪個帳號、回哪一篇;同一帳號回過同一篇就擋下(已送帳本,記 60 天);發布前檢查請另一個模型看過文字;送出後重讀頁面,確認文字出現、抓留言網址,結果寫「【系統】已送出…」。 - 發布關卡(Bot 自己的瀏覽器送出時):送出前讀頁面,看是哪個帳號、回哪一篇;同一帳號回過同一篇就擋下(已送帳本,記 60 天);發布前檢查請另一個模型看過文字;送出後重讀頁面,確認文字出現、抓留言網址,結果寫「【系統】已送出…」。
- Bot 自己的電腦上:每個 Bot 在自己的螢幕上有自己的瀏覽器;第一次開時從共用的那份複製登入過來,之後各自登入、互不影響。支線的瀏覽器從主線那份複製,支線結束就刪掉。
- 做完就關掉瀏覽器:一輪結束就把它用過的視窗關掉(別的 Bot 還在用的不關)。 - 做完就關掉瀏覽器:一輪結束就把它用過的視窗關掉(別的 Bot 還在用的不關)。
## 使用者怎麼到 ## 使用者怎麼到
@ -29,6 +30,8 @@ Bot 用 AnyBot 自己的瀏覽器上網、登入網站、點按、打字、送
- 同一個網站在不同電腦、不同設定檔的登入不共用;沒帶 `profile` 會用到別的設定檔。 - 同一個網站在不同電腦、不同設定檔的登入不共用;沒帶 `profile` 會用到別的設定檔。
- 使用者自己的 Firefox 設定檔,如果他已經用平常的方式開著,要先請他關掉那個視窗,AnyBot 才開得起來。 - 使用者自己的 Firefox 設定檔,如果他已經用平常的方式開著,要先請他關掉那個視窗,AnyBot 才開得起來。
- 一模一樣的按鈕(例如每篇貼文都有的「回覆」)在清單裡只列一次;要點第二篇的,先 `open` 那篇貼文的網址再點。 - 一模一樣的按鈕(例如每篇貼文都有的「回覆」)在清單裡只列一次;要點第二篇的,先 `open` 那篇貼文的網址再點。
- 下拉選單用 `select`,`option` 填選項上看得到的字(給 `value` 也行,對下拉選單 `type` 也會改成選選項);什麼都沒給會報錯。
- `fill` 是保險庫的填入;指著頁面上一個欄位(有 `ref`/`text`、沒有 kind/id/site)時當成 `type`(有 `option` 時當 `select`),不會跑去保險庫。
- `eval` 只能讀頁面:不能發請求、讀 cookie 或儲存、送出表單、換頁(會被拒絕);直接呼叫網站內部 API 會被當成機器人。 - `eval` 只能讀頁面:不能發請求、讀 cookie 或儲存、送出表單、換頁(會被拒絕);直接呼叫網站內部 API 會被當成機器人。
- 雲端中繼資料位址永遠打不開;本機或內部網路的網址要使用者允許(直接操作模式除外)。 - 雲端中繼資料位址永遠打不開;本機或內部網路的網址要使用者允許(直接操作模式除外)。
- 發布關卡、已送帳本、送出後確認只管 AnyBot 自己的瀏覽器;用螢幕操作送出的,只能從步驟推算。頁面看不出回哪一篇時,只擋 24 小時內同一頁一模一樣的內容。 - 發布關卡、已送帳本、送出後確認只管 AnyBot 自己的瀏覽器;用螢幕操作送出的,只能從步驟推算。頁面看不出回哪一篇時,只擋 24 小時內同一頁一模一樣的內容。

View File

@ -5,7 +5,7 @@
## 子功能 ## 子功能
- 四種電腦,每台都用自己的名字稱呼: - 四種電腦,每台都用自己的名字稱呼:
- Bot 自己的電腦(「<Bot 名字> 的電腦」):一台 Linux(Debian,有桌面和 Chromium,可以 sudo 裝套件),跑在 Docker 裡,所有 Bot 共用、各有自己的資料夾,一直開著。沒有 Docker 時退回成一個封閉的資料夾,沒有桌面。 - Bot 自己的電腦(「<Bot 名字> 的電腦」):一台 Linux(Debian,有桌面和 Chromium,可以 sudo 裝套件),跑在 Docker 裡,所有 Bot 共用一台,各有自己的資料夾、自己的螢幕和自己的瀏覽器(見 [screen](screen.md)),一直開著。沒有 Docker 時退回成一個封閉的資料夾,沒有桌面。
- 這台電腦(AnyBot 開著的這台,名字可以改):從 Bot 的「起始資料夾」開始。大腦放在伺服器上時,伺服器本身不在清單裡。 - 這台電腦(AnyBot 開著的這台,名字可以改):從 Bot 的「起始資料夾」開始。大腦放在伺服器上時,伺服器本身不在清單裡。
- SSH 電腦:自己加的,一個名稱加一個位址(例如 me@studio.local)。 - SSH 電腦:自己加的,一個名稱加一個位址(例如 me@studio.local)。
- 帳號裡的其他電腦:登入同一個帳號、打開「讓帳號裡的其他電腦使用這台」、而且現在在線上的 AnyBot(螢幕電腦、手腳電腦),經過帳號伺服器操作檔案、指令、瀏覽器、看畫面和點擊。 - 帳號裡的其他電腦:登入同一個帳號、打開「讓帳號裡的其他電腦使用這台」、而且現在在線上的 AnyBot(螢幕電腦、手腳電腦),經過帳號伺服器操作檔案、指令、瀏覽器、看畫面和點擊。

View File

@ -33,3 +33,5 @@
- 要登入帳號(OAuth)的連接器 AnyBot 還不支援,連線時狀態會說;它若也收 API 金鑰,填在「標頭」。公用市集裡舊式 SSE 的會標「舊式 SSE 連線,AnyBot 還不支援」。 - 要登入帳號(OAuth)的連接器 AnyBot 還不支援,連線時狀態會說;它若也收 API 金鑰,填在「標頭」。公用市集裡舊式 SSE 的會標「舊式 SSE 連線,AnyBot 還不支援」。
- 公用市集只列用網址連的;要在大腦上跑 npm/PyPI 套件的不列。本機連接器要大腦那台裝了 Node.js(npx)或 uv(uvx)。 - 公用市集只列用網址連的;要在大腦上跑 npm/PyPI 套件的不列。本機連接器要大腦那台裝了 Node.js(npx)或 uv(uvx)。
- 在螢幕上改了指令或網址,大腦會清掉密碼(免得送到新的位址),要重新填。 - 在螢幕上改了指令或網址,大腦會清掉密碼(免得送到新的位址),要重新填。
- 參數裡的資料夾在這台找不到(在別台電腦設定的),連接器不連,狀態寫「這台電腦上沒有…」;指令是 `docker`、`ssh` 這類在別處執行的,不檢查(路徑在容器或那台主機上)。
- `anybot --ask` 沒有視窗,也會先連好連接器再開始。

View File

@ -29,7 +29,7 @@ Bot 在它能用的電腦上跑指令、讀寫和搜尋檔案、開背景指令
- 機密檔案一律不能讀、改、傳、打開或發佈:AnyBot 自己的資料資料夾、.git、.ssh、.gnupg、.aws、Keychains、.env、.pem、.key、id_rsa 開頭的檔案等。 - 機密檔案一律不能讀、改、傳、打開或發佈:AnyBot 自己的資料資料夾、.git、.ssh、.gnupg、.aws、Keychains、.env、.pem、.key、id_rsa 開頭的檔案等。
- 在這台電腦上:工作資料夾外讀東西先問(可以一律允許);改檔案會問,工作資料夾外的每次都問、不能一律允許;指令除了唯讀的都會問;sudo、rm -rf /、mkfs、dd、shutdown 這類一律拒絕。完整規則見 [safety](safety.md)。 - 在這台電腦上:工作資料夾外讀東西先問(可以一律允許);改檔案會問,工作資料夾外的每次都問、不能一律允許;指令除了唯讀的都會問;sudo、rm -rf /、mkfs、dd、shutdown 這類一律拒絕。完整規則見 [safety](safety.md)。
- 在 Bot 自己的電腦上,指令和檔案都不用問(可以 sudo,但後面接的一律拒絕指令照樣擋);檔案工具只碰得到它自己的資料夾。 - 在 Bot 自己的電腦上,指令和檔案都不用問(可以 sudo,但後面接的一律拒絕指令照樣擋);檔案工具只碰得到它自己的資料夾。有 sudo 的指令整條用 root 跑,跑完它在 Bot 家目錄裡新留下的檔案會交還給 Bot(不只它的資料夾)。
- SSH 電腦和帳號裡的其他電腦:讀不用問,改檔案和會改變東西的指令會問。 - SSH 電腦和帳號裡的其他電腦:讀不用問,改檔案和會改變東西的指令會問。
- 開互動的 shell(bash、zsh、PowerShell…)每次都問、沒有一律允許:之後在裡面打的指令不會再一條一條檢查。 - 開互動的 shell(bash、zsh、PowerShell…)每次都問、沒有一律允許:之後在裡面打的指令不會再一條一條檢查。
- 一般指令的輸入是關的,`write_terminal` 打不進去:要互動就用 interactive 重跑,或用參數答掉(-y、--yes)。 - 一般指令的輸入是關的,`write_terminal` 打不進去:要互動就用 interactive 重跑,或用參數答掉(-y、--yes)。

View File

@ -11,7 +11,8 @@ Bot 用一個 `computer` 工具看一台電腦的螢幕、動滑鼠和鍵盤:
- `intent`:系統捷徑(音量、Wi-Fi、鎖螢幕、深淺色、清空垃圾桶,Mac 還有退出磁碟)一步做完。電腦現況列了「系統捷徑」才有:macOS 和 Linux 桌面有,Windows 和 Bot 自己的電腦沒有。 - `intent`:系統捷徑(音量、Wi-Fi、鎖螢幕、深淺色、清空垃圾桶,Mac 還有退出磁碟)一步做完。電腦現況列了「系統捷徑」才有:macOS 和 Linux 桌面有,Windows 和 Bot 自己的電腦沒有。
- 交給使用者:`hand_over_computer` 在聊天放一張「需要處理」卡和那台電腦的畫面,使用者做完按「我完成了」或「跳過」。 - 交給使用者:`hand_over_computer` 在聊天放一張「需要處理」卡和那台電腦的畫面,使用者做完按「我完成了」或「跳過」。
- 示範教學(macOS、Linux X11):使用者自己做一次,AnyBot 記成步驟和每一步的畫面;Bot 用 `view_demo_step` 看某一步當時的畫面。 - 示範教學(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 不用問就能操作的 App,可以逐一移除;「整個螢幕(看不出是哪個 App 時)」就是 `computer:control`。
- Bot 在這台電腦上動滑鼠鍵盤時,螢幕上方有「{Bot} 正在操作你的電腦」:按「取得控制權」Bot 先停手(變成「你正在操作,Bot 已暫停」,按「交還給 Bot」還它);按「停止」停掉那一輪。 - Bot 在這台電腦上動滑鼠鍵盤時,螢幕上方有「{Bot} 正在操作你的電腦」:按「取得控制權」Bot 先停手(變成「你正在操作,Bot 已暫停」,按「交還給 Bot」還它);按「停止」停掉那一輪。
- 設定 ›「電腦」›「示範教學」:替目前選的 Bot 輸入任務名稱,按「開始錄製」,照平常做,做完按上方「{Bot} 正在觀看並學習」的「完成」。之後跟 Bot 說「照示範做 名稱」。每個示範可以「播放錄影」、展開「步驟」看每一步的「畫面」、「刪除」。 - 設定 ›「電腦」›「示範教學」:替目前選的 Bot 輸入任務名稱,按「開始錄製」,照平常做,做完按上方「{Bot} 正在觀看並學習」的「完成」。之後跟 Bot 說「照示範做 名稱」。每個示範可以「播放錄影」、展開「步驟」看每一步的「畫面」、「刪除」。
- 「需要處理」卡:Bot 自己的電腦可以在卡上按「接管」直接做;其他電腦要到那台去做。手機上也有同一張卡。 - 「需要處理」卡:Bot 自己的電腦可以在卡上按「接管」直接做,打開的是那個 Bot 自己的螢幕,接管時只有它停手,別的 Bot 照做;其他電腦要到那台去做。手機上也有同一張卡。
- 右側面板的「電腦」畫面和「開啟電腦」:顯示目前選的 Bot 自己的螢幕(還沒開過就顯示共用的桌面);群組聊天顯示正在回答的成員的螢幕,「成員」卡片上點某個成員的小畫面就改顯示它的(再點一次回到跟著回答的人)。
- 「電腦」卡片下的「全部螢幕(N)」(有 Bot 開著自己的螢幕才出現):每個螢幕一格小畫面,寫是誰的、閒置多久;點一格打開那個螢幕看或接手。
- Bot 設定 ›「能力」›「看螢幕與操作」沒開,Bot 就沒有 `computer`。 - Bot 設定 ›「能力」›「看螢幕與操作」沒開,Bot 就沒有 `computer`。
## 怎麼操作 ## 怎麼操作
@ -36,6 +39,7 @@ Bot 用一個 `computer` 工具看一台電腦的螢幕、動滑鼠和鍵盤:
- 按鍵和沒指定欄位的 `typing` 只送到上次截圖時在最前面的 App;中途換了 App 會「沒有按」:先截圖或 `open_app`。 - 按鍵和沒指定欄位的 `typing` 只送到上次截圖時在最前面的 App;中途換了 App 會「沒有按」:先截圖或 `open_app`。
- 結果說「畫面和上一步完全一樣」就是沒點到:換編號或換方法,不要重複同一步。 - 結果說「畫面和上一步完全一樣」就是沒點到:換編號或換方法,不要重複同一步。
- Linux 上開著 IBus 輸入法(注音、拼音)時,`typing` 可能回「已打字(N 個字)」但字沒進去:N 是送出的字數,不是欄位裡的內容。一定看截圖確認;長字或中文改用剪貼簿貼上比較可靠。(Mac 會先直接寫進欄位或用貼上;Bot 自己的電腦中文和長字會自動貼上。) - Linux 上開著 IBus 輸入法(注音、拼音)時,`typing` 可能回「已打字(N 個字)」但字沒進去:N 是送出的字數,不是欄位裡的內容。一定看截圖確認;長字或中文改用剪貼簿貼上比較可靠。(Mac 會先直接寫進欄位或用貼上;Bot 自己的電腦中文和長字會自動貼上。)
- 「全部螢幕」和成員的小畫面每 3 秒更新一次,不是即時畫面;要看即時的點進去。
- `batch` 裡不能 `open_app`,也不能用 cmd+tab 這類切換 App 的鍵。 - `batch` 裡不能 `open_app`,也不能用 cmd+tab 這類切換 App 的鍵。
- 塗黑的卡號、驗證碼 Bot 讀不到:要碼的步驟用 `hand_over_computer`。 - 塗黑的卡號、驗證碼 Bot 讀不到:要碼的步驟用 `hand_over_computer`。
- Mac 沒開「螢幕與系統錄音」時 `screenshot` 只有清單沒有圖;沒開「輔助使用」不能點也不能打字。系統詢問最多每 10 分鐘跳一次。 - Mac 沒開「螢幕與系統錄音」時 `screenshot` 只有清單沒有圖;沒開「輔助使用」不能點也不能打字。系統詢問最多每 10 分鐘跳一次。

View File

@ -16,7 +16,7 @@ Bot 之間可以問問題、交辦工作、教技能;好幾個 Bot 可以在
## 使用者怎麼到 ## 使用者怎麼到
- 群組聊天:側邊欄 +(「新增」)›「群組聊天」,先放前三個 Bot 並打開設定,在「群組成員」勾選。群組的輸入框 + 裡寫「成員:…」,右側面板有「成員」。 - 群組聊天:側邊欄 +(「新增」)›「群組聊天」,先放前三個 Bot 並打開設定,在「群組成員」勾選。群組的輸入框 + 裡寫「成員:…」,右側面板有「成員」;右側的「電腦」畫面跟著正在回答的成員,顯示它自己的螢幕;「成員」卡片上點某個成員的小畫面,改成固定顯示它的。
- 分區:+ ›「新增分區」;Bot 選單「移至」(還沒有分區時是「移至新分區」)。分區標題點一下收合、雙擊改名,右鍵或 ⋯(「分區操作」)有「重新命名」「上移」「下移」「刪除」。 - 分區:+ ›「新增分區」;Bot 選單「移至」(還沒有分區時是「移至新分區」)。分區標題點一下收合、雙擊改名,右鍵或 ⋯(「分區操作」)有「重新命名」「上移」「下移」「刪除」。
- 支線:輸入框打「/」選 /btw。主聊天出現支線卡:狀態、「停止支線」、「看過程」,支線要你核准的步驟直接在卡上按;沒做完時有「重開這條支線」。 - 支線:輸入框打「/」選 /btw。主聊天出現支線卡:狀態、「停止支線」、「看過程」,支線要你核准的步驟直接在卡上按;沒做完時有「重開這條支線」。
@ -32,5 +32,6 @@ Bot 之間可以問問題、交辦工作、教技能;好幾個 Bot 可以在
- 一件事從使用者開始,最多在 Bot 之間轉 3 手;A 在等 B 時,B 不能反過來問 A(會說「正在等你」)。使用者停止 A,替 A 回答的 B 也會停。 - 一件事從使用者開始,最多在 Bot 之間轉 3 手;A 在等 B 時,B 不能反過來問 A(會說「正在等你」)。使用者停止 A,替 A 回答的 B 也會停。
- 不能問自己,不能問群組或把技能教給群組(改找裡面的成員);自己不會的技能不能教,對方已經會的不用教。 - 不能問自己,不能問群組或把技能教給群組(改找裡面的成員);自己不會的技能不能教,對方已經會的不用教。
- 別的 Bot 問或交辦的那一輪不算使用者的話:B 不能因此改自己的設定。答案在發問的聊天裡整理給使用者,不要叫他自己去看別的 Bot 的聊天。被點名同事、卻沒有「和其他 Bot 合作」能力的 Bot,只能照實說,請使用者打開。 - 別的 Bot 問或交辦的那一輪不算使用者的話:B 不能因此改自己的設定。答案在發問的聊天裡整理給使用者,不要叫他自己去看別的 Bot 的聊天。被點名同事、卻沒有「和其他 Bot 合作」能力的 Bot,只能照實說,請使用者打開。
- 群組成員在 Bot 的電腦上各有自己的螢幕和瀏覽器,看不到彼此開著的網頁:交棒時要把網址、檔案或頁面寫進回覆(系統指示會提醒成員這樣做)。
- 群組成員互相 @ 交棒時,兩則使用者訊息之間到 8 個回答就停,交還給使用者。群組自己的模型不會用到;群組不能開支線,輸入框上沒有記憶小卡片;成員至少留一個。 - 群組成員互相 @ 交棒時,兩則使用者訊息之間到 8 個回答就停,交還給使用者。群組自己的模型不會用到;群組不能開支線,輸入框上沒有記憶小卡片;成員至少留一個。
- 支線:一個 Bot 同時最多 3 條;支線不能再開支線,也不能改設定;支線記的、做的頁面和例行任務都算主 Bot 的。主線在忙時,先用執行步驟用的模型判斷會不會衝突,會就等主線這一輪做完。AnyBot 重新啟動時,沒做完的支線會停掉(「AnyBot 重新啟動,這條支線停了」);被停止的支線不回報。 - 支線:一個 Bot 同時最多 3 條;支線不能再開支線,也不能改設定;支線記的、做的頁面和例行任務都算主 Bot 的。主線在忙時,先用執行步驟用的模型判斷會不會衝突,會就等主線這一輪做完。在 Bot 的電腦上支線有自己的暫時螢幕和瀏覽器(登入從主線複製),看不到主線開著的網頁;在使用者的電腦上還是一次一個。AnyBot 重新啟動時,沒做完的支線會停掉(「AnyBot 重新啟動,這條支線停了」);被停止的支線不回報。

View File

@ -2615,7 +2615,7 @@ function openBox(control) {
const at = S.relay ? "host=" + encodeURIComponent(S.host) : "lan=1"; const at = S.relay ? "host=" + encodeURIComponent(S.host) : "lan=1";
boxOpen = true; boxOpen = true;
history.pushState({box: 1}, ""); 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"; $("boxwrap").style.display = "block";
} }
function closeBox() { function closeBox() {

View File

@ -116,7 +116,9 @@ async function ticketFor(path, body) {
const lan = q.get("lan") === "1"; 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 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 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); const $ = (id) => document.getElementById(id);
document.title = name; document.title = name;

View File

@ -492,7 +492,9 @@ impl Relay {
let sid = httpd::random_hex(8); let sid = httpd::random_hex(8);
let (tx, rx) = std::sync::mpsc::sync_channel::<Vec<u8>>(256); let (tx, rx) = std::sync::mpsc::sync_channel::<Vec<u8>>(256);
self.streams.lock().unwrap().insert(sid.clone(), (tx, host.to_string(), on)); 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); self.streams.lock().unwrap().remove(&sid);
return; return;
} }

View File

@ -359,6 +359,8 @@ enum BotBrowser {
/// another job's, and the person's, stay (see botbrowser's "each job its own tabs"). /// another job's, and the person's, stay (see botbrowser's "each job its own tabs").
struct UsedBrowsers { struct UsedBrowsers {
list: Vec<BotBrowser>, list: Vec<BotBrowser>,
/// The bot's screen on the bots' computer (its box browser is there).
screen: String,
via_name: String, via_name: String,
/// Close each browser when done (not only the tabs). /// Close each browser when done (not only the tabs).
close: bool, close: bool,
@ -382,7 +384,7 @@ fn with_job(args: &str, job: &str) -> String {
impl UsedBrowsers { impl UsedBrowsers {
fn new(via_name: &str, bot_id: u64, close: bool) -> Self { fn new(via_name: &str, bot_id: u64, close: bool) -> Self {
let n = JOB_SEQ.fetch_add(1, Ordering::Relaxed); 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) { fn add(&mut self, b: BotBrowser) {
@ -407,7 +409,8 @@ impl UsedBrowsers {
let _ = web::run_full("browser_tabs", &args(p), &never); let _ = web::run_full("browser_tabs", &args(p), &never);
} }
BotBrowser::Box(p) => { 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) => { BotBrowser::Device(host, p) => {
let _ = crate::remote::run_on_device(host, "browser_tabs", &args(p), &self.via_name); let _ = crate::remote::run_on_device(host, "browser_tabs", &args(p), &self.via_name);
@ -605,10 +608,11 @@ fn screen_leases() -> &'static Mutex<Leases> {
/// other work, or forgot to finish), or as soon as that turn ends. /// other work, or forgot to finish), or as soon as that turn ends.
pub const SCREEN_IDLE: Duration = Duration::from_secs(120); 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<String> { fn screen_key(place: &tools::Place) -> Option<String> {
match place { 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::Local { .. } => Some("local".into()),
tools::Place::Device { host, .. } => Some(format!("device:{host}")), tools::Place::Device { host, .. } => Some(format!("device:{host}")),
_ => None, _ => 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) (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<String> {
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). /// 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<String>); type Look<'a> = &'a dyn Fn(&str, &str) -> (String, bool, Option<String>);
@ -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 tools_once = false;
let mut local_once = false; let mut local_once = false;
let mut browsers = UsedBrowsers::new(&job.via_name, bot_id, job.close_browsers); 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…). // 電腦現況: 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) // 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 // 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)), 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), 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), 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 // (On this job's own tab, like its other browser steps: planned outside
// it, every tab looked like another job's — "no open tab".) // 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), BrowserAt::Here => crate::botbrowser::as_job(&tag, plan_here),
}; };
let (output, status) = match planned { 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(); 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)) 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), (_, BrowserAt::Here) => crate::botbrowser::as_job(&tag, fill_here),
}; };
match r { 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) target_for(&job, &call.args)
}; };
let on_box = matches!(target.as_ref().map(|t| &t.place), Ok(tools::Place::Box { .. })); 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) { let on_device = match target.as_ref().map(|t| &t.place) {
Ok(tools::Place::Device { host, .. }) => Some(host.clone()), Ok(tools::Place::Device { host, .. }) => Some(host.clone()),
_ => None, _ => None,
@ -3073,7 +3108,7 @@ pub fn spawn(job: Job, bot_id: u64, tx: Sender<(u64, StreamEvent)>, cancel: Arc<
let mut image = None; let mut image = None;
// 螢幕一次給一個: acting on a screen another turn is working (not just looking). // 螢幕一次給一個: acting on a screen another turn is working (not just looking).
let busy_screen = match (&approved, &target) { 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, _ => None,
}; };
let approved = match busy_screen { 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), Err(e) => (e, false),
} }
} else if is_screen && on_box { } 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)) => { Ok((out, img)) => {
image = img; image = img;
(out, true) (out, true)
@ -3111,6 +3146,9 @@ pub fn spawn(job: Job, bot_id: u64, tx: Sender<(u64, StreamEvent)>, cancel: Arc<
(out, ok) (out, ok)
} else if is_web { } else if is_web {
web::run(&call.name, &call.args, &cancel) 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 { } else {
tools::run_on(&call.name, &call.args, t, &cancel, &ids) 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!(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::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); 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] #[test]

View File

@ -25,6 +25,7 @@ use crate::theme::{Palette, DARK, LIGHT};
mod attach_ui; mod attach_ui;
mod channels_ui; mod channels_ui;
mod computers_ui; mod computers_ui;
mod screens_ui;
mod chat_ui; mod chat_ui;
mod files_ui; mod files_ui;
mod panel_ui; mod panel_ui;
@ -1566,6 +1567,10 @@ impl App {
if speaker.is_some() { if speaker.is_some() {
let names: Vec<String> = conv.members.iter().filter_map(|m| self.state.bot(*m)).map(|x| x.name.clone()).collect(); let names: Vec<String> = 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("、"))); 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 sys
}, },
@ -2117,6 +2122,7 @@ impl App {
} }
self.last_tick = Instant::now(); self.last_tick = Instant::now();
self.tend_garden(); self.tend_garden();
self.tend_screens();
self.resume_interrupted(ctx); self.resume_interrupted(ctx);
let now = crate::routines::now(); let now = crate::routines::now();
let mut fire = vec![]; let mut fire = vec![];
@ -5505,6 +5511,11 @@ impl App {
let mut app = App::new(ctx, None); let mut app = App::new(ctx, None);
app.headless = true; app.headless = true;
app.asking = 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 id = app.state.primary_bot;
let start = app.state.bot(id).map(|b| b.messages.len()).unwrap_or(0); let start = app.state.bot(id).map(|b| b.messages.len()).unwrap_or(0);
app.drafts.insert(id, text.to_string()); app.drafts.insert(id, text.to_string());
@ -5853,6 +5864,7 @@ impl eframe::App for App {
self.delete_dialog(ctx); self.delete_dialog(ctx);
self.delete_routine_dialog(ctx); self.delete_routine_dialog(ctx);
self.routines_window(ctx); self.routines_window(ctx);
self.screens_frame(ctx);
self.rebuild_dialog(ctx); self.rebuild_dialog(ctx);
self.local_control_bar(ctx); self.local_control_bar(ctx);
self.teach_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. // 支線: a copy of the bot doing one more thing alongside its main line.
if b.branch_of != 0 { 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. // 個人檔案: 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.) // (Its soul — the 指示 — comes last, where it weighs most.)

View File

@ -8,7 +8,9 @@
// same files or data, an account they'd both act on, a result the main line is waiting for). // 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. // 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 // - 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 // - 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. // 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); 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); 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. // The report: into the main line's running turn, or into the chat as the branch's words.
if state != BranchState::Stopped { if state != BranchState::Stopped {
let text = match state { let text = match state {

View File

@ -61,6 +61,10 @@ pub struct ComputerUi {
thumb_img: Arc<Mutex<Option<egui::ColorImage>>>, thumb_img: Arc<Mutex<Option<egui::ColorImage>>>,
thumb_busy: Arc<AtomicBool>, thumb_busy: Arc<AtomicBool>,
thumb_at: Option<Instant>, thumb_at: Option<Instant>,
/// 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) /// (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 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 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 }; 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_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()); let (slot, busy, c) = (self.cu.thumb_img.clone(), self.cu.thumb_busy.clone(), ctx.clone());
std::thread::spawn(move || { std::thread::spawn(move || {
let img = match &brain { 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()), 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(320), None => cloudbox::thumbnail_of(&key, 320).or_else(|| cloudbox::thumbnail(320)),
}; };
if let Some(img) = img { if let Some(img) = img {
let size = [img.width() as usize, img.height() as usize]; let size = [img.width() as usize, img.height() as usize];
@ -990,13 +1000,19 @@ impl App {
} }
fn open_screen(&mut self, control: bool) { 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; 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 { if self.mir.on {
let s = self.state.remote.clone(); let s = self.state.remote.clone();
self.box_task(move || { self.box_task(move || {
let ticket = crate::remote::screen_ticket(&s)?; 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); crate::preview::open_with_system(&url);
Ok(String::new()) Ok(String::new())
}); });
@ -1005,8 +1021,10 @@ impl App {
if self.demo { if self.demo {
return; 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 || { self.box_task(move || {
let url = cloudbox::viewer_url(control)?; let url = cloudbox::viewer_url_of(&key, control)?;
crate::preview::open_with_system(&url); crate::preview::open_with_system(&url);
Ok(String::new()) Ok(String::new())
}); });
@ -1031,14 +1049,26 @@ impl App {
self.hold_computer(false); 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 { if self.mir.on {
let s = self.state.remote.clone(); let s = self.state.remote.clone();
std::thread::spawn(move || { 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 { } else {
cloudbox::HELD_BY_PERSON.store(on, Ordering::SeqCst); cloudbox::hold(&key, on);
} }
} }

View File

@ -655,7 +655,7 @@ impl App {
out["mcp"] = self.mcp_state(); out["mcp"] = self.mcp_state();
// The bots' computer lives here; a screen shows its state, not its own computer's. // The bots' computer lives here; a screen shows its state, not its own computer's.
let run = crate::cloudbox::run_state(); 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). // Which computers each bot has (only the brain knows the account's other computers).
out["computers"] = self out["computers"] = self
.state .state

View File

@ -251,6 +251,17 @@ impl App {
if let Some(n) = pick { if let Some(n) = pick {
self.set_computer(bot.id, &n); 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 view {
if available { if available {
self.open_viewer(); self.open_viewer();
@ -265,8 +276,15 @@ impl App {
let mut edit = false; let mut edit = false;
let members: Vec<Bot> = bot.members.iter().filter_map(|m| self.state.bot(*m).cloned()).collect(); let members: Vec<Bot> = bot.members.iter().filter_map(|m| self.state.bot(*m).cloned()).collect();
let colors: Vec<Color32> = members.iter().map(|b| self.bot_color(b)).collect(); let colors: Vec<Color32> = 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<String> = 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<Option<u64>> = None;
panel_card(ui, p, |ui| { 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()); let (rect, r) = ui.allocate_exact_size(vec2(ui.available_width(), ROW_H), egui::Sense::click());
if r.hovered() { if r.hovered() {
ui.painter().rect_filled(rect, 9, p.hover); 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))); 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); avatar::avatar(&mut child, 20.0, &b.shape, col);
child.label(RichText::new(&b.name).size(13.0).color(p.text)); 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(); 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 { if edit {
self.edit_bot = Some((bot.clone(), false)); self.edit_bot = Some((bot.clone(), false));
} }

279
src/app/screens_ui.rs Normal file
View File

@ -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<u64, u64>,
/// 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<u64, egui::TextureHandle>,
fresh: Arc<Mutex<Vec<(u64, egui::ColorImage)>>>,
busy: Arc<AtomicBool>,
tiles_at: Option<Instant>,
/// 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<Instant>,
listed_at: Option<Instant>,
listing: Arc<AtomicBool>,
reaped_at: Option<Instant>,
}
/// 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<u64> = 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<Tile> {
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<Tile> {
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<u64> = 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<u64> = None;
let pictures: Vec<Option<(egui::TextureId, egui::Vec2)>> = 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);
}
}

View File

@ -583,6 +583,21 @@ pub fn wait_loaded(profile: Option<&str>, max_ms: u64) -> bool {
// ---------- the tools ---------- // ---------- 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 { 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() 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") }; let target = if !s(&v, "ref").is_empty() { format!("[{}]", s(&v, "ref")) } else { s(&v, "text") };
match name { match name {
"browser_type" => format!("{target} ← {}", s(&v, "value").chars().take(40).collect::<String>()), "browser_type" => format!("{target} ← {}", s(&v, "value").chars().take(40).collect::<String>()),
"browser_select" => format!("{target} → {}", s(&v, "option")), "browser_select" => format!("{target} → {}", select_option(&v)),
"browser_press" => s(&v, "key"), "browser_press" => s(&v, "key"),
"browser_scroll" => if target.is_empty() { s(&v, "direction") } else { target }, "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")) }, "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 - 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) - 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 - 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": { "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"]}, "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"}, "url": {"type": "string"},
@ -748,7 +763,7 @@ actions:
"append": {"type": "boolean", "description": "type: keep what's in the field"}, "append": {"type": "boolean", "description": "type: keep what's in the field"},
"submit": {"type": "boolean", "description": "type/fill: press Enter / sign in afterwards"}, "submit": {"type": "boolean", "description": "type/fill: press Enter / sign in afterwards"},
"key": {"type": "string", "description": "press: Enter, Tab, Escape, ctrl+a…"}, "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"}, "direction": {"type": "string", "enum": ["down", "up", "top", "bottom", "back", "forward", "reload"], "description": "scroll: down/up/top/bottom; back: back/forward/reload"},
"seconds": {"type": "number"}, "seconds": {"type": "number"},
"days": {"type": "integer", "description": "sent: how far back (default 30, up to 60)"}, "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(); let mut name = action.to_string();
if let Some(o) = v.as_object_mut() { if let Some(o) = v.as_object_mut() {
o.remove("action"); 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" { if name == "browser_fill_login" {
// fill {kind, id} names the exact vault tool and its id field. // 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()); 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>), String>
} }
let mut tab = Tab::current(profile)?; let mut tab = Tab::current(profile)?;
let r = (|| -> Result<(String, Option<String>), String> { let r = (|| -> Result<(String, Option<String>), String> {
// Typing into a dropdown (a <select>) can't work: picking its option is what was meant.
let name = if name == "browser_type" && tab.eval(&format!("(() => {{ const el = {}; return !!el && el.tagName === 'SELECT'; }})()", find_js(&rf, &text))).ok().and_then(|v| v.as_bool()) == Some(true) {
"browser_select"
} else {
name
};
match name { match name {
SEND_INFO => { SEND_INFO => {
let mode = s(args, "mode"); let mode = s(args, "mode");
@ -942,7 +970,10 @@ pub fn run(name: &str, args: &Value) -> Result<(String, Option<String>), String>
Ok((format!("已按 {}。\n{}", s(args, "key"), changes(&before, &after)), None)) Ok((format!("已按 {}。\n{}", s(args, "key"), changes(&before, &after)), None))
} }
"browser_select" => { "browser_select" => {
let option = s(args, "option"); let option = select_option(args);
if option.is_empty() {
return Err("要選哪一個?option 填選項上看得到的字(例如「台中」)。".into());
}
let sig = page_sig(&mut tab); let sig = page_sig(&mut tab);
let before = snapshot(&mut tab); let before = snapshot(&mut tab);
let js = format!( let js = format!(
@ -1404,6 +1435,17 @@ mod tests {
assert!(a.contains(r#""card_id":"7""#) && !a.contains("kind"), "{a}"); assert!(a.contains(r#""card_id":"7""#) && !a.contains("kind"), "{a}");
let (n, _) = c(r#"{"action":"fill"}"#); let (n, _) = c(r#"{"action":"fill"}"#);
assert_eq!(n, "browser_fill_login"); assert_eq!(n, "browser_fill_login");
// Playwright's fill (a control and its words): typing, or picking a dropdown's option.
let (n, a) = c(r#"{"action":"fill","ref":"3","value":"0912345678"}"#);
assert_eq!(n, "browser_type");
assert!(a.contains(r#""ref":"3""#) && a.contains("0912345678"), "{a}");
assert_eq!(c(r#"{"action":"fill","ref":"4","option":"台中"}"#).0, "browser_select");
assert_eq!(c(r#"{"action":"fill","kind":"login","ref":"1"}"#).0, "browser_fill_login", "the vault when it says so");
// A select's option as Playwright names it.
assert_eq!(select_option(&json!({"value": "台中"})), "台中");
assert_eq!(select_option(&json!({"values": ["高雄"]})), "高雄");
assert_eq!(select_option(&json!({"option": "台北", "value": "x"})), "台北");
assert_eq!(select_option(&json!({})), "");
let (n, _) = c(r#"{"action":"nope"}"#); let (n, _) = c(r#"{"action":"nope"}"#);
assert_eq!(n, TOOL, "an unknown action stays put (the runner explains it)"); assert_eq!(n, TOOL, "an unknown action stays put (the runner explains it)");
// Every internal browser tool is reachable from the one schema. // Every internal browser tool is reachable from the one schema.
@ -1690,6 +1732,7 @@ customElements.define('my-panel', class extends HTMLElement { constructor() { su
<div id=menu>商品分析</div><div id=sub style="display:none">分潤率排行</div> <div id=menu>商品分析</div><div id=sub style="display:none">分潤率排行</div>
<div id=dd role=combobox aria-label="排序">預設</div><ul id=opts role=listbox style="display:none"><li role=option>佣金由高到低</li><li role=option>銷量</li></ul> <div id=dd role=combobox aria-label="排序">預設</div><ul id=opts role=listbox style="display:none"><li role=option>佣金由高到低</li><li role=option>銷量</li></ul>
<input id=q placeholder="搜尋商品"> <input id=q placeholder="搜尋商品">
<label>城市 <select id=city aria-label="城市"><option value="">請選擇</option><option>台北</option><option>台中</option><option>高雄</option></select></label>
<div role=table aria-label="商品"><div role=row><span role=columnheader>商品</span><span role=columnheader>分潤率</span></div><div role=row><span role=cell>手機殼</span><span role=cell>8%</span></div><div role=row><span role=cell>乳液</span><span role=cell>12%</span></div></div> <div role=table aria-label="商品"><div role=row><span role=columnheader>商品</span><span role=columnheader>分潤率</span></div><div role=row><span role=cell>手機殼</span><span role=cell>8%</span></div><div role=row><span role=cell>乳液</span><span role=cell>12%</span></div></div>
<p id=out>點擊 0</p><a href="/export">匯出報表</a> <p id=out>點擊 0</p><a href="/export">匯出報表</a>
<script> <script>
@ -1722,6 +1765,14 @@ q.addEventListener('keydown', e => { if (e.key === 'Enter') out.innerText = '搜
assert!(r.contains("點擊 60,訂單 3"), "{r}"); assert!(r.contains("點擊 60,訂單 3"), "{r}");
let (r, _) = run("browser_select", &p(json!({"text": "排序", "option": "佣金由高到低"})))?; let (r, _) = run("browser_select", &p(json!({"text": "排序", "option": "佣金由高到低"})))?;
assert!(r.contains("佣金由高到低"), "{r}"); assert!(r.contains("佣金由高到低"), "{r}");
// A plain <select>: the option given as value, or typed into it, is chosen.
run("browser_select", &p(json!({"text": "城市", "value": "台中"})))?;
let (v, _) = run("browser_eval", &p(json!({"script": "document.getElementById('city').selectedOptions[0].text"})))?;
assert_eq!(v.trim(), "台中");
run("browser_type", &p(json!({"text": "城市", "value": "高雄"})))?;
let (v, _) = run("browser_eval", &p(json!({"script": "document.getElementById('city').selectedOptions[0].text"})))?;
assert_eq!(v.trim(), "高雄");
assert!(run("browser_select", &p(json!({"text": "城市"}))).is_err(), "no option: said, not 「已選「」」");
let (r, _) = run("browser_type", &p(json!({"text": "搜尋商品", "value": "手機殼", "submit": true})))?; let (r, _) = run("browser_type", &p(json!({"text": "搜尋商品", "value": "手機殼", "submit": true})))?;
assert!(r.contains("搜尋:手機殼"), "{r}"); assert!(r.contains("搜尋:手機殼"), "{r}");
let (t, _) = run("browser_table", &p(json!({})))?; let (t, _) = run("browser_table", &p(json!({})))?;

View File

@ -133,6 +133,8 @@ const XRESOURCES: &str = include_str!("../box/Xresources");
const MENU: &str = include_str!("../box/menu"); const MENU: &str = include_str!("../box/menu");
const A11Y: &str = include_str!("../box/a11y"); const A11Y: &str = include_str!("../box/a11y");
const BROWSER: &str = include_str!("../box/browser"); const BROWSER: &str = include_str!("../box/browser");
/// 每個 Bot 一個螢幕: opens, lists and closes the bots' own screens.
const SCREEN_SH: &str = include_str!("../box/screen");
// ---------- state ---------- // ---------- state ----------
@ -218,15 +220,13 @@ struct Shared {
last_used: Instant, last_used: Instant,
rebuilding: bool, rebuilding: bool,
log: Vec<String>, log: Vec<String>,
/// The desktop's size in pixels (the bot's pictures are this, fitted; see box_scale).
size: Option<(u32, u32)>,
tunnel: Option<std::process::Child>, tunnel: Option<std::process::Child>,
host_port: u16, host_port: u16,
} }
fn shared() -> &'static Mutex<Shared> { fn shared() -> &'static Mutex<Shared> {
static S: OnceLock<Mutex<Shared>> = OnceLock::new(); static S: OnceLock<Mutex<Shared>> = OnceLock::new();
S.get_or_init(|| Mutex::new(Shared { run: Run::Absent, last_used: Instant::now(), rebuilding: false, log: vec![], size: None, tunnel: None, host_port: HOST_PORT })) S.get_or_init(|| Mutex::new(Shared { run: Run::Absent, last_used: Instant::now(), rebuilding: false, log: vec![], tunnel: None, host_port: HOST_PORT }))
} }
fn config() -> &'static Mutex<Config> { fn config() -> &'static Mutex<Config> {
@ -894,7 +894,7 @@ fn build_image(pull: bool) -> Result<(), String> {
let dir = std::env::temp_dir().join(format!("anybot-box-build-{}", std::process::id())); let dir = std::env::temp_dir().join(format!("anybot-box-build-{}", std::process::id()));
let _ = std::fs::remove_dir_all(&dir); let _ = std::fs::remove_dir_all(&dir);
std::fs::create_dir_all(&dir).map_err(|e| e.to_string())?; std::fs::create_dir_all(&dir).map_err(|e| e.to_string())?;
for (name, body) in [("Dockerfile", DOCKERFILE), ("start.sh", START_SH), ("fluxbox-init", FLUXBOX_INIT), ("overlay", OVERLAY), ("Xresources", XRESOURCES), ("menu", MENU), ("a11y", A11Y), ("browser", BROWSER)] { for (name, body) in [("Dockerfile", DOCKERFILE), ("start.sh", START_SH), ("fluxbox-init", FLUXBOX_INIT), ("overlay", OVERLAY), ("Xresources", XRESOURCES), ("menu", MENU), ("a11y", A11Y), ("browser", BROWSER), ("screen", SCREEN_SH)] {
std::fs::write(dir.join(name), body).map_err(|e| e.to_string())?; std::fs::write(dir.join(name), body).map_err(|e| e.to_string())?;
} }
log("正在建立電腦的映像檔(第一次要幾分鐘)…"); log("正在建立電腦的映像檔(第一次要幾分鐘)…");
@ -929,7 +929,7 @@ fn free_port(start: u16) -> u16 {
} }
fn create_container() -> Result<(), String> { fn create_container() -> Result<(), String> {
shared().lock().unwrap_or_else(|e| e.into_inner()).size = None; screens().lock().unwrap_or_else(|e| e.into_inner()).clear();
if !image_exists() { if !image_exists() {
build_image(false)?; build_image(false)?;
} }
@ -956,10 +956,10 @@ fn create_container() -> Result<(), String> {
.iter() .iter()
.flat_map(|c| ["--cap-add".to_string(), (*c).to_string()]) .flat_map(|c| ["--cap-add".to_string(), (*c).to_string()])
.collect(); .collect();
let mut args: Vec<&str> = vec!["run", "-d", "--name", container(), "--hostname", "bot-computer", "--shm-size", "1g", "--pids-limit", "4096", "--memory", "2g", "--cpus", "2", "--add-host", "host.docker.internal:host-gateway", "-p", &publish, "-v", &vol, "-e", &env, "-e", &vnc]; let mut args: Vec<&str> = vec!["run", "-d", "--name", container(), "--hostname", "bot-computer", "--shm-size", "2g", "--pids-limit", "4096", "--memory", "4g", "--cpus", "2", "--add-host", "host.docker.internal:host-gateway", "-p", &publish, "-v", &vol, "-e", &env, "-e", &vnc];
if hardened { if hardened {
// (No swap on top of the 2 GB under gVisor; a standard box keeps Docker's default.) // (No swap on top of the 2 GB under gVisor; a standard box keeps Docker's default.)
args.extend(["--memory-swap", "2g"]); args.extend(["--memory-swap", "4g"]);
args.push("--runtime"); args.push("--runtime");
args.push(runtime); args.push(runtime);
args.push("--cap-drop"); args.push("--cap-drop");
@ -1056,11 +1056,11 @@ fn pump(from: &mut impl std::io::Read, to: &mut impl std::io::Write) {
} }
} }
/// A local port that reaches the box's DevTools port. /// A local port that reaches DevTools port `box_port` in the box (one per screen's browser).
fn box_cdp_forward() -> Result<u16, String> { fn box_cdp_forward(box_port: u16) -> Result<u16, String> {
static PORT: Mutex<u16> = Mutex::new(0); static PORTS: OnceLock<Mutex<std::collections::HashMap<u16, u16>>> = OnceLock::new();
let mut p = PORT.lock().unwrap(); let mut ports = PORTS.get_or_init(|| Mutex::new(std::collections::HashMap::new())).lock().unwrap_or_else(|e| e.into_inner());
if *p != 0 { if let Some(p) = ports.get(&box_port) {
return Ok(*p); return Ok(*p);
} }
let l = std::net::TcpListener::bind("127.0.0.1:0").map_err(|e| e.to_string())?; let l = std::net::TcpListener::bind("127.0.0.1:0").map_err(|e| e.to_string())?;
@ -1068,7 +1068,7 @@ fn box_cdp_forward() -> Result<u16, String> {
std::thread::spawn(move || { std::thread::spawn(move || {
for conn in l.incoming().flatten() { for conn in l.incoming().flatten() {
std::thread::spawn(move || { std::thread::spawn(move || {
let script = format!("exec 3<>/dev/tcp/127.0.0.1/{BOX_CDP_PORT} || exit 1; cat <&3 & cat >&3; kill $! 2>/dev/null"); let script = format!("exec 3<>/dev/tcp/127.0.0.1/{box_port} || exit 1; cat <&3 & cat >&3; kill $! 2>/dev/null");
let Ok(mut child) = docker().args(["exec", "-i", container(), "bash", "-c", &script]).stdin(Stdio::piped()).stdout(Stdio::piped()).stderr(Stdio::null()).spawn() else { return }; let Ok(mut child) = docker().args(["exec", "-i", container(), "bash", "-c", &script]).stdin(Stdio::piped()).stdout(Stdio::piped()).stderr(Stdio::null()).spawn() else { return };
let (Some(mut cin), Some(mut cout)) = (child.stdin.take(), child.stdout.take()) else { return }; let (Some(mut cin), Some(mut cout)) = (child.stdin.take(), child.stdout.take()) else { return };
let (Ok(mut r), Ok(mut w)) = (conn.try_clone(), conn.try_clone()) else { return }; let (Ok(mut r), Ok(mut w)) = (conn.try_clone(), conn.try_clone()) else { return };
@ -1081,26 +1081,53 @@ fn box_cdp_forward() -> Result<u16, String> {
}); });
} }
}); });
*p = port; ports.insert(box_port, port);
Ok(port) Ok(port)
} }
/// Is the box's Chromium answering already? /// The current screen's DevTools port in the box (the shared screen's browser: 9222), opening the
pub fn browser_running() -> bool { /// screen when it isn't (and marking it used, at most once a minute, so a bot working only in its
box_cdp_forward().map(box_cdp_alive).unwrap_or(false) /// browser doesn't have its screen closed as idle).
fn screen_cdp_port(fresh: bool) -> Result<u16, String> {
let key = current_screen();
if key.is_empty() {
return Ok(BOX_CDP_PORT);
}
let known = with_screen(|st| st.cdp.filter(|_| !fresh && st.touched.is_some_and(|t| t.elapsed() < Duration::from_secs(60))));
if let Some(p) = known {
return Ok(p);
}
let out = dk_timeout(&["exec", "-u", "bot", container(), "sh", "-c", &format!("command -v anybot-screen >/dev/null || {{ echo CDP_PORT={BOX_CDP_PORT}; exit 0; }}; anybot-screen up {key}")], 30_000)
.map(|o| String::from_utf8_lossy(&o).to_string())
.map_err(|e| screen_full(&e).unwrap_or_else(|| format!("Bot 的電腦開不了這個 Bot 的螢幕:{e}")))?;
let port = out.lines().find_map(|l| l.trim().strip_prefix("CDP_PORT=")?.parse::<u16>().ok()).ok_or("Bot 的電腦沒有說這個 Bot 的瀏覽器在哪個埠")?;
with_screen(|st| {
st.cdp = Some(port);
st.touched = Some(Instant::now());
});
Ok(port)
} }
/// The box's Chromium, started on its desktop when it isn't running. Gives the local port. /// Is the current screen's Chromium answering already?
pub fn browser_running() -> bool {
screen_cdp_port(false).and_then(box_cdp_forward).map(box_cdp_alive).unwrap_or(false)
}
/// The current screen's Chromium (each bot its own, on its own screen, with its own profile that
/// started as a copy of the shared one's logins), started when it isn't running. Gives the local
/// port that reaches it.
pub fn browser_port() -> Result<u16, String> { pub fn browser_port() -> Result<u16, String> {
ensure_running()?; ensure_running()?;
touch(); touch();
let port = box_cdp_forward()?; let port = box_cdp_forward(screen_cdp_port(false)?)?;
if box_cdp_alive(port) { if box_cdp_alive(port) {
return Ok(port); return Ok(port);
} }
// The box's one browser launcher (same profile and port as the person's menu entry, web // Not answering: the screen may have been closed meanwhile — open it again, then the browser.
// pages exposed to accessibility). let key = current_screen();
dk_timeout(&["exec", "-u", "bot", container(), "anybot-browser"], 30_000).map_err(|e| format!("Bot 的電腦打不開瀏覽器:{e}"))?; let port = box_cdp_forward(screen_cdp_port(true)?)?;
let start_cmd = if key.is_empty() { "anybot-browser".to_string() } else { format!("ANYBOT_SCREEN={key} anybot-browser") };
dk_timeout(&["exec", "-u", "bot", container(), "sh", "-c", &start_cmd], 30_000).map_err(|e| format!("Bot 的電腦打不開瀏覽器:{e}"))?;
let start = Instant::now(); let start = Instant::now();
while start.elapsed() < Duration::from_secs(20) { while start.elapsed() < Duration::from_secs(20) {
if box_cdp_alive(port) { if box_cdp_alive(port) {
@ -1723,8 +1750,12 @@ pub fn exec_wrapper(dir: &str, cmd: &str, interactive: bool, tty: bool, job: &st
// uid is not 0"), though the box gives the bot sudo without a password. A command that asks // uid is not 0"), though the box gives the bot sudo without a password. A command that asks
// for sudo runs as the box's root instead (root's sudo needs no setuid), and what it left in // for sudo runs as the box's root instead (root's sudo needs no setuid), and what it left in
// the bot's home is handed back to the bot. Still inside the box, same walls. // the bot's home is handed back to the bot. Still inside the box, same walls.
// What it left anywhere in the bot's home goes back (not only in its folder: a browser it
// started that way left ~/.config/chromium and ~/.local/share/pki to root, and the bot's
// own browser couldn't open later).
let user = if uses_sudo(cmd) { let user = if uses_sudo(cmd) {
inner = format!("m=$(mktemp); {inner}; rc=$?; find -P {d} -xdev -user root -newer \"$m\" -exec chown -h bot:bot {{}} + 2>/dev/null; rm -f \"$m\"; exit $rc", d = sh_quote(dir)); let mine = if dir.starts_with(&format!("{HOME}/")) { sh_quote(HOME) } else { format!("{} {}", sh_quote(HOME), sh_quote(dir)) };
inner = format!("m=$(mktemp); {inner}; rc=$?; find -P {mine} -xdev -user root -newer \"$m\" -exec chown -h bot:bot {{}} + 2>/dev/null; rm -f \"$m\"; exit $rc");
"root" "root"
} else { } else {
"bot" "bot"
@ -1736,6 +1767,16 @@ pub fn exec_wrapper(dir: &str, cmd: &str, interactive: bool, tty: bool, job: &st
(true, false) => " -i", (true, false) => " -i",
_ => "", _ => "",
}; };
// A window a command opens shows on its bot's own screen when that is open (每個 Bot 一個螢幕;
// a 支線's on its temporary one: the current screen), else on the shared one. A command
// doesn't open a screen by itself.
let key = match current_screen() {
k if k.is_empty() => screen_of_dir(dir),
k => k,
};
if !key.is_empty() {
inner = format!("[ -r /tmp/anybot-screens/{key}/env ] && {{ . /tmp/anybot-screens/{key}/env; export DISPLAY DBUS_SESSION_BUS_ADDRESS; }}; {inner}");
}
format!("{} exec{flags} -u {user} -e DISPLAY={DISPLAY} -e HOME={HOME} -e USER=bot{}{env_arg} {box} bash -lc {}", docker_prefix(), egress_env(), sh_quote(&inner), r#box = container()) format!("{} exec{flags} -u {user} -e DISPLAY={DISPLAY} -e HOME={HOME} -e USER=bot{}{env_arg} {box} bash -lc {}", docker_prefix(), egress_env(), sh_quote(&inner), r#box = container())
} }
@ -1834,8 +1875,14 @@ pub fn copy_out(path_in_box: &str) -> Result<PathBuf, String> {
/// The latest picture of the box's screen, small (for the 電腦 card). While the box runs it is /// The latest picture of the box's screen, small (for the 電腦 card). While the box runs it is
/// taken now (and kept on disk); while it sleeps the last one taken is shown. /// taken now (and kept on disk); while it sleeps the last one taken is shown.
pub fn thumbnail(width: u32) -> Option<image::RgbaImage> { pub fn thumbnail(width: u32) -> Option<image::RgbaImage> {
let path = data_dir().join("last-screen.png"); thumbnail_of("", width)
if let Some(img) = frame() { }
/// The same, of `key`'s screen ("" the shared one). None for a bot whose screen isn't open (and
/// never was): the caller shows the shared one.
pub fn thumbnail_of(key: &str, width: u32) -> Option<image::RgbaImage> {
let path = if key.is_empty() { data_dir().join("last-screen.png") } else { data_dir().join(format!("last-screen-{key}.png")) };
if let Some(img) = frame_of(key) {
let h = (img.height() as f32 * width as f32 / img.width().max(1) as f32).round() as u32; let h = (img.height() as f32 * width as f32 / img.width().max(1) as f32).round() as u32;
let small = image::imageops::resize(&img, width, h.max(1), image::imageops::FilterType::Triangle); let small = image::imageops::resize(&img, width, h.max(1), image::imageops::FilterType::Triangle);
let _ = std::fs::create_dir_all(data_dir()); let _ = std::fs::create_dir_all(data_dir());
@ -1845,28 +1892,66 @@ pub fn thumbnail(width: u32) -> Option<image::RgbaImage> {
image::open(&path).ok().map(|i| i.to_rgba8()) image::open(&path).ok().map(|i| i.to_rgba8())
} }
/// The screen now, for a small picture (no waking: None when the box isn't running). People watch /// `key`'s screen now, for a small picture ("" the shared one; no waking: None when the box isn't
/// it live through VNC (vnc.rs). /// running, or the bot's screen isn't open). People watch it live through VNC (vnc.rs).
pub fn frame() -> Option<image::RgbaImage> { pub fn frame_of(key: &str) -> Option<image::RgbaImage> {
if !run_state().is_running() { if !run_state().is_running() {
return None; return None;
} }
let jpeg = dk_timeout(&["exec", container(), "import", "-window", "root", "-display", DISPLAY, "-quality", "80", "jpeg:-"], 5_000).ok()?; let jpeg = if key.is_empty() {
dk_timeout(&["exec", container(), "import", "-window", "root", "-display", DISPLAY, "-quality", "80", "jpeg:-"], 5_000).ok()?
} else {
let script = format!(". /tmp/anybot-screens/{key}/env 2>/dev/null || exit 4; import -window root -display \"$DISPLAY\" -quality 80 jpeg:-");
dk_timeout(&["exec", container(), "sh", "-c", &script], 5_000).ok()?
};
image::load_from_memory(&jpeg).ok().map(|i| i.to_rgba8()) image::load_from_memory(&jpeg).ok().map(|i| i.to_rgba8())
} }
/// The screens open in the box now: (key, seconds since a bot last used it).
pub fn open_screens() -> Vec<(String, u64)> {
if !run_state().is_running() {
return vec![];
}
dk_timeout(&["exec", container(), "sh", "-c", "command -v anybot-screen >/dev/null && anybot-screen list"], 5_000)
.map(|out| String::from_utf8_lossy(&out).lines().filter_map(|l| { let mut p = l.split_whitespace(); Some((p.next()?.to_string(), p.nth(1)?.parse().ok()?)) }).collect())
.unwrap_or_default()
}
/// The screens open in the box as last looked (refresh_open_screens, every few seconds while the
/// window runs): what the 全部螢幕 view and a screen of the brain list, without waiting on the box.
fn seen_screens() -> &'static Mutex<Vec<(String, u64)>> {
static S: OnceLock<Mutex<Vec<(String, u64)>>> = OnceLock::new();
S.get_or_init(|| Mutex::new(vec![]))
}
pub fn refresh_open_screens() {
let open = open_screens();
*seen_screens().lock().unwrap_or_else(|e| e.into_inner()) = open;
}
pub fn open_screens_seen() -> Vec<(String, u64)> {
seen_screens().lock().unwrap_or_else(|e| e.into_inner()).clone()
}
/// Close the screens no bot used for `secs` (their browsers too; profiles stay).
pub fn reap_screens(secs: u64) {
if run_state().is_running() {
let _ = dk_timeout(&["exec", "-u", "bot", container(), "sh", "-c", &format!("command -v anybot-screen >/dev/null && anybot-screen reap {secs}")], 10_000);
}
}
/// The desktop's size in pixels (asked once per box). /// The desktop's size in pixels (asked once per box).
fn box_size() -> Result<(u32, u32), String> { fn box_size() -> Result<(u32, u32), String> {
if let Some(s) = shared().lock().unwrap_or_else(|e| e.into_inner()).size { if let Some(s) = with_screen(|st| st.size) {
return Ok(s); return Ok(s);
} }
let out = dk(&["exec", "-u", "bot", "-e", "DISPLAY=:1", container(), "xdotool", "getdisplaygeometry"])?; let out = box_exec("xdotool getdisplaygeometry")?;
let mut it = out.split_whitespace().filter_map(|n| n.parse::<u32>().ok()); let mut it = out.split_whitespace().filter_map(|n| n.parse::<u32>().ok());
let size = match (it.next(), it.next()) { let size = match (it.next(), it.next()) {
(Some(w), Some(h)) if w > 0 && h > 0 => (w, h), (Some(w), Some(h)) if w > 0 && h > 0 => (w, h),
_ => return Err("讀不到這台電腦的螢幕大小".to_string()), _ => return Err("讀不到這台電腦的螢幕大小".to_string()),
}; };
shared().lock().unwrap_or_else(|e| e.into_inner()).size = Some(size); with_screen(|st| st.size = Some(size));
Ok(size) Ok(size)
} }
@ -1893,7 +1978,7 @@ pub fn box_script(name: &str, v: &Value, scale: (f64, f64)) -> Result<(String, S
Value::Number(n) => n.to_string(), Value::Number(n) => n.to_string(),
_ => return None, _ => return None,
}; };
let spots = BOX_SPOTS.lock().unwrap_or_else(|e| e.into_inner()).clone(); let spots = with_screen(|st| st.spots.clone());
Some(spots.ok_or_else(|| "先用 computer_use_screenshot 看一下畫面,再照圖上的編號操作。".to_string()).and_then(|s| s.get(&r)).map(|((x, y), what)| ((x.round() as i64, y.round() as i64), format!("#{}({what})", crate::marks::number_of(&r).unwrap_or(0))))) Some(spots.ok_or_else(|| "先用 computer_use_screenshot 看一下畫面,再照圖上的編號操作。".to_string()).and_then(|s| s.get(&r)).map(|((x, y), what)| ((x.round() as i64, y.round() as i64), format!("#{}({what})", crate::marks::number_of(&r).unwrap_or(0)))))
}; };
let pt = |p: &Value| -> Result<(i64, i64), String> { let pt = |p: &Value| -> Result<(i64, i64), String> {
@ -2041,7 +2126,8 @@ fn type_script_as(text: &str, paste: bool) -> String {
if !paste && text.is_ascii() && text.chars().count() <= TYPE_KEYS_MAX_CHARS { if !paste && text.is_ascii() && text.chars().count() <= TYPE_KEYS_MAX_CHARS {
return format!("xdotool type --clearmodifiers --delay {TYPE_DELAY_MS} -- {q}"); return format!("xdotool type --clearmodifiers --delay {TYPE_DELAY_MS} -- {q}");
} }
format!("printf '%s' {q} > /tmp/anybot-paste.txt && for s in clipboard primary; do setsid xclip -selection $s -i /tmp/anybot-paste.txt </dev/null >/dev/null 2>&1 & done; sleep 0.15; \ let f = format!("/tmp/anybot-paste-{}.txt", screen_tag(&current_screen()));
format!("printf '%s' {q} > {f} && for s in clipboard primary; do setsid xclip -selection $s -i {f} </dev/null >/dev/null 2>&1 & done; sleep 0.15; \
case \"$(xprop -id $(xdotool getactivewindow) WM_CLASS 2>/dev/null | tr A-Z a-z)\" in *term*) k=shift+Insert;; *) k=ctrl+v;; esac; xdotool key --clearmodifiers $k") case \"$(xprop -id $(xdotool getactivewindow) WM_CLASS 2>/dev/null | tr A-Z a-z)\" in *term*) k=shift+Insert;; *) k=ctrl+v;; esac; xdotool key --clearmodifiers $k")
} }
@ -2057,12 +2143,13 @@ const SETTLE_SH: &str = "{ probe() { { import -window root -crop 160x140+80+30 -
/// Run a script in the box (as the bot user, on its desktop). Gives back what it printed. /// Run a script in the box (as the bot user, on its desktop). Gives back what it printed.
fn box_exec(script: &str) -> Result<String, String> { fn box_exec(script: &str) -> Result<String, String> {
let full = format!("{} {script}", screen_sh(&current_screen()));
// An stdin closed at once, as `docker exec -i` expects. // An stdin closed at once, as `docker exec -i` expects.
match dk_with_input(&["exec", "-i", "-u", "bot", "-e", "DISPLAY=:1", container(), "sh", "-c", script], Some(b""), 30_000) { match dk_with_input(&["exec", "-i", "-u", "bot", "-e", "DISPLAY=:1", container(), "sh", "-c", &full], Some(b""), 30_000) {
Ok(o) => Ok(String::from_utf8_lossy(&o).to_string()), Ok(o) => Ok(String::from_utf8_lossy(&o).to_string()),
Err(e) if e == "逾時" => Err("這台電腦太久沒有回應".into()), Err(e) if e == "逾時" => Err("這台電腦太久沒有回應".into()),
Err(e) if e.is_empty() => Err("這一步沒有成功".into()), Err(e) if e.is_empty() => Err("這一步沒有成功".into()),
Err(e) => Err(format!("xdotool:{e}")), Err(e) => Err(screen_full(&e).unwrap_or_else(|| format!("xdotool:{e}"))),
} }
} }
@ -2106,10 +2193,159 @@ pub fn box_write(path: &str, bytes: &[u8]) -> Result<(), String> {
dk_with_input(&["exec", "-i", "-u", "bot", container(), "sh", "-c", &script], Some(bytes), 60_000).map(|_| ()).map_err(|e| format!("存不進 Bot 的電腦:{e}")) dk_with_input(&["exec", "-i", "-u", "bot", container(), "sh", "-c", &script], Some(bytes), 60_000).map(|_| ()).map_err(|e| format!("存不進 Bot 的電腦:{e}"))
} }
/// The numbered controls of the box's latest look (centres in desktop pixels). // ---------- 每個 Bot 一個螢幕 ----------
static BOX_SPOTS: Mutex<Option<crate::marks::Spots>> = Mutex::new(None); // Grok Bot's split: one computer for the account, a screen of its own for each bot (box/screen:
/// The latest look's fingerprint (to say when a step changed nothing). // `anybot-screen up <key>` makes display :10, :11, … with its own VNC, accessibility bus and
static BOX_LAST: Mutex<Option<u64>> = Mutex::new(None); // browser port). Bots work side by side instead of taking turns on :1; :1 stays the shared
// desktop. A step runs on the current screen (`on_screen`); "" is the shared one.
thread_local! {
static ON_SCREEN: std::cell::RefCell<String> = const { std::cell::RefCell::new(String::new()) };
}
/// The screen of the bot whose folder is `dir` (/home/bot/bot-12 → "bot12"), "" for any other
/// folder (the shared screen). A branch works in its main bot's folder, so on its screen too.
pub fn screen_of_dir(dir: &str) -> String {
dir.trim_end_matches('/').rsplit('/').next().and_then(|f| f.strip_prefix("bot-")).filter(|id| !id.is_empty() && id.chars().all(|c| c.is_ascii_digit())).map(|id| format!("bot{id}")).unwrap_or_default()
}
/// The screen of a bot by its id.
pub fn screen_of_bot(bot_id: u64) -> String {
screen_of_dir(&bot_dir(bot_id))
}
/// A 支線's screen: a temporary one beside its main bot's (`bot12-t57`), so a branch and its main
/// line don't click on one screen. Its browser starts as a copy of the main bot's (the same
/// logins); screen and copy go when the branch ends (close_screen). "" off a bot's own screen.
pub fn branch_screen(main_key: &str, branch: u64) -> String {
if main_key.is_empty() || branch == 0 {
return String::new();
}
format!("{main_key}-t{branch}")
}
/// The bot a screen is (its own bot, or a 支線 for a temporary one): (bot, branch or 0).
pub fn bot_of_screen(key: &str) -> Option<(u64, u64)> {
let rest = key.strip_prefix("bot")?;
let (own, branch) = match rest.split_once("-t") {
Some((a, b)) => (a, b.parse().ok()?),
None => (rest, 0),
};
Some((own.parse().ok()?, branch))
}
/// Close `key`'s screen now (its browser too; a 支線's temporary browser profile goes with it).
pub fn close_screen(key: &str) {
if key.is_empty() || !key.chars().all(|c| c.is_ascii_alphanumeric() || c == '-' || c == '_') {
return;
}
if run_state().is_running() {
let _ = dk_timeout(&["exec", "-u", "bot", container(), "sh", "-c", &format!("command -v anybot-screen >/dev/null && anybot-screen down {key}")], 10_000);
}
screens().lock().unwrap_or_else(|e| e.into_inner()).remove(key);
}
fn current_screen() -> String {
ON_SCREEN.with(|s| s.borrow().clone())
}
/// Run `f` with `key`'s screen as the current one (the box's steps, looks and browser go there).
pub fn on_screen<T>(key: &str, f: impl FnOnce() -> T) -> T {
let before = ON_SCREEN.with(|s| std::mem::replace(&mut *s.borrow_mut(), key.to_string()));
let out = f();
ON_SCREEN.with(|s| *s.borrow_mut() = before);
out
}
/// A screen's name in file names and viewer tokens: its key, or "main" for the shared one.
fn screen_tag(key: &str) -> &str {
if key.is_empty() { "main" } else { key }
}
/// Shell lines that put what follows on `key`'s screen: made there when it isn't open (exit 3 and
/// the screens in use when the box is full). A box from before screens (no anybot-screen) and the
/// shared screen use :1.
fn screen_sh(key: &str) -> String {
if key.is_empty() {
return "export DISPLAY=:1;".into();
}
format!("if command -v anybot-screen >/dev/null 2>&1; then o=$(anybot-screen up {key} 2>&1) || {{ printf '%s\\n' \"$o\" >&2; exit 3; }}; eval \"$o\"; export DISPLAY DBUS_SESSION_BUS_ADDRESS; else export DISPLAY=:1; fi;")
}
/// Which screen each bot is on now (the brain's window sets it every few seconds: a group chat
/// shows the member speaking). What viewers, thumbnails and takeovers from elsewhere — the phone,
/// a screen computer, the account server — go by, since they only name the bot.
fn bot_screens() -> &'static Mutex<std::collections::HashMap<u64, String>> {
static M: OnceLock<Mutex<std::collections::HashMap<u64, String>>> = OnceLock::new();
M.get_or_init(|| Mutex::new(std::collections::HashMap::new()))
}
pub fn set_bot_screens(map: std::collections::HashMap<u64, String>) {
*bot_screens().lock().unwrap_or_else(|e| e.into_inner()) = map;
}
/// The screen to show for `bot` (an id from a viewer's request; "" the shared one).
pub fn screen_for_bot(bot: &str) -> String {
let id: u64 = bot.trim().parse().unwrap_or(0);
bot_screens().lock().unwrap_or_else(|e| e.into_inner()).get(&id).cloned().unwrap_or_default()
}
/// What a step that couldn't get its screen is told.
fn screen_full(err: &str) -> Option<String> {
let keys = err.lines().find_map(|l| l.trim().strip_prefix("FULL="))?;
Some(format!("Bot 的電腦同時開的螢幕已經滿了({} 個,都有 Bot 在用)。先做不用螢幕的部分(指令、檔案),或晚一點再試;閒置 10 分鐘的螢幕會自己關掉。", keys.split_whitespace().count()))
}
/// What one screen remembers between its steps.
#[derive(Default)]
struct ScreenState {
/// The numbered controls of its latest look (centres in desktop pixels).
spots: Option<crate::marks::Spots>,
/// The latest look's fingerprint (to say when a step changed nothing).
last: Option<u64>,
/// Numbers kept from look to look where the same control is still there.
numbers: Option<crate::marks::Numbering>,
/// The latest look's controls (what moved since).
els: Vec<crate::marks::Element>,
/// Its size in pixels.
size: Option<(u32, u32)>,
/// Its browser's DevTools port in the box, and when the screen was last marked used.
cdp: Option<u16>,
touched: Option<Instant>,
}
fn screens() -> &'static Mutex<std::collections::HashMap<String, ScreenState>> {
static S: OnceLock<Mutex<std::collections::HashMap<String, ScreenState>>> = OnceLock::new();
S.get_or_init(|| Mutex::new(std::collections::HashMap::new()))
}
/// The current screen's memory.
fn with_screen<T>(f: impl FnOnce(&mut ScreenState) -> T) -> T {
let key = current_screen();
let mut all = screens().lock().unwrap_or_else(|e| e.into_inner());
f(all.entry(key).or_default())
}
/// The screens a person took over (their keys; "" the shared one): those bots' steps wait.
fn held() -> &'static Mutex<std::collections::HashSet<String>> {
static H: OnceLock<Mutex<std::collections::HashSet<String>>> = OnceLock::new();
H.get_or_init(|| Mutex::new(Default::default()))
}
/// A person takes over (or gives back) `key`'s screen.
pub fn hold(key: &str, on: bool) {
let mut h = held().lock().unwrap_or_else(|e| e.into_inner());
if on {
h.insert(key.to_string());
} else {
h.remove(key);
}
HELD_BY_PERSON.store(!h.is_empty(), Ordering::SeqCst);
}
fn is_held(key: &str) -> bool {
held().lock().unwrap_or_else(|e| e.into_inner()).contains(key)
}
/// AT-SPI roles as words. /// AT-SPI roles as words.
fn role_words(role: &str) -> String { fn role_words(role: &str) -> String {
@ -2178,19 +2414,23 @@ fn box_look(script: Option<&str>, after: Option<String>, pointer: bool) -> Resul
let t_all = Instant::now(); let t_all = Instant::now();
// The picture is captured by a background `import` while the controls are read (the a11y // The picture is captured by a background `import` while the controls are read (the a11y
// read is the slow part on web pages); a JPEG costs less to make and to ship than a PNG. // read is the slow part on web pages); a JPEG costs less to make and to ship than a PNG.
let look = "( import -window root -quality 90 jpeg:- 2>/dev/null > /tmp/anybot-look.jpg & ip=$!; \ let key = current_screen();
sleep 0.18; anybot-a11y --budget 3 > /tmp/anybot-look.json 2>/dev/null || echo '{\"elements\":[]}' > /tmp/anybot-look.json; \ let tag = screen_tag(&key);
let look = format!(
"( import -window root -quality 90 jpeg:- 2>/dev/null > /tmp/anybot-look-{tag}.jpg & ip=$!; \
sleep 0.18; anybot-a11y --budget 3 > /tmp/anybot-look-{tag}.json 2>/dev/null || echo '{{\"elements\":[]}}' > /tmp/anybot-look-{tag}.json; \
printf '%s\\n' \"$(xdotool getactivewindow getwindowname 2>/dev/null | tr -d '\\n')\"; \ printf '%s\\n' \"$(xdotool getactivewindow getwindowname 2>/dev/null | tr -d '\\n')\"; \
wc -c < /tmp/anybot-look.json; cat /tmp/anybot-look.json; wait $ip; cat /tmp/anybot-look.jpg )"; wc -c < /tmp/anybot-look-{tag}.json; cat /tmp/anybot-look-{tag}.json; wait $ip; cat /tmp/anybot-look-{tag}.jpg )"
);
let full = match script { let full = match script {
Some(s) => format!("{{ {s}; }} || exit $?; {SETTLE_SH}; {look}"), Some(s) => format!("{} {{ {s}; }} || exit $?; {SETTLE_SH}; {look}", screen_sh(&key)),
None => look.to_string(), None => format!("{} {look}", screen_sh(&key)),
}; };
let out = match dk_with_input(&["exec", "-i", "-u", "bot", "-e", "DISPLAY=:1", container(), "sh", "-c", &full], Some(b""), 30_000) { let out = match dk_with_input(&["exec", "-i", "-u", "bot", "-e", "DISPLAY=:1", container(), "sh", "-c", &full], Some(b""), 30_000) {
Ok(o) => o, Ok(o) => o,
Err(e) if e == "逾時" => return Err("這台電腦太久沒有回應".into()), Err(e) if e == "逾時" => return Err("這台電腦太久沒有回應".into()),
Err(e) if e.is_empty() => return Err("這一步沒有成功".into()), Err(e) if e.is_empty() => return Err("這一步沒有成功".into()),
Err(e) => return Err(format!("xdotool:{e}")), Err(e) => return Err(screen_full(&e).unwrap_or_else(|| format!("xdotool:{e}"))),
}; };
let exec_ms = t_all.elapsed().as_millis() as u64; let exec_ms = t_all.elapsed().as_millis() as u64;
// "<front window's title>\n<bytes of the list>\n<list JSON><JPEG>" // "<front window's title>\n<bytes of the list>\n<list JSON><JPEG>"
@ -2203,20 +2443,17 @@ fn box_look(script: Option<&str>, after: Option<String>, pointer: bool) -> Resul
let tree: Value = serde_json::from_slice(&out[nl + 1..json_end]).unwrap_or(Value::Null); let tree: Value = serde_json::from_slice(&out[nl + 1..json_end]).unwrap_or(Value::Null);
let img = image::load_from_memory(&out[json_end..]).map_err(|e| format!("截圖讀不出來:{e}"))?.to_rgb8(); let img = image::load_from_memory(&out[json_end..]).map_err(|e| format!("截圖讀不出來:{e}"))?.to_rgb8();
let (w, h) = img.dimensions(); let (w, h) = img.dimensions();
shared().lock().unwrap_or_else(|e| e.into_inner()).size = Some((w, h)); with_screen(|st| st.size = Some((w, h)));
// The window in front comes first (its controls numbered first, never crowded out by a // The window in front comes first (its controls numbered first, never crowded out by a
// window left open behind it), like a person looks at what's in front of them. // window left open behind it), like a person looks at what's in front of them.
let mut els = elements_of(&tree); let mut els = elements_of(&tree);
if !front.is_empty() { if !front.is_empty() {
els.sort_by_key(|e| e.window != front); els.sort_by_key(|e| e.window != front);
} }
// Numbers kept from the last look where the same control is still there (marks::Numbering). // Numbers kept from the last look where the same control is still there (marks::Numbering),
static NUMBERS: Mutex<Option<crate::marks::Numbering>> = Mutex::new(None); // each screen its own.
let (numbered, lines, spots) = { let (numbered, lines, spots) = with_screen(|st| crate::marks::number_keeping(&els, false, st.numbers.get_or_insert_with(Default::default)));
let mut m = NUMBERS.lock().unwrap_or_else(|e| e.into_inner()); with_screen(|st| st.spots = Some(spots));
crate::marks::number_keeping(&els, false, m.get_or_insert_with(Default::default))
};
*BOX_SPOTS.lock().unwrap_or_else(|e| e.into_inner()) = Some(spots);
let (fw, fh, resize) = crate::computer::fit(w, h); let (fw, fh, resize) = crate::computer::fit(w, h);
let mut pic = if resize { image::imageops::resize(&img, fw, fh, image::imageops::FilterType::Triangle) } else { img }; let mut pic = if resize { image::imageops::resize(&img, fw, fh, image::imageops::FilterType::Triangle) } else { img };
let fp = crate::marks::fingerprint(&els) ^ crate::marks::picture_fingerprint(&pic).rotate_left(1); let fp = crate::marks::fingerprint(&els) ^ crate::marks::picture_fingerprint(&pic).rotate_left(1);
@ -2232,12 +2469,11 @@ fn box_look(script: Option<&str>, after: Option<String>, pointer: bool) -> Resul
let mut text = after.clone().map(|n| format!("{n}\n")).unwrap_or_default(); let mut text = after.clone().map(|n| format!("{n}\n")).unwrap_or_default();
text.push_str(&secret_note); text.push_str(&secret_note);
text.push_str(&format!("螢幕截圖({fw}×{fh},Linux 桌面)。")); text.push_str(&format!("螢幕截圖({fw}×{fh},Linux 桌面)。"));
let unchanged = { let unchanged = with_screen(|st| {
let mut last = BOX_LAST.lock().unwrap_or_else(|e| e.into_inner()); let same = pointer && after.is_some() && st.last == Some(fp);
let same = pointer && after.is_some() && *last == Some(fp); st.last = Some(fp);
*last = Some(fp);
same same
}; });
if unchanged { if unchanged {
text.push_str(crate::computer::NOOP_NOTE); text.push_str(crate::computer::NOOP_NOTE);
} }
@ -2247,12 +2483,13 @@ fn box_look(script: Option<&str>, after: Option<String>, pointer: bool) -> Resul
text.push_str(&format!("\n可以操作的東西(圖上同樣的編號,用 ref 點):\n{}", lines.join("\n"))); text.push_str(&format!("\n可以操作的東西(圖上同樣的編號,用 ref 點):\n{}", lines.join("\n")));
} }
// What moved since the last look (same signal the Mac path gives the quick model). // What moved since the last look (same signal the Mac path gives the quick model).
static LAST_ELS: Mutex<Vec<crate::marks::Element>> = Mutex::new(Vec::new());
{ {
let cur: Vec<crate::marks::Element> = numbered.iter().map(|(_, e)| e.clone()).collect(); let cur: Vec<crate::marks::Element> = numbered.iter().map(|(_, e)| e.clone()).collect();
let mut last = LAST_ELS.lock().unwrap_or_else(|e| e.into_inner()); let d = with_screen(|st| {
let d = crate::marks::diff(&last, &cur); let d = crate::marks::diff(&st.els, &cur);
*last = cur; st.els = cur;
d
});
if !d.is_empty() { if !d.is_empty() {
text.push_str(&format!("\n跟上一張圖相比:\n{}", d.join("\n"))); text.push_str(&format!("\n跟上一張圖相比:\n{}", d.join("\n")));
} }
@ -2325,14 +2562,19 @@ fn open_on_box(app: &str) -> Result<String, String> {
/// Run a computer_use tool on the box. Returns (text, screenshot as base64 JPEG). /// Run a computer_use tool on the box. Returns (text, screenshot as base64 JPEG).
/// One screen step on the box at a time: two bots acting at once shared the picture files and the /// One screen step on the box at a time: two bots acting at once shared the picture files and the
/// numbers (a torn picture, or a number resolved against the other bot's picture). /// numbers (a torn picture, or a number resolved against the other bot's picture).
static BOX_STEP: Mutex<()> = Mutex::new(()); /// Each screen its own: bots on their own screens don't wait for each other.
fn step_lock() -> std::sync::Arc<Mutex<()>> {
static L: OnceLock<Mutex<std::collections::HashMap<String, std::sync::Arc<Mutex<()>>>>> = OnceLock::new();
L.get_or_init(|| Mutex::new(std::collections::HashMap::new())).lock().unwrap_or_else(|e| e.into_inner()).entry(current_screen()).or_default().clone()
}
pub fn computer_run(name: &str, v: &Value) -> Result<(String, Option<String>), String> { pub fn computer_run(name: &str, v: &Value) -> Result<(String, Option<String>), String> {
let _one = BOX_STEP.lock().unwrap_or_else(|e| e.into_inner()); let lock = step_lock();
let _one = lock.lock().unwrap_or_else(|e| e.into_inner());
// A control named instead of numbered (「按 4」): its number in the latest look. // A control named instead of numbered (「按 4」): its number in the latest look.
let mut named = v.clone(); let mut named = v.clone();
if matches!(name, "computer_use_click" | "computer_use_typing" | "computer_use_scroll" | "computer_use_mouse_move" | "computer_use_batch") { if matches!(name, "computer_use_click" | "computer_use_typing" | "computer_use_scroll" | "computer_use_mouse_move" | "computer_use_batch") {
let spots = BOX_SPOTS.lock().unwrap_or_else(|e| e.into_inner()).clone(); let spots = with_screen(|st| st.spots.clone());
crate::marks::names_to_numbers(&mut named, spots.as_ref())?; crate::marks::names_to_numbers(&mut named, spots.as_ref())?;
} }
let v = &named; let v = &named;
@ -2342,14 +2584,15 @@ pub fn computer_run(name: &str, v: &Value) -> Result<(String, Option<String>), S
"computer_use_check_permissions" => return Ok(("這台電腦不需要另外的權限:可以截圖,也可以操作滑鼠和鍵盤。".into(), None)), "computer_use_check_permissions" => return Ok(("這台電腦不需要另外的權限:可以截圖,也可以操作滑鼠和鍵盤。".into(), None)),
"computer_use_screenshot" => return box_look(None, None, false), "computer_use_screenshot" => return box_look(None, None, false),
"computer_use_zoom" => { "computer_use_zoom" => {
let out = dk_with_input(&["exec", "-i", "-u", "bot", "-e", "DISPLAY=:1", container(), "sh", "-c", "import -window root png:- 2>/dev/null"], Some(b""), 30_000).map_err(|e| format!("拍不到畫面:{e}"))?; let shot = format!("{} import -window root png:- 2>/dev/null", screen_sh(&current_screen()));
let out = dk_with_input(&["exec", "-i", "-u", "bot", "-e", "DISPLAY=:1", container(), "sh", "-c", &shot], Some(b""), 30_000).map_err(|e| format!("拍不到畫面:{e}"))?;
let img = image::load_from_memory(&out).map_err(|e| format!("截圖讀不出來:{e}"))?.to_rgb8(); let img = image::load_from_memory(&out).map_err(|e| format!("截圖讀不出來:{e}"))?.to_rgb8();
return crate::computer::zoom(&img, v).map(|(t, j)| (t, Some(j))); return crate::computer::zoom(&img, v).map(|(t, j)| (t, Some(j)));
} }
"computer_use_show" => return box_show(), "computer_use_show" => return box_show(),
_ => {} _ => {}
} }
if HELD_BY_PERSON.load(Ordering::SeqCst) || crate::vnc::person_active() { if is_held(&current_screen()) || crate::vnc::person_active() {
return Err("使用者正在自己操作這台電腦。請等他操作完(停下幾秒後)再繼續,或先截圖看看畫面。".into()); return Err("使用者正在自己操作這台電腦。請等他操作完(停下幾秒後)再繼續,或先截圖看看畫面。".into());
} }
if name == "computer_use_open_app" { if name == "computer_use_open_app" {
@ -2365,7 +2608,8 @@ pub fn computer_run(name: &str, v: &Value) -> Result<(String, Option<String>), S
/// The box's screen as the person would see it (no numbers), at the bot's picture size. /// The box's screen as the person would see it (no numbers), at the bot's picture size.
fn box_show() -> Result<(String, Option<String>), String> { fn box_show() -> Result<(String, Option<String>), String> {
let out = dk_with_input(&["exec", "-i", "-u", "bot", "-e", "DISPLAY=:1", container(), "sh", "-c", "import -window root -quality 90 jpeg:- 2>/dev/null"], Some(b""), 30_000).map_err(|e| format!("拍不到畫面:{e}"))?; let shot = format!("{} import -window root -quality 90 jpeg:- 2>/dev/null", screen_sh(&current_screen()));
let out = dk_with_input(&["exec", "-i", "-u", "bot", "-e", "DISPLAY=:1", container(), "sh", "-c", &shot], Some(b""), 30_000).map_err(|e| format!("拍不到畫面:{e}"))?;
let img = image::load_from_memory(&out).map_err(|e| format!("截圖讀不出來:{e}"))?.to_rgb8(); let img = image::load_from_memory(&out).map_err(|e| format!("截圖讀不出來:{e}"))?.to_rgb8();
let (w, h) = img.dimensions(); let (w, h) = img.dimensions();
let (fw, fh, resize) = crate::computer::fit(w, h); let (fw, fh, resize) = crate::computer::fit(w, h);
@ -2374,7 +2618,10 @@ fn box_show() -> Result<(String, Option<String>), String> {
Ok((format!("{}({fw}×{fh})", crate::computer::SHOWN_NOTE), Some(base64::engine::general_purpose::STANDARD.encode(&jpeg)))) Ok((format!("{}({fw}×{fh})", crate::computer::SHOWN_NOTE), Some(base64::engine::general_purpose::STANDARD.encode(&jpeg))))
} }
const BATCH_MARK: &str = "/tmp/anybot-batch.done"; /// Where a batch counts its steps (one file per screen).
fn batch_mark() -> String {
format!("/tmp/anybot-batch-{}.done", screen_tag(&current_screen()))
}
/// Do a planned sequence of steps on the box in one round trip: the steps' scripts chained with /// Do a planned sequence of steps on the box in one round trip: the steps' scripts chained with
/// `&&` (so the chain stops at the first failure), one marker line per step that ran, and one /// `&&` (so the chain stops at the first failure), one marker line per step that ran, and one
@ -2393,13 +2640,14 @@ fn box_batch(v: &Value, scale: (f64, f64)) -> Result<(String, Option<String>), S
for (i, a) in acts.iter().enumerate() { for (i, a) in acts.iter().enumerate() {
let name = crate::computer::action_tool(a["action"].as_str().unwrap_or(""))?; let name = crate::computer::action_tool(a["action"].as_str().unwrap_or(""))?;
let (script, note) = box_script(name, a, scale)?; let (script, note) = box_script(name, a, scale)?;
parts.push(format!("{{ {script} && echo x >> {BATCH_MARK}; }}")); parts.push(format!("{{ {script} && echo x >> {}; }}", batch_mark()));
notes.push(format!("{}. {note}", i + 1)); notes.push(format!("{}. {note}", i + 1));
} }
// The chain runs in the same call as the picture; one more call reads how far it got. // The chain runs in the same call as the picture; one more call reads how far it got.
let chain = format!("rm -f {BATCH_MARK}; {} ; true", parts.join(" && ")); let mark = batch_mark();
let chain = format!("rm -f {mark}; {} ; true", parts.join(" && "));
let (text, pic) = box_look(Some(&chain), Some(String::new()), false)?; let (text, pic) = box_look(Some(&chain), Some(String::new()), false)?;
let done = dk(&["exec", container(), "sh", "-c", &format!("wc -l < {BATCH_MARK} 2>/dev/null || echo 0; rm -f {BATCH_MARK}")]) let done = dk(&["exec", container(), "sh", "-c", &format!("wc -l < {mark} 2>/dev/null || echo 0; rm -f {mark}")])
.ok() .ok()
.and_then(|s| s.trim().parse::<usize>().ok()) .and_then(|s| s.trim().parse::<usize>().ok())
.unwrap_or(0) .unwrap_or(0)
@ -2505,6 +2753,11 @@ fn published_port() -> u16 {
/// The noVNC address on this Mac (through an SSH tunnel when the box is on another host). /// The noVNC address on this Mac (through an SSH tunnel when the box is on another host).
pub fn viewer_url(control: bool) -> Result<String, String> { pub fn viewer_url(control: bool) -> Result<String, String> {
viewer_url_of("", control)
}
/// The same, showing `key`'s screen (its own, 每個 Bot 一個螢幕; "" the shared one).
pub fn viewer_url_of(key: &str, control: bool) -> Result<String, String> {
ensure_running()?; ensure_running()?;
let port = published_port(); let port = published_port();
let host = docker_host(); let host = docker_host();
@ -2537,7 +2790,9 @@ pub fn viewer_url(control: bool) -> Result<String, String> {
port port
}; };
// noVNC signs in with the box's VNC password (x11vnc refuses the keyless login now). // noVNC signs in with the box's VNC password (x11vnc refuses the keyless login now).
Ok(format!("http://127.0.0.1:{local_port}/vnc.html?autoconnect=1&resize=scale&reconnect=1&show_dot=1&password={}{}", vnc_password(), if control { "" } else { "&view_only=1" })) // The box's one web viewer reaches every screen by its token (box/start.sh, box/screen).
let token = crate::httpd::url_encode(&format!("websockify?token={}", screen_tag(key)));
Ok(format!("http://127.0.0.1:{local_port}/vnc.html?autoconnect=1&resize=scale&reconnect=1&show_dot=1&password={}{}&path={token}", vnc_password(), if control { "" } else { "&view_only=1" }))
} }
pub fn shutdown() { pub fn shutdown() {
@ -2582,7 +2837,7 @@ mod tests {
// What the box runs: the field clicked, its text selected, the address pasted in one go. // What the box runs: the field clicked, its text selected, the address pasted in one go.
let els = vec![crate::marks::Element { kind: "輸入框".into(), name: "Address and search bar".into(), value: "about:blank".into(), x: 100.0, y: 50.0, w: 400.0, h: 30.0, active: true, flags: vec![], window: "Chromium".into() }]; let els = vec![crate::marks::Element { kind: "輸入框".into(), name: "Address and search bar".into(), value: "about:blank".into(), x: 100.0, y: 50.0, w: 400.0, h: 30.0, active: true, flags: vec![], window: "Chromium".into() }];
let (_, _, spots) = crate::marks::number_keeping(&els, false, &mut Default::default()); let (_, _, spots) = crate::marks::number_keeping(&els, false, &mut Default::default());
*BOX_SPOTS.lock().unwrap() = Some(spots); with_screen(|st| st.spots = Some(spots));
let (script, _) = box_script("computer_use_typing", &serde_json::json!({"ref": "1", "value": "chrome://settings/search", "submit": true}), (1.0, 1.0)).unwrap(); let (script, _) = box_script("computer_use_typing", &serde_json::json!({"ref": "1", "value": "chrome://settings/search", "submit": true}), (1.0, 1.0)).unwrap();
assert!(script.contains("click 1") && script.contains("ctrl+a") && script.contains("xclip") && script.contains("ctrl+v") && !script.contains("xdotool type"), "{script}"); assert!(script.contains("click 1") && script.contains("ctrl+a") && script.contains("xclip") && script.contains("ctrl+v") && !script.contains("xdotool type"), "{script}");
} }
@ -2595,7 +2850,10 @@ mod tests {
for c in ["echo pseudo code", "ls sudoers.d", "cat /etc/sudoers", "grep sudo_user log"] { for c in ["echo pseudo code", "ls sudoers.d", "cat /etc/sudoers", "grep sudo_user log"] {
assert!(!uses_sudo(c), "{c}"); assert!(!uses_sudo(c), "{c}");
} }
assert!(exec_wrapper("/home/bot/bot-1", "sudo apt-get install -y tree", false, false, "j").contains("-u root")); let w = exec_wrapper("/home/bot/bot-1", "sudo apt-get install -y tree", false, false, "j");
assert!(w.contains("-u root"));
// What root left anywhere in the bot's home goes back to the bot, not only in its folder.
assert!(w.contains("find -P '\\''/home/bot'\\'' -xdev -user root"), "{w}");
assert!(exec_wrapper("/home/bot/bot-1", "ls", false, false, "j").contains("-u bot")); assert!(exec_wrapper("/home/bot/bot-1", "ls", false, false, "j").contains("-u bot"));
} }
@ -2635,7 +2893,10 @@ mod tests {
assert!(sc.starts_with(r"xdotool type --clearmodifiers --delay 12 -- 'it'\''s a '\''test'\'''") && sc.ends_with("xdotool key --clearmodifiers Return"), "{sc}"); assert!(sc.starts_with(r"xdotool type --clearmodifiers --delay 12 -- 'it'\''s a '\''test'\'''") && sc.ends_with("xdotool key --clearmodifiers Return"), "{sc}");
// Another language, or long text: pasted (key by key, 2,000 letters outlasted the step). // Another language, or long text: pasted (key by key, 2,000 letters outlasted the step).
let (sc, _) = box_script("computer_use_typing", &serde_json::json!({"value": "中文"}), s).unwrap(); let (sc, _) = box_script("computer_use_typing", &serde_json::json!({"value": "中文"}), s).unwrap();
assert!(sc.contains("printf '%s' '中文' > /tmp/anybot-paste.txt") && sc.contains("xclip"), "{sc}"); assert!(sc.contains("printf '%s' '中文' > /tmp/anybot-paste-main.txt") && sc.contains("xclip"), "{sc}");
// Each screen pastes from its own file (two bots typing at once don't swap texts).
let (sc, _) = on_screen("bot9", || box_script("computer_use_typing", &serde_json::json!({"value": "中文"}), s)).unwrap();
assert!(sc.contains("/tmp/anybot-paste-bot9.txt"), "{sc}");
let (sc, _) = box_script("computer_use_typing", &serde_json::json!({"value": "a".repeat(TYPE_KEYS_MAX_CHARS + 1)}), s).unwrap(); let (sc, _) = box_script("computer_use_typing", &serde_json::json!({"value": "a".repeat(TYPE_KEYS_MAX_CHARS + 1)}), s).unwrap();
assert!(sc.contains("xclip") && !sc.contains("xdotool type"), "{sc}"); assert!(sc.contains("xclip") && !sc.contains("xdotool type"), "{sc}");
// Keys by name, a character typed (without swallowing the keys after it), several in order. // Keys by name, a character typed (without swallowing the keys after it), several in order.
@ -2747,7 +3008,7 @@ mod tests {
std::thread::sleep(Duration::from_millis(500)); std::thread::sleep(Duration::from_millis(500));
let page_spots = || -> Vec<(f64, f64, String)> { let page_spots = || -> Vec<(f64, f64, String)> {
computer_run("computer_use_screenshot", &serde_json::json!({})).unwrap(); computer_run("computer_use_screenshot", &serde_json::json!({})).unwrap();
let spots = BOX_SPOTS.lock().unwrap().clone().unwrap(); let spots = with_screen(|st| st.spots.clone()).unwrap();
spots.by_number.values().filter(|(_, w)| w.contains("「L")).map(|((x, y), w)| (*x, *y, w.clone())).collect() spots.by_number.values().filter(|(_, w)| w.contains("「L")).map(|((x, y), w)| (*x, *y, w.clone())).collect()
}; };
let top = crate::botbrowser::in_box(|| crate::botbrowser::eval_current(None, "window.outerHeight - window.innerHeight")).map(|(_, v)| v.as_f64().unwrap_or(87.0)).unwrap_or(87.0); let top = crate::botbrowser::in_box(|| crate::botbrowser::eval_current(None, "window.outerHeight - window.innerHeight")).map(|(_, v)| v.as_f64().unwrap_or(87.0)).unwrap_or(87.0);
@ -2771,6 +3032,76 @@ mod tests {
println!("page links numbered: {} in view, {} with a terminal over the page (top of page area {top})", seen.len(), covered.len()); println!("page links numbered: {} in view, {} with a terminal over the page (top of page area {top})", seen.len(), covered.len());
} }
/// 每個 Bot 一個螢幕, on the real Docker (a box of its own: ANYBOT_BOX_NAME, ANYBOT_BOX_IMAGE,
/// ANYBOT_BOX_VOLUME and a scratch ANYBOT_DATA_DIR, so a box in use isn't touched):
/// `cargo test -- --ignored each_bot_has_its_own_screen --nocapture`.
/// Two bots open a terminal each, at once: each sees only its own; each one's typing lands in
/// its own; their browsers are two (two ports), the second bot's starting with the shared
/// logins; the viewer and the thumbnails reach each screen; a full box says so; idle closes.
#[test]
#[ignore]
fn each_bot_has_its_own_screen() {
ensure_running().expect("box starts");
let titles = |key: &str| -> String {
on_screen(key, || box_exec("for w in $(xdotool search --onlyvisible --name . 2>/dev/null); do xdotool getwindowname $w; done | sort -u")).unwrap()
};
// Two bots at once, each a terminal titled with its name (a plain shell keeps the title).
let (a, b) = ("bot901", "bot902");
let one = std::thread::spawn(move || on_screen(a, || box_exec("(setsid xterm -T term-alpha -e bash --norc >/dev/null 2>&1 &); sleep 2; echo ok")));
let two = std::thread::spawn(move || on_screen(b, || box_exec("(setsid xterm -T term-beta -e bash --norc >/dev/null 2>&1 &); sleep 2; echo ok")));
assert!(one.join().unwrap().is_ok() && two.join().unwrap().is_ok());
let (ta, tb) = (titles(a), titles(b));
println!("bot901 sees: {ta:?}\nbot902 sees: {tb:?}");
assert!(ta.contains("term-alpha") && !ta.contains("term-beta"), "{ta}");
assert!(tb.contains("term-beta") && !tb.contains("term-alpha"), "{tb}");
assert!(!titles("").contains("term-alpha"), "the shared screen has neither");
// Each bot's look: its own numbers, each screen's own picture.
let (la, pa) = on_screen(a, || computer_run("computer_use_screenshot", &serde_json::json!({}))).unwrap();
let (_, pb) = on_screen(b, || computer_run("computer_use_screenshot", &serde_json::json!({}))).unwrap();
assert!(pa.is_some() && pb.is_some() && pa != pb, "two pictures");
println!("bot901's look:\n{}", la.lines().take(6).collect::<Vec<_>>().join("\n"));
// Typing goes to the bot's own terminal.
let _ = dk(&["exec", "-u", "bot", container(), "rm", "-f", "/tmp/screen-a.txt", "/tmp/screen-b.txt"]);
on_screen(a, || computer_run("computer_use_typing", &serde_json::json!({"value": "echo A > /tmp/screen-a.txt", "submit": true}))).unwrap();
on_screen(b, || computer_run("computer_use_typing", &serde_json::json!({"value": "echo B > /tmp/screen-b.txt", "submit": true}))).unwrap();
std::thread::sleep(Duration::from_millis(800));
let got = dk(&["exec", "-u", "bot", container(), "sh", "-c", "cat /tmp/screen-a.txt /tmp/screen-b.txt"]).unwrap();
assert_eq!(got.split_whitespace().collect::<Vec<_>>(), vec!["A", "B"]);
// Two browsers, two ports; each on its own screen.
let pa = on_screen(a, browser_port).expect("bot901's browser");
let pb = on_screen(b, browser_port).expect("bot902's browser");
assert_ne!(pa, pb, "each bot its own browser");
assert!(on_screen(a, browser_running) && on_screen(b, browser_running));
assert!(titles(a).to_lowercase().contains("chromium") || titles(a).contains("about:blank"), "{}", titles(a));
// The viewer reaches each screen by its token; thumbnails too.
let tokens = dk(&["exec", container(), "cat", "/tmp/anybot-vnc-tokens"]).unwrap();
assert!(tokens.contains("main: localhost:5900") && tokens.contains("bot901: localhost:") && tokens.contains("bot902: localhost:"), "{tokens}");
assert!(viewer_url_of(a, false).unwrap().contains("token%3Dbot901"));
assert!(thumbnail_of(a, 320).is_some() && thumbnail_of("bot999", 320).is_none());
let open: Vec<String> = open_screens().into_iter().map(|(k, _)| k).collect();
assert!(open.contains(&a.to_string()) && open.contains(&b.to_string()), "{open:?}");
// A 支線 beside bot901: a temporary screen of its own whose browser starts as a copy of
// bot901's (what bot901's profile has, the branch's has), and is gone with the screen.
let _ = dk(&["exec", "-u", "bot", container(), "sh", "-c", "mkdir -p '/home/bot/.config/anybot-profiles/bot901/Default/Local Storage' && echo yes > '/home/bot/.config/anybot-profiles/bot901/Default/Local Storage/anybot-branch-mark'"]);
let t = branch_screen(a, 57);
assert_eq!(t, "bot901-t57");
let pt = on_screen(&t, browser_port).expect("the branch's browser");
assert_ne!(Some(pt), on_screen(a, browser_port).ok());
let copied = dk(&["exec", "-u", "bot", container(), "sh", "-c", "cat '/home/bot/.config/anybot-profiles/bot901-t57/Default/Local Storage/anybot-branch-mark'"]).unwrap_or_default();
assert_eq!(copied.trim(), "yes", "the branch's browser starts from bot901's");
assert!(titles(&t).to_lowercase().contains("chromium") || titles(&t).contains("about:blank"), "{}", titles(&t));
assert!(!titles(a).contains("term-beta"));
close_screen(&t);
let left = dk(&["exec", container(), "sh", "-c", "ls /home/bot/.config/anybot-profiles"]).unwrap();
assert!(left.contains("bot901") && !left.contains("bot901-t57"), "the copy goes with the screen: {left}");
assert!(!open_screens().iter().any(|(k, _)| *k == t));
// Idle: closed (the browser too).
reap_screens(0);
assert!(open_screens().is_empty(), "{:?}", open_screens());
assert!(!titles("").contains("term-beta"));
println!("each bot had its own screen; idle ones closed");
}
/// Uses the real Docker: `cargo test --release -- --ignored box_screen_is_exact --nocapture`. /// Uses the real Docker: `cargo test --release -- --ignored box_screen_is_exact --nocapture`.
/// The bot's clicks land where its picture says, the same spot twice doesn't hang, typing (ASCII, Chinese, a key by name) reaches the app, /// The bot's clicks land where its picture says, the same spot twice doesn't hang, typing (ASCII, Chinese, a key by name) reaches the app,
/// and every step comes back with the screen after it. /// and every step comes back with the screen after it.
@ -2787,7 +3118,7 @@ mod tests {
let (fw, fh, _) = crate::computer::fit(w, h); let (fw, fh, _) = crate::computer::fit(w, h);
println!("desktop {w}×{h}, picture {fw}×{fh}"); println!("desktop {w}×{h}, picture {fw}×{fh}");
// A move, in the bot's picture pixels, with no screenshot taken first. // A move, in the bot's picture pixels, with no screenshot taken first.
shared().lock().unwrap().size = None; with_screen(|st| st.size = None);
let (txt, img) = computer_run("computer_use_mouse_move", &serde_json::json!({"x": fw / 2, "y": fh / 2})).unwrap(); let (txt, img) = computer_run("computer_use_mouse_move", &serde_json::json!({"x": fw / 2, "y": fh / 2})).unwrap();
assert!(img.is_some(), "a picture comes back: {txt}"); assert!(img.is_some(), "a picture comes back: {txt}");
assert_eq!(pointer(), ((w / 2) as i64, (h / 2) as i64)); assert_eq!(pointer(), ((w / 2) as i64, (h / 2) as i64));
@ -3092,7 +3423,37 @@ mod tests {
use chrono::TimeZone; use chrono::TimeZone;
let at = chrono::Utc.with_ymd_and_hms(2026, 11, 6, 19, 0, 0).unwrap().with_timezone(&chrono_tz::Asia::Taipei); let at = chrono::Utc.with_ymd_and_hms(2026, 11, 6, 19, 0, 0).unwrap().with_timezone(&chrono_tz::Asia::Taipei);
assert!(in_schedule_window("03:00", at.time())); assert!(in_schedule_window("03:00", at.time()));
assert_eq!(wanted_version(), "9"); assert_eq!(wanted_version(), "10");
// Every file the Dockerfile copies is one this app carries (build_image writes them).
let carried = ["start.sh", "fluxbox-init", "overlay", "Xresources", "menu", "a11y", "browser", "screen"];
for l in DOCKERFILE.lines().filter_map(|l| l.trim().strip_prefix("COPY ")) {
let src = l.split_whitespace().next().unwrap();
assert!(carried.contains(&src), "the Dockerfile copies {src}, which build_image doesn't write");
}
// 每個 Bot 一個螢幕: a bot's folder names its screen; any other folder is the shared one.
assert_eq!(screen_of_dir("/home/bot/bot-12"), "bot12");
assert_eq!(screen_of_dir("/home/bot/bot-12/"), "bot12");
assert_eq!(screen_of_bot(7), "bot7");
assert_eq!(screen_of_dir("/home/bot"), "");
assert_eq!(screen_of_dir("/home/bot/bot-x1"), "");
assert!(screen_sh("").contains("DISPLAY=:1") && screen_sh("bot12").contains("anybot-screen up bot12"));
assert!(screen_full("FULL=bot1 bot2 bot3").unwrap().contains("3 個"));
assert!(screen_full("xdotool: oops").is_none());
// Each screen remembers its own numbers.
on_screen("bot1", || with_screen(|st| st.last = Some(1)));
on_screen("bot2", || with_screen(|st| st.last = Some(2)));
assert_eq!(on_screen("bot1", || with_screen(|st| st.last)), Some(1));
assert_eq!(current_screen(), "");
// A person holding one bot's screen doesn't stop the others.
hold("bot1", true);
assert!(is_held("bot1") && !is_held("bot2") && HELD_BY_PERSON.load(Ordering::SeqCst));
hold("bot1", false);
assert!(!is_held("bot1") && !HELD_BY_PERSON.load(Ordering::SeqCst));
// What viewers name (a bot) maps to the screen the brain published.
set_bot_screens([(5u64, "bot5".to_string())].into_iter().collect());
assert_eq!(screen_for_bot("5"), "bot5");
assert_eq!(screen_for_bot("6"), "");
assert_eq!(screen_for_bot("x"), "");
} }
#[test] #[test]

View File

@ -319,8 +319,14 @@ fn spawn_error(command: &str, e: &std::io::Error) -> String {
} }
/// A folder the server is given that isn't on this computer (its parent isn't either): usually a /// A folder the server is given that isn't on this computer (its parent isn't either): usually a
/// connector made on another computer, e.g. a Mac's /Users/… on a Linux brain. /// connector made on another computer, e.g. a Mac's /Users/… on a Linux brain. Not for a server
fn missing_folder(args: &[String]) -> Option<&str> { /// that runs somewhere else (`docker exec box /home/…`, `ssh host /opt/…`): its paths are there.
fn missing_folder<'a>(command: &str, args: &'a [String]) -> Option<&'a str> {
const ELSEWHERE: [&str; 8] = ["docker", "podman", "nerdctl", "kubectl", "ssh", "wsl", "orb", "lxc"];
let program = std::path::Path::new(command.trim()).file_name().and_then(|n| n.to_str()).unwrap_or("");
if ELSEWHERE.contains(&program.trim_end_matches(".exe")) {
return None;
}
args.iter().map(|a| a.trim()).find(|a| { args.iter().map(|a| a.trim()).find(|a| {
let p = std::path::Path::new(a); let p = std::path::Path::new(a);
p.is_absolute() && !p.exists() && p.parent().is_some_and(|d| d != std::path::Path::new("/") && !d.exists()) p.is_absolute() && !p.exists() && p.parent().is_some_and(|d| d != std::path::Path::new("/") && !d.exists())
@ -344,7 +350,7 @@ fn connect(config: &Server) -> Result<Conn, String> {
if s.command.trim().is_empty() { if s.command.trim().is_empty() {
return Err("請給指令或網址".into()); return Err("請給指令或網址".into());
} }
if let Some(dir) = missing_folder(&s.args) { if let Some(dir) = missing_folder(&s.command, &s.args) {
return Err(format!("這台電腦上沒有「{dir}」:這個連接器可能是在別台電腦設定的,改成這台的資料夾,或移除它")); return Err(format!("這台電腦上沒有「{dir}」:這個連接器可能是在別台電腦設定的,改成這台的資料夾,或移除它"));
} }
let mut cmd = Command::new(s.command.trim()); let mut cmd = Command::new(s.command.trim());
@ -1062,9 +1068,12 @@ for line in sys.stdin:
assert!(spawn_error("/usr/bin/uvx", &nf).contains("uv")); assert!(spawn_error("/usr/bin/uvx", &nf).contains("uv"));
assert!(spawn_error("my-server", &nf).contains("找不到「my-server」")); assert!(spawn_error("my-server", &nf).contains("找不到「my-server」"));
let s = |args: &[&str]| args.iter().map(|a| a.to_string()).collect::<Vec<_>>(); let s = |args: &[&str]| args.iter().map(|a| a.to_string()).collect::<Vec<_>>();
assert_eq!(missing_folder(&s(&["-y", "x", "/Users-nobody-here/someone/Documents"])), Some("/Users-nobody-here/someone/Documents")); assert_eq!(missing_folder("npx", &s(&["-y", "x", "/Users-nobody-here/someone/Documents"])), Some("/Users-nobody-here/someone/Documents"));
// A server in a container or on another host: its paths are there, not here.
assert_eq!(missing_folder("docker", &s(&["exec", "-i", "box", "/home-nobody-here/bot/.local/bin/cua-driver", "mcp"])), None);
assert_eq!(missing_folder("/usr/bin/ssh", &s(&["host", "/opt-nobody-here/srv/mcp"])), None);
let tmp = std::env::temp_dir().join("anybot-mcp-new-file.json"); let tmp = std::env::temp_dir().join("anybot-mcp-new-file.json");
assert_eq!(missing_folder(&s(&[tmp.to_str().unwrap(), "/api", "relative/dir"])), None, "a file to be made, a top-level name and a relative path are fine"); assert_eq!(missing_folder("npx", &s(&[tmp.to_str().unwrap(), "/api", "relative/dir"])), None, "a file to be made, a top-level name and a relative path are fine");
let one = |command: &str, args: &[&str], url: &str| Server { name: "x".into(), command: command.into(), args: s(args), url: url.into(), ..serde_json::from_str("{\"name\":\"x\"}").unwrap() }; let one = |command: &str, args: &[&str], url: &str| Server { name: "x".into(), command: command.into(), args: s(args), url: url.into(), ..serde_json::from_str("{\"name\":\"x\"}").unwrap() };
let e = connect(&one("npx", &["-y", "@modelcontextprotocol/server-filesystem", "/Users-nobody-here/someone/Documents"], "")).err().unwrap(); let e = connect(&one("npx", &["-y", "@modelcontextprotocol/server-filesystem", "/Users-nobody-here/someone/Documents"], "")).err().unwrap();
assert!(e.contains("/Users-nobody-here/someone/Documents"), "{e}"); assert!(e.contains("/Users-nobody-here/someone/Documents"), "{e}");

View File

@ -775,7 +775,8 @@ pub fn handle(req: Req, via_relay: bool) -> Resp {
("POST", ["api", "sync", "upload", id]) => upload(id.parse().unwrap_or(0), &req), ("POST", ["api", "sync", "upload", id]) => upload(id.parse().unwrap_or(0), &req),
// A screen of this brain shows the bots' own computer, which lives here: a small picture // A screen of this brain shows the bots' own computer, which lives here: a small picture
// (people watch it live through VNC, see vnc.rs). // (people watch it live through VNC, see vnc.rs).
("GET", ["api", "sync", "screen"]) => match crate::cloudbox::thumbnail(320) { // (Of the bot the screen asks about: its own screen when it has one open.)
("GET", ["api", "sync", "screen"]) => match crate::cloudbox::thumbnail_of(&crate::cloudbox::screen_for_bot(req.query.get("bot").map(String::as_str).unwrap_or("")), 320).or_else(|| crate::cloudbox::thumbnail(320)) {
Some(img) => match crate::computer::encode_jpeg(&image::DynamicImage::ImageRgba8(img).to_rgb8()) { Some(img) => match crate::computer::encode_jpeg(&image::DynamicImage::ImageRgba8(img).to_rgb8()) {
Some(j) => Resp::bytes("image/jpeg", j), Some(j) => Resp::bytes("image/jpeg", j),
None => Resp::error(500, "畫面編碼失敗"), None => Resp::error(500, "畫面編碼失敗"),
@ -787,7 +788,8 @@ pub fn handle(req: Req, via_relay: bool) -> Resp {
let v = req.json(); let v = req.json();
match v["kind"].as_str().unwrap_or("") { match v["kind"].as_str().unwrap_or("") {
"hold" => { "hold" => {
crate::cloudbox::HELD_BY_PERSON.store(v["on"].as_bool().unwrap_or(false), Ordering::SeqCst); let bot = v["bot"].as_u64().map(|b| b.to_string()).unwrap_or_default();
crate::cloudbox::hold(&crate::cloudbox::screen_for_bot(&bot), v["on"].as_bool().unwrap_or(false));
Resp::json(&json!({"ok": true})) Resp::json(&json!({"ok": true}))
} }
"wake" => match crate::cloudbox::ensure_running() { "wake" => match crate::cloudbox::ensure_running() {
@ -1553,7 +1555,8 @@ fn lan_vnc(req: Req, mut c: std::net::TcpStream, gen: u64) {
let mut ws = WebSocket::from_raw_socket(c, Role::Server, Some(cfg)); let mut ws = WebSocket::from_raw_socket(c, Role::Server, Some(cfg));
let (tx, rx) = std::sync::mpsc::channel::<Vec<u8>>(); let (tx, rx) = std::sync::mpsc::channel::<Vec<u8>>();
let send = move |b: &[u8]| tx.send(b.to_vec()).is_ok(); let send = move |b: &[u8]| tx.send(b.to_vec()).is_ok();
let Ok(mut session) = crate::vnc::open(send.clone()) else { return }; let screen = crate::cloudbox::screen_for_bot(req.query.get("bot").map(String::as_str).unwrap_or(""));
let Ok(mut session) = crate::vnc::open_on(&screen, send.clone()) else { return };
if !send(crate::vnc::GREETING) { if !send(crate::vnc::GREETING) {
return; return;
} }
@ -2071,8 +2074,8 @@ pub fn sync_voice_voices(s: &Settings) -> Result<Vec<(String, String)>, String>
} }
/// The brain's bots' computer as a JPEG (`thumb`: the small picture that never wakes it). /// The brain's bots' computer as a JPEG (`thumb`: the small picture that never wakes it).
pub fn sync_screen(s: &Settings, thumb: bool) -> Result<Vec<u8>, String> { pub fn sync_screen(s: &Settings, thumb: bool, bot: u64) -> Result<Vec<u8>, String> {
let (st, bytes) = to_brain_raw(s, "GET", "/screen", &[("thumb", if thumb { "1" } else { "0" }.to_string())], &[], 30)?; let (st, bytes) = to_brain_raw(s, "GET", "/screen", &[("thumb", if thumb { "1" } else { "0" }.to_string()), ("bot", bot.to_string())], &[], 30)?;
if !(200..300).contains(&st) { if !(200..300).contains(&st) {
return Err(why_refused(st, &serde_json::from_slice(&bytes).unwrap_or(Value::Null), "大腦")); return Err(why_refused(st, &serde_json::from_slice(&bytes).unwrap_or(Value::Null), "大腦"));
} }

View File

@ -333,7 +333,7 @@ fn streams() -> &'static Mutex<HashMap<String, crate::vnc::Session>> {
S.get_or_init(Default::default) S.get_or_init(Default::default)
} }
fn on_stream(kind: &str, sid: String, body: Vec<u8>, tx: &Sender<Vec<u8>>) { fn on_stream(kind: &str, sid: String, bot: String, body: Vec<u8>, tx: &Sender<Vec<u8>>) {
let send = { let send = {
let (tx, sid) = (tx.clone(), sid.clone()); let (tx, sid) = (tx.clone(), sid.clone());
move |b: &[u8]| tx.send(wire::pack(&json!({"t": "vdata", "sid": sid}), b)).is_ok() move |b: &[u8]| tx.send(wire::pack(&json!({"t": "vdata", "sid": sid}), b)).is_ok()
@ -352,7 +352,10 @@ fn on_stream(kind: &str, sid: String, body: Vec<u8>, tx: &Sender<Vec<u8>>) {
let (send, close) = (send.clone(), close.clone()); let (send, close) = (send.clone(), close.clone());
move |b: &[u8]| if b.is_empty() { close("這台電腦的畫面關了"); false } else { send(b) } move |b: &[u8]| if b.is_empty() { close("這台電腦的畫面關了"); false } else { send(b) }
}; };
match crate::vnc::open(out) { // 每個 Bot 一個螢幕: the bot the viewer was opened for (an older account server
// names none: the shared screen).
let screen = crate::cloudbox::screen_for_bot(&bot);
match crate::vnc::open_on(&screen, out) {
Ok(s) => { Ok(s) => {
streams().lock().unwrap().insert(sid, s); streams().lock().unwrap().insert(sid, s);
// Only now: the viewer answers this at once. // Only now: the viewer answers this at once.
@ -394,7 +397,7 @@ fn on_frame(head: Value, body: Vec<u8>, tx: &Sender<Vec<u8>>, calls: &Calls) {
} }
let t = head["t"].as_str().unwrap_or(""); let t = head["t"].as_str().unwrap_or("");
if matches!(t, "vopen" | "vdata" | "vtext" | "vclose") { if matches!(t, "vopen" | "vdata" | "vtext" | "vclose") {
return on_stream(t, head["sid"].as_str().unwrap_or("").to_string(), body, tx); return on_stream(t, head["sid"].as_str().unwrap_or("").to_string(), head["bot"].as_str().unwrap_or("").to_string(), body, tx);
} }
match t { match t {
"job" => { "job" => {

View File

@ -24,8 +24,15 @@ const HELD_AFTER_INPUT: Duration = Duration::from_secs(8);
/// Joins the box's VNC server to stdin/stdout, and ends when either side does (a loop left in /// Joins the box's VNC server to stdin/stdout, and ends when either side does (a loop left in
/// the box would hold the connection open). /// the box would hold the connection open).
const BRIDGE: &str = r#"import os,select,socket const BRIDGE: &str = r#"import os,select,socket,sys
s=socket.create_connection(('127.0.0.1',5900)) port=5900
k=sys.argv[1] if len(sys.argv)>1 else ''
if k:
try:
for l in open('/tmp/anybot-screens/%s/env'%k):
if l.startswith('VNC_PORT='): port=int(l.split('=',1)[1])
except OSError: pass
s=socket.create_connection(('127.0.0.1',port))
while True: while True:
r=select.select([s,0],[],[])[0] r=select.select([s,0],[],[])[0]
if s in r: if s in r:
@ -77,13 +84,15 @@ pub struct Session {
init: bool, init: bool,
} }
/// Open a viewer's way to the box: sign in to its VNC server, and start sending what the server /// Open a viewer's way to `key`'s screen on the box (a bot's own, 每個 Bot 一個螢幕; "" or one not
/// says to `out` (from a thread of its own; `out` returns false when the viewer is gone, and /// open: the shared one): sign in to its VNC server, and start sending what the server says to
/// gets an empty slice when the box's side ended). The caller then sends the viewer GREETING /// `out` (from a thread of its own; `out` returns false when the viewer is gone, and gets an empty
/// (once it is ready for the viewer's answer). /// slice when the box's side ended). The caller then sends the viewer GREETING (once it is ready
pub fn open(out: impl Fn(&[u8]) -> bool + Send + 'static) -> Result<Session, String> { /// for the viewer's answer).
pub fn open_on(key: &str, out: impl Fn(&[u8]) -> bool + Send + 'static) -> Result<Session, String> {
crate::cloudbox::ensure_running()?; crate::cloudbox::ensure_running()?;
let mut child = crate::cloudbox::exec_piped(&["python3", "-c", BRIDGE])?; let key: String = key.chars().filter(|c| c.is_ascii_alphanumeric() || *c == '_' || *c == '-').take(48).collect();
let mut child = crate::cloudbox::exec_piped(&["python3", "-c", BRIDGE, &key])?;
let mut stdin = child.stdin.take().ok_or("連不上這台電腦的畫面")?; let mut stdin = child.stdin.take().ok_or("連不上這台電腦的畫面")?;
let mut stdout = child.stdout.take().ok_or("連不上這台電腦的畫面")?; let mut stdout = child.stdout.take().ok_or("連不上這台電腦的畫面")?;
let fail = |child: &mut Child, why: &str| -> String { let fail = |child: &mut Child, why: &str| -> String {