Doubao-powered voice input for Linux, Wayland and Omarchy
fix(workflow): stack CI report previews vertically (#36)
Leyang3e49e45b9bae
diff --git a/.github/workflows/deploy-midscene-report.yml b/.github/workflows/deploy-midscene-report.ymlindex 07a24d8..0774916 100644--- a/.github/workflows/deploy-midscene-report.yml+++ b/.github/workflows/deploy-midscene-report.yml@@ -4,7 +4,7 @@ on:workflow_call:inputs:artifact-name:- description: Actions artifact containing one self-contained HTML report+ description: Actions artifact containing the Midscene HTML reports and previewsrequired: truetype: stringreport-label:@@ -19,8 +19,12 @@ on:description: Midscene Test project used for the main report and previewrequired: truetype: string+ auxiliary-project:+ description: Midscene Test project used for the second report and preview+ required: true+ type: stringauxiliary-report-label:- description: Label for the optional second project report+ description: Label for the second project reportrequired: truetype: stringrun-result:@@ -50,7 +54,7 @@ jobs:with:persist-credentials: false- - name: Download the successful run's HTML report artifact+ - name: Download the run's HTML report artifactuses: actions/download-artifact@3e5f45b2cfb9172054b4087a40e8e0b5a5461e7c # v8.0.1with:name: ${{ inputs.artifact-name }}@@ -62,10 +66,12 @@ jobs:- name: Restore history and prepare the Pages siteenv:- REPORT_RETENTION: ${{ vars.REPORT_RETENTION || '10' }}+ REPORT_RETENTION: ${{ vars.REPORT_RETENTION || '30' }}PAGES_BASE_URL: ${{ steps.pages.outputs.base_url }}REPORT_LABEL: ${{ inputs.report-label }}PRIMARY_PROJECT: ${{ inputs.primary-project }}+ AUXILIARY_PROJECT: ${{ inputs.auxiliary-project }}+ AUXILIARY_REPORT_LABEL: ${{ inputs.auxiliary-report-label }}run: |node scripts/build-pages-report.mjs \--report-dir "$RUNNER_TEMP/midscene-report" \@@ -76,7 +82,10 @@ jobs:--retention "$REPORT_RETENTION" \--pages-url "$PAGES_BASE_URL" \--label "$REPORT_LABEL" \- --primary-project "$PRIMARY_PROJECT"+ --primary-project "$PRIMARY_PROJECT" \+ --primary-report-label "Doubao Say" \+ --auxiliary-project "$AUXILIARY_PROJECT" \+ --auxiliary-report-label "$AUXILIARY_REPORT_LABEL"- name: Upload the restricted Pages payloaduses: actions/upload-pages-artifact@fc324d3547104276b827a68afc52ff2a11cc49c9 # v5.0.0@@ -87,84 +96,26 @@ jobs:id: deploymentuses: actions/deploy-pages@368f82528645a54fb793d4d04e342629a3f51346 # v5.0.1- - name: Verify the published HTML endpoints+ - name: Verify every published report endpointenv:- HISTORY_URL: ${{ steps.pages.outputs.base_url }}/- REPORT_URL: ${{ steps.pages.outputs.base_url }}/reports/${{ github.run_id }}/index.html+ PAGES_BASE_URL: ${{ steps.pages.outputs.base_url }}run: |- verify_html() {- local url="$1"- local headers- headers=$(mktemp)- for attempt in $(seq 1 12); do- if curl --fail --silent --show-error --location --head \- --connect-timeout 10 --max-time 20 \- --dump-header "$headers" --output /dev/null "$url" \- && grep -Eiq '^content-type:[[:space:]]*text/html([[:space:]]*;|[[:space:]]*$)' "$headers"; then- echo "Verified HTTP 200 text/html: $url"- return 0- fi- echo "Waiting for Pages propagation (${attempt}/12): $url"- sleep 5- done- echo "Pages endpoint did not return HTTP 200 text/html: $url" >&2- return 1- }-- verify_html "$HISTORY_URL"- verify_html "$REPORT_URL"+ node scripts/verify-pages-report.mjs \+ --manifest "$RUNNER_TEMP/pages-site/reports/manifest.json" \+ --pages-url "$PAGES_BASE_URL" \+ --run-id "$GITHUB_RUN_ID"- name: Add report links to the run summary+ if: always() && steps.deployment.outcome == 'success'env:- HISTORY_URL: ${{ steps.pages.outputs.base_url }}/- REPORT_URL: ${{ steps.pages.outputs.base_url }}/reports/${{ github.run_id }}/index.html- AUXILIARY_URL: ${{ steps.pages.outputs.base_url }}/reports/${{ github.run_id }}/auxiliary-report.html- REPORT_PREVIEW_URL: ${{ steps.pages.outputs.base_url }}/reports/${{ github.run_id }}/report-preview.png- AUXILIARY_PREVIEW_URL: ${{ steps.pages.outputs.base_url }}/reports/${{ github.run_id }}/auxiliary-report-preview.png+ PAGES_BASE_URL: ${{ steps.pages.outputs.base_url }}PRODUCER_RESULT: ${{ inputs.run-result }}- REPORT_LABEL: ${{ inputs.report-label }}SUMMARY_TITLE: ${{ inputs.summary-title }}- AUXILIARY_REPORT_LABEL: ${{ inputs.auxiliary-report-label }}run: |- SUCCESS_RATE=$(jq -r '.reports[0].successRate' "$RUNNER_TEMP/pages-site/reports/manifest.json")- TEST_COUNT=$(jq -r '.reports[0].testCount' "$RUNNER_TEMP/pages-site/reports/manifest.json")- if [[ "$PRODUCER_RESULT" == "success" && "$SUCCESS_RATE" == "100" ]]; then- TITLE="$SUMMARY_TITLE × Midscene · passed"- RESULT_LINE="**All ${TEST_COUNT} published scenarios passed.**"- else- TITLE="$SUMMARY_TITLE × Midscene · failure captured"- RESULT_LINE="**The producing job finished as ${PRODUCER_RESULT}; the latest completed cases are ${SUCCESS_RATE}% passing.**"- fi-- HAS_AUXILIARY_REPORT=false- if [[ -f "$RUNNER_TEMP/pages-site/reports/$GITHUB_RUN_ID/auxiliary-report.html" ]]; then- HAS_AUXILIARY_REPORT=true- fi-- if [[ "${{ inputs.report-label }}" == Omarchy* ]]; then- if [[ "$PRODUCER_RESULT" == "success" && "$SUCCESS_RATE" == "100" && "$HAS_AUXILIARY_REPORT" == "true" ]]; then- RESULT_LINE="**3/3 shell visual checks and all ${TEST_COUNT} published scenarios passed.**"- fi- fi-- if [[ "$HAS_AUXILIARY_REPORT" == "true" ]]; then- REPORT_LINKS="[Open the Doubao Say report]($REPORT_URL) · [$AUXILIARY_REPORT_LABEL]($AUXILIARY_URL) · [Report history]($HISTORY_URL)"- REPORT_PREVIEWS="| Doubao Say | $AUXILIARY_REPORT_LABEL |- |:--|:--|- | []($REPORT_URL) | []($AUXILIARY_URL) |"- else- REPORT_LINKS="[Open the Doubao Say report]($REPORT_URL) · [Report history]($HISTORY_URL)"- REPORT_PREVIEWS="[]($REPORT_URL)"- fi-- cat >> "$GITHUB_STEP_SUMMARY" <<EOF- ## $TITLE-- $RESULT_LINE-- $REPORT_LINKS-- $REPORT_PREVIEWS-- Click either final-node preview to inspect that complete Midscene Test report, screenshots, and Agent replay.- EOF+ node scripts/render-ci-report-summary.mjs \+ --manifest "$RUNNER_TEMP/pages-site/reports/manifest.json" \+ --pages-url "$PAGES_BASE_URL" \+ --producer-result "$PRODUCER_RESULT" \+ --run-id "$GITHUB_RUN_ID" \+ --summary-title "$SUMMARY_TITLE" \+ --output "$GITHUB_STEP_SUMMARY"diff --git a/.github/workflows/midscene-omarchy-4.0.3.yml b/.github/workflows/midscene-omarchy-4.0.3.ymlindex fe93321..0a68e19 100644--- a/.github/workflows/midscene-omarchy-4.0.3.yml+++ b/.github/workflows/midscene-omarchy-4.0.3.yml@@ -8,13 +8,17 @@ on:- ".github/workflows/midscene-omarchy-4.0.3.yml"- ".github/workflows/deploy-midscene-report.yml"- "scripts/build-pages-report.mjs"+ - "scripts/report-cases.mjs"+ - "scripts/render-ci-report-summary.mjs"+ - "scripts/verify-pages-report.mjs"- "scripts/verify-omarchy-evidence.mjs"- "scripts/omarchy-shell-evidence.mjs"- "tests/contracts/test_pages_report_history.mjs"- "tests/e2e/package.json"- "tests/e2e/package-lock.json"- "tests/e2e/gtk_fixture.py"- - "tests/e2e/is-transient-midscene-failure.sh"+ - "tests/e2e/gtk_onboarding_fixture.py"+ - "tests/e2e/gtk_runtime_fixture.py"- "tests/e2e/capture-report-preview.mjs"- "tests/e2e/cases/**"- "tests/e2e/midscene.config.ts"@@ -33,13 +37,17 @@ on:- ".github/workflows/midscene-omarchy-4.0.3.yml"- ".github/workflows/deploy-midscene-report.yml"- "scripts/build-pages-report.mjs"+ - "scripts/report-cases.mjs"+ - "scripts/render-ci-report-summary.mjs"+ - "scripts/verify-pages-report.mjs"- "scripts/verify-omarchy-evidence.mjs"- "scripts/omarchy-shell-evidence.mjs"- "tests/contracts/test_pages_report_history.mjs"- "tests/e2e/package.json"- "tests/e2e/package-lock.json"- "tests/e2e/gtk_fixture.py"- - "tests/e2e/is-transient-midscene-failure.sh"+ - "tests/e2e/gtk_onboarding_fixture.py"+ - "tests/e2e/gtk_runtime_fixture.py"- "tests/e2e/capture-report-preview.mjs"- "tests/e2e/cases/**"- "tests/e2e/midscene.config.ts"@@ -62,7 +70,9 @@ concurrency:# Keep only one pending run for this workflow and ref. Ubuntu, Omarchy, main,# and unrelated PRs must not replace one another in GitHub's concurrency queue.group: midscene-model-e2e-${{ github.workflow }}-${{ github.ref }}- cancel-in-progress: false+ # A newer PR commit supersedes its predecessor. Main runs remain serialized+ # so report publication always follows commit order.+ cancel-in-progress: ${{ github.event_name == 'pull_request' }}jobs:omarchy-vm:@@ -104,7 +114,7 @@ jobs:}')curl --fail --silent --show-error \--connect-timeout 15 --max-time 90 \- --retry 4 --retry-all-errors --retry-delay 5 \+ --retry 4 --retry-all-errors --retry-delay 5 --retry-max-time 90 \-H "Authorization: Bearer $MIDSCENE_MODEL_API_KEY" \-H "Content-Type: application/json" \--data "$payload" \@@ -129,6 +139,7 @@ jobs:cache-dependency-path: tests/e2e/package-lock.json- name: Install Midscene and VNC bridge+ id: test-dependenciesrun: |sudo apt-get install -y --no-install-recommends \fluxbox tigervnc-viewer x11-xserver-utils xvfb@@ -144,17 +155,13 @@ jobs:- name: Run real Omarchy Midscene E2Erun: tests/e2e/run-omarchy-midscene.sh- - name: Capture the final report node for the CI summary- if: always()- run: >-- node tests/e2e/capture-report-preview.mjs- tests/e2e/midscene_run- tests/e2e/midscene_run/report-preview.png- omarchy-onboarding- && node tests/e2e/capture-report-preview.mjs- tests/e2e/midscene_run- tests/e2e/midscene_run/auxiliary-report-preview.png- omarchy-shell+ - name: Capture the report result for the CI summary+ if: always() && steps.test-dependencies.outcome == 'success'+ run: |+ node tests/e2e/capture-report-preview.mjs \+ --report-dir tests/e2e/midscene_run \+ --primary-project omarchy-onboarding \+ --auxiliary-project omarchy-shell- name: Upload installer evidenceif: always()@@ -198,5 +205,6 @@ jobs:report-label: Omarchy 4.0.3summary-title: Omarchyprimary-project: omarchy-onboarding+ auxiliary-project: omarchy-shellauxiliary-report-label: Omarchy visual checksrun-result: ${{ needs.omarchy-vm.result }}diff --git a/.github/workflows/midscene-ubuntu-22.04.yml b/.github/workflows/midscene-ubuntu-22.04.ymlindex 5d05f51..5df4f37 100644--- a/.github/workflows/midscene-ubuntu-22.04.yml+++ b/.github/workflows/midscene-ubuntu-22.04.yml@@ -8,11 +8,15 @@ on:- ".github/workflows/midscene-ubuntu-22.04.yml"- ".github/workflows/deploy-midscene-report.yml"- "scripts/build-pages-report.mjs"+ - "scripts/report-cases.mjs"+ - "scripts/render-ci-report-summary.mjs"+ - "scripts/verify-pages-report.mjs"- "tests/contracts/test_pages_report_history.mjs"- "tests/e2e/package.json"- "tests/e2e/package-lock.json"- "tests/e2e/gtk_fixture.py"- - "tests/e2e/is-transient-midscene-failure.sh"+ - "tests/e2e/gtk_onboarding_fixture.py"+ - "tests/e2e/gtk_runtime_fixture.py"- "tests/e2e/capture-report-preview.mjs"- "tests/e2e/polish_fixture.py"- "tests/e2e/cases/**"@@ -24,11 +28,15 @@ on:- ".github/workflows/midscene-ubuntu-22.04.yml"- ".github/workflows/deploy-midscene-report.yml"- "scripts/build-pages-report.mjs"+ - "scripts/report-cases.mjs"+ - "scripts/render-ci-report-summary.mjs"+ - "scripts/verify-pages-report.mjs"- "tests/contracts/test_pages_report_history.mjs"- "tests/e2e/package.json"- "tests/e2e/package-lock.json"- "tests/e2e/gtk_fixture.py"- - "tests/e2e/is-transient-midscene-failure.sh"+ - "tests/e2e/gtk_onboarding_fixture.py"+ - "tests/e2e/gtk_runtime_fixture.py"- "tests/e2e/capture-report-preview.mjs"- "tests/e2e/polish_fixture.py"- "tests/e2e/cases/**"@@ -43,14 +51,16 @@ concurrency:# Keep only one pending run for this workflow and ref. Ubuntu, Omarchy, main,# and unrelated PRs must not replace one another in GitHub's concurrency queue.group: midscene-model-e2e-${{ github.workflow }}-${{ github.ref }}- cancel-in-progress: false+ # A newer PR commit supersedes its predecessor. Main runs remain serialized+ # so report publication always follows commit order.+ cancel-in-progress: ${{ github.event_name == 'pull_request' }}jobs:ubuntu-gtk:- name: Midscene onboarding+ name: Midscene onboarding and polishing visualsif: github.event_name != 'pull_request' || github.event.pull_request.head.repo.full_name == github.repositoryruns-on: ubuntu-22.04- timeout-minutes: 60+ timeout-minutes: 90env:MIDSCENE_MODEL_API_KEY: ${{ secrets.MIDSCENE_MODEL_API_KEY }}MIDSCENE_MODEL_NAME: ${{ secrets.MIDSCENE_MODEL_NAME }}@@ -118,6 +128,7 @@ jobs:x11-xserver-utils xdg-utils xvfb- name: Install pinned Midscene dependencies+ id: test-dependenciesworking-directory: tests/e2e# sharp's platform packages are pinned explicitly. Skipping lifecycle# scripts avoids an npm ordering bug that tries to build sharp before@@ -136,73 +147,25 @@ jobs:working-directory: tests/e2eenv:NODE_OPTIONS: --dns-result-order=ipv4first --no-network-family-autoselection --require=./node_modules/@computer-use/libnut/dist/import_libnut.js- run: |- set -o pipefail- midscene_passed=false- for test_attempt in 1 2 3; do- attempt_log="/tmp/ubuntu-midscene-attempt-${test_attempt}.log"- if npm test -- --project ubuntu 2>&1 | tee "$attempt_log"; then- midscene_passed=true- break- fi-- if ! ./is-transient-midscene-failure.sh "$attempt_log"; then- echo "Ubuntu Midscene failed for a non-transient reason; not retrying." >&2- exit 1- fi- if [[ $test_attempt -lt 3 ]]; then- echo "Transient model or connection failure on attempt ${test_attempt}; retrying in 10 seconds." >&2- sleep 10- fi- done-- if [[ $midscene_passed != true ]]; then- echo "Ubuntu Midscene exhausted three transient-failure attempts." >&2- exit 1- fi+ run: >-+ timeout --signal=TERM --kill-after=10s 50m+ npm test -- --project ubuntu- name: Verify polishing overlay with Midsceneworking-directory: tests/e2eenv:NODE_OPTIONS: --dns-result-order=ipv4first --no-network-family-autoselection --require=./node_modules/@computer-use/libnut/dist/import_libnut.js- run: |- set -o pipefail- polishing_passed=false- for test_attempt in 1 2 3 4; do- attempt_log="/tmp/ubuntu-polishing-midscene-attempt-${test_attempt}.log"- if timeout --signal=TERM --kill-after=10s 10m \- npm test -- --project ubuntu-polishing 2>&1 | tee "$attempt_log"; then- polishing_passed=true- break- fi-- if ! ./is-transient-midscene-failure.sh "$attempt_log"; then- echo "Ubuntu polishing Midscene failed for a non-transient reason; not retrying." >&2- exit 1- fi- if [[ $test_attempt -lt 4 ]]; then- retry_delay=$((15 * test_attempt))- echo "Transient model or connection failure on polishing attempt ${test_attempt}; retrying in ${retry_delay} seconds." >&2- sleep "$retry_delay"- fi- done-- if [[ $polishing_passed != true ]]; then- echo "Ubuntu polishing Midscene exhausted four transient-failure attempts." >&2- exit 1- fi-- - name: Capture the final report node for the CI summary- if: always()run: >-- node tests/e2e/capture-report-preview.mjs- tests/e2e/midscene_run- tests/e2e/midscene_run/report-preview.png- ubuntu- && node tests/e2e/capture-report-preview.mjs- tests/e2e/midscene_run- tests/e2e/midscene_run/auxiliary-report-preview.png- ubuntu-polishing+ timeout --signal=TERM --kill-after=10s 35m+ npm test -- --project ubuntu-polishing++ - name: Capture the report result for the CI summary+ if: always() && steps.test-dependencies.outcome == 'success'+ run: |+ node tests/e2e/capture-report-preview.mjs \+ --report-dir tests/e2e/midscene_run \+ --primary-project ubuntu \+ --auxiliary-project ubuntu-polishing- name: Upload Midscene reportid: report@@ -233,5 +196,6 @@ jobs:report-label: Ubuntu 22.04summary-title: Ubuntuprimary-project: ubuntu+ auxiliary-project: ubuntu-polishingauxiliary-report-label: Polishing overlay reportrun-result: ${{ needs.ubuntu-gtk.result }}diff --git a/.github/workflows/secrets.yml b/.github/workflows/secrets.ymlindex e699aea..e2e7ed0 100644--- a/.github/workflows/secrets.yml+++ b/.github/workflows/secrets.yml@@ -1,5 +1,10 @@name: Secret scanning-on: [push, pull_request]+on:+ push:+ branches: [main]+ pull_request:+ branches: [main]+ workflow_dispatch:permissions:contents: readjobs:diff --git a/.github/workflows/tests.yml b/.github/workflows/tests.ymlindex 7b7b03a..7e8d4ce 100644--- a/.github/workflows/tests.yml+++ b/.github/workflows/tests.yml@@ -1,6 +1,11 @@name: Tests-on: [push, pull_request]+on:+ push:+ branches: [main]+ pull_request:+ branches: [main]+ workflow_dispatch:permissions:contents: read@@ -24,9 +29,11 @@ jobs:- name: Statically check and test Pages history builderrun: |node --check scripts/build-pages-report.mjs+ node --check scripts/report-cases.mjs+ node --check scripts/render-ci-report-summary.mjs+ node --check scripts/verify-pages-report.mjsnode --check tests/contracts/test_pages_report_history.mjsnode --test tests/contracts/test_pages_report_history.mjs-core-compatibility:name: Core / Python ${{ matrix.python }}runs-on: ubuntu-latestdiff --git a/scripts/build-pages-report.mjs b/scripts/build-pages-report.mjsindex a3d3e15..216d4cb 100644--- a/scripts/build-pages-report.mjs+++ b/scripts/build-pages-report.mjs@@ -10,13 +10,14 @@ import {import path from 'node:path';import process from 'node:process';import {- extractShellEvidence,findHtmlFiles,reportDumps,testRunDump,} from './omarchy-shell-evidence.mjs';+import { reportCases } from './report-cases.mjs';-const MANIFEST_VERSION = 1;+const MANIFEST_VERSION = 4;+const SUPPORTED_MANIFEST_VERSIONS = new Set([1, 2, 3, MANIFEST_VERSION]);function parseArguments(argv) {const options = {};@@ -113,10 +114,71 @@ function collectModelUsage(reportHtml) {};}+function collectAssertionResults(run) {+ let passed = 0;+ let total = 0;+ for (const project of run?.projects ?? []) {+ for (const document of project.documents ?? []) {+ for (const testCase of document.cases ?? []) {+ const attempt = testCase.attempts?.at(-1);+ if (!attempt) continue;+ for (const step of [+ ...(attempt.beforeEach ?? []),+ ...(attempt.steps ?? []),+ ...(attempt.afterEach ?? []),+ ]) {+ if (step.node !== 'aiAssert') continue;+ total += 1;+ if (step.status === 'success') passed += 1;+ }+ }+ }+ }+ return { passed, total };+}++function buildReportEntry({+ label,+ previewPath,+ project,+ report,+ reportPath,+ role,+}) {+ const status = report.run?.status ?? 'unknown';+ const cases = reportCases(report.run, project, {+ reportHtml: report.html,+ }).map((testCase) => ({+ caseId: testCase.caseId,+ name: testCase.name,+ status: testCase.status,+ stepId: testCase.stepId,+ selection: testCase.selection,+ description: testCase.description,+ descriptionKind: testCase.descriptionKind,+ previewPath: `${path.posix.dirname(reportPath)}/${testCase.previewFile}`,+ }));+ return {+ role,+ project,+ label,+ status,+ previewStep: status === 'success' ? 'last' : 'last-error',+ reportPath,+ previewPath,+ scenarios: {+ passed: report.run?.summary?.passed ?? 0,+ total: report.run?.summary?.total ?? 0,+ },+ assertions: collectAssertionResults(report.run),+ cases,+ };+}+function validateHistoryManifest(manifest) {if (!manifest ||- manifest.version !== MANIFEST_VERSION ||+ !SUPPORTED_MANIFEST_VERSIONS.has(manifest.version) ||!Array.isArray(manifest.reports)) {throw new Error('Existing Pages manifest has an unsupported shape');@@ -134,6 +196,44 @@ function validateHistoryManifest(manifest) {typeof file !== 'string' ||!/^reports\/\d+\/[a-z0-9.-]+$/.test(file) ||!file.startsWith(`reports/${report.runId}/`),+ ))) ||+ (report.entries !== undefined &&+ (!Array.isArray(report.entries) ||+ report.entries.some(+ (entry) =>+ !['primary', 'auxiliary'].includes(entry.role) ||+ typeof entry.project !== 'string' ||+ typeof entry.label !== 'string' ||+ typeof entry.status !== 'string' ||+ !['last', 'last-error'].includes(entry.previewStep) ||+ !report.files?.includes(entry.reportPath) ||+ !report.files?.includes(entry.previewPath) ||+ !Number.isInteger(entry.scenarios?.passed) ||+ !Number.isInteger(entry.scenarios?.total) ||+ !Number.isInteger(entry.assertions?.passed) ||+ !Number.isInteger(entry.assertions?.total) ||+ (entry.cases !== undefined &&+ (!Array.isArray(entry.cases) ||+ entry.cases.some(+ (testCase) =>+ typeof testCase.caseId !== 'string' ||+ typeof testCase.name !== 'string' ||+ !['success', 'failed'].includes(testCase.status) ||+ typeof testCase.stepId !== 'string' ||+ !['last-screenshot', 'first-failing-screenshot'].includes(+ testCase.selection,+ ) ||+ (testCase.description !== undefined &&+ (typeof testCase.description !== 'string' ||+ testCase.description.length === 0)) ||+ (testCase.descriptionKind !== undefined &&+ !['ai', 'error', 'result'].includes(+ testCase.descriptionKind,+ )) ||+ ((testCase.description === undefined) !==+ (testCase.descriptionKind === undefined)) ||+ !report.files?.includes(testCase.previewPath),+ ))),)))) {throw new Error(@@ -203,6 +303,99 @@ function formatDuration(durationMs) {return `${(durationMs / 1000).toFixed(2)} s`;}+function runStepHref(entry, testCase) {+ return `${path.basename(entry.reportPath)}#${new URLSearchParams({+ 'runner-step': testCase.stepId,+ })}`;+}++function buildRunIndex(report) {+ const sections = report.entries+ .map((entry) => {+ const rows = entry.cases+ .map((testCase) => {+ const target = runStepHref(entry, testCase);+ const image = path.basename(testCase.previewPath);+ const status = testCase.status === 'success' ? '✅ Passed' : '❌ Failed';+ const descriptionLabel = {+ ai: 'AI',+ error: 'Error',+ result: 'Result',+ }[testCase.descriptionKind];+ return `+ <tr>+ <td class="status">${status}</td>+ <td><a href="${escapeHtml(target)}">${escapeHtml(testCase.name)}</a></td>+ <td><a href="${escapeHtml(target)}"><img src="${escapeHtml(image)}" alt="${escapeHtml(testCase.name)} node screenshot" loading="lazy"></a></td>+ <td><strong>${escapeHtml(descriptionLabel)}:</strong> ${escapeHtml(testCase.description)}</td>+ </tr>`;+ })+ .join('');+ return `+ <section>+ <div class="section-heading">+ <div>+ <h2>${escapeHtml(entry.label)}</h2>+ <p>${entry.scenarios.passed}/${entry.scenarios.total} cases passed</p>+ </div>+ <a class="native-report" href="${escapeHtml(path.basename(entry.reportPath))}">Open native Midscene report →</a>+ </div>+ <div class="table-wrap">+ <table>+ <thead><tr><th>Result</th><th>Case</th><th>Node screenshot</th><th>AI response / error</th></tr></thead>+ <tbody>${rows}+ </tbody>+ </table>+ </div>+ </section>`;+ })+ .join('');++ return `<!doctype html>+<html lang="en">+ <head>+ <meta charset="utf-8">+ <meta name="viewport" content="width=device-width, initial-scale=1">+ <title>${escapeHtml(report.label)} · Midscene E2E evidence</title>+ <style>+ :root { color-scheme: light dark; font-family: ui-sans-serif, system-ui, sans-serif; }+ body { margin: 0 auto; max-width: 1500px; padding: 2rem 1rem 4rem; }+ header { margin-bottom: 2rem; }+ h1, h2 { margin: 0; }+ p { color: #777; margin: .35rem 0 0; }+ section { margin-top: 2rem; }+ .section-heading { align-items: end; display: flex; gap: 1rem; justify-content: space-between; margin-bottom: .75rem; }+ .native-report, a { color: #2878d0; }+ .table-wrap { overflow-x: auto; }+ table { border-collapse: collapse; table-layout: fixed; width: 100%; }+ th, td { border-bottom: 1px solid #8885; padding: .8rem; text-align: left; vertical-align: top; }+ th { font-size: .78rem; text-transform: uppercase; }+ th:nth-child(1) { width: 7rem; }+ th:nth-child(2) { width: 17rem; }+ th:nth-child(3) { width: 34%; }+ td { line-height: 1.45; }+ td.status { white-space: nowrap; }+ img { border: 1px solid #8885; border-radius: .5rem; display: block; height: auto; width: 100%; }+ @media (max-width: 900px) {+ body { padding: 1rem .6rem 3rem; }+ .section-heading { align-items: start; flex-direction: column; }+ table { min-width: 980px; }+ }+ </style>+ </head>+ <body>+ <header>+ <h1>${escapeHtml(report.label)} × Midscene</h1>+ <p>Run ${escapeHtml(report.runId)} · ${escapeHtml(report.successRate.toFixed(1))}% passed · <a href="${escapeHtml(report.workflowUrl)}">GitHub Actions</a> · <a href="../../">Report history</a></p>+ <p>Each image is the original page screenshot used by that node. Click a case or image to open the exact Midscene step and Agent replay.</p>+ </header>+ <main>${sections}+ </main>+ </body>+</html>+`;+}+function buildIndex(reports) {const rows = reports.map(@@ -242,7 +435,7 @@ function buildIndex(reports) {<body><main><h1>Doubao Say test report history</h1>- <p>Successful Midscene CI reports, newest first.</p>+ <p>Midscene CI reports, newest first.</p><div class="table-wrap"><table><thead><tr><th>Run ID</th><th>Distribution</th><th>Generated (UTC)</th><th>Success rate</th><th>Avg. model call</th><th>Model calls</th><th>Tokens</th><th>Workflow</th><th>Report</th></tr></thead>@@ -266,6 +459,14 @@ export async function buildPagesReport(options) {const baseUrl = normalizeBaseUrl(required(options, 'pages-url'));const label = options.label || 'Midscene E2E';const primaryProject = required(options, 'primary-project');+ const primaryReportLabel = options['primary-report-label'] || 'Doubao Say';+ const auxiliaryProject = options['auxiliary-project'];+ const auxiliaryReportLabel = options['auxiliary-report-label'];+ if (Boolean(auxiliaryProject) !== Boolean(auxiliaryReportLabel)) {+ throw new Error(+ '--auxiliary-project and --auxiliary-report-label must be provided together',+ );+ }const existingItems = await readdir(siteDirectory).catch((error) => {if (error.code === 'ENOENT') return null;@@ -296,28 +497,35 @@ export async function buildPagesReport(options) {const htmlReports = [...latestByProject.values()].sort((left, right) => left.startedAt - right.startedAt,);- if (htmlReports.length < 1 || htmlReports.length > 2) {- throw new Error(- `Expected reports for one or two projects, found ${htmlReports.length}`,+ const reportForProject = (projectName) =>+ htmlReports.find(+ (report) =>+ report.run?.projects?.length === 1 &&+ report.run.projects[0].name === projectName,);- }- const primaryReport = htmlReports.find((report) =>- report.run?.projects?.some((project) => project.name === primaryProject),- );+ const primaryReport = reportForProject(primaryProject);if (!primaryReport) {throw new Error(`No Midscene Test report found for project ${primaryProject}`);}- const auxiliaryReport = htmlReports.find((report) => report !== primaryReport);- const shellReport = htmlReports.find((report) =>- report.html.includes('The Omarchy system menu is open'),- );- const checks = shellReport- ? extractShellEvidence(shellReport.html, { allowIncomplete: true })+ const auxiliaryReport = auxiliaryProject+ ? reportForProject(auxiliaryProject): null;+ const selectedReports = [primaryReport, auxiliaryReport].filter(Boolean);+ const selectedFiles = new Set(selectedReports.map((report) => report.file));+ const unexpectedProjects = htmlReports+ .filter((report) => !selectedFiles.has(report.file))+ .flatMap((report) =>+ report.run?.projects?.map((project) => project.name) ?? [path.basename(report.file)],+ );+ if (unexpectedProjects.length) {+ throw new Error(+ `Unexpected Midscene Test project(s): ${unexpectedProjects.join(', ')}`,+ );+ }const usage = collectModelUsage(- htmlReports.map((report) => report.html).join('\n'),+ selectedReports.map((report) => report.html).join('\n'),);- const result = htmlReports.reduce(+ const result = selectedReports.reduce((total, report) => ({passed: total.passed + (report.run?.summary?.passed ?? 0),tests: total.tests + (report.run?.summary?.total ?? 0),@@ -325,34 +533,60 @@ export async function buildPagesReport(options) {{ passed: 0, tests: 0 },);const reportPrefix = `reports/${runId}`;- const files = auxiliaryReport+ const primaryNativeReport = `${reportPrefix}/native-report.html`;+ const auxiliaryNativeReport = `${reportPrefix}/auxiliary-report.html`;+ const baseFiles = auxiliaryReport? ['index.html',+ 'native-report.html','auxiliary-report.html','report-preview.png','auxiliary-report-preview.png',].map((name) => `${reportPrefix}/${name}`): [`${reportPrefix}/index.html`,+ primaryNativeReport,`${reportPrefix}/report-preview.png`,];+ const entries = [+ buildReportEntry({+ role: 'primary',+ project: primaryProject,+ label: primaryReportLabel,+ report: primaryReport,+ reportPath: primaryNativeReport,+ previewPath: `${reportPrefix}/report-preview.png`,+ }),+ ...(auxiliaryReport+ ? [+ buildReportEntry({+ role: 'auxiliary',+ project: auxiliaryProject,+ label: auxiliaryReportLabel,+ report: auxiliaryReport,+ reportPath: auxiliaryNativeReport,+ previewPath: `${reportPrefix}/auxiliary-report-preview.png`,+ }),+ ]+ : []),+ ];+ const casePreviewFiles = entries.flatMap((entry) =>+ entry.cases.map((testCase) => testCase.previewPath),+ );+ const files = [...baseFiles, ...casePreviewFiles];const current = {runId,generatedAt,label,successRate: result.tests? Math.round((result.passed / result.tests) * 100)- : checks- ? Math.round(- (checks.filter((check) => check.passed).length / checks.length) *- 100,- )- : 0,- testCount: result.tests || htmlReports.length,+ : 0,+ testCount: result.tests,...usage,workflowUrl,reportPath: `reports/${runId}/index.html`,files,+ entries,};const history = (await fetchHistory(baseUrl))@@ -367,7 +601,7 @@ export async function buildPagesReport(options) {const currentDirectory = path.join(siteDirectory, reportPrefix);await mkdir(currentDirectory, { recursive: true });if (auxiliaryReport) {- await copyFile(primaryReport.file, path.join(currentDirectory, 'index.html'));+ await copyFile(primaryReport.file, path.join(currentDirectory, 'native-report.html'));await copyFile(auxiliaryReport.file, path.join(currentDirectory, 'auxiliary-report.html'));await copyFile(path.join(reportDirectory, 'report-preview.png'), path.join(currentDirectory, 'report-preview.png'));await copyFile(@@ -375,12 +609,21 @@ export async function buildPagesReport(options) {path.join(currentDirectory, 'auxiliary-report-preview.png'),);} else {- await copyFile(primaryReport.file, path.join(currentDirectory, 'index.html'));+ await copyFile(primaryReport.file, path.join(currentDirectory, 'native-report.html'));await copyFile(path.join(reportDirectory, 'report-preview.png'),path.join(currentDirectory, 'report-preview.png'),);}+ for (const entry of entries) {+ for (const testCase of entry.cases) {+ await copyFile(+ path.join(reportDirectory, path.basename(testCase.previewPath)),+ path.join(currentDirectory, path.basename(testCase.previewPath)),+ );+ }+ }+ await writeFile(path.join(currentDirectory, 'index.html'), buildRunIndex(current));const reports = [current, ...history];const manifest = {diff --git a/scripts/omarchy-shell-evidence.mjs b/scripts/omarchy-shell-evidence.mjsindex cee7243..ad83fd2 100644--- a/scripts/omarchy-shell-evidence.mjs+++ b/scripts/omarchy-shell-evidence.mjs@@ -5,17 +5,14 @@ export const SHELL_CHECKS = [{key: 'shutdown',label: 'Shutdown is readable',- marker: 'The Omarchy system menu is open',},{key: 'focus',label: 'Menu focus highlight is clean',- marker: 'Exactly one row in the open system menu',},{key: 'bar',label: 'Bar is vertical on the left',- marker: 'The Omarchy bar is visible',},];@@ -83,7 +80,10 @@ export function testRunDump(html) {: null;}-export async function findLatestTestReport(directory, { projectName } = {}) {+export async function findLatestTestReport(+ directory,+ { projectName, required = true } = {},+) {const reports = await Promise.all((await findHtmlFiles(directory)).map(async (file) => {const html = await readFile(file, 'utf8');@@ -105,6 +105,7 @@ export async function findLatestTestReport(directory, { projectName } = {}) {.sort((left, right) => left.startedAt - right.startedAt).at(-1);if (!latest) {+ if (!required) return null;throw new Error(projectName? `No Midscene Test HTML report found for project ${projectName}`@@ -125,27 +126,23 @@ export function extractShellEvidence(html, { allowIncomplete = false } = {}) {});}- const finished = new Map();+ const finished = [];for (const dump of reportDumps(html)) {for (const execution of dump.executions ?? []) {for (const task of execution.tasks ?? []) {if (task.status !== 'finished' || task.subType !== 'Assert') continue;- const demand = task.param?.dataDemand;- if (typeof demand === 'string') finished.set(demand, task);+ finished.push(task);}}}- return SHELL_CHECKS.map((check) => {- const entry = [...finished.entries()].find(([demand]) =>- demand.startsWith(check.marker),- );- if (!entry) {+ return SHELL_CHECKS.map((check, index) => {+ const task = finished[index];+ if (!task) {if (allowIncomplete)return { ...check, passed: false, screenshot: null, missing: true };throw new Error(`Missing finished Omarchy assertion: ${check.label}`);}- const task = entry[1];const screenshot = images.get(task.uiContext?.screenshot?.id);if (!screenshot) {if (allowIncomplete)@@ -159,10 +156,8 @@ export function extractShellEvidence(html, { allowIncomplete = false } = {}) {export async function findShellReport(directory) {for (const file of await findHtmlFiles(directory)) {const html = await readFile(file, 'utf8');- if (- html.includes(SHELL_CHECKS[0].marker) &&- html.includes(SHELL_CHECKS[2].marker)- ) {+ const run = testRunDump(html);+ if (run?.projects?.some((project) => project.name === 'omarchy-shell')) {return { file, html, checks: extractShellEvidence(html) };}}diff --git a/scripts/render-ci-report-summary.mjs b/scripts/render-ci-report-summary.mjsnew file mode 100644index 0000000..f94f099--- /dev/null+++ b/scripts/render-ci-report-summary.mjs@@ -0,0 +1,159 @@+#!/usr/bin/env node++import { appendFile, readFile } from 'node:fs/promises';+import process from 'node:process';++function parseArguments(argv) {+ const options = {};+ for (let index = 0; index < argv.length; index += 2) {+ const key = argv[index];+ const value = argv[index + 1];+ if (!key?.startsWith('--') || value === undefined) {+ throw new Error(`Invalid argument near ${key ?? '<end>'}`);+ }+ options[key.slice(2)] = value;+ }+ return options;+}++function required(options, name) {+ const value = options[name];+ if (!value) throw new Error(`Missing --${name}`);+ return value;+}++function normalizedBaseUrl(value) {+ const url = new URL(value);+ if (!url.pathname.endsWith('/')) url.pathname += '/';+ return url;+}++function reportUrl(baseUrl, reportPath) {+ return new URL(reportPath, normalizedBaseUrl(baseUrl)).href;+}++function stepUrl(baseUrl, reportPath, stepId) {+ const url = new URL(reportPath, normalizedBaseUrl(baseUrl));+ url.hash = new URLSearchParams({ 'runner-step': stepId }).toString();+ return url.href;+}++function markdownCell(value) {+ return String(value)+ .replaceAll('\\', '\\\\')+ .replaceAll('|', '\\|')+ .replaceAll('[', '\\[')+ .replaceAll(']', '\\]')+ .replaceAll('\n', ' ');+}++function entryResult(entry) {+ const parts = [];+ if (entry.scenarios.total > 0) {+ parts.push(+ `${entry.scenarios.passed}/${entry.scenarios.total} scenarios passed`,+ );+ }+ if (entry.assertions.total > 0) {+ parts.push(+ `${entry.assertions.passed}/${entry.assertions.total} visual assertions passed`,+ );+ }+ return `**${entry.label}: ${parts.join(' · ') || 'report captured'}.**`;+}++export function renderReportSummary({+ manifest,+ pagesUrl,+ producerResult,+ runId,+ summaryTitle,+}) {+ const report = manifest.reports.find((item) => item.runId === runId);+ if (!report) throw new Error(`Run ${runId} is absent from the report manifest`);+ if (!Array.isArray(report.entries) || report.entries.length === 0) {+ throw new Error(`Run ${runId} does not contain structured report entries`);+ }++ const allPassed =+ producerResult === 'success' &&+ report.entries.every(+ (entry) =>+ entry.scenarios.total > 0 &&+ entry.scenarios.passed === entry.scenarios.total &&+ entry.assertions.passed === entry.assertions.total,+ );+ const title = `${summaryTitle} × Midscene · ${+ allPassed ? 'passed' : 'failure captured'+ }`;+ const historyUrl = normalizedBaseUrl(pagesUrl).href;+ const links = [+ ...report.entries.map(+ (entry) =>+ `[Open ${entry.label}](${reportUrl(pagesUrl, entry.reportPath)})`,+ ),+ `[Report history](${historyUrl})`,+ ].join(' · ');+ const caseTables = report.entries.map((entry) => {+ if (!Array.isArray(entry.cases) || entry.cases.length === 0) {+ throw new Error(`${entry.label} does not contain case evidence`);+ }+ const rows = entry.cases.map((testCase) => {+ if (!testCase.description || !testCase.descriptionKind) {+ throw new Error(`${testCase.name} does not contain node text evidence`);+ }+ const target = stepUrl(pagesUrl, entry.reportPath, testCase.stepId);+ const image = reportUrl(pagesUrl, testCase.previewPath);+ const status = testCase.status === 'success' ? '✅ Passed' : '❌ Failed';+ const evidence =+ testCase.status === 'success'+ ? 'Last screenshot'+ : 'First failing screenshot';+ const descriptionLabel = {+ ai: '**AI:** ',+ error: '**Error:** ',+ result: '**Result:** ',+ }[testCase.descriptionKind];+ return `| ${status} | [${markdownCell(testCase.name)}](${target}) | [](${target}) | ${descriptionLabel}${markdownCell(testCase.description)} |`;+ });+ return `### ${entry.label}++| Result | Case | Node screenshot | AI response / error |+|:--|:--|:--|:--|+${rows.join('\n')}`;+ })+ .join('\n\n');++ return `## ${title}++${report.entries.map(entryResult).join('\n\n')}++${links}++${caseTables}++Each image is the original page screenshot used by that node. Click a case name or image to open the exact Midscene Test node and Agent replay.+`;+}++async function main() {+ const options = parseArguments(process.argv.slice(2));+ const manifest = JSON.parse(+ await readFile(required(options, 'manifest'), 'utf8'),+ );+ const summary = renderReportSummary({+ manifest,+ pagesUrl: required(options, 'pages-url'),+ producerResult: required(options, 'producer-result'),+ runId: required(options, 'run-id'),+ summaryTitle: required(options, 'summary-title'),+ });+ await appendFile(required(options, 'output'), summary);+}++if (import.meta.url === new URL(process.argv[1], 'file:').href) {+ main().catch((error) => {+ process.stderr.write(`${error.stack ?? error.message}\n`);+ process.exitCode = 1;+ });+}diff --git a/scripts/report-cases.mjs b/scripts/report-cases.mjsnew file mode 100644index 0000000..afd3490--- /dev/null+++ b/scripts/report-cases.mjs@@ -0,0 +1,203 @@+import { normalizeJsonControlCharacters } from './omarchy-shell-evidence.mjs';++function allAttemptSteps(attempt) {+ return [+ ...(attempt?.beforeEach ?? []),+ ...(attempt?.steps ?? []),+ ...(attempt?.afterEach ?? []),+ ];+}++function hasScreenshotEvidence(step) {+ return Array.isArray(step?.agentDetails) && step.agentDetails.length > 0;+}++function projectSlug(projectName) {+ const slug = projectName+ .toLowerCase()+ .replace(/[^a-z0-9]+/g, '-')+ .replace(/^-|-$/g, '');+ if (!slug) {+ throw new Error(+ `Cannot build a preview filename for project ${projectName}`,+ );+ }+ return slug;+}++export function casePreviewFileName(projectName, caseId, extension = 'jpg') {+ if (!/^[a-zA-Z0-9-]+$/.test(caseId)) {+ throw new Error(`Invalid Midscene case ID: ${caseId}`);+ }+ if (!['jpg', 'png', 'webp'].includes(extension)) {+ throw new Error(`Unsupported Midscene screenshot format: ${extension}`);+ }+ return `case-preview-${projectSlug(projectName)}-${caseId}.${extension}`;+}++function scriptAttributes(source) {+ const attributes = new Map();+ for (const match of source.matchAll(/([\w-]+)=["']([^"']*)["']/g)) {+ attributes.set(match[1], match[2]);+ }+ return attributes;+}++function embeddedReportData(reportHtml) {+ const dumps = [];+ const images = new Map();+ for (const match of reportHtml.matchAll(+ /<script\s+([^>]*\btype=["']midscene_web_dump["'][^>]*)>\s*(\{[\s\S]*?)<\/script>/g,+ )) {+ const attributes = scriptAttributes(match[1]);+ dumps.push({+ reportId:+ attributes.get('data-report-id') ??+ attributes.get('data-group-id') ??+ null,+ dump: JSON.parse(normalizeJsonControlCharacters(match[2].trim())),+ });+ }+ for (const match of reportHtml.matchAll(+ /<script\s+type=["']midscene-image["']\s+data-id=["']([^"']+)["'][^>]*>\s*data:image\/(jpeg|png|webp);base64,([A-Za-z0-9+/=]+)\s*<\/script>/g,+ )) {+ images.set(match[1], {+ extension: match[2] === 'jpeg' ? 'jpg' : match[2],+ bytes: Buffer.from(match[3], 'base64'),+ });+ }+ return { dumps, images };+}++function normalizedText(value) {+ if (typeof value !== 'string') return null;+ const text = value+ .replaceAll('__midscene_lt__', '<')+ .replaceAll('__midscene_gt__', '>')+ .replace(/\s+/g, ' ')+ .trim();+ return text || null;+}++function taggedModelText(rawResponse) {+ const response = normalizedText(rawResponse);+ if (!response) return null;+ const tagged = response.match(+ /<(?:observation|planning)>([\s\S]*?)<\/(?:observation|planning)>/,+ );+ return normalizedText(tagged?.[1]);+}++function modelTaskText(task) {+ return (+ normalizedText(task?.thought) ??+ normalizedText(task?.log?.taskInfo?.formatResponse?.thought) ??+ normalizedText(task?.output?.thought) ??+ taggedModelText(task?.log?.rawResponse) ??+ taggedModelText(task?.log?.taskInfo?.rawResponse) ??+ normalizedText(task?.output?.output)+ );+}++function isModelTask(task) {+ return (+ task?.type === 'Insight' ||+ (task?.type === 'Planning' && task?.subType === 'Plan')+ );+}++function executionForDetail(dumps, detail) {+ const preferred = dumps.filter(+ (entry) => !detail.reportId || entry.reportId === detail.reportId,+ );+ for (const entry of preferred.length ? preferred : dumps) {+ const execution = entry.dump?.executions?.find(+ (item) => item.id === detail.executionId,+ );+ if (execution) return execution;+ }+ return null;+}++function evidenceForStep(step, embedded) {+ const candidates = [];+ for (const detail of step.agentDetails ?? []) {+ const execution = executionForDetail(embedded.dumps, detail);+ for (const task of execution?.tasks ?? []) {+ const screenshotId = task?.uiContext?.screenshot?.id;+ const explanation = modelTaskText(task);+ if (+ isModelTask(task) &&+ screenshotId &&+ embedded.images.has(screenshotId)+ ) {+ candidates.push({ screenshotId, explanation });+ }+ }+ }+ const selected = candidates.at(-1);+ if (!selected) {+ throw new Error(`Step ${step.id} has no embedded node screenshot`);+ }+ const error = normalizedText(step.error?.message);+ const result = normalizedText(step.output?.summary);+ const description = error ?? selected.explanation ?? result;+ if (!description) {+ throw new Error(`Step ${step.id} has no AI response or error text`);+ }+ return {+ screenshot: embedded.images.get(selected.screenshotId),+ description,+ descriptionKind: error ? 'error' : selected.explanation ? 'ai' : 'result',+ };+}++export function reportCases(run, projectName, { reportHtml } = {}) {+ const project = run?.projects?.find((item) => item.name === projectName);+ if (!project) {+ throw new Error(`Project ${projectName} is absent from the runner dump`);+ }++ const embedded = reportHtml ? embeddedReportData(reportHtml) : null;+ return (project.documents ?? []).flatMap((document) =>+ (document.cases ?? []).map((testCase) => {+ const attempt = testCase.attempts?.at(-1);+ if (!attempt) {+ throw new Error(+ `Case ${testCase.name ?? testCase.caseId} has no attempt`,+ );+ }+ const steps = allAttemptSteps(attempt);+ const passed = (testCase.status ?? attempt.status) === 'success';+ const step = passed+ ? steps.findLast(hasScreenshotEvidence) ?? steps.at(-1)+ : steps.find(+ (item) => item.status === 'failed' && hasScreenshotEvidence(item),+ ) ??+ steps.find((item) => item.status === 'failed');+ if (!step?.id) {+ throw new Error(+ `Case ${testCase.name ?? testCase.caseId} has no report step to preview`,+ );+ }+ if (!testCase.caseId || !testCase.name) {+ throw new Error('Midscene case metadata is incomplete');+ }+ const evidence = embedded ? evidenceForStep(step, embedded) : null;+ return {+ caseId: testCase.caseId,+ name: testCase.name,+ status: passed ? 'success' : 'failed',+ stepId: step.id,+ stepTitle: step.title ?? step.node,+ selection: passed ? 'last-screenshot' : 'first-failing-screenshot',+ previewFile: casePreviewFileName(+ projectName,+ testCase.caseId,+ evidence?.screenshot.extension,+ ),+ ...(evidence ?? {}),+ };+ }),+ );+}diff --git a/scripts/verify-pages-report.mjs b/scripts/verify-pages-report.mjsnew file mode 100644index 0000000..695b0ed--- /dev/null+++ b/scripts/verify-pages-report.mjs@@ -0,0 +1,112 @@+#!/usr/bin/env node++import { readFile } from 'node:fs/promises';+import process from 'node:process';++function parseArguments(argv) {+ const options = {};+ for (let index = 0; index < argv.length; index += 2) {+ const key = argv[index];+ const value = argv[index + 1];+ if (!key?.startsWith('--') || value === undefined) {+ throw new Error(`Invalid argument near ${key ?? '<end>'}`);+ }+ options[key.slice(2)] = value;+ }+ return options;+}++function required(options, name) {+ const value = options[name];+ if (!value) throw new Error(`Missing --${name}`);+ return value;+}++function expectedContentType(file) {+ if (file.endsWith('.html')) return 'text/html';+ if (file.endsWith('.png')) return 'image/png';+ if (file.endsWith('.jpg')) return 'image/jpeg';+ if (file.endsWith('.webp')) return 'image/webp';+ throw new Error(`No expected Content-Type is defined for ${file}`);+}++function normalizedBaseUrl(value) {+ const url = new URL(value);+ if (!url.pathname.endsWith('/')) url.pathname += '/';+ return url;+}++async function checkEndpoint({ expectedType, url }, fetchImpl) {+ const response = await fetchImpl(url, {+ method: 'HEAD',+ redirect: 'follow',+ signal: AbortSignal.timeout(20_000),+ });+ const contentType = response.headers.get('content-type') ?? '';+ if (!response.ok || !contentType.toLowerCase().startsWith(expectedType)) {+ throw new Error(+ `${url}: HTTP ${response.status}, Content-Type ${contentType || '<missing>'}`,+ );+ }+ return `Verified HTTP ${response.status} ${expectedType}: ${url}`;+}++export async function verifyPublishedReport({+ fetchImpl = fetch,+ manifest,+ pagesUrl,+ runId,+}) {+ const report = manifest.reports.find((item) => item.runId === runId);+ if (!report) throw new Error(`Run ${runId} is absent from the report manifest`);+ if (!Array.isArray(report.files) || report.files.length === 0) {+ throw new Error(`Run ${runId} does not list published files`);+ }+ const baseUrl = normalizedBaseUrl(pagesUrl);+ const endpoints = [+ { url: baseUrl, expectedType: 'text/html' },+ ...report.files.map((file) => ({+ url: new URL(file, baseUrl),+ expectedType: expectedContentType(file),+ })),+ ];+ let failures = [];+ for (let attempt = 1; attempt <= 12; attempt += 1) {+ const results = await Promise.allSettled(+ endpoints.map((endpoint) => checkEndpoint(endpoint, fetchImpl)),+ );+ failures = results.filter((result) => result.status === 'rejected');+ if (failures.length === 0) {+ for (const result of results) process.stdout.write(`${result.value}\n`);+ return;+ }+ process.stdout.write(+ `Waiting for Pages propagation (${attempt}/12); ${failures.length} endpoint(s) are not ready.\n`,+ );+ if (attempt < 12) await new Promise((resolve) => setTimeout(resolve, 5000));+ }+ throw new Error(+ `Pages endpoint verification failed: ${failures+ .map((result) => result.reason?.message ?? result.reason)+ .join('; ')}`,+ );+}++async function main() {+ const options = parseArguments(process.argv.slice(2));+ const manifest = JSON.parse(+ await readFile(required(options, 'manifest'), 'utf8'),+ );+ await verifyPublishedReport({+ manifest,+ pagesUrl: required(options, 'pages-url'),+ runId: required(options, 'run-id'),+ });+}++if (import.meta.url === new URL(process.argv[1], 'file:').href) {+ main().catch((error) => {+ process.stderr.write(`${error.stack ?? error.message}\n`);+ process.exitCode = 1;+ });+}diff --git a/src/doubao_input/ui/control_window.py b/src/doubao_input/ui/control_window.pyindex ff8a6f4..39ab154 100644--- a/src/doubao_input/ui/control_window.py+++ b/src/doubao_input/ui/control_window.py@@ -415,7 +415,10 @@ class ControlWindow:self._actions.complete_setup, True)self._feedback = Gtk.Label(xalign=0, wrap=True, selectable=True)self._feedback.add_css_class("window-feedback")- content.append(self._feedback)+ # Action feedback must stay visible while a page's controls scroll.+ # Microphone checks and other async actions finish after the user's+ # click, so placing this label in the scroller can hide their result.+ outer.append(self._feedback)button(content, tr("Quit application", "退出应用"), self._on_quit)if self._actions.summary().get("onboarding_complete"):self._stack.set_visible_child_name("voice")diff --git a/src/doubao_input/ui/overlay.py b/src/doubao_input/ui/overlay.pyindex 66c2d58..2180ee0 100644--- a/src/doubao_input/ui/overlay.py+++ b/src/doubao_input/ui/overlay.py@@ -271,6 +271,7 @@ class Overlay:win.set_default_size(OVERLAY_WIDTH, OVERLAY_HEIGHT)win.set_size_request(OVERLAY_WIDTH, OVERLAY_HEIGHT)win.set_focus_on_click(False)+ win.set_focusable(False)win.set_can_focus(False)win.add_css_class("doubao-overlay")diff --git a/tests/README.md b/tests/README.mdindex 71b5043..759c4d1 100644--- a/tests/README.md+++ b/tests/README.md@@ -72,4 +72,6 @@ verification of the current change.Add or update the relevant YAML scenario when fixing a user-visible flow coveredby E2E. Use image assertions to establish visible results and deterministic testsfor underlying logic. Synthetic onboarding does not verify real credentials,-microphone capture, ASR, or text delivery; those require separate acceptance.+microphone capture, live ASR, system clipboard paste, or delivery into an+unrelated application; those require separate acceptance. The synthetic runtime+target does exercise the real Delivery state machine against its own GTK field.diff --git a/tests/contracts/test_midscene_retry_classifier.py b/tests/contracts/test_midscene_retry_classifier.pydeleted file mode 100644index ab77aee..0000000--- a/tests/contracts/test_midscene_retry_classifier.py+++ /dev/null@@ -1,40 +0,0 @@-import subprocess-import tempfile-import unittest-from pathlib import Path---ROOT = Path(__file__).resolve().parents[2]-CLASSIFIER = ROOT / "tests/e2e/is-transient-midscene-failure.sh"---class MidsceneRetryClassifierTest(unittest.TestCase):- def classify(self, content: str) -> subprocess.CompletedProcess[str]:- with tempfile.NamedTemporaryFile(mode="w", encoding="utf-8") as log:- log.write(content)- log.flush()- return subprocess.run(- [CLASSIFIER, log.name],- check=False,- capture_output=True,- text=True,- )-- def test_retries_network_and_model_protocol_failures(self):- for message in (- "AggregateError [ETIMEDOUT]",- "XML parse error: Invalid parameters for action KeyboardPress",- "Failed to parse action-param-json",- ):- with self.subTest(message=message):- self.assertEqual(self.classify(message).returncode, 0)-- def test_does_not_retry_product_assertion_failures(self):- result = self.classify(- "Assertion failed: the expected endpoint result is not visible"- )- self.assertEqual(result.returncode, 1)---if __name__ == "__main__":- unittest.main()diff --git a/tests/contracts/test_pages_report_history.mjs b/tests/contracts/test_pages_report_history.mjsindex a7e68ec..222b921 100644--- a/tests/contracts/test_pages_report_history.mjs+++ b/tests/contracts/test_pages_report_history.mjs@@ -6,9 +6,51 @@ import path from 'node:path';import test from 'node:test';import { buildPagesReport } from '../../scripts/build-pages-report.mjs';+import {+ findShellReport,+ testRunDump,+} from '../../scripts/omarchy-shell-evidence.mjs';+import { reportCases } from '../../scripts/report-cases.mjs';+import { renderReportSummary } from '../../scripts/render-ci-report-summary.mjs';+import { verifyPublishedReport } from '../../scripts/verify-pages-report.mjs';-function runnerScript({ project, status = 'success', startedAt }) {- return `<script type="midscene_test_run_dump">${JSON.stringify({+function runnerScript({+ assertionCount = 0,+ assertionAttempts,+ project,+ status = 'success',+ startedAt,+}) {+ const attempts =+ assertionAttempts ??+ (assertionCount+ ? [Array.from({ length: assertionCount }, () => 'success')]+ : [[status === 'success' ? 'success' : 'failed']]);+ const reportId = 'runner-report-1';+ const executions = attempts.flatMap((statuses, attemptIndex) =>+ statuses.map((stepStatus, stepIndex) => ({+ id: `execution-${attemptIndex}-${stepIndex}`,+ tasks: [+ {+ status: stepStatus === 'success' ? 'finished' : 'failed',+ type: 'Insight',+ subType: 'Assert',+ uiContext: {+ screenshot: {+ id: `screenshot-${attemptIndex}-${stepIndex}`,+ mimeType: 'image/jpeg',+ storage: 'inline',+ },+ },+ thought:+ stepStatus === 'success'+ ? `AI explanation ${attemptIndex}-${stepIndex}`+ : `AI failure explanation ${attemptIndex}-${stepIndex}`,+ },+ ],+ })),+ );+ const run = {startedAt,status,summary: {@@ -16,8 +58,52 @@ function runnerScript({ project, status = 'success', startedAt }) {passed: status === 'success' ? 1 : 0,failed: status === 'success' ? 0 : 1,},- projects: [{ name: project }],- })}</script>`;+ projects: [+ {+ name: project,+ documents: [+ {+ cases: [+ {+ caseId: `case-${project}`,+ name: `${project} visual case`,+ status,+ attempts: attempts.map((statuses, attemptIndex) => ({+ status: statuses.every((item) => item === 'success')+ ? 'success'+ : 'failed',+ steps: statuses.map((stepStatus, stepIndex) => ({+ id: `assert-${attemptIndex}-${stepIndex}`,+ node: assertionCount || assertionAttempts ? 'aiAssert' : 'aiAct',+ title: `Evidence ${attemptIndex}-${stepIndex}`,+ status: stepStatus,+ ...(stepStatus === 'failed'+ ? {+ error: {+ message: `Fixture error ${attemptIndex}-${stepIndex}`,+ },+ }+ : {}),+ agentDetails: [{ reportId, executionId: `execution-${attemptIndex}-${stepIndex}` }],+ })),+ })),+ },+ ],+ },+ ],+ },+ ],+ };+ return `<script type="midscene_web_dump" data-report-id="${reportId}">${JSON.stringify({ executions })}</script>+${attempts+ .flatMap((statuses, attemptIndex) =>+ statuses.map(+ (_stepStatus, stepIndex) =>+ `<script type="midscene-image" data-id="screenshot-${attemptIndex}-${stepIndex}">data:image/jpeg;base64,/9j/2Q==</script>`,+ ),+ )+ .join('\n')}+<script type="midscene_test_run_dump">${JSON.stringify(run)}</script>`;}const fixtureHtml = `<!doctype html><html><body>report@@ -52,7 +138,7 @@ const shellFixtureHtml = `<!doctype html><html><body>${shellPrompts})}</script><script type="midscene-image" data-id="image-${index}">data:image/jpeg;base64,/9j/2Q==</script>`,)- .join('')}${runnerScript({ project: 'omarchy-shell', startedAt: '2026-09-15T12:05:00Z' })}</body></html>`;+ .join('')}${runnerScript({ assertionCount: 3, project: 'omarchy-shell', startedAt: '2026-09-15T12:05:00Z' })}</body></html>`;async function fixtureDirectory(root) {const reportDirectory = path.join(root, 'artifact', 'report');@@ -60,6 +146,10 @@ async function fixtureDirectory(root) {await writeFile(path.join(reportDirectory, 'test-run-ubuntu.html'), fixtureHtml);await writeFile(path.join(reportDirectory, 'agent-detail.html'), '<html>intermediate Agent report</html>');await writeFile(path.join(path.dirname(reportDirectory), 'report-preview.png'), 'preview');+ await writeFile(+ path.join(path.dirname(reportDirectory), 'case-preview-ubuntu-case-ubuntu.jpg'),+ 'ubuntu case preview',+ );return path.dirname(reportDirectory);}@@ -96,9 +186,11 @@ test('simulates a first deployment when Pages returns 404', async (context) => {});context.after(server.close);- const manifest = await buildPagesReport(- options(reportDirectory, siteDirectory, server.url),- );+ const manifest = await buildPagesReport({+ ...options(reportDirectory, siteDirectory, server.url),+ 'auxiliary-project': 'ubuntu-polishing',+ 'auxiliary-report-label': 'Polishing overlay report',+ });assert.equal(manifest.reports.length, 1);assert.equal(manifest.reports[0].runId, '200');@@ -114,17 +206,31 @@ test('simulates a first deployment when Pages returns 404', async (context) => {assert.match(indexHtml, /Run ID/);assert.match(indexHtml, /Distribution/);assert.match(indexHtml, /Ubuntu 22\.04/);+ const runIndex = await readFile(+ path.join(siteDirectory, 'reports', '200', 'index.html'),+ 'utf8',+ );+ assert.match(runIndex, /Node screenshot/);+ assert.match(runIndex, /AI response \/ error/);+ assert.match(runIndex, /ubuntu visual case/);+ assert.match(+ runIndex,+ /native-report\.html#runner-step=assert-0-0/,+ );assert.equal(await readFile(- path.join(siteDirectory, 'reports', '200', 'index.html'),+ path.join(siteDirectory, 'reports', '200', 'native-report.html'),'utf8',),fixtureHtml,);assert.deepEqual(manifest.reports[0].files, ['reports/200/index.html',+ 'reports/200/native-report.html','reports/200/report-preview.png',+ 'reports/200/case-preview-ubuntu-case-ubuntu.jpg',]);+ assert.equal(manifest.reports[0].entries.length, 1);assert.equal(await readFile(path.join(siteDirectory, 'reports', '200', 'report-preview.png'),@@ -146,29 +252,96 @@ test('publishes the Doubao Say report as the primary CI entrance', async (contexpath.join(reportDirectory, 'auxiliary-report-preview.png'),'auxiliary preview',);+ await writeFile(+ path.join(reportDirectory, 'case-preview-omarchy-shell-case-omarchy-shell.jpg'),+ 'shell case preview',+ );const siteDirectory = path.join(root, 'site');const server = await startServer((_request, response) =>response.writeHead(404).end(),);context.after(server.close);- const manifest = await buildPagesReport(- options(reportDirectory, siteDirectory, server.url),- );+ const manifest = await buildPagesReport({+ ...options(reportDirectory, siteDirectory, server.url),+ 'auxiliary-project': 'omarchy-shell',+ 'auxiliary-report-label': 'Omarchy visual checks',+ });assert.equal(manifest.reports[0].testCount, 2);assert.equal(manifest.reports[0].successRate, 100);+ assert.deepEqual(manifest.reports[0].entries, [+ {+ role: 'primary',+ project: 'ubuntu',+ label: 'Doubao Say',+ status: 'success',+ previewStep: 'last',+ reportPath: 'reports/200/native-report.html',+ previewPath: 'reports/200/report-preview.png',+ scenarios: { passed: 1, total: 1 },+ assertions: { passed: 0, total: 0 },+ cases: [+ {+ caseId: 'case-ubuntu',+ name: 'ubuntu visual case',+ status: 'success',+ stepId: 'assert-0-0',+ selection: 'last-screenshot',+ description: 'AI explanation 0-0',+ descriptionKind: 'ai',+ previewPath: 'reports/200/case-preview-ubuntu-case-ubuntu.jpg',+ },+ ],+ },+ {+ role: 'auxiliary',+ project: 'omarchy-shell',+ label: 'Omarchy visual checks',+ status: 'success',+ previewStep: 'last',+ reportPath: 'reports/200/auxiliary-report.html',+ previewPath: 'reports/200/auxiliary-report-preview.png',+ scenarios: { passed: 1, total: 1 },+ assertions: { passed: 3, total: 3 },+ cases: [+ {+ caseId: 'case-omarchy-shell',+ name: 'omarchy-shell visual case',+ status: 'success',+ stepId: 'assert-0-2',+ selection: 'last-screenshot',+ description: 'AI explanation 0-2',+ descriptionKind: 'ai',+ previewPath:+ 'reports/200/case-preview-omarchy-shell-case-omarchy-shell.jpg',+ },+ ],+ },+ ]);assert.deepEqual(manifest.reports[0].files, ['reports/200/index.html',+ 'reports/200/native-report.html','reports/200/auxiliary-report.html','reports/200/report-preview.png','reports/200/auxiliary-report-preview.png',+ 'reports/200/case-preview-ubuntu-case-ubuntu.jpg',+ 'reports/200/case-preview-omarchy-shell-case-omarchy-shell.jpg',]);- const publishedReport = await readFile(+ const publishedIndex = await readFile(path.join(siteDirectory, 'reports', '200', 'index.html'),'utf8',);- assert.equal(publishedReport, fixtureHtml);+ assert.match(publishedIndex, /Doubao Say/);+ assert.match(publishedIndex, /Omarchy visual checks/);+ assert.match(publishedIndex, /AI response \/ error/);+ assert.equal(+ await readFile(+ path.join(siteDirectory, 'reports', '200', 'native-report.html'),+ 'utf8',+ ),+ fixtureHtml,+ );assert.equal(await readFile(path.join(siteDirectory, 'reports', '200', 'auxiliary-report.html'),@@ -197,6 +370,46 @@ test('publishes the Doubao Say report as the primary CI entrance', async (contex);});+test('reports visual assertions from the final retry attempt only', async (context) => {+ const root = await mkdtemp(path.join(os.tmpdir(), 'pages-retry-'));+ const reportDirectory = path.join(root, 'artifact', 'report');+ await mkdir(reportDirectory, { recursive: true });+ const retriedReport = `<!doctype html><html><body>${runnerScript({+ assertionAttempts: [['failed'], ['success', 'success']],+ project: 'ubuntu',+ startedAt: '2026-09-15T12:00:00Z',+ })}</body></html>`;+ await writeFile(+ path.join(reportDirectory, 'test-run-retried.html'),+ retriedReport,+ );+ await writeFile(+ path.join(path.dirname(reportDirectory), 'report-preview.png'),+ 'preview',+ );+ await writeFile(+ path.join(+ path.dirname(reportDirectory),+ 'case-preview-ubuntu-case-ubuntu.jpg',+ ),+ 'retry preview',+ );+ const siteDirectory = path.join(root, 'site');+ const server = await startServer((_request, response) =>+ response.writeHead(404).end(),+ );+ context.after(server.close);++ const manifest = await buildPagesReport(+ options(path.dirname(reportDirectory), siteDirectory, server.url),+ );++ assert.deepEqual(manifest.reports[0].entries[0].assertions, {+ passed: 2,+ total: 2,+ });+});+test('publishes a failed shell report with its result in history', async (context) => {const root = await mkdtemp(path.join(os.tmpdir(), 'pages-failed-'));const reportDirectory = await fixtureDirectory(root);@@ -214,6 +427,13 @@ test('publishes a failed shell report with its result in history', async (contexpath.join(reportDirectory, 'auxiliary-report-preview.png'),'auxiliary failed',);+ await writeFile(+ path.join(+ reportDirectory,+ 'case-preview-omarchy-shell-case-omarchy-shell.jpg',+ ),+ 'shell failure preview',+ );const siteDirectory = path.join(root, 'site');const server = await startServer((_request, response) =>response.writeHead(404).end(),@@ -221,7 +441,11 @@ test('publishes a failed shell report with its result in history', async (contexcontext.after(server.close);const manifest = await buildPagesReport(- options(reportDirectory, siteDirectory, server.url),+ {+ ...options(reportDirectory, siteDirectory, server.url),+ 'auxiliary-project': 'omarchy-shell',+ 'auxiliary-report-label': 'Omarchy visual checks',+ },);assert.equal(manifest.reports[0].successRate, 50);@@ -244,6 +468,13 @@ test('keeps only the latest failed retry for an Omarchy project', async (contextawait writeFile(path.join(reportPath, 'test-run-retry-1.html'), firstFailure);await writeFile(path.join(reportPath, 'test-run-retry-2.html'), finalFailure);await writeFile(path.join(reportDirectory, 'report-preview.png'), 'failed');+ await writeFile(+ path.join(+ reportDirectory,+ 'case-preview-omarchy-onboarding-case-omarchy-onboarding.jpg',+ ),+ 'failure preview',+ );const siteDirectory = path.join(root, 'site');const server = await startServer((_request, response) =>response.writeHead(404).end(),@@ -260,11 +491,19 @@ test('keeps only the latest failed retry for an Omarchy project', async (contextassert.equal(manifest.reports[0].testCount, 1);assert.deepEqual(manifest.reports[0].files, ['reports/200/index.html',+ 'reports/200/native-report.html','reports/200/report-preview.png',+ 'reports/200/case-preview-omarchy-onboarding-case-omarchy-onboarding.jpg',]);+ const failedRunIndex = await readFile(+ path.join(siteDirectory, 'reports', '200', 'index.html'),+ 'utf8',+ );+ assert.match(failedRunIndex, /❌ Failed/);+ assert.match(failedRunIndex, /Error:/);assert.equal(await readFile(- path.join(siteDirectory, 'reports', '200', 'index.html'),+ path.join(siteDirectory, 'reports', '200', 'native-report.html'),'utf8',),finalFailure,@@ -322,6 +561,7 @@ test('restores retained history before adding the new run', async (context) => {'utf8',),);+ assert.equal(writtenManifest.version, 4);assert.equal(writtenManifest.reports[0].reportPath, 'reports/200/index.html');assert.equal(writtenManifest.reports[0].workflowUrl,@@ -329,6 +569,61 @@ test('restores retained history before adding the new run', async (context) => {);});+test('restores version 4 history created before node text evidence', async (context) => {+ const root = await mkdtemp(path.join(os.tmpdir(), 'pages-v4-history-'));+ const reportDirectory = await fixtureDirectory(root);+ const siteDirectory = path.join(root, 'site');+ const files = [+ 'reports/100/index.html',+ 'reports/100/report-preview.png',+ 'reports/100/case-preview-ubuntu-old-case.jpg',+ ];+ const oldEntry = {+ runId: '100',+ generatedAt: '2026-09-14T12:00:00.000Z',+ label: 'Ubuntu 22.04',+ successRate: 100,+ testCount: 1,+ modelCallCount: 1,+ averageDurationMs: 4000,+ tokenUsage: 100,+ workflowUrl: 'https://github.com/quanru/doubao-say/actions/runs/100',+ reportPath: files[0],+ files,+ entries: [{+ role: 'primary', project: 'ubuntu', label: 'Doubao Say',+ status: 'success', previewStep: 'last', reportPath: files[0],+ previewPath: files[1], scenarios: { passed: 1, total: 1 },+ assertions: { passed: 1, total: 1 },+ cases: [{+ caseId: 'old-case', name: 'Old visual case', status: 'success',+ stepId: 'old-step', selection: 'last-screenshot', previewPath: files[2],+ }],+ }],+ };+ const server = await startServer((request, response) => {+ if (request.url === '/reports/manifest.json') {+ response.setHeader('content-type', 'application/json');+ response.end(JSON.stringify({ version: 4, reports: [oldEntry] }));+ return;+ }+ const file = files.find((candidate) => `/${candidate}` === request.url);+ if (!file) return response.writeHead(404).end();+ response.setHeader(+ 'content-type',+ file.endsWith('.html') ? 'text/html; charset=utf-8' : 'image/png',+ );+ response.end(file);+ });+ context.after(server.close);++ const manifest = await buildPagesReport(+ options(reportDirectory, siteDirectory, server.url),+ );+ assert.deepEqual(manifest.reports.map((report) => report.runId), ['200', '100']);+ assert.equal(manifest.reports[1].entries[0].cases[0].description, undefined);+});+test('stops when a manifest exists but an old report cannot be restored', async (context) => {const root = await mkdtemp(path.join(os.tmpdir(), 'pages-failure-'));const reportDirectory = await fixtureDirectory(root);@@ -373,3 +668,320 @@ test('rejects retention outside the supported range', async (context) => {await assert.rejects(buildPagesReport(invalid), /integer from 1 to 50/);});++test('rejects an undeclared report project', async (context) => {+ const root = await mkdtemp(path.join(os.tmpdir(), 'pages-project-'));+ const reportDirectory = await fixtureDirectory(root);+ await writeFile(+ path.join(reportDirectory, 'report', 'test-run-shell.html'),+ shellFixtureHtml,+ );+ const server = await startServer((_request, response) =>+ response.writeHead(404).end(),+ );+ context.after(server.close);++ await assert.rejects(+ buildPagesReport(+ options(reportDirectory, path.join(root, 'site'), server.url),+ ),+ /Unexpected Midscene Test project\(s\): omarchy-shell/,+ );+});++test('renders one full-width section per structured report entry', () => {+ const manifest = {+ reports: [+ {+ runId: '200',+ entries: [+ {+ role: 'primary',+ project: 'ubuntu',+ label: 'Doubao Say',+ status: 'success',+ previewStep: 'last',+ reportPath: 'reports/200/index.html',+ previewPath: 'reports/200/report-preview.png',+ scenarios: { passed: 6, total: 6 },+ assertions: { passed: 5, total: 5 },+ cases: [+ {+ caseId: 'case-ubuntu',+ name: 'Launch and finish onboarding',+ status: 'success',+ stepId: 'case-ubuntu:steps:8',+ selection: 'last-screenshot',+ description: 'The setup completion state is visible.',+ descriptionKind: 'ai',+ previewPath:+ 'reports/200/case-preview-ubuntu-case-ubuntu.jpg',+ },+ ],+ },+ {+ role: 'auxiliary',+ project: 'ubuntu-polishing',+ label: 'Polishing overlay report',+ status: 'success',+ previewStep: 'last',+ reportPath: 'reports/200/auxiliary-report.html',+ previewPath: 'reports/200/auxiliary-report-preview.png',+ scenarios: { passed: 1, total: 1 },+ assertions: { passed: 8, total: 8 },+ cases: [+ {+ caseId: 'case-polishing',+ name: 'Polish selected text',+ status: 'success',+ stepId: 'case-polishing:steps:5',+ selection: 'last-screenshot',+ description: 'The polished text is visible.',+ descriptionKind: 'ai',+ previewPath:+ 'reports/200/case-preview-ubuntu-polishing-case-polishing.jpg',+ },+ ],+ },+ ],+ },+ ],+ };+ const summary = renderReportSummary({+ manifest,+ pagesUrl: 'https://example.test/doubao-say/',+ producerResult: 'success',+ runId: '200',+ summaryTitle: 'Ubuntu',+ });++ assert.match(summary, /Ubuntu × Midscene · passed/);+ assert.match(summary, /Doubao Say: 6\/6 scenarios passed/);+ assert.match(summary, /Polishing overlay report: 1\/1 scenarios passed/);+ assert.match(+ summary,+ /\| Result \| Case \| Node screenshot \| AI response \/ error \|/,+ );+ assert.match(summary, /✅ Passed/);+ assert.match(+ summary,+ /index\.html#runner-step=case-ubuntu%3Asteps%3A8/,+ );+ assert.match(summary, /Last screenshot: Launch and finish onboarding/);+ assert.match(summary, /\*\*AI:\*\* The setup completion state is visible\./);+ assert.doesNotMatch(summary, /report report/);+ assert.match(summary, /Each image is the original page screenshot/);+});++test('renders singular failure copy for one available report', () => {+ const manifest = {+ reports: [+ {+ runId: '200',+ entries: [+ {+ role: 'primary',+ project: 'ubuntu',+ label: 'Doubao Say',+ status: 'failed',+ previewStep: 'last-error',+ reportPath: 'reports/200/index.html',+ previewPath: 'reports/200/report-preview.png',+ scenarios: { passed: 0, total: 1 },+ assertions: { passed: 1, total: 2 },+ cases: [+ {+ caseId: 'case-fail',+ name: 'Broken flow',+ status: 'failed',+ stepId: 'case-fail:steps:2',+ selection: 'first-failing-screenshot',+ description: 'Node "aiAssert" failed: expected state missing.',+ descriptionKind: 'error',+ previewPath:+ 'reports/200/case-preview-ubuntu-case-fail.jpg',+ },+ ],+ },+ ],+ },+ ],+ };+ const summary = renderReportSummary({+ manifest,+ pagesUrl: 'https://example.test/doubao-say',+ producerResult: 'failure',+ runId: '200',+ summaryTitle: 'Ubuntu',+ });++ assert.match(summary, /Ubuntu × Midscene · failure captured/);+ assert.match(summary, /❌ Failed/);+ assert.match(summary, /First failing screenshot: Broken flow/);+ assert.match(+ summary,+ /\*\*Error:\*\* Node "aiAssert" failed: expected state missing\./,+ );+ assert.match(+ summary,+ /index\.html#runner-step=case-fail%3Asteps%3A2/,+ );+ assert.match(summary, /Each image is the original page screenshot/);+});++test('selects the last screenshot for success and first failed screenshot for failure', () => {+ const run = {+ projects: [+ {+ name: 'ubuntu',+ documents: [+ {+ cases: [+ {+ caseId: 'passed-case',+ name: 'Passed case',+ status: 'success',+ attempts: [+ {+ status: 'success',+ steps: [+ { id: 'pass-1', status: 'success', agentDetails: [{}] },+ { id: 'pass-2', status: 'success' },+ ],+ },+ ],+ },+ {+ caseId: 'failed-case',+ name: 'Failed case',+ status: 'failed',+ attempts: [+ {+ status: 'failed',+ steps: [+ { id: 'fail-1', status: 'failed', agentDetails: [{}] },+ { id: 'fail-2', status: 'failed', agentDetails: [{}] },+ ],+ },+ ],+ },+ ],+ },+ ],+ },+ ],+ };++ assert.deepEqual(+ reportCases(run, 'ubuntu').map(({ caseId, stepId, selection }) => ({+ caseId,+ stepId,+ selection,+ })),+ [+ {+ caseId: 'passed-case',+ stepId: 'pass-1',+ selection: 'last-screenshot',+ },+ {+ caseId: 'failed-case',+ stepId: 'fail-1',+ selection: 'first-failing-screenshot',+ },+ ],+ );+});++test('pairs an original node screenshot with its AI text or error', () => {+ const successHtml = runnerScript({+ project: 'ubuntu',+ startedAt: '2026-09-15T12:00:00Z',+ });+ const success = reportCases(testRunDump(successHtml), 'ubuntu', {+ reportHtml: successHtml,+ })[0];+ assert.equal(success.descriptionKind, 'ai');+ assert.equal(success.description, 'AI explanation 0-0');+ assert.deepEqual(success.screenshot.bytes, Buffer.from('/9j/2Q==', 'base64'));++ const failureHtml = runnerScript({+ project: 'ubuntu',+ startedAt: '2026-09-15T12:00:00Z',+ status: 'failed',+ });+ const failure = reportCases(testRunDump(failureHtml), 'ubuntu', {+ reportHtml: failureHtml,+ })[0];+ assert.equal(failure.descriptionKind, 'error');+ assert.equal(failure.description, 'Fixture error 0-0');+ assert.deepEqual(failure.screenshot.bytes, Buffer.from('/9j/2Q==', 'base64'));+});++test('finds Omarchy evidence by project instead of assertion wording', async () => {+ const root = await mkdtemp(path.join(os.tmpdir(), 'shell-project-'));+ const reportDirectory = path.join(root, 'report');+ await mkdir(reportDirectory, { recursive: true });+ await writeFile(+ path.join(reportDirectory, 'test-run-shell.html'),+ shellFixtureHtml+ .replace(shellPrompts[0], 'Renamed menu assertion.')+ .replace(shellPrompts[1], 'Renamed focus assertion.')+ .replace(shellPrompts[2], 'Renamed bar assertion.'),+ );++ const report = await findShellReport(root);+ assert.deepEqual(+ report.checks.map(({ key, passed }) => ({ key, passed })),+ [+ { key: 'shutdown', passed: true },+ { key: 'focus', passed: true },+ { key: 'bar', passed: true },+ ],+ );+});++test('verifies every file and its expected content type', async () => {+ const requested = [];+ const manifest = {+ reports: [+ {+ runId: '200',+ files: [+ 'reports/200/index.html',+ 'reports/200/auxiliary-report.html',+ 'reports/200/report-preview.png',+ 'reports/200/auxiliary-report-preview.png',+ 'reports/200/case-preview-ubuntu-case-ubuntu.jpg',+ ],+ },+ ],+ };+ await verifyPublishedReport({+ manifest,+ pagesUrl: 'https://example.test/doubao-say/',+ runId: '200',+ fetchImpl: async (url) => {+ requested.push(url.href);+ return new Response(null, {+ status: 200,+ headers: {+ 'content-type': url.pathname.endsWith('.png')+ ? 'image/png'+ : url.pathname.endsWith('.jpg')+ ? 'image/jpeg'+ : 'text/html; charset=utf-8',+ },+ });+ },+ });++ assert.deepEqual(requested, [+ 'https://example.test/doubao-say/',+ 'https://example.test/doubao-say/reports/200/index.html',+ 'https://example.test/doubao-say/reports/200/auxiliary-report.html',+ 'https://example.test/doubao-say/reports/200/report-preview.png',+ 'https://example.test/doubao-say/reports/200/auxiliary-report-preview.png',+ 'https://example.test/doubao-say/reports/200/case-preview-ubuntu-case-ubuntu.jpg',+ ]);+});diff --git a/tests/e2e/README.md b/tests/e2e/README.mdindex d5e2515..a6e890c 100644--- a/tests/e2e/README.md+++ b/tests/e2e/README.md@@ -49,24 +49,38 @@ and `@midscene/computer`. Pull requests from forks are skipped because GitHubdoes not expose the required model secret to untrusted workflow code.Both distributions execute the same declarative onboarding scenario in-`cases/onboarding.yaml`. `midscene.config.ts` prepares the local Xvfb desktop,-GTK fixture or Omarchy VNC viewer. Custom `shell.*` Nodes prepare the real-Omarchy menu and bar; `cases/omarchy-shell.yaml` keeps the three pixel-level-assertions explicit. Run `npm run nodes` in this directory to regenerate the-Node reference, or `npm test -- --project ubuntu` on a prepared Linux desktop.+`cases/onboarding.yaml`, including synthetic microphone and voice checks.+Ubuntu also runs focused onboarding regressions and the synthetic post-setup+dictation flows in `cases/runtime.yaml`. `midscene.config.ts` passes each case+identity to a fresh fixture, prepares the local Xvfb desktop, GTK fixture or+Omarchy VNC viewer, and resets that state for every retry. Custom `shell.*`+Nodes prepare the real Omarchy menu and bar; `cases/omarchy-shell.yaml` keeps+the three pixel-level assertions explicit. Run `npm run nodes` in this+directory to regenerate the Node reference, or+`npm test -- --project ubuntu` on a prepared Linux desktop.+Projects use Midscene Test's case-level `retry` setting, so a failed model+attempt is rerun with a fresh fixture while successful cases are kept. Every+attempt remains visible in the generated report.Each invocation writes a unified Midscene Test HTML report under-`midscene_run/report/`; CI publishes those reports and renders the final shell-report node as its entrance image, including the node's pass or error status.+`midscene_run/report/`; CI publishes those reports and renders each project's+final node as its entrance image. A failed project instead opens and captures+its most recent error node, so the summary shows the relevant failure detail.The Ubuntu stage maps the real GTK onboarding window inside theheadless Midscene desktop. Its synthetic fixture starts signed out, opens anexplicitly labelled CI-only sign-in window, and simulates a successful returnwithout a network request or real credentials. It also performs no recording,-paste, or user-settings read. Midscene verifies the automatic transition to the+system clipboard access, global paste, or user-settings read. Midscene verifies+the automatic transition to themicrophone step, visually navigates to the shortcut page, runs the fake endpointcheck, verifies its visible feedback, continues to the voice page, checks that-navigation reset the scroll position, and completes setup. The HTML replay is-uploaded as a private workflow artifact for every run.+navigation reset the scroll position, completes a synthetic microphone check+and voice test, and finishes setup. Focused cases cover cancellation, device+changes, official API configuration, custom shortcut capture, and a synthetic+F8/Escape dictation target. The runtime target uses the real Delivery state+machine but writes only to its own GTK field, so CI never records audio or reads+or changes the runner clipboard. The HTML replay is uploaded as a private+workflow artifact for every run.The AI stage needs a multimodal model credential. Its `MIDSCENE_MODEL_*`configuration is stored only as GitHub Actions Secrets; tests contain only@@ -97,17 +111,21 @@ This demonstrates visual testing of a Wayland desktop through a VM bridge.## Ubuntu regression cases-`cases/onboarding-regressions.yaml` adds five cases: cancelling and retrying-sign-in, returning to the signed-in account page, blocking a disabled trigger-and retaining F8, toggling polishing, and correcting a failed endpoint model.-The Ubuntu project runs these alongside the successful onboarding case.+`cases/onboarding-regressions.yaml` covers ten focused cases: sign-in+cancellation and persistence, disabled and custom triggers, polishing state,+endpoint recovery, microphone checks and device changes, voice-test+cancellation, and official Volcengine API configuration. `cases/runtime.yaml`+adds successful and cancelled F8 dictation delivery. The Ubuntu project runs+these alongside the successful onboarding case.Each case receives a fresh computer agent, GTK fixture, and temporary configdirectory. Fixture cleanup completes before the next case starts. Shortcut andpolishing changes stay in memory; `synthetic-failing-model` produces a syntheticendpoint error, while `synthetic-model` succeeds without network traffic.-These cases exercise production GTK widgets with synthetic callbacks, not live-ASR, recording, credential persistence, or global shortcut delivery.+These cases exercise production GTK widgets and the Delivery state machine with+synthetic callbacks. They do not establish live ASR, recording, durable+credential persistence, system-wide shortcut capture, clipboard paste, or+delivery into an unrelated application.Run `npm test -- --project ubuntu` with the system dependencies and modelconfiguration from the Ubuntu workflow. The Omarchy projects retain their shareddiff --git a/tests/e2e/capture-report-preview.mjs b/tests/e2e/capture-report-preview.mjsindex 918ec4c..eb7eac9 100644--- a/tests/e2e/capture-report-preview.mjs+++ b/tests/e2e/capture-report-preview.mjs@@ -1,4 +1,4 @@-import { access, mkdir } from 'node:fs/promises';+import { access, mkdir, writeFile } from 'node:fs/promises';import path from 'node:path';import { pathToFileURL } from 'node:url';@@ -7,14 +7,29 @@ import puppeteer from 'puppeteer-core';import {findLatestTestReport,} from '../../scripts/omarchy-shell-evidence.mjs';+import { reportCases } from '../../scripts/report-cases.mjs';+function parseArguments(argv) {+ const options = {};+ for (let index = 0; index < argv.length; index += 2) {+ const key = argv[index];+ const value = argv[index + 1];+ if (!key?.startsWith('--') || value === undefined) {+ throw new Error(`Invalid argument near ${key ?? '<end>'}`);+ }+ options[key.slice(2)] = value;+ }+ return options;+}++const options = parseArguments(process.argv.slice(2));const reportDirectory = path.resolve(- process.argv[2] || 'tests/e2e/midscene_run',-);-const outputFile = path.resolve(- process.argv[3] || path.join(reportDirectory, 'report-preview.png'),+ options['report-dir'] || 'tests/e2e/midscene_run',);-const projectName = process.argv[4];+const primaryProject = options['primary-project'];+const auxiliaryProject = options['auxiliary-project'];+if (!primaryProject) throw new Error('Missing --primary-project');+if (!auxiliaryProject) throw new Error('Missing --auxiliary-project');const candidates = [process.env.CHROME_BIN,@@ -36,13 +51,6 @@ if (!executablePath) {throw new Error('Chrome executable was not found');}-const report = await findLatestTestReport(reportDirectory, { projectName });-const runnerDump = report.run;-if (!runnerDump) throw new Error('Midscene Test runner dump was not found');-const previewUrl = new URL(pathToFileURL(report.file));-previewUrl.hash = new URLSearchParams({ 'runner-step': 'last' }).toString();-await mkdir(path.dirname(outputFile), { recursive: true });-const browser = await puppeteer.launch({executablePath,headless: true,@@ -50,23 +58,78 @@ const browser = await puppeteer.launch({});try {- const page = await browser.newPage();- await page.setViewport({ width: 1600, height: 1000, deviceScaleFactor: 1 });- await page.goto(previewUrl.href, {- waitUntil: 'networkidle0',- });- await page.waitForSelector('[aria-label="Execution steps"]');- await page.waitForFunction(() =>- /STEPS\s*\xb7\s*STEP\s+\d+/i.test(document.body.innerText),- );- await page.evaluate(() => window.scrollTo(0, 0));- await page.waitForFunction(() =>- /Passed|Failed|Error/.test(document.body.innerText),- );- await page.screenshot({ path: outputFile, type: 'png' });- console.log(- `Captured final Midscene report node (${runnerDump.status}): ${outputFile}`,- );+ for (const [projectName, outputName, required] of [+ [primaryProject, 'report-preview.png', true],+ [auxiliaryProject, 'auxiliary-report-preview.png', false],+ ]) {+ const report = await findLatestTestReport(reportDirectory, {+ projectName,+ required,+ });+ if (!report) {+ console.log(+ `Skipped ${projectName} preview because that project did not produce a report.`,+ );+ continue;+ }+ const runnerDump = report.run;+ if (!runnerDump) throw new Error('Midscene Test runner dump was not found');+ const previewStep = runnerDump.status === 'success' ? 'last' : 'last-error';+ const previewUrl = new URL(pathToFileURL(report.file));+ previewUrl.hash = new URLSearchParams({+ 'runner-step': previewStep,+ }).toString();+ const outputFile = path.join(reportDirectory, outputName);+ await mkdir(path.dirname(outputFile), { recursive: true });++ const page = await browser.newPage();+ await page.setViewport({ width: 1600, height: 1000, deviceScaleFactor: 1 });+ await page.goto(previewUrl.href, { waitUntil: 'networkidle0' });+ await page.waitForSelector(+ '[aria-label="Execution steps"] button.is-selected .runner-step-status',+ );+ await page.waitForSelector('.runner-detail-evidence-panel');+ await page.waitForFunction((expectedStep) => {+ const buttons = [+ ...document.querySelectorAll(+ '[aria-label="Execution steps"] .runner-detail-step-group > button',+ ),+ ];+ const selected = document.querySelector(+ '[aria-label="Execution steps"] button.is-selected',+ );+ const selectedName = selected?.querySelector(+ '.runner-detail-step-copy strong',+ )?.textContent;+ const detailName = document.querySelector(+ '.runner-detail-evidence-heading h2',+ )?.textContent;+ return (+ buttons.length > 0 &&+ (expectedStep === 'last'+ ? selected === buttons.at(-1)+ : Boolean(selected?.querySelector('.runner-step-status.is-failed'))) &&+ Boolean(selectedName) &&+ selectedName === detailName+ );+ }, {}, previewStep);+ await page.evaluate(() => window.scrollTo(0, 0));+ await page.screenshot({ path: outputFile, type: 'png' });+ await page.close();+ console.log(+ `Captured Midscene report node ${previewStep} (${runnerDump.status}): ${outputFile}`,+ );++ for (const testCase of reportCases(runnerDump, projectName, {+ reportHtml: report.html,+ })) {+ const caseOutput = path.join(reportDirectory, testCase.previewFile);+ await writeFile(caseOutput, testCase.screenshot.bytes);+ console.log(+ `Extracted ${testCase.status} node screenshot for ${testCase.name} at ${testCase.stepId}: ${caseOutput}`,+ );+ }+ }} finally {await browser.close();}diff --git a/tests/e2e/cases/onboarding-regressions.yaml b/tests/e2e/cases/onboarding-regressions.yamlindex 7ba2fe6..cdcbc65 100644--- a/tests/e2e/cases/onboarding-regressions.yaml+++ b/tests/e2e/cases/onboarding-regressions.yaml@@ -1,72 +1,194 @@cases:- name: Cancel sign-in and retrysteps:- - aiAct: "Verify the current step is Sign in, the account is not signed in, and both left-arrow Previous and right-arrow Next in the fixed top navigation are disabled."- - aiAct: "Click Open Doubao sign-in exactly once, then stop."- - aiAct: "Verify the CI-only Synthetic Doubao sign-in window is visible. Close only that synthetic window using its title-bar close button, without clicking Simulate successful sign-in."- - aiAct: "Verify the synthetic sign-in window is gone, Doubao Say still shows Sign in and Not signed in, right-arrow Next remains disabled, and Open Doubao sign-in is available."- - aiAct: "Verify the visible Doubao Say window starts on the Sign in step, says the user is not signed in, and shows an Open Doubao sign-in button. Do not click anything."- - aiAct: "Click Open Doubao sign-in exactly once, then stop immediately."- - aiAct: "Verify a Synthetic Doubao sign-in window is visible and explicitly says it is CI-only, makes no network request, and uses no real credentials. Do not click anything."- - aiAct: "In the Synthetic Doubao sign-in window, click Simulate successful sign-in exactly once, then stop immediately."- - aiAct: "Verify the synthetic sign-in window closed and the visible Doubao Say window automatically advanced to the Microphone step with a right-arrow Next button in the fixed top navigation."+ - aiAssert: The current step is Sign in and both left-arrow Previous and right-arrow Next in the fixed top navigation are disabled.+ - aiAct: Scroll inside the Sign in content panel until Open Doubao sign-in is fully visible.+ - aiTap: Open Doubao sign-in button in the Sign in content panel+ - wait: { duration: 500 }+ - aiAssert: The CI-only Synthetic Doubao sign-in window is visible.+ - computer.keyPress: { keyName: Escape }+ - wait: { duration: 500 }+ - aiAssert: The synthetic sign-in window is gone, Doubao Say remains on Sign in, and right-arrow Next remains disabled.+ - aiAct: Scroll inside the Sign in content panel until Open Doubao sign-in is fully visible.+ - aiTap: Open Doubao sign-in button in the Sign in content panel+ - wait: { duration: 500 }+ - aiAssert: A Synthetic Doubao sign-in window is visible and explicitly says it is CI-only, makes no network request, and uses no real credentials.+ - aiTap: Simulate successful sign-in button in the Synthetic Doubao sign-in window+ - wait: { duration: 500 }+ - aiAssert: The synthetic sign-in window closed and Doubao Say automatically advanced to the Microphone step.- name: Preserve signed-in account across backward navigationsteps:- - aiAct: "Verify the visible Doubao Say window starts on the Sign in step, says the user is not signed in, and shows an Open Doubao sign-in button. Do not click anything."- - aiAct: "Click Open Doubao sign-in exactly once, then stop immediately."- - aiAct: "Verify a Synthetic Doubao sign-in window is visible and explicitly says it is CI-only, makes no network request, and uses no real credentials. Do not click anything."- - aiAct: "In the Synthetic Doubao sign-in window, click Simulate successful sign-in exactly once, then stop immediately."- - aiAct: "Verify the synthetic sign-in window closed and the visible Doubao Say window automatically advanced to the Microphone step with a right-arrow Next button in the fixed top navigation."- - aiAct: "Scroll to the bottom of the Microphone central content panel, then click left-arrow Previous in the fixed top navigation exactly once and stop."- - aiAct: "Verify the Sign in step shows the heading Your voice, wherever you type near the top of the content without scrolling, and left-arrow Previous is disabled while right-arrow Next is enabled."- - aiAct: "Scroll within the Sign in content if needed. Verify it says Signed in and shows Sign in again / change account. Do not open sign-in."- - aiAct: "Click right-arrow Next in the fixed top navigation exactly once, then stop."- - aiAct: "Verify the Microphone step and its heading Let's make sure we can hear you are visible without scrolling, and no synthetic sign-in window is open."+ - aiAssert: The visible Doubao Say window starts on the Sign in step and says the user is not signed in.+ - aiAct: Scroll inside the Sign in content panel until Open Doubao sign-in is fully visible.+ - aiTap: Open Doubao sign-in button in the Sign in content panel+ - wait: { duration: 500 }+ - aiAssert: A Synthetic Doubao sign-in window is visible and explicitly says it is CI-only, makes no network request, and uses no real credentials.+ - aiTap: Simulate successful sign-in button in the Synthetic Doubao sign-in window+ - wait: { duration: 500 }+ - aiAssert: The synthetic sign-in window closed and Doubao Say automatically advanced to the Microphone step.+ - aiAct: Scroll to the bottom of the Microphone central content panel.+ - aiTap: Left-arrow Previous button in the fixed top navigation+ - aiAssert: The Sign in step shows the heading Your voice, wherever you type; left-arrow Previous is disabled and right-arrow Next is enabled.+ - aiAct: Scroll inside the Sign in content panel until the signed-in account status and Sign in again / change account are fully visible.+ - aiAssert: The account status says Signed in and Sign in again / change account is available.+ - aiTap: Right-arrow Next button in the fixed top navigation+ - aiAssert: The Microphone step shows Let's make sure we can hear you, and no synthetic sign-in window is open.- name: Require an enabled trigger and retain the replacementsteps:- - aiAct: "Verify the visible Doubao Say window starts on the Sign in step, says the user is not signed in, and shows an Open Doubao sign-in button. Do not click anything."- - aiAct: "Click Open Doubao sign-in exactly once, then stop immediately."- - aiAct: "Verify a Synthetic Doubao sign-in window is visible and explicitly says it is CI-only, makes no network request, and uses no real credentials. Do not click anything."- - aiAct: "In the Synthetic Doubao sign-in window, click Simulate successful sign-in exactly once, then stop immediately."- - aiAct: "Verify the synthetic sign-in window closed and the visible Doubao Say window automatically advanced to the Microphone step with a right-arrow Next button in the fixed top navigation."- - aiAct: "Click right-arrow Next in the fixed top navigation exactly once, then stop."- - aiAct: "Verify the current step is Trigger key and the heading Choose how to start speaking is visible. Do not navigate."- - aiAct: "In the trigger selection dropdown below Active trigger, select Disabled. Do not change Voice polishing."- - aiAct: "Click right-arrow Next in the fixed top navigation exactly once, then stop."- - aiAct: "Verify the current step is still Trigger key and the message Choose an enabled trigger to continue is visible."- - aiAct: "In the trigger selection dropdown select F8. Verify Active trigger: F8 is visible and F8 is selected in the trigger dropdown."- - aiAct: "Click right-arrow Next in the fixed top navigation exactly once, then stop."- - aiAct: "Verify the current step is Voice test, the heading Try a sentence. Nothing gets pasted is visible, and right-arrow Next is disabled."- - aiAct: "Click left-arrow Previous exactly once, then stop."- - aiAct: "Verify the Trigger key step still shows Active trigger: F8 and F8 is selected in the trigger dropdown."+ - aiAssert: The visible Doubao Say window starts on the Sign in step and says the user is not signed in.+ - aiAct: Scroll inside the Sign in content panel until Open Doubao sign-in is fully visible.+ - aiTap: Open Doubao sign-in button in the Sign in content panel+ - wait: { duration: 500 }+ - aiAssert: A Synthetic Doubao sign-in window is visible and explicitly says it is CI-only, makes no network request, and uses no real credentials.+ - aiTap: Simulate successful sign-in button in the Synthetic Doubao sign-in window+ - wait: { duration: 500 }+ - aiAssert: The synthetic sign-in window closed and Doubao Say automatically advanced to the Microphone step.+ - aiTap: Right-arrow Next button in the fixed top navigation+ - aiAssert: The current step is Trigger key and the heading Choose how to start speaking is visible.+ - aiAct: In the trigger selection dropdown below Active trigger, select Disabled. Do not change Voice polishing.+ - aiTap: Right-arrow Next button in the fixed top navigation+ - aiAssert: The current step is still Trigger key and the message Choose an enabled trigger to continue is visible.+ - aiAct: In the trigger selection dropdown select F8.+ - aiAssert: Active trigger shows F8 and F8 is selected in the trigger dropdown.+ - aiTap: Right-arrow Next button in the fixed top navigation+ - aiAssert: The current step is Voice test, the heading Try a sentence. Nothing gets pasted is visible, and right-arrow Next is disabled.+ - aiTap: Left-arrow Previous button in the fixed top navigation+ - aiAssert: The Trigger key step still shows Active trigger F8 and F8 is selected in the trigger dropdown.- name: Toggle polishing without losing configurationsteps:- - aiAct: "Verify the visible Doubao Say window starts on the Sign in step, says the user is not signed in, and shows an Open Doubao sign-in button. Do not click anything."- - aiAct: "Click Open Doubao sign-in exactly once, then stop immediately."- - aiAct: "Verify a Synthetic Doubao sign-in window is visible and explicitly says it is CI-only, makes no network request, and uses no real credentials. Do not click anything."- - aiAct: "In the Synthetic Doubao sign-in window, click Simulate successful sign-in exactly once, then stop immediately."- - aiAct: "Verify the synthetic sign-in window closed and the visible Doubao Say window automatically advanced to the Microphone step with a right-arrow Next button in the fixed top navigation."- - aiAct: "Click right-arrow Next in the fixed top navigation exactly once, then stop."- - aiAct: "Verify the current step is Trigger key and the heading Choose how to start speaking is visible. Do not navigate."- - aiAct: "Scroll inside the central content panel to Voice polishing. Turn off the switch beside that heading."- - aiAct: "Verify Voice polishing disabled is visible, the switch is off, and the polishing Base URL and Model fields are hidden."- - aiAct: "Turn on the switch beside Voice polishing."- - aiAct: "Verify Voice polishing enabled is visible, the switch is on, and the Base URL and Model fields have returned. Scroll within the content if needed and verify Model still contains synthetic-model."+ - aiAssert: The visible Doubao Say window starts on the Sign in step and says the user is not signed in.+ - aiAct: Scroll inside the Sign in content panel until Open Doubao sign-in is fully visible.+ - aiTap: Open Doubao sign-in button in the Sign in content panel+ - wait: { duration: 500 }+ - aiAssert: A Synthetic Doubao sign-in window is visible and explicitly says it is CI-only, makes no network request, and uses no real credentials.+ - aiTap: Simulate successful sign-in button in the Synthetic Doubao sign-in window+ - wait: { duration: 500 }+ - aiAssert: The synthetic sign-in window closed and Doubao Say automatically advanced to the Microphone step.+ - aiTap: Right-arrow Next button in the fixed top navigation+ - aiAssert: The current step is Trigger key and the heading Choose how to start speaking is visible.+ - aiAct: Scroll inside the central content panel until the Voice polishing heading and switch are fully visible.+ - aiTap: Enabled switch beside Voice polishing+ - aiAssert: Voice polishing disabled is visible, the switch is off, and the polishing Base URL and Model fields are hidden.+ - aiTap: Disabled switch beside Voice polishing+ - aiAssert: Voice polishing enabled is visible and the switch is on.+ - aiAct: Scroll downward inside the central content panel until the Voice polishing Model input and its complete value are fully visible.+ - aiAssert: The Voice polishing Model input contains exactly synthetic-model.- name: Recover from an endpoint failuresteps:- - aiAct: "Verify the visible Doubao Say window starts on the Sign in step, says the user is not signed in, and shows an Open Doubao sign-in button. Do not click anything."- - aiAct: "Click Open Doubao sign-in exactly once, then stop immediately."- - aiAct: "Verify a Synthetic Doubao sign-in window is visible and explicitly says it is CI-only, makes no network request, and uses no real credentials. Do not click anything."- - aiAct: "In the Synthetic Doubao sign-in window, click Simulate successful sign-in exactly once, then stop immediately."- - aiAct: "Verify the synthetic sign-in window closed and the visible Doubao Say window automatically advanced to the Microphone step with a right-arrow Next button in the fixed top navigation."- - aiAct: "Click right-arrow Next in the fixed top navigation exactly once, then stop."- - aiAct: "Verify the current step is Trigger key and the heading Choose how to start speaking is visible. Do not navigate."- - aiAct: "Scroll inside the central content panel to Voice polishing. Replace the Model field with synthetic-failing-model, then click Test endpoint exactly once, scrolling within the panel if needed."- - aiAct: "Verify the visible endpoint feedback says Endpoint test failed: Synthetic endpoint unavailable, and the enabled retry button says Test failed — try again."- - aiAct: "Scroll upward inside the central content panel until the Voice polishing Model input is visible. Stop with that input on screen."- - aiAct: "In the Model input, select all existing text and replace it with exactly synthetic-model. Do not change Base URL or API Key. Stop after entering the new value."- - aiAct: "Verify the Model input now contains exactly synthetic-model, without the word failing. Do not click or type anything."- - aiAct: "Scroll downward inside the central content panel until the Test failed — try again button is visible. Do not click it yet."- - aiAct: "Click the Test failed — try again button exactly once to run a new endpoint test. Stop immediately after the click."- - aiAct: "Scroll within the central content panel if needed until the endpoint result text below the retry button is fully visible."- - aiAct: "Verify the endpoint result says Endpoint works: Synthetic endpoint response, the enabled button says Endpoint works, and the previous Synthetic endpoint unavailable error is no longer visible."+ - aiAssert: The visible Doubao Say window starts on the Sign in step and says the user is not signed in.+ - aiAct: Scroll inside the Sign in content panel until Open Doubao sign-in is fully visible.+ - aiTap: Open Doubao sign-in button in the Sign in content panel+ - wait: { duration: 500 }+ - aiAssert: A Synthetic Doubao sign-in window is visible and explicitly says it is CI-only, makes no network request, and uses no real credentials.+ - aiTap: Simulate successful sign-in button in the Synthetic Doubao sign-in window+ - wait: { duration: 500 }+ - aiAssert: The synthetic sign-in window closed and Doubao Say automatically advanced to the Microphone step.+ - aiTap: Right-arrow Next button in the fixed top navigation+ - aiAssert: The current step is Trigger key and the heading Choose how to start speaking is visible.+ - aiAct: Scroll inside the central content panel until the Voice polishing Model input is fully visible. Do not click Test endpoint.+ - computer.inputText:+ target: Voice polishing Model input+ value: synthetic-failing-model+ - aiAssert: The Voice polishing Model input contains exactly synthetic-failing-model.+ - aiAct: Scroll downward inside the central content panel until the Test endpoint button is fully visible.+ - aiAssert: The Test endpoint button in Voice polishing is fully visible.+ - aiTap: Test endpoint button in the Voice polishing section+ - wait: { duration: 750 }+ - aiAssert: "The visible endpoint feedback says Endpoint test failed: Synthetic endpoint unavailable, and the enabled retry button says Test failed — try again."+ - aiAct: Scroll upward inside the central content panel until the Model input under Voice polishing is fully visible. Do not click the retry button.+ - computer.inputText:+ target: Model input under Voice polishing+ value: synthetic-model+ - aiAssert: The Voice polishing Model input contains exactly synthetic-model, without the word failing.+ - aiAct: Scroll inside the central content panel until the Test failed — try again button is fully visible.+ - aiTap: Test failed — try again button in the Voice polishing section+ - wait: { duration: 750 }+ - aiAct: Scroll inside the central content panel until the endpoint result text below the retry button is fully visible.+ - aiAssert: "The endpoint result says Endpoint works: Synthetic endpoint response, the enabled button says Endpoint works, and the previous Synthetic endpoint unavailable error is no longer visible."+ - name: Microphone check gates setup completion+ steps:+ - fixture.prepare: { mode: microphone-gate }+ - aiAssert: The visible Doubao Say window starts on the Microphone step, shows Synthetic microphone one, and offers Check microphone · 3 seconds.+ - aiTap: Right-arrow Next button in the fixed top navigation+ - aiTap: Right-arrow Next button in the fixed top navigation+ - aiAct: Scroll down inside the Voice test content panel until the Finish setup button is fully visible.+ - aiAssert: The current step is Voice test and the Finish setup button is visibly disabled.+ - aiTap: Left-arrow Previous button in the fixed top navigation+ - aiTap: Left-arrow Previous button in the fixed top navigation+ - aiTap: Check microphone · 3 seconds button on the Microphone step+ - wait: { duration: 750 }+ - aiAssert: A visible message says Microphone is working and instructs the user to continue to the trigger key step.+ - aiTap: Right-arrow Next button in the fixed top navigation+ - aiTap: Right-arrow Next button in the fixed top navigation+ - aiAct: Scroll down inside the Voice test content panel until the Finish setup button is fully visible.+ - aiAssert: The Finish setup button is visibly enabled.+ - name: Complete and cancel a voice test safely+ steps:+ - fixture.prepare: { mode: voice-test }+ - aiAssert: The visible Doubao Say window starts on the Microphone step and the microphone is already configured.+ - aiTap: Right-arrow Next button in the fixed top navigation+ - aiTap: Right-arrow Next button in the fixed top navigation+ - aiAssert: The current step is Voice test and Start voice test is available.+ - aiAct: Scroll down inside the Voice test content panel until the Finish setup button is fully visible.+ - aiAssert: The Finish setup button is visibly disabled.+ - aiTap: Start voice test button in the Voice test content panel+ - wait: { duration: 750 }+ - aiAssert: Synthetic voice test transcript is visible, and both Finish & check result and Cancel test are available.+ - aiTap: Cancel test button in the Voice test content panel+ - wait: { duration: 500 }+ - aiAssert: The voice-test transcript is empty after cancellation.+ - aiAct: Scroll down inside the Voice test content panel until the setup button is fully visible.+ - aiAssert: The disabled setup button visibly says Voice test cancelled and nothing pasted or sent.+ - aiTap: Start voice test button in the Voice test content panel+ - wait: { duration: 750 }+ - aiAssert: Synthetic voice test transcript is visible, and Finish & check result is available again.+ - aiTap: Finish & check result button in the Voice test content panel+ - wait: { duration: 750 }+ - aiAct: Scroll down inside the Voice test content panel until the setup button is fully visible.+ - aiAssert: The enabled setup button visibly says Voice test passed and nothing pasted or sent.+ - name: Switch to Volcengine and validate credentials+ steps:+ - fixture.prepare: { mode: volcengine }+ - aiAssert: The visible Doubao Say window starts on Sign in with Doubao account selected and right-arrow Next disabled.+ - aiAct: In Recognition service, select Volcengine API exactly once.+ - aiAct: Scroll down inside the central content panel until the API Key field and Test API key button are both visible.+ - aiAssert: The page is now Recognition, shows an empty API Key field, hides Open Doubao sign-in, and both Test API key and right-arrow Next are visibly disabled.+ - computer.inputText:+ target: API Key field+ value: synthetic-ci-key+ - aiAssert: The API Key field visibly contains a non-empty masked value and the Test API key button is enabled.+ - aiTap: Test API key button below the API Key field+ - wait: { duration: 750 }+ - aiAct: Scroll downward exactly once inside the central content panel so the API key test result is visible, then stop.+ - aiAssert: The result says API key accepted by synthetic endpoint and the page reports that the official API is ready.+ - aiTap: Right-arrow Next button in the fixed top navigation+ - aiAssert: The current step is Microphone and the heading Let's make sure we can hear you is visible.+ - name: Changing microphone requires another check+ steps:+ - fixture.prepare: { mode: microphone-change }+ - aiAssert: The visible Doubao Say window starts on the Microphone step with Synthetic microphone one selected.+ - aiAct: In the microphone dropdown, select Synthetic microphone two exactly once.+ - aiAssert: A visible message says Microphone saved and requires a new three-second check.+ - aiTap: Right-arrow Next button in the fixed top navigation+ - aiTap: Right-arrow Next button in the fixed top navigation+ - aiAct: Scroll down inside the Voice test content panel until the Finish setup button is fully visible.+ - aiAssert: The Finish setup button is visibly disabled.+ - aiTap: Left-arrow Previous button in the fixed top navigation+ - aiTap: Left-arrow Previous button in the fixed top navigation+ - aiTap: Check microphone · 3 seconds button on the Microphone step+ - wait: { duration: 750 }+ - aiAssert: The result says Microphone is working and Synthetic microphone two remains selected.+ - aiTap: Right-arrow Next button in the fixed top navigation+ - aiTap: Right-arrow Next button in the fixed top navigation+ - aiAct: Scroll down inside the Voice test content panel until the Finish setup button is fully visible.+ - aiAssert: The Finish setup button is visibly enabled.+ - name: Capture and retain a custom trigger shortcut+ steps:+ - fixture.prepare: { mode: shortcut-capture }+ - aiTap: Right-arrow Next button in the fixed top navigation+ - aiAssert: The Trigger key page shows Active trigger fn and a trigger selection dropdown.+ - aiAct: In the trigger selection dropdown, select Record a shortcut… exactly once and wait for the synthetic shortcut capture to finish.+ - aiAssert: The active trigger now shows the control symbol ⌃ plus F8, and the trigger dropdown displays that same custom shortcut.+ - aiTap: Right-arrow Next button in the fixed top navigation+ - aiTap: Left-arrow Previous button in the fixed top navigation+ - aiAssert: The Trigger key page still shows the custom ⌃ plus F8 shortcut as the active and selected trigger.diff --git a/tests/e2e/cases/onboarding.yaml b/tests/e2e/cases/onboarding.yamlindex 52e9132..9b7aaa3 100644--- a/tests/e2e/cases/onboarding.yaml+++ b/tests/e2e/cases/onboarding.yaml@@ -1,20 +1,36 @@cases:- name: Complete Doubao Say onboarding on a real desktopsteps:- - aiAssert: The visible Doubao Say window is on Sign in, says the user is not signed in, and shows Open Doubao sign-in.- - aiAct: Click Open Doubao sign-in exactly once, then stop immediately.+ - aiAssert: The visible Doubao Say window is on Sign in and says the user is not signed in.+ - aiAct: Scroll inside the Sign in content panel until Open Doubao sign-in is fully visible.+ - aiTap: Open Doubao sign-in button in the Sign in content panel- wait: { duration: 1500 }- aiAssert: A Synthetic Doubao sign-in window is visible and explicitly says it is CI-only, makes no network request, and uses no real credentials.- - aiAct: In the Synthetic Doubao sign-in window, click Simulate successful sign-in exactly once, then stop immediately.+ - aiTap: Simulate successful sign-in button in the Synthetic Doubao sign-in window- aiAssert: The synthetic sign-in window closed and Doubao Say automatically advanced to the Microphone step with a right-arrow Next button in the fixed top navigation.- - aiAct: Click the right-arrow Next button in the Doubao Say fixed top navigation exactly once. Do not click it a second time.+ - aiTap: Check microphone · 3 seconds button on the Microphone step+ - wait: { duration: 750 }+ - aiAssert: A visible message says Microphone is working and instructs the user to continue to the trigger key step.+ - aiTap: Right-arrow Next button in the Doubao Say fixed top navigation- aiAssert: The current Doubao Say step is Trigger key.- - aiAct: Stay on Trigger key. Scroll inside the light-gray central content panel until the Voice polishing heading and its controls are visible.- - aiAct: On Trigger key, click Test endpoint in the visible Voice polishing section and wait for the endpoint result.+ - aiAct: Stay on Trigger key. Scroll downward exactly once inside the light-gray central content panel, then stop.+ - aiAct: Scroll downward exactly once more inside the same central content panel, then stop.+ - aiAct: Scroll downward one final time inside the same central content panel, then stop.+ - aiAssert: The Test endpoint button in the Voice polishing section is fully visible.+ - aiTap: Test endpoint button in the visible Voice polishing section+ - wait: { duration: 750 }- aiAct: If needed, scroll down slightly inside the central content panel until Synthetic endpoint response is visible below Endpoint works. Keep both results on screen.- aiAssert: A visible message says the endpoint works and includes Synthetic endpoint response.- - aiAct: Click the right-arrow Next button in the fixed top navigation exactly once. Do not click it a second time.+ - aiTap: Right-arrow Next button in the fixed top navigation- aiAssert: The current Doubao Say step is Voice test.- aiAssert: The Voice test heading and introductory text are clearly visible near the top of the current content panel.- - aiAct: Scroll within Voice test content if needed and click Finish setup exactly once. Stop when the button changes to the disabled status Setup completed by the synthetic E2E fixture.+ - aiTap: Start voice test button in the Voice test content panel+ - wait: { duration: 750 }+ - aiAssert: The Voice test shows Synthetic voice test transcript and offers both Finish & check result and Cancel test.+ - aiTap: Finish & check result button in the Voice test content panel+ - wait: { duration: 750 }+ - aiAct: Scroll downward exactly once inside the Voice test content panel, then stop.+ - aiAssert: The enabled setup button visibly says Finish setup, Voice test passed, and nothing pasted or sent.+ - aiTap: Enabled setup button that says Voice test passed in the Voice test content panel+ - wait: { duration: 500 }- aiAssert: The Finish setup button changed to a disabled visible status saying Setup completed by the synthetic E2E fixture.diff --git a/tests/e2e/cases/runtime.yaml b/tests/e2e/cases/runtime.yamlnew file mode 100644index 0000000..c7f7c35--- /dev/null+++ b/tests/e2e/cases/runtime.yaml@@ -0,0 +1,26 @@+cases:+ - name: Deliver one synthetic dictation to the focused target+ steps:+ - fixture.prepare: { mode: runtime-delivery }+ - aiAssert: A Synthetic dictation target window is focused, its text field is empty, and the status says Idle with 0 deliveries.+ - computer.keyPress: { keyName: F8 }+ - wait: { duration: 1000 }+ - aiAssert: A dark Doubao Say overlay visibly says Listening to synthetic speech and shows Synthetic dictation is ready to deliver; the target field remains empty.+ - computer.keyPress: { keyName: F8 }+ - wait: { duration: 1200 }+ - aiAssert: The target field contains exactly Synthetic dictation delivered exactly once, and the status says Delivered once, target focus preserved, and 1 delivery.+ - name: Cancel synthetic dictation without delivering text+ steps:+ - fixture.prepare: { mode: runtime-cancel }+ - aiAssert: A Synthetic dictation target window is focused, its text field is empty, and the status says Idle with 0 deliveries.+ - computer.keyPress: { keyName: F8 }+ - wait: { duration: 1000 }+ - aiAssert: The recording overlay is visible and the target field is still empty.+ - computer.keyPress: { keyName: Escape }+ - wait: { duration: 1000 }+ - aiAssert: The overlay is gone, the target field remains empty, and the status says Cancelled, no text delivered, and ready to try again.+ - computer.keyPress: { keyName: F8 }+ - wait: { duration: 1000 }+ - computer.keyPress: { keyName: F8 }+ - wait: { duration: 1200 }+ - aiAssert: A new attempt succeeds with exactly one delivered synthetic sentence and the status reports 1 delivery.diff --git a/tests/e2e/gtk_fixture.py b/tests/e2e/gtk_fixture.pyindex 8dd7c28..2c71c6d 100644--- a/tests/e2e/gtk_fixture.py+++ b/tests/e2e/gtk_fixture.py@@ -1,144 +1,44 @@-"""Mapped GTK onboarding fixture for Midscene CI; uses synthetic data only."""+"""Select a deterministic GTK fixture for one Midscene Test case."""+import base64+import osimport signal+import sysimport gi+# Ubuntu 22.04 supplies PyGObject for its system Python 3.10. The application+# requires Python 3.11+, but this isolated fixture must use the system Python to+# share GTK bindings, so provide the standard-library module through tomli.+if sys.version_info < (3, 11):+ import tomli++ sys.modules["tomllib"] = tomli+gi.require_version("Gtk", "4.0")from gi.repository import GLib, Gtk-from doubao_input.doubao.app_state import AppState, LoginStatusfrom doubao_input.i18n import set_language-from doubao_input.settings import Settings, trigger_shortcut_display-from doubao_input.ui.control_window import ControlWindow-from doubao_input.ui.setup_actions import SetupActions+from gtk_onboarding_fixture import build_onboarding_fixture+from gtk_runtime_fixture import build_runtime_fixture+++RUNTIME_MODES = {"runtime-delivery", "runtime-cancel"}+++def fixture_mode():+ encoded = os.environ.get("DOUBAO_E2E_MODE_B64", "")+ return base64.b64decode(encoded).decode() if encoded else ""def main():Gtk.init()set_language("en")- state = AppState()- state.login_status = LoginStatus.NOT_LOGGED_IN- settings = Settings(- polish_enabled=True,- polish_base_url="https://example.invalid/v1",- polish_model="synthetic-model",- )- summary = {- "key": "Fn",- "key_code": 464,- "key_modifiers": (),- "microphone": "Synthetic microphone",- "microphone_id": "",- "microphone_ok": True,- "voice_test_ok": True,- "onboarding_complete": False,- }- holder = {}-- def show_synthetic_login():- existing = holder.get("login")- if existing:- existing.present()- return-- login = Gtk.Window(- title="CI-only synthetic sign-in — no real credentials"- )- login.set_default_size(760, 420)- login.set_resizable(False)- login.set_modal(True)- login.set_transient_for(holder["control"].window)-- content = Gtk.Box(orientation=Gtk.Orientation.VERTICAL, spacing=18)- for side in ("start", "end", "top", "bottom"):- getattr(content, "set_margin_" + side)(32)- login.set_child(content)-- heading = Gtk.Label(- label="CI-ONLY SYNTHETIC DOUBAO SIGN-IN",- xalign=0,- )- heading.add_css_class("title-1")- content.append(heading)- content.append(Gtk.Label(- label=(- "CI-only window. It makes no network request and uses no real "- "credentials."- ),- xalign=0,- wrap=True,- ))-- success = Gtk.Button(label="Simulate successful sign-in")- success.add_css_class("suggested-action")- content.append(success)-- def signed_in(*_args):- holder["login"] = None- login.destroy()- state.login_status = LoginStatus.LOGGED_IN- holder["control"].advance_after_login()-- success.connect("clicked", signed_in)-- def closed(*_args):- holder["login"] = None- return False-- login.connect("close-request", closed)- holder["login"] = login- login.present()-- def test_endpoint(endpoint_settings, _key, done):- def finish():- if endpoint_settings.polish_model == "synthetic-failing-model":- done(None, "Synthetic endpoint unavailable")- else:- done("Synthetic endpoint response", None)- return GLib.SOURCE_REMOVE-- GLib.timeout_add(350, finish)-- def apply_key(key, modifiers=()):- summary.update(key_code=key, key_modifiers=modifiers,- key=trigger_shortcut_display(key, modifiers))-- def save_polish(updated_settings, _key):- nonlocal settings- settings = updated_settings-- def complete_setup():- control = holder["control"]- message = "Setup completed by the synthetic E2E fixture."- control.set_feedback(message)- control._start_button.set_label(message)- control._start_button.set_sensitive(False)-- actions = SetupActions(- test_voice=lambda: None,- cancel_preview=lambda: None,- open_settings=lambda: None,- is_preview_testing=lambda: False,- summary=lambda: summary,- complete_setup=complete_setup,- apply_key=apply_key,- polish_settings=lambda: settings,- polish_has_key=lambda: True,- save_polish=save_polish,- test_polish=test_endpoint,- apply_microphone=lambda _microphone: None,- )- control = ControlWindow(- state,- on_login_clicked=show_synthetic_login,- on_quit_clicked=lambda: None,- on_check_mic_clicked=lambda: None,- actions=actions,+ mode = fixture_mode()+ cleanup = (+ build_runtime_fixture() if mode in RUNTIME_MODES+ else build_onboarding_fixture(mode))- holder["control"] = control- control.show()-loop = GLib.MainLoop()def stop(*_args):@@ -147,9 +47,14 @@ def main():signal.signal(signal.SIGTERM, lambda *_args: GLib.idle_add(stop))signal.signal(signal.SIGINT, lambda *_args: GLib.idle_add(stop))- print("READY: synthetic Doubao Say GTK fixture", flush=True)- loop.run()- control.destroy()+ print(+ f"READY: synthetic Doubao Say GTK fixture · {mode or 'default'}",+ flush=True,+ )+ try:+ loop.run()+ finally:+ cleanup()if __name__ == "__main__":diff --git a/tests/e2e/gtk_onboarding_fixture.py b/tests/e2e/gtk_onboarding_fixture.pynew file mode 100644index 0000000..4d426d7--- /dev/null+++ b/tests/e2e/gtk_onboarding_fixture.py@@ -0,0 +1,305 @@+"""Synthetic onboarding behavior for Midscene E2E."""++import gi++gi.require_version("Gtk", "4.0")+gi.require_version("Gdk", "4.0")+from gi.repository import Gdk, GLib, Gtk++from doubao_input.doubao.app_state import AppState, LoginStatus, RecordingState+from doubao_input.settings import Settings, trigger_shortcut_display+from doubao_input.ui import control_window as control_window_module+from doubao_input.ui.control_window import ControlWindow+from doubao_input.ui.overlay import Overlay+from doubao_input.ui.setup_actions import SetupActions+++MICROPHONES = [+ ("synthetic-one", "Synthetic microphone one"),+ ("synthetic-two", "Synthetic microphone two"),+]+LOGGED_IN_MODES = {+ "microphone-gate",+ "voice-test",+ "microphone-change",+ "shortcut-capture",+}+++def build_onboarding_fixture(mode):+ control_window_module.microphones = lambda: list(MICROPHONES)+ state = AppState()+ state.login_status = (+ LoginStatus.LOGGED_IN if mode in LOGGED_IN_MODES+ else LoginStatus.NOT_LOGGED_IN+ )+ settings = Settings(+ polish_enabled=True,+ polish_base_url="https://example.invalid/v1",+ polish_model="synthetic-model",+ )+ summary = {+ "key": "Fn",+ "key_code": 464,+ "key_modifiers": (),+ "microphone": MICROPHONES[0][1],+ "microphone_id": MICROPHONES[0][0],+ "microphone_ok": mode not in {"", "microphone-gate"},+ "voice_test_ok": mode in {+ "microphone-gate",+ "microphone-change",+ "shortcut-capture",+ },+ "onboarding_complete": False,+ "asr_provider": "doubao",+ "asr_provider_name": "Doubao",+ }+ holder = {+ "asr_key": False,+ "capture_sources": [],+ "login": None,+ "preview": False,+ }+ overlay = Overlay(state)++ def refresh():+ holder["control"].refresh()+ return GLib.SOURCE_REMOVE++ def show_synthetic_login():+ existing = holder.get("login")+ if existing:+ existing.present()+ return++ login = Gtk.Window(title="CI-only synthetic sign-in — no real credentials")+ login.set_default_size(760, 420)+ login.set_resizable(False)+ login.set_modal(True)+ login.set_transient_for(holder["control"].window)+ content = Gtk.Box(orientation=Gtk.Orientation.VERTICAL, spacing=18)+ for side in ("start", "end", "top", "bottom"):+ getattr(content, "set_margin_" + side)(32)+ login.set_child(content)+ heading = Gtk.Label(label="CI-ONLY SYNTHETIC DOUBAO SIGN-IN", xalign=0)+ heading.add_css_class("title-1")+ content.append(heading)+ content.append(Gtk.Label(+ label=(+ "CI-only window. It makes no network request and uses no real "+ "credentials."+ ),+ xalign=0,+ wrap=True,+ ))+ success = Gtk.Button(label="Simulate successful sign-in")+ success.add_css_class("suggested-action")+ content.append(success)++ def signed_in(*_args):+ holder["login"] = None+ login.destroy()+ state.login_status = LoginStatus.LOGGED_IN+ holder["control"].advance_after_login()++ success.connect("clicked", signed_in)++ def closed(*_args):+ holder["login"] = None+ return False++ login.connect("close-request", closed)+ keys = Gtk.EventControllerKey()+ keys.set_propagation_phase(Gtk.PropagationPhase.CAPTURE)++ def key_pressed(_controller, keyval, _keycode, _modifiers):+ if keyval != Gdk.KEY_Escape:+ return False+ holder["login"] = None+ login.destroy()+ return True++ keys.connect("key-pressed", key_pressed)+ login.add_controller(keys)+ holder["login"] = login+ login.present()++ def test_endpoint(endpoint_settings, _key, done):+ def finish():+ if endpoint_settings.polish_model == "synthetic-failing-model":+ done(None, "Synthetic endpoint unavailable")+ else:+ done("Synthetic endpoint response", None)+ return GLib.SOURCE_REMOVE++ GLib.timeout_add(350, finish)++ def apply_key(key, modifiers=()):+ summary.update(+ key_code=key,+ key_modifiers=modifiers,+ key=trigger_shortcut_display(key, modifiers),+ )++ def capture_key(done, preview):+ holder["capture_sources"] = [+ GLib.timeout_add(250, lambda: preview((66, (29,))) or False),+ GLib.timeout_add(600, lambda: done((66, (29,))) or False),+ ]++ def cancel_key_capture():+ for source in holder["capture_sources"]:+ if GLib.MainContext.default().find_source_by_id(source):+ GLib.source_remove(source)+ holder["capture_sources"] = []++ def save_polish(updated_settings, _key):+ nonlocal settings+ settings = updated_settings++ def apply_microphone(microphone_id):+ names = dict(MICROPHONES)+ summary.update(+ microphone_id=microphone_id,+ microphone=names.get(microphone_id, "System default"),+ microphone_ok=False,+ )+ GLib.idle_add(refresh)++ def check_microphone():+ control = holder["control"]+ control.set_feedback("Checking synthetic microphone for three seconds…")++ def finish():+ summary["microphone_ok"] = True+ control.set_feedback(+ "Microphone is working. Continue to the trigger key step."+ )+ control.refresh()+ return GLib.SOURCE_REMOVE++ GLib.timeout_add(500, finish)++ def test_voice():+ control = holder["control"]+ if state.recording_state == RecordingState.IDLE:+ holder["preview"] = True+ control._start_button.set_label("Finish setup")+ state.recording_state = RecordingState.RECORDING+ overlay.show()++ def transcript():+ state.transcription_text = "Synthetic voice test transcript."+ overlay.set_text(state.transcription_text)+ return GLib.SOURCE_REMOVE++ GLib.timeout_add(350, transcript)+ return++ state.recording_state = RecordingState.STOPPING++ def finish():+ summary["voice_test_ok"] = True+ state.recording_state = RecordingState.IDLE+ holder["preview"] = False+ overlay.hide()+ control.set_feedback(+ "Voice test passed. Your text stayed here — nothing was pasted or sent."+ )+ control.refresh()+ control._start_button.set_label(+ "Finish setup · Voice test passed · nothing pasted or sent"+ )+ return GLib.SOURCE_REMOVE++ GLib.timeout_add(350, finish)++ def cancel_preview():+ holder["preview"] = False+ state.recording_state = RecordingState.IDLE+ state.transcription_text = ""+ overlay.hide()+ holder["control"].set_preview("")+ holder["control"].set_feedback(+ "Voice test cancelled. Nothing was pasted or sent."+ )+ holder["control"].refresh()+ holder["control"]._start_button.set_label(+ "Finish setup · Voice test cancelled · nothing pasted or sent"+ )++ def apply_asr_provider(provider):+ summary.update(+ asr_provider=provider,+ asr_provider_name=("Volcengine" if provider == "volcengine" else "Doubao"),+ )+ state.login_status = (+ LoginStatus.LOGGED_IN+ if provider == "volcengine" and holder["asr_key"]+ else LoginStatus.NOT_LOGGED_IN+ )+ GLib.idle_add(refresh)++ def save_asr(key):+ if not key.strip():+ raise ValueError("Enter an API key first.")+ holder["asr_key"] = True++ def test_asr(_key, done):+ def finish():+ state.login_status = LoginStatus.LOGGED_IN+ refresh()+ done("API key accepted by synthetic endpoint.", None)+ return GLib.SOURCE_REMOVE++ GLib.timeout_add(350, finish)++ def complete_setup():+ summary["onboarding_complete"] = True+ control = holder["control"]+ message = "Setup completed by the synthetic E2E fixture."+ control.set_feedback(message)+ control._start_button.set_label(message)+ control._start_button.set_sensitive(False)++ actions = SetupActions(+ test_voice=test_voice,+ cancel_preview=cancel_preview,+ open_settings=lambda: None,+ is_preview_testing=lambda: holder["preview"],+ summary=lambda: summary,+ complete_setup=complete_setup,+ apply_key=apply_key,+ capture_key=capture_key,+ cancel_key_capture=cancel_key_capture,+ polish_settings=lambda: settings,+ polish_has_key=lambda: True,+ save_polish=save_polish,+ test_polish=test_endpoint,+ apply_microphone=apply_microphone,+ apply_asr_provider=apply_asr_provider,+ asr_has_key=lambda: holder["asr_key"],+ save_asr=save_asr,+ test_asr=test_asr,+ )+ control = ControlWindow(+ state,+ on_login_clicked=show_synthetic_login,+ on_quit_clicked=lambda: None,+ on_check_mic_clicked=check_microphone,+ actions=actions,+ )+ holder["control"] = control+ control.show()++ def cleanup():+ cancel_key_capture()+ overlay.hide()+ if overlay._window:+ overlay._window.destroy()+ login = holder.get("login")+ if login:+ login.destroy()+ control.destroy()++ return cleanupdiff --git a/tests/e2e/gtk_runtime_fixture.py b/tests/e2e/gtk_runtime_fixture.pynew file mode 100644index 0000000..4e54ecb--- /dev/null+++ b/tests/e2e/gtk_runtime_fixture.py@@ -0,0 +1,153 @@+"""Synthetic post-setup dictation target for Midscene E2E."""++import gi++gi.require_version("Gtk", "4.0")+gi.require_version("Gdk", "4.0")+from gi.repository import Gdk, GLib, Gtk++from doubao_input.inject.delivery import Delivery+from doubao_input.ui.overlay import Overlay+++class ImmediateWorker:+ """Run Delivery work on GTK's thread while retaining its real state machine."""++ def submit(self, work, completed):+ completed(work())++ def close(self, cleanup):+ cleanup()+++def build_runtime_fixture():+ overlay = Overlay()+ window = Gtk.Window(title="Synthetic dictation target")+ window.set_default_size(760, 420)+ box = Gtk.Box(orientation=Gtk.Orientation.VERTICAL, spacing=18)+ for side in ("start", "end", "top", "bottom"):+ getattr(box, "set_margin_" + side)(32)+ window.set_child(box)++ heading = Gtk.Label(label="Synthetic dictation delivery", xalign=0)+ heading.add_css_class("title-1")+ box.append(heading)+ box.append(Gtk.Label(+ label=(+ "This CI-only target uses synthetic recognition text and never "+ "reads or changes the system clipboard. Press F8 to start or "+ "finish; press Escape to cancel."+ ),+ xalign=0,+ wrap=True,+ ))+ target = Gtk.Entry(placeholder_text="Synthetic text will be delivered here")+ box.append(target)+ status = Gtk.Label(label="Idle · 0 deliveries", xalign=0, wrap=True)+ status.add_css_class("title-3")+ box.append(status)++ state = {"recording": False, "deliveries": 0, "focus_preserved": False}++ def schedule(delay_ms, callback):+ def invoke():+ callback()+ return GLib.SOURCE_REMOVE++ GLib.timeout_add(delay_ms, invoke)++ def paste(text, _target, cancelled):+ if cancelled():+ return False+ target.set_text(text)+ # A successful real paste is delivered to the focused target. Mirror+ # that contract in the synthetic adapter instead of leaving focus on+ # whichever X11 surface happened to receive the global shortcut.+ target.grab_focus()+ state["deliveries"] += 1+ return True++ def delivery_changed(value):+ if value == "attempted":+ status.set_text("Delivered once · restoring target focus…")++ delivery = Delivery(+ schedule=schedule,+ target=lambda: "synthetic-target",+ paste=paste,+ enter=lambda *_args: False,+ changed=delivery_changed,+ worker=ImmediateWorker(),+ )++ def key_pressed(_controller, keyval, _keycode, _modifiers):+ if keyval == Gdk.KEY_F8:+ if state["recording"]:+ state["recording"] = False+ overlay.set_status("Synthetic recognition complete")+ delivery.submit(+ "Synthetic dictation delivered exactly once.",+ "synthetic-target",+ )++ def close_overlay_and_restore_target():+ overlay.hide()+ window.present()++ def report_focus(attempt=0):+ window.set_focus(target)+ target.grab_focus()+ if not target.has_focus() and attempt < 10:+ schedule(50, lambda: report_focus(attempt + 1))+ return+ state["focus_preserved"] = target.has_focus()+ focus = (+ "focus preserved"+ if state["focus_preserved"]+ else "focus lost"+ )+ status.set_text(+ f"Delivered once · target {focus} · "+ f"{state['deliveries']} delivery"+ )++ schedule(50, report_focus)++ schedule(500, close_overlay_and_restore_target)+ else:+ state["recording"] = True+ overlay.show("Listening to synthetic speech…")+ overlay.set_text("Synthetic dictation is ready to deliver.")+ status.set_text("Recording synthetic dictation · press F8 to finish")+ return True+ if keyval == Gdk.KEY_Escape and state["recording"]:+ state["recording"] = False+ overlay.hide()+ status.set_text("Cancelled · no text delivered · ready to try again")+ return True+ return False++ def listen_for_shortcuts(owner):+ keys = Gtk.EventControllerKey()+ keys.set_propagation_phase(Gtk.PropagationPhase.CAPTURE)+ keys.connect("key-pressed", key_pressed)+ owner.add_controller(keys)++ # The production app receives F8/Escape from its global trigger monitor.+ # This isolated fixture has no monitor, so listen from both of its windows:+ # some X11 window managers activate the overlay while it is visible even+ # though GTK marks it non-focusable.+ overlay._ensure_window()+ listen_for_shortcuts(window)+ listen_for_shortcuts(overlay._window)+ window.present()+ GLib.idle_add(target.grab_focus)++ def cleanup():+ delivery.close(lambda: None)+ overlay.hide()+ if overlay._window:+ overlay._window.destroy()+ window.destroy()++ return cleanupdiff --git a/tests/e2e/is-transient-midscene-failure.sh b/tests/e2e/is-transient-midscene-failure.shdeleted file mode 100755index 13f4040..0000000--- a/tests/e2e/is-transient-midscene-failure.sh+++ /dev/null@@ -1,11 +0,0 @@-#!/bin/bash-set -euo pipefail--if (($# != 1)); then- echo "Usage: $0 <midscene-log>" >&2- exit 2-fi--grep -Eq \- 'Connection error|ETIMEDOUT|ECONNRESET|EAI_AGAIN|UND_ERR_CONNECT_TIMEOUT|failed to call AI model service|XML parse error|Invalid parameters for action|Failed to parse action-param-json|No valid action generated' \- "$1"diff --git a/tests/e2e/midscene-node-reference.md b/tests/e2e/midscene-node-reference.mdindex 917a1e6..d6e6bde 100644--- a/tests/e2e/midscene-node-reference.md+++ b/tests/e2e/midscene-node-reference.md@@ -17,6 +17,9 @@ This table lists all available Nodes. See [Node Details](#node-details) below fo| aiNumber | Run aiNumber with a Midscene UI Agent and store its value. || aiString | Run aiString with a Midscene UI Agent and store its value. || aiTap | Locate and tap an element with a Midscene UI Agent. |+| computer.inputText | Replace text in a visually located input through the active Midscene Computer Agent. |+| computer.keyPress | Press a desktop shortcut through the active Midscene Computer Agent. |+| fixture.prepare | Select deterministic synthetic state for this test case. || recordToReport | Add text or screenshots to the current Midscene report. || shell.closeSystemMenu | Close the Omarchy system menu. || shell.moveBarLeft | Back up Omarchy bar settings and dock the bar left. |@@ -31,7 +34,9 @@ Projects created by `midscene-test create` select `cases/**/*.{yaml,yml}` by def**Config file:** `midscene.config.ts`-**Case files:** `cases/onboarding.yaml`, `cases/onboarding-regressions.yaml` (Execution Project: ubuntu)+**Case files:** `cases/polishing.yaml` (Execution Project: ubuntu-polishing)++**Case files:** `cases/onboarding.yaml`, `cases/onboarding-regressions.yaml`, `cases/runtime.yaml` (Execution Project: ubuntu)**Case files:** `cases/onboarding.yaml` (Execution Project: omarchy-onboarding)@@ -726,6 +731,96 @@ Locate and tap an element with a Midscene UI Agent.}```+### `computer.inputText`++Replace text in a visually located input through the active Midscene Computer Agent.++**String shorthand:** Not supported by this Node.++#### Input Schema++```json+{+ "$schema": "https://json-schema.org/draft/2020-12/schema",+ "additionalProperties": false,+ "properties": {+ "target": {+ "minLength": 1,+ "type": "string"+ },+ "value": {+ "type": "string"+ }+ },+ "required": [+ "target",+ "value"+ ],+ "type": "object"+}+```++### `computer.keyPress`++Press a desktop shortcut through the active Midscene Computer Agent.++**String shorthand:** Not supported by this Node.++#### Input Schema++```json+{+ "$schema": "https://json-schema.org/draft/2020-12/schema",+ "additionalProperties": false,+ "properties": {+ "keyName": {+ "enum": [+ "F8",+ "Escape"+ ],+ "type": "string"+ }+ },+ "required": [+ "keyName"+ ],+ "type": "object"+}+```++### `fixture.prepare`++Select deterministic synthetic state for this test case.++**String shorthand:** Not supported by this Node.++#### Input Schema++```json+{+ "$schema": "https://json-schema.org/draft/2020-12/schema",+ "additionalProperties": false,+ "properties": {+ "mode": {+ "enum": [+ "microphone-gate",+ "voice-test",+ "volcengine",+ "microphone-change",+ "shortcut-capture",+ "runtime-delivery",+ "runtime-cancel"+ ],+ "type": "string"+ }+ },+ "required": [+ "mode"+ ],+ "type": "object"+}+```+### `recordToReport`Add text or screenshots to the current Midscene report.diff --git a/tests/e2e/midscene.config.ts b/tests/e2e/midscene.config.tsindex 2073b4e..5c2dd73 100644--- a/tests/e2e/midscene.config.ts+++ b/tests/e2e/midscene.config.ts@@ -10,7 +10,8 @@ import { createMidsceneNodes } from '@midscene/test/midscene';interface DesktopContext {agent?: ComputerAgent;createAgent: () => Promise<ComputerAgent>;- resetFixture?: () => Promise<void>;+ fixtureMode?: string;+ resetFixture?: (mode: string) => Promise<void>;barConfigBackup?: string;barConfigExisted?: boolean;}@@ -102,6 +103,23 @@ const setup = defineProjectSetup<DesktopContext>({});onTeardown(() => stop(viewer));await sleep(4000);+ if (!shell) {+ const stopGuestFixture = () => {+ guest('if test -s /tmp/doubao-midscene-fixture.pid; then kill "$(cat /tmp/doubao-midscene-fixture.pid)" >/dev/null 2>&1 || true; fi; rm -f /tmp/doubao-midscene-fixture.pid');+ };+ onTeardown(stopGuestFixture);+ context.resetFixture = async (mode) => {+ const encodedMode = Buffer.from(mode).toString('base64');+ stopGuestFixture();+ guest(`rm -rf /tmp/doubao-midscene-config; mkdir -p /tmp/doubao-midscene-config; export PYTHONPATH='/home/omarchy/.config/omarchy/plugins/md.lifeos.doubao-say/src'; export XDG_CONFIG_HOME=/tmp/doubao-midscene-config; export PYTHONDONTWRITEBYTECODE=1; export DOUBAO_E2E_MODE_B64='${encodedMode}'; nohup setsid python3 '/home/omarchy/.config/omarchy/plugins/md.lifeos.doubao-say/tests/e2e/gtk_fixture.py' >/tmp/doubao-midscene-fixture.log 2>&1 </dev/null & echo $! >/tmp/doubao-midscene-fixture.pid`);+ for (let attempt = 0; attempt < 30; attempt++) {+ const ready = guest(`grep -q 'READY: synthetic Doubao Say GTK fixture' /tmp/doubao-midscene-fixture.log && hyprctl -j clients | jq -r '[.[] | select(.title == "Doubao Say")] | length' || true`);+ if (ready === '1') return;+ await sleep(2000);+ }+ throw new Error('Omarchy GTK fixture did not become ready');+ };+ }} else {const root = resolve(import.meta.dirname, '../..');let fixture: ChildProcess | undefined;@@ -115,7 +133,7 @@ const setup = defineProjectSetup<DesktopContext>({}};onTeardown(cleanup);- context.resetFixture = async () => {+ context.resetFixture = async (mode) => {await cleanup();configDirectory = await mkdtemp(resolve(tmpdir(), 'doubao-midscene-'));fixture = spawn('/usr/bin/python3', [polishing ? 'tests/e2e/polish_fixture.py' : 'tests/e2e/gtk_fixture.py'], {@@ -123,6 +141,7 @@ const setup = defineProjectSetup<DesktopContext>({env: {...process.env, GDK_BACKEND: 'x11', GSK_RENDERER: 'cairo', GTK_A11Y: 'none',PYTHONPATH: resolve(root, 'src'), XDG_CONFIG_HOME: configDirectory,+ DOUBAO_E2E_MODE_B64: Buffer.from(mode).toString('base64'),},});await waitForFixture(fixture);@@ -146,9 +165,58 @@ const setup = defineProjectSetup<DesktopContext>({});const empty = z.strictObject({});+const fixtureMode = z.strictObject({+ mode: z.enum([+ 'microphone-gate',+ 'voice-test',+ 'volcengine',+ 'microphone-change',+ 'shortcut-capture',+ 'runtime-delivery',+ 'runtime-cancel',+ ]),+});+const keyboardKey = z.strictObject({+ keyName: z.enum(['F8', 'Escape']),+});+const inputText = z.strictObject({+ target: z.string().min(1),+ value: z.string(),+});+const prepareFixture = defineNode<typeof fixtureMode, void, DesktopContext>({+ name: 'fixture.prepare',+ description: 'Select deterministic synthetic state for this test case.',+ inputSchema: fixtureMode,+ execute({ context, input }) {+ context.fixtureMode = input.mode;+ },+});+const pressKeyboardKey = defineNode<typeof keyboardKey, void, DesktopContext>({+ name: 'computer.keyPress',+ description: 'Press a desktop shortcut through the active Midscene Computer Agent.',+ inputSchema: keyboardKey,+ async execute({ context, input }) {+ if (!context.agent) throw new Error('Midscene Computer Agent is not active');+ await context.agent.aiKeyboardPress(input.keyName);+ },+});+const inputTextField = defineNode<typeof inputText, void, DesktopContext>({+ name: 'computer.inputText',+ description:+ 'Replace text in a visually located input through the active Midscene Computer Agent.',+ inputSchema: inputText,+ async execute({ context, input }) {+ if (!context.agent) throw new Error('Midscene Computer Agent is not active');+ await context.agent.aiInput(input.target, {+ value: input.value,+ mode: 'replace',+ });+ },+});const openSystemMenu = defineNode<typeof empty, void, DesktopContext>({name: 'shell.openSystemMenu', description: 'Open the real Omarchy system menu and focus one row.', inputSchema: empty,async execute() {+ guest('omarchy-shell shell hide omarchy.menu');guest('omarchy-shell shell summon omarchy.menu \'{"menu":"system"}\'');for (let attempt = 0; attempt < 15; attempt++) {if (guest('hyprctl -j layers | jq -r \'[.. | objects | select(.namespace? == "omarchy-menu")] | length\'') !== '0') {@@ -168,9 +236,11 @@ const closeSystemMenu = defineNode<typeof empty, void, DesktopContext>({const moveBarLeft = defineNode<typeof empty, void, DesktopContext>({name: 'shell.moveBarLeft', description: 'Back up Omarchy bar settings and dock the bar left.', inputSchema: empty,async execute({ context }) {- context.barConfigExisted = guest('test -f "$HOME/.config/omarchy/shell.json" && echo yes || echo no') === 'yes';- context.barConfigBackup = guest('mktemp /tmp/omarchy-midscene-bar.XXXXXX');- if (context.barConfigExisted) guest(`cp "$HOME/.config/omarchy/shell.json" '${context.barConfigBackup}'`);+ if (!context.barConfigBackup) {+ context.barConfigExisted = guest('test -f "$HOME/.config/omarchy/shell.json" && echo yes || echo no') === 'yes';+ context.barConfigBackup = guest('mktemp /tmp/omarchy-midscene-bar.XXXXXX');+ if (context.barConfigExisted) guest(`cp "$HOME/.config/omarchy/shell.json" '${context.barConfigBackup}'`);+ }guest('omarchy bar position left');await sleep(2000);},@@ -178,11 +248,39 @@ const moveBarLeft = defineNode<typeof empty, void, DesktopContext>({export default defineTestProject<DesktopContext>({test: { maxConcurrency: 1, testTimeout: 8 * 60_000 },+ // Retries are scoped to failed cases. Every attempt stays visible in the+ // official Midscene report, and agent acquisition resets its fixture.projects: [- { name: 'ubuntu-polishing', setup, files: { include: ['cases/polishing.yaml'] } },- { name: 'ubuntu', setup, files: { include: ['cases/onboarding.yaml', 'cases/onboarding-regressions.yaml'] } },- { name: 'omarchy-onboarding', setup, files: { include: ['cases/onboarding.yaml'] } },- { name: 'omarchy-shell', setup, files: { include: ['cases/omarchy-shell.yaml'] } },+ {+ name: 'ubuntu-polishing',+ retry: 2,+ setup,+ files: { include: ['cases/polishing.yaml'] },+ },+ {+ name: 'ubuntu',+ retry: 2,+ setup,+ files: {+ include: [+ 'cases/onboarding.yaml',+ 'cases/onboarding-regressions.yaml',+ 'cases/runtime.yaml',+ ],+ },+ },+ {+ name: 'omarchy-onboarding',+ retry: 2,+ setup,+ files: { include: ['cases/onboarding.yaml'] },+ },+ {+ name: 'omarchy-shell',+ retry: 2,+ setup,+ files: { include: ['cases/omarchy-shell.yaml'] },+ },],nodes: [...createMidsceneNodes<DesktopContext>({@@ -190,11 +288,12 @@ export default defineTestProject<DesktopContext>({agentProvider: (() => {const active = new Map<string, { agent: ComputerAgent; context: DesktopContext }>();return {- async getAgent(runId: string, { context }: { context: DesktopContext }) {+ async getAgent(runId: string, execution) {+ const { context } = execution;const existing = active.get(runId);if (existing) return existing.agent;context.agent ??= await context.createAgent();- await context.resetFixture?.();+ await context.resetFixture?.(context.fixtureMode ?? '');active.set(runId, { agent: context.agent, context });return context.agent;},@@ -205,12 +304,18 @@ export default defineTestProject<DesktopContext>({const { agent, context } = entry;await agent.destroy();context.agent = undefined;+ context.fixtureMode = undefined;if (!agent.reportFile) throw new Error(`No Agent report for Midscene case ${runId}`);return { reportPath: agent.reportFile };},};})(),}),- openSystemMenu, closeSystemMenu, moveBarLeft,+ prepareFixture,+ pressKeyboardKey,+ inputTextField,+ openSystemMenu,+ closeSystemMenu,+ moveBarLeft,],});diff --git a/tests/e2e/run-omarchy-midscene.sh b/tests/e2e/run-omarchy-midscene.shindex 0a90580..af3b8b4 100755--- a/tests/e2e/run-omarchy-midscene.sh+++ b/tests/e2e/run-omarchy-midscene.sh@@ -13,8 +13,8 @@ readonly SSH_PORT=2222readonly PLUGIN_DIR="/home/omarchy/.config/omarchy/plugins/md.lifeos.doubao-say"readonly SHIM_DIR="$(mktemp -d)"readonly PLUGIN_ARCHIVE="$(mktemp /tmp/doubao-say-omarchy-plugin-XXXXXX.tar)"-readonly MODEL_TEST_ATTEMPTS=4export NODE_OPTIONS="${NODE_OPTIONS:-} --require=$ROOT_DIR/tests/e2e/node_modules/@computer-use/libnut/dist/import_libnut.js"+export OMARCHY_SSH_KEY="$SSH_KEY"VM_PID=""@@ -107,13 +107,14 @@ VM_PID="$(cat "$RUN_DIR/qemu.pid")"kill -0 "$VM_PID"ssh_guest true-# Put this exact checkout at its real Omarchy plugin location, validate the-# manifest with Omarchy, then launch the deterministic GTK fixture in the-# guest's actual Hyprland session.+# Put this exact checkout at its real Omarchy plugin location and validate the+# manifest. The Midscene project lifecycle starts its deterministic GTK fixture+# in the guest's actual Hyprland session for every case attempt.echo "Creating the Omarchy plugin test payload."tar -C "$ROOT_DIR" --exclude='__pycache__' -cf "$PLUGIN_ARCHIVE" \LICENSE README.md manifest.json install.sh setup-omarchy.sh start.sh \- omarchy src tests/e2e/gtk_fixture.py+ omarchy src tests/e2e/gtk_fixture.py tests/e2e/gtk_onboarding_fixture.py \+ tests/e2e/gtk_runtime_fixture.pyfor _copy_attempt in 1 2 3 4 5; doif scp -i "$SSH_KEY" -P "$SSH_PORT" \@@ -151,103 +152,12 @@ ssh_session_tty "printf '%s\\n' omarchy | sudo -S -v && \ssh_guest "test -f /home/omarchy/.local/share/applications/doubao-say.desktop && \grep -Fq '$PLUGIN_DIR/start.sh' /home/omarchy/.local/share/applications/doubao-say.desktop"-echo "Launching the Doubao Say GTK fixture inside Hyprland."-start_guest_fixture() {- ssh_session "if test -s /tmp/doubao-midscene-fixture.pid; then \- kill \"\$(cat /tmp/doubao-midscene-fixture.pid)\" >/dev/null 2>&1 || true; \- fi; \- rm -f /tmp/doubao-midscene-fixture.pid; \- rm -rf /tmp/doubao-midscene-config; \- mkdir -p /tmp/doubao-midscene-config; \- export PYTHONPATH='$PLUGIN_DIR/src'; \- export XDG_CONFIG_HOME=/tmp/doubao-midscene-config; \- export PYTHONDONTWRITEBYTECODE=1; \- nohup setsid python3 '$PLUGIN_DIR/tests/e2e/gtk_fixture.py' \- >/tmp/doubao-midscene-fixture.log 2>&1 </dev/null & \- echo \$! >/tmp/doubao-midscene-fixture.pid"-- for _ready_attempt in $(seq 1 30); do- if ssh_session "grep -q 'READY: synthetic Doubao Say GTK fixture' /tmp/doubao-midscene-fixture.log && \- hyprctl -j clients | jq -e '[.[] | select(.title == \"Doubao Say\")] | length == 1'" \- >/dev/null 2>&1; then- return 0- fi- sleep 2- done+npm --prefix tests/e2e test -- --project omarchy-onboarding- ssh_session "cat /tmp/doubao-midscene-fixture.log" >&2 || true- return 1-}--MIDSCENE_PASSED=false-ATTEMPT_LOG=""-for ((_test_attempt = 1; _test_attempt <= MODEL_TEST_ATTEMPTS; _test_attempt++)); do- start_guest_fixture- ATTEMPT_LOG="/tmp/omarchy-midscene-attempt-${_test_attempt}.log"- if npm --prefix tests/e2e test -- \- --project omarchy-onboarding 2>&1 | tee "$ATTEMPT_LOG"; then- MIDSCENE_PASSED=true- break- fi-- if ! tests/e2e/is-transient-midscene-failure.sh "$ATTEMPT_LOG"; then- echo "Omarchy Midscene failed for a non-transient reason; not retrying." >&2- exit 1- fi- if ((_test_attempt < MODEL_TEST_ATTEMPTS)); then- retry_delay=$((15 * _test_attempt))- echo "Transient model or connection failure on attempt $_test_attempt; retrying in $retry_delay seconds." >&2- sleep "$retry_delay"- fi-done--if [[ $MIDSCENE_PASSED != true ]]; then- echo "Omarchy Midscene exhausted $MODEL_TEST_ATTEMPTS transient-failure attempts." >&2- exit 1-fi--ssh_session "hyprctl -j clients | jq -e '[.[] | select(.title == \"Doubao Say\")] | length == 1'"--# The shell PoC should show Omarchy itself, without the onboarding fixture-# obscuring the desktop or its first-run notifications.-ssh_session "if test -s /tmp/doubao-midscene-fixture.pid; then \- kill \"\$(cat /tmp/doubao-midscene-fixture.pid)\" >/dev/null 2>&1 || true; \- fi; omarchy-shell notifications dismissAll"-for _close_attempt in $(seq 1 15); do- if ssh_session "hyprctl -j clients | jq -e '[.[] | select(.title == \"Doubao Say\")] | length == 0'" \- >/dev/null 2>&1; then- break- fi- if [[ $_close_attempt -eq 15 ]]; then- echo "Doubao Say fixture did not close before the shell visual test." >&2- exit 1- fi- sleep 1-done+# The Midscene project teardown has stopped its onboarding fixture. Dismiss+# first-run notifications before the shell project inspects Omarchy itself.+ssh_session "omarchy-shell notifications dismissAll"# Reuse the same live Hyprland session for a visual comparison against# Omarchy's OCR and hyprctl-based acceptance checks.-MENU_PASSED=false-for ((_test_attempt = 1; _test_attempt <= MODEL_TEST_ATTEMPTS; _test_attempt++)); do- ATTEMPT_LOG="/tmp/omarchy-menu-midscene-attempt-${_test_attempt}.log"- if OMARCHY_SSH_KEY="$SSH_KEY" npm --prefix tests/e2e test -- \- --project omarchy-shell 2>&1 | tee "$ATTEMPT_LOG"; then- MENU_PASSED=true- break- fi-- if ! tests/e2e/is-transient-midscene-failure.sh "$ATTEMPT_LOG"; then- echo "Omarchy menu visual test failed for a non-transient reason; not retrying." >&2- exit 1- fi- if ((_test_attempt < MODEL_TEST_ATTEMPTS)); then- retry_delay=$((15 * _test_attempt))- echo "Transient model or connection failure on menu attempt $_test_attempt; retrying in $retry_delay seconds." >&2- sleep "$retry_delay"- fi-done--if [[ $MENU_PASSED != true ]]; then- echo "Omarchy menu visual test exhausted $MODEL_TEST_ATTEMPTS transient-failure attempts." >&2- exit 1-fi+npm --prefix tests/e2e test -- --project omarchy-shelldiff --git a/tests/unit/test_desktop.py b/tests/unit/test_desktop.pyindex 6aea24b..f6f3287 100644--- a/tests/unit/test_desktop.py+++ b/tests/unit/test_desktop.py@@ -109,6 +109,7 @@ class DesktopTest(TestCase):win.get_display.return_value.__gtype__ = SimpleNamespace(name="GdkX11Display")with self.assertRaises(StopBeforeWidgets):overlay.Overlay._ensure_window(owner)+ win.set_focusable.assert_called_once_with(False)signal, callback = win.connect.call_args.argsself.assertEqual(signal, "realize")callback(win)