Skip to content

Comments

reafctor: renaming persistence store for clarity#1653

Merged
yottahmd merged 4 commits intomainfrom
refactor-convo-store
Feb 12, 2026
Merged

reafctor: renaming persistence store for clarity#1653
yottahmd merged 4 commits intomainfrom
refactor-convo-store

Conversation

@yottahmd
Copy link
Collaborator

@yottahmd yottahmd commented Feb 11, 2026

Summary by CodeRabbit

Release Notes

Refactoring

  • Standardized terminology across agent chat operations: replaced "conversation" with "session" to better represent multi-turn interactions
  • Clarified terminal interactions: renamed "terminal session" to "terminal connection" to distinguish from agent chat sessions
  • Updated API endpoints from /conversations/ to /sessions/ endpoints
  • Aligned audit logging with consistent session and connection terminology

@coderabbitai
Copy link

coderabbitai bot commented Feb 11, 2026

Important

Review skipped

Auto incremental reviews are disabled on this repository.

Please check the settings in the CodeRabbit UI or the .coderabbit.yaml file in this repository. To trigger a single review, invoke the @coderabbitai review command.

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

This pull request systematically renames the "conversation" domain to "session" throughout the codebase, affecting API endpoints, type definitions, storage interfaces, internal managers, configuration schemas, and UI components. The core functionality remains unchanged; all references to conversations are replaced with sessions with consistent naming.

Changes

Cohort / File(s) Summary
API Schema & Generation
api/v1/api.yaml, api/v1/api.gen.go
OpenAPI schema and generated code updated to reference sessions instead of conversations in ChatMessage descriptions and documentation.
Agent API Core
internal/agent/api.go, internal/agent/api_test.go
API struct and handler methods renamed from conversation-centric to session-centric; routes changed from /conversations/* to /sessions/*; internal store type changed from ConversationStore to SessionStore.
Agent Manager Implementation
internal/agent/conversation.go (removed), internal/agent/session.go (added), internal/agent/session_test.go
Entire ConversationManager removed and replaced with SessionManager with identical public methods and behavior; comprehensive session lifecycle, messaging, streaming, and cost tracking implemented.
Agent Loop & Hooks
internal/agent/loop.go, internal/agent/loop_test.go, internal/agent/hooks.go, internal/agent/hooks_test.go
LoopConfig.ConversationID → LoopConfig.SessionID; ToolExecInfo.ConversationID → ToolExecInfo.SessionID; internal loop references updated to session terminology.
Agent Type Definitions & Storage
internal/agent/types.go, internal/agent/store.go, internal/agent/mocks_test.go, internal/agent/think.go
Conversation type renamed to Session; ConversationState to SessionState; ConversationStore interface to SessionStore; all CRUD and message operations updated with session-specific error semantics (ErrSessionNotFound, ErrInvalidSessionID).
Persistence Layer
internal/persis/fileconversation/store.go (removed), internal/persis/filesession/store.go (added), internal/persis/filesession/store_test.go
File-based conversation store completely removed and replaced with session store implementation providing identical persistence, indexing, and message-handling functionality.
Configuration & Schema
internal/cmn/config/config.go, internal/cmn/config/definition.go, internal/cmn/config/loader.go, internal/cmn/config/loader_test.go, internal/cmn/schema/config.schema.json
PathsConfig.ConversationsDir → PathsConfig.SessionsDir; configuration loader updated to map sessionsDir with default path agent/sessions; schema updated accordingly.
Runtime & Execution
internal/runtime/builtin/chat/executor.go, internal/runtime/builtin/chat/tools.go, internal/runtime/data.go, internal/runtime/executor/executor.go, internal/runtime/runner.go, internal/core/llm.go, internal/core/exec/node.go, internal/core/exec/messages.go, internal/core/spec/step.go, internal/llm/types.go
Documentation/comments updated from conversation to session terminology across message types, execution nodes, and LLM configurations; no logic changes.
DAG Schema
internal/cmn/schema/dag.schema.json
Schema descriptions updated to reference session messages and prompts instead of conversation equivalents.
Audit & Service Layer
internal/service/audit/service.go, internal/service/audit/service_test.go, internal/service/frontend/server.go, internal/service/frontend/agent_audit_test.go
Terminal logging methods renamed: LogTerminalSessionStart/End → LogTerminalConnectionStart/End with sessionID → connectionID parameter; server imports filesession instead of fileconversation; agent audit hook updated to use session_id.
Terminal Connection Handler
internal/service/frontend/terminal/connection.go, internal/service/frontend/terminal/handler.go
Session type exported as Connection; NewSession → NewConnection; all receiver references updated; audit logging calls switched to connection terminology.
UI Components & Hooks
ui/src/features/agent/components/AgentChatModal.tsx, ui/src/features/agent/components/AgentChatModalHeader.tsx, ui/src/features/agent/context/AgentChatContext.tsx, ui/src/features/agent/hooks/useAgentChat.ts, ui/src/features/agent/types.ts
ConversationWithState → SessionWithState; API endpoints changed from /conversations to /sessions; all context properties, hooks, and handlers renamed (conversationId → sessionId, selectConversation → selectSession, etc.); SSE event handling updated for session_state.
UI Pages & Schema
ui/src/api/v1/schema.ts, ui/src/pages/audit-logs/index.tsx, ui/src/pages/terminal/index.tsx
Generated schema updated; audit logs display connection_id instead of session_id for terminal events; terminal page label adjusted.
Documentation & RFCs
rfcs/001-agent-authorization.md, rfcs/002-agent-audit.md, rfcs/003-agent-history-management.md, rfcs/009-namespaces.md, rfcs/012-agent-inbox.md, internal/cmd/coord.go
RFC titles and content updated to use session terminology; ConversationStore → SessionStore; comments and descriptions consistently updated across all documentation.

Estimated code review effort

🎯 4 (Complex) | ⏱️ ~75 minutes

Possibly related PRs

  • feat: chat assistant #1615: Introduces the agent conversation subsystem (ConversationManager, ConversationStore, conversation-based API handlers) which this PR comprehensively renames to session equivalents while preserving all underlying functionality.
  • feat: agent model selection #1651: Modifies agent model selection, pricing, and provider resolution within the conversation manager lifecycle—directly affected by the ConversationManager → SessionManager refactoring in this PR.
  • feat: safe mode toggle for agent #1620: Adds SafeMode support to ConversationManager and LoopConfig, which this PR propagates through the new SessionManager and updated LoopConfig fields.
🚥 Pre-merge checks | ✅ 1 | ❌ 2
❌ Failed checks (2 warnings)
Check name Status Explanation Resolution
Title check ⚠️ Warning The title 'reafctor: renaming persistence store for clarity' contains a typo ('reafctor' instead of 'refactor') and is misleading. The changeset involves a comprehensive domain-wide rename from 'conversation' to 'session' across the entire codebase, not just renaming a persistence store. Correct the typo to 'refactor' and update the title to accurately reflect the scope: 'refactor: rename conversation to session throughout codebase' or 'refactor: replace conversation domain with session domain'.
Docstring Coverage ⚠️ Warning Docstring coverage is 18.10% which is insufficient. The required threshold is 80.00%. Write docstrings for the functions missing them to satisfy the coverage threshold.
✅ Passed checks (1 passed)
Check name Status Explanation
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.

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

✨ Finishing touches
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Post copyable unit tests in a comment
  • Commit unit tests in branch refactor-convo-store

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.

Copy link

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

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

Actionable comments posted: 4

Caution

Some comments are outside the diff and can’t be posted inline due to platform limitations.

⚠️ Outside diff range comments (1)
internal/cmn/config/definition.go (1)

175-192: ⚠️ Potential issue | 🟠 Major

Add legacy conversationsDir mapping to prevent breaking existing configs.

The rename from conversationsDir to sessionsDir breaks existing configurations. No migration path exists in loadLegacyPaths(), which handles legacy field mappings for other paths. Add conversationsDir to the legacy paths list or keep both fields with a deprecated alias to maintain backward compatibility.

🤖 Fix all issues with AI agents
In `@internal/agent/session.go`:
- Around line 193-203: GetSession currently returns CreatedAt from the mutable
sm.lastActivity, causing the creation time to drift; add a new immutable field
(e.g., createdAt) to SessionManager, initialize it in NewSessionManager when the
manager is constructed, and update GetSession to set CreatedAt to sm.createdAt
(leave UpdatedAt as sm.lastActivity); make the analogous change in
SubscribeWithSnapshot so that snapshots use sm.createdAt for CreatedAt instead
of sm.lastActivity.

In `@internal/cmn/config/loader.go`:
- Around line 956-958: The default sessions path changed from
"agent/conversations" to "agent/sessions", which will orphan existing data;
update finalizePaths (or startup path initialization where cfg.Paths.SessionsDir
is set) to perform a one-time migration: if cfg.Paths.SessionsDir is empty set
it as now (filepath.Join(cfg.Paths.DataDir, "agent", "sessions")), then check
for an existing oldDir := filepath.Join(cfg.Paths.DataDir, "agent",
"conversations") and if oldDir exists and newDir does not, atomically
rename/move oldDir to newDir (handle errors and permissions), otherwise leave
existing newDir intact; reference cfg.Paths.SessionsDir and the finalizePaths
initialization code to implement this migration.

In `@internal/persis/filesession/store.go`:
- Around line 194-197: The sessionFilePath currently constructs paths using
userID and sessionID directly, allowing path traversal; add a validation helper
(e.g., validateSessionIDs or sanitizeID) and call it from validateSession (or
before any call to sessionFilePath) to reject or return an error for IDs
containing path separators ('/', '\') or path traversal segments (".."); ensure
both userID and sessionID are checked and that Store.sessionFilePath continues
to assume validated IDs so callers cannot escape Store.baseDir using crafted
IDs.

In `@internal/service/frontend/server.go`:
- Line 452: The audit field was renamed from conversation_id to session_id which
breaks downstream queries; update the audit population to set both keys so
existing consumers keep working by assigning info.SessionID to both
details["session_id"] and details["conversation_id"] (locate where the details
map is populated and where info.SessionID is used), ensuring both keys are
emitted for backward compatibility.
🧹 Nitpick comments (9)
internal/runtime/builtin/chat/tools.go (1)

1-1: Comment wording aligns with PR objectives.

The terminology update from "conversation" to "session" is consistent with the PR's refactoring goals.

The phrase "chat (LLM-based session) steps" is grammatically correct but could be simplified for clarity. Consider:

-// Package chat provides an executor for chat (LLM-based session) steps.
+// Package chat provides an executor for LLM-based session steps.

or

-// Package chat provides an executor for chat (LLM-based session) steps.
+// Package chat provides an executor for chat steps using LLM-based sessions.
internal/agent/hooks_test.go (1)

29-36: Test data still uses "conv-1" for SessionID.

The field was renamed to SessionID, but the test value still uses the old "conv-" prefix. Consider updating to "sess-1" for consistency with the new terminology — the AI summary mentions other tests already use sessX-style IDs.

Suggested fix
 	info := ToolExecInfo{
 		ToolName:  "bash",
 		Input:     json.RawMessage(`{"command":"ls"}`),
-		SessionID: "conv-1",
+		SessionID: "sess-1",
 		UserID:    "user-1",
 		Username:  "alice",
 		IPAddress: "10.0.0.1",
 	}

And the corresponding assertion:

-	assert.Equal(t, "conv-1", captured.info.SessionID)
+	assert.Equal(t, "sess-1", captured.info.SessionID)
internal/cmn/config/loader_test.go (1)

536-547: TestLoad_EdgeCases_DerivedPaths doesn't assert SessionsDir.

SessionsDir is derived from DataDir (as seen in the other tests at Lines 184 and 442), but this dedicated derived-paths test doesn't verify it. Consider adding an assertion for completeness.

Suggested addition
 	assert.Equal(t, "/custom/data/service-registry", cfg.Paths.ServiceRegistryDir)
 	assert.Equal(t, "/custom/data/users", cfg.Paths.UsersDir)
+	assert.Equal(t, "/custom/data/agent/sessions", cfg.Paths.SessionsDir)
 }
ui/src/features/agent/types.ts (1)

81-99: Verify UI session types stay aligned with backend payloads.
Backend Session includes user_id and title, and SessionWithState includes total_cost. If those fields are still returned/used, add them here to avoid silent drops or TS friction.

💡 Suggested parity update
 export interface Session {
   id: string;
+  user_id?: string;
+  title?: string;
   created_at: string;
   updated_at: string;
 }

 export interface SessionWithState {
   session: Session;
   working: boolean;
   model?: string;
+  total_cost?: number;
 }
internal/service/frontend/agent_audit_test.go (1)

21-28: Test fixture values still use "conv-" prefix for session IDs.

The SessionID fields use values like "conv-123", "conv-456", "conv-789". While functionally harmless, these could be updated to "sess-123" etc. to avoid confusion now that the domain term is "session."

ui/src/features/agent/components/AgentChatModal.tsx (1)

126-135: totalCost sourced from sessionState?.total_cost — note frontend/backend type gap on SessionWithState.

The totalCost prop is correctly sourced from sessionState?.total_cost (which is of type SessionState). However, the backend Go SessionWithState struct includes a TotalCost float64 field (json:"total_cost") at internal/agent/api.go:92, but the frontend TypeScript SessionWithState interface (ui/src/features/agent/types.ts:94-98) omits total_cost. If you intend to display per-session cost in the session list in the future, the TS type will need updating.

internal/persis/filesession/store.go (1)

271-296: ListSessions re-reads every session file from disk individually.

For each session ID, ListSessions calls GetSession which calls loadSessionByIDloadSessionFromFile, deserializing the full JSON (including all messages) just to return session metadata. For users with many sessions, this is N file reads with full message deserialization.

This is acceptable for a file-based store with small-to-moderate usage, but worth noting for future scalability. An alternative would be to cache session metadata in the index or store metadata separately from messages.

ui/src/features/agent/hooks/useAgentChat.ts (1)

146-159: startSession immediately fetches all sessions after creation — consider optimistic update.

After creating a new session, startSession makes a second API call to fetch the full sessions list. This works correctly but adds latency. An optimistic local insert (appending the new session to the existing list) could improve perceived responsiveness, with a background refresh for consistency.

This is not a blocking concern for a rename PR.

internal/agent/session.go (1)

409-440: createRecordMessageFunc silently swallows persistence errors.

The returned function always returns nil (line 438), even when sm.onMessage fails (line 433-435). The error is logged but not propagated to the Loop. This means the Loop will continue operating normally even if every message fails to persist.

If this is intentional (session continues despite persistence failures), consider adding a brief comment explaining the design decision. If persistence failures should eventually stop the session, the error should be returned.

@yottahmd yottahmd merged commit 5c7afbb into main Feb 12, 2026
6 checks passed
@yottahmd yottahmd deleted the refactor-convo-store branch February 12, 2026 02:57
@codecov
Copy link

codecov bot commented Feb 12, 2026

Codecov Report

❌ Patch coverage is 68.79240% with 230 lines in your changes missing coverage. Please review.
✅ Project coverage is 69.93%. Comparing base (d44040c) to head (72b005e).
⚠️ Report is 1 commits behind head on main.

Files with missing lines Patch % Lines
internal/agent/session.go 64.20% 70 Missing and 51 partials ⚠️
internal/persis/filesession/store.go 71.64% 14 Missing and 60 partials ⚠️
internal/agent/api.go 71.27% 26 Missing and 1 partial ⚠️
internal/runtime/builtin/chat/executor.go 0.00% 5 Missing ⚠️
internal/agent/loop.go 88.46% 3 Missing ⚠️
Additional details and impacted files

Impacted file tree graph

@@            Coverage Diff             @@
##             main    #1653      +/-   ##
==========================================
- Coverage   70.21%   69.93%   -0.29%     
==========================================
  Files         344      344              
  Lines       38307    38316       +9     
==========================================
- Hits        26899    26798     -101     
- Misses       9274     9289      +15     
- Partials     2134     2229      +95     
Files with missing lines Coverage Δ
internal/agent/hooks.go 100.00% <ø> (ø)
internal/agent/store.go 94.28% <ø> (ø)
internal/agent/think.go 100.00% <ø> (ø)
internal/agent/types.go 100.00% <ø> (ø)
internal/cmd/coord.go 74.59% <ø> (ø)
internal/cmn/config/config.go 76.28% <ø> (ø)
internal/cmn/config/loader.go 83.08% <100.00%> (ø)
internal/core/exec/messages.go 100.00% <ø> (ø)
internal/core/exec/node.go 100.00% <ø> (ø)
internal/core/llm.go 75.75% <ø> (ø)
... and 14 more

... and 4 files with indirect coverage changes


Continue to review full report in Codecov by Sentry.

Legend - Click here to learn more
Δ = absolute <relative> (impact), ø = not affected, ? = missing data
Powered by Codecov. Last update d44040c...72b005e. Read the comment docs.

🚀 New features to boost your workflow:
  • ❄️ Test Analytics: Detect flaky tests, report on failures, and find test suite problems.
  • 📦 JS Bundle Analysis: Save yourself from yourself by tracking and limiting bundle sizes in JS merges.

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