Skip to content

Open-source LLM knowledge platform: turn raw documents into a queryable RAG, an autonomous reasoning agent, and a self-maintaining Wiki.

feat(automation): improve model settings, task controls, and notification inbox (#4514)

lyingbug968ca9fb1b7d
diff --git a/docs/docs.go b/docs/docs.go
index 931cf1991..96116fffa 100644
--- a/docs/docs.go
+++ b/docs/docs.go
@@ -276,7 +276,7 @@ const docTemplate = `{
"ApiKeyAuth": []
}
],
- "description": "回答 Agent 运行中发起的交互(ask_user 提问、工具审批,或由浏览器自动应答的页面读写)。\nkind 须与交互一致,response 为该类型的回答 JSON(不接受未知字段):\nask_user 为 {selected?, values?, text?, declined?};\ntool_approval 为 {approved: bool, modified_args?: object, reason?: string, allow_in_session?: bool};\npage_action 为 {declined?, error?, location?, snapshot?, applied?: [{ref, label?, summary?}],\nstayed?, return_path?}。\n返回 resumed=true 表示运行已挂起并在本次回答后恢复,客户端需重新接入该消息的事件流",
+ "description": "回答 Agent 运行中发起的交互(ask_user 提问、工具审批,或由浏览器自动应答的页面读写)。\nkind 须与交互一致,response 为该类型的回答 JSON(不接受未知字段):\nask_user 为 {selected?, values?, text?, declined?};\ntool_approval 为 {approved: bool, modified_args?: object, reason?: string, allow_in_session?: bool};\npage_action 为 {declined?, error?, location?, snapshot?, applied?: [{ref, label?, summary?}],\nstayed?, return_path?}。\n返回 resumed=true 表示挂起的运行已请求恢复(自动化由调度器恢复),客户端需携带 resume_pending_id 重新接入该消息的事件流",
"consumes": [
"application/json"
],
@@ -15137,6 +15137,12 @@ const docTemplate = `{
"name": "limit",
"in": "query"
},
+ {
+ "type": "string",
+ "description": "上一页返回的 next_cursor",
+ "name": "cursor",
+ "in": "query"
+ },
{
"type": "boolean",
"description": "只看未读",
@@ -15146,7 +15152,7 @@ const docTemplate = `{
],
"responses": {
"200": {
- "description": "{items, unread}",
+ "description": "{items, pending, unread, read_count, next_cursor}",
"schema": {
"type": "object",
"additionalProperties": true
@@ -15162,7 +15168,7 @@ const docTemplate = `{
"Bearer": []
}
],
- "description": "ids 为空时全部标记已读",
+ "description": "ids 为空时将全部通知记录标为已读,不改变待处理事项",
"consumes": [
"application/json"
],
@@ -15192,6 +15198,29 @@ const docTemplate = `{
}
}
}
+ },
+ "delete": {
+ "security": [
+ {
+ "Bearer": []
+ }
+ ],
+ "produces": [
+ "application/json"
+ ],
+ "tags": [
+ "通知"
+ ],
+ "summary": "清理已读通知",
+ "responses": {
+ "200": {
+ "description": "OK",
+ "schema": {
+ "type": "object",
+ "additionalProperties": true
+ }
+ }
+ }
}
},
"/organizations": {
@@ -17746,6 +17775,12 @@ const docTemplate = `{
"in": "query",
"required": true
},
+ {
+ "type": "string",
+ "description": "等待此审批恢复后的事件流",
+ "name": "resume_pending_id",
+ "in": "query"
+ },
{
"enum": [
"handle",
@@ -17770,6 +17805,12 @@ const docTemplate = `{
"schema": {
"$ref": "#/definitions/github_com_Tencent_WeKnora_internal_errors.AppError"
}
+ },
+ "409": {
+ "description": "审批恢复后的事件流尚未就绪",
+ "schema": {
+ "$ref": "#/definitions/github_com_Tencent_WeKnora_internal_errors.AppError"
+ }
}
}
}
@@ -26289,6 +26330,11 @@ const docTemplate = `{
"type": "string",
"x-agent": true
},
+ "model_id": {
+ "description": "ModelID overrides the agent's chat model; empty follows the agent default.",
+ "type": "string",
+ "x-agent": true
+ },
"name": {
"type": "string",
"x-agent": true
@@ -26408,6 +26454,11 @@ const docTemplate = `{
],
"x-agent": true
},
+ "model_id": {
+ "description": "Optional chat model from model.list; empty follows the agent default",
+ "type": "string",
+ "x-agent": true
+ },
"name": {
"description": "What the automation is called",
"type": "string",
diff --git a/docs/swagger.json b/docs/swagger.json
index ae103ed0c..f2a7f456a 100644
--- a/docs/swagger.json
+++ b/docs/swagger.json
@@ -269,7 +269,7 @@
"ApiKeyAuth": []
}
],
- "description": "回答 Agent 运行中发起的交互(ask_user 提问、工具审批,或由浏览器自动应答的页面读写)。\nkind 须与交互一致,response 为该类型的回答 JSON(不接受未知字段):\nask_user 为 {selected?, values?, text?, declined?};\ntool_approval 为 {approved: bool, modified_args?: object, reason?: string, allow_in_session?: bool};\npage_action 为 {declined?, error?, location?, snapshot?, applied?: [{ref, label?, summary?}],\nstayed?, return_path?}。\n返回 resumed=true 表示运行已挂起并在本次回答后恢复,客户端需重新接入该消息的事件流",
+ "description": "回答 Agent 运行中发起的交互(ask_user 提问、工具审批,或由浏览器自动应答的页面读写)。\nkind 须与交互一致,response 为该类型的回答 JSON(不接受未知字段):\nask_user 为 {selected?, values?, text?, declined?};\ntool_approval 为 {approved: bool, modified_args?: object, reason?: string, allow_in_session?: bool};\npage_action 为 {declined?, error?, location?, snapshot?, applied?: [{ref, label?, summary?}],\nstayed?, return_path?}。\n返回 resumed=true 表示挂起的运行已请求恢复(自动化由调度器恢复),客户端需携带 resume_pending_id 重新接入该消息的事件流",
"consumes": [
"application/json"
],
@@ -15130,6 +15130,12 @@
"name": "limit",
"in": "query"
},
+ {
+ "type": "string",
+ "description": "上一页返回的 next_cursor",
+ "name": "cursor",
+ "in": "query"
+ },
{
"type": "boolean",
"description": "只看未读",
@@ -15139,7 +15145,7 @@
],
"responses": {
"200": {
- "description": "{items, unread}",
+ "description": "{items, pending, unread, read_count, next_cursor}",
"schema": {
"type": "object",
"additionalProperties": true
@@ -15155,7 +15161,7 @@
"Bearer": []
}
],
- "description": "ids 为空时全部标记已读",
+ "description": "ids 为空时将全部通知记录标为已读,不改变待处理事项",
"consumes": [
"application/json"
],
@@ -15185,6 +15191,29 @@
}
}
}
+ },
+ "delete": {
+ "security": [
+ {
+ "Bearer": []
+ }
+ ],
+ "produces": [
+ "application/json"
+ ],
+ "tags": [
+ "通知"
+ ],
+ "summary": "清理已读通知",
+ "responses": {
+ "200": {
+ "description": "OK",
+ "schema": {
+ "type": "object",
+ "additionalProperties": true
+ }
+ }
+ }
}
},
"/organizations": {
@@ -17739,6 +17768,12 @@
"in": "query",
"required": true
},
+ {
+ "type": "string",
+ "description": "等待此审批恢复后的事件流",
+ "name": "resume_pending_id",
+ "in": "query"
+ },
{
"enum": [
"handle",
@@ -17763,6 +17798,12 @@
"schema": {
"$ref": "#/definitions/github_com_Tencent_WeKnora_internal_errors.AppError"
}
+ },
+ "409": {
+ "description": "审批恢复后的事件流尚未就绪",
+ "schema": {
+ "$ref": "#/definitions/github_com_Tencent_WeKnora_internal_errors.AppError"
+ }
}
}
}
@@ -26282,6 +26323,11 @@
"type": "string",
"x-agent": true
},
+ "model_id": {
+ "description": "ModelID overrides the agent's chat model; empty follows the agent default.",
+ "type": "string",
+ "x-agent": true
+ },
"name": {
"type": "string",
"x-agent": true
@@ -26401,6 +26447,11 @@
],
"x-agent": true
},
+ "model_id": {
+ "description": "Optional chat model from model.list; empty follows the agent default",
+ "type": "string",
+ "x-agent": true
+ },
"name": {
"description": "What the automation is called",
"type": "string",
diff --git a/docs/swagger.yaml b/docs/swagger.yaml
index e2c2b0a41..41cd2706c 100644
--- a/docs/swagger.yaml
+++ b/docs/swagger.yaml
@@ -1816,6 +1816,11 @@ definitions:
misfire_policy:
type: string
x-agent: true
+ model_id:
+ description: ModelID overrides the agent's chat model; empty follows the agent
+ default.
+ type: string
+ x-agent: true
name:
type: string
x-agent: true
@@ -1909,6 +1914,11 @@ definitions:
- run_once
type: string
x-agent: true
+ model_id:
+ description: Optional chat model from model.list; empty follows the agent
+ default
+ type: string
+ x-agent: true
name:
description: What the automation is called
type: string
@@ -14488,7 +14498,7 @@ paths:
tool_approval 为 {approved: bool, modified_args?: object, reason?: string, allow_in_session?: bool};
page_action 为 {declined?, error?, location?, snapshot?, applied?: [{ref, label?, summary?}],
stayed?, return_path?}。
- 返回 resumed=true 表示运行已挂起并在本次回答后恢复,客户端需重新接入该消息的事件流
+ 返回 resumed=true 表示挂起的运行已请求恢复(自动化由调度器恢复),客户端需携带 resume_pending_id 重新接入该消息的事件流
parameters:
- description: 交互 ID(事件中的 pending_id)
in: path
@@ -24091,6 +24101,10 @@ paths:
in: query
name: limit
type: integer
+ - description: 上一页返回的 next_cursor
+ in: query
+ name: cursor
+ type: string
- description: 只看未读
in: query
name: unread
@@ -24099,7 +24113,7 @@ paths:
- application/json
responses:
"200":
- description: '{items, unread}'
+ description: '{items, pending, unread, read_count, next_cursor}'
schema:
additionalProperties: true
type: object
@@ -24109,10 +24123,24 @@ paths:
tags:
- 通知
/notifications/read:
+ delete:
+ produces:
+ - application/json
+ responses:
+ "200":
+ description: OK
+ schema:
+ additionalProperties: true
+ type: object
+ security:
+ - Bearer: []
+ summary: 清理已读通知
+ tags:
+ - 通知
post:
consumes:
- application/json
- description: ids 为空时全部标记已读
+ description: ids 为空时将全部通知记录标为已读,不改变待处理事项
parameters:
- description: '{ids}'
in: body
@@ -26420,6 +26448,10 @@ paths:
name: message_id
required: true
type: string
+ - description: 等待此审批恢复后的事件流
+ in: query
+ name: resume_pending_id
+ type: string
- default: handle
description: 文件引用形式,public 返回可加载直链
enum:
@@ -26439,6 +26471,10 @@ paths:
description: 会话或消息不存在
schema:
$ref: '#/definitions/github_com_Tencent_WeKnora_internal_errors.AppError'
+ "409":
+ description: 审批恢复后的事件流尚未就绪
+ schema:
+ $ref: '#/definitions/github_com_Tencent_WeKnora_internal_errors.AppError'
security:
- Bearer: []
- ApiKeyAuth: []
diff --git a/docs/swagger_contract_test.go b/docs/swagger_contract_test.go
index fcf5816aa..40c708079 100644
--- a/docs/swagger_contract_test.go
+++ b/docs/swagger_contract_test.go
@@ -330,3 +330,25 @@ func swaggerInteger(value any) int {
return 0
}
}
+
+func TestNotificationInboxContract(t *testing.T) {
+ for _, tt := range swaggerDocuments() {
+ t.Run(tt.name, func(t *testing.T) {
+ var spec struct {
+ Paths map[string]map[string]swaggerOperation `json:"paths" yaml:"paths"`
+ }
+ if err := tt.parse(tt.loadSpec(t), &spec); err != nil {
+ t.Fatal(err)
+ }
+ if _, ok := spec.Paths["/notifications/read"]["delete"]; !ok {
+ t.Fatal("missing clear-read notification endpoint")
+ }
+ for _, parameter := range spec.Paths["/notifications"]["get"].Parameters {
+ if parameter.Name == "cursor" && parameter.In == "query" && parameter.Type == "string" {
+ return
+ }
+ }
+ t.Fatal("notification listing must document its history cursor")
+ })
+ }
+}
diff --git a/frontend/src/api/automation.ts b/frontend/src/api/automation.ts
index ebef9259f..879a785d4 100644
--- a/frontend/src/api/automation.ts
+++ b/frontend/src/api/automation.ts
@@ -40,6 +40,7 @@ export interface Automation {
description: string
enabled: boolean
agent_id: string
+ model_id: string
instruction: string
trigger: AutomationTrigger
session_mode: AutomationSessionMode
@@ -66,6 +67,7 @@ export type AutomationInput = Partial<Pick<Automation,
| 'name'
| 'description'
| 'agent_id'
+ | 'model_id'
| 'instruction'
| 'trigger'
| 'session_mode'
@@ -213,13 +215,34 @@ export interface AppNotification {
created_at: string
}
-export function listNotifications(limit = 20) {
- return get<{ success: boolean; data: { items: AppNotification[]; unread: number } }>(
- `/api/v1/notifications?limit=${limit}`,
+export interface PendingNotification {
+ id: string
+ title: string
+ kind: string
+ link: string
+ created_at: string
+}
+
+export interface NotificationPage {
+ items: AppNotification[]
+ pending: PendingNotification[]
+ unread: number
+ read_count: number
+ next_cursor: string
+}
+
+export function listNotifications(limit = 20, cursor = '') {
+ return get<{ success: boolean; data: NotificationPage }>(
+ `/api/v1/notifications?limit=${limit}${cursor ? `&cursor=${enc(cursor)}` : ''}`,
)
}
-/** Mark ids read; no ids marks all of them. */
+/** Removes read history only; live approvals and run records are unaffected. */
+export function clearReadNotifications() {
+ return del<{ success: boolean }>('/api/v1/notifications/read')
+}
+
+/** Mark history ids read; no ids marks all history. Pending work is separate. */
export function markNotificationsRead(ids: string[] = []) {
return post<{ success: boolean }>('/api/v1/notifications/read', { ids })
}
diff --git a/frontend/src/api/chat/streame.test.ts b/frontend/src/api/chat/streame.test.ts
index beb130b0d..4c99da5e7 100644
--- a/frontend/src/api/chat/streame.test.ts
+++ b/frontend/src/api/chat/streame.test.ts
@@ -40,6 +40,23 @@ after(async () => {
else Reflect.deleteProperty(globalThis, 'localStorage')
})
+test('approval reattach identifies the resumed segment without changing ordinary replay', async () => {
+ let stream!: ReturnType<typeof useStream>
+ await renderToString(createSSRApp({ setup() { stream = useStream(); return () => null } }))
+ try {
+ for (const pendingId of [undefined, 'pending/a+b']) {
+ await stream.startStream({
+ session_id: 'session', query: 'message', method: 'GET',
+ url: '/api/v1/sessions/continue-stream', resume_pending_id: pendingId,
+ })
+ assert.equal(stream.error.value, null)
+ const request = transport.requests.at(-1)!
+ assert.equal(request.url, '/api/v1/sessions/continue-stream/session?message_id=message' +
+ (pendingId ? '&resume_pending_id=pending%2Fa%2Bb' : ''))
+ }
+ } finally { stream.stopStream() }
+})
+
for (const effort of [undefined, '', 'off', 'auto', 'high', 'max']) {
test(`SSE body carries only explicit reasoning overrides: ${effort}`, async () => {
let stream!: ReturnType<typeof useStream>
diff --git a/frontend/src/api/chat/streame.ts b/frontend/src/api/chat/streame.ts
index 8d1836f93..e1c4f55c5 100644
--- a/frontend/src/api/chat/streame.ts
+++ b/frontend/src/api/chat/streame.ts
@@ -71,7 +71,7 @@ export function useStream() {
let renderTimer: number | null = null
// 启动流式请求
- const startStream = async (params: { session_id: any; query: any; knowledge_base_ids?: string[]; knowledge_ids?: string[]; tag_ids?: string[]; agent_enabled?: boolean; agent_id?: string; agent_source_tenant_id?: string | number; web_search_enabled?: boolean; local_browser_enabled?: boolean; summary_model_id?: string; reasoning_effort?: string; mcp_service_ids?: string[]; skill_names?: string[]; mentioned_items?: Array<{id: string; name: string; type: string; kb_type?: string; kb_id?: string; kb_name?: string; service_id?: string; skill_name?: string}>; images?: Array<{data: string}>; attachment_uploads?: Array<{data: string; file_name: string; file_size: number}>; attachment_ids?: string[]; suggestion_attribution?: { suggestion_set_id: string; question_id: string }; question_origin?: { knowledge_base_id: string; knowledge_id?: string }; page_context?: PageContextPayload; assistant_access?: AssistantAccessLevel; method: string; url: string; embed_token?: string; embed_session_sig?: string; embed_visitor_id?: string }) => {
+ const startStream = async (params: { session_id: any; query: any; knowledge_base_ids?: string[]; knowledge_ids?: string[]; tag_ids?: string[]; agent_enabled?: boolean; agent_id?: string; agent_source_tenant_id?: string | number; web_search_enabled?: boolean; local_browser_enabled?: boolean; summary_model_id?: string; reasoning_effort?: string; mcp_service_ids?: string[]; skill_names?: string[]; mentioned_items?: Array<{id: string; name: string; type: string; kb_type?: string; kb_id?: string; kb_name?: string; service_id?: string; skill_name?: string}>; images?: Array<{data: string}>; attachment_uploads?: Array<{data: string; file_name: string; file_size: number}>; attachment_ids?: string[]; suggestion_attribution?: { suggestion_set_id: string; question_id: string }; question_origin?: { knowledge_base_id: string; knowledge_id?: string }; page_context?: PageContextPayload; assistant_access?: AssistantAccessLevel; method: string; url: string; resume_pending_id?: string; embed_token?: string; embed_session_sig?: string; embed_visitor_id?: string }) => {
const myGeneration = ++streamGeneration
const streamAbort = controller
// 重置状态
@@ -124,6 +124,9 @@ export function useStream() {
params.method == "POST"
? `${apiUrl}${params.url}/${params.session_id}`
: `${apiUrl}${params.url}/${params.session_id}?message_id=${params.query}`;
+ if (params.method === "GET" && params.resume_pending_id) {
+ url += `&resume_pending_id=${encodeURIComponent(params.resume_pending_id)}`;
+ }
console.log(`[TTFB] request:start request_id=${requestID} url=${url} sent_at=${Date.now()}`);
// Prepare POST body with required fields for agent-chat
diff --git a/frontend/src/components/ChatActionIcon.vue b/frontend/src/components/ChatActionIcon.vue
index f51df68c9..e726fe08b 100644
--- a/frontend/src/components/ChatActionIcon.vue
+++ b/frontend/src/components/ChatActionIcon.vue
@@ -30,11 +30,29 @@
<circle cx="12" cy="12" r="9" />
<path d="M12 11v6m0-10v.01" />
</template>
+ <template v-else-if="name === 'play'">
+ <circle cx="12" cy="12" r="9" />
+ <path d="m10 8 6 4-6 4V8Z" />
+ </template>
+ <template v-else-if="name === 'resume'">
+ <path d="M3 10a9 9 0 1 1 2 8M3 4v6h6" />
+ <path d="M12 7v5l3 2" />
+ </template>
+ <template v-else-if="name === 'pause'">
+ <circle cx="12" cy="12" r="9" />
+ <path d="M9 8v8m6-8v8" />
+ </template>
+ <template v-else-if="name === 'edit'">
+ <path d="m15 4 5 5M4 20l5-1L20 8a2.1 2.1 0 0 0-5-5L4 14l-1 7Z" />
+ </template>
+ <template v-else-if="name === 'delete'">
+ <path d="M3 6h18M9 6V3h6v3M5 6l1 14a1 1 0 0 0 1 1h10a1 1 0 0 0 1-1l1-14M10 10v7m4-7v7" />
+ </template>
</svg>
</template>
<script setup lang="ts">
defineProps<{
- name: 'copy' | 'git-branch' | 'rollback' | 'bookmark-add' | 'compass' | 'folder' | 'info-circle'
+ name: 'copy' | 'git-branch' | 'rollback' | 'bookmark-add' | 'compass' | 'folder' | 'info-circle' | 'play' | 'resume' | 'pause' | 'edit' | 'delete'
}>()
</script>
diff --git a/frontend/src/components/GlobalInvitationBell.test.ts b/frontend/src/components/GlobalInvitationBell.test.ts
new file mode 100644
index 000000000..def61d41e
--- /dev/null
+++ b/frontend/src/components/GlobalInvitationBell.test.ts
@@ -0,0 +1,227 @@
+import assert from 'node:assert/strict'
+import test, { type TestContext } from 'node:test'
+import * as vue from 'vue'
+import { fixture, flush } from '../test-utils/vueFixture.ts'
+import { notificationPreview } from '../utils/notificationPreview.ts'
+
+const notice = (id: string, read = false) => ({ id, kind: 'automation.succeeded', title: id, body: 'done',
+ link: `/platform/automations/${id}`, read_at: read ? '2026-10-20T00:00:00Z' : null, created_at: '2026-10-20T00:00:00Z' })
+const approval = { id: 'prompt', title: 'Approval', kind: 'tool_approval', link: '/platform/chat/session', created_at: '2026-10-20T00:00:00Z' }
+const page = (items: ReturnType<typeof notice>[] = [], extra = {}) => ({ data: { items, pending: [approval],
+ unread: items.filter(item => !item.read_at).length, read_count: items.filter(item => item.read_at).length, next_cursor: '', ...extra } })
+function deferred<T>() {
+ let resolve!: (value: T) => void
+ const promise = new Promise<T>(r => { resolve = r })
+ return { promise, resolve }
+}
+function setup(t: TestContext, api: Record<string, unknown>) {
+ const f = fixture(t)
+ const auth = vue.reactive({ user: { id: 'owner' }, effectiveTenantId: 1, pendingInvitationCount: 1 })
+ const routes: string[] = []
+ const errors: string[] = []
+ const component = f.component(new URL('./GlobalInvitationBell.vue', import.meta.url), {
+ vue: { ...vue, onMounted() {}, onBeforeUnmount() {} },
+ 'vue-router': { useRouter: () => ({ push: (path: string) => { routes.push(path) } }) },
+ 'vue-i18n': { useI18n: () => ({ t: (key: string) => key, te: () => true, locale: vue.ref('en-US') }) },
+ 'tdesign-vue-next': { MessagePlugin: { error: (message: string) => { errors.push(message) } } },
+ '@/stores/auth': { useAuthStore: () => auth }, '@/api/automation': api,
+ '@/utils/notificationPreview': { notificationPreview },
+ })
+ return { ...component, auth, routes, errors }
+}
+
+test('marking and clearing history never removes pending actions or their badge', async t => {
+ let history = [notice('one'), notice('two')]
+ const marked: string[][] = []
+ let cleared = 0
+ const { vm, routes } = setup(t, {
+ listNotifications: async () => page(history),
+ markNotificationsRead: async (ids: string[] = []) => {
+ marked.push(ids)
+ history = history.map(item => !ids.length || ids.includes(item.id) ? notice(item.id, true) : item)
+ },
+ clearReadNotifications: async () => { cleared++; history = history.filter(item => !item.read_at) },
+ })
+ await vm.refresh()
+ assert.equal(vm.badgeCount, 4)
+ vm.openPending(approval)
+ assert.equal(marked.length, 0)
+ assert.equal(routes[0], '/platform/chat/session')
+ await vm.markAllRead()
+ assert.equal(vm.unread, 0)
+ assert.equal(vm.readCount, 2)
+ assert.equal(vm.badgeCount, 2, 'one invitation and one live approval remain')
+ await vm.clearRead()
+ assert.equal(cleared, 1)
+ assert.equal(vm.items.length, 0)
+ assert.equal(vm.pending.length, 1)
+ assert.equal(vm.badgeCount, 2)
+})
+
+test('history retries its cursor and preserves reading position when new results arrive', async t => {
+ let newer = false
+ let failMore = true
+ const cursors: string[] = []
+ const { vm } = setup(t, {
+ listNotifications: async (_limit: number, cursor = '') => {
+ cursors.push(cursor)
+ if (cursor) {
+ if (failMore) { failMore = false; throw new Error('offline') }
+ return page([notice('two'), notice('three')])
+ }
+ return page(newer ? [notice('new'), notice('one')] : [notice('one'), notice('two')], {
+ next_cursor: 'older', pending: newer ? [] : [approval],
+ })
+ },
+ })
+ vm.panelVisible = true
+ await flush()
+ await vm.loadMore()
+ assert.equal(vm.loadError, 'more')
+ assert.equal(vm.nextCursor, 'older')
+ await vm.retry()
+ assert.equal(vm.items.map((item: any) => item.id).join(','), 'one,two,three')
+ assert.equal(cursors.slice(-2).join(','), 'older,older')
+ newer = true
+ await vm.refresh()
+ assert.equal(vm.pending.length, 0, 'resolved approvals disappear while browsing history')
+ assert.equal(vm.hasNew, true)
+ assert.equal(vm.items.map((item: any) => item.id).join(','), 'one,two,three')
+ await vm.refresh(true)
+ assert.equal(vm.items.map((item: any) => item.id).join(','), 'new,one')
+ assert.equal(vm.hasNew, false)
+ assert.equal(vm.nextCursor, 'older')
+})
+
+test('a response from a previous workspace cannot repopulate the notification panel', async t => {
+ const first = deferred<ReturnType<typeof page>>()
+ const second = deferred<ReturnType<typeof page>>()
+ let calls = 0
+ const { vm, auth } = setup(t, { listNotifications: () => ++calls === 1 ? first.promise : second.promise })
+ const old = vm.refresh()
+ auth.effectiveTenantId = 2
+ await vue.nextTick()
+ assert.equal(vm.items.length, 0)
+ second.resolve(page([notice('workspace-two')], { pending: [] }))
+ await flush()
+ first.resolve(page([notice('workspace-one')]))
+ await old
+ assert.equal(vm.items.map((item: any) => item.id).join(','), 'workspace-two')
+ assert.equal(vm.pending.length, 0)
+})
+
+test('failed read and clear requests preserve unread state and history', async t => {
+ const { vm, errors } = setup(t, {
+ listNotifications: async () => page([notice('unread'), notice('read', true)]),
+ markNotificationsRead: async () => { throw new Error('offline') },
+ clearReadNotifications: async () => { throw new Error('offline') },
+ })
+ await vm.refresh()
+ await vm.open(vm.items[0])
+ assert.equal(vm.unread, 1)
+ assert.equal(vm.items[0].read_at, null)
+ await vm.clearRead()
+ assert.equal(vm.items.length, 2)
+ assert.equal(errors.length, 2)
+})
+
+test('banners skip the initial backlog, deduplicate polls, and prioritize new approvals', async t => {
+ let response = page([notice('old')])
+ const { vm } = setup(t, { listNotifications: async () => response })
+ await vm.refresh()
+ assert.equal(vm.banners.length, 0)
+ response = page([notice('new-1'), notice('new-2'), notice('new-3'), notice('old')], {
+ pending: [approval, { ...approval, id: 'new-approval' }],
+ })
+ await vm.refresh()
+ assert.deepEqual(Array.from(vm.banners, (banner: any) => banner.key),
+ ['pending:new-approval', 'result:new-1', 'result:new-2'])
+ assert.equal(vm.banners[0].type, 'pending')
+ await vm.refresh()
+ assert.equal(vm.banners.length, 3)
+ const unread = vm.unread
+ vm.dismissBanner('result:new-1')
+ assert.equal(vm.unread, unread, 'dismissing a banner does not mark the notification read')
+ vm.dismissBanner('pending:new-approval')
+ assert.equal(vm.pending.length, 2, 'dismissing a banner never resolves an approval')
+ await vm.refresh()
+ assert.equal(vm.banners.length, 1, 'dismissed or overflow banners do not replay on the next poll')
+})
+
+test('banners expire after ten seconds and pause while being read', async t => {
+ let response = page()
+ const { vm } = setup(t, { listNotifications: async () => response })
+ await vm.refresh()
+ response = page([notice('new')])
+ await vm.refresh()
+ t.mock.timers.tick(9_000)
+ assert.equal(vm.banners.length, 1)
+ vm.setBannerHover(true)
+ t.mock.timers.tick(20_000)
+ assert.equal(vm.banners.length, 1)
+ vm.setBannerFocus({ type: 'focusin' })
+ vm.setBannerHover(false)
+ t.mock.timers.tick(20_000)
+ assert.equal(vm.banners.length, 1, 'keyboard focus keeps the banner visible after the pointer leaves')
+ vm.setBannerFocus({ type: 'focusout', currentTarget: { contains: () => false }, relatedTarget: null })
+ t.mock.timers.tick(10_000)
+ assert.equal(vm.banners.length, 0)
+ assert.equal(vm.unread, 1)
+})
+
+test('clicking a result banner opens and marks it read; an approval only opens its conversation', async t => {
+ let response = page()
+ const marked: string[][] = []
+ const { vm, routes } = setup(t, {
+ listNotifications: async () => response,
+ markNotificationsRead: async (ids: string[]) => { marked.push(ids) },
+ })
+ await vm.refresh()
+ response = page([notice('new')], { pending: [approval, { ...approval, id: 'new-approval' }] })
+ await vm.refresh()
+ vm.openBanner(vm.banners[0])
+ assert.equal(routes.at(-1), approval.link)
+ assert.equal(marked.length, 0)
+ vm.openBanner(vm.banners[0])
+ await flush()
+ assert.equal(routes.at(-1), '/platform/automations/new')
+ assert.deepEqual(marked.map(ids => Array.from(ids)), [['new']])
+})
+
+test('resolved approvals and read results disappear, and opening the inbox suppresses duplicate banners', async t => {
+ let response = page()
+ const { vm } = setup(t, { listNotifications: async () => response })
+ await vm.refresh()
+ response = page([notice('new')], { pending: [{ ...approval, id: 'new-approval' }] })
+ await vm.refresh()
+ assert.equal(vm.banners.length, 2)
+ response = page([notice('new', true)], { pending: [] })
+ await vm.refresh()
+ assert.equal(vm.banners.length, 0)
+ response = page([notice('another')])
+ await vm.refresh()
+ assert.equal(vm.banners.length, 1)
+ vm.panelVisible = true
+ await flush()
+ assert.equal(vm.banners.length, 0)
+ response = page([notice('while-open'), notice('another')])
+ await vm.refresh()
+ vm.panelVisible = false
+ await vm.refresh()
+ assert.equal(vm.banners.length, 0)
+})
+
+test('workspace switches reset banners, and older results revealed by clearing history are not new arrivals', async t => {
+ let response = page([notice('initial')])
+ const { vm, auth } = setup(t, { listNotifications: async () => response })
+ await vm.refresh()
+ response = page([notice('new')])
+ await vm.refresh()
+ assert.equal(vm.banners.length, 1)
+ auth.effectiveTenantId = 2
+ await flush()
+ assert.equal(vm.banners.length, 0, 'the new workspace is seeded without replaying history')
+ response = page([{ ...notice('older'), created_at: '2026-10-19T00:00:00Z' }])
+ await vm.refresh()
+ assert.equal(vm.banners.length, 0)
+})
diff --git a/frontend/src/components/GlobalInvitationBell.vue b/frontend/src/components/GlobalInvitationBell.vue
index 48da46e07..b401173b2 100644
--- a/frontend/src/components/GlobalInvitationBell.vue
+++ b/frontend/src/components/GlobalInvitationBell.vue
@@ -1,92 +1,314 @@
<template>
- <!-- 通知入口:合并展示"待处理邀请"与站内通知(自动化运行结果、等待审批等)。
- 触发区域由调用方通过默认插槽渲染(侧栏底部用户栏右侧),面板向右弹出。
- 通知靠轮询刷新,页面不可见时暂停。 -->
<t-popup v-model:visible="panelVisible" trigger="click" placement="right-bottom" :overlay-inner-style="{ padding: 0 }">
- <slot :count="badgeCount" :open="panelVisible" />
- <template #content>
- <div class="notification-panel">
- <div class="notification-panel__head">
- <span>{{ $t('notifications.title') }}</span>
- <t-button v-if="unread > 0" size="small" variant="text" theme="primary" @click="markAllRead">
- {{ $t('notifications.markAllRead') }}
- </t-button>
+ <slot :count="badgeCount" :open="panelVisible" />
+ <template #content>
+ <div class="notification-panel" :aria-label="t('notifications.title')">
+ <div class="notification-panel__head">
+ <span>{{ t('notifications.title') }}</span>
+ <div class="notification-panel__actions">
+ <button v-if="unread > 0" type="button" :disabled="busy" @click="markAllRead">{{ t('notifications.markAllRead') }}</button>
+ <t-popconfirm v-if="readCount > 0" :content="t('notifications.clearReadConfirm')" theme="default" placement="bottom-right"
+ :confirm-btn="{ content: t('notifications.clearRead'), theme: 'primary' }" :cancel-btn="t('common.cancel')"
+ :popup-props="{ disabled: busy }" @confirm="clearRead">
+ <button type="button" :disabled="busy">{{ t('notifications.clearRead') }}</button>
+ </t-popconfirm>
</div>
- <button v-if="pendingInvitationCount > 0" type="button" class="notification-item" @click="openInvitations">
- <t-icon name="usergroup-add" size="16px" class="notification-item__icon" />
- <span class="notification-item__body">
- <span class="notification-item__title">{{ $t('tenantInvitation.inboxTooltip') }}</span>
- <span class="notification-item__text">
- {{ $t('notifications.pendingInvitations', { count: pendingInvitationCount }) }}
+ </div>
+ <div class="notification-panel__scroll">
+ <section v-if="pendingCount" class="notification-panel__pending">
+ <h3>{{ t('notifications.pending') }}<span>{{ pendingCount }}</span></h3>
+ <button v-if="pendingInvitationCount > 0" type="button" class="notification-task" @click="openInvitations">
+ <span class="notification-item__body">
+ <span class="notification-item__heading">
+ <t-icon name="usergroup-add" size="16px" class="notification-task__icon" />
+ <span class="notification-item__title">{{ t('tenantInvitation.inboxTooltip') }}</span>
+ </span>
+ <span class="notification-item__text">{{ t('notifications.pendingInvitations', { count: pendingInvitationCount }) }}</span>
+ <span class="notification-task__action">{{ t('notifications.handle') }}<t-icon name="chevron-right" size="12px" /></span>
</span>
- </span>
- </button>
- <button v-for="item in items" :key="item.id" type="button" class="notification-item"
- :class="{ 'is-unread': !item.read_at }" @click="open(item)">
- <span class="notification-item__dot" :class="`is-${item.kind.replace('.', '-')}`" aria-hidden="true" />
- <span class="notification-item__body">
- <span class="notification-item__title">{{ item.title }}</span>
- <span v-if="item.body" class="notification-item__text">{{ item.body }}</span>
- <span class="notification-item__time">
- {{ kindLabel(item.kind) }} · {{ formatTime(item.created_at) }}
+ </button>
+ <button v-for="item in pending" :key="item.id" type="button" class="notification-task" @click="openPending(item)">
+ <span class="notification-item__body">
+ <span class="notification-item__heading">
+ <t-icon :name="item.kind === 'tool_approval' ? 'secured' : 'chat'" size="16px" class="notification-task__icon" />
+ <span class="notification-item__title">{{ item.title }}</span>
+ </span>
+ <span class="notification-item__footer">
+ <span>{{ pendingLabel(item.kind) }}</span>
+ <span class="notification-task__action">{{ item.kind === 'tool_approval' ? t('notifications.review') : t('notifications.handle') }}<t-icon name="chevron-right" size="12px" /></span>
+ </span>
</span>
- </span>
- </button>
- <p v-if="!items.length && pendingInvitationCount === 0" class="notification-panel__empty">
- {{ $t('notifications.empty') }}
- </p>
+ </button>
+ </section>
+ <section class="notification-panel__history">
+ <h3>{{ t('notifications.history') }}<span v-if="unread">{{ t('notifications.unreadCount', { count: unread }) }}</span></h3>
+ <button v-if="hasNew" type="button" class="notification-panel__refresh" :disabled="loading || busy" @click="refresh(true)">
+ {{ t('notifications.newItems') }}
+ </button>
+ <button v-for="item in items" :key="item.id" type="button" class="notification-item"
+ :class="{ 'is-unread': !item.read_at }" :disabled="busy" @click="open(item)">
+ <span class="notification-item__body">
+ <span class="notification-item__heading">
+ <span class="notification-item__title">{{ item.title }}</span>
+ <span v-if="!item.read_at" class="notification-item__unread">{{ t('notifications.unread') }}</span>
+ </span>
+ <span v-if="item.body" class="notification-item__text">{{ item.body }}</span>
+ <span class="notification-item__footer">
+ <span class="notification-item__status">
+ <t-icon :name="historyIcon(item.kind)" size="14px" class="notification-item__icon"
+ :class="{ 'is-success': item.kind === 'automation.succeeded', 'is-error': item.kind === 'automation.failed', 'is-warning': item.kind === 'automation.paused' }" />
+ {{ kindLabel(item.kind) }}
+ </span>
+ <time class="notification-item__time" :datetime="item.created_at">{{ formatTime(item.created_at) }}</time>
+ </span>
+ </span>
+ </button>
+ <p v-if="!items.length && !loading && !loadError" class="notification-panel__empty">{{ t('notifications.empty') }}</p>
+ <div v-if="loadError" class="notification-panel__error" role="status">
+ {{ t('notifications.loadError') }}
+ <button type="button" :disabled="loading || busy" @click="retry">{{ t('common.retry') }}</button>
+ </div>
+ <div v-if="loading" class="notification-panel__loading"><t-loading size="small" /></div>
+ <button v-else-if="nextCursor && !loadError" type="button" class="notification-panel__more" :disabled="busy" @click="loadMore">
+ {{ t('common.loadMore') }}
+ </button>
+ </section>
</div>
- </template>
+ </div>
+ </template>
</t-popup>
<MyInvitationsDialog v-model:visible="dialogVisible" />
+ <Teleport to="body">
+ <TransitionGroup name="notification-banner" tag="div" class="notification-banners" aria-live="polite"
+ :aria-label="t('notifications.title')" @mouseenter="setBannerHover(true)" @mouseleave="setBannerHover(false)"
+ @focusin="setBannerFocus" @focusout="setBannerFocus">
+ <article v-for="banner in banners" :key="banner.key" class="notification-banner"
+ :class="{ 'is-pending': banner.type === 'pending' }">
+ <button type="button" class="notification-banner__content" :disabled="busy" @click="openBanner(banner)">
+ <span class="notification-banner__body">
+ <span class="notification-banner__meta">
+ <t-icon class="notification-banner__icon" :class="{
+ 'is-success': banner.item.kind === 'automation.succeeded',
+ 'is-error': banner.item.kind === 'automation.failed',
+ 'is-warning': banner.type === 'pending' || banner.item.kind === 'automation.paused',
+ }" :name="banner.type === 'pending' ? 'secured' : historyIcon(banner.item.kind)" size="13px" />
+ <span class="notification-banner__label">
+ {{ banner.type === 'pending' ? pendingLabel(banner.item.kind) : kindLabel(banner.item.kind) }}
+ </span>
+ <time class="notification-banner__time" :datetime="banner.item.created_at">{{ bannerTime(banner.item.created_at) }}</time>
+ </span>
+ <span class="notification-banner__title">{{ banner.item.title }}</span>
+ <span v-if="banner.type === 'result' && banner.item.body" class="notification-banner__summary">{{ notificationPreview(banner.item.body) }}</span>
+ </span>
+ </button>
+ <button type="button" class="notification-banner__close" :aria-label="t('common.close')" @click="dismissBanner(banner.key)">
+ <t-icon name="close" size="14px" />
+ </button>
+ </article>
+ </TransitionGroup>
+ </Teleport>
</template>
<script setup lang="ts">
-import { computed, onBeforeUnmount, onMounted, ref } from 'vue'
+import { computed, onBeforeUnmount, onMounted, ref, watch } from 'vue'
import { useRouter } from 'vue-router'
import { useI18n } from 'vue-i18n'
+import { MessagePlugin } from 'tdesign-vue-next'
import { useAuthStore } from '@/stores/auth'
import MyInvitationsDialog from '@/components/MyInvitationsDialog.vue'
-import { listNotifications, markNotificationsRead, type AppNotification } from '@/api/automation'
+import { notificationPreview } from '@/utils/notificationPreview'
+import { clearReadNotifications, listNotifications, markNotificationsRead, type AppNotification, type NotificationPage, type PendingNotification } from '@/api/automation'
const POLL_MS = 60_000
-
const authStore = useAuthStore()
const router = useRouter()
const { t, te, locale } = useI18n()
-
const pendingInvitationCount = computed(() => authStore.pendingInvitationCount)
const items = ref<AppNotification[]>([])
+const pending = ref<PendingNotification[]>([])
const unread = ref(0)
-const badgeCount = computed(() => pendingInvitationCount.value + unread.value)
-
+const readCount = ref(0)
+const pendingCount = computed(() => pendingInvitationCount.value + pending.value.length)
+const badgeCount = computed(() => pendingCount.value + unread.value)
+const nextCursor = ref('')
+const historyExpanded = ref(false)
+const hasNew = ref(false)
+const loading = ref(false)
+const busy = ref(false)
+const loadError = ref<'' | 'refresh' | 'more'>('')
const dialogVisible = ref(false)
const panelVisible = ref(false)
+let version = 0
let timer: ReturnType<typeof setInterval> | undefined
+type NotificationBanner = { key: string } & (
+ { type: 'pending'; item: PendingNotification } | { type: 'result'; item: AppNotification }
+)
+const banners = ref<NotificationBanner[]>([])
+const seenBanners = new Set<string>()
+const bannerTimers = new Map<string, ReturnType<typeof setTimeout>>()
+let bannersInitialized = false
+let newestNotificationTime = 0
+let bannersPaused = false
+let bannerHovered = false
+let bannerFocused = false
+
+function setBannerHover(hovered: boolean) {
+ bannerHovered = hovered
+ if (bannerHovered || bannerFocused) pauseBanners()
+ else resumeBanners()
+}
+function setBannerFocus(event: FocusEvent) {
+ bannerFocused = event.type === 'focusin' || !!(event.currentTarget as HTMLElement).contains(event.relatedTarget as Node | null)
+ if (bannerHovered || bannerFocused) pauseBanners()
+ else resumeBanners()
+}
+
+function dismissBanner(key: string) {
+ clearTimeout(bannerTimers.get(key))
+ bannerTimers.delete(key)
+ banners.value = banners.value.filter(banner => banner.key !== key)
+}
+function pauseBanners() {
+ bannersPaused = true
+ for (const timeout of bannerTimers.values()) clearTimeout(timeout)
+ bannerTimers.clear()
+}
+function resumeBanners() {
+ pauseBanners()
+ bannersPaused = false
+ for (const banner of banners.value) {
+ bannerTimers.set(banner.key, setTimeout(() => dismissBanner(banner.key), 10_000))
+ }
+}
+function clearBanners() {
+ pauseBanners()
+ banners.value = []
+ bannersPaused = false
+ bannerHovered = bannerFocused = false
+}
+function updateBanners(page: NotificationPage) {
+ const livePending = new Set((page.pending ?? []).map(item => item.id))
+ const read = new Set((page.items ?? []).filter(item => item.read_at).map(item => item.id))
+ for (const banner of banners.value) {
+ if (banner.type === 'pending' ? !livePending.has(banner.item.id) : read.has(banner.item.id)) dismissBanner(banner.key)
+ }
+ const candidates: NotificationBanner[] = [
+ ...(page.pending ?? []).map(item => ({ key: `pending:${item.id}`, type: 'pending' as const, item })),
+ ...(page.items ?? []).map(item => ({ key: `result:${item.id}`, type: 'result' as const, item })),
+ ]
+ const fresh = candidates.filter(banner => !seenBanners.has(banner.key) &&
+ (banner.type === 'pending' || (!banner.item.read_at && Date.parse(banner.item.created_at) >= newestNotificationTime)))
+ for (const banner of candidates) seenBanners.add(banner.key)
+ for (const item of page.items ?? []) newestNotificationTime = Math.max(newestNotificationTime, Date.parse(item.created_at) || 0)
+ // Seed the first successful response without replaying historical notifications.
+ if (bannersInitialized && !panelVisible.value && fresh.length) {
+ const next = [...fresh, ...banners.value]
+ .sort((a, b) => Number(b.type === 'pending') - Number(a.type === 'pending')).slice(0, 3)
+ const retained = new Set(next.map(banner => banner.key))
+ for (const banner of banners.value) if (!retained.has(banner.key)) dismissBanner(banner.key)
+ banners.value = next
+ if (!bannersPaused) resumeBanners()
+ }
+ bannersInitialized = true
+}
+function openBanner(banner: NotificationBanner) {
+ if (busy.value) return
+ dismissBanner(banner.key)
+ if (banner.type === 'pending') openPending(banner.item)
+ else void open(banner.item)
+}
+
+function applyCounts(page: NotificationPage) {
+ pending.value = page.pending ?? []
+ unread.value = page.unread ?? 0
+ readCount.value = page.read_count ?? 0
+}
+
+async function refresh(reset = false) {
+ if (busy.value || (loading.value && !reset) || document.visibilityState === 'hidden') return
+ const request = ++version
+ loading.value = true
+ try {
+ const { data } = await listNotifications(20)
+ if (request !== version) return
+ updateBanners(data)
+ applyCounts(data)
+ if (reset || !historyExpanded.value || !panelVisible.value) {
+ items.value = data.items ?? []
+ nextCursor.value = data.next_cursor ?? ''
+ historyExpanded.value = false
+ hasNew.value = false
+ } else {
+ // Keep the cursor and reading position while browsing older pages.
+ // New arrivals are revealed explicitly, so a busy feed cannot create gaps.
+ const known = new Set(items.value.map(item => item.id))
+ hasNew.value = (data.items ?? []).some(item => !known.has(item.id))
+ const fresh = new Map((data.items ?? []).map(item => [item.id, item]))
+ items.value = items.value.map(item => fresh.get(item.id) ?? item)
+ }
+ loadError.value = ''
+ } catch {
+ if (request === version) loadError.value = 'refresh'
+ } finally {
+ if (request === version) loading.value = false
+ }
+}
-async function refresh() {
- if (typeof document !== 'undefined' && document.visibilityState === 'hidden') return
+async function loadMore() {
+ if (!nextCursor.value || loading.value || busy.value) return
+ const request = ++version
+ loading.value = true
try {
- const res = await listNotifications(20)
- items.value = res.data?.items ?? []
- unread.value = res.data?.unread ?? 0
+ const { data } = await listNotifications(20, nextCursor.value)
+ if (request !== version) return
+ const known = new Set(items.value.map(item => item.id))
+ items.value.push(...(data.items ?? []).filter(item => !known.has(item.id)))
+ nextCursor.value = data.next_cursor ?? ''
+ historyExpanded.value = true
+ applyCounts(data)
+ loadError.value = ''
} catch {
- // Polling retries on the next tick.
+ if (request === version) loadError.value = 'more'
+ } finally {
+ if (request === version) loading.value = false
}
}
-const onVisible = () => {
- if (document.visibilityState === 'visible') void refresh()
+function retry() {
+ return loadError.value === 'more' ? loadMore() : refresh(true)
}
+const onVisible = () => { if (document.visibilityState === 'visible') void refresh() }
+watch(panelVisible, open => {
+ if (open) {
+ clearBanners()
+ void refresh(true)
+ }
+})
+watch(() => [authStore.effectiveTenantId, authStore.user?.id], () => {
+ ++version
+ items.value = []
+ pending.value = []
+ unread.value = readCount.value = 0
+ nextCursor.value = ''
+ historyExpanded.value = hasNew.value = loading.value = busy.value = false
+ loadError.value = ''
+ panelVisible.value = false
+ clearBanners()
+ seenBanners.clear()
+ bannersInitialized = false
+ newestNotificationTime = 0
+ if (authStore.user) void refresh(true)
+})
onMounted(() => {
void refresh()
- timer = setInterval(refresh, POLL_MS)
+ timer = setInterval(() => { void refresh() }, POLL_MS)
document.addEventListener('visibilitychange', onVisible)
})
-
onBeforeUnmount(() => {
+ ++version
clearInterval(timer)
+ clearBanners()
document.removeEventListener('visibilitychange', onVisible)
})
@@ -94,121 +316,297 @@ const kindLabel = (kind: string) => {
const key = `notifications.kinds.${kind.replace('.', '_')}`
return te(key) ? t(key) : t('notifications.title')
}
+const pendingLabel = (kind: string) => t(kind === 'tool_approval' ? 'notifications.awaitingApproval'
+ : kind === 'mcp_oauth' ? 'notifications.awaitingAuthorization' : 'notifications.awaitingReply')
+const historyIcon = (kind: string) => kind === 'automation.succeeded' ? 'check-circle'
+ : kind === 'automation.failed' ? 'error-circle' : kind === 'automation.paused' ? 'pause-circle' : 'notification'
const formatTime = (iso: string) => {
const date = new Date(iso)
if (Number.isNaN(date.getTime())) return ''
return new Intl.DateTimeFormat(locale.value, { dateStyle: 'short', timeStyle: 'short' }).format(date)
}
-
-const openInvitations = () => {
+const bannerTime = (iso: string) => {
+ const date = new Date(iso)
+ return Number.isNaN(date.getTime()) ? '' : new Intl.DateTimeFormat(locale.value, {
+ hour: '2-digit', minute: '2-digit',
+ }).format(date)
+}
+const openInvitations = () => { panelVisible.value = false; dialogVisible.value = true }
+function navigate(link: string) {
panelVisible.value = false
- dialogVisible.value = true
+ if (link.startsWith('/') && !link.startsWith('//')) void router.push(link)
}
+function openPending(item: PendingNotification) { navigate(item.link) }
+async function mutate(action: () => Promise<unknown>, onSuccess: () => void, reset = false) {
+ if (busy.value) return
+ const request = ++version
+ busy.value = true
+ loading.value = false
+ try {
+ await action()
+ if (request !== version) return
+ onSuccess()
+ } catch {
+ if (request === version) MessagePlugin.error(t('common.operationFailed'))
+ } finally {
+ if (request === version) {
+ busy.value = false
+ await refresh(reset)
+ }
+ }
+}
async function open(item: AppNotification) {
- panelVisible.value = false
- if (!item.read_at) {
+ if (busy.value) return
+ navigate(item.link)
+ if (!item.read_at) await mutate(() => markNotificationsRead([item.id]), () => {
item.read_at = new Date().toISOString()
- unread.value = Math.max(0, unread.value - 1)
- markNotificationsRead([item.id]).catch(() => {})
- }
- if (item.link.startsWith('/')) void router.push(item.link)
+ })
}
-
async function markAllRead() {
- try {
- await markNotificationsRead()
+ await mutate(() => markNotificationsRead(), () => {
const now = new Date().toISOString()
- items.value = items.value.map((item) => ({ ...item, read_at: item.read_at ?? now }))
- unread.value = 0
- } catch {
- // Left unread; the next poll shows the real state.
- }
+ items.value = items.value.map(item => ({ ...item, read_at: item.read_at ?? now }))
+ for (const banner of banners.value) if (banner.type === 'result') dismissBanner(banner.key)
+ })
+}
+async function clearRead() {
+ await mutate(clearReadNotifications, () => {
+ items.value = items.value.filter(item => !item.read_at)
+ }, true)
}
</script>
<style lang="less" scoped>
-.notification-panel {
- width: 360px;
- max-height: 460px;
+.notification-banners {
+ position: fixed;
+ top: max(20px, env(safe-area-inset-top));
+ right: max(24px, env(safe-area-inset-right));
+ z-index: 5000;
+ display: flex;
+ flex-direction: column;
+ gap: 10px;
+ width: min(352px, calc(100vw - 32px));
+ max-height: calc(100dvh - 40px);
overflow-y: auto;
- padding: 4px 0;
+ padding: 12px;
+ margin: -12px;
+ pointer-events: none;
+ font-family: var(--app-font-family);
+}
+.notification-banner {
+ position: relative;
+ flex-shrink: 0;
+ border-radius: 14px;
+ background: color-mix(in srgb, var(--td-bg-color-container) 94%, transparent);
+ backdrop-filter: blur(20px) saturate(140%);
+ -webkit-backdrop-filter: blur(20px) saturate(140%);
+ color: var(--td-text-color-primary);
+ box-shadow: 0 6px 24px rgb(0 0 0 / 9%), 0 1px 3px rgb(0 0 0 / 4%);
+ pointer-events: auto;
+ button:focus-visible { outline: 2px solid var(--td-brand-color-focus); outline-offset: 2px; }
+}
+.notification-banner__content {
+ display: flex;
+ width: 100%;
+ padding: 12px 16px 14px;
+ border: 0;
+ border-radius: inherit;
+ background: transparent;
+ color: inherit;
+ font: inherit;
+ text-align: left;
+ cursor: pointer;
+ &:disabled { cursor: default; }
+}
+.notification-banner__icon {
+ flex-shrink: 0;
+ color: var(--td-text-color-secondary);
+ &.is-success { color: var(--td-success-color); }
+ &.is-error { color: var(--td-error-color); }
+ &.is-warning { color: var(--td-warning-color); }
+}
+.notification-banner__body { display: flex; flex: 1; flex-direction: column; gap: 3px; min-width: 0; }
+.notification-banner__meta { display: flex; align-items: center; gap: 5px; padding-right: 20px; margin-bottom: 4px; }
+.notification-banner__label { overflow: hidden; text-overflow: ellipsis; white-space: nowrap; color: var(--td-text-color-secondary); font-size: var(--app-text-xs); line-height: 1.5; }
+.notification-banner__time { margin-left: auto; flex-shrink: 0; color: var(--td-text-color-placeholder); font-size: var(--app-text-xs); font-variant-numeric: tabular-nums; }
+.is-pending .notification-banner__label { color: var(--td-warning-color); }
+.notification-banner__title {
+ overflow: hidden;
+ text-overflow: ellipsis;
+ white-space: nowrap;
+ font-size: var(--app-text-md);
+ font-weight: 600;
+ line-height: 1.5;
+}
+.notification-banner__summary {
+ display: -webkit-box;
+ -webkit-box-orient: vertical;
+ -webkit-line-clamp: 2;
+ overflow: hidden;
+ overflow-wrap: anywhere;
+ color: var(--td-text-color-secondary);
+ font-size: var(--app-text-sm);
+ line-height: 1.55;
+}
+.notification-banner__close {
+ position: absolute;
+ top: 8px;
+ right: 8px;
+ display: flex;
+ align-items: center;
+ justify-content: center;
+ width: 24px;
+ height: 24px;
+ border: 0;
+ border-radius: var(--app-radius-sm);
+ background: transparent;
+ color: var(--td-text-color-placeholder);
+ cursor: pointer;
+ &:hover { color: var(--td-text-color-primary); background: var(--td-bg-color-container-hover); }
+}
+.notification-banner-enter-active,
+.notification-banner-leave-active,
+.notification-banner-move { transition: opacity var(--app-motion-base) ease, transform var(--app-motion-base) ease; }
+.notification-banner-enter-from,
+.notification-banner-leave-to { opacity: 0; transform: translateX(16px); }
+@media (max-width: 480px) { .notification-banners { top: max(12px, env(safe-area-inset-top)); right: 16px; } }
+@media (prefers-reduced-motion: reduce) {
+ .notification-banner-enter-active,
+ .notification-banner-leave-active,
+ .notification-banner-move { transition: none; }
+}
+.notification-panel {
+ width: min(380px, calc(100vw - 32px));
+ display: flex;
+ flex-direction: column;
+ max-height: min(560px, calc(100vh - 48px));
+ color: var(--td-text-color-primary);
+ font-family: var(--app-font-family);
+ font-size: var(--app-text-md);
+ font-weight: 400;
+ line-height: 1.5;
}
-
.notification-panel__head {
display: flex;
align-items: center;
justify-content: space-between;
- margin: 0 4px 4px;
- padding: 6px 12px 8px;
+ gap: 12px;
+ padding: 14px 16px;
border-bottom: 1px solid var(--td-component-stroke);
+ font-size: var(--app-text-base);
font-weight: 600;
+ flex-shrink: 0;
}
-
-.notification-panel__empty {
- margin: 0;
- padding: 16px 12px;
- color: var(--td-text-color-placeholder);
+.notification-panel__actions {
+ display: flex;
+ align-items: center;
+ gap: 10px;
+}
+.notification-panel__actions button,
+.notification-panel__error button,
+.notification-panel__more,
+.notification-panel__refresh {
+ border: 0;
+ border-radius: var(--app-radius-sm);
+ background: transparent;
+ color: var(--td-text-color-secondary);
+ font: inherit;
font-size: var(--app-text-sm);
- text-align: center;
+ font-weight: 400;
+ cursor: pointer;
+ padding: 4px;
+ &:hover:not(:disabled) { color: var(--td-text-color-primary); background: var(--td-bg-color-container-hover); }
+ &:disabled { cursor: default; opacity: 0.5; }
}
-
+.notification-panel__scroll { min-height: 0; overflow-y: auto; padding: 12px 8px; overscroll-behavior: contain; }
+.notification-panel h3 {
+ display: flex;
+ align-items: center;
+ gap: 6px;
+ margin: 0 12px 8px;
+ font-size: var(--app-text-xs);
+ font-weight: 500;
+ color: var(--td-text-color-secondary);
+ > span { font-weight: 400; }
+}
+.notification-panel__pending { margin-bottom: 20px; }
+.notification-task,
.notification-item {
display: flex;
- gap: 10px;
- width: calc(100% - 8px);
- margin: 2px 4px;
- padding: 8px 12px;
+ align-items: flex-start;
+ width: 100%;
+ box-sizing: border-box;
+ padding: 12px;
border: 0;
- border-radius: var(--app-radius-sm);
- background: none;
+ border-radius: var(--app-radius-md);
color: var(--td-text-color-primary);
font: inherit;
text-align: left;
cursor: pointer;
-
- &:hover {
- background: var(--td-bg-color-container-hover);
- }
-
+ transition: background-color 0.15s ease;
+}
+.notification-task {
+ margin-bottom: 6px;
+ background: color-mix(in srgb, var(--td-warning-color) 4%, var(--td-bg-color-container));
+ &:hover { background: color-mix(in srgb, var(--td-warning-color) 7%, var(--td-bg-color-container)); }
+}
+.notification-task__icon { flex-shrink: 0; color: var(--td-warning-color); }
+.notification-task__action {
+ display: inline-flex;
+ align-items: center;
+ gap: 2px;
+ flex-shrink: 0;
+ font-size: var(--app-text-sm);
+ font-weight: 500;
+ color: var(--td-text-color-primary);
+}
+.notification-item {
+ background: transparent;
+ &:hover:not(:disabled) { background: color-mix(in srgb, var(--td-bg-color-container-hover) 55%, var(--td-bg-color-container)); }
+ .notification-item__title { font-weight: 400; }
&.is-unread {
- background: var(--td-bg-color-secondarycontainer);
-
- &:hover {
- background: var(--td-bg-color-secondarycontainer-hover);
- }
+ background: color-mix(in srgb, var(--td-bg-color-container-hover) 65%, var(--td-bg-color-container));
+ .notification-item__title { font-weight: 600; }
+ &:hover:not(:disabled) { background: var(--td-bg-color-container-hover); }
}
+ &:disabled { cursor: default; }
+ & + & { margin-top: 4px; }
}
-
-.notification-item__dot {
+.notification-item__icon {
flex-shrink: 0;
- width: 6px;
- height: 6px;
- margin-top: 6px;
- border-radius: 50%;
- background: var(--td-text-color-placeholder);
-
- &.is-automation-succeeded { background: var(--td-success-color); }
- &.is-automation-failed { background: var(--td-error-color); }
- &.is-automation-awaiting_approval,
- &.is-automation-paused { background: var(--td-warning-color); }
-}
-
-.notification-item__body {
- display: flex;
- flex-direction: column;
- gap: 2px;
- min-width: 0;
+ color: var(--td-text-color-secondary);
+ &.is-success { color: var(--td-success-color); }
+ &.is-error { color: var(--td-error-color); }
+ &.is-warning { color: var(--td-warning-color); }
}
-
+.notification-item__body { display: flex; flex: 1; flex-direction: column; gap: 6px; min-width: 0; }
+.notification-item__heading { display: flex; align-items: center; gap: 6px; min-width: 0; }
.notification-item__title {
+ min-width: 0;
overflow: hidden;
font-size: var(--app-text-md);
font-weight: 500;
text-overflow: ellipsis;
white-space: nowrap;
}
-
+.notification-item__unread {
+ display: inline-flex;
+ align-items: center;
+ gap: 5px;
+ flex-shrink: 0;
+ margin-left: auto;
+ color: var(--td-text-color-secondary);
+ font-size: var(--app-text-xs);
+ font-weight: 400;
+ &::before {
+ content: '';
+ width: 6px;
+ height: 6px;
+ border-radius: 50%;
+ background: var(--td-brand-color);
+ }
+}
.notification-item__text {
display: -webkit-box;
-webkit-box-orient: vertical;
@@ -216,13 +614,26 @@ async function markAllRead() {
line-clamp: 2;
overflow: hidden;
color: var(--td-text-color-secondary);
- font-size: var(--app-text-xs);
- line-height: 1.5;
+ font-size: var(--app-text-md);
+ font-weight: 400;
+ line-height: 1.6;
overflow-wrap: anywhere;
}
-
-.notification-item__time {
- color: var(--td-text-color-placeholder);
+.notification-item__footer {
+ display: flex;
+ flex-wrap: wrap;
+ align-items: center;
+ justify-content: space-between;
+ gap: 4px 12px;
+ color: var(--td-text-color-secondary);
font-size: var(--app-text-xs);
}
+.notification-item__status { display: inline-flex; align-items: center; gap: 4px; }
+.notification-item__time { font-variant-numeric: tabular-nums; }
+.notification-panel__empty,
+.notification-panel__error { margin: 0; padding: 16px 8px; color: var(--td-text-color-secondary); font-size: var(--app-text-xs); text-align: center; }
+.notification-panel__loading { display: flex; justify-content: center; padding: 12px; }
+.notification-panel__more,
+.notification-panel__refresh { width: 100%; padding: 8px; margin-top: 6px; }
+.notification-panel button:focus-visible { outline: 2px solid var(--td-brand-color-focus); outline-offset: 1px; }
</style>
diff --git a/frontend/src/composables/useChatStreamHandler.dataChange.test.ts b/frontend/src/composables/useChatStreamHandler.dataChange.test.ts
index a3215fbad..71822f122 100644
--- a/frontend/src/composables/useChatStreamHandler.dataChange.test.ts
+++ b/frontend/src/composables/useChatStreamHandler.dataChange.test.ts
@@ -49,6 +49,19 @@ test('emits the marker of a Wiki edit', t => {
assert.equal(handler.listener.mock.callCount(), 1)
})
+for (const operation of ['automation.create', 'automation.update', 'automation.pause', 'automation.run_now']) {
+ test(`forwards ${operation} changes without requiring resource IDs`, t => {
+ const handler = setup(t)
+ handler.processStreamChunk({ response_type: 'tool_result', id: 'r1', data: {
+ tool_call_id: 'call', tool_name: 'run_operation', success: true,
+ data_change: { operation, area: 'automation' },
+ } })
+ assert.equal(handler.listener.mock.callCount(), 1)
+ assert.equal(handler.listener.mock.calls[0].arguments[0].detail.operation, operation)
+ assert.equal(handler.listener.mock.calls[0].arguments[0].detail.area, 'automation')
+ })
+}
+
for (const data of [
{ success: false, data_change: change('agent.delete') },
{ success: true },
diff --git a/frontend/src/composables/usePromptDock.test.mjs b/frontend/src/composables/usePromptDock.test.mjs
index 6596c394a..dc65c14ef 100644
--- a/frontend/src/composables/usePromptDock.test.mjs
+++ b/frontend/src/composables/usePromptDock.test.mjs
@@ -91,7 +91,7 @@ test('both chat views mount the dock above their composer and feed it their mess
const read = (path) => readFileSync(new URL(path, import.meta.url), 'utf8')
const chat = read('../views/chat/index.vue')
assert.match(chat, /providePromptDock\(messagesList\)/)
- assert.match(chat, /<PendingPromptDock[^>]*\/>\s*<InputField/)
+ assert.match(chat, /<PendingPromptDock[^>]*\/>[\s\S]*?<InputField/)
const embed = read('../views/embed/EmbedChatCore.vue')
assert.match(embed, /providePromptDock\(messagesList\)/)
diff --git a/frontend/src/i18n/locales/en-US.ts b/frontend/src/i18n/locales/en-US.ts
index 120fa7065..373b06e8f 100755
--- a/frontend/src/i18n/locales/en-US.ts
+++ b/frontend/src/i18n/locales/en-US.ts
@@ -125,15 +125,17 @@ export default {
"historyNoOverrides": "No administrator changes",
},
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.',
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}',
- notScheduled: 'Not scheduled',
agentUnavailable: 'Agent unavailable',
- deleteTitle: 'Delete automation',
+ 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',
@@ -153,6 +155,9 @@ export default {
enabled: 'Enabled',
},
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",
createTitle: 'New automation',
editTitle: 'Edit automation',
namePlaceholder: 'e.g. Daily knowledge base digest',
@@ -280,8 +285,6 @@ export default {
stop: 'Stop',
},
detail: {
- overview: 'Overview',
- lastRun: 'Last run',
pausedBecause: 'Paused: {reason}',
runs: 'Runs',
noRuns: 'No runs yet',
@@ -314,6 +317,20 @@ export default {
},
},
notifications: {
+ pending: "Needs attention",
+ history: "Notification history",
+ clearRead: "Clear read",
+ clearReadConfirm: "Clear read notifications? Run records, conversations, and pending actions will be kept.",
+ handle: "Open",
+ review: "Review",
+ unreadCount: "{count} unread",
+ unread: "Unread",
+ newItems: "New notifications — refresh",
+ loadError: "Could not load notifications",
+ awaitingApproval: "Waiting for your approval",
+ awaitingAuthorization: "Waiting for authorization",
+ awaitingReply: "Waiting for your reply",
+
title: 'Notifications',
markAllRead: 'Mark all read',
pendingInvitations: '{count} pending invitations',
diff --git a/frontend/src/i18n/locales/ja-JP.ts b/frontend/src/i18n/locales/ja-JP.ts
index a9974cdfd..98df5a81b 100644
--- a/frontend/src/i18n/locales/ja-JP.ts
+++ b/frontend/src/i18n/locales/ja-JP.ts
@@ -125,15 +125,17 @@ export default {
"historyNoOverrides": "管理者の変更なし",
},
automation: {
+ conversationNotice: "この会話は自動化タスクが実行します。手動でメッセージは送信できません。保留中のリクエストは上で対応してください。",
title: 'オートメーション',
description: 'エージェントにスケジュールどおりあなたとしてタスクを実行させます。結果と承認待ちは通知されます。',
add: '新規オートメーション',
addHint: 'WeKnora アシスタントに作成を頼むこともできます',
paused: '一時停止中',
+ scheduleEnded: '終了',
+ scheduleEndedHint: 'この一回限りのスケジュールは終了しました。今すぐ実行するか、実行日時を変更してから再開してください。',
nextRunAt: '次回 {time}',
- notScheduled: '予定なし',
agentUnavailable: 'エージェントを利用できません',
- deleteTitle: 'オートメーションを削除',
+ runConfirm: '「{name}」を今すぐ実行しますか?スケジュールを変更せずに追加で実行します。',
deleteBody: '実行中の処理を停止し、「{name}」の実行履歴・会話・継続承認を削除します。元に戻せません。',
fields: {
name: '名前',
@@ -153,6 +155,9 @@ export default {
enabled: '有効',
},
editor: {
+ model: "実行モデル",
+ modelHelp: "エージェントの既定モデルを使うか、この自動化専用のモデルを選択します。変更は次回以降の実行に適用されます。",
+ modelDefault: "エージェントの既定モデル",
createTitle: '新規オートメーション',
editTitle: 'オートメーションを編集',
namePlaceholder: '例:毎日のナレッジベース要約',
@@ -280,8 +285,6 @@ export default {
stop: '停止',
},
detail: {
- overview: '概要',
- lastRun: '前回の実行',
pausedBecause: '一時停止中:{reason}',
runs: '実行履歴',
noRuns: 'まだ実行されていません',
@@ -314,6 +317,20 @@ export default {
},
},
notifications: {
+ pending: "対応が必要",
+ history: "通知履歴",
+ clearRead: "既読を削除",
+ clearReadConfirm: "既読の通知を削除しますか?実行履歴、会話、未対応の項目は保持されます。",
+ handle: "対応する",
+ review: "承認を確認",
+ unreadCount: "未読 {count} 件",
+ unread: "未読",
+ newItems: "新しい通知があります。更新",
+ loadError: "通知を読み込めませんでした",
+ awaitingApproval: "操作の承認待ち",
+ awaitingAuthorization: "認可の完了待ち",
+ awaitingReply: "返信待ち",
+
title: '通知',
markAllRead: 'すべて既読',
pendingInvitations: '保留中の招待 {count} 件',
diff --git a/frontend/src/i18n/locales/ko-KR.ts b/frontend/src/i18n/locales/ko-KR.ts
index e3d927491..4986b9a23 100755
--- a/frontend/src/i18n/locales/ko-KR.ts
+++ b/frontend/src/i18n/locales/ko-KR.ts
@@ -125,15 +125,17 @@ export default {
"historyNoOverrides": "관리자 변경 없음",
},
automation: {
+ conversationNotice: "자동화 작업이 실행하는 대화입니다. 메시지를 직접 보낼 수 없습니다. 대기 중인 요청은 위에서 처리하세요.",
title: '자동화',
description: '에이전트가 일정에 따라 사용자 본인으로 작업을 실행합니다. 결과와 승인 대기 항목은 알림으로 받습니다.',
add: '새 자동화',
addHint: 'WeKnora 어시스턴트에게 만들어 달라고 할 수도 있습니다',
paused: '일시 중지됨',
+ scheduleEnded: '종료됨',
+ scheduleEndedHint: '일회성 일정이 종료되었습니다. 지금 실행하거나 실행 시간을 변경한 후 재개하세요.',
nextRunAt: '다음 {time}',
- notScheduled: '예약 없음',
agentUnavailable: '에이전트를 사용할 수 없음',
- deleteTitle: '자동화 삭제',
+ runConfirm: '"{name}"을(를) 지금 실행할까요? 기존 일정을 변경하지 않고 추가로 실행합니다.',
deleteBody: '진행 중인 실행을 중지하고 "{name}"의 실행 기록, 대화, 상시 승인을 삭제합니다. 되돌릴 수 없습니다.',
fields: {
name: '이름',
@@ -153,6 +155,9 @@ export default {
enabled: '사용',
},
editor: {
+ model: "실행 모델",
+ modelHelp: "에이전트의 기본 모델을 사용하거나 이 자동화에 사용할 모델을 선택하세요. 변경 사항은 다음 실행부터 적용됩니다.",
+ modelDefault: "에이전트 기본 모델 사용",
createTitle: '새 자동화',
editTitle: '자동화 편집',
namePlaceholder: '예: 매일 지식 베이스 요약',
@@ -280,8 +285,6 @@ export default {
stop: '중지',
},
detail: {
- overview: '개요',
- lastRun: '마지막 실행',
pausedBecause: '일시 중지됨: {reason}',
runs: '실행 기록',
noRuns: '아직 실행되지 않았습니다',
@@ -314,6 +317,20 @@ export default {
},
},
notifications: {
+ pending: "처리 필요",
+ history: "알림 기록",
+ clearRead: "읽은 알림 삭제",
+ clearReadConfirm: "읽은 알림을 삭제할까요? 실행 기록, 대화 및 처리 대기 항목은 유지됩니다.",
+ handle: "열기",
+ review: "승인 검토",
+ unreadCount: "읽지 않음 {count}개",
+ unread: "읽지 않음",
+ newItems: "새 알림이 있습니다. 새로고침",
+ loadError: "알림을 불러오지 못했습니다",
+ awaitingApproval: "작업 승인 대기 중",
+ awaitingAuthorization: "인증 완료 대기 중",
+ awaitingReply: "답변 대기 중",
+
title: '알림',
markAllRead: '모두 읽음',
pendingInvitations: '대기 중인 초대 {count}개',
diff --git a/frontend/src/i18n/locales/ru-RU.ts b/frontend/src/i18n/locales/ru-RU.ts
index e6c53ea5f..77b076563 100755
--- a/frontend/src/i18n/locales/ru-RU.ts
+++ b/frontend/src/i18n/locales/ru-RU.ts
@@ -125,15 +125,17 @@ export default {
"historyNoOverrides": "Нет изменений администратора",
},
automation: {
+ conversationNotice: "Этот диалог выполняется автоматизацией. Отправка сообщений вручную недоступна. Обработайте ожидающие запросы выше.",
title: 'Автоматизации',
description: 'Агент выполняет задачи по расписанию от вашего имени. О результатах и ожидающих подтверждениях вы получите уведомление.',
add: 'Новая автоматизация',
addHint: 'Или попросите ассистента WeKnora создать её',
paused: 'Приостановлена',
+ scheduleEnded: 'Завершено',
+ scheduleEndedHint: 'Время однократного запуска прошло. Запустите сейчас или измените время перед возобновлением.',
nextRunAt: 'Далее {time}',
- notScheduled: 'Не запланировано',
agentUnavailable: 'Агент недоступен',
- deleteTitle: 'Удалить автоматизацию',
+ runConfirm: 'Запустить «{name}» сейчас? Дополнительный запуск не изменит расписание.',
deleteBody: 'Текущий запуск будет остановлен, а запуски, беседы и постоянные разрешения «{name}» удалены. Это действие необратимо.',
fields: {
name: 'Название',
@@ -153,6 +155,9 @@ export default {
enabled: 'Включена',
},
editor: {
+ model: "Модель запуска",
+ modelHelp: "Используйте модель агента по умолчанию или выберите другую для этой автоматизации. Изменения применяются к последующим запускам.",
+ modelDefault: "Модель агента по умолчанию",
createTitle: 'Новая автоматизация',
editTitle: 'Изменить автоматизацию',
namePlaceholder: 'Например: ежедневная сводка базы знаний',
@@ -280,8 +285,6 @@ export default {
stop: 'Остановить',
},
detail: {
- overview: 'Обзор',
- lastRun: 'Последний запуск',
pausedBecause: 'Приостановлена: {reason}',
runs: 'Запуски',
noRuns: 'Запусков пока нет',
@@ -314,6 +317,20 @@ export default {
},
},
notifications: {
+ pending: "Требуют внимания",
+ history: "История уведомлений",
+ clearRead: "Удалить прочитанные",
+ clearReadConfirm: "Удалить прочитанные уведомления? История запусков, диалоги и ожидающие действия сохранятся.",
+ handle: "Открыть",
+ review: "Рассмотреть",
+ unreadCount: "Непрочитанных: {count}",
+ unread: "Не прочитано",
+ newItems: "Новые уведомления — обновить",
+ loadError: "Не удалось загрузить уведомления",
+ awaitingApproval: "Ожидается ваше одобрение",
+ awaitingAuthorization: "Ожидается авторизация",
+ awaitingReply: "Ожидается ваш ответ",
+
title: 'Уведомления',
markAllRead: 'Прочитать все',
pendingInvitations: 'Ожидающих приглашений: {count}',
diff --git a/frontend/src/i18n/locales/zh-CN.ts b/frontend/src/i18n/locales/zh-CN.ts
index 2203260ae..b41df4466 100755
--- a/frontend/src/i18n/locales/zh-CN.ts
+++ b/frontend/src/i18n/locales/zh-CN.ts
@@ -125,15 +125,17 @@ export default {
"historyNoOverrides": "无管理员修改",
},
automation: {
+ conversationNotice: "此会话由自动化任务运行,不能手动发送消息。请在上方处理待审批事项。",
title: '自动化',
description: '让智能体按计划以你的身份执行任务,结果和待审批事项会通知你。',
add: '新建自动化',
addHint: '也可以直接让 WeKnora 助手帮你创建',
paused: '已暂停',
+ scheduleEnded: '已结束',
+ scheduleEndedHint: '一次性计划已结束。可立即运行,或修改运行时间后恢复。',
nextRunAt: '下次 {time}',
- notScheduled: '未排程',
agentUnavailable: '智能体不可用',
- deleteTitle: '删除自动化',
+ runConfirm: '立即运行「{name}」?这将启动一次额外运行,不影响原有计划。',
deleteBody: '将停止进行中的运行,并删除「{name}」的运行记录、对话和长期授权。此操作无法撤销。',
fields: {
name: '名称',
@@ -153,6 +155,9 @@ export default {
enabled: '启用',
},
editor: {
+ model: "运行模型",
+ modelHelp: "默认沿用智能体的模型设置,也可以为此自动化单独指定。修改后用于后续运行。",
+ modelDefault: "跟随智能体默认模型",
createTitle: '新建自动化',
editTitle: '编辑自动化',
namePlaceholder: '例如:每日知识库周报',
@@ -280,8 +285,6 @@ export default {
stop: '停止',
},
detail: {
- overview: '概览',
- lastRun: '上次运行',
pausedBecause: '已暂停:{reason}',
runs: '运行记录',
noRuns: '还没有运行过',
@@ -314,6 +317,20 @@ export default {
},
},
notifications: {
+ pending: "待处理",
+ history: "通知记录",
+ clearRead: "清理已读",
+ clearReadConfirm: "清理已读通知?不会删除运行记录、对话或待处理事项。",
+ handle: "去处理",
+ review: "去审批",
+ unreadCount: "{count} 条未读",
+ unread: "未读",
+ newItems: "有新通知,点击刷新",
+ loadError: "通知加载失败",
+ awaitingApproval: "等待你确认操作",
+ awaitingAuthorization: "等待你完成授权",
+ awaitingReply: "等待你回复",
+
title: '通知',
markAllRead: '全部已读',
pendingInvitations: '{count} 个待处理邀请',
diff --git a/frontend/src/i18n/locales/zh-TW.ts b/frontend/src/i18n/locales/zh-TW.ts
index 7b769dd2d..e79ae7e38 100644
--- a/frontend/src/i18n/locales/zh-TW.ts
+++ b/frontend/src/i18n/locales/zh-TW.ts
@@ -125,15 +125,17 @@ export default {
"historyNoOverrides": "無管理員修改",
},
automation: {
+ conversationNotice: "此對話由自動化任務執行,無法手動傳送訊息。請在上方處理待審批事項。",
title: '自動化',
description: '讓智慧代理按排程以你的身分執行任務,結果與待審批事項會通知你。',
add: '新增自動化',
addHint: '也可以直接請 WeKnora 助手幫你建立',
paused: '已暫停',
+ scheduleEnded: '已結束',
+ scheduleEndedHint: '一次性排程已結束。可立即執行,或修改執行時間後恢復。',
nextRunAt: '下次 {time}',
- notScheduled: '未排程',
agentUnavailable: '智慧代理不可用',
- deleteTitle: '刪除自動化',
+ runConfirm: '立即執行「{name}」?這會啟動一次額外執行,不影響原有排程。',
deleteBody: '將停止進行中的執行,並刪除「{name}」的執行紀錄、對話與長期授權。此操作無法復原。',
fields: {
name: '名稱',
@@ -153,6 +155,9 @@ export default {
enabled: '啟用',
},
editor: {
+ model: "執行模型",
+ modelHelp: "預設沿用智慧體的模型設定,也可以為此自動化單獨指定。修改後用於後續執行。",
+ modelDefault: "跟隨智慧體預設模型",
createTitle: '新增自動化',
editTitle: '編輯自動化',
namePlaceholder: '例如:每日知識庫週報',
@@ -280,8 +285,6 @@ export default {
stop: '停止',
},
detail: {
- overview: '概覽',
- lastRun: '上次執行',
pausedBecause: '已暫停:{reason}',
runs: '執行紀錄',
noRuns: '還沒有執行過',
@@ -314,6 +317,20 @@ export default {
},
},
notifications: {
+ pending: "待處理",
+ history: "通知記錄",
+ clearRead: "清理已讀",
+ clearReadConfirm: "清理已讀通知?不會刪除執行記錄、對話或待處理事項。",
+ handle: "去處理",
+ review: "去審批",
+ unreadCount: "{count} 則未讀",
+ unread: "未讀",
+ newItems: "有新通知,點擊重新整理",
+ loadError: "通知載入失敗",
+ awaitingApproval: "等待你確認操作",
+ awaitingAuthorization: "等待你完成授權",
+ awaitingReply: "等待你回覆",
+
title: '通知',
markAllRead: '全部已讀',
pendingInvitations: '{count} 個待處理邀請',
diff --git a/frontend/src/utils/automationSchedule.test.ts b/frontend/src/utils/automationSchedule.test.ts
index aab280ab4..57559e302 100644
--- a/frontend/src/utils/automationSchedule.test.ts
+++ b/frontend/src/utils/automationSchedule.test.ts
@@ -3,6 +3,7 @@ import test from 'node:test'
import {
describeTrigger,
+ hasEndedOnceSchedule,
scheduleFormFromTrigger,
triggerFromScheduleForm,
wallClockToISO,
@@ -71,3 +72,13 @@ test('describeTrigger names the schedule', () => {
'automation.schedule.describe.custom{"expr":"*/10 9-17 * * *"}',
)
})
+
+test('only disabled one-shot schedules with no future occurrence have ended', () => {
+ const now = Date.parse('2026-10-20T08:00:00Z')
+ const once = (at: string, enabled = false) => ({ enabled, trigger: { type: 'once' as const, at } })
+ assert.equal(hasEndedOnceSchedule(once('2026-10-20T15:59:59+08:00'), now), true)
+ assert.equal(hasEndedOnceSchedule(once('2026-10-20T16:00:00+08:00'), now), true)
+ assert.equal(hasEndedOnceSchedule(once('2026-10-20T16:00:01+08:00'), now), false)
+ assert.equal(hasEndedOnceSchedule(once('2026-10-20T15:59:59+08:00', true), now), false)
+ assert.equal(hasEndedOnceSchedule({ enabled: false, trigger: { type: 'cron', expr: '0 9 * * *' } }, now), false)
+})
diff --git a/frontend/src/utils/automationSchedule.ts b/frontend/src/utils/automationSchedule.ts
index 28b5d4374..dd3b11ae0 100644
--- a/frontend/src/utils/automationSchedule.ts
+++ b/frontend/src/utils/automationSchedule.ts
@@ -1,9 +1,15 @@
-import type { AutomationTrigger } from '@/api/automation'
+import type { Automation, AutomationTrigger } from '@/api/automation'
// The editor offers a few schedule shapes and falls back to a raw cron
// expression for anything else. Cron here is the server's five-field form,
// minute first, evaluated in the trigger's timezone.
+/** An elapsed one-shot schedule has no future occurrence to resume. */
+export function hasEndedOnceSchedule(automation: Pick<Automation, 'enabled' | 'trigger'>, now = Date.now()): boolean {
+ return !automation.enabled && automation.trigger.type === 'once'
+ && Date.parse(automation.trigger.at || '') <= now
+}
+
export type ScheduleKind = 'hourly' | 'daily' | 'weekdays' | 'weekly' | 'monthly' | 'once' | 'custom'
export interface ScheduleForm {
diff --git a/frontend/src/utils/notificationPreview.test.ts b/frontend/src/utils/notificationPreview.test.ts
new file mode 100644
index 000000000..21a11a5c0
--- /dev/null
+++ b/frontend/src/utils/notificationPreview.test.ts
@@ -0,0 +1,16 @@
+import assert from 'node:assert/strict'
+import test from 'node:test'
+import { notificationPreview } from './notificationPreview.ts'
+
+test('notification excerpts preserve readable text without Markdown decoration', () => {
+ assert.equal(notificationPreview('**GitHub 热榜 · 2026年10月20日**\n\n**抓取状态:** 已成功读取 [GitHub Trending](https://github.com/trending)。'),
+ 'GitHub 热榜 · 2026年10月20日 抓取状态: 已成功读取 GitHub Trending。')
+ assert.equal(notificationPreview('# 今日简报\n- **第一项**\n- `second_item`\n\n> 备注'), '今日简报 第一项 second_item 备注')
+ assert.equal(notificationPreview('**尚未结束的标题…'), '尚未结束的标题…')
+ assert.equal(notificationPreview('2 * 3 = 6, snake_case'), '2 * 3 = 6, snake_case')
+})
+
+test('notification excerpts never render embedded HTML or image URLs', () => {
+ assert.equal(notificationPreview('结果 <img src="https://example.com/pixel"> **完成**'), '结果 完成')
+ assert.equal(notificationPreview('![示意图](https://example.com/image.png)'), '示意图')
+})
diff --git a/frontend/src/utils/notificationPreview.ts b/frontend/src/utils/notificationPreview.ts
new file mode 100644
index 000000000..24c4f1968
--- /dev/null
+++ b/frontend/src/utils/notificationPreview.ts
@@ -0,0 +1,33 @@
+import { marked, type Token, type Tokens } from 'marked'
+
+function plainText(tokens: Token[]): string {
+ return tokens.map(token => {
+ switch (token.type) {
+ case 'html': return ''
+ case 'space':
+ case 'br':
+ case 'hr': return ' '
+ case 'list': return (token as Tokens.List).items.map(item => plainText(item.tokens)).join(' ')
+ case 'table': {
+ const table = token as Tokens.Table
+ return [table.header, ...table.rows]
+ .map(row => row.map(cell => plainText(cell.tokens)).join(' ')).join(' ')
+ }
+ case 'paragraph':
+ case 'heading':
+ case 'blockquote': return plainText(token.tokens ?? []) + ' '
+ default:
+ if ('tokens' in token && token.tokens) return plainText(token.tokens)
+ return 'text' in token ? token.text : ''
+ }
+ }).join('')
+}
+
+/** Notification excerpts are plain text, including when the saved Markdown is truncated. */
+export function notificationPreview(source: string): string {
+ return plainText(marked.lexer(source))
+ .replace(/(^|\s)(\*\*|__|~~)(?=\S)/g, '$1')
+ .replace(/(\*\*|__|~~)(?=\s|$)/g, '')
+ .replace(/\s+/g, ' ')
+ .trim()
+}
diff --git a/frontend/src/views/automation/AutomationDetail.vue b/frontend/src/views/automation/AutomationDetail.vue
index 8464c0ebe..31a4e680c 100644
--- a/frontend/src/views/automation/AutomationDetail.vue
+++ b/frontend/src/views/automation/AutomationDetail.vue
@@ -1,148 +1,176 @@
<template>
- <SettingDrawer :visible="visible" :title="automation?.name || ''" icon="time" width="640px" :min-width="480"
- :max-width="960" storage-key="setting-drawer:width:automation-detail" class="automation-detail-drawer"
+ <SettingDrawer :visible="visible" :title="automation?.name || ''" icon="time" width="720px" :min-width="480"
+ :max-width="960" storage-key="setting-drawer:width:automation-detail" class="automation-detail-drawer" hide-footer
@update:visible="(v: boolean) => !v && close()">
+ <template #headerIcon><t-icon name="time" class="automation-detail__header-icon" /></template>
<template v-if="automation" #subtitle>
<span class="automation-detail__subtitle">
- <AutomationStatusTag v-if="!automation.enabled" status="paused" />
+ <t-tag v-if="hasEndedOnceSchedule(automation)" size="small" variant="light" :title="t('automation.scheduleEndedHint')">{{ t('automation.scheduleEnded') }}</t-tag>
+ <AutomationStatusTag v-else-if="!automation.enabled" status="paused" />
<span>{{ describeTrigger(automation.trigger, t, locale) }} · {{ automation.trigger.timezone || 'UTC' }}</span>
</span>
</template>
+ <template v-if="automation" #header-actions>
+ <div class="automation-detail__actions">
+ <t-popconfirm :content="t('automation.runConfirm', { name: automation.name })" theme="default" placement="bottom-right"
+ :confirm-btn="{ content: t('automation.actions.runNow'), theme: 'primary' }" :cancel-btn="t('common.cancel')"
+ :popup-props="{ zIndex: 2600, disabled: !!busy }" @confirm="runNow">
+ <button type="button" class="automation-detail__icon-btn" :disabled="!!busy" :aria-busy="busy === 'run'"
+ :title="t('automation.actions.runNow')" :aria-label="t('automation.actions.runNow')">
+ <t-loading v-if="busy === 'run'" size="14px" />
+ <ChatActionIcon v-else name="play" />
+ </button>
+ </t-popconfirm>
+ <button v-if="!hasEndedOnceSchedule(automation)" type="button" class="automation-detail__icon-btn" :disabled="!!busy" :aria-busy="busy === 'toggle'"
+ :title="automation.enabled ? t('automation.actions.pause') : t('automation.actions.resume')"
+ :aria-label="automation.enabled ? t('automation.actions.pause') : t('automation.actions.resume')" @click="toggle">
+ <t-loading v-if="busy === 'toggle'" size="14px" />
+ <ChatActionIcon v-else :name="automation.enabled ? 'pause' : 'resume'" />
+ </button>
+ <button type="button" class="automation-detail__icon-btn" :title="t('common.edit')"
+ :aria-label="t('common.edit')" @click="emit('edit', automation)">
+ <ChatActionIcon name="edit" />
+ </button>
+ </div>
+ </template>
+
<template v-if="automation">
<t-alert v-if="!automation.enabled && automation.paused_reason" theme="warning" class="automation-detail__alert"
:message="t('automation.detail.pausedBecause', { reason: automation.paused_reason })" />
-
- <section class="setting-drawer__section">
- <h4 class="setting-drawer__section-title">{{ t('automation.detail.overview') }}</h4>
- <dl class="automation-detail__fields">
- <div class="automation-detail__field">
- <dt>{{ t('automation.fields.nextRun') }}</dt>
- <dd>{{ automation.enabled && automation.next_run_at ? when(automation.next_run_at) : t('automation.notScheduled') }}</dd>
- </div>
- <div class="automation-detail__field">
- <dt>{{ t('automation.detail.lastRun') }}</dt>
- <dd class="automation-detail__inline">
- <template v-if="automation.last_run_at">
- {{ when(automation.last_run_at) }}
- <AutomationStatusTag v-if="automation.last_run_status" :status="automation.last_run_status" />
- </template>
- <template v-else>{{ t('automation.detail.noRuns') }}</template>
- </dd>
- </div>
- <div class="automation-detail__field">
- <dt>{{ t('automation.fields.agent') }}</dt>
- <dd>{{ agentName }}</dd>
- </div>
- <div class="automation-detail__field">
- <dt>{{ t('automation.fields.accessLevel') }}</dt>
- <dd>{{ t(`assistant.access.levels.${automation.access_level}.label`) }}</dd>
- </div>
- <div class="automation-detail__field">
- <dt>{{ t('automation.fields.sessionMode') }}</dt>
- <dd>{{ t(`automation.sessionMode.${automation.session_mode}`) }}</dd>
+ <section class="automation-detail__brief" :aria-label="t('automation.detail.task')">
+ <div class="automation-detail__brief-heading">
+ <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>
</div>
- </dl>
- </section>
-
- <section class="setting-drawer__section">
- <h4 class="setting-drawer__section-title">
- {{ t('automation.detail.task') }}
- <t-button v-if="instructionLong" size="small" variant="text" theme="primary" class="automation-detail__toggle"
- @click="instructionOpen = !instructionOpen">
- {{ instructionOpen ? t('common.collapse') : t('common.expand') }}
- </t-button>
- </h4>
- <p class="automation-detail__instruction" :class="{ 'is-clamped': instructionLong && !instructionOpen }">
- {{ automation.instruction }}
- </p>
+ <t-popup v-model:visible="grantsVisible" trigger="click" placement="bottom-right" :z-index="2600">
+ <button type="button" class="automation-detail__grants-trigger" :class="{ 'is-attention': candidates.length }"
+ :aria-expanded="grantsVisible">
+ <t-icon name="secured" size="14px" />
+ {{ t('automation.detail.grants') }}
+ <span v-if="candidates.length || grants.length" class="automation-detail__count"
+ :title="candidates.length ? t('automation.grants.candidates') : t('automation.grants.active')">
+ {{ candidates.length || grants.length }}
+ </span>
+ <t-icon name="chevron-down" size="12px" />
+ </button>
+ <template #content>
+ <div class="automation-detail__grants-panel" role="region" :aria-label="t('automation.detail.grants')">
+ <h3>{{ t('automation.detail.grants') }}</h3>
+ <p class="automation-detail__muted">{{ t('automation.grants.intro') }}</p>
+ <div v-if="grantsLoading" class="automation-detail__loading"><t-loading size="small" /></div>
+ <template v-else>
+ <ul v-if="grants.length" class="automation-detail__list">
+ <li v-for="grant in grants" :key="grant.id" class="automation-grant">
+ <span class="automation-grant__label">{{ grant.label || grant.grant_key }}</span>
+ <t-tag size="small" variant="light" :theme="grant.risk === 'destructive' ? 'danger' : 'warning'">
+ {{ t(`automation.risk.${grant.risk}`, grant.risk) }}
+ </t-tag>
+ <span v-if="grant.lapse" class="automation-grant__lapse">{{ t('automation.grants.lapsed') }}</span>
+ <t-link theme="danger" hover="color" class="automation-grant__action" @click="revoke(grant)">
+ {{ t('automation.grants.revoke') }}
+ </t-link>
+ </li>
+ </ul>
+ <template v-if="candidates.length">
+ <div class="automation-detail__subhead">{{ t('automation.grants.candidates') }}</div>
+ <ul class="automation-detail__list">
+ <li v-for="candidate in candidates" :key="candidate.prompt_id" class="automation-grant">
+ <span class="automation-grant__label">{{ candidate.label || candidate.tool }}</span>
+ <t-tag size="small" variant="light" :theme="candidate.risk === 'destructive' ? 'danger' : 'warning'">
+ {{ t(`automation.risk.${candidate.risk}`, candidate.risk) }}
+ </t-tag>
+ <span v-if="candidate.service_name" class="automation-grant__meta">{{ candidate.service_name }}</span>
+ <t-link theme="primary" hover="color" class="automation-grant__action" @click="allow(candidate)">
+ {{ t('automation.grants.allow') }}
+ </t-link>
+ </li>
+ </ul>
+ </template>
+ <p v-if="!grants.length && !candidates.length" class="automation-detail__muted">{{ t('automation.grants.none') }}</p>
+ </template>
+ </div>
+ </template>
+ </t-popup>
+ </div>
+ <div
+ ref="instructionScroller"
+ class="automation-detail__instruction-scroll"
+ :class="{ 'automation-detail__instruction-scroll--more': instructionHasMore }"
+ :style="{ maxHeight: instructionExpanded ? 'none' : `${INSTRUCTION_PREVIEW_HEIGHT}px` }"
+ @scroll="updateInstructionOverflow"
+ >
+ <p ref="instructionContent" class="automation-detail__instruction">{{ automation.instruction }}</p>
+ </div>
+ <button
+ v-if="instructionCanExpand"
+ type="button"
+ class="automation-detail__instruction-toggle"
+ :aria-label="t(instructionExpanded ? 'common.collapse' : 'common.expand')"
+ :title="t(instructionExpanded ? 'common.collapse' : 'common.expand')"
+ :aria-expanded="instructionExpanded"
+ @click="toggleInstruction"
+ >
+ <t-icon :name="instructionExpanded ? 'chevron-up' : 'chevron-down'" size="16px" />
+ </button>
</section>
- <section class="setting-drawer__section">
- <h4 class="setting-drawer__section-title">
- {{ t('automation.detail.runs') }}
- <span v-if="runsTotal" class="automation-detail__count">{{ runsTotal }}</span>
- </h4>
+ <section class="automation-detail__history" :aria-label="t('automation.detail.runs')">
+ <div class="automation-detail__history-header">
+ <h3 class="automation-detail__history-heading">
+ {{ t('automation.detail.runs') }}<span class="automation-detail__count">{{ runsTotal }}</span>
+ </h3>
+ <span v-if="automation.enabled && automation.next_run_at" class="automation-detail__next-run">
+ {{ t('automation.fields.nextRun') }}
+ <time :datetime="automation.next_run_at">{{ when(automation.next_run_at) }}</time>
+ </span>
+ </div>
<div v-if="runsLoading && !runs.length" class="automation-detail__loading"><t-loading size="small" /></div>
<p v-else-if="!runs.length" class="automation-detail__muted">{{ t('automation.detail.noRuns') }}</p>
- <ul v-else class="automation-detail__list">
- <li v-for="run in runs" :key="run.id" class="automation-run"
- :class="{ 'is-focused': run.id === focusRunId, 'is-link': !!run.session_id }"
- :role="run.session_id ? 'button' : undefined" :tabindex="run.session_id ? 0 : undefined"
- @click="run.session_id && openRun(run)"
- @keydown.enter="run.session_id && openRun(run)">
- <span class="automation-run__dot" :class="`is-${run.status}`" aria-hidden="true" />
- <div class="automation-run__body">
- <div class="automation-run__head">
- <span class="automation-run__time">{{ when(run.scheduled_at) }}</span>
- <span class="automation-run__status">{{ t(`automation.status.${run.status}`) }}</span>
- <span class="automation-run__meta">
- {{ t(`automation.runTrigger.${run.trigger_kind}`) }}<template v-if="duration(run)"> · {{ duration(run) }}</template>
- </span>
- <t-link v-if="cancellable(run)" theme="danger" hover="color" class="automation-run__stop"
- :disabled="run.cancel_requested" @click.stop="cancel(run)">
- {{ run.cancel_requested ? t('automation.detail.stopping') : t('automation.actions.stop') }}
- </t-link>
- </div>
- <p v-if="run.error" class="automation-run__text is-error">{{ run.error }}</p>
- <p v-else-if="run.answer" class="automation-run__text">{{ run.answer }}</p>
- </div>
- <t-icon v-if="run.session_id" name="chevron-right" size="16px" class="automation-run__chevron" />
- </li>
- </ul>
+ <div v-else class="automation-detail__timeline">
+ <section v-for="group in runGroups" :key="group.date" class="automation-detail__day">
+ <h5 class="automation-detail__date">{{ group.date }}</h5>
+ <ul class="automation-detail__runs">
+ <li v-for="run in group.runs" :key="run.id" class="automation-run" :class="{ 'is-focused': run.id === focusRunId }">
+ <span class="automation-run__marker"><AutomationStatusTag :status="run.status" icon-only /></span>
+ <div class="automation-run__body">
+ <div class="automation-run__head">
+ <time class="automation-run__time" :datetime="run.scheduled_at">{{ runTime(run.scheduled_at) }}</time>
+ <span class="automation-run__meta">
+ {{ t(`automation.runTrigger.${run.trigger_kind}`) }}<template v-if="duration(run)"> · {{ duration(run) }}</template>
+ </span>
+ <t-link v-if="cancellable(run)" theme="danger" hover="color" class="automation-run__stop"
+ :disabled="run.cancel_requested" @click="cancel(run)">
+ {{ run.cancel_requested ? t('automation.detail.stopping') : t('automation.actions.stop') }}
+ </t-link>
+ </div>
+ <component :is="run.session_id ? 'button' : 'div'" class="automation-run__result"
+ :type="run.session_id ? 'button' : undefined"
+ :aria-label="run.session_id ? `${when(run.scheduled_at)} · ${t('automation.actions.openConversation')}` : undefined"
+ @click="run.session_id && openRun(run)">
+ <p v-if="run.error" class="automation-run__text is-error">{{ run.error }}</p>
+ <p v-else-if="run.answer" class="automation-run__text">{{ run.answer }}</p>
+ <span v-else class="automation-detail__muted">{{ t(`automation.status.${run.status}`) }}</span>
+ <t-icon v-if="run.session_id" name="arrow-right-up" size="16px" class="automation-run__chevron" />
+ </component>
+ </div>
+ </li>
+ </ul>
+ </section>
+ </div>
<div v-if="runs.length < runsTotal" class="automation-detail__more">
<t-button size="small" variant="text" :loading="runsLoading" @click="loadRuns(false)">
{{ t('common.loadMore') }}
</t-button>
</div>
</section>
-
- <section class="setting-drawer__section">
- <h4 class="setting-drawer__section-title">{{ t('automation.detail.grants') }}</h4>
- <p class="automation-detail__muted">{{ t('automation.grants.intro') }}</p>
- <div v-if="grantsLoading" class="automation-detail__loading"><t-loading size="small" /></div>
- <template v-else>
- <ul v-if="grants.length" class="automation-detail__list">
- <li v-for="grant in grants" :key="grant.id" class="automation-grant">
- <span class="automation-grant__label">{{ grant.label || grant.grant_key }}</span>
- <t-tag size="small" variant="light" :theme="grant.risk === 'destructive' ? 'danger' : 'warning'">
- {{ t(`automation.risk.${grant.risk}`, grant.risk) }}
- </t-tag>
- <span v-if="grant.lapse" class="automation-grant__lapse">{{ t('automation.grants.lapsed') }}</span>
- <t-link theme="danger" hover="color" class="automation-grant__action" @click="revoke(grant)">
- {{ t('automation.grants.revoke') }}
- </t-link>
- </li>
- </ul>
- <template v-if="candidates.length">
- <div class="automation-detail__subhead">{{ t('automation.grants.candidates') }}</div>
- <ul class="automation-detail__list">
- <li v-for="candidate in candidates" :key="candidate.prompt_id" class="automation-grant">
- <span class="automation-grant__label">{{ candidate.label || candidate.tool }}</span>
- <t-tag size="small" variant="light" :theme="candidate.risk === 'destructive' ? 'danger' : 'warning'">
- {{ t(`automation.risk.${candidate.risk}`, candidate.risk) }}
- </t-tag>
- <span v-if="candidate.service_name" class="automation-grant__meta">{{ candidate.service_name }}</span>
- <t-link theme="primary" hover="color" class="automation-grant__action" @click="allow(candidate)">
- {{ t('automation.grants.allow') }}
- </t-link>
- </li>
- </ul>
- </template>
- <p v-if="!grants.length && !candidates.length" class="automation-detail__muted">{{ t('automation.grants.none') }}</p>
- </template>
- </section>
</template>
- <template v-if="automation" #footer-left>
- <t-button variant="outline" :loading="busy === 'toggle'" @click="toggle">
- {{ automation.enabled ? t('automation.actions.pause') : t('automation.actions.resume') }}
- </t-button>
- <t-button variant="outline" @click="emit('edit', automation)">{{ t('common.edit') }}</t-button>
- </template>
- <template v-if="automation" #footer-right>
- <t-button theme="primary" :loading="busy === 'run'" @click="runNow">{{ t('automation.actions.runNow') }}</t-button>
- </template>
</SettingDrawer>
</template>
@@ -166,9 +194,11 @@ import {
type AutomationGrantCandidate,
type AutomationRun,
} from '@/api/automation'
-import { describeTrigger, formatInZone } from '@/utils/automationSchedule'
+import { describeTrigger, formatInZone, hasEndedOnceSchedule } from '@/utils/automationSchedule'
+import { useAssistantDataChange } from '@/utils/assistantDataChange'
import SettingDrawer from '@/components/settings/SettingDrawer.vue'
import AutomationStatusTag from './AutomationStatusTag.vue'
+import ChatActionIcon from '@/components/ChatActionIcon.vue'
const props = defineProps<{
visible: boolean
@@ -187,7 +217,7 @@ const router = useRouter()
const PAGE = 20
const busy = ref<'' | 'run' | 'toggle'>('')
-const instructionOpen = ref(false)
+const grantsVisible = ref(false)
const runs = ref<AutomationRun[]>([])
const runsTotal = ref(0)
const runsPage = ref(0)
@@ -195,14 +225,60 @@ const runsLoading = ref(false)
const grants = ref<AutomationGrant[]>([])
const candidates = ref<AutomationGrantCandidate[]>([])
const grantsLoading = ref(false)
+const instructionScroller = ref<HTMLElement | null>(null)
+const instructionContent = ref<HTMLElement | null>(null)
+const instructionHasMore = ref(false)
+const instructionCanExpand = ref(false)
+const instructionExpanded = ref(false)
+const INSTRUCTION_PREVIEW_HEIGHT = 160
let poll: ReturnType<typeof setInterval> | undefined
+let detailVersion = 0
+let refreshRunsAfterLoad = false
-const instructionLong = computed(() => {
- const text = props.automation?.instruction ?? ''
- return text.length > 160 || text.split('\n').length > 4
-})
+function updateInstructionOverflow() {
+ const el = instructionScroller.value
+ instructionCanExpand.value = !!el && el.scrollHeight > INSTRUCTION_PREVIEW_HEIGHT + 1
+ instructionHasMore.value = !instructionExpanded.value && !!el && el.scrollHeight - el.clientHeight - el.scrollTop > 1
+}
+
+function toggleInstruction() {
+ instructionExpanded.value = !instructionExpanded.value
+ if (instructionScroller.value) instructionScroller.value.scrollTop = 0
+}
+
+watch(instructionExpanded, updateInstructionOverflow, { flush: 'post' })
+
+watch(
+ [instructionScroller, instructionContent, () => props.visible, () => props.automation?.instruction],
+ (_, __, onCleanup) => {
+ updateInstructionOverflow()
+ if (!props.visible || !instructionScroller.value || !instructionContent.value) return
+ const observer = new ResizeObserver(updateInstructionOverflow)
+ observer.observe(instructionScroller.value)
+ observer.observe(instructionContent.value)
+ onCleanup(() => observer.disconnect())
+ },
+ { flush: 'post' },
+)
const when = (iso: string | null) => formatInZone(iso, props.automation?.trigger.timezone, locale.value)
+const runDateFormatter = computed(() => new Intl.DateTimeFormat(locale.value, {
+ timeZone: props.automation?.trigger.timezone || 'UTC', year: 'numeric', month: 'long', day: 'numeric',
+}))
+const runTimeFormatter = computed(() => new Intl.DateTimeFormat(locale.value, {
+ timeZone: props.automation?.trigger.timezone || 'UTC', hour: '2-digit', minute: '2-digit', hour12: false,
+}))
+const runTime = (iso: string) => runTimeFormatter.value.format(new Date(iso))
+const runGroups = computed(() => {
+ const groups = new Map<string, AutomationRun[]>()
+ for (const run of runs.value) {
+ const date = runDateFormatter.value.format(new Date(run.scheduled_at))
+ const group = groups.get(date) ?? []
+ group.push(run)
+ groups.set(date, group)
+ }
+ return [...groups].map(([date, runs]) => ({ date, runs }))
+})
const cancellable = (run: AutomationRun) =>
run.status === 'queued' || run.status === 'running' || run.status === 'awaiting_approval'
@@ -221,28 +297,43 @@ function close() {
async function loadRuns(reset: boolean) {
const a = props.automation
if (!a) return
+ const version = detailVersion
runsLoading.value = true
try {
const page = reset ? 1 : runsPage.value + 1
const res = await listAutomationRuns(a.id, page, PAGE)
+ if (version !== detailVersion) return
const items = res.data ?? []
runs.value = reset ? items : [...runs.value, ...items]
runsTotal.value = res.total ?? runs.value.length
runsPage.value = page
} catch (e: any) {
- MessagePlugin.error(e?.message || t('common.operationFailed'))
+ if (version === detailVersion) MessagePlugin.error(e?.message || t('common.operationFailed'))
} finally {
- runsLoading.value = false
+ if (version === detailVersion) {
+ runsLoading.value = false
+ if (refreshRunsAfterLoad) {
+ refreshRunsAfterLoad = false
+ void refreshActive(true)
+ }
+ }
}
}
// Refresh the first page in place while a run is in flight, so its status
// moves without the user reopening the drawer.
-async function refreshActive() {
+async function refreshActive(force = false) {
const a = props.automation
- if (!a || runsLoading.value || !runs.value.some(cancellable)) return
+ if (!props.visible || !a) return
+ if (runsLoading.value) {
+ if (force) refreshRunsAfterLoad = true
+ return
+ }
+ if (!force && !runs.value.some(cancellable)) return
+ const version = detailVersion
try {
const res = await listAutomationRuns(a.id, 1, PAGE)
+ if (version !== detailVersion) return
const fresh = new Map((res.data ?? []).map((run) => [run.id, run]))
const known = new Set(runs.value.map((run) => run.id))
runs.value = [
@@ -255,6 +346,10 @@ async function refreshActive() {
}
}
+useAssistantDataChange(changes => {
+ if (changes.some(change => change.operation === 'automation.run_now')) void refreshActive(true)
+}, { areas: ['automation'] })
+
async function loadGrants() {
const a = props.automation
if (!a) return
@@ -270,10 +365,13 @@ async function loadGrants() {
}
}
-watch(() => [props.visible, props.automation?.id] as const, ([open, id]) => {
+watch([() => props.visible, () => props.automation?.id], ([open, id]) => {
+ ++detailVersion
+ refreshRunsAfterLoad = false
+ instructionExpanded.value = false
clearInterval(poll)
if (!open || !id) return
- instructionOpen.value = false
+ grantsVisible.value = false
runs.value = []
runsTotal.value = 0
grants.value = []
@@ -283,9 +381,13 @@ watch(() => [props.visible, props.automation?.id] as const, ([open, id]) => {
poll = setInterval(refreshActive, 5000)
}, { immediate: true })
-onBeforeUnmount(() => clearInterval(poll))
+onBeforeUnmount(() => {
+ ++detailVersion
+ clearInterval(poll)
+})
async function runNow() {
+ if (busy.value) return
const a = props.automation
if (!a) return
busy.value = 'run'
@@ -293,6 +395,7 @@ async function runNow() {
const res = await runAutomationNow(a.id)
MessagePlugin.success(t('automation.messages.queued'))
if (res.data) {
+ grantsVisible.value = false
runs.value = [res.data, ...runs.value]
runsTotal.value += 1
}
@@ -305,7 +408,11 @@ async function runNow() {
async function toggle() {
const a = props.automation
- if (!a) return
+ if (!a || busy.value) return
+ if (hasEndedOnceSchedule(a)) {
+ MessagePlugin.warning(t('automation.scheduleEndedHint'))
+ return
+ }
busy.value = 'toggle'
try {
const res = a.enabled ? await pauseAutomation(a.id) : await resumeAutomation(a.id)
@@ -334,6 +441,7 @@ async function cancel(run: AutomationRun) {
function allow(candidate: AutomationGrantCandidate) {
const a = props.automation
if (!a) return
+ grantsVisible.value = false
const destructive = candidate.risk === 'destructive'
const dialog = DialogPlugin.confirm({
header: t('automation.grants.allowTitle'),
@@ -365,6 +473,42 @@ async function revoke(grant: AutomationGrant) {
</script>
<style scoped lang="less">
+.automation-detail__actions {
+ display: flex;
+ align-items: center;
+ gap: 2px;
+}
+
+.automation-detail__icon-btn {
+ display: inline-flex;
+ align-items: center;
+ justify-content: center;
+ width: 28px;
+ height: 28px;
+ padding: 0;
+ border: 0;
+ border-radius: var(--app-radius-sm);
+ background: transparent;
+ color: color-mix(in srgb, var(--td-text-color-primary) 55%, transparent);
+ cursor: pointer;
+
+ &:hover:not(:disabled) {
+ color: var(--td-text-color-secondary);
+ background: color-mix(in srgb, var(--td-text-color-primary) 5%, transparent);
+ }
+ &:active:not(:disabled) {
+ background: color-mix(in srgb, var(--td-text-color-primary) 9%, transparent);
+ }
+ &:focus-visible {
+ outline: 2px solid var(--td-brand-color-focus);
+ outline-offset: 2px;
+ }
+ &:disabled {
+ cursor: not-allowed;
+ opacity: 0.4;
+ }
+}
+
.automation-detail__subtitle {
display: inline-flex;
align-items: center;
@@ -375,69 +519,163 @@ async function revoke(grant: AutomationGrant) {
margin-bottom: 12px;
}
-.automation-detail__fields {
- display: flex;
- flex-direction: column;
- gap: 10px;
- margin: 0;
+.automation-detail__header-icon {
+ color: var(--td-text-color-secondary);
}
-.automation-detail__field {
- display: grid;
- grid-template-columns: 96px minmax(0, 1fr);
- gap: 12px;
- align-items: baseline;
+:global(.automation-detail-drawer .setting-drawer__header-icon) {
+ color: var(--td-text-color-secondary);
+ background: var(--td-bg-color-secondarycontainer);
+}
- dt {
- color: var(--td-text-color-placeholder);
- font-size: var(--app-text-sm);
- line-height: 1.45;
- white-space: nowrap;
- }
+.automation-detail__next-run {
+ display: inline-flex;
+ flex-wrap: wrap;
+ align-items: center;
+ gap: 4px;
+ color: var(--td-text-color-secondary);
+ font-size: var(--app-text-xs);
+ line-height: 1.6;
- dd {
- margin: 0;
- color: var(--td-text-color-primary);
- font-size: var(--app-text-md);
- line-height: 1.55;
- overflow-wrap: anywhere;
- }
+ time { font-variant-numeric: tabular-nums; }
}
-.automation-detail__inline {
+.automation-detail__brief {
+ padding: 14px 16px 16px;
+ border-radius: var(--app-radius-lg);
+ background: color-mix(in srgb, var(--td-bg-color-secondarycontainer) 40%, var(--td-bg-color-container));
+}
+
+.automation-detail__brief-heading {
display: flex;
- align-items: center;
+ flex-wrap: wrap;
+ align-items: flex-start;
+ justify-content: space-between;
gap: 8px;
+ margin-bottom: 14px;
+
+ h3 { margin: 0; font-size: var(--app-text-sm); font-weight: 600; color: var(--td-text-color-primary); }
}
-.automation-detail__toggle {
- margin-left: auto;
+.automation-detail__brief-context { min-width: 0; }
+
+.automation-detail__grants-trigger {
+ display: inline-flex;
+ align-items: center;
+ gap: 5px;
+ padding: 4px 6px;
+ border: 0;
+ border-radius: var(--app-radius-sm);
+ background: transparent;
+ color: var(--td-text-color-secondary);
+ font: inherit;
+ font-size: var(--app-text-xs);
+ cursor: pointer;
+
+ &:hover, &[aria-expanded="true"] { color: var(--td-text-color-primary); background: var(--td-bg-color-container-hover); }
+ &:focus-visible { outline: 1px solid var(--td-brand-color-focus); outline-offset: 2px; }
+ &.is-attention { color: var(--td-warning-color); }
}
.automation-detail__count {
color: var(--td-text-color-placeholder);
+ font-size: var(--app-text-xs);
font-weight: 400;
+ font-variant-numeric: tabular-nums;
}
-.automation-detail__instruction {
+.is-attention .automation-detail__count { color: inherit; }
+
+.automation-detail__grants-panel {
+ display: flex;
+ flex-direction: column;
+ gap: 14px;
+ box-sizing: border-box;
+ width: min(380px, calc(100vw - 48px));
+ max-height: min(480px, 65vh);
+ overflow-y: auto;
+ padding: 12px;
+
+ h3 { margin: 0; font-size: var(--app-text-md); font-weight: 600; color: var(--td-text-color-primary); }
+}
+
+.automation-detail__execution {
+ display: flex;
+ flex-wrap: wrap;
+ align-items: center;
+ gap: 4px 0;
+ margin-top: 4px;
+ color: var(--td-text-color-secondary);
+ font-size: var(--app-text-xs);
+ line-height: 1.5;
+
+ > span + span::before { content: '·'; margin: 0 8px; color: var(--td-text-color-placeholder); }
+}
+
+.automation-detail__history { margin-top: 24px; }
+
+.automation-detail__history-header {
+ display: flex;
+ flex-wrap: wrap;
+ align-items: center;
+ justify-content: space-between;
+ gap: 8px 16px;
+ margin-bottom: 18px;
+}
+
+.automation-detail__history-heading {
+ display: flex;
+ align-items: center;
+ gap: 8px;
margin: 0;
- padding: 12px 14px;
- border: 1px solid var(--td-component-stroke);
+ color: var(--td-text-color-primary);
+ font-size: var(--app-text-md);
+ font-weight: 600;
+}
+
+.automation-detail__instruction-scroll {
+ box-sizing: border-box;
+ overflow-y: auto;
+ overscroll-behavior: contain;
+ scrollbar-width: thin;
+}
+
+.automation-detail__instruction-scroll--more {
+ mask-image: linear-gradient(to bottom, #000 calc(100% - 28px), transparent);
+}
+
+.automation-detail__instruction-toggle {
+ display: flex;
+ align-items: center;
+ justify-content: center;
+ width: 32px;
+ height: 24px;
+ margin: 6px auto -6px;
+ padding: 0;
+ border: 0;
border-radius: var(--app-radius-md);
- background: var(--td-bg-color-container);
+ background: transparent;
+ color: var(--td-text-color-secondary);
+ cursor: pointer;
+
+ &:hover {
+ color: var(--td-text-color-primary);
+ background: var(--td-bg-color-container);
+ }
+
+ &:focus-visible {
+ outline: 2px solid var(--td-text-color-secondary);
+ outline-offset: 2px;
+ }
+}
+
+.automation-detail__instruction {
+ margin: 0;
color: var(--td-text-color-primary);
font-size: var(--app-text-md);
line-height: 1.6;
white-space: pre-wrap;
overflow-wrap: anywhere;
-
- &.is-clamped {
- display: -webkit-box;
- -webkit-box-orient: vertical;
- -webkit-line-clamp: 4;
- line-clamp: 4;
- overflow: hidden;
- }
}
.automation-detail__muted {
@@ -470,43 +708,74 @@ async function revoke(grant: AutomationGrant) {
}
}
-.automation-run {
- display: flex;
- align-items: flex-start;
- gap: 10px;
- padding: 10px 14px;
+.automation-detail__day + .automation-detail__day { margin-top: 20px; }
- &.is-link {
- cursor: pointer;
+.automation-detail__date {
+ margin: 0 0 12px;
+ color: var(--td-text-color-secondary);
+ font-size: var(--app-text-sm);
+ font-weight: 500;
+}
- &:hover {
- background: var(--td-bg-color-container-hover);
- }
+.automation-detail__runs {
+ margin: 0;
+ padding: 0;
+ list-style: none;
+}
- &:focus-visible {
- outline: 2px solid var(--td-brand-color-focus);
- outline-offset: -2px;
- }
+.automation-run {
+ position: relative;
+ display: flex;
+ align-items: flex-start;
+ gap: 12px;
+ padding-bottom: 20px;
+
+ &::before {
+ content: '';
+ position: absolute;
+ left: 9px;
+ top: 24px;
+ bottom: 0;
+ width: 1px;
+ background: var(--td-component-stroke);
}
-
- &.is-focused {
- background: var(--td-bg-color-container-hover);
+ &:last-child { padding-bottom: 0; }
+ &:last-child::before { display: none; }
+ &.is-focused .automation-run__result {
+ background: color-mix(in srgb, var(--td-brand-color) 5%, var(--td-bg-color-container));
}
}
-.automation-run__dot {
- flex-shrink: 0;
- width: 6px;
- height: 6px;
- margin-top: 7px;
- border-radius: 50%;
- background: var(--td-text-color-placeholder);
+.automation-run__marker {
+ display: flex;
+ justify-content: center;
+ min-width: 20px;
+ padding-top: 2px;
+}
- &.is-succeeded { background: var(--td-success-color); }
- &.is-failed { background: var(--td-error-color); }
- &.is-running { background: var(--td-brand-color); }
- &.is-awaiting_approval,
- &.is-needs_attention { background: var(--td-warning-color); }
+.automation-run__result {
+ display: flex;
+ align-items: flex-start;
+ gap: 12px;
+ width: 100%;
+ box-sizing: border-box;
+ margin-top: 8px;
+ padding: 12px 14px;
+ border: 0;
+ border-radius: var(--app-radius-lg);
+ background: color-mix(in srgb, var(--td-bg-color-secondarycontainer) 40%, var(--td-bg-color-container));
+ text-align: left;
+ font: inherit;
+ transition: background-color var(--app-motion-fast) ease;
+}
+
+button.automation-run__result {
+ cursor: pointer;
+ &:hover { background: var(--td-bg-color-container-hover); }
+ &:focus-visible {
+ outline: 1px solid var(--td-brand-color-focus);
+ outline-offset: 2px;
+ }
}
.automation-run__body {
@@ -516,6 +785,7 @@ async function revoke(grant: AutomationGrant) {
.automation-run__head {
display: flex;
+ flex-wrap: wrap;
align-items: center;
gap: 8px;
min-width: 0;
@@ -527,12 +797,6 @@ async function revoke(grant: AutomationGrant) {
font-variant-numeric: tabular-nums;
}
-.automation-run__status {
- color: var(--td-text-color-secondary);
- font-size: var(--app-text-sm);
- white-space: nowrap;
-}
-
.automation-run__meta {
color: var(--td-text-color-placeholder);
font-size: var(--app-text-sm);
@@ -546,7 +810,8 @@ async function revoke(grant: AutomationGrant) {
.automation-run__chevron {
flex-shrink: 0;
- align-self: center;
+ margin-left: auto;
+ margin-top: 3px;
color: var(--td-text-color-placeholder);
}
@@ -555,10 +820,12 @@ async function revoke(grant: AutomationGrant) {
-webkit-box-orient: vertical;
-webkit-line-clamp: 3;
line-clamp: 3;
- margin: 6px 0 0;
+ flex: 1;
+ min-width: 0;
+ margin: 0;
overflow: hidden;
- color: var(--td-text-color-secondary);
- font-size: var(--app-text-sm);
+ color: var(--td-text-color-primary);
+ font-size: var(--app-text-md);
line-height: 1.6;
white-space: pre-wrap;
overflow-wrap: anywhere;
@@ -570,6 +837,7 @@ async function revoke(grant: AutomationGrant) {
.automation-grant {
display: flex;
+ flex-wrap: wrap;
align-items: center;
gap: 8px;
min-width: 0;
@@ -578,11 +846,10 @@ async function revoke(grant: AutomationGrant) {
.automation-grant__label {
min-width: 0;
- overflow: hidden;
+ flex-basis: 100%;
color: var(--td-text-color-primary);
- font-size: var(--app-text-md);
- text-overflow: ellipsis;
- white-space: nowrap;
+ font-size: var(--app-text-sm);
+ overflow-wrap: anywhere;
}
.automation-grant__meta,
diff --git a/frontend/src/views/automation/AutomationEditor.vue b/frontend/src/views/automation/AutomationEditor.vue
index 412ee9237..d274bd47c 100644
--- a/frontend/src/views/automation/AutomationEditor.vue
+++ b/frontend/src/views/automation/AutomationEditor.vue
@@ -30,6 +30,16 @@
</t-select>
</div>
</div>
+ <div class="setting-row">
+ <div class="setting-info">
+ <label>{{ t('automation.editor.model') }}</label>
+ <p class="desc">{{ t('automation.editor.modelHelp') }}</p>
+ </div>
+ <div class="setting-control">
+ <ModelSelector v-model:selected-model-id="form.model_id" model-type="KnowledgeQA" clearable
+ :placeholder="t('automation.editor.modelDefault')" @add-model="uiStore.openSettings('models', 'llm')" />
+ </div>
+ </div>
<div class="setting-row setting-row-vertical">
<div class="setting-info">
<label>{{ t('automation.fields.instruction') }}<span class="required">*</span></label>
@@ -59,11 +69,12 @@
<label>{{ t('automation.editor.frequency') }}<span class="required">*</span></label>
</div>
<div class="setting-control setting-control-full">
- <t-radio-group v-model="schedule.kind" variant="default-filled">
- <t-radio-button v-for="kind in KINDS" :key="kind" :value="kind">
- {{ t(`automation.schedule.kinds.${kind}`) }}
- </t-radio-button>
- </t-radio-group>
+ <div class="automation-editor__frequency" role="group" :aria-label="t('automation.editor.frequency')">
+ <label v-for="kind in KINDS" :key="kind" class="automation-editor__frequency-option">
+ <input v-model="schedule.kind" type="radio" name="automation-frequency" :value="kind" />
+ <span>{{ t(`automation.schedule.kinds.${kind}`) }}</span>
+ </label>
+ </div>
</div>
</div>
@@ -229,8 +240,11 @@
<p class="desc">{{ t('automation.editor.maxDurationDesc') }}</p>
</div>
<div class="setting-control">
- <t-input-number v-model="maxMinutes" :min="1" :max="240" theme="column"
- :suffix="t('automation.units.minutes')" />
+ <div class="automation-editor__number">
+ <t-input-number v-model="maxMinutes" :min="1" :max="240" :step="1" :decimal-places="0"
+ theme="row" :allow-input-over-limit="false" :aria-label="t('automation.fields.maxDuration')" />
+ <span>{{ t('automation.units.minutes') }}</span>
+ </div>
</div>
</div>
</div>
@@ -249,8 +263,11 @@
<p class="desc">{{ t('automation.editor.approvalTimeoutHelp') }}</p>
</div>
<div class="setting-control">
- <t-input-number v-model="approvalHours" :min="1" :max="168" theme="column"
- :suffix="t('automation.units.hours')" />
+ <div class="automation-editor__number">
+ <t-input-number v-model="approvalHours" :min="1" :max="168" :step="1" :decimal-places="0"
+ theme="row" :allow-input-over-limit="false" :aria-label="t('automation.fields.approvalTimeout')" />
+ <span>{{ t('automation.units.hours') }}</span>
+ </div>
</div>
</div>
<div class="setting-row">
@@ -267,9 +284,10 @@
</div>
<template #footer-note>
- <p v-if="previewRuns.length && !previewError" class="settings-footer-note">
- <t-icon name="time" class="settings-footer-note__icon" />
- <span><strong>{{ describeCurrent }}</strong>{{ t('automation.nextRunAt', { time: formatInZone(previewRuns[0], timezone, locale) }) }}</span>
+ <p v-if="previewRuns.length && !previewError" class="automation-editor__next-run">
+ <t-icon name="time" size="14px" />
+ <span>{{ t('automation.fields.nextRun') }}</span>
+ <time :datetime="previewRuns[0]">{{ formatInZone(previewRuns[0], timezone, locale) }}</time>
</p>
</template>
<template #footer>
@@ -298,7 +316,6 @@ import { ASSISTANT_ACCESS_LEVELS } from '@/api/assistant'
import {
browserTimezone,
defaultScheduleForm,
- describeTrigger,
formatInZone,
scheduleFormFromTrigger,
timezoneOptions,
@@ -307,6 +324,8 @@ import {
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: boolean
@@ -318,6 +337,7 @@ const props = defineProps<{
const emit = defineEmits<{ 'update:visible': [value: boolean]; saved: [value: Automation] }>()
const { t, locale } = useI18n()
+const uiStore = useUIStore()
type Section = 'basic' | 'schedule' | 'execution' | 'notify'
@@ -349,6 +369,7 @@ const navGroups = computed(() => [
const blank = (): Required<Omit<AutomationInput, 'trigger' | 'limits' | 'description'>> => ({
name: '',
agent_id: props.defaultAgentId,
+ model_id: '',
instruction: '',
session_mode: 'per_run',
carry_last_result: false,
@@ -377,7 +398,10 @@ const agentOptions = computed(() => {
const approvalHours = computed({
get: () => Math.max(1, Math.round(form.approval_timeout_minutes / 60)),
- set: (v: number) => { form.approval_timeout_minutes = Math.max(1, Number(v) || 1) * 60 },
+ set: (v: number | undefined) => {
+ if (v === undefined || !Number.isFinite(v)) return
+ form.approval_timeout_minutes = Math.min(168, Math.max(1, Math.round(v))) * 60
+ },
})
const clock = computed({
@@ -390,7 +414,6 @@ const clock = computed({
})
const trigger = computed(() => triggerFromScheduleForm(schedule, timezone.value))
-const describeCurrent = computed(() => (trigger.value ? `${describeTrigger(trigger.value, t, locale.value)} · ` : ''))
function close() {
emit('update:visible', false)
@@ -414,6 +437,7 @@ watch(() => props.visible, (open) => {
Object.assign(form, {
name: a.name,
agent_id: a.agent_id,
+ model_id: a.model_id || '',
instruction: a.instruction,
session_mode: a.session_mode,
carry_last_result: a.carry_last_result,
@@ -497,6 +521,23 @@ async function save() {
</script>
<style scoped lang="less">
+.automation-editor__next-run {
+ display: flex;
+ flex: 1;
+ flex-wrap: wrap;
+ align-items: center;
+ gap: 4px 6px;
+ min-width: 0;
+ margin: 0 auto 0 0;
+ color: var(--td-text-color-secondary);
+ font-size: var(--app-text-xs);
+ line-height: 1.6;
+
+ > .t-icon { flex-shrink: 0; }
+ > span { white-space: nowrap; }
+ time { font-variant-numeric: tabular-nums; }
+}
+
.content-wrapper {
flex: 1;
overflow-y: auto;
@@ -625,6 +666,62 @@ async function save() {
}
}
+.automation-editor__frequency {
+ display: flex;
+ flex-wrap: wrap;
+ gap: 8px;
+}
+
+.automation-editor__frequency-option {
+ position: relative;
+ cursor: pointer;
+
+ input {
+ position: absolute;
+ inset: 0;
+ width: 100%;
+ height: 100%;
+ margin: 0;
+ opacity: 0;
+ cursor: pointer;
+ }
+
+ span {
+ display: block;
+ padding: 8px 16px;
+ border: 1px solid var(--td-component-stroke);
+ border-radius: var(--app-radius-pill);
+ color: var(--td-text-color-secondary);
+ font-size: var(--app-text-base);
+ transition: background-color var(--app-motion-fast) ease, border-color var(--app-motion-fast) ease;
+ }
+
+ &:hover span { background: var(--td-bg-color-container-hover); }
+ input:checked + span {
+ color: var(--td-brand-color);
+ border-color: color-mix(in srgb, var(--td-brand-color) 40%, var(--td-component-stroke));
+ background: color-mix(in srgb, var(--td-brand-color) 7%, var(--td-bg-color-container));
+ font-weight: 500;
+ }
+ input:focus-visible + span {
+ outline: 2px solid var(--td-brand-color-focus);
+ outline-offset: 3px;
+ }
+}
+
+.automation-editor__number {
+ display: flex;
+ align-items: center;
+ gap: 10px;
+ color: var(--td-text-color-secondary);
+ white-space: nowrap;
+
+ :deep(.t-input-number) {
+ width: 160px;
+ flex: none;
+ }
+}
+
.automation-editor__days {
flex-wrap: wrap;
justify-content: flex-end;
diff --git a/frontend/src/views/automation/AutomationList.vue b/frontend/src/views/automation/AutomationList.vue
index ab712f48c..e4fabca09 100644
--- a/frontend/src/views/automation/AutomationList.vue
+++ b/frontend/src/views/automation/AutomationList.vue
@@ -36,20 +36,28 @@
<div class="automation-card__badge" aria-hidden="true"><t-icon name="time" size="14px" /></div>
<h3 class="automation-card__title" :title="item.name">{{ item.name }}</h3>
<div class="automation-card__actions">
- <button type="button" class="automation-card__icon-btn" :title="t('automation.actions.runNow')"
- :aria-label="`${item.name} · ${t('automation.actions.runNow')}`" :disabled="busy.has(item.id)"
- @click="runNow(item)">
- <t-icon name="play-circle" size="14px" />
- </button>
+ <t-popconfirm :content="t('automation.runConfirm', { name: item.name })"
+ :confirm-btn="{ content: t('automation.actions.runNow'), theme: 'primary' }"
+ :cancel-btn="t('common.cancel')" theme="default" placement="bottom"
+ :popup-props="{ disabled: busy.has(item.id) }" @confirm="runNow(item)">
+ <button type="button" class="automation-card__icon-btn" :title="t('automation.actions.runNow')"
+ :aria-label="`${item.name} · ${t('automation.actions.runNow')}`" :disabled="busy.has(item.id)">
+ <ChatActionIcon name="play" />
+ </button>
+ </t-popconfirm>
<button type="button" class="automation-card__icon-btn" :title="t('common.edit')"
:aria-label="`${item.name} · ${t('common.edit')}`" @click="openEditor(item)">
- <t-icon name="edit" size="14px" />
- </button>
- <button type="button" class="automation-card__icon-btn automation-card__icon-btn--danger"
- :title="t('common.delete')" :aria-label="`${item.name} · ${t('common.delete')}`"
- :disabled="busy.has(item.id)" @click="remove(item)">
- <t-icon name="delete" size="14px" />
+ <ChatActionIcon name="edit" />
</button>
+ <t-popconfirm :content="t('automation.deleteBody', { name: item.name })"
+ :confirm-btn="{ content: t('common.delete'), theme: 'danger' }"
+ :cancel-btn="t('common.cancel')" theme="danger" placement="bottom"
+ :popup-props="{ disabled: busy.has(item.id) }" @confirm="remove(item)">
+ <button type="button" class="automation-card__icon-btn" :title="t('common.delete')"
+ :aria-label="`${item.name} · ${t('common.delete')}`" :disabled="busy.has(item.id)">
+ <ChatActionIcon name="delete" />
+ </button>
+ </t-popconfirm>
</div>
</div>
<p class="automation-card__schedule">{{ describeTrigger(item.trigger, t, locale) }}</p>
@@ -64,7 +72,10 @@
</span>
<AutomationStatusTag :status="item.last_run_status" />
</div>
- <button type="button" role="switch" class="automation-card__status" :class="{ 'is-enabled': item.enabled }"
+ <span v-if="hasEndedOnceSchedule(item)" class="automation-card__status is-ended" :title="t('automation.scheduleEndedHint')">
+ {{ t('automation.scheduleEnded') }}
+ </span>
+ <button v-else type="button" role="switch" class="automation-card__status" :class="{ 'is-enabled': item.enabled }"
:aria-checked="item.enabled" :aria-label="`${item.name} · ${t('automation.fields.enabled')}`"
:disabled="busy.has(item.id)" @click="toggle(item)">
<t-loading v-if="busy.has(item.id)" size="12px" />
@@ -89,10 +100,10 @@
</template>
<script setup lang="ts">
-import { computed, onMounted, ref, watch } from 'vue'
+import { computed, onBeforeUnmount, onMounted, ref, watch } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import { useI18n } from 'vue-i18n'
-import { DialogPlugin, MessagePlugin } from 'tdesign-vue-next'
+import { MessagePlugin } from 'tdesign-vue-next'
import { BUILTIN_WEKNORA_ASSISTANT_ID } from '@/api/agent'
import {
deleteAutomation,
@@ -104,10 +115,12 @@ import {
type Automation,
} from '@/api/automation'
import { useAuthStore } from '@/stores/auth'
-import { describeTrigger, formatInZone } from '@/utils/automationSchedule'
+import { describeTrigger, formatInZone, hasEndedOnceSchedule } from '@/utils/automationSchedule'
+import { useAssistantDataChange } from '@/utils/assistantDataChange'
import AutomationEditor from './AutomationEditor.vue'
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'
@@ -127,6 +140,7 @@ const editing = ref<Automation | null>(null)
const detailVisible = ref(false)
const detail = ref<Automation | null>(null)
const focusRunId = ref('')
+let loadVersion = 0
const filtered = computed(() => {
const q = query.value.trim().toLowerCase()
@@ -139,16 +153,29 @@ const agentName = (id: string) =>
agents.value.find((a) => a.id === id)?.name ?? t('automation.agentUnavailable')
async function load() {
+ const version = ++loadVersion
try {
const res = await listAutomations()
+ if (version !== loadVersion) return
automations.value = res.data ?? []
+ if (detail.value) {
+ const fresh = automations.value.find(item => item.id === detail.value?.id)
+ if (fresh) detail.value = fresh
+ else {
+ detailVisible.value = false
+ detail.value = null
+ }
+ }
} catch (e: any) {
- MessagePlugin.error(e?.message || t('common.operationFailed'))
+ if (version === loadVersion) MessagePlugin.error(e?.message || t('common.operationFailed'))
} finally {
- loading.value = false
+ if (version === loadVersion) loading.value = false
}
}
+useAssistantDataChange(() => { void load() }, { areas: ['automation'] })
+onBeforeUnmount(() => { ++loadVersion })
+
async function loadAgents() {
agentsLoading.value = true
try {
@@ -212,6 +239,11 @@ watch(detailVisible, (open) => {
})
async function toggle(item: Automation) {
+ if (busy.value.has(item.id)) return
+ if (hasEndedOnceSchedule(item)) {
+ MessagePlugin.warning(t('automation.scheduleEndedHint'))
+ return
+ }
busy.value.add(item.id)
try {
const res = item.enabled ? await pauseAutomation(item.id) : await resumeAutomation(item.id)
@@ -224,6 +256,7 @@ async function toggle(item: Automation) {
}
async function runNow(item: Automation) {
+ if (busy.value.has(item.id)) return
busy.value.add(item.id)
try {
const res = await runAutomationNow(item.id)
@@ -236,27 +269,19 @@ async function runNow(item: Automation) {
}
}
-function remove(item: Automation) {
- const dialog = DialogPlugin.confirm({
- header: t('automation.deleteTitle'),
- body: t('automation.deleteBody', { name: item.name }),
- theme: 'danger',
- confirmBtn: { content: t('common.delete'), theme: 'danger' },
- onConfirm: async () => {
- dialog.hide()
- busy.value.add(item.id)
- try {
- await deleteAutomation(item.id)
- automations.value = automations.value.filter((a) => a.id !== item.id)
- if (detail.value?.id === item.id) detailVisible.value = false
- MessagePlugin.success(t('common.deleteSuccess'))
- } catch (e: any) {
- MessagePlugin.error(e?.message || t('common.deleteFailed'))
- } finally {
- busy.value.delete(item.id)
- }
- },
- })
+async function remove(item: Automation) {
+ if (busy.value.has(item.id)) return
+ busy.value.add(item.id)
+ try {
+ await deleteAutomation(item.id)
+ automations.value = automations.value.filter((a) => a.id !== item.id)
+ if (detail.value?.id === item.id) detailVisible.value = false
+ MessagePlugin.success(t('common.deleteSuccess'))
+ } catch (e: any) {
+ MessagePlugin.error(e?.message || t('common.deleteFailed'))
+ } finally {
+ busy.value.delete(item.id)
+ }
}
onMounted(async () => {
@@ -308,7 +333,12 @@ onMounted(async () => {
}
.automation-page__search {
- width: 240px;
+ width: 260px;
+ max-width: 100%;
+
+ :deep(.t-input) {
+ border-radius: var(--app-radius-sm);
+ }
}
.automation-page__add.t-button {
@@ -321,7 +351,12 @@ onMounted(async () => {
color: var(--td-text-color-primary);
:deep(.t-icon) {
- color: var(--td-brand-color);
+ color: var(--td-text-color-secondary);
+ }
+
+ &:hover {
+ background: var(--td-bg-color-container-hover);
+ border-color: var(--td-component-stroke);
}
}
@@ -367,10 +402,9 @@ onMounted(async () => {
border: 1px solid var(--td-component-stroke);
border-radius: var(--app-radius-md);
background: var(--td-bg-color-container);
- transition: border-color var(--app-motion-base) ease, box-shadow var(--app-motion-base) ease;
+ transition: background-color var(--app-motion-base) ease, box-shadow var(--app-motion-base) ease;
&:hover:not(.automation-card--add) {
- border-color: color-mix(in srgb, var(--td-brand-color) 40%, var(--td-component-stroke));
box-shadow: 0 3px 12px color-mix(in srgb, var(--td-text-color-primary) 6%, transparent);
}
@@ -392,9 +426,10 @@ onMounted(async () => {
&:hover,
&:focus-visible {
- color: var(--td-brand-color);
- border-color: var(--td-brand-color);
- background: color-mix(in srgb, var(--td-brand-color) 6%, transparent);
+ color: var(--td-text-color-primary);
+ border-color: var(--td-component-border);
+ background: color-mix(in srgb, var(--td-bg-color-secondarycontainer) 15%, var(--td-bg-color-container));
+ box-shadow: 0 3px 12px color-mix(in srgb, var(--td-text-color-primary) 5%, transparent);
}
&__icon {
@@ -474,23 +509,22 @@ onMounted(async () => {
display: inline-flex;
align-items: center;
justify-content: center;
- width: 24px;
- height: 24px;
+ width: 28px;
+ height: 28px;
padding: 0;
border: 0;
border-radius: var(--app-radius-sm);
background: none;
- color: var(--td-text-color-placeholder);
+ color: color-mix(in srgb, var(--td-text-color-primary) 55%, transparent);
cursor: pointer;
&:hover:not(:disabled) {
- color: var(--td-text-color-primary);
- background: var(--td-bg-color-container-hover);
+ color: var(--td-text-color-secondary);
+ background: color-mix(in srgb, var(--td-text-color-primary) 5%, transparent);
}
- &--danger:hover:not(:disabled) {
- color: var(--td-error-color);
- background: color-mix(in srgb, var(--td-error-color) 8%, transparent);
+ &:active:not(:disabled) {
+ background: color-mix(in srgb, var(--td-text-color-primary) 9%, transparent);
}
&:disabled {
@@ -550,7 +584,9 @@ onMounted(async () => {
color: var(--td-success-color);
}
- &:hover:not(:disabled) {
+ &.is-ended { cursor: default; }
+
+ &:hover:not(:disabled):not(.is-ended) {
background: var(--td-bg-color-container-hover);
}
@@ -568,7 +604,7 @@ onMounted(async () => {
.automation-card button:focus-visible,
.automation-card--add:focus-visible {
- outline: 2px solid var(--td-brand-color);
+ outline: 2px solid var(--td-text-color-secondary);
outline-offset: -2px;
}
</style>
diff --git a/frontend/src/views/automation/AutomationStatusTag.vue b/frontend/src/views/automation/AutomationStatusTag.vue
index 2413900f7..a8ef5189b 100644
--- a/frontend/src/views/automation/AutomationStatusTag.vue
+++ b/frontend/src/views/automation/AutomationStatusTag.vue
@@ -1,5 +1,9 @@
<template>
- <t-tag v-if="status" size="small" variant="light" :theme="theme">{{ t(`automation.status.${status}`) }}</t-tag>
+ <span v-if="status && (status === 'succeeded' || iconOnly)" class="automation-status-icon" :class="`is-${status}`" role="img"
+ :aria-label="t(`automation.status.${status}`)" :title="t(`automation.status.${status}`)">
+ <t-icon :name="ICONS[status] || 'time'" size="16px" />
+ </span>
+ <t-tag v-else-if="status" size="small" variant="light" :theme="theme">{{ t(`automation.status.${status}`) }}</t-tag>
</template>
<script setup lang="ts">
@@ -7,9 +11,15 @@ import { computed } from 'vue'
import { useI18n } from 'vue-i18n'
import type { AutomationRunStatus } from '@/api/automation'
-const props = defineProps<{ status: AutomationRunStatus | 'paused' | '' }>()
+const props = defineProps<{ status: AutomationRunStatus | 'paused' | ''; iconOnly?: boolean }>()
const { t } = useI18n()
+const ICONS: Record<string, string> = {
+ succeeded: 'check-circle', failed: 'error-circle', running: 'loading', queued: 'time',
+ awaiting_approval: 'secured', needs_attention: 'error-circle', cancelled: 'close-circle',
+ skipped: 'jump', paused: 'pause-circle',
+}
+
const THEMES: Record<string, 'default' | 'primary' | 'success' | 'warning' | 'danger'> = {
queued: 'default',
running: 'primary',
@@ -24,3 +34,17 @@ const THEMES: Record<string, 'default' | 'primary' | 'success' | 'warning' | 'da
const theme = computed(() => THEMES[props.status] ?? 'default')
</script>
+
+<style scoped lang="less">
+.automation-status-icon {
+ display: inline-flex;
+ flex-shrink: 0;
+ align-items: center;
+ color: var(--td-text-color-secondary);
+
+ &.is-succeeded { color: var(--td-success-color); }
+ &.is-running { color: var(--td-brand-color); }
+ &.is-failed { color: var(--td-error-color); }
+ &.is-awaiting_approval, &.is-needs_attention { color: var(--td-warning-color); }
+}
+</style>
diff --git a/frontend/src/views/automation/automationInteractions.test.ts b/frontend/src/views/automation/automationInteractions.test.ts
new file mode 100644
index 000000000..961006fce
--- /dev/null
+++ b/frontend/src/views/automation/automationInteractions.test.ts
@@ -0,0 +1,347 @@
+import assert from 'node:assert/strict'
+import { readFileSync } from 'node:fs'
+import { createRequire } from 'node:module'
+import test, { type TestContext } from 'node:test'
+import { compileScript, compileTemplate, parse } from '@vue/compiler-sfc'
+import * as vue from 'vue'
+import { change, fixture, flush } from '../../test-utils/vueFixture.ts'
+import * as schedule from '../../utils/automationSchedule.ts'
+
+const require = createRequire(import.meta.url)
+const useInputNumber = require('tdesign-vue-next/cjs/input-number/hooks/useInputNumber.js').default
+const numberProps = require('tdesign-vue-next/cjs/input-number/props.js').default
+
+const automation = {
+ id: 'automation-1', name: 'Reminder', instruction: 'Take a break', agent_id: 'assistant',
+ 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',
+ carry_last_result: false, misfire_policy: 'skip', overlap_policy: 'skip', notify_on_success: false,
+}
+
+function setup(t: TestContext, file: string, api: Record<string, unknown>, props: Record<string, unknown>) {
+ const f = fixture(t)
+ const url = new URL(file, import.meta.url)
+ const page = f.component(url, {
+ 'vue-i18n': { useI18n: () => ({ t: (key: string) => key, locale: vue.ref('en-US') }) },
+ '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)
+ const { descriptor } = parse(readFileSync(url, 'utf8'))
+ const script = compileScript(descriptor, { id: 'automation-interactions' })
+ const compiled = compileTemplate({
+ source: descriptor.template!.content, filename: url.pathname, id: 'automation-interactions',
+ compilerOptions: { bindingMetadata: script.bindings },
+ })
+ assert.deepEqual(compiled.errors, [])
+ const { render } = f.evaluate(compiled.code, {
+ vue: { ...vue, resolveComponent: (name: string) => name === 't-popup' ? { name } : name, resolveDynamicComponent: (name: string) => name,
+ withCtx: (fn: unknown) => fn, withDirectives: (node: unknown) => node },
+ })
+ return { ...page, mount: f.mount, emit: f.emit, render: () => render(page.vm, [], props, page.vm, {}, {}) }
+}
+
+function nodes(node: any): any[] {
+ if (!node || typeof node !== 'object') return []
+ if (Array.isArray(node)) return node.flatMap(nodes)
+ const children = node.children
+ return [node, ...(Array.isArray(children) ? nodes(children)
+ : children && typeof children === 'object'
+ ? Object.values(children).flatMap(slot => typeof slot === 'function' ? nodes(slot()) : []) : [])]
+}
+
+test('assistant mutations refresh the automation list and open detail without replacing an editor draft', async t => {
+ let items = [{ ...automation }]
+ let calls = 0
+ const { vm, emit, close } = setup(t, './AutomationList.vue', {
+ listAutomations: async () => { calls++; return { data: items } },
+ }, {})
+ await flush()
+ vm.openDetail(vm.automations[0])
+ vm.query = 'Reminder'
+ vm.editing = { ...automation, name: 'Unsaved draft' }
+ vm.editorVisible = true
+ items = [{ ...automation, name: 'Updated reminder', enabled: false }, { ...automation, id: 'new' }]
+ emit(change('agent.update'))
+ t.mock.timers.tick(300)
+ assert.equal(calls, 1)
+ emit(change('automation.create'))
+ emit(change('automation.update'))
+ emit(change('automation.pause'))
+ t.mock.timers.tick(300)
+ await flush()
+ assert.equal(calls, 2, 'one request per burst')
+ assert.equal(vm.automations.length, 2)
+ assert.equal(vm.detail.name, 'Updated reminder')
+ assert.equal(vm.detail.enabled, false)
+ assert.equal(vm.detailVisible, true)
+ assert.equal(vm.query, 'Reminder')
+ assert.equal(vm.editing.name, 'Unsaved draft')
+ assert.equal(vm.editorVisible, true)
+ items = []
+ emit(change('automation.delete'))
+ t.mock.timers.tick(300)
+ await flush()
+ assert.equal(vm.detailVisible, false)
+ assert.equal(vm.detail, null)
+ close()
+ emit(change('automation.create'))
+ t.mock.timers.tick(300)
+ assert.equal(calls, 3, 'unmounted pages unsubscribe')
+})
+
+test('a stale automation list response cannot overwrite a newer assistant refresh', async t => {
+ const requests: Array<(result: unknown) => void> = []
+ const { vm, emit } = setup(t, './AutomationList.vue', {
+ listAutomations: () => new Promise(resolve => requests.push(resolve)),
+ }, {})
+ emit(change('automation.update'))
+ t.mock.timers.tick(300)
+ assert.equal(requests.length, 2)
+ requests[1]({ data: [{ ...automation, name: 'Fresh' }] })
+ await flush()
+ requests[0]({ data: [{ ...automation, name: 'Stale' }] })
+ await flush()
+ assert.equal(vm.automations[0].name, 'Fresh')
+})
+
+test('assistant run-now refreshes idle history after any in-flight load and preserves earlier pages', async t => {
+ let first!: (value: unknown) => void
+ let calls = 0
+ const oldRun = { id: 'old', status: 'succeeded', scheduled_at: '2026-10-20T10:00:00Z' }
+ const newRun = { id: 'new', status: 'queued', scheduled_at: '2026-10-20T11:00:00Z' }
+ const { vm, emit } = setup(t, './AutomationDetail.vue', {
+ listAutomationRuns: () => ++calls === 1 ? new Promise(resolve => { first = resolve })
+ : Promise.resolve({ data: [newRun, oldRun], total: 3 }),
+ listAutomationGrants: async () => ({ data: [] }),
+ listAutomationGrantCandidates: async () => ({ data: [] }),
+ }, { visible: true, automation, agentName: 'Assistant' })
+ emit(change('automation.run_now'))
+ t.mock.timers.tick(300)
+ assert.equal(calls, 1, 'wait for the initial page before merging newer runs')
+ first({ data: [oldRun, { ...oldRun, id: 'earlier' }], total: 2 })
+ await flush()
+ assert.equal(calls, 2)
+ assert.deepEqual(Array.from(vm.runs, (run: any) => run.id), ['new', 'old', 'earlier'])
+ assert.equal(vm.runsTotal, 3)
+ vm.instructionExpanded = true
+ vm.$.props.automation = { ...automation, name: 'Updated name' }
+ await vue.nextTick()
+ assert.equal(calls, 2, 'refreshing the same automation does not reset loaded history')
+ assert.equal(vm.instructionExpanded, true)
+ vm.$.props.visible = false
+ await vue.nextTick()
+ emit(change('automation.run_now'))
+ t.mock.timers.tick(300)
+ assert.equal(calls, 2, 'closed detail does not fetch history')
+})
+
+test('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' })
+ const scroller = vue.markRaw({ scrollHeight: 320, clientHeight: 160, scrollTop: 0 })
+ vm.instructionScroller = scroller
+ await vue.nextTick()
+ const scrollNode = () => nodes(render()).find(node =>
+ String(node.props?.class).includes('automation-detail__instruction-scroll'))
+ const toggle = () => nodes(render()).find(node =>
+ node.props?.class === 'automation-detail__instruction-toggle')
+ assert.equal(vm.instructionHasMore, true)
+ assert.match(scrollNode().props.class, /instruction-scroll--more/)
+ assert.equal(toggle().props['aria-expanded'], false)
+ toggle().props.onClick()
+ await vue.nextTick()
+ assert.equal(scrollNode().props.style.maxHeight, 'none')
+ assert.equal(vm.instructionHasMore, false, 'expanded text is not faded')
+ assert.equal(toggle().props['aria-expanded'], true)
+ toggle().props.onClick()
+ await vue.nextTick()
+ assert.equal(scrollNode().props.style.maxHeight, '160px')
+ assert.equal(vm.instructionHasMore, true)
+
+ scroller.scrollTop = 160
+ scrollNode().props.onScroll()
+ assert.equal(vm.instructionHasMore, false, 'the last line is fully visible at the bottom')
+ assert.doesNotMatch(scrollNode().props.class, /instruction-scroll--more/)
+
+ scroller.scrollTop = 50
+ scrollNode().props.onScroll()
+ assert.equal(vm.instructionHasMore, true)
+ scroller.scrollHeight = 100
+ scroller.scrollTop = 0
+ vm.updateInstructionOverflow()
+ assert.equal(vm.instructionHasMore, false, 'short content has no fade')
+ assert.equal(toggle(), undefined, 'short content has no expand control')
+})
+
+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 { vm, render, mount } = setup(t, './AutomationEditor.vue', {
+ updateAutomation: async (_id: string, input: unknown) => { saved = input; return { data: automation } },
+ validateAutomationTrigger: async () => ({ data: { next_runs: [] } }),
+ }, props)
+ vm.$.props.visible = true
+ await vue.nextTick()
+ assert.equal(vm.approvalHours, 24)
+ const input = nodes(render()).find(node => node.type === 't-input-number' && node.props.max === 168)
+ assert.ok(input)
+ assert.equal(input.props.theme, 'row', 'both controls stay visible with full-sized click targets')
+ assert.equal(input.props.suffix, undefined, 'the unit cannot crowd the numeric input or controls')
+ // Use TDesign's real step handlers against the editor's compiled v-model binding.
+ let control: any
+ const NumberControl = vue.defineComponent({
+ props: numberProps,
+ setup(props) { control = useInputNumber(props); return () => null },
+ })
+ mount({ setup: () => () => vue.h(NumberControl,
+ nodes(render()).find(node => node.type === 't-input-number' && node.props.max === 168).props) })
+ control.handleAdd({})
+ await vue.nextTick()
+ assert.equal(vm.form.approval_timeout_minutes, 1500)
+ assert.equal(control.userInput.value, '25')
+ control.handleReduce({})
+ await vue.nextTick()
+ assert.equal(vm.form.approval_timeout_minutes, 1440)
+ assert.equal(control.userInput.value, '24')
+ const update = input.props['onUpdate:modelValue']
+ update(undefined)
+ assert.equal(vm.approvalHours, 24)
+ update(0)
+ assert.equal(vm.approvalHours, 1)
+ update(169)
+ assert.equal(vm.approvalHours, 168)
+ update(4)
+ await vm.save()
+ assert.equal(saved.approval_timeout_minutes, 240)
+})
+
+test('the editor preserves, changes, and clears an automation model override', async t => {
+ const saved: any[] = []
+ const { 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' })
+ vm.$.props.visible = true
+ await vue.nextTick()
+ assert.equal(vm.form.model_id, 'model-one')
+ vm.form.model_id = 'model-two'
+ await vm.save()
+ assert.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')
+})
+
+test('list run and delete actions call APIs only after their inline confirmation', async t => {
+ let runCalls = 0
+ let deleteCalls = 0
+ const { vm, render } = setup(t, './AutomationList.vue', {
+ listAutomations: async () => ({ data: [automation] }),
+ runAutomationNow: async () => { runCalls++; return { data: { id: 'run-1' } } },
+ deleteAutomation: async () => { deleteCalls++ },
+ }, {})
+ await flush()
+ const popups = nodes(render()).filter(node => node.type === 't-popconfirm')
+ assert.equal(popups.length, 2)
+ for (const popup of popups) {
+ const trigger = nodes(popup).find(node => node.type === 'button')
+ assert.ok(trigger)
+ trigger.props.onClick?.()
+ popup.props.onCancel?.()
+ }
+ assert.equal(runCalls, 0)
+ assert.equal(deleteCalls, 0)
+ await popups[0].props.onConfirm()
+ assert.equal(runCalls, 1)
+ assert.equal(vm.detailVisible, true)
+ await popups[1].props.onConfirm()
+ assert.equal(deleteCalls, 1)
+ assert.equal(vm.automations.length, 0)
+})
+
+test('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 { vm, render } = setup(t, './AutomationDetail.vue', {
+ runAutomationNow: async () => { runCalls++; return { data: { id: 'new-run' } } },
+ }, props)
+ vm.runs = [
+ { id: 'a', scheduled_at: '2026-10-20T16:30:00Z' },
+ { id: 'b', scheduled_at: '2026-10-20T16:00:00Z' },
+ { id: 'c', scheduled_at: '2026-10-20T15:59:00Z' },
+ ].map(run => ({ ...run, status: 'succeeded', session_id: 'chat', trigger_kind: 'schedule' }))
+ assert.equal(vm.runGroups.length, 2)
+ assert.equal(vm.runGroups[0].date, 'October 21, 2026')
+ assert.equal(vm.runGroups[0].runs.length, 2)
+ assert.equal(vm.runTime(vm.runs[0].scheduled_at), '00:30')
+ const popup = nodes(render()).find(node => node.type === 't-popconfirm')
+ assert.ok(popup)
+ const trigger = nodes(popup).find(node => node.type === 'button')
+ assert.equal(trigger.props['aria-label'], 'automation.actions.runNow')
+ trigger.props.onClick?.()
+ assert.equal(runCalls, 0)
+ await popup.props.onConfirm()
+ assert.equal(runCalls, 1)
+})
+
+test('grant popup preserves history and dismisses when starting a run or reopening the drawer', async t => {
+ const { vm, render } = setup(t, './AutomationDetail.vue', {
+ listAutomationGrants: async () => ({ data: [] }),
+ listAutomationGrantCandidates: 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' })
+ assert.equal(vm.grantsVisible, false)
+ const popup = nodes(render()).find(node => node.type?.name === 't-popup')
+ popup.props['onUpdate:visible'](true)
+ assert.equal(vm.grantsVisible, true)
+ await vm.loadGrants()
+ assert.equal(vm.grantsVisible, true, 'loading grants must not dismiss their popup')
+ const trigger = nodes(render()).find(node => node.type === 'button' && node.props?.class?.includes('automation-detail__grants-trigger'))
+ assert.ok(trigger.props.class.includes('is-attention'), 'candidates remain visible from the trigger')
+ assert.equal(trigger.props['aria-expanded'], true)
+ assert.ok(nodes(render()).some(node => node.props?.class === 'automation-detail__history'))
+ await vm.runNow()
+ assert.equal(vm.grantsVisible, false, 'a manual run dismisses the popup to reveal progress')
+ assert.equal(vm.runs[0].id, 'new-run')
+ popup.props['onUpdate:visible'](true)
+ vm.$.props.visible = true
+ await flush()
+ assert.equal(vm.grantsVisible, false, 'reopening the drawer does not restore a stale popup')
+})
+
+for (const file of ['./AutomationList.vue', './AutomationDetail.vue']) {
+ test(`${file}: elapsed one-shot schedules have no resume entry, but manual run remains available`, async t => {
+ let resumeCalls = 0
+ const item = { ...automation, enabled: false, trigger: { type: 'once', at: new Date(Date.now() - 60_000).toISOString() } }
+ const { vm, render } = setup(t, file, {
+ listAutomations: async () => ({ data: [item] }),
+ resumeAutomation: async () => { resumeCalls++; return { data: { ...item, enabled: true } } },
+ }, { visible: false, automation: item, agentName: 'Assistant' })
+ await flush()
+ const resumeButton = () => nodes(render()).find(node => node.type === 'button'
+ && (node.props?.role === 'switch' || node.props?.['aria-label'] === 'automation.actions.resume'))
+ assert.equal(resumeButton(), undefined)
+ assert.ok(nodes(render()).some(node => node.type === 't-popconfirm'
+ && node.props?.['confirm-btn']?.content === 'automation.actions.runNow'))
+ await vm.toggle(item)
+ assert.equal(resumeCalls, 0, 'stale handlers cannot resume an elapsed schedule')
+
+ item.trigger.at = new Date(Date.now() + 60_000).toISOString()
+ assert.ok(resumeButton(), 'a paused future one-shot can still be resumed')
+ if (file.includes('Detail')) {
+ assert.ok(nodes(render()).some(node => node.props?.name === 'resume'), 'resume uses its own icon')
+ }
+ await vm.toggle(item)
+ assert.equal(resumeCalls, 1)
+ })
+}
diff --git a/frontend/src/views/chat/automationConversation.test.ts b/frontend/src/views/chat/automationConversation.test.ts
new file mode 100644
index 000000000..f22d4fc07
--- /dev/null
+++ b/frontend/src/views/chat/automationConversation.test.ts
@@ -0,0 +1,70 @@
+import assert from 'node:assert/strict'
+import { readFileSync } from 'node:fs'
+import { runInNewContext } from 'node:vm'
+import test from 'node:test'
+import { compileTemplate } from '@vue/compiler-sfc'
+import * as vue from 'vue'
+import ts from 'typescript'
+
+const source = readFileSync(new URL('./index.vue', import.meta.url), 'utf8')
+const start = source.indexOf('<div class="input-container"')
+const end = source.indexOf('</InputField>', start) + '</InputField>'.length
+const compiled = compileTemplate({
+ source: `${source.slice(start, end)}</div>`, filename: 'index.vue', id: 'automation-composer',
+})
+assert.deepEqual(compiled.errors, [])
+const exports: any = {}
+runInNewContext(ts.transpileModule(compiled.code, {
+ compilerOptions: { module: ts.ModuleKind.CommonJS },
+}).outputText, {
+ exports, require: () => ({
+ ...vue, resolveComponent: (name: string) => name, withCtx: (fn: unknown) => fn,
+ withDirectives: (node: unknown) => node,
+ }),
+})
+function nodes(node: any): any[] {
+ if (!node || typeof node !== 'object') return []
+ if (Array.isArray(node)) return node.flatMap(nodes)
+ const children = node.children
+ return [node, ...(Array.isArray(children) ? nodes(children)
+ : children && typeof children === 'object'
+ ? Object.values(children).flatMap(slot => typeof slot === 'function' ? nodes(slot()) : []) : [])]
+}
+function render(kind: string | null, embeddedMode = false) {
+ const currentSession = vue.ref(kind === null ? null : { kind })
+ const declaration = source.match(/const isAutomationSession = .*;/)![0]
+ const isAutomationSession = runInNewContext(`${declaration}\nisAutomationSession`, { currentSession, computed: vue.computed })
+ return nodes(exports.render({
+ currentSession: currentSession.value, isAutomationSession: isAutomationSession.value,
+ embeddedMode, userHasScrolledUp: false, onClickScrollToBottom() {}, t: (key: string) => key,
+ focusComposerOnMount: false, isReplying: false, composerLocked: false, session_id: 'session',
+ currentAssistantMessageId: '', modelId: '', defaultModelId: '', steerQueue: [],
+ isAgentStreamSession: () => true, $slots: {},
+ }, []))
+}
+
+test('automation conversations replace the composer with a notice but retain prompt responses', () => {
+ const rendered = render('automation')
+ assert.ok(rendered.some(node => node.props?.class === 'automation-session-notice'))
+ assert.ok(rendered.some(node => node.type === 'PendingPromptDock'))
+ assert.ok(!rendered.some(node => node.type === 'InputField'))
+})
+
+test('normal and embedded conversations keep their composer, while unknown sessions wait for metadata', () => {
+ assert.ok(render('chat').some(node => node.type === 'InputField'))
+ assert.ok(render(null, true).some(node => node.type === 'InputField'))
+ assert.ok(!render(null).some(node => node.type === 'InputField'))
+})
+
+test('automation history does not offer fork or rewind actions that lead back to a composer', () => {
+ const fork = source.slice(source.indexOf('function forkAffordanceOf('), source.indexOf('// One pass over the transcript'))
+ const rewind = source.slice(source.indexOf('function canRewindMessage('), source.indexOf('const FORK_PREFILL_KEY'))
+ for (const automation of [true, false]) {
+ const actions = runInNewContext(`${fork}\n${rewind}\n({ forkAffordanceOf, canRewindMessage })`, {
+ isAutomationSession: { value: automation }, messagesList: [],
+ rewindableIds: { value: new Set(['message']) }, resolveForkAffordance: () => ({ canFork: true }),
+ })
+ assert.equal(actions.forkAffordanceOf('message').canFork, !automation)
+ assert.equal(actions.canRewindMessage('message'), !automation)
+ }
+})
diff --git a/frontend/src/views/chat/components/answerToolbarCompletion.test.mjs b/frontend/src/views/chat/components/answerToolbarCompletion.test.mjs
index f2ff1f64b..b62bcf77d 100644
--- a/frontend/src/views/chat/components/answerToolbarCompletion.test.mjs
+++ b/frontend/src/views/chat/components/answerToolbarCompletion.test.mjs
@@ -91,7 +91,7 @@ test('follow-up suggestions wait until the answer is fully rendered', () => {
)
assert.match(
chatView,
- /<FollowUpSuggestions v-if="session\.answerFullyRendered && !session\.steerForked && !session\.suggestionsDismissed"/,
+ /<FollowUpSuggestions v-if="!isAutomationSession && session\.answerFullyRendered && !session\.steerForked && !session\.suggestionsDismissed"/,
)
assert.match(botMessage, /emit\('render-complete-change', ready\)/)
assert.match(agentStream, /emit\('render-complete-change', ready\)/)
diff --git a/frontend/src/views/chat/index.vue b/frontend/src/views/chat/index.vue
index 5e028800a..28048d306 100644
--- a/frontend/src/views/chat/index.vue
+++ b/frontend/src/views/chat/index.vue
@@ -51,7 +51,7 @@
</div>
</div>
<!-- 推荐问题卡片 - 仅在新会话(无消息)时展示 -->
- <div v-if="!embeddedMode && messagesList.length === 0 && !loading"
+ <div v-if="!embeddedMode && currentSession && !isAutomationSession && messagesList.length === 0 && !loading"
class="suggested-questions-container"
:class="{ 'has-questions': suggestedQuestions.length > 0 || suggestedQuestionsLoading }">
<!-- 骨架屏占位 -->
@@ -140,7 +140,7 @@
@ask-assistant="handleAskAssistant"
@render-complete-change="(ready) => handleAnswerRenderComplete(session, ready)">
</botmsg>
- <FollowUpSuggestions v-if="session.answerFullyRendered && !session.steerForked && !session.suggestionsDismissed"
+ <FollowUpSuggestions v-if="!isAutomationSession && session.answerFullyRendered && !session.steerForked && !session.suggestionsDismissed"
:suggestion-set="session.suggestionSet"
:loading="session.suggestionLoading"
:allow-regenerate="session.suggestionSet?.allow_regenerate"
@@ -165,7 +165,11 @@
</div>
</transition>
<PendingPromptDock :embedded-mode="embeddedMode" />
- <InputField ref="inputFieldRef" :auto-focus="focusComposerOnMount" compact
+ <div v-if="isAutomationSession" class="automation-session-notice" role="note">
+ <t-icon name="time" size="14px" />
+ <span>{{ t('automation.conversationNotice') }}</span>
+ </div>
+ <InputField v-else-if="embeddedMode || currentSession" ref="inputFieldRef" :auto-focus="focusComposerOnMount" compact
@send-msg="(query, modelId, mentionedItems, imageFiles, attachmentFiles, options) => sendMsg(query, modelId, mentionedItems, imageFiles, attachmentFiles, options)"
@steer-msg="(query, mentionedItems, delivery) => handleSteerMsg(query, mentionedItems, delivery)"
@promote-steer="handlePromoteSteer"
@@ -341,6 +345,7 @@ const router = useRouter();
const session_id = ref(props.session_id || route.params.chatid);
watch(session_id, () => childTabs.reset(), { flush: 'sync' });
const currentSession = ref(null);
+const isAutomationSession = computed(() => currentSession.value?.kind === 'automation');
// 拉 session 详情,并按其 last_request_state 把输入栏状态恢复到当时的发起态。
// 嵌入式(embeddedMode)由宿主页面注入 agent/KB,所以跳过整套恢复逻辑,
@@ -385,7 +390,7 @@ function handleAskAssistant(messageId) {
}
function forkAffordanceOf(messageId) {
- if (!messageId) return { canFork: false }
+ if (isAutomationSession.value || !messageId) return { canFork: false }
return resolveForkAffordance(messagesList, messageId)
}
@@ -397,7 +402,7 @@ const rewindableIds = computed(() => rewindableMessageIds(messagesList, {
}))
function canRewindMessage(messageId) {
- return Boolean(messageId) && rewindableIds.value.has(String(messageId))
+ return !isAutomationSession.value && Boolean(messageId) && rewindableIds.value.has(String(messageId))
}
const FORK_PREFILL_KEY = 'weknora:fork-prefill'
@@ -405,7 +410,7 @@ let forkInFlight = false
const rewindInFlight = ref(false)
const rewindLockSessionId = ref('')
const composerLocked = computed(() =>
- rewindInFlight.value && String(session_id.value || '') === rewindLockSessionId.value
+ isAutomationSession.value || (rewindInFlight.value && String(session_id.value || '') === rewindLockSessionId.value)
)
function stashForkLanding(sessionId, text) {
@@ -757,6 +762,7 @@ const handleAnswerRenderComplete = (message, ready) => {
};
const loadFollowUpSuggestions = async (message, ensure = false, regenerate = false) => {
+ if (isAutomationSession.value) return;
const messageId = resolveAssistantMessageId(message);
const targetSessionId = session_id.value;
if (!messageId || !targetSessionId || message.suggestionsDismissed) return;
@@ -1417,6 +1423,10 @@ const attachSteerFollowUp = async (completedAssistantId) => {
};
const sendMsg = async (value, modelId = '', mentionedItems = [], imageFiles = [], attachmentFiles = [], options = {}) => {
+ if (!props.embeddedMode && !currentSession.value) {
+ await loadSessionAndHydrate(session_id.value);
+ if (!currentSession.value) return;
+ }
if (composerLocked.value) return
const reasoningEffort = props.embeddedMode ? undefined : (useSettingsStoreInstance.reasoningEffortOverride || undefined);
stopStream();
@@ -1672,7 +1682,7 @@ const resumeSuspendedRun = async (pendingId) => {
currentAssistantMessageId.value = resumeId;
attachingResumedRun = true;
try {
- for (let attempt = 0; attempt < 10; attempt++) {
+ for (let attempt = 0; attempt < 60; attempt++) {
await new Promise((resolve) => setTimeout(resolve, 500));
if (session_id.value !== sessionId) return;
await startStream({
@@ -1680,6 +1690,7 @@ const resumeSuspendedRun = async (pendingId) => {
query: resumeId,
method: 'GET',
url: '/api/v1/sessions/continue-stream',
+ resume_pending_id: pendingId,
});
if (!error.value) return;
}
@@ -2157,6 +2168,19 @@ onBeforeRouteUpdate((to, from, next) => {
}
}
+.automation-session-notice {
+ display: flex;
+ align-items: center;
+ justify-content: center;
+ gap: 8px;
+ padding: 16px 0;
+ color: var(--td-text-color-secondary);
+ font-size: var(--app-text-sm);
+ line-height: 1.6;
+
+ > .t-icon { flex-shrink: 0; }
+}
+
.msg_list {
display: flex;
flex-direction: column;
diff --git a/internal/application/service/automation.go b/internal/application/service/automation.go
index 4f24789e0..3c8308617 100644
--- a/internal/application/service/automation.go
+++ b/internal/application/service/automation.go
@@ -72,6 +72,7 @@ type AutomationService struct {
messages interfaces.MessageService
grants interfaces.AgentGrantRepository
notices *NotificationService
+ models interfaces.ModelService
sessions interfaces.SessionService
broker *hitl.Broker
@@ -103,10 +104,11 @@ func NewAutomationService(
messages interfaces.MessageService,
grants interfaces.AgentGrantRepository,
notices *NotificationService,
+ models interfaces.ModelService,
) *AutomationService {
s := &AutomationService{
db: db, agents: agents, users: users, members: members, tenants: tenants,
- messages: messages, grants: grants, notices: notices,
+ messages: messages, grants: grants, notices: notices, models: models,
instance: uuid.NewString(),
now: time.Now,
wake: make(chan struct{}, 1),
@@ -241,6 +243,9 @@ func applyAutomationPatch(a *types.Automation, p *types.AutomationPatch) {
if p.AgentID != nil {
a.AgentID = strings.TrimSpace(*p.AgentID)
}
+ if p.ModelID != nil {
+ a.ModelID = strings.TrimSpace(*p.ModelID)
+ }
if p.Instruction != nil {
a.Instruction = strings.TrimSpace(*p.Instruction)
}
@@ -287,6 +292,9 @@ func (s *AutomationService) validate(ctx context.Context, a *types.Automation) (
if _, err := s.runnableAgent(ctx, a.AgentID, a.TenantID); err != nil {
return nil, apperrors.NewBadRequestError(err.Error())
}
+ if err := s.validateModel(ctx, a.ModelID, a.TenantID); err != nil {
+ return nil, apperrors.NewBadRequestError(err.Error())
+ }
sched, err := automation.Parse(a.Trigger)
if err != nil {
return nil, apperrors.NewBadRequestError(err.Error())
@@ -357,6 +365,22 @@ func (s *AutomationService) runnableAgent(ctx context.Context, id string, tenant
return agent, nil
}
+func (s *AutomationService) validateModel(ctx context.Context, id string, tenantID uint64) error {
+ if id == "" {
+ return nil
+ }
+ if s.models == nil {
+ return errors.New("model service is unavailable")
+ }
+ model, err := s.models.GetModelByID(ctx, id)
+ if err != nil || model == nil || model.DeletedAt.Valid ||
+ (!model.IsBuiltin && model.TenantID != tenantID) ||
+ model.Type != types.ModelTypeKnowledgeQA || model.Status != types.ModelStatusActive {
+ return errors.New("the selected chat model is unavailable in this workspace")
+ }
+ return nil
+}
+
// Create adds an automation owned by the caller.
func (s *AutomationService) Create(ctx context.Context, p *types.AutomationPatch) (*types.Automation, error) {
tenantID, userID, err := automationOwner(ctx)
@@ -391,7 +415,7 @@ func (s *AutomationService) Create(ctx context.Context, p *types.AutomationPatch
}
var automationEditable = []string{
- "name", "description", "agent_id", "instruction", "trigger_config", "session_mode", "carry_last_result",
+ "name", "description", "agent_id", "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",
diff --git a/internal/application/service/automation_model_test.go b/internal/application/service/automation_model_test.go
new file mode 100644
index 000000000..e9601e28b
--- /dev/null
+++ b/internal/application/service/automation_model_test.go
@@ -0,0 +1,105 @@
+package service
+
+import (
+ "context"
+ "testing"
+ "time"
+
+ "github.com/Tencent/WeKnora/internal/types"
+ "github.com/Tencent/WeKnora/internal/types/interfaces"
+ "github.com/stretchr/testify/require"
+)
+
+type automationModels struct {
+ interfaces.ModelService
+ models map[string]*types.Model
+}
+
+func (m *automationModels) GetModelByID(_ context.Context, id string) (*types.Model, error) {
+ return m.models[id], nil
+}
+
+func setAutomationModels(f *automationFixture) *automationModels {
+ models := &automationModels{models: map[string]*types.Model{
+ "one": {
+ ID: "one", TenantID: automationTenant, Type: types.ModelTypeKnowledgeQA, Status: types.ModelStatusActive,
+ },
+ "two": {
+ ID: "two", TenantID: automationTenant, Type: types.ModelTypeKnowledgeQA, Status: types.ModelStatusActive,
+ },
+ }}
+ f.svc.models = models
+ return models
+}
+
+func TestAutomationModelOverridePersistsAndRuns(t *testing.T) {
+ f := newAutomationFixture(t)
+ setAutomationModels(f)
+ a := f.create(t, types.AutomationPatch{ModelID: ptr(" one ")})
+ require.Equal(t, "one", f.reload(t, a.ID).ModelID)
+ for _, id := range []string{"two", ""} {
+ f.now = f.now.Add(time.Minute)
+ _, err := f.svc.Update(f.ctx, a.ID, &types.AutomationPatch{ModelID: &id})
+ require.NoError(t, err)
+ require.Equal(t, id, f.reload(t, a.ID).ModelID)
+ queued, err := f.svc.RunNow(f.ctx, a.ID)
+ require.NoError(t, err)
+ run := f.settleRun(t, queued.ID)
+ require.Equal(t, types.AutomationRunSucceeded, run.Status)
+ require.Equal(t, id, f.sessions.last().req.SummaryModelID)
+ require.Equal(t, id, f.sessions.last().req.CustomAgent.Config.ModelID)
+ require.Empty(t, f.agents.agent.Config.ModelID, "an override must not mutate the agent")
+ }
+}
+
+func TestAutomationModelOverrideRejectsUnavailableModels(t *testing.T) {
+ f := newAutomationFixture(t)
+ models := setAutomationModels(f)
+ models.models["other"] = &types.Model{
+ ID: "other", TenantID: automationTenant + 1, Type: types.ModelTypeKnowledgeQA, Status: types.ModelStatusActive,
+ }
+ models.models["embedding"] = &types.Model{
+ ID: "embedding", TenantID: automationTenant, Type: types.ModelTypeEmbedding, Status: types.ModelStatusActive,
+ }
+ models.models["inactive"] = &types.Model{
+ ID: "inactive", TenantID: automationTenant,
+ Type: types.ModelTypeKnowledgeQA, Status: types.ModelStatusDownloading,
+ }
+ a := f.create(t, types.AutomationPatch{ModelID: ptr("one")})
+ for _, id := range []string{"missing", "other", "embedding", "inactive"} {
+ _, err := f.svc.Update(f.ctx, a.ID, &types.AutomationPatch{ModelID: &id})
+ require.Error(t, err, id)
+ require.Equal(t, "one", f.reload(t, a.ID).ModelID)
+ }
+ delete(models.models, "one")
+ 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.Empty(t, f.sessions.calls, "a deleted override must not silently fall back to another model")
+}
+
+func TestAutomationModelEditDoesNotChangeSuspendedRun(t *testing.T) {
+ f := newAutomationFixture(t)
+ setAutomationModels(f)
+ a := f.create(t, types.AutomationPatch{ModelID: ptr("one")})
+ f.suspendOnApproval(t, "op:knowledge.delete:kb1")
+ queued, err := f.svc.RunNow(f.ctx, a.ID)
+ require.NoError(t, err)
+ run := f.settleRun(t, queued.ID)
+ require.Equal(t, types.AutomationRunAwaitingApproval, run.Status)
+ _, err = f.svc.Update(f.ctx, a.ID, &types.AutomationPatch{ModelID: ptr("two")})
+ require.NoError(t, err)
+ _, err = f.broker.Store().Transition(f.ctx, run.PendingPromptID, types.AgentPromptTransition{
+ From: []string{types.AgentPromptSuspended}, To: types.AgentPromptAnswered,
+ Response: types.JSON(`{"approved":true}`),
+ })
+ require.NoError(t, err)
+ prompt, err := f.broker.Store().Get(f.ctx, run.PendingPromptID)
+ require.NoError(t, err)
+ require.True(t, f.svc.HandlesPrompt(f.ctx, prompt))
+ run = f.settleRun(t, run.ID)
+ require.Equal(t, types.AutomationRunSucceeded, run.Status)
+ require.Equal(t, "one", f.sessions.last().req.SummaryModelID)
+ require.Equal(t, "two", f.reload(t, a.ID).ModelID)
+}
diff --git a/internal/application/service/automation_regression_test.go b/internal/application/service/automation_regression_test.go
index aa22ad3c2..3571a6072 100644
--- a/internal/application/service/automation_regression_test.go
+++ b/internal/application/service/automation_regression_test.go
@@ -385,6 +385,7 @@ func TestAutomationApprovalResumeUsesRemainingExecutionBudget(t *testing.T) {
f.messages,
f.svc.grants,
f.svc.notices,
+ f.svc.models,
)
restarted.Configure(AutomationConfig{DefaultMaxDuration: time.Second})
restarted.now = func() time.Time { return f.now }
diff --git a/internal/application/service/automation_runner.go b/internal/application/service/automation_runner.go
index 34724bace..2dc5108ec 100644
--- a/internal/application/service/automation_runner.go
+++ b/internal/application/service/automation_runner.go
@@ -255,6 +255,7 @@ func (s *AutomationService) runOnce(ctx context.Context, run *types.AutomationRu
defer cancel()
var resume *types.AgentResume
+ modelID := a.ModelID
session, userMsg, answer, query := (*types.Session)(nil), (*types.Message)(nil), (*types.Message)(nil), ""
if run.Resume {
var stop func()
@@ -268,6 +269,11 @@ func (s *AutomationService) runOnce(ctx context.Context, run *types.AutomationRu
defer stop()
if snap, err := agent.DecodeRunSnapshot(resume.Snapshot); err == nil {
query = snap.Query
+ // A settings edit affects future runs, not an approval already in flight.
+ var original types.ResumableAgentRequest
+ if err := json.Unmarshal(snap.Request, &original); err == nil {
+ modelID = original.SummaryModelID
+ }
}
} else {
session, err = s.runSession(ctx, a, run)
@@ -285,10 +291,21 @@ func (s *AutomationService) runOnce(ctx context.Context, run *types.AutomationRu
return failed("could not record the run: " + err.Error())
}
}
+ if err := s.validateModel(ctx, modelID, a.TenantID); err != nil {
+ return failed(err.Error())
+ }
+ if modelID != "" {
+ // Keep the shared agent configuration untouched. The per-run copy also
+ // allows an explicit model when the agent's default is no longer available.
+ configured := *agentConfig
+ configured.Config.ModelID = modelID
+ agentConfig = &configured
+ }
loc := scheduleLocation(a.Trigger)
req := &types.QARequest{
Session: session, Query: query, AssistantMessageID: answer.ID, UserMessageID: userMsg.ID,
CustomAgent: agentConfig, WebSearchEnabled: agentConfig.Config.WebSearchEnabled,
+ SummaryModelID: modelID,
AssistantAccess: a.AccessLevel, Mode: types.RunModeDeferred, Suspendable: true, Resume: resume,
RunNote: automation.RunNote(a.Name, run.ScheduledAt, loc),
}
@@ -345,7 +362,9 @@ func (s *AutomationService) runSession(
session := &types.Session{
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},
+ LastRequestState: &types.SessionLastRequestState{
+ AgentID: a.AgentID, AgentEnabled: true, ModelID: a.ModelID,
+ },
}
if err := s.db.WithContext(ctx).Session(&gorm.Session{SkipHooks: true}).
Clauses(clause.OnConflict{DoNothing: true}).Create(session).Error; err != nil {
diff --git a/internal/application/service/automation_test.go b/internal/application/service/automation_test.go
index 952ad4086..ad4846305 100644
--- a/internal/application/service/automation_test.go
+++ b/internal/application/service/automation_test.go
@@ -145,7 +145,7 @@ func newAutomationFixture(t *testing.T) *automationFixture {
}
f.sessions = &automationSessions{db: db, run: done}
f.svc = NewAutomationService(db, f.agents, f.users, f.members, &collaborationTenants{},
- f.messages, repository.NewAgentGrantRepository(db), NewNotificationService(db))
+ f.messages, repository.NewAgentGrantRepository(db), NewNotificationService(db), nil)
f.svc.now = func() time.Time { return f.now }
f.svc.Bind(f.sessions, f.broker, nil, nil)
ctx := context.WithValue(context.Background(), types.TenantIDContextKey, automationTenant)
@@ -354,7 +354,10 @@ func (f *automationFixture) suspendOnApproval(t *testing.T, grant string) {
}
require.NoError(t, f.broker.Store().Create(ctx, prompt))
require.NoError(t, f.db.Create(prompt).Error)
- snap, _ := json.Marshal(agent.RunSnapshot{Version: agent.RunSnapshotVersion, Query: req.Query})
+ resumable, _ := json.Marshal(types.ResumableAgentRequest{SummaryModelID: req.SummaryModelID})
+ snap, _ := json.Marshal(agent.RunSnapshot{
+ Version: agent.RunSnapshotVersion, Query: req.Query, Request: resumable,
+ })
require.NoError(t, f.broker.Suspensions().Save(ctx, &types.AgentRunSuspension{
AssistantMessageID: req.AssistantMessageID, PromptID: prompt.ID, SessionID: req.Session.ID,
Snapshot: snap,
@@ -373,9 +376,12 @@ func TestAutomationSuspendsAndResumesAfterApproval(t *testing.T) {
run := f.settleRun(t, queued.ID)
require.Equal(t, types.AutomationRunAwaitingApproval, run.Status)
require.NotEmpty(t, run.PendingPromptID)
- page, err := NewNotificationService(f.db).List(f.ctx, 10, false)
+ notices := NewNotificationService(f.db)
+ notices.now = func() time.Time { return f.now }
+ page, err := notices.List(f.ctx, 10, false, "")
require.NoError(t, err)
- require.Equal(t, types.NotificationAutomationAwaitingApproval, page.Items[0].Kind)
+ require.Len(t, page.Pending, 1)
+ require.Equal(t, types.AgentPromptKindToolApproval, page.Pending[0].Kind)
prompt, _ := f.broker.Store().Get(f.ctx, run.PendingPromptID)
require.True(t, f.svc.HandlesPrompt(f.ctx, prompt), "an automation prompt is not resumed as a chat")
diff --git a/internal/application/service/notification.go b/internal/application/service/notification.go
index 467761a98..cbdfb8e89 100644
--- a/internal/application/service/notification.go
+++ b/internal/application/service/notification.go
@@ -2,9 +2,13 @@ package service
import (
"context"
+ "encoding/base64"
+ "encoding/json"
+ "net/url"
"strings"
"time"
+ apperrors "github.com/Tencent/WeKnora/internal/errors"
"github.com/Tencent/WeKnora/internal/logger"
"github.com/Tencent/WeKnora/internal/types"
"gorm.io/gorm"
@@ -15,12 +19,13 @@ const notificationRetention = 30 * 24 * time.Hour
// NotificationService keeps in-app notifications.
type NotificationService struct {
- db *gorm.DB
+ db *gorm.DB
+ now func() time.Time
}
// NewNotificationService builds the service.
func NewNotificationService(db *gorm.DB) *NotificationService {
- return &NotificationService{db: db}
+ return &NotificationService{db: db, now: time.Now}
}
// Notify records n. A failure is logged, not returned: a notification never
@@ -40,43 +45,140 @@ func (s *NotificationService) Notify(ctx context.Context, n *types.Notification)
}
}
-// NotificationPage is one page of the caller's notifications.
+// PendingNotification is actionable state, independent of notification read state.
+// Its ID is the current prompt, so successive approvals in one run do not collide.
+type PendingNotification struct {
+ ID string `json:"id"`
+ Title string `json:"title"`
+ Kind string `json:"kind"`
+ Link string `json:"link"`
+ CreatedAt time.Time `json:"created_at"`
+}
+
type NotificationPage struct {
- Items []*types.Notification `json:"items"`
- Unread int64 `json:"unread"`
+ Items []*types.Notification `json:"items"`
+ Pending []*PendingNotification `json:"pending"`
+ Unread int64 `json:"unread"`
+ ReadCount int64 `json:"read_count"`
+ NextCursor string `json:"next_cursor"`
+}
+
+type notificationCursor struct {
+ CreatedAt time.Time `json:"created_at"`
+ ID string `json:"id"`
}
-// List returns the caller's newest notifications, at most limit, and how
-// many are unread. unreadOnly leaves out the read ones.
-func (s *NotificationService) List(ctx context.Context, limit int, unreadOnly bool) (*NotificationPage, error) {
+// history excludes approval events: their live prompts are returned separately.
+func (s *NotificationService) history(ctx context.Context) *gorm.DB {
tenantID, userID := notificationOwner(ctx)
+ return s.db.WithContext(ctx).Model(&types.Notification{}).
+ Where("tenant_id = ? AND user_id = ? AND kind <> ?",
+ tenantID, userID, types.NotificationAutomationAwaitingApproval)
+}
+
+// List pages history in stable descending order and always includes current work.
+func (s *NotificationService) List(
+ ctx context.Context, limit int, unreadOnly bool, cursor string,
+) (*NotificationPage, error) {
if limit <= 0 || limit > 100 {
limit = 20
}
- mine := func() *gorm.DB {
- return s.db.WithContext(ctx).Model(&types.Notification{}).
- Where("tenant_id = ? AND user_id = ?", tenantID, userID)
+ query := s.history(ctx)
+ if cursor != "" {
+ if len(cursor) > 1024 {
+ return nil, apperrors.NewBadRequestError("invalid notification cursor")
+ }
+ var c notificationCursor
+ raw, err := base64.RawURLEncoding.DecodeString(cursor)
+ if err != nil || json.Unmarshal(raw, &c) != nil || c.ID == "" || c.CreatedAt.IsZero() {
+ return nil, apperrors.NewBadRequestError("invalid notification cursor")
+ }
+ query = query.Where("created_at < ? OR (created_at = ? AND id < ?)", c.CreatedAt, c.CreatedAt, c.ID)
}
- page := &NotificationPage{Items: []*types.Notification{}}
- query := mine()
if unreadOnly {
query = query.Where("read_at IS NULL")
}
- if err := query.Order("created_at DESC").Limit(limit).Find(&page.Items).Error; err != nil {
+ page := &NotificationPage{Items: []*types.Notification{}}
+ if err := query.Order("created_at DESC").Order("id DESC").Limit(limit + 1).Find(&page.Items).Error; err != nil {
+ return nil, err
+ }
+ if len(page.Items) > limit {
+ page.Items = page.Items[:limit]
+ last := page.Items[limit-1]
+ raw, _ := json.Marshal(notificationCursor{CreatedAt: last.CreatedAt, ID: last.ID})
+ page.NextCursor = base64.RawURLEncoding.EncodeToString(raw)
+ }
+ if err := s.history(ctx).Where("read_at IS NULL").Count(&page.Unread).Error; err != nil {
return nil, err
}
- if err := mine().Where("read_at IS NULL").Count(&page.Unread).Error; err != nil {
+ if err := s.history(ctx).Where("read_at IS NOT NULL").Count(&page.ReadCount).Error; err != nil {
return nil, err
}
+ pending, err := s.pending(ctx)
+ if err != nil {
+ return nil, err
+ }
+ page.Pending = pending
return page, nil
}
-// MarkRead marks the caller's notifications ids read, or all of them when
-// ids is empty.
-func (s *NotificationService) MarkRead(ctx context.Context, ids []string) error {
+func (s *NotificationService) pending(ctx context.Context) ([]*PendingNotification, error) {
tenantID, userID := notificationOwner(ctx)
- query := s.db.WithContext(ctx).Model(&types.Notification{}).
- Where("tenant_id = ? AND user_id = ? AND read_at IS NULL", tenantID, userID)
+ now := s.now()
+ var rows []struct {
+ ID string
+ Title string
+ Kind string
+ SessionID string
+ AutomationID string
+ RunID string
+ CreatedAt time.Time
+ WaitingSince time.Time
+ ApprovalTimeoutMinutes int
+ }
+ // Scope every joined resource. A deleted/cancelled/answered/expired run is no
+ // longer actionable even if its old notification has never been opened.
+ err := s.db.WithContext(ctx).Table("automation_runs AS r").
+ Select("p.id, a.name AS title, p.kind, r.session_id, a.id AS automation_id, r.id AS run_id, "+
+ "p.created_at, r.updated_at AS waiting_since, a.approval_timeout_minutes").
+ Joins("JOIN automations AS a ON a.id = r.automation_id AND a.tenant_id = r.tenant_id").
+ Joins("JOIN agent_prompts AS p ON p.id = r.pending_prompt_id "+
+ "AND p.tenant_id = r.tenant_id AND p.session_id = r.session_id").
+ Where("a.tenant_id = ? AND a.owner_user_id = ? AND a.deleted_at IS NULL", tenantID, userID).
+ Where("r.status = ? AND r.cancel_requested = ?", types.AutomationRunAwaitingApproval, false).
+ Where("p.user_id = ? AND p.status IN ?", automationGrantUser(userID),
+ []string{types.AgentPromptPending, types.AgentPromptSuspended}).
+ Where("p.expires_at IS NULL OR p.expires_at > ?", now).
+ Order("p.created_at ASC").Order("p.id ASC").Scan(&rows).Error
+ if err != nil {
+ return nil, err
+ }
+ pending := make([]*PendingNotification, 0, len(rows))
+ for _, row := range rows {
+ if !now.Before(row.WaitingSince.Add(time.Duration(row.ApprovalTimeoutMinutes) * time.Minute)) {
+ continue
+ }
+ link := "/platform/automations/" + url.PathEscape(row.AutomationID) + "?run=" + url.QueryEscape(row.RunID)
+ if row.SessionID != "" {
+ link = "/platform/chat/" + url.PathEscape(row.SessionID)
+ }
+ pending = append(pending, &PendingNotification{
+ ID: row.ID, Title: row.Title, Kind: row.Kind, Link: link, CreatedAt: row.CreatedAt,
+ })
+ }
+ return pending, nil
+}
+
+// ClearRead removes only read history belonging to the caller. Pending work
+// comes from live runs and prompts and is never affected by this operation.
+func (s *NotificationService) ClearRead(ctx context.Context) error {
+ return s.history(ctx).Where("read_at IS NOT NULL").Delete(&types.Notification{}).Error
+}
+
+// MarkRead marks the caller's history ids read, or all history when ids is empty.
+// Live pending work is independent of read state.
+func (s *NotificationService) MarkRead(ctx context.Context, ids []string) error {
+ query := s.history(ctx).Where("read_at IS NULL")
if len(ids) > 0 {
query = query.Where("id IN ?", ids)
}
diff --git a/internal/application/service/notification_test.go b/internal/application/service/notification_test.go
new file mode 100644
index 000000000..fac1e6adb
--- /dev/null
+++ b/internal/application/service/notification_test.go
@@ -0,0 +1,165 @@
+package service
+
+import (
+ "context"
+ "fmt"
+ "testing"
+ "time"
+
+ "github.com/Tencent/WeKnora/internal/types"
+ "github.com/stretchr/testify/require"
+)
+
+func TestNotificationHistoryCursorAndOwnerIsolation(t *testing.T) {
+ f := newAutomationFixture(t)
+ svc := NewNotificationService(f.db)
+ svc.now = func() time.Time { return f.now }
+ for i := 0; i < 25; i++ {
+ svc.Notify(f.ctx, &types.Notification{
+ ID: fmt.Sprintf("n-%02d", i), TenantID: automationTenant, UserID: "u",
+ Kind: types.NotificationAutomationSucceeded, Title: "done", CreatedAt: f.now,
+ })
+ }
+ svc.Notify(f.ctx, &types.Notification{
+ TenantID: automationTenant, UserID: "other",
+ Kind: types.NotificationAutomationFailed, Title: "private", CreatedAt: f.now,
+ })
+ svc.Notify(f.ctx, &types.Notification{
+ TenantID: automationTenant + 1, UserID: "u",
+ Kind: types.NotificationAutomationFailed, Title: "other tenant", CreatedAt: f.now,
+ })
+ page, err := svc.List(f.ctx, 20, false, "")
+ require.NoError(t, err)
+ require.Len(t, page.Items, 20)
+ require.EqualValues(t, 25, page.Unread)
+ require.Equal(t, "n-24", page.Items[0].ID)
+ require.NotEmpty(t, page.NextCursor)
+ // A new arrival and a deleted boundary row must not shift the second page.
+ svc.Notify(f.ctx, &types.Notification{
+ TenantID: automationTenant, UserID: "u",
+ Kind: types.NotificationAutomationSucceeded, Title: "new", CreatedAt: f.now.Add(time.Minute),
+ })
+ require.NoError(t, f.db.Delete(&types.Notification{}, "id = ?", page.Items[19].ID).Error)
+ next, err := svc.List(f.ctx, 20, false, page.NextCursor)
+ require.NoError(t, err)
+ require.Len(t, next.Items, 5)
+ require.Equal(t, "n-04", next.Items[0].ID)
+ require.Equal(t, "n-00", next.Items[4].ID)
+ require.Empty(t, next.NextCursor)
+ _, err = svc.List(f.ctx, 20, false, "broken")
+ require.Error(t, err)
+}
+
+func TestNotificationPendingUsesLivePromptsNotReadHistory(t *testing.T) {
+ f := newAutomationFixture(t)
+ svc := NewNotificationService(f.db)
+ svc.now = func() time.Time { return f.now }
+ a := f.create(t, types.AutomationPatch{})
+ prompt := &types.AgentPrompt{
+ ID: "prompt", TenantID: automationTenant, UserID: automationGrantUser("u"),
+ SessionID: "chat", Kind: types.AgentPromptKindToolApproval,
+ Status: types.AgentPromptSuspended, CreatedAt: f.now,
+ }
+ require.NoError(t, f.db.Create(prompt).Error)
+ run := &types.AutomationRun{
+ ID: "run", AutomationID: a.ID, TenantID: automationTenant, SessionID: "chat", PendingPromptID: prompt.ID,
+ Status: types.AutomationRunAwaitingApproval, ScheduledAt: f.now, UpdatedAt: f.now,
+ }
+ require.NoError(t, f.db.Create(run).Error)
+ // Pending remains visible even without a notification, and beyond 20 results.
+ for i := 0; i < 30; i++ {
+ svc.Notify(f.ctx, &types.Notification{
+ TenantID: automationTenant, UserID: "u",
+ Kind: types.NotificationAutomationSucceeded, Title: "done", CreatedAt: f.now.Add(time.Minute),
+ })
+ }
+ page, err := svc.List(f.ctx, 20, false, "")
+ require.NoError(t, err)
+ require.Len(t, page.Pending, 1)
+ require.Equal(t, prompt.ID, page.Pending[0].ID)
+ require.Equal(t, "/platform/chat/chat", page.Pending[0].Link)
+ require.EqualValues(t, 30, page.Unread)
+ approval := &types.Notification{
+ TenantID: automationTenant, UserID: "u",
+ Kind: types.NotificationAutomationAwaitingApproval, Title: "approval", ReadAt: &f.now,
+ }
+ svc.Notify(f.ctx, approval)
+ require.NoError(t, svc.MarkRead(f.ctx, nil))
+ require.NoError(t, svc.ClearRead(f.ctx))
+ page, err = svc.List(f.ctx, 20, false, "")
+ require.NoError(t, err)
+ require.Empty(t, page.Items)
+ require.Zero(t, page.Unread)
+ require.Len(t, page.Pending, 1, "mark all read and clear history must never dismiss a pending prompt")
+ require.NoError(t, f.db.First(&types.Notification{}, "id = ?", approval.ID).Error)
+
+ other := types.WithCaller(context.Background(), types.Caller{TenantID: automationTenant, UserID: "other"})
+ otherPage, err := svc.List(other, 20, false, "")
+ require.NoError(t, err)
+ require.Empty(t, otherPage.Pending)
+ other = types.WithCaller(context.Background(), types.Caller{TenantID: automationTenant + 1, UserID: "u"})
+ otherPage, err = svc.List(other, 20, false, "")
+ require.NoError(t, err)
+ require.Empty(t, otherPage.Pending)
+
+ assertPending := func(want int) {
+ t.Helper()
+ page, err := svc.List(f.ctx, 20, false, "")
+ require.NoError(t, err)
+ require.Len(t, page.Pending, want)
+ }
+ for _, status := range []string{
+ types.AgentPromptAnswered, types.AgentPromptExecuting, types.AgentPromptDone,
+ types.AgentPromptCanceled, types.AgentPromptExpired, types.AgentPromptSuperseded,
+ } {
+ require.NoError(t, f.db.Model(prompt).Update("status", status).Error)
+ assertPending(0)
+ }
+ require.NoError(t, f.db.Model(prompt).Update("status", types.AgentPromptSuspended).Error)
+ assertPending(1)
+ require.NoError(t, f.db.Model(prompt).Update("expires_at", f.now).Error)
+ assertPending(0)
+ require.NoError(t, f.db.Model(prompt).Update("expires_at", nil).Error)
+ require.NoError(t, f.db.Model(run).Update("cancel_requested", true).Error)
+ assertPending(0)
+ require.NoError(t, f.db.Model(run).Update("cancel_requested", false).Error)
+ require.NoError(t, f.db.Model(run).Update("status", types.AutomationRunSucceeded).Error)
+ assertPending(0)
+ require.NoError(t, f.db.Model(run).Update("status", types.AutomationRunAwaitingApproval).Error)
+ timedOutAt := f.now.Add(-time.Duration(a.ApprovalTimeoutMinutes) * time.Minute)
+ require.NoError(t, f.db.Model(run).Update("updated_at", timedOutAt).Error)
+ assertPending(0)
+ require.NoError(t, f.db.Model(run).Update("updated_at", f.now).Error)
+ assertPending(1)
+ require.NoError(t, f.db.Delete(a).Error)
+ assertPending(0)
+}
+
+func TestNotificationClearReadOnlyTouchesCallersReadHistory(t *testing.T) {
+ f := newAutomationFixture(t)
+ svc := NewNotificationService(f.db)
+ svc.now = func() time.Time { return f.now }
+ rows := []*types.Notification{
+ {ID: "read", TenantID: automationTenant, UserID: "u", ReadAt: &f.now},
+ {ID: "unread", TenantID: automationTenant, UserID: "u"},
+ {ID: "other-user", TenantID: automationTenant, UserID: "other", ReadAt: &f.now},
+ {ID: "other-tenant", TenantID: automationTenant + 1, UserID: "u", ReadAt: &f.now},
+ }
+ for _, row := range rows {
+ row.Kind = types.NotificationAutomationSucceeded
+ svc.Notify(f.ctx, row)
+ }
+ require.NoError(t, svc.ClearRead(f.ctx))
+ var remaining []types.Notification
+ require.NoError(t, f.db.Order("id").Find(&remaining).Error)
+ require.Len(t, remaining, 3)
+ require.Equal(t, "other-tenant", remaining[0].ID)
+ require.Equal(t, "other-user", remaining[1].ID)
+ require.Equal(t, "unread", remaining[2].ID)
+ require.NoError(t, svc.MarkRead(f.ctx, []string{"unread", "other-user"}))
+ page, err := svc.List(f.ctx, 20, true, "")
+ require.NoError(t, err)
+ require.Empty(t, page.Items)
+ require.EqualValues(t, 1, page.ReadCount)
+ require.Zero(t, page.Unread)
+}
diff --git a/internal/container/container.go b/internal/container/container.go
index 6bfb7ea9e..29206d06e 100644
--- a/internal/container/container.go
+++ b/internal/container/container.go
@@ -739,6 +739,7 @@ func BuildContainer(container *dig.Container) *dig.Container {
return collaboration.StopPrompt(ctx, p)
}
mcp.SetRunResumer(sessions)
+ mcp.SetScheduledPromptRouter(automations.HandlesPrompt)
collaboration.Runtime.Start(context.Background())
automations.Start(context.Background())
}))
diff --git a/internal/database/migration_sqlite_automation_model_test.go b/internal/database/migration_sqlite_automation_model_test.go
new file mode 100644
index 000000000..62e4444f5
--- /dev/null
+++ b/internal/database/migration_sqlite_automation_model_test.go
@@ -0,0 +1,32 @@
+package database
+
+import (
+ "path/filepath"
+ "testing"
+
+ "github.com/stretchr/testify/require"
+)
+
+func TestSQLiteAutomationModelUpgradePreservesDefault(t *testing.T) {
+ repoRoot := sqliteRepoRoot(t)
+ chdirAndRestore(t, copySQLiteMigrationsThrough(t, repoRoot, 48))
+ 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, instruction, trigger_config, limits, created_at, updated_at)
+ VALUES ('task', 1, 'owner', 'Reminder', 'agent', 'Take a break', '{}', '{}',
+ CURRENT_TIMESTAMP, CURRENT_TIMESTAMP)`)
+ require.NoError(t, err)
+ chdirAndRestore(t, repoRoot)
+ require.NoError(t, RunMigrationsWithOptions("sqlite3://unused", opts))
+ var model, name string
+ require.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.Equal(t, "Reminder", name)
+ _, err = db.Exec("UPDATE automations SET model_id = 'chosen-model' WHERE id = 'task'")
+ require.NoError(t, err)
+ require.NoError(t, db.QueryRow("SELECT model_id FROM automations WHERE id = 'task'").Scan(&model))
+ require.Equal(t, "chosen-model", model)
+}
diff --git a/internal/database/migration_sqlite_versioned_schema_test.go b/internal/database/migration_sqlite_versioned_schema_test.go
index 5e72bf994..1f0ef4730 100644
--- a/internal/database/migration_sqlite_versioned_schema_test.go
+++ b/internal/database/migration_sqlite_versioned_schema_test.go
@@ -52,6 +52,7 @@ var versionedSQLiteTables = []string{
// versionedSQLiteColumns maps each existing table to the columns that the
// versioned migrations add and the SQLite baseline was missing.
var versionedSQLiteColumns = map[string][]string{
+ "automations": {"model_id"}, // 000049
"automation_runs": {"execution_duration_ms"}, // 000048
"model_catalog_configs": {"version", "overlay", "history", "updated_by", "updated_at"}, // 000031
"memory_subjects": {"extraction_state"}, // 000094
@@ -87,7 +88,7 @@ var versionedSQLiteColumns = map[string][]string{
}, // 000028
}
-const expectedSQLiteMigrationVersion = 48
+const expectedSQLiteMigrationVersion = 49
func TestSQLiteMigrationsCreateVersionedSchema(t *testing.T) {
repoRoot := sqliteRepoRoot(t)
diff --git a/internal/handler/automation.go b/internal/handler/automation.go
index bfd7327b6..acb0d5b04 100644
--- a/internal/handler/automation.go
+++ b/internal/handler/automation.go
@@ -443,13 +443,14 @@ func (h *AutomationHandler) AddAutomationGrant(c *gin.Context) {
// @Tags 通知
// @Produce json
// @Param limit query int false "条数,最多 100"
+// @Param cursor query string false "上一页返回的 next_cursor"
// @Param unread query bool false "只看未读"
-// @Success 200 {object} map[string]interface{} "{items, unread}"
+// @Success 200 {object} map[string]interface{} "{items, pending, unread, read_count, next_cursor}"
// @Security Bearer
// @Router /notifications [get]
func (h *AutomationHandler) ListNotifications(c *gin.Context) {
limit, _ := strconv.Atoi(c.DefaultQuery("limit", "20"))
- page, err := h.notifications.List(c.Request.Context(), limit, c.Query("unread") == "true")
+ page, err := h.notifications.List(c.Request.Context(), limit, c.Query("unread") == "true", c.Query("cursor"))
if err != nil {
h.fail(c, err)
return
@@ -463,7 +464,7 @@ type markNotificationsReadRequest struct {
// MarkNotificationsRead godoc
// @Summary 标记通知已读
-// @Description ids 为空时全部标记已读
+// @Description ids 为空时将全部通知记录标为已读,不改变待处理事项
// @Tags 通知
// @Accept json
// @Produce json
@@ -480,3 +481,18 @@ func (h *AutomationHandler) MarkNotificationsRead(c *gin.Context) {
}
c.JSON(http.StatusOK, gin.H{"success": true})
}
+
+// ClearReadNotifications removes read notification history without changing work.
+// @Summary 清理已读通知
+// @Tags 通知
+// @Produce json
+// @Success 200 {object} map[string]interface{}
+// @Security Bearer
+// @Router /notifications/read [delete]
+func (h *AutomationHandler) ClearReadNotifications(c *gin.Context) {
+ if err := h.notifications.ClearRead(c.Request.Context()); err != nil {
+ h.fail(c, err)
+ return
+ }
+ c.JSON(http.StatusOK, gin.H{"success": true})
+}
diff --git a/internal/handler/collaboration_prompt_test.go b/internal/handler/collaboration_prompt_test.go
index c81ff82d0..98afb3002 100644
--- a/internal/handler/collaboration_prompt_test.go
+++ b/internal/handler/collaboration_prompt_test.go
@@ -43,3 +43,32 @@ func TestDelegatedPromptAnswerDoesNotBypassDurableScheduler(t *testing.T) {
}
}
}
+
+func TestScheduledPromptAnswerReattachesWithoutStartingChatRun(t *testing.T) {
+ for _, suspended := range []bool{true, false} {
+ t.Run(map[bool]string{true: "suspended", false: "still_running"}[suspended], func(t *testing.T) {
+ recorder := httptest.NewRecorder()
+ ctx, _ := gin.CreateTestContext(recorder)
+ ctx.Request = httptest.NewRequest("POST", "/agent/prompts/p", nil)
+ resumer := &collaborationPromptResumer{delegated: true}
+ handler := &MCPServiceHandler{runResumer: resumer}
+ queued := 0
+ handler.SetScheduledPromptRouter(func(_ context.Context, prompt *types.AgentPrompt) bool {
+ require.Equal(t, "p", prompt.ID)
+ queued++
+ return true
+ })
+ handler.finishResolve(ctx, "p", hitl.Resolution{
+ Prompt: &types.AgentPrompt{ID: "p"}, Resume: suspended,
+ }, nil)
+ require.Equal(t, 200, recorder.Code)
+ require.Equal(t, 1, queued)
+ require.Zero(t, resumer.calls, "the scheduler must retain ownership of automation runs")
+ if suspended {
+ require.JSONEq(t, `{"success":true,"resumed":true}`, recorder.Body.String())
+ } else {
+ require.JSONEq(t, `{"success":true,"resumed":false}`, recorder.Body.String())
+ }
+ })
+ }
+}
diff --git a/internal/handler/mcp_service.go b/internal/handler/mcp_service.go
index b1179bdad..747de5f82 100644
--- a/internal/handler/mcp_service.go
+++ b/internal/handler/mcp_service.go
@@ -34,6 +34,8 @@ type MCPServiceHandler struct {
// runResumer continues a run suspended on an approval once it is
// answered. Nil leaves such answers to the reaper, which closes the run.
runResumer RunResumer
+ // scheduledPrompt queues automation-owned continuations without starting a chat run.
+ scheduledPrompt func(context.Context, *types.AgentPrompt) bool
// grants are the callers' remembered agent approvals.
grants interfaces.AgentGrantRepository
}
@@ -47,6 +49,11 @@ type RunResumer interface {
// SetRunResumer wires the resumer of suspended runs.
func (h *MCPServiceHandler) SetRunResumer(r RunResumer) { h.runResumer = r }
+// SetScheduledPromptRouter routes automation approvals to their scheduler.
+func (h *MCPServiceHandler) SetScheduledPromptRouter(f func(context.Context, *types.AgentPrompt) bool) {
+ h.scheduledPrompt = f
+}
+
// NewMCPServiceHandler creates a new MCP service handler
func NewMCPServiceHandler(
mcpServiceService interfaces.MCPServiceService,
@@ -958,16 +965,21 @@ func (h *MCPServiceHandler) finishResolve(c *gin.Context, pendingID string, res
}
return
}
- // A suspended run has ended; this replica now continues it.
+ // Scheduled runs resume through their scheduler, but the client must still
+ // reattach to their stream after answering a suspended prompt.
+ scheduled := h.scheduledPrompt != nil && h.scheduledPrompt(ctx, res.Prompt)
resumed := res.Resume && h.runResumer != nil
if router, ok := h.runResumer.(interface {
HandlesDelegatedPrompt(context.Context, *types.AgentPrompt) bool
- }); ok && router.HandlesDelegatedPrompt(ctx, res.Prompt) {
+ }); !scheduled && ok && router.HandlesDelegatedPrompt(ctx, res.Prompt) {
resumed = false
}
- if resumed {
+ if resumed && !scheduled {
h.runResumer.ResumeSuspendedRun(c, res.Prompt, res.OwnerGone, res.OwnerLeaseUntil)
}
+ if scheduled {
+ resumed = res.Resume
+ }
c.JSON(http.StatusOK, gin.H{"success": true, "resumed": resumed})
}
@@ -984,7 +996,7 @@ type resolveAgentPromptBody struct {
// @Description tool_approval 为 {approved: bool, modified_args?: object, reason?: string, allow_in_session?: bool};
// @Description page_action 为 {declined?, error?, location?, snapshot?, applied?: [{ref, label?, summary?}],
// @Description stayed?, return_path?}。
-// @Description 返回 resumed=true 表示运行已挂起并在本次回答后恢复,客户端需重新接入该消息的事件流
+// @Description 返回 resumed=true 表示挂起的运行已请求恢复(自动化由调度器恢复),客户端需携带 resume_pending_id 重新接入该消息的事件流
// @Tags Agent
// @Accept json
// @Produce json
diff --git a/internal/handler/session/automation_readonly_test.go b/internal/handler/session/automation_readonly_test.go
new file mode 100644
index 000000000..29564e608
--- /dev/null
+++ b/internal/handler/session/automation_readonly_test.go
@@ -0,0 +1,45 @@
+package session
+
+import (
+ "context"
+ "net/http"
+ "net/http/httptest"
+ "strings"
+ "testing"
+
+ "github.com/Tencent/WeKnora/internal/middleware"
+ "github.com/Tencent/WeKnora/internal/types"
+ "github.com/Tencent/WeKnora/internal/types/interfaces"
+ "github.com/gin-gonic/gin"
+ "github.com/stretchr/testify/require"
+)
+
+type automationConversationStub struct{ interfaces.SessionService }
+
+func (*automationConversationStub) GetOwnedSession(_ context.Context, id string) (*types.Session, error) {
+ return &types.Session{ID: id, Kind: types.SessionKindAutomation}, nil
+}
+
+func TestAutomationConversationRejectsManualMessages(t *testing.T) {
+ gin.SetMode(gin.TestMode)
+ h := &Handler{sessionService: &automationConversationStub{}}
+ r := gin.New()
+ r.Use(middleware.ErrorHandler())
+ r.POST("/knowledge-chat/:session_id", h.KnowledgeQA)
+ r.POST("/agent-chat/:session_id", h.AgentQA)
+ r.POST("/sessions/:session_id/steer", h.SteerMessage)
+ r.POST("/sessions/:session_id/steer/:steer_id/inject", h.PromoteSteerMessage)
+ for _, path := range []string{
+ "/knowledge-chat/session", "/agent-chat/session",
+ "/sessions/session/steer", "/sessions/session/steer/queued/inject",
+ } {
+ t.Run(path, func(t *testing.T) {
+ req := httptest.NewRequest(http.MethodPost, path, strings.NewReader(`{"query":"manual message"}`))
+ req.Header.Set("Content-Type", "application/json")
+ w := httptest.NewRecorder()
+ r.ServeHTTP(w, req)
+ require.Equal(t, http.StatusForbidden, w.Code, w.Body.String())
+ require.Contains(t, w.Body.String(), "automation conversations")
+ })
+ }
+}
diff --git a/internal/handler/session/continue_stream_resume_test.go b/internal/handler/session/continue_stream_resume_test.go
new file mode 100644
index 000000000..fe7cd82aa
--- /dev/null
+++ b/internal/handler/session/continue_stream_resume_test.go
@@ -0,0 +1,85 @@
+package session
+
+import (
+ "context"
+ "net/http"
+ "net/http/httptest"
+ "testing"
+
+ "github.com/Tencent/WeKnora/internal/types"
+ "github.com/Tencent/WeKnora/internal/types/interfaces"
+ "github.com/gin-gonic/gin"
+ "github.com/stretchr/testify/require"
+)
+
+type resumeStreamMessageService struct {
+ interfaces.MessageService
+ completed bool
+}
+
+func (s *resumeStreamMessageService) GetMessage(
+ _ context.Context, sessionID, messageID string,
+) (*types.Message, error) {
+ return &types.Message{ID: messageID, SessionID: sessionID, IsCompleted: s.completed}, nil
+}
+
+func TestContinueStreamWaitsForApprovedSegment(t *testing.T) {
+ for _, tt := range []struct {
+ name string
+ query string
+ marker interfaces.StreamEvent
+ completed bool
+ status int
+ }{
+ {name: "ordinary replay", status: http.StatusOK},
+ {name: "old terminal segment", query: "&resume_pending_id=p", status: http.StatusConflict},
+ {
+ name: "different approval", query: "&resume_pending_id=p", status: http.StatusConflict,
+ marker: interfaces.StreamEvent{
+ Type: types.ResponseTypeAgentQuery, Data: map[string]interface{}{"resume_pending_id": "old"},
+ },
+ },
+ {
+ name: "automation resumed", query: "&resume_pending_id=p", status: http.StatusOK,
+ marker: interfaces.StreamEvent{
+ Type: types.ResponseTypeAgentQuery, Data: map[string]interface{}{"resume_pending_id": "p"},
+ },
+ },
+ {
+ name: "chat resumed", query: "&resume_pending_id=p", status: http.StatusOK,
+ marker: interfaces.StreamEvent{
+ Type: types.ResponseTypeRunResumed, Data: map[string]interface{}{"pending_id": "p"},
+ },
+ },
+ {
+ name: "terminal failure before resume marker", query: "&resume_pending_id=p",
+ completed: true, status: http.StatusOK,
+ },
+ } {
+ t.Run(tt.name, func(t *testing.T) {
+ gin.SetMode(gin.TestMode)
+ r := gin.New()
+ events := []interfaces.StreamEvent{}
+ if tt.marker.Type != "" {
+ events = append(events, tt.marker)
+ }
+ events = append(events, interfaces.StreamEvent{Type: types.ResponseTypeComplete, Done: true})
+ h := &Handler{
+ sessionService: &stubSessionService{},
+ messageService: &resumeStreamMessageService{completed: tt.completed},
+ streamManager: &stubStreamManager{events: events},
+ }
+ r.GET("/sessions/continue-stream/:session_id", h.ContinueStream)
+ recorder := httptest.NewRecorder()
+ request := httptest.NewRequest(http.MethodGet, "/sessions/continue-stream/s?message_id=m"+tt.query, nil)
+ r.ServeHTTP(recorder, request)
+ require.Equal(t, tt.status, recorder.Code, recorder.Body.String())
+ if tt.status == http.StatusConflict {
+ require.NotContains(t, recorder.Body.String(), `"response_type":"complete"`)
+ require.NotContains(t, recorder.Header().Get("Content-Type"), "text/event-stream")
+ } else {
+ require.Contains(t, recorder.Body.String(), `"response_type":"complete"`)
+ }
+ })
+ }
+}
diff --git a/internal/handler/session/qa.go b/internal/handler/session/qa.go
index fe1c8a371..23d532f8e 100644
--- a/internal/handler/session/qa.go
+++ b/internal/handler/session/qa.go
@@ -262,6 +262,9 @@ func (h *Handler) parseQARequest(c *gin.Context, logPrefix string) (*qaRequestCo
logger.Errorf(ctx, "Failed to get session, session ID: %s, error: %v", sessionID, err)
return nil, nil, errors.NewNotFoundError("Session not found")
}
+ if session.Kind == types.SessionKindAutomation {
+ return nil, nil, errors.NewForbiddenError("automation conversations do not accept manual messages")
+ }
// Get custom agent if agent_id is provided. Backend resolves shared agent from share relation (no client-provided tenant).
customAgent, effectiveTenantID, sharedAgentReadOnly := h.resolveAgent(ctx, c, request.AgentID, request.AgentSourceTenantID)
diff --git a/internal/handler/session/steer.go b/internal/handler/session/steer.go
index e0a1be232..ea16379b2 100644
--- a/internal/handler/session/steer.go
+++ b/internal/handler/session/steer.go
@@ -520,12 +520,18 @@ func (h *Handler) SteerMessage(c *gin.Context) {
// Same ownership scope as StopSession: steer mutates an in-flight turn, so
// use the strict owner scope and reject cross-tenant access.
- if _, err := h.sessionService.GetOwnedSession(ctx, sessionID); err != nil {
+ session, err := h.sessionService.GetOwnedSession(ctx, sessionID)
+ if err != nil {
logger.ErrorWithFields(ctx, err, map[string]interface{}{"session_id": sessionID})
_ = c.Error(errors.NewNotFoundError("Session not found"))
return
}
+ if session.Kind == types.SessionKindAutomation {
+ _ = c.Error(errors.NewForbiddenError("automation conversations do not accept manual messages"))
+ return
+ }
+
assistantID, ok := h.resolveLiveAgentRun(ctx, c, sessionID)
if !ok {
return
@@ -651,12 +657,18 @@ func (h *Handler) PromoteSteerMessage(c *gin.Context) {
return
}
- if _, err := h.sessionService.GetOwnedSession(ctx, sessionID); err != nil {
+ session, err := h.sessionService.GetOwnedSession(ctx, sessionID)
+ if err != nil {
logger.ErrorWithFields(ctx, err, map[string]interface{}{"session_id": sessionID})
_ = c.Error(errors.NewNotFoundError("Session not found"))
return
}
+ if session.Kind == types.SessionKindAutomation {
+ _ = c.Error(errors.NewForbiddenError("automation conversations do not accept manual messages"))
+ return
+ }
+
assistantID, ok := h.resolveLiveAgentRun(ctx, c, sessionID)
if !ok {
return
diff --git a/internal/handler/session/stream.go b/internal/handler/session/stream.go
index d30f9555e..4dd2c94d7 100644
--- a/internal/handler/session/stream.go
+++ b/internal/handler/session/stream.go
@@ -26,9 +26,11 @@ import (
// @Produce text/event-stream
// @Param session_id path string true "会话ID"
// @Param message_id query string true "消息ID"
+// @Param resume_pending_id query string false "等待此审批恢复后的事件流"
// @Param resource_urls query string false "文件引用形式,public 返回可加载直链" Enums(handle, public) default(handle)
// @Success 200 {string} string "SSE 事件流"
// @Failure 404 {object} errors.AppError "会话或消息不存在"
+// @Failure 409 {object} errors.AppError "审批恢复后的事件流尚未就绪"
// @Security Bearer
// @Security ApiKeyAuth
// @Router /sessions/continue-stream/{session_id} [get]
@@ -129,6 +131,23 @@ func (h *Handler) ContinueStream(c *gin.Context) {
return
}
+ // A scheduler may not have reset the previous segment yet. Never replay
+ // its terminal event as if the just-approved continuation had completed.
+ if pendingID := c.Query("resume_pending_id"); pendingID != "" && !message.IsCompleted {
+ ready := false
+ for _, evt := range events {
+ if (evt.Type == types.ResponseTypeAgentQuery && evt.Data["resume_pending_id"] == pendingID) ||
+ (evt.Type == types.ResponseTypeRunResumed && evt.Data["pending_id"] == pendingID) {
+ ready = true
+ break
+ }
+ }
+ if !ready {
+ c.JSON(http.StatusConflict, gin.H{"success": false, "error": "The resumed stream is not ready yet"})
+ return
+ }
+ }
+
logger.Infof(
ctx, "Preparing to replay %d events and continue streaming, session ID: %s, message ID: %s",
len(events), sessionID, messageID,
diff --git a/internal/router/routes_automation.go b/internal/router/routes_automation.go
index e1abf5f2a..eef239366 100644
--- a/internal/router/routes_automation.go
+++ b/internal/router/routes_automation.go
@@ -41,5 +41,6 @@ func RegisterAutomationRoutes(r *gin.RouterGroup, h *handler.AutomationHandler,
{
notifications.GET("", h.ListNotifications)
notifications.POST("/read", h.MarkNotificationsRead)
+ notifications.DELETE("/read", h.ClearReadNotifications)
}
}
diff --git a/internal/types/automation.go b/internal/types/automation.go
index 316762fed..c2f44b708 100644
--- a/internal/types/automation.go
+++ b/internal/types/automation.go
@@ -102,6 +102,8 @@ type Automation struct {
// 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 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.
Instruction string `json:"instruction" gorm:"type:text;not null" extensions:"x-agent,x-agent-detail"`
@@ -200,6 +202,8 @@ type AutomationPatch struct {
Description *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
+ 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
diff --git a/migrations/sqlite/000049_automation_model.down.sql b/migrations/sqlite/000049_automation_model.down.sql
new file mode 100644
index 000000000..49a14f420
--- /dev/null
+++ b/migrations/sqlite/000049_automation_model.down.sql
@@ -0,0 +1 @@
+ALTER TABLE automations DROP COLUMN model_id;
diff --git a/migrations/sqlite/000049_automation_model.up.sql b/migrations/sqlite/000049_automation_model.up.sql
new file mode 100644
index 000000000..0a4974072
--- /dev/null
+++ b/migrations/sqlite/000049_automation_model.up.sql
@@ -0,0 +1 @@
+ALTER TABLE automations ADD COLUMN model_id TEXT NOT NULL DEFAULT '';
diff --git a/migrations/versioned/000132_automation_model.down.sql b/migrations/versioned/000132_automation_model.down.sql
new file mode 100644
index 000000000..49a14f420
--- /dev/null
+++ b/migrations/versioned/000132_automation_model.down.sql
@@ -0,0 +1 @@
+ALTER TABLE automations DROP COLUMN model_id;
diff --git a/migrations/versioned/000132_automation_model.up.sql b/migrations/versioned/000132_automation_model.up.sql
new file mode 100644
index 000000000..e22f8c95e
--- /dev/null
+++ b/migrations/versioned/000132_automation_model.up.sql
@@ -0,0 +1 @@
+ALTER TABLE automations ADD COLUMN model_id VARCHAR(64) NOT NULL DEFAULT '';