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: add Studio playground workspace (#2352)
yufeng93aab7761eb3
diff --git a/web-studio/src/components/app-shell.tsx b/web-studio/src/components/app-shell.tsxindex 31248ce33..17db480a8 100644--- a/web-studio/src/components/app-shell.tsx+++ b/web-studio/src/components/app-shell.tsx@@ -89,6 +89,12 @@ const NAV_ITEMS: readonly NavItem[] = [titleKey: 'navigation.home.title',to: '/home',},+ {+ icon: PlugZapIcon,+ id: 'studio',+ titleKey: 'navigation.studio.title',+ to: '/studio',+ },{icon: FolderTreeIcon,id: 'resources',@@ -461,7 +467,9 @@ function AppShellInner({ children }: { children: React.ReactNode }) {className="text-base"><KeyRoundIcon className="size-5" />- <span>{t('navigation.oauthSetup.title', { ns: 'appShell' })}</span>+ <span>+ {t('navigation.oauthSetup.title', { ns: 'appShell' })}+ </span></SidebarMenuButton></SidebarMenuItem><SidebarMenuItem>diff --git a/web-studio/src/hooks/use-app-connection.tsx b/web-studio/src/hooks/use-app-connection.tsxindex 83d3ffcc2..ea435695c 100644--- a/web-studio/src/hooks/use-app-connection.tsx+++ b/web-studio/src/hooks/use-app-connection.tsx@@ -32,12 +32,33 @@ type AppConnectionContextValue = {const CONNECTION_STORAGE_KEY = 'ov_console_connection'+const ENV_BASE_URL =+ typeof import.meta.env.VITE_OV_BASE_URL === 'string'+ ? import.meta.env.VITE_OV_BASE_URL.trim()+ : ''+const ENV_API_KEY =+ typeof import.meta.env.VITE_OV_API_KEY === 'string'+ ? import.meta.env.VITE_OV_API_KEY.trim()+ : ''+const ENV_ACCOUNT =+ typeof import.meta.env.VITE_OV_ACCOUNT === 'string'+ ? import.meta.env.VITE_OV_ACCOUNT.trim()+ : ''+const ENV_AGENT =+ typeof import.meta.env.VITE_OV_AGENT === 'string'+ ? import.meta.env.VITE_OV_AGENT.trim()+ : ''+const ENV_USER =+ typeof import.meta.env.VITE_OV_USER === 'string'+ ? import.meta.env.VITE_OV_USER.trim()+ : ''+const DEFAULT_CONNECTION: ConnectionDraft = {- accountId: 'default',- agentId: 'web-studio',- apiKey: '',+ accountId: ENV_ACCOUNT || 'default',+ agentId: ENV_AGENT || 'web-studio',+ apiKey: ENV_API_KEY,baseUrl: ovClient.getOptions().baseUrl,- userId: 'default',+ userId: ENV_USER || 'default',}const AppConnectionContext =@@ -81,7 +102,9 @@ function persistConnection(connection: ConnectionDraft): void {}}-function normalizeConnectionDraft(connection: ConnectionDraft): ConnectionDraft {+function normalizeConnectionDraft(+ connection: ConnectionDraft,+): ConnectionDraft {return {accountId: connection.accountId.trim(),agentId: connection.agentId.trim() || DEFAULT_CONNECTION.agentId,@@ -108,10 +131,18 @@ function readInitialConnection(): ConnectionDraft {return normalizeConnectionDraft({...DEFAULT_CONNECTION,...storedConnection,+ accountId:+ ENV_ACCOUNT || storedConnection.accountId || DEFAULT_CONNECTION.accountId,+ agentId:+ ENV_AGENT || storedConnection.agentId || DEFAULT_CONNECTION.agentId,apiKey:+ ENV_API_KEY ||ovClient.getConnection().apiKey ||storedConnection.apiKey ||DEFAULT_CONNECTION.apiKey,+ baseUrl:+ ENV_BASE_URL || storedConnection.baseUrl || DEFAULT_CONNECTION.baseUrl,+ userId: ENV_USER || storedConnection.userId || DEFAULT_CONNECTION.userId,})}@@ -215,8 +246,7 @@ export function AppConnectionProvider({connection,isConnectionDialogOpen,openConnectionDialog: () => setConnectionDialogOpen(true),- saveConnection: (next) =>- setConnection(normalizeConnectionDraft(next)),+ saveConnection: (next) => setConnection(normalizeConnectionDraft(next)),serverMode,setConnectionDialogOpen,}),diff --git a/web-studio/src/i18n/locales/en.ts b/web-studio/src/i18n/locales/en.tsindex f24dfa099..4351e7305 100644--- a/web-studio/src/i18n/locales/en.ts+++ b/web-studio/src/i18n/locales/en.ts@@ -30,6 +30,9 @@ const en = {sessions: {title: 'Sessions',},+ studio: {+ title: 'Playground',+ },},sidebar: {loadingSessions: 'Loading...',@@ -766,6 +769,123 @@ const en = {'Sign in to OpenViking Studio (Connection & Identity) or paste an API key below to verify.',},},+ studio: {+ copyUri: 'Copy current URI',+ copied: 'URI copied',+ resizeContext: 'Resize context tree width',+ resizeAction: 'Resize Terminal and Agent width',+ readFailed: 'Failed to read {{uri}}',+ tabs: {+ terminal: 'Terminal',+ agent: 'Agent',+ },+ addResource: {+ title: 'Add resource',+ description:+ 'After it finishes, the context tree on the left refreshes and the Terminal on the right can locate the new resource.',+ submitted: 'Resource add task submitted',+ },+ explorer: {+ title: 'Context tree',+ addResource: 'Add resource',+ refresh: 'Refresh tree',+ namespaces: {+ user: 'Personalized user memories',+ session: 'Raw sessions between the user and the Agent',+ agent: "The Agent's capabilities, tools and experience",+ resources: 'External resources the Agent can reference',+ },+ },+ agent: {+ autoRetrieve: 'The Agent retrieves on its own from messages and tools',+ history: 'Session history',+ newSession: 'New session',+ creating: 'Creating Studio session...',+ detectingBot: 'Detecting bot mode...',+ createFailed: 'Failed to create session: {{error}}',+ retry: 'Retry',+ botDisabledFooter: 'Enable bot mode to chat with the Agent',+ historyTitle: 'Agent session history',+ historyDescription:+ 'Only sessions used by the Agent panel are shown here; a new session opens a blank Agent context.',+ loadingSessions: 'Loading sessions...',+ noSessions: 'No session history yet',+ createTimeout:+ 'Creating the Studio session timed out. Check your connection settings and try again.',+ newSessionTitle: 'New Studio session',+ botPrompt: {+ title: 'Please enable bot mode',+ description:+ 'The current service has not enabled Agent chat. Start the service in bot mode and try again.',+ retry: 'Detect again',+ },+ empty: {+ heading: 'Agent actions sync with the tree on the left',+ body: 'After you send a question, `viking://` files in the tool call output become clickable links — click to locate them on the left and open them in the middle.',+ prompts: [+ 'Summarize the current directory',+ 'Recursively find related docs',+ 'Explain how this resource relates to the project',+ ],+ },+ },+ terminal: {+ welcomeTitle: 'Terminal connected to the context tree',+ welcomeBody:+ 'Run /status, /ls, /search, /read, /add-resource. Resource links in the output locate the left tree and open the middle preview.',+ opened: 'Resource opened',+ onlineTitle: 'Service online',+ onlineBody:+ 'OpenViking API responded normally; found {{count}} nodes under the root.',+ lsBody: 'Showing {{count}} nodes under {{uri}}.',+ fileEmpty: 'File is empty; opened in the middle preview.',+ searchUsage: 'Usage: {{name}} <query>',+ readUsage: 'Usage: /read viking://resources/...',+ enterUri: 'Please enter a viking:// URI',+ hits: 'Hit {{resources}} resources, {{memories}} memories, {{skills}} skills.',+ addResourceBody:+ 'Opened the add-resource dialog. After submitting, the left tree refreshes; use /ls or /search to keep locating new content.',+ addResourceTitle: 'Add resource',+ unknownCommand:+ 'Unknown command. Available: /status, /ls, /search, /find, /read, /add-resource.',+ commandFailed: 'Command failed',+ running: 'Running command...',+ placeholder: 'Enter a CLI command, e.g. /status',+ suggestionsTitle: 'Command suggestions',+ suggestionsHint: '↑↓ select · Tab complete · Enter run',+ groupLabels: {+ resources: 'resource',+ memories: 'memory',+ skills: 'skill',+ },+ commands: {+ status: {+ description: 'Check the OpenViking API and root directory',+ usage: '/status',+ },+ ls: {+ description: 'List the current or a given directory',+ usage: '/ls [viking://resources/...]',+ },+ search: {+ description: 'Semantic search within the current context scope',+ usage: '/search <query>',+ },+ find: {+ description: 'Find related context resources',+ usage: '/find <query>',+ },+ read: {+ description: 'Read and open a resource file',+ usage: '/read viking://resources/.../file.md',+ },+ addResource: {+ description: 'Open the add-resource form',+ usage: '/add-resource',+ },+ },+ },+ },} as constexport default endiff --git a/web-studio/src/i18n/locales/zh-CN.ts b/web-studio/src/i18n/locales/zh-CN.tsindex 790678485..0efe21050 100644--- a/web-studio/src/i18n/locales/zh-CN.ts+++ b/web-studio/src/i18n/locales/zh-CN.ts@@ -30,6 +30,9 @@ const zhCN = {sessions: {title: '会话',},+ studio: {+ title: '实验场',+ },},sidebar: {loadingSessions: '加载中...',@@ -749,6 +752,121 @@ const zhCN = {'请先在“连接与身份”中登录 OpenViking Studio,或在下方临时粘贴 API key 完成授权。',},},+ studio: {+ copyUri: '复制当前 URI',+ copied: '已复制 URI',+ resizeContext: '调整上下文目录宽度',+ resizeAction: '调整 Terminal 和 Agent 宽度',+ readFailed: '无法读取 {{uri}}',+ tabs: {+ terminal: '终端',+ agent: 'Agent',+ },+ addResource: {+ title: '添加资源',+ description:+ '添加完成后左侧目录树会刷新,右侧 Terminal 可继续定位新资源。',+ submitted: '资源添加任务已提交',+ },+ explorer: {+ title: '上下文目录',+ addResource: '添加资源',+ refresh: '刷新目录',+ namespaces: {+ user: '用户个性化记忆',+ session: '用户与 Agent 的原始会话',+ agent: 'Agent 的能力、工具和经验',+ resources: 'Agent 可引用的外部资源',+ },+ },+ agent: {+ autoRetrieve: 'Agent 会根据消息和工具自主检索',+ history: '历史会话',+ newSession: '新建会话',+ creating: '正在创建 Studio 会话...',+ detectingBot: '正在检测 bot 模式...',+ createFailed: '创建会话失败:{{error}}',+ retry: '重试',+ botDisabledFooter: '开启 bot 模式后可使用 Agent 对话',+ historyTitle: 'Agent 会话历史',+ historyDescription:+ '这里只展示实验场右侧 Agent 使用过的会话;新建会话会开启一个空白 Agent 上下文。',+ loadingSessions: '正在加载会话...',+ noSessions: '暂无历史会话',+ createTimeout: '创建 Studio 会话超时,请检查连接设置后重试。',+ newSessionTitle: '新建 Studio 会话',+ botPrompt: {+ title: '请开启 bot 模式',+ description:+ '当前服务未启用 Agent 对话能力,请使用 bot 模式启动服务后重试。',+ retry: '重新检测',+ },+ empty: {+ heading: 'Agent 动作会和左侧目录联动',+ body: '发送问题后,tool call 输出里的 `viking://` 文件会变成可点击链接,点击即可在左侧定位并在中间打开。',+ prompts: [+ '总结当前目录',+ '递归查找相关文档',+ '解释这个资源和项目的关系',+ ],+ },+ },+ terminal: {+ welcomeTitle: 'Terminal 已连接上下文目录',+ welcomeBody:+ '可执行 /status、/ls、/search、/read、/add-resource。输出中的资源链接会定位左侧目录并打开中间预览。',+ opened: '已打开资源',+ onlineTitle: '服务在线',+ onlineBody: 'OpenViking API 正常响应,根目录下发现 {{count}} 个节点。',+ lsBody: '{{uri}} 下共展示 {{count}} 个节点。',+ fileEmpty: '文件为空,已在中间预览区打开。',+ searchUsage: '用法:{{name}} 查询词',+ readUsage: '用法:/read viking://resources/...',+ enterUri: '请输入 viking:// URI',+ hits: '命中 resources {{resources}} 条,memory {{memories}} 条,skill {{skills}} 条。',+ addResourceBody:+ '已打开添加资源弹窗。提交后左侧目录会刷新,也可以用 /ls 或 /search 继续定位新内容。',+ addResourceTitle: '添加资源',+ unknownCommand:+ '未知命令。可用命令:/status、/ls、/search、/find、/read、/add-resource。',+ commandFailed: '命令失败',+ running: '正在执行命令...',+ placeholder: '输入 CLI 命令,例如 /status',+ suggestionsTitle: '命令建议',+ suggestionsHint: '↑↓ 选择 · Tab 补全 · Enter 执行',+ groupLabels: {+ resources: '资源',+ memories: '记忆',+ skills: '技能',+ },+ commands: {+ status: {+ description: '检查 OpenViking API 和根目录',+ usage: '/status',+ },+ ls: {+ description: '列出当前目录或指定目录',+ usage: '/ls [viking://resources/...]',+ },+ search: {+ description: '在当前上下文范围内语义搜索',+ usage: '/search 查询词',+ },+ find: {+ description: '查找相关上下文资源',+ usage: '/find 查询词',+ },+ read: {+ description: '读取并打开一个资源文件',+ usage: '/read viking://resources/.../file.md',+ },+ addResource: {+ description: '打开添加资源表单',+ usage: '/add-resource',+ },+ },+ },+ },} as constexport default zhCNdiff --git a/web-studio/src/lib/sessions/api.ts b/web-studio/src/lib/sessions/api.tsindex 033cdd938..94ad6989d 100644--- a/web-studio/src/lib/sessions/api.ts+++ b/web-studio/src/lib/sessions/api.ts@@ -8,7 +8,12 @@ import {postSessionIdCommit,postSessionIdMessages,} from '#/gen/ov-client/sdk.gen'-import { getOvResult, normalizeOvClientError, ovClient } from '#/lib/ov-client'+import {+ getOvResult,+ normalizeOvClientError,+ OvClientError,+ ovClient,+} from '#/lib/ov-client'import type { BotChatRequest, BotChatResponse } from '@ov-server/bot/v1/chat'import type { Message, MessagePart } from './types/message'@@ -117,6 +122,27 @@ export async function commitSession(// Bot Chat// ---------------------------------------------------------------------------+function extractErrorMessage(text: string, fallback: string): string {+ if (!text.trim()) return fallback++ try {+ const parsed = JSON.parse(text) as unknown+ if (parsed && typeof parsed === 'object') {+ const record = parsed as Record<string, unknown>+ if (typeof record.detail === 'string') return record.detail+ const error = record.error+ if (error && typeof error === 'object') {+ const message = (error as Record<string, unknown>).message+ if (typeof message === 'string') return message+ }+ }+ } catch {+ // Fall through to raw text.+ }++ return text+}+function buildFetchHeaders(): Record<string, string> {const conn = ovClient.getConnection()const headers: Record<string, string> = { 'Content-Type': 'application/json' }@@ -127,6 +153,29 @@ function buildFetchHeaders(): Record<string, string> {return headers}+export async function fetchBotHealth(): Promise<unknown> {+ const baseUrl = ovClient.getOptions().baseUrl+ const response = await fetch(`${baseUrl}/bot/v1/health`, {+ method: 'GET',+ headers: buildFetchHeaders(),+ })++ if (!response.ok) {+ const text = await response.text().catch(() => '')+ throw new OvClientError({+ code: response.status === 503 ? 'BOT_MODE_DISABLED' : 'BOT_HEALTH_FAILED',+ message: extractErrorMessage(+ text,+ `Bot health check failed (${response.status})`,+ ),+ responseBody: text,+ statusCode: response.status,+ })+ }++ return response.json().catch(() => ({ status: 'ok' }))+}+/*** Send a streaming chat request. Returns the raw Response for SSE parsing.* Use parseSseStream() from ./sse.ts to iterate over events.diff --git a/web-studio/src/lib/sessions/use-chat.ts b/web-studio/src/lib/sessions/use-chat.tsindex 2d58939ea..7a0317ea0 100644--- a/web-studio/src/lib/sessions/use-chat.ts+++ b/web-studio/src/lib/sessions/use-chat.ts@@ -17,6 +17,10 @@ function createUserMessage(content: string): Message {}}+type SendOptions = {+ displayMessage?: string+}+function buildAssistantMessage(content: string,toolCalls: StreamToolCall[],@@ -71,7 +75,7 @@ export interface UseChatReturn {streamingToolCalls: StreamToolCall[]streamingReasoning: stringiteration: number- send: (message: string) => Promise<void>+ send: (message: string, options?: SendOptions) => Promise<void>abort: () => voidreset: () => voidsetMessages: React.Dispatch<React.SetStateAction<Message[]>>@@ -92,12 +96,16 @@ export function useChat(options: UseChatOptions): UseChatReturn {const abortRef = useRef<AbortController | null>(null)const messagesRef = useRef<Message[]>(messages)+ const lastSyncedInitialMessagesRef = useRef<Message[] | undefined>(undefined)+ const pendingInitialMessagesRef = useRef<Message[] | undefined>(undefined)messagesRef.current = messages// Reset state when sessionId changesuseEffect(() => {abortRef.current?.abort()abortRef.current = null+ lastSyncedInitialMessagesRef.current = undefined+ pendingInitialMessagesRef.current = undefinedsetMessages([])setStatus('idle')setError(undefined)@@ -107,16 +115,25 @@ export function useChat(options: UseChatOptions): UseChatReturn {setIteration(0)}, [sessionId])- // Sync initialMessages into state when they load (e.g. history fetched)+ // Sync initialMessages into state when they load or when switching sessions.useEffect(() => {- if (- initialMessages &&- initialMessages.length > 0 &&- status !== 'streaming'- ) {- setMessages(initialMessages)+ if (!initialMessages) return++ if (status === 'streaming') {+ pendingInitialMessagesRef.current = initialMessages+ return}- }, [initialMessages])++ const nextInitialMessages =+ pendingInitialMessagesRef.current ?? initialMessages+ // Consume the deferred snapshot on every non-streaming run so it can never+ // permanently shadow later initialMessages updates.+ pendingInitialMessagesRef.current = undefined+ if (lastSyncedInitialMessagesRef.current === nextInitialMessages) return++ lastSyncedInitialMessagesRef.current = nextInitialMessages+ setMessages(nextInitialMessages)+ }, [initialMessages, sessionId, status])const abort = useCallback(() => {abortRef.current?.abort()@@ -135,12 +152,13 @@ export function useChat(options: UseChatOptions): UseChatReturn {}, [abort, initialMessages])const send = useCallback(- async (message: string) => {+ async (message: string, options?: SendOptions) => {if (status === 'streaming') returnconst isFirstExchange = messagesRef.current.length === 0+ const displayMessage = options?.displayMessage ?? message- const userMsg = createUserMessage(message)+ const userMsg = createUserMessage(displayMessage)setMessages((prev) => [...prev, userMsg])setStatus('streaming')setError(undefined)@@ -237,7 +255,7 @@ export function useChat(options: UseChatOptions): UseChatReturn {if (persistMessages) {try {// Sequential: user message must precede assistant message- await addMessage(sessionId, 'user', message)+ await addMessage(sessionId, 'user', displayMessage)await addMessage(sessionId,'assistant',@@ -252,9 +270,9 @@ export function useChat(options: UseChatOptions): UseChatReturn {// Generate session title on first exchangeif (sessionId && isFirstExchange) {// Immediate: use first user message as temp title- setSessionTitle(sessionId, message.slice(0, 20))+ setSessionTitle(sessionId, displayMessage.slice(0, 20))// Async: ask AI for a better title- generateTitle(message, accContent)+ generateTitle(displayMessage, accContent).then((title) => {if (title) setSessionTitle(sessionId, title)})diff --git a/web-studio/src/lib/sessions/use-sessions.ts b/web-studio/src/lib/sessions/use-sessions.tsindex 8d8ac7774..63ad2b36c 100644--- a/web-studio/src/lib/sessions/use-sessions.ts+++ b/web-studio/src/lib/sessions/use-sessions.ts@@ -3,6 +3,7 @@ import { useMutation, useQuery, useQueryClient } from '@tanstack/react-query'import {createSession,deleteSession,+ fetchBotHealth,fetchSession,fetchSessionMessages,fetchSessions,@@ -10,6 +11,16 @@ import {import type { Message } from './types/message'const SESSIONS_KEY = ['sessions'] as const+const BOT_HEALTH_KEY = ['bot', 'health'] as const++export function useBotHealth() {+ return useQuery({+ queryKey: BOT_HEALTH_KEY,+ queryFn: fetchBotHealth,+ retry: false,+ staleTime: 15_000,+ })+}export function useSessionList() {return useQuery({diff --git a/web-studio/src/lib/viking-uri.ts b/web-studio/src/lib/viking-uri.tsindex c42224e30..084d0753f 100644--- a/web-studio/src/lib/viking-uri.ts+++ b/web-studio/src/lib/viking-uri.ts@@ -53,3 +53,19 @@ export function joinUri(baseUri: string, child: string): string {const normalizedBase = normalizeDirUri(baseUri)return `${normalizedBase}${raw.replace(/^\//, '')}`}++/**+ * Matches `viking://` URIs inside arbitrary text. Stops at whitespace, quotes,+ * brackets and the punctuation that commonly trails a URI in prose. Shared so+ * the sessions view and the studio playground extract URIs identically.+ */+export const VIKING_URI_RE = /viking:\/\/[^\s,,。;;'"`<>()\]}\\]+/g++/**+ * Extract the first `viking://` URI from a string (or accept an already-clean+ * URI) and strip trailing punctuation that bleeds in from surrounding prose.+ */+export function cleanVikingUri(value: string): string {+ const match = value.match(VIKING_URI_RE)+ return (match?.[0] ?? value).trim().replace(/[\\,。;;,.]+$/u, '')+}diff --git a/web-studio/src/routeTree.gen.ts b/web-studio/src/routeTree.gen.tsindex 0673bb9a9..e195a2941 100644--- a/web-studio/src/routeTree.gen.ts+++ b/web-studio/src/routeTree.gen.ts@@ -9,6 +9,7 @@// Additionally, you should also exclude this file from your linter and/or formatter to prevent it from being checked or modified.import { Route as rootRouteImport } from './routes/__root'+import { Route as StudioRouteRouteImport } from './routes/studio/route'import { Route as SettingsRouteRouteImport } from './routes/settings/route'import { Route as SessionsRouteRouteImport } from './routes/sessions/route'import { Route as RetrievalRouteRouteImport } from './routes/retrieval/route'@@ -22,6 +23,11 @@ import { Route as OauthVerifyRouteImport } from './routes/oauth/verify'import { Route as OauthSetupRouteImport } from './routes/oauth/setup'import { Route as OauthConsentRouteImport } from './routes/oauth/consent'+const StudioRouteRoute = StudioRouteRouteImport.update({+ id: '/studio',+ path: '/studio',+ getParentRoute: () => rootRouteImport,+} as any)const SettingsRouteRoute = SettingsRouteRouteImport.update({id: '/settings',path: '/settings',@@ -91,6 +97,7 @@ export interface FileRoutesByFullPath {'/retrieval': typeof RetrievalRouteRoute'/sessions': typeof SessionsRouteRouteWithChildren'/settings': typeof SettingsRouteRoute+ '/studio': typeof StudioRouteRoute'/oauth/consent': typeof OauthConsentRoute'/oauth/setup': typeof OauthSetupRoute'/oauth/verify': typeof OauthVerifyRoute@@ -103,6 +110,7 @@ export interface FileRoutesByTo {'/request-logs': typeof RequestLogsRouteRoute'/retrieval': typeof RetrievalRouteRoute'/settings': typeof SettingsRouteRoute+ '/studio': typeof StudioRouteRoute'/oauth/consent': typeof OauthConsentRoute'/oauth/setup': typeof OauthSetupRoute'/oauth/verify': typeof OauthVerifyRoute@@ -118,6 +126,7 @@ export interface FileRoutesById {'/retrieval': typeof RetrievalRouteRoute'/sessions': typeof SessionsRouteRouteWithChildren'/settings': typeof SettingsRouteRoute+ '/studio': typeof StudioRouteRoute'/oauth/consent': typeof OauthConsentRoute'/oauth/setup': typeof OauthSetupRoute'/oauth/verify': typeof OauthVerifyRoute@@ -134,6 +143,7 @@ export interface FileRouteTypes {| '/retrieval'| '/sessions'| '/settings'+ | '/studio'| '/oauth/consent'| '/oauth/setup'| '/oauth/verify'@@ -146,6 +156,7 @@ export interface FileRouteTypes {| '/request-logs'| '/retrieval'| '/settings'+ | '/studio'| '/oauth/consent'| '/oauth/setup'| '/oauth/verify'@@ -160,6 +171,7 @@ export interface FileRouteTypes {| '/retrieval'| '/sessions'| '/settings'+ | '/studio'| '/oauth/consent'| '/oauth/setup'| '/oauth/verify'@@ -175,6 +187,7 @@ export interface RootRouteChildren {RetrievalRouteRoute: typeof RetrievalRouteRouteSessionsRouteRoute: typeof SessionsRouteRouteWithChildrenSettingsRouteRoute: typeof SettingsRouteRoute+ StudioRouteRoute: typeof StudioRouteRouteOauthConsentRoute: typeof OauthConsentRouteOauthSetupRoute: typeof OauthSetupRouteOauthVerifyRoute: typeof OauthVerifyRoute@@ -182,6 +195,13 @@ export interface RootRouteChildren {declare module '@tanstack/react-router' {interface FileRoutesByPath {+ '/studio': {+ id: '/studio'+ path: '/studio'+ fullPath: '/studio'+ preLoaderRoute: typeof StudioRouteRouteImport+ parentRoute: typeof rootRouteImport+ }'/settings': {id: '/settings'path: '/settings'@@ -301,6 +321,7 @@ const rootRouteChildren: RootRouteChildren = {RetrievalRouteRoute: RetrievalRouteRoute,SessionsRouteRoute: SessionsRouteRouteWithChildren,SettingsRouteRoute: SettingsRouteRoute,+ StudioRouteRoute: StudioRouteRoute,OauthConsentRoute: OauthConsentRoute,OauthSetupRoute: OauthSetupRoute,OauthVerifyRoute: OauthVerifyRoute,diff --git a/web-studio/src/routes/resources/-lib/api.ts b/web-studio/src/routes/resources/-lib/api.tsindex bc8550116..a4937ca34 100644--- a/web-studio/src/routes/resources/-lib/api.ts+++ b/web-studio/src/routes/resources/-lib/api.ts@@ -158,7 +158,10 @@ export async function fetchDirectoryLevelContent(}}-export async function fetchFsStat(uri: string): Promise<VikingFsEntry> {+export async function fetchFsStat(+ uri: string,+ options: { throwOnError?: boolean } = {},+): Promise<VikingFsEntry> {try {const result = await getOvResult<FSStatResult>(getFsStat({ query: { uri } }),@@ -181,7 +184,10 @@ export async function fetchFsStat(uri: string): Promise<VikingFsEntry> {abstract: String(data.abstract ?? ''),overview: String(data.overview ?? ''),}- } catch {+ } catch (error) {+ // Callers that need to surface read failures (e.g. clicking a missing or+ // unauthorized URI) opt in; the default keeps the lenient synthetic entry.+ if (options.throwOnError) throw toVikingApiError(error)return {uri,name: fileNameFromUri(uri),diff --git a/web-studio/src/routes/sessions/-components/composer.tsx b/web-studio/src/routes/sessions/-components/composer.tsxindex 82638af0e..899e28dd6 100644--- a/web-studio/src/routes/sessions/-components/composer.tsx+++ b/web-studio/src/routes/sessions/-components/composer.tsx@@ -7,11 +7,18 @@ interface ComposerProps {onSend: (message: string) => voidonCancel: () => voidisStreaming: boolean+ variant?: 'default' | 'compact'}-export function Composer({ onSend, onCancel, isStreaming }: ComposerProps) {+export function Composer({+ onSend,+ onCancel,+ isStreaming,+ variant = 'default',+}: ComposerProps) {const [value, setValue] = useState('')const textareaRef = useRef<HTMLTextAreaElement>(null)+ const isCompact = variant === 'compact'const resize = useCallback(() => {const el = textareaRef.current@@ -45,10 +52,11 @@ export function Composer({ onSend, onCancel, isStreaming }: ComposerProps) {)return (- <div className="px-4 pb-4 pt-2">+ <div className={cn(isCompact ? 'px-3 pb-3 pt-2' : 'px-4 pb-4 pt-2')}><divclassName={cn(- 'mx-auto w-full max-w-3xl rounded-2xl border border-border/50 bg-background/95',+ 'mx-auto w-full max-w-3xl border border-border/50 bg-background/95',+ isCompact ? 'rounded-xl' : 'rounded-2xl','shadow-lg shadow-black/8 dark:shadow-black/25',)}>@@ -65,12 +73,20 @@ export function Composer({ onSend, onCancel, isStreaming }: ComposerProps) {}}onKeyDown={handleKeyDown}className={cn(- 'min-h-[44px] w-full resize-none bg-transparent px-4 pt-3 pb-1 text-sm',+ 'w-full resize-none bg-transparent text-sm',+ isCompact+ ? 'min-h-[38px] px-3 pb-0.5 pt-2.5'+ : 'min-h-[44px] px-4 pb-1 pt-3','placeholder:text-muted-foreground/60','focus-visible:outline-none',)}/>- <div className="flex items-center justify-end px-3 pb-2.5">+ <div+ className={cn(+ 'flex items-center justify-end',+ isCompact ? 'px-2.5 pb-2' : 'px-3 pb-2.5',+ )}+ >{isStreaming ? (<buttontype="button"diff --git a/web-studio/src/routes/sessions/-components/message-list.tsx b/web-studio/src/routes/sessions/-components/message-list.tsxindex e71a17766..295fb9ee9 100644--- a/web-studio/src/routes/sessions/-components/message-list.tsx+++ b/web-studio/src/routes/sessions/-components/message-list.tsx@@ -47,6 +47,15 @@ function getTextFromParts(message: Message): string {.join('\n')}+function stripStudioContextSuffix(text: string): string {+ return text+ .replace(/\n\n当前选中的上下文资源:\s*viking:\/\/[\s\S]*$/u, '')+ .replace(+ /\n\n当前用户在 Studio 中选中的上下文资源是:\s*viking:\/\/[\s\S]*$/u,+ '',+ )+}+/** Format relative time */function formatRelativeTime(iso: string): string {const now = Date.now()@@ -99,9 +108,14 @@ interface MessageListProps {reasoning: stringiteration: number}+ onResourceClick?: (uri: string) => void}-export function MessageList({ messages, streaming }: MessageListProps) {+export function MessageList({+ messages,+ onResourceClick,+ streaming,+}: MessageListProps) {return (<>{messages.map((msg, idx) => {@@ -110,10 +124,20 @@ export function MessageList({ messages, streaming }: MessageListProps) {return msg.role === 'user' ? (<UserMessage key={msg.id} message={msg} compact={sameRole} />) : (- <AssistantMessage key={msg.id} message={msg} compact={sameRole} />+ <AssistantMessage+ key={msg.id}+ message={msg}+ compact={sameRole}+ onResourceClick={onResourceClick}+ />)})}- {streaming && <StreamingAssistantMessage {...streaming} />}+ {streaming && (+ <StreamingAssistantMessage+ {...streaming}+ onResourceClick={onResourceClick}+ />+ )}</>)}@@ -129,7 +153,7 @@ const UserMessage = memo(function UserMessage({message: Messagecompact?: boolean}) {- const text = getTextFromParts(message)+ const text = stripStudioContextSuffix(getTextFromParts(message))return (<div@@ -143,14 +167,14 @@ const UserMessage = memo(function UserMessage({</div><div className="max-w-[75%] space-y-1.5">{text && (- <div className="rounded-2xl rounded-tr-sm bg-primary px-4 py-2.5 text-sm text-primary-foreground whitespace-pre-wrap shadow-sm">+ <div className="whitespace-pre-wrap rounded-2xl rounded-tr-sm border border-border/70 bg-muted/70 px-4 py-2.5 text-sm leading-6 text-foreground shadow-sm">{text}</div>)}</div>{!compact && (- <div className="flex size-7 shrink-0 items-center justify-center rounded-full bg-primary/10">- <UserIcon className="size-3.5 text-primary" />+ <div className="flex size-7 shrink-0 items-center justify-center rounded-full border border-border/70 bg-muted/60">+ <UserIcon className="size-3.5 text-muted-foreground" /></div>)}{compact && <div className="w-7 shrink-0" />}@@ -165,9 +189,11 @@ const UserMessage = memo(function UserMessage({const AssistantMessage = memo(function AssistantMessage({message,compact,+ onResourceClick,}: {message: Messagecompact?: boolean+ onResourceClick?: (uri: string) => void}) {const textContent = getTextFromParts(message)@@ -190,6 +216,7 @@ const AssistantMessage = memo(function AssistantMessage({result={part.tool_output}isError={part.tool_status === 'error'}isRunning={false}+ onResourceClick={onResourceClick}/>)case 'context':@@ -216,11 +243,13 @@ function StreamingAssistantMessage({toolCalls,reasoning,iteration,+ onResourceClick,}: {content: stringtoolCalls: StreamToolCall[]reasoning: stringiteration: number+ onResourceClick?: (uri: string) => void}) {const { t } = useTranslation('sessions')const hasContent = content || toolCalls.length > 0 || reasoning@@ -253,6 +282,7 @@ function StreamingAssistantMessage({args={args}result={tc.result}isRunning={!tc.result}+ onResourceClick={onResourceClick}/>)})}diff --git a/web-studio/src/routes/sessions/-components/message-parts.tsx b/web-studio/src/routes/sessions/-components/message-parts.tsxindex 86b5619e8..e583b9e04 100644--- a/web-studio/src/routes/sessions/-components/message-parts.tsx+++ b/web-studio/src/routes/sessions/-components/message-parts.tsx@@ -5,11 +5,13 @@ import { useTranslation } from 'react-i18next'import {CheckCircle2Icon,CircleAlertIcon,+ FileTextIcon,LoaderIcon,WrenchIcon,} from 'lucide-react'import { cn } from '#/lib/utils'+import { cleanVikingUri, VIKING_URI_RE } from '#/lib/viking-uri'const plugins = { code, cjk }@@ -104,6 +106,7 @@ interface ToolCallBlockProps {result?: stringisError?: booleanisRunning: boolean+ onResourceClick?: (uri: string) => void}export function ToolCallBlock({@@ -112,8 +115,10 @@ export function ToolCallBlock({result,isError,isRunning,+ onResourceClick,}: ToolCallBlockProps) {const { t } = useTranslation('sessions')+ const refs = extractVikingUris(result)return (<details className="my-2 rounded-lg border border-border/30 bg-muted/20">@@ -155,6 +160,23 @@ export function ToolCallBlock({>{result}</pre>+ {refs.length > 0 && onResourceClick ? (+ <div className="mt-2 grid gap-1.5">+ {refs.map((uri) => (+ <button+ key={uri}+ type="button"+ className="flex min-w-0 items-center gap-2 rounded-md border bg-background px-2 py-1.5 text-left transition-colors hover:border-primary/50 hover:bg-primary/5"+ onClick={() => onResourceClick(uri)}+ >+ <FileTextIcon className="size-3.5 shrink-0 text-muted-foreground" />+ <span className="min-w-0 flex-1 truncate font-mono text-[11px] text-primary">+ {uri}+ </span>+ </button>+ ))}+ </div>+ ) : null}</div>)}</div>@@ -174,3 +196,55 @@ function ToolStatusIcon({if (isError) return <CircleAlertIcon className="size-3 text-destructive" />return <CheckCircle2Icon className="size-3 text-primary/70" />}++function extractVikingUris(text: string | undefined): string[] {+ if (!text) return []+ const seen = new Set<string>()++ const parsed = parseJsonResult(text)+ if (parsed !== undefined) {+ collectStructuredUris(parsed, seen)+ }++ // Always scan the raw text too: URIs embedded in free-text fields or under+ // keys other than `uri` are invisible to the structured pass. The Set keeps+ // the two passes deduped.+ const matches = text.match(VIKING_URI_RE) ?? []+ for (const match of matches) {+ const uri = cleanVikingUri(match)+ if (uri) seen.add(uri)+ }+ return [...seen]+}++function parseJsonResult(text: string): unknown {+ const trimmed = text.trim()+ if (!trimmed) return undefined++ try {+ return JSON.parse(trimmed) as unknown+ } catch {+ return undefined+ }+}++function collectStructuredUris(value: unknown, seen: Set<string>): void {+ if (Array.isArray(value)) {+ for (const item of value) collectStructuredUris(item, seen)+ return+ }++ if (!value || typeof value !== 'object') return++ for (const [key, nested] of Object.entries(value)) {+ if (key === 'uri' && typeof nested === 'string') {+ const uri = cleanVikingUri(nested)+ if (uri) seen.add(uri)+ continue+ }++ if (Array.isArray(nested) || (nested && typeof nested === 'object')) {+ collectStructuredUris(nested, seen)+ }+ }+}diff --git a/web-studio/src/routes/studio/-components/agent-panel.tsx b/web-studio/src/routes/studio/-components/agent-panel.tsxnew file mode 100644index 000000000..4973f4215--- /dev/null+++ b/web-studio/src/routes/studio/-components/agent-panel.tsx@@ -0,0 +1,448 @@+import { useCallback, useEffect, useMemo, useRef, useState } from 'react'+import { useTranslation } from 'react-i18next'+import {+ BotIcon,+ CheckCircle2Icon,+ CircleAlertIcon,+ HistoryIcon,+ Loader2Icon,+ SparklesIcon,+ SquarePenIcon,+} from 'lucide-react'++import { Button } from '#/components/ui/button'+import {+ Dialog,+ DialogContent,+ DialogDescription,+ DialogHeader,+ DialogTitle,+} from '#/components/ui/dialog'+import { cn } from '#/lib/utils'+import { useChat } from '#/lib/sessions/use-chat'+import {+ useBotHealth,+ useCreateSession,+ useSessionList,+ useSessionMessages,+} from '#/lib/sessions/use-sessions'+import {+ setSessionTitle,+ useSessionTitles,+} from '#/lib/sessions/use-session-titles'+import { Composer } from '#/routes/sessions/-components/composer'+import { MessageList } from '#/routes/sessions/-components/message-list'++import type { ResourceOpenHandler } from '../-lib/types'+import {+ getErrorMessage,+ readStudioAgentSessionIds,+ registerStudioAgentSessionId,+ withTimeout,+} from '../-lib/utils'++export function AgentPanel({+ initialSessionId,+ onOpenResource,+ onSessionChange,+}: {+ initialSessionId?: string+ onOpenResource: ResourceOpenHandler+ onSessionChange: (sessionId: string) => void+}) {+ const { t } = useTranslation('studio')+ const [sessionId, setSessionId] = useState(initialSessionId ?? '')+ const [historyOpen, setHistoryOpen] = useState(false)+ const [sessionError, setSessionError] = useState<string | null>(null)+ const [isCreatingSession, setIsCreatingSession] = useState(false)+ const creationStartedRef = useRef(false)+ const botHealth = useBotHealth()+ const createSession = useCreateSession()+ const { data: sessions, isLoading: isLoadingSessions } = useSessionList()+ const { getTitle } = useSessionTitles()+ const [studioSessionIds, setStudioSessionIds] = useState<string[]>(() =>+ readStudioAgentSessionIds(),+ )+ const { data: historyMessages } = useSessionMessages(sessionId || undefined)+ const chat = useChat({+ initialMessages: historyMessages,+ persistMessages: Boolean(sessionId),+ sessionId: sessionId || 'studio-preview',+ })+ const scrollRef = useRef<HTMLDivElement>(null)+ const bottomRef = useRef<HTMLDivElement>(null)++ const startSession = useCallback(async () => {+ if (sessionId || creationStartedRef.current) return++ creationStartedRef.current = true+ setIsCreatingSession(true)+ setSessionError(null)++ try {+ const result = await withTimeout(+ createSession.mutateAsync(undefined),+ 12_000,+ t('agent.createTimeout'),+ )+ setStudioSessionIds(registerStudioAgentSessionId(result.session_id))+ setSessionId(result.session_id)+ onSessionChange(result.session_id)+ } catch (error) {+ creationStartedRef.current = false+ setSessionError(error instanceof Error ? error.message : String(error))+ } finally {+ setIsCreatingSession(false)+ }+ }, [createSession, onSessionChange, sessionId, t])++ const handleNewSession = useCallback(async () => {+ if (isCreatingSession) return++ chat.abort()+ chat.setMessages([])+ creationStartedRef.current = true+ setIsCreatingSession(true)+ setSessionError(null)++ try {+ const result = await withTimeout(+ createSession.mutateAsync(undefined),+ 12_000,+ t('agent.createTimeout'),+ )+ setStudioSessionIds(registerStudioAgentSessionId(result.session_id))+ setSessionTitle(result.session_id, t('agent.newSessionTitle'))+ setSessionId(result.session_id)+ onSessionChange(result.session_id)+ setHistoryOpen(false)+ } catch (error) {+ creationStartedRef.current = false+ setSessionError(error instanceof Error ? error.message : String(error))+ } finally {+ setIsCreatingSession(false)+ }+ }, [chat, createSession, isCreatingSession, onSessionChange, t])++ const handleSwitchSession = useCallback(+ (nextSessionId: string) => {+ chat.abort()+ creationStartedRef.current = true+ setSessionError(null)+ setIsCreatingSession(false)+ setStudioSessionIds(registerStudioAgentSessionId(nextSessionId))+ setSessionId(nextSessionId)+ onSessionChange(nextSessionId)+ setHistoryOpen(false)+ },+ [chat, onSessionChange],+ )++ useEffect(() => {+ // Only create a session once bot mode is confirmed available, otherwise we+ // leave orphan sessions behind and flash "creating" before the bot-mode+ // prompt.+ if (!sessionId && !sessionError && botHealth.isSuccess) {+ void startSession()+ }+ }, [botHealth.isSuccess, sessionError, sessionId, startSession])++ useEffect(() => {+ if (sessionId) {+ setStudioSessionIds(registerStudioAgentSessionId(sessionId))+ }+ }, [sessionId])++ useEffect(() => {+ bottomRef.current?.scrollIntoView({ behavior: 'smooth' })+ }, [+ chat.messages.length,+ chat.streamingContent,+ chat.streamingReasoning,+ chat.streamingToolCalls,+ ])++ const send = useCallback(+ (message: string) => {+ void chat.send(message)+ },+ [chat],+ )++ const isStreaming = chat.status === 'streaming'+ const botModeError = botHealth.isError ? getErrorMessage(botHealth.error) : ''+ const isCreating = !sessionId && isCreatingSession+ const reversedSessions = useMemo(() => {+ const sessionById = new Map(+ (sessions ?? []).map((session) => [session.session_id, session]),+ )++ return studioSessionIds+ .map((sessionId) => sessionById.get(sessionId))+ .filter((session): session is NonNullable<typeof session> =>+ Boolean(session),+ )+ }, [sessions, studioSessionIds])++ return (+ <>+ <div className="flex min-h-0 flex-1 flex-col">+ <div className="border-b bg-background/70 px-4 py-3">+ <div className="flex items-center gap-2 text-xs text-muted-foreground">+ <BotIcon className="size-3.5 shrink-0" />+ <span className="min-w-0 flex-1 truncate">+ {t('agent.autoRetrieve')}+ </span>+ <Button+ type="button"+ variant="ghost"+ size="icon-sm"+ className="size-7 shrink-0"+ title={t('agent.history')}+ onClick={() => setHistoryOpen(true)}+ >+ <HistoryIcon className="size-3.5" />+ </Button>+ <Button+ type="button"+ variant="ghost"+ size="icon-sm"+ className="size-7 shrink-0"+ title={t('agent.newSession')}+ disabled={isCreatingSession}+ onClick={() => void handleNewSession()}+ >+ {isCreatingSession ? (+ <Loader2Icon className="size-3.5 animate-spin" />+ ) : (+ <SquarePenIcon className="size-3.5" />+ )}+ </Button>+ </div>+ </div>++ <div+ ref={scrollRef}+ className="min-h-0 flex-1 overflow-y-auto px-4 py-4"+ >+ {isCreating ? (+ <div className="flex h-full items-center justify-center gap-2 text-sm text-muted-foreground">+ <Loader2Icon className="size-4 animate-spin" />+ {t('agent.creating')}+ </div>+ ) : botHealth.isLoading ? (+ <div className="flex h-full items-center justify-center gap-2 text-sm text-muted-foreground">+ <Loader2Icon className="size-4 animate-spin" />+ {t('agent.detectingBot')}+ </div>+ ) : botModeError ? (+ <BotModePrompt+ detail={botModeError}+ onRetry={() => void botHealth.refetch()}+ />+ ) : sessionError ? (+ <div className="grid gap-3 rounded-lg border border-destructive/25 bg-destructive/5 p-3 text-sm text-destructive">+ <div>{t('agent.createFailed', { error: sessionError })}</div>+ <Button+ type="button"+ size="sm"+ variant="outline"+ className="w-fit"+ onClick={() => {+ setSessionError(null)+ void startSession()+ }}+ >+ {t('agent.retry')}+ </Button>+ </div>+ ) : chat.messages.length === 0 && !isStreaming ? (+ <AgentEmptyState onSend={send} />+ ) : (+ <MessageList+ messages={chat.messages}+ onResourceClick={onOpenResource}+ streaming={+ isStreaming+ ? {+ content: chat.streamingContent,+ iteration: chat.iteration,+ reasoning: chat.streamingReasoning,+ toolCalls: chat.streamingToolCalls,+ }+ : undefined+ }+ />+ )}+ <div ref={bottomRef} />+ </div>++ {botModeError ? (+ <div className="border-t bg-background/80 px-4 py-3 text-center text-sm text-muted-foreground">+ {t('agent.botDisabledFooter')}+ </div>+ ) : (+ <div className="border-t bg-background/80">+ <Composer+ variant="compact"+ isStreaming={isStreaming}+ onCancel={chat.abort}+ onSend={send}+ />+ </div>+ )}+ </div>++ <Dialog open={historyOpen} onOpenChange={setHistoryOpen}>+ <DialogContent className="gap-4 sm:max-w-lg">+ <DialogHeader>+ <DialogTitle>{t('agent.historyTitle')}</DialogTitle>+ <DialogDescription>+ {t('agent.historyDescription')}+ </DialogDescription>+ </DialogHeader>+ <div className="max-h-[420px] overflow-y-auto pr-1">+ {isLoadingSessions ? (+ <div className="flex items-center gap-2 rounded-lg border bg-muted/30 p-3 text-sm text-muted-foreground">+ <Loader2Icon className="size-4 animate-spin" />+ {t('agent.loadingSessions')}+ </div>+ ) : reversedSessions.length === 0 ? (+ <div className="rounded-lg border bg-muted/30 p-3 text-sm text-muted-foreground">+ {t('agent.noSessions')}+ </div>+ ) : (+ <div className="grid gap-2">+ {reversedSessions.map((session) => {+ const active = session.session_id === sessionId+ const title = getTitle(session.session_id)++ return (+ <button+ key={session.session_id}+ type="button"+ className={cn(+ 'flex min-w-0 items-center gap-3 rounded-lg border px-3 py-2 text-left transition-colors hover:border-primary/45 hover:bg-muted/45',+ active+ ? 'border-primary/60 bg-primary/10'+ : 'border-border bg-background',+ )}+ onClick={() => handleSwitchSession(session.session_id)}+ >+ <HistoryIcon className="size-4 shrink-0 text-muted-foreground" />+ <span className="min-w-0 flex-1">+ <span className="block truncate text-sm font-medium text-foreground">+ {title}+ </span>+ <span className="block truncate font-mono text-[11px] text-muted-foreground">+ {session.session_id}+ </span>+ </span>+ {active ? (+ <CheckCircle2Icon className="size-4 shrink-0 text-primary" />+ ) : null}+ </button>+ )+ })}+ </div>+ )}+ </div>+ <Button+ type="button"+ className="w-full"+ onClick={() => void handleNewSession()}+ disabled={isCreatingSession}+ >+ {isCreatingSession ? (+ <Loader2Icon className="size-4 animate-spin" />+ ) : (+ <SquarePenIcon className="size-4" />+ )}+ {t('agent.newSession')}+ </Button>+ </DialogContent>+ </Dialog>+ </>+ )+}++export function BotModePrompt({+ detail,+ onRetry,+}: {+ detail: string+ onRetry: () => void+}) {+ const { t } = useTranslation('studio')+ return (+ <div className="flex h-full items-center justify-center">+ <div className="grid max-w-md gap-4 rounded-xl border border-primary/25 bg-primary/5 p-5 text-sm">+ <div className="flex items-start gap-3">+ <div className="flex size-9 shrink-0 items-center justify-center rounded-lg bg-primary/10 text-primary">+ <CircleAlertIcon className="size-4" />+ </div>+ <div className="min-w-0">+ <div className="text-base font-semibold text-foreground">+ {t('agent.botPrompt.title')}+ </div>+ <p className="mt-1 leading-6 text-muted-foreground">+ {t('agent.botPrompt.description')}+ </p>+ </div>+ </div>+ <code className="rounded-lg border bg-background px-3 py-2 font-mono text-xs text-foreground">+ openviking-server --with-bot+ </code>+ {detail ? (+ <div className="rounded-lg bg-muted/50 px-3 py-2 text-xs leading-5 text-muted-foreground">+ {detail}+ </div>+ ) : null}+ <Button+ type="button"+ variant="outline"+ className="w-fit"+ onClick={onRetry}+ >+ {t('agent.botPrompt.retry')}+ </Button>+ </div>+ </div>+ )+}++export function AgentEmptyState({+ onSend,+}: {+ onSend: (message: string) => void+}) {+ const { t } = useTranslation('studio')+ const prompts = t('agent.empty.prompts', {+ returnObjects: true,+ }) as string[]+ return (+ <div className="flex h-full flex-col justify-end gap-4 pb-4">+ <div className="rounded-xl border bg-background p-4">+ <div className="mb-2 flex items-center gap-2 text-sm font-semibold">+ <SparklesIcon className="size-4 text-primary" />+ {t('agent.empty.heading')}+ </div>+ <p className="text-sm leading-6 text-muted-foreground">+ {t('agent.empty.body')}+ </p>+ </div>+ <div className="flex flex-wrap gap-2">+ {prompts.map((prompt) => (+ <button+ key={prompt}+ type="button"+ className="rounded-lg border bg-background px-3 py-2 text-xs text-muted-foreground transition-colors hover:border-primary/40 hover:text-foreground"+ onClick={() => onSend(prompt)}+ >+ {prompt}+ </button>+ ))}+ </div>+ </div>+ )+}diff --git a/web-studio/src/routes/studio/-components/context-explorer.tsx b/web-studio/src/routes/studio/-components/context-explorer.tsxnew file mode 100644index 000000000..da7b31f02--- /dev/null+++ b/web-studio/src/routes/studio/-components/context-explorer.tsx@@ -0,0 +1,403 @@+import { useCallback, useEffect, useMemo, useRef } from 'react'+import type { PointerEvent as ReactPointerEvent } from 'react'+import { useTranslation } from 'react-i18next'+import {+ BotIcon,+ ChevronRightIcon,+ CommandIcon,+ FileTextIcon,+ FolderIcon,+ FolderTreeIcon,+ Loader2Icon,+ PlusIcon,+ RefreshCcwIcon,+} from 'lucide-react'++import { Button } from '#/components/ui/button'+import { cn } from '#/lib/utils'+import { useVikingFsList } from '#/routes/resources/-hooks/viking-fm'+import type { VikingFsEntry } from '#/routes/resources/-types/viking-fm'++import {+ createEntryFromUri,+ sortTreeEntries,+ visibleContextEntries,+} from '../-lib/utils'++const TREE_INDENT_WIDTH = 16+const TREE_ROW_PADDING = 6+const TREE_GUIDE_OFFSET = 8+const TREE_CHILD_CONTENT_OFFSET = 26++export function ContextExplorerHeader({+ isRefreshing,+ onAddResource,+ onRefresh,+}: {+ isRefreshing: boolean+ onAddResource: () => void+ onRefresh: () => void+}) {+ const { t } = useTranslation('studio')+ return (+ <div className="border-b px-3 py-3">+ <div className="flex items-center gap-2">+ <div className="flex size-8 items-center justify-center rounded-lg bg-primary/10 text-primary">+ <FolderTreeIcon className="size-4" />+ </div>+ <div className="min-w-0 flex-1">+ <div className="text-sm font-semibold">{t('explorer.title')}</div>+ </div>+ <Button+ type="button"+ size="icon-sm"+ variant="ghost"+ title={t('explorer.addResource')}+ onClick={onAddResource}+ >+ <PlusIcon className="size-4" />+ </Button>+ <Button+ type="button"+ size="icon-sm"+ variant="ghost"+ title={t('explorer.refresh')}+ onClick={onRefresh}+ >+ <RefreshCcwIcon+ className={cn('size-4', isRefreshing && 'animate-spin')}+ />+ </Button>+ </div>+ </div>+ )+}++const NAMESPACES: Array<{+ descriptionKey: 'agent' | 'resources' | 'session' | 'user'+ icon: typeof FolderIcon+ label: string+ uri: string+}> = [+ {+ descriptionKey: 'user',+ icon: FolderIcon,+ label: 'User',+ uri: 'viking://user/',+ },+ {+ descriptionKey: 'session',+ icon: CommandIcon,+ label: 'Session',+ uri: 'viking://session/',+ },+ {+ descriptionKey: 'agent',+ icon: BotIcon,+ label: 'Agent',+ uri: 'viking://agent/',+ },+ {+ descriptionKey: 'resources',+ icon: FolderTreeIcon,+ label: 'Resources',+ uri: 'viking://resources/',+ },+]++export function ContextTree({+ currentUri,+ expandedKeys,+ onExpandedKeysChange,+ onSelectDirectory,+ onSelectFile,+ selectedFileUri,+}: {+ currentUri: string+ expandedKeys: Set<string>+ onExpandedKeysChange: (next: Set<string>) => void+ onSelectDirectory: (entry: VikingFsEntry) => void+ onSelectFile: (entry: VikingFsEntry) => void+ selectedFileUri?: string | null+}) {+ const { t } = useTranslation('studio')+ return (+ <div className="h-full overflow-auto px-2 py-2 font-mono">+ {NAMESPACES.map((item) => {+ const entry = createEntryFromUri(item.uri, true)+ return (+ <ContextTreeNode+ key={item.uri}+ currentUri={currentUri}+ entry={{+ ...entry,+ name: item.label,+ abstract: t(`explorer.namespaces.${item.descriptionKey}`),+ }}+ expandedKeys={expandedKeys}+ level={0}+ onExpandedKeysChange={onExpandedKeysChange}+ onSelectDirectory={onSelectDirectory}+ onSelectFile={onSelectFile}+ selectedFileUri={selectedFileUri}+ />+ )+ })}+ </div>+ )+}++export function StudioResizeHandle({+ active,+ label,+ onPointerDown,+}: {+ active: boolean+ label: string+ onPointerDown: (event: ReactPointerEvent<HTMLDivElement>) => void+}) {+ return (+ <div+ role="separator"+ aria-label={label}+ aria-orientation="vertical"+ data-active={active}+ className="group hidden w-2 shrink-0 cursor-col-resize touch-none items-center justify-center border-x border-transparent transition-colors hover:bg-primary/10 active:bg-primary/15 data-[active=true]:bg-primary/15 lg:flex"+ onPointerDown={onPointerDown}+ >+ <span className="h-full w-px bg-border transition-colors group-hover:bg-primary/60 group-data-[active=true]:bg-primary" />+ </div>+ )+}++export function ContextTreeNode({+ currentUri,+ entry,+ expandedKeys,+ level,+ onExpandedKeysChange,+ onSelectDirectory,+ onSelectFile,+ selectedFileUri,+}: {+ currentUri: string+ entry: VikingFsEntry+ expandedKeys: Set<string>+ level: number+ onExpandedKeysChange: (next: Set<string>) => void+ onSelectDirectory: (entry: VikingFsEntry) => void+ onSelectFile: (entry: VikingFsEntry) => void+ selectedFileUri?: string | null+}) {+ const isOpen = expandedKeys.has(entry.uri)+ const isFileSelected = !entry.isDir && selectedFileUri === entry.uri+ const isDirSelected =+ entry.isDir && currentUri === entry.uri && !selectedFileUri+ const isSelected = isDirSelected || isFileSelected+ const namespaceHint = level === 0 ? entry.abstract : ''+ const rowRef = useRef<HTMLDivElement>(null)+ const shouldLoadChildren = entry.isDir && isOpen+ const listQuery = useVikingFsList(+ entry.uri,+ {+ output: 'agent',+ showAllHidden: true,+ nodeLimit: 200,+ },+ shouldLoadChildren,+ )+ const children = useMemo(+ () => sortTreeEntries(visibleContextEntries(listQuery.data?.entries ?? [])),+ [listQuery.data?.entries],+ )++ useEffect(() => {+ if (!isSelected) return++ window.requestAnimationFrame(() => {+ rowRef.current?.scrollIntoView({+ block: 'center',+ inline: 'nearest',+ })+ })+ }, [entry.uri, isSelected])++ const toggle = useCallback(() => {+ if (!entry.isDir) return+ const next = new Set(expandedKeys)+ if (isOpen) next.delete(entry.uri)+ else next.add(entry.uri)+ onExpandedKeysChange(next)+ }, [entry.isDir, entry.uri, expandedKeys, isOpen, onExpandedKeysChange])++ const select = useCallback(() => {+ if (entry.isDir) {+ onSelectDirectory(entry)+ toggle()+ } else {+ onSelectFile(entry)+ }+ }, [entry, onSelectDirectory, onSelectFile, toggle])++ return (+ <div className="relative min-w-0">+ <TreeIndentGuides level={level} />+ <div+ ref={rowRef}+ className={cn(+ 'group relative z-10 flex h-7 cursor-pointer select-none items-center gap-1.5 rounded-md px-1.5 text-xs transition-colors',+ isSelected+ ? 'bg-muted text-foreground'+ : 'text-muted-foreground hover:bg-muted/55 hover:text-foreground',+ )}+ style={{ paddingLeft: treeRowPadding(level) }}+ onClick={select}+ >+ {entry.isDir ? (+ <button+ type="button"+ className="inline-flex size-4 shrink-0 items-center justify-center rounded-sm text-muted-foreground transition-colors group-hover:text-foreground"+ onClick={(event) => {+ event.stopPropagation()+ toggle()+ }}+ >+ <ChevronRightIcon+ className={cn(+ 'size-3 transition-transform',+ isOpen && 'rotate-90',+ )}+ />+ </button>+ ) : (+ <span className="size-4 shrink-0" />+ )}+ {entry.isDir ? (+ <FolderIcon+ className={cn(+ 'size-4 shrink-0',+ isOpen ? 'text-primary/80' : 'text-muted-foreground',+ )}+ />+ ) : (+ <FileTextIcon className="size-4 shrink-0 text-muted-foreground" />+ )}+ <span+ className={cn(+ 'truncate',+ namespaceHint ? 'shrink-0 text-foreground' : 'min-w-0 flex-1',+ )}+ >+ {entry.name}+ </span>+ {namespaceHint ? (+ <span className="min-w-0 flex-1 truncate font-sans text-xs text-muted-foreground">+ {namespaceHint}+ </span>+ ) : null}+ {entry.name === '_abstract.md' ? (+ <span className="shrink-0 rounded bg-muted px-1 font-sans text-[10px] text-muted-foreground">+ L0+ </span>+ ) : entry.name === '_overview.md' ? (+ <span className="shrink-0 rounded bg-muted px-1 font-sans text-[10px] text-muted-foreground">+ L1+ </span>+ ) : null}+ </div>++ {entry.isDir && isOpen ? (+ <div className="relative min-w-0">+ {listQuery.isLoading ? (+ <div+ className="relative flex h-7 items-center gap-2 px-1.5 text-xs text-muted-foreground"+ style={{ paddingLeft: treeChildContentPadding(level) }}+ >+ <TreeIndentGuides level={level + 1} />+ <Loader2Icon className="size-3 animate-spin" />+ loading+ </div>+ ) : children.length > 0 ? (+ children.map((child) => (+ <ContextTreeNode+ key={child.uri}+ currentUri={currentUri}+ entry={child}+ expandedKeys={expandedKeys}+ level={level + 1}+ onExpandedKeysChange={onExpandedKeysChange}+ onSelectDirectory={onSelectDirectory}+ onSelectFile={onSelectFile}+ selectedFileUri={selectedFileUri}+ />+ ))+ ) : (+ <div+ className="relative h-7 px-1.5 text-xs leading-7 text-muted-foreground/60"+ style={{ paddingLeft: treeChildContentPadding(level) }}+ >+ <TreeIndentGuides level={level + 1} />+ empty+ </div>+ )}+ </div>+ ) : null}+ </div>+ )+}++export function TreeIndentGuides({ level }: { level: number }) {+ if (level <= 0) return null++ return (+ <div className="pointer-events-none absolute inset-y-0 left-0 right-0 z-0">+ {Array.from({ length: level }, (_, index) => (+ <span+ key={index}+ className="absolute bottom-0 top-0 w-px bg-border/70"+ style={{ left: treeGuideLeft(index) }}+ />+ ))}+ </div>+ )+}++export function treeGuideLeft(index: number): string {+ return `${TREE_ROW_PADDING + index * TREE_INDENT_WIDTH + TREE_GUIDE_OFFSET}px`+}++export function treeRowPadding(level: number): string {+ return `${level * TREE_INDENT_WIDTH + TREE_ROW_PADDING}px`+}++export function treeChildContentPadding(level: number): string {+ return `${(level + 1) * TREE_INDENT_WIDTH + TREE_CHILD_CONTENT_OFFSET}px`+}++export function PanelTab({+ active,+ icon: Icon,+ label,+ onClick,+}: {+ active: boolean+ icon: typeof FolderIcon+ label: string+ onClick: () => void+}) {+ return (+ <button+ type="button"+ className={cn(+ 'inline-flex h-8 items-center gap-1.5 rounded-md px-3 text-xs font-medium transition-colors',+ active+ ? 'bg-foreground text-background shadow-sm'+ : 'text-muted-foreground hover:bg-muted hover:text-foreground',+ )}+ onClick={onClick}+ >+ <Icon className="size-3.5" />+ {label}+ </button>+ )+}diff --git a/web-studio/src/routes/studio/-components/resource-ref-list.tsx b/web-studio/src/routes/studio/-components/resource-ref-list.tsxnew file mode 100644index 000000000..4291430fd--- /dev/null+++ b/web-studio/src/routes/studio/-components/resource-ref-list.tsx@@ -0,0 +1,47 @@+import { FileTextIcon, FolderIcon, Loader2Icon } from 'lucide-react'++import { cn } from '#/lib/utils'+import { fileNameFromUri } from '#/routes/resources/-lib/normalize'++import type { ResourceOpenHandler, ResourceRef } from '../-lib/types'++export function ResourceRefList({+ className,+ refs,+ onOpenResource,+ openingUri,+}: {+ className?: string+ refs: ResourceRef[]+ onOpenResource: ResourceOpenHandler+ openingUri?: string | null+}) {+ return (+ <div className={cn('grid gap-1.5', className)}>+ {refs.map((ref) => (+ <button+ key={`${ref.uri}-${ref.meta ?? ''}`}+ type="button"+ className="flex min-w-0 items-center gap-2 rounded-md border bg-background px-2 py-1.5 text-left transition-colors hover:border-primary/50 hover:bg-primary/5"+ onClick={() => void onOpenResource(ref.uri)}+ >+ {openingUri === ref.uri ? (+ <Loader2Icon className="size-3.5 shrink-0 animate-spin text-primary" />+ ) : ref.uri.endsWith('/') ? (+ <FolderIcon className="size-3.5 shrink-0 text-muted-foreground" />+ ) : (+ <FileTextIcon className="size-3.5 shrink-0 text-muted-foreground" />+ )}+ <span className="min-w-0 flex-1 truncate font-mono text-[11px]">+ {ref.label || fileNameFromUri(ref.uri) || ref.uri}+ </span>+ {ref.meta ? (+ <span className="shrink-0 rounded bg-muted px-1.5 py-0.5 text-[10px] text-muted-foreground">+ {ref.meta}+ </span>+ ) : null}+ </button>+ ))}+ </div>+ )+}diff --git a/web-studio/src/routes/studio/-components/terminal-panel.tsx b/web-studio/src/routes/studio/-components/terminal-panel.tsxnew file mode 100644index 000000000..1833ddb51--- /dev/null+++ b/web-studio/src/routes/studio/-components/terminal-panel.tsx@@ -0,0 +1,439 @@+import { useCallback, useEffect, useMemo, useRef, useState } from 'react'+import { useTranslation } from 'react-i18next'+import {+ CheckCircle2Icon,+ Loader2Icon,+ SendIcon,+ SparklesIcon,+ TerminalIcon,+ XCircleIcon,+} from 'lucide-react'++import { Button } from '#/components/ui/button'+import { cn } from '#/lib/utils'+import {+ fetchFileContent,+ fetchFsList,+ fetchSearch,+} from '#/routes/resources/-lib/api'+import { normalizeDirUri } from '#/routes/resources/-lib/normalize'+import type { VikingFsEntry } from '#/routes/resources/-types/viking-fm'++import { ROOT_URI, TERMINAL_COMMANDS } from '../-lib/constants'+import type {+ ResourceOpenHandler,+ TerminalCommandView,+ TerminalEntry,+} from '../-lib/types'+import {+ cleanVikingUri,+ entryToRef,+ searchResultToRefs,+ visibleContextEntries,+} from '../-lib/utils'+import { ResourceRefList } from './resource-ref-list'++export function TerminalPanel({+ currentUri,+ entries,+ onOpenAddResource,+ onOpenResource,+ openingUri,+}: {+ currentUri: string+ entries: VikingFsEntry[]+ onOpenAddResource: () => void+ onOpenResource: ResourceOpenHandler+ openingUri: string | null+}) {+ const { t } = useTranslation('studio')+ const [command, setCommand] = useState('')+ const [running, setRunning] = useState(false)+ const [suggestionsOpen, setSuggestionsOpen] = useState(false)+ const [activeSuggestionIndex, setActiveSuggestionIndex] = useState(0)+ const [history, setHistory] = useState<TerminalEntry[]>(() => [+ {+ id: 'welcome',+ kind: 'info',+ title: t('terminal.welcomeTitle'),+ body: t('terminal.welcomeBody'),+ },+ ])+ const scrollRef = useRef<HTMLDivElement>(null)++ const commands = useMemo<TerminalCommandView[]>(+ () =>+ TERMINAL_COMMANDS.map((item) => ({+ ...item,+ description: t(`terminal.commands.${item.key}.description`),+ usage: t(`terminal.commands.${item.key}.usage`),+ })),+ [t],+ )++ const groupLabels = useMemo(+ () => ({+ memories: t('terminal.groupLabels.memories'),+ resources: t('terminal.groupLabels.resources'),+ skills: t('terminal.groupLabels.skills'),+ }),+ [t],+ )++ const suggestions = useMemo(() => {+ const query = command.trimStart().toLowerCase()+ if (!query || query === '/') return commands+ if (!query.startsWith('/')) return []+ return commands.filter(+ (item) =>+ item.command.toLowerCase().startsWith(query) ||+ item.description.toLowerCase().includes(query.slice(1)),+ )+ }, [command, commands])++ useEffect(() => {+ setActiveSuggestionIndex(0)+ }, [suggestions.length])++ useEffect(() => {+ scrollRef.current?.scrollTo({+ behavior: 'smooth',+ top: scrollRef.current.scrollHeight,+ })+ }, [history.length, running])++ const append = useCallback((entry: Omit<TerminalEntry, 'id'>) => {+ setHistory((prev) => [+ ...prev,+ {+ ...entry,+ id: `${Date.now()}-${prev.length}`,+ },+ ])+ }, [])++ const runCommand = useCallback(+ async (raw: string) => {+ const trimmed = raw.trim()+ if (!trimmed || running) return++ append({ kind: 'command', title: trimmed })+ setCommand('')+ setRunning(true)++ try {+ const [name = '', ...args] = trimmed.split(/\s+/)+ const body = args.join(' ').trim()++ if (trimmed.startsWith('viking://')) {+ await onOpenResource(trimmed)+ append({+ kind: 'success',+ refs: [{ uri: trimmed }],+ title: t('terminal.opened'),+ })+ return+ }++ switch (name) {+ case '/status': {+ const root = await fetchFsList(ROOT_URI, { nodeLimit: 12 })+ append({+ body: t('terminal.onlineBody', { count: root.entries.length }),+ kind: 'success',+ refs: root.entries.slice(0, 6).map(entryToRef),+ title: t('terminal.onlineTitle'),+ })+ return+ }+ case '/ls': {+ const target = body ? normalizeDirUri(body) : currentUri+ const result = body+ ? await fetchFsList(target, {+ nodeLimit: 60,+ output: 'agent',+ showAllHidden: true,+ })+ : { entries, uri: currentUri }+ const visibleEntries = visibleContextEntries(result.entries)+ append({+ body: t('terminal.lsBody', {+ count: visibleEntries.length,+ uri: target,+ }),+ kind: 'success',+ refs: visibleEntries.map(entryToRef),+ title: `ls ${target}`,+ })+ return+ }+ case '/read': {+ if (!body) throw new Error(t('terminal.readUsage'))+ const uri = cleanVikingUri(body)+ if (!uri) throw new Error(t('terminal.enterUri'))+ const content = await fetchFileContent(uri, {+ limit: 1200,+ raw: true,+ })+ await onOpenResource(uri)+ append({+ body: content.content.slice(0, 1200) || t('terminal.fileEmpty'),+ kind: 'success',+ refs: [{ uri }],+ title: `read ${uri}`,+ })+ return+ }+ case '/find':+ case '/search': {+ if (!body) throw new Error(t('terminal.searchUsage', { name }))+ const result = await fetchSearch(body, {+ limit: 8,+ targetUri: currentUri,+ })+ append({+ body:+ result.query_plan?.reasoning ||+ t('terminal.hits', {+ memories: result.memories.length,+ resources: result.resources.length,+ skills: result.skills.length,+ }),+ kind: 'success',+ refs: searchResultToRefs(result, groupLabels),+ title: `${name} ${body}`,+ })+ return+ }+ case '/add-resource': {+ onOpenAddResource()+ append({+ body: t('terminal.addResourceBody'),+ kind: 'info',+ title: t('terminal.addResourceTitle'),+ })+ return+ }+ default:+ throw new Error(t('terminal.unknownCommand'))+ }+ } catch (error) {+ append({+ body: error instanceof Error ? error.message : String(error),+ kind: 'error',+ title: t('terminal.commandFailed'),+ })+ } finally {+ setRunning(false)+ }+ },+ [+ append,+ currentUri,+ entries,+ groupLabels,+ onOpenAddResource,+ onOpenResource,+ running,+ t,+ ],+ )++ const acceptSuggestion = useCallback((suggestion: TerminalCommandView) => {+ setCommand(suggestion.insertText)+ setSuggestionsOpen(false)+ }, [])++ const quickCommands = commands.filter((item) =>+ ['/status', '/ls', '/search', '/read', '/add-resource'].includes(+ item.command,+ ),+ )++ return (+ <div className="flex min-h-0 flex-1 flex-col">+ <div ref={scrollRef} className="min-h-0 flex-1 overflow-y-auto px-4 py-4">+ <div className="space-y-3">+ {history.map((entry) => (+ <TerminalHistoryItem+ key={entry.id}+ entry={entry}+ onOpenResource={onOpenResource}+ openingUri={openingUri}+ />+ ))}+ {running ? (+ <div className="flex items-center gap-2 rounded-lg border bg-background px-3 py-2 text-xs text-muted-foreground">+ <Loader2Icon className="size-3.5 animate-spin" />+ {t('terminal.running')}+ </div>+ ) : null}+ </div>+ </div>+ <div className="border-t bg-background/80 p-3">+ <div className="mb-2 flex flex-wrap gap-1.5">+ {quickCommands.map((item) => (+ <button+ key={item.command}+ type="button"+ className="rounded-md border bg-muted/40 px-2 py-1 font-mono text-[11px] text-muted-foreground transition-colors hover:border-primary/40 hover:text-foreground"+ onClick={() => acceptSuggestion(item)}+ >+ {item.command}+ </button>+ ))}+ </div>+ <form+ className="relative flex items-center gap-2 rounded-lg border bg-muted/30 px-2 py-2"+ onSubmit={(event) => {+ event.preventDefault()+ void runCommand(command)+ }}+ >+ <input+ value={command}+ onBlur={() => {+ window.setTimeout(() => setSuggestionsOpen(false), 120)+ }}+ onChange={(event) => {+ setCommand(event.target.value)+ setSuggestionsOpen(true)+ }}+ onFocus={() => setSuggestionsOpen(true)}+ onKeyDown={(event) => {+ if (!suggestionsOpen || suggestions.length === 0) return+ if (event.key === 'ArrowDown') {+ event.preventDefault()+ setActiveSuggestionIndex((current) =>+ Math.min(current + 1, suggestions.length - 1),+ )+ return+ }+ if (event.key === 'ArrowUp') {+ event.preventDefault()+ setActiveSuggestionIndex((current) => Math.max(current - 1, 0))+ return+ }+ if (event.key === 'Tab') {+ event.preventDefault()+ acceptSuggestion(suggestions[activeSuggestionIndex])+ return+ }+ if (event.key === 'Enter' && command.trim() === '/') {+ event.preventDefault()+ acceptSuggestion(suggestions[activeSuggestionIndex])+ return+ }+ if (event.key === 'Escape') {+ setSuggestionsOpen(false)+ }+ }}+ placeholder={t('terminal.placeholder')}+ className="h-8 min-w-0 flex-1 bg-transparent font-mono text-sm outline-none placeholder:text-muted-foreground/60"+ />+ {suggestionsOpen && suggestions.length > 0 ? (+ <div className="absolute bottom-[calc(100%+0.5rem)] left-0 right-0 z-20 overflow-hidden rounded-lg border bg-popover shadow-xl">+ <div className="border-b px-3 py-2 text-[11px] font-medium text-muted-foreground">+ {t('terminal.suggestionsTitle')}+ </div>+ <div className="max-h-64 overflow-y-auto p-1">+ {suggestions.map((suggestion, index) => (+ <button+ key={suggestion.command}+ type="button"+ className={cn(+ 'flex w-full min-w-0 items-start gap-3 rounded-md px-2 py-2 text-left transition-colors',+ index === activeSuggestionIndex+ ? 'bg-primary/10 text-foreground'+ : 'hover:bg-muted/60',+ )}+ onClick={() => acceptSuggestion(suggestion)}+ onMouseDown={(event) => event.preventDefault()}+ onMouseEnter={() => setActiveSuggestionIndex(index)}+ >+ <span className="w-24 shrink-0 font-mono text-xs font-semibold text-primary">+ {suggestion.command}+ </span>+ <span className="min-w-0 flex-1">+ <span className="block text-xs text-foreground">+ {suggestion.description}+ </span>+ <span className="mt-0.5 block truncate font-mono text-[11px] text-muted-foreground">+ {suggestion.usage}+ </span>+ </span>+ </button>+ ))}+ </div>+ <div className="border-t px-3 py-1.5 text-[10px] text-muted-foreground">+ {t('terminal.suggestionsHint')}+ </div>+ </div>+ ) : null}+ <Button+ type="submit"+ size="icon-sm"+ disabled={running || !command.trim()}+ >+ <SendIcon className="size-4" />+ </Button>+ </form>+ </div>+ </div>+ )+}++export function TerminalHistoryItem({+ entry,+ onOpenResource,+ openingUri,+}: {+ entry: TerminalEntry+ onOpenResource: ResourceOpenHandler+ openingUri: string | null+}) {+ const Icon =+ entry.kind === 'command'+ ? TerminalIcon+ : entry.kind === 'success'+ ? CheckCircle2Icon+ : entry.kind === 'error'+ ? XCircleIcon+ : SparklesIcon++ return (+ <section+ className={cn(+ 'rounded-lg border bg-background px-3 py-3 text-sm',+ entry.kind === 'command' && 'border-muted bg-muted/40 font-mono',+ entry.kind === 'error' && 'border-destructive/30 bg-destructive/5',+ )}+ >+ <div className="mb-2 flex items-center gap-2">+ <Icon+ className={cn(+ 'size-3.5 shrink-0 text-muted-foreground',+ entry.kind === 'success' && 'text-primary',+ entry.kind === 'error' && 'text-destructive',+ )}+ />+ <span className="min-w-0 truncate text-xs font-semibold">+ {entry.title}+ </span>+ </div>+ {entry.body ? (+ <pre className="max-h-56 overflow-auto whitespace-pre-wrap break-words rounded-md bg-muted/40 p-2 text-xs leading-5 text-muted-foreground">+ {entry.body}+ </pre>+ ) : null}+ {entry.refs?.length ? (+ <ResourceRefList+ className="mt-2"+ refs={entry.refs}+ onOpenResource={onOpenResource}+ openingUri={openingUri}+ />+ ) : null}+ </section>+ )+}diff --git a/web-studio/src/routes/studio/-lib/constants.ts b/web-studio/src/routes/studio/-lib/constants.tsnew file mode 100644index 000000000..195d13a40--- /dev/null+++ b/web-studio/src/routes/studio/-lib/constants.ts@@ -0,0 +1,27 @@+import type { TerminalCommandSuggestion } from './types'++export const ROOT_URI = 'viking://'+export const STUDIO_LEFT_WIDTH_STORAGE_KEY = 'web-studio-playground-left-width'+export const STUDIO_RIGHT_WIDTH_STORAGE_KEY =+ 'web-studio-playground-right-width'+export const STUDIO_AGENT_SESSIONS_STORAGE_KEY = 'web-studio-agent-sessions'+export const STUDIO_LEFT_WIDTH = {+ default: 330,+ max: 620,+ min: 240,+}+export const STUDIO_RIGHT_WIDTH = {+ default: 430,+ max: 680,+ min: 320,+}+export const STUDIO_MAIN_MIN_WIDTH = 420++export const TERMINAL_COMMANDS: TerminalCommandSuggestion[] = [+ { command: '/status', key: 'status', insertText: '/status' },+ { command: '/ls', key: 'ls', insertText: '/ls ' },+ { command: '/search', key: 'search', insertText: '/search ' },+ { command: '/find', key: 'find', insertText: '/find ' },+ { command: '/read', key: 'read', insertText: '/read ' },+ { command: '/add-resource', key: 'addResource', insertText: '/add-resource' },+]diff --git a/web-studio/src/routes/studio/-lib/types.ts b/web-studio/src/routes/studio/-lib/types.tsnew file mode 100644index 000000000..d5f148fdc--- /dev/null+++ b/web-studio/src/routes/studio/-lib/types.ts@@ -0,0 +1,48 @@+import type { VikingFsEntry } from '#/routes/resources/-types/viking-fm'++export type StudioPanel = 'agent' | 'terminal'++export type StudioSearch = {+ uri?: string+ file?: string+ panel?: StudioPanel+ session?: string+}++export type ResourceRef = {+ uri: string+ label?: string+ meta?: string+}++export type TerminalEntry = {+ id: string+ kind: 'command' | 'error' | 'info' | 'success'+ title: string+ body?: string+ refs?: ResourceRef[]+}++export type TerminalCommandKey =+ | 'status'+ | 'ls'+ | 'search'+ | 'find'+ | 'read'+ | 'addResource'++export type TerminalCommandSuggestion = {+ command: string+ /** i18n subkey under `studio.terminal.commands`. */+ key: TerminalCommandKey+ insertText: string+}++/** A {@link TerminalCommandSuggestion} with its label/usage resolved via i18n. */+export type TerminalCommandView = TerminalCommandSuggestion & {+ description: string+ usage: string+}++export type ResourceOpenHandler = (uri: string) => Promise<void> | void+export type VikingEntryHandler = (entry: VikingFsEntry) => voiddiff --git a/web-studio/src/routes/studio/-lib/utils.ts b/web-studio/src/routes/studio/-lib/utils.tsnew file mode 100644index 000000000..9acd7667d--- /dev/null+++ b/web-studio/src/routes/studio/-lib/utils.ts@@ -0,0 +1,238 @@+import {+ fileNameFromUri,+ normalizeDirUri,+ normalizeFileUri,+ parentUri,+} from '#/routes/resources/-lib/normalize'+import type { VikingFsEntry } from '#/routes/resources/-types/viking-fm'+import type { FindResultItem, GroupedFindResult } from '#/lib/retrieval'++import { cleanVikingUri } from '#/lib/viking-uri'++import { ROOT_URI, STUDIO_AGENT_SESSIONS_STORAGE_KEY } from './constants'+import type { ResourceRef } from './types'++export { cleanVikingUri }++export function getErrorMessage(error: unknown): string {+ return error instanceof Error ? error.message : String(error)+}++export function clampNumber(value: number, min: number, max: number): number {+ return Math.min(Math.max(value, min), max)+}++export function readStoredNumber(+ key: string,+ fallback: number,+ min: number,+ max: number,+): number {+ if (typeof window === 'undefined') return fallback++ const raw = window.localStorage.getItem(key)+ if (raw === null) return fallback++ const value = Number(raw)+ return Number.isFinite(value) ? clampNumber(value, min, max) : fallback+}++export function readStudioAgentSessionIds(): string[] {+ if (typeof window === 'undefined') return []++ try {+ const raw = window.localStorage.getItem(STUDIO_AGENT_SESSIONS_STORAGE_KEY)+ const parsed = raw ? (JSON.parse(raw) as unknown) : []+ if (!Array.isArray(parsed)) return []++ return parsed.filter(+ (sessionId): sessionId is string =>+ typeof sessionId === 'string' && sessionId.length > 0,+ )+ } catch {+ return []+ }+}++export function registerStudioAgentSessionId(sessionId: string): string[] {+ const trimmed = sessionId.trim()+ if (typeof window === 'undefined') return trimmed ? [trimmed] : []+ if (!trimmed) return readStudioAgentSessionIds()++ const next = [+ trimmed,+ ...readStudioAgentSessionIds().filter((item) => item !== trimmed),+ ].slice(0, 50)++ try {+ window.localStorage.setItem(+ STUDIO_AGENT_SESSIONS_STORAGE_KEY,+ JSON.stringify(next),+ )+ } catch {+ // Ignore storage failures in restricted browser contexts.+ }++ return next+}++export function createEntryFromUri(uri: string, isDir: boolean): VikingFsEntry {+ const normalized = isDir ? normalizeDirUri(uri) : normalizeFileUri(uri)+ return {+ abstract: '',+ isDir,+ modTime: '',+ modTimestamp: null,+ name: fileNameFromUri(normalized) || normalized,+ overview: '',+ size: '',+ sizeBytes: null,+ uri: normalized,+ }+}++export function getAncestorUris(uri: string): string[] {+ const normalized = normalizeDirUri(uri)+ if (normalized === ROOT_URI) return [ROOT_URI]++ const body = normalized.slice(ROOT_URI.length, -1)+ const parts = body.split('/').filter(Boolean)+ const ancestors = [ROOT_URI]+ let running = ROOT_URI++ for (const part of parts) {+ running = `${running}${part}/`+ ancestors.push(running)+ }++ return ancestors+}++export function mergeExpanded(+ current: Set<string>,+ uris: string[],+): Set<string> {+ const next = new Set(current)+ for (const uri of uris) next.add(uri)+ return next+}++export function buildBreadcrumbs(+ uri: string,+ isFile: boolean,+): Array<{ label: string; uri: string }> {+ const normalized = isFile ? normalizeFileUri(uri) : normalizeDirUri(uri)+ const dirUri = isFile ? normalizeDirUri(parentUri(normalized)) : normalized+ const body = dirUri.slice(ROOT_URI.length).replace(/\/$/, '')+ const parts = body ? body.split('/').filter(Boolean) : []+ const crumbs: Array<{ label: string; uri: string }> = [+ { label: ROOT_URI, uri: ROOT_URI },+ ]+ let running = ROOT_URI++ for (const part of parts) {+ running = `${running}${part}/`+ crumbs.push({ label: part, uri: running })+ }++ if (isFile) {+ crumbs.push({+ label: fileNameFromUri(normalized) || normalized,+ uri: normalized,+ })+ }++ return crumbs+}++export function isDirectoryLevelFile(uri: string): boolean {+ const name = fileNameFromUri(uri)+ return name === '_abstract.md' || name === '_overview.md'+}++export function normalizeStudioResourceUri(uri: string): string {+ const normalized = uri.endsWith('/')+ ? normalizeDirUri(uri)+ : normalizeFileUri(uri)+ if (!normalized.endsWith('/') && isDirectoryLevelFile(normalized)) {+ return normalizeDirUri(parentUri(normalized))+ }+ return normalized+}++export function entryToRef(entry: VikingFsEntry): ResourceRef {+ return {+ label: entry.name || fileNameFromUri(entry.uri),+ meta: entry.isDir ? 'dir' : entry.size || undefined,+ uri: entry.uri,+ }+}++export function visibleContextEntries(+ entries: VikingFsEntry[],+): VikingFsEntry[] {+ return entries.filter(+ (entry) => entry.isDir || !isDirectoryLevelFile(entry.uri),+ )+}++export function sortTreeEntries(entries: VikingFsEntry[]): VikingFsEntry[] {+ return [...entries].sort((left, right) => {+ if (left.isDir !== right.isDir) return left.isDir ? -1 : 1+ return left.name.localeCompare(right.name)+ })+}++export function withTimeout<T>(+ promise: Promise<T>,+ timeoutMs: number,+ message: string,+): Promise<T> {+ return new Promise((resolve, reject) => {+ const timeoutId = window.setTimeout(() => {+ reject(new Error(message))+ }, timeoutMs)++ promise.then(+ (value) => {+ window.clearTimeout(timeoutId)+ resolve(value)+ },+ (error) => {+ window.clearTimeout(timeoutId)+ reject(error)+ },+ )+ })+}++export function formatScore(score: number): string {+ if (!Number.isFinite(score)) return 'score -'+ return `score ${score.toFixed(2)}`+}++type FindGroup = 'memories' | 'resources' | 'skills'++/**+ * Flatten a grouped search result (resources + memories + skills) into a single+ * ordered ref list, tagging each ref with its (localized) type, level and score+ * so nothing is dropped from the terminal output.+ */+export function searchResultToRefs(+ result: GroupedFindResult,+ groupLabels: Record<FindGroup, string>,+): ResourceRef[] {+ const groups: Array<[FindGroup, FindResultItem[]]> = [+ ['resources', result.resources],+ ['memories', result.memories],+ ['skills', result.skills],+ ]++ return groups.flatMap(([group, items]) =>+ items.map((item) => ({+ label: fileNameFromUri(item.uri) || item.uri,+ meta: `${groupLabels[group]} · L${item.level} · ${formatScore(item.score)}`,+ uri: item.uri,+ })),+ )+}diff --git a/web-studio/src/routes/studio/route.tsx b/web-studio/src/routes/studio/route.tsxnew file mode 100644index 000000000..104c644d6--- /dev/null+++ b/web-studio/src/routes/studio/route.tsx@@ -0,0 +1,543 @@+import { useCallback, useEffect, useMemo, useRef, useState } from 'react'+import type { CSSProperties, PointerEvent as ReactPointerEvent } from 'react'+import { createFileRoute, useNavigate } from '@tanstack/react-router'+import { useTranslation } from 'react-i18next'+import { BotIcon, ClipboardIcon, TerminalIcon } from 'lucide-react'+import { toast } from 'sonner'++import { Button } from '#/components/ui/button'+import {+ Dialog,+ DialogContent,+ DialogDescription,+ DialogHeader,+ DialogTitle,+} from '#/components/ui/dialog'+import { cn } from '#/lib/utils'+import { FilePreview } from '#/routes/resources/-components/file-preview'+import { AddResourceForm } from '#/routes/resources/-components/add-resource-page'+import { ResourceUploadProvider } from '#/routes/resources/-hooks/use-resource-upload'+import {+ useInvalidateVikingFs,+ useVikingFsList,+} from '#/routes/resources/-hooks/viking-fm'+import { fetchFsStat } from '#/routes/resources/-lib/api'+import {+ fileNameFromUri,+ normalizeDirUri,+ normalizeFileUri,+ parentUri,+} from '#/routes/resources/-lib/normalize'+import type { VikingFsEntry } from '#/routes/resources/-types/viking-fm'++import { AgentPanel } from './-components/agent-panel'+import {+ ContextExplorerHeader,+ ContextTree,+ PanelTab,+ StudioResizeHandle,+} from './-components/context-explorer'+import { TerminalPanel } from './-components/terminal-panel'+import {+ ROOT_URI,+ STUDIO_LEFT_WIDTH,+ STUDIO_LEFT_WIDTH_STORAGE_KEY,+ STUDIO_MAIN_MIN_WIDTH,+ STUDIO_RIGHT_WIDTH,+ STUDIO_RIGHT_WIDTH_STORAGE_KEY,+} from './-lib/constants'+import type { StudioPanel, StudioSearch } from './-lib/types'+import {+ buildBreadcrumbs,+ clampNumber,+ cleanVikingUri,+ createEntryFromUri,+ getAncestorUris,+ isDirectoryLevelFile,+ mergeExpanded,+ normalizeStudioResourceUri,+ readStoredNumber,+ visibleContextEntries,+} from './-lib/utils'++export const Route = createFileRoute('/studio')({+ validateSearch: (search: Record<string, unknown>): StudioSearch => ({+ file: typeof search.file === 'string' ? search.file : undefined,+ panel:+ search.panel === 'agent' || search.panel === 'terminal'+ ? search.panel+ : undefined,+ session: typeof search.session === 'string' ? search.session : undefined,+ uri: typeof search.uri === 'string' ? search.uri : undefined,+ }),+ component: StudioRoute,+})++function StudioRoute() {+ return (+ <ResourceUploadProvider>+ <StudioWorkbench />+ </ResourceUploadProvider>+ )+}++function StudioWorkbench() {+ const { t } = useTranslation('studio')+ const search = Route.useSearch()+ const navigate = useNavigate({ from: Route.fullPath })+ const initialCurrentUri = useMemo(+ () =>+ search.file+ ? normalizeDirUri(parentUri(search.file))+ : normalizeDirUri(search.uri || ROOT_URI),+ [search.file, search.uri],+ )++ const [currentUri, setCurrentUri] = useState(initialCurrentUri)+ const [selectedFile, setSelectedFile] = useState<VikingFsEntry | null>(() =>+ search.file && !isDirectoryLevelFile(search.file)+ ? createEntryFromUri(search.file, false)+ : createEntryFromUri(initialCurrentUri, true),+ )+ const [expandedKeys, setExpandedKeys] = useState<Set<string>>(+ () => new Set(getAncestorUris(initialCurrentUri)),+ )+ const [activePanel, setActivePanel] = useState<StudioPanel>(+ search.panel ?? 'agent',+ )+ const [uploadDialogOpen, setUploadDialogOpen] = useState(false)+ const [openingUri, setOpeningUri] = useState<string | null>(null)+ const layoutRef = useRef<HTMLDivElement>(null)+ const [leftWidth, setLeftWidth] = useState(() =>+ readStoredNumber(+ STUDIO_LEFT_WIDTH_STORAGE_KEY,+ STUDIO_LEFT_WIDTH.default,+ STUDIO_LEFT_WIDTH.min,+ STUDIO_LEFT_WIDTH.max,+ ),+ )+ const [rightWidth, setRightWidth] = useState(() =>+ readStoredNumber(+ STUDIO_RIGHT_WIDTH_STORAGE_KEY,+ STUDIO_RIGHT_WIDTH.default,+ STUDIO_RIGHT_WIDTH.min,+ STUDIO_RIGHT_WIDTH.max,+ ),+ )+ const [resizingPane, setResizingPane] = useState<'context' | 'action' | null>(+ null,+ )+ const isDraggingPaneRef = useRef(false)+ const activeResizeTeardownRef = useRef<(() => void) | null>(null)+ const leftWidthRef = useRef(leftWidth)+ const rightWidthRef = useRef(rightWidth)+ leftWidthRef.current = leftWidth+ rightWidthRef.current = rightWidth++ const listQuery = useVikingFsList(currentUri, {+ output: 'agent',+ showAllHidden: true,+ nodeLimit: 500,+ })+ const { invalidateList } = useInvalidateVikingFs()++ const syncSearch = useCallback(+ (next: {+ file?: string+ panel?: StudioPanel+ session?: string+ uri?: string+ }) => {+ navigate({+ replace: true,+ search: (prev) => ({+ ...prev,+ ...next,+ }),+ })+ },+ [navigate],+ )++ useEffect(() => {+ const normalized = search.file+ ? normalizeDirUri(parentUri(search.file))+ : normalizeDirUri(search.uri || ROOT_URI)+ setCurrentUri(normalized)+ setSelectedFile(+ search.file && !isDirectoryLevelFile(search.file)+ ? createEntryFromUri(search.file, false)+ : createEntryFromUri(normalized, true),+ )+ setExpandedKeys((prev) => mergeExpanded(prev, getAncestorUris(normalized)))+ }, [search.file, search.uri])++ useEffect(() => {+ if (search.panel === 'agent' || search.panel === 'terminal') {+ setActivePanel(search.panel)+ }+ }, [search.panel])++ const revealResource = useCallback(+ async (rawUri: string) => {+ const cleaned = cleanVikingUri(rawUri)+ if (!cleaned) return++ setOpeningUri(cleaned)+ const targetUri = normalizeStudioResourceUri(cleaned)+ try {+ const stat = await fetchFsStat(targetUri, { throwOnError: true })+ const isDir = stat.isDir || targetUri.endsWith('/')+ const normalized = isDir+ ? normalizeDirUri(targetUri)+ : normalizeFileUri(targetUri)+ const nextCurrentUri = isDir+ ? normalizeDirUri(normalized)+ : normalizeDirUri(parentUri(normalized))++ setCurrentUri(nextCurrentUri)+ setSelectedFile({+ ...stat,+ isDir,+ name: stat.name || fileNameFromUri(normalized),+ uri: normalized,+ })+ setExpandedKeys((prev) =>+ mergeExpanded(prev, getAncestorUris(nextCurrentUri)),+ )+ syncSearch({+ file: isDir ? undefined : normalized,+ uri: nextCurrentUri,+ })+ } catch (error) {+ const fallbackIsDir = targetUri.endsWith('/')+ const normalized = fallbackIsDir+ ? normalizeDirUri(targetUri)+ : normalizeFileUri(targetUri)+ const nextCurrentUri = fallbackIsDir+ ? normalized+ : normalizeDirUri(parentUri(normalized))++ setCurrentUri(nextCurrentUri)+ setSelectedFile(createEntryFromUri(normalized, fallbackIsDir))+ setExpandedKeys((prev) =>+ mergeExpanded(prev, getAncestorUris(nextCurrentUri)),+ )+ syncSearch({+ file: fallbackIsDir ? undefined : normalized,+ uri: nextCurrentUri,+ })+ toast.error(+ error instanceof Error+ ? error.message+ : t('readFailed', { uri: cleaned }),+ )+ } finally {+ setOpeningUri(null)+ }+ },+ [syncSearch, t],+ )++ const handleSelectDirectory = useCallback(+ (entry: VikingFsEntry) => {+ const normalized = normalizeDirUri(entry.uri)+ setCurrentUri(normalized)+ setSelectedFile({ ...entry, isDir: true, uri: normalized })+ setExpandedKeys((prev) =>+ mergeExpanded(prev, getAncestorUris(normalized)),+ )+ syncSearch({ file: undefined, uri: normalized })+ },+ [syncSearch],+ )++ const handleSelectFile = useCallback(+ (entry: VikingFsEntry) => {+ const normalized = normalizeFileUri(entry.uri)+ if (isDirectoryLevelFile(normalized)) {+ const dirUri = normalizeDirUri(parentUri(normalized))+ setCurrentUri(dirUri)+ setSelectedFile(createEntryFromUri(dirUri, true))+ setExpandedKeys((prev) => mergeExpanded(prev, getAncestorUris(dirUri)))+ syncSearch({ file: undefined, uri: dirUri })+ return+ }++ const nextCurrentUri = normalizeDirUri(parentUri(normalized))+ setCurrentUri(nextCurrentUri)+ setSelectedFile({ ...entry, isDir: false, uri: normalized })+ setExpandedKeys((prev) =>+ mergeExpanded(prev, getAncestorUris(nextCurrentUri)),+ )+ syncSearch({ file: normalized, uri: nextCurrentUri })+ },+ [syncSearch],+ )++ const handlePanelChange = useCallback(+ (panel: StudioPanel) => {+ setActivePanel(panel)+ syncSearch({ panel })+ },+ [syncSearch],+ )++ const breadcrumbs = useMemo(() => {+ const targetUri = selectedFile?.uri ?? currentUri+ const isFile = selectedFile ? !selectedFile.isDir : false+ return buildBreadcrumbs(targetUri, isFile)+ }, [currentUri, selectedFile])++ const selectedUri = selectedFile?.uri ?? currentUri+ const entries = visibleContextEntries(listQuery.data?.entries ?? [])+ const layoutStyle = useMemo(+ () =>+ ({+ '--studio-left-width': `${leftWidth}px`,+ '--studio-right-width': `${rightWidth}px`,+ }) as CSSProperties,+ [leftWidth, rightWidth],+ )++ const handleResizeStart = useCallback(+ (pane: 'context' | 'action', event: ReactPointerEvent<HTMLDivElement>) => {+ event.preventDefault()+ event.currentTarget.setPointerCapture(event.pointerId)+ isDraggingPaneRef.current = true+ setResizingPane(pane)++ const startX = event.clientX+ const startLeftWidth = leftWidthRef.current+ const startRightWidth = rightWidthRef.current+ const layoutRect = layoutRef.current?.getBoundingClientRect()++ const getMaxWidth = (+ side: 'left' | 'right',+ currentOppositeWidth: number,+ ) => {+ if (!layoutRect) {+ return side === 'left'+ ? STUDIO_LEFT_WIDTH.max+ : STUDIO_RIGHT_WIDTH.max+ }++ const hardMax =+ side === 'left' ? STUDIO_LEFT_WIDTH.max : STUDIO_RIGHT_WIDTH.max+ const availableMax =+ layoutRect.width - currentOppositeWidth - STUDIO_MAIN_MIN_WIDTH+ return Math.max(+ side === 'left' ? STUDIO_LEFT_WIDTH.min : STUDIO_RIGHT_WIDTH.min,+ Math.min(hardMax, availableMax),+ )+ }++ const onMove = (moveEvent: PointerEvent) => {+ const deltaX = moveEvent.clientX - startX+ if (pane === 'context') {+ const nextWidth = clampNumber(+ startLeftWidth + deltaX,+ STUDIO_LEFT_WIDTH.min,+ getMaxWidth('left', rightWidthRef.current),+ )+ setLeftWidth(nextWidth)+ window.localStorage.setItem(+ STUDIO_LEFT_WIDTH_STORAGE_KEY,+ String(nextWidth),+ )+ return+ }++ const nextWidth = clampNumber(+ startRightWidth - deltaX,+ STUDIO_RIGHT_WIDTH.min,+ getMaxWidth('right', leftWidthRef.current),+ )+ setRightWidth(nextWidth)+ window.localStorage.setItem(+ STUDIO_RIGHT_WIDTH_STORAGE_KEY,+ String(nextWidth),+ )+ }++ const onUp = () => {+ isDraggingPaneRef.current = false+ activeResizeTeardownRef.current = null+ setResizingPane(null)+ document.removeEventListener('pointermove', onMove)+ document.removeEventListener('pointerup', onUp)+ document.removeEventListener('pointercancel', onUp)+ document.body.style.cursor = ''+ document.body.style.userSelect = ''+ }++ document.body.style.cursor = 'col-resize'+ document.body.style.userSelect = 'none'+ document.addEventListener('pointermove', onMove)+ document.addEventListener('pointerup', onUp)+ document.addEventListener('pointercancel', onUp)+ activeResizeTeardownRef.current = onUp+ },+ [],+ )++ useEffect(() => {+ return () => {+ // Tear down any in-flight drag so the document listeners don't outlive+ // the component when it unmounts mid-resize.+ activeResizeTeardownRef.current?.()+ }+ }, [])++ return (+ <div className="-mx-4 -my-6 flex h-[calc(100svh-3rem)] min-h-0 flex-col bg-background md:-mx-6">+ <div+ ref={layoutRef}+ className="flex min-h-0 flex-1 flex-col border-t bg-background lg:flex-row"+ style={layoutStyle}+ >+ <aside className="flex min-h-[260px] min-w-0 flex-col border-b bg-muted/20 lg:min-h-0 lg:w-[var(--studio-left-width)] lg:min-w-[var(--studio-left-width)] lg:border-b-0">+ <ContextExplorerHeader+ isRefreshing={listQuery.isFetching}+ onAddResource={() => setUploadDialogOpen(true)}+ onRefresh={() => {+ void invalidateList(currentUri)+ void listQuery.refetch()+ }}+ />+ <div className="min-h-0 flex-1">+ <ContextTree+ currentUri={currentUri}+ selectedFileUri={+ selectedFile && !selectedFile.isDir ? selectedFile.uri : null+ }+ expandedKeys={expandedKeys}+ onExpandedKeysChange={setExpandedKeys}+ onSelectDirectory={handleSelectDirectory}+ onSelectFile={handleSelectFile}+ />+ </div>+ </aside>+ <StudioResizeHandle+ active={resizingPane === 'context'}+ label={t('resizeContext')}+ onPointerDown={(event) => handleResizeStart('context', event)}+ />++ <main className="flex min-h-[420px] min-w-0 flex-1 flex-col border-b lg:min-h-0 lg:border-b-0">+ <div className="flex min-h-14 items-center gap-3 border-b px-4">+ <nav className="flex min-w-0 flex-1 items-center gap-1 overflow-x-auto whitespace-nowrap text-sm">+ {breadcrumbs.map((crumb, index) => (+ <span+ key={crumb.uri}+ className="flex shrink-0 items-center gap-1.5"+ >+ {index > 0 ? (+ <span className="font-mono text-xs text-muted-foreground/60">+ /+ </span>+ ) : null}+ <button+ type="button"+ className={cn(+ 'rounded px-1.5 py-1 font-mono text-xs transition-colors hover:bg-muted',+ index === breadcrumbs.length - 1+ ? 'font-semibold text-foreground'+ : 'text-muted-foreground',+ )}+ onClick={() => void revealResource(crumb.uri)}+ >+ {crumb.label}+ </button>+ </span>+ ))}+ </nav>+ <Button+ type="button"+ size="icon-sm"+ variant="ghost"+ title={t('copyUri')}+ onClick={() => {+ void navigator.clipboard.writeText(selectedUri)+ toast.success(t('copied'))+ }}+ >+ <ClipboardIcon className="size-4" />+ </Button>+ </div>+ <div className="min-h-0 flex-1">+ <FilePreview+ file={selectedFile}+ onClose={() => setSelectedFile(null)}+ showCloseButton={false}+ />+ </div>+ </main>+ <StudioResizeHandle+ active={resizingPane === 'action'}+ label={t('resizeAction')}+ onPointerDown={(event) => handleResizeStart('action', event)}+ />++ <aside className="flex min-h-[460px] min-w-0 flex-col bg-muted/15 lg:min-h-0 lg:w-[var(--studio-right-width)] lg:min-w-[var(--studio-right-width)]">+ <div className="flex h-14 items-center border-b px-3">+ <div className="inline-flex rounded-lg border bg-background p-1">+ <PanelTab+ active={activePanel === 'terminal'}+ icon={TerminalIcon}+ label={t('tabs.terminal')}+ onClick={() => handlePanelChange('terminal')}+ />+ <PanelTab+ active={activePanel === 'agent'}+ icon={BotIcon}+ label={t('tabs.agent')}+ onClick={() => handlePanelChange('agent')}+ />+ </div>+ </div>++ {activePanel === 'terminal' ? (+ <TerminalPanel+ currentUri={currentUri}+ entries={entries}+ onOpenAddResource={() => setUploadDialogOpen(true)}+ onOpenResource={revealResource}+ openingUri={openingUri}+ />+ ) : (+ <AgentPanel+ initialSessionId={search.session}+ onOpenResource={revealResource}+ onSessionChange={(sessionId) =>+ syncSearch({ session: sessionId })+ }+ />+ )}+ </aside>+ </div>++ <Dialog open={uploadDialogOpen} onOpenChange={setUploadDialogOpen}>+ <DialogContent className="max-h-[min(86vh,760px)] gap-0 overflow-hidden p-0 sm:max-w-4xl">+ <DialogHeader className="border-b px-6 py-5">+ <DialogTitle className="text-xl">+ {t('addResource.title')}+ </DialogTitle>+ <DialogDescription>+ {t('addResource.description')}+ </DialogDescription>+ </DialogHeader>+ <div className="max-h-[calc(min(86vh,760px)-6rem)] overflow-y-auto px-6 py-5">+ <AddResourceForm+ onSubmitted={() => {+ setUploadDialogOpen(false)+ void invalidateList()+ toast.success(t('addResource.submitted'))+ }}+ />+ </div>+ </DialogContent>+ </Dialog>+ </div>+ )+}