Skip to content

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

fix(studio): improve terminal command guidance (#2552)

yufeng9be0124c366f
diff --git a/web-studio/src/components/app-shell.tsx b/web-studio/src/components/app-shell.tsx
index ad86ddf83..19bea98dd 100644
--- a/web-studio/src/components/app-shell.tsx
+++ b/web-studio/src/components/app-shell.tsx
@@ -357,11 +357,11 @@ function AppShellInner({ children }: { children: React.ReactNode }) {
pathname === '/oauth/verify' || pathname.startsWith('/oauth/verify/')
const visibleNavItems = React.useMemo(
() =>
- connectionRole === 'user'
- ? NAV_ITEMS.filter(
+ connectionRole === 'admin' || connectionRole === 'root'
+ ? NAV_ITEMS
+ : NAV_ITEMS.filter(
(item) => item.id !== 'home' && item.id !== 'requestLogs',
- )
- : NAV_ITEMS,
+ ),
[connectionRole],
)
diff --git a/web-studio/src/hooks/use-app-connection.tsx b/web-studio/src/hooks/use-app-connection.tsx
index c4b30f20f..00205eb11 100644
--- a/web-studio/src/hooks/use-app-connection.tsx
+++ b/web-studio/src/hooks/use-app-connection.tsx
@@ -158,7 +158,7 @@ async function detectConnectionRole(
connection: ConnectionDraft,
): Promise<ConnectionRole> {
const headers: Record<string, string> = {}
- const apiKey = connection.apiKey || connection.adminApiKey
+ const apiKey = connection.adminApiKey || connection.apiKey
if (apiKey) {
headers['X-API-Key'] = apiKey
}
@@ -259,8 +259,14 @@ export function AppConnectionProvider({
)
const [connectionRole, setConnectionRole] =
React.useState<ConnectionRole>('unknown')
- const [isConnectionRoleLoading, setConnectionRoleLoading] =
- React.useState(false)
+ const [isConnectionRoleLoading, setConnectionRoleLoading] = React.useState(
+ () =>
+ Boolean(
+ initialConnectionRef.current?.baseUrl &&
+ (initialConnectionRef.current.adminApiKey ||
+ initialConnectionRef.current.apiKey),
+ ),
+ )
const [serverMode, setServerMode] = React.useState<ServerMode>('checking')
const openConnectionSettings = React.useCallback(() => {
@@ -292,7 +298,7 @@ export function AppConnectionProvider({
React.useEffect(() => {
let cancelled = false
- const apiKey = connection.apiKey || connection.adminApiKey
+ const apiKey = connection.adminApiKey || connection.apiKey
setConnectionRole('unknown')
setConnectionRoleLoading(Boolean(connection.baseUrl && apiKey))
diff --git a/web-studio/src/i18n/locales/en.ts b/web-studio/src/i18n/locales/en.ts
index bc1fa2b91..7326f436a 100644
--- a/web-studio/src/i18n/locales/en.ts
+++ b/web-studio/src/i18n/locales/en.ts
@@ -761,22 +761,40 @@ const en = {
terminal: {
welcomeTitle: 'Terminal connected to the context tree',
welcomeBody:
- 'Run /status, /ls, /search, /read, /add-resource. Resource links in the output locate the left tree and open the middle preview.',
+ '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.',
+ scopeLabel: 'cwd: {{uri}}',
+ globalScope: 'global',
opened: 'Resource opened',
onlineTitle: 'Service online',
onlineBody:
'OpenViking API responded normally; found {{count}} nodes under the root.',
lsBody: 'Showing {{count}} nodes under {{uri}}.',
fileEmpty: 'File is empty; opened in the middle preview.',
- searchUsage: 'Usage: {{name}} <query>',
+ searchUsage: 'Usage: {{name}} <query> [--scope .|viking://resources/...]',
+ searchScopeLine: 'Search scope: {{scope}}',
+ helpParameters: 'Parameters',
+ helpExamples: 'Examples',
+ noParameters: 'No parameters',
+ currentScopeAction: 'Use current directory',
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',
+ sessionUsage:
+ 'Usage: /session [current|list|create|switch|get|context|messages|archive|commit|extract|message|used|tool-results|tool-result|tool-search|delete] ...',
+ sessionDeleteUsage: 'Usage: /session delete <session_id>',
+ sessionMissing:
+ 'No active session. Open the Agent panel to create one, or pass a session_id.',
+ sessionCurrentBody: 'Current active session: {{id}}',
+ sessionListBody: '{{count}} sessions.',
+ sessionCreatedBody: 'Created and switched to session: {{id}}',
+ 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, /add-resource.',
+ 'Unknown command. Available: /status, /ls, /search, /find, /read, /session, /add-resource.',
commandFailed: 'Command failed',
running: 'Running command...',
placeholder: 'Enter a CLI command, e.g. /status',
@@ -808,6 +826,255 @@ const en = {
resource: 'Resource paths',
history: 'History',
},
+ commandParameters: {
+ query: {
+ name: 'query',
+ description: 'Keywords or a semantic question to search for.',
+ },
+ scope: {
+ name: '--scope <.|uri>',
+ description:
+ 'Optional. Omit for global search; pass . for the current directory; pass uri for a specific directory.',
+ },
+ sessionAction: {
+ name: 'subcommand',
+ description:
+ 'current, list, create, switch, get, context, messages, archive, commit, extract, message, used, tool-results, tool-result, tool-search, delete.',
+ },
+ sessionId: {
+ name: 'session_id',
+ description:
+ 'Optional. Most subcommands use the current Agent session when omitted; delete requires an explicit ID.',
+ },
+ archiveId: {
+ name: 'archive_id',
+ description: 'Required when reading an archive.',
+ },
+ messageRole: {
+ name: 'role',
+ description: 'For the message subcommand. Use user or assistant.',
+ },
+ messageContent: {
+ name: 'content',
+ description: 'For the message subcommand. Text to append to the session.',
+ },
+ contexts: {
+ name: '--context uri',
+ description:
+ 'Repeatable for the used subcommand. Records context actually used.',
+ },
+ skillJson: {
+ name: '--skill-json JSON',
+ description: 'For the used subcommand. Records skill usage details.',
+ },
+ keepRecent: {
+ name: '--keep-recent count',
+ description:
+ 'For commit. Keep the most recent N live messages after commit.',
+ },
+ tokenBudget: {
+ name: '--token-budget count',
+ description:
+ 'For context. Limits the token budget for assembled session context.',
+ },
+ toolName: {
+ name: '--tool-name name',
+ description: 'For tool-results. Filter by tool name.',
+ },
+ toolResultId: {
+ name: 'tool_result_id',
+ description: 'Required when reading or searching an externalized tool result.',
+ },
+ limit: {
+ name: '--limit count',
+ description: 'Limits tool result list, read, or search results.',
+ },
+ offset: {
+ name: '--offset count',
+ description: 'For tool-result. Read from a character offset.',
+ },
+ contextChars: {
+ name: '--context-chars count',
+ description: 'For tool-search. Controls context length around matches.',
+ },
+ timeout: {
+ name: '--timeout seconds',
+ description: 'Optional. Maximum time to wait for service readiness.',
+ },
+ uri: {
+ name: 'uri',
+ description:
+ 'A viking:// resource path. It may be optional or required by command usage.',
+ },
+ },
+ commandExamples: {
+ status: {
+ default: {
+ code: '/status',
+ description: 'Check Agent and API connectivity',
+ },
+ },
+ ls: {
+ current: {
+ code: '/ls',
+ description: 'List the current directory',
+ },
+ target: {
+ code: '/ls viking://resources/',
+ description: 'List a specified directory',
+ },
+ },
+ search: {
+ global: {
+ code: '/search agent',
+ description: 'Search globally',
+ },
+ current: {
+ code: '/search agent --scope .',
+ description: 'Use the highlighted directory',
+ },
+ scoped: {
+ code: '/search agent --scope viking://resources/',
+ description: 'Search only within a directory',
+ },
+ },
+ find: {
+ global: {
+ code: '/find agent',
+ description: 'Find related resources globally',
+ },
+ current: {
+ code: '/find agent --scope .',
+ description: 'Use the highlighted directory',
+ },
+ scoped: {
+ code: '/find agent --scope viking://resources/',
+ description: 'Find only within a directory',
+ },
+ },
+ read: {
+ file: {
+ code: '/read viking://resources/file.md',
+ description: 'Read and open a file',
+ },
+ },
+ addResource: {
+ default: {
+ code: '/add-resource',
+ description: 'Open the add-resource form',
+ },
+ },
+ session: {
+ current: {
+ code: '/session',
+ description: 'Show the current active session',
+ },
+ list: {
+ code: '/session list',
+ description: 'List all sessions',
+ },
+ create: {
+ code: '/session create [session_id]',
+ description: 'Create and switch to a new session',
+ },
+ switch: {
+ code: '/session switch <session_id>',
+ description: 'Switch the Agent panel session',
+ },
+ get: {
+ code: '/session get [session_id]',
+ description: 'Show session metadata',
+ },
+ context: {
+ code: '/session context [session_id] --token-budget 8000',
+ description: 'Read assembled session context',
+ },
+ messages: {
+ code: '/session messages [session_id]',
+ description: 'Read session messages',
+ },
+ archive: {
+ code: '/session archive [session_id] <archive_id>',
+ description: 'Read an archive',
+ },
+ commit: {
+ code: '/session commit [session_id] --keep-recent 10',
+ description: 'Archive and trigger memory extraction',
+ },
+ extract: {
+ code: '/session extract [session_id]',
+ description: 'Extract memories from a session',
+ },
+ message: {
+ code: '/session message [session_id] user hello',
+ description: 'Append a message to a session',
+ },
+ used: {
+ code: '/session used [session_id] --context viking://resources/...',
+ description: 'Record actually used context or skill',
+ },
+ toolResults: {
+ code: '/session tool-results [session_id] --limit 20',
+ description: 'List externalized tool results',
+ },
+ toolResult: {
+ code: '/session tool-result [session_id] <tool_result_id>',
+ description: 'Read one tool result',
+ },
+ toolSearch: {
+ code: '/session tool-search [session_id] <tool_result_id> query',
+ description: 'Search inside a tool result',
+ },
+ delete: {
+ code: '/session delete <session_id>',
+ description: 'Delete a session',
+ },
+ },
+ tree: {
+ current: {
+ code: '/tree',
+ description: 'Show the current directory tree',
+ },
+ target: {
+ code: '/tree viking://resources/',
+ description: 'Show a specified directory tree',
+ },
+ },
+ stat: {
+ target: {
+ code: '/stat viking://resources/file.md',
+ description: 'Show resource metadata',
+ },
+ },
+ abstract: {
+ target: {
+ code: '/abstract viking://resources/',
+ description: 'Read the directory abstract',
+ },
+ },
+ overview: {
+ target: {
+ code: '/overview viking://resources/',
+ description: 'Read the directory overview',
+ },
+ },
+ health: {
+ default: {
+ code: '/health',
+ description: 'Show backend health',
+ },
+ },
+ wait: {
+ default: {
+ code: '/wait',
+ description: 'Wait for service readiness',
+ },
+ timeout: {
+ code: '/wait --timeout 30',
+ description: 'Set wait time in seconds',
+ },
+ },
+ },
resourceSuggestion: 'Resource path',
historySuggestion: 'History',
groupLabels: {
@@ -817,29 +1084,33 @@ const en = {
},
commands: {
status: {
- description: 'Check the OpenViking API and root directory',
+ description: 'Check connection',
usage: '/status',
},
ls: {
- description: 'List the current or a given directory',
+ description: 'View resources',
usage: '/ls [viking://resources/...]',
},
search: {
- description: 'Semantic search within the current context scope',
+ description: 'Semantic search',
usage: '/search <query>',
},
find: {
- description: 'Find related context resources',
+ description: 'Find related resources',
usage: '/find <query>',
},
read: {
- description: 'Read and open a resource file',
+ description: 'Read a resource file',
usage: '/read viking://resources/.../file.md',
},
addResource: {
- description: 'Open the add-resource form',
+ description: 'Add external resources',
usage: '/add-resource',
},
+ session: {
+ description: 'Manage Agent sessions',
+ usage: '/session subcommand',
+ },
},
},
},
diff --git a/web-studio/src/i18n/locales/zh-CN.ts b/web-studio/src/i18n/locales/zh-CN.ts
index 855cc8b45..031b077cb 100644
--- a/web-studio/src/i18n/locales/zh-CN.ts
+++ b/web-studio/src/i18n/locales/zh-CN.ts
@@ -741,21 +741,38 @@ const zhCN = {
terminal: {
welcomeTitle: 'Terminal 已连接上下文目录',
welcomeBody:
- '可执行 /status、/ls、/search、/read、/add-resource。输出中的资源链接会定位左侧目录并打开中间预览。',
+ '可执行 /status、/ls、/search、/read、/add-resource。/search 默认全局检索,可通过 --scope . 使用当前目录,或通过 --scope viking://resources/... 指定目录。',
+ scopeLabel: '目录:{{uri}}',
+ globalScope: '全局',
opened: '已打开资源',
onlineTitle: '服务在线',
onlineBody: 'OpenViking API 正常响应,根目录下发现 {{count}} 个节点。',
lsBody: '{{uri}} 下共展示 {{count}} 个节点。',
fileEmpty: '文件为空,已在中间预览区打开。',
- searchUsage: '用法:{{name}} 查询词',
+ searchUsage: '用法:{{name}} 查询词 [--scope .|viking://resources/...]',
+ searchScopeLine: '搜索范围:{{scope}}',
+ helpParameters: '参数',
+ helpExamples: '示例',
+ noParameters: '无参数',
+ currentScopeAction: '使用当前目录',
readUsage: '用法:/read viking://resources/...',
enterUri: '请输入 viking:// URI',
hits: '命中 resources {{resources}} 条,memory {{memories}} 条,skill {{skills}} 条。',
addResourceBody:
'已打开添加资源弹窗。提交后左侧目录会刷新,也可以用 /ls 或 /search 继续定位新内容。',
addResourceTitle: '添加资源',
+ sessionUsage:
+ '用法:/session [current|list|create|switch|get|context|messages|archive|commit|extract|message|used|tool-results|tool-result|tool-search|delete] ...',
+ sessionDeleteUsage: '用法:/session delete <session_id>',
+ sessionMissing: '当前没有 active session,请先打开 Agent 面板创建会话,或指定 session_id。',
+ sessionCurrentBody: '当前 active session:{{id}}',
+ sessionListBody: '共有 {{count}} 个 session。',
+ sessionCreatedBody: '已创建并切换到 session:{{id}}',
+ sessionSwitchedBody: '已切换到 session:{{id}}',
+ sessionDeletedBody: '已删除 session:{{id}}',
+ sessionMessageAddedBody: '已向 session {{id}} 添加消息。',
unknownCommand:
- '未知命令。可用命令:/status、/ls、/search、/find、/read、/add-resource。',
+ '未知命令。可用命令:/status、/ls、/search、/find、/read、/session、/add-resource。',
commandFailed: '命令失败',
running: '正在执行命令...',
placeholder: '输入 CLI 命令,例如 /status',
@@ -787,6 +804,249 @@ const zhCN = {
resource: '资源路径',
history: '历史记录',
},
+ commandParameters: {
+ query: {
+ name: '查询词',
+ description: '要检索的关键词或语义问题。',
+ },
+ scope: {
+ name: '--scope <.|uri>',
+ description: '可选。不填则全局搜索;传 . 使用当前目录;传 uri 使用指定目录。',
+ },
+ sessionAction: {
+ name: '子命令',
+ description:
+ 'current、list、create、switch、get、context、messages、archive、commit、extract、message、used、tool-results、tool-result、tool-search、delete。',
+ },
+ sessionId: {
+ name: 'session_id',
+ description: '可选。省略时多数子命令使用当前 Agent session;delete 必须显式指定。',
+ },
+ archiveId: {
+ name: 'archive_id',
+ description: '读取 archive 时必填。',
+ },
+ messageRole: {
+ name: 'role',
+ description: 'message 子命令使用,支持 user 或 assistant。',
+ },
+ messageContent: {
+ name: 'content',
+ description: 'message 子命令使用,要追加到 session 的文本内容。',
+ },
+ contexts: {
+ name: '--context uri',
+ description: 'used 子命令可重复传入,记录本轮实际使用的上下文。',
+ },
+ skillJson: {
+ name: '--skill-json JSON',
+ description: 'used 子命令使用,记录实际使用的 skill 信息。',
+ },
+ keepRecent: {
+ name: '--keep-recent 数量',
+ description: 'commit 子命令使用,提交后保留最近 N 条 live messages。',
+ },
+ tokenBudget: {
+ name: '--token-budget 数量',
+ description: 'context 子命令使用,限制组装上下文的 token 预算。',
+ },
+ toolName: {
+ name: '--tool-name 名称',
+ description: 'tool-results 子命令使用,按工具名过滤。',
+ },
+ toolResultId: {
+ name: 'tool_result_id',
+ description: '读取或搜索外部化 tool result 时必填。',
+ },
+ limit: {
+ name: '--limit 数量',
+ description: 'tool result 列表、读取或搜索时限制返回数量。',
+ },
+ offset: {
+ name: '--offset 数量',
+ description: 'tool-result 子命令使用,从指定字符偏移开始读取。',
+ },
+ contextChars: {
+ name: '--context-chars 数量',
+ description: 'tool-search 子命令使用,控制命中上下文长度。',
+ },
+ timeout: {
+ name: '--timeout 秒',
+ description: '可选。等待服务就绪的最长时间。',
+ },
+ uri: {
+ name: 'uri',
+ description: '可选或必填的 viking:// 资源路径,取决于命令用法。',
+ },
+ },
+ commandExamples: {
+ status: {
+ default: {
+ code: '/status',
+ description: '检查 Agent 和 API 连通状态',
+ },
+ },
+ ls: {
+ current: {
+ code: '/ls',
+ description: '列出当前目录',
+ },
+ target: {
+ code: '/ls viking://resources/',
+ description: '列出指定目录',
+ },
+ },
+ search: {
+ global: {
+ code: '/search agent',
+ description: '全局语义检索',
+ },
+ current: {
+ code: '/search agent --scope .',
+ description: '使用当前高亮目录',
+ },
+ scoped: {
+ code: '/search agent --scope viking://resources/',
+ description: '只在指定目录检索',
+ },
+ },
+ find: {
+ global: {
+ code: '/find agent',
+ description: '全局查找相关资源',
+ },
+ current: {
+ code: '/find agent --scope .',
+ description: '使用当前高亮目录',
+ },
+ scoped: {
+ code: '/find agent --scope viking://resources/',
+ description: '只在指定目录查找',
+ },
+ },
+ read: {
+ file: {
+ code: '/read viking://resources/file.md',
+ description: '读取并打开文件',
+ },
+ },
+ addResource: {
+ default: {
+ code: '/add-resource',
+ description: '打开添加资源表单',
+ },
+ },
+ session: {
+ current: {
+ code: '/session',
+ description: '查看当前 active session',
+ },
+ list: {
+ code: '/session list',
+ description: '列出所有 session',
+ },
+ create: {
+ code: '/session create [session_id]',
+ description: '创建并切换到新 session',
+ },
+ switch: {
+ code: '/session switch <session_id>',
+ description: '切换 Agent 面板会话',
+ },
+ get: {
+ code: '/session get [session_id]',
+ description: '查看 session 元信息',
+ },
+ context: {
+ code: '/session context [session_id] --token-budget 8000',
+ description: '读取组装后的 session context',
+ },
+ messages: {
+ code: '/session messages [session_id]',
+ description: '读取 session 消息列表',
+ },
+ archive: {
+ code: '/session archive [session_id] <archive_id>',
+ description: '读取指定 archive',
+ },
+ commit: {
+ code: '/session commit [session_id] --keep-recent 10',
+ description: '归档并触发记忆提取',
+ },
+ extract: {
+ code: '/session extract [session_id]',
+ description: '从 session 中提取记忆',
+ },
+ message: {
+ code: '/session message [session_id] user hello',
+ description: '向 session 追加消息',
+ },
+ used: {
+ code: '/session used [session_id] --context viking://resources/...',
+ description: '记录实际使用的上下文或 skill',
+ },
+ toolResults: {
+ code: '/session tool-results [session_id] --limit 20',
+ description: '列出外部化 tool results',
+ },
+ toolResult: {
+ code: '/session tool-result [session_id] <tool_result_id>',
+ description: '读取一个 tool result',
+ },
+ toolSearch: {
+ code: '/session tool-search [session_id] <tool_result_id> query',
+ description: '在 tool result 中搜索',
+ },
+ delete: {
+ code: '/session delete <session_id>',
+ description: '删除指定 session',
+ },
+ },
+ tree: {
+ current: {
+ code: '/tree',
+ description: '展示当前目录树',
+ },
+ target: {
+ code: '/tree viking://resources/',
+ description: '展示指定目录树',
+ },
+ },
+ stat: {
+ target: {
+ code: '/stat viking://resources/file.md',
+ description: '查看资源元信息',
+ },
+ },
+ abstract: {
+ target: {
+ code: '/abstract viking://resources/',
+ description: '读取目录摘要',
+ },
+ },
+ overview: {
+ target: {
+ code: '/overview viking://resources/',
+ description: '读取目录概览',
+ },
+ },
+ health: {
+ default: {
+ code: '/health',
+ description: '查看后端健康状态',
+ },
+ },
+ wait: {
+ default: {
+ code: '/wait',
+ description: '等待服务就绪',
+ },
+ timeout: {
+ code: '/wait --timeout 30',
+ description: '指定等待秒数',
+ },
+ },
+ },
resourceSuggestion: '资源路径',
historySuggestion: '历史记录',
groupLabels: {
@@ -796,29 +1056,33 @@ const zhCN = {
},
commands: {
status: {
- description: '检查 OpenViking API 和根目录',
+ description: '检查连通状态',
usage: '/status',
},
ls: {
- description: '列出当前目录或指定目录',
+ description: '查看已有资源',
usage: '/ls [viking://resources/...]',
},
search: {
- description: '在当前上下文范围内语义搜索',
+ description: '语义检索上下文',
usage: '/search 查询词',
},
find: {
- description: '查找相关上下文资源',
+ description: '查找相关资源',
usage: '/find 查询词',
},
read: {
- description: '读取并打开一个资源文件',
+ description: '读取资源文件',
usage: '/read viking://resources/.../file.md',
},
addResource: {
- description: '打开添加资源表单',
+ description: '添加外部资源',
usage: '/add-resource',
},
+ session: {
+ description: '管理 Agent 会话',
+ usage: '/session 子命令',
+ },
},
},
},
diff --git a/web-studio/src/lib/sessions/api.ts b/web-studio/src/lib/sessions/api.ts
index 08e9f5f56..7d38bf95a 100644
--- a/web-studio/src/lib/sessions/api.ts
+++ b/web-studio/src/lib/sessions/api.ts
@@ -1,12 +1,15 @@
import {
deleteSessionBySessionId,
+ getSessionIdArchiveByArchiveId,
getSessions,
getSessionBySessionId,
getSessionIdContext,
postBotV1Chat,
postSessions,
postSessionIdCommit,
+ postSessionIdExtract,
postSessionIdMessages,
+ postSessionIdUsed,
} from '#/gen/ov-client/sdk.gen'
import {
getOvResult,
@@ -26,6 +29,7 @@ import type {
SessionListItem,
SessionMeta,
} from '@ov-server/api/v1/sessions'
+import type { UsedRequest } from '#/gen/ov-client/types.gen'
// ---------------------------------------------------------------------------
// Session CRUD
@@ -54,6 +58,30 @@ export async function createSession(
)
}
+export async function fetchSessionContext(
+ sessionId: string,
+ tokenBudget?: number,
+): Promise<SessionContextResult> {
+ return getOvResult<SessionContextResult>(
+ getSessionIdContext({
+ path: { session_id: sessionId },
+ query:
+ tokenBudget === undefined ? undefined : { token_budget: tokenBudget },
+ }),
+ )
+}
+
+export async function fetchSessionArchive(
+ sessionId: string,
+ archiveId: string,
+): Promise<unknown> {
+ return getOvResult<unknown>(
+ getSessionIdArchiveByArchiveId({
+ path: { archive_id: archiveId, session_id: sessionId },
+ }),
+ )
+}
+
export async function deleteSession(
sessionId: string,
): Promise<DeleteSessionResult> {
@@ -110,14 +138,96 @@ export async function addMessage(
export async function commitSession(
sessionId: string,
+ keepRecentCount?: number,
): Promise<CommitSessionResult> {
return getOvResult<CommitSessionResult>(
postSessionIdCommit({
+ body:
+ keepRecentCount === undefined
+ ? undefined
+ : { keep_recent_count: keepRecentCount },
+ path: { session_id: sessionId },
+ }),
+ )
+}
+
+export async function extractSession(sessionId: string): Promise<unknown> {
+ return getOvResult<unknown>(
+ postSessionIdExtract({
path: { session_id: sessionId },
}),
)
}
+export async function recordSessionUsed(
+ sessionId: string,
+ body: UsedRequest,
+): Promise<unknown> {
+ return getOvResult<unknown>(
+ postSessionIdUsed({
+ body,
+ path: { session_id: sessionId },
+ }),
+ )
+}
+
+export async function fetchSessionToolResults(
+ sessionId: string,
+ options: { limit?: number; toolName?: string } = {},
+): Promise<unknown> {
+ const response = await ovClient.instance.get(
+ `/api/v1/sessions/${encodeURIComponent(sessionId)}/tool-results`,
+ {
+ params: {
+ limit: options.limit,
+ tool_name: options.toolName || undefined,
+ },
+ },
+ )
+ return getOvResult<unknown>(Promise.resolve(response))
+}
+
+export async function fetchSessionToolResult(
+ sessionId: string,
+ toolResultId: string,
+ options: { includeMetadata?: boolean; limit?: number; offset?: number } = {},
+): Promise<unknown> {
+ const response = await ovClient.instance.get(
+ `/api/v1/sessions/${encodeURIComponent(sessionId)}/tool-results/${encodeURIComponent(
+ toolResultId,
+ )}`,
+ {
+ params: {
+ include_metadata: options.includeMetadata,
+ limit: options.limit,
+ offset: options.offset,
+ },
+ },
+ )
+ return getOvResult<unknown>(Promise.resolve(response))
+}
+
+export async function searchSessionToolResult(
+ sessionId: string,
+ toolResultId: string,
+ query: string,
+ options: { contextChars?: number; limit?: number } = {},
+): Promise<unknown> {
+ const response = await ovClient.instance.get(
+ `/api/v1/sessions/${encodeURIComponent(sessionId)}/tool-results/${encodeURIComponent(
+ toolResultId,
+ )}/search`,
+ {
+ params: {
+ context_chars: options.contextChars,
+ limit: options.limit,
+ q: query,
+ },
+ },
+ )
+ return getOvResult<unknown>(Promise.resolve(response))
+}
+
// ---------------------------------------------------------------------------
// Bot Chat
// ---------------------------------------------------------------------------
diff --git a/web-studio/src/routes/home/route.tsx b/web-studio/src/routes/home/route.tsx
index 645a6a79d..a99aefa00 100644
--- a/web-studio/src/routes/home/route.tsx
+++ b/web-studio/src/routes/home/route.tsx
@@ -24,8 +24,8 @@ export const Route = createFileRoute('/home')({
function HomePage() {
const { t } = useTranslation('home')
const { connectionRole, isConnectionRoleLoading } = useAppConnection()
- const isRegularUser = connectionRole === 'user'
- const canQueryAdminMetrics = !isConnectionRoleLoading && !isRegularUser
+ const hasAdminRole = connectionRole === 'admin' || connectionRole === 'root'
+ const canQueryAdminMetrics = !isConnectionRoleLoading && hasAdminRole
const dashboard = useQuery({
enabled: canQueryAdminMetrics,
@@ -51,7 +51,7 @@ function HomePage() {
const summary = dashboard.data
const usageDisabled = isDisabledPayload(summary)
- if (isRegularUser) {
+ if (!isConnectionRoleLoading && !hasAdminRole) {
return (
<div className="flex min-h-[calc(100svh-8rem)] items-center justify-center px-4 py-10">
<section className="w-full max-w-xl rounded-lg border bg-card px-6 py-5 shadow-sm">
diff --git a/web-studio/src/routes/index.tsx b/web-studio/src/routes/index.tsx
index dcef54e25..36e09dd22 100644
--- a/web-studio/src/routes/index.tsx
+++ b/web-studio/src/routes/index.tsx
@@ -1,9 +1,26 @@
import { Navigate, createFileRoute } from '@tanstack/react-router'
+import { useAppConnection } from '#/hooks/use-app-connection'
+
export const Route = createFileRoute('/')({
component: IndexRoute,
})
function IndexRoute() {
- return <Navigate replace to="/playground" />
+ const { connectionRole, isConnectionRoleLoading } = useAppConnection()
+
+ if (isConnectionRoleLoading) {
+ return null
+ }
+
+ return (
+ <Navigate
+ replace
+ to={
+ connectionRole === 'admin' || connectionRole === 'root'
+ ? '/home'
+ : '/playground'
+ }
+ />
+ )
}
diff --git a/web-studio/src/routes/playground/-components/terminal-panel.tsx b/web-studio/src/routes/playground/-components/terminal-panel.tsx
index 7240054e8..1644608e1 100644
--- a/web-studio/src/routes/playground/-components/terminal-panel.tsx
+++ b/web-studio/src/routes/playground/-components/terminal-panel.tsx
@@ -27,6 +27,22 @@ import {
getSystemStatus,
postSystemWait,
} from '#/lib/ov-client'
+import {
+ addMessage,
+ commitSession,
+ createSession,
+ deleteSession,
+ extractSession,
+ fetchSession,
+ fetchSessionArchive,
+ fetchSessionContext,
+ fetchSessionMessages,
+ fetchSessions,
+ fetchSessionToolResult,
+ fetchSessionToolResults,
+ recordSessionUsed,
+ searchSessionToolResult,
+} from '#/lib/sessions/api'
import { cn } from '#/lib/utils'
import {
fetchDirectoryLevelContent,
@@ -38,12 +54,14 @@ import {
} from '#/routes/resources/-lib/api'
import { normalizeDirUri } from '#/routes/resources/-lib/normalize'
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 type {
ResourceRef,
ResourceOpenHandler,
TerminalCommandGroup,
+ TerminalCommandParameterKey,
TerminalCommandView,
TerminalEntry,
} from '../-lib/types'
@@ -52,6 +70,7 @@ import {
entryToRef,
getErrorMessage,
readStoredJsonArray,
+ registerPlaygroundAgentSessionId,
removeStoredValue,
searchResultToRefs,
visibleContextEntries,
@@ -74,7 +93,436 @@ const URI_ARGUMENT_COMMANDS = new Set([
'/tree',
])
-type TerminalSuggestionGroup = TerminalCommandGroup | 'history' | 'resource'
+const COMMAND_HELP_FALLBACKS: Partial<
+ Record<string, { description: string; usage: string }>
+> = {
+ '/abstract': {
+ description: '读取目录摘要',
+ usage: '/abstract viking://resources/...',
+ },
+ '/add-resource': {
+ description: '添加外部资源',
+ usage: '/add-resource',
+ },
+ '/find': {
+ description: '查找相关资源',
+ usage: '/find 查询词',
+ },
+ '/health': {
+ description: '查看后端健康状态',
+ usage: '/health',
+ },
+ '/ls': {
+ description: '查看已有资源',
+ usage: '/ls [viking://resources/...]',
+ },
+ '/overview': {
+ description: '读取目录概览',
+ usage: '/overview viking://resources/...',
+ },
+ '/read': {
+ description: '读取资源文件',
+ usage: '/read viking://resources/.../file.md',
+ },
+ '/search': {
+ description: '语义检索上下文',
+ usage: '/search 查询词',
+ },
+ '/session': {
+ description: '管理 Agent 会话',
+ usage: '/session 子命令',
+ },
+ '/stat': {
+ description: '查看资源元信息',
+ usage: '/stat viking://resources/...',
+ },
+ '/status': {
+ description: '检查连通状态',
+ usage: '/status',
+ },
+ '/tree': {
+ description: '展示目录树',
+ usage: '/tree [viking://resources/...]',
+ },
+ '/wait': {
+ description: '等待服务就绪',
+ usage: '/wait [--timeout seconds]',
+ },
+}
+
+const PARAMETER_HELP_FALLBACKS: Record<
+ TerminalCommandParameterKey,
+ { description: string; name: string }
+> = {
+ archiveId: {
+ description: '读取 archive 时必填。',
+ name: 'archive_id',
+ },
+ contextChars: {
+ description: 'tool-search 子命令使用,控制命中上下文长度。',
+ name: '--context-chars 数量',
+ },
+ contexts: {
+ description: 'used 子命令可重复传入,记录本轮实际使用的上下文。',
+ name: '--context uri',
+ },
+ keepRecent: {
+ description: 'commit 子命令使用,提交后保留最近 N 条 live messages。',
+ name: '--keep-recent 数量',
+ },
+ limit: {
+ description: 'tool result 列表、读取或搜索时限制返回数量。',
+ name: '--limit 数量',
+ },
+ messageContent: {
+ description: 'message 子命令使用,要追加到 session 的文本内容。',
+ name: 'content',
+ },
+ messageRole: {
+ description: 'message 子命令使用,支持 user 或 assistant。',
+ name: 'role',
+ },
+ offset: {
+ description: 'tool-result 子命令使用,从指定字符偏移开始读取。',
+ name: '--offset 数量',
+ },
+ query: {
+ description: '要检索的关键词或语义问题。',
+ name: '查询词',
+ },
+ scope: {
+ description: '可选。不填则全局搜索;传 . 使用当前目录;传 uri 使用指定目录。',
+ name: '--scope <.|uri>',
+ },
+ sessionAction: {
+ description:
+ 'current、list、create、switch、get、context、messages、archive、commit、extract、message、used、tool-results、tool-result、tool-search、delete。',
+ name: '子命令',
+ },
+ sessionId: {
+ description: '可选。省略时多数子命令使用当前 Agent session;delete 必须显式指定。',
+ name: 'session_id',
+ },
+ skillJson: {
+ description: 'used 子命令使用,记录实际使用的 skill 信息。',
+ name: '--skill-json JSON',
+ },
+ timeout: {
+ description: '可选。等待服务就绪的最长时间。',
+ name: '--timeout 秒',
+ },
+ tokenBudget: {
+ description: 'context 子命令使用,限制组装上下文的 token 预算。',
+ name: '--token-budget 数量',
+ },
+ toolName: {
+ description: 'tool-results 子命令使用,按工具名过滤。',
+ name: '--tool-name 名称',
+ },
+ toolResultId: {
+ description: '读取或搜索外部化 tool result 时必填。',
+ name: 'tool_result_id',
+ },
+ uri: {
+ description: '可选或必填的 viking:// 资源路径,取决于命令用法。',
+ name: 'uri',
+ },
+}
+
+const EXAMPLE_HELP_FALLBACKS: Partial<
+ Record<string, { code: string; description: string }>
+> = {
+ 'abstract.target': {
+ code: '/abstract viking://resources/',
+ description: '读取目录摘要',
+ },
+ 'addResource.default': {
+ code: '/add-resource',
+ description: '打开添加资源表单',
+ },
+ 'find.current': {
+ code: '/find agent --scope .',
+ description: '使用当前高亮目录',
+ },
+ 'find.global': {
+ code: '/find agent',
+ description: '全局查找相关资源',
+ },
+ 'find.scoped': {
+ code: '/find agent --scope viking://resources/',
+ description: '只在指定目录查找',
+ },
+ 'health.default': {
+ code: '/health',
+ description: '查看后端健康状态',
+ },
+ 'ls.current': {
+ code: '/ls',
+ description: '列出当前目录',
+ },
+ 'ls.target': {
+ code: '/ls viking://resources/',
+ description: '列出指定目录',
+ },
+ 'overview.target': {
+ code: '/overview viking://resources/',
+ description: '读取目录概览',
+ },
+ 'read.file': {
+ code: '/read viking://resources/file.md',
+ description: '读取并打开文件',
+ },
+ 'search.current': {
+ code: '/search agent --scope .',
+ description: '使用当前高亮目录',
+ },
+ 'search.global': {
+ code: '/search agent',
+ description: '全局语义检索',
+ },
+ 'search.scoped': {
+ code: '/search agent --scope viking://resources/',
+ description: '只在指定目录检索',
+ },
+ 'session.archive': {
+ code: '/session archive [session_id] <archive_id>',
+ description: '读取指定 archive',
+ },
+ 'session.commit': {
+ code: '/session commit [session_id] --keep-recent 10',
+ description: '归档并触发记忆提取',
+ },
+ 'session.context': {
+ code: '/session context [session_id] --token-budget 8000',
+ description: '读取组装后的 session context',
+ },
+ 'session.create': {
+ code: '/session create [session_id]',
+ description: '创建并切换到新 session',
+ },
+ 'session.current': {
+ code: '/session',
+ description: '查看当前 active session',
+ },
+ 'session.delete': {
+ code: '/session delete <session_id>',
+ description: '删除指定 session',
+ },
+ 'session.extract': {
+ code: '/session extract [session_id]',
+ description: '从 session 中提取记忆',
+ },
+ 'session.get': {
+ code: '/session get [session_id]',
+ description: '查看 session 元信息',
+ },
+ 'session.list': {
+ code: '/session list',
+ description: '列出所有 session',
+ },
+ 'session.message': {
+ code: '/session message [session_id] user hello',
+ description: '向 session 追加消息',
+ },
+ 'session.messages': {
+ code: '/session messages [session_id]',
+ description: '读取 session 消息列表',
+ },
+ 'session.switch': {
+ code: '/session switch <session_id>',
+ description: '切换 Agent 面板会话',
+ },
+ 'session.toolResult': {
+ code: '/session tool-result [session_id] <tool_result_id>',
+ description: '读取一个 tool result',
+ },
+ 'session.toolResults': {
+ code: '/session tool-results [session_id] --limit 20',
+ description: '列出外部化 tool results',
+ },
+ 'session.toolSearch': {
+ code: '/session tool-search [session_id] <tool_result_id> query',
+ description: '在 tool result 中搜索',
+ },
+ 'session.used': {
+ code: '/session used [session_id] --context viking://resources/...',
+ description: '记录实际使用的上下文或 skill',
+ },
+ 'stat.target': {
+ code: '/stat viking://resources/file.md',
+ description: '查看资源元信息',
+ },
+ 'status.default': {
+ code: '/status',
+ description: '检查 Agent 和 API 连通状态',
+ },
+ 'tree.current': {
+ code: '/tree',
+ description: '展示当前目录树',
+ },
+ 'tree.target': {
+ code: '/tree viking://resources/',
+ description: '展示指定目录树',
+ },
+ 'wait.default': {
+ code: '/wait',
+ description: '等待服务就绪',
+ },
+ 'wait.timeout': {
+ code: '/wait --timeout 30',
+ description: '指定等待秒数',
+ },
+}
+
+type SessionSubcommandHelp = {
+ description: string
+ examples: string[]
+ insertText: string
+ key: string
+ parameters: TerminalCommandParameterKey[]
+ usage: string
+}
+
+const SESSION_SUBCOMMANDS: SessionSubcommandHelp[] = [
+ {
+ description: '查看当前 active session',
+ examples: ['session.current'],
+ insertText: '/session current',
+ key: 'current',
+ parameters: [],
+ usage: '/session current',
+ },
+ {
+ description: '列出所有 session',
+ examples: ['session.list'],
+ insertText: '/session list',
+ key: 'list',
+ parameters: [],
+ usage: '/session list',
+ },
+ {
+ description: '创建并切换到新 session',
+ examples: ['session.create'],
+ insertText: '/session create ',
+ key: 'create',
+ parameters: ['sessionId'],
+ usage: '/session create [session_id]',
+ },
+ {
+ description: '切换 Agent 面板会话',
+ examples: ['session.switch'],
+ insertText: '/session switch ',
+ key: 'switch',
+ parameters: ['sessionId'],
+ usage: '/session switch <session_id>',
+ },
+ {
+ description: '查看 session 元信息',
+ examples: ['session.get'],
+ insertText: '/session get ',
+ key: 'get',
+ parameters: ['sessionId'],
+ usage: '/session get [session_id]',
+ },
+ {
+ description: '读取组装后的 session context',
+ examples: ['session.context'],
+ insertText: '/session context ',
+ key: 'context',
+ parameters: ['sessionId', 'tokenBudget'],
+ usage: '/session context [session_id] --token-budget 8000',
+ },
+ {
+ description: '读取 session 消息列表',
+ examples: ['session.messages'],
+ insertText: '/session messages ',
+ key: 'messages',
+ parameters: ['sessionId'],
+ usage: '/session messages [session_id]',
+ },
+ {
+ description: '读取指定 archive',
+ examples: ['session.archive'],
+ insertText: '/session archive ',
+ key: 'archive',
+ parameters: ['sessionId', 'archiveId'],
+ usage: '/session archive [session_id] <archive_id>',
+ },
+ {
+ description: '归档并触发记忆提取',
+ examples: ['session.commit'],
+ insertText: '/session commit ',
+ key: 'commit',
+ parameters: ['sessionId', 'keepRecent'],
+ usage: '/session commit [session_id] --keep-recent 10',
+ },
+ {
+ description: '从 session 中提取记忆',
+ examples: ['session.extract'],
+ insertText: '/session extract ',
+ key: 'extract',
+ parameters: ['sessionId'],
+ usage: '/session extract [session_id]',
+ },
+ {
+ description: '向 session 追加消息',
+ examples: ['session.message'],
+ insertText: '/session message ',
+ key: 'message',
+ parameters: ['sessionId', 'messageRole', 'messageContent'],
+ usage: '/session message [session_id] user hello',
+ },
+ {
+ description: '记录实际使用的上下文或 skill',
+ examples: ['session.used'],
+ insertText: '/session used ',
+ key: 'used',
+ parameters: ['sessionId', 'contexts', 'skillJson'],
+ usage: '/session used [session_id] --context viking://resources/...',
+ },
+ {
+ description: '列出外部化 tool results',
+ examples: ['session.toolResults'],
+ insertText: '/session tool-results ',
+ key: 'tool-results',
+ parameters: ['sessionId', 'toolName', 'limit'],
+ usage: '/session tool-results [session_id] --limit 20',
+ },
+ {
+ description: '读取一个 tool result',
+ examples: ['session.toolResult'],
+ insertText: '/session tool-result ',
+ key: 'tool-result',
+ parameters: ['sessionId', 'toolResultId', 'limit', 'offset'],
+ usage: '/session tool-result [session_id] <tool_result_id>',
+ },
+ {
+ description: '在 tool result 中搜索',
+ examples: ['session.toolSearch'],
+ insertText: '/session tool-search ',
+ key: 'tool-search',
+ parameters: ['sessionId', 'toolResultId', 'query', 'limit', 'contextChars'],
+ usage: '/session tool-search [session_id] <tool_result_id> query',
+ },
+ {
+ description: '删除指定 session',
+ examples: ['session.delete'],
+ insertText: '/session delete ',
+ key: 'delete',
+ parameters: ['sessionId'],
+ usage: '/session delete <session_id>',
+ },
+]
+
+const SESSION_SUBCOMMANDS_BY_KEY = new Map(
+ SESSION_SUBCOMMANDS.map((item) => [item.key, item]),
+)
+
+type TerminalSuggestionGroup =
+ | TerminalCommandGroup
+ | 'history'
+ | 'resource'
+ | 'subcommand'
type TerminalSuggestion = Omit<TerminalCommandView, 'group'> & {
group: TerminalSuggestionGroup
@@ -89,6 +537,16 @@ type TerminalQuickStartExample = {
title: string
}
+type ScopedSearchInput = {
+ query: string
+ scopeUri?: string
+}
+
+type ParsedOptions = {
+ flags: Map<string, string[]>
+ positional: string[]
+}
+
function loadCommandHistory(): string[] {
return readStoredJsonArray(
TERMINAL_COMMAND_HISTORY_STORAGE_KEY,
@@ -183,18 +641,123 @@ function parseWaitTimeout(body: string): number | undefined {
return Number(match[1])
}
+function joinBodyLines(lines: Array<string | undefined>): string {
+ return lines.filter((line): line is string => Boolean(line)).join('\n')
+}
+
+function parseOptions(body: string): ParsedOptions {
+ const tokens = body.trim().split(/\s+/).filter(Boolean)
+ const flags = new Map<string, string[]>()
+ const positional: string[] = []
+
+ for (let index = 0; index < tokens.length; index += 1) {
+ const token = tokens[index]
+ if (!token.startsWith('--')) {
+ positional.push(token)
+ continue
+ }
+
+ const eqIndex = token.indexOf('=')
+ const key = token.slice(2, eqIndex > -1 ? eqIndex : undefined)
+ const inlineValue = eqIndex > -1 ? token.slice(eqIndex + 1) : undefined
+ let value = inlineValue ?? 'true'
+
+ if (
+ inlineValue === undefined &&
+ tokens[index + 1] &&
+ !tokens[index + 1].startsWith('--')
+ ) {
+ value = tokens[index + 1]
+ index += 1
+ }
+
+ flags.set(key, [...(flags.get(key) ?? []), value])
+ }
+
+ return { flags, positional }
+}
+
+function getLastFlag(
+ flags: Map<string, string[]>,
+ key: string,
+): string | undefined {
+ return flags.get(key)?.at(-1)
+}
+
+function getNumberFlag(
+ flags: Map<string, string[]>,
+ key: string,
+): number | undefined {
+ const value = getLastFlag(flags, key)
+ if (value === undefined || value === 'true') return undefined
+ const parsed = Number(value)
+ if (!Number.isFinite(parsed)) {
+ throw new Error(`Invalid --${key}: ${value}`)
+ }
+ return parsed
+}
+
+function getBooleanFlag(flags: Map<string, string[]>, key: string): boolean {
+ return flags.has(key) && getLastFlag(flags, key) !== 'false'
+}
+
+function parseScopedSearchInput(
+ body: string,
+ currentUri: string,
+ missingScopeMessage: string,
+): ScopedSearchInput {
+ const tokens = body.trim().split(/\s+/).filter(Boolean)
+ const queryParts: string[] = []
+ let scopeUri: string | undefined
+
+ for (let index = 0; index < tokens.length; index += 1) {
+ const token = tokens[index]
+ if (token === '--scope') {
+ 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 (!value) throw new Error(missingScopeMessage)
+ scopeUri = value === '.' ? currentUri : normalizeDirUri(value)
+ continue
+ }
+ queryParts.push(token)
+ }
+
+ return {
+ query: queryParts.join(' ').trim(),
+ scopeUri,
+ }
+}
+
+function sessionToRef(session: Pick<SessionListItem, 'session_id' | 'uri'>) {
+ return {
+ label: session.session_id,
+ meta: 'session',
+ uri: session.uri || `viking://session/${session.session_id}`,
+ }
+}
+
export function TerminalPanel({
currentUri,
entries,
onOpenAddResource,
onOpenResource,
openingUri,
+ onSessionChange,
+ sessionId,
}: {
currentUri: string
entries: VikingFsEntry[]
onOpenAddResource: () => void
onOpenResource: ResourceOpenHandler
openingUri: string | null
+ onSessionChange: (sessionId: string) => void
+ sessionId?: string
}) {
const { t } = useTranslation('playground')
const { connectionRole } = useAppConnection()
@@ -205,7 +768,9 @@ export function TerminalPanel({
const [commandHistory, setCommandHistory] = useState(loadCommandHistory)
const [history, setHistory] = useState(loadTerminalHistory)
const [historyOpen, setHistoryOpen] = useState(false)
+ const [inputFocused, setInputFocused] = useState(false)
const inputRef = useRef<HTMLInputElement>(null)
+ const suggestionRefs = useRef<Array<HTMLButtonElement | null>>([])
const scrollRef = useRef<HTMLDivElement>(null)
const commands = useMemo<TerminalCommandView[]>(
@@ -215,15 +780,18 @@ export function TerminalPanel({
!item.adminOnly ||
connectionRole === 'admin' ||
connectionRole === 'root',
- ).map((item) => ({
- ...item,
- description: t(`terminal.commands.${item.key}.description`, {
- defaultValue: item.command,
- }),
- usage: t(`terminal.commands.${item.key}.usage`, {
- defaultValue: item.insertText.trim(),
- }),
- })),
+ ).map((item) => {
+ const fallback = COMMAND_HELP_FALLBACKS[item.command]
+ return {
+ ...item,
+ description: t(`terminal.commands.${item.key}.description`, {
+ defaultValue: fallback?.description ?? item.command,
+ }),
+ usage: t(`terminal.commands.${item.key}.usage`, {
+ defaultValue: fallback?.usage ?? item.insertText.trim(),
+ }),
+ }
+ }),
[connectionRole, t],
)
@@ -257,6 +825,16 @@ export function TerminalPanel({
return Array.from(candidates).filter(Boolean).sort()
}, [commandHistory, currentUri, entries, history])
+ const activeCommand = useMemo(() => {
+ const rawQuery = command.trimStart()
+ return [...commands]
+ .sort((a, b) => b.command.length - a.command.length)
+ .find(
+ (item) =>
+ rawQuery === item.command || rawQuery.startsWith(`${item.command} `),
+ )
+ }, [command, commands])
+
const suggestions = useMemo<TerminalSuggestion[]>(() => {
const rawQuery = command.trimStart()
const query = rawQuery.toLowerCase()
@@ -279,12 +857,6 @@ export function TerminalPanel({
}))
: []
- const activeCommand = [...commands]
- .sort((a, b) => b.command.length - a.command.length)
- .find(
- (item) =>
- rawQuery === item.command || rawQuery.startsWith(`${item.command} `),
- )
const resourceMatches =
activeCommand && URI_ARGUMENT_COMMANDS.has(activeCommand.command)
? resourceCandidates
@@ -311,6 +883,48 @@ export function TerminalPanel({
}))
: []
+ const sessionSubcommandMatches =
+ activeCommand?.command === '/session'
+ ? (() => {
+ const rawBody = rawQuery.slice(activeCommand.command.length)
+ const body = rawBody.trimStart()
+ const [partial = ''] = body.split(/\s+/)
+ const isChoosingSubcommand =
+ body.length === 0 ||
+ (!rawBody.endsWith(' ') && !body.slice(partial.length).trim())
+
+ if (!isChoosingSubcommand) return []
+
+ return SESSION_SUBCOMMANDS.filter(
+ (item) =>
+ !partial ||
+ item.key.toLowerCase().startsWith(partial.toLowerCase()) ||
+ item.description.toLowerCase().includes(partial.toLowerCase()),
+ ).map((item) => {
+ const exampleKey = item.examples[0]
+ const fallback = exampleKey
+ ? EXAMPLE_HELP_FALLBACKS[exampleKey]
+ : undefined
+ const description = t(
+ `terminal.commandExamples.${exampleKey}.description`,
+ {
+ defaultValue: fallback?.description ?? item.description,
+ },
+ )
+ return {
+ ...activeCommand,
+ command: item.key,
+ description,
+ group: 'subcommand' as const,
+ id: `subcommand:session:${item.key}`,
+ insertText: item.insertText,
+ key: `session:${item.key}`,
+ usage: item.usage,
+ }
+ })
+ })()
+ : []
+
const historyMatches = commandHistory
.filter((item) => {
const lower = item.toLowerCase()
@@ -330,37 +944,135 @@ export function TerminalPanel({
}))
const seen = new Set<string>()
- return [...commandMatches, ...resourceMatches, ...historyMatches].filter(
- (item) => {
- if (seen.has(item.insertText)) return false
- seen.add(item.insertText)
- return true
- },
- )
- }, [command, commandHistory, commands, resourceCandidates, t])
-
- const groupedSuggestions = useMemo(() => {
- const order: TerminalSuggestionGroup[] = [
- 'core',
- 'filesystem',
- 'search',
- 'status',
- 'resource',
- 'history',
- ]
- return order
- .map((group) => ({
- group,
- items: suggestions.filter((item) => item.group === group),
- label: t(`terminal.commandGroups.${group}`),
- }))
- .filter((group) => group.items.length > 0)
- }, [suggestions, t])
+ return [
+ ...commandMatches,
+ ...resourceMatches,
+ ...sessionSubcommandMatches,
+ ...historyMatches,
+ ].filter((item) => {
+ if (seen.has(item.insertText)) return false
+ seen.add(item.insertText)
+ return true
+ })
+ }, [activeCommand, command, commandHistory, commands, resourceCandidates, t])
+
+ const helpCommand = useMemo(() => {
+ if (!activeCommand) return undefined
+ return activeCommand
+ }, [activeCommand])
+
+ const selectedSessionSubcommand = useMemo(() => {
+ if (helpCommand?.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])
+
+ const sessionSubcommandRows = useMemo(
+ () =>
+ SESSION_SUBCOMMANDS.map((item) => {
+ const exampleKey = item.examples[0]
+ const fallback = exampleKey
+ ? EXAMPLE_HELP_FALLBACKS[exampleKey]
+ : undefined
+ return {
+ ...item,
+ description: t(`terminal.commandExamples.${exampleKey}.description`, {
+ defaultValue: fallback?.description ?? item.description,
+ }),
+ }
+ }),
+ [t],
+ )
+
+ const showSessionSubcommandList =
+ helpCommand?.command === '/session' && !selectedSessionSubcommand
+
+ const helpTitle = selectedSessionSubcommand
+ ? `/session ${selectedSessionSubcommand.key}`
+ : helpCommand?.command
+ const helpDescription = selectedSessionSubcommand
+ ? t(
+ `terminal.commandExamples.${selectedSessionSubcommand.examples[0]}.description`,
+ {
+ defaultValue:
+ EXAMPLE_HELP_FALLBACKS[selectedSessionSubcommand.examples[0]]
+ ?.description ?? selectedSessionSubcommand.description,
+ },
+ )
+ : helpCommand?.description
+ const helpUsage = selectedSessionSubcommand
+ ? selectedSessionSubcommand.usage
+ : helpCommand?.usage
+
+ const commandParameters = useMemo(
+ () =>
+ (
+ selectedSessionSubcommand?.parameters ??
+ (showSessionSubcommandList ? [] : (helpCommand?.parameters ?? []))
+ ).map((key) => {
+ const fallback = PARAMETER_HELP_FALLBACKS[key]
+ return {
+ description: t(`terminal.commandParameters.${key}.description`, {
+ defaultValue: fallback.description,
+ }),
+ key,
+ name: t(`terminal.commandParameters.${key}.name`, {
+ defaultValue: fallback.name,
+ }),
+ }
+ }),
+ [helpCommand, selectedSessionSubcommand, showSessionSubcommandList, t],
+ )
+
+ const commandExamples = useMemo(
+ () =>
+ (
+ selectedSessionSubcommand?.examples ??
+ (showSessionSubcommandList ? [] : (helpCommand?.examples ?? []))
+ ).map((key) => {
+ const fallback = EXAMPLE_HELP_FALLBACKS[key]
+ return {
+ code: t(`terminal.commandExamples.${key}.code`, {
+ defaultValue: fallback?.code ?? key,
+ }),
+ description: t(`terminal.commandExamples.${key}.description`, {
+ defaultValue: fallback?.description ?? '',
+ }),
+ key,
+ }
+ }),
+ [helpCommand, selectedSessionSubcommand, showSessionSubcommandList, t],
+ )
+
+ const canUseCurrentScope =
+ helpCommand?.command === '/find' || helpCommand?.command === '/search'
+
+ const showCommandAssist =
+ inputFocused &&
+ (Boolean(helpCommand) || (suggestionsOpen && suggestions.length > 0))
useEffect(() => {
setActiveSuggestionIndex(0)
}, [suggestions.length])
+ useEffect(() => {
+ suggestionRefs.current = suggestionRefs.current.slice(
+ 0,
+ suggestions.length,
+ )
+ }, [suggestions.length])
+
+ useEffect(() => {
+ if (!suggestionsOpen) return
+ suggestionRefs.current[activeSuggestionIndex]?.scrollIntoView({
+ block: 'nearest',
+ })
+ }, [activeSuggestionIndex, suggestionsOpen])
+
useEffect(() => {
scrollRef.current?.scrollTo({
behavior: 'smooth',
@@ -408,6 +1120,7 @@ export function TerminalPanel({
append({ kind: 'command', title: trimmed })
rememberCommand(trimmed)
setCommand('')
+ setSuggestionsOpen(false)
setRunning(true)
try {
@@ -551,19 +1264,28 @@ export function TerminalPanel({
}
case '/find':
case '/search': {
- if (!body) throw new Error(t('terminal.searchUsage', { name }))
- const result = await fetchSearch(body, {
+ const { query, scopeUri } = parseScopedSearchInput(
+ body,
+ currentUri,
+ t('terminal.searchUsage', { name }),
+ )
+ if (!query) throw new Error(t('terminal.searchUsage', { name }))
+ const result = await fetchSearch(query, {
limit: 8,
- targetUri: currentUri,
+ targetUri: scopeUri,
+ })
+ const scopeText = scopeUri ?? t('terminal.globalScope')
+ const summary = t('terminal.hits', {
+ memories: result.memories.length,
+ resources: result.resources.length,
+ skills: result.skills.length,
})
append({
- body:
- result.query_plan?.reasoning ||
- t('terminal.hits', {
- memories: result.memories.length,
- resources: result.resources.length,
- skills: result.skills.length,
- }),
+ body: joinBodyLines([
+ t('terminal.searchScopeLine', { scope: scopeText }),
+ result.query_plan?.reasoning || summary,
+ result.query_plan?.reasoning ? summary : undefined,
+ ]),
kind: 'success',
refs: searchResultToRefs(result, groupLabels),
title: `${name} ${body}`,
@@ -579,6 +1301,289 @@ export function TerminalPanel({
})
return
}
+ case '/session': {
+ const { flags, positional } = parseOptions(body)
+ const subcommand = positional.shift() ?? 'current'
+ const requireCurrentSession = () => {
+ if (!sessionId) throw new Error(t('terminal.sessionMissing'))
+ return sessionId
+ }
+ const resolveSessionId = () =>
+ positional.shift() ?? requireCurrentSession()
+ const sessionRef = (id: string): ResourceRef => ({
+ label: id,
+ meta: 'session',
+ uri: `viking://session/${id}`,
+ })
+
+ switch (subcommand) {
+ case 'current': {
+ const id = requireCurrentSession()
+ append({
+ body: t('terminal.sessionCurrentBody', { id }),
+ kind: 'success',
+ refs: [sessionRef(id)],
+ title: '/session current',
+ })
+ return
+ }
+ case 'list': {
+ const sessions = await fetchSessions()
+ append({
+ body: t('terminal.sessionListBody', {
+ count: sessions.length,
+ }),
+ kind: 'success',
+ refs: sessions.map(sessionToRef),
+ title: '/session list',
+ })
+ return
+ }
+ case 'create': {
+ const requestedId = positional.shift()
+ const result = await createSession(requestedId)
+ registerPlaygroundAgentSessionId(result.session_id)
+ onSessionChange(result.session_id)
+ append({
+ body: joinBodyLines([
+ t('terminal.sessionCreatedBody', {
+ id: result.session_id,
+ }),
+ formatJson(result),
+ ]),
+ kind: 'success',
+ refs: [sessionRef(result.session_id)],
+ title: '/session create',
+ })
+ return
+ }
+ case 'switch': {
+ const id = positional.shift()
+ if (!id) throw new Error(t('terminal.sessionUsage'))
+ registerPlaygroundAgentSessionId(id)
+ onSessionChange(id)
+ append({
+ body: t('terminal.sessionSwitchedBody', { id }),
+ kind: 'success',
+ refs: [sessionRef(id)],
+ title: `/session switch ${id}`,
+ })
+ return
+ }
+ case 'get': {
+ const id = resolveSessionId()
+ const result = await fetchSession(id)
+ append({
+ body: formatJson(result),
+ kind: 'success',
+ refs: [sessionRef(id)],
+ title: `/session get ${id}`,
+ })
+ return
+ }
+ case 'context': {
+ const id = resolveSessionId()
+ const result = await fetchSessionContext(
+ id,
+ getNumberFlag(flags, 'token-budget'),
+ )
+ append({
+ body: formatJson(result),
+ kind: 'success',
+ refs: [sessionRef(id)],
+ title: `/session context ${id}`,
+ })
+ return
+ }
+ case 'messages': {
+ const id = resolveSessionId()
+ const result = await fetchSessionMessages(id)
+ append({
+ body: formatJson(result),
+ kind: 'success',
+ refs: [sessionRef(id)],
+ title: `/session messages ${id}`,
+ })
+ return
+ }
+ case 'archive': {
+ const id =
+ positional.length > 1
+ ? positional.shift()!
+ : requireCurrentSession()
+ const archiveId = positional.shift()
+ if (!archiveId) throw new Error(t('terminal.sessionUsage'))
+ const result = await fetchSessionArchive(id, archiveId)
+ append({
+ body: formatJson(result),
+ kind: 'success',
+ refs: [
+ {
+ label: archiveId,
+ meta: 'archive',
+ uri: `viking://session/${id}/history/${archiveId}`,
+ },
+ ],
+ title: `/session archive ${id} ${archiveId}`,
+ })
+ return
+ }
+ case 'commit': {
+ const id = resolveSessionId()
+ const result = await commitSession(
+ id,
+ getNumberFlag(flags, 'keep-recent'),
+ )
+ append({
+ body: formatJson(result),
+ kind: 'success',
+ refs: [sessionRef(id)],
+ title: `/session commit ${id}`,
+ })
+ return
+ }
+ case 'extract': {
+ const id = resolveSessionId()
+ const result = await extractSession(id)
+ append({
+ body: formatJson(result),
+ kind: 'success',
+ refs: [sessionRef(id)],
+ title: `/session extract ${id}`,
+ })
+ return
+ }
+ case 'message': {
+ const roleIndex = positional.findIndex(
+ (item) => item === 'user' || item === 'assistant',
+ )
+ if (roleIndex < 0) throw new Error(t('terminal.sessionUsage'))
+ const id =
+ roleIndex > 0
+ ? positional.slice(0, roleIndex).join(' ')
+ : requireCurrentSession()
+ const role = positional[roleIndex] as 'user' | 'assistant'
+ const content = positional.slice(roleIndex + 1).join(' ').trim()
+ if (!content) throw new Error(t('terminal.sessionUsage'))
+ const result = await addMessage(id, role, content)
+ append({
+ body: joinBodyLines([
+ t('terminal.sessionMessageAddedBody', { id }),
+ formatJson(result),
+ ]),
+ kind: 'success',
+ refs: [sessionRef(id)],
+ title: `/session message ${id}`,
+ })
+ return
+ }
+ case 'used': {
+ const id = resolveSessionId()
+ const contexts = flags.get('context')
+ const skillJson = getLastFlag(flags, 'skill-json')
+ const result = await recordSessionUsed(id, {
+ contexts,
+ skill: skillJson ? JSON.parse(skillJson) : undefined,
+ })
+ append({
+ body: formatJson(result),
+ kind: 'success',
+ refs: [sessionRef(id)],
+ title: `/session used ${id}`,
+ })
+ return
+ }
+ case 'tool-results': {
+ const id = resolveSessionId()
+ const result = await fetchSessionToolResults(id, {
+ limit: getNumberFlag(flags, 'limit'),
+ toolName: getLastFlag(flags, 'tool-name'),
+ })
+ append({
+ body: formatJson(result),
+ kind: 'success',
+ refs: [sessionRef(id)],
+ title: `/session tool-results ${id}`,
+ })
+ return
+ }
+ case 'tool-result': {
+ const id =
+ positional.length > 1
+ ? positional.shift()!
+ : requireCurrentSession()
+ const toolResultId = positional.shift()
+ if (!toolResultId) throw new Error(t('terminal.sessionUsage'))
+ const result = await fetchSessionToolResult(id, toolResultId, {
+ includeMetadata: !getBooleanFlag(flags, 'no-metadata'),
+ limit: getNumberFlag(flags, 'limit'),
+ offset: getNumberFlag(flags, 'offset'),
+ })
+ append({
+ body: formatJson(result),
+ kind: 'success',
+ refs: [
+ {
+ label: toolResultId,
+ meta: 'tool result',
+ uri: `viking://session/${id}/tool-results/${toolResultId}`,
+ },
+ ],
+ title: `/session tool-result ${id} ${toolResultId}`,
+ })
+ return
+ }
+ case 'tool-search': {
+ const id =
+ positional.length > 2
+ ? positional.shift()!
+ : requireCurrentSession()
+ const toolResultId = positional.shift()
+ const query = positional.join(' ').trim()
+ if (!toolResultId || !query) {
+ throw new Error(t('terminal.sessionUsage'))
+ }
+ const result = await searchSessionToolResult(
+ id,
+ toolResultId,
+ query,
+ {
+ contextChars: getNumberFlag(flags, 'context-chars'),
+ limit: getNumberFlag(flags, 'limit'),
+ },
+ )
+ append({
+ body: formatJson(result),
+ kind: 'success',
+ refs: [
+ {
+ label: toolResultId,
+ meta: 'tool search',
+ uri: `viking://session/${id}/tool-results/${toolResultId}`,
+ },
+ ],
+ title: `/session tool-search ${id} ${toolResultId}`,
+ })
+ return
+ }
+ case 'delete': {
+ const id = positional.shift()
+ if (!id) throw new Error(t('terminal.sessionDeleteUsage'))
+ const result = await deleteSession(id)
+ append({
+ body: joinBodyLines([
+ t('terminal.sessionDeletedBody', { id }),
+ formatJson(result),
+ ]),
+ kind: 'success',
+ title: `/session delete ${id}`,
+ })
+ return
+ }
+ default:
+ throw new Error(t('terminal.sessionUsage'))
+ }
+ }
default:
throw new Error(t('terminal.unknownCommand'))
}
@@ -599,8 +1604,10 @@ export function TerminalPanel({
groupLabels,
onOpenAddResource,
onOpenResource,
+ onSessionChange,
running,
rememberCommand,
+ sessionId,
t,
],
)
@@ -618,17 +1625,26 @@ export function TerminalPanel({
})
}, [])
- const runSuggestion = useCallback(
- (suggestion: TerminalSuggestion) => {
- setSuggestionsOpen(false)
- if (suggestion.executable) {
- void runCommand(suggestion.insertText)
- return
- }
- setCommand(suggestion.insertText)
- },
- [runCommand],
- )
+ const insertCurrentScope = useCallback(() => {
+ const trimmed = command.trimEnd()
+ const hasScope = trimmed.match(/(?:^|\s)--scope(?:=|\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}`
+ const cursorPosition =
+ hasScope || body ? next.length : commandName.length + 1
+ setCommand(next)
+ setSuggestionsOpen(false)
+ window.requestAnimationFrame(() => {
+ const input = inputRef.current
+ input?.focus()
+ input?.setSelectionRange(cursorPosition, cursorPosition)
+ })
+ }, [command, currentUri, helpCommand])
const quickCommands = commands.filter((item) =>
['/status', '/find', '/search', '/add-resource'].includes(item.command),
@@ -669,6 +1685,12 @@ export function TerminalPanel({
<span className="min-w-0 flex-1 truncate">
{t('terminal.header')}
</span>
+ <span
+ className="min-w-0 max-w-[60%] truncate rounded-md border bg-muted/40 px-2 py-1 font-mono text-[11px] text-foreground"
+ title={currentUri}
+ >
+ {t('terminal.scopeLabel', { uri: currentUri })}
+ </span>
<Button
type="button"
variant="ghost"
@@ -732,13 +1754,19 @@ export function TerminalPanel({
ref={inputRef}
value={command}
onBlur={() => {
- window.setTimeout(() => setSuggestionsOpen(false), 120)
+ window.setTimeout(() => {
+ setInputFocused(false)
+ setSuggestionsOpen(false)
+ }, 120)
}}
onChange={(event) => {
setCommand(event.target.value)
setSuggestionsOpen(true)
}}
- onFocus={() => setSuggestionsOpen(true)}
+ onFocus={() => {
+ setInputFocused(true)
+ setSuggestionsOpen(true)
+ }}
onKeyDown={(event) => {
if (!suggestionsOpen || suggestions.length === 0) return
if (event.key === 'ArrowDown') {
@@ -771,11 +1799,7 @@ export function TerminalPanel({
}
if (event.key === 'Enter') {
event.preventDefault()
- if (command.trim() === '/') {
- acceptSuggestion(suggestions[activeSuggestionIndex])
- return
- }
- runSuggestion(suggestions[activeSuggestionIndex])
+ acceptSuggestion(suggestions[activeSuggestionIndex])
return
}
if (event.key === 'Escape') {
@@ -785,62 +1809,196 @@ export function TerminalPanel({
placeholder={t('terminal.placeholder')}
className="h-8 min-w-0 flex-1 bg-transparent font-mono text-sm outline-none placeholder:text-muted-foreground/60"
/>
- {suggestionsOpen && suggestions.length > 0 ? (
- <div className="absolute bottom-[calc(100%+0.5rem)] left-0 right-0 z-20 overflow-hidden rounded-lg border bg-popover shadow-xl">
- <div className="border-b px-3 py-2 text-[11px] font-medium text-muted-foreground">
- {t('terminal.suggestionsTitle')}
- </div>
- <div className="max-h-64 overflow-y-auto p-1">
- {(() => {
- let suggestionIndex = 0
- return groupedSuggestions.map((group) => (
- <div key={group.group} className="py-1 first:pt-0">
- <div className="px-2 pb-1 pt-1 text-[10px] font-semibold text-muted-foreground">
- {group.label}
+ {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>
- {group.items.map((suggestion) => {
- const index = suggestionIndex
- suggestionIndex += 1
- return (
- <button
- key={suggestion.id}
- type="button"
- className={cn(
- 'grid w-full min-w-0 grid-cols-[minmax(5rem,12rem)_minmax(0,1fr)] items-start gap-3 rounded-md px-2 py-2 text-left transition-colors',
- index === activeSuggestionIndex
- ? 'bg-primary/10 text-foreground'
- : 'hover:bg-muted/60',
- )}
- onClick={() => acceptSuggestion(suggestion)}
- onMouseDown={(event) => event.preventDefault()}
- onMouseEnter={() =>
- setActiveSuggestionIndex(index)
- }
- >
- <span
- className="min-w-0 truncate font-mono text-xs font-semibold text-primary"
- title={suggestion.command}
- >
- {suggestion.command}
- </span>
- <span className="min-w-0 flex-1">
- <span className="block text-xs text-foreground">
- {suggestion.description}
- </span>
- <span className="mt-0.5 block truncate font-mono text-[11px] text-muted-foreground">
- {suggestion.usage}
- </span>
- </span>
- </button>
- )
- })}
</div>
- ))
- })()}
- </div>
- <div className="border-t px-3 py-1.5 text-[10px] text-muted-foreground">
- {t('terminal.suggestionsHint')}
- </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="min-w-0">
+ <div className="mb-1.5 text-[11px] font-medium text-muted-foreground">
+ {t('terminal.helpSubcommands', {
+ defaultValue: '子命令',
+ })}
+ </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>
+ </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 className="min-w-0">
+ <div className="mb-1.5 text-[11px] font-medium text-muted-foreground">
+ {t('terminal.helpExamples')}
+ </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}
+ >
+ {example.code}
+ </span>
+ </td>
+ <td className="align-top px-2 py-1.5 leading-4 text-muted-foreground">
+ {example.description}
+ </td>
+ </tr>
+ ))}
+ </tbody>
+ </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>
+ )}
+ </button>
+ ))}
+ </div>
+ ) : null}
</div>
) : null}
<Button
diff --git a/web-studio/src/routes/playground/-lib/constants.ts b/web-studio/src/routes/playground/-lib/constants.ts
index c38b23dcb..a9eb82972 100644
--- a/web-studio/src/routes/playground/-lib/constants.ts
+++ b/web-studio/src/routes/playground/-lib/constants.ts
@@ -21,88 +21,150 @@ export const PLAYGROUND_MAIN_MIN_WIDTH = 420
export const TERMINAL_COMMANDS: TerminalCommandSuggestion[] = [
{
- command: '/add-resource',
+ command: '/status',
+ executable: true,
+ examples: ['status.default'],
+ group: 'status',
+ key: 'status',
+ insertText: '/status',
+ },
+ {
+ command: '/ls',
+ executable: true,
+ examples: ['ls.current', 'ls.target'],
+ group: 'filesystem',
+ key: 'ls',
+ insertText: '/ls ',
+ parameters: ['uri'],
+ },
+ {
+ command: '/search',
executable: true,
+ examples: ['search.global', 'search.current', 'search.scoped'],
+ group: 'search',
+ key: 'search',
+ insertText: '/search ',
+ parameters: ['query', 'scope'],
+ },
+ {
+ command: '/read',
+ executable: true,
+ examples: ['read.file'],
group: 'core',
- key: 'addResource',
- insertText: '/add-resource',
+ key: 'read',
+ insertText: '/read ',
+ parameters: ['uri'],
},
{
command: '/find',
executable: true,
+ examples: ['find.global', 'find.current', 'find.scoped'],
group: 'core',
key: 'find',
insertText: '/find ',
+ parameters: ['query', 'scope'],
},
{
- command: '/read',
+ command: '/add-resource',
executable: true,
+ examples: ['addResource.default'],
group: 'core',
- key: 'read',
- insertText: '/read ',
+ key: 'addResource',
+ insertText: '/add-resource',
},
{
- command: '/ls',
+ command: '/session',
executable: true,
- group: 'filesystem',
- key: 'ls',
- insertText: '/ls ',
+ examples: [
+ 'session.current',
+ 'session.list',
+ 'session.create',
+ 'session.switch',
+ 'session.get',
+ 'session.context',
+ 'session.messages',
+ 'session.archive',
+ 'session.commit',
+ 'session.extract',
+ 'session.message',
+ 'session.used',
+ 'session.toolResults',
+ 'session.toolResult',
+ 'session.toolSearch',
+ 'session.delete',
+ ],
+ group: 'core',
+ key: 'session',
+ insertText: '/session ',
+ parameters: [
+ 'sessionAction',
+ 'sessionId',
+ 'archiveId',
+ 'messageRole',
+ 'messageContent',
+ 'contexts',
+ 'skillJson',
+ 'keepRecent',
+ 'tokenBudget',
+ 'toolName',
+ 'toolResultId',
+ 'limit',
+ 'offset',
+ 'contextChars',
+ ],
},
{
command: '/tree',
executable: true,
+ examples: ['tree.current', 'tree.target'],
group: 'filesystem',
key: 'tree',
insertText: '/tree ',
+ parameters: ['uri'],
},
{
command: '/stat',
executable: true,
+ examples: ['stat.target'],
group: 'filesystem',
key: 'stat',
insertText: '/stat ',
- },
- {
- command: '/search',
- executable: true,
- group: 'search',
- key: 'search',
- insertText: '/search ',
+ parameters: ['uri'],
},
{
command: '/abstract',
executable: true,
+ examples: ['abstract.target'],
group: 'search',
key: 'abstract',
insertText: '/abstract ',
+ parameters: ['uri'],
},
{
command: '/overview',
executable: true,
+ examples: ['overview.target'],
group: 'search',
key: 'overview',
insertText: '/overview ',
+ parameters: ['uri'],
},
{
command: '/health',
executable: true,
+ examples: ['health.default'],
group: 'status',
key: 'health',
insertText: '/health',
},
- {
- command: '/status',
- executable: true,
- group: 'status',
- key: 'status',
- insertText: '/status',
- },
{
adminOnly: true,
command: '/wait',
executable: true,
+ examples: ['wait.default', 'wait.timeout'],
group: 'status',
key: 'wait',
insertText: '/wait ',
+ parameters: ['timeout'],
},
]
diff --git a/web-studio/src/routes/playground/-lib/types.ts b/web-studio/src/routes/playground/-lib/types.ts
index cc39bb1cb..0e2a553aa 100644
--- a/web-studio/src/routes/playground/-lib/types.ts
+++ b/web-studio/src/routes/playground/-lib/types.ts
@@ -26,13 +26,35 @@ export type TerminalEntry = {
export type TerminalCommandGroup = 'core' | 'filesystem' | 'search' | 'status'
+export type TerminalCommandParameterKey =
+ | 'archiveId'
+ | 'contextChars'
+ | 'contexts'
+ | 'keepRecent'
+ | 'limit'
+ | 'messageContent'
+ | 'messageRole'
+ | 'offset'
+ | 'query'
+ | 'scope'
+ | 'sessionAction'
+ | 'sessionId'
+ | 'skillJson'
+ | 'tokenBudget'
+ | 'toolName'
+ | 'toolResultId'
+ | 'timeout'
+ | 'uri'
+
export type TerminalCommandSuggestion = {
adminOnly?: boolean
command: string
+ examples?: string[]
group: TerminalCommandGroup
/** i18n subkey under `playground.terminal.commands`. */
key: string
insertText: string
+ parameters?: TerminalCommandParameterKey[]
executable?: boolean
}
diff --git a/web-studio/src/routes/playground/route.tsx b/web-studio/src/routes/playground/route.tsx
index a6ad96788..4644d8071 100644
--- a/web-studio/src/routes/playground/route.tsx
+++ b/web-studio/src/routes/playground/route.tsx
@@ -565,7 +565,11 @@ function PlaygroundWorkbench() {
entries={entries}
onOpenAddResource={() => setUploadDialogOpen(true)}
onOpenResource={revealResource}
+ onSessionChange={(sessionId) =>
+ syncSearch({ session: sessionId })
+ }
openingUri={openingUri}
+ sessionId={search.session}
/>
) : (
<AgentPanel