Skip to content

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

feat(studio): improve Compile first-use workflow (#6491)

leowldd15b28dd2953
diff --git a/web-studio/src/i18n/locales/en/activity.ts b/web-studio/src/i18n/locales/en/activity.ts
index 0c3545db9..9144d5607 100644
--- a/web-studio/src/i18n/locales/en/activity.ts
+++ b/web-studio/src/i18n/locales/en/activity.ts
@@ -176,6 +176,7 @@ const activity = {
agent: 'Agent capabilities, tools, and experience',
user: 'Personalized user memories',
resources: 'External resources the Agent can reference',
+ system: 'Built-in system resources',
},
},
agent: {
diff --git a/web-studio/src/i18n/locales/en/compile.ts b/web-studio/src/i18n/locales/en/compile.ts
index 7d849972a..722983e5e 100644
--- a/web-studio/src/i18n/locales/en/compile.ts
+++ b/web-studio/src/i18n/locales/en/compile.ts
@@ -1,4 +1,102 @@
export default {
+ builtinSkills: 'Built-in',
+ installedSkills: 'My and shared skills',
+ specializedSkill: 'Specialized session input',
+ skillDescriptionUnavailable:
+ 'No description is available. View the Skill definition for details.',
+ skillMetadataFailed: 'Unable to read the latest definition for this skill.',
+ skillContentEmpty: 'This Skill has no content yet.',
+ skillPreview: 'Skill details',
+ manageSkills: 'Manage my and shared skills',
+ skillGroupFailed:
+ 'Could not load {{group}}. Other loaded skills are still available.',
+ suitableInputs: 'Suitable inputs',
+ expectedOutputs: 'Expected output',
+ usageLimits: 'Usage limits',
+ personalSpace: 'Personal space',
+ sharedSpace: 'Shared space',
+ otherLocation: 'Other location',
+ spaceRoot: 'Root folder',
+ openFilesystem: 'Open filesystem',
+ copyPath: 'Copy directory path',
+ copyFailed: 'Could not copy. Please try again.',
+ checkingTarget: 'Checking the destination…',
+ targetNew: 'This is a new folder. It will be created during execution.',
+ targetExists: 'This folder already exists. Its contents may be updated.',
+ targetNotDirectory:
+ 'This location is a file. Choose a folder or use a different folder name.',
+ targetRootInvalid:
+ 'Choose a destination folder inside a space, not a space root or system directory.',
+ sourceNotDirectory:
+ 'Sources must be readable folders. Please select them again.',
+ submissionSummary:
+ 'Use {{skill}} to compile {{count}} source folder(s) into “{{folder}}” in {{space}}.',
+ compileThisFolder: 'Compile this folder',
+ viewGenerated: 'View generated content',
+ outputHint: 'Open the destination to view generated or updated files.',
+ capability: {
+ checking: 'Checking submission requirements…',
+ failed: 'Could not check submission requirements. Please retry.',
+ notConfigured:
+ 'Compile execution is not enabled. Ask an administrator to configure it.',
+ keyRequired:
+ 'This connection needs an OpenViking API key to submit a compile task. Check connection settings.',
+ connection: 'Open connection settings',
+ adminGuide: 'Administrator setup guide',
+ technical:
+ 'Administrators can configure an Agent Runtime (compile_api.base_url) or use the built-in VikingBot runtime. Credential requirements are determined by the server.',
+ },
+ builtin: {
+ 'llm-wiki': {
+ name: 'Knowledge Wiki',
+ description:
+ 'Organize multiple sources into knowledge pages with an index and citations.',
+ inputs: 'Documents, notes, meeting records, research materials, or code.',
+ outputs: 'Topic-based Markdown pages, an index, and source references.',
+ limits:
+ 'Uses the selected sources only. Existing knowledge pages may be updated.',
+ },
+ 'knowledge-distillation': {
+ name: 'Knowledge Distillation',
+ description:
+ 'Extract shared findings, differences, trends, and conclusions across sources.',
+ inputs: 'Related source collections or materials to compare.',
+ outputs: 'Topic-organized conclusion pages supported by evidence.',
+ limits:
+ 'Designed for synthesis, not per-document summaries. Specify your analytical question in Additional instructions.',
+ },
+ 'daily-report': {
+ name: 'Daily Report',
+ description:
+ 'Turn activity records into progress, outcomes, and next steps for specific dates.',
+ inputs: 'Dated work records, meeting notes, tasks, or conversation logs.',
+ outputs: 'One Markdown daily report per date, such as YYYY-MM-DD.md.',
+ limits:
+ 'Specify the reporting date in Additional instructions. Studio sessions are not read automatically.',
+ },
+ 'knowledge-graph': {
+ name: 'Knowledge Graph',
+ description:
+ 'Extract entities and relationships while retaining their sources.',
+ inputs:
+ 'Materials containing people, organizations, projects, events, or other entities.',
+ outputs:
+ 'Entity documents under entities/ and a relations.jsonl relationship file.',
+ limits:
+ 'Produces graph data files. An interactive graph viewer is not included.',
+ },
+ 'ov-session-report': {
+ name: 'Session Q&A Weekly Report',
+ description:
+ 'Generate a Q&A weekly report from specialized session JSONL data.',
+ inputs:
+ 'Session JSONL matching the Skill format and the sessions_root parameter.',
+ outputs:
+ 'One Markdown weekly report with metrics, topics, and issue analysis.',
+ limits:
+ 'English output by default. Requires specialized input and parameters; Studio sessions are not read automatically.',
+ },
+ },
errors: {
generic: 'The request could not be completed.',
invalidArgument: 'Check the request parameters and try again.',
@@ -70,13 +168,13 @@ export default {
skillRequired: 'Choose a Skill.',
sourcesRequired: 'Add at least one source directory.',
targetRequired: 'Set an output directory.',
- mySkills: 'My Skills',
- sharedSkills: 'Shared Skills',
+ mySkills: 'My',
+ sharedSkills: 'Shared',
otherSkills: 'Other paths',
noMatchingSkills: 'No matching skills',
skillLocationHint:
- 'Add a Skill on the Skills page first. Private and shared Skills are supported; the directory must contain SKILL.md.',
+ 'Use a built-in capability, or choose one of your own or shared skills.',
expiredSubmission:
'The retry window has expired. Look up the last submission or check the task list before clearing the draft to start another task.',
targetPlaceholder: 'viking://resources/wiki',
@@ -95,15 +193,15 @@ export default {
retry: 'Retry',
failedLoad: 'Could not load data',
unconfigured: 'Compilation is unavailable for this connection or identity.',
- skill: '1. Choose a Skill',
+ skill: 'Generation capability',
skillSearch: 'Search Skills',
- chooseSkill: 'Choose a Skill',
- noSkills: 'No available Skills. Visit Skills to add one.',
- preview: 'View current Skill',
+ chooseSkill: 'Choose what to generate',
+ noSkills: 'No skills are available on this server.',
+ preview: 'Preview Skill',
sources: 'Source directories',
browse: 'Browse directories',
- sourceHint: 'One Viking directory URI per line. Files are not accepted.',
- target: '3. Choose an output location',
+ sourceHint: 'Choose directories stored in Viking. You can add more than one.',
+ target: 'Output directory',
targetHint:
'Existing contents may be updated. A new target is created during execution.',
instruction: 'Additional instructions',
@@ -117,9 +215,11 @@ export default {
copied: 'Copied',
cancel: 'Cancel',
clear: 'Clear draft',
+ restoreDraft: 'Restore draft',
draft:
'Public fields are saved as a draft. Advanced parameters are not saved.',
- required: 'Choose a Skill, at least one source directory and an output URI.',
+ required:
+ 'Choose a capability, at least one source folder, and a destination.',
invalidUri: 'Use full viking:// URIs for every path.',
argsError: 'Advanced parameters must be a valid JSON object.',
runningHint: 'You can leave this page. The task will continue.',
@@ -137,7 +237,7 @@ export default {
result: 'Result',
output: 'Open output directory',
noResult: 'No structured result is available yet.',
- raw: 'Raw result',
+ raw: 'Technical details (raw result)',
stage: 'Current stage',
updated: 'Last updated',
stale: 'Updates are unavailable. Showing the last known state.',
diff --git a/web-studio/src/i18n/locales/zh-CN/activity.ts b/web-studio/src/i18n/locales/zh-CN/activity.ts
index a7438e431..27cbee59f 100644
--- a/web-studio/src/i18n/locales/zh-CN/activity.ts
+++ b/web-studio/src/i18n/locales/zh-CN/activity.ts
@@ -168,6 +168,7 @@ const activity = {
agent: 'Agent 的能力、工具和经验',
user: '用户个性化记忆',
resources: 'Agent 可引用的外部资源',
+ system: '系统内置资源',
},
},
agent: {
diff --git a/web-studio/src/i18n/locales/zh-CN/compile.ts b/web-studio/src/i18n/locales/zh-CN/compile.ts
index dff640a94..ca2865da5 100644
--- a/web-studio/src/i18n/locales/zh-CN/compile.ts
+++ b/web-studio/src/i18n/locales/zh-CN/compile.ts
@@ -1,4 +1,82 @@
export default {
+ builtinSkills: '内置',
+ installedSkills: '我的和共享能力',
+ specializedSkill: '需专用会话数据',
+ skillDescriptionUnavailable: '暂未提供用途说明,可查看 Skill 定义。',
+ skillMetadataFailed: '无法读取此能力的最新说明。',
+ skillContentEmpty: '此 Skill 暂无内容。',
+ skillPreview: '能力说明',
+ manageSkills: '管理我的和共享 Skill',
+ skillGroupFailed: '{{group}}加载失败,其他已加载能力仍可使用。',
+ suitableInputs: '适用素材',
+ expectedOutputs: '生成内容',
+ usageLimits: '使用限制',
+ personalSpace: '个人空间',
+ sharedSpace: '共享空间',
+ otherLocation: '其他位置',
+ spaceRoot: '根目录',
+ openFilesystem: '前往文件系统',
+ copyPath: '复制目录路径',
+ copyFailed: '复制失败,请重试。',
+ checkingTarget: '正在检查保存位置…',
+ targetNew: '新目录,将在执行时创建。',
+ targetExists: '已有目录,其中内容可能被更新。',
+ targetNotDirectory: '此位置是文件,请选择目录或使用其他文件夹名称。',
+ targetRootInvalid:
+ '请选择空间内的目标文件夹,不能直接保存到空间根目录或系统目录。',
+ sourceNotDirectory: '素材必须是可读取的目录,请重新选择。',
+ submissionSummary:
+ '使用{{skill}},将 {{count}} 个素材目录整理到{{space}}的「{{folder}}」。',
+ compileThisFolder: '使用此目录编译',
+ viewGenerated: '查看生成内容',
+ outputHint: '打开保存位置,查看生成或更新的文件。',
+ capability: {
+ checking: '正在检查执行条件…',
+ failed: '执行条件检查失败,请重试。',
+ notConfigured: '当前尚未启用编译执行服务,请联系管理员完成配置。',
+ keyRequired: '当前连接缺少执行所需的 OpenViking API Key,请检查连接设置。',
+ connection: '打开连接设置',
+ adminGuide: '管理员配置说明',
+ technical:
+ '管理员可配置 Agent Runtime(compile_api.base_url),或使用内置 VikingBot 执行服务。凭据要求以服务端检查结果为准。',
+ },
+ builtin: {
+ 'llm-wiki': {
+ name: '知识 Wiki',
+ description: '将多份资料整理为带索引和引用的知识页面。',
+ inputs: '文档、笔记、会议记录、研究资料或代码。',
+ outputs: '按主题组织的 Markdown 页面、索引和来源引用。',
+ limits: '只处理所选素材;已有知识页面可能被更新。',
+ },
+ 'knowledge-distillation': {
+ name: '知识提炼',
+ description: '跨多份资料提取共识、差异、趋势和结论。',
+ inputs: '围绕同一主题或需要对比的多份资料。',
+ outputs: '按主题归类、带证据的结论页面。',
+ limits: '适合综合分析,不是逐篇摘要;可在补充要求中写明分析问题。',
+ },
+ 'daily-report': {
+ name: '工作日报',
+ description: '从活动记录中整理指定日期的进展、结果和待办。',
+ inputs: '带日期的工作记录、会议纪要、任务或对话记录。',
+ outputs: '每个报告日期一份 Markdown 日报,如 YYYY-MM-DD.md。',
+ limits: '请在补充要求中写明日期;不会自动读取 Studio 会话。',
+ },
+ 'knowledge-graph': {
+ name: '知识图谱',
+ description: '从资料中整理实体及其关系,并保留来源。',
+ inputs: '包含人物、组织、项目、事件等实体的资料。',
+ outputs: 'entities/ 下的实体文档与 relations.jsonl 关系文件。',
+ limits: '生成的是图谱数据文件,当前不提供交互式图谱展示。',
+ },
+ 'ov-session-report': {
+ name: '会话问答周报',
+ description: '基于专用会话 JSONL 数据生成问答周报。',
+ inputs: '符合 Skill 要求的会话 JSONL 和 sessions_root 参数。',
+ outputs: '一份包含统计、主题和问题分析的 Markdown 周报。',
+ limits: '默认输出英文;需要专用输入和参数,不会自动读取 Studio 会话。',
+ },
+ },
errors: {
generic: '请求未能完成。',
invalidArgument: '请检查请求参数后重试。',
@@ -63,13 +141,12 @@ export default {
skillRequired: '请选择一个 Skill。',
sourcesRequired: '请添加至少一个素材目录。',
targetRequired: '请设置输出目录。',
- mySkills: '我的 Skill',
- sharedSkills: '共享 Skill',
+ mySkills: '我的',
+ sharedSkills: '共享',
otherSkills: '其他路径',
noMatchingSkills: '没有匹配的 Skill',
- skillLocationHint:
- '请先在 Skills 页面添加 Skill;支持当前用户私有或共享的 Skill,目录内需包含 SKILL.md。',
+ skillLocationHint: '直接使用内置能力,也可选择我的或共享 Skill。',
expiredSubmission:
'已超过安全重试时间。请先查询上次提交或检查任务列表,确认后清空草稿再创建新任务。',
targetPlaceholder: 'viking://resources/wiki',
@@ -88,11 +165,11 @@ export default {
retry: '重试',
failedLoad: '加载失败',
unconfigured: '当前连接或身份暂不可创建编译任务。',
- skill: '编译 Skill',
+ skill: '生成能力',
skillSearch: '搜索 Skill',
- chooseSkill: '请选择 Skill',
- noSkills: '暂无可用 Skill,请前往 Skills 添加。',
- preview: '查看当前 Skill',
+ chooseSkill: '选择要生成的内容',
+ noSkills: '服务器暂无可用能力。',
+ preview: '预览 Skill',
sources: '素材目录',
browse: '浏览目录',
sourceHint: '选择已存入 Viking 的目录,可添加多个。',
@@ -108,8 +185,9 @@ export default {
copied: '已复制',
cancel: '取消',
clear: '清空草稿',
+ restoreDraft: '恢复草稿',
draft: '已自动保存草稿 · 高级参数不保存',
- required: '请选择 Skill、至少一个素材目录,并填写输出 URI。',
+ required: '请选择生成能力、至少一个素材目录,并设置保存位置。',
invalidUri: '所有路径请填写完整的 viking:// URI。',
argsError: '高级参数必须是合法的 JSON 对象。',
runningHint: '可以离开页面,任务会继续执行。',
@@ -125,7 +203,7 @@ export default {
result: '结果',
output: '打开输出目录',
noResult: '暂未提供结构化结果。',
- raw: '原始结果',
+ raw: '技术详情(原始结果)',
stage: '当前阶段',
updated: '最近更新',
stale: '暂时无法更新,以下为最近一次状态。',
diff --git a/web-studio/src/routes/compile/-components/capability-notice.test.tsx b/web-studio/src/routes/compile/-components/capability-notice.test.tsx
new file mode 100644
index 000000000..88557f141
--- /dev/null
+++ b/web-studio/src/routes/compile/-components/capability-notice.test.tsx
@@ -0,0 +1,80 @@
+// @vitest-environment jsdom
+import { afterEach, expect, it, vi } from 'vitest'
+import { cleanup, fireEvent, render, waitFor } from '@testing-library/react'
+import { QueryClient, QueryClientProvider } from '@tanstack/react-query'
+import { CapabilityNotice, useCompileCapability } from './capability-notice'
+
+const api = vi.hoisted(() => ({
+ fetchCapabilities: vi.fn(),
+ openConnectionSettings: vi.fn(),
+}))
+vi.mock('../-lib/api', () => ({ fetchCapabilities: api.fetchCapabilities }))
+vi.mock('#/hooks/use-app-connection', () => ({
+ useAppConnection: () => ({
+ identityScopeKey: 'alice',
+ openConnectionSettings: api.openConnectionSettings,
+ }),
+}))
+vi.mock('react-i18next', () => ({
+ useTranslation: () => ({ t: (key: string) => key, i18n: { language: 'en' } }),
+}))
+vi.mock('./shared', () => ({
+ CompileError: ({ retry }: { retry: () => void }) => (
+ <button onClick={retry}>Retry check</button>
+ ),
+}))
+const clients: QueryClient[] = []
+function Notice() {
+ const query = useCompileCapability()
+ return <CapabilityNotice capability={query} />
+}
+function mount() {
+ const client = new QueryClient()
+ clients.push(client)
+ return render(
+ <QueryClientProvider client={client}>
+ <Notice />
+ </QueryClientProvider>,
+ )
+}
+afterEach(() => {
+ cleanup()
+ clients.splice(0).forEach((client) => client.clear())
+ vi.resetAllMocks()
+})
+
+it('offers administrator guidance for unconfigured execution', async () => {
+ api.fetchCapabilities.mockResolvedValue({
+ can_create: false,
+ reason_code: 'NOT_CONFIGURED',
+ })
+ const page = mount()
+ expect(await page.findByText('capability.notConfigured')).toBeTruthy()
+ expect(
+ page
+ .getByRole('link', { name: 'capability.adminGuide' })
+ .getAttribute('href'),
+ ).toContain('/en/api/23-agent-runtime')
+ expect(page.queryByText('capability.keyRequired')).toBeNull()
+})
+it('opens connection settings when the identity needs an API key', async () => {
+ api.fetchCapabilities.mockResolvedValue({
+ can_create: false,
+ reason_code: 'API_KEY_REQUIRED',
+ })
+ const page = mount()
+ fireEvent.click(
+ await page.findByRole('button', { name: 'capability.connection' }),
+ )
+ expect(api.openConnectionSettings).toHaveBeenCalledOnce()
+})
+it('retries failed checks without mislabeling them as unconfigured or healthy', async () => {
+ api.fetchCapabilities
+ .mockRejectedValueOnce(new Error('Offline'))
+ .mockResolvedValue({ can_create: true })
+ const page = mount()
+ expect(await page.findByText('capability.failed')).toBeTruthy()
+ expect(page.queryByText('capability.notConfigured')).toBeNull()
+ fireEvent.click(page.getByText('Retry check'))
+ await waitFor(() => expect(page.container.textContent).toBe(''))
+})
diff --git a/web-studio/src/routes/compile/-components/capability-notice.tsx b/web-studio/src/routes/compile/-components/capability-notice.tsx
new file mode 100644
index 000000000..82b829a34
--- /dev/null
+++ b/web-studio/src/routes/compile/-components/capability-notice.tsx
@@ -0,0 +1,98 @@
+import { useQuery } from '@tanstack/react-query'
+import { useTranslation } from 'react-i18next'
+import { Button } from '#/components/ui/button'
+import { useAppConnection } from '#/hooks/use-app-connection'
+import { fetchCapabilities } from '../-lib/api'
+import { CompileError } from './shared'
+
+export function useCompileCapability() {
+ const { identityScopeKey } = useAppConnection()
+ return useQuery({
+ queryKey: ['compile-capability', identityScopeKey],
+ queryFn: ({ signal }) => fetchCapabilities(signal),
+ retry: false,
+ })
+}
+
+export function CapabilityNotice({
+ capability,
+}: {
+ capability: ReturnType<typeof useCompileCapability>
+}) {
+ const { t, i18n } = useTranslation('compile')
+ const { openConnectionSettings } = useAppConnection()
+ if (capability.isError)
+ return (
+ <div className="space-y-2">
+ <p className="text-sm">{t('capability.failed')}</p>
+ <CompileError
+ error={capability.error}
+ retry={() => void capability.refetch()}
+ />
+ </div>
+ )
+ if (capability.isPending)
+ return (
+ <p role="status" className="text-sm text-muted-foreground">
+ {t('capability.checking')}
+ </p>
+ )
+ if (capability.data.can_create) return null
+ const reason = capability.data.reason_code
+ const missingKey = reason === 'API_KEY_REQUIRED'
+ const unconfigured = reason === 'NOT_CONFIGURED'
+ return (
+ <div
+ role="status"
+ className="space-y-3 rounded-lg border bg-muted/30 p-4 text-sm"
+ >
+ <p>
+ {t(
+ missingKey
+ ? 'capability.keyRequired'
+ : unconfigured
+ ? 'capability.notConfigured'
+ : 'unconfigured',
+ )}
+ </p>
+ <div className="flex flex-wrap gap-3">
+ {missingKey && (
+ <Button
+ type="button"
+ variant="outline"
+ size="sm"
+ onClick={openConnectionSettings}
+ >
+ {t('capability.connection')}
+ </Button>
+ )}
+ {unconfigured && (
+ <a
+ className="underline underline-offset-4"
+ href={`https://docs.openviking.ai/${i18n.language.startsWith('zh') ? 'zh' : 'en'}/api/23-agent-runtime`}
+ target="_blank"
+ rel="noreferrer"
+ >
+ {t('capability.adminGuide')}
+ </a>
+ )}
+ <Button
+ type="button"
+ variant="ghost"
+ size="sm"
+ disabled={capability.isFetching}
+ onClick={() => void capability.refetch()}
+ >
+ {t('retry')}
+ </Button>
+ </div>
+ <details>
+ <summary className="cursor-pointer text-xs text-muted-foreground">
+ {t('errors.details')}
+ </summary>
+ <p className="mt-2 text-xs">{t('capability.technical')}</p>
+ {reason && <code className="text-xs">{reason}</code>}
+ </details>
+ </div>
+ )
+}
diff --git a/web-studio/src/routes/compile/-components/compile-form.test.tsx b/web-studio/src/routes/compile/-components/compile-form.test.tsx
index eb97270b2..75772304b 100644
--- a/web-studio/src/routes/compile/-components/compile-form.test.tsx
+++ b/web-studio/src/routes/compile/-components/compile-form.test.tsx
@@ -8,10 +8,15 @@ import { prepareCompileHandoff } from '../-lib/handoff'
import { OvClientError } from '#/lib/ov-client'
const api = vi.hoisted(() => ({
+ BUILTIN_SKILLS_ROOT: 'viking://system/compile/example-skills',
createCompile: vi.fn(),
lookupSubmission: vi.fn(),
fetchCompileSkills: vi.fn(async () => []),
fetchCompileTask: vi.fn(),
+ fetchCapabilities: vi.fn(async () => ({
+ configured: true,
+ can_create: true,
+ })),
navigate: vi.fn(),
}))
vi.mock('../-lib/api', () => api)
@@ -21,7 +26,7 @@ vi.mock('@tanstack/react-router', () => ({
Link: ({ children }: { children: ReactNode }) => <span>{children}</span>,
}))
vi.mock('react-i18next', () => ({
- useTranslation: () => ({ t: (key: string) => key }),
+ useTranslation: () => ({ t: (key: string) => key, i18n: { language: 'en' } }),
}))
vi.mock('#/hooks/use-app-connection', () => ({
useAppConnection: () => ({
@@ -39,19 +44,22 @@ vi.mock('./skill-picker', () => ({ SkillPicker: () => null }))
vi.mock('#/routes/resources/-components/directory-picker-dialog', () => ({
DirectoryPickerDialog: () => null,
}))
-vi.mock('#/routes/resources/-lib/api', () => ({ fetchFileContent: vi.fn() }))
+vi.mock('#/routes/resources/-lib/api', () => ({
+ fetchFileContent: vi.fn(),
+ fetchFsStat: vi.fn(async () => ({ isDir: true })),
+}))
const storageKey = 'compile-submission:recovery-test'
const clients: QueryClient[] = []
const task = { task_id: 'cmp-original', status: 'pending' }
-function mount() {
+function mount(props: { fromTask?: string; sourceUri?: string } = {}) {
const client = new QueryClient({
defaultOptions: { queries: { retry: false } },
})
clients.push(client)
const page = render(
<QueryClientProvider client={client}>
- <CompileForm />
+ <CompileForm {...props} />
</QueryClientProvider>,
)
return {
@@ -61,9 +69,158 @@ function mount() {
}
beforeEach(() => {
vi.clearAllMocks()
+ api.fetchCapabilities.mockResolvedValue({
+ configured: true,
+ can_create: true,
+ })
localStorage.clear()
sessionStorage.clear()
})
+
+const savedDraft = {
+ skill: 'viking://agent/skills/wiki',
+ sources:
+ 'viking://resources/one\nviking://resources/two\nviking://resources/three',
+ to: 'viking://resources/wiki',
+ instruction: 'Keep citations',
+}
+const draftKey = 'compile-draft:recovery-test'
+
+it('prefills only the current user resource root and preserves the old draft until explicitly restored', () => {
+ localStorage.setItem(draftKey, JSON.stringify(savedDraft))
+ const page = mount()
+ const fields = page.getAllByRole('textbox', { name: 'sourceNumber' })
+ expect(fields).toHaveLength(1)
+ expect((fields[0] as HTMLInputElement).value).toBe(
+ 'viking://user/alice/resources',
+ )
+ expect(JSON.parse(localStorage.getItem(draftKey)!)).toEqual(savedDraft)
+ fireEvent.click(page.getByRole('button', { name: 'restoreDraft' }))
+ expect(
+ page
+ .getAllByRole('textbox', { name: 'sourceNumber' })
+ .map((field) => (field as HTMLInputElement).value),
+ ).toEqual(savedDraft.sources.split('\n'))
+ expect(
+ (page.getByRole('textbox', { name: 'target *' }) as HTMLInputElement).value,
+ ).toBe(savedDraft.to)
+ expect(page.queryByRole('button', { name: 'restoreDraft' })).toBeNull()
+})
+
+it('starts a new draft on editing and keeps clear from restoring previous sources', () => {
+ localStorage.setItem(draftKey, JSON.stringify(savedDraft))
+ const page = mount()
+ fireEvent.change(page.getByRole('textbox', { name: 'sourceNumber' }), {
+ target: { value: 'viking://resources/new' },
+ })
+ expect(JSON.parse(localStorage.getItem(draftKey)!).sources).toBe(
+ 'viking://resources/new',
+ )
+ expect(page.queryByRole('button', { name: 'restoreDraft' })).toBeNull()
+ fireEvent.click(page.getByRole('button', { name: 'clear' }))
+ expect(page.getAllByRole('textbox', { name: 'sourceNumber' })).toHaveLength(1)
+ expect(
+ (page.getByRole('textbox', { name: 'sourceNumber' }) as HTMLInputElement)
+ .value,
+ ).toBe('')
+ expect(JSON.parse(localStorage.getItem(draftKey)!).sources).toBe('')
+})
+
+it('uses only the filesystem entry directory instead of merging old draft sources', () => {
+ localStorage.setItem(draftKey, JSON.stringify(savedDraft))
+ const page = mount({ sourceUri: 'viking://resources/current' })
+ const fields = page.getAllByRole('textbox', { name: 'sourceNumber' })
+ expect(fields).toHaveLength(1)
+ expect((fields[0] as HTMLInputElement).value).toBe(
+ 'viking://resources/current',
+ )
+})
+
+it('still fills all original sources when rerunning an existing task', async () => {
+ api.fetchCompileTask.mockResolvedValueOnce({
+ meta: {
+ request: {
+ skill: savedDraft.skill,
+ from: savedDraft.sources.split('\n'),
+ to: savedDraft.to,
+ },
+ },
+ })
+ const page = mount({ fromTask: 'original-task' })
+ await waitFor(() =>
+ expect(page.getAllByRole('textbox', { name: 'sourceNumber' })).toHaveLength(
+ 3,
+ ),
+ )
+ expect(
+ (page.getByRole('textbox', { name: 'target *' }) as HTMLInputElement).value,
+ ).toBe(savedDraft.to)
+})
+
+it('preserves pending submission parameters ahead of new entry and rerun values', async () => {
+ localStorage.setItem(draftKey, JSON.stringify(savedDraft))
+ sessionStorage.setItem(storageKey, `${Date.now()}:pending`)
+ prepareCompileHandoff(
+ 'recovery-test',
+ 'compile --from viking://resources/handoff --to viking://resources/new --skill viking://agent/skills/new',
+ )
+ api.fetchCompileTask.mockResolvedValueOnce({
+ meta: {
+ request: {
+ skill: 'viking://agent/skills/other',
+ from: ['viking://resources/rerun'],
+ to: 'viking://resources/rerun-output',
+ },
+ },
+ })
+ const page = mount({
+ fromTask: 'different-task',
+ sourceUri: 'viking://resources/current',
+ })
+ await waitFor(() => expect(api.fetchCompileTask).toHaveBeenCalled())
+ expect(
+ page
+ .getAllByRole('textbox', { name: 'sourceNumber' })
+ .map((field) => (field as HTMLInputElement).value),
+ ).toEqual(savedDraft.sources.split('\n'))
+ expect(
+ (page.getByRole('textbox', { name: 'target *' }) as HTMLInputElement).value,
+ ).toBe(savedDraft.to)
+ expect(page.queryByRole('button', { name: 'restoreDraft' })).toBeNull()
+})
+
+it('blocks a direct form submission when execution requirements are not met', async () => {
+ prepareCompileHandoff(
+ 'recovery-test',
+ 'compile --from viking://resources/source --to viking://resources/wiki --skill viking://system/compile/example-skills/llm-wiki',
+ )
+ api.fetchCapabilities.mockResolvedValue({
+ configured: false,
+ can_create: false,
+ })
+ const page = mount()
+ page.submit()
+ await waitFor(() =>
+ expect(
+ page.getByRole('button', { name: 'start' }).hasAttribute('disabled'),
+ ).toBe(true),
+ )
+ expect(api.createCompile).not.toHaveBeenCalled()
+})
+
+it('still recovers an accepted task when execution is no longer configured', async () => {
+ const key = `${Date.now()}:accepted-task`
+ sessionStorage.setItem(storageKey, key)
+ api.fetchCapabilities.mockResolvedValue({
+ configured: false,
+ can_create: false,
+ })
+ api.lookupSubmission.mockResolvedValueOnce(task)
+ const page = mount()
+ page.submit()
+ await waitFor(() => expect(api.navigate).toHaveBeenCalled())
+ expect(api.createCompile).not.toHaveBeenCalled()
+})
afterEach(() => {
cleanup()
clients.splice(0).forEach((client) => client.clear())
diff --git a/web-studio/src/routes/compile/-components/compile-form.tsx b/web-studio/src/routes/compile/-components/compile-form.tsx
index 251bc24be..080f93bc6 100644
--- a/web-studio/src/routes/compile/-components/compile-form.tsx
+++ b/web-studio/src/routes/compile/-components/compile-form.tsx
@@ -6,25 +6,30 @@ import { useQuery } from '@tanstack/react-query'
import { Link, useNavigate, useBlocker } from '@tanstack/react-router'
import { useTranslation } from 'react-i18next'
import { toast } from 'sonner'
+import { EyeIcon } from 'lucide-react'
import { isOvClientError } from '#/lib/ov-client'
import { createRandomUuid } from '#/lib/browser-crypto'
-import { FolderOpen, Plus, X } from 'lucide-react'
import { Button } from '#/components/ui/button'
-import { Input } from '#/components/ui/input'
+import {
+ Dialog,
+ DialogContent,
+ DialogDescription,
+ DialogHeader,
+ DialogTitle,
+ DialogTrigger,
+} from '#/components/ui/dialog'
import { Textarea } from '#/components/ui/textarea'
import { useAppConnection } from '#/hooks/use-app-connection'
-import { DirectoryPickerDialog } from '#/routes/resources/-components/directory-picker-dialog'
-import { fetchFileContent } from '#/routes/resources/-lib/api'
-import {
- createCompile,
- fetchCompileSkills,
- fetchCompileTask,
- lookupSubmission,
-} from '../-lib/api'
+import { fetchFileContent, fetchFsStat } from '#/routes/resources/-lib/api'
+import { createCompile, fetchCompileTask, lookupSubmission } from '../-lib/api'
import type { CompileRequest, CompileTask } from '../-lib/api'
import { compileCommand, parseArgs } from '../-lib/commands'
import { CompileError, CompileShell } from './shared'
import { SkillPicker } from './skill-picker'
+import { CapabilityNotice, useCompileCapability } from './capability-notice'
+import { CompileLocations } from './compile-locations'
+import { useCompileSkills, skillGuide } from '../-lib/skills'
+import { locationLabel, sourceUris, targetError } from '../-lib/locations'
type Draft = { skill: string; sources: string; to: string; instruction: string }
const empty: Draft = { skill: '', sources: '', to: '', instruction: '' }
@@ -41,7 +46,13 @@ function readDraft(key: string): Draft {
return empty
}
}
-export function CompileForm({ fromTask }: { fromTask?: string }) {
+export function CompileForm({
+ fromTask,
+ sourceUri,
+}: {
+ fromTask?: string
+ sourceUri?: string
+}) {
const { t } = useTranslation('compile'),
navigate = useNavigate()
const { identityScopeKey, connection } = useAppConnection()
@@ -49,24 +60,43 @@ export function CompileForm({ fromTask }: { fromTask?: string }) {
const draftKey = `compile-draft:${identityScopeKey}`,
submissionKey = `compile-submission:${identityScopeKey}`
const [handoff] = useState(() => readCompileHandoff(identityScopeKey))
+ const [recoverKey, setRecoverKey] = useState(() => {
+ try {
+ return sessionStorage.getItem(submissionKey)
+ } catch {
+ return null
+ }
+ })
+ const [savedDraft] = useState(() => readDraft(draftKey))
+ const [draftStarted, setDraftStarted] = useState(
+ () => !!(recoverKey || handoff || fromTask || sourceUri),
+ )
useEffect(() => {
clearCompileHandoff()
}, [])
const [draft, setDraft] = useState(() =>
- handoff
- ? {
- skill: handoff.skill || '',
- sources: handoff.from?.join('\n') || '',
- to: handoff.to || '',
- instruction: handoff.instruction || '',
- }
- : readDraft(draftKey),
+ recoverKey
+ ? savedDraft
+ : handoff
+ ? {
+ skill: handoff.skill || '',
+ sources: handoff.from?.join('\n') || '',
+ to: handoff.to || '',
+ instruction: handoff.instruction || '',
+ }
+ : fromTask
+ ? savedDraft
+ : {
+ ...empty,
+ sources: sourceUri || userResourceRoot.replace(/\/$/, ''),
+ },
)
const [args, setArgs] = useState(
- handoff?.args ? JSON.stringify(handoff.args, null, 2) : '',
+ !recoverKey && handoff?.args ? JSON.stringify(handoff.args, null, 2) : '',
),
[preview, setPreview] = useState(false)
- const [picker, setPicker] = useState<'sources' | 'to' | null>(null)
+ const [locationRevision, setLocationRevision] = useState(0)
+ const capability = useCompileCapability()
const [error, setError] = useState<unknown>(null),
[savingError, setSavingError] = useState(false)
const [busy, setBusy] = useState(false),
@@ -77,13 +107,6 @@ export function CompileForm({ fromTask }: { fromTask?: string }) {
const mounted = useRef(true),
completed = useRef(false),
filled = useRef(false)
- const [recoverKey, setRecoverKey] = useState(() => {
- try {
- return sessionStorage.getItem(submissionKey)
- } catch {
- return null
- }
- })
useEffect(() => {
mounted.current = true
return () => {
@@ -98,18 +121,15 @@ export function CompileForm({ fromTask }: { fromTask?: string }) {
enableBeforeUnload: () => !completed.current && !!args.trim(),
})
useEffect(() => {
- if (completed.current) return
+ if (completed.current || !draftStarted) return
try {
localStorage.setItem(draftKey, JSON.stringify(draft))
setSavingError(false)
} catch {
setSavingError(true)
}
- }, [draft, draftKey])
- const skills = useQuery({
- queryKey: ['compile-skills', identityScopeKey],
- queryFn: ({ signal }) => fetchCompileSkills(signal),
- })
+ }, [draft, draftKey, draftStarted])
+ const skills = useCompileSkills()
const original = useQuery({
queryKey: ['compile-task', identityScopeKey, fromTask],
queryFn: ({ signal }) => fetchCompileTask(fromTask!, signal),
@@ -117,13 +137,14 @@ export function CompileForm({ fromTask }: { fromTask?: string }) {
})
useEffect(() => {
const originalRequest = original.data?.meta?.request
- if (!originalRequest || filled.current) return
+ if (!originalRequest || filled.current || recoverKey) return
filled.current = true
if (
Object.values(readDraft(draftKey)).some(Boolean) &&
!window.confirm(t('selectDraft'))
)
return
+ setLocationRevision((value) => value + 1)
setDraft({
skill: originalRequest.skill,
sources: originalRequest.from.join('\n'),
@@ -133,7 +154,7 @@ export function CompileForm({ fromTask }: { fromTask?: string }) {
setArgs(
originalRequest.args ? JSON.stringify(originalRequest.args, null, 2) : '',
)
- }, [original.data, draftKey, t])
+ }, [original.data, draftKey, recoverKey, t])
const skillContent = useQuery({
queryKey: ['compile-skill-content', identityScopeKey, draft.skill],
queryFn: () =>
@@ -141,6 +162,7 @@ export function CompileForm({ fromTask }: { fromTask?: string }) {
enabled: preview && !!draft.skill,
})
function update(key: keyof Draft, value: string) {
+ setDraftStarted(true)
setDraft((v) => ({ ...v, [key]: value }))
}
const [attempted, setAttempted] = useState(false)
@@ -152,11 +174,7 @@ export function CompileForm({ fromTask }: { fromTask?: string }) {
: sourceRows.some((v) => v.trim() && !v.trim().startsWith('viking://'))
? t('invalidUri')
: '',
- to: !draft.to.trim()
- ? t('targetRequired')
- : !draft.to.trim().startsWith('viking://')
- ? t('invalidUri')
- : '',
+ to: targetError(draft.to.trim()) ? t(targetError(draft.to.trim())!) : '',
args: (() => {
try {
parseArgs(args)
@@ -219,8 +237,11 @@ export function CompileForm({ fromTask }: { fromTask?: string }) {
...(parsed ? { args: parsed } : {}),
}
}
+ function isCurrent() {
+ return mounted.current
+ }
async function finish(task: CompileTask) {
- if (!mounted.current) return
+ if (!isCurrent()) return
completed.current = true
try {
localStorage.removeItem(draftKey)
@@ -247,7 +268,7 @@ export function CompileForm({ fromTask }: { fromTask?: string }) {
} catch (cause) {
if (!isOvClientError(cause) || cause.code !== 'NOT_FOUND') throw cause
}
- if (!mounted.current) return
+ if (!isCurrent()) return
const submittedAt = Number(restoredKey.split(':')[0])
if (
!Number.isFinite(submittedAt) ||
@@ -256,6 +277,28 @@ export function CompileForm({ fromTask }: { fromTask?: string }) {
throw new Error(t('expiredSubmission'))
}
if (!submission.current && !validate()) return
+ const checked = await capability.refetch()
+ if (!isCurrent() || checked.isError || !checked.data?.can_create) return
+ if (!submission.current && !restoredKey) {
+ const entries = await Promise.all(
+ sourceUris(draft.sources).map((uri) =>
+ fetchFsStat(uri, { throwOnError: true }),
+ ),
+ )
+ if (!isCurrent()) return
+ if (entries.some((entry) => !entry.isDir))
+ throw new Error(t('sourceNotDirectory'))
+ try {
+ const destination = await fetchFsStat(draft.to.trim(), {
+ throwOnError: true,
+ })
+ if (!destination.isDir) throw new Error(t('targetNotDirectory'))
+ } catch (cause) {
+ // Only a confirmed missing directory is safe to create during execution.
+ if ((cause as { code?: string }).code !== 'NOT_FOUND') throw cause
+ }
+ if (!isCurrent()) return
+ }
const body = submission.current?.request || request()
if (!submission.current)
submission.current = {
@@ -306,9 +349,17 @@ export function CompileForm({ fromTask }: { fromTask?: string }) {
useEffect(() => {
if (error) document.getElementById('compile-error')?.focus()
}, [error])
- const selected = skills.data?.find((s) => s.uri === draft.skill)
+ const selected = skills.data.find((s) => s.uri === draft.skill)
+ const guide = selected ? skillGuide(selected, t) : null
+ const targetLabel = locationLabel(draft.to, userResourceRoot)
+ const skillGroups = [
+ ['builtinSkills', skills.builtin],
+ ['mySkills', skills.mine],
+ ['sharedSkills', skills.shared],
+ ] as const
return (
<CompileShell title={t('new')}>
+ <CapabilityNotice capability={capability} />
{recoverKey && (
<Button
variant="outline"
@@ -346,24 +397,95 @@ export function CompileForm({ fromTask }: { fromTask?: string }) {
}}
className="w-full min-w-0 space-y-5"
>
- <p className="text-sm text-muted-foreground">{t('formIntro')}</p>
+ <div className="flex flex-wrap items-center justify-between gap-2">
+ <p className="text-sm text-muted-foreground">{t('formIntro')}</p>
+ {!draftStarted && Object.values(savedDraft).some(Boolean) && (
+ <Button
+ type="button"
+ variant="ghost"
+ size="sm"
+ disabled={busy || uncertain}
+ onClick={() => {
+ setDraft(savedDraft)
+ setDraftStarted(true)
+ setAttempted(false)
+ setError(null)
+ setLocationRevision((value) => value + 1)
+ }}
+ >
+ {t('restoreDraft')}
+ </Button>
+ )}
+ </div>
<fieldset
disabled={busy || uncertain}
className="space-y-6 rounded-xl border bg-card p-5 disabled:opacity-60 sm:p-6"
>
<section className="space-y-2">
- <label
- htmlFor="compile-skill"
- className="block text-sm font-medium"
- >
- {t('skill')} <span className="text-destructive">*</span>
- </label>
+ <div className="flex items-center justify-between gap-3">
+ <label
+ htmlFor="compile-skill"
+ className="block text-sm font-medium"
+ >
+ {t('skill')} <span className="text-destructive">*</span>
+ </label>
+ {draft.skill && (
+ <Dialog open={preview} onOpenChange={setPreview}>
+ <DialogTrigger
+ render={<Button type="button" variant="ghost" size="sm" />}
+ >
+ <EyeIcon className="size-4" />
+ {t('preview')}
+ </DialogTrigger>
+ <DialogContent className="flex max-h-[80dvh] min-w-0 flex-col gap-0 overflow-hidden p-0 sm:max-w-3xl">
+ <DialogHeader className="shrink-0 border-b py-5 pl-6 pr-14">
+ <DialogTitle className="break-words text-lg leading-snug">
+ {guide?.name || selected?.name || t('preview')}
+ </DialogTitle>
+ <DialogDescription className="break-all text-xs">
+ {draft.skill}
+ </DialogDescription>
+ </DialogHeader>
+ <div className="min-h-0 overflow-auto overscroll-contain px-6 py-5">
+ {skillContent.isPending ? (
+ <p role="status" className="text-muted-foreground">
+ {t('loading')}
+ </p>
+ ) : skillContent.isError ? (
+ <CompileError
+ error={skillContent.error}
+ retry={() => void skillContent.refetch()}
+ />
+ ) : skillContent.data.content ? (
+ <pre className="whitespace-pre-wrap break-words text-xs leading-relaxed">
+ {skillContent.data.content}
+ </pre>
+ ) : (
+ <p className="text-muted-foreground">
+ {t('skillContentEmpty')}
+ </p>
+ )}
+ </div>
+ </DialogContent>
+ </Dialog>
+ )}
+ </div>
<SkillPicker
invalid={attempted && !!fieldErrors.skill}
- disabled={busy || uncertain || skills.isPending}
- loading={skills.isPending}
+ disabled={
+ busy ||
+ uncertain ||
+ (skills.builtin.isPending &&
+ skills.mine.isPending &&
+ skills.shared.isPending)
+ }
+ loading={
+ skills.builtin.isPending ||
+ skills.mine.isPending ||
+ skills.shared.isPending
+ }
value={draft.skill}
- skills={skills.data ?? []}
+ skills={skills.data}
onChange={(uri) => {
update('skill', uri)
setPreview(false)
@@ -373,149 +495,58 @@ export function CompileForm({ fromTask }: { fromTask?: string }) {
<p className="text-xs text-muted-foreground">
{t('skillLocationHint')}
</p>
- {skills.isError && (
- <CompileError
- error={skills.error}
- retry={() => void skills.refetch()}
- />
- )}
- {skills.data?.length === 0 && (
- <Link to="/skills" className="text-sm text-primary underline">
- {t('noSkills')}
- </Link>
+ {skillGroups.map(
+ ([label, query]) =>
+ query.isError && (
+ <div key={label} className="space-y-2">
+ <p className="text-sm">
+ {t('skillGroupFailed', { group: t(label) })}
+ </p>
+ <CompileError
+ error={query.error}
+ retry={() => void query.refetch()}
+ />
+ </div>
+ ),
)}
- {selected && (
- <p className="text-sm text-muted-foreground">
- {selected.description}
+ {!skills.builtin.isPending &&
+ !skills.mine.isPending &&
+ !skills.shared.isPending &&
+ !skills.builtin.isError &&
+ !skills.mine.isError &&
+ !skills.shared.isError &&
+ !skills.data.length && (
+ <p className="text-sm text-muted-foreground">
+ {t('noSkills')}{' '}
+ <Link to="/skills" className="text-primary underline">
+ {t('manageSkills')}
+ </Link>
+ </p>
+ )}
+ {selected?.metadataError && (
+ <p className="text-xs text-muted-foreground">
+ {t('skillMetadataFailed')}{' '}
+ <Button
+ type="button"
+ size="sm"
+ variant="ghost"
+ onClick={() => void skills.builtin.refetch()}
+ >
+ {t('retry')}
+ </Button>
</p>
)}
- {draft.skill && (
- <Button
- type="button"
- variant="ghost"
- size="sm"
- onClick={() => setPreview((v) => !v)}
- >
- {t('preview')}
- </Button>
- )}
- {preview && (
- <div className="max-h-80 overflow-auto rounded-lg border p-4">
- <pre className="whitespace-pre-wrap break-words text-xs">
- {skillContent.data?.content || t('loading')}
- </pre>
- {skillContent.isError && (
- <CompileError error={skillContent.error} />
- )}
- </div>
- )}
- </section>
- <section className="space-y-2 border-t pt-5">
- <label
- htmlFor="compile-sources"
- className="block text-sm font-medium"
- >
- {t('sources')} <span className="text-destructive">*</span>
- </label>
- <p id="source-hint" className="text-xs text-muted-foreground">
- {t('sourceHint')}
- </p>
- <div className="space-y-2">
- {sourceRows.map((uri, index) => (
- <div key={index} className="flex items-center gap-2">
- <Input
- id={
- index === 0
- ? 'compile-sources'
- : `compile-source-${index}`
- }
- aria-label={t('sourceNumber', { number: index + 1 })}
- aria-invalid={attempted && !!fieldErrors.sources}
- aria-describedby="source-hint error-sources"
- placeholder={t('sourcePlaceholder')}
- value={uri}
- className="min-w-0 flex-1 font-mono text-xs"
- onChange={(e) =>
- update(
- 'sources',
- sourceRows
- .map((v, i) => (i === index ? e.target.value : v))
- .join('\n'),
- )
- }
- />
- <Button
- type="button"
- variant="ghost"
- size="icon"
- aria-label={t('removeSource', { uri: uri || index + 1 })}
- onClick={() =>
- update(
- 'sources',
- sourceRows.filter((_, i) => i !== index).join('\n'),
- )
- }
- >
- <X className="size-4" />
- </Button>
- </div>
- ))}
- </div>
- {fieldError('sources')}
- <div className="flex flex-wrap gap-2">
- <Button
- type="button"
- variant="outline"
- size="sm"
- onClick={() => setPicker('sources')}
- >
- <FolderOpen className="size-4" />
- {t('browse')}
- </Button>
- <Button
- type="button"
- variant="ghost"
- size="sm"
- onClick={() =>
- update('sources', [...sourceRows, ''].join('\n'))
- }
- >
- <Plus className="size-4" />
- {t('addSource')}
- </Button>
- </div>
- </section>
- <section className="space-y-2">
- <label
- htmlFor="compile-target"
- className="block text-sm font-medium"
- >
- {t('target')} <span className="text-destructive">*</span>
- </label>
- <div className="flex gap-2">
- <Input
- id="compile-target"
- aria-invalid={attempted && !!fieldErrors.to}
- aria-describedby="target-hint error-to"
- className="min-w-0 flex-1 font-mono text-xs"
- required
- value={draft.to}
- onChange={(e) => update('to', e.target.value)}
- placeholder={t('targetPlaceholder')}
- />
- <Button
- type="button"
- variant="outline"
- onClick={() => setPicker('to')}
- >
- {t('browse')}
- </Button>
- </div>
- {fieldError('to')}
- <p id="target-hint" className="text-xs text-muted-foreground">
- {t('targetHint')}
- </p>
</section>
+ <CompileLocations
+ key={locationRevision}
+ sources={draft.sources}
+ to={draft.to}
+ onSources={(value) => update('sources', value)}
+ onTarget={(value) => update('to', value)}
+ attempted={attempted}
+ sourceError={fieldErrors.sources}
+ destinationError={fieldErrors.to}
+ />
<section className="space-y-2">
<label
htmlFor="compile-instruction"
@@ -538,17 +569,36 @@ export function CompileForm({ fromTask }: { fromTask?: string }) {
<summary className="cursor-pointer rounded text-sm font-medium focus-visible:outline-2 focus-visible:outline-ring">
{t('advanced')}
</summary>
- <ArgsEditor value={args} onChange={setArgs} />
+ <ArgsEditor
+ value={args}
+ onChange={(value) => {
+ setDraftStarted(true)
+ setArgs(value)
+ }}
+ />
<p className="mt-2 text-xs text-muted-foreground">
{t('argsHint')}
</p>
{fieldError('args')}
</details>
</fieldset>
- <div className="sticky bottom-0 space-y-3 border-t bg-background/95 py-4 backdrop-blur">
- <p className="text-xs text-muted-foreground">
- {t(savingError ? 'storageFailed' : 'draft')}
- </p>
+ <div className="sticky bottom-0 space-y-3 border-t bg-background py-4">
+ {draft.skill && sourceUris(draft.sources).length > 0 && draft.to && (
+ <p className="break-words text-sm">
+ {t('submissionSummary', {
+ skill:
+ guide?.name || selected?.name || draft.skill.split('/').pop(),
+ count: sourceUris(draft.sources).length,
+ space: t(targetLabel.scope),
+ folder: targetLabel.path || t('spaceRoot'),
+ })}
+ </p>
+ )}
+ {draftStarted && (
+ <p className="text-xs text-muted-foreground">
+ {t(savingError ? 'storageFailed' : 'draft')}
+ </p>
+ )}
<div className="flex flex-wrap justify-between gap-3">
<Button
type="button"
@@ -574,12 +624,15 @@ export function CompileForm({ fromTask }: { fromTask?: string }) {
variant="ghost"
disabled={busy || uncertain}
onClick={() => {
+ setDraftStarted(true)
setDraft(empty)
+ setLocationRevision((value) => value + 1)
setArgs('')
setAttempted(false)
setError(null)
setPreview(false)
submission.current = null
+ filled.current = true
setRecoverKey(null)
try {
sessionStorage.removeItem(submissionKey)
@@ -590,33 +643,21 @@ export function CompileForm({ fromTask }: { fromTask?: string }) {
>
{t('clear')}
</Button>
- <Button type="submit" disabled={busy}>
+ <Button
+ type="submit"
+ disabled={
+ busy ||
+ (!recoverKey &&
+ !uncertain &&
+ (capability.isError || !capability.data?.can_create))
+ }
+ >
{t(busy ? 'submitting' : uncertain ? 'retry' : 'start')}
</Button>
</div>
</div>
</div>
</form>
- <DirectoryPickerDialog
- identityScopeKey={identityScopeKey}
- userResourceRoot={userResourceRoot}
- open={!!picker}
- onOpenChange={(open) => {
- if (!open) setPicker(null)
- }}
- value={picker === 'to' && draft.to ? draft.to : userResourceRoot}
- onSelect={(uri) => {
- if (picker === 'to') update('to', uri)
- else
- update(
- 'sources',
- [
- ...new Set([...draft.sources.split('\n').filter(Boolean), uri]),
- ].join('\n'),
- )
- setPicker(null)
- }}
- />
</CompileShell>
)
}
diff --git a/web-studio/src/routes/compile/-components/compile-locations.test.tsx b/web-studio/src/routes/compile/-components/compile-locations.test.tsx
new file mode 100644
index 000000000..8ea242f62
--- /dev/null
+++ b/web-studio/src/routes/compile/-components/compile-locations.test.tsx
@@ -0,0 +1,190 @@
+// @vitest-environment jsdom
+import { useState } from 'react'
+import { afterEach, beforeEach, expect, it, vi } from 'vitest'
+import { cleanup, fireEvent, render, waitFor } from '@testing-library/react'
+import { QueryClient, QueryClientProvider } from '@tanstack/react-query'
+import { CompileLocations } from './compile-locations'
+
+const stat = vi.hoisted(() => vi.fn())
+const clipboard = vi.hoisted(() => ({
+ copy: vi.fn(),
+ success: vi.fn(),
+ error: vi.fn(),
+}))
+vi.mock('#/lib/clipboard', () => ({ copyTextToClipboard: clipboard.copy }))
+vi.mock('sonner', () => ({ toast: clipboard }))
+vi.mock('#/routes/resources/-lib/api', () => ({ fetchFsStat: stat }))
+vi.mock('react-i18next', () => ({
+ useTranslation: () => ({ t: (key: string) => key }),
+}))
+vi.mock('#/hooks/use-app-connection', () => ({
+ useAppConnection: () => ({
+ identityScopeKey: 'alice',
+ connection: { userId: 'alice' },
+ }),
+}))
+vi.mock('@tanstack/react-router', () => ({
+ Link: ({ children }: { children: React.ReactNode }) => <a>{children}</a>,
+}))
+vi.mock('./shared', () => ({
+ CompileError: () => <p role="alert">Read failed</p>,
+}))
+vi.mock('#/routes/resources/-components/directory-picker-dialog', () => ({
+ DirectoryPickerDialog: ({
+ open,
+ onSelect,
+ onOpenChange,
+ }: {
+ open: boolean
+ onSelect: (uri: string) => void
+ onOpenChange: (open: boolean) => void
+ }) =>
+ open ? (
+ <div>
+ <button onClick={() => onSelect('viking://resources/project/')}>
+ Select project
+ </button>
+ <button onClick={() => onOpenChange(false)}>Cancel selection</button>
+ </div>
+ ) : null,
+}))
+
+const clients: QueryClient[] = []
+function Form({ initialSources }: { initialSources: string }) {
+ const [sources, setSources] = useState(initialSources)
+ const [to, setTo] = useState('')
+ return (
+ <>
+ <CompileLocations
+ sources={sources}
+ to={to}
+ onSources={setSources}
+ onTarget={setTo}
+ attempted={false}
+ sourceError=""
+ destinationError=""
+ />
+ <output data-testid="destination">{to}</output>
+ <output data-testid="sources">{sources}</output>
+ </>
+ )
+}
+function mount(initialSources = '') {
+ const client = new QueryClient({
+ defaultOptions: { queries: { retry: false } },
+ })
+ clients.push(client)
+ return render(
+ <QueryClientProvider client={client}>
+ <Form initialSources={initialSources} />
+ </QueryClientProvider>,
+ )
+}
+beforeEach(() => {
+ vi.clearAllMocks()
+ stat.mockReset().mockResolvedValue({ isDir: true })
+ clipboard.copy.mockReset().mockResolvedValue(undefined)
+})
+afterEach(() => {
+ cleanup()
+ clients.splice(0).forEach((client) => client.clear())
+})
+
+it('browses for a destination and allows editing a new folder path', async () => {
+ stat.mockRejectedValue(
+ Object.assign(new Error('Missing'), { code: 'NOT_FOUND' }),
+ )
+ const page = mount()
+ fireEvent.click(page.getAllByRole('button', { name: 'browse' })[1])
+ fireEvent.click(page.getByText('Select project'))
+ expect(page.getByTestId('destination').textContent).toBe(
+ 'viking://resources/project',
+ )
+ fireEvent.change(page.getByRole('textbox', { name: 'target *' }), {
+ target: { value: 'viking://resources/project/项目知识库' },
+ })
+ expect(page.getByTestId('destination').textContent).toBe(
+ 'viking://resources/project/项目知识库',
+ )
+ await waitFor(() => expect(page.getByText('targetNew')).toBeTruthy())
+})
+
+it('does not describe permission failures as a new folder', async () => {
+ stat.mockRejectedValue(
+ Object.assign(new Error('Denied'), { code: 'PERMISSION_DENIED' }),
+ )
+ const page = mount()
+ fireEvent.change(page.getByRole('textbox', { name: 'target *' }), {
+ target: { value: 'viking://resources/private' },
+ })
+ await waitFor(() => expect(page.getByRole('alert')).toBeTruthy())
+ expect(page.queryByText('targetNew')).toBeNull()
+})
+
+it('edits multiple path rows and removes them independently', () => {
+ const page = mount('viking://resources/first')
+ fireEvent.click(page.getByRole('button', { name: 'addSource' }))
+ const inputs = page.getAllByRole('textbox', { name: 'sourceNumber' })
+ expect(inputs).toHaveLength(2)
+ fireEvent.change(inputs[1], {
+ target: { value: 'viking://resources/second' },
+ })
+ expect(page.getByTestId('sources').textContent).toBe(
+ 'viking://resources/first\nviking://resources/second',
+ )
+ fireEvent.click(page.getAllByRole('button', { name: 'removeSource' })[0])
+ expect(page.getByTestId('sources').textContent).toBe(
+ 'viking://resources/second',
+ )
+})
+
+it('appends browsed folders without duplicates and preserves paths on cancel', () => {
+ const page = mount('viking://user/alice/resources/notes')
+ const browse = page.getAllByRole('button', { name: 'browse' })[0]
+ fireEvent.click(browse)
+ fireEvent.click(page.getByText('Select project'))
+ const selected =
+ 'viking://user/alice/resources/notes\nviking://resources/project'
+ expect(page.getByTestId('sources').textContent).toBe(selected)
+ fireEvent.click(browse)
+ fireEvent.click(page.getByText('Select project'))
+ expect(page.getByTestId('sources').textContent).toBe(selected)
+ fireEvent.click(browse)
+ fireEvent.click(page.getByText('Cancel selection'))
+ expect(page.getByTestId('sources').textContent).toBe(selected)
+})
+
+it('copies complete current paths without changing the form', async () => {
+ const uri = 'viking://resources/项目/会议记录'
+ const page = mount(uri)
+ const destination = 'viking://resources/知识库'
+ fireEvent.change(page.getByRole('textbox', { name: 'target *' }), {
+ target: { value: destination },
+ })
+ fireEvent.click(page.getByRole('button', { name: `copyPath ${uri}` }))
+ fireEvent.click(page.getByRole('button', { name: `copyPath ${destination}` }))
+ expect(clipboard.copy.mock.calls).toEqual([[uri], [destination]])
+ await waitFor(() => expect(clipboard.success).toHaveBeenCalledTimes(2))
+ expect(page.getByTestId('sources').textContent).toBe(uri)
+ expect(page.getByTestId('destination').textContent).toBe(destination)
+})
+
+it('disables empty-path copy and reports clipboard failure without success', async () => {
+ const page = mount()
+ expect(
+ page
+ .getAllByRole('button', { name: 'copyPath' })
+ .every((button) => button.hasAttribute('disabled')),
+ ).toBe(true)
+ clipboard.copy.mockRejectedValue(new Error('Clipboard unavailable'))
+ fireEvent.change(page.getByRole('textbox', { name: 'sourceNumber' }), {
+ target: { value: 'viking://resources/notes' },
+ })
+ fireEvent.click(
+ page.getByRole('button', { name: 'copyPath viking://resources/notes' }),
+ )
+ await waitFor(() =>
+ expect(clipboard.error).toHaveBeenCalledWith('copyFailed'),
+ )
+ expect(clipboard.success).not.toHaveBeenCalled()
+})
diff --git a/web-studio/src/routes/compile/-components/compile-locations.tsx b/web-studio/src/routes/compile/-components/compile-locations.tsx
new file mode 100644
index 000000000..005fe54ef
--- /dev/null
+++ b/web-studio/src/routes/compile/-components/compile-locations.tsx
@@ -0,0 +1,244 @@
+import { useEffect, useState } from 'react'
+import { useQuery } from '@tanstack/react-query'
+import { Link } from '@tanstack/react-router'
+import { Copy, FolderOpen, Plus, X } from 'lucide-react'
+import { useTranslation } from 'react-i18next'
+import { toast } from 'sonner'
+import { Button } from '#/components/ui/button'
+import { Input } from '#/components/ui/input'
+import { useAppConnection } from '#/hooks/use-app-connection'
+import { copyTextToClipboard } from '#/lib/clipboard'
+import { DirectoryPickerDialog } from '#/routes/resources/-components/directory-picker-dialog'
+import { fetchFsStat } from '#/routes/resources/-lib/api'
+import { sourceUris, targetError } from '../-lib/locations'
+import { CompileError } from './shared'
+
+function CopyPathButton({ value }: { value: string }) {
+ const { t } = useTranslation('compile')
+ return (
+ <Button
+ type="button"
+ variant="ghost"
+ size="icon-sm"
+ className="absolute right-1 top-1/2 -translate-y-1/2 text-muted-foreground"
+ title={t('copyPath')}
+ aria-label={`${t('copyPath')} ${value.trim()}`.trim()}
+ disabled={!value.trim()}
+ onClick={() => {
+ void copyTextToClipboard(value.trim())
+ .then(() => toast.success(t('copied')))
+ .catch(() => toast.error(t('copyFailed')))
+ }}
+ >
+ <Copy className="size-4" />
+ </Button>
+ )
+}
+
+export function CompileLocations({
+ sources,
+ to,
+ onSources,
+ onTarget,
+ attempted,
+ sourceError,
+ destinationError,
+}: {
+ sources: string
+ to: string
+ onSources: (value: string) => void
+ onTarget: (value: string) => void
+ attempted: boolean
+ sourceError: string
+ destinationError: string
+}) {
+ const { t } = useTranslation('compile')
+ const { identityScopeKey, connection } = useAppConnection()
+ const userRoot = `viking://user/${connection.userId || 'default'}/resources/`
+ const [picker, setPicker] = useState<'source' | 'target' | null>(null)
+ const rows = sources ? sources.split('\n') : ['']
+ const [checkedTarget, setCheckedTarget] = useState(to)
+ useEffect(() => {
+ const timer = setTimeout(() => setCheckedTarget(to), 350)
+ return () => clearTimeout(timer)
+ }, [to])
+ const target = useQuery({
+ queryKey: ['compile-target-stat', identityScopeKey, checkedTarget],
+ queryFn: () => fetchFsStat(checkedTarget, { throwOnError: true }),
+ enabled: !targetError(checkedTarget),
+ retry: false,
+ })
+ const notFound =
+ target.isError && (target.error as { code?: string }).code === 'NOT_FOUND'
+ return (
+ <>
+ <section
+ className="space-y-2 border-t pt-5"
+ aria-labelledby="compile-sources-heading"
+ >
+ <label
+ id="compile-sources-heading"
+ htmlFor="compile-sources"
+ className="block text-sm font-medium"
+ >
+ {t('sources')} <span className="text-destructive">*</span>
+ </label>
+ <p id="source-hint" className="text-xs text-muted-foreground">
+ {t('sourceHint')}
+ </p>
+ <div className="space-y-2">
+ {rows.map((uri, index) => (
+ <div key={index} className="flex items-center gap-2">
+ <div className="relative min-w-0 flex-1">
+ <Input
+ id={
+ index === 0 ? 'compile-sources' : `compile-source-${index}`
+ }
+ aria-label={t('sourceNumber', { number: index + 1 })}
+ aria-invalid={attempted && !!sourceError}
+ aria-describedby="source-hint error-sources"
+ placeholder={t('sourcePlaceholder')}
+ value={uri}
+ className="pr-10 font-mono text-xs"
+ onChange={(event) =>
+ onSources(
+ rows
+ .map((value, i) =>
+ i === index ? event.target.value : value,
+ )
+ .join('\n'),
+ )
+ }
+ />
+ <CopyPathButton value={uri} />
+ </div>
+ <Button
+ type="button"
+ variant="ghost"
+ size="icon"
+ aria-label={t('removeSource', { uri: uri || index + 1 })}
+ onClick={() =>
+ onSources(rows.filter((_, i) => i !== index).join('\n'))
+ }
+ >
+ <X className="size-4" />
+ </Button>
+ </div>
+ ))}
+ </div>
+ {attempted && sourceError && (
+ <p
+ id="error-sources"
+ role="alert"
+ className="text-xs text-destructive"
+ >
+ {sourceError}
+ </p>
+ )}
+ <div className="flex flex-wrap gap-2">
+ <Button
+ type="button"
+ variant="outline"
+ size="sm"
+ onClick={() => setPicker('source')}
+ >
+ <FolderOpen className="size-4" />
+ {t('browse')}
+ </Button>
+ <Button
+ type="button"
+ variant="ghost"
+ size="sm"
+ onClick={() => onSources([...rows, ''].join('\n'))}
+ >
+ <Plus className="size-4" />
+ {t('addSource')}
+ </Button>
+ </div>
+ </section>
+ <section className="space-y-2" aria-labelledby="compile-target-heading">
+ <label
+ id="compile-target-heading"
+ htmlFor="compile-target"
+ className="block text-sm font-medium"
+ >
+ {t('target')} <span className="text-destructive">*</span>
+ </label>
+ <div className="flex gap-2">
+ <div className="relative min-w-0 flex-1">
+ <Input
+ id="compile-target"
+ aria-invalid={attempted && !!destinationError}
+ aria-describedby="target-hint error-to"
+ className="pr-10 font-mono text-xs"
+ required
+ value={to}
+ onChange={(event) => onTarget(event.target.value)}
+ placeholder={t('targetPlaceholder')}
+ />
+ <CopyPathButton value={to} />
+ </div>
+ <Button
+ type="button"
+ variant="outline"
+ onClick={() => setPicker('target')}
+ >
+ {t('browse')}
+ </Button>
+ </div>
+ {attempted && destinationError && (
+ <p id="error-to" role="alert" className="text-xs text-destructive">
+ {destinationError}
+ </p>
+ )}
+ <div
+ id="target-hint"
+ className="text-xs text-muted-foreground"
+ role="status"
+ >
+ {targetError(to) ? (
+ t('targetHint')
+ ) : checkedTarget !== to || target.isPending ? (
+ t('checkingTarget')
+ ) : notFound ? (
+ t('targetNew')
+ ) : target.isError ? (
+ <CompileError
+ error={target.error}
+ retry={() => void target.refetch()}
+ />
+ ) : target.data.isDir ? (
+ t('targetExists')
+ ) : (
+ t('targetNotDirectory')
+ )}
+ </div>
+ </section>
+ <DirectoryPickerDialog
+ identityScopeKey={identityScopeKey}
+ userResourceRoot={userRoot}
+ open={!!picker}
+ onOpenChange={(open) => {
+ if (!open) setPicker(null)
+ }}
+ value={picker === 'target' && to ? to : userRoot}
+ emptyAction={
+ picker === 'source' ? (
+ <Link
+ to="/filesystem"
+ search={{ uri: userRoot }}
+ className="text-sm text-primary underline underline-offset-4"
+ >
+ {t('openFilesystem')}
+ </Link>
+ ) : undefined
+ }
+ onSelect={(uri) => {
+ if (picker === 'target') onTarget(uri.replace(/\/$/, ''))
+ else onSources(sourceUris([...rows, uri].join('\n')).join('\n'))
+ setPicker(null)
+ }}
+ />
+ </>
+ )
+}
diff --git a/web-studio/src/routes/compile/-components/context-link.test.tsx b/web-studio/src/routes/compile/-components/context-link.test.tsx
index e16ef1e96..fe8b8c645 100644
--- a/web-studio/src/routes/compile/-components/context-link.test.tsx
+++ b/web-studio/src/routes/compile/-components/context-link.test.tsx
@@ -19,10 +19,16 @@ const api = vi.hoisted(() => ({
fetchCompileSkills: vi.fn(),
fetchFsStat: vi.fn(),
}))
-vi.mock('../-lib/api', () => ({ fetchCompileSkills: api.fetchCompileSkills }))
+vi.mock('../-lib/api', () => ({
+ BUILTIN_SKILLS_ROOT: 'viking://system/compile/example-skills',
+ fetchCompileSkills: api.fetchCompileSkills,
+}))
vi.mock('#/routes/resources/-lib/api', () => ({ fetchFsStat: api.fetchFsStat }))
vi.mock('#/hooks/use-app-connection', () => ({
- useAppConnection: () => ({ identityScopeKey: 'alice' }),
+ useAppConnection: () => ({
+ identityScopeKey: 'alice',
+ connection: { userId: 'alice' },
+ }),
}))
vi.mock('@tanstack/react-router', () => ({
Link: ({
diff --git a/web-studio/src/routes/compile/-components/context-link.tsx b/web-studio/src/routes/compile/-components/context-link.tsx
index 5f7808058..f55a54489 100644
--- a/web-studio/src/routes/compile/-components/context-link.tsx
+++ b/web-studio/src/routes/compile/-components/context-link.tsx
@@ -6,22 +6,20 @@ import { useAppConnection } from '#/hooks/use-app-connection'
import { fetchFsStat } from '#/routes/resources/-lib/api'
import { parentUri } from '#/lib/viking-uri'
import { cn } from '#/lib/utils'
-import { fetchCompileSkills } from '../-lib/api'
+import { skillGuide, useCompileSkills } from '../-lib/skills'
export const contextName = (uri: string) =>
uri.split('/').filter(Boolean).pop() || uri
export function useCompileSkillName() {
- const { identityScopeKey } = useAppConnection()
- const { data } = useQuery({
- queryKey: ['compile-skills', identityScopeKey],
- queryFn: ({ signal }) => fetchCompileSkills(signal),
- staleTime: 30_000,
- })
- return (uri: string) =>
- data?.find(
- (skill) => skill.uri.replace(/\/$/, '') === uri.replace(/\/$/, ''),
- )?.name || contextName(uri)
+ const { t } = useTranslation('compile')
+ const { data } = useCompileSkills()
+ return (uri: string) => {
+ const skill = data.find(
+ (item) => item.uri.replace(/\/$/, '') === uri.replace(/\/$/, ''),
+ )
+ return skill ? skillGuide(skill, t)?.name || skill.name : contextName(uri)
+ }
}
export function ContextLink({
diff --git a/web-studio/src/routes/compile/-components/skill-picker.test.tsx b/web-studio/src/routes/compile/-components/skill-picker.test.tsx
new file mode 100644
index 000000000..5f62bf126
--- /dev/null
+++ b/web-studio/src/routes/compile/-components/skill-picker.test.tsx
@@ -0,0 +1,68 @@
+// @vitest-environment jsdom
+import { afterEach, expect, it, vi } from 'vitest'
+import { cleanup, render, screen, within } from '@testing-library/react'
+import userEvent from '@testing-library/user-event'
+import type * as ReactI18next from 'react-i18next'
+import { SkillPicker } from './skill-picker'
+import zh from '#/i18n/locales/zh-CN/compile'
+
+vi.mock('react-i18next', async (importOriginal) => ({
+ ...(await importOriginal<typeof ReactI18next>()),
+ useTranslation: () => ({
+ t: (key: string) =>
+ key.split('.').reduce((value: any, part) => value?.[part], zh) ?? key,
+ }),
+}))
+
+const skills = [
+ {
+ uri: 'viking://system/compile/example-skills/llm-wiki',
+ name: 'llm-wiki',
+ description: '',
+ },
+ {
+ uri: 'viking://system/compile/example-skills/ov-session-report',
+ name: 'ov-session-report',
+ description: '',
+ },
+ {
+ uri: 'viking://user/alice/skills/custom',
+ name: 'Custom',
+ description: 'My custom skill',
+ },
+]
+
+afterEach(cleanup)
+
+it('previews requirements using the keyboard without selecting until Enter', async () => {
+ const onChange = vi.fn()
+ const user = userEvent.setup()
+ render(<SkillPicker skills={skills} value="" onChange={onChange} />)
+ await user.tab()
+ await user.keyboard('{ArrowDown}')
+ const search = await screen.findByRole('combobox', { name: '搜索 Skill' })
+ await user.type(search, '会话')
+ await user.keyboard('{ArrowDown}')
+ const details = within(screen.getByRole('region', { name: '能力说明' }))
+ expect(details.getByText(/sessions_root/)).toBeTruthy()
+ expect(details.getByText(/默认输出英文/)).toBeTruthy()
+ expect(onChange).not.toHaveBeenCalled()
+ expect(screen.getByRole('option').textContent).not.toContain('sessions_root')
+ await user.keyboard('{Enter}')
+ expect(onChange).toHaveBeenCalledWith(skills[1].uri)
+})
+
+it('does not show stale skill details when search has no matches', async () => {
+ const user = userEvent.setup()
+ render(
+ <SkillPicker skills={skills} value={skills[0].uri} onChange={vi.fn()} />,
+ )
+ await user.tab()
+ await user.keyboard('{ArrowDown}')
+ await user.type(
+ await screen.findByRole('combobox', { name: '搜索 Skill' }),
+ 'no-such-skill',
+ )
+ expect(screen.getByText(zh.noMatchingSkills)).toBeTruthy()
+ expect(screen.queryByRole('region', { name: '能力说明' })).toBeNull()
+})
diff --git a/web-studio/src/routes/compile/-components/skill-picker.tsx b/web-studio/src/routes/compile/-components/skill-picker.tsx
index f9d0d306a..c3cbcd854 100644
--- a/web-studio/src/routes/compile/-components/skill-picker.tsx
+++ b/web-studio/src/routes/compile/-components/skill-picker.tsx
@@ -1,7 +1,9 @@
import { Combobox } from '@base-ui/react/combobox'
-import { Check, ChevronsUpDown } from 'lucide-react'
+import { Check, ChevronsUpDown, Search } from 'lucide-react'
+import { useState } from 'react'
import { useTranslation } from 'react-i18next'
import type { CompileSkill } from '../-lib/api'
+import { skillGuide, skillScope } from '../-lib/skills'
export function SkillPicker({
value,
@@ -19,6 +21,8 @@ export function SkillPicker({
onChange: (uri: string) => void
}) {
const { t } = useTranslation('compile')
+ const [highlighted, setHighlighted] = useState<CompileSkill>()
+ const [query, setQuery] = useState('')
const selected =
skills.find((skill) => skill.uri === value) ??
(value ? { uri: value, name: value, description: '' } : null)
@@ -27,6 +31,10 @@ export function SkillPicker({
? [selected, ...skills]
: skills
const groups = [
+ {
+ label: t('builtinSkills'),
+ items: items.filter((s) => skillScope(s.uri) === 'builtinSkills'),
+ },
{
label: t('mySkills'),
items: items.filter((s) => s.uri.startsWith('viking://user/')),
@@ -40,24 +48,41 @@ export function SkillPicker({
items: items.filter(
(s) =>
!s.uri.startsWith('viking://user/') &&
- !s.uri.startsWith('viking://agent/skills/'),
+ !s.uri.startsWith('viking://agent/skills/') &&
+ skillScope(s.uri) !== 'builtinSkills',
),
},
].filter((group) => group.items.length)
+ function matches(skill: CompileSkill, search: string) {
+ const guide = skillGuide(skill, t)
+ return `${guide?.name || ''} ${guide?.description || ''} ${skill.name} ${skill.description} ${skill.uri}`
+ .toLowerCase()
+ .includes(search.trim().toLowerCase())
+ }
+ const matchingItems = items.filter((skill) => matches(skill, query))
+ const preview =
+ matchingItems.find((skill) => skill.uri === highlighted?.uri) ??
+ matchingItems.find((skill) => skill.uri === selected?.uri) ??
+ matchingItems.at(0)
+ const previewGuide = preview ? skillGuide(preview, t) : null
return (
<Combobox.Root
items={groups}
disabled={disabled}
value={selected}
+ onOpenChange={() => {
+ setHighlighted(undefined)
+ setQuery('')
+ }}
+ onInputValueChange={setQuery}
+ onItemHighlighted={(skill) => {
+ if (skill) setHighlighted(skill)
+ }}
onValueChange={(skill) => onChange(skill?.uri ?? '')}
- itemToStringLabel={(skill) => skill.name}
+ itemToStringLabel={(skill) => skillGuide(skill, t)?.name || skill.name}
itemToStringValue={(skill) => skill.uri}
isItemEqualToValue={(a, b) => a.uri === b.uri}
- filter={(skill, query) =>
- `${skill.name} ${skill.description} ${skill.uri}`
- .toLowerCase()
- .includes(query.trim().toLowerCase())
- }
+ filter={matches}
>
<Combobox.Trigger
id="compile-skill"
@@ -65,52 +90,120 @@ export function SkillPicker({
aria-describedby="error-skill"
className="flex h-10 w-full items-center justify-between gap-2 rounded-md border bg-background px-3 text-left text-sm focus-visible:outline-2 focus-visible:outline-ring disabled:opacity-50"
>
- <span className="truncate">
- {selected
- ? `${selected.name} · ${selected.uri.startsWith('viking://user/') ? t('mySkills') : t('sharedSkills')}`
- : t(loading ? 'loading' : 'chooseSkill')}
+ <span className="flex min-w-0 items-center gap-2">
+ <span className="truncate">
+ {selected
+ ? skillGuide(selected, t)?.name || selected.name
+ : t(loading ? 'loading' : 'chooseSkill')}
+ </span>
+ {selected && (
+ <span className="shrink-0 rounded bg-muted px-1.5 py-0.5 text-xs text-muted-foreground">
+ {t(skillScope(selected.uri))}
+ </span>
+ )}
</span>
<ChevronsUpDown className="size-4 shrink-0 text-muted-foreground" />
</Combobox.Trigger>
<Combobox.Portal>
- <Combobox.Positioner sideOffset={4} align="start" className="z-50">
- <Combobox.Popup className="w-[var(--anchor-width)] max-w-[calc(100vw-2rem)] rounded-md border bg-popover p-1 text-popover-foreground shadow-md">
- <Combobox.Input
- aria-label={t('skillSearch')}
- placeholder={t('skillSearch')}
- className="h-10 w-full border-b bg-transparent px-3 text-sm outline-none"
- />
- <Combobox.Empty className="p-3 text-sm text-muted-foreground">
+ <Combobox.Positioner sideOffset={6} align="start" className="z-50">
+ <Combobox.Popup className="flex max-h-[min(36rem,var(--available-height))] w-[40rem] max-w-[calc(100vw-2rem)] flex-col overflow-hidden rounded-lg bg-popover text-popover-foreground shadow-lg ring-1 ring-foreground/10">
+ <div className="flex shrink-0 items-center gap-2 border-b px-3">
+ <Search
+ aria-hidden
+ className="size-4 shrink-0 text-muted-foreground"
+ />
+ <Combobox.Input
+ aria-label={t('skillSearch')}
+ placeholder={t('skillSearch')}
+ className="h-10 min-w-0 flex-1 bg-transparent text-sm outline-none placeholder:text-muted-foreground"
+ />
+ </div>
+ <Combobox.Empty className="p-3 text-sm text-muted-foreground empty:hidden">
{t('noMatchingSkills')}
</Combobox.Empty>
- <Combobox.List className="max-h-64 overflow-y-auto overscroll-contain">
- {(group: { label: string; items: CompileSkill[] }) => (
- <Combobox.Group key={group.label} items={group.items}>
- <Combobox.GroupLabel className="px-3 pt-3 pb-1 text-xs font-medium text-muted-foreground">
- {group.label}
- </Combobox.GroupLabel>
- <Combobox.Collection>
- {(skill: CompileSkill) => (
- <Combobox.Item
- key={skill.uri}
- value={skill}
- className="flex cursor-pointer items-center gap-2 rounded px-3 py-2 text-sm data-highlighted:bg-accent data-highlighted:text-accent-foreground"
- >
- <div className="min-w-0 flex-1">
- <div className="truncate">{skill.name}</div>
- <div className="break-all text-xs text-muted-foreground">
- {skill.uri}
- </div>
- </div>
- <Combobox.ItemIndicator>
- <Check className="size-4" />
- </Combobox.ItemIndicator>
- </Combobox.Item>
+ <div className="grid min-h-0 overflow-y-auto sm:grid-cols-2 sm:overflow-hidden">
+ <Combobox.List className="max-h-64 overflow-y-auto overscroll-contain p-1 sm:max-h-80">
+ {(group: { label: string; items: CompileSkill[] }) => (
+ <Combobox.Group key={group.label} items={group.items}>
+ <Combobox.GroupLabel className="px-2 pt-2 pb-1 text-xs font-medium text-muted-foreground">
+ {group.label}
+ </Combobox.GroupLabel>
+ <Combobox.Collection>
+ {(skill: CompileSkill) => {
+ const guide = skillGuide(skill, t)
+ return (
+ <Combobox.Item
+ key={skill.uri}
+ value={skill}
+ className="flex cursor-pointer items-center gap-2 rounded-md px-2 py-2.5 text-sm data-highlighted:bg-accent data-highlighted:text-accent-foreground"
+ >
+ <div className="min-w-0 flex-1">
+ <div className="truncate font-medium">
+ {guide?.name || skill.name}
+ </div>
+ <div className="mt-0.5 truncate text-xs text-muted-foreground">
+ {guide?.description ||
+ skill.description ||
+ t('skillDescriptionUnavailable')}
+ </div>
+ </div>
+ <span className="size-4 shrink-0">
+ <Combobox.ItemIndicator>
+ <Check className="size-4" />
+ </Combobox.ItemIndicator>
+ </span>
+ </Combobox.Item>
+ )
+ }}
+ </Combobox.Collection>
+ </Combobox.Group>
+ )}
+ </Combobox.List>
+ {preview && (
+ <section
+ aria-label={t('skillPreview')}
+ className="max-h-64 overflow-y-auto overscroll-contain border-t bg-muted/30 p-4 text-xs leading-relaxed sm:max-h-80 sm:border-t-0 sm:border-l"
+ >
+ <header className="space-y-2">
+ <h3 className="break-words text-lg font-semibold leading-snug">
+ {previewGuide?.name || preview.name}
+ </h3>
+ <p className="break-words text-muted-foreground">
+ {previewGuide?.description ||
+ preview.description ||
+ t('skillDescriptionUnavailable')}
+ </p>
+ {previewGuide?.specialized && (
+ <p className="text-muted-foreground">
+ {t('specializedSkill')}
+ </p>
)}
- </Combobox.Collection>
- </Combobox.Group>
+ </header>
+ {previewGuide && (
+ <dl className="mt-4 space-y-4 border-t pt-4">
+ <div className="grid grid-cols-[4rem_minmax(0,1fr)] gap-x-3">
+ <dt className="text-muted-foreground">
+ {t('suitableInputs')}
+ </dt>
+ <dd>{previewGuide.inputs}</dd>
+ </div>
+ <div className="grid grid-cols-[4rem_minmax(0,1fr)] gap-x-3">
+ <dt className="text-muted-foreground">
+ {t('expectedOutputs')}
+ </dt>
+ <dd>{previewGuide.outputs}</dd>
+ </div>
+ <div className="grid grid-cols-[4rem_minmax(0,1fr)] gap-x-3">
+ <dt className="text-muted-foreground">
+ {t('usageLimits')}
+ </dt>
+ <dd>{previewGuide.limits}</dd>
+ </div>
+ </dl>
+ )}
+ </section>
)}
- </Combobox.List>
+ </div>
</Combobox.Popup>
</Combobox.Positioner>
</Combobox.Portal>
diff --git a/web-studio/src/routes/compile/-lib/api.test.ts b/web-studio/src/routes/compile/-lib/api.test.ts
index 2f7dd1526..8d43102ce 100644
--- a/web-studio/src/routes/compile/-lib/api.test.ts
+++ b/web-studio/src/routes/compile/-lib/api.test.ts
@@ -1,6 +1,11 @@
import { beforeEach, describe, expect, it, vi } from 'vitest'
-import { fetchCompileTask, fetchCompileTasks } from './api'
+import {
+ BUILTIN_SKILLS_ROOT,
+ fetchCompileSkills,
+ fetchCompileTask,
+ fetchCompileTasks,
+} from './api'
const clientMocks = vi.hoisted(() => ({
get: vi.fn(),
@@ -55,3 +60,63 @@ describe('compile task API normalization', () => {
expect(task.meta?.request?.from).toEqual([])
})
})
+
+describe('built-in skill discovery', () => {
+ it('discovers server-provided skills and reads file-only metadata, including unknown skills', async () => {
+ clientMocks.get.mockImplementation(async ({ url, query }) => {
+ if (url === '/api/v1/skills') {
+ expect(query.target_uri).toBe(BUILTIN_SKILLS_ROOT)
+ return {
+ skills: [
+ {
+ name: 'future-tool',
+ root_uri: `${BUILTIN_SKILLS_ROOT}/future-tool`,
+ },
+ ],
+ }
+ }
+ return {
+ content:
+ '---\nname: future-tool\ndescription: A new server-provided capability.\n---\nBody',
+ }
+ })
+ expect(await fetchCompileSkills(undefined, BUILTIN_SKILLS_ROOT)).toEqual([
+ {
+ name: 'future-tool',
+ uri: `${BUILTIN_SKILLS_ROOT}/future-tool`,
+ description: 'A new server-provided capability.',
+ },
+ ])
+ })
+
+ it('keeps other skills when one definition is unreadable', async () => {
+ clientMocks.get
+ .mockResolvedValueOnce({
+ skills: [
+ {
+ name: 'ready',
+ uri: `${BUILTIN_SKILLS_ROOT}/ready`,
+ description: 'Ready to use',
+ },
+ { name: 'unreadable', uri: `${BUILTIN_SKILLS_ROOT}/unreadable` },
+ ],
+ })
+ .mockRejectedValueOnce(new Error('Unavailable'))
+ const result = await fetchCompileSkills(undefined, BUILTIN_SKILLS_ROOT)
+ expect(result).toHaveLength(2)
+ expect(result[0].description).toBe('Ready to use')
+ expect(result[1].metadataError).toBe(true)
+ })
+
+ it('does not start definition reads after a connection abort', async () => {
+ const controller = new AbortController()
+ clientMocks.get.mockImplementationOnce(async () => {
+ controller.abort()
+ return { skills: [{ name: 'wiki', uri: `${BUILTIN_SKILLS_ROOT}/wiki` }] }
+ })
+ await expect(
+ fetchCompileSkills(controller.signal, BUILTIN_SKILLS_ROOT),
+ ).rejects.toThrow()
+ expect(clientMocks.get).toHaveBeenCalledOnce()
+ })
+})
diff --git a/web-studio/src/routes/compile/-lib/api.ts b/web-studio/src/routes/compile/-lib/api.ts
index 7357fc64f..a6cbb7ca8 100644
--- a/web-studio/src/routes/compile/-lib/api.ts
+++ b/web-studio/src/routes/compile/-lib/api.ts
@@ -1,6 +1,9 @@
import i18n from '#/i18n/core'
import { getOvResult, ovClient, OvClientError } from '#/lib/ov-client'
import type { TaskRecord } from '#/routes/tasks/-lib/task-record'
+import { parse as parseYaml } from 'yaml'
+import { splitMarkdownFrontmatter } from '#/lib/markdown-frontmatter'
+import { normalizeReadContent } from '#/routes/resources/-lib/normalize'
export type CompileRequest = {
from: string[]
@@ -101,12 +104,12 @@ export async function cancelCompile(id: string) {
),
)
}
-export function fetchCapabilities() {
+export function fetchCapabilities(signal?: AbortSignal) {
return getOvResult<{
configured: boolean
can_create: boolean
reason_code?: string
- }>(ovClient.client.get({ url: '/api/v1/compile/capabilities' }))
+ }>(ovClient.client.get({ url: '/api/v1/compile/capabilities', signal }))
}
export async function lookupSubmission(key: string) {
return normalizeCompileTask(
@@ -117,9 +120,16 @@ export async function lookupSubmission(key: string) {
),
)
}
-export type CompileSkill = { name: string; uri: string; description: string }
+export const BUILTIN_SKILLS_ROOT = 'viking://system/compile/example-skills'
+export type CompileSkill = {
+ name: string
+ uri: string
+ description: string
+ metadataError?: boolean
+}
export async function fetchCompileSkills(
signal?: AbortSignal,
+ targetUri?: string,
): Promise<CompileSkill[]> {
const result = await getOvResult<{
skills: Array<{
@@ -128,9 +138,61 @@ export async function fetchCompileSkills(
root_uri?: string
description?: string
}>
- }>(ovClient.client.get({ url: '/api/v1/skills', signal }))
- return result.skills.flatMap((s) => {
+ }>(
+ ovClient.client.get({
+ url: '/api/v1/skills',
+ signal,
+ ...(targetUri ? { query: { target_uri: targetUri } } : {}),
+ }),
+ )
+ const skills = result.skills.flatMap((s) => {
const uri = s.uri || s.root_uri
return uri ? [{ name: s.name, uri, description: s.description || '' }] : []
})
+ if (targetUri !== BUILTIN_SKILLS_ROOT) return skills
+ signal?.throwIfAborted()
+ // System assets are file-only: their descriptions do not have abstract sidecars.
+ // Read the definition supplied by this server, including skills unknown to Studio.
+ return Promise.all(
+ skills.map(async (skill): Promise<CompileSkill> => {
+ if (skill.description) return skill
+ try {
+ const content = await getOvResult<unknown>(
+ ovClient.client.get({
+ url: '/api/v1/content/read',
+ signal,
+ query: {
+ uri: `${skill.uri.replace(/\/$/, '')}/SKILL.md`,
+ limit: 100,
+ },
+ }),
+ )
+ const frontmatter = splitMarkdownFrontmatter(
+ normalizeReadContent(content),
+ )
+ const meta = frontmatter
+ ? parseYaml(
+ frontmatter.rawFrontmatter.split('\n').slice(1, -1).join('\n'),
+ )
+ : null
+ if (
+ !meta ||
+ typeof meta.description !== 'string' ||
+ !meta.description.trim()
+ )
+ return { ...skill, metadataError: true }
+ return {
+ ...skill,
+ name:
+ typeof meta.name === 'string' && meta.name.trim()
+ ? meta.name
+ : skill.name,
+ description: meta.description,
+ }
+ } catch (error) {
+ if (signal?.aborted) throw error
+ return { ...skill, metadataError: true }
+ }
+ }),
+ )
}
diff --git a/web-studio/src/routes/compile/-lib/locations.ts b/web-studio/src/routes/compile/-lib/locations.ts
new file mode 100644
index 000000000..d6e8a88e8
--- /dev/null
+++ b/web-studio/src/routes/compile/-lib/locations.ts
@@ -0,0 +1,46 @@
+export function sourceUris(value: string) {
+ return [
+ ...new Set(
+ value
+ .split('\n')
+ .map((uri) => uri.trim().replace(/\/$/, ''))
+ .filter(Boolean),
+ ),
+ ]
+}
+
+export function locationLabel(uri: string, userRoot: string) {
+ const clean = uri.replace(/\/$/, '')
+ const mine = userRoot.replace(/\/$/, '')
+ if (clean === mine || clean.startsWith(`${mine}/`))
+ return {
+ scope: 'personalSpace' as const,
+ path: clean.slice(mine.length + 1),
+ }
+ if (clean === 'viking://resources' || clean.startsWith('viking://resources/'))
+ return {
+ scope: 'sharedSpace' as const,
+ path: clean.slice('viking://resources/'.length),
+ }
+ return { scope: 'otherLocation' as const, path: clean }
+}
+
+export function targetError(uri: string) {
+ if (!uri.trim()) return 'targetRequired' as const
+ if (
+ !uri.startsWith('viking://') ||
+ /[\\\r\n]/.test(uri) ||
+ uri
+ .slice(9)
+ .split('/')
+ .some((part) => part === '.' || part === '..')
+ )
+ return 'invalidUri' as const
+ if (
+ /^viking:\/\/(?:resources|user\/[^/]+\/resources)\/?$/.test(uri) ||
+ uri === 'viking://' ||
+ uri.startsWith('viking://system/')
+ )
+ return 'targetRootInvalid' as const
+ return null
+}
diff --git a/web-studio/src/routes/compile/-lib/skills.test.tsx b/web-studio/src/routes/compile/-lib/skills.test.tsx
new file mode 100644
index 000000000..db52512d9
--- /dev/null
+++ b/web-studio/src/routes/compile/-lib/skills.test.tsx
@@ -0,0 +1,52 @@
+// @vitest-environment jsdom
+import type { ReactNode } from 'react'
+import { afterEach, expect, it, vi } from 'vitest'
+import { cleanup, renderHook, waitFor } from '@testing-library/react'
+import { QueryClient, QueryClientProvider } from '@tanstack/react-query'
+import { skillScope, useCompileSkills } from './skills'
+
+const fetchSkills = vi.hoisted(() => vi.fn())
+vi.mock('./api', () => ({
+ BUILTIN_SKILLS_ROOT: 'viking://system/compile/example-skills',
+ fetchCompileSkills: fetchSkills,
+}))
+vi.mock('#/hooks/use-app-connection', () => ({
+ useAppConnection: () => ({
+ identityScopeKey: 'alice',
+ connection: { userId: 'alice' },
+ }),
+}))
+const clients: QueryClient[] = []
+afterEach(() => {
+ cleanup()
+ clients.splice(0).forEach((client) => client.clear())
+ vi.resetAllMocks()
+})
+it('keeps built-ins usable without personal skills and when shared discovery fails', async () => {
+ fetchSkills.mockImplementation(async (_signal: AbortSignal, root: string) => {
+ if (root === 'viking://agent/skills') throw new Error('Shared unavailable')
+ if (root === 'viking://user/alice/skills') return []
+ return [
+ {
+ uri: `${root}/future-skill`,
+ name: 'Future skill',
+ description: 'From the server',
+ },
+ ]
+ })
+ const client = new QueryClient({
+ defaultOptions: { queries: { retry: false } },
+ })
+ clients.push(client)
+ const { result } = renderHook(useCompileSkills, {
+ wrapper: ({ children }: { children: ReactNode }) => (
+ <QueryClientProvider client={client}>{children}</QueryClientProvider>
+ ),
+ })
+ await waitFor(() => expect(result.current.shared.isError).toBe(true))
+ expect(result.current.mine.data).toEqual([])
+ expect(result.current.data.map((skill) => skill.name)).toEqual([
+ 'Future skill',
+ ])
+ expect(skillScope(result.current.data[0].uri)).toBe('builtinSkills')
+})
diff --git a/web-studio/src/routes/compile/-lib/skills.ts b/web-studio/src/routes/compile/-lib/skills.ts
new file mode 100644
index 000000000..98d86efc6
--- /dev/null
+++ b/web-studio/src/routes/compile/-lib/skills.ts
@@ -0,0 +1,70 @@
+import { useQuery } from '@tanstack/react-query'
+import type { TFunction } from 'i18next'
+import { useAppConnection } from '#/hooks/use-app-connection'
+import { BUILTIN_SKILLS_ROOT, fetchCompileSkills } from './api'
+import type { CompileSkill } from './api'
+
+export function skillScope(uri: string) {
+ if (uri.startsWith(`${BUILTIN_SKILLS_ROOT}/`)) return 'builtinSkills'
+ if (uri.startsWith('viking://user/')) return 'mySkills'
+ if (uri.startsWith('viking://agent/skills/')) return 'sharedSkills'
+ return 'otherSkills'
+}
+
+// These are localized explanations, not an inventory. Only server-listed skills appear.
+export function skillGuide(skill: CompileSkill, t: TFunction<'compile'>) {
+ if (skillScope(skill.uri) !== 'builtinSkills') return null
+ const key = skill.uri.replace(/\/$/, '').split('/').pop()
+ if (
+ ![
+ 'llm-wiki',
+ 'knowledge-distillation',
+ 'daily-report',
+ 'knowledge-graph',
+ 'ov-session-report',
+ ].includes(key ?? '')
+ )
+ return null
+ return {
+ name: t(`builtin.${key}.name`),
+ description: t(`builtin.${key}.description`),
+ inputs: t(`builtin.${key}.inputs`),
+ outputs: t(`builtin.${key}.outputs`),
+ limits: t(`builtin.${key}.limits`),
+ specialized: key === 'ov-session-report',
+ }
+}
+
+export function useCompileSkills() {
+ const { identityScopeKey, connection } = useAppConnection()
+ const mine = useQuery({
+ queryKey: ['compile-skills', identityScopeKey, 'mine'],
+ queryFn: ({ signal }) =>
+ fetchCompileSkills(
+ signal,
+ `viking://user/${connection.userId || 'default'}/skills`,
+ ),
+ staleTime: 30_000,
+ })
+ const shared = useQuery({
+ queryKey: ['compile-skills', identityScopeKey, 'shared'],
+ queryFn: ({ signal }) =>
+ fetchCompileSkills(signal, 'viking://agent/skills'),
+ staleTime: 30_000,
+ })
+ const builtin = useQuery({
+ queryKey: ['compile-skills', identityScopeKey, 'builtin'],
+ queryFn: ({ signal }) => fetchCompileSkills(signal, BUILTIN_SKILLS_ROOT),
+ staleTime: 30_000,
+ })
+ return {
+ mine,
+ shared,
+ builtin,
+ data: [
+ ...(builtin.data ?? []),
+ ...(mine.data ?? []),
+ ...(shared.data ?? []),
+ ],
+ }
+}
diff --git a/web-studio/src/routes/compile/index.tsx b/web-studio/src/routes/compile/index.tsx
index 68b5227b6..cc9b88d90 100644
--- a/web-studio/src/routes/compile/index.tsx
+++ b/web-studio/src/routes/compile/index.tsx
@@ -26,7 +26,11 @@ import {
CompileStatus,
} from './-components/shared'
import { ContextLink, useCompileSkillName } from './-components/context-link'
-import { fetchCapabilities, fetchCompileTasks } from './-lib/api'
+import { fetchCompileTasks } from './-lib/api'
+import {
+ CapabilityNotice,
+ useCompileCapability,
+} from './-components/capability-notice'
const STATUSES = [
'pending',
@@ -75,11 +79,7 @@ function CompileList() {
fetchCompileTasks(search.status, search.q, pageParam, signal),
getNextPageParam: (page) => page.next_cursor || undefined,
})
- const capability = useQuery({
- queryKey: ['compile-capability', identityScopeKey],
- queryFn: fetchCapabilities,
- retry: false,
- })
+ const capability = useCompileCapability()
const latest = useQuery({
queryKey: ['compile-latest', identityScopeKey, search],
queryFn: ({ signal }) =>
@@ -106,20 +106,13 @@ function CompileList() {
back={false}
title={t('title')}
actions={
- <Button
- disabled={capability.data?.can_create === false}
- onClick={() => void navigate({ to: '/compile/new' })}
- >
+ <Button onClick={() => void navigate({ to: '/compile/new' })}>
<PlusIcon />
{t('new')}
</Button>
}
>
- {capability.data?.can_create === false && (
- <p role="status" className="rounded-lg border bg-muted/30 p-4 text-sm">
- {t('unconfigured')}
- </p>
- )}
+ <CapabilityNotice capability={capability} />
<div className="flex flex-wrap items-center gap-3">
<div className="relative w-full sm:max-w-md">
<Search className="pointer-events-none absolute left-3 top-1/2 size-4 -translate-y-1/2 text-muted-foreground" />
diff --git a/web-studio/src/routes/compile/new.tsx b/web-studio/src/routes/compile/new.tsx
index 6e6eacdf0..838cb84cb 100644
--- a/web-studio/src/routes/compile/new.tsx
+++ b/web-studio/src/routes/compile/new.tsx
@@ -3,18 +3,25 @@ import { useAppConnection } from '#/hooks/use-app-connection'
import { CompileForm } from './-components/compile-form'
export const Route = createFileRoute('/compile/new')({
- validateSearch: (s: Record<string, unknown>): { fromTask?: string } => ({
+ validateSearch: (
+ s: Record<string, unknown>,
+ ): { fromTask?: string; from?: string } => ({
fromTask: typeof s.fromTask === 'string' ? s.fromTask : undefined,
+ from:
+ typeof s.from === 'string' && s.from.startsWith('viking://')
+ ? s.from
+ : undefined,
}),
component: NewCompile,
})
function NewCompile() {
const { identityScopeKey } = useAppConnection()
- const { fromTask } = Route.useSearch()
+ const { fromTask, from } = Route.useSearch()
return (
<CompileForm
- key={`${identityScopeKey}:${fromTask || ''}`}
+ key={`${identityScopeKey}:${fromTask || ''}:${from || ''}`}
fromTask={fromTask}
+ sourceUri={from}
/>
)
}
diff --git a/web-studio/src/routes/compile/tasks/$taskId.tsx b/web-studio/src/routes/compile/tasks/$taskId.tsx
index a149ec3ac..69ee9f320 100644
--- a/web-studio/src/routes/compile/tasks/$taskId.tsx
+++ b/web-studio/src/routes/compile/tasks/$taskId.tsx
@@ -12,6 +12,7 @@ import {
} from 'lucide-react'
import { Button } from '#/components/ui/button'
import { useAppConnection } from '#/hooks/use-app-connection'
+import { useInvalidateVikingFs } from '#/routes/resources/-hooks/viking-fm'
import { TaskExecutionEvents } from '#/routes/tasks/-components/task-execution-events'
import {
CompileError,
@@ -33,6 +34,7 @@ function CompileDetail() {
{ t, i18n } = useTranslation('compile')
const { identityScopeKey, connectionRole } = useAppConnection(),
client = useQueryClient()
+ const { invalidateAll, invalidatePreview } = useInvalidateVikingFs()
const [tab, setTab] = useState<'overview' | 'events' | 'result'>('overview')
const key = ['compile-task', identityScopeKey, taskId]
const query = useQuery({
@@ -52,6 +54,25 @@ function CompileDetail() {
const task = query.data,
request = task?.meta?.request
const previousStatus = useRef<{ id: string; status?: string } | null>(null)
+ const refreshedOutput = useRef('')
+ useEffect(() => {
+ const scope = `${identityScopeKey}:${taskId}`
+ if (task?.status !== 'completed' || refreshedOutput.current === scope)
+ return
+ refreshedOutput.current = scope
+ void invalidateAll()
+ void invalidatePreview()
+ void client.invalidateQueries({
+ queryKey: ['dir-picker', identityScopeKey],
+ })
+ }, [
+ client,
+ identityScopeKey,
+ invalidateAll,
+ invalidatePreview,
+ taskId,
+ task?.status,
+ ])
useEffect(() => {
if (
previousStatus.current?.id === taskId &&
@@ -163,6 +184,27 @@ function CompileDetail() {
</section>
{stop.isError && <CompileError error={stop.error} />}
{task.error && <CompileError error={task.error} />}
+ {task.status === 'completed' && request?.to && (
+ <section className="flex flex-wrap items-center justify-between gap-4 rounded-xl border bg-muted/20 p-5">
+ <div className="min-w-0">
+ <h2 className="font-medium">{t('viewGenerated')}</h2>
+ <p className="mt-1 text-sm text-muted-foreground">
+ {t('outputHint')}
+ </p>
+ <p className="mt-2 break-words text-sm">
+ {request.to.split('/').filter(Boolean).pop()}
+ </p>
+ </div>
+ <Link
+ to="/filesystem"
+ search={{ uri: request.to }}
+ className="inline-flex items-center gap-2 rounded-md bg-primary px-4 py-2 text-sm text-primary-foreground focus-visible:outline-2 focus-visible:outline-offset-2 focus-visible:outline-ring"
+ >
+ <FolderOutput className="size-4" />
+ {t('viewGenerated')}
+ </Link>
+ </section>
+ )}
<div role="tablist" className="flex gap-2 border-b pb-3">
{TABS.map((item) => (
<Button
@@ -268,7 +310,7 @@ function CompileDetail() {
{t('noResult')}
</p>
) : (
- <details open>
+ <details>
<summary className="text-sm font-medium">
{t('raw')}
</summary>
diff --git a/web-studio/src/routes/compile/tasks/-task-detail.test.tsx b/web-studio/src/routes/compile/tasks/-task-detail.test.tsx
new file mode 100644
index 000000000..efaae16e2
--- /dev/null
+++ b/web-studio/src/routes/compile/tasks/-task-detail.test.tsx
@@ -0,0 +1,158 @@
+// @vitest-environment jsdom
+
+import type { ComponentType, ReactNode } from 'react'
+import type * as TanStackRouter from '@tanstack/react-router'
+import type * as CompileApi from '../-lib/api'
+import { QueryClient, QueryClientProvider } from '@tanstack/react-query'
+import { act, cleanup, render, screen, waitFor } from '@testing-library/react'
+import { afterEach, beforeAll, beforeEach, expect, it, vi } from 'vitest'
+import { Route } from './$taskId'
+
+const api = vi.hoisted(() => ({ fetchCompileTask: vi.fn() }))
+vi.mock('../-lib/api', async (importOriginal) => ({
+ ...(await importOriginal<typeof CompileApi>()),
+ fetchCompileTask: api.fetchCompileTask,
+}))
+vi.mock('@tanstack/react-router', async (importOriginal) => ({
+ ...(await importOriginal<typeof TanStackRouter>()),
+ useLocation: () => ({ state: {} }),
+ useRouter: () => ({ history: { back: vi.fn() } }),
+ Link: ({
+ to,
+ search,
+ children,
+ }: {
+ to: string
+ search?: Record<string, string>
+ children: ReactNode
+ }) => <a href={`${to}?${new URLSearchParams(search)}`}>{children}</a>,
+}))
+vi.mock('#/hooks/use-app-connection', () => ({
+ useAppConnection: () => ({
+ identityScopeKey: 'connection-a',
+ connectionRole: 'user',
+ }),
+}))
+vi.mock('react-i18next', () => ({
+ useTranslation: () => ({
+ t: (key: string) => key,
+ i18n: { language: 'en' },
+ }),
+}))
+vi.mock('../-components/context-link', () => ({
+ ContextLink: ({ uri }: { uri: string }) => <span>{uri}</span>,
+ useCompileSkillName: () => (uri: string) => uri,
+}))
+vi.mock('sonner', () => ({
+ toast: { success: vi.fn(), error: vi.fn() },
+}))
+
+const DetailPage = Route.options.component as ComponentType & {
+ preload?: () => Promise<void>
+}
+const taskKey = ['compile-task', 'connection-a', 'cmp-1']
+const outputUri = 'viking://resources/output'
+const outputKeys = [
+ ['viking-fs-ls', `${outputUri}/`, {}],
+ ['viking-fs-tree', 'viking://resources/', {}],
+ ['viking-fs-stat', outputUri],
+ ['viking-file-read', `${outputUri}/index.md`, '', {}],
+ ['dir-picker', 'connection-a', outputUri],
+]
+const unrelatedKeys = [
+ ['dir-picker', 'connection-b', outputUri],
+ ['compile-list', 'connection-a'],
+]
+const clients: QueryClient[] = []
+
+function task(status: 'running' | 'completed'): CompileApi.CompileTask {
+ return {
+ task_id: 'cmp-1',
+ task_type: 'compile',
+ status,
+ meta: {
+ request: {
+ from: ['viking://resources/input'],
+ to: outputUri,
+ skill: 'viking://system/compile/example-skills/llm-wiki',
+ },
+ },
+ }
+}
+
+function mount() {
+ const client = new QueryClient({
+ defaultOptions: { queries: { retry: false } },
+ })
+ clients.push(client)
+ for (const key of [...outputKeys, ...unrelatedKeys])
+ client.setQueryData(key, { cached: true })
+ const page = render(
+ <QueryClientProvider client={client}>
+ <DetailPage />
+ </QueryClientProvider>,
+ )
+ return { client, page }
+}
+
+beforeAll(async () => {
+ await DetailPage.preload?.()
+})
+beforeEach(() => {
+ vi.spyOn(Route, 'useParams').mockReturnValue({ taskId: 'cmp-1' })
+})
+afterEach(() => {
+ cleanup()
+ clients.splice(0).forEach((client) => client.clear())
+ vi.resetAllMocks()
+ vi.restoreAllMocks()
+})
+
+it('invalidates cached output listings, trees, metadata, previews, and directory pickers when opening a completed task', async () => {
+ api.fetchCompileTask.mockResolvedValue(task('completed'))
+ const { client } = mount()
+
+ const outputLink = await screen.findByRole('link', {
+ name: 'viewGenerated',
+ })
+ expect(outputLink.getAttribute('href')).toBe(
+ `/filesystem?${new URLSearchParams({ uri: outputUri })}`,
+ )
+ await waitFor(() => {
+ for (const key of outputKeys)
+ expect(client.getQueryState(key)?.isInvalidated).toBe(true)
+ })
+ for (const key of unrelatedKeys)
+ expect(client.getQueryState(key)?.isInvalidated).toBe(false)
+})
+
+it('refreshes output caches only once when a running task completes', async () => {
+ api.fetchCompileTask.mockResolvedValue(task('running'))
+ const { client, page } = mount()
+
+ await screen.findByText('statuses.running')
+ for (const key of outputKeys)
+ expect(client.getQueryState(key)?.isInvalidated).toBe(false)
+
+ api.fetchCompileTask.mockResolvedValue(task('completed'))
+ await act(async () => {
+ await client.refetchQueries({ queryKey: taskKey })
+ })
+ await waitFor(() => {
+ for (const key of outputKeys)
+ expect(client.getQueryState(key)?.isInvalidated).toBe(true)
+ })
+
+ // Model the explorer having fetched fresh output after that invalidation.
+ for (const key of outputKeys) client.setQueryData(key, { cached: false })
+ page.rerender(
+ <QueryClientProvider client={client}>
+ <DetailPage />
+ </QueryClientProvider>,
+ )
+ await act(async () => {
+ await client.refetchQueries({ queryKey: taskKey })
+ })
+ for (const key of outputKeys)
+ expect(client.getQueryState(key)?.isInvalidated).toBe(false)
+})
diff --git a/web-studio/src/routes/filesystem/-components/context-explorer.tsx b/web-studio/src/routes/filesystem/-components/context-explorer.tsx
index a501d10ff..e5e220a2d 100644
--- a/web-studio/src/routes/filesystem/-components/context-explorer.tsx
+++ b/web-studio/src/routes/filesystem/-components/context-explorer.tsx
@@ -125,11 +125,13 @@ const NAMESPACE_DESCRIPTION_KEYS: Partial<
string,
| 'explorer.namespaces.agent'
| 'explorer.namespaces.resources'
+ | 'explorer.namespaces.system'
| 'explorer.namespaces.user'
>
> = {
agent: 'explorer.namespaces.agent',
resources: 'explorer.namespaces.resources',
+ system: 'explorer.namespaces.system',
user: 'explorer.namespaces.user',
} as const
diff --git a/web-studio/src/routes/filesystem/route.tsx b/web-studio/src/routes/filesystem/route.tsx
index d8aed425d..3a2074a89 100644
--- a/web-studio/src/routes/filesystem/route.tsx
+++ b/web-studio/src/routes/filesystem/route.tsx
@@ -11,6 +11,7 @@ import {
PanelRightCloseIcon,
PanelRightOpenIcon,
TerminalIcon,
+ WandSparkles,
} from 'lucide-react'
import { toast } from 'sonner'
@@ -642,6 +643,29 @@ function FilesystemWorkbench() {
>
<ClipboardIcon className="size-4" />
</Button>
+ {canUseLocalTools &&
+ selectedIsDirectory &&
+ /^viking:\/\/(?:resources(?:\/|$)|user\/[^/]+\/resources(?:\/|$))/.test(
+ selectedUri,
+ ) && (
+ <Button
+ type="button"
+ variant="ghost"
+ size="sm"
+ aria-label={t('compile:compileThisFolder')}
+ onClick={() =>
+ void navigate({
+ to: '/compile/new',
+ search: { from: selectedUri },
+ })
+ }
+ >
+ <WandSparkles className="size-4" />
+ <span className="hidden sm:inline">
+ {t('compile:compileThisFolder')}
+ </span>
+ </Button>
+ )}
{canManageSelectedUri ? (
<Button
type="button"
diff --git a/web-studio/src/routes/resources/-components/directory-picker-dialog.test.tsx b/web-studio/src/routes/resources/-components/directory-picker-dialog.test.tsx
new file mode 100644
index 000000000..2c8c0631e
--- /dev/null
+++ b/web-studio/src/routes/resources/-components/directory-picker-dialog.test.tsx
@@ -0,0 +1,117 @@
+// @vitest-environment jsdom
+import { useState } from 'react'
+import { afterEach, beforeEach, expect, it, vi } from 'vitest'
+import { cleanup, render, screen, waitFor } from '@testing-library/react'
+import userEvent from '@testing-library/user-event'
+import { QueryClient, QueryClientProvider } from '@tanstack/react-query'
+import type * as ReactI18next from 'react-i18next'
+import zh from '#/i18n/locales/zh-CN/resources'
+import { DirectoryPickerDialog } from './directory-picker-dialog'
+
+const list = vi.hoisted(() => vi.fn())
+vi.mock('#/lib/ov-client', () => ({
+ getFsLs: list,
+ getOvResult: (result: unknown) => result,
+ isOvClientError: () => false,
+}))
+vi.mock('react-i18next', async (importOriginal) => ({
+ ...(await importOriginal<typeof ReactI18next>()),
+ useTranslation: () => ({
+ t: (key: string, values: Record<string, unknown> = {}) => {
+ const template =
+ key
+ .split('.')
+ .reduce((value: any, part) => value?.[part], zh.addResource) ?? key
+ return String(template).replace(/\{\{(\w+)\}\}/g, (_, name: string) =>
+ String(values[name] ?? ''),
+ )
+ },
+ }),
+}))
+
+const root = 'viking://user/alice/resources/'
+const shared = 'viking://resources/'
+const folders: Record<string, string[]> = {
+ [root]: ['project/', 'notes/'],
+ [`${root}project/`]: ['research/'],
+ [`${root}project/research/`]: [],
+ [shared]: ['team/'],
+}
+const clients: QueryClient[] = []
+
+beforeEach(() => {
+ list
+ .mockReset()
+ .mockImplementation(({ query }: { query: { uri: string } }) =>
+ Promise.resolve(folders[query.uri] ?? []),
+ )
+})
+afterEach(() => {
+ cleanup()
+ clients.splice(0).forEach((client) => client.clear())
+})
+
+function mount() {
+ const onSelect = vi.fn()
+ const client = new QueryClient({
+ defaultOptions: { queries: { retry: false, staleTime: Infinity } },
+ })
+ clients.push(client)
+ function Harness({ revision }: { revision: number }) {
+ const [open, setOpen] = useState(false)
+ return (
+ <>
+ <button type="button" onClick={() => setOpen(true)}>
+ Open picker {revision}
+ </button>
+ <DirectoryPickerDialog
+ open={open}
+ onOpenChange={setOpen}
+ value={root}
+ userResourceRoot={root}
+ identityScopeKey="alice"
+ onSelect={onSelect}
+ />
+ </>
+ )
+ }
+ const element = (revision: number) => (
+ <QueryClientProvider client={client}>
+ <Harness revision={revision} />
+ </QueryClientProvider>
+ )
+ const page = render(element(0))
+ return {
+ onSelect,
+ rerender: () => page.rerender(element(1)),
+ }
+}
+
+it('preserves single-selection browsing and confirms only the current directory', async () => {
+ const user = userEvent.setup()
+ const page = mount()
+ await user.click(screen.getByRole('button', { name: 'Open picker 0' }))
+ await user.click(await screen.findByRole('button', { name: 'project' }))
+ await screen.findByRole('button', { name: 'research' })
+ page.rerender()
+ expect(screen.getByRole('button', { name: 'research' })).toBeTruthy()
+ expect(screen.queryByRole('checkbox')).toBeNull()
+ expect(page.onSelect).not.toHaveBeenCalled()
+ await user.click(screen.getByRole('button', { name: '选择' }))
+ expect(page.onSelect).toHaveBeenCalledExactlyOnceWith(`${root}project/`)
+})
+
+it('discards navigation when cancelled and reopens at the original directory', async () => {
+ const user = userEvent.setup()
+ const page = mount()
+ await user.click(screen.getByRole('button', { name: 'Open picker 0' }))
+ await user.click(await screen.findByRole('button', { name: 'project' }))
+ await screen.findByRole('button', { name: 'research' })
+ await user.click(screen.getByRole('button', { name: '取消' }))
+ await waitFor(() => expect(screen.queryByRole('dialog')).toBeNull())
+ expect(page.onSelect).not.toHaveBeenCalled()
+ await user.click(screen.getByRole('button', { name: 'Open picker 0' }))
+ expect(screen.getByRole('button', { name: 'notes' })).toBeTruthy()
+ await user.click(screen.getByRole('button', { name: '选择' }))
+ expect(page.onSelect).toHaveBeenCalledExactlyOnceWith(root)
+})
diff --git a/web-studio/src/routes/resources/-components/directory-picker-dialog.tsx b/web-studio/src/routes/resources/-components/directory-picker-dialog.tsx
index e79bcca61..1138c898a 100644
--- a/web-studio/src/routes/resources/-components/directory-picker-dialog.tsx
+++ b/web-studio/src/routes/resources/-components/directory-picker-dialog.tsx
@@ -1,6 +1,7 @@
import { useQuery } from '@tanstack/react-query'
import { ChevronRight, FolderIcon, FolderOpen } from 'lucide-react'
import { useEffect, useState } from 'react'
+import type { ReactNode } from 'react'
import { useTranslation } from 'react-i18next'
import { Button } from '#/components/ui/button'
@@ -29,6 +30,7 @@ function getErrorMessage(error: unknown): string {
}
interface DirectoryPickerDialogProps {
+ emptyAction?: ReactNode
userResourceRoot?: string
identityScopeKey?: string
open: boolean
@@ -55,6 +57,7 @@ function parseBreadcrumbs(uri: string): Array<{ label: string; uri: string }> {
}
export function DirectoryPickerDialog({
+ emptyAction,
identityScopeKey = 'default',
userResourceRoot,
open,
@@ -189,6 +192,7 @@ export function DirectoryPickerDialog({
<div className="flex flex-col items-center justify-center gap-2 py-12 text-muted-foreground">
<FolderOpen className="size-8" />
<p className="text-sm">{t('dirPicker.empty')}</p>
+ {emptyAction}
</div>
)}
</ScrollArea>