Skip to content

fix: wire CLI run session continuity to project session store#1949

Draft
cursor[bot] wants to merge 2 commits into
mainfrom
cursor/critical-bug-investigation-dc5e
Draft

fix: wire CLI run session continuity to project session store#1949
cursor[bot] wants to merge 2 commits into
mainfrom
cursor/critical-bug-investigation-dc5e

Conversation

@cursor

@cursor cursor Bot commented Jun 13, 2026

Copy link
Copy Markdown
Contributor

Bug and impact

praisonai run --continue / --session (added in #1929) did not actually resume conversation history. Sessions were discovered in the project-scoped store (~/.praisonai/sessions/projects/...) but agents saved and loaded from the global default store. Users saw "Continuing session: …" but the agent had no prior context.

Additionally, praisonai run "…" --continue --output actions crashed with TypeError: unexpected keyword argument 'resume_session' because Agent has no such parameter.

Root cause

  • run.py set args.resume_session but handle_direct_prompt() never consumed it.
  • Auto-save used MemoryConfig(auto_save=…) without binding the project session store or restoring history.
  • The actions output path passed resume_session directly to Agent(**kwargs).

Fix

  • Add apply_cli_session_continuity() to bind agents to the project session store and restore prior turns.
  • Wire resume_session in handle_direct_prompt() via MemoryConfig(session_id=…, history=True).
  • Fix the actions output path to use MemoryConfig instead of invalid kwargs.
  • Remove unreachable duplicate actions block in run.py.

Validation

  • Added regression tests in src/praisonai/tests/unit/cli/test_run_session_continuity.py
  • All 3 tests pass locally
Open in Web View Automation 

Summary by CodeRabbit

Release Notes

  • New Features

    • Added --resume-session flag to resume prior CLI sessions with automatic chat history restoration.
    • Enhanced session continuity support for CLI agents with persistent, project-scoped session management.
  • Improvements

    • Streamlined output handling in CLI execution for cleaner command output.

- Restore chat history from project-scoped store on --continue/--session
- Replace invalid Agent resume_session kwarg with MemoryConfig + store wiring
- Add apply_cli_session_continuity helper and regression tests

Fixes broken session resume introduced in #1929 where sessions were
discovered in the project store but saved/loaded from the global store.

Co-authored-by: Mervin Praison <MervinPraison@users.noreply.github.com>
@MervinPraison

Copy link
Copy Markdown
Owner

@coderabbitai review

@MervinPraison

Copy link
Copy Markdown
Owner

/review

@qodo-code-review

Copy link
Copy Markdown

Qodo reviews are paused for this user.

Troubleshooting steps vary by plan Learn more →

On a Teams plan?
Reviews resume once this user has a paid seat and their Git account is linked in Qodo.
Link Git account →

Using GitHub Enterprise Server, GitLab Self-Managed, or Bitbucket Data Center?
These require an Enterprise plan - Contact us
Contact us →

@coderabbitai

coderabbitai Bot commented Jun 13, 2026

Copy link
Copy Markdown
Contributor
✅ Action performed

Review finished.

Note: CodeRabbit is an incremental review system and does not re-review already reviewed commits. This command is applicable only when automatic reviews are paused.

@coderabbitai

coderabbitai Bot commented Jun 13, 2026

Copy link
Copy Markdown
Contributor

Review Change Stack

Important

Review skipped

Bot user detected.

To trigger a single review, invoke the @coderabbitai review command.

⚙️ Run configuration

Configuration used: defaults

Review profile: CHILL

Plan: Pro

Run ID: 04a9643d-de85-40a2-84ad-e629392d84e8

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
📝 Walkthrough

Walkthrough

The PR refactors CLI session continuity by introducing a new apply_cli_session_continuity helper in the project session store that binds agents to project-scoped state and restores prior chat history. The direct-prompt handler now supports --resume-session by configuring MemoryConfig with the resumed session ID and applying continuity, while the actions execution path is refactored to use the same continuity approach instead of direct config injection. Duplicate console output in the non-actions path is removed.

Changes

CLI Session Continuity with Resume-Session

Layer / File(s) Summary
Session continuity helper and session store integration
src/praisonai/praisonai/cli/state/project_sessions.py
New apply_cli_session_continuity(agent, session_id, project_path) helper wires an agent to the project-scoped session store, loads prior chat history from stored messages into agent.chat_history, and initializes _auto_save_last_index. find_last_session() now returns the store's final session ID.
Resume-session memory configuration and continuity wiring in direct-prompt
src/praisonai/praisonai/cli/main.py
When --resume-session is provided, handle_direct_prompt creates MemoryConfig with the resumed session_id, auto_save (fallback), and history=True, then calls apply_cli_session_continuity on the constructed agent before execution.
Actions mode session continuity refactor and output cleanup
src/praisonai/praisonai/cli/commands/run.py
output_mode="actions" now computes a continuity ID from session/auto-save, sets agent memory conditionally, and applies continuity via the helper, replacing direct agent-config injection. Removes duplicate console print(result) in non-actions direct-prompt path.
Regression test coverage for session continuity
src/praisonai/tests/unit/cli/test_run_session_continuity.py
Three tests validate: Agent rejects resume_session kwarg; apply_cli_session_continuity restores chat history and session state from store; handle_direct_prompt propagates --resume-session into MemoryConfig and invokes continuity with matching session IDs.

Estimated code review effort

🎯 3 (Moderate) | ⏱️ ~20 minutes

Possibly related issues

Possibly related PRs

  • MervinPraison/PraisonAI#1929: Implements foundational project-scoped CLI session continuity that this PR builds upon by extending the session store API and wiring resume-session into the run command and direct-prompt handler.

Suggested reviewers

  • MervinPraison

Poem

🐰 A rabbit hops through sessions past,
With memories restored so vast—
Resume your talk, the chain held fast,
Continuity at last! ✨

🚥 Pre-merge checks | ✅ 4 | ❌ 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 77.78% which is insufficient. The required threshold is 80.00%. Write docstrings for the functions missing them to satisfy the coverage threshold.
✅ Passed checks (4 passed)
Check name Status Explanation
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Title check ✅ Passed The title clearly describes the main purpose of the PR: wiring CLI run session continuity to the project session store, which is the core fix across all changed files.
Linked Issues check ✅ Passed Check skipped because no linked issues were found for this pull request.
Out of Scope Changes check ✅ Passed Check skipped because no linked issues were found for this pull request.

✏️ Tip: You can configure your own custom pre-merge checks in the settings.

✨ Finishing Touches
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Commit unit tests in branch cursor/critical-bug-investigation-dc5e

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 and usage tips.

@MervinPraison

Copy link
Copy Markdown
Owner

@copilot Do a thorough review of this PR. Read ALL existing reviewer comments above from Qodo, Coderabbit, and Gemini first — incorporate their findings.

Review areas:

  1. Bloat check: Are changes minimal and focused? Any unnecessary code or scope creep?
  2. Security: Any hardcoded secrets, unsafe eval/exec, missing input validation?
  3. Performance: Any module-level heavy imports? Hot-path regressions?
  4. Tests: Are tests included? Do they cover the changes adequately?
  5. Backward compat: Any public API changes without deprecation?
  6. Code quality: DRY violations, naming conventions, error handling?
  7. Address reviewer feedback: If Qodo, Coderabbit, or Gemini flagged valid issues, include them in your review
  8. Suggest specific improvements with code examples where possible

@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

🧹 Nitpick comments (1)
src/praisonai/tests/unit/cli/test_run_session_continuity.py (1)

43-134: ⚡ Quick win

Add a regression that hits run.py’s output_mode="actions" branch directly.

These tests prove the helper and handle_direct_prompt() wiring, but they never call _run_prompt(..., output_mode="actions"), which is the branch that previously raised the resume_session TypeError. A focused unit test there would catch both the kwargs regression and any future drift between src/praisonai/praisonai/cli/commands/run.py and src/praisonai/praisonai/cli/main.py. As per coding guidelines, test coverage/quality for changed or critical paths should be included before merge.

Possible test shape
+def test_run_prompt_actions_mode_wires_session_continuity(monkeypatch):
+    from praisonai.cli.commands.run import _run_prompt
+
+    captured = {}
+
+    class FakeAgent:
+        def __init__(self, **kwargs):
+            captured["agent_config"] = kwargs
+
+        def start(self, prompt):
+            captured["prompt"] = prompt
+            return "ok"
+
+    monkeypatch.setattr("praisonaiagents.Agent", FakeAgent)
+    monkeypatch.setattr(
+        "praisonai.cli.state.project_sessions.apply_cli_session_continuity",
+        lambda agent, session_id, project_path=None: captured.setdefault("continuity", session_id),
+    )
+
+    _run_prompt(
+        "follow up question",
+        output_mode="actions",
+        session="saved-session",
+    )
+
+    memory = captured["agent_config"]["memory"]
+    assert isinstance(memory, MemoryConfig)
+    assert memory.session_id == "saved-session"
+    assert captured["continuity"] == "saved-session"
+```
</details>

<details>
<summary>🤖 Prompt for AI Agents</summary>

Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In @src/praisonai/tests/unit/cli/test_run_session_continuity.py around lines 43

  • 134, Add a focused unit test that exercises the run command branch that uses
    output_mode="actions" to catch the previous resume_session TypeError: call the
    Run command handler/_run_prompt path with output_mode="actions" (the same args
    pattern used in test_handle_direct_prompt_wires_project_session) and assert that
    resume_session is forwarded into the created agent's MemoryConfig and that the
    call returns normally; specifically, add a new test function that patches the
    same helpers (praisonaiagents.Agent -> FakeAgent,
    PraisonAI._execute_agent_with_budget_handling,
    state.project_sessions.apply_cli_session_continuity, etc.), invokes the
    run/_run_prompt entry used for CLI actions with resume_session="saved-session",
    and asserts MemoryConfig.session_id == "saved-session" and no TypeError is
    raised. Ensure the test targets the run command branch (output_mode="actions")
    and reuses captured dict assertions similar to
    test_handle_direct_prompt_wires_project_session.

</details>

<!-- cr-comment:v1:4eca202d743ba445e2ede90b -->

</blockquote></details>

</blockquote></details>

<details>
<summary>🤖 Prompt for all review comments with AI agents</summary>

Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

Inline comments:
In @src/praisonai/praisonai/cli/main.py:

  • Around line 4517-4525: The current code overwrites agent_config["memory"] when
    setting MemoryConfig for resume (using resume_session_id/save_name), which
    discards previously set fields like user_id; change this to merge with any
    existing memory configuration instead of replacing it: read the existing value
    from agent_config.get("memory") (handle either a dict or a MemoryConfig
    instance), preserve all existing fields (e.g., user_id and other keys), then
    set/override only session_id, auto_save and history before assigning the merged
    result back to agent_config["memory"]; keep the use of MemoryConfig when
    constructing the final config so other code continues to expect that type.

Nitpick comments:
In @src/praisonai/tests/unit/cli/test_run_session_continuity.py:

  • Around line 43-134: Add a focused unit test that exercises the run command
    branch that uses output_mode="actions" to catch the previous resume_session
    TypeError: call the Run command handler/_run_prompt path with
    output_mode="actions" (the same args pattern used in
    test_handle_direct_prompt_wires_project_session) and assert that resume_session
    is forwarded into the created agent's MemoryConfig and that the call returns
    normally; specifically, add a new test function that patches the same helpers
    (praisonaiagents.Agent -> FakeAgent,
    PraisonAI._execute_agent_with_budget_handling,
    state.project_sessions.apply_cli_session_continuity, etc.), invokes the
    run/_run_prompt entry used for CLI actions with resume_session="saved-session",
    and asserts MemoryConfig.session_id == "saved-session" and no TypeError is
    raised. Ensure the test targets the run command branch (output_mode="actions")
    and reuses captured dict assertions similar to
    test_handle_direct_prompt_wires_project_session.

</details>

<details>
<summary>🪄 Autofix (Beta)</summary>

Fix all unresolved CodeRabbit comments on this PR:

- [ ] <!-- {"checkboxId": "4b0d0e0a-96d7-4f10-b296-3a18ea78f0b9"} --> Push a commit to this branch (recommended)
- [ ] <!-- {"checkboxId": "ff5b1114-7d8c-49e6-8ac1-43f82af23a33"} --> Create a new PR with the fixes

</details>

---

<details>
<summary>ℹ️ Review info</summary>

<details>
<summary>⚙️ Run configuration</summary>

**Configuration used**: defaults

**Review profile**: CHILL

**Plan**: Pro

**Run ID**: `ac86bfea-f618-4c6b-8b1d-02c88c253497`

</details>

<details>
<summary>📥 Commits</summary>

Reviewing files that changed from the base of the PR and between 2f9677abb2ea68eab864ee8b6a828fd0141612e1 and 59b3ed4dda0c34938298c4a64739fd2adbaa557e.

</details>

<details>
<summary>📒 Files selected for processing (4)</summary>

* `src/praisonai/praisonai/cli/commands/run.py`
* `src/praisonai/praisonai/cli/main.py`
* `src/praisonai/praisonai/cli/state/project_sessions.py`
* `src/praisonai/tests/unit/cli/test_run_session_continuity.py`

</details>

</details>

<!-- This is an auto-generated comment by CodeRabbit for review status -->

Comment thread src/praisonai/praisonai/cli/main.py Outdated
Comment on lines +4517 to +4525
resume_session_id = getattr(self.args, 'resume_session', None)
if resume_session_id:
from praisonaiagents import MemoryConfig
save_name = getattr(self.args, 'auto_save', None) or resume_session_id
agent_config["memory"] = MemoryConfig(
session_id=resume_session_id,
auto_save=save_name,
history=True,
)

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.

⚠️ Potential issue | 🟠 Major | ⚡ Quick win

Preserve existing memory isolation fields when enabling --resume.

Line 4521 replaces the whole memory config, which discards fields already set earlier (notably user_id from Line 4502). With --memory --user-id ... --resume ..., memory can silently fall back to non-user-scoped state.

Suggested fix
                 resume_session_id = getattr(self.args, 'resume_session', None)
                 if resume_session_id:
                     from praisonaiagents import MemoryConfig
                     save_name = getattr(self.args, 'auto_save', None) or resume_session_id
-                    agent_config["memory"] = MemoryConfig(
-                        session_id=resume_session_id,
-                        auto_save=save_name,
-                        history=True,
-                    )
+                    existing_memory = agent_config.get("memory")
+                    if isinstance(existing_memory, MemoryConfig):
+                        existing_memory.session_id = resume_session_id
+                        existing_memory.auto_save = save_name
+                        existing_memory.history = True
+                    else:
+                        agent_config["memory"] = MemoryConfig(
+                            session_id=resume_session_id,
+                            auto_save=save_name,
+                            history=True,
+                        )
                     print(f"[bold cyan]Resuming session '{resume_session_id}'[/bold cyan]")
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@src/praisonai/praisonai/cli/main.py` around lines 4517 - 4525, The current
code overwrites agent_config["memory"] when setting MemoryConfig for resume
(using resume_session_id/save_name), which discards previously set fields like
user_id; change this to merge with any existing memory configuration instead of
replacing it: read the existing value from agent_config.get("memory") (handle
either a dict or a MemoryConfig instance), preserve all existing fields (e.g.,
user_id and other keys), then set/override only session_id, auto_save and
history before assigning the merged result back to agent_config["memory"]; keep
the use of MemoryConfig when constructing the final config so other code
continues to expect that type.

@MervinPraison

Copy link
Copy Markdown
Owner

@claude You are the FINAL architecture reviewer. If the branch is under MervinPraison/PraisonAI (not a fork), you are able to make modifications to this branch and push directly. SCOPE: Focus ONLY on Python packages (praisonaiagents, praisonai). Do NOT modify praisonai-rust or praisonai-ts. Read ALL comments above from Gemini, Qodo, CodeRabbit, and Copilot carefully before responding.

Phase 1: Review per AGENTS.md

  1. Protocol-driven: check heavy implementations vs core SDK
  2. Backward compatible: ensure zero feature regressions
  3. Performance: no hot-path regressions

Phase 2: FIX Valid Issues
4. For any VALID bugs or architectural flaws found by Gemini, CodeRabbit, Qodo, Copilot, or any other reviewer: implement the fix
5. Push all code fixes directly to THIS branch (do NOT create a new PR)
6. Comment a summary of exact files modified and what you skipped

Phase 3: Final Verdict
7. If all issues are resolved, approve the PR / close the Issue
8. If blocking issues remain, request changes / leave clear action items

@praisonai-triage-agent

praisonai-triage-agent Bot commented Jun 13, 2026

Copy link
Copy Markdown
Contributor

Claude finished @MervinPraison's task —— View job


Final Architecture Review Complete ✅

Phase 1: Architecture Review per AGENTS.md

  • Read AGENTS.md guidelines
  • Review protocol-driven design compliance
  • Check backward compatibility
  • Verify no performance regressions

Phase 2: Fix Valid Issues from Other Reviewers

  • Fix memory config overwriting (CodeRabbit finding)
  • Add missing test coverage for actions mode
  • Push fixes to branch

Phase 3: Final Verdict

  • Run tests and validation
  • Provide approval/change requests

Architecture Review Results ✅

Protocol-driven design: Changes properly separate concerns - core protocols in project_sessions.py helper, implementation in CLI wrapper
Backward compatibility: No breaking changes, only fixes existing functionality
Performance: No hot-path regressions, session loading is lazy

Issues Fixed ✅

  1. Memory Config Overwriting (CodeRabbit): Fixed in praisonai/cli/main.py:4522-4541 - now preserves existing fields like user_id when applying --resume-session
  2. Missing Test Coverage (CodeRabbit): Added test_run_prompt_actions_mode_wires_session_continuity() in tests/unit/cli/test_run_session_continuity.py to cover the actions mode branch

Final Verdict: ✅ APPROVE

This PR successfully fixes the CLI session continuity bug and addresses all valid reviewer feedback:

  • Core Issue Fixed: --continue/--session now properly resume conversation history via apply_cli_session_continuity()
  • TypeError Fixed: Actions mode no longer crashes with invalid resume_session parameter
  • Memory Preservation: User-scoped sessions (--user-id) work correctly with resume
  • Test Coverage: Complete regression coverage for both direct-prompt and actions paths

The implementation follows AGENTS.md guidelines with clean separation between protocol (core SDK) and implementation (CLI wrapper). All changes are backward-compatible and focused on the specific bug.

Pushed fixes to commit 03326c95

--- • Branch: cursor/critical-bug-investigation-dc5e

- Fix memory config being completely replaced in main.py, now preserves existing fields like user_id
- Add test coverage for actions mode session continuity to prevent TypeError regression

Co-authored-by: Mervin Praison <MervinPraison@users.noreply.github.com>
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.

2 participants