From cdf7a1957ad6a5bd569f60fb7113c44973f4e2d7 Mon Sep 17 00:00:00 2001
From: dan <dan.abramov@gmail.com>
Date: Fri, 3 May 2024 03:47:11 +0100
Subject: [Session] Rely on agent session change event for persisting resumed
 session (#3836)

* Rely on agent session change handler for resumption

* Add a fast path for noop resumes
---
 src/state/session/index.tsx | 44 ++++++++++++--------------------------------
 1 file changed, 12 insertions(+), 32 deletions(-)

(limited to 'src/state/session/index.tsx')

diff --git a/src/state/session/index.tsx b/src/state/session/index.tsx
index b4799e2f7..b9d67f2e0 100644
--- a/src/state/session/index.tsx
+++ b/src/state/session/index.tsx
@@ -158,6 +158,18 @@ export function Provider({children}: React.PropsWithChildren<{}>) {
        * out.
        */
       setState(s => {
+        const existingAccount = s.accounts.find(
+          a => a.did === refreshedAccount.did,
+        )
+        if (
+          !expired &&
+          existingAccount &&
+          refreshedAccount &&
+          JSON.stringify(existingAccount) === JSON.stringify(refreshedAccount)
+        ) {
+          // Fast path without a state update.
+          return s
+        }
         return {
           accounts: [
             refreshedAccount,
@@ -379,38 +391,6 @@ export function Provider({children}: React.PropsWithChildren<{}>) {
 
         // Intentionally not awaited to unblock the UI:
         resumeSessionWithFreshAccount()
-          .then(freshAccount => {
-            if (JSON.stringify(account) !== JSON.stringify(freshAccount)) {
-              logger.info(
-                `session: reuse of previous session returned a fresh account, upserting`,
-              )
-              setState(s => {
-                return {
-                  accounts: [
-                    freshAccount,
-                    ...s.accounts.filter(a => a.did !== freshAccount.did),
-                  ],
-                  currentAgentState: {
-                    did: freshAccount.did,
-                    agent: agent,
-                  },
-                  needsPersist: true,
-                }
-              })
-            }
-          })
-          .catch(e => {
-            /*
-             * Note: `agent.persistSession` is also called when this fails, and
-             * we handle that failure via `createPersistSessionHandler`
-             */
-            logger.info(`session: resumeSessionWithFreshAccount failed`, {
-              message: e,
-            })
-
-            __globalAgent = PUBLIC_BSKY_AGENT
-            // TODO: This needs a setState.
-          })
       }
 
       async function resumeSessionWithFreshAccount(): Promise<SessionAccount> {
-- 
cgit 1.4.1

