Skip to content

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

feat(web-studio): add Compile workflows and lifecycle documentation (#5098)

yufeng114f6c51b6cc
diff --git a/docs/design/web-studio-compile-interaction-design.md b/docs/design/web-studio-compile-interaction-design.md
new file mode 100644
index 000000000..5b03e2ee0
--- /dev/null
+++ b/docs/design/web-studio-compile-interaction-design.md
@@ -0,0 +1,521 @@
+# Web Studio Compile 交互与实现设计
+
+| 项目 | 内容 |
+| --- | --- |
+| 状态 | 待实现设计 |
+| 更新日期 | 2026-09-16 |
+| 适用范围 | Web Studio Compile 独立导航页、Playground 终端、通用任务联动 |
+| 核心流程 | 选择 Skill → 选择素材 → 设置输出 → 提交 → 查看执行 → 打开产物 |
+
+## 1. 目标与边界
+
+Compile 使用一个指定 Skill,加工一个或多个 OpenViking 素材目录,并将结果写入目标目录。用户应能理解“用什么方法、处理什么内容、结果放在哪里”,无需先学习 API 或 Runtime 配置。
+
+提供两个平等入口:
+
+1. **Compile 独立 Tab**:在 Studio 左侧工作区导航中增加 Compile,紧邻 Skills。提供任务列表、新建页、详情页。
+2. **Playground 终端**:支持 compile 和 task 命令,适合熟悉 CLI 的用户;提交后可进入同一详情页。
+
+本文的 Tab 指独立导航模块,不是 Playground 内部新面板。资源页、Skills 页第一版不增加额外创建入口。
+
+第一版包含完整的创建、查询、取消、参数回填、再次运行和结果查看闭环,并补齐服务端分页。暂不包含定时执行、批量取消、任务删除、任务重命名、产物差异比较、运行中修改参数及通用 Skill 参数表单生成。
+
+## 2. 当前能力与设计依赖
+
+以下现状以本地源码为依据,不代表部署环境已验证。
+
+| 能力 | 当前实现 | 本方案处理 |
+| --- | --- | --- |
+| 创建 | `POST /api/v1/compile`,202,返回 TaskRecord | 复用 |
+| 必填参数 | `from`、`to`、`skill` | 映射三个表单区块 |
+| 可选参数 | `instruction`、`args` | 补充要求、折叠高级参数 |
+| 查询详情 | `GET /api/v1/tasks/{task_id}` | 复用,携带 `include_events=true` |
+| 查询列表 | `GET /api/v1/tasks`,默认 50、最多 200,无游标 | 增加兼容的分页模式 |
+| 取消 | `POST /api/v1/tasks/{task_id}/cancel`,ROOT 禁止取消 | 复用并明确权限和状态 |
+| 原始输入 | `meta.request` 保存公开请求字段 | 用于详情及回填;敏感参数不回显 |
+| 执行事件 | 详情可返回 `execution_events` | 复用已有事件展示,缺失时不伪造 |
+| 执行后端 | 外部 `compile_api` 或 `--with-bot` 本地执行服务 | 新增能力状态用于入口反馈 |
+| Studio 终端 | 自有命令解释器,不是操作系统 Shell | 增加命令解析与 API 调用 |
+| 原生 CLI | 已支持 `ov compile` 和 `ov task status/cancel/list` | Studio 对齐对应语法 |
+
+`docs/design/ov-compile-design.md` 保留了历史 Bot 直连方案。本文以现行 OpenViking 托管任务的接口为准;浏览器不直接调用 Runtime 或旧 Bot compile 接口。
+
+## 3. 页面和路由
+
+| 页面 | 路由 | 主要动作 |
+| --- | --- | --- |
+| 编译列表 | `/compile` | 筛选、加载更多、新建、点击任务 |
+| 新建编译 | `/compile/new` | 选择 Skill/素材/输出、提交、保存草稿 |
+| 编译详情 | `/compile/tasks/$taskId` | 查看执行、取消、打开结果、再次运行 |
+| 基于任务新建 | `/compile/new?fromTask=$taskId` | 获取公开配置后回填,不立即提交 |
+| 终端 | 现有 Playground terminal 面板 | 命令补全、提交、查询、取消、跳转详情 |
+
+列表筛选放入 URL,例如 `?status=running&q=wiki`。草稿、指令、args 不放入 URL。详情页面的任务 ID 只定位任务,权限仍由服务端验证。
+
+导航规则:
+
+- 点击左侧 Compile 默认进入列表;不自动跳到上次任务。
+- 点击列表行进入完整详情页,不用抽屉承载主要流程。
+- 返回列表恢复筛选、已加载页面及滚动位置;刷新详情可直接重新获取任务。
+- 外部直接进入详情时,“返回列表”落到默认列表。
+- 列表行支持键盘 Enter、链接新标签打开;行内复制按钮不触发行跳转。
+- 通用 Tasks 页面保留 compile 记录,并提供进入 Compile 详情的链接。
+
+```mermaid
+flowchart LR
+ L[Compile 列表] --> N[新建编译]
+ L --> D[任务详情]
+ N -->|创建成功| D
+ T[Playground 终端] -->|compile 提交| A[任务回执]
+ A -->|查看任务| D
+ T -->|打开表单| N
+ D -->|修改后重新运行| N
+ D -->|查看输出| R[资源或 Skill 浏览页面]
+ D -->|返回| L
+```
+
+## 4. 页面一:Compile 列表
+
+### 4.1 布局
+
+```text
+Compile [新建编译]
+使用 Skill 将素材整理为新的内容
+
+[搜索 Skill、路径或任务 ID…] [全部状态 ▾] [刷新]
+
+任务 / Skill 素材 状态 创建时间
+monthly_wiki → 团队知识库 周报 等 2 个目录 运行中 今天 14:20
+guide_builder → 操作指南 产品文档 已完成 今天 13:10
+monthly_wiki → 月报 周报 失败 昨天 18:00
+
+ [加载更多]
+```
+
+### 4.2 列表字段与操作
+
+| 字段 | 展示规则 |
+| --- | --- |
+| 任务标题 | 从请求派生“Skill 名称 → 输出目录名”;无请求信息时显示任务 ID |
+| Skill | 显示名称;完整 URI 可通过详情查看,不依赖 Skill 当前仍存在 |
+| 素材 | 第一个目录名及“等 N 个目录”;详情展示完整集合 |
+| 状态 | 图标与文字共同表达,不只使用颜色 |
+| 创建时间 | 本地时区,相对日期;悬停显示完整时间和时区 |
+| 任务 ID | 行次要信息,支持复制 |
+
+排序固定为 `created_at DESC, task_id DESC`。同一素材或同一目标的多次执行分别保留,不应用通用 Tasks 页面按资源去重的逻辑。
+
+行点击只负责打开详情。第一版不在行内堆叠取消、重跑和输出等按钮,这些操作集中在详情。
+
+### 4.3 筛选与分页
+
+- 状态选项:全部、排队中、运行中、取消中、已完成、失败、已取消。
+- 搜索覆盖当前用户可见的全部历史任务,范围为任务 ID、公开请求中的 Skill URI、来源 URI、目标 URI;不搜索 instruction 和 args。
+- 搜索输入防抖 300 ms;更改筛选时回到第一页,清除旧游标并取消过时请求。
+- 每页 30 条,“加载更多”追加结果;失败在按钮位置重试,不清空已加载内容。
+- 无下一页时显示“已显示全部可用记录”,不显示未经计算的任务总数。
+- 初次查询失败显示错误和重试,不能显示为“暂无任务”。
+- 新任务提示为“有新任务,点击刷新”;浏览历史时不自动插入并推动列表。
+- 列表可见时每 10 秒刷新第一页;仅更新已显示 ID 的状态,新 ID 先显示提示。详情页拥有更及时的单任务刷新。
+- 分页是实时记录浏览,不是严格快照。状态筛选期间任务可能移入或移出集合;刷新后重新建立游标链,不承诺固定总数。
+
+### 4.4 空状态与服务状态
+
+| 场景 | 文案与操作 |
+| --- | --- |
+| 无历史任务 | “使用 Skill,把已有素材整理成新的内容。”+“新建编译” |
+| 筛选无结果 | “没有符合条件的任务。”+“清除筛选” |
+| 加载失败 | “任务列表加载失败。”+“重试” |
+| 执行服务未配置 | 顶部说明“当前连接尚未启用编译服务”;历史记录仍可查看,创建入口禁用并提供原因 |
+| 能力状态获取失败 | 显示“暂时无法确认编译服务状态”及重试;不误报为未配置,可进入表单并由提交接口最终判定 |
+
+## 5. 页面二:新建编译
+
+### 5.1 表单布局
+
+采用单页分组表单,不使用多步弹窗。Skill 在最前面,帮助用户先理解加工方式,再选择输入和输出。
+
+```text
+[返回列表] 新建编译 草稿已保存
+
+1 使用哪个 Skill? *
+ [搜索并选择 Skill ▾]
+ 按月汇总周报,生成主题知识页 [查看 Skill]
+
+2 处理哪些素材? *
+ [选择目录] [粘贴 URI]
+ 周报 viking://resources/weekly [移除]
+ 项目记录 viking://resources/projects [移除]
+
+3 将结果保存到哪里? *
+ [viking://resources/team-wiki ] [浏览]
+ 目标目录尚不存在,执行时按后端能力创建
+
+补充要求
+[例如:按主题整理,保留引用来源,优先使用最近一个月的材料]
+
+▸ 高级参数(可选)
+
+使用 monthly_wiki,处理 2 个目录,输出到 team-wiki
+[复制命令] [取消] [开始编译]
+```
+
+底部操作区在长表单中保持可见,但不遮挡字段错误或屏幕键盘。窄屏取消横向摘要,将完整路径换行显示。
+
+### 5.2 Skill 选择
+
+点击后打开可搜索选择面板。每项显示名称、简短描述、所属范围和 URI;同名 Skill 依靠范围、URI 区分。
+
+- 只列当前身份可见的 Skill,不通过 URI 文本推断权限。
+- 搜索结果缺少描述时显示 URI,不生成未经验证的用途说明。
+- 首次打开不自动选中任意 Skill;只有草稿或复制任务时预选。
+- “查看 Skill”打开侧边预览,显示实际 `SKILL.md`,保留主表单上下文。
+- 预览读取失败不丢失选择,提供重试;提交时仍由后端验证其有效性。
+- 无 Skill 时显示“还没有可用的 Skill”,提供“前往 Skills”;离开前保存公开草稿。
+- 切换 Skill 保留素材、输出和指令。args 非空时提示“已更换 Skill,请检查高级参数”;不静默删除参数。
+- 不假设 Skill 描述能可靠推导输出类型或参数 schema,第一版不自动生成专属表单。
+
+### 5.3 素材目录选择
+
+“选择目录”打开带面包屑的目录选择器,支持进入目录、多选目录及跨目录保留选择。
+
+- 文件可见时置灰并解释“请选择所在目录”;禁止直接选文件作为 from。
+- 已选项以完整 URI 去重,保留选择顺序;后端最终 canonicalize。
+- 手动粘贴支持每行一个 URI,逐条校验并展示错误;无效项可编辑,不清空其它内容。
+- 选择父目录后再选择其子目录时提示可能存在重叠,不静默删除用户选择。
+- 目录不存在、不可读、连接失败使用不同文案;检查中显示局部 loading。
+- 不递归扫描所有内容来估算 token、价格或执行时间。
+
+### 5.4 输出位置
+
+复用目录浏览交互,支持直接输入新路径。字段下持续显示完整 URI,避免同名目录混淆。
+
+- 支持后端允许的 resource、memory 和 skills 目标;具体合法位置以后端校验为准。
+- 技能产物目标必须符合支持的 skills 命名空间,不能按普通目录规则任意嵌套。
+- 来源和目标重叠时提示“结果将写入素材范围,后续执行可能读取这些结果”,不强制替用户更改路径。
+- 已有目标提示“此目录已有内容,执行可能更新其中内容”。不展示尚未支持的“只新增”“自动覆盖”等策略选项。
+- 新目录提示仅表示路径未存在,不在填写表单时提前创建远端目录。
+- 目标为文件、无写权限或命名空间根不合法时就地报错。
+- 可做轻量存在性检查;写权限和业务合法性必须由创建接口最终确认,不将 stat 成功当作可写证明。
+
+### 5.5 补充要求与高级参数
+
+instruction 可留空,空字符串归一化为未设置。输入框示例不作为默认提交值。
+
+args 使用折叠的 JSON 编辑区,默认空;支持格式化、错误定位,只接受 JSON 对象。解析失败时禁用提交并将错误定位到编辑器。
+
+第一版高级参数仅保留于当前页面内存,不写入本地草稿或终端持久历史。复制命令默认省略 args,并明确提示;用户显式选择“包含高级参数”后才纳入剪贴板。服务端公开请求可能脱敏,不能将脱敏占位值作为真实参数再次提交。
+
+### 5.6 草稿、离开与恢复
+
+- 一个身份范围保存一份公开草稿:Skill、from、to、instruction;键包含连接、账号、用户,禁止跨身份复用。
+- 字段变更后防抖保存,显示“草稿已保存”;存储失败显示“草稿未保存”,不阻断编辑。
+- 再次进入新建页提示“已恢复上次草稿”,提供“清空”。
+- 返回列表或点击取消保留公开草稿;“取消”不创建任务。
+- 有未保存输入或内存中的 args 时,离开弹出“继续编辑 / 离开并丢弃未保存内容”。正常已保存草稿不反复确认。
+- 成功提交后清除本次草稿;提交失败保留全部输入。
+- `fromTask` 回填前若已有草稿,提供“继续现有草稿 / 使用任务配置”;不得静默覆盖。
+- 页面刷新无法恢复 args,在高级参数附近明确提示其不自动保存。
+
+### 5.7 提交交互
+
+1. 点击“开始编译”,检查必填项、URI 基本格式和 args;聚焦首个错误字段。
+2. 校验通过后生成本次提交标识,按钮改为“正在提交”,禁止重复提交;保留可见摘要。
+3. 创建成功后跳转任务详情,提示“任务已创建,离开页面不会中断执行”。
+4. 请求参数、权限或配置错误就地展示;有可定位字段时关联字段,否则显示表单顶部错误。
+5. 请求超时或断连时提示“尚未确认是否创建成功”,不宣称创建失败,不直接发起全新任务。
+6. 在服务端幂等能力支持下,“重试确认”复用同一提交标识;参数改变则必须先解决原请求状态或明确新建另一任务。
+
+正常提交不增加确认弹窗。取消正在提交的页面导航只停止前端等待,不承诺撤销服务端创建。
+
+## 6. 页面三:任务详情
+
+### 6.1 布局
+
+```text
+[返回列表] monthly_wiki → 团队知识库 [修改后重新运行]
+cmp_... [复制] 运行中 已运行 2 分 18 秒 [取消任务]
+当前阶段:后端报告的阶段名称 最后更新:14:22:18
+可以离开页面,任务会继续执行
+
+[概览] [执行记录] [结果]
+
+概览
+Skill monthly_wiki [查看 Skill]
+素材 周报、项目记录 [展开路径]
+输出 viking://resources/team-wiki [打开目录]
+补充要求 按主题整理,保留来源
+创建时间 / 更新时间 / 完成时间(有可靠数据时)
+▸ 高级参数(仅公开、脱敏后的内容)
+```
+
+顶部生命周期状态由 `status` 决定,`stage` 只补充当前阶段,不用字符串猜测覆盖 status。未知状态显示“未知状态”及原始值,不自动当作完成。
+
+### 6.2 概览
+
+- 全量展示本次请求的公开配置;超长来源列表默认显示前三项,可展开全部。
+- Skill 链接读取的是当前版本,标注“查看当前 Skill”;后端无快照信息时不声称这是运行时版本。
+- “打开目录”可以查看运行中的已有内容,但标注“执行中,内容可能继续变化”。目标不存在时显示“输出尚未生成”,不当作任务失败。
+- 没有可靠完成时间时不将任意 `updated_at` 标为完成时间;结束耗时仅在后端提供可确认时间时展示。
+- 旧任务缺少 `meta.request` 时显示“该任务未记录完整创建参数”,不从 resource_id 拼凑可执行请求。
+
+### 6.3 执行记录
+
+- 按后端事件顺序展示时间、事件名称、说明及可展开详情;复用现有事件组件。
+- 没有事件时显示“暂未提供执行记录”,仍显示任务状态和 stage。
+- 不展示模拟日志、虚构的阶段完成勾选或百分比。
+- 用户停留底部时自动跟随;向上滚动后暂停跟随,显示“有新记录 / 回到底部”。
+- 原始结构化信息默认折叠,敏感字段应在服务端脱敏,前端不负责恢复。
+- 若事件历史被截断,展示后端提供的截断提示;没有事件分页能力时不承诺完整日志。
+
+### 6.4 结果
+
+| 状态 | 结果区 |
+| --- | --- |
+| 未结束 | “任务完成后将在此展示结果”;可查看已有目标目录 |
+| 已完成且有标准产物 | 结果摘要、产物链接、主要按钮“打开输出目录” |
+| 已完成但 result 为空或格式未知 | “任务已完成”,提供输出目录;未知结构放入“原始结果” |
+| 失败 | 错误原因、可展开技术信息、“修改后重新运行”;可能存在部分产物时允许查看目标 |
+| 已取消 | “任务已停止;已写入的内容可能保留”,可查看目标和基于参数新建 |
+
+产物链接必须来自明确 URI,不能仅凭 result 中任意字符串生成跳转。resource、memory、skills 使用对应浏览能力;暂不能直接定位的 URI 提供复制及可用的目录浏览入口。
+
+第一版不假设存在统一的 created/updated 文件列表,不显示未经后端确认的文件数量、覆盖差异或“全部成功写入”结论。
+
+### 6.5 取消与再次运行
+
+取消按钮仅在后端可取消状态及身份下启用。ROOT 显示禁用原因“当前 ROOT 身份不能取消任务”,不能仅隐藏后使用户误认为不支持。
+
+点击取消打开轻量确认框:“停止此任务?已经写入的内容可能保留。”按钮为“继续执行 / 停止任务”。请求成功后依据返回状态显示取消中或实际终态,不立即伪造 cancelled。
+
+- 请求失败保留真实状态并允许重试。
+- 取消期间任务已经完成时,展示最终完成状态并说明结果已更新。
+- “修改后重新运行”只打开预填表单,不隐式创建任务;原任务不受影响。
+- 缺少敏感参数或公开参数被脱敏时提示需要重新填写,不提交脱敏占位符。
+- 当前 Skill 已删除或权限变化时回填 URI 并标为待重新选择;不阻止用户查看旧任务。
+
+### 6.6 刷新、恢复与通知
+
+- 活跃任务详情可见时每 5 秒查询;浏览器隐藏时暂停,重新聚焦立即刷新。
+- 终态停止自动轮询,保留手动刷新;未知状态使用低频刷新并允许重试。
+- 后端 provider 可能以更长间隔刷新状态,前端查询频率不等于执行进度更新频率。
+- 连续请求失败采用有上限的退避;显示“暂时无法更新,以下为最近状态”,不将任务改为 failed。
+- 返回列表、刷新浏览器、关闭终端都不取消任务;恢复后重新查询服务端。
+- 当前页面观察到完成时显示一次带“查看结果”的通知,不主动切换用户正在查看的子页。
+- 不承诺浏览器关闭后的系统通知;第一版不请求浏览器通知权限。
+- 404 统一显示“任务不存在、已过期或当前身份不可访问”,提供返回列表;不泄露其他用户任务。
+
+## 7. Playground 终端交互
+
+### 7.1 命令集
+
+```bash
+compile --from viking://resources/weekly --to viking://resources/wiki --skill viking://agent/skills/monthly_wiki --instruction "按主题整理,保留来源"
+task status cmp_example
+task list --task-type compile --status running
+task cancel cmp_example
+```
+
+同时接受可选的 `ov` 前缀。from 支持重复参数和逗号分隔,与原生 CLI 对齐。compile 成功后立即返回回执,不阻塞用户输入下一条命令。
+
+这是 Studio 命令语法,不能执行 Shell 的管道、重定向、命令替换或环境变量展开。明确拒绝不支持的语法,不传给系统 Shell。
+
+### 7.2 提示与补全
+
+- 输入 `compile` 显示用途、必填参数、一个可运行结构的示例及“打开可视化表单”。单独回车显示帮助,不创建空任务。
+- 参数补全区分 `--from` 的可读目录、`--skill` 的 Skill 和 `--to` 的目标路径。
+- 缺参时展示准确字段,如“缺少 --skill”,并允许将已解析值带入表单。
+- 无效 JSON 指出 `--args` 必须是对象,不输出完整可能含凭证的输入。
+- 支持单引号、双引号、转义及 JSON 字符串;共享专门的解析模块,不继续使用空格 split。
+- 终端到表单通过身份隔离的内存交接保存参数,地址栏不携带参数;不能恢复的高级参数明确提示。
+
+### 7.3 提交回执与后续操作
+
+```text
+任务已创建
+任务:cmp_example
+状态:排队中
+输出:viking://resources/wiki
+[查看任务] [复制任务 ID]
+```
+
+回执卡片可在可见时刷新状态,复用同一任务查询缓存;不为历史每张卡片分别长期轮询。点击“查看任务”进入 Compile 详情。
+
+task status 展示状态、阶段、错误或结果摘要及详情链接。task list 展示分页结果及“加载更多”,明确范围是当前连接与身份。task cancel 属于用户明确取消指令,不再弹二次确认,返回“正在取消”或真实终态,并说明已有写入可能保留。
+
+历史只持久化经过处理的命令摘要及任务 ID,args 不落盘;含高级参数的原始命令不得进入现有命令历史、entry title 或错误文本。重用历史时提示补齐参数。
+
+表单“复制命令”采用统一转义生成器,并与解析器做往返验证。正常公开字段可复制,默认省略 args;复制内容必须与当前表单实际值一致。
+
+## 8. 接口补充设计
+
+本节均为拟新增契约,不能当作当前接口已支持。
+
+### 8.1 创建及公开请求
+
+现有请求保持兼容:
+
+```json
+{
+ "from": ["viking://resources/weekly"],
+ "to": "viking://resources/wiki",
+ "skill": "viking://agent/skills/monthly_wiki",
+ "instruction": "按主题整理,保留来源"
+}
+```
+
+前端通过适配层读取 `meta.request`,不要让页面散落依赖任意 meta 字段。无参数快照时禁用自动回填并解释原因。
+
+### 8.2 创建幂等
+
+为 `POST /api/v1/compile` 增加可选 `Idempotency-Key`。幂等范围为连接对应服务内的 account、user、操作类型及 key。
+
+- 同 key、同规范化请求返回同一 task_id;同 key、不同请求返回明确冲突。
+- 请求校验失败不产生任务;校验通过后的幂等登记与任务创建必须具备原子保证。
+- 并发请求和服务重启不能产生重复任务,需持久化幂等关联。
+- 建议幂等映射至少保留 24 小时,并在契约中说明保留期;超出保留期不自动重发。
+- 浏览器仅保存 key 与确认状态,不持久化 args。页面恢复后可通过下述 lookup 找回已创建任务。
+- 拟增加 `GET /api/v1/compile/submissions/{key}`:在相同身份下返回已关联任务或明确的未找到;不得返回私有请求。
+- lookup 未找到但原请求可能仍在途时,同 key 重试仍由原子幂等处理,不能改用新 key。
+
+现有 provider 的内部幂等 key 以已生成的 OV task_id 为基础,不能替代浏览器重复创建请求的幂等保护。
+
+### 8.3 任务分页与搜索
+
+为通用列表增加显式分页模式,避免破坏当前数组返回值:
+
+```http
+GET /api/v1/tasks?pagination=cursor&task_type=compile&limit=30&status=running&q=wiki
+GET /api/v1/tasks?pagination=cursor&task_type=compile&limit=30&status=running&q=wiki&cursor=opaque-token
+```
+
+```json
+{
+ "status": "ok",
+ "result": {
+ "items": [],
+ "next_cursor": null,
+ "has_more": false
+ }
+}
+```
+
+- 未传 `pagination=cursor` 时保持现有数组返回,现有 CLI 和 Tasks 调用不受影响。
+- 服务端使用 `created_at DESC, task_id DESC` 的键集分页,过滤先于分页;读取 `limit + 1` 判断 has_more。
+- cursor 是服务端生成的不可随意篡改标识,绑定排序版本、过滤条件和身份范围。过期或条件不匹配返回明确错误,前端提示重新加载。
+- `q` 只对明确的公开字段搜索,不读取私有 args;新 Compile 页固定 `task_type=compile`。
+- 从持久化存储层实现分页,不能延续“全部读入内存再截取”的做法来声称完成服务端分页。
+- ROOT 的可见范围、系统任务及普通身份隔离沿用现有权限规则;分页、搜索不得扩大可见范围。
+- 列表按 task_id 去重;状态变化导致筛选集合变化时,以刷新重新建立列表为准。
+- total 暂不返回,避免额外计数和不稳定总数产生误导。
+
+### 8.4 能力查询
+
+拟增加 `GET /api/v1/compile/capabilities`,用于当前身份的入口提示,至少返回:
+
+```json
+{
+ "status": "ok",
+ "result": {
+ "configured": true,
+ "can_create": true,
+ "reason_code": null
+ }
+}
+```
+
+configured 仅表示已配置执行后端,不承诺 Runtime 此刻健康。can_create 表示静态配置与身份允许尝试创建,不替代 URI 权限检查。不得返回 gateway token、API Key 或内部地址。网络故障作为查询失败处理,不能返回 configured=false。
+
+取消能力依旧按角色、任务状态和后端响应判断。若后续统一任务接口提供 allowed_actions,前端再迁移使用,第一版不依赖尚不存在字段。
+
+## 9. 状态、数据隔离与组件复用
+
+所有 Query key、草稿和内存交接包含当前连接及 identityScopeKey;切换身份时中止旧请求、清空可见旧数据。每个任务 ID 在同一身份下共享缓存,避免终端、详情和列表互相显示过期状态。
+
+建议模块边界:
+
+| 模块 | 职责 |
+| --- | --- |
+| Compile API 适配层 | 创建、能力、幂等恢复、分页、详情、取消 |
+| Compile 列表页 | 筛选、分页、列表状态及导航 |
+| Compile 新建页 | 草稿、字段编排、提交状态 |
+| Compile 详情页 | 状态、配置、执行记录、结果、操作 |
+| Skill 选择器 | 搜索、选择和当前内容预览 |
+| Viking 目录选择器 | 浏览、单选/多选、粘贴 URI、局部错误 |
+| Compile 表单模型 | 参数归一化、校验、公开回填、命令生成 |
+| 终端命令模块 | tokenize、compile/task 解析、回执、历史脱敏 |
+
+复用 Studio 的按钮、表单、目录浏览、任务状态和事件组件,不复制一套任务生命周期实现。业务文件保持职责单一,单文件不超过 800 行。
+
+## 10. 视觉、可访问性与文案
+
+- 沿用现有 Studio 主题、排版、间距和 Lucide 图标,不为 Compile 引入另一套设计语言。
+- 每页只有一个突出主动作:列表“新建编译”、表单“开始编译”、完成详情“打开输出目录”。
+- loading、空数据、错误和无权限必须是可区分状态。
+- 字段有真实 label、必填标识和关联错误;目录选择器支持键盘操作,弹层关闭后焦点返回触发按钮。
+- 状态变化采用适度的 aria-live 提示,不每次轮询朗读整页。
+- URI 可复制、可换行;截断只用于列表,详情始终可查看完整值。
+- 所有文案通过中英文 i18n 管理;错误原文保留在技术详情中。
+- 移动端表格退化为紧凑列表,表单保持单列;主要按钮满足可触达尺寸。
+
+## 11. 关键流程验收
+
+| 场景 | 验收标准 |
+| --- | --- |
+| 首次创建 | 空列表 → 新建 → 选 Skill、两个素材目录、输出 → 提交 → 详情,可打开结果 |
+| 查看历史 | 进入列表、筛选、加载更多、点击详情、返回,筛选和位置不丢失 |
+| 超过 200 条 | 能通过服务端游标访问更早记录,不局限于内存中的 200 条 |
+| Skill 不可用 | 清楚显示缺失或权限问题,保留其它表单值,可替换 Skill |
+| 参数错误 | 定位具体字段;非法 JSON 不发送请求;含空格指令完整保留 |
+| 双击与网络超时 | 双击只产生一个任务;超时使用相同 key 恢复到同一个 task_id |
+| 刷新页面 | 详情恢复服务端状态;公开草稿恢复;args 不泄露或静默回填占位值 |
+| 取消竞争 | 运行中取消、取消请求失败、同时完成等情况均显示服务端最终状态 |
+| 再次运行 | 回填公开参数,可修改;原任务保留,新提交产生新 task_id |
+| 执行失败 | 显示可读错误和技术详情,可调整参数再次提交,可查看已有目标 |
+| 状态断连 | 保留最后状态并提示更新时间,不将网络错误映射为任务失败 |
+| 终端互通 | 带引号、重复 from、JSON args 正确解析,提交回执可打开同一详情 |
+| 身份切换 | 列表、详情缓存和草稿不串号;旧请求不能覆盖新身份页面 |
+| 结果不完整 | result 为空、未知结构、无事件时页面仍可操作,不显示虚构统计 |
+| 历史与敏感参数 | 终端命令历史、草稿、URL、错误提示不保存原始 args |
+| 可访问性 | 键盘完成创建与查看,错误可聚焦,状态不只依赖颜色 |
+
+验证分三层:参数解析和状态模型的单元验证;真实 API 契约与分页/幂等/权限验证;浏览器端到端验证。构建或类型检查通过不能替代真实创建、取消和结果浏览的验证。
+
+## 12. 实施顺序与完成条件
+
+1. **后端契约**:完成分页与公开字段搜索、创建幂等及恢复、能力查询;保持旧任务列表返回兼容,更新 OpenAPI。
+2. **基础模块**:同步 Studio SDK,完成 API 适配层、目录/Skill 选择器、表单模型和身份隔离。
+3. **独立页面**:交付列表、新建、详情三页及公开草稿、状态刷新、结果入口。
+4. **终端接入**:完成语法解析、补全、回执、task 操作、命令复制及持久历史处理。
+5. **联动与验收**:通用 Tasks 添加 compile 类型和详情链接,跑通上述关键流程。
+
+完成标准是两个入口使用相同任务模型,用户能够创建、追踪、取消、恢复、再次运行并找到结果,历史浏览具备真实分页。接口增强未完成时可开发页面,但不能把模拟数据或本地分页作为完整交付。
+
+## 13. 源码依据
+
+- `openviking/server/routers/compile.py`:创建路由。
+- `openviking/service/compile_service.py`:请求模型、URI 校验、执行后端配置、结果快照。
+- `openviking/service/external_task_service.py`:公开请求保存、外部执行任务生命周期。
+- `openviking/server/routers/tasks.py`:任务详情、列表和取消。
+- `openviking/service/task_tracker.py`:TaskRecord 与现有列表读取逻辑。
+- `web-studio/src/components/app-shell.tsx`:导航结构。
+- `web-studio/src/routes/tasks/route.tsx`:现有通用任务页。
+- `web-studio/src/routes/tasks/-components/task-detail-sheet.tsx`:任务查询、事件展示与刷新基础。
+- `web-studio/src/routes/playground/-components/terminal-panel.tsx`:现有终端解析、历史和回执。
+- `crates/ov_cli/src/commands/compile.rs`、`crates/ov_cli/src/main.rs`:原生 CLI 参数和 task 命令。
+
+## 14. 本分支实现说明(2026-09-16)
+
+`feat/studio-compile` 实现独立列表、新建与详情页面,以及 Playground 终端的 `compile` / `task` 命令。支持 Skill 查询与内容预览、目录浏览与多来源输入、公开草稿、参数回填、取消、结果目录跳转、中英文文案和终端到表单的内存参数交接。
+
+服务端增加可选游标分页、公开字段搜索、Compile 能力查询、`Idempotency-Key` 创建去重及提交结果查询;未启用游标模式的任务列表保持数组返回。
+
+实现边界:
+
+- AGFS 当前没有任务索引查询,分页逐条扫描持久化记录,通过有界堆保留当前页,不把所有任务载入 TaskTracker。记录对象内存受页大小约束,目录枚举和读取成本仍随历史记录数量增长;不是索引级查询。
+- 游标包含身份、角色和筛选范围,并使用当前服务进程的密钥签名。服务重启后旧游标失效,刷新列表可恢复。多实例部署需要共享游标签名配置。
+- 幂等标识派生为稳定任务 ID,参数摘要保存在任务记录中但不通过公共 API 回显;同标识的并发创建与恢复在当前实例内串行。已创建请求先按身份及规范化请求摘要恢复,不重新依赖素材、Skill 或执行后端仍然可用;新请求仍执行完整资源与权限校验。保障建立在现有单 TaskTracker 写入者模型上,多写入者部署仍需存储级 CAS。
+- 幂等恢复与任务记录共用保留周期。当前 tracker 对完成/取消任务保留 24 小时,对失败任务保留 7 天;此功能不新增永久历史。页面对超过 24 小时的持久提交标识停止自动重发。分页扫描会清理当前身份目录中的过期记录,清理前在任务锁内复查状态;不将全量历史载入缓存。
+- 公开高级参数可从历史任务回填,但不保存到浏览器草稿。复制命令默认不包含高级参数;没有“一键复制私有参数”的入口。
+- 结果页面提供输出目录入口及后端原始结果;不假设不同 Runtime 已统一产物清单、进度百分比和完成时间字段。
+- 本地验证包含后端 HTTP/持久化测试、前端单元测试及浏览器可控 API 场景。真实执行服务与模型产物需要部署环境联调验证。
diff --git a/docs/en/api/01-overview.md b/docs/en/api/01-overview.md
index e54e0e28a..b3280a6f8 100644
--- a/docs/en/api/01-overview.md
+++ b/docs/en/api/01-overview.md
@@ -468,6 +468,8 @@ This catalog follows the routes actually mounted by the server. Each group headi
| Method | Path | Description |
|--------|------|-------------|
| POST | `/api/v1/compile` | Create an OV-owned Compile task |
+| GET | `/api/v1/compile/capabilities` | Check Compile availability |
+| GET | `/api/v1/compile/submissions/{key}` | Find a task by submission key |
| GET | `/api/v1/tasks/{task_id}` | Get a background task |
| POST | `/api/v1/tasks/{task_id}/cancel` | Cancel a background task |
| GET | `/api/v1/tasks` | List background tasks |
@@ -531,6 +533,8 @@ This catalog follows the routes actually mounted by the server. Each group headi
| MKCOL | `/webdav/resources`, `/webdav/resources/{resource_path}` | Create a directory |
| MOVE | `/webdav/resources`, `/webdav/resources/{resource_path}` | Move or rename a resource |
| POST | `/api/v1/compile` | Create an asynchronous Compile task |
+| GET | `/api/v1/compile/capabilities` | Check Compile availability |
+| GET | `/api/v1/compile/submissions/{key}` | Find a task by submission key |
| GET | `/bot/v1/health` | VikingBot health check |
| POST | `/bot/v1/chat` | Non-streaming VikingBot chat |
| POST | `/bot/v1/chat/stream` | Streaming VikingBot chat |
diff --git a/docs/en/api/23-agent-runtime.md b/docs/en/api/23-agent-runtime.md
index aed071815..8899ff8f3 100644
--- a/docs/en/api/23-agent-runtime.md
+++ b/docs/en/api/23-agent-runtime.md
@@ -107,6 +107,54 @@ task, err := client.Compile(
:::
+### Check Compile availability
+
+```http
+GET /api/v1/compile/capabilities
+```
+
+Uses the current authentication context and takes no request parameters. Returns `200 OK`:
+
+```json
+{
+ "status": "ok",
+ "result": {
+ "configured": true,
+ "can_create": true,
+ "reason_code": null
+ }
+}
+```
+
+| Field | Meaning |
+|-------|---------|
+| `configured` | Whether a Compile execution endpoint is configured |
+| `can_create` | Whether the current authentication context permits submission to that endpoint |
+| `reason_code` | `NOT_CONFIGURED` when no endpoint is configured; `API_KEY_REQUIRED` when a remote endpoint requires a forwardable OV API key; otherwise `null` |
+
+An unavailable configuration is reported in the result with `can_create: false`, not as an HTTP error. This checks configuration and credentials; it does not probe backend health or validate a particular Compile request.
+
+### Find a task by submission key
+
+```http
+GET /api/v1/compile/submissions/{key}
+```
+
+Use this endpoint when a task creation response was lost or timed out. Pass the same key that was sent in the optional `Idempotency-Key` header of `POST /api/v1/compile`.
+
+| Parameter | Location | Type | Required | Description |
+|-----------|----------|------|----------|-------------|
+| `key` | Path | string | Yes | 16–128 characters; only letters, digits, `:`, `.`, `_`, and `-` are allowed |
+
+```bash
+curl http://localhost:1933/api/v1/compile/submissions/studio-compile-001 \
+ -H "X-API-Key: your-key"
+```
+
+Returns `200 OK` with `status: "ok"` and the existing OV task record in `result`, using the same structure as the task creation response above. Lookup is scoped to the current account and user and does not create a task. A missing submission, including a key used only by another user, returns `404`; an invalid key returns `422`.
+
+To retry creation safely, reuse the same `Idempotency-Key` and request parameters. A key reused with different parameters returns `409`. Without this header, creation does not provide a submission key for this lookup.
+
### Get task status
A task is visible only to the principal that created it. A missing task and a task owned by another principal both return `404`.
diff --git a/docs/zh/api/01-overview.md b/docs/zh/api/01-overview.md
index 278cb22b3..758129eef 100644
--- a/docs/zh/api/01-overview.md
+++ b/docs/zh/api/01-overview.md
@@ -463,6 +463,8 @@ JSON 输出 - 错误:
| 方法 | 路径 | 说明 |
|------|------|------|
| POST | `/api/v1/compile` | 创建由 OV 托管的 Compile 任务 |
+| GET | `/api/v1/compile/capabilities` | 检查 Compile 可用性 |
+| GET | `/api/v1/compile/submissions/{key}` | 按提交键查询任务 |
| GET | `/api/v1/tasks/{task_id}` | 获取后台任务 |
| POST | `/api/v1/tasks/{task_id}/cancel` | 取消后台任务 |
| GET | `/api/v1/tasks` | 列出后台任务 |
@@ -526,6 +528,8 @@ JSON 输出 - 错误:
| MKCOL | `/webdav/resources`、`/webdav/resources/{resource_path}` | 创建目录 |
| MOVE | `/webdav/resources`、`/webdav/resources/{resource_path}` | 移动或重命名资源 |
| POST | `/api/v1/compile` | 创建异步 Compile 任务 |
+| GET | `/api/v1/compile/capabilities` | 检查 Compile 可用性 |
+| GET | `/api/v1/compile/submissions/{key}` | 按提交键查询任务 |
| GET | `/bot/v1/health` | VikingBot 健康检查 |
| POST | `/bot/v1/chat` | VikingBot 非流式对话 |
| POST | `/bot/v1/chat/stream` | VikingBot 流式对话 |
diff --git a/docs/zh/api/23-agent-runtime.md b/docs/zh/api/23-agent-runtime.md
index 14b4b82a9..3dad55bb8 100644
--- a/docs/zh/api/23-agent-runtime.md
+++ b/docs/zh/api/23-agent-runtime.md
@@ -107,6 +107,54 @@ task, err := client.Compile(
:::
+### 检查 Compile 可用性
+
+```http
+GET /api/v1/compile/capabilities
+```
+
+使用当前认证上下文,无需请求参数。返回 `200 OK`:
+
+```json
+{
+ "status": "ok",
+ "result": {
+ "configured": true,
+ "can_create": true,
+ "reason_code": null
+ }
+}
+```
+
+| 字段 | 含义 |
+|------|------|
+| `configured` | 是否已配置 Compile 执行端点 |
+| `can_create` | 当前认证上下文是否允许向该端点提交任务 |
+| `reason_code` | 未配置端点时为 `NOT_CONFIGURED`;远程端点需要可转发的 OV API Key 时为 `API_KEY_REQUIRED`;其他情况为 `null` |
+
+配置不可用时,在结果中返回 `can_create: false`,不会因此返回 HTTP 错误。此接口仅检查配置和凭证,不探测执行后端的健康状态,也不校验具体 Compile 请求。
+
+### 按提交键查询任务
+
+```http
+GET /api/v1/compile/submissions/{key}
+```
+
+创建任务的响应丢失或超时时,可通过此接口找回任务。传入的键必须与 `POST /api/v1/compile` 请求中可选的 `Idempotency-Key` 请求头一致。
+
+| 参数 | 位置 | 类型 | 必填 | 说明 |
+|------|------|------|------|------|
+| `key` | 路径 | string | 是 | 长度为 16–128 个字符;仅允许字母、数字、`:`、`.`、`_` 和 `-` |
+
+```bash
+curl http://localhost:1933/api/v1/compile/submissions/studio-compile-001 \
+ -H "X-API-Key: your-key"
+```
+
+返回 `200 OK`,其中 `status` 为 `"ok"`,`result` 为已有的 OV 任务记录,结构与上方创建任务响应一致。查询范围限定为当前账号和用户,不会创建任务。提交不存在(包括键仅被其他用户使用)时返回 `404`;键格式不合法时返回 `422`。
+
+需要安全重试创建请求时,应复用相同的 `Idempotency-Key` 和请求参数。使用同一键提交不同参数会返回 `409`。未传入该请求头的创建请求,不提供用于此查询的提交键。
+
### 查询任务
任务仅对创建它的 principal 可见;任务不存在或属于其他 principal 时均返回 `404`。
diff --git a/openviking/server/routers/compile.py b/openviking/server/routers/compile.py
index 51ab05dad..ada62004c 100644
--- a/openviking/server/routers/compile.py
+++ b/openviking/server/routers/compile.py
@@ -2,7 +2,7 @@
# SPDX-License-Identifier: AGPL-3.0
"""Compile task creation API."""
-from fastapi import APIRouter, Depends, status
+from fastapi import APIRouter, Depends, Header, Path, status
from openviking.server.auth import get_request_context
from openviking.server.dependencies import get_service
@@ -17,10 +17,41 @@ router = APIRouter(prefix="/api/v1", tags=["compile"])
async def create_compile(
body: CompileRequest,
ctx: RequestContext = Depends(get_request_context),
+ idempotency_key: str | None = Header(
+ None, min_length=16, max_length=128, pattern=r"^[A-Za-z0-9:._-]+$"
+ ),
):
connection = {"api_key": ctx.api_key} if ctx.api_key else {}
- task = await get_service().compile.create(body, connection=connection, ctx=ctx)
+ task = await get_service().compile.create(
+ body,
+ connection=connection,
+ ctx=ctx,
+ **({"idempotency_key": idempotency_key} if idempotency_key else {}),
+ )
return Response(status="ok", result=task.to_dict())
__all__ = ["router"]
+
+
[email protected]("/compile/capabilities")
+async def compile_capabilities(ctx: RequestContext = Depends(get_request_context)):
+ return Response(status="ok", result=get_service().compile.capabilities(ctx))
+
+
[email protected]("/compile/submissions/{key}")
+async def get_submission(
+ key: str = Path(..., min_length=16, max_length=128, pattern=r"^[A-Za-z0-9:._-]+$"),
+ ctx: RequestContext = Depends(get_request_context),
+):
+ from openviking.service.external_task_service import submission_task_id
+ from openviking.service.task_tracker import get_task_tracker
+ from openviking_cli.exceptions import NotFoundError
+
+ task_id = submission_task_id(ctx, "compile", "cmp_", key)
+ task = await get_task_tracker().get(
+ task_id, account_id=ctx.account_id, user_id=ctx.user.user_id
+ )
+ if task is None:
+ raise NotFoundError(key, "submission")
+ return Response(status="ok", result=task.to_dict())
diff --git a/openviking/server/routers/tasks.py b/openviking/server/routers/tasks.py
index cbcfb078a..b40c82989 100644
--- a/openviking/server/routers/tasks.py
+++ b/openviking/server/routers/tasks.py
@@ -35,6 +35,8 @@ async def get_task(
tracker = get_task_tracker()
if _ctx.role == Role.ROOT:
task = await tracker.get(task_id)
+ if task is None:
+ task = await tracker.get(task_id, account_id=_ctx.account_id, user_id=_ctx.user.user_id)
if task is None:
task = await tracker.get(
task_id,
@@ -91,11 +93,52 @@ async def list_tasks(
),
resource_id: Optional[str] = Query(None, description="Filter by resource ID (e.g. session_id)"),
include_internal: bool = Query(False, description="Include internal Connector child tasks"),
- limit: int = Query(50, le=200, description="Max results"),
+ limit: int = Query(50, ge=1, le=200, description="Max results"),
+ pagination: Optional[str] = Query(None, pattern="^cursor$"),
+ cursor: Optional[str] = Query(None, max_length=2048),
+ q: Optional[str] = Query(None, max_length=200),
_ctx: RequestContext = Depends(get_request_context),
):
"""List background tasks with optional filters."""
tracker = get_task_tracker()
+ if pagination == "cursor":
+ from openviking.service.task_pagination import decode_cursor, encode_cursor, page_scope
+
+ # ROOT retains the legacy system + cached visibility and its own
+ # persisted tasks, including submissions restored after restart.
+ account = SYSTEM_TASK_ACCOUNT_ID if _ctx.role == Role.ROOT else _ctx.account_id
+ user = SYSTEM_TASK_USER_ID if _ctx.role == Role.ROOT else _ctx.user.user_id
+ filters = {
+ "task_type": task_type,
+ "status": status,
+ "resource_id": resource_id,
+ "include_internal": include_internal,
+ "q": q,
+ }
+ scope = page_scope(
+ account=_ctx.account_id, user=_ctx.user.user_id, role=str(_ctx.role), **filters
+ )
+ tasks = await tracker.list_page(
+ account_id=account,
+ user_id=user,
+ limit=limit + 1,
+ before=decode_cursor(cursor, scope),
+ include_cached=_ctx.role == Role.ROOT,
+ additional_owner=(_ctx.account_id, _ctx.user.user_id)
+ if _ctx.role == Role.ROOT
+ else None,
+ **filters,
+ )
+ more = len(tasks) > limit
+ items = [t.to_dict() for t in tasks[:limit]]
+ return Response(
+ status="ok",
+ result={
+ "items": items,
+ "has_more": more,
+ "next_cursor": encode_cursor(items[-1], scope) if more else None,
+ },
+ )
if _ctx.role == Role.ROOT:
system_tasks = await tracker.list_tasks(
task_type=task_type,
diff --git a/openviking/service/compile_service.py b/openviking/service/compile_service.py
index 08462b6b4..c9f21dc5a 100644
--- a/openviking/service/compile_service.py
+++ b/openviking/service/compile_service.py
@@ -292,13 +292,34 @@ class CompileService:
def _client(self) -> CompileAPIClient:
return CompileAPIClient(self._endpoint())
+ def capabilities(self, ctx: RequestContext) -> dict[str, Any]:
+ try:
+ endpoint = self._endpoint()
+ except UnavailableError:
+ return {"configured": False, "can_create": False, "reason_code": "NOT_CONFIGURED"}
+ allowed = endpoint.local or bool(ctx.api_key)
+ return {
+ "configured": True,
+ "can_create": allowed,
+ "reason_code": None if allowed else "API_KEY_REQUIRED",
+ }
+
async def create(
self,
request: CompileRequest,
*,
connection: Mapping[str, Any],
ctx: RequestContext,
+ idempotency_key: str | None = None,
) -> TaskRecord:
+ request = self._normalize_request_uris(request, ctx)
+ if idempotency_key:
+ payload, private_payload = self._split_payload(request)
+ existing = await self._tasks.recover_submission(
+ self.task_type, payload, private_payload, ctx, idempotency_key
+ )
+ if existing is not None:
+ return existing
endpoint = self._endpoint()
if not endpoint.local and not str(connection.get("api_key") or "").strip():
raise UnauthenticatedError("Compile requires a forwardable OpenViking API key")
@@ -311,6 +332,7 @@ class CompileService:
private_payload=private_payload,
connection=connection,
ctx=ctx,
+ **({"idempotency_key": idempotency_key} if idempotency_key else {}),
)
async def submit(
@@ -384,62 +406,53 @@ class CompileService:
**(private_args if isinstance(private_args, dict) else {}),
}
- async def _normalize_request(
- self,
- request: CompileRequest,
- ctx: RequestContext,
+ def _normalize_request_uris(
+ self, request: CompileRequest, ctx: RequestContext
) -> CompileRequest:
- sources: list[str] = []
- for index, source in enumerate(request.from_):
- uri = validate_request_viking_uri(
- resolve_path_variables(source),
- ctx,
- field_name=f"from[{index}]",
- ).rstrip("/")
- stat = await self._fs.stat(uri, ctx)
- if not stat.get("isDir"):
- raise InvalidArgumentError(f"Compile source must be a directory: {uri}")
- canonical = str(stat.get("uri") or uri).rstrip("/")
- if canonical not in sources:
- sources.append(canonical)
-
- skill = request.skill
- if skill.endswith("/SKILL.md"):
- skill = skill[: -len("/SKILL.md")]
+ """Normalize identity-bound names without requiring live resources."""
+ sources = list(
+ dict.fromkeys(
+ validate_request_viking_uri(
+ resolve_path_variables(source), ctx, field_name=f"from[{index}]"
+ ).rstrip("/")
+ for index, source in enumerate(request.from_)
+ )
+ )
+ skill = request.skill.removesuffix("/SKILL.md")
skill = validate_request_viking_uri(
- resolve_path_variables(skill),
- ctx,
- field_name="skill",
+ resolve_path_variables(skill), ctx, field_name="skill"
).rstrip("/")
if not classify_uri(skill).is_skill_root:
raise InvalidArgumentError("skill must resolve to a Skill directory or SKILL.md")
- skill_stat = await self._fs.stat(skill, ctx)
+ target = validate_request_viking_uri(
+ resolve_path_variables(request.to), ctx, field_name="to"
+ ).rstrip("/")
+ self._validate_target(target)
+ return request.model_copy(update={"from_": sources, "to": target, "skill": skill})
+
+ async def _normalize_request(
+ self, request: CompileRequest, ctx: RequestContext
+ ) -> CompileRequest:
+ request = self._normalize_request_uris(request, ctx)
+ for uri in request.from_:
+ stat = await self._fs.stat(uri, ctx)
+ if not stat.get("isDir"):
+ raise InvalidArgumentError(f"Compile source must be a directory: {uri}")
+ skill_stat = await self._fs.stat(request.skill, ctx)
if not skill_stat.get("isDir"):
raise InvalidArgumentError("skill must resolve to a Skill directory or SKILL.md")
- skill = str(skill_stat.get("uri") or skill).rstrip("/")
- skill_file = await self._fs.stat(f"{skill}/SKILL.md", ctx)
+ skill_file = await self._fs.stat(f"{request.skill}/SKILL.md", ctx)
if skill_file.get("isDir"):
raise InvalidArgumentError("Skill directory must contain a SKILL.md file")
-
- target = validate_request_viking_uri(
- resolve_path_variables(request.to),
- ctx,
- field_name="to",
- ).rstrip("/")
- self._validate_target(target)
- await self._fs.ensure_write_access(target, ctx)
+ await self._fs.ensure_write_access(request.to, ctx)
try:
- target_stat = await self._fs.stat(target, ctx)
+ target_stat = await self._fs.stat(request.to, ctx)
except NotFoundError:
pass
else:
if not target_stat.get("isDir"):
raise InvalidArgumentError("Compile target must be a directory")
- target = str(target_stat.get("uri") or target).rstrip("/")
-
- return request.model_copy(
- update={"from_": sources, "to": target, "skill": skill},
- )
+ return request
@staticmethod
def _validate_target(target: str) -> None:
diff --git a/openviking/service/external_task_service.py b/openviking/service/external_task_service.py
index f77a11f27..63708d390 100644
--- a/openviking/service/external_task_service.py
+++ b/openviking/service/external_task_service.py
@@ -5,14 +5,21 @@
from __future__ import annotations
import asyncio
+import hashlib
+import json
from dataclasses import dataclass
from typing import Any, Awaitable, Callable, Iterable, Mapping, Protocol
from uuid import uuid4
from openviking.server.identity import RequestContext
from openviking.service.task_tracker import TaskRecord, TaskStatus, get_task_tracker
-from openviking.service.task_tracker_concurrency import run_to_completion
+from openviking.service.task_tracker_concurrency import (
+ KeyedAsyncLockPool,
+ OwnerLoopDispatcher,
+ run_to_completion,
+)
from openviking.storage.queuefs import QueueManager, get_queue_manager
+from openviking_cli.exceptions import ConflictError
from openviking_cli.utils.logger import get_logger
logger = get_logger(__name__)
@@ -89,6 +96,8 @@ class ExternalTaskService:
# tasks submitted before target serialization was enabled.
self._owners: dict[tuple[str | None, str, str], set[str]] = {}
self._executing: set[str] = set()
+ self._submission_locks = KeyedAsyncLockPool[str]()
+ self._submission_dispatcher = OwnerLoopDispatcher()
def register(self, provider: ExternalTaskProvider) -> None:
if provider.task_type in self._providers:
@@ -144,21 +153,75 @@ class ExternalTaskService:
private_payload: Mapping[str, Any] | None = None,
connection: Mapping[str, Any],
ctx: RequestContext,
+ idempotency_key: str | None = None,
+ ) -> TaskRecord:
+ async def create_task():
+ return await self._create(
+ task_type,
+ resource_id=resource_id,
+ payload=payload,
+ private_payload=private_payload,
+ connection=connection,
+ ctx=ctx,
+ idempotency_key=idempotency_key,
+ )
+
+ if not idempotency_key:
+ return await create_task()
+ key = submission_task_id(ctx, task_type, "", idempotency_key)
+
+ async def serialized():
+ async with self._submission_locks.acquire(key):
+ return await run_to_completion(create_task)
+
+ return await self._submission_dispatcher.run(serialized)
+
+ async def _create(
+ self,
+ task_type: str,
+ *,
+ resource_id: str | None,
+ payload: Mapping[str, Any],
+ private_payload: Mapping[str, Any] | None = None,
+ connection: Mapping[str, Any],
+ ctx: RequestContext,
+ idempotency_key: str | None = None,
) -> TaskRecord:
provider = self._provider(task_type)
tracker = get_task_tracker()
+ request_hash = submission_request_hash(payload, private_payload)
+ token = uuid4().hex
+ task_id = (
+ submission_task_id(ctx, task_type, provider.task_id_prefix, idempotency_key)
+ if idempotency_key
+ else f"{provider.task_id_prefix}{token}"
+ )
task = await tracker.create(
task_type,
resource_id=resource_id,
account_id=ctx.account_id,
user_id=ctx.user.user_id,
- task_id=f"{provider.task_id_prefix}{uuid4().hex}",
- meta={"request": dict(payload)},
+ task_id=task_id,
+ meta={
+ "request": dict(payload),
+ **(
+ {"submission_hash": request_hash, "submission_token": token}
+ if idempotency_key
+ else {}
+ ),
+ },
auth={
"openviking_connection": dict(connection),
"external_request_private": dict(private_payload or {}),
},
)
+ if idempotency_key and task.meta.get("submission_hash") != request_hash:
+ raise ConflictError("Idempotency-Key was already used with different parameters")
+ if idempotency_key and task.meta.get("submission_token") != token:
+ # Recover a creation interrupted before queue delivery. Duplicate
+ # deliveries are safe: execute claims each task before submitting.
+ await self._resume_submission(task, ctx)
+ return task
enqueued = False
try:
await tracker.update_stage(
@@ -194,6 +257,47 @@ class ExternalTaskService:
raise
return task
+ async def recover_submission(
+ self,
+ task_type: str,
+ payload: Mapping[str, Any],
+ private_payload: Mapping[str, Any],
+ ctx: RequestContext,
+ key: str,
+ ) -> TaskRecord | None:
+ async def recover():
+ provider = self._provider(task_type)
+ task = await get_task_tracker().get(
+ submission_task_id(ctx, task_type, provider.task_id_prefix, key),
+ account_id=ctx.account_id,
+ user_id=ctx.user.user_id,
+ )
+ if task is None:
+ return None
+ if task.meta.get("submission_hash") != submission_request_hash(
+ payload, private_payload
+ ):
+ raise ConflictError("Idempotency-Key was already used with different parameters")
+ await self._resume_submission(task, ctx)
+ return task
+
+ async def serialized():
+ async with self._submission_locks.acquire(submission_task_id(ctx, task_type, "", key)):
+ return await run_to_completion(recover)
+
+ return await self._submission_dispatcher.run(serialized)
+
+ async def _resume_submission(self, task: TaskRecord, ctx: RequestContext) -> None:
+ if task.status == TaskStatus.PENDING:
+ await get_queue_manager().enqueue(
+ QueueManager.EXTERNAL_TASK,
+ {
+ "task_id": task.task_id,
+ "account_id": ctx.account_id,
+ "user_id": ctx.user.user_id,
+ },
+ )
+
async def execute(self, task_id: str, account_id: str, user_id: str) -> bool:
"""Return False when this delivery must rotate behind other target work."""
tracker = get_task_tracker()
@@ -530,3 +634,21 @@ __all__ = [
"ExternalTaskService",
"ExternalTaskSnapshot",
]
+
+
+def submission_task_id(ctx: RequestContext, task_type: str, prefix: str, key: str) -> str:
+ scope = json.dumps([ctx.account_id, ctx.user.user_id, task_type, key])
+ return prefix + hashlib.sha256(scope.encode()).hexdigest()
+
+
+def submission_request_hash(
+ payload: Mapping[str, Any], private_payload: Mapping[str, Any] | None
+) -> str:
+ return hashlib.sha256(
+ json.dumps(
+ {"payload": dict(payload), "private": dict(private_payload or {})},
+ sort_keys=True,
+ ensure_ascii=False,
+ separators=(",", ":"),
+ ).encode()
+ ).hexdigest()
diff --git a/openviking/service/task_pagination.py b/openviking/service/task_pagination.py
new file mode 100644
index 000000000..5afc36325
--- /dev/null
+++ b/openviking/service/task_pagination.py
@@ -0,0 +1,75 @@
+# Copyright (c) 2026 Beijing Volcano Engine Technology Co., Ltd.
+# SPDX-License-Identifier: AGPL-3.0
+"""Bounded-memory task pagination over the durable task store."""
+
+from __future__ import annotations
+
+import base64
+import hashlib
+import hmac
+import json
+import math
+import secrets
+from typing import Any
+
+from openviking_cli.exceptions import InvalidArgumentError
+
+_CURSOR_SECRET = secrets.token_bytes(32)
+
+
+def page_scope(**filters: Any) -> str:
+ return hashlib.sha256(json.dumps(filters, sort_keys=True).encode()).hexdigest()
+
+
+def decode_cursor(cursor: str | None, scope: str) -> tuple[float, str] | None:
+ if not cursor:
+ return None
+ try:
+ payload, signature = cursor.rsplit(".", 1)
+ expected = hmac.new(_CURSOR_SECRET, payload.encode(), hashlib.sha256).hexdigest()
+ if not hmac.compare_digest(signature, expected):
+ raise ValueError("invalid signature")
+ data = json.loads(base64.urlsafe_b64decode(payload.encode()))
+ if data["scope"] != scope:
+ raise ValueError("scope mismatch")
+ timestamp = float(data["time"])
+ if not math.isfinite(timestamp):
+ raise ValueError("invalid timestamp")
+ return timestamp, str(data["id"])
+ except (ValueError, KeyError, TypeError) as exc:
+ raise InvalidArgumentError("Invalid task cursor; reload the list") from exc
+
+
+def encode_cursor(task: dict, scope: str) -> str:
+ payload = base64.urlsafe_b64encode(
+ json.dumps({"scope": scope, "time": task["created_at"], "id": task["task_id"]}).encode()
+ ).decode()
+ return payload + "." + hmac.new(_CURSOR_SECRET, payload.encode(), hashlib.sha256).hexdigest()
+
+
+def matches(
+ task: dict,
+ *,
+ task_type: str | None,
+ status: str | None,
+ resource_id: str | None,
+ include_internal: bool,
+ q: str | None,
+) -> bool:
+ if task_type and task.get("task_type") != task_type:
+ return False
+ if status and task.get("status") != status:
+ return False
+ if resource_id and task.get("resource_id") != resource_id:
+ return False
+ meta = task.get("meta") or {}
+ if not include_internal and meta.get("internal"):
+ return False
+ request = meta.get("request") or {}
+ fields = [
+ task.get("task_id", ""),
+ request.get("skill", ""),
+ request.get("to", ""),
+ *(request.get("from") or []),
+ ]
+ return not q or q.casefold() in " ".join(str(v) for v in fields).casefold()
diff --git a/openviking/service/task_store.py b/openviking/service/task_store.py
index ed4381992..7920d9139 100644
--- a/openviking/service/task_store.py
+++ b/openviking/service/task_store.py
@@ -4,12 +4,15 @@
from __future__ import annotations
+import heapq
import json
+from collections.abc import Awaitable, Callable
from copy import deepcopy
from typing import Any, Dict, List, Optional, Protocol
from openviking.pyagfs import AsyncAGFSClient
from openviking.pyagfs.exceptions import AGFSAlreadyExistsError, AGFSNotFoundError
+from openviking.service.task_tracker_concurrency import StoreIOLimiter, run_to_completion
SYSTEM_TASK_ACCOUNT_ID = "_system"
SYSTEM_TASK_USER_ID = "root"
@@ -32,6 +35,18 @@ class TaskStore(Protocol):
self, account_id: str, *, user_id: Optional[str] = None
) -> List[Dict[str, Any]]: ...
+ async def list_page(
+ self,
+ account_id: str,
+ *,
+ user_id: str,
+ limit: int,
+ before: tuple[float, str] | None = None,
+ prune_expired: Callable[[Dict[str, Any]], Awaitable[bool]] | None = None,
+ io_limiter: StoreIOLimiter | None = None,
+ **filters: Any,
+ ) -> List[Dict[str, Any]]: ...
+
async def delete(
self, task_id: str, *, account_id: str, user_id: Optional[str] = None
) -> None: ...
@@ -98,6 +113,63 @@ class PersistentTaskStore:
tasks.append(json.loads(_decode_bytes(raw)))
return tasks
+ async def list_page(
+ self,
+ account_id: str,
+ *,
+ user_id: str,
+ limit: int,
+ before: tuple[float, str] | None = None,
+ prune_expired: Callable[[Dict[str, Any]], Awaitable[bool]] | None = None,
+ io_limiter: StoreIOLimiter | None = None,
+ **filters: Any,
+ ) -> List[Dict[str, Any]]:
+ """Scan durable records, retaining only the requested page in memory.
+
+ AGFS has no indexed query API. This bounds record memory, but still
+ performs O(n) reads; it deliberately does not load all tasks into the tracker.
+ """
+ from openviking.service.task_pagination import matches
+
+ async def read(operation: str, factory: Callable[[], Awaitable[Any]]) -> Any:
+ if io_limiter is None:
+ return await factory()
+ return await io_limiter.run(operation, lambda: run_to_completion(factory))
+
+ directory = self._task_dir(account_id, user_id)
+ try:
+ entries = await read("list_page_ls", lambda: self._agfs.ls(directory))
+ except (AGFSNotFoundError, FileNotFoundError):
+ return []
+ heap: list = []
+ for entry in entries:
+ path = entry.get("path") or f"{directory}/{entry.get('name', '')}"
+ if not path.endswith(".json"):
+ continue
+ try:
+ task = json.loads(
+ _decode_bytes(
+ await read("list_page_read", lambda path=path: self._agfs.read(path))
+ )
+ )
+ except (AGFSNotFoundError, FileNotFoundError):
+ continue
+ if task.get("account_id") != account_id or task.get("user_id") != user_id:
+ continue
+ if prune_expired is not None and await prune_expired(task):
+ continue
+ key = (float(task["created_at"]), str(task["task_id"]))
+ if before is not None and key >= before:
+ continue
+ if not matches(task, **filters):
+ continue
+ item = (*key, task)
+ if len(heap) < limit:
+ heapq.heappush(heap, item)
+ elif key > heap[0][:2]:
+ heapq.heapreplace(heap, item)
+ return [item[2] for item in sorted(heap, reverse=True)]
+
async def delete(self, task_id: str, *, account_id: str, user_id: Optional[str] = None) -> None:
"""Delete a task record, succeeding if it has already been removed."""
if not user_id:
diff --git a/openviking/service/task_tracker.py b/openviking/service/task_tracker.py
index 9e23e9693..f5713b701 100644
--- a/openviking/service/task_tracker.py
+++ b/openviking/service/task_tracker.py
@@ -94,6 +94,9 @@ class TaskRecord:
def to_dict(self, *, include_events: bool = False) -> Dict[str, Any]:
"""Serialize for JSON response."""
+ public_meta = deepcopy(self.meta)
+ public_meta.pop("submission_hash", None)
+ public_meta.pop("submission_token", None)
return {
**({"execution_events": deepcopy(self.execution_events)} if include_events else {}),
"task_id": self.task_id,
@@ -102,7 +105,7 @@ class TaskRecord:
"created_at": self.created_at,
"updated_at": self.updated_at,
"resource_id": self.resource_id,
- "meta": _sanitize_task_result(deepcopy(self.meta)),
+ "meta": _sanitize_task_result(public_meta),
"stage": self.stage,
"result": _sanitize_task_result(deepcopy(self.result)),
"error": self.error,
@@ -1062,6 +1065,83 @@ class TaskTracker:
return None
return self._copy(task)
+ async def _prune_persisted_expired(self, payload: Dict[str, Any]) -> bool:
+ """Prune cold records under the same lock and I/O budget as mutations."""
+ candidate = self._record_from_payload(payload)
+ now = time.time()
+ if not self._is_expired(candidate, now):
+ return False
+ async with self._task_locks.acquire(candidate.task_id):
+ # The scan may race with a lifecycle write. Re-read under the same
+ # lock used by mutations before removing any durable state.
+ current = await self._store_io.run(
+ "get",
+ lambda: self._store.get(
+ candidate.task_id, account_id=candidate.account_id, user_id=candidate.user_id
+ ),
+ )
+ if current is None:
+ return True
+ task = self._record_from_payload(current)
+ if not self._is_expired(task, now) or self._work_index.has_work(task.task_id):
+ payload.clear()
+ payload.update(current)
+ return False
+ await self._store_io.run(
+ "delete",
+ lambda: run_to_completion(
+ lambda: self._store.delete(
+ task.task_id, account_id=task.account_id, user_id=task.user_id
+ )
+ ),
+ )
+ with self._lock:
+ self._tasks.pop(task.task_id, None)
+ return True
+
+ async def list_page(
+ self,
+ *,
+ account_id: str,
+ user_id: str,
+ limit: int,
+ before: tuple[float, str] | None = None,
+ include_cached: bool = False,
+ additional_owner: tuple[str, str] | None = None,
+ **filters: Any,
+ ) -> list[TaskRecord]:
+ from openviking.service.task_pagination import matches
+
+ async def read():
+ owners = {(account_id, user_id)}
+ if additional_owner:
+ owners.add(additional_owner)
+ records = []
+ for account, user in owners:
+ page = await self._store.list_page(
+ account,
+ user_id=user,
+ limit=limit,
+ before=before,
+ prune_expired=self._prune_persisted_expired,
+ io_limiter=self._store_io,
+ **filters,
+ )
+ records.extend(self._record_from_payload(record) for record in page)
+ if include_cached:
+ records.extend(self._copy(t) for t in self._cache_snapshot())
+ visible = {
+ t.task_id: t
+ for t in records
+ if (before is None or (t.created_at, t.task_id) < before)
+ and matches(t.to_dict(), **filters)
+ }
+ return sorted(visible.values(), key=lambda t: (t.created_at, t.task_id), reverse=True)[
+ :limit
+ ]
+
+ return await self._dispatcher.run(read)
+
async def list_tasks(
self,
task_type: Optional[str] = None,
diff --git a/tests/server/test_compile_studio.py b/tests/server/test_compile_studio.py
new file mode 100644
index 000000000..6ae526b27
--- /dev/null
+++ b/tests/server/test_compile_studio.py
@@ -0,0 +1,285 @@
+"""Studio task pagination and submission retry contracts."""
+
+import asyncio
+import time
+from types import SimpleNamespace
+from unittest.mock import AsyncMock
+
+import pytest
+
+from openviking.server.identity import RequestContext, Role
+from openviking.service.external_task_service import ExternalTaskService
+from openviking.service.task_pagination import decode_cursor, encode_cursor, page_scope
+from openviking.service.task_store import PersistentTaskStore
+from openviking.service.task_tracker import TaskStatus, TaskTracker
+from openviking_cli.exceptions import ConflictError, InvalidArgumentError
+from openviking_cli.session.user_id import UserIdentifier
+from tests.test_task_tracker import _FakeAgfs
+
+
+async def test_page_reads_past_200_and_isolates_owner():
+ store = PersistentTaskStore(_FakeAgfs())
+ tracker = TaskTracker(store)
+ owner = {"account_id": "acme", "user_id": "alice"}
+ for index in range(205):
+ record = await tracker.create(
+ "compile",
+ task_id=f"cmp_{index:03}",
+ meta={"request": {"to": "viking://resources/wiki"}},
+ **owner,
+ )
+ record.created_at = 100.0
+ await store.update(record)
+ await tracker.create("compile", task_id="foreign", account_id="acme", user_id="bob")
+ # Empty cache: pagination must read durable records without repopulating all tasks.
+ tracker = TaskTracker(store)
+ filters = {
+ "task_type": "compile",
+ "status": None,
+ "resource_id": None,
+ "include_internal": False,
+ "q": "wiki",
+ }
+ seen = []
+ before = None
+ while True:
+ page = await tracker.list_page(**owner, limit=30, before=before, **filters)
+ if not page:
+ break
+ seen.extend(task.task_id for task in page)
+ before = (page[-1].created_at, page[-1].task_id)
+ assert len(seen) == len(set(seen)) == 205
+ assert seen[0] == "cmp_204"
+ assert "foreign" not in seen
+ assert not tracker._tasks
+
+
+def test_cursor_is_bound_to_identity_and_filters():
+ scope = page_scope(account="a", user="u", status="running")
+ cursor = encode_cursor({"created_at": 123.4, "task_id": "cmp_a"}, scope)
+ assert decode_cursor(cursor, scope) == (123.4, "cmp_a")
+ with pytest.raises(InvalidArgumentError):
+ decode_cursor(cursor, page_scope(account="a", user="other", status="running"))
+ with pytest.raises(InvalidArgumentError):
+ decode_cursor("broken", scope)
+
+
+async def test_concurrent_submission_retry_and_restart(monkeypatch):
+ import openviking.service.external_task_service as module
+
+ store = PersistentTaskStore(_FakeAgfs())
+ tracker = TaskTracker(store)
+ monkeypatch.setattr(module, "get_task_tracker", lambda: tracker)
+ monkeypatch.setattr(module, "get_queue_manager", lambda: SimpleNamespace(enqueue=AsyncMock()))
+ service = ExternalTaskService()
+ service.register(SimpleNamespace(task_type="compile", task_id_prefix="cmp_"))
+ ctx = RequestContext(user=UserIdentifier("acme", "alice"), role=Role.USER)
+ params = {
+ "resource_id": None,
+ "payload": {"from": ["viking://resources/a"], "to": "viking://resources/b"},
+ "connection": {},
+ "ctx": ctx,
+ "idempotency_key": "test-submission-123",
+ }
+ results = await asyncio.gather(*(service.create("compile", **params) for _ in range(5)))
+ assert len({t.task_id for t in results}) == 1
+ tracker = TaskTracker(store)
+ again = await service.create("compile", **params)
+ assert again.task_id == results[0].task_id
+ with pytest.raises(ConflictError):
+ await service.create("compile", **{**params, "payload": {"to": "different"}})
+ other = RequestContext(user=UserIdentifier("acme", "bob"), role=Role.USER)
+ assert (await service.create("compile", **{**params, "ctx": other})).task_id != again.task_id
+
+
+async def test_http_contract_preserves_legacy_list_and_retries(monkeypatch):
+ import httpx
+ from fastapi import FastAPI
+ from fastapi.responses import JSONResponse
+
+ import openviking.server.routers.compile as compile_router
+ import openviking.server.routers.tasks as task_router
+ import openviking.service.external_task_service as external
+ import openviking.service.task_tracker as tracker_module
+ from openviking.server.auth import get_request_context
+ from openviking.service.compile_service import CompileService
+ from openviking_cli.exceptions import OpenVikingError
+ from openviking_cli.utils.config.open_viking_config import CompileApiConfig
+
+ store = PersistentTaskStore(_FakeAgfs())
+ tracker = TaskTracker(store)
+ monkeypatch.setattr(external, "get_task_tracker", lambda: tracker)
+ monkeypatch.setattr(task_router, "get_task_tracker", lambda: tracker)
+ monkeypatch.setattr(tracker_module, "get_task_tracker", lambda: tracker)
+ monkeypatch.setattr(external, "get_queue_manager", lambda: SimpleNamespace(enqueue=AsyncMock()))
+ tasks = ExternalTaskService()
+ fs = SimpleNamespace(
+ stat=AsyncMock(
+ side_effect=lambda uri, ctx: {"uri": uri, "isDir": not uri.endswith("SKILL.md")}
+ ),
+ ensure_write_access=AsyncMock(),
+ )
+ compile_service = CompileService(CompileApiConfig(), tasks, fs)
+ compile_service.configure_local_backend("http://localhost:1", "")
+ tasks.register(compile_service)
+ monkeypatch.setattr(
+ compile_router, "get_service", lambda: SimpleNamespace(compile=compile_service)
+ )
+ ctx = RequestContext(user=UserIdentifier("acme", "alice"), role=Role.USER)
+ app = FastAPI()
+ app.include_router(compile_router.router)
+ app.include_router(task_router.router)
+ app.dependency_overrides[get_request_context] = lambda: ctx
+
+ @app.exception_handler(OpenVikingError)
+ async def on_error(request, error):
+ return JSONResponse(
+ status_code=409 if error.code == "CONFLICT" else 400, content={"error": error.code}
+ )
+
+ payload = {
+ "from": ["viking://resources/source"],
+ "to": "viking://resources/wiki",
+ "skill": "viking://agent/skills/wiki",
+ "args": {"api_key": "synthetic-private-key", "mode": "summary"},
+ }
+ headers = {"Idempotency-Key": "http-retry-key-123"}
+ async with httpx.AsyncClient(
+ transport=httpx.ASGITransport(app=app), base_url="http://test"
+ ) as client:
+ first = await client.post("/api/v1/compile", json=payload, headers=headers)
+ assert first.status_code == 202, first.text
+ second = await client.post("/api/v1/compile", json=payload, headers=headers)
+ task_id = first.json()["result"]["task_id"]
+ assert second.json()["result"]["task_id"] == task_id
+ recovery = await client.get("/api/v1/compile/submissions/http-retry-key-123")
+ assert recovery.json()["result"]["task_id"] == task_id
+ assert isinstance((await client.get("/api/v1/tasks")).json()["result"], list)
+ paged = await client.get(
+ "/api/v1/tasks", params={"pagination": "cursor", "task_type": "compile"}
+ )
+ assert paged.json()["result"]["items"][0]["task_id"] == task_id
+ assert (await client.get("/api/v1/tasks", params={"limit": 0})).status_code == 422
+ conflict = await client.post(
+ "/api/v1/compile", json={**payload, "instruction": "changed"}, headers=headers
+ )
+ assert conflict.status_code == 409
+ stopped = await client.post(f"/api/v1/tasks/{task_id}/cancel")
+ assert stopped.status_code == 200
+ assert stopped.json()["result"]["status"] in {"cancelled", "cancelling"}
+ retry_after_cancel = await client.post("/api/v1/compile", json=payload, headers=headers)
+ assert retry_after_cancel.json()["result"]["task_id"] == task_id
+ assert "submission_hash" not in retry_after_cancel.json()["result"]["meta"]
+ ctx = RequestContext(user=UserIdentifier("acme", "alice"), role=Role.ROOT)
+ tracker = TaskTracker(store)
+ root_page = await client.get(
+ "/api/v1/tasks", params={"pagination": "cursor", "task_type": "compile"}
+ )
+ assert root_page.json()["result"]["items"][0]["task_id"] == task_id
+ assert tracker.count() == 0
+ detail = await client.get(f"/api/v1/tasks/{task_id}")
+ assert detail.status_code == 200
+ assert detail.json()["result"]["task_id"] == task_id
+
+ # Recovery must not need the old resources or a currently configured backend.
+ from openviking_cli.exceptions import NotFoundError
+
+ fs.stat.side_effect = NotFoundError("deleted-source", "resource")
+ compile_service._local_endpoint = None
+ restored = await client.post("/api/v1/compile", json=payload, headers=headers)
+ assert restored.status_code == 202, restored.text
+ assert restored.json()["result"]["task_id"] == task_id
+ changed = await client.post(
+ "/api/v1/compile", json={**payload, "args": {"api_key": "different"}}, headers=headers
+ )
+ assert changed.status_code == 409
+ compile_service.configure_local_backend("http://localhost:1", "")
+ rejected = await client.post(
+ "/api/v1/compile", json=payload, headers={"Idempotency-Key": "new-invalid-request-key"}
+ )
+ assert rejected.status_code != 202
+ ctx = RequestContext(user=UserIdentifier("acme", "bob"), role=Role.USER)
+ assert (await client.get("/api/v1/tasks", params={"pagination": "cursor"})).json()[
+ "result"
+ ]["items"] == []
+
+
+async def test_cursor_prunes_cold_expired_records_without_loading_cache():
+ store = PersistentTaskStore(_FakeAgfs())
+ tracker = TaskTracker(store)
+ owner = {"account_id": "acme", "user_id": "alice"}
+ for task_id, status, days in [
+ ("expired-complete", TaskStatus.COMPLETED, 2),
+ ("expired-cancelled", TaskStatus.CANCELLED, 2),
+ ("expired-failed", TaskStatus.FAILED, 8),
+ ("recent-failed", TaskStatus.FAILED, 2),
+ ("active", TaskStatus.RUNNING, 8),
+ ]:
+ task = await tracker.create("compile", task_id=task_id, **owner)
+ task.status = status
+ task.updated_at = time.time() - days * 86400
+ await store.update(task)
+ tracker = TaskTracker(store, max_concurrent_store_io=1)
+ page = await asyncio.wait_for(
+ tracker.list_page(
+ **owner,
+ limit=30,
+ task_type="compile",
+ status=None,
+ resource_id=None,
+ include_internal=False,
+ q=None,
+ ),
+ timeout=3,
+ )
+ assert {task.task_id for task in page} == {"recent-failed", "active"}
+ assert tracker.count() == 0
+ assert {task["task_id"] for task in await store.list("acme", user_id="alice")} == {
+ "recent-failed",
+ "active",
+ }
+
+
+async def test_cursor_cleanup_rechecks_task_updated_after_scan(monkeypatch):
+ store = PersistentTaskStore(_FakeAgfs())
+ tracker = TaskTracker(store, max_concurrent_store_io=1)
+ owner = {"account_id": "acme", "user_id": "alice"}
+ task = await tracker.create("compile", task_id="updated-after-scan", **owner)
+ task.status = TaskStatus.COMPLETED
+ task.updated_at = time.time() - 2 * 86400
+ await store.update(task)
+ tracker = TaskTracker(store, max_concurrent_store_io=1)
+ prune = tracker._prune_persisted_expired
+ scanned = asyncio.Event()
+
+ async def signal_before_prune(payload):
+ scanned.set()
+ return await prune(payload)
+
+ monkeypatch.setattr(tracker, "_prune_persisted_expired", signal_before_prune)
+ async with tracker._task_locks.acquire(task.task_id):
+ reading = asyncio.create_task(
+ tracker.list_page(
+ **owner,
+ limit=30,
+ task_type="compile",
+ status=None,
+ resource_id=None,
+ include_internal=False,
+ q=None,
+ )
+ )
+ await asyncio.wait_for(scanned.wait(), timeout=3)
+ task.updated_at = time.time()
+ # A scan waiting for this task lock must not hold the sole I/O slot.
+ await asyncio.wait_for(
+ tracker._store_io.run("update", lambda: store.update(task)), timeout=3
+ )
+ page = await asyncio.wait_for(reading, timeout=3)
+ assert [record.task_id for record in page] == [task.task_id]
+ assert await store.get(task.task_id, **owner) is not None
diff --git a/web-studio/src/components/app-shell.tsx b/web-studio/src/components/app-shell.tsx
index 82cecdf59..333a72096 100644
--- a/web-studio/src/components/app-shell.tsx
+++ b/web-studio/src/components/app-shell.tsx
@@ -111,6 +111,14 @@ const NAV_ITEMS: readonly NavItem[] = [
titleKey: 'navigation.skills.title',
to: '/skills',
},
+
+ {
+ icon: SparklesIcon,
+ id: 'compile',
+ section: 'workspace',
+ titleKey: 'navigation.compile.title',
+ to: '/compile',
+ },
{
icon: BrainIcon,
id: 'agentExperience',
diff --git a/web-studio/src/i18n/locales/en.ts b/web-studio/src/i18n/locales/en.ts
index c0ab2aad4..4fdcca575 100644
--- a/web-studio/src/i18n/locales/en.ts
+++ b/web-studio/src/i18n/locales/en.ts
@@ -1,9 +1,11 @@
+import compile from './en/compile'
import memoryPolicy from './en/user-memory-policy'
import workspace from './en/workspace'
import resources from './en/resources'
import activity from './en/activity'
const en = {
+ compile,
...workspace,
...resources,
...activity,
diff --git a/web-studio/src/i18n/locales/en/compile.ts b/web-studio/src/i18n/locales/en/compile.ts
new file mode 100644
index 000000000..0f7328172
--- /dev/null
+++ b/web-studio/src/i18n/locales/en/compile.ts
@@ -0,0 +1,169 @@
+export default {
+ errors: {
+ generic: 'The request could not be completed.',
+ invalidArgument: 'Check the request parameters and try again.',
+ notFound: 'The requested resource or task was not found.',
+ permissionDenied: 'You do not have permission to perform this action.',
+ unauthenticated: 'Check your connection credentials and try again.',
+ conflict: 'This submission conflicts with an existing request.',
+ network: 'Unable to reach the server. Check your connection and try again.',
+ upgrade: 'Update OpenViking to use paginated task history.',
+ details: 'Technical details',
+ },
+ commandErrors: {
+ expiredSubmission:
+ 'The previous submission is too old to retry safely. Check task history before starting another task.',
+ pendingSubmission:
+ 'Resolve the previous submission before changing the command. Retry the original command or open the Compile form to look up its result.',
+ shellSyntax: 'Shell operators are not supported.',
+ unclosedQuote:
+ 'Close all quotes and escape sequences before running the command.',
+ invalidArgument:
+ 'Invalid argument. Use a supported flag followed by its value, separated by a space.',
+ duplicateArgument: 'Only --from may be specified more than once.',
+ required: 'Required arguments: --from, --to, --skill.',
+ argsObject: '--args must contain a valid JSON object.',
+ unknownCommand: 'Unknown command. Use compile or task.',
+ taskUsage: 'Use task status <id>, task cancel <id>, or task list.',
+ missingValue: 'A command flag is missing its value.',
+ listUsage:
+ 'Supported options: --task-type compile, --status <status>, --cursor <cursor>.',
+ },
+ argMode: 'Parameter editor mode',
+ argFields: 'Fields',
+ argRaw: 'JSON',
+ argKey: 'Parameter name',
+ argType: 'Type',
+ argValue: 'Value',
+ argRemove: 'Remove parameter',
+ argAdd: 'Add parameter',
+ argEmpty: 'Leave empty unless your Skill requires additional parameters.',
+ argKeyRequired: 'Enter a parameter name.',
+ argDuplicate: 'Parameter names must be unique.',
+ argNumberError: 'Enter a valid number.',
+ argJsonError: 'Enter valid JSON for this value.',
+ argTypes: {
+ string: 'Text',
+ number: 'Number',
+ boolean: 'Boolean',
+ json: 'JSON',
+ },
+
+ moreSources: '{{count}} more source directories',
+ detailTitle: 'Compile task details',
+ copyTaskId: 'Copy task ID',
+ stages: {
+ queued: 'Queued',
+ loading_skill: 'Loading Skill',
+ running: 'Compiling',
+ completed: 'Completed',
+ processing: 'Processing sources',
+ },
+ sourcePlaceholder: 'viking://resources/…',
+ formIntro:
+ 'Choose a Skill, add source directories, and choose where to save the result. * indicates a required field.',
+ optional: 'Optional',
+ addSource: 'Add path',
+ sourceNumber: 'Source directory {{number}}',
+ skillRequired: 'Choose a Skill.',
+ sourcesRequired: 'Add at least one source directory.',
+ targetRequired: 'Set an output directory.',
+ mySkills: 'My Skills',
+ sharedSkills: 'Shared Skills',
+ otherSkills: 'Other paths',
+
+ noMatchingSkills: 'No matching skills',
+ skillLocationHint:
+ 'Add a Skill on the Skills page first. Private and shared Skills are supported; the directory must contain SKILL.md.',
+ expiredSubmission:
+ 'The retry window has expired. Look up the last submission or check the task list before clearing the draft to start another task.',
+ targetPlaceholder: 'viking://resources/wiki',
+ removeSource: 'Remove {{uri}}',
+ title: 'Compile',
+ description: 'Transform your materials with a Skill.',
+ new: 'New compilation',
+ back: 'Back to list',
+ search: 'Search Skill, path or task ID',
+ all: 'All statuses',
+ refresh: 'Refresh',
+ more: 'Load more',
+ empty: 'No compilations yet',
+ emptyFiltered: 'No matching tasks',
+ loading: 'Loading…',
+ retry: 'Retry',
+ failedLoad: 'Could not load data',
+ unconfigured: 'Compilation is unavailable for this connection or identity.',
+ skill: '1. Choose a Skill',
+ skillSearch: 'Search Skills',
+ chooseSkill: 'Choose a Skill',
+ noSkills: 'No available Skills. Visit Skills to add one.',
+ preview: 'View current Skill',
+ sources: 'Source directories',
+ browse: 'Browse directories',
+ sourceHint: 'One Viking directory URI per line. Files are not accepted.',
+ target: '3. Choose an output location',
+ targetHint:
+ 'Existing contents may be updated. A new target is created during execution.',
+ instruction: 'Additional instructions',
+ instructionPlaceholder:
+ 'For example: group by topic and preserve source references.',
+ advanced: 'Advanced parameters (optional)',
+ argsHint: 'JSON object. Not saved in drafts or copied commands.',
+ start: 'Start compilation',
+ submitting: 'Submitting…',
+ copyCommand: 'Copy command',
+ copied: 'Copied',
+ cancel: 'Cancel',
+ clear: 'Clear draft',
+ draft:
+ 'Public fields are saved as a draft. Advanced parameters are not saved.',
+ required: 'Choose a Skill, at least one source directory and an output URI.',
+ invalidUri: 'Use full viking:// URIs for every path.',
+ argsError: 'Advanced parameters must be a valid JSON object.',
+ runningHint: 'You can leave this page. The task will continue.',
+ unknownSubmission:
+ 'Creation could not be confirmed. Retry with the same parameters to avoid duplicates.',
+ recover: 'Recover last submission',
+ rerun: 'Edit and run again',
+ rerunHint:
+ 'Review the current Skill and re-enter any private parameters before running.',
+ stop: 'Stop task',
+ stopConfirm: 'Stop this task? Content already written may remain.',
+ rootCancel: 'ROOT cannot cancel tasks.',
+ overview: 'Overview',
+ events: 'Execution log',
+ result: 'Result',
+ output: 'Open output directory',
+ noResult: 'No structured result is available yet.',
+ raw: 'Raw result',
+ stage: 'Current stage',
+ updated: 'Last updated',
+ stale: 'Updates are unavailable. Showing the last known state.',
+ missingRequest: 'This task has no complete saved request.',
+ selectDraft:
+ 'Replace the current draft with this task’s public configuration?',
+ leave: 'Advanced parameters will be lost. Leave this page?',
+ viewTask: 'View task',
+ created: 'Task created',
+ terminalHint: 'Compile materials with a Skill',
+ openForm: 'Open compilation form',
+ terminalHelp:
+ 'compile --from <directory> --to <directory> --skill <Skill URI> [--instruction "..."] [--args \'{}\']\ntask status <id> | task cancel <id> | task list --task-type compile',
+ argsOmitted: 'Advanced parameters omitted from history and copied commands.',
+ storageFailed: 'Draft could not be saved.',
+ newTasks: 'Refresh to see new tasks',
+ createdAt: 'Created',
+ task: 'Task / Skill',
+ materials: 'Materials',
+ status: 'Status',
+ invalidTask: 'Task not found or not a compilation.',
+ statuses: {
+ pending: 'Queued',
+ running: 'Running',
+ cancelling: 'Stopping',
+ completed: 'Completed',
+ failed: 'Failed',
+ cancelled: 'Cancelled',
+ unknown: 'Unknown',
+ },
+} as const
diff --git a/web-studio/src/i18n/locales/en/resources.ts b/web-studio/src/i18n/locales/en/resources.ts
index bba621f42..0fdef586c 100644
--- a/web-studio/src/i18n/locales/en/resources.ts
+++ b/web-studio/src/i18n/locales/en/resources.ts
@@ -133,6 +133,10 @@ const resources = {
tooManyFiles: 'Only the first {{count}} files were kept.',
error: 'Request Failed',
dirPicker: {
+ scope: 'Resource scope',
+ mine: 'My resources',
+ shared: 'Shared resources',
+
title: 'Select Directory',
select: 'Select',
cancel: 'Cancel',
diff --git a/web-studio/src/i18n/locales/en/workspace.ts b/web-studio/src/i18n/locales/en/workspace.ts
index 623402be0..63ee28a6a 100644
--- a/web-studio/src/i18n/locales/en/workspace.ts
+++ b/web-studio/src/i18n/locales/en/workspace.ts
@@ -30,6 +30,7 @@ const workspace = {
defaultTitle: 'OpenViking Studio',
},
navigation: {
+ compile: { title: 'Compile' },
home: {
title: 'Home',
},
@@ -413,6 +414,15 @@ const workspace = {
},
error: 'Failure reason',
result: 'Result',
+ noResultRunning: 'Task in progress',
+ noResultRunningDescription:
+ 'No final result is available yet. See the reported stages and execution log above.',
+ noResultPending: 'Task queued',
+ noResultPendingDescription:
+ 'The task has not started yet. Reported stages and execution events will appear when available.',
+ noResultCompleted: 'Task completed',
+ noResultCompletedDescription:
+ 'This task did not return a displayable result.',
noResult: 'No result yet',
noResultDescription:
'Results returned by the API will appear here when the task completes.',
@@ -476,6 +486,7 @@ const workspace = {
unknown: 'Unknown',
},
types: {
+ compile: 'Compile',
session_commit: 'Session commit',
add_resource: 'Resource processing',
add_skill: 'Skill import',
diff --git a/web-studio/src/i18n/locales/zh-CN.ts b/web-studio/src/i18n/locales/zh-CN.ts
index bdae33f98..2493e278a 100644
--- a/web-studio/src/i18n/locales/zh-CN.ts
+++ b/web-studio/src/i18n/locales/zh-CN.ts
@@ -1,9 +1,11 @@
+import compile from './zh-CN/compile'
import memoryPolicy from './zh-CN/user-memory-policy'
import workspace from './zh-CN/workspace'
import resources from './zh-CN/resources'
import activity from './zh-CN/activity'
const zhCN = {
+ compile,
...workspace,
...resources,
...activity,
diff --git a/web-studio/src/i18n/locales/zh-CN/compile.ts b/web-studio/src/i18n/locales/zh-CN/compile.ts
new file mode 100644
index 000000000..c5b77bd04
--- /dev/null
+++ b/web-studio/src/i18n/locales/zh-CN/compile.ts
@@ -0,0 +1,156 @@
+export default {
+ errors: {
+ generic: '请求未能完成。',
+ invalidArgument: '请检查请求参数后重试。',
+ notFound: '未找到请求的资源或任务。',
+ permissionDenied: '当前身份没有执行此操作的权限。',
+ unauthenticated: '请检查连接凭据后重试。',
+ conflict: '本次提交与已有请求冲突。',
+ network: '无法连接服务器,请检查网络后重试。',
+ upgrade: '请升级 OpenViking 后使用任务历史分页。',
+ details: '技术详情',
+ },
+ commandErrors: {
+ expiredSubmission:
+ '上次提交已超过安全重试期限,请先检查任务历史,再通过表单新建任务。',
+ pendingSubmission:
+ '上次提交结果尚未确认。请重试原命令,或打开编译表单查询结果后再更改命令。',
+ shellSyntax: '不支持 Shell 运算符。',
+ unclosedQuote: '请补全引号或转义字符后再执行命令。',
+ invalidArgument: '参数无效。请使用支持的参数名,并以空格分隔参数名和值。',
+ duplicateArgument: '只有 --from 可以重复指定。',
+ required: '请填写必填参数:--from、--to、--skill。',
+ argsObject: '--args 必须是合法的 JSON 对象。',
+ unknownCommand: '未知命令,请使用 compile 或 task。',
+ taskUsage: '请使用 task status <id>、task cancel <id> 或 task list。',
+ missingValue: '命令参数缺少对应的值。',
+ listUsage:
+ '支持的选项:--task-type compile、--status <status>、--cursor <cursor>。',
+ },
+ argMode: '参数编辑方式',
+ argFields: '表单模式',
+ argRaw: 'JSON 模式',
+ argKey: '参数名',
+ argType: '类型',
+ argValue: '参数值',
+ argRemove: '删除参数',
+ argAdd: '添加参数',
+ argEmpty: '无需额外参数时留空。仅添加 Skill 约定的参数。',
+ argKeyRequired: '请填写参数名。',
+ argDuplicate: '参数名不能重复。',
+ argNumberError: '请输入有效数字。',
+ argJsonError: '参数值必须是合法 JSON。',
+ argTypes: { string: '文本', number: '数字', boolean: '布尔值', json: 'JSON' },
+
+ moreSources: '另有 {{count}} 个素材目录',
+ detailTitle: '编译任务详情',
+ copyTaskId: '复制任务 ID',
+ stages: {
+ queued: '等待执行',
+ loading_skill: '读取 Skill',
+ running: '编译处理中',
+ completed: '执行完成',
+ processing: '处理素材',
+ },
+ sourcePlaceholder: 'viking://resources/…',
+ formIntro:
+ '选择编译规则、添加素材,并设置结果的保存位置。标有 * 的为必填项。',
+ optional: '可选',
+ addSource: '添加路径',
+ sourceNumber: '素材目录 {{number}}',
+ skillRequired: '请选择一个 Skill。',
+ sourcesRequired: '请添加至少一个素材目录。',
+ targetRequired: '请设置输出目录。',
+ mySkills: '我的 Skill',
+ sharedSkills: '共享 Skill',
+ otherSkills: '其他路径',
+
+ noMatchingSkills: '没有匹配的 Skill',
+ skillLocationHint:
+ '请先在 Skills 页面添加 Skill;支持当前用户私有或共享的 Skill,目录内需包含 SKILL.md。',
+ expiredSubmission:
+ '已超过安全重试时间。请先查询上次提交或检查任务列表,确认后清空草稿再创建新任务。',
+ targetPlaceholder: 'viking://resources/wiki',
+ removeSource: '移除 {{uri}}',
+ title: 'Compile',
+ description: '使用 Skill 将素材整理为新的内容。',
+ new: '新建编译',
+ back: '返回列表',
+ search: '搜索 Skill、路径或任务 ID',
+ all: '全部状态',
+ refresh: '刷新',
+ more: '加载更多',
+ empty: '暂无编译任务',
+ emptyFiltered: '没有符合条件的任务',
+ loading: '正在加载…',
+ retry: '重试',
+ failedLoad: '加载失败',
+ unconfigured: '当前连接或身份暂不可创建编译任务。',
+ skill: '编译 Skill',
+ skillSearch: '搜索 Skill',
+ chooseSkill: '请选择 Skill',
+ noSkills: '暂无可用 Skill,请前往 Skills 添加。',
+ preview: '查看当前 Skill',
+ sources: '素材目录',
+ browse: '浏览目录',
+ sourceHint: '选择已存入 Viking 的目录,可添加多个。',
+ target: '输出目录',
+ targetHint: '已有内容可能被更新;新目标在执行时创建。',
+ instruction: '补充要求',
+ instructionPlaceholder: '例如:按主题整理,保留引用来源。',
+ advanced: '高级参数(可选)',
+ argsHint: '参数不保存到草稿或复制的命令中;嵌套对象和数组可使用 JSON 类型。',
+ start: '开始编译',
+ submitting: '正在提交…',
+ copyCommand: '复制命令',
+ copied: '已复制',
+ cancel: '取消',
+ clear: '清空草稿',
+ draft: '已自动保存草稿 · 高级参数不保存',
+ required: '请选择 Skill、至少一个素材目录,并填写输出 URI。',
+ invalidUri: '所有路径请填写完整的 viking:// URI。',
+ argsError: '高级参数必须是合法的 JSON 对象。',
+ runningHint: '可以离开页面,任务会继续执行。',
+ unknownSubmission: '尚未确认是否创建成功。请保留参数重试确认,避免重复任务。',
+ recover: '查询上次提交结果',
+ rerun: '修改后重新运行',
+ rerunHint: '请检查当前 Skill,并重新填写所需私有参数。',
+ stop: '停止任务',
+ stopConfirm: '停止此任务?已经写入的内容可能保留。',
+ rootCancel: 'ROOT 身份不能取消任务。',
+ overview: '概览',
+ events: '执行记录',
+ result: '结果',
+ output: '打开输出目录',
+ noResult: '暂未提供结构化结果。',
+ raw: '原始结果',
+ stage: '当前阶段',
+ updated: '最近更新',
+ stale: '暂时无法更新,以下为最近一次状态。',
+ missingRequest: '该任务未记录完整创建参数。',
+ selectDraft: '用该任务的公开配置替换当前草稿?',
+ leave: '高级参数尚未保存,离开将丢失。是否离开?',
+ viewTask: '查看任务',
+ created: '任务已创建',
+ terminalHint: '使用 Skill 编译素材',
+ openForm: '打开编译表单',
+ terminalHelp:
+ 'compile --from <素材目录> --to <输出目录> --skill <Skill URI> [--instruction "..."] [--args \'{}\']\ntask status <id> | task cancel <id> | task list --task-type compile',
+ argsOmitted: '高级参数不写入历史记录或复制的命令。',
+ storageFailed: '草稿保存失败。',
+ newTasks: '刷新查看新任务',
+ createdAt: '创建时间',
+ task: '任务 / Skill',
+ materials: '素材',
+ status: '状态',
+ invalidTask: '任务不存在或不是编译任务。',
+ statuses: {
+ pending: '排队中',
+ running: '运行中',
+ cancelling: '取消中',
+ completed: '已完成',
+ failed: '失败',
+ cancelled: '已取消',
+ unknown: '未知状态',
+ },
+} as const
diff --git a/web-studio/src/i18n/locales/zh-CN/resources.ts b/web-studio/src/i18n/locales/zh-CN/resources.ts
index 93b18c62c..401b9a7af 100644
--- a/web-studio/src/i18n/locales/zh-CN/resources.ts
+++ b/web-studio/src/i18n/locales/zh-CN/resources.ts
@@ -126,6 +126,10 @@ const resources = {
tooManyFiles: '仅保留前 {{count}} 个文件,其余已忽略。',
error: '请求失败',
dirPicker: {
+ scope: '资源范围',
+ mine: '我的资源',
+ shared: '公共资源',
+
title: '选择目录',
select: '选择',
cancel: '取消',
diff --git a/web-studio/src/i18n/locales/zh-CN/workspace.ts b/web-studio/src/i18n/locales/zh-CN/workspace.ts
index eef49c0d7..e6b93f381 100644
--- a/web-studio/src/i18n/locales/zh-CN/workspace.ts
+++ b/web-studio/src/i18n/locales/zh-CN/workspace.ts
@@ -30,6 +30,7 @@ const workspace = {
defaultTitle: 'OpenViking Studio',
},
navigation: {
+ compile: { title: 'Compile' },
home: {
title: '首页',
},
@@ -400,6 +401,14 @@ const workspace = {
},
error: '失败原因',
result: '执行结果',
+ noResultRunning: '任务进行中',
+ noResultRunningDescription:
+ '尚未返回最终结果。可查看上方已上报的阶段和执行日志。',
+ noResultPending: '任务排队中',
+ noResultPendingDescription:
+ '任务尚未开始执行,开始后会显示已上报的阶段和执行日志。',
+ noResultCompleted: '任务已完成',
+ noResultCompletedDescription: '该任务未返回可展示的执行结果。',
noResult: '暂无执行结果',
noResultDescription: '任务完成后,接口返回的结果会显示在这里。',
noResultFailedDescription: '该任务未返回结果,请查看上方失败原因。',
@@ -457,6 +466,7 @@ const workspace = {
unknown: '未知',
},
types: {
+ compile: 'Compile',
session_commit: '会话提交',
add_resource: '资源处理',
add_skill: '技能导入',
diff --git a/web-studio/src/lib/markdown-frontmatter.test.ts b/web-studio/src/lib/markdown-frontmatter.test.ts
new file mode 100644
index 000000000..3d51ec5b8
--- /dev/null
+++ b/web-studio/src/lib/markdown-frontmatter.test.ts
@@ -0,0 +1,20 @@
+import { expect, it } from 'vitest'
+import { splitMarkdownFrontmatter } from './markdown-frontmatter'
+
+it('separates leading metadata without changing body separators', () => {
+ expect(
+ splitMarkdownFrontmatter('---\ntitle: Report\n---\n# Report\n---\nBody'),
+ ).toEqual({
+ rawFrontmatter: '---\ntitle: Report\n---',
+ body: '# Report\n---\nBody',
+ })
+})
+it('ignores ordinary separators and incomplete metadata', () => {
+ expect(splitMarkdownFrontmatter('# Report\n---\nBody')).toBeNull()
+ expect(splitMarkdownFrontmatter('---\nBody')).toBeNull()
+})
+it('preserves embedded fences and Windows newlines as plain metadata', () => {
+ expect(
+ splitMarkdownFrontmatter('\uFEFF---\r\nvalue: ```\r\n...\r\n# Body'),
+ ).toEqual({ rawFrontmatter: '---\r\nvalue: ```\r\n...', body: '# Body' })
+})
diff --git a/web-studio/src/lib/markdown-frontmatter.ts b/web-studio/src/lib/markdown-frontmatter.ts
new file mode 100644
index 000000000..0d1c6b531
--- /dev/null
+++ b/web-studio/src/lib/markdown-frontmatter.ts
@@ -0,0 +1,14 @@
+/** Display leading YAML metadata as code without changing the stored document. */
+export function splitMarkdownFrontmatter(
+ markdown: string,
+): { rawFrontmatter: string; body: string } | null {
+ const match =
+ /^(?:\uFEFF)?---[ \t]*\r?\n([\s\S]*?)\r?\n(?:---|\.\.\.)[ \t]*(?:\r?\n|$)/.exec(
+ markdown,
+ )
+ if (!match) return null
+ return {
+ rawFrontmatter: match[0].replace(/^\uFEFF/, '').trimEnd(),
+ body: markdown.slice(match[0].length),
+ }
+}
diff --git a/web-studio/src/routeTree.gen.ts b/web-studio/src/routeTree.gen.ts
index 0784ed8d6..19ba845fa 100644
--- a/web-studio/src/routeTree.gen.ts
+++ b/web-studio/src/routeTree.gen.ts
@@ -23,10 +23,13 @@ import { Route as HomeRouteRouteImport } from './routes/home/route'
import { Route as AgentExperienceRouteRouteImport } from './routes/agent-experience/route'
import { Route as IndexRouteImport } from './routes/index'
import { Route as SessionsIndexRouteImport } from './routes/sessions/index'
+import { Route as CompileIndexRouteImport } from './routes/compile/index'
import { Route as AgentExperienceIndexRouteImport } from './routes/agent-experience/index'
import { Route as OauthVerifyRouteImport } from './routes/oauth/verify'
import { Route as OauthConsentRouteImport } from './routes/oauth/consent'
+import { Route as CompileNewRouteImport } from './routes/compile/new'
import { Route as AgentExperienceExperienceUriRouteImport } from './routes/agent-experience/$experienceUri'
+import { Route as CompileTasksTaskIdRouteImport } from './routes/compile/tasks/$taskId'
const WatchesRouteRoute = WatchesRouteRouteImport.update({
id: '/watches',
@@ -98,6 +101,11 @@ const SessionsIndexRoute = SessionsIndexRouteImport.update({
path: '/',
getParentRoute: () => SessionsRouteRoute,
} as any)
+const CompileIndexRoute = CompileIndexRouteImport.update({
+ id: '/compile/',
+ path: '/compile/',
+ getParentRoute: () => rootRouteImport,
+} as any)
const AgentExperienceIndexRoute = AgentExperienceIndexRouteImport.update({
id: '/',
path: '/',
@@ -113,12 +121,22 @@ const OauthConsentRoute = OauthConsentRouteImport.update({
path: '/oauth/consent',
getParentRoute: () => rootRouteImport,
} as any)
+const CompileNewRoute = CompileNewRouteImport.update({
+ id: '/compile/new',
+ path: '/compile/new',
+ getParentRoute: () => rootRouteImport,
+} as any)
const AgentExperienceExperienceUriRoute =
AgentExperienceExperienceUriRouteImport.update({
id: '/$experienceUri',
path: '/$experienceUri',
getParentRoute: () => AgentExperienceRouteRoute,
} as any)
+const CompileTasksTaskIdRoute = CompileTasksTaskIdRouteImport.update({
+ id: '/compile/tasks/$taskId',
+ path: '/compile/tasks/$taskId',
+ getParentRoute: () => rootRouteImport,
+} as any)
export interface FileRoutesByFullPath {
'/': typeof IndexRoute
@@ -135,10 +153,13 @@ export interface FileRoutesByFullPath {
'/users': typeof UsersRouteRoute
'/watches': typeof WatchesRouteRoute
'/agent-experience/$experienceUri': typeof AgentExperienceExperienceUriRoute
+ '/compile/new': typeof CompileNewRoute
'/oauth/consent': typeof OauthConsentRoute
'/oauth/verify': typeof OauthVerifyRoute
'/agent-experience/': typeof AgentExperienceIndexRoute
+ '/compile/': typeof CompileIndexRoute
'/sessions/': typeof SessionsIndexRoute
+ '/compile/tasks/$taskId': typeof CompileTasksTaskIdRoute
}
export interface FileRoutesByTo {
'/': typeof IndexRoute
@@ -153,10 +174,13 @@ export interface FileRoutesByTo {
'/users': typeof UsersRouteRoute
'/watches': typeof WatchesRouteRoute
'/agent-experience/$experienceUri': typeof AgentExperienceExperienceUriRoute
+ '/compile/new': typeof CompileNewRoute
'/oauth/consent': typeof OauthConsentRoute
'/oauth/verify': typeof OauthVerifyRoute
'/agent-experience': typeof AgentExperienceIndexRoute
+ '/compile': typeof CompileIndexRoute
'/sessions': typeof SessionsIndexRoute
+ '/compile/tasks/$taskId': typeof CompileTasksTaskIdRoute
}
export interface FileRoutesById {
__root__: typeof rootRouteImport
@@ -174,10 +198,13 @@ export interface FileRoutesById {
'/users': typeof UsersRouteRoute
'/watches': typeof WatchesRouteRoute
'/agent-experience/$experienceUri': typeof AgentExperienceExperienceUriRoute
+ '/compile/new': typeof CompileNewRoute
'/oauth/consent': typeof OauthConsentRoute
'/oauth/verify': typeof OauthVerifyRoute
'/agent-experience/': typeof AgentExperienceIndexRoute
+ '/compile/': typeof CompileIndexRoute
'/sessions/': typeof SessionsIndexRoute
+ '/compile/tasks/$taskId': typeof CompileTasksTaskIdRoute
}
export interface FileRouteTypes {
fileRoutesByFullPath: FileRoutesByFullPath
@@ -196,10 +223,13 @@ export interface FileRouteTypes {
| '/users'
| '/watches'
| '/agent-experience/$experienceUri'
+ | '/compile/new'
| '/oauth/consent'
| '/oauth/verify'
| '/agent-experience/'
+ | '/compile/'
| '/sessions/'
+ | '/compile/tasks/$taskId'
fileRoutesByTo: FileRoutesByTo
to:
| '/'
@@ -214,10 +244,13 @@ export interface FileRouteTypes {
| '/users'
| '/watches'
| '/agent-experience/$experienceUri'
+ | '/compile/new'
| '/oauth/consent'
| '/oauth/verify'
| '/agent-experience'
+ | '/compile'
| '/sessions'
+ | '/compile/tasks/$taskId'
id:
| '__root__'
| '/'
@@ -234,10 +267,13 @@ export interface FileRouteTypes {
| '/users'
| '/watches'
| '/agent-experience/$experienceUri'
+ | '/compile/new'
| '/oauth/consent'
| '/oauth/verify'
| '/agent-experience/'
+ | '/compile/'
| '/sessions/'
+ | '/compile/tasks/$taskId'
fileRoutesById: FileRoutesById
}
export interface RootRouteChildren {
@@ -254,8 +290,11 @@ export interface RootRouteChildren {
TasksRouteRoute: typeof TasksRouteRoute
UsersRouteRoute: typeof UsersRouteRoute
WatchesRouteRoute: typeof WatchesRouteRoute
+ CompileNewRoute: typeof CompileNewRoute
OauthConsentRoute: typeof OauthConsentRoute
OauthVerifyRoute: typeof OauthVerifyRoute
+ CompileIndexRoute: typeof CompileIndexRoute
+ CompileTasksTaskIdRoute: typeof CompileTasksTaskIdRoute
}
declare module '@tanstack/react-router' {
@@ -358,6 +397,13 @@ declare module '@tanstack/react-router' {
preLoaderRoute: typeof SessionsIndexRouteImport
parentRoute: typeof SessionsRouteRoute
}
+ '/compile/': {
+ id: '/compile/'
+ path: '/compile'
+ fullPath: '/compile/'
+ preLoaderRoute: typeof CompileIndexRouteImport
+ parentRoute: typeof rootRouteImport
+ }
'/agent-experience/': {
id: '/agent-experience/'
path: '/'
@@ -379,6 +425,13 @@ declare module '@tanstack/react-router' {
preLoaderRoute: typeof OauthConsentRouteImport
parentRoute: typeof rootRouteImport
}
+ '/compile/new': {
+ id: '/compile/new'
+ path: '/compile/new'
+ fullPath: '/compile/new'
+ preLoaderRoute: typeof CompileNewRouteImport
+ parentRoute: typeof rootRouteImport
+ }
'/agent-experience/$experienceUri': {
id: '/agent-experience/$experienceUri'
path: '/$experienceUri'
@@ -386,6 +439,13 @@ declare module '@tanstack/react-router' {
preLoaderRoute: typeof AgentExperienceExperienceUriRouteImport
parentRoute: typeof AgentExperienceRouteRoute
}
+ '/compile/tasks/$taskId': {
+ id: '/compile/tasks/$taskId'
+ path: '/compile/tasks/$taskId'
+ fullPath: '/compile/tasks/$taskId'
+ preLoaderRoute: typeof CompileTasksTaskIdRouteImport
+ parentRoute: typeof rootRouteImport
+ }
}
}
@@ -428,8 +488,11 @@ const rootRouteChildren: RootRouteChildren = {
TasksRouteRoute: TasksRouteRoute,
UsersRouteRoute: UsersRouteRoute,
WatchesRouteRoute: WatchesRouteRoute,
+ CompileNewRoute: CompileNewRoute,
OauthConsentRoute: OauthConsentRoute,
OauthVerifyRoute: OauthVerifyRoute,
+ CompileIndexRoute: CompileIndexRoute,
+ CompileTasksTaskIdRoute: CompileTasksTaskIdRoute,
}
export const routeTree = rootRouteImport
._addFileChildren(rootRouteChildren)
diff --git a/web-studio/src/routes/compile/-components/args-editor.tsx b/web-studio/src/routes/compile/-components/args-editor.tsx
new file mode 100644
index 000000000..d3776de9b
--- /dev/null
+++ b/web-studio/src/routes/compile/-components/args-editor.tsx
@@ -0,0 +1,252 @@
+import { useEffect, useRef, useState } from 'react'
+import { Plus, X } from 'lucide-react'
+import { useTranslation } from 'react-i18next'
+import { Button } from '#/components/ui/button'
+import { Input } from '#/components/ui/input'
+import { Textarea } from '#/components/ui/textarea'
+import { parseArgs } from '../-lib/commands'
+
+type Row = { id: number; key: string; type: string; value: string }
+const TYPES = ['string', 'number', 'boolean', 'json'] as const
+function decode(value: string): Row[] {
+ return Object.entries(parseArgs(value) ?? {}).map(([key, v], id) => ({
+ id,
+ key,
+ type:
+ typeof v === 'string'
+ ? 'string'
+ : typeof v === 'number'
+ ? 'number'
+ : typeof v === 'boolean'
+ ? 'boolean'
+ : 'json',
+ value: typeof v === 'string' ? v : JSON.stringify(v),
+ }))
+}
+export function ArgsEditor({
+ value,
+ onChange,
+}: {
+ value: string
+ onChange: (value: string) => void
+}) {
+ const { t } = useTranslation('compile')
+ const [mode, setMode] = useState<'fields' | 'json'>(() => {
+ try {
+ decode(value)
+ return 'fields'
+ } catch {
+ return 'json'
+ }
+ })
+ const [rows, setRows] = useState<Row[]>(() => {
+ try {
+ return decode(value)
+ } catch {
+ return []
+ }
+ })
+ const [error, setError] = useState('')
+ const emitted = useRef(value)
+ useEffect(() => {
+ if (value === emitted.current) return
+ emitted.current = value
+ try {
+ setRows(decode(value))
+ setError('')
+ } catch {
+ setMode('json')
+ }
+ }, [value])
+ function emit(next: string) {
+ emitted.current = next
+ onChange(next)
+ }
+ function edit(next: Row[]) {
+ setRows(next)
+ try {
+ const entries: [string, unknown][] = []
+ const keys = new Set<string>()
+ for (const row of next) {
+ if (!row.key.trim()) throw Error(t('argKeyRequired'))
+ if (keys.has(row.key)) throw Error(t('argDuplicate'))
+ keys.add(row.key)
+ let v: unknown = row.value
+ if (row.type === 'number') {
+ if (!row.value.trim() || !Number.isFinite(Number(row.value)))
+ throw Error(t('argNumberError'))
+ v = Number(row.value)
+ } else if (row.type === 'boolean') v = row.value === 'true'
+ else if (row.type === 'json') {
+ try {
+ v = JSON.parse(row.value)
+ } catch {
+ throw Error(t('argJsonError'))
+ }
+ }
+ entries.push([row.key, v])
+ }
+ setError('')
+ emit(
+ next.length ? JSON.stringify(Object.fromEntries(entries), null, 2) : '',
+ )
+ } catch (cause) {
+ setError((cause as Error).message)
+ // An invalid draft must never submit the previous valid parameter values.
+ emit(' ' + JSON.stringify(next) + '\n')
+ }
+ }
+ function patch(id: number, change: Partial<Row>) {
+ edit(rows.map((row) => (row.id === id ? { ...row, ...change } : row)))
+ }
+ return (
+ <div className="mt-4 space-y-3">
+ <div
+ className="flex items-center gap-1 rounded-lg bg-muted/40 p-1"
+ role="group"
+ aria-label={t('argMode')}
+ >
+ <Button
+ type="button"
+ size="sm"
+ variant={mode === 'fields' ? 'secondary' : 'ghost'}
+ aria-pressed={mode === 'fields'}
+ onClick={() => {
+ try {
+ setRows(decode(value))
+ setError('')
+ setMode('fields')
+ } catch {
+ setError(t('argsError'))
+ }
+ }}
+ >
+ {t('argFields')}
+ </Button>
+ <Button
+ type="button"
+ size="sm"
+ variant={mode === 'json' ? 'secondary' : 'ghost'}
+ aria-pressed={mode === 'json'}
+ disabled={mode === 'fields' && !!error}
+ onClick={() => setMode('json')}
+ >
+ {t('argRaw')}
+ </Button>
+ </div>
+ {mode === 'json' ? (
+ <Textarea
+ id="compile-args"
+ aria-label={t('argRaw')}
+ aria-describedby="args-editor-error"
+ value={value}
+ rows={6}
+ className="font-mono text-xs"
+ placeholder={JSON.stringify({ key: 'value' }, null, 2)}
+ onChange={(e) => {
+ emit(e.target.value)
+ try {
+ parseArgs(e.target.value)
+ setError('')
+ } catch {
+ setError(t('argsError'))
+ }
+ }}
+ />
+ ) : (
+ <div id="compile-args" tabIndex={-1} className="space-y-3">
+ {!rows.length && (
+ <p className="rounded-lg border border-dashed p-4 text-sm text-muted-foreground">
+ {t('argEmpty')}
+ </p>
+ )}
+ {rows.map((row, index) => (
+ <div
+ key={row.id}
+ className="grid grid-cols-[1fr_auto] gap-2 rounded-lg border p-3 sm:grid-cols-[minmax(0,1fr)_110px_minmax(0,1.5fr)_auto]"
+ >
+ <Input
+ aria-label={`${t('argKey')} ${index + 1}`}
+ placeholder={t('argKey')}
+ value={row.key}
+ onChange={(e) => patch(row.id, { key: e.target.value })}
+ />
+ <select
+ aria-label={`${t('argType')} ${index + 1}`}
+ className="h-9 rounded-md border bg-background px-2 text-sm"
+ value={row.type}
+ onChange={(e) =>
+ patch(row.id, {
+ type: e.target.value,
+ value: e.target.value === 'boolean' ? 'false' : row.value,
+ })
+ }
+ >
+ {TYPES.map((type) => (
+ <option key={type} value={type}>
+ {t(`argTypes.${type}`)}
+ </option>
+ ))}
+ </select>
+ {row.type === 'boolean' ? (
+ <select
+ aria-label={`${t('argValue')} ${index + 1}`}
+ className="h-9 rounded-md border bg-background px-2 text-sm"
+ value={row.value}
+ onChange={(e) => patch(row.id, { value: e.target.value })}
+ >
+ <option value="true">{String(true)}</option>
+ <option value="false">{String(false)}</option>
+ </select>
+ ) : (
+ <Input
+ aria-label={`${t('argValue')} ${index + 1}`}
+ placeholder={t('argValue')}
+ value={row.value}
+ onChange={(e) => patch(row.id, { value: e.target.value })}
+ />
+ )}
+ <Button
+ type="button"
+ variant="ghost"
+ size="icon"
+ aria-label={`${t('argRemove')} ${index + 1}`}
+ onClick={() => edit(rows.filter((v) => v.id !== row.id))}
+ >
+ <X className="size-4" />
+ </Button>
+ </div>
+ ))}
+ <Button
+ type="button"
+ size="sm"
+ variant="outline"
+ onClick={() =>
+ edit([
+ ...rows,
+ {
+ id: Math.max(-1, ...rows.map((r) => r.id)) + 1,
+ key: '',
+ type: 'string',
+ value: '',
+ },
+ ])
+ }
+ >
+ <Plus className="size-4" />
+ {t('argAdd')}
+ </Button>
+ </div>
+ )}
+ {error && (
+ <p
+ id="args-editor-error"
+ role="alert"
+ className="text-xs text-destructive"
+ >
+ {error}
+ </p>
+ )}
+ </div>
+ )
+}
diff --git a/web-studio/src/routes/compile/-components/compile-form.test.tsx b/web-studio/src/routes/compile/-components/compile-form.test.tsx
new file mode 100644
index 000000000..aa7e51fb1
--- /dev/null
+++ b/web-studio/src/routes/compile/-components/compile-form.test.tsx
@@ -0,0 +1,143 @@
+// @vitest-environment jsdom
+import type { ReactNode } from 'react'
+import { afterEach, beforeEach, expect, it, vi } from 'vitest'
+import { cleanup, fireEvent, render, waitFor } from '@testing-library/react'
+import { QueryClient, QueryClientProvider } from '@tanstack/react-query'
+import { CompileForm } from './compile-form'
+import { prepareCompileHandoff } from '../-lib/handoff'
+import { OvClientError } from '#/lib/ov-client'
+
+const api = vi.hoisted(() => ({
+ createCompile: vi.fn(),
+ lookupSubmission: vi.fn(),
+ fetchCompileSkills: vi.fn(async () => []),
+ fetchCompileTask: vi.fn(),
+ navigate: vi.fn(),
+}))
+vi.mock('../-lib/api', () => api)
+vi.mock('@tanstack/react-router', () => ({
+ useNavigate: () => api.navigate,
+ useBlocker: () => {},
+ Link: ({ children }: { children: ReactNode }) => <span>{children}</span>,
+}))
+vi.mock('react-i18next', () => ({
+ useTranslation: () => ({ t: (key: string) => key }),
+}))
+vi.mock('#/hooks/use-app-connection', () => ({
+ useAppConnection: () => ({
+ identityScopeKey: 'recovery-test',
+ connection: { userId: 'alice' },
+ }),
+}))
+vi.mock('./shared', () => ({
+ CompileShell: ({ children }: { children: ReactNode }) => (
+ <div>{children}</div>
+ ),
+ CompileError: () => <div role="alert">Submission error</div>,
+}))
+vi.mock('./skill-picker', () => ({ SkillPicker: () => null }))
+vi.mock('#/routes/resources/-components/directory-picker-dialog', () => ({
+ DirectoryPickerDialog: () => null,
+}))
+vi.mock('#/routes/resources/-lib/api', () => ({ fetchFileContent: vi.fn() }))
+
+const storageKey = 'compile-submission:recovery-test'
+const clients: QueryClient[] = []
+const task = { task_id: 'cmp-original', status: 'pending' }
+function mount() {
+ const client = new QueryClient({
+ defaultOptions: { queries: { retry: false } },
+ })
+ clients.push(client)
+ const page = render(
+ <QueryClientProvider client={client}>
+ <CompileForm />
+ </QueryClientProvider>,
+ )
+ return {
+ ...page,
+ submit: () => fireEvent.submit(page.container.querySelector('form')!),
+ }
+}
+beforeEach(() => {
+ vi.clearAllMocks()
+ localStorage.clear()
+ sessionStorage.clear()
+})
+afterEach(() => {
+ cleanup()
+ clients.splice(0).forEach((client) => client.clear())
+})
+
+it('recovers an accepted submission after response loss and reload without resubmitting missing args', async () => {
+ prepareCompileHandoff(
+ 'recovery-test',
+ `compile --from viking://resources/source --to viking://resources/wiki --skill viking://agent/skills/wiki --args '{"mode":"summary"}'`,
+ )
+ api.createCompile.mockRejectedValueOnce(
+ new OvClientError({ code: 'NETWORK_ERROR', message: 'Response lost' }),
+ )
+ let page = mount()
+ page.submit()
+ await waitFor(() => expect(page.getByText('retry')).toBeTruthy())
+ const originalKey = sessionStorage.getItem(storageKey)
+ expect(api.createCompile.mock.calls[0][0].args).toEqual({ mode: 'summary' })
+ page.unmount()
+ api.lookupSubmission.mockResolvedValueOnce(task)
+ page = mount()
+ page.submit()
+ await waitFor(() =>
+ expect(api.navigate).toHaveBeenCalledWith({
+ to: '/compile/tasks/$taskId',
+ params: { taskId: task.task_id },
+ }),
+ )
+ expect(api.lookupSubmission).toHaveBeenCalledWith(originalKey)
+ expect(api.createCompile).toHaveBeenCalledTimes(1)
+ expect(sessionStorage.getItem(storageKey)).toBeNull()
+})
+
+it('keeps the restored key after a lookup race and conflict, then finds the original task', async () => {
+ const key = `${Date.now()}:original-submission`
+ sessionStorage.setItem(storageKey, key)
+ localStorage.setItem(
+ 'compile-draft:recovery-test',
+ JSON.stringify({
+ skill: 'viking://agent/skills/wiki',
+ sources: 'viking://resources/source',
+ to: 'viking://resources/wiki',
+ instruction: '',
+ }),
+ )
+ api.lookupSubmission
+ .mockRejectedValueOnce(
+ new OvClientError({ code: 'NOT_FOUND', message: 'Not yet visible' }),
+ )
+ .mockResolvedValueOnce(task)
+ api.createCompile.mockRejectedValueOnce(
+ new OvClientError({ code: 'CONFLICT', message: 'Different args' }),
+ )
+ const page = mount()
+ page.submit()
+ await waitFor(() => expect(page.getByRole('alert')).toBeTruthy())
+ expect(sessionStorage.getItem(storageKey)).toBe(key)
+ expect(api.createCompile.mock.calls[0][1]).toBe(key)
+ page.submit()
+ await waitFor(() => expect(api.navigate).toHaveBeenCalled())
+ expect(api.createCompile).toHaveBeenCalledTimes(1)
+ expect(api.lookupSubmission.mock.calls).toEqual([[key], [key]])
+})
+
+it('does not resubmit or discard the recovery key when lookup is unavailable', async () => {
+ const key = `${Date.now()}:original-submission`
+ sessionStorage.setItem(storageKey, key)
+ api.lookupSubmission.mockRejectedValueOnce(
+ new OvClientError({ code: 'NETWORK_ERROR', message: 'Offline' }),
+ )
+ const page = mount()
+ page.submit()
+ await waitFor(() => expect(page.getByRole('alert')).toBeTruthy())
+ expect(api.lookupSubmission).toHaveBeenCalledWith(key)
+ expect(api.createCompile).not.toHaveBeenCalled()
+ expect(sessionStorage.getItem(storageKey)).toBe(key)
+})
diff --git a/web-studio/src/routes/compile/-components/compile-form.tsx b/web-studio/src/routes/compile/-components/compile-form.tsx
new file mode 100644
index 000000000..71a339622
--- /dev/null
+++ b/web-studio/src/routes/compile/-components/compile-form.tsx
@@ -0,0 +1,621 @@
+import { ArgsEditor } from './args-editor'
+import { readCompileHandoff, clearCompileHandoff } from '../-lib/handoff'
+import { isRejectedCompileSubmission } from '../-lib/errors'
+import { useEffect, useRef, useState } from 'react'
+import { useQuery } from '@tanstack/react-query'
+import { Link, useNavigate, useBlocker } from '@tanstack/react-router'
+import { useTranslation } from 'react-i18next'
+import { toast } from 'sonner'
+import { isOvClientError } from '#/lib/ov-client'
+import { FolderOpen, Plus, X } from 'lucide-react'
+import { Button } from '#/components/ui/button'
+import { Input } from '#/components/ui/input'
+import { Textarea } from '#/components/ui/textarea'
+import { useAppConnection } from '#/hooks/use-app-connection'
+import { DirectoryPickerDialog } from '#/routes/resources/-components/directory-picker-dialog'
+import { fetchFileContent } from '#/routes/resources/-lib/api'
+import {
+ createCompile,
+ fetchCompileSkills,
+ fetchCompileTask,
+ lookupSubmission,
+} from '../-lib/api'
+import type { CompileRequest, CompileTask } from '../-lib/api'
+import { compileCommand, parseArgs } from '../-lib/commands'
+import { CompileError, CompileShell } from './shared'
+import { SkillPicker } from './skill-picker'
+
+type Draft = { skill: string; sources: string; to: string; instruction: string }
+const empty: Draft = { skill: '', sources: '', to: '', instruction: '' }
+function readDraft(key: string): Draft {
+ try {
+ const data = JSON.parse(localStorage.getItem(key) || '{}')
+ return Object.fromEntries(
+ Object.keys(empty).map((field) => [
+ field,
+ typeof data?.[field] === 'string' ? data[field] : '',
+ ]),
+ ) as Draft
+ } catch {
+ return empty
+ }
+}
+export function CompileForm({ fromTask }: { fromTask?: string }) {
+ const { t } = useTranslation('compile'),
+ navigate = useNavigate()
+ const { identityScopeKey, connection } = useAppConnection()
+ const userResourceRoot = `viking://user/${connection.userId || 'default'}/resources/`
+ const draftKey = `compile-draft:${identityScopeKey}`,
+ submissionKey = `compile-submission:${identityScopeKey}`
+ const [handoff] = useState(() => readCompileHandoff(identityScopeKey))
+ useEffect(() => {
+ clearCompileHandoff()
+ }, [])
+ const [draft, setDraft] = useState(() =>
+ handoff
+ ? {
+ skill: handoff.skill || '',
+ sources: handoff.from?.join('\n') || '',
+ to: handoff.to || '',
+ instruction: handoff.instruction || '',
+ }
+ : readDraft(draftKey),
+ )
+ const [args, setArgs] = useState(
+ handoff?.args ? JSON.stringify(handoff.args, null, 2) : '',
+ ),
+ [preview, setPreview] = useState(false)
+ const [picker, setPicker] = useState<'sources' | 'to' | null>(null)
+ const [error, setError] = useState<unknown>(null),
+ [savingError, setSavingError] = useState(false)
+ const [busy, setBusy] = useState(false),
+ [uncertain, setUncertain] = useState(false)
+ const submission = useRef<{ key: string; request: CompileRequest } | null>(
+ null,
+ )
+ const mounted = useRef(true),
+ completed = useRef(false),
+ filled = useRef(false)
+ const [recoverKey, setRecoverKey] = useState(() => {
+ try {
+ return sessionStorage.getItem(submissionKey)
+ } catch {
+ return null
+ }
+ })
+ useEffect(() => {
+ mounted.current = true
+ return () => {
+ mounted.current = false
+ }
+ }, [])
+ useBlocker({
+ shouldBlockFn: () =>
+ !completed.current &&
+ (busy || !!args.trim() || savingError) &&
+ !window.confirm(t('leave')),
+ enableBeforeUnload: () => !completed.current && !!args.trim(),
+ })
+ useEffect(() => {
+ if (completed.current) return
+ try {
+ localStorage.setItem(draftKey, JSON.stringify(draft))
+ setSavingError(false)
+ } catch {
+ setSavingError(true)
+ }
+ }, [draft, draftKey])
+ const skills = useQuery({
+ queryKey: ['compile-skills', identityScopeKey],
+ queryFn: ({ signal }) => fetchCompileSkills(signal),
+ })
+ const original = useQuery({
+ queryKey: ['compile-task', identityScopeKey, fromTask],
+ queryFn: ({ signal }) => fetchCompileTask(fromTask!, signal),
+ enabled: !!fromTask,
+ })
+ useEffect(() => {
+ const originalRequest = original.data?.meta?.request
+ if (!originalRequest || filled.current) return
+ filled.current = true
+ if (
+ Object.values(readDraft(draftKey)).some(Boolean) &&
+ !window.confirm(t('selectDraft'))
+ )
+ return
+ setDraft({
+ skill: originalRequest.skill,
+ sources: originalRequest.from.join('\n'),
+ to: originalRequest.to,
+ instruction: originalRequest.instruction || '',
+ })
+ setArgs(
+ originalRequest.args ? JSON.stringify(originalRequest.args, null, 2) : '',
+ )
+ }, [original.data, draftKey, t])
+ const skillContent = useQuery({
+ queryKey: ['compile-skill-content', identityScopeKey, draft.skill],
+ queryFn: () =>
+ fetchFileContent(`${draft.skill.replace(/\/$/, '')}/SKILL.md`),
+ enabled: preview && !!draft.skill,
+ })
+ function update(key: keyof Draft, value: string) {
+ setDraft((v) => ({ ...v, [key]: value }))
+ }
+ const [attempted, setAttempted] = useState(false)
+ const sourceRows = draft.sources ? draft.sources.split('\n') : ['']
+ const fieldErrors = {
+ skill: !draft.skill ? t('skillRequired') : '',
+ sources: !draft.sources.trim()
+ ? t('sourcesRequired')
+ : sourceRows.some((v) => v.trim() && !v.trim().startsWith('viking://'))
+ ? t('invalidUri')
+ : '',
+ to: !draft.to.trim()
+ ? t('targetRequired')
+ : !draft.to.trim().startsWith('viking://')
+ ? t('invalidUri')
+ : '',
+ args: (() => {
+ try {
+ parseArgs(args)
+ return ''
+ } catch {
+ return t('argsError')
+ }
+ })(),
+ }
+ function validate() {
+ setAttempted(true)
+ const first = (
+ Object.keys(fieldErrors) as (keyof typeof fieldErrors)[]
+ ).find((key) => fieldErrors[key])
+ if (!first) return true
+ if (first === 'args')
+ document.getElementById('compile-advanced')?.setAttribute('open', '')
+ document
+ .getElementById(`compile-${first === 'to' ? 'target' : first}`)
+ ?.focus()
+ return false
+ }
+ function fieldError(key: keyof typeof fieldErrors) {
+ return attempted && fieldErrors[key] ? (
+ <p id={`error-${key}`} role="alert" className="text-xs text-destructive">
+ {fieldErrors[key]}
+ </p>
+ ) : null
+ }
+ function request(): CompileRequest {
+ const sources = [
+ ...new Set(
+ draft.sources
+ .split('\n')
+ .map((v) => v.trim().replace(/\/$/, ''))
+ .filter(Boolean),
+ ),
+ ]
+ if (!draft.skill || !sources.length || !draft.to.trim())
+ throw new Error(t('required'))
+ if (
+ [...sources, draft.skill, draft.to.trim()].some(
+ (uri) => !uri.startsWith('viking://'),
+ )
+ )
+ throw new Error(t('invalidUri'))
+ let parsed: Record<string, unknown> | undefined
+ try {
+ parsed = parseArgs(args)
+ } catch {
+ throw new Error(t('argsError'))
+ }
+ return {
+ from: sources,
+ skill: draft.skill,
+ to: draft.to.trim(),
+ ...(draft.instruction.trim()
+ ? { instruction: draft.instruction.trim() }
+ : {}),
+ ...(parsed ? { args: parsed } : {}),
+ }
+ }
+ async function finish(task: CompileTask) {
+ if (!mounted.current) return
+ completed.current = true
+ try {
+ localStorage.removeItem(draftKey)
+ sessionStorage.removeItem(submissionKey)
+ } catch {
+ /* storage is optional */
+ }
+ await navigate({
+ to: '/compile/tasks/$taskId',
+ params: { taskId: task.task_id },
+ })
+ }
+ async function submit() {
+ if (busy) return
+ setError(null)
+ const restoredKey = submission.current ? null : recoverKey
+ setBusy(true)
+ try {
+ if (restoredKey) {
+ try {
+ const task = await lookupSubmission(restoredKey)
+ await finish(task)
+ return
+ } catch (cause) {
+ if (!isOvClientError(cause) || cause.code !== 'NOT_FOUND') throw cause
+ }
+ if (!mounted.current) return
+ const submittedAt = Number(restoredKey.split(':')[0])
+ if (
+ !Number.isFinite(submittedAt) ||
+ Date.now() - submittedAt > 86400000
+ )
+ throw new Error(t('expiredSubmission'))
+ }
+ if (!submission.current && !validate()) return
+ const body = submission.current?.request || request()
+ if (!submission.current)
+ submission.current = {
+ key: recoverKey || `${Date.now()}:${crypto.randomUUID()}`,
+ request: body,
+ }
+ const key = submission.current.key
+ try {
+ sessionStorage.setItem(submissionKey, key)
+ } catch {
+ /* optional recovery */
+ }
+ setRecoverKey(key)
+ await finish(await createCompile(body, key))
+ } catch (cause) {
+ if (mounted.current) {
+ const definite = isRejectedCompileSubmission(cause)
+ if (definite && !restoredKey) {
+ submission.current = null
+ setRecoverKey(null)
+ try {
+ sessionStorage.removeItem(submissionKey)
+ } catch {
+ /* optional */
+ }
+ }
+ // After reload the original args are unavailable. A rejection of the
+ // reconstructed request does not prove the original was never created.
+ if (restoredKey) submission.current = null
+ setError(cause)
+ setUncertain(!definite && !!submission.current)
+ }
+ } finally {
+ if (mounted.current) setBusy(false)
+ }
+ }
+ async function recover() {
+ if (!recoverKey) return
+ setBusy(true)
+ try {
+ await finish(await lookupSubmission(recoverKey))
+ } catch (cause) {
+ setError(cause)
+ } finally {
+ if (mounted.current) setBusy(false)
+ }
+ }
+ useEffect(() => {
+ if (error) document.getElementById('compile-error')?.focus()
+ }, [error])
+ const selected = skills.data?.find((s) => s.uri === draft.skill)
+ return (
+ <CompileShell title={t('new')}>
+ {recoverKey && (
+ <Button
+ variant="outline"
+ className="self-start"
+ disabled={busy}
+ onClick={() => void recover()}
+ >
+ {t('recover')}
+ </Button>
+ )}
+ {fromTask && (
+ <p className="text-sm text-muted-foreground">{t('rerunHint')}</p>
+ )}
+ {original.isError && (
+ <CompileError
+ error={original.error}
+ retry={() => void original.refetch()}
+ />
+ )}
+ {error != null && (
+ <div id="compile-error" tabIndex={-1}>
+ <CompileError error={error} />
+ </div>
+ )}
+ {uncertain && (
+ <p role="status" className="text-sm text-amber-700 dark:text-amber-400">
+ {t('unknownSubmission')}
+ </p>
+ )}
+ <form
+ noValidate
+ onSubmit={(e) => {
+ e.preventDefault()
+ void submit()
+ }}
+ className="w-full min-w-0 space-y-5"
+ >
+ <p className="text-sm text-muted-foreground">{t('formIntro')}</p>
+ <fieldset
+ disabled={busy || uncertain}
+ className="space-y-6 rounded-xl border bg-card p-5 disabled:opacity-60 sm:p-6"
+ >
+ <section className="space-y-2">
+ <label
+ htmlFor="compile-skill"
+ className="block text-sm font-medium"
+ >
+ {t('skill')} <span className="text-destructive">*</span>
+ </label>
+ <SkillPicker
+ invalid={attempted && !!fieldErrors.skill}
+ disabled={busy || uncertain || skills.isPending}
+ loading={skills.isPending}
+ value={draft.skill}
+ skills={skills.data ?? []}
+ onChange={(uri) => {
+ update('skill', uri)
+ setPreview(false)
+ }}
+ />
+ {fieldError('skill')}
+ <p className="text-xs text-muted-foreground">
+ {t('skillLocationHint')}
+ </p>
+ {skills.isError && (
+ <CompileError
+ error={skills.error}
+ retry={() => void skills.refetch()}
+ />
+ )}
+ {skills.data?.length === 0 && (
+ <Link to="/skills" className="text-sm text-primary underline">
+ {t('noSkills')}
+ </Link>
+ )}
+ {selected && (
+ <p className="text-sm text-muted-foreground">
+ {selected.description}
+ </p>
+ )}
+ {draft.skill && (
+ <Button
+ type="button"
+ variant="ghost"
+ size="sm"
+ onClick={() => setPreview((v) => !v)}
+ >
+ {t('preview')}
+ </Button>
+ )}
+ {preview && (
+ <div className="max-h-80 overflow-auto rounded-lg border p-4">
+ <pre className="whitespace-pre-wrap break-words text-xs">
+ {skillContent.data?.content || t('loading')}
+ </pre>
+ {skillContent.isError && (
+ <CompileError error={skillContent.error} />
+ )}
+ </div>
+ )}
+ </section>
+ <section className="space-y-2 border-t pt-5">
+ <label
+ htmlFor="compile-sources"
+ className="block text-sm font-medium"
+ >
+ {t('sources')} <span className="text-destructive">*</span>
+ </label>
+ <p id="source-hint" className="text-xs text-muted-foreground">
+ {t('sourceHint')}
+ </p>
+ <div className="space-y-2">
+ {sourceRows.map((uri, index) => (
+ <div key={index} className="flex items-center gap-2">
+ <Input
+ id={
+ index === 0
+ ? 'compile-sources'
+ : `compile-source-${index}`
+ }
+ aria-label={t('sourceNumber', { number: index + 1 })}
+ aria-invalid={attempted && !!fieldErrors.sources}
+ aria-describedby="source-hint error-sources"
+ placeholder={t('sourcePlaceholder')}
+ value={uri}
+ className="min-w-0 flex-1 font-mono text-xs"
+ onChange={(e) =>
+ update(
+ 'sources',
+ sourceRows
+ .map((v, i) => (i === index ? e.target.value : v))
+ .join('\n'),
+ )
+ }
+ />
+ <Button
+ type="button"
+ variant="ghost"
+ size="icon"
+ aria-label={t('removeSource', { uri: uri || index + 1 })}
+ onClick={() =>
+ update(
+ 'sources',
+ sourceRows.filter((_, i) => i !== index).join('\n'),
+ )
+ }
+ >
+ <X className="size-4" />
+ </Button>
+ </div>
+ ))}
+ </div>
+ {fieldError('sources')}
+ <div className="flex flex-wrap gap-2">
+ <Button
+ type="button"
+ variant="outline"
+ size="sm"
+ onClick={() => setPicker('sources')}
+ >
+ <FolderOpen className="size-4" />
+ {t('browse')}
+ </Button>
+ <Button
+ type="button"
+ variant="ghost"
+ size="sm"
+ onClick={() =>
+ update('sources', [...sourceRows, ''].join('\n'))
+ }
+ >
+ <Plus className="size-4" />
+ {t('addSource')}
+ </Button>
+ </div>
+ </section>
+ <section className="space-y-2">
+ <label
+ htmlFor="compile-target"
+ className="block text-sm font-medium"
+ >
+ {t('target')} <span className="text-destructive">*</span>
+ </label>
+ <div className="flex gap-2">
+ <Input
+ id="compile-target"
+ aria-invalid={attempted && !!fieldErrors.to}
+ aria-describedby="target-hint error-to"
+ className="min-w-0 flex-1 font-mono text-xs"
+ required
+ value={draft.to}
+ onChange={(e) => update('to', e.target.value)}
+ placeholder={t('targetPlaceholder')}
+ />
+ <Button
+ type="button"
+ variant="outline"
+ onClick={() => setPicker('to')}
+ >
+ {t('browse')}
+ </Button>
+ </div>
+ {fieldError('to')}
+ <p id="target-hint" className="text-xs text-muted-foreground">
+ {t('targetHint')}
+ </p>
+ </section>
+ <section className="space-y-2">
+ <label
+ htmlFor="compile-instruction"
+ className="block text-sm font-medium"
+ >
+ {t('instruction')}{' '}
+ <span className="ml-2 font-normal text-muted-foreground">
+ {t('optional')}
+ </span>
+ </label>
+ <Textarea
+ id="compile-instruction"
+ rows={2}
+ placeholder={t('instructionPlaceholder')}
+ value={draft.instruction}
+ onChange={(e) => update('instruction', e.target.value)}
+ />
+ </section>
+ <details id="compile-advanced" className="border-t pt-4">
+ <summary className="cursor-pointer rounded text-sm font-medium focus-visible:outline-2 focus-visible:outline-ring">
+ {t('advanced')}
+ </summary>
+ <ArgsEditor value={args} onChange={setArgs} />
+ <p className="mt-2 text-xs text-muted-foreground">
+ {t('argsHint')}
+ </p>
+ {fieldError('args')}
+ </details>
+ </fieldset>
+ <div className="sticky bottom-0 space-y-3 border-t bg-background/95 py-4 backdrop-blur">
+ <p className="text-xs text-muted-foreground">
+ {t(savingError ? 'storageFailed' : 'draft')}
+ </p>
+ <div className="flex flex-wrap justify-between gap-3">
+ <Button
+ type="button"
+ variant="outline"
+ onClick={() => {
+ try {
+ if (!validate()) return
+ const body = request()
+ void navigator.clipboard
+ .writeText(compileCommand(body))
+ .then(() => toast.success(t('copied')))
+ .catch(setError)
+ } catch (cause) {
+ setError(cause)
+ }
+ }}
+ >
+ {t('copyCommand')}
+ </Button>
+ <div className="flex gap-2">
+ <Button
+ type="button"
+ variant="ghost"
+ disabled={busy || uncertain}
+ onClick={() => {
+ setDraft(empty)
+ setArgs('')
+ setAttempted(false)
+ setError(null)
+ setPreview(false)
+ submission.current = null
+ setRecoverKey(null)
+ try {
+ sessionStorage.removeItem(submissionKey)
+ } catch {
+ /* optional */
+ }
+ }}
+ >
+ {t('clear')}
+ </Button>
+ <Button type="submit" disabled={busy}>
+ {t(busy ? 'submitting' : uncertain ? 'retry' : 'start')}
+ </Button>
+ </div>
+ </div>
+ </div>
+ </form>
+ <DirectoryPickerDialog
+ identityScopeKey={identityScopeKey}
+ userResourceRoot={userResourceRoot}
+ open={!!picker}
+ onOpenChange={(open) => {
+ if (!open) setPicker(null)
+ }}
+ value={picker === 'to' && draft.to ? draft.to : userResourceRoot}
+ onSelect={(uri) => {
+ if (picker === 'to') update('to', uri)
+ else
+ update(
+ 'sources',
+ [
+ ...new Set([...draft.sources.split('\n').filter(Boolean), uri]),
+ ].join('\n'),
+ )
+ setPicker(null)
+ }}
+ />
+ </CompileShell>
+ )
+}
diff --git a/web-studio/src/routes/compile/-components/shared.tsx b/web-studio/src/routes/compile/-components/shared.tsx
new file mode 100644
index 000000000..eca48e949
--- /dev/null
+++ b/web-studio/src/routes/compile/-components/shared.tsx
@@ -0,0 +1,130 @@
+import type { ReactNode } from 'react'
+import { useTranslation } from 'react-i18next'
+import { Link, useLocation, useRouter } from '@tanstack/react-router'
+import { AlertCircleIcon, ArrowLeftIcon, LoaderCircleIcon } from 'lucide-react'
+import { Badge } from '#/components/ui/badge'
+import { Button } from '#/components/ui/button'
+import { useAppConnection } from '#/hooks/use-app-connection'
+import { compileListReturn } from '../-lib/navigation'
+import { compileErrorKey } from '../-lib/errors'
+import { errorText } from '../-lib/api'
+
+export function CompileShell({
+ children,
+ title,
+ actions,
+ back = true,
+}: {
+ children: ReactNode
+ title: string
+ actions?: ReactNode
+ back?: boolean
+}) {
+ const { t } = useTranslation('compile')
+ const location = useLocation()
+ const router = useRouter()
+ const { identityScopeKey } = useAppConnection()
+ const returnTo = compileListReturn(
+ location.state.compileListOrigin,
+ identityScopeKey,
+ location.state.__TSR_index,
+ )
+ return (
+ <main className="flex w-full min-w-0 flex-col gap-6">
+ <header className="flex flex-wrap items-center justify-between gap-4">
+ <div className="min-w-0 flex-1 space-y-2">
+ {back && (
+ <Link
+ to="/compile"
+ search={returnTo.search}
+ onClick={(event) => {
+ if (
+ returnTo.restoreHistory &&
+ event.button === 0 &&
+ !event.metaKey &&
+ !event.ctrlKey &&
+ !event.shiftKey &&
+ !event.altKey
+ ) {
+ event.preventDefault()
+ router.history.back()
+ }
+ }}
+ className="inline-flex items-center gap-1 text-sm text-muted-foreground hover:text-foreground"
+ >
+ <ArrowLeftIcon className="size-4" />
+ {t('back')}
+ </Link>
+ )}
+ <h1 className="text-2xl font-semibold tracking-tight [overflow-wrap:anywhere]">
+ {title}
+ </h1>
+ {!back && (
+ <p className="text-sm text-muted-foreground">{t('description')}</p>
+ )}
+ </div>
+ <div className="flex flex-wrap gap-2">{actions}</div>
+ </header>
+ {children}
+ </main>
+ )
+}
+export function CompileError({
+ error,
+ retry,
+}: {
+ error: unknown
+ retry?: () => void
+}) {
+ const { t } = useTranslation('compile')
+ return (
+ <div
+ role="alert"
+ className="flex flex-wrap items-center gap-3 rounded-lg border border-destructive/30 bg-destructive/5 p-4 text-sm"
+ >
+ <AlertCircleIcon className="size-4 shrink-0" />
+ <div className="min-w-0 flex-1 break-words">
+ <p>{t(compileErrorKey(error))}</p>
+ <details className="mt-2">
+ <summary className="cursor-pointer">{t('errors.details')}</summary>
+ <p className="mt-1 whitespace-pre-wrap">{errorText(error)}</p>
+ </details>
+ </div>
+ {retry && (
+ <Button variant="outline" size="sm" onClick={retry}>
+ {t('retry')}
+ </Button>
+ )}
+ </div>
+ )
+}
+export function CompileLoading() {
+ const { t } = useTranslation('compile')
+ return (
+ <div
+ role="status"
+ className="flex items-center gap-2 py-8 text-muted-foreground"
+ >
+ <LoaderCircleIcon className="size-4 animate-spin" />
+ {t('loading')}
+ </div>
+ )
+}
+export function CompileStatus({ status }: { status?: string }) {
+ const { t } = useTranslation('compile')
+ const known = [
+ 'pending',
+ 'running',
+ 'cancelling',
+ 'completed',
+ 'failed',
+ 'cancelled',
+ ].includes(status || '')
+ ? status
+ : 'unknown'
+ return (
+ <Badge variant={known === 'failed' ? 'destructive' : 'secondary'}>
+ {t(`statuses.${known}`)}
+ </Badge>
+ )
+}
diff --git a/web-studio/src/routes/compile/-components/skill-picker.tsx b/web-studio/src/routes/compile/-components/skill-picker.tsx
new file mode 100644
index 000000000..f9d0d306a
--- /dev/null
+++ b/web-studio/src/routes/compile/-components/skill-picker.tsx
@@ -0,0 +1,119 @@
+import { Combobox } from '@base-ui/react/combobox'
+import { Check, ChevronsUpDown } from 'lucide-react'
+import { useTranslation } from 'react-i18next'
+import type { CompileSkill } from '../-lib/api'
+
+export function SkillPicker({
+ value,
+ skills,
+ onChange,
+ invalid,
+ disabled,
+ loading,
+}: {
+ invalid?: boolean
+ disabled?: boolean
+ loading?: boolean
+ value: string
+ skills: CompileSkill[]
+ onChange: (uri: string) => void
+}) {
+ const { t } = useTranslation('compile')
+ const selected =
+ skills.find((skill) => skill.uri === value) ??
+ (value ? { uri: value, name: value, description: '' } : null)
+ const items =
+ selected && !skills.some((skill) => skill.uri === value)
+ ? [selected, ...skills]
+ : skills
+ const groups = [
+ {
+ label: t('mySkills'),
+ items: items.filter((s) => s.uri.startsWith('viking://user/')),
+ },
+ {
+ label: t('sharedSkills'),
+ items: items.filter((s) => s.uri.startsWith('viking://agent/skills/')),
+ },
+ {
+ label: t('otherSkills'),
+ items: items.filter(
+ (s) =>
+ !s.uri.startsWith('viking://user/') &&
+ !s.uri.startsWith('viking://agent/skills/'),
+ ),
+ },
+ ].filter((group) => group.items.length)
+ return (
+ <Combobox.Root
+ items={groups}
+ disabled={disabled}
+ value={selected}
+ onValueChange={(skill) => onChange(skill?.uri ?? '')}
+ itemToStringLabel={(skill) => skill.name}
+ itemToStringValue={(skill) => skill.uri}
+ isItemEqualToValue={(a, b) => a.uri === b.uri}
+ filter={(skill, query) =>
+ `${skill.name} ${skill.description} ${skill.uri}`
+ .toLowerCase()
+ .includes(query.trim().toLowerCase())
+ }
+ >
+ <Combobox.Trigger
+ id="compile-skill"
+ aria-invalid={invalid}
+ aria-describedby="error-skill"
+ className="flex h-10 w-full items-center justify-between gap-2 rounded-md border bg-background px-3 text-left text-sm focus-visible:outline-2 focus-visible:outline-ring disabled:opacity-50"
+ >
+ <span className="truncate">
+ {selected
+ ? `${selected.name} · ${selected.uri.startsWith('viking://user/') ? t('mySkills') : t('sharedSkills')}`
+ : t(loading ? 'loading' : 'chooseSkill')}
+ </span>
+ <ChevronsUpDown className="size-4 shrink-0 text-muted-foreground" />
+ </Combobox.Trigger>
+ <Combobox.Portal>
+ <Combobox.Positioner sideOffset={4} align="start" className="z-50">
+ <Combobox.Popup className="w-[var(--anchor-width)] max-w-[calc(100vw-2rem)] rounded-md border bg-popover p-1 text-popover-foreground shadow-md">
+ <Combobox.Input
+ aria-label={t('skillSearch')}
+ placeholder={t('skillSearch')}
+ className="h-10 w-full border-b bg-transparent px-3 text-sm outline-none"
+ />
+ <Combobox.Empty className="p-3 text-sm text-muted-foreground">
+ {t('noMatchingSkills')}
+ </Combobox.Empty>
+ <Combobox.List className="max-h-64 overflow-y-auto overscroll-contain">
+ {(group: { label: string; items: CompileSkill[] }) => (
+ <Combobox.Group key={group.label} items={group.items}>
+ <Combobox.GroupLabel className="px-3 pt-3 pb-1 text-xs font-medium text-muted-foreground">
+ {group.label}
+ </Combobox.GroupLabel>
+ <Combobox.Collection>
+ {(skill: CompileSkill) => (
+ <Combobox.Item
+ key={skill.uri}
+ value={skill}
+ className="flex cursor-pointer items-center gap-2 rounded px-3 py-2 text-sm data-highlighted:bg-accent data-highlighted:text-accent-foreground"
+ >
+ <div className="min-w-0 flex-1">
+ <div className="truncate">{skill.name}</div>
+ <div className="break-all text-xs text-muted-foreground">
+ {skill.uri}
+ </div>
+ </div>
+ <Combobox.ItemIndicator>
+ <Check className="size-4" />
+ </Combobox.ItemIndicator>
+ </Combobox.Item>
+ )}
+ </Combobox.Collection>
+ </Combobox.Group>
+ )}
+ </Combobox.List>
+ </Combobox.Popup>
+ </Combobox.Positioner>
+ </Combobox.Portal>
+ </Combobox.Root>
+ )
+}
diff --git a/web-studio/src/routes/compile/-lib/api.ts b/web-studio/src/routes/compile/-lib/api.ts
new file mode 100644
index 000000000..990fc0c59
--- /dev/null
+++ b/web-studio/src/routes/compile/-lib/api.ts
@@ -0,0 +1,113 @@
+import { getOvResult, ovClient, OvClientError } from '#/lib/ov-client'
+import type { TaskRecord } from '#/routes/tasks/-lib/task-record'
+
+export type CompileRequest = {
+ from: string[]
+ to: string
+ skill: string
+ instruction?: string
+ args?: Record<string, unknown>
+}
+export type CompileTask = TaskRecord & {
+ task_id: string
+ meta?: { request?: CompileRequest }
+}
+export type TaskPage = {
+ items: CompileTask[]
+ next_cursor: string | null
+ has_more: boolean
+}
+export const active = (status?: string) =>
+ ['pending', 'running', 'cancelling'].includes(status ?? '')
+export const taskTitle = (task: CompileTask) =>
+ task.meta?.request
+ ? `${task.meta.request.skill.split('/').pop()} → ${task.meta.request.to.split('/').pop()}`
+ : task.task_id
+export const errorText = (error: unknown) =>
+ error && typeof error === 'object' && 'message' in error
+ ? String(error.message)
+ : String(error)
+export async function fetchCompileTasks(
+ status = '',
+ q = '',
+ cursor?: string,
+ signal?: AbortSignal,
+) {
+ const page = await getOvResult<TaskPage>(
+ ovClient.client.get({
+ url: '/api/v1/tasks',
+ signal,
+ query: {
+ task_type: 'compile',
+ pagination: 'cursor',
+ limit: 30,
+ ...(status ? { status } : {}),
+ ...(q ? { q } : {}),
+ ...(cursor ? { cursor } : {}),
+ },
+ }),
+ )
+ if (!Array.isArray(page.items))
+ throw new OvClientError({
+ code: 'PAGINATION_UNSUPPORTED',
+ message:
+ 'The server does not support paginated tasks. Update OpenViking and retry.',
+ })
+ return page
+}
+export function fetchCompileTask(id: string, signal?: AbortSignal) {
+ return getOvResult<CompileTask>(
+ ovClient.client.get({
+ url: `/api/v1/tasks/${encodeURIComponent(id)}`,
+ signal,
+ query: { include_events: true },
+ }),
+ )
+}
+export function createCompile(body: CompileRequest, key: string) {
+ return getOvResult<CompileTask>(
+ ovClient.client.post({
+ url: '/api/v1/compile',
+ body,
+ headers: { 'Idempotency-Key': key },
+ }),
+ )
+}
+export function cancelCompile(id: string) {
+ return getOvResult<CompileTask>(
+ ovClient.client.post({
+ url: `/api/v1/tasks/${encodeURIComponent(id)}/cancel`,
+ }),
+ )
+}
+export function fetchCapabilities() {
+ return getOvResult<{
+ configured: boolean
+ can_create: boolean
+ reason_code?: string
+ }>(ovClient.client.get({ url: '/api/v1/compile/capabilities' }))
+}
+export function lookupSubmission(key: string) {
+ return getOvResult<CompileTask>(
+ ovClient.client.get({
+ url: `/api/v1/compile/submissions/${encodeURIComponent(key)}`,
+ }),
+ )
+}
+export type CompileSkill = { name: string; uri: string; description: string }
+export async function fetchCompileSkills(
+ signal?: AbortSignal,
+): Promise<CompileSkill[]> {
+ const result = await getOvResult<{
+ skills: Array<{
+ name: string
+ uri?: string
+ root_uri?: string
+ description?: string
+ }>
+ }>(ovClient.client.get({ url: '/api/v1/skills', signal }))
+ return result.skills.flatMap((s) => {
+ const uri = s.uri || s.root_uri
+ return uri ? [{ name: s.name, uri, description: s.description || '' }] : []
+ })
+}
diff --git a/web-studio/src/routes/compile/-lib/commands.test.ts b/web-studio/src/routes/compile/-lib/commands.test.ts
new file mode 100644
index 000000000..15e26d876
--- /dev/null
+++ b/web-studio/src/routes/compile/-lib/commands.test.ts
@@ -0,0 +1,87 @@
+import { describe, expect, it } from 'vitest'
+import {
+ compileCommand,
+ compileHistory,
+ parseArgs,
+ parseCompile,
+ tokenize,
+} from './commands'
+
+import { compileSuggestions } from './suggestions'
+import {
+ clearCompileHandoff,
+ prepareCompileHandoff,
+ readCompileHandoff,
+} from './handoff'
+
+describe('Compile command grammar', () => {
+ it('round trips paths, quotes, spaces and unicode without shell execution', () => {
+ const request = {
+ from: ['viking://resources/团队 资料', "viking://resources/John's"],
+ to: 'viking://resources/wiki',
+ skill: 'viking://agent/skills/wiki',
+ instruction: 'Keep "quotes" and $literal `text`',
+ }
+ expect(parseCompile(tokenize(compileCommand(request)))).toEqual(request)
+ })
+ it('accepts repeated sources and quoted JSON', () => {
+ expect(
+ parseCompile(
+ tokenize(
+ `compile --from viking://resources/a --from viking://resources/b --to viking://resources/c --skill viking://agent/skills/wiki --args '{"model_name":"hello world"}'`,
+ ),
+ ).args,
+ ).toEqual({ model_name: 'hello world' })
+ })
+ it('rejects incomplete flags and shell operators', () => {
+ expect(() => parseCompile(tokenize('compile --from'))).toThrow()
+ expect(() => tokenize('compile | sh')).toThrow()
+ expect(() => tokenize('compile "unfinished')).toThrow()
+ expect(() => parseArgs('[]')).toThrow()
+ })
+ it('never puts private arguments into copied commands', () => {
+ expect(
+ compileCommand({
+ from: ['viking://resources/a'],
+ to: 'viking://resources/b',
+ skill: 'viking://agent/skills/s',
+ args: { api_key: 'private' },
+ }),
+ ).not.toContain('private')
+ })
+})
+
+it('completes a Skill URI and keeps handoff scoped to the identity', () => {
+ expect(
+ compileSuggestions('compile --skill ', [], ['viking://agent/skills/wiki']),
+ ).toEqual(['compile --skill "viking://agent/skills/wiki" '])
+ prepareCompileHandoff(
+ 'alice',
+ 'compile --from viking://resources/a --instruction "keep sources" --skill',
+ )
+ expect(readCompileHandoff('bob')).toBeUndefined()
+ expect(readCompileHandoff('alice')).toEqual({
+ from: ['viking://resources/a'],
+ instruction: 'keep sources',
+ })
+ clearCompileHandoff()
+ expect(readCompileHandoff('alice')).toBeUndefined()
+})
+
+it.each(['--args', "'--args'", '"--args"', String.raw`--ar\gs`])(
+ 'omits private args from history for %s',
+ (flag) => {
+ const command = `compile --from viking://resources/a --to viking://resources/b --skill viking://agent/skills/s ${flag} '{"api_key":"synthetic-secret"}'`
+ expect(parseCompile(tokenize(command)).args).toEqual({
+ api_key: 'synthetic-secret',
+ })
+ const history = compileHistory(command)
+ expect(JSON.stringify(history)).not.toContain('synthetic-secret')
+ expect(history.remember).toBe(false)
+ },
+)
+it('does not persist malformed commands containing private args', () => {
+ expect(
+ compileHistory(`compile --args '{"api_key":"synthetic-secret"}`),
+ ).toEqual({ title: 'compile / task', remember: false })
+})
diff --git a/web-studio/src/routes/compile/-lib/commands.ts b/web-studio/src/routes/compile/-lib/commands.ts
new file mode 100644
index 000000000..641a6c0cf
--- /dev/null
+++ b/web-studio/src/routes/compile/-lib/commands.ts
@@ -0,0 +1,149 @@
+import type { CompileRequest } from './api'
+
+export class CompileCommandError extends Error {
+ constructor(
+ readonly code:
+ | 'shellSyntax'
+ | 'unclosedQuote'
+ | 'invalidArgument'
+ | 'duplicateArgument'
+ | 'required'
+ | 'argsObject'
+ | 'unknownCommand'
+ | 'taskUsage'
+ | 'missingValue'
+ | 'listUsage'
+ | 'pendingSubmission'
+ | 'expiredSubmission',
+ ) {
+ super(code)
+ this.name = 'CompileCommandError'
+ }
+}
+
+/** Tokenize the documented CLI subset, without executing shell syntax. */
+export function tokenize(input: string): string[] {
+ const tokens: string[] = []
+ let value = '',
+ quote = '',
+ escaped = false,
+ started = false
+ for (const c of input.trim()) {
+ if (escaped) {
+ value += c
+ escaped = false
+ started = true
+ continue
+ }
+ if (c === '\\' && quote !== "'") {
+ escaped = true
+ continue
+ }
+ if (quote) {
+ if (c === quote) quote = ''
+ else value += c
+ continue
+ }
+ if (c === '"' || c === "'") {
+ quote = c
+ started = true
+ continue
+ }
+ if (/\s/.test(c)) {
+ if (started) tokens.push(value)
+ value = ''
+ started = false
+ continue
+ }
+ if ('|;&<>`'.includes(c) || c === '$')
+ throw new CompileCommandError('shellSyntax')
+ value += c
+ started = true
+ }
+ if (quote || escaped) throw new CompileCommandError('unclosedQuote')
+ if (started) tokens.push(value)
+ const result = tokens[0] === 'ov' ? tokens.slice(1) : tokens
+ if (result[0]?.startsWith('/')) result[0] = result[0].slice(1)
+ return result
+}
+export function parseCompile(tokens: string[]): CompileRequest {
+ const result: CompileRequest = { from: [], to: '', skill: '' }
+ const seen = new Set<string>()
+ for (let i = 1; i < tokens.length; i += 2) {
+ const key = tokens[i],
+ value = tokens[i + 1]
+ if (
+ !['--from', '--to', '--skill', '--instruction', '--args'].includes(key) ||
+ i + 1 >= tokens.length
+ )
+ throw new CompileCommandError('invalidArgument')
+ if (key !== '--from' && seen.has(key))
+ throw new CompileCommandError('duplicateArgument')
+ seen.add(key)
+ if (key === '--from') result.from.push(...value.split(','))
+ else if (key === '--args') result.args = parseArgs(value)
+ else if (key === '--to') result.to = value
+ else if (key === '--skill') result.skill = value
+ else result.instruction = value
+ }
+ if (
+ !result.from.length ||
+ result.from.some((v) => !v.trim()) ||
+ !result.to ||
+ !result.skill
+ )
+ throw new CompileCommandError('required')
+ result.from = [...new Set(result.from.map((v) => v.trim()))]
+ return result
+}
+export function parseArgs(value: string): Record<string, unknown> | undefined {
+ if (!value.trim()) return undefined
+ let parsed: unknown
+ try {
+ parsed = JSON.parse(value)
+ } catch {
+ throw new CompileCommandError('argsObject')
+ }
+ if (!parsed || typeof parsed !== 'object' || Array.isArray(parsed))
+ throw new CompileCommandError('argsObject')
+ return parsed as Record<string, unknown>
+}
+const quote = (value: string) => `'${value.replaceAll("'", "'\\''")}'`
+export function compileCommand(request: CompileRequest): string {
+ return [
+ 'ov compile',
+ ...request.from.map((uri) => `--from ${quote(uri)}`),
+ `--to ${quote(request.to)}`,
+ `--skill ${quote(request.skill)}`,
+ ...(request.instruction
+ ? [`--instruction ${quote(request.instruction)}`]
+ : []),
+ ].join(' ')
+}
+export const isCompileCommand = (input: string) =>
+ /^(?:ov\s+)?(?:\/?compile|\/?task)(?:\s|$)/.test(input.trim())
+
+/** Persist only parsed public fields; malformed input must never echo raw args. */
+export function compileHistory(input: string): {
+ title: string
+ remember: boolean
+} {
+ try {
+ const tokens = tokenize(input)
+ if (tokens[0] === 'compile') {
+ const request = parseCompile(tokens)
+ return {
+ title: compileCommand(request),
+ remember: !tokens.includes('--args'),
+ }
+ }
+ if (
+ tokens[0] === 'task' &&
+ !tokens.some((token) => token.startsWith('--args'))
+ )
+ return { title: input, remember: true }
+ return { title: 'task', remember: false }
+ } catch {
+ return { title: 'compile / task', remember: false }
+ }
+}
diff --git a/web-studio/src/routes/compile/-lib/errors.ts b/web-studio/src/routes/compile/-lib/errors.ts
new file mode 100644
index 000000000..37f4f2cd7
--- /dev/null
+++ b/web-studio/src/routes/compile/-lib/errors.ts
@@ -0,0 +1,37 @@
+import { isOvClientError } from '#/lib/ov-client'
+
+const errorKeys = {
+ INVALID_URI: 'errors.invalidArgument',
+ INVALID_ARGUMENT: 'errors.invalidArgument',
+ NOT_FOUND: 'errors.notFound',
+ PERMISSION_DENIED: 'errors.permissionDenied',
+ UNAUTHENTICATED: 'errors.unauthenticated',
+ CONFLICT: 'errors.conflict',
+ NETWORK_ERROR: 'errors.network',
+ PAGINATION_UNSUPPORTED: 'errors.upgrade',
+} as const
+
+export function compileErrorKey(error: unknown) {
+ const code =
+ error && typeof error === 'object' && 'code' in error
+ ? String(error.code)
+ : ''
+ return Object.hasOwn(errorKeys, code)
+ ? errorKeys[code as keyof typeof errorKeys]
+ : 'errors.generic'
+}
+
+/** These responses confirm that this request was rejected before creation. */
+export function isRejectedCompileSubmission(error: unknown): boolean {
+ return (
+ isOvClientError(error) &&
+ [
+ 'INVALID_ARGUMENT',
+ 'INVALID_URI',
+ 'NOT_FOUND',
+ 'PERMISSION_DENIED',
+ 'UNAUTHENTICATED',
+ 'CONFLICT',
+ ].includes(error.code)
+ )
+}
diff --git a/web-studio/src/routes/compile/-lib/handoff.ts b/web-studio/src/routes/compile/-lib/handoff.ts
new file mode 100644
index 000000000..cea396ac7
--- /dev/null
+++ b/web-studio/src/routes/compile/-lib/handoff.ts
@@ -0,0 +1,32 @@
+import type { CompileRequest } from './api'
+import { parseArgs, tokenize } from './commands'
+
+let handoff: { scope: string; request: Partial<CompileRequest> } | undefined
+export const readCompileHandoff = (scope: string) =>
+ handoff?.scope === scope ? handoff.request : undefined
+export const clearCompileHandoff = () => {
+ handoff = undefined
+}
+export function prepareCompileHandoff(scope: string, input: string) {
+ const request: Partial<CompileRequest> = { from: [] }
+ try {
+ const tokens = tokenize(input)
+ if (tokens[0] !== 'compile') {
+ handoff = undefined
+ return
+ }
+ for (let i = 1; i + 1 < tokens.length; i += 2) {
+ const key = tokens[i],
+ value = tokens[i + 1]
+ if (key === '--from')
+ request.from?.push(...value.split(',').filter(Boolean))
+ if (key === '--to') request.to = value
+ if (key === '--skill') request.skill = value
+ if (key === '--instruction') request.instruction = value
+ if (key === '--args') request.args = parseArgs(value)
+ }
+ } catch {
+ /* Keep only successfully parsed, in-memory values. */
+ }
+ handoff = { scope, request }
+}
diff --git a/web-studio/src/routes/compile/-lib/navigation.test.ts b/web-studio/src/routes/compile/-lib/navigation.test.ts
new file mode 100644
index 000000000..7238f4d08
--- /dev/null
+++ b/web-studio/src/routes/compile/-lib/navigation.test.ts
@@ -0,0 +1,70 @@
+import {
+ createMemoryHistory,
+ createRootRoute,
+ createRoute,
+ createRouter,
+} from '@tanstack/react-router'
+import { expect, it } from 'vitest'
+import { compileListReturn } from './navigation'
+
+it('restores the original filtered history entry and scroll-restoration key', async () => {
+ const root = createRootRoute()
+ const list = createRoute({
+ getParentRoute: () => root,
+ path: '/compile',
+ validateSearch: (search: Record<string, unknown>) => ({
+ status: String(search.status || ''),
+ q: String(search.q || ''),
+ }),
+ })
+ const detail = createRoute({
+ getParentRoute: () => root,
+ path: '/compile/tasks/$taskId',
+ })
+ const router = createRouter({
+ routeTree: root.addChildren([list, detail]),
+ history: createMemoryHistory({
+ initialEntries: ['/compile?status=running&q=wiki'],
+ }),
+ scrollRestoration: true,
+ })
+ await router.load()
+ const original = router.state.location
+ await router.navigate({
+ to: '/compile/tasks/$taskId',
+ params: { taskId: 'task-1' },
+ state: {
+ compileListOrigin: {
+ scope: 'alice',
+ index: original.state.__TSR_index,
+ search: { status: 'running', q: 'wiki' },
+ },
+ },
+ })
+ const location = router.state.location
+ const destination = compileListReturn(
+ location.state.compileListOrigin,
+ 'alice',
+ location.state.__TSR_index,
+ )
+ expect(destination.search).toEqual({ status: 'running', q: 'wiki' })
+ expect(destination.restoreHistory).toBe(true)
+ router.history.back()
+ await router.load()
+ expect(router.state.location.href).toBe(original.href)
+ expect(router.state.location.state.__TSR_key).toBe(original.state.__TSR_key)
+})
+
+it('defaults to the list for direct links or a different identity', () => {
+ expect(compileListReturn(undefined, 'alice', 0)).toEqual({
+ search: {},
+ restoreHistory: false,
+ })
+ expect(
+ compileListReturn(
+ { scope: 'alice', index: 0, search: { q: 'private-path' } },
+ 'bob',
+ 1,
+ ),
+ ).toEqual({ search: {}, restoreHistory: false })
+})
diff --git a/web-studio/src/routes/compile/-lib/navigation.ts b/web-studio/src/routes/compile/-lib/navigation.ts
new file mode 100644
index 000000000..40f553a08
--- /dev/null
+++ b/web-studio/src/routes/compile/-lib/navigation.ts
@@ -0,0 +1,23 @@
+export type CompileListOrigin = {
+ scope: string
+ index: number
+ search: { status?: string; q?: string }
+}
+
+declare module '@tanstack/react-router' {
+ interface HistoryState {
+ compileListOrigin?: CompileListOrigin
+ }
+}
+
+export function compileListReturn(
+ origin: CompileListOrigin | undefined,
+ scope: string,
+ currentIndex: number,
+) {
+ const sameIdentity = origin?.scope === scope
+ return {
+ search: sameIdentity ? origin.search : {},
+ restoreHistory: sameIdentity && currentIndex === origin.index + 1,
+ }
+}
diff --git a/web-studio/src/routes/compile/-lib/suggestions.ts b/web-studio/src/routes/compile/-lib/suggestions.ts
new file mode 100644
index 000000000..afde64c0c
--- /dev/null
+++ b/web-studio/src/routes/compile/-lib/suggestions.ts
@@ -0,0 +1,23 @@
+/** Complete only the current argument; never execute or expand shell input. */
+export function compileSuggestions(
+ input: string,
+ directories: string[],
+ skills: string[],
+): string[] {
+ if (/^(?:ov\s+)?\/?comp\w*$/.test(input)) return ['compile --from ']
+ if (!/^(?:ov\s+)?\/?compile\s/.test(input)) return []
+ const argument = input.match(/^(.*\s)(--from|--to|--skill)\s+([^\s]*)$/)
+ if (argument) {
+ const candidates = argument[2] === '--skill' ? skills : directories
+ return [...new Set(candidates)]
+ .filter((uri) => uri.toLowerCase().includes(argument[3].toLowerCase()))
+ .slice(0, 8)
+ .map((uri) => `${argument[1]}${argument[2]} ${JSON.stringify(uri)} `)
+ }
+ const flag = input.match(/^(.*\s)(--[\w-]*)?$/)
+ return flag
+ ? ['--from', '--to', '--skill', '--instruction', '--args']
+ .filter((value) => value.startsWith(flag[2] || ''))
+ .map((value) => `${flag[1]}${value} `)
+ : []
+}
diff --git a/web-studio/src/routes/compile/-lib/terminal.test.ts b/web-studio/src/routes/compile/-lib/terminal.test.ts
new file mode 100644
index 000000000..48be498dd
--- /dev/null
+++ b/web-studio/src/routes/compile/-lib/terminal.test.ts
@@ -0,0 +1,244 @@
+import { beforeEach, describe, expect, it, vi } from 'vitest'
+import { createInstance } from 'i18next'
+import { OvClientError } from '#/lib/ov-client'
+import { runCompileCommand, runCompileSubmission } from './terminal'
+import { CompileCommandError } from './commands'
+import en from '#/i18n/locales/en/compile'
+import zh from '#/i18n/locales/zh-CN/compile'
+
+const api = vi.hoisted(() => ({
+ createCompile: vi.fn(),
+ lookupSubmission: vi.fn(),
+ fetchCompileTasks: vi.fn(),
+ fetchCompileTask: vi.fn(),
+ cancelCompile: vi.fn(),
+}))
+vi.mock('./api', () => api)
+beforeEach(() => vi.resetAllMocks())
+
+describe('Compile terminal regressions', () => {
+ it('keeps status filters in the executable next-page command', async () => {
+ api.fetchCompileTasks
+ .mockResolvedValueOnce({ items: [], next_cursor: 'signed-cursor' })
+ .mockResolvedValueOnce({ items: [], next_cursor: null })
+ const page = await runCompileCommand('task list --status running', 'key')
+ await runCompileCommand(page.body.trim(), 'key')
+ expect(api.fetchCompileTasks.mock.calls).toEqual([
+ ['running', '', undefined],
+ ['running', '', 'signed-cursor'],
+ ])
+ })
+
+ it.each(['en', 'zh-CN'])(
+ 'localizes known statuses and errors in %s without echoing private args',
+ async (lng) => {
+ const i18n = createInstance()
+ await i18n.init({
+ lng,
+ resources: { en: { compile: en }, 'zh-CN': { compile: zh } },
+ defaultNS: 'compile',
+ })
+ api.fetchCompileTask.mockResolvedValue({
+ task_id: 'task-1',
+ status: 'running',
+ stage: 'custom-stage',
+ })
+ const result = await runCompileCommand(
+ 'task status task-1',
+ 'key',
+ (status) => i18n.t(`statuses.${status}`, { defaultValue: status }),
+ )
+ expect(result.body).toContain(lng === 'en' ? 'Running' : '运行中')
+ expect(result.body).toContain('custom-stage')
+ const input = `compile --from viking://resources/a --to viking://resources/b --skill viking://agent/skills/s --args='{"api_key":"private-example"}'`
+ const error: unknown = await runCompileCommand(input, 'key').catch(
+ (cause: unknown) => cause,
+ )
+ expect(error).toBeInstanceOf(CompileCommandError)
+ if (!(error instanceof CompileCommandError))
+ throw new Error('Expected command error')
+ const storedEntry = JSON.stringify({
+ body: i18n.t(`commandErrors.${error.code}`),
+ })
+ expect(error.message).not.toContain('private-example')
+ expect(storedEntry).not.toContain('private-example')
+ expect(storedEntry).not.toContain('commandErrors.')
+ expect(api.createCompile).not.toHaveBeenCalled()
+ },
+ )
+})
+
+it('retains the creation key across response loss and task queries', async () => {
+ const pending = { current: null }
+ const saveKey = vi.fn()
+ const status = (value: string) => value
+ const command =
+ 'compile --from viking://resources/a --to viking://resources/b --skill viking://agent/skills/s'
+ const tasks = new Map<string, string>()
+ api.createCompile.mockImplementation(async (_body, key: string) => {
+ if (!tasks.has(key)) tasks.set(key, `task-${tasks.size + 1}`)
+ if (api.createCompile.mock.calls.length === 1)
+ throw new Error('response lost')
+ return { task_id: tasks.get(key), status: 'pending' }
+ })
+ api.fetchCompileTasks.mockResolvedValue({ items: [], next_cursor: null })
+ await expect(
+ runCompileSubmission(command, pending, status, saveKey),
+ ).rejects.toThrow('response lost')
+ await runCompileSubmission('task list', pending, status, saveKey)
+ await expect(
+ runCompileSubmission(
+ command + ' --instruction changed',
+ pending,
+ status,
+ saveKey,
+ ),
+ ).rejects.toThrow('pendingSubmission')
+ const recovered = await runCompileSubmission(
+ command,
+ pending,
+ status,
+ saveKey,
+ )
+ expect(recovered.taskId).toBe('task-1')
+ expect(tasks.size).toBe(1)
+ expect(api.createCompile.mock.calls[0][1]).toBe(
+ api.createCompile.mock.calls[1][1],
+ )
+ expect(pending.current).toBeNull()
+ expect(saveKey).toHaveBeenLastCalledWith(null)
+})
+
+it.each(['INVALID_ARGUMENT', 'INVALID_URI'])(
+ 'releases %s so parameters can be corrected',
+ async (code) => {
+ const pending = { current: null }
+ api.createCompile.mockRejectedValueOnce(
+ new OvClientError({ code, message: 'Invalid URI' }),
+ )
+ const command =
+ 'compile --from viking://resources/a --to viking://resources/b --skill viking://agent/skills/s'
+ await expect(
+ runCompileSubmission(command, pending, String, vi.fn()),
+ ).rejects.toThrow('Invalid URI')
+ expect(pending.current).toBeNull()
+ },
+)
+
+const retryCommand =
+ 'compile --from viking://resources/a --to viking://resources/b --skill viking://agent/skills/s'
+it('recovers a persisted submission after remount without creating again', async () => {
+ let saved: string | null = null
+ const save = (key: string | null) => {
+ saved = key
+ }
+ api.createCompile.mockRejectedValueOnce(new Error('response lost'))
+ await expect(
+ runCompileSubmission(retryCommand, { current: null }, String, save),
+ ).rejects.toThrow('response lost')
+ const originalKey = saved
+ api.lookupSubmission.mockResolvedValueOnce({
+ task_id: 'original-task',
+ status: 'pending',
+ })
+ const result = await runCompileSubmission(
+ retryCommand,
+ { current: null },
+ String,
+ save,
+ () => saved,
+ )
+ expect(result.taskId).toBe('original-task')
+ expect(api.lookupSubmission).toHaveBeenCalledWith(originalKey)
+ expect(api.createCompile).toHaveBeenCalledTimes(1)
+ expect(saved).toBeNull()
+})
+it('reuses the persisted key when lookup races creation, including after conflict', async () => {
+ const key = `${Date.now()}:saved-key`
+ const pending = { current: null }
+ const save = vi.fn()
+ api.lookupSubmission.mockRejectedValue(
+ new OvClientError({ code: 'NOT_FOUND', message: 'not found' }),
+ )
+ api.createCompile.mockRejectedValueOnce(
+ new OvClientError({ code: 'CONFLICT', message: 'different request' }),
+ )
+ await expect(
+ runCompileSubmission(
+ retryCommand + ' --instruction changed',
+ pending,
+ String,
+ save,
+ () => key,
+ ),
+ ).rejects.toThrow('different request')
+ expect(pending.current).toBeNull()
+ expect(save).not.toHaveBeenCalledWith(null)
+ api.createCompile.mockResolvedValueOnce({
+ task_id: 'original-task',
+ status: 'pending',
+ })
+ await runCompileSubmission(retryCommand, pending, String, save, () => key)
+ expect(api.createCompile.mock.calls.map((call) => call[1])).toEqual([
+ key,
+ key,
+ ])
+})
+it('does not create after a failed recovery lookup or expired key', async () => {
+ api.lookupSubmission.mockRejectedValueOnce(new Error('offline'))
+ await expect(
+ runCompileSubmission(
+ retryCommand,
+ { current: null },
+ String,
+ vi.fn(),
+ () => `${Date.now()}:saved`,
+ ),
+ ).rejects.toThrow('offline')
+ api.lookupSubmission.mockRejectedValueOnce(
+ new OvClientError({ code: 'NOT_FOUND', message: 'not found' }),
+ )
+ await expect(
+ runCompileSubmission(
+ retryCommand,
+ { current: null },
+ String,
+ vi.fn(),
+ () => `1:expired`,
+ ),
+ ).rejects.toThrow('expiredSubmission')
+ expect(api.createCompile).not.toHaveBeenCalled()
+})
+
+it('localizes known stages while preserving unknown provider stages', async () => {
+ const i18n = createInstance()
+ await i18n.init({
+ lng: 'zh-CN',
+ resources: { 'zh-CN': { compile: zh } },
+ defaultNS: 'compile',
+ })
+ const localizeStage = (stage: string) =>
+ i18n.t(`stages.${stage.replace(/^compile:\s*/, '')}`, {
+ defaultValue: stage,
+ })
+ for (const stage of ['compile: queued', 'custom-stage']) {
+ api.fetchCompileTask.mockResolvedValueOnce({
+ task_id: 't',
+ status: 'running',
+ stage,
+ })
+ const result = await runCompileSubmission(
+ 'task status t',
+ { current: null },
+ String,
+ vi.fn(),
+ () => null,
+ localizeStage,
+ )
+ expect(result.body).toContain(
+ stage === 'custom-stage' ? stage : i18n.t('stages.queued'),
+ )
+ if (stage !== 'custom-stage')
+ expect(result.body).not.toContain('compile: queued')
+ }
+})
diff --git a/web-studio/src/routes/compile/-lib/terminal.ts b/web-studio/src/routes/compile/-lib/terminal.ts
new file mode 100644
index 000000000..f8a751768
--- /dev/null
+++ b/web-studio/src/routes/compile/-lib/terminal.ts
@@ -0,0 +1,130 @@
+import { isOvClientError } from '#/lib/ov-client'
+import {
+ lookupSubmission,
+ cancelCompile,
+ createCompile,
+ fetchCompileTask,
+ fetchCompileTasks,
+} from './api'
+import { isRejectedCompileSubmission } from './errors'
+import { CompileCommandError, parseCompile, tokenize } from './commands'
+
+export async function runCompileCommand(
+ input: string,
+ key: string,
+ localizeStatus: (status: string) => string = (status) => status,
+ localizeStage: (stage: string) => string = (stage) => stage,
+): Promise<{ body: string; taskId?: string }> {
+ const tokens = tokenize(input)
+ if (tokens[0] === 'compile') {
+ const task = await createCompile(parseCompile(tokens), key)
+ return {
+ body: `${task.task_id}\n${localizeStatus(task.status || 'unknown')}\n${task.meta?.request?.to || ''}`,
+ taskId: task.task_id,
+ }
+ }
+ if (tokens[0] !== 'task') throw new CompileCommandError('unknownCommand')
+ if (tokens[1] === 'status' || tokens[1] === 'cancel') {
+ if (tokens.length !== 3) throw new CompileCommandError('taskUsage')
+ const task = await (
+ tokens[1] === 'status' ? fetchCompileTask : cancelCompile
+ )(tokens[2])
+ return {
+ body: `${task.task_id}\n${localizeStatus(task.status || 'unknown')}\n${localizeStage(task.stage || '')}\n${task.error || ''}`,
+ taskId: task.task_id,
+ }
+ }
+ if (tokens[1] === 'list') {
+ let status = '',
+ cursor: string | undefined
+ for (let i = 2; i < tokens.length; i += 2) {
+ if (!tokens[i + 1]) throw new CompileCommandError('missingValue')
+ if (tokens[i] === '--status') status = tokens[i + 1]
+ else if (tokens[i] === '--cursor') cursor = tokens[i + 1]
+ else if (tokens[i] !== '--task-type' || tokens[i + 1] !== 'compile')
+ throw new CompileCommandError('listUsage')
+ }
+ const page = await fetchCompileTasks(status, '', cursor)
+ return {
+ body:
+ page.items
+ .map(
+ (task) =>
+ `${task.task_id} ${localizeStatus(task.status || 'unknown')}`,
+ )
+ .join('\n') +
+ (page.next_cursor
+ ? `\n\ntask list --task-type compile${status ? ` --status ${status}` : ''} --cursor ${page.next_cursor}`
+ : ''),
+ }
+ }
+ throw new CompileCommandError('taskUsage')
+}
+
+export type PendingCompileSubmission = { raw: string; key: string }
+
+/** Task queries must not consume an unresolved creation's idempotency key. */
+export async function runCompileSubmission(
+ input: string,
+ pending: { current: PendingCompileSubmission | null },
+ localizeStatus: (status: string) => string,
+ saveKey: (key: string | null) => void,
+ readKey: () => string | null = () => null,
+ localizeStage: (stage: string) => string = (stage) => stage,
+) {
+ const tokens = tokenize(input)
+ if (tokens[0] !== 'compile')
+ return runCompileCommand(input, '', localizeStatus, localizeStage)
+ parseCompile(tokens)
+ // A remounted terminal has no private request in memory. Resolve the saved
+ // submission before interpreting the command as a new creation.
+ const restoredKey = pending.current ? null : readKey()
+ if (restoredKey) {
+ try {
+ const task = await lookupSubmission(restoredKey)
+ saveKey(null)
+ return {
+ body: `${task.task_id}\n${localizeStatus(task.status || 'unknown')}\n${task.meta?.request?.to || ''}`,
+ taskId: task.task_id,
+ }
+ } catch (error) {
+ if (!isOvClientError(error) || error.code !== 'NOT_FOUND') throw error
+ }
+ const submittedAt = Number(restoredKey.split(':')[0])
+ if (!Number.isFinite(submittedAt) || Date.now() - submittedAt > 86400000)
+ throw new CompileCommandError('expiredSubmission')
+ }
+ if (pending.current && pending.current.raw !== input)
+ throw new CompileCommandError('pendingSubmission')
+ const submission = pending.current ?? {
+ raw: input,
+ key: restoredKey || `${Date.now()}:${crypto.randomUUID()}`,
+ }
+ pending.current = submission
+ saveKey(submission.key)
+ try {
+ const result = await runCompileCommand(
+ input,
+ submission.key,
+ localizeStatus,
+ )
+ if (pending.current === submission) {
+ pending.current = null
+ saveKey(null)
+ }
+ return result
+ } catch (error) {
+ if (
+ pending.current === submission &&
+ isRejectedCompileSubmission(error) &&
+ !restoredKey
+ ) {
+ pending.current = null
+ saveKey(null)
+ }
+ // A restored request may differ from the original. Keep its key so a
+ // conflict cannot turn the next correction into a duplicate creation.
+ if (restoredKey && pending.current === submission) pending.current = null
+ throw error
+ }
+}
diff --git a/web-studio/src/routes/compile/index.tsx b/web-studio/src/routes/compile/index.tsx
new file mode 100644
index 000000000..b34c27e82
--- /dev/null
+++ b/web-studio/src/routes/compile/index.tsx
@@ -0,0 +1,309 @@
+import { useEffect, useState } from 'react'
+import { useInfiniteQuery, useQuery } from '@tanstack/react-query'
+import {
+ createFileRoute,
+ Link,
+ useNavigate,
+ useLocation,
+} from '@tanstack/react-router'
+import {
+ PlusIcon,
+ RefreshCwIcon,
+ SparklesIcon,
+ FolderOutput,
+ FolderInput,
+ ChevronRight,
+ Search,
+} from 'lucide-react'
+import { useTranslation } from 'react-i18next'
+import { Button } from '#/components/ui/button'
+import { Input } from '#/components/ui/input'
+import { useAppConnection } from '#/hooks/use-app-connection'
+import {
+ CompileError,
+ CompileLoading,
+ CompileShell,
+ CompileStatus,
+} from './-components/shared'
+import { fetchCapabilities, fetchCompileTasks } from './-lib/api'
+
+const STATUSES = [
+ 'pending',
+ 'running',
+ 'cancelling',
+ 'completed',
+ 'failed',
+ 'cancelled',
+] as const
+
+export const Route = createFileRoute('/compile/')({
+ validateSearch: (
+ search: Record<string, unknown>,
+ ): { status?: string; q?: string } => ({
+ status: typeof search.status === 'string' ? search.status : '',
+ q: typeof search.q === 'string' ? search.q : '',
+ }),
+ component: CompileList,
+})
+function CompileList() {
+ const { t, i18n } = useTranslation('compile')
+ const { identityScopeKey } = useAppConnection()
+ const location = useLocation()
+ const search = Route.useSearch(),
+ navigate = useNavigate()
+ const [input, setInput] = useState(search.q || '')
+ useEffect(() => {
+ setInput(search.q || '')
+ }, [search.q])
+ useEffect(() => {
+ const timer = setTimeout(() => {
+ if (input !== search.q)
+ void navigate({
+ to: '/compile',
+ search: { ...search, q: input },
+ replace: true,
+ })
+ }, 300)
+ return () => clearTimeout(timer)
+ }, [input, navigate, search])
+ const query = useInfiniteQuery({
+ queryKey: ['compile-list', identityScopeKey, search],
+ initialPageParam: undefined as string | undefined,
+ queryFn: ({ pageParam, signal }) =>
+ fetchCompileTasks(search.status, search.q, pageParam, signal),
+ getNextPageParam: (page) => page.next_cursor || undefined,
+ })
+ const capability = useQuery({
+ queryKey: ['compile-capability', identityScopeKey],
+ queryFn: fetchCapabilities,
+ retry: false,
+ })
+ const latest = useQuery({
+ queryKey: ['compile-latest', identityScopeKey, search],
+ queryFn: ({ signal }) =>
+ fetchCompileTasks(search.status, search.q, undefined, signal),
+ enabled: !!query.data,
+ refetchInterval: 10_000,
+ })
+ const latestById = new Map(
+ latest.data?.items.map((task) => [task.task_id, task]),
+ )
+ const loadedIds = new Set(
+ query.data?.pages.flatMap((page) => page.items.map((task) => task.task_id)),
+ )
+ const hasNew = latest.data?.items.some((task) => !loadedIds.has(task.task_id))
+ const tasks = [
+ ...new Map(
+ query.data?.pages
+ .flatMap((p) => p.items)
+ .map((task) => [task.task_id, latestById.get(task.task_id) || task]),
+ ).values(),
+ ]
+ return (
+ <CompileShell
+ back={false}
+ title={t('title')}
+ actions={
+ <Button
+ disabled={capability.data?.can_create === false}
+ onClick={() => void navigate({ to: '/compile/new' })}
+ >
+ <PlusIcon />
+ {t('new')}
+ </Button>
+ }
+ >
+ {capability.data?.can_create === false && (
+ <p role="status" className="rounded-lg border bg-muted/30 p-4 text-sm">
+ {t('unconfigured')}
+ </p>
+ )}
+ <div className="flex flex-wrap items-center gap-3">
+ <div className="relative w-full sm:max-w-md">
+ <Search className="pointer-events-none absolute left-3 top-1/2 size-4 -translate-y-1/2 text-muted-foreground" />
+ <Input
+ aria-label={t('search')}
+ placeholder={t('search')}
+ value={input}
+ onChange={(e) => setInput(e.target.value)}
+ className="pl-9"
+ />
+ </div>
+ <select
+ aria-label={t('status')}
+ className="h-9 rounded-md border bg-background px-3 text-sm"
+ value={search.status}
+ onChange={(e) =>
+ void navigate({
+ to: '/compile',
+ search: { ...search, status: e.target.value },
+ })
+ }
+ >
+ <option value="">{t('all')}</option>
+ {STATUSES.map((status) => (
+ <option key={status} value={status}>
+ {t(`statuses.${status}`)}
+ </option>
+ ))}
+ </select>
+ <Button
+ variant="outline"
+ disabled={query.isFetching}
+ onClick={() => void query.refetch()}
+ >
+ <RefreshCwIcon />
+ {t('refresh')}
+ </Button>
+ </div>
+ {hasNew && (
+ <Button
+ variant="outline"
+ className="self-start"
+ onClick={() => void query.refetch()}
+ >
+ {t('newTasks')}
+ </Button>
+ )}
+ {query.isLoading ? (
+ <CompileLoading />
+ ) : query.isError ? (
+ <CompileError error={query.error} retry={() => void query.refetch()} />
+ ) : null}
+ {!query.isLoading && !query.isError && !tasks.length && (
+ <div className="grid justify-items-center gap-3 rounded-xl border border-dashed py-16 text-center">
+ <SparklesIcon className="size-8 text-muted-foreground" />
+ <h2 className="font-medium">
+ {t(search.q || search.status ? 'emptyFiltered' : 'empty')}
+ </h2>
+ <p className="text-sm text-muted-foreground">{t('description')}</p>
+ </div>
+ )}
+ {!!tasks.length && (
+ <div className="overflow-hidden rounded-xl border">
+ <div className="hidden grid-cols-[minmax(0,2fr)_minmax(0,1.4fr)_minmax(0,1fr)_150px_16px] gap-5 border-b bg-muted/30 px-5 py-3 text-xs font-medium text-muted-foreground lg:grid">
+ <span>{t('task')}</span>
+ <span>{t('materials')}</span>
+ <span>{t('status')}</span>
+ <span>{t('createdAt')}</span>
+ <span />
+ </div>
+ {tasks.map((task) => {
+ const request = task.meta?.request
+ const leaf = (uri: string) =>
+ uri.split('/').filter(Boolean).pop() || uri
+ const date = task.created_at
+ ? new Date(Number(task.created_at) * 1000)
+ : null
+ return (
+ <Link
+ key={task.task_id}
+ to="/compile/tasks/$taskId"
+ params={{ taskId: task.task_id }}
+ state={{
+ compileListOrigin: {
+ scope: identityScopeKey,
+ index: location.state.__TSR_index,
+ search,
+ },
+ }}
+ className="group grid gap-4 border-b bg-card px-5 py-5 transition-colors last:border-b-0 hover:bg-muted/30 focus-visible:outline-2 focus-visible:outline-primary focus-visible:outline-offset-[-2px] lg:grid-cols-[minmax(0,2fr)_minmax(0,1.4fr)_minmax(0,1fr)_150px_16px] lg:items-center lg:gap-5"
+ >
+ <div className="min-w-0 space-y-2">
+ <p
+ className="break-words text-sm font-semibold [overflow-wrap:anywhere]"
+ title={request?.skill}
+ >
+ {request ? leaf(request.skill) : t('title')}
+ </p>
+ <div
+ className="flex items-start gap-2 text-xs text-muted-foreground"
+ title={request?.to}
+ >
+ <FolderOutput className="mt-0.5 size-3.5 shrink-0" />
+ <span className="min-w-0 break-words [overflow-wrap:anywhere]">
+ {request ? leaf(request.to) : '—'}
+ </span>
+ </div>
+ <p
+ className="font-mono text-[11px] text-muted-foreground/70"
+ title={task.task_id}
+ >
+ {task.task_id.length > 24
+ ? `${task.task_id.slice(0, 12)}…${task.task_id.slice(-6)}`
+ : task.task_id}
+ </p>
+ </div>
+ <div className="min-w-0 space-y-2">
+ <p className="text-xs text-muted-foreground lg:hidden">
+ {t('materials')}
+ </p>
+ {request?.from.length
+ ? request.from.slice(0, 2).map((uri) => (
+ <div
+ key={uri}
+ title={uri}
+ className="flex items-start gap-2 text-xs leading-5 text-muted-foreground"
+ >
+ <FolderInput className="mt-0.5 size-3.5 shrink-0" />
+ <span className="min-w-0 break-words [overflow-wrap:anywhere]">
+ {leaf(uri)}
+ </span>
+ </div>
+ ))
+ : '—'}
+ {request && request.from.length > 2 && (
+ <p className="text-xs text-muted-foreground">
+ {t('moreSources', { count: request.from.length - 2 })}
+ </p>
+ )}
+ </div>
+ <div className="min-w-0 space-y-2">
+ <CompileStatus status={task.status} />
+ {task.stage && (
+ <p
+ className="break-words text-xs text-muted-foreground"
+ title={task.stage}
+ >
+ {t(`stages.${task.stage.replace(/^compile:\s*/, '')}`, {
+ defaultValue: task.stage,
+ })}
+ </p>
+ )}
+ </div>
+ <time
+ dateTime={date?.toISOString()}
+ className="text-xs leading-5 text-muted-foreground"
+ >
+ {date ? (
+ <>
+ <span className="block">
+ {date.toLocaleDateString(i18n.language)}
+ </span>
+ <span className="block text-muted-foreground/70">
+ {date.toLocaleTimeString(i18n.language)}
+ </span>
+ </>
+ ) : (
+ '—'
+ )}
+ </time>
+ <ChevronRight className="hidden size-4 text-muted-foreground transition-transform group-hover:translate-x-0.5 lg:block" />
+ </Link>
+ )
+ })}
+ </div>
+ )}
+ {query.hasNextPage && (
+ <Button
+ variant="outline"
+ className="self-center"
+ disabled={query.isFetchingNextPage}
+ onClick={() => void query.fetchNextPage()}
+ >
+ {t(query.isFetchingNextPage ? 'loading' : 'more')}
+ </Button>
+ )}
+ </CompileShell>
+ )
+}
diff --git a/web-studio/src/routes/compile/new.tsx b/web-studio/src/routes/compile/new.tsx
new file mode 100644
index 000000000..6e6eacdf0
--- /dev/null
+++ b/web-studio/src/routes/compile/new.tsx
@@ -0,0 +1,20 @@
+import { createFileRoute } from '@tanstack/react-router'
+import { useAppConnection } from '#/hooks/use-app-connection'
+import { CompileForm } from './-components/compile-form'
+
+export const Route = createFileRoute('/compile/new')({
+ validateSearch: (s: Record<string, unknown>): { fromTask?: string } => ({
+ fromTask: typeof s.fromTask === 'string' ? s.fromTask : undefined,
+ }),
+ component: NewCompile,
+})
+function NewCompile() {
+ const { identityScopeKey } = useAppConnection()
+ const { fromTask } = Route.useSearch()
+ return (
+ <CompileForm
+ key={`${identityScopeKey}:${fromTask || ''}`}
+ fromTask={fromTask}
+ />
+ )
+}
diff --git a/web-studio/src/routes/compile/tasks/$taskId.tsx b/web-studio/src/routes/compile/tasks/$taskId.tsx
new file mode 100644
index 000000000..666a95743
--- /dev/null
+++ b/web-studio/src/routes/compile/tasks/$taskId.tsx
@@ -0,0 +1,283 @@
+import { useEffect, useRef, useState } from 'react'
+import { useMutation, useQuery, useQueryClient } from '@tanstack/react-query'
+import { createFileRoute, Link } from '@tanstack/react-router'
+import { useTranslation } from 'react-i18next'
+import { toast } from 'sonner'
+import {
+ Copy,
+ FolderInput,
+ FolderOutput,
+ WandSparkles,
+ Activity,
+} from 'lucide-react'
+import { Button } from '#/components/ui/button'
+import { useAppConnection } from '#/hooks/use-app-connection'
+import { TaskExecutionEvents } from '#/routes/tasks/-components/task-execution-events'
+import {
+ CompileError,
+ CompileLoading,
+ CompileShell,
+ CompileStatus,
+} from '../-components/shared'
+import { active, cancelCompile, fetchCompileTask } from '../-lib/api'
+
+const TABS = ['overview', 'events', 'result'] as const
+
+export const Route = createFileRoute('/compile/tasks/$taskId')({
+ component: CompileDetail,
+})
+function CompileDetail() {
+ const { taskId } = Route.useParams(),
+ { t, i18n } = useTranslation('compile')
+ const { identityScopeKey, connectionRole } = useAppConnection(),
+ client = useQueryClient()
+ const [tab, setTab] = useState<'overview' | 'events' | 'result'>('overview')
+ const key = ['compile-task', identityScopeKey, taskId]
+ const query = useQuery({
+ queryKey: key,
+ queryFn: ({ signal }) => fetchCompileTask(taskId, signal),
+ refetchInterval: (q) => (active(q.state.data?.status) ? 5000 : false),
+ })
+ const stop = useMutation({
+ mutationFn: () => cancelCompile(taskId),
+ onSuccess: (task) => {
+ client.setQueryData(key, task)
+ void client.invalidateQueries({
+ queryKey: ['compile-list', identityScopeKey],
+ })
+ },
+ })
+ const task = query.data,
+ request = task?.meta?.request
+ const previousStatus = useRef<{ id: string; status?: string } | null>(null)
+ useEffect(() => {
+ if (
+ previousStatus.current?.id === taskId &&
+ active(previousStatus.current.status) &&
+ task?.status === 'completed'
+ ) {
+ toast.success(t('statuses.completed'), {
+ action: { label: t('result'), onClick: () => setTab('result') },
+ })
+ }
+ if (task) previousStatus.current = { id: taskId, status: task.status }
+ }, [taskId, task, t])
+ return (
+ <CompileShell
+ title={t('detailTitle')}
+ actions={
+ request && (
+ <Link
+ to="/compile/new"
+ search={{ fromTask: taskId }}
+ className="rounded-md border px-4 py-2 text-sm hover:bg-muted"
+ >
+ {t('rerun')}
+ </Link>
+ )
+ }
+ >
+ {query.isLoading && <CompileLoading />}
+ {query.isError && (
+ <CompileError
+ error={task ? t('stale') : query.error}
+ retry={() => void query.refetch()}
+ />
+ )}
+ {task && task.task_type !== 'compile' && (
+ <CompileError error={t('invalidTask')} />
+ )}
+ {task?.task_type === 'compile' && (
+ <>
+ <section className="rounded-xl border bg-card p-5 sm:p-6">
+ <div className="flex flex-wrap items-center gap-3">
+ <CompileStatus status={task.status} />
+ <button
+ title={taskId}
+ aria-label={t('copyTaskId')}
+ className="inline-flex min-w-0 items-center gap-2 rounded px-2 py-1 font-mono text-xs text-muted-foreground hover:bg-muted"
+ onClick={() =>
+ void navigator.clipboard
+ .writeText(taskId)
+ .then(() => toast.success(t('copied')))
+ .catch(() => toast.error(t('failedLoad')))
+ }
+ >
+ <span>{taskId.slice(0, 16)}…</span>
+ <Copy className="size-3" />
+ </button>
+ {active(task.status) && (
+ <Button
+ variant="outline"
+ className="ml-auto"
+ title={
+ connectionRole === 'root' ? t('rootCancel') : undefined
+ }
+ disabled={
+ connectionRole === 'root' ||
+ task.status === 'cancelling' ||
+ stop.isPending
+ }
+ onClick={() => {
+ if (window.confirm(t('stopConfirm'))) stop.mutate()
+ }}
+ >
+ {t('stop')}
+ </Button>
+ )}
+ </div>
+ <div className="mt-5 grid gap-4 border-t pt-5 text-sm sm:grid-cols-2">
+ {task.stage && (
+ <div>
+ <p className="mb-2 text-xs text-muted-foreground">
+ {t('stage')}
+ </p>
+ <p className="flex items-center gap-2 font-medium">
+ <Activity className="size-4 text-primary" />
+ {t(`stages.${task.stage.replace(/^compile:\s*/, '')}`, {
+ defaultValue: task.stage,
+ })}
+ </p>
+ </div>
+ )}
+ <div>
+ <p className="mb-2 text-xs text-muted-foreground">
+ {t('updated')}
+ </p>
+ <p className="font-medium">
+ {task.updated_at
+ ? new Date(Number(task.updated_at) * 1000).toLocaleString(
+ i18n.language,
+ )
+ : '—'}
+ </p>
+ </div>
+ </div>
+ {active(task.status) && (
+ <p className="mt-4 text-xs text-muted-foreground">
+ {t('runningHint')}
+ </p>
+ )}
+ </section>
+ {stop.isError && <CompileError error={stop.error} />}
+ {task.error && <CompileError error={task.error} />}
+ <div role="tablist" className="flex gap-2 border-b pb-3">
+ {TABS.map((item) => (
+ <Button
+ key={item}
+ role="tab"
+ aria-selected={tab === item}
+ variant={tab === item ? 'secondary' : 'ghost'}
+ onClick={() => setTab(item)}
+ >
+ {t(item)}
+ </Button>
+ ))}
+ </div>
+ <div role="tabpanel">
+ {tab === 'overview' &&
+ (request ? (
+ <dl className="grid gap-4 text-sm md:grid-cols-2">
+ <div className="rounded-xl border bg-card p-5 md:col-span-2">
+ <dt className="mb-3 flex items-center gap-2 text-xs font-medium text-muted-foreground">
+ <WandSparkles className="size-4" />
+ {t('skill')}
+ </dt>
+ <dd>
+ <p className="mb-2 break-all font-medium">
+ {request.skill.split('/').filter(Boolean).pop()}
+ </p>
+ <p className="break-all font-mono text-xs text-muted-foreground">
+ {request.skill}
+ </p>
+ </dd>
+ </div>
+ <div className="min-w-0 rounded-xl border bg-card p-5">
+ <dt className="mb-4 flex items-center gap-2 text-xs font-medium text-muted-foreground">
+ <FolderInput className="size-4" />
+ {t('sources')}
+ <span className="ml-auto rounded bg-muted px-2 py-0.5">
+ {request.from.length}
+ </span>
+ </dt>
+ <dd className="space-y-4">
+ {request.from.map((uri) => (
+ <div key={uri}>
+ <p className="mb-1 break-all font-medium">
+ {uri.split('/').filter(Boolean).pop()}
+ </p>
+ <p className="break-all font-mono text-xs leading-5 text-muted-foreground">
+ {uri}
+ </p>
+ </div>
+ ))}
+ </dd>
+ </div>
+ <div className="min-w-0 rounded-xl border bg-card p-5">
+ <dt className="mb-4 flex items-center gap-2 text-xs font-medium text-muted-foreground">
+ <FolderOutput className="size-4" />
+ {t('target')}
+ </dt>
+ <dd>
+ <p className="mb-1 break-all font-medium">
+ {request.to.split('/').filter(Boolean).pop()}
+ </p>
+ <p className="break-all font-mono text-xs leading-5 text-muted-foreground">
+ {request.to}
+ </p>
+ </dd>
+ </div>
+ {request.instruction && (
+ <div className="rounded-xl border bg-card p-5 md:col-span-2">
+ <dt className="mb-2 font-medium">{t('instruction')}</dt>
+ <dd className="whitespace-pre-wrap">
+ {request.instruction}
+ </dd>
+ </div>
+ )}
+ {request.args && (
+ <details className="rounded-xl border p-5 md:col-span-2">
+ <summary>{t('advanced')}</summary>
+ <pre className="mt-3 overflow-auto rounded-lg bg-muted p-4 text-xs">
+ {JSON.stringify(request.args, null, 2)}
+ </pre>
+ </details>
+ )}
+ </dl>
+ ) : (
+ <p>{t('missingRequest')}</p>
+ ))}
+ {tab === 'events' && <TaskExecutionEvents task={task} />}
+ {tab === 'result' && (
+ <div className="space-y-5">
+ {request && (
+ <Link
+ to="/playground"
+ search={{ uri: request.to }}
+ className="inline-flex rounded-md bg-primary px-4 py-2 text-sm text-primary-foreground"
+ >
+ {t('output')}
+ </Link>
+ )}
+ {task.result == null ? (
+ <p className="text-sm text-muted-foreground">
+ {t('noResult')}
+ </p>
+ ) : (
+ <details open>
+ <summary className="text-sm font-medium">
+ {t('raw')}
+ </summary>
+ <pre className="mt-3 max-h-[60vh] overflow-auto whitespace-pre-wrap break-words rounded-lg border bg-muted/30 p-4 text-xs">
+ {JSON.stringify(task.result, null, 2)}
+ </pre>
+ </details>
+ )}
+ </div>
+ )}
+ </div>
+ </>
+ )}
+ </CompileShell>
+ )
+}
diff --git a/web-studio/src/routes/playground/-components/terminal-panel.tsx b/web-studio/src/routes/playground/-components/terminal-panel.tsx
index 09aac2867..c5694ae3f 100644
--- a/web-studio/src/routes/playground/-components/terminal-panel.tsx
+++ b/web-studio/src/routes/playground/-components/terminal-panel.tsx
@@ -1,3 +1,14 @@
+import { prepareCompileHandoff } from '#/routes/compile/-lib/handoff'
+import { useQuery } from '@tanstack/react-query'
+import { fetchCompileSkills } from '#/routes/compile/-lib/api'
+import { compileSuggestions } from '#/routes/compile/-lib/suggestions'
+import { Link } from '@tanstack/react-router'
+import {
+ CompileCommandError,
+ isCompileCommand,
+ compileHistory,
+} from '#/routes/compile/-lib/commands'
+import { runCompileSubmission } from '#/routes/compile/-lib/terminal'
import { useCallback, useEffect, useMemo, useRef, useState } from 'react'
import { createPortal } from 'react-dom'
import { useTranslation } from 'react-i18next'
@@ -223,10 +234,7 @@ const SESSION_SUBCOMMANDS_BY_KEY = new Map(
)
type TerminalSuggestionGroup =
- | TerminalCommandGroup
- | 'history'
- | 'resource'
- | 'subcommand'
+ TerminalCommandGroup | 'history' | 'resource' | 'subcommand'
type TerminalSuggestion = Omit<TerminalCommandView, 'group'> & {
group: TerminalSuggestionGroup
@@ -306,6 +314,11 @@ function loadTerminalHistory(storageKey: string): TerminalEntry[] {
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,
@@ -474,6 +487,13 @@ export function TerminalPanel({
)
const [command, setCommand] = useState('')
const [running, setRunning] = useState(false)
+ const compileSkills = useQuery({
+ queryKey: ['compile-skills', identityScopeKey],
+ queryFn: ({ signal }) => fetchCompileSkills(signal),
+ enabled: /^(?:ov\s+)?\/?compile\s/.test(command),
+ })
+ const identityRef = useRef(identityScopeKey)
+ identityRef.current = identityScopeKey
const [suggestionsOpen, setSuggestionsOpen] = useState(false)
const [activeSuggestionIndex, setActiveSuggestionIndex] = useState(0)
const [commandHistory, setCommandHistory] = useState(() =>
@@ -651,6 +671,21 @@ export function TerminalPanel({
const seen = new Set<string>()
return [
+ ...compileSuggestions(
+ rawQuery,
+ entries.filter((entry) => entry.isDir).map((entry) => entry.uri),
+ compileSkills.data?.map((skill) => skill.uri) || [],
+ ).map((insertText) => ({
+ adminOnly: false,
+ command: insertText,
+ description: t('compile:terminalHint'),
+ executable: false,
+ group: 'core' as const,
+ id: `compile:${insertText}`,
+ insertText,
+ key: 'compile',
+ usage: insertText,
+ })),
...commandMatches,
...resourceMatches,
...sessionSubcommandMatches,
@@ -660,7 +695,16 @@ export function TerminalPanel({
seen.add(item.insertText)
return true
})
- }, [activeCommand, command, commandHistory, commands, resourceCandidates, t])
+ }, [
+ activeCommand,
+ command,
+ commandHistory,
+ commands,
+ resourceCandidates,
+ t,
+ entries,
+ compileSkills.data,
+ ])
const helpCommand = useMemo(() => {
if (!activeCommand) return undefined
@@ -803,18 +847,73 @@ export function TerminalPanel({
[commandHistoryStorageKey],
)
+ const compileSubmission = useRef<{ raw: string; key: string } | null>(null)
+ useEffect(() => {
+ compileSubmission.current = null
+ }, [identityScopeKey])
const runCommand = useCallback(
async (raw: string) => {
const trimmed = raw.trim()
if (!trimmed || running) return
- append({ kind: 'command', title: trimmed })
- rememberCommand(trimmed)
+ const isCompile = isCompileCommand(trimmed)
+ const safeHistory = isCompile
+ ? compileHistory(trimmed)
+ : { title: trimmed, remember: true }
+ append({ kind: 'command', title: safeHistory.title })
+ if (safeHistory.remember) rememberCommand(safeHistory.title)
setCommand('')
setSuggestionsOpen(false)
setRunning(true)
try {
+ if (isCompile) {
+ if (/^(?:ov\s+)?\/?compile$/.test(trimmed)) {
+ append({
+ kind: 'info',
+ title: 'compile',
+ body: t('compile:terminalHelp'),
+ compileForm: true,
+ })
+ return
+ }
+ const recoveryKey = `compile-submission:${identityScopeKey}`
+ const result = await runCompileSubmission(
+ trimmed,
+ compileSubmission,
+ (status) =>
+ t(`compile:statuses.${status}`, { defaultValue: status }),
+ (key) => {
+ if (identityRef.current !== identityScopeKey)
+ throw new DOMException('Identity changed', 'AbortError')
+ try {
+ if (key) sessionStorage.setItem(recoveryKey, key)
+ else sessionStorage.removeItem(recoveryKey)
+ } catch {
+ /* optional recovery */
+ }
+ },
+ () => {
+ try {
+ return sessionStorage.getItem(recoveryKey)
+ } catch {
+ return null
+ }
+ },
+ (stage) =>
+ t(`compile:stages.${stage.replace(/^compile:\s*/, '')}`, {
+ defaultValue: stage,
+ }),
+ )
+ if (identityRef.current !== identityScopeKey) return
+ append({
+ kind: 'success',
+ title: 'compile',
+ body: result.body,
+ compileTaskId: result.taskId,
+ })
+ return
+ }
const [name = '', ...args] = trimmed.split(/\s+/)
const body = args.join(' ').trim()
@@ -1285,8 +1384,12 @@ export function TerminalPanel({
throw new Error(t('terminal.unknownCommand'))
}
} catch (error) {
+ if (identityRef.current !== identityScopeKey) return
append({
- body: getErrorMessage(error),
+ body:
+ error instanceof CompileCommandError
+ ? t(`compile:commandErrors.${error.code}`)
+ : getErrorMessage(error),
kind: 'error',
title: t('terminal.commandFailed'),
})
@@ -1423,6 +1526,20 @@ export function TerminalPanel({
</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}
@@ -1823,6 +1940,7 @@ export function TerminalHistoryItem({
onOpenResource: ResourceOpenHandler
openingUri: string | null
}) {
+ const { t } = useTranslation('playground')
const Icon =
entry.kind === 'command'
? TerminalIcon
@@ -1852,6 +1970,20 @@ export function TerminalHistoryItem({
{entry.title}
</span>
</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.body}
diff --git a/web-studio/src/routes/playground/-lib/types.ts b/web-studio/src/routes/playground/-lib/types.ts
index d1b4dede1..3a3980436 100644
--- a/web-studio/src/routes/playground/-lib/types.ts
+++ b/web-studio/src/routes/playground/-lib/types.ts
@@ -15,6 +15,8 @@ export type ResourceRef = {
}
export type TerminalEntry = {
+ compileTaskId?: string
+ compileForm?: boolean
id: string
kind: 'command' | 'error' | 'info' | 'success'
title: string
diff --git a/web-studio/src/routes/resources/-components/directory-picker-dialog.tsx b/web-studio/src/routes/resources/-components/directory-picker-dialog.tsx
index e3af83ce6..e79bcca61 100644
--- a/web-studio/src/routes/resources/-components/directory-picker-dialog.tsx
+++ b/web-studio/src/routes/resources/-components/directory-picker-dialog.tsx
@@ -29,6 +29,8 @@ function getErrorMessage(error: unknown): string {
}
interface DirectoryPickerDialogProps {
+ userResourceRoot?: string
+ identityScopeKey?: string
open: boolean
onOpenChange: (open: boolean) => void
value: string
@@ -53,6 +55,8 @@ function parseBreadcrumbs(uri: string): Array<{ label: string; uri: string }> {
}
export function DirectoryPickerDialog({
+ identityScopeKey = 'default',
+ userResourceRoot,
open,
onOpenChange,
value,
@@ -70,7 +74,7 @@ export function DirectoryPickerDialog({
const normalizedUri = normalizeDirUri(browseUri)
const dirQuery = useQuery({
- queryKey: ['dir-picker', normalizedUri],
+ queryKey: ['dir-picker', identityScopeKey, normalizedUri],
queryFn: async () => {
const result = await getOvResult<FSListResult>(
getFsLs({
@@ -95,6 +99,42 @@ export function DirectoryPickerDialog({
<DialogTitle>{t('dirPicker.title')}</DialogTitle>
</DialogHeader>
+ {userResourceRoot && (
+ <div
+ className="flex gap-2"
+ role="group"
+ aria-label={t('dirPicker.scope')}
+ >
+ <Button
+ type="button"
+ size="sm"
+ variant={
+ normalizedUri.startsWith(normalizeDirUri(userResourceRoot))
+ ? 'secondary'
+ : 'ghost'
+ }
+ aria-pressed={normalizedUri.startsWith(
+ normalizeDirUri(userResourceRoot),
+ )}
+ onClick={() => setBrowseUri(userResourceRoot)}
+ >
+ {t('dirPicker.mine')}
+ </Button>
+ <Button
+ type="button"
+ size="sm"
+ variant={
+ normalizedUri.startsWith('viking://resources/')
+ ? 'secondary'
+ : 'ghost'
+ }
+ aria-pressed={normalizedUri.startsWith('viking://resources/')}
+ onClick={() => setBrowseUri('viking://resources/')}
+ >
+ {t('dirPicker.shared')}
+ </Button>
+ </div>
+ )}
{/* Breadcrumb */}
<div className="flex flex-wrap items-center gap-1 text-sm">
{breadcrumbs.map((crumb, i) => (
@@ -164,6 +204,7 @@ export function DirectoryPickerDialog({
{t('dirPicker.cancel')}
</Button>
<Button
+ disabled={dirQuery.isLoading || dirQuery.isError}
onClick={() => {
onSelect(normalizedUri)
onOpenChange(false)
diff --git a/web-studio/src/routes/resources/-components/file-preview.tsx b/web-studio/src/routes/resources/-components/file-preview.tsx
index 6f1216279..0e12ddf18 100644
--- a/web-studio/src/routes/resources/-components/file-preview.tsx
+++ b/web-studio/src/routes/resources/-components/file-preview.tsx
@@ -1,3 +1,5 @@
+import { YamlMetadata } from './yaml-metadata'
+import { splitMarkdownFrontmatter } from '#/lib/markdown-frontmatter'
import { useEffect, useMemo, useRef, useState, lazy, Suspense } from 'react'
import type { ComponentProps, ReactNode } from 'react'
import { useQuery } from '@tanstack/react-query'
@@ -1359,6 +1361,7 @@ export function FilePreview({
() => memoryFieldsDisplayContent(preview?.content || ''),
[preview?.content],
)
+ const frontmatter = useMemo(() => splitMarkdownFrontmatter(displayContent || ''), [displayContent])
const okfDocument = useMemo(
() =>
file && preview?.fileType === 'markdown'
@@ -1908,7 +1911,7 @@ export function FilePreview({
onNavigate={onNavigate}
rawFrontmatter={okfDocument.rawFrontmatter}
/>
- ) : null}
+ ) : frontmatter ? <YamlMetadata rawFrontmatter={frontmatter.rawFrontmatter} defaultOpen /> : null}
<article className="prose prose-sm max-w-none break-words dark:prose-invert dark:prose-pre:bg-muted-foreground/20">
<ReactMarkdown
remarkPlugins={[remarkGfm]}
@@ -1936,7 +1939,7 @@ export function FilePreview({
>
{okfDocument
? okfDocument.body || emptyFileText
- : displayContent || emptyFileText}
+ : (frontmatter?.body ?? displayContent) || emptyFileText}
</ReactMarkdown>
</article>
</div>
diff --git a/web-studio/src/routes/resources/-components/okf-metadata-panel.tsx b/web-studio/src/routes/resources/-components/okf-metadata-panel.tsx
index fce7f8443..9cb9f5c78 100644
--- a/web-studio/src/routes/resources/-components/okf-metadata-panel.tsx
+++ b/web-studio/src/routes/resources/-components/okf-metadata-panel.tsx
@@ -1,6 +1,6 @@
+import { YamlMetadata } from './yaml-metadata'
import {
Bot,
- ChevronRight,
CircleAlert,
FolderOpen,
RefreshCw,
@@ -136,17 +136,7 @@ export function OkfMetadataPanel({
</div>
) : null}
- <details className="group border-t bg-background/40">
- <summary className="flex cursor-pointer list-none items-center gap-1.5 px-3 py-2 text-[11px] font-medium text-muted-foreground transition-colors marker:hidden hover:bg-muted/40 hover:text-foreground">
- <ChevronRight className="size-3.5 shrink-0 transition-transform group-open:rotate-90" />
- {t('filePreview.yamlMetadata.rawYaml')}
- </summary>
- <div className="border-t bg-background/70 p-3">
- <pre className="max-h-[32rem] min-h-32 overflow-auto whitespace-pre rounded-md border bg-muted/20 p-3 font-mono text-xs leading-5 text-foreground">
- <code>{rawFrontmatter}</code>
- </pre>
- </div>
- </details>
+ <YamlMetadata rawFrontmatter={rawFrontmatter} />
</section>
)
}
diff --git a/web-studio/src/routes/resources/-components/yaml-metadata.tsx b/web-studio/src/routes/resources/-components/yaml-metadata.tsx
new file mode 100644
index 000000000..a06ae957f
--- /dev/null
+++ b/web-studio/src/routes/resources/-components/yaml-metadata.tsx
@@ -0,0 +1,28 @@
+import { ChevronRight } from 'lucide-react'
+import { useTranslation } from 'react-i18next'
+
+export function YamlMetadata({
+ rawFrontmatter,
+ defaultOpen = false,
+}: {
+ rawFrontmatter: string
+ defaultOpen?: boolean
+}) {
+ const { t } = useTranslation('resources')
+ return (
+ <details
+ open={defaultOpen}
+ className="not-prose group rounded-md border bg-background/40"
+ >
+ <summary className="flex cursor-pointer list-none items-center gap-1.5 px-3 py-2 text-[11px] font-medium text-muted-foreground transition-colors marker:hidden hover:bg-muted/40 hover:text-foreground">
+ <ChevronRight className="size-3.5 shrink-0 transition-transform group-open:rotate-90" />
+ {t('filePreview.yamlMetadata.rawYaml')}
+ </summary>
+ <div className="border-t bg-background/70 p-3">
+ <pre className="max-h-[32rem] min-h-32 overflow-auto whitespace-pre rounded-md border bg-muted/20 p-3 font-mono text-xs leading-5 text-foreground">
+ <code>{rawFrontmatter}</code>
+ </pre>
+ </div>
+ </details>
+ )
+}
diff --git a/web-studio/src/routes/tasks/-lib/task-list.ts b/web-studio/src/routes/tasks/-lib/task-list.ts
index 58e3dd183..ab501627b 100644
--- a/web-studio/src/routes/tasks/-lib/task-list.ts
+++ b/web-studio/src/routes/tasks/-lib/task-list.ts
@@ -5,6 +5,7 @@ import type { TaskRecord, TaskStatus } from '#/routes/tasks/-lib/task-record'
export type TaskStatusFilter = Exclude<TaskStatus, 'unknown'> | 'all'
export type TaskTypeFilter =
+ | 'compile'
| 'add_resource'
| 'add_skill'
| 'admin_reindex'
diff --git a/web-studio/src/routes/tasks/route.test.tsx b/web-studio/src/routes/tasks/route.test.tsx
index a0899491d..82a95e831 100644
--- a/web-studio/src/routes/tasks/route.test.tsx
+++ b/web-studio/src/routes/tasks/route.test.tsx
@@ -1,9 +1,9 @@
// @vitest-environment jsdom
-import * as React from 'react'
import { createInstance } from 'i18next'
import { I18nextProvider } from 'react-i18next'
import type { ComponentType } from 'react'
+import type * as TanStackRouter from '@tanstack/react-router'
import en from '#/i18n/locales/en/workspace'
import zh from '#/i18n/locales/zh-CN/workspace'
import { QueryClient, QueryClientProvider } from '@tanstack/react-query'
@@ -24,6 +24,12 @@ import type { TaskRecord } from './-lib/task-record'
const clientMocks = vi.hoisted(() => ({ getTasks: vi.fn() }))
+const navigationMocks = vi.hoisted(() => ({ navigate: vi.fn() }))
+vi.mock('@tanstack/react-router', async (importOriginal) => ({
+ ...(await importOriginal<typeof TanStackRouter>()),
+ useNavigate: () => navigationMocks.navigate,
+}))
+
vi.mock('#/lib/ov-client', () => ({
getOvResult: async (value: unknown) => value,
getTasks: clientMocks.getTasks,
@@ -192,4 +198,24 @@ describe('task status presentation', () => {
expectRunningRows(6)
expect(screen.getByText('26 / 0')).toBeDefined()
})
+ it('keeps separate compile runs and opens their dedicated detail page', async () => {
+ records = ['cmp_one', 'cmp_two'].map((task_id) => ({
+ task_id,
+ task_type: 'compile',
+ resource_id: 'same-source',
+ status: 'running',
+ created_at: 200,
+ }))
+ const user = await renderPage()
+ await user.click(
+ await screen.findByRole('row', { name: 'View details for task cmp_one' }),
+ )
+ expect(
+ screen.getByRole('row', { name: 'View details for task cmp_two' }),
+ ).toBeDefined()
+ expect(navigationMocks.navigate).toHaveBeenCalledWith({
+ to: '/compile/tasks/$taskId',
+ params: { taskId: 'cmp_one' },
+ })
+ })
})
diff --git a/web-studio/src/routes/tasks/route.tsx b/web-studio/src/routes/tasks/route.tsx
index fc1402150..74389952a 100644
--- a/web-studio/src/routes/tasks/route.tsx
+++ b/web-studio/src/routes/tasks/route.tsx
@@ -1,6 +1,6 @@
import * as React from 'react'
import { useMutation, useQuery, useQueryClient } from '@tanstack/react-query'
-import { createFileRoute } from '@tanstack/react-router'
+import { createFileRoute, useNavigate } from '@tanstack/react-router'
import {
CheckCircle2Icon,
CheckIcon,
@@ -63,6 +63,7 @@ export const Route = createFileRoute('/tasks')({
const DEFAULT_PAGE_SIZE = 20
const PAGE_SIZE_OPTIONS = [20, 50, 100] as const
const TASK_TYPE_OPTIONS: Exclude<TaskTypeFilter, 'all'>[] = [
+ 'compile',
'session_commit',
'add_resource',
'add_skill',
@@ -82,6 +83,7 @@ const TASK_STATUS_OPTIONS: Exclude<TaskStatusFilter, 'all'>[] = [
]
function TasksRoute() {
+ const navigate = useNavigate()
const { i18n, t } = useTranslation('tasksPage')
const { identityScopeKey } = useAppConnection()
const queryClient = useQueryClient()
@@ -104,7 +106,7 @@ function TasksRoute() {
if (!dedupByResource) return rawTasks
const map = new Map<string, TaskRecord>()
for (const t of rawTasks) {
- const key = t.resource_id ? `res:${t.resource_id}` : `task:${t.task_id}`
+ const key = t.resource_id && t.task_type !== 'compile' ? `res:${t.resource_id}` : `task:${t.task_id}`
if (!map.has(key)) {
map.set(key, t)
}
@@ -866,7 +868,11 @@ function TasksRoute() {
'cursor-pointer outline-none hover:bg-muted/35 focus-visible:bg-muted/35 focus-visible:ring-2 focus-visible:ring-primary/40 focus-visible:ring-inset',
)}
onClick={() => {
- if (taskId) setSelectedTaskId(taskId)
+ if (taskId) {
+ if (task.task_type === 'compile') {
+ void navigate({ to: '/compile/tasks/$taskId', params: { taskId } })
+ } else setSelectedTaskId(taskId)
+ }
}}
onKeyDown={(event) => {
if (
@@ -874,7 +880,9 @@ function TasksRoute() {
(event.key === 'Enter' || event.key === ' ')
) {
event.preventDefault()
- setSelectedTaskId(taskId)
+ if (task.task_type === 'compile') {
+ void navigate({ to: '/compile/tasks/$taskId', params: { taskId } })
+ } else setSelectedTaskId(taskId)
}
}}
>