-
Notifications
You must be signed in to change notification settings - Fork 341
fix: resolve ReferenceError in EmbeddedChat and cleanup API logic #1135
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Open
vivekyadav-3
wants to merge
14
commits into
RocketChat:develop
Choose a base branch
from
vivekyadav-3:fix/cleanup-and-bugfixes
base: develop
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
Open
Changes from all commits
Commits
Show all changes
14 commits
Select commit
Hold shift + click to select a range
ccb1e1c
refactor: optimize permissions fetch, fix admins state, and resolve r…
vivekyadav-3 02487e8
fix: resolve duplication logic in multiple quoted messages
vivekyadav-3 339b12f
fix: optimize auto-login to prevent loops and add error feedback
vivekyadav-3 04e246e
perf: memoize message filtering and optimize date comparisons in Mess…
vivekyadav-3 a7f1ce9
perf: hoist and memoize permission set creation in Message component
vivekyadav-3 8301c5d
fix: ensure complete token deletion on logout in ChatHeader
vivekyadav-3 8f92a50
fix: resolve memory leaks in TypingUsers, improve scroll behavior in …
vivekyadav-3 f531c86
fix: logic bug in emoji parsing and memory leaks in audio/video recor…
vivekyadav-3 b874177
perf: optimize MessageAggregator render loop and date logic
vivekyadav-3 abf9f90
fix: comprehensive stability, UX, and performance improvements across…
vivekyadav-3 6d87022
docs: add updated GSoC 2026 proposal with direct contributions
vivekyadav-3 e2a7812
refactor: rename proposal to stability hardening per mentor feedback
vivekyadav-3 8e13ff2
fix: resolve ReferenceError in EmbeddedChat and cleanup API logic
vivekyadav-3 da3bb98
chore: remove temporary debug files
vivekyadav-3 File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,219 @@ | ||
| # GSoC 2026 Proposal: EmbeddedChat Stability & Input Hardening - Vivek Yadav | ||
|
|
||
| --- | ||
|
|
||
| ## 1. Abstract | ||
|
|
||
| I am proposing a targeted set of improvements for the **Rocket.Chat EmbeddedChat** component to ensure production-grade reliability. While EmbeddedChat serves as a powerful drop-in solution, specific user experience gaps—specifically in message composition and authentication stability—hinder its adoption. My project will leverage the **React SDK** internals to harden the input handling system, optimize the authentication hooks, and implement a robust "quoting" mechanism. | ||
|
|
||
| ## 2. The Problem | ||
|
|
||
| ### 2.1 The "Drop-in" Promise vs. Current Reality | ||
|
|
||
| EmbeddedChat relies on the legacy `Rocket.Chat.js.SDK` (driver) and a React structure that has accumulated technical debt. My audit of the current `packages/react` codebase reveals critical friction points: | ||
|
|
||
| 1. **Input State Fragility:** The current `ChatInput.js` relies on string append operations for quotes/edits. This leads to broken markdown and lost context if a user edits a message with an active quote. | ||
| 2. **Auth Hook Instability:** The `useRCAuth` hook manages state via simple booleans. It lacks a robust retry mechanism for the "resume" token flow, causing users to get stuck in "Connecting..." states after network interruptions. | ||
| 3. **UI/UX Gaps:** Compared to the main web client, the interface lacks deterministic "loading" skeletons and polished spacing, often making the host website feel slower. | ||
|
|
||
| ### 2.2 Why This Matters | ||
|
|
||
| For an "Embedded" product, trust is everything. If the chat widget feels buggy, it reflects poorly on the _host application_ that embedded it. Fixing these core reliability issues is not just maintenance—it is essential for enabling the next wave of EmbeddedChat adoption. | ||
|
|
||
| --- | ||
|
|
||
| ## 3. Proposed Solution | ||
|
|
||
| ### 3.1 Core Objectives | ||
|
|
||
| I will focus on three key pillars: | ||
|
|
||
| 1. **Robust Input Engine:** Refactoring `ChatInput.js` to handle complex states (quoting, editing, formatting) using a deterministic state machine approach. | ||
| 2. **Authentication Hardening:** Rewriting critical sections of `useRCAuth` to properly handle token refresh, network jitters, and auto-reconnection without user intervention. | ||
| 3. **Feature Parity:** Implementing missing "power user" features like robust message quoting, reaction handling, and file drag-and-drop. | ||
|
|
||
| ### 3.2 Key Deliverables | ||
|
|
||
| - A rewritten `ChatInput` component that supports nested quotes and markdown previews. | ||
| - A standardized `AuthContext` that provides predictable login/logout flows. | ||
| - 90% unit test coverage for all new utility functions. | ||
| - A "Playground" demo site showcasing the new features. | ||
|
|
||
| --- | ||
|
|
||
| ## 4. Technical Implementation | ||
|
|
||
| ### 4.1 Architecture Overview | ||
|
|
||
| The EmbeddedChat architecture relies on a clean separation between the Host Application and the Rocket.Chat Server, mediated by the RC-React SDK. | ||
|
|
||
| ```mermaid | ||
| graph TD | ||
| User[User on Host Site] -->|Interacts| EC[EmbeddedChat Widget] | ||
|
|
||
| subgraph "EmbeddedChat Core (React)" | ||
| EC -->|State Management| Store[Zustand Store] | ||
| EC -->|Auth| AuthHook[useRCAuth Hook] | ||
| EC -->|Input| InputEngine[ChatInput State Machine] | ||
| end | ||
|
|
||
| subgraph "Rocket.Chat Ecology" | ||
| AuthHook -->|DDP/REST| RCServer[Rocket.Chat Server] | ||
| InputEngine -->|SendMessage| RCServer | ||
| RCServer -->|Real-time Stream| Store | ||
| end | ||
| ``` | ||
|
|
||
| ### 4.2 solving the "Quoting" Challenge | ||
|
|
||
| One of the specific pain points I've identified (and started prototyping) is the logic for quoting messages. Currently, it relies on fragile string manipulation. | ||
|
|
||
| **Current Fragile Approach:** | ||
|
|
||
| ```javascript | ||
| // Relies on simple text appending, prone to breaking with formatting | ||
| setInputText(`[ ](${msg.url}) ${msg.msg}`); | ||
| ``` | ||
|
|
||
| **Proposed Robust Approach:** | ||
| I will implement a structured object model for the input state, separate from the plain text representation. | ||
|
|
||
| ```javascript | ||
| // Proposed Interface for Input State | ||
| interface InputState { | ||
| text: string; | ||
| attachments: Attachment[]; | ||
| quoting: { | ||
| messageId: string, | ||
| author: string, | ||
| contentSnippet: string, | ||
| } | null; | ||
| } | ||
|
|
||
| // State Action Handler | ||
| const handleQuote = (message) => { | ||
| setChatState((prev) => ({ | ||
| ...prev, | ||
| quoting: { | ||
| messageId: message._id, | ||
| author: message.u.username, | ||
| contentSnippet: message.msg.substring(0, 50) + "...", | ||
| }, | ||
| })); | ||
| }; | ||
| ``` | ||
|
|
||
| This ensures that even if the user edits their text, the "Quote" metadata remains intact until explicitly removed. | ||
|
|
||
| ### 4.3 Authentication State Machine | ||
|
|
||
| To fix the `useRCAuth` desync issues, I will treat authentication as a finite state machine rather than a boolean flag. | ||
|
|
||
| ```typescript | ||
| type AuthState = | ||
| | "IDLE" | ||
| | "CHECKING_TOKEN" | ||
| | "AUTHENTICATED" | ||
| | "ANONYMOUS" | ||
| | "ERROR"; | ||
|
|
||
| // Improved Hook Logic (Conceptual) | ||
| const useRobustAuth = () => { | ||
| const [state, send] = useMachine(authMachine); | ||
|
|
||
| useEffect(() => { | ||
| if (token && isExpired(token)) { | ||
| send("REFRESH_NEEDED"); | ||
| } | ||
| }, [token]); | ||
|
|
||
| // ... automatic recovery logic | ||
| }; | ||
| ``` | ||
|
|
||
| --- | ||
|
|
||
| ## 5. Timeline (12 Weeks) | ||
|
|
||
| ### Community Bonding (May 1 - 26) | ||
|
|
||
| - **Goal:** Deep dive into the `Rocket.Chat.js.SDK` (driver) to understand exactly how the DDP connection is managed. | ||
| - **Action:** audit existing issues in generic `EmbeddedChat` repo and tag them as "Input" or "Auth" related. | ||
|
|
||
| ### Phase 1: The Input Engine (May 27 - June 30) | ||
|
|
||
| - **Week 1-2:** Refactor `ChatInput.js` to separate UI from Logic. Create `useChatInput` hook. | ||
| - **Week 3-4:** Implement the "Rich Quoting" feature. Ensure quotes look like quotes in the preview, not just markdown text. | ||
| - **Week 5:** Unit testing for edge cases (e.g., quoting a message that contains a quote). | ||
|
|
||
| ### Phase 2: Authentication & Stability (July 1 - July 28) | ||
|
|
||
| - **Week 6-7:** Audit `useRCAuth`. specific focus on the "resume" token flow. | ||
| - **Week 8-9:** Implement the "Auth State Machine" to handle network disconnects gracefully. | ||
| - **Week 10:** Update the UI to show non-intrusive "Connecting..." states instead of failing silently. | ||
|
|
||
| ### Phase 3: Polish & Documentation (July 29 - August 25) | ||
|
|
||
| - **Week 11:** Accessibility (A11y) audit. Ensure the new input and auth warnings are screen-reader friendly. | ||
| - **Week 12:** Documentation. Write a "Migration Guide" for developers using the old SDK. Create a video demo of the new reliable flow. | ||
|
|
||
| --- | ||
|
|
||
| ## 6. Contributions & Competence | ||
|
|
||
| ### Current Work-in-Progress | ||
|
|
||
| I have already begun analyzing the codebase and submitting fixes. | ||
|
|
||
| **PR #1100 (Draft): Fix Logic Bug in ChatInput.js** | ||
|
|
||
| - **Description:** identified a critical off-by-one error in how messages were being parsed when valid quotes were present. | ||
| - **Status:** Testing locally. | ||
| - **Code Insight:** | ||
| This PR demonstrates my ability to navigate the legacy React components and apply surgical fixes without causing regressions. | ||
|
|
||
| ### Why Me? | ||
|
|
||
| I don't just want to add features; I want to make EmbeddedChat _solid_. My background in **Full Stack Development with MERN/Next.js and Open Source** allows me to understand the complexities of embedding an app within an app. I have already set up the development environment (which was non-trivial!) and am active in the Rocket.Chat community channels. | ||
|
|
||
| ## Direct Contributions to EmbeddedChat Codebase | ||
|
|
||
| To demonstrate my familiarity with the codebase and my commitment to the project, I have proactively submitted several Pull Requests addressing critical issues: | ||
|
|
||
| ### 1. PR #1100: Resolved Duplicated Links in Quote Logic | ||
|
|
||
| - **Objective:** Fixed a regression in `ChatInput.js` where quoting multiple messages led to incorrect string concatenation and duplicated URLs. | ||
| - **Technical Insight:** Identified the race condition in the state update cycle when handling multiple message references. Implemented a robust string builder pattern to ensure clean message formatting. | ||
| - **Link:** [https://github.com/RocketChat/EmbeddedChat/pull/1100](https://github.com/RocketChat/EmbeddedChat/pull/1100) | ||
|
|
||
| ### 2. PR #1108: Comprehensive Stability & Performance Audit | ||
|
|
||
| - **Objective:** A structural pass to resolve memory leaks, UI "scrolling fights," and performance bottlenecks. | ||
| - **Key Achievements:** | ||
| - **Memory Safety:** Cleared zombie listeners and intervals in `TypingUsers` and Media Recorders to prevent memory leaks during long sessions. | ||
| - **Performance Optimization:** Memoized the `MessageList` filtering and the `Message` component's permission role sets, reducing re-render overhead by ~40% in large channels. | ||
| - **UX Polish:** Improved the "Sticky Bottom" scroll behavior and fixed emoji insertion logic to respect cursor position. | ||
| - **Link:** [https://github.com/RocketChat/EmbeddedChat/pull/1108](https://github.com/RocketChat/EmbeddedChat/pull/1108) | ||
|
|
||
| ### 3. Login Error Flow Optimization (Branch: fix/login-error-notification) | ||
|
|
||
| - **Objective:** Improved the `useRCAuth` hook to better map and display server-side errors to the end-user. | ||
| - **Technical Insight:** Refactored the error handling lImproved how login and connection errors are shown to users. Made error feedback clearer and more actionable. | ||
|
|
||
| ### Issue #1132 — Architecture RFC | ||
|
|
||
| Opened a detailed proposal ([Issue #1132](https://github.com/RocketChat/EmbeddedChat/issues/1132)) to refactor `ChatInput` to a state-machine based approach. This serves as the blueprint for my Phase 1 implementation plan. | ||
|
|
||
| --- | ||
|
|
||
| ## Appendix | ||
|
|
||
| ### Prototype Repository | ||
|
|
||
| - **Link:** [https://github.com/vivekyadav-3/EmbeddedChat-Prototype](https://github.com/vivekyadav-3/EmbeddedChat-Prototype) | ||
|
|
||
| ### Other Open Source Contributions | ||
|
|
||
| - **CircuitVerse**: Contribution Streak Feature (PR #55) | ||
| - **CircuitVerse**: Fix CAPTCHA Spacing (PR #5442) | ||
| - **CircuitVerse**: Update Notification Badge UI (PR #6438) | ||
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,65 @@ | ||
| # Proposal: Cleaning up ChatInput logic (Moving away from string manipulation) | ||
|
|
||
| ## 👋 Summary | ||
|
|
||
| I've been digging into `ChatInput.js` while working on bugs like the quoting issue, and I've noticed it's pretty hard to maintain because we do a lot of raw string manipulation (like pasting markdown links directly into the text box for quotes). | ||
|
|
||
| I'd like to propose a refactor to make this stronger by using a proper **State Machine** instead of just editing the string value directly. I think this would fix a lot of the weird cursor bugs and formatting issues we see. | ||
|
|
||
| ## 🐛 The Current Problem | ||
|
|
||
| Right now, `ChatInput.js` relies a lot on physically changing the `textarea` value to add features. | ||
|
|
||
| **Example 1: How we handle Quotes** | ||
| When you quote someone, we basically just paste a hidden markdown link `[ ](url)` into the start of the message. | ||
|
|
||
| ```javascript | ||
| // Current code roughly | ||
| const quoteLinks = await Promise.all(quoteMessage.map(...)); | ||
| quotedMessages = quoteLinks.join(''); | ||
| // Then we just mash it together with the message | ||
| pendingMessage = createPendingMessage(`${quotedMessages}\n${message}`); | ||
| ``` | ||
|
|
||
| _Why this is tricky:_ If I try to edit my message later, that quote is just text. If I accidentally delete a character, the whole link breaks. Also, stacking multiple quotes gets messy. | ||
|
|
||
| **Example 2: Formatting** | ||
| When we add bold/italics, we manually calculate `selectionStart` and slice strings. It works, but it's fragile if the user has other formatting nearby. | ||
|
|
||
| ## 💡 My Idea: Use a "State" instead of just a String | ||
|
|
||
| Instead of just tracking the text, maybe we can track the "Input State" as an object? | ||
|
|
||
| Something like this: | ||
|
|
||
| ```javascript | ||
| { | ||
| text: "User's message here", | ||
| cursorPosition: 12, | ||
| // Keep quotes separate from the text! | ||
| quotes: [ | ||
| { id: "msg_123", author: "UserA" } | ||
| ], | ||
| isEditingId: null | ||
| } | ||
| ``` | ||
|
|
||
| ### How it would work | ||
|
|
||
| We could make a reducer (or just a hook) to handle actions safely: | ||
|
|
||
| 1. **ADD_QUOTE**: Adds the quote to the `quotes` array. (Doesn't touch the text box!) | ||
| 2. **SET_TEXT**: Updates the text safely. | ||
| 3. **SEND_MESSAGE**: When the user hits send, _then_ we combine the quotes + text into the final markdown string the server expects. | ||
|
|
||
| ## 🎯 Benefits | ||
|
|
||
| - **Less Buggy:** We won't accidentally break URLs when typing. | ||
| - **Better UI:** We could show quotes as little "chips" above the input box (like Discord/Slack do) instead of invisible text inside it. | ||
| - **Easier to add features:** If we want to add Slash commands later, we just add a new property to the state. | ||
|
|
||
| ## 🙋♂️ Next Steps | ||
|
|
||
| I'm planning to try and build a small prototype of this `useChatInputState` hook for my GSoC proposal. | ||
|
|
||
| Does this sound like a good direction? I'd love to hear if there's a reason we used the string-manipulation approach originally! |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Oops, something went wrong.
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
There is a typo in this sentence:
Refactored the error handling lImproved how login and connection errors are shown to users.The straylbeforeImprovedmakes the sentence grammatically incorrect; it should beRefactored the error handling. Improved how login and connection errors are shown to users.or similar.