-
Notifications
You must be signed in to change notification settings - Fork 0
Session management #396
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
jzgom067
wants to merge
21
commits into
v0.5.0
Choose a base branch
from
session-management
base: v0.5.0
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
Session management #396
Changes from all commits
Commits
Show all changes
21 commits
Select commit
Hold shift + click to select a range
96755ac
Move security submenu to client page
jzgom067 0045c36
Add created_at to session data
jzgom067 2a83415
Create formatTimeAgo function
jzgom067 6bf3c2d
Add basic session data to security submenu
jzgom067 83ffb90
Move security submenu back to server page
jzgom067 be64815
Update subtitle
jzgom067 e292563
Update active sessions endpoint return type
jzgom067 ce2c5a9
Update session data and display
jzgom067 b067a8c
Lighten accent on current session
jzgom067 b1a6906
Add device type value typing
jzgom067 2e1b675
Add collapsible session information
jzgom067 28cb62f
Add tablet device icon
jzgom067 845652c
Clean up layout and imports
jzgom067 574bfe5
Add cursor pointer to collapsible trigger
jzgom067 ca04e46
Move created at conversion logic
jzgom067 0b5db4a
Add session removal
jzgom067 73e7ee6
Add updating last used timestamps
jzgom067 0812706
Change remove session to TypeScript file
jzgom067 fbd7520
Add session pruning
jzgom067 0155de9
Add empty other sessions layout
jzgom067 94acaec
Remove accidental whitespace
jzgom067 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
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
302 changes: 302 additions & 0 deletions
302
frontend/src/features/account/settings/security/components/session-manager.tsx
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,302 @@ | ||
| "use client"; | ||
|
|
||
| import { | ||
| startTransition, | ||
| useEffect, | ||
| useOptimistic, | ||
| useRef, | ||
| useState, | ||
| } from "react"; | ||
|
|
||
| import * as Collapsible from "@radix-ui/react-collapsible"; | ||
| import { toZonedTime } from "date-fns-tz"; | ||
| import { | ||
| ChevronDownIcon, | ||
| CircleQuestionMark, | ||
| Laptop2Icon, | ||
| SmartphoneIcon, | ||
| TabletIcon, | ||
| } from "lucide-react"; | ||
|
|
||
| import { pruneSessions } from "@/features/account/settings/security/prune-sessions"; | ||
| import { removeSession } from "@/features/account/settings/security/remove-session"; | ||
| import ActionButton from "@/features/button/components/action"; | ||
| import { ConfirmationDialog, useToast } from "@/features/system-feedback"; | ||
| import { MESSAGES } from "@/lib/messages"; | ||
| import { ActiveSessionList, type ActiveSession } from "@/lib/utils/api/types"; | ||
| import { cn } from "@/lib/utils/classname"; | ||
| import { formatTimeAgo } from "@/lib/utils/date-time-format"; | ||
|
|
||
| type SessionAction = { type: "remove"; publicId: string } | { type: "prune" }; | ||
|
|
||
| export default function SessionManager({ | ||
| sessions, | ||
| }: { | ||
| sessions: ActiveSessionList; | ||
| }) { | ||
| const [now, setNow] = useState(Date.now()); | ||
| // This updates the "last used" timestamps every minute | ||
| useEffect(() => { | ||
| const interval = setInterval(() => { | ||
| setNow(Date.now()); | ||
| }, 60000); // Update every minute | ||
| return () => clearInterval(interval); | ||
| }, []); | ||
|
|
||
| const userTimeZone = Intl.DateTimeFormat().resolvedOptions().timeZone; | ||
|
|
||
| const [optimisticSessions, setOptimisticSessions] = useOptimistic( | ||
| sessions, | ||
| (state, action: SessionAction) => { | ||
| switch (action.type) { | ||
| case "remove": | ||
| return { | ||
| current_session: state.current_session, | ||
| other_sessions: state.other_sessions.filter( | ||
| (s) => s.public_id !== action.publicId, | ||
| ), | ||
| }; | ||
| case "prune": | ||
| return { | ||
| current_session: state.current_session, | ||
| other_sessions: [], | ||
| }; | ||
| default: | ||
| return state; | ||
| } | ||
| }, | ||
| ); | ||
|
|
||
| const [pruneConfirmationOpen, setPruneConfirmationOpen] = useState(false); | ||
| const [removeConfirmationOpen, setRemoveConfirmationOpen] = useState(false); | ||
| const sessionToRemove = useRef<string | null>(null); | ||
| const { addToast } = useToast(); | ||
|
|
||
| const handlePruneSessions = async () => { | ||
| // Immediate UI update | ||
| startTransition(() => { | ||
| setOptimisticSessions({ type: "prune" }); | ||
| }); | ||
|
|
||
| // Server Action | ||
| const result = await pruneSessions(); | ||
|
|
||
| if (!result.success) { | ||
| addToast("error", result.error || MESSAGES.ERROR_GENERIC); | ||
| } else { | ||
| addToast("success", MESSAGES.SUCCESS_SESSION_PRUNE); | ||
| } | ||
| }; | ||
|
|
||
| const handleRemoveSession = async (publicId: string) => { | ||
| // Immediate UI update | ||
| startTransition(() => { | ||
| setOptimisticSessions({ type: "remove", publicId }); | ||
| }); | ||
|
|
||
| // Server Action | ||
| const result = await removeSession(publicId); | ||
|
|
||
| if (!result.success) { | ||
| addToast("error", result.error || MESSAGES.ERROR_GENERIC); | ||
| } else { | ||
| addToast("success", MESSAGES.SUCCESS_SESSION_REMOVE); | ||
| } | ||
| }; | ||
|
|
||
| const onRemoveSession = (publicId: string) => { | ||
| sessionToRemove.current = publicId; | ||
| setRemoveConfirmationOpen(true); | ||
| }; | ||
|
|
||
| return ( | ||
| <div className="bg-panel flex flex-col gap-4 rounded-3xl border-none p-6 md:p-8"> | ||
| <div> | ||
| <h2 className="text-lg font-bold">Active Sessions</h2> | ||
| <p className="mt-1 text-sm leading-tight opacity-75"> | ||
| These devices have access to your account. If there are any you don | ||
| {"'"}t recognize, remove them and change your password. | ||
| </p> | ||
| </div> | ||
|
|
||
| <Session | ||
| session={optimisticSessions.current_session} | ||
| now={now} | ||
| userTz={userTimeZone} | ||
| /> | ||
| <div className="bg-foreground/10 h-px w-full" /> | ||
| {optimisticSessions.other_sessions.length > 0 ? ( | ||
| <> | ||
| <div className="flex flex-col gap-2"> | ||
| {optimisticSessions.other_sessions.map((session) => ( | ||
| <Session | ||
| key={session.public_id} | ||
| session={session} | ||
| now={now} | ||
| userTz={userTimeZone} | ||
| onRemove={() => { | ||
| onRemoveSession(session.public_id); | ||
| }} | ||
| /> | ||
| ))} | ||
| </div> | ||
|
|
||
| <ActionButton | ||
| buttonStyle="danger" | ||
| label="Remove All Other Sessions" | ||
| className="mx-auto w-fit" | ||
| onClick={() => { | ||
| setPruneConfirmationOpen(true); | ||
| }} | ||
| /> | ||
| </> | ||
| ) : ( | ||
| <p className="text-center text-sm opacity-75"> | ||
| No other active sessions. | ||
| </p> | ||
| )} | ||
|
|
||
| <ConfirmationDialog | ||
| type="delete" | ||
| autoClose={true} | ||
| title="Remove Session" | ||
| description="Are you sure you want to log out of this device?" | ||
| open={removeConfirmationOpen} | ||
| onOpenChange={setRemoveConfirmationOpen} | ||
| onConfirm={() => { | ||
| if (!sessionToRemove.current) return false; | ||
| handleRemoveSession(sessionToRemove.current); | ||
| return true; | ||
| }} | ||
| /> | ||
| <ConfirmationDialog | ||
| type="delete" | ||
| autoClose={true} | ||
| title="Remove All Other Sessions" | ||
| description="Are you sure you want to log out of all other devices? You will remain logged in here." | ||
| open={pruneConfirmationOpen} | ||
| onOpenChange={setPruneConfirmationOpen} | ||
| onConfirm={() => { | ||
| handlePruneSessions(); | ||
| return true; | ||
| }} | ||
| /> | ||
| </div> | ||
| ); | ||
| } | ||
|
|
||
| function Session({ | ||
| session, | ||
| now, | ||
| userTz, | ||
| onRemove, | ||
| }: { | ||
| session: ActiveSession; | ||
| now: number; | ||
| userTz: string; | ||
| onRemove?: () => void; | ||
| }) { | ||
| const [isOpen, setIsOpen] = useState(false); | ||
|
|
||
| const lastUsedLocal = toZonedTime(new Date(session.last_used + "Z"), userTz); | ||
| const lastUsedSecondsAgo = (now - lastUsedLocal.getTime()) / 1000; | ||
|
|
||
| const createdAtLocal = toZonedTime( | ||
| new Date(session.created_at + "Z"), | ||
| userTz, | ||
| ); | ||
|
|
||
| return ( | ||
| <div className="bg-background w-full rounded-3xl p-2"> | ||
| <Collapsible.Root open={isOpen} onOpenChange={setIsOpen}> | ||
| <Collapsible.Trigger | ||
| className={ | ||
| "group flex w-full cursor-pointer justify-between gap-2 text-left" | ||
| } | ||
| > | ||
| <div className="flex gap-2"> | ||
| <div | ||
| className={cn( | ||
| "bg-panel h-fit rounded-full p-2", | ||
| session.is_current && "bg-accent/50 text-accent-text", | ||
| )} | ||
| > | ||
| {session.device_type === "desktop" ? ( | ||
| <Laptop2Icon className="h-5 w-5" /> | ||
| ) : session.device_type === "smartphone" ? ( | ||
| <SmartphoneIcon className="h-5 w-5" /> | ||
| ) : session.device_type === "tablet" ? ( | ||
| <TabletIcon className="h-5 w-5" /> | ||
| ) : ( | ||
| <CircleQuestionMark className="h-5 w-5" /> | ||
| )} | ||
| </div> | ||
|
|
||
| <div className="flex flex-col items-start justify-between"> | ||
| <div className="text-sm font-semibold"> | ||
| {!session.os_name && !session.client_name | ||
| ? "Unknown" | ||
| : (session.os_name || "Unknown Device") + | ||
| " • " + | ||
| (session.client_name || "Unknown Browser")} | ||
| </div> | ||
| <div className="text-xs opacity-75"> | ||
| {session.is_current | ||
| ? "This Session" | ||
| : `Last used ${formatTimeAgo(lastUsedSecondsAgo)}`} | ||
| </div> | ||
| </div> | ||
| </div> | ||
| <div | ||
| className={cn( | ||
| "group-hover:bg-accent/25 group-active:bg-accent/40", | ||
| "m-1 h-fit rounded-full p-1", | ||
| )} | ||
| > | ||
| <div | ||
| className={cn( | ||
| "transition-transform duration-200", | ||
| isOpen && "rotate-x-180", | ||
| )} | ||
| > | ||
| <ChevronDownIcon className="h-5 w-5" /> | ||
| </div> | ||
| </div> | ||
| </Collapsible.Trigger> | ||
| <Collapsible.Content className="collapsible-content"> | ||
| <div className="mt-2 flex flex-col gap-2 pl-2 md:flex-row md:items-end md:justify-between"> | ||
| <div className="text-sm"> | ||
| {session.os_name && session.os_version && ( | ||
| <p> | ||
| {session.os_name} {session.os_version} | ||
| </p> | ||
| )} | ||
| {session.client_name && session.client_version && ( | ||
| <p> | ||
| {session.client_name} {session.client_version} | ||
| </p> | ||
| )} | ||
| <p className="opacity-75"> | ||
| Logged in on{" "} | ||
| {createdAtLocal.toLocaleString(undefined, { | ||
| month: "short", | ||
| day: "numeric", | ||
| hour: "numeric", | ||
| minute: "numeric", | ||
| })} | ||
| </p> | ||
| </div> | ||
| {onRemove && ( | ||
| <ActionButton | ||
| buttonStyle="danger" | ||
| label="Remove" | ||
| className="mx-auto w-fit md:mx-0" | ||
| onClick={onRemove} | ||
| /> | ||
| )} | ||
| </div> | ||
| </Collapsible.Content> | ||
| </Collapsible.Root> | ||
| </div> | ||
| ); | ||
| } | ||
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.
Uh oh!
There was an error while loading. Please reload this page.
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.
🎯 Functional Correctness | 🟡 Minor | ⚡ Quick win
🧩 Analysis chain
🏁 Script executed:
Repository: plan-cake/plancake
Length of output: 2744
🏁 Script executed:
Repository: plan-cake/plancake
Length of output: 21504
🌐 Web query:
React useOptimistic startTransition async action optimistic state pending official documentation💡 Result:
According to the official React documentation, the useOptimistic hook is designed to show a temporary state while an asynchronous Action is in progress [1][2]. It works by returning an optimistic value that is rendered while a Transition is active [3]. To use useOptimistic with an async action: 1. Call the setter function returned by useOptimistic (often named something like addOptimistic or setOptimistic) inside a Transition [1][4]. 2. A Transition is created by wrapping the update in startTransition or by using a form Action [1][5]. 3. When the setter is called inside this Transition, React immediately re-renders the UI to display the optimistic state [2][3]. 4. The Transition remains "pending" until the async action (e.g., a network request) completes [5][3]. 5. Once the action settles, React automatically reconciles the state. If the parent state updates, the optimistic layer is discarded; if the action fails or the state does not change, the optimistic state is dropped, and the UI reverts to the last confirmed state [3]. Crucially, you must call the optimistic setter function inside a transition [1][4]. If you call it outside of one, React will issue a warning, and the optimistic state will not persist correctly [1][2][4]. When performing async work inside startTransition, ensure any state updates scheduled after an await are wrapped in their own startTransition, as this is currently required by React to ensure they are treated as part of the Transition [6][5][7]. For tracking whether the transition is ongoing, you can use the isPending boolean provided by the useTransition hook, which remains true from the start of the transition until all associated actions are completed [5][2][7]. Top results: [1], [6], [5], [4], [3]
Citations:
🏁 Script executed:
Repository: plan-cake/plancake
Length of output: 43277
🏁 Script executed:
Repository: plan-cake/plancake
Length of output: 50374
🏁 Script executed:
Repository: plan-cake/plancake
Length of output: 9016
🌐 Web query:
Django REST framework DateTimeField ISO-8601 representation naive datetime USE_TZ False trailing Z official documentation source💡 Result:
In Django REST framework, the ISO-8601 representation of a
DateTimeFieldis controlled by theto_representationmethod [1][2]. When the field'sformatis set to'iso-8601'(which is the default) [3][4], the DRF implementation converts the datetime object to an ISO-8601 string [1][2]. Regarding the trailing 'Z': 1. The underlying implementation ofto_representationuses Python'sdatetime.isoformat()[1][2]. 2. If the datetime is UTC aware,isoformat()may return a string ending in+00:00. 3. To ensure a standard ISO-8601 representation, DRF explicitly checks for this and replaces the+00:00suffix withZ[5][1][2]. WhenUSE_TZis set toFalsein your Django settings, theDateTimeFielddefault behavior is to treat datetime objects as naive [3][6]. The field'senforce_timezonemethod ensures that whenUSE_TZisFalse, the default timezone isNone, resulting in naive datetimes being returned or processed [7][5]. Because these objects are naive, they do not have an offset, and consequently, theto_representationlogic—which specifically targets+00:00for theZreplacement—will not appendZto the output unless the object is explicitly made aware and set to UTC [1][2]. In summary, whenUSE_TZisFalse, your datetimes are naive and will be rendered byisoformat()without a timezone suffix, meaning no trailingZwill be added by the framework [1][2].Citations:
Keep each server mutation inside its transition.
The current synchronous transitions finish before
pruneSessions()andremoveSession()start. Wrap each mutation in anasyncstartTransitioncallback so the optimistic state remains active until the mutation completes.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.
@coderabbitai Could you clarify what you mean by this? This is the same logic flow we use in other areas of the site and it has no problem with everything functioning as intented. Unless, are we missing something and our optimistic transitions actually aren't working properly?
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.
🧩 Analysis chain
🏁 Script executed:
Length of output: 25552
@jzgom067, the current code does render the optimistic update. The problem is its lifetime.setOptimisticSessions()runs inside this synchronous transition:That transition completes when the callback returns.
pruneSessions()starts after the transition has completed. React therefore does not associate the pending server action with the optimistic update.As a result, the UI can show the removed session immediately, but React does not guarantee that the optimistic state remains active until
pruneSessions()orremoveSession()completes. If the confirmedsessionsprop has not updated yet, React can revert to that base state before the request completes. The server action’srevalidatePath()can then update the UI again after success. Fast requests can make this sequence appear correct in normal use.The dashboard and event-results code use the same pattern. This is a shared limitation, not evidence that this implementation is different.
For React 19, the transition should include both the optimistic update and the server mutation:
The same structure applies to
removeSession().I should have stated the concern more precisely. This is not a claim that the current UI always fails. It is a claim that the optimistic state is not tied to the pending mutation, so it is not reliable under latency or delayed revalidation.
You are interacting with an AI system.
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.
@coderabbitai I'm still not understanding. Isn't the point of the optimistic state to activate early, and stay active until revalidatePath is called?
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.
@jzgom067, no. I described that relationship incorrectly in the earlier reply.revalidatePath()does not keepuseOptimisticstate active.revalidatePath()runs on the server. It invalidates the cached route data. Next.js later sends updated route data to the client.useOptimisticis controlled by React on the client. React keeps its optimistic state for the Transition that containssetOptimisticSessions().The current code does this:
setOptimisticSessions().pruneSessions()orremoveSession().revalidatePath().Therefore, the optimistic state is not tied to Step 4 or Step 5.
The UI can still appear correct because the optimistic update renders immediately, and the server action usually returns quickly with refreshed data. However,
revalidatePath()is not the mechanism that preserves the optimistic state during that interval.The intended React 19 pattern is to put the server action in the same asynchronous Transition:
This makes the optimistic update and the pending server action one Transition. The same change applies to
handleRemoveSession().You are interacting with an AI system.
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.
@coderabbitai I'm talking with someone else, and they are explaining to me that keeping my code as is, only using startTransition for the optimistic state update is the correct way. This way, the server action isn't blocking the transition from finishing. The optimistic state is handled via useOptimistic on its own, it doesn't depend on startTransition. Am I still misunderstanding?
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.
@jzgom067, the other explanation is correct about one important part: an asyncstartTransition()does not block the UI while the server action runs.However,
useOptimisticdoes depend on an Action or Transition for its optimistic state lifetime. React requiressetOptimisticSessions()to run inside a Transition or Action. When the Transition ends, React can discard the optimistic layer unless a pending Action still owns it.Your current sequence is:
setOptimisticSessions().pruneSessions()orremoveSession()outside the Transition.This does render the optimistic UI immediately. The concern is that Step 3 occurs before the server action starts. React does not associate the pending server action with that optimistic update.
An async Transition has the required behavior without blocking the interface:
The UI stays responsive. React marks the Transition as pending while
pruneSessions()runs.useOptimisticcan then retain the optimistic state until the action settles and the refreshed server data becomes available.So, you are not misunderstanding the goal of optimistic UI. The disputed point is the Transition scope. Keeping only the optimistic setter in a synchronous Transition can appear to work for fast actions, but it does not connect the optimistic state to the server action. The async Transition is the React-supported pattern for this case.
You are interacting with an AI system.