Skip to content

feat: persist AI chat history to localStorage across page refreshes#307

Open
KaparthyReddy wants to merge 3 commits into
piyushdotcomm:mainfrom
KaparthyReddy:feat/persist-chat-history
Open

feat: persist AI chat history to localStorage across page refreshes#307
KaparthyReddy wants to merge 3 commits into
piyushdotcomm:mainfrom
KaparthyReddy:feat/persist-chat-history

Conversation

@KaparthyReddy
Copy link
Copy Markdown

@KaparthyReddy KaparthyReddy commented May 26, 2026

Summary

  • Added CHAT_HISTORY key to STORAGE_KEYS in lib/constants/config.ts
  • Added loadChatHistory() to load persisted messages on store initialization
  • Updated addMessage() to save chat history to localStorage on every new message
  • Updated clearChat() to remove chat history from localStorage on clear
  • Follows the exact same localStorage persistence pattern already used for API keys, editor theme, and inline suggestions in the same store

Previously, chatMessages was always initialized to [], meaning every page refresh wiped the entire AI conversation. This change ensures chat history survives refreshes and tab closes.

Type of change

  • Bug fix
  • New feature
  • Refactor
  • Documentation
  • Test or CI improvement
  • Starter template change

Related issue

Closes #265

Validation

  • npm run lint
  • npm test
  • npm run build

Manual verification performed:

  • lint: 0 errors, 25 pre-existing warnings (none in changed files)
  • test: 1 pre-existing failure in useAI.test.ts (localStorage mock missing in test environment, unrelated to this change), 65/65 tests passing
  • build: successful

Screenshots or recordings

No UI changes — this is a pure localStorage persistence fix in the Zustand store.

Checklist

  • I kept this PR focused on one primary change
  • I updated documentation if behavior changed
  • I did not commit secrets, local logs, or scratch files
  • I am requesting review on the correct scope

Summary by CodeRabbit

  • New Features
    • Chat history is now persisted in your browser and restored on return so conversations resume where you left off.
    • Chat can be cleared to remove saved history.
    • Persisted history is capped to the most recent 100 messages to limit storage growth.

Review Change Stack

- Add CHAT_HISTORY key to STORAGE_KEYS in lib/constants/config.ts
- Add loadChatHistory() to load persisted messages on store init
- Update addMessage() to save chat history to localStorage on every message
- Update clearChat() to remove chat history from localStorage on clear
- Follows the same localStorage persistence pattern used for API keys,
  editor theme, and inline suggestions in the same store
@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 →

@github-actions
Copy link
Copy Markdown

👋 Thanks for opening a PR, @KaparthyReddy!

Your PR has entered the 🚦 PR Review Pipeline.

Standard PR detected — your PR will follow the standard review pipeline.


What happens next

Stage Reviewer Checks
Stage 1 — Automated Validation 🤖 Bot DCO · Format · AI/Slop · Duplicate
Stage 2 — Human Review 👥 Maintainer Code + Quality Review
Stage 3 — PA / Maintainer Review 🔑 Project Admin Final Merge Decision

A pipeline status comment will appear below and update automatically as your PR progresses.


While you wait

  • Sign all commits (git commit -s)
  • Link your issue (Closes #123)
  • Use a feature branch (not main)
  • Avoid unrelated changes

This comment is posted only once.

@github-actions github-actions Bot added the enhancement New feature or request label May 26, 2026
@coderabbitai
Copy link
Copy Markdown

coderabbitai Bot commented May 26, 2026

Warning

Review limit reached

@KaparthyReddy, we couldn't start this review because you've reached your PR review rate limit.

More reviews will be available in 15 minutes and 32 seconds. Learn how PR review limits work.

Your organization has run out of usage credits. Purchase more in the billing tab.

⌛ How to resolve this issue?

After more reviews become available, 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 include higher PR review limits than trial, open-source, and free plans. In all cases, reviews become available again over time. During sustained high-volume PR review activity, CodeRabbit may temporarily slow when the next review becomes available.

Please see our Fair Usage Limits Policy for further information.

ℹ️ Review info
⚙️ Run configuration

Configuration used: Path: .coderabbit.yaml

Review profile: CHILL

Plan: Pro Plus

Run ID: 3abbc72b-8aff-4f75-b2e9-1ac2e39e339e

📥 Commits

Reviewing files that changed from the base of the PR and between d0ee24d and 2d93314.

📒 Files selected for processing (1)
  • modules/playground/hooks/useAI.ts

Walkthrough

Adds a CHAT_HISTORY localStorage key and updates the useAI hook to load persisted chat messages on init, save the most recent 100 messages on addMessage, and remove persisted history on clearChat.

Changes

Chat History Persistence

Layer / File(s) Summary
Persistent chat history with localStorage
lib/constants/config.ts, modules/playground/hooks/useAI.ts
Storage key CHAT_HISTORY: "editron_chat_history" added. Introduces MAX_PERSISTED_MESSAGES and loadChatHistory() to safely parse stored messages. Hook initializes chatMessages from persisted data. addMessage persists capped recent messages; clearChat removes persisted history.

Estimated code review effort

🎯 3 (Moderate) | ⏱️ ~20 minutes

Possibly related PRs

Suggested labels

gssoc:approved, mentor:piyushdotcomm

Suggested reviewers

  • piyushdotcomm

Poem

🐰 I stash the chats where browsers keep their dreams,
So prompts and answers stay stitched at the seams.
On refresh they greet you, recent and bright,
A tail of tokens saved through the night.
Hooray—your convo hops back into sight!

🚥 Pre-merge checks | ✅ 4 | ❌ 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 0.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
Title check ✅ Passed The title accurately describes the main change: persisting AI chat history to localStorage across page refreshes.
Description check ✅ Passed The PR description is complete, addressing all template sections with clear context, validation results, and proper checklist completion.
Linked Issues check ✅ Passed All four coding objectives from issue #265 are met: CHAT_HISTORY key added, loadChatHistory() implemented, addMessage() persists data, clearChat() removes persisted data [#265].
Out of Scope Changes check ✅ Passed All changes are directly scoped to implementing localStorage persistence for chat history as specified in issue #265; no extraneous modifications detected.

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

✨ Finishing Touches
🧪 Generate unit tests (beta)
  • Create PR with unit tests

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
Copy Markdown

@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.

🧹 Nitpick comments (1)
modules/playground/hooks/useAI.ts (1)

94-104: ⚡ Quick win

Consider adding a size limit to prevent localStorage quota issues.

Chat history grows unbounded over time. Unlike API keys or theme settings (which are fixed-size), the chatMessages array will continuously grow with usage. This could eventually exceed localStorage quota limits (typically 5-10MB), causing persistence to silently fail.

♻️ Limit chat history to last N messages
                const updated = [...s.chatMessages, newMessage];
-                try { localStorage.setItem(STORAGE_KEYS.CHAT_HISTORY, JSON.stringify(updated)); } catch { }
+                const toStore = updated.slice(-100); // Keep last 100 messages
+                try { localStorage.setItem(STORAGE_KEYS.CHAT_HISTORY, JSON.stringify(toStore)); } catch { }
                return { chatMessages: updated };

This keeps the in-memory state complete while limiting persisted history to prevent quota issues.

🤖 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 `@modules/playground/hooks/useAI.ts` around lines 94 - 104, The addMessage
setter in useAI.ts currently persists the entire chatMessages array to
localStorage (STORAGE_KEYS.CHAT_HISTORY) which can grow without bound; modify
addMessage so it still appends newMessage to the in-memory s.chatMessages but
only writes a bounded tail (e.g., last N entries, configurable constant like
MAX_PERSISTED_MESSAGES) to localStorage—compute persistedArray =
updated.slice(-MAX_PERSISTED_MESSAGES) before JSON.stringify, keep the try/catch
around localStorage.setItem, and document/centralize MAX_PERSISTED_MESSAGES near
the hook so persistence quota is protected while in-memory state remains
complete.
🤖 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.

Nitpick comments:
In `@modules/playground/hooks/useAI.ts`:
- Around line 94-104: The addMessage setter in useAI.ts currently persists the
entire chatMessages array to localStorage (STORAGE_KEYS.CHAT_HISTORY) which can
grow without bound; modify addMessage so it still appends newMessage to the
in-memory s.chatMessages but only writes a bounded tail (e.g., last N entries,
configurable constant like MAX_PERSISTED_MESSAGES) to localStorage—compute
persistedArray = updated.slice(-MAX_PERSISTED_MESSAGES) before JSON.stringify,
keep the try/catch around localStorage.setItem, and document/centralize
MAX_PERSISTED_MESSAGES near the hook so persistence quota is protected while
in-memory state remains complete.

ℹ️ Review info
⚙️ Run configuration

Configuration used: Path: .coderabbit.yaml

Review profile: CHILL

Plan: Pro Plus

Run ID: e398d11e-0d63-4787-8ae9-95e3da913be0

📥 Commits

Reviewing files that changed from the base of the PR and between f12b223 and d398b17.

📒 Files selected for processing (2)
  • lib/constants/config.ts
  • modules/playground/hooks/useAI.ts

Copy link
Copy Markdown

@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.

Caution

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

⚠️ Outside diff range comments (1)
modules/playground/hooks/useAI.ts (1)

62-70: ⚠️ Potential issue | 🟠 Major | ⚡ Quick win

Validate and cap chat history on load to avoid runtime crashes.

loadChatHistory() currently trusts parsed JSON as ChatMessage[]. If localStorage contains non-array JSON, later addMessage can fail when spreading s.chatMessages. Also, read-side capping should match the new write cap.

Proposed fix
 function loadChatHistory(): ChatMessage[] {
     if (typeof window === "undefined") return [];
     try {
         const stored = localStorage.getItem(STORAGE_KEYS.CHAT_HISTORY);
-        return stored ? (JSON.parse(stored) as ChatMessage[]) : [];
+        if (!stored) return [];
+        const parsed: unknown = JSON.parse(stored);
+        if (!Array.isArray(parsed)) return [];
+        return (parsed as ChatMessage[]).slice(-MAX_PERSISTED_MESSAGES);
     } catch {
         return [];
     }
 }
🤖 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 `@modules/playground/hooks/useAI.ts` around lines 62 - 70, loadChatHistory
currently trusts parsed localStorage JSON as ChatMessage[] which can crash later
when addMessage spreads s.chatMessages; modify loadChatHistory to validate the
parsed value is an array of objects (and optionally validate minimal ChatMessage
shape), fall back to [] on malformed data, and trim the returned array to
MAX_PERSISTED_MESSAGES so read-side capping matches the write cap; reference the
STORAGE_KEYS.CHAT_HISTORY key, the loadChatHistory function, and
MAX_PERSISTED_MESSAGES constant when implementing these checks.
🤖 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.

Outside diff comments:
In `@modules/playground/hooks/useAI.ts`:
- Around line 62-70: loadChatHistory currently trusts parsed localStorage JSON
as ChatMessage[] which can crash later when addMessage spreads s.chatMessages;
modify loadChatHistory to validate the parsed value is an array of objects (and
optionally validate minimal ChatMessage shape), fall back to [] on malformed
data, and trim the returned array to MAX_PERSISTED_MESSAGES so read-side capping
matches the write cap; reference the STORAGE_KEYS.CHAT_HISTORY key, the
loadChatHistory function, and MAX_PERSISTED_MESSAGES constant when implementing
these checks.

ℹ️ Review info
⚙️ Run configuration

Configuration used: Path: .coderabbit.yaml

Review profile: CHILL

Plan: Pro Plus

Run ID: eccf4639-66b2-4e8a-8e67-3c2456824a8f

📥 Commits

Reviewing files that changed from the base of the PR and between d398b17 and d0ee24d.

📒 Files selected for processing (1)
  • modules/playground/hooks/useAI.ts

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

enhancement New feature or request

Projects

None yet

Development

Successfully merging this pull request may close these issues.

[Feature]: Persist AI chat history across page refreshes using localStorage

1 participant