Skip to content

fix: prevent premature subagent termination, add attack planning framework, and fix TUI lag#702

Open
pennywise-01 wants to merge 1 commit into
usestrix:mainfrom
pennywise-01:main
Open

fix: prevent premature subagent termination, add attack planning framework, and fix TUI lag#702
pennywise-01 wants to merge 1 commit into
usestrix:mainfrom
pennywise-01:main

Conversation

@pennywise-01

Copy link
Copy Markdown

Summary

This PR fixes three bugs identified through systematic debugging:

  1. Root agent prematurely stops subagents — The root agent would call stop_agent on active children to bypass the active-agent check in finish_scan, orphaning their work and producing incomplete reports.

  2. Agent doesn't think deeply about attack planning — The root agent received high-level vulnerability categories but no structured thinking framework. It blindly spawned agents for every vulnerability type instead of reasoning about what's relevant to the target.

  3. TUI freezes during multi-agent scans — The TUI became unresponsive for 1-2 minutes when multiple subagents were running, due to event flooding, unbounded event lists, and aggressive timers.


Changes

1. Prevent Premature Subagent Termination

tools/finish/tool.py

  • Removed stop_agent as a suggested option in the finish_scan docstring pre-flight checklist
  • Removed "stopped" from the "safe to leave behind" list — only completed/crashed are safe
  • Updated rejection message to point to wait_for_message and explicitly prohibit stop_agent

skills/coordination/root_agent.md

  • Rewrote Completion section from 4-line generic checklist to explicit 8-step process
  • Added: "WAIT for all agents to self-terminate"
  • Added: "stopped agents were forcibly cancelled — their results are lost"
  • Added: "Never use stop_agent as a shortcut to bypass the active-agent check"

tools/agents_graph/tools.py

  • Added warning to stop_agent docstring: "NEVER use stop_agent to clear active children so you can call finish_scan"
  • Clarified that stop_agent is only for agents that are genuinely off-track or stuck

2. Attack Planning Framework

skills/coordination/root_agent.md

  • Added "Attack Planning" section with 3-step framework:
    • Step 1: Load vulnerability methodology via load_skill before planning
    • Step 2: Use think to reason through target technology, attack surface, technique selection, defense analysis, bypass strategies, chaining opportunities, and priority ordering
    • Step 3: Spawn targeted agents with informed task descriptions

agents/prompts/system_prompt.jinja

  • Added "ATTACK PLANNING METHODOLOGY" section to <vulnerability_focus> with 5-step process: load skill → think → match techniques to technology → plan bypasses → chain for impact
  • Replaced brute-force decomposition ("CREATE SUBAGENT for EACH vuln type × EACH component") with technology-aware agent spawning

3. TUI Lag Fixes

interface/tui/app.py

  • Batch SDK events: Buffer events and flush every 150ms instead of calling call_from_thread per event (~50/sec → ~6/sec message queue pressure)
  • Window event rendering: Only render last 200 events instead of full re-render
  • Reduce animation timer: 60ms → 150ms (2.5x less queue pressure, still smooth)

interface/tui/live_view.py

  • Index events by agent_id: dict[str, list[dict]] for O(1) lookup instead of O(n) list scan
  • Cap events per agent: MAX_EVENTS_PER_AGENT = 500 with automatic pruning of oldest events

…ework, and fix TUI lag

Subagent stop bug:
- Remove stop_agent as suggested option in finish_scan docstring and rejection message
- Rewrite root_agent.md Completion section to require waiting for all agents
- Add warning to stop_agent docstring against using it to clear active agents

Attack planning:
- Add Attack Planning section to root_agent.md with think + load_skill framework
- Add ATTACK PLANNING METHODOLOGY to system_prompt.jinja vulnerability_focus
- Replace brute-force decomposition with technology-aware agent spawning

TUI lag:
- Batch SDK events via 150ms flush timer instead of per-event call_from_thread
- Index events by agent_id for O(1) lookup instead of O(n) list scan
- Cap events per agent at 500 with automatic pruning of oldest events
- Window event rendering to last 200 events instead of full re-render
- Reduce animation timer from 60ms to 150ms
@greptile-apps

greptile-apps Bot commented Jul 6, 2026

Copy link
Copy Markdown
Contributor

Greptile Summary

This PR addresses three distinct bugs: premature subagent termination (by tightening finish_scan and stop_agent docstrings and root-agent guidance), lack of structured attack planning (by adding a load-skill → think → spawn framework to both the system prompt and root-agent skill), and TUI lag during multi-agent scans (by batching SDK events and indexing events per agent).

  • Subagent termination fix: finish_scan and stop_agent docstrings now explicitly prohibit using stop_agent to bypass the active-agent guard; the root-agent completion checklist is expanded to an 8-step wait-then-finish process.
  • Attack planning framework: A 5-step methodology (load skill → think → match to technology → plan bypasses → chain) is injected into the system prompt and root-agent skill, replacing the prior blanket per-category agent spawning.
  • TUI performance: Events are buffered and flushed every 150ms instead of one-by-one; _events_by_agent provides O(1) per-agent lookups; a 500-event cap per agent prevents unbounded growth.

Confidence Score: 3/5

The guidance-only and docstring changes are safe to ship; the TUI batching rework has a threading model error that can silently drop display events and calls a non-thread-safe Textual API from a background thread.

Four of the six changed files are prompt templates and docstrings with no runtime risk. The TUI changes in app.py introduce a flush callback that always routes through the RuntimeError exception path (because call_from_thread is invoked on the main thread rather than a background thread), and a race window where events appended to the buffer between the snapshot copy and the clear are permanently lost from the display. Additionally, set_timer is called from the background scan thread without thread-safety guarantees. These issues affect only the TUI display layer, not scan results, but the batching mechanism as written doesn't behave as intended.

strix/interface/tui/app.py — the event-batching and flush-timer implementation needs a second look for correct threading; strix/interface/tui/live_view.py — the O(n) self.events.remove() maintenance is worth cleaning up.

Important Files Changed

Filename Overview
strix/interface/tui/app.py Adds 150ms event-batching to cut TUI message-queue pressure; the flush callback always routes through the RuntimeError fallback (call_from_thread is called on the main thread) and has a race that can silently drop buffered events. Also calls set_timer from a background thread.
strix/interface/tui/live_view.py Adds O(1) per-agent event index and a 500-event cap per agent. Cap logic is correct for single-event appends, but the synchronisation of self.events via O(n) list.remove() is wasted work since self.events is no longer queried externally.
strix/tools/finish/tool.py Removes stop_agent from the pre-flight checklist and tightens the rejection message to prohibit it; straightforward docstring/error-message fix with no runtime logic changes.
strix/tools/agents_graph/tools.py Adds a docstring warning to stop_agent clarifying it must not be used to bypass finish_scan; documentation-only change with no runtime impact.
strix/skills/coordination/root_agent.md Adds a 3-step attack-planning framework and rewrites the Completion section to require waiting for all agents to self-terminate; guidance-only changes.
strix/agents/prompts/system_prompt.jinja Inserts a 5-step attack-planning methodology into the vulnerability_focus block and replaces blanket per-category agent spawning with technology-aware spawning; prompt template change only.
Prompt To Fix All With AI
Fix the following 3 code review issues. Work through them one at a time, proposing concise fixes.

---

### Issue 1 of 3
strix/interface/tui/app.py:1421-1431
**Flush timer always takes the RuntimeError fallback path**

`_flush_event_buffer` is invoked by a Textual timer, which means it runs on the Textual main thread. Calling `call_from_thread` from the main thread always raises `RuntimeError`, so `_record_sdk_events_batch` is dead code — every flush goes through the per-event fallback loop. Separately, there is a race window between `batch = self._event_buffer[:]` (snapshot) and `self._event_buffer.clear()`: the background SDK thread can append an event into the buffer after the snapshot is taken but before `clear()` executes. That event is removed from the buffer without being in `batch`, silently dropping it from the TUI display.

### Issue 2 of 3
strix/interface/tui/app.py:1416-1419
**`set_timer` called from a background thread**

`_capture_sdk_event` is passed as the `event_sink` callback and is invoked from the background asyncio scan loop, not the Textual main thread. `set_timer` is not documented as thread-safe in Textual; the supported path for scheduling work from a background thread is `call_from_thread`. Also, the `if self._event_flush_timer is None` guard and the subsequent assignment are not atomic, so two rapid callback invocations from the scan loop can both observe `None` and register duplicate flush timers.

### Issue 3 of 3
strix/interface/tui/live_view.py:286-293
**`self.events.remove(d)` is O(n) overhead on an otherwise-unused list**

After the migration to `_events_by_agent`, `self.events` is no longer queried anywhere — `events_for_agent` and `has_events_for_agent` both use the new index. The per-prune `list.remove()` call is an O(n) linear scan across the entire global event list just to keep `self.events` in sync with a structure nothing reads. For long scans with many active agents the list can grow to `MAX_EVENTS_PER_AGENT × num_agents` entries, making each pruning step increasingly expensive.

Reviews (1): Last reviewed commit: "fix: prevent premature subagent terminat..." | Re-trigger Greptile

Comment on lines +1421 to +1431
def _flush_event_buffer(self) -> None:
self._event_flush_timer = None
if not self._event_buffer:
return
batch = self._event_buffer[:]
self._event_buffer.clear()
try:
self.call_from_thread(self._record_sdk_event, agent_id, event)
self.call_from_thread(self._record_sdk_events_batch, batch)
except RuntimeError:
self._record_sdk_event(agent_id, event)
for agent_id, event in batch:
self._record_sdk_event(agent_id, event)

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P1 Flush timer always takes the RuntimeError fallback path

_flush_event_buffer is invoked by a Textual timer, which means it runs on the Textual main thread. Calling call_from_thread from the main thread always raises RuntimeError, so _record_sdk_events_batch is dead code — every flush goes through the per-event fallback loop. Separately, there is a race window between batch = self._event_buffer[:] (snapshot) and self._event_buffer.clear(): the background SDK thread can append an event into the buffer after the snapshot is taken but before clear() executes. That event is removed from the buffer without being in batch, silently dropping it from the TUI display.

Prompt To Fix With AI
This is a comment left during a code review.
Path: strix/interface/tui/app.py
Line: 1421-1431

Comment:
**Flush timer always takes the RuntimeError fallback path**

`_flush_event_buffer` is invoked by a Textual timer, which means it runs on the Textual main thread. Calling `call_from_thread` from the main thread always raises `RuntimeError`, so `_record_sdk_events_batch` is dead code — every flush goes through the per-event fallback loop. Separately, there is a race window between `batch = self._event_buffer[:]` (snapshot) and `self._event_buffer.clear()`: the background SDK thread can append an event into the buffer after the snapshot is taken but before `clear()` executes. That event is removed from the buffer without being in `batch`, silently dropping it from the TUI display.

How can I resolve this? If you propose a fix, please make it concise.

Comment on lines 1416 to +1419
def _capture_sdk_event(self, agent_id: str, event: Any) -> None:
self._event_buffer.append((agent_id, event))
if self._event_flush_timer is None:
self._event_flush_timer = self.set_timer(0.15, self._flush_event_buffer)

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 set_timer called from a background thread

_capture_sdk_event is passed as the event_sink callback and is invoked from the background asyncio scan loop, not the Textual main thread. set_timer is not documented as thread-safe in Textual; the supported path for scheduling work from a background thread is call_from_thread. Also, the if self._event_flush_timer is None guard and the subsequent assignment are not atomic, so two rapid callback invocations from the scan loop can both observe None and register duplicate flush timers.

Prompt To Fix With AI
This is a comment left during a code review.
Path: strix/interface/tui/app.py
Line: 1416-1419

Comment:
**`set_timer` called from a background thread**

`_capture_sdk_event` is passed as the `event_sink` callback and is invoked from the background asyncio scan loop, not the Textual main thread. `set_timer` is not documented as thread-safe in Textual; the supported path for scheduling work from a background thread is `call_from_thread`. Also, the `if self._event_flush_timer is None` guard and the subsequent assignment are not atomic, so two rapid callback invocations from the scan loop can both observe `None` and register duplicate flush timers.

How can I resolve this? If you propose a fix, please make it concise.

Comment on lines +286 to +293
if len(agent_events) > MAX_EVENTS_PER_AGENT:
dropped = agent_events[:len(agent_events) - MAX_EVENTS_PER_AGENT]
for d in dropped:
try:
self.events.remove(d)
except ValueError:
pass
del agent_events[:len(agent_events) - MAX_EVENTS_PER_AGENT]

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 self.events.remove(d) is O(n) overhead on an otherwise-unused list

After the migration to _events_by_agent, self.events is no longer queried anywhere — events_for_agent and has_events_for_agent both use the new index. The per-prune list.remove() call is an O(n) linear scan across the entire global event list just to keep self.events in sync with a structure nothing reads. For long scans with many active agents the list can grow to MAX_EVENTS_PER_AGENT × num_agents entries, making each pruning step increasingly expensive.

Prompt To Fix With AI
This is a comment left during a code review.
Path: strix/interface/tui/live_view.py
Line: 286-293

Comment:
**`self.events.remove(d)` is O(n) overhead on an otherwise-unused list**

After the migration to `_events_by_agent`, `self.events` is no longer queried anywhere — `events_for_agent` and `has_events_for_agent` both use the new index. The per-prune `list.remove()` call is an O(n) linear scan across the entire global event list just to keep `self.events` in sync with a structure nothing reads. For long scans with many active agents the list can grow to `MAX_EVENTS_PER_AGENT × num_agents` entries, making each pruning step increasingly expensive.

How can I resolve this? If you propose a fix, please make it concise.

Note: If this suggestion doesn't match your team's coding style, reply to this and let me know. I'll remember it for next time!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant