Skip to content

20 AI testers on 20 different phones, in parallel, on GitHub's free runners: Claude Code agents on iOS Simulators and Android emulators that find broken flows, translation, layout and accessibility bugs

Cheaper models, improvement report, compare two versions

Pierre RAFFALLIe75641635a84
diff --git a/.github/workflows/agent-testers.yml b/.github/workflows/agent-testers.yml
index 959e0f9..53e4ef2 100644
--- a/.github/workflows/agent-testers.yml
+++ b/.github/workflows/agent-testers.yml
@@ -48,8 +48,11 @@ on:
description: "Bug to reproduce instead of exploring: an issue (owner/repo#123 or its URL) or the steps as text. Agents follow it: read it first"
default: ""
model:
- description: Claude model (alias or full id)
+ description: "Model: sonnet, opus, haiku (cheapest) or a full Claude id. With llm_base_url, the provider's model name"
default: sonnet
+ llm_base_url:
+ description: "Optional: any Anthropic-compatible API instead of Claude (OpenRouter, DeepSeek, Kimi, GLM...), key in the LLM_API_KEY secret. Quality depends on how well the model reads screenshots and reasons: docs/cheaper-models.md"
+ default: ""
block_hosts:
description: Hosts the app must not reach during tests (analytics, ads), space-separated
default: "app.posthog.com eu.i.posthog.com us.i.posthog.com graph.facebook.com api.mixpanel.com api2.amplitude.com"
@@ -235,6 +238,8 @@ jobs:
APP_ID: ${{ inputs.app_id }}
BRIEF: ${{ inputs.bug_report != '' && inputs.brief == 'AGENT_BRIEF.md' && 'briefs/reproduce.md' || inputs.brief }}
MODEL: ${{ inputs.model }}
+ LLM_BASE_URL: ${{ inputs.llm_base_url }}
+ LLM_API_KEY: ${{ secrets.LLM_API_KEY }}
BLOCK_HOSTS: ${{ inputs.block_hosts }}
RECORD_VIDEO: ${{ inputs.record_video }}
with:
@@ -337,6 +342,8 @@ jobs:
APP_ID: ${{ inputs.app_id }}
BRIEF: ${{ inputs.bug_report != '' && inputs.brief == 'AGENT_BRIEF.md' && 'briefs/reproduce.md' || inputs.brief }}
MODEL: ${{ inputs.model }}
+ LLM_BASE_URL: ${{ inputs.llm_base_url }}
+ LLM_API_KEY: ${{ secrets.LLM_API_KEY }}
BLOCK_HOSTS: ${{ inputs.block_hosts }}
RECORD_VIDEO: ${{ inputs.record_video }}
run: bash scripts/ios/run_agent.sh
diff --git a/CHANGELOG.md b/CHANGELOG.md
index e545819..a562424 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -2,6 +2,10 @@
## Unreleased
+- **Cheaper models**: `model=haiku`, or any Anthropic-compatible API (OpenRouter, DeepSeek, Kimi, GLM, MiniMax, Qwen) with the new `llm_base_url` input and an `LLM_API_KEY` secret ([scripts/llm_env.sh](scripts/llm_env.sh)). The findings depend on how well the model reads screenshots and reasons: [docs/cheaper-models.md](docs/cheaper-models.md).
+- **Improvement report**: with [briefs/improve.md](briefs/improve.md), each persona uses the app once to reach its goal, then lists what to change first, by area and impact. SUMMARY.md starts with the goals reached, the actions and the scores, then the improvements.
+- **Compare two versions**: `scripts/compare.py` puts two runs of the same personas side by side (two branches, two builds): goals reached, actions, scores, issues seen on one version only, improvements by area ([docs/compare-versions.md](docs/compare-versions.md)).
+- **README**: a "What it does" list of the uses, and the LocalSend, AnkiDroid and Flutter runs grouped under "Applied examples".
- **Reproduce a bug report**: the `bug_report` input takes an issue (`owner/repo#123` or its URL) or the steps as text. Each agent follows it on its own device with [briefs/reproduce.md](briefs/reproduce.md) and answers yes, no or unclear, with screenshots; the summary starts with a table of the devices where it happens.
- **Standalone skill**: `skills/mobile-agent-testers/` is the plugin's setup skill as a plain Agent Skill, for skill catalogs and agents without Claude Code plugins. A test keeps the two copies identical.
diff --git a/README.es.md b/README.es.md
index 77354c8..60e83fc 100644
--- a/README.es.md
+++ b/README.es.md
@@ -27,7 +27,22 @@ o tu clave de API: entre 0,15 y 0,55 $ por teléfono en [estas ejecuciones](docs
![Claude Code plugin](https://img.shields.io/badge/Claude%20Code-plugin-orange)
[![Last commit](https://img.shields.io/github/last-commit/pierridotite/mobile-agent-testers)](https://github.com/pierridotite/mobile-agent-testers/commits/main)
-## No solo accesibilidad
+## Qué puede hacer
+
+Un uso por ejecución, elegido con los parámetros de [Prueba tu propia app](#prueba-tu-propia-app).
+
+- **Explorar como usuarios nuevos** (por defecto). Cada persona intenta alcanzar su objetivo y cuenta lo que se lo impide, con capturas numeradas.
+- **Recorrer una función de principio a fin.** Tu propio brief manda a cada agente por una mecánica completa: una reserva en varios pasos, un editor con deshacer, una sincronización entre dos pantallas. Los agentes tocan, mantienen pulsado, deslizan y escriben, salen de la app y vuelven, la reinician para comprobar qué se guardó o abren un enlace profundo para empezar directamente en la función, y un brief puede subir el presupuesto de unas 30 acciones. [El de AnkiDroid](briefs/ankidroid.md) encontró el campo del reverso de una tarjeta nueva tapado por el teclado.
+- **Reproducir un informe de error** en cada teléfono: das un issue o los pasos, y cada agente responde sí, no o no está claro, con capturas ([briefs/reproduce.md](briefs/reproduce.md)).
+- **Obtener un informe de mejoras.** Cada persona usa la app una vez y luego dice dónde dudó, qué esperaba y qué cambiaría primero, por área e impacto ([briefs/improve.md](briefs/improve.md)).
+- **Comparar dos versiones.** Las mismas personas en dos ramas o builds, y luego una tabla: objetivos alcanzados, acciones, puntuaciones, errores vistos en una sola versión ([docs/compare-versions.md](docs/compare-versions.md)). Una comprobación antes de un test A/B real, no un sustituto.
+- **Usar un modelo más barato**: Claude Haiku, o cualquier API compatible con Anthropic (OpenRouter, DeepSeek, Kimi, GLM, MiniMax, Qwen). Los hallazgos dependen de lo bien que el modelo lea las capturas y razone ([docs/cheaper-models.md](docs/cheaper-models.md)).
+
+## Ejemplos aplicados
+
+Ejecuciones reales en apps de código abierto, sin nada plantado.
+
+### No solo accesibilidad
El texto grande da las capturas más llamativas, pero es una parte pequeña de lo que reportan los agentes. Cada persona tiene un objetivo («terminar una tarea sin inglés», «rellenar cada campo de texto con caracteres turcos, emojis y textos muy largos», «salir de la app a mitad y volver») e intenta lograrlo como un usuario nuevo, así que los agentes reportan todo lo que se interpone:
@@ -40,12 +55,6 @@ El texto grande da las capturas más llamativas, pero es una parte pequeña de l
En LocalSend, 34 de los 46 errores no tenían nada que ver con el tamaño del texto ni con la accesibilidad. Además, cada informe termina con la opinión de la persona y una nota sobre 10 (¿se quedaría con la app?), así que una ejecución muestra dónde se pierden los usuarios nuevos, no solo qué está roto.
-### También funciones complejas
-
-El brief por defecto explora como un usuario nuevo. Con tu propio brief puedes mandar a cada agente a recorrer una mecánica completa, paso a paso: [el de AnkiDroid](briefs/ankidroid.md) pidió a los 10 crear un mazo, añadir tres tarjetas, estudiarlas y luego cambiar un ajuste, y dos encontraron el campo del reverso de una tarjeta nueva tapado por el teclado. Mándalos a tu función más difícil: una reserva en varios pasos, un editor con deshacer, una sincronización entre dos pantallas, un juego de puzles. Los agentes tocan, mantienen pulsado, deslizan y escriben, salen de la app y vuelven, la reinician para comprobar qué se guardó o abren un enlace profundo para empezar directamente en la función. Un brief también puede subir el presupuesto por defecto de unas 30 acciones por agente.
-
-## Hallazgos reales
-
### LocalSend: 20 agentes, 20 dispositivos, 14 idiomas
<p align="center"><img src="assets/real-findings-localsend-20.png" alt="Cuatro pantallas de LocalSend con las franjas de desbordamiento de Flutter, cada problema enmarcado en rojo: un Pixel 7 con el texto al 200 % donde los seis botones de envío se desbordan, un iPhone SE en sueco con el texto más grande donde el diálogo de mensaje se desborda 149 píxeles y oculta el campo de texto y Confirmar, un iPad Air en alemán donde el botón Añadir se sale 114 píxeles de su tarjeta, y un iPhone SE en francés con el tamaño de texto por defecto donde una fila se desborda 28 píxeles" width="100%"></p>
@@ -142,8 +151,9 @@ gh workflow run agent-testers.yml -f source_repo=you/app -f app_id=com.you.app \
| `source_repo`, `ref` | Repositorio y rama de la app (vacío = este repositorio). Repositorio privado: añade un secret `SOURCE_REPO_TOKEN` de solo lectura |
| `app_dir`, `app_id` | Carpeta de la app, paquete de Android / bundle id de iOS (si la otra plataforma usa otro id, se lee de su app compilada) |
| `android_personas`, `ios_personas` | Ids de [personas.json](personas.json), un teléfono cada una, `all`, o `none` para saltar una plataforma. 20 listas: 14 idiomas, derecha a izquierda, tabletas, texto desde pequeño hasta el mayor tamaño de accesibilidad |
-| `brief` | Instrucciones para los agentes ([AGENT_BRIEF.md](AGENT_BRIEF.md)) |
+| `brief` | Instrucciones para los agentes: [AGENT_BRIEF.md](AGENT_BRIEF.md) para explorar, [briefs/improve.md](briefs/improve.md) para un informe de mejoras, o el tuyo para una función |
| `bug_report` | Un error que reproducir en lugar de explorar: un issue (`owner/repo#123` o su URL) o los pasos en texto. Cada agente lo sigue en su propio dispositivo ([briefs/reproduce.md](briefs/reproduce.md)) |
+| `model`, `llm_base_url` | `sonnet` por defecto, `haiku` para gastar menos, o cualquier API compatible con Anthropic con su clave en un secret `LLM_API_KEY` ([docs/cheaper-models.md](docs/cheaper-models.md)) |
| `framework` | `auto` (por defecto) o fuerza uno de los frameworks de abajo |
| `android_build` + `apk_path`, `ios_build` + `ios_app_path` | Tu propio comando de compilación, o la descarga de una app ya compilada (rutas relativas a `app_dir`) |
| `block_hosts` | Hosts de analítica bloqueados durante las pruebas |
@@ -191,7 +201,7 @@ No. En LocalSend, los 103 informes eran 46 errores distintos, y 29 de ellos los
### ¿Cuánto cuesta?
-Los runners de GitHub son gratis para repositorios públicos, macOS incluido. El uso del modelo fue de 0,15 a 0,55 $ por agente en [estas ejecuciones](docs/runs/), unos 5 $ para 20 teléfonos. Con una suscripción a Claude, las ejecuciones cuentan en el uso de tu plan en lugar de facturarse.
+Los runners de GitHub son gratis para repositorios públicos, macOS incluido. El uso del modelo fue de 0,15 a 0,55 $ por agente en [estas ejecuciones](docs/runs/), unos 5 $ para 20 teléfonos. Con una suscripción a Claude, las ejecuciones cuentan en el uso de tu plan en lugar de facturarse. Para gastar menos, usa `model=haiku` o el modelo de otro proveedor: [docs/cheaper-models.md](docs/cheaper-models.md).
### ¿Cuánto tarda una ejecución?
diff --git a/README.ja.md b/README.ja.md
index a8b23ba..8c30617 100644
--- a/README.ja.md
+++ b/README.ja.md
@@ -27,7 +27,22 @@ API キーを使います。[これまでの実行](docs/runs/)では 1 台あ
![Claude Code plugin](https://img.shields.io/badge/Claude%20Code-plugin-orange)
[![Last commit](https://img.shields.io/github/last-commit/pierridotite/mobile-agent-testers)](https://github.com/pierridotite/mobile-agent-testers/commits/main)
-## アクセシビリティだけではない
+## できること
+
+1 回の実行で 1 つの使い方です。設定は[自分のアプリをテストする](#自分のアプリをテストする)の入力で行います。
+
+- **新しいユーザーとして探索**(デフォルト)。各ペルソナが自分の目標を達成しようとし、妨げになったことを番号付きのスクリーンショットとともに報告します。
+- **1 つの機能を最初から最後まで試す。** 自分で書いた brief で、各エージェントに 1 つの仕組みを通しで試させます。複数ステップの予約、元に戻せるエディター、2 つの画面間の同期などです。エージェントはタップ、長押し、スワイプ、入力ができ、アプリを離れて戻ったり、再起動して保存内容を確かめたり、ディープリンクで目的の機能から直接始めたりします。brief では約 30 操作という上限を増やすこともできます。[AnkiDroid 用の brief](briefs/ankidroid.md) では、新しいカードの裏面の入力欄がキーボードに隠れることが見つかりました。
+- **バグ報告をすべての端末で再現**:issue か手順を渡すと、各エージェントが「再現した / しなかった / はっきりしない」をスクリーンショット付きで答えます([briefs/reproduce.md](briefs/reproduce.md))。
+- **改善レポートを作る。** 各ペルソナがアプリを一度使い、どこで迷ったか、何を期待していたか、まず何を変えるべきかを、領域と影響度つきで挙げます([briefs/improve.md](briefs/improve.md))。
+- **2 つのバージョンを比較する。** 同じペルソナで 2 つのブランチやビルドを試し、目標の達成、操作数、スコア、片方のバージョンだけで見つかった問題を 1 つの表にまとめます([docs/compare-versions.md](docs/compare-versions.md))。本物の A/B テストの前のチェックであり、その代わりにはなりません。
+- **安いモデルを使う**:Claude Haiku、または Anthropic 互換の API(OpenRouter、DeepSeek、Kimi、GLM、MiniMax、Qwen)。見つかるものの質は、モデルがスクリーンショットをどれだけ正しく読めるかと推論力で決まります([docs/cheaper-models.md](docs/cheaper-models.md))。
+
+## 適用例
+
+オープンソースのアプリでの実際の実行です。仕込んだバグはありません。
+
+### アクセシビリティだけではない
大きな文字のスクリーンショットは目を引きますが、エージェントが報告する内容のほんの一部です。各ペルソナには目標があり(「英語を使わずにタスクを 1 つ終える」「すべての入力欄にトルコ語の文字、絵文字、とても長いテキストを入れる」「途中でアプリを離れて、また戻ってくる」)、新しいユーザーとしてそれを達成しようとするので、行く手をはばむものは何でも報告されます。
@@ -39,11 +54,6 @@ API キーを使います。[これまでの実行](docs/runs/)では 1 台あ
- **データ**:再起動すると何も保存されていない(デモアプリ)。
LocalSend では、46 件のバグのうち 34 件が文字サイズともアクセシビリティとも無関係でした。どのレポートも最後にペルソナ自身の意見と 10 点満点のスコア(このアプリを使い続けるか?)が付くので、壊れている箇所だけでなく、新しいユーザーがどこで迷うかもわかります。
-### 複雑な機能もテストできる
-
-デフォルトの brief では、新しいユーザーとして自由に探索します。自分で brief を書けば、各エージェントに 1 つの仕組みを最初から最後まで順に試させることもできます。[AnkiDroid 用の brief](briefs/ankidroid.md) は、10 エージェント全員にデッキを作らせ、カードを 3 枚追加して一度学習させ、最後に設定を 1 つ変更させるものです。その途中で 2 つのエージェントが、新しいカードの裏面の入力欄がキーボードに隠れることを見つけました。複数ステップの予約、元に戻せるエディター、2 つの画面間の同期、パズルゲームなど、いちばん難しい機能に向かわせてください。エージェントはタップ、長押し、スワイプ、入力ができ、アプリを離れて戻ったり、再起動して保存内容を確かめたり、ディープリンクで目的の機能から直接始めたりできます。brief では、1 エージェントあたり約 30 操作というデフォルトの上限を増やすこともできます。
-
-## 実際に見つかったバグ
### LocalSend:20 エージェント、20 台、14 言語
@@ -141,8 +151,9 @@ gh workflow run agent-testers.yml -f source_repo=you/app -f app_id=com.you.app \
| `source_repo`, `ref` | アプリのリポジトリとブランチ(空 = このリポジトリ)。プライベートリポジトリの場合は読み取り専用の `SOURCE_REPO_TOKEN` シークレットを追加 |
| `app_dir`, `app_id` | アプリのフォルダー、Android のパッケージ名 / iOS の bundle id(もう一方のプラットフォームが別の id を使う場合は、ビルドしたアプリから読み取ります) |
| `android_personas`, `ios_personas` | [personas.json](personas.json) の id(1 つにつき 1 台)、`all`、またはプラットフォームを飛ばす `none`。20 人が用意済み:14 言語、右から左、タブレット、小さい文字からアクセシビリティの最大サイズまで |
-| `brief` | エージェントへの指示([AGENT_BRIEF.md](AGENT_BRIEF.md)) |
+| `brief` | エージェントへの指示:探索なら [AGENT_BRIEF.md](AGENT_BRIEF.md)、改善レポートなら [briefs/improve.md](briefs/improve.md)、1 つの機能を試すなら自分で書いたもの |
| `bug_report` | 探索の代わりに再現するバグ:issue(`owner/repo#123` またはその URL)か、手順をそのまま書いたテキスト。各エージェントが自分の端末でその手順を試します([briefs/reproduce.md](briefs/reproduce.md)) |
+| `model`、`llm_base_url` | デフォルトは `sonnet`。費用を抑えるなら `haiku`、または Anthropic 互換の任意の API(キーは `LLM_API_KEY` シークレットに設定)([docs/cheaper-models.md](docs/cheaper-models.md)) |
| `framework` | `auto`(デフォルト)、または下のフレームワークのいずれかを指定 |
| `android_build` + `apk_path`, `ios_build` + `ios_app_path` | 独自のビルドコマンド、またはビルド済みアプリのダウンロード(パスは `app_dir` からの相対パス) |
| `block_hosts` | テスト中にブロックする分析系のホスト |
@@ -188,7 +199,7 @@ gh workflow run agent-testers.yml -f source_repo=you/app -f app_id=com.you.app \
### 費用は?
-公開リポジトリでは GitHub のランナーは macOS も含めて無料です。[これまでの実行](docs/runs/)では、モデル使用量はエージェント 1 つあたり 0.15〜0.55 ドルで、20 台でおよそ 5 ドルでした。Claude のサブスクリプションを使う場合は、請求ではなくプランの使用量として数えられます。
+公開リポジトリでは GitHub のランナーは macOS も含めて無料です。[これまでの実行](docs/runs/)では、モデル使用量はエージェント 1 つあたり 0.15〜0.55 ドルで、20 台でおよそ 5 ドルでした。Claude のサブスクリプションを使う場合は、請求ではなくプランの使用量として数えられます。費用を抑えるには、`model=haiku` かほかのプロバイダーのモデルで実行してください:[docs/cheaper-models.md](docs/cheaper-models.md)。
### 1 回の実行にかかる時間は?
diff --git a/README.md b/README.md
index 681d1ca..6fa79f9 100644
--- a/README.md
+++ b/README.md
@@ -26,7 +26,22 @@ Claude subscription or API key: about $0.15 to $0.55 per phone in [these runs](d
![Claude Code plugin](https://img.shields.io/badge/Claude%20Code-plugin-orange)
[![Last commit](https://img.shields.io/github/last-commit/pierridotite/mobile-agent-testers)](https://github.com/pierridotite/mobile-agent-testers/commits/main)
-## Not just accessibility
+## What it does
+
+One use per run, set with the inputs of [Test your own app](#test-your-own-app).
+
+- **Explore like new users** (the default). Each persona tries to reach its goal and reports what gets in the way, with numbered screenshots.
+- **Run one feature end to end.** Your own brief sends every agent through a whole mechanic: a booking in several steps, an editor with undo, a sync between two screens. Agents tap, long press, swipe and type, leave the app and come back, relaunch it to check what was saved, or open a deep link to start right at the feature, and a brief can raise the budget of about 30 actions. [AnkiDroid's](briefs/ankidroid.md) found the Back field of a new card hidden behind the keyboard.
+- **Reproduce a bug report** on every phone: give an issue or the steps, and each agent answers yes, no or unclear, with screenshots ([briefs/reproduce.md](briefs/reproduce.md)).
+- **Get an improvement report.** Each persona uses the app once, then says where it hesitated, what it expected and what to change first, by area and impact ([briefs/improve.md](briefs/improve.md)).
+- **Compare two versions.** The same personas on two branches or builds, then one table: goals reached, actions, scores, issues seen on one version only ([docs/compare-versions.md](docs/compare-versions.md)). A check before a real A/B test, not a replacement for one.
+- **Use a cheaper model**: Claude Haiku, or any Anthropic-compatible API (OpenRouter, DeepSeek, Kimi, GLM, MiniMax, Qwen). The findings are only as good as the model's reading of screenshots and its reasoning ([docs/cheaper-models.md](docs/cheaper-models.md)).
+
+## Applied examples
+
+Real runs on open-source apps, with nothing planted.
+
+### Not just accessibility
Large text makes the most striking screenshots, but it is a small part of what the agents report. Each persona has a goal ("finish one task without English", "fill every text field with Turkish characters, emoji and very long text", "leave the app in the middle of it, then come back") and tries to reach it like a new user, so the agents report whatever gets in the way:
@@ -39,12 +54,6 @@ Large text makes the most striking screenshots, but it is a small part of what t
On LocalSend, 34 of the 46 bugs had nothing to do with text size or accessibility. Every report also ends with the persona's opinion and a score out of 10 (would they keep the app?), so a run shows where new users get lost, not only what is broken.
-### Complex features too
-
-The default brief explores like a new user. Your own brief can send every agent through a whole mechanic, step by step: [AnkiDroid's](briefs/ankidroid.md) asked all 10 to create a deck, add three cards, study them, then change a setting, and two of them found the Back field of a new card hidden behind the keyboard. Point them at your hardest feature: a booking in several steps, an editor with undo, a sync between two screens, a puzzle game. The agents tap, long press, swipe and type, leave the app and come back, relaunch it to check what was saved, or open a deep link to start right at the feature. A brief can also raise the default budget of about 30 actions per agent.
-
-## Real findings
-
### LocalSend: 20 agents, 20 devices, 14 languages
<p align="center"><img src="assets/real-findings-localsend-20.png" alt="Four LocalSend screens with Flutter's overflow stripes, each boxed in red: a Pixel 7 at 200% text where all six Send buttons overflow, an iPhone SE in Swedish at the largest text size where the message dialog overflows by 149 pixels and hides the text field and Confirm, an iPad Air in German where the Add button overflows its card by 114 pixels, and an iPhone SE in French at the default text size where a row overflows by 28 pixels" width="100%"></p>
@@ -141,8 +150,9 @@ gh workflow run agent-testers.yml -f source_repo=you/app -f app_id=com.you.app \
| `source_repo`, `ref` | App repo and branch (empty = this repo). Private repo: add a read-only `SOURCE_REPO_TOKEN` secret |
| `app_dir`, `app_id` | App folder, Android package / iOS bundle id (if the other platform uses another id, it is read from its built app) |
| `android_personas`, `ios_personas` | Ids from [personas.json](personas.json), one phone each, `all`, or `none` to skip a platform. 20 ready: 14 languages, right to left, tablets, text from small to the largest accessibility size |
-| `brief` | Agent instructions ([AGENT_BRIEF.md](AGENT_BRIEF.md)) |
+| `brief` | Agent instructions: [AGENT_BRIEF.md](AGENT_BRIEF.md) to explore, [briefs/improve.md](briefs/improve.md) for an improvement report, or your own for one feature |
| `bug_report` | A bug to reproduce instead of exploring: an issue (`owner/repo#123` or its URL) or the steps as text. Each agent follows it on its own device ([briefs/reproduce.md](briefs/reproduce.md)) |
+| `model`, `llm_base_url` | `sonnet` by default, `haiku` to spend less, or any Anthropic-compatible API with its key in an `LLM_API_KEY` secret ([docs/cheaper-models.md](docs/cheaper-models.md)) |
| `framework` | `auto` (default) or force one of the frameworks below |
| `android_build` + `apk_path`, `ios_build` + `ios_app_path` | Your own build command, or a download of a prebuilt app (paths relative to `app_dir`) |
| `block_hosts` | Analytics hosts blocked during tests |
@@ -190,7 +200,7 @@ No. On LocalSend, the 103 reports were 46 distinct bugs, and 29 of them were fou
### How much does it cost?
-GitHub's runners are free for public repos, macOS included. Model usage was $0.15 to $0.55 per agent in [these runs](docs/runs/), so about $5 for 20 phones. With a Claude subscription, runs count against your plan's usage instead of a bill.
+GitHub's runners are free for public repos, macOS included. Model usage was $0.15 to $0.55 per agent in [these runs](docs/runs/), so about $5 for 20 phones. With a Claude subscription, runs count against your plan's usage instead of a bill. To spend less, run `model=haiku` or another provider's model: [docs/cheaper-models.md](docs/cheaper-models.md).
### How long does a run take?
diff --git a/README.pt-BR.md b/README.pt-BR.md
index 0996133..cf3c587 100644
--- a/README.pt-BR.md
+++ b/README.pt-BR.md
@@ -27,7 +27,22 @@ Claude ou chave de API: de US$ 0,15 a US$ 0,55 por celular [nestas execuções](
![Claude Code plugin](https://img.shields.io/badge/Claude%20Code-plugin-orange)
[![Last commit](https://img.shields.io/github/last-commit/pierridotite/mobile-agent-testers)](https://github.com/pierridotite/mobile-agent-testers/commits/main)
-## Não é só acessibilidade
+## O que ele faz
+
+Um uso por execução, escolhido com os parâmetros de [Teste o seu próprio app](#teste-o-seu-próprio-app).
+
+- **Explorar como usuários novos** (o padrão). Cada persona tenta chegar ao seu objetivo e conta o que atrapalha, com capturas numeradas.
+- **Percorrer uma função do começo ao fim.** O seu próprio brief manda cada agente por uma mecânica inteira: uma reserva em várias etapas, um editor com desfazer, uma sincronização entre duas telas. Os agentes tocam, pressionam e seguram, deslizam e digitam, saem do app e voltam, reiniciam o app para conferir o que foi salvo ou abrem um deep link para começar direto na função, e um brief pode aumentar o orçamento de cerca de 30 ações. [O do AnkiDroid](briefs/ankidroid.md) encontrou o campo do verso de um cartão novo escondido atrás do teclado.
+- **Reproduzir um relato de bug** em cada celular: você passa uma issue ou os passos, e cada agente responde sim, não ou incerto, com capturas ([briefs/reproduce.md](briefs/reproduce.md)).
+- **Gerar um relatório de melhorias.** Cada persona usa o app uma vez e depois diz onde hesitou, o que esperava e o que mudaria primeiro, por área e impacto ([briefs/improve.md](briefs/improve.md)).
+- **Comparar duas versões.** As mesmas personas em dois branches ou builds, e depois uma tabela: objetivos alcançados, ações, notas, problemas vistos em uma versão só ([docs/compare-versions.md](docs/compare-versions.md)). Uma checagem antes de um teste A/B de verdade, não um substituto.
+- **Usar um modelo mais barato**: Claude Haiku, ou qualquer API compatível com a Anthropic (OpenRouter, DeepSeek, Kimi, GLM, MiniMax, Qwen). Os achados dependem de quão bem o modelo lê as capturas e raciocina ([docs/cheaper-models.md](docs/cheaper-models.md)).
+
+## Exemplos aplicados
+
+Execuções reais em apps de código aberto, sem nada plantado.
+
+### Não é só acessibilidade
Texto grande rende as capturas mais chamativas, mas é uma parte pequena do que os agentes relatam. Cada persona tem um objetivo ("terminar uma tarefa sem inglês", "preencher cada campo de texto com caracteres turcos, emojis e textos muito longos", "sair do app no meio e voltar depois") e tenta chegar lá como um usuário novo, então os agentes relatam tudo o que atrapalha:
@@ -40,12 +55,6 @@ Texto grande rende as capturas mais chamativas, mas é uma parte pequena do que
No LocalSend, 34 dos 46 bugs não tinham nada a ver com tamanho de texto nem com acessibilidade. Cada relatório também termina com a opinião da persona e uma nota de 0 a 10 (ela continuaria com o app?), então uma execução mostra onde os usuários novos se perdem, não só o que está quebrado.
-### Funções complexas também
-
-O brief padrão explora como um usuário novo. Com o seu próprio brief, você pode mandar cada agente percorrer uma mecânica inteira, passo a passo: [o do AnkiDroid](briefs/ankidroid.md) pediu aos 10 que criassem um baralho, adicionassem três cartões, estudassem e depois mudassem um ajuste, e dois encontraram o campo do verso de um cartão novo escondido atrás do teclado. Mande-os para a sua função mais difícil: uma reserva em várias etapas, um editor com desfazer, uma sincronização entre duas telas, um jogo de quebra-cabeça. Os agentes tocam, pressionam e seguram, deslizam e digitam, saem do app e voltam, reiniciam o app para conferir o que foi salvo ou abrem um deep link para começar direto na função. Um brief também pode aumentar o orçamento padrão de cerca de 30 ações por agente.
-
-## Bugs reais encontrados
-
### LocalSend: 20 agentes, 20 aparelhos, 14 idiomas
<p align="center"><img src="assets/real-findings-localsend-20.png" alt="Quatro telas do LocalSend com as faixas de overflow do Flutter, cada problema marcado em vermelho: um Pixel 7 com texto a 200% em que os seis botões de envio transbordam, um iPhone SE em sueco com o maior tamanho de texto em que o diálogo de mensagem transborda 149 pixels e esconde o campo de texto e o Confirmar, um iPad Air em alemão em que o botão Adicionar sai 114 pixels do cartão, e um iPhone SE em francês com o tamanho de texto padrão em que uma linha transborda 28 pixels" width="100%"></p>
@@ -142,8 +151,9 @@ gh workflow run agent-testers.yml -f source_repo=you/app -f app_id=com.you.app \
| `source_repo`, `ref` | Repositório e branch do app (vazio = este repositório). Repositório privado: adicione um secret `SOURCE_REPO_TOKEN` somente leitura |
| `app_dir`, `app_id` | Pasta do app, pacote Android / bundle id iOS (se a outra plataforma usa outro id, ele é lido do app compilado) |
| `android_personas`, `ios_personas` | Ids do [personas.json](personas.json), um celular cada, `all`, ou `none` para pular uma plataforma. 20 prontas: 14 idiomas, direita para a esquerda, tablets, texto do pequeno ao maior tamanho de acessibilidade |
-| `brief` | Instruções para os agentes ([AGENT_BRIEF.md](AGENT_BRIEF.md)) |
+| `brief` | Instruções para os agentes: [AGENT_BRIEF.md](AGENT_BRIEF.md) para explorar, [briefs/improve.md](briefs/improve.md) para um relatório de melhorias, ou o seu para uma função |
| `bug_report` | Um bug para reproduzir em vez de explorar: uma issue (`owner/repo#123` ou a URL dela) ou os passos em texto. Cada agente segue os passos no próprio aparelho ([briefs/reproduce.md](briefs/reproduce.md)) |
+| `model`, `llm_base_url` | `sonnet` por padrão, `haiku` para gastar menos, ou qualquer API compatível com a Anthropic com a chave em um secret `LLM_API_KEY` ([docs/cheaper-models.md](docs/cheaper-models.md)) |
| `framework` | `auto` (padrão) ou force um dos frameworks abaixo |
| `android_build` + `apk_path`, `ios_build` + `ios_app_path` | Seu próprio comando de build, ou o download de um app já compilado (caminhos relativos a `app_dir`) |
| `block_hosts` | Hosts de analytics bloqueados durante os testes |
@@ -191,7 +201,7 @@ Não. No LocalSend, os 103 relatórios eram 46 bugs distintos, e 29 deles foram
### Quanto custa?
-Os runners do GitHub são gratuitos para repositórios públicos, macOS incluído. O uso do modelo foi de US$ 0,15 a US$ 0,55 por agente [nestas execuções](docs/runs/), cerca de US$ 5 para 20 celulares. Com uma assinatura do Claude, as execuções contam no uso do seu plano em vez de virar conta.
+Os runners do GitHub são gratuitos para repositórios públicos, macOS incluído. O uso do modelo foi de US$ 0,15 a US$ 0,55 por agente [nestas execuções](docs/runs/), cerca de US$ 5 para 20 celulares. Com uma assinatura do Claude, as execuções contam no uso do seu plano em vez de virar conta. Para gastar menos, use `model=haiku` ou o modelo de outro provedor: [docs/cheaper-models.md](docs/cheaper-models.md).
### Quanto tempo leva uma execução?
diff --git a/README.zh-CN.md b/README.zh-CN.md
index 41010c9..3c0d1fa 100644
--- a/README.zh-CN.md
+++ b/README.zh-CN.md
@@ -26,7 +26,22 @@
![Claude Code plugin](https://img.shields.io/badge/Claude%20Code-plugin-orange)
[![Last commit](https://img.shields.io/github/last-commit/pierridotite/mobile-agent-testers)](https://github.com/pierridotite/mobile-agent-testers/commits/main)
-## 不只是无障碍
+## 能做什么
+
+每次运行一种用法,用[测试你自己的应用](#测试你自己的应用)里的参数来设置。
+
+- **像新用户一样探索**(默认)。每个角色都会努力完成自己的目标,并报告一路上遇到的障碍,附带编号截图。
+- **把一个功能从头测到尾。** 用你自己的 brief 让每个智能体完整走一遍某个机制:分几步的预订、带撤销的编辑器、两个页面之间的同步。智能体会点按、长按、滑动和输入,离开应用再回来,重启应用检查保存了什么,或者打开深层链接直接进入这个功能;brief 还可以提高默认约 30 步操作的预算。[AnkiDroid 的 brief](briefs/ankidroid.md) 就发现新卡片的背面输入框被键盘挡住了。
+- **在每台手机上复现一个缺陷报告**:给出一个 issue 或复现步骤,每个智能体回答“是 / 否 / 不确定”,并附上截图([briefs/reproduce.md](briefs/reproduce.md))。
+- **生成改进报告。** 每个角色把应用用一遍,然后说出在哪里犹豫、原本期待什么、最该先改什么,并标出领域和影响([briefs/improve.md](briefs/improve.md))。
+- **对比两个版本。** 同一批角色分别使用两个分支或构建,最后得到一张表:目标是否达成、操作次数、评分、只在一个版本出现的问题([docs/compare-versions.md](docs/compare-versions.md))。适合在真正的 A/B 测试之前做检查,但不能代替 A/B 测试。
+- **使用更便宜的模型**:Claude Haiku,或任何兼容 Anthropic 接口的 API(OpenRouter、DeepSeek、Kimi、GLM、MiniMax、通义千问)。发现的质量取决于模型读截图的能力和推理能力([docs/cheaper-models.md](docs/cheaper-models.md))。
+
+## 应用实例
+
+在开源应用上的真实运行,没有预先埋入任何缺陷。
+
+### 不只是无障碍
大字号的截图最醒目,但这只是智能体报告内容的一小部分。每个角色都有自己的目标(“不靠英语完成一项任务”“在每个输入框里填土耳其语字符、表情符号和超长文本”“用到一半离开应用,再回来”),像新用户一样去完成,所以一路上挡路的问题都会被报告出来:
@@ -38,11 +53,6 @@
- **数据**:重新打开后什么都没保存(演示应用)。
在 LocalSend 上,46 个缺陷中有 34 个与字号和无障碍都无关。每份报告最后还有角色自己的看法和 10 分制评分(会不会继续用这个应用?),所以一次运行不仅告诉你哪里坏了,也告诉你新用户在哪里卡住。
-### 复杂功能也能测
-
-默认的 brief 让智能体像新用户一样自由探索。你也可以写自己的 brief,让每个智能体一步步走完一整套机制:[AnkiDroid 的 brief](briefs/ankidroid.md) 让 10 个智能体都去创建卡组、添加三张卡片、学习一遍,再改一项设置,其中两个发现新卡片的背面输入框被键盘挡住了。把它们派去测你最难的功能吧:分好几步的预订、带撤销的编辑器、两个页面之间的同步、益智游戏。智能体可以点按、长按、滑动、输入,离开应用再回来,重启应用检查数据有没有保存,或者打开深层链接直接进入某个功能。brief 还可以提高默认每个智能体约 30 步操作的预算。
-
-## 真实发现
### LocalSend:20 个智能体,20 台设备,14 种语言
@@ -140,8 +150,9 @@ gh workflow run agent-testers.yml -f source_repo=you/app -f app_id=com.you.app \
| `source_repo`, `ref` | 应用仓库和分支(留空 = 本仓库)。私有仓库:添加一个只读的 `SOURCE_REPO_TOKEN` secret |
| `app_dir`, `app_id` | 应用目录,Android 包名 / iOS bundle id(如果另一个平台用的是别的 id,会从它的构建产物中读取) |
| `android_personas`, `ios_personas` | [personas.json](personas.json) 中的 id,每个角色一台手机;`all` 表示全部,`none` 表示跳过该平台。内置 20 个角色:14 种语言、从右到左、平板、从小号到最大辅助功能字号 |
-| `brief` | 给智能体的说明([AGENT_BRIEF.md](AGENT_BRIEF.md)) |
+| `brief` | 给智能体的说明:[AGENT_BRIEF.md](AGENT_BRIEF.md) 用于探索,[briefs/improve.md](briefs/improve.md) 用于改进报告,也可以用你自己写的来测某个功能 |
| `bug_report` | 要复现的缺陷,而不是自由探索:一个 issue(`owner/repo#123` 或它的链接),或者直接写步骤。每个智能体在自己的设备上照着做([briefs/reproduce.md](briefs/reproduce.md)) |
+| `model`、`llm_base_url` | 默认 `sonnet`,想省钱用 `haiku`,也可以用任何兼容 Anthropic 接口的 API,密钥放在 `LLM_API_KEY` secret 里([docs/cheaper-models.md](docs/cheaper-models.md)) |
| `framework` | `auto`(默认),或强制使用下表中的某个框架 |
| `android_build` + `apk_path`, `ios_build` + `ios_app_path` | 你自己的构建命令,或下载一个预构建的应用(路径相对于 `app_dir`) |
| `block_hosts` | 测试期间屏蔽的统计分析域名 |
@@ -187,7 +198,7 @@ gh workflow run agent-testers.yml -f source_repo=you/app -f app_id=com.you.app \
### 要花多少钱?
-公开仓库的 GitHub runner 免费,包括 macOS。在[这些运行](docs/runs/)中,每个智能体的模型用量为 0.15 到 0.55 美元,20 台手机大约 5 美元。如果使用 Claude 订阅,运行会计入你套餐的用量,不会另外收费。
+公开仓库的 GitHub runner 免费,包括 macOS。在[这些运行](docs/runs/)中,每个智能体的模型用量为 0.15 到 0.55 美元,20 台手机大约 5 美元。如果使用 Claude 订阅,运行会计入你套餐的用量,不会另外收费。想省钱,可以用 `model=haiku` 或其他服务商的模型:见 [docs/cheaper-models.md](docs/cheaper-models.md)。
### 一次运行要多久?
diff --git a/briefs/improve.md b/briefs/improve.md
new file mode 100644
index 0000000..147c681
--- /dev/null
+++ b/briefs/improve.md
@@ -0,0 +1,29 @@
+# Brief: improvement report from one walkthrough
+
+Read AGENT_BRIEF.md first: its tools, rules and final report files all apply.
+Only the mission changes. You are not hunting bugs first: you use the app once,
+the way your persona would, to reach your persona's `goal` (personas.json), and
+then you tell the team what would make the app better for people like you. Bugs
+you meet on the way still go in `issues`, as usual.
+
+1. Start like a new user: no guide and no help page, unless your persona would
+ open one. Screenshot after every action, as usual.
+2. While you go, note in `report.md` the moments that matter, with the screenshot
+ numbers: where you hesitated, what you expected and did not find, what you
+ misunderstood, what made you want to leave, and what you liked.
+3. When you reach the goal, or give up as your persona would, answer as the
+ persona: did you reach it (`yes`, `partly`, `no`), how many actions did it take,
+ would you keep the app, and your score out of 10.
+4. Then think as a tester again and write at most 7 improvements, the most useful
+ first. Each one says what to change, why (what happened to you, with screenshot
+ numbers), on which screen, its area, and how much it would help a new user like
+ you: `high`, `medium` or `low`. Base every improvement on something you saw on
+ this device. No wish lists, and no features your persona would never use.
+
+Areas: onboarding, navigation, copy, layout, feedback, trust, performance,
+feature, accessibility, translation.
+
+In `findings.json`, add these fields next to `score` and `issues`:
+`"goal_reached": "partly"`, `"actions": 23` and
+`"improvements": [{"title": "Say why the app needs access to all files", "area": "onboarding", "impact": "high", "screen": "Permissions", "screens": ["04", "05"], "why": "A system page opened with no explanation and I almost gave up"}]`.
+Start `report.md` with `Goal reached: yes` (or `partly`, `no`) and `Score: N/10`.
diff --git a/docs/cheaper-models.md b/docs/cheaper-models.md
new file mode 100644
index 0000000..eaa0f3d
--- /dev/null
+++ b/docs/cheaper-models.md
@@ -0,0 +1,49 @@
+# Cheaper models
+
+Each agent drives a phone by looking at screenshots and deciding what to do next, for about 30 actions. Two abilities of the model decide what a run is worth:
+
+- **Reading images.** Every screenshot reaches the model as an image. A model that reads them poorly misses cut text, hidden buttons and untranslated labels, or reports ones that aren't there. A model with no image input gets a text placeholder instead of the screen: the agent is blind and the run is worthless.
+- **Reasoning.** The agent has to plan, notice that a tap did nothing, try another way, and tell a bug in the app from a quirk of the emulator. A weaker model gives up sooner, repeats itself and reports more false positives.
+
+So a cheaper model is a trade: more phones or more runs for the same money, and fewer, less reliable findings per phone. Open the screenshots before you file anything.
+
+## 1. Claude Haiku: same setup, smaller bill
+
+Run with `-f model=haiku`. Nothing else changes: same tools, same screenshots, same secrets (Claude subscription or API key).
+
+At API list prices (November 2026), Claude Haiku costs $0.10 per million input tokens and $0.50 per million output tokens for requests up to 100K tokens, and $0.50 / $2.50 beyond, against $2 / $10 for Claude Sonnet, the default. An agent sends its history again with every action, so long sessions go past 100K tokens: expect 4 to 20 times less than Sonnet, depending on the length of the session. On a subscription, Haiku uses less of your plan's limits.
+
+Good for many phones on an app you already know, a quick check before a release, or a second reproduction pass. Keep Sonnet or Opus for a first look at an app, for complex features and for anything you will file.
+
+## 2. Any Anthropic-compatible API
+
+Claude Code can talk to any API that speaks Anthropic's Messages format. Several providers offer one, often for less, and some are easier to pay for in China.
+
+1. Create a key with the provider and add it as the `LLM_API_KEY` secret: `gh secret set LLM_API_KEY`.
+2. Run with `-f llm_base_url=<base URL> -f model=<the provider's model name>`. Start with one persona:
+
+```bash
+gh workflow run agent-testers.yml -f llm_base_url=https://openrouter.ai/api -f model=<a model with image input> \
+ -f android_personas=anna -f ios_personas=none
+```
+
+| Provider | `llm_base_url` | Image input |
+|---|---|---|
+| OpenRouter | `https://openrouter.ai/api` | One key for hundreds of models (Gemini, Qwen, GLM, Kimi...): pick one that takes images |
+| DeepSeek | `https://api.deepseek.com/anthropic` | Depends on the model: some replace images with a text placeholder |
+| Moonshot (Kimi) | `https://api.moonshot.ai/anthropic` | Check the model you pick |
+| Z.ai (GLM) | `https://api.z.ai/api/anthropic` | Check the model you pick |
+| MiniMax | `https://api.minimax.io/anthropic` | Some models only |
+| Alibaba Cloud (Qwen) | `https://dashscope-intl.aliyuncs.com/apps/anthropic` | Check the model you pick |
+
+Model names, prices and image support change often, and mainland China has its own endpoints: check the provider's documentation before a run.
+
+With `llm_base_url` set, [scripts/llm_env.sh](../scripts/llm_env.sh) sends every request of the agent to that URL with your key, uses your model for Claude Code's small background requests too, and leaves your Claude secrets out of that run. The key never appears in the logs.
+
+Then open that persona's screenshots and report. Did it see the screen? Did it get past the onboarding? Are the findings real? Claude Code is built and tested with Claude models, and OpenRouter's own guide warns that other models may not work as well: one may stop early, loop, or fail a tool call. That is a limit of the model, not of your setup.
+
+## 3. Spend less with any model
+
+- Fewer phones: pick the devices that matter to you (`-f android_personas=anna,malik`).
+- Shorter sessions: your brief can lower the budget of about 30 actions.
+- The summary groups duplicates with your local `claude` CLI: `SUMMARY_MODEL=haiku bash scripts/collect.sh <run id>` makes that cheaper too, and `SUMMARY_GROUPING=0` skips it.
diff --git a/docs/compare-versions.md b/docs/compare-versions.md
new file mode 100644
index 0000000..e845c4a
--- /dev/null
+++ b/docs/compare-versions.md
@@ -0,0 +1,31 @@
+# Compare two versions
+
+Run the same personas on two versions of your app, then put the two runs side by side.
+
+1. Version A, for example your main branch:
+ ```bash
+ gh workflow run agent-testers.yml -f source_repo=you/app -f app_id=com.you.app -f ref=main \
+ -f brief=briefs/improve.md -f android_personas=all -f ios_personas=all
+ ```
+2. Version B: the same command with `-f ref=new-onboarding` (another branch, tag or commit), or another prebuilt app with `android_build` and `ios_build`.
+3. Collect both runs and compare them:
+ ```bash
+ bash scripts/collect.sh <run A>
+ bash scripts/collect.sh <run B>
+ python3 scripts/compare.py runs/<run A> runs/<run B> main new-onboarding > COMPARE.md
+ ```
+
+`COMPARE.md` shows, for each version, the goals reached (yes / partly / no), the median number of actions, the average score and the issues by severity. Then each persona on both versions, the issues seen on one version only, and the improvements the personas suggested, by area.
+
+## What it tells you, and what it doesn't
+
+It shows where each version blocks or confuses simulated new users: a step nobody gets through, a screen that takes twice the actions, a sentence that most personas misread, a regression on one device. That is worth knowing before real users see a version.
+
+It does not tell you which version will convert or retain better. The personas are patient, read everything, never pay, and come from the same model, so their opinions move together. With ten personas, a gap of one or two either way is noise. Use it to fix each version before a real A/B test, not to pick the winner.
+
+## Tips
+
+- Change only the app: same personas, same brief and same model on both runs.
+- [briefs/improve.md](../briefs/improve.md) gives every persona a goal and asks how many actions it took, which is what the comparison needs. Your own brief works too if it writes the same fields (`goal_reached`, `actions`, `score`).
+- Both versions in one build, behind a flag? Write two briefs that each open their variant first (a deep link, a debug menu), and run each version with its brief.
+- Each run explores in its own way. When a difference matters, run each version twice and keep what repeats.
diff --git a/scripts/android/run_agent.sh b/scripts/android/run_agent.sh
index 8e93dde..9dbea83 100755
--- a/scripts/android/run_agent.sh
+++ b/scripts/android/run_agent.sh
@@ -45,7 +45,8 @@ if [ "${RECORD_VIDEO:-false}" = true ]; then
done ) &
REC=$!
fi
-# 5. The agent: only the listed tools, nothing else
+# 5. The agent: only the listed tools, nothing else (another model API if llm_base_url is set)
+source scripts/llm_env.sh || exit 1
claude -p "Read $BRIEF and personas.json, then do the mission until the final report. PERSONA=$PERSONA PLATFORM=android APP_ID=$APP_ID. Device: ${DEVICE}, font scale x${FONT_SCALE:-1.0}, theme ${THEME:-light}, language $LOCALE. Report anything that does not fit this screen (cut text, off-screen buttons, broken layout)." \
--model "${MODEL:-sonnet}" --max-turns 400 --output-format json \
--allowedTools "Bash(adb:*),Bash(python3 scripts/android/screen.py:*),Bash(python3 scripts/android/type.py:*),Bash(sleep:*),Bash(ls:*),Bash(cat:*),Bash(mkdir:*),Read,Write,Edit" \
diff --git a/scripts/compare.py b/scripts/compare.py
new file mode 100644
index 0000000..bee0123
--- /dev/null
+++ b/scripts/compare.py
@@ -0,0 +1,132 @@
+"""Compares two collected runs of the same personas on two versions of an app
+(two branches, two builds, a flag): goal reached, actions, score and issues of
+each version, persona by persona, the issues seen on one version only and the
+improvements by area. Works with any brief; briefs/improve.md gives the goal
+and action counts.
+
+Simulated users show what blocks or confuses them on each version. They do not
+predict which version converts better: confirm with real users before deciding.
+Usage: python3 scripts/compare.py <run_dir_A> <run_dir_B> [name_A name_B]"""
+import sys
+from collections import defaultdict
+from statistics import median
+
+from summarize import AREAS, GOALS, ORDER, cell, number, per_persona, personas_by_id, phone
+
+SEVERITIES = ("blocker", "major", "minor", "cosmetic")
+
+
+def load(run_dir):
+ """persona -> score, goal reached, actions, issues and improvement areas of one run."""
+ run = {}
+ for persona, data in per_persona(run_dir):
+ goal = str(data.get("goal_reached") or "").strip().lower()
+ issues = [{"severity": str(i.get("severity") or "?").strip().lower(),
+ "title": str(i.get("title") or "?").strip()}
+ for i in data.get("issues") or [] if isinstance(i, dict)]
+ areas = [str(i.get("area") or "").strip().lower()
+ for i in data.get("improvements") or [] if isinstance(i, dict) and i.get("title")]
+ run[persona] = {"score": number(data.get("score")), "actions": number(data.get("actions")),
+ "goal": goal if goal in GOALS else "", "issues": issues,
+ "areas": [a if a in AREAS else "other" for a in areas]}
+ return run
+
+
+def fmt(x):
+ return "" if x is None else f"{x:g}"
+
+
+def overview(run):
+ ps = list(run.values())
+ goals = [p["goal"] for p in ps if p["goal"]]
+ actions = [p["actions"] for p in ps if p["actions"] is not None]
+ scores = [p["score"] for p in ps if p["score"] is not None]
+ sev = defaultdict(int)
+ for p in ps:
+ for i in p["issues"]:
+ sev[i["severity"]] += 1
+ return [str(len(ps)),
+ " / ".join(str(goals.count(g)) for g in GOALS) if goals else "",
+ fmt(median(actions)) if actions else "",
+ f"{sum(scores) / len(scores):.1f}/10" if scores else "",
+ " / ".join(str(sev[s]) for s in SEVERITIES)]
+
+
+def only_in(run, other):
+ """Issues whose title (case aside) never appears in the other run, most severe first."""
+ seen = {i["title"].lower() for p in other.values() for i in p["issues"]}
+ found = {}
+ for persona, p in run.items():
+ for i in p["issues"]:
+ if i["title"].lower() not in seen:
+ f = found.setdefault(i["title"].lower(), {"title": i["title"], "sev": i["severity"], "personas": set()})
+ f["personas"].add(persona)
+ if ORDER.get(i["severity"], 9) < ORDER.get(f["sev"], 9):
+ f["sev"] = i["severity"]
+ return sorted(found.values(), key=lambda f: (ORDER.get(f["sev"], 9), -len(f["personas"]), f["title"].lower()))
+
+
+def render(a, b, names=("A", "B"), dirs=("", "")):
+ na, nb = names
+ both, alone = sorted(set(a) & set(b)), sorted(set(a) ^ set(b))
+ lines = [f"# {na} vs {nb}", "",
+ f"The same personas on two versions of the app ({na}: {dirs[0]}, {nb}: {dirs[1]}). "
+ f"{len(both)} personas ran both."]
+ if alone:
+ lines.append(f"Only on one version, so not in the persona table: {', '.join(alone)}.")
+ lines += ["Simulated users show what blocks or confuses them on each version. They do not predict "
+ "which version converts better: confirm with real users before you decide.", "",
+ f"| | {na} | {nb} |", "|---|---|---|"]
+ labels = ["Personas", "Goal reached (yes / partly / no)", "Median actions", "Average score",
+ "Issues (blocker / major / minor / cosmetic)"]
+ for label, x, y in zip(labels, overview(a), overview(b)):
+ lines.append(f"| {label} | {x} | {y} |")
+
+ personas = personas_by_id()
+ lines += ["", "## Persona by persona", "",
+ f"| Persona | Device | Language | Goal {na} | Goal {nb} | Actions {na} | Actions {nb} "
+ f"| Score {na} | Score {nb} | Issues {na} | Issues {nb} |", "|---|---|---|---|---|---|---|---|---|---|---|"]
+ up = down = same = 0
+ for p in both:
+ x, y = a[p], b[p]
+ device, locale, _ = phone(personas.get(p))
+ lines.append(f"| {p} | {cell(device)} | {locale} | {x['goal']} | {y['goal']} | {fmt(x['actions'])} "
+ f"| {fmt(y['actions'])} | {fmt(x['score'])} | {fmt(y['score'])} | {len(x['issues'])} "
+ f"| {len(y['issues'])} |")
+ if x["score"] is not None and y["score"] is not None:
+ up, down, same = up + (y["score"] > x["score"]), down + (y["score"] < x["score"]), same + (y["score"] == x["score"])
+ if up + down + same:
+ lines += ["", f"{nb} scored higher than {na} for {up} of {up + down + same} personas, lower for {down}, "
+ f"the same for {same}. With ten personas, a gap of one or two is noise."]
+
+ for name, run, other in ((na, a, b), (nb, b, a)):
+ found = only_in(run, other)
+ lines += ["", f"## Issues seen only on {name}", ""]
+ if not found:
+ lines.append("None.")
+ lines += [f"- {f['sev']}: {cell(f['title'])} ({', '.join(sorted(f['personas']))})" for f in found[:20]]
+ if len(found) > 20:
+ lines.append(f"- and {len(found) - 20} more")
+ lines += ["", "The same bug described in other words appears on both lists: read them side by side."]
+
+ areas = {name: defaultdict(int) for name in names}
+ for name, run in zip(names, (a, b)):
+ for p in run.values():
+ for area in p["areas"]:
+ areas[name][area] += 1
+ if any(areas[n] for n in names):
+ lines += ["", "## Improvements suggested, by area", "", f"| Area | {na} | {nb} |", "|---|---|---|"]
+ for area in sorted(set(areas[na]) | set(areas[nb]), key=lambda k: (-(areas[na][k] + areas[nb][k]), k)):
+ lines.append(f"| {area} | {areas[na][area]} | {areas[nb][area]} |")
+ return "\n".join(lines) + "\n"
+
+
+def main():
+ if len(sys.argv) not in (3, 5):
+ sys.exit(__doc__)
+ names = tuple(sys.argv[3:5]) or ("A", "B")
+ print(render(load(sys.argv[1]), load(sys.argv[2]), names, tuple(sys.argv[1:3])), end="")
+
+
+if __name__ == "__main__":
+ main()
diff --git a/scripts/ios/run_agent.sh b/scripts/ios/run_agent.sh
index c6b3d9c..d4f142b 100755
--- a/scripts/ios/run_agent.sh
+++ b/scripts/ios/run_agent.sh
@@ -28,6 +28,8 @@ if [ "${RECORD_VIDEO:-false}" = true ]; then
xcrun simctl io "$UDID" recordVideo --codec=h264 --force "results/$PERSONA/video/rec_01.mp4" > "$RUNNER_TEMP/rec.log" 2>&1 &
REC=$!; set +m; sleep 2
fi
+# The agent (another model API if llm_base_url is set)
+source scripts/llm_env.sh || exit 1
claude -p "Read $BRIEF and personas.json, then do the mission until the final report. PERSONA=$PERSONA PLATFORM=ios APP_ID=$APP_ID. Device: $DEVICE, text size ${TEXT_SIZE:-large}, theme ${THEME:-light}, language $LOCALE. The simulator is already booted and the tools find it on their own (UDID is set): use the commands of the brief directly. Report anything that does not fit this screen (cut text, off-screen buttons, under the notch or home bar, broken layout)." \
--model "${MODEL:-sonnet}" --max-turns 400 --output-format json \
--allowedTools "Bash(bash scripts/ios/gesture.sh:*),Bash(python3 scripts/ios/screen.py:*),Bash(python3 scripts/ios/type.py:*),Bash(sleep:*),Bash(ls:*),Bash(cat:*),Bash(mkdir:*),Read,Write,Edit" \
diff --git a/scripts/llm_env.sh b/scripts/llm_env.sh
new file mode 100644
index 0000000..31a678e
--- /dev/null
+++ b/scripts/llm_env.sh
@@ -0,0 +1,29 @@
+# shellcheck shell=bash
+# Sourced by scripts/*/run_agent.sh. When the llm_base_url input is set, Claude
+# Code talks to that Anthropic-compatible API (OpenRouter, DeepSeek, Kimi, GLM,
+# MiniMax, Qwen...) with the LLM_API_KEY secret instead of Claude, and MODEL is
+# the provider's model name. Nothing changes when LLM_BASE_URL is empty.
+# Results depend on how well that model reads screenshots and reasons:
+# see docs/cheaper-models.md.
+if [ -n "${LLM_BASE_URL:-}" ]; then
+ if [ -z "${LLM_API_KEY:-}" ]; then
+ echo "llm_base_url is set, but the LLM_API_KEY secret is empty" >&2
+ return 1
+ fi
+ case "${MODEL:-}" in
+ "" | sonnet | opus | haiku | default)
+ echo "llm_base_url is set: put the provider's model name in the model input, not '${MODEL:-}'" >&2
+ return 1 ;;
+ esac
+ export ANTHROPIC_BASE_URL="${LLM_BASE_URL%/}" ANTHROPIC_AUTH_TOKEN="$LLM_API_KEY" ANTHROPIC_API_KEY=""
+ unset CLAUDE_CODE_OAUTH_TOKEN
+ # Claude Code also sends small background requests (titles, summaries) to its
+ # "haiku" slot: the provider only knows MODEL, so every slot uses it
+ for v in ANTHROPIC_MODEL ANTHROPIC_DEFAULT_OPUS_MODEL ANTHROPIC_DEFAULT_SONNET_MODEL \
+ ANTHROPIC_DEFAULT_HAIKU_MODEL CLAUDE_CODE_SUBAGENT_MODEL; do
+ export "$v=$MODEL"
+ done
+ export CLAUDE_CODE_DISABLE_NONESSENTIAL_TRAFFIC=1 API_TIMEOUT_MS="${API_TIMEOUT_MS:-600000}"
+ llm_host=${LLM_BASE_URL#*://}; llm_host=${llm_host%%/*}
+ echo "Model $MODEL through ${llm_host##*@}"
+fi
diff --git a/scripts/summarize.py b/scripts/summarize.py
index 86a55fa..4ff34df 100644
--- a/scripts/summarize.py
+++ b/scripts/summarize.py
@@ -7,13 +7,20 @@ testers). Only the report titles, screens and severities are sent. Without the
CLI, or with SUMMARY_GROUPING=0, only identical titles are merged.
A reproduction run (bug_report input, briefs/reproduce.md) starts with a table:
which devices reproduced the reported bug, which did not, and the evidence.
+An improvement run (briefs/improve.md) adds a walkthrough table (goal reached,
+actions and score of each persona) and the improvements by area and impact.
Usage: python3 scripts/summarize.py <collected_run_dir>"""
import json, os, re, shutil, subprocess, sys
from collections import defaultdict
from pathlib import Path
+from statistics import median
ORDER = {"blocker": 0, "major": 1, "minor": 2, "cosmetic": 3}
RESULTS = ("yes", "unclear", "no") # answers of briefs/reproduce.md, in table order
+GOALS = ("yes", "partly", "no") # goal_reached of briefs/improve.md
+IMPACTS = ("high", "medium", "low")
+AREAS = ("onboarding", "navigation", "copy", "layout", "feedback", "trust", "performance",
+ "feature", "accessibility", "translation")
CLASSES = ["layout and text size", "feedback and errors", "accessibility", "translation",
"right to left", "tablet", "system bars", "copy", "visual polish", "crash",
"likely test artefact"]
@@ -33,17 +40,30 @@ Reports (id. [persona, severity, screen] title):
"""
-def load(run_dir):
- findings, scores = [], []
+def per_persona(run_dir):
+ """(persona, content of its findings.json) for each persona of a collected run."""
for f in sorted(Path(run_dir).glob("*/results/*/findings.json")):
try:
data = json.loads(f.read_text(encoding="utf-8"))
except (OSError, ValueError):
continue
- if isinstance(data.get("score"), (int, float)):
+ if isinstance(data, dict):
+ yield f.parent.name, data
+
+
+def number(x):
+ return x if isinstance(x, (int, float)) and not isinstance(x, bool) else None
+
+
+def load(run_dir):
+ findings, scores = [], []
+ for persona, data in per_persona(run_dir):
+ if number(data.get("score")) is not None:
scores.append(data["score"])
- for i in data.get("issues", []):
- findings.append({"id": len(findings) + 1, "persona": f.parent.name,
+ for i in data.get("issues") or []:
+ if not isinstance(i, dict):
+ continue
+ findings.append({"id": len(findings) + 1, "persona": persona,
"severity": i.get("severity") or "?",
"title": (i.get("title") or "?").strip(),
"screen": (i.get("screen") or "").strip()})
@@ -53,15 +73,11 @@ def load(run_dir):
def load_reproduction(run_dir):
"""One row per persona that answered `reproduced`, and the title of the bug report."""
rows, title = [], ""
- for f in sorted(Path(run_dir).glob("*/results/*/findings.json")):
- try:
- data = json.loads(f.read_text(encoding="utf-8"))
- except (OSError, ValueError):
- continue
+ for persona, data in per_persona(run_dir):
answer = str(data.get("reproduced") or "").strip().lower()
if answer:
evidence = data.get("evidence") if isinstance(data.get("evidence"), list) else []
- rows.append({"persona": f.parent.name, "result": answer if answer in RESULTS else "unclear",
+ rows.append({"persona": persona, "result": answer if answer in RESULTS else "unclear",
"evidence": [str(e) for e in evidence], "note": str(data.get("note") or "").strip()})
for b in sorted(Path(run_dir).glob("*/results/bug_report.md")):
lines = b.read_text(encoding="utf-8", errors="replace").strip().splitlines()
@@ -70,6 +86,27 @@ def load_reproduction(run_dir):
return rows, title
+def load_walkthrough(run_dir):
+ """Goal reached, actions, score and improvements of each persona that followed briefs/improve.md."""
+ rows = []
+ for persona, data in per_persona(run_dir):
+ goal = str(data.get("goal_reached") or "").strip().lower()
+ ideas = []
+ for i in data.get("improvements") or []:
+ if not isinstance(i, dict) or not str(i.get("title") or "").strip():
+ continue
+ area, impact = (str(i.get(k) or "").strip().lower() for k in ("area", "impact"))
+ screens = i.get("screens") if isinstance(i.get("screens"), list) else []
+ ideas.append({"title": str(i["title"]).strip(), "area": area if area in AREAS else "other",
+ "impact": impact if impact in IMPACTS else "?", "why": str(i.get("why") or "").strip(),
+ "screen": str(i.get("screen") or "").strip(), "screens": [str(x) for x in screens]})
+ if goal or ideas:
+ rows.append({"persona": persona, "goal": goal if goal in GOALS else ("?" if goal else ""),
+ "actions": number(data.get("actions")), "score": number(data.get("score")),
+ "ideas": ideas})
+ return rows
+
+
def personas_by_id():
try:
data = json.loads((Path(__file__).resolve().parent.parent / "personas.json").read_text(encoding="utf-8"))
@@ -102,6 +139,47 @@ def render_reproduction(rows, title):
return lines + [""]
+def num(x):
+ return "" if x is None else f"{x:g}"
+
+
+def render_walkthrough(rows):
+ personas, n = personas_by_id(), {g: sum(r["goal"] == g for r in rows) for g in GOALS}
+ head, actions = [], [r["actions"] for r in rows if r["actions"] is not None]
+ if any(r["goal"] for r in rows):
+ head.append(f"Goal reached: yes for {n['yes']}, partly for {n['partly']}, no for {n['no']} "
+ f"of {len(rows)} personas.")
+ if actions:
+ head.append(f"Median: {median(actions):g} actions.")
+ lines = ["## Walkthrough", "", " ".join(head), "",
+ "| Persona | Device | Language | Text size | Goal reached | Actions | Score |",
+ "|---|---|---|---|---|---|---|"]
+ for r in sorted(rows, key=lambda x: (GOALS.index(x["goal"]) if x["goal"] in GOALS else 3, x["persona"])):
+ device, locale, size = phone(personas.get(r["persona"]))
+ lines.append(f"| {r['persona']} | {cell(device)} | {locale} | {size} | {r['goal'] or '?'} "
+ f"| {num(r['actions'])} | {num(r['score'])} |")
+ ideas = [dict(i, persona=r["persona"]) for r in rows for i in r["ideas"]]
+ if not ideas:
+ return lines + [""]
+ areas = defaultdict(lambda: [0, set()])
+ for i in ideas:
+ areas[i["area"]][0] += 1
+ areas[i["area"]][1].add(i["persona"])
+ ranked = sorted(areas, key=lambda a: (-len(areas[a][1]), -areas[a][0], a))
+ lines += ["", "## Improvements", "",
+ f"{len(ideas)} suggestions from {len({i['persona'] for i in ideas})} personas. The same idea often "
+ "comes back in other words: read each area together, and open the screenshots.", "",
+ "| Area | Suggestions | Personas |", "|---|---|---|"]
+ lines += [f"| {a} | {areas[a][0]} | {len(areas[a][1])} ({', '.join(sorted(areas[a][1]))}) |" for a in ranked]
+ lines += ["", "| Impact | Area | Improvement | Persona | Screen | Why |", "|---|---|---|---|---|---|"]
+ for i in sorted(ideas, key=lambda i: (IMPACTS.index(i["impact"]) if i["impact"] in IMPACTS else 3,
+ ranked.index(i["area"]), i["persona"])):
+ where = i["screen"] + (f" ({', '.join(i['screens'])})" if i["screens"] else "")
+ lines.append(f"| {i['impact']} | {i['area']} | {cell(i['title'])} | {i['persona']} | {cell(where.strip())} "
+ f"| {cell(i['why'])} |")
+ return lines + [""]
+
+
def group_by_title(findings):
groups = {}
for f in findings:
@@ -154,7 +232,7 @@ def cell(s):
return str(s).replace("|", "\\|").replace("\n", " ")
-def render(findings, scores, groups, by_claude, repro=None):
+def render(findings, scores, groups, by_claude, repro=None, walk=None):
by_id = {f["id"]: f for f in findings}
rows = []
for g in groups:
@@ -165,11 +243,15 @@ def render(findings, scores, groups, by_claude, repro=None):
"screens": sorted({f["screen"] for f in fs if f["screen"]})})
rows.sort(key=lambda r: (ORDER.get(r["sev"], 9), -len(r["personas"]), r["title"].lower()))
personas = sorted({f["persona"] for f in findings})
- lines = ["# Agent test summary", ""]
- if repro and repro[0]:
- lines += render_reproduction(*repro) + ["## Everything else the agents reported", ""]
+ lines, reproduced = ["# Agent test summary", ""], bool(repro and repro[0])
+ if reproduced:
+ lines += render_reproduction(*repro)
+ if walk:
+ lines += render_walkthrough(walk)
+ if reproduced or walk:
+ lines += ["## Everything else the agents reported" if reproduced else "## Issues", ""]
if not findings:
- return "\n".join(lines + ["Nothing else."]) + "\n"
+ return "\n".join(lines + ["Nothing else." if reproduced else "No issues reported."]) + "\n"
head = f"{len(findings)} reports from {len(personas)} personas"
if scores:
head += f", average score {sum(scores) / len(scores):.1f}/10"
@@ -210,7 +292,7 @@ def main():
findings, scores = load(sys.argv[1])
groups = group_with_claude(findings)
print(render(findings, scores, groups or group_by_title(findings), groups is not None,
- load_reproduction(sys.argv[1])), end="")
+ load_reproduction(sys.argv[1]), load_walkthrough(sys.argv[1])), end="")
if __name__ == "__main__":
diff --git a/tests/test_compare.py b/tests/test_compare.py
new file mode 100644
index 0000000..99881fb
--- /dev/null
+++ b/tests/test_compare.py
@@ -0,0 +1,89 @@
+"""scripts/compare.py: the same personas on two versions of an app."""
+import json
+import subprocess
+import sys
+import tempfile
+import unittest
+from pathlib import Path
+
+ROOT = Path(__file__).resolve().parent.parent
+sys.path.insert(0, str(ROOT / "scripts"))
+import compare # noqa: E402
+
+A = {
+ "anna": {"score": 5, "goal_reached": "no", "actions": 30, "issues": [
+ {"title": "Continue hidden by keyboard", "severity": "blocker"},
+ {"title": "Typo on home", "severity": "cosmetic"}],
+ "improvements": [{"title": "Shorter sign-up", "area": "onboarding"}]},
+ "noah": {"score": 7, "goal_reached": "yes", "actions": 14, "issues": [
+ {"title": "Typo on home", "severity": "cosmetic"}]},
+ "kenji": {"score": 6, "issues": []},
+}
+B = {
+ "anna": {"score": 7, "goal_reached": "yes", "actions": 18, "issues": [
+ {"title": "typo on home", "severity": "cosmetic"}, {"title": "Price unclear", "severity": "major"}],
+ "improvements": [{"title": "Show the price", "area": "Trust"}, {"title": "Odd one", "area": "weird"},
+ {"area": "copy"}]},
+ "noah": {"score": 7, "goal_reached": "partly", "actions": 20, "issues": []},
+ "olga": {"score": 9, "issues": []},
+}
+
+
+def write_run(base, findings):
+ for persona, data in findings.items():
+ d = Path(base, persona, "results", persona)
+ d.mkdir(parents=True)
+ (d / "findings.json").write_text(json.dumps(data), encoding="utf-8")
+
+
+class Compare(unittest.TestCase):
+ def setUp(self):
+ self.tmp = tempfile.TemporaryDirectory()
+ self.a, self.b = Path(self.tmp.name, "a"), Path(self.tmp.name, "b")
+ write_run(self.a, A)
+ write_run(self.b, B)
+ self.md = compare.render(compare.load(self.a), compare.load(self.b))
+
+ def tearDown(self):
+ self.tmp.cleanup()
+
+ def test_overview_table(self):
+ for row in ("| Personas | 3 | 3 |",
+ "| Goal reached (yes / partly / no) | 1 / 0 / 1 | 1 / 1 / 0 |",
+ "| Median actions | 22 | 19 |",
+ "| Average score | 6.0/10 | 7.7/10 |",
+ "| Issues (blocker / major / minor / cosmetic) | 1 / 0 / 0 / 2 | 0 / 1 / 0 / 1 |"):
+ self.assertIn(row, self.md)
+ self.assertIn("They do not predict which version converts better", self.md)
+
+ def test_personas_on_one_version_only_are_left_out_of_the_pairs(self):
+ self.assertIn("2 personas ran both.", self.md)
+ self.assertIn("Only on one version, so not in the persona table: kenji, olga.", self.md)
+ self.assertIn("B scored higher than A for 1 of 2 personas, lower for 0, the same for 1.", self.md)
+
+ def test_issues_seen_on_one_version_only(self):
+ only_a = self.md.split("## Issues seen only on A")[1].split("## Issues seen only on B")[0]
+ self.assertIn("- blocker: Continue hidden by keyboard (anna)", only_a)
+ self.assertNotIn("Typo", only_a) # same title on B, case aside
+ self.assertIn("- major: Price unclear (anna)", self.md.split("## Issues seen only on B")[1])
+
+ def test_improvements_by_area(self):
+ for row in ("| onboarding | 1 | 0 |", "| trust | 0 | 1 |", "| other | 0 | 1 |"):
+ self.assertIn(row, self.md)
+ self.assertNotIn("| copy |", self.md) # no title: not an improvement
+
+ def test_empty_runs(self):
+ md = compare.render({}, {})
+ self.assertIn("0 personas ran both.", md)
+ self.assertEqual(md.count("None."), 2)
+
+ def test_command_line_with_names(self):
+ out = subprocess.run([sys.executable, str(ROOT / "scripts/compare.py"), str(self.a), str(self.b),
+ "main", "new-onboarding"], capture_output=True, text=True)
+ self.assertEqual(out.returncode, 0, out.stderr)
+ self.assertTrue(out.stdout.startswith("# main vs new-onboarding\n"))
+ self.assertIn("| Score main | Score new-onboarding |", out.stdout)
+
+
+if __name__ == "__main__":
+ unittest.main()
diff --git a/tests/test_llm_env.py b/tests/test_llm_env.py
new file mode 100644
index 0000000..658950b
--- /dev/null
+++ b/tests/test_llm_env.py
@@ -0,0 +1,70 @@
+"""scripts/llm_env.sh: another Anthropic-compatible API instead of Claude (llm_base_url input)."""
+import os
+import subprocess
+import unittest
+from pathlib import Path
+
+ROOT = Path(__file__).resolve().parent.parent
+SHOWN = ("ANTHROPIC_BASE_URL", "ANTHROPIC_AUTH_TOKEN", "ANTHROPIC_API_KEY", "CLAUDE_CODE_OAUTH_TOKEN",
+ "ANTHROPIC_MODEL", "ANTHROPIC_DEFAULT_HAIKU_MODEL", "CLAUDE_CODE_SUBAGENT_MODEL",
+ "CLAUDE_CODE_DISABLE_NONESSENTIAL_TRAFFIC")
+
+
+def source(show=True, **env):
+ """Sources the helper like run_agent.sh does, then prints the variables it may change."""
+ clean = {k: v for k, v in os.environ.items()
+ if not k.startswith(("ANTHROPIC_", "CLAUDE_CODE_", "LLM_", "API_TIMEOUT")) and k != "MODEL"}
+ script = f'source "{ROOT / "scripts/llm_env.sh"}" || exit 3'
+ if show:
+ script += "".join(f'; echo "{v}=${{{v}-<unset>}}"' for v in SHOWN)
+ return subprocess.run(["bash", "-c", script], env={**clean, **env}, capture_output=True, text=True)
+
+
+def values(out):
+ return dict(line.split("=", 1) for line in out.stdout.splitlines() if "=" in line)
+
+
+class LlmEnv(unittest.TestCase):
+ def test_claude_stays_when_no_base_url(self):
+ out = source(CLAUDE_CODE_OAUTH_TOKEN="oauth", MODEL="sonnet")
+ self.assertEqual(out.returncode, 0, out.stderr)
+ v = values(out)
+ self.assertEqual(v["CLAUDE_CODE_OAUTH_TOKEN"], "oauth")
+ self.assertEqual(v["ANTHROPIC_BASE_URL"], "<unset>")
+ self.assertEqual(v["ANTHROPIC_MODEL"], "<unset>")
+
+ def test_provider_replaces_claude(self):
+ out = source(LLM_BASE_URL="https://api.deepseek.com/anthropic/", LLM_API_KEY="sk-provider",
+ MODEL="provider-model", CLAUDE_CODE_OAUTH_TOKEN="oauth", ANTHROPIC_API_KEY="sk-ant")
+ self.assertEqual(out.returncode, 0, out.stderr)
+ v = values(out)
+ self.assertEqual(v["ANTHROPIC_BASE_URL"], "https://api.deepseek.com/anthropic")
+ self.assertEqual(v["ANTHROPIC_AUTH_TOKEN"], "sk-provider")
+ self.assertEqual(v["ANTHROPIC_API_KEY"], "")
+ self.assertEqual(v["CLAUDE_CODE_OAUTH_TOKEN"], "<unset>")
+ for name in ("ANTHROPIC_MODEL", "ANTHROPIC_DEFAULT_HAIKU_MODEL", "CLAUDE_CODE_SUBAGENT_MODEL"):
+ self.assertEqual(v[name], "provider-model")
+ self.assertEqual(v["CLAUDE_CODE_DISABLE_NONESSENTIAL_TRAFFIC"], "1")
+
+ def test_log_shows_the_host_never_the_key(self):
+ out = source(show=False, LLM_BASE_URL="https://user:[email protected]/api", LLM_API_KEY="sk-provider",
+ MODEL="vendor/vision-model")
+ self.assertEqual(out.returncode, 0, out.stderr)
+ self.assertEqual(out.stdout.strip(), "Model vendor/vision-model through openrouter.ai")
+ self.assertNotIn("sk-provider", out.stdout + out.stderr)
+ self.assertNotIn("pw", out.stdout + out.stderr)
+
+ def test_missing_key_stops_the_agent(self):
+ out = source(LLM_BASE_URL="https://api.moonshot.ai/anthropic", MODEL="provider-model")
+ self.assertEqual(out.returncode, 3)
+ self.assertIn("LLM_API_KEY", out.stderr)
+
+ def test_claude_alias_sent_to_a_provider_stops_the_agent(self):
+ for model in ("sonnet", "haiku", ""):
+ out = source(LLM_BASE_URL="https://api.z.ai/api/anthropic", LLM_API_KEY="k", MODEL=model)
+ self.assertEqual(out.returncode, 3, model)
+ self.assertIn("model input", out.stderr)
+
+
+if __name__ == "__main__":
+ unittest.main()
diff --git a/tests/test_summarize.py b/tests/test_summarize.py
index a627f04..d32e5c4 100644
--- a/tests/test_summarize.py
+++ b/tests/test_summarize.py
@@ -158,5 +158,72 @@ class Reproduction(unittest.TestCase):
self.assertTrue(out.stdout.endswith("Nothing else.\n"))
+
+class Walkthrough(unittest.TestCase):
+ """briefs/improve.md: goal reached, actions, score and improvements of each persona."""
+ RUN = {
+ "anna": {"score": 5, "goal_reached": "Partly", "actions": 31, "issues": [], "improvements": [
+ {"title": "Say why the app needs all files", "area": "Onboarding", "impact": "high",
+ "screen": "Permissions", "screens": ["04", "05"], "why": "I almost | gave up"},
+ {"title": "Bigger Send button", "area": "layout", "impact": "low", "screen": "Send"}]},
+ "noah": {"score": 8, "goal_reached": "yes", "actions": 12, "issues": [
+ {"title": "Typo on home", "severity": "cosmetic", "screen": "Home"}], "improvements": [
+ {"title": "Skip the tour", "area": "onboarding", "impact": "medium"},
+ {"title": "", "area": "copy"}, "not a dict"]},
+ "kenji": {"score": 7, "issues": []}, # default brief: not part of the walkthrough
+ }
+
+ def setUp(self):
+ self.tmp = tempfile.TemporaryDirectory()
+ write_run(self.tmp.name, self.RUN)
+ self.rows = summarize.load_walkthrough(self.tmp.name)
+
+ def tearDown(self):
+ self.tmp.cleanup()
+
+ def test_rows(self):
+ by = {r["persona"]: r for r in self.rows}
+ self.assertEqual(sorted(by), ["anna", "noah"])
+ self.assertEqual((by["anna"]["goal"], by["anna"]["actions"], by["anna"]["score"]), ("partly", 31, 5))
+ self.assertEqual([i["title"] for i in by["noah"]["ideas"]], ["Skip the tour"])
+ self.assertEqual(by["anna"]["ideas"][0]["area"], "onboarding")
+
+ def test_walkthrough_and_improvements_come_before_the_issues(self):
+ findings, scores = summarize.load(self.tmp.name)
+ md = summarize.render(findings, scores, summarize.group_by_title(findings), False, ([], ""), self.rows)
+ self.assertTrue(md.startswith("# Agent test summary\n\n## Walkthrough\n"))
+ self.assertIn("Goal reached: yes for 1, partly for 1, no for 0 of 2 personas. Median: 21.5 actions.", md)
+ people = [line.split(" | ")[0][2:] for line in md.splitlines() if line.startswith(("| anna", "| noah"))]
+ self.assertEqual(people, ["noah", "anna"])
+ self.assertIn("3 suggestions from 2 personas.", md)
+ self.assertIn("| onboarding | 2 | 2 (anna, noah) |", md)
+ ideas = [line for line in md.splitlines() if line.startswith(("| high", "| medium", "| low"))]
+ self.assertEqual(ideas[0], "| high | onboarding | Say why the app needs all files | anna "
+ "| Permissions (04, 05) | I almost \\| gave up |")
+ self.assertEqual([i.split(" | ")[0] for i in ideas], ["| high", "| medium", "| low"])
+ self.assertLess(md.index("## Improvements"), md.index("## Issues"))
+ self.assertIn("| cosmetic | Typo on home | 1 (noah) | Home |", md)
+
+ def test_a_normal_run_is_unchanged(self):
+ with tempfile.TemporaryDirectory() as d:
+ write_run(d, FINDINGS)
+ rows = summarize.load_walkthrough(d)
+ findings, scores = summarize.load(d)
+ md = summarize.render(findings, scores, summarize.group_by_title(findings), False, ([], ""), rows)
+ self.assertEqual(rows, [])
+ self.assertNotIn("Walkthrough", md)
+ self.assertNotIn("## Issues", md)
+
+ def test_command_line_with_no_issues(self):
+ with tempfile.TemporaryDirectory() as d:
+ write_run(d, {"olga": {"score": 9, "goal_reached": "yes", "actions": 8, "issues": [],
+ "improvements": [{"title": "Dark mode", "area": "layout", "impact": "low"}]}})
+ out = subprocess.run([sys.executable, str(ROOT / "scripts/summarize.py"), d],
+ env=dict(os.environ, SUMMARY_GROUPING="0"), capture_output=True, text=True)
+ self.assertEqual(out.returncode, 0, out.stderr)
+ self.assertIn("| low | layout | Dark mode | olga |", out.stdout)
+ self.assertTrue(out.stdout.endswith("## Issues\n\nNo issues reported.\n"))
+
+
if __name__ == "__main__":
unittest.main()