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
Improve web studio resource reader (#2163)
Zayn Jarvisa534f789f686
diff --git a/web-studio/index.html b/web-studio/index.htmlindex 67a13a67b..c474176d9 100644--- a/web-studio/index.html+++ b/web-studio/index.html@@ -2,9 +2,16 @@<html lang="en"><head><meta charset="UTF-8" />- <link rel="icon" type="image/png" href="%BASE_URL%openviking-icon.png" />+ <link+ rel="icon"+ type="image/png"+ sizes="32x32"+ href="%BASE_URL%favicon-32.png"+ />+ <link rel="apple-touch-icon" href="%BASE_URL%apple-touch-icon.png" />+ <link rel="manifest" href="%BASE_URL%manifest.json" /><meta name="viewport" content="width=device-width, initial-scale=1.0" />- <title>web-studio</title>+ <title>OpenViking Studio</title></head><body><div id="app"></div>diff --git a/web-studio/public/manifest.json b/web-studio/public/manifest.jsonindex 55080ac00..ae9062b72 100644--- a/web-studio/public/manifest.json+++ b/web-studio/public/manifest.json@@ -3,10 +3,16 @@"name": "OpenViking Studio","icons": [{- "src": "openviking-icon.png",+ "src": "favicon-32.png","type": "image/png",- "sizes": "1280x1280",- "purpose": "any maskable"+ "sizes": "32x32",+ "purpose": "any"+ },+ {+ "src": "apple-touch-icon.png",+ "type": "image/png",+ "sizes": "180x180",+ "purpose": "any"}],"start_url": ".",diff --git a/web-studio/public/openviking-icon.png b/web-studio/public/openviking-icon.pngdeleted file mode 100644index 08dc9b4ac..000000000Binary files a/web-studio/public/openviking-icon.png and /dev/null differdiff --git a/web-studio/src/components/app-shell.tsx b/web-studio/src/components/app-shell.tsxindex 16e878610..7f0e3b9ce 100644--- a/web-studio/src/components/app-shell.tsx+++ b/web-studio/src/components/app-shell.tsx@@ -27,7 +27,6 @@ import {CollapsibleTrigger,} from '#/components/ui/collapsible'import { ConnectionDialog } from '#/components/connection-dialog'-import { Badge } from '#/components/ui/badge'import { buttonVariants } from '#/components/ui/button'import {DropdownMenu,@@ -60,7 +59,6 @@ import {AppConnectionProvider,useAppConnection,} from '#/hooks/use-app-connection'-import { describeServerMode } from '#/hooks/use-server-mode'import {useSessionList,useCreateSession,@@ -352,9 +350,8 @@ function AppShellInner({ children }: { children: React.ReactNode }) {const pathname = useRouterState({select: (state) => state.location.pathname,})- const { openConnectionDialog, serverMode } = useAppConnection()+ const { openConnectionDialog } = useAppConnection()const { setTheme, resolvedTheme } = useTheme()- const serverModeBadge = describeServerMode(serverMode)const currentLanguage = resolveLanguage(i18n.resolvedLanguage ?? i18n.language,)@@ -483,10 +480,6 @@ function AppShellInner({ children }: { children: React.ReactNode }) {<header className="flex h-12 shrink-0 items-center justify-end border-b border-border/70 bg-background px-4 backdrop-blur-md md:px-6"><SidebarTrigger className="mr-auto shrink-0 md:hidden" /><div className="flex items-center gap-1">- <Badge variant={serverModeBadge.variant} className="mr-1">- {t(serverModeBadge.labelKey, { ns: 'common' })}- </Badge>-<buttontype="button"aria-label={t('theme.toggle', { ns: 'common' })}diff --git a/web-studio/src/hooks/use-app-connection.tsx b/web-studio/src/hooks/use-app-connection.tsxindex ec6df6e6d..5abb867ed 100644--- a/web-studio/src/hooks/use-app-connection.tsx+++ b/web-studio/src/hooks/use-app-connection.tsx@@ -1,4 +1,5 @@import * as React from 'react'+import { useQueryClient } from '@tanstack/react-query'import { isOvClientError, ovClient } from '#/lib/ov-client'@@ -78,6 +79,38 @@ function persistConnection(connection: ConnectionDraft): void {}}+function normalizeConnectionDraft(connection: ConnectionDraft): ConnectionDraft {+ return {+ accountId: connection.accountId.trim(),+ apiKey: connection.apiKey.trim(),+ baseUrl: normalizeBaseUrl(connection.baseUrl),+ userId: connection.userId.trim(),+ }+}++function applyConnection(connection: ConnectionDraft): void {+ ovClient.setOptions({+ baseUrl: connection.baseUrl,+ })+ ovClient.setConnection({+ accountId: connection.accountId,+ apiKey: connection.apiKey,+ userId: connection.userId,+ })+}++function readInitialConnection(): ConnectionDraft {+ const storedConnection = readStoredConnection()+ return normalizeConnectionDraft({+ ...DEFAULT_CONNECTION,+ ...storedConnection,+ apiKey:+ ovClient.getConnection().apiKey ||+ storedConnection.apiKey ||+ DEFAULT_CONNECTION.apiKey,+ })+}+export function summarizeConnectionIdentity(connection: ConnectionDraft,serverMode: ServerMode,@@ -115,30 +148,25 @@ export function AppConnectionProvider({}: {children: React.ReactNode}) {- const storedConnection = React.useMemo(() => readStoredConnection(), [])- const [connection, setConnection] = React.useState<ConnectionDraft>({- ...DEFAULT_CONNECTION,- ...storedConnection,- apiKey:- ovClient.getConnection().apiKey ||- storedConnection.apiKey ||- DEFAULT_CONNECTION.apiKey,- })+ const queryClient = useQueryClient()+ const initialConnectionRef = React.useRef<ConnectionDraft | null>(null)+ if (initialConnectionRef.current === null) {+ initialConnectionRef.current = readInitialConnection()+ applyConnection(initialConnectionRef.current)+ }++ const [connection, setConnection] = React.useState<ConnectionDraft>(+ initialConnectionRef.current,+ )const [isConnectionDialogOpen, setConnectionDialogOpen] =React.useState(false)const [serverMode, setServerMode] = React.useState<ServerMode>('checking')React.useEffect(() => {- ovClient.setOptions({- baseUrl: connection.baseUrl,- })- ovClient.setConnection({- accountId: connection.accountId,- apiKey: connection.apiKey,- userId: connection.userId,- })+ applyConnection(connection)persistConnection(connection)- }, [connection])+ void queryClient.invalidateQueries()+ }, [connection, queryClient])React.useEffect(() => {let cancelled = false@@ -180,12 +208,7 @@ export function AppConnectionProvider({isConnectionDialogOpen,openConnectionDialog: () => setConnectionDialogOpen(true),saveConnection: (next) =>- setConnection({- accountId: next.accountId.trim(),- apiKey: next.apiKey.trim(),- baseUrl: normalizeBaseUrl(next.baseUrl),- userId: next.userId.trim(),- }),+ setConnection(normalizeConnectionDraft(next)),serverMode,setConnectionDialogOpen,}),diff --git a/web-studio/src/i18n/locales/en.ts b/web-studio/src/i18n/locales/en.tsindex efbd1ec99..4cb030982 100644--- a/web-studio/src/i18n/locales/en.ts+++ b/web-studio/src/i18n/locales/en.ts@@ -56,7 +56,7 @@ const en = {},serverMode: {checking: 'Detecting',- devImplicit: 'Development Mode',+ devImplicit: 'Server Identity',explicitAuth: 'Explicit Auth',offline: 'Offline',},@@ -64,8 +64,8 @@ const en = {connection: {devMode: {description:- 'This server is using implicit identity, so account, user, and API key are usually not required.',- title: 'Development Mode Detected',+ 'This server provides identity automatically, so account, user, and API key are usually not required.',+ title: 'Server-managed identity',},dialog: {title: 'Connection & Identity',diff --git a/web-studio/src/i18n/locales/zh-CN.ts b/web-studio/src/i18n/locales/zh-CN.tsindex 7efe42a7c..397a91235 100644--- a/web-studio/src/i18n/locales/zh-CN.ts+++ b/web-studio/src/i18n/locales/zh-CN.ts@@ -56,7 +56,7 @@ const zhCN = {},serverMode: {checking: '检测中',- devImplicit: '开发模式',+ devImplicit: '服务端身份',explicitAuth: '显式鉴权',offline: '未连接',},@@ -64,8 +64,8 @@ const zhCN = {connection: {devMode: {description:- '当前服务使用隐式身份,通常不需要填写 account、user 和 API key。',- title: '已检测到开发模式',+ '当前服务会自动提供身份,通常不需要填写 account、user 和 API key。',+ title: '服务端托管身份',},dialog: {title: '连接与身份',diff --git a/web-studio/src/routes/resources/-components/file-list.tsx b/web-studio/src/routes/resources/-components/file-list.tsxindex ade9146c6..c8a0177ad 100644--- a/web-studio/src/routes/resources/-components/file-list.tsx+++ b/web-studio/src/routes/resources/-components/file-list.tsx@@ -13,7 +13,7 @@ type SortDirection = 'asc' | 'desc'interface FileListProps {entries: Array<VikingFsEntry>selectedFileUri: string | null- onOpenDirectory: (uri: string) => void+ onOpenDirectory: (entry: VikingFsEntry) => voidonOpenFile: (file: VikingFsEntry) => void}@@ -78,7 +78,7 @@ export function FileList({type="button"onClick={() => {if (entry.isDir) {- onOpenDirectory(entry.uri)+ onOpenDirectory(entry)return}onOpenFile(entry)diff --git a/web-studio/src/routes/resources/-components/file-preview.tsx b/web-studio/src/routes/resources/-components/file-preview.tsxindex fe18576ce..431596289 100644--- a/web-studio/src/routes/resources/-components/file-preview.tsx+++ b/web-studio/src/routes/resources/-components/file-preview.tsx@@ -1,4 +1,6 @@import { useEffect, useMemo, useRef, useState, lazy, Suspense } from 'react'+import type { ComponentProps, ReactNode } from 'react'+import { useQuery } from '@tanstack/react-query'import hljs from 'highlight.js/lib/core'import ReactMarkdown from 'react-markdown'import remarkGfm from 'remark-gfm'@@ -12,8 +14,8 @@ import { getContentDownload, ovClient } from '#/lib/ov-client'import type { GetContentDownloadData } from '#/gen/ov-client/types.gen'import type { ContentDownloadQuery } from '@ov-server/api/v1/content'-import { formatSize } from '../-lib/normalize'-import { saveFileContent } from '../-lib/api'+import { formatSize, normalizeReadContent } from '../-lib/normalize'+import { fetchDirectoryLevelContent, saveFileContent } from '../-lib/api'import {useVikingFilePreview,useInvalidateVikingFs,@@ -76,6 +78,17 @@ const languageLoaders: Partial<}const loadedLanguages = new Set<string>()+const markdownLanguageAliases: Record<string, string> = {+ cjs: 'javascript',+ js: 'javascript',+ jsx: 'javascript',+ mjs: 'javascript',+ sh: 'bash',+ ts: 'typescript',+ tsx: 'typescript',+ yml: 'yaml',+ zsh: 'bash',+}async function ensureLanguage(lang: string): Promise<void> {if (loadedLanguages.has(lang)) return@@ -96,6 +109,49 @@ const vikingPrefix = 'viking://'const contentDownloadUrl: GetContentDownloadData['url'] ='/api/v1/content/download'+type DirectoryLevelId = 'abstract' | 'overview'++const DIRECTORY_LEVEL_META: Array<{+ id: DirectoryLevelId+ label: string+ name: string+ title: string+}> = [+ {+ id: 'abstract',+ label: 'Abstract',+ name: 'L0',+ title: 'Short semantic abstract',+ },+ {+ id: 'overview',+ label: 'Overview',+ name: 'L1',+ title: 'Directory overview',+ },+]++const JSONL_MESSAGE_PREVIEW_LIMIT = 720+const JSONL_TOOLCALL_STORAGE_KEY = 'web-studio-jsonl-toolcall'++type JsonlRecord = {+ error: Error | null+ index: number+ line: string+ parsed: unknown+}++type JsonlMessage = {+ id: string+ kind: 'agent' | 'assistant' | 'invalid' | 'other' | 'tool-result' | 'user'+ label: string+ lineNo: number+ roleId: string+ text: string+ time: string+ toolName: string+}+function toDownloadUrl(vikingUri: string): string {const query: ContentDownloadQuery = { uri: vikingUri }return client.buildUrl({@@ -110,6 +166,71 @@ function withCacheBust(url: string, cacheKey: string): string {return `${url}${separator}_t=${encodeURIComponent(cacheKey)}`}+function isRecord(value: unknown): value is Record<string, unknown> {+ return value !== null && typeof value === 'object' && !Array.isArray(value)+}++function cleanSummaryContent(value: unknown): string {+ if (value === undefined || value === null) return ''+ const normalized = normalizeReadContent(value)+ const text = typeof normalized === 'string' ? normalized.trim() : ''+ if (!text) return ''+ if (+ /\[directory (overview|abstract) is not (generated|ready)\]/i.test(text)+ ) {+ return ''+ }+ return text+}++function useDirectoryPreview(file: VikingFsEntry | null) {+ const enabled = Boolean(file?.isDir)+ const abstractQuery = useQuery({+ enabled,+ queryKey: ['viking-directory-level', file?.uri, 'abstract'],+ queryFn: () => fetchDirectoryLevelContent(file!.uri, 'abstract'),+ staleTime: 30_000,+ })+ const overviewQuery = useQuery({+ enabled,+ queryKey: ['viking-directory-level', file?.uri, 'overview'],+ queryFn: () => fetchDirectoryLevelContent(file!.uri, 'overview'),+ staleTime: 30_000,+ })++ return useMemo(+ () => ({+ isLoading: abstractQuery.isLoading || overviewQuery.isLoading,+ levels: [+ {+ ...DIRECTORY_LEVEL_META[0],+ content:+ cleanSummaryContent(abstractQuery.data) ||+ cleanSummaryContent(file?.abstract),+ error: abstractQuery.error,+ },+ {+ ...DIRECTORY_LEVEL_META[1],+ content:+ cleanSummaryContent(overviewQuery.data) ||+ cleanSummaryContent(file?.overview),+ error: overviewQuery.error,+ },+ ],+ }),+ [+ abstractQuery.data,+ abstractQuery.error,+ abstractQuery.isLoading,+ file?.abstract,+ file?.overview,+ overviewQuery.data,+ overviewQuery.error,+ overviewQuery.isLoading,+ ],+ )+}+function dirnameVikingUri(fileUri: string): string {if (fileUri === vikingPrefix) {return vikingPrefix@@ -270,6 +391,470 @@ function escapeHtml(raw: string): string {return raw.replace(/&/g, '&').replace(/</g, '<').replace(/>/g, '>')}+function textFromReactNode(node: ReactNode): string {+ if (typeof node === 'string' || typeof node === 'number') {+ return String(node)+ }+ if (Array.isArray(node)) {+ return node.map(textFromReactNode).join('')+ }+ return ''+}++function normalizeMarkdownLanguage(className: string | undefined): string {+ const match = /language-([\w-]+)/.exec(className || '')+ const raw = match?.[1]?.toLowerCase() || ''+ return markdownLanguageAliases[raw] ?? raw+}++function MarkdownCode({+ className,+ children,+}: ComponentProps<'code'> & { inline?: boolean }) {+ const rawText = textFromReactNode(children).replace(/\n$/, '')+ const language = normalizeMarkdownLanguage(className)+ const isBlock = Boolean(language || rawText.includes('\n'))+ const [html, setHtml] = useState(() => escapeHtml(rawText))++ useEffect(() => {+ if (!isBlock) {+ setHtml(escapeHtml(rawText))+ return+ }++ let cancelled = false+ const run = async () => {+ try {+ if (language) {+ await ensureLanguage(language)+ }+ if (cancelled) return+ const highlighted =+ language && hljs.getLanguage(language)+ ? hljs.highlight(rawText, {+ ignoreIllegals: true,+ language,+ }).value+ : escapeHtml(rawText)+ setHtml(highlighted)+ } catch {+ if (!cancelled) setHtml(escapeHtml(rawText))+ }+ }++ void run()+ return () => {+ cancelled = true+ }+ }, [isBlock, language, rawText])++ if (!isBlock) {+ return (+ <code className="rounded bg-muted px-1 py-0.5 font-mono text-[0.92em] text-foreground">+ {children}+ </code>+ )+ }++ return (+ <code+ className={`hljs block overflow-x-auto whitespace-pre font-mono text-xs leading-6 ${className || ''}`}+ dangerouslySetInnerHTML={{ __html: html || escapeHtml(rawText) }}+ />+ )+}++function MarkdownPre({ children }: ComponentProps<'pre'>) {+ return (+ <pre className="overflow-x-auto rounded-md border bg-muted/30 p-3 text-xs leading-6 text-foreground dark:bg-muted-foreground/20">+ {children}+ </pre>+ )+}++const markdownComponents = {+ code: MarkdownCode,+ pre: MarkdownPre,+ table: ({ children }: ComponentProps<'table'>) => (+ <div className="my-4 overflow-x-auto rounded-md border">+ <table className="w-full border-collapse text-sm">{children}</table>+ </div>+ ),+ td: ({ children }: ComponentProps<'td'>) => (+ <td className="border-t px-3 py-2 align-top">{children}</td>+ ),+ th: ({ children }: ComponentProps<'th'>) => (+ <th className="bg-muted/50 px-3 py-2 text-left font-medium">{children}</th>+ ),+}++function parseJsonlRecords(text: string): JsonlRecord[] {+ return text+ .replace(/\r\n/g, '\n')+ .split('\n')+ .map((line, index) => ({ line, index }))+ .filter((record) => record.line.trim().length > 0)+ .map((record) => {+ try {+ return {+ ...record,+ error: null,+ parsed: JSON.parse(record.line) as unknown,+ }+ } catch (error) {+ return {+ ...record,+ error: error instanceof Error ? error : new Error(String(error)),+ parsed: null,+ }+ }+ })+}++function formatJsonlPart(part: unknown): string {+ if (typeof part === 'string') return part+ if (!isRecord(part)) return JSON.stringify(part)++ if (typeof part.text === 'string') return part.text++ if (part.type === 'tool_use') {+ const name = typeof part.name === 'string' ? part.name : 'tool'+ const input = part.input ?? part.arguments ?? {}+ return `[tool: ${name}]\n${JSON.stringify(input, null, 2)}`+ }++ if (part.type === 'tool_result') {+ const content = part.content ?? part.result ?? ''+ return `[tool result]\n${+ typeof content === 'string' ? content : JSON.stringify(content, null, 2)+ }`+ }++ const payload = { ...part }+ delete payload.type+ const type = String(part.type || 'part')+ const body = Object.keys(payload).length+ ? JSON.stringify(payload, null, 2)+ : ''+ return body ? `[${type}]\n${body}` : `[${type}]`+}++function stringifyJsonlContent(value: unknown): string {+ if (typeof value === 'string') return value+ if (Array.isArray(value)) return value.map(formatJsonlPart).join('\n\n')+ if (value === undefined || value === null) return ''+ return JSON.stringify(value, null, 2)+}++function getJsonlMessage(record: JsonlRecord): JsonlMessage {+ const { error, index, line, parsed } = record+ if (error || !isRecord(parsed)) {+ return {+ id: '',+ kind: 'invalid',+ label: 'invalid',+ lineNo: index + 1,+ roleId: '',+ text: line,+ time: '',+ toolName: '',+ }+ }++ const nestedMessage = isRecord(parsed.message) ? parsed.message : null+ const source = nestedMessage ?? parsed+ const role = String(source.role ?? parsed.role ?? parsed.type ?? 'message')+ .trim()+ .toLowerCase()+ const content =+ source.content ?? source.parts ?? parsed.parts ?? parsed.content ?? parsed+ const text = stringifyJsonlContent(content)+ const toolCall = text.match(/^\[tool:\s*([^\]]+)\]/)+ const toolResult = /^\[tool result\]/.test(text)+ const kind = toolResult+ ? 'tool-result'+ : role === 'user'+ ? 'user'+ : role === 'assistant' || role === 'agent'+ ? role+ : 'other'++ return {+ id: String(parsed.uuid ?? parsed.id ?? source.id ?? ''),+ kind,+ label: toolResult ? 'tool-result' : role,+ lineNo: index + 1,+ roleId: String(parsed.role_id ?? source.role_id ?? ''),+ text,+ time: String(+ parsed.timestamp ?? parsed.created_at ?? source.created_at ?? '',+ ),+ toolName: toolCall?.[1] ?? '',+ }+}++function isJsonlMarkdownMessage(kind: JsonlMessage['kind']): boolean {+ return kind === 'assistant' || kind === 'agent' || kind === 'user'+}++function formatJsonlTime(value: string): string {+ if (!value) return ''+ const date = new Date(value)+ if (Number.isNaN(date.getTime())) return value+ return date.toLocaleString([], {+ day: 'numeric',+ hour: '2-digit',+ minute: '2-digit',+ month: 'short',+ })+}++function JsonlRawRow({ record }: { record: JsonlRecord }) {+ const [open, setOpen] = useState(false)+ const parsed = record.parsed+ const keys = isRecord(parsed) ? Object.keys(parsed) : []+ const titleKey = keys.find((key) =>+ ['name', 'title', 'event', 'type', 'role', 'method'].includes(key),+ )++ return (+ <div+ className={`grid grid-cols-[3.5rem_1fr] border-b transition-colors hover:bg-muted/40 ${+ open ? 'bg-muted/30' : ''+ }`}+ >+ <button+ type="button"+ className="flex items-center justify-end gap-1 border-r px-2 py-2 font-mono text-[11px] text-muted-foreground hover:text-foreground"+ onClick={() => setOpen((current) => !current)}+ >+ <span>{record.index + 1}</span>+ <span>{open ? '▾' : '▸'}</span>+ </button>+ <div className="min-w-0 px-3 py-2">+ {open ? (+ <pre className="overflow-auto whitespace-pre-wrap break-words text-xs leading-5">+ {record.error+ ? record.line+ : JSON.stringify(record.parsed, null, 2)}+ </pre>+ ) : record.error ? (+ <div className="truncate text-xs text-destructive">{record.line}</div>+ ) : titleKey && isRecord(parsed) ? (+ <div className="flex min-w-0 items-center gap-2 text-xs">+ <span className="rounded bg-primary/10 px-1.5 py-0.5 font-mono text-[10px] font-semibold uppercase text-primary">+ {titleKey}+ </span>+ <span className="truncate font-medium">+ {String(parsed[titleKey])}+ </span>+ <span className="shrink-0 text-muted-foreground">+ {keys+ .filter((key) => key !== titleKey)+ .slice(0, 3)+ .join(', ')}+ </span>+ </div>+ ) : (+ <div className="truncate text-xs text-muted-foreground">+ {keys.slice(0, 6).join(', ') || record.line}+ </div>+ )}+ </div>+ </div>+ )+}++function JsonlToolBody({ text, toolName }: { text: string; toolName: string }) {+ const afterTag = text.replace(/^\[tool:\s*[^\]]+\]\s*/, '')+ const parsed = useMemo(() => {+ if (!toolName || !afterTag.trim()) return null+ try {+ return JSON.parse(afterTag) as unknown+ } catch {+ return null+ }+ }, [afterTag, toolName])++ return parsed ? (+ <pre className="max-h-96 overflow-auto rounded border bg-muted/30 p-2 text-xs leading-5">+ {JSON.stringify(parsed, null, 2)}+ </pre>+ ) : (+ <pre className="whitespace-pre-wrap break-words text-xs leading-5">+ {afterTag || 'No arguments'}+ </pre>+ )+}++function JsonlMarkdownBody({ content }: { content: string }) {+ return (+ <div className="prose prose-sm max-w-none break-words dark:prose-invert dark:prose-pre:bg-muted-foreground/20">+ <ReactMarkdown remarkPlugins={[remarkGfm]} components={markdownComponents}>+ {content || 'Empty message'}+ </ReactMarkdown>+ </div>+ )+}++function JsonlMessageCard({ record }: { record: JsonlRecord }) {+ const [expanded, setExpanded] = useState(false)+ const message = useMemo(() => getJsonlMessage(record), [record])+ const isTool = Boolean(message.toolName || message.kind === 'tool-result')+ const needsExpand =+ !isTool && message.text.length > JSONL_MESSAGE_PREVIEW_LIMIT+ const body =+ expanded || !needsExpand+ ? message.text+ : `${message.text.slice(0, JSONL_MESSAGE_PREVIEW_LIMIT).trimEnd()}...`+ const alignClass =+ message.kind === 'user'+ ? 'ml-auto bg-primary/10 border-primary/25'+ : message.kind === 'tool-result'+ ? 'mx-auto border-dashed bg-muted/50'+ : message.kind === 'invalid' || message.kind === 'other'+ ? 'w-full max-w-none bg-muted/40'+ : 'mr-auto bg-background'++ return (+ <article+ className={`w-fit max-w-[min(820px,88%)] rounded-lg border p-3 text-sm shadow-sm ${alignClass}`}+ >+ <div className="mb-2 flex min-w-0 items-center gap-2">+ <span className="text-xs font-semibold">{message.label}</span>+ {message.roleId ? (+ <span className="truncate text-xs text-muted-foreground">+ {message.roleId}+ </span>+ ) : null}+ {message.toolName ? (+ <span className="truncate rounded border bg-muted px-1.5 py-0.5 font-mono text-[11px] text-muted-foreground">+ {message.toolName}+ </span>+ ) : null}+ <span className="ml-auto shrink-0 font-mono text-[11px] text-muted-foreground">+ #{message.lineNo}+ </span>+ </div>++ {message.toolName ? (+ <JsonlToolBody text={message.text} toolName={message.toolName} />+ ) : isJsonlMarkdownMessage(message.kind) ? (+ <JsonlMarkdownBody content={body} />+ ) : (+ <pre className="whitespace-pre-wrap break-words text-xs leading-5">+ {body || 'Empty message'}+ </pre>+ )}++ <div className="mt-2 flex items-center gap-2 border-t pt-2 text-[11px] text-muted-foreground">+ {message.time ? (+ <time dateTime={message.time}>{formatJsonlTime(message.time)}</time>+ ) : null}+ {message.id ? <span className="truncate">{message.id}</span> : null}+ {needsExpand ? (+ <button+ type="button"+ className="ml-auto rounded border px-2 py-0.5 font-medium text-primary hover:border-primary"+ onClick={() => setExpanded((current) => !current)}+ >+ {expanded ? 'Collapse' : 'Expand'}+ </button>+ ) : null}+ </div>+ </article>+ )+}++function JsonlPreview({ content }: { content: string }) {+ const [dialogMode, setDialogMode] = useState(true)+ const [showTools, setShowTools] = useState(() => {+ if (typeof window === 'undefined') return true+ const stored = window.localStorage.getItem(JSONL_TOOLCALL_STORAGE_KEY)+ return stored === null ? true : stored === 'true'+ })+ const records = useMemo(() => parseJsonlRecords(content), [content])+ const filteredRecords = useMemo(() => {+ if (!dialogMode || showTools) return records+ return records.filter((record) => {+ const message = getJsonlMessage(record)+ return !message.toolName && message.kind !== 'tool-result'+ })+ }, [dialogMode, records, showTools])+ const hasTools = useMemo(+ () =>+ records.some((record) => {+ const message = getJsonlMessage(record)+ return Boolean(message.toolName || message.kind === 'tool-result')+ }),+ [records],+ )++ if (!records.length) {+ return (+ <div className="rounded-md border border-dashed p-6 text-sm text-muted-foreground">+ Empty JSONL.+ </div>+ )+ }++ return (+ <div className="grid gap-3">+ <div className="flex flex-wrap items-center justify-between gap-3 text-xs text-muted-foreground">+ <span className="font-medium text-primary">+ {records.length} record{records.length === 1 ? '' : 's'}+ </span>+ <div className="flex items-center gap-2">+ {dialogMode && hasTools ? (+ <label className="inline-flex cursor-pointer items-center gap-2">+ <span className="font-medium">toolcall</span>+ <input+ type="checkbox"+ className="peer sr-only"+ checked={showTools}+ onChange={(event) => {+ setShowTools(event.target.checked)+ window.localStorage.setItem(+ JSONL_TOOLCALL_STORAGE_KEY,+ String(event.target.checked),+ )+ }}+ />+ <span className="h-5 w-9 rounded-full border bg-muted transition-colors after:block after:size-3.5 after:translate-x-0.5 after:translate-y-0.5 after:rounded-full after:bg-muted-foreground after:transition-transform peer-checked:border-primary peer-checked:bg-primary/15 peer-checked:after:translate-x-[18px] peer-checked:after:bg-primary" />+ </label>+ ) : null}+ <label className="inline-flex cursor-pointer items-center gap-2">+ <span className="font-medium">+ {dialogMode ? 'Dialog' : 'JSONL'}+ </span>+ <input+ type="checkbox"+ className="peer sr-only"+ checked={dialogMode}+ onChange={(event) => setDialogMode(event.target.checked)}+ />+ <span className="h-5 w-9 rounded-full border bg-muted transition-colors after:block after:size-3.5 after:translate-x-0.5 after:translate-y-0.5 after:rounded-full after:bg-muted-foreground after:transition-transform peer-checked:border-primary peer-checked:bg-primary/15 peer-checked:after:translate-x-[18px] peer-checked:after:bg-primary" />+ </label>+ </div>+ </div>++ {dialogMode ? (+ <div className="flex flex-col gap-3">+ {filteredRecords.map((record) => (+ <JsonlMessageCard key={record.index} record={record} />+ ))}+ </div>+ ) : (+ <div className="overflow-hidden rounded-md border">+ {records.map((record) => (+ <JsonlRawRow key={record.index} record={record} />+ ))}+ </div>+ )}+ </div>+ )+}+export function FilePreview({file,onClose,@@ -281,23 +866,30 @@ export function FilePreview({defaultReadLimit: -1,})const preview = previewQuery.preview+ const directoryPreview = useDirectoryPreview(file)const [markdownMode, setMarkdownMode] = useState<'preview' | 'source'>('preview',)+ const [activeDirectoryLevels, setActiveDirectoryLevels] = useState<+ Set<DirectoryLevelId>+ >(new Set(['abstract', 'overview']))const [editing, setEditing] = useState(false)const [saving, setSaving] = useState(false)const editorRef = useRef<CodeEditorHandle>(null)const { invalidatePreview } = useInvalidateVikingFs()const canEdit =+ !file?.isDir &&preview?.shouldAutoRead &&(preview.fileType === 'code' ||preview.fileType === 'markdown' ||+ preview.fileType === 'jsonl' ||preview.fileType === 'text')useEffect(() => {setMarkdownMode('preview')setEditing(false)+ setActiveDirectoryLevels(new Set(['abstract', 'overview']))}, [file?.uri])const [imageUrl, setImageUrl] = useState<string | null>(null)@@ -436,6 +1028,12 @@ export function FilePreview({const isMarkdown = preview?.fileType === 'markdown'const isDark = document.documentElement.classList.contains('dark')const emptyFileText = t('filePreview.emptyFile')+ const availableDirectoryLevels = directoryPreview.levels.filter((level) =>+ level.content.trim(),+ )+ const visibleDirectoryLevels = availableDirectoryLevels.filter((level) =>+ activeDirectoryLevels.has(level.id),+ )return (<div className="flex h-full min-h-0 flex-col overflow-hidden">@@ -444,7 +1042,8 @@ export function FilePreview({<div className="min-w-0"><div className="truncate text-sm font-medium">{file.name}</div><div className="text-xs text-muted-foreground">- {formatSize(file.sizeBytes ?? file.size)} · {file.modTime || '-'}+ {file.isDir ? 'Folder' : formatSize(file.sizeBytes ?? file.size)}{' '}+ · {file.modTime || '-'}</div></div>{editing ? (@@ -516,162 +1115,259 @@ export function FilePreview({</Suspense></div>) : (- <ScrollArea className="h-full min-h-0 p-4">- {isMarkdown && !editing ? (- <div className="mb-3 inline-flex overflow-hidden rounded-md border">- <button- type="button"- className={`px-3 py-1.5 text-xs ${markdownMode === 'preview' ? 'bg-muted font-medium text-foreground' : 'text-muted-foreground hover:bg-muted/60'}`}- onClick={() => setMarkdownMode('preview')}- >- {t('filePreview.markdownPreview')}- </button>- <button- type="button"- className={`px-3 py-1.5 text-xs ${markdownMode === 'source' ? 'bg-muted font-medium text-foreground' : 'text-muted-foreground hover:bg-muted/60'}`}- onClick={() => setMarkdownMode('source')}- >- {t('filePreview.markdownSource')}- </button>- </div>- ) : null}+ <ScrollArea className="h-full min-h-0">+ <div className="mx-auto min-h-full w-full max-w-5xl p-4">+ {isMarkdown && !editing ? (+ <div className="mb-3 inline-flex overflow-hidden rounded-md border">+ <button+ type="button"+ className={`px-3 py-1.5 text-xs ${markdownMode === 'preview' ? 'bg-muted font-medium text-foreground' : 'text-muted-foreground hover:bg-muted/60'}`}+ onClick={() => setMarkdownMode('preview')}+ >+ {t('filePreview.markdownPreview')}+ </button>+ <button+ type="button"+ className={`px-3 py-1.5 text-xs ${markdownMode === 'source' ? 'bg-muted font-medium text-foreground' : 'text-muted-foreground hover:bg-muted/60'}`}+ onClick={() => setMarkdownMode('source')}+ >+ {t('filePreview.markdownSource')}+ </button>+ </div>+ ) : null}- {preview?.fileType === 'image' ? (- imageLoading ? (- <div className="text-sm text-muted-foreground">- {t('filePreview.imageLoading')}+ {file.isDir ? (+ <div className="grid gap-4">+ {availableDirectoryLevels.length > 0 ? (+ <div className="flex flex-wrap gap-2 border-b pb-3">+ {availableDirectoryLevels.map((level) => {+ const active = activeDirectoryLevels.has(level.id)+ return (+ <button+ key={level.id}+ type="button"+ className={`inline-flex items-baseline gap-1.5 rounded-full border px-3 py-1 text-xs transition-colors ${+ active+ ? 'border-primary bg-primary text-primary-foreground'+ : 'border-border bg-background text-muted-foreground hover:border-foreground/30 hover:text-foreground'+ }`}+ title={level.title}+ onClick={() =>+ setActiveDirectoryLevels((current) => {+ const next = new Set(current)+ if (next.has(level.id)) {+ next.delete(level.id)+ } else {+ next.add(level.id)+ }+ return next+ })+ }+ >+ <span+ className={`font-mono text-[10px] font-semibold uppercase tracking-wide ${+ active+ ? 'text-primary-foreground'+ : 'text-primary'+ }`}+ >+ {level.name}+ </span>+ <span className="font-medium">{level.label}</span>+ </button>+ )+ })}+ </div>+ ) : null}++ {directoryPreview.isLoading &&+ availableDirectoryLevels.length === 0 ? (+ <div className="text-sm text-muted-foreground">+ {t('filePreview.loadingContent')}+ </div>+ ) : availableDirectoryLevels.length === 0 ? (+ <div className="rounded-md border border-dashed p-6 text-sm text-muted-foreground">+ No abstract or overview available for this folder.+ </div>+ ) : visibleDirectoryLevels.length === 0 ? (+ <div className="rounded-md border border-dashed p-6 text-sm text-muted-foreground">+ Select a chip to show folder context.+ </div>+ ) : (+ <div className="grid gap-5">+ {visibleDirectoryLevels.map((level, index) => (+ <section key={level.id} className="grid gap-2">+ {index > 0 ? <div className="border-t" /> : null}+ <header className="flex items-center gap-2 text-xs">+ <span className="font-mono font-semibold uppercase tracking-wide text-primary">+ {level.name}+ </span>+ <span className="font-medium">{level.label}</span>+ <span className="text-muted-foreground">+ {level.title}+ </span>+ </header>+ <article className="prose prose-sm max-w-none break-words rounded-md border bg-muted/20 p-3 dark:prose-invert dark:prose-pre:bg-muted-foreground/20">+ <ReactMarkdown+ remarkPlugins={[remarkGfm]}+ components={markdownComponents}+ >+ {level.content}+ </ReactMarkdown>+ </article>+ </section>+ ))}+ </div>+ )}</div>- ) : imageUrl ? (- <img- src={imageUrl}- alt={file.name}- className="max-h-[70vh] max-w-full rounded-md object-contain outline outline-1 -outline-offset-1 outline-black/10 dark:outline-white/10"- />- ) : imageSrc ? (- <div className="space-y-3">+ ) : null}++ {preview?.fileType === 'image' ? (+ imageLoading ? (+ <div className="text-sm text-muted-foreground">+ {t('filePreview.imageLoading')}+ </div>+ ) : imageUrl ? (<img- src={imageSrc}+ src={imageUrl}alt={file.name}className="max-h-[70vh] max-w-full rounded-md object-contain outline outline-1 -outline-offset-1 outline-black/10 dark:outline-white/10"- onError={() => setImageError('direct img failed')}/>- {imageError ? (- <div className="text-xs text-muted-foreground">- {imageError}- </div>- ) : null}- </div>- ) : (- <div className="space-y-1 text-sm text-muted-foreground">- <div>{t('filePreview.imageFailed')}</div>- {imageError ? (- <div className="text-xs">{imageError}</div>- ) : null}+ ) : imageSrc ? (+ <div className="space-y-3">+ <img+ src={imageSrc}+ alt={file.name}+ className="max-h-[70vh] max-w-full rounded-md object-contain outline outline-1 -outline-offset-1 outline-black/10 dark:outline-white/10"+ onError={() => setImageError('direct img failed')}+ />+ {imageError ? (+ <div className="text-xs text-muted-foreground">+ {imageError}+ </div>+ ) : null}+ </div>+ ) : (+ <div className="space-y-1 text-sm text-muted-foreground">+ <div>{t('filePreview.imageFailed')}</div>+ {imageError ? (+ <div className="text-xs">{imageError}</div>+ ) : null}+ </div>+ )+ ) : null}++ {previewQuery.isLoading && preview?.fileType !== 'image' ? (+ <div className="text-sm text-muted-foreground">+ {t('filePreview.loadingContent')}</div>- )- ) : null}+ ) : null}- {previewQuery.isLoading && preview?.fileType !== 'image' ? (- <div className="text-sm text-muted-foreground">- {t('filePreview.loadingContent')}- </div>- ) : null}+ {!previewQuery.isLoading &&+ preview &&+ !file.isDir &&+ preview.fileType !== 'image' &&+ !preview.shouldAutoRead ? (+ <div className="text-sm text-muted-foreground">+ {preview.reason === 'binary'+ ? t('filePreview.unsupportedBinary')+ : t('filePreview.largeFileSkipped')}+ </div>+ ) : null}- {!previewQuery.isLoading &&- preview &&- preview.fileType !== 'image' &&- !preview.shouldAutoRead ? (- <div className="text-sm text-muted-foreground">- {preview.reason === 'binary'- ? t('filePreview.unsupportedBinary')- : t('filePreview.largeFileSkipped')}- </div>- ) : null}+ {!previewQuery.isLoading &&+ preview?.fileType === 'markdown' &&+ preview.shouldAutoRead &&+ markdownMode === 'preview' ? (+ <article className="prose prose-sm max-w-none break-words dark:prose-invert dark:prose-pre:bg-muted-foreground/20">+ <ReactMarkdown+ remarkPlugins={[remarkGfm]}+ components={{+ ...markdownComponents,+ img: ({ src, alt }) => {+ const resolvedSrc = src+ ? resolveMarkdownAssetUrl(String(src), file.uri)+ : String(src || '')+ return (+ <img+ src={resolvedSrc}+ alt={alt || ''}+ loading="lazy"+ className="max-w-full rounded-md outline outline-1 -outline-offset-1 outline-black/10 dark:outline-white/10"+ />+ )+ },+ a: ({ href, children }) => {+ const resolvedHref = href+ ? resolveMarkdownAssetUrl(String(href), file.uri)+ : String(href || '')+ const isExternal = /^(https?:|mailto:|tel:)/i.test(+ resolvedHref,+ )+ return (+ <a+ href={resolvedHref}+ target={isExternal ? '_blank' : undefined}+ rel={isExternal ? 'noreferrer noopener' : undefined}+ >+ {children}+ </a>+ )+ },+ }}+ >+ {preview.content || emptyFileText}+ </ReactMarkdown>+ </article>+ ) : null}- {!previewQuery.isLoading &&- preview?.fileType === 'markdown' &&- preview.shouldAutoRead &&- markdownMode === 'preview' ? (- <article className="prose prose-sm max-w-none break-words dark:prose-invert dark:prose-pre:bg-muted-foreground/20">- <ReactMarkdown- remarkPlugins={[remarkGfm]}- components={{- img: ({ src, alt }) => {- const resolvedSrc = src- ? resolveMarkdownAssetUrl(String(src), file.uri)- : String(src || '')- return (- <img- src={resolvedSrc}- alt={alt || ''}- loading="lazy"- className="max-w-full rounded-md outline outline-1 -outline-offset-1 outline-black/10 dark:outline-white/10"- />- )- },- a: ({ href, children }) => {- const resolvedHref = href- ? resolveMarkdownAssetUrl(String(href), file.uri)- : String(href || '')- const isExternal = /^(https?:|mailto:|tel:)/i.test(- resolvedHref,- )- return (- <a- href={resolvedHref}- target={isExternal ? '_blank' : undefined}- rel={isExternal ? 'noreferrer noopener' : undefined}- >- {children}- </a>- )- },- }}- >- {preview.content || emptyFileText}- </ReactMarkdown>- </article>- ) : null}+ {!previewQuery.isLoading &&+ preview?.fileType === 'markdown' &&+ preview.shouldAutoRead &&+ markdownMode === 'source' ? (+ <pre className="overflow-auto rounded-md border bg-muted/20 p-3 text-xs leading-6">+ <code+ className="hljs block"+ dangerouslySetInnerHTML={{+ __html:+ highlightedCodeHtml ||+ escapeHtml(preview.content || emptyFileText),+ }}+ />+ </pre>+ ) : null}- {!previewQuery.isLoading &&- preview?.fileType === 'markdown' &&- preview.shouldAutoRead &&- markdownMode === 'source' ? (- <pre className="overflow-auto rounded-md border bg-muted/20 p-3 text-xs leading-6">- <code- className="hljs block"- dangerouslySetInnerHTML={{- __html:- highlightedCodeHtml ||- escapeHtml(preview.content || emptyFileText),- }}- />- </pre>- ) : null}+ {!previewQuery.isLoading &&+ preview?.fileType === 'code' &&+ preview.shouldAutoRead ? (+ <pre className="overflow-auto rounded-md border bg-muted/20 p-3 text-xs leading-6">+ <code+ className="hljs block"+ dangerouslySetInnerHTML={{+ __html: highlightedCodeHtml || escapeHtml(emptyFileText),+ }}+ />+ </pre>+ ) : null}- {!previewQuery.isLoading &&- preview?.fileType === 'code' &&- preview.shouldAutoRead ? (- <pre className="overflow-auto rounded-md border bg-muted/20 p-3 text-xs leading-6">- <code- className="hljs block"- dangerouslySetInnerHTML={{- __html: highlightedCodeHtml || escapeHtml(emptyFileText),- }}- />- </pre>- ) : null}+ {!previewQuery.isLoading &&+ preview?.fileType === 'jsonl' &&+ preview.shouldAutoRead ? (+ <JsonlPreview content={preview.content || ''} />+ ) : null}- {!previewQuery.isLoading &&- preview &&- preview.fileType !== 'image' &&- preview.fileType !== 'markdown' &&- preview.fileType !== 'code' &&- preview.shouldAutoRead ? (- <pre className="whitespace-pre-wrap break-words text-xs leading-6">- {preview.content || emptyFileText}- </pre>- ) : null}+ {!previewQuery.isLoading &&+ preview &&+ preview.fileType !== 'image' &&+ preview.fileType !== 'markdown' &&+ preview.fileType !== 'jsonl' &&+ preview.fileType !== 'code' &&+ preview.shouldAutoRead ? (+ <pre className="whitespace-pre-wrap break-words text-xs leading-6">+ {preview.content || emptyFileText}+ </pre>+ ) : null}+ </div></ScrollArea>)}</div>diff --git a/web-studio/src/routes/resources/-components/file-tree.tsx b/web-studio/src/routes/resources/-components/file-tree.tsxindex c70682116..9dfbbee40 100644--- a/web-studio/src/routes/resources/-components/file-tree.tsx+++ b/web-studio/src/routes/resources/-components/file-tree.tsx@@ -13,7 +13,7 @@ interface FileTreeProps {selectedFileUri?: string | nullexpandedKeys: Set<string>onExpandedKeysChange: (next: Set<string>) => void- onSelectDirectory: (uri: string) => void+ onSelectDirectory: (entry: VikingFsEntry) => voidonSelectFile?: (entry: VikingFsEntry) => void}@@ -24,7 +24,7 @@ interface TreeNodeProps {selectedFileUri?: string | nullexpandedKeys: Set<string>onExpandedKeysChange: (next: Set<string>) => void- onSelectDirectory: (uri: string) => void+ onSelectDirectory: (entry: VikingFsEntry) => voidonSelectFile?: (entry: VikingFsEntry) => voidprefetch?: (uri: string) => void}@@ -106,7 +106,7 @@ function TreeNode({const handleSelect = useCallback(() => {if (entryRef.current.isDir) {- onSelectDirectory(entryRef.current.uri)+ onSelectDirectory(entryRef.current)} else {onSelectFile?.(entryRef.current)}@@ -215,13 +215,14 @@ const TreeNodeMemo = memo(TreeNode)const ROOT_ENTRY: VikingFsEntry = {uri: 'viking://',- name: fileNameFromUri('viking://'),+ name: 'viking://',isDir: true,size: '',sizeBytes: null,modTime: '',modTimestamp: null,abstract: '',+ overview: '',}export function FileTree({diff --git a/web-studio/src/routes/resources/-components/viking-file-manager.tsx b/web-studio/src/routes/resources/-components/viking-file-manager.tsxindex 96102bf19..aa62d4b17 100644--- a/web-studio/src/routes/resources/-components/viking-file-manager.tsx+++ b/web-studio/src/routes/resources/-components/viking-file-manager.tsx@@ -1,4 +1,5 @@import { useCallback, useEffect, useMemo, useRef, useState } from 'react'+import type { CSSProperties, PointerEvent as ReactPointerEvent } from 'react'import {ChevronRight,FolderOpen,@@ -59,6 +60,31 @@ function isDirectoryUri(uri: string): boolean {return uri.endsWith('/')}+const TREE_WIDTH_STORAGE_KEY = 'web-studio-resource-tree-width'+const TREE_HEIGHT_STORAGE_KEY = 'web-studio-resource-tree-height'++function clampNumber(value: number, min: number, max: number): number {+ return Math.min(Math.max(value, min), max)+}++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 stored = Number(raw)+ return Number.isFinite(stored) ? clampNumber(stored, min, max) : fallback+}+export function VikingFileManager({initialUri,initialFile,@@ -105,6 +131,7 @@ export function VikingFileManager({modTime: '',modTimestamp: null,abstract: '',+ overview: '',})}, [initialFile])@@ -125,6 +152,16 @@ export function VikingFileManager({setSelectedFile(null)}, [])+ const handleOpenDirectory = useCallback((entry: VikingFsEntry) => {+ const normalized = normalizeDirUri(entry.uri)+ setCurrentUri(normalized)+ setSelectedFile({+ ...entry,+ uri: normalized,+ isDir: true,+ })+ }, [])+const handleNavigateFromSearch = useCallback((uri: string) => {if (isDirectoryUri(uri)) {const normalized = normalizeDirUri(uri)@@ -143,6 +180,7 @@ export function VikingFileManager({modTime: '',modTimestamp: null,abstract: '',+ overview: '',})}}, [])@@ -257,65 +295,113 @@ export function VikingFileManager({return crumbs}, [currentUri])- const showTree = currentUri !== 'viking://' || selectedFile !== null- const showPreview = selectedFile !== null+ const showPreview = selectedFile !== null || currentUri === 'viking://'- const [treeWidth, setTreeWidth] = useState(280)+ const layoutRef = useRef<HTMLDivElement>(null)+ const [treeWidth, setTreeWidth] = useState(() =>+ readStoredNumber(TREE_WIDTH_STORAGE_KEY, 450, 180, 640),+ )+ const [treeHeight, setTreeHeight] = useState(() =>+ readStoredNumber(TREE_HEIGHT_STORAGE_KEY, 46, 34, 72),+ )+ const [isResizingTree, setResizingTree] = useState(false)const dragging = useRef(false)const treeWidthRef = useRef(treeWidth)+ const treeHeightRef = useRef(treeHeight)treeWidthRef.current = treeWidth+ treeHeightRef.current = treeHeight++ const treePaneStyle = useMemo(+ () =>+ ({+ '--resource-tree-height': `${treeHeight}%`,+ '--resource-tree-width': `${treeWidth}px`,+ }) as CSSProperties,+ [treeHeight, treeWidth],+ )- const handleResizeStart = useCallback((e: React.MouseEvent) => {- e.preventDefault()- dragging.current = true- const startX = e.clientX- const startWidth = treeWidthRef.current-- const onMove = (ev: MouseEvent) => {- const newWidth = Math.min(- Math.max(startWidth + ev.clientX - startX, 160),- 600,- )- setTreeWidth(newWidth)- }- const onUp = () => {- dragging.current = false- document.removeEventListener('mousemove', onMove)- document.removeEventListener('mouseup', onUp)+ const handleResizeStart = useCallback(+ (event: ReactPointerEvent<HTMLDivElement>) => {+ event.preventDefault()+ event.currentTarget.setPointerCapture(event.pointerId)+ dragging.current = true+ setResizingTree(true)++ const isDesktop = window.matchMedia('(min-width: 768px)').matches+ const startX = event.clientX+ const startY = event.clientY+ const startWidth = treeWidthRef.current+ const startHeight = treeHeightRef.current+ const layoutRect = layoutRef.current?.getBoundingClientRect()++ const onMove = (moveEvent: PointerEvent) => {+ if (isDesktop) {+ const nextWidth = clampNumber(+ startWidth + moveEvent.clientX - startX,+ 180,+ 640,+ )+ setTreeWidth(nextWidth)+ window.localStorage.setItem(TREE_WIDTH_STORAGE_KEY, String(nextWidth))+ return+ }++ const rect = layoutRef.current?.getBoundingClientRect() ?? layoutRect+ if (!rect) {+ const fallbackHeight = clampNumber(+ startHeight ++ ((moveEvent.clientY - startY) / Math.max(1, window.innerHeight)) *+ 100,+ 34,+ 72,+ )+ setTreeHeight(fallbackHeight)+ window.localStorage.setItem(+ TREE_HEIGHT_STORAGE_KEY,+ String(fallbackHeight),+ )+ return+ }++ const y = moveEvent.clientY - rect.top+ const nextHeight = clampNumber(+ (y / Math.max(1, rect.height)) * 100,+ 34,+ 72,+ )+ setTreeHeight(nextHeight)+ window.localStorage.setItem(TREE_HEIGHT_STORAGE_KEY, String(nextHeight))+ }++ const onUp = () => {+ dragging.current = false+ setResizingTree(false)+ document.removeEventListener('pointermove', onMove)+ document.removeEventListener('pointerup', onUp)+ document.removeEventListener('pointercancel', onUp)+ document.body.style.cursor = ''+ document.body.style.userSelect = ''+ }++ document.body.style.cursor = isDesktop ? 'col-resize' : 'row-resize'+ document.body.style.userSelect = 'none'+ document.addEventListener('pointermove', onMove)+ document.addEventListener('pointerup', onUp)+ document.addEventListener('pointercancel', onUp)+ },+ [],+ )++ useEffect(() => {+ return () => {+ if (!dragging.current) returndocument.body.style.cursor = ''document.body.style.userSelect = ''}- document.body.style.cursor = 'col-resize'- document.body.style.userSelect = 'none'- document.addEventListener('mousemove', onMove)- document.addEventListener('mouseup', onUp)}, [])const toolbar = (<div className="flex h-10 items-center gap-1 border-b px-3">- {!showTree && (- <>- <Button- variant="ghost"- size="icon"- className="size-7"- title={t('toolbar.refresh')}- onClick={() => void handleRefresh()}- >- <RefreshCcw className="size-4" />- </Button>- <Button- variant="secondary"- size="icon"- className="h-8 w-fit px-2"- title={t('toolbar.search')}- onClick={() => setPaletteOpen(true)}- >- <Search className="size-4" />- </Button>- <div className="mx-1 h-4 w-px bg-border" />- </>- )}<nav className="flex items-center gap-0.5 overflow-hidden text-sm text-muted-foreground">{breadcrumbs.map((crumb, i) => (<span key={crumb.uri} className="flex shrink-0 items-center gap-0.5">@@ -330,104 +416,81 @@ export function VikingFileManager({</span>))}</nav>- {!showTree ? (- <div className="ml-auto flex items-center gap-2">- <Button- type="button"- size="sm"- variant="secondary"- className="h-8"- onClick={() => setTaskDialogOpen(true)}- >- {t('toolbar.processingTasks')}- </Button>- <Button- type="button"- size="sm"- variant="secondary"- className="h-8 gap-1.5"- onClick={() => setUploadDialogOpen(true)}- >- <Upload className="size-4" />- {t('toolbar.upload')}- </Button>- </div>- ) : null}</div>)return (- <div className="-mx-4 -mt-6 -mb-4 flex h-[calc(100vh-3.5rem)] flex-col md:-mx-6">- <div className="flex min-h-0 flex-1">- {showTree && (- <>- <section- className="flex min-h-0 flex-col bg-muted/30"- style={{ width: treeWidth, minWidth: treeWidth }}+ <div className="web-studio-resource-fs -mx-4 -mt-6 -mb-4 flex h-[calc(100vh-3.5rem)] flex-col md:-mx-6">+ <div ref={layoutRef} className="flex min-h-0 flex-1 flex-col md:flex-row">+ <section+ className="flex h-[var(--resource-tree-height)] min-h-[190px] min-w-0 flex-col bg-muted/30 md:h-auto md:min-h-0 md:w-[var(--resource-tree-width)] md:min-w-[var(--resource-tree-width)]"+ style={treePaneStyle}+ >+ <div className="flex h-10 items-center gap-1 overflow-hidden border-b px-2">+ <Button+ variant="ghost"+ size="icon"+ className="size-7"+ title={t('toolbar.refresh')}+ onClick={() => void handleRefresh()}>- <div className="flex h-10 items-center gap-1 overflow-hidden border-b px-2">- <Button- variant="ghost"- size="icon"- className="size-7"- title={t('toolbar.refresh')}- onClick={() => void handleRefresh()}- >- <RefreshCcw className="size-4" />- </Button>- <div className="ml-auto flex w-fit items-center gap-1.5">- <Button- type="button"- size="sm"- variant="secondary"- className="h-8"- onClick={() => setTaskDialogOpen(true)}- >- {t('toolbar.processingTasks')}- </Button>- <Button- type="button"- size="sm"- variant="secondary"- className="h-8 gap-1.5"- onClick={() => setUploadDialogOpen(true)}- >- <Upload className="size-4" />- {t('toolbar.upload')}- </Button>- <Button- variant="secondary"- size="icon"- className="h-8 w-fit px-2"- title={t('toolbar.search')}- onClick={() => setPaletteOpen(true)}- >- <Search className="size-4" />- </Button>- </div>- </div>- <div className="min-h-0 flex-1">- <FileTree- currentUri={currentUri}- selectedFileUri={selectedFile?.uri ?? null}- expandedKeys={expandedKeys}- onExpandedKeysChange={setExpandedKeys}- onSelectDirectory={updateUri}- onSelectFile={setSelectedFile}- />- </div>- </section>- <div- className="w-1 shrink-0 cursor-col-resize bg-transparent transition-colors hover:bg-primary/20 active:bg-primary/30"- onMouseDown={handleResizeStart}+ <RefreshCcw className="size-4" />+ </Button>+ <div className="ml-auto flex w-fit items-center gap-1.5">+ <Button+ type="button"+ size="sm"+ variant="secondary"+ className="h-8"+ onClick={() => setTaskDialogOpen(true)}+ >+ {t('toolbar.processingTasks')}+ </Button>+ <Button+ type="button"+ size="sm"+ variant="secondary"+ className="h-8 gap-1.5"+ onClick={() => setUploadDialogOpen(true)}+ >+ <Upload className="size-4" />+ {t('toolbar.upload')}+ </Button>+ <Button+ variant="secondary"+ size="icon"+ className="h-8 w-fit px-2"+ title={t('toolbar.search')}+ onClick={() => setPaletteOpen(true)}+ >+ <Search className="size-4" />+ </Button>+ </div>+ </div>+ <div className="min-h-0 flex-1">+ <FileTree+ currentUri={currentUri}+ selectedFileUri={selectedFile?.uri ?? null}+ expandedKeys={expandedKeys}+ onExpandedKeysChange={setExpandedKeys}+ onSelectDirectory={handleOpenDirectory}+ onSelectFile={setSelectedFile}/>- </>- )}+ </div>+ </section>+ <div+ role="separator"+ data-dragging={isResizingTree}+ className="group flex h-2 w-full shrink-0 cursor-row-resize touch-none items-center justify-center bg-transparent transition-colors hover:bg-primary/10 active:bg-primary/20 data-[dragging=true]:bg-primary/20 md:h-auto md:w-1 md:cursor-col-resize"+ onPointerDown={handleResizeStart}+ >+ <span className="h-0.5 w-12 rounded-full bg-border transition-colors group-hover:bg-primary/50 md:h-8 md:w-0.5" />+ </div>{showPreview ? (<section className="relative flex min-h-0 min-w-0 flex-1 flex-col">{toolbar}- <div className="mx-auto min-h-0 w-full max-w-5xl flex-1">+ <div className="min-h-0 w-full flex-1"><FilePreviewfile={selectedFile}onClose={() => setSelectedFile(null)}@@ -459,7 +522,7 @@ export function VikingFileManager({<FileListentries={entries}selectedFileUri={null}- onOpenDirectory={updateUri}+ onOpenDirectory={handleOpenDirectory}onOpenFile={(file) => setSelectedFile(file)}/>)}diff --git a/web-studio/src/routes/resources/-lib/api.ts b/web-studio/src/routes/resources/-lib/api.tsindex 78baa5094..56cd90cb9 100644--- a/web-studio/src/routes/resources/-lib/api.ts+++ b/web-studio/src/routes/resources/-lib/api.ts@@ -1,6 +1,8 @@import { fetchFind, fetchFindAllTypes, fetchSearch } from '#/lib/retrieval'import {getContentRead,+ getContentAbstract,+ getContentOverview,getFsLs,getFsStat,getFsTree,@@ -139,6 +141,22 @@ export async function fetchFileContent(}}+export async function fetchDirectoryLevelContent(+ uri: string,+ level: 'abstract' | 'overview',+): Promise<string> {+ try {+ const request =+ level === 'abstract'+ ? getContentAbstract({ query: { uri: normalizeDirUri(uri) } })+ : getContentOverview({ query: { uri: normalizeDirUri(uri) } })+ const result = await getOvResult<unknown>(request)+ return normalizeReadContent(result)+ } catch (error) {+ throw toVikingApiError(error)+ }+}+export async function fetchFsStat(uri: string): Promise<VikingFsEntry> {try {const result = await getOvResult<FSStatResult>(@@ -160,6 +178,7 @@ export async function fetchFsStat(uri: string): Promise<VikingFsEntry> {modTime: formatModTime(rawModTime),modTimestamp: null,abstract: String(data.abstract ?? ''),+ overview: String(data.overview ?? ''),}} catch {return {@@ -171,6 +190,7 @@ export async function fetchFsStat(uri: string): Promise<VikingFsEntry> {modTime: '',modTimestamp: null,abstract: '',+ overview: '',}}}diff --git a/web-studio/src/routes/resources/-lib/normalize.ts b/web-studio/src/routes/resources/-lib/normalize.tsindex 9093a8acd..8fa0ec73b 100644--- a/web-studio/src/routes/resources/-lib/normalize.ts+++ b/web-studio/src/routes/resources/-lib/normalize.ts@@ -46,6 +46,7 @@ const IMAGE_EXTS = ['avif',]const MARKDOWN_EXTS = ['md', 'markdown', 'mdx']+const JSONL_EXTS = ['jsonl', 'ndjson']const CODE_EXTS = ['js','ts',@@ -104,6 +105,12 @@ const BINARY_EXTS = ['bin',]const TEXT_FILES = ['readme', 'license', 'dockerfile', 'makefile']+const HIDDEN_SUMMARY_FILENAMES = new Set([+ '.abstract',+ '.abstract.md',+ '.overview',+ '.overview.md',+])function pickFirstNonEmpty(values: Array<unknown>): unknown {for (const value of values) {@@ -199,12 +206,19 @@ export function detectFileType(uri: string): VikingFileType {const name = fileNameFromUri(uri).toLowerCase()const ext = name.includes('.') ? name.split('.').pop() || '' : ''+ if (uri.endsWith('/')) {+ return 'directory'+ }+if (IMAGE_EXTS.includes(ext)) {return 'image'}if (MARKDOWN_EXTS.includes(ext)) {return 'markdown'}+ if (JSONL_EXTS.includes(ext)) {+ return 'jsonl'+ }if (CODE_EXTS.includes(ext)) {return 'code'}@@ -268,6 +282,7 @@ export function normalizeFsEntry(modTime: '',modTimestamp: null,abstract: '',+ overview: '',}}@@ -326,6 +341,7 @@ export function normalizeFsEntry(abstract: String(pickFirstNonEmpty([item.abstract, item.summary, item.description]),),+ overview: String(pickFirstNonEmpty([item.overview, item.l1, item.L1])),}}@@ -339,9 +355,14 @@ export function normalizeFsEntry(modTime: '',modTimestamp: null,abstract: '',+ overview: '',}}+function isHiddenSummaryEntry(entry: VikingFsEntry): boolean {+ return !entry.isDir && HIDDEN_SUMMARY_FILENAMES.has(entry.name)+}+export function normalizeFsEntries(result: unknown,currentUri: string,@@ -349,7 +370,9 @@ export function normalizeFsEntries(const normalizedCurrentUri = normalizeDirUri(currentUri)if (Array.isArray(result)) {- return result.map((item) => normalizeFsEntry(item, normalizedCurrentUri))+ return result+ .map((item) => normalizeFsEntry(item, normalizedCurrentUri))+ .filter((entry) => !isHiddenSummaryEntry(entry))}if (isRecord(result)) {@@ -362,9 +385,9 @@ export function normalizeFsEntries(]for (const bucket of buckets) {if (Array.isArray(bucket)) {- return bucket.map((item) =>- normalizeFsEntry(item, normalizedCurrentUri),- )+ return bucket+ .map((item) => normalizeFsEntry(item, normalizedCurrentUri))+ .filter((entry) => !isHiddenSummaryEntry(entry))}}}@@ -426,5 +449,9 @@ export function normalizeReadContent(result: unknown): string {}}+ if (result === undefined) {+ return ''+ }+return JSON.stringify(result, null, 2)}diff --git a/web-studio/src/routes/resources/-types/viking-fm.ts b/web-studio/src/routes/resources/-types/viking-fm.tsindex bfd36e5b6..185dd2f48 100644--- a/web-studio/src/routes/resources/-types/viking-fm.ts+++ b/web-studio/src/routes/resources/-types/viking-fm.ts@@ -1,4 +1,11 @@-export type VikingFileType = 'image' | 'markdown' | 'code' | 'text' | 'binary'+export type VikingFileType =+ | 'directory'+ | 'image'+ | 'markdown'+ | 'jsonl'+ | 'code'+ | 'text'+ | 'binary'export interface VikingFsEntry {uri: string@@ -9,6 +16,7 @@ export interface VikingFsEntry {modTime: stringmodTimestamp: number | nullabstract: string+ overview?: string}export interface VikingListQueryOptions {diff --git a/web-studio/src/routes/sessions/-components/message-list.tsx b/web-studio/src/routes/sessions/-components/message-list.tsxindex 129770340..e71a17766 100644--- a/web-studio/src/routes/sessions/-components/message-list.tsx+++ b/web-studio/src/routes/sessions/-components/message-list.tsx@@ -7,7 +7,7 @@ import type { StreamToolCall } from '#/lib/sessions/types/chat'import type { Message } from '#/lib/sessions/types/message'import { MarkdownContent, ReasoningBlock, ToolCallBlock } from './message-parts'-const OPENVIKING_ICON_SRC = resolvePublicAsset('openviking-icon.png')+const OPENVIKING_ICON_SRC = resolvePublicAsset('favicon-32.png')// ---------------------------------------------------------------------------// CopyButtondiff --git a/web-studio/src/styles.css b/web-studio/src/styles.cssindex 3c7cd67bf..5bc077c3e 100644--- a/web-studio/src/styles.css+++ b/web-studio/src/styles.css@@ -160,6 +160,31 @@height: 100%;overflow: hidden;}++ @media (max-width: 767px) {+ input,+ select,+ textarea {+ font-size: 1rem;+ line-height: 1.5rem;+ }+ }+}++@media (max-width: 767px) {+ .web-studio-resource-fs :where(.text-xs, .text-sm, .text-\[10px\], .text-\[11px\]) {+ font-size: 1rem;+ line-height: 1.5rem;+ }++ .web-studio-resource-fs :where(.prose-sm) {+ font-size: 1rem;+ line-height: 1.75;+ }++ .web-studio-resource-fs :where(pre, code, table, th, td) {+ font-size: 1rem;+ }}/* ---- FindPalette animations ---- */