Skip to content

The agent that grows with you

fix(desktop): index artifacts by transcript page

Kean Hd23cc6b06455
diff --git a/apps/desktop/src/app/artifacts/artifact-utils.ts b/apps/desktop/src/app/artifacts/artifact-utils.ts
index 8e48bf29b5c..50b26eee248 100644
--- a/apps/desktop/src/app/artifacts/artifact-utils.ts
+++ b/apps/desktop/src/app/artifacts/artifact-utils.ts
@@ -1,6 +1,6 @@
import { mediaTagValues } from '@/lib/chat-messages/parts'
import { isArtifactFilePath, mediaExternalUrl, mediaPathFromMarkdownHref, resolveMediaDisplaySrc } from '@/lib/media'
-import type { SessionInfo, SessionMessage } from '@/types/hermes'
+import type { SessionInfo, SessionMessage, SessionMessagesResponse } from '@/types/hermes'
export type ArtifactKind = 'image' | 'file' | 'link'
export type ArtifactFilter = 'all' | ArtifactKind
@@ -28,6 +28,9 @@ export interface ArtifactLoadResult {
failures: ArtifactLoadFailure[]
}
+const ARTIFACT_MESSAGE_PAGE_SIZE = 100
+const MAX_ARTIFACT_MESSAGE_PAGE_JSON_CHARS = 32_000_000
+
const MARKDOWN_IMAGE_RE = /!\[([^\]]*)\]\(([^)\s]+)\)/g
const MARKDOWN_LINK_RE = /\[([^\]]+)\]\(([^)\s]+)\)/g
const URL_RE = /https?:\/\/[^\s<>"')`]+/g
@@ -532,18 +535,49 @@ export function collectArtifactsForSession(session: SessionInfo, messages: Sessi
export async function loadArtifactsForSessions(
sessions: SessionInfo[],
- loadMessages: (session: SessionInfo) => Promise<SessionMessage[]>
+ loadPage: (
+ session: SessionInfo,
+ page: { limit: number; offset: number }
+ ) => Promise<Pick<SessionMessagesResponse, 'messages' | 'pagination'>>,
+ options: { maxPageJsonChars?: number } = {}
): Promise<ArtifactLoadResult> {
const artifacts: ArtifactRecord[] = []
const failures: ArtifactLoadFailure[] = []
+ const maxPageJsonChars = options.maxPageJsonChars ?? MAX_ARTIFACT_MESSAGE_PAGE_JSON_CHARS
- // 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.
+ // Keep only one transcript page resident at a time. Recent sessions can each
+ // be tens of megabytes, so retaining complete transcripts exhausts the
+ // Desktop renderer even when transport requests are paginated.
for (const session of sessions) {
try {
- const messages = await loadMessages(session)
- artifacts.push(...collectArtifactsForSession(session, messages))
+ const sessionArtifacts = new Map<string, ArtifactRecord>()
+ let offset = 0
+
+ while (true) {
+ const page = await loadPage(session, { limit: ARTIFACT_MESSAGE_PAGE_SIZE, offset })
+ const pageJsonChars = (JSON.stringify(page.messages) ?? '').length
+
+ if (pageJsonChars > maxPageJsonChars) {
+ throw new Error(
+ 'Session transcript page exceeds the Desktop safe-load limit; use the Web Dashboard export for this session.'
+ )
+ }
+
+ for (const artifact of collectArtifactsForSession(session, page.messages)) {
+ if (!sessionArtifacts.has(artifact.id)) {
+ sessionArtifacts.set(artifact.id, artifact)
+ }
+ }
+
+ // 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
+ }
+
+ artifacts.push(...sessionArtifacts.values())
} catch (error) {
failures.push({ error, session })
}
diff --git a/apps/desktop/src/app/artifacts/index.test.ts b/apps/desktop/src/app/artifacts/index.test.ts
index e3ab56cc12b..5640cc9d223 100644
--- a/apps/desktop/src/app/artifacts/index.test.ts
+++ b/apps/desktop/src/app/artifacts/index.test.ts
@@ -608,7 +608,51 @@ ${payload}
})
describe('loadArtifactsForSessions', () => {
- it('loads transcripts serially and continues after a session fails', async () => {
+ it('indexes oldest-first pages incrementally and keeps the first duplicate', async () => {
+ const session = makeSession()
+ const duplicate = 'https://example.com/shared.pdf'
+ const requestedPages: Array<{ limit: number; offset: number }> = []
+
+ const pages: SessionMessage[][] = [
+ [
+ { content: duplicate, role: 'assistant', timestamp: 1000 },
+ { content: 'https://example.com/first.png', role: 'assistant', timestamp: 1500 }
+ ],
+ [
+ {
+ content: `${duplicate} https://example.com/last.pdf`,
+ role: 'assistant',
+ timestamp: 3000
+ }
+ ]
+ ]
+
+ const result = await loadArtifactsForSessions(
+ [session],
+ async (_session, page) => {
+ requestedPages.push(page)
+ const messages = pages[page.offset === 0 ? 0 : 1] || []
+
+ return {
+ messages,
+ pagination: { limit: 2, offset: page.offset, order: 'oldest', returned: messages.length }
+ }
+ },
+ { maxPageJsonChars: 200 }
+ )
+
+ expect(requestedPages.map(page => page.offset)).toEqual([0, 2])
+ expect(requestedPages.every(page => page.limit > 0)).toBe(true)
+ expect(result.artifacts.map(artifact => artifact.value)).toEqual([
+ duplicate,
+ 'https://example.com/first.png',
+ 'https://example.com/last.pdf'
+ ])
+ expect(result.artifacts.find(artifact => artifact.value === duplicate)?.timestamp).toBe(1_000_000)
+ expect(result.failures).toEqual([])
+ })
+
+ it('discards a failed session and continues after an oversized later page', async () => {
const sessions = [
makeSession({ id: 'session-1' }),
makeSession({ id: 'session-2' }),
@@ -619,42 +663,60 @@ describe('loadArtifactsForSessions', () => {
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')
- }
+ const result = await loadArtifactsForSessions(
+ sessions,
+ async (session, page) => {
+ activeLoads += 1
+ maxActiveLoads = Math.max(maxActiveLoads, activeLoads)
+ callOrder.push(`start:${session.id}:${page.offset}`)
+
+ try {
+ await Promise.resolve()
+
+ if (session.id === 'session-2' && page.offset === 0) {
+ return {
+ messages: [
+ {
+ content: 'https://example.com/session-2-partial.png',
+ role: 'assistant',
+ timestamp: 2000
+ }
+ ],
+ pagination: { limit: 1, offset: 0, order: 'oldest', returned: 1 }
+ }
+ }
- return [
- {
- content: `https://example.com/${session.id}.png`,
- role: 'assistant',
- timestamp: 2000
+ return {
+ messages: [
+ {
+ content: session.id === 'session-2' ? 'x'.repeat(500) : `https://example.com/${session.id}.png`,
+ role: 'assistant',
+ timestamp: 2000
+ }
+ ]
}
- ]
- } finally {
- callOrder.push(`end:${session.id}`)
- activeLoads -= 1
- }
- })
+ } finally {
+ callOrder.push(`end:${session.id}:${page.offset}`)
+ activeLoads -= 1
+ }
+ },
+ { maxPageJsonChars: 200 }
+ )
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'
+ 'start:session-1:0',
+ 'end:session-1:0',
+ 'start:session-2:0',
+ 'end:session-2:0',
+ 'start:session-2:1',
+ 'end:session-2:1',
+ 'start:session-3:0',
+ 'end:session-3:0'
])
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')
+ expect(String(result.failures[0]?.error)).toContain('transcript page exceeds the Desktop safe-load limit')
})
})
diff --git a/apps/desktop/src/app/artifacts/index.tsx b/apps/desktop/src/app/artifacts/index.tsx
index d87a76a4a65..59c13b62e81 100644
--- a/apps/desktop/src/app/artifacts/index.tsx
+++ b/apps/desktop/src/app/artifacts/index.tsx
@@ -18,7 +18,7 @@ import {
} from '@/components/ui/pagination'
import { RowButton } from '@/components/ui/row-button'
import { Tip } from '@/components/ui/tooltip'
-import { getAllSessionMessages, listAllProfileSessions } from '@/hermes'
+import { getSessionMessages, listAllProfileSessions } from '@/hermes'
import { type Translations, useI18n } from '@/i18n'
import { resolveBrandIcon } from '@/lib/brand-icon'
import {
@@ -138,9 +138,12 @@ export function ArtifactsView({ setStatusbarItemGroup: _setStatusbarItemGroup, .
try {
const sessions = (await listAllProfileSessions(30, 1)).sessions
- const { artifacts: nextArtifacts, failures } = await loadArtifactsForSessions(
- sessions,
- async session => (await getAllSessionMessages(session.id, session.profile)).messages
+ const { artifacts: nextArtifacts, failures } = await loadArtifactsForSessions(sessions, (session, page) =>
+ getSessionMessages(session.id, session.profile, {
+ ...page,
+ includeCompacted: true,
+ order: 'oldest'
+ })
)
if (failures.length > 0) {
diff --git a/apps/desktop/src/app/artifacts/remote-open.test.tsx b/apps/desktop/src/app/artifacts/remote-open.test.tsx
index 5d1cd495b9b..fb9e327a2c0 100644
--- a/apps/desktop/src/app/artifacts/remote-open.test.tsx
+++ b/apps/desktop/src/app/artifacts/remote-open.test.tsx
@@ -18,28 +18,33 @@ const paths = vi.hoisted(() => [
'/srv/absolute.txt'
])
+const getSessionMessages = vi.hoisted(() => vi.fn())
+
vi.mock('@/hermes', async () => ({
...(await vi.importActual('@/hermes')),
listAllProfileSessions: async () => ({
sessions: [{ id: 'artifact-session', title: 'Fixture', profile: 'origin-profile' }]
}),
- getAllSessionMessages: async () => ({
- messages: [
- {
- role: 'assistant',
- timestamp: 1000,
- content: paths.map(path => `MEDIA:${path}`).join(' ') + ' https://example.com/report.txt'
- }
- ]
- })
+ getSessionMessages
}))
afterEach(() => {
cleanup()
$connection.set(null)
+ vi.clearAllMocks()
vi.unstubAllGlobals()
})
it('keeps discovered file paths and originating session scope intact through remote opening', async () => {
+ getSessionMessages.mockResolvedValue({
+ messages: [
+ {
+ role: 'assistant',
+ timestamp: 1000,
+ content: paths.map(path => `MEDIA:${path}`).join(' ') + ' https://example.com/report.txt'
+ }
+ ],
+ session_id: 'artifact-session'
+ })
const saveGatewayFile = vi.fn().mockResolvedValue({ saved: true })
const openExternal = vi.fn()
vi.stubGlobal('hermesDesktop', { saveGatewayFile, openExternal })
@@ -87,4 +92,10 @@ it('keeps discovered file paths and originating session scope intact through rem
)
expect(screen.getByRole('link').getAttribute('href')).toBe('https://example.com/report.txt')
expect(openExternal).not.toHaveBeenCalled()
+ expect(getSessionMessages).toHaveBeenCalledWith('artifact-session', 'origin-profile', {
+ includeCompacted: true,
+ limit: expect.any(Number),
+ offset: 0,
+ order: 'oldest'
+ })
})