8000 chore(sidebar): handle session updates by yzuyr · Pull Request #116 · getgrinta/grinta · GitHub
[go: up one dir, main page]
More Web Proxy on the site http://driver.im/
Skip to content

chore(sidebar): handle session updates #116

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

Merged
merged 1 commit into from
May 23, 2025
Merged

Conversation

yzuyr
Copy link
Member
@yzuyr yzuyr commented May 23, 2025

Summary by CodeRabbit

  • New Features

    • Added an "About" section to the settings page, displaying the current app version and providing links to Documentation, Support, Privacy Policy, and Terms of Service.
  • Improvements

    • Updated authentication management across multiple pages to use a centralized authentication store for improved session handling.
    • Enhanced sign-out navigation to include a session refresh parameter in the URL.
    • Improved extension and website integration by triggering session fetches based on URL parameters.
  • Bug Fixes

    • Removed unnecessary debug console logs from drag-and-drop components for a cleaner user experience.

Copy link
8000
coderabbitai bot commented May 23, 2025

Walkthrough

This update introduces a centralized authentication store (AuthStore) to manage session and user state, replacing previous client-based session management across multiple components. It updates session-fetching logic, removes debug logging from drag-and-drop handlers, adds an "About" section to the settings page, and implements conditional session refresh logic based on URL parameters in the website components.

Changes

File(s) Change Summary
apps/extension/src/lib/store/auth.svelte.ts Introduced AuthStore class with session/user state and fetchSession(); exported singleton authStore.
apps/extension/src/app.svelte
apps/extension/src/pages/chats.svelte
apps/extension/src/pages/home.svelte
Refactored authentication logic to use authStore and fetchSession(); removed previous session management.
apps/extension/src/lib/components/space-essentials.svelte
apps/extension/src/lib/components/space-picker.svelte
Removed debug console.log statements from drag-and-drop event handlers.
apps/extension/src/pages/settings.svelte Added "About" section with app version and external links.
apps/extension/package.json Changed version from 1.0.0 to 0.1.0.
apps/website/src/components/account-management.svelte Updated sign-out redirect to include ?fetchSession=true query parameter.
apps/website/src/components/download-grinta.svelte Added onMount hook to trigger window.grinta.fetchSession() if URL has fetchSession parameter.

Sequence Diagram(s)

sequenceDiagram
    participant Component
    participant authStore
    participant authClient

    Component->>authStore: fetchSession()
    authStore->>authClient: getSession()
    authClient-->>authStore: { session, user }
    authStore-->>Component: Updates reactive session/user state
Loading
sequenceDiagram
    participant User
    participant Website
    participant Browser
    participant Extension

    User->>Website: Sign out
    Website->>Browser: Redirect to /?fetchSession=true
    Browser->>Extension: If fetchSession param, call window.grinta.fetchSession()
    Extension->>authStore: fetchSession()
Loading

Possibly related PRs

Poem

A hop, a skip, a session fetch anew,
The authStore’s here, with state in view!
Debug logs gone, the code feels light,
Settings shine with version bright.
When users sign out, the query’s true—
Grinta’s refreshed, for me and you!
🐇✨

✨ Finishing Touches
  • 📝 Generate Docstrings

🪧 Tips

Chat

There are 3 ways to chat with CodeRabbit:

  • Review comments: Directly reply to a review comment made by CodeRabbit. Example:
    • I pushed a fix in commit <commit_id>, please review it.
    • Explain this complex logic.
    • Open a follow-up GitHub issue for this discussion.
  • Files and specific lines of code (under the "Files changed" tab): Tag @coderabbitai in a new review comment at the desired location with your query. Examples:
    • @coderabbitai explain this code block.
    • @coderabbitai modularize this function.
  • PR comments: Tag @coderabbitai in a new PR comment to ask questions about the PR branch. For the best results, please provide a very specific query, as very limited context is provided in this mode. Examples:
    • @coderabbitai gather interesting stats about this repository and render them as a table. Additionally, render a pie chart showing the language distribution in the codebase.
    • @coderabbitai read src/utils.ts and explain its main purpose.
    • @coderabbitai read the files in the src/scheduler package and generate a class diagram using mermaid and a README in the markdown format.
    • @coderabbitai help me debug CodeRabbit configuration file.

Support

Need help? Create a ticket on our support page for assistance with any issues or questions.

Note: Be mindful of the bot's finite context window. It's strongly recommended to break down tasks such as reading entire modules into smaller chunks. For a focused discussion, use review comments to chat about specific files and their changes, instead of using the PR comments.

CodeRabbit Commands (Invoked using PR comments)

  • @coderabbitai pause to pause the reviews on a PR.
  • @coderabbitai resume to resume the paused reviews.
  • @coderabbitai review to trigger an incremental review. This is useful when automatic reviews are disabled for the repository.
  • @coderabbitai full review to do a full review from scratch and review all the files again.
  • @coderabbitai summary to regenerate the summary of the PR.
  • @coderabbitai generate docstrings to generate docstrings for this PR.
  • @coderabbitai generate sequence diagram to generate a sequence diagram of the changes in this PR.
  • @coderabbitai resolve resolve all the CodeRabbit review comments.
  • @coderabbitai configuration to show the current CodeRabbit configuration for the repository.
  • @coderabbitai help to get help.

Other keywords and placeholders

  • Add @coderabbitai ignore anywhere in the PR description to prevent this PR from being reviewed.
  • Add @coderabbitai summary to generate the high-level summary at a specific location in the PR description.
  • Add @coderabbitai anywhere in the PR title to generate the title automatically.

CodeRabbit Configuration File (.coderabbit.yaml)

  • You can programmatically configure CodeRabbit by adding a .coderabbit.yaml file to the root of your repository.
  • Please see the configuration documentation for more information.
  • If your editor has YAML language server enabled, you can add the path at the top of this file to enable auto-completion and validation: # yaml-language-server: $schema=https://coderabbit.ai/integrations/schema.v2.json

Documentation and Community

  • Visit our Documentation for detailed information on how to use CodeRabbit.
  • Join our Discord Community to get help, request features, and share feedback.
  • Follow us on X/Twitter for updates and announcements.

@yzuyr yzuyr merged commit 2dc042b into main May 23, 2025
3 of 4 checks passed
@yzuyr yzuyr deleted the chore/wave-session-management branch May 23, 2025 20:09
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: 2

🔭 Outside diff range comments (1)
apps/website/src/components/account-management.svelte (1)

40-49: ⚠️ Potential issue

Add safety checks and error handling.

The code calls window.grinta.fetchSession() without verifying that the grinta object and its fetchSession method exist, which could cause runtime errors.

Add proper safety checks and error handling:

 onMount(() => {
   if (typeof window === "undefined") return;
   const searchParams = new URLSearchParams(window.location.search);
   const fetchSession = searchParams.get("fetchSession");
   if (fetchSession) {
+    if (!window.grinta?.fetchSession) {
+      console.warn('window.grinta.fetchSession is not available');
+      return;
+    }
     setTimeout(() => {
+      try {
         window.grinta.fetchSession();
+      } catch (error) {
+        console.error('Failed to fetch session:', error);
+      }
     }, 1000);
   }
 });
🧹 Nitpick comments (5)
apps/extension/src/lib/store/auth.svelte.ts (1)

5-15: Consider adding loading state management.

The store lacks loading state management, which could lead to race conditions if fetchSession() is called multiple times before completion. Users may also benefit from knowing when session fetching is in progress.

Consider adding a loading state:

 export class AuthStore {
   session = $state<Session>();
   user = $state<User>();
+  loading = $state<boolean>(false);

   async fetchSession() {
+    if (this.loading) return; // Prevent concurrent calls
+    this.loading = true;
     try {
       const { data } = await authClient.getSession();
       if (!data) return;
       this.session = data.session;
       this.user = data.user;
     } catch (error) {
       console.error('Failed to fetch session:', error);
       this.session = undefined;
       this.user = undefined;
+    } finally {
+      this.loading = false;
     }
   }
 }
apps/website/src/components/account-management.svelte (1)

45-47: Consider explaining the 1000ms delay.

The 1000ms timeout delay appears arbitrary. Consider adding a comment explaining why this delay is necessary, or making it configurable if the timing is critical for the session refresh flow.

Add a comment explaining the delay:

 setTimeout(() => {
   window.grinta.fetchSession();
-}, 1000);
+}, 1000); // Allow time for sign-out to complete before fetching new session
apps/extension/src/app.svelte (1)

47-50: Excellent improvement: Targeted session refresh over full reload.

Replacing window.location.reload() with authStore.fetchSession() is a much better approach as it only refreshes the session data without disrupting the entire application state. However, consider adding error handling around the fetchSession() calls.

Consider adding error handling:

const unsub = onMessage("grinta_fetchSession", () => {
-  authStore.fetchSession();
+  authStore.fetchSession().catch(console.error);
});
-authStore.fetchSession();
+authStore.fetchSession().catch(console.error);
apps/extension/src/pages/home.svelte (1)

251-251: Good initialization pattern with room for error handling.

Adding authStore.fetchSession() in onMount ensures proper session initialization. Consider adding error handling for robustness.

Consider adding error handling:

-authStore.fetchSession();
+authStore.fetchSession().catch(console.error);
apps/extension/src/pages/chats.svelte (1)

282-284: Good session initialization with error handling opportunity.

The onMount hook with authStore.fetchSession() ensures proper session initialization when the component mounts. This is consistent with the pattern used in other components.

Consider adding error handling for consistency:

onMount(() => {
- authStore.fetchSession();
+ authStore.fetchSession().catch(console.error);
});
📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between a40859b and 7cc327f.

📒 Files selected for processing (10)
  • apps/extension/package.json (1 hunks)
  • apps/extension/src/app.svelte (2 hunks)
  • apps/extension/src/lib/components/space-essentials.svelte (0 hunks)
  • apps/extension/src/lib/components/space-picker.svelte (0 hunks)
  • apps/extension/src/lib/store/auth.svelte.ts (1 hunks)
  • apps/extension/src/pages/chats.svelte (2 hunks)
  • apps/extension/src/pages/home.svelte (3 hunks)
  • apps/extension/src/pages/settings.svelte (2 hunks)
  • apps/website/src/components/account-management.svelte (1 hunks)
  • apps/website/src/components/download-grinta.svelte (2 hunks)
💤 Files with no reviewable changes (2)
  • apps/extension/src/lib/components/space-essentials.svelte
  • apps/extension/src/lib/components/space-picker.svelte
🔇 Additional comments (10)
apps/extension/package.json (1)

5-5: Verify the version downgrade is intentional.

The version was changed from "1.0.0" to "0.1.0", which is a significant downgrade. This could impact extension updates for existing users and may cause confusion.

Please confirm this version change is intentional and explain the reasoning. If this is a restructuring of the versioning scheme, consider documenting this change in a changelog or migration guide.

apps/extension/src/pages/settings.svelte (2)

2-2: LGTM: Clean import for version display.

Good approach to import the package.json directly to display the current version dynamically.


106-133: LGTM: Well-implemented About section.

The About section is well-implemented with:

  • Dynamic version display using the imported package.json
  • Proper security attributes on external links (target="_blank" and rel="noopener noreferrer")
  • Clean UI structure consistent with the rest of the component
apps/website/src/components/account-management.svelte (1)

17-17: LGTM: Clean integration with session fetching.

Good approach to use a query parameter to trigger session refresh after sign-out.

apps/extension/src/app.svelte (1)

21-21: LGTM: Good import addition for centralized auth store.

The import of authStore aligns with the migration to centralized authentication state management.

apps/extension/src/pages/home.svelte (2)

24-24: LGTM: Consistent migration to centralized auth store.

The import change from authClient to authStore aligns with the architectural refactor.


316-331: Excellent migration to direct store access.

The change from derived user variable to direct authStore.user access simplifies the code while maintaining the same conditional rendering logic. The user avatar URL construction and conditional rendering work correctly.

apps/website/src/components/download-grinta.svelte (1)

3-3: LGTM: Proper lifecycle import for new functionality.

The onMount import is necessary for the new session fetching logic.

apps/extension/src/pages/chats.svelte (2)

24-25: LGTM: Consistent authentication migration pattern.

The addition of onMount and migration from authClient to authStore follows the same pattern established in other components, ensuring consistency across the extension.


287-287: Perfect migration to direct store access.

The change from a derived user variable to direct authStore.user access in the conditional rendering simplifies the code while maintaining the same functionality. The sign-in modal will correctly show when the user is not authenticated.

Comment on lines +9 to +14
async fetchSession() {
const { data } = await authClient.getSession();
if (!data) return;
this.session = data.session;
this.user = data.user;
}
Copy link

Choose a reason for hiding this comment

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

⚠️ Potential issue

Add error handling to prevent unhandled exceptions.

The fetchSession method lacks error handling. If authClient.getSession() throws an exception, it will propagate unhandled, potentially crashing the application.

Add proper error handling:

 async fetchSession() {
+  try {
     const { data } = await authClient.getSession();
     if (!data) return;
     this.session = data.session;
     this.user = data.user;
+  } catch (error) {
+    console.error('Failed to fetch session:', error);
+    // Optionally reset session state on error
+    this.session = undefined;
+    this.user = undefined;
+  }
 }
📝 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
async fetchSession() {
const { data } = await authClient.getSession();
if (!data) return;
this.session = data.session;
this.user = data.user;
}
async fetchSession() {
try {
const { data } = await authClient.getSession();
if (!data) return;
this.session = data.session;
this.user = data.user;
} catch (error) {
console.error('Failed to fetch session:', error);
// Optionally reset session state on error
this.session = undefined;
this.user = undefined;
}
}
🤖 Prompt for AI Agents
In apps/extension/src/lib/store/auth.svelte.ts around lines 9 to 14, the
fetchSession method does not handle errors from the async call to
authClient.getSession(), which can cause unhandled exceptions. Wrap the await
call in a try-catch block to catch any exceptions, and handle errors
appropriately, such as logging the error or setting an error state, to prevent
the application from crashing.

Comment on lines +13 to +22
onMount(() => {
if (typeof window === "undefined") return;
const searchParams = new URLSearchParams(window.location.search);
const fetchSession = searchParams.get("fetchSession");
if (fetchSession) {
setTimeout(() => {
window.grinta.fetchSession();
}, 1000);
}
});
Copy link

Choose a reason for hiding this comment

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

💡 Verification agent

🧩 Analysis chain

Add type safety and error handling for robustness.

The conditional session fetching based on URL parameters is a good approach for cross-component coordination. However, there are a few concerns that should be addressed:

Apply this diff to improve type safety and error handling:

onMount(() => {
  if (typeof window === "undefined") return;
  const searchParams = new URLSearchParams(window.location.search);
  const fetchSession = searchParams.get("fetchSession");
  if (fetchSession) {

8000
    setTimeout(() => {
-     window.grinta.fetchSession();
+     if (window.grinta?.fetchSession) {
+       window.grinta.fetchSession().catch(console.error);
+     }
    }, 1000);
  }
});

The improvements include:

  1. Type safety: Check if window.grinta.fetchSession exists before calling
  2. Error handling: Add .catch() to handle potential promise rejections
  3. Optional chaining: Use ?. for safer property access

To verify the window.grinta interface is properly typed, run:


🏁 Script executed:

#!/bin/bash
# Description: Check for window.grinta type definitions
# Expected: Find type declarations for the grinta global object

rg -A 5 -B 5 "grinta.*fetchSession|window\.grinta" --type ts --type js

Length of output: 1706


Ensure robust, type-safe invocation of window.grinta.fetchSession

The extension injects a grinta.fetchSession async function, but without it present on every page and without a global type declaration, you risk runtime errors and TS compilation failures. Please apply the following fixes:

• In apps/website/src/components/download-grinta.svelte, guard and handle errors:

 onMount(() => {
   if (typeof window === "undefined") return;
   const searchParams = new URLSearchParams(window.location.search);
   const fetchSession = searchParams.get("fetchSession");
   if (fetchSession) {
     setTimeout(() => {
-      window.grinta.fetchSession();
+      // Only call if the extension has injected grinta.fetchSession
+      if (window.grinta?.fetchSession) {
+        window.grinta.fetchSession().catch(err => {
+          console.error("grinta.fetchSession failed:", err);
+        });
+      }
     }, 1000);
   }
 });

• Declare the global grinta interface so TS knows about it. Create apps/website/src/global.d.ts (or another .d.ts included by your tsconfig) with:

declare interface Window {
  grinta?: {
    /** Injected by the browser extension */
    fetchSession: () => Promise<void>;
  };
}

After adding that file, ensure your tsconfig.json includes src/global.d.ts under "include".
These changes cover optional chaining, promise‐rejection handling, and compile-time type safety.

🤖 Prompt for AI Agents
In apps/website/src/components/download-grinta.svelte around lines 13 to 22,
improve type safety and error handling by first checking if
window.grinta?.fetchSession exists before calling it, then invoke it with
optional chaining and add a .catch() block to handle any promise rejections.
Additionally, create a global type declaration file apps/website/src/global.d.ts
declaring the Window interface with an optional grinta object containing
fetchSession as a Promise-returning function, and ensure this file is included
in tsconfig.json to enable compile-time type safety.

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
0