Skip to content

Commit 738db6f

Browse files
authored
Merge pull request #12 from Zoo-Code-Org/fix/chat-focus-preservation
fix(jetbrains): keep chat input focus while the agent works
2 parents 2819114 + c2bbe3b commit 738db6f

30 files changed

Lines changed: 3562 additions & 136 deletions

‎.github/workflows/pr.yml‎

Lines changed: 11 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -87,10 +87,12 @@ jobs:
8787
mkdir -p plugins/zoo-code/extension
8888
touch plugins/zoo-code/extension/.keep prodDep.txt
8989
90-
# The connector tests are pure JVM tests and the focus of these gates.
90+
# The connector and focus tests are pure JVM tests and the focus of
91+
# these gates. The Gradle test task sets java.awt.headless=true, so the
92+
# Swing-based focus regression tests initialize on the headless runner.
9193
# The platform-fixture tests need a display and the extension payload,
9294
# which a pull-request build does not assemble.
93-
- name: Run the connector tests
95+
- name: Run the connector and focus tests
9496
working-directory: jetbrains_plugin
9597
shell: bash
9698
run: >
@@ -101,6 +103,13 @@ jobs:
101103
--tests "org.zoocode.jetbrains.terminal.TerminalPtyBuilderTest"
102104
--tests "org.zoocode.jetbrains.terminal.ShellIntegrationOutputStateTest"
103105
--tests "org.zoocode.jetbrains.terminal.TerminalShellReadinessTest"
106+
--tests "org.zoocode.jetbrains.editor.EditorFocusIntentTest"
107+
--tests "org.zoocode.jetbrains.terminal.TerminalWidgetVisibilityTest"
108+
--tests "org.zoocode.jetbrains.ui.WebViewMountPlanTest"
109+
--tests "org.zoocode.jetbrains.util.FocusRequestEpochTest"
110+
--tests "org.zoocode.jetbrains.util.ManualFocusGuardTest"
111+
--tests "org.zoocode.jetbrains.util.TerminalCreationFocusGuardTest"
112+
--tests "org.zoocode.jetbrains.webview.InstanceRetirementTrackerTest"
104113
--no-configuration-cache
105114
106115
- name: Build the plugin

‎docs/KNOWN_ISSUES.md‎

Lines changed: 57 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -168,7 +168,62 @@ The plugin requires Node.js command line tools to function properly. Node.js exe
168168

169169
---
170170

171-
## 3. General Troubleshooting Steps
171+
## 3. Focus Behavior
172+
173+
Measured triggers, fixes, and remaining limits are recorded in
174+
[the validation report](validation/chat-focus-preservation.md). Raw evidence
175+
paths in that report are local, ignored build artifacts; the report includes
176+
the relevant trace excerpts for readers of a clean checkout.
177+
178+
### 3.1 Terminal Creation Focus Restoration
179+
180+
Production terminal creation activates the new terminal and can move Swing
181+
focus from the chat OSR canvas to `JBTerminalPanel`.
182+
`TerminalCreationFocusGuard` captures the exact chat owner before
183+
initialization and restores that owner once after the platform activation
184+
settles. It restores only when focus ended inside the newly created terminal,
185+
chat remains visible, and no user click, key, or Tab traversal intervened. The
186+
guard expires at the callback or 1500 ms after creation; there is no polling or
187+
permanent listener. Instrumented probes retain pre- and post-creation typing
188+
with the owner back on the chat OSR canvas, and pure decision tests are in the
189+
CI allowlist.
190+
191+
Deliberate Terminal user actions are expected platform behavior, not defects.
192+
The first show of the Terminal tool window, stock new-tab actions outside the
193+
plugin-owned creation path, and stock tab selection request terminal focus by
194+
design. The plugin does not wrap these stock actions. The preserving-show and
195+
deliberate-show harness checks for these paths remain required. macOS, native
196+
Windows, and other IDE builds remain untested.
197+
198+
### 3.2 Corrected Test Fixture Items
199+
200+
Two earlier harness failures were test-setup defects, not current product
201+
issues: an IDEA script-launcher warning balloon covered the chat textarea, and
202+
a harness step clicked the browser retired during webview replacement. The
203+
fixture now uses the native launcher, waits for smart mode, and references the
204+
currently mounted browser. No balloon-restoration or permanent focus code was
205+
added to the plugin. Modal dismissal and visibility-only hide/show still do not
206+
automatically activate chat.
207+
208+
### 3.3 Intermittent First-Turn Draft Character Loss
209+
210+
Open. Not fixed. Not conclusively attributed. Real provider-backed
211+
conversations intermittently lose one draft character near the first
212+
file-editor or diff opening. The latest run completed both turns but failed
213+
draft preservation: 32/33 characters in the first turn, 6/6 in the follow-up.
214+
The IDE trace recorded the key release without a matching press, with no
215+
browser remount and the Swing owner stable on the chat OSR canvas. The
216+
initiating platform call remains unproven. The same test stream found and fixed
217+
the separate diff `preserveFocus` decoding bug; the live diff now opens with
218+
`preserveFocus=true` and chat focus retained. A pure JDK probe
219+
(`scripts/ui-harness/KeyDropProbe.java`) reproduced release-without-press only
220+
under deliberate focus churn (4/120; control 0/120); it is analogous evidence,
221+
not an IDE reproduction. A later passing run does not clear this issue.
222+
Observed only in the Linux Xvfb/Openbox fixture on IU-253.28294.334. Other
223+
platforms, builds, and live click races are untested. Trace excerpts and
224+
failed-run references are in [the validation report](validation/chat-focus-preservation.md).
225+
226+
## 4. General Troubleshooting Steps
172227

173228
If you encounter any of the above issues, follow these general troubleshooting steps:
174229

@@ -180,7 +235,7 @@ If you encounter any of the above issues, follow these general troubleshooting s
180235

181236
---
182237

183-
## 4. Reporting New Issues
238+
## 5. Reporting New Issues
184239

185240
If you encounter issues not documented here, please report them with the following information:
186241

Lines changed: 230 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,230 @@
1+
# Chat focus validation summary
2+
3+
Status 2026-10-17. Two plugin-owned focus defects are fixed and test-covered:
4+
terminal creation stealing chat focus, and `preserveFocus` dropped by the diff
5+
RPC decoder. The intermittent first-turn draft loss during real conversations
6+
is **open**: not fixed, and not conclusively attributed. `docs/KNOWN_ISSUES.md`
7+
links this file. Raw evidence paths below are relative to
8+
`jetbrains_plugin/build/ui-harness/evidence/`. Those directories are local,
9+
ignored artifacts kept in the investigation workspace; this file carries the
10+
decisive excerpts for a clean checkout.
11+
12+
## Plugin-owned fix 1: bounded terminal-creation focus restoration
13+
14+
Proven trigger. `TerminalInstance.addToTerminalToolWindow` calls
15+
`TerminalToolWindowManager.newTab`, which inserts and selects the new content
16+
with focus enabled. The platform then moves Swing focus from the chat
17+
`JBCefOsrComponent` to `JBTerminalPanel`, and typed text goes to the terminal.
18+
The bytecode pin from the actual IDE (IU-253.28294.334) is in
19+
`terminal-stack-baseline/terminal-manager-bytecode.txt`:
20+
21+
```text
22+
newTab: iconst_1; iconst_1; invokevirtual createNewTab(..., boolean, boolean)
23+
createNewTab: ToolWindow.activate(runnable, true, true)
24+
selection runnable: ContentManager.setSelectedContent(content, requestFocus)
25+
```
26+
27+
The transition trace in `terminal-stack-baseline/progress.log` records T7
28+
production creation before the fix. The intended post-creation text was
29+
`createpost`; none reached chat.
30+
31+
```text
32+
BATTERY-MARK ts=40771 step=T7-production-preserving-show
33+
FOCUS-TIME ts=40796 prop=focusOwner old=com.intellij.ui.jcef.JBCefOsrComponent new=null
34+
FOCUS-TIME ts=40797 prop=focusOwner old=null new=com.intellij.terminal.JBTerminalPanel
35+
RECORD T7_creationFocusOwner = com.intellij.terminal.JBTerminalPanel
36+
```
37+
38+
Fix. `TerminalCreationFocusGuard` captures the exact Swing chat owner before
39+
terminal initialization. After creation it joins `ToolWindowManager.invokeLater`
40+
and waits once for native focus to settle. It restores the captured component
41+
once, only if focus ended inside the newly created terminal, chat stays visible,
42+
the project is alive, and no user click, key, or Tab traversal intervened.
43+
Focus in an editor or balloon is left alone. Input observation ends at the
44+
callback or 1500 ms after creation. There is no polling loop, permanent
45+
listener, repeated request, or unconditional restoration. Manager shutdown uses
46+
a volatile flag, and refused JCEF registrations are disposed on the EDT outside
47+
the ownership lock. The deliberate-show `ManualFocusGuard` is unchanged except
48+
for documenting this bounded exception.
49+
50+
Ordering evidence. `terminal-inline-callback-diagnostic/idea.log` records the
51+
focus-settled callback before platform activation seeing the chat owner and
52+
returning `restore=false`. `terminal-queued-callback-diagnostic/idea.log`
53+
records the callback after the tool-window queue seeing `JBTerminalPanel` and
54+
returning `restore=true` for T2 and T7, with exact typing probes passing. Later
55+
attempts of that diagnostic died to system OOM
56+
(`terminal-final-oom/`, `terminal-reduced-heap-oom/`); T7 observations after a
57+
renderer kill are invalid, not regressions or passes. Final runs execute the
58+
batteries sequentially and retain intermediate failures.
59+
60+
## Plugin-owned fix 2: diff preserveFocus decoding
61+
62+
The bundled extension passes `{preserveFocus:true}` to `vscode.diff`, but the
63+
extension host wraps the options in a tuple
64+
(`deps/vscode/src/vs/workbench/api/common/extHostApiCommands.ts:459`:
65+
`[ViewColumn.from(...), TextEditorOpenOptions.from(...)]`). The Kotlin decoder
66+
accepted only a map, so the real task logged `Opening diff, preserveFocus=false`
67+
and the focus recorder caught an editor transition at ts=113909 with return to
68+
the chat canvas at ts=113974. `decodeDiffPreserveFocus` now unwraps the tuple's
69+
options member and still accepts direct-map callers. Missing or malformed flags
70+
keep the existing false default. Four unit cases pin true, false, missing
71+
options, and malformed input.
72+
73+
Bundled extension note. The bundled Zoo Code extension 3.84.0 command runner
74+
calls `terminal.show(true)` before `runCommand` (bundle SHA-256
75+
`2fe6fbde2ba7bc67e0c2e3f7eed62246da3cd9554a1ae2b9090faa1a7a0385b7`), so the
76+
changed omitted-argument default does not force terminal focus on that path.
77+
Explicit false or an omitted argument from another caller still requests
78+
terminal focus.
79+
80+
## Test status
81+
82+
The CI allowlist command in `.github/workflows/pr.yml` passes with **104 tests,
83+
0 failures, 0 errors, 0 skipped** (local output `review-3-unit-tests.log`).
84+
Historical 86 and 100 counts describe earlier builds. The local relay tests
85+
pass (`python3 -m unittest test_solheim_proxy.py`; twelve cases after the
86+
run-4 relay hardening). Shell syntax and diff whitespace checks pass. The full
87+
platform-fixture suite was not rerun; its previously documented failures are
88+
not claimed fixed.
89+
90+
## Harness results
91+
92+
Live-run environment: harness IDE IU-253.28294.334, Linux Xvfb with Openbox,
93+
heap 768 MB, 4 CPUs, plugin zip SHA-256
94+
`4d9b34ca46c4bbe0aba7637181e697da4f1bcbb96590d87efdf99c72ab3865e4` unless
95+
noted. Conversation runs use the real bundled extension, the real React
96+
textarea, real tool execution, and Solheim `qwen3.8-27b` through the
97+
loopback-only relay (`scripts/ui-harness/solheim_proxy.py`). No simulated
98+
provider responses or injected chat input are used for the conversation battery.
99+
100+
Corrected runs on plugin-owned paths:
101+
102+
- Mode F: PASS. Typing reaches the input with the OSR canvas focused
103+
(`typedWithCanvasFocusVerdict=true`) and stops when Swing focus moves
104+
elsewhere (`keysLostWhenFocusMovedVerdict=true`). Evidence: `f/`.
105+
- Mode T: plugin-owned paths pass. T2 production creation, T2R streaming and
106+
editor replay, T3 visibility-only show, T7 creation and preserving show, and
107+
T8 deliberate show. Evidence: `t/`. Stock first-show (T1) and stock
108+
new-tab/selection (T4) still focus the terminal; see the classification
109+
below.
110+
- Mode G, corrected final run: PASS. G6 manual click recovery, G7 preserving
111+
editor bridge with exact owner identity and post-bridge typing, and G8
112+
disposal typing. G1 reload and G5/G6 raw hide-show without manual refocus
113+
still do not type; recorded as-is. Evidence: `g/`. The earlier invalid run
114+
that clicked the retired browser is `g-native-stale-browser/`.
115+
- Mode P, final instrumented run: PASS in 103 seconds. Thirty exact first-turn
116+
samples and five exact follow-up samples; history grew 21 then 29 messages;
117+
three real commands exited 0; the diff logged `preserveFocus=true`. Evidence:
118+
`p/`. This 35/35 pass is historical; the latest conversation run below
119+
supersedes it.
120+
121+
Deliberate stock user actions, classified separately. The first Terminal
122+
tool-window show and stock tab-selection and new-session paths move focus to
123+
the terminal by platform design. The plugin does not wrap these stock actions,
124+
and this report does not classify them as defects. The preserving-show and
125+
deliberate-show harness checks for these paths remain required.
126+
127+
Fixture corrections, not product issues. The IDEA script-launcher warning
128+
balloon covered the textarea in early runs; the fixture now uses the native
129+
launcher. One G prerequisite clicked the browser retired during webview
130+
replacement; the harness now references the mounted browser. The driver also
131+
waits for smart mode and a showing browser before its setup click. These were
132+
test-setup defects. No balloon-restoration or permanent focus code was added to
133+
the plugin.
134+
135+
## Latest real provider run: FAIL
136+
137+
**FAIL-REAL-CONVERSATION**, 123 seconds, on the same executable plugin
138+
artifact. Both real turns completed; history grew, commands ran, the fixture
139+
changed, and the diff opened with `preserveFocus=true`. Draft preservation
140+
failed: the first turn kept **32 of 33** characters, the follow-up kept **6 of
141+
6**. The first mismatch is sample 16 (`snapshot=19`): 15 actual characters
142+
against 16 expected, with the chat still active. Raw evidence:
143+
`review-3-standalone-p/`; earlier startup failures:
144+
`review-3-standalone-startup-{1,2,3}/`.
145+
146+
No browser remount occurred around the loss: the only mount and repeated-mount
147+
logs are at 01:05:59 and 01:06:00, and the diff opened at 01:06:46.305. The
148+
Swing owner stayed on the chat OSR canvas. The affected sample logs only the
149+
key release in the IDE PRE/POST trace:
150+
151+
```text
152+
E2EAWT PRE ts=1791940006381 when=1791940006326 id=402 key=88 char=120 consumed=false owner=com.intellij.ui.jcef.JBCefOsrComponent@5f8aec10
153+
E2EAWT POST ts=1791940006382 when=1791940006326 id=402 key=88 consumed=false source=com.intellij.ui.jcef.JBCefOsrComponent@5f8aec10
154+
RECORD P_expected_16 = xxxxxxxxxxxxxxxx
155+
```
156+
157+
No matching key press or DOM keydown or input arrived for that sample. The
158+
trace narrows the gap to delivery before the recorded IDE preprocessors. It
159+
does not prove which platform call caused it.
160+
161+
Two earlier real runs on this build each lost one character near the first
162+
file-editor opening (`p-tuple-fix-one-key-loss/`, `p-dom-key-loss/`); DOM
163+
tracing there showed no textarea replacement and no blur. An intermediate
164+
complete run is preserved as FAIL for a stale probe sample
165+
(`p-complete-stale-probe/`), and a partial first attempt as
166+
`p-native-partial-first/`.
167+
168+
## JDK probe: analogous evidence and its limits
169+
170+
`jetbrains_plugin/scripts/ui-harness/KeyDropProbe.java` is a JDK-only probe
171+
with no IDE, plugin, or JCEF code. It types with `java.awt.Robot` and counts
172+
press, typed, and release deliveries. In a local manual run, deliberate focus
173+
churn produced release-without-press **4 times in 120 keys**, while the control
174+
mode produced **0 in 120**. The probe's churn styles change the focus owner;
175+
the IDE trace above kept the owner stable. The probe therefore shows that a
176+
release can arrive without its press under focus churn in a pure JDK and Swing
177+
stack. It does not reproduce the IDE mechanism, does not identify the
178+
initiating IDE platform call, and does not prove a JDK root cause or clear the
179+
product defect. Single runs are nondeterministic; compare control and churn on
180+
the same host in the same session.
181+
182+
## Remaining validation gaps
183+
184+
- The intermittent first-turn draft loss is **open**: no fix, no proven
185+
initiating call, and later passing runs do not clear it.
186+
- macOS, native Windows, and other IDE builds are untested. The live
187+
preserving-diff chain is exercised on build 253 only; builds 233/263 are
188+
untested.
189+
- Live user-click races during the guard window are untested. Controlled guard
190+
lifecycle tests cover clicks, Tab traversal, expiry, repeated callbacks,
191+
hidden chat, and disposal before or while queued.
192+
- The full platform-fixture suite was not rerun; its previously documented
193+
failures are not claimed fixed.
194+
195+
## Reproduction
196+
197+
Build and harness modes T/G/F/P:
198+
199+
```sh
200+
cd jetbrains_plugin
201+
./gradlew buildPlugin -PdebugMode=release -PvscodePlugin=zoo-code --no-configuration-cache
202+
cd build/ui-harness
203+
unzip -oq ../distributions/ZooCode-3.78.0.zip -d plugins-dist
204+
HARNESS_HEAP_MB=768 HARNESS_CPU_COUNT=4 IDE_DIR=$PWD/ide-253 DEADLINE_SECONDS=600 bash bin/run-test.sh t
205+
HARNESS_HEAP_MB=768 HARNESS_CPU_COUNT=4 IDE_DIR=$PWD/ide-253 DEADLINE_SECONDS=600 bash bin/run-test.sh g
206+
HARNESS_HEAP_MB=768 HARNESS_CPU_COUNT=4 IDE_DIR=$PWD/ide-253 DEADLINE_SECONDS=600 bash bin/run-test.sh f
207+
```
208+
209+
The live provider conversation needs the relay and key setup from
210+
`jetbrains_plugin/scripts/ui-harness/README.md`. The JDK probe needs only Xvfb
211+
and a headful JDK:
212+
213+
```sh
214+
cd jetbrains_plugin/scripts/ui-harness
215+
xvfb-run -a /path/to/headful-jdk/bin/java KeyDropProbe.java control 120 7
216+
xvfb-run -a /path/to/headful-jdk/bin/java KeyDropProbe.java churn 120 7 hidden-frame
217+
```
218+
219+
## Evidence index (local, ignored)
220+
221+
Under `jetbrains_plugin/build/ui-harness/evidence/`: `review-3-standalone-p/`
222+
(latest FAIL), `review-3-standalone-startup-{1,2,3}/`, `p/` (historical
223+
instrumented pass), `p-tuple-fix-one-key-loss/`, `p-dom-key-loss/`,
224+
`p-complete-stale-probe/`, `p-native-partial-first/`,
225+
`terminal-stack-baseline/`, `terminal-replay-baseline/`,
226+
`terminal-inline-callback-diagnostic/`,
227+
`terminal-queued-callback-diagnostic/`, `terminal-final-oom/`,
228+
`terminal-reduced-heap-oom/`, `t/`, `g/`, `f/`, `g-native-stale-browser/`,
229+
unit XML in `review-fixes-unit-results/` and
230+
`terminal-creation-unit-results/`, and earlier reports `FOCUS_FIX_REPORT*.md`.

‎jetbrains_plugin/build.gradle.kts‎

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -498,6 +498,12 @@ ktlint {
498498
}
499499
}
500500

501+
// Run unit tests without a display; Swing components used by the regression
502+
// tests must initialize in headless mode
503+
tasks.named<Test>("test") {
504+
systemProperty("java.awt.headless", "true")
505+
}
506+
501507
// Configure detekt
502508
detekt {
503509
toolVersion = "1.23.4"
Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1 @@
1+
__pycache__/

0 commit comments

Comments
 (0)