diff --git a/src/components/BottomPanel.tsx b/src/components/BottomPanel.tsx index 6c8fac9c..f41d6974 100644 --- a/src/components/BottomPanel.tsx +++ b/src/components/BottomPanel.tsx @@ -13,6 +13,7 @@ const Terminal = lazy(() => import('./Terminal').then(module => ({ default: modu const SessionChangesPanel = lazy(() => import('./SessionChangesPanel').then(module => ({ default: module.SessionChangesPanel })), ) +const ContextPanel = lazy(() => import('./ContextPanel').then(module => ({ default: module.ContextPanel }))) const FileExplorer = lazy(() => import('./FileExplorer').then(module => ({ default: module.FileExplorer }))) const McpPanel = lazy(() => import('./McpPanel').then(module => ({ default: module.McpPanel }))) const SkillPanel = lazy(() => import('./SkillPanel').then(module => ({ default: module.SkillPanel }))) @@ -108,6 +109,12 @@ export const BottomPanel = memo(function BottomPanel({ directory, serverId, term ) : null} + {activeTab.type === 'context' ? ( + }> + + + ) : null} + {activeTab.type === 'terminal' ? ( }> diff --git a/src/components/ContextPanel.test.tsx b/src/components/ContextPanel.test.tsx new file mode 100644 index 00000000..68398637 --- /dev/null +++ b/src/components/ContextPanel.test.tsx @@ -0,0 +1,106 @@ +import { render, screen } from '@testing-library/react' +import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' +import type { ApiSession } from '../api' +import { SessionContext, type SessionContextValue } from '../contexts/SessionContext.shared' +import i18n from '../i18n' +import { messageStore } from '../store/messageStore' +import type { SessionMessageInfo } from '../types/api/message' +import { ContextPanel } from './ContextPanel' + +vi.mock('../hooks/useModels', () => ({ + useModels: () => ({ + models: [ + { + id: 'deepseek-v4.1-flash-free', + providerID: 'opencode', + name: 'DeepSeek V4.1 Flash Free', + status: 'active', + limit: { context: 1_000_000 }, + }, + ], + providers: [{ id: 'opencode', name: 'OpenCode' }], + isLoading: false, + error: null, + refetch: async () => undefined, + }), +})) + +const messages: SessionMessageInfo[] = [ + { id: 'u1', type: 'user', time: { created: 1 }, text: 'hi' }, + { + id: 'a1', + type: 'assistant', + time: { created: 2 }, + agent: 'default', + model: { id: 'deepseek-v4.1-flash-free', providerID: 'opencode' }, + content: [{ type: 'text', text: 'ok' }], + tokens: { input: 226, output: 268, reasoning: 67, cache: { read: 130688, write: 0 } }, + }, +] + +const session = { + id: 'ses_1', + title: 'OpenCode deepseek-v4.1-flash-free 上下文查询', + cost: 0, + projectID: 'project', + tokens: { input: 0, output: 0, reasoning: 0, cache: { read: 0, write: 0 } }, + time: { created: Date.UTC(2026, 9, 17, 6, 45), updated: Date.UTC(2026, 9, 17, 6, 45) }, + location: { directory: '/repo' }, +} as ApiSession + +function renderPanel(sessionId: string | null) { + const value: SessionContextValue = { + sessions: [session], + isLoading: false, + isLoadingMore: false, + hasMore: false, + search: '', + setSearch: () => undefined, + refresh: async () => undefined, + loadMore: async () => undefined, + createSession: async () => session, + deleteSession: async () => undefined, + } + return render( + + + , + ) +} + +describe('ContextPanel', () => { + const previousLanguage = i18n.language + + beforeEach(async () => { + messageStore.clearAll() + await i18n.changeLanguage('zh-CN') + }) + + afterEach(async () => { + messageStore.clearAll() + await i18n.changeLanguage(previousLanguage) + }) + + it('shows live session context stats on the official field list', () => { + messageStore.setMessages('local::ses_1', messages, { title: session.title, directory: '/repo' }) + renderPanel('local::ses_1') + + expect(screen.getByText('会话').parentElement).toHaveTextContent(session.title!) + expect(screen.getByText('消息数').parentElement).toHaveTextContent('2') + expect(screen.getByText('提供商').parentElement).toHaveTextContent('OpenCode') + expect(screen.getByText('模型').parentElement).toHaveTextContent('DeepSeek V4.1 Flash Free') + expect(screen.getByText('上下文限制').parentElement).toHaveTextContent('1,000,000') + expect(screen.getByText('词元总数').parentElement).toHaveTextContent('131,249') + expect(screen.getByText('使用率').parentElement).toHaveTextContent('13%') + expect(screen.getByText('输入词元').parentElement).toHaveTextContent('226') + expect(screen.getByText('输出词元').parentElement).toHaveTextContent('268') + expect(screen.getByText('推理词元').parentElement).toHaveTextContent('67') + expect(screen.getByText('缓存词元(读/写)').parentElement).toHaveTextContent('130,688 / 0') + expect(screen.getByText('导出会话')).toBeInTheDocument() + }) + + it('asks for a session when none is focused', () => { + renderPanel(null) + expect(screen.getByText('没有活跃会话')).toBeInTheDocument() + }) +}) diff --git a/src/components/ContextPanel.tsx b/src/components/ContextPanel.tsx new file mode 100644 index 00000000..5d681006 --- /dev/null +++ b/src/components/ContextPanel.tsx @@ -0,0 +1,233 @@ +import { memo, useCallback, useRef, useState, useSyncExternalStore } from 'react' +import { useTranslation } from 'react-i18next' +import { ChevronDownIcon, ChevronUpIcon, DownloadIcon } from './Icons' +import { Button } from './ui' +import { CodeBlock } from './CodeBlock' +import { exportSession } from '../api/session' +import { useSessionContext } from '../contexts/useSessionContext' +import { useModels } from '../hooks/useModels' +import { childSessionStore } from '../store/childSessionStore' +import { messageStore } from '../store/messageStore' +import { saveData } from '../utils/downloadUtils' +import { uiErrorHandler } from '../utils' +import { sessionDisplayTitle } from '../utils/sessionTitle' +import { splitSessionKey } from '../utils/sessionKey' +import { + buildContextPageModel, + formatContextCost, + formatContextNumber, + formatContextPercent, + formatContextTime, + sumSessionCost, +} from './contextPageModel' + +interface ContextPanelProps { + sessionId?: string | null + serverId?: string +} + +function useLiveSessionTick(sessionId: string | null) { + const version = useRef(0) + const subscribe = useCallback( + (onStoreChange: () => void) => { + let timer: ReturnType | null = null + const bump = () => { + if (timer) { + clearTimeout(timer) + timer = null + } + version.current += 1 + onStoreChange() + } + const schedule = () => { + if (sessionId && !messageStore.getIsStreaming(sessionId)) { + bump() + return + } + if (timer) return + timer = setTimeout(bump, 200) + } + const unsubMessages = messageStore.subscribe(schedule) + const unsubChildren = childSessionStore.subscribe(schedule) + return () => { + unsubMessages() + unsubChildren() + if (timer) clearTimeout(timer) + } + }, + [sessionId], + ) + return useSyncExternalStore( + subscribe, + () => version.current, + () => version.current, + ) +} + +function Stat({ label, value }: { label: string; value: string }) { + return ( +
+
{label}
+
{value}
+
+ ) +} + +export const ContextPanel = memo(function ContextPanel({ sessionId, serverId }: ContextPanelProps) { + const { t } = useTranslation(['components', 'commands']) + + if (!sessionId) { + return ( +
+ {t('rightPanel.noActiveSession')} +
+ ) + } + + return +}) + +function ContextPanelBody({ sessionId, serverId }: { sessionId: string; serverId?: string }) { + const { t, i18n } = useTranslation(['components', 'commands']) + const { sessions } = useSessionContext() + const { models, providers } = useModels(serverId) + useLiveSessionTick(sessionId) + const [expandedId, setExpandedId] = useState(null) + const [exporting, setExporting] = useState(false) + const locale = i18n.resolvedLanguage || i18n.language || 'en' + + const state = messageStore.getSessionState(sessionId) + const rawId = splitSessionKey(sessionId).sessionId + const info = sessions.find(session => session.id === rawId) + const storedTitle = state?.title || info?.title + const sessionTitle = storedTitle + ? sessionDisplayTitle( + { title: storedTitle, parentID: info?.parentID }, + { + newSession: t('commands:sessions.newSession'), + childSession: t('commands:sessions.childSession'), + }, + ) + : rawId + const isChild = Boolean(info?.parentID || childSessionStore.getSessionInfo(sessionId)) + const ownCost = state?.cost ?? info?.cost ?? 0 + const childCosts = isChild + ? [] + : childSessionStore.getChildSessionIds(sessionId).map(childKey => messageStore.getSessionState(childKey)?.cost ?? 0) + const created = info?.time.created ?? childSessionStore.getSessionInfo(sessionId)?.createdAt + const page = buildContextPageModel({ + messages: state?.messages ?? [], + boundary: state?.revertState?.messageId, + sessionTitle, + sessionId: rawId, + created, + cost: sumSessionCost(ownCost, childCosts, isChild), + models, + providers, + }) + + const rows = [ + { label: t('contextPanel.session'), value: page.sessionLabel }, + { label: t('contextPanel.messages'), value: formatContextNumber(page.messageCount, locale) }, + { label: t('contextPanel.provider'), value: page.providerLabel }, + { label: t('contextPanel.model'), value: page.modelLabel }, + { label: t('contextPanel.limit'), value: formatContextNumber(page.limit, locale) }, + { label: t('contextPanel.totalTokens'), value: formatContextNumber(page.total, locale) }, + { label: t('contextPanel.usage'), value: formatContextPercent(page.usage, locale) }, + { label: t('contextPanel.inputTokens'), value: formatContextNumber(page.input, locale) }, + { label: t('contextPanel.outputTokens'), value: formatContextNumber(page.output, locale) }, + { label: t('contextPanel.reasoningTokens'), value: formatContextNumber(page.reasoning, locale) }, + { + label: t('contextPanel.cacheTokens'), + value: `${formatContextNumber(page.cacheRead, locale)} / ${formatContextNumber(page.cacheWrite, locale)}`, + }, + { label: t('contextPanel.userMessages'), value: formatContextNumber(page.userCount, locale) }, + { label: t('contextPanel.assistantMessages'), value: formatContextNumber(page.assistantCount, locale) }, + { label: t('contextPanel.totalCost'), value: formatContextCost(page.cost, locale) }, + { label: t('contextPanel.sessionCreated'), value: formatContextTime(page.created, locale) }, + { label: t('contextPanel.lastActivity'), value: formatContextTime(page.lastActivity, locale) }, + ] + + const messages = messageStore.getSessionState(sessionId)?.messages ?? [] + + const handleExport = useCallback(async () => { + setExporting(true) + try { + const transfer = await exportSession(sessionId, undefined, serverId) + const raw = messageStore.getSessionState(sessionId)?.title || '' + const name = raw + .toLowerCase() + .replace(/[^a-z0-9_-]+/gi, '-') + .replace(/^-+|-+$/g, '') + saveData( + new TextEncoder().encode(JSON.stringify(transfer, null, 2)), + `${name || splitSessionKey(sessionId).sessionId}.json`, + 'application/json', + ) + } catch (error) { + uiErrorHandler('export session', error) + } finally { + setExporting(false) + } + }, [serverId, sessionId]) + + return ( +
+
+
+ {rows.map(row => ( + + ))} +
+ + {page.systemPrompt && ( +
+

{t('contextPanel.systemPrompt')}

+
+              {page.systemPrompt}
+            
+
+ )} + +
+
+

{t('contextPanel.rawMessages')}

+ +
+
+ {messages.map(message => { + const isExpanded = expandedId === message.id + return ( +
+ + {isExpanded && ( +
+ +
+ )} +
+ ) + })} +
+
+
+
+ ) +} diff --git a/src/components/PanelContainer.tsx b/src/components/PanelContainer.tsx index d8aa908c..5594c43a 100644 --- a/src/components/PanelContainer.tsx +++ b/src/components/PanelContainer.tsx @@ -16,6 +16,7 @@ import { PlugIcon, TeachIcon, GitWorktreeIcon, + CpuIcon, } from './Icons' import { layoutStore, useLayoutStore, type PanelTab, type PanelPosition, type PanelTabType } from '../store/layoutStore' import { updatePtySession } from '../api/pty' @@ -47,6 +48,7 @@ const TAB_ICONS: Record = { terminal: , files: , changes: , + context: , mcp: , skill: , worktree: , @@ -71,6 +73,8 @@ function getTabLabel(tab: PanelTab, tabs: PanelTab[], t: (key: string) => string if (changesTabs.length <= 1) return t('panelContainer.changes') return `${t('panelContainer.changes')} ${changesTabs.findIndex(item => item.id === tab.id) + 1}` } + case 'context': + return t('panelContainer.context') case 'mcp': return t('panelContainer.mcp') case 'skill': @@ -471,6 +475,18 @@ export const PanelContainer = memo(function PanelContainer({ {t('panelContainer.changes')} +