Skip to content

fix(agents): keep-awake + sidebar attribution from foreground process evidence - #9415

Closed
bbingz wants to merge 8 commits into
stablyai:mainfrom
bbingz:bbingz/unknown-busy-and-wrapper-visibility
Closed

bbingz wants to merge 8 commits into
stablyai:mainfrom
bbingz:bbingz/unknown-busy-and-wrapper-visibility

Conversation

@bbingz

@bbingz bbingz commented Jul 19, 2026 •

Copy link
Copy Markdown
Contributor

Part of #9414

Keep-awake and sidebar attribution now follow foreground-process evidence, so the machine is less likely to sleep and a tab is less likely to read idle while a real agent is still the process in front — including wrapper-launched agents with no recognizable title.

Status (2026-08-06 restack note)

An earlier note here said the busy half was fully superseded by main. Re-checked against main (79896cb): only the first half is.

  • Already on main — the pre-confirmation gate classifies shell vs non-shell. src/main/runtime/orca-runtime.ts:16630 returns false for any non-shell foreground process, so a plain unrecognized foreground already counts as busy.
  • Still open on main — the confirmation branch ignores unrecognized processes. When a stronger provider re-reads the foreground, src/main/runtime/orca-runtime.ts:16647 returns recognizeAgentProcess(confirmedProcess) === null, so an unrecognized-but-alive process is read as "no agent" and the terminal is reported not running. This PR narrows that to confirmedProcess === null || isShellProcess(confirmedProcess): only a confirmed shell proves the agent exited.

The branch carries brennanb2025's fix(awake): reuse existing foreground inspections (11b6ed4), preserved through the latest rebase.

Problem

  • Keep-awake can drop while a real agent is in the foreground if hooks and title are quiet
  • The sidebar misses wrapper-launched Claude (and similar) when OSC/title identity is empty
  • Foreground confirmation discards a live agent it cannot name

Solution

  • Report foreground agent evidence with freshness (observedAt / TTL), reusing completed provider inspections rather than adding scans
  • Drive keep-awake and sidebar / worktree-ring attribution from that evidence
  • Treat a confirmed non-shell foreground as still running, recognized or not

Stack

Test plan

  • Wrapper-launched Claude appears in the sidebar without an agent title
  • Keep-awake holds while foreground evidence is fresh; expires on TTL
  • A confirmed unrecognized non-shell foreground keeps the terminal busy
  • Rebase clean

Focused suites re-run post-rebase at 5f08623 (2026-08-06): agent-awake-service, pane-foreground-agent, worktree-title-derived-agent-rows, ipc/pty, orca-runtime — 1586 passed / 1 skipped.

ELI5

Keep-awake and sidebar busy state now lean on real foreground-process evidence. Orca is less likely to sleep the machine or mislabel a tab while an agent it cannot name by title is still the process in front.

@coderabbitai

coderabbitai Bot commented Jul 19, 2026 •

Copy link
Copy Markdown
Contributor

Review Change Stack

Note

Reviews paused

It looks like this branch is under active development. To avoid overwhelming you with review comments due to an influx of new commits, CodeRabbit has automatically paused this review. You can configure this behavior by changing the reviews.auto_review.auto_pause_after_reviewed_commits setting.

Use the following commands to manage reviews:

  • @coderabbitai resume to resume automatic reviews.
  • @coderabbitai review to trigger a single review.

Use the checkboxes below for quick actions:

  • ▶️ Resume reviews
  • 🔍 Trigger review
📝 Walkthrough

Walkthrough

Adds TTL-based foreground-agent evidence tracking for keep-awake eligibility, including per-PTY reporting, renewal, stale-cap expiry, and timer scheduling. Runtime PTY scans and inspections now emit or refresh PTY-bound evidence, while stopped PTYs clear it. Renderer state records timestamps and PTY identity, filters stale or mismatched evidence, scopes it to worktrees, and uses it to attribute title-derived agent activity. Expiry-driven hooks recompute worktree statuses and agent rows when evidence becomes stale.

🚥 Pre-merge checks | ✅ 1 | ❌ 4

❌ Failed checks (4 warnings)

Check name Status Explanation Resolution
Linked Issues check ⚠️ Warning The linked issue is about typed close intent and host-side session-tab close adjudication, but this PR only changes foreground-evidence keep-awake and sidebar attribution. Either link the correct issue for this PR or add the typed close-intent host-adjudication changes and tests required by #8872.
Out of Scope Changes check ⚠️ Warning The diff is centered on foreground-process evidence plumbing, keep-awake, sidebar attribution, and tests, but it does not implement the linked issue's typed close-intent work. Remove or re-scope this PR to the linked issue, or update the linked issue set so the foreground-evidence changes are in-scope.
Docstring Coverage ⚠️ Warning Docstring coverage is 35.48% which is insufficient. The required threshold is 80.00%. Write docstrings for the functions missing them to satisfy the coverage threshold.
Description check ⚠️ Warning The description explains the scope and includes focused test results, but it omits the required Screenshots, AI Review Report, Security Audit, and Notes sections. Add all missing template sections, mark the testing checklist accurately, and include the required cross-platform AI review and security audit details.
✅ Passed checks (1 passed)
Check name Status Explanation
Title check ✅ Passed The title clearly summarizes the main keep-awake and sidebar attribution changes driven by foreground process evidence.

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ Share

Comment @coderabbitai help to get the list of available commands.

@brennanb2025

Copy link
Copy Markdown
Contributor

Taking a look!

@brennanb2025
brennanb2025 force-pushed the bbingz/unknown-busy-and-wrapper-visibility branch from 15aa992 to 607f130 Compare July 21, 2026 03:53
@brennanb2025

Copy link
Copy Markdown
Contributor

Thanks for the thoughtful fix. I rebased the branch onto current main and tightened the keep-awake wiring so known launch agents—including wrapper launches without hooks—reuse the renderer’s existing foreground-process inspections; this closes the remaining gap without adding scans or changing scan cadence. I also preserved the PTY-bound/TTL expiry safeguards, applied the review comment cleanup, and verified the affected runtime, IPC, sidebar, scan-volume, typecheck, and lint suites.

@bbingz
bbingz force-pushed the bbingz/unknown-busy-and-wrapper-visibility branch from 607f130 to 9d0b62d Compare July 22, 2026 01:29
@bbingz

bbingz commented Jul 22, 2026

Copy link
Copy Markdown
Contributor Author

@brennanb2025 Rebased onto current `origin/main` and force-pushed (`bbingz/unknown-busy-and-wrapper-visibility` → `$(git rev-parse HEAD)`).

Conflict resolution in title-derived agent rows:

@bbingz

bbingz commented Jul 22, 2026

Copy link
Copy Markdown
Contributor Author

@brennanb2025 Correction: rebased head is 9d0b62d3c5 (force-pushed to bbingz/unknown-busy-and-wrapper-visibility). Prior comment had an unexpanded shell placeholder for the SHA.

Conflict resolution summary stands: main's braille → launchAgent fallback kept; PR process-identity attribution re-applied; your inspection-reuse commit preserved.

@bbingz

bbingz commented Jul 22, 2026

Copy link
Copy Markdown
Contributor Author

@brennanb2025 Rebased onto current main (head 9d0b62d3c5), preserving your “reuse existing foreground inspections” follow-up and reconciling sidebar title-derived rows with main’s braille→launchAgent fallback.

Ready for re-review / merge.

@bbingz bbingz changed the title fix(agents): treat unrecognized-but-running agents as busy; surface wrapper-launched claude in the sidebar fix(agents): keep-awake + sidebar attribution from foreground process evidence Jul 23, 2026
@bbingz
bbingz force-pushed the bbingz/unknown-busy-and-wrapper-visibility branch from 9d0b62d to 7bc527a Compare July 23, 2026 03:32
@bbingz

bbingz commented Jul 23, 2026

Copy link
Copy Markdown
Contributor Author

Restack + review guide (community, awaiting maintainer)

Rebased onto latest main (force-with-lease). 5 commits, behind=0. Title/body already rewritten for residual scope.

Partial supersession note

Main already treats unrecognized non-shell FG as busy (hook-status gate). One commit in this series still carries that theme — reviewers: prefer keep-awake + sidebar attribution; busy predicate may be redundant with main and can be dropped in a follow-up trim if desired.

Unique residual (primary value)

  1. Keep-awake held from FG evidence (TTL + revalidation; 2h-cap leak fix)
  2. Sidebar / worktree ring attribution from TTL-gated pane process identity
  3. Reuse existing foreground inspections (awake path)

Stack

#9415 (this)
  └── #9434 (draft) exe-image recognition + SSH confirmForeground
        └── #9435 (draft) structured FG result + unknown-live tab icon

Tests (local)

  • pane-foreground-agent + worktree-status — 46 passed

Community author cannot merge.

@coderabbitai coderabbitai Bot left a comment

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.

Actionable comments posted: 1


ℹ️ Review info
⚙️ Run configuration

Configuration used: Repository UI

Review profile: CHILL

Plan: Pro Plus

Run ID: e74ac69a-3324-4df2-9f16-5caae87e4d7e

📥 Commits

Reviewing files that changed from the base of the PR and between 9d0b62d3c5234023a71c59d3b1540715852d7a04 and 7bc527a46749e3bc3a467ef64ce3d5f6248ba302.

📒 Files selected for processing (8)
  • src/main/agent-awake-foreground-evidence.ts
  • src/main/agent-awake-service.test.ts
  • src/main/agent-awake-service.ts
  • src/main/index.ts
  • src/main/ipc/pty.test.ts
  • src/main/ipc/pty.ts
  • src/main/runtime/orca-runtime.test.ts
  • src/main/runtime/orca-runtime.ts
🚧 Files skipped from review as they are similar to previous changes (6)
  • src/main/index.ts
  • src/main/agent-awake-service.test.ts
  • src/main/runtime/orca-runtime.ts
  • src/main/runtime/orca-runtime.test.ts
  • src/main/agent-awake-service.ts
  • src/main/agent-awake-foreground-evidence.ts

Comment thread src/main/ipc/pty.ts Resolved
@bbingz
bbingz force-pushed the bbingz/unknown-busy-and-wrapper-visibility branch from 7bc527a to 9c8d7c8 Compare July 24, 2026 08:16
@bbingz
bbingz force-pushed the bbingz/unknown-busy-and-wrapper-visibility branch from 9c8d7c8 to 2d6164a Compare July 26, 2026 07:37

@coderabbitai coderabbitai Bot left a comment

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.

Actionable comments posted: 1


ℹ️ Review info
⚙️ Run configuration

Configuration used: Repository UI

Review profile: CHILL

Plan: Pro Plus

Run ID: 1a434da9-9611-48c3-acdf-cf2a460ac617

📥 Commits

Reviewing files that changed from the base of the PR and between 9c8d7c8 and 2d6164a.

📒 Files selected for processing (8)
  • src/main/agent-awake-foreground-evidence.ts
  • src/main/agent-awake-service.test.ts
  • src/main/agent-awake-service.ts
  • src/main/index.ts
  • src/main/ipc/pty.test.ts
  • src/main/ipc/pty.ts
  • src/main/runtime/orca-runtime.test.ts
  • src/main/runtime/orca-runtime.ts
🚧 Files skipped from review as they are similar to previous changes (7)
  • src/main/ipc/pty.ts
  • src/main/runtime/orca-runtime.ts
  • src/main/agent-awake-foreground-evidence.ts
  • src/main/index.ts
  • src/main/runtime/orca-runtime.test.ts
  • src/main/agent-awake-service.ts
  • src/main/agent-awake-service.test.ts

Comment thread src/main/ipc/pty.test.ts Resolved
@nwparker nwparker added the bug Something isn't working label Jul 27, 2026
@bbingz
bbingz force-pushed the bbingz/unknown-busy-and-wrapper-visibility branch from 2d6164a to 0a4d8ee Compare July 28, 2026 02:02
@bbingz
bbingz force-pushed the bbingz/unknown-busy-and-wrapper-visibility branch from ab6c43b to beacf35 Compare July 31, 2026 09:55
@greptile-apps

greptile-apps Bot commented Jul 31, 2026 •

Copy link
Copy Markdown

Greptile Summary

This PR adds two capabilities: (1) keep-awake evidence sourced from foreground-process scans (with TTL + revalidation) for agents that emit no hook statuses, and (2) sidebar/worktree ring attribution from the same process-identity evidence for wrapper-launched agents (e.g., Claude without a stable title). It also tightens terminalHasShellForegroundProcess so that only confirmed shells (not just unrecognized processes) prove agent exit.

  • New ForegroundAgentEvidenceLedger in the main process: tracks per-PTY keep-awake evidence with a quantum guard, TTL-based revalidation, and a 2-hour stale cap; AgentAwakeService now counts evidence alongside hook statuses for wake eligibility.
  • IPC hooks in pty.ts: inspector results are fed to runtime.recordPtyForegroundProcessObservation so that completed scans (triggered by the renderer coordinator) automatically populate the keep-awake ledger without a separate process scan.
  • Renderer attribution via refreshPaneForegroundAgentObservation: coordinator inspections that find a recognized agent call onForegroundAgentInspected, which stamps a ptyId-bound entry in the pane foreground agent store; worktree-title-derived-agent-rows and worktree-status consume this evidence to attribute title-less wrapper rows and the worktree ring.

Confidence Score: 5/5

  • Safe to merge; the change is additive — it layers foreground-process evidence on top of existing hook-based wake logic without altering any hook path.
  • All changes are opt-in extensions: hook-based keep-awake is unchanged, and the new foreground evidence path only activates when a recognized agent is the foreground process. The confirmPtyForegroundProcessIsShell narrowing is intentional and correctly prevents wrapper processes from being misclassified as shells. The two identified concerns are non-blocking limitations rather than regressions.
  • src/main/ipc/pty.ts (null observation on subprocess scans) and src/renderer/src/lib/worktree-status.ts (missing terminalLayoutsByTabId from use-worktree-activity-status call site).

Important Files Changed

Filename Overview
src/main/agent-awake-foreground-evidence.ts New file: ForegroundAgentEvidenceLedger with quantum-guarded report, TTL-based pruneAndCount with revalidation, and nextExpiry. Logic is correct. The null-agent path bypasses the quantum guard (intentional: clear immediately), but this means any unrecognized subprocess seen during a scan will drop evidence without a debounce window.
src/main/agent-awake-service.ts Adds foreground-agent evidence support: reportForegroundAgentEvidence delegates to the new ledger, and refresh sums eligibleForegroundAgentCount alongside existing hook-based running count. scheduleStaleTimer now also consults ledger nextExpiry. Looks correct.
src/main/ipc/pty.ts pty:inspect and pty:confirmForeground IPC handlers now call runtime.recordPtyForegroundProcessObservation with incarnation-guarded results. Correctly skips reporting if the PTY was respawned between capture and resolution. Any unrecognized foreground process (subprocess) will fire a null observation, immediately dropping keep-awake evidence.
src/main/runtime/orca-runtime.ts Adds recordPtyForegroundProcessObservation (now public), hasWakeEligibleForegroundAgent, and onPtyForegroundAgentEvidence callback. confirmPtyForegroundProcessIsShell changed from recognizeAgentProcess === null to isShellProcess — correctly narrows the "agent exited" proof so wrapper/fork agents are no longer treated as shells.
src/renderer/src/store/slices/pane-foreground-agent.ts Adds ptyId field to entries and refreshPaneForegroundAgentObservation; resolveFreshPaneForegroundAgent uses pane-bound PTY for precise attribution, falling back to live-tab PTYs. The ptyId backfill branch (line 117) was flagged in a prior review thread for not doing a full identity rebind on first ptyId assignment.
src/renderer/src/components/sidebar/worktree-agent-activity-summary.ts Adds paneForegroundAgentByPaneKey to WorktreeAgentActivitySummary and the per-worktree narrowing loop. paneForegroundAgentsEqual uses reference identity for entries, which correctly invalidates on observedAt bumps. Module-level agentActivityCache will invalidate on every quantum bump, but the per-worktree reuse optimization keeps render amplification bounded.
src/renderer/src/components/sidebar/worktree-title-derived-agent-rows.ts Adds freshProcessAgentForLeaf helper and threads paneForegroundAgentByPaneKey through buildTitleDerivedAgentRows for wrapper identity; resolveTitleDerivedAgentType now falls back to process identity for title-less Claude rows. Logic is clean.
src/renderer/src/lib/worktree-status.ts tabHasStatus now resolves process identity per-leaf via freshProcessAgentForLeaf for more precise Claude attribution. Uses options.terminalLayoutsByTabId for pane-bound PTY checking, but use-worktree-activity-status.ts only passes terminalLayoutRootsByTabId — meaning the pane-bound PTY check is unavailable from that call site and falls through to the tab-level liveness fallback.
src/renderer/src/components/terminal-pane/agent-completion-coordinator.ts Adds onForegroundAgentInspected callback called on every successful recognized-agent inspection; passes the inspected PTY ID to prevent cross-pane attribution. No logic changes to completion/attention flow.
src/renderer/src/components/terminal-pane/pty-connection.ts Three locations now stamp ptyId on setPaneForegroundAgent entries; onForegroundAgentInspected is wired to refreshPaneForegroundAgentObservation with PTY-identity guard. isForegroundTrackingAllowed check prevents SSH/WSL evidence from binding to local panes.

Sequence Diagram

sequenceDiagram
    participant Coord as Renderer Coordinator
    participant IPC as pty.ts IPC Handler
    participant Runtime as OrcaRuntime
    participant Ledger as ForegroundAgentEvidenceLedger
    participant Awake as AgentAwakeService
    participant Store as Renderer Store

    Coord->>IPC: pty:inspect(ptyId)
    IPC->>Runtime: getForegroundProcess(ptyId)
    Runtime-->>IPC: ""claude" | "git" | null"
    IPC->>Runtime: recordPtyForegroundProcessObservation(ptyId, process)
    Runtime->>Awake: "onPtyForegroundAgentEvidence(ptyId, agent|null)"
    Awake->>Ledger: "report(ptyId, agent|null)"
    Note over Ledger: null → delete immediately<br/>agent → quantum-guarded upsert
    Ledger-->>Awake: changed?
    Awake->>Awake: refresh() → pruneAndCount() → startBlocker/stop

    IPC-->>Coord: RuntimeTerminalProcessInspection
    alt recognized agent
        Coord->>Store: onForegroundAgentInspected(process, ptyId)
        Store->>Store: refreshPaneForegroundAgentObservation(paneKey, agent, ptyId)
    end

    Note over Ledger,Awake: TTL expiry (5 min)
    Ledger->>Runtime: revalidate(ptyId) → hasWakeEligibleForegroundAgent
    Runtime-->>Ledger: "pty.connected && foregroundAgent !== null"
    alt still eligible
        Ledger->>Ledger: "evidence.observedAt = now"
    else expired
        Ledger->>Ledger: delete entry
        Awake->>Awake: stopBlocker
    end
Loading

Reviews (2): Last reviewed commit: "fix(agents): stabilize foreground eviden..." | Re-trigger Greptile

bbingz and others added 7 commits August 6, 2026 07:39
…-status gate

A confirmed foreground that is neither a shell nor a recognized agent
(wrapper/fork agent binaries) previously counted as "shell only", which
suppressed fresh hook state and reported the pane idle. Only a confirmed
real shell (or an unavailable confirmation, matching the fail-closed catch
path) may now suppress explicit hook status.
…L + revalidation

Hook 'working' statuses were the only wake evidence, so wrapper-launched or
manually-run recognized agents (resolved by the existing foreground scans)
let the machine sleep mid-run. The runtime now reports each completed scan's
recognized-agent-or-null result; AgentAwakeService holds wake eligibility per
PTY while that evidence is fresh (5 min TTL), renews it at expiry via a
cache-only revalidation callback (never a new scan, 2h hard cap), and drops
it on a null report or PTY stop. Arbitrary non-shell processes never grant
wake. No new scans or cadences are added.
…rocess identity

Wrapper-launched claude (a shell function exec'ing the real binary) emits
Claude activity titles without the literal 'claude' token, so the row builder
and worktree ring rejected the pane as unattributable — invisible while
working. The paneForegroundAgent slice already resolves the recognized
foreground process; surface it as identity attribution:

- Slice entries now carry observedAt (stamped centrally) and the publishing
  PTY; resolveFreshPaneForegroundAgent gates consumers on a 30s TTL plus
  pane/tab PTY liveness so stale evidence after agent exit cannot fake a
  working state. The completion coordinator's existing inspections re-arm
  the observation (no new scans, no new cadence).
- resolveTitleDerivedAgentType/resolveAgentTypeFromTerminalTitle accept the
  process agent so a token-less Claude title yields a Claude row and an
  attributable working ring. State still comes from title activity or hooks;
  process identity alone never invents 'working'. Hook rows keep precedence.
- worktree-agent-activity-summary narrows the slice per worktree with stable
  references; card status, agent rows, and section activity consume it.
…to PTY, expire attribution on wall clock

Review fixes for the busy/visibility PR:

- agent-awake-foreground-evidence: enforce the 2h reportedAt cap
  unconditionally in pruneAndCount and align boundary comparisons with
  nextExpiry, so a stale timer firing at the cap (or exactly at the TTL)
  can no longer keep the power-save blocker held forever with no timer
  rescheduled. New test drives revalidation-renewed evidence to the cap
  and asserts the blocker stops with no timer left.
- onForegroundAgentInspected now carries the PTY the inspection ran
  against; pty-connection only accepts it while the pane still owns that
  PTY, and refreshPaneForegroundAgentObservation stamps it on created
  entries and rebinds (identity-only) evidence held for a previous PTY
  instead of keeping it fresh across a respawn.
- new usePaneForegroundAgentEvidenceExpiryTick schedules a one-shot
  re-render at the earliest evidence expiry for the worktree ring and
  agent rows, so a past-TTL working ring/row drops without unrelated
  store churn.
- restore the Claude-glyph regression fixture alongside the braille
  variant (it.each) in worktree-title-derived-agent-rows.test.
- update terminal-pane-detach-agent-identity.test for the central
  observedAt stamping introduced by this branch (was failing).
Known launch agents skip runtime foreground probes, so feed existing renderer inspections into runtime identity and wake evidence. Keep the review-driven rationale comments concise.
@bbingz
bbingz force-pushed the bbingz/unknown-busy-and-wrapper-visibility branch from 7781050 to 60457b2 Compare August 5, 2026 23:41
UNION rebase kept PR's ptyId stamping on setPaneForegroundAgent
publishes; two main-era expectations lagged. Align them with the
PR field and nearby tests. Cosmetic indent fix on the revoke path.
bbingz added a commit to bbingz/orca that referenced this pull request Aug 6, 2026
Introduce ForegroundProcessResolution { engine, rawProcessName, isShell }
so an unrecognized live foreground is no longer collapsed to a bare shell.
The deployed-relay wire contract stays string|null; consumers rebuild the
structure locally via resolveForegroundProcess (degrade old-relay strings).

Thread it only along the renderer path: the pane-foreground-agent tracker
publishes rawProcessName on the command-path entry for a live, non-shell,
unrecognized foreground (recognized agents publish their engine; shells need
no raw name). The store slice gains an optional rawProcessName and a new
resolveFreshPaneForegroundRawProcess that reuses stablyai#9415's TTL/PTY freshness
gate (extracted into one shared helper — existing resolveFreshPaneForegroundAgent
behavior unchanged).
@bbingz

bbingz commented Aug 10, 2026

Copy link
Copy Markdown
Contributor Author

Closing as part of fork PR backlog cleanup.

This branch is long-conflicted (DIRTY) against current main and is not on the active campaign rebase list. Feel free to reopen or cut a fresh PR from an updated branch if the change is still needed.

@bbingz bbingz closed this Aug 10, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

bug Something isn't working

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants