Merge origin/main into child-run-auto-approval

Resolve conflicts with the run preparation removal: drop the prepare
types from the fabro-config import lists and keep the new children and
approvals types, keep both sets of appended workflow settings round-trip
tests, and keep [server.approvals] in the server configuration table
without [run.prepare].

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
Scott Werner 2026-10-28 15:39:59 -04:00
commit 7960ba5ff1
137 changed files with 3938 additions and 1867 deletions

View file

@ -3,6 +3,11 @@
slow-timeout = { period = "1s", terminate-after = 3 }
leak-timeout = "500ms"
# Real Docker worker crashes wait for supervisor cleanup and retain files.
[[profile.default.overrides]]
filter = "package(fabro-cli) & test(worker_crash_honors_the_docker_stop_policy_and_retains_files)"
slow-timeout = { period = "30s", terminate-after = 3 }
[[profile.default.overrides]]
filter = "package(fabro-cli)"
slow-timeout = { period = "6s", terminate-after = 4 }

View file

@ -55,7 +55,7 @@ RUN cargo install cargo-nextest --locked
ENV CARGO_INCREMENTAL=0
# Bun
RUN curl -fsSL https://bun.sh/install | bash
RUN curl -fsSL https://bun.sh/install | bash -s -- bun-v1.4.4
ENV PATH="/root/.bun/bin:${PATH}"
WORKDIR /root

View file

@ -40,7 +40,7 @@ RUN cargo install cargo-nextest --locked
ENV CARGO_INCREMENTAL=0
# Bun
RUN curl -fsSL https://bun.sh/install | bash
RUN curl -fsSL https://bun.sh/install | bash -s -- bun-v1.4.4
ENV PATH="/root/.bun/bin:${PATH}"
WORKDIR /root

View file

@ -45,7 +45,7 @@ jobs:
- uses: oven-sh/setup-bun@0c5077e51419868618aeaa5fe8019c62421857d6 # v2.2.0
if: steps.skip.outputs.skip != 'true'
with:
bun-version: 1.3.14
bun-version: 1.4.4
no-cache: true
- name: Install bun deps (for SPA verify)

View file

@ -49,7 +49,7 @@ jobs:
- uses: oven-sh/setup-bun@0c5077e51419868618aeaa5fe8019c62421857d6 # v2.2.0
with:
bun-version: 1.3.14
bun-version: 1.4.4
no-cache: true
- name: Install bun deps

View file

@ -45,7 +45,7 @@ jobs:
persist-credentials: false
- uses: oven-sh/setup-bun@0c5077e51419868618aeaa5fe8019c62421857d6 # v2.2.0
with:
bun-version: 1.3.14
bun-version: 1.4.4
- run: bun install --frozen-lockfile
- run: cd apps/fabro-web && bun run typecheck
- run: cd lib/packages/fabro-api-client && bun run typecheck
@ -61,7 +61,7 @@ jobs:
persist-credentials: false
- uses: oven-sh/setup-bun@0c5077e51419868618aeaa5fe8019c62421857d6 # v2.2.0
with:
bun-version: 1.3.14
bun-version: 1.4.4
- run: bun install --frozen-lockfile
- run: cd apps/fabro-web && bun run test
@ -76,7 +76,7 @@ jobs:
persist-credentials: false
- uses: oven-sh/setup-bun@0c5077e51419868618aeaa5fe8019c62421857d6 # v2.2.0
with:
bun-version: 1.3.14
bun-version: 1.4.4
- run: bun install --frozen-lockfile
- uses: dtolnay/rust-toolchain@631a55b12751854ce901bb631d5902ceb48146f7 # stable
with:

178
Cargo.lock generated
View file

@ -355,9 +355,9 @@ dependencies = [
[[package]]
name = "aws-lc-rs"
version = "1.16.3"
version = "1.18.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "0ec6fb3fe69024a75fa7e1bfb48aa6cf59706a101658ea01bfd33b2b248a038f"
checksum = "faac5829c2b74c28f830747e7818ccfb684261b5f48a1118b1e2a13d36dfab13"
dependencies = [
"aws-lc-sys",
"untrusted 0.7.1",
@ -366,14 +366,15 @@ dependencies = [
[[package]]
name = "aws-lc-sys"
version = "0.40.0"
version = "0.46.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "f50037ee5e1e41e7b8f9d161680a725bd1626cb6f8c7e901f91f942850852fe7"
checksum = "f1622d8446a2d4b2ce0c7eefc73dd43a99779028d5ee5c2dd8073a658ba8a2bc"
dependencies = [
"cc",
"cmake",
"dunce",
"fs_extra",
"pkg-config",
]
[[package]]
@ -1991,7 +1992,7 @@ dependencies = [
[[package]]
name = "fabro-api"
version = "0.387.0-nightly.0"
version = "0.400.0-nightly.0"
dependencies = [
"chrono",
"fabro-automation",
@ -2017,7 +2018,7 @@ dependencies = [
[[package]]
name = "fabro-auth"
version = "0.387.0-nightly.0"
version = "0.400.0-nightly.0"
dependencies = [
"anyhow",
"async-trait",
@ -2042,7 +2043,7 @@ dependencies = [
[[package]]
name = "fabro-automation"
version = "0.387.0-nightly.0"
version = "0.400.0-nightly.0"
dependencies = [
"anyhow",
"chrono",
@ -2063,11 +2064,11 @@ dependencies = [
[[package]]
name = "fabro-build-support"
version = "0.387.0-nightly.0"
version = "0.400.0-nightly.0"
[[package]]
name = "fabro-checkpoint"
version = "0.387.0-nightly.0"
version = "0.400.0-nightly.0"
dependencies = [
"fabro-config",
"fabro-types",
@ -2075,7 +2076,7 @@ dependencies = [
[[package]]
name = "fabro-cli"
version = "0.387.0-nightly.0"
version = "0.400.0-nightly.0"
dependencies = [
"anyhow",
"assert_cmd",
@ -2171,7 +2172,7 @@ dependencies = [
[[package]]
name = "fabro-client"
version = "0.387.0-nightly.0"
version = "0.400.0-nightly.0"
dependencies = [
"anyhow",
"bytes",
@ -2200,7 +2201,7 @@ dependencies = [
[[package]]
name = "fabro-config"
version = "0.387.0-nightly.0"
version = "0.400.0-nightly.0"
dependencies = [
"anyhow",
"chrono",
@ -2229,7 +2230,7 @@ dependencies = [
[[package]]
name = "fabro-db"
version = "0.387.0-nightly.0"
version = "0.400.0-nightly.0"
dependencies = [
"anyhow",
"chrono",
@ -2242,7 +2243,7 @@ dependencies = [
[[package]]
name = "fabro-dev"
version = "0.387.0-nightly.0"
version = "0.400.0-nightly.0"
dependencies = [
"anyhow",
"assert_cmd",
@ -2261,7 +2262,7 @@ dependencies = [
[[package]]
name = "fabro-dot"
version = "0.387.0-nightly.0"
version = "0.400.0-nightly.0"
dependencies = [
"fabro-template",
"fabro-types",
@ -2273,7 +2274,7 @@ dependencies = [
[[package]]
name = "fabro-dump"
version = "0.387.0-nightly.0"
version = "0.400.0-nightly.0"
dependencies = [
"anyhow",
"bytes",
@ -2287,7 +2288,7 @@ dependencies = [
[[package]]
name = "fabro-environment"
version = "0.387.0-nightly.0"
version = "0.400.0-nightly.0"
dependencies = [
"anyhow",
"chrono",
@ -2309,7 +2310,7 @@ dependencies = [
[[package]]
name = "fabro-github"
version = "0.387.0-nightly.0"
version = "0.400.0-nightly.0"
dependencies = [
"anyhow",
"async-trait",
@ -2334,7 +2335,7 @@ dependencies = [
[[package]]
name = "fabro-graphviz"
version = "0.387.0-nightly.0"
version = "0.400.0-nightly.0"
dependencies = [
"anyhow",
"fabro-dot",
@ -2344,7 +2345,7 @@ dependencies = [
[[package]]
name = "fabro-http"
version = "0.387.0-nightly.0"
version = "0.400.0-nightly.0"
dependencies = [
"fabro-static",
"http 1.4.0",
@ -2354,7 +2355,7 @@ dependencies = [
[[package]]
name = "fabro-install"
version = "0.387.0-nightly.0"
version = "0.400.0-nightly.0"
dependencies = [
"anyhow",
"fabro-config",
@ -2371,7 +2372,7 @@ dependencies = [
[[package]]
name = "fabro-interview"
version = "0.387.0-nightly.0"
version = "0.400.0-nightly.0"
dependencies = [
"async-trait",
"fabro-types",
@ -2383,7 +2384,7 @@ dependencies = [
[[package]]
name = "fabro-llm"
version = "0.387.0-nightly.0"
version = "0.400.0-nightly.0"
dependencies = [
"async-trait",
"bytes",
@ -2408,7 +2409,7 @@ dependencies = [
[[package]]
name = "fabro-macros"
version = "0.387.0-nightly.0"
version = "0.400.0-nightly.0"
dependencies = [
"clap",
"fabro-options-metadata",
@ -2419,7 +2420,7 @@ dependencies = [
[[package]]
name = "fabro-manifest"
version = "0.387.0-nightly.0"
version = "0.400.0-nightly.0"
dependencies = [
"anyhow",
"async-trait",
@ -2448,7 +2449,7 @@ dependencies = [
[[package]]
name = "fabro-mcp-server"
version = "0.387.0-nightly.0"
version = "0.400.0-nightly.0"
dependencies = [
"anyhow",
"fabro-client",
@ -2468,7 +2469,7 @@ dependencies = [
[[package]]
name = "fabro-mcp-store"
version = "0.387.0-nightly.0"
version = "0.400.0-nightly.0"
dependencies = [
"chrono",
"fabro-db",
@ -2486,7 +2487,7 @@ dependencies = [
[[package]]
name = "fabro-oauth"
version = "0.387.0-nightly.0"
version = "0.400.0-nightly.0"
dependencies = [
"anyhow",
"axum",
@ -2508,7 +2509,7 @@ dependencies = [
[[package]]
name = "fabro-options-metadata"
version = "0.387.0-nightly.0"
version = "0.400.0-nightly.0"
dependencies = [
"serde",
"serde_json",
@ -2516,7 +2517,7 @@ dependencies = [
[[package]]
name = "fabro-petri"
version = "0.387.0-nightly.0"
version = "0.400.0-nightly.0"
dependencies = [
"anyhow",
"async-trait",
@ -2571,7 +2572,7 @@ dependencies = [
[[package]]
name = "fabro-proc"
version = "0.387.0-nightly.0"
version = "0.400.0-nightly.0"
dependencies = [
"libc",
"tempfile",
@ -2583,7 +2584,7 @@ dependencies = [
[[package]]
name = "fabro-redact"
version = "0.387.0-nightly.0"
version = "0.400.0-nightly.0"
dependencies = [
"aho-corasick",
"pebble-coding-agent",
@ -2595,12 +2596,13 @@ dependencies = [
"toml 0.8.23",
"tracing",
"tracing-subscriber",
"ulid",
"url",
]
[[package]]
name = "fabro-server"
version = "0.387.0-nightly.0"
version = "0.400.0-nightly.0"
dependencies = [
"anyhow",
"async-trait",
@ -2695,7 +2697,7 @@ dependencies = [
[[package]]
name = "fabro-slack"
version = "0.387.0-nightly.0"
version = "0.400.0-nightly.0"
dependencies = [
"fabro-http",
"fabro-interview",
@ -2716,18 +2718,18 @@ dependencies = [
[[package]]
name = "fabro-spa"
version = "0.387.0-nightly.0"
version = "0.400.0-nightly.0"
dependencies = [
"rust-embed",
]
[[package]]
name = "fabro-static"
version = "0.387.0-nightly.0"
version = "0.400.0-nightly.0"
[[package]]
name = "fabro-store"
version = "0.387.0-nightly.0"
version = "0.400.0-nightly.0"
dependencies = [
"bytes",
"chrono",
@ -2755,7 +2757,7 @@ dependencies = [
[[package]]
name = "fabro-telemetry"
version = "0.387.0-nightly.0"
version = "0.400.0-nightly.0"
dependencies = [
"anyhow",
"base64",
@ -2781,7 +2783,7 @@ dependencies = [
[[package]]
name = "fabro-template"
version = "0.387.0-nightly.0"
version = "0.400.0-nightly.0"
dependencies = [
"anyhow",
"fabro-types",
@ -2795,7 +2797,7 @@ dependencies = [
[[package]]
name = "fabro-test"
version = "0.387.0-nightly.0"
version = "0.400.0-nightly.0"
dependencies = [
"anyhow",
"assert_cmd",
@ -2820,7 +2822,7 @@ dependencies = [
[[package]]
name = "fabro-tool"
version = "0.387.0-nightly.0"
version = "0.400.0-nightly.0"
dependencies = [
"anyhow",
"async-trait",
@ -2844,7 +2846,7 @@ dependencies = [
[[package]]
name = "fabro-tracker"
version = "0.387.0-nightly.0"
version = "0.400.0-nightly.0"
dependencies = [
"anyhow",
"async-trait",
@ -2858,7 +2860,7 @@ dependencies = [
[[package]]
name = "fabro-types"
version = "0.387.0-nightly.0"
version = "0.400.0-nightly.0"
dependencies = [
"chrono",
"clap",
@ -2885,7 +2887,7 @@ dependencies = [
[[package]]
name = "fabro-util"
version = "0.387.0-nightly.0"
version = "0.400.0-nightly.0"
dependencies = [
"anyhow",
"console 0.15.11",
@ -2908,7 +2910,7 @@ dependencies = [
[[package]]
name = "fabro-variable"
version = "0.387.0-nightly.0"
version = "0.400.0-nightly.0"
dependencies = [
"anyhow",
"chrono",
@ -2925,7 +2927,7 @@ dependencies = [
[[package]]
name = "fabro-vault"
version = "0.387.0-nightly.0"
version = "0.400.0-nightly.0"
dependencies = [
"anyhow",
"chrono",
@ -2944,7 +2946,7 @@ dependencies = [
[[package]]
name = "fabro-workflow"
version = "0.387.0-nightly.0"
version = "0.400.0-nightly.0"
dependencies = [
"anyhow",
"async-trait",
@ -2989,7 +2991,7 @@ dependencies = [
[[package]]
name = "fabro-workflow-version"
version = "0.387.0-nightly.0"
version = "0.400.0-nightly.0"
dependencies = [
"fabro-config",
"fabro-dot",
@ -3716,7 +3718,7 @@ dependencies = [
"tokio",
"tokio-rustls",
"tower-service",
"webpki-roots 1.0.6",
"webpki-roots 1.0.10",
]
[[package]]
@ -4301,7 +4303,7 @@ checksum = "6373607a59f0be73a39b6fe456b8192fcc3585f602af20751600e974dd455e77"
[[package]]
name = "lithos-llm"
version = "0.1.0"
source = "git+https://github.com/lithoscomputer/lithos-llm?branch=main#b47b0065df903cb759a0911100d151bd04fc5546"
source = "git+https://github.com/lithoscomputer/lithos-llm?branch=main#e8fd3ecf593fa943646ad5cd7bf584fa117dfca9"
dependencies = [
"async-trait",
"aws-config",
@ -5091,7 +5093,7 @@ checksum = "df94ce210e5bc13cb6651479fa48d14f601d9858cfe0467f43ae157023b938d3"
[[package]]
name = "pebble-agent"
version = "0.1.0"
source = "git+https://github.com/lithoscomputer/pebble?branch=main#68955515624540dc582636e377ddc3210dec8503"
source = "git+https://github.com/lithoscomputer/pebble?branch=main#65a3bab8b35f4ce46ef0742599511a331de5885b"
dependencies = [
"async-trait",
"futures-util",
@ -5108,7 +5110,7 @@ dependencies = [
[[package]]
name = "pebble-cli-core"
version = "0.1.0"
source = "git+https://github.com/lithoscomputer/pebble?branch=main#68955515624540dc582636e377ddc3210dec8503"
source = "git+https://github.com/lithoscomputer/pebble?branch=main#65a3bab8b35f4ce46ef0742599511a331de5885b"
dependencies = [
"anyhow",
"async-trait",
@ -5137,7 +5139,7 @@ dependencies = [
[[package]]
name = "pebble-coding-agent"
version = "0.1.0"
source = "git+https://github.com/lithoscomputer/pebble?branch=main#68955515624540dc582636e377ddc3210dec8503"
source = "git+https://github.com/lithoscomputer/pebble?branch=main#65a3bab8b35f4ce46ef0742599511a331de5885b"
dependencies = [
"async-trait",
"futures-util",
@ -5179,7 +5181,7 @@ checksum = "9b4f627cb1b25917193a259e49bdad08f671f8d9708acfd5fe0a8c1455d87220"
[[package]]
name = "petri-attractor-steps"
version = "0.1.0"
source = "git+https://github.com/lithoscomputer/petri.git?branch=main#56ec3849ca693974ff778aa5ad4f9f9410d47d29"
source = "git+https://github.com/lithoscomputer/petri.git?branch=main#cfd57a52245e54b702d60321d94144800fdd92c2"
dependencies = [
"async-trait",
"globset",
@ -5210,7 +5212,7 @@ dependencies = [
[[package]]
name = "petri-driver"
version = "0.1.0"
source = "git+https://github.com/lithoscomputer/petri.git?branch=main#56ec3849ca693974ff778aa5ad4f9f9410d47d29"
source = "git+https://github.com/lithoscomputer/petri.git?branch=main#cfd57a52245e54b702d60321d94144800fdd92c2"
dependencies = [
"async-trait",
"getrandom 0.3.4",
@ -5230,7 +5232,7 @@ dependencies = [
[[package]]
name = "petri-engine"
version = "0.1.0"
source = "git+https://github.com/lithoscomputer/petri.git?branch=main#56ec3849ca693974ff778aa5ad4f9f9410d47d29"
source = "git+https://github.com/lithoscomputer/petri.git?branch=main#cfd57a52245e54b702d60321d94144800fdd92c2"
dependencies = [
"petri-ir",
"serde",
@ -5242,7 +5244,7 @@ dependencies = [
[[package]]
name = "petri-execution"
version = "0.1.0"
source = "git+https://github.com/lithoscomputer/petri.git?branch=main#56ec3849ca693974ff778aa5ad4f9f9410d47d29"
source = "git+https://github.com/lithoscomputer/petri.git?branch=main#cfd57a52245e54b702d60321d94144800fdd92c2"
dependencies = [
"async-trait",
"petri-driver",
@ -5266,7 +5268,7 @@ dependencies = [
[[package]]
name = "petri-executor"
version = "0.1.0"
source = "git+https://github.com/lithoscomputer/petri.git?branch=main#56ec3849ca693974ff778aa5ad4f9f9410d47d29"
source = "git+https://github.com/lithoscomputer/petri.git?branch=main#cfd57a52245e54b702d60321d94144800fdd92c2"
dependencies = [
"async-trait",
"libc",
@ -5281,7 +5283,7 @@ dependencies = [
[[package]]
name = "petri-executor-sandbox"
version = "0.1.0"
source = "git+https://github.com/lithoscomputer/petri.git?branch=main#56ec3849ca693974ff778aa5ad4f9f9410d47d29"
source = "git+https://github.com/lithoscomputer/petri.git?branch=main#cfd57a52245e54b702d60321d94144800fdd92c2"
dependencies = [
"async-trait",
"petri-executor",
@ -5303,7 +5305,7 @@ dependencies = [
[[package]]
name = "petri-frontend"
version = "0.1.0"
source = "git+https://github.com/lithoscomputer/petri.git?branch=main#56ec3849ca693974ff778aa5ad4f9f9410d47d29"
source = "git+https://github.com/lithoscomputer/petri.git?branch=main#cfd57a52245e54b702d60321d94144800fdd92c2"
dependencies = [
"marked-yaml",
"petri-ir",
@ -5317,7 +5319,7 @@ dependencies = [
[[package]]
name = "petri-frontend-attractor"
version = "0.1.0"
source = "git+https://github.com/lithoscomputer/petri.git?branch=main#56ec3849ca693974ff778aa5ad4f9f9410d47d29"
source = "git+https://github.com/lithoscomputer/petri.git?branch=main#cfd57a52245e54b702d60321d94144800fdd92c2"
dependencies = [
"minijinja",
"petri-frontend",
@ -5334,7 +5336,7 @@ dependencies = [
[[package]]
name = "petri-frontend-fabro"
version = "0.1.0"
source = "git+https://github.com/lithoscomputer/petri.git?branch=main#56ec3849ca693974ff778aa5ad4f9f9410d47d29"
source = "git+https://github.com/lithoscomputer/petri.git?branch=main#cfd57a52245e54b702d60321d94144800fdd92c2"
dependencies = [
"petri-frontend",
"petri-frontend-attractor",
@ -5342,7 +5344,6 @@ dependencies = [
"regex",
"serde",
"serde_json",
"shlex",
"smol_str",
"toml 0.9.12+spec-1.1.0",
]
@ -5350,7 +5351,7 @@ dependencies = [
[[package]]
name = "petri-frontend-native"
version = "0.1.0"
source = "git+https://github.com/lithoscomputer/petri.git?branch=main#56ec3849ca693974ff778aa5ad4f9f9410d47d29"
source = "git+https://github.com/lithoscomputer/petri.git?branch=main#cfd57a52245e54b702d60321d94144800fdd92c2"
dependencies = [
"petri-frontend",
"petri-ir",
@ -5361,7 +5362,7 @@ dependencies = [
[[package]]
name = "petri-ir"
version = "0.1.0"
source = "git+https://github.com/lithoscomputer/petri.git?branch=main#56ec3849ca693974ff778aa5ad4f9f9410d47d29"
source = "git+https://github.com/lithoscomputer/petri.git?branch=main#cfd57a52245e54b702d60321d94144800fdd92c2"
dependencies = [
"regex",
"serde",
@ -5374,7 +5375,7 @@ dependencies = [
[[package]]
name = "petri-runtime"
version = "0.1.0"
source = "git+https://github.com/lithoscomputer/petri.git?branch=main#56ec3849ca693974ff778aa5ad4f9f9410d47d29"
source = "git+https://github.com/lithoscomputer/petri.git?branch=main#cfd57a52245e54b702d60321d94144800fdd92c2"
dependencies = [
"async-trait",
"petri-driver",
@ -5395,7 +5396,7 @@ dependencies = [
[[package]]
name = "petri-steps"
version = "0.1.0"
source = "git+https://github.com/lithoscomputer/petri.git?branch=main#56ec3849ca693974ff778aa5ad4f9f9410d47d29"
source = "git+https://github.com/lithoscomputer/petri.git?branch=main#cfd57a52245e54b702d60321d94144800fdd92c2"
dependencies = [
"async-trait",
"petri-executor",
@ -5411,7 +5412,7 @@ dependencies = [
[[package]]
name = "petri-store"
version = "0.1.0"
source = "git+https://github.com/lithoscomputer/petri.git?branch=main#56ec3849ca693974ff778aa5ad4f9f9410d47d29"
source = "git+https://github.com/lithoscomputer/petri.git?branch=main#cfd57a52245e54b702d60321d94144800fdd92c2"
dependencies = [
"async-trait",
"getrandom 0.3.4",
@ -5426,7 +5427,7 @@ dependencies = [
[[package]]
name = "petri-testkit"
version = "0.1.0"
source = "git+https://github.com/lithoscomputer/petri.git?branch=main#56ec3849ca693974ff778aa5ad4f9f9410d47d29"
source = "git+https://github.com/lithoscomputer/petri.git?branch=main#cfd57a52245e54b702d60321d94144800fdd92c2"
dependencies = [
"async-trait",
"petri-driver",
@ -6018,7 +6019,7 @@ dependencies = [
"wasm-bindgen-futures",
"wasm-streams 0.4.2",
"web-sys",
"webpki-roots 1.0.6",
"webpki-roots 1.0.10",
]
[[package]]
@ -6283,9 +6284,9 @@ checksum = "f87165f0995f63a9fbeea62b64d10b4d9d8e78ec6d7d51fb2125fda7bb36788f"
[[package]]
name = "rustls-webpki"
version = "0.103.13"
version = "0.103.16"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "61c429a8649f110dddef65e2a5ad240f747e85f7758a6bccc7e5777bd33f756e"
checksum = "4443b1b6d39d7c663139942cc4558262562d2c84123bb6282ef177009ca8b281"
dependencies = [
"aws-lc-rs",
"ring",
@ -6317,24 +6318,27 @@ dependencies = [
[[package]]
name = "sandbox-driver"
version = "0.1.0"
source = "git+https://github.com/lithoscomputer/sandbox-driver?branch=main#4b35158b591337a9ac17295ca53158f9e8ce4029"
source = "git+https://github.com/lithoscomputer/sandbox-driver?branch=main#e5e9582567524963b689d23e868f4dd2c342fa74"
dependencies = [
"async-trait",
"futures-util",
"globset",
"humantime",
"jsonschema",
"rand 0.10.1",
"serde",
"serde_json",
"thiserror 2.0.18",
"tokio",
"tokio-util",
"toml 0.8.23",
"tracing",
]
[[package]]
name = "sandbox-driver-daytona"
version = "0.1.0"
source = "git+https://github.com/lithoscomputer/sandbox-driver?branch=main#4b35158b591337a9ac17295ca53158f9e8ce4029"
source = "git+https://github.com/lithoscomputer/sandbox-driver?branch=main#e5e9582567524963b689d23e868f4dd2c342fa74"
dependencies = [
"anyhow",
"async-trait",
@ -6362,7 +6366,7 @@ dependencies = [
[[package]]
name = "sandbox-driver-daytona-config"
version = "0.1.0"
source = "git+https://github.com/lithoscomputer/sandbox-driver?branch=main#4b35158b591337a9ac17295ca53158f9e8ce4029"
source = "git+https://github.com/lithoscomputer/sandbox-driver?branch=main#e5e9582567524963b689d23e868f4dd2c342fa74"
dependencies = [
"sandbox-driver-docker-config",
"serde",
@ -6372,7 +6376,7 @@ dependencies = [
[[package]]
name = "sandbox-driver-docker"
version = "0.1.0"
source = "git+https://github.com/lithoscomputer/sandbox-driver?branch=main#4b35158b591337a9ac17295ca53158f9e8ce4029"
source = "git+https://github.com/lithoscomputer/sandbox-driver?branch=main#e5e9582567524963b689d23e868f4dd2c342fa74"
dependencies = [
"anyhow",
"async-trait",
@ -6393,7 +6397,7 @@ dependencies = [
[[package]]
name = "sandbox-driver-docker-config"
version = "0.1.0"
source = "git+https://github.com/lithoscomputer/sandbox-driver?branch=main#4b35158b591337a9ac17295ca53158f9e8ce4029"
source = "git+https://github.com/lithoscomputer/sandbox-driver?branch=main#e5e9582567524963b689d23e868f4dd2c342fa74"
dependencies = [
"serde",
"serde_json",
@ -6402,7 +6406,7 @@ dependencies = [
[[package]]
name = "sandbox-driver-host"
version = "0.1.0"
source = "git+https://github.com/lithoscomputer/sandbox-driver?branch=main#4b35158b591337a9ac17295ca53158f9e8ce4029"
source = "git+https://github.com/lithoscomputer/sandbox-driver?branch=main#e5e9582567524963b689d23e868f4dd2c342fa74"
dependencies = [
"anyhow",
"async-trait",
@ -6420,7 +6424,7 @@ dependencies = [
[[package]]
name = "sandbox-driver-protocol"
version = "0.1.0"
source = "git+https://github.com/lithoscomputer/sandbox-driver?branch=main#4b35158b591337a9ac17295ca53158f9e8ce4029"
source = "git+https://github.com/lithoscomputer/sandbox-driver?branch=main#e5e9582567524963b689d23e868f4dd2c342fa74"
dependencies = [
"async-trait",
"base64",
@ -6437,11 +6441,13 @@ dependencies = [
[[package]]
name = "sandbox-driver-testing"
version = "0.1.0"
source = "git+https://github.com/lithoscomputer/sandbox-driver?branch=main#4b35158b591337a9ac17295ca53158f9e8ce4029"
source = "git+https://github.com/lithoscomputer/sandbox-driver?branch=main#e5e9582567524963b689d23e868f4dd2c342fa74"
dependencies = [
"async-trait",
"sandbox-driver",
"serde_json",
"tokio",
"tokio-util",
]
[[package]]
@ -7925,7 +7931,7 @@ dependencies = [
[[package]]
name = "twin-github"
version = "0.387.0-nightly.0"
version = "0.400.0-nightly.0"
dependencies = [
"axum",
"base64",
@ -8427,9 +8433,9 @@ dependencies = [
[[package]]
name = "webpki-root-certs"
version = "1.0.6"
version = "1.0.10"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "804f18a4ac2676ffb4e8b5b5fa9ae38af06df08162314f96a68d2a363e21a8ca"
checksum = "58ec80e73fd8baf57bf0d9615554c75348bda990d6d5bbeab964dd068319fecb"
dependencies = [
"rustls-pki-types",
]
@ -8440,14 +8446,14 @@ version = "0.26.11"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "521bc38abb08001b01866da9f51eb7c5d647a19260e00054a8c7fd5f9e57f7a9"
dependencies = [
"webpki-roots 1.0.6",
"webpki-roots 1.0.10",
]
[[package]]
name = "webpki-roots"
version = "1.0.6"
version = "1.0.10"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "22cfaf3c063993ff62e73cb4311efde4db1efb31ab78a3e5c457939ad5cc0bed"
checksum = "1c1c8e20c8a38fc7d65abfe74eb7280e4aa667e8eec8bc84996d2874810748d9"
dependencies = [
"rustls-pki-types",
]

View file

@ -10,7 +10,7 @@ resolver = "2"
[workspace.package]
edition = "2021"
version = "0.387.0-nightly.0"
version = "0.400.0-nightly.0"
license = "MIT"
[workspace.dependencies]

View file

@ -1,9 +1,16 @@
import { describe, expect, test } from "bun:test";
import { createElement, useState } from "react";
import TestRenderer, { act } from "react-test-renderer";
import type { Environment, EnvironmentResourcesSettings } from "@qltysh/fabro-api-client";
import { setupReactTestEnv } from "../lib/test-utils";
import {
EMPTY_ENVIRONMENT_FORM,
EnvironmentFormFields,
createRequestFromForm,
environmentToFormValues,
isEnvironmentFormValid,
replaceRequestFromForm,
type EnvironmentFormValues,
} from "./environment-form";
@ -48,3 +55,115 @@ describe("environment image source", () => {
expect(request.image.dockerfile?.value).toBe("FROM ubuntu");
});
});
function environment(resources: EnvironmentResourcesSettings): Environment {
return {
id: "roundtrip",
revision: "revision-1",
provider: "docker",
image: { docker: "ubuntu:24.04", dockerfile: null },
resources,
network: { mode: "allow_all", allow: [] },
lifecycle: { preserve: false, stop_on_terminal: true, auto_stop: null },
labels: { owner: "api", purpose: "roundtrip" },
env: { TZ: "UTC" },
};
}
describe("environment resource round trips", () => {
const cases: EnvironmentResourcesSettings[] = [
// API response for 512MiB; regression originally reported in #952.
{ cpu: null, memory: "536870912B", disk: null },
{ cpu: 4, memory: "4GB", disk: "8GB" },
{ cpu: null, memory: null, disk: null },
{ cpu: 32, memory: "64GB", disk: "2TB" },
{ cpu: 1, memory: "512MiB", disk: "1GiB" },
{ cpu: 2, memory: "1.5GB", disk: "512MB" },
{ cpu: 2, memory: "1B", disk: "1TiB" },
];
for (const resources of cases) {
test(`no-op save preserves ${JSON.stringify(resources)}`, () => {
const original = environment(resources);
const { id, revision, ...settings } = original;
expect(replaceRequestFromForm(environmentToFormValues(original))).toEqual(settings);
});
test(`unrelated edits preserve ${JSON.stringify(resources)} and labels`, () => {
const original = environment(resources);
const values = environmentToFormValues(original);
const saved = replaceRequestFromForm({
...values,
dockerRef: "ubuntu:26.04",
preserve: true,
autoStop: "30m",
envVars: [...values.envVars, { key: "EDITOR", value: "vi" }],
});
expect(saved.resources).toEqual(resources);
expect(saved.labels).toEqual(original.labels);
expect(saved.image.docker).toBe("ubuntu:26.04");
expect(saved.lifecycle).toEqual({ preserve: true, stop_on_terminal: true, auto_stop: "30m" });
expect(saved.env).toEqual({ TZ: "UTC", EDITOR: "vi" });
});
}
test("editing one resource preserves the other resources", () => {
const values = environmentToFormValues(environment(cases[0]));
expect(replaceRequestFromForm({ ...values, cpu: 6 }).resources).toEqual({
...cases[0], cpu: 6,
});
expect(replaceRequestFromForm({ ...values, memory: "6GB" }).resources).toEqual({
...cases[0], memory: "6GB",
});
expect(replaceRequestFromForm({ ...values, disk: "12GB" }).resources).toEqual({
...cases[0], disk: "12GB",
});
});
test("new environments keep the existing resource defaults", () => {
expect(createRequestFromForm(form({ dockerRef: "ubuntu:24.04" })).resources)
.toEqual({ cpu: 4, memory: "8GB", disk: "16GB" });
});
});
test("sliders preserve loaded resources until that specific slider changes", () => {
const cleanup = setupReactTestEnv();
let renderer: TestRenderer.ReactTestRenderer | undefined;
let saved: ReturnType<typeof replaceRequestFromForm> | undefined;
function Editor() {
const [values, setValues] = useState(() => environmentToFormValues(environment({
cpu: null, memory: "536870912B", disk: null,
})));
saved = replaceRequestFromForm(values);
return createElement(EnvironmentFormFields, { values, onChange: setValues, lockId: true });
}
try {
act(() => { renderer = TestRenderer.create(createElement(Editor)); });
const input = (label: string) => renderer!.root.findByProps({ "aria-label": label });
for (const [label, min, max] of [["CPU", 1, 8], ["Memory", 1, 16], ["Disk", 1, 20]] as const) {
expect(input(label).props.type).toBe("range");
expect(input(label).props.min).toBe(min);
expect(input(label).props.max).toBe(max);
expect(input(label).props.step).toBe(1);
}
expect(input("CPU").props["aria-valuetext"]).toBe("Provider default");
expect(input("Memory").props.value).toBe(1);
expect(input("Memory").props["aria-valuetext"]).toBe("536870912B");
expect(input("Disk").props["aria-valuetext"]).toBe("Provider default");
act(() => { input("Image reference").props.onChange({ target: { value: "alpine:latest" } }); });
expect(saved!.resources).toEqual({ cpu: null, memory: "536870912B", disk: null });
expect(saved!.labels).toEqual({ owner: "api", purpose: "roundtrip" });
act(() => { input("CPU").props.onChange({ target: { value: "6" } }); });
expect(saved!.resources).toEqual({ cpu: 6, memory: "536870912B", disk: null });
// Selecting the displayed fallback is an explicit edit, even when the
// numeric position matches the initial projection of the loaded value.
act(() => { input("Memory").props.onChange({ target: { value: "2" } }); });
act(() => { input("Memory").props.onChange({ target: { value: "1" } }); });
expect(saved!.resources).toEqual({ cpu: 6, memory: "1GB", disk: null });
act(() => { input("Disk").props.onChange({ target: { value: "12" } }); });
expect(saved!.resources).toEqual({ cpu: 6, memory: "1GB", disk: "12GB" });
} finally {
act(() => { renderer?.unmount(); });
cleanup();
}
});

View file

@ -39,8 +39,8 @@ export function parseCreatableProvider(value: string | null): string {
// Environment ids are server-managed file names: lowercase, digits, hyphens.
const ENVIRONMENT_ID_PATTERN = /^[a-z0-9][a-z0-9-]{0,62}$/;
// Resource sliders pick a concrete value within a fixed range. Memory and disk
// are expressed in whole GB; the wire format keeps the `GB` suffix string.
// Sliders select values within these ranges; loaded API values remain intact
// until the user moves that resource's slider.
const CPU = { min: 1, max: 8, step: 1, default: 4 };
const MEMORY = { min: 1, max: 16, step: 1, default: 8 };
const DISK = { min: 1, max: 20, step: 1, default: 16 };
@ -57,9 +57,9 @@ export interface EnvironmentFormValues {
imageSource: ImageSource;
dockerRef: string;
dockerfile: string;
cpu: number;
memory: number;
disk: number;
cpu: number | null;
memory: string | null;
disk: string | null;
blockNetwork: boolean;
preserve: boolean;
stopOnTerminal: boolean;
@ -78,8 +78,8 @@ export const EMPTY_ENVIRONMENT_FORM: EnvironmentFormValues = {
dockerRef: "",
dockerfile: "",
cpu: CPU.default,
memory: MEMORY.default,
disk: DISK.default,
memory: `${MEMORY.default}GB`,
disk: `${DISK.default}GB`,
blockNetwork: false,
preserve: false,
stopOnTerminal: true,
@ -95,9 +95,9 @@ export function environmentToFormValues(environment: Environment): EnvironmentFo
imageSource: environment.image.dockerfile ? "dockerfile" : "image",
dockerRef: environment.image.docker ?? "",
dockerfile: environment.image.dockerfile?.value ?? "",
cpu: clampGb(environment.resources.cpu, CPU),
memory: parseGb(environment.resources.memory, MEMORY),
disk: parseGb(environment.resources.disk, DISK),
cpu: environment.resources.cpu,
memory: environment.resources.memory,
disk: environment.resources.disk,
blockNetwork: environment.network.mode === EnvironmentNetworkMode.BLOCK,
preserve: environment.lifecycle.preserve,
stopOnTerminal: environment.lifecycle.stop_on_terminal,
@ -169,8 +169,8 @@ function imageFromForm(values: EnvironmentFormValues): EnvironmentApiImageSettin
function resourcesFromForm(values: EnvironmentFormValues): EnvironmentResourcesSettings {
return {
cpu: values.cpu,
memory: `${values.memory}GB`,
disk: `${values.disk}GB`,
memory: values.memory,
disk: values.disk,
};
}
@ -181,8 +181,8 @@ interface ResourceRange {
default: number;
}
// Snap a numeric value into the slider range, falling back to the default when
// the environment leaves the resource unset (provider default).
// Project values onto the slider for display only. Never serialize this
// rounded/clamped position unless the user explicitly changes the slider.
function clampGb(value: number | null, range: ResourceRange): number {
if (value === null) return range.default;
return Math.min(range.max, Math.max(range.min, Math.round(value)));
@ -198,9 +198,10 @@ function parseGb(value: string | null, range: ResourceRange): number {
const amount = Number(match[1]);
if (!Number.isFinite(amount)) return range.default;
const perGb: { [unit: string]: number } = {
"": 1, g: 1, gb: 1, gib: 1,
m: 1 / 1000, mb: 1 / 1000, mib: 1 / 1000,
t: 1000, tb: 1000, tib: 1000,
"": 1, g: 1, gb: 1, gib: 1024 ** 3 / 1e9,
b: 1 / 1e9, k: 1e-6, kb: 1e-6, kib: 1024 / 1e9,
m: 1 / 1000, mb: 1 / 1000, mib: 1024 ** 2 / 1e9,
t: 1000, tb: 1000, tib: 1024 ** 4 / 1e9,
};
const factor = perGb[match[2].toLowerCase()] ?? 1;
return clampGb(amount * factor, range);
@ -322,27 +323,27 @@ export function EnvironmentFormFields({
<ResourceSlider
ariaLabel="CPU"
range={CPU}
value={values.cpu}
value={clampGb(values.cpu, CPU)}
onChange={(cpu) => patch({ cpu })}
format={(n) => `${n} CPU`}
displayValue={values.cpu === null ? "Provider default" : `${values.cpu} CPU`}
/>
</Row>
<Row title="Memory" help="Memory limit for each run.">
<ResourceSlider
ariaLabel="Memory"
range={MEMORY}
value={values.memory}
onChange={(memory) => patch({ memory })}
format={(n) => `${n} GB`}
value={parseGb(values.memory, MEMORY)}
onChange={(memory) => patch({ memory: `${memory}GB` })}
displayValue={values.memory?.replace(/GB$/, " GB") ?? "Provider default"}
/>
</Row>
<Row title="Disk" help="Disk limit for each run.">
<ResourceSlider
ariaLabel="Disk"
range={DISK}
value={values.disk}
onChange={(disk) => patch({ disk })}
format={(n) => `${n} GB`}
value={parseGb(values.disk, DISK)}
onChange={(disk) => patch({ disk: `${disk}GB` })}
displayValue={values.disk?.replace(/GB$/, " GB") ?? "Provider default"}
/>
</Row>
</Panel>
@ -429,13 +430,13 @@ function ResourceSlider({
value,
range,
ariaLabel,
format,
displayValue,
onChange,
}: {
value: number;
range: ResourceRange;
ariaLabel: string;
format: (value: number) => string;
displayValue: string;
onChange: (value: number) => void;
}) {
const fill = ((value - range.min) / (range.max - range.min)) * 100;
@ -448,6 +449,7 @@ function ResourceSlider({
<input
type="range"
aria-label={ariaLabel}
aria-valuetext={displayValue}
value={value}
min={range.min}
max={range.max}
@ -456,8 +458,8 @@ function ResourceSlider({
className="relative h-4 w-full cursor-pointer appearance-none bg-transparent focus-visible:outline-none [&::-moz-range-thumb]:size-4 [&::-moz-range-thumb]:rounded-full [&::-moz-range-thumb]:border-0 [&::-moz-range-thumb]:bg-fg [&::-moz-range-thumb]:shadow-sm [&::-moz-range-track]:h-1.5 [&::-moz-range-track]:rounded-full [&::-moz-range-track]:bg-transparent [&::-webkit-slider-runnable-track]:h-1.5 [&::-webkit-slider-runnable-track]:rounded-full [&::-webkit-slider-runnable-track]:bg-transparent [&::-webkit-slider-thumb]:-mt-[5px] [&::-webkit-slider-thumb]:size-4 [&::-webkit-slider-thumb]:appearance-none [&::-webkit-slider-thumb]:rounded-full [&::-webkit-slider-thumb]:bg-fg [&::-webkit-slider-thumb]:shadow-sm [&::-webkit-slider-thumb]:outline [&::-webkit-slider-thumb]:outline-1 [&::-webkit-slider-thumb]:-outline-offset-1 [&::-webkit-slider-thumb]:outline-line-strong focus-visible:[&::-webkit-slider-thumb]:outline-2 focus-visible:[&::-webkit-slider-thumb]:outline-teal-500"
/>
</div>
<output className="w-16 shrink-0 text-right font-mono text-sm tabular-nums text-fg">
{format(value)}
<output className="min-w-16 shrink-0 text-right font-mono text-sm tabular-nums text-fg">
{displayValue}
</output>
</div>
);

View file

@ -0,0 +1,27 @@
import { describe, expect, test } from "bun:test";
import { renderToStaticMarkup } from "react-dom/server";
import { Markdown } from "./markdown";
describe("Markdown", () => {
test("renders GitHub-flavored Markdown", () => {
const html = renderToStaticMarkup(
<Markdown content={"# Plan\n\n- [x] Review this"} />,
);
expect(html).toContain("<h1>Plan</h1>");
expect(html).toContain('type="checkbox"');
expect(html).toContain("Review this");
});
test("strips raw HTML and unsafe URLs", () => {
const html = renderToStaticMarkup(
<Markdown
content={'<script>alert("no")</script>\n\n[bad](javascript:alert("no"))'}
/>,
);
expect(html).not.toContain("<script>");
expect(html).not.toContain("javascript:");
});
});

View file

@ -0,0 +1,47 @@
import { useMemo } from "react";
import { Marked } from "marked";
const SAFE_HTTP_URL_RE = /^https?:\/\//i;
const SAFE_MAILTO_URL_RE = /^mailto:/i;
function isSafeMarkdownHref(href: string): boolean {
return (
SAFE_HTTP_URL_RE.test(href) ||
SAFE_MAILTO_URL_RE.test(href) ||
href.startsWith("#") ||
(href.startsWith("/") && !href.startsWith("//"))
);
}
const markedSafe = new Marked();
markedSafe.use({
async: false,
walkTokens(token) {
if (
(token.type === "link" || token.type === "image") &&
typeof token.href === "string" &&
!isSafeMarkdownHref(token.href)
) {
token.href = "";
}
},
renderer: {
html() {
return "";
},
},
});
export function Markdown({ content }: { content: string }) {
const html = useMemo(
() => markedSafe.parse(content, { async: false }) as string,
[content],
);
return (
// react-doctor-disable-next-line react-doctor/no-danger -- markedSafe strips raw HTML and unsafe link/image URLs before rendering Markdown.
<div
className="prose prose-sm max-w-none text-fg-3 prose-headings:text-fg-2 prose-strong:text-fg-2 prose-code:rounded prose-code:bg-overlay-strong prose-code:px-1 prose-code:py-0.5 prose-code:text-[0.8em] prose-code:font-mono prose-code:text-fg-3 prose-code:before:content-none prose-code:after:content-none prose-pre:bg-overlay-strong prose-pre:text-fg-3 prose-a:text-teal-500"
dangerouslySetInnerHTML={{ __html: html }}
/>
);
}

View file

@ -1,93 +0,0 @@
import { useMemo } from "react";
import type { RunProjection } from "@qltysh/fabro-api-client";
import { formatAbsoluteTs } from "../lib/format";
import {
platformRecordsOf,
type PlatformRecordEntry,
} from "../lib/petri-stream";
import { useRunState, useRunStream } from "../lib/queries";
const KIND_LABEL: Record<string, string> = {
"checkpoint": "Checkpoint",
"pull_request.created": "Pull request",
"run.notice": "Notice",
"run.title": "Title",
"run.branch": "Run branch",
};
function kindLabel(kind: string): string {
return KIND_LABEL[kind] ?? kind;
}
/**
* The platform records of a Petri run: Fabro's own facts beside the engine's
* events (a checkpoint with its commit, a pull request, a notice), each with
* the stage it belongs to when it belongs to one.
*/
export function PlatformRecordsPanelView({
records,
projection,
}: {
records: PlatformRecordEntry[];
projection: RunProjection | null | undefined;
}) {
const pullRequest = projection?.pull_request ?? null;
if (records.length === 0 && !pullRequest) return null;
return (
<section
aria-label="Platform records"
className="rounded-md border border-line bg-panel/60 px-6 py-4"
>
<h3 className="text-[10px] font-medium uppercase tracking-[0.08em] text-fg-muted">
Platform records
</h3>
<ul className="mt-2 space-y-1 text-sm">
{pullRequest && (
<li className="flex items-baseline gap-3">
<span className="w-28 shrink-0 text-fg-muted">Pull request</span>
<a
href={pullRequest.html_url}
target="_blank"
rel="noreferrer"
className="truncate font-mono text-teal-500 hover:text-teal-300"
>
#{pullRequest.number}
</a>
</li>
)}
{records.map((record) => (
<li
key={record.streamSeq}
data-kind={record.kind}
className="flex items-baseline gap-3"
>
<span className="w-28 shrink-0 text-fg-muted">{kindLabel(record.kind)}</span>
<span className="min-w-0 flex-1 truncate font-mono text-fg-2">
{record.detail ?? "—"}
</span>
{record.stageKey && (
<span className="shrink-0 font-mono text-xs text-fg-muted">
stage {record.stageKey}
</span>
)}
<span className="shrink-0 font-mono text-xs tabular-nums text-fg-muted">
{formatAbsoluteTs(record.ts)}
</span>
</li>
))}
</ul>
</section>
);
}
/** The panel for a run: the platform records on its stream. */
export function PlatformRecordsPanel({ runId }: { runId: string }) {
const runStateQuery = useRunState(runId);
const streamQuery = useRunStream(runId);
const records = useMemo(
() => (streamQuery.data ? platformRecordsOf(streamQuery.data) : []),
[streamQuery.data],
);
return <PlatformRecordsPanelView records={records} projection={runStateQuery.data} />;
}

View file

@ -0,0 +1,64 @@
import { useRef, useState } from "react";
import { useNavigate } from "react-router";
import { useSWRConfig } from "swr";
import { mutateRunListCaches } from "../lib/board-cache";
import { queryKeys } from "../lib/query-keys";
import { mapError, retryRun } from "../lib/run-actions";
import { ConfirmDialog, ErrorMessage } from "./ui";
export function RetryRunDialog({
runId,
onClose,
}: {
runId: string;
onClose: () => void;
}) {
const navigate = useNavigate();
const { mutate } = useSWRConfig();
const inFlight = useRef(false);
const [pending, setPending] = useState(false);
const [error, setError] = useState<string | null>(null);
async function handleRetry() {
// Lock synchronously: two clicks can arrive before React renders pending.
if (inFlight.current) return;
inFlight.current = true;
setPending(true);
setError(null);
try {
const run = await retryRun(runId);
// Retry returns a different run; never replace the original's detail cache.
void mutate(queryKeys.runs.detail(run.id), run, { revalidate: false });
mutateRunListCaches(mutate);
onClose();
void navigate(`/runs/${encodeURIComponent(run.id)}`);
} catch (error) {
setError(mapError(error, "retry"));
} finally {
inFlight.current = false;
setPending(false);
}
}
return (
<ConfirmDialog
open
title="Retry this run?"
description={
<div className="space-y-3">
<p>Retry creates a new run from the saved specification and starts from the beginning.</p>
{error && <ErrorMessage message={error} />}
</div>
}
confirmLabel="Retry run"
pendingLabel="Creating run…"
tone="primary"
pending={pending}
onConfirm={() => void handleRetry()}
onCancel={() => {
if (!inFlight.current) onClose();
}}
/>
);
}

View file

@ -3,6 +3,7 @@ import { Link } from "react-router";
import { StageState, type RunStage } from "@qltysh/fabro-api-client";
import { HoverCard, PopoverHeader, PopoverRow, PopoverRows } from "./ui";
import { stagePath } from "../lib/stage-routes";
import { isVisibleStage } from "../data/runs";
import { formatAbsoluteTs, formatDurationMs } from "../lib/format";
import {
@ -150,7 +151,7 @@ function stageRow(runId: string, stage: RunStage, nowMs: number): Row | null {
endMs,
durationMs,
barClass: stageBarClass(stage.status),
href: `/runs/${runId}/stages/${encodeURIComponent(stage.id)}`,
href: stagePath(runId, stage.id),
popover: stagePopover(stage, durationMs, inFlight),
};
}

View file

@ -11,6 +11,7 @@ import {
canArchive,
canCancel,
canDelete,
canRetry,
canUnarchive,
cancellationActionLabel,
cancellationSuccessMessage,
@ -24,6 +25,7 @@ import {
} from "../../lib/run-actions";
import type { LifecycleAction } from "../../lib/run-actions";
import { useToast } from "../toast";
import { RetryRunDialog } from "../retry-run-dialog";
import { ConfirmDialog } from "../ui";
const MENU_ITEM_CLASS =
@ -37,12 +39,14 @@ export function RowActionsMenu({ run }: { run: RunWithStatus }) {
const { push } = useToast();
const [pendingAction, setPendingAction] = useState<LifecycleAction | "delete" | null>(null);
const [optimisticallyCancelled, setOptimisticallyCancelled] = useState(false);
const [retryDialogOpen, setRetryDialogOpen] = useState(false);
const [deleteDialogOpen, setDeleteDialogOpen] = useState(false);
const [idCopied, setIdCopied] = useState(false);
const status = run.lifecycleStatus;
const showApprove = run.pendingApproval === true;
const showDeny = run.pendingApproval === true;
const showRetry = canRetry(status);
const showArchive = canArchive(status);
const showUnarchive = canUnarchive(status);
const showCancel = canCancel(status);
@ -54,7 +58,7 @@ export function RowActionsMenu({ run }: { run: RunWithStatus }) {
);
const pending = pendingAction !== null || cancellationPending;
const hasLifecycle = showArchive || showUnarchive;
const hasLifecycle = showRetry || showArchive || showUnarchive;
const hasDestructive = showDeny || showCancel || showDelete;
async function runAction<T>(
@ -160,6 +164,18 @@ export function RowActionsMenu({ run }: { run: RunWithStatus }) {
</button>
</MenuItem>
)}
{showRetry && (
<MenuItem>
<button
type="button"
onClick={() => setRetryDialogOpen(true)}
disabled={pending}
className={MENU_ITEM_CLASS}
>
Retry
</button>
</MenuItem>
)}
{showArchive && (
<MenuItem>
<button
@ -233,6 +249,9 @@ export function RowActionsMenu({ run }: { run: RunWithStatus }) {
)}
</MenuItems>
</Menu>
{retryDialogOpen && (
<RetryRunDialog runId={run.id} onClose={() => setRetryDialogOpen(false)} />
)}
<ConfirmDialog
open={deleteDialogOpen}
title="Delete this run?"

View file

@ -1,6 +1,7 @@
import { Link } from "react-router";
import type { StageState } from "@qltysh/fabro-api-client";
import { stagePath } from "../lib/stage-routes";
import { formatTokenCount } from "../lib/format";
import {
formatStageLabel,
@ -106,7 +107,7 @@ export function StagePopover({ runId, stage, duration }: StagePopoverProps) {
{stage.resumedFromStageId && (
<PopoverRow label="Resumed from">
<Link
to={`/runs/${runId}/stages/${encodeURIComponent(stage.resumedFromStageId)}`}
to={stagePath(runId, stage.resumedFromStageId)}
className="font-mono text-teal-500 hover:underline"
>
{stage.resumedFromStageId}

View file

@ -0,0 +1,123 @@
import { afterEach, beforeEach, describe, expect, test } from "bun:test";
import type { RunStreamItem } from "@qltysh/fabro-api-client";
import TestRenderer, { act } from "react-test-renderer";
import { MemoryRouter } from "react-router";
import { findPetriEdgeForStage } from "../../lib/petri-stream";
import { makeStage, setupReactTestEnv, textContent } from "../../lib/test-utils";
import { ConditionalDecision } from "./conditional-decision";
let teardown: () => void;
let renderer: TestRenderer.ReactTestRenderer | undefined;
beforeEach(() => { teardown = setupReactTestEnv(); });
afterEach(() => {
if (renderer) act(() => renderer!.unmount());
renderer = undefined;
teardown();
});
// The reported decision: the false branch goes to a; the default goes to z.
function route(edge = 2, visit = 1) {
return {
run_id: "run-1", stream_seq: visit, kind: "petri", id: String(visit), recorded_at: 1,
item: {
subject: {
node: {
name: "gate", kind: "noop",
meta: {
kind: "conditional",
edges: {
"1": { to: "a", label: "Special", condition: "never=true" },
"2": { to: "z", label: "Default" },
} as Record<string, unknown> | undefined,
},
},
visit,
},
record: { body: { event: "route.applied", kind: "edge", edge: edge as unknown } },
derived: { target: { name: edge === 1 ? "a" : "z" } },
},
} satisfies RunStreamItem;
}
function renderDecision(stream: RunStreamItem[], visit = 1) {
const stage = makeStage({ id: `gate@${visit}`, nodeId: "gate", handler: "conditional", visit });
const targets = ["a", "z"].map((nodeId) => makeStage({ id: `${nodeId}@1`, nodeId }));
act(() => {
renderer = TestRenderer.create(
<MemoryRouter>
<ConditionalDecision
stage={stage}
edge={findPetriEdgeForStage(stream, stage.id)}
allStages={targets}
runId="run-1"
/>
</MemoryRouter>,
);
});
return {
details: renderer!.root.findAllByType("dd").map(textContent),
target: renderer!.root.findByType("a").props.href,
};
}
describe("Decision reason from the selected route", () => {
test.each([false, true])("an unconditional fallback is the default edge (replayed: %s)", (replay) => {
const stream = [route()];
expect(renderDecision(replay ? JSON.parse(JSON.stringify(stream)) : stream)).toEqual({
details: ["Default edge"], target: "/runs/run-1/stages/z%401",
});
});
test("a matched condition keeps its expression and target", () => {
const item = route(1);
item.item.subject.node.meta.edges!["1"] = {
to: "a", label: "Special", condition: "outcome=succeeded",
};
expect(renderDecision([item])).toEqual({
details: ["Matched condition", "outcome=succeeded"], target: "/runs/run-1/stages/a%401",
});
});
test.each([
["missing table", undefined],
["missing selected edge", { "1": { to: "a", condition: "never=true" } }],
["malformed selected edge", { "2": [] }],
["missing target metadata", { "2": {} }],
["mismatched target metadata", { "2": { to: "a" } }],
["malformed condition", { "2": { to: "z", condition: false } }],
])("%s keeps the target without inventing a reason", (_name, edges) => {
const item = route();
item.item.subject.node.meta.edges = edges;
expect(renderDecision([item])).toEqual({
details: ["Reason unavailable"], target: "/runs/run-1/stages/z%401",
});
});
test("a missing edge id cannot identify the fallback", () => {
const item = route();
item.item.record.body.edge = undefined;
expect(renderDecision([item]).details).toEqual(["Reason unavailable"]);
});
test("a human choice without a condition is not called a default", () => {
const item = route();
item.item.subject.node.meta.kind = "human";
expect(renderDecision([item]).details).toEqual(["Reason unavailable"]);
});
test("the edge id distinguishes routes sharing a destination", () => {
const item = route();
item.item.subject.node.meta.edges!["1"] = { to: "z", condition: "never=true" };
expect(renderDecision([item]).details).toEqual(["Default edge"]);
});
test("a later visit does not replace the selected visit's reason", () => {
const first = route(2, 1);
const second = route(1, 2);
expect(renderDecision([first, second], 1).details).toEqual(["Default edge"]);
expect(findPetriEdgeForStage([first, second], "gate@2")).toMatchObject({
toNode: "a", reason: "condition", condition: "never=true",
});
});
});

View file

@ -5,17 +5,19 @@ import {
ArrowsRightLeftIcon,
} from "@heroicons/react/20/solid";
import { stagePath } from "../../lib/stage-routes";
import type { Stage } from "../stage-sidebar";
import { StageMetaBar } from "./meta-bar";
import type { EdgeSelection } from "./helpers";
const REASON_LABEL: Record<string, string> = {
const REASON_LABEL: Record<EdgeSelection["reason"], string> = {
condition: "Matched condition",
unconditional: "Default edge",
preferred_label: "Preferred label",
unknown: "Reason unavailable",
};
function reasonLabel(reason: string): string {
function reasonLabel(reason: EdgeSelection["reason"]): string {
return REASON_LABEL[reason] ?? reason;
}
@ -67,7 +69,7 @@ export function ConditionalDecision({
{edge ? (
targetStage ? (
<Link
to={`/runs/${runId}/stages/${targetStage.id}`}
to={stagePath(runId, targetStage.id)}
className="group rounded-md bg-teal-500/10 px-3 py-2 text-center transition-colors hover:bg-teal-500/20 focus-visible:outline-2 focus-visible:-outline-offset-2 focus-visible:outline-teal-500"
>
<div className="text-[10px] font-medium uppercase tracking-wider text-teal-500">

View file

@ -83,7 +83,7 @@ export interface StageContextData {
export interface EdgeSelection {
fromNode: string;
toNode: string;
reason: string;
reason: "condition" | "unconditional" | "preferred_label" | "unknown";
condition: string | null;
}

View file

@ -119,8 +119,8 @@ describe("ParallelChildren", () => {
expect(rows[1]).toContain("Running");
expect(rows[1]).toContain("review_opus");
expect(hrefs(renderer)).toEqual([
"/runs/run-1/stages/review_glm@1",
"/runs/run-1/stages/review_opus@1",
"/runs/run-1/stages/review_glm%401",
"/runs/run-1/stages/review_opus%401",
]);
expect(statValue(renderer, "Succeeded")).toBe("1");
expect(statValue(renderer, "Failed")).toBe("0");
@ -154,7 +154,7 @@ describe("ParallelChildren", () => {
],
);
expect(hrefs(renderer)).toEqual(["/runs/run-1/stages/review_glm@1"]);
expect(hrefs(renderer)).toEqual(["/runs/run-1/stages/review_glm%401"]);
});
test("shows a late-starting branch when lower indexes have no stage yet", () => {
@ -168,7 +168,7 @@ describe("ParallelChildren", () => {
"PendingBranch 2",
"Runningreview_opus",
]);
expect(hrefs(renderer)).toEqual(["/runs/run-1/stages/review_opus@1"]);
expect(hrefs(renderer)).toEqual(["/runs/run-1/stages/review_opus%401"]);
expect(statValue(renderer, "Branches")).toBe("3");
});
@ -192,7 +192,7 @@ describe("ParallelChildren", () => {
);
expect(branchRowText(renderer)).toEqual(["Runningreview_glm@2"]);
expect(hrefs(renderer)).toEqual(["/runs/run-1/stages/review_glm@2"]);
expect(hrefs(renderer)).toEqual(["/runs/run-1/stages/review_glm%402"]);
});
test("keeps duplicate branch targets in index order and only links recorded stages", () => {
@ -208,7 +208,7 @@ describe("ParallelChildren", () => {
expect(rows).toHaveLength(2);
expect(rows[0]).toContain("Succeeded");
expect(rows[1]).toContain("Failed");
expect(hrefs(renderer)).toEqual(["/runs/run-1/stages/review@1"]);
expect(hrefs(renderer)).toEqual(["/runs/run-1/stages/review%401"]);
});
test("renders a completed result without a matching stage as an unlinked row", () => {

View file

@ -3,6 +3,7 @@ import { Link } from "react-router";
import { ArrowTopRightOnSquareIcon } from "@heroicons/react/20/solid";
import { StageState } from "@qltysh/fabro-api-client";
import { stagePath } from "../../lib/stage-routes";
import type { Stage } from "../stage-sidebar";
import { formatStageLabel, stageStatusLabel, stageStatusTone } from "../../lib/stage-sidebar";
import { StageMetaBar } from "./meta-bar";
@ -82,7 +83,7 @@ function ChildRow({
<li className="flex items-center gap-3 px-4 py-2.5">
{row.stageId ? (
<Link
to={`/runs/${runId}/stages/${row.stageId}`}
to={stagePath(runId, row.stageId)}
className="group flex flex-1 items-center gap-3 rounded -m-1 p-1 transition-colors hover:bg-overlay focus-visible:bg-overlay focus-visible:outline-2 focus-visible:-outline-offset-2 focus-visible:outline-teal-500"
>
{inner}

View file

@ -1,9 +1,10 @@
import { useMemo, type ReactNode } from "react";
import { Marked } from "marked";
import { highlightJson } from "../event-debug-helpers";
import { prettyJson } from "./pretty-json";
export { Markdown } from "../markdown";
export function DetailField({
label,
children,
@ -49,48 +50,3 @@ export function JsonBlock({ value }: { value: string }) {
</pre>
);
}
const SAFE_HTTP_URL_RE = /^https?:\/\//i;
const SAFE_MAILTO_URL_RE = /^mailto:/i;
function isSafeMarkdownHref(href: string): boolean {
return (
SAFE_HTTP_URL_RE.test(href) ||
SAFE_MAILTO_URL_RE.test(href) ||
href.startsWith("#") ||
(href.startsWith("/") && !href.startsWith("//"))
);
}
const markedSafe = new Marked();
markedSafe.use({
async: false,
walkTokens(token) {
if (
(token.type === "link" || token.type === "image") &&
typeof token.href === "string" &&
!isSafeMarkdownHref(token.href)
) {
token.href = "";
}
},
renderer: {
html() {
return "";
},
},
});
export function Markdown({ content }: { content: string }) {
const html = useMemo(
() => markedSafe.parse(content, { async: false }) as string,
[content],
);
return (
// react-doctor-disable-next-line react-doctor/no-danger -- markedSafe strips raw HTML and unsafe link/image URLs before rendering Markdown.
<div
className="prose prose-sm max-w-none text-fg-3 prose-headings:text-fg-2 prose-strong:text-fg-2 prose-code:rounded prose-code:bg-overlay-strong prose-code:px-1 prose-code:py-0.5 prose-code:text-[0.8em] prose-code:font-mono prose-code:text-fg-3 prose-code:before:content-none prose-code:after:content-none prose-pre:bg-overlay-strong prose-pre:text-fg-3 prose-a:text-teal-500"
dangerouslySetInnerHTML={{ __html: html }}
/>
);
}

View file

@ -18,6 +18,7 @@ import {
MapIcon,
PaperClipIcon,
} from "@heroicons/react/24/outline";
import { stagePath } from "../lib/stage-routes";
import { formatDurationSecs } from "../lib/format";
import { ACTIVE_STAGE_STATES, formatStageLabel, type Stage } from "../lib/stage-sidebar";
import { elapsedSecsSince, useTickingNow } from "../lib/time";
@ -207,7 +208,7 @@ export function StageSidebar({ stages, runId, selectedStageId, activeLink }: Sta
return (
<SidebarRow
key={stage.id}
to={`/runs/${runId}/stages/${stage.id}`}
to={stagePath(runId, stage.id)}
icon={config.icon}
iconClass={config.color}
label={formatStageLabel(stage)}

View file

@ -85,6 +85,7 @@ export function ConfirmDialog({
confirmLabel,
pendingLabel,
cancelLabel = "Cancel",
tone = "danger",
pending = false,
onConfirm,
onCancel,
@ -95,6 +96,7 @@ export function ConfirmDialog({
confirmLabel: string;
pendingLabel?: string;
cancelLabel?: string;
tone?: "primary" | "danger";
pending?: boolean;
onConfirm: () => void;
onCancel: () => void;
@ -126,7 +128,7 @@ export function ConfirmDialog({
type="button"
onClick={onConfirm}
disabled={pending}
className={DANGER_BUTTON_CLASS}
className={tone === "danger" ? DANGER_BUTTON_CLASS : PRIMARY_BUTTON_CLASS}
>
{pending ? (pendingLabel ?? `${confirmLabel}…`) : confirmLabel}
</button>

View file

@ -1,8 +1,9 @@
import { afterEach, describe, expect, mock, test } from "bun:test";
import type { AxiosAdapter } from "axios";
import { StrictMode } from "react";
import { StrictMode, type ReactNode } from "react";
import { MemoryRouter, Route, Routes } from "react-router";
import TestRenderer, { act } from "react-test-renderer";
import { SWRConfig } from "swr";
import InstallApp from "./install-app";
import { generatedAxios } from "./lib/api-client";
@ -25,6 +26,15 @@ const SESSION_RESPONSE = {
const originalAdapter = generatedAxios.defaults.adapter;
function createInstallRenderer(children: ReactNode) {
// Each test gets its own session cache and in-flight request registry.
return TestRenderer.create(
<SWRConfig value={{ provider: () => new Map() }}>
{children}
</SWRConfig>,
);
}
type TestWindow = {
history: {
state: unknown;
@ -209,7 +219,7 @@ describe("InstallApp", () => {
let renderer: TestRenderer.ReactTestRenderer | null = null;
await act(async () => {
renderer = TestRenderer.create(
renderer = createInstallRenderer(
<StrictMode>
<MemoryRouter initialEntries={["/install/github?error=github-app-manifest-conversion-failed"]}>
<Routes>
@ -281,7 +291,7 @@ describe("InstallApp", () => {
let renderer: TestRenderer.ReactTestRenderer | null = null;
await act(async () => {
renderer = TestRenderer.create(
renderer = createInstallRenderer(
<MemoryRouter initialEntries={["/install/github/done?token=test-install-token"]}>
<Routes>
<Route path="/install/*" element={<InstallApp />} />
@ -369,7 +379,7 @@ describe("InstallApp", () => {
let renderer: TestRenderer.ReactTestRenderer | null = null;
await act(async () => {
renderer = TestRenderer.create(
renderer = createInstallRenderer(
<MemoryRouter initialEntries={["/install/object-store"]}>
<Routes>
<Route path="/install/*" element={<InstallApp />} />
@ -465,7 +475,7 @@ describe("InstallApp", () => {
let renderer: TestRenderer.ReactTestRenderer | null = null;
await act(async () => {
renderer = TestRenderer.create(
renderer = createInstallRenderer(
<MemoryRouter initialEntries={["/install/object-store"]}>
<Routes>
<Route path="/install/*" element={<InstallApp />} />
@ -540,7 +550,7 @@ describe("InstallApp", () => {
let renderer: TestRenderer.ReactTestRenderer | null = null;
await act(async () => {
renderer = TestRenderer.create(
renderer = createInstallRenderer(
<MemoryRouter initialEntries={["/install/review"]}>
<Routes>
<Route path="/install/*" element={<InstallApp />} />
@ -606,7 +616,7 @@ describe("InstallApp", () => {
let renderer: TestRenderer.ReactTestRenderer | null = null;
await act(async () => {
renderer = TestRenderer.create(
renderer = createInstallRenderer(
<MemoryRouter initialEntries={["/install/review"]}>
<Routes>
<Route path="/install/*" element={<InstallApp />} />
@ -703,7 +713,7 @@ describe("InstallApp", () => {
let renderer: TestRenderer.ReactTestRenderer | null = null;
await act(async () => {
renderer = TestRenderer.create(
renderer = createInstallRenderer(
<MemoryRouter initialEntries={["/install/sandbox"]}>
<Routes>
<Route path="/install/*" element={<InstallApp />} />
@ -797,7 +807,7 @@ describe("InstallApp", () => {
let renderer: TestRenderer.ReactTestRenderer | null = null;
await act(async () => {
renderer = TestRenderer.create(
renderer = createInstallRenderer(
<MemoryRouter initialEntries={["/install/sandbox"]}>
<Routes>
<Route path="/install/*" element={<InstallApp />} />
@ -885,7 +895,7 @@ describe("InstallApp", () => {
let renderer: TestRenderer.ReactTestRenderer | null = null;
await act(async () => {
renderer = TestRenderer.create(
renderer = createInstallRenderer(
<MemoryRouter initialEntries={["/install/review"]}>
<Routes>
<Route path="/install/*" element={<InstallApp />} />
@ -969,7 +979,7 @@ describe("InstallApp", () => {
let renderer: TestRenderer.ReactTestRenderer | null = null;
await act(async () => {
renderer = TestRenderer.create(
renderer = createInstallRenderer(
<MemoryRouter initialEntries={["/install/llm"]}>
<Routes>
<Route path="/install/*" element={<InstallApp />} />
@ -1047,7 +1057,7 @@ describe("InstallApp", () => {
let renderer: TestRenderer.ReactTestRenderer | null = null;
await act(async () => {
renderer = TestRenderer.create(
renderer = createInstallRenderer(
<MemoryRouter initialEntries={["/install/llm"]}>
<Routes>
<Route path="/install/*" element={<InstallApp />} />
@ -1117,7 +1127,7 @@ describe("InstallApp", () => {
let renderer: TestRenderer.ReactTestRenderer | null = null;
await act(async () => {
renderer = TestRenderer.create(
renderer = createInstallRenderer(
<MemoryRouter initialEntries={["/install/review"]}>
<Routes>
<Route path="/install/*" element={<InstallApp />} />
@ -1178,7 +1188,7 @@ describe("InstallApp", () => {
let renderer: TestRenderer.ReactTestRenderer | null = null;
await act(async () => {
renderer = TestRenderer.create(
renderer = createInstallRenderer(
<MemoryRouter initialEntries={["/install/review"]}>
<Routes>
<Route path="/install/*" element={<InstallApp />} />
@ -1247,7 +1257,7 @@ describe("InstallApp", () => {
let renderer: TestRenderer.ReactTestRenderer | null = null;
await act(async () => {
renderer = TestRenderer.create(
renderer = createInstallRenderer(
<MemoryRouter initialEntries={["/install/llm"]}>
<Routes>
<Route path="/install/*" element={<InstallApp />} />

View file

@ -1,4 +1,4 @@
import type { Model } from "@qltysh/fabro-api-client";
import type { Model, Provider } from "@qltysh/fabro-api-client";
type ModelOfferingIdentity = Pick<Model, "provider" | "id">;
@ -6,6 +6,13 @@ export function modelOfferingKey(model: ModelOfferingIdentity): string {
return `${model.provider}\u0000${model.id}`;
}
/** Provider ids to the names the catalog displays, falling back to the id. */
export function providerNamesById(
providers: readonly Pick<Provider, "id" | "display_name">[],
): Map<string, string> {
return new Map(providers.map((p) => [p.id, p.display_name || p.id]));
}
export function modelOfferingTestArgs(
model: ModelOfferingIdentity,
): [id: string, provider: string] {

View file

@ -21,7 +21,6 @@ import {
petriEventName,
petriStageLabel,
platformRecordKind,
platformRecordsOf,
reducerTranscriptFromProjection,
stagesFromProjection,
streamItemName,
@ -106,6 +105,81 @@ describe("questions", () => {
test("a run without a gate asks nothing", () => {
expect(parsePetriInterviewPairs(command.stream)).toEqual([]);
});
function question(reference: unknown, id = "review#1", seq = 1): RunStreamItem {
return {
run_id: "run-review",
stream_seq: seq,
kind: "petri",
id: `execution 0/${seq}/0`,
recorded_at: 1_000 * seq,
item: {
record: { body: { event: "step.progress.recorded" } },
derived: {
parsed: {
kind: "question",
question: { id, text: "Review the document.", reference },
},
},
},
};
}
const reference = {
label: "Design review",
url: "https://example.com/review/%2Fdraft?revision=one&token=a%2Bb#feedback",
kind: "document",
};
test("each question keeps its original review target through answer and replay", () => {
const asked = question(reference);
const answered: RunStreamItem = {
...asked,
stream_seq: 2,
id: "execution 0/2/0",
recorded_at: 2_000,
item: {
record: { body: { event: "control.requested" } },
derived: { deliverable: true, answer: { question: "review#1", choice: "Y" } },
},
};
const nextReference = { ...reference, label: "Revised design", url: "https://example.com/next" };
const stream = [asked, answered, question(nextReference, "review#2", 3)];
const pending = parsePetriInterviewPairs([asked]);
expect(pending[0].question.reviewTarget).toEqual(reference);
expect(pending[0].resolution).toBeNull();
const pairs = parsePetriInterviewPairs(stream);
expect(pairs.map((pair) => pair.question.reviewTarget)).toEqual([reference, nextReference]);
expect(pairs[0].resolution).toMatchObject({ kind: "answered", answer: "Y" });
expect(pairs[1].resolution).toBeNull();
// A fresh page reads serialized events, with no live question or context cache.
expect(parsePetriInterviewPairs(JSON.parse(JSON.stringify(stream)))).toEqual(pairs);
});
test.each([undefined, null])("a reference with kind %p is a document, like the pending projection", (kind) => {
const [pair] = parsePetriInterviewPairs([question({ ...reference, kind })]);
expect(pair.question.reviewTarget).toEqual(reference);
});
test.each([
undefined,
null,
"https://example.com/review",
[],
{},
{ ...reference, kind: "pull_request" },
{ ...reference, kind: "" },
{ ...reference, kind: 42 },
{ ...reference, label: 42 },
{ ...reference, label: " " },
{ ...reference, url: 42 },
{ ...reference, url: " " },
].map((value) => [value]))("a missing or malformed reference falls back to question text: %p", (value) => {
const [pair] = parsePetriInterviewPairs([question(value)]);
expect(pair.question.reviewTarget).toBeNull();
expect(pair.question.question).toBe("Review the document.");
});
});
describe("run phases", () => {
@ -129,27 +203,6 @@ describe("run phases", () => {
});
describe("platform records", () => {
test("a notice recorded between the branches lists with its message", () => {
const records = platformRecordsOf(parallel.stream);
const notices = records.filter((record) => record.kind === "run.notice");
expect(notices).toHaveLength(1);
expect(notices[0].detail).toBe("recorded while both branches ran");
expect(notices[0].stageKey).toBeNull();
});
test("each stage's checkpoint lists with its commit and its stage", () => {
const records = platformRecordsOf(parallel.stream);
const checkpoints = records.filter((record) => record.kind === "checkpoint");
// start, fork, a, b, merge, exit, and the two branch delegates.
expect(checkpoints.length).toBeGreaterThanOrEqual(6);
for (const checkpoint of checkpoints) {
expect(checkpoint.detail).toMatch(/^[0-9a-f]{12}$/);
expect(checkpoint.stageKey).not.toBeNull();
}
const order = records.map((record) => record.kind);
expect(order.indexOf("checkpoint")).toBeLessThan(order.indexOf("run.notice"));
});
test("the debug rows name every item and carry its stage", () => {
const rows = debugRowsFromStream(parallel.stream);
expect(rows).toHaveLength(parallel.stream.length);
@ -196,7 +249,7 @@ describe("stage renderers", () => {
expect(findPetriEdgeForStage(gate.stream, "gate@1")).toEqual({
fromNode: "gate",
toNode: "no",
reason: "condition",
reason: "unknown",
condition: null,
});
expect(findPetriEdgeForStage(gate.stream, "exit@1")).toBeNull();

View file

@ -6,8 +6,9 @@
* keyed by `stream_seq`. The mapping from items to views follows
* `lib/components/fabro-petri/VIEWS.md`.
*/
import { StageOutcome, StageState } from "@qltysh/fabro-api-client";
import { ReviewTargetKind, StageOutcome, StageState } from "@qltysh/fabro-api-client";
import type {
ReviewTarget,
RunProjection,
RunStreamItem,
StageProjection,
@ -156,6 +157,18 @@ export function itemsForStage(
// ── Questions ───────────────────────────────────────────────────────────
/** Match the pending-question projection's document reference mapping. */
function parseReviewTarget(value: unknown): ReviewTarget | null {
if (!isRecord(value)) return null;
if (value.kind != null && value.kind !== ReviewTargetKind.DOCUMENT) return null;
const label = getString(value, "label")?.trim();
const url = getString(value, "url")?.trim();
if (!label || !url) return null;
// Keep the recorded URL (including query and fragment). The shared
// question renderer checks URL safety before creating a link.
return { label, url, kind: ReviewTargetKind.DOCUMENT };
}
function parseOptions(value: unknown): InterviewOption[] {
if (!Array.isArray(value)) return [];
const out: InterviewOption[] = [];
@ -243,7 +256,7 @@ export function parsePetriInterviewPairs(stream: PetriStream): HumanInterviewPai
allowFreeform: getBool(question, "freeform") === true,
timeoutSeconds: timeoutMs !== undefined ? Math.round(timeoutMs / 1000) : null,
contextDisplay: getString(question, "context") ?? null,
reviewTarget: null,
reviewTarget: parseReviewTarget(question?.reference),
},
resolution: null,
});
@ -399,55 +412,6 @@ export function deriveRunPhasesFromStream(
return phases;
}
// ── Platform records ────────────────────────────────────────────────────
export interface PlatformRecordEntry {
streamSeq: number;
kind: string;
ts: string;
/** The stage the record belongs to, as `execution:firing`, if any. */
stageKey: string | null;
/** A one-line summary: the commit sha, the pull request url, the notice. */
detail: string | null;
}
/** The platform records on the stream that name a Fabro fact worth a row. */
export function platformRecordsOf(stream: PetriStream): PlatformRecordEntry[] {
const out: PlatformRecordEntry[] = [];
for (const item of stream) {
const kind = platformRecordKind(item);
if (!kind) continue;
const rec = record(item) ?? {};
const position = getObject(item.item, "position");
const execution = getNumber(position, "execution") ?? getNumber(rec, "execution");
const firing = getNumber(position, "firing") ?? getNumber(rec, "firing");
const stageKey =
execution !== undefined && firing !== undefined ? `${execution}:${firing}` : null;
let detail: string | null = null;
switch (kind) {
case "checkpoint":
detail = getString(rec, "git_commit_sha")?.slice(0, 12) ?? null;
break;
case "pull_request.created":
detail = getString(rec, "html_url") ?? getString(rec, "url") ?? null;
break;
case "run.notice":
detail = getString(rec, "message") ?? getString(rec, "code") ?? null;
break;
case "run.title":
detail = getString(rec, "title") ?? null;
break;
case "run.branch":
detail = getString(rec, "run_branch") ?? null;
break;
default:
continue;
}
out.push({ streamSeq: item.stream_seq, kind, ts: streamItemTs(item), stageKey, detail });
}
return out;
}
// ── Debug rows ──────────────────────────────────────────────────────────
/** A stream item as the events listing and the stage debug tab show it. */
@ -498,11 +462,25 @@ export function findPetriEdgeForStage(
if (petriStageLabel(item) !== stageLabel) continue;
const target = getString(getObject(derived(item), "target"), "name");
if (!target) continue;
const edge = selectedEdgeMetadata(item);
const condition = matchedCondition(item) ?? null;
let reason: EdgeSelection["reason"] = "unknown";
if (condition) {
reason = "condition";
} else if (
edge &&
getString(getObject(subjectNode(item), "meta"), "kind") === "conditional" &&
(edge.condition === undefined || edge.condition === "")
) {
// Other handlers can select a conditionless edge by preferred label or
// suggested target. Only a conditional stage establishes this fallback.
reason = "unconditional";
}
latest = {
fromNode: getString(subjectNode(item), "name") ?? stageLabel,
toNode: target,
reason: "condition",
condition: matchedCondition(item) ?? null,
reason,
condition,
};
}
return latest;
@ -636,10 +614,20 @@ export function agentEnvelopesOf(items: PetriStream): PetriAgentEnvelope[] {
* the edge's `condition` when it has one (EVENTS.md "Source metadata").
*/
export function matchedCondition(item: RunStreamItem): string | undefined {
const edge = getNumber(petriBody(item), "edge");
if (edge === undefined) return undefined;
const condition = getString(selectedEdgeMetadata(item), "condition");
return condition?.trim() ? condition : undefined;
}
/** Missing or inconsistent metadata does not establish an unconditional edge. */
function selectedEdgeMetadata(item: RunStreamItem): UnknownRecord | undefined {
const body = petriBody(item);
if (getString(body, "kind") !== "edge") return undefined;
const edge = getNumber(body, "edge");
if (edge === undefined || !Number.isSafeInteger(edge) || edge < 0) return undefined;
const edges = getObject(getObject(subjectNode(item), "meta"), "edges");
return getString(getObject(edges, String(edge)), "condition");
const selected = getObject(edges, String(edge));
const target = getString(getObject(derived(item), "target"), "name");
return target && getString(selected, "to") === target ? selected : undefined;
}
/**

View file

@ -534,9 +534,10 @@ export function useServerSettings() {
);
}
export function useProviders() {
/** The provider catalog; `enabled: false` skips the request. */
export function useProviders({ enabled = true }: { enabled?: boolean } = {}) {
return useSWR<ProviderList>(
queryKeys.providers.list(),
enabled ? queryKeys.providers.list() : null,
() => apiData(() => modelsApi.listProviders()),
immutableOptions,
);

View file

@ -11,6 +11,8 @@ import {
archiveRun,
archiveRuns,
canArchive,
canRetry,
retryRun,
canApprove,
canCancel,
canUnarchive,
@ -460,3 +462,32 @@ describe("run lifecycle actions", () => {
expect(cancellationActionLabel(false)).toBe("Cancel");
});
});
describe("retryRun", () => {
test("posts to retry and returns the new run", async () => {
const run = { ...makeRun({ kind: "pending" }), id: "new-run" };
const { requests } = stubGeneratedAxiosOnce({ status: 201, body: run });
expect(await retryRun("run-1")).toEqual(run);
expect(requests).toEqual([{ url: "/api/v1/runs/run-1/retry", method: "post", data: undefined }]);
});
test("preserves API errors for the retry dialog", async () => {
const errors = [{ status: "422", title: "Invalid run", detail: "Saved environment is unavailable." }];
stubGeneratedAxiosOnce({ status: 422, body: { errors } });
await expect(retryRun("run-1")).rejects.toEqual({ status: 422, errors });
});
test("eligibility includes all terminal states and excludes archived or unknown states", () => {
for (const status of ["succeeded", "failed", "dead"]) expect(canRetry(status)).toBe(true);
for (const status of ["archived", "submitted", "pending", "runnable", "starting", "running", "paused", "blocked", "unknown", null, undefined]) {
expect(canRetry(status)).toBe(false);
}
});
test("maps retry failures with actionable fallback messages", () => {
expect(mapError({ status: 404, errors: [] }, "retry")).toBe("This run no longer exists.");
expect(mapError({ status: 409, errors: [] }, "retry")).toBe("Only terminal, non-archived runs can be retried.");
expect(mapError(new Error("offline"), "retry")).toBe("Couldn't retry the run right now. Try again.");
});
});

View file

@ -46,6 +46,18 @@ const TERMINAL_RUN_STATUSES = new Set<RunStatus>([
"dead",
]);
export async function retryRun(id: string): Promise<Run> {
try {
return await apiData(() => runsApi.retryRun(id));
} catch (error) {
throw lifecycleActionErrorFromError(error);
}
}
export function canRetry(status: string | null | undefined): boolean {
return isTerminalRunStatus(status);
}
export async function cancelRun(id: string, request?: Request): Promise<Run> {
return runLifecycleAction(id, "cancel", request);
}
@ -197,13 +209,15 @@ export function deleteErrorMessage(error: unknown): string {
return "Couldn't delete the run right now. Try again.";
}
export function mapError(error: unknown, action: LifecycleAction): string {
export function mapError(error: unknown, action: LifecycleAction | "retry"): string {
if (isLifecycleActionError(error)) {
if (error.status === 404) {
return "This run no longer exists.";
}
if (error.status === 409) {
switch (action) {
case "retry":
return "Only terminal, non-archived runs can be retried.";
case "cancel":
return "This run can no longer be cancelled.";
case "approve":
@ -223,6 +237,8 @@ export function mapError(error: unknown, action: LifecycleAction): string {
}
switch (action) {
case "retry":
return "Couldn't retry the run right now. Try again.";
case "cancel":
return "Couldn't cancel the run right now. Try again.";
case "approve":

View file

@ -0,0 +1,19 @@
/** Build a stage link from the original occurrence ID, never an encoded ID. */
export function stagePath(runId: string, stageId: string): string {
return `/runs/${encodeURIComponent(runId)}/stages/${encodeURIComponent(stageId)}`;
}
/**
* Read the original URL segment once. React Router's params replace literal
* `%2F` with `/` after decoding, so they cannot distinguish those stage IDs.
* Pass useLocation().pathname, which excludes the query and fragment.
*/
export function stageIdFromPathname(pathname: string): string | undefined {
const segment = pathname.match(/\/stages\/([^/]+)\/*$/i)?.[1];
if (segment === undefined) return undefined;
try {
return decodeURIComponent(segment);
} catch {
return undefined;
}
}

View file

@ -0,0 +1,76 @@
import { describe, expect, test } from "bun:test";
import { renderToStaticMarkup } from "react-dom/server";
import { createMemoryRouter, RouterProvider, type RouteObject } from "react-router";
import { installRoutes } from "./install-router";
import { routes } from "./router";
async function renderPage(routeObjects: RouteObject[], path: string, navigate = false) {
const router = createMemoryRouter(routeObjects, {
initialEntries: [navigate ? "/" : path],
});
try {
if (navigate) await router.navigate(path);
return renderToStaticMarkup(<RouterProvider router={router} />);
} finally {
router.dispose();
}
}
describe("root error boundary", () => {
for (const path of ["/some_random_route", "/runs/existing-run/billing"]) {
for (const navigate of [false, true]) {
test(`${path} displays 404 on ${navigate ? "navigation" : "initial load"}`, async () => {
const html = await renderPage(routes, path, navigate);
expect(html).toContain(">404</p>");
expect(html).toContain("Page not found");
expect(html).not.toContain("Something went wrong");
expect(html).toContain('href="/runs"');
expect(html).toContain("Go back");
});
}
}
for (const [name, root] of [["app", routes[0]], ["installer", installRoutes[0]]] as const) {
async function renderFailure(error: unknown) {
return renderPage([
{
...root,
children: [{
path: "failure",
loader() { throw error; },
Component: () => null,
}],
},
], "/failure", true);
}
test(`${name} displays a route's 404 response as page not found`, async () => {
const html = await renderFailure(new Response(null, { status: 404 }));
expect(html).toContain(">404</p>");
expect(html).toContain("Page not found");
expect(html).not.toContain("Something went wrong");
});
test.each([403, 500])(`${name} preserves a route's %i error response`, async (status) => {
const statusText = status === 403 ? "Forbidden" : "Internal Server Error";
const html = await renderFailure(new Response(null, { status, statusText }));
expect(html).toContain(`>${status}</p>`);
expect(html).toContain(`${status} Error`);
expect(html).toContain(statusText);
expect(html).not.toContain("Page not found");
});
test(`${name} keeps unexpected exceptions as 500 errors`, async () => {
const html = await renderFailure(new Error("Unexpected route failure"));
expect(html).toContain(">500</p>");
expect(html).toContain("Something went wrong");
expect(html).toContain("Unexpected route failure");
expect(html).not.toContain("Page not found");
});
}
});

View file

@ -1,10 +1,11 @@
import { isRouteErrorResponse, Outlet } from "react-router";
import { isRouteErrorResponse, Outlet, useRouteError } from "react-router";
export default function Root() {
return <Outlet />;
}
export function ErrorBoundary({ error }: any) {
export function ErrorBoundary() {
const error = useRouteError();
let status = 500;
let heading = "Something went wrong";
let message = "An unexpected error occurred. Please try again.";

View file

@ -20,6 +20,10 @@ let currentRunSummary: any = null;
let currentRunState: any = null;
let currentQuestions: any[] = [];
let currentBoardRuns: any[] = [];
let retryRunApiResult: Promise<unknown> | null = null;
const retryRunApiMock = mock((_id: string) =>
retryRunApiResult ?? Promise.resolve({ data: null }),
);
let deleteRunApiResult: Promise<unknown> | null = null;
const mountedRenderers: TestRenderer.ReactTestRenderer[] = [];
@ -82,6 +86,7 @@ mock.module("../lib/queries", () => ({
isValidating: false,
mutate: mock(() => Promise.resolve(null)),
}),
useProviders: () => ({ data: null }),
}));
mock.module("../lib/run-events", () => ({
@ -110,6 +115,7 @@ mock.module("../lib/api-client", () => ({
requestSignalOptions: () => undefined,
runsApi: {
deleteRun: deleteRunApiMock,
retryRun: retryRunApiMock,
},
ApiError: class ApiError extends Error {
readonly status: number;
@ -200,6 +206,8 @@ const {
default: RunDetail,
resolveDockClearance,
} = await import("./run-detail");
const { RowActionsMenu } = await import("../components/runs-list/row-actions-menu");
const { toRunWithStatus } = await import("../data/runs");
const { default: Runs } = await import("./runs");
mock.restore();
type LifecycleToastState = import("./run-detail/lifecycle-toasts").LifecycleToastState;
@ -346,6 +354,10 @@ async function renderRunDetailHarness({
const router = createMemoryRouter(
[
{
path: "/row",
element: h(RowActionsMenu, { run: toRunWithStatus(currentRunSummary) }),
},
{
path: "/runs",
element: h(Runs),
@ -638,7 +650,7 @@ describe("handleLifecycleToastResult", () => {
});
});
describe("RunDetail full-height child routes", () => {
describe("RunDetail and run actions", () => {
afterEach(() => {
act(() => {
for (const renderer of mountedRenderers.splice(0)) {
@ -653,6 +665,8 @@ describe("RunDetail full-height child routes", () => {
questionQueryMock.mockClear();
submitAnswerMock.mockClear();
submitAnswerHookMock.mockClear();
retryRunApiResult = null;
retryRunApiMock.mockClear();
deleteRunApiResult = null;
deleteRunApiMock.mockClear();
mutateRunListCachesMock.mockClear();
@ -660,6 +674,68 @@ describe("RunDetail full-height child routes", () => {
delete (globalThis as { IS_REACT_ACT_ENVIRONMENT?: boolean }).IS_REACT_ACT_ENVIRONMENT;
});
for (const surface of ["row", "header"] as const) {
const initialEntry = surface === "row" ? "/row" : "/runs/run_1";
for (const status of ["submitted", "pending", "runnable", "starting", "running", "paused", "blocked", "succeeded", "failed", "dead", "archived"]) {
test(`${surface} offers Retry only for terminal, non-archived runs: ${status}`, async () => {
const { renderer } = await renderRunDetailHarness({ initialEntry, status });
expect(findButtonsByText(renderer, "Retry")).toHaveLength(
["succeeded", "failed", "dead"].includes(status) ? 1 : 0,
);
if (["succeeded", "failed", "dead"].includes(status)) {
expect(findButtonByText(renderer, "Archive")).toBeDefined();
}
});
}
test(`${surface} retries once while pending and opens the returned new run`, async () => {
const response = deferred<unknown>();
retryRunApiResult = response.promise;
const { renderer, router } = await renderRunDetailHarness({ initialEntry, status: "failed" });
await act(async () => { findButtonByText(renderer, "Retry")!.props.onClick(); });
expect(textFromNode(renderer.toJSON())).toContain(
"Retry creates a new run from the saved specification and starts from the beginning.",
);
const confirm = findButtonByText(renderer, "Retry run")!;
await act(async () => {
confirm.props.onClick();
confirm.props.onClick();
});
expect(retryRunApiMock).toHaveBeenCalledTimes(1);
expect(retryRunApiMock.mock.calls[0]?.[0]).toBe("run_1");
expect(findButtonByText(renderer, "Creating run…")!.props.disabled).toBe(true);
expect(findButtonsByText(renderer, "Cancel").at(-1)!.props.disabled).toBe(true);
expect(router.state.location.pathname).toBe(initialEntry);
const newRun = { ...makeRunSummary({ status: "pending" }), id: "new-run" };
await act(async () => { response.resolve({ data: newRun }); });
expect(router.state.location.pathname).toBe("/runs/new-run");
expect(mutateRunListCachesMock).toHaveBeenCalledTimes(1);
expect(swrMutateMock.mock.calls).toContainEqual([
["runs", "detail", "new-run"], newRun, { revalidate: false },
]);
expect(swrMutateMock.mock.calls.some(([key]) =>
JSON.stringify(key) === JSON.stringify(["runs", "detail", "run_1"]),
)).toBe(false);
});
test(`${surface} shows retry errors, stays on the source run, and allows recovery`, async () => {
const response = deferred<unknown>();
retryRunApiResult = response.promise;
const { renderer, router } = await renderRunDetailHarness({ initialEntry, status: "succeeded" });
await act(async () => { findButtonByText(renderer, "Retry")!.props.onClick(); });
await act(async () => { findButtonByText(renderer, "Retry run")!.props.onClick(); });
await act(async () => { response.reject({ status: 422, errors: [{ detail: "Saved environment is unavailable." }] }); });
expect(textFromTestNode(renderer.root.findByProps({ role: "alert" }))).toBe("Saved environment is unavailable.");
expect(router.state.location.pathname).toBe(initialEntry);
expect(mutateRunListCachesMock).not.toHaveBeenCalled();
expect(findButtonByText(renderer, "Retry run")!.props.disabled).toBe(false);
retryRunApiResult = Promise.resolve({ data: { ...makeRunSummary(), id: "recovered-run" } });
await act(async () => { findButtonByText(renderer, "Retry run")!.props.onClick(); });
expect(retryRunApiMock).toHaveBeenCalledTimes(2);
expect(router.state.location.pathname).toBe("/runs/recovered-run");
});
}
test("Answer Question on a blocked board card opens that run's pending interview", async () => {
currentBoardRuns = [
{ ...makeRunSummary(), id: "other-run" },

View file

@ -1,5 +1,6 @@
import {
useCallback,
useMemo,
useRef,
useState,
type CSSProperties,
@ -12,6 +13,7 @@ import {
import { AgentSessionActivity } from "@qltysh/fabro-api-client";
import { type SteerBarHandle } from "../components/steer-bar";
import { RetryRunDialog } from "../components/retry-run-dialog";
import { ErrorState } from "../components/state";
import { useToast } from "../components/toast";
import {
@ -33,7 +35,8 @@ import {
} from "../lib/mutations";
import { useRunEvents } from "../lib/run-events";
import { useRunToasts } from "../hooks/use-run-toasts";
import { useRun, useRunQuestions, useRunState } from "../lib/queries";
import { useProviders, useRun, useRunQuestions, useRunState } from "../lib/queries";
import { providerNamesById } from "../lib/model-offerings";
import {
canApprove,
deleteErrorMessage,
@ -49,6 +52,8 @@ import {
RunDetailAskFabroShell,
RunDetailDockedControls,
} from "./run-detail/docked-controls";
import { buildRunFailureView } from "./run-detail/failure";
import { RunFailureBanner } from "./run-detail/failure-banner";
import { RunDetailHeader } from "./run-detail/header";
import {
createLifecycleToastState,
@ -114,6 +119,7 @@ export default function RunDetail({ params }: { params: { id: string } }) {
const interruptMutation = useInterruptRun(params.id);
const navigate = useNavigate();
const { mutate } = useSWRConfig();
const [retryDialogOpen, setRetryDialogOpen] = useState(false);
const [deleteDialogOpen, setDeleteDialogOpen] = useState(false);
const [deletePending, setDeletePending] = useState(false);
const [dockMeasurement, setDockMeasurement] =
@ -146,6 +152,16 @@ export default function RunDetail({ params }: { params: { id: string } }) {
useRunEvents(params.id);
useRunToasts(params.id);
// Provider names only matter to a failed run's banner.
const providersQuery = useProviders({ enabled: statusKind === "failed" || statusKind === "dead" });
const providerNames = useMemo(
() => providerNamesById(providersQuery.data?.data ?? []),
[providersQuery.data],
);
const failure = buildRunFailureView(runStateQuery.data, {
providerNames,
lifecycleError: runQuery.data?.lifecycle.error?.message,
});
const handleLifecycleMutationResult = useCallback(
(
@ -279,6 +295,13 @@ export default function RunDetail({ params }: { params: { id: string } }) {
},
],
lifecycle: [
...(visibility.showRetry
? [{
key: "retry",
label: "Retry",
onSelect: () => setRetryDialogOpen(true),
}]
: []),
...(visibility.showArchive
? [{
key: "archive",
@ -373,6 +396,15 @@ export default function RunDetail({ params }: { params: { id: string } }) {
}}
/>
{failure ? <RunFailureBanner failure={failure} /> : null}
{retryDialogOpen && (
<RetryRunDialog
key={params.id}
runId={params.id}
onClose={() => setRetryDialogOpen(false)}
/>
)}
<ConfirmDialog
open={deleteDialogOpen}
title="Delete this run?"

View file

@ -0,0 +1,62 @@
import { ChevronDownIcon, ExclamationTriangleIcon } from "@heroicons/react/20/solid";
import type { RunFailureView } from "./failure";
export function RunFailureBanner({ failure }: { failure: RunFailureView }) {
return (
<section aria-label="Why this run failed" className="mb-6">
<details className="group rounded-lg bg-panel-alt outline-1 -outline-offset-1 outline-line">
<summary className="flex cursor-pointer list-none items-start gap-3 rounded-lg px-4 py-3.5 transition-colors hover:bg-overlay focus-visible:outline-2 focus-visible:-outline-offset-1 focus-visible:outline-teal-500 [&::-webkit-details-marker]:hidden">
<ExclamationTriangleIcon
className="mt-0.5 size-4 shrink-0 text-coral"
aria-hidden="true"
/>
<span className="min-w-0 flex-1">
<span className="block text-sm/5 font-medium text-fg">
{failure.stage ? (
<>
Stopped at <span className="font-mono text-[0.8125rem]">{failure.stage}</span>
<span className="mx-2 text-fg-muted" aria-hidden="true">
·
</span>
</>
) : null}
{failure.headline}
</span>
<span className="mt-1 block text-sm/5 text-fg-3">{failure.nextStep}</span>
</span>
<span className="inline-flex shrink-0 items-center gap-1 pt-0.5 text-xs font-medium text-fg-muted transition-colors group-hover:text-fg-3">
<span className="group-open:hidden">Details</span>
<span className="hidden group-open:inline">Hide</span>
<ChevronDownIcon
className="size-3.5 shrink-0 transition-transform group-open:-rotate-180"
aria-hidden="true"
/>
</span>
</summary>
<dl className="space-y-3 px-4 pt-0.5 pb-4 pl-11">
<div>
<dt className="mb-1 font-mono text-[0.6875rem] tracking-wide text-fg-muted uppercase">
{failure.provider ? "Provider message" : "Message"}
</dt>
<dd className="max-h-48 overflow-auto rounded-md bg-overlay px-3 py-2 font-mono text-xs/5 wrap-break-word whitespace-pre-wrap text-fg-3">
{failure.message}
</dd>
</div>
{failure.output ? (
<div>
<dt className="mb-1 font-mono text-[0.6875rem] tracking-wide text-fg-muted uppercase">
Output
</dt>
<dd>
<pre className="max-h-48 overflow-auto rounded-md bg-overlay px-3 py-2 font-mono text-xs/5 text-fg-3">
{failure.output}
</pre>
</dd>
</div>
) : null}
</dl>
</details>
</section>
);
}

View file

@ -0,0 +1,218 @@
import { describe, expect, test } from "bun:test";
import type { RunProjection } from "@qltysh/fabro-api-client";
import { buildRunFailureView } from "./failure";
type State = Pick<RunProjection, "status" | "conclusion" | "stages">;
const NAMES = new Map([
["anthropic", "Anthropic"],
["openai", "OpenAI"],
]);
const CREDIT =
"model request failed (invalid_request): provider anthropic Your credit balance is too low to access the Anthropic API. Please go to Plans & Billing to upgrade or purchase credits. [provider anthropic, status 400, code invalid_request_error]";
function stages(...entries: Array<[string, string, string]>): State["stages"] {
return Object.fromEntries(
entries.map(([key, state, started_at]) => [key, { state, started_at } as State["stages"][string]]),
);
}
function failedRun(
detail: Record<string, unknown>,
{ reason = "workflow_error", kind = "failed", runStages = {} as State["stages"] } = {},
): State {
return {
status: (kind === "failed" ? { kind, reason } : { kind }) as State["status"],
conclusion: {
failure: { reason, detail: { category: "deterministic", ...detail } },
} as State["conclusion"],
stages: runStages,
};
}
const view = (state: State) => buildRunFailureView(state, { providerNames: NAMES });
describe("buildRunFailureView", () => {
test("names the step the run stopped at and the provider's real message", () => {
const failure = view(
failedRun({ message: CREDIT }, {
runStages: stages(["pick@1", "succeeded", "2026-10-10T18:05:42.783Z"], ["spec@1", "failed", "2026-10-10T18:41:53.513Z"]),
}),
);
expect(failure).toMatchObject({
stage: "spec",
headline: "Anthropic declined the request for billing reasons",
provider: "anthropic",
message: CREDIT,
});
expect(failure?.nextStep).toBe("Add credit or raise the spend limit with Anthropic, then choose Retry from Actions.");
});
test("reads a spent quota as billing, though the provider answered 429", () => {
const failure = view(
failedRun({
message: "model request failed (quota_exceeded): provider gemini Quota exceeded for metric generate_content_requests [provider gemini, status 429, code RESOURCE_EXHAUSTED]",
}),
);
expect(failure?.headline).toBe("gemini declined the request for billing reasons");
});
test("names an unknown provider by its id", () => {
const failure = view(
failedRun({ message: "model request failed (authentication): provider acme bad key [provider acme, status 401, code unauthorized]" }),
);
expect(failure?.headline).toBe("acme rejected the API key");
});
test("reads auth, rate limits, timeouts and outages from the request's own status and kind", () => {
const headline = (message: string) => view(failedRun({ message }))?.headline;
expect(headline("model request failed (authentication): provider anthropic invalid x-api-key [provider anthropic, status 401, code authentication_error]"))
.toBe("Anthropic rejected the API key");
expect(headline("model request failed (access_denied): provider openai The model is not available to your organization [provider openai, status 403, code model_not_found]"))
.toBe("OpenAI denied access to the request");
expect(headline("model request failed (authentication): provider acme forbidden [provider acme, status 403, code forbidden]"))
.toBe("acme rejected the API key");
expect(headline("model request failed (rate_limit): provider openai Too many requests [provider openai, status 429, code rate_limit_exceeded]"))
.toBe("OpenAI rate-limited the request");
expect(headline("model request failed (server): provider anthropic Overloaded [provider anthropic, status 529, code overloaded_error]"))
.toBe("Anthropic was unavailable");
expect(headline("model request failed (timeout): provider openai request timed out"))
.toBe("The request to OpenAI timed out");
});
test("doesn't blame the provider for failures on Fabro's side", () => {
const failure = (message: string) => view(failedRun({ message }));
expect(failure("model request failed (configuration): provider anthropic is disabled in the catalog")).toMatchObject({
headline: "Fabro couldn't send the request to Anthropic",
nextStep: "Check Anthropic and the step's model under Settings → Models, then choose Retry from Actions.",
});
expect(failure("model request failed (model_selection): provider anthropic has no default model")?.headline)
.toBe("Fabro couldn't send the request to Anthropic");
expect(failure("model request failed (network): provider openai connection refused")?.headline)
.toBe("The request never reached OpenAI");
expect(failure("model request failed (resource_limit): provider openai response exceeded 16 MiB")?.headline)
.toBe("Fabro stopped the request to OpenAI");
});
test("falls back to the provider's status and code", () => {
const failure = view(
failedRun({
message: "model request failed (invalid_request): provider openai Unsupported parameter: 'temperature' is not supported with this model. [provider openai, status 400, code unsupported_parameter]",
}),
);
expect(failure?.headline).toBe("OpenAI returned 400 unsupported parameter");
});
test("never reads a provider, status or billing problem out of a command's own words", () => {
const failure = view(
failedRun({
message: "script exited with status 401",
exec_output_tail: { stdout: "test billing::invoice ... FAILED\nretry the provider list later\n", stderr: null },
}),
);
expect(failure).toMatchObject({
headline: "The step's command exited with status 401",
provider: null,
nextStep: "Its output, under Details, usually says why.",
});
expect(view(failedRun({ message: "Ran 512 tests; line 503 failed." }))?.headline).toBe("Ran 512 tests; line 503 failed.");
});
test("names no step when the run recovered from an earlier failed one", () => {
const failure = view(
failedRun({ message: "push rejected: remote branch moved" }, {
reason: "publish_failed",
runStages: stages(
["toolchain@1", "failed", "2026-10-10T15:20:45Z"],
["fixup@1", "succeeded", "2026-10-10T15:21:00Z"],
["verify@1", "succeeded", "2026-10-10T15:25:00.500Z"],
),
}),
);
expect(failure?.stage).toBeNull();
expect(failure?.headline).toBe("The steps finished, but publishing the result failed");
});
test("labels a looped step with its visit, as the Stages sidebar does", () => {
const runStages = stages(["review@1", "succeeded", "2026-10-10T15:20:00Z"], ["review@3", "failed", "2026-10-10T15:30:00Z"]);
expect(view(failedRun({ message: "script exited with status 1" }, { runStages }))?.stage).toBe("review@3");
});
test("names the failed branch of a fan-out, though a sibling started after it", () => {
const runStages = stages(
["checks@1", "failed", "2026-10-10T15:20:00.000Z"],
["lint@1", "failed", "2026-10-10T15:20:00.010Z"],
["test@1", "cancelled", "2026-10-10T15:20:00.013Z"],
);
runStages["lint@1"]!.parallel_branch_id = "checks@1:0";
runStages["test@1"]!.parallel_branch_id = "checks@1:1";
expect(view(failedRun({ message: "script exited with status 1" }, { runStages }))?.stage).toBe("lint");
runStages["report@1"] = { state: "succeeded", started_at: "2026-10-10T15:21:00Z" } as State["stages"][string];
expect(view(failedRun({ message: "push rejected" }, { reason: "publish_failed", runStages }))?.stage).toBeNull();
});
test("shows nothing for a cancelled run, and says what happened for other endings", () => {
expect(view(failedRun({ message: "Run cancelled before worker launch completed" }, { reason: "cancelled" }))).toBeNull();
expect(view(failedRun({ message: "denied at review" }, { reason: "approval_denied" }))?.headline).toBe("Approval was denied");
expect(view(failedRun({ message: "budget of $5 reached" }, { reason: "budget_exhausted" }))?.headline).toBe("The run used up its budget");
expect(view(failedRun({ message: "sandbox image not found" }, { reason: "sandbox_init_failed" }))?.headline).toBe("The run couldn't start");
expect(view(failedRun({ message: "sandbox connection reset" }, { reason: "transient_infra" }))).toMatchObject({
headline: "The step hit a temporary infrastructure error",
nextStep: "Choose Retry from Actions in a few minutes.",
});
});
test("says why a dead run stopped, though a dead run records no conclusion", () => {
const dead = {
status: { kind: "dead" },
conclusion: null,
stages: stages(["build@1", "failed", "2026-10-10T18:05:42Z"]),
} as unknown as State;
expect(buildRunFailureView(dead, { lifecycleError: "worker exited unexpectedly" })).toMatchObject({
stage: "build",
headline: "Worker exited unexpectedly",
message: "worker exited unexpectedly",
});
expect(buildRunFailureView(dead)?.headline).toBe("The run's worker stopped before the run finished");
});
test("shows the end of a command's output, from whichever stream has it", () => {
const tail = (exec_output_tail: Record<string, unknown>) =>
view(failedRun({ message: "script exited with status 1", exec_output_tail }))?.output;
expect(tail({ stderr: "\n \n", stdout: "real error\n" })).toBe("real error");
expect(tail({ stderr: "line one\r\nline two\r\n", stdout: null })).toBe("line one\nline two");
expect(tail({ stdout: "10%\r50%\r100% done\n" })).toBe("100% done");
const many = Array.from({ length: 30 }, (_, i) => `line ${i + 1}`).join("\n");
expect(tail({ stdout: many })?.split("\n")).toEqual(Array.from({ length: 12 }, (_, i) => `line ${i + 19}`));
});
test("falls back to the output the failed step recorded", () => {
const runStages = stages(["test@1", "failed", "2026-10-10T18:05:42Z"]);
runStages["test@1"]!.output = "running 3 tests\ntest parse ... FAILED\n";
const failure = view(failedRun({ message: "script exited with status 101" }, { runStages }));
expect(failure).toMatchObject({
output: "running 3 tests\ntest parse ... FAILED",
nextStep: "Its output, under Details, usually says why.",
});
runStages["test@1"]!.output = "blob://sha256/abc";
expect(view(failedRun({ message: "script exited with status 101" }, { runStages }))?.output).toBeNull();
runStages["test@1"]!.output = "I will now write the spec.";
expect(view(failedRun({ message: CREDIT }, { runStages }))?.output).toBeNull();
});
test("cuts a long fallback headline without splitting a character", () => {
const headline = view(failedRun({ message: `${"🔥".repeat(200)} and more` }))!.headline;
expect(Array.from(headline)).toHaveLength(111);
expect(headline.endsWith("🔥…")).toBe(true);
});
test("shows nothing for runs that didn't fail", () => {
expect(buildRunFailureView({ status: { kind: "succeeded" }, stages: {} } as State)).toBeNull();
expect(buildRunFailureView(null)).toBeNull();
});
});

View file

@ -0,0 +1,272 @@
import {
FailureCategory,
FailureReason,
type ExecOutputTail,
type RunProjection,
} from "@qltysh/fabro-api-client";
import { formatStageLabel } from "../../lib/stage-sidebar";
/** Lines of a failed command's output shown on the page. */
const OUTPUT_LINES = 12;
/** Fallback headlines are cut to this many characters. */
const HEADLINE_CHARS = 110;
export interface RunFailureView {
/** The step the run stopped at (`spec`, `review@3`), when it stopped at one. */
stage: string | null;
headline: string;
nextStep: string;
/** The recorded failure message, verbatim. */
message: string;
/** Provider id, when the failure is a model request the provider refused. */
provider: string | null;
/**
* Last OUTPUT_LINES of the failed command's stderr, else its stdout, else
* the output the step the run stopped at recorded.
*/
output: string | null;
}
type FailureState = Pick<RunProjection, "status" | "conclusion" | "stages">;
export interface RunFailureContext {
/** Provider ids to display names, from the provider catalog. */
providerNames?: ReadonlyMap<string, string>;
/** The run summary's `lifecycle.error`, the only reason a dead run records. */
lifecycleError?: string | null;
}
/**
* Reads the failure from run state (`conclusion.failure`); the run summary the
* status popover reads doesn't carry the message or the command's output. A
* dead run has no conclusion, so its reason comes from the summary instead.
*/
export function buildRunFailureView(
state: FailureState | null | undefined,
{ providerNames = new Map(), lifecycleError = null }: RunFailureContext = {},
): RunFailureView | null {
const kind = state?.status?.kind;
if (!state || (kind !== "failed" && kind !== "dead")) return null;
const failure = state.conclusion?.failure;
if (!failure) return kind === "dead" ? deadRunView(state, lifecycleError) : null;
if (!failure.detail.message || failure.reason === FailureReason.CANCELLED) return null;
const { message, category } = failure.detail;
const request = parseModelRequest(message);
const stage = stoppedAt(state.stages);
// A refused model request's message is the whole story; the step's
// output would be the agent's own text.
const output =
outputTail(failure.detail.exec_output_tail) ??
(request || !stage ? null : lastLines(state.stages[stage]?.output));
const name = (id: string) => providerNames.get(id) ?? id;
const advice =
reasonAdvice(failure.reason, category) ??
(request
? requestAdvice(request, message, name(request.provider))
: stepAdvice(message, failure.reason, category, output));
return {
stage: stageLabel(stage),
...advice,
message,
provider: request?.provider ?? null,
output,
};
}
/** A run whose worker went away before the run concluded. */
function deadRunView(state: FailureState, lifecycleError: string | null): RunFailureView {
const message = lifecycleError?.trim() || "The run ended without recording a reason.";
return {
stage: stageLabel(stoppedAt(state.stages)),
headline: lifecycleError?.trim() ? firstSentence(message) : "The run's worker stopped before the run finished",
nextStep: `Open the failed step's logs for details. To run it again, ${RETRY}.`,
message,
provider: null,
output: null,
};
}
type Advice = Pick<RunFailureView, "headline" | "nextStep">;
const RETRY = "choose Retry from Actions";
function reasonAdvice(reason: FailureReason, category: FailureCategory): Advice | null {
if (reason === FailureReason.APPROVAL_DENIED) {
return { headline: "Approval was denied", nextStep: `The run stops where it was denied. To run it again, ${RETRY}.` };
}
if (reason === FailureReason.BUDGET_EXHAUSTED || category === FailureCategory.BUDGET_EXHAUSTED) {
return { headline: "The run used up its budget", nextStep: `Raise the run's budget, then ${RETRY}.` };
}
if (reason === FailureReason.TERMINATED) {
return { headline: "The run was terminated", nextStep: `To run it again, ${RETRY}.` };
}
if (reason === FailureReason.PUBLISH_FAILED) {
return {
headline: "The steps finished, but publishing the result failed",
nextStep: "The work is on the run branch. The message under Details says why publishing failed.",
};
}
if (
reason === FailureReason.LAUNCH_FAILED ||
reason === FailureReason.BOOTSTRAP_FAILED ||
reason === FailureReason.SANDBOX_INIT_FAILED
) {
return { headline: "The run couldn't start", nextStep: "The message under Details says why." };
}
return null;
}
interface ModelRequest {
provider: string;
kind: string | null;
status: number | null;
code: string | null;
}
/**
* A refused model request, as the server records it:
* `model request failed (<kind>): provider <id> <text> [provider <id>, status <n>, code <code>]`.
* Only this shape is read, so numbers and words in a command's output can't
* pass for a provider's status or name.
*/
function parseModelRequest(message: string): ModelRequest | null {
const lead = /^model request failed \(([a-z_]+)\): provider (\S+)/i.exec(message);
const tail = /\[provider ([^,\]]+), status (\d{3})(?:, code ([^\]]+))?\]\s*$/i.exec(message);
const provider = tail?.[1] ?? lead?.[2];
if (!provider) return null;
return {
provider: provider.toLowerCase(),
kind: lead?.[1]?.toLowerCase() ?? null,
status: tail ? Number(tail[2]) : null,
code: tail?.[3] ?? null,
};
}
function requestAdvice({ kind, status, code }: ModelRequest, message: string, who: string): Advice {
// These kinds fail on Fabro's side, before or without the provider's say.
if (kind === "configuration" || kind === "model_selection") {
return {
headline: `Fabro couldn't send the request to ${who}`,
nextStep: `Check ${who} and the step's model under Settings → Models, then ${RETRY}.`,
};
}
if (kind === "network") {
return {
headline: `The request never reached ${who}`,
nextStep: "Check that the Fabro server can reach the provider, then choose Retry from Actions.",
};
}
if (kind === "middleware" || kind === "resource_limit") {
return { headline: `Fabro stopped the request to ${who}`, nextStep: "The message, under Details, says why." };
}
if (
kind === "quota_exceeded" ||
status === 402 ||
/credit balance|insufficient[_ ]quota|payment required|billing|spend limit/i.test(message)
) {
return {
headline: `${who} declined the request for billing reasons`,
nextStep: `Add credit or raise the spend limit with ${who}, then ${RETRY}.`,
};
}
if (kind === "authentication" || status === 401) {
return { headline: `${who} rejected the API key`, nextStep: `Check the key under Settings → Secrets, then ${RETRY}.` };
}
if (kind === "access_denied" || status === 403) {
return {
headline: `${who} denied access to the request`,
nextStep: `The key works, but ${who} doesn't allow this account to make the call. ${who}'s message, under Details, says why.`,
};
}
if (kind === "rate_limit" || status === 429) {
return { headline: `${who} rate-limited the request`, nextStep: "This is usually temporary. Choose Retry from Actions in a few minutes." };
}
if (kind === "timeout" || /timed out/i.test(message)) {
return { headline: `The request to ${who} timed out`, nextStep: "This is usually temporary. Choose Retry from Actions in a few minutes." };
}
if ((status !== null && status >= 500) || /overloaded/i.test(message)) {
return { headline: `${who} was unavailable`, nextStep: "This is usually temporary. Choose Retry from Actions in a few minutes." };
}
const what = [status, code?.replace(/_/g, " ")].filter(Boolean).join(" ");
return {
headline: what ? `${who} returned ${what}` : `${who} rejected the request`,
nextStep: `${who}'s message, under Details, says why.`,
};
}
// A transient model request failure keeps requestAdvice's wording, which
// names the provider, so transient infrastructure is checked here.
function stepAdvice(
message: string,
reason: FailureReason,
category: FailureCategory,
output: string | null,
): Advice {
const exit = /exited with (?:status|code) (\d+)/i.exec(message);
if (exit) {
return {
headline: `The step's command exited with status ${exit[1]}`,
nextStep: output ? "Its output, under Details, usually says why." : "Open the step's logs for its output.",
};
}
if (reason === FailureReason.TRANSIENT_INFRA || category === FailureCategory.TRANSIENT_INFRA) {
return { headline: "The step hit a temporary infrastructure error", nextStep: "Choose Retry from Actions in a few minutes." };
}
return { headline: firstSentence(message), nextStep: "Open the failed step's logs for details." };
}
/**
* The key of the failed step the run stopped at: the latest failed step that
* no later step went on from. A step that started later in a sibling branch
* of the same fan-out ran beside it, not after it, so it doesn't count; an
* earlier failure that a later step recovered from isn't named.
*/
function stoppedAt(stages: FailureState["stages"]): string | null {
const started = Object.entries(stages).flatMap(([key, stage]) => {
const at = stage.started_at ? Date.parse(stage.started_at) : NaN;
if (Number.isNaN(at)) return [];
const branch = stage.parallel_branch_id ?? null;
const group = branch && branch.includes(":") ? branch.slice(0, branch.lastIndexOf(":")) : null;
return [{ key, at, branch, group, failed: stage.state === "failed" }];
});
let stop: (typeof started)[number] | null = null;
for (const step of started) {
if (!step.failed) continue;
const wentOn = started.some(
(later) =>
later.at > step.at &&
later.group !== step.key &&
!(step.group !== null && later.group === step.group && later.branch !== step.branch),
);
if (!wentOn && (!stop || step.at > stop.at)) stop = step;
}
return stop?.key ?? null;
}
/** A stage key (`node@visit`) as the Stages sidebar labels it. */
function stageLabel(key: string | null): string | null {
if (!key) return null;
const at = key.lastIndexOf("@");
if (at <= 0) return key;
return formatStageLabel({ name: key.slice(0, at), visit: Number.parseInt(key.slice(at + 1), 10) || 1 });
}
function outputTail(tail: ExecOutputTail | null | undefined): string | null {
return lastLines([tail?.stderr, tail?.stdout].find((text) => text?.trim()));
}
function lastLines(stream: string | null | undefined): string | null {
// An offloaded output is a `blob://` reference, not text to show.
if (!stream?.trim() || stream.startsWith("blob://")) return null;
// Carriage-return progress lines keep only what was drawn last.
const lines = stream.trimEnd().split(/\r?\n/).map((line) => line.slice(line.lastIndexOf("\r") + 1));
return lines.slice(-OUTPUT_LINES).join("\n");
}
function firstSentence(message: string): string {
const sentence = message.split(/(?<=[.!?])\s+/)[0]!.trim().replace(/\s+/g, " ");
const chars = Array.from(sentence.charAt(0).toUpperCase() + sentence.slice(1));
return chars.length > HEADLINE_CHARS ? `${chars.slice(0, HEADLINE_CHARS).join("").trimEnd()}…` : chars.join("");
}

View file

@ -7,6 +7,7 @@ import {
canArchive,
canCancel,
canDelete,
canRetry,
canUnarchive,
cancellationSuccessMessage,
mapError,
@ -55,6 +56,7 @@ export function updateLifecycleToastState(
export function lifecycleActionVisibility(status: string | null | undefined) {
return {
showPrimaryCancel: canCancel(status),
showRetry: canRetry(status),
showArchive: canArchive(status),
showUnarchive: canUnarchive(status),
showDelete: canDelete(status),

View file

@ -225,6 +225,55 @@ describe("RunFiles rendering", () => {
expect(multiFileDiffCalls[0].options.diffStyle).toBe("split");
});
test("previews Markdown files and can switch back to their diff", () => {
currentFilesPayload = makePayload(1);
currentFilesPayload.data[0] = {
change_kind: "added",
old_file: { name: "artifacts/planning/spec.md", contents: "" },
new_file: {
name: "artifacts/planning/spec.md",
contents: "# Plan\n\n- Review this",
},
};
const renderer = renderRunFiles();
expect(renderer.root.findAllByProps({ "data-markdown-preview": "true" })).toHaveLength(1);
const renderedMarkdown = renderer.root.findAll(
(node) => typeof node.props.dangerouslySetInnerHTML?.__html === "string",
);
expect(renderedMarkdown).toHaveLength(1);
expect(renderedMarkdown[0].props.dangerouslySetInnerHTML.__html).toContain(
"<h1>Plan</h1>",
);
expect(multiFileDiffCalls).toHaveLength(0);
const changesButton = renderer.root
.findAllByType("button")
.find((button) => button.children.includes("Changes"));
expect(changesButton).toBeDefined();
act(() => {
changesButton!.props.onClick();
});
expect(multiFileDiffCalls).toHaveLength(1);
});
test("shows deleted Markdown files as a diff instead of an empty preview", () => {
currentFilesPayload = makePayload(1);
currentFilesPayload.data[0] = {
change_kind: "deleted",
old_file: { name: "docs/plan.md", contents: "# Plan\n\nReview this\n" },
new_file: { name: "", contents: "" },
};
const renderer = renderRunFiles();
expect(renderer.root.findAllByProps({ "data-markdown-preview": "true" })).toHaveLength(0);
expect(multiFileDiffCalls).toHaveLength(1);
expect(multiFileDiffCalls[0].oldFile.contents).toBe("# Plan\n\nReview this\n");
expect(multiFileDiffCalls[0].newFile.contents).toBe("");
});
test("passes the selected URL scope to useRunFiles", () => {
currentFilesPayload = makePayload(1);

View file

@ -15,6 +15,7 @@ import {
PatchDiff,
type FileContents,
} from "@pierre/diffs/react";
import { Markdown } from "../components/markdown";
import { useToast } from "../components/toast";
import { importChunk } from "../lib/import-chunk";
import type {
@ -74,6 +75,8 @@ const DIFF_STYLE_STORAGE_KEY = "fabro.run-files.diff-style";
// resolve a cached/304 refetch in tens of ms, leaving the user unsure
// whether the click registered.
const MIN_REFRESH_SPIN_MS = 500;
const MARKDOWN_PREVIEW_CLASS =
"rounded-md border border-line bg-panel px-8 py-6";
export const ErrorBoundary = RunFilesErrorBoundary;
@ -251,6 +254,11 @@ const RunFileRow = memo(function RunFileRow({
const newContents = file.new_file.contents;
const oldPath = file.old_file.name || display;
const newPath = file.new_file.name || display;
const canPreviewMarkdown =
file.change_kind !== "deleted" &&
/\.md$/i.test(newPath) && newContents != null && !placeholder;
const [showMarkdownPreview, setShowMarkdownPreview] =
useState(canPreviewMarkdown);
const oldFile = useMemo<FileContents | null>(() => {
if (oldContents == null) return null;
@ -297,6 +305,12 @@ const RunFileRow = memo(function RunFileRow({
let body: ReactElement | null = null;
if (placeholder) {
body = placeholder;
} else if (canPreviewMarkdown && showMarkdownPreview) {
body = (
<div className={MARKDOWN_PREVIEW_CLASS} data-markdown-preview="true">
<Markdown content={newContents} />
</div>
);
} else if (oldFile && newFile) {
body = (
<MultiFileDiff
@ -323,6 +337,31 @@ const RunFileRow = memo(function RunFileRow({
aria-label={`${file.change_kind ?? "modified"}: ${display}`}
className="focus:outline-2 focus:outline-focus focus:outline-offset-2 rounded-md"
>
{canPreviewMarkdown ? (
<header className="mb-2 flex items-center justify-between gap-3 rounded-md border border-line bg-panel-alt px-3 py-2">
<span className="truncate font-mono text-xs text-fg-2" title={display}>
{display}
</span>
<div className="flex shrink-0 rounded-md bg-overlay p-0.5 text-xs">
<button
type="button"
aria-pressed={showMarkdownPreview}
onClick={() => setShowMarkdownPreview(true)}
className={`rounded px-2 py-1 ${showMarkdownPreview ? "bg-panel text-fg" : "text-fg-muted hover:text-fg-2"}`}
>
Preview
</button>
<button
type="button"
aria-pressed={!showMarkdownPreview}
onClick={() => setShowMarkdownPreview(false)}
className={`rounded px-2 py-1 ${showMarkdownPreview ? "text-fg-muted hover:text-fg-2" : "bg-panel text-fg"}`}
>
Changes
</button>
</div>
</header>
) : null}
{body}
</section>
);

View file

@ -21,8 +21,6 @@ mock.module("../lib/queries", () => ({
mutate: graphMutateMock,
}),
useRunGraphSource: () => ({ data: undefined }),
useRunState: () => ({ data: undefined }),
useRunStream: () => ({ data: undefined }),
}));
mock.module("../components/run-summary-panel", () => ({

View file

@ -1,9 +1,9 @@
import { useCallback, useEffect, useMemo, useRef, useState } from "react";
import { useNavigate, useParams } from "react-router";
import { stagePath } from "../lib/stage-routes";
import { ApiError } from "../lib/api-client";
import { useRun, useRunGraph, useRunGraphSource, useRunStages } from "../lib/queries";
import { FloatingTooltip } from "../components/floating-tooltip";
import { PlatformRecordsPanel } from "../components/platform-records-panel";
import { RunSummaryPanel } from "../components/run-summary-panel";
import { StagePopover } from "../components/stage-popover";
import { StageSidebar } from "../components/stage-sidebar";
@ -76,7 +76,9 @@ export default function RunOverview() {
const [hoveredNode, setHoveredNode] = useState<RunGraphNodeHover | null>(null);
const openStage = useCallback(
(stageId: string) => navigate(`/runs/${id}/stages/${stageId}`),
(stageId: string) => {
if (id) navigate(stagePath(id, stageId));
},
[id, navigate],
);
useAnnotatedRunGraphSvg({
@ -151,9 +153,8 @@ export default function RunOverview() {
</div>
<div className="flex min-h-0 min-w-0 flex-1 flex-col gap-4 pb-[var(--fabro-interview-dock-clearance,0px)]">
<div className="shrink-0 space-y-4">
<div className="shrink-0">
<RunSummaryPanel runId={id!} />
<PlatformRecordsPanel runId={id!} />
</div>
{graphSvg === undefined && graphQuery.isLoading ? (
<div className="flex-1" />

View file

@ -10,7 +10,6 @@ import type { RunStage } from "@qltysh/fabro-api-client";
import TestRenderer, { act } from "react-test-renderer";
import { MemoryRouter } from "react-router";
import { PlatformRecordsPanelView } from "../components/platform-records-panel";
import { RunWaterfall } from "../components/run-waterfall";
import { StageSidebar } from "../components/stage-sidebar";
import { FanInResults } from "../components/stage-renderers/fan-in-results";
@ -25,11 +24,12 @@ import {
itemsForStage,
parallelOverviewFromProjection,
parsePetriInterviewPairs,
platformRecordsOf,
petriParsed,
reducerTranscriptFromProjection,
stagesFromProjection,
} from "../lib/petri-stream";
import { setupReactTestEnv } from "../lib/test-utils";
import { getObject } from "../lib/unknown";
import { StreamEventsView } from "./run-events";
import { StageChatView, buildPetriStageActivity } from "./run-stages";
@ -177,8 +177,8 @@ describe("a two-branch parallel run", () => {
/>,
);
expect(html).toContain("Branches");
expect(html).toContain("/runs/run-1/stages/a@1");
expect(html).toContain("/runs/run-1/stages/b@1");
expect(html).toContain("/runs/run-1/stages/a%401");
expect(html).toContain("/runs/run-1/stages/b%401");
expect((html.match(/Succeeded/g) ?? []).length).toBeGreaterThanOrEqual(2);
});
@ -195,7 +195,7 @@ describe("a two-branch parallel run", () => {
expect(html).not.toContain("Reducer transcript");
});
test("the events view lists Petri events by name and the platform notice", () => {
test("the events view lists Petri events, platform notices and checkpoints", () => {
const html = render(
<StreamEventsView
rows={debugRowsFromStream(fixture.stream)}
@ -210,29 +210,11 @@ describe("a two-branch parallel run", () => {
expect(html).toContain(name);
}
expect(html).toContain("run.notice");
expect(html).toContain("checkpoint");
expect(html).toContain('"data-stage":"a@1"');
expect(html).toContain(`${fixture.stream.length} items`);
});
test("the overview lists the platform records", () => {
const html = render(
<PlatformRecordsPanelView
records={platformRecordsOf(fixture.stream)}
projection={fixture.projection}
/>,
);
expect(html).toContain("Platform records");
expect(html).toContain("Notice");
expect(html).toContain("recorded while both branches ran");
// The checkpoint hook wrote one record per stage, with its commit.
expect(html).toContain("Checkpoint");
const checkpoint = fixture.stream.find(
(item) => item.kind === "platform" && item.item.record?.kind === "checkpoint",
);
expect(checkpoint).toBeDefined();
expect(html).toContain(String(checkpoint!.item.record.git_commit_sha).slice(0, 12));
});
test("the sidebar groups the branches under the fork", () => {
const branches = stages.filter((stage) => stage.parallelGroupId === "fork@1");
expect(branches.map((stage) => stage.id)).toEqual(["a@1", "b@1"]);
@ -274,7 +256,7 @@ describe("a human gate answered through the API", () => {
runId="run-1"
/>,
);
expect(html).toContain("/runs/run-1/stages/no@1");
expect(html).toContain("/runs/run-1/stages/no%401");
expect(html).not.toContain("No target");
});
@ -282,4 +264,48 @@ describe("a human gate answered through the API", () => {
expect(Object.keys(fixture.projection.pending_interviews)).toEqual([]);
expect(stages.map((stage) => stage.id)).toEqual(["start@1", "gate@1", "no@1", "exit@1"]);
});
test.each([
["https://example.com/review/%2Fdraft?revision=one&token=a%2Bb#feedback", true],
["javascript:alert(1)", false],
["https://user:password@example.com/review", false],
["/relative/review", false],
["ftp://example.com/review", false],
])("answered Q&A preserves safe review links after replay: %s", (url, linked) => {
// Add a reference to the real API-captured gate stream; keep its delivered
// answer and settled projection, which has no pending interview left.
const stream = structuredClone(fixture.stream);
const question = stream.map((item) => getObject(petriParsed(item), "question")).find(Boolean)!;
question.text = "Review the design document, then choose the next action.";
question.reference = { label: "Design review", url, kind: "document" };
const gate = stages.find((stage) => stage.id === "gate@1")!;
for (const events of [stream, JSON.parse(JSON.stringify(stream))]) {
let renderer!: TestRenderer.ReactTestRenderer;
act(() => {
renderer = TestRenderer.create(
<HumanQA stage={gate} pairs={parsePetriInterviewPairs(events)} />,
);
});
try {
const links = renderer.root.findAllByType("a");
expect(links).toHaveLength(linked ? 1 : 0);
if (linked) {
expect(links[0].props).toMatchObject({
href: url,
target: "_blank",
rel: "noopener noreferrer",
referrerPolicy: "no-referrer",
});
expect(links[0].findByType("span").children).toEqual(["Design review"]);
} else {
expect(JSON.stringify(renderer.toJSON())).toContain(question.text);
}
expect(JSON.stringify(renderer.toJSON())).toContain("Answered");
expect(JSON.stringify(renderer.toJSON())).toContain("dev");
} finally {
act(() => renderer.unmount());
}
}
});
});

View file

@ -0,0 +1,331 @@
import { afterEach, beforeEach, describe, expect, mock, test } from "bun:test";
import type { ReactNode } from "react";
import TestRenderer, { act } from "react-test-renderer";
import { createMemoryRouter, Outlet, RouterProvider } from "react-router";
import { loadPetriFixture } from "../lib/petri-fixtures";
import { makeStage, setupReactTestEnv, textContent } from "../lib/test-utils";
import { ParallelChildren } from "../components/stage-renderers/parallel-children";
import { ConditionalDecision } from "../components/stage-renderers/conditional-decision";
import { StagePopover } from "../components/stage-popover";
import { RunWaterfall } from "../components/run-waterfall";
const ids = [
"reviewer@1",
"reviewer/e2@1",
"reviewer/50%@1",
"reviewer%20x@1",
"reviewer%2Fe2@1",
"reviewer%252Fe2@1",
"reviewer?x#y@1",
"réview/日本@1",
];
const fixture = loadPetriFixture("command");
const stages = ids.map((id) => ({
id,
name: id.slice(0, -2),
node_id: id.slice(0, -2),
visit: 1,
handler: "command",
status: "succeeded",
usage: fixture.projection.stages["say@1"].usage,
}));
const projection = {
...fixture.projection,
stages: Object.fromEntries(
ids.map((id) => [id, fixture.projection.stages["say@1"]]),
),
};
// Keep real Petri records and give each occurrence a visibly distinct command.
const stream = ids.flatMap((id) =>
fixture.stream
.filter(
(entry) =>
entry.kind === "petri" && entry.item.subject?.node?.name === "say",
)
.map((entry) => {
const copy = structuredClone(entry);
copy.item.subject.node.name = id.slice(0, -2);
copy.item.subject.node.meta.script = `echo selected:${id}`;
return copy;
}),
);
let loading = false;
let available = stages;
const logRequests: string[] = [];
mock.module("../lib/queries", () => ({
useRunGraph: () => ({ data: undefined }),
useRunGraphSource: () => ({ data: undefined }),
useRun: () => ({ data: undefined }),
useRunStages: () => ({
data: loading ? undefined : { data: available },
isLoading: loading,
}),
useRunState: () => ({ data: projection }),
useRunStream: () => ({ data: stream }),
useRunStageContextWindow: () => ({ data: undefined }),
useRunStageLog: (_runId: string, stageId: string) => {
logRequests.push(stageId);
const output = Buffer.from(`output:${stageId}`, "utf8");
return {
data: {
bytes_base64: output.toString("base64"),
next_offset: output.length,
total_bytes: output.length,
},
};
},
}));
mock.module("../components/run-summary-panel", () => ({
RunSummaryPanel: () => null,
}));
let graphClick: (id: string) => void;
mock.module("../hooks/use-annotated-run-graph-svg", () => ({
useAnnotatedRunGraphSvg: ({
onStageClick,
}: {
onStageClick: (id: string) => void;
}) => {
graphClick = onStageClick;
},
}));
const { default: RunOverview } = await import("./run-overview");
const { default: RunStages } = await import("./run-stages");
let renderer: TestRenderer.ReactTestRenderer;
let teardown: () => void;
beforeEach(() => {
teardown = setupReactTestEnv();
loading = false;
available = stages;
logRequests.length = 0;
});
afterEach(() => {
if (renderer) act(() => renderer.unmount());
teardown();
});
function render(entry = "/runs/run-1/stages", source?: ReactNode) {
const router = createMemoryRouter(
[
{
path: "/runs/:id",
element: <Outlet />,
children: [
{ index: true, element: source ?? <RunOverview /> },
{ path: "stages", element: <RunStages /> },
{ path: "stages/:stageId", element: <RunStages /> },
],
},
],
{ initialEntries: [entry] },
);
act(() => {
renderer = TestRenderer.create(<RouterProvider router={router} />);
});
return router;
}
async function clickStage(id: string) {
const link = renderer.root
.findAllByType("a")
.find(
(node) =>
node.props.href.includes("/stages/") &&
node
.findAllByType("span")
.some((span) => textContent(span) === id.slice(0, -2)),
);
expect(link).toBeDefined();
await act(async () =>
link!.props.onClick({
button: 0,
defaultPrevented: false,
preventDefault() {
this.defaultPrevented = true;
},
}),
);
}
function expectSelected(id: string) {
const text = textContent(renderer.root);
expect(text).toContain(`echo selected:${id}`);
expect(text).toContain(`output:${id}`);
expect(logRequests.at(-1)).toBe(id);
const active = renderer.root
.findAllByType("a")
.filter((node) => node.props.className?.includes("bg-overlay text-fg"));
expect(active).toHaveLength(1);
expect(active[0].props.href).toBe(
`/runs/run-1/stages/${encodeURIComponent(id)}`,
);
for (const other of ids.filter((value) => value !== id)) {
expect(text).not.toContain(`echo selected:${other}`);
expect(text).not.toContain(`output:${other}`);
}
}
describe("stage occurrence navigation", () => {
test.each(ids)("clicking the sidebar opens exactly %s", async (id) => {
const router = render();
await clickStage(id);
expect(router.state.location.pathname).toBe(
`/runs/run-1/stages/${encodeURIComponent(id)}`,
);
expectSelected(id);
});
test.each(ids)("direct links preserve %s through the nested route", (id) => {
render(`/runs/run-1/stages/${encodeURIComponent(id)}/?view=detail#output`);
expectSelected(id);
});
test("back and forward restore the exact occurrence", async () => {
const router = render();
await clickStage(ids[1]);
await clickStage(ids[4]);
await act(async () => {
await router.navigate(-1);
});
expectSelected(ids[1]);
await act(async () => {
await router.navigate(1);
});
expectSelected(ids[4]);
});
test("the stage index still selects the first stage", () => {
render();
expectSelected(ids[0]);
});
test.each(["missing%401", "bad%ZZ"])(
"an explicit unavailable ID %s never selects another stage",
(segment) => {
render(`/runs/run-1/stages/${segment}`);
expect(textContent(renderer.root)).toContain("Stage not found");
expect(logRequests).toEqual([]);
},
);
test("an explicit ID waits for the stage list then selects it", async () => {
loading = true;
const router = render(`/runs/run-1/stages/${encodeURIComponent(ids[1])}`);
expect(textContent(renderer.root)).toContain("Loading stages");
expect(textContent(renderer.root)).not.toContain("Stage not found");
loading = false;
await act(async () => {
await router.navigate(router.state.location.pathname, { replace: true });
});
expectSelected(ids[1]);
});
});
describe("other stage navigation surfaces", () => {
const target = makeStage({
id: ids[1],
name: "reviewer/e2",
nodeId: "reviewer/e2",
handler: "command",
status: "succeeded",
parallelGroupId: "fork@1",
parallelBranchIndex: 0,
});
const source = makeStage({
id: "fork@1",
nodeId: "fork",
status: "succeeded",
});
const producers = [
[
"parallel child",
<ParallelChildren
stage={source}
runId="run-1"
allStages={[target]}
overview={{ branchCount: 1, results: [] }}
/>,
],
[
"conditional target",
<ConditionalDecision
stage={source}
runId="run-1"
allStages={[target]}
edge={{
fromNode: "fork",
toNode: target.nodeId,
reason: "unconditional",
condition: null,
}}
/>,
],
[
"resumed-stage popover",
<StagePopover
stage={{ ...source, resumedFromStageId: target.id }}
runId="run-1"
duration="1s"
/>,
],
[
"waterfall",
<RunWaterfall
runId="run-1"
phases={[]}
stages={[
{
...stages[1],
started_at: "2026-10-20T12:00:00Z",
wall_time_ms: 1000,
},
]}
createdAtIso="2026-10-20T12:00:00Z"
completedAtIso="2026-10-20T12:00:02Z"
/>,
],
] as const;
test.each(producers)(
"%s opens the offered occurrence",
async (_name, element) => {
const router = render("/runs/run-1", element);
const link = renderer.root
.findAllByType("a")
.find((node) => node.props.href.includes("/stages/"));
expect(link).toBeDefined();
await act(async () =>
link!.props.onClick({
button: 0,
defaultPrevented: false,
preventDefault() {
this.defaultPrevented = true;
},
}),
);
expect(router.state.location.pathname).toBe(
`/runs/run-1/stages/${encodeURIComponent(target.id)}`,
);
expectSelected(target.id);
},
);
test("the resumed-stage banner opens the source occurrence", async () => {
available = stages.map((stage, index) =>
index === 0 ? { ...stage, resumed_from_stage_id: ids[1] } : stage,
);
render();
const link = renderer.root
.findAllByType("a")
.find((node) => textContent(node) === ids[1]);
await act(async () =>
link!.props.onClick({
button: 0,
defaultPrevented: false,
preventDefault() {
this.defaultPrevented = true;
},
}),
);
expectSelected(ids[1]);
});
test("the graph stage-click handler navigates to the offered occurrence", async () => {
const router = render("/runs/run-1");
await act(async () => graphClick(ids[1]));
expect(router.state.location.pathname).toBe(
`/runs/run-1/stages/${encodeURIComponent(ids[1])}`,
);
expectSelected(ids[1]);
});
});

View file

@ -5,7 +5,7 @@ import {
useState,
type ReactNode,
} from "react";
import { Link, useParams } from "react-router";
import { Link, useLocation, useParams } from "react-router";
import {
ArrowDownTrayIcon,
ChevronDownIcon,
@ -38,6 +38,7 @@ import type {
ThreadDnaItem,
ThreadDnaSelection,
} from "../components/event-debug";
import { stageIdFromPathname, stagePath } from "../lib/stage-routes";
import { StageContext } from "../components/stage-context";
import { StageInsightsSidebar } from "../components/stage-insights-sidebar";
import { StageSidebar } from "../components/stage-sidebar";
@ -2374,7 +2375,7 @@ function RunStageActivityStage({
<p className="pb-2 text-xs text-fg-muted">
Resumed from{" "}
<Link
to={`/runs/${runId}/stages/${encodeURIComponent(selectedStage.resumedFromStageId)}`}
to={stagePath(runId, selectedStage.resumedFromStageId)}
className="font-mono text-teal-500 hover:underline"
>
{selectedStage.resumedFromStageId}
@ -2526,7 +2527,9 @@ function RunStageActivity({
}
export default function RunStages() {
const { id, stageId } = useParams();
const { id, stageId: stageParam } = useParams();
const { pathname } = useLocation();
const stageId = stageIdFromPathname(pathname);
const runQuery = useRun(id);
const stagesQuery = useRunStages(id);
const stages = useMemo(
@ -2535,7 +2538,9 @@ export default function RunStages() {
);
const selectedStage =
stages.find((s: Stage) => s.id === stageId) ?? stages[0];
stageParam === undefined
? stages[0]
: stages.find((s: Stage) => s.id === stageId);
const selectedStageId = selectedStage?.id;
const runStart =
selectedStage?.startedAt ??
@ -2563,6 +2568,25 @@ export default function RunStages() {
? runStateQuery.data?.stages[selectedStageId]
: undefined;
if (stagesQuery.isLoading && !stagesQuery.data) {
return (
<div className="py-12">
<EmptyState title="Loading stages" description="Fetching the run’s stages." />
</div>
);
}
if (id && stageParam !== undefined && !selectedStage) {
return (
<div className="py-12">
<EmptyState
title="Stage not found"
description="This stage occurrence is not available in this run."
/>
</div>
);
}
if (!id || !selectedStage) {
return (
<div className="py-12">

View file

@ -31,6 +31,7 @@ import { formatContextWindow, formatTokensPerSecond } from "../lib/format";
import {
modelOfferingKey,
modelOfferingTestArgs,
providerNamesById,
} from "../lib/model-offerings";
import { useDebouncedValue } from "../hooks/effects";
@ -244,11 +245,7 @@ function ModelsSection({ providers }: { providers: Provider[] }) {
const { data, isLoading } = useModels(providerFilter, debouncedSearch);
const providerNameById = useMemo(() => {
const map = new Map<string, string>();
for (const p of providers) map.set(p.id, p.display_name || p.id);
return map;
}, [providers]);
const providerNameById = useMemo(() => providerNamesById(providers), [providers]);
const rows = useMemo(() => {
const all = (data?.data ?? []).filter((m) => m.configured);

View file

@ -36,10 +36,6 @@
"git": {
"author": null
},
"prepare": {
"steps": [],
"timeout_ms": 300000
},
"execution": {
"mode": "normal",
"approval": "prompt"
@ -511,10 +507,6 @@
"git": {
"author": null
},
"prepare": {
"steps": [],
"timeout_ms": 300000
},
"execution": {
"mode": "normal",
"approval": "prompt"

View file

@ -36,10 +36,6 @@
"git": {
"author": null
},
"prepare": {
"steps": [],
"timeout_ms": 300000
},
"execution": {
"mode": "normal",
"approval": "prompt"
@ -633,10 +629,6 @@
"git": {
"author": null
},
"prepare": {
"steps": [],
"timeout_ms": 300000
},
"execution": {
"mode": "normal",
"approval": "prompt"

View file

@ -36,10 +36,6 @@
"git": {
"author": null
},
"prepare": {
"steps": [],
"timeout_ms": 300000
},
"execution": {
"mode": "normal",
"approval": "prompt"
@ -809,10 +805,6 @@
"git": {
"author": null
},
"prepare": {
"steps": [],
"timeout_ms": 300000
},
"execution": {
"mode": "normal",
"approval": "prompt"

View file

@ -36,10 +36,6 @@
"git": {
"author": null
},
"prepare": {
"steps": [],
"timeout_ms": 300000
},
"execution": {
"mode": "normal",
"approval": "prompt"
@ -833,10 +829,6 @@
"git": {
"author": null
},
"prepare": {
"steps": [],
"timeout_ms": 300000
},
"execution": {
"mode": "normal",
"approval": "prompt"

View file

@ -43,22 +43,36 @@ the vault:
`FABRO_JWT_PRIVATE_KEY` and `FABRO_JWT_PUBLIC_KEY` are removed. `SESSION_SECRET` is the single auth root.
Provisioning into the vault is not the same as the resolver being vault-only. `VaultCredentialSource`
(`lib/foundation/fabro-auth/src/vault_source.rs`) reads each secret name lithos-llm asks for from
the process environment first and the vault second, under the same conventional names. Which paths
that environment lookup is live on is a per-process question:
For conventional provider API-key names, `VaultCredentialSource::new` and
`SqlVaultCredentialSource::new` check the process environment before the vault. Their
`vault_only` constructors disable that lookup. OAuth records and interpolated secret headers
resolve through the vault separately. The owning process chooses the source:
- **Server process** — inert. `lib/apps/fabro-server/src/server.rs:2453` builds
`SqlVaultCredentialSource::vault_only(...)`, so the env lookup always returns `None`.
- **Worker process** — wired but effectively inert for provider keys. `build_llm_source`
(`lib/components/fabro-workflow/src/pipeline/initialize.rs:275`) builds the run's credential
source with `VaultCredentialSource::new`, which carries the process-env fallback; the
provider-listing path does the same via `with_env_lookup(process_env_var)`
(`operations/start.rs:529`). But the worker's env was cleared and repopulated from
`WORKER_ENV_ALLOWLIST` (`lib/apps/fabro-server/src/spawn_env.rs:6`), which does not include
provider API keys. Exporting a provider key in the server's shell therefore has no effect on runs.
- **`fabro exec` and direct `fabro-llm` SDK usage** — live. These have no vault and read process
env deliberately.
- **Server process** — `lib/apps/fabro-server/src/server.rs` constructs
`SqlVaultCredentialSource::vault_only(...)`. Model calls, provider listing and gateway
completions therefore do not use process-environment provider API keys.
- **Worker process** — `runtime_spec` in
`lib/apps/fabro-cli/src/commands/run/petri_worker.rs` constructs `VaultCredentialSource::new`.
The worker environment is cleared and repopulated from `WORKER_ENV_ALLOWLIST` in
`lib/apps/fabro-server/src/spawn_env.rs`, which excludes conventional provider API keys,
including Bedrock bearer tokens. Exporting them in the server's shell has no effect on runs.
- **Direct `fabro exec` (no server target)** — `CommandContext::llm_source` in
`lib/apps/fabro-cli/src/command_context.rs` opens the local SQL secret store and constructs
`SqlVaultCredentialSource::new`. Conventional API keys use environment-first lookup,
then that local store.
- **`fabro exec --server ...`** — `FABRO_SERVER` also selects this mode. The CLI sends completions through the gateway; the target
server resolves credentials using its vault-only source.
- **Direct SDK usage** — the caller selects a `CredentialProvider`. For example,
`VaultCredentialSource::environment_only()` explicitly reads process-environment keys.
Bedrock SigV4 is a separate mechanism: the AWS default credential chain's identity inputs
are deliberately allowlisted into workers so sessions can refresh. This does not enable
environment lookup for Bedrock bearer tokens. Providers with no authentication need no key.
Installation can accept an explicit stdin or named-environment credential input and persist
it in the vault; this is provisioning, not a runtime fallback. Endpoint catalog overrides such
as `OPENAI_BASE_URL` are also independent of credential lookup. The public contract lives in
`docs/public/core-concepts/models.mdx` under **Credential sources**.
## Which process resolves what

View file

@ -18,7 +18,7 @@ Fabro only reads `settings.toml`. Older `server.toml`, `user.toml`, and `cli.tom
| Scope | Examples |
|---|---|
| Server-owned (runtime-only from local `settings.toml`) | `[server.listen]`, `[server.api]`, `[server.web]`, `[server.auth]`, `[server.sandbox]`, `[server.storage]`, `[server.artifacts]`, `[server.scheduler]`, `[server.approvals]`, `[server.logging]`, `[server.integrations]` |
| Shared run defaults (layered through `.fabro/project.toml`/`workflow.toml`) | `[run.model]`, `[run.prepare]`, `[run.environment]`, `[environments.<slug>]`, `[run.checkpoint]`, `[run.inputs]`, `[run.pull_request]`, `[run.git]`, `[run.hooks]`, `[run.agent]` |
| Shared run defaults (layered through `.fabro/project.toml`/`workflow.toml`) | `[run.model]`, `[run.environment]`, `[environments.<slug>]`, `[run.checkpoint]`, `[run.inputs]`, `[run.pull_request]`, `[run.git]`, `[run.hooks]`, `[run.agent]` |
The CLI-only `[cli.*]` sections (including `[cli.target]`) belong in the client machine's `settings.toml`. They tell CLI commands how to reach a server. The server process does not read `[cli.*]` for its own binding or routing.
@ -92,9 +92,6 @@ provider = "anthropic"
[run.model.fallbacks]
"claude-sonnet-4-5" = ["gemini", "openai"]
[[run.prepare.steps]]
script = "npm install"
[run.environment]
id = "cloud"
@ -286,7 +283,7 @@ Run creation uses the registered workflow version's `workflow.toml` above the se
Server-owned values like `[server.storage]`, `[server.api]`, `[server.web]`, `[server.scheduler]`, and `[server.approvals]` come from the server machine's `settings.toml` or `fabro server start` flags. Environments and MCP server references resolve against the server's catalogs.
Merge rules follow the normative matrix: TOML `[run.inputs]` tables replace wholesale, explicit intent inputs merge per key at highest precedence, environment `env` and `labels` merge by key, `[run.prepare.steps]` replaces whole-list, and `[[run.hooks]]` merge by optional `id`. Most other fields use "higher-precedence wins" field-wise merging.
Merge rules follow the normative matrix: TOML `[run.inputs]` tables replace wholesale, explicit intent inputs merge per key at highest precedence, environment `env` and `labels` merge by key, `[[run.hooks]]` merge by optional `id`. Most other fields use "higher-precedence wins" field-wise merging.
### `[server.approvals]` section
@ -315,7 +312,7 @@ The CLI has its own `[cli.logging]` section.
### `[run.git.author]` section
Override the Git author and committer identity for every commit a run creates: Fabro's own checkpoint and metadata commits, and any `git commit` a prepare step, command stage, or agent tool runs inside the sandbox. Fabro resolves one identity per run and injects it as `GIT_AUTHOR_NAME`, `GIT_AUTHOR_EMAIL`, `GIT_COMMITTER_NAME`, and `GIT_COMMITTER_EMAIL` into every workflow command, so the primary checkout, additional clones, and repositories a workflow clones itself all commit as the same identity. It does not write to any Git configuration file.
Override the Git author and committer identity for every commit a run creates: Fabro's own checkpoint and metadata commits, and any `git commit` a command stage or agent tool runs inside the sandbox. Fabro resolves one identity per run and injects it as `GIT_AUTHOR_NAME`, `GIT_AUTHOR_EMAIL`, `GIT_COMMITTER_NAME`, and `GIT_COMMITTER_EMAIL` into every workflow command, so the primary checkout, additional clones, and repositories a workflow clones itself all commit as the same identity. It does not write to any Git configuration file.
When a field is not set, Fabro derives it from the run's GitHub credential:
@ -409,7 +406,7 @@ fabro secret set OPENAI_API_KEY sk-...
fabro secret set GEMINI_API_KEY AI...
```
`fabro exec` and direct library usage can opt into env-backed credential sources explicitly. Runs cannot: the Fabro server reads provider keys from the vault after the temporary startup migration, and workers start from a cleared environment that does not inherit provider keys.
Exporting a conventional provider API key in the server's shell neither configures the provider nor overrides a vault value. Workers start from a cleared environment that does not inherit those keys. `fabro exec --server ...` also uses the target server's credentials. Direct `fabro exec` (no server target) checks the invoking process environment before its local secret store for conventional API-key names; SDK callers choose their credential source. Bedrock SigV4 uses the separate AWS default credential chain. See [Credential sources](/core-concepts/models#credential-sources) for the full distinction.
| Variable | Provider |
|---|---|
@ -526,3 +523,8 @@ fabro secret set FABRO_SLACK_APP_TOKEN xapp-...
|---|---|---|
| `FABRO_LOG` | `info` | Log level: `error`, `warn`, `info`, `debug` |
| `FABRO_LOG_DESTINATION` | Command-mode default | Server log destination: `file` or `stdout` |
Setup commands belong in each workflow as explicit command nodes after `start`,
or in a shared script those nodes invoke. The removed `run.prepare` setting is
rejected even when a workflow would override it. See the
[setup migration guide](/execution/run-configuration#setup-command-migration).

View file

@ -28,7 +28,7 @@ LLM provider probe failures are reported as errors. Use `--verbose` to see the u
**Server exited after I finished the install wizard** — Expected. The server writes `~/.fabro/settings.toml` and exits cleanly at the end of the wizard. Start it again with `fabro server start` to boot in configured mode, or run it under a supervisor with a restart policy (for example docker-compose `restart: unless-stopped`, systemd, or Railway's restart-on-exit) so the second start happens automatically.
**"No API key configured"** — For runs, set at least one provider key in the server vault with `fabro provider login` or `fabro secret set`; workers start from a cleared environment, so exporting a provider key in the server's shell has no effect on runs. `fabro exec` and direct library usage can use env-backed credential sources explicitly. Run `fabro doctor` to verify server connectivity.
**"No API key configured"** — For runs, set at least one provider key in the server vault with `fabro provider login` or `fabro secret set`; workers start from a cleared environment, so exporting a provider key in the server's shell has no effect on runs. Direct `fabro exec` (no server target) can read keys from the invoking shell or local secret store; `fabro exec --server ...` uses the target server's vault. SDK callers choose their credential source. See [Credential sources](/core-concepts/models#credential-sources). Run `fabro doctor` to verify server connectivity.
**Stall watchdog timeouts** — If runs are cancelled unexpectedly, the agent may be stuck or the LLM provider may be slow. Check `FABRO_LOG=debug` output for `Agent.LlmRetry` events. Increase `stall_timeout` in the graph if needed, or add [fallback providers](/core-concepts/models) to handle outages.

View file

@ -5,31 +5,43 @@ description: "Run custom logic in response to workflow lifecycle events"
Hooks let you run custom logic at key points during a workflow — before a stage starts, after a run completes, when a sandbox is ready, and more. Use them for validation, notifications, guardrails, and orchestration without modifying the workflow graph itself.
The examples below are configuration fragments for `workflow.toml`. Add them to a workflow configuration using the current [run configuration schema](/execution/run-configuration).
## Hook types
Fabro supports four hook types, from simple shell commands to full agent sessions:
### Command
Run a shell command via `sh -c`. The simplest and most common hook type.
Use `script` for a shell command string. This is the simplest and most common hook type.
```toml title="run.toml"
[[hooks]]
```toml title="workflow.toml"
[[run.hooks]]
event = "stage_start"
command = "./scripts/pre-check.sh"
script = "./scripts/pre-check.sh"
```
Alternatively, `command` accepts an array of strings:
```toml title="workflow.toml"
[[run.hooks]]
event = "post_tool_use"
command = ["cargo", "fmt"]
matcher = "write_file|edit_file|apply_patch"
```
Use either `script` or `command` for a command hook.
### HTTP
POST the event context as JSON to an HTTP endpoint. Useful for webhooks, external APIs, and notification services.
```toml title="run.toml"
[[hooks]]
```toml title="workflow.toml"
[[run.hooks]]
event = "run_complete"
type = "http"
url = "https://hooks.example.com/done"
[hooks.headers]
[run.hooks.headers]
X-Deployment-Environment = "{{ vars.DEPLOY_ENV }}"
```
@ -45,10 +57,9 @@ X-Deployment-Environment = "{{ vars.DEPLOY_ENV }}"
A single-turn LLM call that evaluates the event context and returns an `ok`/`block` decision. The model responds with structured JSON.
```toml title="run.toml"
[[hooks]]
```toml title="workflow.toml"
[[run.hooks]]
event = "stage_start"
type = "prompt"
prompt = "Should this stage proceed given the current context? Check for any red flags."
model = "haiku"
blocking = true
@ -63,10 +74,10 @@ blocking = true
A multi-turn agent session with full tool access (shell, file read/write, grep, glob). The agent can investigate the workspace before making a decision.
```toml title="run.toml"
[[hooks]]
```toml title="workflow.toml"
[[run.hooks]]
event = "run_complete"
type = "agent"
agent = "enabled"
prompt = "Verify that all tests pass and the code compiles. Run the test suite."
model = "sonnet"
max_tool_rounds = 10
@ -75,10 +86,13 @@ blocking = true
| Field | Description |
|---|---|
| `agent` | Set to `"enabled"` to select an agent hook. |
| `prompt` | Task instructions for the agent. |
| `model` | Model alias or ID. Defaults to `haiku`. |
| `max_tool_rounds` | Maximum tool call rounds before the agent gives up. Default: `50`. |
The `agent = "enabled"` marker selects an agent hook; `prompt` supplies its instructions. Without that marker, `prompt` selects a single-turn prompt hook.
## Lifecycle events
Each hook fires on a specific lifecycle event:
@ -104,34 +118,41 @@ Each hook fires on a specific lifecycle event:
## Configuration
Hooks are defined as `[[hooks]]` entries in any of these TOML config files:
Hooks are defined as `[[run.hooks]]` entries in any of these TOML config files:
- **`.fabro/project.toml`** — project-level hooks, apply to all workflows in the project
- **`workflow.toml`** — per-workflow hooks
- **`~/.fabro/settings.toml`** — global defaults for all runs
Each entry selects one transport: `script` or `command`, `url`, `prompt`, or `agent = "enabled"` together with `prompt`. Do not add a `type` field; the transport fields select the hook type.
See [Merging hook configs](#merging-hook-configs) for how these layers combine.
```toml title="run.toml"
[[hooks]]
name = "pre-check"
```toml title="workflow.toml"
[[run.hooks]]
id = "pre-check"
name = "Pre-check script"
event = "stage_start"
command = "./scripts/pre-check.sh"
script = "./scripts/pre-check.sh"
matcher = "agent"
blocking = true
timeout_ms = 30000
timeout = "30s"
sandbox = false
```
| Field | Description |
|---|---|
| `name` | Optional display name. Auto-generated from event and type if omitted. |
| `id` | Optional merge identity. Hooks with the same `id` replace each other across layers. |
| `name` | Optional display name; does not control merging. If omitted, the hook uses `id` or an auto-generated label. |
| `event` | The lifecycle event to listen for (required). |
| `command` | Shell command shorthand — implies `type = "command"`. |
| `type` | Explicit hook type: `"command"`, `"http"`, `"prompt"`, or `"agent"`. |
| `script` | Shell command string. |
| `command` | Command and arguments as an array of strings, such as `["cargo", "fmt"]`; an alternative to `script`. |
| `url` | Selects an HTTP hook. |
| `prompt` | Instructions for a prompt hook, or for an agent hook when `agent` is set. |
| `agent` | Set to `"enabled"` to select an agent hook. |
| `matcher` | Regex pattern to filter which stages trigger this hook. |
| `blocking` | Whether the hook must complete before execution continues. Defaults vary by event. |
| `timeout_ms` | Hook timeout in milliseconds. Default: `60000` (60s) for most types, `30000` (30s) for prompt hooks. |
| `timeout` | Duration string with a unit, such as `"500ms"`, `"30s"`, or `"2m"`. Default: `"30s"` for prompt hooks, `"60s"` for other types. |
| `sandbox` | Run inside the sandbox (`true`, default) or on the host (`false`). |
## Blocking vs. non-blocking
@ -211,34 +232,33 @@ For tool events, the matcher is tested against the tool's internal name (e.g., `
This example auto-formats Rust code whenever the agent writes or edits a file:
```toml
[[hooks]]
```toml title="workflow.toml"
[[run.hooks]]
name = "cargo-fmt"
event = "post_tool_use"
command = "cargo fmt"
script = "cargo fmt"
matcher = "write_file|edit_file|apply_patch"
blocking = true
```
More examples:
```toml
```toml title="workflow.toml"
# Only fire for agent handler nodes
[[hooks]]
[[run.hooks]]
event = "stage_start"
command = "./scripts/agent-guard.sh"
script = "./scripts/agent-guard.sh"
matcher = "^agent$"
# Fire for any node with "test" in its ID
[[hooks]]
[[run.hooks]]
event = "stage_complete"
command = "./scripts/report-test.sh"
script = "./scripts/report-test.sh"
matcher = "test"
# Gate shell commands with a guardrail
[[hooks]]
[[run.hooks]]
event = "pre_tool_use"
type = "prompt"
prompt = "Is this shell command safe to run?"
matcher = "^shell$"
model = "haiku"
@ -327,7 +347,7 @@ Each hook type has a default timeout:
| Prompt | 30 seconds |
| Agent | 60 seconds |
Override with `timeout_ms` on any hook definition. Prompt and agent hooks **fail open** on timeout — execution proceeds as if the hook returned `ok: true`.
Override with `timeout` on any hook definition, using a duration string such as `timeout = "30s"` or `timeout = "2m"`. Supported units are `ms`, `s`, `m`, `h`, and `d`. Prompt and agent hooks **fail open** on timeout — execution proceeds as if the hook returned `ok: true`.
## Fail-open behavior
@ -343,61 +363,61 @@ Command hooks do **not** fail open. A non-zero exit code (other than 0 or 2) pro
## Merging hook configs
Hooks from multiple config files are merged in this order (later layers win on name collisions):
Hooks from multiple config files are merged in this order (later layers replace hooks with the same `id`):
1. **`~/.fabro/settings.toml`** — global defaults
2. **`.fabro/project.toml`** — project-level overrides
3. **`workflow.toml`** — per-workflow overrides
This lets you define global hooks at the server level, project-wide hooks in `.fabro/project.toml`, and override or extend them per workflow.
Hooks with matching `id` values replace in place. Hooks without an `id` append after inherited hooks, even when their `name` matches. Use `id` when a workflow should override an inherited hook.
This lets you define global hooks at the server level, project-wide hooks in `.fabro/project.toml`, and override or extend them per workflow. See [configuration precedence](/execution/run-configuration#precedence) for the complete layer order.
## Full example
```toml title="run.toml"
```toml title="workflow.toml"
# Validate environment before the run starts
[[hooks]]
[[run.hooks]]
name = "env-check"
event = "run_start"
command = "./scripts/check-env.sh"
script = "./scripts/check-env.sh"
blocking = true
sandbox = false
# Notify Slack when a stage completes
[[hooks]]
[[run.hooks]]
name = "slack-notify"
event = "stage_complete"
type = "http"
url = "https://hooks.slack.com/workflows/T00/B00/abc123"
tls = "verify"
blocking = false
# LLM guardrail before agent stages
[[hooks]]
[[run.hooks]]
name = "safety-check"
event = "stage_start"
type = "prompt"
prompt = "Review the event context. Is there any reason this stage should not proceed?"
model = "haiku"
matcher = "^agent$"
blocking = true
timeout_ms = 15000
timeout = "15s"
# Post-run verification agent
[[hooks]]
[[run.hooks]]
name = "verify"
event = "run_complete"
type = "agent"
agent = "enabled"
prompt = "Run the test suite and verify all tests pass. Report any failures."
model = "sonnet"
max_tool_rounds = 20
blocking = true
timeout_ms = 120000
timeout = "2m"
# Auto-format Rust files after writes
[[hooks]]
[[run.hooks]]
name = "cargo-fmt"
event = "post_tool_use"
command = "cargo fmt"
script = "cargo fmt"
matcher = "write_file|edit_file|apply_patch"
blocking = true
```

View file

@ -8693,11 +8693,11 @@ components:
expected_secret_name:
type: ["string", "null"]
description: |
Suggested vault secret name for configuring this provider,
derived from the first vault credential reference in the
provider catalog. Null when the provider has no vault
credential (e.g. no-auth or env-only providers). Used to
prefill the create-secret form.
Suggested vault secret name for configuring this provider: the
first conventional secret name for its catalog authentication scheme.
Null when that scheme declares no conventional secret names (for
example, no-auth providers). Used to prefill the create-secret form;
providers such as Modal require more than one secret.
ProviderId:
description: LLM provider identifier.
@ -8868,10 +8868,12 @@ components:
configured:
type: boolean
description: |
Whether credential material is present for this model's provider on the
server (vault entry or environment variable). Does NOT imply the
credential is valid or that requests will succeed; call
`POST /models/{id}/test` to verify usability.
Whether the server resolved credentials and built a client for this
model's provider. Provider API keys and OAuth records come from the
server vault, not process environment variables. Bedrock SigV4 uses
the separate AWS default credential chain; no-auth providers need no
key. Does NOT imply authentication or model requests will succeed;
call `POST /models/{id}/test` to test usability.
ModelTestResult:
description: Result of testing a model in `basic` or `deep` mode.
@ -9012,12 +9014,16 @@ components:
model:
type: string
description: >-
Model selector: `provider/model`, a model id or alias, or a
provider id. The server picks a ready-provider default when
omitted.
Model selector: `provider/model`, or a model id or alias. A bare
provider name is rejected; pin it with `provider` instead. When
omitted, the server picks the pinned provider's default model, or
a ready-provider default when `provider` is also omitted.
provider:
type: string
description: Optional provider pin for a bare model selector.
description: >-
Optional provider pin. Scopes a bare model selector to that
provider, which also lets an uncatalogued model id reach a
provider that allows passthrough.
system:
type: string
description: System prompt (convenience; prepended as a system message).
@ -12803,8 +12809,7 @@ components:
The display graph of a run: the admitted workflow's name, goal,
stages and edges, read off the graph Petri admitted at create time.
Lowering artifacts (the goal check, a synthetic fan-in) are left out;
the stages are the nodes the workflow declares, imports and
`[run.prepare]` steps included.
the stages are the nodes the workflow declares, including imported nodes.
type: object
required: [name]
properties:
@ -15795,7 +15800,6 @@ components:
- inputs
- model
- git
- prepare
- execution
- checkpoint
- clone
@ -15829,8 +15833,6 @@ components:
$ref: "#/components/schemas/RunModelSettings"
git:
$ref: "#/components/schemas/RunGitSettings"
prepare:
$ref: "#/components/schemas/RunPrepareSettings"
execution:
$ref: "#/components/schemas/RunExecutionSettings"
checkpoint:
@ -15993,63 +15995,6 @@ components:
email:
type: ["string", "null"]
RunPrepareSettings:
type: object
required: [steps, timeout_ms]
properties:
steps:
type: array
items:
$ref: "#/components/schemas/PreparedStep"
timeout_ms:
type: integer
format: int64
PreparedStep:
description: |
A single resolved prepare step. The runnable part preserves the
script-vs-argv distinction via the `type` discriminator: a `script`
is a raw shell snippet kept verbatim, while a `command` is an argv
whose elements are shell-quoted and joined at the run boundary (after
`{{ secrets.* }}` resolution) so an interpolated value cannot inject shell
syntax. Optional per-step `env` is shared by both shapes.
type: object
required: [type]
oneOf:
- $ref: "#/components/schemas/PreparedScriptStep"
- $ref: "#/components/schemas/PreparedCommandStep"
discriminator:
propertyName: type
mapping:
script: "#/components/schemas/PreparedScriptStep"
command: "#/components/schemas/PreparedCommandStep"
PreparedScriptStep:
type: object
required: [type, script]
properties:
type:
type: string
enum: [script]
script:
type: string
env:
$ref: "#/components/schemas/StringMap"
PreparedCommandStep:
type: object
required: [type, command]
properties:
type:
type: string
enum: [command]
command:
type: array
items:
type: string
env:
$ref: "#/components/schemas/StringMap"
RunExecutionSettings:
type: object
required: [mode, approval]

View file

@ -72,7 +72,7 @@ Fabro performs this selection once when creating a run and persists the chosen p
| `qwen3.8-max` | venice | `qwen`, `qwen-max`, `qwen3.8`, `qwen-3.8`, `qwen38`, `qwen-3.8-max`, `qwen38-max` | 1M | $2.50 / $7.50 | n/a |
| `qwen3.8-27b` | venice | `qwen-27b`, `qwen-3.8-27b`, `qwen38-27b` | 262K | $0.45 / $3.20 | n/a |
Each provider requires its own API key. Server-backed workflows read provider credentials from the server vault (for example `ANTHROPIC_API_KEY`, `OPENAI_API_KEY`, `GEMINI_API_KEY`, `DEEPSEEK_API_KEY`, or `POOLSIDE_API_KEY` set with `fabro secret set` or `fabro provider login`). Standalone SDK/CLI flows can opt into env-backed credential sources explicitly. See the [Quick Start](/getting-started/quick-start) for setup.
Providers can use API keys, OAuth, AWS credentials, or no authentication, depending on their configuration. See [Credential sources](#credential-sources) below and the [Quick Start](/getting-started/quick-start#configure-api-keys) for setup.
Claude Fable 5 is available as an explicit model but is not the default Anthropic model. If Fable refuses a request, Fabro reports the refusal as a content-filter LLM error and applies the configured `run.model.fallbacks` chain when one is present.
@ -130,12 +130,12 @@ capabilities = { text = true, tools = true }
`api_model` is the model name sent to that provider's API. It defaults to the exact model id, so omit it when the two strings match. Fabro does not infer vendor prefixes or rewrite the value.
<Note>
A `provider/model` selector such as `openai/gpt-5.6-sol` pins the provider and names the model by id, alias, or wire id. A bare selector with no provider pin picks the highest-priority ready offering; a separate `provider = "openrouter"` pin selects the OpenRouter offering. Providers with `allow_passthrough = true` also accept `provider/model` selectors for models the catalog does not list.
A `provider/model` selector such as `openai/gpt-5.6-sol` pins the provider and names the model by id, alias, or wire id. A bare selector with no provider pin picks the highest-priority ready offering; a separate `provider = "openrouter"` pin selects the OpenRouter offering. Providers with `allow_passthrough = true` also accept `provider/model` selectors for models the catalog does not list. A bare selector the catalog does not know is an error rather than a passthrough, and a bare provider name such as `gemini` is an error too: pin the provider and omit the model to use its default.
</Note>
Model roles are separate: the provider's `default_model` controls normal model selection for workflow execution, while `small_default = true` on a model row marks the provider's small utility model for metadata tasks such as generated run titles. If a provider has no small default, Fabro falls back to that provider's default model.
Provider auth has two parts. The lithos `auth` scheme says how a credential is sent: `{ type = "bearer" }`, `{ type = "header", name = "x-api-key" }`, `{ type = "headers" }` for providers that take several secret headers, `{ type = "none" }`, or `{ type = "aws" }`. lithos also says which secret names a provider reads: `OPENAI_API_KEY` for `openai`, `GEMINI_API_KEY` then `GOOGLE_API_KEY` for `gemini`, `MODAL_TOKEN_ID` and `MODAL_TOKEN_SECRET` for `modal`, and `<PROVIDER>_API_KEY` for a provider you define. Fabro looks each name up in the process environment first and the server vault second. Custom headers for any provider go in `default_headers` as literal text or `{{ secrets.NAME }}` tokens; put credentials in secrets and reference them with `{{ secrets.NAME }}` instead of a bare literal.
Provider auth has two parts. The lithos `auth` scheme says how a credential is sent: `{ type = "bearer" }`, `{ type = "header", name = "x-api-key" }`, `{ type = "headers" }` for providers that take several secret headers, `{ type = "none" }`, or `{ type = "aws" }`. lithos also says which secret names a provider reads: `OPENAI_API_KEY` for `openai`, `GEMINI_API_KEY` then `GOOGLE_API_KEY` for `gemini`, `MODAL_TOKEN_ID` and `MODAL_TOKEN_SECRET` for `modal`, and `<PROVIDER>_API_KEY` for a provider you define. The source of those values depends on how the model call is made; see [Credential sources](#credential-sources). Custom headers for any provider go in `default_headers` as literal text or `{{ secrets.NAME }}` tokens. Secret tokens resolve against the vault, not process environment variables; put credentials in secrets and reference them instead of using a bare literal.
Workflow runs add `x-session-id: <run-id>` to native HTTP model requests, including model-based hooks, run titles, Ask Fabro and pull request descriptions. The ID stays the same across retries, provider fallback and resume; separate runs get separate IDs. Explicit provider `default_headers` take precedence regardless of header-name casing. Calls outside a run do not receive an automatic session header.
@ -151,6 +151,34 @@ Costs come from the lithos `pricing` table on each model row. Each token bucket
Provider fields in configuration, APIs, and model routing are provider ID strings. Built-in names like `anthropic`, `openai`, and `gemini` still work, but custom IDs like `proxy` work anywhere a provider ID is accepted.
</Note>
## Credential sources
`fabro exec` is direct when neither `--server` nor `FABRO_SERVER` selects a server. With either target selector, it sends model calls through that server.
For `fabro run`, server model calls, and `fabro exec --server ...`, store provider API keys and OAuth credentials in the **target server's vault**. This also applies when the server runs locally on your laptop. Exporting a provider API key in either the CLI's shell or the server's shell does not configure or override that server's model credentials.
```bash
fabro secret set OPENAI_API_KEY sk-...
# For a remote server, target the same server used for model calls:
fabro secret --server https://fabro.example.com set OPENAI_API_KEY sk-...
```
Use `fabro provider login` for supported API-key and OAuth login flows. The provider's secret names are the vault entry names, not instructions to export environment variables. For providers that require an API-key secret, an environment-only key leaves the server provider unconfigured; with conflicting environment and vault values, the server uses the vault value. Workers do not inherit conventional provider API keys from the server's environment.
| Model-call context | Credential source |
| --- | --- |
| Workflows and server model calls, including `fabro exec --server ...` | Target server's vault for provider API keys and OAuth records. |
| Direct `fabro exec` (no server target) | For conventional API-key names, the invoking process environment first, then the local Fabro secret store. Stored OAuth records are resolved separately. |
| Direct SDK use | The caller chooses the credential source. `VaultCredentialSource::environment_only()` explicitly reads conventional keys from the process environment; `vault_only(...)` disables that lookup. |
Installation can accept a key explicitly from stdin or a named environment variable and save it to the vault. That is a provisioning step, not a server credential fallback. Startup does not import provider keys from process environment variables, `.env`, or `server.env`.
Endpoint settings are separate from credentials. For example, `OPENAI_BASE_URL` can change the normal server's OpenAI endpoint without making `OPENAI_API_KEY` an environment-backed server credential.
[Bedrock SigV4](/integrations/bedrock#configure-credentials) is a separate authentication mechanism: it uses the AWS default credential chain, whose identity inputs are deliberately available to workers. Bedrock bearer API keys still follow the vault rule above. Providers configured with `auth = { type = "none" }` do not need an API key. External ACP agents manage their own model authentication; this section describes Fabro's model client.
## Provider integrations
### Venice
Fabro ships a built-in [Venice](/integrations/venice) provider with a curated catalog of Venice-hosted Kimi, Grok, GLM, DeepSeek, and Qwen models. Store its API key with `fabro provider login --provider venice`. Pin `provider = "venice"` when a shared model slug must use Venice instead of a higher-priority direct provider.

View file

@ -27,6 +27,8 @@ digraph SemanticPort {
]
start [shape=Mdiamond, label="Start"]
fetch_upstream [shape=parallelogram, script="git clone https://github.com/openai/openai-agents-python upstream || (cd upstream && git pull)", timeout="5m", on_failure="exit", max_retries=0]
install_ledger [shape=parallelogram, script="pip install -r ledger/requirements.txt", timeout="5m", on_failure="exit", max_retries=0]
exit [shape=Msquare, label="Exit"]
// Phase 1: Find the next unprocessed commit
@ -119,7 +121,7 @@ digraph SemanticPort {
]
// Wiring
start -> fetch
start -> fetch_upstream -> install_ledger -> fetch
fetch -> analyze [label="Process", condition="preferred_label=process"]
fetch -> exit [label="Done"]
@ -230,12 +232,6 @@ provider = "anthropic"
"claude-sonnet-4-5" = ["openai"]
"gemini-3.1-pro-preview" = ["anthropic"]
[[run.prepare.steps]]
script = "git clone https://github.com/openai/openai-agents-python upstream || (cd upstream && git pull)"
[[run.prepare.steps]]
script = "pip install -r ledger/requirements.txt"
[run.inputs]
upstream_repo = "openai/openai-agents-python"
downstream_lang = "go"

View file

@ -29,6 +29,7 @@ digraph BuildSolitaire {
]
start [shape=Mdiamond, label="Start"]
install_dependencies [shape=parallelogram, script="python3 -m venv .venv && . .venv/bin/activate && pip install pytest curses", timeout="5m", on_failure="exit", max_retries=0]
exit [shape=Msquare, label="Exit"]
// Phase 0: Expand the goal into a detailed spec
@ -148,7 +149,7 @@ digraph BuildSolitaire {
check_review [shape=diamond, label="Review OK?"]
// Wiring: linear phases with verify-gate loops
start -> expand_spec -> impl_setup -> verify_setup -> check_setup
start -> install_dependencies -> expand_spec -> impl_setup -> verify_setup -> check_setup
check_setup -> impl_data [condition="outcome=succeeded"]
check_setup -> impl_setup [condition="outcome=failed", label="Retry"]
@ -270,9 +271,6 @@ provider = "anthropic"
[run.model.fallbacks]
"claude-sonnet-4-5" = ["openai", "gemini"]
[[run.prepare.steps]]
script = "python3 -m venv .venv && . .venv/bin/activate && pip install pytest curses"
[run.environment]
id = "python-dev"

View file

@ -4,7 +4,7 @@ description: "Configure workflow runs with TOML files"
---
A workflow config is a TOML file that bundles a workflow graph with its
execution behavior — the goal, model, prepare steps, inputs, hooks, and other
execution behavior — the goal, model, inputs, hooks, and other
workflow-owned settings. Instead of passing a dozen CLI flags, check
`workflow.toml` into version control and launch it with a single command:
@ -75,12 +75,6 @@ reasoning_effort = "high"
[run.model.fallbacks]
"claude-sonnet-4-5" = ["openai", "gemini"]
[[run.prepare.steps]]
script = "git clone https://github.com/fabro-sh/fabro repo"
[[run.prepare.steps]]
script = "cd repo && npm install"
[run.integrations.github.permissions]
contents = "write"
pull_requests = "write"
@ -211,28 +205,100 @@ Use the reserved `"..."` marker in one model's list to splice in that model's in
"gpt-5.6-sol" = ["anthropic", "..."]
```
### `[run.prepare]`
### Setup command migration
Ordered list of steps to run before the workflow starts. Use this to clone repositories, install dependencies, or prepare the environment.
`run.prepare` is no longer supported in any authored settings file, including
server, workflow, direct-run, project, and user settings. Move setup into named
command nodes after `start`. Setup is visible in the graph and timeline and uses
ordinary stage hooks and failure handling. Review broad hook matchers that
assume dependencies are already installed: they now also match setup commands.
```toml title="run.toml"
[[run.prepare.steps]]
script = "pip install -r requirements.txt"
Before, a workflow whose graph was `start -> work -> exit` could use:
[[run.prepare.steps]]
command = ["npm", "install"]
env = { NPM_TOKEN = "{{ secrets.NPM_TOKEN }}" }
```toml title="workflow.toml (removed syntax)"
[run.prepare]
timeout = "5m"
steps = [
{ command = ["bundle", "install"] },
{ script = "bundle exec rake db:prepare", env = { TOKEN = "{{ secrets.SETUP_TOKEN }}" } },
]
```
| Field | Description |
|---|---|
| `script` | Bash source, evaluated by the sandbox's non-login Bash (`bash -c`). Supports `{{ vars.* }}` and `{{ secrets.* }}` interpolation. |
| `command` | Argv-style command, mutually exclusive with `script`. Each resolved element is shell-quoted as one argument. |
| `env` | Additional environment variables for this step. Values support the same interpolation as `script` and `command`. |
Remove that section. Use the existing workflow-wide environment for secrets:
Each step must exit with status 0. If any step fails, the run aborts before the workflow starts. Prepare steps replace across layers — the higher-precedence layer wins wholesale.
```toml title="workflow.toml"
_version = 1
[workflow]
graph = "workflow.fabro"
Fabro substitutes `{{ vars.* }}` when the server creates the run, then resolves `{{ secrets.* }}` from token entries in the server vault immediately before the worker executes the steps. Secret expressions remain in the persisted run definition; resolved secret values are not persisted. A missing or non-token secret aborts startup with the affected step and token named in the error.
[run.environment.env]
SETUP_TOKEN = "{{ secrets.SETUP_TOKEN }}"
```
Then put setup in the workflow:
```dot title="workflow.fabro"
digraph Workflow {
start [shape=Mdiamond]
install [shape=parallelogram, script="bundle install", timeout="5m", on_failure="exit", max_retries=0]
database [shape=parallelogram, script="TOKEN=\"$SETUP_TOKEN\" bundle exec rake db:prepare", timeout="5m", on_failure="exit", max_retries=0]
work [shape=parallelogram, script="bundle exec rake test"]
exit [shape=Msquare]
start -> install -> database -> work -> exit
}
```
The timeout applies **per command**. Set `timeout="5m"` to retain preparation's
old default; ordinary commands otherwise default to ten minutes. Keep
`on_failure="exit"` so a failed setup command prevents downstream work. The
example assumes no graph retry defaults or exhaustion override. Where those
exist, preserve the inherited retry count and `on_retries_exhausted` policy rather
than blindly copying `max_retries=0`. Ordinary shell exit failures do not request
retries; a nonzero graph retry default alone does not retry them.
For branching workflows, move every outgoing edge from `start` to the final
setup node, preserving its attributes. Keep the edges between setup commands
unconditional. Keep setup in the scope that owns the checkout and selected
environment; repository checkout still happens before these commands.
**Secret scope changes:** a formerly per-step secret moved into
`[run.environment.env]` (or the selected environment's `env` table) is available
to every command and process in that workflow environment, including `work` in
this example. Resolution remains late and output remains redacted. This is
broader exposure than the old per-step overlay. Do not put resolved secrets into
scripts or print them. When two old steps used `TOKEN` for different secrets,
use distinct workflow keys such as `FIRST_TOKEN` and `SECOND_TOKEN`, then map
with `TOKEN="$FIRST_TOKEN" ./scripts/setup-one.sh` and
`TOKEN="$SECOND_TOKEN" ./scripts/setup-two.sh`. Both source keys remain available
workflow-wide. Literal values can stay command-local: `MODE=first ./setup.sh`.
Convert argv values to safely quoted shell arguments. For example, the argv
argument `a space, 'quote'; $HOME` can be expressed without expansion as:
```dot
quoted [shape=parallelogram, script="printf '%s\n' 'a space, '\"'\"'quote'\"'\"'; $HOME'", timeout="5m", on_failure="exit", max_retries=0]
```
Keep supported input/variable template tokens in their existing script renderer;
do not turn them into shell command substitutions. Quote shell environment
expansions as in the secret example.
Server-wide setup must move into each applicable workflow, or into a shared
script explicitly called by those workflows. Fabro does not choose a repository
or rewrite user files automatically. Environment images and Dockerfiles remain
available for installing tools and dependencies.
Historical runs retain their saved admitted commands, encoded per-command env
overlays, graph digests, and events. Reading, resuming, retrying, or forking a saved
run uses its admission; it does not recompile retired syntax. Submitting an old
workflow version as a new run does reject it. Executing commands named
`run_prepare_…`, including old generated commands, now invokes ordinary stage
hooks; the old prefix-based hook exemption is removed. Existing encoded secret
overlays keep their original per-command scope.
The resolved settings API no longer emits `run.prepare` or its preparation
schemas. Upgrade server, workers, and clients together; clients that required
that response field must update. Saved records are not rewritten by this change.
### `[run.clone]`
@ -244,7 +310,7 @@ enabled = true
depth = 100
```
Set `enabled = false` to start runs with an empty workspace. Use [prepare steps](#runprepare) to clone or create any files the workflow needs.
Set `enabled = false` to start runs with an empty workspace. Use [explicit setup commands](#setup-command-migration) to clone or create any files the workflow needs.
| Field | Description |
|---|---|
@ -558,7 +624,7 @@ id = "sentry"
| `startup_timeout` | Max duration for server startup + MCP handshake (e.g. `"10s"`, `"1m"`). | `"10s"` |
| `tool_timeout` | Max duration for a single tool call. | `"60s"` |
Inline transport commands, URLs, env values, and headers support `{{ vars.* }}` and `{{ secrets.* }}` interpolation. As with prepare steps, server variables resolve at run creation and token secrets resolve at launch; missing values fail closed. See [MCP runtime interpolation](/agents/mcp#runtime-interpolation) for the standalone `fabro exec` difference.
Inline transport commands, URLs, env values, and headers support `{{ vars.* }}` and `{{ secrets.* }}` interpolation. Server variables resolve at run creation and token secrets resolve at launch; missing values fail closed. See [MCP runtime interpolation](/agents/mcp#runtime-interpolation) for the standalone `fabro exec` difference.
The `sandbox` transport runs the MCP server inside the workflow's sandbox. This is useful for tools that need access to the sandbox environment, such as browser automation with Playwright. See [MCP](/agents/mcp#sandbox) for details.
@ -602,11 +668,11 @@ sandbox = false
| `id` | Optional merge identity. Hooks with the same `id` replace each other across layers. |
| `name` | Optional display name for the hook. |
| `event` | Lifecycle event: `run_start`, `run_complete`, `stage_start`, `stage_complete`, etc. |
| `script` | Shell-evaluated command (equivalent to the old `type = "command"` shorthand). |
| `command` | Argv-style command (alternative to `script`). |
| `script` | Shell command string. |
| `command` | Command and arguments as an array of strings, such as `["cargo", "fmt"]`; an alternative to `script`. |
| `matcher` | Regex matched against node ID or handler type. Limits which stages trigger this hook. |
| `blocking` | Whether the hook must complete before execution continues. Defaults vary by event. |
| `timeout` | Human-readable hook timeout (e.g. `"30s"`, `"1m"`). Default: `"60s"`. |
| `timeout` | Human-readable hook timeout (e.g. `"30s"`, `"1m"`). Default: `"30s"` for prompt hooks, `"60s"` for other types. |
| `sandbox` | Run inside the sandbox (`true`, default) or on the host (`false`). |
Hook merge semantics: hooks with matching `id` values replace in place. Hooks without an `id` from a higher-precedence layer append after the fully merged inherited hook list.

View file

@ -65,22 +65,16 @@ This creates `.fabro/project.toml` and a starter workflow under `.fabro/workflow
## Configure API keys
For local CLI runs, export at least one LLM provider key in your shell:
```bash
ANTHROPIC_API_KEY=sk-ant-...
OPENAI_API_KEY=sk-...
GEMINI_API_KEY=AI...
```
<Note>
You only need one provider key to get started. Add more to enable multi-model workflows.
For server-backed runs, store provider keys in the server vault instead:
`fabro run` uses the Fabro server even when you run it from a local terminal. If installation has not already configured a provider, store a key in that server's vault:
```bash
fabro secret set ANTHROPIC_API_KEY sk-ant-...
```
You can also use `fabro provider login --provider anthropic` for guided setup. You only need one provider to get started; add more to enable multi-model workflows.
<Note>
Exporting a provider key in your shell does not configure server-backed workflows. For a remote server, use `fabro secret --server https://fabro.example.com set ANTHROPIC_API_KEY sk-ant-...` and `fabro run --server https://fabro.example.com hello` so both commands use the same server. Direct `fabro exec` and SDK callers have different [credential sources](/core-concepts/models#credential-sources).
</Note>
## Run your first workflow

View file

@ -45,11 +45,11 @@ fabro secret set AWS_BEARER_TOKEN_BEDROCK bedrock-api-key-...
fabro secret set BEDROCK_API_KEY bedrock-api-key-...
```
Runs read the bearer token from the vault only. Workers start from a cleared environment and the bearer token is not on the inherited allowlist, so exporting it in the server's shell has no effect on runs. `fabro exec` and direct `fabro-llm` SDK usage do read it from process env.
Runs read the bearer token from the vault only. Workers start from a cleared environment and the bearer token is not on the inherited allowlist, so exporting it in the server's shell has no effect on runs. Direct `fabro exec` (no server target) checks process environment before the local secret store for these names; SDK callers can explicitly choose an environment-backed source. `fabro exec --server ...` uses the target server's vault.
**AWS SigV4** (IAM-scoped): with no API key configured, Fabro signs each request using the AWS default credential chain — environment keys, shared profile, EC2/ECS instance roles, IRSA/web identity, SSO. Expiring session credentials refresh automatically.
The order is fixed by lithos-llm: `AWS_BEARER_TOKEN_BEDROCK`, then `BEDROCK_API_KEY`, then the AWS default chain. Each name is read from the process environment first and the server vault (`fabro secret set`) second — so on a server, prefer `secret set`. To select a non-default AWS profile for SigV4, set `AWS_PROFILE` (it, and the rest of the AWS credential-chain variables, are passed through to workflow workers).
The order is fixed by lithos-llm: `AWS_BEARER_TOKEN_BEDROCK`, then `BEDROCK_API_KEY`, then the AWS default chain. For server model calls and workflows, those two bearer-token names are read from the vault only. The AWS default chain is separate from bearer-token lookup; it can use environment credentials and other AWS identity sources. To select a non-default AWS profile for SigV4, set `AWS_PROFILE` (it, and the rest of the AWS credential-chain variables, are passed through to workflow workers).
<Warning>
**Bearer-vs-SigV4 precedence.** Because the bearer key is tried before SigV4, setting `AWS_BEARER_TOKEN_BEDROCK` makes the `bedrock` (Converse) provider authenticate with that key too — not just the `bedrock-openai` mantle provider below. If your key is valid only for mantle (it lacks `bedrock:InvokeModel*` on the runtime), every Converse model then fails with *"Authentication failed."* Use a key that covers both surfaces, or keep Converse on SigV4 by leaving both Bedrock secret names unset and enabling only `bedrock`.
@ -124,7 +124,7 @@ Bedrock-specific request fields pass through verbatim via `provider_options.bedr
## Troubleshooting
**"no AWS credentials provider found"** — Neither an API key nor any AWS chain source resolved. Set `AWS_BEARER_TOKEN_BEDROCK` (or `BEDROCK_API_KEY`), or configure standard AWS credentials.
**"no AWS credentials provider found"** — Neither an API key nor any AWS chain source resolved. Store `AWS_BEARER_TOKEN_BEDROCK` (or `BEDROCK_API_KEY`) with `fabro secret set` on the target server, or configure the AWS default credential chain. For direct execution, follow the [credential-source rules](/core-concepts/models#credential-sources).
**`AccessDeniedException` / 403** — The IAM principal lacks `bedrock:InvokeModel*` for the model, or model access has not been granted in the Bedrock console for your Region (Claude needs the per-Region use-case approval; third-party models need `aws-marketplace:Subscribe`).

View file

@ -316,7 +316,7 @@ The upper bound on what Fabro will mint is whatever permissions the GitHub App i
### Commit attribution
Every commit a run creates is authored and committed by the run's GitHub credential identity. In App mode that is the App's bot account, `<slug>[bot] <id+slug[bot]@users.noreply.github.com>`, so GitHub attributes checkpoint commits and workflow-created commits to the App. In token mode it is the token's user with their GitHub noreply address. Fabro resolves the identity once per run and passes it to every prepare step, command stage, agent tool, and ACP agent as `GIT_AUTHOR_*` / `GIT_COMMITTER_*` variables, so a workflow that clones or initializes another repository commits as the same identity without configuring Git itself. `[run.git.author]` overrides either field; see [server configuration](/administration/server-configuration#rungitauthor-section).
Every commit a run creates is authored and committed by the run's GitHub credential identity. In App mode that is the App's bot account, `<slug>[bot] <id+slug[bot]@users.noreply.github.com>`, so GitHub attributes checkpoint commits and workflow-created commits to the App. In token mode it is the token's user with their GitHub noreply address. Fabro resolves the identity once per run and passes it to every command stage, agent tool, and ACP agent as `GIT_AUTHOR_*` / `GIT_COMMITTER_*` variables, so a workflow that clones or initializes another repository commits as the same identity without configuring Git itself. `[run.git.author]` overrides either field; see [server configuration](/administration/server-configuration#rungitauthor-section).
### Checkpoint pushing

View file

@ -44,12 +44,14 @@ For a server-owned secret:
fabro secret set LITELLM_API_KEY sk-proxy-key
```
`fabro exec` and direct `fabro-llm` SDK usage can use an env-backed credential source explicitly:
For direct `fabro exec` (no server target), export the key in the invoking shell. SDK callers can explicitly choose an environment-backed credential source:
```bash
export LITELLM_API_KEY=sk-proxy-key
```
`fabro exec --server ...` uses the target Fabro server's vault, even when the CLI has a key in its own environment. See [Credential sources](/core-concepts/models#credential-sources).
If your local LiteLLM proxy does not enforce authentication, use a placeholder value such as `anything`; the OpenAI-compatible client still needs a credential value.
## Use LiteLLM models
@ -97,7 +99,7 @@ The provider's `default_model` names its default. You may also mark one small ut
## Troubleshooting
**"No API key configured"** — For runs, set `vault:LITELLM_API_KEY` with `fabro secret set LITELLM_API_KEY ...`. Exporting it in the server's shell has no effect on runs: workers start from a cleared environment and provider keys are not inherited. For `fabro exec` or direct SDK usage, export `LITELLM_API_KEY` in the invoking shell and use an env-backed credential source.
**"No API key configured"** — For runs, store `LITELLM_API_KEY` in the target server vault with `fabro secret set LITELLM_API_KEY ...`. Exporting it in the server's shell has no effect on runs: workers start from a cleared environment and provider keys are not inherited. For direct `fabro exec` (no server target), export `LITELLM_API_KEY` in the invoking shell or store it in the local secret store. SDK callers must choose the appropriate credential source.
**Connection refused** — Confirm the LiteLLM proxy is running and that `base_url` is reachable from the Fabro process. For Docker deployments, `localhost` means the Fabro container unless you point it at a host or service name.

View file

@ -113,9 +113,9 @@ digraph Example {
## Direct SDK environment credentials
The built-in Modal provider authenticates with two headers, `Modal-Key` and `Modal-Secret`, read from the secrets `MODAL_TOKEN_ID` and `MODAL_TOKEN_SECRET`. Direct SDK use reads the same two names from the process environment.
The built-in Modal provider authenticates with two headers, `Modal-Key` and `Modal-Secret`, read from the secrets `MODAL_TOKEN_ID` and `MODAL_TOKEN_SECRET`. For environment-backed SDK use, export both names and select `VaultCredentialSource::environment_only()` explicitly. Alternatively, use `VaultCredentialSource::vault_only(...)` with a vault holding both tokens.
For direct SDK use, enable Modal and set its endpoint URL in the `[llm]` overlay, then build the client with `fabro_llm::build_client` over a `VaultCredentialSource` whose vault holds both secrets. The catalog you pass to the client must be built from the same settings file with `fabro_llm::build_catalog`.
Enable Modal and set its endpoint URL in the `[llm]` overlay, then build the client with `fabro_llm::build_client` over your chosen credential source. The catalog you pass to the client must be built from the same settings file with `fabro_llm::build_catalog`.
```toml title="settings.toml"
[llm.providers.modal]

View file

@ -17,7 +17,7 @@ These flags apply to all subcommands:
| `-h, --help` | Print help |
| `-V, --version` | Print version |
Connection-target flags like `--storage-dir` and `--server` are command-specific, not global. Fabro no longer auto-loads `~/.fabro/.env`; persist server-owned credentials with `fabro provider login` / `fabro secret set`, or provide environment variables in the invoking shell.
Connection-target flags like `--storage-dir` and `--server` are command-specific, not global. Fabro no longer auto-loads `~/.fabro/.env`. Configure server model credentials with `fabro provider login` or `fabro secret set` on the target server; shell provider keys do not configure `fabro run` or `fabro exec --server ...`. Direct `fabro exec` (no server target) checks the invoking process environment before the local secret store for conventional API-key names. See [Credential sources](/core-concepts/models#credential-sources), including the separate Bedrock SigV4 mechanism.
## Configuration
@ -46,7 +46,7 @@ url = "https://fabro.example.com/api/v1"
`[cli.exec]` config applies to `fabro exec`. `[run.model]` sets the default workflow model/provider for commands like `fabro run` and `fabro preflight`. `[cli.target]` stores connection info for commands that can target a remote Fabro server.
`fabro model` uses `[cli.target]` by default when no explicit `--storage-dir` is passed. `fabro exec` remains a local session unless you pass `--server`, even if `[cli.target]` is configured.
`fabro model` uses `[cli.target]` by default when no explicit `--storage-dir` is passed. `fabro exec` remains a direct session unless you select a server with `--server` or `FABRO_SERVER`, even if `[cli.target]` is configured.
Explicit `http(s)://...` targets are always treated as remote servers. They do not inherit identity from a local daemon, a local storage dir, or `~/.fabro/dev-token`. For remote URLs, use `fabro auth login --server ...` or a stored CLI auth session.

View file

@ -331,7 +331,9 @@ The `fabro_llm::catalog` module reads Fabro policy from the catalog: `enabled_pr
`ClientOptions::standard()` turns on the lithos retry middleware (three attempts with short exponential backoff) and local attachment inlining. Add middleware with `with_middleware`, replace a provider's adapter with `with_adapter`, or set `http` to inject a configured HTTP client. `fabro_llm::build_offline_client(catalog, options)` builds a client whose only providers are custom adapters, which is how `fabro exec --server` routes every call through a Fabro server.
Credential sources live in `fabro-auth`: `VaultCredentialSource` reads a Fabro vault with an optional process-environment fallback (`VaultCredentialSource::environment_only()` for SDK callers with no vault), and `SqlVaultCredentialSource` reads the server's secret store. lithos-llm decides which secret names a provider reads (`OPENAI_API_KEY`, `MODAL_TOKEN_ID` and `MODAL_TOKEN_SECRET`, or `<PROVIDER>_API_KEY` for an operator-defined provider); Fabro's vault is keyed by those same names.
Credential sources live in `fabro-auth`. For conventional API-key names, `VaultCredentialSource::new(...)` and `SqlVaultCredentialSource::new(...)` check process environment first, then their in-memory vault or SQL secret store. Use `VaultCredentialSource::environment_only()` when the SDK should read only process environment keys, or either source's `vault_only(...)` constructor to disable environment lookup. Stored OAuth records and `{{ secrets.NAME }}` header tokens resolve through the vault separately.
The Fabro server uses `SqlVaultCredentialSource::vault_only(...)`; an SDK's choice of source does not change server behavior. lithos-llm decides which secret names a provider reads (`OPENAI_API_KEY`, `MODAL_TOKEN_ID` and `MODAL_TOKEN_SECRET`, or `<PROVIDER>_API_KEY` for an operator-defined provider); Fabro's vault is keyed by those same names. Bedrock SigV4 retains its separate AWS default credential chain. See [Credential sources](/core-concepts/models#credential-sources).
#### Requests and responses

View file

@ -34,7 +34,7 @@ Files that omit `_version` are treated as version `1`. The legacy top-level `ver
| Scope | Examples |
|---|---|
| CLI-only | `[cli.target]`, `[cli.auth]`, `[cli.exec]`, `[cli.output]`, `[cli.updates]`, `[cli.logging]` |
| Server-side run policy | `[run.model]`, `[run.environment]`, `[environments.<slug>]`, `[run.checkpoint]`, `[run.inputs]`, `[run.prepare]`, `[run.pull_request]`, `[run.integrations.github]`, `[run.hooks]`, `[run.agent.mcps]` |
| Server-side run policy | `[run.model]`, `[run.environment]`, `[environments.<slug>]`, `[run.checkpoint]`, `[run.inputs]`, `[run.pull_request]`, `[run.integrations.github]`, `[run.hooks]`, `[run.agent.mcps]` |
| Shared LLM catalog | `[llm]`, a lithos-llm catalog overlay: `[llm.providers.<id>]`, `[llm.providers.<id>.models.<id>]`, and the agent harness under `metadata.agent` |
| Server-only | `[server.listen]`, `[server.api]`, `[server.web]`, `[server.auth]`, `[server.storage]`, `[server.artifacts]`, `[server.scheduler]`, `[server.logging]`, `[server.integrations]` |

View file

@ -218,7 +218,7 @@ async fn attach_petri_run_with_client(
printer: Printer,
) -> Result<ExitCode> {
let is_tty = std::io::stderr().is_terminal();
let mut progress_ui = run_progress::ProgressUI::new(is_tty, opts.verbose);
let mut progress_ui = run_progress::ProgressUI::new(is_tty, opts.verbose, &state.spec);
let ctrl_c_signal = ctrl_c();
tokio::pin!(ctrl_c_signal);

View file

@ -33,6 +33,7 @@ pub(crate) mod run_progress;
pub(crate) mod runner;
mod selection;
pub(crate) mod ssh;
mod stage_presentation;
pub(crate) mod start;
pub(crate) mod steer;
#[cfg(test)]

View file

@ -25,12 +25,13 @@ use std::time::Duration;
use anyhow::{Context as _, Result};
use chrono::{DateTime, TimeZone as _, Utc};
use fabro_redact::redact_jsonl_line;
use fabro_types::{RunId, RunStreamItem, RunStreamItemKind};
use fabro_types::{RunId, RunStreamItem, RunStreamItemKind, StageOutcome};
use fabro_util::terminal::Styles;
use serde_json::Value;
use tokio::time;
use tracing::debug;
use super::stage_presentation::StagePresentation;
use crate::args::EventsArgs;
use crate::server_client;
use crate::shared::{format_duration_ms, format_usd_micros};
@ -338,22 +339,29 @@ pub(crate) fn format_pretty(
let status = outcome.get("status").and_then(Value::as_str).unwrap_or("?");
let duration = format_duration_ms(elapsed.unwrap_or(0));
if !executed || status == "skipped" {
let presentation = StagePresentation::new(StageOutcome::Skipped, styles);
return Some(format!(
"{ts} {} {} {}",
styles.dim.apply_to("\u{2298}"),
presentation.glyph,
styles.bold.apply_to(label),
styles.dim.apply_to("skipped"),
presentation.label.unwrap_or_default(),
));
}
match status {
"success" | "partial_success" => {
let outcome_kind = if status == "partial_success" {
StageOutcome::PartiallySucceeded
} else {
StageOutcome::Succeeded
};
let presentation = StagePresentation::new(outcome_kind, styles);
let mut line = format!(
"{ts} {} {}",
styles.green.apply_to("\u{2713}"),
presentation.glyph,
styles.bold.apply_to(label),
);
if status == "partial_success" {
let _ = write!(line, " {}", styles.yellow.apply_to("partial"));
if let Some(label) = presentation.label {
let _ = write!(line, " {label}");
}
let _ = write!(line, " {duration}");
if let Some(usage) = usage_summary(outcome, styles) {
@ -362,13 +370,19 @@ pub(crate) fn format_pretty(
Some(line)
}
other => {
let presentation = StagePresentation::new(
StageOutcome::Failed {
retry_requested: false,
},
styles,
);
let error = outcome
.pointer("/failure/message")
.and_then(Value::as_str)
.unwrap_or(other);
Some(format!(
"{ts} {} {} {}",
styles.red.apply_to("\u{2717}"),
presentation.glyph,
styles.bold.apply_to(label),
styles.red.apply_to(error),
))
@ -1325,4 +1339,39 @@ mod tests {
assert_eq!(value["kind"], "platform");
assert_eq!(value["item"]["record"]["kind"], "run.notice");
}
#[test]
fn redacted_raw_lines_keep_the_typed_run_id() {
let run_id = "01M5228EHCT0P73Z4BYGDRWJNS";
let secret = "xK9mZ2vL8nQ5rT1wY4bC7dF0gH3jE6p";
let mut event = petri(1, json!({"record": {"body": {"value": secret}}}));
event.run_id = run_id.parse().expect("a valid run ID");
let line = raw_line(&event).expect("a redacted line");
let decoded: RunStreamItem = serde_json::from_str(&line).expect("a valid stream item");
assert_eq!(decoded.run_id, event.run_id);
assert_eq!(decoded.stream_seq, event.stream_seq);
assert_eq!(decoded.item["record"]["body"]["value"], "REDACTED");
}
#[test]
fn raw_lines_preserve_run_ids_that_cross_the_entropy_threshold() {
// This ID has enough distinct characters to read as a secret to the
// entropy scanner; the Web UI link and run branch must survive.
let run_id = "01M5228EHCT0P73Z4BYGDRWJNS";
for (kind, field, text) in [
(
"run.created",
"web_url",
format!("http://localhost:3000/runs/{run_id}"),
),
("run.branch", "run_branch", format!("fabro/run/{run_id}")),
] {
let mut event = platform(1, &json!({"kind": kind, field: text, "content": run_id}));
event.run_id = run_id.parse().expect("a valid run ID");
let line = raw_line(&event).expect("a redacted line");
let decoded: RunStreamItem = serde_json::from_str(&line).expect("a valid stream item");
assert_eq!(decoded, event);
}
}
}

View file

@ -27,7 +27,6 @@ pub(super) enum ProgressEvent {
},
WorkflowStarted {
worktree_dir: Option<String>,
base_branch: Option<String>,
base_sha: Option<String>,
},
StageStarted {

View file

@ -3,7 +3,7 @@
reason = "sync CLI run-progress renderer: writes to std::io::stderr directly"
)]
use fabro_types::{RunNoticeCode, RunStreamItem};
use fabro_types::{RunNoticeCode, RunSpec, RunStreamItem, RunTarget};
mod event;
mod info_display;
@ -11,6 +11,8 @@ mod petri;
mod renderer;
mod stage_display;
mod styles;
#[cfg(test)]
mod tests;
use event::ProgressEvent;
use info_display::InfoDisplay;
@ -24,10 +26,11 @@ pub(crate) struct ProgressUI {
info: InfoDisplay,
saw_metadata_snapshot_failure: bool,
petri: PetriProgressState,
source_branch: Option<String>,
}
impl ProgressUI {
pub(crate) fn new(is_tty: bool, verbose: bool) -> Self {
pub(crate) fn new(is_tty: bool, verbose: bool, spec: &RunSpec) -> Self {
let renderer = if is_tty {
ProgressRenderer::new_tty()
} else {
@ -36,7 +39,7 @@ impl ProgressUI {
console::colors_enabled_stderr(),
)
};
Self::with_renderer(renderer, verbose)
Self::with_renderer(renderer, verbose).with_source_spec(spec)
}
fn with_renderer(renderer: ProgressRenderer, verbose: bool) -> Self {
@ -46,9 +49,25 @@ impl ProgressUI {
info: InfoDisplay::new(verbose),
saw_metadata_snapshot_failure: false,
petri: PetriProgressState::default(),
source_branch: None,
}
}
fn with_source_spec(mut self, spec: &RunSpec) -> Self {
// A fork starts at a checkpoint, and a tag need not name the input
// branch's history. Keep those bases commit-only instead of pairing
// the inherited working branch with an unrelated revision.
if spec.fork_source_ref.is_none()
&& !matches!(&spec.target, Some(RunTarget::Git(target)) if target.tag.is_some())
{
self.source_branch = spec
.base_branch()
.filter(|branch| !branch.trim().is_empty())
.map(str::to_owned);
}
self
}
pub(crate) fn hide_bars(&self) {
self.renderer.hide();
}
@ -80,14 +99,13 @@ impl ProgressUI {
}
ProgressEvent::WorkflowStarted {
worktree_dir,
base_branch,
base_sha,
} => {
if let Some(worktree_dir) = worktree_dir {
InfoDisplay::show_worktree(renderer, std::path::Path::new(&worktree_dir));
}
if let Some(base_sha) = base_sha {
InfoDisplay::show_base_info(renderer, base_branch.as_deref(), &base_sha);
InfoDisplay::show_base_info(renderer, self.source_branch.as_deref(), &base_sha);
}
}
ProgressEvent::StageStarted {

View file

@ -221,10 +221,6 @@ fn platform_progress_event(record: &Value) -> Option<ProgressEvent> {
}),
"run.branch" => Some(ProgressEvent::WorkflowStarted {
worktree_dir: None,
base_branch: record
.get("run_branch")
.and_then(Value::as_str)
.map(str::to_string),
base_sha: record
.get("base_sha")
.and_then(Value::as_str)

View file

@ -9,6 +9,7 @@ use indicatif::ProgressBar;
use super::event::ProgressUsage;
use super::renderer::ProgressRenderer;
use super::styles;
use crate::commands::run::stage_presentation::StagePresentation;
use crate::shared::{format_duration_ms, format_tokens_human};
const MAX_TOOL_CALLS: usize = 5;
@ -138,14 +139,11 @@ impl StageDisplay {
status: &str,
usage: Option<&ProgressUsage>,
) {
let succeeded = status.parse::<StageOutcome>().map_or_else(
|_| matches!(status, "succeeded" | "partially_succeeded"),
|status| {
matches!(
status,
StageOutcome::Succeeded | StageOutcome::PartiallySucceeded
)
},
let presentation = StagePresentation::new(
status.parse().unwrap_or(StageOutcome::Failed {
retry_requested: false,
}),
renderer.styles(),
);
let cost_str = usage
.and_then(ProgressUsage::display_cost)
@ -171,13 +169,14 @@ impl StageDisplay {
} else {
String::new()
};
let prefix = format!("{cost_str}{}{stats_str}", format_duration_ms(duration_ms));
let glyph = if succeeded {
styles::green_check(renderer.styles())
} else {
styles::red_cross(renderer.styles())
};
self.finish_stage(renderer, node_id, name, &glyph, &prefix);
let label = presentation
.label
.map_or_else(String::new, |label| format!("{label} "));
let prefix = format!(
"{label}{cost_str}{}{stats_str}",
format_duration_ms(duration_ms)
);
self.finish_stage(renderer, node_id, name, &presentation.glyph, &prefix);
}
pub(super) fn on_stage_failed(
@ -187,13 +186,13 @@ impl StageDisplay {
name: &str,
error: &str,
) {
self.finish_stage(
renderer,
node_id,
name,
&styles::red_cross(renderer.styles()),
"",
let presentation = StagePresentation::new(
StageOutcome::Failed {
retry_requested: false,
},
renderer.styles(),
);
self.finish_stage(renderer, node_id, name, &presentation.glyph, "");
let summary = styles::last_line_truncated(error, 120);
Self::insert_global_info_line(
renderer,

View file

@ -0,0 +1,286 @@
#![expect(
clippy::disallowed_types,
reason = "capture the synchronous progress renderer's output in memory"
)]
use std::io::{self, Write};
use std::sync::{Arc, Mutex};
use fabro_types::{
DirtyStatus, ForkSourceRef, GitContext, GitRunTarget, RunStreamItemKind, fixtures, test_support,
};
use fabro_util::terminal::Styles;
use serde_json::{Value, json};
use super::*;
use crate::commands::run::petri_stream::{self, PrettyState};
#[derive(Clone, Default)]
struct Output(Arc<Mutex<Vec<u8>>>);
impl Write for Output {
fn write(&mut self, buf: &[u8]) -> io::Result<usize> {
self.0.lock().unwrap().extend_from_slice(buf);
Ok(buf.len())
}
fn flush(&mut self) -> io::Result<()> {
Ok(())
}
}
impl Output {
fn text(&self) -> String {
String::from_utf8(self.0.lock().unwrap().clone()).unwrap()
}
}
fn visit(seq: u64, event: &str, derived: Value) -> RunStreamItem {
let mut derived = derived;
derived["event"] = json!(event);
RunStreamItem {
run_id: fixtures::RUN_1,
stream_seq: seq,
kind: RunStreamItemKind::Petri,
id: seq.to_string(),
recorded_at: 1_789_706_579_000 + seq * 1000,
item: json!({
"origin": "derived",
"context": {"invocation": 0, "execution": 0},
"subject": {
"node": {"id": 2, "name": "work", "kind": "attractor/x",
"meta": {"label": "work", "kind": "agent"}},
"firing": 2, "visit": 1, "attempt": 1,
"generation": 0, "branch": {"role": "none"}
},
"derived": derived
}),
}
}
fn completed(status: &str, executed: bool) -> RunStreamItem {
visit(
4,
"visit.completed",
json!({
"outcome": {"status": status},
"executed": executed,
"attempts": 1
}),
)
}
#[test]
fn progress_and_events_present_stage_outcomes_consistently() {
let mut cases = Vec::new();
for (status, executed) in [
("skipped", true),
("success", false),
("success", true),
("partial_success", true),
("failure", true),
("cancelled", true),
("unrecognized", true),
] {
let started = visit(1, "visit.started", json!({}));
let completed = completed(status, executed);
let raw_before = petri_stream::raw_line(&completed).unwrap();
let mut progress = Vec::new();
for verbose in [false, true] {
let output = Output::default();
let renderer = ProgressRenderer::new_plain(Box::new(output.clone()), false);
let mut ui = ProgressUI::with_renderer(renderer, verbose);
ui.handle_stream_item(&started);
ui.handle_stream_item(&completed);
assert!(ui.stage.active_stages.is_empty());
ui.finish();
progress.push(output.text());
}
let mut state = PrettyState::default();
let styles = Styles::new(false);
petri_stream::format_pretty(&started, &styles, &mut state);
let pretty = petri_stream::format_pretty(&completed, &styles, &mut state).unwrap();
// Presentation must not change the machine-readable event or turn a
// stage outcome into the run's terminal result.
assert_eq!(petri_stream::raw_line(&completed).unwrap(), raw_before);
assert_eq!(petri_stream::exit_code_of(&completed), None);
cases.push(json!({
"status": status, "executed": executed,
"progress": progress[0], "verbose_progress": progress[1], "events": pretty
}));
}
insta::assert_snapshot!(serde_json::to_string_pretty(&cases).unwrap(), @r#"
[
{
"status": "skipped",
"executed": true,
"progress": " ⊘ work skipped 3s\n",
"verbose_progress": " ⊘ work skipped 3s\n",
"events": "04:43:03 ⊘ work skipped"
},
{
"status": "success",
"executed": false,
"progress": " ⊘ work skipped 3s\n",
"verbose_progress": " ⊘ work skipped 3s\n",
"events": "04:43:03 ⊘ work skipped"
},
{
"status": "success",
"executed": true,
"progress": " ✓ work 3s\n",
"verbose_progress": " ✓ work 3s\n",
"events": "04:43:03 ✓ work 3s"
},
{
"status": "partial_success",
"executed": true,
"progress": " ✓ work partial 3s\n",
"verbose_progress": " ✓ work partial 3s\n",
"events": "04:43:03 ✓ work partial 3s"
},
{
"status": "failure",
"executed": true,
"progress": " ✗ work\n Error: failure\n",
"verbose_progress": " ✗ work\n Error: failure\n",
"events": "04:43:03 ✗ work failure"
},
{
"status": "cancelled",
"executed": true,
"progress": " ✗ work 3s\n",
"verbose_progress": " ✗ work 3s\n",
"events": "04:43:03 ✗ work cancelled"
},
{
"status": "unrecognized",
"executed": true,
"progress": " ✗ work\n Error: unrecognized\n",
"verbose_progress": " ✗ work\n Error: unrecognized\n",
"events": "04:43:03 ✗ work unrecognized"
}
]
"#);
}
#[test]
fn skipped_stage_finishes_terminal_progress_with_a_neutral_label() {
for (status, executed) in [("skipped", true), ("success", false)] {
for verbose in [false, true] {
let renderer = ProgressRenderer::new_tty();
renderer.hide();
let mut ui = ProgressUI::with_renderer(renderer, verbose);
ui.handle_stream_item(&visit(1, "visit.started", json!({})));
let bar = ui.stage.active_stages["work"].spinner.clone();
ui.handle_stream_item(&completed(status, executed));
assert_eq!(console::strip_ansi_codes(&bar.message()), "⊘ work");
assert_eq!(console::strip_ansi_codes(&bar.prefix()), "skipped 3s");
assert!(bar.is_finished());
assert!(ui.stage.active_stages.is_empty());
ui.finish();
}
}
}
#[test]
fn skipped_stage_is_dim_in_both_renderers_and_visible_in_plain_replay_without_a_start() {
let completed = completed("skipped", true);
let output = Output::default();
let renderer = ProgressRenderer::new_plain(Box::new(output.clone()), true);
let mut ui = ProgressUI::with_renderer(renderer, false);
ui.handle_stream_item(&completed);
ui.finish();
let progress = output.text();
let pretty =
petri_stream::format_pretty(&completed, &Styles::new(true), &mut PrettyState::default())
.unwrap();
for text in [&progress, &pretty] {
assert!(text.contains("\u{1b}[2m⊘\u{1b}[0m"), "{text:?}");
assert!(text.contains("\u{1b}[2mskipped\u{1b}[0m"), "{text:?}");
assert!(!text.contains('✗'), "{text:?}");
}
assert_eq!(
console::strip_ansi_codes(&progress),
" ⊘ work skipped 0ms\n"
);
}
fn branch_record(base_sha: Option<&str>) -> RunStreamItem {
RunStreamItem {
run_id: fixtures::RUN_1,
stream_seq: 2,
kind: RunStreamItemKind::Platform,
id: "2".to_string(),
recorded_at: 1_789_706_579_000,
item: json!({"record": {
"kind": "run.branch",
"run_branch": format!("fabro/run/{}", fixtures::RUN_1),
"base_sha": base_sha
}}),
}
}
fn source_spec() -> RunSpec {
RunSpec {
git: Some(GitContext {
origin_url: String::new(),
branch: "main".to_string(),
// The branch-point record, not this creation-time observation,
// supplies the SHA displayed next to the source branch.
sha: Some("1111111111111111111111111111111111111111".to_string()),
dirty: DirtyStatus::Clean,
}),
..test_support::test_run_spec()
}
}
fn render_base(spec: &RunSpec, base_sha: Option<&str>, verbose: bool) -> String {
let output = Output::default();
let renderer = ProgressRenderer::new_plain(Box::new(output.clone()), false);
let mut ui = ProgressUI::with_renderer(renderer, verbose).with_source_spec(spec);
let record = branch_record(base_sha);
let raw = petri_stream::raw_line(&record).unwrap();
ui.handle_stream_item(&record);
ui.finish();
assert_eq!(petri_stream::raw_line(&record).unwrap(), raw);
output.text()
}
#[test]
fn base_header_uses_saved_source_branch_and_recorded_base_commit() {
let spec = source_spec();
for verbose in [false, true] {
insta::allow_duplicates! {
insta::assert_snapshot!(render_base(&spec, Some("abcdef0123456789"), verbose), @" Base: main (abcdef012345)");
}
assert_eq!(render_base(&spec, None, verbose), "");
}
}
#[test]
fn base_header_uses_only_the_commit_when_source_branch_is_unknown_or_ambiguous() {
let mut absent = source_spec();
absent.git = None;
let mut empty = source_spec();
empty.git.as_mut().unwrap().branch = " ".to_string();
let mut fork = source_spec();
fork.fork_source_ref = Some(ForkSourceRef {
source_run_id: fixtures::RUN_2,
checkpoint_sha: "abcdef0123456789".to_string(),
});
let mut tag = source_spec();
tag.target = Some(RunTarget::Git(GitRunTarget {
repo: "acme/widgets".to_string(),
branch: "main".to_string(),
tag: Some("v1".to_string()),
sha: None,
}));
for spec in [absent, empty, fork, tag] {
for verbose in [false, true] {
insta::allow_duplicates! {
insta::assert_snapshot!(render_base(&spec, Some("abcdef0123456789"), verbose), @" Base: abcdef012345");
}
}
}
}

View file

@ -0,0 +1,28 @@
//! Terminal styling for an already interpreted stage outcome. Decoding engine
//! events and deciding run success remain the callers' responsibilities.
use fabro_types::StageOutcome;
use fabro_util::terminal::Styles;
pub(super) struct StagePresentation {
pub(super) glyph: String,
pub(super) label: Option<String>,
}
impl StagePresentation {
pub(super) fn new(outcome: StageOutcome, styles: &Styles) -> Self {
let (glyph, label) = match outcome {
StageOutcome::Succeeded => (styles.green.apply_to("\u{2713}").to_string(), None),
StageOutcome::PartiallySucceeded => (
styles.green.apply_to("\u{2713}").to_string(),
Some(styles.yellow.apply_to("partial").to_string()),
),
StageOutcome::Skipped => (
styles.dim.apply_to("\u{2298}").to_string(),
Some(styles.dim.apply_to("skipped").to_string()),
),
StageOutcome::Failed { .. } => (styles.red.apply_to("\u{2717}").to_string(), None),
};
Self { glyph, label }
}
}

View file

@ -2905,3 +2905,51 @@ fn attach_json_errors_without_prompting_for_human_input() {
});
wait_for_status(&run.run_dir, &["succeeded"]);
}
#[test]
fn attach_base_header_preserves_the_saved_source_branch() {
let context = test_context!();
let workflow = super::support::write_workflow(&context.temp_dir, "base-header", "BaseHeader");
let workspace = context.temp_dir.join("source");
context.write_temp("source/README.md", "source commit\n");
let source_sha = super::support::init_remote_fixture(&workspace, "main");
let run = context
.run_cmd()
.args([
"--auto-approve",
"--detach",
"--environment",
"local",
"--target-from",
])
.arg(&workspace)
.arg(&workflow)
.timeout(SHARED_DAEMON_TIMEOUT)
.assert()
.success();
let run_id = created_run_id(run.get_output());
context
.command()
.args(["wait", &run_id])
.timeout(SHARED_DAEMON_TIMEOUT)
.assert()
.success();
// Reattach must use the stored source, even if the caller changes branches.
super::support::run_git(&workspace, &["checkout", "-b", "later"]);
let output = context
.command()
.args(["attach", &run_id])
.current_dir(&workspace)
.timeout(SHARED_DAEMON_TIMEOUT)
.assert()
.success();
let stderr = String::from_utf8_lossy(&output.get_output().stderr);
let base_lines: Vec<_> = stderr
.lines()
.map(str::trim)
.filter(|line| line.starts_with("Base:"))
.collect();
// Do not apply the shared Base filter: it would hide a wrong branch name.
assert_eq!(base_lines, [format!("Base: main ({})", &source_sha[..12])]);
}

View file

@ -242,8 +242,8 @@ root = "{}"
[run.execution]
approval = "auto"
[[run.prepare.steps]]
script = "cli-setup"
[run.checkpoint]
exclude_globs = ["cli-cache/**"]
"#,
storage_dir.display()
),
@ -257,8 +257,8 @@ script = "cli-setup"
r#"
_version = 1
[[run.prepare.steps]]
script = "project-setup"
[run.checkpoint]
exclude_globs = ["project-cache/**"]
"#,
)
.expect("external workflow project config should write");
@ -289,8 +289,8 @@ goal = "Ship it"
[run.model]
name = "claude-sonnet-4-6"
[[run.prepare.steps]]
script = "workflow-setup"
[run.checkpoint]
exclude_globs = ["workflow-cache/**"]
"#,
)
.expect("external workflow config should write");
@ -366,12 +366,9 @@ fn create_explicit_workflow_warns_without_transmitting_machine_or_project_run_se
run_spec["settings"]["run"]["model"]["name"].as_str(),
Some("gpt-5.4-pro")
);
// run.prepare.steps replaces the whole ordered list across layers. A
// `script` step serializes with the `type` discriminator that preserves the
// script-vs-argv distinction in the run spec wire shape.
assert_eq!(
run_spec["settings"]["run"]["prepare"]["steps"],
serde_json::json!([{ "type": "script", "script": "workflow-setup" }])
run_spec["settings"]["run"]["checkpoint"]["exclude_globs"],
serde_json::json!(["workflow-cache/**"])
);
}

View file

@ -82,6 +82,8 @@ fn dump_accepts_server_target_from_separate_home() {
#[test]
fn dump_exports_large_command_output_backed_by_blob_refs() {
let context = test_context!();
// Exceed the 100 KiB blob threshold without emitting thousands of log
// events: this tests export hydration, not event-stream throughput.
let workflow = context.temp_dir.join("large-output.fabro");
fs::write(
&workflow,
@ -91,7 +93,7 @@ fn dump_exports_large_command_output_backed_by_blob_refs() {
start [shape=Mdiamond, label="Start"]
exit [shape=Msquare, label="Exit"]
big [shape=parallelogram, label="Big", script="yes xxxxxxxxxxxxxxxx | head -n 8000"]
big [shape=parallelogram, label="Big", script="printf '%0136000d' 0"]
start -> big -> exit
}
@ -144,6 +146,10 @@ fn dump_exports_large_command_output_backed_by_blob_refs() {
!run_json.contains("blob://sha256/"),
"run export should hydrate blob refs\n{run_json}"
);
assert_eq!(
fs::read_to_string(output_dir.join("stages/002-big@1/output.log")).unwrap(),
"0".repeat(136_000)
);
}
#[test]
@ -160,7 +166,7 @@ fn dump_exports_blob_refs_and_artifacts_together() {
start [shape=Mdiamond, label="Start"]
exit [shape=Msquare, label="Exit"]
big [shape=parallelogram, label="Big", script="mkdir -p assets/shared && printf exported > assets/shared/report.txt && yes xxxxxxxxxxxxxxxx | head -n 8000"]
big [shape=parallelogram, label="Big", script="mkdir -p assets/shared && printf exported > assets/shared/report.txt && printf '%0136000d' 0"]
start -> big -> exit
}
@ -230,6 +236,10 @@ include = ["assets/**"]
!run_json.contains("blob://sha256/"),
"run export should hydrate blob refs\n{run_json}"
);
assert_eq!(
fs::read_to_string(output_dir.join("stages/002-big@1/output.log")).unwrap(),
"0".repeat(136_000)
);
assert_eq!(
fs::read_to_string(
output_dir.join("artifacts/002-big@1/retry-0001/assets/shared/report.txt")

View file

@ -137,10 +137,6 @@ fn inspect_resolves_selector_via_server_endpoint() {
"git": {
"author": null
},
"prepare": {
"steps": [],
"timeout_ms": 300000
},
"execution": {
"mode": "normal",
"approval": "prompt"

View file

@ -439,6 +439,7 @@ fn foreground_start_writes_tracing_to_stdout_by_default() {
let storage_log_path = storage_dir.join("logs").join("server.log");
std::fs::create_dir_all(storage_log_path.parent().unwrap()).unwrap();
std::fs::write(&storage_log_path, "stale pre-start log entry\n").unwrap();
let stdout_capture = tempfile::NamedTempFile::new_in("/tmp").unwrap();
let mut cmd = std::process::Command::new(env!("CARGO_BIN_EXE_fabro"));
apply_test_isolation(&mut cmd, home_dir.path());
@ -450,7 +451,7 @@ fn foreground_start_writes_tracing_to_stdout_by_default() {
.arg("--config")
.arg(&config_path)
.stdin(Stdio::null())
.stdout(Stdio::piped())
.stdout(stdout_capture.reopen().unwrap())
.stderr(Stdio::piped());
let mut child = cmd.spawn().expect("server start should spawn");
@ -478,6 +479,10 @@ fn foreground_start_writes_tracing_to_stdout_by_default() {
"expected foreground start to create server.json"
);
// The daemon record is written before startup tracing. Wait for that trace
// before stopping the server so shutdown cannot race the log under test.
wait_for_log_line(stdout_capture.path(), "API server started");
let stop_output = {
let mut stop = std::process::Command::new(env!("CARGO_BIN_EXE_fabro"));
apply_test_isolation(&mut stop, home_dir.path());
@ -497,7 +502,8 @@ fn foreground_start_writes_tracing_to_stdout_by_default() {
let output = child
.wait_with_output()
.expect("server start output should be readable");
let stdout = String::from_utf8_lossy(&output.stdout);
let stdout = std::fs::read_to_string(stdout_capture.path())
.expect("foreground stdout should be readable");
assert!(
stdout.contains("API server started"),
"expected foreground stdout to contain server tracing, got:\n{stdout}\nforeground stderr:\n{}",

View file

@ -509,3 +509,87 @@ async fn docker_failed_cleanup_preserves_success_across_server_restarts() {
.await;
server.shutdown();
}
/// Remove the disposable run's container even if its regression fails.
struct WorkerCrashContainer(String);
impl Drop for WorkerCrashContainer {
fn drop(&mut self) {
cleanup(&self.0);
}
}
/// A worker-only crash leaves the server responsible for terminal cleanup.
/// The keep-running control must not be stopped by that supervisor backstop.
#[tokio::test(flavor = "multi_thread")]
async fn worker_crash_honors_the_docker_stop_policy_and_retains_files() {
if !fabro_test::docker_available() {
return;
}
for stop_on_terminal in [true, false] {
let context = test_context!();
let server = docker_server().await;
let workspace = write_petri_workflow(
&context,
"digraph Cleanup { start [shape=Mdiamond]; exit [shape=Msquare]; \
work [shape=parallelogram, script=\"printf retained > retained.txt\"]; \
gate [shape=hexagon, label=\"Continue?\"]; \
start -> work -> gate; gate -> exit [label=\"[A] Continue\"]; }",
);
// Workflow configuration is public input, above the catalog default.
let config = workspace.join("workflow.toml");
let text = std::fs::read_to_string(&config).unwrap();
std::fs::write(
&config,
format!("{text}\n[run.environment.lifecycle]\nstop_on_terminal = {stop_on_terminal}\n"),
)
.unwrap();
let run_id = run_detached_in(&context, &server, &workspace, ENVIRONMENT, &[]);
let _container_cleanup = WorkerCrashContainer(run_id.clone());
let gate_deadline = std::time::Instant::now() + std::time::Duration::from_mins(1);
while super::petri::questions(&server, &run_id).await.is_empty() {
let run = run_json(&server, &format!("runs/{run_id}")).await;
assert!(
run["lifecycle"]["status"]["kind"] != "failed"
&& run["lifecycle"]["status"]["kind"] != "succeeded"
&& std::time::Instant::now() < gate_deadline,
"the fixture did not reach its human gate: {run}"
);
tokio::time::sleep(std::time::Duration::from_millis(50)).await;
}
let container = container_of(&run_id).expect("the gated run has a container");
let worker = wait_for_worker(&run_id);
fabro_proc::sigkill(worker);
wait_for_status(&server, &run_id, &["failed"]).await;
// Usage is counted after the supervisor finishes handling the exit,
// so a keep-running assertion cannot race a pending cleanup task.
let deadline = std::time::Instant::now() + std::time::Duration::from_secs(35);
while run_json(&server, "usage").await["totals"]["runs"].as_u64() != Some(1) {
assert!(
std::time::Instant::now() < deadline,
"worker exit did not settle"
);
tokio::time::sleep(std::time::Duration::from_millis(50)).await;
}
let output = Command::new("docker")
.args(["inspect", "--format", "{{.State.Running}}", &container])
.output()
.expect("inspect runs");
assert!(output.status.success(), "the container is retained");
let running = String::from_utf8_lossy(&output.stdout).trim() == "true";
// docker cp also reads a stopped container without activating it.
let retained = context.temp_dir.join("retained.txt");
let copied = Command::new("docker")
.args(["cp", &format!("{container}:/workspace/retained.txt")])
.arg(&retained)
.status()
.expect("docker cp runs");
let contents = std::fs::read_to_string(&retained);
cleanup(&run_id);
server.shutdown();
assert_eq!(running, !stop_on_terminal);
assert!(copied.success());
assert_eq!(contents.unwrap(), "retained");
}
}

View file

@ -1054,8 +1054,7 @@ mod runs {
use fabro_api::types::*;
use fabro_types::settings::run::{
EnvironmentImageSettings, EnvironmentLifecycleSettings, EnvironmentResourcesSettings,
EnvironmentSettings, PreparedStep, PreparedStepRun, RunEnvironmentSettings, RunGoal,
RunModelSettings, RunNamespace, RunPrepareSettings,
EnvironmentSettings, RunEnvironmentSettings, RunGoal, RunModelSettings, RunNamespace,
};
use fabro_types::settings::{InterpString, ProjectNamespace, WorkflowNamespace};
use fabro_types::{
@ -1868,23 +1867,6 @@ mod runs {
name: Some("claude-opus-4-6".to_string()),
..RunModelSettings::default()
},
prepare: RunPrepareSettings {
steps: vec![
PreparedStep {
run: PreparedStepRun::Script {
script: "bun install".to_string(),
},
env: HashMap::new(),
},
PreparedStep {
run: PreparedStepRun::Script {
script: "bun run typecheck".to_string(),
},
env: HashMap::new(),
},
],
timeout_ms: 120_000,
},
environment: RunEnvironmentSettings::from_environment(
"api-server".to_string(),
environment,

View file

@ -2155,29 +2155,14 @@ fn install_catalog_with_base_url(
let Some(base_url) = state.upstreams.provider_base_urls.get(provider.id()) else {
return Ok(Catalog::clone(&INSTALL_CATALOG));
};
let overlay = fabro_config::LlmLayer(
toml::from_str(&format!(
"[providers.{}]\nbase_url = {}\n",
toml_key(provider.id().as_str()),
toml::Value::String(base_url.clone())
))
.context("install provider base URL overlay should parse")?,
);
let overlay = fabro_config::LlmLayer::from_providers([(
provider.id().to_string(),
toml::Table::from_iter([("base_url".into(), toml::Value::String(base_url.clone()))]),
)]);
fabro_llm::build_catalog(&overlay, &|_| None)
.context("install catalog with provider base URL override should build")
}
fn toml_key(key: &str) -> String {
if key
.chars()
.all(|c| c.is_ascii_alphanumeric() || c == '-' || c == '_')
{
key.to_string()
} else {
format!("{key:?}")
}
}
#[cfg(test)]
fn provider_base_url_override(state: &InstallAppState, provider: &CatalogProvider) -> String {
state

View file

@ -251,7 +251,7 @@ pub(crate) enum InvalidSourceError {
#[derive(Debug, thiserror::Error)]
pub(crate) enum InvalidSettingsError {
#[error("Failed to parse run config TOML")]
#[error("Failed to parse run config TOML at {path}")]
Parse {
path: ManifestPath,
#[source]
@ -732,7 +732,10 @@ key = "value"
panic!("unknown settings key should fail");
};
assert_eq!(error.to_string(), "Failed to parse run config TOML");
assert_eq!(
error.to_string(),
"Failed to parse run config TOML at flows/workflow.toml"
);
let source = error
.source()
.expect("parse error should retain the TOML source");

View file

@ -140,7 +140,15 @@ pub(crate) fn prepare_manifest_with_environment_defaults(
.filter(|config| config.type_ == types::ManifestConfigType::User)
{
if let Some(source) = config.source.as_deref() {
workflow_settings_builder = workflow_settings_builder.user_toml(source)?;
workflow_settings_builder =
workflow_settings_builder
.user_toml(source)
.with_context(|| {
format!(
"Failed to parse user settings at {}",
config.path.as_deref().unwrap_or("manifest user settings")
)
})?;
}
}
let mut settings = workflow_settings_builder
@ -525,7 +533,6 @@ async fn build_preflight_report(
}
fn base_preflight_checks(prepared: &PreparedManifest, shape: &WorkflowShape) -> Vec<CheckResult> {
let setup_command_count = prepared.settings.run.prepare.steps.len();
let repo_summary = prepared.git.as_ref().map_or_else(
|| "unknown".to_string(),
|git| {
@ -542,26 +549,23 @@ fn base_preflight_checks(prepared: &PreparedManifest, shape: &WorkflowShape) ->
name: "Repository".into(),
status: CheckStatus::Pass,
summary: repo_summary,
details: vec![
CheckDetail::new(format!("Setup commands: {setup_command_count}")),
CheckDetail {
text: format!(
"Git: {}",
prepared
.git
.as_ref()
.map_or("unknown", |git| match git.dirty {
fabro_types::DirtyStatus::Clean => "clean",
fabro_types::DirtyStatus::Dirty => "dirty",
fabro_types::DirtyStatus::Unknown => "unknown",
})
),
warn: prepared
details: vec![CheckDetail {
text: format!(
"Git: {}",
prepared
.git
.as_ref()
.is_some_and(|git| git.dirty != fabro_types::DirtyStatus::Clean),
},
],
.map_or("unknown", |git| match git.dirty {
fabro_types::DirtyStatus::Clean => "clean",
fabro_types::DirtyStatus::Dirty => "dirty",
fabro_types::DirtyStatus::Unknown => "unknown",
})
),
warn: prepared
.git
.as_ref()
.is_some_and(|git| git.dirty != fabro_types::DirtyStatus::Clean),
}],
remediation: None,
},
CheckResult {
@ -2313,6 +2317,37 @@ override = "server"
);
}
#[test]
fn prepare_manifest_rejects_removed_preparation_in_supplied_sources() {
for kind in [
types::ManifestConfigType::User,
types::ManifestConfigType::Project,
] {
let mut manifest = minimal_manifest();
manifest.configs.push(types::ManifestConfig {
path: Some("retired.toml".into()),
source: Some("[run.prepare]\nsteps = []".into()),
type_: kind,
});
let error = prepare_manifest(&RunLayer::default(), &manifest)
.err()
.expect("retired preparation must fail");
assert!(format!("{error:#}").contains("run.prepare"));
}
let mut manifest = minimal_manifest();
manifest.workflows.get_mut("workflow.fabro").unwrap().config =
Some(types::ManifestWorkflowConfig {
path: "workflow.toml".into(),
source: "[run.prepare]\nsteps = []".into(),
});
let error = prepare_manifest(&RunLayer::default(), &manifest)
.err()
.expect("retired preparation must fail");
let message = format!("{error:#}");
assert!(message.contains("run.prepare"));
assert!(message.contains("workflow.toml"));
}
#[test]
fn prepare_manifest_prefers_bundled_settings_without_duplication() {
let server_settings = manifest_run_defaults(Some(&server_settings_fixture(
@ -2322,8 +2357,8 @@ _version = 1
[server.storage]
root = "/srv/fabro"
[[run.prepare.steps]]
script = "cli-setup"
[run.checkpoint]
exclude_globs = ["cli-cache/**"]
[server.integrations.github]
app_id = "fixture-app-id"
@ -2337,8 +2372,8 @@ app_id = "fixture-app-id"
source: r#"
_version = 1
[[run.prepare.steps]]
script = "workflow-setup"
[run.checkpoint]
exclude_globs = ["workflow-cache/**"]
"#
.to_string(),
});
@ -2351,8 +2386,8 @@ _version = 1
[server.auth]
methods = ["dev-token"]
[[run.prepare.steps]]
script = "cli-setup"
[run.checkpoint]
exclude_globs = ["cli-cache/**"]
[server.integrations.github]
app_id = "fixture-app-id"
@ -2365,13 +2400,9 @@ app_id = "fixture-app-id"
let prepared = prepare_manifest(&server_settings, &manifest).unwrap();
let settings_json = serde_json::to_value(&prepared.settings).unwrap();
// run.prepare.steps replaces the whole list across layers, so the
// higher-precedence workflow layer wins over cli.
assert_eq!(prepared.settings.run.prepare.steps.len(), 1);
assert_eq!(
prepared.settings.run.prepare.steps[0].to_shell_command(),
"workflow-setup"
);
assert_eq!(prepared.settings.run.checkpoint.exclude_globs, [
"workflow-cache/**"
]);
assert!(settings_json.pointer("/server").is_none());
}

View file

@ -34,6 +34,7 @@ use anyhow::Context as _;
use fabro_config::Storage;
use fabro_petri::providers;
pub(crate) use fabro_petri::providers::DaytonaCredentials;
use fabro_types::settings::run::RunEnvironmentSettings;
use fabro_types::settings::server::{
SandboxPluginSettings, ServerSandboxProviderSettings, ServerSandboxProvidersSettings,
};
@ -270,6 +271,60 @@ async fn attach_run_sandbox_on(
.with_context(|| format!("Failed to reconnect {kind} sandbox '{sandbox_id}'"))
}
/// Stop the sandboxes an exited worker can no longer release. This is a
/// supervisor backstop, not a deletion: the workspace and Petri's lease
/// records remain available for inspection, recovery and later pruning.
/// Local process cleanup belongs to the Host provider's worker guardian.
pub(crate) async fn stop_run_sandboxes(
access: &ProviderAccess,
environment: &RunEnvironmentSettings,
run_id: RunId,
) -> anyhow::Result<()> {
if !environment.lifecycle.stop_on_terminal
|| environment.provider.bundled() == Some(BundledProvider::Local)
{
return Ok(());
}
let provider = connect_provider(&environment.provider, access).await?;
stop_run_sandboxes_on(provider, run_id).await
}
async fn stop_run_sandboxes_on(
provider: Arc<dyn SandboxProvider>,
run_id: RunId,
) -> anyhow::Result<()> {
// Listing also finds a container whose create completed just before the
// worker died without recording its id, and every nested scope. Both
// list and attach verify ownership, so unrelated resources stay alone.
let provider = OwnedProvider::new(provider, run_ownership(run_id));
let sandboxes = provider
.list(&SandboxFilter::default())
.await
.context("Failed to list the exited worker's sandboxes")?;
let results =
join_all(sandboxes.into_iter().map(|status| {
let provider = &provider;
async move {
let result = match provider.attach(&status.id, None).await {
Ok(sandbox) => sandbox.stop().await,
Err(error) => Err(error),
};
match result {
// A concurrent run deletion already cleaned it up.
Ok(()) | Err(DriverError::NotFound { .. }) => Ok(()),
Err(error) => Err(anyhow::Error::new(error)
.context("Failed to stop an exited worker's sandbox")),
}
}
}))
.await;
// Every owned sandbox gets its stop attempt even if one fails.
for result in results {
result?;
}
Ok(())
}
/// Attaches to a run's host sandbox: the managed directory the record
/// names, with the record the run's worker kept for it.
///
@ -861,6 +916,54 @@ mod tests {
assert!(ownership.owns(&labels));
}
#[tokio::test]
async fn worker_cleanup_stops_all_owned_sandboxes_without_deleting_their_data() {
let run_id = RunId::new();
let mine = petri_scripted_sandbox("root", &run_id.to_string());
let nested = petri_scripted_sandbox("nested", &run_id.to_string());
let theirs = petri_scripted_sandbox("foreign", &RunId::new().to_string());
let unlabelled = Arc::new(ScriptedSandbox::new());
mine.fs().write("retained", b"keep me").await.unwrap();
let provider = scripted_provider("docker", vec![
Arc::clone(&mine),
Arc::clone(&nested),
Arc::clone(&theirs),
Arc::clone(&unlabelled),
]);
stop_run_sandboxes_on(provider, run_id).await.unwrap();
for sandbox in [&mine, &nested] {
assert_eq!(sandbox.current_state(), SandboxState::Stopped);
assert_eq!(sandbox.delete_count(), 0);
assert_eq!(sandbox.start_count(), 0);
}
assert_eq!(mine.fs().read("retained").await.unwrap(), b"keep me");
for sandbox in [&theirs, &unlabelled] {
assert_eq!(sandbox.current_state(), SandboxState::Running);
assert_eq!(sandbox.stop_count(), 0);
assert_eq!(sandbox.delete_count(), 0);
}
}
#[tokio::test]
async fn worker_cleanup_skips_keep_running_and_host_environments() {
// This plugin cannot connect: skipping the policy must happen first.
let provider = kind("unreachable-cleanup");
let access = unreachable_plugin_access(provider.as_str());
let mut environment = RunEnvironmentSettings {
provider,
..RunEnvironmentSettings::default()
};
environment.lifecycle.stop_on_terminal = false;
stop_run_sandboxes(&access, &environment, RunId::new())
.await
.unwrap();
stop_run_sandboxes(&access, &RunEnvironmentSettings::default(), RunId::new())
.await
.unwrap();
}
#[tokio::test]
async fn a_scoped_provider_attaches_only_to_the_runs_sandbox() {
let run_id = RunId::new();

View file

@ -4418,6 +4418,32 @@ async fn execute_run_subprocess(state: Arc<AppState>, run_id: RunId) {
}
};
// Normal release is Petri's. An abnormal exit can leave its scopes
// running forever; the surviving supervisor must enforce the terminal
// stop policy after deciding that this execution will not be resumed.
if !worker_exit.succeeded() && final_state.status.is_terminal() {
let cleanup = async {
let access = state.provider_access().await?;
sandbox_access::stop_run_sandboxes(
&access,
&final_state.spec.settings.run.environment,
run_id,
)
.await
};
match timeout(Duration::from_secs(30), cleanup).await {
Ok(Ok(())) => {}
Ok(Err(error)) => tracing::warn!(
run_id = %run_id, error = ?error,
"Failed to stop sandboxes after the worker exited"
),
Err(error) => tracing::warn!(
run_id = %run_id, error = ?error,
"Timed out stopping sandboxes after the worker exited"
),
}
}
accumulate_concluded_run_usage(&state, &final_state);
let mut runs = state.runs.lock().expect("runs lock poisoned");

View file

@ -299,7 +299,8 @@ fn model_selection_response(error: &ModelSelectionError) -> Response {
match error {
ModelSelectionError::UnknownProvider { .. }
| ModelSelectionError::UnknownSelector { .. }
| ModelSelectionError::UnknownSelectorOnProvider { .. } => {
| ModelSelectionError::UnknownSelectorOnProvider { .. }
| ModelSelectionError::ProviderUsedAsModel { .. } => {
ApiError::not_found(error.to_string()).into_response()
}
ModelSelectionError::ProviderUnavailable { .. }

View file

@ -1523,10 +1523,8 @@ enabled = true
.unwrap(),
(openrouter, "future-model".to_string())
);
assert_eq!(
canonical_session_model(&catalog, &both, Some("future-model"), None).unwrap(),
(openai, "future-model".to_string())
);
// Without a pin there is no provider to pass through on.
assert!(canonical_session_model(&catalog, &both, Some("future-model"), None).is_err());
}
/// A colon in a model ID does not make it provider-qualified. Ollama
@ -1548,9 +1546,8 @@ enabled = true
.unwrap(),
(openrouter, "future-model:latest".to_string())
);
assert_eq!(
canonical_session_model(&catalog, &both, Some("future-model:latest"), None).unwrap(),
(openai, "future-model:latest".to_string())
assert!(
canonical_session_model(&catalog, &both, Some("future-model:latest"), None).is_err()
);
}

View file

@ -1717,6 +1717,85 @@ async fn resolve_llm_client_reads_openai_token_from_vault() {
assert!(llm_result.auth_issues.is_empty());
}
#[tokio::test]
async fn dotted_provider_starts_and_uses_its_vault_key_with_inferred_or_explicit_profile() {
for explicit_profile in [false, true] {
let upstream = MockServer::start_async().await;
let completion = upstream
.mock_async(|when, then| {
when.method(POST)
.path("/v1/chat/completions")
.header("authorization", "Bearer dotted-provider-test-key")
.json_body_includes(r#"{"model":"wire-model"}"#);
then.status(200)
.header("content-type", "application/json")
.json_body(json!({
"id": "chatcmpl-dotted",
"object": "chat.completion",
"created": 1_700_000_000,
"model": "wire-model",
"choices": [{
"index": 0,
"message": {"role": "assistant", "content": "OK"},
"finish_reason": "stop"
}],
"usage": {"prompt_tokens": 1, "completion_tokens": 1, "total_tokens": 2}
}));
})
.await;
let mut overlay = r#"
[providers."my.gw"]
display_name = "Gateway"
base_url = "http://unused.invalid"
auth = { type = "bearer" }
[providers."my.gw".models."model.v1"]
display_name = "Model"
api_model = "wire-model"
capabilities = { text = true }
"#
.to_string();
if explicit_profile {
overlay.push_str(
r#"
[providers."my.gw".metadata.agent]
profile = "openai"
"#,
);
}
let state = TestAppStateBuilder::new()
.runtime_settings(default_test_server_settings(), RunLayer::default())
.env_lookup(|_| None)
.llm_overlay_toml(&overlay)
.provider_base_url("my.gw", upstream.base_url())
.build();
state
.stores
.vault
.set(
"MY_GW_API_KEY",
"dotted-provider-test-key",
SecretType::Token,
None,
)
.await
.unwrap();
let llm = state.resolve_llm_client().await.unwrap();
let response = llm
.client
.complete(
LlmRequest::builder()
.model("my.gw/model.v1")
.user("Hello")
.build()
.unwrap(),
)
.await
.unwrap();
assert_eq!(response.text(), "OK");
completion.assert_async().await;
}
}
#[tokio::test]
async fn resolve_llm_client_ignores_env_lookup_provider_tokens() {
let state = test_app_state_with_env_lookup(

View file

@ -364,12 +364,10 @@ pub fn llm_overlay_with_provider_base_url(
provider: impl Into<String>,
base_url: impl Into<String>,
) -> LlmLayer {
let provider = provider.into();
llm_overlay_from_toml(&format!(
"[providers.{}]\nbase_url = {}\n",
toml::Value::String(provider),
toml::Value::String(base_url.into())
))
LlmLayer::from_providers([(
provider.into(),
toml::Table::from_iter([("base_url".into(), toml::Value::String(base_url.into()))]),
)])
}
/// The catalog a test app state builds from `overlay`.

View file

@ -956,14 +956,6 @@ async fn token_install_finish_persists_settings_env_and_vault() {
let settings = std::fs::read_to_string(&config_path).unwrap();
assert!(settings.contains("https://fabro.example.com"));
assert!(settings.contains("strategy = \"token\""));
assert!(
settings.contains("[run.environment]"),
"settings.toml should contain [run.environment]"
);
assert!(
!settings.contains("[environments"),
"settings.toml should not contain environment catalog entries"
);
assert_sandbox_provider_policy(&settings, true, true, false);
assert_no_legacy_environment_dir(&temp_dir);
let default_environment = seeded_default_environment(&temp_dir).await;
@ -2614,11 +2606,6 @@ async fn sandbox_switching_from_daytona_to_docker_drops_saved_key() {
)
.await;
let settings = std::fs::read_to_string(&config_path).unwrap();
assert!(
settings.contains("[run.environment]"),
"settings.toml should select the default environment"
);
assert_no_legacy_environment_dir(&temp_dir);
let default_environment = seeded_default_environment(&temp_dir).await;
assert_eq!(default_environment.settings.provider.to_string(), "docker");
@ -2730,14 +2717,6 @@ async fn daytona_install_finish_writes_settings_and_vault_secret() {
.await;
let settings = std::fs::read_to_string(&config_path).unwrap();
assert!(
settings.contains("[run.environment]"),
"settings.toml should contain [run.environment]"
);
assert!(
!settings.contains("[environments"),
"settings.toml should not contain environment catalog entries"
);
assert_sandbox_provider_policy(&settings, true, false, true);
assert_no_legacy_environment_dir(&temp_dir);
let default_environment = seeded_default_environment(&temp_dir).await;

View file

@ -222,11 +222,10 @@ async fn unknown_session_models_preserve_passthrough_on_the_selected_provider()
let app = fabro_server::test_support::build_test_router(test_app_state());
let (run_id, _run_id_workspace) = create_run(&app).await;
for model in ["not-a-real-model", "openai/not-a-real-model"] {
let created = create_session_with_model(&app, &run_id, "Ask Fabro", model).await;
assert_eq!(created["model"], "not-a-real-model");
assert_eq!(created["provider"], "openai");
}
let created =
create_session_with_model(&app, &run_id, "Ask Fabro", "openai/not-a-real-model").await;
assert_eq!(created["model"], "not-a-real-model");
assert_eq!(created["provider"], "openai");
}
#[tokio::test]
@ -234,7 +233,7 @@ async fn invalid_session_model_refs_are_rejected_at_creation() {
let app = fabro_server::test_support::build_test_router(test_app_state());
let (run_id, _run_id_workspace) = create_run(&app).await;
for model in ["openai", "openai/", "anthropic/gpt-5.4"] {
for model in ["openai", "openai/", "anthropic/gpt-5.4", "not-a-real-model"] {
let response = create_session_response(
&app,
&run_id,

View file

@ -167,6 +167,48 @@ async fn completion_non_streaming_returns_valid_json() {
assert!(body["usage"]["output"].is_number());
}
/// A provider name in the model field, or a selector the catalog does not
/// know, is refused before any provider is called. Neither may pass through
/// to whichever ready provider wins priority.
#[tokio::test]
async fn completion_with_a_bare_provider_or_unknown_selector_is_rejected_before_any_call() {
let mock_server = MockServer::start_async().await;
let anthropic = mock_server
.mock_async(|when, then| {
when.method("POST").path("/v1/messages");
then.status(500);
})
.await;
let app = test_app_with_mock_anthropic(&format!("{}/v1", mock_server.url("")));
for (model, expected_detail) in [
("gemini", "set provider = \"gemini\""),
("anthropic", "set provider = \"anthropic\""),
(
"not-a-real-model",
"unknown model selector 'not-a-real-model'",
),
] {
let response = app
.clone()
.oneshot(completion_request_with_model(false, model))
.await
.unwrap();
let body = response_json(
response,
StatusCode::BAD_REQUEST,
&format!("POST /api/v1/completions with model {model}"),
)
.await;
let detail = body["errors"][0]["detail"].as_str().unwrap_or_default();
assert!(
detail.contains(expected_detail),
"model {model}: unexpected detail {detail:?}"
);
}
assert_eq!(anthropic.calls_async().await, 0);
}
#[tokio::test]
async fn completion_streaming_returns_sse() {
let mock_server = MockServer::start_async().await;

View file

@ -498,10 +498,9 @@ pub fn write_sandbox_settings(
allow_local: bool,
) -> Result<()> {
let root = root_table_mut(doc)?;
let run = ensure_table(root, "run")?;
let environment = ensure_table(run, "environment")?;
environment.insert("id".to_string(), toml::Value::String("default".to_string()));
// Install seeds `default` in the server catalog separately. Run creation
// already selects it when no environment is supplied; writing a [run] table
// here would make the CLI warn about settings it does not transmit.
let server = ensure_table(root, "server")?;
write_sandbox_provider_policy(server, selection, allow_local)?;
Ok(())
@ -1325,7 +1324,6 @@ stale = "remove-me"
.and_then(toml::Value::as_str),
Some("/srv/fabro/objects")
);
assert!(server.get("slatedb").is_none());
assert!(plan.writes.is_empty());
assert_eq!(plan.removals.len(), 2);
}
@ -1354,7 +1352,6 @@ stale = "remove-me"
.and_then(toml::Value::as_str),
Some("artifacts")
);
assert!(server.get("slatedb").is_none());
assert!(plan.writes.is_empty());
}
@ -1393,42 +1390,22 @@ stale = "remove-me"
}
#[test]
fn write_sandbox_settings_records_run_default_without_environment_catalog() {
fn write_sandbox_settings_records_docker_policy() {
let mut doc = toml::Value::Table(toml::Table::default());
write_sandbox_settings(&mut doc, InstallSandboxSelection::Docker, true)
.expect("docker sandbox selection should succeed");
assert_eq!(
doc.get("run")
.and_then(toml::Value::as_table)
.and_then(|run| run.get("environment"))
.and_then(toml::Value::as_table)
.and_then(|env| env.get("id"))
.and_then(toml::Value::as_str),
Some("default")
);
assert!(doc.get("environments").is_none());
assert_eq!(sandbox_provider_enabled(&doc, "local"), Some(true));
assert_eq!(sandbox_provider_enabled(&doc, "docker"), Some(true));
assert_eq!(sandbox_provider_enabled(&doc, "daytona"), Some(false));
}
#[test]
fn write_sandbox_settings_records_daytona_policy_without_environment_catalog() {
fn write_sandbox_settings_records_daytona_policy() {
let mut doc = toml::Value::Table(toml::Table::default());
write_sandbox_settings(&mut doc, InstallSandboxSelection::Daytona, true)
.expect("daytona sandbox selection should succeed");
assert_eq!(
doc.get("run")
.and_then(toml::Value::as_table)
.and_then(|run| run.get("environment"))
.and_then(toml::Value::as_table)
.and_then(|env| env.get("id"))
.and_then(toml::Value::as_str),
Some("default")
);
assert!(doc.get("environments").is_none());
assert_eq!(sandbox_provider_enabled(&doc, "local"), Some(true));
assert_eq!(sandbox_provider_enabled(&doc, "docker"), Some(false));
assert_eq!(sandbox_provider_enabled(&doc, "daytona"), Some(true));

View file

@ -17,6 +17,7 @@ use lithos_llm::catalog::{
adapter_ids, codec_ids,
};
use serde::Deserialize;
use toml::{Table, Value};
/// The metadata namespace agent harnesses read.
const AGENT_METADATA_NAMESPACE: &str = "agent";
@ -30,75 +31,59 @@ pub fn build_catalog(
overlay: &LlmLayer,
env_lookup: &dyn Fn(&str) -> Option<String>,
) -> Result<Catalog, CatalogError> {
let mut builder = Catalog::builder().with_builtin();
if !overlay.is_empty() {
let mut document = overlay.to_overlay_toml();
document.insert_str(0, "schema_version = 1\n");
builder = builder.toml_layer("settings [llm]", &document)?;
}
if let Some(base_url) = env_lookup(EnvVars::OPENAI_BASE_URL) {
let document = format!(
"schema_version = 1\n[providers.openai]\nbase_url = {}\n",
toml::Value::String(base_url.trim_end_matches("/v1").to_string())
);
builder = builder.toml_layer("OPENAI_BASE_URL", &document)?;
}
let catalog = builder.build()?;
// The coding agent reads a provider's harness profile from
// `metadata.agent.profile` and refuses a provider without one. The lithos
// built-ins all declare theirs; an operator-defined provider that does
// not gets the profile its wire protocol implies, layered on last.
let base_url_overlay = env_lookup(EnvVars::OPENAI_BASE_URL).map(|base_url| {
LlmLayer::from_providers([(
"openai".into(),
Table::from_iter([(
"base_url".into(),
Value::String(base_url.trim_end_matches("/v1").to_string()),
)]),
)])
});
let build_base = || {
let mut builder = Catalog::builder().with_builtin();
if !overlay.is_empty() {
builder = add_catalog_layer(builder, "settings [llm]", overlay)?;
}
if let Some(overlay) = &base_url_overlay {
builder = add_catalog_layer(builder, "OPENAI_BASE_URL", overlay)?;
}
Ok::<_, CatalogError>(builder)
};
let catalog = build_base()?.build()?;
// Pebble needs provider-level profile metadata. Fill only missing profiles
// after the operator overlay has selected the provider's wire protocol.
let implied = implied_agent_profiles(&catalog);
if implied.is_empty() {
return Ok(catalog);
}
let mut builder = Catalog::builder().with_builtin();
if !overlay.is_empty() {
let mut document = overlay.to_overlay_toml();
document.insert_str(0, "schema_version = 1\n");
builder = builder.toml_layer("settings [llm]", &document)?;
}
if let Some(base_url) = env_lookup(EnvVars::OPENAI_BASE_URL) {
let document = format!(
"schema_version = 1\n[providers.openai]\nbase_url = {}\n",
toml::Value::String(base_url.trim_end_matches("/v1").to_string())
);
builder = builder.toml_layer("OPENAI_BASE_URL", &document)?;
}
builder
.toml_layer("implied agent profiles", &implied)
.and_then(CatalogBuilder::build)
add_catalog_layer(build_base()?, "implied agent profiles", &implied)?.build()
}
/// A TOML layer declaring `metadata.agent.profile` for every provider that
/// has none, as the profile implied by the provider's adapter. Empty when
/// every provider already says.
fn implied_agent_profiles(catalog: &Catalog) -> String {
use std::fmt::Write as _;
fn add_catalog_layer(
builder: CatalogBuilder,
name: &str,
overlay: &LlmLayer,
) -> Result<CatalogBuilder, CatalogError> {
// The fixed schema declaration is outside the settings overlay. All
// dynamic keys and values are serialized together by the TOML library.
let document = format!("schema_version = 1\n{}", overlay.to_overlay_toml());
builder.toml_layer(name, &document)
}
let mut document = String::new();
for provider in catalog.providers() {
/// Metadata for providers without an explicit harness profile.
fn implied_agent_profiles(catalog: &Catalog) -> LlmLayer {
LlmLayer::from_providers(catalog.providers().filter_map(|provider| {
if agent_metadata(provider.metadata()).profile.is_some() {
continue;
return None;
}
let profile = adapter_agent_profile(provider);
let _ = writeln!(
document,
"[providers.{}.metadata.agent]\nprofile = {}\n",
provider.id(),
toml::Value::String(
serde_json::to_value(profile)
.ok()
.and_then(|value| value.as_str().map(str::to_owned))
.unwrap_or_else(|| "openai".to_string())
),
);
}
if document.is_empty() {
return document;
}
document.insert_str(0, "schema_version = 1\n");
document
let profile = Value::try_from(adapter_agent_profile(provider))
.expect("agent profiles serialize as strings");
let agent = Table::from_iter([("profile".into(), profile)]);
let metadata = Table::from_iter([("agent".into(), Value::Table(agent))]);
let fields = Table::from_iter([("metadata".into(), Value::Table(metadata))]);
Some((provider.id().to_string(), fields))
}))
}
/// The profile a provider's wire protocol implies, for a provider whose
@ -313,6 +298,111 @@ capabilities = { text = true, tools = true }
);
}
#[test]
fn dotted_provider_profiles_preserve_identity_metadata_and_model_overrides() {
let source = r#"
[providers."my.gw"]
display_name = "Gateway"
base_url = "http://127.0.0.1:1234/v1"
auth = { type = "bearer" }
[providers."my.gw".metadata.agent]
reasoning_by_default = false
[providers."my.gw".models."model.v1"]
display_name = "Model"
api_model = "wire-model"
[providers."my.gw".models."model.v1".metadata.agent]
profile = "anthropic"
[providers.my]
display_name = "Sibling"
base_url = "http://127.0.0.1:5678"
auth = { type = "none" }
[providers.my.metadata.agent]
profile = "gemini"
"#;
for enabled in [true, false] {
let mut overlay = LlmLayer(toml::from_str(source).unwrap());
overlay.0["providers"]["my.gw"]
.as_table_mut()
.unwrap()
.insert("enabled".into(), Value::Boolean(enabled));
let catalog = build_catalog(&overlay, &|name| {
(name == EnvVars::OPENAI_BASE_URL).then(|| "http://127.0.0.1:4321/v1".into())
})
.unwrap();
let gateway = catalog.provider("my.gw").unwrap();
assert_eq!(gateway.id().as_str(), "my.gw");
assert_eq!(gateway.base_url(), "http://127.0.0.1:1234/v1");
assert_eq!(
agent_metadata(gateway.metadata()).profile,
Some(AgentProfileKind::OpenAi)
);
assert_eq!(
agent_metadata(gateway.metadata()).reasoning_by_default,
Some(false)
);
assert_eq!(gateway.model("model.v1").unwrap().api_model(), "wire-model");
assert_eq!(
model_agent_profile(gateway, gateway.model("model.v1").unwrap()),
AgentProfileKind::Anthropic
);
assert_eq!(
fabro_auth::expected_secret_name(gateway).as_deref(),
Some("MY_GW_API_KEY")
);
assert_eq!(
agent_profile(&catalog, "my", None),
Some(AgentProfileKind::Gemini)
);
assert_eq!(catalog.enabled_provider("my.gw").is_some(), enabled);
assert_eq!(
catalog.provider("openai").unwrap().base_url(),
"http://127.0.0.1:4321"
);
}
}
#[test]
fn provider_names_remain_literal_with_inferred_and_explicit_profiles() {
for id in [
"my.gw", "my.gw.v2", "my-gw", "my_gw", ".gateway", "gateway.",
] {
for explicit in [None, Some("openai"), Some("gemini")] {
let mut fields: Table = toml::from_str(
r#"
display_name = "Gateway"
base_url = "http://127.0.0.1:1234"
auth = { type = "none" }
"#,
)
.unwrap();
if let Some(profile) = explicit {
fields.insert(
"metadata".into(),
Value::Table(Table::from_iter([(
"agent".into(),
Value::Table(Table::from_iter([(
"profile".into(),
Value::String(profile.into()),
)])),
)])),
);
}
let overlay = LlmLayer::from_providers([(id.into(), fields)]);
let catalog = build_catalog(&overlay, &|_| None).unwrap();
assert_eq!(catalog.provider(id).unwrap().id().as_str(), id);
assert_eq!(
agent_profile(&catalog, id, None),
Some(if explicit == Some("gemini") {
AgentProfileKind::Gemini
} else {
AgentProfileKind::OpenAi
})
);
assert!(catalog.provider("my").is_err());
}
}
}
/// The implied profile follows the provider's first codec, so a host that
/// speaks Anthropic Messages gets the Anthropic harness.
#[test]

Some files were not shown because too many files have changed in this diff Show more