Open-source LLM knowledge platform: turn raw documents into a queryable RAG, an autonomous reasoning agent, and a self-maintaining Wiki.
Go agentagenticaichatbotdsh-pluginembeddingsevaluationgenerative-aigolangknowledge-basellmmulti-tenantollamaopenaiquestion-answeringragrerankingsemantic-searchvector-searchwiki
refactor(automation): run scheduled tasks through the assistant (#4522)
lyingbugc1979838044d
diff --git a/docs/design/agent-automation.md b/docs/design/agent-automation.mdindex 9f6be0ec2..cbe70ae37 100644--- a/docs/design/agent-automation.md+++ b/docs/design/agent-automation.md@@ -20,7 +20,7 @@第一版包含:- 触发方式为 cron 周期和一次性定时,支持时区;另提供手动“立即运行”。-- 执行者为当前工作空间可用的 smart-reasoning Agent,或者内置助手。+- 执行者固定为内置 WeKnora 助手;需要其他智能体时,在任务提示词中写明委派对象与工作,由助手通过现有协作工具委派。- 运行历史、运行详情(复用会话详情和子任务查看)、停止运行、暂停或恢复自动化。- 站内通知:运行成功、失败、等待审批、自动暂停。- 助手可通过 operations 创建和管理自动化,需要用户确认。@@ -49,7 +49,7 @@|---|---|| `id, tenant_id, owner_user_id` | 所有者是创建者的账户 ID,不保存任何凭据 || `name, description, enabled` | |-| `agent_id` | 为空表示使用内置助手;非空时引用 `CustomAgent`,跟随模板更新 |+| `model_id` | 可选,覆盖助手本次执行使用的模型;为空跟随助手默认模型,委派的智能体仍使用各自的模型 || `instruction` | 任务提示词,支持运行时变量(§5.4) || `trigger` | JSON:`{type: cron, expr, timezone}` 或 `{type: once, at, timezone}` || `session_mode` | `per_run`(默认)或 `persistent` |@@ -57,7 +57,7 @@| `carry_last_result` | `per_run` 模式下是否注入上次成功运行的结果摘要 || `misfire_policy` | `skip`(默认)或 `run_once`:停机或暂停期间错过的触发,最多补跑一次 || `overlap_policy` | `skip`(默认)或 `queue`:上一次还在运行时如何处理本次触发;`queue` 最多排队一个 |-| `access_level` | 执行档位,语义见权限模型 §2.2;默认 `confirm`,`auto_write` 必须显式选择;运行时仍受 Agent 与工作空间上限约束 |+| `access_level` | 执行档位,语义见权限模型 §2.2;默认 `confirm`,`auto_write` 必须显式选择;运行时仍受工作空间的助手权限上限约束 || `approval_timeout` | 挂起等待审批的最长时间,默认 24 小时 || `limits` | JSON:单次运行最长时间、最大迭代数、token 上限 || `next_run_at, last_run_at, last_success_at` | 调度状态 |@@ -123,7 +123,7 @@ queued → skipped (重叠策略或自动### 5.1 运行身份-- 运行前加载所有者,重新校验:账户有效、仍是工作空间成员、`agent_id` 仍可用、知识库与 MCP 的授权范围仍成立。任一失败则本次 `failed`,并将自动化暂停、写入 `paused_reason`、发通知。+- 运行前加载所有者,重新校验:账户有效、仍是工作空间成员、内置助手仍可用、知识库与 MCP 的授权范围仍成立。任一失败则本次 `failed`,并将自动化暂停、写入 `paused_reason`、发通知。- 校验通过后构造上下文:`Principal{web_user, owner_user_id, ActingVia: "automation:<id>"}`,租户与工作空间取自自动化记录。路由层按所有者鉴权,因此 operations 可用;根 Agent 满足协作父任务条件,可以 `spawn_agent`。审计日志通过 `ActingVia` 区分代为执行。- 子任务按权限模型 §2.5 处理:档位不超过父任务,继承本次运行的授权。@@ -193,15 +193,15 @@ API(均校验所有者或空间管理员权限):前端:-- 自动化列表:名称、执行 Agent、触发描述、下次运行、最近状态、启用开关。-- 编辑表单:Agent 选择、任务提示词(含变量提示)、触发方式(预设项“每天/每周/每月”加高级 cron)、时区、会话形态、执行档位、长期授权(勾选运行时无需确认的写类与 destructive 工具及资源范围;destructive 项单独分组、必须选择具体资源,保存时弹审批卡)、审批等待期限、限制、通知选项。+- 自动化列表:名称、触发描述、下次运行、最近状态、启用开关。+- 编辑表单:运行模型、任务提示词(含变量提示)、触发方式(预设项“每天/每周/每月”加高级 cron)、时区、会话形态、执行档位、长期授权(勾选运行时无需确认的写类与 destructive 工具及资源范围;destructive 项单独分组、必须选择具体资源,保存时弹审批卡)、审批等待期限、限制、通知选项。- 运行历史与详情:详情直接打开自动化会话,复用现有消息流、子任务卡片、审批卡和产物抽屉。## 9. 助手集成operations 新增:`automation.list`、`automation.get`、`automation.create`、`automation.update`、`automation.pause`、`automation.resume`、`automation.run_now`、`automation.delete`。-- 写操作走现有 confirm 审批,审批卡展示人类可读的触发描述、未来 3 次触发时间、执行 Agent、执行档位和将要创建的长期授权。长期授权由用户在审批卡上批准,模型不能代为授予。+- 写操作走现有 confirm 审批,审批卡展示人类可读的触发描述、未来 3 次触发时间、执行档位和将要创建的长期授权。长期授权由用户在审批卡上批准,模型不能代为授予。- 模型负责把自然语言转换为 cron 和时区,服务端负责校验;模型不能设置所有者,所有者固定为当前用户。- 助手只读档位下只能列出和查看。@@ -221,7 +221,7 @@ operations 新增:`automation.list`、`automation.get`、`automation.create`- 时区为 `Asia/Shanghai` 的“每天 9:00”在 UTC 服务器上按北京时间触发;跨夏令时时区的触发时间正确。- `overlap_policy = skip` 时,上一次未结束则本次记为 `skipped`。- 所有者被移出工作空间后,下一次运行失败,自动化暂停并通知;不以旧权限执行。-- Agent 模板被删除后运行失败并给出明确原因。+- 助手不可用时运行失败并给出明确原因;委派目标不可用时由助手报告具体阻塞。- 命中长期授权的写类工具不弹审批;未命中的挂起并通知,审批后从原轮次继续,只执行一次;超过 `approval_timeout` 后运行失败,迟到的审批不会恢复。- destructive 工具未在设置中预先授权时,运行时每次挂起询问,审批卡不提供“以后都允许”;在设置中对知识库 X 预先授权后,删除 X 中的文档直接执行,删除其他知识库中的文档仍挂起询问。- `Always` 工具(管理员要求每次审批的 MCP、技能安装)在设置中不可勾选,运行时每次挂起询问。@@ -254,6 +254,6 @@ operations 新增:`automation.list`、`automation.get`、`automation.create`- **长期授权从历史审批提升**。设置页不提供工具清单勾选,而是列出本自动化运行中请求过审批、尚未授权的写类与 destructive 调用,由所有者逐条确认;授权绑定 Agent 配置与所有者角色(`AutomationBinding`),变化后显示失效。需要每次审批的调用不会出现在候选里。- **限制只有时长**。`limits` 目前只有 `max_duration_minutes`(默认 30,上限 240,不含等待审批的时间);token 上限没有单独实现,由 Agent 自身的 `max_iterations` 约束。- **`persistent` 会话忙时跳过**。长期会话里还有进行中的运行(包括用户在该会话里手动对话)时,本次运行记为 `skipped`。-- **内置助手的 `agent_id` 存为助手 ID**(`builtin-weknora-assistant`),空字符串只在创建时作为默认值。+- **执行入口固定为内置助手**(`builtin-weknora-assistant`),自动化表与创建、更新接口不提供 `agent_id`。表单和对话创建使用同一规则,提示词可要求助手委派其他智能体。- **前端入口**:侧栏“自动化”页面(`/platform/automations`),运行详情直接打开自动化会话;通知链接 `/platform/automations/:id?run=:runId` 打开对应运行。右上角铃铛合并展示邀请与通知,60 秒轮询。- **助手审批卡**仍是通用的 operation 参数展示,未单独渲染触发描述与未来触发时间;助手需要先调用 `automation.validate_trigger` 并在对话里告知用户。diff --git a/docs/docs.go b/docs/docs.goindex 31227d083..36d754d62 100644--- a/docs/docs.go+++ b/docs/docs.go@@ -2048,7 +2048,7 @@ const docTemplate = `{"max_items": 100,"risk": "read"},- "x-agent-hint": "Lists the user's automations: scheduled tasks an agent runs on their behalf, with next and last run."+ "x-agent-hint": "Lists the user's automations: scheduled tasks the WeKnora assistant runs on their behalf, with next and last run."},"post": {"security": [@@ -2056,7 +2056,7 @@ const docTemplate = `{"Bearer": []}],- "description": "创建一个按计划由 Agent 以当前用户身份运行的任务",+ "description": "创建一个按计划由 WeKnora 助手以当前用户身份运行的任务","consumes": ["application/json"],@@ -2111,7 +2111,7 @@ const docTemplate = `{"risk": "write","role": "viewer"},- "x-agent-hint": "Creates an automation the user runs as. Turn the user's wording into a cron expression (five fields, minute first) and an IANA timezone, and check it with automation.validate_trigger first, telling the user the next run times it returns. Runs are unattended: write the instruction as a complete task, since nobody can answer questions during a run. access_level defaults to confirm, where each change waits for the user's approval; only set auto_write when the user asks for it."+ "x-agent-hint": "Creates an automation the WeKnora assistant runs as the user. If work requires other agents, name them and their assignments in the instruction so the assistant can delegate. Turn the user's wording into a cron expression (five fields, minute first) and an IANA timezone, and check it with automation.validate_trigger first, telling the user the next run times it returns. Runs are unattended: write the instruction as a complete task, since nobody can answer questions during a run. access_level defaults to confirm, where each change waits for the user's approval; only set auto_write when the user asks for it."}},"/automations/validate-trigger": {@@ -26259,7 +26259,7 @@ const docTemplate = `{"type": "object","properties": {"access_level": {- "description": "AccessLevel is how far runs may change data without asking, capped by\nthe agent's and the workspace's ceilings.",+ "description": "AccessLevel is how far runs may change data without asking, capped by\nthe workspace's assistant ceiling.","allOf": [{"$ref": "#/definitions/github_com_Tencent_WeKnora_internal_types.AssistantAccessLevel"@@ -26267,11 +26267,6 @@ const docTemplate = `{],"x-agent": true},- "agent_id": {- "description": "AgentID is the agent that runs it; the WeKnora assistant's ID runs the\nassistant.",- "type": "string",- "x-agent": true- },"approval_timeout_minutes": {"description": "ApprovalTimeoutMinutes is how long a run waits for an approval before\nit fails.","type": "integer",@@ -26331,7 +26326,7 @@ const docTemplate = `{"x-agent": true},"model_id": {- "description": "ModelID overrides the agent's chat model; empty follows the agent default.",+ "description": "ModelID overrides the assistant's chat model; empty follows the assistant default.","type": "string","x-agent": true},@@ -26412,11 +26407,6 @@ const docTemplate = `{],"x-agent": true},- "agent_id": {- "description": "Agent that runs it, from agent.list; empty runs the WeKnora assistant",- "type": "string",- "x-agent": true- },"approval_timeout_minutes": {"description": "How long a run waits for an approval before it fails, in minutes","type": "integer",@@ -26455,7 +26445,7 @@ const docTemplate = `{"x-agent": true},"model_id": {- "description": "Optional chat model from model.list; empty follows the agent default",+ "description": "Optional chat model from model.list; empty follows the assistant default","type": "string","x-agent": true},@@ -37365,11 +37355,6 @@ const docTemplate = `{],"x-agent": true},- "agent_id": {- "description": "Agent that runs it, from agent.list; empty runs the WeKnora assistant",- "type": "string",- "x-agent": true- },"approval_timeout_minutes": {"description": "How long a run waits for an approval before it fails, in minutes; default 1440","type": "integer",@@ -37403,6 +37388,11 @@ const docTemplate = `{],"x-agent": true},+ "model_id": {+ "description": "Optional chat model from model.list; empty follows the assistant default",+ "type": "string",+ "x-agent": true+ },"name": {"description": "What the automation is called","type": "string",diff --git a/docs/swagger.json b/docs/swagger.jsonindex b27711243..5a3456753 100644--- a/docs/swagger.json+++ b/docs/swagger.json@@ -2041,7 +2041,7 @@"max_items": 100,"risk": "read"},- "x-agent-hint": "Lists the user's automations: scheduled tasks an agent runs on their behalf, with next and last run."+ "x-agent-hint": "Lists the user's automations: scheduled tasks the WeKnora assistant runs on their behalf, with next and last run."},"post": {"security": [@@ -2049,7 +2049,7 @@"Bearer": []}],- "description": "创建一个按计划由 Agent 以当前用户身份运行的任务",+ "description": "创建一个按计划由 WeKnora 助手以当前用户身份运行的任务","consumes": ["application/json"],@@ -2104,7 +2104,7 @@"risk": "write","role": "viewer"},- "x-agent-hint": "Creates an automation the user runs as. Turn the user's wording into a cron expression (five fields, minute first) and an IANA timezone, and check it with automation.validate_trigger first, telling the user the next run times it returns. Runs are unattended: write the instruction as a complete task, since nobody can answer questions during a run. access_level defaults to confirm, where each change waits for the user's approval; only set auto_write when the user asks for it."+ "x-agent-hint": "Creates an automation the WeKnora assistant runs as the user. If work requires other agents, name them and their assignments in the instruction so the assistant can delegate. Turn the user's wording into a cron expression (five fields, minute first) and an IANA timezone, and check it with automation.validate_trigger first, telling the user the next run times it returns. Runs are unattended: write the instruction as a complete task, since nobody can answer questions during a run. access_level defaults to confirm, where each change waits for the user's approval; only set auto_write when the user asks for it."}},"/automations/validate-trigger": {@@ -26252,7 +26252,7 @@"type": "object","properties": {"access_level": {- "description": "AccessLevel is how far runs may change data without asking, capped by\nthe agent's and the workspace's ceilings.",+ "description": "AccessLevel is how far runs may change data without asking, capped by\nthe workspace's assistant ceiling.","allOf": [{"$ref": "#/definitions/github_com_Tencent_WeKnora_internal_types.AssistantAccessLevel"@@ -26260,11 +26260,6 @@],"x-agent": true},- "agent_id": {- "description": "AgentID is the agent that runs it; the WeKnora assistant's ID runs the\nassistant.",- "type": "string",- "x-agent": true- },"approval_timeout_minutes": {"description": "ApprovalTimeoutMinutes is how long a run waits for an approval before\nit fails.","type": "integer",@@ -26324,7 +26319,7 @@"x-agent": true},"model_id": {- "description": "ModelID overrides the agent's chat model; empty follows the agent default.",+ "description": "ModelID overrides the assistant's chat model; empty follows the assistant default.","type": "string","x-agent": true},@@ -26405,11 +26400,6 @@],"x-agent": true},- "agent_id": {- "description": "Agent that runs it, from agent.list; empty runs the WeKnora assistant",- "type": "string",- "x-agent": true- },"approval_timeout_minutes": {"description": "How long a run waits for an approval before it fails, in minutes","type": "integer",@@ -26448,7 +26438,7 @@"x-agent": true},"model_id": {- "description": "Optional chat model from model.list; empty follows the agent default",+ "description": "Optional chat model from model.list; empty follows the assistant default","type": "string","x-agent": true},@@ -37358,11 +37348,6 @@],"x-agent": true},- "agent_id": {- "description": "Agent that runs it, from agent.list; empty runs the WeKnora assistant",- "type": "string",- "x-agent": true- },"approval_timeout_minutes": {"description": "How long a run waits for an approval before it fails, in minutes; default 1440","type": "integer",@@ -37396,6 +37381,11 @@],"x-agent": true},+ "model_id": {+ "description": "Optional chat model from model.list; empty follows the assistant default",+ "type": "string",+ "x-agent": true+ },"name": {"description": "What the automation is called","type": "string",diff --git a/docs/swagger.yaml b/docs/swagger.yamlindex 06f70a21f..833eb8986 100644--- a/docs/swagger.yaml+++ b/docs/swagger.yaml@@ -1757,13 +1757,7 @@ definitions:- $ref: '#/definitions/github_com_Tencent_WeKnora_internal_types.AssistantAccessLevel'description: |-AccessLevel is how far runs may change data without asking, capped by- the agent's and the workspace's ceilings.- x-agent: true- agent_id:- description: |-- AgentID is the agent that runs it; the WeKnora assistant's ID runs the- assistant.- type: string+ the workspace's assistant ceiling.x-agent: trueapproval_timeout_minutes:description: |-@@ -1817,8 +1811,8 @@ definitions:type: stringx-agent: truemodel_id:- description: ModelID overrides the agent's chat model; empty follows the agent- default.+ description: ModelID overrides the assistant's chat model; empty follows the+ assistant default.type: stringx-agent: truename:@@ -1878,10 +1872,6 @@ definitions:- confirm- auto_writex-agent: true- agent_id:- description: Agent that runs it, from agent.list; empty runs the WeKnora assistant- type: string- x-agent: trueapproval_timeout_minutes:description: How long a run waits for an approval before it fails, in minutestype: integer@@ -1915,7 +1905,7 @@ definitions:type: stringx-agent: truemodel_id:- description: Optional chat model from model.list; empty follows the agent+ description: Optional chat model from model.list; empty follows the assistantdefaulttype: stringx-agent: true@@ -10626,10 +10616,6 @@ definitions:- confirm- auto_writex-agent: true- agent_id:- description: Agent that runs it, from agent.list; empty runs the WeKnora assistant- type: string- x-agent: trueapproval_timeout_minutes:description: How long a run waits for an approval before it fails, in minutes;default 1440@@ -10661,6 +10647,11 @@ definitions:- run_oncetype: stringx-agent: true+ model_id:+ description: Optional chat model from model.list; empty follows the assistant+ default+ type: string+ x-agent: truename:description: What the automation is calledtype: string@@ -15632,12 +15623,12 @@ paths:id: automation.listmax_items: 100risk: read- x-agent-hint: 'Lists the user''s automations: scheduled tasks an agent runs- on their behalf, with next and last run.'+ x-agent-hint: 'Lists the user''s automations: scheduled tasks the WeKnora assistant+ runs on their behalf, with next and last run.'post:consumes:- application/json- description: 创建一个按计划由 Agent 以当前用户身份运行的任务+ description: 创建一个按计划由 WeKnora 助手以当前用户身份运行的任务parameters:- description: 自动化in: body@@ -15672,13 +15663,14 @@ paths:label_param: namerisk: writerole: viewer- x-agent-hint: 'Creates an automation the user runs as. Turn the user''s wording- into a cron expression (five fields, minute first) and an IANA timezone, and- check it with automation.validate_trigger first, telling the user the next- run times it returns. Runs are unattended: write the instruction as a complete- task, since nobody can answer questions during a run. access_level defaults- to confirm, where each change waits for the user''s approval; only set auto_write- when the user asks for it.'+ x-agent-hint: 'Creates an automation the WeKnora assistant runs as the user.+ If work requires other agents, name them and their assignments in the instruction+ so the assistant can delegate. Turn the user''s wording into a cron expression+ (five fields, minute first) and an IANA timezone, and check it with automation.validate_trigger+ first, telling the user the next run times it returns. Runs are unattended:+ write the instruction as a complete task, since nobody can answer questions+ during a run. access_level defaults to confirm, where each change waits for+ the user''s approval; only set auto_write when the user asks for it.'/automations/{id}:delete:description: 停止进行中的运行,删除自动化及其运行记录、会话和长期授权diff --git a/docs/swagger_contract_test.go b/docs/swagger_contract_test.goindex 40c708079..4ce426f80 100644--- a/docs/swagger_contract_test.go+++ b/docs/swagger_contract_test.go@@ -64,6 +64,36 @@ func TestKnowledgeSearchRouteContract(t *testing.T) {}}+func TestAutomationAssistantContract(t *testing.T) {+ for _, tt := range swaggerDocuments() {+ t.Run(tt.name, func(t *testing.T) {+ var spec struct {+ Definitions map[string]struct {+ Properties map[string]any `json:"properties" yaml:"properties"`+ } `json:"definitions" yaml:"definitions"`+ }+ if err := tt.parse(tt.loadSpec(t), &spec); err != nil {+ t.Fatal(err)+ }+ for _, name := range []string{+ "internal_handler.CreateAutomationRequest",+ "github_com_Tencent_WeKnora_internal_types.AutomationPatch",+ "github_com_Tencent_WeKnora_internal_types.Automation",+ } {+ properties := spec.Definitions[name].Properties+ if _, ok := properties["agent_id"]; ok {+ t.Errorf("%s must not expose executor selection", name)+ }+ for _, field := range []string{"instruction", "model_id"} {+ if _, ok := properties[field]; !ok {+ t.Errorf("%s must expose %s", name, field)+ }+ }+ }+ })+ }+}+func TestReleaseAPIContracts(t *testing.T) {for _, tt := range swaggerDocuments() {t.Run(tt.name, func(t *testing.T) {diff --git a/frontend/src/api/automation.ts b/frontend/src/api/automation.tsindex 879a785d4..7fb51d77a 100644--- a/frontend/src/api/automation.ts+++ b/frontend/src/api/automation.ts@@ -39,7 +39,6 @@ export interface Automation {name: stringdescription: stringenabled: boolean- agent_id: stringmodel_id: stringinstruction: stringtrigger: AutomationTrigger@@ -66,7 +65,6 @@ export interface Automation {export type AutomationInput = Partial<Pick<Automation,| 'name'| 'description'- | 'agent_id'| 'model_id'| 'instruction'| 'trigger'diff --git a/frontend/src/i18n/locales/en-US.ts b/frontend/src/i18n/locales/en-US.tsindex 373b06e8f..b3217a236 100755--- a/frontend/src/i18n/locales/en-US.ts+++ b/frontend/src/i18n/locales/en-US.ts@@ -127,19 +127,17 @@ export default {automation: {conversationNotice: "This conversation is run by an automation. Manual messages are unavailable; handle pending requests above.",title: 'Automations',- description: 'Have an agent run tasks on a schedule as you. You are notified of results and pending approvals.',+ description: 'Have the WeKnora assistant run tasks on a schedule as you. You are notified of results and pending approvals.',add: 'New automation',addHint: 'Or ask the WeKnora assistant to set one up',paused: 'Paused',scheduleEnded: 'Ended',scheduleEndedHint: 'This one-time schedule has ended. Run it now, or edit the run time before resuming.',nextRunAt: 'Next {time}',- agentUnavailable: 'Agent unavailable',runConfirm: 'Run "{name}" now? This starts an extra run without changing its schedule.',deleteBody: 'Stops any run in progress and deletes the runs, conversations and standing approvals of "{name}". This cannot be undone.',fields: {name: 'Name',- agent: 'Agent',instruction: 'Task',schedule: 'Schedule',timezone: 'Timezone',@@ -156,16 +154,15 @@ export default {},editor: {model: "Run model",- modelHelp: "Use the agent’s default model or choose one for this automation. Changes apply to future runs.",- modelDefault: "Use agent default",+ modelHelp: 'Use the assistant’s default model or choose one for this task. Delegated agents use their own models. Changes apply to future runs.',+ modelDefault: 'Use assistant default',createTitle: 'New automation',editTitle: 'Edit automation',namePlaceholder: 'e.g. Daily knowledge base digest',instructionPlaceholder: 'Say what to do, which sources to use and how to present the result',variablesHint: 'Variables:',- unattendedHint: 'Nobody is watching a run, so the agent cannot ask you questions. Actions that need approval pause it and notify you.',+ unattendedHint: 'Nobody is watching a run, so the assistant cannot ask you questions. Actions that need approval pause it and notify you.',nameDesc: 'Shown in the list and in notifications so you can tell it apart',- agentDesc: 'The agent that does the task, with its knowledge bases, tools and skills',frequency: 'Repeats',weekdays: 'Days',dayOfMonthDesc: 'In months without this day, it runs on the last day',@@ -184,7 +181,7 @@ export default {sections: {basic: {title: 'Basics',- desc: 'Name the task, pick the agent that runs it and describe what to do.',+ desc: 'The WeKnora assistant runs each task. To delegate work, name the agents and their assignments in the task.',},schedule: {title: 'Schedule',@@ -201,7 +198,7 @@ export default {},sessionModeDesc: {per_run: 'Each run starts a new conversation',- persistent: 'All runs share one conversation, so the agent sees earlier ones',+ persistent: 'All runs share one conversation, so the assistant sees earlier ones',},errors: {name: 'Enter a name',diff --git a/frontend/src/i18n/locales/ja-JP.ts b/frontend/src/i18n/locales/ja-JP.tsindex 98df5a81b..446c1abf2 100644--- a/frontend/src/i18n/locales/ja-JP.ts+++ b/frontend/src/i18n/locales/ja-JP.ts@@ -127,19 +127,17 @@ export default {automation: {conversationNotice: "この会話は自動化タスクが実行します。手動でメッセージは送信できません。保留中のリクエストは上で対応してください。",title: 'オートメーション',- description: 'エージェントにスケジュールどおりあなたとしてタスクを実行させます。結果と承認待ちは通知されます。',+ description: 'WeKnora アシスタントがあなたに代わって定期的にタスクを実行します。結果と承認待ちの操作を通知します。',add: '新規オートメーション',addHint: 'WeKnora アシスタントに作成を頼むこともできます',paused: '一時停止中',scheduleEnded: '終了',scheduleEndedHint: 'この一回限りのスケジュールは終了しました。今すぐ実行するか、実行日時を変更してから再開してください。',nextRunAt: '次回 {time}',- agentUnavailable: 'エージェントを利用できません',runConfirm: '「{name}」を今すぐ実行しますか?スケジュールを変更せずに追加で実行します。',deleteBody: '実行中の処理を停止し、「{name}」の実行履歴・会話・継続承認を削除します。元に戻せません。',fields: {name: '名前',- agent: '実行エージェント',instruction: 'タスク',schedule: 'スケジュール',timezone: 'タイムゾーン',@@ -156,16 +154,15 @@ export default {},editor: {model: "実行モデル",- modelHelp: "エージェントの既定モデルを使うか、この自動化専用のモデルを選択します。変更は次回以降の実行に適用されます。",- modelDefault: "エージェントの既定モデル",+ modelHelp: 'アシスタントの既定モデルを使うか、このタスク用に指定します。委任先のエージェントはそれぞれのモデルを使います。変更は次回以降の実行に適用されます。',+ modelDefault: 'アシスタントの既定モデル',createTitle: '新規オートメーション',editTitle: 'オートメーションを編集',namePlaceholder: '例:毎日のナレッジベース要約',instructionPlaceholder: '何をするか、どの資料を使うか、結果をどう出すかを書いてください',variablesHint: '使える変数:',- unattendedHint: '実行中は誰も見ていないため、エージェントは質問できません。承認が必要な操作は一時停止して通知します。',+ unattendedHint: '実行中は誰も見ていないため、アシスタントは質問できません。承認が必要な操作は一時停止して通知します。',nameDesc: '一覧と通知に表示され、タスクを見分けるのに使います',- agentDesc: 'タスクを実行するエージェント。そのナレッジベース、ツール、スキルを使えます',frequency: '繰り返し',weekdays: '曜日',dayOfMonthDesc: 'その日がない月は月末に実行します',@@ -184,7 +181,7 @@ export default {sections: {basic: {title: '基本情報',- desc: 'タスクに名前を付け、実行するエージェントを選び、やることを書きます。',+ desc: 'WeKnora アシスタントがタスクを実行します。他のエージェントに委任する場合は、タスクに委任先と作業内容を記載してください。',},schedule: {title: '実行スケジュール',@@ -201,7 +198,7 @@ export default {},sessionModeDesc: {per_run: '実行ごとに新しい会話を開きます',- persistent: 'すべての実行が同じ会話で行われ、以前の内容を参照できます',+ persistent: 'すべての実行で同じ会話を使い、アシスタントが過去の内容を参照できます',},errors: {name: '名前を入力してください',diff --git a/frontend/src/i18n/locales/ko-KR.ts b/frontend/src/i18n/locales/ko-KR.tsindex 4986b9a23..a248ae28d 100755--- a/frontend/src/i18n/locales/ko-KR.ts+++ b/frontend/src/i18n/locales/ko-KR.ts@@ -127,19 +127,17 @@ export default {automation: {conversationNotice: "자동화 작업이 실행하는 대화입니다. 메시지를 직접 보낼 수 없습니다. 대기 중인 요청은 위에서 처리하세요.",title: '자동화',- description: '에이전트가 일정에 따라 사용자 본인으로 작업을 실행합니다. 결과와 승인 대기 항목은 알림으로 받습니다.',+ description: 'WeKnora 도우미가 예약된 시간에 사용자를 대신해 작업을 실행합니다. 결과와 승인 대기 항목을 알려드립니다.',add: '새 자동화',addHint: 'WeKnora 어시스턴트에게 만들어 달라고 할 수도 있습니다',paused: '일시 중지됨',scheduleEnded: '종료됨',scheduleEndedHint: '일회성 일정이 종료되었습니다. 지금 실행하거나 실행 시간을 변경한 후 재개하세요.',nextRunAt: '다음 {time}',- agentUnavailable: '에이전트를 사용할 수 없음',runConfirm: '"{name}"을(를) 지금 실행할까요? 기존 일정을 변경하지 않고 추가로 실행합니다.',deleteBody: '진행 중인 실행을 중지하고 "{name}"의 실행 기록, 대화, 상시 승인을 삭제합니다. 되돌릴 수 없습니다.',fields: {name: '이름',- agent: '실행 에이전트',instruction: '작업',schedule: '일정',timezone: '시간대',@@ -156,16 +154,15 @@ export default {},editor: {model: "실행 모델",- modelHelp: "에이전트의 기본 모델을 사용하거나 이 자동화에 사용할 모델을 선택하세요. 변경 사항은 다음 실행부터 적용됩니다.",- modelDefault: "에이전트 기본 모델 사용",+ modelHelp: '도우미의 기본 모델을 사용하거나 이 작업에 사용할 모델을 선택하세요. 위임받은 에이전트는 각자의 모델을 사용합니다. 변경 사항은 이후 실행에 적용됩니다.',+ modelDefault: '도우미 기본 모델 사용',createTitle: '새 자동화',editTitle: '자동화 편집',namePlaceholder: '예: 매일 지식 베이스 요약',instructionPlaceholder: '무엇을 할지, 어떤 자료를 쓸지, 결과를 어떻게 낼지 적어 주세요',variablesHint: '사용 가능한 변수:',- unattendedHint: '실행 중에는 아무도 보고 있지 않으므로 에이전트가 질문할 수 없습니다. 승인이 필요한 작업은 일시 중지되고 알림이 갑니다.',+ unattendedHint: '실행 중에는 사용자가 없으므로 도우미가 질문할 수 없습니다. 승인이 필요한 작업은 일시 중지되고 알림이 전송됩니다.',nameDesc: '목록과 알림에 표시되어 작업을 구분하는 데 쓰입니다',- agentDesc: '작업을 실행할 에이전트. 해당 지식베이스, 도구, 스킬을 사용할 수 있습니다',frequency: '반복',weekdays: '요일',dayOfMonthDesc: '해당 날짜가 없는 달에는 마지막 날에 실행합니다',@@ -184,7 +181,7 @@ export default {sections: {basic: {title: '기본 정보',- desc: '작업 이름을 정하고, 실행할 에이전트를 고른 뒤 할 일을 적습니다.',+ desc: 'WeKnora 도우미가 작업을 실행합니다. 다른 에이전트에 위임하려면 작업에 에이전트와 맡길 일을 명시하세요.',},schedule: {title: '실행 시간',@@ -201,7 +198,7 @@ export default {},sessionModeDesc: {per_run: '실행마다 새 대화를 엽니다',- persistent: '모든 실행이 같은 대화에서 진행되어 이전 내용을 볼 수 있습니다',+ persistent: '모든 실행이 하나의 대화를 공유하므로 도우미가 이전 내용을 볼 수 있습니다',},errors: {name: '이름을 입력하세요',diff --git a/frontend/src/i18n/locales/ru-RU.ts b/frontend/src/i18n/locales/ru-RU.tsindex 77b076563..9d93157d5 100755--- a/frontend/src/i18n/locales/ru-RU.ts+++ b/frontend/src/i18n/locales/ru-RU.ts@@ -127,19 +127,17 @@ export default {automation: {conversationNotice: "Этот диалог выполняется автоматизацией. Отправка сообщений вручную недоступна. Обработайте ожидающие запросы выше.",title: 'Автоматизации',- description: 'Агент выполняет задачи по расписанию от вашего имени. О результатах и ожидающих подтверждениях вы получите уведомление.',+ description: 'Помощник WeKnora выполняет задачи по расписанию от вашего имени. О результатах и ожидающих подтверждениях вы получите уведомление.',add: 'Новая автоматизация',addHint: 'Или попросите ассистента WeKnora создать её',paused: 'Приостановлена',scheduleEnded: 'Завершено',scheduleEndedHint: 'Время однократного запуска прошло. Запустите сейчас или измените время перед возобновлением.',nextRunAt: 'Далее {time}',- agentUnavailable: 'Агент недоступен',runConfirm: 'Запустить «{name}» сейчас? Дополнительный запуск не изменит расписание.',deleteBody: 'Текущий запуск будет остановлен, а запуски, беседы и постоянные разрешения «{name}» удалены. Это действие необратимо.',fields: {name: 'Название',- agent: 'Агент',instruction: 'Задача',schedule: 'Расписание',timezone: 'Часовой пояс',@@ -156,16 +154,15 @@ export default {},editor: {model: "Модель запуска",- modelHelp: "Используйте модель агента по умолчанию или выберите другую для этой автоматизации. Изменения применяются к последующим запускам.",- modelDefault: "Модель агента по умолчанию",+ modelHelp: 'Используйте модель помощника по умолчанию или выберите другую для этой задачи. Агенты, которым поручена работа, используют свои модели. Изменения применяются к последующим запускам.',+ modelDefault: 'Модель помощника по умолчанию',createTitle: 'Новая автоматизация',editTitle: 'Изменить автоматизацию',namePlaceholder: 'Например: ежедневная сводка базы знаний',instructionPlaceholder: 'Опишите, что сделать, какие источники использовать и как оформить результат',variablesHint: 'Переменные:',- unattendedHint: 'За запуском никто не следит, поэтому агент не может задавать вопросы. Действия, требующие подтверждения, приостанавливают запуск и присылают уведомление.',+ unattendedHint: 'За запуском никто не следит, поэтому помощник не может задавать вопросы. Действия, требующие подтверждения, приостанавливают запуск и присылают уведомление.',nameDesc: 'Показывается в списке и уведомлениях, чтобы отличать задачу',- agentDesc: 'Агент, который выполняет задачу, со своими базами знаний, инструментами и навыками',frequency: 'Повтор',weekdays: 'Дни недели',dayOfMonthDesc: 'В месяцы без этого дня запуск будет в последний день',@@ -184,7 +181,7 @@ export default {sections: {basic: {title: 'Основное',- desc: 'Назовите задачу, выберите агента и опишите, что нужно сделать.',+ desc: 'Задачи выполняет помощник WeKnora. Для делегирования укажите в задаче агентов и порученную им работу.',},schedule: {title: 'Расписание',@@ -201,7 +198,7 @@ export default {},sessionModeDesc: {per_run: 'Каждый запуск открывает новый диалог',- persistent: 'Все запуски идут в одном диалоге, агент видит прошлые',+ persistent: 'Все запуски используют один диалог, поэтому помощник видит предыдущие сообщения',},errors: {name: 'Введите название',diff --git a/frontend/src/i18n/locales/zh-CN.ts b/frontend/src/i18n/locales/zh-CN.tsindex b41df4466..416981d25 100755--- a/frontend/src/i18n/locales/zh-CN.ts+++ b/frontend/src/i18n/locales/zh-CN.ts@@ -127,19 +127,17 @@ export default {automation: {conversationNotice: "此会话由自动化任务运行,不能手动发送消息。请在上方处理待审批事项。",title: '自动化',- description: '让智能体按计划以你的身份执行任务,结果和待审批事项会通知你。',+ description: '让 WeKnora 助手按计划以你的身份执行任务,结果和待审批事项会通知你。',add: '新建自动化',addHint: '也可以直接让 WeKnora 助手帮你创建',paused: '已暂停',scheduleEnded: '已结束',scheduleEndedHint: '一次性计划已结束。可立即运行,或修改运行时间后恢复。',nextRunAt: '下次 {time}',- agentUnavailable: '智能体不可用',runConfirm: '立即运行「{name}」?这将启动一次额外运行,不影响原有计划。',deleteBody: '将停止进行中的运行,并删除「{name}」的运行记录、对话和长期授权。此操作无法撤销。',fields: {name: '名称',- agent: '执行智能体',instruction: '任务',schedule: '运行时间',timezone: '时区',@@ -156,16 +154,15 @@ export default {},editor: {model: "运行模型",- modelHelp: "默认沿用智能体的模型设置,也可以为此自动化单独指定。修改后用于后续运行。",- modelDefault: "跟随智能体默认模型",+ modelHelp: '默认沿用助手的模型设置,也可以单独指定。委派的智能体使用各自的模型。修改后用于后续运行。',+ modelDefault: '跟随助手默认模型',createTitle: '新建自动化',editTitle: '编辑自动化',namePlaceholder: '例如:每日知识库周报',instructionPlaceholder: '写清楚要做什么、用哪些资料、结果如何输出',variablesHint: '可用变量:',- unattendedHint: '运行时无人在场,智能体不能向你提问;需要审批的操作会暂停并通知你。',+ unattendedHint: '运行时无人在场,助手不能向你提问;需要审批的操作会暂停并通知你。',nameDesc: '在列表和通知里显示,方便你认出这项任务',- agentDesc: '由哪个智能体执行任务,它的知识库、工具和技能都可用',frequency: '重复频率',weekdays: '星期',dayOfMonthDesc: '当月没有这一天时,在最后一天运行',@@ -184,7 +181,7 @@ export default {sections: {basic: {title: '基本信息',- desc: '给任务起个名字,选择执行的智能体,并写下要做的事。',+ desc: '任务由 WeKnora 助手执行。需要其他智能体时,请在任务中写明委派对象和工作。',},schedule: {title: '运行时间',@@ -201,7 +198,7 @@ export default {},sessionModeDesc: {per_run: '每次运行开一个新对话,互不影响',- persistent: '所有运行都在同一个对话里,智能体能看到之前的内容',+ persistent: '所有运行都在同一个对话里,助手能看到之前的内容',},errors: {name: '请填写名称',diff --git a/frontend/src/i18n/locales/zh-TW.ts b/frontend/src/i18n/locales/zh-TW.tsindex e79ae7e38..e0dab87a9 100644--- a/frontend/src/i18n/locales/zh-TW.ts+++ b/frontend/src/i18n/locales/zh-TW.ts@@ -127,19 +127,17 @@ export default {automation: {conversationNotice: "此對話由自動化任務執行,無法手動傳送訊息。請在上方處理待審批事項。",title: '自動化',- description: '讓智慧代理按排程以你的身分執行任務,結果與待審批事項會通知你。',+ description: '讓 WeKnora 助手按排程以你的身分執行任務,結果與待審批事項會通知你。',add: '新增自動化',addHint: '也可以直接請 WeKnora 助手幫你建立',paused: '已暫停',scheduleEnded: '已結束',scheduleEndedHint: '一次性排程已結束。可立即執行,或修改執行時間後恢復。',nextRunAt: '下次 {time}',- agentUnavailable: '智慧代理不可用',runConfirm: '立即執行「{name}」?這會啟動一次額外執行,不影響原有排程。',deleteBody: '將停止進行中的執行,並刪除「{name}」的執行紀錄、對話與長期授權。此操作無法復原。',fields: {name: '名稱',- agent: '執行智慧代理',instruction: '任務',schedule: '執行時間',timezone: '時區',@@ -156,16 +154,15 @@ export default {},editor: {model: "執行模型",- modelHelp: "預設沿用智慧體的模型設定,也可以為此自動化單獨指定。修改後用於後續執行。",- modelDefault: "跟隨智慧體預設模型",+ modelHelp: '預設沿用助手的模型設定,也可以單獨指定。受委派的智慧代理使用各自的模型。修改後用於後續執行。',+ modelDefault: '跟隨助手預設模型',createTitle: '新增自動化',editTitle: '編輯自動化',namePlaceholder: '例如:每日知識庫週報',instructionPlaceholder: '寫清楚要做什麼、用哪些資料、結果如何輸出',variablesHint: '可用變數:',- unattendedHint: '執行時無人在場,智慧代理不能向你提問;需要審批的操作會暫停並通知你。',+ unattendedHint: '執行時無人在場,助手不能向你提問;需要審批的操作會暫停並通知你。',nameDesc: '在列表和通知中顯示,方便你認出這項任務',- agentDesc: '由哪個智慧體執行任務,它的知識庫、工具和技能都可用',frequency: '重複頻率',weekdays: '星期',dayOfMonthDesc: '當月沒有這一天時,在最後一天執行',@@ -184,7 +181,7 @@ export default {sections: {basic: {title: '基本資訊',- desc: '為任務命名,選擇執行的智慧體,並寫下要做的事。',+ desc: '任務由 WeKnora 助手執行。需要其他智慧代理時,請在任務中寫明委派對象與工作。',},schedule: {title: '執行時間',@@ -201,7 +198,7 @@ export default {},sessionModeDesc: {per_run: '每次執行開一個新對話,互不影響',- persistent: '所有執行都在同一個對話中,智慧體能看到先前的內容',+ persistent: '所有執行都在同一個對話裡,助手能看到之前的內容',},errors: {name: '請填寫名稱',diff --git a/frontend/src/views/automation/AutomationDetail.vue b/frontend/src/views/automation/AutomationDetail.vueindex 31a4e680c..f697ce16f 100644--- a/frontend/src/views/automation/AutomationDetail.vue+++ b/frontend/src/views/automation/AutomationDetail.vue@@ -43,7 +43,6 @@<div class="automation-detail__brief-context"><h3>{{ t('automation.detail.task') }}</h3><div class="automation-detail__execution">- <span :title="t('automation.fields.agent')">{{ agentName }}</span><span :title="t('automation.fields.accessLevel')">{{ t(`assistant.access.levels.${automation.access_level}.label`) }}</span><span :title="t('automation.fields.sessionMode')">{{ t(`automation.sessionMode.${automation.session_mode}`) }}</span></div>@@ -203,7 +202,6 @@ import ChatActionIcon from '@/components/ChatActionIcon.vue'const props = defineProps<{visible: booleanautomation: Automation | null- agentName: stringfocusRunId?: string}>()const emit = defineEmits<{diff --git a/frontend/src/views/automation/AutomationEditor.vue b/frontend/src/views/automation/AutomationEditor.vueindex d274bd47c..5a35529b7 100644--- a/frontend/src/views/automation/AutomationEditor.vue+++ b/frontend/src/views/automation/AutomationEditor.vue@@ -19,17 +19,6 @@<t-input v-model="form.name" :maxlength="100" :placeholder="t('automation.editor.namePlaceholder')" /></div></div>- <div class="setting-row">- <div class="setting-info">- <label>{{ t('automation.fields.agent') }}</label>- <p class="desc">{{ t('automation.editor.agentDesc') }}</p>- </div>- <div class="setting-control">- <t-select v-model="form.agent_id" :loading="agentsLoading" filterable>- <t-option v-for="agent in agentOptions" :key="agent.id" :value="agent.id" :label="agent.name" />- </t-select>- </div>- </div><div class="setting-row"><div class="setting-info"><label>{{ t('automation.editor.model') }}</label>@@ -323,16 +312,12 @@ import {weekdayName,type ScheduleKind,} from '@/utils/automationSchedule'-import type { AutomationAgentOption } from './agents'import ModelSelector from '@/components/ModelSelector.vue'import { useUIStore } from '@/stores/ui'const props = defineProps<{visible: booleanautomation: Automation | null- agents: AutomationAgentOption[]- agentsLoading?: boolean- defaultAgentId: string}>()const emit = defineEmits<{ 'update:visible': [value: boolean]; saved: [value: Automation] }>()@@ -368,7 +353,6 @@ const navGroups = computed(() => [const blank = (): Required<Omit<AutomationInput, 'trigger' | 'limits' | 'description'>> => ({name: '',- agent_id: props.defaultAgentId,model_id: '',instruction: '',session_mode: 'per_run',@@ -388,14 +372,6 @@ const saving = ref(false)const zones = computed(() => timezoneOptions(timezone.value))-const agentOptions = computed(() => {- const list = [...props.agents]- if (form.agent_id && !list.some((a) => a.id === form.agent_id)) {- list.push({ id: form.agent_id, name: t('automation.agentUnavailable') })- }- return list-})-const approvalHours = computed({get: () => Math.max(1, Math.round(form.approval_timeout_minutes / 60)),set: (v: number | undefined) => {@@ -436,7 +412,6 @@ watch(() => props.visible, (open) => {if (a) {Object.assign(form, {name: a.name,- agent_id: a.agent_id,model_id: a.model_id || '',instruction: a.instruction,session_mode: a.session_mode,diff --git a/frontend/src/views/automation/AutomationList.vue b/frontend/src/views/automation/AutomationList.vueindex e4fabca09..41b6ba265 100644--- a/frontend/src/views/automation/AutomationList.vue+++ b/frontend/src/views/automation/AutomationList.vue@@ -66,7 +66,6 @@</p><div class="automation-card__footer"><div class="automation-card__meta">- <span>{{ agentName(item.agent_id) }}</span><span v-if="item.enabled && item.next_run_at">{{ t('automation.nextRunAt', { time: formatInZone(item.next_run_at, item.trigger.timezone, locale) }) }}</span>@@ -92,9 +91,8 @@</div></section>- <AutomationEditor v-model:visible="editorVisible" :automation="editing" :agents="agents"- :agents-loading="agentsLoading" :default-agent-id="BUILTIN_WEKNORA_ASSISTANT_ID" @saved="onSaved" />- <AutomationDetail v-model:visible="detailVisible" :automation="detail" :agent-name="detail ? agentName(detail.agent_id) : ''"+ <AutomationEditor v-model:visible="editorVisible" :automation="editing" @saved="onSaved" />+ <AutomationDetail v-model:visible="detailVisible" :automation="detail":focus-run-id="focusRunId" @changed="onSaved" @edit="openEditor" /></main></template>@@ -104,7 +102,6 @@ import { computed, onBeforeUnmount, onMounted, ref, watch } from 'vue'import { useRoute, useRouter } from 'vue-router'import { useI18n } from 'vue-i18n'import { MessagePlugin } from 'tdesign-vue-next'-import { BUILTIN_WEKNORA_ASSISTANT_ID } from '@/api/agent'import {deleteAutomation,getAutomation,@@ -114,7 +111,6 @@ import {runAutomationNow,type Automation,} from '@/api/automation'-import { useAuthStore } from '@/stores/auth'import { describeTrigger, formatInZone, hasEndedOnceSchedule } from '@/utils/automationSchedule'import { useAssistantDataChange } from '@/utils/assistantDataChange'import AutomationEditor from './AutomationEditor.vue'@@ -122,19 +118,15 @@ import AutomationDetail from './AutomationDetail.vue'import AutomationStatusTag from './AutomationStatusTag.vue'import ChatActionIcon from '@/components/ChatActionIcon.vue'import ResourceIcon from '@/components/icons/ResourceIcon.vue'-import { loadAutomationAgents, type AutomationAgentOption } from './agents'const { t, locale } = useI18n()const route = useRoute()const router = useRouter()-const authStore = useAuthStore()const automations = ref<Automation[]>([])const loading = ref(true)const query = ref('')const busy = ref(new Set<string>())-const agents = ref<AutomationAgentOption[]>([])-const agentsLoading = ref(false)const editorVisible = ref(false)const editing = ref<Automation | null>(null)const detailVisible = ref(false)@@ -149,9 +141,6 @@ const filtered = computed(() => {a.name.toLowerCase().includes(q) || a.instruction.toLowerCase().includes(q))})-const agentName = (id: string) =>- agents.value.find((a) => a.id === id)?.name ?? t('automation.agentUnavailable')-async function load() {const version = ++loadVersiontry {@@ -176,17 +165,6 @@ async function load() {useAssistantDataChange(() => { void load() }, { areas: ['automation'] })onBeforeUnmount(() => { ++loadVersion })-async function loadAgents() {- agentsLoading.value = true- try {- agents.value = await loadAutomationAgents(authStore.currentTenantId, t('assistant.title'))- } catch {- agents.value = [{ id: BUILTIN_WEKNORA_ASSISTANT_ID, name: t('assistant.title') }]- } finally {- agentsLoading.value = false- }-}-function replace(item: Automation) {const index = automations.value.findIndex((a) => a.id === item.id)if (index >= 0) automations.value.splice(index, 1, item)@@ -285,7 +263,6 @@ async function remove(item: Automation) {}onMounted(async () => {- void loadAgents()await load()await openFromRoute()})diff --git a/frontend/src/views/automation/agents.ts b/frontend/src/views/automation/agents.tsdeleted file mode 100644index db4e6aa13..000000000--- a/frontend/src/views/automation/agents.ts+++ /dev/null@@ -1,36 +0,0 @@-import { BUILTIN_WEKNORA_ASSISTANT_ID, listAgents, type CustomAgent } from '@/api/agent'--export interface AutomationAgentOption {- id: string- name: string-}--// Built-in agents that serve one feature and cannot run an automation.-const RESERVED = new Set(['builtin-wiki-fixer', 'builtin-skill-installer'])--/**- * Agents the server accepts for an automation: the WeKnora assistant, then- * this workspace's smart-reasoning agents. Agents shared in from other- * workspaces are left out because a run would be refused.- */-export function automationAgentOptions(- agents: CustomAgent[],- tenantId: number | string | null | undefined,- assistantName: string,-): AutomationAgentOption[] {- const tenant = tenantId == null ? null : Number(tenantId)- const runnable = agents.filter((agent) =>- agent.id !== BUILTIN_WEKNORA_ASSISTANT_ID- && !RESERVED.has(agent.id)- && agent.config?.agent_mode === 'smart-reasoning'- && (tenant === null || agent.tenant_id == null || Number(agent.tenant_id) === tenant))- return [- { id: BUILTIN_WEKNORA_ASSISTANT_ID, name: assistantName },- ...runnable.map((agent) => ({ id: agent.id, name: agent.name })),- ]-}--export async function loadAutomationAgents(tenantId: number | string | null | undefined, assistantName: string) {- const res = await listAgents()- return automationAgentOptions(res.data ?? [], tenantId, assistantName)-}diff --git a/frontend/src/views/automation/automationInteractions.test.ts b/frontend/src/views/automation/automationInteractions.test.tsindex 961006fce..d52c6f917 100644--- a/frontend/src/views/automation/automationInteractions.test.ts+++ b/frontend/src/views/automation/automationInteractions.test.ts@@ -12,7 +12,7 @@ const useInputNumber = require('tdesign-vue-next/cjs/input-number/hooks/useInputconst numberProps = require('tdesign-vue-next/cjs/input-number/props.js').defaultconst automation = {- id: 'automation-1', name: 'Reminder', instruction: 'Take a break', agent_id: 'assistant',+ id: 'automation-1', name: 'Reminder', instruction: 'Take a break',trigger: { type: 'cron', expr: '0 9 * * *', timezone: 'Asia/Shanghai' },approval_timeout_minutes: 1440, limits: { max_duration_minutes: 30 },enabled: true, session_mode: 'per_run', access_level: 'confirm',@@ -27,11 +27,8 @@ function setup(t: TestContext, file: string, api: Record<string, unknown>, props'vue-router': { useRoute: () => ({ params: {}, query: {} }), useRouter: () => ({ replace() {}, push() {} }) },'tdesign-vue-next': { MessagePlugin: { success() {}, error() {}, warning() {} } },'@/api/automation': api,- '@/api/agent': { BUILTIN_WEKNORA_ASSISTANT_ID: 'assistant' },'@/api/assistant': { ASSISTANT_ACCESS_LEVELS: ['read_only', 'confirm', 'auto_write'] },- '@/stores/auth': { useAuthStore: () => ({ currentTenantId: 'tenant' }) },'@/stores/ui': { useUIStore: () => ({ openSettings() {} }) },- './agents': { loadAutomationAgents: async () => [] },'@/utils/automationSchedule': schedule,'@/composables/useModalShell': { useModalShell: () => ({ markClean() {}, requestClose() {} }) },}, props)@@ -123,7 +120,7 @@ test('assistant run-now refreshes idle history after any in-flight load and pres: Promise.resolve({ data: [newRun, oldRun], total: 3 }),listAutomationGrants: async () => ({ data: [] }),listAutomationGrantCandidates: async () => ({ data: [] }),- }, { visible: true, automation, agentName: 'Assistant' })+ }, { visible: true, automation })emit(change('automation.run_now'))t.mock.timers.tick(300)assert.equal(calls, 1, 'wait for the initial page before merging newer runs')@@ -146,7 +143,7 @@ test('assistant run-now refreshes idle history after any in-flight load and prestest('task content fades only while more text remains below the scroll position', async t => {const { vm, render } = setup(t, './AutomationDetail.vue', {},- { visible: false, automation, agentName: 'Assistant' })+ { visible: false, automation })const scroller = vue.markRaw({ scrollHeight: 320, clientHeight: 160, scrollTop: 0 })vm.instructionScroller = scrollerawait vue.nextTick()@@ -184,7 +181,7 @@ test('task content fades only while more text remains below the scroll position'test('approval hours update in both directions and save as minutes, without resetting on an empty edit', async t => {let saved: any- const props = { visible: false, automation, agents: [], defaultAgentId: 'assistant' }+ const props = { visible: false, automation }const { vm, render, mount } = setup(t, './AutomationEditor.vue', {updateAutomation: async (_id: string, input: unknown) => { saved = input; return { data: automation } },validateAutomationTrigger: async () => ({ data: { next_runs: [] } }),@@ -229,7 +226,7 @@ test('the editor preserves, changes, and clears an automation model override', aconst { vm } = setup(t, './AutomationEditor.vue', {updateAutomation: async (_id: string, input: unknown) => { saved.push(input); return { data: automation } },validateAutomationTrigger: async () => ({ data: { next_runs: [] } }),- }, { visible: false, automation: { ...automation, model_id: 'model-one' }, agents: [], defaultAgentId: 'assistant' })+ }, { visible: false, automation: { ...automation, model_id: 'model-one' } })vm.$.props.visible = trueawait vue.nextTick()assert.equal(vm.form.model_id, 'model-one')@@ -238,7 +235,7 @@ test('the editor preserves, changes, and clears an automation model override', aassert.equal(saved[0].model_id, 'model-two')vm.form.model_id = ''await vm.save()- assert.equal(saved[1].model_id, '', 'clearing restores the agent default instead of omitting the patch')+ assert.equal(saved[1].model_id, '', 'clearing restores the assistant default instead of omitting the patch')})test('list run and delete actions call APIs only after their inline confirmation', async t => {@@ -270,7 +267,7 @@ test('list run and delete actions call APIs only after their inline confirmationtest('run history groups by the automation timezone and drawer run requires confirmation', async t => {let runCalls = 0- const props = { visible: false, automation, agentName: 'Assistant' }+ const props = { visible: false, automation }const { vm, render } = setup(t, './AutomationDetail.vue', {runAutomationNow: async () => { runCalls++; return { data: { id: 'new-run' } } },}, props)@@ -299,7 +296,7 @@ test('grant popup preserves history and dismisses when starting a run or reopenilistAutomationGrantCandidates: async () => ({ data: [{ prompt_id: 'approval-1', label: 'Update document', risk: 'write' }] }),listAutomationRuns: async () => ({ data: [], total: 0 }),runAutomationNow: async () => ({ data: { id: 'new-run' } }),- }, { visible: false, automation, agentName: 'Assistant' })+ }, { visible: false, automation })assert.equal(vm.grantsVisible, false)const popup = nodes(render()).find(node => node.type?.name === 't-popup')popup.props['onUpdate:visible'](true)@@ -326,7 +323,7 @@ for (const file of ['./AutomationList.vue', './AutomationDetail.vue']) {const { vm, render } = setup(t, file, {listAutomations: async () => ({ data: [item] }),resumeAutomation: async () => { resumeCalls++; return { data: { ...item, enabled: true } } },- }, { visible: false, automation: item, agentName: 'Assistant' })+ }, { visible: false, automation: item })await flush()const resumeButton = () => nodes(render()).find(node => node.type === 'button'&& (node.props?.role === 'switch' || node.props?.['aria-label'] === 'automation.actions.resume'))diff --git a/internal/application/service/automation.go b/internal/application/service/automation.goindex 3c8308617..2b2871b55 100644--- a/internal/application/service/automation.go+++ b/internal/application/service/automation.go@@ -240,9 +240,6 @@ func applyAutomationPatch(a *types.Automation, p *types.AutomationPatch) {if p.Description != nil {a.Description = strings.TrimSpace(*p.Description)}- if p.AgentID != nil {- a.AgentID = strings.TrimSpace(*p.AgentID)- }if p.ModelID != nil {a.ModelID = strings.TrimSpace(*p.ModelID)}@@ -286,10 +283,7 @@ func (s *AutomationService) validate(ctx context.Context, a *types.Automation) (if a.Instruction == "" || len([]rune(a.Instruction)) > maxAutomationInstructionRune {return nil, badAutomation("instruction is required, at most %d characters", maxAutomationInstructionRune)}- if a.AgentID == "" {- a.AgentID = types.BuiltinWeKnoraAssistantID- }- if _, err := s.runnableAgent(ctx, a.AgentID, a.TenantID); err != nil {+ if _, err := s.runnableAssistant(ctx); err != nil {return nil, apperrors.NewBadRequestError(err.Error())}if err := s.validateModel(ctx, a.ModelID, a.TenantID); err != nil {@@ -346,23 +340,14 @@ func (s *AutomationService) validate(ctx context.Context, a *types.Automation) (return sched, nil}-// runnableAgent loads agent id for a run in tenantID: a smart-reasoning-// agent of the workspace, or the WeKnora assistant. ctx must carry tenantID.-func (s *AutomationService) runnableAgent(ctx context.Context, id string, tenantID uint64) (*types.CustomAgent, error) {- if id == types.BuiltinWikiFixerID || id == types.BuiltinSkillInstallerID {- return nil, errors.New("this built-in agent cannot run automations")- }- agent, err := s.agents.GetAgentByID(ctx, id)- if err != nil || agent == nil {- return nil, fmt.Errorf("agent %s is not available in this workspace", id)- }- if !types.GrantsOperationCatalog(agent) && agent.TenantID != tenantID {- return nil, fmt.Errorf("agent %s is not available in this workspace", id)- }- if !agent.IsAgentMode() {- return nil, fmt.Errorf("agent %s must use smart reasoning to run automations", id)+// runnableAssistant loads the workspace assistant, the sole automation executor.+// Tasks may ask it to delegate work to other agents through the instruction.+func (s *AutomationService) runnableAssistant(ctx context.Context) (*types.CustomAgent, error) {+ assistant, err := s.agents.GetAgentByID(ctx, types.BuiltinWeKnoraAssistantID)+ if err != nil || assistant == nil || !types.GrantsOperationCatalog(assistant) || !assistant.IsAgentMode() {+ return nil, errors.New("the WeKnora assistant is unavailable in this workspace")}- return agent, nil+ return assistant, nil}func (s *AutomationService) validateModel(ctx context.Context, id string, tenantID uint64) error {@@ -415,7 +400,7 @@ func (s *AutomationService) Create(ctx context.Context, p *types.AutomationPatch}var automationEditable = []string{- "name", "description", "agent_id", "model_id", "instruction", "trigger_config", "session_mode", "carry_last_result",+ "name", "description", "model_id", "instruction", "trigger_config", "session_mode", "carry_last_result","misfire_policy", "overlap_policy", "access_level", "approval_timeout_minutes", "limits","notify_on_success", "enabled", "next_run_at", "paused_reason", "consecutive_failures", "version","updated_at",@@ -728,7 +713,7 @@ type AutomationGrantCandidate struct {// binding is what a's standing grants are given under right now.func (s *AutomationService) binding(ctx context.Context, a *types.Automation) (string, error) {- agent, err := s.runnableAgent(ctx, a.AgentID, a.TenantID)+ agent, err := s.runnableAssistant(ctx)if err != nil {return "", err}diff --git a/internal/application/service/automation_runner.go b/internal/application/service/automation_runner.goindex 2dc5108ec..ab31e05d2 100644--- a/internal/application/service/automation_runner.go+++ b/internal/application/service/automation_runner.go@@ -231,7 +231,7 @@ func (s *AutomationService) runOnce(ctx context.Context, run *types.AutomationRu}return failed(err.Error())}- agentConfig, err := s.runnableAgent(ctx, a.AgentID, a.TenantID)+ agentConfig, err := s.runnableAssistant(ctx)if err != nil {return runOutcome{status: types.AutomationRunFailed, reason: err.Error(), pause: err.Error()}}@@ -363,7 +363,7 @@ func (s *AutomationService) runSession(ID: uuid.NewString(), TenantID: a.TenantID, UserID: a.OwnerUserID, Kind: types.SessionKindAutomation,Title: clipRunes(title, 200), CreatedAt: now, UpdatedAt: now,LastRequestState: &types.SessionLastRequestState{- AgentID: a.AgentID, AgentEnabled: true, ModelID: a.ModelID,+ AgentID: types.BuiltinWeKnoraAssistantID, AgentEnabled: true, ModelID: a.ModelID,},}if err := s.db.WithContext(ctx).Session(&gorm.Session{SkipHooks: true}).diff --git a/internal/application/service/automation_test.go b/internal/application/service/automation_test.goindex ad4846305..988581232 100644--- a/internal/application/service/automation_test.go+++ b/internal/application/service/automation_test.go@@ -103,6 +103,18 @@ func complete(ctx context.Context, bus *event.EventBus, data event.AgentCompletereturn bus.Emit(ctx, event.Event{Type: event.EventAgentComplete, Data: data})}+type automationAgents struct {+ interfaces.CustomAgentService+ agent *types.CustomAgent+}++func (f *automationAgents) GetAgentByID(_ context.Context, id string) (*types.CustomAgent, error) {+ if id != types.BuiltinWeKnoraAssistantID {+ return nil, errors.New("automations must load the WeKnora assistant")+ }+ return f.agent, nil+}+type automationFixture struct {svc *AutomationServicedb *gorm.DB@@ -110,7 +122,7 @@ type automationFixture struct {messages *automationMessagesusers *collaborationUsersmembers *collaborationMembers- agents *collaborationAgents+ agents *automationAgentsbroker *hitl.Brokernow time.Timectx context.Context@@ -133,8 +145,8 @@ func newAutomationFixture(t *testing.T) *automationFixture {messages: &automationMessages{rows: map[string]*types.Message{}},users: &collaborationUsers{active: true},members: &collaborationMembers{active: true},- agents: &collaborationAgents{agent: &types.CustomAgent{- ID: "a", TenantID: automationTenant,+ agents: &automationAgents{agent: &types.CustomAgent{+ ID: types.BuiltinWeKnoraAssistantID, IsBuiltin: true,Config: types.CustomAgentConfig{AgentMode: types.AgentModeSmartReasoning, AllowedTools: []string{"x"}},}},broker: hitl.NewBroker(nil, nil),@@ -165,9 +177,6 @@ func (f *automationFixture) create(t *testing.T, p types.AutomationPatch) *typesif p.Instruction == nil {p.Instruction = ptr("summarize {{automation_name}} at {{now}}")}- if p.AgentID == nil {- p.AgentID = ptr("a")- }if p.Trigger == nil {p.Trigger = &types.AutomationTrigger{Type: types.AutomationTriggerCron, Expr: "0 9 * * *"}}@@ -214,16 +223,12 @@ func TestAutomationCreateValidatesAndSchedules(t *testing.T) {for name, p := range map[string]types.AutomationPatch{"too frequent": {Trigger: &types.AutomationTrigger{Type: types.AutomationTriggerCron, Expr: "* * * * *"}},- "bad agent": {AgentID: ptr("builtin-wiki-fixer")},"bad mode": {SessionMode: ptr("forever")},"once in past": {Trigger: &types.AutomationTrigger{Type: types.AutomationTriggerOnce, At: f.now.Add(-time.Hour).Format(time.RFC3339),}},} {p.Name, p.Instruction = ptr("n"), ptr("i")- if p.AgentID == nil {- p.AgentID = ptr("a")- }if p.Trigger == nil {p.Trigger = &types.AutomationTrigger{Type: types.AutomationTriggerCron, Expr: "0 9 * * *"}}@@ -292,6 +297,7 @@ func TestAutomationRunSucceedsAsOwnerUnattended(t *testing.T) {require.Equal(t, types.AutomationRunSucceeded, done.Status)require.Equal(t, "done", done.Answer)call := f.sessions.last()+ require.Equal(t, types.BuiltinWeKnoraAssistantID, call.req.CustomAgent.ID)require.Equal(t, types.RunModeDeferred, call.mode)require.Equal(t, types.AutomationActingVia(a.ID), call.via)require.Equal(t, types.GrantScope{@@ -306,6 +312,7 @@ func TestAutomationRunSucceedsAsOwnerUnattended(t *testing.T) {var session types.Sessionrequire.NoError(t, f.db.Where("id = ?", done.SessionID).First(&session).Error)require.Equal(t, types.SessionKindAutomation, session.Kind)+ require.Equal(t, types.BuiltinWeKnoraAssistantID, session.LastRequestState.AgentID)require.Equal(t, "u", session.UserID)stored := f.reload(t, a.ID)require.Equal(t, types.AutomationRunSucceeded, stored.LastRunStatus)@@ -326,6 +333,19 @@ func TestAutomationPersistentSessionCarriesAcrossRuns(t *testing.T) {require.Equal(t, r1.SessionID, f.reload(t, a.ID).PersistentSessionID)}+func TestAutomationPausesWhenAssistantUnavailable(t *testing.T) {+ f := newAutomationFixture(t)+ a := f.create(t, types.AutomationPatch{})+ f.agents.agent = nil+ queued, err := f.svc.RunNow(f.ctx, a.ID)+ require.NoError(t, err)+ run := f.settleRun(t, queued.ID)+ require.Equal(t, types.AutomationRunFailed, run.Status)+ require.Contains(t, run.Error, "WeKnora assistant is unavailable")+ require.False(t, f.reload(t, a.ID).Enabled)+ require.Empty(t, f.sessions.calls)+}+func TestAutomationCarriesLastResult(t *testing.T) {f := newAutomationFixture(t)a := f.create(t, types.AutomationPatch{CarryLastResult: ptr(true)})diff --git a/internal/database/migration_sqlite_automation_assistant_test.go b/internal/database/migration_sqlite_automation_assistant_test.gonew file mode 100644index 000000000..a163c92e9--- /dev/null+++ b/internal/database/migration_sqlite_automation_assistant_test.go@@ -0,0 +1,38 @@+package database++import (+ "path/filepath"+ "testing"++ "github.com/stretchr/testify/require"+)++func TestSQLiteAutomationAssistantRemovesExecutorSelection(t *testing.T) {+ repoRoot := sqliteRepoRoot(t)+ chdirAndRestore(t, copySQLiteMigrationsThrough(t, repoRoot, 49))+ dbPath := filepath.Join(t.TempDir(), "automations.db")+ opts := MigrationOptions{SQLiteDBPath: dbPath}+ require.NoError(t, RunMigrationsWithOptions("sqlite3://unused", opts))+ db := openSQLiteDB(t, dbPath)+ _, err := db.Exec(`INSERT INTO automations+ (id, tenant_id, owner_user_id, name, agent_id, model_id, instruction, trigger_config, created_at, updated_at)+ VALUES ('task', 1, 'owner', 'Digest', 'custom-agent', 'chosen-model', 'Summarize the news', '{}',+ CURRENT_TIMESTAMP, CURRENT_TIMESTAMP)`)+ require.NoError(t, err)++ chdirAndRestore(t, repoRoot)+ require.NoError(t, RunMigrationsWithOptions("sqlite3://unused", opts))+ var count int+ require.NoError(t, db.QueryRow(`SELECT COUNT(*) FROM pragma_table_info('automations')+ WHERE name = 'agent_id'`).Scan(&count))+ require.Zero(t, count)+ var model, instruction string+ require.NoError(t, db.QueryRow(`SELECT model_id, instruction FROM automations+ WHERE id = 'task'`).Scan(&model, &instruction))+ require.Equal(t, "chosen-model", model)+ require.Equal(t, "Summarize the news", instruction)+ _, err = db.Exec(`INSERT INTO automations+ (id, tenant_id, owner_user_id, name, instruction, trigger_config, created_at, updated_at)+ VALUES ('new-task', 1, 'owner', 'Reminder', 'Take a break', '{}', CURRENT_TIMESTAMP, CURRENT_TIMESTAMP)`)+ require.NoError(t, err, "new automations must not need an executor field")+}diff --git a/internal/database/migration_sqlite_automation_model_test.go b/internal/database/migration_sqlite_automation_model_test.goindex 62e4444f5..e688099bc 100644--- a/internal/database/migration_sqlite_automation_model_test.go+++ b/internal/database/migration_sqlite_automation_model_test.go@@ -23,7 +23,7 @@ func TestSQLiteAutomationModelUpgradePreservesDefault(t *testing.T) {require.NoError(t, RunMigrationsWithOptions("sqlite3://unused", opts))var model, name stringrequire.NoError(t, db.QueryRow("SELECT model_id, name FROM automations WHERE id = 'task'").Scan(&model, &name))- require.Empty(t, model, "existing automations must continue using the agent default")+ require.Empty(t, model, "automations must use the assistant default")require.Equal(t, "Reminder", name)_, err = db.Exec("UPDATE automations SET model_id = 'chosen-model' WHERE id = 'task'")require.NoError(t, err)diff --git a/internal/database/migration_sqlite_versioned_schema_test.go b/internal/database/migration_sqlite_versioned_schema_test.goindex 1f0ef4730..d64fe4250 100644--- a/internal/database/migration_sqlite_versioned_schema_test.go+++ b/internal/database/migration_sqlite_versioned_schema_test.go@@ -88,7 +88,7 @@ var versionedSQLiteColumns = map[string][]string{}, // 000028}-const expectedSQLiteMigrationVersion = 49+const expectedSQLiteMigrationVersion = 50func TestSQLiteMigrationsCreateVersionedSchema(t *testing.T) {repoRoot := sqliteRepoRoot(t)diff --git a/internal/handler/automation.go b/internal/handler/automation.goindex acb0d5b04..dae2b728a 100644--- a/internal/handler/automation.go+++ b/internal/handler/automation.go@@ -44,8 +44,8 @@ type CreateAutomationRequest struct {Name string `json:"name" binding:"required" extensions:"x-agent"`// What it is forDescription string `json:"description" extensions:"x-agent"`- // Agent that runs it, from agent.list; empty runs the WeKnora assistant- AgentID string `json:"agent_id" extensions:"x-agent"`+ // Optional chat model from model.list; empty follows the assistant default+ ModelID string `json:"model_id" extensions:"x-agent"`// The task, sent as the user message of each run. May name now,// last_run_at, last_success_at, run_id or automation_name inside double// curly braces to have it filled in@@ -71,7 +71,7 @@ type CreateAutomationRequest struct {func (r CreateAutomationRequest) patch() *types.AutomationPatch {return &types.AutomationPatch{- Name: &r.Name, Description: &r.Description, AgentID: &r.AgentID, Instruction: &r.Instruction,+ Name: &r.Name, Description: &r.Description, ModelID: &r.ModelID, Instruction: &r.Instruction,Trigger: &r.Trigger, SessionMode: &r.SessionMode, CarryLastResult: &r.CarryLastResult,MisfirePolicy: &r.MisfirePolicy, OverlapPolicy: &r.OverlapPolicy, AccessLevel: &r.AccessLevel,ApprovalTimeoutMinutes: &r.ApprovalTimeoutMinutes, Limits: &r.Limits, NotifyOnSuccess: &r.NotifyOnSuccess,@@ -86,7 +86,7 @@ func (r CreateAutomationRequest) patch() *types.AutomationPatch {// @Success 200 {object} handler.DataResponse{data=[]types.Automation} "自动化列表"// @Security Bearer// @x-agent {"id":"automation.list","risk":"read","max_items":100}-// @x-agent-hint "Lists the user's automations: scheduled tasks an agent runs on their behalf, with next and last run."+// @x-agent-hint "Lists the user's automations: scheduled tasks the WeKnora assistant runs on their behalf, with next and last run."// @Router /automations [get]func (h *AutomationHandler) ListAutomations(c *gin.Context) {list, err := h.automations.List(c.Request.Context())@@ -99,7 +99,7 @@ func (h *AutomationHandler) ListAutomations(c *gin.Context) {// CreateAutomation godoc// @Summary 创建自动化-// @Description 创建一个按计划由 Agent 以当前用户身份运行的任务+// @Description 创建一个按计划由 WeKnora 助手以当前用户身份运行的任务// @Tags 自动化// @Accept json// @Produce json@@ -108,7 +108,7 @@ func (h *AutomationHandler) ListAutomations(c *gin.Context) {// @Failure 400 {object} errors.AppError "参数不合法"// @Security Bearer// @x-agent {"id":"automation.create","role":"viewer","risk":"write","label_param":"name","always_confirm":true}-// @x-agent-hint "Creates an automation the user runs as. Turn the user's wording into a cron expression (five fields, minute first) and an IANA timezone, and check it with automation.validate_trigger first, telling the user the next run times it returns. Runs are unattended: write the instruction as a complete task, since nobody can answer questions during a run. access_level defaults to confirm, where each change waits for the user's approval; only set auto_write when the user asks for it."+// @x-agent-hint "Creates an automation the WeKnora assistant runs as the user. If work requires other agents, name them and their assignments in the instruction so the assistant can delegate. Turn the user's wording into a cron expression (five fields, minute first) and an IANA timezone, and check it with automation.validate_trigger first, telling the user the next run times it returns. Runs are unattended: write the instruction as a complete task, since nobody can answer questions during a run. access_level defaults to confirm, where each change waits for the user's approval; only set auto_write when the user asks for it."// @Router /automations [post]func (h *AutomationHandler) CreateAutomation(c *gin.Context) {var req CreateAutomationRequestdiff --git a/internal/handler/automation_test.go b/internal/handler/automation_test.gonew file mode 100644index 000000000..ddf1756a8--- /dev/null+++ b/internal/handler/automation_test.go@@ -0,0 +1,19 @@+package handler++import (+ "encoding/json"+ "testing"++ "github.com/stretchr/testify/require"+)++func TestCreateAutomationPreservesModelOverride(t *testing.T) {+ var req CreateAutomationRequest+ require.NoError(t, json.Unmarshal([]byte(`{+ "name": "Digest", "instruction": "Summarize the news",+ "model_id": "selected-model",+ "trigger": {"type": "cron", "expr": "0 9 * * *"}+ }`), &req))+ require.NotNil(t, req.patch().ModelID)+ require.Equal(t, "selected-model", *req.patch().ModelID)+}diff --git a/internal/types/automation.go b/internal/types/automation.goindex c2f44b708..98a410506 100644--- a/internal/types/automation.go+++ b/internal/types/automation.go@@ -90,7 +90,7 @@ type AutomationLimits struct {MaxDurationMinutes int `json:"max_duration_minutes,omitempty" extensions:"x-agent"`}-// Automation is a task an agent runs on a schedule on its owner's behalf.+// Automation is a task the WeKnora assistant runs on a schedule on its owner's behalf.type Automation struct {ID string `json:"id" gorm:"type:varchar(36);primaryKey" extensions:"x-agent=automation_id,x-agent-response"`TenantID uint64 `json:"tenant_id" gorm:"not null;index:idx_automations_owner"`@@ -99,10 +99,7 @@ type Automation struct {Name string `json:"name" gorm:"type:varchar(255);not null" extensions:"x-agent"`Description string `json:"description" gorm:"type:text" extensions:"x-agent"`Enabled bool `json:"enabled" gorm:"not null;default:true;index:idx_automations_due" extensions:"x-agent,x-agent-response"`- // AgentID is the agent that runs it; the WeKnora assistant's ID runs the- // assistant.- AgentID string `json:"agent_id" gorm:"type:varchar(64);not null" extensions:"x-agent"`- // ModelID overrides the agent's chat model; empty follows the agent default.+ // ModelID overrides the assistant's chat model; empty follows the assistant default.ModelID string `json:"model_id" gorm:"type:varchar(64);not null;default:''" extensions:"x-agent"`// Instruction is the task, sent as the user message of each run after// its variables are filled in.@@ -118,7 +115,7 @@ type Automation struct {MisfirePolicy string `json:"misfire_policy" gorm:"type:varchar(16);not null;default:'skip'" extensions:"x-agent"`OverlapPolicy string `json:"overlap_policy" gorm:"type:varchar(16);not null;default:'skip'" extensions:"x-agent"`// AccessLevel is how far runs may change data without asking, capped by- // the agent's and the workspace's ceilings.+ // the workspace's assistant ceiling.AccessLevel AssistantAccessLevel `json:"access_level" gorm:"type:varchar(16);not null;default:'confirm'" extensions:"x-agent"`// ApprovalTimeoutMinutes is how long a run waits for an approval before// it fails.@@ -200,9 +197,7 @@ type AutomationPatch struct {Name *string `json:"name" extensions:"x-agent"`// What it is forDescription *string `json:"description" extensions:"x-agent"`- // Agent that runs it, from agent.list; empty runs the WeKnora assistant- AgentID *string `json:"agent_id" extensions:"x-agent"`- // Optional chat model from model.list; empty follows the agent default+ // Optional chat model from model.list; empty follows the assistant defaultModelID *string `json:"model_id" extensions:"x-agent"`// The task, sent as the user message of each run. May name now,// last_run_at, last_success_at, run_id or automation_name inside doublediff --git a/migrations/sqlite/000050_automation_assistant.down.sql b/migrations/sqlite/000050_automation_assistant.down.sqlnew file mode 100644index 000000000..9912cd90e--- /dev/null+++ b/migrations/sqlite/000050_automation_assistant.down.sql@@ -0,0 +1 @@+ALTER TABLE automations ADD COLUMN agent_id VARCHAR(64) NOT NULL DEFAULT 'builtin-weknora-assistant';diff --git a/migrations/sqlite/000050_automation_assistant.up.sql b/migrations/sqlite/000050_automation_assistant.up.sqlnew file mode 100644index 000000000..37c05bdea--- /dev/null+++ b/migrations/sqlite/000050_automation_assistant.up.sql@@ -0,0 +1 @@+ALTER TABLE automations DROP COLUMN agent_id;diff --git a/migrations/versioned/000133_automation_assistant.down.sql b/migrations/versioned/000133_automation_assistant.down.sqlnew file mode 100644index 000000000..9912cd90e--- /dev/null+++ b/migrations/versioned/000133_automation_assistant.down.sql@@ -0,0 +1 @@+ALTER TABLE automations ADD COLUMN agent_id VARCHAR(64) NOT NULL DEFAULT 'builtin-weknora-assistant';diff --git a/migrations/versioned/000133_automation_assistant.up.sql b/migrations/versioned/000133_automation_assistant.up.sqlnew file mode 100644index 000000000..37c05bdea--- /dev/null+++ b/migrations/versioned/000133_automation_assistant.up.sql@@ -0,0 +1 @@+ALTER TABLE automations DROP COLUMN agent_id;