Skip to content

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

feat(studio): align filesystem CLI commands and task interactions (#6463)

leowld07c84bf7474a
diff --git a/web-studio/docs/studio-cli-demo.gif b/web-studio/docs/studio-cli-demo.gif
new file mode 100644
index 000000000..3c4390c80
Binary files /dev/null and b/web-studio/docs/studio-cli-demo.gif differ
diff --git a/web-studio/src/i18n/locales/en/activity.ts b/web-studio/src/i18n/locales/en/activity.ts
index 036388bb7..0c3545db9 100644
--- a/web-studio/src/i18n/locales/en/activity.ts
+++ b/web-studio/src/i18n/locales/en/activity.ts
@@ -220,7 +220,7 @@ const activity = {
noHistory: 'No command history',
welcomeTitle: 'Terminal connected to the filesystem',
welcomeBody:
- 'Run /status, /ls, /search, /read, /add-resource. /search is global by default; add --scope . to use the current directory, or --scope viking://resources/... to limit it to a directory.',
+ 'Run /status, /ls, /find, /search, /read, /write, or /add-resource. Use --uri viking://resources/... to limit a search to a directory.',
scopeLabel: 'cwd: {{uri}}',
globalScope: 'global',
opened: 'Resource opened',
@@ -229,9 +229,24 @@ const activity = {
'OpenViking API responded normally; found {{count}} nodes under the root.',
lsBody: 'Showing {{count}} nodes under {{uri}}.',
fileEmpty: 'File is empty; opened in the middle preview.',
- searchUsage: 'Usage: {{name}} <query> [--scope .|viking://resources/...]',
+ searchUsage: 'Usage: {{name}} <query> [--uri viking://resources/...]',
searchScopeLine: 'Search scope: {{scope}}',
+ patternUsage:
+ 'Usage: {{name}} <pattern> [--uri viking://...] [--node-limit n]',
+ patternHits: '{{count}} matches under {{uri}}.',
helpParameters: 'Parameters',
+ parameterName: 'Parameter',
+ parameterRequired: 'Required',
+ parameterDescription: 'Description',
+ parameterDefault: 'Default',
+ parameterTypes: {
+ Text: 'Text',
+ URI: 'URI',
+ Number: 'Number',
+ Boolean: 'Boolean',
+ },
+ yes: 'Yes',
+ no: 'No',
helpExamples: 'Examples',
helpSubcommands: 'Subcommands',
noParameters: 'No parameters',
@@ -239,9 +254,24 @@ const activity = {
readUsage: 'Usage: /read viking://resources/...',
enterUri: 'Please enter a viking:// URI',
hits: 'Hit {{resources}} resources, {{memories}} memories, {{skills}} skills.',
- addResourceBody:
- 'Opened the add-resource dialog. After submitting, the left tree refreshes; use /ls or /search to keep locating new content.',
- addResourceTitle: 'Add resource',
+ resourceProcessing: 'Task submitted and processing. Task ID: {{taskId}}',
+ resourceCompleted: 'Import completed. Opened {{uri}}.',
+ resourceFailed: 'Resource import was not successful.',
+ resourceTaskFailed: 'Import failed: {{reason}}\nTask ID: {{taskId}}',
+ backgroundTaskFailed: 'Task failed: {{reason}}\nTask ID: {{taskId}}',
+ resourceStillProcessing:
+ 'Task is still processing. Check Task Center. Task ID: {{taskId}}',
+ viewResourceTask: 'View task status',
+ taskCompleted: 'Task completed',
+ taskCompletedHint: 'The task is complete. View the result.',
+ viewResult: 'View result',
+ taskDetails: {
+ taskId: 'Task ID:',
+ rootUri: 'Root URI:',
+ uri: 'URI:',
+ name: 'Name:',
+ auxiliaryFiles: 'Auxiliary files:',
+ },
sessionUsage:
'Usage: /session [current|list|create|switch|get|context|messages|archive|commit|message|tool-results|tool-result|tool-search|delete] ...',
sessionDeleteUsage: 'Usage: /session delete <session_id>',
@@ -253,30 +283,66 @@ const activity = {
sessionSwitchedBody: 'Switched to session: {{id}}',
sessionDeletedBody: 'Deleted session: {{id}}',
sessionMessageAddedBody: 'Added a message to session {{id}}.',
- unknownCommand:
- 'Unknown command. Available: /status, /ls, /search, /find, /read, /session, /add-resource.',
+ unknownCommand: 'Unknown command. Type / to browse available commands.',
+ addMemoryUsage:
+ 'Usage: /add-memory "memory content" [--session-id <session ID>]',
+ addMemorySubmitted:
+ 'Session committed; memory extraction is running in the background.',
+ memoryCompleted: 'Background processing completed for session {{id}}.',
+ skillCompleted: 'Skill processing completed; view it on the Skills page.',
+ addSkillUsage:
+ 'Usage: /add-skill <Git URL> [-p viking://agent/skills]. Upload local files on the Skills page.',
+ addResourceUsage:
+ 'Usage: /add-resource <URL> [--to <URI>|--parent <URI>] [--args <JSON>] [--reason <text>]. Use Add Resource above the file tree for visual import.',
+ writeUsage:
+ 'Usage: /write <URI> --content "text" [--mode replace|append|create] [--wait]',
+ waitUsage: 'Usage: /wait (the current open-source API takes no timeout)',
+ addSkillSubmitted:
+ 'Skill submitted for processing; check the Skills page.',
commandFailed: 'Command failed',
running: 'Running command...',
placeholder: 'Enter a CLI command, e.g. /status',
+ inputHint: 'Type / for commands · ↑↓ select · Enter complete',
suggestionsTitle: 'Command suggestions',
suggestionsHint: '↑↓ select · Tab complete · Enter run',
+ paletteGroups: {
+ core: 'Core workflows',
+ filesystem: 'Filesystem',
+ search: 'Search and context',
+ status: 'Configuration and status',
+ history: 'Recent commands',
+ resource: 'Resource paths',
+ subcommand: 'Session commands',
+ },
quickStart: {
title: 'Quick start',
+ heading: 'OpenViking CLI',
+ description: 'Work with context directly from the CLI',
addResource: {
title: 'Add a resource',
command: '/add-resource',
code: 'Import docs or files into viking://resources',
},
+ addSkill: {
+ title: 'Add a Skill',
+ command: '/add-skill',
+ code: 'Enter a Git URL to add a personal or shared Skill',
+ },
addMemory: {
title: 'Add memory',
- command: 'Agent remembers from chat',
- code: 'Send a message in the Agent panel, then commit the session',
+ command: '/add-memory',
+ code: 'Enter memory content; optionally target an existing session',
},
find: {
title: 'Find related context',
- command: '/find openviking value',
+ command: 'ov find "What is OpenViking useful for?"',
code: 'Search resources, memories, and skills from the current scope',
},
+ compile: {
+ title: 'Compile sources',
+ command: '/compile',
+ code: 'Choose source and output directories plus a Skill',
+ },
},
commandGroups: {
core: 'Core commands',
@@ -287,12 +353,117 @@ const activity = {
history: 'History',
},
commandParameters: {
+ compileFrom: {
+ name: '--from <source directory>',
+ description:
+ 'Required. A viking:// source path; repeat for multiple sources.',
+ },
+ compileTo: {
+ name: '--to <output directory>',
+ description: 'Required. The viking:// directory for compiled output.',
+ },
+ compileSkill: {
+ name: '--skill <Skill URI>',
+ description:
+ 'Required. An installed Skill used to organize the sources.',
+ },
+ skillSource: {
+ name: '<Git URL>',
+ description:
+ 'Required. A Git repository or GitHub directory containing SKILL.md; upload local files on the Skills page.',
+ },
+ skillScope: {
+ name: '--scope user|agent',
+ description:
+ 'Optional. Defaults to a personal Skill; agent shares it with the account.',
+ },
+ skillParent: {
+ name: '-p <URI>',
+ description: 'Optional Skill root; defaults to viking://~/skills.',
+ },
+ resourceSource: {
+ name: '<URL>',
+ description:
+ 'Optional remote URL; omit to open the local upload form.',
+ },
+ resourceTo: {
+ name: '--to <URI>',
+ description:
+ 'Optional exact destination URI; cannot be combined with --parent.',
+ },
+ resourceParent: {
+ name: '--parent <URI>',
+ description:
+ 'Optional parent directory; cannot be combined with --to.',
+ },
+ resourceReason: {
+ name: '--reason <text>',
+ description: 'Optional reason for importing this resource.',
+ },
+ resourceArgs: {
+ name: '--args <JSON>',
+ description:
+ 'Optional parser arguments, such as {"branch":"main"} for Git.',
+ },
+ writeContent: {
+ name: '--content <text>',
+ description: 'Required text to write. Quote text with spaces.',
+ },
+ writeMode: {
+ name: '--mode <mode>',
+ description:
+ 'Optional replace, append, or create; defaults to replace.',
+ },
+ writeWait: {
+ name: '--wait',
+ description: 'Optional. Wait for server processing.',
+ },
+ nodeLimit: {
+ name: '--node-limit <n>',
+ description:
+ 'Optional maximum result count; defaults to 10, or 256 for pattern search.',
+ },
+ threshold: {
+ name: '--threshold <score>',
+ description: 'Optional minimum result score.',
+ },
+ searchSessionId: {
+ name: '--session-id <id>',
+ description: 'Optional session to associate with the search.',
+ },
+ pattern: {
+ name: '<pattern>',
+ description:
+ 'Required content pattern for grep or path pattern for glob.',
+ },
+ ignoreCase: {
+ name: '-i',
+ description: 'Optional case-insensitive grep matching.',
+ },
+ taskAction: {
+ name: 'list|status|cancel',
+ description:
+ 'Required action to list compile tasks or inspect/cancel a task.',
+ },
+ taskId: {
+ name: '<task_id>',
+ description: 'Required for status and cancel.',
+ },
+ memoryContent: {
+ name: '<memory content>',
+ description: 'Required. Quote text containing spaces.',
+ },
+ memorySessionId: {
+ name: '--session-id <session ID>',
+ description:
+ 'Optional existing session; a new session is created when omitted.',
+ },
query: {
name: 'query',
description: 'Keywords or a semantic question to search for.',
},
scope: {
- name: '--scope <.|uri>',
+ name: '--uri <.|uri>',
description:
'Optional. Omit for global search; pass . for the current directory; pass uri for a specific directory.',
},
@@ -362,6 +533,24 @@ const activity = {
},
},
commandExamples: {
+ compile: {
+ default: {
+ code: '/compile --from viking://resources/source --to viking://resources/output --skill viking://~/skills/daily-report',
+ description: 'Compile a source directory with an installed Skill',
+ },
+ },
+ addSkill: {
+ git: {
+ code: '/add-skill https://github.com/volcengine/OpenViking/tree/main/examples/compile/ov-compile-skills/daily-report',
+ description: 'Add a personal Skill from a GitHub directory',
+ },
+ },
+ addMemory: {
+ default: {
+ code: '/add-memory "a useful fact"',
+ description: 'Create a session and extract memory',
+ },
+ },
status: {
default: {
code: '/status',
@@ -384,11 +573,11 @@ const activity = {
description: 'Search globally',
},
current: {
- code: '/search agent --scope .',
+ code: '/search agent --uri .',
description: 'Use the highlighted directory',
},
scoped: {
- code: '/search agent --scope viking://resources/',
+ code: '/search agent --uri viking://resources/',
description: 'Search only within a directory',
},
},
@@ -398,11 +587,11 @@ const activity = {
description: 'Find related resources globally',
},
current: {
- code: '/find agent --scope .',
+ code: '/find agent --uri .',
description: 'Use the highlighted directory',
},
scoped: {
- code: '/find agent --scope viking://resources/',
+ code: '/find agent --uri viking://resources/',
description: 'Find only within a directory',
},
},
@@ -417,6 +606,54 @@ const activity = {
code: '/add-resource',
description: 'Open the add-resource form',
},
+ remote: {
+ code: `ov add-resource https://github.com/volcengine/OpenViking --to viking://resources/openviking-repo --args '{"branch":"main"}'`,
+ description: 'Import the main branch of the OpenViking repository',
+ },
+ },
+ write: {
+ default: {
+ code: '/write viking://resources/notes.md --content "New content"',
+ description: 'Replace file content',
+ },
+ append: {
+ code: '/write viking://resources/notes.md --content "More content" --append',
+ description: 'Append to an existing file',
+ },
+ },
+ grep: {
+ default: {
+ code: '/grep "OpenViking"',
+ description: 'Find text in resources',
+ },
+ scoped: {
+ code: '/grep "OpenViking" --uri viking://resources/',
+ description: 'Find text under one directory',
+ },
+ },
+ glob: {
+ default: {
+ code: '/glob "**/*.md"',
+ description: 'Match Markdown file paths',
+ },
+ scoped: {
+ code: '/glob "**/*.md" --uri viking://resources/',
+ description: 'Match paths under one directory',
+ },
+ },
+ task: {
+ list: {
+ code: '/task list --task-type compile',
+ description: 'List compile tasks',
+ },
+ status: {
+ code: '/task status <task_id>',
+ description: 'Inspect a task',
+ },
+ cancel: {
+ code: '/task cancel <task_id>',
+ description: 'Cancel a task',
+ },
},
session: {
current: {
@@ -535,43 +772,73 @@ const activity = {
},
ls: {
description: 'View resources',
- usage: '/ls [viking://resources/...]',
+ usage: '/ls [<URI>]',
},
search: {
description: 'Semantic search',
- usage: '/search <query>',
+ usage: '/search <query> [--uri <URI>] [--node-limit <n>]',
},
find: {
description: 'Find related resources',
- usage: '/find <query>',
+ usage: '/find <query> [--uri <URI>] [--node-limit <n>]',
},
read: {
description: 'Read a resource file',
- usage: '/read viking://resources/.../file.md',
+ usage: '/read <URI>',
+ },
+ compile: {
+ description: 'Compile source materials with a Skill',
+ usage:
+ '/compile --from <source directory> --to <output directory> --skill <Skill URI>',
+ },
+ addSkill: {
+ description: 'Add a Skill from a Git URL',
+ usage: '/add-skill <Git URL> [-p <target root>]',
+ },
+ addMemory: {
+ description: 'Add a message to a session and extract memory',
+ usage: '/add-memory "memory content" [--session-id <session ID>]',
},
addResource: {
description: 'Add external resources',
- usage: '/add-resource',
+ usage:
+ '/add-resource <URL> [--to <URI>|--parent <URI>] [--args <JSON>]',
+ },
+ write: {
+ description: 'Write or append resource content',
+ usage: '/write <URI> --content <text> [--mode replace|append|create]',
+ },
+ grep: {
+ description: 'Search resource text patterns',
+ usage: '/grep <pattern> [--uri <URI>]',
+ },
+ glob: {
+ description: 'Search resource paths',
+ usage: '/glob <pattern> [--uri <URI>]',
+ },
+ task: {
+ description: 'Inspect and manage compile tasks',
+ usage: '/task <list|status|cancel> [<task ID>]',
},
session: {
description: 'Manage Agent sessions',
- usage: '/session subcommand',
+ usage: '/session <subcommand>',
},
tree: {
description: 'Show directory tree',
- usage: '/tree [viking://resources/...]',
+ usage: '/tree [<URI>]',
},
stat: {
description: 'Show resource metadata',
- usage: '/stat viking://resources/...',
+ usage: '/stat <URI>',
},
abstract: {
description: 'Read directory abstract',
- usage: '/abstract viking://resources/...',
+ usage: '/abstract <URI>',
},
overview: {
description: 'Read directory overview',
- usage: '/overview viking://resources/...',
+ usage: '/overview <URI>',
},
health: {
description: 'Show backend health',
@@ -579,7 +846,7 @@ const activity = {
},
wait: {
description: 'Wait for service readiness',
- usage: '/wait [--timeout seconds]',
+ usage: '/wait',
},
},
},
diff --git a/web-studio/src/i18n/locales/en/compile.ts b/web-studio/src/i18n/locales/en/compile.ts
index 0f5c2a697..7d849972a 100644
--- a/web-studio/src/i18n/locales/en/compile.ts
+++ b/web-studio/src/i18n/locales/en/compile.ts
@@ -157,6 +157,21 @@ export default {
createdAt: 'Created',
skillColumn: 'Skill',
taskId: 'Task ID',
+ terminalResult: {
+ taskId: 'Task ID',
+ taskType: 'Task type',
+ status: 'Status',
+ createdAt: 'Created at',
+ updatedAt: 'Updated at',
+ resourceId: 'Resource ID',
+ outputUri: 'Output URI',
+ inputUri: 'Input URI {{index}}',
+ request: 'Request',
+ stage: 'Stage',
+ createdAtIso: 'Created at ISO',
+ updatedAtIso: 'Updated at ISO',
+ error: 'Error',
+ },
materials: 'Materials',
status: 'Status',
invalidTask: 'Task not found or not a compilation.',
diff --git a/web-studio/src/i18n/locales/zh-CN/activity.ts b/web-studio/src/i18n/locales/zh-CN/activity.ts
index 7186627ec..a7438e431 100644
--- a/web-studio/src/i18n/locales/zh-CN/activity.ts
+++ b/web-studio/src/i18n/locales/zh-CN/activity.ts
@@ -211,7 +211,7 @@ const activity = {
noHistory: '暂无命令历史',
welcomeTitle: '终端已连接文件系统',
welcomeBody:
- '可执行 /status、/ls、/search、/read、/add-resource。/search 默认全局检索,可通过 --scope . 使用当前目录,或通过 --scope viking://resources/... 指定目录。',
+ '可执行 /status、/ls、/find、/search、/read、/write、/add-resource。搜索时可用 --uri viking://resources/... 限定目录。',
scopeLabel: '目录:{{uri}}',
globalScope: '全局',
opened: '已打开资源',
@@ -219,9 +219,24 @@ const activity = {
onlineBody: 'OpenViking API 正常响应,根目录下发现 {{count}} 个节点。',
lsBody: '{{uri}} 下共展示 {{count}} 个节点。',
fileEmpty: '文件为空,已在中间预览区打开。',
- searchUsage: '用法:{{name}} 查询词 [--scope .|viking://resources/...]',
+ searchUsage: '用法:{{name}} 查询词 [--uri viking://resources/...]',
searchScopeLine: '搜索范围:{{scope}}',
+ patternUsage:
+ '用法:{{name}} <模式> [--uri viking://...] [--node-limit 数量]',
+ patternHits: '在 {{uri}} 中找到 {{count}} 项。',
helpParameters: '参数',
+ parameterName: '参数',
+ parameterRequired: '必填',
+ parameterDescription: '说明',
+ parameterDefault: '默认值',
+ parameterTypes: {
+ Text: '文本',
+ URI: 'URI',
+ Number: '数字',
+ Boolean: '布尔值',
+ },
+ yes: '是',
+ no: '否',
helpExamples: '示例',
helpSubcommands: '子命令',
noParameters: '无参数',
@@ -229,9 +244,24 @@ const activity = {
readUsage: '用法:/read viking://resources/...',
enterUri: '请输入 viking:// URI',
hits: '命中资源 {{resources}} 条、记忆 {{memories}} 条、技能 {{skills}} 条。',
- addResourceBody:
- '已打开添加资源弹窗。提交后左侧目录会刷新,也可以用 /ls 或 /search 继续定位新内容。',
- addResourceTitle: '添加资源',
+ resourceProcessing: '任务已提交,正在处理。任务 ID:{{taskId}}',
+ resourceCompleted: '导入完成,已打开 {{uri}}。',
+ resourceFailed: '资源导入未成功。',
+ resourceTaskFailed: '导入失败:{{reason}}\n任务 ID:{{taskId}}',
+ backgroundTaskFailed: '任务失败:{{reason}}\n任务 ID:{{taskId}}',
+ resourceStillProcessing:
+ '任务仍在处理,请到任务中心查看。任务 ID:{{taskId}}',
+ viewResourceTask: '查看任务状态',
+ taskCompleted: '任务完成',
+ taskCompletedHint: '任务已完成,可点击查看结果。',
+ viewResult: '查看结果',
+ taskDetails: {
+ taskId: 'Task ID:',
+ rootUri: 'Root URI:',
+ uri: 'URI:',
+ name: 'Name:',
+ auxiliaryFiles: 'Auxiliary files:',
+ },
sessionUsage:
'用法:/session [current|list|create|switch|get|context|messages|archive|commit|message|tool-results|tool-result|tool-search|delete] ...',
sessionDeleteUsage: '用法:/session delete <session_id>',
@@ -243,30 +273,63 @@ const activity = {
sessionSwitchedBody: '已切换到会话:{{id}}',
sessionDeletedBody: '已删除会话:{{id}}',
sessionMessageAddedBody: '已向会话 {{id}} 添加消息。',
- unknownCommand:
- '未知命令。可用命令:/status、/ls、/search、/find、/read、/session、/add-resource。',
+ unknownCommand: '未知命令。输入 / 可浏览可用命令。',
+ addMemoryUsage: '用法:/add-memory "记忆内容" [--session-id <会话 ID>]',
+ addMemorySubmitted: '会话已提交,记忆正在后台提取。',
+ memoryCompleted: '会话 {{id}} 的后台处理已完成。',
+ skillCompleted: 'Skill 处理完成;可在「技能」页面查看。',
+ addSkillUsage:
+ '用法:/add-skill <Git URL> [-p viking://agent/skills]。本地文件请到「技能」页面上传。',
+ addResourceUsage:
+ '用法:/add-resource <URL> [--to <URI>|--parent <URI>] [--args <JSON>] [--reason <说明>]。可视化上传请点击文件系统上方的「添加资源」。',
+ writeUsage:
+ '用法:/write <URI> --content "文本" [--mode replace|append|create] [--wait]',
+ waitUsage: '用法:/wait(当前开源 API 不接收超时参数)',
+ addSkillSubmitted: 'Skill 已提交处理;可在「技能」页面查看。',
commandFailed: '命令失败',
running: '正在执行命令...',
placeholder: '输入 CLI 命令,例如 /status',
+ inputHint: '输入 / 查看全部指令 · ↑↓ 选择 · Enter 补全',
suggestionsTitle: '命令建议',
suggestionsHint: '↑↓ 选择 · Tab 补全 · Enter 执行',
+ paletteGroups: {
+ core: '核心流程',
+ filesystem: '文件系统',
+ search: '搜索与上下文',
+ status: '配置与状态',
+ history: '历史命令',
+ resource: '资源路径',
+ subcommand: '会话命令',
+ },
quickStart: {
title: '快速开始',
+ heading: 'OpenViking CLI',
+ description: 'CLI 直接操作上下文',
addResource: {
title: '添加资源',
command: '/add-resource',
code: '导入文档或文件到 viking://resources',
},
+ addSkill: {
+ title: '添加 Skill',
+ command: '/add-skill',
+ code: '输入 Git 地址,将 Skill 添加到个人或共享目录',
+ },
addMemory: {
title: '添加记忆',
- command: '通过 Agent 会话提取记忆',
- code: '在 Agent 面板发送消息,然后提交会话',
+ command: '/add-memory',
+ code: '输入记忆内容;可选指定已有会话 ID',
},
find: {
title: '查找相关上下文',
- command: '/find openviking 价值',
+ command: 'ov find "OpenViking 有什么价值?"',
code: '在当前范围内搜索资源、记忆和技能',
},
+ compile: {
+ title: '编译素材',
+ command: '/compile',
+ code: '选择素材目录、输出目录和 Skill',
+ },
},
commandGroups: {
core: '核心命令',
@@ -277,12 +340,102 @@ const activity = {
history: '历史记录',
},
commandParameters: {
+ compileFrom: {
+ name: '--from <素材目录>',
+ description: '必填。需要编译的 viking:// 素材路径,可重复填写。',
+ },
+ compileTo: {
+ name: '--to <输出目录>',
+ description: '必填。编译结果保存到这个 viking:// 目录。',
+ },
+ compileSkill: {
+ name: '--skill <Skill URI>',
+ description: '必填。用于组织素材的已安装 Skill。',
+ },
+ skillSource: {
+ name: '<Git URL>',
+ description:
+ '必填。Git 仓库或含 SKILL.md 的 GitHub 子目录;本地文件请到技能页面上传。',
+ },
+ skillScope: {
+ name: '--scope user|agent',
+ description: '可选。默认添加为个人 Skill;agent 为账号共享 Skill。',
+ },
+ skillParent: {
+ name: '-p <URI>',
+ description: '可选。Skill 的目标根目录,默认 viking://~/skills。',
+ },
+ resourceSource: {
+ name: '<URL>',
+ description: '可选。远程 URL 直接导入;省略则打开本地上传表单。',
+ },
+ resourceTo: {
+ name: '--to <URI>',
+ description: '可选。完整目标 URI;不能与 --parent 同用。',
+ },
+ resourceParent: {
+ name: '--parent <URI>',
+ description: '可选。资源父目录 URI;不能与 --to 同用。',
+ },
+ resourceReason: {
+ name: '--reason <说明>',
+ description: '可选。说明此次导入的用途。',
+ },
+ resourceArgs: {
+ name: '--args <JSON>',
+ description: '可选。解析器参数,例如 Git 的 {"branch":"main"}。',
+ },
+ writeContent: {
+ name: '--content <文本>',
+ description: '必填。写入的文本,包含空格时请用引号包裹。',
+ },
+ writeMode: {
+ name: '--mode <模式>',
+ description: '可选。replace、append 或 create;默认 replace。',
+ },
+ writeWait: {
+ name: '--wait',
+ description: '可选。等待服务端处理完成。',
+ },
+ nodeLimit: {
+ name: '--node-limit <n>',
+ description: '可选。最多返回的结果数,默认 10;模式搜索默认 256。',
+ },
+ threshold: {
+ name: '--threshold <分数>',
+ description: '可选。仅返回达到最低分数的结果。',
+ },
+ searchSessionId: {
+ name: '--session-id <id>',
+ description: '可选。将检索关联到指定会话。',
+ },
+ pattern: {
+ name: '<模式>',
+ description: '必填。grep 搜正文,glob 匹配路径。',
+ },
+ ignoreCase: {
+ name: '-i',
+ description: '可选。grep 匹配时忽略大小写。',
+ },
+ taskAction: {
+ name: 'list|status|cancel',
+ description: '必填。列出编译任务,或查询、取消任务。',
+ },
+ taskId: { name: '<task_id>', description: 'status 和 cancel 必填。' },
+ memoryContent: {
+ name: '<记忆内容>',
+ description: '必填。写入会话的文本;包含空格时请用引号包裹。',
+ },
+ memorySessionId: {
+ name: '--session-id <会话 ID>',
+ description: '可选。指定已有会话;省略时自动新建会话。',
+ },
query: {
name: '查询词',
description: '要检索的关键词或语义问题。',
},
scope: {
- name: '--scope <.|uri>',
+ name: '--uri <.|uri>',
description:
'可选。不填则全局搜索;传入 . 使用当前目录,传入 URI 使用指定目录。',
},
@@ -346,6 +499,24 @@ const activity = {
},
},
commandExamples: {
+ compile: {
+ default: {
+ code: '/compile --from viking://resources/source --to viking://resources/output --skill viking://~/skills/daily-report',
+ description: '用已安装的 Skill 编译指定素材目录',
+ },
+ },
+ addSkill: {
+ git: {
+ code: '/add-skill https://github.com/volcengine/OpenViking/tree/main/examples/compile/ov-compile-skills/daily-report',
+ description: '从 GitHub 子目录添加个人 Skill',
+ },
+ },
+ addMemory: {
+ default: {
+ code: '/add-memory "需要记住的内容"',
+ description: '新建会话并提取记忆',
+ },
+ },
status: {
default: {
code: '/status',
@@ -368,11 +539,11 @@ const activity = {
description: '全局语义检索',
},
current: {
- code: '/search agent --scope .',
+ code: '/search agent --uri .',
description: '使用当前高亮目录',
},
scoped: {
- code: '/search agent --scope viking://resources/',
+ code: '/search agent --uri viking://resources/',
description: '只在指定目录检索',
},
},
@@ -382,11 +553,11 @@ const activity = {
description: '全局查找相关资源',
},
current: {
- code: '/find agent --scope .',
+ code: '/find agent --uri .',
description: '使用当前高亮目录',
},
scoped: {
- code: '/find agent --scope viking://resources/',
+ code: '/find agent --uri viking://resources/',
description: '只在指定目录查找',
},
},
@@ -401,6 +572,51 @@ const activity = {
code: '/add-resource',
description: '打开添加资源表单',
},
+ remote: {
+ code: `ov add-resource https://github.com/volcengine/OpenViking --to viking://resources/openviking-repo --args '{"branch":"main"}'`,
+ description: '导入 OpenViking 仓库的 main 分支',
+ },
+ },
+ write: {
+ default: {
+ code: '/write viking://resources/notes.md --content "新内容"',
+ description: '替换文件内容',
+ },
+ append: {
+ code: '/write viking://resources/notes.md --content "补充内容" --append',
+ description: '追加到已有文件',
+ },
+ },
+ grep: {
+ default: {
+ code: '/grep "OpenViking"',
+ description: '在资源正文中查找文字',
+ },
+ scoped: {
+ code: '/grep "OpenViking" --uri viking://resources/',
+ description: '只在指定目录查找文字',
+ },
+ },
+ glob: {
+ default: {
+ code: '/glob "**/*.md"',
+ description: '按路径模式查找 Markdown 文件',
+ },
+ scoped: {
+ code: '/glob "**/*.md" --uri viking://resources/',
+ description: '在指定目录匹配路径',
+ },
+ },
+ task: {
+ list: {
+ code: '/task list --task-type compile',
+ description: '列出编译任务',
+ },
+ status: {
+ code: '/task status <task_id>',
+ description: '查询任务状态',
+ },
+ cancel: { code: '/task cancel <task_id>', description: '取消任务' },
},
session: {
current: {
@@ -519,43 +735,73 @@ const activity = {
},
ls: {
description: '查看已有资源',
- usage: '/ls [viking://resources/...]',
+ usage: '/ls [<URI>]',
},
search: {
description: '语义检索上下文',
- usage: '/search 查询词',
+ usage: '/search <查询词> [--uri <URI>] [--node-limit <n>]',
},
find: {
description: '查找相关资源',
- usage: '/find 查询词',
+ usage: '/find <查询词> [--uri <URI>] [--node-limit <n>]',
},
read: {
description: '读取资源文件',
- usage: '/read viking://resources/.../file.md',
+ usage: '/read <URI>',
+ },
+ compile: {
+ description: '使用 Skill 编译素材',
+ usage:
+ '/compile --from <素材目录> --to <输出目录> --skill <Skill URI>',
+ },
+ addSkill: {
+ description: '从 Git 地址添加 Skill',
+ usage: '/add-skill <Git URL> [-p <目标根目录>]',
+ },
+ addMemory: {
+ description: '向指定会话写入消息并提取记忆',
+ usage: '/add-memory "记忆内容" [--session-id <会话 ID>]',
},
addResource: {
description: '添加外部资源',
- usage: '/add-resource',
+ usage:
+ '/add-resource <URL> [--to <URI>|--parent <URI>] [--args <JSON>]',
+ },
+ write: {
+ description: '写入或追加资源文件',
+ usage: '/write <URI> --content <文本> [--mode replace|append|create]',
+ },
+ grep: {
+ description: '按正文模式查找资源',
+ usage: '/grep <模式> [--uri <URI>]',
+ },
+ glob: {
+ description: '按路径模式查找资源',
+ usage: '/glob <模式> [--uri <URI>]',
+ },
+ task: {
+ description: '查看和管理编译任务',
+ usage: '/task <list|status|cancel> [<任务 ID>]',
},
session: {
description: '管理 Agent 会话',
- usage: '/session 子命令',
+ usage: '/session <子命令>',
},
tree: {
description: '展示目录树',
- usage: '/tree [viking://resources/...]',
+ usage: '/tree [<URI>]',
},
stat: {
description: '查看资源元信息',
- usage: '/stat viking://resources/...',
+ usage: '/stat <URI>',
},
abstract: {
description: '读取目录摘要',
- usage: '/abstract viking://resources/...',
+ usage: '/abstract <URI>',
},
overview: {
description: '读取目录概览',
- usage: '/overview viking://resources/...',
+ usage: '/overview <URI>',
},
health: {
description: '查看后端健康状态',
@@ -563,7 +809,7 @@ const activity = {
},
wait: {
description: '等待服务就绪',
- usage: '/wait [--timeout seconds]',
+ usage: '/wait',
},
},
},
diff --git a/web-studio/src/i18n/locales/zh-CN/compile.ts b/web-studio/src/i18n/locales/zh-CN/compile.ts
index f2287f93a..dff640a94 100644
--- a/web-studio/src/i18n/locales/zh-CN/compile.ts
+++ b/web-studio/src/i18n/locales/zh-CN/compile.ts
@@ -144,6 +144,21 @@ export default {
createdAt: '创建时间',
skillColumn: '技能',
taskId: '任务 ID',
+ terminalResult: {
+ taskId: '任务 ID',
+ taskType: '任务类型',
+ status: '状态',
+ createdAt: '创建时间',
+ updatedAt: '更新时间',
+ resourceId: '资源 ID',
+ outputUri: '输出 URI',
+ inputUri: '输入 URI {{index}}',
+ request: '请求',
+ stage: '阶段',
+ createdAtIso: '创建时间 ISO',
+ updatedAtIso: '更新时间 ISO',
+ error: '错误',
+ },
materials: '素材',
status: '状态',
invalidTask: '任务不存在或不是编译任务。',
diff --git a/web-studio/src/routes/filesystem/-components/agent-panel-submission.test.tsx b/web-studio/src/routes/filesystem/-components/agent-panel-submission.test.tsx
index 3b59a1243..2c1f2e07a 100644
--- a/web-studio/src/routes/filesystem/-components/agent-panel-submission.test.tsx
+++ b/web-studio/src/routes/filesystem/-components/agent-panel-submission.test.tsx
@@ -174,10 +174,15 @@ it('deletes the active history session only after confirmation and returns to a
expect(m.create).not.toHaveBeenCalled()
})
-it('opens a new draft without persisting an empty conversation', () => {
+it('shows new session only for an existing conversation and opens an unpersisted draft', () => {
const pending = setup()
+ expect(screen.queryByTitle('agent.newSession')).toBeNull()
+ fireEvent.click(screen.getByTitle('agent.history'))
+ fireEvent.click(screen.getAllByText('B')[0].closest('button')!)
+ expect(screen.getByTitle('agent.newSession')).toBeTruthy()
fireEvent.click(screen.getByTitle('agent.newSession'))
expect(m.create).not.toHaveBeenCalled()
expect(m.history).toHaveBeenLastCalledWith(undefined)
expect(pending.url).toHaveBeenCalledWith('')
+ expect(screen.queryByTitle('agent.newSession')).toBeNull()
})
diff --git a/web-studio/src/routes/filesystem/-components/agent-panel.test.tsx b/web-studio/src/routes/filesystem/-components/agent-panel.test.tsx
index 84aa4636c..fe2df00ac 100644
--- a/web-studio/src/routes/filesystem/-components/agent-panel.test.tsx
+++ b/web-studio/src/routes/filesystem/-components/agent-panel.test.tsx
@@ -26,6 +26,7 @@ describe('AgentToolbar', () => {
onNewSession={onNewSession}
onOpenHistory={onOpenHistory}
sessionTitle="Current session"
+ showNewSession
/>,
)
diff --git a/web-studio/src/routes/filesystem/-components/agent-panel.tsx b/web-studio/src/routes/filesystem/-components/agent-panel.tsx
index e6ce5a22b..d29b5812d 100644
--- a/web-studio/src/routes/filesystem/-components/agent-panel.tsx
+++ b/web-studio/src/routes/filesystem/-components/agent-panel.tsx
@@ -204,6 +204,9 @@ export function AgentPanel({
onNewSession={() => void handleNewSession()}
onOpenHistory={() => setHistoryOpen(true)}
sessionTitle={displayedSessionTitle}
+ showNewSession={Boolean(
+ persistedSessionId || chat.messages.length || sessionError,
+ )}
/>
<div className="flex min-h-0 flex-1 flex-col">
<div
@@ -385,6 +388,7 @@ export function AgentToolbar({
onNewSession,
onOpenHistory,
sessionTitle,
+ showNewSession,
}: {
container: HTMLDivElement | null
historyLabel: string
@@ -393,6 +397,7 @@ export function AgentToolbar({
onNewSession: () => void
onOpenHistory: () => void
sessionTitle: string
+ showNewSession: boolean
}) {
if (!container) return null
@@ -414,21 +419,24 @@ export function AgentToolbar({
>
<HistoryIcon className="size-3.5" />
</Button>
- <Button
- type="button"
- variant="ghost"
- size="icon-sm"
- className="size-7 shrink-0"
- title={newSessionLabel}
- disabled={isCreatingSession}
- onClick={onNewSession}
- >
- {isCreatingSession ? (
- <Loader2Icon className="size-3.5 animate-spin" />
- ) : (
- <SquarePenIcon className="size-3.5" />
- )}
- </Button>
+ {showNewSession ? (
+ <Button
+ type="button"
+ variant="ghost"
+ size="icon-sm"
+ className="size-7 shrink-0"
+ title={newSessionLabel}
+ aria-label={newSessionLabel}
+ disabled={isCreatingSession}
+ onClick={onNewSession}
+ >
+ {isCreatingSession ? (
+ <Loader2Icon className="size-3.5 animate-spin" />
+ ) : (
+ <SquarePenIcon className="size-3.5" />
+ )}
+ </Button>
+ ) : null}
</>,
container,
)
diff --git a/web-studio/src/routes/filesystem/-components/compile-task-result.test.tsx b/web-studio/src/routes/filesystem/-components/compile-task-result.test.tsx
new file mode 100644
index 000000000..3af1c47de
--- /dev/null
+++ b/web-studio/src/routes/filesystem/-components/compile-task-result.test.tsx
@@ -0,0 +1,86 @@
+// @vitest-environment jsdom
+
+import { QueryClient, QueryClientProvider } from '@tanstack/react-query'
+import {
+ cleanup,
+ fireEvent,
+ render,
+ screen,
+ waitFor,
+} from '@testing-library/react'
+import { afterEach, expect, it, vi } from 'vitest'
+import type * as CompileApi from '#/routes/compile/-lib/api'
+import { CompileTaskResult } from './terminal-panel'
+
+const api = vi.hoisted(() => ({ fetchCompileTask: vi.fn() }))
+vi.mock('#/routes/compile/-lib/api', async (importOriginal) => ({
+ ...(await importOriginal<typeof CompileApi>()),
+ fetchCompileTask: api.fetchCompileTask,
+}))
+vi.mock('#/hooks/use-app-connection', () => ({
+ useAppConnection: () => ({ identityScopeKey: 'connection-a' }),
+}))
+vi.mock('react-i18next', () => ({
+ useTranslation: () => ({
+ t: (key: string, options?: { index?: number }) =>
+ options?.index ? `${key} ${options.index}` : key,
+ }),
+}))
+
+afterEach(() => {
+ cleanup()
+ vi.resetAllMocks()
+})
+
+it('refreshes explorer data and opens the output URI after compilation completes', async () => {
+ api.fetchCompileTask.mockResolvedValue({
+ task_id: 'cmp-1',
+ status: 'completed',
+ resource_id: 'viking://resources/input-a, viking://resources/input-b',
+ meta: {
+ request: {
+ from: ['viking://resources/input-a', 'viking://resources/input-b'],
+ to: 'viking://resources/output',
+ skill: 'viking://agent/skills/demo',
+ },
+ },
+ })
+ const client = new QueryClient({
+ defaultOptions: { queries: { retry: false } },
+ })
+ const explorerKeys = [
+ ['viking-fs-ls', 'viking://resources/', {}],
+ ['viking-fs-tree', 'viking://resources/', {}],
+ ['viking-fs-stat', 'viking://resources/output'],
+ ['viking-file-read', 'viking://resources/output', '', {}],
+ ]
+ for (const key of explorerKeys) client.setQueryData(key, { stale: true })
+ const onOpenResource = vi.fn()
+ render(
+ <QueryClientProvider client={client}>
+ <CompileTaskResult taskId="cmp-1" onOpenResource={onOpenResource} />
+ </QueryClientProvider>,
+ )
+
+ await waitFor(() => {
+ expect(
+ screen.getByRole('button', { name: 'viking://resources/output' }),
+ ).not.toBeNull()
+ for (const key of explorerKeys)
+ expect(client.getQueryState(key)?.isInvalidated).toBe(true)
+ })
+ fireEvent.click(
+ screen.getByRole('button', { name: 'viking://resources/output' }),
+ )
+ expect(onOpenResource).toHaveBeenCalledWith('viking://resources/output')
+ expect(
+ screen
+ .getByText('viking://resources/input-a, viking://resources/input-b')
+ .closest('button'),
+ ).toBeNull()
+ fireEvent.click(
+ screen.getByRole('button', { name: 'viking://resources/input-b' }),
+ )
+ expect(onOpenResource).toHaveBeenCalledWith('viking://resources/input-b')
+ client.clear()
+})
diff --git a/web-studio/src/routes/filesystem/-components/context-explorer.tsx b/web-studio/src/routes/filesystem/-components/context-explorer.tsx
index b74f47260..a501d10ff 100644
--- a/web-studio/src/routes/filesystem/-components/context-explorer.tsx
+++ b/web-studio/src/routes/filesystem/-components/context-explorer.tsx
@@ -92,17 +92,6 @@ export function ContextExplorerHeader({
>
<SearchIcon className="size-4" />
</Button>
- {onAddResource ? (
- <Button
- type="button"
- size="icon-sm"
- variant="ghost"
- title={t('explorer.addResource')}
- onClick={onAddResource}
- >
- <PlusIcon className="size-4" />
- </Button>
- ) : null}
<Button
type="button"
size="icon-sm"
@@ -115,6 +104,18 @@ export function ContextExplorerHeader({
/>
</Button>
</div>
+ {onAddResource ? (
+ <Button
+ type="button"
+ size="sm"
+ variant="outline"
+ className="mt-3 w-full justify-center gap-2"
+ onClick={onAddResource}
+ >
+ <PlusIcon className="size-4" />
+ {t('explorer.addResource')}
+ </Button>
+ ) : null}
</div>
)
}
diff --git a/web-studio/src/routes/filesystem/-components/terminal-panel.test.tsx b/web-studio/src/routes/filesystem/-components/terminal-panel.test.tsx
index 7aae40a3e..12518a19a 100644
--- a/web-studio/src/routes/filesystem/-components/terminal-panel.test.tsx
+++ b/web-studio/src/routes/filesystem/-components/terminal-panel.test.tsx
@@ -10,16 +10,18 @@ afterEach(() => {
})
describe('TerminalHistoryItem', () => {
- it('renders command entries with their terminal icon', () => {
+ it('shows the full command in a right-aligned bubble', () => {
+ const command =
+ 'ov add-resource https://example.com/spec.md --to viking://resources/spec'
const { container } = render(
<TerminalHistoryItem
- entry={{ id: 'command-1', kind: 'command', title: '/ls' }}
+ entry={{ id: 'command-1', kind: 'command', title: command }}
onOpenResource={vi.fn()}
openingUri={null}
/>,
)
- expect(screen.getByText('/ls')).not.toBeNull()
- expect(container.querySelector('svg')).not.toBeNull()
+ expect(screen.getByText(command)).not.toBeNull()
+ expect(container.querySelector('.justify-end')).not.toBeNull()
})
})
diff --git a/web-studio/src/routes/filesystem/-components/terminal-panel.tsx b/web-studio/src/routes/filesystem/-components/terminal-panel.tsx
index 291a9049f..dc03dede3 100644
--- a/web-studio/src/routes/filesystem/-components/terminal-panel.tsx
+++ b/web-studio/src/routes/filesystem/-components/terminal-panel.tsx
@@ -1,18 +1,25 @@
import i18n from '#/i18n/core'
-import { prepareCompileHandoff } from '#/routes/compile/-lib/handoff'
import { useQuery } from '@tanstack/react-query'
-import { fetchCompileSkills } from '#/routes/compile/-lib/api'
+import {
+ active as activeCompileTask,
+ fetchCompileSkills,
+ fetchCompileTask,
+} from '#/routes/compile/-lib/api'
import { compileSuggestions } from '#/routes/compile/-lib/suggestions'
import { Link } from '@tanstack/react-router'
import {
CompileCommandError,
isCompileCommand,
compileHistory,
+ tokenize,
} from '#/routes/compile/-lib/commands'
import { runCompileSubmission } from '#/routes/compile/-lib/terminal'
+import { addNewSkill } from '#/routes/skills/-lib/add-skill'
+import { useInvalidateVikingFs } from '#/routes/resources/-hooks/viking-fm'
import { useCallback, useEffect, useMemo, useRef, useState } from 'react'
import { createPortal } from 'react-dom'
import { useTranslation } from 'react-i18next'
+import { toast } from 'sonner'
import {
ArrowRightIcon,
CheckCircle2Icon,
@@ -20,7 +27,6 @@ import {
Loader2Icon,
SendIcon,
SparklesIcon,
- TerminalIcon,
TrashIcon,
XCircleIcon,
} from 'lucide-react'
@@ -38,6 +44,9 @@ import {
getHealth,
getOvResult,
getSystemStatus,
+ getTaskByTaskId,
+ postResources,
+ postContentWrite,
postSystemWait,
} from '#/lib/ov-client'
import {
@@ -55,9 +64,11 @@ import {
searchSessionToolResult,
} from '#/lib/sessions/api'
import { cn } from '#/lib/utils'
+import { fetchGlob, fetchGrep } from '#/lib/retrieval'
import {
fetchDirectoryLevelContent,
fetchFileContent,
+ fetchFind,
fetchFsList,
fetchFsStat,
fetchFsTree,
@@ -68,6 +79,19 @@ import type { VikingFsEntry } from '#/routes/resources/-types/viking-fm'
import type { SessionListItem } from '@ov-server/api/v1/sessions'
import { ROOT_URI, TERMINAL_COMMANDS } from '../-lib/constants'
+import { getCommandInputHint } from '../-lib/terminal-input-hint'
+import {
+ parseAddMemory,
+ parseAddResource,
+ parseAddSkill,
+ parseWrite,
+ submitMemoryCommand,
+ taskResultDetails,
+ taskResultResourceUri,
+ TerminalActionError,
+ waitForResourceTask,
+} from '../-lib/terminal-actions'
+import type { ResourceTaskState } from '../-lib/terminal-actions'
import type {
ResourceRef,
ResourceOpenHandler,
@@ -81,14 +105,13 @@ import {
createIdentityStorageKey,
entryToRef,
getErrorMessage,
- readStoredJsonArray,
registerFilesystemAgentSessionId,
removeStoredValue,
searchResultToRefs,
visibleContextEntries,
- writeStoredJson,
} from '../-lib/utils'
import { ResourceRefList } from './resource-ref-list'
+import type { ResourceImportResult } from '#/routes/resources/-lib/resource-import-types'
const TERMINAL_COMMAND_HISTORY_STORAGE_KEY =
'openviking.playground.terminalCommandHistory'
@@ -96,6 +119,12 @@ const TERMINAL_ENTRY_HISTORY_STORAGE_KEY =
'openviking.playground.terminalEntryHistory'
const TERMINAL_COMMAND_HISTORY_LIMIT = 50
const TERMINAL_ENTRY_HISTORY_LIMIT = 100
+// Keep terminal history across SPA route changes, but discard it on page reload.
+let terminalPageCache: {
+ identityScopeKey: string
+ history: TerminalEntry[]
+ commandHistory: string[]
+} | null = null
const URI_ARGUMENT_COMMANDS = new Set([
'/abstract',
'/ls',
@@ -154,7 +183,7 @@ const SESSION_SUBCOMMANDS: SessionSubcommandHelp[] = [
insertText: '/session context ',
key: 'context',
parameters: ['sessionId', 'tokenBudget'],
- usage: '/session context [session_id] --token-budget 8000',
+ usage: '/session context [<session_id>] [--token-budget <tokens>]',
},
{
examples: ['session.messages'],
@@ -175,21 +204,21 @@ const SESSION_SUBCOMMANDS: SessionSubcommandHelp[] = [
insertText: '/session commit ',
key: 'commit',
parameters: ['sessionId', 'keepRecent'],
- usage: '/session commit [session_id] --keep-recent 10',
+ usage: '/session commit [<session_id>] [--keep-recent <count>]',
},
{
examples: ['session.message'],
insertText: '/session message ',
key: 'message',
parameters: ['sessionId', 'messageRole', 'messageContent'],
- usage: '/session message [session_id] user hello',
+ usage: '/session message [<session_id>] <role> <content>',
},
{
examples: ['session.toolResults'],
insertText: '/session tool-results ',
key: 'tool-results',
parameters: ['sessionId', 'toolName', 'limit'],
- usage: '/session tool-results [session_id] --limit 20',
+ usage: '/session tool-results [<session_id>] [--limit <count>]',
},
{
examples: ['session.toolResult'],
@@ -203,7 +232,7 @@ const SESSION_SUBCOMMANDS: SessionSubcommandHelp[] = [
insertText: '/session tool-search ',
key: 'tool-search',
parameters: ['sessionId', 'toolResultId', 'query', 'limit', 'contextChars'],
- usage: '/session tool-search [session_id] <tool_result_id> query',
+ usage: '/session tool-search [<session_id>] <tool_result_id> <query>',
},
{
examples: ['session.delete'],
@@ -234,12 +263,14 @@ type TerminalQuickStartExample = {
command: string
code: string
key: string
- title: string
}
type ScopedSearchInput = {
query: string
scopeUri?: string
+ limit?: number
+ scoreThreshold?: number
+ sessionId?: string
}
type ParsedOptions = {
@@ -247,82 +278,54 @@ type ParsedOptions = {
positional: string[]
}
-function loadCommandHistory(storageKey: string): string[] {
- return readStoredJsonArray(
- storageKey,
- (item) => {
- if (typeof item !== 'string') return undefined
- const trimmed = item.trim()
- return trimmed || undefined
- },
- TERMINAL_COMMAND_HISTORY_LIMIT,
- )
-}
-
-function persistCommandHistory(storageKey: string, history: string[]): void {
- writeStoredJson(storageKey, history.slice(0, TERMINAL_COMMAND_HISTORY_LIMIT))
-}
-
-function normalizeRefs(value: unknown): ResourceRef[] | undefined {
- if (!Array.isArray(value)) return undefined
- const refs = value
- .filter(
- (item): item is ResourceRef =>
- typeof item === 'object' &&
- item !== null &&
- typeof (item as ResourceRef).uri === 'string',
- )
- .map((item) => ({
- label: typeof item.label === 'string' ? item.label : undefined,
- meta: typeof item.meta === 'string' ? item.meta : undefined,
- uri: item.uri,
- }))
- return refs.length > 0 ? refs : undefined
-}
-
-function loadTerminalHistory(storageKey: string): TerminalEntry[] {
- return readStoredJsonArray(
- storageKey,
- (item): TerminalEntry | undefined => {
- if (typeof item !== 'object' || item === null) return undefined
- const record = item as Record<string, unknown>
- if (
- typeof record.id !== 'string' ||
- typeof record.title !== 'string' ||
- !['command', 'error', 'info', 'success'].includes(
- String(record.kind),
- ) ||
- (record.body !== undefined && typeof record.body !== 'string')
- ) {
- return undefined
- }
- return {
- body: typeof record.body === 'string' ? record.body : undefined,
- id: record.id,
- kind: record.kind as TerminalEntry['kind'],
- refs: normalizeRefs(record.refs),
- title: record.title,
- compileTaskId:
- typeof record.compileTaskId === 'string'
- ? record.compileTaskId
- : undefined,
- compileForm: record.compileForm === true,
- }
- },
- TERMINAL_ENTRY_HISTORY_LIMIT,
- true,
- )
-}
-
-function persistTerminalHistory(
- storageKey: string,
- history: TerminalEntry[],
-): void {
- writeStoredJson(storageKey, history.slice(-TERMINAL_ENTRY_HISTORY_LIMIT))
-}
-
-function clearPersistedTerminalHistory(storageKey: string): void {
- removeStoredValue(storageKey)
+const PARAMETER_META: Partial<
+ Record<
+ TerminalCommandParameterKey,
+ {
+ type: 'Text' | 'URI' | 'Number' | 'Boolean'
+ required?: boolean
+ defaultValue?: string
+ }
+ >
+> = {
+ archiveId: { type: 'Text', required: true },
+ compileFrom: { type: 'URI', required: true },
+ compileSkill: { type: 'URI', required: true },
+ compileTo: { type: 'URI', required: true },
+ contextChars: { type: 'Number' },
+ ignoreCase: { type: 'Boolean', defaultValue: 'false' },
+ keepRecent: { type: 'Number' },
+ limit: { type: 'Number' },
+ memoryContent: { type: 'Text', required: true },
+ memorySessionId: { type: 'Text' },
+ messageContent: { type: 'Text', required: true },
+ messageRole: { type: 'Text', required: true },
+ nodeLimit: { type: 'Number', defaultValue: '10' },
+ offset: { type: 'Number', defaultValue: '0' },
+ pattern: { type: 'Text', required: true },
+ query: { type: 'Text', required: true },
+ resourceParent: { type: 'URI' },
+ resourceReason: { type: 'Text' },
+ resourceArgs: { type: 'Text' },
+ resourceSource: { type: 'Text' },
+ resourceTo: { type: 'URI' },
+ scope: { type: 'URI' },
+ searchSessionId: { type: 'Text' },
+ sessionAction: { type: 'Text' },
+ sessionId: { type: 'Text' },
+ skillParent: { type: 'URI', defaultValue: 'viking://~/skills' },
+ skillSource: { type: 'Text', required: true },
+ taskAction: { type: 'Text', required: true },
+ taskId: { type: 'Text', required: true },
+ threshold: { type: 'Number' },
+ timeout: { type: 'Number' },
+ tokenBudget: { type: 'Number' },
+ toolName: { type: 'Text' },
+ toolResultId: { type: 'Text', required: true },
+ uri: { type: 'URI' },
+ writeContent: { type: 'Text', required: true },
+ writeMode: { type: 'Text', defaultValue: 'replace' },
+ writeWait: { type: 'Boolean', defaultValue: 'false' },
}
function extractVikingUris(text: string): string[] {
@@ -333,16 +336,6 @@ function formatJson(value: unknown): string {
return JSON.stringify(value, null, 2)
}
-function parseWaitTimeout(body: string): number | undefined {
- const trimmed = body.trim()
- if (!trimmed) return undefined
- const match = trimmed.match(/^(?:--timeout\s+)?(\d+(?:\.\d+)?)$/)
- if (!match) {
- throw new Error(i18n.t('studio:errors.waitUsage'))
- }
- return Number(match[1])
-}
-
function joinBodyLines(lines: Array<string | undefined>): string {
return lines.filter((line): line is string => Boolean(line)).join('\n')
}
@@ -408,31 +401,66 @@ function parseScopedSearchInput(
currentUri: string,
missingScopeMessage: string,
): ScopedSearchInput {
- const tokens = body.trim().split(/\s+/).filter(Boolean)
+ const tokens = tokenize(`/find ${body}`).slice(1)
const queryParts: string[] = []
let scopeUri: string | undefined
+ let limit: number | undefined
+ let scoreThreshold: number | undefined
+ let sessionId: string | undefined
for (let index = 0; index < tokens.length; index += 1) {
const token = tokens[index]
- if (token === '--scope') {
+ if (token === '--scope' || token === '--uri' || token === '-u') {
const value = tokens[index + 1]
if (!value) throw new Error(missingScopeMessage)
scopeUri = value === '.' ? currentUri : normalizeDirUri(value)
index += 1
continue
}
- if (token.startsWith('--scope=')) {
- const value = token.slice('--scope='.length)
+ if (token.startsWith('--scope=') || token.startsWith('--uri=')) {
+ const value = token.slice(token.indexOf('=') + 1)
if (!value) throw new Error(missingScopeMessage)
scopeUri = value === '.' ? currentUri : normalizeDirUri(value)
continue
}
+ if (
+ [
+ '--node-limit',
+ '--limit',
+ '-n',
+ '--threshold',
+ '-t',
+ '--session-id',
+ ].includes(token)
+ ) {
+ const value = tokens[index + 1]
+ if (!value) throw new Error(missingScopeMessage)
+ if (token === '--session-id') sessionId = value
+ else {
+ const parsed = Number(value)
+ if (
+ !Number.isFinite(parsed) ||
+ (token !== '--threshold' &&
+ token !== '-t' &&
+ (!Number.isInteger(parsed) || parsed < 0))
+ )
+ throw new Error(missingScopeMessage)
+ if (token === '--threshold' || token === '-t') scoreThreshold = parsed
+ else limit = parsed
+ }
+ index += 1
+ continue
+ }
+ if (token.startsWith('-')) throw new Error(missingScopeMessage)
queryParts.push(token)
}
return {
query: queryParts.join(' ').trim(),
scopeUri,
+ limit,
+ scoreThreshold,
+ sessionId,
}
}
@@ -447,7 +475,6 @@ function sessionToRef(session: Pick<SessionListItem, 'session_id' | 'uri'>) {
export function TerminalPanel({
currentUri,
entries,
- onOpenAddResource,
onOpenResource,
openingUri,
onSessionChange,
@@ -456,7 +483,6 @@ export function TerminalPanel({
}: {
currentUri: string
entries: VikingFsEntry[]
- onOpenAddResource: () => void
onOpenResource: ResourceOpenHandler
openingUri: string | null
onSessionChange: (sessionId: string) => void
@@ -465,14 +491,7 @@ export function TerminalPanel({
}) {
const { t } = useTranslation('filesystem')
const { connectionRole, identityScopeKey } = useAppConnection()
- const commandHistoryStorageKey = createIdentityStorageKey(
- TERMINAL_COMMAND_HISTORY_STORAGE_KEY,
- identityScopeKey,
- )
- const terminalHistoryStorageKey = createIdentityStorageKey(
- TERMINAL_ENTRY_HISTORY_STORAGE_KEY,
- identityScopeKey,
- )
+ const { invalidateAll } = useInvalidateVikingFs()
const [command, setCommand] = useState('')
const [running, setRunning] = useState(false)
const compileSkills = useQuery({
@@ -482,13 +501,35 @@ export function TerminalPanel({
})
const identityRef = useRef(identityScopeKey)
identityRef.current = identityScopeKey
+ const mountedRef = useRef(false)
+ useEffect(() => {
+ mountedRef.current = true
+ return () => {
+ mountedRef.current = false
+ }
+ }, [])
+ const resourcePollsRef = useRef(new Set<AbortController>())
+ const trackedResourceEntriesRef = useRef(new Set<string>())
+ useEffect(() => {
+ return () => {
+ for (const controller of resourcePollsRef.current) controller.abort()
+ resourcePollsRef.current.clear()
+ }
+ }, [identityScopeKey])
const [suggestionsOpen, setSuggestionsOpen] = useState(false)
const [activeSuggestionIndex, setActiveSuggestionIndex] = useState(0)
- const [commandHistory, setCommandHistory] = useState(() =>
- loadCommandHistory(commandHistoryStorageKey),
+ const [previewSuggestionIndex, setPreviewSuggestionIndex] = useState<
+ number | null
+ >(null)
+ const [commandHistory, setCommandHistory] = useState<string[]>(() =>
+ terminalPageCache?.identityScopeKey === identityScopeKey
+ ? terminalPageCache.commandHistory
+ : [],
)
- const [history, setHistory] = useState(() =>
- loadTerminalHistory(terminalHistoryStorageKey),
+ const [history, setHistory] = useState<TerminalEntry[]>(() =>
+ terminalPageCache?.identityScopeKey === identityScopeKey
+ ? terminalPageCache.history
+ : [],
)
const [historyOpen, setHistoryOpen] = useState(false)
const [inputFocused, setInputFocused] = useState(false)
@@ -553,15 +594,51 @@ export function TerminalPanel({
)
}, [command, commands])
+ const inputHint = useMemo(
+ () => getCommandInputHint(command, [...commands, ...SESSION_SUBCOMMANDS]),
+ [command, commands],
+ )
+
const suggestions = useMemo<TerminalSuggestion[]>(() => {
const rawQuery = command.trimStart()
const query = rawQuery.toLowerCase()
+ const commandOrder = [
+ '/add-resource',
+ '/add-skill',
+ '/compile',
+ '/find',
+ '/read',
+ '/write',
+ '/add-memory',
+ '/session',
+ '/ls',
+ '/tree',
+ '/stat',
+ '/search',
+ '/grep',
+ '/glob',
+ '/abstract',
+ '/overview',
+ '/status',
+ '/health',
+ '/task',
+ '/wait',
+ ]
const commandMatches =
- !query || query === '/'
- ? commands.map((item) => ({
- ...item,
- id: `command:${item.command}`,
- }))
+ query === '/'
+ ? [...commands]
+ .sort((a, b) => {
+ const aIndex = commandOrder.indexOf(a.command)
+ const bIndex = commandOrder.indexOf(b.command)
+ return (
+ (aIndex === -1 ? commandOrder.length : aIndex) -
+ (bIndex === -1 ? commandOrder.length : bIndex)
+ )
+ })
+ .map((item) => ({
+ ...item,
+ id: `command:${item.command}`,
+ }))
: query.startsWith('/')
? commands
.filter(
@@ -639,7 +716,7 @@ export function TerminalPanel({
})()
: []
- const historyMatches = commandHistory
+ const historyMatches = (query ? commandHistory : [])
.filter((item) => {
const lower = item.toLowerCase()
return lower !== query && lower.startsWith(query)
@@ -699,15 +776,28 @@ export function TerminalPanel({
return activeCommand
}, [activeCommand])
+ const hoveredHelpCommand =
+ suggestionsOpen && previewSuggestionIndex !== null
+ ? commands.find(
+ (item) =>
+ item.command === suggestions[previewSuggestionIndex]?.command,
+ )
+ : undefined
+ const displayHelpCommand = hoveredHelpCommand ?? helpCommand
+
const selectedSessionSubcommand = useMemo(() => {
- if (helpCommand?.command !== '/session') return undefined
+ if (
+ helpCommand?.command !== '/session' ||
+ displayHelpCommand?.command !== '/session'
+ )
+ return undefined
const body = command
.trimStart()
.slice(helpCommand.command.length)
.trimStart()
const [subcommand = ''] = body.split(/\s+/)
return SESSION_SUBCOMMANDS_BY_KEY.get(subcommand)
- }, [command, helpCommand])
+ }, [command, displayHelpCommand, helpCommand])
const sessionSubcommandRows = useMemo(
() =>
@@ -722,40 +812,57 @@ export function TerminalPanel({
)
const showSessionSubcommandList =
- helpCommand?.command === '/session' && !selectedSessionSubcommand
+ displayHelpCommand?.command === '/session' && !selectedSessionSubcommand
const helpTitle = selectedSessionSubcommand
? `/session ${selectedSessionSubcommand.key}`
- : helpCommand?.command
+ : displayHelpCommand?.command
const helpDescription = selectedSessionSubcommand
? t(
`terminal.commandExamples.${selectedSessionSubcommand.examples[0]}.description`,
)
- : helpCommand?.description
+ : displayHelpCommand?.description
const helpUsage = selectedSessionSubcommand
? selectedSessionSubcommand.usage
- : helpCommand?.usage
+ : displayHelpCommand?.usage
const commandParameters = useMemo(
() =>
(
selectedSessionSubcommand?.parameters ??
- (showSessionSubcommandList ? [] : (helpCommand?.parameters ?? []))
+ (showSessionSubcommandList
+ ? []
+ : (displayHelpCommand?.parameters ?? []))
).map((key) => {
+ const meta: {
+ type: 'Text' | 'URI' | 'Number' | 'Boolean'
+ required?: boolean
+ defaultValue?: string
+ } = PARAMETER_META[key] ?? { type: 'Text' }
return {
description: t(`terminal.commandParameters.${key}.description`),
key,
name: t(`terminal.commandParameters.${key}.name`),
+ ...meta,
+ ...(key === 'nodeLimit' &&
+ ['/grep', '/glob'].includes(displayHelpCommand?.command ?? '')
+ ? { defaultValue: '256' }
+ : {}),
}
}),
- [helpCommand, selectedSessionSubcommand, showSessionSubcommandList, t],
+ [
+ displayHelpCommand,
+ selectedSessionSubcommand,
+ showSessionSubcommandList,
+ t,
+ ],
)
const commandExamples = useMemo(
() =>
(
selectedSessionSubcommand?.examples ??
- (showSessionSubcommandList ? [] : (helpCommand?.examples ?? []))
+ (showSessionSubcommandList ? [] : (displayHelpCommand?.examples ?? []))
).map((key) => {
return {
code: t(`terminal.commandExamples.${key}.code`),
@@ -763,18 +870,25 @@ export function TerminalPanel({
key,
}
}),
- [helpCommand, selectedSessionSubcommand, showSessionSubcommandList, t],
+ [
+ displayHelpCommand,
+ selectedSessionSubcommand,
+ showSessionSubcommandList,
+ t,
+ ],
)
const canUseCurrentScope =
- helpCommand?.command === '/find' || helpCommand?.command === '/search'
+ displayHelpCommand?.command === '/find' ||
+ displayHelpCommand?.command === '/search'
const showCommandAssist =
inputFocused &&
- (Boolean(helpCommand) || (suggestionsOpen && suggestions.length > 0))
+ (Boolean(displayHelpCommand) || (suggestionsOpen && suggestions.length > 0))
useEffect(() => {
setActiveSuggestionIndex(0)
+ setPreviewSuggestionIndex(null)
}, [suggestions.length])
useEffect(() => {
@@ -795,49 +909,213 @@ export function TerminalPanel({
})
}, [history.length, running])
- const append = useCallback(
- (entry: Omit<TerminalEntry, 'id'>) => {
- setHistory((prev) => {
- const next = [
- ...prev,
- {
- ...entry,
- id: `${Date.now()}-${prev.length}`,
- },
- ].slice(-TERMINAL_ENTRY_HISTORY_LIMIT)
- persistTerminalHistory(terminalHistoryStorageKey, next)
- return next
- })
+ const append = useCallback((entry: Omit<TerminalEntry, 'id'>) => {
+ const id = crypto.randomUUID()
+ setHistory((prev) =>
+ [
+ ...prev,
+ {
+ ...entry,
+ createdAt: Date.now(),
+ id,
+ },
+ ].slice(-TERMINAL_ENTRY_HISTORY_LIMIT),
+ )
+ return id
+ }, [])
+
+ const updateEntry = useCallback(
+ (id: string, changes: Partial<Omit<TerminalEntry, 'id'>>) => {
+ setHistory((prev) =>
+ prev.map((entry) =>
+ entry.id === id ? { ...entry, ...changes } : entry,
+ ),
+ )
},
- [terminalHistoryStorageKey],
+ [],
)
+ const trackBackgroundTask = useCallback(
+ (
+ taskId: string,
+ title: string,
+ completedBody: string,
+ notifyOnComplete = true,
+ existingEntryId?: string,
+ resource?: { fallbackUri?: string; source: string },
+ ) => {
+ const entryId =
+ existingEntryId ??
+ append({
+ backgroundTaskCompletedBody: completedBody,
+ backgroundTaskNotify: notifyOnComplete,
+ backgroundTaskFallbackUri: resource?.fallbackUri,
+ backgroundTaskSource: resource?.source,
+ body: t('terminal.resourceProcessing', { taskId }),
+ kind: 'info',
+ resourceTaskId: taskId,
+ title,
+ })
+ if (trackedResourceEntriesRef.current.has(entryId)) return
+ trackedResourceEntriesRef.current.add(entryId)
+ const controller = new AbortController()
+ resourcePollsRef.current.add(controller)
+ void (async () => {
+ try {
+ const task = await waitForResourceTask(
+ taskId,
+ async (id) =>
+ getOvResult<ResourceTaskState>(
+ getTaskByTaskId({
+ path: { task_id: id },
+ signal: controller.signal,
+ }),
+ ),
+ { signal: controller.signal },
+ )
+ if (
+ controller.signal.aborted ||
+ identityRef.current !== identityScopeKey
+ )
+ return
+ if (!task) {
+ updateEntry(entryId, {
+ body: t('terminal.resourceStillProcessing', { taskId }),
+ })
+ } else if (task.status !== 'completed') {
+ updateEntry(entryId, {
+ body: t('terminal.backgroundTaskFailed', {
+ reason: task.error || task.status,
+ taskId,
+ }),
+ kind: 'error',
+ })
+ } else {
+ await invalidateAll()
+ const resultUri = taskResultResourceUri(task, resource?.fallbackUri)
+ const details = taskResultDetails(taskId, task, resultUri).map(
+ ({ key, ...detail }) => ({
+ ...detail,
+ label: t(`terminal.taskDetails.${key}`),
+ }),
+ )
+ updateEntry(entryId, {
+ body: resource
+ ? t('terminal.resourceCompleted', {
+ uri: resultUri || resource.source,
+ })
+ : completedBody,
+ details,
+ kind: 'success',
+ refs: resultUri ? [{ uri: resultUri }] : undefined,
+ })
+ if (notifyOnComplete) {
+ toast.success(t('terminal.taskCompleted'), {
+ description: t('terminal.taskCompletedHint'),
+ duration: Infinity,
+ action: {
+ label: t('terminal.viewResult'),
+ onClick: () => {
+ if (resultUri) {
+ void onOpenResource(resultUri)
+ } else {
+ document
+ .getElementById(`terminal-entry-${entryId}`)
+ ?.scrollIntoView({
+ behavior: 'smooth',
+ block: 'center',
+ })
+ }
+ },
+ },
+ })
+ }
+ }
+ } catch (error) {
+ if (
+ !controller.signal.aborted &&
+ identityRef.current === identityScopeKey
+ )
+ updateEntry(entryId, {
+ body: t('terminal.backgroundTaskFailed', {
+ reason: getErrorMessage(error),
+ taskId,
+ }),
+ kind: 'error',
+ })
+ } finally {
+ resourcePollsRef.current.delete(controller)
+ }
+ })()
+ },
+ [append, identityScopeKey, invalidateAll, onOpenResource, t, updateEntry],
+ )
+
+ useEffect(() => {
+ if (previousIdentityScopeKey.current !== identityScopeKey) return
+ for (const entry of history) {
+ if (entry.kind !== 'info' || !entry.resourceTaskId) continue
+ if (trackedResourceEntriesRef.current.has(entry.id)) continue
+ trackBackgroundTask(
+ entry.resourceTaskId,
+ entry.title,
+ entry.backgroundTaskCompletedBody ?? t('terminal.taskCompleted'),
+ entry.backgroundTaskNotify ?? false,
+ entry.id,
+ entry.backgroundTaskSource
+ ? {
+ fallbackUri: entry.backgroundTaskFallbackUri,
+ source: entry.backgroundTaskSource,
+ }
+ : undefined,
+ )
+ }
+ }, [history, identityScopeKey, t, trackBackgroundTask])
+
const clearHistory = useCallback(() => {
setHistory([])
- clearPersistedTerminalHistory(terminalHistoryStorageKey)
- }, [terminalHistoryStorageKey])
+ }, [])
- const rememberCommand = useCallback(
- (raw: string) => {
- const trimmed = raw.trim()
- if (!trimmed) return
- setCommandHistory((prev) => {
- const next = [
- trimmed,
- ...prev.filter(
- (item) => item.toLowerCase() !== trimmed.toLowerCase(),
- ),
- ].slice(0, TERMINAL_COMMAND_HISTORY_LIMIT)
- persistCommandHistory(commandHistoryStorageKey, next)
- return next
- })
- },
- [commandHistoryStorageKey],
- )
+ const rememberCommand = useCallback((raw: string) => {
+ const trimmed = raw.trim()
+ if (!trimmed) return
+ setCommandHistory((prev) => {
+ const next = [
+ trimmed,
+ ...prev.filter((item) => item.toLowerCase() !== trimmed.toLowerCase()),
+ ].slice(0, TERMINAL_COMMAND_HISTORY_LIMIT)
+ return next
+ })
+ }, [])
const compileSubmission = useRef<{ raw: string; key: string } | null>(null)
+ const previousIdentityScopeKey = useRef(identityScopeKey)
+ useEffect(() => {
+ if (previousIdentityScopeKey.current !== identityScopeKey) return
+ terminalPageCache = { identityScopeKey, history, commandHistory }
+ }, [identityScopeKey, history, commandHistory])
useEffect(() => {
compileSubmission.current = null
+ removeStoredValue(
+ createIdentityStorageKey(
+ TERMINAL_COMMAND_HISTORY_STORAGE_KEY,
+ identityScopeKey,
+ ),
+ )
+ removeStoredValue(
+ createIdentityStorageKey(
+ TERMINAL_ENTRY_HISTORY_STORAGE_KEY,
+ identityScopeKey,
+ ),
+ )
+ if (previousIdentityScopeKey.current !== identityScopeKey) {
+ terminalPageCache = null
+ trackedResourceEntriesRef.current.clear()
+ setHistory([])
+ setCommandHistory([])
+ setCommand('')
+ previousIdentityScopeKey.current = identityScopeKey
+ }
}, [identityScopeKey])
const runCommand = useCallback(
async (raw: string) => {
@@ -845,16 +1123,82 @@ export function TerminalPanel({
if (!trimmed || running) return
const isCompile = isCompileCommand(trimmed)
+ const isSensitiveImport =
+ /^(?:ov\s+)?\/?add-(?:memory|skill)(?:\s|$)/.test(trimmed)
+ const isSensitiveResource =
+ /^(?:ov\s+)?\/?(?:add-resource|write)(?:\s|$)/.test(trimmed)
const safeHistory = isCompile
? compileHistory(trimmed)
- : { title: trimmed, remember: true }
- append({ kind: 'command', title: safeHistory.title })
+ : isSensitiveImport || isSensitiveResource
+ ? {
+ title:
+ trimmed.match(/add-(?:memory|skill|resource)|write/)?.[0] ??
+ 'command',
+ remember: false,
+ }
+ : { title: trimmed, remember: true }
+ append({ kind: 'command', title: trimmed })
if (safeHistory.remember) rememberCommand(safeHistory.title)
setCommand('')
setSuggestionsOpen(false)
setRunning(true)
try {
+ if (isSensitiveImport) {
+ if (/^(?:ov\s+)?\/?add-memory(?:\s|$)/.test(trimmed)) {
+ const { content, sessionId: targetSessionId } =
+ parseAddMemory(trimmed)
+ const submission = await submitMemoryCommand(
+ content,
+ targetSessionId,
+ () =>
+ mountedRef.current && identityRef.current === identityScopeKey,
+ { createSession, addMessage, commitSession },
+ )
+ if (!submission) return
+ const { id, result } = submission
+ if (result.task_id) {
+ trackBackgroundTask(
+ result.task_id,
+ '/add-memory',
+ t('terminal.memoryCompleted', { id }),
+ false,
+ )
+ } else {
+ append({
+ kind: 'success',
+ title: '/add-memory',
+ body: joinBodyLines([
+ t('terminal.addMemorySubmitted'),
+ id,
+ formatJson(result),
+ ]),
+ refs: [{ uri: `viking://session/${id}` }],
+ })
+ }
+ return
+ }
+ const { source, targetUri } = parseAddSkill(trimmed)
+ const result = await addNewSkill(
+ source,
+ targetUri as `viking://${string}`,
+ )
+ if (identityRef.current !== identityScopeKey) return
+ if (result.task_id) {
+ trackBackgroundTask(
+ result.task_id,
+ '/add-skill',
+ t('terminal.skillCompleted'),
+ )
+ } else {
+ append({
+ kind: 'success',
+ title: '/add-skill',
+ body: t('terminal.addSkillSubmitted'),
+ })
+ }
+ return
+ }
if (isCompile) {
if (/^(?:ov\s+)?\/?compile$/.test(trimmed)) {
append({
@@ -902,7 +1246,11 @@ export function TerminalPanel({
})
return
}
- const [name = '', ...args] = trimmed.split(/\s+/)
+ const normalized = trimmed.replace(/^ov\s+/, '')
+ const commandInput = normalized.startsWith('/')
+ ? normalized
+ : `/${normalized}`
+ const [name = '', ...args] = commandInput.split(/\s+/)
const body = args.join(' ').trim()
if (trimmed.startsWith('viking://')) {
@@ -939,14 +1287,8 @@ export function TerminalPanel({
return
}
case '/wait': {
- const timeout = parseWaitTimeout(body)
- const result = await getOvResult<unknown>(
- postSystemWait({
- body: {
- timeout,
- },
- }),
- )
+ if (body) throw new Error(t('terminal.waitUsage'))
+ const result = await getOvResult<unknown>(postSystemWait())
append({
body: formatJson(result),
kind: 'success',
@@ -1042,16 +1384,27 @@ export function TerminalPanel({
}
case '/find':
case '/search': {
- const { query, scopeUri } = parseScopedSearchInput(
+ const {
+ query,
+ scopeUri,
+ limit,
+ scoreThreshold,
+ sessionId: searchSessionId,
+ } = parseScopedSearchInput(
body,
currentUri,
t('terminal.searchUsage', { name }),
)
if (!query) throw new Error(t('terminal.searchUsage', { name }))
- const result = await fetchSearch(query, {
- limit: 8,
- targetUri: scopeUri,
- })
+ const result = await (name === '/find' ? fetchFind : fetchSearch)(
+ query,
+ {
+ limit: limit ?? 10,
+ targetUri: scopeUri,
+ scoreThreshold,
+ ...(name === '/search' ? { sessionId: searchSessionId } : {}),
+ },
+ )
const scopeText = scopeUri ?? t('terminal.globalScope')
const summary = t('terminal.hits', {
memories: result.memories.length,
@@ -1070,13 +1423,100 @@ export function TerminalPanel({
})
return
}
- case '/add-resource': {
- onOpenAddResource()
+ case '/grep':
+ case '/glob': {
+ const tokens = tokenize(trimmed)
+ const pattern = tokens[1]
+ if (!pattern || pattern.startsWith('-'))
+ throw new Error(t('terminal.patternUsage', { name }))
+ let uri = ROOT_URI
+ let limit = 256
+ let caseInsensitive = false
+ for (let i = 2; i < tokens.length; i++) {
+ const flag = tokens[i]
+ if (flag === '-i' && name === '/grep') {
+ caseInsensitive = true
+ continue
+ }
+ const value = tokens[++i]
+ if (!value) throw new Error(t('terminal.patternUsage', { name }))
+ if (flag === '--uri' || flag === '-u') uri = value
+ else if (['--node-limit', '-n', '--limit'].includes(flag)) {
+ const parsed = Number(value)
+ if (!Number.isInteger(parsed) || parsed < 0)
+ throw new Error(t('terminal.patternUsage', { name }))
+ limit = parsed
+ } else throw new Error(t('terminal.patternUsage', { name }))
+ }
+ const result =
+ name === '/grep'
+ ? await fetchGrep(pattern, { uri, limit, caseInsensitive })
+ : await fetchGlob(pattern, { uri, limit })
append({
- body: t('terminal.addResourceBody'),
- kind: 'info',
- title: t('terminal.addResourceTitle'),
+ body: t('terminal.patternHits', {
+ count: result.resources.length,
+ uri,
+ }),
+ kind: 'success',
+ refs: searchResultToRefs(result, groupLabels),
+ title: `${name} ${pattern}`,
+ })
+ return
+ }
+ case '/write': {
+ const request = parseWrite(trimmed)
+ const result = await getOvResult<unknown>(
+ postContentWrite({ body: request }),
+ )
+ if (identityRef.current !== identityScopeKey) return
+ append({
+ body: formatJson(result),
+ kind: 'success',
+ refs: [{ uri: request.uri }],
+ title: `/write ${request.uri}`,
})
+ await invalidateAll()
+ await onOpenResource(request.uri)
+ return
+ }
+ case '/add-resource': {
+ const request = parseAddResource(trimmed)
+ const result = await getOvResult<ResourceImportResult>(
+ postResources({ body: request }),
+ )
+ if (identityRef.current !== identityScopeKey) return
+ if (result.status === 'error') {
+ throw new Error(
+ result.errors?.join('; ') ||
+ result.message ||
+ t('terminal.resourceFailed'),
+ )
+ }
+ const taskId = result.task_id?.trim()
+ const rootUri = result.root_uri || request.to
+ if (!taskId) {
+ await invalidateAll()
+ if (rootUri) await onOpenResource(rootUri)
+ append({
+ body: t('terminal.resourceCompleted', {
+ uri: rootUri || request.path,
+ }),
+ kind: 'success',
+ title: '/add-resource',
+ refs: rootUri ? [{ uri: rootUri }] : undefined,
+ })
+ return
+ }
+ trackBackgroundTask(
+ taskId,
+ '/add-resource',
+ t('terminal.resourceCompleted', {
+ uri: rootUri || request.path,
+ }),
+ true,
+ undefined,
+ { fallbackUri: rootUri, source: request.path },
+ )
return
}
case '/session': {
@@ -1215,6 +1655,15 @@ export function TerminalPanel({
id,
getNumberFlag(flags, 'keep-recent'),
)
+ if (result.task_id) {
+ trackBackgroundTask(
+ result.task_id,
+ `/session commit ${id}`,
+ t('terminal.memoryCompleted', { id }),
+ false,
+ )
+ return
+ }
append({
body: formatJson(result),
kind: 'success',
@@ -1350,7 +1799,9 @@ export function TerminalPanel({
body:
error instanceof CompileCommandError
? t(`compile:commandErrors.${error.code}`)
- : getErrorMessage(error),
+ : error instanceof TerminalActionError
+ ? t(`terminal.${error.code}`)
+ : getErrorMessage(error),
kind: 'error',
title: t('terminal.commandFailed'),
})
@@ -1364,13 +1815,14 @@ export function TerminalPanel({
entries,
groupLabels,
identityScopeKey,
- onOpenAddResource,
+ invalidateAll,
onOpenResource,
onSessionChange,
running,
rememberCommand,
sessionId,
t,
+ updateEntry,
],
)
@@ -1389,14 +1841,14 @@ export function TerminalPanel({
const insertCurrentScope = useCallback(() => {
const trimmed = command.trimEnd()
- const hasScope = trimmed.match(/(?:^|\s)--scope(?:=|\s)/)
+ const hasScope = trimmed.match(/(?:^|\s)(?:--uri|--scope|-u)(?:=|\s)/)
const commandName = helpCommand?.command ?? trimmed.split(/\s+/)[0]
const body = trimmed.slice(commandName.length).trim()
const next = hasScope
? command
: body
- ? `${trimmed} --scope ${currentUri}`
- : `${commandName} --scope ${currentUri}`
+ ? `${trimmed} --uri ${currentUri}`
+ : `${commandName} --uri ${currentUri}`
const cursorPosition =
hasScope || body ? next.length : commandName.length + 1
setCommand(next)
@@ -1408,34 +1860,37 @@ export function TerminalPanel({
})
}, [command, currentUri, helpCommand])
- const quickCommands = commands.filter((item) =>
- ['/status', '/find', '/search', '/add-resource'].includes(item.command),
- )
-
const quickStartExamples = useMemo<TerminalQuickStartExample[]>(
() => [
{
- action: () => void runCommand('/add-resource'),
+ action: () => acceptSuggestion({ insertText: '/add-resource ' }),
code: t('terminal.quickStart.addResource.code'),
command: t('terminal.quickStart.addResource.command'),
key: 'add-resource',
- title: t('terminal.quickStart.addResource.title'),
},
{
+ action: () => acceptSuggestion({ insertText: '/add-skill ' }),
+ code: t('terminal.quickStart.addSkill.code'),
+ command: t('terminal.quickStart.addSkill.command'),
+ key: 'add-skill',
+ },
+ {
+ action: () => acceptSuggestion({ insertText: '/add-memory ' }),
code: t('terminal.quickStart.addMemory.code'),
command: t('terminal.quickStart.addMemory.command'),
key: 'add-memory',
- title: t('terminal.quickStart.addMemory.title'),
},
{
code: t('terminal.quickStart.find.code'),
command: t('terminal.quickStart.find.command'),
key: 'find',
- title: t('terminal.quickStart.find.title'),
- action: () => void runCommand(t('terminal.quickStart.find.command')),
+ action: () =>
+ acceptSuggestion({
+ insertText: t('terminal.quickStart.find.command'),
+ }),
},
],
- [runCommand, t],
+ [acceptSuggestion, t],
)
return (
@@ -1467,6 +1922,8 @@ export function TerminalPanel({
<TerminalQuickStart
examples={quickStartExamples}
title={t('terminal.quickStart.title')}
+ heading={t('terminal.quickStart.heading')}
+ description={t('terminal.quickStart.description')}
/>
) : null}
{history.map((entry) => (
@@ -1485,230 +1942,154 @@ export function TerminalPanel({
) : null}
</div>
</div>
- <div className="border-t bg-background/80 p-3">
- <div className="mb-2 flex flex-wrap gap-1.5">
- <button
- type="button"
- className="rounded-md border px-2 py-1 font-mono text-[11px]"
- onClick={() => setCommand('compile')}
- >
- {t('compile:title')}
- </button>
- <Link
- to="/compile/new"
- onClick={() => prepareCompileHandoff(identityScopeKey, command)}
- className="rounded-md border px-2 py-1 text-[11px]"
- >
- {t('compile:openForm')}
- </Link>
- {quickCommands.map((item) => (
- <button
- key={item.command}
- type="button"
- className="rounded-md border bg-muted/40 px-2 py-1 font-mono text-[11px] text-muted-foreground transition-colors hover:border-primary/40 hover:text-foreground"
- onClick={() => acceptSuggestion(item)}
- >
- {item.command}
- </button>
- ))}
- </div>
+ <div className="border-t bg-background p-3">
<form
- className="relative flex items-center gap-2 rounded-lg border bg-muted/30 px-2 py-2"
+ className="relative rounded-xl border bg-background px-3 py-2 focus-within:border-ring"
onSubmit={(event) => {
event.preventDefault()
void runCommand(command)
}}
>
<span
- className="max-w-[45%] shrink-0 truncate font-mono text-[11px] text-muted-foreground"
+ className="block truncate font-mono text-[10px] text-muted-foreground"
title={t('terminal.scopeLabel', { uri: currentUri })}
>
{currentUri}
</span>
- <input
- ref={inputRef}
- value={command}
- onBlur={() => {
- window.setTimeout(() => {
- setInputFocused(false)
- setSuggestionsOpen(false)
- }, 120)
- }}
- onChange={(event) => {
- setCommand(event.target.value)
- setSuggestionsOpen(true)
- }}
- onFocus={() => {
- setInputFocused(true)
- setSuggestionsOpen(true)
- }}
- onKeyDown={(event) => {
- if (!suggestionsOpen || suggestions.length === 0) return
- if (event.key === 'ArrowDown') {
- event.preventDefault()
- setActiveSuggestionIndex((current) =>
- Math.min(current + 1, suggestions.length - 1),
- )
- return
- }
- if (event.key === 'ArrowUp') {
- event.preventDefault()
- setActiveSuggestionIndex((current) =>
- Math.max(current - 1, 0),
- )
- return
- }
- if (event.key === 'Tab') {
- event.preventDefault()
- acceptSuggestion(suggestions[activeSuggestionIndex])
- return
- }
- if (
- event.key === 'ArrowRight' &&
- event.currentTarget.selectionStart === command.length &&
- event.currentTarget.selectionEnd === command.length
- ) {
- event.preventDefault()
- acceptSuggestion(suggestions[activeSuggestionIndex])
- return
- }
- if (event.key === 'Enter') {
- event.preventDefault()
- acceptSuggestion(suggestions[activeSuggestionIndex])
- return
- }
- if (event.key === 'Escape') {
- setSuggestionsOpen(false)
- }
- }}
- placeholder={t('terminal.placeholder')}
- className="h-8 min-w-0 flex-1 bg-transparent font-mono text-sm outline-none placeholder:text-muted-foreground/60"
- />
- {showCommandAssist ? (
- <div className="absolute bottom-[calc(100%+0.5rem)] left-0 right-0 z-20 max-h-[min(72vh,36rem)] overflow-y-auto rounded-xl border bg-popover shadow-xl">
- {helpCommand ? (
- <div className="border-b p-3">
- <div className="flex min-w-0 items-start justify-between gap-3">
- <div className="min-w-0">
- <div className="truncate font-mono text-sm font-semibold text-primary">
- {helpTitle}
- </div>
- <div className="mt-0.5 text-xs leading-4 text-muted-foreground">
- {helpDescription}
- </div>
- </div>
- <div className="shrink-0 rounded-md bg-muted px-2 py-1 font-mono text-[11px] text-muted-foreground">
- {helpUsage}
- </div>
- </div>
- <div className="mt-3 space-y-3">
- {showSessionSubcommandList ? (
+ <div className="flex min-w-0 items-center gap-2">
+ <div className="relative min-w-0 flex-1">
+ {inputHint ? (
+ <div
+ aria-hidden="true"
+ className="pointer-events-none absolute inset-0 flex h-8 min-w-0 items-center overflow-hidden whitespace-pre font-mono text-xs"
+ >
+ <span className="text-transparent">{command}</span>
+ <span className="truncate text-muted-foreground/70">
+ {inputHint}
+ </span>
+ </div>
+ ) : null}
+ <input
+ ref={inputRef}
+ value={command}
+ onBlur={() => {
+ window.setTimeout(() => {
+ setInputFocused(false)
+ setSuggestionsOpen(false)
+ }, 120)
+ }}
+ onChange={(event) => {
+ setCommand(event.target.value)
+ setSuggestionsOpen(true)
+ setPreviewSuggestionIndex(null)
+ }}
+ onFocus={() => {
+ setInputFocused(true)
+ setSuggestionsOpen(true)
+ }}
+ onKeyDown={(event) => {
+ if (!suggestionsOpen || suggestions.length === 0) return
+ if (event.key === 'ArrowDown') {
+ event.preventDefault()
+ setActiveSuggestionIndex((current) =>
+ Math.min(current + 1, suggestions.length - 1),
+ )
+ setPreviewSuggestionIndex((current) =>
+ Math.min(
+ (current ?? activeSuggestionIndex) + 1,
+ suggestions.length - 1,
+ ),
+ )
+ return
+ }
+ if (event.key === 'ArrowUp') {
+ event.preventDefault()
+ setActiveSuggestionIndex((current) =>
+ Math.max(current - 1, 0),
+ )
+ setPreviewSuggestionIndex((current) =>
+ Math.max((current ?? activeSuggestionIndex) - 1, 0),
+ )
+ return
+ }
+ if (event.key === 'Tab') {
+ event.preventDefault()
+ acceptSuggestion(suggestions[activeSuggestionIndex])
+ return
+ }
+ if (
+ event.key === 'ArrowRight' &&
+ event.currentTarget.selectionStart === command.length &&
+ event.currentTarget.selectionEnd === command.length
+ ) {
+ event.preventDefault()
+ acceptSuggestion(suggestions[activeSuggestionIndex])
+ return
+ }
+ if (event.key === 'Enter') {
+ event.preventDefault()
+ acceptSuggestion(suggestions[activeSuggestionIndex])
+ return
+ }
+ if (event.key === 'Escape') {
+ setSuggestionsOpen(false)
+ }
+ }}
+ placeholder={t('terminal.placeholder')}
+ className="relative h-8 w-full min-w-0 bg-transparent font-mono text-xs outline-none placeholder:text-muted-foreground/80"
+ />
+ </div>
+ {showCommandAssist ? (
+ <div className="pointer-events-none absolute bottom-[calc(100%+0.5rem)] left-0 right-0 z-30">
+ {displayHelpCommand ? (
+ <div
+ className={cn(
+ 'pointer-events-auto max-h-[min(420px,52vh)] overflow-y-auto rounded-xl border bg-popover p-4 shadow-lg',
+ suggestionsOpen && suggestions.length > 0
+ ? 'absolute bottom-0 right-[calc(100%+2px)] hidden w-[400px] lg:block'
+ : 'w-full',
+ )}
+ >
+ <div className="flex min-w-0 items-start justify-between gap-3">
<div className="min-w-0">
- <div className="mb-1.5 text-[11px] font-medium text-muted-foreground">
- {t('terminal.helpSubcommands')}
+ <div className="truncate font-mono text-base font-semibold text-foreground">
+ {helpTitle}
</div>
- <div className="overflow-hidden rounded-md border">
- <table className="w-full table-fixed border-collapse text-xs">
- <tbody className="divide-y">
- {sessionSubcommandRows.map((item) => (
- <tr key={item.key}>
- <td className="w-40 align-top bg-muted/30 px-2 py-1.5 font-mono text-foreground">
- <button
- type="button"
- className="block max-w-full truncate text-left text-primary hover:underline"
- title={item.usage}
- onClick={() =>
- acceptSuggestion({
- insertText: item.insertText,
- })
- }
- onMouseDown={(event) =>
- event.preventDefault()
- }
- >
- {item.key}
- </button>
- </td>
- <td className="align-top px-2 py-1.5 leading-4 text-muted-foreground">
- {item.description}
- </td>
- </tr>
- ))}
- </tbody>
- </table>
+ <div className="mt-1 text-xs leading-5 text-muted-foreground">
+ {helpDescription}
</div>
</div>
- ) : (
- <>
- <div className="min-w-0">
- <div className="mb-1.5 text-[11px] font-medium text-muted-foreground">
- {t('terminal.helpParameters')}
- </div>
- {commandParameters.length > 0 ? (
- <div className="overflow-hidden rounded-md border">
- <table className="w-full table-fixed border-collapse text-xs">
- <tbody className="divide-y">
- {commandParameters.map((parameter) => (
- <tr key={parameter.key}>
- <td className="w-32 align-top bg-muted/30 px-2 py-1.5 font-mono text-foreground">
- <span className="block truncate">
- {parameter.name}
- </span>
- </td>
- <td className="align-top px-2 py-1.5 text-muted-foreground">
- <div className="flex min-w-0 items-start justify-between gap-2">
- <span className="min-w-0 leading-4">
- {parameter.description}
- </span>
- {canUseCurrentScope &&
- parameter.key === 'scope' ? (
- <Button
- type="button"
- variant="outline"
- size="sm"
- className="h-6 shrink-0 px-2 text-xs"
- onClick={insertCurrentScope}
- onMouseDown={(event) =>
- event.preventDefault()
- }
- >
- {t(
- 'terminal.currentScopeAction',
- )}
- </Button>
- ) : null}
- </div>
- </td>
- </tr>
- ))}
- </tbody>
- </table>
- </div>
- ) : (
- <div className="rounded-md border px-2 py-1.5 text-xs text-muted-foreground">
- {t('terminal.noParameters')}
- </div>
- )}
- </div>
+ </div>
+ <div className="mt-4 space-y-4">
+ {showSessionSubcommandList ? (
<div className="min-w-0">
<div className="mb-1.5 text-[11px] font-medium text-muted-foreground">
- {t('terminal.helpExamples')}
+ {t('terminal.helpSubcommands')}
</div>
<div className="overflow-hidden rounded-md border">
<table className="w-full table-fixed border-collapse text-xs">
<tbody className="divide-y">
- {commandExamples.map((example) => (
- <tr key={example.key}>
- <td className="w-56 align-top bg-muted/30 px-2 py-1.5 font-mono text-foreground">
- <span
- className="block truncate"
- title={example.code}
+ {sessionSubcommandRows.map((item) => (
+ <tr key={item.key}>
+ <td className="w-40 align-top bg-muted/30 px-2 py-1.5 font-mono text-foreground">
+ <button
+ type="button"
+ className="block max-w-full truncate text-left text-primary hover:underline"
+ title={item.usage}
+ onClick={() =>
+ acceptSuggestion({
+ insertText: item.insertText,
+ })
+ }
+ onMouseDown={(event) =>
+ event.preventDefault()
+ }
>
- {example.code}
- </span>
+ {item.key}
+ </button>
</td>
<td className="align-top px-2 py-1.5 leading-4 text-muted-foreground">
- {example.description}
+ {item.description}
</td>
</tr>
))}
@@ -1716,77 +2097,212 @@ export function TerminalPanel({
</table>
</div>
</div>
- </>
- )}
- </div>
- </div>
- ) : null}
- {suggestionsOpen && suggestions.length > 0 ? (
- <div className="max-h-56 overflow-y-auto p-1.5">
- {suggestions.map((suggestion, index) => (
- <button
- key={suggestion.id}
- ref={(node) => {
- suggestionRefs.current[index] = node
- }}
- type="button"
- title={`${suggestion.usage} · ${t('terminal.suggestionsHint')}`}
- className={cn(
- 'min-h-8 w-full min-w-0 rounded-md px-2.5 py-1 text-left transition-colors',
- index === activeSuggestionIndex
- ? 'bg-primary/10 text-foreground'
- : 'hover:bg-muted/60',
- )}
- onClick={() => acceptSuggestion(suggestion)}
- onMouseDown={(event) => event.preventDefault()}
- onMouseEnter={() => setActiveSuggestionIndex(index)}
- >
- {suggestion.group === 'history' ||
- suggestion.group === 'resource' ||
- suggestion.group === 'subcommand' ? (
- <span className="flex min-w-0 items-center gap-3">
- <span
- className="min-w-0 flex-1 truncate font-mono text-xs font-semibold text-primary"
- title={suggestion.command}
- >
- {suggestion.command}
- </span>
- <span className="shrink-0 text-xs leading-4 text-muted-foreground">
- {suggestion.description}
- </span>
- </span>
) : (
- <span className="grid min-w-0 grid-cols-[minmax(5.25rem,7.5rem)_minmax(0,1fr)] items-center gap-2.5">
- <span
- className="min-w-0 truncate font-mono text-xs font-semibold text-primary"
- title={suggestion.command}
- >
- {suggestion.command}
- </span>
- <span className="min-w-0 text-xs leading-4 text-muted-foreground">
- {suggestion.description}
- </span>
- </span>
+ <>
+ {commandExamples.length > 0 ? (
+ <div className="min-w-0">
+ <div className="mb-2 text-xs text-muted-foreground">
+ {t('terminal.quickStart.title')}
+ </div>
+ <div className="space-y-1">
+ {commandExamples.map((example, index) => (
+ <button
+ key={example.key}
+ type="button"
+ className="flex w-full items-start gap-2 rounded-lg bg-muted/70 px-3 py-2 text-left font-mono text-xs leading-5 text-foreground transition-colors hover:bg-muted focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring"
+ title={example.description}
+ onMouseDown={(event) =>
+ event.preventDefault()
+ }
+ onClick={() =>
+ acceptSuggestion({
+ insertText: example.code,
+ })
+ }
+ >
+ <span className="w-4 shrink-0 text-muted-foreground">
+ {index + 1}
+ </span>
+ <span className="min-w-0 break-all">
+ {example.code}
+ </span>
+ </button>
+ ))}
+ </div>
+ </div>
+ ) : null}
+ <div className="min-w-0">
+ <div className="mb-1.5 text-sm font-semibold text-foreground">
+ {t('terminal.helpParameters')}
+ </div>
+ <div className="mb-1 break-all rounded-md border bg-muted/70 px-3 py-2 font-mono text-xs leading-5 text-foreground">
+ {helpUsage}
+ </div>
+ {commandParameters.length > 0 ? (
+ <div className="overflow-hidden rounded-md border">
+ <table className="w-full table-fixed border-collapse text-[11px]">
+ <thead className="border-b bg-muted/40 text-muted-foreground">
+ <tr>
+ <th className="w-[32%] px-2 py-1.5 text-left font-medium">
+ {t('terminal.parameterName')}
+ </th>
+ <th className="w-[12%] px-1 py-1.5 text-center font-medium">
+ {t('terminal.parameterRequired')}
+ </th>
+ <th className="w-[41%] px-2 py-1.5 text-left font-medium">
+ {t('terminal.parameterDescription')}
+ </th>
+ <th className="w-[15%] px-1 py-1.5 text-center font-medium">
+ {t('terminal.parameterDefault')}
+ </th>
+ </tr>
+ </thead>
+ <tbody className="divide-y">
+ {commandParameters.map((parameter) => (
+ <tr key={parameter.key}>
+ <td className="align-top px-2 py-1.5 text-foreground">
+ <span className="block break-all font-mono leading-4">
+ {parameter.name}
+ </span>
+ <span className="mt-1 inline-block rounded bg-muted px-1 py-0.5 text-[9px] leading-none text-muted-foreground">
+ {t(
+ `terminal.parameterTypes.${parameter.type}`,
+ )}
+ </span>
+ </td>
+ <td className="align-top px-1 py-1.5 text-center text-muted-foreground">
+ {parameter.required
+ ? t('terminal.yes')
+ : t('terminal.no')}
+ </td>
+ <td className="align-top px-2 py-1.5 text-muted-foreground">
+ <div className="flex min-w-0 items-start justify-between gap-2">
+ <span className="min-w-0 break-words leading-4">
+ {parameter.description}
+ </span>
+ {canUseCurrentScope &&
+ parameter.key === 'scope' ? (
+ <Button
+ type="button"
+ variant="outline"
+ size="sm"
+ className="h-6 shrink-0 px-2 text-xs"
+ onClick={insertCurrentScope}
+ onMouseDown={(event) =>
+ event.preventDefault()
+ }
+ >
+ {t(
+ 'terminal.currentScopeAction',
+ )}
+ </Button>
+ ) : null}
+ </div>
+ </td>
+ <td className="break-all px-1 py-1.5 text-center font-mono text-muted-foreground">
+ {parameter.defaultValue ?? '—'}
+ </td>
+ </tr>
+ ))}
+ </tbody>
+ </table>
+ </div>
+ ) : (
+ <div className="rounded-md border border-dashed bg-muted/40 px-3 py-2 text-center text-xs text-muted-foreground">
+ {t('terminal.noParameters')}
+ </div>
+ )}
+ </div>
+ </>
)}
- </button>
- ))}
- </div>
- ) : null}
- </div>
- ) : null}
- <Button
- type="submit"
- size="icon-sm"
- disabled={running || !command.trim()}
- >
- <SendIcon className="size-4" />
- </Button>
+ </div>
+ </div>
+ ) : null}
+ {suggestionsOpen && suggestions.length > 0 ? (
+ <div className="pointer-events-auto max-h-[min(360px,45vh)] overflow-y-auto rounded-xl border bg-popover px-2 py-3 shadow-lg">
+ {suggestions.map((suggestion, index) => (
+ <div key={suggestion.id}>
+ {index === 0 ||
+ suggestions[index - 1]?.group !== suggestion.group ? (
+ <div className="px-2.5 pb-1 pt-2 text-[10px] text-muted-foreground">
+ {t(`terminal.paletteGroups.${suggestion.group}`)}
+ </div>
+ ) : null}
+ <button
+ ref={(node) => {
+ suggestionRefs.current[index] = node
+ }}
+ type="button"
+ className={cn(
+ 'min-h-8 w-full min-w-0 rounded-md px-2.5 py-1 text-left transition-colors focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring',
+ index === activeSuggestionIndex
+ ? 'bg-muted text-foreground'
+ : 'hover:bg-muted/60',
+ )}
+ onClick={() => acceptSuggestion(suggestion)}
+ onMouseDown={(event) => event.preventDefault()}
+ onMouseEnter={() => {
+ setActiveSuggestionIndex(index)
+ setPreviewSuggestionIndex(index)
+ }}
+ >
+ {suggestion.group === 'history' ||
+ suggestion.group === 'resource' ||
+ suggestion.group === 'subcommand' ? (
+ <span className="flex min-w-0 items-center gap-3">
+ <span className="min-w-0 flex-1 truncate font-mono text-xs font-medium text-foreground">
+ {suggestion.command}
+ </span>
+ <span className="shrink-0 text-xs leading-4 text-muted-foreground">
+ {suggestion.description}
+ </span>
+ </span>
+ ) : (
+ <span className="grid min-w-0 grid-cols-[minmax(5.25rem,7.5rem)_minmax(0,1fr)] items-center gap-2.5">
+ <span className="min-w-0 truncate font-mono text-xs font-medium text-foreground">
+ {suggestion.command}
+ </span>
+ <span className="min-w-0 text-xs leading-4 text-muted-foreground">
+ {suggestion.description}
+ </span>
+ </span>
+ )}
+ </button>
+ </div>
+ ))}
+ </div>
+ ) : null}
+ </div>
+ ) : null}
+ <Button
+ type="submit"
+ size="icon-sm"
+ disabled={running || !command.trim()}
+ >
+ <SendIcon className="size-4" />
+ </Button>
+ </div>
</form>
+ <div className="mt-2 flex flex-wrap gap-1.5">
+ {quickStartExamples.map((example) => (
+ <button
+ key={example.key}
+ type="button"
+ className="rounded-md border bg-muted/30 px-2 py-1 font-mono text-[11px] text-foreground transition-colors hover:bg-muted focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring"
+ onClick={example.action}
+ >
+ {`/${example.key}`}
+ </button>
+ ))}
+ </div>
+ <div className="mt-1.5 text-[10px] text-muted-foreground">
+ {t('terminal.inputHint')}
+ </div>
</div>
</div>
<Dialog open={historyOpen} onOpenChange={setHistoryOpen}>
<DialogContent className="gap-4 sm:max-w-2xl">
- <DialogHeader>
+ <DialogHeader className="pr-10">
<div className="flex items-start gap-3">
<div className="min-w-0 flex-1">
<DialogTitle>{t('terminal.historyTitle')}</DialogTitle>
@@ -1833,34 +2349,42 @@ export function TerminalPanel({
}
function TerminalQuickStart({
+ description,
examples,
+ heading,
title,
}: {
+ description: string
examples: TerminalQuickStartExample[]
+ heading: string
title: string
}) {
return (
- <section className="space-y-3 py-3">
- <div className="text-xs font-semibold text-muted-foreground">{title}</div>
+ <section className="py-10">
+ <h2 className="font-mono text-xl font-normal tracking-tight text-foreground">
+ {heading}
+ <span
+ aria-hidden="true"
+ className="ml-1 inline-block h-4 w-1 bg-muted-foreground/30"
+ />
+ </h2>
+ <p className="mt-1 text-xs text-muted-foreground">{description}</p>
+ <div className="mb-2 mt-8 text-xs text-muted-foreground">{title}</div>
<div className="space-y-2">
{examples.map((example) => {
const content = (
<>
- <span className="flex size-8 shrink-0 items-center justify-center rounded-md bg-background text-muted-foreground">
- <ArrowRightIcon className="size-4" />
+ <span className="flex size-4 shrink-0 items-center justify-center text-muted-foreground">
+ <ArrowRightIcon className="size-3" />
</span>
- <span className="min-w-0 flex-1">
- <span className="flex flex-wrap items-center gap-2">
- <span className="text-sm font-medium text-foreground">
- {example.title}
- </span>
- <span className="rounded-md border bg-background px-2 py-0.5 font-mono text-xs font-semibold">
- {example.command}
- </span>
- </span>
- <span className="mt-1 block truncate font-mono text-xs text-muted-foreground">
- {example.code}
- </span>
+ <span className="w-[13ch] shrink-0 truncate font-mono text-xs text-foreground">
+ {example.key}
+ </span>
+ <span
+ className="min-w-0 flex-1 truncate text-xs text-muted-foreground"
+ title={example.code}
+ >
+ {example.code}
</span>
</>
)
@@ -1869,7 +2393,7 @@ function TerminalQuickStart({
return (
<div
key={example.key}
- className="flex min-w-0 items-center gap-3 rounded-lg bg-muted/40 px-3 py-3"
+ className="flex h-[43px] min-w-0 items-center gap-3 rounded-2xl bg-muted/40 px-4"
>
{content}
</div>
@@ -1880,7 +2404,7 @@ function TerminalQuickStart({
<button
key={example.key}
type="button"
- className="flex w-full min-w-0 items-center gap-3 rounded-lg bg-muted/40 px-3 py-3 text-left transition-colors hover:bg-muted/70"
+ className="flex h-[43px] w-full min-w-0 items-center gap-3 rounded-2xl bg-muted/40 px-4 text-left transition-colors hover:bg-muted/70 focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring"
onClick={example.action}
>
{content}
@@ -1901,10 +2425,32 @@ export function TerminalHistoryItem({
onOpenResource: ResourceOpenHandler
openingUri: string | null
}) {
- const { t } = useTranslation('filesystem')
+ const { t, i18n: translation } = useTranslation('filesystem')
+ if (entry.kind === 'command') {
+ return (
+ <div id={`terminal-entry-${entry.id}`} className="flex justify-end">
+ <div className="flex max-w-[90%] items-end gap-2 rounded-xl bg-muted/60 px-3 py-2.5 font-mono text-xs leading-5">
+ <span className="min-w-0 whitespace-pre-wrap break-all">
+ {entry.title}
+ </span>
+ {entry.createdAt && (
+ <time className="shrink-0 text-[11px] text-muted-foreground">
+ {new Date(entry.createdAt).toLocaleTimeString(
+ translation.language,
+ {
+ hour: '2-digit',
+ minute: '2-digit',
+ },
+ )}
+ </time>
+ )}
+ </div>
+ </div>
+ )
+ }
const Icon =
- entry.kind === 'command'
- ? TerminalIcon
+ entry.kind === 'info' && entry.resourceTaskId
+ ? Loader2Icon
: entry.kind === 'success'
? CheckCircle2Icon
: entry.kind === 'error'
@@ -1913,9 +2459,9 @@ export function TerminalHistoryItem({
return (
<section
+ id={`terminal-entry-${entry.id}`}
className={cn(
'rounded-lg border bg-background px-3 py-3 text-sm',
- entry.kind === 'command' && 'border-muted bg-muted/40 font-mono',
entry.kind === 'error' && 'border-destructive/30 bg-destructive/5',
)}
>
@@ -1923,33 +2469,74 @@ export function TerminalHistoryItem({
<Icon
className={cn(
'size-3.5 shrink-0 text-muted-foreground',
+ entry.kind === 'info' && entry.resourceTaskId && 'animate-spin',
entry.kind === 'success' && 'text-primary',
+ entry.compileTaskId && 'text-emerald-600',
entry.kind === 'error' && 'text-destructive',
)}
/>
<span className="min-w-0 truncate text-xs font-semibold">
{entry.title}
</span>
+ {entry.compileTaskId && (
+ <Link
+ to="/compile/tasks/$taskId"
+ params={{ taskId: entry.compileTaskId }}
+ className="ml-auto shrink-0 text-xs text-primary hover:underline"
+ >
+ {t('compile:viewTask')}
+ </Link>
+ )}
+ {entry.resourceTaskId && (
+ <Link
+ to="/tasks"
+ className="ml-auto shrink-0 text-xs text-primary hover:underline"
+ >
+ {t('terminal.viewResourceTask')}
+ </Link>
+ )}
</div>
- {entry.compileTaskId && (
- <Link
- to="/compile/tasks/$taskId"
- params={{ taskId: entry.compileTaskId }}
- className="text-xs text-primary underline"
- >
- {t('compile:viewTask')}
- </Link>
- )}
{entry.compileForm && (
<Link to="/compile/new" className="text-xs text-primary underline">
{t('compile:openForm')}
</Link>
)}
- {entry.body ? (
- <pre className="max-h-56 overflow-auto whitespace-pre-wrap break-words rounded-md bg-muted/40 p-2 text-xs leading-5 text-muted-foreground">
+ {entry.compileTaskId ? (
+ <CompileTaskResult
+ taskId={entry.compileTaskId}
+ fallback={entry.body}
+ onOpenResource={onOpenResource}
+ />
+ ) : entry.body ? (
+ <pre className="whitespace-pre-wrap break-words rounded-md bg-muted/40 p-2 text-xs leading-5 text-muted-foreground">
{entry.body}
</pre>
) : null}
+ {entry.details?.length ? (
+ <dl className="mt-2 space-y-2">
+ {entry.details.map((detail) => (
+ <div
+ key={detail.label}
+ className="flex min-w-0 gap-2 rounded-[10px] bg-muted/40 px-3 py-2.5 font-mono text-xs"
+ >
+ <dt className="shrink-0 text-muted-foreground">{detail.label}</dt>
+ <dd className="min-w-0 break-all">
+ {detail.uri ? (
+ <button
+ type="button"
+ className="text-left text-primary hover:underline"
+ onClick={() => void onOpenResource(detail.uri!)}
+ >
+ {detail.value}
+ </button>
+ ) : (
+ detail.value
+ )}
+ </dd>
+ </div>
+ ))}
+ </dl>
+ ) : null}
{entry.refs?.length ? (
<ResourceRefList
className="mt-2"
@@ -1961,3 +2548,130 @@ export function TerminalHistoryItem({
</section>
)
}
+
+export function CompileTaskResult({
+ taskId,
+ fallback,
+ onOpenResource,
+}: {
+ taskId: string
+ fallback?: string
+ onOpenResource: ResourceOpenHandler
+}) {
+ const { t } = useTranslation('compile')
+ const { identityScopeKey } = useAppConnection()
+ const { invalidateAll, invalidatePreview } = useInvalidateVikingFs()
+ const refreshedTasksRef = useRef(new Set<string>())
+ const query = useQuery({
+ queryKey: ['compile-task', identityScopeKey, taskId],
+ queryFn: ({ signal }) => fetchCompileTask(taskId, signal),
+ refetchInterval: (result) =>
+ !result.state.data || activeCompileTask(result.state.data.status)
+ ? 5000
+ : false,
+ })
+ const task = query.data
+ useEffect(() => {
+ const key = `${identityScopeKey}:${taskId}`
+ if (task?.status !== 'completed' || refreshedTasksRef.current.has(key))
+ return
+ refreshedTasksRef.current.add(key)
+ void invalidateAll()
+ void invalidatePreview()
+ }, [identityScopeKey, invalidateAll, invalidatePreview, task?.status, taskId])
+ const rows = task
+ ? [
+ { label: t('terminalResult.taskId'), value: task.task_id },
+ {
+ label: t('terminalResult.taskType'),
+ value: task.task_type || 'compile',
+ },
+ {
+ label: t('terminalResult.status'),
+ value: t(`statuses.${task.status}`, {
+ defaultValue: task.status || 'unknown',
+ }),
+ },
+ task.created_at && {
+ label: t('terminalResult.createdAt'),
+ value: String(task.created_at),
+ },
+ task.updated_at && {
+ label: t('terminalResult.updatedAt'),
+ value: String(task.updated_at),
+ },
+ task.resource_id && {
+ label: t('terminalResult.resourceId'),
+ value: task.resource_id,
+ },
+ task.meta?.request?.to && {
+ label: t('terminalResult.outputUri'),
+ value: task.meta.request.to,
+ uri: task.meta.request.to,
+ },
+ ...(task.meta?.request?.from ?? []).map((uri, index) => ({
+ label: t('terminalResult.inputUri', { index: index + 1 }),
+ value: uri,
+ uri,
+ })),
+ task.meta?.request && {
+ label: t('terminalResult.request'),
+ value: JSON.stringify(task.meta.request),
+ },
+ task.stage && {
+ label: t('terminalResult.stage'),
+ value: t(`stages.${task.stage.replace(/^compile:\s*/, '')}`, {
+ defaultValue: task.stage,
+ }),
+ },
+ task.created_at_iso && {
+ label: t('terminalResult.createdAtIso'),
+ value: task.created_at_iso,
+ },
+ task.updated_at_iso && {
+ label: t('terminalResult.updatedAtIso'),
+ value: task.updated_at_iso,
+ },
+ task.error && { label: t('terminalResult.error'), value: task.error },
+ ].filter((row): row is { label: string; value: string; uri?: string } =>
+ Boolean(row),
+ )
+ : []
+
+ return (
+ <>
+ {query.isError && (
+ <p className="mb-2 text-xs text-destructive">{t('stale')}</p>
+ )}
+ {task ? (
+ <dl className="space-y-2 font-mono text-xs leading-5">
+ {rows.map((row) => (
+ <div
+ key={row.label}
+ className="min-w-0 rounded-lg bg-muted/40 px-3 py-2.5"
+ >
+ <dt className="inline">{row.label}: </dt>
+ <dd className="inline break-all">
+ {row.uri ? (
+ <button
+ type="button"
+ className="text-left text-primary underline-offset-2 hover:underline"
+ onClick={() => void onOpenResource(row.uri!)}
+ >
+ {row.value}
+ </button>
+ ) : (
+ row.value
+ )}
+ </dd>
+ </div>
+ ))}
+ </dl>
+ ) : fallback ? (
+ <pre className="whitespace-pre-wrap break-words rounded-md bg-muted/40 p-2 text-xs leading-5 text-muted-foreground">
+ {fallback}
+ </pre>
+ ) : null}
+ </>
+ )
+}
diff --git a/web-studio/src/routes/filesystem/-lib/constants.ts b/web-studio/src/routes/filesystem/-lib/constants.ts
index d02538041..38c528c2b 100644
--- a/web-studio/src/routes/filesystem/-lib/constants.ts
+++ b/web-studio/src/routes/filesystem/-lib/constants.ts
@@ -50,7 +50,7 @@ export const TERMINAL_COMMANDS: TerminalCommandSuggestion[] = [
group: 'search',
key: 'search',
insertText: '/search ',
- parameters: ['query', 'scope'],
+ parameters: ['query', 'scope', 'nodeLimit', 'threshold', 'searchSessionId'],
},
{
command: '/read',
@@ -68,15 +68,58 @@ export const TERMINAL_COMMANDS: TerminalCommandSuggestion[] = [
group: 'core',
key: 'find',
insertText: '/find ',
- parameters: ['query', 'scope'],
+ parameters: ['query', 'scope', 'nodeLimit', 'threshold'],
+ },
+ {
+ command: '/compile',
+ executable: true,
+ examples: ['compile.default'],
+ group: 'core',
+ key: 'compile',
+ insertText: '/compile ',
+ parameters: ['compileFrom', 'compileTo', 'compileSkill'],
},
{
command: '/add-resource',
executable: true,
- examples: ['addResource.default'],
+ examples: ['addResource.default', 'addResource.remote'],
group: 'core',
key: 'addResource',
- insertText: '/add-resource',
+ insertText: '/add-resource ',
+ parameters: [
+ 'resourceSource',
+ 'resourceTo',
+ 'resourceParent',
+ 'resourceReason',
+ 'resourceArgs',
+ ],
+ },
+ {
+ command: '/add-skill',
+ executable: true,
+ examples: ['addSkill.git'],
+ group: 'core',
+ key: 'addSkill',
+ insertText: '/add-skill ',
+ parameters: ['skillSource', 'skillParent'],
+ },
+ {
+ command: '/add-memory',
+ executable: true,
+ examples: ['addMemory.default'],
+ group: 'core',
+ key: 'addMemory',
+ insertText: '/add-memory ',
+ parameters: ['memoryContent', 'memorySessionId'],
+ },
+ {
+ command: '/write',
+ executable: true,
+ examples: ['write.default', 'write.append'],
+ group: 'core',
+ key: 'write',
+ insertText: '/write ',
+ parameters: ['uri', 'writeContent', 'writeMode', 'writeWait'],
},
{
command: '/session',
@@ -133,6 +176,24 @@ export const TERMINAL_COMMANDS: TerminalCommandSuggestion[] = [
insertText: '/stat ',
parameters: ['uri'],
},
+ {
+ command: '/grep',
+ executable: true,
+ examples: ['grep.default', 'grep.scoped'],
+ group: 'search',
+ key: 'grep',
+ insertText: '/grep ',
+ parameters: ['pattern', 'scope', 'nodeLimit', 'ignoreCase'],
+ },
+ {
+ command: '/glob',
+ executable: true,
+ examples: ['glob.default', 'glob.scoped'],
+ group: 'search',
+ key: 'glob',
+ insertText: '/glob ',
+ parameters: ['pattern', 'scope', 'nodeLimit'],
+ },
{
command: '/abstract',
executable: true,
@@ -160,13 +221,20 @@ export const TERMINAL_COMMANDS: TerminalCommandSuggestion[] = [
insertText: '/health',
},
{
- adminOnly: true,
+ command: '/task',
+ executable: true,
+ examples: ['task.list', 'task.status', 'task.cancel'],
+ group: 'status',
+ key: 'task',
+ insertText: '/task ',
+ parameters: ['taskAction', 'taskId'],
+ },
+ {
command: '/wait',
executable: true,
- examples: ['wait.default', 'wait.timeout'],
+ examples: ['wait.default'],
group: 'status',
key: 'wait',
- insertText: '/wait ',
- parameters: ['timeout'],
+ insertText: '/wait',
},
]
diff --git a/web-studio/src/routes/filesystem/-lib/terminal-actions.test.ts b/web-studio/src/routes/filesystem/-lib/terminal-actions.test.ts
new file mode 100644
index 000000000..8cd9ef1a8
--- /dev/null
+++ b/web-studio/src/routes/filesystem/-lib/terminal-actions.test.ts
@@ -0,0 +1,178 @@
+import { describe, expect, it, vi } from 'vitest'
+import {
+ parseAddMemory,
+ parseAddResource,
+ parseAddSkill,
+ submitMemoryCommand,
+ taskResultDetails,
+ taskResultResourceUri,
+ waitForResourceTask,
+} from './terminal-actions'
+
+describe('terminal import commands', () => {
+ it('stops a memory submission when its connection changes during session creation', async () => {
+ let finishCreate!: (session: { session_id: string }) => void
+ const createSession = vi.fn(
+ () =>
+ new Promise<{ session_id: string }>((resolve) => {
+ finishCreate = resolve
+ }),
+ )
+ const addMessage = vi.fn().mockResolvedValue(undefined)
+ const commitSession = vi.fn().mockResolvedValue({ task_id: 'task' })
+ let active = true
+ const submission = submitMemoryCommand('secret', undefined, () => active, {
+ createSession,
+ addMessage,
+ commitSession,
+ })
+ active = false
+ finishCreate({ session_id: 'old-session' })
+ expect(await submission).toBeUndefined()
+ expect(addMessage).not.toHaveBeenCalled()
+ expect(commitSession).not.toHaveBeenCalled()
+ })
+
+ it('does not commit a memory after switching connections during addMessage', async () => {
+ let finishMessage!: () => void
+ const addMessage = vi.fn(
+ () =>
+ new Promise<void>((resolve) => {
+ finishMessage = resolve
+ }),
+ )
+ const commitSession = vi.fn().mockResolvedValue({ task_id: 'task' })
+ let active = true
+ const submission = submitMemoryCommand(
+ 'secret',
+ 'old-session',
+ () => active,
+ {
+ createSession: vi.fn(),
+ addMessage,
+ commitSession,
+ },
+ )
+ active = false
+ finishMessage()
+ expect(await submission).toBeUndefined()
+ expect(commitSession).not.toHaveBeenCalled()
+ })
+ it('accepts quoted memory content and a session ID', () => {
+ expect(
+ parseAddMemory('/add-memory "a useful fact" --session-id session-1'),
+ ).toEqual({
+ content: 'a useful fact',
+ sessionId: 'session-1',
+ })
+ })
+
+ it('can create a new session for a one-shot memory command', () => {
+ expect(parseAddMemory('/add-memory "a useful fact"')).toEqual({
+ content: 'a useful fact',
+ sessionId: undefined,
+ })
+ })
+
+ it('accepts a Git URL and rejects host filesystem paths', () => {
+ expect(
+ parseAddSkill('/add-skill https://example.com/skill.git --scope agent'),
+ ).toEqual({
+ source: 'https://example.com/skill.git',
+ targetUri: 'viking://agent/skills',
+ })
+ expect(
+ parseAddSkill(
+ '/add-skill https://example.com/skill.git -p viking://~/skills',
+ ),
+ ).toEqual({
+ source: 'https://example.com/skill.git',
+ targetUri: 'viking://~/skills',
+ })
+ expect(() => parseAddSkill('/add-skill ./local/skill')).toThrow()
+ })
+
+ it('maps browser-safe resource URLs to the open-source resource API', () => {
+ expect(
+ parseAddResource(
+ `ov add-resource https://github.com/volcengine/OpenViking --to viking://resources/openviking-repo --args '{"branch":"main"}'`,
+ ),
+ ).toEqual({
+ path: 'https://github.com/volcengine/OpenViking',
+ to: 'viking://resources/openviking-repo',
+ args: { branch: 'main' },
+ })
+ expect(() =>
+ parseAddResource('/add-resource https://example.com --args []'),
+ ).toThrow()
+ expect(() => parseAddResource('/add-resource ./local.md')).toThrow()
+ expect(() =>
+ parseAddResource(
+ '/add-resource https://example.com --to viking://a --parent viking://b',
+ ),
+ ).toThrow()
+ })
+})
+
+describe('resource task completion', () => {
+ it('opens the task-produced resource before a requested fallback path', () => {
+ expect(
+ taskResultResourceUri(
+ {
+ status: 'completed',
+ resource_id: 'viking://resources/generated',
+ },
+ 'viking://resources/requested',
+ ),
+ ).toBe('viking://resources/generated')
+ expect(
+ taskResultResourceUri(
+ {
+ status: 'completed',
+ resource_id: 'opaque-task-id',
+ result: { root_uri: 'viking://agent/skills/demo' },
+ },
+ 'viking://resources/requested',
+ ),
+ ).toBe('viking://agent/skills/demo')
+ })
+ it('shows only fields returned by a completed task, including zero auxiliary files', () => {
+ expect(
+ taskResultDetails('task-1', {
+ status: 'completed',
+ result: {
+ root_uri: 'viking://agent/skills/demo',
+ name: 'demo',
+ auxiliary_files: 0,
+ },
+ }),
+ ).toEqual([
+ { key: 'taskId', value: 'task-1' },
+ {
+ key: 'rootUri',
+ value: 'viking://agent/skills/demo',
+ uri: 'viking://agent/skills/demo',
+ },
+ { key: 'name', value: 'demo' },
+ { key: 'auxiliaryFiles', value: '0' },
+ ])
+ })
+ it('does not treat task submission or running as a completed import', async () => {
+ const fetchTask = vi
+ .fn()
+ .mockResolvedValueOnce({ status: 'pending' })
+ .mockResolvedValueOnce({ status: 'running' })
+ .mockResolvedValueOnce({
+ status: 'failed',
+ error: 'Source URL returned HTTP 404',
+ })
+ const task = await waitForResourceTask('task-1', fetchTask, {
+ wait: async () => {},
+ })
+ expect(fetchTask).toHaveBeenCalledTimes(3)
+ expect(task).toEqual({
+ status: 'failed',
+ error: 'Source URL returned HTTP 404',
+ })
+ })
+})
diff --git a/web-studio/src/routes/filesystem/-lib/terminal-actions.ts b/web-studio/src/routes/filesystem/-lib/terminal-actions.ts
new file mode 100644
index 000000000..433f6814e
--- /dev/null
+++ b/web-studio/src/routes/filesystem/-lib/terminal-actions.ts
@@ -0,0 +1,227 @@
+import { tokenize } from '#/routes/compile/-lib/commands'
+
+export class TerminalActionError extends Error {
+ constructor(
+ readonly code:
+ | 'addMemoryUsage'
+ | 'addSkillUsage'
+ | 'addResourceUsage'
+ | 'writeUsage',
+ ) {
+ super(code)
+ }
+}
+
+export async function submitMemoryCommand(
+ content: string,
+ sessionId: string | undefined,
+ isActive: () => boolean,
+ actions: {
+ createSession: () => Promise<{ session_id: string }>
+ addMessage: (id: string, role: 'user', content: string) => Promise<unknown>
+ commitSession: (id: string) => Promise<{ task_id?: string | null }>
+ },
+) {
+ const id = sessionId ?? (await actions.createSession()).session_id
+ if (!isActive()) return
+ await actions.addMessage(id, 'user', content)
+ if (!isActive()) return
+ const result = await actions.commitSession(id)
+ if (!isActive()) return
+ return { id, result }
+}
+
+export type ResourceTaskState = {
+ status: string
+ error?: string | null
+ resource_id?: string | null
+ result?: Record<string, unknown> | null
+}
+
+export function taskResultResourceUri(
+ task: ResourceTaskState,
+ fallbackUri?: string,
+): string | undefined {
+ const result = task.result ?? {}
+ for (const value of [
+ result.root_uri,
+ result.rootUri,
+ result.skill_uri,
+ result.skillUri,
+ result.uri,
+ task.resource_id,
+ fallbackUri,
+ ]) {
+ if (typeof value === 'string' && value.startsWith('viking://')) return value
+ }
+ return undefined
+}
+
+export function taskResultDetails(
+ taskId: string,
+ task: ResourceTaskState,
+ fallbackRootUri?: string,
+): Array<{ key: string; value: string; uri?: string }> {
+ const result = task.result ?? {}
+ const details: Array<{ key: string; value: string; uri?: string }> = [
+ { key: 'taskId', value: taskId },
+ ]
+ for (const [key, field] of [
+ ['rootUri', 'root_uri'],
+ ['uri', 'uri'],
+ ['name', 'name'],
+ ['auxiliaryFiles', 'auxiliary_files'],
+ ] as const) {
+ const value =
+ key === 'rootUri' ? (result[field] ?? fallbackRootUri) : result[field]
+ if (typeof value === 'string' || typeof value === 'number') {
+ const text = String(value)
+ details.push({
+ key,
+ value: text,
+ ...(text.startsWith('viking://') ? { uri: text } : {}),
+ })
+ }
+ }
+ return details
+}
+
+export async function waitForResourceTask(
+ taskId: string,
+ fetchTask: (taskId: string) => Promise<ResourceTaskState>,
+ options: {
+ signal?: AbortSignal
+ intervalMs?: number
+ maxChecks?: number
+ wait?: (ms: number) => Promise<void>
+ } = {},
+): Promise<ResourceTaskState | null> {
+ const {
+ signal,
+ intervalMs = 3000,
+ maxChecks = 200,
+ wait = (ms) => new Promise<void>((resolve) => setTimeout(resolve, ms)),
+ } = options
+ for (let check = 0; check < maxChecks; check++) {
+ if (signal?.aborted) return null
+ const task = await fetchTask(taskId)
+ if (['completed', 'failed', 'cancelled'].includes(task.status)) return task
+ if (check < maxChecks - 1) await wait(intervalMs)
+ }
+ return null
+}
+
+export function parseAddMemory(input: string) {
+ const tokens = tokenize(input)
+ const flagIndex = tokens.indexOf('--session-id')
+ const content = tokens
+ .slice(1, flagIndex < 0 ? undefined : flagIndex)
+ .join(' ')
+ const sessionId = flagIndex < 0 ? '' : tokens[flagIndex + 1]
+ if (
+ tokens[0] !== 'add-memory' ||
+ !content.trim() ||
+ (flagIndex >= 0 && (!sessionId || flagIndex !== tokens.length - 2))
+ )
+ throw new TerminalActionError('addMemoryUsage')
+ return { content, sessionId: sessionId || undefined }
+}
+
+export function parseAddSkill(input: string) {
+ const tokens = tokenize(input)
+ const source = tokens[1]
+ const flag = tokens[2]
+ const targetUri =
+ flag === '-p' || flag === '--parent-auto-create'
+ ? tokens[3]
+ : flag === '--scope'
+ ? tokens[3] === 'agent'
+ ? 'viking://agent/skills'
+ : tokens[3] === 'user'
+ ? 'viking://~/skills'
+ : undefined
+ : 'viking://~/skills'
+ if (
+ tokens[0] !== 'add-skill' ||
+ !source ||
+ !/^(https?:\/\/|git@)/.test(source) ||
+ !targetUri?.startsWith('viking://') ||
+ tokens.length !== (flag ? 4 : 2)
+ )
+ throw new TerminalActionError('addSkillUsage')
+ return { source, targetUri }
+}
+
+export function parseAddResource(input: string) {
+ const tokens = tokenize(input)
+ if (tokens[0] !== 'add-resource' || tokens.length < 2)
+ throw new TerminalActionError('addResourceUsage')
+ const path = tokens[1]
+ if (!/^https?:\/\//.test(path))
+ throw new TerminalActionError('addResourceUsage')
+ const options: {
+ path: string
+ to?: string
+ parent?: string
+ reason?: string
+ args?: Record<string, unknown>
+ } = { path }
+ for (let i = 2; i < tokens.length; i += 2) {
+ const flag = tokens[i]
+ const value = tokens[i + 1]
+ if (!value || value.startsWith('--'))
+ throw new TerminalActionError('addResourceUsage')
+ if (flag === '--to') options.to = value
+ else if (flag === '--parent') options.parent = value
+ else if (flag === '--reason') options.reason = value
+ else if (flag === '--args') {
+ try {
+ const args: unknown = JSON.parse(value)
+ if (!args || typeof args !== 'object' || Array.isArray(args))
+ throw new TerminalActionError('addResourceUsage')
+ options.args = args as Record<string, unknown>
+ } catch {
+ throw new TerminalActionError('addResourceUsage')
+ }
+ } else throw new TerminalActionError('addResourceUsage')
+ }
+ if (
+ (options.to && options.parent) ||
+ [options.to, options.parent].some(
+ (uri) => uri && !uri.startsWith('viking://'),
+ )
+ )
+ throw new TerminalActionError('addResourceUsage')
+ return options
+}
+
+export function parseWrite(input: string) {
+ const tokens = tokenize(input)
+ if (tokens[0] !== 'write' || !tokens[1]?.startsWith('viking://'))
+ throw new TerminalActionError('writeUsage')
+ let content: string | undefined
+ let mode: 'replace' | 'append' | 'create' = 'replace'
+ let wait = false
+ for (let i = 2; i < tokens.length; i++) {
+ const flag = tokens[i]
+ if (flag === '--append') {
+ mode = 'append'
+ continue
+ }
+ if (flag === '--wait') {
+ wait = true
+ continue
+ }
+ const value = tokens[++i]
+ if (!value) throw new TerminalActionError('writeUsage')
+ if (flag === '--content') content = value
+ else if (
+ flag === '--mode' &&
+ ['replace', 'append', 'create'].includes(value)
+ )
+ mode = value as typeof mode
+ else throw new TerminalActionError('writeUsage')
+ }
+ if (content === undefined) throw new TerminalActionError('writeUsage')
+ return { uri: tokens[1], content, mode, wait }
+}
diff --git a/web-studio/src/routes/filesystem/-lib/terminal-input-hint.test.ts b/web-studio/src/routes/filesystem/-lib/terminal-input-hint.test.ts
new file mode 100644
index 000000000..2d8ea538f
--- /dev/null
+++ b/web-studio/src/routes/filesystem/-lib/terminal-input-hint.test.ts
@@ -0,0 +1,34 @@
+import { describe, expect, it } from 'vitest'
+
+import { getCommandInputHint } from './terminal-input-hint'
+
+const templates = [
+ { insertText: '/add-skill ', usage: '/add-skill <Git URL> [-p <URI>]' },
+ { insertText: '/session ', usage: '/session <子命令>' },
+ { insertText: '/session switch ', usage: '/session switch <session_id>' },
+ { insertText: '/status', usage: '/status' },
+]
+
+describe('command parameter hint', () => {
+ it('shows arguments after a selected command without adding them to the value', () => {
+ expect(getCommandInputHint('/add-skill ', templates)).toBe(
+ '<Git URL> [-p <URI>]',
+ )
+ expect(getCommandInputHint('/add-skill', templates)).toBe(
+ ' <Git URL> [-p <URI>]',
+ )
+ })
+
+ it('prefers session subcommands and hides hints once arguments are entered', () => {
+ expect(getCommandInputHint('/session switch ', templates)).toBe(
+ '<session_id>',
+ )
+ expect(getCommandInputHint('/session switch my-session', templates)).toBe(
+ '',
+ )
+ })
+
+ it('does not show parameters for a command without arguments', () => {
+ expect(getCommandInputHint('/status', templates)).toBe('')
+ })
+})
diff --git a/web-studio/src/routes/filesystem/-lib/terminal-input-hint.ts b/web-studio/src/routes/filesystem/-lib/terminal-input-hint.ts
new file mode 100644
index 000000000..d001f8254
--- /dev/null
+++ b/web-studio/src/routes/filesystem/-lib/terminal-input-hint.ts
@@ -0,0 +1,24 @@
+type CommandTemplate = {
+ insertText: string
+ usage: string
+}
+
+/** Show syntax after a selected command without putting placeholders in its value. */
+export function getCommandInputHint(
+ value: string,
+ templates: CommandTemplate[],
+): string {
+ const template = [...templates]
+ .sort((a, b) => b.insertText.length - a.insertText.length)
+ .find(
+ (item) =>
+ value === item.insertText || value === item.insertText.trimEnd(),
+ )
+ if (!template) return ''
+
+ const commandPrefix = template.insertText.trimEnd()
+ if (!template.usage.startsWith(commandPrefix)) return ''
+ const suffix = template.usage.slice(commandPrefix.length)
+ if (!suffix.trim()) return ''
+ return value.endsWith(' ') ? suffix.trimStart() : suffix
+}
diff --git a/web-studio/src/routes/filesystem/-lib/types.ts b/web-studio/src/routes/filesystem/-lib/types.ts
index f144b9eda..99b3bc50b 100644
--- a/web-studio/src/routes/filesystem/-lib/types.ts
+++ b/web-studio/src/routes/filesystem/-lib/types.ts
@@ -15,18 +15,48 @@ export type ResourceRef = {
}
export type TerminalEntry = {
+ backgroundTaskCompletedBody?: string
+ backgroundTaskNotify?: boolean
+ backgroundTaskFallbackUri?: string
+ backgroundTaskSource?: string
+ createdAt?: number
compileTaskId?: string
+ resourceTaskId?: string
compileForm?: boolean
id: string
kind: 'command' | 'error' | 'info' | 'success'
title: string
body?: string
+ details?: Array<{ label: string; value: string; uri?: string }>
refs?: ResourceRef[]
}
export type TerminalCommandGroup = 'core' | 'filesystem' | 'search' | 'status'
export type TerminalCommandParameterKey =
+ | 'compileFrom'
+ | 'compileTo'
+ | 'compileSkill'
+ | 'skillSource'
+ | 'skillScope'
+ | 'skillParent'
+ | 'resourceSource'
+ | 'resourceTo'
+ | 'resourceParent'
+ | 'resourceReason'
+ | 'resourceArgs'
+ | 'writeContent'
+ | 'writeMode'
+ | 'writeWait'
+ | 'nodeLimit'
+ | 'threshold'
+ | 'searchSessionId'
+ | 'pattern'
+ | 'ignoreCase'
+ | 'taskAction'
+ | 'taskId'
+ | 'memoryContent'
+ | 'memorySessionId'
| 'archiveId'
| 'contextChars'
| 'keepRecent'
diff --git a/web-studio/src/routes/filesystem/route.test.tsx b/web-studio/src/routes/filesystem/route.test.tsx
index 2d8bd3cdc..f0ab504a3 100644
--- a/web-studio/src/routes/filesystem/route.test.tsx
+++ b/web-studio/src/routes/filesystem/route.test.tsx
@@ -26,7 +26,7 @@ const mocks = vi.hoisted(() => ({
navigate: vi.fn(),
dataManagement: vi.fn(),
refreshLabel: 'refresh',
- search: {} as { file?: string; uri?: string },
+ search: {} as { file?: string; panel?: 'agent' | 'terminal'; uri?: string },
}))
vi.mock('@tanstack/react-router', async (importOriginal) => {
@@ -96,7 +96,11 @@ vi.mock('./-components/context-explorer', () => ({
<button type="button" aria-label={mocks.refreshLabel} onClick={onRefresh} />
),
ContextTree: () => null,
- PanelTab: () => null,
+ PanelTab: ({ label }: { label: string }) => (
+ <button type="button" role="tab">
+ {label}
+ </button>
+ ),
FilesystemResizeHandle: () => null,
}))
@@ -174,8 +178,9 @@ describe('filesystem context tree refresh', () => {
expect(mocks.dataManagement.mock.lastCall?.[0].isDirectory).toBe(true)
})
- it('offers snapshot history for hosted reads without incompatible local tools', async () => {
+ it('shows only the CLI tab for hosted reads while keeping local tools unavailable', async () => {
mocks.provider = 'volcengine'
+ mocks.search = { file: firstFile, panel: 'agent', uri: parentDirectory }
render(<FilesystemRoute />)
await userEvent.click(
screen.getByRole('button', { name: 'dataManagement:historyTitle' }),
@@ -191,8 +196,11 @@ describe('filesystem context tree refresh', () => {
expect(mocks.preview.mock.lastCall?.[0].defaultReadLimit).toBe(10000)
expect(mocks.uploadProvider.mock.lastCall?.[0]).toBe(false)
expect(mocks.agent).not.toHaveBeenCalled()
- expect(mocks.terminal).not.toHaveBeenCalled()
- expect(screen.queryByRole('tab')).toBeNull()
+ expect(mocks.terminal).toHaveBeenCalled()
+ expect(mocks.agent).not.toHaveBeenCalled()
+ expect(screen.getAllByRole('tab')).toHaveLength(1)
+ expect(screen.getByRole('tab', { name: 'tabs.terminal' })).toBeTruthy()
+ expect(screen.queryByRole('tab', { name: 'tabs.agent' })).toBeNull()
expect(screen.queryByText('addResource.title')).toBeNull()
})
diff --git a/web-studio/src/routes/filesystem/route.tsx b/web-studio/src/routes/filesystem/route.tsx
index f9ce7c91b..d8aed425d 100644
--- a/web-studio/src/routes/filesystem/route.tsx
+++ b/web-studio/src/routes/filesystem/route.tsx
@@ -112,6 +112,7 @@ function FilesystemWorkbench() {
const { t } = useTranslation(['filesystem', 'resources'])
const { provider } = useStudioService()
const canUseLocalTools = provider === 'opensource'
+ const canUseCliPanel = canUseLocalTools || provider === 'volcengine'
const { identityScopeKey } = useAppConnection()
const search = Route.useSearch()
const navigate = useNavigate({ from: Route.fullPath })
@@ -138,7 +139,7 @@ function FilesystemWorkbench() {
),
)
const [activePanel, setActivePanel] = useState<FilesystemPanel>(
- search.panel ?? 'agent',
+ provider === 'volcengine' ? 'terminal' : (search.panel ?? 'agent'),
)
const [actionPanelOpen, setActionPanelOpen] = useState(false)
const isCompactLayout = useIsCompactFilesystemLayout()
@@ -173,6 +174,7 @@ function FilesystemWorkbench() {
)
const [rightCollapsed, setRightCollapsed] = useState(
() =>
+ provider === 'opensource' &&
typeof window !== 'undefined' &&
window.localStorage.getItem(FILESYSTEM_RIGHT_COLLAPSED_STORAGE_KEY) ===
'1',
@@ -261,10 +263,13 @@ function FilesystemWorkbench() {
)
useEffect(() => {
- if (search.panel === 'agent' || search.panel === 'terminal') {
- setActivePanel(search.panel)
+ if (provider === 'volcengine') {
+ setActivePanel('terminal')
+ setRightCollapsed(false)
+ } else {
+ setActivePanel(search.panel ?? 'agent')
}
- }, [search.panel])
+ }, [provider, search.panel])
useEffect(() => {
if (search.upload) {
@@ -377,10 +382,11 @@ function FilesystemWorkbench() {
const handlePanelChange = useCallback(
(panel: FilesystemPanel) => {
+ if (provider === 'volcengine' && panel !== 'terminal') return
setActivePanel(panel)
syncSearch({ panel })
},
- [syncSearch],
+ [provider, syncSearch],
)
const handleOpenActionPanel = useCallback(
@@ -663,7 +669,7 @@ function FilesystemWorkbench() {
</span>
</Button>
) : null}
- {canUseLocalTools ? (
+ {canUseCliPanel ? (
<div className="flex shrink-0 items-center gap-1 lg:hidden">
<Button
type="button"
@@ -675,19 +681,21 @@ function FilesystemWorkbench() {
>
<TerminalIcon className="size-4" />
</Button>
- <Button
- type="button"
- size="icon-sm"
- variant={activePanel === 'agent' ? 'secondary' : 'ghost'}
- title={t('tabs.agent')}
- aria-label={t('tabs.agent')}
- onClick={() => handleOpenActionPanel('agent')}
- >
- <BotIcon className="size-4" />
- </Button>
+ {canUseLocalTools ? (
+ <Button
+ type="button"
+ size="icon-sm"
+ variant={activePanel === 'agent' ? 'secondary' : 'ghost'}
+ title={t('tabs.agent')}
+ aria-label={t('tabs.agent')}
+ onClick={() => handleOpenActionPanel('agent')}
+ >
+ <BotIcon className="size-4" />
+ </Button>
+ ) : null}
</div>
) : null}
- {canUseLocalTools && rightCollapsed ? (
+ {canUseCliPanel && rightCollapsed ? (
<Button
type="button"
size="icon-sm"
@@ -712,7 +720,7 @@ function FilesystemWorkbench() {
/>
</div>
</main>
- {canUseLocalTools && !rightCollapsed ? (
+ {canUseCliPanel && !rightCollapsed ? (
<FilesystemResizeHandle
active={resizingPane === 'action'}
label={t('resizeAction')}
@@ -720,14 +728,13 @@ function FilesystemWorkbench() {
/>
) : null}
- {!isCompactLayout && canUseLocalTools && !rightCollapsed ? (
+ {!isCompactLayout && canUseCliPanel && !rightCollapsed ? (
<aside className="hidden min-h-0 min-w-0 flex-col bg-muted/15 lg:flex lg:w-[var(--filesystem-right-width)] lg:min-w-[var(--filesystem-right-width)]">
<FilesystemActionPanel
activePanel={activePanel}
currentUri={currentUri}
entries={entries}
onCollapse={toggleRightCollapsed}
- onOpenAddResource={() => setUploadDialogOpen(true)}
onOpenResource={revealResource}
onPanelChange={handlePanelChange}
onSessionChange={(sessionId) =>
@@ -735,24 +742,25 @@ function FilesystemWorkbench() {
}
openingUri={openingUri}
sessionId={search.session}
+ showAgentTab={canUseLocalTools}
/>
</aside>
) : null}
</div>
- {canUseLocalTools && isCompactLayout ? (
+ {canUseCliPanel && isCompactLayout ? (
<FilesystemMobileActionScreen
activePanel={activePanel}
currentUri={currentUri}
entries={entries}
onClose={() => setActionPanelOpen(false)}
- onOpenAddResource={() => setUploadDialogOpen(true)}
onOpenResource={revealResource}
onPanelChange={handlePanelChange}
onSessionChange={(sessionId) => syncSearch({ session: sessionId })}
open={actionPanelOpen}
openingUri={openingUri}
sessionId={search.session}
+ showAgentTab={canUseLocalTools}
/>
) : null}
@@ -843,23 +851,23 @@ function FilesystemActionPanel({
currentUri,
entries,
onCollapse,
- onOpenAddResource,
onOpenResource,
onPanelChange,
onSessionChange,
openingUri,
sessionId,
+ showAgentTab,
}: {
activePanel: FilesystemPanel
currentUri: string
entries: VikingFsEntry[]
onCollapse: () => void
- onOpenAddResource: () => void
onOpenResource: ResourceOpenHandler
onPanelChange: (panel: FilesystemPanel) => void
onSessionChange: (sessionId: string) => void
openingUri: string | null
sessionId?: string
+ showAgentTab: boolean
}) {
const { t } = useTranslation('filesystem')
const [toolbarContainer, setToolbarContainer] =
@@ -871,6 +879,7 @@ function FilesystemActionPanel({
<FilesystemActionTabs
activePanel={activePanel}
onPanelChange={onPanelChange}
+ showAgentTab={showAgentTab}
/>
<div
ref={setToolbarContainer}
@@ -893,12 +902,12 @@ function FilesystemActionPanel({
activePanel={activePanel}
currentUri={currentUri}
entries={entries}
- onOpenAddResource={onOpenAddResource}
onOpenResource={onOpenResource}
onSessionChange={onSessionChange}
openingUri={openingUri}
sessionId={sessionId}
toolbarContainer={toolbarContainer}
+ showAgentTab={showAgentTab}
/>
</div>
)
@@ -909,25 +918,25 @@ function FilesystemMobileActionScreen({
currentUri,
entries,
onClose,
- onOpenAddResource,
onOpenResource,
onPanelChange,
onSessionChange,
open,
openingUri,
sessionId,
+ showAgentTab,
}: {
activePanel: FilesystemPanel
currentUri: string
entries: VikingFsEntry[]
onClose: () => void
- onOpenAddResource: () => void
onOpenResource: ResourceOpenHandler
onPanelChange: (panel: FilesystemPanel) => void
onSessionChange: (sessionId: string) => void
open: boolean
openingUri: string | null
sessionId?: string
+ showAgentTab: boolean
}) {
const { t } = useTranslation(['filesystem', 'resources'])
const [toolbarContainer, setToolbarContainer] =
@@ -953,6 +962,7 @@ function FilesystemMobileActionScreen({
<FilesystemActionTabs
activePanel={activePanel}
onPanelChange={onPanelChange}
+ showAgentTab={showAgentTab}
/>
<div
ref={setToolbarContainer}
@@ -964,12 +974,12 @@ function FilesystemMobileActionScreen({
activePanel={activePanel}
currentUri={currentUri}
entries={entries}
- onOpenAddResource={onOpenAddResource}
onOpenResource={onOpenResource}
onSessionChange={onSessionChange}
openingUri={openingUri}
sessionId={sessionId}
toolbarContainer={toolbarContainer}
+ showAgentTab={showAgentTab}
/>
</div>
</div>
@@ -979,9 +989,11 @@ function FilesystemMobileActionScreen({
function FilesystemActionTabs({
activePanel,
onPanelChange,
+ showAgentTab,
}: {
activePanel: FilesystemPanel
onPanelChange: (panel: FilesystemPanel) => void
+ showAgentTab: boolean
}) {
const { t } = useTranslation('filesystem')
@@ -993,12 +1005,14 @@ function FilesystemActionTabs({
label={t('tabs.terminal')}
onClick={() => onPanelChange('terminal')}
/>
- <PanelTab
- active={activePanel === 'agent'}
- icon={BotIcon}
- label={t('tabs.agent')}
- onClick={() => onPanelChange('agent')}
- />
+ {showAgentTab ? (
+ <PanelTab
+ active={activePanel === 'agent'}
+ icon={BotIcon}
+ label={t('tabs.agent')}
+ onClick={() => onPanelChange('agent')}
+ />
+ ) : null}
</div>
)
}
@@ -1007,30 +1021,29 @@ function FilesystemActionContent({
activePanel,
currentUri,
entries,
- onOpenAddResource,
onOpenResource,
onSessionChange,
openingUri,
sessionId,
toolbarContainer,
+ showAgentTab,
}: {
activePanel: FilesystemPanel
currentUri: string
entries: VikingFsEntry[]
- onOpenAddResource: () => void
onOpenResource: ResourceOpenHandler
onSessionChange: (sessionId: string) => void
openingUri: string | null
sessionId?: string
toolbarContainer: HTMLDivElement | null
+ showAgentTab: boolean
}) {
return (
<div className="flex h-full min-h-0 flex-col">
- {activePanel === 'terminal' ? (
+ {activePanel === 'terminal' || !showAgentTab ? (
<TerminalPanel
currentUri={currentUri}
entries={entries}
- onOpenAddResource={onOpenAddResource}
onOpenResource={onOpenResource}
onSessionChange={onSessionChange}
openingUri={openingUri}
diff --git a/web-studio/src/routes/resources/-hooks/viking-fm.ts b/web-studio/src/routes/resources/-hooks/viking-fm.ts
index 46da97f11..1be330572 100644
--- a/web-studio/src/routes/resources/-hooks/viking-fm.ts
+++ b/web-studio/src/routes/resources/-hooks/viking-fm.ts
@@ -1,4 +1,4 @@
-import { useMemo, useState, useEffect } from 'react'
+import { useMemo, useState, useEffect, useCallback } from 'react'
import { useQuery, useQueryClient } from '@tanstack/react-query'
import {
@@ -127,10 +127,26 @@ export function useVikingFilePreview(
export function useInvalidateVikingFs() {
const queryClient = useQueryClient()
+ const invalidateAll = useCallback(
+ () =>
+ queryClient.invalidateQueries({
+ predicate: ({ queryKey }) =>
+ queryKey[0] === 'viking-fs-ls' ||
+ queryKey[0] === 'viking-fs-tree' ||
+ queryKey[0] === 'viking-fs-stat',
+ }),
+ [queryClient],
+ )
+ const invalidatePreview = useCallback(
+ (uri?: string) =>
+ queryClient.invalidateQueries({
+ queryKey: uri ? ['viking-file-read', uri] : ['viking-file-read'],
+ }),
+ [queryClient],
+ )
return {
- invalidateAll: () =>
- queryClient.invalidateQueries({ queryKey: ['viking-fs'] }),
+ invalidateAll,
invalidateList: (uri?: string) =>
queryClient.invalidateQueries({
queryKey: uri
@@ -143,10 +159,7 @@ export function useInvalidateVikingFs() {
? ['viking-fs-tree', normalizeDirUri(uri)]
: ['viking-fs-tree'],
}),
- invalidatePreview: (uri?: string) =>
- queryClient.invalidateQueries({
- queryKey: uri ? ['viking-file-read', uri] : ['viking-file-read'],
- }),
+ invalidatePreview,
}
}
diff --git a/web-studio/src/routes/skills/-lib/add-skill.ts b/web-studio/src/routes/skills/-lib/add-skill.ts
index 1536dcc12..c2898f045 100644
--- a/web-studio/src/routes/skills/-lib/add-skill.ts
+++ b/web-studio/src/routes/skills/-lib/add-skill.ts
@@ -33,7 +33,7 @@ export async function validateNewSkill(data: string): Promise<SkillValidation> {
export async function addNewSkill(
data: string,
- scope: SkillScope,
+ scope: SkillScope | `viking://${string}`,
): Promise<{ task_id?: string }> {
return getOvResult<{ task_id?: string }>(
ovClient.client.post({
@@ -41,7 +41,11 @@ export async function addNewSkill(
body: {
data,
target_uri:
- scope === 'agent' ? 'viking://agent/skills' : 'viking://~/skills',
+ scope === 'agent'
+ ? 'viking://agent/skills'
+ : scope === 'user'
+ ? 'viking://~/skills'
+ : scope,
},
}),
)