Self-evolving Context Database for AI Agents. Unify Agent Memory, Knowledge RAG and Skills.
Python agent-contextagent-memoryagent-pluginsagentic-ragcontext-databasedsh-pluginknowledge-basememorymemory-managementself-evolvingvector-database
feat(web-studio): add Agent Experience module (#4716)
yufengc3977d9775e0
diff --git a/web-studio/src/components/app-shell.tsx b/web-studio/src/components/app-shell.tsxindex cf3d9ee2f..36399a5fa 100644--- a/web-studio/src/components/app-shell.tsx+++ b/web-studio/src/components/app-shell.tsx@@ -4,6 +4,7 @@ import {BlocksIcon,BookOpenIcon,BracesIcon,+ BrainCircuitIcon,ChevronRightIcon,ClipboardListIcon,Clock3Icon,@@ -109,6 +110,13 @@ const NAV_ITEMS: readonly NavItem[] = [titleKey: 'navigation.skills.title',to: '/skills',},+ {+ icon: BrainCircuitIcon,+ id: 'agentExperience',+ section: 'workspace',+ titleKey: 'navigation.agentExperience.title',+ to: '/agent-experience',+ },{icon: BlocksIcon,id: 'sessions',diff --git a/web-studio/src/components/current-user-menu.interaction.test.tsx b/web-studio/src/components/current-user-menu.interaction.test.tsxindex 080e6290a..21f24bb75 100644--- a/web-studio/src/components/current-user-menu.interaction.test.tsx+++ b/web-studio/src/components/current-user-menu.interaction.test.tsx@@ -8,6 +8,7 @@ import {screen,waitFor,} from '@testing-library/react'+import userEvent from '@testing-library/user-event'import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'import { CurrentUserMenu } from './current-user-menu'@@ -24,6 +25,8 @@ const connectionMocks = vi.hoisted(() => ({baseUrl: 'http://localhost:1933',userId: 'alice',},+ connectionRole: 'root',+ isConnectionRoleLoading: false,serverMode: 'trusted',switchIdentity: vi.fn(),}))@@ -64,6 +67,8 @@ function renderMenu() {beforeEach(() => {connectionMocks.connection.adminApiKey = 'root-key'+ connectionMocks.connectionRole = 'root'+ connectionMocks.isConnectionRoleLoading = falseconnectionMocks.serverMode = 'trusted'connectionMocks.switchIdentity.mockResolvedValue(undefined)adminMocks.fetchAdminUsers.mockResolvedValue([@@ -93,8 +98,13 @@ describe('CurrentUserMenu', () => {screen.getByRole('button', { name: 'header.currentUser.openMenu' }),)- const bob = await screen.findByRole('button', { name: 'bob' })- fireEvent.click(bob)+ const selector = await screen.findByRole('combobox', {+ name: 'header.currentUser.switchUser',+ })+ expect(screen.queryByRole('option', { name: 'bob' })).toBeNull()+ await userEvent.click(selector)+ const bob = await screen.findByRole('option', { name: 'bob' })+ await userEvent.click(bob)await waitFor(() => {expect(connectionMocks.switchIdentity).toHaveBeenCalledWith({@@ -109,8 +119,49 @@ describe('CurrentUserMenu', () => {)})- it('keeps non-trusted user menus read-only', () => {+ it('switches API-key identities when management access exposes a user key', async () => {connectionMocks.serverMode = 'api_key'+ adminMocks.fetchAdminUsers.mockResolvedValue([+ {+ accountId: 'account-a',+ apiKey: 'alice-key',+ role: 'admin',+ userId: 'alice',+ },+ {+ accountId: 'account-a',+ apiKey: 'bob-key',+ role: 'user',+ userId: 'bob',+ },+ ])+ renderMenu()++ fireEvent.click(+ screen.getByRole('button', { name: 'header.currentUser.openMenu' }),+ )++ const selector = await screen.findByRole('combobox', {+ name: 'header.currentUser.switchUser',+ })+ expect(screen.queryByRole('option', { name: 'bob' })).toBeNull()+ await userEvent.click(selector)+ const bob = await screen.findByRole('option', { name: 'bob' })+ await userEvent.click(bob)++ await waitFor(() => {+ expect(connectionMocks.switchIdentity).toHaveBeenCalledWith({+ accountId: 'account-a',+ allowLegacyIdentityFallback: true,+ apiKey: 'bob-key',+ userId: 'bob',+ })+ })+ })++ it('keeps ordinary API-key user menus read-only', () => {+ connectionMocks.serverMode = 'api_key'+ connectionMocks.connectionRole = 'user'renderMenu()fireEvent.click(@@ -121,6 +172,38 @@ describe('CurrentUserMenu', () => {expect(adminMocks.fetchAdminUsers).not.toHaveBeenCalled()})+ it('disables API-key identities whose secret is unavailable', async () => {+ connectionMocks.serverMode = 'api_key'+ adminMocks.fetchAdminUsers.mockResolvedValue([+ {+ accountId: 'account-a',+ apiKey: 'alice-key',+ role: 'admin',+ userId: 'alice',+ },+ {+ accountId: 'account-a',+ keyPrefix: 'ovk_bob',+ role: 'user',+ userId: 'bob',+ },+ ])+ renderMenu()++ fireEvent.click(+ screen.getByRole('button', { name: 'header.currentUser.openMenu' }),+ )++ const selector = await screen.findByRole('combobox', {+ name: 'header.currentUser.switchUser',+ })+ expect(screen.queryByRole('option', { name: 'bob' })).toBeNull()+ await userEvent.click(selector)+ const bob = await screen.findByRole('option', { name: 'bob' })+ expect(bob.getAttribute('aria-disabled')).toBe('true')+ expect(screen.getByText('header.currentUser.keyUnavailable')).toBeTruthy()+ })+it('accepts a user ID when trusted mode has no user directory', async () => {connectionMocks.connection.adminApiKey = ''renderMenu()diff --git a/web-studio/src/components/current-user-menu.tsx b/web-studio/src/components/current-user-menu.tsxindex 13a3c9857..229f6430b 100644--- a/web-studio/src/components/current-user-menu.tsx+++ b/web-studio/src/components/current-user-menu.tsx@@ -2,7 +2,6 @@ import * as React from 'react'import { useQuery } from '@tanstack/react-query'import {Building2Icon,- CheckIcon,ChevronDownIcon,LoaderCircleIcon,UserRoundIcon,@@ -15,9 +14,17 @@ import {PopoverContent,PopoverTrigger,} from '#/components/ui/popover'+import {+ Select,+ SelectContent,+ SelectItem,+ SelectTrigger,+ SelectValue,+} from '#/components/ui/select'import { useAppConnection } from '#/hooks/use-app-connection'import { fetchAdminUsers } from '#/lib/admin'import type { AdminConnection } from '#/lib/admin'+import { resolveStudioManagementCapabilities } from '#/lib/studio-permissions'export function getUserInitial(userId: string): string {const normalizedUserId = userId.trim()@@ -26,15 +33,28 @@ export function getUserInitial(userId: string): string {export function CurrentUserMenu() {const { t } = useTranslation('appShell')- const { connection, serverMode, switchIdentity } = useAppConnection()+ const {+ connection,+ connectionRole,+ isConnectionRoleLoading,+ serverMode,+ switchIdentity,+ } = useAppConnection()const [open, setOpen] = React.useState(false)const [manualUserId, setManualUserId] = React.useState('')const [switchingUserId, setSwitchingUserId] = React.useState('')const { accountId, userId } = connectionconst accountLabel = accountId || t('header.currentUser.unset')const userLabel = userId || t('header.currentUser.unset')- const canSwitchUser = serverMode === 'trusted' && Boolean(accountId)- const canListUsers = Boolean(connection.adminApiKey)+ const { canManageUsers } = resolveStudioManagementCapabilities({+ hasControlCredential: Boolean(connection.adminApiKey.trim()),+ isRoleLoading: isConnectionRoleLoading,+ role: connectionRole,+ serverMode,+ })+ const canSwitchUser =+ Boolean(accountId) && (serverMode === 'trusted' || canManageUsers)+ const canListUsers = canManageUsersconst manualTargetUserId = manualUserId.trim()const adminConnection = React.useMemo<AdminConnection>(() => ({@@ -57,7 +77,10 @@ export function CurrentUserMenu() {retry: false,})- async function selectUser(nextUserId: string): Promise<void> {+ async function selectUser(+ nextUserId: string,+ nextApiKey = '',+ ): Promise<void> {const normalizedUserId = nextUserId.trim()if (!normalizedUserId || normalizedUserId === userId) {return@@ -68,7 +91,7 @@ export function CurrentUserMenu() {await switchIdentity({accountId,allowLegacyIdentityFallback: true,- apiKey: '',+ apiKey: serverMode === 'trusted' ? '' : nextApiKey,userId: normalizedUserId,})setManualUserId('')@@ -136,107 +159,120 @@ export function CurrentUserMenu() {<dt className="w-16 shrink-0 text-xs text-muted-foreground">{t('header.currentUser.user')}</dt>- <dd className="min-w-0 flex-1 truncate text-right text-xs font-medium">- {userLabel}- </dd>- </div>- </dl>-- {canSwitchUser ? (- <div className="border-t p-1.5">- <p className="px-2.5 py-1.5 text-[11px] font-semibold uppercase tracking-[0.1em] text-muted-foreground">- {t('header.currentUser.switchUser')}- </p>- <div className="max-h-56 overflow-y-auto">- {!canListUsers ? (- <form- className="grid gap-2 p-2"- onSubmit={(event) => {- event.preventDefault()- void selectUser(manualTargetUserId)- }}- >- <label className="sr-only" htmlFor="trusted-user-id">- {t('header.currentUser.userId')}- </label>- <input- id="trusted-user-id"- type="text"- autoComplete="off"- value={manualUserId}- className="h-9 rounded-md border bg-background px-3 text-sm outline-none placeholder:text-muted-foreground focus-visible:ring-2 focus-visible:ring-ring"- placeholder={t('header.currentUser.userIdPlaceholder')}- onChange={(event) => setManualUserId(event.target.value)}- />- <button- type="submit"- disabled={- !manualTargetUserId ||- manualTargetUserId === userId ||- Boolean(switchingUserId)- }- className="flex h-9 items-center justify-center gap-2 rounded-md bg-primary px-3 text-sm font-medium text-primary-foreground transition-opacity disabled:cursor-not-allowed disabled:opacity-50"- >- {switchingUserId ? (+ <dd className="min-w-0 flex-1 text-right text-xs font-medium">+ {canSwitchUser ? (+ <div>+ {!canListUsers ? (+ <form+ className="grid gap-2"+ onSubmit={(event) => {+ event.preventDefault()+ void selectUser(manualTargetUserId)+ }}+ >+ <label className="sr-only" htmlFor="trusted-user-id">+ {t('header.currentUser.userId')}+ </label>+ <input+ id="trusted-user-id"+ type="text"+ autoComplete="off"+ value={manualUserId}+ className="h-9 rounded-md border bg-background px-3 text-sm outline-none placeholder:text-muted-foreground focus-visible:ring-2 focus-visible:ring-ring"+ placeholder={t('header.currentUser.userIdPlaceholder')}+ onChange={(event) =>+ setManualUserId(event.target.value)+ }+ />+ <button+ type="submit"+ disabled={+ !manualTargetUserId ||+ manualTargetUserId === userId ||+ Boolean(switchingUserId)+ }+ className="flex h-9 items-center justify-center gap-2 rounded-md bg-primary px-3 text-sm font-medium text-primary-foreground transition-opacity disabled:cursor-not-allowed disabled:opacity-50"+ >+ {switchingUserId ? (+ <LoaderCircleIcon className="size-3.5 animate-spin" />+ ) : null}+ {t('header.currentUser.switchAction')}+ </button>+ </form>+ ) : usersQuery.isLoading ? (+ <div className="flex items-center justify-center gap-2 px-3 py-5 text-xs text-muted-foreground"><LoaderCircleIcon className="size-3.5 animate-spin" />- ) : null}- {t('header.currentUser.switchAction')}- </button>- </form>- ) : usersQuery.isLoading ? (- <div className="flex items-center justify-center gap-2 px-3 py-5 text-xs text-muted-foreground">- <LoaderCircleIcon className="size-3.5 animate-spin" />- {t('header.currentUser.loadingUsers')}- </div>- ) : usersQuery.isError ? (- <div className="grid gap-2 px-2.5 py-3 text-center">- <p className="text-xs text-destructive">- {t('header.currentUser.loadUsersFailed')}- </p>- <button- type="button"- className="text-xs font-medium text-primary hover:underline"- onClick={() => void usersQuery.refetch()}- >- {t('header.currentUser.retry')}- </button>+ {t('header.currentUser.loadingUsers')}+ </div>+ ) : usersQuery.isError ? (+ <div className="grid gap-2 px-2.5 py-3 text-center">+ <p className="text-xs text-destructive">+ {t('header.currentUser.loadUsersFailed')}+ </p>+ <button+ type="button"+ className="text-xs font-medium text-primary hover:underline"+ onClick={() => void usersQuery.refetch()}+ >+ {t('header.currentUser.retry')}+ </button>+ </div>+ ) : usersQuery.data?.length ? (+ <div>+ <Select+ value={userId}+ onValueChange={(nextUserId) => {+ const user = usersQuery.data.find(+ (item) => item.userId === nextUserId,+ )+ if (user) void selectUser(user.userId, user.apiKey)+ }}+ >+ <SelectTrigger+ aria-label={t('header.currentUser.switchUser')}+ className="h-8 w-full justify-end border-transparent bg-transparent px-2 text-xs shadow-none hover:bg-accent"+ disabled={Boolean(switchingUserId)}+ >+ {switchingUserId ? (+ <LoaderCircleIcon className="size-3.5 animate-spin" />+ ) : null}+ <SelectValue>{userLabel}</SelectValue>+ </SelectTrigger>+ <SelectContent>+ {usersQuery.data.map((user) => {+ const canUseIdentity =+ serverMode === 'trusted' || Boolean(user.apiKey)+ return (+ <SelectItem+ key={user.userId}+ value={user.userId}+ aria-label={user.userId}+ disabled={!canUseIdentity}+ >+ {user.userId}+ {!canUseIdentity ? (+ <span className="text-[10px] text-muted-foreground">+ {t('header.currentUser.keyUnavailable')}+ </span>+ ) : null}+ </SelectItem>+ )+ })}+ </SelectContent>+ </Select>+ </div>+ ) : (+ <p className="px-2.5 py-4 text-center text-xs text-muted-foreground">+ {t('header.currentUser.noUsers')}+ </p>+ )}</div>- ) : usersQuery.data?.length ? (- usersQuery.data.map((user) => {- const current = user.userId === userId- const switching = switchingUserId === user.userId- return (- <button- key={user.userId}- type="button"- aria-current={current ? 'true' : undefined}- aria-label={user.userId}- disabled={current || Boolean(switchingUserId)}- className="flex w-full items-center gap-2 rounded-md px-2.5 py-2 text-left transition-colors hover:bg-accent disabled:cursor-default disabled:opacity-70"- onClick={() => void selectUser(user.userId)}- >- <span className="flex size-7 shrink-0 items-center justify-center rounded-md border bg-background text-xs font-semibold">- {getUserInitial(user.userId)}- </span>- <span className="min-w-0 flex-1 truncate text-sm font-medium">- {user.userId}- </span>- {switching ? (- <LoaderCircleIcon className="size-3.5 animate-spin" />- ) : current ? (- <CheckIcon className="size-3.5 text-primary" />- ) : null}- </button>- )- })) : (- <p className="px-2.5 py-4 text-center text-xs text-muted-foreground">- {t('header.currentUser.noUsers')}- </p>+ userLabel)}- </div>+ </dd></div>- ) : null}+ </dl></PopoverContent></Popover>)diff --git a/web-studio/src/i18n/locales/en/activity.ts b/web-studio/src/i18n/locales/en/activity.tsindex e3331ecc6..9d109fbe5 100644--- a/web-studio/src/i18n/locales/en/activity.ts+++ b/web-studio/src/i18n/locales/en/activity.ts@@ -71,6 +71,7 @@ const activity = {loadFailed: 'Could not load memory changes',retry: 'Retry',empty: 'This session commit did not produce any memory changes.',+ viewExperienceImpact: 'View impact for this experience',},empty: {description: 'Select a session from the list or create a new one.',diff --git a/web-studio/src/i18n/locales/en/workspace.ts b/web-studio/src/i18n/locales/en/workspace.tsindex c50bae058..6d7c46b49 100644--- a/web-studio/src/i18n/locales/en/workspace.ts+++ b/web-studio/src/i18n/locales/en/workspace.ts@@ -12,6 +12,7 @@ const workspace = {currentUser: {account: 'Account',accountSummary: 'Account · {{account}}',+ keyUnavailable: 'User key unavailable',loadingUsers: 'Loading users',loadUsersFailed: 'Failed to load users',noUsers: 'No users in this account',@@ -47,6 +48,9 @@ const workspace = {skills: {title: 'Skills',},+ agentExperience: {+ title: 'Agent Experience',+ },tasks: {title: 'Task Center',},@@ -203,6 +207,125 @@ const workspace = {action: 'Open connection settings',},},+ agentExperiencePage: {+ title: 'Agent Experience',+ description:+ 'Track experiences distilled from committed sessions, along with the trajectories and outcomes produced after they are applied.',+ refresh: 'Refresh',+ searchPlaceholder: 'Search this page by name or URI',+ searchClear: 'Clear',+ searchNoResults: 'No matching experiences on this page',+ searchNoResultsDescription:+ 'Clear the search or switch pages to continue browsing.',+ loading: 'Loading experiences...',+ loadFailed: 'Could not load experiences',+ networkError:+ 'Could not connect to the OpenViking service. Check the server URL and connection status.',+ connectionSettings: 'Open connection settings',+ empty: 'No Agent experiences yet',+ emptyDescription:+ 'Experiences are distilled automatically from committed sessions. Once a session is committed, reusable experiences will appear here.',+ emptyAction: 'Go to Sessions',+ directoryHint: 'memories / experiences',+ updated: 'Updated {{time}}',+ updatedBadge: 'Updated',+ columnFile: 'Experience file',+ columnUpdated: 'Updated',+ columnActions: 'Actions',+ viewAnalysis: 'Impact',+ openDetail: 'View impact for {{name}}',+ pagination: {+ summary: 'Page {{page}}',+ pageSize: 'Rows per page',+ pageSizeValue: '{{count}} / page',+ previous: 'Previous',+ next: 'Next',+ },+ help: {+ title: 'No experiences yet? Check:',+ reasonConnected: 'Whether the Agent is connected to OpenViking',+ reasonSessions: 'Whether new sessions ran after connecting',+ reasonCommit: 'Whether those sessions were committed to OpenViking',+ },+ settings: {+ title: 'Experience settings',+ description:+ 'Agent Evolution switch for the target account. When off, new session commits in that account stop extracting experiences and trajectories.',+ targetAccount: 'Target account: {{account}}',+ unknownAccount: 'Unconfirmed',+ scopeMismatch:+ 'The API target account differs from the current account or cannot be confirmed. Changes are disabled. Use an administrator credential for the current account.',+ loading: 'Reading switch status...',+ loadFailed: 'Could not read switch status',+ statusEnabled: 'Enabled',+ statusDisabled: 'Disabled',+ statusEnabledHint:+ 'Session commits extract experiences and trajectories.',+ statusDisabledHint:+ 'While disabled no new experiences or trajectories are produced, and impact panels stay empty.',+ pending: 'Applying...',+ enabledToast: 'Agent Experience enabled',+ disabledToast: 'Agent Experience disabled',+ toggleFailed: 'Could not update the switch',+ },+ detail: {+ back: 'Back',+ copyUri: 'Copy URI',+ openPlayground: 'Open in Workbench',+ copied: 'Copied',+ copyFailed: 'Copy failed',+ contentTitle: 'Experience content',+ contentLoading: 'Loading experience content...',+ contentLoadFailed: 'Could not load experience content',+ analysisTitle: 'Application impact',+ analysisDescription:+ 'Trajectories and task outcomes produced by commits that read this experience.',+ tabImpact: 'Impact',+ tabSource: 'Source',+ sourceTitle: 'Source trace',+ sourceDescription:+ 'Trajectories that generated and evolved this experience, via experience relations.',+ sourceLoading: 'Loading source relations...',+ sourceLoadFailed: 'Could not load source relations',+ sourceEmpty:+ 'No source relations yet. Links are established as later commits evolve this experience.',+ rangeLabel: 'Time range',+ rangeAll: 'All time',+ range7d: 'Last 7 days',+ range30d: 'Last 30 days',+ rangeCustom: 'Custom',+ rangeStart: 'Start date (UTC)',+ rangeEnd: 'End date (UTC)',+ rangeApply: 'Apply',+ rangeCancel: 'Cancel',+ rangeOrderError: 'Start date must not be after end date',+ rangeInvalidError: 'Invalid date format, expected YYYY-MM-DD',+ rangeUtcHint: 'Filtered by UTC date',+ outcomeTitle: 'Outcome distribution',+ outcomeTotal: '{{count}} trajectories',+ outcomeEmpty: 'No applied trajectories in this time range',+ outcomeEmptyDescription:+ 'This experience has not been applied yet, or its trajectories carry no outcome tags. Switch to “All time” to see historical trajectories.',+ trajectoriesTitle: 'Applied trajectories',+ trajectoriesLoadFailed: 'Could not load trajectories',+ trajectoryView: 'View trajectory {{name}}',+ loadMore: 'Load more',+ loadingMore: 'Loading...',+ noMore: 'All {{count}} trajectories shown',+ previewTitle: 'Trajectory content',+ previewLoading: 'Loading trajectory content...',+ previewLoadFailed: 'Could not load trajectory content',+ totalApplied: 'Applied {{count}} times',+ successRate: '{{rate}}% success',+ },+ outcomes: {+ success: 'Success',+ failure: 'Failure',+ partial: 'Partial',+ unknown: 'Unknown',+ unfinished: 'Unfinished',+ },+ },skillsPage: {title: 'Skills',description:diff --git a/web-studio/src/i18n/locales/zh-CN/activity.ts b/web-studio/src/i18n/locales/zh-CN/activity.tsindex e82cfbb35..dd45fb7e2 100644--- a/web-studio/src/i18n/locales/zh-CN/activity.ts+++ b/web-studio/src/i18n/locales/zh-CN/activity.ts@@ -71,6 +71,7 @@ const activity = {loadFailed: '记忆变更加载失败',retry: '重试',empty: '本次会话提交没有产生记忆变更。',+ viewExperienceImpact: '查看该经验的应用效果',},empty: {description: '从左侧选择一个会话,或创建新会话。',diff --git a/web-studio/src/i18n/locales/zh-CN/workspace.ts b/web-studio/src/i18n/locales/zh-CN/workspace.tsindex da7df1e16..f2f5151e5 100644--- a/web-studio/src/i18n/locales/zh-CN/workspace.ts+++ b/web-studio/src/i18n/locales/zh-CN/workspace.ts@@ -12,6 +12,7 @@ const workspace = {currentUser: {account: '账号',accountSummary: '账号 · {{account}}',+ keyUnavailable: '用户凭证不可用',loadingUsers: '正在加载用户',loadUsersFailed: '用户列表加载失败',noUsers: '当前账号暂无用户',@@ -47,6 +48,9 @@ const workspace = {skills: {title: '技能',},+ agentExperience: {+ title: 'Agent 经验',+ },tasks: {title: '任务中心',},@@ -202,6 +206,120 @@ const workspace = {action: '打开连接设置',},},+ agentExperiencePage: {+ title: 'Agent 经验',+ description:+ '跟踪从会话提交中沉淀的经验资产,以及经验被应用后的执行轨迹与结果分布。',+ refresh: '刷新',+ searchPlaceholder: '搜索当前页的经验名称或 URI',+ searchClear: '清除',+ searchNoResults: '当前页没有匹配的经验',+ searchNoResultsDescription: '可清除搜索条件,或切换页面继续查看。',+ loading: '正在加载经验列表...',+ loadFailed: '经验列表加载失败',+ networkError: '无法连接 OpenViking 服务,请检查服务地址和连接状态。',+ connectionSettings: '打开连接设置',+ empty: '还没有 Agent 经验',+ emptyDescription:+ '经验由已提交的会话自动提取。提交一个会话后,可复用的经验会出现在这里。',+ emptyAction: '前往会话',+ directoryHint: 'memories / experiences',+ updated: '更新于 {{time}}',+ updatedBadge: '有更新',+ columnFile: '经验文件',+ columnUpdated: '更新时间',+ columnActions: '操作',+ viewAnalysis: '应用效果',+ openDetail: '查看 {{name}} 的应用效果',+ pagination: {+ summary: '第 {{page}} 页',+ pageSize: '每页条数',+ pageSizeValue: '{{count}} 条/页',+ previous: '上一页',+ next: '下一页',+ },+ help: {+ title: '一直无经验产生?请检查:',+ reasonConnected: 'Agent 是否已接入 OpenViking',+ reasonSessions: '接入后是否产生了新的会话',+ reasonCommit: '会话是否已提交(commit)到 OpenViking',+ },+ settings: {+ title: '经验设置',+ description:+ '作用账号的 Agent Evolution 开关。关闭后,该账号的新会话提交将停止提取经验与轨迹。',+ targetAccount: '作用账号:{{account}}',+ unknownAccount: '无法确认',+ scopeMismatch:+ '接口返回的作用账号与当前账号不一致或无法确认,已禁止修改。请使用当前账号的管理凭证。',+ loading: '正在读取开关状态...',+ loadFailed: '开关状态读取失败',+ statusEnabled: '已启用',+ statusDisabled: '已停用',+ statusEnabledHint: '会话提交会提取经验与轨迹。',+ statusDisabledHint:+ '停用期间不会产生新的经验与轨迹,应用效果将始终为空。',+ pending: '正在生效...',+ enabledToast: 'Agent 经验已启用',+ disabledToast: 'Agent 经验已停用',+ toggleFailed: '开关设置失败',+ },+ detail: {+ back: '返回',+ copyUri: '复制 URI',+ openPlayground: '在工作台中打开',+ copied: '已复制',+ copyFailed: '复制失败',+ contentTitle: '经验内容',+ contentLoading: '正在加载经验内容...',+ contentLoadFailed: '经验内容加载失败',+ analysisTitle: '应用效果',+ analysisDescription: '读取过该经验的会话提交所产生的轨迹与任务结果分布。',+ tabImpact: '应用效果',+ tabSource: '来源追溯',+ sourceTitle: '来源追溯',+ sourceDescription:+ '当前经验由哪些轨迹生成及演进(基于经验与轨迹的关联关系)。',+ sourceLoading: '正在加载来源关系...',+ sourceLoadFailed: '来源关系加载失败',+ sourceEmpty: '暂无来源关系。经验首次提取时的关联会在后续提交后逐步建立。',+ rangeLabel: '时间范围',+ rangeAll: '全部',+ range7d: '近 7 天',+ range30d: '近 30 天',+ rangeCustom: '自定义',+ rangeStart: '开始日期(UTC)',+ rangeEnd: '结束日期(UTC)',+ rangeApply: '应用',+ rangeCancel: '取消',+ rangeOrderError: '开始日期不能晚于结束日期',+ rangeInvalidError: '日期格式无效,应为 YYYY-MM-DD',+ rangeUtcHint: '按 UTC 日期过滤',+ outcomeTitle: '结果分布',+ outcomeTotal: '共 {{count}} 条轨迹',+ outcomeEmpty: '选定时间范围内暂无应用轨迹',+ outcomeEmptyDescription:+ '该经验尚未被读取应用,或轨迹未产生结果标签。尝试切换到“全部”查看历史轨迹。',+ trajectoriesTitle: '应用轨迹',+ trajectoriesLoadFailed: '应用轨迹加载失败',+ trajectoryView: '查看轨迹 {{name}}',+ loadMore: '加载更多',+ loadingMore: '正在加载...',+ noMore: '已显示全部 {{count}} 条轨迹',+ previewTitle: '轨迹内容',+ previewLoading: '正在加载轨迹内容...',+ previewLoadFailed: '轨迹内容加载失败',+ totalApplied: '应用 {{count}} 次',+ successRate: '{{rate}}% 成功',+ },+ outcomes: {+ success: '成功',+ failure: '失败',+ partial: '部分完成',+ unknown: '未知结果',+ unfinished: '未完成',+ },+ },skillsPage: {title: '技能',description: '查看当前用户和当前空间可用的 Agent 技能。',diff --git a/web-studio/src/routeTree.gen.ts b/web-studio/src/routeTree.gen.tsindex d883864d5..0784ed8d6 100644--- a/web-studio/src/routeTree.gen.ts+++ b/web-studio/src/routeTree.gen.ts@@ -20,10 +20,13 @@ import { Route as RequestLogsRouteRouteImport } from './routes/request-logs/routimport { Route as PlaygroundRouteRouteImport } from './routes/playground/route'import { Route as MonitoringRouteRouteImport } from './routes/monitoring/route'import { Route as HomeRouteRouteImport } from './routes/home/route'+import { Route as AgentExperienceRouteRouteImport } from './routes/agent-experience/route'import { Route as IndexRouteImport } from './routes/index'import { Route as SessionsIndexRouteImport } from './routes/sessions/index'+import { Route as AgentExperienceIndexRouteImport } from './routes/agent-experience/index'import { Route as OauthVerifyRouteImport } from './routes/oauth/verify'import { Route as OauthConsentRouteImport } from './routes/oauth/consent'+import { Route as AgentExperienceExperienceUriRouteImport } from './routes/agent-experience/$experienceUri'const WatchesRouteRoute = WatchesRouteRouteImport.update({id: '/watches',@@ -80,6 +83,11 @@ const HomeRouteRoute = HomeRouteRouteImport.update({path: '/home',getParentRoute: () => rootRouteImport,} as any)+const AgentExperienceRouteRoute = AgentExperienceRouteRouteImport.update({+ id: '/agent-experience',+ path: '/agent-experience',+ getParentRoute: () => rootRouteImport,+} as any)const IndexRoute = IndexRouteImport.update({id: '/',path: '/',@@ -90,6 +98,11 @@ const SessionsIndexRoute = SessionsIndexRouteImport.update({path: '/',getParentRoute: () => SessionsRouteRoute,} as any)+const AgentExperienceIndexRoute = AgentExperienceIndexRouteImport.update({+ id: '/',+ path: '/',+ getParentRoute: () => AgentExperienceRouteRoute,+} as any)const OauthVerifyRoute = OauthVerifyRouteImport.update({id: '/oauth/verify',path: '/oauth/verify',@@ -100,9 +113,16 @@ const OauthConsentRoute = OauthConsentRouteImport.update({path: '/oauth/consent',getParentRoute: () => rootRouteImport,} as any)+const AgentExperienceExperienceUriRoute =+ AgentExperienceExperienceUriRouteImport.update({+ id: '/$experienceUri',+ path: '/$experienceUri',+ getParentRoute: () => AgentExperienceRouteRoute,+ } as any)export interface FileRoutesByFullPath {'/': typeof IndexRoute+ '/agent-experience': typeof AgentExperienceRouteRouteWithChildren'/home': typeof HomeRouteRoute'/monitoring': typeof MonitoringRouteRoute'/playground': typeof PlaygroundRouteRoute@@ -114,8 +134,10 @@ export interface FileRoutesByFullPath {'/tasks': typeof TasksRouteRoute'/users': typeof UsersRouteRoute'/watches': typeof WatchesRouteRoute+ '/agent-experience/$experienceUri': typeof AgentExperienceExperienceUriRoute'/oauth/consent': typeof OauthConsentRoute'/oauth/verify': typeof OauthVerifyRoute+ '/agent-experience/': typeof AgentExperienceIndexRoute'/sessions/': typeof SessionsIndexRoute}export interface FileRoutesByTo {@@ -130,13 +152,16 @@ export interface FileRoutesByTo {'/tasks': typeof TasksRouteRoute'/users': typeof UsersRouteRoute'/watches': typeof WatchesRouteRoute+ '/agent-experience/$experienceUri': typeof AgentExperienceExperienceUriRoute'/oauth/consent': typeof OauthConsentRoute'/oauth/verify': typeof OauthVerifyRoute+ '/agent-experience': typeof AgentExperienceIndexRoute'/sessions': typeof SessionsIndexRoute}export interface FileRoutesById {__root__: typeof rootRouteImport'/': typeof IndexRoute+ '/agent-experience': typeof AgentExperienceRouteRouteWithChildren'/home': typeof HomeRouteRoute'/monitoring': typeof MonitoringRouteRoute'/playground': typeof PlaygroundRouteRoute@@ -148,14 +173,17 @@ export interface FileRoutesById {'/tasks': typeof TasksRouteRoute'/users': typeof UsersRouteRoute'/watches': typeof WatchesRouteRoute+ '/agent-experience/$experienceUri': typeof AgentExperienceExperienceUriRoute'/oauth/consent': typeof OauthConsentRoute'/oauth/verify': typeof OauthVerifyRoute+ '/agent-experience/': typeof AgentExperienceIndexRoute'/sessions/': typeof SessionsIndexRoute}export interface FileRouteTypes {fileRoutesByFullPath: FileRoutesByFullPathfullPaths:| '/'+ | '/agent-experience'| '/home'| '/monitoring'| '/playground'@@ -167,8 +195,10 @@ export interface FileRouteTypes {| '/tasks'| '/users'| '/watches'+ | '/agent-experience/$experienceUri'| '/oauth/consent'| '/oauth/verify'+ | '/agent-experience/'| '/sessions/'fileRoutesByTo: FileRoutesByToto:@@ -183,12 +213,15 @@ export interface FileRouteTypes {| '/tasks'| '/users'| '/watches'+ | '/agent-experience/$experienceUri'| '/oauth/consent'| '/oauth/verify'+ | '/agent-experience'| '/sessions'id:| '__root__'| '/'+ | '/agent-experience'| '/home'| '/monitoring'| '/playground'@@ -200,13 +233,16 @@ export interface FileRouteTypes {| '/tasks'| '/users'| '/watches'+ | '/agent-experience/$experienceUri'| '/oauth/consent'| '/oauth/verify'+ | '/agent-experience/'| '/sessions/'fileRoutesById: FileRoutesById}export interface RootRouteChildren {IndexRoute: typeof IndexRoute+ AgentExperienceRouteRoute: typeof AgentExperienceRouteRouteWithChildrenHomeRouteRoute: typeof HomeRouteRouteMonitoringRouteRoute: typeof MonitoringRouteRoutePlaygroundRouteRoute: typeof PlaygroundRouteRoute@@ -301,6 +337,13 @@ declare module '@tanstack/react-router' {preLoaderRoute: typeof HomeRouteRouteImportparentRoute: typeof rootRouteImport}+ '/agent-experience': {+ id: '/agent-experience'+ path: '/agent-experience'+ fullPath: '/agent-experience'+ preLoaderRoute: typeof AgentExperienceRouteRouteImport+ parentRoute: typeof rootRouteImport+ }'/': {id: '/'path: '/'@@ -315,6 +358,13 @@ declare module '@tanstack/react-router' {preLoaderRoute: typeof SessionsIndexRouteImportparentRoute: typeof SessionsRouteRoute}+ '/agent-experience/': {+ id: '/agent-experience/'+ path: '/'+ fullPath: '/agent-experience/'+ preLoaderRoute: typeof AgentExperienceIndexRouteImport+ parentRoute: typeof AgentExperienceRouteRoute+ }'/oauth/verify': {id: '/oauth/verify'path: '/oauth/verify'@@ -329,9 +379,29 @@ declare module '@tanstack/react-router' {preLoaderRoute: typeof OauthConsentRouteImportparentRoute: typeof rootRouteImport}+ '/agent-experience/$experienceUri': {+ id: '/agent-experience/$experienceUri'+ path: '/$experienceUri'+ fullPath: '/agent-experience/$experienceUri'+ preLoaderRoute: typeof AgentExperienceExperienceUriRouteImport+ parentRoute: typeof AgentExperienceRouteRoute+ }}}+interface AgentExperienceRouteRouteChildren {+ AgentExperienceExperienceUriRoute: typeof AgentExperienceExperienceUriRoute+ AgentExperienceIndexRoute: typeof AgentExperienceIndexRoute+}++const AgentExperienceRouteRouteChildren: AgentExperienceRouteRouteChildren = {+ AgentExperienceExperienceUriRoute: AgentExperienceExperienceUriRoute,+ AgentExperienceIndexRoute: AgentExperienceIndexRoute,+}++const AgentExperienceRouteRouteWithChildren =+ AgentExperienceRouteRoute._addFileChildren(AgentExperienceRouteRouteChildren)+interface SessionsRouteRouteChildren {SessionsIndexRoute: typeof SessionsIndexRoute}@@ -346,6 +416,7 @@ const SessionsRouteRouteWithChildren = SessionsRouteRoute._addFileChildren(const rootRouteChildren: RootRouteChildren = {IndexRoute: IndexRoute,+ AgentExperienceRouteRoute: AgentExperienceRouteRouteWithChildren,HomeRouteRoute: HomeRouteRoute,MonitoringRouteRoute: MonitoringRouteRoute,PlaygroundRouteRoute: PlaygroundRouteRoute,diff --git a/web-studio/src/routes/agent-experience/$experienceUri.tsx b/web-studio/src/routes/agent-experience/$experienceUri.tsxnew file mode 100644index 000000000..a9e7c0776--- /dev/null+++ b/web-studio/src/routes/agent-experience/$experienceUri.tsx@@ -0,0 +1,410 @@+import * as React from 'react'+import { useInfiniteQuery, useQuery } from '@tanstack/react-query'+import { Link, createFileRoute } from '@tanstack/react-router'+import {+ ArrowLeftIcon,+ BarChart3Icon,+ BrainCircuitIcon,+ ClipboardIcon,+ ExternalLinkIcon,+ FileTextIcon,+ GitBranchIcon,+ LoaderCircleIcon,+ RefreshCwIcon,+} from 'lucide-react'+import { useTranslation } from 'react-i18next'+import ReactMarkdown from 'react-markdown'+import remarkGfm from 'remark-gfm'+import { toast } from 'sonner'++import { Button } from '#/components/ui/button'+import {+ Card,+ CardContent,+ CardDescription,+ CardHeader,+ CardTitle,+} from '#/components/ui/card'+import { useAppConnection } from '#/hooks/use-app-connection'+import { copyTextToClipboard } from '#/lib/clipboard'+import { isOvClientError } from '#/lib/ov-client'++import { OutcomeDistribution } from './-components/outcome-distribution'+import { SourceTracePanel } from './-components/source-trace-panel'+import { TimeRangePicker } from './-components/time-range-picker'+import { TrajectoryList } from './-components/trajectory-list'+import { TrajectoryPreviewSheet } from './-components/trajectory-preview-sheet'+import {+ fetchContent,+ fetchOutcomeDistribution,+ fetchTrajectories,+} from './-lib/api'+import { getExperienceDisplayName, resolveTimeRange } from './-lib/experience'+import type {+ TimeRange,+ TimeRangePreset,+ TrajectoryItem,+ TrajectoryPage,+} from './-lib/types'++export const Route = createFileRoute('/agent-experience/$experienceUri')({+ component: ExperienceDetailRoute,+})++type DetailTab = 'impact' | 'source'++const DETAIL_TABS: readonly DetailTab[] = ['impact', 'source']++function getErrorMessage(error: unknown): string {+ if (isOvClientError(error) || error instanceof Error) {+ return error.message+ }+ return String(error)+}++function ExperienceDetailRoute() {+ const { t, i18n } = useTranslation('agentExperiencePage')+ const { identityScopeKey } = useAppConnection()+ const params = Route.useParams()+ // The router percent-encodes path params when building hrefs and decodes+ // them again on match, so `params.experienceUri` is the raw `viking://` URI.+ const experienceUri = params.experienceUri++ const [activeTab, setActiveTab] = React.useState<DetailTab>('impact')+ const [timeRangePreset, setTimeRangePreset] =+ React.useState<TimeRangePreset>('all')+ const [timeRange, setTimeRange] = React.useState<TimeRange>(() =>+ resolveTimeRange('all'),+ )+ const [selectedTrajectory, setSelectedTrajectory] =+ React.useState<TrajectoryItem | null>(null)++ const handleTimeRangeChange = (preset: TimeRangePreset, range: TimeRange) => {+ setTimeRangePreset(preset)+ setTimeRange(preset === 'custom' ? range : resolveTimeRange(preset))+ }++ const contentQuery = useQuery({+ queryFn: ({ signal }) => fetchContent(experienceUri, signal),+ queryKey: ['agent-experience-content', identityScopeKey, experienceUri],+ staleTime: 60_000,+ })++ const outcomeQuery = useQuery({+ enabled: activeTab === 'impact',+ queryFn: ({ signal }) =>+ fetchOutcomeDistribution({+ experienceUri,+ signal,+ timeRange,+ }),+ queryKey: [+ 'agent-experience-outcomes',+ identityScopeKey,+ experienceUri,+ timeRange.preset,+ timeRange.startDate,+ timeRange.endDate,+ ],+ retry: false,+ })++ const trajectoriesQuery = useInfiniteQuery<+ TrajectoryPage,+ Error,+ { pages: TrajectoryPage[]; pageParams: number[] },+ readonly unknown[],+ number+ >({+ enabled: activeTab === 'impact',+ initialPageParam: 0,+ getNextPageParam: (lastPage) =>+ lastPage.hasMore ? lastPage.offset + lastPage.items.length : undefined,+ queryFn: ({ pageParam, signal }) =>+ fetchTrajectories({+ experienceUri,+ offset: pageParam,+ signal,+ timeRange,+ }),+ queryKey: [+ 'agent-experience-trajectories',+ identityScopeKey,+ experienceUri,+ timeRange.preset,+ timeRange.startDate,+ timeRange.endDate,+ ],+ retry: false,+ })++ const trajectories =+ trajectoriesQuery.data?.pages.flatMap((page) => page.items) ?? []+ const trajectoryTotal = trajectoriesQuery.data?.pages[0]?.total ?? 0+ const hasMoreTrajectories = Boolean(trajectoriesQuery.hasNextPage)+ const experienceName = getExperienceDisplayName(experienceUri)+ const outcomeErrorMessage = outcomeQuery.error+ ? getErrorMessage(outcomeQuery.error)+ : undefined+ const trajectoryErrorMessage = trajectoriesQuery.error+ ? getErrorMessage(trajectoriesQuery.error)+ : undefined++ const handleCopyUri = () => {+ void copyTextToClipboard(experienceUri)+ .then(() => {+ toast.success(t('detail.copied'))+ })+ .catch(() => {+ toast.error(t('detail.copyFailed'))+ })+ }++ return (+ <div className="flex w-full min-w-0 flex-col gap-6">+ <header className="grid gap-3">+ <div>+ <Button+ render={<Link to="/agent-experience" />}+ nativeButton={false}+ size="xs"+ variant="ghost"+ className="-ml-2 text-muted-foreground"+ >+ <ArrowLeftIcon className="size-3.5" />+ {t('detail.back')}+ </Button>+ </div>+ <div className="flex min-w-0 items-center gap-2.5">+ <div className="flex size-9 shrink-0 items-center justify-center rounded-xl bg-primary/10 text-primary">+ <BrainCircuitIcon className="size-4.5" />+ </div>+ <div className="min-w-0">+ <h1+ className="truncate text-xl font-semibold tracking-tight"+ title={experienceName}+ >+ {experienceName}+ </h1>+ <div className="flex items-center gap-1.5">+ <code+ className="min-w-0 truncate text-xs text-muted-foreground"+ title={experienceUri}+ >+ {experienceUri}+ </code>+ <Button+ type="button"+ aria-label={t('detail.copyUri')}+ size="icon-xs"+ variant="ghost"+ onClick={handleCopyUri}+ >+ <ClipboardIcon className="size-3.5" />+ </Button>+ <Button+ render={+ <Link+ rel="noreferrer noopener"+ search={{ file: experienceUri }}+ target="_blank"+ to="/playground"+ />+ }+ nativeButton={false}+ aria-label={t('detail.openPlayground')}+ title={t('detail.openPlayground')}+ size="icon-xs"+ variant="ghost"+ >+ <ExternalLinkIcon className="size-3.5" />+ </Button>+ </div>+ </div>+ </div>+ </header>++ <div className="grid min-w-0 items-start gap-6 xl:grid-cols-[minmax(0,3fr)_minmax(360px,2fr)]">+ <Card+ size="sm"+ className="gap-0 bg-background shadow-none ring-border/70"+ >+ <CardHeader className="border-b border-border/60">+ <div className="flex items-center justify-between gap-3">+ <div className="flex min-w-0 items-center gap-2">+ <FileTextIcon className="size-4 shrink-0 text-muted-foreground" />+ <CardTitle className="truncate text-base">+ {t('detail.contentTitle')}+ </CardTitle>+ </div>+ <Button+ type="button"+ aria-label={t('refresh')}+ size="icon-xs"+ variant="ghost"+ disabled={contentQuery.isFetching}+ onClick={() => void contentQuery.refetch()}+ >+ <RefreshCwIcon+ className={+ contentQuery.isFetching ? 'animate-spin' : undefined+ }+ />+ </Button>+ </div>+ </CardHeader>+ <CardContent className="px-0">+ {contentQuery.isLoading ? (+ <div className="flex min-h-64 items-center justify-center gap-2 px-6 text-sm text-muted-foreground">+ <LoaderCircleIcon className="size-4 animate-spin" />+ {t('detail.contentLoading')}+ </div>+ ) : contentQuery.isError ? (+ <div className="grid min-h-64 place-items-center gap-2 px-6 text-center">+ <p className="font-medium">{t('detail.contentLoadFailed')}</p>+ <p className="max-w-md text-sm text-muted-foreground">+ {getErrorMessage(contentQuery.error)}+ </p>+ <Button+ type="button"+ size="xs"+ variant="outline"+ onClick={() => void contentQuery.refetch()}+ >+ {t('refresh')}+ </Button>+ </div>+ ) : (+ <div className="max-h-[75vh] overflow-y-auto px-6 py-6 sm:px-8">+ <div className="prose prose-sm max-w-none break-words prose-headings:font-semibold prose-headings:tracking-tight prose-h2:text-lg prose-p:leading-7 prose-li:leading-7 prose-hr:border-border dark:prose-invert dark:prose-pre:bg-muted/40">+ <ReactMarkdown remarkPlugins={[remarkGfm]}>+ {contentQuery.data || ''}+ </ReactMarkdown>+ </div>+ </div>+ )}+ </CardContent>+ </Card>++ <Card size="sm" className="bg-background shadow-none ring-border/70">+ <CardHeader>+ <div className="flex flex-wrap items-center justify-between gap-3">+ <div className="grid min-w-0 gap-1">+ <CardTitle className="truncate text-base">+ {activeTab === 'impact'+ ? t('detail.analysisTitle')+ : t('detail.sourceTitle')}+ </CardTitle>+ <CardDescription>+ {activeTab === 'impact'+ ? t('detail.analysisDescription')+ : t('detail.sourceDescription')}+ </CardDescription>+ </div>+ {activeTab === 'impact' ? (+ <TimeRangePicker+ onChange={handleTimeRangeChange}+ preset={timeRangePreset}+ range={timeRange}+ />+ ) : null}+ </div>+ <div className="mt-4 flex gap-5 border-b border-border/60">+ {DETAIL_TABS.map((tab) => (+ <button+ key={tab}+ type="button"+ aria-pressed={activeTab === tab}+ className={+ activeTab === tab+ ? 'flex items-center gap-2 border-b-2 border-primary px-1 pb-3 text-sm font-medium text-foreground'+ : 'flex items-center gap-2 border-b-2 border-transparent px-1 pb-3 text-sm text-muted-foreground transition-colors hover:text-foreground'+ }+ onClick={() => setActiveTab(tab)}+ >+ {tab === 'impact' ? (+ <BarChart3Icon className="size-3" />+ ) : (+ <GitBranchIcon className="size-3" />+ )}+ {tab === 'impact'+ ? t('detail.tabImpact')+ : t('detail.tabSource')}+ </button>+ ))}+ </div>+ </CardHeader>+ <CardContent className="grid gap-5 px-5 pb-5">+ {activeTab === 'impact' ? (+ <>+ <section className="grid gap-3">+ <h3 className="text-sm font-medium">+ {t('detail.outcomeTitle')}+ </h3>+ {outcomeQuery.isLoading ? (+ <div className="flex min-h-16 items-center gap-2 text-sm text-muted-foreground">+ <LoaderCircleIcon className="size-4 animate-spin" />+ {t('detail.loadingMore')}+ </div>+ ) : outcomeQuery.isError ? (+ <div className="grid min-h-16 place-items-center gap-2 text-center">+ <p className="text-sm text-muted-foreground">+ {outcomeErrorMessage}+ </p>+ <Button+ type="button"+ size="xs"+ variant="outline"+ onClick={() => void outcomeQuery.refetch()}+ >+ {t('refresh')}+ </Button>+ </div>+ ) : outcomeQuery.data ? (+ <OutcomeDistribution+ distribution={outcomeQuery.data.distribution}+ />+ ) : null}+ </section>++ <section className="grid gap-3">+ <div className="flex items-center justify-between gap-3">+ <h3 className="text-sm font-medium">+ {t('detail.trajectoriesTitle')}+ </h3>+ <span className="text-xs text-muted-foreground">+ {t('detail.rangeUtcHint')}+ </span>+ </div>+ <TrajectoryList+ errorMessage={trajectoryErrorMessage}+ hasMore={hasMoreTrajectories}+ isLoading={trajectoriesQuery.isLoading}+ isLoadingMore={trajectoriesQuery.isFetchingNextPage}+ items={trajectories}+ language={i18n.language}+ onLoadMore={() => void trajectoriesQuery.fetchNextPage()}+ onRetry={() => void trajectoriesQuery.refetch()}+ onSelect={setSelectedTrajectory}+ total={trajectoryTotal}+ />+ </section>+ </>+ ) : (+ <SourceTracePanel+ experienceUri={experienceUri}+ onSelect={setSelectedTrajectory}+ />+ )}+ </CardContent>+ </Card>+ </div>++ <TrajectoryPreviewSheet+ language={i18n.language}+ onClose={() => setSelectedTrajectory(null)}+ trajectory={selectedTrajectory}+ />+ </div>+ )+}diff --git a/web-studio/src/routes/agent-experience/-components/evolution-settings-popover.tsx b/web-studio/src/routes/agent-experience/-components/evolution-settings-popover.tsxnew file mode 100644index 000000000..8879285a2--- /dev/null+++ b/web-studio/src/routes/agent-experience/-components/evolution-settings-popover.tsx@@ -0,0 +1,162 @@+import { useMutation, useQuery, useQueryClient } from '@tanstack/react-query'+import { LoaderCircleIcon, SettingsIcon } from 'lucide-react'+import { useTranslation } from 'react-i18next'+import { toast } from 'sonner'++import { Button } from '#/components/ui/button'+import {+ Popover,+ PopoverContent,+ PopoverDescription,+ PopoverHeader,+ PopoverTitle,+ PopoverTrigger,+} from '#/components/ui/popover'+import { Switch } from '#/components/ui/switch'+import { useAppConnection } from '#/hooks/use-app-connection'+import { isOvClientError } from '#/lib/ov-client'++import {+ fetchAgentEvolutionStatus,+ setAgentEvolutionEnabled,+} from '../-lib/api'++/**+ * Admin/root-only settings popover that toggles the deployment Agent+ * Evolution switch (`GET/PUT /api/v1/admin/agent-evolution`).+ *+ * When disabled, new session commits stop extracting experiences and+ * trajectories, which is the most common reason the impact panel stays empty.+ */+export function EvolutionSettingsPopover() {+ const { t } = useTranslation('agentExperiencePage')+ const {+ connection,+ connectionRole,+ identityScopeKey,+ isConnectionRoleLoading,+ } = useAppConnection()+ const queryClient = useQueryClient()++ const canManage =+ !isConnectionRoleLoading &&+ (connectionRole === 'admin' || connectionRole === 'root')++ const statusQuery = useQuery({+ enabled: canManage,+ queryFn: ({ signal }) => fetchAgentEvolutionStatus(signal),+ queryKey: ['agent-evolution-status', identityScopeKey],+ staleTime: 30_000,+ })++ const targetAccountId = statusQuery.data?.accountId+ const matchesCurrentAccount =+ Boolean(targetAccountId) && targetAccountId === connection.accountId++ const toggleMutation = useMutation({+ mutationFn: (enabled: boolean) => {+ if (!matchesCurrentAccount) {+ throw new Error(t('settings.scopeMismatch'))+ }+ return setAgentEvolutionEnabled(enabled)+ },+ onSuccess: (status) => {+ queryClient.setQueryData(+ ['agent-evolution-status', identityScopeKey],+ status,+ )+ toast.success(+ status.enabled+ ? t('settings.enabledToast')+ : t('settings.disabledToast'),+ )+ },+ onError: (error) => {+ toast.error(+ isOvClientError(error) || error instanceof Error+ ? `${t('settings.toggleFailed')}: ${error.message}`+ : t('settings.toggleFailed'),+ )+ },+ })++ if (!canManage) return null++ return (+ <Popover>+ <PopoverTrigger+ className="inline-flex h-8 items-center gap-1.5 rounded-[min(var(--radius-md),10px)] border border-border bg-background px-2.5 text-sm font-medium shadow-xs transition-colors hover:bg-muted focus-visible:outline-none focus-visible:ring-3 focus-visible:ring-ring/50"+ aria-label={t('settings.title')}+ >+ <SettingsIcon className="size-3.5" />+ {t('settings.title')}+ </PopoverTrigger>+ <PopoverContent align="end" className="w-80">+ <PopoverHeader>+ <PopoverTitle>{t('settings.title')}</PopoverTitle>+ <PopoverDescription>{t('settings.description')}</PopoverDescription>+ </PopoverHeader>+ <div className="grid gap-3 px-1 pb-1">+ {statusQuery.isLoading ? (+ <div className="flex items-center gap-2 text-sm text-muted-foreground">+ <LoaderCircleIcon className="size-3.5 animate-spin" />+ {t('settings.loading')}+ </div>+ ) : statusQuery.isError ? (+ <div className="grid gap-2 text-sm">+ <p className="text-muted-foreground">+ {t('settings.loadFailed')}+ </p>+ <Button+ type="button"+ size="xs"+ variant="outline"+ className="w-fit"+ onClick={() => void statusQuery.refetch()}+ >+ {t('refresh')}+ </Button>+ </div>+ ) : statusQuery.data ? (+ <div className="flex items-center justify-between gap-3 rounded-lg border px-3 py-2.5">+ <div className="grid gap-0.5">+ <span className="break-all text-xs text-muted-foreground">+ {t('settings.targetAccount', {+ account: targetAccountId || t('settings.unknownAccount'),+ })}+ </span>+ <span className="text-sm font-medium">+ {statusQuery.data.enabled+ ? t('settings.statusEnabled')+ : t('settings.statusDisabled')}+ </span>+ <span className="text-xs text-muted-foreground">+ {statusQuery.data.enabled+ ? t('settings.statusEnabledHint')+ : t('settings.statusDisabledHint')}+ </span>+ </div>+ <Switch+ aria-label={t('settings.title')}+ checked={statusQuery.data.enabled}+ disabled={toggleMutation.isPending || !matchesCurrentAccount}+ onCheckedChange={(checked) => toggleMutation.mutate(checked)}+ />+ </div>+ ) : null}+ {statusQuery.data && !matchesCurrentAccount ? (+ <p className="text-xs text-destructive" role="status">+ {t('settings.scopeMismatch')}+ </p>+ ) : null}+ {toggleMutation.isPending ? (+ <p className="flex items-center gap-1.5 text-xs text-muted-foreground">+ <LoaderCircleIcon className="size-3 animate-spin" />+ {t('settings.pending')}+ </p>+ ) : null}+ </div>+ </PopoverContent>+ </Popover>+ )+}diff --git a/web-studio/src/routes/agent-experience/-components/experience-preview-sheet.tsx b/web-studio/src/routes/agent-experience/-components/experience-preview-sheet.tsxnew file mode 100644index 000000000..561a9929a--- /dev/null+++ b/web-studio/src/routes/agent-experience/-components/experience-preview-sheet.tsx@@ -0,0 +1,117 @@+import { useQuery } from '@tanstack/react-query'+import { Link } from '@tanstack/react-router'+import { BarChart3Icon, LoaderCircleIcon } from 'lucide-react'+import { useTranslation } from 'react-i18next'+import ReactMarkdown from 'react-markdown'+import remarkGfm from 'remark-gfm'++import { Button } from '#/components/ui/button'+import {+ Sheet,+ SheetContent,+ SheetDescription,+ SheetHeader,+ SheetTitle,+} from '#/components/ui/sheet'+import { useAppConnection } from '#/hooks/use-app-connection'++import { fetchContent } from '../-lib/api'+import { formatTimestamp } from '../-lib/experience'+import type { ExperienceFileItem } from '../-lib/types'++/** Quick preview of an experience without leaving the list page. */+export function ExperiencePreviewSheet({+ experience,+ language,+ onClose,+}: {+ experience: ExperienceFileItem | null+ language: string+ onClose: () => void+}) {+ const { t } = useTranslation('agentExperiencePage')+ const { identityScopeKey } = useAppConnection()+ const contentQuery = useQuery({+ enabled: Boolean(experience),+ queryFn: ({ signal }) => fetchContent(experience?.uri ?? '', signal),+ queryKey: ['agent-experience-content', identityScopeKey, experience?.uri],+ staleTime: 60_000,+ })++ const updated = formatTimestamp(experience?.modTime, language)++ return (+ <Sheet+ open={Boolean(experience)}+ onOpenChange={(open) => {+ if (!open) onClose()+ }}+ >+ <SheetContent className="gap-0 data-[side=right]:sm:max-w-2xl">+ <SheetHeader className="border-b px-6 py-5">+ <div className="flex items-center gap-2 pr-10">+ <SheetTitle className="truncate text-lg">+ {experience?.name ?? t('title')}+ </SheetTitle>+ </div>+ <SheetDescription className="pr-10">+ <span className="block truncate font-mono text-xs">+ {experience?.uri}+ </span>+ {updated ? (+ <span className="block pt-1 text-xs">+ {t('updated', { time: updated })}+ </span>+ ) : null}+ </SheetDescription>+ </SheetHeader>++ <div className="min-h-0 flex-1 overflow-y-auto px-6 py-5">+ {contentQuery.isLoading ? (+ <div className="flex min-h-48 items-center justify-center gap-2 text-sm text-muted-foreground">+ <LoaderCircleIcon className="size-4 animate-spin" />+ {t('detail.contentLoading')}+ </div>+ ) : contentQuery.isError ? (+ <div className="grid min-h-48 place-items-center gap-2 text-center">+ <p className="font-medium">{t('detail.contentLoadFailed')}</p>+ <Button+ type="button"+ size="xs"+ variant="outline"+ onClick={() => void contentQuery.refetch()}+ >+ {t('refresh')}+ </Button>+ </div>+ ) : (+ <div className="prose prose-sm max-w-none break-words dark:prose-invert dark:prose-pre:bg-muted-foreground/20">+ <ReactMarkdown remarkPlugins={[remarkGfm]}>+ {contentQuery.data || ''}+ </ReactMarkdown>+ </div>+ )}+ </div>++ {experience ? (+ <div className="flex justify-end border-t px-6 py-4">+ <Button+ render={+ <Link+ params={{ experienceUri: experience.uri }}+ to="/agent-experience/$experienceUri"+ />+ }+ nativeButton={false}+ size="sm"+ onClick={onClose}+ >+ <BarChart3Icon className="size-4" />+ {t('viewAnalysis')}+ </Button>+ </div>+ ) : null}+ </SheetContent>+ </Sheet>+ )+}diff --git a/web-studio/src/routes/agent-experience/-components/outcome-distribution.tsx b/web-studio/src/routes/agent-experience/-components/outcome-distribution.tsxnew file mode 100644index 000000000..acfee7458--- /dev/null+++ b/web-studio/src/routes/agent-experience/-components/outcome-distribution.tsx@@ -0,0 +1,90 @@+import { useTranslation } from 'react-i18next'++import { OUTCOME_COLORS, TRAJECTORY_OUTCOMES } from '../-lib/experience'+import type { OutcomeCount } from '../-lib/types'++function OutcomeLegend({+ count,+ label,+ outcome,+}: {+ count: number+ label: string+ outcome: OutcomeCount['outcome']+}) {+ return (+ <div className="flex min-w-0 items-center gap-1.5">+ <span+ aria-hidden="true"+ className={`size-2 shrink-0 rounded-full ${OUTCOME_COLORS[outcome]}`}+ />+ <span className="truncate text-muted-foreground">{label}</span>+ <span className="ml-auto shrink-0 font-mono text-xs tabular-nums text-foreground">+ {count}+ </span>+ </div>+ )+}++/**+ * Horizontal stacked bar plus legend for the five fixed trajectory outcomes.+ *+ * Zero-count buckets are still rendered (muted) so the legend stays stable and+ * users can discover which outcomes exist.+ */+export function OutcomeDistribution({+ distribution,+}: {+ distribution: OutcomeCount[]+}) {+ const { t } = useTranslation('agentExperiencePage')+ const byOutcome = new Map(distribution.map((item) => [item.outcome, item]))+ const total = distribution.reduce((sum, item) => sum + item.count, 0)+ const successCount = byOutcome.get('success')?.count ?? 0++ return (+ <div className="grid gap-3">+ <div className="flex flex-wrap items-baseline gap-x-3 gap-y-1">+ <span className="text-2xl font-semibold tabular-nums">{total}</span>+ <span className="text-sm text-muted-foreground">+ {t('detail.outcomeTotal', { count: total })}+ </span>+ {total > 0 ? (+ <span className="text-sm font-medium text-emerald-600 dark:text-emerald-400">+ {t('detail.successRate', {+ rate: Math.round((successCount / total) * 100),+ })}+ </span>+ ) : null}+ </div>++ {total > 0 ? (+ <div+ aria-hidden="true"+ className="flex h-2.5 w-full overflow-hidden rounded-full bg-muted"+ >+ {distribution.map((item) =>+ item.count > 0 ? (+ <div+ key={item.outcome}+ className={OUTCOME_COLORS[item.outcome]}+ style={{ width: `${(item.count / total) * 100}%` }}+ />+ ) : null,+ )}+ </div>+ ) : null}++ <div className="grid gap-1.5 text-sm sm:grid-cols-2 lg:grid-cols-1 xl:grid-cols-2">+ {TRAJECTORY_OUTCOMES.map((outcome) => (+ <OutcomeLegend+ key={outcome}+ count={byOutcome.get(outcome)?.count ?? 0}+ label={t(`outcomes.${outcome}`)}+ outcome={outcome}+ />+ ))}+ </div>+ </div>+ )+}diff --git a/web-studio/src/routes/agent-experience/-components/source-trace-panel.tsx b/web-studio/src/routes/agent-experience/-components/source-trace-panel.tsxnew file mode 100644index 000000000..1fb5eaafe--- /dev/null+++ b/web-studio/src/routes/agent-experience/-components/source-trace-panel.tsx@@ -0,0 +1,107 @@+import { useQuery } from '@tanstack/react-query'+import { LinkIcon, LoaderCircleIcon, RouteIcon } from 'lucide-react'+import { useTranslation } from 'react-i18next'++import { Button } from '#/components/ui/button'+import { useAppConnection } from '#/hooks/use-app-connection'++import { fetchSourceTrajectories } from '../-lib/api'+import type { TrajectoryItem } from '../-lib/types'++/**+ * Source lineage: `derived_from` links stored in the Experience memory attrs.+ */+export function SourceTracePanel({+ experienceUri,+ onSelect,+}: {+ experienceUri: string+ onSelect: (trajectory: TrajectoryItem) => void+}) {+ const { t } = useTranslation('agentExperiencePage')+ const { identityScopeKey } = useAppConnection()+ const sourceQuery = useQuery({+ queryFn: ({ signal }) => fetchSourceTrajectories(experienceUri, signal),+ queryKey: ['agent-experience-sources', identityScopeKey, experienceUri],+ staleTime: 60_000,+ })++ const links = sourceQuery.data ?? []++ return (+ <section className="grid gap-3">+ {sourceQuery.isLoading ? (+ <div className="flex min-h-24 items-center gap-2 text-sm text-muted-foreground">+ <LoaderCircleIcon className="size-4 animate-spin" />+ {t('detail.sourceLoading')}+ </div>+ ) : sourceQuery.isError ? (+ <div className="grid min-h-24 place-items-center gap-2 text-center">+ <p className="text-sm text-muted-foreground">+ {t('detail.sourceLoadFailed')}+ </p>+ <Button+ type="button"+ size="xs"+ variant="outline"+ onClick={() => void sourceQuery.refetch()}+ >+ {t('refresh')}+ </Button>+ </div>+ ) : links.length === 0 ? (+ <div className="grid min-h-24 place-items-center px-4 py-4 text-center">+ <p className="max-w-md text-sm text-muted-foreground">+ {t('detail.sourceEmpty')}+ </p>+ </div>+ ) : (+ <ul className="grid gap-2">+ {links.map((link) => {+ const name = link.uri.split('/').pop() ?? link.uri+ return (+ <li key={`${link.uri}:${link.reason ?? ''}`}>+ <button+ type="button"+ aria-label={t('detail.trajectoryView', { name })}+ className="grid w-full gap-2 rounded-lg border border-border/60 px-4 py-3.5 text-left transition-colors hover:border-primary/30 hover:bg-muted/20 focus-visible:outline-none focus-visible:ring-3 focus-visible:ring-ring/50"+ onClick={() =>+ onSelect({+ description: link.reason,+ name,+ uri: link.uri,+ })+ }+ >+ <span className="flex min-w-0 items-center gap-2">+ <RouteIcon className="size-3.5 shrink-0 text-muted-foreground" />+ <span className="truncate text-sm font-medium" title={name}>+ {name}+ </span>+ </span>+ <span className="flex min-w-0 items-center gap-1.5 pl-5.5">+ <LinkIcon className="size-3 shrink-0 text-muted-foreground/70" />+ <code+ className="min-w-0 truncate text-xs text-muted-foreground"+ title={link.uri}+ >+ {link.uri}+ </code>+ </span>+ {link.reason ? (+ <span+ className="truncate pl-5.5 text-xs text-muted-foreground/80"+ title={link.reason}+ >+ {link.reason}+ </span>+ ) : null}+ </button>+ </li>+ )+ })}+ </ul>+ )}+ </section>+ )+}diff --git a/web-studio/src/routes/agent-experience/-components/time-range-picker.tsx b/web-studio/src/routes/agent-experience/-components/time-range-picker.tsxnew file mode 100644index 000000000..21c30f116--- /dev/null+++ b/web-studio/src/routes/agent-experience/-components/time-range-picker.tsx@@ -0,0 +1,154 @@+import * as React from 'react'+import { CalendarRangeIcon } from 'lucide-react'+import { useTranslation } from 'react-i18next'++import { Button } from '#/components/ui/button'+import { ButtonGroup } from '#/components/ui/button-group'+import { Input } from '#/components/ui/input'+import {+ Popover,+ PopoverContent,+ PopoverDescription,+ PopoverHeader,+ PopoverTitle,+ PopoverTrigger,+} from '#/components/ui/popover'++import { buildCustomTimeRange } from '../-lib/experience'+import type { TimeRange, TimeRangePreset } from '../-lib/types'++const QUICK_PRESETS: readonly TimeRangePreset[] = ['all', '7d', '30d']++const PRESET_LABEL_KEYS: Record<TimeRangePreset, string> = {+ all: 'detail.rangeAll',+ '7d': 'detail.range7d',+ '30d': 'detail.range30d',+ custom: 'detail.rangeCustom',+}++/**+ * Shared time-range control for the impact panel: quick presets plus a+ * custom UTC date range popover. The effective range is reported upward via+ * `onChange` and applied to both the outcome and trajectory queries.+ */+export function TimeRangePicker({+ onChange,+ preset,+ range,+}: {+ onChange: (preset: TimeRangePreset, range: TimeRange) => void+ preset: TimeRangePreset+ range: TimeRange+}) {+ const { t } = useTranslation('agentExperiencePage')+ const [open, setOpen] = React.useState(false)+ const [customStart, setCustomStart] = React.useState(+ range.preset === 'custom' ? (range.startDate ?? '') : '',+ )+ const [customEnd, setCustomEnd] = React.useState(+ range.preset === 'custom' ? (range.endDate ?? '') : '',+ )++ const customError = React.useMemo(() => {+ if (!customStart.trim() && !customEnd.trim()) return undefined+ return buildCustomTimeRange(customStart, customEnd).error+ }, [customEnd, customStart])++ const applyCustom = () => {+ const { error, range: customRange } = buildCustomTimeRange(+ customStart,+ customEnd,+ )+ if (error || !customRange) return+ onChange('custom', customRange)+ setOpen(false)+ }++ return (+ <div className="flex flex-wrap items-center gap-1.5">+ <ButtonGroup>+ {QUICK_PRESETS.map((item) => (+ <Button+ key={item}+ type="button"+ size="xs"+ aria-pressed={preset === item}+ variant={preset === item ? 'secondary' : 'ghost'}+ onClick={() => onChange(item, { preset: item })}+ >+ {t(PRESET_LABEL_KEYS[item])}+ </Button>+ ))}+ <Popover onOpenChange={setOpen} open={open}>+ <PopoverTrigger+ className="inline-flex h-6 items-center gap-1 rounded-[min(var(--radius-md),8px)] px-2 text-xs font-medium transition-colors hover:bg-muted focus-visible:outline-none focus-visible:ring-3 focus-visible:ring-ring/50 aria-pressed:bg-secondary"+ aria-pressed={preset === 'custom'}+ >+ <CalendarRangeIcon className="size-3" />+ {preset === 'custom' && (range.startDate || range.endDate)+ ? `${range.startDate ?? '…'} ~ ${range.endDate ?? '…'}`+ : t('detail.rangeCustom')}+ </PopoverTrigger>+ <PopoverContent align="end" className="w-72">+ <PopoverHeader>+ <PopoverTitle>{t('detail.rangeCustom')}</PopoverTitle>+ <PopoverDescription>+ {t('detail.rangeUtcHint')}+ </PopoverDescription>+ </PopoverHeader>+ <div className="grid gap-3 px-1 pb-1">+ <label className="grid gap-1.5 text-xs text-muted-foreground">+ {t('detail.rangeStart')}+ <Input+ aria-label={t('detail.rangeStart')}+ className="h-8 font-mono text-xs"+ placeholder="2026-08-01"+ value={customStart}+ onChange={(event) => setCustomStart(event.target.value)}+ />+ </label>+ <label className="grid gap-1.5 text-xs text-muted-foreground">+ {t('detail.rangeEnd')}+ <Input+ aria-label={t('detail.rangeEnd')}+ className="h-8 font-mono text-xs"+ placeholder="2026-08-15"+ value={customEnd}+ onChange={(event) => setCustomEnd(event.target.value)}+ />+ </label>+ {customError ? (+ <p className="text-xs text-destructive">+ {customError === 'order'+ ? t('detail.rangeOrderError')+ : t('detail.rangeInvalidError')}+ </p>+ ) : null}+ <div className="flex justify-end gap-2">+ <Button+ type="button"+ size="xs"+ variant="ghost"+ onClick={() => setOpen(false)}+ >+ {t('detail.rangeCancel')}+ </Button>+ <Button+ type="button"+ size="xs"+ disabled={+ Boolean(customError) ||+ (!customStart.trim() && !customEnd.trim())+ }+ onClick={applyCustom}+ >+ {t('detail.rangeApply')}+ </Button>+ </div>+ </div>+ </PopoverContent>+ </Popover>+ </ButtonGroup>+ </div>+ )+}diff --git a/web-studio/src/routes/agent-experience/-components/trajectory-list.tsx b/web-studio/src/routes/agent-experience/-components/trajectory-list.tsxnew file mode 100644index 000000000..c3e0fa73d--- /dev/null+++ b/web-studio/src/routes/agent-experience/-components/trajectory-list.tsx@@ -0,0 +1,186 @@+import { LoaderCircleIcon } from 'lucide-react'+import { useTranslation } from 'react-i18next'++import { Button } from '#/components/ui/button'+import { Spinner } from '#/components/ui/spinner'+import {+ Table,+ TableBody,+ TableCell,+ TableHead,+ TableHeader,+ TableRow,+} from '#/components/ui/table'++import { formatTimestamp } from '../-lib/experience'+import type { TrajectoryItem } from '../-lib/types'++function TrajectoryRows({+ items,+ language,+ onSelect,+ selectLabel,+}: {+ items: TrajectoryItem[]+ language: string+ onSelect: (trajectory: TrajectoryItem) => void+ selectLabel: string+}) {+ return (+ <>+ {items.map((trajectory) => {+ const updated = formatTimestamp(+ trajectory.updated_at ?? trajectory.created_at,+ language,+ )++ return (+ <TableRow+ key={trajectory.uri}+ className="cursor-pointer"+ onClick={() => onSelect(trajectory)}+ >+ <TableCell className="max-w-0 py-2.5 pl-4">+ <button+ type="button"+ aria-label={selectLabel}+ className="block min-w-0 max-w-full truncate text-left font-medium underline-offset-2 hover:underline focus-visible:outline-none focus-visible:ring-3 focus-visible:ring-ring/50"+ onClick={(event) => {+ event.stopPropagation()+ onSelect(trajectory)+ }}+ >+ {trajectory.name}+ </button>+ {trajectory.description ? (+ <span className="block truncate text-xs text-muted-foreground">+ {trajectory.description}+ </span>+ ) : null}+ </TableCell>+ <TableCell className="w-40 py-2.5 pr-4 text-sm whitespace-nowrap text-muted-foreground">+ {updated ?? '-'}+ </TableCell>+ </TableRow>+ )+ })}+ </>+ )+}++/**+ * Applied-trajectory list with offset-based "load more" pagination.+ *+ * Clicking a row (or its name button) opens the trajectory content preview.+ */+export function TrajectoryList({+ errorMessage,+ hasMore,+ isLoading,+ isLoadingMore,+ items,+ language,+ onLoadMore,+ onRetry,+ onSelect,+ total,+}: {+ errorMessage?: string+ hasMore: boolean+ isLoading: boolean+ isLoadingMore: boolean+ items: TrajectoryItem[]+ language: string+ onLoadMore: () => void+ onRetry: () => void+ onSelect: (trajectory: TrajectoryItem) => void+ total: number+}) {+ const { t } = useTranslation('agentExperiencePage')++ if (isLoading) {+ return (+ <div className="flex min-h-24 items-center justify-center gap-2 text-sm text-muted-foreground">+ <Spinner className="size-3.5" />+ {t('detail.loadingMore')}+ </div>+ )+ }++ if (items.length === 0 && errorMessage) {+ return (+ <div className="grid min-h-24 place-items-center gap-2 text-center text-sm">+ <p className="text-muted-foreground">+ {t('detail.trajectoriesLoadFailed')}+ </p>+ <p className="max-w-md text-xs leading-5 text-muted-foreground/80">+ {errorMessage}+ </p>+ <Button type="button" size="xs" variant="outline" onClick={onRetry}>+ {t('refresh')}+ </Button>+ </div>+ )+ }++ if (items.length === 0) {+ return (+ <div className="grid min-h-24 place-items-center gap-1 px-4 py-4 text-center">+ <p className="text-sm text-muted-foreground">+ {t('detail.outcomeEmpty')}+ </p>+ <p className="max-w-md text-xs leading-5 text-muted-foreground/80">+ {t('detail.outcomeEmptyDescription')}+ </p>+ </div>+ )+ }++ return (+ <div className="grid gap-2">+ <div className="overflow-hidden rounded-lg border">+ <Table>+ <TableHeader>+ <TableRow className="hover:bg-transparent">+ <TableHead className="h-9 pl-4">+ {t('detail.trajectoriesTitle')}+ </TableHead>+ <TableHead className="h-9 w-40 pr-4 text-right">+ {t('columnUpdated')}+ </TableHead>+ </TableRow>+ </TableHeader>+ <TableBody>+ <TrajectoryRows+ items={items}+ language={language}+ onSelect={onSelect}+ selectLabel={t('detail.previewTitle')}+ />+ </TableBody>+ </Table>+ </div>++ <div className="flex items-center justify-center">+ {hasMore ? (+ <Button+ type="button"+ size="sm"+ variant="outline"+ disabled={isLoadingMore}+ onClick={onLoadMore}+ >+ {isLoadingMore ? (+ <LoaderCircleIcon className="animate-spin" />+ ) : null}+ {isLoadingMore ? t('detail.loadingMore') : t('detail.loadMore')}+ </Button>+ ) : (+ <span className="text-xs text-muted-foreground">+ {t('detail.noMore', { count: total })}+ </span>+ )}+ </div>+ </div>+ )+}diff --git a/web-studio/src/routes/agent-experience/-components/trajectory-preview-sheet.tsx b/web-studio/src/routes/agent-experience/-components/trajectory-preview-sheet.tsxnew file mode 100644index 000000000..a79c0cdb2--- /dev/null+++ b/web-studio/src/routes/agent-experience/-components/trajectory-preview-sheet.tsx@@ -0,0 +1,101 @@+import { useQuery } from '@tanstack/react-query'+import { LoaderCircleIcon, RouteIcon } from 'lucide-react'+import { useTranslation } from 'react-i18next'+import ReactMarkdown from 'react-markdown'+import remarkGfm from 'remark-gfm'++import { Button } from '#/components/ui/button'+import {+ Sheet,+ SheetContent,+ SheetDescription,+ SheetHeader,+ SheetTitle,+} from '#/components/ui/sheet'+import { fetchTrajectoryContent } from '../-lib/api'+import { formatTimestamp } from '../-lib/experience'+import type { TrajectoryItem } from '../-lib/types'++/** Side sheet that renders the trajectory markdown content. */+export function TrajectoryPreviewSheet({+ language,+ onClose,+ trajectory,+}: {+ language: string+ onClose: () => void+ trajectory: TrajectoryItem | null+}) {+ const { t } = useTranslation('agentExperiencePage')+ const contentQuery = useQuery({+ enabled: Boolean(trajectory),+ queryFn: ({ signal }) =>+ fetchTrajectoryContent(trajectory?.uri ?? '', signal),+ queryKey: ['agent-experience-trajectory-content', trajectory?.uri],+ staleTime: 60_000,+ })++ const updated = formatTimestamp(+ trajectory?.updated_at ?? trajectory?.created_at,+ language,+ )++ return (+ <Sheet+ open={Boolean(trajectory)}+ onOpenChange={(open) => {+ if (!open) onClose()+ }}+ >+ <SheetContent className="gap-0 data-[side=right]:sm:max-w-2xl">+ <SheetHeader className="border-b px-6 py-5">+ <div className="flex items-center gap-2 pr-10">+ <div className="flex size-8 shrink-0 items-center justify-center rounded-lg bg-primary/10 text-primary">+ <RouteIcon className="size-4" />+ </div>+ <SheetTitle className="truncate text-lg">+ {trajectory?.name ?? t('detail.previewTitle')}+ </SheetTitle>+ </div>+ <SheetDescription className="pr-10">+ <span className="block truncate font-mono text-xs">+ {trajectory?.uri}+ </span>+ {updated ? (+ <span className="block pt-1 text-xs">+ {t('updated', { time: updated })}+ </span>+ ) : null}+ </SheetDescription>+ </SheetHeader>++ <div className="min-h-0 flex-1 overflow-y-auto px-6 py-5">+ {contentQuery.isLoading ? (+ <div className="flex min-h-48 items-center justify-center gap-2 text-sm text-muted-foreground">+ <LoaderCircleIcon className="size-4 animate-spin" />+ {t('detail.previewLoading')}+ </div>+ ) : contentQuery.isError ? (+ <div className="grid min-h-48 place-items-center gap-2 text-center">+ <p className="font-medium">{t('detail.previewLoadFailed')}</p>+ <Button+ type="button"+ size="xs"+ variant="outline"+ onClick={() => void contentQuery.refetch()}+ >+ {t('refresh')}+ </Button>+ </div>+ ) : (+ <div className="prose prose-sm max-w-none break-words dark:prose-invert dark:prose-pre:bg-muted-foreground/20">+ <ReactMarkdown remarkPlugins={[remarkGfm]}>+ {contentQuery.data || ''}+ </ReactMarkdown>+ </div>+ )}+ </div>+ </SheetContent>+ </Sheet>+ )+}diff --git a/web-studio/src/routes/agent-experience/-lib/api.test.ts b/web-studio/src/routes/agent-experience/-lib/api.test.tsnew file mode 100644index 000000000..08c01cc93--- /dev/null+++ b/web-studio/src/routes/agent-experience/-lib/api.test.ts@@ -0,0 +1,78 @@+import { beforeEach, describe, expect, it, vi } from 'vitest'++import { fetchExperiences } from './api'++const { get } = vi.hoisted(() => ({ get: vi.fn() }))+vi.mock('#/lib/ov-client', () => ({+ ovClient: { client: { get } },+ getOvResult: (result: unknown) => result,+ isOvClientError: () => false,+}))++const experiencesUri = 'viking://user/default/memories/experiences'+const file = (name: string) => ({ name, uri: `${experiencesUri}/${name}` })++describe('experience listing server pagination', () => {+ beforeEach(() => get.mockReset())++ it('requests a page beyond the old 1000 limit with one lookahead entry', async () => {+ get.mockResolvedValue([file('a.md'), file('b.md'), file('c.md')])+ const result = await fetchExperiences({+ experiencesUri,+ page: 502,+ pageSize: 2,+ })+ expect(get).toHaveBeenCalledWith(+ expect.objectContaining({+ url: '/api/v1/fs/ls',+ query: expect.objectContaining({+ offset: 1002,+ limit: 3,+ uri: experiencesUri,+ }),+ }),+ )+ expect(result.items.map((item) => item.name)).toEqual(['a.md', 'b.md'])+ expect(result.hasMore).toBe(true)+ expect(result).not.toHaveProperty('total')+ })++ it('does not skip lookahead records between pages', async () => {+ get.mockResolvedValueOnce([file('a.md'), file('b.md'), file('c.md')])+ get.mockResolvedValueOnce([file('c.md'), file('d.md')])+ await fetchExperiences({ experiencesUri, page: 1, pageSize: 2 })+ const last = await fetchExperiences({+ experiencesUri,+ page: 2,+ pageSize: 2,+ })+ expect(get.mock.calls[1][0].query.offset).toBe(2)+ expect(last.items.map((item) => item.name)).toEqual(['c.md', 'd.md'])+ expect(last.hasMore).toBe(false)+ })++ it('applies pagination to raw entries before filtering out directories', async () => {+ get.mockResolvedValue([+ { ...file('folder'), isDir: true },+ file('a.md'),+ file('b.md'),+ ])+ const result = await fetchExperiences({+ experiencesUri,+ page: 1,+ pageSize: 2,+ })+ expect(result.items.map((item) => item.name)).toEqual(['a.md'])+ expect(result.hasMore).toBe(true)+ })++ it('allows an empty later page without inventing a total', async () => {+ get.mockResolvedValue([])+ const result = await fetchExperiences({+ experiencesUri,+ page: 3,+ pageSize: 50,+ })+ expect(result).toEqual({ items: [], hasMore: false, page: 3, pageSize: 50 })+ })+})diff --git a/web-studio/src/routes/agent-experience/-lib/api.ts b/web-studio/src/routes/agent-experience/-lib/api.tsnew file mode 100644index 000000000..4862d6644--- /dev/null+++ b/web-studio/src/routes/agent-experience/-lib/api.ts@@ -0,0 +1,187 @@+import { getOvResult, isOvClientError, ovClient } from '#/lib/ov-client'++import {+ DEFAULT_TRAJECTORY_PAGE_SIZE,+ normalizeExperienceFiles,+ normalizeOutcomeDistribution,+ normalizeSourceTrajectoryLinks,+ normalizeTrajectoryPage,+} from './experience'+import type { SourceTrajectoryLink } from './experience'+import type {+ AgentEvolutionStatus,+ ExperiencePage,+ OutcomeDistribution,+ TimeRange,+ TrajectoryPage,+} from './types'++/** Fetch one page; the extra raw entry determines whether another page exists. */+export async function fetchExperiences(options: {+ experiencesUri: string+ page: number+ pageSize: number+ signal?: AbortSignal+}): Promise<ExperiencePage> {+ const { experiencesUri, page, pageSize, signal } = options+ try {+ const result = await getOvResult<unknown>(+ ovClient.client.get({+ query: {+ limit: pageSize + 1,+ offset: (page - 1) * pageSize,+ output: 'original',+ sort_by: 'mtime',+ sort_order: 'desc',+ uri: experiencesUri,+ },+ signal,+ url: '/api/v1/fs/ls',+ }),+ )+ if (!Array.isArray(result)) throw new Error('Invalid fs/ls response')+ return {+ items: normalizeExperienceFiles(result.slice(0, pageSize)),+ hasMore: result.length > pageSize,+ page,+ pageSize,+ }+ } catch (error) {+ if (isOvClientError(error) && error.statusCode === 404) {+ return { items: [], hasMore: false, page, pageSize }+ }+ throw error+ }+}++export async function fetchContent(+ uri: string,+ signal?: AbortSignal,+): Promise<string> {+ const result = await getOvResult<unknown>(+ ovClient.client.get({+ query: { limit: -1, offset: 0, uri },+ signal,+ url: '/api/v1/content/read',+ }),+ )++ if (typeof result === 'string') return result+ if (result && typeof result === 'object') {+ const record = result as Record<string, unknown>+ if (typeof record.content === 'string') return record.content+ }+ return ''+}++export async function fetchTrajectories(options: {+ experienceUri: string+ limit?: number+ offset?: number+ timeRange?: TimeRange+ signal?: AbortSignal+}): Promise<TrajectoryPage> {+ const {+ experienceUri,+ limit = DEFAULT_TRAJECTORY_PAGE_SIZE,+ offset = 0,+ timeRange,+ signal,+ } = options+ const result = await getOvResult<unknown>(+ ovClient.client.get({+ query: {+ experience_uri: experienceUri,+ limit,+ offset,+ start_date: timeRange?.startDate,+ end_date: timeRange?.endDate,+ },+ signal,+ url: '/api/v1/agent-evolution/experiences/trajectories',+ }),+ )+ return (+ normalizeTrajectoryPage(result, experienceUri) ?? {+ experienceUri,+ items: [],+ total: 0,+ limit,+ offset,+ hasMore: false,+ }+ )+}++export async function fetchOutcomeDistribution(options: {+ experienceUri: string+ timeRange?: TimeRange+ signal?: AbortSignal+}): Promise<OutcomeDistribution> {+ const { experienceUri, timeRange, signal } = options+ const result = await getOvResult<unknown>(+ ovClient.client.get({+ query: {+ experience_uri: experienceUri,+ start_date: timeRange?.startDate,+ end_date: timeRange?.endDate,+ },+ signal,+ url: '/api/v1/agent-evolution/experiences/outcomes',+ }),+ )+ return normalizeOutcomeDistribution(result, experienceUri)+}++export async function fetchSourceTrajectories(+ uri: string,+ signal?: AbortSignal,+): Promise<SourceTrajectoryLink[]> {+ const result = await getOvResult<unknown>(+ ovClient.client.get({+ query: { uri },+ signal,+ url: '/api/v1/fs/attrs',+ }),+ )+ return normalizeSourceTrajectoryLinks(result)+}++export async function fetchAgentEvolutionStatus(+ signal?: AbortSignal,+): Promise<AgentEvolutionStatus> {+ const result = await getOvResult<unknown>(+ ovClient.client.get({ signal, url: '/api/v1/admin/agent-evolution' }),+ )+ const record =+ result && typeof result === 'object'+ ? (result as Record<string, unknown>)+ : {}+ return {+ enabled: record.enabled === true,+ accountId:+ typeof record.account_id === 'string' ? record.account_id : undefined,+ }+}++export async function setAgentEvolutionEnabled(+ enabled: boolean,+): Promise<AgentEvolutionStatus> {+ const result = await getOvResult<unknown>(+ ovClient.client.put({+ body: { enabled },+ url: '/api/v1/admin/agent-evolution',+ }),+ )+ const record =+ result && typeof result === 'object'+ ? (result as Record<string, unknown>)+ : {}+ return {+ enabled: record.enabled === true,+ accountId:+ typeof record.account_id === 'string' ? record.account_id : undefined,+ }+}++export const fetchTrajectoryContent = fetchContentdiff --git a/web-studio/src/routes/agent-experience/-lib/experience.test.ts b/web-studio/src/routes/agent-experience/-lib/experience.test.tsnew file mode 100644index 000000000..0e6e0303d--- /dev/null+++ b/web-studio/src/routes/agent-experience/-lib/experience.test.ts@@ -0,0 +1,288 @@+// @vitest-environment jsdom++import { describe, expect, it } from 'vitest'++import {+ buildCustomTimeRange,+ buildExperiencesUri,+ formatFileSize,+ formatTimestamp,+ getExperienceDisplayName,+ isExperienceUpdatedSinceLastSeen,+ markExperiencesSeen,+ normalizeOutcomeDistribution,+ normalizeTrajectoryPage,+ resolveTimeRange,+} from './experience'++describe('buildExperiencesUri', () => {+ it('builds the experiences directory URI for a user', () => {+ expect(buildExperiencesUri('default')).toBe(+ 'viking://user/default/memories/experiences',+ )+ expect(buildExperiencesUri('glm-4.7')).toBe(+ 'viking://user/glm-4.7/memories/experiences',+ )+ })++ it('encodes user ids with reserved characters', () => {+ expect(buildExperiencesUri('user/with/slashes')).toBe(+ 'viking://user/user%2Fwith%2Fslashes/memories/experiences',+ )+ })++ it('falls back to the default user for empty ids', () => {+ expect(buildExperiencesUri('')).toBe(+ 'viking://user/default/memories/experiences',+ )+ expect(buildExperiencesUri(' ')).toBe(+ 'viking://user/default/memories/experiences',+ )+ })+})++describe('getExperienceDisplayName', () => {+ it('strips the markdown extension from the file name', () => {+ expect(+ getExperienceDisplayName(+ 'viking://user/default/memories/experiences/exchange.md',+ ),+ ).toBe('exchange')+ expect(+ getExperienceDisplayName(+ 'viking://user/default/memories/exchanges/Refund_Flow.MD',+ ),+ ).toBe('Refund_Flow')+ })++ it('returns the raw segment when there is no extension', () => {+ expect(+ getExperienceDisplayName('viking://user/default/memories/experiences/x'),+ ).toBe('x')+ })+})++describe('normalizeTrajectoryPage', () => {+ const payload = {+ experience_uri: 'viking://user/u/memories/experiences/e.md',+ items: [+ {+ uri: 'viking://user/u/memories/trajectories/t1.md',+ name: 't1.md',+ description: '处理换货请求',+ created_at: '2026-08-05T02:00:00Z',+ updated_at: '2026-08-05T02:10:00Z',+ },+ { name: 'missing-uri.md' },+ ],+ total: 21,+ limit: 20,+ offset: 0,+ has_more: true,+ }++ it('normalizes items, pagination and has_more', () => {+ const page = normalizeTrajectoryPage(payload, 'fallback')+ expect(page).not.toBeNull()+ expect(page?.items).toHaveLength(1)+ expect(page?.items[0].name).toBe('t1.md')+ expect(page?.total).toBe(21)+ expect(page?.hasMore).toBe(true)+ })++ it('derives has_more when the flag is missing', () => {+ const page = normalizeTrajectoryPage(+ { items: [{ uri: 'viking://t/1', name: 't' }], total: 2, offset: 0 },+ 'fallback',+ )+ expect(page?.hasMore).toBe(true)+ })++ it('returns null for non-object payloads', () => {+ expect(normalizeTrajectoryPage('nope', 'fallback')).toBeNull()+ expect(normalizeTrajectoryPage(undefined, 'fallback')).toBeNull()+ })++ it('falls back to the provided uri when the response omits it', () => {+ const page = normalizeTrajectoryPage({ items: [] }, 'fallback-uri')+ expect(page?.experienceUri).toBe('fallback-uri')+ })+})++describe('normalizeOutcomeDistribution', () => {+ it('fills the five fixed buckets and zeroes missing counts', () => {+ const result = normalizeOutcomeDistribution(+ {+ outcome_distribution: [+ { outcome: 'success', count: 4 },+ { outcome: 'failure', count: 1 },+ ],+ },+ 'viking://user/u/memories/experiences/e.md',+ )++ expect(result.distribution).toEqual([+ { outcome: 'success', count: 4 },+ { outcome: 'failure', count: 1 },+ { outcome: 'partial', count: 0 },+ { outcome: 'unknown', count: 0 },+ { outcome: 'unfinished', count: 0 },+ ])+ })++ it('keeps the stable order regardless of server ordering', () => {+ const result = normalizeOutcomeDistribution(+ {+ outcome_distribution: [+ { outcome: 'unfinished', count: 2 },+ { outcome: 'partial', count: 3 },+ ],+ },+ 'uri',+ )+ expect(result.distribution.map((item) => item.outcome)).toEqual([+ 'success',+ 'failure',+ 'partial',+ 'unknown',+ 'unfinished',+ ])+ expect(result.distribution.map((item) => item.count)).toEqual([+ 0, 0, 3, 0, 2,+ ])+ })++ it('handles empty or malformed payloads', () => {+ const empty = normalizeOutcomeDistribution(undefined, 'uri')+ expect(empty.distribution).toHaveLength(5)+ expect(empty.distribution.every((item) => item.count === 0)).toBe(true)+ })+})++describe('resolveTimeRange', () => {+ it('disables filtering for the all preset', () => {+ expect(resolveTimeRange('all', new Date('2026-08-15T12:00:00Z'))).toEqual({+ preset: 'all',+ })+ })++ it('returns no bounds for the custom preset', () => {+ expect(resolveTimeRange('custom')).toEqual({ preset: 'custom' })+ })++ it('computes inclusive UTC bounds for the 7d preset', () => {+ expect(resolveTimeRange('7d', new Date('2026-08-15T12:00:00Z'))).toEqual({+ preset: '7d',+ startDate: '2026-08-09',+ endDate: '2026-08-15',+ })+ })++ it('computes inclusive UTC bounds for the 30d preset', () => {+ expect(resolveTimeRange('30d', new Date('2026-08-15T12:00:00Z'))).toEqual({+ preset: '30d',+ startDate: '2026-07-17',+ endDate: '2026-08-15',+ })+ })++ it('handles month boundaries', () => {+ expect(resolveTimeRange('7d', new Date('2026-09-03T23:59:59Z'))).toEqual({+ preset: '7d',+ startDate: '2026-08-28',+ endDate: '2026-09-03',+ })+ })+})++describe('buildCustomTimeRange', () => {+ it('builds a range from both bounds', () => {+ expect(buildCustomTimeRange('2026-08-01', '2026-08-10')).toEqual({+ range: { preset: 'all', startDate: '2026-08-01', endDate: '2026-08-10' },+ })+ })++ it('supports an open-ended start bound only', () => {+ expect(buildCustomTimeRange('2026-08-01', '')).toEqual({+ range: { preset: 'all', startDate: '2026-08-01' },+ })+ })++ it('supports an open-ended end bound only', () => {+ expect(buildCustomTimeRange('', '2026-08-10')).toEqual({+ range: { preset: 'all', endDate: '2026-08-10' },+ })+ })++ it('rejects invalid formats', () => {+ expect(buildCustomTimeRange('2026/08/01', '2026-08-10')).toEqual({+ error: 'invalid',+ })+ expect(buildCustomTimeRange('2026-13-01', '')).toEqual({+ error: 'invalid',+ })+ expect(buildCustomTimeRange('', '')).toEqual({ error: 'invalid' })+ })++ it('rejects reversed ranges', () => {+ expect(buildCustomTimeRange('2026-08-10', '2026-08-01')).toEqual({+ error: 'order',+ })+ })+})++describe('last-seen tracking', () => {+ it('reports unseen experiences as updated until marked seen', () => {+ expect(+ isExperienceUpdatedSinceLastSeen(+ 'viking://user/u/memories/experiences/e.md',+ '2026-08-05T02:00:00Z',+ ),+ ).toBe(true)++ markExperiencesSeen([{ uri: 'viking://user/u/memories/experiences/e.md' }])++ expect(+ isExperienceUpdatedSinceLastSeen(+ 'viking://user/u/memories/experiences/e.md',+ '2026-08-05T02:00:00Z',+ ),+ ).toBe(false)+ expect(+ isExperienceUpdatedSinceLastSeen(+ 'viking://user/u/memories/experiences/e.md',+ undefined,+ ),+ ).toBe(false)+ })+})++describe('formatTimestamp', () => {+ it('formats parseable timestamps', () => {+ const formatted = formatTimestamp('2026-08-05T02:00:00Z', 'zh-CN')+ expect(formatted).toBeTruthy()+ expect(formatTimestamp('2026-08-05T02:00:00Z', 'zh-CN')).toBe(formatted)+ })++ it('returns undefined for missing or invalid values', () => {+ expect(formatTimestamp(undefined, 'zh-CN')).toBeUndefined()+ expect(formatTimestamp('', 'zh-CN')).toBeUndefined()+ expect(formatTimestamp('not-a-date', 'zh-CN')).toBeUndefined()+ })+})++describe('formatFileSize', () => {+ it('formats bytes, kilobytes and megabytes', () => {+ expect(formatFileSize(0)).toBe('0 B')+ expect(formatFileSize(512)).toBe('512 B')+ expect(formatFileSize(2048)).toBe('2 KB')+ expect(formatFileSize(1024 * 1024)).toBe('1 MB')+ expect(formatFileSize(1024 * 1024 * 1024)).toBe('1 GB')+ })++ it('returns undefined for missing or invalid sizes', () => {+ expect(formatFileSize(undefined)).toBeUndefined()+ expect(formatFileSize(-1)).toBeUndefined()+ expect(formatFileSize(Number.NaN)).toBeUndefined()+ })+})diff --git a/web-studio/src/routes/agent-experience/-lib/experience.ts b/web-studio/src/routes/agent-experience/-lib/experience.tsnew file mode 100644index 000000000..32e902889--- /dev/null+++ b/web-studio/src/routes/agent-experience/-lib/experience.ts@@ -0,0 +1,328 @@+import type {+ ExperienceFileItem,+ OutcomeCount,+ OutcomeDistribution,+ TimeRange,+ TimeRangePreset,+ TrajectoryItem,+ TrajectoryOutcome,+ TrajectoryPage,+} from './types'++/** Directory (relative to the user space root) that stores experience memories. */+export const EXPERIENCES_DIRECTORY = 'memories/experiences'++export const TRAJECTORY_OUTCOMES: readonly TrajectoryOutcome[] = [+ 'success',+ 'failure',+ 'partial',+ 'unknown',+ 'unfinished',+]++export const OUTCOME_COLORS: Record<TrajectoryOutcome, string> = {+ success: 'bg-emerald-500',+ failure: 'bg-rose-500',+ partial: 'bg-amber-500',+ unknown: 'bg-zinc-400',+ unfinished: 'bg-sky-500',+}++export const DEFAULT_TRAJECTORY_PAGE_SIZE = 20++/** Build the experiences directory URI for a given user id. */+export function buildExperiencesUri(userId: string): string {+ const normalized = userId.trim() || 'default'+ return `viking://user/${encodeURIComponent(normalized)}/${EXPERIENCES_DIRECTORY}`+}++/** Extract a display name from an experience URI (`exchange.md` -> `exchange`). */+export function getExperienceDisplayName(uri: string): string {+ const fileName = uri.split('/').filter(Boolean).pop() ?? uri+ return fileName.replace(/\.md$/i, '')+}++function isRecord(value: unknown): value is Record<string, unknown> {+ return typeof value === 'object' && value !== null && !Array.isArray(value)+}++function readString(value: unknown): string | undefined {+ return typeof value === 'string' && value ? value : undefined+}++export function normalizeExperienceFiles(value: unknown): ExperienceFileItem[] {+ if (!Array.isArray(value)) return []++ return value.flatMap((raw) => {+ const entry = isRecord(raw) ? raw : null+ if (!entry || entry.isDir === true) return []+ const name = readString(entry.name)+ const uri = readString(entry.uri)+ if (!name || !uri) return []+ return [+ {+ name,+ uri,+ modTime: readString(entry.modTime),+ size: typeof entry.size === 'number' ? entry.size : undefined,+ } satisfies ExperienceFileItem,+ ]+ })+}++/** Normalize `GET /api/v1/agent-evolution/experiences/trajectories` result. */+export function normalizeTrajectoryPage(+ value: unknown,+ experienceUri: string,+): TrajectoryPage | null {+ const result = isRecord(value) ? value : null+ if (!result) return null++ const rawItems = Array.isArray(result.items) ? result.items : []+ const items = rawItems.flatMap((raw) => {+ const item = isRecord(raw) ? raw : null+ const uri = item ? readString(item.uri) : undefined+ if (!item || !uri) return []++ return [+ {+ uri,+ name: readString(item.name) ?? uri.split('/').pop() ?? uri,+ description: readString(item.description),+ created_at: readString(item.created_at),+ updated_at: readString(item.updated_at),+ } satisfies TrajectoryItem,+ ]+ })++ const total = typeof result.total === 'number' ? result.total : items.length+ const limit = typeof result.limit === 'number' ? result.limit : items.length+ const offset = typeof result.offset === 'number' ? result.offset : 0++ return {+ experienceUri: readString(result.experience_uri) ?? experienceUri,+ items,+ total,+ limit,+ offset,+ hasMore:+ typeof result.has_more === 'boolean'+ ? result.has_more+ : offset + items.length < total,+ }+}++/** Normalize `GET /api/v1/agent-evolution/experiences/outcomes` result. */+export function normalizeOutcomeDistribution(+ value: unknown,+ experienceUri: string,+): OutcomeDistribution {+ const result = isRecord(value) ? value : null+ const rawDistribution = Array.isArray(result?.outcome_distribution)+ ? result.outcome_distribution+ : []+ const byOutcome = new Map<string, number>()++ for (const raw of rawDistribution) {+ const entry = isRecord(raw) ? raw : null+ const outcome = entry ? readString(entry.outcome) : undefined+ if (!entry || !outcome) continue+ byOutcome.set(outcome, Number(entry.count) || 0)+ }++ // The server always returns the five fixed buckets; fall back to zero for+ // missing entries so the UI renders a stable legend.+ const distribution: OutcomeCount[] = TRAJECTORY_OUTCOMES.map((outcome) => ({+ outcome,+ count: byOutcome.get(outcome) ?? 0,+ }))++ return {+ experienceUri: readString(result?.experience_uri) ?? experienceUri,+ distribution,+ }+}++function toUtcDate(date: Date): string {+ return date.toISOString().slice(0, 10)+}++/**+ * Resolve a quick time-range preset into UTC `YYYY-MM-DD` bounds.+ *+ * The Agent Evolution API filters trajectories by their UTC creation date, so+ * presets are computed in UTC as well. `all` disables filtering; `custom` is+ * built by {@link buildCustomTimeRange} and returns no bounds here.+ */+export function resolveTimeRange(+ preset: TimeRangePreset,+ now: Date = new Date(),+): TimeRange {+ if (preset === 'all' || preset === 'custom') {+ return { preset }+ }++ const days = preset === '7d' ? 7 : 30+ const end = new Date(now)+ const start = new Date(now)+ start.setUTCDate(start.getUTCDate() - (days - 1))++ return {+ preset,+ startDate: toUtcDate(start),+ endDate: toUtcDate(end),+ }+}++/** Format an ISO-ish timestamp for list display; returns `undefined` on garbage input. */+export function formatTimestamp(+ value: string | undefined,+ locale: string,+): string | undefined {+ if (!value) return undefined+ const date = new Date(value)+ if (Number.isNaN(date.getTime())) return undefined++ return new Intl.DateTimeFormat(locale, {+ dateStyle: 'medium',+ timeStyle: 'short',+ }).format(date)+}++/** Human readable file size for the experience list. */+export function formatFileSize(size: number | undefined): string | undefined {+ if (size === undefined || !Number.isFinite(size) || size < 0) return undefined+ if (size < 1024) return `${size} B`++ const units = ['KB', 'MB', 'GB']+ let value = size+ let unit = 'B'+ for (const next of units) {+ if (value < 1024) break+ value /= 1024+ unit = next+ }+ return `${value >= 10 ? Math.round(value) : Math.round(value * 10) / 10} ${unit}`+}++export type SourceTrajectoryLink = {+ uri: string+ reason?: string+}++export function normalizeSourceTrajectoryLinks(+ value: unknown,+): SourceTrajectoryLink[] {+ const result = isRecord(value) ? value : null+ const attrs = result && isRecord(result.attrs) ? result.attrs : null+ const memory = attrs && isRecord(attrs.memory) ? attrs.memory : null+ const links = memory && Array.isArray(memory.links) ? memory.links : []+ const seen = new Set<string>()++ return links.flatMap((raw) => {+ const link = isRecord(raw) ? raw : null+ const uri = link ? readString(link.to_uri) : undefined+ const linkType = link ? readString(link.link_type) : undefined+ if (+ !uri ||+ linkType !== 'derived_from' ||+ !uri.includes('/memories/trajectories/') ||+ seen.has(uri)+ ) {+ return []+ }+ seen.add(uri)+ const reason = readString(link?.description) ?? readString(link?.match_text)+ return [{ uri, reason } satisfies SourceTrajectoryLink]+ })+}++/** Local-storage key tracking the last time each experience was seen. */+const EXPERIENCE_LAST_SEEN_KEY = 'ov_agent_experience_last_seen'++type LastSeenMap = Record<string, number>++function readLastSeenMap(): LastSeenMap {+ if (typeof window === 'undefined') return {}+ try {+ const raw = window.localStorage.getItem(EXPERIENCE_LAST_SEEN_KEY)+ const parsed = raw ? (JSON.parse(raw) as unknown) : {}+ return isRecord(parsed)+ ? Object.fromEntries(+ Object.entries(parsed).flatMap(([uri, value]) =>+ typeof value === 'number' ? [[uri, value] as const] : [],+ ),+ )+ : {}+ } catch {+ return {}+ }+}++function writeLastSeenMap(map: LastSeenMap): void {+ if (typeof window === 'undefined') return+ try {+ window.localStorage.setItem(EXPERIENCE_LAST_SEEN_KEY, JSON.stringify(map))+ } catch {+ // Ignore storage failures (private mode, quota).+ }+}++/** Whether an experience was updated after the caller last saw it. */+export function isExperienceUpdatedSinceLastSeen(+ uri: string,+ modTime: string | undefined,+): boolean {+ if (!modTime) return false+ const updated = new Date(modTime).getTime()+ if (Number.isNaN(updated)) return false+ const map = readLastSeenMap()+ if (!Object.prototype.hasOwnProperty.call(map, uri)) return true+ return updated > map[uri]+}++/** Record "now" as the last-seen time for the given experiences. */+export function markExperiencesSeen(entries: readonly { uri: string }[]): void {+ if (entries.length === 0) return+ const map = readLastSeenMap()+ const now = Date.now()+ for (const entry of entries) {+ map[entry.uri] = now+ }+ writeLastSeenMap(map)+}++/** Parse a `YYYY-MM-DD` string; returns `undefined` when invalid. */+export function parseUtcDate(value: string): Date | undefined {+ if (!/^\d{4}-\d{2}-\d{2}$/.test(value.trim())) return undefined+ const date = new Date(`${value.trim()}T00:00:00Z`)+ return Number.isNaN(date.getTime()) ? undefined : date+}++/**+ * Build a custom time range from user-provided UTC dates.+ *+ * Returns an error key when the combination is invalid, so callers can+ * surface inline validation instead of firing a bad request.+ */+export function buildCustomTimeRange(+ startDate: string,+ endDate: string,+): { error?: 'invalid' | 'order'; range?: TimeRange } {+ const start = parseUtcDate(startDate)+ const end = parseUtcDate(endDate)+ const rawStart = startDate.trim()+ const rawEnd = endDate.trim()++ if ((rawStart && !start) || (rawEnd && !end)) return { error: 'invalid' }+ if (!rawStart && !rawEnd) return { error: 'invalid' }+ if (start && end && start > end) return { error: 'order' }++ return {+ range: {+ preset: 'all',+ startDate: rawStart || undefined,+ endDate: rawEnd || undefined,+ },+ }+}diff --git a/web-studio/src/routes/agent-experience/-lib/router-params.test.ts b/web-studio/src/routes/agent-experience/-lib/router-params.test.tsnew file mode 100644index 000000000..4e29e6280--- /dev/null+++ b/web-studio/src/routes/agent-experience/-lib/router-params.test.ts@@ -0,0 +1,43 @@+import { describe, expect, it } from 'vitest'++// These tests pin down the @tanstack/router param round-trip that the list and+// detail views rely on: Link params are percent-encoded when the href is built+// and decoded again when matched, so callers must pass the RAW viking URI.+describe('router param round-trip', () => {+ it('encodes params into the href and decodes them on match', async () => {+ const { createMemoryHistory, createRouter, createRootRoute, createRoute } =+ await import('@tanstack/react-router')++ const rawUri = 'viking://user/default/memories/experiences/exchange flow.md'+ const rootRoute = createRootRoute()+ const detailRoute = createRoute({+ getParentRoute: () => rootRoute,+ path: '/agent-experience/$experienceUri',+ })+ const routeTree = rootRoute.addChildren([detailRoute])+ const router = createRouter({+ history: createMemoryHistory({ initialEntries: ['/'] }),+ routeTree,+ })+ await router.load()++ const location = await router.buildLocation({+ params: { experienceUri: rawUri },+ to: '/agent-experience/$experienceUri',+ })++ expect(location.href).not.toContain('://')+ expect(decodeURIComponent(location.href)).toContain(rawUri)++ // Navigate and inspect the matched params.+ await router.navigate({+ params: { experienceUri: rawUri },+ to: '/agent-experience/$experienceUri',+ })+ await router.load()+ const match = router.state.matches.find(+ (item) => item.routeId === '/agent-experience/$experienceUri',+ )+ expect(match?.params.experienceUri).toBe(rawUri)+ })+})diff --git a/web-studio/src/routes/agent-experience/-lib/types.ts b/web-studio/src/routes/agent-experience/-lib/types.tsnew file mode 100644index 000000000..436cc2bdb--- /dev/null+++ b/web-studio/src/routes/agent-experience/-lib/types.ts@@ -0,0 +1,63 @@+export type ExperienceFileItem = {+ /** File name, e.g. `exchange.md`. */+ name: string+ /** Full Viking URI, e.g. `viking://user/default/memories/experiences/exchange.md`. */+ uri: string+ /** Last modification time reported by `GET /api/v1/fs/ls` (`modTime`). */+ modTime?: string+ /** File size in bytes. */+ size?: number+}++export type ExperiencePage = {+ items: ExperienceFileItem[]+ hasMore: boolean+ page: number+ pageSize: number+}++export type TrajectoryOutcome =+ 'success' | 'failure' | 'partial' | 'unknown' | 'unfinished'++export type OutcomeCount = {+ outcome: TrajectoryOutcome+ count: number+}++export type TrajectoryItem = {+ uri: string+ name: string+ description?: string+ created_at?: string+ updated_at?: string+}++export type TrajectoryPage = {+ experienceUri: string+ items: TrajectoryItem[]+ total: number+ limit: number+ offset: number+ hasMore: boolean+}++export type OutcomeDistribution = {+ experienceUri: string+ distribution: OutcomeCount[]+}++/** Quick time-range options shared by the outcome and trajectory queries. */+export type TimeRangePreset = 'all' | '7d' | '30d' | 'custom'++export type TimeRange = {+ preset: TimeRangePreset+ /** UTC `YYYY-MM-DD` inclusive lower bound, or `undefined` for no filter. */+ startDate?: string+ /** UTC `YYYY-MM-DD` inclusive upper bound, or `undefined` for no filter. */+ endDate?: string+}++export type AgentEvolutionStatus = {+ enabled: boolean+ accountId?: string+}diff --git a/web-studio/src/routes/agent-experience/index.tsx b/web-studio/src/routes/agent-experience/index.tsxnew file mode 100644index 000000000..d676caaba--- /dev/null+++ b/web-studio/src/routes/agent-experience/index.tsx@@ -0,0 +1,551 @@+import * as React from 'react'+import { useQuery } from '@tanstack/react-query'+import { Link, createFileRoute } from '@tanstack/react-router'+import {+ BrainCircuitIcon,+ FileTextIcon,+ ArrowUpRightIcon,+ LoaderCircleIcon,+ MessageSquareTextIcon,+ RefreshCwIcon,+ SearchIcon,+ XIcon,+} from 'lucide-react'+import { useTranslation } from 'react-i18next'++import { Badge } from '#/components/ui/badge'+import { Button } from '#/components/ui/button'+import { Card } from '#/components/ui/card'+import { Input } from '#/components/ui/input'+import {+ Pagination,+ PaginationContent,+ PaginationItem,+ PaginationNext,+ PaginationPrevious,+} from '#/components/ui/pagination'+import {+ Select,+ SelectContent,+ SelectItem,+ SelectTrigger,+ SelectValue,+} from '#/components/ui/select'+import {+ Table,+ TableBody,+ TableCell,+ TableHead,+ TableHeader,+ TableRow,+} from '#/components/ui/table'+import { useAppConnection } from '#/hooks/use-app-connection'+import { isOvClientError } from '#/lib/ov-client'+import { cn } from '#/lib/utils'++import { EvolutionSettingsPopover } from './-components/evolution-settings-popover'+import { ExperiencePreviewSheet } from './-components/experience-preview-sheet'+import { fetchExperiences } from './-lib/api'+import {+ buildExperiencesUri,+ formatTimestamp,+ isExperienceUpdatedSinceLastSeen,+ markExperiencesSeen,+} from './-lib/experience'+import type { ExperienceFileItem } from './-lib/types'++export const Route = createFileRoute('/agent-experience/')({+ component: AgentExperienceRoute,+})++function getErrorMessage(error: unknown): string {+ if (isOvClientError(error) || error instanceof Error) {+ return error.message+ }+ return String(error)+}++function HighlightedText({ keyword, text }: { keyword: string; text: string }) {+ const normalizedKeyword = keyword.trim().toLocaleLowerCase()+ if (!normalizedKeyword) return <>{text}</>++ const normalizedText = text.toLocaleLowerCase()+ const fragments: React.ReactNode[] = []+ let cursor = 0+ let matchIndex = normalizedText.indexOf(normalizedKeyword)++ while (matchIndex !== -1) {+ if (matchIndex > cursor) {+ fragments.push(text.slice(cursor, matchIndex))+ }+ const matchEnd = matchIndex + normalizedKeyword.length+ fragments.push(+ <mark+ key={`${matchIndex}-${matchEnd}`}+ className="rounded-xs bg-primary/15 px-0.5 text-inherit"+ >+ {text.slice(matchIndex, matchEnd)}+ </mark>,+ )+ cursor = matchEnd+ matchIndex = normalizedText.indexOf(normalizedKeyword, cursor)+ }+ if (cursor < text.length) {+ fragments.push(text.slice(cursor))+ }+ return <>{fragments}</>+}++function EmptyHelpChecklist() {+ const { t } = useTranslation('agentExperiencePage')+ const reasons = [+ t('help.reasonConnected'),+ t('help.reasonSessions'),+ t('help.reasonCommit'),+ ]++ return (+ <div className="grid max-w-md gap-2 rounded-lg border border-dashed bg-muted/30 px-4 py-3 text-left">+ <p className="text-sm text-muted-foreground">{t('help.title')}</p>+ <ol className="grid gap-1.5 text-sm text-muted-foreground">+ {reasons.map((reason, index) => (+ <li className="flex items-center gap-2" key={reason}>+ <span className="flex size-4 shrink-0 items-center justify-center rounded-full bg-muted text-[10px] font-medium text-muted-foreground">+ {index + 1}+ </span>+ {reason}+ </li>+ ))}+ </ol>+ </div>+ )+}++const EXPERIENCE_PAGE_SIZE_OPTIONS = [10, 20, 50, 100] as const++function ExperiencePagination({+ onPageChange,+ onPageSizeChange,+ page,+ hasMore,+ disabled,+ pageSize,+}: {+ onPageChange: (page: number) => void+ onPageSizeChange: (pageSize: number) => void+ page: number+ hasMore: boolean+ disabled: boolean+ pageSize: number+}) {+ const { t } = useTranslation('agentExperiencePage')++ return (+ <div className="flex flex-col gap-3 border-t border-border/60 px-5 py-4 sm:flex-row sm:items-center sm:justify-between">+ <div className="flex flex-wrap items-center justify-center gap-3 sm:justify-start">+ <p className="text-sm text-muted-foreground">+ {t('pagination.summary', { page })}+ </p>+ <Select+ disabled={disabled}+ value={String(pageSize)}+ onValueChange={(value) => onPageSizeChange(Number(value))}+ >+ <SelectTrigger size="sm" aria-label={t('pagination.pageSize')}>+ <SelectValue>+ {t('pagination.pageSizeValue', { count: pageSize })}+ </SelectValue>+ </SelectTrigger>+ <SelectContent>+ {EXPERIENCE_PAGE_SIZE_OPTIONS.map((option) => (+ <SelectItem key={option} value={String(option)}>+ {t('pagination.pageSizeValue', { count: option })}+ </SelectItem>+ ))}+ </SelectContent>+ </Select>+ </div>+ <Pagination className="mx-0 w-auto justify-center sm:justify-end">+ <PaginationContent>+ <PaginationItem>+ <PaginationPrevious+ href="#"+ text={t('pagination.previous')}+ aria-disabled={disabled || page <= 1}+ className={cn(+ (disabled || page <= 1) && 'pointer-events-none opacity-50',+ )}+ onClick={(event) => {+ event.preventDefault()+ if (!disabled && page > 1) onPageChange(page - 1)+ }}+ />+ </PaginationItem>+ <PaginationItem>+ <PaginationNext+ href="#"+ text={t('pagination.next')}+ aria-disabled={disabled || !hasMore}+ className={cn(+ (disabled || !hasMore) && 'pointer-events-none opacity-50',+ )}+ onClick={(event) => {+ event.preventDefault()+ if (!disabled && hasMore) onPageChange(page + 1)+ }}+ />+ </PaginationItem>+ </PaginationContent>+ </Pagination>+ </div>+ )+}++function AgentExperienceRoute() {+ const { t, i18n } = useTranslation('agentExperiencePage')+ const { connection, identityScopeKey } = useAppConnection()+ const [keyword, setKeyword] = React.useState('')+ const [page, setPage] = React.useState(1)+ const [pageSize, setPageSize] = React.useState(10)+ const [previewExperience, setPreviewExperience] =+ React.useState<ExperienceFileItem | null>(null)++ const experiencesUri = buildExperiencesUri(connection.userId)+ const experiencesQuery = useQuery({+ queryFn: ({ signal }) =>+ fetchExperiences({+ experiencesUri,+ page,+ pageSize,+ signal,+ }),+ queryKey: [+ 'agent-experience-list',+ identityScopeKey,+ experiencesUri,+ page,+ pageSize,+ ],+ staleTime: 30_000,+ })++ const pageItems = experiencesQuery.data?.items ?? []+ const hasMore = experiencesQuery.data?.hasMore ?? false+ const normalizedKeyword = keyword.trim().toLocaleLowerCase()+ const experiences = pageItems.filter(+ (item) =>+ !normalizedKeyword ||+ item.name.toLocaleLowerCase().includes(normalizedKeyword) ||+ item.uri.toLocaleLowerCase().includes(normalizedKeyword),+ )++ // Snapshot "updated since last visit" badges when the list settles, then+ // mark the whole list as seen. Comparing against the pre-visit snapshot+ // (instead of live state) keeps badges visible for the current visit.+ const [updatedUris, setUpdatedUris] = React.useState<ReadonlySet<string>>(+ () => new Set(),+ )+ const markedRef = React.useRef<string | null>(null)+ React.useEffect(() => {+ if (!experiencesQuery.isSuccess || experiences.length === 0) return+ const fingerprint = `${experiencesUri}:${experiences+ .map((item) => item.uri)+ .join('|')}`+ if (markedRef.current === fingerprint) return+ markedRef.current = fingerprint++ setUpdatedUris(+ new Set(+ experiences+ .filter((experience) =>+ isExperienceUpdatedSinceLastSeen(+ experience.uri,+ experience.modTime,+ ),+ )+ .map((experience) => experience.uri),+ ),+ )+ markExperiencesSeen(experiences)+ }, [experiences, experiencesQuery.isSuccess, experiencesUri])++ const connectionUnavailable =+ isOvClientError(experiencesQuery.error) &&+ experiencesQuery.error.code === 'NETWORK_ERROR'++ const handleOpenPreview = (experience: ExperienceFileItem) => {+ setPreviewExperience(experience)+ }++ return (+ <div className="flex w-full min-w-0 flex-col gap-6">+ <header className="flex flex-wrap items-start justify-between gap-4">+ <div className="grid gap-1.5">+ <div className="flex items-center gap-2.5">+ <h1 className="text-2xl font-semibold tracking-tight sm:text-3xl">+ {t('title')}+ </h1>+ </div>+ <p className="max-w-2xl text-sm leading-6 text-muted-foreground">+ {t('description')}+ </p>+ </div>+ <div className="flex items-center gap-2">+ <EvolutionSettingsPopover />+ <Button+ type="button"+ variant="outline"+ size="sm"+ disabled={experiencesQuery.isFetching}+ onClick={() => void experiencesQuery.refetch()}+ >+ <RefreshCwIcon+ className={+ experiencesQuery.isFetching ? 'animate-spin' : undefined+ }+ />+ {t('refresh')}+ </Button>+ </div>+ </header>++ {experiencesQuery.isLoading ? (+ <Card className="min-h-56 items-center justify-center">+ <div className="flex items-center gap-2 text-sm text-muted-foreground">+ <LoaderCircleIcon className="size-4 animate-spin" />+ {t('loading')}+ </div>+ </Card>+ ) : experiencesQuery.isError ? (+ <Card className="min-h-56 items-center justify-center px-6 text-center">+ <div className="grid gap-1">+ <p className="font-medium">{t('loadFailed')}</p>+ <p className="max-w-xl text-sm text-muted-foreground">+ {connectionUnavailable+ ? t('networkError')+ : getErrorMessage(experiencesQuery.error)}+ </p>+ {connectionUnavailable ? (+ <Button+ render={<Link to="/settings" />}+ nativeButton={false}+ variant="outline"+ size="sm"+ className="mx-auto mt-2"+ >+ {t('connectionSettings')}+ </Button>+ ) : (+ <Button+ type="button"+ variant="outline"+ size="sm"+ className="mx-auto mt-2"+ disabled={experiencesQuery.isFetching}+ onClick={() => void experiencesQuery.refetch()}+ >+ <RefreshCwIcon+ className={+ experiencesQuery.isFetching ? 'animate-spin' : undefined+ }+ />+ {t('refresh')}+ </Button>+ )}+ </div>+ </Card>+ ) : pageItems.length === 0 &&+ page === 1 &&+ !hasMore &&+ !keyword.trim() ? (+ <Card className="min-h-56 items-center justify-center px-6 text-center">+ <div className="flex size-10 items-center justify-center rounded-xl bg-primary/10 text-primary">+ <BrainCircuitIcon className="size-5" />+ </div>+ <div className="grid max-w-md gap-1">+ <p className="font-medium">{t('empty')}</p>+ <p className="text-sm text-muted-foreground">+ {t('emptyDescription')}+ </p>+ <Button+ render={<Link to="/sessions" />}+ nativeButton={false}+ variant="outline"+ size="sm"+ className="mx-auto mt-3"+ >+ <MessageSquareTextIcon />+ {t('emptyAction')}+ </Button>+ </div>+ <div className="pt-4">+ <EmptyHelpChecklist />+ </div>+ </Card>+ ) : (+ <Card+ size="sm"+ className="rounded-xl bg-background shadow-none ring-border/70 data-[size=sm]:gap-0 data-[size=sm]:py-0"+ >+ <div className="flex flex-wrap items-center justify-end gap-3 border-b border-border/60 px-5 py-4">+ <div className="relative w-full sm:max-w-sm">+ <SearchIcon className="pointer-events-none absolute top-1/2 left-2.5 size-4 -translate-y-1/2 text-muted-foreground" />+ <Input+ aria-label={t('searchPlaceholder')}+ autoComplete="off"+ className="h-9 bg-transparent pr-9 pl-8 shadow-none dark:bg-transparent"+ name="agent-experience-search"+ placeholder={t('searchPlaceholder')}+ value={keyword}+ onChange={(event) => {+ setKeyword(event.target.value)+ }}+ />+ {keyword ? (+ <button+ type="button"+ aria-label={t('searchClear')}+ className="absolute top-1/2 right-2 flex size-6 -translate-y-1/2 items-center justify-center rounded-md text-muted-foreground transition-colors hover:bg-muted hover:text-foreground"+ onClick={() => {+ setKeyword('')+ }}+ >+ <XIcon className="size-3.5" />+ </button>+ ) : null}+ </div>+ </div>++ {experiences.length === 0 ? (+ <div className="grid min-h-40 place-items-center px-6 py-8 text-center">+ <div className="grid max-w-md gap-1">+ <p className="font-medium">{t('searchNoResults')}</p>+ <p className="text-sm text-muted-foreground">+ {t('searchNoResultsDescription')}+ </p>+ </div>+ </div>+ ) : (+ <Table>+ <TableHeader>+ <TableRow className="bg-muted/20 hover:bg-muted/20">+ <TableHead className="h-10 pl-5 text-xs font-normal text-muted-foreground">+ {t('columnFile')}+ </TableHead>+ <TableHead className="h-10 w-44 text-xs font-normal text-muted-foreground">+ {t('columnUpdated')}+ </TableHead>+ <TableHead className="h-10 w-28 pr-5 text-right text-xs font-normal text-muted-foreground">+ {t('columnActions')}+ </TableHead>+ </TableRow>+ </TableHeader>+ <TableBody>+ {experiences.map((experience) => {+ const updated = formatTimestamp(+ experience.modTime,+ i18n.language,+ )+ const isUpdated = updatedUris.has(experience.uri)++ return (+ <TableRow+ key={experience.uri}+ className="group cursor-pointer border-border/50 transition-colors hover:bg-muted/30"+ onClick={() => handleOpenPreview(experience)}+ >+ <TableCell className="max-w-0 py-2.5 pl-5">+ <div className="flex min-w-0 items-center gap-3">+ <span className="flex size-9 shrink-0 items-center justify-center rounded-lg border border-border/70 text-muted-foreground transition-colors group-hover:border-primary/30 group-hover:text-primary">+ <FileTextIcon className="size-4" />+ </span>+ <div className="grid min-w-0 gap-1">+ <div className="flex min-w-0 items-center gap-1.5">+ <button+ type="button"+ className="min-w-0 truncate text-left font-medium underline-offset-2 hover:underline focus-visible:outline-none focus-visible:ring-3 focus-visible:ring-ring/50"+ onClick={(event) => {+ event.stopPropagation()+ handleOpenPreview(experience)+ }}+ >+ <HighlightedText+ keyword={normalizedKeyword}+ text={experience.name}+ />+ </button>+ {isUpdated ? (+ <Badge+ variant="secondary"+ className="h-4 shrink-0 px-1 text-[10px]"+ >+ {t('updatedBadge')}+ </Badge>+ ) : null}+ </div>+ <span+ className="truncate font-mono text-[11px] text-muted-foreground/80"+ title={experience.uri}+ >+ <HighlightedText+ keyword={normalizedKeyword}+ text={experience.uri}+ />+ </span>+ </div>+ </div>+ </TableCell>+ <TableCell className="w-44 text-xs text-muted-foreground">+ {updated ?? '-'}+ </TableCell>+ <TableCell+ className="w-28 pr-5 text-right"+ onClick={(event) => event.stopPropagation()}+ >+ <Button+ render={+ <Link+ params={{ experienceUri: experience.uri }}+ to="/agent-experience/$experienceUri"+ />+ }+ nativeButton={false}+ size="xs"+ variant="ghost"+ className="gap-1 text-muted-foreground hover:text-foreground"+ aria-label={t('openDetail', {+ name: experience.name,+ })}+ >+ {t('viewAnalysis')}+ <ArrowUpRightIcon className="size-3.5" />+ </Button>+ </TableCell>+ </TableRow>+ )+ })}+ </TableBody>+ </Table>+ )}+ <ExperiencePagination+ page={page}+ hasMore={hasMore}+ disabled={experiencesQuery.isFetching}+ pageSize={pageSize}+ onPageChange={setPage}+ onPageSizeChange={(nextPageSize) => {+ setPageSize(nextPageSize)+ setPage(1)+ }}+ />+ </Card>+ )}++ <ExperiencePreviewSheet+ experience={previewExperience}+ language={i18n.language}+ onClose={() => setPreviewExperience(null)}+ />+ </div>+ )+}diff --git a/web-studio/src/routes/agent-experience/route.tsx b/web-studio/src/routes/agent-experience/route.tsxnew file mode 100644index 000000000..466cff9a8--- /dev/null+++ b/web-studio/src/routes/agent-experience/route.tsx@@ -0,0 +1,10 @@+import { Outlet, createFileRoute } from '@tanstack/react-router'++export const Route = createFileRoute('/agent-experience')({+ component: AgentExperienceLayout,+})++/** Layout shell shared by the list and detail views. */+function AgentExperienceLayout() {+ return <Outlet />+}diff --git a/web-studio/src/routes/sessions/-components/memory-impact.tsx b/web-studio/src/routes/sessions/-components/memory-impact.tsxindex 6f12446b2..7b0649541 100644--- a/web-studio/src/routes/sessions/-components/memory-impact.tsx+++ b/web-studio/src/routes/sessions/-components/memory-impact.tsx@@ -1,5 +1,7 @@import { useMemo, useState } from 'react'+import { Link } from '@tanstack/react-router'import {+ BarChart3Icon,BrainCircuitIcon,FilePenLineIcon,FilePlus2Icon,@@ -307,6 +309,7 @@ function OperationRow({}) {const { t } = useTranslation('sessions')const { icon: Icon, text } = KIND_STYLES[operation.kind]+ const isExperience = operation.memoryType === 'experiences'return (<details className="group border-b last:border-b-0">@@ -318,6 +321,18 @@ function OperationRow({<Badge className="max-w-28" variant="outline"><span className="truncate">{operation.memoryType}</span></Badge>+ {isExperience ? (+ <Link+ aria-label={t('impact.viewExperienceImpact')}+ params={{ experienceUri: operation.uri }}+ title={t('impact.viewExperienceImpact')}+ to="/agent-experience/$experienceUri"+ className="inline-flex size-6 shrink-0 items-center justify-center rounded-md text-muted-foreground transition-colors hover:bg-muted hover:text-foreground focus-visible:outline-none focus-visible:ring-3 focus-visible:ring-ring/50"+ onClick={(event) => event.stopPropagation()}+ >+ <BarChart3Icon className="size-3.5" />+ </Link>+ ) : null}<span className="text-[10px] text-muted-foreground transition-transform group-open:rotate-90">›</span>