Skip to content

The agent that grows with you

fix(sessions): prevent oversized transcripts from exhausting memory

kinsoleec750d5354aed
diff --git a/apps/desktop/src/app/artifacts/artifact-utils.ts b/apps/desktop/src/app/artifacts/artifact-utils.ts
index 730ec0e0016..48e4258904d 100644
--- a/apps/desktop/src/app/artifacts/artifact-utils.ts
+++ b/apps/desktop/src/app/artifacts/artifact-utils.ts
@@ -17,6 +17,16 @@ export interface ArtifactRecord {
timestamp: number
}
+export interface ArtifactLoadFailure {
+ error: unknown
+ session: SessionInfo
+}
+
+export interface ArtifactLoadResult {
+ artifacts: ArtifactRecord[]
+ failures: ArtifactLoadFailure[]
+}
+
const MARKDOWN_IMAGE_RE = /!\[([^\]]*)\]\(([^)\s]+)\)/g
const MARKDOWN_LINK_RE = /\[([^\]]+)\]\(([^)\s]+)\)/g
const URL_RE = /https?:\/\/[^\s<>"')]+/g
@@ -280,3 +290,25 @@ export function collectArtifactsForSession(session: SessionInfo, messages: Sessi
return Array.from(found.values())
}
+
+export async function loadArtifactsForSessions(
+ sessions: SessionInfo[],
+ loadMessages: (session: SessionInfo) => Promise<SessionMessage[]>
+): Promise<ArtifactLoadResult> {
+ const artifacts: ArtifactRecord[] = []
+ const failures: ArtifactLoadFailure[] = []
+
+ // Keep only one transcript resident at a time. Recent sessions can each be
+ // tens of megabytes, so loading the whole page concurrently can exhaust both
+ // the Desktop renderer and a remote dashboard backend.
+ for (const session of sessions) {
+ try {
+ const messages = await loadMessages(session)
+ artifacts.push(...collectArtifactsForSession(session, messages))
+ } catch (error) {
+ failures.push({ error, session })
+ }
+ }
+
+ return { artifacts, failures }
+}
diff --git a/apps/desktop/src/app/artifacts/index.test.ts b/apps/desktop/src/app/artifacts/index.test.ts
index cd98db3243a..a6d2371e616 100644
--- a/apps/desktop/src/app/artifacts/index.test.ts
+++ b/apps/desktop/src/app/artifacts/index.test.ts
@@ -3,7 +3,7 @@ import { afterEach, describe, expect, it, vi } from 'vitest'
import { $connection } from '@/store/session'
import type { SessionInfo, SessionMessage } from '@/types/hermes'
-import { artifactImageSrc, collectArtifactsForSession } from './artifact-utils'
+import { artifactImageSrc, collectArtifactsForSession, loadArtifactsForSessions } from './artifact-utils'
function makeSession(overrides: Partial<SessionInfo> = {}): SessionInfo {
return {
@@ -89,3 +89,54 @@ describe('collectArtifactsForSession', () => {
})
})
})
+
+describe('loadArtifactsForSessions', () => {
+ it('loads transcripts serially and continues after a session fails', async () => {
+ const sessions = [
+ makeSession({ id: 'session-1' }),
+ makeSession({ id: 'session-2' }),
+ makeSession({ id: 'session-3' })
+ ]
+ const callOrder: string[] = []
+ let activeLoads = 0
+ let maxActiveLoads = 0
+
+ const result = await loadArtifactsForSessions(sessions, async session => {
+ activeLoads += 1
+ maxActiveLoads = Math.max(maxActiveLoads, activeLoads)
+ callOrder.push(`start:${session.id}`)
+
+ try {
+ await Promise.resolve()
+
+ if (session.id === 'session-2') {
+ throw new Error('Session transcript exceeds the Desktop safe-load limit')
+ }
+
+ return [
+ {
+ content: `https://example.com/${session.id}.png`,
+ role: 'assistant',
+ timestamp: 2000
+ }
+ ]
+ } finally {
+ callOrder.push(`end:${session.id}`)
+ activeLoads -= 1
+ }
+ })
+
+ expect(maxActiveLoads).toBe(1)
+ expect(callOrder).toEqual([
+ 'start:session-1',
+ 'end:session-1',
+ 'start:session-2',
+ 'end:session-2',
+ 'start:session-3',
+ 'end:session-3'
+ ])
+ expect(result.artifacts.map(artifact => artifact.sessionId)).toEqual(['session-1', 'session-3'])
+ expect(result.failures).toHaveLength(1)
+ expect(result.failures[0]?.session.id).toBe('session-2')
+ })
+})
diff --git a/apps/desktop/src/app/artifacts/index.tsx b/apps/desktop/src/app/artifacts/index.tsx
index 83f46863593..b13cb78b705 100644
--- a/apps/desktop/src/app/artifacts/index.tsx
+++ b/apps/desktop/src/app/artifacts/index.tsx
@@ -1,5 +1,5 @@
import type * as React from 'react'
-import { memo, useCallback, useEffect, useMemo, useState } from 'react'
+import { memo, useCallback, useEffect, useMemo, useRef, useState } from 'react'
import { useNavigate } from 'react-router'
import { ZoomableImage } from '@/components/chat/zoomable-image'
@@ -17,7 +17,7 @@ import {
} from '@/components/ui/pagination'
import { RowButton } from '@/components/ui/row-button'
import { Tip } from '@/components/ui/tooltip'
-import { getSessionMessages, listAllProfileSessions } from '@/hermes'
+import { getAllSessionMessages, listAllProfileSessions } from '@/hermes'
import { type Translations, useI18n } from '@/i18n'
import { resolveBrandIcon } from '@/lib/brand-icon'
import {
@@ -33,7 +33,7 @@ import { downloadGatewayMediaFile, isRemoteGateway } from '@/lib/media'
import { normalize } from '@/lib/text'
import { fmtDayTime } from '@/lib/time'
import { cn } from '@/lib/utils'
-import { notifyError } from '@/store/notifications'
+import { notify, notifyError } from '@/store/notifications'
import { useRefreshHotkey } from '../hooks/use-refresh-hotkey'
import { useRouteEnumParam } from '../hooks/use-route-enum-param'
@@ -46,7 +46,7 @@ import {
type ArtifactFilter,
artifactImageSrc,
type ArtifactRecord,
- collectArtifactsForSession
+ loadArtifactsForSessions
} from './artifact-utils'
function formatArtifactTime(timestamp: number): string {
@@ -124,29 +124,51 @@ export function ArtifactsView({ setStatusbarItemGroup: _setStatusbarItemGroup, .
const [filePage, setFilePage] = useState(1)
const [refreshing, setRefreshing] = useState(false)
+ const refreshInFlightRef = useRef(false)
const refreshArtifacts = useCallback(async () => {
+ if (refreshInFlightRef.current) {
+ return
+ }
+
+ refreshInFlightRef.current = true
setRefreshing(true)
try {
const sessions = (await listAllProfileSessions(30, 1)).sessions
- const results = await Promise.allSettled(sessions.map(session => getSessionMessages(session.id, session.profile)))
- const nextArtifacts: ArtifactRecord[] = []
-
- results.forEach((result, index) => {
- if (result.status !== 'fulfilled') {
- return
- }
+ const { artifacts: nextArtifacts, failures } = await loadArtifactsForSessions(
+ sessions,
+ async session => (await getAllSessionMessages(session.id, session.profile)).messages
+ )
- const session = sessions[index]
- nextArtifacts.push(...collectArtifactsForSession(session, result.value.messages))
- })
+ if (failures.length > 0) {
+ const safeLimitFailures = failures.filter(({ error }) =>
+ String(error instanceof Error ? error.message : error).includes('safe-load limit')
+ ).length
+ const otherFailures = failures.length - safeLimitFailures
+ const detail = [
+ safeLimitFailures ? `${safeLimitFailures} exceeded the safe transcript load limit.` : '',
+ otherFailures ? `${otherFailures} could not be read.` : ''
+ ]
+ .filter(Boolean)
+ .join(' ')
+
+ notify({
+ id: 'artifacts-partial-load',
+ kind: 'warning',
+ title: a.failedLoad,
+ message: `Skipped ${failures.length} of ${sessions.length} recent sessions while indexing artifacts.`,
+ detail,
+ durationMs: 10_000
+ })
+ }
setArtifacts(nextArtifacts.sort((left, right) => right.timestamp - left.timestamp))
} catch (err) {
notifyError(err, a.failedLoad)
setArtifacts([])
} finally {
+ refreshInFlightRef.current = false
setRefreshing(false)
}
}, [a])
diff --git a/apps/desktop/src/app/contrib/hooks/use-session-tile-delegate.ts b/apps/desktop/src/app/contrib/hooks/use-session-tile-delegate.ts
index 5770dfb85b8..0fd18f15b78 100644
--- a/apps/desktop/src/app/contrib/hooks/use-session-tile-delegate.ts
+++ b/apps/desktop/src/app/contrib/hooks/use-session-tile-delegate.ts
@@ -1,6 +1,6 @@
import { useEffect } from 'react'
-import { getSessionMessages, PROMPT_SUBMIT_REQUEST_TIMEOUT_MS } from '@/hermes'
+import { getLatestSessionMessages, PROMPT_SUBMIT_REQUEST_TIMEOUT_MS } from '@/hermes'
import { toChatMessages } from '@/lib/chat-messages'
import { publishSessionState, setSessionTileDelegate } from '@/store/session-states'
import type { SessionResumeResponse } from '@/types/hermes'
@@ -110,7 +110,7 @@ export function useSessionTileDelegate({
const profile = await resolveSessionProfile(storedSessionId)
const [prefetch, resumed] = await Promise.all([
- getSessionMessages(storedSessionId, profile).catch(() => null),
+ getLatestSessionMessages(storedSessionId, profile).catch(() => null),
requestGateway<SessionResumeResponse>('session.resume', {
session_id: storedSessionId,
cols: 96,
diff --git a/apps/desktop/src/app/contrib/wiring.tsx b/apps/desktop/src/app/contrib/wiring.tsx
index 02f95d9765a..f1394a262ff 100644
--- a/apps/desktop/src/app/contrib/wiring.tsx
+++ b/apps/desktop/src/app/contrib/wiring.tsx
@@ -24,7 +24,7 @@ import { $newSessionTabAction, registerPaneCloser } from '@/components/pane-shel
import { FloatingPet } from '@/components/pet/floating-pet'
import { RemoteDisplayBanner } from '@/components/remote-display-banner'
import { emitGatewayEvent } from '@/contrib/events'
-import { getSessionMessages, triggerCronJob } from '@/hermes'
+import { getLatestSessionMessages, triggerCronJob } from '@/hermes'
import { type ChatMessage, chatMessageText, preserveLocalAssistantErrors, toChatMessages } from '@/lib/chat-messages'
import { sessionMessagesSignature } from '@/lib/session-signatures'
import { isMessagingSource } from '@/lib/session-source'
@@ -330,7 +330,7 @@ export function ContribWiring({ children }: { children: ReactNode }) {
for (let index = 0; index < Math.max(1, attempts); index += 1) {
try {
- const latest = await getSessionMessages(storedSessionId, storedProfile)
+ const latest = await getLatestSessionMessages(storedSessionId, storedProfile)
const messages = toChatMessages(latest.messages)
updateSessionState(
runtimeSessionId,
@@ -377,7 +377,7 @@ export function ContribWiring({ children }: { children: ReactNode }) {
}
try {
- const latest = await getSessionMessages(storedSessionId, stored.profile)
+ const latest = await getLatestSessionMessages(storedSessionId, stored.profile)
const signatureKey = `${stored.profile ?? 'default'}:${storedSessionId}`
const sig = sessionMessagesSignature(latest.messages)
diff --git a/apps/desktop/src/app/session/hooks/use-session-actions/index.ts b/apps/desktop/src/app/session/hooks/use-session-actions/index.ts
index 8bb8029caac..a800a22fa26 100644
--- a/apps/desktop/src/app/session/hooks/use-session-actions/index.ts
+++ b/apps/desktop/src/app/session/hooks/use-session-actions/index.ts
@@ -3,7 +3,12 @@ import { type MutableRefObject, useCallback, useEffect, useRef } from 'react'
import type { NavigateFunction } from 'react-router'
import { revealTreePane } from '@/components/pane-shell/tree/store'
-import { deleteSession, getSessionMessages, setSessionArchived } from '@/hermes'
+import {
+ deleteSession,
+ getAllSessionMessages,
+ getLatestSessionMessages,
+ setSessionArchived
+} from '@/hermes'
import { useI18n } from '@/i18n'
import { type ChatMessage, preserveLocalAssistantErrors, toChatMessages } from '@/lib/chat-messages'
import { isMissingRpcMethod } from '@/lib/gateway-rpc'
@@ -707,7 +712,7 @@ export function useSessionActions({
// prefetch. Watch mirrors stay live-only by design.
const persistedTranscriptPromise = isWatchWindow()
? null
- : getSessionMessages(storedSessionId, sessionProfile).catch(() => null)
+ : getLatestSessionMessages(storedSessionId, sessionProfile).catch(() => null)
setFreshDraftReady(false)
clearNotifications()
@@ -893,7 +898,7 @@ export function useSessionActions({
// max(prefetch, resume) instead of their sum. The prefetch paints the
// transcript as soon as it lands; the RPC binds the runtime id.
// Watch windows skip the prefetch — lazy resume attaches the live mirror.
- const prefetchPromise = watchWindow ? null : getSessionMessages(storedSessionId, sessionProfile)
+ const prefetchPromise = watchWindow ? null : getLatestSessionMessages(storedSessionId, sessionProfile)
const resumePromise = requestGateway<SessionResumeResponse>('session.resume', {
session_id: storedSessionId,
@@ -1060,7 +1065,7 @@ export function useSessionActions({
let fallbackError: unknown = null
try {
- const fallback = await getSessionMessages(storedSessionId, sessionProfile)
+ const fallback = await getLatestSessionMessages(storedSessionId, sessionProfile)
if (!isCurrentResume()) {
return
@@ -1318,7 +1323,7 @@ export function useSessionActions({
try {
await ensureGatewayProfile(profile)
- const { messages } = await getSessionMessages(storedSessionId, profile)
+ const { messages } = await getAllSessionMessages(storedSessionId, profile)
const branchMessages = toBranchMessages(toChatMessages(messages))
if (!branchMessages.length) {
diff --git a/apps/desktop/src/hermes.test.ts b/apps/desktop/src/hermes.test.ts
index a1dc61c6095..dff0379e103 100644
--- a/apps/desktop/src/hermes.test.ts
+++ b/apps/desktop/src/hermes.test.ts
@@ -7,6 +7,7 @@ import {
AUDIO_TRANSCRIBE_MIN_REQUEST_TIMEOUT_MS,
audioSpeakRequestTimeoutMs,
audioTranscribeRequestTimeoutMs,
+ getAllSessionMessages,
getCronJobs,
getGlobalModelInfo,
getGlobalModelOptions,
@@ -333,6 +334,59 @@ describe('Hermes REST helpers', () => {
})
})
+ it('passes bounded transcript pagination through to the backend', async () => {
+ api.mockResolvedValue({ messages: [], session_id: 'session-1' })
+
+ await getSessionMessages('session-1', 'xiaoxuxu', {
+ limit: 500,
+ offset: 1000,
+ order: 'latest'
+ })
+
+ expect(api).toHaveBeenCalledWith({
+ path: '/api/sessions/session-1/messages?profile=xiaoxuxu&limit=500&offset=1000&order=latest',
+ profile: 'xiaoxuxu'
+ })
+ })
+
+ it('loads complete transcripts through bounded oldest-first pages', async () => {
+ api
+ .mockResolvedValueOnce({
+ messages: [{ id: 1 }, { id: 2 }],
+ session_id: 'session-1',
+ pagination: { limit: 2, offset: 0, order: 'oldest', returned: 2 }
+ })
+ .mockResolvedValueOnce({
+ messages: [{ id: 3 }],
+ session_id: 'session-1',
+ pagination: { limit: 2, offset: 2, order: 'oldest', returned: 1 }
+ })
+
+ const result = await getAllSessionMessages('session-1', 'xiaoxuxu')
+
+ expect(result.messages).toEqual([{ id: 1 }, { id: 2 }, { id: 3 }])
+ expect(api).toHaveBeenNthCalledWith(1, {
+ path: '/api/sessions/session-1/messages?profile=xiaoxuxu&limit=500&offset=0&order=oldest',
+ profile: 'xiaoxuxu'
+ })
+ expect(api).toHaveBeenNthCalledWith(2, {
+ path: '/api/sessions/session-1/messages?profile=xiaoxuxu&limit=500&offset=2&order=oldest',
+ profile: 'xiaoxuxu'
+ })
+ })
+
+ it('stops complete transcript loads before Desktop memory becomes unbounded', async () => {
+ api.mockResolvedValueOnce({
+ messages: [{ id: 1, content: 'large transcript page' }],
+ session_id: 'session-1',
+ pagination: { limit: 1, offset: 0, order: 'oldest', returned: 1 }
+ })
+
+ await expect(getAllSessionMessages('session-1', null, { maxJsonChars: 1 })).rejects.toThrow(
+ 'Desktop safe-load limit'
+ )
+ })
+
it('bounds blocking TTS synthesis timeouts by text length', () => {
expect(audioSpeakRequestTimeoutMs('short message')).toBe(AUDIO_SPEAK_MIN_REQUEST_TIMEOUT_MS)
expect(audioSpeakRequestTimeoutMs('x'.repeat(8_000))).toBe(280_000)
diff --git a/apps/desktop/src/hermes.ts b/apps/desktop/src/hermes.ts
index b931fe8678f..d83b9a26130 100644
--- a/apps/desktop/src/hermes.ts
+++ b/apps/desktop/src/hermes.ts
@@ -52,6 +52,7 @@ import type {
ProfileSoul,
ProfilesResponse,
SessionInfo,
+ SessionMessage,
SessionMessagesResponse,
SessionSearchResponse,
SkillHubPreview,
@@ -655,8 +656,17 @@ export function getSession(id: string, profile?: string | null): Promise<Session
// this GET to the remote backend (which serves its own state.db); for a local
// profile the primary opens that profile's state.db via ?profile=. Omit for
// the current/default profile.
-export function getSessionMessages(id: string, profile?: string | null): Promise<SessionMessagesResponse> {
- const suffix = profile ? `?profile=${encodeURIComponent(profile)}` : ''
+export function getSessionMessages(
+ id: string,
+ profile?: string | null,
+ page: { limit?: number; offset?: number; order?: 'latest' | 'oldest' } = {}
+): Promise<SessionMessagesResponse> {
+ const query = new URLSearchParams()
+ if (profile) query.set('profile', profile)
+ if (page.limit !== undefined) query.set('limit', String(page.limit))
+ if (page.offset !== undefined) query.set('offset', String(page.offset))
+ if (page.order) query.set('order', page.order)
+ const suffix = query.size ? `?${query.toString()}` : ''
return window.hermesDesktop.api<SessionMessagesResponse>({
...(profile ? { profile } : {}),
@@ -664,6 +674,54 @@ export function getSessionMessages(id: string, profile?: string | null): Promise
})
}
+export function getLatestSessionMessages(
+ id: string,
+ profile?: string | null
+): Promise<SessionMessagesResponse> {
+ return getSessionMessages(id, profile, { limit: 500, order: 'latest' })
+}
+
+export async function getAllSessionMessages(
+ id: string,
+ profile?: string | null,
+ options: { maxJsonChars?: number } = {}
+): Promise<SessionMessagesResponse> {
+ const messages: SessionMessage[] = []
+ const pageSize = 500
+ const maxJsonChars = options.maxJsonChars ?? 32_000_000
+ let jsonChars = 0
+ let offset = 0
+ let resolvedSessionId = id
+
+ while (true) {
+ const page = await getSessionMessages(id, profile, {
+ limit: pageSize,
+ offset,
+ order: 'oldest'
+ })
+ resolvedSessionId = page.session_id
+ jsonChars += (JSON.stringify(page.messages) ?? '').length
+ if (jsonChars > maxJsonChars) {
+ throw new Error(
+ 'Session transcript exceeds the Desktop safe-load limit; use the Web Dashboard export for this session.'
+ )
+ }
+ messages.push(...page.messages)
+
+ // Legacy backends ignore pagination and return the full transcript.
+ if (
+ !page.pagination ||
+ page.messages.length === 0 ||
+ page.messages.length < page.pagination.limit
+ ) {
+ break
+ }
+ offset += page.messages.length
+ }
+
+ return { session_id: resolvedSessionId, messages }
+}
+
export function deleteSession(id: string, profile?: string | null): Promise<{ ok: boolean }> {
return window.hermesDesktop.api<{ ok: boolean }>({
...(profile ? { profile } : {}),
diff --git a/apps/desktop/src/lib/session-export.ts b/apps/desktop/src/lib/session-export.ts
index 8aa31c695cb..a64621ecbbe 100644
--- a/apps/desktop/src/lib/session-export.ts
+++ b/apps/desktop/src/lib/session-export.ts
@@ -1,5 +1,5 @@
import type { SessionInfo } from '@/hermes'
-import { getSessionMessages } from '@/hermes'
+import { getAllSessionMessages } from '@/hermes'
import { translateNow } from '@/i18n'
import { notify, notifyError } from '@/store/notifications'
@@ -33,7 +33,7 @@ export async function exportSession(sessionId: string, params: Omit<ExportSessio
try {
const profile = params.profile ?? params.session?.profile
- const { messages } = await getSessionMessages(sessionId, profile)
+ const { messages } = await getAllSessionMessages(sessionId, profile)
const payload = {
exported_at: new Date().toISOString(),
diff --git a/apps/desktop/src/types/hermes.ts b/apps/desktop/src/types/hermes.ts
index 374bc4db9af..ad0ba7d180d 100644
--- a/apps/desktop/src/types/hermes.ts
+++ b/apps/desktop/src/types/hermes.ts
@@ -570,6 +570,12 @@ export interface SessionMessage {
export interface SessionMessagesResponse {
messages: SessionMessage[]
+ pagination?: {
+ limit: number
+ offset: number
+ order: 'latest' | 'oldest'
+ returned: number
+ }
session_id: string
}
diff --git a/gateway/platforms/api_server.py b/gateway/platforms/api_server.py
index d7bf5332667..60999347f03 100644
--- a/gateway/platforms/api_server.py
+++ b/gateway/platforms/api_server.py
@@ -3540,11 +3540,52 @@ class APIServerAdapter(BasePlatformAdapter):
return err
db = await self._ensure_session_db_async()
resolved_id = await asyncio.to_thread(db.resolve_resume_session_id, session_id)
- messages = await asyncio.to_thread(db.get_messages, resolved_id)
+ raw_limit = request.query.get("limit")
+ raw_offset = request.query.get("offset", "0")
+ order = request.query.get("order")
+ if order not in (None, "oldest", "latest"):
+ return web.json_response(
+ _openai_error(
+ "order must be one of: oldest, latest",
+ code="invalid_pagination",
+ ),
+ status=400,
+ )
+ try:
+ offset = int(raw_offset)
+ requested_limit = None if raw_limit is None else int(raw_limit)
+ except (TypeError, ValueError):
+ offset = -1
+ requested_limit = -1
+ if offset < 0 or (requested_limit is not None and requested_limit < 0):
+ return web.json_response(
+ _openai_error(
+ "limit and offset must be non-negative integers",
+ code="invalid_pagination",
+ ),
+ status=400,
+ )
+
+ default_page = requested_limit is None
+ latest_page = order == "latest" or (order is None and default_page)
+ limit = 500 if default_page else min(requested_limit, 500)
+ messages = await asyncio.to_thread(
+ db.get_messages,
+ resolved_id,
+ limit=limit,
+ offset=offset,
+ latest=latest_page,
+ )
return web.json_response({
"object": "list",
"session_id": resolved_id,
"data": [self._message_response(m) for m in messages],
+ "pagination": {
+ "limit": limit,
+ "offset": offset,
+ "order": order or ("latest" if default_page else "oldest"),
+ "returned": len(messages),
+ },
})
async def _handle_fork_session(self, request: "web.Request") -> "web.Response":
diff --git a/hermes_cli/cli_agent_setup_mixin.py b/hermes_cli/cli_agent_setup_mixin.py
index 40bbff5ede0..25e5fc17e76 100644
--- a/hermes_cli/cli_agent_setup_mixin.py
+++ b/hermes_cli/cli_agent_setup_mixin.py
@@ -404,6 +404,19 @@ class CLIAgentSetupMixin:
resolved_meta = self._session_db.get_session(self.session_id)
if resolved_meta:
session_meta = resolved_meta
+ prior_resume_error = getattr(self, "_resume_history_error", None)
+ if prior_resume_error:
+ return False
+ resume_limit_error = self._resume_history_limit_error()
+ if resume_limit_error:
+ self._resume_history_error = resume_limit_error
+ if _quiet_mode:
+ print(f"Cannot resume session: {resume_limit_error}", file=sys.stderr)
+ else:
+ ChatConsole().print(
+ f"[bold red]Cannot resume session:[/] {_escape(resume_limit_error)}"
+ )
+ return False
restored = self._session_db.get_messages_as_conversation(
self.session_id, repair_alternation=True
)
@@ -573,6 +586,24 @@ class CLIAgentSetupMixin:
console.print(line)
return False
+ def _resume_history_limit_error(self):
+ """Return a safe-resume error without materializing transcript rows."""
+ if not self._session_db:
+ return None
+ safety_check = getattr(self._session_db, "assert_resume_safe", None)
+ if not callable(safety_check):
+ return None
+ try:
+ safety_check(self.session_id)
+ except Exception as exc:
+ from hermes_state import SessionResumeTooLargeError
+
+ if isinstance(exc, SessionResumeTooLargeError):
+ return str(exc)
+ logger.warning("Resume safety check failed for %s: %s", self.session_id, exc)
+ return f"resume safety check failed: {exc}"
+ return None
+
def _preload_resumed_session(self) -> bool:
"""Load a resumed session's history from the DB early (before first chat).
@@ -615,6 +646,14 @@ class CLIAgentSetupMixin:
if resolved_meta:
session_meta = resolved_meta
+ resume_limit_error = self._resume_history_limit_error()
+ if resume_limit_error:
+ self._resume_history_error = resume_limit_error
+ self._console_print(
+ f"[bold red]Cannot resume session:[/] {resume_limit_error}"
+ )
+ return False
+
model_history, display_history = self._session_db.get_resume_conversations(self.session_id)
restored = model_history
if restored:
diff --git a/hermes_cli/console_engine.py b/hermes_cli/console_engine.py
index 627e8abd84a..febfb629bad 100644
--- a/hermes_cli/console_engine.py
+++ b/hermes_cli/console_engine.py
@@ -1414,19 +1414,44 @@ def _sessions_export(_engine: HermesConsoleEngine, args: list[str]) -> str:
ns = parser.parse_args(args)
def _run() -> None:
- from hermes_state import SessionDB
+ from hermes_state import (
+ MAX_SAFE_EXPORT_MESSAGES,
+ SessionDB,
+ SessionExportTooLargeError,
+ )
db = SessionDB()
try:
+ def _guard_exports(session_ids: list[str]) -> None:
+ total_messages = 0
+ try:
+ for session_id in session_ids:
+ total_messages += db.assert_export_safe(
+ session_id,
+ max_messages=MAX_SAFE_EXPORT_MESSAGES - total_messages,
+ )
+ except SessionExportTooLargeError as exc:
+ raise ConsoleCommandError(
+ f"Export includes more than {MAX_SAFE_EXPORT_MESSAGES:,} active "
+ f"messages (limit reached at session '{exc.session_id}'). "
+ "Use the Sessions page's streaming Export action instead."
+ ) from exc
+
if ns.session_id:
resolved_session_id = db.resolve_session_id(ns.session_id)
if not resolved_session_id:
raise ConsoleCommandError(f"Session '{ns.session_id}' not found.")
+ _guard_exports([resolved_session_id])
data = db.export_session(resolved_session_id)
if not data:
raise ConsoleCommandError(f"Session '{ns.session_id}' not found.")
rows = [data]
else:
+ session_ids = [
+ session["id"]
+ for session in db.search_sessions(source=ns.source, limit=100000)
+ ]
+ _guard_exports(session_ids)
rows = db.export_all(source=ns.source)
lines = [json.dumps(row, ensure_ascii=False) for row in rows]
diff --git a/hermes_cli/web_routers/sessions.py b/hermes_cli/web_routers/sessions.py
index c692d7b21e1..2a5e6e504e1 100644
--- a/hermes_cli/web_routers/sessions.py
+++ b/hermes_cli/web_routers/sessions.py
@@ -13,11 +13,14 @@ the late-binding seam in :mod:`hermes_cli.web_deps` so tests that
"""
import asyncio # noqa: F401 — used by handlers
+import json
import logging
import time # noqa: F401
from typing import Any, Dict, List, Optional # noqa: F401
from fastapi import APIRouter, HTTPException, Query, Request # noqa: F401
+from fastapi.encoders import jsonable_encoder
+from fastapi.responses import StreamingResponse
from hermes_cli.web_deps import late
from hermes_cli.web_models import (
@@ -601,7 +604,14 @@ async def get_session_messages(
profile: Optional[str] = None,
limit: Optional[int] = Query(None, ge=0),
offset: int = Query(0, ge=0),
+ order: Optional[str] = Query(None),
):
+ if order not in (None, "oldest", "latest"):
+ raise HTTPException(
+ status_code=400,
+ detail="order must be one of: oldest, latest",
+ )
+
def _read():
db = _open_session_db_for_profile(profile, read_only=True)
try:
@@ -609,9 +619,20 @@ async def get_session_messages(
if not sid:
return None
sid = db.resolve_resume_session_id(sid)
- # Clamp limit to prevent abuse (max 500 per page)
- _limit = min(limit, 500) if limit is not None else None
- return sid, _limit, db.get_messages(sid, limit=_limit, offset=offset)
+ # Always page this endpoint. An omitted limit used to load an
+ # entire transcript, which can be hundreds of thousands of rows
+ # for a runaway session and exhaust the dashboard process. Keep
+ # explicit pagination anchored at the start, while the default
+ # dashboard view returns the latest page in chronological order.
+ default_page = limit is None
+ latest_page = order == "latest" or (order is None and default_page)
+ _limit = 500 if default_page else min(limit, 500)
+ return sid, _limit, db.get_messages(
+ sid,
+ limit=_limit,
+ offset=offset,
+ latest=latest_page,
+ )
finally:
db.close()
@@ -625,6 +646,7 @@ async def get_session_messages(
"pagination": {
"limit": _limit,
"offset": offset,
+ "order": order or ("latest" if limit is None else "oldest"),
"returned": len(messages),
},
}
@@ -699,19 +721,60 @@ async def rename_session_endpoint(session_id: str, body: SessionRename):
@manage_router.get("/api/sessions/{session_id}/export")
async def export_session_endpoint(session_id: str, profile: Optional[str] = None):
- """Export a single session (metadata + messages) as JSON."""
- def _export():
+ """Stream a single session (metadata + messages) as JSON."""
+ def _prepare_export():
db = _open_session_db_for_profile(profile, read_only=True)
try:
sid = db.resolve_session_id(session_id)
- return db.export_session(sid) if sid else None
+ return (sid, db.get_session(sid)) if sid else None
finally:
db.close()
- data = await asyncio.to_thread(_export)
- if data is None:
+ prepared = await asyncio.to_thread(_prepare_export)
+ if prepared is None or prepared[1] is None:
raise HTTPException(status_code=404, detail="Session not found")
- return data
+
+ sid, session = prepared
+
+ def _stream_export():
+ db = _open_session_db_for_profile(profile, read_only=True)
+ try:
+ metadata = json.dumps(
+ jsonable_encoder(session),
+ ensure_ascii=False,
+ separators=(",", ":"),
+ )
+ yield metadata[:-1] + ',"messages":['
+
+ offset = 0
+ first = True
+ while True:
+ messages = db.get_messages(
+ sid,
+ limit=500,
+ offset=offset,
+ )
+ for message in messages:
+ if not first:
+ yield ","
+ yield json.dumps(
+ jsonable_encoder(message),
+ ensure_ascii=False,
+ separators=(",", ":"),
+ )
+ first = False
+ if len(messages) < 500:
+ break
+ offset += len(messages)
+
+ yield "]}"
+ finally:
+ db.close()
+
+ return StreamingResponse(
+ _stream_export(),
+ media_type="application/json",
+ )
@manage_router.post("/api/sessions/prune")
diff --git a/hermes_state.py b/hermes_state.py
index 92b238c061f..8271f3ad9b1 100644
--- a/hermes_state.py
+++ b/hermes_state.py
@@ -84,6 +84,37 @@ except ImportError: # pragma: no cover - stripped/scaffold installs only
logger = logging.getLogger(__name__)
+MAX_SAFE_RESUME_MESSAGES = 20_000
+MAX_SAFE_EXPORT_MESSAGES = 20_000
+
+
+class SessionResumeTooLargeError(ValueError):
+ def __init__(self, message_count: int, limit: int = MAX_SAFE_RESUME_MESSAGES):
+ self.message_count = message_count
+ self.limit = limit
+ super().__init__(
+ f"session has at least {message_count} active messages across its lineage; "
+ f"safe resume limit is {limit}. Export or repair the session before "
+ "resuming it."
+ )
+
+
+class SessionExportTooLargeError(ValueError):
+ def __init__(
+ self,
+ session_id: str,
+ message_count: int,
+ limit: int = MAX_SAFE_EXPORT_MESSAGES,
+ ):
+ self.session_id = session_id
+ self.message_count = message_count
+ self.limit = limit
+ super().__init__(
+ f"session '{session_id}' has at least {message_count} active messages; "
+ f"safe in-memory export limit is {limit}"
+ )
+
+
_COMPRESSION_LOCK_HOLDER_PID_RE = re.compile(r"(?:^|:)pid=(\d+)(?::|$)")
@@ -7352,6 +7383,7 @@ class SessionDB(SessionSearchMixin, SessionSchemaMixin, SessionPortabilityMixin)
include_inactive: bool = False,
limit: Optional[int] = None,
offset: int = 0,
+ latest: bool = False,
) -> List[Dict[str, Any]]:
"""Load messages for a session in insertion order.
@@ -7366,13 +7398,16 @@ class SessionDB(SessionSearchMixin, SessionSchemaMixin, SessionPortabilityMixin)
When ``limit`` is provided, returns at most ``limit`` messages
starting from ``offset`` (0-based, in insertion order). Enables
pagination for the API endpoint to avoid loading entire transcripts.
- ``offset`` alone (without ``limit``) also pages — SQLite requires a
- LIMIT clause for OFFSET, so it's emitted as ``LIMIT -1`` (unbounded).
+ With ``latest=True``, the offset is measured back from the newest
+ message and the selected page is still returned in chronological
+ order. ``offset`` alone (without ``limit``) also pages — SQLite
+ requires a LIMIT clause for OFFSET, so it's emitted as ``LIMIT -1``
+ (unbounded).
"""
active_clause = "" if include_inactive else " AND active = 1"
sql = (
"SELECT * FROM messages WHERE session_id = ?"
- f"{active_clause} ORDER BY id"
+ f"{active_clause} ORDER BY id {'DESC' if latest else 'ASC'}"
)
params: list = [session_id]
if limit is not None or offset:
@@ -7382,6 +7417,8 @@ class SessionDB(SessionSearchMixin, SessionSchemaMixin, SessionPortabilityMixin)
with self._read_ctx() as conn:
cursor = conn.execute(sql, params)
rows = cursor.fetchall()
+ if latest:
+ rows.reverse()
result = []
for row in rows:
msg = dict(row)
@@ -7817,6 +7854,66 @@ class SessionDB(SessionSearchMixin, SessionSchemaMixin, SessionPortabilityMixin)
)
return model_history, display_history
+ def get_resume_message_count(self, session_id: str) -> int:
+ """Count active rows that a full resume would materialize."""
+ session_ids = self._session_lineage_root_to_tip(session_id)
+ placeholders = ",".join("?" for _ in session_ids)
+ with self._read_ctx() as conn:
+ row = conn.execute(
+ f"SELECT COUNT(*) FROM messages "
+ f"WHERE session_id IN ({placeholders}) AND active = 1",
+ tuple(session_ids),
+ ).fetchone()
+ return int(row[0] if row else 0)
+
+ def assert_resume_safe(
+ self,
+ session_id: str,
+ max_messages: int = MAX_SAFE_RESUME_MESSAGES,
+ ) -> int:
+ """Return resume row count or reject a transcript too large to load."""
+ if max_messages < 0:
+ raise ValueError("max_messages must be non-negative")
+ session_ids = self._session_lineage_root_to_tip(session_id)
+ placeholders = ",".join("?" for _ in session_ids)
+ with self._read_ctx() as conn:
+ row = conn.execute(
+ "SELECT COUNT(*) FROM ("
+ f"SELECT 1 FROM messages WHERE session_id IN ({placeholders}) "
+ "AND active = 1 LIMIT ?"
+ ")",
+ (*session_ids, max_messages + 1),
+ ).fetchone()
+ message_count = int(row[0] if row else 0)
+ if message_count > max_messages:
+ raise SessionResumeTooLargeError(message_count, max_messages)
+ return message_count
+
+ def assert_export_safe(
+ self,
+ session_id: str,
+ max_messages: int = MAX_SAFE_EXPORT_MESSAGES,
+ ) -> int:
+ """Return active row count or reject an unsafe in-memory export.
+
+ Exporting one session does not include compression ancestors, so this
+ guard deliberately counts only the requested segment. The limited
+ subquery stops as soon as it proves the transcript exceeds the bound.
+ """
+ if max_messages < 0:
+ raise ValueError("max_messages must be non-negative")
+ with self._read_ctx() as conn:
+ row = conn.execute(
+ "SELECT COUNT(*) FROM ("
+ "SELECT 1 FROM messages WHERE session_id = ? AND active = 1 LIMIT ?"
+ ")",
+ (session_id, max_messages + 1),
+ ).fetchone()
+ message_count = int(row[0] if row else 0)
+ if message_count > max_messages:
+ raise SessionExportTooLargeError(session_id, message_count, max_messages)
+ return message_count
+
def get_ancestor_display_prefix(self, session_id: str) -> List[Dict[str, Any]]:
"""Return the ancestor-only display messages for a session lineage.
diff --git a/tests/cli/test_resume_display.py b/tests/cli/test_resume_display.py
index b5fad756042..4c15008d864 100644
--- a/tests/cli/test_resume_display.py
+++ b/tests/cli/test_resume_display.py
@@ -274,6 +274,29 @@ class TestPreloadResumedSession:
assert "ended_at = NULL" in call_args[0][0]
mock_conn.commit.assert_called_once()
+ def test_rejects_runaway_transcript_before_history_load(self):
+ from hermes_state import SessionResumeTooLargeError
+
+ cli = _make_cli(resume="runaway-session")
+ mock_db = MagicMock()
+ mock_db.get_session.return_value = {
+ "id": "runaway-session",
+ "title": None,
+ }
+ mock_db.resolve_resume_session_id.return_value = "runaway-session"
+ mock_db.assert_resume_safe = MagicMock(
+ side_effect=SessionResumeTooLargeError(20_001)
+ )
+ cli._session_db = mock_db
+
+ output = StringIO()
+ cli.console.file = output
+ result = cli._preload_resumed_session()
+
+ assert result is False
+ assert "safe resume limit is 20000" in output.getvalue()
+ mock_db.get_resume_conversations.assert_not_called()
+
# ── Tests for _handle_resume_command recap display ───────────────────
@@ -406,4 +429,3 @@ class TestResumeDisplaySanitization:
assert "\x07" not in output
assert "hi" in output and "there" in output
assert "fine" in output
-
diff --git a/tests/gateway/test_session_api.py b/tests/gateway/test_session_api.py
index 05e42c7d1a9..b73a39ae8e2 100644
--- a/tests/gateway/test_session_api.py
+++ b/tests/gateway/test_session_api.py
@@ -75,6 +75,40 @@ async def test_capabilities_advertises_session_control_surface(adapter):
}
+async def test_session_messages_default_to_latest_bounded_page(adapter, session_db):
+ session_id = session_db.create_session("bounded-messages", "api_server")
+ session_db.replace_messages(
+ session_id,
+ [{"role": "user", "content": f"msg {i}"} for i in range(501)],
+ )
+
+ app = _create_session_app(adapter)
+ async with TestClient(TestServer(app)) as cli:
+ resp = await cli.get(f"/api/sessions/{session_id}/messages")
+ assert resp.status == 200
+ payload = await resp.json()
+
+ explicit_resp = await cli.get(
+ f"/api/sessions/{session_id}/messages?limit=2&offset=1"
+ )
+ assert explicit_resp.status == 200
+ explicit = await explicit_resp.json()
+
+ assert payload["pagination"] == {
+ "limit": 500,
+ "offset": 0,
+ "order": "latest",
+ "returned": 500,
+ }
+ assert payload["data"][0]["content"] == "msg 1"
+ assert payload["data"][-1]["content"] == "msg 500"
+ assert [message["content"] for message in explicit["data"]] == [
+ "msg 1",
+ "msg 2",
+ ]
+
+
@pytest.mark.asyncio
async def test_run_agent_binds_api_session_context_for_tool_env(adapter, monkeypatch):
"""API-server request sessions should reach tools and terminal subprocess env."""
diff --git a/tests/hermes_cli/test_console_engine.py b/tests/hermes_cli/test_console_engine.py
index bb470423763..fbd406e12af 100644
--- a/tests/hermes_cli/test_console_engine.py
+++ b/tests/hermes_cli/test_console_engine.py
@@ -262,6 +262,94 @@ def test_sessions_list_and_stats_use_isolated_session_store(_isolate_hermes_home
assert "Listable sessions: 1" in stats.output
+def test_sessions_export_rejects_oversized_single_before_touching_output(
+ _isolate_hermes_home,
+ monkeypatch,
+ tmp_path,
+):
+ import hermes_state
+ from hermes_state import SessionDB
+
+ db = SessionDB()
+ try:
+ db.create_session("too-large", source="cli")
+ db.append_messages_batch(
+ "too-large",
+ [{"role": "user", "content": f"message-{i}"} for i in range(3)],
+ )
+ finally:
+ db.close()
+
+ monkeypatch.setattr(hermes_state, "MAX_SAFE_EXPORT_MESSAGES", 2)
+ materialized = []
+ original_export_session = SessionDB.export_session
+
+ def tracked_export_session(self, session_id):
+ materialized.append(session_id)
+ return original_export_session(self, session_id)
+
+ monkeypatch.setattr(SessionDB, "export_session", tracked_export_session)
+ output = tmp_path / "sessions.jsonl"
+ output.write_text("keep me\n", encoding="utf-8")
+
+ result = HermesConsoleEngine().execute(
+ f"sessions export {output} --session-id too-large",
+ confirmed=True,
+ )
+
+ assert result.status == "error"
+ assert "too-large" in result.output
+ assert "streaming Export" in result.output
+ assert "resume" not in result.output.lower()
+ assert materialized == []
+ assert output.read_text(encoding="utf-8") == "keep me\n"
+
+
+def test_sessions_export_all_preflights_before_export_all(
+ _isolate_hermes_home,
+ monkeypatch,
+ tmp_path,
+):
+ import hermes_state
+ from hermes_state import SessionDB
+
+ db = SessionDB()
+ try:
+ db.create_session("first-safe", source="cli")
+ db.append_messages_batch(
+ "first-safe",
+ [{"role": "user", "content": f"first-{i}"} for i in range(2)],
+ )
+ db.create_session("second-safe", source="cli")
+ db.append_messages_batch(
+ "second-safe",
+ [{"role": "user", "content": f"second-{i}"} for i in range(2)],
+ )
+ finally:
+ db.close()
+
+ monkeypatch.setattr(hermes_state, "MAX_SAFE_EXPORT_MESSAGES", 3)
+ export_all_calls = []
+
+ def tracked_export_all(self, source=None):
+ export_all_calls.append(source)
+ raise AssertionError("export_all must not run before every guard passes")
+
+ monkeypatch.setattr(SessionDB, "export_all", tracked_export_all)
+ output = tmp_path / "all-sessions.jsonl"
+
+ result = HermesConsoleEngine().execute(
+ f"sessions export {output}",
+ confirmed=True,
+ )
+
+ assert result.status == "error"
+ assert "more than 3 active messages" in result.output
+ assert "streaming Export" in result.output
+ assert export_all_calls == []
+ assert not output.exists()
+
+
def test_cron_pause_resume_and_run_require_confirmation(_isolate_hermes_home):
from cron.jobs import create_job, get_job
@@ -337,5 +425,3 @@ def test_execute_handler_string_exit_returns_error_not_crash(_isolate_hermes_hom
assert result.status == "error"
assert result.output
-
-
diff --git a/tests/hermes_cli/test_web_server.py b/tests/hermes_cli/test_web_server.py
index 5154fcffbf8..5d0429c654f 100644
--- a/tests/hermes_cli/test_web_server.py
+++ b/tests/hermes_cli/test_web_server.py
@@ -1826,6 +1826,89 @@ class TestWebServerEndpoints:
assert resp.status_code == 200
assert resp.json()["pagination"]["limit"] == 500
+ def test_get_session_messages_omitted_limit_defaults_to_500(self):
+ """The dashboard must never load an entire unbounded transcript."""
+ from hermes_state import SessionDB
+
+ db = SessionDB()
+ try:
+ db.create_session(session_id="default-limit-messages", source="cli")
+ db.append_messages_batch(
+ "default-limit-messages",
+ [
+ {"role": "user", "content": f"msg {i}"}
+ for i in range(501)
+ ],
+ )
+ finally:
+ db.close()
+
+ resp = self.client.get("/api/sessions/default-limit-messages/messages")
+ assert resp.status_code == 200
+ payload = resp.json()
+ assert payload["pagination"] == {
+ "limit": 500,
+ "offset": 0,
+ "order": "latest",
+ "returned": 500,
+ }
+ assert len(payload["messages"]) == 500
+ assert payload["messages"][0]["content"] == "msg 1"
+ assert payload["messages"][-1]["content"] == "msg 500"
+
+ explicit = self.client.get(
+ "/api/sessions/default-limit-messages/messages?limit=2&offset=1"
+ ).json()
+ assert explicit["pagination"]["order"] == "oldest"
+ assert [message["content"] for message in explicit["messages"]] == [
+ "msg 1",
+ "msg 2",
+ ]
+
+ latest = self.client.get(
+ "/api/sessions/default-limit-messages/messages"
+ "?limit=2&offset=1&order=latest"
+ ).json()
+ assert latest["pagination"]["order"] == "latest"
+ assert [message["content"] for message in latest["messages"]] == [
+ "msg 498",
+ "msg 499",
+ ]
+
+ def test_export_session_streams_bounded_message_pages(self, monkeypatch):
+ from hermes_state import SessionDB
+
+ db = SessionDB()
+ try:
+ db.create_session(session_id="stream-export", source="cli")
+ db.append_messages_batch(
+ "stream-export",
+ [
+ {"role": "user", "content": f"msg {i}"}
+ for i in range(501)
+ ],
+ )
+ finally:
+ db.close()
+
+ calls = []
+ original_get_messages = SessionDB.get_messages
+
+ def tracked_get_messages(self, session_id, *args, **kwargs):
+ calls.append((kwargs.get("limit"), kwargs.get("offset")))
+ return original_get_messages(self, session_id, *args, **kwargs)
+
+ monkeypatch.setattr(SessionDB, "get_messages", tracked_get_messages)
+ response = self.client.get("/api/sessions/stream-export/export")
+
+ assert response.status_code == 200
+ payload = response.json()
+ assert payload["id"] == "stream-export"
+ assert len(payload["messages"]) == 501
+ assert payload["messages"][0]["content"] == "msg 0"
+ assert payload["messages"][-1]["content"] == "msg 500"
+ assert calls == [(500, 0), (500, 500)]
+
diff --git a/tests/test_hermes_state.py b/tests/test_hermes_state.py
index 9a2895ff065..debfa60b930 100644
--- a/tests/test_hermes_state.py
+++ b/tests/test_hermes_state.py
@@ -3766,6 +3766,60 @@ class TestGetMessagesPagination:
assert [m["content"] for m in page2] == ["msg-4", "msg-5", "msg-6", "msg-7"]
assert [m["content"] for m in page3] == ["msg-8", "msg-9"]
+ def test_latest_pages_count_back_from_newest_but_remain_chronological(self, db):
+ self._seed(db)
+ page1 = db.get_messages("s1", limit=4, offset=0, latest=True)
+ page2 = db.get_messages("s1", limit=4, offset=4, latest=True)
+ page3 = db.get_messages("s1", limit=4, offset=8, latest=True)
+ assert [m["content"] for m in page1] == ["msg-6", "msg-7", "msg-8", "msg-9"]
+ assert [m["content"] for m in page2] == ["msg-2", "msg-3", "msg-4", "msg-5"]
+ assert [m["content"] for m in page3] == ["msg-0", "msg-1"]
+
+ def test_resume_safety_counts_active_rows_across_lineage(self, db):
+ db.create_session(session_id="root", source="cli")
+ db.append_messages_batch(
+ "root",
+ [{"role": "user", "content": f"root-{i}"} for i in range(3)],
+ )
+ db.create_session(
+ session_id="tip",
+ source="compression",
+ parent_session_id="root",
+ )
+ db.append_messages_batch(
+ "tip",
+ [{"role": "assistant", "content": f"tip-{i}"} for i in range(2)],
+ )
+
+ assert db.get_resume_message_count("tip") == 5
+ with pytest.raises(hermes_state.SessionResumeTooLargeError) as exc_info:
+ db.assert_resume_safe("tip", max_messages=4)
+ assert exc_info.value.message_count == 5
+ assert exc_info.value.limit == 4
+
+ def test_export_safety_is_bounded_to_the_requested_active_segment(self, db):
+ db.create_session(session_id="root", source="cli")
+ db.append_messages_batch(
+ "root",
+ [{"role": "user", "content": f"root-{i}"} for i in range(3)],
+ )
+ db.create_session(
+ session_id="tip",
+ source="compression",
+ parent_session_id="root",
+ )
+ db.append_messages_batch(
+ "tip",
+ [{"role": "assistant", "content": f"tip-{i}"} for i in range(2)],
+ )
+
+ assert db.assert_export_safe("tip", max_messages=2) == 2
+ with pytest.raises(hermes_state.SessionExportTooLargeError) as exc_info:
+ db.assert_export_safe("root", max_messages=2)
+ assert exc_info.value.session_id == "root"
+ assert exc_info.value.message_count == 3
+ assert exc_info.value.limit == 2
+
diff --git a/tests/tui_gateway/test_protocol.py b/tests/tui_gateway/test_protocol.py
index 37efc79918a..d333aba3b57 100644
--- a/tests/tui_gateway/test_protocol.py
+++ b/tests/tui_gateway/test_protocol.py
@@ -349,6 +349,39 @@ def test_session_resume_returns_hydrated_messages(server, monkeypatch):
]
+def test_session_resume_rejects_runaway_transcript_before_history_load(
+ server, monkeypatch
+):
+ class _DB:
+ def get_session(self, sid):
+ return {"id": sid, "message_count": 20_001}
+
+ def get_session_by_title(self, _title):
+ return None
+
+ def resolve_resume_session_id(self, sid):
+ return sid
+
+ def reopen_session(self, _sid):
+ raise AssertionError("oversized session must be rejected before reopen")
+
+ monkeypatch.setattr(server, "_get_db", lambda: _DB())
+
+ response = server.handle_request(
+ {
+ "id": "r1",
+ "method": "session.resume",
+ "params": {
+ "session_id": "runaway-session",
+ "omit_messages": True,
+ },
+ }
+ )
+
+ assert response["error"]["code"] == 4130
+ assert "safe resume limit is 20000" in response["error"]["message"]
+
+
def test_enforce_session_cap_evicts_oldest_detached_only(server, monkeypatch):
"""The LRU cap frees the least-recently-active DETACHED sessions when over
the limit, and never a live-transport / running / mid-build one."""
@@ -664,4 +697,3 @@ def test_unregister_live_transport_stops_delivery(capture):
# No live transports left → fell back to stdio.
assert json.loads(buf.getvalue())["params"]["type"] == "skin.changed"
-
diff --git a/tui_gateway/methods_session.py b/tui_gateway/methods_session.py
index 214e84c4257..736910b2127 100644
--- a/tui_gateway/methods_session.py
+++ b/tui_gateway/methods_session.py
@@ -378,6 +378,26 @@ def _(rid, params: dict) -> dict:
target = tip
found = db.get_session(target) or found
+ # Every interactive resume path materializes the model history, even when
+ # omit_messages suppresses the response copy. Count the complete lineage
+ # before any reopen/history read so a runaway transcript cannot exhaust
+ # the dashboard. The metadata fallback keeps lightweight test/adaptor DBs
+ # that predate the shared SessionDB guard compatible.
+ from hermes_state import MAX_SAFE_RESUME_MESSAGES, SessionResumeTooLargeError
+
+ safety_check = getattr(db, "assert_resume_safe", None)
+ try:
+ if callable(safety_check):
+ safety_check(target)
+ else:
+ stored_message_count = int(found.get("message_count") or 0)
+ if stored_message_count > MAX_SAFE_RESUME_MESSAGES:
+ raise SessionResumeTooLargeError(stored_message_count)
+ except SessionResumeTooLargeError as exc:
+ return _err(rid, 4130, str(exc))
+ except Exception as exc:
+ return _err(rid, 5000, f"resume safety check failed: {exc}")
+
profile_resume_cwd = str(found.get("cwd") or "").strip() or _profile_configured_cwd(
profile_home
)
diff --git a/web/src/lib/api.ts b/web/src/lib/api.ts
index ca7ac23f30a..02ff011945a 100644
--- a/web/src/lib/api.ts
+++ b/web/src/lib/api.ts
@@ -385,7 +385,10 @@ export const api = {
},
getSessionMessages: (id: string, profile = getManagementProfile()) =>
fetchJSON<SessionMessagesResponse>(
- appendProfileParam(`/api/sessions/${encodeURIComponent(id)}/messages`, profile),
+ appendProfileParam(
+ `/api/sessions/${encodeURIComponent(id)}/messages?limit=500&order=latest`,
+ profile,
+ ),
),
getSessionDetail: (id: string, profile = getManagementProfile()) =>
fetchJSON<SessionInfo>(
@@ -2004,6 +2007,12 @@ export interface SessionMessage {
export interface SessionMessagesResponse {
session_id: string;
messages: SessionMessage[];
+ pagination?: {
+ limit: number;
+ offset: number;
+ order: "latest" | "oldest";
+ returned: number;
+ };
}
export interface LogsResponse {
diff --git a/website/docs/user-guide/features/web-dashboard.md b/website/docs/user-guide/features/web-dashboard.md
index ccaf77c010f..30c55a9ae67 100644
--- a/website/docs/user-guide/features/web-dashboard.md
+++ b/website/docs/user-guide/features/web-dashboard.md
@@ -453,7 +453,7 @@ Returns metadata for a single session.
### GET /api/sessions/\{session_id\}/messages
-Returns the full message history for a session, including tool calls and timestamps.
+Returns a bounded page of message history, including tool calls and timestamps. By default it returns the latest 500 messages in chronological order. Use `limit` (maximum 500), `offset`, and `order=oldest|latest` for explicit pagination.
### GET /api/sessions/search
diff --git a/website/i18n/zh-Hans/docusaurus-plugin-content-docs/current/user-guide/features/web-dashboard.md b/website/i18n/zh-Hans/docusaurus-plugin-content-docs/current/user-guide/features/web-dashboard.md
index 6a711739246..a3183843ea7 100644
--- a/website/i18n/zh-Hans/docusaurus-plugin-content-docs/current/user-guide/features/web-dashboard.md
+++ b/website/i18n/zh-Hans/docusaurus-plugin-content-docs/current/user-guide/features/web-dashboard.md
@@ -238,7 +238,7 @@ Web Dashboard 暴露了一个供前端使用的 REST API。你也可以直接调
### GET /api/sessions/\{session_id\}/messages
-返回会话的完整消息历史,包含工具调用和时间戳。
+返回有上限的会话消息页,包含工具调用和时间戳。默认按时间升序返回最近 500 条;可用 `limit`(最大 500)、`offset` 和 `order=oldest|latest` 显式分页。
### GET /api/sessions/search
@@ -348,4 +348,4 @@ Dashboard 内置六个主题,并可通过用户自定义主题、插件标签
- 布局变体——`standard`、`cockpit`、`tiled`
- 插件 manifest、SDK、shell 插槽、页面级插槽(在不覆盖内置页面的情况下注入控件)、后端 FastAPI 路由
- 完整的主题加插件综合演示(Strike Freedom cockpit 示例)
-- 发现、重载和故障排查
\ No newline at end of file
+- 发现、重载和故障排查