Skip to content

Self-evolving Context Database for AI Agents. Unify Agent Memory, Knowledge RAG and Skills.

feat(studio): improve filesystem management and Markdown previews (#6413)

leowldee07304d974d
diff --git a/web-studio/package-lock.json b/web-studio/package-lock.json
index 98c9e829b..2e842d1d3 100644
--- a/web-studio/package-lock.json
+++ b/web-studio/package-lock.json
@@ -43,6 +43,7 @@
"axios": "^1.14.0",
"class-variance-authority": "^0.7.1",
"clsx": "^2.1.1",
+ "diff": "^8.0.2",
"file-type": "^22.0.1",
"gsap": "^3.14.2",
"highlight.js": "^11.11.1",
diff --git a/web-studio/package.json b/web-studio/package.json
index 02d3e076b..c44499db5 100644
--- a/web-studio/package.json
+++ b/web-studio/package.json
@@ -55,6 +55,7 @@
"axios": "^1.14.0",
"class-variance-authority": "^0.7.1",
"clsx": "^2.1.1",
+ "diff": "^8.0.2",
"file-type": "^22.0.1",
"gsap": "^3.14.2",
"highlight.js": "^11.11.1",
diff --git a/web-studio/src/i18n/locales/en.ts b/web-studio/src/i18n/locales/en.ts
index 91e11611a..a87a4d8ee 100644
--- a/web-studio/src/i18n/locales/en.ts
+++ b/web-studio/src/i18n/locales/en.ts
@@ -8,11 +8,13 @@ import resources from './en/resources'
import activity from './en/activity'
import memoryTemplates from './en/memory-templates'
import gateway from './en/gateway'
+import dataManagement from './en/data-management'
const en = {
studio,
onboarding,
gateway,
+ dataManagement,
compile,
vikingbot,
...workspace,
diff --git a/web-studio/src/i18n/locales/en/data-management.ts b/web-studio/src/i18n/locales/en/data-management.ts
new file mode 100644
index 000000000..9e9d9a3f8
--- /dev/null
+++ b/web-studio/src/i18n/locales/en/data-management.ts
@@ -0,0 +1,47 @@
+const dataManagement = {
+ historyTitle: 'Version history',
+ transferTitle: 'OVPack import and export',
+ transferShortLabel: 'OVPack',
+ exportTab: 'Export',
+ importTab: 'Import',
+ message: 'Describe this snapshot',
+ saveSnapshot: 'Save snapshot',
+ snapshotSaved: 'Snapshot saved',
+ snapshotScope:
+ 'Only the selected path is included. Excluded files, permissions, and vector indexes are not versioned.',
+ loading: 'Loading history...',
+ noSnapshots: 'No snapshots for this path yet.',
+ viewDiff: 'View diff',
+ diffComparison: 'Version comparison',
+ previousVersion: 'Base version',
+ selectedVersion: 'Target version',
+ currentContent: 'Current content (including unsnapshotted edits)',
+ invalidSnapshotContent: 'Could not read snapshot content.',
+ versionMissingFile: 'This version does not contain this file',
+ emptyVersion: 'Empty file (compare with first snapshot)',
+ comparingVersions: 'Comparing versions...',
+ selectDifferentVersions: 'Choose two different versions.',
+ diffSection: 'Change section {{number}}',
+ noChanges: 'No changes',
+ invalidExport: 'The server returned an invalid OVPack export.',
+ missingUploadId: 'The server did not return an upload ID.',
+ exportTitle: 'Export this directory',
+ exportDescription:
+ 'Download an OVPack file. Vectors are omitted so it can be imported across environments.',
+ exportAction: 'Download OVPack',
+ exported: 'OVPack downloaded',
+ importTitle: 'Import into this directory',
+ importDescription: 'Choose an OVPack file and how to handle existing files.',
+ chooseFile: 'Choose OVPack file',
+ changeFile: 'Click to choose another file',
+ supportedFileType: 'Accepts .ovpack files',
+ conflict: 'On conflict',
+ conflictFail: 'Stop on conflict',
+ conflictSkip: 'Skip existing files',
+ conflictOverwrite: 'Overwrite existing files',
+ importAction: 'Import OVPack',
+ importing: 'Importing OVPack...',
+ imported: 'OVPack imported',
+} as const
+
+export default dataManagement
diff --git a/web-studio/src/i18n/locales/zh-CN.ts b/web-studio/src/i18n/locales/zh-CN.ts
index b39c4254b..c4f89b474 100644
--- a/web-studio/src/i18n/locales/zh-CN.ts
+++ b/web-studio/src/i18n/locales/zh-CN.ts
@@ -8,11 +8,13 @@ import workspace from './zh-CN/workspace'
import resources from './zh-CN/resources'
import activity from './zh-CN/activity'
import memoryTemplates from './zh-CN/memory-templates'
+import dataManagement from './zh-CN/data-management'
const zhCN = {
studio,
onboarding,
gateway,
+ dataManagement,
compile,
vikingbot,
...workspace,
diff --git a/web-studio/src/i18n/locales/zh-CN/data-management.ts b/web-studio/src/i18n/locales/zh-CN/data-management.ts
new file mode 100644
index 000000000..5e473432d
--- /dev/null
+++ b/web-studio/src/i18n/locales/zh-CN/data-management.ts
@@ -0,0 +1,45 @@
+const dataManagement = {
+ historyTitle: '历史版本',
+ transferTitle: 'OVPack 导入与导出',
+ transferShortLabel: 'OVPack',
+ exportTab: '导出',
+ importTab: '导入',
+ message: '描述这次快照',
+ saveSnapshot: '保存快照',
+ snapshotSaved: '快照已保存',
+ snapshotScope: '仅包含当前路径。被排除的文件、权限和向量索引不纳入版本管理。',
+ loading: '正在加载历史版本…',
+ noSnapshots: '当前路径还没有快照。',
+ viewDiff: '查看差异',
+ diffComparison: '版本对比',
+ previousVersion: '基准版本',
+ selectedVersion: '目标版本',
+ currentContent: '当前内容(含未保存到快照的修改)',
+ invalidSnapshotContent: '快照内容读取失败。',
+ versionMissingFile: '此版本不包含该文件',
+ emptyVersion: '空文件(与首次快照对比)',
+ comparingVersions: '正在比较版本…',
+ selectDifferentVersions: '请选择两个不同的版本。',
+ diffSection: '变更区块 {{number}}',
+ noChanges: '没有变化',
+ invalidExport: '服务端返回了无效的 OVPack 导出文件。',
+ missingUploadId: '服务端没有返回上传 ID。',
+ exportTitle: '导出此目录',
+ exportDescription: '下载 OVPack 文件。默认不包含向量,方便跨环境导入。',
+ exportAction: '下载 OVPack',
+ exported: 'OVPack 已下载',
+ importTitle: '导入到此目录',
+ importDescription: '选择 OVPack 文件,并设置遇到已有文件时的处理方式。',
+ chooseFile: '选择 OVPack 文件',
+ changeFile: '点击更换文件',
+ supportedFileType: '支持 .ovpack 文件',
+ conflict: '遇到冲突',
+ conflictFail: '停止导入',
+ conflictSkip: '跳过已有文件',
+ conflictOverwrite: '覆盖已有文件',
+ importAction: '导入 OVPack',
+ importing: '正在导入 OVPack…',
+ imported: 'OVPack 已导入',
+} as const
+
+export default dataManagement
diff --git a/web-studio/src/routes/filesystem/-components/data-management-dialog.test.tsx b/web-studio/src/routes/filesystem/-components/data-management-dialog.test.tsx
new file mode 100644
index 000000000..d4236bf36
--- /dev/null
+++ b/web-studio/src/routes/filesystem/-components/data-management-dialog.test.tsx
@@ -0,0 +1,143 @@
+// @vitest-environment jsdom
+
+import { cleanup, render, screen, waitFor } from '@testing-library/react'
+import userEvent from '@testing-library/user-event'
+import { toast } from 'sonner'
+import { afterEach, expect, it, vi } from 'vitest'
+
+import { DataManagementDialog } from './data-management-dialog'
+import { importOvpack } from '../-lib/data-management'
+
+vi.mock('react-i18next', () => ({
+ useTranslation: () => ({ t: (key: string) => key }),
+}))
+
+vi.mock('sonner', () => ({
+ toast: { success: vi.fn() },
+}))
+
+vi.mock('../-lib/data-management', () => ({
+ createDataManagementClient: () => ({ client: {} }),
+ exportOvpack: vi.fn(),
+ importOvpack: vi.fn(),
+ listSnapshots: vi.fn(),
+}))
+
+afterEach(cleanup)
+
+it('shows a loading button, then closes and refreshes after a successful import', async () => {
+ let completeImport!: (value: { uri: string }) => void
+ vi.mocked(importOvpack).mockReturnValueOnce(
+ new Promise((resolve) => {
+ completeImport = resolve
+ }),
+ )
+ const user = userEvent.setup()
+ const onClose = vi.fn()
+ const onChanged = vi.fn()
+ render(
+ <DataManagementDialog
+ mode="transfer"
+ uri="viking://resources/project/"
+ isDirectory
+ onClose={onClose}
+ onCompare={vi.fn()}
+ onChanged={onChanged}
+ />,
+ )
+
+ await user.click(screen.getByRole('tab', { name: 'importTab' }))
+ await user.upload(
+ screen.getByLabelText('chooseFile'),
+ new File(['sample'], 'project.ovpack'),
+ )
+ await user.click(screen.getByRole('button', { name: 'importAction' }))
+
+ expect(onClose).not.toHaveBeenCalled()
+ expect(onChanged).not.toHaveBeenCalled()
+ expect(screen.getByRole('button', { name: 'importing' })).toHaveProperty(
+ 'disabled',
+ true,
+ )
+
+ completeImport({ uri: 'viking://resources/project/' })
+ await waitFor(() => expect(onClose).toHaveBeenCalledOnce())
+ await waitFor(() => expect(onChanged).toHaveBeenCalledOnce())
+ expect(toast.success).toHaveBeenCalledWith('imported')
+})
+
+it('keeps the import tab open with the error and does not refresh on failure', async () => {
+ vi.mocked(importOvpack).mockRejectedValueOnce(new Error('Import failed'))
+ const user = userEvent.setup()
+ const onClose = vi.fn()
+ const onChanged = vi.fn()
+ render(
+ <DataManagementDialog
+ mode="transfer"
+ uri="viking://resources/project/"
+ isDirectory
+ onClose={onClose}
+ onCompare={vi.fn()}
+ onChanged={onChanged}
+ />,
+ )
+
+ await user.click(screen.getByRole('tab', { name: 'importTab' }))
+ await user.upload(
+ screen.getByLabelText('chooseFile'),
+ new File(['sample'], 'project.ovpack'),
+ )
+ await user.click(screen.getByRole('button', { name: 'importAction' }))
+
+ expect(await screen.findByRole('alert')).toHaveProperty(
+ 'textContent',
+ 'Import failed',
+ )
+ expect(
+ screen
+ .getByRole('tab', { name: 'importTab' })
+ .getAttribute('aria-selected'),
+ ).toBe('true')
+ expect(onClose).not.toHaveBeenCalled()
+ expect(onChanged).not.toHaveBeenCalled()
+ expect(screen.getByRole('button', { name: 'importAction' })).toHaveProperty(
+ 'disabled',
+ false,
+ )
+})
+
+it('keeps the selected OVPack file while switching between import and export', async () => {
+ const user = userEvent.setup()
+ render(
+ <DataManagementDialog
+ mode="transfer"
+ uri="viking://resources/project/"
+ isDirectory
+ onClose={vi.fn()}
+ onCompare={vi.fn()}
+ onChanged={vi.fn()}
+ />,
+ )
+
+ expect(screen.getByRole('button', { name: 'exportAction' })).toBeTruthy()
+ await user.click(screen.getByRole('tab', { name: 'importTab' }))
+ const importButton = screen.getByRole('button', { name: 'importAction' })
+ expect(importButton.disabled).toBe(true)
+ expect(screen.getByText('chooseFile')).toBeTruthy()
+
+ await user.upload(
+ screen.getByLabelText('chooseFile'),
+ new File(['sample'], 'project.ovpack', { type: 'application/zip' }),
+ )
+ expect(importButton.disabled).toBe(false)
+ expect(screen.getByText('project.ovpack')).toBeTruthy()
+ expect(screen.getByText('changeFile')).toBeTruthy()
+
+ await user.click(screen.getByRole('tab', { name: 'exportTab' }))
+ await user.click(screen.getByRole('tab', { name: 'importTab' }))
+ expect(importButton.disabled).toBe(false)
+ expect(screen.getByLabelText('chooseFile')).toHaveProperty(
+ 'files',
+ expect.objectContaining({ length: 1 }),
+ )
+})
diff --git a/web-studio/src/routes/filesystem/-components/data-management-dialog.tsx b/web-studio/src/routes/filesystem/-components/data-management-dialog.tsx
new file mode 100644
index 000000000..df7ac9082
--- /dev/null
+++ b/web-studio/src/routes/filesystem/-components/data-management-dialog.tsx
@@ -0,0 +1,339 @@
+import { useEffect, useMemo, useRef, useState } from 'react'
+import { useTranslation } from 'react-i18next'
+import { toast } from 'sonner'
+import { Loader2Icon, UploadIcon } from 'lucide-react'
+
+import { Button } from '#/components/ui/button'
+import {
+ Dialog,
+ DialogContent,
+ DialogDescription,
+ DialogHeader,
+ DialogTitle,
+} from '#/components/ui/dialog'
+import {
+ Select,
+ SelectContent,
+ SelectItem,
+ SelectTrigger,
+ SelectValue,
+} from '#/components/ui/select'
+import { Tabs, TabsContent, TabsList, TabsTrigger } from '#/components/ui/tabs'
+import { formatDateTime } from '#/i18n/format'
+
+import {
+ commitSnapshot,
+ createDataManagementClient,
+ exportOvpack,
+ importOvpack,
+ listSnapshots,
+} from '../-lib/data-management'
+import type { SnapshotCommit } from '../-lib/data-management'
+
+interface Props {
+ mode: 'history' | 'transfer'
+ onClose: () => void
+ onCompare: () => void
+ onChanged: () => void
+ uri: string
+ isDirectory: boolean
+}
+
+function errorMessage(error: unknown): string {
+ return error instanceof Error ? error.message : String(error)
+}
+
+function downloadBlob(blob: Blob, uri: string): void {
+ const name = uri.replace(/\/$/, '').split('/').at(-1) || 'openviking'
+ const safeName = name.replace(/[^\w.-]+/g, '_')
+ const url = URL.createObjectURL(blob)
+ const link = document.createElement('a')
+ link.href = url
+ link.download = `${safeName}.ovpack`
+ document.body.append(link)
+ link.click()
+ link.remove()
+ window.setTimeout(() => URL.revokeObjectURL(url), 60_000)
+}
+
+export function DataManagementDialog({
+ mode,
+ onClose,
+ onCompare,
+ onChanged,
+ uri,
+ isDirectory,
+}: Props) {
+ const { t } = useTranslation('dataManagement')
+ const source = useMemo(createDataManagementClient, [])
+ const controller = useRef(new AbortController())
+ const [busy, setBusy] = useState(false)
+ const [error, setError] = useState('')
+ const [commits, setCommits] = useState<SnapshotCommit[] | null>(null)
+ const [message, setMessage] = useState('')
+ const [file, setFile] = useState<File | null>(null)
+ const [transferTab, setTransferTab] = useState('export')
+ const [conflict, setConflict] = useState<'fail' | 'skip' | 'overwrite'>(
+ 'fail',
+ )
+
+ useEffect(() => {
+ const signal = controller.current.signal
+ if (mode === 'history') {
+ void listSnapshots(source, uri, signal)
+ .then((items) => {
+ if (!signal.aborted) setCommits(items)
+ })
+ .catch((cause) => {
+ if (!signal.aborted) setError(errorMessage(cause))
+ })
+ }
+ return () => controller.current.abort()
+ }, [mode, source, uri])
+
+ async function run(action: () => Promise<void>) {
+ setBusy(true)
+ setError('')
+ try {
+ await action()
+ } catch (cause) {
+ if (!controller.current.signal.aborted) {
+ setError(errorMessage(cause))
+ }
+ } finally {
+ if (!controller.current.signal.aborted) setBusy(false)
+ }
+ }
+
+ const signal = controller.current.signal
+ return (
+ <Dialog open onOpenChange={(open) => !open && onClose()}>
+ <DialogContent className="max-h-[90dvh] min-w-0 overflow-x-hidden overflow-y-auto sm:max-w-2xl">
+ <DialogHeader>
+ <DialogTitle>
+ {t(mode === 'history' ? 'historyTitle' : 'transferTitle')}
+ </DialogTitle>
+ <DialogDescription className="break-all">{uri}</DialogDescription>
+ </DialogHeader>
+
+ {mode === 'history' ? (
+ <div className="min-w-0 space-y-5">
+ <form
+ className="flex gap-2"
+ onSubmit={(event) => {
+ event.preventDefault()
+ if (!message.trim() || busy) return
+ void run(async () => {
+ await commitSnapshot(source, uri, message.trim(), signal)
+ setCommits(await listSnapshots(source, uri, signal))
+ setMessage('')
+ onChanged()
+ toast.success(t('snapshotSaved'))
+ })
+ }}
+ >
+ <input
+ aria-label={t('message')}
+ className="min-w-0 flex-1 rounded-md border bg-background px-3 py-2 text-sm"
+ maxLength={200}
+ onChange={(event) => setMessage(event.target.value)}
+ placeholder={t('message')}
+ value={message}
+ />
+ <Button disabled={busy || !message.trim()} type="submit">
+ {t('saveSnapshot')}
+ </Button>
+ </form>
+ <div className="text-xs text-muted-foreground">
+ {t('snapshotScope')}
+ </div>
+ {commits === null ? (
+ <p>{t('loading')}</p>
+ ) : commits.length === 0 ? (
+ <p className="text-sm text-muted-foreground">
+ {t('noSnapshots')}
+ </p>
+ ) : (
+ <ul className="max-h-56 space-y-2 overflow-y-auto">
+ {commits.map((commit) => (
+ <li
+ className="flex items-center justify-between gap-2 rounded-md border p-3"
+ key={commit.oid}
+ >
+ <div className="min-w-0">
+ <p className="truncate text-sm font-medium">
+ {commit.message}
+ </p>
+ <p className="font-mono text-xs text-muted-foreground">
+ {commit.oid.slice(0, 12)}
+ {commit.author?.time_seconds
+ ? ` · ${formatDateTime(new Date(commit.author.time_seconds * 1000))}`
+ : ''}
+ </p>
+ </div>
+ </li>
+ ))}
+ </ul>
+ )}
+ {!isDirectory && commits && commits.length > 0 && (
+ <div className="flex justify-end">
+ <Button type="button" variant="outline" onClick={onCompare}>
+ {t('diffComparison')}
+ </Button>
+ </div>
+ )}
+ </div>
+ ) : (
+ <Tabs
+ value={transferTab}
+ onValueChange={(value) => {
+ if (busy) return
+ setTransferTab(value)
+ setError('')
+ }}
+ >
+ <TabsList className="w-full" aria-label={t('transferTitle')}>
+ <TabsTrigger
+ value="export"
+ disabled={busy && transferTab !== 'export'}
+ >
+ {t('exportTab')}
+ </TabsTrigger>
+ <TabsTrigger
+ value="import"
+ disabled={busy && transferTab !== 'import'}
+ >
+ {t('importTab')}
+ </TabsTrigger>
+ </TabsList>
+ <TabsContent value="export" className="min-h-52 space-y-4 pt-4">
+ <p className="text-xs text-muted-foreground">
+ {t('exportDescription')}
+ </p>
+ <Button
+ disabled={busy || !isDirectory}
+ onClick={() =>
+ void run(async () => {
+ const blob = await exportOvpack(source, uri, signal)
+ if (signal.aborted) return
+ downloadBlob(blob, uri)
+ toast.success(t('exported'))
+ })
+ }
+ >
+ {t('exportAction')}
+ </Button>
+ {error && (
+ <p
+ role="alert"
+ className="break-words text-sm text-destructive"
+ >
+ {error}
+ </p>
+ )}
+ </TabsContent>
+ <TabsContent
+ value="import"
+ keepMounted
+ className="min-h-52 space-y-4 pt-4"
+ >
+ <p className="text-xs text-muted-foreground">
+ {t('importDescription')}
+ </p>
+ <div>
+ <input
+ id="ovpack-file"
+ accept=".ovpack"
+ aria-label={t('chooseFile')}
+ className="peer sr-only"
+ disabled={busy || !isDirectory}
+ onChange={(event) => setFile(event.target.files?.[0] ?? null)}
+ type="file"
+ />
+ <label
+ htmlFor="ovpack-file"
+ className="flex min-h-28 cursor-pointer flex-col items-center justify-center gap-2 rounded-md border border-dashed border-input px-4 py-5 text-center transition-colors hover:border-foreground/50 hover:bg-muted/40 peer-focus-visible:outline-none peer-focus-visible:ring-2 peer-focus-visible:ring-ring peer-disabled:pointer-events-none peer-disabled:opacity-50"
+ >
+ <UploadIcon
+ aria-hidden="true"
+ className="size-5 text-muted-foreground"
+ />
+ <span className="max-w-full truncate text-sm font-medium">
+ {file?.name ?? t('chooseFile')}
+ </span>
+ <span className="text-xs text-muted-foreground">
+ {file ? t('changeFile') : t('supportedFileType')}
+ </span>
+ </label>
+ </div>
+ <div className="space-y-1.5 text-sm">
+ <label htmlFor="ovpack-conflict">{t('conflict')}</label>
+ <Select
+ disabled={busy}
+ items={[
+ { value: 'fail', label: t('conflictFail') },
+ { value: 'skip', label: t('conflictSkip') },
+ { value: 'overwrite', label: t('conflictOverwrite') },
+ ]}
+ onValueChange={(value) =>
+ setConflict(value as typeof conflict)
+ }
+ value={conflict}
+ >
+ <SelectTrigger
+ id="ovpack-conflict"
+ className="w-full bg-background"
+ >
+ <SelectValue />
+ </SelectTrigger>
+ <SelectContent
+ align="start"
+ className="w-[var(--anchor-width)]"
+ >
+ <SelectItem value="fail">{t('conflictFail')}</SelectItem>
+ <SelectItem value="skip">{t('conflictSkip')}</SelectItem>
+ <SelectItem value="overwrite">
+ {t('conflictOverwrite')}
+ </SelectItem>
+ </SelectContent>
+ </Select>
+ </div>
+ <Button
+ disabled={busy || !isDirectory || !file}
+ aria-busy={busy}
+ onClick={() =>
+ void run(async () => {
+ if (!file) return
+ await importOvpack(source, uri, file, conflict, signal)
+ if (signal.aborted) return
+ onClose()
+ onChanged()
+ toast.success(t('imported'))
+ })
+ }
+ >
+ {busy && (
+ <Loader2Icon aria-hidden="true" className="animate-spin" />
+ )}
+ {t(busy ? 'importing' : 'importAction')}
+ </Button>
+ {error && (
+ <p
+ role="alert"
+ className="break-words text-sm text-destructive"
+ >
+ {error}
+ </p>
+ )}
+ </TabsContent>
+ </Tabs>
+ )}
+ {mode === 'history' && error && (
+ <p role="alert" className="text-sm text-destructive">
+ {error}
+ </p>
+ )}
+ </DialogContent>
+ </Dialog>
+ )
+}
diff --git a/web-studio/src/routes/filesystem/-components/snapshot-comparison-dialog.test.tsx b/web-studio/src/routes/filesystem/-components/snapshot-comparison-dialog.test.tsx
new file mode 100644
index 000000000..2bfba8d29
--- /dev/null
+++ b/web-studio/src/routes/filesystem/-components/snapshot-comparison-dialog.test.tsx
@@ -0,0 +1,106 @@
+// @vitest-environment jsdom
+
+import { act, cleanup, render, screen, waitFor } from '@testing-library/react'
+import userEvent from '@testing-library/user-event'
+import { afterEach, expect, it, vi } from 'vitest'
+
+import { SnapshotComparisonDialog } from './snapshot-comparison-dialog'
+
+const mocks = vi.hoisted(() => ({
+ diffSnapshot: vi.fn(),
+ diffSnapshotWithCurrent: vi.fn(),
+ listSnapshots: vi.fn(),
+}))
+
+vi.mock('react-i18next', () => ({
+ useTranslation: () => ({ t: (key: string) => key }),
+}))
+
+vi.mock('../-lib/data-management', () => ({
+ createDataManagementClient: () => ({}),
+ diffSnapshot: mocks.diffSnapshot,
+ diffSnapshotWithCurrent: mocks.diffSnapshotWithCurrent,
+ listSnapshots: mocks.listSnapshots,
+}))
+
+vi.mock('./snapshot-diff-viewer', () => ({
+ SnapshotDiffViewer: ({ diff }: { diff: string }) => <div>{diff}</div>,
+}))
+
+afterEach(() => {
+ cleanup()
+ vi.clearAllMocks()
+})
+
+it('compares on selection and ignores a stale response', async () => {
+ mocks.listSnapshots.mockResolvedValue([
+ { oid: 'new', message: 'New' },
+ { oid: 'old', message: 'Old' },
+ ])
+ const pending: Array<
+ (value: {
+ diff: string
+ missingBase: boolean
+ missingTarget: boolean
+ }) => void
+ > = []
+ mocks.diffSnapshotWithCurrent.mockImplementation(
+ () => new Promise((resolve) => pending.push(resolve)),
+ )
+ mocks.diffSnapshot.mockResolvedValue({
+ diff: 'selected comparison',
+ missingBase: false,
+ missingTarget: false,
+ })
+
+ render(
+ <SnapshotComparisonDialog
+ onClose={vi.fn()}
+ uri="viking://resources/note.md"
+ />,
+ )
+ await waitFor(() =>
+ expect(mocks.diffSnapshotWithCurrent).toHaveBeenCalledTimes(1),
+ )
+ expect(mocks.diffSnapshotWithCurrent.mock.calls[0][2]).toBe('new')
+
+ const user = userEvent.setup()
+ await user.click(screen.getByRole('combobox', { name: 'selectedVersion' }))
+ await user.click(screen.getByRole('option', { name: /Old · old/ }))
+ await waitFor(() => expect(mocks.diffSnapshot).toHaveBeenCalledTimes(1))
+ expect(mocks.diffSnapshot.mock.calls[0][2]).toBe('old')
+ expect(mocks.diffSnapshot.mock.calls[0][3]).toBe('new')
+
+ expect(await screen.findByText('selected comparison')).toBeTruthy()
+ expect(screen.getByRole('dialog').className).toContain('h-[min(90dvh,760px)]')
+ await act(async () =>
+ pending[0]({
+ diff: 'stale comparison',
+ missingBase: false,
+ missingTarget: false,
+ }),
+ )
+ expect(screen.queryByText('stale comparison')).toBeNull()
+})
+
+it('shows the latest current content diff without another click', async () => {
+ mocks.listSnapshots.mockResolvedValue([{ oid: 'latest', message: 'Latest' }])
+ mocks.diffSnapshotWithCurrent.mockResolvedValue({
+ diff: 'current comparison',
+ missingBase: false,
+ missingTarget: false,
+ })
+ render(
+ <SnapshotComparisonDialog
+ onClose={vi.fn()}
+ uri="viking://resources/note.md"
+ />,
+ )
+ expect(await screen.findByText('current comparison')).toBeTruthy()
+ expect(
+ screen.getByRole('combobox', { name: 'previousVersion' }).textContent,
+ ).toContain('Latest')
+ expect(
+ screen.getByRole('combobox', { name: 'selectedVersion' }).textContent,
+ ).toContain('currentContent')
+})
diff --git a/web-studio/src/routes/filesystem/-components/snapshot-comparison-dialog.tsx b/web-studio/src/routes/filesystem/-components/snapshot-comparison-dialog.tsx
new file mode 100644
index 000000000..7913a6aee
--- /dev/null
+++ b/web-studio/src/routes/filesystem/-components/snapshot-comparison-dialog.tsx
@@ -0,0 +1,219 @@
+import { useEffect, useMemo, useRef, useState } from 'react'
+import { useTranslation } from 'react-i18next'
+
+import {
+ Dialog,
+ DialogContent,
+ DialogDescription,
+ DialogHeader,
+ DialogTitle,
+} from '#/components/ui/dialog'
+import {
+ Select,
+ SelectContent,
+ SelectItem,
+ SelectTrigger,
+ SelectValue,
+} from '#/components/ui/select'
+import { formatDateTime } from '#/i18n/format'
+
+import {
+ createDataManagementClient,
+ diffSnapshot,
+ diffSnapshotWithCurrent,
+ listSnapshots,
+} from '../-lib/data-management'
+import type {
+ SnapshotCommit,
+ SnapshotComparison,
+} from '../-lib/data-management'
+import { SnapshotDiffViewer } from './snapshot-diff-viewer'
+
+interface Props {
+ onClose: () => void
+ uri: string
+}
+
+const EMPTY_VERSION = '__empty_version__'
+
+function versionLabel(commit: SnapshotCommit): string {
+ const date = commit.author?.time_seconds
+ ? ` · ${formatDateTime(new Date(commit.author.time_seconds * 1000))}`
+ : ''
+ return `${commit.message} · ${commit.oid.slice(0, 12)}${date}`
+}
+
+export function SnapshotComparisonDialog({ onClose, uri }: Props) {
+ const { t } = useTranslation('dataManagement')
+ const source = useMemo(createDataManagementClient, [])
+ const controller = useRef(new AbortController())
+ const [commits, setCommits] = useState<SnapshotCommit[] | null>(null)
+ const [base, setBase] = useState('')
+ const [target, setTarget] = useState('')
+ const [comparison, setComparison] = useState<SnapshotComparison | null>(null)
+ const [busy, setBusy] = useState(false)
+ const [error, setError] = useState('')
+ const versionOptions = useMemo(
+ () =>
+ commits?.map((commit) => ({
+ value: commit.oid,
+ label: versionLabel(commit),
+ })) ?? [],
+ [commits],
+ )
+
+ useEffect(() => {
+ const signal = controller.current.signal
+ void listSnapshots(source, uri, signal, 500)
+ .then((items) => {
+ if (signal.aborted) return
+ setCommits(items)
+ setTarget('current')
+ setBase(items[0]?.oid ?? '')
+ })
+ .catch((cause: unknown) => {
+ if (!signal.aborted)
+ setError(cause instanceof Error ? cause.message : String(cause))
+ })
+ return () => controller.current.abort()
+ }, [source, uri])
+
+ useEffect(() => {
+ setComparison(null)
+ setError('')
+ if (!commits || !target || base === target) {
+ setBusy(false)
+ return
+ }
+
+ const request = new AbortController()
+ setBusy(true)
+ void (
+ target === 'current'
+ ? diffSnapshotWithCurrent(source, uri, base, request.signal)
+ : diffSnapshot(source, uri, target, base || undefined, request.signal)
+ )
+ .then((result) => {
+ if (!request.signal.aborted) setComparison(result)
+ })
+ .catch((cause: unknown) => {
+ if (!request.signal.aborted)
+ setError(cause instanceof Error ? cause.message : String(cause))
+ })
+ .finally(() => {
+ if (!request.signal.aborted) setBusy(false)
+ })
+
+ return () => request.abort()
+ }, [base, commits, source, target, uri])
+
+ return (
+ <Dialog open onOpenChange={(open) => !open && onClose()}>
+ <DialogContent className="flex h-[min(90dvh,760px)] min-w-0 flex-col overflow-hidden sm:max-w-5xl">
+ <DialogHeader className="shrink-0">
+ <DialogTitle>{t('diffComparison')}</DialogTitle>
+ <DialogDescription className="min-w-0 break-all">
+ {uri}
+ </DialogDescription>
+ </DialogHeader>
+
+ {commits === null && !error ? (
+ <p className="text-sm text-muted-foreground">{t('loading')}</p>
+ ) : commits?.length === 0 ? (
+ <p className="text-sm text-muted-foreground">{t('noSnapshots')}</p>
+ ) : commits ? (
+ <div className="flex min-h-0 min-w-0 flex-1 flex-col gap-4">
+ <div className="grid shrink-0 gap-3 sm:grid-cols-2">
+ <div className="min-w-0 space-y-1.5 text-sm font-medium">
+ <label htmlFor="snapshot-base-version">
+ {t('previousVersion')}
+ </label>
+ <Select
+ value={base || EMPTY_VERSION}
+ items={[
+ { value: EMPTY_VERSION, label: t('emptyVersion') },
+ ...versionOptions,
+ ]}
+ onValueChange={(value) =>
+ setBase(value === EMPTY_VERSION ? '' : value)
+ }
+ >
+ <SelectTrigger
+ id="snapshot-base-version"
+ className="w-full min-w-0 bg-background"
+ >
+ <SelectValue className="min-w-0 truncate" />
+ </SelectTrigger>
+ <SelectContent
+ align="start"
+ className="w-[var(--anchor-width)] max-w-[calc(100vw-3rem)]"
+ >
+ <SelectItem value={EMPTY_VERSION}>
+ {t('emptyVersion')}
+ </SelectItem>
+ {commits.map((commit) => (
+ <SelectItem key={commit.oid} value={commit.oid}>
+ {versionLabel(commit)}
+ </SelectItem>
+ ))}
+ </SelectContent>
+ </Select>
+ </div>
+ <div className="min-w-0 space-y-1.5 text-sm font-medium">
+ <label htmlFor="snapshot-target-version">
+ {t('selectedVersion')}
+ </label>
+ <Select
+ value={target}
+ items={[
+ { value: 'current', label: t('currentContent') },
+ ...versionOptions,
+ ]}
+ onValueChange={setTarget}
+ >
+ <SelectTrigger
+ id="snapshot-target-version"
+ className="w-full min-w-0 bg-background"
+ >
+ <SelectValue className="min-w-0 truncate" />
+ </SelectTrigger>
+ <SelectContent
+ align="start"
+ className="w-[var(--anchor-width)] max-w-[calc(100vw-3rem)]"
+ >
+ <SelectItem value="current">
+ {t('currentContent')}
+ </SelectItem>
+ {commits.map((commit) => (
+ <SelectItem key={commit.oid} value={commit.oid}>
+ {versionLabel(commit)}
+ </SelectItem>
+ ))}
+ </SelectContent>
+ </Select>
+ </div>
+ </div>
+ <div
+ className="h-5 shrink-0 text-sm text-muted-foreground"
+ aria-live="polite"
+ >
+ {busy
+ ? t('comparingVersions')
+ : base === target
+ ? t('selectDifferentVersions')
+ : null}
+ </div>
+ <div className="min-h-0 flex-1 overflow-hidden">
+ {comparison !== null && <SnapshotDiffViewer {...comparison} />}
+ </div>
+ </div>
+ ) : null}
+ {error && (
+ <p role="alert" className="text-sm text-destructive">
+ {error}
+ </p>
+ )}
+ </DialogContent>
+ </Dialog>
+ )
+}
diff --git a/web-studio/src/routes/filesystem/-components/snapshot-diff-viewer.test.tsx b/web-studio/src/routes/filesystem/-components/snapshot-diff-viewer.test.tsx
new file mode 100644
index 000000000..42f8f4b7c
--- /dev/null
+++ b/web-studio/src/routes/filesystem/-components/snapshot-diff-viewer.test.tsx
@@ -0,0 +1,24 @@
+// @vitest-environment jsdom
+
+import { cleanup, render, screen } from '@testing-library/react'
+import { afterEach, expect, it, vi } from 'vitest'
+
+import { SnapshotDiffViewer } from './snapshot-diff-viewer'
+
+vi.mock('react-i18next', () => ({
+ useTranslation: () => ({ t: (key: string) => key }),
+}))
+
+afterEach(cleanup)
+
+it('marks the missing version while retaining the added file diff', () => {
+ render(
+ <SnapshotDiffViewer
+ diff={'--- old\n+++ new\n@@ -0,0 +1 @@\n+new content\n'}
+ missingBase
+ />,
+ )
+ expect(screen.getByText('versionMissingFile')).toBeTruthy()
+ expect(screen.getByText('new content')).toBeTruthy()
+ expect(screen.getByText('+1')).toBeTruthy()
+})
diff --git a/web-studio/src/routes/filesystem/-components/snapshot-diff-viewer.tsx b/web-studio/src/routes/filesystem/-components/snapshot-diff-viewer.tsx
new file mode 100644
index 000000000..f64d1ed05
--- /dev/null
+++ b/web-studio/src/routes/filesystem/-components/snapshot-diff-viewer.tsx
@@ -0,0 +1,111 @@
+import { useMemo } from 'react'
+import { useTranslation } from 'react-i18next'
+
+import { parseSnapshotDiff } from '../-lib/snapshot-diff'
+
+interface Props {
+ diff: string
+ missingBase?: boolean
+ missingTarget?: boolean
+}
+
+export function SnapshotDiffViewer({
+ diff,
+ missingBase = false,
+ missingTarget = false,
+}: Props) {
+ const { t } = useTranslation('dataManagement')
+ const hunks = useMemo(() => parseSnapshotDiff(diff), [diff])
+ const rows = hunks.flatMap((hunk) => hunk.rows)
+ const added = rows.filter(
+ (row) => row.newText !== undefined && row.kind !== 'context',
+ ).length
+ const removed = rows.filter(
+ (row) => row.oldText !== undefined && row.kind !== 'context',
+ ).length
+
+ return (
+ <section
+ aria-label={t('diffComparison')}
+ className="flex h-full min-h-0 min-w-0 flex-col gap-3"
+ >
+ <div className="flex shrink-0 flex-wrap items-center justify-between gap-2 text-sm">
+ <h3 className="font-medium">{t('diffComparison')}</h3>
+ <div className="flex gap-3 font-mono text-xs tabular-nums">
+ <span className="text-emerald-700 dark:text-emerald-400">
+ +{added}
+ </span>
+ <span className="text-red-700 dark:text-red-400">−{removed}</span>
+ </div>
+ </div>
+ {(missingBase || missingTarget) && (
+ <div className="grid shrink-0 gap-2 text-xs md:grid-cols-2">
+ <div>
+ {missingBase && (
+ <span className="inline-block rounded border border-muted-foreground/30 bg-muted px-2 py-1 text-muted-foreground">
+ {t('versionMissingFile')}
+ </span>
+ )}
+ </div>
+ <div>
+ {missingTarget && (
+ <span className="inline-block rounded border border-muted-foreground/30 bg-muted px-2 py-1 text-muted-foreground">
+ {t('versionMissingFile')}
+ </span>
+ )}
+ </div>
+ </div>
+ )}
+ {hunks.length === 0 ? (
+ <p className="text-sm text-muted-foreground">{t('noChanges')}</p>
+ ) : (
+ <div className="min-h-0 min-w-0 flex-1 overflow-y-auto rounded-md border">
+ <div className="sticky top-0 z-10 hidden grid-cols-2 border-b bg-muted text-xs font-medium md:grid">
+ <div className="border-r px-3 py-2">{t('previousVersion')}</div>
+ <div className="px-3 py-2">{t('selectedVersion')}</div>
+ </div>
+ {hunks.map((hunk, hunkIndex) => (
+ <div key={hunkIndex}>
+ <div className="border-y bg-muted/70 px-3 py-1.5 font-mono text-xs text-muted-foreground">
+ {hunk.label || t('diffSection', { number: hunkIndex + 1 })}
+ </div>
+ {hunk.rows.map((row, rowIndex) => (
+ <div
+ className="grid min-w-0 grid-cols-1 border-b border-border/50 font-mono text-xs leading-5 last:border-b-0 md:grid-cols-2"
+ key={rowIndex}
+ >
+ <div
+ className={`flex min-w-0 border-r px-2 py-0.5 ${row.oldText === undefined ? 'hidden md:flex' : ''} ${row.kind === 'removed' || row.kind === 'changed' ? 'bg-red-500/10' : ''}`}
+ >
+ <span
+ aria-hidden="true"
+ className="w-9 shrink-0 select-none text-right text-muted-foreground"
+ >
+ {row.oldLine}
+ </span>
+ <span className="min-w-0 flex-1 whitespace-pre-wrap break-all pl-3">
+ {row.oldText}
+ </span>
+ </div>
+ <div
+ className={`flex min-w-0 px-2 py-0.5 ${row.newText === undefined ? 'hidden md:flex' : ''} ${row.kind === 'added' || row.kind === 'changed' ? 'bg-emerald-500/10' : ''}`}
+ >
+ <span
+ aria-hidden="true"
+ className="w-9 shrink-0 select-none text-right text-muted-foreground"
+ >
+ {row.newLine}
+ </span>
+ <span className="min-w-0 flex-1 whitespace-pre-wrap break-all pl-3">
+ {row.newText}
+ </span>
+ </div>
+ </div>
+ ))}
+ </div>
+ ))}
+ </div>
+ )}
+ </section>
+ )
+}
diff --git a/web-studio/src/routes/filesystem/-lib/data-management.test.ts b/web-studio/src/routes/filesystem/-lib/data-management.test.ts
new file mode 100644
index 000000000..f26d6668b
--- /dev/null
+++ b/web-studio/src/routes/filesystem/-lib/data-management.test.ts
@@ -0,0 +1,263 @@
+import { beforeEach, describe, expect, it, vi } from 'vitest'
+
+import {
+ diffSnapshot,
+ diffSnapshotWithCurrent,
+ exportOvpack,
+ importOvpack,
+ listSnapshots,
+} from './data-management'
+import type { OvClientAdapter } from '#/lib/ov-client/types'
+
+const mocks = vi.hoisted(() => ({
+ get: vi.fn(),
+ post: vi.fn(),
+ tempUpload: vi.fn(),
+ packImport: vi.fn(),
+}))
+
+vi.mock('#/lib/ov-client', () => ({
+ createOvClient: vi.fn(),
+ ovClient: { getOptions: vi.fn(), getConnection: vi.fn() },
+ normalizeOvClientError: (error: unknown) => error,
+ getOvResult: async (request: Promise<unknown>) => {
+ const response = (await request) as { data?: { result?: unknown } }
+ return response.data?.result
+ },
+ postResourcesTempUpload: mocks.tempUpload,
+ postPackImport: mocks.packImport,
+}))
+
+const uri = 'viking://resources/docs/'
+const signal = new AbortController().signal
+const source = {
+ client: { get: mocks.get, post: mocks.post },
+} as unknown as OvClientAdapter
+
+beforeEach(() => {
+ vi.clearAllMocks()
+})
+
+describe('data management API', () => {
+ it('scopes snapshot history to the selected path', async () => {
+ mocks.get.mockResolvedValue({ data: { result: [{ oid: 'one' }] } })
+
+ await expect(listSnapshots(source, uri, signal)).resolves.toEqual([
+ { oid: 'one' },
+ ])
+ expect(mocks.get).toHaveBeenCalledWith({
+ url: '/api/v1/snapshot/log',
+ query: { branch: 'main', limit: 20, paths: [uri] },
+ signal,
+ })
+ })
+
+ it('loads more history for version selection and compares chosen refs', async () => {
+ mocks.get.mockResolvedValue({ data: { result: [] } })
+ await listSnapshots(source, uri, signal, 500)
+ expect(mocks.get).toHaveBeenCalledWith({
+ url: '/api/v1/snapshot/log',
+ query: { branch: 'main', limit: 500, paths: [uri] },
+ signal,
+ })
+
+ mocks.get.mockResolvedValue({ data: { result: { diff_text: 'diff' } } })
+ await expect(
+ diffSnapshot(source, uri, 'target-oid', 'base-oid', signal),
+ ).resolves.toEqual({
+ diff: 'diff',
+ missingBase: false,
+ missingTarget: false,
+ })
+ expect(mocks.get).toHaveBeenLastCalledWith({
+ url: '/api/v1/snapshot/diff',
+ query: { path: uri, to: 'target-oid', from: 'base-oid' },
+ signal,
+ })
+ })
+
+ it('compares saved versions through show when the diff route is unavailable', async () => {
+ mocks.get
+ .mockRejectedValueOnce({ statusCode: 404, message: 'Not found' })
+ .mockResolvedValueOnce({ data: new Blob(['old\n']) })
+ .mockResolvedValueOnce({ data: new Blob(['new\n']) })
+
+ const comparison = await diffSnapshot(
+ source,
+ uri,
+ 'new-oid',
+ 'old-oid',
+ signal,
+ )
+ expect(comparison.diff).toContain('-old')
+ expect(comparison.diff).toContain('+new')
+ expect(comparison).toMatchObject({
+ missingBase: false,
+ missingTarget: false,
+ })
+ expect(mocks.get).toHaveBeenNthCalledWith(2, {
+ url: '/api/v1/snapshot/show',
+ query: { target_ref: 'old-oid', path: uri, raw: true },
+ responseType: 'blob',
+ signal,
+ })
+ expect(mocks.get).toHaveBeenNthCalledWith(3, {
+ url: '/api/v1/snapshot/show',
+ query: { target_ref: 'new-oid', path: uri, raw: true },
+ responseType: 'blob',
+ signal,
+ })
+ })
+
+ it('compares a saved snapshot with the live file content', async () => {
+ mocks.get
+ .mockResolvedValueOnce({ data: new Blob(['old\n']) })
+ .mockResolvedValueOnce({ data: { result: { content: 'new\n' } } })
+ const comparison = await diffSnapshotWithCurrent(
+ source,
+ 'viking://resources/docs/a.md',
+ 'saved-oid',
+ signal,
+ )
+ expect(comparison.diff).toContain('-old')
+ expect(comparison.diff).toContain('+new')
+ expect(comparison).toMatchObject({
+ missingBase: false,
+ missingTarget: false,
+ })
+ expect(mocks.get).toHaveBeenNthCalledWith(1, {
+ url: '/api/v1/snapshot/show',
+ query: {
+ target_ref: 'saved-oid',
+ path: 'viking://resources/docs/a.md',
+ raw: true,
+ },
+ responseType: 'blob',
+ signal,
+ })
+ })
+
+ it('marks a deleted target from the native diff response', async () => {
+ mocks.get.mockResolvedValue({
+ data: { result: { diff_text: '-removed', change_type: 'deleted' } },
+ })
+ await expect(
+ diffSnapshot(source, uri, 'deleted-oid', 'old-oid', signal),
+ ).resolves.toEqual({
+ diff: '-removed',
+ missingBase: false,
+ missingTarget: true,
+ })
+ })
+
+ it('treats a missing snapshot blob as an empty comparison side', async () => {
+ const missing = {
+ statusCode: 404,
+ code: 'NOT_FOUND',
+ details: { type: 'git_blob', resource: uri },
+ }
+ mocks.get
+ .mockRejectedValueOnce({ statusCode: 404 }) // diff route unavailable
+ .mockRejectedValueOnce(missing) // base version has no file
+ .mockResolvedValueOnce({ data: new Blob(['new\n']) })
+ .mockResolvedValueOnce({
+ data: { result: [{ oid: 'old-oid' }, { oid: 'new-oid' }] },
+ })
+ const result = await diffSnapshot(source, uri, 'new-oid', 'old-oid', signal)
+ expect(result.diff).toContain('+new')
+ expect(result).toMatchObject({ missingBase: true, missingTarget: false })
+ })
+
+ it('reads a missing-file error returned as a binary response', async () => {
+ mocks.get
+ .mockRejectedValueOnce({ statusCode: 404 })
+ .mockRejectedValueOnce({
+ statusCode: 404,
+ code: 'HTTP_ERROR',
+ responseBody: new Blob([
+ JSON.stringify({
+ error: {
+ code: 'NOT_FOUND',
+ details: { type: 'git_blob', resource: uri },
+ },
+ }),
+ ]),
+ })
+ .mockResolvedValueOnce({ data: new Blob(['new\n']) })
+ .mockResolvedValueOnce({ data: { result: [{ oid: 'old-oid' }] } })
+ const result = await diffSnapshot(source, uri, 'new-oid', 'old-oid', signal)
+ expect(result).toMatchObject({ missingBase: true, missingTarget: false })
+ })
+
+ it('does not mistake an invalid ref for a missing file', async () => {
+ const missing = {
+ statusCode: 404,
+ code: 'NOT_FOUND',
+ details: { type: 'git_blob', resource: uri },
+ }
+ mocks.get
+ .mockRejectedValueOnce({ statusCode: 404 })
+ .mockRejectedValueOnce(missing)
+ .mockResolvedValueOnce({ data: new Blob(['new\n']) })
+ .mockResolvedValueOnce({ data: { result: [{ oid: 'new-oid' }] } })
+ await expect(
+ diffSnapshot(source, uri, 'new-oid', 'invalid-oid', signal),
+ ).rejects.toBe(missing)
+ })
+
+ it('compares current content when the saved version lacks the file', async () => {
+ const fileUri = 'viking://resources/docs/a.md'
+ mocks.get
+ .mockRejectedValueOnce({
+ statusCode: 404,
+ code: 'NOT_FOUND',
+ details: { type: 'git_blob', resource: fileUri },
+ })
+ .mockResolvedValueOnce({ data: { result: { content: 'current\n' } } })
+ .mockResolvedValueOnce({ data: { result: [{ oid: 'saved-oid' }] } })
+ const result = await diffSnapshotWithCurrent(
+ source,
+ fileUri,
+ 'saved-oid',
+ signal,
+ )
+ expect(result.diff).toContain('+current')
+ expect(result).toMatchObject({ missingBase: true, missingTarget: false })
+ })
+
+ it('downloads binary OVPack and imports through the same source client', async () => {
+ const blob = new Blob(['pack'], { type: 'application/zip' })
+ mocks.post.mockResolvedValue({ data: blob })
+ await expect(exportOvpack(source, uri, signal)).resolves.toBe(blob)
+ expect(mocks.post).toHaveBeenCalledWith({
+ url: '/api/v1/pack/export',
+ body: { uri, include_vectors: false },
+ responseType: 'blob',
+ signal,
+ })
+
+ const file = new File(['pack'], 'docs.ovpack')
+ mocks.tempUpload.mockResolvedValue({
+ data: { result: { temp_file_id: 'temp-1' } },
+ })
+ mocks.packImport.mockResolvedValue({
+ data: { result: { uri: 'viking://resources/docs/' } },
+ })
+ await importOvpack(source, uri, file, 'fail', signal)
+ expect(mocks.tempUpload).toHaveBeenCalledWith({
+ client: source.client,
+ body: { file },
+ signal,
+ })
+ expect(mocks.packImport).toHaveBeenCalledWith({
+ client: source.client,
+ body: {
+ temp_file_id: 'temp-1',
+ parent: uri,
+ on_conflict: 'fail',
+ vector_mode: 'auto',
+ },
+ signal,
+ })
+ })
+})
diff --git a/web-studio/src/routes/filesystem/-lib/data-management.ts b/web-studio/src/routes/filesystem/-lib/data-management.ts
new file mode 100644
index 000000000..df93abd50
--- /dev/null
+++ b/web-studio/src/routes/filesystem/-lib/data-management.ts
@@ -0,0 +1,243 @@
+import {
+ createOvClient,
+ getOvResult,
+ normalizeOvClientError,
+ ovClient,
+ postPackImport,
+ postResourcesTempUpload,
+} from '#/lib/ov-client'
+import type { OvClientAdapter } from '#/lib/ov-client/types'
+import i18n from '#/i18n/core'
+import { getContentRead } from '#/gen/ov-client/sdk.gen'
+import { normalizeReadContent } from '#/routes/resources/-lib/normalize'
+import { createPatch } from 'diff'
+
+export interface SnapshotCommit {
+ oid: string
+ message: string
+ author?: { name?: string; time_seconds?: number }
+}
+
+export interface SnapshotComparison {
+ diff: string
+ missingBase: boolean
+ missingTarget: boolean
+}
+
+export function createDataManagementClient(): OvClientAdapter {
+ return createOvClient({
+ ...ovClient.getOptions(),
+ apiKeyStorageKey: '',
+ connection: ovClient.getConnection(),
+ })
+}
+
+export async function listSnapshots(
+ source: OvClientAdapter,
+ uri: string,
+ signal: AbortSignal,
+ limit = 20,
+): Promise<SnapshotCommit[]> {
+ try {
+ return await getOvResult<SnapshotCommit[]>(
+ source.client.get({
+ url: '/api/v1/snapshot/log',
+ query: { branch: 'main', limit, paths: [uri] },
+ signal,
+ }),
+ )
+ } catch (error) {
+ if (normalizeOvClientError(error).statusCode === 404) return []
+ throw error
+ }
+}
+
+export async function commitSnapshot(
+ source: OvClientAdapter,
+ uri: string,
+ message: string,
+ signal: AbortSignal,
+): Promise<{ result: string; commit_oid: string }> {
+ return getOvResult(
+ source.client.post({
+ url: '/api/v1/snapshot/commit',
+ body: { message, paths: [uri], branch: 'main' },
+ signal,
+ }),
+ )
+}
+
+export async function diffSnapshot(
+ source: OvClientAdapter,
+ uri: string,
+ to: string,
+ from: string | undefined,
+ signal: AbortSignal,
+): Promise<SnapshotComparison> {
+ try {
+ const result = await getOvResult<{
+ diff_text: string
+ change_type?: 'added' | 'deleted' | 'modified' | 'unchanged'
+ }>(
+ source.client.get({
+ url: '/api/v1/snapshot/diff',
+ query: { path: uri, to, ...(from ? { from } : {}) },
+ signal,
+ }),
+ )
+ return {
+ diff: result.diff_text,
+ missingBase: !from || result.change_type === 'added',
+ missingTarget: result.change_type === 'deleted',
+ }
+ } catch (error) {
+ // Hosted connections expose snapshot/show but may not route snapshot/diff.
+ if (normalizeOvClientError(error).statusCode !== 404) throw error
+ const [older, newer] = await Promise.all([
+ from
+ ? readSnapshotFile(source, uri, from, signal)
+ : Promise.resolve({ content: '', missing: true }),
+ readSnapshotFile(source, uri, to, signal),
+ ])
+ return {
+ diff: createPatch(uri, older.content, newer.content),
+ missingBase: older.missing,
+ missingTarget: newer.missing,
+ }
+ }
+}
+
+async function isMissingSnapshotBlob(
+ error: unknown,
+ uri: string,
+): Promise<boolean> {
+ const normalized = normalizeOvClientError(error)
+ if (normalized.statusCode !== 404) return false
+ let code = normalized.code
+ let details: unknown = normalized.details
+ if (normalized.responseBody instanceof Blob) {
+ try {
+ const body: unknown = JSON.parse(await normalized.responseBody.text())
+ if (body !== null && typeof body === 'object' && 'error' in body) {
+ const payload = body.error
+ if (payload !== null && typeof payload === 'object') {
+ if ('code' in payload && typeof payload.code === 'string')
+ code = payload.code
+ if ('details' in payload) details = payload.details
+ }
+ }
+ } catch {
+ return false
+ }
+ }
+ return (
+ code === 'NOT_FOUND' &&
+ details !== null &&
+ typeof details === 'object' &&
+ 'type' in details &&
+ details.type === 'git_blob' &&
+ 'resource' in details &&
+ details.resource === uri
+ )
+}
+
+async function readSnapshotFile(
+ source: OvClientAdapter,
+ uri: string,
+ ref: string,
+ signal: AbortSignal,
+): Promise<{ content: string; missing: boolean }> {
+ try {
+ const response = await source.client.get({
+ url: '/api/v1/snapshot/show',
+ query: { target_ref: ref, path: uri, raw: true },
+ responseType: 'blob',
+ signal,
+ })
+ if (!(response.data instanceof Blob))
+ throw new Error(i18n.t('dataManagement:invalidSnapshotContent'))
+ return { content: await response.data.text(), missing: false }
+ } catch (error) {
+ if (!(await isMissingSnapshotBlob(error, uri))) throw error
+ // The show endpoint maps a missing ref and a missing blob to the same
+ // git_blob error. Confirm this ref still exists before treating it as empty.
+ const commits = await listSnapshots(source, uri, signal, 500)
+ if (!commits.some((commit) => commit.oid === ref)) throw error
+ return { content: '', missing: true }
+ }
+}
+
+export async function diffSnapshotWithCurrent(
+ source: OvClientAdapter,
+ uri: string,
+ from: string,
+ signal: AbortSignal,
+): Promise<SnapshotComparison> {
+ const [savedContent, current] = await Promise.all([
+ from
+ ? readSnapshotFile(source, uri, from, signal)
+ : Promise.resolve({ content: '', missing: true }),
+ getOvResult<unknown>(
+ getContentRead({
+ client: source.client,
+ query: { uri, offset: 0, limit: -1, raw: true } as Parameters<
+ typeof getContentRead
+ >[0]['query'] & { raw: boolean },
+ signal,
+ }),
+ ),
+ ])
+ return {
+ diff: createPatch(uri, savedContent.content, normalizeReadContent(current)),
+ missingBase: savedContent.missing,
+ missingTarget: false,
+ }
+}
+
+export async function exportOvpack(
+ source: OvClientAdapter,
+ uri: string,
+ signal: AbortSignal,
+): Promise<Blob> {
+ const response = await source.client.post({
+ url: '/api/v1/pack/export',
+ body: { uri, include_vectors: false },
+ responseType: 'blob',
+ signal,
+ })
+ const data: unknown = response.data
+ if (!(data instanceof Blob) || data.size === 0) {
+ throw new Error(i18n.t('dataManagement:invalidExport'))
+ }
+ return data
+}
+
+export async function importOvpack(
+ source: OvClientAdapter,
+ parent: string,
+ file: File,
+ onConflict: 'fail' | 'skip' | 'overwrite',
+ signal: AbortSignal,
+): Promise<{ uri: string }> {
+ const upload = await getOvResult<{ temp_file_id: string }>(
+ postResourcesTempUpload({
+ client: source.client,
+ body: { file },
+ signal,
+ }),
+ )
+ if (!upload.temp_file_id)
+ throw new Error(i18n.t('dataManagement:missingUploadId'))
+ return getOvResult(
+ postPackImport({
+ client: source.client,
+ body: {
+ temp_file_id: upload.temp_file_id,
+ parent,
+ on_conflict: onConflict,
+ vector_mode: 'auto',
+ },
+ signal,
+ }),
+ )
+}
diff --git a/web-studio/src/routes/filesystem/-lib/snapshot-diff.test.ts b/web-studio/src/routes/filesystem/-lib/snapshot-diff.test.ts
new file mode 100644
index 000000000..04136cf0e
--- /dev/null
+++ b/web-studio/src/routes/filesystem/-lib/snapshot-diff.test.ts
@@ -0,0 +1,35 @@
+import { expect, it } from 'vitest'
+
+import { parseSnapshotDiff } from './snapshot-diff'
+
+it('aligns changed lines and keeps line numbers across hunks', () => {
+ const hunks = parseSnapshotDiff(
+ [
+ '--- a/note.md',
+ '+++ b/note.md',
+ '@@ -2,2 +2,3 @@',
+ ' same',
+ '-old',
+ '+new',
+ '+extra',
+ '@@ -9,1 +10,0 @@',
+ '-gone',
+ ].join('\n'),
+ )
+
+ expect(hunks).toHaveLength(2)
+ expect(hunks[0].rows).toEqual([
+ {
+ kind: 'context',
+ oldLine: 2,
+ newLine: 2,
+ oldText: 'same',
+ newText: 'same',
+ },
+ { kind: 'changed', oldLine: 3, newLine: 3, oldText: 'old', newText: 'new' },
+ { kind: 'added', newLine: 4, newText: 'extra' },
+ ])
+ expect(hunks[1].rows).toEqual([
+ { kind: 'removed', oldLine: 9, oldText: 'gone' },
+ ])
+})
diff --git a/web-studio/src/routes/filesystem/-lib/snapshot-diff.ts b/web-studio/src/routes/filesystem/-lib/snapshot-diff.ts
new file mode 100644
index 000000000..6a5ce2641
--- /dev/null
+++ b/web-studio/src/routes/filesystem/-lib/snapshot-diff.ts
@@ -0,0 +1,65 @@
+export interface DiffRow {
+ oldLine?: number
+ newLine?: number
+ oldText?: string
+ newText?: string
+ kind: 'context' | 'added' | 'removed' | 'changed'
+}
+
+export interface DiffHunk {
+ label: string
+ rows: DiffRow[]
+}
+
+export function parseSnapshotDiff(diff: string): DiffHunk[] {
+ const hunks: DiffHunk[] = []
+ let hunk: DiffHunk | null = null
+ let oldLine = 0
+ let newLine = 0
+ let removed: string[] = []
+ let added: string[] = []
+
+ function flushChanges() {
+ if (!hunk) return
+ const count = Math.max(removed.length, added.length)
+ for (let index = 0; index < count; index++) {
+ const hasOld = index < removed.length
+ const hasNew = index < added.length
+ hunk.rows.push({
+ ...(hasOld ? { oldLine: oldLine++, oldText: removed[index] } : {}),
+ ...(hasNew ? { newLine: newLine++, newText: added[index] } : {}),
+ kind: !hasOld ? 'added' : !hasNew ? 'removed' : 'changed',
+ })
+ }
+ removed = []
+ added = []
+ }
+
+ for (const line of diff.split('\n')) {
+ const match = /^@@ -(\d+)(?:,\d+)? \+(\d+)(?:,\d+)? @@(.*)$/.exec(line)
+ if (match) {
+ flushChanges()
+ oldLine = Number(match[1])
+ newLine = Number(match[2])
+ hunk = { label: match[3].trim(), rows: [] }
+ hunks.push(hunk)
+ } else if (hunk && line.startsWith('-')) {
+ removed.push(line.slice(1))
+ } else if (hunk && line.startsWith('+')) {
+ added.push(line.slice(1))
+ } else if (hunk && line.startsWith(' ')) {
+ flushChanges()
+ hunk.rows.push({
+ oldLine: oldLine++,
+ newLine: newLine++,
+ oldText: line.slice(1),
+ newText: line.slice(1),
+ kind: 'context',
+ })
+ } else if (hunk && line === '\\ No newline at end of file') {
+ continue
+ }
+ }
+ flushChanges()
+ return hunks
+}
diff --git a/web-studio/src/routes/filesystem/route.test.tsx b/web-studio/src/routes/filesystem/route.test.tsx
index c3fff53a1..2d8bd3cdc 100644
--- a/web-studio/src/routes/filesystem/route.test.tsx
+++ b/web-studio/src/routes/filesystem/route.test.tsx
@@ -24,6 +24,7 @@ const mocks = vi.hoisted(() => ({
fetchFsStat: vi.fn(),
invalidateList: vi.fn(),
navigate: vi.fn(),
+ dataManagement: vi.fn(),
refreshLabel: 'refresh',
search: {} as { file?: string; uri?: string },
}))
@@ -103,6 +104,12 @@ vi.mock('./-components/agent-panel', () => ({ AgentPanel: mocks.agent }))
vi.mock('./-components/terminal-panel', () => ({
TerminalPanel: mocks.terminal,
}))
+vi.mock('./-components/data-management-dialog', () => ({
+ DataManagementDialog: (props: { uri: string; isDirectory: boolean }) => {
+ mocks.dataManagement(props)
+ return <div data-testid="data-management-uri">{props.uri}</div>
+ },
+}))
vi.mock('#/routes/resources/-components/find-palette', () => ({
FindPalette: () => null,
}))
@@ -131,11 +138,54 @@ describe('filesystem context tree refresh', () => {
mocks.fetchFsStat.mockReset()
mocks.invalidateList.mockReset().mockResolvedValue(undefined)
mocks.navigate.mockReset()
+ mocks.dataManagement.mockReset()
})
- it('reuses the same workbench for hosted reads without scope tabs or incompatible local tools', () => {
+ it('offers OVPack for the parent resource directory while a file is selected', async () => {
+ mocks.search = {
+ file: 'viking://resources/preferences/response-tone.md',
+ uri: 'viking://resources/preferences/',
+ }
+ render(<FilesystemRoute />)
+
+ await userEvent.click(
+ screen.getByRole('button', { name: 'dataManagement:transferTitle' }),
+ )
+ expect(screen.getByTestId('data-management-uri').textContent).toBe(
+ 'viking://resources/preferences/',
+ )
+ expect(mocks.dataManagement.mock.lastCall?.[0].isDirectory).toBe(true)
+ })
+
+ it('offers OVPack on hosted resource directories too', async () => {
mocks.provider = 'volcengine'
+ mocks.search = {
+ file: 'viking://resources/preferences/response-tone.md',
+ uri: 'viking://resources/preferences/',
+ }
render(<FilesystemRoute />)
+
+ await userEvent.click(
+ screen.getByRole('button', { name: 'dataManagement:transferTitle' }),
+ )
+ expect(screen.getByTestId('data-management-uri').textContent).toBe(
+ 'viking://resources/preferences/',
+ )
+ expect(mocks.dataManagement.mock.lastCall?.[0].isDirectory).toBe(true)
+ })
+
+ it('offers snapshot history for hosted reads without incompatible local tools', async () => {
+ mocks.provider = 'volcengine'
+ render(<FilesystemRoute />)
+ await userEvent.click(
+ screen.getByRole('button', { name: 'dataManagement:historyTitle' }),
+ )
+ expect(screen.getByTestId('data-management-uri').textContent).toBe(
+ firstFile,
+ )
+ expect(
+ screen.queryByRole('button', { name: 'dataManagement:transferTitle' }),
+ ).toBeNull()
expect(screen.getByTestId('preview').textContent).toBe(firstFile)
expect(mocks.preview.mock.lastCall?.[0].readOnly).not.toBe(true)
expect(mocks.preview.mock.lastCall?.[0].defaultReadLimit).toBe(10000)
diff --git a/web-studio/src/routes/filesystem/route.tsx b/web-studio/src/routes/filesystem/route.tsx
index 2a7c3858c..f9ce7c91b 100644
--- a/web-studio/src/routes/filesystem/route.tsx
+++ b/web-studio/src/routes/filesystem/route.tsx
@@ -6,6 +6,8 @@ import {
ArrowLeftIcon,
BotIcon,
ClipboardIcon,
+ HistoryIcon,
+ PackageIcon,
PanelRightCloseIcon,
PanelRightOpenIcon,
TerminalIcon,
@@ -52,6 +54,8 @@ import {
FilesystemResizeHandle,
} from './-components/context-explorer'
import { TerminalPanel } from './-components/terminal-panel'
+import { DataManagementDialog } from './-components/data-management-dialog'
+import { SnapshotComparisonDialog } from './-components/snapshot-comparison-dialog'
import {
ROOT_URI,
FILESYSTEM_LEFT_WIDTH,
@@ -143,6 +147,9 @@ function FilesystemWorkbench() {
)
const [findPaletteOpen, setFindPaletteOpen] = useState(false)
const [taskDialogOpen, setTaskDialogOpen] = useState(false)
+ const [dataManagementMode, setDataManagementMode] = useState<
+ 'history' | 'transfer' | 'compare' | null
+ >(null)
const [openingUri, setOpeningUri] = useState<string | null>(null)
const layoutRef = useRef<HTMLDivElement>(null)
const [leftWidth, setLeftWidth] = useState(() =>
@@ -200,7 +207,7 @@ function FilesystemWorkbench() {
refreshTasks,
tasks,
} = useResourceUpload()
- const { invalidateList } = useInvalidateVikingFs()
+ const { invalidateAll, invalidateList } = useInvalidateVikingFs()
const syncSearch = useCallback(
(next: {
@@ -448,6 +455,15 @@ function FilesystemWorkbench() {
}, [])
const selectedUri = selectedFile?.uri ?? currentUri
+ const selectedIsDirectory = selectedFile?.isDir ?? true
+ const transferUri = selectedIsDirectory
+ ? selectedUri
+ : normalizeDirUri(parentUri(selectedUri))
+ useEffect(() => {
+ setDataManagementMode(null)
+ }, [selectedUri])
+ const canManageSelectedUri = selectedUri !== ROOT_URI
+ const canTransferSelectedUri = transferUri.startsWith('viking://resources/')
const displayUri =
selectedUri === ROOT_URI ? selectedUri : selectedUri.replace(/\/$/, '')
const entries = visibleContextEntries(listQuery.data?.entries ?? [])
@@ -620,6 +636,33 @@ function FilesystemWorkbench() {
>
<ClipboardIcon className="size-4" />
</Button>
+ {canManageSelectedUri ? (
+ <Button
+ type="button"
+ size="icon-sm"
+ variant="ghost"
+ title={t('dataManagement:historyTitle')}
+ aria-label={t('dataManagement:historyTitle')}
+ onClick={() => setDataManagementMode('history')}
+ >
+ <HistoryIcon className="size-4" />
+ </Button>
+ ) : null}
+ {canTransferSelectedUri ? (
+ <Button
+ type="button"
+ size="sm"
+ variant="ghost"
+ title={t('dataManagement:transferTitle')}
+ aria-label={t('dataManagement:transferTitle')}
+ onClick={() => setDataManagementMode('transfer')}
+ >
+ <PackageIcon className="size-4" />
+ <span className="hidden sm:inline">
+ {t('dataManagement:transferShortLabel')}
+ </span>
+ </Button>
+ ) : null}
{canUseLocalTools ? (
<div className="flex shrink-0 items-center gap-1 lg:hidden">
<Button
@@ -746,6 +789,23 @@ function FilesystemWorkbench() {
/>
</>
) : null}
+ {dataManagementMode === 'compare' ? (
+ <SnapshotComparisonDialog
+ key={`${identityScopeKey}:${selectedUri}:compare`}
+ onClose={() => setDataManagementMode(null)}
+ uri={selectedUri}
+ />
+ ) : dataManagementMode ? (
+ <DataManagementDialog
+ key={`${identityScopeKey}:${dataManagementMode === 'transfer' ? transferUri : selectedUri}:${dataManagementMode}`}
+ mode={dataManagementMode}
+ onClose={() => setDataManagementMode(null)}
+ onCompare={() => setDataManagementMode('compare')}
+ onChanged={() => void invalidateAll()}
+ uri={dataManagementMode === 'transfer' ? transferUri : selectedUri}
+ isDirectory={dataManagementMode === 'transfer' || selectedIsDirectory}
+ />
+ ) : null}
<FindPalette
open={findPaletteOpen}
onClose={() => setFindPaletteOpen(false)}
diff --git a/web-studio/src/routes/resources/-components/file-preview.test.tsx b/web-studio/src/routes/resources/-components/file-preview.test.tsx
index 974c5a4e0..ee48e0d44 100644
--- a/web-studio/src/routes/resources/-components/file-preview.test.tsx
+++ b/web-studio/src/routes/resources/-components/file-preview.test.tsx
@@ -144,7 +144,7 @@ const directory: VikingFsEntry = {
function renderPreview(
entry: VikingFsEntry,
- onNavigate: (uri: string) => void,
+ onNavigate?: (uri: string) => void,
directoryOverview?: string,
directoryAbstract?: string,
) {
@@ -180,11 +180,40 @@ describe('FilePreview Markdown rendering', () => {
beforeEach(() => {
cleanup()
previewMocks.renderMermaid.mockClear()
+ Object.defineProperty(URL, 'createObjectURL', {
+ configurable: true,
+ value: vi.fn(() => 'blob:internal-image'),
+ })
+ Object.defineProperty(URL, 'revokeObjectURL', {
+ configurable: true,
+ value: vi.fn(),
+ })
})
afterEach(() => {
previewState.override = null
})
+ it('shows available file metadata at the bottom and omits missing values', () => {
+ const { container, rerender } = renderPreview(file, vi.fn())
+ expect(container.querySelector('footer')?.textContent).toBe(
+ '24 B · 2026-08-04 12:00',
+ )
+ expect(
+ container.querySelector('footer')?.previousElementSibling,
+ ).toBeTruthy()
+
+ rerender(
+ <FilePreview
+ file={{ ...file, size: '', sizeBytes: null, modTime: '' }}
+ onClose={vi.fn()}
+ onNavigate={vi.fn()}
+ showCloseButton={false}
+ />,
+ )
+ expect(container.querySelector('footer')).toBeNull()
+ expect(container.textContent).not.toContain('- · -')
+ })
+
it('opens internal Markdown links in the resource preview', () => {
const onNavigate = vi.fn()
renderPreview(file, onNavigate)
@@ -199,6 +228,79 @@ describe('FilePreview Markdown rendering', () => {
expect(previewMocks.renderMermaid).not.toHaveBeenCalled()
})
+ it('renders explicit and relative internal images through authenticated downloads', async () => {
+ previewState.override = {
+ content: [
+ '![Explicit](viking://resources/wiki/photo.jpg)',
+ '![Relative](./photo.jpg)',
+ '[Open image](viking://resources/wiki/photo.jpg)',
+ ].join('\n\n'),
+ fileType: 'markdown',
+ }
+ vi.mocked(getContentDownload).mockResolvedValue({
+ data: new Blob(['image'], { type: 'image/jpeg' }),
+ } as never)
+ const onNavigate = vi.fn()
+ renderPreview(file, onNavigate)
+
+ await screen.findByRole('img', { name: 'Explicit' })
+ await screen.findByRole('img', { name: 'Relative' })
+ expect(getContentDownload).toHaveBeenCalledWith({
+ query: { uri: 'viking://resources/wiki/photo.jpg' },
+ responseType: 'blob',
+ throwOnError: true,
+ })
+ expect(
+ screen.getAllByRole('link', { name: /Explicit|Relative/ }),
+ ).toHaveLength(2)
+ fireEvent.click(screen.getByRole('link', { name: 'Relative' }))
+ fireEvent.click(screen.getByRole('link', { name: 'Open image' }))
+ expect(onNavigate).toHaveBeenCalledTimes(2)
+ expect(onNavigate).toHaveBeenCalledWith('viking://resources/wiki/photo.jpg')
+ })
+
+ it('keeps a linked image on its enclosing destination without nested links', async () => {
+ previewState.override = {
+ content: '[![Linked image](./photo.jpg)](./target.md)',
+ fileType: 'markdown',
+ }
+ vi.mocked(getContentDownload).mockResolvedValue({
+ data: new Blob(['image'], { type: 'image/jpeg' }),
+ } as never)
+ const onNavigate = vi.fn()
+ const { container } = renderPreview(file, onNavigate)
+ await screen.findByRole('img', { name: 'Linked image' })
+
+ const link = screen.getByRole('link', { name: 'Linked image' })
+ expect(link.getAttribute('href')).toBe('viking://resources/wiki/target.md')
+ expect(container.querySelector('a a')).toBeNull()
+ fireEvent.click(link)
+ expect(onNavigate).toHaveBeenCalledOnce()
+ expect(onNavigate).toHaveBeenCalledWith('viking://resources/wiki/target.md')
+ })
+
+ it('leaves images display-only without navigation and strips unsafe markup', async () => {
+ previewState.override = {
+ content: [
+ '![Display only](./photo.jpg)',
+ '[Unsafe](javascript:alert(1))',
+ '<img src="javascript:alert(1)" onerror="alert(1)" />',
+ ].join('\n\n'),
+ fileType: 'markdown',
+ }
+ vi.mocked(getContentDownload).mockResolvedValue({
+ data: new Blob(['image'], { type: 'image/jpeg' }),
+ } as never)
+ const { container } = renderPreview(file)
+ await screen.findByRole('img', { name: 'Display only' })
+
+ expect(screen.queryByRole('link', { name: 'Display only' })).toBeNull()
+ expect(container.querySelector('[onerror]')).toBeNull()
+ expect(
+ container.querySelector('[href^="javascript:"], [src^="javascript:"]'),
+ ).toBeNull()
+ })
+
it('opens viking links from a directory overview', () => {
const onNavigate = vi.fn()
renderPreview(
diff --git a/web-studio/src/routes/resources/-components/file-preview.tsx b/web-studio/src/routes/resources/-components/file-preview.tsx
index 0ec431feb..17c51d67b 100644
--- a/web-studio/src/routes/resources/-components/file-preview.tsx
+++ b/web-studio/src/routes/resources/-components/file-preview.tsx
@@ -1,7 +1,9 @@
import { formatDateTime } from '#/i18n/format'
import i18n from '#/i18n/core'
import {
+ createContext,
isValidElement,
+ useContext,
useEffect,
useMemo,
useRef,
@@ -14,7 +16,7 @@ import { useQuery } from '@tanstack/react-query'
import hljs from 'highlight.js/lib/core'
import ReactMarkdown, { defaultUrlTransform } from 'react-markdown'
import rehypeRaw from 'rehype-raw'
-import rehypeSanitize from 'rehype-sanitize'
+import rehypeSanitize, { defaultSchema } from 'rehype-sanitize'
import remarkBreaks from 'remark-breaks'
import remarkGfm from 'remark-gfm'
import { X, Pencil, Save, XCircle, Loader2 } from 'lucide-react'
@@ -138,6 +140,15 @@ interface FilePreviewProps {
}
const vikingPrefix = 'viking://'
+const markdownSanitizeSchema = {
+ ...defaultSchema,
+ protocols: {
+ ...defaultSchema.protocols,
+ src: [...(defaultSchema.protocols?.src ?? []), 'viking'],
+ href: [...(defaultSchema.protocols?.href ?? []), 'viking'],
+ },
+}
+const MarkdownLinkContext = createContext(false)
const contentDownloadUrl: GetContentDownloadData['url'] =
'/api/v1/content/download'
@@ -419,7 +430,9 @@ function MarkdownLink({
target={isExternal ? '_blank' : undefined}
rel={isExternal ? 'noreferrer noopener' : undefined}
>
- {children}
+ <MarkdownLinkContext.Provider value={true}>
+ {children}
+ </MarkdownLinkContext.Provider>
</a>
)
}
@@ -451,11 +464,14 @@ function MarkdownImage({
src,
alt,
fileUri,
+ onNavigate,
}: {
src?: string
alt?: string
fileUri: string
+ onNavigate?: (uri: string) => void
}) {
+ const insideLink = useContext(MarkdownLinkContext)
const target = useMemo(
() => (src ? resolveMarkdownAssetTarget(String(src), fileUri) : null),
[src, fileUri],
@@ -518,15 +534,29 @@ function MarkdownImage({
}
return null
}
+ if (!resolvedSrc) return null
- return (
+ const image = (
<img
src={resolvedSrc}
- alt={alt || ''}
+ alt={
+ alt ||
+ (target?.kind === 'viking' && onNavigate && !insideLink
+ ? fileNameFromUri(target.value)
+ : '')
+ }
loading="lazy"
className="max-w-full rounded-md outline outline-1 -outline-offset-1 outline-black/10 dark:outline-white/10"
/>
)
+ if (target?.kind === 'viking' && onNavigate && !insideLink) {
+ return (
+ <MarkdownLink href={src} fileUri={fileUri} onNavigate={onNavigate}>
+ {image}
+ </MarkdownLink>
+ )
+ }
+ return image
}
function detectCodeLanguage(filename: string): string | null {
@@ -1625,6 +1655,14 @@ export function FilePreview({
)
const showHeader = !(hideDirectoryHeader && file.isDir)
const previewFile = resolvedFile || file
+ const sizeLabel = formatSize(previewFile.sizeBytes ?? previewFile.size, {
+ fallback: '',
+ })
+ const modTimeLabel =
+ previewFile.modTime && previewFile.modTime !== '-'
+ ? previewFile.modTime
+ : ''
+ const fileMetadata = [sizeLabel, modTimeLabel].filter(Boolean).join(' · ')
const showJsonPreview =
!editing &&
!previewLoading &&
@@ -1641,12 +1679,6 @@ export function FilePreview({
<div className="truncate text-sm font-medium leading-5">
{file.name}
</div>
- {!file.isDir ? (
- <div className="text-xs leading-5 text-muted-foreground">
- {formatSize(previewFile.sizeBytes ?? previewFile.size)} ·{' '}
- {previewFile.modTime || '-'}
- </div>
- ) : null}
</div>
{editing ? (
<div className="flex items-center gap-1">
@@ -2003,8 +2035,11 @@ export function FilePreview({
<article className="prose prose-sm max-w-none break-words dark:prose-invert dark:prose-pre:bg-muted-foreground/20">
<ReactMarkdown
remarkPlugins={[remarkGfm]}
- rehypePlugins={[rehypeRaw, rehypeSanitize]}
- urlTransform={(url) => url}
+ rehypePlugins={[
+ rehypeRaw,
+ [rehypeSanitize, markdownSanitizeSchema],
+ ]}
+ urlTransform={transformDirectoryMarkdownUrl}
components={{
...markdownComponents,
img: ({ src, alt }) => (
@@ -2012,6 +2047,7 @@ export function FilePreview({
src={src ? String(src) : undefined}
alt={alt}
fileUri={file.uri}
+ onNavigate={onNavigate}
/>
),
a: ({ href, children }) => (
@@ -2085,6 +2121,11 @@ export function FilePreview({
</div>
</ScrollArea>
)}
+ {!file.isDir && fileMetadata ? (
+ <footer className="shrink-0 border-t px-4 py-2 text-xs text-muted-foreground">
+ {fileMetadata}
+ </footer>
+ ) : null}
</div>
)
}