Skip to content

The agent that grows with you

fix(desktop): bound the artifact registry's retained content (#108172)

Brooklyn Nicholsonb9f6ab279d4e
diff --git a/apps/desktop/src/store/artifacts.test.ts b/apps/desktop/src/store/artifacts.test.ts
index b8724ec1cab..ec5122e9765 100644
--- a/apps/desktop/src/store/artifacts.test.ts
+++ b/apps/desktop/src/store/artifacts.test.ts
@@ -3,6 +3,7 @@ import { afterEach, beforeEach, describe, expect, it } from 'vitest'
import type { ArtifactDetection } from '@/lib/artifact-detect'
import {
+ $artifactRegistry,
$artifactVersionSelection,
artifactsForSession,
clearArtifactRegistry,
@@ -163,4 +164,92 @@ describe('artifacts store', () => {
expect($previewTabs.get()).toEqual([])
expect(artifactsForSession('session-1')).toEqual([])
})
+
+ it('evicts the oldest historical version when versions exceed the content budget (#108172)', () => {
+ // One unit of headroom under the 4 Mi budget: latest versions are always
+ // retained, so a single artifact with 5 oversized versions must drop its
+ // oldest history while keeping every version's content byte-exact.
+ const chunk = 'x'.repeat(1024 * 1024)
+ const result = upsertArtifact('session-1', HTML_DETECTION, `${chunk} v1`)!
+
+ for (let n = 2; n <= 5; n += 1) {
+ upsertArtifact('session-1', HTML_DETECTION, `${chunk} v${n}`)
+ }
+
+ const record = getArtifact(result.artifactId)!
+
+ // 5 Mi total exceeded the budget; the oldest historical version was
+ // evicted, the newest version survives byte-exact.
+ expect(record.versions.length).toBeLessThan(5)
+ expect(record.versions.at(-1)!.content).toBe(`${chunk} v5`)
+
+ const totalUnits = Object.values($artifactRegistry.get())
+ .flatMap(records => records)
+ .flatMap(record => record.versions)
+ .reduce((sum, version) => sum + version.content.length, 0)
+
+ expect(totalUnits).toBeLessThanOrEqual(4 * 1024 * 1024)
+ })
+
+ it('evicts oldest whole artifact records when latest-only records exceed the budget (#108172)', () => {
+ const chunk = 'y'.repeat(1024 * 1024)
+
+ // Six separate artifacts, each one Mi: cumulative latest-only content
+ // (6 Mi) exceeds the 4 Mi budget, so the oldest whole records go.
+ for (let n = 1; n <= 6; n += 1) {
+ upsertArtifact(`session-${n}`, HTML_DETECTION, `${chunk} a${n}`)
+ }
+
+ const retained = Object.values($artifactRegistry.get()).flatMap(records => records)
+
+ expect(retained.length).toBeLessThan(6)
+
+ const totalUnits = retained
+ .flatMap(record => record.versions)
+ .reduce((sum, version) => sum + version.content.length, 0)
+
+ expect(totalUnits).toBeLessThanOrEqual(4 * 1024 * 1024)
+
+ // The newest record always survives, even when the registry is over budget.
+ expect(retained.some(record => record.versions[0]!.content === `${chunk} a6`)).toBe(true)
+ })
+
+ it('keeps the single newest record even when it alone exceeds the budget (#108172)', () => {
+ const huge = 'z'.repeat(5 * 1024 * 1024)
+ const result = upsertArtifact('session-1', HTML_DETECTION, huge)!
+
+ const record = getArtifact(result.artifactId)!
+
+ expect(record).not.toBeNull()
+ expect(record.versions.at(-1)!.content).toBe(huge)
+ })
+
+ it('follows a pinned selection by hash when pruning shifts version indexes (#108172)', () => {
+ // One artifact with four versions: the FIRST is oversized, the second is
+ // pinned. Going over budget evicts the oldest historical version (v1),
+ // shifting the pinned v2 from index 1 to index 0 while keeping its content.
+ const result = upsertArtifact('session-1', HTML_DETECTION, 'h'.repeat(3 * 1024 * 1024))!
+
+ upsertArtifact('session-1', HTML_DETECTION, 'small-v2')
+ upsertArtifact('session-1', HTML_DETECTION, 'small-v3')
+ upsertArtifact('session-1', HTML_DETECTION, 'small-v4')
+
+ // Pin the SECOND version (index 1) and capture ITS hash.
+ selectArtifactVersion(result.artifactId, 1)
+ const pinnedHash = getArtifact(result.artifactId)!.versions[1]!.hash
+ expect(pinnedHash).toBeTruthy()
+
+ // Push the registry over the 4 Mi budget: the oversized v1 is the oldest
+ // historical version, so pruning evicts exactly it.
+ upsertArtifact('session-2', { ...HTML_DETECTION, title: 'Huge Report' }, 'x'.repeat(1024 * 1024))
+
+ const record = getArtifact(result.artifactId)!
+ const selectionIndex = $artifactVersionSelection.get()[result.artifactId]
+
+ // v1 was evicted; the pinned version survived at a shifted index.
+ expect(record.versions).toHaveLength(3)
+ expect(record.versions.some(version => version.hash === pinnedHash)).toBe(true)
+ expect(selectionIndex).toBe(0)
+ expect(record.versions[selectionIndex!]!.hash).toBe(pinnedHash)
+ })
})
diff --git a/apps/desktop/src/store/artifacts.ts b/apps/desktop/src/store/artifacts.ts
index 4ece3833563..52b894ccfb2 100644
--- a/apps/desktop/src/store/artifacts.ts
+++ b/apps/desktop/src/store/artifacts.ts
@@ -42,10 +42,45 @@ export interface ArtifactRecord {
export type ArtifactRegistry = Record<string, ArtifactRecord[]>
+export const $artifactRegistry = atom<ArtifactRegistry>({})
+
+/** Per-artifact selected version index; absent = newest. */
+export const $artifactVersionSelection = atom<Record<string, number>>({})
+
const MAX_ARTIFACTS_PER_SESSION = 24
const MAX_VERSIONS_PER_ARTIFACT = 20
const MAX_SESSIONS = 40
+/**
+ * Global retained-content budget in UTF-16 code units (the representation
+ * actually held by JS strings). Count caps alone still admit up to
+ * 40×24×20 = 19,200 unbounded content strings; this bounds the duplicate
+ * history the registry pins in memory (#108172). Content is never truncated:
+ * the transcript stays the durable copy, evicted cards re-register on render,
+ * and the single newest record is always retained even when oversized.
+ */
+const MAX_REGISTRY_CONTENT_UNITS = 4 * 1024 * 1024
+
+function recordContentUnits(record: ArtifactRecord): number {
+ let total = 0
+
+ for (const version of record.versions) {
+ total += version.content.length
+ }
+
+ return total
+}
+
+function registryContentUnits(records: readonly ArtifactRecord[]): number {
+ let total = 0
+
+ for (const record of records) {
+ total += recordContentUnits(record)
+ }
+
+ return total
+}
+
function pruneRegistry(registry: ArtifactRegistry): ArtifactRegistry {
const entries = Object.entries(registry)
.map(([sessionId, records]) => {
@@ -64,13 +99,138 @@ function pruneRegistry(registry: ArtifactRegistry): ArtifactRegistry {
})
.slice(0, MAX_SESSIONS)
- return Object.fromEntries(entries)
+ return Object.fromEntries(enforceContentBudget(entries))
}
-export const $artifactRegistry = atom<ArtifactRegistry>({})
+/**
+ * Enforce {@link MAX_REGISTRY_CONTENT_UNITS} after the count caps.
+ *
+ * 1. Evict the globally-oldest HISTORICAL versions first — every record's
+ * latest version survives this pass.
+ * 2. If the latest-only records still exceed the budget, evict the oldest
+ * whole records; the registry's single newest record is always retained,
+ * even when it alone is over budget. Content is never truncated or
+ * rewritten — eviction removes whole version entries / whole records only.
+ * 3. Explicit version selections ($artifactVersionSelection pins by array
+ * index) follow their hash: a selected surviving version keeps pointing at
+ * the same content after index shifts, and a selection whose version was
+ * evicted snaps back to newest.
+ */
+function enforceContentBudget(
+ entries: readonly (readonly [string, ArtifactRecord[]])[]
+): [string, ArtifactRecord[]][] {
+ // Capture each explicitly selected version's hash BEFORE pruning: after the
+ // array shifts, the selection index no longer names the version the user
+ // pinned, so the hash is the only stable handle.
+ const selection = $artifactVersionSelection.get()
+ const selectedHashes = new Map<string, string>()
-/** Per-artifact selected version index; absent = newest. */
-export const $artifactVersionSelection = atom<Record<string, number>>({})
+ for (const [artifactId, index] of Object.entries(selection)) {
+ const hash = findArtifact(Object.fromEntries(entries), artifactId)?.versions[index]?.hash
+
+ if (hash) {
+ selectedHashes.set(artifactId, hash)
+ }
+ }
+
+ const working: [string, ArtifactRecord[]][] = entries.map(([sessionId, records]) => [
+ sessionId,
+ records.map(record => ({ ...record, versions: [...record.versions] }))
+ ])
+
+ if (registryContentUnits(working.flatMap(([, records]) => records)) <= MAX_REGISTRY_CONTENT_UNITS) {
+ return working
+ }
+
+ // Pass 1: drop globally-oldest historical versions until the registry fits.
+ const historical = working
+ .flatMap(([, records]) => records)
+ .flatMap(record => record.versions.slice(0, -1).map(version => ({ record, version })))
+ .sort((left, right) => left.version.createdAt - right.version.createdAt)
+
+ for (const { record, version } of historical) {
+ if (registryContentUnits(working.flatMap(([, records]) => records)) <= MAX_REGISTRY_CONTENT_UNITS) {
+ break
+ }
+
+ record.versions = record.versions.filter(candidate => candidate !== version)
+ }
+
+ // Pass 2: latest-only records still over budget — evict the oldest whole
+ // records until the registry fits. The registry's newest record is never
+ // evicted, even when it alone is oversized.
+ const byAge = working
+ .flatMap(([sessionId, records]) => records.map(record => ({ record, sessionId })))
+ .sort((left, right) => left.record.updatedAt - right.record.updatedAt)
+
+ for (const { record, sessionId } of byAge) {
+ if (registryContentUnits(working.flatMap(([, records]) => records)) <= MAX_REGISTRY_CONTENT_UNITS) {
+ break
+ }
+
+ const retained = working.flatMap(([, records]) => records)
+
+ if (retained.length <= 1) {
+ break
+ }
+
+ const sessionEntry = working.find(([id]) => id === sessionId)
+
+ if (sessionEntry) {
+ sessionEntry[1] = sessionEntry[1].filter(candidate => candidate !== record)
+ }
+ }
+
+ reconcileVersionSelection(working, selectedHashes)
+
+ return working.filter(([, records]) => records.length > 0)
+}
+
+/**
+ * Re-point explicit version selections after pruning shifted version arrays.
+ * The hash of each selected version is captured against the pruned records:
+ * a selected surviving version keeps pointing at the same content (whatever
+ * its new index), and a selection whose version was evicted snaps back to
+ * newest (absent = newest).
+ */
+function reconcileVersionSelection(
+ entries: readonly (readonly [string, ArtifactRecord[]])[],
+ selectedHashes: ReadonlyMap<string, string>
+): void {
+ const selection = $artifactVersionSelection.get()
+ const prunedById = new Map<string, ArtifactRecord>()
+
+ for (const [, records] of entries) {
+ for (const record of records) {
+ prunedById.set(record.id, record)
+ }
+ }
+
+ let updated: Record<string, number> | null = null
+
+ for (const [artifactId, selectedHash] of selectedHashes) {
+ const record = prunedById.get(artifactId)
+ const next: Record<string, number> = updated ?? { ...selection }
+ const newIndex = record?.versions.findIndex(version => version.hash === selectedHash) ?? -1
+
+ if (newIndex < 0 || newIndex === record!.versions.length - 1) {
+ // Selected version was evicted (or the record went away, or pruning
+ // left it as the newest): absent = newest.
+ delete next[artifactId]
+ updated = next
+ continue
+ }
+
+ if (newIndex !== selection[artifactId]) {
+ next[artifactId] = newIndex
+ updated = next
+ }
+ }
+
+ if (updated) {
+ $artifactVersionSelection.set(updated)
+ }
+}
/** Lookup against a registry value, for components that already subscribe to
* the atom and need the record to change identity when it does. */