Skip to content

Self-evolving Context Database for AI Agents. Unify Agent Memory, Knowledge RAG and Skills.

feat(sessions): sort session list by filesystem modTime (#2972)

Zayn Jarvis6f97624d8e7c
diff --git a/openviking/service/session_service.py b/openviking/service/session_service.py
index 806af8ffd..9a7991d68 100644
--- a/openviking/service/session_service.py
+++ b/openviking/service/session_service.py
@@ -203,6 +203,7 @@ class SessionService:
"session_id": name,
"uri": f"{session_base_uri}/{name}",
"is_dir": entry.get("isDir", False),
+ "mod_time": entry.get("modTime", ""),
}
except Exception:
logger.debug("Failed to list sessions", exc_info=True)
@@ -217,6 +218,7 @@ class SessionService:
"session_id": name,
"uri": entry.get("uri", f"viking://session/{name}"),
"is_dir": entry.get("isDir", False),
+ "mod_time": entry.get("modTime", ""),
}
except Exception:
logger.debug("Failed to list legacy sessions", exc_info=True)
diff --git a/web-studio/src/components/app-shell.tsx b/web-studio/src/components/app-shell.tsx
index 3e225e83f..7fabcff54 100644
--- a/web-studio/src/components/app-shell.tsx
+++ b/web-studio/src/components/app-shell.tsx
@@ -51,7 +51,7 @@ import {
} from '#/hooks/use-app-connection'
import { cn } from '#/lib/utils'
import {
- useSessionList,
+ useSessionListByRecency,
useCreateSession,
useDeleteSession,
} from '#/lib/sessions/use-sessions'
@@ -209,7 +209,7 @@ function NavSessionsItem({
const isActive = pathname === '/sessions' || pathname.startsWith('/sessions/')
const [open, setOpen] = React.useState(isActive)
- const { data: sessions, isLoading } = useSessionList()
+ const { data: sessions, isLoading } = useSessionListByRecency()
const { getTitle } = useSessionTitles()
const createSession = useCreateSession()
const deleteSession = useDeleteSession()
@@ -250,11 +250,6 @@ function NavSessionsItem({
[deleteSession, activeSessionId, navigate],
)
- const reversedSessions = React.useMemo(
- () => (sessions ?? []).slice().reverse(),
- [sessions],
- )
-
return (
<Collapsible
open={open}
@@ -288,14 +283,14 @@ function NavSessionsItem({
</span>
</div>
</SidebarMenuSubItem>
- ) : reversedSessions.length === 0 ? (
+ ) : sessions.length === 0 ? (
<SidebarMenuSubItem>
<div className="px-2 py-1.5 text-xs text-muted-foreground">
{t('sidebar.noSessions', { ns: 'appShell' })}
</div>
</SidebarMenuSubItem>
) : (
- reversedSessions.map((s) => {
+ sessions.map((s) => {
const sessionTitle = getTitle(s.session_id)
const isSessionActive = activeSessionId === s.session_id
diff --git a/web-studio/src/lib/sessions/use-sessions.ts b/web-studio/src/lib/sessions/use-sessions.ts
index 63ad2b36c..94075134c 100644
--- a/web-studio/src/lib/sessions/use-sessions.ts
+++ b/web-studio/src/lib/sessions/use-sessions.ts
@@ -9,6 +9,7 @@ import {
fetchSessions,
} from './api'
import type { Message } from './types/message'
+import type { SessionListItem } from '@ov-server/api/v1/sessions'
const SESSIONS_KEY = ['sessions'] as const
const BOT_HEALTH_KEY = ['bot', 'health'] as const
@@ -30,6 +31,33 @@ export function useSessionList() {
})
}
+/**
+ * Session list ordered by recency (newest first).
+ *
+ * The list API returns sessions in name order. Each entry carries a
+ * `mod_time` (filesystem mtime of the session directory) from the backend,
+ * so we sort by that descending — no per-session detail requests needed.
+ * Sessions without a timestamp sort to the bottom.
+ */
+export function useSessionListByRecency() {
+ const { data: sessions, isLoading } = useSessionList()
+
+ if (!sessions) return { data: [] as SessionListItem[], isLoading }
+
+ const data = [...sessions].sort((a, b) => {
+ const aTime = a.mod_time || ''
+ const bTime = b.mod_time || ''
+ // Missing timestamps sort to bottom.
+ if (aTime === '' && bTime === '') return 0
+ if (aTime === '') return 1
+ if (bTime === '') return -1
+ // ISO-8601 UTC strings: lexicographic compare == chronological.
+ return bTime.localeCompare(aTime)
+ })
+
+ return { data, isLoading }
+}
+
export function useSession(sessionId: string | undefined) {
return useQuery({
queryKey: [...SESSIONS_KEY, sessionId],
diff --git a/web-studio/src/routes/playground/-components/agent-panel.tsx b/web-studio/src/routes/playground/-components/agent-panel.tsx
index 57b1f8e41..d0fc46981 100644
--- a/web-studio/src/routes/playground/-components/agent-panel.tsx
+++ b/web-studio/src/routes/playground/-components/agent-panel.tsx
@@ -19,11 +19,12 @@ import {
DialogTitle,
} from '#/components/ui/dialog'
import { cn } from '#/lib/utils'
+import { createRandomUuid } from '#/lib/browser-crypto'
import { useChat } from '#/lib/sessions/use-chat'
import {
useBotHealth,
useCreateSession,
- useSessionList,
+ useSessionListByRecency,
useSessionMessages,
} from '#/lib/sessions/use-sessions'
import {
@@ -51,53 +52,30 @@ export function AgentPanel({
onSessionChange: (sessionId: string) => void
}) {
const { t } = useTranslation('playground')
- const [sessionId, setSessionId] = useState(initialSessionId ?? '')
+ const [sessionId, setSessionId] = useState(
+ initialSessionId ?? createRandomUuid(),
+ )
const [historyOpen, setHistoryOpen] = useState(false)
const [sessionError, setSessionError] = useState<string | null>(null)
const [isCreatingSession, setIsCreatingSession] = useState(false)
const creationStartedRef = useRef(false)
const botHealth = useBotHealth()
const createSession = useCreateSession()
- const { data: sessions, isLoading: isLoadingSessions } = useSessionList()
+ const { data: sessions, isLoading: isLoadingSessions } =
+ useSessionListByRecency()
const { getTitle } = useSessionTitles()
const [playgroundSessionIds, setPlaygroundSessionIds] = useState<string[]>(
() => readPlaygroundAgentSessionIds(),
)
- const { data: historyMessages } = useSessionMessages(sessionId || undefined)
+ const { data: historyMessages } = useSessionMessages(sessionId)
const chat = useChat({
initialMessages: historyMessages,
- persistMessages: Boolean(sessionId),
- sessionId: sessionId || 'playground-preview',
+ persistMessages: true,
+ sessionId,
})
const scrollRef = useRef<HTMLDivElement>(null)
const bottomRef = useRef<HTMLDivElement>(null)
- const startSession = useCallback(async () => {
- if (sessionId || creationStartedRef.current) return
-
- creationStartedRef.current = true
- setIsCreatingSession(true)
- setSessionError(null)
-
- try {
- const result = await withTimeout(
- createSession.mutateAsync(undefined),
- 12_000,
- t('agent.createTimeout'),
- )
- setPlaygroundSessionIds(
- registerPlaygroundAgentSessionId(result.session_id),
- )
- setSessionId(result.session_id)
- onSessionChange(result.session_id)
- } catch (error) {
- creationStartedRef.current = false
- setSessionError(error instanceof Error ? error.message : String(error))
- } finally {
- setIsCreatingSession(false)
- }
- }, [createSession, onSessionChange, sessionId, t])
-
const handleNewSession = useCallback(async () => {
if (isCreatingSession) return
@@ -142,14 +120,13 @@ export function AgentPanel({
[chat, onSessionChange],
)
+ // Notify parent of the initial sessionId so the URL stays in sync.
+ // The session is lazily created on the backend by the first addMessage call.
useEffect(() => {
- // Only create a session once bot mode is confirmed available, otherwise we
- // leave orphan sessions behind and flash "creating" before the bot-mode
- // prompt.
- if (!sessionId && !sessionError && botHealth.isSuccess) {
- void startSession()
+ if (sessionId) {
+ onSessionChange(sessionId)
}
- }, [botHealth.isSuccess, sessionError, sessionId, startSession])
+ }, [])
useEffect(() => {
if (sessionId) {
@@ -175,8 +152,9 @@ export function AgentPanel({
const isStreaming = chat.status === 'streaming'
const botModeError = botHealth.isError ? getErrorMessage(botHealth.error) : ''
- const isCreating = !sessionId && isCreatingSession
const reversedSessions = useMemo(() => {
+ // `sessions` is already sorted by recency (newest first). Filter to
+ // sessions that were opened in this playground, preserving recency order.
const sessionById = new Map(
(sessions ?? []).map((session) => [session.session_id, session]),
)
@@ -229,12 +207,7 @@ export function AgentPanel({
ref={scrollRef}
className="min-h-0 flex-1 overflow-y-auto px-4 py-4"
>
- {isCreating ? (
- <div className="flex h-full items-center justify-center gap-2 text-sm text-muted-foreground">
- <Loader2Icon className="size-4 animate-spin" />
- {t('agent.creating')}
- </div>
- ) : botHealth.isLoading ? (
+ {botHealth.isLoading ? (
<div className="flex h-full items-center justify-center gap-2 text-sm text-muted-foreground">
<Loader2Icon className="size-4 animate-spin" />
{t('agent.detectingBot')}
@@ -254,7 +227,7 @@ export function AgentPanel({
className="w-fit"
onClick={() => {
setSessionError(null)
- void startSession()
+ void handleNewSession()
}}
>
{t('agent.retry')}
diff --git a/web-studio/src/routes/playground/-lib/utils.ts b/web-studio/src/routes/playground/-lib/utils.ts
index 614f31a94..da1189ab0 100644
--- a/web-studio/src/routes/playground/-lib/utils.ts
+++ b/web-studio/src/routes/playground/-lib/utils.ts
@@ -225,7 +225,13 @@ export function visibleContextEntries(
export function sortTreeEntries(entries: VikingFsEntry[]): VikingFsEntry[] {
return [...entries].sort((left, right) => {
+ // Directories first.
if (left.isDir !== right.isDir) return left.isDir ? -1 : 1
+ // Sort by modTime descending (newest first). Fall back to name when
+ // timestamps are missing or equal.
+ const leftTime = left.modTimestamp ?? 0
+ const rightTime = right.modTimestamp ?? 0
+ if (leftTime !== rightTime) return rightTime - leftTime
return left.name.localeCompare(right.name)
})
}
diff --git a/web-studio/types/ov-server/api/v1/sessions.ts b/web-studio/types/ov-server/api/v1/sessions.ts
index 4ac2151a6..8518e8766 100644
--- a/web-studio/types/ov-server/api/v1/sessions.ts
+++ b/web-studio/types/ov-server/api/v1/sessions.ts
@@ -12,6 +12,7 @@ export type TokenUsage = {
export type SessionListItem = {
is_dir: boolean
+ mod_time: string
session_id: string
uri: string
}