Skip to content

feat: add server-side session management for multi-turn conversations - #51

Merged
pavelanni merged 6 commits into
mainfrom
feature/server-side-sessions
May 5, 2026
Merged

pavelanni merged 6 commits into
mainfrom
feature/server-side-sessions

Conversation

@pavelanni

@pavelanni pavelanni commented May 5, 2026 •

Copy link
Copy Markdown
Collaborator

Summary

  • Add internal/session package with in-memory Store (map + RWMutex, TTL-based reaper)
  • Executor manages session lifecycle using client-sent x-session-id header as session key
  • MessageProcessor signature changes from func(ctx, string) to func(ctx, []llm.Message) — server builds conversation history, not the client
  • Chat TUI generates a stable session ID per instance and sends it via ServiceParams
  • Client stops prepending conversation history as plaintext (server has it)

Each chat message creates an independent A2A task (respecting the protocol's terminal task states), but the server groups them into a conversation session via the x-session-id header. Two terminal sessions get independent conversations. Sessions expire after 30 minutes of idle time.

Design

See docs/superpowers/specs/2026-05-04-server-side-sessions-design.md.

Test plan

  • make test passes — session store tests cover GetOrCreate, Append, reaper, cancellation
  • make lint passes (0 issues)
  • make build passes
  • Manual: 5-turn conversation, agent remembers context, session_id stable, message_count grows correctly

Closes #5 (Phase 1)

🤖 Generated with Claude Code

Summary by CodeRabbit

Release Notes

  • New Features

    • Multi-turn conversation sessions with automatic inactivity-based cleanup
    • Server-side session management reduces redundant message transmission and improves context awareness
  • Documentation

    • Added session management design specification

pavelanni added 2 commits May 4, 2026 20:08
Assisted-By: Claude (Anthropic AI) <[email protected]>
Signed-off-by: Pavel Anni <[email protected]>
…#5)

The server was stateless — the chat TUI worked around this by
prepending full conversation history as plaintext into each request,
wasting tokens and losing message structure.

Now the server maintains per-task conversation sessions using the
A2A protocol's taskId. The client detects server-side sessions from
the response and stops prepending history.

- Add internal/session package with in-memory Store (TTL + reaper)
- Update executor to manage session lifecycle (GetOrCreate, Append)
- Change MessageProcessor to accept []llm.Message instead of string
- Add TaskID to InvokeRequest/InvokeResult for session continuity
- Chat TUI stores taskID and skips history prepending when set

Assisted-By: Claude (Anthropic AI) <[email protected]>
Signed-off-by: Pavel Anni <[email protected]>
@coderabbitai

coderabbitai Bot commented May 5, 2026 •

Copy link
Copy Markdown

Warning

Rate limit exceeded

@pavelanni has exceeded the limit for the number of commits that can be reviewed per hour. Please wait 50 minutes and 26 seconds before requesting another review.

To keep reviews running without waiting, you can enable usage-based add-on for your organization. This allows additional reviews beyond the hourly cap. Account admins can enable it under billing.

⌛ How to resolve this issue?

After the wait time has elapsed, a review can be triggered using the @coderabbitai review command as a PR comment. Alternatively, push new commits to this PR.

We recommend that you space out your commits to avoid hitting the rate limit.

🚦 How do rate limits work?

CodeRabbit enforces hourly rate limits for each developer per organization.

Our paid plans have higher rate limits than the trial, open-source and free plans. In all cases, we re-allow further reviews after a brief timeout.

Please see our FAQ for further information.

ℹ️ Review info
⚙️ Run configuration

Configuration used: Organization UI

Review profile: CHILL

Plan: Enterprise

Run ID: e8627aa5-1784-4d75-8fce-1f3257443280

📥 Commits

Reviewing files that changed from the base of the PR and between 0e2061b and 57be091.

📒 Files selected for processing (4)
  • docs/superpowers/specs/2026-05-04-server-side-sessions-design.md
  • internal/bridge/executor.go
  • internal/session/store.go
  • internal/session/store_test.go
📝 Walkthrough

Walkthrough

This PR implements server-side session management to enable multi-message LLM interactions without per-request full-history tokenization. It introduces an in-memory session store with TTL eviction, updates the client protocol to send session IDs via headers, and modifies the executor to manage session state and message history across requests.

Changes

Server-Side Session Management

Layer / File(s) Summary
Data Shape
internal/session/store.go (lines 12–25)
Session type holds ID, message history ([]llm.Message), and timestamps. Store manages sessions in a mutex-protected map with a configured TTL.
Session Store Implementation
internal/session/store.go (lines 27–115)
NewStore(ttl) initializes the store; GetOrCreate(id, systemPrompt) retrieves or creates a session seeded with a system message; Get(id) retrieves a session; Append(id, msg) adds messages and updates LastActive; StartReaper(ctx) runs a background ticker to delete idle sessions exceeding TTL.
Protocol & Client Wiring
internal/bridge/client.go (lines 31–77)
InvokeRequest gains SessionID field; A2AClient.Invoke injects SessionID as x-session-id header when present.
Chat Client State
internal/chat/model.go (lines 4–303)
Model generates a persistent sessionID on creation via generateSessionID() and tracks sessionConfirmed state. After first successful response, history prepending is skipped; session ID is sent with each InvokeRequest.
Executor Integration
internal/bridge/executor.go (lines 12–128)
MessageProcessor signature changes from (ctx, userMessage string) to (ctx, messages []llm.Message). AgentExecutor gains Sessions store and SystemPrompt fields. Execute extracts x-session-id header, constructs message history from sessions (or single-turn with system prompt), calls ProcessMessage, and appends assistant response to session when session-backed.
Server Wiring
internal/cmd/serve.go (lines 19–435)
Initializes session store with background reaper goroutine; assigns to executor.Sessions; sets executor.SystemPrompt to systemPrompt + skillsSummary; replaces free-form ProcessMessage to accept []llm.Message and invoke tools.RunToolLoop directly.
Session Store Tests
internal/session/store_test.go (lines 11–118)
Tests cover GetOrCreate (creates and reuses), Append (updates LastActive, no-ops on nonexistent sessions), Get (returns nil for missing), TTL reaping, and background reaper cancellation.
Project Documentation
CLAUDE.md (line 59), docs/superpowers/specs/2026-05-04-server-side-sessions-design.md (lines 7–153)
Updated project structure table; added comprehensive design document specifying session store API, executor/server changes, client protocol (SessionID header), lifecycle behavior, and future persistence work.

Sequence Diagram

sequenceDiagram
    participant Client as Chat Client
    participant Server as Server/Executor
    participant Store as Session Store
    participant LLM as LLM Provider

    rect rgba(100, 150, 200, 0.5)
    Note over Client,LLM: First Message
    Client->>Client: Generate sessionID
    Client->>Server: InvokeRequest + x-session-id header
    Server->>Store: GetOrCreate(sessionID, systemPrompt)
    Store->>Store: Create Session [system message]
    Store-->>Server: Session (with system message)
    Server->>Server: Append user message
    Server->>LLM: ProcessMessage([system, user])
    LLM-->>Server: Assistant response
    Server->>Store: Append(sessionID, assistant message)
    Server-->>Client: Response + set sessionConfirmed
    end

    rect rgba(150, 200, 100, 0.5)
    Note over Client,LLM: Subsequent Messages (Session Active)
    Client->>Server: InvokeRequest + sessionID (no history prepended)
    Server->>Store: Get(sessionID)
    Store-->>Server: Session [system, user₁, assistant₁, ...]
    Server->>Server: Append user₂ to message list
    Server->>LLM: ProcessMessage([system, user₁, assistant₁, user₂])
    LLM-->>Server: Assistant response
    Server->>Store: Append(sessionID, assistant₂)
    Server-->>Client: Response
    end

    rect rgba(200, 150, 100, 0.5)
    Note over Store: Background TTL Reaper
    Store->>Store: Periodically check LastActive
    Store->>Store: Delete sessions idle > TTL
    end
Loading

Estimated code review effort

🎯 3 (Moderate) | ⏱️ ~22 minutes

🚥 Pre-merge checks | ✅ 4 | ❌ 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 20.00% 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 accurately describes the main change: adding server-side session management for multi-turn conversations, which is the core feature implemented across all modified files.
Linked Issues check ✅ Passed The PR implements Phase 1 server-side session persistence addressing the broader objective of issue #5, though the full acceptance criteria (memory framework evaluation, tool interface, agent-config integration) remain future work.
Out of Scope Changes check ✅ Passed All changes are scoped to implementing server-side session management: new session store, executor/client integration, MessageProcessor signature update, and comprehensive testing—all aligned with the Phase 1 session persistence objective.

✏️ 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 feature/server-side-sessions

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.

pavelanni added 2 commits May 4, 2026 20:48
A2A tasks are terminal once completed — reusing taskId for follow-up
messages causes "task in terminal state" errors. Switch to a
client-generated session ID sent as x-session-id ServiceParam header.
Each message creates an independent A2A task but shares a server-side
session via the header.

Assisted-By: Claude (Anthropic AI) <[email protected]>
Signed-off-by: Pavel Anni <[email protected]>
- Only skip history prepending after first successful response
  (sessionConfirmed flag), not based on sessionID presence alone.
  Preserves backward compat with servers without session support.
- Add session ID length validation (max 64 chars) in executor
- Update design doc to reflect x-session-id implementation

Assisted-By: Claude (Anthropic AI) <[email protected]>
Signed-off-by: Pavel Anni <[email protected]>
Assisted-By: Claude (Anthropic AI) <[email protected]>
Signed-off-by: Pavel Anni <[email protected]>
@pavelanni
pavelanni marked this pull request as ready for review May 5, 2026 01:01

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

Actionable comments posted: 4

🧹 Nitpick comments (7)
internal/session/store.go (2)

88-100: 💤 Low value

Reaper ticker interval is hardcoded — consider plumbing through NewStore.

The 60s tick is a reasonable default but unrelated to the configured ttl. For tests using sub-second TTLs (see TestStoreReaper), a configurable interval would let StartReaper be exercised directly instead of having to call the unexported s.reap().

🤖 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 `@internal/session/store.go` around lines 88 - 100, StartReaper uses a
hardcoded 60s ticker which prevents tests with sub-second ttl from exercising
the reaper; add a configurable reaper interval to Store (e.g., a reaperInterval
time.Duration field) and accept it via NewStore (with a sensible default derived
from ttl or a constant) so StartReaper uses s.reaperInterval instead of 60s;
update NewStore to set the default interval when not provided and adjust tests
to pass a short interval for TestStoreReaper while keeping reap() available for
internal calls.

28-33: 🏗️ Heavy lift

Unbounded session/message growth is a DoS vector.

Attackers (or buggy clients) can send unlimited unique x-session-id values within a 30-minute window, each creating a session that retains its full message history until idle TTL expires. Similarly, a single long-lived session has no cap on accumulated messages. The TTL alone is not enough back-pressure for an internet-facing endpoint.

Recommended phase-1 hardening (also flagged in the design doc's "Future work"):

  • Cap total active sessions (e.g. maxSessions); evict oldest by LastActive when exceeded.
  • Cap messages per session (e.g. maxMessagesPerSession); drop or compact oldest non-system messages.

Not blocking for the chat-TUI proof of concept, but should land before this is exposed beyond trusted callers.

🤖 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 `@internal/session/store.go` around lines 28 - 33, NewStore currently creates
an unbounded Store (sessions map) which allows unlimited sessions and unlimited
messages per session; update the Store and NewStore to accept or embed limits
(e.g. maxSessions and maxMessagesPerSession), enforce maxSessions by evicting
the oldest session(s) by Session.LastActive when creating a new session or on
insertion into Store.sessions, and enforce maxMessagesPerSession inside the
Session message append path (e.g. an AddMessage/AppendMessage method) by
dropping or compacting the oldest non-system messages until the session is under
the limit; ensure these limits are enforced atomically under the Store's mutex
where Store.sessions is mutated and reference the NewStore, Store, Session,
LastActive, sessions map, and any message-append function to locate and change
the code.
docs/superpowers/specs/2026-05-04-server-side-sessions-design.md (1)

110-122: 💤 Low value

Add a language hint to the lifecycle code fence (markdownlint MD040).

Static analysis flags the unlabelled fence. Use ```text (or similar) to silence the warning and improve rendering.

📝 Suggested fix
-```
+```text
 TUI: "hello"  →  Server: x-session-id=S1 → create session S1
🤖 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 `@docs/superpowers/specs/2026-05-04-server-side-sessions-design.md` around
lines 110 - 122, The lifecycle code fence showing the session flow is an
unlabelled markdown fence causing markdownlint MD040; update the opening fence
(the block that begins with ```) for the TUI→Server session lifecycle to use a
language hint such as ```text (or similar) so the fence is labelled and the
linter warning is silenced.
internal/session/store_test.go (2)

81-99: 💤 Low value

TTL/reaper tests rely on real wall-clock sleeps; consider a fakeable clock for stability.

TestStoreReaper uses 10ms TTL plus 20ms sleeps, which can be flaky on heavily loaded CI runners. Not blocking, but extracting time via a small now func() time.Time (or accepting a clock) would make these deterministic.

🤖 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 `@internal/session/store_test.go` around lines 81 - 99, TestStoreReaper is
flaky because Store uses real time; change Store to use an injectable clock
(e.g., add a now func() time.Time field or accept a Clock interface) so TTL
checks and reap() use that instead of time.Now; update NewStore (or add
NewStoreWithClock) to set the default now to time.Now, update methods reap,
GetOrCreate, Append, and any TTL comparisons to call s.now(), and update the
test TestStoreReaper to use a fake clock instance and advance it instead of
calling time.Sleep so the test becomes deterministic.

11-118: ⚡ Quick win

Add a -race-aware concurrent test for the store.

The store will be exercised by concurrent Execute calls keyed on a shared x-session-id. A small test that runs many parallel GetOrCreate/Append/Get ops would catch races inside the store and any future regressions when the executor is reworked to take snapshots under lock (see comment on internal/bridge/executor.go).

🤖 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 `@internal/session/store_test.go` around lines 11 - 118, Add a new concurrent
test (e.g., TestStoreConcurrentRace) that stresses
NewStore/GetOrCreate/Append/Get under parallelism: create a store, spawn many
goroutines (use sync.WaitGroup) that repeatedly call
s.GetOrCreate("x-session-id", "system-prompt"), s.Append("x-session-id",
llm.Message{...}) and s.Get("x-session-id") in tight loops (hundreds/thousands
of iterations), then wait for all goroutines and assert no panics and that
s.Len() == 1 and the session has at least the expected number of messages; this
will exercise the same session id concurrently to catch races when running `go
test -race`. Ensure the test function name is unique (TestStoreConcurrentRace)
and references NewStore, GetOrCreate, Append, and Get so it’s easy to locate.
internal/chat/model.go (1)

86-90: 💤 Low value

Consider handling the crypto/rand.Read error for defensive session ID generation.

If rand.Read ever returns an error, b stays zeroed and every session ID degenerates to the same all-zero UUID, causing all clients to share the same server session. In practice rand.Read is extremely reliable on supported platforms, but a tiny guard avoids that worst-case sharing.

♻️ Suggested handling
 func generateSessionID() string {
 	b := make([]byte, 16)
-	_, _ = rand.Read(b)
+	if _, err := rand.Read(b); err != nil {
+		// Fall back to time-based ID; collisions still unlikely in single-TUI use.
+		return fmt.Sprintf("ts-%d", time.Now().UnixNano())
+	}
 	return fmt.Sprintf("%x-%x-%x-%x-%x", b[0:4], b[4:6], b[6:8], b[8:10], b[10:])
 }
🤖 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 `@internal/chat/model.go` around lines 86 - 90, generateSessionID currently
ignores the error from rand.Read which can produce identical all-zero IDs;
modify generateSessionID to check the error returned by rand.Read and handle it
defensively (e.g., on err != nil retry rand.Read once, and if it still fails use
a secure fallback such as filling b with a math/rand PRNG seeded from
time.Now().UnixNano() or composing a timestamp+random nonce) so the function
never returns a constant all-zero value; update references in generateSessionID
to ensure any fallback still produces a suitably unique hex UUID-like string.
internal/bridge/executor.go (1)

97-99: 💤 Low value

Session ID truncation guard is good; consider also rejecting empty/whitespace IDs.

Truncating to 64 chars correctly bounds attacker-influenced input. A trimmed/non-printable check would further prevent edge cases like clients sending whitespace or control characters as the session key, but it's not blocking.

🤖 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 `@internal/bridge/executor.go` around lines 97 - 99, The current truncation
(sessionID = sessionID[:64]) should be preceded by sanitization: trim
surrounding whitespace with strings.TrimSpace, then reject (return an error or
nil/unauthorized) if the trimmed sessionID is empty or consists solely of
non-printable/control characters (check runes with unicode.IsPrint or similar);
after that, enforce the 64-char cap using either rune-aware truncation (slice by
runes) or validate utf8 length before slicing. Update the code paths that use
the sessionID variable (the sessionID assignment/truncation block) to perform
TrimSpace + printable-rune check and return a clear error when invalid, then
apply the existing 64-character truncation safely.
🤖 Prompt for all review comments with 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.

Inline comments:
In `@docs/superpowers/specs/2026-05-04-server-side-sessions-design.md`:
- Around line 131-138: Update the PR summary table to reflect the actual
session-id flow: change the bridge/client row to say that InvokeRequest now
carries sessionID which is propagated as the x-session-id header to A2A and note
that InvokeResult is unchanged (no TaskID change), and change the chat/model row
to say the model stores sessionID and gates history prepending on
sessionConfirmed (which is set after the first successful response) rather than
referring to the old TaskID behavior; reference the symbols InvokeRequest,
InvokeResult, sessionID, sessionConfirmed and the x-session-id header to make
locating the code clear.

In `@internal/bridge/executor.go`:
- Around line 100-128: There is a race on the session's mutable fields because
executor reads sess.Messages (via e.Sessions.GetOrCreate -> sess.Messages)
outside the store lock while other goroutines can call e.Sessions.Append; to
fix, add a Store method (e.g., AppendAndSnapshot or Snapshot) that performs the
append (or just snapshot) under the store's mutex and returns a copied
[]llm.Message, then update executor.go to call that new method instead of
reading sess.Messages directly and pass the returned slice into
e.ProcessMessage; ensure you also update the post-processing append path to use
the same atomic AppendAndSnapshot (or a separate Append when appropriate) so no
pointer to the store-owned session is used outside the lock.

In `@internal/session/store.go`:
- Around line 37-57: GetOrCreate currently returns a live *Session that callers
read without the store mutex, causing data races with Append/reap; change the
API so callers get safe snapshots: modify GetOrCreate to return a Session
(value) copy instead of *Session, and add Snapshot(id) (returns []llm.Message,
bool) plus AppendAndSnapshot(id string, msg llm.Message) []llm.Message that
perform all reads/writes under s.mu and return copies of Messages; update
internal callers to use AppendAndSnapshot or Snapshot and remove any direct
pointer reads so no code accesses Session fields outside the mutex.
- Around line 67-77: The Append method on Store silently drops messages if the
session was reaped; update Store.Append to return an error or bool indicating
success (e.g., (bool, error)) instead of void and log a warning when the session
id is missing, so callers like the code path that calls Append after GetOrCreate
(executor.go:126) can detect failure and recreate the session; modify the Append
signature and all callers to handle the returned value, log a descriptive
warning via the existing logger when sess not found, and consider propagating an
error type such as ErrSessionNotFound for callers to react to.

---

Nitpick comments:
In `@docs/superpowers/specs/2026-05-04-server-side-sessions-design.md`:
- Around line 110-122: The lifecycle code fence showing the session flow is an
unlabelled markdown fence causing markdownlint MD040; update the opening fence
(the block that begins with ```) for the TUI→Server session lifecycle to use a
language hint such as ```text (or similar) so the fence is labelled and the
linter warning is silenced.

In `@internal/bridge/executor.go`:
- Around line 97-99: The current truncation (sessionID = sessionID[:64]) should
be preceded by sanitization: trim surrounding whitespace with strings.TrimSpace,
then reject (return an error or nil/unauthorized) if the trimmed sessionID is
empty or consists solely of non-printable/control characters (check runes with
unicode.IsPrint or similar); after that, enforce the 64-char cap using either
rune-aware truncation (slice by runes) or validate utf8 length before slicing.
Update the code paths that use the sessionID variable (the sessionID
assignment/truncation block) to perform TrimSpace + printable-rune check and
return a clear error when invalid, then apply the existing 64-character
truncation safely.

In `@internal/chat/model.go`:
- Around line 86-90: generateSessionID currently ignores the error from
rand.Read which can produce identical all-zero IDs; modify generateSessionID to
check the error returned by rand.Read and handle it defensively (e.g., on err !=
nil retry rand.Read once, and if it still fails use a secure fallback such as
filling b with a math/rand PRNG seeded from time.Now().UnixNano() or composing a
timestamp+random nonce) so the function never returns a constant all-zero value;
update references in generateSessionID to ensure any fallback still produces a
suitably unique hex UUID-like string.

In `@internal/session/store_test.go`:
- Around line 81-99: TestStoreReaper is flaky because Store uses real time;
change Store to use an injectable clock (e.g., add a now func() time.Time field
or accept a Clock interface) so TTL checks and reap() use that instead of
time.Now; update NewStore (or add NewStoreWithClock) to set the default now to
time.Now, update methods reap, GetOrCreate, Append, and any TTL comparisons to
call s.now(), and update the test TestStoreReaper to use a fake clock instance
and advance it instead of calling time.Sleep so the test becomes deterministic.
- Around line 11-118: Add a new concurrent test (e.g., TestStoreConcurrentRace)
that stresses NewStore/GetOrCreate/Append/Get under parallelism: create a store,
spawn many goroutines (use sync.WaitGroup) that repeatedly call
s.GetOrCreate("x-session-id", "system-prompt"), s.Append("x-session-id",
llm.Message{...}) and s.Get("x-session-id") in tight loops (hundreds/thousands
of iterations), then wait for all goroutines and assert no panics and that
s.Len() == 1 and the session has at least the expected number of messages; this
will exercise the same session id concurrently to catch races when running `go
test -race`. Ensure the test function name is unique (TestStoreConcurrentRace)
and references NewStore, GetOrCreate, Append, and Get so it’s easy to locate.

In `@internal/session/store.go`:
- Around line 88-100: StartReaper uses a hardcoded 60s ticker which prevents
tests with sub-second ttl from exercising the reaper; add a configurable reaper
interval to Store (e.g., a reaperInterval time.Duration field) and accept it via
NewStore (with a sensible default derived from ttl or a constant) so StartReaper
uses s.reaperInterval instead of 60s; update NewStore to set the default
interval when not provided and adjust tests to pass a short interval for
TestStoreReaper while keeping reap() available for internal calls.
- Around line 28-33: NewStore currently creates an unbounded Store (sessions
map) which allows unlimited sessions and unlimited messages per session; update
the Store and NewStore to accept or embed limits (e.g. maxSessions and
maxMessagesPerSession), enforce maxSessions by evicting the oldest session(s) by
Session.LastActive when creating a new session or on insertion into
Store.sessions, and enforce maxMessagesPerSession inside the Session message
append path (e.g. an AddMessage/AppendMessage method) by dropping or compacting
the oldest non-system messages until the session is under the limit; ensure
these limits are enforced atomically under the Store's mutex where
Store.sessions is mutated and reference the NewStore, Store, Session,
LastActive, sessions map, and any message-append function to locate and change
the code.
🪄 Autofix (Beta)

Fix all unresolved CodeRabbit comments on this PR:

  • Push a commit to this branch (recommended)
  • Create a new PR with the fixes

ℹ️ Review info
⚙️ Run configuration

Configuration used: Organization UI

Review profile: CHILL

Plan: Enterprise

Run ID: 3ed96045-0e68-4eb0-abcb-76541470ac6f

📥 Commits

Reviewing files that changed from the base of the PR and between 9d5794a and 0e2061b.

📒 Files selected for processing (8)
  • CLAUDE.md
  • docs/superpowers/specs/2026-05-04-server-side-sessions-design.md
  • internal/bridge/client.go
  • internal/bridge/executor.go
  • internal/chat/model.go
  • internal/cmd/serve.go
  • internal/session/store.go
  • internal/session/store_test.go

Comment thread internal/bridge/executor.go Resolved
Comment thread internal/session/store.go Resolved
Comment thread internal/session/store.go
Comment on lines +67 to +77
func (s *Store) Append(id string, msg llm.Message) {
s.mu.Lock()
defer s.mu.Unlock()

sess, ok := s.sessions[id]
if !ok {
return
}
sess.Messages = append(sess.Messages, msg)
sess.LastActive = time.Now()
}

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

⚠️ Potential issue | 🟡 Minor | ⚡ Quick win

Append silently drops the message when the session was reaped.

If the reaper deletes a session between GetOrCreate and the post-LLM Append("assistant", …) call (executor.go:126), the assistant turn is lost without any signal to the caller. At minimum, log a warning so this state is observable; ideally return a bool/error so callers can decide to recreate.

📝 Suggested handling
 func (s *Store) Append(id string, msg llm.Message) {
 	s.mu.Lock()
 	defer s.mu.Unlock()

 	sess, ok := s.sessions[id]
 	if !ok {
+		slog.Warn("append to missing session", "session_id", id, "role", msg.Role)
 		return
 	}
 	sess.Messages = append(sess.Messages, msg)
 	sess.LastActive = time.Now()
 }
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
func (s *Store) Append(id string, msg llm.Message) {
s.mu.Lock()
defer s.mu.Unlock()
sess, ok := s.sessions[id]
if !ok {
return
}
sess.Messages = append(sess.Messages, msg)
sess.LastActive = time.Now()
}
func (s *Store) Append(id string, msg llm.Message) {
s.mu.Lock()
defer s.mu.Unlock()
sess, ok := s.sessions[id]
if !ok {
slog.Warn("append to missing session", "session_id", id, "role", msg.Role)
return
}
sess.Messages = append(sess.Messages, msg)
sess.LastActive = time.Now()
}
🤖 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 `@internal/session/store.go` around lines 67 - 77, The Append method on Store
silently drops messages if the session was reaped; update Store.Append to return
an error or bool indicating success (e.g., (bool, error)) instead of void and
log a warning when the session id is missing, so callers like the code path that
calls Append after GetOrCreate (executor.go:126) can detect failure and recreate
the session; modify the Append signature and all callers to handle the returned
value, log a descriptive warning via the existing logger when sess not found,
and consider propagating an error type such as ErrSessionNotFound for callers to
react to.

- Add AppendAndSnapshot method that appends + copies under the lock,
  preventing race between concurrent reads and writes on sess.Messages
- Executor uses AppendAndSnapshot instead of reading live session pointer
- Add concurrent race test (50 goroutines × 100 ops, passes -race)
- Add AppendAndSnapshot unit tests including snapshot isolation
- Update design doc tables to match x-session-id implementation
- Fix unlabelled markdown code fence (MD040)

Assisted-By: Claude (Anthropic AI) <[email protected]>
Signed-off-by: Pavel Anni <[email protected]>
@pavelanni
pavelanni merged commit f494ebd into main May 5, 2026
3 checks passed
@pavelanni
pavelanni deleted the feature/server-side-sessions branch May 5, 2026 01:18
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.

Memory and context persistence

1 participant