From 28c712868661d3f9aec7bb2ccc6a844fe1856cd3 Mon Sep 17 00:00:00 2001 From: zhanglinghao Date: Sun, 22 Nov 2026 03:12:23 +0800 Subject: [PATCH 01/19] Lighter install, a short last screen, and a word before the local voice's first download Measured on a clean Mac: 71 of the install's 90 s and 305 MB were the reference repos, which a first film does not use; the install ended with a 60-line doctor report that said ready even when uv or a render browser was missing (Linux); the local voice's first use downloaded about 2.5 GB without a word. - install.sh fetches the reference repos only with --refs; references/fetch.sh says what it fetches and how big first (a size table in the script, checked by CI), and an unknown name exits 2. - bin/vh doctor --first: ready for a first film or not, what is missing and how to get it, how a voice comes here; the installer ends with it, the skills step says one line, the example sentence is the README's silent one. - bin/vh tts: before the local voice's first download, one line with the size, the time it may take and the way around it (--provider edge); uv's download lines shown, the model's progress every 10 s. The default provider is set in tts.py alone (DEFAULT_PROVIDER). - README, homepage: the sizes measured. --- README.md | 8 ++--- README.zh-CN.md | 8 ++--- bin/vh | 11 +++++-- changes/first-run.md | 7 +++++ docs/site/index.html | 2 +- install.sh | 61 ++++++++++++++++++++----------------- references/fetch.sh | 30 ++++++++++++++++--- tools/audio/tts.py | 71 ++++++++++++++++++++++++++++++++++++++++---- tools/ci.sh | 38 ++++++++++++++++++++++++ tools/commands.json | 8 +++-- tools/doctor.py | 63 ++++++++++++++++++++++++++++++++++----- 11 files changed, 246 insertions(+), 61 deletions(-) create mode 100644 changes/first-run.md diff --git a/README.md b/README.md index 9035a877..187520f3 100644 --- a/README.md +++ b/README.md @@ -410,20 +410,20 @@ For finer control, name what you want to decide yourself: the hook, the look, th ## Install options and updates -By default the installer registers the skills for both agents and fetches 37 read-only reference repos. It uses about 650 MB on disk, or 380 MB with `--no-refs`. The Studio app uses about 380 MB more, including its cached installer. +By default the installer registers the skills for both agents and uses about 400 MB on disk. The 37 read-only reference repos agents can read are not fetched then: an agent fetches the one a doc points to when it first needs it, saying its size first; `--refs` fetches them all now (about 300 MB more). The Studio app uses about 380 MB more, including its cached installer. ```bash bash install.sh --dir ~/code/OpenVideoHarness # install somewhere else -bash install.sh --no-refs # skip the reference repos for now (references/fetch.sh later) +bash install.sh --refs # fetch all 37 reference repos now (about 300 MB) bash install.sh --no-skill # don't register the global skill bash install.sh --no-icon # leave OVH Studio out of your applications (bin/vh studio --install-icon adds it later) ``` -- Nothing asks a question. On macOS and on a Linux desktop the installer puts OVH Studio, Studio's own window, in your applications (Electron: about 130 MB downloaded once, 260 MB on disk); when a step fails it says what to do next in one sentence. It ends with the two ways to start: click OVH Studio, or open Claude Code or Codex in the folder and say what film you want. +- Nothing asks a question. On macOS and on a Linux desktop the installer puts OVH Studio, Studio's own window, in your applications (Electron: about 130 MB downloaded once, 260 MB on disk); when a step fails it says what to do next in one sentence. It ends with a few lines: ready for a first film or not, what it still needs and how to get it, how a voice comes on this machine, and the two ways to start: click OVH Studio, or open Claude Code or Codex in the folder and say what film you want (`bin/vh doctor` has the full report). - The installer fetches only the newest commit: the repo itself is about 95 MB to download and 200 MB on disk, before its packages and the reference repos. To contribute or browse the history, `git clone` normally and run `bin/vh setup`. - To update, run the installer again with the same options (or `git pull`); `LOCAL.md` and `projects/` are left alone, and it stops before overwriting files you changed. The installed skills are short stubs that read `skills/` in the clone, so they follow the update; `bin/vh doctor` says in the rare case one needs `bin/vh install-skill` again. - The showcase videos aren't in git; to rebuild a showcase locally, `tools/fetch_media.sh` downloads them from the release to where its scripts expect them. -- The first render and the first use of the sound tools download more into `~/.cache`: Chrome about 200 MB, Python packages up to about 1.5 GB, and the default local voice's model about 2 GB (measured 2026-11; where each goes is on the wiki's [Getting Started](https://github.com/ZLHad/OpenVideoHarness/wiki/Getting-Started)). If npm, PyPI, Hugging Face or Google Fonts are blocked or slow where you are, [China network](https://github.com/ZLHad/OpenVideoHarness/wiki/China-Network) has the mirror settings. +- The first render and the first use of the sound tools download more into `~/.cache`: Chrome about 200 MB, Python packages up to about 1.5 GB, and the default local voice about 2.5 GB, its model and packages, which `bin/vh tts` says before it starts, showing the progress (`--provider edge` downloads nothing; measured 2026-11; where each goes is on the wiki's [Getting Started](https://github.com/ZLHad/OpenVideoHarness/wiki/Getting-Started)). If npm, PyPI, Hugging Face or Google Fonts are blocked or slow where you are, [China network](https://github.com/ZLHad/OpenVideoHarness/wiki/China-Network) has the mirror settings. Skill only: `npx skills add https://github.com/ZLHad/OpenVideoHarness --skill open-video-harness`. It's a pointer: on first use it asks before installing the full workbench. That copy stays as it was when the repo changes; once the workbench is installed, `bin/vh install-skill` replaces it with a stub that follows the clone. diff --git a/README.zh-CN.md b/README.zh-CN.md index d417878d..dbb778d2 100644 --- a/README.zh-CN.md +++ b/README.zh-CN.md @@ -410,20 +410,20 @@ AI 听不见,所以声音尽量做成能计算、能测量的。 ## 安装、更新和国内网络 -默认给两个 agent 注册 skill,并拉取 37 个只读参考仓库。合计约占 650 MB,用 `--no-refs` 安装约占 380 MB。Studio 应用另占约 380 MB,含缓存的安装包。 +默认给两个 agent 注册 skill,约占 400 MB。37 个只读参考仓库安装时不拉:agent 用到文档指的那一个时再拉,拉之前先说多大;`--refs` 在安装时一次拉全(再约 300 MB)。Studio 应用另占约 380 MB,含缓存的安装包。 ```bash bash install.sh --dir ~/code/OpenVideoHarness # 装到别的位置 -bash install.sh --no-refs # 先不拉参考仓库(之后用 references/fetch.sh 拉) +bash install.sh --refs # 安装时就把 37 个参考仓库拉全(约 300 MB) bash install.sh --no-skill # 不注册全局 skill bash install.sh --no-icon # 不把 OVH Studio 放进应用程序(以后 bin/vh studio --install-icon 再放) ``` -- 安装时什么都不问。macOS 和 Linux 桌面上,它会把 OVH Studio(Studio 自己的窗口)放进应用程序(Electron:第一次下载约 130 MB,占约 260 MB 磁盘);哪一步没成,它用一句话说接下来做什么。最后告诉你两种开始的办法:点 OVH Studio,或者在这个文件夹里打开 Claude Code 或 Codex,说你想做什么片子。 +- 安装时什么都不问。macOS 和 Linux 桌面上,它会把 OVH Studio(Studio 自己的窗口)放进应用程序(Electron:第一次下载约 130 MB,占约 260 MB 磁盘);哪一步没成,它用一句话说接下来做什么。最后几行说清这台机器能不能做第一支片、还缺什么、怎么补,配音在这台机器上怎么来,以及两种开始的办法:点 OVH Studio,或者在这个文件夹里打开 Claude Code 或 Codex,说你想做什么片子(完整的报告在 `bin/vh doctor`)。 - 安装脚本只拉最新的一个提交,仓库本身下载约 95 MB、占约 200 MB 磁盘,依赖和参考仓库另算;想参与贡献或翻历史,就正常 `git clone`,再运行 `bin/vh setup`。 - 更新:用同样的参数再运行一次安装命令(或者 `git pull`);`LOCAL.md` 和 `projects/` 不动,要覆盖你改过的文件时会先停下来。装出去的 skill 是指回克隆里 `skills/` 的短桩,跟着一起更新;少数要重装的时候(`bin/vh install-skill`),`bin/vh doctor` 会说。 - 样片的视频不在 git 里,要在本地复现样片时运行 `tools/fetch_media.sh`,它从 Release 下载到脚本要的位置。 -- 第一次渲染、第一次用声音工具时还会往 `~/.cache` 下载:Chrome 约 200 MB,Python 依赖最多约 1.5 GB,默认的本地配音模型约 2 GB(2026-11 实测;各放在哪里见 wiki 的[快速开始](https://github.com/ZLHad/OpenVideoHarness/wiki/%E5%BF%AB%E9%80%9F%E5%BC%80%E5%A7%8B))。国内网络连不上 npm、PyPI、Hugging Face 或 Google Fonts 时,镜像设置见 wiki 的[国内网络](https://github.com/ZLHad/OpenVideoHarness/wiki/%E5%9B%BD%E5%86%85%E7%BD%91%E7%BB%9C)。 +- 第一次渲染、第一次用声音工具时还会往 `~/.cache` 下载:Chrome 约 200 MB,Python 依赖最多约 1.5 GB,默认的本地配音约 2.5 GB(模型加它的依赖;`bin/vh tts` 开始前会先说,并显示进度;`--provider edge` 什么都不下)(2026-11 实测;各放在哪里见 wiki 的[快速开始](https://github.com/ZLHad/OpenVideoHarness/wiki/%E5%BF%AB%E9%80%9F%E5%BC%80%E5%A7%8B))。国内网络连不上 npm、PyPI、Hugging Face 或 Google Fonts 时,镜像设置见 wiki 的[国内网络](https://github.com/ZLHad/OpenVideoHarness/wiki/%E5%9B%BD%E5%86%85%E7%BD%91%E7%BB%9C)。 只装 skill:`npx skills add https://github.com/ZLHad/OpenVideoHarness --skill open-video-harness`。它只是一个指针,第一次用时会征得你同意,再把完整的工作台装好。这样装的是整份副本,仓库更新了它不变;工作台装好以后跑一次 `bin/vh install-skill`,换成跟随克隆的短桩。 diff --git a/bin/vh b/bin/vh index 9728dea0..a9321046 100755 --- a/bin/vh +++ b/bin/vh @@ -61,7 +61,7 @@ cmd_doctor() { local a skip="" live="" rec="" for a in "$@"; do # a usage error is said at once (by doctor.py), before the probe below if [ -n "$skip" ]; then skip=""; continue; fi - case "$a" in -h|--help) exec python3 "$ROOT/tools/doctor.py" -h ;; --json|--fill-local|--only=*) ;; --only) skip=1 ;; --probe) live=1 ;; --offline=*) rec=1 ;; --offline) rec=1 skip=1 ;; + case "$a" in -h|--help) exec python3 "$ROOT/tools/doctor.py" -h ;; --json|--fill-local|--first|--only=*) ;; --only) skip=1 ;; --probe) live=1 ;; --offline=*) rec=1 ;; --offline) rec=1 skip=1 ;; *) exec python3 "$ROOT/tools/doctor.py" "$@" ;; esac done [ -z "$rec" ] || [ -n "$live" ] || exec python3 "$ROOT/tools/doctor.py" "$@" @@ -1299,7 +1299,8 @@ cmd_tts() { [ -d "$proj" ] || { echo "$c_no bin/vh tts: no such project: $proj" >&2; exit 2; } # before uv builds an environment; tts.py would make the folder shift while [ $# -gt 0 ] && [ ${#pos[@]} -lt 4 ] && [[ "$1" != --* ]]; do pos+=("$1"); shift; done # positionals stop at the first --flag - local prov=${pos[0]:-qwen} voice=${pos[1]:-} lang=${pos[2]:-} instruct=${pos[3]:-} a prev="" np="" + local prov=${pos[0]:-} voice=${pos[1]:-} lang=${pos[2]:-} instruct=${pos[3]:-} a prev="" np="" quiet=-q fresh="" + [ -n "$prov" ] || prov=$(python3 "$ROOT/tools/audio/tts.py" --default-provider) # tts.py's DEFAULT_PROVIDER, the one place it is set for a in "$@"; do # tts.py's own --provider X / --provider=X picks the dependencies too; the last one wins, as in argparse [ "$prev" = --provider ] && prov=$a case "$a" in --provider=*) prov=${a#--provider=} ;; --candidates|--candidates=*) np="--with numpy" ;; --align=local) np="$np --with mlx-whisper" ;; esac # the takes are measured with numpy @@ -1311,7 +1312,11 @@ cmd_tts() { case "$prov" in qwen) deps="--with mlx-audio" ;; edge) deps="--with edge-tts" ;; dashscope) [ -z "${DASHSCOPE_API_KEY:-}" ] || deps="--with dashscope" ;; esac # no key: tts.py says so, with no package fetched first deps="$deps${np:+ $np}" - on_ctrl_c uv run -q --no-project $deps python "$ROOT/tools/audio/tts.py" "$proj" --provider "$prov" ${lang:+--lang "$lang"} ${voice:+--voice "$voice"} ${instruct:+--instruct "$instruct"} "$@" + # the local voice's first use downloads gigabytes: said first in one line (how much, how long, the way around it), and + # uv's own download lines shown instead of quieted (tts.py adds the model's progress) + if [ "$prov" = qwen ] && command -v uv >/dev/null 2>&1 && ! uv run -q --no-project --offline $deps python -c "" >/dev/null 2>&1; then quiet=""; fresh=--packages-missing; fi + [ "$prov" != qwen ] || python3 "$ROOT/tools/audio/tts.py" --first-use qwen $fresh + on_ctrl_c uv run $quiet --no-project $deps python "$ROOT/tools/audio/tts.py" "$proj" --provider "$prov" ${lang:+--lang "$lang"} ${voice:+--voice "$voice"} ${instruct:+--instruct "$instruct"} "$@" } cmd_voices() { # audition measures the takes (numpy) and synthesizes with the provider's own packages, through uv [ $# -gt 0 ] || set -- list diff --git a/changes/first-run.md b/changes/first-run.md new file mode 100644 index 00000000..e22c5b0b --- /dev/null +++ b/changes/first-run.md @@ -0,0 +1,7 @@ +**安装更轻,最后一屏只说第一支片要知道的事;本地配音第一次下载前先说** +- Why: 在干净的机器上量过,安装 90 秒里有 71 秒、305 MB 在拉参考仓库,而第一支片用不到它们;安装最后一屏是 60 多行 doctor,十几行黄色提示大多和第一支片无关,Linux 上真挡路的缺项淹在里面,最后照样说"ready";本地配音第一次用要静默下载约 2.5 GB。 +- 37 个参考仓库安装时不再拉:agent 用到文档指的那一个时再拉,`references/fetch.sh <目录>` 拉之前用一行说清拉什么、从哪、多大(大小表在脚本里,CI 查每一个都有);名字写错时说清并退出 2。`install.sh --refs` 一次拉全;`--no-refs` 照旧认,现在就是默认。之前拉过的留着不动。 +- 安装最后几行换成 `bin/vh doctor --first`:能不能做第一支片,缺什么、一句怎么补(Node、FFmpeg、Python、uv、能渲染的浏览器、一个 agent),Linux 上缺中文字体也说,配音在这台机器上怎么来;有缺的就不说 ready。完整报告照旧是 `bin/vh doctor`。skill 注册只说一行。示例句换成 README 那条无声 15 秒。 +- `bin/vh tts` 用本地配音、第一次要下载时,先说一行:约多大、大概多久、显示进度,以及不用下载的办法(`--provider edge`,免费,在线:稿子会发到微软的配音服务);Python 包的下载逐个显示,模型下载每 10 秒说一次下了多少。默认配音只在 `tools/audio/tts.py` 的 `DEFAULT_PROVIDER` 一处设,`bin/vh tts` 问它。 +- doctor 找本地配音模型时也看 `XDG_CACHE_HOME`(Hugging Face 自己就这样找)。 +- README 中英文和官网的安装大小按实测更新:安装约 400 MB,`--refs` 再约 300 MB,本地配音约 2.5 GB。 diff --git a/docs/site/index.html b/docs/site/index.html index 13f1f8af..5898ddea 100644 --- a/docs/site/index.html +++ b/docs/site/index.html @@ -866,7 +866,7 @@

Compare the revision同一段改完
Quick draft: make a silent 15-second vertical explainer showing why doubling a square’s side length quadruples its area. Use a grid and on-screen text.快速出一版 15 秒的竖屏无声科普,用方格和画面文字讲清楚为什么正方形边长翻倍,面积变成四倍。
-

Needs Git, Node.js 22+, Chrome, FFmpeg, Python 3 with uv, and Claude Code or Codex. About 650 MB on disk including 37 read-only reference repos. Step-by-step guide · China network需要 Git、Node.js ≥ 22、Chrome、FFmpeg、Python 3 和 uv,以及 Claude Code 或 Codex。连同 37 个只读参考仓库,约占 650 MB。分步教程 · 国内网络

+

Needs Git, Node.js 22+, Chrome, FFmpeg, Python 3 with uv, and Claude Code or Codex. About 400 MB on disk; the 37 read-only reference repos come when an agent first needs one. Step-by-step guide · China network需要 Git、Node.js ≥ 22、Chrome、FFmpeg、Python 3 和 uv,以及 Claude Code 或 Codex。约占 400 MB;37 个只读参考仓库等 agent 用到时再拉。分步教程 · 国内网络

Review stops for standard and studio标准档和精品档怎么审

diff --git a/install.sh b/install.sh index 6598d988..8a32c32f 100755 --- a/install.sh +++ b/install.sh @@ -1,19 +1,21 @@ #!/usr/bin/env bash # OpenVideoHarness one-line installer. # curl -fsSL https://raw.githubusercontent.com/ZLHad/OpenVideoHarness/main/install.sh | bash -# bash install.sh [--dir ~/OpenVideoHarness] [--no-refs] [--no-skill] [--skill claude|codex|all] [--obscura] [--icon | --no-icon] +# bash install.sh [--dir ~/OpenVideoHarness] [--refs] [--no-skill] [--skill claude|codex|all] [--obscura] [--icon | --no-icon] # What it does, and where it puts things: # 1. clone the repo into --dir, newest commit only (about 200 MB on disk; a re-run moves it to the newest commit, keeping LOCAL.md and projects/) -# 2. npm install in engines/ClaudeAnimationBase and npm ci in styles/_swatch (HyperFrames 0.8.202), both inside --dir (about 210 MB of -# node_modules; npm also writes its own cache, ~/.npm); unless --no-refs, fetch the read-only reference repos references/fetch.sh lists -# into references/repos/ (about 250 MB, git-ignored; references/fetch.sh fetches one later) +# 2. npm install in engines/ClaudeAnimationBase and npm ci in styles/_swatch (HyperFrames 0.8.202), both inside --dir (about 180 MB of +# node_modules; npm also writes its own cache, ~/.npm). The read-only reference repos references/fetch.sh lists are not fetched: +# an agent fetches the one a doc points to when it first needs it (bash references/fetch.sh , which says its size first); +# --refs fetches them all now into references/repos/ (about 300 MB, git-ignored; --no-refs, the old way to skip them, is the default) # 3. copy LOCAL.example.md to LOCAL.md (git-ignored) if there is no LOCAL.md # 4. unless --no-skill, write the skills (skills/*: open-video-harness, open-video-harness-web) to ~/.claude/skills and # ~/.agents/skills (--skill claude|codex: only one): short stubs that read skills/ in --dir, so a re-run or git pull updates them # 4b. with --obscura, bin/vh web install: the pinned Obscura release (a headless browser, about 70 MB from its GitHub releases) # into ~/.local/share/ovh/obscura, linked from ~/.local/bin; bin/vh web checks facts against web pages with it -# 5. run bin/vh doctor --fill-local as a final check: it also writes LOCAL.md's machine lines (硬件, 已装工具, 已装引擎) -# where they still hold the template, never a line you wrote +# 5. run bin/vh doctor --fill-local --first as the last lines: ready for a first film or not, what it still needs and how to get it, +# how a voice comes on this machine (the full report: bin/vh doctor); it also writes LOCAL.md's machine lines (硬件, 已装工具, +# 已装引擎) where they still hold the template, never a line you wrote # 6. put OVH Studio, Studio's own window, in your applications (macOS: ~/Applications/OVH Studio.app; a Linux desktop: a # desktop entry in ~/.local/share/applications): Electron, about 130 MB downloaded once and 260 MB on disk (without npm or # a network, a small launcher that opens a browser's window instead). No question. A run again leaves it alone when it is @@ -25,16 +27,16 @@ # - the first hyperframes render: HyperFrames' own chrome-headless-shell (about 200 MB, ~/.cache/hyperframes) # - the first bin/vh beats, music, sfx, qa or sheet: their Python packages, through uv (about 700 MB, ~/.cache/uv) # - the first bin/vh tts with the default qwen provider (skipped with another one): its Python packages (about 750 MB, ~/.cache/uv) -# and the Qwen3-TTS model (about 2 GB, ~/.cache/huggingface) +# and the Qwen3-TTS model (1.8 GB, ~/.cache/huggingface); bin/vh tts says so before it starts and shows the progress # - every bin/vh new short, promo, data or meme: about 140 MB of node_modules in that project # The wiki's Getting Started ("What gets downloaded") has the same list. set -euo pipefail REPO="${OVH_REPO:-https://github.com/ZLHad/OpenVideoHarness.git}" -DIR="${OVH_DIR:-$HOME/OpenVideoHarness}"; REFS=1; SKILL=all; OBSCURA=0; ICON=default +DIR="${OVH_DIR:-$HOME/OpenVideoHarness}"; REFS=0; SKILL=all; OBSCURA=0; ICON=default while [ $# -gt 0 ]; do case "$1" in - --dir) DIR="$2"; shift 2 ;; --no-refs) REFS=0; shift ;; --no-skill) SKILL=none; shift ;; --skill) SKILL="${2:?--skill needs claude|codex|all|none}"; shift 2 ;; --obscura) OBSCURA=1; shift ;; + --dir) DIR="$2"; shift 2 ;; --refs) REFS=1; shift ;; --no-refs) REFS=0; shift ;; --no-skill) SKILL=none; shift ;; --skill) SKILL="${2:?--skill needs claude|codex|all|none}"; shift 2 ;; --obscura) OBSCURA=1; shift ;; --icon) ICON=yes; shift ;; --no-icon) ICON=no; shift ;; - -h|--help) sed -n '2,30p' "$0"; exit 0 ;; *) echo "unknown option: $1"; exit 1 ;; esac; done + -h|--help) sed -n '2,32p' "$0"; exit 0 ;; *) echo "unknown option: $1"; exit 1 ;; esac; done case "$SKILL" in claude|codex|all|none) ;; *) echo "unknown --skill '$SKILL' (claude|codex|all|none)"; exit 1 ;; esac say() { printf '\033[1m→ %s\033[0m\n' "$*"; } NOAPP="${XDG_DATA_HOME:-$HOME/.local/share}/ovh-studio/no-app" # --no-icon once: kept here, so an update leaves OVH Studio out too (--icon clears it) @@ -98,30 +100,33 @@ else say "cloning into $DIR (newest commit only)" cd "$DIR" say "installing the bundled engine (ClaudeAnimationBase)" (cd engines/ClaudeAnimationBase && npm install --silent) || echo "! the hand-drawn engine's packages did not install; running this installer again finishes them" -if [ "$REFS" = 1 ]; then n=$(grep -cE '^(full|sparse|textonly) ' references/fetch.sh || true) # counted from the list, so it cannot go stale - say "fetching $n reference repos (about 250 MB, read-only, git-ignored; --no-refs skips them)" - references/fetch.sh || echo "! some reference repos were not fetched; bash references/fetch.sh fetches them later"; fi +n=$(grep -cE '^(full|sparse|textonly) ' references/fetch.sh || true) # counted from the list, so it cannot go stale +if [ "$REFS" = 1 ]; then + say "fetching $n reference repos (about 300 MB, read-only, git-ignored)" + references/fetch.sh || echo "! some reference repos were not fetched; bash references/fetch.sh fetches them later" +else had=$(find references/repos -mindepth 2 -maxdepth 2 -name .git 2>/dev/null | wc -l | tr -d ' ') + if [ "${had:-0}" -gt 0 ]; then echo " the $had reference repos fetched before stay as they are (--refs updates them and fetches the rest)"; fi +fi say "installing the renderer for style samples (HyperFrames, for bin/vh style)" (cd styles/_swatch && npm ci --silent) || echo "! the renderer for style samples did not install; it is tried again the first time a style sample is made" [ -f LOCAL.md ] || cp LOCAL.example.md LOCAL.md -[ "$SKILL" = none ] || { say "telling Claude Code and Codex where this workbench is (skills)"; bin/vh install-skill "$SKILL" || echo "! the skills were not registered; bin/vh install-skill $SKILL registers them"; } +if [ "$SKILL" != none ]; then # one line for the stubs it wrote (each says where it went when run by hand: bin/vh install-skill) + say "telling Claude Code and Codex where this workbench is (skills)" + if out=$(bin/vh install-skill "$SKILL" 2>&1); then + echo " $(printf '%s\n' "$out" | grep -c 'skill →') skill stubs written; restart Claude Code or Codex if it is open, so it sees them" + else printf '%s\n' "$out"; echo "! the skills were not registered; bin/vh install-skill $SKILL registers them"; fi +fi [ "$OBSCURA" = 0 ] || { say "installing Obscura (an optional page reader that bin/vh web can use to keep web pages for fact checks)"; bin/vh web install || echo "! Obscura not installed; bin/vh web install retries it"; } -say "final check (and this machine's lines in LOCAL.md)"; bin/vh doctor --fill-local || true ICON_LATER=""; ICON_DONE=""; ICON_HEADLESS=""; put_icon -arm="" # Linux arm64: HyperFrames has no Chrome of its own there (engines/README.md, its notes), so a missing browser is said again below -if [ "$(uname -s)" = Linux ]; then case "$(uname -m)" in aarch64|arm64) - bin/vh doctor --json 2>/dev/null | python3 -c 'import json, sys; sys.exit(0 if any(c["name"] == "browser" and c["state"] == "ok" for c in json.load(sys.stdin)["checks"]) else 1)' 2>/dev/null || arm=1 ;; esac; fi -cat </, bash references/fetch.sh fetches that one" -[ -z "$arm" ] || echo " ! Linux arm64: no browser yet, and HyperFrames has none of its own here; set one up before the first render (engines/README.md, \"Linux:渲染前要先备好的三样\")" echo -echo "✓ OpenVideoHarness is ready at $DIR. Two ways to start:" +# the last lines: ready for a first film or not, what it still needs, how a voice comes here (the full report: bin/vh doctor) +READY=""; bin/vh doctor --fill-local --first && READY=1 +echo +if [ -n "$READY" ]; then echo "✓ OpenVideoHarness is ready at $DIR. Two ways to start:" +else echo "✗ OpenVideoHarness is installed at $DIR; a first film still needs what is listed above. Then, two ways to start:"; fi if [ -n "$ICON_DONE" ]; then echo " 1. Click OVH Studio in your applications: your films, their stops and the agent, in one window." elif [ -n "$ICON_HEADLESS" ]; then echo " 1. Studio, in a browser on another computer: cd \"$DIR\" && bin/vh studio --print-address (this machine has no desktop)" else echo " 1. Studio, your films in one window: cd \"$DIR\" && bin/vh studio$([ -z "$ICON_LATER" ] || printf ' (bin/vh studio --install-icon puts it in your applications)')"; fi -echo " 2. Open Claude Code or Codex in that folder (cd \"$DIR\" && claude) and say what film you want, e.g. \"做一个 30 秒的竖屏科普:为什么低轨卫星的信号会变调\"" +echo " 2. Open Claude Code or Codex in that folder (cd \"$DIR\" && claude) and say what film you want, e.g." +echo " \"快速出一版 15 秒的竖屏无声科普,用方格和画面文字讲清楚为什么正方形边长翻倍,面积变成四倍。\"" +echo " The full report of this machine: bin/vh doctor" diff --git a/references/fetch.sh b/references/fetch.sh index bc0578f8..b069541a 100755 --- a/references/fetch.sh +++ b/references/fetch.sh @@ -10,11 +10,31 @@ # 用法:bash references/fetch.sh 拉取或更新全部 # bash references/fetch.sh 只处理一个(dir 是下表第二列,例如 lemo-opuscar) # bash references/fetch.sh --neutralize 不联网,只对已拉取的仓库重新做一遍中和 +# +# 安装时默认不拉(install.sh --refs 才一次拉全):文档指到哪一个,agent 第一次用时再拉那一个,拉之前用一行说清拉什么、多大。 set -euo pipefail unset CDPATH # an exported one could send these relative cds elsewhere (as in bin/vh) cd "$(dirname "$0")" && mkdir -p repos && cd repos ARG=${1:-} +# 各仓库第一次拉下来占的磁盘(MB,含浅克隆的 .git;2026-11-22 在 macOS 上量的,合计约 300 MB)。拉之前那一行用它说大小; +# 加一个仓库时在这里补一项(tools/ci.sh 查每一行都有) +SIZES=" + 3brown1blue 1 Battle-of-Austerlitz-Film 2 Code2Video <1 MathLens <1 OpenMontage 27 PDoomVideo 8 Paper-Cut <1 + anatomy-reveal <1 anatomy 14 awesome-claude-video-skills <1 awesome-opus5-5-videos 5 blender-skills 2 + claude-animation-skill 6 data-animation-skills <1 faceless-shorts-creator 2 functional-emotions-video 18 + gbro-collage-info 5 guizang-product-video 3 hand-drawn-explainer <1 huashu-art-motion 7 huashu-design 4 + hyperframes-launches 12 hyperframes 11 lemo-opuscar 42 openfilm-examples 8 openfilm 59 opus55-catalog-zhuyansen 4 + opus55-guide-athemeroy 7 procedural-film 13 product-film-skill <1 remotion-guofeng-starter <1 remotion-skills 2 + story-to-handdrawn-video 3 video-shotcraft 11 video-talkcraft 18 viral-video-decomposer 4 vox-director <1 +" +size_of() { printf '%s\n' $SIZES | awk -v d="$1" 'p { print; exit } $0 == d { p = 1 }'; } +announce() { # announce :第一次拉一个之前,一行说清拉什么、从哪、多大 + local mb; mb=$(size_of "$2") + echo "fetching $2 from github.com/$1 (${mb:+about $mb MB, }read-only, for agents to read)" +} +MATCHED="" + AGENT_FILES=(.claude .agents CLAUDE.md CLAUDE.local.md AGENTS.md .mcp.json) agent_paths() { # 列出 $1 下所有层级的 agent 文件(跳过 .git),深的在前,保证先改子项再改父目录 local d=$1 f args=() @@ -34,7 +54,8 @@ neutralize() { # 更新后:改名为同目录下的 _upstream_*(git status skip() { # 按参数决定是否跳过这一行;--neutralize 模式只中和、不联网 local d=$1 if [ "$ARG" = "--neutralize" ]; then [ -d "$d" ] && neutralize "$d" && echo "ok $d (neutralized)"; return 0; fi - [ -n "$ARG" ] && [ "$ARG" != "$d" ] + [ -n "$ARG" ] && [ "$ARG" != "$d" ] && return 0 + MATCHED=1; return 1 } SKIPPED="" failed() { # failed <原因>:一个上游拉不下来只跳过这一行,不中断其余仓库和调用本脚本的安装流程 @@ -49,14 +70,14 @@ full() { # full :整仓浅克隆 skip "$2" && return 0 restore "$2" if [ -d "$2/.git" ]; then git -C "$2" pull --ff-only -q || true - else clone "$1" "$2" || return 0; fi + else announce "$1" "$2"; clone "$1" "$2" || return 0; fi neutralize "$2"; echo "ok $2" } sparse() { # sparse :只检出指定目录(大仓库用) local r=$1 d=$2; shift 2 skip "$d" && return 0 restore "$d" - if [ ! -d "$d/.git" ]; then clone "$r" "$d" --filter=blob:none --sparse || return 0; fi + if [ ! -d "$d/.git" ]; then announce "$r" "$d"; clone "$r" "$d" --filter=blob:none --sparse || return 0; fi git -C "$d" sparse-checkout set "$@" && git -C "$d" pull --ff-only -q || true neutralize "$d"; echo "ok $d ($*)" } @@ -64,7 +85,7 @@ textonly() { # textonly :只检出代码和文档,跳过 local r=$1 d=$2 fresh= skip "$d" && return 0 restore "$d" - if [ ! -d "$d/.git" ]; then clone "$r" "$d" --filter=blob:none --no-checkout || return 0; fresh=1; fi + if [ ! -d "$d/.git" ]; then announce "$r" "$d"; clone "$r" "$d" --filter=blob:none --no-checkout || return 0; fresh=1; fi git -C "$d" sparse-checkout set --no-cone '/*' '!*.mp4' '!*.mov' '!*.webm' '!*.mkv' '!*.gif' '!*.mp3' '!*.wav' '!*.m4a' '!*.aac' '!*.flac' \ '!*.png' '!*.jpg' '!*.jpeg' '!*.webp' '!*.psd' '!*.ttf' '!*.otf' '!*.woff' '!*.woff2' '!*.zip' '!*.pdf' '!*.onnx' '!*.bin' # 新克隆只需检出;已有克隆要 pull(空参数的 checkout 总是成功,放在 || 前面会让 pull 永远跑不到) @@ -124,5 +145,6 @@ textonly annnguyentt/anatomy-reveal-skill anatomy-reveal # 用 # Blender 只做资产(见 engines/blender.md"只做资产") textonly EL4CTEO/blender-skills blender-skills # Blender 5.2 的建模、UV、PBR、烘焙、绑骨、导出和资产质检 skill,`blender -b` 就能跑;bin/vh model3d check --blender 借它 asset-qa 的检查(MIT) +[ -z "$ARG" ] || [ "$ARG" = --neutralize ] || [ -n "$MATCHED" ] || { echo "no reference repo named $ARG: the names are the second column of references/fetch.sh" >&2; exit 2; } [ -z "$SKIPPED" ] || echo "skipped (re-run later, e.g. bash references/fetch.sh ):$SKIPPED" exit 0 diff --git a/tools/audio/tts.py b/tools/audio/tts.py index 0e3663be..54613cb8 100644 --- a/tools/audio/tts.py +++ b/tools/audio/tts.py @@ -269,6 +269,54 @@ def hf_cached(model_id): return True return os.path.isdir(os.path.join(constants.HF_HUB_CACHE, "models--" + model_id.replace("/", "--"), "snapshots")) +# The provider bin/vh tts uses when none is named: the one place to change it (bin/vh asks: tts.py --default-provider). +DEFAULT_PROVIDER = "qwen" +QWEN_MODEL = "mlx-community/Qwen3-TTS-12Hz-0.6B-CustomVoice-8bit" +QWEN_SIZES = {"packages": 0.75, "model": 1.8} # GB on disk the first time: mlx-audio and its packages (uv), the model (Hugging Face) + +def hub_dir(): + """Where the Hugging Face Hub keeps models, worked out as huggingface_hub does (stdlib, before it is installed).""" + if os.environ.get("HF_HUB_CACHE"): + return Path(os.environ["HF_HUB_CACHE"]) + home = os.environ.get("HF_HOME") or os.path.join(os.environ.get("XDG_CACHE_HOME") or os.path.expanduser("~/.cache"), "huggingface") + return Path(home) / "hub" + +def model_dir(model_id): + return hub_dir() / ("models--" + model_id.replace("/", "--")) + +def first_use_line(provider, packages_missing=False): + """The one line bin/vh tts says before a provider's first run downloads gigabytes (or None: nothing that big to fetch): + how much, roughly how long, that the progress shows, and the way around it.""" + if provider != "qwen" or not (sys.platform == "darwin" and platform.machine() == "arm64"): + return None + model_id = os.environ.get("QWEN_TTS_MODEL", QWEN_MODEL) + model = model_id == QWEN_MODEL and not os.path.isdir(os.path.expanduser(model_id)) and not list(model_dir(model_id).glob("snapshots/*/*.safetensors")) + parts = (["its Python packages"] if packages_missing else []) + (["the voice model"] if model else []) + if not parts: + return None + gb = (QWEN_SIZES["packages"] if packages_missing else 0) + (QWEN_SIZES["model"] if model else 0) + return (f" first use of the local voice: about {gb:.1f} GB to download once ({' and '.join(parts)}); a few minutes on a fast line," + f" half an hour or more on a slow one; the progress shows below. To skip it: --provider edge (free, online: the script" + f" goes to Microsoft's voice service)") + +def show_progress(folder, total_gb, every=10.0): + """A line every `every` seconds with how much a download has added to `folder` (the Hub's whole cache: its xet transfer + stages the parts outside the model's own folder), for output nobody watches live, where a progress bar is turned + off. → the thread's stop event.""" + import threading + stop = threading.Event() + def size(): + return sum(f.stat().st_size for f in Path(folder).rglob("*") if f.is_file() and not f.is_symlink()) if Path(folder).is_dir() else 0 + base = size() + def run(): + last = None + while not stop.wait(every): + got = round((size() - base) / 1e9, 1) + if got != last: + print(f" voice model: {got:.1f} of about {total_gb} GB", flush=True); last = got + threading.Thread(target=run, daemon=True).start() + return stop + _QWEN = {} def p_qwen(text, voice, out: Path, tmp: Path, lang, instruct=None): # Set before the libraries are imported, which is when they read them; one set outside wins (TRANSFORMERS_VERBOSITY=info). @@ -281,18 +329,22 @@ def p_qwen(text, voice, out: Path, tmp: Path, lang, instruct=None): import contextlib, io import numpy as np from mlx_audio.tts.utils import load_model # provided by `uv run --with mlx-audio` - default = "mlx-community/Qwen3-TTS-12Hz-0.6B-CustomVoice-8bit" - model_id = os.environ.get("QWEN_TTS_MODEL", default) + model_id = os.environ.get("QWEN_TTS_MODEL", QWEN_MODEL) if model_id not in _QWEN: - print(f" loading {model_id}" + ("" if hf_cached(model_id) else " (not downloaded yet: " + ("about 2 GB " if model_id == default else "") - + "into the Hugging Face cache, once)") + " …", flush=True) + fresh = not hf_cached(model_id) + print(f" loading {model_id}" + (" (not downloaded yet: " + (f"{QWEN_SIZES['model']} GB " if model_id == QWEN_MODEL else "") + + "into the Hugging Face cache, once)" if fresh else "") + " …", flush=True) said = io.StringIO() # mlx-audio prints what it loads; shown only when loading fails + stop = show_progress(hub_dir(), QWEN_SIZES["model"] if model_id == QWEN_MODEL else "?") if fresh and not sys.stderr.isatty() else None try: with contextlib.redirect_stdout(said): _QWEN[model_id] = load_model(model_id) except BaseException: sys.stdout.write(said.getvalue()) raise + finally: + if stop: + stop.set() model = _QWEN[model_id] zh = lang.startswith("zh") kw = dict(text=text, speaker=voice or ("Serena" if zh else "Aiden"), language="Chinese" if zh else "English") @@ -1151,8 +1203,15 @@ def usage_error(msg): # a mistake in the command line: one line, exit 2 (a run def main(): if sys.argv[1:2] == ["voices"] and (len(sys.argv) == 2 or sys.argv[2] in ("list", "design", "delete", "audition", "-h", "--help")): return voices_main(sys.argv[2:]) + if sys.argv[1:] == ["--default-provider"]: # for bin/vh tts, which picks the provider's packages before this runs + print(DEFAULT_PROVIDER); return + if sys.argv[1:2] == ["--first-use"] and len(sys.argv) in (3, 4): # bin/vh tts: the line before a big first download + line = first_use_line(sys.argv[2], sys.argv[3:] == ["--packages-missing"]) + if line: + print(line, flush=True) + return ap = argparse.ArgumentParser() - ap.add_argument("project"); ap.add_argument("--provider", choices=PROVIDERS, help="default qwen (with --resume: the run's provider)") + ap.add_argument("project"); ap.add_argument("--provider", choices=PROVIDERS, help=f"default {DEFAULT_PROVIDER} (with --resume: the run's provider)") ap.add_argument("--voice"); ap.add_argument("--lang", choices=["zh", "en"], help="spoken side (default zh; en for an English-only script)") ap.add_argument("--gap", type=float, default=0.25); ap.add_argument("--instruct") ap.add_argument("--keep-edges", action="store_true", help="keep the silence the provider puts before/after each line") @@ -1207,7 +1266,7 @@ def main(): sys.exit(f"--resume: GEMINI_TTS_STYLE was {man.get('style_env')!r} for the run, now {os.environ.get('GEMINI_TTS_STYLE')!r};" f" set it back, or drop --resume to start over") a.provider, a.voice, a.instruct, a.keep_edges = man["provider"], man["voice"], man.get("instruct"), man["keep_edges"] - a.provider = a.provider or "qwen" + a.provider = a.provider or DEFAULT_PROVIDER gemini = a.provider.startswith("gemini") timed = a.provider in WORD_TIMED # word timing from the provider itself penv = {k: os.environ.get(k) for k in MINIMAX_ENV} if a.provider == "minimax" else {} diff --git a/tools/ci.sh b/tools/ci.sh index 9da0f4f5..70f7aad3 100755 --- a/tools/ci.sh +++ b/tools/ci.sh @@ -1565,6 +1565,44 @@ print(d.references_note(0, 37, 0, d.install_says())); print(d.references_note(31 case "$a" in "0/37 repos fetched → bash references/fetch.sh (all 37: about $b;"*"31/37 repos fetched → bash references/fetch.sh (all 37: about 255 MB, at the size of the 31 here;"*) ok "doctor: the reference repos' size from the ones fetched (31 of 37 at 214 MB: about 255 MB), else as install.sh says it ($b)" ;; *) bad "doctor's line for the reference repos: $a (install.sh says: ${b:-nothing found})" ;; esac + # the reference repos are fetched on first use: references/fetch.sh knows each one's size, and says it in one line before + # a first fetch; a name it does not have is said, exit 2 (it used to do nothing) + a=$(bash -c 'cd references && sed -n "/^SIZES=\"/,/^\"/p" fetch.sh | tr " " "\n" | grep -v "^SIZES\|^\"\|^$" | paste - - | cut -f1 | sort' 2>&1) + b=$(grep -E '^(full|sparse|textonly) ' references/fetch.sh | awk '{print $3}' | sort) + c=$(bash references/fetch.sh no-such-repo 2>&1); rc=$? + if [ -n "$b" ] && [ "$a" = "$b" ] && [ "$rc" = 2 ] && case "$c" in "no reference repo named no-such-repo"*) true ;; *) false ;; esac \ + && grep -q '^ else announce "$1" "$2"; clone' references/fetch.sh && grep -q 'REFS=0;' install.sh && grep -q -- '--refs) REFS=1' install.sh + then ok "references/fetch.sh: a size for each of the $(printf '%s\n' "$b" | wc -l | tr -d ' ') reference repos, said before a first fetch; an unknown name exits 2; install.sh fetches them only with --refs" + else bad "references/fetch.sh's sizes or names (exit $rc): $(diff <(printf '%s\n' "$a") <(printf '%s\n' "$b") | head -5 | tr '\n' ' ') | $c"; fi + # doctor --first, the installer's last lines: ready only when a first film has what it needs; what is missing, with how + # to get it; a voice line for this platform; a Chinese font missing is said (Linux) + a=$(python3 - <<'PY' 2>&1 +import sys; sys.path.insert(0, "tools"); import doctor as d +ok = lambda n, **k: dict({"name": n, "state": "ok", "install": f"get {n}"}, **k) +mods = [ok("node"), ok("ffmpeg"), ok("python3"), ok("uv"), ok("chrome"), ok("chrome-headless-shell", state="missing"), ok("claude-code"), ok("codex", state="missing"), + ok("qwen3-tts", state="missing"), ok("mlx-audio")] +checks = [{"name": "browser", "state": "missing"}] +l1, r1 = d.first_film(mods, checks, "darwin-arm64") # no browser yet, but the first render brings its own: ready +mods2 = [dict(m, state="missing") if m["name"] in ("uv", "claude-code") else m for m in mods] +l2, r2 = d.first_film(mods2, checks + [{"name": "fonts", "state": "missing"}], "linux-arm64") # no uv, no browser, no agent, no font +print(r1, r2, len(l1), len(l2)); print("\n".join(l1 + ["--"] + l2)) +PY +) + case "$a" in "True False 3 6"*"✓ Ready for a first film: Node, FFmpeg, uv, a browser to render with, Claude Code"*"downloads its own Chrome once"*"- Voice: the first bin/vh tts downloads the local voice once (about 2.5 GB"*"--provider edge"*"--"*"✗ Not ready for a first film yet"*" uv → get uv"*" a browser to render with → get chrome"*" Claude Code or Codex →"*"! Chinese text"*"- Voice: bin/vh tts --provider edge"*) + ok "doctor --first: ready only with Node, FFmpeg, Python, uv, a browser (or a platform whose first render brings one) and an agent; each missing one with how to get it; the voice for the platform; a missing Chinese font said" ;; + *) bad "doctor --first: $(printf '%s' "$a" | head -c 600)" ;; esac + # bin/vh tts: the default provider is said in one place (tts.py), and the local voice's first use is said before it + # downloads, with the size, the time it may take and the way around it; nothing for another provider or a cached model + a=$(python3 tools/audio/tts.py --default-provider 2>&1) + b=$(HF_HOME="$(mktemp -d)" python3 tools/audio/tts.py --first-use qwen --packages-missing 2>&1) + c=$(python3 tools/audio/tts.py --first-use edge --packages-missing 2>&1) + want="first use of the local voice: about 2.5 GB to download once (its Python packages and the voice model)" + case "$(uname -s)-$(uname -m)" in Darwin-arm64) ;; *) want="" ;; esac # elsewhere the local voice does not run, so nothing is said + if [ "$a" = qwen ] && case "$b" in *"$want"*) [ -n "$want" ] || [ -z "$b" ] ;; *) false ;; esac && [ -z "$c" ] \ + && { [ -z "$want" ] || case "$b" in *"--provider edge (free, online"*) true ;; *) false ;; esac; } \ + && grep -q 'prov=$(python3 "$ROOT/tools/audio/tts.py" --default-provider)' bin/vh + then ok "bin/vh tts: the default provider comes from tts.py alone; the local voice's first use is said before its 2.5 GB download (Apple Silicon), with the way around it; nothing for edge" + else bad "bin/vh tts's default and first-use line: $a | $b | $c"; fi # recipes sample: bad usage exits 2 before any render (an unknown id, a sequence, an unknown style); list --json names # the sheet a recipe carries (recipes check, above, holds every sketch to its sheet) vh recipes sample no-such-recipe >/dev/null 2>&1; rc=$?; vh recipes sample launch-15s >/dev/null 2>&1; rc2=$? diff --git a/tools/commands.json b/tools/commands.json index 305e3c75..c9373420 100644 --- a/tools/commands.json +++ b/tools/commands.json @@ -70,7 +70,7 @@ "writes": ["LOCAL.md (--fill-local: its machine lines that still hold the template; LOCAL.example.md copied first when there is none)"], "usage": [ { - "synopsis": "doctor [--json] [--fill-local] [--probe [--only a,b] [--offline DIR]]", + "synopsis": "doctor [--json] [--first] [--fill-local] [--probe [--only a,b] [--offline DIR]]", "text": [ "what this machine can use, from tools/modules.json (tools/doctor.py): each outside module's program and version (under the", "minimum, not the pin, or older than its max_age_days: outdated), the parts it needs, packages in uv's cache, a model in", @@ -79,7 +79,9 @@ "--probe: also call each service with a key, and each public one that takes none, once, at an endpoint that costs", "nothing (--only a,b: these modules alone; --offline DIR: answered from responses recorded the way", "tools/assets/fetch.py records them); --fill-local: also write LOCAL.md's machine lines (硬件, 已装工具, 已装引擎)", - "where they still hold the template, never a line a person wrote (the installer runs it). Exit 0: it is a report" + "where they still hold the template, never a line a person wrote (the installer runs it). --first: only the few lines", + "a first film needs (the installer ends with them): ready or not, what is missing and how to get it, how a voice", + "comes here (exit 1 when not ready). Exit 0: it is a report" ] }, { @@ -1629,7 +1631,7 @@ "--candidates N: N takes a block, the one nearest the narration's median voice kept (N × the synthesis);", "warns of a line far off the take's seconds per character, and (with --align) of a phrase heard twice;", "--resume: continue the last run after a failed synthesis or transcription, same script and command)", - "providers: qwen (default, local open-source Qwen3-TTS) | say | edge | dashscope | elevenlabs | gemini | gemini-lite | minimax" + "providers: qwen (default, local open-source Qwen3-TTS; its first use downloads about 2.5 GB, said first, with the progress) | say | edge | dashscope | elevenlabs | gemini | gemini-lite | minimax" ] } ] diff --git a/tools/doctor.py b/tools/doctor.py index 89282010..8976b6b8 100644 --- a/tools/doctor.py +++ b/tools/doctor.py @@ -1,8 +1,10 @@ """bin/vh doctor: what this machine can use, from the table of outside modules (tools/modules.json). Stdlib only. -usage: bin/vh doctor [--json] [--fill-local] [--probe [--only a,b] [--offline DIR]] +usage: bin/vh doctor [--json] [--first] [--fill-local] [--probe [--only a,b] [--offline DIR]] (bin/vh passes what its own finders found: --chrome, --hf-chrome, --hf-pin, --webgl) --json the same as JSON (below), the lines a person reads not printed + --first only the few lines a first film needs (the installer ends with them): ready or not, what is missing + for a first silent film and how to get it, how a voice comes here. Exit 1 when it is not ready --fill-local also write LOCAL.md's machine lines (硬件, 已装工具, 已装引擎) from this check, where they still hold the template's {…}; with no LOCAL.md, LOCAL.example.md is copied first. A line a person wrote stays; the other lines' {…} are their defaults (the installer runs this) @@ -28,7 +30,7 @@ a whole copy stays as it was when the repo moves on); studio-icon, the launcher bin/vh studio --install-icon makes (installed or not, which clone it runs, made by an earlier launcher or picture); caches, whether the folders a first run downloads into (uv's, npm's, Hugging Face's, HyperFrames', bin/vh's own) can be written, tried with a file made and removed. -Exit 0: it is a report (2 on a usage error or an unreadable table). +Exit 0: it is a report (2 on a usage error or an unreadable table; with --first, 1 when a first film still lacks something). --json, "version": 1 (these fields stay; new ones may be added): {"version", "tool", "platform", "modules": [{"name", "kind", "status" ("planned" when nothing calls it yet, else "used"), "required", "state", "found", "version", "keys": @@ -117,6 +119,45 @@ def references_note(have, want, fetched, said): " the one a doc points to, references/repos//…: bash references/fetch.sh )") +OWN_CHROME = ("darwin-arm64", "darwin-x86_64", "linux-x86_64") # where HyperFrames downloads its own chrome-headless-shell +LOCAL_VOICE = "about 2.5 GB" # the local voice's first use: mlx-audio and its packages (about 0.75 GB) and the model (1.8 GB on disk) + + +def first_film(mods, checks, plat): + """--first, the few lines install.sh ends with: is this machine ready for a first (silent) film, what it lacks for + one, and how a voice comes. → (lines, ready). Ready only with nothing missing that the first film needs: Node, FFmpeg, + Python 3, uv, a browser to render with (or a platform where the first render downloads its own), and an agent.""" + m, c = {x["name"]: x for x in mods}, {x["name"]: x for x in checks} + lack = [] + for name, what in (("node", "Node 22 or newer"), ("ffmpeg", "FFmpeg"), ("python3", "Python 3"), ("uv", "uv")): + r = m.get(name) + if r and r["state"] != "ok": + lack.append(f"{what} → {r.get('install') or 'install it'}") + own = plat in OWN_CHROME + if (c.get("browser") or {}).get("state") != "ok" and not own: + lack.append(f"a browser to render with → {(m.get('chrome') or {}).get('install') or 'set CHROME_PATH'}") + agents = [w for n, w in (("claude-code", "Claude Code"), ("codex", "Codex")) if (m.get(n) or {}).get("state") == "ok"] + if not agents: + lack.append("Claude Code or Codex → claude.com/claude-code, or npm install -g @openai/codex") + if lack: + lines = ["✗ Not ready for a first film yet. It still needs:"] + [f" {x}" for x in lack] + else: + lines = [f"✓ Ready for a first film: Node, FFmpeg, uv, a browser to render with, {' and '.join(agents)}"] + if (m.get("chrome-headless-shell") or {}).get("state") != "ok" and own: + lines.append(" The first render downloads its own Chrome once (about 0.2 GB).") + if (c.get("fonts") or {}).get("state") == "missing": + lines.append("! Chinese text: no Chinese font here, so it would draw as boxes → sudo apt install fonts-noto-cjk") + if plat == "darwin-arm64": + if (m.get("qwen3-tts") or {}).get("state") == "ok" and (m.get("mlx-audio") or {}).get("state") == "ok": + lines.append("✓ Voice: the local voice is downloaded.") + else: + lines.append(f"- Voice: the first bin/vh tts downloads the local voice once ({LOCAL_VOICE}; it says so first and shows the progress)." + " With --provider edge it downloads nothing (free, online).") + else: + lines.append("- Voice: bin/vh tts --provider edge (free, online), or a cloud voice with a key; the local voice needs Apple Silicon.") + return lines, not lack + + def this_platform(): m = platform.machine().lower() return f"{sys.platform}-{'arm64' if m in ('arm64', 'aarch64') else m}" @@ -137,7 +178,7 @@ def uv_has(pkgs): def hf_snapshot(model): """The Hugging Face snapshot folder of a model with weights in it, or None.""" - hub = os.environ.get("HF_HUB_CACHE") or os.path.join(os.environ.get("HF_HOME") or str(home("~/.cache/huggingface")), "hub") + hub = os.environ.get("HF_HUB_CACHE") or os.path.join(os.environ.get("HF_HOME") or os.path.join(os.environ.get("XDG_CACHE_HOME") or str(home("~/.cache")), "huggingface"), "hub") for snap in sorted(glob.glob(os.path.join(hub, "models--" + model.replace("/", "--"), "snapshots", "*", ""))): if glob.glob(os.path.join(snap, "*.safetensors")): return snap @@ -805,7 +846,7 @@ def print_module(m, r): def main(argv): - a = {"json": False, "probe": False, "fill-local": False, "offline": None, "only": None, "chrome": "", "hf-chrome": "", "hf-pin": "", "webgl": ""} + a = {"json": False, "probe": False, "fill-local": False, "first": False, "offline": None, "only": None, "chrome": "", "hf-chrome": "", "hf-pin": "", "webgl": ""} i = 0 while i < len(argv): x = argv[i] @@ -820,7 +861,7 @@ def main(argv): print(f"tools/modules.json: {len(t['modules'])} modules") return 1 if bad else 0 k, eq, v = x[2:].partition("=") - if x in ("--json", "--probe", "--fill-local"): + if x in ("--json", "--probe", "--fill-local", "--first"): a[x[2:]] = True elif k in ("offline", "only", "chrome", "hf-chrome", "hf-pin", "webgl") and x.startswith("--"): if not eq: @@ -829,7 +870,7 @@ def main(argv): i += 1; v = argv[i] a[k] = v else: - print(f"bin/vh doctor: unknown option {x} (usage: bin/vh doctor [--json] [--fill-local] [--probe [--only a,b] [--offline DIR]], or bin/vh doctor )", file=sys.stderr) + print(f"bin/vh doctor: unknown option {x} (usage: bin/vh doctor [--json] [--first] [--fill-local] [--probe [--only a,b] [--offline DIR]], or bin/vh doctor )", file=sys.stderr) return 2 i += 1 if (a["offline"] or a["only"] is not None) and not a["probe"]: @@ -855,9 +896,15 @@ def main(argv): pr = probe(m, a["offline"], recs) if a["probe"] and (only is None or m["name"] in only) else None mods[i] = {"name": m["name"], "kind": m["kind"], "status": m.get("status", "used"), "required": m["required"], **r, "install": (m.get("install") or {}).get("macos" if sys.platform == "darwin" else "linux"), "probe": pr} - if a["fill-local"]: # before the checks, so the LOCAL.md line says what is there now - print(fill_local(mods), file=sys.stderr if a["json"] else sys.stdout) + if a["fill-local"]: # before the checks, so the LOCAL.md line says what is there now (--first: written, not said) + said = fill_local(mods) + if not a["first"]: + print(said, file=sys.stderr if a["json"] else sys.stdout) checks = repo_checks(a["webgl"], found_by) + if a["first"] and not a["json"]: + lines, ready = first_film(mods, checks, this_platform()) + print("\n".join(lines)) + return 0 if ready else 1 first = [m.get("first_run") for m, r in zip(t["modules"], mods) if m.get("first_run") and r["state"] == "missing"] counts = {} for x in mods + checks: From 8ec76976b14dd71860dfa152802ccfc6d7bdfe85 Mon Sep 17 00:00:00 2001 From: zhanglinghao Date: Sun, 22 Nov 2026 03:12:46 +0800 Subject: [PATCH 02/19] install.sh: no references/repos yet is the usual first install (pipefail stopped the script there) --- install.sh | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/install.sh b/install.sh index 8a32c32f..d9c64abc 100755 --- a/install.sh +++ b/install.sh @@ -104,7 +104,7 @@ n=$(grep -cE '^(full|sparse|textonly) ' references/fetch.sh || true) # counted if [ "$REFS" = 1 ]; then say "fetching $n reference repos (about 300 MB, read-only, git-ignored)" references/fetch.sh || echo "! some reference repos were not fetched; bash references/fetch.sh fetches them later" -else had=$(find references/repos -mindepth 2 -maxdepth 2 -name .git 2>/dev/null | wc -l | tr -d ' ') +else had=0; [ ! -d references/repos ] || had=$(find references/repos -mindepth 2 -maxdepth 2 -name .git | wc -l | tr -d ' ') if [ "${had:-0}" -gt 0 ]; then echo " the $had reference repos fetched before stay as they are (--refs updates them and fetches the rest)"; fi fi say "installing the renderer for style samples (HyperFrames, for bin/vh style)" From 6d6de958a888ae9c1504983f997ef93cb976db3a Mon Sep 17 00:00:00 2001 From: zhanglinghao Date: Sun, 22 Nov 2026 03:33:42 +0800 Subject: [PATCH 03/19] bin/vh tts: a Ctrl-C during the local voice's package probe ends bin/vh too (it went on to uv run) --- bin/vh | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/bin/vh b/bin/vh index a9321046..33a2f683 100755 --- a/bin/vh +++ b/bin/vh @@ -1314,7 +1314,7 @@ cmd_tts() { deps="$deps${np:+ $np}" # the local voice's first use downloads gigabytes: said first in one line (how much, how long, the way around it), and # uv's own download lines shown instead of quieted (tts.py adds the model's progress) - if [ "$prov" = qwen ] && command -v uv >/dev/null 2>&1 && ! uv run -q --no-project --offline $deps python -c "" >/dev/null 2>&1; then quiet=""; fresh=--packages-missing; fi + if [ "$prov" = qwen ] && command -v uv >/dev/null 2>&1 && ! on_ctrl_c uv run -q --no-project --offline $deps python -c "" >/dev/null 2>&1; then quiet=""; fresh=--packages-missing; fi # (a Ctrl-C here ends bin/vh too) [ "$prov" != qwen ] || python3 "$ROOT/tools/audio/tts.py" --first-use qwen $fresh on_ctrl_c uv run $quiet --no-project $deps python "$ROOT/tools/audio/tts.py" "$proj" --provider "$prov" ${lang:+--lang "$lang"} ${voice:+--voice "$voice"} ${instruct:+--instruct "$instruct"} "$@" } From 3c73c044a144d96aead216cec2c3d0ccd8ae9452 Mon Sep 17 00:00:00 2001 From: zhanglinghao Date: Sun, 22 Nov 2026 04:14:32 +0800 Subject: [PATCH 04/19] Review of #228: python3 asked for, every big first download said, the checks run the behaviour - install.sh asks for python3 up front; bin/vh doctor --first with no python3 is not ready (exit 1). - doctor --first: a Chinese locale with no Chinese font is not ready; on Linux the render browser's missing system libraries are not ready, and libraries it cannot ask about are 'not checked' (exit 3, the installer then does not say ready); an outdated agent is told to update; Python 3 in the ready line; uv says what it is for. - tools/audio/firstuse.py: the local voice's and the local Whisper's first downloads in one table (sizes measured: 0.8 + 1.8 GB, 2.0 + 1.6 GB), the line before them, the model's progress written to the real stdout so a redirect_stdout around the loader cannot swallow it. bin/vh's first_use helper is used by tts, voices audition and pace; tts checks its script first. doctor and tts read the sizes from there; edge 'needs only a small package'. - references: one repo by name that does not come exits 1; a full fetch with no network is one line; 'under 1 MB'; doctor's references line is fine by default; setup says its size; four docs say the one-name fetch. - The example sentence follows the locale; the skill says to read the installer's last lines. - README sizes: no double count. CI: fetch.sh through a stand-in git, doctor --first's states, the bare doctor, the first-download lines through a stand-in uv, the progress inside a redirect. --- README.md | 2 +- README.zh-CN.md | 2 +- bin/vh | 50 +++++++---- cases/remotion-production.md | 2 +- changes/first-run.md | 13 +-- engines/README.md | 4 +- install.sh | 18 ++-- playbook/04-audio.md | 2 +- references/fetch.sh | 16 ++-- references/open-source.md | 2 +- skills/open-video-harness/SKILL.md | 4 + tools/audio/firstuse.py | 135 +++++++++++++++++++++++++++++ tools/audio/pace.py | 12 ++- tools/audio/tts.py | 72 ++++----------- tools/ci.sh | 117 ++++++++++++++++++------- tools/commands.json | 2 +- tools/doctor.py | 103 ++++++++++++++++------ tools/modules.json | 8 +- 18 files changed, 399 insertions(+), 165 deletions(-) create mode 100644 tools/audio/firstuse.py diff --git a/README.md b/README.md index 187520f3..d4ca7edb 100644 --- a/README.md +++ b/README.md @@ -423,7 +423,7 @@ bash install.sh --no-icon # leave OVH Studio out of your - The installer fetches only the newest commit: the repo itself is about 95 MB to download and 200 MB on disk, before its packages and the reference repos. To contribute or browse the history, `git clone` normally and run `bin/vh setup`. - To update, run the installer again with the same options (or `git pull`); `LOCAL.md` and `projects/` are left alone, and it stops before overwriting files you changed. The installed skills are short stubs that read `skills/` in the clone, so they follow the update; `bin/vh doctor` says in the rare case one needs `bin/vh install-skill` again. - The showcase videos aren't in git; to rebuild a showcase locally, `tools/fetch_media.sh` downloads them from the release to where its scripts expect them. -- The first render and the first use of the sound tools download more into `~/.cache`: Chrome about 200 MB, Python packages up to about 1.5 GB, and the default local voice about 2.5 GB, its model and packages, which `bin/vh tts` says before it starts, showing the progress (`--provider edge` downloads nothing; measured 2026-11; where each goes is on the wiki's [Getting Started](https://github.com/ZLHad/OpenVideoHarness/wiki/Getting-Started)). If npm, PyPI, Hugging Face or Google Fonts are blocked or slow where you are, [China network](https://github.com/ZLHad/OpenVideoHarness/wiki/China-Network) has the mirror settings. +- The first render and the first use of the sound tools download more into `~/.cache`: Chrome about 200 MB, the sound tools' Python packages about 0.7 GB, and the default local voice about 2.6 GB (its packages 0.8 GB, its model 1.8 GB), which `bin/vh tts` says before it starts and shows the progress of (`--provider edge` needs only a small package). The local Whisper behind `--align local` is about 3.6 GB more, said the same way (measured 2026-11; where each goes is on the wiki's [Getting Started](https://github.com/ZLHad/OpenVideoHarness/wiki/Getting-Started)). If npm, PyPI, Hugging Face or Google Fonts are blocked or slow where you are, [China network](https://github.com/ZLHad/OpenVideoHarness/wiki/China-Network) has the mirror settings. Skill only: `npx skills add https://github.com/ZLHad/OpenVideoHarness --skill open-video-harness`. It's a pointer: on first use it asks before installing the full workbench. That copy stays as it was when the repo changes; once the workbench is installed, `bin/vh install-skill` replaces it with a stub that follows the clone. diff --git a/README.zh-CN.md b/README.zh-CN.md index dbb778d2..72f71d3b 100644 --- a/README.zh-CN.md +++ b/README.zh-CN.md @@ -423,7 +423,7 @@ bash install.sh --no-icon # 不把 OVH Studio 放进应 - 安装脚本只拉最新的一个提交,仓库本身下载约 95 MB、占约 200 MB 磁盘,依赖和参考仓库另算;想参与贡献或翻历史,就正常 `git clone`,再运行 `bin/vh setup`。 - 更新:用同样的参数再运行一次安装命令(或者 `git pull`);`LOCAL.md` 和 `projects/` 不动,要覆盖你改过的文件时会先停下来。装出去的 skill 是指回克隆里 `skills/` 的短桩,跟着一起更新;少数要重装的时候(`bin/vh install-skill`),`bin/vh doctor` 会说。 - 样片的视频不在 git 里,要在本地复现样片时运行 `tools/fetch_media.sh`,它从 Release 下载到脚本要的位置。 -- 第一次渲染、第一次用声音工具时还会往 `~/.cache` 下载:Chrome 约 200 MB,Python 依赖最多约 1.5 GB,默认的本地配音约 2.5 GB(模型加它的依赖;`bin/vh tts` 开始前会先说,并显示进度;`--provider edge` 什么都不下)(2026-11 实测;各放在哪里见 wiki 的[快速开始](https://github.com/ZLHad/OpenVideoHarness/wiki/%E5%BF%AB%E9%80%9F%E5%BC%80%E5%A7%8B))。国内网络连不上 npm、PyPI、Hugging Face 或 Google Fonts 时,镜像设置见 wiki 的[国内网络](https://github.com/ZLHad/OpenVideoHarness/wiki/%E5%9B%BD%E5%86%85%E7%BD%91%E7%BB%9C)。 +- 第一次渲染、第一次用声音工具时还会往 `~/.cache` 下载:Chrome 约 200 MB,声音工具的 Python 依赖约 0.7 GB,默认的本地配音约 2.6 GB(依赖 0.8 GB、模型 1.8 GB;`bin/vh tts` 开始前会先说,并显示进度;`--provider edge` 只要一个小包);`--align local` 用的本地 Whisper 另需约 3.6 GB,同样先说(2026-11 实测;各放在哪里见 wiki 的[快速开始](https://github.com/ZLHad/OpenVideoHarness/wiki/%E5%BF%AB%E9%80%9F%E5%BC%80%E5%A7%8B))。国内网络连不上 npm、PyPI、Hugging Face 或 Google Fonts 时,镜像设置见 wiki 的[国内网络](https://github.com/ZLHad/OpenVideoHarness/wiki/%E5%9B%BD%E5%86%85%E7%BD%91%E7%BB%9C)。 只装 skill:`npx skills add https://github.com/ZLHad/OpenVideoHarness --skill open-video-harness`。它只是一个指针,第一次用时会征得你同意,再把完整的工作台装好。这样装的是整份副本,仓库更新了它不变;工作台装好以后跑一次 `bin/vh install-skill`,换成跟随克隆的短桩。 diff --git a/bin/vh b/bin/vh index 33a2f683..21660ee4 100755 --- a/bin/vh +++ b/bin/vh @@ -57,7 +57,7 @@ cmd_doctor() { case "${1:-}" in ""|-*) ;; *) python3 "$ROOT/tools/engine_copy.py" "$@"; return ;; esac # this machine: tools/doctor.py reads tools/modules.json and reports; bin/vh hands it what its own finders find (the # browser the page tools take, the chrome-headless-shell HyperFrames pins) and the WebGL probe, which runs only here - command -v python3 >/dev/null 2>&1 || { doctor_bare "$@"; return 0; } + command -v python3 >/dev/null 2>&1 || { doctor_bare "$@"; case " $* " in *" --first "*) return 1 ;; esac; return 0; } # --first: not ready local a skip="" live="" rec="" for a in "$@"; do # a usage error is said at once (by doctor.py), before the probe below if [ -n "$skip" ]; then skip=""; continue; fi @@ -182,7 +182,7 @@ cmd_sync_agents() { # CLAUDE.md's 命令行 line from tools/commands.json first, cmd_setup() { echo "→ installing ClaudeAnimationBase deps"; (cd "$ROOT/engines/ClaudeAnimationBase" && npm install --silent) - echo "→ fetching reference repos"; "$ROOT/references/fetch.sh" + echo "→ fetching all $(grep -cE '^(full|sparse|textonly) ' "$ROOT/references/fetch.sh") reference repos (about 300 MB; an install fetches each on first use instead)"; "$ROOT/references/fetch.sh" echo "→ installing the style swatch renderer"; (cd "$ROOT/styles/_swatch" && npm ci --silent) [ -f "$ROOT/LOCAL.md" ] || cp "$ROOT/LOCAL.example.md" "$ROOT/LOCAL.md" echo "→ smoke test" @@ -1299,12 +1299,12 @@ cmd_tts() { [ -d "$proj" ] || { echo "$c_no bin/vh tts: no such project: $proj" >&2; exit 2; } # before uv builds an environment; tts.py would make the folder shift while [ $# -gt 0 ] && [ ${#pos[@]} -lt 4 ] && [[ "$1" != --* ]]; do pos+=("$1"); shift; done # positionals stop at the first --flag - local prov=${pos[0]:-} voice=${pos[1]:-} lang=${pos[2]:-} instruct=${pos[3]:-} a prev="" np="" quiet=-q fresh="" + local prov=${pos[0]:-} voice=${pos[1]:-} lang=${pos[2]:-} instruct=${pos[3]:-} a prev="" np="" kinds=() [ -n "$prov" ] || prov=$(python3 "$ROOT/tools/audio/tts.py" --default-provider) # tts.py's DEFAULT_PROVIDER, the one place it is set for a in "$@"; do # tts.py's own --provider X / --provider=X picks the dependencies too; the last one wins, as in argparse [ "$prev" = --provider ] && prov=$a - case "$a" in --provider=*) prov=${a#--provider=} ;; --candidates|--candidates=*) np="--with numpy" ;; --align=local) np="$np --with mlx-whisper" ;; esac # the takes are measured with numpy - [ "$prev|$a" = "--align|local" ] && np="$np --with mlx-whisper" # a local Whisper for the word times + case "$a" in --provider=*) prov=${a#--provider=} ;; --candidates|--candidates=*) np="--with numpy" ;; --align=local) np="$np --with mlx-whisper"; kinds+=(whisper) ;; esac # the takes are measured with numpy + [ "$prev|$a" = "--align|local" ] && { np="$np --with mlx-whisper"; kinds+=(whisper); } # a local Whisper for the word times prev=$a done # everything from the first --flag on goes straight to tts.py (--beats, --snap, --lead, --gap, --min-gap, --align, --join, --candidates, --min-sim, --vocab, --resume) @@ -1312,24 +1312,40 @@ cmd_tts() { case "$prov" in qwen) deps="--with mlx-audio" ;; edge) deps="--with edge-tts" ;; dashscope) [ -z "${DASHSCOPE_API_KEY:-}" ] || deps="--with dashscope" ;; esac # no key: tts.py says so, with no package fetched first deps="$deps${np:+ $np}" - # the local voice's first use downloads gigabytes: said first in one line (how much, how long, the way around it), and - # uv's own download lines shown instead of quieted (tts.py adds the model's progress) - if [ "$prov" = qwen ] && command -v uv >/dev/null 2>&1 && ! on_ctrl_c uv run -q --no-project --offline $deps python -c "" >/dev/null 2>&1; then quiet=""; fresh=--packages-missing; fi # (a Ctrl-C here ends bin/vh too) - [ "$prov" != qwen ] || python3 "$ROOT/tools/audio/tts.py" --first-use qwen $fresh - on_ctrl_c uv run $quiet --no-project $deps python "$ROOT/tools/audio/tts.py" "$proj" --provider "$prov" ${lang:+--lang "$lang"} ${voice:+--voice "$voice"} ${instruct:+--instruct "$instruct"} "$@" + # no script yet: tts.py writes a sample and stops, with no package fetched for it (it needs none for that) + [ -f "$proj/audio/script.txt" ] || exec python3 "$ROOT/tools/audio/tts.py" "$proj" --provider "$prov" + [ "$prov" != qwen ] || kinds+=(qwen) + first_use ${kinds[@]+"${kinds[@]}"} + on_ctrl_c uv run $uvq --no-project $deps python "$ROOT/tools/audio/tts.py" "$proj" --provider "$prov" ${lang:+--lang "$lang"} ${voice:+--voice "$voice"} ${instruct:+--instruct "$instruct"} "$@" +} +first_use() { # first_use [kind…]: before a command that can start one of the big first downloads (qwen: the local voice; whisper: + # the local Whisper), say it in one line (tools/audio/firstuse.py: how much, how long, the way around it, its sizes in one + # place) and set uvq to show uv's own download lines instead of quieting them; the model's progress comes from the tool. + # Apple Silicon only: elsewhere these do not run, and the command says so itself + local k pk miss="" + uvq=-q + [ $# -gt 0 ] && [ "$(uname -s) $(uname -m)" = "Darwin arm64" ] && command -v uv >/dev/null 2>&1 || return 0 + for k in "$@"; do + pk=$(python3 "$ROOT/tools/audio/firstuse.py" --package "$k") || continue + on_ctrl_c uv run -q --no-project --offline --with "$pk" python -c "" >/dev/null 2>&1 || miss="$miss${miss:+,}$k" # (a Ctrl-C here ends bin/vh too) + done + [ -z "$miss" ] || uvq="" + python3 "$ROOT/tools/audio/firstuse.py" "$(IFS=,; echo "$*")" ${miss:+--packages-missing "$miss"} } cmd_voices() { # audition measures the takes (numpy) and synthesizes with the provider's own packages, through uv [ $# -gt 0 ] || set -- list [ "$1" = audition ] || { python3 "$ROOT/tools/audio/tts.py" voices "$@"; return; } - local a prev="" prov=gemini deps="--with numpy" - for a in "$@"; do [ "$prev" = --provider ] && prov=$a; [ "$prev|$a" = "--align|local" ] && deps="$deps --with mlx-whisper"; case "$a" in --provider=*) prov=${a#--provider=} ;; --align=local) deps="$deps --with mlx-whisper" ;; esac; prev=$a; done - case "$prov" in qwen) deps="$deps --with mlx-audio" ;; edge) deps="$deps --with edge-tts" ;; dashscope) deps="$deps --with dashscope" ;; esac - on_ctrl_c uv run -q --no-project $deps python "$ROOT/tools/audio/tts.py" voices "$@" + local a prev="" prov=gemini deps="--with numpy" kinds=() + for a in "$@"; do [ "$prev" = --provider ] && prov=$a; [ "$prev|$a" = "--align|local" ] && { deps="$deps --with mlx-whisper"; kinds+=(whisper); }; case "$a" in --provider=*) prov=${a#--provider=} ;; --align=local) deps="$deps --with mlx-whisper"; kinds+=(whisper) ;; esac; prev=$a; done + case "$prov" in qwen) deps="$deps --with mlx-audio"; kinds+=(qwen) ;; edge) deps="$deps --with edge-tts" ;; dashscope) deps="$deps --with dashscope" ;; esac + first_use ${kinds[@]+"${kinds[@]}"} + on_ctrl_c uv run $uvq --no-project $deps python "$ROOT/tools/audio/tts.py" voices "$@" } cmd_pace() { # numpy for the waveform; mlx-whisper only with --align whisper (Apple Silicon) - local a prev="" deps="--with numpy" - for a in "$@"; do case "$prev:$a" in --align:whisper|*:--align=whisper|--align:local|*:--align=local) deps="$deps --with mlx-whisper" ;; esac; prev=$a; done - on_ctrl_c uv run -q --no-project $deps python "$ROOT/tools/audio/pace.py" "$@" + local a prev="" deps="--with numpy" kinds=() + for a in "$@"; do case "$prev:$a" in --align:whisper|*:--align=whisper|--align:local|*:--align=local) deps="$deps --with mlx-whisper"; kinds=(whisper) ;; esac; prev=$a; done + first_use ${kinds[@]+"${kinds[@]}"} + on_ctrl_c uv run $uvq --no-project $deps python "$ROOT/tools/audio/pace.py" "$@" } cmd_captions() { # --media-end S: where a caption too short for its minimum may be lengthened to (default: the picture's length) local u="usage: bin/vh captions [zh|en] [zh-max] [--en-max 42] [--cards] [--cps 9] [--media-end S] [--skip-lint]" x diff --git a/cases/remotion-production.md b/cases/remotion-production.md index 9d9a8b7c..85ff8f22 100644 --- a/cases/remotion-production.md +++ b/cases/remotion-production.md @@ -31,4 +31,4 @@ - 动画必须用 `useCurrentFrame()` 加 `interpolate()` 驱动。CSS transition、CSS animation 和 Tailwind 的动画类在渲染时都不会正确生效。 - 字幕:`@remotion/install-whisper-cpp` 的 `transcribe()`,再加 `toCaptions`。 - 配音:用 ElevenLabs 为每个场景生成一个 mp3,在 `calculateMetadata` 里读取音频时长,设置 `durationInFrames`。 -- 官方 skills 已拉到本地:`references/repos/remotion-skills/skills/`。 +- 官方 skills 在 `references/repos/remotion-skills/skills/`(没有就先 `bash references/fetch.sh remotion-skills`,约 2 MB)。 diff --git a/changes/first-run.md b/changes/first-run.md index e22c5b0b..af9c136d 100644 --- a/changes/first-run.md +++ b/changes/first-run.md @@ -1,7 +1,8 @@ -**安装更轻,最后一屏只说第一支片要知道的事;本地配音第一次下载前先说** -- Why: 在干净的机器上量过,安装 90 秒里有 71 秒、305 MB 在拉参考仓库,而第一支片用不到它们;安装最后一屏是 60 多行 doctor,十几行黄色提示大多和第一支片无关,Linux 上真挡路的缺项淹在里面,最后照样说"ready";本地配音第一次用要静默下载约 2.5 GB。 -- 37 个参考仓库安装时不再拉:agent 用到文档指的那一个时再拉,`references/fetch.sh <目录>` 拉之前用一行说清拉什么、从哪、多大(大小表在脚本里,CI 查每一个都有);名字写错时说清并退出 2。`install.sh --refs` 一次拉全;`--no-refs` 照旧认,现在就是默认。之前拉过的留着不动。 -- 安装最后几行换成 `bin/vh doctor --first`:能不能做第一支片,缺什么、一句怎么补(Node、FFmpeg、Python、uv、能渲染的浏览器、一个 agent),Linux 上缺中文字体也说,配音在这台机器上怎么来;有缺的就不说 ready。完整报告照旧是 `bin/vh doctor`。skill 注册只说一行。示例句换成 README 那条无声 15 秒。 -- `bin/vh tts` 用本地配音、第一次要下载时,先说一行:约多大、大概多久、显示进度,以及不用下载的办法(`--provider edge`,免费,在线:稿子会发到微软的配音服务);Python 包的下载逐个显示,模型下载每 10 秒说一次下了多少。默认配音只在 `tools/audio/tts.py` 的 `DEFAULT_PROVIDER` 一处设,`bin/vh tts` 问它。 +**安装更轻,最后一屏只说第一支片要知道的事;几个 GB 的第一次下载都先说一声** +- Why: 在干净的机器上量过,安装 90 秒里有 71 秒、305 MB 在拉参考仓库,而第一支片用不到它们;安装最后一屏是 60 多行 doctor,十几行黄色提示大多和第一支片无关,Linux 上真挡路的缺项淹在里面,最后照样说"ready";本地配音第一次用要静默下载约 2.6 GB。 +- 37 个参考仓库安装时不再拉:agent 用到文档指的那一个时再拉,`references/fetch.sh <目录>` 拉之前用一行说清拉什么、从哪、多大(大小表在脚本里,CI 查每一个都有);指名的那一个没拉下来就退出 1,名字写错退出 2;拉全部时断网只说一行。`install.sh --refs` 一次拉全;`--no-refs` 照旧认,现在就是默认。之前拉过的留着不动。`bin/vh doctor` 不再把没拉的参考仓库当成缺项。`bin/vh setup` 仍然拉全部,先说约 300 MB。 +- 安装最后几行换成 `bin/vh doctor --first`:能不能做第一支片,缺什么、一句怎么补(Node、FFmpeg、Python 3、uv、能渲染的浏览器和它要的系统库、一个 agent;中文环境下还有中文字体),配音在这台机器上怎么来;有缺的就不说 ready,没法检查的(Linux 上问不到浏览器的系统库)说"没检查",也不说 ready。完整报告照旧是 `bin/vh doctor`。安装前就要 python3。skill 注册只说一行。示例句跟着你的语言:中文环境是 README 那条无声 15 秒,其他是它的英文版。skill 里写明:安装看最后几行,不看退出码。 +- 几个 GB 的第一次下载,开始前都先说一行:约多大、大概多久、显示进度,以及不用下载的办法。本地配音(`bin/vh tts`、`voices audition`)约 2.6 GB,`--provider edge` 只要一个小包(免费,在线:稿子会发到微软的配音服务);本地 Whisper(`tts`、`voices audition --align local`、`pace --align whisper`)约 3.6 GB,`--align gemini` 不用下载。Python 包的下载逐个显示,模型下载每 10 秒说一次下了多少(输出给 agent 看、或者外面关了进度条时)。大小只记在 `tools/audio/firstuse.py` 一处,doctor 也从那里读。`bin/vh tts` 先查稿子:没有稿子时写一份示例就停,一个包都不下。 +- 默认配音只在 `tools/audio/tts.py` 的 `DEFAULT_PROVIDER` 一处设,`bin/vh tts` 问它。 - doctor 找本地配音模型时也看 `XDG_CACHE_HOME`(Hugging Face 自己就这样找)。 -- README 中英文和官网的安装大小按实测更新:安装约 400 MB,`--refs` 再约 300 MB,本地配音约 2.5 GB。 +- README 中英文和官网的安装大小按实测更新:安装约 400 MB,`--refs` 再约 300 MB,本地配音约 2.6 GB,本地 Whisper 约 3.6 GB。 diff --git a/engines/README.md b/engines/README.md index 89d01817..d31167ba 100644 --- a/engines/README.md +++ b/engines/README.md @@ -109,7 +109,7 @@ HYPERFRAMES_RENDER_DETACHED=1 nohup caffeinate -i npx hyperframes render --quali - **`font-weight: 800` 在 macOS 自带的 PingFang SC 上等于 600。** 现象:字幕规格写了字重 800,渲出来却不够粗,也没有报错。原因:PingFang SC 只有 6 个字重,从 Ultralight 到 Semibold(CSS 的 100–600),没有 Bold 和 Heavy;请求 700、800、900 都落到 600,实测渲出的字和 600 逐像素相同,浏览器也不会再合成粗体。解决:用 PingFang SC 就写 600,并在 STYLE.md 里记下;真要 800,自己带一个有这个字重的字体(Noto Sans SC 等,不联网的取法见 wiki 的[国内网络](https://github.com/ZLHad/OpenVideoHarness/wiki/%E5%9B%BD%E5%86%85%E7%BD%91%E7%BB%9C)),或者换一个有更粗字重的系统字体(比如 Songti SC 有 900,`styles/_swatch/README.md` 的字体表列了各字体实测可用的字重)。 - **`--format png-sequence` 写出的是 RGBA,而且不画 `html`、`body` 的背景。** 那些地方 alpha = 0,元素自己的底色会留下。0.8.82 连合成根元素(带 `data-composition-id` 的那个)上的 `background` 也不画;0.8.202 画它,根元素有不透明的底色时整帧不透明,PNG 就成了不带 alpha 的 RGB(2026-10-26 用 html、body、根元素三种写法各测一遍)。做确定性检查时要留意,细节和比对办法见 `playbook/02-verification.md` 的"确定性"一节。 - **现成的块和组件**(字幕样式、lower-third、转场、图表等,0.8.202 的 registry 有 448 个):`bin/vh hf catalog <词>` 查,`bin/vh hf add <项目> <名字>` 装。它把项目的 `hyperframes.json` 钉到这个版本的 tag(HyperFrames 默认取 GitHub `main` 上最新的那份),装进来的文件记进素材台账,并提示里面用了 CSS 动画、`Math.random` 或联网加载的地方。 -- **不要运行 `npx hyperframes skills update`**。skill 文档已经拉到本地,直接读:`references/repos/hyperframes/skills/`(工作流和参考资料)、`references/repos/hyperframes/_upstream_claude/skills/`(motion-doctrine 等内部规范,写动画前先读 motion-doctrine)。 +- **不要运行 `npx hyperframes skills update`**。skill 文档在参考仓库里(没有就先 `bash references/fetch.sh hyperframes`,约 11 MB),直接读:`references/repos/hyperframes/skills/`(工作流和参考资料)、`references/repos/hyperframes/_upstream_claude/skills/`(motion-doctrine 等内部规范,写动画前先读 motion-doctrine)。 - 想让所有项目都能用 `/hyperframes`、`/faceless-explainer` 等命令,可以装成 Claude Code 的用户级插件(`claude plugin marketplace add heygen-com/hyperframes && claude plugin install hyperframes@hyperframes`)。这会修改全局配置,**必须先征得用户同意**。 - **没有 `@font-face` 的字体,渲染时会去 Google Fonts 取。** `render`、`snapshot`、`check` 每次运行都请求,连不上就挂住(render 停在 5% 的 "Compiling composition")。lint 拦不住其中两种:它别名表里的名字(Arial、Helvetica Neue、Menlo 等)没有声明也算通过,渲染时被换成 Inter、JetBrains Mono 去取;以 `sans-serif` 这类通用族名开头的栈,前面会被补上 Inter。所以本机字体也写 `@font-face`、`src` 用 `local()`,栈里排第一的写声明过的字体,照 `bin/vh hf-init` 搭的脚手架做。渲染日志里出现 `[Compiler] Injected deterministic @font-face rules`,就是还有字体没声明。国内网络下的做法见 wiki 的[国内网络](https://github.com/ZLHad/OpenVideoHarness/wiki/%E5%9B%BD%E5%86%85%E7%BD%91%E7%BB%9C)。 - **字体里缺的字**:字体在、字不在时,浏览器换一个字体画这个字,哪个字体都没有就画成空的缺字字形(苹方的是空白),lint 和渲染都不报。`bin/vh fonts check <项目>` 用 HyperFrames 自己的运行时抽帧,查每个 clip 的 DOM 字和 canvas 字实际由哪个字体画(2026-10-12 在一台 Mac 上:showcase 00 的 "LF Mono" 里有三个汉字落到了苹方,showcase 02 的"Δ"落到了 Arial)。HyperFrames 渲染时把 Google 字体换成它缓存的一份,这个检查看的是页面声明的字体,所以 `local()` 和项目里的字体文件最准。 @@ -251,7 +251,7 @@ npx remotion studio # 预览 ``` - 许可:个人和 3 人以内的公司免费,超过这个规模需要购买授权。 -- 官方 skills 已拉到本地:`references/repos/remotion-skills/skills/`。 +- 官方 skills 在 `references/repos/remotion-skills/skills/`(没有就先 `bash references/fetch.sh remotion-skills`,约 2 MB)。 ## Manim CE(Python),装进每个项目 diff --git a/install.sh b/install.sh index d9c64abc..ccd5174c 100755 --- a/install.sh +++ b/install.sh @@ -26,8 +26,9 @@ # your home directory, without asking: # - the first hyperframes render: HyperFrames' own chrome-headless-shell (about 200 MB, ~/.cache/hyperframes) # - the first bin/vh beats, music, sfx, qa or sheet: their Python packages, through uv (about 700 MB, ~/.cache/uv) -# - the first bin/vh tts with the default qwen provider (skipped with another one): its Python packages (about 750 MB, ~/.cache/uv) -# and the Qwen3-TTS model (1.8 GB, ~/.cache/huggingface); bin/vh tts says so before it starts and shows the progress +# - the first bin/vh tts with the default qwen provider (skipped with another one): its Python packages (about 0.8 GB, ~/.cache/uv) +# and the Qwen3-TTS model (1.8 GB, ~/.cache/huggingface); --align local adds the local Whisper (about 3.6 GB); bin/vh tts says +# so before it starts and shows the progress (the sizes: tools/audio/firstuse.py) # - every bin/vh new short, promo, data or meme: about 140 MB of node_modules in that project # The wiki's Getting Started ("What gets downloaded") has the same list. set -euo pipefail @@ -65,7 +66,7 @@ if [ "$(uname -s)" = Darwin ] && [ "$(command -v git)" = /usr/bin/git ] && ! xco echo "✗ First this Mac needs Apple's command line tools (git comes with them): run xcode-select --install, then run this installer again."; exit 1 fi missing="" -for t in git node ffmpeg; do command -v "$t" >/dev/null 2>&1 || missing="$missing $t"; done +for t in git node ffmpeg python3; do command -v "$t" >/dev/null 2>&1 || missing="$missing $t"; done # (bin/vh's commands run on python3) if [ -n "$missing" ]; then if [ "$(uname -s)" = Darwin ] && command -v brew >/dev/null 2>&1; then how="brew install${missing}" elif [ "$(uname -s)" = Darwin ]; then how="get Homebrew (https://brew.sh), then brew install${missing}" @@ -120,13 +121,16 @@ fi ICON_LATER=""; ICON_DONE=""; ICON_HEADLESS=""; put_icon echo # the last lines: ready for a first film or not, what it still needs, how a voice comes here (the full report: bin/vh doctor) -READY=""; bin/vh doctor --fill-local --first && READY=1 +st=0; bin/vh doctor --fill-local --first || st=$? # 0 ready, 3 one thing not checked, else not ready echo -if [ -n "$READY" ]; then echo "✓ OpenVideoHarness is ready at $DIR. Two ways to start:" -else echo "✗ OpenVideoHarness is installed at $DIR; a first film still needs what is listed above. Then, two ways to start:"; fi +case $st in 0) echo "✓ OpenVideoHarness is ready at $DIR. Two ways to start:" ;; + 3) echo "OpenVideoHarness is installed at $DIR; one thing above could not be checked here. Two ways to start:" ;; + *) echo "✗ OpenVideoHarness is installed at $DIR; a first film still needs what is listed above. Then, two ways to start:" ;; esac if [ -n "$ICON_DONE" ]; then echo " 1. Click OVH Studio in your applications: your films, their stops and the agent, in one window." elif [ -n "$ICON_HEADLESS" ]; then echo " 1. Studio, in a browser on another computer: cd \"$DIR\" && bin/vh studio --print-address (this machine has no desktop)" else echo " 1. Studio, your films in one window: cd \"$DIR\" && bin/vh studio$([ -z "$ICON_LATER" ] || printf ' (bin/vh studio --install-icon puts it in your applications)')"; fi echo " 2. Open Claude Code or Codex in that folder (cd \"$DIR\" && claude) and say what film you want, e.g." -echo " \"快速出一版 15 秒的竖屏无声科普,用方格和画面文字讲清楚为什么正方形边长翻倍,面积变成四倍。\"" +case "${LC_ALL:-${LC_MESSAGES:-${LANG:-}}}" in # the example in the person's language (the README's silent first film) + zh*|ZH*) echo " \"快速出一版 15 秒的竖屏无声科普,用方格和画面文字讲清楚为什么正方形边长翻倍,面积变成四倍。\"" ;; + *) echo " \"Quick draft: make a silent 15-second vertical explainer showing why doubling a square's side length quadruples its area. Use a grid and on-screen text.\"" ;; esac echo " The full report of this machine: bin/vh doctor" diff --git a/playbook/04-audio.md b/playbook/04-audio.md index 3adc8df8..57b73c84 100644 --- a/playbook/04-audio.md +++ b/playbook/04-audio.md @@ -62,7 +62,7 @@ bin/vh beats <任意音乐文件> # 外来音乐的节 | provider | 什么时候用 | |---|---| -| `qwen`(默认) | 本地开源 Qwen3-TTS,免费、离线,首次下载约 2 GB;0.6B 模型念英文短句偶尔停不下来,每条都要查 | +| `qwen`(默认) | 本地开源 Qwen3-TTS,免费、离线,首次下载约 2.6 GB(`bin/vh tts` 开始前先说,并显示进度);0.6B 模型念英文短句偶尔停不下来,每条都要查 | | `gemini` | 云端,表演力最好,能用一句话导演语气,适合讲解旁白和双人对话;要 `GEMINI_API_KEY` | | `minimax` | 云端 MiniMax(`speech-2.8-hd`),中文音色多(`Chinese (Mandarin)_*`)。`--join all` 整份稿一个请求,从头到尾一个声音;自带逐字时间,不用转写;支持停顿标记 `<#0.4#>` 和发音词典 `@pronounce`。语气只认一个情绪词。要 `MINIMAX_TOKEN_PLAN_KEY` 或 `MINIMAX_API_KEY`,细节见 `tools/audio/README.md` 的"MiniMax" | | `say` / `edge` | 打草稿;只能念,不能演 | diff --git a/references/fetch.sh b/references/fetch.sh index b069541a..ea22afbf 100755 --- a/references/fetch.sh +++ b/references/fetch.sh @@ -29,9 +29,11 @@ SIZES=" story-to-handdrawn-video 3 video-shotcraft 11 video-talkcraft 18 viral-video-decomposer 4 vox-director <1 " size_of() { printf '%s\n' $SIZES | awk -v d="$1" 'p { print; exit } $0 == d { p = 1 }'; } -announce() { # announce :第一次拉一个之前,一行说清拉什么、从哪、多大 +announce() { # announce :只拉一个时,第一次拉之前一行说清拉什么、从哪、多大(拉全部时调用方已说过总共多大) + [ -n "$ARG" ] || return 0 local mb; mb=$(size_of "$2") - echo "fetching $2 from github.com/$1 (${mb:+about $mb MB, }read-only, for agents to read)" + case "$mb" in "<1") mb="under 1 MB, " ;; "") ;; *) mb="about $mb MB, " ;; esac + echo "fetching $2 from github.com/$1 (${mb}read-only, for agents to read)" } MATCHED="" @@ -58,12 +60,13 @@ skip() { # 按参数决定是否跳过这一行;--neutralize 模式只 MATCHED=1; return 1 } SKIPPED="" -failed() { # failed <原因>:一个上游拉不下来只跳过这一行,不中断其余仓库和调用本脚本的安装流程 - echo "skip $1 ($2)"; SKIPPED="$SKIPPED $1" +failed() { # failed <原因>:一个上游拉不下来只跳过这一行,不中断其余仓库和调用本脚本的安装流程(拉全部时最后一行一起说) + [ -z "$ARG" ] || echo "skip $1 ($2)"; SKIPPED="$SKIPPED $1" } clone() { # clone [git clone 参数...] local r=$1 d=$2; shift 2 - git clone -q --depth 1 "$@" "https://github.com/$r.git" "$d" || { failed "$d" "clone failed"; return 1; } + git clone -q --depth 1 "$@" "https://github.com/$r.git" "$d" 2>"${TMPDIR:-/tmp}/fetch-$d.err" || { failed "$d" "clone failed: $(tail -1 "${TMPDIR:-/tmp}/fetch-$d.err")"; rm -f "${TMPDIR:-/tmp}/fetch-$d.err"; return 1; } + rm -f "${TMPDIR:-/tmp}/fetch-$d.err" } full() { # full :整仓浅克隆 @@ -146,5 +149,6 @@ textonly annnguyentt/anatomy-reveal-skill anatomy-reveal # 用 textonly EL4CTEO/blender-skills blender-skills # Blender 5.2 的建模、UV、PBR、烘焙、绑骨、导出和资产质检 skill,`blender -b` 就能跑;bin/vh model3d check --blender 借它 asset-qa 的检查(MIT) [ -z "$ARG" ] || [ "$ARG" = --neutralize ] || [ -n "$MATCHED" ] || { echo "no reference repo named $ARG: the names are the second column of references/fetch.sh" >&2; exit 2; } -[ -z "$SKIPPED" ] || echo "skipped (re-run later, e.g. bash references/fetch.sh ):$SKIPPED" +[ -z "$SKIPPED" ] || echo "skipped $(echo $SKIPPED | wc -w | tr -d ' ') (no network? re-run later, e.g. bash references/fetch.sh ):$SKIPPED" +[ -z "$ARG" ] || [ -z "$SKIPPED" ] || exit 1 # the one asked for did not come: say so in the exit status too exit 0 diff --git a/references/open-source.md b/references/open-source.md index 3b2ec18b..f15ad86a 100644 --- a/references/open-source.md +++ b/references/open-source.md @@ -2,7 +2,7 @@ 所有项目都通过 GitHub API 核实过存在性;⭐ 是约数,日期是最近一次 push。 -已拉到本地的仓库都在 `references/repos/`(运行 `references/fetch.sh` 更新),包括: +下面这些仓库由 `references/fetch.sh` 拉进 `references/repos/`:安装时默认不拉,用到哪一个再拉哪一个(`bash references/fetch.sh <目录>`,拉之前说多大),`bash references/fetch.sh` 一次拉全(约 300 MB)。其中有: - PDoomVideo、functional-emotions-video、hyperframes-launches、remotion-skills; - HyperFrames 的 skills(部分检出)、Code2Video 的 prompts 和 src(部分检出)、3brown1blue 的 skill(部分检出); - 2026-09-29 补:Battle-of-Austerlitz-Film、claude-animation-skill、product-film-skill、procedural-film,以及两份 Opus 5.5 作品目录(athemeroy、zhuyansen)。社区 skill 和目录的完整清单见 `community-skills.md`。 diff --git a/skills/open-video-harness/SKILL.md b/skills/open-video-harness/SKILL.md index a0ea0fc6..b848fde5 100644 --- a/skills/open-video-harness/SKILL.md +++ b/skills/open-video-harness/SKILL.md @@ -25,6 +25,10 @@ If none exists, ask the user for permission, then install it: curl -fsSL https://raw.githubusercontent.com/ZLHad/OpenVideoHarness/main/install.sh | bash ``` +Read the installer's last lines, not its exit status: it exits 0 whenever the install itself worked, and its last lines +say whether a first film can be made here ("✗ Not ready for a first film yet" lists what is missing, each with how to +get it). Tell the user what is missing before starting a film. + ## 2. Follow the harness, not this file Read `/CLAUDE.md` (Codex: `/AGENTS.md`, which is identical) and follow it: diff --git a/tools/audio/firstuse.py b/tools/audio/firstuse.py new file mode 100644 index 00000000..cfe32ec4 --- /dev/null +++ b/tools/audio/firstuse.py @@ -0,0 +1,135 @@ +"""The big first downloads the sound commands can start, said before they start. Stdlib only. + +usage: python3 tools/audio/firstuse.py [--packages-missing kind[,kind]] the one line (nothing when nothing big + is to come); bin/vh's first_use helper + python3 tools/audio/firstuse.py --package the Python package bin/vh probes for it + +Kinds: qwen, the local voice (bin/vh tts and voices audition with the default provider); whisper, the local Whisper (tts and +voices audition --align local, pace --align whisper). Each is Python packages fetched by uv on first use and a model fetched +from Hugging Face on first load, on Apple Silicon only (mlx). Their sizes live here and only here: bin/vh doctor --first and +the line bin/vh says read them. Measured 2026-11-22 on macOS (Apple Silicon), each in an empty cache: mlx-audio and its +packages 0.8 GB, mlx-whisper and its packages 2.0 GB (torch among them; the two together 2.6 GB), the Qwen3-TTS model +1.8 GB, whisper-large-v3-turbo 1.6 GB. +""" +import os, platform, sys, threading +from pathlib import Path + +KINDS = { + "qwen": {"what": "the local voice", "package": "mlx-audio", "packages_gb": 0.8, "env": "QWEN_TTS_MODEL", + "model": "mlx-community/Qwen3-TTS-12Hz-0.6B-CustomVoice-8bit", "model_gb": 1.8, + "around": "--provider edge needs only a small package (free, online: the script goes to Microsoft's voice service)"}, + "whisper": {"what": "the local Whisper", "package": "mlx-whisper", "packages_gb": 2.0, "env": "WHISPER_MODEL", + "model": "mlx-community/whisper-large-v3-turbo", "model_gb": 1.6, + "around": "--align gemini needs a Gemini key and no download"}, +} + + +def gb(x): + return f"{x:.1f} GB" + + +def total(kinds=("qwen",)): + """The whole first download of these kinds, packages and models (what doctor --first says).""" + return sum(KINDS[k]["packages_gb"] + KINDS[k]["model_gb"] for k in kinds) + + +def here(): + """These downloads run on Apple Silicon only (mlx); elsewhere the commands say so themselves.""" + return sys.platform == "darwin" and platform.machine() == "arm64" + + +def hub_dir(): + """Where the Hugging Face Hub keeps models, worked out as huggingface_hub does (stdlib, before it is installed).""" + if os.environ.get("HF_HUB_CACHE"): + return Path(os.environ["HF_HUB_CACHE"]) + home = os.environ.get("HF_HOME") or os.path.join(os.environ.get("XDG_CACHE_HOME") or os.path.expanduser("~/.cache"), "huggingface") + return Path(home) / "hub" + + +def model_id(kind): + return os.environ.get(KINDS[kind]["env"], KINDS[kind]["model"]) + + +def model_cached(kind): + """The model is here: a local folder, or a snapshot with weights in the Hub's cache. Another model than ours (the env + variable) counts as here when it is a folder; else as we cannot size it, it is said without a size.""" + m = model_id(kind) + if os.path.isdir(os.path.expanduser(m)): + return True + d = hub_dir() / ("models--" + m.replace("/", "--")) / "snapshots" + return any(d.glob("*/*.safetensors")) or any(d.glob("*/*.npz")) + + +def line(kinds, packages_missing=()): + """The one line before a first download of these kinds (or None: nothing big to fetch, or not this platform): how much, + roughly how long, that the progress shows, and the way around each.""" + if not here(): + return None + parts, size, around, whats = [], 0.0, [], [] + for k in kinds: + K = KINDS[k]; mine = model_id(k) == K["model"] + pk, md = k in packages_missing, not model_cached(k) + if not (pk or md): + continue + whats.append(K["what"]) + size += (K["packages_gb"] if pk else 0) + (K["model_gb"] if md and mine else 0) + model = "model" if mine else f"model {model_id(k)}" + parts.append(f"{K['what']}'s " + ("Python packages and " + model if pk and md else "Python packages" if pk else model)) + around.append(K["around"]) + if not parts: + return None + return (f" first use of {' and '.join(whats)}: about {gb(size)} to download once ({', '.join(parts)}); a few minutes on a fast" + f" line, half an hour or more on a slow one; the progress shows below. Without it: {'; '.join(around)}") + + +def show_progress(total_gb, every=10.0, folder=None): + """A line every `every` seconds with how much a download has added to `folder` (default: the Hub's whole cache, as its + xet transfer stages the parts outside the model's own folder). Written to the process's real stdout (sys.__stdout__), + so a caller that has swapped sys.stdout (contextlib.redirect_stdout, around a library that prints as it loads) does not + swallow it. → the thread's stop event.""" + folder = Path(folder) if folder else hub_dir() + stop = threading.Event() + + def size(): + return sum(f.stat().st_size for f in folder.rglob("*") if f.is_file() and not f.is_symlink()) if folder.is_dir() else 0 + base = size() + + def run(): + last = None + while not stop.wait(every): + got = round((size() - base) / 1e9, 1) + if got != last: + out = sys.__stdout__ or sys.stderr + out.write(f" model: {got:.1f} of about {total_gb} GB\n"); out.flush(); last = got + threading.Thread(target=run, daemon=True).start() + return stop + + +def progress(kind): + """show_progress for this kind's model when it is not here yet and no progress bar will show (output nobody watches + live, or the Hub's bars turned off from outside): the stop event, or None.""" + if model_cached(kind): + return None + if sys.stderr.isatty() and not os.environ.get("HF_HUB_DISABLE_PROGRESS_BARS"): + return None + mine = model_id(kind) == KINDS[kind]["model"] + return show_progress(KINDS[kind]["model_gb"] if mine else "?") + + +def main(argv): + if argv[:1] in (["-h"], ["--help"]) or not argv: + print(__doc__.strip()); return 0 + if argv[0] == "--package" and len(argv) == 2 and argv[1] in KINDS: + print(KINDS[argv[1]]["package"]); return 0 + kinds = [k for k in argv[0].split(",") if k] + miss = argv[2].split(",") if argv[1:2] == ["--packages-missing"] and len(argv) == 3 else [] + if any(k not in KINDS for k in kinds + miss) or len(argv) not in (1, 3): + print(f"firstuse: kinds are {', '.join(KINDS)} (python3 tools/audio/firstuse.py -h)", file=sys.stderr); return 2 + said = line(kinds, miss) + if said: + print(said, flush=True) + return 0 + + +if __name__ == "__main__": + sys.exit(main(sys.argv[1:])) diff --git a/tools/audio/pace.py b/tools/audio/pace.py index d386e96c..d3261896 100644 --- a/tools/audio/pace.py +++ b/tools/audio/pace.py @@ -69,6 +69,7 @@ sys.path.insert(0, str(Path(__file__).resolve().parent)) import tts # noqa: E402 parse_script, align_lines, transcribe, asr_record: one alignment for the whole harness +import firstuse # noqa: E402 the local Whisper's model: its first download's progress try: import numpy as np except ImportError: # -h on a plain python3; bin/vh pace runs it with numpy @@ -215,9 +216,14 @@ def asr_words(wav, engine, lang, texts, cuts, tmp): import mlx_whisper except ImportError: sys.exit("--align whisper needs mlx-whisper (Apple Silicon; bin/vh pace adds it with --align whisper)") - r = mlx_whisper.transcribe(str(wav), path_or_hf_repo=os.environ.get("WHISPER_MODEL", "mlx-community/whisper-large-v3-turbo"), - word_timestamps=True, language=lang, condition_on_previous_text=False, - initial_prompt="".join(texts)[:120] if lang == "zh" else None) # simplified characters, the terms + stop = firstuse.progress("whisper") # its model's first download (1.6 GB), where no progress bar shows + try: + r = mlx_whisper.transcribe(str(wav), path_or_hf_repo=firstuse.model_id("whisper"), + word_timestamps=True, language=lang, condition_on_previous_text=False, + initial_prompt="".join(texts)[:120] if lang == "zh" else None) # simplified characters, the terms + finally: + if stop: + stop.set() return [{"w": w["word"].strip(), "start": float(w["start"]), "end": float(w["end"])} for sg in r.get("segments", []) for w in sg.get("words", []) if w["word"].strip()] dur, pieces, t0, prev = probe_len(wav), [], 0.0, None diff --git a/tools/audio/tts.py b/tools/audio/tts.py index 54613cb8..b463c922 100644 --- a/tools/audio/tts.py +++ b/tools/audio/tts.py @@ -145,6 +145,8 @@ import urllib.error, urllib.parse, urllib.request, wave from concurrent.futures import Future, ThreadPoolExecutor from pathlib import Path +sys.path.insert(0, str(Path(__file__).resolve().parent)) +import firstuse # noqa: E402 the big first downloads: their sizes, the line before them, their progress RESUME = None # what a stop keeps for a resume, once a line is on disk @@ -253,7 +255,7 @@ def gemini_call(path, body=None, method=None, query=None, timeout=180, tries=3): def no_key(provider): """Exit (1) on a provider with no key: the key it needs, and what works with none on this machine.""" if sys.platform == "darwin" and platform.machine() == "arm64": - free = "the local default needs no key: leave the provider out, bin/vh tts (qwen, free, about 2 GB on first use)" + free = "the local default needs no key: leave the provider out, bin/vh tts (qwen, free, about " + firstuse.gb(firstuse.total(["qwen"])) + " on first use)" else: free = "the local default (qwen) needs no key but only runs on Apple Silicon; here --provider edge needs none (free, online)" sys.exit(f"set {KEY_OF[provider]} for {provider}; {free}") @@ -271,51 +273,7 @@ def hf_cached(model_id): # The provider bin/vh tts uses when none is named: the one place to change it (bin/vh asks: tts.py --default-provider). DEFAULT_PROVIDER = "qwen" -QWEN_MODEL = "mlx-community/Qwen3-TTS-12Hz-0.6B-CustomVoice-8bit" -QWEN_SIZES = {"packages": 0.75, "model": 1.8} # GB on disk the first time: mlx-audio and its packages (uv), the model (Hugging Face) - -def hub_dir(): - """Where the Hugging Face Hub keeps models, worked out as huggingface_hub does (stdlib, before it is installed).""" - if os.environ.get("HF_HUB_CACHE"): - return Path(os.environ["HF_HUB_CACHE"]) - home = os.environ.get("HF_HOME") or os.path.join(os.environ.get("XDG_CACHE_HOME") or os.path.expanduser("~/.cache"), "huggingface") - return Path(home) / "hub" - -def model_dir(model_id): - return hub_dir() / ("models--" + model_id.replace("/", "--")) - -def first_use_line(provider, packages_missing=False): - """The one line bin/vh tts says before a provider's first run downloads gigabytes (or None: nothing that big to fetch): - how much, roughly how long, that the progress shows, and the way around it.""" - if provider != "qwen" or not (sys.platform == "darwin" and platform.machine() == "arm64"): - return None - model_id = os.environ.get("QWEN_TTS_MODEL", QWEN_MODEL) - model = model_id == QWEN_MODEL and not os.path.isdir(os.path.expanduser(model_id)) and not list(model_dir(model_id).glob("snapshots/*/*.safetensors")) - parts = (["its Python packages"] if packages_missing else []) + (["the voice model"] if model else []) - if not parts: - return None - gb = (QWEN_SIZES["packages"] if packages_missing else 0) + (QWEN_SIZES["model"] if model else 0) - return (f" first use of the local voice: about {gb:.1f} GB to download once ({' and '.join(parts)}); a few minutes on a fast line," - f" half an hour or more on a slow one; the progress shows below. To skip it: --provider edge (free, online: the script" - f" goes to Microsoft's voice service)") - -def show_progress(folder, total_gb, every=10.0): - """A line every `every` seconds with how much a download has added to `folder` (the Hub's whole cache: its xet transfer - stages the parts outside the model's own folder), for output nobody watches live, where a progress bar is turned - off. → the thread's stop event.""" - import threading - stop = threading.Event() - def size(): - return sum(f.stat().st_size for f in Path(folder).rglob("*") if f.is_file() and not f.is_symlink()) if Path(folder).is_dir() else 0 - base = size() - def run(): - last = None - while not stop.wait(every): - got = round((size() - base) / 1e9, 1) - if got != last: - print(f" voice model: {got:.1f} of about {total_gb} GB", flush=True); last = got - threading.Thread(target=run, daemon=True).start() - return stop +QWEN_MODEL = firstuse.KINDS["qwen"]["model"] # its size, and the line said before a first download: tools/audio/firstuse.py _QWEN = {} def p_qwen(text, voice, out: Path, tmp: Path, lang, instruct=None): @@ -324,6 +282,7 @@ def p_qwen(text, voice, out: Path, tmp: Path, lang, instruct=None): # progress bar redrawn with \r is noise in output nobody watches live (an agent's). os.environ.setdefault("TRANSFORMERS_VERBOSITY", "error") os.environ.setdefault("HF_HUB_VERBOSITY", "error") + stop = firstuse.progress("qwen") # before the bars are turned off below: it reads whether they will show if not sys.stderr.isatty(): os.environ.setdefault("HF_HUB_DISABLE_PROGRESS_BARS", "1") import contextlib, io @@ -332,10 +291,9 @@ def p_qwen(text, voice, out: Path, tmp: Path, lang, instruct=None): model_id = os.environ.get("QWEN_TTS_MODEL", QWEN_MODEL) if model_id not in _QWEN: fresh = not hf_cached(model_id) - print(f" loading {model_id}" + (" (not downloaded yet: " + (f"{QWEN_SIZES['model']} GB " if model_id == QWEN_MODEL else "") + print(f" loading {model_id}" + (" (not downloaded yet: " + (f"{firstuse.KINDS['qwen']['model_gb']} GB " if model_id == QWEN_MODEL else "") + "into the Hugging Face cache, once)" if fresh else "") + " …", flush=True) - said = io.StringIO() # mlx-audio prints what it loads; shown only when loading fails - stop = show_progress(hub_dir(), QWEN_SIZES["model"] if model_id == QWEN_MODEL else "?") if fresh and not sys.stderr.isatty() else None + said = io.StringIO() # mlx-audio prints what it loads; shown only when loading fails (the progress goes to the real stdout) try: with contextlib.redirect_stdout(said): _QWEN[model_id] = load_model(model_id) @@ -861,9 +819,14 @@ def transcribe_local(wav: Path, lang, vocab=None): the terms go into Whisper's initial prompt (it has no custom vocabulary).""" import mlx_whisper # bin/vh tts adds it with --align local prompt = (",".join(vocab) if vocab else None) or None - r = mlx_whisper.transcribe(str(wav), path_or_hf_repo=os.environ.get("WHISPER_MODEL", "mlx-community/whisper-large-v3-turbo"), - word_timestamps=True, language=lang if lang in ("zh", "en", "ja", "ko") else None, condition_on_previous_text=False, - initial_prompt=prompt) + stop = firstuse.progress("whisper") # its model's first download (1.6 GB), where no progress bar shows + try: + r = mlx_whisper.transcribe(str(wav), path_or_hf_repo=firstuse.model_id("whisper"), + word_timestamps=True, language=lang if lang in ("zh", "en", "ja", "ko") else None, condition_on_previous_text=False, + initial_prompt=prompt) + finally: + if stop: + stop.set() words = [{"w": w["word"].strip(), "start": float(w["start"]), "end": float(w["end"])} for sg in r.get("segments", []) for w in sg.get("words", []) if str(w.get("word", "")).strip()] return str(r.get("text", "")).strip(), words @@ -1205,11 +1168,6 @@ def main(): return voices_main(sys.argv[2:]) if sys.argv[1:] == ["--default-provider"]: # for bin/vh tts, which picks the provider's packages before this runs print(DEFAULT_PROVIDER); return - if sys.argv[1:2] == ["--first-use"] and len(sys.argv) in (3, 4): # bin/vh tts: the line before a big first download - line = first_use_line(sys.argv[2], sys.argv[3:] == ["--packages-missing"]) - if line: - print(line, flush=True) - return ap = argparse.ArgumentParser() ap.add_argument("project"); ap.add_argument("--provider", choices=PROVIDERS, help=f"default {DEFAULT_PROVIDER} (with --resume: the run's provider)") ap.add_argument("--voice"); ap.add_argument("--lang", choices=["zh", "en"], help="spoken side (default zh; en for an English-only script)") diff --git a/tools/ci.sh b/tools/ci.sh index 70f7aad3..17a05833 100755 --- a/tools/ci.sh +++ b/tools/ci.sh @@ -1562,47 +1562,102 @@ print(sum("hold-confirm" in x for x in rows(row)))' 2>&1 | tr '\n' ' ') a=$(python3 -c 'import sys; sys.path.insert(0, "tools"); import doctor as d print(d.references_note(0, 37, 0, d.install_says())); print(d.references_note(31, 37, 214e6, None))' 2>&1) b=$(grep -o 'reference repos (about [0-9.]* [MG]B' install.sh | grep -o '[0-9.]* [MG]B') - case "$a" in "0/37 repos fetched → bash references/fetch.sh (all 37: about $b;"*"31/37 repos fetched → bash references/fetch.sh (all 37: about 255 MB, at the size of the 31 here;"*) + case "$a" in "0/37 repos fetched; an agent fetches the one a doc points to when it first needs it"*"all 37 now: bash references/fetch.sh (about $b)"*"31/37 repos fetched;"*"(about 255 MB, at the size of the 31 here)"*) ok "doctor: the reference repos' size from the ones fetched (31 of 37 at 214 MB: about 255 MB), else as install.sh says it ($b)" ;; *) bad "doctor's line for the reference repos: $a (install.sh says: ${b:-nothing found})" ;; esac - # the reference repos are fetched on first use: references/fetch.sh knows each one's size, and says it in one line before - # a first fetch; a name it does not have is said, exit 2 (it used to do nothing) - a=$(bash -c 'cd references && sed -n "/^SIZES=\"/,/^\"/p" fetch.sh | tr " " "\n" | grep -v "^SIZES\|^\"\|^$" | paste - - | cut -f1 | sort' 2>&1) - b=$(grep -E '^(full|sparse|textonly) ' references/fetch.sh | awk '{print $3}' | sort) - c=$(bash references/fetch.sh no-such-repo 2>&1); rc=$? - if [ -n "$b" ] && [ "$a" = "$b" ] && [ "$rc" = 2 ] && case "$c" in "no reference repo named no-such-repo"*) true ;; *) false ;; esac \ - && grep -q '^ else announce "$1" "$2"; clone' references/fetch.sh && grep -q 'REFS=0;' install.sh && grep -q -- '--refs) REFS=1' install.sh - then ok "references/fetch.sh: a size for each of the $(printf '%s\n' "$b" | wc -l | tr -d ' ') reference repos, said before a first fetch; an unknown name exits 2; install.sh fetches them only with --refs" - else bad "references/fetch.sh's sizes or names (exit $rc): $(diff <(printf '%s\n' "$a") <(printf '%s\n' "$b") | head -5 | tr '\n' ' ') | $c"; fi - # doctor --first, the installer's last lines: ready only when a first film has what it needs; what is missing, with how - # to get it; a voice line for this platform; a Chinese font missing is said (Linux) + # the reference repos come on first use: references/fetch.sh says what, from where and how big before it fetches one, + # for each kind of fetch (full, sparse, text only), through a stand-in git; one asked for by name that does not come exits 1; + # every repo has a size; an unknown name exits 2; a full fetch with no network is one line and exit 0; install.sh fetches + # them all only with --refs + ft=$(mktemp -d "${TMPDIR:-/tmp}/vh-fetch.XXXXXX"); mkdir -p "$ft/references" "$ft/bin"; cp references/fetch.sh "$ft/references/" + printf '#!/bin/sh\ncase "$1" in clone) [ -n "$FAIL" ] && { echo "fatal: could not resolve host" >&2; exit 128; }; for a; do d=$a; done; mkdir -p "$d/.git" ;; esac\nexit 0\n' > "$ft/bin/git"; chmod +x "$ft/bin/git" + fe() { env PATH="$ft/bin:$PATH" "$@" bash "$ft/references/fetch.sh" ${FA[@]+"${FA[@]}"} 2>&1; } + FA=(PDoomVideo); a=$(fe); FA=(hyperframes); b=$(fe); FA=(vox-director); c=$(fe) # full, sparse, text only + FA=(Paper-Cut); d=$(fe FAIL=1); rd=$?; FA=(no-such-repo); e=$(fe); re=$?; rm -rf "$ft/references/repos"; FA=(); f=$(fe FAIL=1); rf=$? + sz=$(sed -n '/^SIZES="/,/^"/p' references/fetch.sh | tr " " "\n" | grep -v '^SIZES\|^"\|^$' | paste - - | cut -f1 | sort) + names=$(grep -E '^(full|sparse|textonly) ' references/fetch.sh | awk '{print $3}' | sort) + if case "$a" in "fetching PDoomVideo from github.com/JohnHeibel/PDoomVideo (about "*" MB, read-only"*) true ;; *) false ;; esac \ + && case "$b" in "fetching hyperframes from github.com/heygen-com/hyperframes (about "*) true ;; *) false ;; esac \ + && case "$c" in "fetching vox-director from github.com/Alisa0808/vox-director (under 1 MB, read-only"*) true ;; *) false ;; esac \ + && [ $rd = 1 ] && case "$d" in *"skip Paper-Cut (clone failed: fatal: could not resolve host)"*) true ;; *) false ;; esac \ + && [ $re = 2 ] && case "$e" in "no reference repo named no-such-repo"*) true ;; *) false ;; esac \ + && [ $rf = 0 ] && [ "$(printf '%s\n' "$f" | wc -l | tr -d ' ')" = 1 ] && case "$f" in "skipped $(printf '%s\n' "$names" | wc -l | tr -d ' ') (no network?"*) true ;; *) false ;; esac \ + && [ -n "$names" ] && [ "$sz" = "$names" ] && grep -q 'REFS=0;' install.sh && grep -q -- '--refs) REFS=1' install.sh + then ok "references/fetch.sh: one repo by name says what, where from and how big first (full, sparse and text only), exits 1 when it did not come, 2 for an unknown name; every repo has a size; all of them with no network: one line, exit 0; install.sh only with --refs" + else bad "references/fetch.sh ($rd/$re/$rf): $a | $b | $c | $d | $e | $(printf '%s' "$f" | head -c 200)"; fi + rm -rf "$ft" + # doctor --first, the installer's last lines: ready only when a first film has what it needs; each missing one with how to + # get it; in a Chinese locale a missing Chinese font is not ready; on Linux the render browser's missing libraries are not + # ready, and libraries it could not ask about are "not checked" (exit 3), not ready; an outdated agent is told to update; + # with no python3 at all (bin/vh's bare doctor) it is not ready either (exit 1) a=$(python3 - <<'PY' 2>&1 import sys; sys.path.insert(0, "tools"); import doctor as d ok = lambda n, **k: dict({"name": n, "state": "ok", "install": f"get {n}"}, **k) mods = [ok("node"), ok("ffmpeg"), ok("python3"), ok("uv"), ok("chrome"), ok("chrome-headless-shell", state="missing"), ok("claude-code"), ok("codex", state="missing"), ok("qwen3-tts", state="missing"), ok("mlx-audio")] -checks = [{"name": "browser", "state": "missing"}] -l1, r1 = d.first_film(mods, checks, "darwin-arm64") # no browser yet, but the first render brings its own: ready +nob = [{"name": "browser", "state": "missing"}]; nofont = nob + [{"name": "fonts", "state": "missing"}] +r = [] +r.append(d.first_film(mods, nob, "darwin-arm64")) # the first render brings its own Chrome mods2 = [dict(m, state="missing") if m["name"] in ("uv", "claude-code") else m for m in mods] -l2, r2 = d.first_film(mods2, checks + [{"name": "fonts", "state": "missing"}], "linux-arm64") # no uv, no browser, no agent, no font -print(r1, r2, len(l1), len(l2)); print("\n".join(l1 + ["--"] + l2)) +r.append(d.first_film(mods2, nofont, "linux-arm64", libs=([], True))) # no uv, no browser, no agent +r.append(d.first_film(mods, nofont, "linux-x86_64", env={"LANG": "zh_CN.UTF-8"}, libs=([], True))) # zh, no Chinese font +r.append(d.first_film(mods, nofont, "linux-x86_64", env={"LANG": "en_US.UTF-8"}, libs=([], True))) # en: said, still ready +r.append(d.first_film(mods, nob, "linux-x86_64", env={}, libs=(["libnss3.so", "libnspr4.so"], True))) +r.append(d.first_film(mods, nob, "linux-x86_64", env={}, libs=([], False))) +mods3 = [dict(m, state="outdated", version="1.0") if m["name"] == "claude-code" else m for m in mods] +r.append(d.first_film(mods3, nob, "darwin-arm64")) +print(" ".join(st for _, st in r)) +for lines, _ in r: print("\n".join(lines)); print("--") PY ) - case "$a" in "True False 3 6"*"✓ Ready for a first film: Node, FFmpeg, uv, a browser to render with, Claude Code"*"downloads its own Chrome once"*"- Voice: the first bin/vh tts downloads the local voice once (about 2.5 GB"*"--provider edge"*"--"*"✗ Not ready for a first film yet"*" uv → get uv"*" a browser to render with → get chrome"*" Claude Code or Codex →"*"! Chinese text"*"- Voice: bin/vh tts --provider edge"*) - ok "doctor --first: ready only with Node, FFmpeg, Python, uv, a browser (or a platform whose first render brings one) and an agent; each missing one with how to get it; the voice for the platform; a missing Chinese font said" ;; - *) bad "doctor --first: $(printf '%s' "$a" | head -c 600)" ;; esac - # bin/vh tts: the default provider is said in one place (tts.py), and the local voice's first use is said before it - # downloads, with the size, the time it may take and the way around it; nothing for another provider or a cached model - a=$(python3 tools/audio/tts.py --default-provider 2>&1) - b=$(HF_HOME="$(mktemp -d)" python3 tools/audio/tts.py --first-use qwen --packages-missing 2>&1) - c=$(python3 tools/audio/tts.py --first-use edge --packages-missing 2>&1) - want="first use of the local voice: about 2.5 GB to download once (its Python packages and the voice model)" - case "$(uname -s)-$(uname -m)" in Darwin-arm64) ;; *) want="" ;; esac # elsewhere the local voice does not run, so nothing is said - if [ "$a" = qwen ] && case "$b" in *"$want"*) [ -n "$want" ] || [ -z "$b" ] ;; *) false ;; esac && [ -z "$c" ] \ - && { [ -z "$want" ] || case "$b" in *"--provider edge (free, online"*) true ;; *) false ;; esac; } \ - && grep -q 'prov=$(python3 "$ROOT/tools/audio/tts.py" --default-provider)' bin/vh - then ok "bin/vh tts: the default provider comes from tts.py alone; the local voice's first use is said before its 2.5 GB download (Apple Silicon), with the way around it; nothing for edge" - else bad "bin/vh tts's default and first-use line: $a | $b | $c"; fi + ft=$(mktemp -d "${TMPDIR:-/tmp}/vh-nopy.XXXXXX"); mkdir -p "$ft/bin" + for f in /usr/bin/* /bin/*; do n=$(basename "$f"); case "$n" in python*|pydoc*) continue ;; esac; [ -e "$ft/bin/$n" ] || ln -s "$f" "$ft/bin/$n"; done + for n in node ffmpeg git; do command -v "$n" >/dev/null && ln -sf "$(command -v "$n")" "$ft/bin/$n"; done + b=$(PATH="$ft/bin" "$VH_BASH" "$ROOT/bin/vh" doctor --first 2>&1); rb=$?; rm -rf "$ft" + if case "$a" in "ready not not ready not unchecked not"*) true ;; *) false ;; esac \ + && case "$a" in *"✓ Ready for a first film: Node, FFmpeg, Python 3, uv, a browser to render with, Claude Code"*"downloads its own Chrome once"*"- Voice: the first bin/vh tts downloads the local voice once (about 2.6 GB"*"--provider edge needs only a small package"*) true ;; *) false ;; esac \ + && case "$a" in *" uv (it runs the Python tools"*" a browser to render with → get chrome"*" Claude Code or Codex →"*"- Voice: bin/vh tts --provider edge (free, online; only a small package)"*) true ;; *) false ;; esac \ + && case "$a" in *" a Chinese font (Chinese text would draw as boxes) → sudo apt install fonts-noto-cjk"*"! Chinese text: no Chinese font here"*) true ;; *) false ;; esac \ + && case "$a" in *"the render browser's system libraries (libnspr4.so, libnss3.so) → sudo apt install libnspr4 libnss3"*"? Nearly ready"*"not checked:"*"Claude Code is out of date (1.0) → update it"*) true ;; *) false ;; esac \ + && [ $rb = 1 ] && case "$b" in *"python3 not found"*) true ;; *) false ;; esac + then ok "doctor --first: ready only with Node, FFmpeg, Python 3, uv, a browser (or a platform whose first render brings one) and its libraries, an agent, a Chinese font in a Chinese locale; each missing one with how to get it; libraries not asked about are not checked (3); an old agent is told to update; no python3: not ready (1)" + else bad "doctor --first (no python3: exit $rb): $(printf '%s' "$a" | head -c 900) | $(printf '%s' "$b" | head -3)"; fi + # the big first downloads (tools/audio/firstuse.py) are said by bin/vh before they start: tts with the local voice and with + # --align local, voices audition with the local voice, pace --align whisper (uv and the Hub stood in for: uv says the + # packages are not cached); uv then runs without -q, so its download lines show; a project with no script gets the sample + # and no package at all; the model's progress reaches the terminal even inside the redirect a loader runs in. Apple Silicon: + # the lines; elsewhere these do not run, and nothing is said + ft=$(mktemp -d "${TMPDIR:-/tmp}/vh-firstuse.XXXXXX"); mkdir -p "$ft/bin" "$ft/p/audio" "$ft/q"; echo "一句话" > "$ft/p/audio/script.txt"; : > "$ft/t.txt" + printf '#!/bin/sh\necho "uv $*" >> "%s/calls"\ncase "$*" in *--offline*) exit 1 ;; esac\nexit 0\n' "$ft" > "$ft/bin/uv"; chmod +x "$ft/bin/uv" + fu() { env PATH="$ft/bin:$PATH" HF_HOME="$ft/hf" "$VH_BASH" "$ROOT/bin/vh" "$@" 2>&1; } + a=$(fu tts "$ft/p"); b=$(fu tts "$ft/p" --align local); c=$(fu voices audition --provider qwen --voices x --text "$ft/t.txt"); d=$(fu pace "$ft/p" --align whisper) + calls=$(cat "$ft/calls" 2>/dev/null); : > "$ft/calls"; e=$(fu tts "$ft/q"); re=$?; qcalls=$(cat "$ft/calls" 2>/dev/null) + g=$(python3 - "$ft/hf" <<'PY' +import contextlib, io, os, subprocess, sys, time +code = ("import contextlib, io, sys, time, os; sys.path.insert(0, 'tools/audio'); import firstuse; d = sys.argv[1]; os.makedirs(d, exist_ok=True)\n" + "with contextlib.redirect_stdout(io.StringIO()):\n" + " st = firstuse.show_progress(1.8, every=0.2, folder=d)\n" + " for i in range(3): open(os.path.join(d, f'x{i}'), 'wb').write(b'0' * 100_000_000); time.sleep(0.35)\n" + " st.set()\n") +r = subprocess.run([sys.executable, "-c", code, sys.argv[1]], capture_output=True, text=True) +print(r.stdout.count("model:")) +PY +) + case "$(uname -s) $(uname -m)" in + "Darwin arm64") + if case "$a" in *"first use of the local voice: about 2.6 GB to download once"*"--provider edge needs only a small package"*) true ;; *) false ;; esac \ + && case "$b" in *"first use of the local Whisper and the local voice: about 6.2 GB"*) true ;; *) false ;; esac \ + && case "$c" in *"first use of the local voice"*) true ;; *) false ;; esac && case "$d" in *"first use of the local Whisper: about 3.6 GB"*"--align gemini"*) true ;; *) false ;; esac \ + && printf '%s\n' "$calls" | grep -q '^uv run --no-project --with mlx-audio' && ! printf '%s\n' "$calls" | grep -q '^uv run -q --no-project --with mlx-audio' \ + && [ $re = 1 ] && [ -z "$qcalls" ] && [ -s "$ft/q/audio/script.txt" ] && [ "${g:-0}" -ge 2 ] + then ok "first downloads: tts, tts --align local, voices audition and pace --align whisper say theirs first (size, the way around), uv shows its lines; no script: the sample and no package; the model's progress gets past a redirect" + else bad "first downloads: $a | $b | $c | $d | calls: $(printf '%s' "$calls" | head -c 300) | no script ($re): $qcalls | progress lines: $g"; fi ;; + *) + if ! printf '%s' "$a$b$c$d" | grep -q "first use of" && [ $re = 1 ] && [ -z "$qcalls" ] && [ "${g:-0}" -ge 2 ] + then ok "first downloads: not on this platform (the local voice and Whisper are Apple Silicon only), so nothing said; no script: the sample and no package; the model's progress gets past a redirect" + else bad "first downloads here: $a | $b | no script ($re): $qcalls | progress lines: $g"; fi ;; + esac + rm -rf "$ft" # recipes sample: bad usage exits 2 before any render (an unknown id, a sequence, an unknown style); list --json names # the sheet a recipe carries (recipes check, above, holds every sketch to its sheet) vh recipes sample no-such-recipe >/dev/null 2>&1; rc=$?; vh recipes sample launch-15s >/dev/null 2>&1; rc2=$? diff --git a/tools/commands.json b/tools/commands.json index c9373420..228499bc 100644 --- a/tools/commands.json +++ b/tools/commands.json @@ -1631,7 +1631,7 @@ "--candidates N: N takes a block, the one nearest the narration's median voice kept (N × the synthesis);", "warns of a line far off the take's seconds per character, and (with --align) of a phrase heard twice;", "--resume: continue the last run after a failed synthesis or transcription, same script and command)", - "providers: qwen (default, local open-source Qwen3-TTS; its first use downloads about 2.5 GB, said first, with the progress) | say | edge | dashscope | elevenlabs | gemini | gemini-lite | minimax" + "providers: qwen (default, local open-source Qwen3-TTS; its first use downloads about 2.6 GB, said first, with the progress) | say | edge | dashscope | elevenlabs | gemini | gemini-lite | minimax" ] } ] diff --git a/tools/doctor.py b/tools/doctor.py index 8976b6b8..1c18ac55 100644 --- a/tools/doctor.py +++ b/tools/doctor.py @@ -4,7 +4,8 @@ (bin/vh passes what its own finders found: --chrome, --hf-chrome, --hf-pin, --webgl) --json the same as JSON (below), the lines a person reads not printed --first only the few lines a first film needs (the installer ends with them): ready or not, what is missing - for a first silent film and how to get it, how a voice comes here. Exit 1 when it is not ready + for a first silent film and how to get it, how a voice comes here. Exit 1 when it is not ready, 3 when + nothing is missing but something could not be checked (the render browser's libraries on Linux) --fill-local also write LOCAL.md's machine lines (硬件, 已装工具, 已装引擎) from this check, where they still hold the template's {…}; with no LOCAL.md, LOCAL.example.md is copied first. A line a person wrote stays; the other lines' {…} are their defaults (the installer runs this) @@ -30,7 +31,8 @@ a whole copy stays as it was when the repo moves on); studio-icon, the launcher bin/vh studio --install-icon makes (installed or not, which clone it runs, made by an earlier launcher or picture); caches, whether the folders a first run downloads into (uv's, npm's, Hugging Face's, HyperFrames', bin/vh's own) can be written, tried with a file made and removed. -Exit 0: it is a report (2 on a usage error or an unreadable table; with --first, 1 when a first film still lacks something). +Exit 0: it is a report (2 on a usage error or an unreadable table; with --first, 1 when a first film still lacks something, 3 +when nothing is missing but something could not be checked). --json, "version": 1 (these fields stay; new ones may be added): {"version", "tool", "platform", "modules": [{"name", "kind", "status" ("planned" when nothing calls it yet, else "used"), "required", "state", "found", "version", "keys": @@ -112,50 +114,99 @@ def install_says(): def references_note(have, want, fetched, said): - """doctor's line for references/repos when some are not fetched: the whole set's size worked out from the ones that - are (fetched: their bytes), else what install.sh says (said), else none.""" + """doctor's line for references/repos when not all are fetched, which is the default (they come on first use): the + whole set's size worked out from the ones that are (fetched: their bytes), else what install.sh says (said), else none.""" size = f"about {mb_text(fetched * want / have)}, at the size of the {have} here" if have and fetched else f"about {said}" if said else None - return (f"{have}/{want} repos fetched → bash references/fetch.sh (all {want}{': ' + size if size else ''}; agents read them for the case studies;" - " the one a doc points to, references/repos//…: bash references/fetch.sh )") + return (f"{have}/{want} repos fetched; an agent fetches the one a doc points to when it first needs it (bash references/fetch.sh ," + f" which says its size first); all {want} now: bash references/fetch.sh{' (' + size + ')' if size else ''}") OWN_CHROME = ("darwin-arm64", "darwin-x86_64", "linux-x86_64") # where HyperFrames downloads its own chrome-headless-shell -LOCAL_VOICE = "about 2.5 GB" # the local voice's first use: mlx-audio and its packages (about 0.75 GB) and the model (1.8 GB on disk) +BROWSER_LIBS = {"libnss3.so": "libnss3", "libnspr4.so": "libnspr4"} # what a fresh Ubuntu with ffmpeg still lacked for it (engines/README.md) -def first_film(mods, checks, plat): - """--first, the few lines install.sh ends with: is this machine ready for a first (silent) film, what it lacks for - one, and how a voice comes. → (lines, ready). Ready only with nothing missing that the first film needs: Node, FFmpeg, - Python 3, uv, a browser to render with (or a platform where the first render downloads its own), and an agent.""" +def zh_locale(env=os.environ): + """The person's language is Chinese: the first of LC_ALL, LC_MESSAGES, LANG that is set starts with zh.""" + v = next((env[k] for k in ("LC_ALL", "LC_MESSAGES", "LANG") if env.get(k)), "") + return v.lower().startswith("zh") + + +def browser_libs(plat, path=None, run=subprocess.run): + """Linux: the system libraries the render browser needs that are missing → (missing .so names, checked). With a browser + found, what ldd says is "not found" in it; with none yet on a platform where the first render downloads one, whether the + linker knows libnss3 and libnspr4 (ldconfig -p). Not Linux: nothing to check ([], True). No ldd or ldconfig: ([], False).""" + if not plat.startswith("linux"): + return [], True + try: + if path and os.path.isfile(path): + out = run(["ldd", path], capture_output=True, text=True, timeout=20).stdout + return sorted({ln.split()[0] for ln in out.splitlines() if "not found" in ln}), True + ldc = shutil.which("ldconfig") or ("/sbin/ldconfig" if os.path.exists("/sbin/ldconfig") else None) + if not ldc: + return [], False + out = run([ldc, "-p"], capture_output=True, text=True, timeout=20).stdout + return [so for so in BROWSER_LIBS if so not in out], True + except (OSError, subprocess.SubprocessError): + return [], False + + +def first_film(mods, checks, plat, found_by=None, env=os.environ, libs=None): + """--first, the few lines install.sh ends with: is this machine ready for a first (silent) film, what it lacks for one, + and how a voice comes. → (lines, "ready" | "not" | "unchecked"). Ready only with nothing missing a first film needs: + Node, FFmpeg, Python 3, uv, a browser to render with (or a platform where the first render downloads its own) and the + system libraries it needs (Linux), an agent, and in a Chinese locale a Chinese font. "unchecked": nothing missing, but + the browser's libraries could not be checked. libs: browser_libs's answer, given by the tests.""" + sys.path.insert(0, str(ROOT / "tools" / "audio")) + import firstuse m, c = {x["name"]: x for x in mods}, {x["name"]: x for x in checks} - lack = [] - for name, what in (("node", "Node 22 or newer"), ("ffmpeg", "FFmpeg"), ("python3", "Python 3"), ("uv", "uv")): + lack, unsure = [], [] + for name, what in (("node", "Node 22 or newer"), ("ffmpeg", "FFmpeg"), ("python3", "Python 3"), + ("uv", "uv (it runs the Python tools: contact sheets, sound checks, the voice)")): r = m.get(name) if r and r["state"] != "ok": lack.append(f"{what} → {r.get('install') or 'install it'}") own = plat in OWN_CHROME if (c.get("browser") or {}).get("state") != "ok" and not own: lack.append(f"a browser to render with → {(m.get('chrome') or {}).get('install') or 'set CHROME_PATH'}") + elif plat.startswith("linux"): + found_by = found_by or {} + missing, checked = libs if libs is not None else browser_libs(plat, found_by.get("hf-chrome") or found_by.get("chrome")) + missing = sorted(missing) + if missing: + pkgs = [BROWSER_LIBS[so] for so in missing if so in BROWSER_LIBS] + lack.append(f"the render browser's system libraries ({', '.join(missing)}) → " + + (f"sudo apt install {' '.join(pkgs)}" if len(pkgs) == len(missing) else "install the packages that give them")) + elif not checked: + unsure.append("the render browser's system libraries: no ldd or ldconfig here to ask; the first render names any it misses" + " (engines/README.md, Linux:渲染前要先备好的三样)") agents = [w for n, w in (("claude-code", "Claude Code"), ("codex", "Codex")) if (m.get(n) or {}).get("state") == "ok"] + old = [(w, m[n]) for n, w in (("claude-code", "Claude Code"), ("codex", "Codex")) if (m.get(n) or {}).get("state") == "outdated"] if not agents: - lack.append("Claude Code or Codex → claude.com/claude-code, or npm install -g @openai/codex") + lack += ([f"{w} is out of date ({r.get('version') or r.get('note') or 'too old'}) → update it" for w, r in old] if old else + ["Claude Code or Codex → claude.com/claude-code, or npm install -g @openai/codex"]) + font = (c.get("fonts") or {}).get("state") == "missing" + if font and zh_locale(env): + lack.append("a Chinese font (Chinese text would draw as boxes) → sudo apt install fonts-noto-cjk") if lack: lines = ["✗ Not ready for a first film yet. It still needs:"] + [f" {x}" for x in lack] + elif unsure: + lines = [f"? Nearly ready for a first film: Node, FFmpeg, Python 3, uv and {' and '.join(agents)} are here; not checked:"] + [f" {x}" for x in unsure] else: - lines = [f"✓ Ready for a first film: Node, FFmpeg, uv, a browser to render with, {' and '.join(agents)}"] - if (m.get("chrome-headless-shell") or {}).get("state") != "ok" and own: - lines.append(" The first render downloads its own Chrome once (about 0.2 GB).") - if (c.get("fonts") or {}).get("state") == "missing": + lines = [f"✓ Ready for a first film: Node, FFmpeg, Python 3, uv, a browser to render with, {' and '.join(agents)}"] + if not lack and (m.get("chrome-headless-shell") or {}).get("state") != "ok" and own: + lines.append(" The first render downloads its own Chrome once (about 0.2 GB).") + if font and not zh_locale(env): lines.append("! Chinese text: no Chinese font here, so it would draw as boxes → sudo apt install fonts-noto-cjk") if plat == "darwin-arm64": if (m.get("qwen3-tts") or {}).get("state") == "ok" and (m.get("mlx-audio") or {}).get("state") == "ok": lines.append("✓ Voice: the local voice is downloaded.") else: - lines.append(f"- Voice: the first bin/vh tts downloads the local voice once ({LOCAL_VOICE}; it says so first and shows the progress)." - " With --provider edge it downloads nothing (free, online).") + lines.append(f"- Voice: the first bin/vh tts downloads the local voice once (about {firstuse.gb(firstuse.total(['qwen']))};" + " it says so first and shows the progress). --provider edge needs only a small package (free, online).") else: - lines.append("- Voice: bin/vh tts --provider edge (free, online), or a cloud voice with a key; the local voice needs Apple Silicon.") - return lines, not lack + lines.append("- Voice: bin/vh tts --provider edge (free, online; only a small package), or a cloud voice with a key;" + " the local voice needs Apple Silicon.") + return lines, "not" if lack else "unchecked" if unsure else "ready" def this_platform(): @@ -571,7 +622,7 @@ def cache_homes(has_chrome=False): return [ ("uv", uv or str(home("~/.cache/uv")), "the Python packages of beats, music, qa, tts and the other uv tools", "UV_CACHE_DIR="), ("npm", env("npm_config_cache") or env("NPM_CONFIG_CACHE") or str(home("~/.npm")), "bin/vh new's npm install and every npx hyperframes", "NPM_CONFIG_CACHE="), - ("Hugging Face", env("HF_HOME") or str(home("~/.cache/huggingface")), "the local voice's model, about 2 GB", "HF_HOME="), + ("Hugging Face", env("HF_HOME") or str(home("~/.cache/huggingface")), "the local voice's model, 1.8 GB", "HF_HOME="), ("HyperFrames", env("HYPERFRAMES_FONT_CACHE_DIR") or str(home("~/.cache/hyperframes/fonts")), "the fonts a film asks for; its Chrome is already there", "HYPERFRAMES_FONT_CACHE_DIR=") if has_chrome else ("HyperFrames", str(home("~/.cache/hyperframes")), "its Chrome on a first snapshot or render, about 200 MB, and its fonts", @@ -627,7 +678,7 @@ def repo_checks(webgl, found_by): if have >= want: out.append({"name": "references", "state": "ok", "note": f"{have}/{want} repos fetched, {size_of(ROOT / 'references' / 'repos')}"}) else: - out.append({"name": "references", "state": "missing", "note": references_note(have, want, bytes_of(ROOT / "references" / "repos") if have else 0, install_says())}) + out.append({"name": "references", "state": "ok", "note": references_note(have, want, bytes_of(ROOT / "references" / "repos") if have else 0, install_says())}) local = ROOT / "LOCAL.md" if not local.exists(): out.append({"name": "local_md", "state": "missing", "note": "no LOCAL.md → bin/vh doctor --fill-local (copies LOCAL.example.md, writes this machine's lines)"}) @@ -902,9 +953,9 @@ def main(argv): print(said, file=sys.stderr if a["json"] else sys.stdout) checks = repo_checks(a["webgl"], found_by) if a["first"] and not a["json"]: - lines, ready = first_film(mods, checks, this_platform()) + lines, state = first_film(mods, checks, this_platform(), found_by) print("\n".join(lines)) - return 0 if ready else 1 + return {"ready": 0, "not": 1, "unchecked": 3}[state] first = [m.get("first_run") for m, r in zip(t["modules"], mods) if m.get("first_run") and r["state"] == "missing"] counts = {} for x in mods + checks: diff --git a/tools/modules.json b/tools/modules.json index 82e0a1e4..a48cba20 100644 --- a/tools/modules.json +++ b/tools/modules.json @@ -242,8 +242,8 @@ "commands": ["tts", "voices"], "required": false, "check": {"hf_model": {"env": "QWEN_TTS_MODEL", "default": "mlx-community/Qwen3-TTS-12Hz-0.6B-CustomVoice-8bit"}}, - "first_run": "Qwen3-TTS model 2 GB", - "install": {"macos": "the first bin/vh tts with the default provider fetches it (about 2 GB) from Hugging Face"} + "first_run": "Qwen3-TTS model 1.8 GB", + "install": {"macos": "the first bin/vh tts with the default provider fetches it (1.8 GB) from Hugging Face, said first"} }, { "name": "mlx-audio", @@ -257,8 +257,8 @@ "commands": ["tts", "voices"], "required": false, "check": {"uv": ["mlx-audio"]}, - "first_run": "mlx-audio 0.75 GB", - "install": {"macos": "the first bin/vh tts with the default provider fetches it and its packages (about 750 MB)"} + "first_run": "mlx-audio 0.8 GB", + "install": {"macos": "the first bin/vh tts with the default provider fetches it and its packages (about 0.8 GB), said first"} }, { "name": "mlx-whisper", From 3284d197209a1bf9d4808b928d9fc52f54400860 Mon Sep 17 00:00:00 2001 From: zhanglinghao Date: Sun, 22 Nov 2026 04:17:58 +0800 Subject: [PATCH 05/19] ci: the tts --provider check gives its project a script (with none, tts now writes the sample and fetches nothing) --- tools/ci.sh | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) diff --git a/tools/ci.sh b/tools/ci.sh index 17a05833..30f83e58 100755 --- a/tools/ci.sh +++ b/tools/ci.sh @@ -1182,8 +1182,9 @@ PY [ $rc = 2 ] && [ $a = 2 ] && [ -z "$(ls -d "$t"/*-cf2 "$t"/*-cf3 2>/dev/null)" ] && ok "bin/vh new refuses a vertical canvas-film and an unknown --engine" \ || bad "bin/vh new --engine: --aspect 9:16 exited $rc, an unknown engine $a" rm -rf "$t" - # tts picks the uv dependencies from --provider too (a fake uv prints the command instead of running it) - t=$(mktemp -d "${TMPDIR:-/tmp}/vh-ci.XXXXXX"); printf '#!/bin/sh\necho "$*"\n' > "$t/uv"; chmod +x "$t/uv" + # tts picks the uv dependencies from --provider too (a fake uv prints the command instead of running it; a script is there, + # as with none tts writes the sample and fetches nothing) + t=$(mktemp -d "${TMPDIR:-/tmp}/vh-ci.XXXXXX"); printf '#!/bin/sh\necho "$*"\n' > "$t/uv"; chmod +x "$t/uv"; mkdir -p "$t/audio"; echo "A line." > "$t/audio/script.txt" a=$(PATH="$t:$PATH" vh tts "$t" --provider edge --lang en; PATH="$t:$PATH" DASHSCOPE_API_KEY=ci vh tts "$t" --provider=dashscope) case "$a" in *"--with edge-tts "*"--provider edge"*"--with dashscope "*) ok "tts --provider picks the provider's dependencies" ;; *) bad "tts --provider: uv got '$a'" ;; esac From 66a97815d862166d93e41f62abac8bf9d28e6f12 Mon Sep 17 00:00:00 2001 From: zhanglinghao Date: Sun, 22 Nov 2026 03:41:44 +0800 Subject: [PATCH 06/19] Mirrors in one step: the installer falls back to them when the official npm registry does not answer, and every later download follows - tools/mirrors.txt: each kind of download, its variable, the official source, the mainland-China mirror, who runs it. - This machine's settings in $XDG_CONFIG_HOME/ovh/settings.json (tools/settings.py, bin/vh settings): mirror cn|off|auto. - bin/vh exports the mirror variables for everything it runs when the mirror is cn (a variable already set wins); HyperFrames' Chrome is fetched from the mirror by bin/vh new, install.sh and settings chrome, as HyperFrames has no setting for it. - install.sh tries registry.npmjs.org for 5 s; only when it does not answer and the mirror does, it keeps cn and says so; --mirror cn|off forces it either way. doctor says which sources are in use. - README: the China network line; homepage and overview: 74 commands. --- AGENTS.md | 2 +- CLAUDE.md | 2 +- README.md | 5 +- README.zh-CN.md | 5 +- bin/vh | 37 +++++- changes/first-run-mirrors.md | 7 ++ docs/assets/overview.en.svg | 2 +- docs/assets/overview.zh.svg | 2 +- docs/site/index.html | 4 +- install.sh | 20 ++- tools/ci.sh | 21 ++++ tools/commands.json | 19 +++ tools/doctor.py | 11 ++ tools/mirrors.txt | 19 +++ tools/schemas/output/settings.schema.json | 30 +++++ tools/settings.py | 145 ++++++++++++++++++++++ tools/test_contract.py | 6 +- 17 files changed, 320 insertions(+), 17 deletions(-) create mode 100644 changes/first-run-mirrors.md create mode 100644 tools/mirrors.txt create mode 100644 tools/schemas/output/settings.schema.json create mode 100644 tools/settings.py diff --git a/AGENTS.md b/AGENTS.md index f6067dc5..a0adeae2 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -138,7 +138,7 @@ OpenVideoHarness/ ├── CLAUDE.md / AGENTS.md 入口(本文件;AGENTS.md 由 bin/vh sync-agents 生成,内容相同) ├── README.md / README.zh-CN.md 给人看的说明;CONTRIBUTING.md 是改本仓库时的规则;install.sh 一键安装 ├── LOCAL.md 本机环境(不入库;模板是 LOCAL.example.md) -├── bin/vh 命令行:doctor · setup · install-skill · sync-agents · sound · commands · status · projects · cancel · history · activity · know · artifacts · studio · types · effort · new · footage · assets · scout · ref · web · review · gate · desk · concept · breakdown · cast · style · recipes · storyboard · rhythm · words · edit · bgm · tts · pace · voices · captions · timeline · remap · timemap · beats · music · sfx · hf-init · determinism · image · model3d · hdri · hf · components · frames · cues · readcheck · textcheck · fonts · sheet · proxy · thumbs · peaks · render · patch · versions · check · mix · qa · mux · deliver · looks · clean · gif · cover-preview +├── bin/vh 命令行:doctor · setup · settings · install-skill · sync-agents · sound · commands · status · projects · cancel · history · activity · know · artifacts · studio · types · effort · new · footage · assets · scout · ref · web · review · gate · desk · concept · breakdown · cast · style · recipes · storyboard · rhythm · words · edit · bgm · tts · pace · voices · captions · timeline · remap · timemap · beats · music · sfx · hf-init · determinism · image · model3d · hdri · hf · components · frames · cues · readcheck · textcheck · fonts · sheet · proxy · thumbs · peaks · render · patch · versions · check · mix · qa · mux · deliver · looks · clean · gif · cover-preview ├── tools/ bin/vh 背后的脚本;commands.json 是命令表(`bin/vh commands` 按阶段列出),modules.json 是外接模块表(`bin/vh doctor` 报这台机器能用哪些),audio/README.md 是声音命令的参数手册,desk/README.md 是审阅台的读取约定;ci.sh 是仓库自检 ├── skills/ 轻量 skill(`bin/vh install-skill` 装上的是指回这里的短桩,`git pull` 后不用重装):open-video-harness 在任何目录把做视频的请求引到本仓库;open-video-harness-web 用已装浏览器查网页事实、存参考页 ├── video-types/ 11 类视频(09、11 实验中):工作流、审美、禁止项、Prompt 增量块、自查重点、案例 diff --git a/CLAUDE.md b/CLAUDE.md index 489e7213..25540d68 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -135,7 +135,7 @@ OpenVideoHarness/ ├── CLAUDE.md / AGENTS.md 入口(本文件;AGENTS.md 由 bin/vh sync-agents 生成,内容相同) ├── README.md / README.zh-CN.md 给人看的说明;CONTRIBUTING.md 是改本仓库时的规则;install.sh 一键安装 ├── LOCAL.md 本机环境(不入库;模板是 LOCAL.example.md) -├── bin/vh 命令行:doctor · setup · install-skill · sync-agents · sound · commands · status · projects · cancel · history · activity · know · artifacts · studio · types · effort · new · footage · assets · scout · ref · web · review · gate · desk · concept · breakdown · cast · style · recipes · storyboard · rhythm · words · edit · bgm · tts · pace · voices · captions · timeline · remap · timemap · beats · music · sfx · hf-init · determinism · image · model3d · hdri · hf · components · frames · cues · readcheck · textcheck · fonts · sheet · proxy · thumbs · peaks · render · patch · versions · check · mix · qa · mux · deliver · looks · clean · gif · cover-preview +├── bin/vh 命令行:doctor · setup · settings · install-skill · sync-agents · sound · commands · status · projects · cancel · history · activity · know · artifacts · studio · types · effort · new · footage · assets · scout · ref · web · review · gate · desk · concept · breakdown · cast · style · recipes · storyboard · rhythm · words · edit · bgm · tts · pace · voices · captions · timeline · remap · timemap · beats · music · sfx · hf-init · determinism · image · model3d · hdri · hf · components · frames · cues · readcheck · textcheck · fonts · sheet · proxy · thumbs · peaks · render · patch · versions · check · mix · qa · mux · deliver · looks · clean · gif · cover-preview ├── tools/ bin/vh 背后的脚本;commands.json 是命令表(`bin/vh commands` 按阶段列出),modules.json 是外接模块表(`bin/vh doctor` 报这台机器能用哪些),audio/README.md 是声音命令的参数手册,desk/README.md 是审阅台的读取约定;ci.sh 是仓库自检 ├── skills/ 轻量 skill(`bin/vh install-skill` 装上的是指回这里的短桩,`git pull` 后不用重装):open-video-harness 在任何目录把做视频的请求引到本仓库;open-video-harness-web 用已装浏览器查网页事实、存参考页 ├── video-types/ 11 类视频(09、11 实验中):工作流、审美、禁止项、Prompt 增量块、自查重点、案例 diff --git a/README.md b/README.md index d4ca7edb..fd69ccc3 100644 --- a/README.md +++ b/README.md @@ -265,7 +265,7 @@ Say what the film is about, who it's for and where it will be shown; a long brie ## What's in the box -The tools follow the work: think, gather, make, check and deliver. Each name below is a `bin/vh` command; `bin/vh commands` lists all 73 commands by pipeline stage, and any command takes `-h`. +The tools follow the work: think, gather, make, check and deliver. Each name below is a `bin/vh` command; `bin/vh commands` lists all 74 commands by pipeline stage, and any command takes `-h`. | | Command | What it does | |---|---|---| @@ -415,6 +415,7 @@ By default the installer registers the skills for both agents and uses about 400 ```bash bash install.sh --dir ~/code/OpenVideoHarness # install somewhere else bash install.sh --refs # fetch all 37 reference repos now (about 300 MB) +bash install.sh --mirror cn # use the mainland-China mirrors (--mirror off: never; without it the official sources come first) bash install.sh --no-skill # don't register the global skill bash install.sh --no-icon # leave OVH Studio out of your applications (bin/vh studio --install-icon adds it later) ``` @@ -423,7 +424,7 @@ bash install.sh --no-icon # leave OVH Studio out of your - The installer fetches only the newest commit: the repo itself is about 95 MB to download and 200 MB on disk, before its packages and the reference repos. To contribute or browse the history, `git clone` normally and run `bin/vh setup`. - To update, run the installer again with the same options (or `git pull`); `LOCAL.md` and `projects/` are left alone, and it stops before overwriting files you changed. The installed skills are short stubs that read `skills/` in the clone, so they follow the update; `bin/vh doctor` says in the rare case one needs `bin/vh install-skill` again. - The showcase videos aren't in git; to rebuild a showcase locally, `tools/fetch_media.sh` downloads them from the release to where its scripts expect them. -- The first render and the first use of the sound tools download more into `~/.cache`: Chrome about 200 MB, the sound tools' Python packages about 0.7 GB, and the default local voice about 2.6 GB (its packages 0.8 GB, its model 1.8 GB), which `bin/vh tts` says before it starts and shows the progress of (`--provider edge` needs only a small package). The local Whisper behind `--align local` is about 3.6 GB more, said the same way (measured 2026-11; where each goes is on the wiki's [Getting Started](https://github.com/ZLHad/OpenVideoHarness/wiki/Getting-Started)). If npm, PyPI, Hugging Face or Google Fonts are blocked or slow where you are, [China network](https://github.com/ZLHad/OpenVideoHarness/wiki/China-Network) has the mirror settings. +- The first render and the first use of the sound tools download more into `~/.cache`: Chrome about 200 MB, the sound tools' Python packages about 0.7 GB, and the default local voice about 2.6 GB (its packages 0.8 GB, its model 1.8 GB), which `bin/vh tts` says before it starts and shows the progress of (`--provider edge` needs only a small package). The local Whisper behind `--align local` is about 3.6 GB more, said the same way (measured 2026-11; where each goes is on the wiki's [Getting Started](https://github.com/ZLHad/OpenVideoHarness/wiki/Getting-Started)). Where the official sources are blocked: the installer tries the official npm registry first, and when it does not answer in 5 s and the mainland-China mirror does, it switches to the mirrors (npmmirror, Tsinghua's TUNA, hf-mirror, listed in `tools/mirrors.txt`), says so, and every later `bin/vh` download follows (npm, Python packages, the local voice's model, Electron, the Chrome renders use); `bin/vh settings mirror off` turns that off. GitHub itself has no mirror: cloning the repo still needs GitHub. More on the wiki's [China network](https://github.com/ZLHad/OpenVideoHarness/wiki/China-Network) page. Skill only: `npx skills add https://github.com/ZLHad/OpenVideoHarness --skill open-video-harness`. It's a pointer: on first use it asks before installing the full workbench. That copy stays as it was when the repo changes; once the workbench is installed, `bin/vh install-skill` replaces it with a stub that follows the clone. diff --git a/README.zh-CN.md b/README.zh-CN.md index 72f71d3b..0fca0b0a 100644 --- a/README.zh-CN.md +++ b/README.zh-CN.md @@ -265,7 +265,7 @@ curl -fsSL https://raw.githubusercontent.com/ZLHad/OpenVideoHarness/main/install ## 工具一览 -工具跟着做片子的顺序走:想、找料、做、查和交付。下表每个名字都是一条 `bin/vh` 命令;`bin/vh commands` 按流程阶段列出全部 73 条命令,每条命令加 `-h` 看用法。 +工具跟着做片子的顺序走:想、找料、做、查和交付。下表每个名字都是一条 `bin/vh` 命令;`bin/vh commands` 按流程阶段列出全部 74 条命令,每条命令加 `-h` 看用法。 | | 命令 | 做什么 | |---|---|---| @@ -415,6 +415,7 @@ AI 听不见,所以声音尽量做成能计算、能测量的。 ```bash bash install.sh --dir ~/code/OpenVideoHarness # 装到别的位置 bash install.sh --refs # 安装时就把 37 个参考仓库拉全(约 300 MB) +bash install.sh --mirror cn # 直接用国内镜像(--mirror off:不用;不写时先试官方源) bash install.sh --no-skill # 不注册全局 skill bash install.sh --no-icon # 不把 OVH Studio 放进应用程序(以后 bin/vh studio --install-icon 再放) ``` @@ -423,7 +424,7 @@ bash install.sh --no-icon # 不把 OVH Studio 放进应 - 安装脚本只拉最新的一个提交,仓库本身下载约 95 MB、占约 200 MB 磁盘,依赖和参考仓库另算;想参与贡献或翻历史,就正常 `git clone`,再运行 `bin/vh setup`。 - 更新:用同样的参数再运行一次安装命令(或者 `git pull`);`LOCAL.md` 和 `projects/` 不动,要覆盖你改过的文件时会先停下来。装出去的 skill 是指回克隆里 `skills/` 的短桩,跟着一起更新;少数要重装的时候(`bin/vh install-skill`),`bin/vh doctor` 会说。 - 样片的视频不在 git 里,要在本地复现样片时运行 `tools/fetch_media.sh`,它从 Release 下载到脚本要的位置。 -- 第一次渲染、第一次用声音工具时还会往 `~/.cache` 下载:Chrome 约 200 MB,声音工具的 Python 依赖约 0.7 GB,默认的本地配音约 2.6 GB(依赖 0.8 GB、模型 1.8 GB;`bin/vh tts` 开始前会先说,并显示进度;`--provider edge` 只要一个小包);`--align local` 用的本地 Whisper 另需约 3.6 GB,同样先说(2026-11 实测;各放在哪里见 wiki 的[快速开始](https://github.com/ZLHad/OpenVideoHarness/wiki/%E5%BF%AB%E9%80%9F%E5%BC%80%E5%A7%8B))。国内网络连不上 npm、PyPI、Hugging Face 或 Google Fonts 时,镜像设置见 wiki 的[国内网络](https://github.com/ZLHad/OpenVideoHarness/wiki/%E5%9B%BD%E5%86%85%E7%BD%91%E7%BB%9C)。 +- 第一次渲染、第一次用声音工具时还会往 `~/.cache` 下载:Chrome 约 200 MB,声音工具的 Python 依赖约 0.7 GB,默认的本地配音约 2.6 GB(依赖 0.8 GB、模型 1.8 GB;`bin/vh tts` 开始前会先说,并显示进度;`--provider edge` 只要一个小包);`--align local` 用的本地 Whisper 另需约 3.6 GB,同样先说(2026-11 实测;各放在哪里见 wiki 的[快速开始](https://github.com/ZLHad/OpenVideoHarness/wiki/%E5%BF%AB%E9%80%9F%E5%BC%80%E5%A7%8B))。国内网络:安装时先试官方的 npm 源,5 秒内没有应答、国内镜像有,就改用国内镜像(npmmirror、清华 TUNA、hf-mirror,列在 `tools/mirrors.txt`)并说一声,之后 `bin/vh` 的下载(npm、Python 包、本地配音模型、Electron、渲染用的 Chrome)都跟着走;`bin/vh settings mirror off` 关掉。GitHub 本身没有镜像:克隆仓库还是要连得上 GitHub。其余细节见 wiki 的[国内网络](https://github.com/ZLHad/OpenVideoHarness/wiki/%E5%9B%BD%E5%86%85%E7%BD%91%E7%BB%9C)。 只装 skill:`npx skills add https://github.com/ZLHad/OpenVideoHarness --skill open-video-harness`。它只是一个指针,第一次用时会征得你同意,再把完整的工作台装好。这样装的是整份副本,仓库更新了它不变;工作台装好以后跑一次 `bin/vh install-skill`,换成跟随克隆的短桩。 diff --git a/bin/vh b/bin/vh index 21660ee4..1b082d88 100755 --- a/bin/vh +++ b/bin/vh @@ -8,6 +8,15 @@ set -euo pipefail unset CDPATH # an exported CDPATH would send a relative cd (this one: bin/vh run as bin/vh) to another folder, and print it ROOT="$(cd "$(dirname "${BASH_SOURCE[0]}")/.." && pwd)" c_ok=$'\033[32m✓\033[0m'; c_no=$'\033[31m✗\033[0m'; c_wa=$'\033[33m!\033[0m' +# this machine's settings (tools/settings.py): with "mirror": "cn", every download a command starts goes to the mirrors in +# tools/mirrors.txt (npm, uv, Hugging Face, Electron; a variable already set wins); read with grep, so no python3 per run +if [ -f "${XDG_CONFIG_HOME:-$HOME/.config}/ovh/settings.json" ] && grep -q '"mirror"[[:space:]]*:[[:space:]]*"cn"' "${XDG_CONFIG_HOME:-$HOME/.config}/ovh/settings.json" 2>/dev/null; then + while read -r _k _v _o _m _w; do + case "$_k" in ""|\#*) continue ;; esac + if [ "$_v" != - ] && [ -z "${!_v:-}" ]; then export "$_v=$_m"; fi + done < "$ROOT/tools/mirrors.txt" + export OVH_MIRROR=cn +fi declare -a TYPES=( "math:01-math-science-explainer:数学/科学原理讲解(Manim)" @@ -126,6 +135,18 @@ hf_pin() { # hf_pin : the Chrome version pinned by the HyperFrames in the n [ ${#files[@]} -gt 0 ] || return 1 awk -F'"' -v k="var $k = " '$1 == k && $2 ~ /^[0-9][0-9.]*$/ { print $2; f = 1; exit } END { exit !f }' "${files[@]}" 2>/dev/null } +hf_chrome_mirror() { # hf_chrome_mirror : with the mirror on (cn) and no chrome-headless-shell yet at the version the HyperFrames + # installed for dir pins, fetch it from the mirror into the folder HyperFrames looks in: HyperFrames has no setting for where it + # downloads its Chrome, so without this the first render would go to storage.googleapis.com anyway (no hash is pinned for it) + [ "${OVH_MIRROR:-}" = cn ] || return 0 + local d=$1 pin base + pin=$(hf_pin "$d") || return 0 + [ -n "$(shell_folder "$HOME/.cache/hyperframes/chrome/chrome-headless-shell" "$pin" 2>/dev/null)" ] && return 0 + base=$(awk '$1 == "chrome" { print $4 }' "$ROOT/tools/mirrors.txt") + echo "→ HyperFrames' Chrome $pin from the mirror ($base, about 93 MB), into ~/.cache/hyperframes/chrome, where its first render looks" + (cd "$d" && npx --yes @puppeteer/browsers install "chrome-headless-shell@$pin" --path "$HOME/.cache/hyperframes/chrome" --base-url "$base" >/dev/null 2>&1) \ + || echo "$c_wa HyperFrames' Chrome did not come from the mirror; the first render tries its own download" +} old_mac() { [ "$(uname)" = Darwin ] && [ "$(uname -r | cut -d. -f1)" -lt 22 ]; } # macOS 12 or older: HyperFrames stops Chrome at 150 shell_folder() { # shell_folder [version]: the folder of that chrome-headless-shell version, else (no version given) the newest; # only a folder with the browser in it counts (an interrupted download leaves an empty one). Folders are - @@ -170,6 +191,17 @@ cmd_install_skill() { # writes a stub for each skill in skills/: its frontmatter echo " restart Claude Code / Codex so it picks up the skill; then ask for a video from any folder." echo " a git pull here updates the skill; run this again only when bin/vh doctor's skills line says so (a renamed skill, a new one, a changed description)." } +cmd_settings() { # this machine's settings (tools/settings.py, -h); the mirror turned on also fetches HyperFrames' Chrome from it now, + # since HyperFrames cannot be pointed at a mirror itself + if [ "${1:-}" = chrome ]; then # settings chrome: HyperFrames' Chrome from the mirror now, when the mirror is on and it is not here + [ $# = 1 ] || { echo "usage: bin/vh settings chrome" >&2; return 2; } + [ "${OVH_MIRROR:-}" = cn ] || { echo "the mirrors are not on (bin/vh settings mirror cn): HyperFrames downloads its own Chrome at the first render"; return 0; } + [ -d "$ROOT/styles/_swatch/node_modules/hyperframes" ] || { echo "$c_wa no HyperFrames in styles/_swatch yet (cd styles/_swatch && npm ci): nothing to fetch Chrome for" >&2; return 1; } + hf_chrome_mirror "$ROOT/styles/_swatch"; return 0 + fi + python3 "$ROOT/tools/settings.py" "$@" || return $? + if [ "${1:-}" = mirror ] && [ "${2:-}" = cn ] && [ -d "$ROOT/styles/_swatch/node_modules/hyperframes" ]; then OVH_MIRROR=cn; hf_chrome_mirror "$ROOT/styles/_swatch"; fi +} cmd_sync_agents() { # CLAUDE.md's 命令行 line from tools/commands.json first, then AGENTS.md from CLAUDE.md local m; m=$(python3 "$ROOT/tools/commands.py" claude-line --write "$ROOT/CLAUDE.md") || exit 1 echo "$c_ok $m" @@ -1051,6 +1083,7 @@ PY done shopt -u dotglob; rm -rf "$tmp" (cd "$dir" && npm i -D --save-exact --silent --no-fund --no-audit "hyperframes@${HYPERFRAMES_VERSION:-0.8.202}" >/dev/null 2>&1) || echo "$c_wa could not pin hyperframes locally (offline?)" + hf_chrome_mirror "$dir" # with the mirror on: its Chrome now, from the mirror, not at the first render from Google's # the scaffold loads GSAP from a CDN; an offline render then hangs silently, so vend it locally (same pinned version) local gv; gv=$(grep -o 'cdn.jsdelivr.net/npm/gsap@[0-9.]*' "$dir"/*.html 2>/dev/null | head -1 | sed 's/.*gsap@//') || true if [ -n "$gv" ] && (cd "$dir" && npm i -D --save-exact --silent --no-fund --no-audit "gsap@$gv" >/dev/null 2>&1); then @@ -1450,11 +1483,12 @@ case "${2:-}" in -h|--help) # `bin/vh -h` prints its usage instead o pace) cmd_usage pace; echo; exec python3 "$ROOT/tools/audio/pace.py" -h ;; words) cmd_usage words; echo; exec python3 "$ROOT/tools/words.py" -h ;; # + what it reads, the checks and the --json fields doctor) cmd_usage doctor; echo; exec python3 "$ROOT/tools/doctor.py" -h ;; # + the --json fields + settings) cmd_usage settings; echo; exec python3 "$ROOT/tools/settings.py" -h ;; # + the file's shape frames|render|determinism|cues|patch) cmd_usage "$1"; echo; exec node "$ROOT/tools/film/$1.mjs" -h ;; # + every flag *) cmd_usage "$1" && exit 0 ;; esac ;; esac case "${1:-}" in # the activity log: every command that works on a project (act_start finds it) but the read-only views - ""|help|-h|--help|setup|install-skill|sync-agents|types|effort|recipes|doctor|commands|status|activity|know|artifacts|projects|new|words|studio) ;; # (new: once the project is made; words only reads; studio opens a page, and the desk it starts logs its own run) + ""|help|-h|--help|setup|install-skill|settings|sync-agents|types|effort|recipes|doctor|commands|status|activity|know|artifacts|projects|new|words|studio) ;; # (new: once the project is made; words only reads; studio opens a page, and the desk it starts logs its own run) components) [ "${2:-}" != add ] || act_start "$@" || true ;; # list, check and sample touch no project desk) case "${2:-}" in data|agents) ;; *) act_start "$@" || true ;; esac ;; # agents: no project (it installs into a cache) versions) case "${2:-}" in compare|use) act_start "$@" || true ;; esac ;; # the list is a read-only view @@ -1481,6 +1515,7 @@ case "${1:-help}" in doctor) shift; cmd_doctor "$@" ;; setup) cmd_setup ;; types) cmd_types ;; tts) shift; cmd_tts "$@" ;; pace) shift; cmd_pace "$@" ;; voices) shift; cmd_voices "$@" ;; captions) shift; cmd_captions "$@" ;; timeline) shift; cmd_timeline "$@" ;; remap) shift; cmd_remap "$@" ;; timemap) shift; cmd_timemap "$@" ;; music) shift; cmd_music "$@" ;; sfx) shift; cmd_sfx "$@" ;; beats) shift; cmd_beats "$@" ;; mix) shift; cmd_mix "$@" ;; qa) shift; cmd_qa "$@" ;; mux) shift; cmd_mux "$@" ;; install-skill) shift; cmd_install_skill "$@" ;; + settings) shift; cmd_settings "$@" ;; recipes) shift; python3 "$ROOT/tools/recipes.py" "$@" ;; bgm) shift; cmd_bgm "$@" ;; sound) shift; cmd_sound "$@" ;; diff --git a/changes/first-run-mirrors.md b/changes/first-run-mirrors.md new file mode 100644 index 00000000..d11bde11 --- /dev/null +++ b/changes/first-run-mirrors.md @@ -0,0 +1,7 @@ +**连不上官方源时,安装自动改用国内镜像,之后的下载都跟着走** +- Why: 在国内网络下,第一次安装和第一次做片要连 npm、PyPI、Hugging Face、GitHub Releases 和 Google 的存储;原来要照 wiki 手动设三四个变量、另跑两条命令装 Chrome,Studio 应用的 Electron 下载没有写怎么办。 +- 安装时先试官方的 npm 源(5 秒);没有应答、国内镜像有,就改用国内镜像,用一句话说明,并记在这台机器自己的设置里(`~/.config/ovh/settings.json`)。不按语言或时区猜。`--mirror cn` 直接用,`--mirror off` 不用,也记下来。 +- 镜像的地址集中在 `tools/mirrors.txt` 一个文件里,每一行写明是谁在运营(npmmirror.com、清华 TUNA、hf-mirror.com)。镜像打开时,`bin/vh` 给它运行的每条命令设好 npm、uv(Python 包和 Python 本身)、Hugging Face 和 Electron 的镜像变量;你自己设过的变量不动。HyperFrames 下载 Chrome 时没有可设的地址,所以由 `bin/vh new` 和安装先从镜像把它装进 HyperFrames 找的目录。 +- 新命令 `bin/vh settings`:看这台机器的设置,`bin/vh settings mirror cn|off|auto` 改镜像,`--json` 给 Studio 的设置面板读。`bin/vh doctor` 多一行说现在走哪里、怎么关。 +- 已有的校验不变,也不信任镜像:npm ci 按 lockfile 里的哈希核对每个包;Electron 按它自己的包里带的 checksums.json 核对。uv 的包、Hugging Face 的模型、Python 和 Chrome 没有钉住的哈希,和从官方源下一样照收。 +- 切到镜像以后,uv 会按新的源重新下载之前缓存过的 Python 包(它的缓存按源区分)。 diff --git a/docs/assets/overview.en.svg b/docs/assets/overview.en.svg index 18c77caa..bac3cec4 100644 --- a/docs/assets/overview.en.svg +++ b/docs/assets/overview.en.svg @@ -37,7 +37,7 @@ rect{stroke-width:0.8} Knowledge11 video types · 13 playbook docs43 styles · 75 shot recipes6 motion components · 15 cases37 reference repos, read-only -Tools and enginesbin/vh: 73 commandsHyperFrames · canvas + Three.jsp5.brush · Manim · Blendervoice · score · SFX · mix · QA +Tools and enginesbin/vh: 74 commandsHyperFrames · canvas + Three.jsp5.brush · Manim · Blendervoice · score · SFX · mix · QA Records and lessonsREVIEW.md logs every noteLESSONS flow into the playbookthe next film starts better diff --git a/docs/assets/overview.zh.svg b/docs/assets/overview.zh.svg index 590e82ee..ce213a8b 100644 --- a/docs/assets/overview.zh.svg +++ b/docs/assets/overview.zh.svg @@ -37,7 +37,7 @@ rect{stroke-width:0.8} 知识库11 类视频 · 13 篇 playbook43 种风格 · 75 张镜头配方6 个动效组件 · 15 个案例37 个只读参考仓库 -工具与引擎bin/vh:73 条命令HyperFrames · canvas + Three.jsp5.brush · Manim · Blender配音 · 作曲 · 音效 · 混音 · QA +工具与引擎bin/vh:74 条命令HyperFrames · canvas + Three.jsp5.brush · Manim · Blender配音 · 作曲 · 音效 · 混音 · QA 记录与回流REVIEW.md 记下每条意见LESSONS 回流进 playbook下一支片子直接受益 diff --git a/docs/site/index.html b/docs/site/index.html index 5898ddea..02696c6e 100644 --- a/docs/site/index.html +++ b/docs/site/index.html @@ -976,7 +976,7 @@

Reads读

-

Runs跑 one CLI, 73 commands, 5 engines一个命令行,73 条命令,5 个引擎

+

Runs跑 one CLI, 74 commands, 5 engines一个命令行,74 条命令,5 个引擎

bin/vhnew · edit · render · check · gate · studio · footage · image · tts · music
HyperFramescanvas + Three.jsp5.brushManimBlender
@@ -1006,7 +1006,7 @@

Runs跑

06Capability map能力地图

From idea to delivery, a tool at every step.从立意到交付,每一步都有工具。

-

One CLI, bin/vh, with 73 commands. Each name below is one; any command takes -h, and bin/vh commands lists them by stage.一个命令行 bin/vh,73 条命令。下面每个名字都是其中一条;每条加 -h 看用法,bin/vh commands 按阶段列出全部。

+

One CLI, bin/vh, with 74 commands. Each name below is one; any command takes -h, and bin/vh commands lists them by stage.一个命令行 bin/vh,74 条命令。下面每个名字都是其中一条;每条加 -h 看用法,bin/vh commands 按阶段列出全部。

diff --git a/install.sh b/install.sh index ccd5174c..b824a488 100755 --- a/install.sh +++ b/install.sh @@ -1,9 +1,13 @@ #!/usr/bin/env bash # OpenVideoHarness one-line installer. # curl -fsSL https://raw.githubusercontent.com/ZLHad/OpenVideoHarness/main/install.sh | bash -# bash install.sh [--dir ~/OpenVideoHarness] [--refs] [--no-skill] [--skill claude|codex|all] [--obscura] [--icon | --no-icon] +# bash install.sh [--dir ~/OpenVideoHarness] [--refs] [--no-skill] [--skill claude|codex|all] [--mirror cn|off] [--obscura] [--icon | --no-icon] # What it does, and where it puts things: # 1. clone the repo into --dir, newest commit only (about 200 MB on disk; a re-run moves it to the newest commit, keeping LOCAL.md and projects/) +# 1b. the download mirrors (tools/mirrors.txt): with neither --mirror nor a choice made before (bin/vh settings), try the official +# npm registry for 5 s; when it does not answer and the mainland-China mirror does, use the mirrors from here on, say so in one +# line, and keep the choice in ~/.config/ovh/settings.json, so later bin/vh downloads use them too (bin/vh settings mirror off +# turns that off). --mirror cn uses them without trying, --mirror off never. Never guessed from the language or time zone # 2. npm install in engines/ClaudeAnimationBase and npm ci in styles/_swatch (HyperFrames 0.8.202), both inside --dir (about 180 MB of # node_modules; npm also writes its own cache, ~/.npm). The read-only reference repos references/fetch.sh lists are not fetched: # an agent fetches the one a doc points to when it first needs it (bash references/fetch.sh , which says its size first); @@ -33,12 +37,13 @@ # The wiki's Getting Started ("What gets downloaded") has the same list. set -euo pipefail REPO="${OVH_REPO:-https://github.com/ZLHad/OpenVideoHarness.git}" -DIR="${OVH_DIR:-$HOME/OpenVideoHarness}"; REFS=0; SKILL=all; OBSCURA=0; ICON=default +DIR="${OVH_DIR:-$HOME/OpenVideoHarness}"; REFS=0; SKILL=all; OBSCURA=0; ICON=default; MIRROR="" while [ $# -gt 0 ]; do case "$1" in - --dir) DIR="$2"; shift 2 ;; --refs) REFS=1; shift ;; --no-refs) REFS=0; shift ;; --no-skill) SKILL=none; shift ;; --skill) SKILL="${2:?--skill needs claude|codex|all|none}"; shift 2 ;; --obscura) OBSCURA=1; shift ;; + --dir) DIR="$2"; shift 2 ;; --refs) REFS=1; shift ;; --no-refs) REFS=0; shift ;; --no-skill) SKILL=none; shift ;; --skill) SKILL="${2:?--skill needs claude|codex|all|none}"; shift 2 ;; --obscura) OBSCURA=1; shift ;; --mirror) MIRROR="${2:?--mirror needs cn or off}"; shift 2 ;; --icon) ICON=yes; shift ;; --no-icon) ICON=no; shift ;; -h|--help) sed -n '2,32p' "$0"; exit 0 ;; *) echo "unknown option: $1"; exit 1 ;; esac; done case "$SKILL" in claude|codex|all|none) ;; *) echo "unknown --skill '$SKILL' (claude|codex|all|none)"; exit 1 ;; esac +case "$MIRROR" in ""|cn|off) ;; *) echo "unknown --mirror '$MIRROR' (cn|off)"; exit 1 ;; esac say() { printf '\033[1m→ %s\033[0m\n' "$*"; } NOAPP="${XDG_DATA_HOME:-$HOME/.local/share}/ovh-studio/no-app" # --no-icon once: kept here, so an update leaves OVH Studio out too (--icon clears it) put_icon() { # OVH Studio in the applications, unasked (macOS, a Linux desktop): left alone when it is there and current, never @@ -99,6 +104,14 @@ if [ -d "$DIR/.git" ]; then say "updating $DIR" else say "cloning into $DIR (newest commit only)" git clone -q --depth 1 --single-branch "$REPO" "$DIR" || { echo "✗ Could not download OpenVideoHarness: check the network (or your proxy) and run this installer again."; exit 1; }; fi cd "$DIR" +answers() { command -v curl >/dev/null 2>&1 && curl -fsS -m 5 -o /dev/null "$1" 2>/dev/null; } +if [ -n "$MIRROR" ]; then bin/vh settings mirror "$MIRROR" --why "install.sh --mirror $MIRROR, $(date +%F)" | sed 's/^/ /' +elif [ "$(bin/vh settings mirror --get 2>/dev/null)" = auto ] && ! answers https://registry.npmjs.org/ && answers https://registry.npmmirror.com/; then + bin/vh settings mirror cn --why "install.sh, $(date +%F): registry.npmjs.org did not answer in 5 s, registry.npmmirror.com did" >/dev/null + echo " npm's registry did not answer in 5 s, so downloads come from the mainland-China mirrors from now on (npmmirror.com, TUNA, hf-mirror.com;" + echo " tools/mirrors.txt). bin/vh settings mirror off turns that off." +fi +eval "$(python3 tools/settings.py env)" # the mirrors, when they are on, for this script's own downloads too say "installing the bundled engine (ClaudeAnimationBase)" (cd engines/ClaudeAnimationBase && npm install --silent) || echo "! the hand-drawn engine's packages did not install; running this installer again finishes them" n=$(grep -cE '^(full|sparse|textonly) ' references/fetch.sh || true) # counted from the list, so it cannot go stale @@ -110,6 +123,7 @@ else had=0; [ ! -d references/repos ] || had=$(find references/repos -mindepth 2 fi say "installing the renderer for style samples (HyperFrames, for bin/vh style)" (cd styles/_swatch && npm ci --silent) || echo "! the renderer for style samples did not install; it is tried again the first time a style sample is made" +[ "${OVH_MIRROR:-}" != cn ] || bin/vh settings chrome # with the mirrors on: HyperFrames' Chrome from the mirror now [ -f LOCAL.md ] || cp LOCAL.example.md LOCAL.md if [ "$SKILL" != none ]; then # one line for the stubs it wrote (each says where it went when run by hand: bin/vh install-skill) say "telling Claude Code and Codex where this workbench is (skills)" diff --git a/tools/ci.sh b/tools/ci.sh index 30f83e58..b650e41c 100755 --- a/tools/ci.sh +++ b/tools/ci.sh @@ -1659,6 +1659,27 @@ PY else bad "first downloads here: $a | $b | no script ($re): $qcalls | progress lines: $g"; fi ;; esac rm -rf "$ft" + # the download mirrors: this machine's settings (tools/settings.py) in a file of their own; with "mirror": "cn" bin/vh exports + # the variables of tools/mirrors.txt for what it runs (one the person set stays theirs); install.sh tries the official npm + # registry first and keeps cn only when it does not answer and the mirror does; --mirror off is kept, and stops the trying + t=$(mktemp -d "${TMPDIR:-/tmp}/vh-mirror.XXXXXX") + a=$(XDG_CONFIG_HOME="$t/c" vh settings mirror --get; XDG_CONFIG_HOME="$t/c" vh settings mirror cn --why "a test" >/dev/null + (unset npm_config_registry HF_ENDPOINT UV_DEFAULT_INDEX ELECTRON_MIRROR; XDG_CONFIG_HOME="$t/c" vh settings --json) | python3 -c 'import json, sys; d = json.load(sys.stdin); e = d["environment"] +print(d["mirror"], d["settings"].get("mirror_why"), e["npm_config_registry"], e["HF_ENDPOINT"], e["UV_DEFAULT_INDEX"], e["ELECTRON_MIRROR"])' + XDG_CONFIG_HOME="$t/c" npm_config_registry=https://mine.example vh settings --json | python3 -c 'import json, sys; print(json.load(sys.stdin)["environment"]["npm_config_registry"])' + XDG_CONFIG_HOME="$t/c" vh settings mirror off >/dev/null; (unset npm_config_registry; XDG_CONFIG_HOME="$t/c" vh settings --json) | python3 -c 'import json, sys; d = json.load(sys.stdin); print(d["mirror"], d["environment"]["npm_config_registry"])' + XDG_CONFIG_HOME="$t/c" vh settings mirror nope 2>/dev/null; echo "exit $?") + b=$(awk '!/^#/ && NF { if ($4 !~ /^https:\/\//) print "not https: " $1 }' tools/mirrors.txt) + mkdir -p "$t/bin"; printf '#!/bin/sh\ncase "$*" in *registry.npmjs.org*) [ -n "$OFFICIAL" ] && exit 0; exit 28 ;; *) exit 0 ;; esac\n' > "$t/bin/curl"; chmod +x "$t/bin/curl" + sed -n '/^answers() {/,/^eval "\$(python3 tools\/settings.py env)"/p' install.sh > "$t/probe.sh" + probe() { (env PATH="$t/bin:$PATH" XDG_CONFIG_HOME="$t/$1" "${@:2}" bash -c '. "$1"; vh_get() { bin/vh settings mirror --get; }; echo "now $(vh_get) ${npm_config_registry:-official}"' _ "$t/probe.sh" 2>&1 | tail -1); } + c=$(MIRROR="" probe p1 env -u npm_config_registry); d=$(probe p2 env -u npm_config_registry OFFICIAL=1); e=$(probe p3 env -u npm_config_registry MIRROR=off); f=$(probe p3 env -u npm_config_registry MIRROR=) + if case "$a" in "auto"*"cn a test https://registry.npmmirror.com https://hf-mirror.com https://mirrors.tuna.tsinghua.edu.cn/pypi/web/simple https://npmmirror.com/mirrors/electron/"*"https://mine.example"*"off None"*"exit 2") true ;; *) false ;; esac \ + && [ -z "$b" ] && [ -s "$t/probe.sh" ] && [ "$c" = "now cn https://registry.npmmirror.com" ] && [ "$d" = "now auto official" ] && [ "$e" = "now off official" ] && [ "$f" = "now off official" ] \ + && grep -q '"mirror_why": "install.sh, ' "$t/p1/ovh/settings.json" + then ok "mirrors: kept in this machine's settings; bin/vh exports tools/mirrors.txt's variables with cn (a variable the person set stays); install.sh keeps cn only when the official npm registry does not answer and the mirror does; off is kept and stops the trying" + else bad "mirrors: $a | $b | probe: $c / $d / $e / $f"; fi + rm -rf "$t" # recipes sample: bad usage exits 2 before any render (an unknown id, a sequence, an unknown style); list --json names # the sheet a recipe carries (recipes check, above, holds every sketch to its sheet) vh recipes sample no-such-recipe >/dev/null 2>&1; rc=$?; vh recipes sample launch-15s >/dev/null 2>&1; rc2=$? diff --git a/tools/commands.json b/tools/commands.json index 228499bc..f83dcf7c 100644 --- a/tools/commands.json +++ b/tools/commands.json @@ -119,6 +119,25 @@ } ] }, + { + "name": "settings", + "summary": "This machine's own settings, the ones that are not secret, kept once for every clone and for Studio: for now the download mirrors (tools/mirrors.txt), cn, off or auto.", + "when": "when downloads are blocked or slow where you are (install.sh switches to the mirrors by itself when the official npm registry does not answer), or to turn the mirrors off again", + "stages": ["env"], + "reads": ["$XDG_CONFIG_HOME/ovh/settings.json (~/.config/ovh/settings.json)", "tools/mirrors.txt"], + "writes": ["$XDG_CONFIG_HOME/ovh/settings.json (~/.config/ovh/settings.json)", "~/.cache/hyperframes/chrome (mirror cn: HyperFrames' Chrome from the mirror)"], + "usage": [ + { + "synopsis": "settings [--json] | settings mirror cn|off|auto [--why TEXT] | settings mirror --get | settings chrome", + "text": [ + "what this machine's settings are and where they are kept; mirror cn: every later download a command starts comes from the", + "mainland-China mirrors in tools/mirrors.txt (npm, uv, Hugging Face, Electron; HyperFrames' Chrome fetched from the mirror", + "now, as HyperFrames cannot be pointed at one; settings chrome does only that), off: never, auto: the official sources", + "(install.sh tries them first)" + ] + } + ] + }, { "name": "install-skill", "summary": "Register the skills in skills/ for Claude Code, Codex or both: short stubs that read skills//SKILL.md in this clone, so a git pull updates them.", diff --git a/tools/doctor.py b/tools/doctor.py index 1c18ac55..64711724 100644 --- a/tools/doctor.py +++ b/tools/doctor.py @@ -197,6 +197,8 @@ def first_film(mods, checks, plat, found_by=None, env=os.environ, libs=None): lines.append(" The first render downloads its own Chrome once (about 0.2 GB).") if font and not zh_locale(env): lines.append("! Chinese text: no Chinese font here, so it would draw as boxes → sudo apt install fonts-noto-cjk") + if ((c.get("mirror") or {}).get("note") or "").startswith("cn:"): + lines.append(" Downloads come from the mainland-China mirrors (bin/vh settings mirror off turns that off).") if plat == "darwin-arm64": if (m.get("qwen3-tts") or {}).get("state") == "ok" and (m.get("mlx-audio") or {}).get("state") == "ok": lines.append("✓ Voice: the local voice is downloaded.") @@ -679,6 +681,15 @@ def repo_checks(webgl, found_by): out.append({"name": "references", "state": "ok", "note": f"{have}/{want} repos fetched, {size_of(ROOT / 'references' / 'repos')}"}) else: out.append({"name": "references", "state": "ok", "note": references_note(have, want, bytes_of(ROOT / "references" / "repos") if have else 0, install_says())}) + try: # the download mirrors this machine's settings say (tools/settings.py, tools/mirrors.txt) + import settings as S + d = S.load(); m = S.mirror(d); why = f" ({d['mirror_why']})" if d.get("mirror_why") else "" + out.append({"name": "mirror", "state": "ok", "note": { + "cn": f"cn: downloads come from the mainland-China mirrors ({S.operators()}; tools/mirrors.txt){why} → bin/vh settings mirror off turns that off", + "off": f"off: the official sources, and install.sh does not try the mirrors{why} → bin/vh settings mirror auto or cn changes it", + "auto": "auto: the official sources (install.sh tries the mainland-China mirrors when the official npm registry does not answer) → bin/vh settings mirror cn uses them now"}[m]}) + except (OSError, ValueError, ImportError) as e: + out.append({"name": "mirror", "state": "unchecked", "note": f"tools/mirrors.txt or this machine's settings not readable: {e}"}) local = ROOT / "LOCAL.md" if not local.exists(): out.append({"name": "local_md", "state": "missing", "note": "no LOCAL.md → bin/vh doctor --fill-local (copies LOCAL.example.md, writes this machine's lines)"}) diff --git a/tools/mirrors.txt b/tools/mirrors.txt new file mode 100644 index 00000000..3c2a8785 --- /dev/null +++ b/tools/mirrors.txt @@ -0,0 +1,19 @@ +# Download mirrors for a network where the official sources do not answer (mainland China), in one place. +# install.sh tries the official npm registry first (5 s); only when it does not answer and the mirror does, this machine's +# settings get "mirror": "cn" ($XDG_CONFIG_HOME/ovh/settings.json, tools/settings.py), and from then on bin/vh exports the +# variables below with the mirror column, so every later download goes there: npm (project packages, Studio's app and its +# agent adapters), uv (Python packages, a Python build), Hugging Face (the local voice), Electron, and HyperFrames' Chrome, +# which bin/vh fetches from the mirror itself because HyperFrames has no setting for it. A variable you set yourself wins. +# install.sh --mirror cn uses them without trying, --mirror off never; bin/vh settings mirror cn|off|auto changes it later. +# The checks the tools already make stay as they are, and do not trust the mirror: npm ci checks each package against the +# lockfile's hash; Electron's download is checked against the checksums.json its npm package ships (itself under that +# hash). uv's packages, the Hugging Face model, a Python build and Chrome have no hash pinned here: they are taken as the +# mirror serves them over https, as they are taken from the official source. +# +# kind variable official (tried first) mirror (cn) who runs the mirror +npm npm_config_registry https://registry.npmjs.org https://registry.npmmirror.com npmmirror.com, run by the cnpm project +pypi UV_DEFAULT_INDEX https://pypi.org/simple https://mirrors.tuna.tsinghua.edu.cn/pypi/web/simple TUNA, Tsinghua University's open-source mirror +python UV_PYTHON_INSTALL_MIRROR https://github.com/astral-sh/python-build-standalone/releases/download https://registry.npmmirror.com/-/binary/python-build-standalone npmmirror.com +huggingface HF_ENDPOINT https://huggingface.co https://hf-mirror.com hf-mirror.com, a non-profit community project, not Hugging Face's own +electron ELECTRON_MIRROR https://github.com/electron/electron/releases/download/ https://npmmirror.com/mirrors/electron/ npmmirror.com +chrome - https://storage.googleapis.com/chrome-for-testing-public https://cdn.npmmirror.com/binaries/chrome-for-testing npmmirror.com diff --git a/tools/schemas/output/settings.schema.json b/tools/schemas/output/settings.schema.json new file mode 100644 index 00000000..ad29f391 --- /dev/null +++ b/tools/schemas/output/settings.schema.json @@ -0,0 +1,30 @@ +{ + "$schema": "https://json-schema.org/draft/2020-12/schema", + "$id": "https://github.com/ZLHad/OpenVideoHarness/tools/schemas/output/settings.schema.json", + "title": "bin/vh settings --json", + "description": "This machine's own settings (tools/settings.py: $XDG_CONFIG_HOME/ovh/settings.json), the mirror in effect, the mirror table (tools/mirrors.txt) and the mirror variables as bin/vh exported them.", + "type": "object", + "required": ["version", "tool", "file", "settings", "mirror", "mirrors", "environment"], + "properties": { + "version": {"enum": [1]}, + "tool": {"type": "string"}, + "file": {"type": "string"}, + "settings": {"type": "object"}, + "mirror": {"enum": ["cn", "off", "auto"]}, + "mirrors": { + "type": "array", + "items": { + "type": "object", + "required": ["kind", "variable", "official", "mirror", "who"], + "properties": { + "kind": {"type": "string"}, + "variable": {"type": ["string", "null"]}, + "official": {"type": "string"}, + "mirror": {"type": "string"}, + "who": {"type": "string"} + } + } + }, + "environment": {"type": "object"} + } +} diff --git a/tools/settings.py b/tools/settings.py new file mode 100644 index 00000000..58d97aa7 --- /dev/null +++ b/tools/settings.py @@ -0,0 +1,145 @@ +"""bin/vh settings: this machine's own settings, the ones that are not secret, for every clone on it and for Studio. Stdlib only. + +usage: bin/vh settings [--json] what they are now, and where they are kept + bin/vh settings mirror cn|off|auto [--why TEXT] the download mirrors (tools/mirrors.txt): + cn every later download comes from the mainland-China mirrors (bin/vh exports their variables) + off never: the official sources, and install.sh does not try the mirrors either + auto the official sources; install.sh tries the official npm registry once and switches to cn when it + does not answer and the mirror does (the default: no "mirror" key) + bin/vh settings mirror --get cn, off or auto, alone on a line + bin/vh settings chrome with the mirrors on, HyperFrames' Chrome from the mirror now when it + is not here (HyperFrames has no setting for where it downloads it; + bin/vh new and settings mirror cn do this by themselves) + python3 tools/settings.py env the lines bin/vh and install.sh run to use the mirrors + (export NAME=value; none when the mirror is not cn, or for a + variable already set) + +Kept in $XDG_CONFIG_HOME/ovh/settings.json (~/.config/ovh/settings.json): one file per machine, outside every clone, so a +git pull, a second clone or Studio's settings panel see the same values. Never a key or a token: those stay in the +environment (LOCAL.md names them, never their values). Shape, "version": 1 (keys only added, never renamed; a key +this file does not know is kept as it is when another is written): + {"version": 1, + "mirror": "cn" | "off", absent: auto + "mirror_why": "…", who set it and why, in a sentence (install.sh's probe says what did not answer) + "mirror_at": "YYYY-MM-DD"} +Written whole to a temporary file beside it and moved into place, so a reader never sees half a file. +""" +import datetime, json, os, sys, tempfile +from pathlib import Path + +ROOT = Path(__file__).resolve().parent.parent +MODES = ("cn", "off", "auto") + + +def path(): + return Path(os.environ.get("XDG_CONFIG_HOME") or Path.home() / ".config") / "ovh" / "settings.json" + + +def load(): + """The settings as kept, or {"version": 1} (none yet, or a file that is not a JSON object: said on stderr).""" + p = path() + try: + d = json.loads(p.read_text(encoding="utf-8")) + except FileNotFoundError: + return {"version": 1} + except (OSError, ValueError) as e: + print(f"bin/vh settings: {p} is not readable JSON ({e}); taken as empty", file=sys.stderr) + return {"version": 1} + return d if isinstance(d, dict) else {"version": 1} + + +def save(d): + p = path() + p.parent.mkdir(parents=True, exist_ok=True) + fd, tmp = tempfile.mkstemp(prefix=".settings.", suffix=".tmp", dir=p.parent) + try: + with os.fdopen(fd, "w", encoding="utf-8") as f: + f.write(json.dumps(dict(d, version=1), ensure_ascii=False, indent=2) + "\n") + os.replace(tmp, p) + finally: + if os.path.exists(tmp): + os.unlink(tmp) + + +def mirror(d=None): + m = (d if d is not None else load()).get("mirror") + return m if m in ("cn", "off") else "auto" + + +def mirrors(): + """tools/mirrors.txt → [{kind, variable, official, mirror, who}].""" + rows = [] + for line in (ROOT / "tools" / "mirrors.txt").read_text(encoding="utf-8").splitlines(): + if not line.strip() or line.startswith("#"): + continue + kind, var, official, mir, who = line.split(None, 4) + rows.append({"kind": kind, "variable": None if var == "-" else var, "official": official, "mirror": mir, "who": who}) + return rows + + +def env_lines(environ=os.environ): + """export lines for the mirror variables, when the mirror is cn; a variable already set (by the person) is left.""" + if mirror() != "cn": + return [] + out = [f"export {r['variable']}={r['mirror']}" for r in mirrors() if r["variable"] and not environ.get(r["variable"])] + return out + ["export OVH_MIRROR=cn"] + + +def in_effect(environ=os.environ): + """The mirror variables as this process has them (bin/vh exports them before it runs a tool): {name: value or None}.""" + return {r["variable"]: environ.get(r["variable"]) for r in mirrors() if r["variable"]} + + +def operators(): + """The mirrors' operators by name, each once: "npmmirror.com, TUNA and hf-mirror.com".""" + names = list(dict.fromkeys(r["who"].split(",")[0] for r in mirrors())) + return ", ".join(names[:-1]) + " and " + names[-1] if len(names) > 1 else names[0] + + +def show(d, as_json=False): + m = mirror(d) + if as_json: + print(json.dumps({"version": 1, "tool": "bin/vh settings", "file": str(path()), "settings": d, "mirror": m, + "mirrors": mirrors(), "environment": in_effect()}, ensure_ascii=False, indent=1)) + return + print(f"this machine's settings: {path()}" + ("" if path().exists() else " (not written yet: the defaults)")) + said = {"cn": "the mainland-China mirrors, for every download (tools/mirrors.txt)", + "off": "the official sources; install.sh does not try the mirrors", + "auto": "the official sources; install.sh switches to the mirrors when the official npm registry does not answer"}[m] + print(f" mirror {m}: {said}" + (f" · {d['mirror_why']}" if d.get("mirror_why") else "") + + (f" ({d['mirror_at']})" if d.get("mirror_at") else "")) + print(" bin/vh settings mirror cn|off|auto changes it") + + +def main(argv): + if argv[:1] in (["-h"], ["--help"]): + print(__doc__.strip()); return 0 + if argv == ["env"]: + print("\n".join(env_lines())); return 0 + if not argv or argv == ["--json"]: + show(load(), bool(argv)); return 0 + if argv[0] == "mirror": + if argv[1:] == ["--get"]: + print(mirror()); return 0 + if len(argv) < 2 or argv[1] not in MODES or (len(argv) > 2 and (argv[2] != "--why" or len(argv) != 4)): + print("usage: bin/vh settings mirror cn|off|auto [--why TEXT] (or --get)", file=sys.stderr); return 2 + d = load() + for k in ("mirror", "mirror_why", "mirror_at"): + d.pop(k, None) + if argv[1] != "auto": + d.update(mirror=argv[1], mirror_at=datetime.date.today().isoformat()) + if len(argv) == 4: + d["mirror_why"] = argv[3] + save(d) + if argv[1] == "cn": + print(f"✓ downloads now come from the mainland-China mirrors ({operators()}; tools/mirrors.txt), kept in {path()};" + " bin/vh settings mirror off turns that off") + else: + print(f"✓ downloads come from the official sources{'' if argv[1] == 'auto' else ', and install.sh does not try the mirrors'} (kept in {path()})") + return 0 + print(f"bin/vh settings: unknown {' '.join(argv)} (bin/vh settings -h)", file=sys.stderr) + return 2 + + +if __name__ == "__main__": + sys.exit(main(sys.argv[1:])) diff --git a/tools/test_contract.py b/tools/test_contract.py index d17d0c58..a7759b5c 100644 --- a/tools/test_contract.py +++ b/tools/test_contract.py @@ -22,7 +22,7 @@ SCHEMAS = HERE / "schemas" / "output" ALL = ("status", "activity", "versions", "check", "commands", "desk-data", "edit-list", "edit-build", "assets-list", "artifacts-list", "projects", "error", "cancel", "peaks", "timeline", "history", - "history-save", "history-diff", "history-restore", "gate", "new", "proxy", "thumbs", "words") + "history-save", "history-diff", "history-restore", "gate", "new", "proxy", "thumbs", "words", "settings") class VH: @@ -47,7 +47,7 @@ def fixture(t, sh): """The projects: p (bin/vh new, a film, its render, check, version and delivery records, a ledger, a cast and research folder, a log with each kind of line), z (the desk's fixture with a page and a submission), e (an edit list), and bad things for the failures. → (vh, p, z, e, whether there is a film).""" - vh = VH(sh, {"OVH_PROJECTS": f"{t}/projects"}) + vh = VH(sh, {"OVH_PROJECTS": f"{t}/projects", "XDG_CONFIG_HOME": f"{t}/config"}) # (settings: this run's own) r = vh("new", "math", "ci-contract") if r.returncode: raise SystemExit(f"bin/vh new: exit {r.returncode}: {r.stderr[-400:]}") @@ -113,7 +113,7 @@ def outputs(vh, p, z, e, has_film): ("edit-list", ["edit", "list", e]), ("edit-build", ["edit", "build", e]), ("assets-list", ["assets", "list", p]), ("artifacts-list", ["artifacts", "list", p]), ("artifacts-list", ["artifacts", "list", z]), ("projects", ["projects"]), ("cancel", ["cancel", p]), ("timeline", ["timeline", p, "--resolved"]), ("timeline", ["timeline", z, "--resolved"]), ("timeline", ["timeline", e, "--resolved"]), ("history", ["history", "list", p]), ("history-save", ["history", "save", p]), ("history-diff", ["history", "diff", p]), ("history-restore", ["history", "restore", p, "NOTES.md", "--at", "s1"]), ("gate", ["gate", z, "1", "--page"]), ("new", ["new", "math", "ci-contract-too"]), - ("words", ["words", z]), ("words", ["words", f"{z}/SCRIPT.md", "--all"])] + ("words", ["words", z]), ("words", ["words", f"{z}/SCRIPT.md", "--all"]), ("settings", ["settings"])] if has_film: runs.insert(0, ("check", ["check", f"{p}/out/final.mp4"])) # first: status and the others have its record runs.append(("peaks", ["peaks", f"{p}/out/final.mp4", "--bins", "8"])) From f1a64af6816790baab95adbebb173a559748cd32 Mon Sep 17 00:00:00 2001 From: zhanglinghao Date: Sun, 22 Nov 2026 04:02:07 +0800 Subject: [PATCH 07/19] ci: the mirrors check keeps its temp folder to itself (it took smoke_checks' $t) --- tools/ci.sh | 24 ++++++++++++------------ 1 file changed, 12 insertions(+), 12 deletions(-) diff --git a/tools/ci.sh b/tools/ci.sh index b650e41c..ce9f2361 100755 --- a/tools/ci.sh +++ b/tools/ci.sh @@ -1662,24 +1662,24 @@ PY # the download mirrors: this machine's settings (tools/settings.py) in a file of their own; with "mirror": "cn" bin/vh exports # the variables of tools/mirrors.txt for what it runs (one the person set stays theirs); install.sh tries the official npm # registry first and keeps cn only when it does not answer and the mirror does; --mirror off is kept, and stops the trying - t=$(mktemp -d "${TMPDIR:-/tmp}/vh-mirror.XXXXXX") - a=$(XDG_CONFIG_HOME="$t/c" vh settings mirror --get; XDG_CONFIG_HOME="$t/c" vh settings mirror cn --why "a test" >/dev/null - (unset npm_config_registry HF_ENDPOINT UV_DEFAULT_INDEX ELECTRON_MIRROR; XDG_CONFIG_HOME="$t/c" vh settings --json) | python3 -c 'import json, sys; d = json.load(sys.stdin); e = d["environment"] + mt=$(mktemp -d "${TMPDIR:-/tmp}/vh-mirror.XXXXXX") + a=$(XDG_CONFIG_HOME="$mt/c" vh settings mirror --get; XDG_CONFIG_HOME="$mt/c" vh settings mirror cn --why "a test" >/dev/null + (unset npm_config_registry HF_ENDPOINT UV_DEFAULT_INDEX ELECTRON_MIRROR; XDG_CONFIG_HOME="$mt/c" vh settings --json) | python3 -c 'import json, sys; d = json.load(sys.stdin); e = d["environment"] print(d["mirror"], d["settings"].get("mirror_why"), e["npm_config_registry"], e["HF_ENDPOINT"], e["UV_DEFAULT_INDEX"], e["ELECTRON_MIRROR"])' - XDG_CONFIG_HOME="$t/c" npm_config_registry=https://mine.example vh settings --json | python3 -c 'import json, sys; print(json.load(sys.stdin)["environment"]["npm_config_registry"])' - XDG_CONFIG_HOME="$t/c" vh settings mirror off >/dev/null; (unset npm_config_registry; XDG_CONFIG_HOME="$t/c" vh settings --json) | python3 -c 'import json, sys; d = json.load(sys.stdin); print(d["mirror"], d["environment"]["npm_config_registry"])' - XDG_CONFIG_HOME="$t/c" vh settings mirror nope 2>/dev/null; echo "exit $?") + XDG_CONFIG_HOME="$mt/c" npm_config_registry=https://mine.example vh settings --json | python3 -c 'import json, sys; print(json.load(sys.stdin)["environment"]["npm_config_registry"])' + XDG_CONFIG_HOME="$mt/c" vh settings mirror off >/dev/null; (unset npm_config_registry; XDG_CONFIG_HOME="$mt/c" vh settings --json) | python3 -c 'import json, sys; d = json.load(sys.stdin); print(d["mirror"], d["environment"]["npm_config_registry"])' + XDG_CONFIG_HOME="$mt/c" vh settings mirror nope 2>/dev/null; echo "exit $?") b=$(awk '!/^#/ && NF { if ($4 !~ /^https:\/\//) print "not https: " $1 }' tools/mirrors.txt) - mkdir -p "$t/bin"; printf '#!/bin/sh\ncase "$*" in *registry.npmjs.org*) [ -n "$OFFICIAL" ] && exit 0; exit 28 ;; *) exit 0 ;; esac\n' > "$t/bin/curl"; chmod +x "$t/bin/curl" - sed -n '/^answers() {/,/^eval "\$(python3 tools\/settings.py env)"/p' install.sh > "$t/probe.sh" - probe() { (env PATH="$t/bin:$PATH" XDG_CONFIG_HOME="$t/$1" "${@:2}" bash -c '. "$1"; vh_get() { bin/vh settings mirror --get; }; echo "now $(vh_get) ${npm_config_registry:-official}"' _ "$t/probe.sh" 2>&1 | tail -1); } + mkdir -p "$mt/bin"; printf '#!/bin/sh\ncase "$*" in *registry.npmjs.org*) [ -n "$OFFICIAL" ] && exit 0; exit 28 ;; *) exit 0 ;; esac\n' > "$mt/bin/curl"; chmod +x "$mt/bin/curl" + sed -n '/^answers() {/,/^eval "\$(python3 tools\/settings.py env)"/p' install.sh > "$mt/probe.sh" + probe() { (env PATH="$mt/bin:$PATH" XDG_CONFIG_HOME="$mt/$1" "${@:2}" bash -c '. "$1"; vh_get() { bin/vh settings mirror --get; }; echo "now $(vh_get) ${npm_config_registry:-official}"' _ "$mt/probe.sh" 2>&1 | tail -1); } c=$(MIRROR="" probe p1 env -u npm_config_registry); d=$(probe p2 env -u npm_config_registry OFFICIAL=1); e=$(probe p3 env -u npm_config_registry MIRROR=off); f=$(probe p3 env -u npm_config_registry MIRROR=) if case "$a" in "auto"*"cn a test https://registry.npmmirror.com https://hf-mirror.com https://mirrors.tuna.tsinghua.edu.cn/pypi/web/simple https://npmmirror.com/mirrors/electron/"*"https://mine.example"*"off None"*"exit 2") true ;; *) false ;; esac \ - && [ -z "$b" ] && [ -s "$t/probe.sh" ] && [ "$c" = "now cn https://registry.npmmirror.com" ] && [ "$d" = "now auto official" ] && [ "$e" = "now off official" ] && [ "$f" = "now off official" ] \ - && grep -q '"mirror_why": "install.sh, ' "$t/p1/ovh/settings.json" + && [ -z "$b" ] && [ -s "$mt/probe.sh" ] && [ "$c" = "now cn https://registry.npmmirror.com" ] && [ "$d" = "now auto official" ] && [ "$e" = "now off official" ] && [ "$f" = "now off official" ] \ + && grep -q '"mirror_why": "install.sh, ' "$mt/p1/ovh/settings.json" then ok "mirrors: kept in this machine's settings; bin/vh exports tools/mirrors.txt's variables with cn (a variable the person set stays); install.sh keeps cn only when the official npm registry does not answer and the mirror does; off is kept and stops the trying" else bad "mirrors: $a | $b | probe: $c / $d / $e / $f"; fi - rm -rf "$t" + rm -rf "$mt" # recipes sample: bad usage exits 2 before any render (an unknown id, a sequence, an unknown style); list --json names # the sheet a recipe carries (recipes check, above, holds every sketch to its sheet) vh recipes sample no-such-recipe >/dev/null 2>&1; rc=$?; vh recipes sample launch-15s >/dev/null 2>&1; rc2=$? From f23d43ccc3e3201218a75f5b15cc7ca533805e67 Mon Sep 17 00:00:00 2001 From: zhanglinghao Date: Sun, 22 Nov 2026 04:16:30 +0800 Subject: [PATCH 08/19] install.sh: --mirror checked without an empty case (the wording check reads it); ci: bin/vh exec's into settings.py, known --- install.sh | 2 +- tools/ci.sh | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/install.sh b/install.sh index b824a488..1781e744 100755 --- a/install.sh +++ b/install.sh @@ -43,7 +43,7 @@ while [ $# -gt 0 ]; do case "$1" in --icon) ICON=yes; shift ;; --no-icon) ICON=no; shift ;; -h|--help) sed -n '2,32p' "$0"; exit 0 ;; *) echo "unknown option: $1"; exit 1 ;; esac; done case "$SKILL" in claude|codex|all|none) ;; *) echo "unknown --skill '$SKILL' (claude|codex|all|none)"; exit 1 ;; esac -case "$MIRROR" in ""|cn|off) ;; *) echo "unknown --mirror '$MIRROR' (cn|off)"; exit 1 ;; esac +[ -z "$MIRROR" ] || case "$MIRROR" in cn|off) ;; *) echo "unknown --mirror '$MIRROR' (cn|off)"; exit 1 ;; esac say() { printf '\033[1m→ %s\033[0m\n' "$*"; } NOAPP="${XDG_DATA_HOME:-$HOME/.local/share}/ovh-studio/no-app" # --no-icon once: kept here, so an update leaves OVH Studio out too (--icon clears it) put_icon() { # OVH Studio in the applications, unasked (macOS, a Linux desktop): left alone when it is there and current, never diff --git a/tools/ci.sh b/tools/ci.sh index ce9f2361..62fa23b4 100755 --- a/tools/ci.sh +++ b/tools/ci.sh @@ -9220,7 +9220,7 @@ for cmd, cl in (("render", "node /r/tools/film/render.mjs --browser b p"), ("fra for cmd, cl in (("render", "bash /r/bin/vh qa /p/render/x"), ("qa", "sleep 30"), ("", "bash /r/bin/vh qa"), ("music", "python3 /r/tools/audio/music.py p"), ("style", "bash /r/bin/vh qa x"), ("render", "node /elsewhere/render.mjs")): if C.is_ours(cmd, cl): bad.append(f"is_ours, not: {cmd}, {cl}") -known = {"doctor.py", "textcheck.mjs", "$tool.mjs", "activity.py", "know.py", "status.py", "projects.py", "gate.py", "desk.py", "studio.py", "render.sh", "resolved.py", "lyria.py", "tts.py", "pace.py", "$1.mjs", "commands.py", "artifacts.py", "words.py"} +known = {"doctor.py", "settings.py", "textcheck.mjs", "$tool.mjs", "activity.py", "know.py", "status.py", "projects.py", "gate.py", "desk.py", "studio.py", "render.sh", "resolved.py", "lyria.py", "tts.py", "pace.py", "$1.mjs", "commands.py", "artifacts.py", "words.py"} for m in re.finditer(r'\bexec\s+(?:python3|node)?\s*"?\$(?:ROOT|sw)/([^"\s]+)', open(f"{root}/bin/vh", encoding="utf-8").read()): if m.group(1).rsplit("/", 1)[-1] not in known: bad.append(f"bin/vh exec's into {m.group(1)}: say in tools/cancel.py's EXEC what its pid's command line is (a command not named after its tool), and add it here") From e5865caa45616cf6f94b4a77bf5ad882bbaba6d5 Mon Sep 17 00:00:00 2001 From: zhanglinghao Date: Sun, 22 Nov 2026 04:21:12 +0800 Subject: [PATCH 09/19] settings: a locked update(patch) is the one way to write (re-read, merge, keep the other keys, replace whole); save() goes through it Studio's settings panel and a terminal writing at once both land: the CI check runs two writers of 60 updates each (all 120 land; without the lock, 64 did). --- tools/ci.sh | 15 +++++++++++++ tools/settings.py | 55 ++++++++++++++++++++++++++++++++++++----------- 2 files changed, 58 insertions(+), 12 deletions(-) diff --git a/tools/ci.sh b/tools/ci.sh index 62fa23b4..d7646abe 100755 --- a/tools/ci.sh +++ b/tools/ci.sh @@ -1679,6 +1679,21 @@ print(d["mirror"], d["settings"].get("mirror_why"), e["npm_config_registry"], e[ && grep -q '"mirror_why": "install.sh, ' "$mt/p1/ovh/settings.json" then ok "mirrors: kept in this machine's settings; bin/vh exports tools/mirrors.txt's variables with cn (a variable the person set stays); install.sh keeps cn only when the official npm registry does not answer and the mirror does; off is kept and stops the trying" else bad "mirrors: $a | $b | probe: $c / $d / $e / $f"; fi + # two writers at once (Studio's settings panel and a terminal) both land: settings.update holds a lock, re-reads, merges, + # keeps the keys it was not given + a=$(XDG_CONFIG_HOME="$mt/w" python3 - <<'PY' 2>&1 +import json, os, subprocess, sys +code = "import sys; sys.path.insert(0, 'tools'); import settings\nfor i in range(60): settings.update({f'{sys.argv[1]}{i}': i})\n" +ps = [subprocess.Popen([sys.executable, "-c", code, w]) for w in ("a", "b")] +for q in ps: q.wait() +sys.path.insert(0, "tools"); import settings +settings.update({"mirror": "cn"}); settings.update({"mirror": None, "studio_theme": "dark"}) +d = json.load(open(settings.path())) +print(sum(k[0] in "ab" and k[1:].isdigit() for k in d), d.get("mirror"), d.get("studio_theme"), d.get("version")) +PY +) + if [ "$a" = "120 None dark 1" ]; then ok "settings: two writers at once both land (a lock, a fresh read, a merge); a key given as None goes, the others stay" + else bad "settings with two writers: $a"; fi rm -rf "$mt" # recipes sample: bad usage exits 2 before any render (an unknown id, a sequence, an unknown style); list --json names # the sheet a recipe carries (recipes check, above, holds every sketch to its sheet) diff --git a/tools/settings.py b/tools/settings.py index 58d97aa7..3839c49a 100644 --- a/tools/settings.py +++ b/tools/settings.py @@ -22,9 +22,11 @@ "mirror": "cn" | "off", absent: auto "mirror_why": "…", who set it and why, in a sentence (install.sh's probe says what did not answer) "mirror_at": "YYYY-MM-DD"} -Written whole to a temporary file beside it and moved into place, so a reader never sees half a file. +Every write goes through update(patch): under a lock (settings.json.lock), it reads the file as it is now, sets the keys +it was given (None takes one out), keeps all the others, and writes the whole file to a temporary file moved into place, +so two writers at once (Studio and a terminal) both land and a reader never sees half a file. """ -import datetime, json, os, sys, tempfile +import contextlib, datetime, fcntl, json, os, sys, tempfile from pathlib import Path ROOT = Path(__file__).resolve().parent.parent @@ -48,9 +50,21 @@ def load(): return d if isinstance(d, dict) else {"version": 1} -def save(d): +@contextlib.contextmanager +def locked(): + """The settings file's lock (settings.json.lock beside it, never removed: another process may hold the old one): held + by every write, so Studio and a terminal writing at once both land.""" + p = path(); p.parent.mkdir(parents=True, exist_ok=True) + with open(str(p) + ".lock", "a+") as f: + fcntl.flock(f, fcntl.LOCK_EX) + try: + yield + finally: + fcntl.flock(f, fcntl.LOCK_UN) + + +def _write(d): p = path() - p.parent.mkdir(parents=True, exist_ok=True) fd, tmp = tempfile.mkstemp(prefix=".settings.", suffix=".tmp", dir=p.parent) try: with os.fdopen(fd, "w", encoding="utf-8") as f: @@ -61,6 +75,28 @@ def save(d): os.unlink(tmp) +def update(patch): + """The one way to write: under the lock, read the file as it is now, set each key of patch (None takes a key out), keep + every other key (another writer's, or one this code does not know), and write the whole file to a temp file moved into + place. → the settings as written. Studio's settings panel and bin/vh settings both go through it.""" + with locked(): + d = load() + for k, v in patch.items(): + if k == "version": + continue + if v is None: + d.pop(k, None) + else: + d[k] = v + _write(d) + return d + + +def save(d): + """Write these keys (as update: under the lock, onto what is there now, nothing else taken out).""" + return update(d) + + def mirror(d=None): m = (d if d is not None else load()).get("mirror") return m if m in ("cn", "off") else "auto" @@ -123,14 +159,9 @@ def main(argv): print(mirror()); return 0 if len(argv) < 2 or argv[1] not in MODES or (len(argv) > 2 and (argv[2] != "--why" or len(argv) != 4)): print("usage: bin/vh settings mirror cn|off|auto [--why TEXT] (or --get)", file=sys.stderr); return 2 - d = load() - for k in ("mirror", "mirror_why", "mirror_at"): - d.pop(k, None) - if argv[1] != "auto": - d.update(mirror=argv[1], mirror_at=datetime.date.today().isoformat()) - if len(argv) == 4: - d["mirror_why"] = argv[3] - save(d) + on = argv[1] != "auto" + update({"mirror": argv[1] if on else None, "mirror_at": datetime.date.today().isoformat() if on else None, + "mirror_why": argv[3] if on and len(argv) == 4 else None}) if argv[1] == "cn": print(f"✓ downloads now come from the mainland-China mirrors ({operators()}; tools/mirrors.txt), kept in {path()};" " bin/vh settings mirror off turns that off") From 40f348b57d80b06879686ce4f1d5ffab833e4030 Mon Sep 17 00:00:00 2001 From: zhanglinghao Date: Sun, 22 Nov 2026 04:22:24 +0800 Subject: [PATCH 10/19] settings: set_mirror(mode, why=None) -> dict, what bin/vh settings mirror writes, without the saying (Studio calls it in-process) --- tools/ci.sh | 12 +++++++++++- tools/settings.py | 17 ++++++++++++++--- 2 files changed, 25 insertions(+), 4 deletions(-) diff --git a/tools/ci.sh b/tools/ci.sh index d7646abe..134f306a 100755 --- a/tools/ci.sh +++ b/tools/ci.sh @@ -1690,9 +1690,19 @@ sys.path.insert(0, "tools"); import settings settings.update({"mirror": "cn"}); settings.update({"mirror": None, "studio_theme": "dark"}) d = json.load(open(settings.path())) print(sum(k[0] in "ab" and k[1:].isdigit() for k in d), d.get("mirror"), d.get("studio_theme"), d.get("version")) +# set_mirror writes what the command writes, and leaves a key it does not know where it was +mine = settings.set_mirror("cn", "a test"); subprocess.run([sys.executable, "tools/settings.py", "mirror", "off"], capture_output=True) +cmd_off = {k: v for k, v in json.load(open(settings.path())).items() if k.startswith("mirror")} +settings.set_mirror("off"); fn_off = {k: v for k, v in json.load(open(settings.path())).items() if k.startswith("mirror")} +subprocess.run([sys.executable, "tools/settings.py", "mirror", "cn", "--why", "a test"], capture_output=True) +cmd_cn = {k: v for k, v in json.load(open(settings.path())).items() if k.startswith("mirror")} +last = settings.set_mirror("auto") +print(mine.get("mirror"), mine.get("mirror_why"), cmd_off == fn_off, cmd_cn == {k: v for k, v in mine.items() if k.startswith("mirror")}, + "mirror" in last, last.get("studio_theme"), last.get("a0")) PY ) - if [ "$a" = "120 None dark 1" ]; then ok "settings: two writers at once both land (a lock, a fresh read, a merge); a key given as None goes, the others stay" + if [ "$a" = "120 None dark 1 +cn a test True True False dark 0" ]; then ok "settings: two writers at once both land (a lock, a fresh read, a merge); a key given as None goes, the others stay; set_mirror writes what bin/vh settings mirror writes, other keys untouched" else bad "settings with two writers: $a"; fi rm -rf "$mt" # recipes sample: bad usage exits 2 before any render (an unknown id, a sequence, an unknown style); list --json names diff --git a/tools/settings.py b/tools/settings.py index 3839c49a..3fb2f6a0 100644 --- a/tools/settings.py +++ b/tools/settings.py @@ -22,6 +22,7 @@ "mirror": "cn" | "off", absent: auto "mirror_why": "…", who set it and why, in a sentence (install.sh's probe says what did not answer) "mirror_at": "YYYY-MM-DD"} +In-process (Studio): update(patch: dict) -> dict and set_mirror(mode, why=None) -> dict; load() reads, path() says where. Every write goes through update(patch): under a lock (settings.json.lock), it reads the file as it is now, sets the keys it was given (None takes one out), keeps all the others, and writes the whole file to a temporary file moved into place, so two writers at once (Studio and a terminal) both land and a reader never sees half a file. @@ -92,6 +93,18 @@ def update(patch): return d +def set_mirror(mode, why=None): + """The mirror setting, as bin/vh settings mirror [--why TEXT] writes it, through update(), saying nothing (Studio's + settings panel calls it in-process; main() calls it and does the saying). mode: cn, off or auto (auto takes the keys + out). → the settings as written. It does not fetch HyperFrames' Chrome from the mirror: bin/vh settings mirror cn and + bin/vh new do that (bin/vh settings chrome alone).""" + if mode not in MODES: + raise ValueError(f"mirror: {mode!r} is not one of {', '.join(MODES)}") + on = mode != "auto" + return update({"mirror": mode if on else None, "mirror_at": datetime.date.today().isoformat() if on else None, + "mirror_why": why if on and why else None}) + + def save(d): """Write these keys (as update: under the lock, onto what is there now, nothing else taken out).""" return update(d) @@ -159,9 +172,7 @@ def main(argv): print(mirror()); return 0 if len(argv) < 2 or argv[1] not in MODES or (len(argv) > 2 and (argv[2] != "--why" or len(argv) != 4)): print("usage: bin/vh settings mirror cn|off|auto [--why TEXT] (or --get)", file=sys.stderr); return 2 - on = argv[1] != "auto" - update({"mirror": argv[1] if on else None, "mirror_at": datetime.date.today().isoformat() if on else None, - "mirror_why": argv[3] if on and len(argv) == 4 else None}) + set_mirror(argv[1], argv[3] if len(argv) == 4 else None) if argv[1] == "cn": print(f"✓ downloads now come from the mainland-China mirrors ({operators()}; tools/mirrors.txt), kept in {path()};" " bin/vh settings mirror off turns that off") From e7e347aaa5e7ea28f0980d18fe25471889d17dbe Mon Sep 17 00:00:00 2001 From: zhanglinghao Date: Sun, 22 Nov 2026 04:30:38 +0800 Subject: [PATCH 11/19] Studio's settings page: language, look, the default agent and this machine's defaults in one place MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit A page at #/settings (the rail's foot, Cmd/Ctrl+, and the shell's Settings… menu item): General (language, look, where films are kept), Agent (the default agent, each one's model and effort once it has offered them), Film defaults (the download mirror, editable; LOCAL.md's lines shown only), This computer (what it lacks), About. Studio's own three settings (studio_lang, studio_theme, agent_default) are kept in this machine's settings file through tools/settings.py, so another port, a second window and the terminal see the same; the top bar's buttons stay and change the same settings. GET/POST /api/settings need the run's token and take only these names and values. --- changes/settings-panel.md | 6 + tools/ci-paths.txt | 4 - tools/ci-shards.txt | 1 + tools/ci.sh | 13 +- tools/desk/README.md | 12 ++ tools/desk/server.py | 10 +- tools/desk/settings_api.py | 111 +++++++++++ tools/desk/shell/main.js | 14 +- tools/desk/static/agent.js | 2 +- tools/desk/static/index.html | 2 + tools/desk/static/settings.css | 49 +++++ tools/desk/static/settings.js | 195 +++++++++++++++++++ tools/desk/static/studio.js | 6 +- tools/desk/test_settings.py | 219 ++++++++++++++++++++++ tools/desk/test_wording.py | 2 +- tools/schemas/output/settings.schema.json | 12 +- tools/settings.py | 26 ++- 17 files changed, 668 insertions(+), 16 deletions(-) create mode 100644 changes/settings-panel.md create mode 100644 tools/desk/settings_api.py create mode 100644 tools/desk/static/settings.css create mode 100644 tools/desk/static/settings.js create mode 100644 tools/desk/test_settings.py diff --git a/changes/settings-panel.md b/changes/settings-panel.md new file mode 100644 index 00000000..1a06de7a --- /dev/null +++ b/changes/settings-panel.md @@ -0,0 +1,6 @@ +**Studio 有了设置页:语言、外观、默认的 agent 和这台电脑的默认放在一处** +- Why: Studio 的设置散在几处:语言和主题是顶栏的两个按钮,记在浏览器里,Studio 换一个端口就回到默认;模型和思考深度只在对话里选;这台电脑缺什么是空间页单独一块;LOCAL.md 里的默认要打开文件看。 +- 左栏最下面一个"设置",或者 ⌘,(Studio 自己的窗口里菜单也有"设置…")。分通用、agent、片子的默认、这台电脑、关于几节,一次看一节。 +- 语言、外观、新对话默认用哪个 agent 记在这台电脑的设置文件里(`~/.config/ovh/settings.json`,和下载镜像同一份),换端口、开第二个窗口都还在。顶栏的两个按钮照旧,改的是同一份。 +- 模型和思考深度:agent 在对话里给过选项以后,这里也能选,和对话里选的是同一份。 +- 下载镜像可以在这里换;LOCAL.md 里的默认(努力程度、在哪看每一站、预算等)只显示,没写的说明没写时按什么,要改让 agent 改。 diff --git a/tools/ci-paths.txt b/tools/ci-paths.txt index c66d8296..2f5749e8 100644 --- a/tools/ci-paths.txt +++ b/tools/ci-paths.txt @@ -20,7 +20,6 @@ always static_checks doc_checks readpath_report # change notes, landing, this table and its reader changes/** plumbing_checks studio_checks land_checks -CHANGELOG.md plumbing_checks smoke_checks desk_checks studio_checks cancel_checks assets_checks scout_checks web_checks model3d_checks land_checks tools/changes.py plumbing_checks studio_checks tools/land.py land_checks tools/ci_select.py plumbing_checks @@ -33,12 +32,9 @@ ACKNOWLEDGMENTS.md CONTRIBUTING.md plumbing_checks studio_checks hdri_checks CODE_OF_CONDUCT.md SECURITY.md -CITATION.cff plumbing_checks studio_checks LICENSE hf_checks cases/** gate_checks desk_checks console_checks status_checks contract_checks cancel_checks history_checks know_checks artifacts_checks studio_checks showcase/** smoke_checks timeline_checks decision_checks web_checks model3d_checks -install.sh plumbing_checks smoke_checks desk_checks studio_checks cancel_checks assets_checks scout_checks web_checks model3d_checks -LOCAL.example.md plumbing_checks smoke_checks desk_checks studio_checks cancel_checks assets_checks scout_checks web_checks model3d_checks skills/** smoke_checks cancel_checks assets_checks scout_checks web_checks model3d_checks # tools a few groups reach diff --git a/tools/ci-shards.txt b/tools/ci-shards.txt index 74e454f7..1e958cbf 100644 --- a/tools/ci-shards.txt +++ b/tools/ci-shards.txt @@ -22,6 +22,7 @@ gate_checks 23 desk_checks 14 console_checks 12 agent_checks 16 +settings_page_checks 6 studio_checks 30 looks_checks 17 activity_checks 6 diff --git a/tools/ci.sh b/tools/ci.sh index 134f306a..700ea9f3 100755 --- a/tools/ci.sh +++ b/tools/ci.sh @@ -4625,6 +4625,17 @@ agent_checks() { # the console's agent column (tools/desk/agents.py, acp.py, a rm -rf "$t" } +settings_page_checks() { # Studio's settings page (tools/desk/settings_api.py, static/settings.js, tools/settings.py's Studio + # keys) on a console of its own: its own HOME, temp folder, settings file and LOCAL.md, no window, no agent, no network + local t k m; t=$(mktemp -d "${TMPDIR:-/tmp}/vh-settings.XXXXXX") + python3 tools/desk/test_settings.py "$t" > "$t/out" 2>&1 + while IFS=$'\t' read -r k m; do + case $k in ok) ok "settings page: $m" ;; bad) bad "settings page: $m" ;; esac + done < "$t/out" + grep -qx end "$t/out" || bad "settings page: the test stopped: $(tail -n 3 "$t/out" | tr '\n' ' ')" + rm -rf "$t" +} + concept_checks() { # bin/vh concept: the roulette (seeded by the project's name, what the project has and --not left out) # and the six-then-three board (pillow through uv: the same bytes for the same input) local t p a b c rc rc2 rc3 @@ -12756,7 +12767,7 @@ esac CI_TMP=$(mktemp -d "${TMPDIR:-/tmp}/vh-ci-run.XXXXXX") || exit 2 CI_TMP=${CI_TMP//\/\//\/} # one / (a TMPDIR ending in / gives two) export TMPDIR="$CI_TMP" -CI_OWN_TMP=" gate_checks decision_checks desk_checks console_checks agent_checks studio_checks activity_checks status_checks cancel_checks history_checks artifacts_checks " +CI_OWN_TMP=" gate_checks decision_checks desk_checks console_checks agent_checks settings_page_checks studio_checks activity_checks status_checks cancel_checks history_checks artifacts_checks " export OVH_GATE_STUDIO=0 # a standard film's stop does not look for a running Studio: the checks test the page and their own desks (the check of that rule clears it) unset OVH_PROJECTS # the desks a check starts in the background (bin/vh gate's is in a session of its own) are recorded and stopped when the diff --git a/tools/desk/README.md b/tools/desk/README.md index a50425cf..23514d44 100644 --- a/tools/desk/README.md +++ b/tools/desk/README.md @@ -135,6 +135,7 @@ bin/vh desk agents install # 装那一家的 ACP 适配器 | `GET /api/p/<键>/agent//events?token=…[&after=N]` | 这个对话的事件,SSE:先一个 `hello`(会话的状态、设置、agent 报的能力),然后 `after`(或 `Last-Event-ID`)之后的每一件,再来的边到边推;每 5 秒一行注释保活。要页面的令牌 | | `POST /api/p/<键>/agent/new` | `{kind, personal, model, effort}`:开一个新对话,起好 agent,带着它的设置回来;`model`、`effort` 是人在开新对话的框里挑的(可以不带),agent 报了这个值才设、并记成这一家下次的起点,没报就不管;没装 424,起不来 503。`GET …/agents` 每一家的 `choices` 是新对话会用什么开始:`{model, effort: {value, name, from}, offered}`,`from` 是 picked(你挑过的)、default(Studio 的默认)、dsh(桌面版的推理档)、agent(它自己的),`offered` 是这次运行里它报过的选项(没见过是 null) | | `GET /api/machine` | `{lacks: [{what, state}], platform}`:这台电脑还缺什么(`bin/vh doctor --json` 读出的 FFmpeg、Node、uv、git 没有或太旧,没有画网页用的浏览器,一家 agent 适配器都没装),空间页照它出那一块;不要令牌。什么都不缺时这次运行一直记着;缺东西时,隔一分钟以上再问会重新看一次(人可能已经装上了);doctor 没说清楚时不记,回 `error` | +| `GET /api/settings`、`POST /api/settings {name, value}` | 设置页(`settings_api.py`):要令牌。GET 回 `{version: 1, file, studio, mirror, agents, local, about}`:Studio 自己的三项(`studio_lang`、`studio_theme`、`agent_default`,没设是 `null`)、下载镜像、每种 agent 装没装和新对话从什么模型和思考深度开始(`choices`,同对话列)、LOCAL.md 里人和 agent 都读的那几行(只读,模板的 `{…}` 和注释不算值)、版本。POST 只认这几个名字:`studio_lang`、`studio_theme`、`agent_default`(`null` 回到 Studio 的默认)、`mirror`(`cn`、`off`、`auto`)、`model:`、`effort:`(只认这次运行里这种 agent 在对话里给过的值,记进 `picks.json`);别的名字、值、没有令牌、别的来源一律拒绝,什么都不改。写都经 `tools/settings.py`,从不直接写文件,也不写 LOCAL.md。 | | `POST /api/p/<键>/agent/install` | `{kind}`:人点了「装上」:控制台在后台运行 `bin/vh desk agents install `,回 `{installing: {state, since, took, said}}`(`state`:running、done、no_npm、timeout、cancelled、busy、failed;`limit` 是时限秒数;`said` 是它最后三行话,家目录写成 `~`,页面不显示);`{kind, cancel: true}` 停下正在装的那一次;在装时再点是同一次;`kind` 不是三家之一(包括不是字符串)回 400;`GET …/agents` 的每一家带着同样的 `installing`,页面照它跟到装完 | | `GET /api/space/agents`、`GET /api/space/agent//events`、`POST /api/space/agent/new · install · /say · answer · stop · mode · config` | 空间那一列:和片子里的同名地址一样(要令牌、同源、页面带着空间文件夹的 `pid`),对话是从空间开、还没建片子的那些;`new` 开的对话 agent 在工作台里干活;`events`、`stop` 等也找得到从这里开、已经建好片子的对话。片子建好时事件流里来一条 `{type: notice, code: placed, key, name}`(锁被别人拿着时是 `place_busy`)。`GET /api/space/agents?sid=` 在那段对话已经建好片子时多一个 `went: {id, key}` | | `GET /api/p/<键>/agents` 的 `strays`、`POST /api/p/<键>/agent//bring` | 一支对话列还空着的新片子:可能是它的、从空间开的对话(跑过 `bin/vh new`、没找到自己的片子、这支片子是它开始以后才有的);人点"把它带到这里",那段对话就成了这支片子的(不在 `strays` 里的 409) | @@ -147,6 +148,17 @@ bin/vh desk agents install # 装那一家的 ACP 适配器 起服务时给了项目的,原来的 `/api/data`、`/api/status`、`/api/feedback`、`/p/<路径>` 照旧只对这个项目。这些 JSON 不是命令的 `--json` 输出,没有 schema;字段同样只加不改。 +### 设置页(`#/settings`) + +左栏最下面一个"设置",或者 ⌘,(Linux 上 Ctrl+,;Studio 自己的窗口里,菜单的"设置…"也是它)。一整页:左边分节(通用、agent、片子的默认、这台电脑、关于;账号的那一节先空着,不显示),一次看一节,右边的对话列照常在;"返回"和 Esc 回到打开它之前的那一页。 + +- **存在哪**:能在这一页改的都记在这台电脑自己的设置文件里(`$XDG_CONFIG_HOME/ovh/settings.json`,只经 `tools/settings.py` 读写),换一个端口、开第二个窗口、在终端里都是同一份。语言和外观另在浏览器里留一份,开屏就用它;页面一连上就以设置文件为准,设置文件还没有、浏览器里有的,记进去。顶栏的语言和"主题"两个按钮照旧,改的是同一份。 +- **通用**:语言、外观(三个主题的小样)、片子放在哪(这个 Studio 找片子的文件夹;换地方不在页面上改:页面说让 agent 改、改完重开 Studio,因为 Studio 起来时就按这些文件夹定了自己是哪一个)。 +- **agent**:新对话默认用哪一种(只列装好的;对话列在没有别的记录时从它开始);每种装好的 agent 的模型和思考深度:开过一次对话、agent 给过选项以后才能选(记进 `picks.json`,和对话列里选的是同一份),之前只写现在从什么开始。模式和"不带个人设置"按对话,留在对话里。 +- **片子的默认**:下载镜像(自动、国内镜像、官方源,同 `bin/vh settings mirror`)可以改;LOCAL.md 里人和 agent 都读的几行(默认努力程度、在哪看每一站、素材许可、声音库、谁拍板哪些事、帮手 agent 用的模型、默认预算)只显示,没写的写出没写时按什么,末尾一句"让 agent 帮你改"。这一页从不写 LOCAL.md。 +- **这台电脑**:同空间页的"这台电脑上还缺"(`/api/machine`),什么都不缺时一句"做片子要的都有了";空间页那一块多一个"去设置里看"。 +- **关于**:版本、工作台在哪、更新记录。 + ## 读什么 表格按表头的**开头几个字**认列(中英文都行,英文不分大小写),列的顺序随意,多出来的列不管。 diff --git a/tools/desk/server.py b/tools/desk/server.py index 3860b50c..a2b27768 100644 --- a/tools/desk/server.py +++ b/tools/desk/server.py @@ -87,12 +87,14 @@ import reader # noqa: E402 import review # noqa: E402 (tools/review.py: the gate view, the same markup as the static page) import agents as A # noqa: E402 (the agents the column talks to: one adapter process a kind, a session a conversation) +import settings_api as SA # noqa: E402 (Studio's settings page: GET and POST /api/settings) STATIC = {"ui.css": "text/css; charset=utf-8", "ui.js": "text/javascript; charset=utf-8", "studio.css": "text/css; charset=utf-8", "studio.js": "text/javascript; charset=utf-8", "modules.css": "text/css; charset=utf-8", "modules.js": "text/javascript; charset=utf-8", "core.js": "text/javascript; charset=utf-8", "agent.css": "text/css; charset=utf-8", "agent.js": "text/javascript; charset=utf-8", - "reader.css": "text/css; charset=utf-8", "reader.js": "text/javascript; charset=utf-8"} + "reader.css": "text/css; charset=utf-8", "reader.js": "text/javascript; charset=utf-8", + "settings.css": "text/css; charset=utf-8", "settings.js": "text/javascript; charset=utf-8"} # GET /v//: a project file on a page of its own (Studio's app opens the console's new-page links there) VIEW = {"image": {".png", ".jpg", ".jpeg", ".gif", ".webp", ".svg", ".avif", ".bmp"}, "video": {".mp4", ".mov", ".m4v", ".webm"}, "audio": {".mp3", ".wav", ".m4a", ".aac", ".ogg", ".oga", ".flac", ".opus"}, "page": {".html", ".htm"}, "markdown": {".md", ".markdown"}, @@ -1065,6 +1067,8 @@ def do_GET(self): return self._json({"ok": True} if ok else {"ok": False, "reopen": True}, 200 if ok else 403) if path == "/api/presence": return self._presence() + if path == "/api/settings": # Studio's settings page (settings_api.py): this machine's settings, never a secret + return SA.get(self) if path == "/api/machine": # what this machine still lacks for making films (the space page says it, only when something is missing) return self._json(srv.machine()) m = re.fullmatch(r"/api/p/([^/]+)/(data|stage|status|gate/([A-Za-z0-9_-]{1,24}))", path) @@ -1148,7 +1152,7 @@ def _agents(self, project, key, space=False): strays = [{k: x.get(k) for k in ("id", "kind", "label", "first", "created", "running")} for x in mgr.strays(project, self.server.space)] if strays: extra["strays"] = strays[:3] - return self._json({"agents": [dict(a, signed_in={"authenticated": True, "unauthenticated": False}.get(auth.get(a["kind"])), installing=mgr.install_state(a["kind"]), choices=mgr.choices(a["kind"])) for a in A.catalog()], "sessions": sessions, "pid": pid_of(project), "approval_timeout": A.APPROVAL_TIMEOUT, + return self._json({"agents": [dict(a, signed_in={"authenticated": True, "unauthenticated": False}.get(auth.get(a["kind"])), installing=mgr.install_state(a["kind"]), choices=mgr.choices(a["kind"])) for a in A.catalog()], "sessions": sessions, "pid": pid_of(project), "approval_timeout": A.APPROVAL_TIMEOUT, "default": SA.S.studio()["agent_default"], "lock": {k: lock.get(k) for k in ("kind", "label", "session", "since")} if lock else None, **extra, **({"error": err} if err else {})}) @@ -1423,6 +1427,8 @@ def do_POST(self): return self._error(404, "no such project") elif path == "/api/feedback" and self.server.project: project = self.server.project + elif path == "/api/settings": + return SA.post(self) elif path == "/api/claim": return self._claim() elif path == "/api/open": diff --git a/tools/desk/settings_api.py b/tools/desk/settings_api.py new file mode 100644 index 00000000..d49db044 --- /dev/null +++ b/tools/desk/settings_api.py @@ -0,0 +1,111 @@ +"""Studio's settings page, the server's half: GET /api/settings and POST /api/settings (server.py hands both here). + +What a person can change from the page is kept in this machine's settings file and nowhere else, written through +tools/settings.py (never the file itself): Studio's language and look, the agent a new chat starts with, the download +mirrors. The model and effort a new chat starts with stay where the agent column keeps them (picks.json, agents.py), and +only a value the agent offered is ever set. LOCAL.md's lines that people and agents both read (effort, the way a stop is +looked at, budget, asset licences, sound library, who decides) are shown, never written: the page says to ask the agent. + +Both routes need this run's token. GET answers {version: 1, file, studio, mirror, agents, local, about}; POST takes +{name, value} (studio_lang, studio_theme, agent_default, mirror, model:, effort:) and answers the same as GET. +""" +import os, re, secrets, sys +from pathlib import Path + +HERE = Path(__file__).resolve().parent +WORKSPACE = HERE.parent.parent +sys.path.insert(0, str(HERE.parent)) +import settings as S # noqa: E402 (tools/settings.py: this machine's settings file, its one reader and writer) +import agents as A # noqa: E402 + +# LOCAL.md's lines shown on the page: id → the labels a line may start with (as the tools that read them accept) +LOCAL_LINES = ( + ("effort", r"默认努力程度|努力程度|默认档位|档位|default\s+effort|effort"), + ("review", r"审阅方式|review(?:\s+(?:channel|surface|mode))?"), + ("director", r"默认导演模式|导演模式|director"), + ("subagent", r"子代理模型|subagent\s+model"), + ("budget", r"默认预算|default\s+budget|budget"), + ("assets", r"素材许可|许可策略|assets(?:\s+policy)?"), + ("sound", r"声音库|sound\s+library"), +) + + +def local_md(): + """The harness's LOCAL.md, or the file OVH_LOCAL_MD names (as tools/gatecheck.py reads it).""" + return Path(os.environ.get("OVH_LOCAL_MD") or WORKSPACE / "LOCAL.md") + + +def local_lines(): + """{file, exists, lines: {id: value or None}}: a line still the template's {…}, empty or missing is None.""" + p = local_md() + try: + text = re.sub(r"", "", p.read_text(encoding="utf-8", errors="replace"), flags=re.S) + except OSError: + return {"file": str(p), "exists": False, "lines": {k: None for k, _ in LOCAL_LINES}} + out = {} + for k, labels in LOCAL_LINES: + m = re.search(rf"^[ \t]*[-*]?[ \t]*(?:\*\*)?(?:{labels})(?:\*\*)?[ \t]*[::][ \t]*(.*?)[ \t]*$", text, re.I | re.M) + v = m.group(1).strip().strip("*`").strip() if m else "" + out[k] = None if not v or v.startswith("{") else v[:200] + return {"file": str(p), "exists": True, "lines": out} + + +def version(): + try: + m = re.search(r'^version:\s*"?([^"\n]+)"?', (WORKSPACE / "CITATION.cff").read_text(encoding="utf-8"), re.M) + return m.group(1).strip() if m else None + except OSError: + return None + + +def state(mgr): + d = S.load() + st = S.studio(d) + kinds = A.catalog() + return {"version": 1, "file": str(S.path()), "studio": st, + "mirror": {"mode": S.mirror(d), "why": d.get("mirror_why"), "at": d.get("mirror_at")}, + "agents": {"default": st["agent_default"], + "kinds": [{"kind": a["kind"], "label": a["label"], "installed": a["installed"], "size": a["size"], + "choices": mgr.choices(a["kind"]) if mgr else None} for a in kinds]}, + "local": local_lines(), + "about": {"version": version(), "workspace": str(WORKSPACE)}} + + +def token_ok(handler): + given = handler.headers.get("X-Desk-Token", "").encode("utf-8", "replace") + return secrets.compare_digest(given, handler.server.token.encode("ascii")) + + +def get(handler): + if not token_ok(handler): + return handler._error(403, "missing or wrong desk token: reload the page") + return handler._json(state(handler.server.agents)) + + +def post(handler): + raw = handler._body(4096) + if raw is None: + return + name, value = raw.get("name"), raw.get("value") + if not isinstance(name, str) or not (value is None or isinstance(value, str)): + return handler._error(400, "send {name, value}: value a string, or null for Studio's default") + try: + if name in S.STUDIO: + S.set_studio(name, value) + elif name == "mirror": + if value not in S.MODES: + raise ValueError(f"mirror: one of {', '.join(S.MODES)}") + S.set_mirror(value, "set in Studio's settings") + elif re.fullmatch(r"(model|effort):(\w+)", name): + role, kind = name.split(":") + offered = ((handler.server.agents.choices(kind) if kind in A.ADAPTERS else {}).get("offered") or {}).get(role) or [] + if value not in {x["value"] for x in offered}: # only what this kind of agent offered in a chat this run + raise ValueError(f"{name}: not a value this agent offered") + A.remember(kind, role, value) + else: + raise ValueError(f"{name}: not a setting Studio changes") + except ValueError as e: + return handler._error(400, str(e)) + except OSError as e: + return handler._error(500, f"could not keep it ({type(e).__name__})") + return handler._json(state(handler.server.agents)) diff --git a/tools/desk/shell/main.js b/tools/desk/shell/main.js index 1ca1f30d..2db30a68 100644 --- a/tools/desk/shell/main.js +++ b/tools/desk/shell/main.js @@ -192,10 +192,22 @@ function askClone() { // a click: ask the clone to show Studio; it starts this }); } +function openSettings(_item, focused) { // the menu's 设置… (⌘,): the window in front goes to Studio's settings page, in place + const win = focused && !focused.isDestroyed() ? focused : BrowserWindow.getFocusedWindow(); + if (!win) return; + try { + const u = new URL(win.webContents.getURL()); + if (u.protocol !== "http:" || !["/", "/index.html"].includes(u.pathname)) return; // a reader window: no settings there + u.hash = "/settings"; + win.webContents.loadURL(u.href); // only the part after # changes: the page stays and follows its hash + } catch (e) { /* no page yet */ } +} + function menu() { const m = [ ...(MAC ? [{ label: "OVH Studio", submenu: [ { role: "about", label: T("关于 OVH Studio", "About OVH Studio") }, { type: "separator" }, + { label: T("设置…", "Settings…"), accelerator: "CmdOrCtrl+,", click: openSettings }, { type: "separator" }, { role: "hide", label: T("隐藏 OVH Studio", "Hide OVH Studio") }, { role: "hideOthers", label: T("隐藏其他", "Hide Others") }, { role: "unhide", label: T("全部显示", "Show All") }, { type: "separator" }, { role: "quit", label: T("退出 OVH Studio", "Quit OVH Studio") }] }] : []), @@ -212,7 +224,7 @@ function menu() { { role: "minimize", label: T("最小化", "Minimize") }, { role: "zoom", label: T("缩放", "Zoom") }, { role: "close", label: T("关闭窗口", "Close Window") }, // ⌘W / Ctrl+W ...(MAC ? [{ type: "separator" }, { role: "front", label: T("前置全部窗口", "Bring All to Front") }] : [])] }, - ...(MAC ? [] : [{ label: T("文件", "File"), submenu: [{ role: "quit", label: T("退出", "Quit") }] }]), + ...(MAC ? [] : [{ label: T("文件", "File"), submenu: [{ label: T("设置…", "Settings…"), accelerator: "CmdOrCtrl+,", click: openSettings }, { type: "separator" }, { role: "quit", label: T("退出", "Quit") }] }]), ]; Menu.setApplicationMenu(Menu.buildFromTemplate(m)); } diff --git a/tools/desk/static/agent.js b/tools/desk/static/agent.js index 07920211..ed23f251 100644 --- a/tools/desk/static/agent.js +++ b/tools/desk/static/agent.js @@ -205,7 +205,7 @@ const AGENT = (() => { if (typeof spacePlaced === "function") spacePlaced(INFO.went.key); } const saved = store_.get(`desk:agent:${KEYP}`) || {}; - KIND = KIND || saved.kind || (kinds().find((a) => a.installed) || kinds()[0] || {}).kind || "claude"; + KIND = KIND || saved.kind || (kinds().find((a) => a.installed && a.kind === INFO.default) || kinds().find((a) => a.installed) || kinds()[0] || {}).kind || "claude"; // INFO.default: the settings page's 新对话默认用 return true; } let INSTWATCH = 0; diff --git a/tools/desk/static/index.html b/tools/desk/static/index.html index f531fc49..a8cad962 100644 --- a/tools/desk/static/index.html +++ b/tools/desk/static/index.html @@ -11,6 +11,7 @@ + @@ -55,6 +56,7 @@ + diff --git a/tools/desk/static/settings.css b/tools/desk/static/settings.css new file mode 100644 index 00000000..9b69b4c4 --- /dev/null +++ b/tools/desk/static/settings.css @@ -0,0 +1,49 @@ +/* Studio's settings page (settings.js): its sections on the left, one section at a time; the theme's own values only. */ +.module.settings{max-width:980px} +.settings .mh{justify-content:space-between;align-items:center} +.st-wrap{display:grid;grid-template-columns:180px minmax(0,1fr);gap:28px;align-items:start} +.st-nav{display:flex;flex-direction:column;gap:2px;position:sticky;top:0} +.st-nav a{padding:7px 12px;border-radius:var(--r-ctl);color:var(--ink-2);text-decoration:none;font-size:var(--fs-small);border-left:2px solid transparent} +.st-nav a:hover{color:var(--ink);background:var(--panel-2)} +.st-nav a[aria-current=page]{color:var(--ink-hi);background:var(--panel-2);border-left-color:var(--you)} +.st-body{min-width:0;max-width:640px} +.st-row{display:grid;grid-template-columns:170px minmax(0,1fr);gap:8px 20px;padding:14px 0;border-top:1px solid var(--rule)} +.st-row:first-child{border-top:0;padding-top:2px} +.st-k{color:var(--ink-2);font-size:var(--fs-small);padding-top:6px} +.st-v{min-width:0;font-size:var(--fs-small);color:var(--ink)} +.st-v p{margin:6px 0 0} +.st-v code{font:var(--fs-label)/1.6 var(--mono);color:var(--ink-2);word-break:break-all} +.st-note{color:var(--ink-3);font-size:var(--fs-label);line-height:1.6;margin:8px 0 0} +.st-dim{color:var(--ink-3)} +.st-lead{color:var(--ink-2);font-size:var(--fs-small);margin:0 0 10px;max-width:36em} +.st-foot{padding-top:12px;border-top:1px solid var(--rule)} +.st-h{margin:24px 0 2px;font:500 var(--fs-small)/1.4 var(--sans);color:var(--ink-hi)} +.st-list,.st-paths{margin:8px 0 0;padding:0;list-style:none;display:grid;gap:4px} +.st-seg{display:inline-flex;flex-wrap:wrap;gap:6px} +.st-seg button{min-height:32px;padding:0 14px;border:1px solid var(--rule-2);border-radius:var(--r-ctl);background:transparent;color:var(--ink-2);cursor:pointer;font-size:var(--fs-small)} +.st-seg button:hover{color:var(--ink)} +.st-seg button[aria-checked=true]{color:var(--ink-hi);border-color:var(--you);background:var(--you-soft)} +.st-v select{background:var(--panel-2);border:1px solid var(--rule-2);color:var(--ink);padding:6px 8px;border-radius:var(--r-ctl);font-size:var(--fs-small);max-width:100%} +.st-looks{display:flex;flex-wrap:wrap;gap:10px} +.st-look{display:flex;flex-direction:column;gap:7px;padding:8px;border:1px solid var(--rule-2);border-radius:var(--r-card);background:transparent;cursor:pointer;color:var(--ink-2);font-size:var(--fs-label);width:118px} +.st-look[aria-checked=true]{border-color:var(--you);color:var(--ink-hi)} +.st-look i{display:block;height:58px;border-radius:calc(var(--r-card) - 2px);padding:10px;position:relative;overflow:hidden} +.st-look b{display:block;height:5px;margin:0 0 6px;border-radius:2px} +.st-look b:nth-child(1){width:60%}.st-look b:nth-child(2){width:85%;opacity:.5}.st-look b:nth-child(3){width:34%;height:9px;margin-top:9px} +/* each look's own colours (ui.css holds them on :root only, so the three swatches say them here) */ +.st-look-darkfield i{background:#111111;border:1px solid rgba(255,255,255,.08)} +.st-look-darkfield b{background:#ebe8e2}.st-look-darkfield b:nth-child(3){background:#5ec9dc} +.st-look-prism i{background:radial-gradient(120% 90% at 20% 0,rgba(167,139,250,.28),transparent 60%),#04060b;border:1px solid rgba(255,255,255,.085)} +.st-look-prism b{background:#e9eef7}.st-look-prism b:nth-child(3){background:#4fd1e8;box-shadow:0 0 10px -2px rgba(79,209,232,.7)} +.st-look-bridge i{background:linear-gradient(rgba(150,178,200,.06) 1px,transparent 1px) 0 0/10px 10px,linear-gradient(90deg,rgba(150,178,200,.06) 1px,transparent 1px) 0 0/10px 10px,#06080a;border:1px solid rgba(150,178,200,.42);border-radius:0} +.st-look-bridge b{background:#dde5ec;border-radius:0}.st-look-bridge b:nth-child(3){background:#3dd6f0} +.lacks-more{display:inline-block;margin-top:6px;color:var(--you);font-size:var(--fs-label);text-decoration:none} +.lacks-more:hover{text-decoration:underline} +.settings .lacks{margin:0} +@media (max-width:900px){ + .st-wrap{grid-template-columns:1fr;gap:12px} + .st-nav{flex-direction:row;flex-wrap:wrap;position:static} + .st-nav a{border-left:0;border-bottom:2px solid transparent} + .st-nav a[aria-current=page]{border-bottom-color:var(--you)} + .st-row{grid-template-columns:1fr;gap:4px} +} diff --git a/tools/desk/static/settings.js b/tools/desk/static/settings.js new file mode 100644 index 00000000..6cf9e40a --- /dev/null +++ b/tools/desk/static/settings.js @@ -0,0 +1,195 @@ +/* Studio's settings page, #/settings[/
] (tools/desk/settings_api.py serves it; tools/desk/README.md "设置"). + One page with its sections on the left and one section at a time. What a person changes is kept in this machine's + settings file (tools/settings.py), so a second window, another port or the terminal see the same; the language and the + look are also kept in this browser, so the first paint already has them. The top bar's language and look buttons stay: + they change the same two settings (the clicks are heard here). Loaded before studio.js; it uses studio.js's and + core.js's names only when it runs. */ +const SETTINGS = (() => { + const W = { + zh: { + title: "设置", back: "返回", rail: "设置", rail_tip: "设置(⌘,)", + s_general: "通用", s_agent: "agent", s_films: "片子的默认", s_machine: "这台电脑", s_about: "关于", s_account: "账号", + lang: "语言", look: "外观", th_darkfield: "暗场", th_prism: "棱镜", th_bridge: "舰桥", + where: "片子放在哪", where_how: "想换个地方,让 agent 帮你改,改完重新打开 Studio。", where_none: "还没读到片子放在哪。", + ag_default: "新对话默认用", ag_not: "还没装", ag_not_how: "在右边的对话里点「装上」。", ag_model: "模型", ag_effort: "思考深度", + ag_from_default: "Studio 的默认", ag_from_agent: "{a} 自己的默认", ag_from_dsh: "DeepSeek Harness 桌面版里的设置", + ag_later: "开一次对话以后,这里能改。", ag_none: "这台电脑上还没有装好的 agent。", + f_lead: "这些是这台电脑给每支片子的默认。片子自己写了的,以片子的为准。", + f_effort: "默认努力程度", f_review: "在哪看每一站", f_assets: "素材许可", f_sound: "声音库", f_director: "谁拍板哪些事", + f_subagent: "帮手 agent 用的模型", f_budget: "默认预算", f_unset: "没写", f_unset_effort: "没写:按标准", f_unset_review: "没写:按努力程度", + f_unset_assets: "没写:严格", f_unset_sound: "没写:用 ~/.ovh/sound", f_unset_budget: "没写:不调收费的接口", + f_how: "让 agent 帮你改。", + mirror: "下载镜像", m_auto: "自动", m_cn: "国内镜像", m_off: "官方源", + m_auto_d: "从官方源下载;安装时官方源连不上,会自己换成国内镜像。", m_cn_d: "以后的下载都走国内镜像。", m_off_d: "只从官方源下载。", + m_set: "({d} 设的)", mc_rest: "别的做片子要的都有了。", + v_quick: "快速", v_standard: "标准", v_studio: "精品", v_chat: "对话里", v_page: "网页", v_desk: "Studio", v_strict: "严格", v_record: "记下就能用", mc_lead: "做片子要的", mc_ok: "做片子要的都有了。", mc_wait: "正在看这台电脑…", mc_fail: "这次没看成,过一会儿再打开这一页。", + ab_version: "版本", ab_where: "工作台在哪", ab_news: "更新了什么", + saved: "记下了", see: "去设置里看", failed: "没记下:{x}", nokey: "这一页现在只能看:在 Studio 自己的窗口里才能改。", + }, + en: { + title: "Settings", back: "Back", rail: "Settings", rail_tip: "Settings (⌘,)", + s_general: "General", s_agent: "Agent", s_films: "Film defaults", s_machine: "This computer", s_about: "About", s_account: "Account", + lang: "Language", look: "Look", th_darkfield: "Darkfield", th_prism: "Prism", th_bridge: "Bridge", + where: "Where films are kept", where_how: "To keep them somewhere else, ask your agent to change it, then reopen Studio.", where_none: "Not known yet.", + ag_default: "New chats start with", ag_not: "Not set up", ag_not_how: "Press “Set it up” in the chat on the right.", ag_model: "Model", ag_effort: "Effort", + ag_from_default: "Studio's default", ag_from_agent: "{a}'s own default", ag_from_dsh: "as set in the DeepSeek Harness app", + ag_later: "Start one chat and you can change it here.", ag_none: "No agent is set up on this computer yet.", + f_lead: "This computer's defaults for every film. What a film says for itself comes first.", + f_effort: "Default effort", f_review: "Where you look at each stop", f_assets: "Asset licences", f_sound: "Sound library", f_director: "Who decides what", + f_subagent: "Model for helper agents", f_budget: "Default budget", f_unset: "Not set", f_unset_effort: "Not set: standard", f_unset_review: "Not set: by effort", + f_unset_assets: "Not set: strict", f_unset_sound: "Not set: ~/.ovh/sound", f_unset_budget: "Not set: no paid services are called", + f_how: "Ask your agent to change it.", + mirror: "Download mirror", m_auto: "Automatic", m_cn: "Mainland China mirrors", m_off: "Official sources", + m_auto_d: "Downloads come from the official sources; if they don't answer during install, it switches to the mirrors by itself.", m_cn_d: "Every later download comes from the mainland China mirrors.", m_off_d: "Downloads only come from the official sources.", + m_set: "(set {d})", mc_rest: "Everything else films need is here.", + v_quick: "Quick", v_standard: "Standard", v_studio: "Studio", v_chat: "In the chat", v_page: "A web page", v_desk: "Studio", v_strict: "Strict", v_record: "Allowed if recorded", mc_lead: "Needed for films", mc_ok: "Everything films need is here.", mc_wait: "Looking at this computer…", mc_fail: "Couldn't look this time; open this page again in a moment.", + ab_version: "Version", ab_where: "Where the workbench is", ab_news: "What's new", + saved: "Saved", see: "See it in Settings", failed: "Not saved: {x}", nokey: "This page can only look: change settings in Studio's own window.", + }, + }; + const w = (k, v) => String((W[LANG] || W.zh)[k] != null ? (W[LANG] || W.zh)[k] : W.en[k] != null ? W.en[k] : k).replace(/\{(\w+)\}/g, (_, x) => (v && v[x] != null ? v[x] : "")); + // the sections, in order; account waits for accounts (not shown) + const SECTIONS = [{ id: "general" }, { id: "agent" }, { id: "films" }, { id: "machine" }, { id: "about" }, { id: "account", hidden: true }]; + const THEMES = ["darkfield", "prism", "bridge"]; + let ST = null, BACK = "#/", SEC = "general"; + + async function call(method, body) { + try { + const r = await fetch("/api/settings", { method, cache: "no-store", headers: Object.assign({ "X-Desk-Token": TOKEN }, body ? { "Content-Type": "application/json" } : {}), body: body ? JSON.stringify(body) : undefined }); + const j = await r.json().catch(() => null); + return { ok: r.ok, status: r.status, data: j }; + } catch (e) { return { ok: false, status: 0, data: null }; } + } + async function load() { const r = await call("GET"); if (r.ok && r.data) ST = r.data; return r; } + async function save(name, value, quiet) { + const r = await call("POST", { name, value }); + if (r.ok && r.data) { ST = r.data; if (!quiet) toast(w("saved")); } + else if (!quiet) toast(r.status === 403 ? w("nokey") : w("failed", { x: (r.data && r.data.error) || r.status })); + return r.ok; + } + + /* the rail's entry, at its foot (studio.js's renderRail adds it) */ + const GEAR = ''; + function railItem(proj) { + const here = parse().view === "settings"; + return `${proj ? "" : ''}
${esc(w("rail"))}`; + } + + /* the page */ + async function show(sec) { + if (parse().view !== "settings") return; + SEC = SECTIONS.some((s) => s.id === sec && !s.hidden) ? sec : "general"; + leaveProject(); D = null; PKEY = ""; MOD = ""; GV = null; + crumbs([{ text: t("m_space"), href: "#/" }, { text: w("title") }]); renderFlow(); renderRail(); spaceColumn(); + if (!ST) $("#stage").innerHTML = `

…

`; + const r = await load(); + if (parse().view !== "settings") return; + if (!ST) { $("#stage").innerHTML = `

${esc(r.status === 403 ? w("nokey") : t("noServer"))}

`; return; } + if (SEC === "general" && !LIST) await listing(); + if (parse().view !== "settings") return; + draw(); + if (SEC === "machine") machine().then(() => { if (parse().view === "settings" && SEC === "machine") draw(); }); + } + function draw() { + const area = $("#stage"), y = area.scrollTop; + const nav = SECTIONS.filter((s) => !s.hidden).map((s) => `${esc(w("s_" + s.id))}`).join(""); + area.innerHTML = `

${esc(w("title"))}

${esc(w("back"))}
+
${({ general, agent, films, machine: machineSec, about })[SEC === "machine" ? "machine" : SEC]()}
`; + area.scrollTop = y; + } + const row = (label, body, note) => `
${esc(label)}
${body}${note ? `

${note}

` : ""}
`; + const seg = (name, opts, cur) => `
${opts.map(([v, label]) => ``).join("")}
`; + + function general() { + const theme = document.documentElement.getAttribute("data-theme") || "darkfield"; + const looks = `
${THEMES.map((x) => ``).join("")}
`; + const roots = ((LIST && LIST.roots) || []).map((x) => x.path || x).filter(Boolean); + const where = roots.length ? `
    ${roots.map((p) => `
  • ${esc(p)}
  • `).join("")}
` : `

${esc(w("where_none"))}

`; + return row(w("lang"), seg("studio_lang", [["zh", "中文"], ["en", "English"]], LANG)) + + row(w("look"), looks) + + row(w("where"), where, esc(w("where_how"))); + } + function agent() { + const kinds = (ST.agents && ST.agents.kinds) || [], got = kinds.filter((k) => k.installed); + if (!got.length) return row(w("ag_default"), `

${esc(w("ag_none"))}

`, esc(w("ag_not_how"))); + const def = (got.find((k) => k.kind === ST.agents.default) || got[0]).kind; + const pick = got.length > 1 ? seg("agent_default", got.map((k) => [k.kind, k.label]), def) : `

${esc(got[0].label)}

`; + const missing = kinds.filter((k) => !k.installed).map((k) => `
  • ${esc(k.label)} · ${esc(w("ag_not"))}
  • `).join(""); + let out = row(w("ag_default"), pick + (missing ? `
      ${missing}
    ` : ""), missing ? esc(w("ag_not_how")) : ""); + for (const k of got) { + const ch = k.choices || {}, offered = ch.offered || {}; + const one = (role) => { + const c = ch[role] || {}, opts = offered[role] || []; + if (opts.length) return ``; + const from = c.from === "default" ? w("ag_from_default") : c.from === "dsh" ? w("ag_from_dsh") : c.from === "agent" || !c.name ? w("ag_from_agent", { a: k.label }) : ""; + return `

    ${esc(c.name || "")}${c.name && from ? " · " : ""}${esc(from)}

    `; + }; + const later = !(offered.model || offered.effort); + out += `

    ${esc(k.label)}

    ` + row(w("ag_model"), one("model")) + row(w("ag_effort"), one("effort"), later ? esc(w("ag_later")) : ""); + } + return out; + } + function films() { + const L = (ST.local && ST.local.lines) || {}, M = ST.mirror || {}; + const said = (k) => { // a known value in the page's words (LOCAL.md's own words for the way a stop is looked at, too) + const m = String(L[k]).match(/^(quick|standard|studio|对话|chat|审阅页|page|审阅台|desk|strict|record)(?![A-Za-z])/i); + return m && ["effort", "review", "assets"].includes(k) ? w("v_" + m[1].toLowerCase().replace(/^对话$/, "chat").replace(/^审阅页$/, "page").replace(/^审阅台$/, "desk")) : L[k]; + }; + const val = (k) => (L[k] ? `

    ${esc(said(k))}

    ` : `

    ${esc(w(W.zh["f_unset_" + k] ? "f_unset_" + k : "f_unset"))}

    `); + const mirror = seg("mirror", [["auto", w("m_auto")], ["cn", w("m_cn")], ["off", w("m_off")]], M.mode || "auto"); + const when = M.at ? ` ${esc(w("m_set", { d: M.at }))}` : ""; + return `

    ${esc(w("f_lead"))}

    ` + + row(w("mirror"), mirror, esc(w("m_" + (M.mode || "auto") + "_d")) + when) + + ["effort", "review", "assets", "sound", "director", "subagent", "budget"].map((k) => row(w("f_" + k), val(k))).join("") + + `

    ${esc(w("f_how"))}

    `; + } + function machineSec() { + if (!MACHINE) return `

    ${esc(w("mc_wait"))}

    `; + if (MACHINE.error) return `

    ${esc(w("mc_fail"))}

    `; + return (MACHINE.lacks || []).length ? lacksHtml() + `

    ${esc(w("mc_rest"))}

    ` : row(w("mc_lead"), `

    ${esc(w("mc_ok"))}

    `); + } + function about() { + const a = ST.about || {}; + return row(w("ab_version"), `

    ${esc(a.version || "")}

    `) + + row(w("ab_where"), `${esc(a.workspace || "")}`) + + row(w("ab_news"), `CHANGELOG`); + } + + /* the page's clicks; the top bar's language and look buttons (their own handlers ran first: the new value is in place) */ + document.addEventListener("click", async (e) => { + if (e.target.closest("#lang")) { save("studio_lang", LANG, true); if (parse().view === "settings") draw(); return; } + const th = e.target.closest("[data-theme-set]"); + if (th) { save("studio_theme", th.dataset.themeSet, true); if (parse().view === "settings" && SEC === "general") draw(); return; } + const b = e.target.closest(".settings [data-set]"); + if (!b || b.tagName === "SELECT") return; + const name = b.dataset.set, v = b.dataset.val; + if (name === "studio_lang") { if (v !== LANG) $("#lang").click(); return; } + if (await save(name, v) && parse().view === "settings") draw(); + }); + document.addEventListener("change", async (e) => { + const s = e.target.closest(".settings select[data-set]"); + if (s && await save(s.dataset.set, s.value) && parse().view === "settings") draw(); + }); + document.addEventListener("keydown", (e) => { // ⌘, (Ctrl+, elsewhere): in Studio's own window the menu item does this + if (e.key === "," && (e.metaKey || e.ctrlKey) && !e.altKey && !e.shiftKey) { e.preventDefault(); go("#/settings"); } + else if (e.key === "Escape" && parse().view === "settings" && !typing()) go(BACK); + }); + window.addEventListener("hashchange", (e) => { // where Back goes: the page this one was opened from + const from = new URL(e.oldURL).hash || "#/"; + if (!from.startsWith("#/settings") && location.hash.startsWith("#/settings")) BACK = from; + }); + + /* at start: what is kept for this machine wins over this browser's copy; a copy with nothing kept yet is kept */ + async function sync(tries) { + const r = await load(); + if (!r.ok) { if (r.status === 403 && tries < 10) setTimeout(() => sync(tries + 1), 1000); return; } + const st = ST.studio || {}, theme = document.documentElement.getAttribute("data-theme"); + if (st.studio_theme && st.studio_theme !== theme) OVH.theme(st.studio_theme); + else if (!st.studio_theme && theme && theme !== "darkfield") save("studio_theme", theme, true); + if (st.studio_lang && st.studio_lang !== LANG) $("#lang").click(); + else if (!st.studio_lang && LANG !== "zh") save("studio_lang", LANG, true); + } + setTimeout(() => sync(0), 300); + + return { show, railItem, word: w, words: W }; +})(); diff --git a/tools/desk/static/studio.js b/tools/desk/static/studio.js index 8b692059..5314e754 100644 --- a/tools/desk/static/studio.js +++ b/tools/desk/static/studio.js @@ -63,6 +63,7 @@ function parse() { const h = decodeURIComponent(location.hash.replace(/^#/, "")); if (!h) return HOME ? { view: "project", key: HOME } : { view: "home" }; if (h === "/") return { view: "home" }; + if (/^\/settings(\/|$)/.test(h)) return { view: "settings", sec: h.slice(10) }; // the settings page (settings.js) const m = h.match(/^\/p\/([^/]+)(?:\/(.*))?$/); if (m) { const rest = m[2] || "", g = rest.match(/^gate\/([A-Za-z0-9_-]{1,24})$/); @@ -80,6 +81,7 @@ async function route() { const r = parse(); closeSearch(); if (r.view === "home") return showHome(); + if (r.view === "settings") return SETTINGS.show(r.sec); return showProject(r); } window.addEventListener("hashchange", route); @@ -107,7 +109,7 @@ function renderRail() { // the space and a new film; a film's modules only whi return `${svg(m)}${esc(t("m_" + m))}${dot}`; }; const fresh = `${svg("new")}${esc(t("m_new"))}`; // the space's column, a fresh sentence - $("#rail").innerHTML = item("space") + fresh + (proj ? "
    " + ["idea", "outline", "board", "sound", "cut", "ship"].map(item).join("") + '
    ' + ["assets", "ledger"].map(item).join("") : ""); + $("#rail").innerHTML = item("space") + fresh + (proj ? "
    " + ["idea", "outline", "board", "sound", "cut", "ship"].map(item).join("") + '
    ' + ["assets", "ledger"].map(item).join("") : "") + SETTINGS.railItem(proj); } $("#rail").addEventListener("click", (e) => { if (e.target.closest("[data-new]")) setTimeout(() => AGENT.fresh(), parse().view === "home" ? 0 : 300); }); // 新建: the space's column, a sentence for a new film $("#flow").addEventListener("click", (e) => { const b = e.target.closest("[data-go-mod]"); if (b && PKEY) go(projHash(PKEY, b.dataset.goMod)); }); @@ -215,7 +217,7 @@ async function machine() { // asked once a page; again (a minute later at most function lacksHtml() { const L = (MACHINE && MACHINE.lacks) || []; if (!L.length) return ""; - return ``; + return ``; } function copyText(s) { return new Promise((ok) => { diff --git a/tools/desk/test_settings.py b/tools/desk/test_settings.py new file mode 100644 index 00000000..67eb0dd4 --- /dev/null +++ b/tools/desk/test_settings.py @@ -0,0 +1,219 @@ +"""Studio's settings page (tools/ci.sh settings_page_checks): a console of its own on a made-up machine (its own HOME, temp +folder, settings file, LOCAL.md, no window, no agent, no network), asked through its two addresses as the page asks them, +and the page's words. One line a check on stdout: "ok\t" or "bad\t: ", then "end". + + python3 tools/desk/test_settings.py +""" +import http.client, json, os, re, signal, subprocess, sys, time, urllib.request +from pathlib import Path + +HERE = Path(__file__).resolve().parent +ROOT = HERE.parent.parent +if len(sys.argv) < 2 or sys.argv[1].startswith("-"): + sys.exit("usage: python3 tools/desk/test_settings.py ") +T = Path(sys.argv[1]).resolve() +for d in ("tmp", "home", "config", "cache", "data", "films", "agents", "profiles"): + (T / d).mkdir(parents=True, exist_ok=True) +CONF = T / "config" / "ovh" / "settings.json" +LOCAL = T / "LOCAL.md" +ENV = dict(os.environ, TMPDIR=str(T / "tmp"), HOME=str(T / "home"), XDG_CONFIG_HOME=str(T / "config"), XDG_CACHE_HOME=str(T / "cache"), + XDG_DATA_HOME=str(T / "data"), OVH_LOCAL_MD=str(LOCAL), OVH_AGENTS_DIR=str(T / "agents"), OVH_STUDIO_PROFILES=str(T / "profiles"), + OVH_STUDIO_SHELL="none", OVH_STUDIO_BROWSER="none", OVH_GATE_STUDIO="0", BROWSER="/usr/bin/false") +ENV.pop("OVH_PROJECTS", None) + + +def say(ok, what, why=""): + print(("ok" if ok else "bad") + "\t" + what + ("" if ok else f": {why}"), flush=True) + + +def check(what, fn): + try: + r = fn() + say(r is None, what, "" if r is None else str(r)) + except Exception as e: + say(False, what, f"{type(e).__name__}: {e}") + + +def conf(): + try: + return json.loads(CONF.read_text(encoding="utf-8")) + except (OSError, ValueError): + return {} + + +# ---------- the module, without a console ---------- + +def module_check(): + sys.path.insert(0, str(ROOT / "tools")) + keep = dict(os.environ) + os.environ["XDG_CONFIG_HOME"] = str(T / "config-module") + try: + import settings as S + S.save({"version": 1, "studio_theme": "neon", "studio_lang": "en", "someone_elses": [1]}) + bad = [] + if S.studio() != {"studio_lang": "en", "studio_theme": None, "agent_default": None}: + bad.append(f"a value it does not know read as a setting: {S.studio()}") + for name, value in (("studio_theme", "neon"), ("api_key", "x"), ("mirror", "cn")): + try: + S.set_studio(name, value) + bad.append(f"set_studio took {name}={value}") + except ValueError: + pass + S.set_studio("agent_default", "codex") + S.set_studio("studio_lang", None) + d = S.load() + if d.get("agent_default") != "codex" or "studio_lang" in d or d.get("someone_elses") != [1]: + bad.append(f"after two writes: {d}") + return "; ".join(bad) or None + finally: + os.environ.clear(); os.environ.update(keep) + + +# ---------- a console ---------- + +class Desk: + def __init__(self): + self.log = T / "desk.log" + self.proc = subprocess.Popen([sys.executable, str(HERE / "fixtures" / "with_tty.py"), sys.executable, str(HERE / "desk.py"), + "--root", str(T / "films"), "--port", "0", "--print-address"], + stdout=open(self.log, "w"), stderr=subprocess.STDOUT, env=ENV, cwd=str(T)) + for _ in range(150): + m = re.search(r"http://127\.0\.0\.1:(\d+)/\?c=([A-Za-z0-9_-]+)", self.log.read_text()) + if m: + break + time.sleep(0.1) + else: + raise RuntimeError("no address: " + self.log.read_text()[-400:]) + self.port = int(m.group(1)) + self.page = urllib.request.urlopen(f"http://127.0.0.1:{self.port}/?c={m.group(2)}").read().decode() + st, d = self.req("POST", "/api/claim", {"c": m.group(2)}, token=False) + self.token = d.get("token", "") + + def req(self, method, path, body=None, token=True, origin=None): + c = http.client.HTTPConnection("127.0.0.1", self.port, timeout=15) + h = {"Content-Type": "application/json"} if body is not None else {} + if token: + h["X-Desk-Token"] = self.token if token is True else token + if origin: + h["Origin"] = origin + c.request(method, path, body=json.dumps(body).encode() if body is not None else None, headers=h) + r = c.getresponse() + b = r.read() + try: + return r.status, json.loads(b) + except ValueError: + return r.status, b + + def stop(self): + self.proc.send_signal(signal.SIGTERM) + try: + self.proc.wait(20) + except subprocess.TimeoutExpired: + self.proc.kill() + + +def run(): + text = (ROOT / "LOCAL.example.md").read_text(encoding="utf-8") + text = re.sub(r"^- 默认努力程度:.*$", "- 默认努力程度:quick", text, flags=re.M) + text = re.sub(r"^- 默认预算:.*$", "- 默认预算:每支片子 5 美元 ", text, flags=re.M) + LOCAL.write_text(text, encoding="utf-8") + CONF.parent.mkdir(parents=True, exist_ok=True) + CONF.write_text(json.dumps({"version": 1, "mirror": "cn", "mirror_at": "2026-11-01", "kept_for_later": {"a": 1}}), encoding="utf-8") + d = Desk() + try: + def page(): + bad = [f for f in ("settings.js", "settings.css") if f'/static/{f}' not in d.page] + for f in ("settings.js", "settings.css"): + st, _ = d.req("GET", f"/static/{f}", token=False) + if st != 200: + bad.append(f"/static/{f} answers {st}") + return "; ".join(bad) or None + check("the page loads the settings page's script and style, and the console serves them", page) + + def read(): + st, _ = d.req("GET", "/api/settings", token=False) + if st != 403: + return f"without the token: {st}" + if d.req("GET", "/api/settings", token="not-it")[0] != 403: + return "a wrong token is let in" + st, s = d.req("GET", "/api/settings") + if st != 200 or s.get("version") != 1: + return f"{st} {s}" + bad = [] + if s["studio"] != {"studio_lang": None, "studio_theme": None, "agent_default": None}: bad.append(f"studio {s['studio']}") + if s["mirror"] != {"mode": "cn", "why": None, "at": "2026-11-01"}: bad.append(f"mirror {s['mirror']}") + L = s["local"]["lines"] + if L.get("effort") != "quick" or L.get("budget") != "每支片子 5 美元" or L.get("review") is not None or L.get("sound") is not None: + bad.append(f"LOCAL.md's lines (a template's {{…}} and a comment are not values): {L}") + if [k["kind"] for k in s["agents"]["kinds"]] != ["claude", "codex", "dsh"] or any(k["installed"] for k in s["agents"]["kinds"]): + bad.append(f"agents {s['agents']}") + if not s["about"].get("version"): bad.append("no version") + return "; ".join(bad) or None + check("GET /api/settings: only with this run's token; Studio's three settings, the mirror, LOCAL.md's lines as shown (never a template or a comment), the agents, the version", read) + + def write(): + bad = [] + for body, want in (({"name": "studio_theme", "value": "prism"}, 200), ({"name": "studio_lang", "value": "en"}, 200), + ({"name": "agent_default", "value": "codex"}, 200)): + st, s = d.req("POST", "/api/settings", body) + if st != want: bad.append(f"{body}: {st} {s}") + c = conf() + if (c.get("studio_theme"), c.get("studio_lang"), c.get("agent_default")) != ("prism", "en", "codex"): bad.append(f"the file: {c}") + if c.get("kept_for_later") != {"a": 1} or c.get("mirror") != "cn": bad.append(f"a key it does not change was not kept: {c}") + st, s = d.req("POST", "/api/settings", {"name": "studio_lang", "value": None}) + if st != 200 or "studio_lang" in conf() or s["studio"]["studio_lang"] is not None: bad.append(f"null (back to Studio's default): {st} {conf()}") + st, a = d.req("GET", "/api/space/agents") + if st != 200 or a.get("default") != "codex": bad.append(f"the agent column is not told the default: {st} {a.get('default') if isinstance(a, dict) else a}") + return "; ".join(bad) or None + check("POST /api/settings: language, look and the default agent kept in this machine's settings file (other keys kept as they were; null goes back to Studio's default); the agent column is told the default", write) + + def mirror(): + bad = [] + st, s = d.req("POST", "/api/settings", {"name": "mirror", "value": "off"}) + c = conf() + if st != 200 or c.get("mirror") != "off" or s["mirror"]["mode"] != "off" or not c.get("mirror_at"): bad.append(f"off: {st} {c}") + st, s = d.req("POST", "/api/settings", {"name": "mirror", "value": "auto"}) + c = conf() + if st != 200 or any(k in c for k in ("mirror", "mirror_at", "mirror_why")) or s["mirror"]["mode"] != "auto": bad.append(f"auto: {st} {c}") + r = subprocess.run(["bash", str(ROOT / "bin" / "vh"), "settings", "mirror", "--get"], env=ENV, capture_output=True, text=True, timeout=60) + if r.stdout.strip() != "auto": bad.append(f"bin/vh settings mirror --get says {r.stdout.strip()!r} {r.stderr[-200:]}") + return "; ".join(bad) or None + check("the download mirror from the page: off, then automatic, through tools/settings.py, and bin/vh settings sees the same", mirror) + + def refusals(): + bad = [] + before = CONF.read_bytes() + for body in ({"name": "studio_theme", "value": "neon"}, {"name": "GEMINI_API_KEY", "value": "x"}, {"name": "mirror", "value": "nope"}, + {"name": "studio_lang", "value": 3}, {"name": "model:claude", "value": "claude-opus-5-5"}, + {"name": "effort:nobody", "value": "high"}, {"value": "en"}): + st, _ = d.req("POST", "/api/settings", body) + if st != 400: bad.append(f"{body}: {st}") + if d.req("POST", "/api/settings", {"name": "studio_theme", "value": "bridge"}, token=False)[0] != 403: bad.append("no token") + if d.req("POST", "/api/settings", {"name": "studio_theme", "value": "bridge"}, origin="http://evil.example")[0] != 403: bad.append("another origin") + if CONF.read_bytes() != before: bad.append("a refused request changed the file") + return "; ".join(bad) or None + check("POST /api/settings refuses what is not one of its settings or values (a model no chat offered, any key's name), without the token, from another origin, and changes nothing then", refusals) + + def local_untouched(): + return None if "默认努力程度:quick" in LOCAL.read_text(encoding="utf-8") and not list(T.glob("LOCAL.md.*")) else "LOCAL.md was written" + check("nothing on the page writes LOCAL.md", local_untouched) + finally: + d.stop() + + +def words_check(): + src = (HERE / "static" / "settings.js").read_text(encoding="utf-8") + zh = src[src.index(" zh: {"):src.index(" en: {")] + en = src[src.index(" en: {"):src.index(" };", src.index(" en: {"))] + keys = lambda block: set(re.findall(r"(?:^|[\s,{])(\w+): \"", block)) # noqa: E731 + if keys(zh) != keys(en): + return f"only in Chinese: {sorted(keys(zh) - keys(en))}; only in English: {sorted(keys(en) - keys(zh))}" + + +check("tools/settings.py: Studio's three settings, a value it does not know read as not set, any other name or value refused, other keys kept", module_check) +check("the settings page's words: every one in both languages", words_check) +try: + run() +except Exception as e: + say(False, "the console for the settings page", f"{type(e).__name__}: {e}") +print("end", flush=True) diff --git a/tools/desk/test_wording.py b/tools/desk/test_wording.py index bc34f21a..ecea0dc9 100644 --- a/tools/desk/test_wording.py +++ b/tools/desk/test_wording.py @@ -24,7 +24,7 @@ TERMINAL_OK = re.compile(r"bin/vh|\.md\b|\bproxy\b") # a terminal line may name the command to run, a file, the network's proxy CJK = re.compile(r"[一-鿿]") PROSE = re.compile(r"[A-Za-z]{2,}[,:;.!?]? [A-Za-z]{2,}") # English words a space apart: not an identifier, a key or a file name -PAGES = ["tools/desk/static/studio.js", "tools/desk/static/ui.js", "tools/desk/static/reader.js", "tools/desk/static/index.html", +PAGES = ["tools/desk/static/studio.js", "tools/desk/static/settings.js", "tools/desk/static/ui.js", "tools/desk/static/reader.js", "tools/desk/static/index.html", "tools/desk/shell/main.js", "tools/desk/launcher/shell-boot.js"] TERMINAL = ["install.sh", "tools/desk/launcher/studio-launch.sh", "tools/desk/launcher/studio.applescript"] diff --git a/tools/schemas/output/settings.schema.json b/tools/schemas/output/settings.schema.json index ad29f391..26efe478 100644 --- a/tools/schemas/output/settings.schema.json +++ b/tools/schemas/output/settings.schema.json @@ -2,7 +2,7 @@ "$schema": "https://json-schema.org/draft/2020-12/schema", "$id": "https://github.com/ZLHad/OpenVideoHarness/tools/schemas/output/settings.schema.json", "title": "bin/vh settings --json", - "description": "This machine's own settings (tools/settings.py: $XDG_CONFIG_HOME/ovh/settings.json), the mirror in effect, the mirror table (tools/mirrors.txt) and the mirror variables as bin/vh exported them.", + "description": "This machine's own settings (tools/settings.py: $XDG_CONFIG_HOME/ovh/settings.json), the mirror in effect, the mirror table (tools/mirrors.txt) and the mirror variables as bin/vh exported them, and Studio's own settings.", "type": "object", "required": ["version", "tool", "file", "settings", "mirror", "mirrors", "environment"], "properties": { @@ -25,6 +25,14 @@ } } }, - "environment": {"type": "object"} + "environment": {"type": "object"}, + "studio": { + "type": "object", + "properties": { + "studio_lang": {"enum": ["zh", "en", null]}, + "studio_theme": {"enum": ["darkfield", "prism", "bridge", null]}, + "agent_default": {"enum": ["claude", "codex", "dsh", null]} + } + } } } diff --git a/tools/settings.py b/tools/settings.py index 3fb2f6a0..cdf07ddf 100644 --- a/tools/settings.py +++ b/tools/settings.py @@ -21,7 +21,11 @@ {"version": 1, "mirror": "cn" | "off", absent: auto "mirror_why": "…", who set it and why, in a sentence (install.sh's probe says what did not answer) - "mirror_at": "YYYY-MM-DD"} + "mirror_at": "YYYY-MM-DD", + "studio_lang": "zh" | "en", Studio's language (absent: zh) + "studio_theme": "darkfield" | "prism" | "bridge", Studio's look (absent: darkfield) + "agent_default": "claude" | "codex" | "dsh"} the agent a new chat in Studio starts with (absent: the first one set up) + ("agent_picks" is taken for the models and efforts picked in Studio, should they move here from picks.json.) In-process (Studio): update(patch: dict) -> dict and set_mirror(mode, why=None) -> dict; load() reads, path() says where. Every write goes through update(patch): under a lock (settings.json.lock), it reads the file as it is now, sets the keys it was given (None takes one out), keeps all the others, and writes the whole file to a temporary file moved into place, @@ -32,6 +36,7 @@ ROOT = Path(__file__).resolve().parent.parent MODES = ("cn", "off", "auto") +STUDIO = {"studio_lang": ("zh", "en"), "studio_theme": ("darkfield", "prism", "bridge"), "agent_default": ("claude", "codex", "dsh")} def path(): @@ -115,6 +120,20 @@ def mirror(d=None): return m if m in ("cn", "off") else "auto" +def studio(d=None): + """Studio's own settings: {studio_lang, studio_theme, agent_default}, each a value STUDIO allows, or None (not set, or + a value it does not know: Studio's default).""" + d = d if d is not None else load() + return {k: d.get(k) if d.get(k) in ok else None for k, ok in STUDIO.items()} + + +def set_studio(name, value): + """One of Studio's settings (None: back to Studio's default) → the settings as kept. ValueError for any other name or value.""" + if name not in STUDIO or value is not None and value not in STUDIO[name]: + raise ValueError(f"{name}={value!r}: not one of Studio's settings") + return update({name: value}) + + def mirrors(): """tools/mirrors.txt → [{kind, variable, official, mirror, who}].""" rows = [] @@ -149,7 +168,7 @@ def show(d, as_json=False): m = mirror(d) if as_json: print(json.dumps({"version": 1, "tool": "bin/vh settings", "file": str(path()), "settings": d, "mirror": m, - "mirrors": mirrors(), "environment": in_effect()}, ensure_ascii=False, indent=1)) + "mirrors": mirrors(), "environment": in_effect(), "studio": studio(d)}, ensure_ascii=False, indent=1)) return print(f"this machine's settings: {path()}" + ("" if path().exists() else " (not written yet: the defaults)")) said = {"cn": "the mainland-China mirrors, for every download (tools/mirrors.txt)", @@ -158,6 +177,9 @@ def show(d, as_json=False): print(f" mirror {m}: {said}" + (f" · {d['mirror_why']}" if d.get("mirror_why") else "") + (f" ({d['mirror_at']})" if d.get("mirror_at") else "")) print(" bin/vh settings mirror cn|off|auto changes it") + st = {k: v for k, v in studio(d).items() if v} + if st: + print(" studio " + ", ".join(f"{k} {v}" for k, v in st.items()) + " (Studio's settings page changes these)") def main(argv): From 2106efc3c94bdf3689212e7eb01484c768970387 Mon Sep 17 00:00:00 2001 From: zhanglinghao Date: Sun, 22 Nov 2026 05:40:20 +0800 Subject: [PATCH 12/19] Mirrors, review of #231: read on every run (off takes out what an earlier bin/vh exported), a source of the person's own stays, every Chrome fetch through the mirror, the probe tries the right hosts twice settings.py: env_changes() is the one reader (bin/vh asks it when the file names a mirror or one was inherited), an inherited OVH_MIRROR with the setting not cn takes out exactly the values bin/vh exported; npm's registry in an .npmrc and uv's index or Python mirror in a uv.toml or pyproject.toml are left alone and said; a broken file kept as settings.json.bad, a newer version never written over, a relative XDG_CONFIG_HOME ignored, an unwritable folder one line. install.sh: npmjs through npm ping, Hugging Face and Google's storage through curl, all at once, twice each; the reason says what happened; the Chrome step cannot stop the install; -h prints the whole header. bin/vh: render, frames, textcheck and hf fetch HyperFrames' Chrome through the mirror with cn, with the @puppeteer/browsers HyperFrames' node_modules holds; settings chrome [project]; the hints name it. mirrors.txt says what is checked and what is trusted to the mirror, and what is not covered; README and the change note too. --- README.md | 2 +- README.zh-CN.md | 2 +- bin/vh | 72 ++++--- changes/first-run-mirrors.md | 6 +- install.sh | 66 ++++-- tools/ci.sh | 132 ++++++++---- tools/commands.json | 8 +- tools/doctor.py | 7 +- tools/mirrors.txt | 29 ++- tools/readcheck.py | 6 +- tools/schemas/output/settings.schema.json | 10 +- tools/settings.py | 252 ++++++++++++++++++---- tools/status.py | 6 +- 13 files changed, 453 insertions(+), 145 deletions(-) diff --git a/README.md b/README.md index fd69ccc3..68337849 100644 --- a/README.md +++ b/README.md @@ -424,7 +424,7 @@ bash install.sh --no-icon # leave OVH Studio out of your - The installer fetches only the newest commit: the repo itself is about 95 MB to download and 200 MB on disk, before its packages and the reference repos. To contribute or browse the history, `git clone` normally and run `bin/vh setup`. - To update, run the installer again with the same options (or `git pull`); `LOCAL.md` and `projects/` are left alone, and it stops before overwriting files you changed. The installed skills are short stubs that read `skills/` in the clone, so they follow the update; `bin/vh doctor` says in the rare case one needs `bin/vh install-skill` again. - The showcase videos aren't in git; to rebuild a showcase locally, `tools/fetch_media.sh` downloads them from the release to where its scripts expect them. -- The first render and the first use of the sound tools download more into `~/.cache`: Chrome about 200 MB, the sound tools' Python packages about 0.7 GB, and the default local voice about 2.6 GB (its packages 0.8 GB, its model 1.8 GB), which `bin/vh tts` says before it starts and shows the progress of (`--provider edge` needs only a small package). The local Whisper behind `--align local` is about 3.6 GB more, said the same way (measured 2026-11; where each goes is on the wiki's [Getting Started](https://github.com/ZLHad/OpenVideoHarness/wiki/Getting-Started)). Where the official sources are blocked: the installer tries the official npm registry first, and when it does not answer in 5 s and the mainland-China mirror does, it switches to the mirrors (npmmirror, Tsinghua's TUNA, hf-mirror, listed in `tools/mirrors.txt`), says so, and every later `bin/vh` download follows (npm, Python packages, the local voice's model, Electron, the Chrome renders use); `bin/vh settings mirror off` turns that off. GitHub itself has no mirror: cloning the repo still needs GitHub. More on the wiki's [China network](https://github.com/ZLHad/OpenVideoHarness/wiki/China-Network) page. +- The first render and the first use of the sound tools download more into `~/.cache`: Chrome about 200 MB, the sound tools' Python packages about 0.7 GB, and the default local voice about 2.6 GB (its packages 0.8 GB, its model 1.8 GB), which `bin/vh tts` says before it starts and shows the progress of (`--provider edge` needs only a small package). The local Whisper behind `--align local` is about 3.6 GB more, said the same way (measured 2026-11; where each goes is on the wiki's [Getting Started](https://github.com/ZLHad/OpenVideoHarness/wiki/Getting-Started)). Where the official sources are blocked: the installer tries the official npm registry, Hugging Face and Google's storage first (twice each), and when one does not answer and its mainland-China mirror does, it switches to the mirrors (npmmirror, Tsinghua's TUNA, hf-mirror, listed in `tools/mirrors.txt`) and says which and why. From then on the downloads `bin/vh` starts follow: npm, Python packages, the local voice's model, Electron, the Chrome renders use, and an agent's own `npm` or `uv` in a session Studio started. A registry you set yourself (an `.npmrc`, a `uv.toml`, the variable) stays yours. `bin/vh settings mirror off` turns it off; installed before this, `bin/vh settings mirror cn` turns it on. Not covered: GitHub (the clone itself, `references/fetch.sh`, `--obscura`), `bin/vh hf add`, `bin/vh hdri` (Poly Haven) and the Google Fonts the hand-drawn engine's studio page loads. More on the wiki's [China network](https://github.com/ZLHad/OpenVideoHarness/wiki/China-Network) page. Skill only: `npx skills add https://github.com/ZLHad/OpenVideoHarness --skill open-video-harness`. It's a pointer: on first use it asks before installing the full workbench. That copy stays as it was when the repo changes; once the workbench is installed, `bin/vh install-skill` replaces it with a stub that follows the clone. diff --git a/README.zh-CN.md b/README.zh-CN.md index 0fca0b0a..1a5b677b 100644 --- a/README.zh-CN.md +++ b/README.zh-CN.md @@ -424,7 +424,7 @@ bash install.sh --no-icon # 不把 OVH Studio 放进应 - 安装脚本只拉最新的一个提交,仓库本身下载约 95 MB、占约 200 MB 磁盘,依赖和参考仓库另算;想参与贡献或翻历史,就正常 `git clone`,再运行 `bin/vh setup`。 - 更新:用同样的参数再运行一次安装命令(或者 `git pull`);`LOCAL.md` 和 `projects/` 不动,要覆盖你改过的文件时会先停下来。装出去的 skill 是指回克隆里 `skills/` 的短桩,跟着一起更新;少数要重装的时候(`bin/vh install-skill`),`bin/vh doctor` 会说。 - 样片的视频不在 git 里,要在本地复现样片时运行 `tools/fetch_media.sh`,它从 Release 下载到脚本要的位置。 -- 第一次渲染、第一次用声音工具时还会往 `~/.cache` 下载:Chrome 约 200 MB,声音工具的 Python 依赖约 0.7 GB,默认的本地配音约 2.6 GB(依赖 0.8 GB、模型 1.8 GB;`bin/vh tts` 开始前会先说,并显示进度;`--provider edge` 只要一个小包);`--align local` 用的本地 Whisper 另需约 3.6 GB,同样先说(2026-11 实测;各放在哪里见 wiki 的[快速开始](https://github.com/ZLHad/OpenVideoHarness/wiki/%E5%BF%AB%E9%80%9F%E5%BC%80%E5%A7%8B))。国内网络:安装时先试官方的 npm 源,5 秒内没有应答、国内镜像有,就改用国内镜像(npmmirror、清华 TUNA、hf-mirror,列在 `tools/mirrors.txt`)并说一声,之后 `bin/vh` 的下载(npm、Python 包、本地配音模型、Electron、渲染用的 Chrome)都跟着走;`bin/vh settings mirror off` 关掉。GitHub 本身没有镜像:克隆仓库还是要连得上 GitHub。其余细节见 wiki 的[国内网络](https://github.com/ZLHad/OpenVideoHarness/wiki/%E5%9B%BD%E5%86%85%E7%BD%91%E7%BB%9C)。 +- 第一次渲染、第一次用声音工具时还会往 `~/.cache` 下载:Chrome 约 200 MB,声音工具的 Python 依赖约 0.7 GB,默认的本地配音约 2.6 GB(依赖 0.8 GB、模型 1.8 GB;`bin/vh tts` 开始前会先说,并显示进度;`--provider edge` 只要一个小包);`--align local` 用的本地 Whisper 另需约 3.6 GB,同样先说(2026-11 实测;各放在哪里见 wiki 的[快速开始](https://github.com/ZLHad/OpenVideoHarness/wiki/%E5%BF%AB%E9%80%9F%E5%BC%80%E5%A7%8B))。国内网络:安装时先试官方的 npm 源、Hugging Face 和 Google 的存储(各试两次),哪个连不上、它的国内镜像连得上,就改用国内镜像(npmmirror、清华 TUNA、hf-mirror,列在 `tools/mirrors.txt`),并说明是哪个、为什么。之后 `bin/vh` 起的下载都跟着走:npm、Python 包、本地配音模型、Electron、渲染用的 Chrome,还有 Studio 起的 agent 自己跑的 `npm`、`uv`。你自己设过的源(`.npmrc`、`uv.toml` 或那个变量)不动。`bin/vh settings mirror off` 关掉;这之前装的,`bin/vh settings mirror cn` 打开。不走镜像的:GitHub(克隆本身、`references/fetch.sh`、`--obscura`)、`bin/vh hf add`、`bin/vh hdri`(Poly Haven),以及手绘引擎的 studio 页面加载的 Google Fonts。其余细节见 wiki 的[国内网络](https://github.com/ZLHad/OpenVideoHarness/wiki/%E5%9B%BD%E5%86%85%E7%BD%91%E7%BB%9C)。 只装 skill:`npx skills add https://github.com/ZLHad/OpenVideoHarness --skill open-video-harness`。它只是一个指针,第一次用时会征得你同意,再把完整的工作台装好。这样装的是整份副本,仓库更新了它不变;工作台装好以后跑一次 `bin/vh install-skill`,换成跟随克隆的短桩。 diff --git a/bin/vh b/bin/vh index 1b082d88..9cce523f 100755 --- a/bin/vh +++ b/bin/vh @@ -8,15 +8,16 @@ set -euo pipefail unset CDPATH # an exported CDPATH would send a relative cd (this one: bin/vh run as bin/vh) to another folder, and print it ROOT="$(cd "$(dirname "${BASH_SOURCE[0]}")/.." && pwd)" c_ok=$'\033[32m✓\033[0m'; c_no=$'\033[31m✗\033[0m'; c_wa=$'\033[33m!\033[0m' -# this machine's settings (tools/settings.py): with "mirror": "cn", every download a command starts goes to the mirrors in -# tools/mirrors.txt (npm, uv, Hugging Face, Electron; a variable already set wins); read with grep, so no python3 per run -if [ -f "${XDG_CONFIG_HOME:-$HOME/.config}/ovh/settings.json" ] && grep -q '"mirror"[[:space:]]*:[[:space:]]*"cn"' "${XDG_CONFIG_HOME:-$HOME/.config}/ovh/settings.json" 2>/dev/null; then - while read -r _k _v _o _m _w; do - case "$_k" in ""|\#*) continue ;; esac - if [ "$_v" != - ] && [ -z "${!_v:-}" ]; then export "$_v=$_m"; fi - done < "$ROOT/tools/mirrors.txt" - export OVH_MIRROR=cn +# this machine's settings (tools/settings.py) are read on every run, so a change reaches every process at its next bin/vh: +# with "mirror": "cn" bin/vh exports the mirror variables of tools/mirrors.txt for what it runs, the agents Studio starts +# included (one the person set stays theirs: in the environment, or npm's or uv's own configuration); otherwise it takes out +# again the ones a bin/vh before it exported (inherited OVH_MIRROR=cn). One reader, settings.py; python3 runs only when the +# file names a mirror or a mirror was inherited (an XDG_CONFIG_HOME that is not absolute is ignored, as settings.py does) +_cf=${XDG_CONFIG_HOME:-}; case "$_cf" in /*) ;; *) _cf=$HOME/.config ;; esac +if [ -n "${OVH_MIRROR:-}" ] || { [ -f "$_cf/ovh/settings.json" ] && grep -q '"mirror"' "$_cf/ovh/settings.json" 2>/dev/null; }; then + if _env=$(python3 "$ROOT/tools/settings.py" env 2>/dev/null); then eval "$_env"; fi fi +unset _cf _env declare -a TYPES=( "math:01-math-science-explainer:数学/科学原理讲解(Manim)" @@ -135,17 +136,37 @@ hf_pin() { # hf_pin : the Chrome version pinned by the HyperFrames in the n [ ${#files[@]} -gt 0 ] || return 1 awk -F'"' -v k="var $k = " '$1 == k && $2 ~ /^[0-9][0-9.]*$/ { print $2; f = 1; exit } END { exit !f }' "${files[@]}" 2>/dev/null } +hf_mods() { # hf_mods : the folder at or above dir whose node_modules holds HyperFrames (as hf_pin looks), else fails + local d + [ -n "${1:-}" ] && d=$(cd "$1" 2>/dev/null && pwd) || return 1 + while [ ! -d "$d/node_modules/hyperframes" ]; do [ "$d" = / ] && return 1; d=$(dirname "$d"); done + echo "$d" +} hf_chrome_mirror() { # hf_chrome_mirror : with the mirror on (cn) and no chrome-headless-shell yet at the version the HyperFrames - # installed for dir pins, fetch it from the mirror into the folder HyperFrames looks in: HyperFrames has no setting for where it - # downloads its Chrome, so without this the first render would go to storage.googleapis.com anyway (no hash is pinned for it) + # installed for dir pins (dir has none: styles/_swatch's), fetch it from the mirror into the folder HyperFrames looks in: + # HyperFrames has no setting for where it downloads its Chrome, so without this the first render would go to + # storage.googleapis.com anyway. With the @puppeteer/browsers HyperFrames' own node_modules holds (under its lockfile's + # hash where there is one), else the one pinned here; no hash is pinned for the Chrome itself. Its lines go to stderr [ "${OVH_MIRROR:-}" = cn ] || return 0 - local d=$1 pin base - pin=$(hf_pin "$d") || return 0 + local d m pin base cli + m=$(hf_mods "${1:-.}") || m=$(hf_mods "$ROOT/styles/_swatch") || return 0 + pin=$(hf_pin "$m") || return 0 [ -n "$(shell_folder "$HOME/.cache/hyperframes/chrome/chrome-headless-shell" "$pin" 2>/dev/null)" ] && return 0 base=$(awk '$1 == "chrome" { print $4 }' "$ROOT/tools/mirrors.txt") - echo "→ HyperFrames' Chrome $pin from the mirror ($base, about 93 MB), into ~/.cache/hyperframes/chrome, where its first render looks" - (cd "$d" && npx --yes @puppeteer/browsers install "chrome-headless-shell@$pin" --path "$HOME/.cache/hyperframes/chrome" --base-url "$base" >/dev/null 2>&1) \ - || echo "$c_wa HyperFrames' Chrome did not come from the mirror; the first render tries its own download" + if [ -x "$m/node_modules/.bin/browsers" ]; then cli=("$m/node_modules/.bin/browsers"); else cli=(npx --yes "@puppeteer/browsers@$PUPPETEER_BROWSERS"); fi + echo "→ HyperFrames' Chrome $pin from the mirror ($base, about 93 MB), into ~/.cache/hyperframes/chrome, where its first render looks" >&2 + (cd "$m" && "${cli[@]}" install "chrome-headless-shell@$pin" --path "$HOME/.cache/hyperframes/chrome" --base-url "$base" >/dev/null 2>&1) \ + || { echo "$c_wa HyperFrames' Chrome did not come from the mirror; the first render tries its own download (bin/vh settings chrome tries again)" >&2; return 1; } +} +PUPPETEER_BROWSERS=3.2.3 # the @puppeteer/browsers HyperFrames 0.8.202 brings, for a folder without node_modules +chrome_hint() { # chrome_hint : how to get the chrome-headless-shell HyperFrames renders with, in words for a message + if [ "${OVH_MIRROR:-}" = cn ]; then echo "bin/vh settings chrome ${1:-} (from the mirror)"; else echo "npx hyperframes browser ensure (in a HyperFrames project)"; fi +} +hf_shell_any() { # hf_shell_any : hf_shell, and with the mirror on and none here yet, after fetching it from the mirror + hf_shell "${1:-}" && return 0 + [ "${OVH_MIRROR:-}" = cn ] || return 1 + hf_chrome_mirror "${1:-.}" >/dev/null || return 1 + hf_shell "${1:-}" } old_mac() { [ "$(uname)" = Darwin ] && [ "$(uname -r | cut -d. -f1)" -lt 22 ]; } # macOS 12 or older: HyperFrames stops Chrome at 150 shell_folder() { # shell_folder [version]: the folder of that chrome-headless-shell version, else (no version given) the newest; @@ -193,14 +214,15 @@ cmd_install_skill() { # writes a stub for each skill in skills/: its frontmatter } cmd_settings() { # this machine's settings (tools/settings.py, -h); the mirror turned on also fetches HyperFrames' Chrome from it now, # since HyperFrames cannot be pointed at a mirror itself - if [ "${1:-}" = chrome ]; then # settings chrome: HyperFrames' Chrome from the mirror now, when the mirror is on and it is not here - [ $# = 1 ] || { echo "usage: bin/vh settings chrome" >&2; return 2; } + if [ "${1:-}" = chrome ]; then # settings chrome [project]: HyperFrames' Chrome from the mirror now, when the mirror is on and it is not here + [ $# -le 2 ] || { echo "usage: bin/vh settings chrome [project]" >&2; return 2; } [ "${OVH_MIRROR:-}" = cn ] || { echo "the mirrors are not on (bin/vh settings mirror cn): HyperFrames downloads its own Chrome at the first render"; return 0; } - [ -d "$ROOT/styles/_swatch/node_modules/hyperframes" ] || { echo "$c_wa no HyperFrames in styles/_swatch yet (cd styles/_swatch && npm ci): nothing to fetch Chrome for" >&2; return 1; } - hf_chrome_mirror "$ROOT/styles/_swatch"; return 0 + local w=${2:-$ROOT/styles/_swatch} + hf_mods "$w" >/dev/null || { echo "$c_wa no HyperFrames installed for ${2:-styles/_swatch} yet (${2:+bin/vh hf-init it, or }cd ${2:-styles/_swatch} && npm ci): nothing to fetch Chrome for" >&2; return 1; } + hf_chrome_mirror "$w"; return $? fi python3 "$ROOT/tools/settings.py" "$@" || return $? - if [ "${1:-}" = mirror ] && [ "${2:-}" = cn ] && [ -d "$ROOT/styles/_swatch/node_modules/hyperframes" ]; then OVH_MIRROR=cn; hf_chrome_mirror "$ROOT/styles/_swatch"; fi + if [ "${1:-}" = mirror ] && [ "${2:-}" = cn ] && [ -d "$ROOT/styles/_swatch/node_modules/hyperframes" ]; then OVH_MIRROR=cn; hf_chrome_mirror "$ROOT/styles/_swatch" || true; fi } cmd_sync_agents() { # CLAUDE.md's 命令行 line from tools/commands.json first, then AGENTS.md from CLAUDE.md local m; m=$(python3 "$ROOT/tools/commands.py" claude-line --write "$ROOT/CLAUDE.md") || exit 1 @@ -887,8 +909,8 @@ cmd_textcheck() { # canvas text covered or too faint (tools/textcheck/textcheck. local b=${CHROME_PATH:-} d if [ -z "$b" ] || [ ! -x "$b" ]; then d=$(arg_dir "$@") - b=$(hf_shell "$d") || b=$(chrome_path) || { echo "$c_no bin/vh textcheck needs a headless Chrome: npx hyperframes browser ensure (in a HyperFrames project), install Chrome or Chromium, or set CHROME_PATH" >&2; exit 2; } - hf_chrome "$d" >/dev/null || echo "$c_wa not the chrome-headless-shell hyperframes render uses for this project, so text can lay out a little differently in the film (npx hyperframes browser ensure there fetches it)" >&2 + b=$(hf_shell_any "$d") || b=$(chrome_path) || { echo "$c_no bin/vh textcheck needs a headless Chrome: $(chrome_hint "$d"), install Chrome or Chromium, or set CHROME_PATH" >&2; exit 2; } + hf_chrome "$d" >/dev/null || echo "$c_wa not the chrome-headless-shell hyperframes render uses for this project, so text can lay out a little differently in the film ($(chrome_hint "$d") fetches it)" >&2 fi exec node "$ROOT/tools/textcheck/textcheck.mjs" --browser "$b" "$@" } @@ -920,7 +942,7 @@ film_browser() { # film_browser [dir]: the browser the page-contract t # render uses for dir, else the newest in ~/.cache/puppeteer, else Chrome or Chromium); the command is for the message local b=${CHROME_PATH:-} if [ -z "$b" ] || [ ! -x "$b" ]; then - b=$(hf_shell "${2:-}") || b=$(chrome_path) || { echo "$c_no bin/vh $1 needs a headless Chrome: npx hyperframes browser ensure (in a HyperFrames project), install Chrome or Chromium, or set CHROME_PATH" >&2; return 1; } + b=$(hf_shell_any "${2:-}") || b=$(chrome_path) || { echo "$c_no bin/vh $1 needs a headless Chrome: $(chrome_hint "${2:-}"), install Chrome or Chromium, or set CHROME_PATH" >&2; return 1; } fi echo "$b" } @@ -1454,7 +1476,9 @@ cmd_web() { # stdlib + the existing Chrome CDP transport; Obscura is an explicit case "$1" in fetch|shot) b=$(film_browser web "${2:-}" 2>/dev/null) || b="" ;; esac CHROME_PATH="${b:-${CHROME_PATH:-}}" python3 "$ROOT/tools/web/web.py" "$@" } -cmd_hf() { [ $# -gt 0 ] || { cmd_usage hf >&2; exit 2; }; python3 "$ROOT/tools/hf.py" "$@"; } # stdlib; add runs HyperFrames' own add +cmd_hf() { [ $# -gt 0 ] || { cmd_usage hf >&2; exit 2; } # stdlib; add runs HyperFrames' own add + case "${1:-}" in -h|--help) ;; *) hf_chrome_mirror "$(arg_dir "${@:2}")" || true ;; esac # with the mirror on: its Chrome first, from there + python3 "$ROOT/tools/hf.py" "$@"; } cmd_components() { python3 "$ROOT/tools/components.py" "$@"; } # stdlib; check reads component.js through node, sample runs the swatch renderer cmd_deliver() { [ $# -gt 0 ] || { cmd_usage deliver >&2; exit 2; }; python3 "$ROOT/tools/deliver.py" "$@"; } # ffmpeg only cmd_looks() { [ $# -gt 0 ] || { cmd_usage looks >&2; exit 2; }; python3 "$ROOT/tools/looks.py" "$@"; } # ffmpeg; the ledger outside the repo diff --git a/changes/first-run-mirrors.md b/changes/first-run-mirrors.md index d11bde11..ea671aeb 100644 --- a/changes/first-run-mirrors.md +++ b/changes/first-run-mirrors.md @@ -1,7 +1,7 @@ **连不上官方源时,安装自动改用国内镜像,之后的下载都跟着走** - Why: 在国内网络下,第一次安装和第一次做片要连 npm、PyPI、Hugging Face、GitHub Releases 和 Google 的存储;原来要照 wiki 手动设三四个变量、另跑两条命令装 Chrome,Studio 应用的 Electron 下载没有写怎么办。 -- 安装时先试官方的 npm 源(5 秒);没有应答、国内镜像有,就改用国内镜像,用一句话说明,并记在这台机器自己的设置里(`~/.config/ovh/settings.json`)。不按语言或时区猜。`--mirror cn` 直接用,`--mirror off` 不用,也记下来。 -- 镜像的地址集中在 `tools/mirrors.txt` 一个文件里,每一行写明是谁在运营(npmmirror.com、清华 TUNA、hf-mirror.com)。镜像打开时,`bin/vh` 给它运行的每条命令设好 npm、uv(Python 包和 Python 本身)、Hugging Face 和 Electron 的镜像变量;你自己设过的变量不动。HyperFrames 下载 Chrome 时没有可设的地址,所以由 `bin/vh new` 和安装先从镜像把它装进 HyperFrames 找的目录。 +- 安装时先试官方的 npm 源(经 npm 试,它自己的代理设置算数)、Hugging Face 和 Google 的存储(Chrome),各试两次、每次 5 秒;哪个连不上、它的国内镜像连得上,就改用国内镜像,用一句话说明是哪个、怎么连不上,并记在这台机器自己的设置里(`~/.config/ovh/settings.json`)。不按语言或时区猜。`--mirror cn` 直接用,`--mirror off` 不用,也记下来。这之前装的,`bin/vh settings mirror cn` 打开。 +- 镜像的地址集中在 `tools/mirrors.txt` 一个文件里,每一行写明是谁在运营(npmmirror.com、清华 TUNA、hf-mirror.com)。设置每次都从文件读:镜像打开时,`bin/vh` 给它运行的每条命令设好 npm、uv(Python 包和 Python 本身)、Hugging Face 和 Electron 的镜像变量,Studio 起的 agent 也一样;关掉以后,之前继承下来的这些变量下一次运行就拿掉。你自己设的源不动:环境变量,`.npmrc` 里 npm 的源,`uv.toml` 里 uv 的源。HyperFrames 下载 Chrome 没有可设的地方,`bin/vh new`、`render`、`hf`、`frames` 和 `bin/vh settings chrome [项目]` 从镜像替它下好。不走镜像的:GitHub(克隆、`references/fetch.sh`、`--obscura`)、`bin/vh hf add`、`bin/vh hdri`、手绘引擎 studio 页面的 Google Fonts。 - 新命令 `bin/vh settings`:看这台机器的设置,`bin/vh settings mirror cn|off|auto` 改镜像,`--json` 给 Studio 的设置面板读。`bin/vh doctor` 多一行说现在走哪里、怎么关。 -- 已有的校验不变,也不信任镜像:npm ci 按 lockfile 里的哈希核对每个包;Electron 按它自己的包里带的 checksums.json 核对。uv 的包、Hugging Face 的模型、Python 和 Chrome 没有钉住的哈希,和从官方源下一样照收。 +- 校验:有 lockfile 的地方(`styles/_swatch`、Studio 的 Electron 壳、agent 适配器、ClaudeAnimationBase),npm ci 按 lockfile 里的哈希核对每个包;Electron 按它自己的包里带的 checksums.json 核对;uv 按它自带的 sha256 核对 Python 的构建(试过:从镜像目录换进去的包会被拒)。没有 lockfile 的就完全信任镜像,和今天信任 npmjs.org 一样:`bin/vh new` 装的 hyperframes 和 gsap、`npx hyperframes@<版本>`、没有 node_modules 时用的 @puppeteer/browsers(钉了版本,没钉哈希),包和核对它的哈希都来自镜像;uv 的包、Hugging Face 的模型、HyperFrames 的 Chrome 也是照收。 - 切到镜像以后,uv 会按新的源重新下载之前缓存过的 Python 包(它的缓存按源区分)。 diff --git a/install.sh b/install.sh index 1781e744..ac47dd99 100755 --- a/install.sh +++ b/install.sh @@ -5,9 +5,10 @@ # What it does, and where it puts things: # 1. clone the repo into --dir, newest commit only (about 200 MB on disk; a re-run moves it to the newest commit, keeping LOCAL.md and projects/) # 1b. the download mirrors (tools/mirrors.txt): with neither --mirror nor a choice made before (bin/vh settings), try the official -# npm registry for 5 s; when it does not answer and the mainland-China mirror does, use the mirrors from here on, say so in one -# line, and keep the choice in ~/.config/ovh/settings.json, so later bin/vh downloads use them too (bin/vh settings mirror off -# turns that off). --mirror cn uses them without trying, --mirror off never. Never guessed from the language or time zone +# npm registry (through npm, so its own proxy setting counts), Hugging Face and Google's storage (Chrome), twice each, 5 s a try; +# when one does not answer and its mainland-China mirror does, use the mirrors from here on, say which and why in one line, +# and keep the choice in ~/.config/ovh/settings.json, so later bin/vh downloads use them too (bin/vh settings mirror off turns +# that off). --mirror cn uses them without trying, --mirror off never. Never guessed from the language or time zone # 2. npm install in engines/ClaudeAnimationBase and npm ci in styles/_swatch (HyperFrames 0.8.202), both inside --dir (about 180 MB of # node_modules; npm also writes its own cache, ~/.npm). The read-only reference repos references/fetch.sh lists are not fetched: # an agent fetches the one a doc points to when it first needs it (bash references/fetch.sh , which says its size first); @@ -41,7 +42,7 @@ DIR="${OVH_DIR:-$HOME/OpenVideoHarness}"; REFS=0; SKILL=all; OBSCURA=0; ICON=def while [ $# -gt 0 ]; do case "$1" in --dir) DIR="$2"; shift 2 ;; --refs) REFS=1; shift ;; --no-refs) REFS=0; shift ;; --no-skill) SKILL=none; shift ;; --skill) SKILL="${2:?--skill needs claude|codex|all|none}"; shift 2 ;; --obscura) OBSCURA=1; shift ;; --mirror) MIRROR="${2:?--mirror needs cn or off}"; shift 2 ;; --icon) ICON=yes; shift ;; --no-icon) ICON=no; shift ;; - -h|--help) sed -n '2,32p' "$0"; exit 0 ;; *) echo "unknown option: $1"; exit 1 ;; esac; done + -h|--help) awk 'NR == 1 { next } /^#/ { sub(/^# ?/, ""); print; next } { exit }' "$0"; exit 0 ;; *) echo "unknown option: $1"; exit 1 ;; esac; done case "$SKILL" in claude|codex|all|none) ;; *) echo "unknown --skill '$SKILL' (claude|codex|all|none)"; exit 1 ;; esac [ -z "$MIRROR" ] || case "$MIRROR" in cn|off) ;; *) echo "unknown --mirror '$MIRROR' (cn|off)"; exit 1 ;; esac say() { printf '\033[1m→ %s\033[0m\n' "$*"; } @@ -104,14 +105,55 @@ if [ -d "$DIR/.git" ]; then say "updating $DIR" else say "cloning into $DIR (newest commit only)" git clone -q --depth 1 --single-branch "$REPO" "$DIR" || { echo "✗ Could not download OpenVideoHarness: check the network (or your proxy) and run this installer again."; exit 1; }; fi cd "$DIR" -answers() { command -v curl >/dev/null 2>&1 && curl -fsS -m 5 -o /dev/null "$1" 2>/dev/null; } -if [ -n "$MIRROR" ]; then bin/vh settings mirror "$MIRROR" --why "install.sh --mirror $MIRROR, $(date +%F)" | sed 's/^/ /' -elif [ "$(bin/vh settings mirror --get 2>/dev/null)" = auto ] && ! answers https://registry.npmjs.org/ && answers https://registry.npmmirror.com/; then - bin/vh settings mirror cn --why "install.sh, $(date +%F): registry.npmjs.org did not answer in 5 s, registry.npmmirror.com did" >/dev/null - echo " npm's registry did not answer in 5 s, so downloads come from the mainland-China mirrors from now on (npmmirror.com, TUNA, hf-mirror.com;" - echo " tools/mirrors.txt). bin/vh settings mirror off turns that off." +reach() { # reach [npm]: does it answer at all (any HTTP reply counts), in 5 s, at the first or the second try? → 0; else 1, + # and what happened on stdout. With npm: npm ping, so a proxy that lives only in npm's own configuration is used as npm would + local rc out="" + for _ in 1 2; do + if [ "${2:-}" = npm ] && command -v npm >/dev/null 2>&1; then + out=$(npm ping --registry "$1" --fetch-timeout=5000 --fetch-retries=0 2>&1) && return 0 + case "$out" in *ENOTFOUND*|*EAI_AGAIN*) out="its name did not resolve" ;; *ETIMEDOUT*|*imeout*) out="it did not answer in 5 s" ;; + *ECONNREFUSED*) out="it refused the connection" ;; *ECONNRESET*) out="the connection was reset" ;; *) out="npm could not reach it" ;; esac + elif command -v curl >/dev/null 2>&1; then + rc=0; curl -sS -o /dev/null -m 5 "$1" 2>/dev/null || rc=$? + [ "$rc" = 0 ] && return 0 + case $rc in 5) out="the proxy's name did not resolve" ;; 6) out="its name did not resolve" ;; 7) out="it refused the connection" ;; + 28) out="it did not answer in 5 s" ;; 35|60) out="the secure connection failed" ;; 52|56) out="the connection was reset" ;; *) out="curl error $rc" ;; esac + else echo "nothing here to try it with (no curl)"; return 1 + fi + done + echo "$out, twice"; return 1 +} +PROBES='registry.npmjs.org https://registry.npmjs.org/ https://registry.npmmirror.com/ npm +huggingface.co https://huggingface.co/ https://hf-mirror.com/ curl +storage.googleapis.com https://storage.googleapis.com/chrome-for-testing-public/ https://cdn.npmmirror.com/binaries/chrome-for-testing/ curl' # each official source: what to try, its mirror, how (npm: through npm itself) +probe_mirrors() { # with no choice made: each official source, all three at once; cn when one fails and its mirror answers. → the why + local pt name url mir how n=0 why="" + pt=$(mktemp -d "${TMPDIR:-/tmp}/ovh-probe.XXXXXX") + while read -r name url mir how; do + n=$((n + 1)); ( if r=$(reach "$url" "$how"); then : > "$pt/$n.ok"; else printf '%s' "$r" > "$pt/$n.no"; fi ) & + done <<<"$PROBES" + wait + n=0 + while read -r name url mir how; do + n=$((n + 1)); [ -f "$pt/$n.no" ] || continue + mir=${mir#https://} + if reach "https://$mir" >/dev/null; then why="${why:+$why; }$name: $(cat "$pt/$n.no"), and ${mir%%/*} answered"; fi + done <<<"$PROBES" + rm -rf "$pt" + printf '%s' "$why" +} +NOW="" # the mirror for this run when it could not be kept (an unwritable ~/.config) +if [ -n "$MIRROR" ]; then + bin/vh settings mirror "$MIRROR" --why "install.sh --mirror $MIRROR, $(date +%F)" | sed 's/^/ /' || NOW=$MIRROR +elif [ "$(bin/vh settings mirror --get 2>/dev/null)" = auto ]; then + why=$(probe_mirrors) + if [ -n "$why" ]; then + bin/vh settings mirror cn --why "install.sh, $(date +%F): $why" >/dev/null || NOW=cn + echo " $why: so downloads come from the mainland-China mirrors from now on (npmmirror.com, TUNA, hf-mirror.com;" + echo " tools/mirrors.txt). bin/vh settings mirror off turns that off." + fi fi -eval "$(python3 tools/settings.py env)" # the mirrors, when they are on, for this script's own downloads too +eval "$(python3 tools/settings.py env ${NOW:+--mode "$NOW"})" # the mirrors, when they are on, for this script's own downloads too say "installing the bundled engine (ClaudeAnimationBase)" (cd engines/ClaudeAnimationBase && npm install --silent) || echo "! the hand-drawn engine's packages did not install; running this installer again finishes them" n=$(grep -cE '^(full|sparse|textonly) ' references/fetch.sh || true) # counted from the list, so it cannot go stale @@ -123,7 +165,7 @@ else had=0; [ ! -d references/repos ] || had=$(find references/repos -mindepth 2 fi say "installing the renderer for style samples (HyperFrames, for bin/vh style)" (cd styles/_swatch && npm ci --silent) || echo "! the renderer for style samples did not install; it is tried again the first time a style sample is made" -[ "${OVH_MIRROR:-}" != cn ] || bin/vh settings chrome # with the mirrors on: HyperFrames' Chrome from the mirror now +[ "${OVH_MIRROR:-}" != cn ] || bin/vh settings chrome || true # with the mirrors on: its Chrome from the mirror now (a miss says so, in a line) [ -f LOCAL.md ] || cp LOCAL.example.md LOCAL.md if [ "$SKILL" != none ]; then # one line for the stubs it wrote (each says where it went when run by hand: bin/vh install-skill) say "telling Claude Code and Codex where this workbench is (skills)" diff --git a/tools/ci.sh b/tools/ci.sh index 134f306a..8d7ea792 100755 --- a/tools/ci.sh +++ b/tools/ci.sh @@ -1659,51 +1659,105 @@ PY else bad "first downloads here: $a | $b | no script ($re): $qcalls | progress lines: $g"; fi ;; esac rm -rf "$ft" - # the download mirrors: this machine's settings (tools/settings.py) in a file of their own; with "mirror": "cn" bin/vh exports - # the variables of tools/mirrors.txt for what it runs (one the person set stays theirs); install.sh tries the official npm - # registry first and keeps cn only when it does not answer and the mirror does; --mirror off is kept, and stops the trying - mt=$(mktemp -d "${TMPDIR:-/tmp}/vh-mirror.XXXXXX") - a=$(XDG_CONFIG_HOME="$mt/c" vh settings mirror --get; XDG_CONFIG_HOME="$mt/c" vh settings mirror cn --why "a test" >/dev/null - (unset npm_config_registry HF_ENDPOINT UV_DEFAULT_INDEX ELECTRON_MIRROR; XDG_CONFIG_HOME="$mt/c" vh settings --json) | python3 -c 'import json, sys; d = json.load(sys.stdin); e = d["environment"] -print(d["mirror"], d["settings"].get("mirror_why"), e["npm_config_registry"], e["HF_ENDPOINT"], e["UV_DEFAULT_INDEX"], e["ELECTRON_MIRROR"])' - XDG_CONFIG_HOME="$mt/c" npm_config_registry=https://mine.example vh settings --json | python3 -c 'import json, sys; print(json.load(sys.stdin)["environment"]["npm_config_registry"])' - XDG_CONFIG_HOME="$mt/c" vh settings mirror off >/dev/null; (unset npm_config_registry; XDG_CONFIG_HOME="$mt/c" vh settings --json) | python3 -c 'import json, sys; d = json.load(sys.stdin); print(d["mirror"], d["environment"]["npm_config_registry"])' - XDG_CONFIG_HOME="$mt/c" vh settings mirror nope 2>/dev/null; echo "exit $?") - b=$(awk '!/^#/ && NF { if ($4 !~ /^https:\/\//) print "not https: " $1 }' tools/mirrors.txt) - mkdir -p "$mt/bin"; printf '#!/bin/sh\ncase "$*" in *registry.npmjs.org*) [ -n "$OFFICIAL" ] && exit 0; exit 28 ;; *) exit 0 ;; esac\n' > "$mt/bin/curl"; chmod +x "$mt/bin/curl" - sed -n '/^answers() {/,/^eval "\$(python3 tools\/settings.py env)"/p' install.sh > "$mt/probe.sh" - probe() { (env PATH="$mt/bin:$PATH" XDG_CONFIG_HOME="$mt/$1" "${@:2}" bash -c '. "$1"; vh_get() { bin/vh settings mirror --get; }; echo "now $(vh_get) ${npm_config_registry:-official}"' _ "$mt/probe.sh" 2>&1 | tail -1); } - c=$(MIRROR="" probe p1 env -u npm_config_registry); d=$(probe p2 env -u npm_config_registry OFFICIAL=1); e=$(probe p3 env -u npm_config_registry MIRROR=off); f=$(probe p3 env -u npm_config_registry MIRROR=) - if case "$a" in "auto"*"cn a test https://registry.npmmirror.com https://hf-mirror.com https://mirrors.tuna.tsinghua.edu.cn/pypi/web/simple https://npmmirror.com/mirrors/electron/"*"https://mine.example"*"off None"*"exit 2") true ;; *) false ;; esac \ - && [ -z "$b" ] && [ -s "$mt/probe.sh" ] && [ "$c" = "now cn https://registry.npmmirror.com" ] && [ "$d" = "now auto official" ] && [ "$e" = "now off official" ] && [ "$f" = "now off official" ] \ - && grep -q '"mirror_why": "install.sh, ' "$mt/p1/ovh/settings.json" - then ok "mirrors: kept in this machine's settings; bin/vh exports tools/mirrors.txt's variables with cn (a variable the person set stays); install.sh keeps cn only when the official npm registry does not answer and the mirror does; off is kept and stops the trying" - else bad "mirrors: $a | $b | probe: $c / $d / $e / $f"; fi - # two writers at once (Studio's settings panel and a terminal) both land: settings.update holds a lock, re-reads, merges, - # keeps the keys it was not given - a=$(XDG_CONFIG_HOME="$mt/w" python3 - <<'PY' 2>&1 -import json, os, subprocess, sys -code = "import sys; sys.path.insert(0, 'tools'); import settings\nfor i in range(60): settings.update({f'{sys.argv[1]}{i}': i})\n" -ps = [subprocess.Popen([sys.executable, "-c", code, w]) for w in ("a", "b")] -for q in ps: q.wait() + # the download mirrors: this machine's settings (tools/settings.py) in a file of their own, read on every bin/vh run. With + # "mirror": "cn" bin/vh exports the variables of tools/mirrors.txt for what it runs; a source the person set stays theirs (the + # variable, npm's registry in an .npmrc, uv's index in a uv.toml); once it is not cn, the ones a bin/vh before exported + # (inherited, as Studio's agents have them) are taken out again, and a value of the person's own is left + mt=$(mktemp -d "${TMPDIR:-/tmp}/vh-mirror.XXXXXX"); mh="$mt/home"; mkdir -p "$mh" + mv_() { env -u npm_config_registry -u HF_ENDPOINT -u UV_DEFAULT_INDEX -u UV_INDEX_URL -u ELECTRON_MIRROR -u UV_PYTHON_INSTALL_MIRROR -u OVH_MIRROR -u NPM_CONFIG_USERCONFIG HOME="$mh" XDG_CONFIG_HOME="$mt/c" "$@"; } + envj() { python3 -c 'import json, sys; d = json.load(sys.stdin); e = d["environment"]; print(d["mirror"], " ".join(f"{k}={e[k]}" for k in sorted(e)), [k["kind"] for k in d.get("kept_own", [])])'; } + a=$(mv_ bin/vh settings mirror --get; mv_ bin/vh settings mirror cn --why "a test" >/dev/null; mv_ bin/vh settings --json | envj + mv_ npm_config_registry=https://mine.example bin/vh settings --json | envj + mv_ bin/vh settings mirror off >/dev/null + mv_ OVH_MIRROR=cn npm_config_registry=https://registry.npmmirror.com HF_ENDPOINT=https://hf-mirror.com UV_DEFAULT_INDEX=https://mine.example/simple bin/vh settings --json | envj + mv_ bin/vh settings mirror nope 2>/dev/null; echo "exit $?") + want="auto +cn ELECTRON_MIRROR=https://npmmirror.com/mirrors/electron/ HF_ENDPOINT=https://hf-mirror.com UV_DEFAULT_INDEX=https://mirrors.tuna.tsinghua.edu.cn/pypi/web/simple UV_PYTHON_INSTALL_MIRROR=https://registry.npmmirror.com/-/binary/python-build-standalone npm_config_registry=https://registry.npmmirror.com [] +cn ELECTRON_MIRROR=https://npmmirror.com/mirrors/electron/ HF_ENDPOINT=https://hf-mirror.com UV_DEFAULT_INDEX=https://mirrors.tuna.tsinghua.edu.cn/pypi/web/simple UV_PYTHON_INSTALL_MIRROR=https://registry.npmmirror.com/-/binary/python-build-standalone npm_config_registry=https://mine.example ['npm'] +off ELECTRON_MIRROR=None HF_ENDPOINT=None UV_DEFAULT_INDEX=https://mine.example/simple UV_PYTHON_INSTALL_MIRROR=None npm_config_registry=None [] +exit 2" + # a registry of the person's own in their .npmrc and a uv.toml: not exported over, and said + mv_ bin/vh settings mirror cn >/dev/null; printf 'registry=https://corp.example/npm/\n' > "$mh/.npmrc"; mkdir -p "$mt/c/uv"; printf 'index-url = "https://corp.example/pypi/simple"\n' > "$mt/c/uv/uv.toml" + b=$(mv_ bin/vh settings --json | envj; mv_ bin/vh settings | grep -c 'your own source stays'); rm -f "$mh/.npmrc" "$mt/c/uv/uv.toml" + wantb="cn ELECTRON_MIRROR=https://npmmirror.com/mirrors/electron/ HF_ENDPOINT=https://hf-mirror.com UV_DEFAULT_INDEX=None UV_PYTHON_INSTALL_MIRROR=https://registry.npmmirror.com/-/binary/python-build-standalone npm_config_registry=None ['npm', 'pypi'] +2" + c=$(awk '!/^#/ && NF { if ($4 !~ /^https:\/\//) print "not https: " $1 }' tools/mirrors.txt) + # HyperFrames' Chrome: only through the mirror helper with cn, and not for an inherited OVH_MIRROR once the setting is off; a + # folder with no HyperFrames is one line and exit 1 (the installer goes on past it) + hp="$mt/hfp"; mkdir -p "$hp/node_modules/hyperframes/dist" "$hp/node_modules/.bin"; printf 'var CHROME_VERSION = "152.0.1.2";\n' > "$hp/node_modules/hyperframes/dist/a.js" + printf '#!/bin/sh\necho "$*" >> "%s/browsers.log"\n' "$mt" > "$hp/node_modules/.bin/browsers"; chmod +x "$hp/node_modules/.bin/browsers" + d=$(mv_ bin/vh settings chrome "$hp" 2>&1 >/dev/null; mv_ bin/vh settings mirror off >/dev/null; mv_ OVH_MIRROR=cn bin/vh settings chrome "$hp" + mkdir -p "$mt/empty"; mv_ bin/vh settings mirror cn >/dev/null; mv_ bin/vh settings chrome "$mt/empty" 2>&1; echo "exit $?"; mv_ bin/vh settings mirror auto >/dev/null) + chr=$(sed -n '/settings chrome || true/p' install.sh | sed 's/ *#.*$//'); mkdir -p "$mt/inst/bin"; printf '#!/bin/sh\necho "! no HyperFrames yet" >&2; exit 1\n' > "$mt/inst/bin/vh"; chmod +x "$mt/inst/bin/vh" + e=$(cd "$mt/inst" && OVH_MIRROR=cn bash -euo pipefail -c "$chr; echo went on" 2>&1) + if [ "$a" = "$want" ] && [ "$b" = "$wantb" ] && [ -z "$c" ] && [ "$(cat "$mt/browsers.log" 2>/dev/null)" = "install chrome-headless-shell@152.0.1.2 --path $mh/.cache/hyperframes/chrome --base-url https://cdn.npmmirror.com/binaries/chrome-for-testing" ] \ + && case "$d" in *"HyperFrames' Chrome 152.0.1.2 from the mirror"*"the mirrors are not on"*"no HyperFrames installed for $mt/empty yet"*"exit 1") true ;; *) false ;; esac \ + && [ "$(printf '%s\n' "$e" | tail -1)" = "went on" ] + then ok "mirrors: read on every run; cn exports tools/mirrors.txt's variables (one the person set stays, and npm's or uv's own registry is not exported over, and said); off takes out what an earlier bin/vh exported, not the person's own; HyperFrames' Chrome through the mirror only with cn, a folder with no HyperFrames one line and the installer goes on" + else bad "mirrors: $a | own: $b | $c | chrome: $(cat "$mt/browsers.log" 2>/dev/null) / $d | installer: $e"; fi + # install.sh's probe: npmjs through npm (its own proxy counts), Hugging Face and Google's storage through curl, twice each; + # cn when one fails twice and its mirror answers, the reason saying what happened; one failed try is not a failure; off is + # kept and stops the trying; a choice that cannot be kept still uses the mirrors for this run + mkdir -p "$mt/bin" + printf '#!/bin/sh\n[ -n "$NPM_DOWN" ] && { echo "npm error code ENOTFOUND" >&2; exit 1; }; exit 0\n' > "$mt/bin/npm" + printf '#!/bin/sh\nfor a; do u=$a; done\ncase "$u" in *huggingface.co*) [ -n "$HF_DOWN" ] && exit 28; if [ -n "$HF_FLAKY" ] && [ ! -e "$HF_FLAKY" ]; then : > "$HF_FLAKY"; exit 6; fi ;; *registry.npmjs.org*) [ -n "$CURL_NPM_DOWN" ] && exit 7 ;; esac\nexit 0\n' > "$mt/bin/curl" + chmod +x "$mt/bin/npm" "$mt/bin/curl" + sed -n '/^reach() {/,/^eval "\$(python3 tools\/settings.py env/p' install.sh > "$mt/probe.sh" + probe() { (env -u npm_config_registry -u HF_ENDPOINT -u OVH_MIRROR PATH="$mt/bin:$PATH" HOME="$mh" XDG_CONFIG_HOME="$mt/$1" "${@:2}" bash -euo pipefail -c 'MIRROR=${MIRROR:-}; . "$1"; echo "now $(bin/vh settings mirror --get) ${HF_ENDPOINT:-official}"' _ "$mt/probe.sh" 2>&1 | tail -1); } + f1=$(probe p1 HF_DOWN=1); f2=$(probe p2); f3=$(probe p3 MIRROR=off HF_DOWN=1); f4=$(probe p4 HF_FLAKY="$mt/flaky"); f5=$(probe p5 CURL_NPM_DOWN=1); f6=$(probe p6 NPM_DOWN=1) + mkdir -p "$mt/ro"; chmod 555 "$mt/ro"; f7=$(probe ro HF_DOWN=1); chmod 755 "$mt/ro" + why=$(python3 -c 'import json, sys; print(json.load(open(sys.argv[1]))["mirror_why"])' "$mt/p1/ovh/settings.json" 2>&1) + why6=$(python3 -c 'import json, sys; print(json.load(open(sys.argv[1]))["mirror_why"])' "$mt/p6/ovh/settings.json" 2>&1) + if [ -s "$mt/probe.sh" ] && [ "$f1" = "now cn https://hf-mirror.com" ] && [ "$f2" = "now auto official" ] && [ "$f3" = "now off official" ] \ + && [ "$f4" = "now auto official" ] && [ "$f5" = "now auto official" ] && [ "$f6" = "now cn https://hf-mirror.com" ] && [ "$f7" = "now auto https://hf-mirror.com" ] \ + && case "$why" in "install.sh, "*": huggingface.co: it did not answer in 5 s, twice, and hf-mirror.com answered") true ;; *) false ;; esac \ + && case "$why6" in *"registry.npmjs.org: its name did not resolve, twice, and registry.npmmirror.com answered") true ;; *) false ;; esac + then ok "install.sh's probe: npmjs through npm, Hugging Face and Google's storage twice each; cn when one fails and its mirror answers, with what happened; one failed try is not a failure; off is kept; a choice it cannot keep still uses the mirrors for this run" + else bad "install.sh's probe: $f1 / $f2 / $f3 / $f4 / $f5 / $f6 / $f7 | $why | $why6"; fi + # this machine's settings file: two writers both land (deterministically: the second writes while the first holds the lock + # between its read and its write); a key given as None goes, an unknown one stays; set_mirror writes what the command writes; + # a file that is not a JSON object is kept as settings.json.bad; one of a newer version is not written over; an XDG_CONFIG_HOME + # that is not absolute is ignored; a key nested in another is not the mirror; an unwritable folder is one line, no traceback + a=$(cd "$ROOT" && XDG_CONFIG_HOME="$mt/w" HOME="$mh" python3 - <<'PY' 2>&1 +import json, os, subprocess, sys, time sys.path.insert(0, "tools"); import settings -settings.update({"mirror": "cn"}); settings.update({"mirror": None, "studio_theme": "dark"}) -d = json.load(open(settings.path())) -print(sum(k[0] in "ab" and k[1:].isdigit() for k in d), d.get("mirror"), d.get("studio_theme"), d.get("version")) -# set_mirror writes what the command writes, and leaves a key it does not know where it was +first = ("import sys, time; sys.path.insert(0, 'tools'); import settings\n" + "with settings.locked():\n d = settings.load(); open(sys.argv[1], 'w').close(); time.sleep(1.0); d['a'] = 1; settings._write(d)\n") +flag = os.path.join(os.environ["XDG_CONFIG_HOME"], "held"); os.makedirs(os.environ["XDG_CONFIG_HOME"], exist_ok=True) +pa = subprocess.Popen([sys.executable, "-c", first, flag]) +while not os.path.exists(flag): time.sleep(0.01) +settings.update({"b": 1}); pa.wait() +d = json.load(open(settings.path())); out = [d.get("a"), d.get("b")] +settings.update({"mirror": "cn"}); settings.update({"mirror": None, "studio_theme": "dark"}); d = json.load(open(settings.path())) +out += [d.get("mirror"), d.get("studio_theme"), d.get("version")] mine = settings.set_mirror("cn", "a test"); subprocess.run([sys.executable, "tools/settings.py", "mirror", "off"], capture_output=True) cmd_off = {k: v for k, v in json.load(open(settings.path())).items() if k.startswith("mirror")} settings.set_mirror("off"); fn_off = {k: v for k, v in json.load(open(settings.path())).items() if k.startswith("mirror")} -subprocess.run([sys.executable, "tools/settings.py", "mirror", "cn", "--why", "a test"], capture_output=True) -cmd_cn = {k: v for k, v in json.load(open(settings.path())).items() if k.startswith("mirror")} -last = settings.set_mirror("auto") -print(mine.get("mirror"), mine.get("mirror_why"), cmd_off == fn_off, cmd_cn == {k: v for k, v in mine.items() if k.startswith("mirror")}, - "mirror" in last, last.get("studio_theme"), last.get("a0")) +out += [mine.get("mirror"), cmd_off == fn_off] +p = settings.path(); p.write_text('{"mirror": "cn", "studio_theme": "da'); r = subprocess.run([sys.executable, "tools/settings.py", "mirror", "auto"], capture_output=True, text=True) +out += [p.with_name("settings.json.bad").read_text().startswith('{"mirror": "cn"'), "kept as settings.json.bad" in r.stderr, settings.mirror()] +p.write_text('{"version": 2, "mirror": "off"}'); r = subprocess.run([sys.executable, "tools/settings.py", "mirror", "cn"], capture_output=True, text=True) +out += [r.returncode, json.loads(p.read_text())["version"], "newer" in r.stderr] +p.write_text('{"version": 1, "x": {"mirror": "cn"}}'); out += [subprocess.run(["bash", "bin/vh", "settings", "mirror", "--get"], capture_output=True, text=True).stdout.strip()] +clean = {k: v for k, v in os.environ.items() if k not in ("OVH_MIRROR", *(r["variable"] for r in settings.mirrors() if r["variable"]))} +out += [all(v is None for v in json.loads(subprocess.run(["bash", "bin/vh", "settings", "--json"], capture_output=True, text=True, env=clean).stdout)["environment"].values())] +out += [str(settings.path()).startswith(os.environ["XDG_CONFIG_HOME"]), + subprocess.run([sys.executable, "-c", "import sys; sys.path.insert(0, 'tools'); import settings; print(settings.path())"], + capture_output=True, text=True, env=dict(os.environ, XDG_CONFIG_HOME="rel")).stdout.strip() == os.path.join(os.environ["HOME"], ".config/ovh/settings.json")] +ro = os.path.join(os.environ["XDG_CONFIG_HOME"], "..", "ro2"); os.makedirs(ro); os.chmod(ro, 0o555) +r = subprocess.run([sys.executable, "tools/settings.py", "mirror", "cn"], capture_output=True, text=True, env=dict(os.environ, XDG_CONFIG_HOME=os.path.abspath(ro))) +os.chmod(ro, 0o755); out += [r.returncode, "Traceback" in r.stderr, "could not be kept" in r.stderr] +print(*out) PY ) - if [ "$a" = "120 None dark 1 -cn a test True True False dark 0" ]; then ok "settings: two writers at once both land (a lock, a fresh read, a merge); a key given as None goes, the others stay; set_mirror writes what bin/vh settings mirror writes, other keys untouched" - else bad "settings with two writers: $a"; fi + if [ "$a" = "1 1 None dark 1 cn True True True auto 1 2 True auto True True True 1 False True" ] + then ok "settings: two writers both land (the second waits for the first's lock); None takes a key out, an unknown one stays; set_mirror writes what the command writes; a broken file kept as .bad; a newer version not written over; one reader (a nested key is not the mirror); a relative XDG_CONFIG_HOME ignored; an unwritable folder one line" + else bad "settings: $a"; fi + # the help prints the whole header; a project made under cn records the mirror in its own lockfile, so no committed one may + x=$(bash install.sh -h); lk=$(git ls-files '*package-lock.json' | xargs grep -l 'npmmirror\|tuna.tsinghua\|hf-mirror' 2>/dev/null) + if case "$x" in *"--mirror cn|off"*"the first bin/vh tts with the default qwen provider"*"every bin/vh new short, promo, data or meme"*"Getting Started"*) true ;; *) false ;; esac && [ -z "$lk" ] + then ok "install.sh -h prints its whole header; no committed lockfile names a mirror" + else bad "install.sh -h or a lockfile with a mirror in it: $(printf '%s' "$x" | tail -2) | $lk"; fi rm -rf "$mt" # recipes sample: bad usage exits 2 before any render (an unknown id, a sequence, an unknown style); list --json names # the sheet a recipe carries (recipes check, above, holds every sketch to its sheet) diff --git a/tools/commands.json b/tools/commands.json index f83dcf7c..ca69832f 100644 --- a/tools/commands.json +++ b/tools/commands.json @@ -128,12 +128,12 @@ "writes": ["$XDG_CONFIG_HOME/ovh/settings.json (~/.config/ovh/settings.json)", "~/.cache/hyperframes/chrome (mirror cn: HyperFrames' Chrome from the mirror)"], "usage": [ { - "synopsis": "settings [--json] | settings mirror cn|off|auto [--why TEXT] | settings mirror --get | settings chrome", + "synopsis": "settings [--json] | settings mirror cn|off|auto [--why TEXT] | settings mirror --get | settings chrome [project]", "text": [ - "what this machine's settings are and where they are kept; mirror cn: every later download a command starts comes from the", + "what this machine's settings are and where they are kept; mirror cn: the downloads a command starts come from the", "mainland-China mirrors in tools/mirrors.txt (npm, uv, Hugging Face, Electron; HyperFrames' Chrome fetched from the mirror", - "now, as HyperFrames cannot be pointed at one; settings chrome does only that), off: never, auto: the official sources", - "(install.sh tries them first)" + "now, as HyperFrames cannot be pointed at one; settings chrome [project] does only that), a source of your own stays;", + "off: never, auto: the official sources (install.sh tries them first)" ] } ] diff --git a/tools/doctor.py b/tools/doctor.py index 64711724..3dcc1d78 100644 --- a/tools/doctor.py +++ b/tools/doctor.py @@ -628,7 +628,7 @@ def cache_homes(has_chrome=False): ("HyperFrames", env("HYPERFRAMES_FONT_CACHE_DIR") or str(home("~/.cache/hyperframes/fonts")), "the fonts a film asks for; its Chrome is already there", "HYPERFRAMES_FONT_CACHE_DIR=") if has_chrome else ("HyperFrames", str(home("~/.cache/hyperframes")), "its Chrome on a first snapshot or render, about 200 MB, and its fonts", - "no setting moves it: let the sandbox write it, or fetch the Chrome once outside the sandbox (npx hyperframes browser ensure) " + "no setting moves it: let the sandbox write it, or fetch the Chrome once outside the sandbox (" + ("bin/vh settings chrome" if os.environ.get("OVH_MIRROR") == "cn" else "npx hyperframes browser ensure") + ") " "and give the fonts HYPERFRAMES_FONT_CACHE_DIR="), ("bin/vh", os.path.join(xdg, "ovh"), "the font index of fonts and textcheck, HyperFrames' registry list", "XDG_CACHE_HOME="), ] @@ -994,7 +994,10 @@ def main(argv): print_module(m, r) print("- every bin/vh new short|promo|data|meme installs its own pinned HyperFrames into the project (about 140 MB of node_modules)") if first: - print(f" still to come on first use: {', '.join(first)} (wiki: Getting Started; mirrors behind a slow or blocked network: wiki China-Network / 国内网络)") + mirrored = os.environ.get("OVH_MIRROR") == "cn" + print(f" still to come on first use: {', '.join(first)} (wiki: Getting Started; " + + ("from the mainland-China mirrors, as this machine's settings say: bin/vh settings)" if mirrored else + "mirrors behind a slow or blocked network: bin/vh settings mirror cn, wiki China-Network / 国内网络)")) if not a["probe"]: print(" bin/vh doctor --probe: also call each service with a key once, at an endpoint that costs nothing") return 0 diff --git a/tools/mirrors.txt b/tools/mirrors.txt index 3c2a8785..32508f34 100644 --- a/tools/mirrors.txt +++ b/tools/mirrors.txt @@ -1,14 +1,25 @@ # Download mirrors for a network where the official sources do not answer (mainland China), in one place. -# install.sh tries the official npm registry first (5 s); only when it does not answer and the mirror does, this machine's -# settings get "mirror": "cn" ($XDG_CONFIG_HOME/ovh/settings.json, tools/settings.py), and from then on bin/vh exports the -# variables below with the mirror column, so every later download goes there: npm (project packages, Studio's app and its -# agent adapters), uv (Python packages, a Python build), Hugging Face (the local voice), Electron, and HyperFrames' Chrome, -# which bin/vh fetches from the mirror itself because HyperFrames has no setting for it. A variable you set yourself wins. +# install.sh tries the official npm registry (through npm), Hugging Face and Google's storage first (twice each, 5 s a try); +# only when one does not answer and its mirror does, this machine's settings get "mirror": "cn" ($XDG_CONFIG_HOME/ovh/ +# settings.json, tools/settings.py), and from then on bin/vh exports the variables below with the mirror column for +# everything it runs (the agents Studio starts too, so their own npm or uv goes there as well): npm (project packages, +# Studio's app and its agent adapters), uv (Python packages, a Python build), Hugging Face (the local voice), Electron, and +# HyperFrames' Chrome, which bin/vh fetches from the mirror itself because HyperFrames has no setting for it. A source you set +# yourself stays yours: the variable in your environment, npm's registry in an .npmrc, uv's index in a uv.toml. # install.sh --mirror cn uses them without trying, --mirror off never; bin/vh settings mirror cn|off|auto changes it later. -# The checks the tools already make stay as they are, and do not trust the mirror: npm ci checks each package against the -# lockfile's hash; Electron's download is checked against the checksums.json its npm package ships (itself under that -# hash). uv's packages, the Hugging Face model, a Python build and Chrome have no hash pinned here: they are taken as the -# mirror serves them over https, as they are taken from the official source. +# Not covered (they still go to the official place): the git clone itself and references/fetch.sh (GitHub), install.sh +# --obscura (GitHub releases), bin/vh hf add (HyperFrames' registry), bin/vh hdri (Poly Haven), and the Google Fonts that +# ClaudeAnimationBase's studio.html loads. +# What still checks a download, mirror or not, and what the mirror is trusted with: +# - checked: npm ci where a lockfile is (styles/_swatch, Studio's Electron shell, the agent adapters, ClaudeAnimationBase) +# checks each package against the lockfile's hash; Electron's zip is checked against the checksums.json its npm package +# ships (itself under that hash); uv checks a Python build against the sha256 built into uv (a substituted archive from a +# mirror folder is refused, tried 2026-11-22). +# - trusted to the mirror, wholly, as it is to npmjs.org today: what has no lockfile. bin/vh new's npm i -D hyperframes@ +# and gsap with what they bring, npx --yes hyperframes@ (bin/vh hf), the @puppeteer/browsers a folder without +# HyperFrames' node_modules runs (pinned to a version, not a hash): their packages and the hashes they are checked +# against both come from the mirror. So do uv's packages (uv run --with …, not pinned), the Hugging Face model, and +# HyperFrames' Chrome (no hash is pinned for it anywhere): over https, as from the official source. # # kind variable official (tried first) mirror (cn) who runs the mirror npm npm_config_registry https://registry.npmjs.org https://registry.npmmirror.com npmmirror.com, run by the cnpm project diff --git a/tools/readcheck.py b/tools/readcheck.py index 70d2a7c6..8af37198 100644 --- a/tools/readcheck.py +++ b/tools/readcheck.py @@ -525,8 +525,10 @@ def check_hint(a, out): def canvas_texts(html, out, browser, force=False): """Export the live registry; texts.mjs owns exclusive creation so two writers cannot silently replace each other.""" if not browser: # "": bin/vh looked and found none; None: run without bin/vh - raise ValueError("canvas-film needs a headless Chrome: " + ("npx hyperframes browser ensure (in a HyperFrames project), " - "install Chrome or Chromium, or set CHROME_PATH" if browser == "" else "run it as bin/vh readcheck, or pass --browser ")) + get = ("bin/vh settings chrome (from the mirror)" if os.environ.get("OVH_MIRROR") == "cn" + else "npx hyperframes browser ensure (in a HyperFrames project)") + raise ValueError("canvas-film needs a headless Chrome: " + (f"{get}, install Chrome or Chromium, or set CHROME_PATH" if browser == "" + else "run it as bin/vh readcheck, or pass --browser ")) cmd = ["node", str(Path(__file__).resolve().parent / "film" / "texts.mjs"), str(html), "--browser", browser, "--out", str(out)] + (["--force"] if force else []) proc = subprocess.Popen(cmd) diff --git a/tools/schemas/output/settings.schema.json b/tools/schemas/output/settings.schema.json index ad29f391..f1f25022 100644 --- a/tools/schemas/output/settings.schema.json +++ b/tools/schemas/output/settings.schema.json @@ -2,9 +2,9 @@ "$schema": "https://json-schema.org/draft/2020-12/schema", "$id": "https://github.com/ZLHad/OpenVideoHarness/tools/schemas/output/settings.schema.json", "title": "bin/vh settings --json", - "description": "This machine's own settings (tools/settings.py: $XDG_CONFIG_HOME/ovh/settings.json), the mirror in effect, the mirror table (tools/mirrors.txt) and the mirror variables as bin/vh exported them.", + "description": "This machine's own settings (tools/settings.py: $XDG_CONFIG_HOME/ovh/settings.json), the mirror in effect, the mirror table (tools/mirrors.txt), the mirror variables as bin/vh exported them, and the sources of the person's own that bin/vh leaves alone with cn.", "type": "object", - "required": ["version", "tool", "file", "settings", "mirror", "mirrors", "environment"], + "required": ["version", "tool", "file", "settings", "mirror", "mirrors", "environment", "kept_own"], "properties": { "version": {"enum": [1]}, "tool": {"type": "string"}, @@ -25,6 +25,10 @@ } } }, - "environment": {"type": "object"} + "environment": {"type": "object"}, + "kept_own": { + "type": "array", + "items": {"type": "object", "required": ["kind", "why"], "properties": {"kind": {"type": "string"}, "why": {"type": "string"}}} + } } } diff --git a/tools/settings.py b/tools/settings.py index 3fb2f6a0..51375c80 100644 --- a/tools/settings.py +++ b/tools/settings.py @@ -2,53 +2,78 @@ usage: bin/vh settings [--json] what they are now, and where they are kept bin/vh settings mirror cn|off|auto [--why TEXT] the download mirrors (tools/mirrors.txt): - cn every later download comes from the mainland-China mirrors (bin/vh exports their variables) + cn later downloads come from the mainland-China mirrors (bin/vh exports their variables for everything + it runs, the agents Studio starts included) off never: the official sources, and install.sh does not try the mirrors either - auto the official sources; install.sh tries the official npm registry once and switches to cn when it - does not answer and the mirror does (the default: no "mirror" key) + auto the official sources; install.sh tries the official npm registry, Hugging Face and Google's storage + (Chrome) and switches to cn when one does not answer twice and its mirror does (the default: no + "mirror" key) bin/vh settings mirror --get cn, off or auto, alone on a line - bin/vh settings chrome with the mirrors on, HyperFrames' Chrome from the mirror now when it + bin/vh settings chrome [project] with the mirrors on, HyperFrames' Chrome from the mirror now when it is not here (HyperFrames has no setting for where it downloads it; - bin/vh new and settings mirror cn do this by themselves) - python3 tools/settings.py env the lines bin/vh and install.sh run to use the mirrors - (export NAME=value; none when the mirror is not cn, or for a - variable already set) - -Kept in $XDG_CONFIG_HOME/ovh/settings.json (~/.config/ovh/settings.json): one file per machine, outside every clone, so a -git pull, a second clone or Studio's settings panel see the same values. Never a key or a token: those stay in the -environment (LOCAL.md names them, never their values). Shape, "version": 1 (keys only added, never renamed; a key -this file does not know is kept as it is when another is written): + bin/vh new, render, hf, frames and settings mirror cn do this by + themselves); project: that project's HyperFrames, else styles/_swatch's + python3 tools/settings.py env [--mode cn] the lines bin/vh and install.sh run (export NAME=value, unset NAME): + with cn, the mirror variables; otherwise none, and the ones bin/vh + exported before (inherited: OVH_MIRROR=cn) taken out again + +Kept in $XDG_CONFIG_HOME/ovh/settings.json (~/.config/ovh/settings.json; an XDG_CONFIG_HOME that is not an absolute path +is ignored, as the XDG spec says): one file per machine, outside every clone, so a git pull, a second clone or Studio's +settings panel see the same values. Never a key or a token: those stay in the environment (LOCAL.md names them, never their +values). Shape, "version": 1 (keys only added, never renamed; a key this file does not know is kept as it is when another +is written): {"version": 1, "mirror": "cn" | "off", absent: auto - "mirror_why": "…", who set it and why, in a sentence (install.sh's probe says what did not answer) + "mirror_why": "…", who set it and why, in a sentence (install.sh's probe says what did not answer, and how) "mirror_at": "YYYY-MM-DD"} -In-process (Studio): update(patch: dict) -> dict and set_mirror(mode, why=None) -> dict; load() reads, path() says where. +In-process (Studio): update(patch: dict) -> dict and set_mirror(mode, why=None) -> dict; load() reads, path() says where; +env_changes(environ) -> {NAME: value, or None to take it out}: what a long-lived process (Studio's server) applies to its own +environment after a change, so the agents it starts next follow it (bin/vh itself works it out again on every run). Every write goes through update(patch): under a lock (settings.json.lock), it reads the file as it is now, sets the keys it was given (None takes one out), keeps all the others, and writes the whole file to a temporary file moved into place, -so two writers at once (Studio and a terminal) both land and a reader never sees half a file. +so two writers at once (Studio and a terminal) both land and a reader never sees half a file. A file that is not a JSON +object (cut short, edited by hand) is kept beside it as settings.json.bad, said, and a fresh one written; a file of a newer +"version" is never written over (Newer). A folder it cannot write to raises OSError; the commands say so in one line. +A variable the person set stays theirs: one set in the environment (an empty one counts as not set), and npm's registry +set in an .npmrc (the person's, the project's, the global one) or uv's default index or Python mirror set in a uv.toml or +pyproject.toml, when it names a source other than the official one and the mirror: bin/vh then does not export that +one, and bin/vh settings says so. """ -import contextlib, datetime, fcntl, json, os, sys, tempfile +import contextlib, datetime, fcntl, json, os, re, shlex, shutil, sys, tempfile from pathlib import Path ROOT = Path(__file__).resolve().parent.parent MODES = ("cn", "off", "auto") +VERSION = 1 + + +class Newer(Exception): + """The file was written by a newer OpenVideoHarness ("version" above VERSION): not written over.""" def path(): - return Path(os.environ.get("XDG_CONFIG_HOME") or Path.home() / ".config") / "ovh" / "settings.json" + x = os.environ.get("XDG_CONFIG_HOME") or "" + return Path(x if os.path.isabs(x) else Path.home() / ".config") / "ovh" / "settings.json" -def load(): - """The settings as kept, or {"version": 1} (none yet, or a file that is not a JSON object: said on stderr).""" +def _read(): + """→ (the settings as kept, or None when there is no file, or "bad" when it is not a JSON object, with why).""" p = path() try: d = json.loads(p.read_text(encoding="utf-8")) except FileNotFoundError: - return {"version": 1} + return None, None except (OSError, ValueError) as e: - print(f"bin/vh settings: {p} is not readable JSON ({e}); taken as empty", file=sys.stderr) - return {"version": 1} - return d if isinstance(d, dict) else {"version": 1} + return "bad", str(e) + return (d, None) if isinstance(d, dict) else ("bad", f"a JSON {type(d).__name__}, not an object") + + +def load(): + """The settings as kept, or {"version": 1} (none yet, or a file that is not a JSON object: said on stderr).""" + d, why = _read() + if d == "bad": + print(f"bin/vh settings: {path()} is not readable ({why}); taken as empty", file=sys.stderr) + return d if isinstance(d, dict) else {"version": VERSION} @contextlib.contextmanager @@ -69,7 +94,7 @@ def _write(d): fd, tmp = tempfile.mkstemp(prefix=".settings.", suffix=".tmp", dir=p.parent) try: with os.fdopen(fd, "w", encoding="utf-8") as f: - f.write(json.dumps(dict(d, version=1), ensure_ascii=False, indent=2) + "\n") + f.write(json.dumps(dict(d, version=VERSION), ensure_ascii=False, indent=2) + "\n") os.replace(tmp, p) finally: if os.path.exists(tmp): @@ -79,9 +104,20 @@ def _write(d): def update(patch): """The one way to write: under the lock, read the file as it is now, set each key of patch (None takes a key out), keep every other key (another writer's, or one this code does not know), and write the whole file to a temp file moved into - place. → the settings as written. Studio's settings panel and bin/vh settings both go through it.""" + place. → the settings as written. A file that is not a JSON object is kept as settings.json.bad first (said on stderr); + one of a newer version raises Newer and stays as it is. Studio's settings panel and bin/vh settings both go through it.""" with locked(): - d = load() + d, why = _read() + if d == "bad": + bad = path().with_name("settings.json.bad") + shutil.copyfile(path(), bad) + print(f"bin/vh settings: {path()} was not readable ({why}); kept as {bad.name} beside it, and a new one written", + file=sys.stderr) + d = {} + d = d or {} + if isinstance(d.get("version"), int) and d["version"] > VERSION: + raise Newer(f"{path()} was written by a newer OpenVideoHarness (version {d['version']}): it is left as it is; " + "update this clone (git pull) to change it") for k, v in patch.items(): if k == "version": continue @@ -90,14 +126,14 @@ def update(patch): else: d[k] = v _write(d) - return d + return dict(d, version=VERSION) def set_mirror(mode, why=None): """The mirror setting, as bin/vh settings mirror [--why TEXT] writes it, through update(), saying nothing (Studio's - settings panel calls it in-process; main() calls it and does the saying). mode: cn, off or auto (auto takes the keys - out). → the settings as written. It does not fetch HyperFrames' Chrome from the mirror: bin/vh settings mirror cn and - bin/vh new do that (bin/vh settings chrome alone).""" + settings panel calls it in-process, then applies env_changes() to its own environment; main() calls it and does the + saying). mode: cn, off or auto (auto takes the keys out). → the settings as written. It does not fetch HyperFrames' + Chrome from the mirror: bin/vh settings mirror cn and bin/vh new do that (bin/vh settings chrome alone).""" if mode not in MODES: raise ValueError(f"mirror: {mode!r} is not one of {', '.join(MODES)}") on = mode != "auto" @@ -126,16 +162,130 @@ def mirrors(): return rows -def env_lines(environ=os.environ): - """export lines for the mirror variables, when the mirror is cn; a variable already set (by the person) is left.""" - if mirror() != "cn": - return [] - out = [f"export {r['variable']}={r['mirror']}" for r in mirrors() if r["variable"] and not environ.get(r["variable"])] - return out + ["export OVH_MIRROR=cn"] +def _same(a, b): + return a.rstrip("/").lower() == b.rstrip("/").lower() + + +def _upward(cwd, names): + """The files of these names in cwd and every folder above it, nearest first.""" + d, out = Path(cwd).resolve(), [] + while True: + out += [d / n for n in names if (d / n).is_file()] + if d.parent == d: + return out + d = d.parent + + +def _ini(p, key): # the value of key=… in an .npmrc (the last one counts, as npm reads it) + v = None + try: + for line in p.read_text(encoding="utf-8", errors="replace").splitlines(): + m = re.match(r"\s*" + re.escape(key) + r"\s*=\s*(\S+)", line) + if m: + v = m.group(1).strip("'\"") + except OSError: + pass + return v + + +def _toml_url(p, keys): # a uv setting in a uv.toml or pyproject.toml ([tool.uv]): index-url, default-index, a default [[index]] + try: + text = p.read_text(encoding="utf-8", errors="replace") + except OSError: + return None + if p.name == "pyproject.toml" and "[tool.uv" not in text: + return None + for k in keys: + m = re.search(r'(?m)^\s*' + re.escape(k) + r'\s*=\s*["\']([^"\']+)["\']', text) + if m: + return m.group(1) + if "default-index" in keys: + for block in re.split(r"(?m)^\s*\[\[(?:tool\.uv\.)?index\]\]\s*$", text)[1:]: + block = re.split(r"(?m)^\s*\[", block)[0] + if re.search(r"(?m)^\s*default\s*=\s*true", block): + m = re.search(r'(?m)^\s*url\s*=\s*["\']([^"\']+)["\']', block) + if m: + return m.group(1) + return None + + +def own_config(row, environ=os.environ, cwd=None): + """Where the person's own tool configuration names a source of its own for this kind of download (not the official + one, not the mirror): → "a sentence: the value, from which file", or None.""" + cwd = cwd or os.getcwd(); home = Path(environ.get("HOME") or Path.home()) + def other(v): + return v and not _same(v, row["official"]) and not _same(v, row["mirror"]) + if row["kind"] in ("npm", "electron"): + key = "registry" if row["kind"] == "npm" else "electron_mirror" + node = shutil.which("node", path=environ.get("PATH")) + files = _upward(cwd, [".npmrc"]) + [Path(environ.get("NPM_CONFIG_USERCONFIG") or home / ".npmrc")] + files += [Path(environ["NPM_CONFIG_GLOBALCONFIG"])] if environ.get("NPM_CONFIG_GLOBALCONFIG") else \ + ([Path(node).resolve().parent.parent / "etc" / "npmrc"] if node else []) + for f in files: + v = _ini(f, key) if f.is_file() else None + if v is not None: # the nearest one npm reads wins + return f"{v} (npm's {key}, from {f})" if other(v) else None + if row["kind"] in ("pypi", "python"): + keys = ("index-url", "default-index") if row["kind"] == "pypi" else ("python-install-mirror",) + xdg = environ.get("XDG_CONFIG_HOME") or "" + user = Path(xdg if os.path.isabs(xdg) else home / ".config") / "uv" / "uv.toml" + for f in _upward(cwd, ["uv.toml", "pyproject.toml"]) + [user, Path("/etc/uv/uv.toml")]: + v = _toml_url(f, keys) if f.is_file() else None + if v: + return f"{v} (uv's {keys[0]}, from {f})" if other(v) else None + if row["kind"] == "pypi" and environ.get("UV_INDEX_URL"): # uv's older name for the same setting + return f"{environ['UV_INDEX_URL']} (UV_INDEX_URL)" + return None + + +def env_changes(environ=os.environ, mode=None, cwd=None): + """What bin/vh (and install.sh, and Studio's server) does to its environment for the mirror setting: {NAME: value to + export, or None to take out}. With cn: each mirror variable not set by the person (unset or empty, or already the + mirror's value) and not named by their own npm or uv configuration, and OVH_MIRROR=cn. Otherwise, only when the + environment came from a bin/vh run under cn (OVH_MIRROR=cn inherited): OVH_MIRROR, and each mirror variable that + still holds exactly the mirror's value, taken out; nothing else is touched.""" + mode = mode or mirror() + out = {} + if mode == "cn": + for r in mirrors(): + v = r["variable"] + if v and (not environ.get(v) or environ.get(v) == r["mirror"]) and not own_config(r, environ, cwd): + if environ.get(v) != r["mirror"]: + out[v] = r["mirror"] + if environ.get("OVH_MIRROR") != "cn": + out["OVH_MIRROR"] = "cn" + return out + if environ.get("OVH_MIRROR"): + out["OVH_MIRROR"] = None + for r in mirrors(): + if r["variable"] and environ.get(r["variable"]) == r["mirror"]: + out[r["variable"]] = None + return out + + +def env_lines(environ=os.environ, mode=None): + """env_changes() as shell lines: export NAME=value, unset NAME.""" + return [f"export {k}={shlex.quote(v)}" if v is not None else f"unset {k}" for k, v in env_changes(environ, mode).items()] + + +def kept_own(environ=os.environ): + """With cn, the mirror variables bin/vh leaves alone because the person set them: [(kind, why)].""" + out = [] + for r in mirrors(): + if not r["variable"]: + continue + mine = environ.get(r["variable"]) + if mine and mine != r["mirror"]: + out.append((r["kind"], f"{mine} ({r['variable']}, set in the environment)")) + else: + o = own_config(r, environ) + if o: + out.append((r["kind"], o)) + return out def in_effect(environ=os.environ): - """The mirror variables as this process has them (bin/vh exports them before it runs a tool): {name: value or None}.""" + """The mirror variables as this process has them (bin/vh works them out before it runs a tool): {name: value or None}.""" return {r["variable"]: environ.get(r["variable"]) for r in mirrors() if r["variable"]} @@ -147,24 +297,31 @@ def operators(): def show(d, as_json=False): m = mirror(d) + own = kept_own() if m == "cn" else [] if as_json: print(json.dumps({"version": 1, "tool": "bin/vh settings", "file": str(path()), "settings": d, "mirror": m, - "mirrors": mirrors(), "environment": in_effect()}, ensure_ascii=False, indent=1)) + "mirrors": mirrors(), "environment": in_effect(), "kept_own": [{"kind": k, "why": w} for k, w in own]}, + ensure_ascii=False, indent=1)) return print(f"this machine's settings: {path()}" + ("" if path().exists() else " (not written yet: the defaults)")) - said = {"cn": "the mainland-China mirrors, for every download (tools/mirrors.txt)", + said = {"cn": "the mainland-China mirrors, for the downloads tools/mirrors.txt lists", "off": "the official sources; install.sh does not try the mirrors", - "auto": "the official sources; install.sh switches to the mirrors when the official npm registry does not answer"}[m] + "auto": "the official sources; install.sh switches to the mirrors when an official source does not answer and its mirror does"}[m] print(f" mirror {m}: {said}" + (f" · {d['mirror_why']}" if d.get("mirror_why") else "") + (f" ({d['mirror_at']})" if d.get("mirror_at") else "")) + for k, w in own: + print(f" {k}: your own source stays, {w}") print(" bin/vh settings mirror cn|off|auto changes it") def main(argv): if argv[:1] in (["-h"], ["--help"]): print(__doc__.strip()); return 0 - if argv == ["env"]: - print("\n".join(env_lines())); return 0 + if argv[:1] == ["env"]: + mode = argv[2] if argv[1:2] == ["--mode"] and len(argv) == 3 and argv[2] in MODES else None + if len(argv) > 1 and mode is None: + print("usage: python3 tools/settings.py env [--mode cn|off|auto]", file=sys.stderr); return 2 + print("\n".join(env_lines(mode=mode))); return 0 if not argv or argv == ["--json"]: show(load(), bool(argv)); return 0 if argv[0] == "mirror": @@ -172,10 +329,17 @@ def main(argv): print(mirror()); return 0 if len(argv) < 2 or argv[1] not in MODES or (len(argv) > 2 and (argv[2] != "--why" or len(argv) != 4)): print("usage: bin/vh settings mirror cn|off|auto [--why TEXT] (or --get)", file=sys.stderr); return 2 - set_mirror(argv[1], argv[3] if len(argv) == 4 else None) + try: + set_mirror(argv[1], argv[3] if len(argv) == 4 else None) + except Newer as e: + print(f"✗ {e}", file=sys.stderr); return 1 + except OSError as e: + print(f"✗ the choice could not be kept in {path()} ({e.strerror or e}): nothing changed", file=sys.stderr); return 1 if argv[1] == "cn": print(f"✓ downloads now come from the mainland-China mirrors ({operators()}; tools/mirrors.txt), kept in {path()};" " bin/vh settings mirror off turns that off") + for k, w in kept_own(): + print(f" {k}: your own source stays, {w}") else: print(f"✓ downloads come from the official sources{'' if argv[1] == 'auto' else ', and install.sh does not try the mirrors'} (kept in {path()})") return 0 diff --git a/tools/status.py b/tools/status.py index 18aadc45..93288462 100644 --- a/tools/status.py +++ b/tools/status.py @@ -534,6 +534,10 @@ def hf_pin(project): return None +def chrome_fetch(project): # how to fetch HyperFrames' Chrome beforehand: from the mirror when it is on (bin/vh exports OVH_MIRROR) + return f"bin/vh settings chrome {shown(project)}" if os.environ.get("OVH_MIRROR") == "cn" else f"(cd {shown(project)} && npx hyperframes browser ensure)" + + def hf_chrome_note(project, proj): """HyperFrames' first snapshot or render downloads its own Chrome (chrome-headless-shell, about 200 MB, into ~/.cache/hyperframes, which it finds from the home folder) and shows nothing while it does: the words that say so, or "" once @@ -559,7 +563,7 @@ def wanted(folder): # bin/vh's shell_folder: the pinned version (any when ther except OSError: pass return (f" (HyperFrames' first snapshot or render downloads its Chrome first, about 200 MB into ~/.cache/hyperframes, with nothing" - f" shown; (cd {shown(project)} && npx hyperframes browser ensure) fetches it beforehand and shows the download)") + f" shown; {chrome_fetch(project)} fetches it beforehand and shows the download)") def engine_docs(project, proj): From f5cbf1823b08063b86c7c898ad8109432df2a98b Mon Sep 17 00:00:00 2001 From: zhanglinghao Date: Sun, 22 Nov 2026 05:53:25 +0800 Subject: [PATCH 13/19] settings.py says the installer, not its file name: bin/vh runs it on every start, so a file it names reaches every CI group --- tools/settings.py | 16 ++++++++-------- 1 file changed, 8 insertions(+), 8 deletions(-) diff --git a/tools/settings.py b/tools/settings.py index 51375c80..c0dfd70c 100644 --- a/tools/settings.py +++ b/tools/settings.py @@ -4,8 +4,8 @@ bin/vh settings mirror cn|off|auto [--why TEXT] the download mirrors (tools/mirrors.txt): cn later downloads come from the mainland-China mirrors (bin/vh exports their variables for everything it runs, the agents Studio starts included) - off never: the official sources, and install.sh does not try the mirrors either - auto the official sources; install.sh tries the official npm registry, Hugging Face and Google's storage + off never: the official sources, and the installer does not try the mirrors either + auto the official sources; the installer tries the official npm registry, Hugging Face and Google's storage (Chrome) and switches to cn when one does not answer twice and its mirror does (the default: no "mirror" key) bin/vh settings mirror --get cn, off or auto, alone on a line @@ -13,7 +13,7 @@ is not here (HyperFrames has no setting for where it downloads it; bin/vh new, render, hf, frames and settings mirror cn do this by themselves); project: that project's HyperFrames, else styles/_swatch's - python3 tools/settings.py env [--mode cn] the lines bin/vh and install.sh run (export NAME=value, unset NAME): + python3 tools/settings.py env [--mode cn] the lines bin/vh and the installer run (export NAME=value, unset NAME): with cn, the mirror variables; otherwise none, and the ones bin/vh exported before (inherited: OVH_MIRROR=cn) taken out again @@ -24,7 +24,7 @@ is written): {"version": 1, "mirror": "cn" | "off", absent: auto - "mirror_why": "…", who set it and why, in a sentence (install.sh's probe says what did not answer, and how) + "mirror_why": "…", who set it and why, in a sentence (the installer's probe says what did not answer, and how) "mirror_at": "YYYY-MM-DD"} In-process (Studio): update(patch: dict) -> dict and set_mirror(mode, why=None) -> dict; load() reads, path() says where; env_changes(environ) -> {NAME: value, or None to take it out}: what a long-lived process (Studio's server) applies to its own @@ -239,7 +239,7 @@ def other(v): def env_changes(environ=os.environ, mode=None, cwd=None): - """What bin/vh (and install.sh, and Studio's server) does to its environment for the mirror setting: {NAME: value to + """What bin/vh (and the installer, and Studio's server) does to its environment for the mirror setting: {NAME: value to export, or None to take out}. With cn: each mirror variable not set by the person (unset or empty, or already the mirror's value) and not named by their own npm or uv configuration, and OVH_MIRROR=cn. Otherwise, only when the environment came from a bin/vh run under cn (OVH_MIRROR=cn inherited): OVH_MIRROR, and each mirror variable that @@ -305,8 +305,8 @@ def show(d, as_json=False): return print(f"this machine's settings: {path()}" + ("" if path().exists() else " (not written yet: the defaults)")) said = {"cn": "the mainland-China mirrors, for the downloads tools/mirrors.txt lists", - "off": "the official sources; install.sh does not try the mirrors", - "auto": "the official sources; install.sh switches to the mirrors when an official source does not answer and its mirror does"}[m] + "off": "the official sources; the installer does not try the mirrors", + "auto": "the official sources; the installer switches to the mirrors when an official source does not answer and its mirror does"}[m] print(f" mirror {m}: {said}" + (f" · {d['mirror_why']}" if d.get("mirror_why") else "") + (f" ({d['mirror_at']})" if d.get("mirror_at") else "")) for k, w in own: @@ -341,7 +341,7 @@ def main(argv): for k, w in kept_own(): print(f" {k}: your own source stays, {w}") else: - print(f"✓ downloads come from the official sources{'' if argv[1] == 'auto' else ', and install.sh does not try the mirrors'} (kept in {path()})") + print(f"✓ downloads come from the official sources{'' if argv[1] == 'auto' else ', and the installer does not try the mirrors'} (kept in {path()})") return 0 print(f"bin/vh settings: unknown {' '.join(argv)} (bin/vh settings -h)", file=sys.stderr) return 2 From 5ef1a46ee04346f9b3f653cabc4be72c46e3a87f Mon Sep 17 00:00:00 2001 From: zhanglinghao Date: Sun, 22 Nov 2026 06:16:14 +0800 Subject: [PATCH 14/19] Settings page, after review: the file decides what shows, a new chat takes the default agent, folders can be opened - The console writes Studio's look and language into the page it serves (no flip after the first paint); the language and look buttons are drawn from the settings file and every click saves; radio groups are one tab stop with arrow keys. - "New chat" and a new film on the space start with the default agent; the default must be an agent that is set up. - Where films are kept: only folders that exist, ~ for the home folder, each with a button that opens it (one of those folders only, $OVH_REVEAL stands in for the file browser). - LOCAL.md: only list items count, and a value's bracketed hint is left out; a model or effort that could not be written is an error, not "saved". - The rail marks the space only on the space; on the settings page the column says it is the space's chat; without this run's token the page says to open it in Studio's window, with the button that does. - Mirror: the page says that downloads Studio itself started in this run follow once it is reopened. - tools/ci-paths.txt keeps its four narrow lines: tools/settings.py says "the installer", the version comes from git, "What's new" links the release page; LOCAL.example.md also runs settings_page_checks. - Tests: the file wins over the browser's copy, the top bar's buttons save, the default agent for a new chat, the folder button, an agent not set up refused, LOCAL.md's list items. --- tools/ci-paths.txt | 4 + tools/desk/README.md | 13 +-- tools/desk/server.py | 2 + tools/desk/settings_api.py | 93 +++++++++++++++++---- tools/desk/static/agent.js | 13 ++- tools/desk/static/index.html | 3 +- tools/desk/static/settings.css | 1 + tools/desk/static/settings.js | 143 +++++++++++++++++++++------------ tools/desk/static/studio.js | 5 +- tools/desk/test_settings.py | 100 ++++++++++++++++++++--- tools/settings.py | 6 +- 11 files changed, 285 insertions(+), 98 deletions(-) diff --git a/tools/ci-paths.txt b/tools/ci-paths.txt index 2f5749e8..45108a7e 100644 --- a/tools/ci-paths.txt +++ b/tools/ci-paths.txt @@ -20,6 +20,7 @@ always static_checks doc_checks readpath_report # change notes, landing, this table and its reader changes/** plumbing_checks studio_checks land_checks +CHANGELOG.md plumbing_checks smoke_checks desk_checks studio_checks cancel_checks assets_checks scout_checks web_checks model3d_checks land_checks tools/changes.py plumbing_checks studio_checks tools/land.py land_checks tools/ci_select.py plumbing_checks @@ -32,9 +33,12 @@ ACKNOWLEDGMENTS.md CONTRIBUTING.md plumbing_checks studio_checks hdri_checks CODE_OF_CONDUCT.md SECURITY.md +CITATION.cff plumbing_checks studio_checks LICENSE hf_checks cases/** gate_checks desk_checks console_checks status_checks contract_checks cancel_checks history_checks know_checks artifacts_checks studio_checks showcase/** smoke_checks timeline_checks decision_checks web_checks model3d_checks +install.sh plumbing_checks smoke_checks desk_checks studio_checks cancel_checks assets_checks scout_checks web_checks model3d_checks +LOCAL.example.md plumbing_checks smoke_checks desk_checks studio_checks cancel_checks assets_checks scout_checks web_checks model3d_checks settings_page_checks skills/** smoke_checks cancel_checks assets_checks scout_checks web_checks model3d_checks # tools a few groups reach diff --git a/tools/desk/README.md b/tools/desk/README.md index 23514d44..22358d14 100644 --- a/tools/desk/README.md +++ b/tools/desk/README.md @@ -135,7 +135,7 @@ bin/vh desk agents install # 装那一家的 ACP 适配器 | `GET /api/p/<键>/agent//events?token=…[&after=N]` | 这个对话的事件,SSE:先一个 `hello`(会话的状态、设置、agent 报的能力),然后 `after`(或 `Last-Event-ID`)之后的每一件,再来的边到边推;每 5 秒一行注释保活。要页面的令牌 | | `POST /api/p/<键>/agent/new` | `{kind, personal, model, effort}`:开一个新对话,起好 agent,带着它的设置回来;`model`、`effort` 是人在开新对话的框里挑的(可以不带),agent 报了这个值才设、并记成这一家下次的起点,没报就不管;没装 424,起不来 503。`GET …/agents` 每一家的 `choices` 是新对话会用什么开始:`{model, effort: {value, name, from}, offered}`,`from` 是 picked(你挑过的)、default(Studio 的默认)、dsh(桌面版的推理档)、agent(它自己的),`offered` 是这次运行里它报过的选项(没见过是 null) | | `GET /api/machine` | `{lacks: [{what, state}], platform}`:这台电脑还缺什么(`bin/vh doctor --json` 读出的 FFmpeg、Node、uv、git 没有或太旧,没有画网页用的浏览器,一家 agent 适配器都没装),空间页照它出那一块;不要令牌。什么都不缺时这次运行一直记着;缺东西时,隔一分钟以上再问会重新看一次(人可能已经装上了);doctor 没说清楚时不记,回 `error` | -| `GET /api/settings`、`POST /api/settings {name, value}` | 设置页(`settings_api.py`):要令牌。GET 回 `{version: 1, file, studio, mirror, agents, local, about}`:Studio 自己的三项(`studio_lang`、`studio_theme`、`agent_default`,没设是 `null`)、下载镜像、每种 agent 装没装和新对话从什么模型和思考深度开始(`choices`,同对话列)、LOCAL.md 里人和 agent 都读的那几行(只读,模板的 `{…}` 和注释不算值)、版本。POST 只认这几个名字:`studio_lang`、`studio_theme`、`agent_default`(`null` 回到 Studio 的默认)、`mirror`(`cn`、`off`、`auto`)、`model:`、`effort:`(只认这次运行里这种 agent 在对话里给过的值,记进 `picks.json`);别的名字、值、没有令牌、别的来源一律拒绝,什么都不改。写都经 `tools/settings.py`,从不直接写文件,也不写 LOCAL.md。 | +| `GET /api/settings`、`POST /api/settings {name, value}` | 设置页(`settings_api.py`):要令牌。GET 回 `{version: 1, file, studio, mirror, agents, roots, local, about}`:Studio 自己的三项(`studio_lang`、`studio_theme`、`agent_default`,没设是 `null`)、下载镜像、每种 agent 装没装和新对话从什么模型和思考深度开始(`choices`,同对话列)、LOCAL.md 里人和 agent 都读的那几行(只读,模板的 `{…}` 和注释不算值)、版本。POST 只认这几个名字:`studio_lang`、`studio_theme`、`agent_default`(`null` 回到 Studio 的默认;没装好的 agent 不收)、`mirror`(`cn`、`off`、`auto`)、`model:`、`effort:`(只认这次运行里这种 agent 在对话里给过的值,记进 `picks.json`,没写进去就报错)、`reveal`(值是 GET 列出的片子文件夹之一:在系统的文件浏览器里打开它,`$OVH_REVEAL` 可以换成别的命令,一分钟至多二十次);别的名字、值、没有令牌、别的来源一律拒绝,什么都不改。写都经 `tools/settings.py`,从不直接写文件,也不写 LOCAL.md。 | | `POST /api/p/<键>/agent/install` | `{kind}`:人点了「装上」:控制台在后台运行 `bin/vh desk agents install `,回 `{installing: {state, since, took, said}}`(`state`:running、done、no_npm、timeout、cancelled、busy、failed;`limit` 是时限秒数;`said` 是它最后三行话,家目录写成 `~`,页面不显示);`{kind, cancel: true}` 停下正在装的那一次;在装时再点是同一次;`kind` 不是三家之一(包括不是字符串)回 400;`GET …/agents` 的每一家带着同样的 `installing`,页面照它跟到装完 | | `GET /api/space/agents`、`GET /api/space/agent//events`、`POST /api/space/agent/new · install · /say · answer · stop · mode · config` | 空间那一列:和片子里的同名地址一样(要令牌、同源、页面带着空间文件夹的 `pid`),对话是从空间开、还没建片子的那些;`new` 开的对话 agent 在工作台里干活;`events`、`stop` 等也找得到从这里开、已经建好片子的对话。片子建好时事件流里来一条 `{type: notice, code: placed, key, name}`(锁被别人拿着时是 `place_busy`)。`GET /api/space/agents?sid=` 在那段对话已经建好片子时多一个 `went: {id, key}` | | `GET /api/p/<键>/agents` 的 `strays`、`POST /api/p/<键>/agent//bring` | 一支对话列还空着的新片子:可能是它的、从空间开的对话(跑过 `bin/vh new`、没找到自己的片子、这支片子是它开始以后才有的);人点"把它带到这里",那段对话就成了这支片子的(不在 `strays` 里的 409) | @@ -152,12 +152,13 @@ bin/vh desk agents install # 装那一家的 ACP 适配器 左栏最下面一个"设置",或者 ⌘,(Linux 上 Ctrl+,;Studio 自己的窗口里,菜单的"设置…"也是它)。一整页:左边分节(通用、agent、片子的默认、这台电脑、关于;账号的那一节先空着,不显示),一次看一节,右边的对话列照常在;"返回"和 Esc 回到打开它之前的那一页。 -- **存在哪**:能在这一页改的都记在这台电脑自己的设置文件里(`$XDG_CONFIG_HOME/ovh/settings.json`,只经 `tools/settings.py` 读写),换一个端口、开第二个窗口、在终端里都是同一份。语言和外观另在浏览器里留一份,开屏就用它;页面一连上就以设置文件为准,设置文件还没有、浏览器里有的,记进去。顶栏的语言和"主题"两个按钮照旧,改的是同一份。 -- **通用**:语言、外观(三个主题的小样)、片子放在哪(这个 Studio 找片子的文件夹;换地方不在页面上改:页面说让 agent 改、改完重开 Studio,因为 Studio 起来时就按这些文件夹定了自己是哪一个)。 -- **agent**:新对话默认用哪一种(只列装好的;对话列在没有别的记录时从它开始);每种装好的 agent 的模型和思考深度:开过一次对话、agent 给过选项以后才能选(记进 `picks.json`,和对话列里选的是同一份),之前只写现在从什么开始。模式和"不带个人设置"按对话,留在对话里。 -- **片子的默认**:下载镜像(自动、国内镜像、官方源,同 `bin/vh settings mirror`)可以改;LOCAL.md 里人和 agent 都读的几行(默认努力程度、在哪看每一站、素材许可、声音库、谁拍板哪些事、帮手 agent 用的模型、默认预算)只显示,没写的写出没写时按什么,末尾一句"让 agent 帮你改"。这一页从不写 LOCAL.md。 +- **存在哪**:能在这一页改的都记在这台电脑自己的设置文件里(`$XDG_CONFIG_HOME/ovh/settings.json`,只经 `tools/settings.py` 读写),换一个端口、开第二个窗口、在终端里都是同一份。控制台把语言和外观写进它发出的页面,开屏就是它们;浏览器另留一份,设置文件还没有、浏览器里有的,记进去。页面上的选中照设置文件画,点哪个都写一次。顶栏的语言和"主题"两个按钮照旧,改的是同一份。 +- **右边那一列**:设置页里是空间的对话(从片子里打开也一样),上面一行说明这一点,免得把它当成片子的对话。没有这一次运行的令牌时,这一页什么都不显示,只说要在 Studio 的窗口里打开,带一个打开的按钮。 +- **通用**:语言、外观(三个主题的小样)、片子放在哪(这个 Studio 找片子的、真有的文件夹,家目录写成 `~`,每个后面"在访达里打开"(Linux:"打开文件夹"),服务端只开这几个文件夹之一;换地方不在页面上改:页面说让 agent 改、改完重开 Studio,因为 Studio 起来时就按这些文件夹定了自己是哪一个)。 +- **agent**:新对话默认用哪一种(只列装好的、只认装好的;对话列里每点一次"新对话"、空间里每开一支新片,都从它开始;一个地方上次用的是哪种,只决定打开时显示哪段已有的对话);每种装好的 agent 的模型和思考深度:开过一次对话、agent 给过选项以后才能选(记进 `picks.json`,和对话列里选的是同一份),之前只写现在从什么开始。模式和"不带个人设置"按对话,留在对话里。 +- **片子的默认**:下载镜像(自动、国内镜像、官方源,同 `bin/vh settings mirror`)可以改,页面写明 Studio 这一次运行里自己发起的下载要重开 Studio 才跟着变;LOCAL.md 里人和 agent 都读的几行(只认模板那样的列表项,值后面括号里的说明不算)(默认努力程度、在哪看每一站、素材许可、声音库、谁拍板哪些事、帮手 agent 用的模型、默认预算)只显示,没写的写出没写时按什么,末尾一句"让 agent 帮你改"。这一页从不写 LOCAL.md。 - **这台电脑**:同空间页的"这台电脑上还缺"(`/api/machine`),什么都不缺时一句"做片子要的都有了";空间页那一块多一个"去设置里看"。 -- **关于**:版本、工作台在哪、更新记录。 +- **关于**:版本(这份克隆所在的那一版,之后还有提交就加上提交号)、工作台在哪、这一版在 GitHub 上的发布说明。 ## 读什么 diff --git a/tools/desk/server.py b/tools/desk/server.py index a2b27768..cc72ec94 100644 --- a/tools/desk/server.py +++ b/tools/desk/server.py @@ -1056,6 +1056,8 @@ def do_GET(self): # code in its address for the token (POST /api/claim) page = (HERE / "static" / "index.html").read_text(encoding="utf-8").replace("{{TOKEN}}", "") \ .replace("{{HOME}}", srv.own_key or "") + st = SA.S.studio() # Studio's look and language as this machine keeps them: the first paint already has them + page = page.replace("{{THEME}}", st["studio_theme"] or "").replace("{{LANG}}", st["studio_lang"] or "") return self._send(200, page.encode("utf-8"), "text/html; charset=utf-8", {"Content-Security-Policy": CSP}) if path.startswith("/static/") and path[8:] in STATIC: return self._send(200, (HERE / "static" / path[8:]).read_bytes(), STATIC[path[8:]]) diff --git a/tools/desk/settings_api.py b/tools/desk/settings_api.py index d49db044..4257ce05 100644 --- a/tools/desk/settings_api.py +++ b/tools/desk/settings_api.py @@ -6,10 +6,12 @@ only a value the agent offered is ever set. LOCAL.md's lines that people and agents both read (effort, the way a stop is looked at, budget, asset licences, sound library, who decides) are shown, never written: the page says to ask the agent. -Both routes need this run's token. GET answers {version: 1, file, studio, mirror, agents, local, about}; POST takes -{name, value} (studio_lang, studio_theme, agent_default, mirror, model:, effort:) and answers the same as GET. +Both routes need this run's token. GET answers {version: 1, file, studio, mirror, agents, roots, local, about}; POST takes +{name, value} (studio_lang, studio_theme, agent_default, mirror, model:, effort:) and answers the same as GET, +or {name: "reveal", value: }: that folder opens in the system's file browser ($OVH_REVEAL, a command, +stands in for it; twenty a minute). """ -import os, re, secrets, sys +import os, re, secrets, subprocess, sys, threading, time from pathlib import Path HERE = Path(__file__).resolve().parent @@ -17,6 +19,7 @@ sys.path.insert(0, str(HERE.parent)) import settings as S # noqa: E402 (tools/settings.py: this machine's settings file, its one reader and writer) import agents as A # noqa: E402 +import projects as PJ # noqa: E402 (where this console looks for films) # LOCAL.md's lines shown on the page: id → the labels a line may start with (as the tools that read them accept) LOCAL_LINES = ( @@ -36,7 +39,8 @@ def local_md(): def local_lines(): - """{file, exists, lines: {id: value or None}}: a line still the template's {…}, empty or missing is None.""" + """{file, exists, lines: {id: value or None}}: the list item ("- label:value") that names it, its bracketed hint + left out; a line still the template's {…}, empty or missing is None.""" p = local_md() try: text = re.sub(r"", "", p.read_text(encoding="utf-8", errors="replace"), flags=re.S) @@ -44,21 +48,50 @@ def local_lines(): return {"file": str(p), "exists": False, "lines": {k: None for k, _ in LOCAL_LINES}} out = {} for k, labels in LOCAL_LINES: - m = re.search(rf"^[ \t]*[-*]?[ \t]*(?:\*\*)?(?:{labels})(?:\*\*)?[ \t]*[::][ \t]*(.*?)[ \t]*$", text, re.I | re.M) - v = m.group(1).strip().strip("*`").strip() if m else "" + m = re.search(rf"^[-*][ \t]+(?:\*\*)?(?:{labels})(?:\*\*)?[ \t]*[::][ \t]*(.*?)[ \t]*$", text, re.I | re.M) + v = m.group(1).strip() if m else "" + while re.search(r"[((][^()()]*[))]$", v): # the template's hint after a value: "standard(不填就是 standard;…)" + v = re.sub(r"\s*[((][^()()]*[))]$", "", v) + v = v.strip().strip("*`").strip() out[k] = None if not v or v.startswith("{") else v[:200] return {"file": str(p), "exists": True, "lines": out} -def version(): - try: - m = re.search(r'^version:\s*"?([^"\n]+)"?', (WORKSPACE / "CITATION.cff").read_text(encoding="utf-8"), re.M) - return m.group(1).strip() if m else None - except OSError: - return None +RELEASES = "https://github.com/ZLHad/OpenVideoHarness/releases" -def state(mgr): +def version(): + """{version, url}: the release this clone is at (its tag), else its commit; the release's page, else all releases.""" + def git(*a): + try: + r = subprocess.run(["git", "-C", str(WORKSPACE), *a], capture_output=True, text=True, timeout=5, stdin=subprocess.DEVNULL) + return r.stdout.strip() if r.returncode == 0 else "" + except (OSError, subprocess.SubprocessError): + return "" + tag = git("describe", "--tags", "--abbrev=0", "--match", "v[0-9]*") + exact = tag and git("describe", "--tags", "--exact-match", "--match", "v[0-9]*") == tag + head = git("rev-parse", "--short", "HEAD") + v = tag if exact else f"{tag} + {head}" if tag and head else head or None + return {"version": v, "url": f"{RELEASES}/tag/{tag}" if tag else RELEASES} + + +def shown(p): + """A folder as a person reads it: ~ for the home folder.""" + home = os.path.realpath(str(Path.home())) + return "~" + p[len(home):] if p == home or p.startswith(home + os.sep) else p + + +def roots(given): + """The folders this console finds films in, those that exist: {path, shown}.""" + out = [] + for r in PJ.roots_of(given): + if r.get("exists"): + p = os.path.realpath(os.path.expanduser(r["path"])) + out.append({"path": p, "shown": shown(p)}) + return out + + +def state(mgr, given=()): d = S.load() st = S.studio(d) kinds = A.catalog() @@ -67,8 +100,8 @@ def state(mgr): "agents": {"default": st["agent_default"], "kinds": [{"kind": a["kind"], "label": a["label"], "installed": a["installed"], "size": a["size"], "choices": mgr.choices(a["kind"]) if mgr else None} for a in kinds]}, - "local": local_lines(), - "about": {"version": version(), "workspace": str(WORKSPACE)}} + "roots": roots(given), "local": local_lines(), + "about": dict(version(), workspace=shown(os.path.realpath(WORKSPACE)))} def token_ok(handler): @@ -79,7 +112,22 @@ def token_ok(handler): def get(handler): if not token_ok(handler): return handler._error(403, "missing or wrong desk token: reload the page") - return handler._json(state(handler.server.agents)) + return handler._json(state(handler.server.agents, handler.server.roots)) + + +REVEALED, REVEAL_LOCK = [], threading.Lock() + + +def reveal(path): + """Open one folder in the system's file browser (Finder, the desktop's own), as the person asked on the page.""" + with REVEAL_LOCK: + now = time.time() + REVEALED[:] = [x for x in REVEALED if now - x < 60] + if len(REVEALED) >= 20: + raise PermissionError("asked too often: try again in a minute") + REVEALED.append(now) + cmd = os.environ.get("OVH_REVEAL") or ("open" if sys.platform == "darwin" else "xdg-open") + subprocess.Popen([cmd, path], stdin=subprocess.DEVNULL, stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL, start_new_session=True) def post(handler): @@ -90,6 +138,13 @@ def post(handler): if not isinstance(name, str) or not (value is None or isinstance(value, str)): return handler._error(400, "send {name, value}: value a string, or null for Studio's default") try: + if name == "reveal": # only one of this console's own film folders, never a path the page makes up + if value not in {r["path"] for r in roots(handler.server.roots)}: + raise ValueError("reveal: not one of the folders Studio finds films in") + reveal(value) + return handler._json({"ok": True}) + if name == "agent_default" and value is not None and not (value in A.ADAPTERS and A.installed(value)): + raise ValueError(f"agent_default: {value!r} is not set up in Studio") if name in S.STUDIO: S.set_studio(name, value) elif name == "mirror": @@ -102,10 +157,14 @@ def post(handler): if value not in {x["value"] for x in offered}: # only what this kind of agent offered in a chat this run raise ValueError(f"{name}: not a value this agent offered") A.remember(kind, role, value) + if (A.picks().get(kind) or {}).get(role) != value: # (remember says nothing when it cannot write) + raise OSError(f"{A.picks_path()} was not written") else: raise ValueError(f"{name}: not a setting Studio changes") + except PermissionError as e: + return handler._error(429, str(e)) except ValueError as e: return handler._error(400, str(e)) except OSError as e: return handler._error(500, f"could not keep it ({type(e).__name__})") - return handler._json(state(handler.server.agents)) + return handler._json(state(handler.server.agents, handler.server.roots)) diff --git a/tools/desk/static/agent.js b/tools/desk/static/agent.js index ed23f251..a26da025 100644 --- a/tools/desk/static/agent.js +++ b/tools/desk/static/agent.js @@ -205,7 +205,7 @@ const AGENT = (() => { if (typeof spacePlaced === "function") spacePlaced(INFO.went.key); } const saved = store_.get(`desk:agent:${KEYP}`) || {}; - KIND = KIND || saved.kind || (kinds().find((a) => a.installed && a.kind === INFO.default) || kinds().find((a) => a.installed) || kinds()[0] || {}).kind || "claude"; // INFO.default: the settings page's 新对话默认用 + KIND = KIND || saved.kind || defaultKind(); // this place's last agent decides which conversation shows; a new one starts with the default return true; } let INSTWATCH = 0; @@ -275,6 +275,10 @@ const AGENT = (() => { render(); return S; } + function defaultKind(info) { // a new conversation's agent: the settings page's 新对话默认用 when it is set up, else the first set up + const ks = ((info || INFO || {}).agents) || [], d = (info || INFO || {}).default; + return (ks.find((a) => a.installed && a.kind === d) || ks.find((a) => a.installed) || ks[0] || {}).kind || "claude"; + } async function pickKind(kind) { KIND = kind; NEWBOX = false; ERR = null; NEWASK = {}; close(); store_.set(`desk:agent:${KEYP}`, { kind }); @@ -499,7 +503,7 @@ const AGENT = (() => { if (part("agTop", top)) { DRAWN.agState = null; $("#agKind").addEventListener("change", (e) => pickKind(e.target.value)); - $("#agNew").addEventListener("click", async () => { if (KEYP === SPACE) return fresh(); NEWBOX = true; NEWASK = {}; await load(); render(); const b = $("#agNewGo"); if (b) b.focus(); }); // (load: the agent's list as this run last saw it) + $("#agNew").addEventListener("click", async () => { if (KEYP === SPACE) return fresh(); NEWBOX = true; NEWASK = {}; await load(); KIND = defaultKind(); render(); const b = $("#agNewGo"); if (b) b.focus(); }); // (load: the agent's list as this run last saw it) $$("#agTop [data-sid]").forEach((b) => b.addEventListener("click", () => back(b.dataset.sid))); } $("#agOrb").className = "ag-orb " + st.cls; @@ -786,8 +790,9 @@ const AGENT = (() => { } async function fresh() { // the space: a sentence box for another new film (the one open stays in the history, and goes on) close(); NEWBOX = false; ERR = null; BUSY = null; NEWASK = {}; + await load(); KIND = defaultKind(); // a new film's conversation starts with the default agent store_.set(`desk:agent:${SPACE}`, { kind: KIND }); - await load(); render(); + render(); const ta = $("#agSay"); if (ta) ta.focus(); } @@ -848,6 +853,6 @@ const AGENT = (() => { }, _again: (e) => again(e), // for tools/desk/test_agents.py (node): the busy line's "anyway" after a refused carry-on busy: () => !!(S && S.running && KEYP !== SPACE), // a turn in this film's column now (the flow strip's agent lamp) - _md: md, _diff: diffLines, _ask: (pm, d) => askHtml(pm, d), _state: () => (S ? { id: S.id, items: S.items.length, seq: S.seq, es: ES ? ES.readyState : null, url: ES ? ES.url.replace(/token=[^&]*/, "token=…") : null } : null), // for tools/desk/test_agents.py (node): the escaping and the diff, without a page + _md: md, _diff: diffLines, _ask: (pm, d) => askHtml(pm, d), _defaultKind: defaultKind, _state: () => (S ? { id: S.id, items: S.items.length, seq: S.seq, es: ES ? ES.readyState : null, url: ES ? ES.url.replace(/token=[^&]*/, "token=…") : null } : null), // for tools/desk/test_agents.py (node): the escaping and the diff, without a page }; })(); diff --git a/tools/desk/static/index.html b/tools/desk/static/index.html index a8cad962..69993b0c 100644 --- a/tools/desk/static/index.html +++ b/tools/desk/static/index.html @@ -1,10 +1,11 @@ - + + Studio diff --git a/tools/desk/static/settings.css b/tools/desk/static/settings.css index 9b69b4c4..7a600ef2 100644 --- a/tools/desk/static/settings.css +++ b/tools/desk/static/settings.css @@ -18,6 +18,7 @@ .st-lead{color:var(--ink-2);font-size:var(--fs-small);margin:0 0 10px;max-width:36em} .st-foot{padding-top:12px;border-top:1px solid var(--rule)} .st-h{margin:24px 0 2px;font:500 var(--fs-small)/1.4 var(--sans);color:var(--ink-hi)} +.st-paths li{display:grid;grid-template-columns:minmax(0,1fr) auto;align-items:center;gap:12px} .st-list,.st-paths{margin:8px 0 0;padding:0;list-style:none;display:grid;gap:4px} .st-seg{display:inline-flex;flex-wrap:wrap;gap:6px} .st-seg button{min-height:32px;padding:0 14px;border:1px solid var(--rule-2);border-radius:var(--r-ctl);background:transparent;color:var(--ink-2);cursor:pointer;font-size:var(--fs-small)} diff --git a/tools/desk/static/settings.js b/tools/desk/static/settings.js index 6cf9e40a..463010b4 100644 --- a/tools/desk/static/settings.js +++ b/tools/desk/static/settings.js @@ -1,50 +1,60 @@ -/* Studio's settings page, #/settings[/
    ] (tools/desk/settings_api.py serves it; tools/desk/README.md "设置"). +/* Studio's settings page, #/settings[/
    ] (tools/desk/settings_api.py serves it; tools/desk/README.md "设置页"). One page with its sections on the left and one section at a time. What a person changes is kept in this machine's - settings file (tools/settings.py), so a second window, another port or the terminal see the same; the language and the - look are also kept in this browser, so the first paint already has them. The top bar's language and look buttons stay: - they change the same two settings (the clicks are heard here). Loaded before studio.js; it uses studio.js's and - core.js's names only when it runs. */ + settings file (tools/settings.py), so a second window, another port or the terminal see the same; the console writes + the language and the look into the page it serves, so the first paint has them, and this browser keeps a copy. The top + bar's language and look buttons stay: they change the same two settings (their clicks are heard here). Loaded before + studio.js; it uses studio.js's and core.js's names only when it runs. */ const SETTINGS = (() => { const W = { zh: { title: "设置", back: "返回", rail: "设置", rail_tip: "设置(⌘,)", s_general: "通用", s_agent: "agent", s_films: "片子的默认", s_machine: "这台电脑", s_about: "关于", s_account: "账号", lang: "语言", look: "外观", th_darkfield: "暗场", th_prism: "棱镜", th_bridge: "舰桥", - where: "片子放在哪", where_how: "想换个地方,让 agent 帮你改,改完重新打开 Studio。", where_none: "还没读到片子放在哪。", + where: "片子放在哪", where_how: "想换个地方,让 agent 帮你改,改完重新打开 Studio。", where_none: "还没有这样的文件夹。", reveal: "在访达里打开", reveal_other: "打开文件夹", ag_default: "新对话默认用", ag_not: "还没装", ag_not_how: "在右边的对话里点「装上」。", ag_model: "模型", ag_effort: "思考深度", ag_from_default: "Studio 的默认", ag_from_agent: "{a} 自己的默认", ag_from_dsh: "DeepSeek Harness 桌面版里的设置", ag_later: "开一次对话以后,这里能改。", ag_none: "这台电脑上还没有装好的 agent。", + col_space: "这里是空间的对话:在这里写一句,agent 会开一支新片子。片子自己的对话,回到那支片子里看。", f_lead: "这些是这台电脑给每支片子的默认。片子自己写了的,以片子的为准。", f_effort: "默认努力程度", f_review: "在哪看每一站", f_assets: "素材许可", f_sound: "声音库", f_director: "谁拍板哪些事", f_subagent: "帮手 agent 用的模型", f_budget: "默认预算", f_unset: "没写", f_unset_effort: "没写:按标准", f_unset_review: "没写:按努力程度", f_unset_assets: "没写:严格", f_unset_sound: "没写:用 ~/.ovh/sound", f_unset_budget: "没写:不调收费的接口", + f_unset_director: "没写:按努力程度的默认", f_unset_subagent: "没写:比 agent 自己便宜一档", f_how: "让 agent 帮你改。", mirror: "下载镜像", m_auto: "自动", m_cn: "国内镜像", m_off: "官方源", - m_auto_d: "从官方源下载;安装时官方源连不上,会自己换成国内镜像。", m_cn_d: "以后的下载都走国内镜像。", m_off_d: "只从官方源下载。", - m_set: "({d} 设的)", mc_rest: "别的做片子要的都有了。", - v_quick: "快速", v_standard: "标准", v_studio: "精品", v_chat: "对话里", v_page: "网页", v_desk: "Studio", v_strict: "严格", v_record: "记下就能用", mc_lead: "做片子要的", mc_ok: "做片子要的都有了。", mc_wait: "正在看这台电脑…", mc_fail: "这次没看成,过一会儿再打开这一页。", - ab_version: "版本", ab_where: "工作台在哪", ab_news: "更新了什么", - saved: "记下了", see: "去设置里看", failed: "没记下:{x}", nokey: "这一页现在只能看:在 Studio 自己的窗口里才能改。", + m_auto_d: "从官方源下载;安装时官方源连不上,会自己换成国内镜像。", m_cn_d: "以后的下载走国内镜像。", m_off_d: "以后的下载走官方源。", + m_restart: "Studio 这一次运行里它自己发起的下载(比如右边的「装上」),重新打开 Studio 以后才跟着变。", + m_set: "({d} 设的)", mc_lead: "做片子要的", mc_ok: "做片子要的都有了。", mc_rest: "别的做片子要的都有了。", + mc_wait: "正在看这台电脑…", mc_fail: "这次没看成,过一会儿再打开这一页。", mc_agent_d: "在右边的对话里点「装上」。", + v_quick: "快速", v_standard: "标准", v_studio: "精品", v_chat: "对话里", v_page: "网页", v_desk: "Studio", v_strict: "严格", v_record: "记下就能用", + ab_version: "版本", ab_where: "工作台在哪", ab_news: "更新了什么", ab_news_link: "这一版的说明", + saved: "记下了", see: "去设置里看", failed: "没记下:{x}", + nokey: "这一页要在 Studio 的窗口里打开才看得到。", reopen: "在 Studio 窗口里打开", }, en: { title: "Settings", back: "Back", rail: "Settings", rail_tip: "Settings (⌘,)", s_general: "General", s_agent: "Agent", s_films: "Film defaults", s_machine: "This computer", s_about: "About", s_account: "Account", lang: "Language", look: "Look", th_darkfield: "Darkfield", th_prism: "Prism", th_bridge: "Bridge", - where: "Where films are kept", where_how: "To keep them somewhere else, ask your agent to change it, then reopen Studio.", where_none: "Not known yet.", + where: "Where films are kept", where_how: "To keep them somewhere else, ask your agent to change it, then reopen Studio.", where_none: "No such folder yet.", reveal: "Show in Finder", reveal_other: "Open folder", ag_default: "New chats start with", ag_not: "Not set up", ag_not_how: "Press “Set it up” in the chat on the right.", ag_model: "Model", ag_effort: "Effort", ag_from_default: "Studio's default", ag_from_agent: "{a}'s own default", ag_from_dsh: "as set in the DeepSeek Harness app", ag_later: "Start one chat and you can change it here.", ag_none: "No agent is set up on this computer yet.", + col_space: "This is the space's chat: a sentence here starts a new film. A film's own chat is in that film.", f_lead: "This computer's defaults for every film. What a film says for itself comes first.", f_effort: "Default effort", f_review: "Where you look at each stop", f_assets: "Asset licences", f_sound: "Sound library", f_director: "Who decides what", f_subagent: "Model for helper agents", f_budget: "Default budget", f_unset: "Not set", f_unset_effort: "Not set: standard", f_unset_review: "Not set: by effort", f_unset_assets: "Not set: strict", f_unset_sound: "Not set: ~/.ovh/sound", f_unset_budget: "Not set: no paid services are called", + f_unset_director: "Not set: the effort's own defaults", f_unset_subagent: "Not set: one tier cheaper than the agent's own", f_how: "Ask your agent to change it.", mirror: "Download mirror", m_auto: "Automatic", m_cn: "Mainland China mirrors", m_off: "Official sources", - m_auto_d: "Downloads come from the official sources; if they don't answer during install, it switches to the mirrors by itself.", m_cn_d: "Every later download comes from the mainland China mirrors.", m_off_d: "Downloads only come from the official sources.", - m_set: "(set {d})", mc_rest: "Everything else films need is here.", - v_quick: "Quick", v_standard: "Standard", v_studio: "Studio", v_chat: "In the chat", v_page: "A web page", v_desk: "Studio", v_strict: "Strict", v_record: "Allowed if recorded", mc_lead: "Needed for films", mc_ok: "Everything films need is here.", mc_wait: "Looking at this computer…", mc_fail: "Couldn't look this time; open this page again in a moment.", - ab_version: "Version", ab_where: "Where the workbench is", ab_news: "What's new", - saved: "Saved", see: "See it in Settings", failed: "Not saved: {x}", nokey: "This page can only look: change settings in Studio's own window.", + m_auto_d: "Downloads come from the official sources; if they don't answer during install, it switches to the mirrors by itself.", m_cn_d: "Later downloads come from the mainland China mirrors.", m_off_d: "Later downloads come from the official sources.", + m_restart: "Downloads Studio itself starts in this run (like “Set it up” on the right) follow once Studio is reopened.", + m_set: "(set {d})", mc_lead: "Needed for films", mc_ok: "Everything films need is here.", mc_rest: "Everything else films need is here.", + mc_wait: "Looking at this computer…", mc_fail: "Couldn't look this time; open this page again in a moment.", mc_agent_d: "Press “Set it up” in the chat on the right.", + v_quick: "Quick", v_standard: "Standard", v_studio: "Studio", v_chat: "In the chat", v_page: "A web page", v_desk: "Studio", v_strict: "Strict", v_record: "Allowed if recorded", + ab_version: "Version", ab_where: "Where the workbench is", ab_news: "What's new", ab_news_link: "This version's notes", + saved: "Saved", see: "See it in Settings", failed: "Not saved: {x}", + nokey: "This page shows only in Studio's own window.", reopen: "Open in Studio's window", }, }; const w = (k, v) => String((W[LANG] || W.zh)[k] != null ? (W[LANG] || W.zh)[k] : W.en[k] != null ? W.en[k] : k).replace(/\{(\w+)\}/g, (_, x) => (v && v[x] != null ? v[x] : "")); @@ -63,8 +73,8 @@ const SETTINGS = (() => { async function load() { const r = await call("GET"); if (r.ok && r.data) ST = r.data; return r; } async function save(name, value, quiet) { const r = await call("POST", { name, value }); - if (r.ok && r.data) { ST = r.data; if (!quiet) toast(w("saved")); } - else if (!quiet) toast(r.status === 403 ? w("nokey") : w("failed", { x: (r.data && r.data.error) || r.status })); + if (r.ok && r.data && r.data.version) ST = r.data; + if (!quiet) toast(r.ok ? w("saved") : r.status === 403 ? w("nokey") : w("failed", { x: (r.data && r.data.error) || r.status })); return r.ok; } @@ -81,31 +91,42 @@ const SETTINGS = (() => { SEC = SECTIONS.some((s) => s.id === sec && !s.hidden) ? sec : "general"; leaveProject(); D = null; PKEY = ""; MOD = ""; GV = null; crumbs([{ text: t("m_space"), href: "#/" }, { text: w("title") }]); renderFlow(); renderRail(); spaceColumn(); + const now = $("#colNow"); // the column is the space's here, not the film's it came from: said above it + now.className = "col-now"; now.innerHTML = `

    ${esc(w("col_space"))}

    `; now.dataset.html = ""; now.hidden = false; if (!ST) $("#stage").innerHTML = `

    …

    `; const r = await load(); if (parse().view !== "settings") return; - if (!ST) { $("#stage").innerHTML = `

    ${esc(r.status === 403 ? w("nokey") : t("noServer"))}

    `; return; } - if (SEC === "general" && !LIST) await listing(); - if (parse().view !== "settings") return; + if (!ST) { + $("#stage").innerHTML = r.status === 403 ? `

    ${esc(w("nokey"))}

    ` + : `

    ${esc(t("noServer"))}

    `; + const b = $("#stReopen"); if (b) b.addEventListener("click", (e) => { if (e.isTrusted) reopen(); }); + return; + } draw(); if (SEC === "machine") machine().then(() => { if (parse().view === "settings" && SEC === "machine") draw(); }); } function draw() { - const area = $("#stage"), y = area.scrollTop; + const area = $("#stage"), y = area.scrollTop, f = $("#stage :focus"), refocus = f && (f.dataset.val || f.dataset.themeSet || f.dataset.set); const nav = SECTIONS.filter((s) => !s.hidden).map((s) => `${esc(w("s_" + s.id))}`).join(""); area.innerHTML = `

    ${esc(w("title"))}

    ${esc(w("back"))}
    -
    ${({ general, agent, films, machine: machineSec, about })[SEC === "machine" ? "machine" : SEC]()}
    `; +
    ${({ general, agent, films, machine: machineSec, about })[SEC]()}
    `; area.scrollTop = y; + if (refocus) { const b = [...area.querySelectorAll("[role=radio], select")].find((x) => (x.dataset.val || x.dataset.themeSet || x.dataset.set) === refocus); if (b) b.focus(); } } const row = (label, body, note) => `
    ${esc(label)}
    ${body}${note ? `

    ${note}

    ` : ""}
    `; - const seg = (name, opts, cur) => `
    ${opts.map(([v, label]) => ``).join("")}
    `; + const radios = (label, items) => // a radio group: one tab stop (the chosen one), arrows move and choose + `
    ${items.map((x) => ``).join("")}
    `; + const seg = (name, opts, cur, label) => radios(label, opts.map(([v, text]) => ({ on: v === cur, attrs: `data-set="${esc(name)}" data-val="${esc(v)}"`, body: esc(text) }))); function general() { - const theme = document.documentElement.getAttribute("data-theme") || "darkfield"; - const looks = `
    ${THEMES.map((x) => ``).join("")}
    `; - const roots = ((LIST && LIST.roots) || []).map((x) => x.path || x).filter(Boolean); - const where = roots.length ? `
      ${roots.map((p) => `
    • ${esc(p)}
    • `).join("")}
    ` : `

    ${esc(w("where_none"))}

    `; - return row(w("lang"), seg("studio_lang", [["zh", "中文"], ["en", "English"]], LANG)) + const st = ST.studio || {}, theme = st.studio_theme || document.documentElement.getAttribute("data-theme") || "darkfield"; + const looks = radios(w("look"), THEMES.map((x) => ({ on: x === theme, attrs: `class="st-look st-look-${x}" data-theme-set="${x}"`, body: `${esc(w("th_" + x))}` }))) + .replace('class="st-seg"', 'class="st-looks"'); + const mac = /Mac/i.test(navigator.platform || navigator.userAgent || ""); + const roots = ST.roots || []; + const where = roots.length ? `
      ${roots.map((r) => `
    • ${esc(r.shown)}
    • `).join("")}
    ` + : `

    ${esc(w("where_none"))}

    `; + return row(w("lang"), seg("studio_lang", [["zh", "中文"], ["en", "English"]], st.studio_lang || "zh", w("lang"))) + row(w("look"), looks) + row(w("where"), where, esc(w("where_how"))); } @@ -113,14 +134,14 @@ const SETTINGS = (() => { const kinds = (ST.agents && ST.agents.kinds) || [], got = kinds.filter((k) => k.installed); if (!got.length) return row(w("ag_default"), `

    ${esc(w("ag_none"))}

    `, esc(w("ag_not_how"))); const def = (got.find((k) => k.kind === ST.agents.default) || got[0]).kind; - const pick = got.length > 1 ? seg("agent_default", got.map((k) => [k.kind, k.label]), def) : `

    ${esc(got[0].label)}

    `; + const pick = got.length > 1 ? seg("agent_default", got.map((k) => [k.kind, k.label]), def, w("ag_default")) : `

    ${esc(got[0].label)}

    `; const missing = kinds.filter((k) => !k.installed).map((k) => `
  • ${esc(k.label)} · ${esc(w("ag_not"))}
  • `).join(""); let out = row(w("ag_default"), pick + (missing ? `
      ${missing}
    ` : ""), missing ? esc(w("ag_not_how")) : ""); for (const k of got) { const ch = k.choices || {}, offered = ch.offered || {}; const one = (role) => { const c = ch[role] || {}, opts = offered[role] || []; - if (opts.length) return ``; + if (opts.length) return ``; const from = c.from === "default" ? w("ag_from_default") : c.from === "dsh" ? w("ag_from_dsh") : c.from === "agent" || !c.name ? w("ag_from_agent", { a: k.label }) : ""; return `

    ${esc(c.name || "")}${c.name && from ? " · " : ""}${esc(from)}

    `; }; @@ -136,42 +157,55 @@ const SETTINGS = (() => { return m && ["effort", "review", "assets"].includes(k) ? w("v_" + m[1].toLowerCase().replace(/^对话$/, "chat").replace(/^审阅页$/, "page").replace(/^审阅台$/, "desk")) : L[k]; }; const val = (k) => (L[k] ? `

    ${esc(said(k))}

    ` : `

    ${esc(w(W.zh["f_unset_" + k] ? "f_unset_" + k : "f_unset"))}

    `); - const mirror = seg("mirror", [["auto", w("m_auto")], ["cn", w("m_cn")], ["off", w("m_off")]], M.mode || "auto"); + const mode = M.mode || "auto", mirror = seg("mirror", [["auto", w("m_auto")], ["cn", w("m_cn")], ["off", w("m_off")]], mode, w("mirror")); const when = M.at ? ` ${esc(w("m_set", { d: M.at }))}` : ""; return `

    ${esc(w("f_lead"))}

    ` - + row(w("mirror"), mirror, esc(w("m_" + (M.mode || "auto") + "_d")) + when) + + row(w("mirror"), mirror, esc(w("m_" + mode + "_d")) + when + `
    ${esc(w("m_restart"))}`) + ["effort", "review", "assets", "sound", "director", "subagent", "budget"].map((k) => row(w("f_" + k), val(k))).join("") + `

    ${esc(w("f_how"))}

    `; } function machineSec() { if (!MACHINE) return `

    ${esc(w("mc_wait"))}

    `; if (MACHINE.error) return `

    ${esc(w("mc_fail"))}

    `; - return (MACHINE.lacks || []).length ? lacksHtml() + `

    ${esc(w("mc_rest"))}

    ` : row(w("mc_lead"), `

    ${esc(w("mc_ok"))}

    `); + const L = MACHINE.lacks || []; + if (!L.length) return row(w("mc_lead"), `

    ${esc(w("mc_ok"))}

    `); + const items = L.map((x) => `
  • ${esc(t("lk_" + x.what + "_n"))}${esc(COLON())}${esc(x.what === "agent" ? t("lk_agent_s") : t(x.state === "outdated" ? "lk_old" : "lk_missing", { s: t("lk_" + x.what + "_s") }))} ${esc(x.what === "agent" ? w("mc_agent_d") : t("lk_" + x.what + "_d"))}
  • `).join(""); + return `

    ${esc(w("mc_rest"))}

    `; } function about() { const a = ST.about || {}; return row(w("ab_version"), `

    ${esc(a.version || "")}

    `) + row(w("ab_where"), `${esc(a.workspace || "")}`) - + row(w("ab_news"), `CHANGELOG`); + + row(w("ab_news"), `${esc(w("ab_news_link"))}`); } /* the page's clicks; the top bar's language and look buttons (their own handlers ran first: the new value is in place) */ - document.addEventListener("click", async (e) => { - if (e.target.closest("#lang")) { save("studio_lang", LANG, true); if (parse().view === "settings") draw(); return; } - const th = e.target.closest("[data-theme-set]"); - if (th) { save("studio_theme", th.dataset.themeSet, true); if (parse().view === "settings" && SEC === "general") draw(); return; } - const b = e.target.closest(".settings [data-set]"); - if (!b || b.tagName === "SELECT") return; + async function choose(b) { // a radio of this page, by click or by arrow: always saved, even when it shows as chosen already + if (b.dataset.themeSet) { OVH.theme(b.dataset.themeSet); return save("studio_theme", b.dataset.themeSet, true).then(() => draw()); } const name = b.dataset.set, v = b.dataset.val; - if (name === "studio_lang") { if (v !== LANG) $("#lang").click(); return; } + if (name === "studio_lang") { if (v !== LANG) $("#lang").click(); else { await save("studio_lang", v, true); draw(); } return; } if (await save(name, v) && parse().view === "settings") draw(); + } + document.addEventListener("click", async (e) => { + if (e.target.closest("#lang")) { await save("studio_lang", LANG, true); if (parse().view === "settings") draw(); return; } + const th = e.target.closest("[data-theme-set]"); + if (th && !th.closest(".settings")) { await save("studio_theme", th.dataset.themeSet, true); if (parse().view === "settings" && SEC === "general") draw(); return; } + const rv = e.target.closest(".settings [data-reveal]"); + if (rv) { if (e.isTrusted) save("reveal", rv.dataset.reveal, true); return; } + const b = e.target.closest('.settings [role="radio"]'); + if (b) choose(b); }); document.addEventListener("change", async (e) => { const s = e.target.closest(".settings select[data-set]"); if (s && await save(s.dataset.set, s.value) && parse().view === "settings") draw(); }); - document.addEventListener("keydown", (e) => { // ⌘, (Ctrl+, elsewhere): in Studio's own window the menu item does this - if (e.key === "," && (e.metaKey || e.ctrlKey) && !e.altKey && !e.shiftKey) { e.preventDefault(); go("#/settings"); } + document.addEventListener("keydown", (e) => { + const r = e.target.closest && e.target.closest('.settings [role="radio"]'); + if (r && /^Arrow(Left|Right|Up|Down)$/.test(e.key)) { // a radio group: the arrows move to the next one and choose it + const all = [...r.parentNode.querySelectorAll('[role="radio"]')], i = all.indexOf(r), d = /Left|Up/.test(e.key) ? -1 : 1, n = all[(i + d + all.length) % all.length]; + e.preventDefault(); n.focus(); choose(n); return; + } + if (e.key === "," && (e.metaKey || e.ctrlKey) && !e.altKey && !e.shiftKey) { e.preventDefault(); go("#/settings"); } // in Studio's own window the menu item does this else if (e.key === "Escape" && parse().view === "settings" && !typing()) go(BACK); }); window.addEventListener("hashchange", (e) => { // where Back goes: the page this one was opened from @@ -179,17 +213,22 @@ const SETTINGS = (() => { if (!from.startsWith("#/settings") && location.hash.startsWith("#/settings")) BACK = from; }); - /* at start: what is kept for this machine wins over this browser's copy; a copy with nothing kept yet is kept */ + /* at start: what this machine keeps wins over this browser's copy; a copy with nothing kept yet is kept */ + function plan(st, theme, lang) { // → {theme, lang}: what to show; {keep_theme, keep_lang}: what to write into the file + st = st || {}; + return { theme: st.studio_theme || theme, lang: st.studio_lang || lang, + keep_theme: !st.studio_theme && theme && theme !== "darkfield" ? theme : null, keep_lang: !st.studio_lang && lang && lang !== "zh" ? lang : null }; + } async function sync(tries) { const r = await load(); if (!r.ok) { if (r.status === 403 && tries < 10) setTimeout(() => sync(tries + 1), 1000); return; } - const st = ST.studio || {}, theme = document.documentElement.getAttribute("data-theme"); - if (st.studio_theme && st.studio_theme !== theme) OVH.theme(st.studio_theme); - else if (!st.studio_theme && theme && theme !== "darkfield") save("studio_theme", theme, true); - if (st.studio_lang && st.studio_lang !== LANG) $("#lang").click(); - else if (!st.studio_lang && LANG !== "zh") save("studio_lang", LANG, true); + const p = plan(ST.studio, document.documentElement.getAttribute("data-theme"), LANG); + if (p.theme !== document.documentElement.getAttribute("data-theme")) OVH.theme(p.theme); + if (p.lang !== LANG) $("#lang").click(); + if (p.keep_theme) save("studio_theme", p.keep_theme, true); + if (p.keep_lang) save("studio_lang", p.keep_lang, true); } setTimeout(() => sync(0), 300); - return { show, railItem, word: w, words: W }; + return { show, railItem, word: w, words: W, _plan: plan }; })(); diff --git a/tools/desk/static/studio.js b/tools/desk/static/studio.js index 5314e754..c32abdb5 100644 --- a/tools/desk/static/studio.js +++ b/tools/desk/static/studio.js @@ -54,7 +54,8 @@ function setLang(l) { $$("#themes [data-theme-set]").forEach((b) => { b.textContent = t("th_" + b.dataset.themeSet); }); } function pickLang(fallback) { - let pick = null; try { pick = localStorage.getItem("desk:lang"); } catch (e) { /* no storage */ } + let pick = (document.querySelector('meta[name="desk-lang"]') || {}).content || null; // as this machine keeps it (the settings page), else this browser's + if (pick !== "zh" && pick !== "en") try { pick = localStorage.getItem("desk:lang"); } catch (e) { /* no storage */ } return pick === "zh" || pick === "en" ? pick : fallback || (/^zh/i.test(navigator.language || "zh") ? "zh" : "en"); } @@ -104,7 +105,7 @@ function waitsIn(mod) { const f = FLOW.find((x) => x.mod === mod); return !!f && function renderRail() { // the space and a new film; a film's modules only while a film is open (on the space they would point at nothing, or at the last film) const proj = !!D; const item = (m) => { - if (m === "space") return `${svg("space")}${esc(t("m_space"))}`; + if (m === "space") return `${svg("space")}${esc(t("m_space"))}`; const dot = waitsIn(m) ? '' : ""; return `${svg(m)}${esc(t("m_" + m))}${dot}`; }; diff --git a/tools/desk/test_settings.py b/tools/desk/test_settings.py index 67eb0dd4..cbf878ae 100644 --- a/tools/desk/test_settings.py +++ b/tools/desk/test_settings.py @@ -4,7 +4,7 @@ python3 tools/desk/test_settings.py """ -import http.client, json, os, re, signal, subprocess, sys, time, urllib.request +import http.client, json, os, re, shutil, signal, subprocess, sys, time, urllib.request from pathlib import Path HERE = Path(__file__).resolve().parent @@ -12,14 +12,21 @@ if len(sys.argv) < 2 or sys.argv[1].startswith("-"): sys.exit("usage: python3 tools/desk/test_settings.py ") T = Path(sys.argv[1]).resolve() -for d in ("tmp", "home", "config", "cache", "data", "films", "agents", "profiles"): +for d in ("tmp", "home/films", "config", "cache", "data", "agents", "profiles"): (T / d).mkdir(parents=True, exist_ok=True) +FILMS = T / "home" / "films" # a films folder in the home folder: the page shows it as ~/films +REVEAL = T / "revealed.log" +(T / "reveal.sh").write_text(f"#!/bin/sh\nprintf '%s\\n' \"$1\" >> '{REVEAL}'\n") +(T / "reveal.sh").chmod(0o755) CONF = T / "config" / "ovh" / "settings.json" +sys.path.insert(0, str(HERE)) +import agents as _A # noqa: E402 (the agents' packages: a stand-in of one is set up below) +A_INFO = _A.ADAPTERS LOCAL = T / "LOCAL.md" ENV = dict(os.environ, TMPDIR=str(T / "tmp"), HOME=str(T / "home"), XDG_CONFIG_HOME=str(T / "config"), XDG_CACHE_HOME=str(T / "cache"), XDG_DATA_HOME=str(T / "data"), OVH_LOCAL_MD=str(LOCAL), OVH_AGENTS_DIR=str(T / "agents"), OVH_STUDIO_PROFILES=str(T / "profiles"), - OVH_STUDIO_SHELL="none", OVH_STUDIO_BROWSER="none", OVH_GATE_STUDIO="0", BROWSER="/usr/bin/false") -ENV.pop("OVH_PROJECTS", None) + OVH_STUDIO_SHELL="none", OVH_STUDIO_BROWSER="none", OVH_GATE_STUDIO="0", BROWSER="/usr/bin/false", + OVH_PROJECTS=str(T / "no-such-folder"), OVH_REVEAL=str(T / "reveal.sh")) def say(ok, what, why=""): @@ -75,7 +82,7 @@ class Desk: def __init__(self): self.log = T / "desk.log" self.proc = subprocess.Popen([sys.executable, str(HERE / "fixtures" / "with_tty.py"), sys.executable, str(HERE / "desk.py"), - "--root", str(T / "films"), "--port", "0", "--print-address"], + "--root", str(FILMS), "--port", "0", "--print-address"], stdout=open(self.log, "w"), stderr=subprocess.STDOUT, env=ENV, cwd=str(T)) for _ in range(150): m = re.search(r"http://127\.0\.0\.1:(\d+)/\?c=([A-Za-z0-9_-]+)", self.log.read_text()) @@ -114,9 +121,15 @@ def stop(self): def run(): text = (ROOT / "LOCAL.example.md").read_text(encoding="utf-8") - text = re.sub(r"^- 默认努力程度:.*$", "- 默认努力程度:quick", text, flags=re.M) + text = re.sub(r"^- 默认努力程度:.*$", "- 默认努力程度:quick(不填就是 standard;规则见 CLAUDE.md)", text, flags=re.M) text = re.sub(r"^- 默认预算:.*$", "- 默认预算:每支片子 5 美元 ", text, flags=re.M) + text = "Effort: studio, said in a note, not a setting\n素材许可:record(也是一句话里的)\n" + text # lines that are no list item are no setting LOCAL.write_text(text, encoding="utf-8") + codex = A_INFO["codex"] # one agent set up (a stand-in of its package, never run): the default may name it, not another + exe = T / "agents" / "codex" / "node_modules" / ".bin" / codex["bin"] + exe.parent.mkdir(parents=True, exist_ok=True); exe.write_text("#!/bin/sh\nexit 1\n"); exe.chmod(0o755) + pkg = T / "agents" / "codex" / "node_modules" / codex["package"] / "package.json" + pkg.parent.mkdir(parents=True, exist_ok=True); pkg.write_text(json.dumps({"version": codex["version"]})) CONF.parent.mkdir(parents=True, exist_ok=True) CONF.write_text(json.dumps({"version": 1, "mirror": "cn", "mirror_at": "2026-11-01", "kept_for_later": {"a": 1}}), encoding="utf-8") d = Desk() @@ -143,13 +156,17 @@ def read(): if s["studio"] != {"studio_lang": None, "studio_theme": None, "agent_default": None}: bad.append(f"studio {s['studio']}") if s["mirror"] != {"mode": "cn", "why": None, "at": "2026-11-01"}: bad.append(f"mirror {s['mirror']}") L = s["local"]["lines"] - if L.get("effort") != "quick" or L.get("budget") != "每支片子 5 美元" or L.get("review") is not None or L.get("sound") is not None: - bad.append(f"LOCAL.md's lines (a template's {{…}} and a comment are not values): {L}") - if [k["kind"] for k in s["agents"]["kinds"]] != ["claude", "codex", "dsh"] or any(k["installed"] for k in s["agents"]["kinds"]): + if L.get("effort") != "quick" or L.get("budget") != "每支片子 5 美元" or L.get("review") is not None or L.get("sound") is not None or L.get("assets") is not None: + bad.append(f"LOCAL.md's lines (only list items; a template's {{…}}, its bracketed hint and a comment are no part of a value): {L}") + if [(k["kind"], k["installed"]) for k in s["agents"]["kinds"]] != [("claude", False), ("codex", True), ("dsh", False)]: bad.append(f"agents {s['agents']}") - if not s["about"].get("version"): bad.append("no version") + if {"path": os.path.realpath(FILMS), "shown": "~/films"} not in s["roots"] or any("no-such-folder" in r["path"] for r in s["roots"]): + bad.append(f"the films folders (those that exist, ~ for the home folder): {s['roots']}") + if not s["about"].get("version") or not str(s["about"].get("url", "")).startswith("https://github.com/ZLHad/OpenVideoHarness/releases"): + bad.append(f"about {s['about']}") return "; ".join(bad) or None - check("GET /api/settings: only with this run's token; Studio's three settings, the mirror, LOCAL.md's lines as shown (never a template or a comment), the agents, the version", read) + return "; ".join(bad) or None + check("GET /api/settings: only with this run's token; Studio's three settings, the mirror, LOCAL.md's list items as shown (never a template, its hint, a comment or a line in a note), the agents, the films folders that exist (~ for home), the version and its notes", read) def write(): bad = [] @@ -160,6 +177,8 @@ def write(): c = conf() if (c.get("studio_theme"), c.get("studio_lang"), c.get("agent_default")) != ("prism", "en", "codex"): bad.append(f"the file: {c}") if c.get("kept_for_later") != {"a": 1} or c.get("mirror") != "cn": bad.append(f"a key it does not change was not kept: {c}") + page = urllib.request.urlopen(f"http://127.0.0.1:{d.port}/").read().decode() + if '' not in page or '' not in page: bad.append("the page served does not carry the look and the language kept") st, s = d.req("POST", "/api/settings", {"name": "studio_lang", "value": None}) if st != 200 or "studio_lang" in conf() or s["studio"]["studio_lang"] is not None: bad.append(f"null (back to Studio's default): {st} {conf()}") st, a = d.req("GET", "/api/space/agents") @@ -185,14 +204,25 @@ def refusals(): before = CONF.read_bytes() for body in ({"name": "studio_theme", "value": "neon"}, {"name": "GEMINI_API_KEY", "value": "x"}, {"name": "mirror", "value": "nope"}, {"name": "studio_lang", "value": 3}, {"name": "model:claude", "value": "claude-opus-5-5"}, - {"name": "effort:nobody", "value": "high"}, {"value": "en"}): + {"name": "effort:nobody", "value": "high"}, {"value": "en"}, {"name": "agent_default", "value": "dsh"}, + {"name": "reveal", "value": "/"}, {"name": "reveal", "value": str(T)}): st, _ = d.req("POST", "/api/settings", body) if st != 400: bad.append(f"{body}: {st}") if d.req("POST", "/api/settings", {"name": "studio_theme", "value": "bridge"}, token=False)[0] != 403: bad.append("no token") if d.req("POST", "/api/settings", {"name": "studio_theme", "value": "bridge"}, origin="http://evil.example")[0] != 403: bad.append("another origin") if CONF.read_bytes() != before: bad.append("a refused request changed the file") return "; ".join(bad) or None - check("POST /api/settings refuses what is not one of its settings or values (a model no chat offered, any key's name), without the token, from another origin, and changes nothing then", refusals) + check("POST /api/settings refuses what is not one of its settings or values (a model no chat offered, any key's name, an agent not set up, a folder that is not one of its films folders), without the token, from another origin, and changes nothing then", refusals) + + def reveal(): + st, _ = d.req("POST", "/api/settings", {"name": "reveal", "value": os.path.realpath(FILMS)}) + for _ in range(50): + if REVEAL.exists(): + break + time.sleep(0.1) + got = REVEAL.read_text().split("\n")[:-1] if REVEAL.exists() else [] + return None if st == 200 and got == [os.path.realpath(FILMS)] else f"{st}, opened {got}" + check("a films folder opens in the file browser (a stand-in here), that folder and nothing else", reveal) def local_untouched(): return None if "默认努力程度:quick" in LOCAL.read_text(encoding="utf-8") and not list(T.glob("LOCAL.md.*")) else "LOCAL.md was written" @@ -201,6 +231,49 @@ def local_untouched(): d.stop() +def page_check(): + """settings.js and agent.js in node: what this machine keeps wins over this browser's copy; the top bar's language and look + buttons save; a new conversation starts with the default agent that is set up.""" + node = shutil.which("node") + if not node: + return None + prog = r""" +const vm = require("vm"), fs = require("fs"), dir = process.argv[1]; +const on = {}, posts = []; +const listen = (k, f) => { (on[k] = on[k] || []).push(f); }; +const doc = { querySelector: () => null, querySelectorAll: () => [], documentElement: { lang: "", getAttribute: () => "darkfield" }, addEventListener: listen }; +const g = vm.createContext({ console, document: doc, window: { addEventListener: listen }, navigator: { platform: "MacIntel" }, URL, + localStorage: { getItem: () => null, setItem() {} }, setTimeout: () => 0, clearInterval() {}, setInterval: () => 0, requestAnimationFrame: () => 0, + fetch: async (url, o) => { if (o && o.method === "POST") posts.push(JSON.parse(o.body)); return { ok: true, status: 200, json: async () => ({}) }; } }); +vm.runInContext(fs.readFileSync(dir + "/core.js", "utf8"), g); +vm.runInContext("let TOKEN = 't'; function toast() {} function parse() { return { view: 'home' }; } const OVH = { theme() {} }; LANG = 'en';", g); +for (const f of ["settings.js", "agent.js"]) vm.runInContext(fs.readFileSync(dir + "/" + f, "utf8") + (f === "agent.js" ? "\nthis.AGENT = AGENT;" : "\nthis.SETTINGS = SETTINGS;"), g); +const P = g.SETTINGS._plan; +const plans = [P({ studio_theme: "prism", studio_lang: "zh" }, "bridge", "en"), P({}, "bridge", "en"), P({}, "darkfield", "zh"), P({ studio_lang: "en" }, "prism", "zh")]; +const click = (sel, extra) => Promise.all(on.click.map((f) => f({ target: { closest: (s) => (s === sel ? Object.assign({ closest: () => null }, extra) : null) }, isTrusted: true }))); +(async () => { + await click("#lang"); + await click("[data-theme-set]", { dataset: { themeSet: "bridge" } }); + const K = g.AGENT._defaultKind; + const ks = [{ kind: "claude", installed: true }, { kind: "codex", installed: true }, { kind: "dsh", installed: false }]; + const kinds = [K({ agents: ks, default: "codex" }), K({ agents: ks, default: "dsh" }), K({ agents: ks, default: null }), K({ agents: [{ kind: "claude", installed: false }], default: null })]; + console.log(JSON.stringify({ plans, posts, kinds })); +})(); +""" + out = subprocess.run([node, "-e", prog, str(HERE / "static")], capture_output=True, text=True, timeout=30) + if out.returncode: + return out.stderr[-400:] + r = json.loads(out.stdout) + want = [{"theme": "prism", "lang": "zh", "keep_theme": None, "keep_lang": None}, {"theme": "bridge", "lang": "en", "keep_theme": "bridge", "keep_lang": "en"}, + {"theme": "darkfield", "lang": "zh", "keep_theme": None, "keep_lang": None}, {"theme": "prism", "lang": "en", "keep_theme": "prism", "keep_lang": None}] + if r["plans"] != want: + return f"what this machine keeps does not win over the browser's copy: {r['plans']}" + if r["posts"] != [{"name": "studio_lang", "value": "en"}, {"name": "studio_theme", "value": "bridge"}]: + return f"the top bar's buttons did not save: {r['posts']}" + if r["kinds"] != ["codex", "claude", "claude", "claude"]: + return f"a new conversation's agent: {r['kinds']}" + + def words_check(): src = (HERE / "static" / "settings.js").read_text(encoding="utf-8") zh = src[src.index(" zh: {"):src.index(" en: {")] @@ -212,6 +285,7 @@ def words_check(): check("tools/settings.py: Studio's three settings, a value it does not know read as not set, any other name or value refused, other keys kept", module_check) check("the settings page's words: every one in both languages", words_check) +check("the page in node: this machine's look and language win over the browser's copy (which is kept when the file has none); the top bar's two buttons save; a new conversation starts with the default agent when it is set up", page_check) try: run() except Exception as e: diff --git a/tools/settings.py b/tools/settings.py index cdf07ddf..fdcbb498 100644 --- a/tools/settings.py +++ b/tools/settings.py @@ -172,8 +172,8 @@ def show(d, as_json=False): return print(f"this machine's settings: {path()}" + ("" if path().exists() else " (not written yet: the defaults)")) said = {"cn": "the mainland-China mirrors, for every download (tools/mirrors.txt)", - "off": "the official sources; install.sh does not try the mirrors", - "auto": "the official sources; install.sh switches to the mirrors when the official npm registry does not answer"}[m] + "off": "the official sources; the installer does not try the mirrors", + "auto": "the official sources; the installer switches to the mirrors when the official npm registry does not answer"}[m] print(f" mirror {m}: {said}" + (f" · {d['mirror_why']}" if d.get("mirror_why") else "") + (f" ({d['mirror_at']})" if d.get("mirror_at") else "")) print(" bin/vh settings mirror cn|off|auto changes it") @@ -199,7 +199,7 @@ def main(argv): print(f"✓ downloads now come from the mainland-China mirrors ({operators()}; tools/mirrors.txt), kept in {path()};" " bin/vh settings mirror off turns that off") else: - print(f"✓ downloads come from the official sources{'' if argv[1] == 'auto' else ', and install.sh does not try the mirrors'} (kept in {path()})") + print(f"✓ downloads come from the official sources{'' if argv[1] == 'auto' else ', and the installer does not try the mirrors'} (kept in {path()})") return 0 print(f"bin/vh settings: unknown {' '.join(argv)} (bin/vh settings -h)", file=sys.stderr) return 2 From 75ebc453acc7d924f021c137ca3f12ad72d6a2be Mon Sep 17 00:00:00 2001 From: zhanglinghao Date: Sun, 22 Nov 2026 06:25:45 +0800 Subject: [PATCH 15/19] Studio's settings page takes API keys: kept in this computer's password store, found by every command - tools/keys.py: a service's key from the environment first, else the one saved in Studio, kept in the Keychain (macOS) or the Secret Service (Linux, through secret-tool); written through standard input, never an argument, never in a file; only the names tools/modules.json's services need. tts, pace, image, lyria, doctor and bin/vh read keys through it; a command the agent column runs finds a saved key (the agent's own environment still has none). - The settings page's Services section: each service, what it is for, free or paid in a word, each key not set / set in Studio / set in the environment, Set up / Replace / Remove (asked twice) / Test (doctor's free probe), where to get a key; one sentence on where a saved key is kept; an API Key is not a budget. - bin/vh doctor says "set in Studio" or "set in the environment" (--json: key_source). tools/modules.json: cost and key_url on the four services. tools/ci.sh turns the store off (OVH_KEYSTORE=none): no check finds a key the person saved, so nothing paid is called. - Tests on a keychain of their own (made with HOME in the scratch folder, named on every call, deleted after; the person's search list checked unchanged) or a stand-in secret-tool elsewhere. --- CONTRIBUTING.md | 4 +- bin/vh | 2 +- changes/settings-keys.md | 6 ++ tools/assets/image.py | 7 +- tools/audio/README.md | 2 +- tools/audio/lyria.py | 5 +- tools/audio/pace.py | 4 +- tools/audio/tts.py | 21 +++-- tools/ci-paths.txt | 6 +- tools/ci.sh | 1 + tools/commands.json | 8 +- tools/desk/README.md | 3 +- tools/desk/settings_api.py | 65 ++++++++++++- tools/desk/static/settings.css | 20 ++++ tools/desk/static/settings.js | 84 ++++++++++++++++- tools/desk/test_settings.py | 162 +++++++++++++++++++++++++++++++++ tools/doctor.py | 25 +++-- tools/keys.py | 155 +++++++++++++++++++++++++++++++ tools/modules.json | 4 + 19 files changed, 541 insertions(+), 43 deletions(-) create mode 100644 changes/settings-keys.md create mode 100644 tools/keys.py diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md index a5c0cfb4..a0edd1b5 100644 --- a/CONTRIBUTING.md +++ b/CONTRIBUTING.md @@ -46,7 +46,7 @@ - **新的状态写进机器可读的文件,项目根目录不再加 markdown。** 给工具读的放 JSON(追加的记录用 JSONL,像 `.ovh/activity.jsonl`),带 `"version": 1`,`bin/vh status --json` 能汇总;人写的想法和决定仍然写在模板现有的那几份 markdown 里。版本字段新文件一律拼 `version`;已有文件的 `v`(`edit.json`、台账、活动记录这些)不改名。 - **新的中间文件在 `tools/artifacts.json` 登记一项。** 一支片子里多了一种文件(命令写的,或者工具开始读的),就加一项:路径、谁写谁读、什么时候必须有、怎么判过期(`stale`,判不了就是 `null`)、`bin/vh clean` 怎么处理它。工具和客户端要靠它的形状时,在 `tools/schemas/` 放一份 schema 和好坏两种 fixture,只用 `tools/schemalite.py` 读得懂的关键字;字段只加不改,所以 schema 只钉必需的字段和类型,允许多字段。`bin/vh artifacts check` 查表和命令表、schema、`tools/clean.py` 对得上:`tools/commands.json` 的 `writes`、`reads` 里 `/…` 的路径没有对应的一项,CI 就不过。反过来,一项里列的 writer,在 `tools/commands.json` 里要有一行 `writes` 写到它的路径(自由文本说不清的,在 `tools/artifacts.py` 的 `NOT_SAID` 里写明原因)。 - **检查给出路。** `bin/vh check` 新报一类问题(checkrec.py 的一种 kind)时,在 `tools/remedies.json` 给它配一两条出路:能解决它的配方筛选、命令或文档的一节。检查只报告,出路只给选项;`tools/remedies.py check` 查每条都真有其物。 -- **外接模块记在 `tools/modules.json`。** 别人在维护、我们只是调用的东西(程序、npm 和 Python 包、模型、联网的服务、agent),在第一次有命令用它的那个 PR 里登记一项:用途;版本(`pin` 钉死的,`min` 最低,`range`,`tested` 测过的,服务写默认模型,按日期发版的工具可以给 `max_age_days`);许可;要什么账号、key、平台,以及依赖这张表里的哪些模块(`needs`,模块名写在 `programs` 里,只在某个平台能用的再写 `elsewhere`:别处用什么);适配文件在哪(`adapter`);哪些命令用它(`commands`);`bin/vh doctor` 怎么查它(`check`)。联网的服务再给一个不花钱的探测(`probe`,`bin/vh doctor --probe` 调它)。key 只放进 header,不进 URL,不跟着重定向走,只走 https(本机除外),不打印,失败时也只报状态码和错误码。改钉的版本时表里的 `pin` 一起改:HyperFrames 的,CI 拿它和 `bin/vh`、`styles/_swatch/package.json` 对。表本身用 `python3 tools/doctor.py --check` 查。 +- **外接模块记在 `tools/modules.json`。** 别人在维护、我们只是调用的东西(程序、npm 和 Python 包、模型、联网的服务、agent),在第一次有命令用它的那个 PR 里登记一项:用途;版本(`pin` 钉死的,`min` 最低,`range`,`tested` 测过的,服务写默认模型,按日期发版的工具可以给 `max_age_days`);许可;要什么账号、key、平台,以及依赖这张表里的哪些模块(`needs`,模块名写在 `programs` 里,只在某个平台能用的再写 `elsewhere`:别处用什么);适配文件在哪(`adapter`);哪些命令用它(`commands`);`bin/vh doctor` 怎么查它(`check`)。联网的服务再给一个不花钱的探测(`probe`,`bin/vh doctor --probe` 调它);要 key 的服务再写 `cost`(`free`、`free_tier`、`paid`)和 `key_url`(去哪拿 key 的 https 地址),Studio 设置页的"服务"一节照它们画。key 只放进 header,不进 URL,不跟着重定向走,只走 https(本机除外),不打印,失败时也只报状态码和错误码。改钉的版本时表里的 `pin` 一起改:HyperFrames 的,CI 拿它和 `bin/vh`、`styles/_swatch/package.json` 对。表本身用 `python3 tools/doctor.py --check` 查。 ## 加一个风格 @@ -124,7 +124,7 @@ d=$(mktemp -d) && printf '#!/bin/sh\nexec uvx --from shellcheck-py shellcheck "$ - **有 `--offline <文件夹>`。** 命令照常跑,只是响应从录音里取(`fetch.Replay`;Range 照样回答,续传也能离线测)。找不到对应的 URL 就失败,不会偷偷联网。 - **CI 只测解析、台账写入和许可分类。** 用录好的响应跑命令,查三样:解析出的字段;写进 `assets/ledger.json` 的记录,对着 `tools/assets/asset.schema.json` 查;许可落进哪一类(`tools/assets/licenses.py`,对照表是 `tools/assets/fixtures/licenses.tsv`)。活的接口不进 CI,由 `bin/vh doctor --probe` 探(`tools/modules.json` 里登记的服务)。 -调付费接口的命令还要守预算:每次调用都包在 `tools/assets/budget.py` 的 `with budget.hold(项目, 估价, 币种, 做什么) as h:` 里。它在锁里检查并预占这笔估价,没有预算或者超了就拒绝,并说差多少;几个进程同时调用也不会一起越过预算。调用完用 `h.settle(实际花费)` 结算,没计费就记 0;出了异常没结算,按估价算。登记产物时把花费交给 `ledger.add(…, cost=…)`,花费记录里已有的不会重记。key 只从环境变量读,放在请求头里,不进 URL、录音和日志;记录和报错里的 URL 都去掉 query 的值(`fetch.redact`),带 key、token、签名的 URL 不录。 +调付费接口的命令还要守预算:每次调用都包在 `tools/assets/budget.py` 的 `with budget.hold(项目, 估价, 币种, 做什么) as h:` 里。它在锁里检查并预占这笔估价,没有预算或者超了就拒绝,并说差多少;几个进程同时调用也不会一起越过预算。调用完用 `h.settle(实际花费)` 结算,没计费就记 0;出了异常没结算,按估价算。登记产物时把花费交给 `ledger.add(…, cost=…)`,花费记录里已有的不会重记。key 一律经 `tools/keys.py` 取(先环境变量,没有再用人在 Studio 设置页里存的那一份,它在系统自己的密码库里),放在请求头里,不进 URL、录音和日志;记录和报错里的 URL 都去掉 query 的值(`fetch.redact`),带 key、token、签名的 URL 不录。 ## 在 GitHub 上启用规则集 diff --git a/bin/vh b/bin/vh index 1b082d88..a30920e7 100755 --- a/bin/vh +++ b/bin/vh @@ -1343,7 +1343,7 @@ cmd_tts() { # everything from the first --flag on goes straight to tts.py (--beats, --snap, --lead, --gap, --min-gap, --align, --join, --candidates, --min-sim, --vocab, --resume) [ "$voice" = "-" ] && voice=""; [ "$lang" = "-" ] && lang=""; [ "$instruct" = "-" ] && instruct="" # no lang: tts.py picks zh, or en for an English-only script case "$prov" in qwen) deps="--with mlx-audio" ;; edge) deps="--with edge-tts" ;; - dashscope) [ -z "${DASHSCOPE_API_KEY:-}" ] || deps="--with dashscope" ;; esac # no key: tts.py says so, with no package fetched first + dashscope) python3 "$ROOT/tools/keys.py" has DASHSCOPE_API_KEY && deps="--with dashscope" ;; esac # no key (environment or Studio): tts.py says so, with no package fetched first deps="$deps${np:+ $np}" # no script yet: tts.py writes a sample and stops, with no package fetched for it (it needs none for that) [ -f "$proj/audio/script.txt" ] || exec python3 "$ROOT/tools/audio/tts.py" "$proj" --provider "$prov" diff --git a/changes/settings-keys.md b/changes/settings-keys.md new file mode 100644 index 00000000..baf63084 --- /dev/null +++ b/changes/settings-keys.md @@ -0,0 +1,6 @@ +**Studio 的设置页里能填 API Key:存在这台电脑的钥匙串里,终端和 Studio 里的对话都用得上** +- Why: 配音、出图、作曲这些在线服务要 API Key,原来只能写成终端里的环境变量;Studio 里的对话根本拿不到,新人也不知道该去哪拿、怎么设。 +- 设置页多一节"服务":Gemini、MiniMax、ElevenLabs、阿里云百炼,各写用来做什么、免费还是收费、去哪拿 API Key;可以填上、换一个、拿掉,"测一下"用服务不花钱的地址问一次。配音默认仍用这台电脑上的声音,不用任何 key。 +- 填的 key 存进系统自己的密码库(macOS 的钥匙串;Linux 上有 Secret Service 时用它,没有就照旧只能用环境变量),不写进任何文件,页面以后只知道设没设。环境变量里有的,仍然优先用环境变量的。 +- 所有读 key 的命令都改成先看环境变量、再看 Studio 里存的(`tools/keys.py`);`bin/vh doctor` 说清是"在 Studio 里设了"还是"在环境变量里设了"。 +- 有 key 不等于能花钱:付费调用的预算规则一点没变。 diff --git a/tools/assets/image.py b/tools/assets/image.py index 47920323..3ba109da 100644 --- a/tools/assets/image.py +++ b/tools/assets/image.py @@ -65,6 +65,7 @@ sys.path.insert(0, str(HERE)) sys.path.insert(0, str(HERE.parent)) import assets as A, budget, fetch, ledger # noqa: E402,E401 +import keys # noqa: E402 (tools/keys.py: the environment's key, else the one saved in Studio) PROG = "bin/vh image" SUB = ("gen", "cutout", "prices") @@ -517,7 +518,7 @@ def paid_call(h, estimate, url, body, opener, timeout=180): host) settle at 0; a timeout, a reset or an answer that cannot be read leave the hold at the estimate, as such a call may have been billed. → the answer.""" try: - return fetch.post_json(url, body, opener, secret={"x-goog-api-key": os.environ.get("GEMINI_API_KEY", "")}, timeout=timeout) + return fetch.post_json(url, body, opener, secret={"x-goog-api-key": keys.get("GEMINI_API_KEY") or ""}, timeout=timeout) except fetch.FetchError as e: if (e.status or 0) >= 400 or not e.sent: h.settle(0) @@ -619,8 +620,8 @@ def cmd_gen(a): say(" nothing called (--dry-run)") return 0 if a.provider == "gemini": - if not a.offline and not os.environ.get("GEMINI_API_KEY"): - raise Usage("set GEMINI_API_KEY (Google AI Studio → Get API key): it is read from the environment only") + if not a.offline and not keys.get("GEMINI_API_KEY"): + raise Usage("set GEMINI_API_KEY (Google AI Studio → Get API key), or save it in Studio's settings (Services)") if not plan["budget"]["ok"]: raise Failed(f"{plan['budget']['message']} (bin/vh image gen --dry-run shows the estimate)") if refs: diff --git a/tools/audio/README.md b/tools/audio/README.md index aa06007b..e30f550f 100644 --- a/tools/audio/README.md +++ b/tools/audio/README.md @@ -169,7 +169,7 @@ bin/vh tts projects/

    minimax "Chinese (Mandarin)_Reliable_Executive" zh --joi MINIMAX_TTS_SPEED=1.25 bin/vh tts projects/

    minimax - zh --join all --gap 0.3 # 默认音色,语速 1.25,句间停 0.3 s ``` -- **key 和接口**:请求发到国际站 `https://api.minimax.io/v1/t2a_v2`。key 只从环境变量读,先找 `MINIMAX_TOKEN_PLAN_KEY`(Token Plan 的 Subscription Key,花的是买的 Credits),没有再用 `MINIMAX_API_KEY`(按量付费,账户没有余额时报 `1008 insufficient balance`)。买了 Credits 却只设了按量付费的 key,也是 1008。国际站的 key 发到国内站 `api.minimaxi.com` 会报 `2049 invalid api key`,所以默认走国际站;用国内站(platform.minimaxi.com)的 key 时,设 `MINIMAX_BASE_URL=https://api.minimaxi.com`。报错只写 key 来自哪个变量,不写 key 本身; +- **key 和接口**:请求发到国际站 `https://api.minimax.io/v1/t2a_v2`。key 先从环境变量读,没有再用 Studio 设置页里存的(`tools/keys.py`),先找 `MINIMAX_TOKEN_PLAN_KEY`(Token Plan 的 Subscription Key,花的是买的 Credits),没有再用 `MINIMAX_API_KEY`(按量付费,账户没有余额时报 `1008 insufficient balance`)。买了 Credits 却只设了按量付费的 key,也是 1008。国际站的 key 发到国内站 `api.minimaxi.com` 会报 `2049 invalid api key`,所以默认走国际站;用国内站(platform.minimaxi.com)的 key 时,设 `MINIMAX_BASE_URL=https://api.minimaxi.com`。报错只写 key 来自哪个变量,不写 key 本身; - **音色**:`--voice` 写系统音色的 id。中文音色都以 `Chinese (Mandarin)_` 开头,例如 `Chinese (Mandarin)_Reliable_Executive`(沉稳的中年男声,默认)、`_News_Anchor`(女声新闻主播)、`_Male_Announcer`、`_Radio_Host`;英文默认 `English_expressive_narrator`。全部系统音色(2026-10-07 有 332 个)用 `POST /v1/get_voice`、body `{"voice_type": "system"}` 列出,`bin/vh voices` 只管 Gemini: ```bash diff --git a/tools/audio/lyria.py b/tools/audio/lyria.py index 29222f8f..7b679b48 100644 --- a/tools/audio/lyria.py +++ b/tools/audio/lyria.py @@ -37,6 +37,7 @@ sys.path.insert(0, str(ROOT / "tools" / "assets")) sys.path.insert(0, str(ROOT / "tools")) import assets as A, budget, fetch, image, ledger # noqa: E402,E401 +import keys # noqa: E402 (tools/keys.py: the environment's key, else the one saved in Studio) PROG = "bin/vh music --provider lyria" API = image.API @@ -131,8 +132,8 @@ def cmd_gen(a): say(f" {chk['message']}") say(" nothing called (--dry-run)") return 0 - if not a.offline and not os.environ.get("GEMINI_API_KEY"): - raise Usage("set GEMINI_API_KEY (Google AI Studio → Get API key): it is read from the environment only") + if not a.offline and not keys.get("GEMINI_API_KEY"): + raise Usage("set GEMINI_API_KEY (Google AI Studio → Get API key), or save it in Studio's settings (Services)") if not chk["ok"]: raise Failed(f"{chk['message']} (--dry-run shows the price)") folder = project / GENMUSIC / cid diff --git a/tools/audio/pace.py b/tools/audio/pace.py index d3261896..d8fe29d6 100644 --- a/tools/audio/pace.py +++ b/tools/audio/pace.py @@ -677,7 +677,7 @@ def captions(old, skip_lint=False): sys.exit(f"no word times for {', '.join(missing[:6])}{' …' if len(missing) > 6 else ''}: run bin/vh tts … --align gemini" f" --resume first, or pass --align gemini|whisper here to transcribe the take") if (missing and not found) or (a.align != "map" and not a.dry_run): # before anything is written - if a.align == "gemini" and not os.environ.get("GEMINI_API_KEY"): + if a.align == "gemini" and not tts.keys.get("GEMINI_API_KEY"): sys.exit("set GEMINI_API_KEY (Google AI Studio → Get API key) for --align gemini; nothing was written") if a.align == "whisper" and importlib.util.find_spec("mlx_whisper") is None: sys.exit("--align whisper needs mlx-whisper (Apple Silicon; bin/vh pace adds it with --align whisper); nothing was written") @@ -758,7 +758,7 @@ def save(): print(f"→ {rel(wav)} ({out['duration']} s) · {rel(tlp)} · the original: {rel(raw_wav)}, {rel(raw_tl)}") rc = 0 if a.align != "map": - if a.align == "gemini" and not os.environ.get("GEMINI_API_KEY"): + if a.align == "gemini" and not tts.keys.get("GEMINI_API_KEY"): sys.exit("set GEMINI_API_KEY for --align gemini: the paced take is written with mapped word times") try: fresh = align_take(new, wav, a.align, a.lang, tmp, out["duration"]) diff --git a/tools/audio/tts.py b/tools/audio/tts.py index b463c922..2e5eff07 100644 --- a/tools/audio/tts.py +++ b/tools/audio/tts.py @@ -147,6 +147,8 @@ from pathlib import Path sys.path.insert(0, str(Path(__file__).resolve().parent)) import firstuse # noqa: E402 the big first downloads: their sizes, the line before them, their progress +sys.path.insert(0, str(Path(__file__).resolve().parents[1])) +import keys # noqa: E402 an API key: the environment's, else the one saved in Studio's settings (tools/keys.py) RESUME = None # what a stop keeps for a resume, once a line is on disk @@ -216,7 +218,7 @@ def gemini_call(path, body=None, method=None, query=None, timeout=180, tries=3): so does one asking for more than 90 s. The delay and the quota are read from the first 8 KB of the body: a long quota message puts "retry in Ns" past the first 500 bytes, which are all that the error message repeats. A call that fails for good raises GeminiError.""" - key = os.environ.get("GEMINI_API_KEY") or sys.exit("set GEMINI_API_KEY (Google AI Studio → Get API key)") + key = keys.get("GEMINI_API_KEY") or sys.exit("set GEMINI_API_KEY (Google AI Studio → Get API key)") url = f"{GEMINI_API}/{path}" + (f"?{urllib.parse.urlencode(query, doseq=True)}" if query else "") data = None if body is None else json.dumps(body).encode() k = limited = 0 @@ -335,7 +337,7 @@ def p_edge(text, voice, out: Path, tmp: Path, lang, instruct=None): return None def p_elevenlabs(text, voice, out: Path, tmp: Path, lang, instruct=None): - key = os.environ.get("ELEVENLABS_API_KEY") or no_key("elevenlabs") + key = keys.get("ELEVENLABS_API_KEY") or no_key("elevenlabs") voice = voice or sys.exit("--voice is required for elevenlabs") body = json.dumps({"text": text, "model_id": os.environ.get("ELEVENLABS_MODEL", "eleven_multilingual_v2")}).encode() req = urllib.request.Request(f"https://api.elevenlabs.io/v1/text-to-speech/{voice}/with-timestamps?output_format=mp3_44100_128", @@ -358,7 +360,7 @@ def char_words(chars, starts, ends): def p_dashscope(text, voice, out: Path, tmp: Path, lang, instruct=None): import dashscope # provided by `uv run --with dashscope` - key = os.environ.get("DASHSCOPE_API_KEY") or no_key("dashscope") + key = keys.get("DASHSCOPE_API_KEY") or no_key("dashscope") if os.environ.get("DASHSCOPE_BASE_URL"): dashscope.base_http_api_url = os.environ["DASHSCOPE_BASE_URL"] resp = dashscope.MultiModalConversation.call( @@ -415,8 +417,11 @@ class MinimaxError(RuntimeError): def minimax_key(): """(key, its variable): the Token Plan key first, since only it spends Token Plan credits.""" - var = next((k for k in ("MINIMAX_TOKEN_PLAN_KEY", "MINIMAX_API_KEY") if os.environ.get(k)), None) - return (os.environ[var], var) if var else (None, None) + for var in ("MINIMAX_TOKEN_PLAN_KEY", "MINIMAX_API_KEY"): + key = keys.get(var) + if key: + return key, var + return None, None def minimax_hint(code, base): if code in (1004, 2049): # authentication failed / invalid api key @@ -1116,7 +1121,7 @@ def audition(a): gemini = a.provider.startswith("gemini") if a.align == "local": need_local_asr() - if (gemini or a.align == "gemini") and not os.environ.get("GEMINI_API_KEY"): + if (gemini or a.align == "gemini") and not keys.get("GEMINI_API_KEY"): sys.exit("voices audition: set GEMINI_API_KEY (Google AI Studio → Get API key)" + (f" for --provider {a.provider}" if gemini else " for --align gemini") + "; nothing was synthesized") if a.provider == "minimax" and not minimax_key()[0]: @@ -1262,7 +1267,7 @@ def main(): print(" --join recovers line boundaries from word timestamps → --align gemini is on") if a.align == "local": # before anything is synthesized or deleted need_local_asr() - if align and a.align != "local" and not os.environ.get("GEMINI_API_KEY"): + if align and a.align != "local" and not keys.get("GEMINI_API_KEY"): sys.exit("set GEMINI_API_KEY (Google AI Studio → Get API key): --align gemini / --join transcribe with Gemini (or --align local)") if man and a.provider == "minimax" and join != "none" and man.get("gap") != a.gap: sys.exit(f"--resume: --gap was {man.get('gap')} for the run, now {a.gap}; in a joined minimax request it is part of the" @@ -1282,7 +1287,7 @@ def linked(texts): # one minimax request: the lines linked by a pause mark of blocks.append([s]) wavs = [f"{i+1:02d}.wav" for i in range(len(segs))] if join == "none" else [f"_block{i+1:02d}.wav" for i in range(len(blocks))] voiced = a.resume and all((vo / f).exists() and ((vo / f).with_suffix(".words.json").exists() or not timed) for f in wavs) # the synthesis loops' own test - if not voiced and a.provider in ("elevenlabs", "dashscope", "gemini", "gemini-lite") and not os.environ.get(KEY_OF[a.provider].split()[0]): + if not voiced and a.provider in ("elevenlabs", "dashscope", "gemini", "gemini-lite") and not keys.get(KEY_OF[a.provider].split()[0]): no_key(a.provider) # before anything is synthesized or deleted; --resume with all voiced needs none if a.provider == "minimax": minimax_settings() # a value out of range exits here, not mid-run diff --git a/tools/ci-paths.txt b/tools/ci-paths.txt index 45108a7e..6e56b39e 100644 --- a/tools/ci-paths.txt +++ b/tools/ci-paths.txt @@ -20,7 +20,7 @@ always static_checks doc_checks readpath_report # change notes, landing, this table and its reader changes/** plumbing_checks studio_checks land_checks -CHANGELOG.md plumbing_checks smoke_checks desk_checks studio_checks cancel_checks assets_checks scout_checks web_checks model3d_checks land_checks +CHANGELOG.md plumbing_checks smoke_checks desk_checks studio_checks cancel_checks assets_checks scout_checks web_checks model3d_checks land_checks settings_page_checks tools/changes.py plumbing_checks studio_checks tools/land.py land_checks tools/ci_select.py plumbing_checks @@ -37,9 +37,9 @@ CITATION.cff plumbing_checks studio_checks LICENSE hf_checks cases/** gate_checks desk_checks console_checks status_checks contract_checks cancel_checks history_checks know_checks artifacts_checks studio_checks showcase/** smoke_checks timeline_checks decision_checks web_checks model3d_checks -install.sh plumbing_checks smoke_checks desk_checks studio_checks cancel_checks assets_checks scout_checks web_checks model3d_checks +install.sh plumbing_checks smoke_checks desk_checks studio_checks cancel_checks assets_checks scout_checks web_checks model3d_checks settings_page_checks LOCAL.example.md plumbing_checks smoke_checks desk_checks studio_checks cancel_checks assets_checks scout_checks web_checks model3d_checks settings_page_checks -skills/** smoke_checks cancel_checks assets_checks scout_checks web_checks model3d_checks +skills/** smoke_checks cancel_checks assets_checks scout_checks web_checks model3d_checks settings_page_checks # tools a few groups reach tools/model3d/** model3d_checks diff --git a/tools/ci.sh b/tools/ci.sh index 700ea9f3..8f187498 100755 --- a/tools/ci.sh +++ b/tools/ci.sh @@ -12768,6 +12768,7 @@ CI_TMP=$(mktemp -d "${TMPDIR:-/tmp}/vh-ci-run.XXXXXX") || exit 2 CI_TMP=${CI_TMP//\/\//\/} # one / (a TMPDIR ending in / gives two) export TMPDIR="$CI_TMP" CI_OWN_TMP=" gate_checks decision_checks desk_checks console_checks agent_checks settings_page_checks studio_checks activity_checks status_checks cancel_checks history_checks artifacts_checks " +export OVH_KEYSTORE=none # no key the person saved in Studio is found by a check (tools/keys.py): a "no key" check stays one, and nothing paid is called export OVH_GATE_STUDIO=0 # a standard film's stop does not look for a running Studio: the checks test the page and their own desks (the check of that rule clears it) unset OVH_PROJECTS # the desks a check starts in the background (bin/vh gate's is in a session of its own) are recorded and stopped when the diff --git a/tools/commands.json b/tools/commands.json index f83dcf7c..5fef6c14 100644 --- a/tools/commands.json +++ b/tools/commands.json @@ -578,7 +578,7 @@ "reads": [ "the prompt (--prompt, --prompt-file) and the reference pictures (--ref; cast:: /cast//'s, bin/vh cast)", "/BRIEF.md (Budget; Output for the aspect), LOCAL.md (默认预算)", - "GEMINI_API_KEY from the environment; or the codex CLI, signed in with ChatGPT", + "GEMINI_API_KEY from the environment or Studio's settings (tools/keys.py); or the codex CLI, signed in with ChatGPT", "--offline : recorded answers" ], "writes": [ @@ -1634,7 +1634,7 @@ "stages": ["4"], "reads": [ "/audio/script.txt", - "a cloud provider's key, from the environment" + "a cloud provider's key, from the environment or Studio's settings (tools/keys.py)" ], "writes": [ "/audio/voiceover..wav", @@ -1689,7 +1689,7 @@ "stages": ["4", "3"], "reads": [ "--text f.txt (audition)", - "the provider's key, from the environment" + "the provider's key, from the environment or Studio's settings (tools/keys.py)" ], "writes": [ "--out dir: a WAV per voice and audition.json (audition)", @@ -1869,7 +1869,7 @@ "stages": ["4"], "reads": [ "", - "--provider lyria: the prompt, GEMINI_API_KEY from the environment, /BRIEF.md (Budget)" + "--provider lyria: the prompt, GEMINI_API_KEY from the environment or Studio's settings (tools/keys.py), /BRIEF.md (Budget)" ], "writes": [ "", diff --git a/tools/desk/README.md b/tools/desk/README.md index 22358d14..074517c4 100644 --- a/tools/desk/README.md +++ b/tools/desk/README.md @@ -135,7 +135,7 @@ bin/vh desk agents install # 装那一家的 ACP 适配器 | `GET /api/p/<键>/agent//events?token=…[&after=N]` | 这个对话的事件,SSE:先一个 `hello`(会话的状态、设置、agent 报的能力),然后 `after`(或 `Last-Event-ID`)之后的每一件,再来的边到边推;每 5 秒一行注释保活。要页面的令牌 | | `POST /api/p/<键>/agent/new` | `{kind, personal, model, effort}`:开一个新对话,起好 agent,带着它的设置回来;`model`、`effort` 是人在开新对话的框里挑的(可以不带),agent 报了这个值才设、并记成这一家下次的起点,没报就不管;没装 424,起不来 503。`GET …/agents` 每一家的 `choices` 是新对话会用什么开始:`{model, effort: {value, name, from}, offered}`,`from` 是 picked(你挑过的)、default(Studio 的默认)、dsh(桌面版的推理档)、agent(它自己的),`offered` 是这次运行里它报过的选项(没见过是 null) | | `GET /api/machine` | `{lacks: [{what, state}], platform}`:这台电脑还缺什么(`bin/vh doctor --json` 读出的 FFmpeg、Node、uv、git 没有或太旧,没有画网页用的浏览器,一家 agent 适配器都没装),空间页照它出那一块;不要令牌。什么都不缺时这次运行一直记着;缺东西时,隔一分钟以上再问会重新看一次(人可能已经装上了);doctor 没说清楚时不记,回 `error` | -| `GET /api/settings`、`POST /api/settings {name, value}` | 设置页(`settings_api.py`):要令牌。GET 回 `{version: 1, file, studio, mirror, agents, roots, local, about}`:Studio 自己的三项(`studio_lang`、`studio_theme`、`agent_default`,没设是 `null`)、下载镜像、每种 agent 装没装和新对话从什么模型和思考深度开始(`choices`,同对话列)、LOCAL.md 里人和 agent 都读的那几行(只读,模板的 `{…}` 和注释不算值)、版本。POST 只认这几个名字:`studio_lang`、`studio_theme`、`agent_default`(`null` 回到 Studio 的默认;没装好的 agent 不收)、`mirror`(`cn`、`off`、`auto`)、`model:`、`effort:`(只认这次运行里这种 agent 在对话里给过的值,记进 `picks.json`,没写进去就报错)、`reveal`(值是 GET 列出的片子文件夹之一:在系统的文件浏览器里打开它,`$OVH_REVEAL` 可以换成别的命令,一分钟至多二十次);别的名字、值、没有令牌、别的来源一律拒绝,什么都不改。写都经 `tools/settings.py`,从不直接写文件,也不写 LOCAL.md。 | +| `GET /api/settings`、`POST /api/settings {name, value}` | 设置页(`settings_api.py`):要令牌。GET 回 `{version: 1, file, studio, mirror, agents, roots, local, services, store, about}`:Studio 自己的三项(`studio_lang`、`studio_theme`、`agent_default`,没设是 `null`)、下载镜像、每种 agent 装没装和新对话从什么模型和思考深度开始(`choices`,同对话列)、LOCAL.md 里人和 agent 都读的那几行(只读,模板的 `{…}` 和注释不算值)、版本。POST 只认这几个名字:`studio_lang`、`studio_theme`、`agent_default`(`null` 回到 Studio 的默认;没装好的 agent 不收)、`mirror`(`cn`、`off`、`auto`)、`model:`、`effort:`(只认这次运行里这种 agent 在对话里给过的值,记进 `picks.json`,没写进去就报错)、`key:<变量名>`(值是 key:存进系统的密码库;`null`:拿掉;名字只认服务要的那几个,值不像 key 的不收,回的东西里从来没有 key)、`test:<服务>`(`bin/vh doctor --probe --only` 那一家,回 `{ok, probe: {state, note}}`,一分钟至多十次;`$OVH_PROBE_OFFLINE` 让它从录音里答)、`reveal`(值是 GET 列出的片子文件夹之一:在系统的文件浏览器里打开它,`$OVH_REVEAL` 可以换成别的命令,一分钟至多二十次);别的名字、值、没有令牌、别的来源一律拒绝,什么都不改。写都经 `tools/settings.py`,从不直接写文件,也不写 LOCAL.md。 | | `POST /api/p/<键>/agent/install` | `{kind}`:人点了「装上」:控制台在后台运行 `bin/vh desk agents install `,回 `{installing: {state, since, took, said}}`(`state`:running、done、no_npm、timeout、cancelled、busy、failed;`limit` 是时限秒数;`said` 是它最后三行话,家目录写成 `~`,页面不显示);`{kind, cancel: true}` 停下正在装的那一次;在装时再点是同一次;`kind` 不是三家之一(包括不是字符串)回 400;`GET …/agents` 的每一家带着同样的 `installing`,页面照它跟到装完 | | `GET /api/space/agents`、`GET /api/space/agent//events`、`POST /api/space/agent/new · install · /say · answer · stop · mode · config` | 空间那一列:和片子里的同名地址一样(要令牌、同源、页面带着空间文件夹的 `pid`),对话是从空间开、还没建片子的那些;`new` 开的对话 agent 在工作台里干活;`events`、`stop` 等也找得到从这里开、已经建好片子的对话。片子建好时事件流里来一条 `{type: notice, code: placed, key, name}`(锁被别人拿着时是 `place_busy`)。`GET /api/space/agents?sid=` 在那段对话已经建好片子时多一个 `went: {id, key}` | | `GET /api/p/<键>/agents` 的 `strays`、`POST /api/p/<键>/agent//bring` | 一支对话列还空着的新片子:可能是它的、从空间开的对话(跑过 `bin/vh new`、没找到自己的片子、这支片子是它开始以后才有的);人点"把它带到这里",那段对话就成了这支片子的(不在 `strays` 里的 409) | @@ -156,6 +156,7 @@ bin/vh desk agents install # 装那一家的 ACP 适配器 - **右边那一列**:设置页里是空间的对话(从片子里打开也一样),上面一行说明这一点,免得把它当成片子的对话。没有这一次运行的令牌时,这一页什么都不显示,只说要在 Studio 的窗口里打开,带一个打开的按钮。 - **通用**:语言、外观(三个主题的小样)、片子放在哪(这个 Studio 找片子的、真有的文件夹,家目录写成 `~`,每个后面"在访达里打开"(Linux:"打开文件夹"),服务端只开这几个文件夹之一;换地方不在页面上改:页面说让 agent 改、改完重开 Studio,因为 Studio 起来时就按这些文件夹定了自己是哪一个)。 - **agent**:新对话默认用哪一种(只列装好的、只认装好的;对话列里每点一次"新对话"、空间里每开一支新片,都从它开始;一个地方上次用的是哪种,只决定打开时显示哪段已有的对话);每种装好的 agent 的模型和思考深度:开过一次对话、agent 给过选项以后才能选(记进 `picks.json`,和对话列里选的是同一份),之前只写现在从什么开始。模式和"不带个人设置"按对话,留在对话里。 +- **服务**:要 API Key 的在线服务(`tools/modules.json` 里带 `needs.keys` 的服务:Gemini、MiniMax、ElevenLabs、阿里云百炼),一家一块:用来做什么、一个词说花不花钱(`cost`)、每个 key 是"没设""在 Studio 里设了"还是"在环境变量里设了(优先用它)",按钮"填上""换一个""拿掉"(再点一次才拿掉)、"测一下"(`bin/vh doctor --probe --only <服务>`,不花钱),"去哪拿 API Key"(`key_url`)。填进框里的 key 发一次就清空,存进系统的密码库(`tools/keys.py`:macOS 的钥匙串,Linux 上有 Secret Service 时用 `secret-tool`,都没有就说只能用环境变量),页面以后只知道设没设,拿不回它。有一个存在 Studio 里时,这一节说一句它存在哪。末尾说清:终端里设的环境变量这一页不一定看得到;有 API Key 不等于能花钱,收费的调用还要预算。命令都经 `tools/keys.py` 取 key:环境变量优先,没有再用存在 Studio 里的;右边对话里的 agent 跑的命令也取得到(agent 自己的环境里照旧没有 key)。 - **片子的默认**:下载镜像(自动、国内镜像、官方源,同 `bin/vh settings mirror`)可以改,页面写明 Studio 这一次运行里自己发起的下载要重开 Studio 才跟着变;LOCAL.md 里人和 agent 都读的几行(只认模板那样的列表项,值后面括号里的说明不算)(默认努力程度、在哪看每一站、素材许可、声音库、谁拍板哪些事、帮手 agent 用的模型、默认预算)只显示,没写的写出没写时按什么,末尾一句"让 agent 帮你改"。这一页从不写 LOCAL.md。 - **这台电脑**:同空间页的"这台电脑上还缺"(`/api/machine`),什么都不缺时一句"做片子要的都有了";空间页那一块多一个"去设置里看"。 - **关于**:版本(这份克隆所在的那一版,之后还有提交就加上提交号)、工作台在哪、这一版在 GitHub 上的发布说明。 diff --git a/tools/desk/settings_api.py b/tools/desk/settings_api.py index 4257ce05..a61750bf 100644 --- a/tools/desk/settings_api.py +++ b/tools/desk/settings_api.py @@ -10,6 +10,12 @@ {name, value} (studio_lang, studio_theme, agent_default, mirror, model:, effort:) and answers the same as GET, or {name: "reveal", value: }: that folder opens in the system's file browser ($OVH_REVEAL, a command, stands in for it; twenty a minute). + +The services (tools/modules.json's services with needs.keys): GET's services lists each with its keys, where a command +finds each (env, studio or none) and whether one is saved in Studio, never a key itself; store says what keeps them +(keychain, secret-service or none: tools/keys.py). POST {name: "key:", value: or null} saves or takes out +the key saved in Studio; {name: "test:"} asks the service once at its free address (bin/vh doctor --probe --only +; $OVH_PROBE_OFFLINE: answered from that folder's recordings), ten a minute, → {ok, probe: {state, note}}. """ import os, re, secrets, subprocess, sys, threading, time from pathlib import Path @@ -20,6 +26,8 @@ import settings as S # noqa: E402 (tools/settings.py: this machine's settings file, its one reader and writer) import agents as A # noqa: E402 import projects as PJ # noqa: E402 (where this console looks for films) +import keys as K # noqa: E402 (tools/keys.py: the services' keys, the environment's or saved in this computer's store) +import json # noqa: E402 # LOCAL.md's lines shown on the page: id → the labels a line may start with (as the tools that read them accept) LOCAL_LINES = ( @@ -91,6 +99,25 @@ def roots(given): return out +def services(): + """[{module, keys: [{name, source, saved}], cost, key_url, probe}]: the services a key opens, as tools/modules.json has them.""" + try: + t = json.loads((WORKSPACE / "tools" / "modules.json").read_text(encoding="utf-8")) + except (OSError, ValueError): + return [] + out = [] + for m in t.get("modules") or []: + names = (m.get("needs") or {}).get("keys") or [] + if m.get("kind") != "service" or not names: + continue + ks = [] + for n in names: + saved = bool(K.stored(n)) + ks.append({"name": n, "source": "env" if os.environ.get(n) else "studio" if saved else None, "saved": saved}) + out.append({"module": m["name"], "keys": ks, "cost": m.get("cost"), "key_url": m.get("key_url"), "probe": bool(m.get("probe"))}) + return out + + def state(mgr, given=()): d = S.load() st = S.studio(d) @@ -100,7 +127,7 @@ def state(mgr, given=()): "agents": {"default": st["agent_default"], "kinds": [{"kind": a["kind"], "label": a["label"], "installed": a["installed"], "size": a["size"], "choices": mgr.choices(a["kind"]) if mgr else None} for a in kinds]}, - "roots": roots(given), "local": local_lines(), + "roots": roots(given), "local": local_lines(), "services": services(), "store": K.store_kind(), "about": dict(version(), workspace=shown(os.path.realpath(WORKSPACE)))} @@ -115,7 +142,28 @@ def get(handler): return handler._json(state(handler.server.agents, handler.server.roots)) -REVEALED, REVEAL_LOCK = [], threading.Lock() +REVEALED, REVEAL_LOCK, TESTED = [], threading.Lock(), [] + + +def test(module): + """Ask one service once at its free address (bin/vh doctor's probe) → {state, note}: never a key in what comes back.""" + if module not in {s["module"] for s in services()}: + raise ValueError(f"test: {module!r} is not a service with a key") + with REVEAL_LOCK: + now = time.time() + TESTED[:] = [x for x in TESTED if now - x < 60] + if len(TESTED) >= 10: + raise PermissionError("asked too often: try again in a minute") + TESTED.append(now) + argv = [os.environ.get("OVH_BASH") or "bash", str(WORKSPACE / "bin" / "vh"), "doctor", "--json", "--probe", "--only", module] + if os.environ.get("OVH_PROBE_OFFLINE"): + argv += ["--offline", os.environ["OVH_PROBE_OFFLINE"]] + try: + r = subprocess.run(argv, capture_output=True, text=True, timeout=60, stdin=subprocess.DEVNULL) + m = next(x for x in json.loads(r.stdout)["modules"] if x["name"] == module) + return m.get("probe") or {"state": "skipped", "note": "not asked"} + except (OSError, ValueError, StopIteration, KeyError, subprocess.SubprocessError) as e: + return {"state": "failed", "note": f"could not ask ({type(e).__name__})"} def reveal(path): @@ -143,6 +191,17 @@ def post(handler): raise ValueError("reveal: not one of the folders Studio finds films in") reveal(value) return handler._json({"ok": True}) + if name.startswith("key:"): # a key: saved in (or taken out of) this computer's store; never said back + n = name[4:] + if n not in K.KEY_NAMES: + raise ValueError(f"{n}: not the name of a key a service needs") + if value is None: + K.clear(n) + else: + K.save(n, value) + return handler._json(state(handler.server.agents, handler.server.roots)) + if name.startswith("test:"): + return handler._json({"ok": True, "probe": test(name[5:])}) if name == "agent_default" and value is not None and not (value in A.ADAPTERS and A.installed(value)): raise ValueError(f"agent_default: {value!r} is not set up in Studio") if name in S.STUDIO: @@ -166,5 +225,5 @@ def post(handler): except ValueError as e: return handler._error(400, str(e)) except OSError as e: - return handler._error(500, f"could not keep it ({type(e).__name__})") + return handler._error(500, f"could not keep it: {e}") # (tools/keys.py's messages name the key's variable, never the key) return handler._json(state(handler.server.agents, handler.server.roots)) diff --git a/tools/desk/static/settings.css b/tools/desk/static/settings.css index 7a600ef2..29928f2d 100644 --- a/tools/desk/static/settings.css +++ b/tools/desk/static/settings.css @@ -48,3 +48,23 @@ .st-nav a[aria-current=page]{border-bottom-color:var(--you)} .st-row{grid-template-columns:1fr;gap:4px} } +/* the services: one card a service, a line a key */ +.sv{padding:14px 0 12px;border-top:1px solid var(--rule)} +.sv-h{display:flex;flex-wrap:wrap;align-items:center;gap:6px 10px;margin-bottom:6px} +.sv-h b{color:var(--ink-hi);font-weight:500;font-size:var(--fs-small)} +.sv-h .btn{margin-left:auto} +.sv-d{color:var(--ink-3);font-size:var(--fs-label)} +.sv-key{display:grid;grid-template-columns:170px minmax(0,1fr) auto;align-items:center;gap:6px 14px;padding:4px 0;font-size:var(--fs-small)} +.sv-key .st-note,.sv-key .sv-form{grid-column:1/-1} +.sv-st{color:var(--ink-3)} +.sv-st.on{color:var(--ink)} +.sv-acts{display:flex;gap:6px} +.sv-acts .warn{color:var(--wait);border-color:var(--wait-line)} +.sv-form{display:flex;gap:8px;grid-column:2/-1} +.sv-form input{flex:1;min-width:0;background:var(--panel-2);border:1px solid var(--rule-2);border-radius:var(--r-ctl);padding:6px 10px;color:var(--ink);font:var(--fs-small)/1.4 var(--mono)} +.sv-form input:focus{outline:none;border-color:var(--you)} +.sv-test.ok{color:var(--ok,var(--ink))} +.sv-get{display:inline-block;margin-top:6px;color:var(--you);font-size:var(--fs-label);text-decoration:none} +.sv-get:hover{text-decoration:underline} +.sv-kept{margin:0 0 6px} +@media (max-width:900px){.sv-key{grid-template-columns:1fr auto}.sv-key>.st-dim{grid-column:1/-1}.sv-form{grid-column:1/-1}} diff --git a/tools/desk/static/settings.js b/tools/desk/static/settings.js index 463010b4..356e26b4 100644 --- a/tools/desk/static/settings.js +++ b/tools/desk/static/settings.js @@ -8,7 +8,7 @@ const SETTINGS = (() => { const W = { zh: { title: "设置", back: "返回", rail: "设置", rail_tip: "设置(⌘,)", - s_general: "通用", s_agent: "agent", s_films: "片子的默认", s_machine: "这台电脑", s_about: "关于", s_account: "账号", + s_general: "通用", s_agent: "agent", s_services: "服务", s_films: "片子的默认", s_machine: "这台电脑", s_about: "关于", s_account: "账号", lang: "语言", look: "外观", th_darkfield: "暗场", th_prism: "棱镜", th_bridge: "舰桥", where: "片子放在哪", where_how: "想换个地方,让 agent 帮你改,改完重新打开 Studio。", where_none: "还没有这样的文件夹。", reveal: "在访达里打开", reveal_other: "打开文件夹", ag_default: "新对话默认用", ag_not: "还没装", ag_not_how: "在右边的对话里点「装上」。", ag_model: "模型", ag_effort: "思考深度", @@ -18,7 +18,7 @@ const SETTINGS = (() => { f_lead: "这些是这台电脑给每支片子的默认。片子自己写了的,以片子的为准。", f_effort: "默认努力程度", f_review: "在哪看每一站", f_assets: "素材许可", f_sound: "声音库", f_director: "谁拍板哪些事", f_subagent: "帮手 agent 用的模型", f_budget: "默认预算", f_unset: "没写", f_unset_effort: "没写:按标准", f_unset_review: "没写:按努力程度", - f_unset_assets: "没写:严格", f_unset_sound: "没写:用 ~/.ovh/sound", f_unset_budget: "没写:不调收费的接口", + f_unset_assets: "没写:严格", f_unset_sound: "没写:用 ~/.ovh/sound", f_unset_budget: "没写:不调收费的服务", f_unset_director: "没写:按努力程度的默认", f_unset_subagent: "没写:比 agent 自己便宜一档", f_how: "让 agent 帮你改。", mirror: "下载镜像", m_auto: "自动", m_cn: "国内镜像", m_off: "官方源", @@ -29,11 +29,24 @@ const SETTINGS = (() => { v_quick: "快速", v_standard: "标准", v_studio: "精品", v_chat: "对话里", v_page: "网页", v_desk: "Studio", v_strict: "严格", v_record: "记下就能用", ab_version: "版本", ab_where: "工作台在哪", ab_news: "更新了什么", ab_news_link: "这一版的说明", saved: "记下了", see: "去设置里看", failed: "没记下:{x}", + sv_lead: "配音默认用这台电脑上的声音,不用 API Key。下面的在线服务,用到哪家再设哪家。", + sv_gemini: "Gemini(Google)", sv_gemini_d: "在线配音、给字幕对时间、出图、作曲", sv_minimax: "MiniMax", sv_minimax_d: "在线配音", + sv_elevenlabs: "ElevenLabs", sv_elevenlabs_d: "在线配音", sv_dashscope: "阿里云百炼", sv_dashscope_d: "在线配音", + k_key: "API Key", k_MINIMAX_TOKEN_PLAN_KEY: "Token Plan 的 API Key", k_MINIMAX_API_KEY: "按量计费的 API Key", + c_free: "免费", c_free_tier: "有免费额度", c_paid: "收费", + st_none: "没设", st_studio: "在 Studio 里设了", st_env: "在环境变量里设了(优先用它)", + b_set: "填上", b_replace: "换一个", b_clear: "拿掉", b_clear_sure: "确定拿掉", b_test: "测一下", b_save: "保存", b_cancel: "取消", + ph: "粘贴 {s} 的 API Key", get_key: "去哪拿 API Key", clear_note: "拿掉以后,用到它的命令会停下来告诉你。", + t_wait: "正在问…", t_ok: "能用了", t_fail: "没通过,服务的回答:{x}", t_skip: "还没有 API Key 可以测", t_free: "测一下不花钱。", + sv_kept_keychain: "存在这台电脑的钥匙串里,不写进任何文件。", sv_kept_secret: "存在这台电脑的密码库里,不写进任何文件。", + sv_none: "这台电脑上没有密码库,API Key 只能写在环境变量里:{v}。", + sv_env_note: "在终端里设的环境变量,这一页不一定看得到;在这里填上的,终端里和右边的对话里都用得上。", + sv_budget: "有 API Key 不等于能花钱:收费的调用还要片子或这台电脑写了预算。这台电脑的默认预算:{x}", nokey: "这一页要在 Studio 的窗口里打开才看得到。", reopen: "在 Studio 窗口里打开", }, en: { title: "Settings", back: "Back", rail: "Settings", rail_tip: "Settings (⌘,)", - s_general: "General", s_agent: "Agent", s_films: "Film defaults", s_machine: "This computer", s_about: "About", s_account: "Account", + s_general: "General", s_agent: "Agent", s_services: "Services", s_films: "Film defaults", s_machine: "This computer", s_about: "About", s_account: "Account", lang: "Language", look: "Look", th_darkfield: "Darkfield", th_prism: "Prism", th_bridge: "Bridge", where: "Where films are kept", where_how: "To keep them somewhere else, ask your agent to change it, then reopen Studio.", where_none: "No such folder yet.", reveal: "Show in Finder", reveal_other: "Open folder", ag_default: "New chats start with", ag_not: "Not set up", ag_not_how: "Press “Set it up” in the chat on the right.", ag_model: "Model", ag_effort: "Effort", @@ -54,14 +67,28 @@ const SETTINGS = (() => { v_quick: "Quick", v_standard: "Standard", v_studio: "Studio", v_chat: "In the chat", v_page: "A web page", v_desk: "Studio", v_strict: "Strict", v_record: "Allowed if recorded", ab_version: "Version", ab_where: "Where the workbench is", ab_news: "What's new", ab_news_link: "This version's notes", saved: "Saved", see: "See it in Settings", failed: "Not saved: {x}", + sv_lead: "Voices are made on this computer by default, no API Key needed. Set up an online service below only when you want it.", + sv_gemini: "Gemini (Google)", sv_gemini_d: "online voices, timing the captions, pictures, music", sv_minimax: "MiniMax", sv_minimax_d: "online voices", + sv_elevenlabs: "ElevenLabs", sv_elevenlabs_d: "online voices", sv_dashscope: "Alibaba Cloud Model Studio", sv_dashscope_d: "online voices", + k_key: "API Key", k_MINIMAX_TOKEN_PLAN_KEY: "Token Plan API Key", k_MINIMAX_API_KEY: "Pay-as-you-go API Key", + c_free: "Free", c_free_tier: "Free tier", c_paid: "Paid", + st_none: "Not set", st_studio: "Set in Studio", st_env: "Set in the environment (used first)", + b_set: "Set up", b_replace: "Replace", b_clear: "Remove", b_clear_sure: "Yes, remove", b_test: "Test", b_save: "Save", b_cancel: "Cancel", + ph: "Paste your {s} API Key", get_key: "Get an API Key", clear_note: "Once removed, commands that need it stop and tell you.", + t_wait: "Asking…", t_ok: "Works", t_fail: "Didn't work; the service said: {x}", t_skip: "No API Key to test yet", t_free: "Testing costs nothing.", + sv_kept_keychain: "Kept in this computer's Keychain, never written into any file.", sv_kept_secret: "Kept in this computer's password store, never written into any file.", + sv_none: "This computer has no password store; an API Key can only come from the environment: {v}.", + sv_env_note: "Environment variables set in your terminal may not show on this page; a key set here works in the terminal and in the chat on the right.", + sv_budget: "An API Key isn't a budget: a paid call also needs a budget on the film or this computer. This computer's default budget: {x}", nokey: "This page shows only in Studio's own window.", reopen: "Open in Studio's window", }, }; const w = (k, v) => String((W[LANG] || W.zh)[k] != null ? (W[LANG] || W.zh)[k] : W.en[k] != null ? W.en[k] : k).replace(/\{(\w+)\}/g, (_, x) => (v && v[x] != null ? v[x] : "")); // the sections, in order; account waits for accounts (not shown) - const SECTIONS = [{ id: "general" }, { id: "agent" }, { id: "films" }, { id: "machine" }, { id: "about" }, { id: "account", hidden: true }]; + const SECTIONS = [{ id: "general" }, { id: "agent" }, { id: "services" }, { id: "films" }, { id: "machine" }, { id: "about" }, { id: "account", hidden: true }]; const THEMES = ["darkfield", "prism", "bridge"]; let ST = null, BACK = "#/", SEC = "general"; + let EDIT = "", ARM = "", TESTS = {}; // the services: the key being typed, the key whose 拿掉 asks once more, each service's last test async function call(method, body) { try { @@ -109,7 +136,7 @@ const SETTINGS = (() => { const area = $("#stage"), y = area.scrollTop, f = $("#stage :focus"), refocus = f && (f.dataset.val || f.dataset.themeSet || f.dataset.set); const nav = SECTIONS.filter((s) => !s.hidden).map((s) => `${esc(w("s_" + s.id))}`).join(""); area.innerHTML = `

    ${esc(w("title"))}

    ${esc(w("back"))}
    -
    ${({ general, agent, films, machine: machineSec, about })[SEC]()}
    `; +
    ${({ general, agent, services, films, machine: machineSec, about })[SEC]()}
    `; area.scrollTop = y; if (refocus) { const b = [...area.querySelectorAll("[role=radio], select")].find((x) => (x.dataset.val || x.dataset.themeSet || x.dataset.set) === refocus); if (b) b.focus(); } } @@ -150,6 +177,30 @@ const SETTINGS = (() => { } return out; } + function services() { + const store = ST.store || "none", list = ST.services || [], L = (ST.local && ST.local.lines) || {}; + const anySaved = list.some((s) => s.keys.some((k) => k.saved)); + const keyRow = (s, k) => { + const label = (W.zh["k_" + k.name] ? w("k_" + k.name) : w("k_key")), status = w(k.source === "env" ? "st_env" : k.source === "studio" ? "st_studio" : "st_none"); + if (EDIT === k.name) return `
    ${esc(label)}
    `; + const acts = store === "none" ? "" : k.saved ? `` + : k.source === "env" ? "" : ``; + return `
    ${esc(label)}${esc(status)}${acts}${ARM === k.name ? `

    ${esc(w("clear_note"))}

    ` : ""}
    `; + }; + const card = (s) => { + const t = TESTS[s.module], has = s.keys.some((k) => k.source); + const test = s.probe && has ? `` : ""; + const said = !t ? "" : t === "wait" ? w("t_wait") : t.state === "ok" ? w("t_ok") : t.state === "skipped" ? w("t_skip") : w("t_fail", { x: t.note || "" }); + return `
    ${esc(w("sv_" + s.module))}${esc(w("c_" + (s.cost || "paid")))}${esc(w("sv_" + s.module + "_d"))}${test}
    ` + + s.keys.map((k) => keyRow(s, k)).join("") + + `${said ? `

    ${esc(said)}

    ` : ""}${s.key_url ? `${esc(w("get_key"))} ↗` : ""}
    `; + }; + const names = list.flatMap((s) => s.keys.map((k) => k.name)).join(", "); + return `

    ${esc(w("sv_lead"))}

    ` + + (store === "none" ? `

    ${esc(w("sv_none", { v: names }))}

    ` : anySaved ? `

    ${esc(w(store === "keychain" ? "sv_kept_keychain" : "sv_kept_secret"))}

    ` : "") + + list.map(card).join("") + + `

    ${esc(w("sv_env_note"))}
    ${esc(w("sv_budget", { x: L.budget || w("f_unset") }))}

    `; + } function films() { const L = (ST.local && ST.local.lines) || {}, M = ST.mirror || {}; const said = (k) => { // a known value in the page's words (LOCAL.md's own words for the way a stop is looked at, too) @@ -195,6 +246,29 @@ const SETTINGS = (() => { const b = e.target.closest('.settings [role="radio"]'); if (b) choose(b); }); + document.addEventListener("click", async (e) => { // the services' buttons (the page's own clicks only) + const b = e.target.closest(".settings [data-sv-edit], .settings [data-sv-cancel], .settings [data-sv-clear], .settings [data-sv-test]"); + if (!b || !e.isTrusted) return; + if (b.dataset.svEdit) { EDIT = b.dataset.svEdit; ARM = ""; draw(); const i = $("#svIn"); if (i) i.focus(); return; } + if (b.hasAttribute("data-sv-cancel")) { EDIT = ""; draw(); return; } + if (b.dataset.svClear) { + if (ARM !== b.dataset.svClear) { ARM = b.dataset.svClear; EDIT = ""; draw(); return; } + ARM = ""; await save("key:" + b.dataset.svClear, null); draw(); return; + } + const m = b.dataset.svTest; TESTS[m] = "wait"; draw(); + const r = await call("POST", { name: "test:" + m }); + TESTS[m] = r.ok && r.data && r.data.probe ? r.data.probe : { state: "failed", note: r.status === 403 ? w("nokey") : String((r.data && r.data.error) || r.status) }; + if (parse().view === "settings") draw(); + }); + document.addEventListener("submit", async (e) => { // a key typed into the box: sent once, the box emptied at once, never kept in the page + const f = e.target.closest(".settings [data-sv-form]"); + if (!f) return; + e.preventDefault(); + const i = f.querySelector("input"), v = i.value.trim(); i.value = ""; + if (!v || !e.isTrusted) return; + const name = f.dataset.svForm; EDIT = ""; + await save("key:" + name, v); draw(); + }); document.addEventListener("change", async (e) => { const s = e.target.closest(".settings select[data-set]"); if (s && await save(s.dataset.set, s.value) && parse().view === "settings") draw(); diff --git a/tools/desk/test_settings.py b/tools/desk/test_settings.py index cbf878ae..bec59d6b 100644 --- a/tools/desk/test_settings.py +++ b/tools/desk/test_settings.py @@ -27,6 +27,46 @@ XDG_DATA_HOME=str(T / "data"), OVH_LOCAL_MD=str(LOCAL), OVH_AGENTS_DIR=str(T / "agents"), OVH_STUDIO_PROFILES=str(T / "profiles"), OVH_STUDIO_SHELL="none", OVH_STUDIO_BROWSER="none", OVH_GATE_STUDIO="0", BROWSER="/usr/bin/false", OVH_PROJECTS=str(T / "no-such-folder"), OVH_REVEAL=str(T / "reveal.sh")) +for k in ("OVH_KEYSTORE", "OVH_KEYCHAIN", "OVH_KEYSTORE_SERVICE", "OVH_SECRET_TOOL"): # (tools/ci.sh turns the store off: these checks have one of their own) + ENV.pop(k, None) +for k in [k for k in ENV if "API_KEY" in k.upper() or k.upper().endswith(("_TOKEN", "_SECRET", "_PLAN_KEY"))]: # no real key of the person's reaches anything here + del ENV[k] +FAKE = "ovhTestKey" + os.urandom(6).hex() # a made-up key: never a real one, and never seen in anything the checks read back +MAC = sys.platform == "darwin" and shutil.which("security") is not None + + +def stage_store(): + """A password store of these checks' own. macOS: a keychain file in the scratch folder, made with HOME there too (so + the person's keychain search list is not touched), named on every call, under a service name of its own; deleted at + the end. Elsewhere: a stand-in secret-tool that keeps its secrets in a file and notes every argument it gets.""" + ENV["OVH_KEYSTORE_SERVICE"] = "ovh-test-" + os.urandom(4).hex() + if MAC: + kc = T / "keys" / "test.keychain-db" + kc.parent.mkdir(parents=True, exist_ok=True) + subprocess.run(["security", "create-keychain", "-p", "made-up", str(kc)], env=ENV, check=True, capture_output=True, timeout=20) + ENV["OVH_KEYCHAIN"] = str(kc) + return + tool = T / "secret-tool" + tool.write_text(f"""#!{sys.executable} +import json, os, sys +store, log = {str(T / "secrets.json")!r}, {str(T / "secret-argv.log")!r} +open(log, "a").write(json.dumps(sys.argv[1:]) + "\\n") +d = json.load(open(store)) if os.path.exists(store) else {{}} +a = sys.argv[1:]; at = dict(zip(a[-4::2], a[-3::2])); k = at.get("service", "") + "|" + at.get("key", "") +if a[0] == "lookup": + if k in d: print(d[k]); sys.exit(0) + sys.exit(1) +if a[0] == "store": d[k] = sys.stdin.read() +if a[0] == "clear": d.pop(k, None) +json.dump(d, open(store, "w")) +""") + tool.chmod(0o755) + ENV["OVH_SECRET_TOOL"] = str(tool) + + +def unstage_store(): + if ENV.get("OVH_KEYCHAIN"): + subprocess.run(["security", "delete-keychain", ENV["OVH_KEYCHAIN"]], env=ENV, capture_output=True, timeout=20) def say(ok, what, why=""): @@ -132,6 +172,7 @@ def run(): pkg.parent.mkdir(parents=True, exist_ok=True); pkg.write_text(json.dumps({"version": codex["version"]})) CONF.parent.mkdir(parents=True, exist_ok=True) CONF.write_text(json.dumps({"version": 1, "mirror": "cn", "mirror_at": "2026-11-01", "kept_for_later": {"a": 1}}), encoding="utf-8") + ENV["OVH_PROBE_OFFLINE"] = str(T / "rec") # the page's 测一下: answered from the recording doctor_keys_check made d = Desk() try: def page(): @@ -224,6 +265,32 @@ def reveal(): return None if st == 200 and got == [os.path.realpath(FILMS)] else f"{st}, opened {got}" check("a films folder opens in the file browser (a stand-in here), that folder and nothing else", reveal) + def services(): + bad = [] + st, s = d.req("POST", "/api/settings", {"name": "key:GEMINI_API_KEY", "value": None}) # (the checks before saved one) + sv = {x["module"]: x for x in s.get("services", [])} + if list(sv) != ["gemini", "minimax", "elevenlabs", "dashscope"] or s.get("store") not in ("keychain", "secret-service"): + return f"services {list(sv)}, store {s.get('store')}" + if sv["gemini"]["keys"] != [{"name": "GEMINI_API_KEY", "source": None, "saved": False}] or sv["gemini"]["cost"] != "free_tier" \ + or not sv["gemini"]["key_url"].startswith("https://") or sv["minimax"]["cost"] != "paid": + bad.append(f"gemini before: {sv['gemini']}") + st, s = d.req("POST", "/api/settings", {"name": "key:GEMINI_API_KEY", "value": FAKE}) + g = {x["module"]: x for x in s.get("services", [])}.get("gemini", {}) + if st != 200 or FAKE in json.dumps(s) or g.get("keys") != [{"name": "GEMINI_API_KEY", "source": "studio", "saved": True}]: + bad.append(f"saving: {st} {g}") + st, t = d.req("POST", "/api/settings", {"name": "test:gemini"}) + if st != 200 or (t.get("probe") or {}).get("state") != "ok": bad.append(f"测一下: {st} {t}") + for body in ({"name": "key:GEMINI_API_KEY", "value": "not a key"}, {"name": "key:PATH", "value": FAKE}, {"name": "test:openverse"}): + st, e = d.req("POST", "/api/settings", body) + if st != 400 or FAKE in json.dumps(e) or "not a key" in json.dumps(e): bad.append(f"{body['name']}: {st} {e}") + if d.req("POST", "/api/settings", {"name": "key:GEMINI_API_KEY", "value": FAKE}, token=False)[0] != 403: bad.append("saved without the token") + st, s = d.req("POST", "/api/settings", {"name": "key:GEMINI_API_KEY", "value": None}) + if st != 200 or {x["module"]: x for x in s["services"]}["gemini"]["keys"][0]["saved"]: bad.append(f"taking it out: {st}") + d.req("POST", "/api/settings", {"name": "key:GEMINI_API_KEY", "value": FAKE}) # saved again, for what follows + if FAKE in d.log.read_text(): bad.append("the key is in the console's log") + return "; ".join(bad) or None + check("the services: each key's state and never the key; saved, tested at no cost (a recording here), refused when it is not a key, a key's name or a service with a key, taken out; nothing in the console's log", services) + def local_untouched(): return None if "默认努力程度:quick" in LOCAL.read_text(encoding="utf-8") and not list(T.glob("LOCAL.md.*")) else "LOCAL.md was written" check("nothing on the page writes LOCAL.md", local_untouched) @@ -274,6 +341,91 @@ def page_check(): return f"a new conversation's agent: {r['kinds']}" +def py(code, env=None): + """A few lines of Python in the checks' environment (the store staged), in tools/ → (exit, stdout + stderr).""" + r = subprocess.run([sys.executable, "-c", code], cwd=str(ROOT / "tools"), env=env or ENV, capture_output=True, text=True, timeout=60) + return r.returncode, r.stdout + r.stderr + + +def keys_module_check(): + code = f""" +import os, keys as K +v = {FAKE!r} +assert K.store_kind() in ("keychain", "secret-service"), K.store_kind() +assert K.get("GEMINI_API_KEY") is None and K.source("GEMINI_API_KEY") is None +K.save("GEMINI_API_KEY", v) +assert K.stored("GEMINI_API_KEY") == v and K.get("GEMINI_API_KEY") == v and K.source("GEMINI_API_KEY") == "studio" +os.environ["GEMINI_API_KEY"] = "fromTheEnvironment1" +assert K.get("GEMINI_API_KEY") == "fromTheEnvironment1" and K.source("GEMINI_API_KEY") == "env" +del os.environ["GEMINI_API_KEY"] +for name, val in (("GEMINI_API_KEY", "has a space"), ("GEMINI_API_KEY", "-looksLikeAnOption"), ("GEMINI_API_KEY", "short"), ("HOME", v), ("SOME_API_KEY", v)): + try: + K.save(name, val); raise SystemExit(f"took {{name}}={{val!r}}") + except ValueError: + pass +K.clear("ELEVENLABS_API_KEY") # nothing saved: nothing to do +print("ok") +""" + rc, out = py(code) + if rc or out.strip() != "ok": + return out[-300:] + if not MAC and FAKE in (T / "secret-argv.log").read_text(): + return "the key was an argument of secret-tool" + if subprocess.run([sys.executable, str(ROOT / "tools" / "keys.py"), "has", "GEMINI_API_KEY"], env=ENV, timeout=30).returncode != 0: + return "keys.py has: a saved key not found" + + +def readers_check(): + """Every place that reads one of the services' keys goes through tools/keys.py (nothing reads the environment for one).""" + sys.path.insert(0, str(ROOT / "tools")) + import keys as K + pat = re.compile(r"environ(?:\.get)?\(\s*[\"'](" + "|".join(K.KEY_NAMES) + r")[\"']|environ\[[\"'](" + "|".join(K.KEY_NAMES) + r")[\"']|\$\{?(" + "|".join(K.KEY_NAMES) + r")\b") + bad = [] + for f in [ROOT / "bin" / "vh", *(ROOT / "tools").rglob("*.py")]: + if f.name in ("keys.py",) or f.name.startswith("test_") or "fixtures" in f.parts: + continue + for i, line in enumerate(f.read_text(encoding="utf-8", errors="replace").splitlines(), 1): + if pat.search(line): + bad.append(f"{f.relative_to(ROOT)}:{i}") + return f"reads a key without tools/keys.py: {bad}" if bad else None + + +def doctor_keys_check(): + rec = T / "rec"; rec.mkdir(exist_ok=True) + (rec / "gemini.json").write_text(json.dumps({"models": [{"name": "models/" + n} for n in ("gemini-3.8-flash-tts", "gemini-3.8-flash-lite-tts", + "gemini-3.5-transcribe", "gemini-nano-banana-2.1", "gemini-3-pro-image", "lyria-3.5")]})) + (rec / "responses.json").write_text(json.dumps({"v": 1, "responses": [{"url": "https://generativelanguage.googleapis.com/v1beta/models?pageSize=1000", + "status": 200, "headers": {}, "body": "gemini.json"}]})) + doc = lambda *a: subprocess.run([sys.executable, str(ROOT / "tools" / "doctor.py"), *a], env=ENV, capture_output=True, text=True, timeout=120) # noqa: E731 + j, t, p = doc("--json"), doc(), doc("--json", "--probe", "--only", "gemini", "--offline", str(rec)) + if FAKE in j.stdout + j.stderr + t.stdout + t.stderr + p.stdout + p.stderr: + return "doctor printed the key" + g = next(m for m in json.loads(j.stdout)["modules"] if m["name"] == "gemini") + if g["keys"] != {"GEMINI_API_KEY": True} or g["key_source"] != {"GEMINI_API_KEY": "studio"} or g["state"] != "ok": + return f"doctor --json: {g['keys']} {g.get('key_source')} {g['state']}" + if "GEMINI_API_KEY set in Studio" not in t.stdout: + return "doctor's line does not say the key is set in Studio" + pr = next(m for m in json.loads(p.stdout)["modules"] if m["name"] == "gemini")["probe"] + if not pr or pr["state"] != "ok": + return f"doctor --probe with the key saved in Studio: {pr}" + + +def column_check(): + """A command the agent column's agent runs (its environment has no key: acp.clean_env) finds a key saved in Studio.""" + sys.path.insert(0, str(HERE)) + import acp + keep = dict(os.environ) + try: + os.environ.clear(); os.environ.update(ENV) + env = acp.clean_env({k: ENV[k] for k in ("OVH_KEYCHAIN", "OVH_KEYSTORE_SERVICE", "OVH_SECRET_TOOL") if ENV.get(k)}) + finally: + os.environ.clear(); os.environ.update(keep) + if any("API_KEY" in k for k in env): + return f"the column's environment carries a key: {[k for k in env if 'API_KEY' in k]}" + r = subprocess.run([sys.executable, str(ROOT / "tools" / "keys.py"), "has", "GEMINI_API_KEY"], env=env, timeout=30) + return None if r.returncode == 0 else "not found in the column's environment" + + def words_check(): src = (HERE / "static" / "settings.js").read_text(encoding="utf-8") zh = src[src.index(" zh: {"):src.index(" en: {")] @@ -285,9 +437,19 @@ def words_check(): check("tools/settings.py: Studio's three settings, a value it does not know read as not set, any other name or value refused, other keys kept", module_check) check("the settings page's words: every one in both languages", words_check) +check("every command that reads a service's key does it through tools/keys.py", readers_check) check("the page in node: this machine's look and language win over the browser's copy (which is kept when the file has none); the top bar's two buttons save; a new conversation starts with the default agent when it is set up", page_check) +real_list = subprocess.run(["security", "list-keychains", "-d", "user"], capture_output=True, text=True).stdout if MAC else "" try: + stage_store() + check("tools/keys.py on a store of these checks' own: saved, found, the environment first, taken out; what is not a key or a key's name refused" + ("" if MAC else "; the key never an argument"), keys_module_check) + check("bin/vh doctor finds a key saved in Studio, says so, and probes with it (a recording), never printing it", doctor_keys_check) + check("a command run in the agent column's environment (no key in it) finds a key saved in Studio", column_check) run() except Exception as e: say(False, "the console for the settings page", f"{type(e).__name__}: {e}") +finally: + unstage_store() + if MAC and subprocess.run(["security", "list-keychains", "-d", "user"], capture_output=True, text=True).stdout != real_list: + say(False, "the person's keychain search list", "changed") print("end", flush=True) diff --git a/tools/doctor.py b/tools/doctor.py index 64711724..43c3da51 100644 --- a/tools/doctor.py +++ b/tools/doctor.py @@ -36,13 +36,16 @@ --json, "version": 1 (these fields stay; new ones may be added): {"version", "tool", "platform", "modules": [{"name", "kind", "status" ("planned" when nothing calls it yet, else "used"), "required", "state", "found", "version", "keys": -{VAR: true|false}, "note", "install", "probe": {"state", "note"} | null}], "checks": [{"name", "state", "note"}], +{VAR: true|false}, "key_source": {VAR: "env" | "studio" | null} (saved in Studio's settings: tools/keys.py), "note", +"install", "probe": {"state", "note"} | null}], "checks": [{"name", "state", "note"}], "first_run": [what the first runs still download], "counts": {state: n}}. state: ok · missing · outdated (under the minimum, not the pin, or older than max_age_days) · incomplete (found, a part it needs is not) · no_key · unsupported (not on this platform) · per_project · unchecked. A probe: ok · failed · skipped. """ import contextlib, datetime, glob, http.client, json, os, platform, re, shutil, subprocess, sys, tempfile, time import urllib.error, urllib.parse, urllib.request +sys.path.insert(0, os.path.dirname(os.path.abspath(__file__))) +import keys # noqa: E402 (tools/keys.py: a key from the environment, else saved in Studio's settings) from pathlib import Path ROOT = Path(__file__).resolve().parent.parent @@ -241,13 +244,14 @@ def hf_snapshot(model): def check_module(m, found_by, today): """One module on this machine: {state, found, version, keys, note}.""" ck, ver, needs = m.get("check") or {}, m.get("version") or {}, m.get("needs") or {} - r = {"state": "ok", "found": None, "version": None, "keys": {}, "note": ""} + r = {"state": "ok", "found": None, "version": None, "keys": {}, "key_source": {}, "note": ""} notes = [] if not platform_ok(needs.get("platform")): r.update(state="unsupported", note=f"for {needs['platform']} only; this is {this_platform()}" + (f": {m['elsewhere']}" if m.get("elsewhere") else "")) return r for k in needs.get("keys", []): - r["keys"][k] = bool(os.environ.get(k)) + r["keys"][k] = bool(keys.get(k)) + r["key_source"][k] = keys.source(k) # env or studio (saved in Studio's settings), or None if ck.get("per_project"): r.update(state="per_project", note=f"each project has its own: {ck['per_project']}") return r @@ -415,10 +419,10 @@ def probe(m, offline, recs): if not p: return None keyless = not (m.get("needs") or {}).get("keys") and not p.get("auth") - var = None if keyless else next((k for k in (m.get("needs") or {}).get("keys", []) if os.environ.get(k)), None) + var = None if keyless else next((k for k in (m.get("needs") or {}).get("keys", []) if keys.get(k)), None) if not var and not keyless: return {"state": "skipped", "note": "no key set"} - key, url = (os.environ[var] if var else ""), p["url"] + key, url = (keys.get(var) if var else ""), p["url"] if p.get("base_env") and os.environ.get(p["base_env"]): b = urllib.parse.urlsplit(os.environ[p["base_env"]]) if not b.hostname or not (b.scheme == "https" or (b.scheme == "http" and b.hostname in LOCAL)): @@ -826,7 +830,7 @@ def problems(t, commands=None): bad.append(f"{at}: the name is not lower-case letters, digits and -"); continue names.append(n) extra = set(m) - {"name", "kind", "status", "purpose", "version", "license", "needs", "adapter", "commands", "required", "check", - "probe", "first_run", "install", "elsewhere"} + "probe", "first_run", "install", "elsewhere", "cost", "key_url"} if extra: bad.append(f"{at}: fields doctor does not know: {sorted(extra)}") if m.get("kind") not in KINDS: @@ -841,6 +845,10 @@ def problems(t, commands=None): ver = m.get("version") if not isinstance(ver, dict) or set(ver) - {"pin", "min", "range", "tested", "models", "max_age_days"}: bad.append(f"{at}: version is not an object of pin, min, range, tested, models, max_age_days") + if "cost" in m and m["cost"] not in ("free", "free_tier", "paid"): + bad.append(f"{at}: cost is not free, free_tier or paid") + if "key_url" in m and not (isinstance(m["key_url"], str) and m["key_url"].startswith("https://") and (m.get("needs") or {}).get("keys")): + bad.append(f"{at}: key_url is not an https address, or the module needs no key") needs = m.get("needs") if not isinstance(needs, dict) or set(needs) - {"keys", "programs", "account", "platform"}: bad.append(f"{at}: needs is not an object of keys, programs, account, platform") @@ -897,8 +905,9 @@ def print_module(m, r): mark = OK if r["state"] == "ok" else NO if bad and m["required"] else WA if bad else "-" ck = m.get("check") or {} where = shown(r["found"]) if r["found"] and not r["version"] and (ck.get("program") or ck.get("finder") == "chrome") else "" - keys = [k for k, on in r["keys"].items() if on] - detail = " · ".join(x for x in (", ".join(keys) + " set" if keys else "", r["version"], where, r["note"]) if x) + src = r.get("key_source") or {} + have = [f"{k} set {'in Studio' if src.get(k) == 'studio' else 'in the environment'}" for k, on in r["keys"].items() if on] + detail = " · ".join(x for x in (", ".join(have), r["version"], where, r["note"]) if x) if r["state"] == "no_key" and m["commands"]: detail += f" (for bin/vh {', '.join(m['commands'])})" hint = f" → {r['install']}" if bad and r["install"] else "" diff --git a/tools/keys.py b/tools/keys.py new file mode 100644 index 00000000..fa66753e --- /dev/null +++ b/tools/keys.py @@ -0,0 +1,155 @@ +"""The API keys of the outside services (tools/modules.json's needs.keys), looked up one way by every command: the +environment first, as before, then the key the person saved in Studio's settings page, kept in this computer's own +password store (macOS: the Keychain; Linux: the Secret Service through secret-tool, when there is one). Stdlib only. + +A key never goes into a file, a log, a URL, an event or the page, and never onto a command line (where the process list +shows it): it is written to the store through standard input. Only names in KEY_NAMES are read or written here. + +usage: python3 tools/keys.py has exit 0 when a command would find that key (environment or store), else 1 + python3 tools/keys.py where each name: env, studio or -, and what kind of store this computer has + (there is no command that prints a key) + +Tests: OVH_KEYCHAIN= names a keychain of their own on every call (macOS), OVH_KEYSTORE_SERVICE a service name of +their own, OVH_SECRET_TOOL a stand-in for secret-tool (Linux); OVH_KEYSTORE=none turns the store off. +""" +import json, os, re, shutil, subprocess, sys +from pathlib import Path + +ROOT = Path(__file__).resolve().parent.parent +VALUE = re.compile(r"[A-Za-z0-9][A-Za-z0-9._:+/=-]{7,511}") # what a provider's API key looks like: no space, no quote, no newline +_CACHE = {} + + +def key_names(): + """Every key a service in tools/modules.json needs, in the table's order.""" + try: + t = json.loads((ROOT / "tools" / "modules.json").read_text(encoding="utf-8")) + except (OSError, ValueError): + return [] + out = [] + for m in t.get("modules") or []: + for k in ((m.get("needs") or {}).get("keys") or []): + if k not in out: + out.append(k) + return out + + +KEY_NAMES = key_names() + + +def service(): + return os.environ.get("OVH_KEYSTORE_SERVICE") or "OpenVideoHarness" + + +def _known(name): + if name not in KEY_NAMES: + raise ValueError(f"{name}: not the name of a key a service needs (tools/modules.json)") + + +def store_kind(): + """keychain, secret-service or none: where a key saved in Studio is kept on this computer.""" + if "kind" in _CACHE: + return _CACHE["kind"] + kind = "none" + if os.environ.get("OVH_KEYSTORE") != "none": + if sys.platform == "darwin" and shutil.which("security"): + kind = "keychain" + elif sys.platform.startswith("linux") and _secret_tool(): + try: # a lookup of nothing: exit 1 when the Secret Service answers, an error message when there is none to answer + r = subprocess.run([_secret_tool(), "lookup", "service", service(), "key", "-"], capture_output=True, text=True, + timeout=5, stdin=subprocess.DEVNULL) + kind = "secret-service" if r.returncode in (0, 1) and not r.stderr.strip() else "none" + except (OSError, subprocess.SubprocessError): + kind = "none" + _CACHE["kind"] = kind + return kind + + +def _secret_tool(): + return os.environ.get("OVH_SECRET_TOOL") or shutil.which("secret-tool") + + +def _keychain(): + k = os.environ.get("OVH_KEYCHAIN") + return [k] if k else [] + + +def _run(argv, stdin=None): + try: + return subprocess.run(argv, input=stdin, capture_output=True, text=True, timeout=10, + stdin=None if stdin is not None else subprocess.DEVNULL) + except (OSError, subprocess.SubprocessError): + return None + + +def stored(name): + """The key saved in Studio for this name, or None (no store, nothing saved, the store did not answer).""" + _known(name) + kind = store_kind() + if kind == "keychain": + r = _run(["security", "find-generic-password", "-s", service(), "-a", name, "-w", *_keychain()]) + elif kind == "secret-service": + r = _run([_secret_tool(), "lookup", "service", service(), "key", name]) + else: + return None + v = r.stdout.strip() if r is not None and r.returncode == 0 else "" + return v or None + + +def get(name): + """What a command uses for this key: the environment's when it is set (it wins), else the one saved in Studio, else None.""" + _known(name) + return os.environ.get(name) or stored(name) + + +def source(name): + """env, studio or None: where a command would find this key (the value is not handed back).""" + _known(name) + return "env" if os.environ.get(name) else "studio" if stored(name) else None + + +def save(name, value): + """Save (or replace) the key for this name in this computer's store. ValueError: an unknown name, a value that is not + a key; OSError: no store, or it did not take it.""" + _known(name) + if not isinstance(value, str) or not VALUE.fullmatch(value): + raise ValueError(f"{name}: that is not an API key (8 to 512 letters, digits and . _ : + / = -, starting with a letter or digit)") + kind = store_kind() + if kind == "keychain": # security's own prompt reads the line on stdin: the key never is an argument of a process + r = _run(["security", "-i"], stdin=f'add-generic-password -U -s "{service()}" -a {name} -l "{service()} {name}" -w {value} {" ".join(chr(34) + k + chr(34) for k in _keychain())}\n') + elif kind == "secret-service": + r = _run([_secret_tool(), "store", f"--label={service()} {name}", "service", service(), "key", name], stdin=value) + else: + raise OSError("this computer has no password store: the key can only come from the environment") + if r is None or r.returncode != 0 or stored(name) != value: + raise OSError(f"{name} was not saved ({kind} did not take it)") + + +def clear(name): + """Take the key saved for this name out of the store (nothing saved: nothing to do).""" + _known(name) + kind = store_kind() + if kind == "keychain": + _run(["security", "delete-generic-password", "-s", service(), "-a", name, *_keychain()]) + elif kind == "secret-service": + _run([_secret_tool(), "clear", "service", service(), "key", name]) + if stored(name): + raise OSError(f"{name} is still saved ({kind} did not take it out)") + + +def main(argv): + if argv[:1] in (["-h"], ["--help"]) or not argv: + print(__doc__.strip()); return 0 if argv else 2 + if argv[0] == "has" and len(argv) == 2 and argv[1] in KEY_NAMES: + return 0 if get(argv[1]) else 1 + if argv == ["where"]: + print(f"store: {store_kind()}") + for k in KEY_NAMES: + print(f" {k} {source(k) or '-'}") + return 0 + print("usage: python3 tools/keys.py has | where", file=sys.stderr) + return 2 + + +if __name__ == "__main__": + sys.exit(main(sys.argv[1:])) diff --git a/tools/modules.json b/tools/modules.json index a48cba20..2fe56b2f 100644 --- a/tools/modules.json +++ b/tools/modules.json @@ -307,6 +307,7 @@ "purpose": "Google's Gemini API: bin/vh tts gemini and gemini-lite, word timing with --align gemini (tts, pace), the voice library and voice design (voices), pictures (image gen: Nano Banana 2.1 for drafts, Nano Banana Pro for finals) and music (music --provider lyria: Lyria 3.5), both through the Interactions API.", "version": {"models": ["gemini-3.8-flash-tts (GEMINI_TTS_MODEL)", "gemini-3.8-flash-lite-tts", "gemini-3.5-transcribe (GEMINI_ASR_MODEL)", "gemini-nano-banana-2.1 (image gen --tier draft)", "gemini-3-pro-image (image gen --tier final)", "lyria-3.5 (music --provider lyria)", "lyria-3-clip-preview"]}, "license": "Google's Gemini API terms; its speech carries an inaudible SynthID watermark, so AI narration is disclosed (NOTES.md); so do its pictures (image gen: AIGC on record)", + "cost": "free_tier", "key_url": "https://aistudio.google.com/apikey", "needs": {"keys": ["GEMINI_API_KEY"], "account": "a Google AI Studio API key; the free tier has a daily quota"}, "adapter": ["tools/audio/tts.py (gemini_call)", "tools/audio/pace.py", "tools/assets/image.py (gemini_body, media_of)", "tools/audio/lyria.py"], "commands": ["tts", "pace", "voices", "image", "music"], @@ -322,6 +323,7 @@ "purpose": "MiniMax's T2A v2 speech: bin/vh tts minimax, with word timing from its own subtitles.", "version": {"models": ["speech-2.8-hd (MINIMAX_TTS_MODEL)"]}, "license": "MiniMax's terms", + "cost": "paid", "key_url": "https://platform.minimax.io", "needs": {"keys": ["MINIMAX_TOKEN_PLAN_KEY", "MINIMAX_API_KEY"], "account": "the international platform (platform.minimax.io): a Token Plan key spends its credits, a pay-as-you-go key the account's balance; a China-platform key needs MINIMAX_BASE_URL=https://api.minimaxi.com"}, "adapter": ["tools/audio/tts.py (minimax)"], "commands": ["tts"], @@ -338,6 +340,7 @@ "purpose": "ElevenLabs speech with timestamps: bin/vh tts elevenlabs.", "version": {"models": ["eleven_multilingual_v2 (ELEVENLABS_MODEL)"]}, "license": "ElevenLabs' terms", + "cost": "paid", "key_url": "https://elevenlabs.io/app/settings/api-keys", "needs": {"keys": ["ELEVENLABS_API_KEY"], "account": "an ElevenLabs account and API key"}, "adapter": ["tools/audio/tts.py (elevenlabs)"], "commands": ["tts"], @@ -352,6 +355,7 @@ "purpose": "Alibaba Cloud Model Studio speech through the dashscope SDK: bin/vh tts dashscope.", "version": {"models": ["qwen3-tts-flash (DASHSCOPE_TTS_MODEL)"]}, "license": "Alibaba Cloud's terms; the SDK: Apache-2.0", + "cost": "paid", "key_url": "https://bailian.console.aliyun.com", "needs": {"keys": ["DASHSCOPE_API_KEY"], "programs": ["uv"], "account": "an Alibaba Cloud Model Studio key; the international site needs DASHSCOPE_BASE_URL=https://dashscope-intl.aliyuncs.com/api/v1"}, "adapter": ["tools/audio/tts.py (dashscope)"], "commands": ["tts"], From 768194d08a73d3371d0ae3909d706f245e5adc43 Mon Sep 17 00:00:00 2001 From: zhanglinghao Date: Sun, 22 Nov 2026 07:01:30 +0800 Subject: [PATCH 16/19] test_settings: no nested quotes in an f-string (Python before 3.12 cannot read it) --- tools/desk/test_settings.py | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/tools/desk/test_settings.py b/tools/desk/test_settings.py index 0319f724..2313cfdc 100644 --- a/tools/desk/test_settings.py +++ b/tools/desk/test_settings.py @@ -16,7 +16,8 @@ (T / d).mkdir(parents=True, exist_ok=True) FILMS = T / "home" / "films" # a films folder in the home folder: the page shows it as ~/films REVEAL = T / "revealed.log" -(T / "reveal.sh").write_text(f"#!/bin/sh\nprintf '%s\\n' \"$1\" >> '{REVEAL}'\nenv > '{T / "reveal-env.txt"}'\n") # (what a child of the console inherits, as the column's install does) +CHILD_ENV = T / "reveal-env.txt" +(T / "reveal.sh").write_text(f"#!/bin/sh\nprintf '%s\\n' \"$1\" >> '{REVEAL}'\nenv > '{CHILD_ENV}'\n") # (what a child of the console inherits, as the column's install does) (T / "reveal.sh").chmod(0o755) CONF = T / "config" / "ovh" / "settings.json" sys.path.insert(0, str(HERE)) From 0553060f5e1f69d717c1679be25704dacb7c4356 Mon Sep 17 00:00:00 2001 From: zhanglinghao Date: Sun, 22 Nov 2026 13:38:10 +0800 Subject: [PATCH 17/19] Settings keys after review: the budget sentence says what is true, one store lookup per name, a readers check that finds indirect reads - the page and the change note: pictures and Lyria music stop without a budget; voices, word timing and auditions with these services are called directly and bill that account - tools/keys.py remembers each name's lookup per process (a missing key and a store that does not answer within 3 s too); a save or a removal refreshes that name; keys up to 2048 characters - the readers check searches bin/, tools/, engines/, components/, styles/ for a key read by name and, in files that touch keys, any read of the environment by a name the line does not spell; it is first tried on the old ways of reading - refusals carry a reason the page says in its own words; a failed save keeps the box open with the next step; no password box or form; a computer with no store gets plain words and a README section on how - doctor --probe asks with each key that is set (both of MiniMax's) - OVH_KEYSTORE=none passed on by the three doctor checks that build their own environment, and kept by acp.clean_env; the checks stage their store before any check --- README.md | 14 +++- README.zh-CN.md | 14 +++- changes/settings-keys.md | 5 +- tools/ci.sh | 6 +- tools/desk/README.md | 2 +- tools/desk/acp.py | 4 +- tools/desk/settings_api.py | 9 ++- tools/desk/static/settings.css | 2 + tools/desk/static/settings.js | 66 +++++++++++------ tools/desk/test_settings.py | 125 ++++++++++++++++++++++++++++----- tools/doctor.py | 25 +++++-- tools/keys.py | 73 ++++++++++++++----- 12 files changed, 270 insertions(+), 75 deletions(-) diff --git a/README.md b/README.md index 68337849..0efe3878 100644 --- a/README.md +++ b/README.md @@ -404,10 +404,22 @@ For finer control, name what you want to decide yourself: the hook, the look, th | LaTeX | formulas in Manim | | Blender 5.2 | only for path-traced shots and preparing 3D models; its sandbox is macOS-only for now | -- **Cost.** Rendering, music and sound effects run locally and cost nothing. What costs money is the agent itself (a Claude Code or Codex subscription, or API usage), plus any cloud voice, generated picture, generated music or generated video you choose, billed by that provider. A paid call needs a budget (the brief's `Budget:`, or a default in `LOCAL.md`) and is held against it before it's made; keys are always read from environment variables. +- **Cost.** Rendering, music and sound effects run locally and cost nothing. What costs money is the agent itself (a Claude Code or Codex subscription, or API usage), plus any cloud voice, generated picture, generated music or generated video you choose, billed by that provider. A paid call needs a budget (the brief's `Budget:`, or a default in `LOCAL.md`) and is held against it before it's made. API keys come from the environment or from Studio's settings ([API Key](#api-key)). - **Time.** A 30-second film at the standard level takes about 1–2 hours, most of it checking and fixing. - **Limits.** The agent can't watch or listen, only read frames and audio measurements, so the last look and listen are yours. The full workflow has only been run on macOS (Apple Silicon); on Linux, a silent film has been made on Ubuntu 24.04 (arm64, in Docker), and the three things it needed first are in [engines/README.md](engines/README.md#linux渲染前要先备好的三样). Realistic people need generated video. Type 09 (editing your own footage) is experimental and hasn't been tried on real footage yet. +### API Key + +Voices are made on this computer by default and need no API Key. An online service (Gemini, MiniMax, ElevenLabs, Alibaba Cloud Model Studio) needs the API Key from its own site. Paste it into Studio's settings (Settings → Services): it's kept in the computer's Keychain (on Linux, the Secret Service), never written into a file, and every command finds it, in the terminal and in Studio's chat. + +Where there is no such store, put the key in the file your terminal reads each time it starts (`~/.zshrc` on macOS, `~/.bashrc` on most Linux), then open a new terminal and start Studio from it: + +```bash +echo 'export GEMINI_API_KEY=paste-your-key-here' >> ~/.zshrc +``` + +The settings page lists the other services' names. A key set this way is used before one saved in Studio, name by name. An API Key isn't a budget: pictures and Lyria music are not made without a budget, while voices, word timing and auditions with these services are called directly and bill that account. + ## Install options and updates By default the installer registers the skills for both agents and uses about 400 MB on disk. The 37 read-only reference repos agents can read are not fetched then: an agent fetches the one a doc points to when it first needs it, saying its size first; `--refs` fetches them all now (about 300 MB more). The Studio app uses about 380 MB more, including its cached installer. diff --git a/README.zh-CN.md b/README.zh-CN.md index 1a5b677b..971304e8 100644 --- a/README.zh-CN.md +++ b/README.zh-CN.md @@ -404,10 +404,22 @@ AI 听不见,所以声音尽量做成能计算、能测量的。 | LaTeX | Manim 里的公式 | | Blender 5.2 | 只有路径追踪的镜头和整理 3D 模型才要;沙箱目前只在 macOS 上有 | -- **成本**:渲染、配乐、音效都在本地跑,不花钱。要花的是 agent 本身(Claude Code 或 Codex 的订阅或 API 用量),以及你选用的云端配音、生成图、生成音乐、生成式视频,按各家收费。付费调用要有预算(Brief 的 `Budget:`,或者 `LOCAL.md` 里的默认预算),调用前先按预算占住;key 一律从环境变量读。 +- **成本**:渲染、配乐、音效都在本地跑,不花钱。要花的是 agent 本身(Claude Code 或 Codex 的订阅或 API 用量),以及你选用的云端配音、生成图、生成音乐、生成式视频,按各家收费。付费调用要有预算(Brief 的 `Budget:`,或者 `LOCAL.md` 里的默认预算),调用前先按预算占住。API Key 从环境变量读,或者用 Studio 设置页里存的(见 [API Key](#api-key))。 - **时间**:30 秒的标准档片子大约 1–2 小时,大部分花在自查和返工上。 - **限制**:agent 看不了视频、听不了声音,只能看渲染出的帧、读声音的数据,所以最后一关还是要你看、你听;目前只在 macOS(Apple Silicon)上完整跑过,Linux 上在 Ubuntu 24.04(arm64,Docker 里)做过一支无声片,事先要备好的三样见 [engines/README.md](engines/README.md#linux渲染前要先备好的三样);写实人物要靠生成式视频;第 09 类剪辑还在试验,没有用真实素材试过。 +### API Key + +配音默认用这台电脑上的声音,不用 API Key。在线服务(Gemini、MiniMax、ElevenLabs、阿里云百炼)要用各家网站上的 API Key。把它粘贴到 Studio 的设置页(设置 → 服务):存在这台电脑的钥匙串里(Linux 上是 Secret Service),不写进任何文件,终端里和 Studio 的对话里,每条命令都找得到。 + +没有这样的地方可存时,把 key 写进终端每次启动都会读的那个文件(macOS 是 `~/.zshrc`,多数 Linux 是 `~/.bashrc`),再开一个新终端,从那里打开 Studio: + +```bash +echo 'export GEMINI_API_KEY=把你的key粘贴在这里' >> ~/.zshrc +``` + +其他几家的变量名,设置页上都写着。这样设的 key,比 Studio 里存的同名 key 先用。有 API Key 不等于有预算:出图和 Lyria 作曲没写预算就不调;用这几家配音、逐字对时、试音,是直接调用,花的是那个账户的钱。 + ## 安装、更新和国内网络 默认给两个 agent 注册 skill,约占 400 MB。37 个只读参考仓库安装时不拉:agent 用到文档指的那一个时再拉,拉之前先说多大;`--refs` 在安装时一次拉全(再约 300 MB)。Studio 应用另占约 380 MB,含缓存的安装包。 diff --git a/changes/settings-keys.md b/changes/settings-keys.md index baf63084..1548bda4 100644 --- a/changes/settings-keys.md +++ b/changes/settings-keys.md @@ -3,4 +3,7 @@ - 设置页多一节"服务":Gemini、MiniMax、ElevenLabs、阿里云百炼,各写用来做什么、免费还是收费、去哪拿 API Key;可以填上、换一个、拿掉,"测一下"用服务不花钱的地址问一次。配音默认仍用这台电脑上的声音,不用任何 key。 - 填的 key 存进系统自己的密码库(macOS 的钥匙串;Linux 上有 Secret Service 时用它,没有就照旧只能用环境变量),不写进任何文件,页面以后只知道设没设。环境变量里有的,仍然优先用环境变量的。 - 所有读 key 的命令都改成先看环境变量、再看 Studio 里存的(`tools/keys.py`);`bin/vh doctor` 说清是"在 Studio 里设了"还是"在环境变量里设了"。 -- 有 key 不等于能花钱:付费调用的预算规则一点没变。 +- 一台电脑上同一个变量名,环境变量里的先用;没有再用 Studio 里存的。每个命令对每个名字只问一次密码库,问不到(没有、超过 3 秒没回)也记住,不会在长时间配音的半路因为密码库卡一下就停。 +- "测一下"对设了的每个 key 各问一次(MiniMax 两个都设了就问两次),哪个没通过说哪个。 +- 没有密码库的电脑,页面说清要把 key 写进终端启动时读的文件,并链到 README 新加的"API Key"一节。 +- 有 API Key 不等于有预算:出图和 Lyria 作曲没写预算就不调;用这几家配音、逐字对时、试音,现在是直接调用,花的是那个账户的钱。存在钥匙串里的 key,这个用户运行的程序(包括 Studio 对话里的 agent)都读得到,所以对话里的 agent 现在也能调这几家收费的配音。预算规则本身这次没改。 diff --git a/tools/ci.sh b/tools/ci.sh index c59df926..6269edca 100755 --- a/tools/ci.sh +++ b/tools/ci.sh @@ -823,7 +823,7 @@ nxt, first = LocalServer(("127.0.0.1", 0), Next), LocalServer(("127.0.0.1", 0), for srv in (nxt, first): threading.Thread(target=srv.serve_forever, daemon=True).start() live = subprocess.run([sys.executable, "tools/doctor.py", "--json", "--probe", "--only", "minimax,dashscope"], capture_output=True, text=True, encoding="utf-8", - env={"PATH": stub, "HOME": t, "HF_HOME": os.path.join(t, "hf"), "MINIMAX_API_KEY": keys["MINIMAX_API_KEY"], + env={"PATH": stub, "HOME": t, "OVH_KEYSTORE": "none", "HF_HOME": os.path.join(t, "hf"), "MINIMAX_API_KEY": keys["MINIMAX_API_KEY"], "MINIMAX_BASE_URL": f"http://127.0.0.1:{first.server_address[1]}", "DASHSCOPE_API_KEY": keys["DASHSCOPE_API_KEY"], "DASHSCOPE_BASE_URL": "http://example.invalid/api/v1"}) outs += [live.stdout, live.stderr] @@ -859,7 +859,7 @@ for d in ("/bin", "/usr/bin"): os.symlink(os.path.join(d, n), os.path.join(bare, n)) shell = shutil.which(sh) if os.sep not in sh else sh for args in ([], ["--json"]): - r = subprocess.run([shell, "bin/vh", "doctor", *args], capture_output=True, text=True, encoding="utf-8", env={"PATH": stub + os.pathsep + bare, "HOME": t}) + r = subprocess.run([shell, "bin/vh", "doctor", *args], capture_output=True, text=True, encoding="utf-8", env={"PATH": stub + os.pathsep + bare, "HOME": t, "OVH_KEYSTORE": "none"}) ok_ = r.returncode == 0 and (json.loads(r.stdout)["modules"][1] == {"name": "node", "state": "outdated", "note": "v18.19.0 (22 or newer needed)"} if args else all(w in r.stdout for w in ("python3 not found", "node v18.19.0 (22 or newer needed)", "ffmpeg", "uv uv 0.9.0", "git", "chrome", "needs python3"))) if not ok_: @@ -1015,7 +1015,7 @@ import json, os, subprocess, sys t = sys.argv[1] stub = os.path.join(t, "stub"); os.makedirs(stub) def gx(): - r = subprocess.run([sys.executable, "tools/doctor.py", "--json"], capture_output=True, text=True, encoding="utf-8", env={"PATH": stub, "HOME": t}) + r = subprocess.run([sys.executable, "tools/doctor.py", "--json"], capture_output=True, text=True, encoding="utf-8", env={"PATH": stub, "HOME": t, "OVH_KEYSTORE": "none"}) return {m["name"]: m for m in json.loads(r.stdout)["modules"]}["manimgx"] def put(name, body): f = os.path.join(stub, name) diff --git a/tools/desk/README.md b/tools/desk/README.md index f0b084c1..7e927efb 100644 --- a/tools/desk/README.md +++ b/tools/desk/README.md @@ -156,7 +156,7 @@ bin/vh desk agents install # 装那一家的 ACP 适配器 - **右边那一列**:设置页里是空间的对话(从片子里打开也一样),上面一行说明这一点,免得把它当成片子的对话。没有这一次运行的令牌时,这一页什么都不显示,只说要在 Studio 的窗口里打开,带一个打开的按钮。 - **通用**:语言、外观(三个主题的小样)、片子放在哪(这个 Studio 找片子的、真有的文件夹,家目录写成 `~`,每个后面"在访达里打开"(Linux:"打开文件夹"),服务端只开这几个文件夹之一;换地方不在页面上改:页面说让 agent 改、改完重开 Studio,因为 Studio 起来时就按这些文件夹定了自己是哪一个)。 - **agent**:新对话默认用哪一种(只列装好的、只认装好的;对话列里每点一次"新对话"、空间里每开一支新片,都从它开始;一个地方上次用的是哪种,只决定打开时显示哪段已有的对话);每种装好的 agent 的模型和思考深度:开过一次对话、agent 给过选项以后才能选(记进 `picks.json`,和对话列里选的是同一份),之前只写现在从什么开始。模式和"不带个人设置"按对话,留在对话里。 -- **服务**:要 API Key 的在线服务(`tools/modules.json` 里带 `needs.keys` 的服务:Gemini、MiniMax、ElevenLabs、阿里云百炼),一家一块:用来做什么、一个词说花不花钱(`cost`)、每个 key 是"没设""在 Studio 里设了"还是"在环境变量里设了(优先用它)",按钮"填上""换一个""拿掉"(再点一次才拿掉)、"测一下"(`bin/vh doctor --probe --only <服务>`,不花钱),"去哪拿 API Key"(`key_url`)。填进框里的 key 发一次就清空,存进系统的密码库(`tools/keys.py`:macOS 的钥匙串,Linux 上有 Secret Service 时用 `secret-tool`,都没有就说只能用环境变量),页面以后只知道设没设,拿不回它。有一个存在 Studio 里时,这一节说一句它存在哪。末尾说清:终端里设的环境变量这一页不一定看得到;有 API Key 不等于能花钱,收费的调用还要预算。命令都经 `tools/keys.py` 取 key:环境变量优先,没有再用存在 Studio 里的;右边对话里的 agent 跑的命令也取得到(agent 自己的环境里照旧没有 key)。 +- **服务**:要 API Key 的在线服务(`tools/modules.json` 里带 `needs.keys` 的服务:Gemini、MiniMax、ElevenLabs、阿里云百炼),一家一块:用来做什么、一个词说花不花钱(`cost`)、每个 key 是"没设""在 Studio 里设了"还是"在环境变量里设了(优先用它)",按钮"填上""换一个""拿掉"(再点一次才拿掉)、"测一下"(`bin/vh doctor --probe --only <服务>`,不花钱),"去哪拿 API Key"(`key_url`)。填进框里的 key 发一次就清空,存进系统的密码库(`tools/keys.py`:macOS 的钥匙串,Linux 上有 Secret Service 时用 `secret-tool`,都没有就说这台电脑没有能妥善保管 key 的地方,要写进终端启动时读的文件,链到 README 的"API Key"一节),页面以后只知道设没设,拿不回它。存不进去时框不关,告诉人下一步怎么办(服务端的拒绝带 `reason`:`not_a_key`、`not_kept`、`no_store`,页面用自己的中英文说)。框是遮住字的普通输入框,不在 `
    ` 里,免得浏览器提出替人记住这个 key。"测一下"对设了的每个 key 各问一次。有一个存在 Studio 里时,这一节说一句它存在哪。末尾说清:终端里设的环境变量这一页不一定看得到;有 API Key 不等于有预算:出图和 Lyria 作曲没有预算不调,用这几家配音、逐字对时、试音是直接调用,花那个账户的钱。命令都经 `tools/keys.py` 取 key:环境变量优先,没有再用存在 Studio 里的;右边对话里的 agent 跑的命令也取得到(agent 自己的环境里照旧没有 key)。 - **片子的默认**:下载镜像(自动、国内镜像、官方源,同 `bin/vh settings mirror`)可以改:一改,Studio 自己的环境就跟着变(`settings.env_changes`),它之后起的安装和 agent 都按新的走,页面写明已经开着的对话里 agent 自己的 npm、uv 下载要新开对话才跟着变;用镜像时,你自己设了别的源的几处(`kept_own`)照旧用你的,页面列出来;设置文件是更新版本写的(`Newer`)时不改它,说一句;LOCAL.md 里人和 agent 都读的几行(只认模板那样的列表项,值后面括号里的说明不算)(默认努力程度、在哪看每一站、素材许可、声音库、谁拍板哪些事、帮手 agent 用的模型、默认预算)只显示,没写的写出没写时按什么,末尾一句"让 agent 帮你改"。这一页从不写 LOCAL.md。 - **这台电脑**:同空间页的"这台电脑上还缺"(`/api/machine`),什么都不缺时一句"做片子要的都有了";空间页那一块多一个"去设置里看"。 - **关于**:版本(这份克隆所在的那一版,之后还有提交就加上提交号)、工作台在哪、这一版在 GitHub 上的发布说明。 diff --git a/tools/desk/acp.py b/tools/desk/acp.py index e35d759f..d796e957 100644 --- a/tools/desk/acp.py +++ b/tools/desk/acp.py @@ -22,7 +22,9 @@ KEEP_ENV = ("HOME", "USER", "LOGNAME", "SHELL", "LANG", "TMPDIR", "PATH", # a proxy or a company's certificates the person's login goes through "HTTPS_PROXY", "HTTP_PROXY", "ALL_PROXY", "NO_PROXY", "https_proxy", "http_proxy", "all_proxy", "no_proxy", - "NODE_EXTRA_CA_CERTS", "SSL_CERT_FILE", "SSL_CERT_DIR", "REQUESTS_CA_BUNDLE") + "NODE_EXTRA_CA_CERTS", "SSL_CERT_FILE", "SSL_CERT_DIR", "REQUESTS_CA_BUNDLE", + # not a secret: "no password store" (tools/keys.py), so a console under tools/ci.sh starts agents that find no saved key + "OVH_KEYSTORE") # a key in the environment would bill the person's API account instead of using their subscription, and the host's # session variables (a Claude Code running the desk) would point the agent at the host's own endpoint and state DROP_PREFIX = ("ANTHROPIC_", "CLAUDE", "OPENAI_", "CODEX_", "DEEPSEEK_", "GEMINI_", "GOOGLE_API", "AWS_", "AZURE_") diff --git a/tools/desk/settings_api.py b/tools/desk/settings_api.py index af7db6f5..2793807f 100644 --- a/tools/desk/settings_api.py +++ b/tools/desk/settings_api.py @@ -112,8 +112,7 @@ def services(): continue ks = [] for n in names: - saved = bool(K.stored(n)) - ks.append({"name": n, "source": "env" if os.environ.get(n) else "studio" if saved else None, "saved": saved}) + ks.append({"name": n, "source": K.source(n), "saved": bool(K.stored(n))}) # (the store asked once per name: tools/keys.py) out.append({"module": m["name"], "keys": ks, "cost": m.get("cost"), "key_url": m.get("key_url"), "probe": bool(m.get("probe"))}) return out @@ -226,6 +225,10 @@ def post(handler): raise OSError(f"{A.picks_path()} was not written") else: raise ValueError(f"{name}: not a setting Studio changes") + except K.NotAKey as e: # (tools/keys.py's messages name the key's variable, never the key; the page says them in its own words) + return handler._error(400, str(e), "not_a_key") + except K.NotKept as e: + return handler._error(500, f"could not keep it: {e}", "no_store" if K.store_kind() == "none" else "not_kept") except S.Newer: return handler._error(409, "this computer's settings file was written by a newer OpenVideoHarness: not written over", "newer") except PermissionError as e: @@ -233,5 +236,5 @@ def post(handler): except ValueError as e: return handler._error(400, str(e)) except OSError as e: - return handler._error(500, f"could not keep it: {e}") # (tools/keys.py's messages name the key's variable, never the key) + return handler._error(500, f"could not keep it: {e}") return handler._json(state(handler.server.agents, handler.server.roots)) diff --git a/tools/desk/static/settings.css b/tools/desk/static/settings.css index 29928f2d..4573e52c 100644 --- a/tools/desk/static/settings.css +++ b/tools/desk/static/settings.css @@ -63,6 +63,8 @@ .sv-form{display:flex;gap:8px;grid-column:2/-1} .sv-form input{flex:1;min-width:0;background:var(--panel-2);border:1px solid var(--rule-2);border-radius:var(--r-ctl);padding:6px 10px;color:var(--ink);font:var(--fs-small)/1.4 var(--mono)} .sv-form input:focus{outline:none;border-color:var(--you)} +.sv-in{-webkit-text-security:disc} /* the key's box: masked by style, not a password box a browser would offer to remember */ +.sv-err{color:var(--wait)} .sv-test.ok{color:var(--ok,var(--ink))} .sv-get{display:inline-block;margin-top:6px;color:var(--you);font-size:var(--fs-label);text-decoration:none} .sv-get:hover{text-decoration:underline} diff --git a/tools/desk/static/settings.js b/tools/desk/static/settings.js index a0dd44d4..5489b76d 100644 --- a/tools/desk/static/settings.js +++ b/tools/desk/static/settings.js @@ -39,9 +39,12 @@ const SETTINGS = (() => { ph: "粘贴 {s} 的 API Key", get_key: "去哪拿 API Key", clear_note: "拿掉以后,用到它的命令会停下来告诉你。", t_wait: "正在问…", t_ok: "能用了", t_fail: "没通过,服务的回答:{x}", t_skip: "还没有 API Key 可以测", t_free: "测一下不花钱。", sv_kept_keychain: "存在这台电脑的钥匙串里,不写进任何文件。", sv_kept_secret: "存在这台电脑的密码库里,不写进任何文件。", - sv_none: "这台电脑上没有密码库,API Key 只能写在环境变量里:{v}。", + sv_none: "这台电脑上没有 Studio 能妥善保管 API Key 的地方。要用在线服务,就把 API Key 写进终端每次启动都会读的那个文件,再从新开的终端里打开 Studio。", how: "怎么写", + e_not_a_key: "这不像 API Key:从服务商的页面把它整段复制下来,不带空格和引号,再粘贴一次。", + e_not_kept: "没存进去:{s}没收下。再粘贴一次试试;还是不行,就照说明写进终端启动时读的文件。", e_not_cleared: "没拿掉:{s}没响应。再试一次。", + s_keychain: "钥匙串", s_secret: "密码库", sv_env_note: "在终端里设的环境变量,这一页不一定看得到;在这里填上的,终端里和右边的对话里都用得上。", - sv_budget: "有 API Key 不等于能花钱:收费的调用还要片子或这台电脑写了预算。这台电脑的默认预算:{x}", + sv_budget: "有 API Key 不等于有预算。出图和 Lyria 作曲,片子和这台电脑都没写预算就不调;用这几家配音、给字幕对时间、试音,是直接调用,花的是那个账户的钱(有免费额度的先用免费额度)。这台电脑的默认预算:{x}", nokey: "这一页要在 Studio 的窗口里打开才看得到。", reopen: "在 Studio 窗口里打开", }, en: { @@ -77,9 +80,12 @@ const SETTINGS = (() => { ph: "Paste your {s} API Key", get_key: "Get an API Key", clear_note: "Once removed, commands that need it stop and tell you.", t_wait: "Asking…", t_ok: "Works", t_fail: "Didn't work; the service said: {x}", t_skip: "No API Key to test yet", t_free: "Testing costs nothing.", sv_kept_keychain: "Kept in this computer's Keychain, never written into any file.", sv_kept_secret: "Kept in this computer's password store, never written into any file.", - sv_none: "This computer has no password store; an API Key can only come from the environment: {v}.", + sv_none: "This computer has no place where Studio can keep an API Key safely. To use an online service, put the API Key in the file your terminal reads each time it starts, then open Studio from a new terminal.", how: "How", + e_not_a_key: "That doesn't look like an API Key: copy the whole key from the provider's page, with no spaces or quotes, and paste it again.", + e_not_kept: "Not saved: {s} didn't take it. Paste it again; if it still fails, put it in the file your terminal reads when it starts.", e_not_cleared: "Not removed: {s} didn't answer. Try again.", + s_keychain: "the Keychain", s_secret: "the password store", sv_env_note: "Environment variables set in your terminal may not show on this page; a key set here works in the terminal and in the chat on the right.", - sv_budget: "An API Key isn't a budget: a paid call also needs a budget on the film or this computer. This computer's default budget: {x}", + sv_budget: "An API Key isn't a budget. Pictures and Lyria music are not made unless the film or this computer has a budget; voices, caption timing and auditions with these services are called directly and bill that account (a free tier is used first). This computer's default budget: {x}", nokey: "This page shows only in Studio's own window.", reopen: "Open in Studio's window", }, }; @@ -88,7 +94,14 @@ const SETTINGS = (() => { const SECTIONS = [{ id: "general" }, { id: "agent" }, { id: "services" }, { id: "films" }, { id: "machine" }, { id: "about" }, { id: "account", hidden: true }]; const THEMES = ["darkfield", "prism", "bridge"]; let ST = null, BACK = "#/", SEC = "general"; - let EDIT = "", ARM = "", TESTS = {}; // the services: the key being typed, the key whose 拿掉 asks once more, each service's last test + let EDIT = "", ARM = "", TESTS = {}, SVERR = {}; // the services: the key being typed, the key whose 拿掉 asks once more, each service's last test, what a failed save of a key said + const HOWTO = () => `https://github.com/ZLHad/OpenVideoHarness/blob/main/README${LANG === "en" ? "" : ".zh-CN"}.md#api-key`; // the front page's "API Key": how to put a key where the terminal reads it + const why_err = (r) => { // a refusal of the console's as the page's own word (said in the language shown), when it gave a reason + const why = r.data && r.data.reason; + return why === "not_a_key" ? "e_not_a_key" : why === "not_kept" ? "e_not_kept" : why === "no_store" ? "sv_none" : null; + }; + const store_word = () => w(ST && ST.store === "secret-service" ? "s_secret" : "s_keychain"); + const said_err = (r) => { const k = why_err(r); return k ? w(k, { s: store_word() }) : null; }; async function call(method, body) { try { @@ -101,7 +114,7 @@ const SETTINGS = (() => { async function save(name, value, quiet) { const r = await call("POST", { name, value }); if (r.ok && r.data && r.data.version) ST = r.data; - if (!quiet || (!r.ok && r.data && r.data.reason === "newer")) toast(r.ok ? w("saved") : r.status === 403 ? w("nokey") : r.data && r.data.reason === "newer" ? w("newer") : w("failed", { x: (r.data && r.data.error) || r.status })); + if (!quiet || (!r.ok && r.data && r.data.reason === "newer")) toast(r.ok ? w("saved") : r.status === 403 ? w("nokey") : r.data && r.data.reason === "newer" ? w("newer") : said_err(r) || w("failed", { x: (r.data && r.data.error) || r.status })); return r.ok; } @@ -182,7 +195,8 @@ const SETTINGS = (() => { const anySaved = list.some((s) => s.keys.some((k) => k.saved)); const keyRow = (s, k) => { const label = (W.zh["k_" + k.name] ? w("k_" + k.name) : w("k_key")), status = w(k.source === "env" ? "st_env" : k.source === "studio" ? "st_studio" : "st_none"); - if (EDIT === k.name) return `
    ${esc(label)}
    `; + // (no
    and no password box: a browser would offer to keep the key in its own password manager; the box is masked by its style) + if (EDIT === k.name) return `
    ${esc(label)}
    ${SVERR[k.name] ? `` : ""}
    `; const acts = store === "none" ? "" : k.saved ? `` : k.source === "env" ? "" : ``; return `
    ${esc(label)}${esc(status)}${acts}${ARM === k.name ? `

    ${esc(w("clear_note"))}

    ` : ""}
    `; @@ -195,11 +209,10 @@ const SETTINGS = (() => { + s.keys.map((k) => keyRow(s, k)).join("") + `${said ? `

    ${esc(said)}

    ` : ""}${s.key_url ? `${esc(w("get_key"))} ↗` : ""}
    `; }; - const names = list.flatMap((s) => s.keys.map((k) => k.name)).join(", "); return `

    ${esc(w("sv_lead"))}

    ` - + (store === "none" ? `

    ${esc(w("sv_none", { v: names }))}

    ` : anySaved ? `

    ${esc(w(store === "keychain" ? "sv_kept_keychain" : "sv_kept_secret"))}

    ` : "") + + (store === "none" ? `

    ${esc(w("sv_none"))} ${esc(w("how"))} ↗

    ` : anySaved ? `

    ${esc(w(store === "keychain" ? "sv_kept_keychain" : "sv_kept_secret"))}

    ` : "") + list.map(card).join("") - + `

    ${esc(w("sv_env_note"))}
    ${esc(w("sv_budget", { x: L.budget || w("f_unset") }))}

    `; + + `

    ${store === "none" ? "" : `${esc(w("sv_env_note"))}
    `}${esc(w("sv_budget", { x: L.budget || w("f_unset") }))}

    `; } function films() { const L = (ST.local && ST.local.lines) || {}, M = ST.mirror || {}; @@ -248,27 +261,36 @@ const SETTINGS = (() => { if (b) choose(b); }); document.addEventListener("click", async (e) => { // the services' buttons (the page's own clicks only) - const b = e.target.closest(".settings [data-sv-edit], .settings [data-sv-cancel], .settings [data-sv-clear], .settings [data-sv-test]"); + const b = e.target.closest(".settings [data-sv-edit], .settings [data-sv-cancel], .settings [data-sv-save], .settings [data-sv-clear], .settings [data-sv-test]"); if (!b || !e.isTrusted) return; - if (b.dataset.svEdit) { EDIT = b.dataset.svEdit; ARM = ""; draw(); const i = $("#svIn"); if (i) i.focus(); return; } - if (b.hasAttribute("data-sv-cancel")) { EDIT = ""; draw(); return; } + if (b.dataset.svEdit) { EDIT = b.dataset.svEdit; ARM = ""; SVERR = {}; draw(); const i = $("#svIn"); if (i) i.focus(); return; } + if (b.hasAttribute("data-sv-cancel")) { EDIT = ""; SVERR = {}; draw(); return; } + if (b.hasAttribute("data-sv-save")) return sendKey(b.closest("[data-sv-form]")); if (b.dataset.svClear) { if (ARM !== b.dataset.svClear) { ARM = b.dataset.svClear; EDIT = ""; draw(); return; } - ARM = ""; await save("key:" + b.dataset.svClear, null); draw(); return; + ARM = ""; const r = await call("POST", { name: "key:" + b.dataset.svClear, value: null }); + if (r.ok && r.data && r.data.version) ST = r.data; + toast(r.ok ? w("saved") : r.status === 403 ? w("nokey") : r.data && r.data.reason === "not_kept" ? w("e_not_cleared", { s: w(ST && ST.store === "secret-service" ? "s_secret" : "s_keychain") }) : said_err(r) || w("failed", { x: (r.data && r.data.error) || r.status })); + draw(); return; } const m = b.dataset.svTest; TESTS[m] = "wait"; draw(); const r = await call("POST", { name: "test:" + m }); TESTS[m] = r.ok && r.data && r.data.probe ? r.data.probe : { state: "failed", note: r.status === 403 ? w("nokey") : String((r.data && r.data.error) || r.status) }; if (parse().view === "settings") draw(); }); - document.addEventListener("submit", async (e) => { // a key typed into the box: sent once, the box emptied at once, never kept in the page - const f = e.target.closest(".settings [data-sv-form]"); - if (!f) return; - e.preventDefault(); - const i = f.querySelector("input"), v = i.value.trim(); i.value = ""; - if (!v || !e.isTrusted) return; - const name = f.dataset.svForm; EDIT = ""; - await save("key:" + name, v); draw(); + async function sendKey(f) { // a key typed into the box: sent once, the box emptied at once, never kept in the page + const i = f && f.querySelector("input"); + if (!i) return; + const v = i.value.trim(), name = f.dataset.svForm; i.value = ""; + if (!v) return; + const r = await call("POST", { name: "key:" + name, value: v }); + if (r.ok && r.data && r.data.version) { ST = r.data; EDIT = ""; SVERR = {}; toast(w("saved")); } + else SVERR = { [name]: r.status === 403 ? { k: "nokey" } : why_err(r) ? { k: why_err(r) } : { x: w("failed", { x: (r.data && r.data.error) || r.status }) } }; // the box stays open, empty, with what to do next + if (parse().view === "settings") { draw(); const n = $("#svIn"); if (n && EDIT) n.focus(); } + } + document.addEventListener("keydown", (e) => { // Enter in the key's box sends it (there is no form to submit) + if (e.key !== "Enter" || !e.isTrusted || e.isComposing || !(e.target.matches && e.target.matches(".settings .sv-in"))) return; + e.preventDefault(); sendKey(e.target.closest("[data-sv-form]")); }); document.addEventListener("change", async (e) => { const s = e.target.closest(".settings select[data-set]"); diff --git a/tools/desk/test_settings.py b/tools/desk/test_settings.py index 5a80477c..e8988c01 100644 --- a/tools/desk/test_settings.py +++ b/tools/desk/test_settings.py @@ -30,7 +30,7 @@ OVH_PROJECTS=str(T / "no-such-folder"), OVH_REVEAL=str(T / "reveal.sh")) for k in ("OVH_KEYSTORE", "OVH_KEYCHAIN", "OVH_KEYSTORE_SERVICE", "OVH_SECRET_TOOL"): # (tools/ci.sh turns the store off: these checks have one of their own) ENV.pop(k, None) -for k in [k for k in ENV if "API_KEY" in k.upper() or k.upper().endswith(("_TOKEN", "_SECRET", "_PLAN_KEY"))]: # no real key of the person's reaches anything here +for k in [k for k in ENV if "API_KEY" in k.upper() or k.upper().endswith(("_TOKEN", "_SECRET", "_PLAN_KEY", "_BASE_URL"))]: # no real key of the person's reaches anything here del ENV[k] FAKE = "ovhTestKey" + os.urandom(6).hex() # a made-up key: never a real one, and never seen in anything the checks read back MAC = sys.platform == "darwin" and shutil.which("security") is not None @@ -293,12 +293,16 @@ def services(): bad.append(f"saving: {st} {g}") st, t = d.req("POST", "/api/settings", {"name": "test:gemini"}) if st != 200 or (t.get("probe") or {}).get("state") != "ok": bad.append(f"测一下: {st} {t}") - for body in ({"name": "key:GEMINI_API_KEY", "value": "not a key"}, {"name": "key:PATH", "value": FAKE}, {"name": "test:openverse"}): + for body, why in (({"name": "key:GEMINI_API_KEY", "value": "not a key"}, "not_a_key"), ({"name": "key:PATH", "value": FAKE}, None), ({"name": "test:openverse"}, None)): st, e = d.req("POST", "/api/settings", body) - if st != 400 or FAKE in json.dumps(e) or "not a key" in json.dumps(e): bad.append(f"{body['name']}: {st} {e}") + if st != 400 or FAKE in json.dumps(e) or "not a key" in json.dumps(e) or e.get("reason") != why: bad.append(f"{body['name']}: {st} {e}") + st, s = d.req("POST", "/api/settings", {"name": "key:GEMINI_API_KEY", "value": "a" * 2048}) # a key as long as the longest a provider issues + if st != 200 or {x["module"]: x for x in s["services"]}["gemini"]["keys"][0]["source"] != "studio": bad.append(f"a 2048-character key: {st}") if d.req("POST", "/api/settings", {"name": "key:GEMINI_API_KEY", "value": FAKE}, token=False)[0] != 403: bad.append("saved without the token") st, s = d.req("POST", "/api/settings", {"name": "key:GEMINI_API_KEY", "value": None}) if st != 200 or {x["module"]: x for x in s["services"]}["gemini"]["keys"][0]["saved"]: bad.append(f"taking it out: {st}") + st, s = d.req("GET", "/api/settings") # (the console remembers what it asked the store: a save or a removal is seen at once) + if {x["module"]: x for x in s["services"]}["gemini"]["keys"][0] != {"name": "GEMINI_API_KEY", "source": None, "saved": False}: bad.append("after taking it out, the page is told it is still set") d.req("POST", "/api/settings", {"name": "key:GEMINI_API_KEY", "value": FAKE}) # saved again, for what follows if FAKE in d.log.read_text(): bad.append("the key is in the console's log") return "; ".join(bad) or None @@ -377,6 +381,17 @@ def keys_module_check(): except ValueError: pass K.clear("ELEVENLABS_API_KEY") # nothing saved: nothing to do +calls, real = [], K._run +K._run = lambda *a, **k: (calls.append(a[0][:2]), real(*a, **k))[1] # every call of the store, counted +K.forget(); K.get("GEMINI_API_KEY"); K.get("GEMINI_API_KEY"); K.source("GEMINI_API_KEY"); K.stored("GEMINI_API_KEY") +assert len(calls) == 1, f"four lookups asked the store {{len(calls)}} times" +K.clear("GEMINI_API_KEY"); n = len(calls) +assert K.get("GEMINI_API_KEY") is None and K.source("GEMINI_API_KEY") is None and len(calls) == n, "after a removal: still found, or asked again" +K.save("GEMINI_API_KEY", v); n = len(calls) +assert K.get("GEMINI_API_KEY") == v and len(calls) == n, "after a save: not found at once, or asked again" +K.forget(); K._run = lambda *a, **k: (calls.append(a[0][:2]), None)[1]; n = len(calls) # a store that does not answer in time +assert K.get("MINIMAX_API_KEY") is None and K.get("MINIMAX_API_KEY") is None and len(calls) == n + 1, "a store with no answer asked again" +assert K.LOOKUP_S <= 3 print("ok") """ rc, out = py(code) @@ -388,18 +403,78 @@ def keys_module_check(): return "keys.py has: a saved key not found" +def env_reads(rel, text, names): + """The lines of one file that read a service's key from the environment, not through tools/keys.py: a key's name + read anywhere (os.environ, getenv, "X" in os.environ, process.env, a shell's $X); and, in a file that has anything + to do with keys (it names one, KEY_NAMES, KEY_OF, imports keys or reads modules.json's "keys"), any read of the + environment by a name it does not spell, which could be a key's (os.environ.get(k), os.environ[var], getenv(x)).""" + k = "|".join(map(re.escape, names)) + lit = re.compile(r"""environ(?:\.get|\.pop|\.setdefault)?\(\s*["'](?:%s)["']|environ\[\s*["'](?:%s)["']\s*\](?!\s*=[^=])|getenv\(\s*["'](?:%s)["']""" + r"""|["'](?:%s)["']\s+(?:not\s+)?in\s+(?:os\.)?environ\b|process\.env(?:\.(?:%s)\b|\[\s*["'](?:%s)["'])""" + r"""|\$\{?(?:%s)\b|printenv\s+["']?(?:%s)\b""" % ((k,) * 8)) + shell = rel.endswith(".sh") or rel.startswith("bin/") + dyn = re.compile(r"""(?:environ\.get|getenv)\(\s*(?!["'\s)])|environ\[\s*(?!["'])(?![^\]]*\]\s*=[^=])|(? names a keychain of their own on every call (macOS), OVH_KEYSTORE_SERVICE a service name of -their own, OVH_SECRET_TOOL a stand-in for secret-tool (Linux); OVH_KEYSTORE=none turns the store off. +their own, OVH_SECRET_TOOL a stand-in for secret-tool (Linux); OVH_KEYSTORE=none turns the store off. tools/ci.sh sets +OVH_KEYSTORE=none for all its checks and passes it on where a check builds an environment of its own (acp.clean_env +keeps it too); a check that never set it still runs with a scratch HOME, whose search list has no keychain of the person's. """ import json, os, re, shutil, subprocess, sys from pathlib import Path ROOT = Path(__file__).resolve().parent.parent -VALUE = re.compile(r"[A-Za-z0-9][A-Za-z0-9._:+/=-]{7,511}") # what a provider's API key looks like: no space, no quote, no newline -_CACHE = {} +VALUE = re.compile(r"[A-Za-z0-9][A-Za-z0-9._:+/=-]{7,2047}") # what a provider's API key looks like (JWT-style ones run past 600): no space, quote or newline +LOOKUP_S, WRITE_S = 3, 10 # seconds a store may take to answer a lookup, and a save or a clear +_CACHE, _FOUND = {}, {} # the store's kind; name → the saved key or None, as this process last asked the store def key_names(): @@ -41,6 +55,14 @@ def service(): return os.environ.get("OVH_KEYSTORE_SERVICE") or "OpenVideoHarness" +class NotAKey(ValueError): + """A value that does not look like an API key (Studio's page says so in the person's language).""" + + +class NotKept(OSError): + """The store did not take a save or a clear, or there is no store.""" + + def _known(name): if name not in KEY_NAMES: raise ValueError(f"{name}: not the name of a key a service needs (tools/modules.json)") @@ -57,7 +79,7 @@ def store_kind(): elif sys.platform.startswith("linux") and _secret_tool(): try: # a lookup of nothing: exit 1 when the Secret Service answers, an error message when there is none to answer r = subprocess.run([_secret_tool(), "lookup", "service", service(), "key", "-"], capture_output=True, text=True, - timeout=5, stdin=subprocess.DEVNULL) + timeout=LOOKUP_S, stdin=subprocess.DEVNULL) kind = "secret-service" if r.returncode in (0, 1) and not r.stderr.strip() else "none" except (OSError, subprocess.SubprocessError): kind = "none" @@ -74,17 +96,32 @@ def _keychain(): return [k] if k else [] -def _run(argv, stdin=None): +def _run(argv, stdin=None, timeout=LOOKUP_S): try: - return subprocess.run(argv, input=stdin, capture_output=True, text=True, timeout=10, + return subprocess.run(argv, input=stdin, capture_output=True, text=True, timeout=timeout, stdin=None if stdin is not None else subprocess.DEVNULL) except (OSError, subprocess.SubprocessError): return None def stored(name): - """The key saved in Studio for this name, or None (no store, nothing saved, the store did not answer).""" + """The key saved in Studio for this name, or None (no store, nothing saved, the store did not answer): asked once + per process, then remembered.""" _known(name) + if name not in _FOUND: + _FOUND[name] = _lookup(name) + return _FOUND[name] + + +def forget(name=None): + """Ask the store again next time (one name, or all): for a long-running process when something else changed it.""" + if name is None: + _FOUND.clear() + else: + _FOUND.pop(name, None) + + +def _lookup(name): kind = store_kind() if kind == "keychain": r = _run(["security", "find-generic-password", "-s", service(), "-a", name, "-w", *_keychain()]) @@ -113,16 +150,17 @@ def save(name, value): a key; OSError: no store, or it did not take it.""" _known(name) if not isinstance(value, str) or not VALUE.fullmatch(value): - raise ValueError(f"{name}: that is not an API key (8 to 512 letters, digits and . _ : + / = -, starting with a letter or digit)") + raise NotAKey(f"{name}: that is not an API key (8 to 2048 letters, digits and . _ : + / = -, starting with a letter or digit)") kind = store_kind() if kind == "keychain": # security's own prompt reads the line on stdin: the key never is an argument of a process - r = _run(["security", "-i"], stdin=f'add-generic-password -U -s "{service()}" -a {name} -l "{service()} {name}" -w {value} {" ".join(chr(34) + k + chr(34) for k in _keychain())}\n') + r = _run(["security", "-i"], timeout=WRITE_S, stdin=f'add-generic-password -U -s "{service()}" -a {name} -l "{service()} {name}" -w {value} {" ".join(chr(34) + k + chr(34) for k in _keychain())}\n') elif kind == "secret-service": - r = _run([_secret_tool(), "store", f"--label={service()} {name}", "service", service(), "key", name], stdin=value) + r = _run([_secret_tool(), "store", f"--label={service()} {name}", "service", service(), "key", name], stdin=value, timeout=WRITE_S) else: - raise OSError("this computer has no password store: the key can only come from the environment") - if r is None or r.returncode != 0 or stored(name) != value: - raise OSError(f"{name} was not saved ({kind} did not take it)") + raise NotKept("this computer has no password store: the key can only come from the environment") + _FOUND[name] = _lookup(name) # what the store holds now, asked afresh + if r is None or r.returncode != 0 or _FOUND[name] != value: + raise NotKept(f"{name} was not saved ({kind} did not take it)") def clear(name): @@ -130,11 +168,12 @@ def clear(name): _known(name) kind = store_kind() if kind == "keychain": - _run(["security", "delete-generic-password", "-s", service(), "-a", name, *_keychain()]) + _run(["security", "delete-generic-password", "-s", service(), "-a", name, *_keychain()], timeout=WRITE_S) elif kind == "secret-service": - _run([_secret_tool(), "clear", "service", service(), "key", name]) - if stored(name): - raise OSError(f"{name} is still saved ({kind} did not take it out)") + _run([_secret_tool(), "clear", "service", service(), "key", name], timeout=WRITE_S) + _FOUND[name] = _lookup(name) + if _FOUND[name]: + raise NotKept(f"{name} is still saved ({kind} did not take it out)") def main(argv): From b89fd5d2b77629e90d5eb4e821d44993b56d6ce0 Mon Sep 17 00:00:00 2001 From: zhanglinghao Date: Sun, 22 Nov 2026 14:43:06 +0800 Subject: [PATCH 18/19] First-run guidance: a command that stops for a missing API Key says where to set it and where to get one; Studio's now line says the film waits on it MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - tools/keys.py: one sentence for a missing key (the service, Studio's Settings → Services or the environment, where to get one, what works with none), put on the run's record as the new code no_key - tts (each provider, --align gemini, voices audition), pace --align gemini, music --provider lyria, image gen say it - tools/standing.py: needs_key while the newest run of a command stopped for a key that is still not set, with the way to Settings → Services (act kind settings); Studio's column renders that button - schemas, jsonerr's code list, the desk README --- changes/settings-first-run.md | 5 ++ tools/assets/image.py | 2 +- tools/audio/lyria.py | 2 +- tools/audio/pace.py | 4 +- tools/audio/tts.py | 25 +++++----- tools/desk/README.md | 4 +- tools/desk/static/studio.js | 1 + tools/desk/test_agents.py | 32 ++++++++++++- tools/desk/test_settings.py | 41 +++++++++++++++++ tools/jsonerr.py | 1 + tools/keys.py | 47 +++++++++++++++++++ tools/schemas/output/error.schema.json | 2 +- tools/schemas/output/projects.schema.json | 2 +- tools/schemas/output/status.schema.json | 2 +- tools/standing.py | 56 ++++++++++++++++++++++- 15 files changed, 201 insertions(+), 25 deletions(-) create mode 100644 changes/settings-first-run.md diff --git a/changes/settings-first-run.md b/changes/settings-first-run.md new file mode 100644 index 00000000..369a1b22 --- /dev/null +++ b/changes/settings-first-run.md @@ -0,0 +1,5 @@ +**少了 API Key 时,命令和 Studio 都用一句话说清去哪设、去哪拿、不用它还能怎么做** +- Why: 配音、对时间、出图、作曲缺 key 时,原来各说各的("set GEMINI_API_KEY (Google AI Studio → Get API key)"),只说了环境变量;Studio 里只看得到"配音结束时报了问题",人不知道片子在等什么、该去哪里补。 +- 缺 key 停下的命令(`bin/vh tts` 各家、`--align gemini`、`voices audition`、`pace --align gemini`、`music --provider lyria`、`image gen`)都说同一句:哪一家、哪个 key,在 Studio 的设置 → 服务里填上(或者设环境变量),去哪拿,不用它时这台电脑上还能怎么做(本地配音、本地对时间、本地作曲)。这句由 `tools/keys.py` 写,记进这次运行的记录,代码是新的 `no_key`。 +- `bin/vh status` 和 Studio 的现状行在片子等 key 时说:"配音停下了:还没有 Gemini 的 API Key。在设置 → 服务里填上,再让 agent 接着做。"Studio 里那一行带一个按钮,点了直接到设置 → 服务。key 设上了(Studio 里或环境变量里),或者同一条命令再跑一次没为它停,这句就不说了。 +- 不花钱:检查在调用之前,什么都没调就停。 diff --git a/tools/assets/image.py b/tools/assets/image.py index 3ba109da..84b3afb6 100644 --- a/tools/assets/image.py +++ b/tools/assets/image.py @@ -621,7 +621,7 @@ def cmd_gen(a): return 0 if a.provider == "gemini": if not a.offline and not keys.get("GEMINI_API_KEY"): - raise Usage("set GEMINI_API_KEY (Google AI Studio → Get API key), or save it in Studio's settings (Services)") + raise Usage(keys.stopping("GEMINI_API_KEY")) if not plan["budget"]["ok"]: raise Failed(f"{plan['budget']['message']} (bin/vh image gen --dry-run shows the estimate)") if refs: diff --git a/tools/audio/lyria.py b/tools/audio/lyria.py index 7b679b48..eb7ab16c 100644 --- a/tools/audio/lyria.py +++ b/tools/audio/lyria.py @@ -133,7 +133,7 @@ def cmd_gen(a): say(" nothing called (--dry-run)") return 0 if not a.offline and not keys.get("GEMINI_API_KEY"): - raise Usage("set GEMINI_API_KEY (Google AI Studio → Get API key), or save it in Studio's settings (Services)") + raise Usage(keys.stopping("GEMINI_API_KEY", "or bin/vh music without --provider, composed on this computer")) if not chk["ok"]: raise Failed(f"{chk['message']} (--dry-run shows the price)") folder = project / GENMUSIC / cid diff --git a/tools/audio/pace.py b/tools/audio/pace.py index d8fe29d6..50ac3c7b 100644 --- a/tools/audio/pace.py +++ b/tools/audio/pace.py @@ -678,7 +678,7 @@ def captions(old, skip_lint=False): f" --resume first, or pass --align gemini|whisper here to transcribe the take") if (missing and not found) or (a.align != "map" and not a.dry_run): # before anything is written if a.align == "gemini" and not tts.keys.get("GEMINI_API_KEY"): - sys.exit("set GEMINI_API_KEY (Google AI Studio → Get API key) for --align gemini; nothing was written") + sys.exit(tts.keys.stopping("GEMINI_API_KEY", "--align gemini needs it (--align whisper does not); nothing was written")) if a.align == "whisper" and importlib.util.find_spec("mlx_whisper") is None: sys.exit("--align whisper needs mlx-whisper (Apple Silicon; bin/vh pace adds it with --align whisper); nothing was written") if missing: # the take's own word times, transcribed once and kept beside it @@ -759,7 +759,7 @@ def save(): rc = 0 if a.align != "map": if a.align == "gemini" and not tts.keys.get("GEMINI_API_KEY"): - sys.exit("set GEMINI_API_KEY for --align gemini: the paced take is written with mapped word times") + sys.exit(tts.keys.stopping("GEMINI_API_KEY", "--align gemini needs it; the paced take is written with mapped word times")) try: fresh = align_take(new, wav, a.align, a.lang, tmp, out["duration"]) except Exception as e: # quota, network: the mapped word times stay diff --git a/tools/audio/tts.py b/tools/audio/tts.py index 2e5eff07..b3cd47dc 100644 --- a/tools/audio/tts.py +++ b/tools/audio/tts.py @@ -218,7 +218,7 @@ def gemini_call(path, body=None, method=None, query=None, timeout=180, tries=3): so does one asking for more than 90 s. The delay and the quota are read from the first 8 KB of the body: a long quota message puts "retry in Ns" past the first 500 bytes, which are all that the error message repeats. A call that fails for good raises GeminiError.""" - key = keys.get("GEMINI_API_KEY") or sys.exit("set GEMINI_API_KEY (Google AI Studio → Get API key)") + key = keys.get("GEMINI_API_KEY") or sys.exit(keys.stopping("GEMINI_API_KEY")) url = f"{GEMINI_API}/{path}" + (f"?{urllib.parse.urlencode(query, doseq=True)}" if query else "") data = None if body is None else json.dumps(body).encode() k = limited = 0 @@ -250,17 +250,17 @@ def gemini_call(path, body=None, method=None, query=None, timeout=180, tries=3): # ---------- providers: each writes a WAV at `out` and may return word/char timings ---------- -KEY_OF = {"gemini": "GEMINI_API_KEY (Google AI Studio → Get API key)", "gemini-lite": "GEMINI_API_KEY (Google AI Studio → Get API key)", - "minimax": "MINIMAX_TOKEN_PLAN_KEY (Token Plan) or MINIMAX_API_KEY (pay-as-you-go), from platform.minimax.io", - "elevenlabs": "ELEVENLABS_API_KEY (elevenlabs.io)", "dashscope": "DASHSCOPE_API_KEY (Alibaba Cloud Model Studio, 阿里云百炼)"} +KEY_OF = {"gemini": ["GEMINI_API_KEY"], "gemini-lite": ["GEMINI_API_KEY"], "minimax": ["MINIMAX_TOKEN_PLAN_KEY", "MINIMAX_API_KEY"], # Token Plan first + "elevenlabs": ["ELEVENLABS_API_KEY"], "dashscope": ["DASHSCOPE_API_KEY"]} def no_key(provider): - """Exit (1) on a provider with no key: the key it needs, and what works with none on this machine.""" + """Exit (1) on a provider with no key: tools/keys.py's sentence (where to set it, where to get one), and what works with + none on this machine; on the run's record as no_key.""" if sys.platform == "darwin" and platform.machine() == "arm64": - free = "the local default needs no key: leave the provider out, bin/vh tts (qwen, free, about " + firstuse.gb(firstuse.total(["qwen"])) + " on first use)" + free = "or leave the provider out for this computer's own voice, which needs no key (qwen, free, about " + firstuse.gb(firstuse.total(["qwen"])) + " on first use)" else: - free = "the local default (qwen) needs no key but only runs on Apple Silicon; here --provider edge needs none (free, online)" - sys.exit(f"set {KEY_OF[provider]} for {provider}; {free}") + free = "or --provider edge, which needs no key (free, online; the local default, qwen, runs only on Apple Silicon)" + sys.exit(keys.stopping(KEY_OF[provider], free)) def hf_cached(model_id): """The model is on this machine: a local folder, or a snapshot in the Hugging Face cache, found where the Hub itself @@ -1122,10 +1122,9 @@ def audition(a): if a.align == "local": need_local_asr() if (gemini or a.align == "gemini") and not keys.get("GEMINI_API_KEY"): - sys.exit("voices audition: set GEMINI_API_KEY (Google AI Studio → Get API key)" - + (f" for --provider {a.provider}" if gemini else " for --align gemini") + "; nothing was synthesized") + sys.exit("voices audition: " + keys.stopping("GEMINI_API_KEY", (f"--provider {a.provider}" if gemini else "--align gemini") + " needs it; nothing was synthesized")) if a.provider == "minimax" and not minimax_key()[0]: - sys.exit("voices audition: set MINIMAX_TOKEN_PLAN_KEY or MINIMAX_API_KEY for --provider minimax; nothing was synthesized") + sys.exit("voices audition: " + keys.stopping(KEY_OF["minimax"], "nothing was synthesized")) try: import voicefeat except ImportError: @@ -1268,7 +1267,7 @@ def main(): if a.align == "local": # before anything is synthesized or deleted need_local_asr() if align and a.align != "local" and not keys.get("GEMINI_API_KEY"): - sys.exit("set GEMINI_API_KEY (Google AI Studio → Get API key): --align gemini / --join transcribe with Gemini (or --align local)") + sys.exit(keys.stopping("GEMINI_API_KEY", "--align gemini and --join transcribe with Gemini; or --align local, on this computer")) if man and a.provider == "minimax" and join != "none" and man.get("gap") != a.gap: sys.exit(f"--resume: --gap was {man.get('gap')} for the run, now {a.gap}; in a joined minimax request it is part of the" f" text: pass --gap {man.get('gap')}, or drop --resume to start over") @@ -1287,7 +1286,7 @@ def linked(texts): # one minimax request: the lines linked by a pause mark of blocks.append([s]) wavs = [f"{i+1:02d}.wav" for i in range(len(segs))] if join == "none" else [f"_block{i+1:02d}.wav" for i in range(len(blocks))] voiced = a.resume and all((vo / f).exists() and ((vo / f).with_suffix(".words.json").exists() or not timed) for f in wavs) # the synthesis loops' own test - if not voiced and a.provider in ("elevenlabs", "dashscope", "gemini", "gemini-lite") and not keys.get(KEY_OF[a.provider].split()[0]): + if not voiced and a.provider in ("elevenlabs", "dashscope", "gemini", "gemini-lite") and not keys.get(KEY_OF[a.provider][0]): no_key(a.provider) # before anything is synthesized or deleted; --resume with all voiced needs none if a.provider == "minimax": minimax_settings() # a value out of range exits here, not mid-run diff --git a/tools/desk/README.md b/tools/desk/README.md index 7e927efb..e17ff5eb 100644 --- a/tools/desk/README.md +++ b/tools/desk/README.md @@ -325,7 +325,7 @@ JSON 的格式: 下面这些命令加了 `--json`,失败时 stdout 是一行 `{"version": 1, "error": {"code", "message", "hint"}}`,给人看的那一行照旧在 stderr,退出码和不加 `--json` 时一样:`status`、`activity`、`versions`、`check`、`assets`、`edit`、`proxy`、`thumbs`、`peaks`、`artifacts`、`projects`、`cancel`、`history`、`timeline --resolved`、`commands`、`doctor`、`desk data`(它总是 JSON)、`gate`、`new`,连同 `bin/vh` 自己在 Python 起来之前发现的(打错的命令、`--json` 时没有 python3,退出码 127)。 -`code` 是稳定的,按它分支,别按文字:`usage`(参数错)、`no_project`(没有这个项目,或者这个文件夹不是)、`not_found`(项目在,它说的文件、片子、版本、run 不在)、`invalid`(文件在,读不成它该是的样子:不是 JSON、不合 schema、还有占位)、`exists`(要写的东西已经有了)、`refused`(规矩不让:页面犯了规)、`missing_tool`(少一个程序)、`timeout`(等到头了)、`failed`(别的)。`hint` 有话说时是一句接下来怎么办,否则 `null`。 +`code` 是稳定的,按它分支,别按文字:`usage`(参数错)、`no_project`(没有这个项目,或者这个文件夹不是)、`not_found`(项目在,它说的文件、片子、版本、run 不在)、`invalid`(文件在,读不成它该是的样子:不是 JSON、不合 schema、还有占位)、`exists`(要写的东西已经有了)、`refused`(规矩不让:页面犯了规)、`missing_tool`(少一个程序)、`no_key`(一家服务的 API Key 没设:说哪一家、去设置 → 服务里填,片子等着它时 `bin/vh status` 和 Studio 也这么说)、`timeout`(等到头了)、`failed`(别的)。`hint` 有话说时是一句接下来怎么办,否则 `null`。 几种记录有自己的字段,不是这个形状:`bin/vh check --json` 读不了片子时打它的记录,`error` 是字符串,退出码 1(这是对这支片子的判决);`bin/vh doctor --json` 没有 python3 时 `error` 也是字符串,退出码 0;清单和检查(`artifacts list --strict`、`assets check`、`edit check`)退出码 1 时打它们的记录。所以先看 `error` 是不是对象。 @@ -384,7 +384,7 @@ JSON 的格式: - `state` 七种:`done`(REVIEW.md 里有它的"定了":先看关于最新那一页的最后一节,审阅台为提交写的那节、或写了 `gate-.html` 的那节,模板的三节都预先写了;没有这种节,就看这一站自己的节,而且 REVIEW.md 要晚于这一页,`note` 里会说是按日期算的。关卡 ① 和 `bin/vh render`、`check` 用同一条规则(`tools/gatecheck.py`):关卡 ① 的节里有定了和人的原话;`record` 另有 `concept_on_record`、`concept_from`(`REVIEW.md`,或者老项目 DECISIONS.md 里立意那一行)和 `concept`(关卡 ① 定了那一行的原文:写的是哪张卡就是哪张卡,只写"通过"就是"通过"))、`skipped`(quick 档:这一站没有自己的页面,Director 也没要它(`stop=`、`x=own`);或者 REVIEW.md 里有用户原话授权跳过)、`waiting_person`(这一页发出去了(`bin/vh gate` 出的页面:写好还没发的 gate JSON 不算,上一次被 `bin/vh gate` 拒绝、退出码 1 的也不算,那一次什么都没发给人),是这一轮(`out/review/.current`),还没有回音)、`waiting_agent`(人提交了还没交给 agent,或者交了但 REVIEW.md 还没写定了;或者这一轮已经往后走、这一页没有记录;或者关卡 ① 定了,但缺人的原话,render 和 check 会拒绝)、`in_progress`(前面都过了,agent 正朝这一站做)、`not_started`、`no_record`(standard、studio 的项目没有 REVIEW.md,模板有它之前做的:无从读起,gatecheck 也不查)。交付:`bin/vh deliver` 写过记录,或成片(`out/final*`、`out/final/`、直接放在 `media/` 下的文件、Manim 1080p 及以上的渲染;不含它 480p15、720p30 的草稿,也不含 `bin/vh patch` 留下的 `.failed`)有一份通过的检查记录、而且就是这支成片的(记录里的 `size` 和 `mtime_ns` 和它现在的一样;没有这两个字段的老记录,要比它晚),而且关卡 ③ 过了(`done` 或 `skipped`),就是 `done`;关卡 ③ 还没过时 `note` 会说;各站都过了是 `in_progress`;没有 REVIEW.md 是 `no_record`。 - `waiting_on`:`person`、`agent`、`nobody`(交付了)或 `unknown`(没有 REVIEW.md,又没有命令在跑);REVIEW.md 写了暂停(`paused: true`)也是 `person`。机器写的记录(检查记录、`.render.json`、`.deliver.json`、审阅台的提交)里类型不对的字段当作没有。`next`:一句话,谁下一步做什么。 - `next_step`:下一步,按项目停在哪一站算出来:`who`(`person`、`agent`、`nobody`、`unknown`)、`do`(一句话,还没填的 `{…}` 和 gate 骨架里的占位有几处都说出来;Director 写了 `x=own`、还没有记录的事排在最前面,记录是它那一站过了,或者 DECISIONS.md 里它那一行写了已定)、`commands`(能直接跑的命令,`` 这类尖括号是要换的)、`read`(该读的:`<文件>#<节>` 由 `bin/vh know --show` 打印,没有 `#` 的整篇读)、`unfilled`(`BRIEF.md`、`STYLE.md`、`STORYBOARD.md` 各还有几处 `{…}`,不算代码块和行内代码里的,也不算模板的 `{none}` 和 `{fill: #e33}` 这种带值的花括号;交付以后 `who` 是 `nobody`,这里是空的,没有要填的了)。 -- `now`:这支片子现在怎么样,说给人听的(`tools/standing.py`,Studio 说的也是这些字;字都在它开头的 `WORDS` 表里,中英文挨着)。只说磁盘能证明的:最后记下的事和它在什么时候(命令的开始和结束、交出的意见、Studio 对话的事件、片子自己文件的改动)、现在有没有进程在跑、等着的进程和它等的 agent 活不活着、Studio 的一轮怎么结束的、一条命令是在哪个 agent 程序下跑的(那个 agent 还活着,就是有 agent 开着这支片子)。磁盘不知道 agent 是不是正在两条命令之间想事情,所以安静的片子只说"上一次动静:12 分钟前,渲染做完了",从不说没人在做;"停下了"要有正面的证据;"让 agent 接着做"是一个可以点的选项,不是"没人在做"的断言。字段:`code`、`who`(下一步该谁动,和 `waiting_on` 一致)、`you`(人跟它有什么事:`decide` 在等人定,`nudge` 要人说一声,`offer` 人可以点,`none`)、`tone`(点的颜色:`you` 琥珀、`busy` 紫、`quiet` 灰)、`say`(`{zh, en}` 一句短话,两秒读完)、`more`(`{zh, en}` 或 `null`:下面那一行)、`short`(`{zh, en}` 卡片上的几个字,不带路径,也不带不在词表里的命令名)、`act`(至多一件事:`{kind: "open", mod, sub, label}` 去 Studio 的哪个模块;`{kind: "tell", label, text, confirm, secondary}` 对 agent 说的那句话,`confirm` 是先问一次(最近 30 分钟里还有动静,或者有 agent 开着),`secondary` 是它不是主要该做的事、写成第二行的小字;`{kind: "none"}`)、`facts`(`paths`:这些话里点到的项目文件,Studio 里点得开;还有 `stop`、`listening`、`pending`、`cmd`、`film`、`subtitles`、`version` 这些)。 +- `now`:这支片子现在怎么样,说给人听的(`tools/standing.py`,Studio 说的也是这些字;字都在它开头的 `WORDS` 表里,中英文挨着)。只说磁盘能证明的:最后记下的事和它在什么时候(命令的开始和结束、交出的意见、Studio 对话的事件、片子自己文件的改动)、现在有没有进程在跑、等着的进程和它等的 agent 活不活着、Studio 的一轮怎么结束的、一条命令是在哪个 agent 程序下跑的(那个 agent 还活着,就是有 agent 开着这支片子)。磁盘不知道 agent 是不是正在两条命令之间想事情,所以安静的片子只说"上一次动静:12 分钟前,渲染做完了",从不说没人在做;"停下了"要有正面的证据;"让 agent 接着做"是一个可以点的选项,不是"没人在做"的断言。字段:`code`、`who`(下一步该谁动,和 `waiting_on` 一致)、`you`(人跟它有什么事:`decide` 在等人定,`nudge` 要人说一声,`offer` 人可以点,`none`)、`tone`(点的颜色:`you` 琥珀、`busy` 紫、`quiet` 灰)、`say`(`{zh, en}` 一句短话,两秒读完)、`more`(`{zh, en}` 或 `null`:下面那一行)、`short`(`{zh, en}` 卡片上的几个字,不带路径,也不带不在词表里的命令名)、`act`(至多一件事:`{kind: "open", mod, sub, label}` 去 Studio 的哪个模块;`{kind: "settings", sub, label}` 去设置页的哪一节(片子等一家服务的 API Key 时:`code` 是 `needs_key`,`facts.keys` 是还没设的 key 名,`facts.service` 是哪一家;有一个设上了、或者那条命令再跑一次没为它停,就不再这么说);`{kind: "tell", label, text, confirm, secondary}` 对 agent 说的那句话,`confirm` 是先问一次(最近 30 分钟里还有动静,或者有 agent 开着),`secondary` 是它不是主要该做的事、写成第二行的小字;`{kind: "none"}`)、`facts`(`paths`:这些话里点到的项目文件,Studio 里点得开;还有 `stop`、`listening`、`pending`、`cmd`、`film`、`subtitles`、`version`、`keys`、`service` 这些)。 `code` 按这个先后取第一个对上的:`paused`(REVIEW.md 写了暂停);`revision_ready`(有一条复审等人看);`waiting_you`(一站的页发出去了等人:`facts.listening` 按上面 `.listening` 的三样算,真就"你交了,agent 就接着做",不然"交了以后,要跟 agent 说一声";声音那一站是"等你听");最新的一份意见还没人取时,不管别的在不在跑都先说它:等着的人活着是 `notes_sent`,不然 `notes_unheard`(有命令在跑时写"渲染还在跑,但你 21:30 交的这一份没人取");`notes_taken`(意见交到 agent 手里了,而且这会儿真有东西在为这支片子做:`bin/vh` 命令在跑,或 Studio 的一个对话拿着锁;没东西在跑时不说"正在改");`running`(`bin/vh` 命令在跑,带进度;pid 被后来的进程占去的不算在跑);`working`(Studio 的一个对话拿着锁,锁的 pid 也照这样核对);`delivered`(最新的一份交付记录:哪支成片、旁边的字幕、`versions` 里正好是它的那一版);`no_record`;然后是轮到 agent、现在没东西在跑的几种。先把所有动静排一遍(结束了的命令:做完了、结束时报了问题、被停下了、中断了;发出的审阅页;开始等你的意见;它取走了你的意见;Studio 对话的最后一件事;片子自己的文件里最新改的那个:先看片子的文件夹,再一层层往下(广度优先,四层),不看 `out/`、`media/`、`renders/` 和 Studio 自己写的 `REVIEW.md`;`assets/`、`audio/`、帧序列这种重的文件夹(按名字,或者一个文件夹里超过 300 项)只看文件夹自己的时间,不一个个看;看到 4000 项还没看完就停,这时说的是"看到的最近一次动静","之后没有别的动静"这种话不说),取最新的那一件:它是一条没有结束记录、进程也没了的命令,或者 Studio 的一轮被停下、出错、做到一半断了,而且没有 agent 开着,才是 `stopped`("agent 停下了:渲染中断了。",下面一行是什么时候、到第几帧、之后没有别的动静、下一站);做这支片子的 agent 还开着,是 `agent_open`("现在没有命令在跑;上次做这支片子的 agent 还开着。","让 agent 接着做"降成第二行、点之前先问一次):只在这个 agent 程序最近一次做的就是这支片子,或者这支片子最新的动静在 6 小时以内时这么说;一个开了很久、做过许多支片子的程序(比如 Studio 那一列背后的那个)不让它做过的每支片子都显得"开着",那些片子照常说它们自己的情况,再加一句"做过它的 agent 程序还开着,可能在忙别的片子。";各站都过了还没交付是 `ship_missing`;下一步是装引擎是 `setup`;其余是 `idle`("现在没有命令在跑。",下面一行"上一次动静:……")。一条命令出错结束(`check` 没过、`gate` 拒绝)是它的结果,不是停下了:写成"上一次动静:3 分钟前,检查查出 2 处要改",下一步还是 agent 的。 diff --git a/tools/desk/static/studio.js b/tools/desk/static/studio.js index c32abdb5..f9691893 100644 --- a/tools/desk/static/studio.js +++ b/tools/desk/static/studio.js @@ -479,6 +479,7 @@ function renderNow() { // where this film stands, in bin/vh status's own sente const armed = a.kind === "tell" && a.confirm && NOWARM === PKEY; // an offer that asks once more: the first click arms it const quiet = a.secondary && !armed, cls = quiet ? "btn btn-quiet xs now-second" : a.secondary ? "btn" : "btn btn-primary"; // a second line, or the one thing to do const btn = a.kind === "tell" ? `${armed ? `` : ""}` + : a.kind === "settings" ? `${esc(a.label[L])}` // only the person can give it (an API Key): the settings page's section : mod && mod !== MOD ? `${esc(a.label[L])} →` : ""; // already on that page: no button to it const opens = (txt) => ((n.facts || {}).paths || []).reduce((h, p) => h.split(esc(p)).join(`${esc(p)}`), esc(txt)); // a file the words name opens const html = `

    ${esc(n.say[L])}

    ${n.more ? `

    ${opens(n.more[L])}

    ` : ""}${armed ? `

    ${esc(t("now_sure_note"))}

    ` : ""}${btn ? `
    ${btn}
    ` : ""}${plan ? `

    ${esc(plan[L])}

    ` : ""}`; diff --git a/tools/desk/test_agents.py b/tools/desk/test_agents.py index 6a6eff09..6fd1f98b 100644 --- a/tools/desk/test_agents.py +++ b/tools/desk/test_agents.py @@ -1901,6 +1901,22 @@ def unit(): # the order of what is said, and what each sentence never claims, pending_busy = one(stations=both_, activity={"running": [render]}) taken = one(stations=handed, activity={"running": [render]}) unknown = one(activity={"running": [{"cmd": "foo-bar"}]}) + import keys # a film waiting on a service's API Key: on no store of anyone's, with no key in the environment + kept = {k: os.environ.pop(k) for k in [*keys.KEY_NAMES, "OVH_KEYSTORE"] if k in os.environ} + os.environ["OVH_KEYSTORE"] = "none"; keys._CACHE.pop("kind", None); keys.forget() + try: + nk = lambda cmd, names, t=now - 90: {"cmd": cmd, "state": "failed", "exit": 1, "start": t - 10, "end": t, "error": {"code": "no_key", "message": keys.missing(names)}} # noqa: E731 + ok = lambda cmd, t: {"cmd": cmd, "state": "ok", "exit": 0, "start": t - 10, "end": t} # noqa: E731 + key_tts = one(activity={"recent": [nk("tts", "GEMINI_API_KEY")]}) + key_mm = one(activity={"recent": [nk("tts", ["MINIMAX_TOKEN_PLAN_KEY", "MINIMAX_API_KEY"])]}) + key_image = one(activity={"recent": [nk("image", "GEMINI_API_KEY"), ok("render", now - 30)]}) # another command after it: still waiting + key_again = one(activity={"recent": [nk("tts", "GEMINI_API_KEY"), ok("tts", now - 30)]}) # the same command again, fine: no more + key_old_way = one(activity={"recent": [{"cmd": "tts", "state": "failed", "exit": 1, "start": now - 100, "end": now - 90, "error": {"code": "failed", "message": "set GEMINI_API_KEY"}}]}) + os.environ["GEMINI_API_KEY"] = "madeUpForThisCheck1" + key_set = one(activity={"recent": [nk("tts", "GEMINI_API_KEY")]}) + del os.environ["GEMINI_API_KEY"] + finally: + os.environ.pop("OVH_KEYSTORE", None); os.environ.update(kept); keys._CACHE.pop("kind", None); keys.forget() got = { "paused": one(paused=True)["code"], "revision": one(review={"revisions": [{"state": "pending", "available": True}]})["code"], "setup": one(next_step={"do": "the engine's scaffold is not there: this makes it"})["code"], "idle": one()["code"], @@ -1932,6 +1948,11 @@ def unit(): # the order of what is said, and what each sentence never claims, for v in ("TTS voice, no music", "Charon, 不要背景音乐", "none (music only)")], "short": all(not any(x in json.dumps(y["short"]) for x in ("/", ".mp4", "bin/vh")) for y in (gone, found, taken, unknown)), "ago": ["3 天", "2 小时"], + "key_tts": [key_tts["code"], key_tts["you"], key_tts["tone"], key_tts["say"], key_tts["more"]["zh"], key_tts["short"]["zh"], key_tts["act"], + key_tts["facts"]["keys"], key_tts["facts"]["service"]], + "key_mm": [key_mm["say"]["en"], key_mm["facts"]["keys"]], + "key_image": [key_image["say"]["zh"], key_image["more"]["en"]], + "key_gone": [key_again["code"], key_set["code"], key_old_way["code"]], } want = {"paused": "paused", "revision": "revision_ready", "setup": "setup", "idle": "idle", "running": "正在配音,12 / 30 句。", "gone": ["stopped", "agent 停下了:渲染中断了。", "nudge", False], @@ -1949,13 +1970,20 @@ def unit(): # the order of what is said, and what each sentence never claims, "plan_music": {"zh": "2 分 30 秒横屏,没有旁白,停在立意、定声音、初版", "en": "2 min 30 s landscape, no narration, it stops at the concept, the final sound, the first draft"}, "plan_cn": {"zh": "没有旁白,中间不停,做完给你看", "en": "No narration, no stops on the way: you see it finished"}, "plan_odd": {"zh": "立意、分镜、初版都给你看", "en": "You see the concept, the storyboard and the first draft"}, "short": True, - "plan_voice": ["有旁白", "有旁白", "没有旁白"], "ago": [standing.ago(2.99 * 86400)[0], standing.ago(100 * 60)[0]]} + "plan_voice": ["有旁白", "有旁白", "没有旁白"], "ago": [standing.ago(2.99 * 86400)[0], standing.ago(100 * 60)[0]], + "key_tts": ["needs_key", "decide", "you", {"zh": "配音停下了:还没有 Gemini 的 API Key。", "en": "The voice-over stopped: there's no Gemini API Key yet."}, + "在设置 → 服务里填上,再让 agent 接着做。不想用在线服务,也可以让 agent 换成这台电脑上的声音。", "等 API Key", + {"kind": "settings", "mod": None, "sub": "services", "label": {"zh": "去设置 → 服务", "en": "Open Settings → Services"}}, ["GEMINI_API_KEY"], "gemini"], + "key_mm": ["The voice-over stopped: there's no MiniMax API Key yet.", ["MINIMAX_TOKEN_PLAN_KEY", "MINIMAX_API_KEY"]], + "key_image": ["出图停下了:还没有 Gemini 的 API Key。", "Set it up in Settings → Services, then ask the agent to carry on."], + "key_gone": ["idle", "idle", "idle"]} return None if got == want else {k: v for k, v in got.items() if want.get(k) != v} check("what each state never says falsely: a run cut off with nothing after it is the only command that stops the agent (a finished run with " "findings, one stopped on purpose, a later run that went fine, the console ending, are not); the newest notes nobody took come first; " "working on them only while something runs; never that nobody works on the film; whose move as waiting_on; a command not in the table " "is no name on the page; the final sound is listened to and the sound plan looked at, plurals agree; the plan says what the BRIEF says plainly (none (music only), 2 min 30 s, " - "a checkpoint) and leaves out what it does not", unit) + "a checkpoint) and leaves out what it does not; a command that stopped for a service's API Key says so, what to do and where (Settings → Services), " + "until the key is set or the same command ran again without stopping for it", unit) def title(): # a film begun on the space, its BRIEF still the template's: the person's own sentence, shortened, not the dated folder import server diff --git a/tools/desk/test_settings.py b/tools/desk/test_settings.py index e8988c01..9fb17cdc 100644 --- a/tools/desk/test_settings.py +++ b/tools/desk/test_settings.py @@ -526,6 +526,46 @@ def column_check(): return None if r.returncode == 0 else "not found in the column's environment" +def first_run_check(): + """A film whose voice-over stopped for want of Gemini's API Key: the command says the one sentence (where to set it, where + to get one, what works without), its record has the code no_key, and bin/vh status says the film waits on the key, with + the way to Settings → Services; once the key is saved in Studio, it says so no more. (No call is made: the check comes + first, and the store is these checks' own.)""" + if not shutil.which("uv"): + return None + film = T / "first-run" + shutil.rmtree(film, ignore_errors=True) + shutil.copytree(HERE / "fixtures" / "demo", film) + (film / "audio" / "script.txt").write_text("你好,这是一句试音。\n", encoding="utf-8") + env = dict(ENV, OVH_ACTIVITY_AGENT="0") + vh = lambda *a: subprocess.run(["bash", str(ROOT / "bin" / "vh"), *a], env=env, capture_output=True, text=True, timeout=180) # noqa: E731 + rc, out = py("import keys as K\nK.clear('GEMINI_API_KEY')") + if rc: + return out[-300:] + r = vh("tts", str(film), "gemini") + if r.returncode != 1 or "Studio's Settings → Services" not in r.stderr or "GEMINI_API_KEY" not in r.stderr or "aistudio.google.com" not in r.stderr: + return f"bin/vh tts gemini with no key: exit {r.returncode}, {r.stderr[-300:]!r}" + if list((film / "audio").glob("voiceover*")): + return "something was voiced" + notes = [json.loads(x) for x in (film / ".ovh" / "activity.jsonl").read_text().splitlines() if '"note"' in x] + if not any(n.get("level") == "error" and n.get("code") == "no_key" for n in notes): + return f"the run's record: {notes[-1:]}" + now = json.loads(vh("status", str(film), "--json").stdout)["now"] + if now["code"] != "needs_key" or now["act"].get("kind") != "settings" or now["act"].get("sub") != "services" or now["facts"].get("keys") != ["GEMINI_API_KEY"]: + return f"bin/vh status while the film waits: {now['code']} {now['act']}" + if "now: The voice-over stopped: there's no Gemini API Key yet." not in vh("status", str(film)).stdout: + return "bin/vh status's now: line" + rc, out = py(f"import keys as K\nK.save('GEMINI_API_KEY', {FAKE!r})") + try: + if rc: + return out[-300:] + now = json.loads(vh("status", str(film), "--json").stdout)["now"] + if now["code"] == "needs_key": + return "the key saved in Studio, and the film is still said to wait on it" + finally: + py("import keys as K\nK.clear('GEMINI_API_KEY')") + + def words_check(): src = (HERE / "static" / "settings.js").read_text(encoding="utf-8") zh = src[src.index(" zh: {"):src.index(" en: {")] @@ -545,6 +585,7 @@ def words_check(): check("tools/keys.py on a store of these checks' own: saved, found, the environment first, taken out; what is not a key or a key's name refused; the store asked once per name (a missing key and a store with no answer too), a save or removal seen at once" + ("" if MAC else "; the key never an argument"), keys_module_check) check("bin/vh doctor finds a key saved in Studio, says so, and probes with it (a recording), with each of MiniMax's two when both are saved, never printing one", doctor_keys_check) check("a command run in the agent column's environment (no key in it) finds a key saved in Studio", column_check) + check("a voice-over with no key: the command says where to set it and where to get one (code no_key on its record); bin/vh status says the film waits on the key, with the way to Settings → Services, and no more once it is saved", first_run_check) run() except Exception as e: say(False, "the console for the settings page", f"{type(e).__name__}: {e}") diff --git a/tools/jsonerr.py b/tools/jsonerr.py index aaad3039..a1f7dd42 100644 --- a/tools/jsonerr.py +++ b/tools/jsonerr.py @@ -15,6 +15,7 @@ exists what it would make is there already refused a rule says no: a page that breaks one, a render before gate ① is on record missing_tool a program it needs is not installed (the hint says which way to get it) + no_key a service's API Key is not set (tools/keys.py says which and where; bin/vh status says it while the film waits) timeout it waited as long as it was told to failed anything else that went wrong while it worked (exit 1 as a rule) A record the command prints of its own stays as it is: bin/vh check --json on a film it cannot read, bin/vh doctor --json diff --git a/tools/keys.py b/tools/keys.py index aeefab46..424bd44f 100644 --- a/tools/keys.py +++ b/tools/keys.py @@ -5,6 +5,11 @@ A key never goes into a file, a log, a URL, an event or the page, and never onto a command line (where the process list shows it): it is written to the store through standard input. Only names in KEY_NAMES are read or written here. +A command that stops because a key is missing says one sentence, the same everywhere (missing()): which service and key, +where to set it (Studio's Settings → Services, or the environment), where to get one, and what works with none; stopping() +also puts it on the run's record with the code no_key (tools/jsonerr.py), which bin/vh status and Studio say while the +film waits on that key (tools/standing.py). + usage: python3 tools/keys.py has exit 0 when a command would find that key (environment or store), else 1 python3 tools/keys.py where each name: env, studio or -, and what kind of store this computer has (there is no command that prints a key) @@ -176,6 +181,48 @@ def clear(name): raise NotKept(f"{name} is still saved ({kind} did not take it out)") +SERVICE = {"gemini": "Gemini", "minimax": "MiniMax", "elevenlabs": "ElevenLabs", "dashscope": "Alibaba Cloud Model Studio"} # as Studio's page names them + + +def module_of(name): + """tools/modules.json's service whose keys include this name, or None.""" + try: + t = json.loads((ROOT / "tools" / "modules.json").read_text(encoding="utf-8")) + except (OSError, ValueError): + return None + return next((m for m in t.get("modules") or [] if name in ((m.get("needs") or {}).get("keys") or [])), None) + + +def missing(names, instead=None): + """The sentence for a command that stops because none of these keys (one service's) is set.""" + names = [names] if isinstance(names, str) else list(names) + m = module_of(names[0]) or {} + said = " or ".join(names) + s = f"no {SERVICE.get(m.get('name'), m.get('name') or 'service')} API Key ({said}): paste one into Studio's Settings → Services" + if m.get("key_url"): + s += f" (get one at {m['key_url']})" + s += f", or set {said} in the environment" + return s + (f"; {instead}" if instead else "") + + +def stopping(names, instead=None): + """missing(), put on the run's record with the code no_key (once a run; nothing outside a logged run): → the sentence, + for the caller to print and stop with.""" + msg = missing(names, instead) + try: + import jsonerr + jsonerr.report("no_key", msg, "Studio's Settings → Services takes the key") + except Exception: # the sentence is said all the same + pass + return msg + + +def wanted(names): + """The key names a no_key message names that are still not set: [] once any of them is (the film waits no more).""" + names = [n for n in names if n in KEY_NAMES] + return [] if any(get(n) for n in names) else names + + def main(argv): if argv[:1] in (["-h"], ["--help"]) or not argv: print(__doc__.strip()); return 0 if argv else 2 diff --git a/tools/schemas/output/error.schema.json b/tools/schemas/output/error.schema.json index 0fd9c3f5..430dfce6 100644 --- a/tools/schemas/output/error.schema.json +++ b/tools/schemas/output/error.schema.json @@ -11,7 +11,7 @@ "type": "object", "required": ["code", "message", "hint"], "properties": { - "code": {"enum": ["usage", "no_project", "not_found", "invalid", "exists", "refused", "missing_tool", "timeout", "failed"]}, + "code": {"enum": ["usage", "no_project", "not_found", "invalid", "exists", "refused", "missing_tool", "no_key", "timeout", "failed"]}, "message": {"type": "string"}, "hint": {"type": ["string", "null"]} } diff --git a/tools/schemas/output/projects.schema.json b/tools/schemas/output/projects.schema.json index 7d3430f8..ed8b9e20 100644 --- a/tools/schemas/output/projects.schema.json +++ b/tools/schemas/output/projects.schema.json @@ -95,7 +95,7 @@ }, "$defs": { "words": {"type": "object", "required": ["zh", "en"], "properties": {"zh": {"type": "string"}, "en": {"type": "string"}}}, - "now": {"description": "Where the film stands for the person, in a sentence, and the one thing to do (tools/standing.py): what Studio says too", "type": ["object", "null"], "required": ["code", "who", "you", "tone", "say", "more", "short", "act", "facts"], "properties": {"code": {"enum": ["paused", "revision_ready", "waiting_you", "notes_unheard", "notes_sent", "notes_taken", "running", "working", "delivered", "no_record", "stopped", "agent_open", "ship_missing", "setup", "idle", "unknown"]}, "who": {"enum": ["person", "agent", "nobody", "unknown"]}, "say": {"$ref": "#/$defs/words"}, "more": {"anyOf": [{"type": "null"}, {"$ref": "#/$defs/words"}]}, "short": {"$ref": "#/$defs/words"}, "act": {"type": "object", "required": ["kind"], "properties": {"kind": {"enum": ["open", "tell", "none"]}, "mod": {"type": "string"}, "sub": {"type": ["string", "null"]}, "label": {"$ref": "#/$defs/words"}, "text": {"$ref": "#/$defs/words"}, "confirm": {"type": "boolean"}, "secondary": {"type": "boolean"}}}, "facts": {"type": "object", "properties": {"paths": {"type": "array", "items": {"type": "string"}}, "stop": {"type": "string"}, "listening": {"type": "boolean"}, "pending": {"type": "integer"}, "revisions": {"type": "integer"}, "cmd": {"type": ["string", "null"]}, "film": {"type": ["string", "null"]}, "subtitles": {"type": "array", "items": {"type": "string"}}, "version": {"type": ["string", "null"]}}}, "you": {"enum": ["decide", "nudge", "offer", "none"]}, "tone": {"enum": ["you", "busy", "quiet"]}}}, + "now": {"description": "Where the film stands for the person, in a sentence, and the one thing to do (tools/standing.py): what Studio says too", "type": ["object", "null"], "required": ["code", "who", "you", "tone", "say", "more", "short", "act", "facts"], "properties": {"code": {"enum": ["paused", "revision_ready", "waiting_you", "notes_unheard", "notes_sent", "notes_taken", "running", "working", "delivered", "no_record", "stopped", "agent_open", "ship_missing", "setup", "needs_key", "idle", "unknown"]}, "who": {"enum": ["person", "agent", "nobody", "unknown"]}, "say": {"$ref": "#/$defs/words"}, "more": {"anyOf": [{"type": "null"}, {"$ref": "#/$defs/words"}]}, "short": {"$ref": "#/$defs/words"}, "act": {"type": "object", "required": ["kind"], "properties": {"kind": {"enum": ["open", "tell", "settings", "none"]}, "mod": {"type": ["string", "null"]}, "sub": {"type": ["string", "null"]}, "label": {"$ref": "#/$defs/words"}, "text": {"$ref": "#/$defs/words"}, "confirm": {"type": "boolean"}, "secondary": {"type": "boolean"}}}, "facts": {"type": "object", "properties": {"paths": {"type": "array", "items": {"type": "string"}}, "stop": {"type": "string"}, "listening": {"type": "boolean"}, "pending": {"type": "integer"}, "revisions": {"type": "integer"}, "cmd": {"type": ["string", "null"]}, "film": {"type": ["string", "null"]}, "subtitles": {"type": "array", "items": {"type": "string"}}, "version": {"type": ["string", "null"]}, "keys": {"type": "array", "items": {"type": "string"}}, "service": {"type": ["string", "null"]}}}, "you": {"enum": ["decide", "nudge", "offer", "none"]}, "tone": {"enum": ["you", "busy", "quiet"]}}}, "plan": {"description": "The film in a line from its BRIEF and its stops", "anyOf": [{"type": "null"}, {"$ref": "#/$defs/words"}]} } } diff --git a/tools/schemas/output/status.schema.json b/tools/schemas/output/status.schema.json index 5cc8b656..60867a61 100644 --- a/tools/schemas/output/status.schema.json +++ b/tools/schemas/output/status.schema.json @@ -254,7 +254,7 @@ }, "$defs": { "words": {"type": "object", "required": ["zh", "en"], "properties": {"zh": {"type": "string"}, "en": {"type": "string"}}}, - "now": {"description": "Where the film stands for the person, in a sentence, and the one thing to do (tools/standing.py): what Studio says too", "type": ["object", "null"], "required": ["code", "who", "you", "tone", "say", "more", "short", "act", "facts"], "properties": {"code": {"enum": ["paused", "revision_ready", "waiting_you", "notes_unheard", "notes_sent", "notes_taken", "running", "working", "delivered", "no_record", "stopped", "agent_open", "ship_missing", "setup", "idle", "unknown"]}, "who": {"enum": ["person", "agent", "nobody", "unknown"]}, "say": {"$ref": "#/$defs/words"}, "more": {"anyOf": [{"type": "null"}, {"$ref": "#/$defs/words"}]}, "short": {"$ref": "#/$defs/words"}, "act": {"type": "object", "required": ["kind"], "properties": {"kind": {"enum": ["open", "tell", "none"]}, "mod": {"type": "string"}, "sub": {"type": ["string", "null"]}, "label": {"$ref": "#/$defs/words"}, "text": {"$ref": "#/$defs/words"}, "confirm": {"type": "boolean"}, "secondary": {"type": "boolean"}}}, "facts": {"type": "object", "properties": {"paths": {"type": "array", "items": {"type": "string"}}, "stop": {"type": "string"}, "listening": {"type": "boolean"}, "pending": {"type": "integer"}, "revisions": {"type": "integer"}, "cmd": {"type": ["string", "null"]}, "film": {"type": ["string", "null"]}, "subtitles": {"type": "array", "items": {"type": "string"}}, "version": {"type": ["string", "null"]}}}, "you": {"enum": ["decide", "nudge", "offer", "none"]}, "tone": {"enum": ["you", "busy", "quiet"]}}}, + "now": {"description": "Where the film stands for the person, in a sentence, and the one thing to do (tools/standing.py): what Studio says too", "type": ["object", "null"], "required": ["code", "who", "you", "tone", "say", "more", "short", "act", "facts"], "properties": {"code": {"enum": ["paused", "revision_ready", "waiting_you", "notes_unheard", "notes_sent", "notes_taken", "running", "working", "delivered", "no_record", "stopped", "agent_open", "ship_missing", "setup", "needs_key", "idle", "unknown"]}, "who": {"enum": ["person", "agent", "nobody", "unknown"]}, "say": {"$ref": "#/$defs/words"}, "more": {"anyOf": [{"type": "null"}, {"$ref": "#/$defs/words"}]}, "short": {"$ref": "#/$defs/words"}, "act": {"type": "object", "required": ["kind"], "properties": {"kind": {"enum": ["open", "tell", "settings", "none"]}, "mod": {"type": ["string", "null"]}, "sub": {"type": ["string", "null"]}, "label": {"$ref": "#/$defs/words"}, "text": {"$ref": "#/$defs/words"}, "confirm": {"type": "boolean"}, "secondary": {"type": "boolean"}}}, "facts": {"type": "object", "properties": {"paths": {"type": "array", "items": {"type": "string"}}, "stop": {"type": "string"}, "listening": {"type": "boolean"}, "pending": {"type": "integer"}, "revisions": {"type": "integer"}, "cmd": {"type": ["string", "null"]}, "film": {"type": ["string", "null"]}, "subtitles": {"type": "array", "items": {"type": "string"}}, "version": {"type": ["string", "null"]}, "keys": {"type": "array", "items": {"type": "string"}}, "service": {"type": ["string", "null"]}}}, "you": {"enum": ["decide", "nudge", "offer", "none"]}, "tone": {"enum": ["you", "busy", "quiet"]}}}, "plan": {"description": "The film in a line from its BRIEF and its stops", "anyOf": [{"type": "null"}, {"$ref": "#/$defs/words"}]}, "run": { "type": "object", diff --git a/tools/standing.py b/tools/standing.py index b96847fd..5c450929 100644 --- a/tools/standing.py +++ b/tools/standing.py @@ -59,7 +59,7 @@ "cmd.captions": ("做字幕", "making the subtitles", "the subtitles"), "cmd.cues": ("对时间", "lining up the timing", "the timing"), "cmd.readcheck": ("查字停得够不够久", "checking the words stay long enough to read", "the reading-time check"), "cmd.textcheck": ("查画面文字", "checking the text on screen", "the text check"), "cmd.timeline": ("排时间线", "laying out the timeline", "the timeline"), "cmd.peaks": ("画波形", "drawing the waveform", "the waveform"), - "cmd.bgm": ("配乐", "picking the music", "the music"), "cmd.voices": ("试听声音", "trying voices", "the voice trial"), + "cmd.bgm": ("配乐", "picking the music", "the music"), "cmd.voices": ("试听声音", "trying voices", "the voice trial"), "cmd.pace": ("调配音的快慢", "evening out the voice's pace", "the voice's pace"), "cmd.edit": ("排剪辑表", "laying out the edit", "the edit"), "cmd.footage": ("找素材", "finding footage", "the footage"), "cmd.rhythm": ("画节奏图", "drawing the rhythm chart", "the rhythm chart"), "cmd.beats": ("找节拍", "finding the beats", "the beats"), "cmd.determinism": ("查同一帧重渲是否一样", "checking a frame renders the same twice", "the same-frame check"), "cmd.hf": ("跑引擎", "running the engine", "the engine run"), @@ -124,6 +124,15 @@ "gap.cut": ("初版还没定", "the first draft is not decided yet"), "gap.check": ("成片没过检查", "the film has not passed its check"), "gap.final": ("正式版还没做好或还没检查", "the final is not made or not checked yet"), "setup": ("引擎还没装好。", "The engine is not set up yet."), + # a command stopped because a service's API Key is not set, and it still is not (tools/keys.py) + "needs_key": ("{x}停下了:还没有 {s} 的 API Key。", "{T} stopped: there's no {s} API Key yet."), + "needs_key.more": ("在设置 → 服务里填上,再让 agent 接着做。", "Set it up in Settings → Services, then ask the agent to carry on."), + "needs_key.voice": ("不想用在线服务,也可以让 agent 换成这台电脑上的声音。", "Or ask the agent to use this computer's own voice, with no service."), + "needs_key.timing": ("不想用在线服务,也可以让 agent 在这台电脑上对时间。", "Or ask the agent to time the words on this computer, with no service."), + "needs_key.music": ("不想用在线服务,也可以让 agent 在这台电脑上作曲。", "Or ask the agent to compose the music on this computer, with no service."), + "needs_key.short": ("等 API Key", "waiting for an API Key"), + "svc.gemini": ("Gemini", "Gemini"), "svc.minimax": ("MiniMax", "MiniMax"), "svc.elevenlabs": ("ElevenLabs", "ElevenLabs"), + "svc.dashscope": ("阿里云百炼", "Alibaba Cloud Model Studio"), "setup.more": ("agent 接着做时会先装它(要联网)。", "The agent sets it up first when it carries on (it needs the network)."), "setup.short": ("引擎还没装好", "engine not set up"), "unknown": ("读不出这支片子现在到哪了。", "Where this film stands could not be worked out."), "unknown.short": ("读不出", "unreadable"), @@ -133,6 +142,7 @@ "next": ("下一步是{s}。", "Next: {s}."), "next.notes": ("下一步:照你的意见改{s}。", "Next: {s}, changed as your notes say."), # the buttons, and the words a tell button sends (only these words, numbers and times: nothing else from the project) "act.look": ("去{v}{s}", "{V} {s}"), "act.revision": ("去复审", "Review the change"), "act.ship": ("打开交付", "Open the delivery"), + "act.settings": ("去设置 → 服务", "Open Settings → Services"), "act.go_cut": ("去看初版", "Go to the first draft"), "act.go_ship": ("去看交付", "Go to the delivery"), "act.carry": ("让 agent 接着做", "Ask the agent to carry on"), "act.fetch": ("让 agent 来看意见", "Ask the agent to read your notes"), "act.carry_open": ("它要是没反应,在这里叫一个 agent 接着做", "If it does not answer, ask an agent here to carry on"), @@ -434,6 +444,42 @@ def act_open(mod, label, sub=None): return {"kind": "open", "mod": mod, "sub": sub, "label": label} +def act_settings(label, sub): + return {"kind": "settings", "mod": None, "sub": sub, "label": label} + + +LOCAL_WAY = {"tts": "voice", "voices": "voice", "pace": "timing", "music": "music"} # what works on this computer instead, by command + + +def needs_key(o): + """The run that stopped for want of a service's API Key (its record's code no_key, tools/keys.py) while that key is + still not set, as the newest run of its command: (run, the key names it waits on, the service), or None. Once the key + is set (in Studio or the environment), or the command ran again and did not stop for it, the film waits no more.""" + newest = {} + for r in (o.get("activity") or {}).get("recent") or []: + if r.get("state") in ("running", "gone") or not r.get("cmd"): + continue + if (r.get("end") or 0) >= (newest.get(r["cmd"], {}).get("end") or 0): + newest[r["cmd"]] = r + hits = [r for r in newest.values() if r.get("exit") not in (0, None) and (r.get("error") or {}).get("code") == "no_key"] + if not hits: + return None + try: + import keys + except Exception: + return None + for r in sorted(hits, key=lambda x: x.get("end") or 0, reverse=True): + names = [n for n in keys.KEY_NAMES if re.search(r"\b" + n + r"\b", (r.get("error") or {}).get("message") or "")] + try: + left = keys.wanted(names) + except Exception: + left = [] + if left: + m = keys.module_of(left[0]) or {} + return r, left, m.get("name") + return None + + def act_tell(label, text, confirm=False, secondary=False): return {"kind": "tell", "label": label, "text": text, "confirm": bool(confirm), "secondary": bool(secondary)} @@ -529,6 +575,14 @@ def seen(s): paths=([film] if film and not gone else []) + subs, film=film, subtitles=subs, version=vid) if any(s["state"] == "no_record" for s in st): return say("no_record", who, "none", both("no_record"), [both("no_record.more")]) + nk = needs_key(o) + if nk: # only the person can give a key: what to do and where, and what works without one + r, names, svc = nk + c, sv = cmd_words(r), both(f"svc.{svc}") if f"svc.{svc}" in WORDS else two(svc or "", svc or "") + way = LOCAL_WAY.get(r.get("cmd")) + return say("needs_key", who, "decide", two(w("needs_key", 0, x=c[0], s=sv["zh"]), w("needs_key", 1, T=cap(c[2]), s=sv["en"])), + [both("needs_key.more"), both(f"needs_key.{way}") if way else None], both("needs_key.short"), + act_settings(both("act.settings"), "services"), cmd=r.get("cmd"), keys=names, service=svc) # the agent's move, and nothing works on the film now: the last thing seen and when; "stopped" only on positive evidence do = (o.get("next_step") or {}).get("do") or "" made = (o.get("media") or {}).get("film") or next((r["path"] for r in o.get("renders") or []), None) From 7d18d88e0f612dc5cba849934e413b651fdabf13 Mon Sep 17 00:00:00 2001 From: zhanglinghao Date: Sun, 22 Nov 2026 15:20:07 +0800 Subject: [PATCH 19/19] First-run guidance after review: Lyria's run ends, the line follows what the key was for and what this computer has, and it clears on a later run - lyria.py writes its run's end (bin/vh exec's into it): a stop for a key shows as one, and no Lyria run reads as cut off - the no_key record says what the key was for (voice, timing, music, image) and its names; the line under Studio's sentence follows it, not the command - what works with no key is per platform (Apple Silicon: the local voice and timing; an Intel Mac: macOS's say; Linux: none, said plainly), and Codex for pictures when it is there, in the command's words and in Studio's - a stop clears once a later run did the same kind of work fine, or a later run failed; read from the whole log (activity.key_stop), not the last five runs - the desk README: a key set only in a terminal's environment is not seen by a Studio opened elsewhere --- changes/settings-first-run.md | 5 +- tools/activity.py | 4 +- tools/assets/image.py | 2 +- tools/audio/lyria.py | 5 +- tools/audio/pace.py | 4 +- tools/audio/tts.py | 14 ++-- tools/desk/README.md | 2 +- tools/desk/test_agents.py | 56 ++++++++++++---- tools/desk/test_settings.py | 12 +++- tools/jsonerr.py | 12 ++-- tools/keys.py | 45 +++++++++++-- tools/schemas/output/activity.schema.json | 4 +- tools/schemas/output/projects.schema.json | 2 +- tools/schemas/output/status.schema.json | 5 +- tools/standing.py | 79 +++++++++++++++-------- tools/status.py | 2 +- 16 files changed, 181 insertions(+), 72 deletions(-) diff --git a/changes/settings-first-run.md b/changes/settings-first-run.md index 369a1b22..c390a21d 100644 --- a/changes/settings-first-run.md +++ b/changes/settings-first-run.md @@ -1,5 +1,6 @@ **少了 API Key 时,命令和 Studio 都用一句话说清去哪设、去哪拿、不用它还能怎么做** - Why: 配音、对时间、出图、作曲缺 key 时,原来各说各的("set GEMINI_API_KEY (Google AI Studio → Get API key)"),只说了环境变量;Studio 里只看得到"配音结束时报了问题",人不知道片子在等什么、该去哪里补。 -- 缺 key 停下的命令(`bin/vh tts` 各家、`--align gemini`、`voices audition`、`pace --align gemini`、`music --provider lyria`、`image gen`)都说同一句:哪一家、哪个 key,在 Studio 的设置 → 服务里填上(或者设环境变量),去哪拿,不用它时这台电脑上还能怎么做(本地配音、本地对时间、本地作曲)。这句由 `tools/keys.py` 写,记进这次运行的记录,代码是新的 `no_key`。 -- `bin/vh status` 和 Studio 的现状行在片子等 key 时说:"配音停下了:还没有 Gemini 的 API Key。在设置 → 服务里填上,再让 agent 接着做。"Studio 里那一行带一个按钮,点了直接到设置 → 服务。key 设上了(Studio 里或环境变量里),或者同一条命令再跑一次没为它停,这句就不说了。 +- 缺 key 停下的命令(`bin/vh tts` 各家、`--align gemini`、`voices audition`、`pace --align gemini`、`music --provider lyria`、`image gen`)都说同一句:哪一家、哪个 key,在 Studio 的设置 → 服务里填上(或者设环境变量),去哪拿,不用它时这台电脑上还能怎么做。能怎么做看这台电脑:Apple Silicon 上是本地配音、本地对时间;Intel Mac 上是 macOS 自带的声音;Linux 上没有本地的,就直说;作曲哪里都能在本地做;出图装了 Codex 时可以走 ChatGPT 的订阅。这句由 `tools/keys.py` 写,记进这次运行的记录,代码是新的 `no_key`,还记下 key 拿来做什么(配音、对时间、作曲、出图)。 +- `bin/vh status` 和 Studio 的现状行在片子等 key 时说:"配音停下了:还没有 Gemini 的 API Key。在设置 → 服务里填上,再让 agent 接着做。"Studio 里那一行带一个按钮,点了直接到设置 → 服务。下面那句按 key 拿来做什么来说(配音的 key 说本地声音,对时间的 key 说本地对时间)。key 设上了(Studio 里或环境变量里)、后来同类的活做成了、或者后来别的命令失败了,这句就不说了。 +- `music --provider lyria` 的运行现在会记下结束,不再被当成中断。 - 不花钱:检查在调用之前,什么都没调就停。 diff --git a/tools/activity.py b/tools/activity.py index 20fa34bf..3766ca4e 100644 --- a/tools/activity.py +++ b/tools/activity.py @@ -350,7 +350,7 @@ def event(project, kind, **fields): # ---------- reading ---------- -_STR = ("run", "cmd", "cwd", "summary", "unit", "parent", "file", "round", "level", "code", "kept", "project") +_STR = ("run", "cmd", "cwd", "summary", "unit", "parent", "file", "round", "level", "code", "kept", "project", "need") _INT = ("pid", "exit", "decisions") _NUM = ("duration", "done", "total", "pass", "passes") @@ -543,6 +543,8 @@ def runs(records, now=None, same_process=True): run["summary"] = r["summary"] elif ev == "note" and r.get("level") == "error": run["error"] = {"code": r.get("code") or "failed", "message": r.get("summary") or ""} + if r.get("code") == "no_key": # what the key was for (voice, timing, music, image) and its names (tools/keys.py) + run["error"].update(need=r.get("need"), keys=[k for k in r.get("keys") or [] if isinstance(k, str)] if isinstance(r.get("keys"), list) else []) elif ev == "note": if r.get("summary"): run["summary"] = r["summary"] diff --git a/tools/assets/image.py b/tools/assets/image.py index 84b3afb6..72833c89 100644 --- a/tools/assets/image.py +++ b/tools/assets/image.py @@ -621,7 +621,7 @@ def cmd_gen(a): return 0 if a.provider == "gemini": if not a.offline and not keys.get("GEMINI_API_KEY"): - raise Usage(keys.stopping("GEMINI_API_KEY")) + raise Usage(keys.stopping("GEMINI_API_KEY", "image")) if not plan["budget"]["ok"]: raise Failed(f"{plan['budget']['message']} (bin/vh image gen --dry-run shows the estimate)") if refs: diff --git a/tools/audio/lyria.py b/tools/audio/lyria.py index eb7ab16c..9c097ef2 100644 --- a/tools/audio/lyria.py +++ b/tools/audio/lyria.py @@ -133,7 +133,7 @@ def cmd_gen(a): say(" nothing called (--dry-run)") return 0 if not a.offline and not keys.get("GEMINI_API_KEY"): - raise Usage(keys.stopping("GEMINI_API_KEY", "or bin/vh music without --provider, composed on this computer")) + raise Usage(keys.stopping("GEMINI_API_KEY", "music")) if not chk["ok"]: raise Failed(f"{chk['message']} (--dry-run shows the price)") folder = project / GENMUSIC / cid @@ -255,7 +255,8 @@ def main(argv): if __name__ == "__main__": + import activity # bin/vh exec's into this (cmd_music): this process writes the run's end, or the run reads as cut off try: - sys.exit(main(sys.argv[1:])) + sys.exit(activity.exiting(lambda: main(sys.argv[1:]))) except BrokenPipeError: sys.exit(0) diff --git a/tools/audio/pace.py b/tools/audio/pace.py index 50ac3c7b..70e795d6 100644 --- a/tools/audio/pace.py +++ b/tools/audio/pace.py @@ -678,7 +678,7 @@ def captions(old, skip_lint=False): f" --resume first, or pass --align gemini|whisper here to transcribe the take") if (missing and not found) or (a.align != "map" and not a.dry_run): # before anything is written if a.align == "gemini" and not tts.keys.get("GEMINI_API_KEY"): - sys.exit(tts.keys.stopping("GEMINI_API_KEY", "--align gemini needs it (--align whisper does not); nothing was written")) + sys.exit(tts.keys.stopping("GEMINI_API_KEY", "timing", "--align gemini needs it; nothing was written", align="--align whisper")) if a.align == "whisper" and importlib.util.find_spec("mlx_whisper") is None: sys.exit("--align whisper needs mlx-whisper (Apple Silicon; bin/vh pace adds it with --align whisper); nothing was written") if missing: # the take's own word times, transcribed once and kept beside it @@ -759,7 +759,7 @@ def save(): rc = 0 if a.align != "map": if a.align == "gemini" and not tts.keys.get("GEMINI_API_KEY"): - sys.exit(tts.keys.stopping("GEMINI_API_KEY", "--align gemini needs it; the paced take is written with mapped word times")) + sys.exit(tts.keys.stopping("GEMINI_API_KEY", "timing", "--align gemini needs it; the paced take is written with mapped word times", align="--align whisper")) try: fresh = align_take(new, wav, a.align, a.lang, tmp, out["duration"]) except Exception as e: # quota, network: the mapped word times stay diff --git a/tools/audio/tts.py b/tools/audio/tts.py index b3cd47dc..6c4c0ffb 100644 --- a/tools/audio/tts.py +++ b/tools/audio/tts.py @@ -141,7 +141,7 @@ pronunciation_dict.tone. text_normalization is on: "1953 年" is read 一千九百五十三年, so write years as 一九五三年 in the spoken text. """ -import argparse, base64, difflib, hashlib, json, os, platform, re, shutil, signal, subprocess, sys, tempfile, time, unicodedata +import argparse, base64, difflib, hashlib, json, os, re, shutil, signal, subprocess, sys, tempfile, time, unicodedata import urllib.error, urllib.parse, urllib.request, wave from concurrent.futures import Future, ThreadPoolExecutor from pathlib import Path @@ -256,11 +256,7 @@ def gemini_call(path, body=None, method=None, query=None, timeout=180, tries=3): def no_key(provider): """Exit (1) on a provider with no key: tools/keys.py's sentence (where to set it, where to get one), and what works with none on this machine; on the run's record as no_key.""" - if sys.platform == "darwin" and platform.machine() == "arm64": - free = "or leave the provider out for this computer's own voice, which needs no key (qwen, free, about " + firstuse.gb(firstuse.total(["qwen"])) + " on first use)" - else: - free = "or --provider edge, which needs no key (free, online; the local default, qwen, runs only on Apple Silicon)" - sys.exit(keys.stopping(KEY_OF[provider], free)) + sys.exit(keys.stopping(KEY_OF[provider], "voice", size=firstuse.gb(firstuse.total(["qwen"])))) # (what works with none: per platform, tools/keys.py) def hf_cached(model_id): """The model is on this machine: a local folder, or a snapshot in the Hugging Face cache, found where the Hub itself @@ -1122,9 +1118,9 @@ def audition(a): if a.align == "local": need_local_asr() if (gemini or a.align == "gemini") and not keys.get("GEMINI_API_KEY"): - sys.exit("voices audition: " + keys.stopping("GEMINI_API_KEY", (f"--provider {a.provider}" if gemini else "--align gemini") + " needs it; nothing was synthesized")) + sys.exit("voices audition: " + keys.stopping("GEMINI_API_KEY", "voice" if gemini else "timing", (f"--provider {a.provider}" if gemini else "--align gemini") + " needs it; nothing was synthesized")) if a.provider == "minimax" and not minimax_key()[0]: - sys.exit("voices audition: " + keys.stopping(KEY_OF["minimax"], "nothing was synthesized")) + sys.exit("voices audition: " + keys.stopping(KEY_OF["minimax"], "voice", "nothing was synthesized")) try: import voicefeat except ImportError: @@ -1267,7 +1263,7 @@ def main(): if a.align == "local": # before anything is synthesized or deleted need_local_asr() if align and a.align != "local" and not keys.get("GEMINI_API_KEY"): - sys.exit(keys.stopping("GEMINI_API_KEY", "--align gemini and --join transcribe with Gemini; or --align local, on this computer")) + sys.exit(keys.stopping("GEMINI_API_KEY", "timing", "--align gemini and --join transcribe time the words with Gemini")) if man and a.provider == "minimax" and join != "none" and man.get("gap") != a.gap: sys.exit(f"--resume: --gap was {man.get('gap')} for the run, now {a.gap}; in a joined minimax request it is part of the" f" text: pass --gap {man.get('gap')}, or drop --resume to start over") diff --git a/tools/desk/README.md b/tools/desk/README.md index e17ff5eb..f364d038 100644 --- a/tools/desk/README.md +++ b/tools/desk/README.md @@ -384,7 +384,7 @@ JSON 的格式: - `state` 七种:`done`(REVIEW.md 里有它的"定了":先看关于最新那一页的最后一节,审阅台为提交写的那节、或写了 `gate-.html` 的那节,模板的三节都预先写了;没有这种节,就看这一站自己的节,而且 REVIEW.md 要晚于这一页,`note` 里会说是按日期算的。关卡 ① 和 `bin/vh render`、`check` 用同一条规则(`tools/gatecheck.py`):关卡 ① 的节里有定了和人的原话;`record` 另有 `concept_on_record`、`concept_from`(`REVIEW.md`,或者老项目 DECISIONS.md 里立意那一行)和 `concept`(关卡 ① 定了那一行的原文:写的是哪张卡就是哪张卡,只写"通过"就是"通过"))、`skipped`(quick 档:这一站没有自己的页面,Director 也没要它(`stop=`、`x=own`);或者 REVIEW.md 里有用户原话授权跳过)、`waiting_person`(这一页发出去了(`bin/vh gate` 出的页面:写好还没发的 gate JSON 不算,上一次被 `bin/vh gate` 拒绝、退出码 1 的也不算,那一次什么都没发给人),是这一轮(`out/review/.current`),还没有回音)、`waiting_agent`(人提交了还没交给 agent,或者交了但 REVIEW.md 还没写定了;或者这一轮已经往后走、这一页没有记录;或者关卡 ① 定了,但缺人的原话,render 和 check 会拒绝)、`in_progress`(前面都过了,agent 正朝这一站做)、`not_started`、`no_record`(standard、studio 的项目没有 REVIEW.md,模板有它之前做的:无从读起,gatecheck 也不查)。交付:`bin/vh deliver` 写过记录,或成片(`out/final*`、`out/final/`、直接放在 `media/` 下的文件、Manim 1080p 及以上的渲染;不含它 480p15、720p30 的草稿,也不含 `bin/vh patch` 留下的 `.failed`)有一份通过的检查记录、而且就是这支成片的(记录里的 `size` 和 `mtime_ns` 和它现在的一样;没有这两个字段的老记录,要比它晚),而且关卡 ③ 过了(`done` 或 `skipped`),就是 `done`;关卡 ③ 还没过时 `note` 会说;各站都过了是 `in_progress`;没有 REVIEW.md 是 `no_record`。 - `waiting_on`:`person`、`agent`、`nobody`(交付了)或 `unknown`(没有 REVIEW.md,又没有命令在跑);REVIEW.md 写了暂停(`paused: true`)也是 `person`。机器写的记录(检查记录、`.render.json`、`.deliver.json`、审阅台的提交)里类型不对的字段当作没有。`next`:一句话,谁下一步做什么。 - `next_step`:下一步,按项目停在哪一站算出来:`who`(`person`、`agent`、`nobody`、`unknown`)、`do`(一句话,还没填的 `{…}` 和 gate 骨架里的占位有几处都说出来;Director 写了 `x=own`、还没有记录的事排在最前面,记录是它那一站过了,或者 DECISIONS.md 里它那一行写了已定)、`commands`(能直接跑的命令,`` 这类尖括号是要换的)、`read`(该读的:`<文件>#<节>` 由 `bin/vh know --show` 打印,没有 `#` 的整篇读)、`unfilled`(`BRIEF.md`、`STYLE.md`、`STORYBOARD.md` 各还有几处 `{…}`,不算代码块和行内代码里的,也不算模板的 `{none}` 和 `{fill: #e33}` 这种带值的花括号;交付以后 `who` 是 `nobody`,这里是空的,没有要填的了)。 -- `now`:这支片子现在怎么样,说给人听的(`tools/standing.py`,Studio 说的也是这些字;字都在它开头的 `WORDS` 表里,中英文挨着)。只说磁盘能证明的:最后记下的事和它在什么时候(命令的开始和结束、交出的意见、Studio 对话的事件、片子自己文件的改动)、现在有没有进程在跑、等着的进程和它等的 agent 活不活着、Studio 的一轮怎么结束的、一条命令是在哪个 agent 程序下跑的(那个 agent 还活着,就是有 agent 开着这支片子)。磁盘不知道 agent 是不是正在两条命令之间想事情,所以安静的片子只说"上一次动静:12 分钟前,渲染做完了",从不说没人在做;"停下了"要有正面的证据;"让 agent 接着做"是一个可以点的选项,不是"没人在做"的断言。字段:`code`、`who`(下一步该谁动,和 `waiting_on` 一致)、`you`(人跟它有什么事:`decide` 在等人定,`nudge` 要人说一声,`offer` 人可以点,`none`)、`tone`(点的颜色:`you` 琥珀、`busy` 紫、`quiet` 灰)、`say`(`{zh, en}` 一句短话,两秒读完)、`more`(`{zh, en}` 或 `null`:下面那一行)、`short`(`{zh, en}` 卡片上的几个字,不带路径,也不带不在词表里的命令名)、`act`(至多一件事:`{kind: "open", mod, sub, label}` 去 Studio 的哪个模块;`{kind: "settings", sub, label}` 去设置页的哪一节(片子等一家服务的 API Key 时:`code` 是 `needs_key`,`facts.keys` 是还没设的 key 名,`facts.service` 是哪一家;有一个设上了、或者那条命令再跑一次没为它停,就不再这么说);`{kind: "tell", label, text, confirm, secondary}` 对 agent 说的那句话,`confirm` 是先问一次(最近 30 分钟里还有动静,或者有 agent 开着),`secondary` 是它不是主要该做的事、写成第二行的小字;`{kind: "none"}`)、`facts`(`paths`:这些话里点到的项目文件,Studio 里点得开;还有 `stop`、`listening`、`pending`、`cmd`、`film`、`subtitles`、`version`、`keys`、`service` 这些)。 +- `now`:这支片子现在怎么样,说给人听的(`tools/standing.py`,Studio 说的也是这些字;字都在它开头的 `WORDS` 表里,中英文挨着)。只说磁盘能证明的:最后记下的事和它在什么时候(命令的开始和结束、交出的意见、Studio 对话的事件、片子自己文件的改动)、现在有没有进程在跑、等着的进程和它等的 agent 活不活着、Studio 的一轮怎么结束的、一条命令是在哪个 agent 程序下跑的(那个 agent 还活着,就是有 agent 开着这支片子)。磁盘不知道 agent 是不是正在两条命令之间想事情,所以安静的片子只说"上一次动静:12 分钟前,渲染做完了",从不说没人在做;"停下了"要有正面的证据;"让 agent 接着做"是一个可以点的选项,不是"没人在做"的断言。字段:`code`、`who`(下一步该谁动,和 `waiting_on` 一致)、`you`(人跟它有什么事:`decide` 在等人定,`nudge` 要人说一声,`offer` 人可以点,`none`)、`tone`(点的颜色:`you` 琥珀、`busy` 紫、`quiet` 灰)、`say`(`{zh, en}` 一句短话,两秒读完)、`more`(`{zh, en}` 或 `null`:下面那一行)、`short`(`{zh, en}` 卡片上的几个字,不带路径,也不带不在词表里的命令名)、`act`(至多一件事:`{kind: "open", mod, sub, label}` 去 Studio 的哪个模块;`{kind: "settings", sub, label}` 去设置页的哪一节(片子等一家服务的 API Key 时:`code` 是 `needs_key`,`facts.keys` 是还没设的 key 名,`facts.service` 是哪一家,`facts.need` 是 key 拿来做什么:`voice`、`timing`、`music`、`image`;下面那一行按它和这台电脑有什么来说不用 key 的办法,没有就直说没有。从整份记录里找(`activity.key_stop`),不看最近几条:有一个 key 设上了、后来同类的活做成了(配音成了,配音和对时间的停都算过去)、或者后来有别的命令失败了,就不再这么说。只在终端的环境变量里设了 key、Studio 又是从别处打开的,Studio 看不到这个变量,会一直说在等,直到那条命令在那个终端里再跑一次);`{kind: "tell", label, text, confirm, secondary}` 对 agent 说的那句话,`confirm` 是先问一次(最近 30 分钟里还有动静,或者有 agent 开着),`secondary` 是它不是主要该做的事、写成第二行的小字;`{kind: "none"}`)、`facts`(`paths`:这些话里点到的项目文件,Studio 里点得开;还有 `stop`、`listening`、`pending`、`cmd`、`film`、`subtitles`、`version`、`keys`、`service` 这些)。 `code` 按这个先后取第一个对上的:`paused`(REVIEW.md 写了暂停);`revision_ready`(有一条复审等人看);`waiting_you`(一站的页发出去了等人:`facts.listening` 按上面 `.listening` 的三样算,真就"你交了,agent 就接着做",不然"交了以后,要跟 agent 说一声";声音那一站是"等你听");最新的一份意见还没人取时,不管别的在不在跑都先说它:等着的人活着是 `notes_sent`,不然 `notes_unheard`(有命令在跑时写"渲染还在跑,但你 21:30 交的这一份没人取");`notes_taken`(意见交到 agent 手里了,而且这会儿真有东西在为这支片子做:`bin/vh` 命令在跑,或 Studio 的一个对话拿着锁;没东西在跑时不说"正在改");`running`(`bin/vh` 命令在跑,带进度;pid 被后来的进程占去的不算在跑);`working`(Studio 的一个对话拿着锁,锁的 pid 也照这样核对);`delivered`(最新的一份交付记录:哪支成片、旁边的字幕、`versions` 里正好是它的那一版);`no_record`;然后是轮到 agent、现在没东西在跑的几种。先把所有动静排一遍(结束了的命令:做完了、结束时报了问题、被停下了、中断了;发出的审阅页;开始等你的意见;它取走了你的意见;Studio 对话的最后一件事;片子自己的文件里最新改的那个:先看片子的文件夹,再一层层往下(广度优先,四层),不看 `out/`、`media/`、`renders/` 和 Studio 自己写的 `REVIEW.md`;`assets/`、`audio/`、帧序列这种重的文件夹(按名字,或者一个文件夹里超过 300 项)只看文件夹自己的时间,不一个个看;看到 4000 项还没看完就停,这时说的是"看到的最近一次动静","之后没有别的动静"这种话不说),取最新的那一件:它是一条没有结束记录、进程也没了的命令,或者 Studio 的一轮被停下、出错、做到一半断了,而且没有 agent 开着,才是 `stopped`("agent 停下了:渲染中断了。",下面一行是什么时候、到第几帧、之后没有别的动静、下一站);做这支片子的 agent 还开着,是 `agent_open`("现在没有命令在跑;上次做这支片子的 agent 还开着。","让 agent 接着做"降成第二行、点之前先问一次):只在这个 agent 程序最近一次做的就是这支片子,或者这支片子最新的动静在 6 小时以内时这么说;一个开了很久、做过许多支片子的程序(比如 Studio 那一列背后的那个)不让它做过的每支片子都显得"开着",那些片子照常说它们自己的情况,再加一句"做过它的 agent 程序还开着,可能在忙别的片子。";各站都过了还没交付是 `ship_missing`;下一步是装引擎是 `setup`;其余是 `idle`("现在没有命令在跑。",下面一行"上一次动静:……")。一条命令出错结束(`check` 没过、`gate` 拒绝)是它的结果,不是停下了:写成"上一次动静:3 分钟前,检查查出 2 处要改",下一步还是 agent 的。 diff --git a/tools/desk/test_agents.py b/tools/desk/test_agents.py index 6fd1f98b..47024a7c 100644 --- a/tools/desk/test_agents.py +++ b/tools/desk/test_agents.py @@ -1901,21 +1901,47 @@ def unit(): # the order of what is said, and what each sentence never claims, pending_busy = one(stations=both_, activity={"running": [render]}) taken = one(stations=handed, activity={"running": [render]}) unknown = one(activity={"running": [{"cmd": "foo-bar"}]}) - import keys # a film waiting on a service's API Key: on no store of anyone's, with no key in the environment + import keys # a film waiting on a service's API Key: on no store of anyone's, with no key in the environment, on a platform made up kept = {k: os.environ.pop(k) for k in [*keys.KEY_NAMES, "OVH_KEYSTORE"] if k in os.environ} os.environ["OVH_KEYSTORE"] = "none"; keys._CACHE.pop("kind", None); keys.forget() + real_machine, real_codex = keys.machine, keys.has_codex try: - nk = lambda cmd, names, t=now - 90: {"cmd": cmd, "state": "failed", "exit": 1, "start": t - 10, "end": t, "error": {"code": "no_key", "message": keys.missing(names)}} # noqa: E731 + keys.machine, keys.has_codex = (lambda: ("darwin", "arm64")), (lambda: False) + nk = lambda cmd, names, need=None, t=now - 900: {"cmd": cmd, "state": "failed", "exit": 1, "start": t - 10, "end": t, # noqa: E731 + "error": dict({"code": "no_key", "message": keys.missing(names)}, **({"need": need, "keys": [names] if isinstance(names, str) else names} if need else {}))} ok = lambda cmd, t: {"cmd": cmd, "state": "ok", "exit": 0, "start": t - 10, "end": t} # noqa: E731 + bad = lambda cmd, t, **k: dict({"cmd": cmd, "state": "failed", "exit": 1, "start": t - 10, "end": t}, **k) # noqa: E731 + two_lines = lambda n: [n["code"], n["more"]["zh"].split("。")[1] + "。" if n["code"] == "needs_key" else None] # noqa: E731 key_tts = one(activity={"recent": [nk("tts", "GEMINI_API_KEY")]}) - key_mm = one(activity={"recent": [nk("tts", ["MINIMAX_TOKEN_PLAN_KEY", "MINIMAX_API_KEY"])]}) - key_image = one(activity={"recent": [nk("image", "GEMINI_API_KEY"), ok("render", now - 30)]}) # another command after it: still waiting - key_again = one(activity={"recent": [nk("tts", "GEMINI_API_KEY"), ok("tts", now - 30)]}) # the same command again, fine: no more - key_old_way = one(activity={"recent": [{"cmd": "tts", "state": "failed", "exit": 1, "start": now - 100, "end": now - 90, "error": {"code": "failed", "message": "set GEMINI_API_KEY"}}]}) + key_mm = one(activity={"recent": [nk("tts", ["MINIMAX_TOKEN_PLAN_KEY", "MINIMAX_API_KEY"], "voice")]}) + key_image = one(activity={"recent": [nk("image", "GEMINI_API_KEY", "image"), ok("render", now - 30)]}) # another kind of work after it: still waiting + key_timing = one(activity={"recent": [nk("tts", "GEMINI_API_KEY", "timing")]}) # tts --align gemini on the local voice: the timing line, not the voice one + settled = { # what a later run does to it + "tts_again": one(activity={"recent": [nk("tts", "GEMINI_API_KEY", "voice"), ok("tts", now - 30)]})["code"], + "voices_then_tts": one(activity={"recent": [nk("voices", "GEMINI_API_KEY", "voice"), ok("tts", now - 60), ok("render", now - 30)]})["code"], + "pace_then_tts": one(activity={"recent": [nk("pace", "GEMINI_API_KEY", "timing"), ok("tts", now - 30)]})["code"], + "pace_then_render": one(activity={"recent": [nk("pace", "GEMINI_API_KEY", "timing"), ok("render", now - 30)]})["code"], + "image_then_failed_check": one(activity={"recent": [nk("image", "GEMINI_API_KEY", "image"), bad("check", now - 30)]})["code"], + "image_then_stopped": one(activity={"recent": [nk("image", "GEMINI_API_KEY", "image"), dict(bad("render", now - 30), exit=130, cancelled=True)]})["code"], + "image_then_image": one(activity={"recent": [nk("image", "GEMINI_API_KEY", "image"), ok("image", now - 30)]})["code"], + "old_way": one(activity={"recent": [bad("tts", now - 90, error={"code": "failed", "message": "set GEMINI_API_KEY"})]})["code"], + "whole_log": one(activity={"recent": [ok("render", now - 50 + i) for i in range(5)], "key_stop": nk("tts", "GEMINI_API_KEY", "voice")})["code"], + "whole_log_none": one(activity={"recent": [nk("tts", "GEMINI_API_KEY", "voice")], "key_stop": None})["code"], + } + keys.has_codex = lambda: True + key_codex = one(activity={"recent": [nk("image", "GEMINI_API_KEY", "image")]}) + keys.has_codex = lambda: False + keys.machine = lambda: ("darwin", "x86_64") # an Intel Mac: macOS's own voice; no local timing + intel = [two_lines(one(activity={"recent": [nk("tts", "GEMINI_API_KEY", need)]})) for need in ("voice", "timing")] + keys.machine = lambda: ("linux", "x86_64") # Linux: no voice or timing of its own; music still composed here + linux = [two_lines(one(activity={"recent": [nk(c, "GEMINI_API_KEY", need)]})) for c, need in (("tts", "voice"), ("pace", "timing"), ("music", "music"))] + words = {"voice": keys.local_way("voice")[1], "timing": keys.local_way("timing", "--align whisper")[1]} # what the command says there + keys.machine = lambda: ("darwin", "arm64") os.environ["GEMINI_API_KEY"] = "madeUpForThisCheck1" - key_set = one(activity={"recent": [nk("tts", "GEMINI_API_KEY")]}) + key_set = one(activity={"recent": [nk("tts", "GEMINI_API_KEY", "voice")]}) del os.environ["GEMINI_API_KEY"] finally: + keys.machine, keys.has_codex = real_machine, real_codex os.environ.pop("OVH_KEYSTORE", None); os.environ.update(kept); keys._CACHE.pop("kind", None); keys.forget() got = { "paused": one(paused=True)["code"], "revision": one(review={"revisions": [{"state": "pending", "available": True}]})["code"], @@ -1952,7 +1978,8 @@ def unit(): # the order of what is said, and what each sentence never claims, key_tts["facts"]["keys"], key_tts["facts"]["service"]], "key_mm": [key_mm["say"]["en"], key_mm["facts"]["keys"]], "key_image": [key_image["say"]["zh"], key_image["more"]["en"]], - "key_gone": [key_again["code"], key_set["code"], key_old_way["code"]], + "key_timing": key_timing["more"]["en"], "key_codex": key_codex["more"]["zh"], "key_set": key_set["code"], "settled": settled, + "key_intel": intel, "key_linux": linux, "key_linux_words": [w.split(" (")[0] for w in words.values()], } want = {"paused": "paused", "revision": "revision_ready", "setup": "setup", "idle": "idle", "running": "正在配音,12 / 30 句。", "gone": ["stopped", "agent 停下了:渲染中断了。", "nudge", False], @@ -1975,15 +2002,22 @@ def unit(): # the order of what is said, and what each sentence never claims, "在设置 → 服务里填上,再让 agent 接着做。不想用在线服务,也可以让 agent 换成这台电脑上的声音。", "等 API Key", {"kind": "settings", "mod": None, "sub": "services", "label": {"zh": "去设置 → 服务", "en": "Open Settings → Services"}}, ["GEMINI_API_KEY"], "gemini"], "key_mm": ["The voice-over stopped: there's no MiniMax API Key yet.", ["MINIMAX_TOKEN_PLAN_KEY", "MINIMAX_API_KEY"]], - "key_image": ["出图停下了:还没有 Gemini 的 API Key。", "Set it up in Settings → Services, then ask the agent to carry on."], - "key_gone": ["idle", "idle", "idle"]} + "key_image": ["出图停下了:还没有 Gemini 的 API Key。", "Set it up in Settings → Services, then ask the agent to carry on. This computer has no way to do it without an API Key."], + "key_timing": "Set it up in Settings → Services, then ask the agent to carry on. Or ask the agent to time the words on this computer, with no service.", + "key_codex": "在设置 → 服务里填上,再让 agent 接着做。也可以让 agent 用 Codex 出图,走 ChatGPT 的订阅,不用 API Key。", "key_set": "idle", + "settled": {"tts_again": "idle", "voices_then_tts": "idle", "pace_then_tts": "idle", "pace_then_render": "needs_key", "image_then_failed_check": "idle", + "image_then_stopped": "needs_key", "image_then_image": "idle", "old_way": "idle", "whole_log": "needs_key", "whole_log_none": "idle"}, + "key_intel": [["needs_key", "不想用在线服务,也可以让 agent 换成 macOS 自带的声音(够打草稿)。"], ["needs_key", "这台电脑上没有不用 API Key 的办法。"]], + "key_linux": [["needs_key", "这台电脑上没有不用 API Key 的办法。"], ["needs_key", "这台电脑上没有不用 API Key 的办法。"], ["needs_key", "不想用在线服务,也可以让 agent 在这台电脑上作曲。"]], + "key_linux_words": ["this computer has no voice of its own that needs no key", "this computer has no way of its own to time the words"]} return None if got == want else {k: v for k, v in got.items() if want.get(k) != v} check("what each state never says falsely: a run cut off with nothing after it is the only command that stops the agent (a finished run with " "findings, one stopped on purpose, a later run that went fine, the console ending, are not); the newest notes nobody took come first; " "working on them only while something runs; never that nobody works on the film; whose move as waiting_on; a command not in the table " "is no name on the page; the final sound is listened to and the sound plan looked at, plurals agree; the plan says what the BRIEF says plainly (none (music only), 2 min 30 s, " "a checkpoint) and leaves out what it does not; a command that stopped for a service's API Key says so, what to do and where (Settings → Services), " - "until the key is set or the same command ran again without stopping for it", unit) + "with the line under it chosen by what the key was for and by what this computer has (a made-up Apple Silicon Mac, Intel Mac and Linux; Codex there or not), " + "until the key is set, a later run did the same kind of work fine, or a later run failed; read from the whole log", unit) def title(): # a film begun on the space, its BRIEF still the template's: the person's own sentence, shortened, not the dated folder import server diff --git a/tools/desk/test_settings.py b/tools/desk/test_settings.py index 9fb17cdc..f108a705 100644 --- a/tools/desk/test_settings.py +++ b/tools/desk/test_settings.py @@ -555,6 +555,16 @@ def first_run_check(): return f"bin/vh status while the film waits: {now['code']} {now['act']}" if "now: The voice-over stopped: there's no Gemini API Key yet." not in vh("status", str(film)).stdout: return "bin/vh status's now: line" + if now.get("facts", {}).get("need") != "voice": + return f"what the key was for: {now.get('facts')}" + r = vh("music", str(film), "--provider", "lyria", "--prompt", "a calm tide") # bin/vh exec's into lyria.py: it ends its own run + runs = json.loads(vh("activity", str(film), "--json").stdout)["runs"] + mus = [x for x in runs if x.get("cmd") == "music"] + if r.returncode != 2 or "Studio's Settings → Services" not in r.stderr or not mus or mus[-1].get("state") != "failed" or mus[-1].get("exit") != 2: + return f"bin/vh music --provider lyria with no key: exit {r.returncode}, its run {mus[-1:] and {k: mus[-1].get(k) for k in ('state', 'exit')}}, {r.stderr[-200:]!r}" + now = json.loads(vh("status", str(film), "--json").stdout)["now"] + if now["code"] != "needs_key" or now["facts"].get("cmd") != "music" or now["facts"].get("need") != "music": + return f"bin/vh status after the music stop: {now['code']} {now['facts']}" rc, out = py(f"import keys as K\nK.save('GEMINI_API_KEY', {FAKE!r})") try: if rc: @@ -585,7 +595,7 @@ def words_check(): check("tools/keys.py on a store of these checks' own: saved, found, the environment first, taken out; what is not a key or a key's name refused; the store asked once per name (a missing key and a store with no answer too), a save or removal seen at once" + ("" if MAC else "; the key never an argument"), keys_module_check) check("bin/vh doctor finds a key saved in Studio, says so, and probes with it (a recording), with each of MiniMax's two when both are saved, never printing one", doctor_keys_check) check("a command run in the agent column's environment (no key in it) finds a key saved in Studio", column_check) - check("a voice-over with no key: the command says where to set it and where to get one (code no_key on its record); bin/vh status says the film waits on the key, with the way to Settings → Services, and no more once it is saved", first_run_check) + check("a voice-over, then Lyria's music, with no key: each command says where to set it and where to get one (code no_key and what the key was for on its record; the music run ends as failed, not cut off); bin/vh status says the film waits on the key, with the way to Settings → Services, and no more once it is saved", first_run_check) run() except Exception as e: say(False, "the console for the settings page", f"{type(e).__name__}: {e}") diff --git a/tools/jsonerr.py b/tools/jsonerr.py index a1f7dd42..3a870eea 100644 --- a/tools/jsonerr.py +++ b/tools/jsonerr.py @@ -51,17 +51,17 @@ def record(code, message, hint=None): return {"version": 1, "error": {"code": code, "message": message, "hint": hint if hint is not None else HINTS.get(code)}} -def _note(code, message): +def _note(code, message, **extra): try: import activity - activity.note(message, level="error", code=code) + activity.note(message, level="error", code=code, **extra) except Exception: # the failure is said all the same pass -def report(code, message, hint=None): - """The failure on record, once a run: JSON on stdout with --json (unless a record is out already), a note in the log. The - line a person reads is the caller's.""" +def report(code, message, hint=None, **extra): + """The failure on record, once a run: JSON on stdout with --json (unless a record is out already), a note in the log + (with extra's fields: no_key's need and keys). The line a person reads is the caller's.""" global _said if _said: return @@ -72,7 +72,7 @@ def report(code, message, hint=None): hint = activity.scrub(activity._text(str(hint))) if hint is not None else None except Exception: message = str(message) - _note(code, message) + _note(code, message, **extra) if wanted() and not (_out is not None and _out.count): print(json.dumps(record(code, message, hint), ensure_ascii=False), flush=True) diff --git a/tools/keys.py b/tools/keys.py index 424bd44f..13661fc3 100644 --- a/tools/keys.py +++ b/tools/keys.py @@ -30,7 +30,7 @@ OVH_KEYSTORE=none for all its checks and passes it on where a check builds an environment of its own (acp.clean_env keeps it too); a check that never set it still runs with a scratch HOME, whose search list has no keychain of the person's. """ -import json, os, re, shutil, subprocess, sys +import json, os, platform, re, shutil, subprocess, sys from pathlib import Path ROOT = Path(__file__).resolve().parent.parent @@ -205,13 +205,48 @@ def missing(names, instead=None): return s + (f"; {instead}" if instead else "") -def stopping(names, instead=None): - """missing(), put on the run's record with the code no_key (once a run; nothing outside a logged run): → the sentence, - for the caller to print and stop with.""" +def machine(): + """(sys.platform, the processor): what decides the ways that need no key (a check fakes it).""" + return sys.platform, platform.machine() + + +def has_codex(): + return shutil.which("codex") is not None # as bin/vh doctor finds it (tools/modules.json's codex: the program on PATH) + + +def local_way(need, align="--align local", size=None): + """What does the same work with no API Key here: (word, the command's words). word is what tools/standing.py says + (voice, voice_say, timing, music, image_codex), None when this computer has no such way (the words say so plainly, or + are None). need: voice | timing | music | image.""" + plat, cpu = machine() + apple = plat == "darwin" and cpu == "arm64" + if need == "voice": + if apple: + return "voice", "or leave the provider out for this computer's own voice, which needs no key (qwen, free" + (f", about {size} on first use)" if size else ")") + if plat == "darwin": + return "voice_say", "or --provider say, macOS's own voice on this computer, which needs no key (free; good enough for a draft)" + return None, "this computer has no voice of its own that needs no key (the local one, qwen, runs only on Apple Silicon); --provider edge needs none, but it is an online service" + if need == "timing": + if apple: + return "timing", f"or {align}, which times the words on this computer with no key" + return None, f"this computer has no way of its own to time the words ({align} runs only on Apple Silicon)" + if need == "music": + return "music", "or bin/vh music without --provider, composed on this computer with no key" + if need == "image": + return ("image_codex", "or --provider codex, on the ChatGPT plan Codex is signed in with (no API Key)") if has_codex() else (None, None) + return None, None + + +def stopping(names, need=None, tail=None, align="--align local", size=None): + """missing() with what works with no key here (local_way), put on the run's record with the code no_key, what the key + was for (need) and its names (once a run; nothing outside a logged run): → the sentence, for the caller to print and + stop with.""" + names = [names] if isinstance(names, str) else list(names) + instead = "; ".join(x for x in (local_way(need, align, size)[1], tail) if x) or None msg = missing(names, instead) try: import jsonerr - jsonerr.report("no_key", msg, "Studio's Settings → Services takes the key") + jsonerr.report("no_key", msg, "Studio's Settings → Services takes the key", need=need, keys=names) except Exception: # the sentence is said all the same pass return msg diff --git a/tools/schemas/output/activity.schema.json b/tools/schemas/output/activity.schema.json index e44ad1d5..69f6b1f0 100644 --- a/tools/schemas/output/activity.schema.json +++ b/tools/schemas/output/activity.schema.json @@ -61,7 +61,9 @@ "required": ["code", "message"], "properties": { "code": {"type": "string"}, - "message": {"type": "string"} + "message": {"type": "string"}, + "need": {"description": "code no_key: what the key was for", "enum": ["voice", "timing", "music", "image", null]}, + "keys": {"description": "code no_key: the key names it stopped for", "type": "array", "items": {"type": "string"}} } }, "cancelled": {"type": "boolean"}, diff --git a/tools/schemas/output/projects.schema.json b/tools/schemas/output/projects.schema.json index ed8b9e20..7b03ecb0 100644 --- a/tools/schemas/output/projects.schema.json +++ b/tools/schemas/output/projects.schema.json @@ -95,7 +95,7 @@ }, "$defs": { "words": {"type": "object", "required": ["zh", "en"], "properties": {"zh": {"type": "string"}, "en": {"type": "string"}}}, - "now": {"description": "Where the film stands for the person, in a sentence, and the one thing to do (tools/standing.py): what Studio says too", "type": ["object", "null"], "required": ["code", "who", "you", "tone", "say", "more", "short", "act", "facts"], "properties": {"code": {"enum": ["paused", "revision_ready", "waiting_you", "notes_unheard", "notes_sent", "notes_taken", "running", "working", "delivered", "no_record", "stopped", "agent_open", "ship_missing", "setup", "needs_key", "idle", "unknown"]}, "who": {"enum": ["person", "agent", "nobody", "unknown"]}, "say": {"$ref": "#/$defs/words"}, "more": {"anyOf": [{"type": "null"}, {"$ref": "#/$defs/words"}]}, "short": {"$ref": "#/$defs/words"}, "act": {"type": "object", "required": ["kind"], "properties": {"kind": {"enum": ["open", "tell", "settings", "none"]}, "mod": {"type": ["string", "null"]}, "sub": {"type": ["string", "null"]}, "label": {"$ref": "#/$defs/words"}, "text": {"$ref": "#/$defs/words"}, "confirm": {"type": "boolean"}, "secondary": {"type": "boolean"}}}, "facts": {"type": "object", "properties": {"paths": {"type": "array", "items": {"type": "string"}}, "stop": {"type": "string"}, "listening": {"type": "boolean"}, "pending": {"type": "integer"}, "revisions": {"type": "integer"}, "cmd": {"type": ["string", "null"]}, "film": {"type": ["string", "null"]}, "subtitles": {"type": "array", "items": {"type": "string"}}, "version": {"type": ["string", "null"]}, "keys": {"type": "array", "items": {"type": "string"}}, "service": {"type": ["string", "null"]}}}, "you": {"enum": ["decide", "nudge", "offer", "none"]}, "tone": {"enum": ["you", "busy", "quiet"]}}}, + "now": {"description": "Where the film stands for the person, in a sentence, and the one thing to do (tools/standing.py): what Studio says too", "type": ["object", "null"], "required": ["code", "who", "you", "tone", "say", "more", "short", "act", "facts"], "properties": {"code": {"enum": ["paused", "revision_ready", "waiting_you", "notes_unheard", "notes_sent", "notes_taken", "running", "working", "delivered", "no_record", "stopped", "agent_open", "ship_missing", "setup", "needs_key", "idle", "unknown"]}, "who": {"enum": ["person", "agent", "nobody", "unknown"]}, "say": {"$ref": "#/$defs/words"}, "more": {"anyOf": [{"type": "null"}, {"$ref": "#/$defs/words"}]}, "short": {"$ref": "#/$defs/words"}, "act": {"type": "object", "required": ["kind"], "properties": {"kind": {"enum": ["open", "tell", "settings", "none"]}, "mod": {"type": ["string", "null"]}, "sub": {"type": ["string", "null"]}, "label": {"$ref": "#/$defs/words"}, "text": {"$ref": "#/$defs/words"}, "confirm": {"type": "boolean"}, "secondary": {"type": "boolean"}}}, "facts": {"type": "object", "properties": {"paths": {"type": "array", "items": {"type": "string"}}, "stop": {"type": "string"}, "listening": {"type": "boolean"}, "pending": {"type": "integer"}, "revisions": {"type": "integer"}, "cmd": {"type": ["string", "null"]}, "film": {"type": ["string", "null"]}, "subtitles": {"type": "array", "items": {"type": "string"}}, "version": {"type": ["string", "null"]}, "keys": {"type": "array", "items": {"type": "string"}}, "service": {"type": ["string", "null"]}, "need": {"enum": ["voice", "timing", "music", "image", null]}}}, "you": {"enum": ["decide", "nudge", "offer", "none"]}, "tone": {"enum": ["you", "busy", "quiet"]}}}, "plan": {"description": "The film in a line from its BRIEF and its stops", "anyOf": [{"type": "null"}, {"$ref": "#/$defs/words"}]} } } diff --git a/tools/schemas/output/status.schema.json b/tools/schemas/output/status.schema.json index 60867a61..04f50716 100644 --- a/tools/schemas/output/status.schema.json +++ b/tools/schemas/output/status.schema.json @@ -221,7 +221,8 @@ "properties": { "running": {"type": "array"}, "listening": {"type": "array"}, - "recent": {"type": "array", "items": {"$ref": "#/$defs/run"}} + "recent": {"type": "array", "items": {"$ref": "#/$defs/run"}}, + "key_stop": {"description": "the newest run that stopped for want of an API Key (error code no_key) that no later run settled, from the whole log (tools/standing.py key_stop), or null", "anyOf": [{"type": "null"}, {"$ref": "#/$defs/run"}]} } }, "media": { @@ -254,7 +255,7 @@ }, "$defs": { "words": {"type": "object", "required": ["zh", "en"], "properties": {"zh": {"type": "string"}, "en": {"type": "string"}}}, - "now": {"description": "Where the film stands for the person, in a sentence, and the one thing to do (tools/standing.py): what Studio says too", "type": ["object", "null"], "required": ["code", "who", "you", "tone", "say", "more", "short", "act", "facts"], "properties": {"code": {"enum": ["paused", "revision_ready", "waiting_you", "notes_unheard", "notes_sent", "notes_taken", "running", "working", "delivered", "no_record", "stopped", "agent_open", "ship_missing", "setup", "needs_key", "idle", "unknown"]}, "who": {"enum": ["person", "agent", "nobody", "unknown"]}, "say": {"$ref": "#/$defs/words"}, "more": {"anyOf": [{"type": "null"}, {"$ref": "#/$defs/words"}]}, "short": {"$ref": "#/$defs/words"}, "act": {"type": "object", "required": ["kind"], "properties": {"kind": {"enum": ["open", "tell", "settings", "none"]}, "mod": {"type": ["string", "null"]}, "sub": {"type": ["string", "null"]}, "label": {"$ref": "#/$defs/words"}, "text": {"$ref": "#/$defs/words"}, "confirm": {"type": "boolean"}, "secondary": {"type": "boolean"}}}, "facts": {"type": "object", "properties": {"paths": {"type": "array", "items": {"type": "string"}}, "stop": {"type": "string"}, "listening": {"type": "boolean"}, "pending": {"type": "integer"}, "revisions": {"type": "integer"}, "cmd": {"type": ["string", "null"]}, "film": {"type": ["string", "null"]}, "subtitles": {"type": "array", "items": {"type": "string"}}, "version": {"type": ["string", "null"]}, "keys": {"type": "array", "items": {"type": "string"}}, "service": {"type": ["string", "null"]}}}, "you": {"enum": ["decide", "nudge", "offer", "none"]}, "tone": {"enum": ["you", "busy", "quiet"]}}}, + "now": {"description": "Where the film stands for the person, in a sentence, and the one thing to do (tools/standing.py): what Studio says too", "type": ["object", "null"], "required": ["code", "who", "you", "tone", "say", "more", "short", "act", "facts"], "properties": {"code": {"enum": ["paused", "revision_ready", "waiting_you", "notes_unheard", "notes_sent", "notes_taken", "running", "working", "delivered", "no_record", "stopped", "agent_open", "ship_missing", "setup", "needs_key", "idle", "unknown"]}, "who": {"enum": ["person", "agent", "nobody", "unknown"]}, "say": {"$ref": "#/$defs/words"}, "more": {"anyOf": [{"type": "null"}, {"$ref": "#/$defs/words"}]}, "short": {"$ref": "#/$defs/words"}, "act": {"type": "object", "required": ["kind"], "properties": {"kind": {"enum": ["open", "tell", "settings", "none"]}, "mod": {"type": ["string", "null"]}, "sub": {"type": ["string", "null"]}, "label": {"$ref": "#/$defs/words"}, "text": {"$ref": "#/$defs/words"}, "confirm": {"type": "boolean"}, "secondary": {"type": "boolean"}}}, "facts": {"type": "object", "properties": {"paths": {"type": "array", "items": {"type": "string"}}, "stop": {"type": "string"}, "listening": {"type": "boolean"}, "pending": {"type": "integer"}, "revisions": {"type": "integer"}, "cmd": {"type": ["string", "null"]}, "film": {"type": ["string", "null"]}, "subtitles": {"type": "array", "items": {"type": "string"}}, "version": {"type": ["string", "null"]}, "keys": {"type": "array", "items": {"type": "string"}}, "service": {"type": ["string", "null"]}, "need": {"enum": ["voice", "timing", "music", "image", null]}}}, "you": {"enum": ["decide", "nudge", "offer", "none"]}, "tone": {"enum": ["you", "busy", "quiet"]}}}, "plan": {"description": "The film in a line from its BRIEF and its stops", "anyOf": [{"type": "null"}, {"$ref": "#/$defs/words"}]}, "run": { "type": "object", diff --git a/tools/standing.py b/tools/standing.py index 5c450929..1c2f4298 100644 --- a/tools/standing.py +++ b/tools/standing.py @@ -128,6 +128,9 @@ "needs_key": ("{x}停下了:还没有 {s} 的 API Key。", "{T} stopped: there's no {s} API Key yet."), "needs_key.more": ("在设置 → 服务里填上,再让 agent 接着做。", "Set it up in Settings → Services, then ask the agent to carry on."), "needs_key.voice": ("不想用在线服务,也可以让 agent 换成这台电脑上的声音。", "Or ask the agent to use this computer's own voice, with no service."), + "needs_key.voice_say": ("不想用在线服务,也可以让 agent 换成 macOS 自带的声音(够打草稿)。", "Or ask the agent to use macOS's own voice, with no service (good enough for a draft)."), + "needs_key.image_codex": ("也可以让 agent 用 Codex 出图,走 ChatGPT 的订阅,不用 API Key。", "Or ask the agent to make the pictures with Codex, on the ChatGPT plan, with no API Key."), + "needs_key.only": ("这台电脑上没有不用 API Key 的办法。", "This computer has no way to do it without an API Key."), "needs_key.timing": ("不想用在线服务,也可以让 agent 在这台电脑上对时间。", "Or ask the agent to time the words on this computer, with no service."), "needs_key.music": ("不想用在线服务,也可以让 agent 在这台电脑上作曲。", "Or ask the agent to compose the music on this computer, with no service."), "needs_key.short": ("等 API Key", "waiting for an API Key"), @@ -448,36 +451,56 @@ def act_settings(label, sub): return {"kind": "settings", "mod": None, "sub": sub, "label": label} -LOCAL_WAY = {"tts": "voice", "voices": "voice", "pace": "timing", "music": "music"} # what works on this computer instead, by command +DOES = {"tts": {"voice", "timing"}, "voices": {"voice"}, "pace": {"timing"}, "music": {"music"}, "image": {"image"}} # the kinds of work a run that ended fine did +NEED_OF = {"tts": "voice", "voices": "voice", "pace": "timing", "music": "music", "image": "image"} # a record that does not say what its key was for -def needs_key(o): - """The run that stopped for want of a service's API Key (its record's code no_key, tools/keys.py) while that key is - still not set, as the newest run of its command: (run, the key names it waits on, the service), or None. Once the key - is set (in Studio or the environment), or the command ran again and did not stop for it, the film waits no more.""" - newest = {} - for r in (o.get("activity") or {}).get("recent") or []: - if r.get("state") in ("running", "gone") or not r.get("cmd"): +def need_of(r): + return (r.get("error") or {}).get("need") or NEED_OF.get(r.get("cmd")) + + +def key_stop(runs): + """The newest finished run that stopped for want of an API Key (code no_key) that nothing after it settled, or None. + A later run that did the same kind of work fine settles it (a voice-over clears a voice or a timing stop; a picture an + image stop); a later run of anything that failed or was cut off takes the line, since it is newer news; one stopped on + purpose, and the console's own run, count for neither. The whole log is read (bin/vh status passes it as + activity.key_stop), not a window of the last few runs.""" + done = [r for r in runs if r.get("state") in ("ok", "failed", "gone") and r.get("cmd") != "desk"] + at = max((i for i, r in enumerate(done) if r.get("state") == "failed" and (r.get("error") or {}).get("code") == "no_key"), default=None) + if at is None: + return None + need = need_of(done[at]) + for r in done[at + 1:]: + if r.get("cancelled") or r.get("exit") in (130, 143): continue - if (r.get("end") or 0) >= (newest.get(r["cmd"], {}).get("end") or 0): - newest[r["cmd"]] = r - hits = [r for r in newest.values() if r.get("exit") not in (0, None) and (r.get("error") or {}).get("code") == "no_key"] - if not hits: + if r.get("state") == "gone" or r.get("exit") != 0: + return None + if need in DOES.get(r.get("cmd"), ()): + return None + return done[at] + + +def needs_key(o): + """The run that stopped for want of a service's API Key (key_stop) while that key is still not set: (run, the key names + it waits on, the service, what the key was for), or None. Once a key it names is set (in Studio or the environment), + the film waits no more.""" + act = o.get("activity") or {} + r = act["key_stop"] if "key_stop" in act else key_stop(act.get("recent") or []) + if not r: return None try: import keys except Exception: return None - for r in sorted(hits, key=lambda x: x.get("end") or 0, reverse=True): - names = [n for n in keys.KEY_NAMES if re.search(r"\b" + n + r"\b", (r.get("error") or {}).get("message") or "")] - try: - left = keys.wanted(names) - except Exception: - left = [] - if left: - m = keys.module_of(left[0]) or {} - return r, left, m.get("name") - return None + err = r.get("error") or {} + names = [n for n in err.get("keys") or [] if n in keys.KEY_NAMES] or [n for n in keys.KEY_NAMES if re.search(r"\b" + n + r"\b", err.get("message") or "")] + try: + left = keys.wanted(names) + except Exception: + left = [] + if not left: + return None + return r, left, (keys.module_of(left[0]) or {}).get("name"), need_of(r) def act_tell(label, text, confirm=False, secondary=False): @@ -577,12 +600,16 @@ def seen(s): return say("no_record", who, "none", both("no_record"), [both("no_record.more")]) nk = needs_key(o) if nk: # only the person can give a key: what to do and where, and what works without one - r, names, svc = nk + r, names, svc, need = nk c, sv = cmd_words(r), both(f"svc.{svc}") if f"svc.{svc}" in WORDS else two(svc or "", svc or "") - way = LOCAL_WAY.get(r.get("cmd")) + try: # what does the same work with no key on this computer (the platform decides: tools/keys.py) + import keys + way = keys.local_way(need)[0] if need else None + except Exception: + way = None return say("needs_key", who, "decide", two(w("needs_key", 0, x=c[0], s=sv["zh"]), w("needs_key", 1, T=cap(c[2]), s=sv["en"])), - [both("needs_key.more"), both(f"needs_key.{way}") if way else None], both("needs_key.short"), - act_settings(both("act.settings"), "services"), cmd=r.get("cmd"), keys=names, service=svc) + [both("needs_key.more"), both(f"needs_key.{way}" if way else "needs_key.only")], both("needs_key.short"), + act_settings(both("act.settings"), "services"), cmd=r.get("cmd"), keys=names, service=svc, need=need) # the agent's move, and nothing works on the film now: the last thing seen and when; "stopped" only on positive evidence do = (o.get("next_step") or {}).get("do") or "" made = (o.get("media") or {}).get("film") or next((r["path"] for r in o.get("renders") or []), None) diff --git a/tools/status.py b/tools/status.py index 93288462..e98ae167 100644 --- a/tools/status.py +++ b/tools/status.py @@ -969,7 +969,7 @@ def vinfo(v, s): "open": {"review_items": open_items, "facts_to_verify": facts}, "renders": [vinfo(v, s) for v, s in vids[:10]], "deliveries": deliveries, "versions": vers, "check": check_summary(project, *checks[0]) if checks else None, "assets": assets, "cast": cast, "research": research, - "activity": {"running": working, "listening": listening, "recent": recent}, + "activity": {"running": working, "listening": listening, "recent": recent, "key_stop": standing.key_stop(runs)}, # (the whole log: a stop for an API Key nothing settled) "media": None, "next_step": None, "now": None, "plan": None} try: # what cannot be read is said, never a failure of status out["media"] = media(project)