Skip to content

fix(automations): attribute run completion by agent session, not only paneKey - #11158

Closed
innocarpe wants to merge 4 commits into
stablyai:mainfrom
innocarpe:fix/automation-pane-key-attribution
Closed

innocarpe wants to merge 4 commits into
stablyai:mainfrom
innocarpe:fix/automation-pane-key-attribution

Conversation

@innocarpe

Copy link
Copy Markdown
Contributor

Description

Automation runs no longer finalize early when a nested same-pane agent (e.g. Claude SessionStart claude -p) emits done on the same paneKey as the primary automation agent.

Focused fix

  • In scope: bind providerSession fingerprint after dispatch; only finalize matching session; pure tracker + tests; wire observe paths
  • Out of scope: rewriting global agentStatusByPaneKey store identity for all agents

Preserves

  • Fallback to paneKey+time when no provider session is available (including OSC-only paths)
  • reuseSession completion path still works when session fingerprints match

Evidence

  • pnpm exec vitest run --config config/vitest.config.ts src/renderer/src/lib/automation-agent-session-attribution.test.ts src/renderer/src/hooks/useAutomationDispatchEvents.test.ts → 26 passed

User-regression-tradeoffs

  • Nested same-type agents may still overwrite sidebar status rows; this PR only gates automation finalization, not the full status map UX

Fixes #10999

@coderabbitai

coderabbitai Bot commented Jul 28, 2026 •

Copy link
Copy Markdown
Contributor

Review Change Stack

Important

Review skipped

We couldn't safely recover the incremental review. No full review was started, and the last reviewed checkpoint was preserved. Retry later, or explicitly request a full review by commenting @coderabbitai full review.

You can disable this status message by setting the reviews.review_status to false in the CodeRabbit configuration file.

Use the checkbox below for a quick retry:

  • Trigger review

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.

  • Last reviewed commit: c1d556dfcf6b18dc91ffdb442c0f4242ebb8aef9
  • Latest commit, not reviewed: 2e4e1f7

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

Adds provider-session attribution utilities and shared completion-attribution types. Integrates session tracking into fresh-launch, reusable-session, and store-driven completion handling. Persists attribution with automation runs and migrates legacy runs. Adds tests for session boundaries, nested sessions, output handling, duplicate signals, exit cleanup, persistence failures, and reusable-session completion.

🚥 Pre-merge checks | ✅ 3 | ❌ 2

❌ Failed checks (2 warnings)

Check name Status Explanation Resolution
Description check ⚠️ Warning The description explains the fix and testing, but it omits most required template sections, including visual proof, checklist, review, and author details. Use the repository template and complete the required sections, including ELI5, What Changed, Why, Visual Proof or N/A, Testing checkboxes, Review, and Checklist.
Docstring Coverage ⚠️ Warning Docstring coverage is 16.67% which is insufficient. The required threshold is 80.00%. Write docstrings for the functions missing them to satisfy the coverage threshold.
✅ Passed checks (3 passed)

Check name Status Explanation
Title check ✅ Passed The title clearly identifies the primary change: attributing automation completion to the agent session instead of only the pane key.
Linked Issues check ✅ Passed The changes address issue #10999 by matching completion events to the primary provider session while preserving pane-and-time fallback behavior.
Out of Scope Changes check ✅ Passed The persistence updates, attribution utilities, dispatch changes, fixtures, and tests support the linked automation-session attribution fix.
  • Autofix · Keep fixing CodeRabbit findings and required CI, and resolving merge conflicts

@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: 2

🧹 Nitpick comments (3)
src/renderer/src/lib/automation-agent-session-attribution.test.ts (1)

32-58: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick win

Add coverage for the two unbound-tracker orderings.

Neither case is exercised: (a) a nested session emitting the first live status binds as primary, and (b) a fingerprinted done arriving before any live status returns true. Both are the behaviors flagged in automation-agent-session-attribution.ts; pinning them in tests will make the intended semantics explicit either way.

src/renderer/src/hooks/useAutomationDispatchEvents.ts (1)

556-576: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick win

Extract the duplicated OSC status-attribution handler. Both callbacks implement the same four steps — note non-done state, bail when a fingerprint is bound, gate done through the tracker, then update latestAssistantMessage and finalize — differing only by requireWorkingAfterStart. Keeping two copies means future attribution fixes must land twice.

  • src/renderer/src/hooks/useAutomationDispatchEvents.ts#L556-L576: replace the inline fresh-launch handler with a call to a shared handleOscAgentStatus(payload) helper defined once in this scope, passing no requireWorkingAfterStart.
  • src/renderer/src/hooks/useAutomationDispatchEvents.ts#L466-L494: replace handleReusableAgentStatus with the same shared helper, passing requireWorkingAfterStart: true.
src/renderer/src/hooks/useAutomationDispatchEvents.test.ts (1)

781-832: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick win

No coverage for the OSC (onAgentStatus) reuse path.

observeExistingAutomationSession is mocked to a bare no-op, so handleReusableAgentStatus — the branch that preserves paneKey-only completion when no provider session exists, and suppresses OSC done once a session is bound — is never exercised. Capturing the mock's onAgentStatus callback and driving it would cover the fallback the PR explicitly preserves.


ℹ️ Review info
⚙️ Run configuration

Configuration used: Repository UI

Review profile: CHILL

Plan: Pro Plus

Run ID: 3fc29781-8ad5-4141-8f52-57338b9ef908

📥 Commits

Reviewing files that changed from the base of the PR and between 0404f27 and 5613cec874c01f85b26877c1e49f41526f637d3c.

📒 Files selected for processing (4)
  • src/renderer/src/hooks/useAutomationDispatchEvents.test.ts
  • src/renderer/src/hooks/useAutomationDispatchEvents.ts
  • src/renderer/src/lib/automation-agent-session-attribution.test.ts
  • src/renderer/src/lib/automation-agent-session-attribution.ts

@innocarpe

Copy link
Copy Markdown
Contributor Author

Sync update (d6ba053f9)

Address CodeRabbit: working-only fingerprint bind + ignore nested done before primary working; keep agentStatusByPaneKey reset in beforeEach

@AmethystLiang
AmethystLiang requested a review from OrcaWin July 28, 2026 16:48
@innocarpe
innocarpe force-pushed the fix/automation-pane-key-attribution branch from d6ba053 to 51f454c Compare August 6, 2026 02:35
@innocarpe

Copy link
Copy Markdown
Contributor Author

Sync update (51f454c6f6)

Rebase onto latest upstream/main: agent-session attribution for automation completion; keep submitPrompt mocks for paste path.

@coderabbitai

coderabbitai Bot commented Aug 6, 2026

Copy link
Copy Markdown
Contributor

Note

GitHub couldn't provide a complete incremental comparison for this pull request, so CodeRabbit is performing a full review instead. This review may take a little longer.

@mco-works

Copy link
Copy Markdown

Thanks for the focused fix. One downstream interface gap appears to remain.

Because this PR intentionally preserves paneKey/time fallback when a provider session is unavailable, an external verifier needs AutomationRun JSON to expose which attribution path was used. Could the run persist and return:

  • the provider-session fingerprint used for completion
  • the terminal/process incarnation identity bound to that session
  • provenance that explicitly distinguishes exact session binding from pane/time fallback

Fallback may still be used internally for compatibility, but it should not be indistinguishable from a positive exact-attribution receipt. Completion, outputSnapshot, and the returned identity should all refer to the same provider session.

Is that persisted receipt/provenance part of #11158, or would it require a follow-up change?

@innocarpe
innocarpe force-pushed the fix/automation-pane-key-attribution branch from 51f454c to c1d556d Compare August 13, 2026 04:30
@coderabbitai

coderabbitai Bot commented Aug 13, 2026

Copy link
Copy Markdown
Contributor

Note

GitHub couldn't provide a complete incremental comparison for this pull request, so CodeRabbit is performing a full review instead. This review may take a little longer.

@innocarpe

Copy link
Copy Markdown
Contributor Author

Addressed the exact-attribution receipt requested on #10999.

orca automations runs --json now persists completionAttribution on each run. A positive exact receipt (kind: exact_provider_session) is emitted only when completion is bound to the primary provider-session fingerprint; nested same-pane sessions cannot satisfy it. Pane/time fallback remains for UI compatibility as kind: pane_time_fallback, which is not a positive exact result.

Validation: focused attribution/dispatch/retention tests 52 passed after rebase onto current upstream/main.

@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: 3

🧹 Nitpick comments (1)
src/renderer/src/hooks/useAutomationDispatchEvents.completion.test.ts (1)

702-706: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick win

Assert the attribution receipt in the reuse-session test.

The test name states attribution by primary provider session, but the assertion checks only status: 'completed'. It passes even if the run persists pane_time_fallback. Add the attribution fields, as the fresh-launch test does at lines 644-653.

♻️ Proposed test assertion
     await vi.waitFor(() =>
       expect(mockMarkDispatchResult).toHaveBeenCalledWith(
-        expect.objectContaining({ status: 'completed' })
+        expect.objectContaining({
+          status: 'completed',
+          completionAttribution: expect.objectContaining({
+            kind: 'exact_provider_session',
+            providerSessionId: 'reuse-primary'
+          })
+        })
       )
     )

ℹ️ Review info
⚙️ Run configuration

Configuration used: Repository UI

Review profile: CHILL

Plan: Pro Plus

Run ID: 8de72693-d2a1-43d1-bb72-111260b587ae

📥 Commits

Reviewing files that changed from the base of the PR and between b115f8d and c1d556dfcf6b18dc91ffdb442c0f4242ebb8aef9.

📒 Files selected for processing (18)
  • src/main/persistence.test.ts
  • src/main/persistence.ts
  • src/renderer/src/components/automations/AutomationListLocalRows.test.tsx
  • src/renderer/src/components/automations/automation-list-last-run.test.ts
  • src/renderer/src/components/automations/automation-list-view.test.ts
  • src/renderer/src/components/automations/automation-run-completion-evidence.test.ts
  • src/renderer/src/components/automations/automation-run-open-target.test.ts
  • src/renderer/src/components/automations/automation-run-view-state.test.ts
  • src/renderer/src/components/automations/automation-usage-model.test.ts
  • src/renderer/src/hooks/useAutomationDispatchEvents.completion.test.ts
  • src/renderer/src/hooks/useAutomationDispatchEvents.test.ts
  • src/renderer/src/hooks/useAutomationDispatchEvents.ts
  • src/renderer/src/lib/automation-agent-session-attribution.test.ts
  • src/renderer/src/lib/automation-agent-session-attribution.ts
  • src/renderer/src/lib/automation-session-reuse.test.ts
  • src/shared/automation-run-completion-attribution.ts
  • src/shared/automation-run-retention.test.ts
  • src/shared/automations-types.ts

@innocarpe
innocarpe force-pushed the fix/automation-pane-key-attribution branch from c1d556d to d73ffcd Compare August 13, 2026 05:23
@innocarpe

Copy link
Copy Markdown
Contributor Author

Sync update (d73ffcd7b)

Address CodeRabbit on #11158:

  • Exact receipts are authorized only by a matching done, so a PTY exit after a working bind stays pane_time_fallback.
  • Provider sessions bind from live working samples only; historical replay no longer attaches the live session to a past working row.
  • sawWorkingAfterStart is set only for working, so OSC waiting then done cannot satisfy reuse.

Validation: focused attribution/dispatch tests 39 passed after rebase onto current upstream/main.

@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: fa9be2a7-0ce6-4d98-a4e7-8117ca399608

📥 Commits

Reviewing files that changed from the base of the PR and between c1d556dfcf6b18dc91ffdb442c0f4242ebb8aef9 and d73ffcd7b0f61d8252afb7baa68d67f66702a121.

📒 Files selected for processing (4)
  • src/renderer/src/hooks/useAutomationDispatchEvents.completion.test.ts
  • src/renderer/src/hooks/useAutomationDispatchEvents.ts
  • src/renderer/src/lib/automation-agent-session-attribution.test.ts
  • src/renderer/src/lib/automation-agent-session-attribution.ts
🚧 Files skipped from review as they are similar to previous changes (3)
  • src/renderer/src/lib/automation-agent-session-attribution.test.ts
  • src/renderer/src/hooks/useAutomationDispatchEvents.ts
  • src/renderer/src/lib/automation-agent-session-attribution.ts

@innocarpe
innocarpe force-pushed the fix/automation-pane-key-attribution branch from d73ffcd to 40e543b Compare August 15, 2026 11:18
innocarpe added a commit to innocarpe/orca that referenced this pull request Aug 15, 2026
Address CodeRabbit on stablyai#11158:
- Reset agentStatusByPaneKey early in beforeEach (leftover done can flake)
- Bind fingerprint only from working, never from done alone
- Ignore fingerprint-bearing done before any primary working bind

Full launcher-identity bind (session id from launchAgentBackgroundSession)
is deferred; this is the minimal guard without redesigning the launch API.
innocarpe added a commit to innocarpe/orca that referenced this pull request Aug 15, 2026
Address CodeRabbit on stablyai#11158: authorize exact receipts only from a matching
done, bind provider sessions from live working samples only, and treat
blocked/waiting as non-working for reuse.

Preserves: pane/time fallback completion and historical working-edge
recovery for recreated reuse-session entries.
@innocarpe

Copy link
Copy Markdown
Contributor Author

Address CodeRabbit: await a microtask after the nested done before the negative completion assertion, matching the sibling tests.

Also rebased onto current main. Persistence receipt coverage now lives in persistence-automations.test.ts after the test-file split.

Validation: focused attribution/dispatch/persistence tests 70 passed.

innocarpe added a commit to innocarpe/orca that referenced this pull request Oct 29, 2026
Address CodeRabbit on stablyai#11158:
- Reset agentStatusByPaneKey early in beforeEach (leftover done can flake)
- Bind fingerprint only from working, never from done alone
- Ignore fingerprint-bearing done before any primary working bind

Full launcher-identity bind (session id from launchAgentBackgroundSession)
is deferred; this is the minimal guard without redesigning the launch API.
innocarpe added a commit to innocarpe/orca that referenced this pull request Oct 29, 2026
Address CodeRabbit on stablyai#11158: authorize exact receipts only from a matching
done, bind provider sessions from live working samples only, and treat
blocked/waiting as non-working for reuse.

Preserves: pane/time fallback completion and historical working-edge
recovery for recreated reuse-session entries.
@innocarpe
innocarpe force-pushed the fix/automation-pane-key-attribution branch from 40e543b to 70da04f Compare October 29, 2026 08:06
@greptile-apps

greptile-apps Bot commented Oct 29, 2026 •

Copy link
Copy Markdown

RetriggerView in GreptileConfidence Score: 4/5

[Medium impact] Adds session tracking to automation run completion logic.

The early-finalization defect should be fixed before merging because a nested same-pane session can still win the initial bind and complete the primary automation prematurely.

Findings

  1. P1 Nested working session wins binding ▶

Summary

The PR adds provider-session-aware completion attribution for desktop automation runs and persists the resulting completion provenance.

  • Introduces a pure session tracker that gates done events by provider-session fingerprint.
  • Wires store and OSC observation paths into the tracker for fresh and reused sessions.
  • Adds durable completion-attribution data, legacy-state backfill, and focused regression tests.

Diagram

%%{init: {'theme': 'neutral'}}%%
flowchart TD
  A[Automation dispatch] --> B[Observe shared pane status]
  B --> C{First working fingerprint}
  C --> D[Bind provider session]
  D --> E{Done fingerprint matches?}
  E -- No --> F[Keep observing]
  E -- Yes --> G[Persist completed run]
  G --> H[Retire or preserve terminal]
Loading

Reviews (1) · Last reviewed commit: "test(automations): await nested done bef..." · Reviewed by Greptile

Comment on lines +64 to +65
if (identity.state === 'working' && tracker.boundFingerprint === null) {
tracker.boundFingerprint = fingerprint

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

P1 Nested working session wins binding

When a nested Claude or Codex session publishes working before the primary automation session, this code binds the nested provider fingerprint as the run's identity. The nested session's matching done event then finalizes the automation and can retire its terminal while the primary agent is still running.

Knowledge Base Used: Automation services

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!

innocarpe added a commit to innocarpe/orca that referenced this pull request Nov 2, 2026
Address CodeRabbit on stablyai#11158:
- Reset agentStatusByPaneKey early in beforeEach (leftover done can flake)
- Bind fingerprint only from working, never from done alone
- Ignore fingerprint-bearing done before any primary working bind

Full launcher-identity bind (session id from launchAgentBackgroundSession)
is deferred; this is the minimal guard without redesigning the launch API.
innocarpe added a commit to innocarpe/orca that referenced this pull request Nov 2, 2026
Address CodeRabbit on stablyai#11158: authorize exact receipts only from a matching
done, bind provider sessions from live working samples only, and treat
blocked/waiting as non-working for reuse.

Preserves: pane/time fallback completion and historical working-edge
recovery for recreated reuse-session entries.
@innocarpe
innocarpe force-pushed the fix/automation-pane-key-attribution branch from 70da04f to 49858e8 Compare November 2, 2026 12:30
… paneKey

Ignore nested same-pane agent status (e.g. SessionStart claude -p) so the
automation run waits for the primary agent and is not finalized early.

Fixes stablyai#10999
Address CodeRabbit on stablyai#11158:
- Reset agentStatusByPaneKey early in beforeEach (leftover done can flake)
- Bind fingerprint only from working, never from done alone
- Ignore fingerprint-bearing done before any primary working bind

Full launcher-identity bind (session id from launchAgentBackgroundSession)
is deferred; this is the minimal guard without redesigning the launch API.
Expose a machine-verifiable completionAttribution receipt on AutomationRun
JSON so nested same-pane sessions cannot satisfy automations runs --json
consumers. Pane/time fallback remains, but is distinguishable.

Preserves: fallback completion when no provider session is available.
Address CodeRabbit on stablyai#11158: authorize exact receipts only from a matching
done, bind provider sessions from live working samples only, and treat
blocked/waiting as non-working for reuse.

Preserves: pane/time fallback completion and historical working-edge
recovery for recreated reuse-session entries.
@innocarpe
innocarpe force-pushed the fix/automation-pane-key-attribution branch from 49858e8 to 2e4e1f7 Compare November 10, 2026 13:39
@innocarpe

Copy link
Copy Markdown
Contributor Author

Sync update (2e4e1f77d5)

Rebased onto current main. Completion still waits for the primary provider session, and a completionAttribution receipt now tells orca automations runs --json whether that session was exact or only a pane/time fallback. Exact receipts are recorded only after the bound session's own done. The desktop run observer writes the receipt; the old renderer dispatch hooks stay deleted.

@nwparker

nwparker commented Dec 1, 2026

Copy link
Copy Markdown
Contributor

Closing because the linked issue #10999 was closed as completed by #31780 (589499e3bd99, treating nested claude -p hooks as guests so they do not take over the parent pane or finish the run early). Thank you for working on this!

@nwparker nwparker closed this Dec 1, 2026
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.

[Bug]: Automation run output is attributed by paneKey, so a nested claude -p in the same pane is captured as the run's reply

4 participants