[GH-ISSUE #4660] [Bug] inspect-adb-window silently omits a later display's focused window and app #2430

Closed
opened 2026-10-17 21:04:32 +00:00 by bsakaguchi · 2 comments
Owner

Originally created by @coygeek on GitHub (Oct 17, 2026).
Original GitHub issue: https://github.com/morluto/rea/issues/4660

Before submitting

  • I searched the open and closed issues for a related report.
  • I removed credentials, tokens, private paths, and sensitive target data.

Area

Process capture or runtime observation

Observed behavior

inspect-adb-window SERIAL --json silently keeps only the first display's focus pair from dumpsys window displays. With inactive display 3 first and focused display 0 later, the later Settings window/app disappear from both the focus fields and observed_lines. No limitation identifies the selected display or acknowledges discarded declarations. Reversing the same display blocks changes the reported focus.

This reproduced through the CLI on both tested builds using captured display output and a caller-selected fake adb. The focus-free windows response was simulated to reach the documented displays fallback. No physical device or live adb server was used.

Reproduction

Build a source checkout with its pinned toolchain (npm ci, npm run build:cached), then run the following from its root. For an installed package, replace the script argument scripts/rea.mjs with node_modules/rea-agents/scripts/rea.mjs. Put the supported Node executable on PATH. Each CLI invocation receives a fresh HOME and only the environment variables shown.

python3 - scripts/rea.mjs <<'PY'
import json, os, shutil, subprocess, sys, tempfile
from pathlib import Path

node = shutil.which("node")
assert node is not None
cli = str(Path(sys.argv[1]).resolve())
inactive = """  Display: mDisplayId=3 rootTasks=0
  mCurrentFocus=null
  mFocusedApp=null
"""
active = """  Display: mDisplayId=0 rootTasks=12
  mCurrentFocus=Window{ded34a7 u0 com.android.settings/com.android.settings.Settings$DeviceInfoSettingsActivity}
  mFocusedApp=ActivityRecord{4bc4e51 u0 com.android.settings/.Settings$DeviceInfoSettingsActivity t6844}
"""
header = "WINDOW MANAGER DISPLAY CONTENTS (dumpsys window displays)\n"
with tempfile.TemporaryDirectory() as directory:
    root = Path(directory)
    for name, output in {
        "inactive-first": header + inactive + active,
        "active-first": header + active + inactive,
        "active-only": header + active,
    }.items():
        (root / (name + ".txt")).write_text(output)
    adb = root / "adb"
    adb.write_text('''#!/usr/bin/python3
from pathlib import Path
import sys
args = sys.argv[1:]
if args == ["version"]:
    print("Android Debug Bridge version 1.0.41\\nVersion 34.0.5-fixture")
    sys.exit(0)
if len(args) == 6 and args[0] == "-s" and args[2:5] == ["shell", "dumpsys", "window"]:
    if args[5] == "windows":
        print("WINDOW MANAGER WINDOWS (dumpsys window windows)")
        sys.exit(0)
    if args[5] == "displays":
        sys.stdout.write((Path(__file__).parent / (args[1] + ".txt")).read_text())
        sys.exit(0)
sys.exit(9)
''')
    adb.chmod(0o755)
    for index, serial in enumerate([
        "inactive-first", "inactive-first", "active-first", "active-only"
    ]):
        home = root / ("home-" + str(index))
        home.mkdir()
        env = {"HOME": str(home), "TMPDIR": str(home),
               "PATH": str(Path(node).parent) + os.pathsep + os.defpath,
               "REA_ADB_PATH": str(adb)}
        result = subprocess.run(
            [node, cli, "inspect-adb-window", serial, "--json"],
            cwd=home, env=env, text=True, capture_output=True,
        )
        assert result.returncode == 0, result.stdout + result.stderr
        assert not result.stderr, result.stderr
        evidence = json.loads(result.stdout)
        answer = evidence["normalized_result"]
        print(json.dumps({"case": serial,
            "focused_window": answer["focused_window"],
            "focused_app": answer["focused_app"],
            "observed_lines": answer["observed_lines"],
            "limitations": evidence["limitations"]}))
        raw = subprocess.check_output(
            [str(adb), "-s", serial, "shell", "dumpsys", "window", "displays"],
            env=env, text=True,
        )
        if serial == "inactive-first":
            assert "mDisplayId=3" in raw and "mDisplayId=0" in raw
            assert "mCurrentFocus=Window{" in raw
PY

Both inactive-first calls omit the named pair. The reversed-order and single-active-display controls return it. Separately, replaying the complete original capture without reduction or reordering produced the same omission twice per build. Every CLI call exited 0 with empty stderr.

Expected behavior

Preserve the display-scoped declarations, or explicitly identify the scope/ambiguity of any singular focus answer and account for omitted displays. The tool promises the window manager's current focus declarations; the repository requires identity, omission, uncertainty, and source evidence to survive interpretation. A singular result can satisfy this contract with explicit display scope and limitations; this report does not require a particular new schema.

Impact and scope

The CLI returns incomplete focus evidence for the replayed multi-display fallback input and changes its answer when identical blocks change order. Complete-capture failure: 2/2 attempts per build. Reduced inactive-first failure: 2/2 per build; reversed-order and single-display controls passed once each per build. Physical-device frequency and downstream actions were not measured. MCP was not executed.

  • Impact level: P2
  • Assessment status: supported
  • Impact basis: This is a bounded incorrect machine-readable observation: a later display's declared focus is lost without disclosing display selection.
  • Workaround status: available
  • Workaround basis: Direct adb -s SERIAL shell dumpsys window displays preserved both display headers and all four declarations in the executed replay, including byte-for-byte preservation of the complete capture. Callers can retain that raw output and interpret its display blocks.

REA version

Current main at source commit 150e996a86; latest npm release rea-agents@6.5.0, installed independently from the registry. Both CLI launchers reported 6.5.0.

Runtime and platform

Node.js v24.18.0; Darwin arm64. Source install/build used the repository's pinned npm 11.16.0. The fake adb identifies itself as 34.0.5-fixture; no real adb server or device was contacted.

Target and artifact context

The display fixture comes from the complete public dumpsys window displays capture in MaaAssistantArknights issue #7057. It has inactive display 3 before focused display 0. The inline reduction retains those headers and focus declarations; the reversed and single-display controls were also executed. The focus-free windows response is simulated, not captured alongside the display output. This establishes replayed parser/provider behavior, without claiming an Android 16 device reproduction.

Interface

CLI

Earliest failure stage

Capture or observation

Relevant output or evidence

  • Expected source: src/contracts/adb/adbToolContracts.ts:224-230 and docs/adb-device-analysis.md:88 promise the current focus declarations; AGENTS.md:19-23 requires preservation of identity, omission, uncertainty, and source evidence.
  • Failure source: src/adb/AdbShellOutput.ts:190-209 retains the first declaration for each field; src/adb/AdbProvider.ts:1739-1780 projects only that pair. Executed CLI replay results below show the omission on both tested builds.
  • Evidence provenance: observed
  • Local verification: reproduced
  • Reproduction completeness: complete

Relevant output for the inactive-first case, repeated twice per build (client identity and serial omitted):

{"build":"main","focused_window":null,"focused_app":null,"observed_lines":["  mCurrentFocus=null","  mFocusedApp=null"]}
{"build":"npm release","focused_window":"null","focused_app":"null","observed_lines":["null","null"]}

Both controls returned the named Settings pair in focused_window and focused_app, and retained it in observed_lines. The complete capture produced the same inactive-first result above. Every case had only these limitations:

Artifact identity is unavailable for this observation.
Focus values are the window manager's declarations at read time; no interaction occurred
Focus declarations were read from `dumpsys window displays`

The raw read still contains the later named declarations. Main's null normalization and preservation of individual declaration lines do not resolve selection among display blocks.

Typed outcome or recovery expected

For the two-display input, preserve or explicitly account for the later display's focus and disclose the scope or ambiguity of singular fields. Reordering the same blocks must not silently change an apparently device-wide answer's meaning. Keep the active-only control's named focus correct. Converting the first pair to JSON null alone does not meet this check.

Analysis or suspected cause

Source-derived reasoning: the parser keeps the first matching declaration independently for each field without tracking the enclosing display block. The provider's limitation identifies the section, but gives no display identity or coverage warning.

Additional context

Issue #2996 covers the missing Android 16 section fallback. The same display-selection concern was previously raised in the review of PR #2998, which was closed after main delivered the fallback. This report supplies an executed reproduction of that separate selection concern. Issue #4608 covers explicit-null normalization and preservation of individual declaration lines; the maintainer response explicitly leaves selection among multiple display blocks separate from that fix. Open/closed issue and PR searches found no dedicated display-selection report or fix beyond that prior review observation.

Originally created by @coygeek on GitHub (Oct 17, 2026). Original GitHub issue: https://github.com/morluto/rea/issues/4660 ### Before submitting - [X] I searched the open and closed issues for a related report. - [X] I removed credentials, tokens, private paths, and sensitive target data. ### Area Process capture or runtime observation ### Observed behavior `inspect-adb-window SERIAL --json` silently keeps only the first display's focus pair from `dumpsys window displays`. With inactive display 3 first and focused display 0 later, the later Settings window/app disappear from both the focus fields and `observed_lines`. No limitation identifies the selected display or acknowledges discarded declarations. Reversing the same display blocks changes the reported focus. This reproduced through the CLI on both tested builds using captured display output and a caller-selected fake adb. The focus-free `windows` response was simulated to reach the documented `displays` fallback. No physical device or live adb server was used. ### Reproduction Build a source checkout with its pinned toolchain (`npm ci`, `npm run build:cached`), then run the following from its root. For an installed package, replace the script argument `scripts/rea.mjs` with `node_modules/rea-agents/scripts/rea.mjs`. Put the supported Node executable on PATH. Each CLI invocation receives a fresh HOME and only the environment variables shown. ```sh python3 - scripts/rea.mjs <<'PY' import json, os, shutil, subprocess, sys, tempfile from pathlib import Path node = shutil.which("node") assert node is not None cli = str(Path(sys.argv[1]).resolve()) inactive = """ Display: mDisplayId=3 rootTasks=0 mCurrentFocus=null mFocusedApp=null """ active = """ Display: mDisplayId=0 rootTasks=12 mCurrentFocus=Window{ded34a7 u0 com.android.settings/com.android.settings.Settings$DeviceInfoSettingsActivity} mFocusedApp=ActivityRecord{4bc4e51 u0 com.android.settings/.Settings$DeviceInfoSettingsActivity t6844} """ header = "WINDOW MANAGER DISPLAY CONTENTS (dumpsys window displays)\n" with tempfile.TemporaryDirectory() as directory: root = Path(directory) for name, output in { "inactive-first": header + inactive + active, "active-first": header + active + inactive, "active-only": header + active, }.items(): (root / (name + ".txt")).write_text(output) adb = root / "adb" adb.write_text('''#!/usr/bin/python3 from pathlib import Path import sys args = sys.argv[1:] if args == ["version"]: print("Android Debug Bridge version 1.0.41\\nVersion 34.0.5-fixture") sys.exit(0) if len(args) == 6 and args[0] == "-s" and args[2:5] == ["shell", "dumpsys", "window"]: if args[5] == "windows": print("WINDOW MANAGER WINDOWS (dumpsys window windows)") sys.exit(0) if args[5] == "displays": sys.stdout.write((Path(__file__).parent / (args[1] + ".txt")).read_text()) sys.exit(0) sys.exit(9) ''') adb.chmod(0o755) for index, serial in enumerate([ "inactive-first", "inactive-first", "active-first", "active-only" ]): home = root / ("home-" + str(index)) home.mkdir() env = {"HOME": str(home), "TMPDIR": str(home), "PATH": str(Path(node).parent) + os.pathsep + os.defpath, "REA_ADB_PATH": str(adb)} result = subprocess.run( [node, cli, "inspect-adb-window", serial, "--json"], cwd=home, env=env, text=True, capture_output=True, ) assert result.returncode == 0, result.stdout + result.stderr assert not result.stderr, result.stderr evidence = json.loads(result.stdout) answer = evidence["normalized_result"] print(json.dumps({"case": serial, "focused_window": answer["focused_window"], "focused_app": answer["focused_app"], "observed_lines": answer["observed_lines"], "limitations": evidence["limitations"]})) raw = subprocess.check_output( [str(adb), "-s", serial, "shell", "dumpsys", "window", "displays"], env=env, text=True, ) if serial == "inactive-first": assert "mDisplayId=3" in raw and "mDisplayId=0" in raw assert "mCurrentFocus=Window{" in raw PY ``` Both inactive-first calls omit the named pair. The reversed-order and single-active-display controls return it. Separately, replaying the complete original capture without reduction or reordering produced the same omission twice per build. Every CLI call exited 0 with empty stderr. ### Expected behavior Preserve the display-scoped declarations, or explicitly identify the scope/ambiguity of any singular focus answer and account for omitted displays. The tool promises the window manager's current focus declarations; the repository requires identity, omission, uncertainty, and source evidence to survive interpretation. A singular result can satisfy this contract with explicit display scope and limitations; this report does not require a particular new schema. ### Impact and scope The CLI returns incomplete focus evidence for the replayed multi-display fallback input and changes its answer when identical blocks change order. Complete-capture failure: 2/2 attempts per build. Reduced inactive-first failure: 2/2 per build; reversed-order and single-display controls passed once each per build. Physical-device frequency and downstream actions were not measured. MCP was not executed. - Impact level: P2 - Assessment status: supported - Impact basis: This is a bounded incorrect machine-readable observation: a later display's declared focus is lost without disclosing display selection. - Workaround status: available - Workaround basis: Direct `adb -s SERIAL shell dumpsys window displays` preserved both display headers and all four declarations in the executed replay, including byte-for-byte preservation of the complete capture. Callers can retain that raw output and interpret its display blocks. ### REA version Current main at source commit 150e996a86f2bec4982ba87f37bf502a8d5e8214; latest npm release `rea-agents@6.5.0`, installed independently from the registry. Both CLI launchers reported `6.5.0`. ### Runtime and platform Node.js v24.18.0; Darwin arm64. Source install/build used the repository's pinned npm 11.16.0. The fake adb identifies itself as 34.0.5-fixture; no real adb server or device was contacted. ### Target and artifact context The display fixture comes from the complete public `dumpsys window displays` capture in [MaaAssistantArknights issue #7057](https://github.com/MaaAssistantArknights/MaaAssistantArknights/issues/7057). It has inactive display 3 before focused display 0. The inline reduction retains those headers and focus declarations; the reversed and single-display controls were also executed. The focus-free `windows` response is simulated, not captured alongside the display output. This establishes replayed parser/provider behavior, without claiming an Android 16 device reproduction. ### Interface CLI ### Earliest failure stage Capture or observation ### Relevant output or evidence - Expected source: `src/contracts/adb/adbToolContracts.ts:224-230` and `docs/adb-device-analysis.md:88` promise the current focus declarations; `AGENTS.md:19-23` requires preservation of identity, omission, uncertainty, and source evidence. - Failure source: `src/adb/AdbShellOutput.ts:190-209` retains the first declaration for each field; `src/adb/AdbProvider.ts:1739-1780` projects only that pair. Executed CLI replay results below show the omission on both tested builds. - Evidence provenance: observed - Local verification: reproduced - Reproduction completeness: complete Relevant output for the inactive-first case, repeated twice per build (client identity and serial omitted): ```json {"build":"main","focused_window":null,"focused_app":null,"observed_lines":[" mCurrentFocus=null"," mFocusedApp=null"]} {"build":"npm release","focused_window":"null","focused_app":"null","observed_lines":["null","null"]} ``` Both controls returned the named Settings pair in `focused_window` and `focused_app`, and retained it in `observed_lines`. The complete capture produced the same inactive-first result above. Every case had only these limitations: ```text Artifact identity is unavailable for this observation. Focus values are the window manager's declarations at read time; no interaction occurred Focus declarations were read from `dumpsys window displays` ``` The raw read still contains the later named declarations. Main's null normalization and preservation of individual declaration lines do not resolve selection among display blocks. ### Typed outcome or recovery expected For the two-display input, preserve or explicitly account for the later display's focus and disclose the scope or ambiguity of singular fields. Reordering the same blocks must not silently change an apparently device-wide answer's meaning. Keep the active-only control's named focus correct. Converting the first pair to JSON null alone does not meet this check. ### Analysis or suspected cause Source-derived reasoning: the parser keeps the first matching declaration independently for each field without tracking the enclosing display block. The provider's limitation identifies the section, but gives no display identity or coverage warning. ### Additional context [Issue #2996](https://github.com/morluto/rea/issues/2996) covers the missing Android 16 section fallback. The same display-selection concern was previously raised in the [review of PR #2998](https://github.com/morluto/rea/pull/2998#discussion_r4263050910), which was closed after main delivered the fallback. This report supplies an executed reproduction of that separate selection concern. [Issue #4608](https://github.com/morluto/rea/issues/4608) covers explicit-null normalization and preservation of individual declaration lines; the [maintainer response](https://github.com/morluto/rea/issues/4608#issuecomment-6227449008) explicitly leaves selection among multiple display blocks separate from that fix. Open/closed issue and PR searches found no dedicated display-selection report or fix beyond that prior review observation.
Author
Owner

@morluto commented on GitHub (Oct 17, 2026):

Published in 7086768a27 on main.

The parser previously selected the first window/app fields independently, losing display ownership and later declarations. It now owns the complete parsed focus representation: focus_contexts retains each display header and exact recognized ID, every field/value/original line, missing fields, explicit nulls, duplicate declarations and unknown IDs. Header-free declarations remain explicitly unscoped. The provider consumes those parsed facts instead of rebuilding a first-match pair. The model follows AOSP DisplayContent's dump ownership, which prints the display header and its focus fields together.

The additive CLI/MCP fields are source_section, focus_contexts, and focus_summary. Singular fields summarize only one context without repeated fields; multiple contexts/repeated declarations yield ambiguous and null singular fields, with every observation retained. No declarations yields unavailable; explicit-null declarations still prevent fallback. observed_lines now retains all selected-section display headers and focus fields in order. No display is promoted to a device-wide focus.

Validation executed:

  • The report's public CLI replay before/after: both inactive-first repetitions and the reversed case now retain all six header/declaration lines. Reordering does not select a different singular focus; the active-only control retains its named pair and display context.
  • Four new parser controls failed on baseline be0b2d138. Final 23 parser/public CLI/official MCP checks passed, including reordered two-display cases, a single-display control, existing explicit-null/missing-field/fallback controls and converted SDK schema validation.
  • Eleven overlapping selected parser/provider controls passed; unrelated provider tests were explicitly skipped. Unknown IDs, missing peers, duplicate declarations and prevention of cross-display pairing are covered.
  • check:fast, docs:check with five README checks, normal commit/pre-push hooks passed. One initial lint length failure was corrected by grouping the tests by behavior.

Bounded completed-task costs, same selected fake adb/input/public CLI: separate first processes and two alternating warm repeats per build. Warm baseline/candidate medians were elapsed 0.391/0.403s, CPU 0.622/0.622s, sampled process-family RSS 388.4/382.7MB, and raw cl100k full-reply tokens 282/513. Replies intentionally differ because the candidate restores omitted observations and context; no speed/memory improvement is claimed. wait4 CPU includes reaped children; sampled PPID-family RSS may miss transient peaks/reparenting. True cold, whole-agent/catalog/converted-schema/retry, real-device and larger-output costs remain unmeasured. Measured source fingerprints match the published files.

Scope is captured/reduced-text replay and selected fake adb on Darwin arm64/Node24.18, through production CLI/MCP adapters. No live Android/multi-display/vendor-format behavior was verified. The temporary baseline was ownership-checked and removed normally; local reply/source evidence remains retained. The broader Android/codebase audit remains partial; heavy profiling and stress tests remain stopped.

<!-- gh-comment-id:6230291742 --> @morluto commented on GitHub (Oct 17, 2026): Published in 7086768a27242a15daa93486aefbaacc3c891e78 on main. The parser previously selected the first window/app fields independently, losing display ownership and later declarations. It now owns the complete parsed focus representation: `focus_contexts` retains each display header and exact recognized ID, every field/value/original line, missing fields, explicit nulls, duplicate declarations and unknown IDs. Header-free declarations remain explicitly `unscoped`. The provider consumes those parsed facts instead of rebuilding a first-match pair. The model follows [AOSP DisplayContent's dump ownership](https://github.com/aosp-mirror/platform_frameworks_base/blob/android-14.0.0_r1/services/core/java/com/android/server/wm/DisplayContent.java), which prints the display header and its focus fields together. The additive CLI/MCP fields are `source_section`, `focus_contexts`, and `focus_summary`. Singular fields summarize only one context without repeated fields; multiple contexts/repeated declarations yield `ambiguous` and null singular fields, with every observation retained. No declarations yields `unavailable`; explicit-null declarations still prevent fallback. `observed_lines` now retains all selected-section display headers and focus fields in order. No display is promoted to a device-wide focus. Validation executed: - The report's public CLI replay before/after: both inactive-first repetitions and the reversed case now retain all six header/declaration lines. Reordering does not select a different singular focus; the active-only control retains its named pair and display context. - Four new parser controls failed on baseline be0b2d138. Final 23 parser/public CLI/official MCP checks passed, including reordered two-display cases, a single-display control, existing explicit-null/missing-field/fallback controls and converted SDK schema validation. - Eleven overlapping selected parser/provider controls passed; unrelated provider tests were explicitly skipped. Unknown IDs, missing peers, duplicate declarations and prevention of cross-display pairing are covered. - check:fast, docs:check with five README checks, normal commit/pre-push hooks passed. One initial lint length failure was corrected by grouping the tests by behavior. Bounded completed-task costs, same selected fake adb/input/public CLI: separate first processes and two alternating warm repeats per build. Warm baseline/candidate medians were elapsed 0.391/0.403s, CPU 0.622/0.622s, sampled process-family RSS 388.4/382.7MB, and raw cl100k full-reply tokens 282/513. Replies intentionally differ because the candidate restores omitted observations and context; no speed/memory improvement is claimed. wait4 CPU includes reaped children; sampled PPID-family RSS may miss transient peaks/reparenting. True cold, whole-agent/catalog/converted-schema/retry, real-device and larger-output costs remain unmeasured. Measured source fingerprints match the published files. Scope is captured/reduced-text replay and selected fake adb on Darwin arm64/Node24.18, through production CLI/MCP adapters. No live Android/multi-display/vendor-format behavior was verified. The temporary baseline was ownership-checked and removed normally; local reply/source evidence remains retained. The broader Android/codebase audit remains partial; heavy profiling and stress tests remain stopped.
Author
Owner

@coygeek commented on GitHub (Oct 18, 2026):

Closing as addressed on main by 7086768a2. Window focus inspection now retains every display-scoped declaration and source line and marks multiple contexts ambiguous instead of silently selecting the first display. I verified the committed source and regression coverage; I have not rerun the runtime reproduction.

<!-- gh-comment-id:6244112081 --> @coygeek commented on GitHub (Oct 18, 2026): Closing as addressed on `main` by [7086768a2](https://github.com/morluto/rea/commit/7086768a27242a15daa93486aefbaacc3c891e78). Window focus inspection now retains every display-scoped declaration and source line and marks multiple contexts ambiguous instead of silently selecting the first display. I verified the committed source and regression coverage; I have not rerun the runtime reproduction.
Sign in to join this conversation.
No milestone
No project
No assignees
1 participant
Notifications
Due date
The due date is invalid or out of range. Please use the format "yyyy-mm-dd".

No due date set.

Dependencies

No dependencies set.

Reference
morluto/rea#2430
No description provided.