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
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion apps/extension/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@
"name": "@getgrinta/extension",
"description": "Agentic web browsing with privacy in mind.",
"private": true,
"version": "1.0.0",
"version": "0.1.0",
"type": "module",
"scripts": {
"dev": "bun run build:rpc && vite",
Expand Down
4 changes: 3 additions & 1 deletion apps/extension/src/app.svelte
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,7 @@
import { onMessage, sendMessage } from "webext-bridge/popup";
import { ModeWatcher, systemPrefersMode } from "mode-watcher";
import { chatsStore } from "$lib/store/chats.svelte";
import { authStore } from "$lib/store/auth.svelte";

dayjs.extend(relativeTime);
dayjs.extend(localizedFormat);
Expand All @@ -44,8 +45,9 @@
});
requestStateUpdate();
const unsub = onMessage("grinta_fetchSession", () => {
window.location.reload();
authStore.fetchSession();
});
authStore.fetchSession();
return () => {
sessionStorage.unwatchAll();
unsub();
Expand Down
1 change: 0 additions & 1 deletion apps/extension/src/lib/components/space-essentials.svelte
8000
Original file line number Diff line number Diff line change
Expand Up @@ -27,7 +27,6 @@
state: DragDropState<{ index: number; type: string; id: number }>,
) {
const { draggedItem, targetContainer } = state;
console.log(">>>DRAGGED", draggedItem);
const dragIndex = draggedItem.index;
const dropIndex = Number(targetContainer ?? "0");
if (draggedItem.type === "essential") {
Expand Down
2 changes: 0 additions & 2 deletions apps/extension/src/lib/components/space-picker.svelte
Original file line number Diff line number Diff line change
Expand Up @@ -19,7 +19,6 @@
const { draggedItem, targetContainer } = state;
const dragIndex = parseInt(draggedItem.index);
const dropIndex = parseInt(targetContainer ?? "0");
console.log("DROP1", draggedItem, targetContainer);
if (draggedItem.type === "space") {
if (dragIndex === dropIndex) return;
await sendMessage(
Expand All @@ -32,7 +31,6 @@
);
}
if (draggedItem.type === "tab") {
console.log("DROP2", draggedItem, targetContainer);
const groupId = tabsStore.groups[dropIndex]?.id;
if (!groupId) return;
await sendMessage(
Expand Down
17 changes: 17 additions & 0 deletions apps/extension/src/lib/store/auth.svelte.ts
8000
Original file line number Diff line number Diff line change
@@ -0,0 +1,17 @@
import { authClient } from "$lib/auth";
import type { Session } from "better-auth";
import type { User } from "better-auth";

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

async fetchSession() {
const { data } = await authClient.getSession();
if (!data) return;
this.session = data.session;
this.user = data.user;
}
Comment on lines +9 to +14
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 ses 8000 sion 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.

}

export const authStore = new AuthStore();
11 changes: 7 additions & 4 deletions apps/extension/src/pages/chats.svelte
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,6 @@
import Layout from "$lib/components/layout.svelte";
import type { PageContext } from "$lib/types";
import { useRsv } from "@ryuz/rsv";
import { authClient } from "$lib/auth";
import ViewTitle from "$lib/components/view-title.svelte";
import { Chat } from "@ai-sdk/svelte";
import { type Attachment } from "ai";
Expand All @@ -22,6 +21,8 @@
import { tabs } from "webextension-polyfill";
import { Base64 } from "ox";
import { tabsStore } from "$lib/store/tabs.svelte";
import { onMount } from "svelte";
import { authStore } from "$lib/store/auth.svelte";

const router = useRsv();
let chatId = $derived(router?.getParam("id"));
Expand All @@ -35,8 +36,6 @@
tabsStore.currentTab?.url?.startsWith("chrome://"),
);
const lastChats = $derived(takeLast(3)(chatsStore.data.chats).reverse());
const session = authClient.useSession();
const user = $derived($session.data?.user);
const chatUrl = $derived(env.VITE_API_URL + "/api/ai/stream");
const chat = $derived(
new Chat({
Expand Down Expand Up @@ -279,9 +278,13 @@
chatsStore.setMessages(chatId, chat.messages);
},
);

onMount(() => {
authStore.fetchSession();
});
</script>

{#if !user}
{#if !authStore.user}
<dialog class="modal modal-open">
<div class="modal-box">
<h3 class="text-lg font-bold">GrintAI</h3>
Expand Down
11 changes: 5 additions & 6 deletions apps/extension/src/pages/home.svelte
Original file line number Diff line number Diff line change
Expand Up @@ -21,7 +21,7 @@
import ViewTitle from "$lib/components/view-title.svelte";
import SpaceColorPicker from "$lib/components/space-color-picker.svelte";
import pDebounce from "p-debounce";
import { authClient } from "$lib/auth";
import { authStore } from "$lib/store/auth.svelte";

const router = useRsv();
let mode = $state<"tabs" | "search" | "editing">("tabs");
Expand Down Expand Up @@ -53,7 +53,6 @@
}, 1);
}

const session = authClient.useSession();
const currentTab = $derived(tabsStore.tabs.find((tab) => tab.active));
const currentSpaceTitle = $derived(tabsStore.currentSpace?.title);
const currentSpaceEssentials = $derived(
Expand All @@ -64,7 +63,6 @@
(group) => group.id === tabsStore.currentSpaceId,
),
);
const user = $derived($session.data?.user);

const spaceTabs = $derived(
tabsStore.tabs.filter((tab) => tab.groupId === tabsStore.currentSpaceId),
Expand Down Expand Up @@ -250,6 +248,7 @@
{ wheel: { axis: "x" } },
);
document.body.addEventListener("keydown", handleShortcuts);
authStore.fetchSession();
return () => {
gesture.destroy();
document.body.removeEventListener("keydown", handleShortcuts);
Expand Down Expand Up @@ -314,15 +313,15 @@
</button>
<a
class="btn btn-ghost btn-sm btn-square"
href={user
href={authStore.user
? "https://getgrinta.com/account"
: "https://getgrinta.com/sign-in"}
target="_blank"
rel="noopener noreferrer"
>
{#if user}
{#if authStore.user}
<img
src={`https://meshy.studio/api/mesh/${user.id}?noise=8&sharpen=1&negate=false&gammaIn=2.1&gammaOut=2.2&brightness=100&saturation=100&hue=0&lightness=0&blur=0`}
src={`https://meshy.studio/api/mesh/${authStore.user.id}?noise=8&sharpen=1&negate=false&gammaIn=2.1&gammaOut=2.2&brightness=100&saturation=100&hue=0&lightness=0&blur=0`}
alt="Avatar"
class="w-6 rounded-full"
/>
Expand Down
29 changes: 29 additions & 0 deletions apps/extension/src/pages/settings.svelte
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
<script lang="ts">
import packageJson from "../../package.json";
import Layout from "$lib/components/layout.svelte";
import { appStore, THEME, type Theme } from "$lib/store/app.svelte";
import { tabsStore } from "$lib/store/tabs.svelte";
Expand Down Expand Up @@ -102,4 +103,32 @@
<p>Add site specific actions</p>
<button class="btn" disabled>Summarize</button>
</div>
<div class="flex flex-col gap-2 p-2">
<h2 class="text-lg font-semibold">About</h2>
<p>Version {packageJson.version}</p>
<a
class="link"
href="https://grnt.me/docs"
target="_blank"
rel="noopener noreferrer">Documentation</a
>
<a
class="link"
href="https://grnt.me/support"
target="_blank"
rel="noopener noreferrer">Support</a
>
<a
class="link"
href="https://getgrinta.com/privacy-policy"
target="_blank"
rel="noopener noreferrer">Privacy Policy</a
>
<a
class="link"
href="https://getgrinta.com/terms-of-service"
target="_blank"
rel="noopener noreferrer">Terms of Service</a
>
</div>
</Layout>
2 changes: 1 addition & 1 deletion apps/website/src/components/account-management.svelte
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,7 @@

async function signOut() {
await authClient.signOut();
return navigate("/");
return navigate("/?fetchSession=true");
}

async function upgradeToPro() {
Expand Down
12 changes: 12 additions & 0 deletions apps/website/src/components/download-grinta.svelte
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
<script lang="ts">
import packageJson from "../../../app/package.json";
import { onMount } from "svelte";

let version = $state(packageJson.version);
const downloadUrlAarch64 = $derived(
Expand All @@ -8,6 +9,17 @@
const downloadUrlX64 = $derived(
`https://github.com/getgrinta/grinta/releases/download/v${version}/Grinta_${version}_x64.dmg`,
);

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);
}
});
Comment on lines +13 to +22
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) {
    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.

</script>

<section
Expand Down
0