Skip to content

Session management - #396

Open
jzgom067 wants to merge 21 commits into
v0.5.0from
session-management
Open

Session management#396
jzgom067 wants to merge 21 commits into
v0.5.0from
session-management

Conversation

@jzgom067

Copy link
Copy Markdown
Member

This PR adds the ability to view and remove sessions on your account.

Session Management

In the "security" submenu of settings, the "Active Sessions" panel was added. It shows the current session at the top, with all other sessions listed below.

Each session is collapsible, showing more detailed information and an option to terminate it when expanded. All sessions can be terminated at once with the big button at the bottom.

Active Sessions Endpoint Changes

In implementing this on the frontend, I realized the endpoint could be returning more data and in a better format.

  • The endpoint now includes the "created at" date for each session.
  • The endpoint return type now has a separate field for the current session.

New Util Function

The formatTimeAgo function was created to display "time ago" in a convenient format. It outputs strings like:

  • "just now"
  • "14 minutes ago"
  • "3 hours ago"
  • "28 days ago"

@coderabbitai

coderabbitai Bot commented Aug 14, 2026

Copy link
Copy Markdown

Review Change Stack

Walkthrough

The backend now returns a required current_session and an other_sessions list with session timestamps. Frontend types match the new response shape. The security page fetches sessions server-side and renders SessionManager. New server actions remove one session or prune other sessions. The client interface shows session details, refreshes relative timestamps, and supports confirmed individual or bulk removal with optimistic updates and toast feedback.

Merge Risk: 🔵 Low · up to 0155d

The PR adds session viewing and termination, but a frontend type mismatch and premature completion of mutation pending state could cause type inconsistencies or misleading session-management UI. It is mergeable with explicit owner awareness and follow-up on these bounded issues.


Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ Share

Comment @coderabbitai help to get the list of available commands.

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

Actionable comments posted: 2


ℹ️ Review info
⚙️ Run configuration

Configuration used: Organization UI

Review profile: ASSERTIVE

Plan: Pro Plus

Run ID: cf1148aa-a30a-477d-82af-a1134c93f9b1

📥 Commits

Reviewing files that changed from the base of the PR and between 53ec3d7 and 0155de9.

📒 Files selected for processing (9)
  • backend/api/account/serializers.py
  • backend/api/account/views.py
  • frontend/src/app/settings/(submenus)/security/page.tsx
  • frontend/src/features/account/settings/security/components/session-manager.tsx
  • frontend/src/features/account/settings/security/prune-sessions.ts
  • frontend/src/features/account/settings/security/remove-session.ts
  • frontend/src/lib/messages.ts
  • frontend/src/lib/utils/api/types.ts
  • frontend/src/lib/utils/date-time-format.ts

Comment on lines +75 to +105
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);
}
};

@coderabbitai coderabbitai Bot Aug 14, 2026

Copy link
Copy Markdown

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:

#!/bin/bash
set -euo pipefail

rg -n -C 12 \
  'startTransition|setOptimisticSessions|await pruneSessions|await removeSession' \
  frontend/src/features/account/settings/security/components/session-manager.tsx

Repository: plan-cake/plancake

Length of output: 2744


🏁 Script executed:

#!/bin/bash
set -euo pipefail

printf '%s\n' '--- component structure and timestamp parsing ---'
sed -n '1,230p' frontend/src/features/account/settings/security/components/session-manager.tsx

printf '%s\n' '--- React and Next versions ---'
rg -n '"react"|"next"' frontend/package.json package.json 2>/dev/null || true

printf '%s\n' '--- session-manager callers and session data declarations ---'
rg -n -C 8 'SessionManager|interface Session|type Session|last_used|last_active|created_at' frontend/src/features/account frontend/src 2>/dev/null | head -n 240

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:

#!/bin/bash
set -euo pipefail

printf '%s\n' '--- session API and serializer definitions ---'
rg -n -C 12 \
  'ActiveSession|active.?sessions|last_used|created_at|DateTimeField|SessionSerializer' \
  --glob '!frontend/src/features/account/settings/security/components/session-manager.tsx' \
  --glob '!**/node_modules/**' . | head -n 320

printf '%s\n' '--- mutation implementations and refresh behavior ---'
sed -n '1,220p' frontend/src/features/account/settings/security/prune-sessions.ts
sed -n '1,220p' frontend/src/features/account/settings/security/remove-session.ts
rg -n -C 8 'revalidatePath|router.refresh|refresh\(' frontend/src/features/account/settings/security frontend/src | head -n 240

printf '%s\n' '--- deterministic source checks ---'
python3 - <<'PY'
from pathlib import Path
import re

p = Path("frontend/src/features/account/settings/security/components/session-manager.tsx")
s = p.read_text()

for name, pattern in {
    "prune optimistic transition": r"startTransition\(\(\) => \{\s*setOptimisticSessions\(\{ type: \"prune\" \}\);\s*\}\);\s*.*?await pruneSessions\(\)",
    "remove optimistic transition": r"startTransition\(\(\) => \{\s*setOptimisticSessions\(\{ type: \"remove\", publicId \}\);\s*\}\);\s*.*?await removeSession\(publicId\)",
    "last_used parser": r"new Date\(session\.last_used \+ \"Z\"\)",
    "created_at parser": r"new Date\(session\.created_at \+ \"Z\"\)",
}.items():
    print(f"{name}: {bool(re.search(pattern, s, re.S))}")

for field in ("last_used", "created_at"):
    print(f"{field} + Z parses:")
    for value in ("2026-08-01T12:34:56Z", "2026-08-01T12:34:56.123Z", "2026-08-01T12:34:56"):
        candidate = value + "Z"
        # ECMAScript Date parsing is checked as data here; report the resulting
        # ISO value where Python can parse the equivalent forms.
        valid = not bool(re.search(r"ZZ$", candidate))
        print(f"  {value!r} -> {candidate!r}; syntactic double-Z: {not valid}")
PY

Repository: plan-cake/plancake

Length of output: 43277


🏁 Script executed:

#!/bin/bash
set -euo pipefail

printf '%s\n' '--- backend file inventory for session code ---'
git ls-files | rg -i 'session|serializer|account' | head -n 240

printf '%s\n' '--- exact session endpoint references ---'
rg -n -C 20 \
  'active-sessions|terminate-session|prune-sessions|UserSession|user_session' \
  backend frontend --glob '!**/node_modules/**' | head -n 400

printf '%s\n' '--- Django datetime configuration and field definitions ---'
rg -n -C 8 \
  'DateTimeField|DateTimeNoTZField|USE_TZ|DATETIME_FORMAT|REST_FRAMEWORK|created_at|last_used' \
  backend --glob '*.py' | head -n 400

Repository: plan-cake/plancake

Length of output: 50374


🏁 Script executed:

#!/bin/bash
set -euo pipefail

printf '%s\n' '--- backend account serializers ---'
cat -n backend/api/account/serializers.py

printf '%s\n' '--- backend account views: session endpoints ---'
rg -n -C 35 \
  'def get_active_sessions|def terminate_session|def prune_sessions' \
  backend/api/account/views.py

printf '%s\n' '--- custom datetime field ---'
sed -n '1,35p' backend/api/models.py

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 DateTimeField is controlled by the to_representation method [1][2]. When the field's format is 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 of to_representation uses Python's datetime.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:00 suffix with Z [5][1][2]. When USE_TZ is set to False in your Django settings, the DateTimeField default behavior is to treat datetime objects as naive [3][6]. The field's enforce_timezone method ensures that when USE_TZ is False, the default timezone is None, resulting in naive datetimes being returned or processed [7][5]. Because these objects are naive, they do not have an offset, and consequently, the to_representation logic—which specifically targets +00:00 for the Z replacement—will not append Z to the output unless the object is explicitly made aware and set to UTC [1][2]. In summary, when USE_TZ is False, your datetimes are naive and will be rendered by isoformat() without a timezone suffix, meaning no trailing Z will be added by the framework [1][2].

Citations:


Keep each server mutation inside its transition.

The current synchronous transitions finish before pruneSessions() and removeSession() start. Wrap each mutation in an async startTransition callback so the optimistic state remains active until the mutation completes.

Copy link
Copy Markdown
Member Author

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?

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

🧩 Analysis chain

🏁 Script executed:

#!/bin/bash
set -euo pipefail

printf '%s\n' '--- React versions ---'
rg -n -C 2 '"react"|"react-dom"|next' frontend/package.json package.json 2>/dev/null || true

printf '%s\n' '--- session manager relevant sections ---'
sed -n '32,135p' frontend/src/features/account/settings/security/components/session-manager.tsx

printf '%s\n' '--- useOptimistic usage with transitions and mutations ---'
rg -n -U -C 10 \
  'useOptimistic[\s\S]{0,220}startTransition|startTransition[\s\S]{0,220}(useOptimistic|await )' \
  frontend/src --glob '*.{ts,tsx}' || true

printf '%s\n' '--- direct optimistic setter and async server-action patterns ---'
rg -n -C 8 \
  'setOptimistic|addOptimistic|startTransition\s*\(\s*(async|\(\)\s*=>)' \
  frontend/src --glob '*.{ts,tsx}' || true

Length of output: 25552


@jzgom067, the current code does render the optimistic update. The problem is its lifetime.

setOptimisticSessions() runs inside this synchronous transition:

startTransition(() => {
  setOptimisticSessions({ type: "prune" });
});

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() or removeSession() completes. If the confirmed sessions prop has not updated yet, React can revert to that base state before the request completes. The server action’s revalidatePath() 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:

startTransition(async () => {
  setOptimisticSessions({ type: "prune" });

  const result = await pruneSessions();

  if (!result.success) {
    addToast("error", result.error || MESSAGES.ERROR_GENERIC);
  } else {
    addToast("success", MESSAGES.SUCCESS_SESSION_PRUNE);
  }
});

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.

Copy link
Copy Markdown
Member Author

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?

Copy link
Copy Markdown

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 keep useOptimistic state active.

revalidatePath() runs on the server. It invalidates the cached route data. Next.js later sends updated route data to the client.

useOptimistic is controlled by React on the client. React keeps its optimistic state for the Transition that contains setOptimisticSessions().

The current code does this:

  1. Start a Transition.
  2. Call setOptimisticSessions().
  3. End the Transition.
  4. Call pruneSessions() or removeSession().
  5. The server action calls 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:

startTransition(async () => {
  setOptimisticSessions({ type: "prune" });

  const result = await pruneSessions();

  if (!result.success) {
    addToast("error", result.error || MESSAGES.ERROR_GENERIC);
  } else {
    addToast("success", MESSAGES.SUCCESS_SESSION_PRUNE);
  }
});

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.

Copy link
Copy Markdown
Member Author

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?

Copy link
Copy Markdown

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 async startTransition() does not block the UI while the server action runs.

However, useOptimistic does depend on an Action or Transition for its optimistic state lifetime. React requires setOptimisticSessions() 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:

  1. Start a synchronous Transition.
  2. Call setOptimisticSessions().
  3. End the Transition.
  4. Start pruneSessions() or removeSession() 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:

startTransition(async () => {
  setOptimisticSessions({ type: "prune" });

  const result = await pruneSessions();

  if (!result.success) {
    addToast("error", result.error || MESSAGES.ERROR_GENERIC);
  } else {
    addToast("success", MESSAGES.SUCCESS_SESSION_PRUNE);
  }
});

The UI stays responsive. React marks the Transition as pending while pruneSessions() runs. useOptimistic can 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.

Comment thread frontend/src/lib/utils/api/types.ts Outdated
@jzgom067
jzgom067 requested a review from mirmirmirr August 14, 2026 04:41
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