Self-hosted workflows for coding-agent delivery. Orchestrate CodeBuddy, Codex and Claude Code with scripts and human approval gates. Includes Local workflows for coding assistants.
JavaScript agent-orchestrationagentic-workflowai-agentsai-codingclaude-codecode-reviewcodebuddycodexcoding-agentscursordeveloper-toolshuman-on-the-loopllmmcpmulti-agentsdlcself-hostedsopworkflow-automationworkflow-engine
feat: run scheduled tasks as normal chat turns on the chosen CLI (#146)
crispinhu272b282af8a3df
diff --git a/docs/ai-scheduled-task-capabilities.md b/docs/ai-scheduled-task-capabilities.mdindex 998380bd..f1573748 100644--- a/docs/ai-scheduled-task-capabilities.md+++ b/docs/ai-scheduled-task-capabilities.md@@ -13,17 +13,15 @@| Skill | 与主页现有能力一致,不额外禁用内置 Skill 工具。启动 SOP 后,节点会按原有逻辑装载角色绑定的 Skill。主页与定时对话均未独立提供平台 Skill 绑定和自动装载功能,本次不新增这套机制。 || 结果与产物 | 支持自然语言结果,以及主页相同的草稿提交回退;终止 CLI 后仍按完全权限落库并保留已提交结果。工作区附件和浏览器截图写入定时会话。 |-执行身份沿用原逻辑:优先使用项目 Owner 的 CodeBuddy Key,其次使用任务 Owner;工具访问范围沿用执行账号和当前项目的现有规则。关闭页面不会中断执行,定时任务来源、调度方式和超时时间保持不变。+执行身份是项目 Owner,否则是非共享任务的任务 Owner。用的是所选 CLI 的 Key,不是只能用 CodeBuddy;平台共享的 CodeBuddy Key 不会借给定时任务,Codex / Claude Code 仍要该账号自己的凭据。工具访问范围沿用执行账号和当前项目的现有规则。关闭页面不会中断执行。定时任务没有单独的超时:它就是一轮普通对话,CLI 结束或有人从会话页停止时结束,MCP 网关跟这一轮一起结束。由于任务以项目 Owner 身份、完全权限执行,`/api/schedule-jobs` 的新建、修改、立即运行和删除都要求项目写权限(Owner、平台管理员或非 viewer 成员),列表只返回调用者所在项目的任务;按 id 保存时既校验原项目也校验目标项目。执行身份只由服务端决定(项目 Owner,否则保留原任务 Owner),请求里的 `ownerUserId` 不生效。项目记录已不存在的任务只允许平台管理员或该任务原 Owner 管理。## 实现与验证-- `internal/httpapi/assistant_schedule.go`:不再设置 `DeferSOP`,传入主页完全权限策略。-- `internal/httpapi/assistant.go`:`openScheduledToolSession` 复用 `openAssistantToolSession`,绑定执行账号和定时会话。-- `internal/httpapi/assistant_tasks.go`:两类助手定时任务统一使用完全权限,持久化会话、维护工作区租约,接收终结回复并保存附件。-- `internal/httpapi/assistant_write.go`:定时系统提示词包含主页完全权限的完整系统提示词。-- `TestScheduledToolSessionMatchesFullAccessConversation`:比较两种入口实际工具目录与 MCP 配置,覆盖 SOP、工作区、浏览器等工具。+- `internal/httpapi/assistant_schedule.go`:按所选模型的 CLI 选择执行账号,不再给这一轮单独设超时。+- `internal/httpapi/assistant_tasks.go`:定时任务打开一轮普通对话(`executeGeneration` → `POST /api/assistant/chat`),系统提示词、技能、流式和停止都走主页路径;跑完再把结果写回任务。+- `internal/httpapi/agent_tool_session.go`:工具网关跟当前轮次的 context 一起结束,没有 5 分钟或固定时长的轮次上限。- `TestScheduledAssistantCanDispatchSOP`:通过定时执行链路调用真实平台派发接口,使用内存测试数据和仅含审批节点的 SOP。- `TestScheduledAssistantNativeGatewayKeepsWorkspaceAndTerminalReply`:模拟 CLI 通过本地回环网关提交最终回复,验证执行前会话、租约控制器初始化、绑定和附件留存。diff --git a/docs/api/orchestration.md b/docs/api/orchestration.mdindex cdd0692c..351fcc65 100644--- a/docs/api/orchestration.md+++ b/docs/api/orchestration.md@@ -336,11 +336,11 @@ curl -u "$AGENTFLOW_USER:$AGENTFLOW_PASS" \触发任务可选 `maxDispatch`,配置每次最多成功触发的需求数,取值为 1–10;不配置(或为 0)时默认为 10,旧任务同样适用。自动执行和「立即运行」共用此上限;已有任务、基线阻塞或派发时被跳过的需求不占用名额,其余需求留待后续执行。`lastPulled` 仍记录所有匹配候选数,`lastDispatched` 记录本次实际成功触发数。AI 定时任务不使用此配置。-AI 定时任务(`skipDispatch=true`)字段包括 `id`、`name`、`enabled`、`projectId`、`assistantPrompt` / `assistantModel` / `ownerUserId`、`intervalSec` 或 `cron`。到点用项目 Owner 的 CodeBuddy 按提示词原文执行并自动写入,不扫描需求、不派发 SOP。+AI 定时任务(`skipDispatch=true`)字段包括 `id`、`name`、`enabled`、`projectId`、`assistantPrompt` / `assistantModel` / `ownerUserId`、`intervalSec` 或 `cron`。到点用项目 Owner(否则任务 Owner)在所选 CLI 上的 Key,按提示词原文走与主页相同的对话轮次并自动写入,不扫描需求、不派发 SOP。非 CodeBuddy CLI 仍要该账号自己的凭据,不借用平台共享的 CodeBuddy Key。AI 定时任务固定使用自动执行模式,不受 Studio 对话审批模式影响,平台写入无需逐次人工确认。-AI 定时任务单次执行最长 180 分钟。本实例已有定时任务运行时,到点的 cron 会被跳过,不排队、不在当前任务结束后补跑;等待下一个 cron 时间。手动运行仍返回 `409`。+AI 定时任务没有单独的时长上限:这一轮和普通对话一样,在 CLI 结束或有人从会话页停止时结束;工具网关跟这一轮一起结束。本实例已有定时任务运行时,到点的 cron 会被跳过,不排队、不在当前任务结束后补跑;等待下一个 cron 时间。手动运行仍返回 `409`。### `GET /api/schedule-jobs`@@ -348,7 +348,7 @@ AI 定时任务单次执行最长 180 分钟。本实例已有定时任务运行### `POST|PUT /api/schedule-jobs`-新建或按 `id` 更新,两种方法语义相同。`name` 必填。调度为 `intervalSec`(常用间隔)或 5 段 `cron`(东八区)。`skipDispatch` 为 true 时是 AI 定时任务,必须有 `assistantPrompt`,保存时清空 SOP 字段;否则是触发任务,必须有 `workflowId`,保存时清空提示词。可选 `useIssueWorkflow`。`assistantModel` 取自助手 CodeBuddy 目录。保存时把项目 Owner 记为 `ownerUserId`。更新时若请求未带 `blockers`,保留触发任务已有的基线暂停状态。+新建或按 `id` 更新,两种方法语义相同。`name` 必填。调度为 `intervalSec`(常用间隔)或 5 段 `cron`(东八区)。`skipDispatch` 为 true 时是 AI 定时任务,必须有 `assistantPrompt`,保存时清空 SOP 字段;否则是触发任务,必须有 `workflowId`,保存时清空提示词。可选 `useIssueWorkflow`。`assistantModel` 保存时保留已支持 CLI 的模型(`codex:…`、`claude-code:…`);CodeBuddy 模型仍限制在助手目录内。运行前检查执行账号在该 CLI 上的 Key。保存时把项目 Owner 记为 `ownerUserId`。更新时若请求未带 `blockers`,保留触发任务已有的基线暂停状态。`id` 为空时生成;`projectId` 默认 `platform`;`intervalSec<30` 时重置为 `300`。更新若不提供 `lastRunAt` 会保留已有最近运行字段。成功 `200` 返回 job;校验/存储错误 `400`。diff --git a/docs/deployment.md b/docs/deployment.mdindex c5283bc4..f0da1d7b 100644--- a/docs/deployment.md+++ b/docs/deployment.md@@ -4,7 +4,7 @@`bash scripts/dev.sh` explicitly configures local secrets, starts only this checkout's MySQL service, builds the platform, provisions the `admin` account, installs the missing observability generated columns through an explicit script, applies `migrations/seed/*.sql`, and starts the server on port 8090. Existing catalog definitions are preserved by `INSERT IGNORE`. Keep `.env`, `.local/` and database volumes outside version control.-For a native installation, use Node.js 22+ on the API host and install the CLIs you choose. CodeBuddy is also used for requirement clarification and scheduled assistant tasks:+For a native installation, use Node.js 22+ on the API host and install the CLIs you choose. CodeBuddy is also used for requirement clarification; scheduled assistant tasks use whichever supported CLI the task selects:```bashnpm install --global @tencent-ai/codebuddy-code@@ -93,9 +93,9 @@ The upstream process roles remain `-role api`, `-role worker` and `-role all`. APersonal runners are connected from the execution-machine page with a short-lived binding code. The installer is served at `/runners/install.sh`. `AGENTFLOW_RUNNER_BINARY` can point to binaries with `{os}` and `{arch}` substitutions. Container images bundle Linux/macOS amd64/arm64 runner and gate binaries. Native source installations can build on demand with Go.-A platform administrator can share one CodeBuddy API Key under **Platform administration → Shared CodeBuddy Key** (平台共享 CodeBuddy Key): pick the network environment that issued it and the models members may use (the first is the default). Members without a key of their own then chat and run SOPs on it, limited to those models; a role configured with another model runs on the default and the run says so. Members with their own key keep using it with any model. Scheduled tasks, clarification, reports, bots and run evaluation still need a personal key. The key is stored in the database like personal keys and is never shown again after saving. `AGENTFLOW_ASSISTANT_SPONSOR_LOGIN`, which lent one account's key limited to `deepseek-v4.1-flash`, still applies while no shared key is configured.+A platform administrator can share one CodeBuddy API Key under **Platform administration → Shared CodeBuddy Key** (平台共享 CodeBuddy Key): pick the network environment that issued it and the models members may use (the first is the default). Members without a key of their own then chat and run SOPs on it, limited to those models; a role configured with another model runs on the default and the run says so. Members with their own key keep using it with any model. Scheduled tasks, clarification, reports, bots and run evaluation still need the runner's own key. A scheduled task uses the key for its selected CLI and does not borrow the shared CodeBuddy key. The key is stored in the database like personal keys and is never shown again after saving. `AGENTFLOW_ASSISTANT_SPONSOR_LOGIN`, which lent one account's key limited to `deepseek-v4.1-flash`, still applies while no shared key is configured.-Configure provider credentials in the platform UI, not the host's global CLI configuration. Credentials are bound to the responsible actor by the upstream runtime. The home composer and SOP roles support CodeBuddy, Codex and Claude Code independently. Select the executor beside the home model selector; its API key (and optional Codex/Claude base URL) comes from your personal settings. Changing the executor preserves the draft; saved conversations record the executor used. Main Bot writes still pass through the platform tool gateway and its approval checks. Requirement clarification, scheduled assistant tasks and notifications continue to use CodeBuddy. Live model tests are opt-in; set `AGENTFLOW_LIVE_TESTS=1` only for the acceptance suites that need to load local credentials.+Configure provider credentials in the platform UI, not the host's global CLI configuration. Credentials are bound to the responsible actor by the upstream runtime. The home composer and SOP roles support CodeBuddy, Codex and Claude Code independently. Select the executor beside the home model selector; its API key (and optional Codex/Claude base URL) comes from your personal settings. Changing the executor preserves the draft; saved conversations record the executor used. Main Bot writes still pass through the platform tool gateway and its approval checks. Requirement clarification and notifications continue to use CodeBuddy. A scheduled assistant task can select any supported CLI and runs as an ordinary chat turn; Codex and Claude Code still need that account's own credential. Live model tests are opt-in; set `AGENTFLOW_LIVE_TESTS=1` only for the acceptance suites that need to load local credentials.## Observability schemadiff --git a/internal/httpapi/agent_tool_lifecycle_test.go b/internal/httpapi/agent_tool_lifecycle_test.gonew file mode 100644index 00000000..a9ed818b--- /dev/null+++ b/internal/httpapi/agent_tool_lifecycle_test.go@@ -0,0 +1,192 @@+package httpapi++import (+ "bytes"+ "context"+ "encoding/json"+ "errors"+ "testing"+ "time"++ "agentflow/internal/domain"+)++func TestAgentToolSessionFollowsTurnWithoutDeadline(t *testing.T) {+ for _, mode := range []AgentToolMode{AgentToolAssistant, AgentToolScheduled, AgentToolClarify, AgentToolReport} {+ t.Run(string(mode), func(t *testing.T) {+ ctx, cancel := context.WithCancel(context.Background())+ defer cancel()+ stopped := make(chan struct{})+ session, files, err := startAgentToolSession(ctx, domain.User{ID: 1}, "project", mode, assistantExecMode{}, "", nil, func() { cancel(); close(stopped) }, t.TempDir())+ if err != nil {+ t.Fatal(err)+ }+ defer session.Close()+ defer files.Cleanup()+ // Advance the janitor's clock beyond the old five-minute TTL.+ agentToolSessions.purgeExpired(time.Now().Add(24 * time.Hour))+ if _, ok := agentToolSessions.get(session.Token); !ok || ctx.Err() != nil {+ t.Fatal("a live turn without a deadline lost its tools")+ }+ cancel()+ select {+ case <-stopped:+ case <-time.After(time.Second):+ t.Fatal("cancellation did not clean up the gateway")+ }+ if _, ok := agentToolSessions.get(session.Token); ok {+ t.Fatal("a cancelled turn retained access to its tools")+ }+ if session.finished() {+ t.Fatal("cancellation was mistaken for a submitted reply")+ }+ })+ }+}++func TestAgentToolStandaloneSessionStillExpires(t *testing.T) {+ registry := newAgentToolSessionRegistry()+ session := &AgentToolSession{}+ if err := registry.create(session); err != nil {+ t.Fatal(err)+ }+ if session.ExpiresAt.IsZero() {+ t.Fatal("a binding with no owning context needs a bounded lifetime")+ }+ registry.purgeExpired(time.Now().Add(10 * time.Minute))+ if _, ok := registry.get(session.Token); ok || session.finished() {+ t.Fatal("standalone binding outlived its fallback TTL or claimed a reply")+ }+}++func TestAssistantAndScheduledTaskKeepToolsPastFiveMinutes(t *testing.T) {+ for _, scheduled := range []bool{false, true} {+ name := "ordinary"+ if scheduled {+ name = "scheduled"+ }+ t.Run(name, func(t *testing.T) {+ h, actor := workbenchFixture(t)+ calls := 0+ h.generate = func(ctx context.Context, _ string, _ domain.User) (string, error) {+ calls+++ agentToolSessions.mu.Lock()+ var session *AgentToolSession+ for _, candidate := range agentToolSessions.sessions {+ if candidate.ctx == ctx {+ session = candidate+ break+ }+ }+ agentToolSessions.mu.Unlock()+ if session == nil {+ t.Fatal("turn has no gateway bound to its execution context")+ }+ agentToolSessions.purgeExpired(time.Now().Add(24 * time.Hour))+ if _, ok := agentToolSessions.get(session.Token); !ok || ctx.Err() != nil {+ t.Fatal("long-running generation lost its tools")+ }+ _, err := (&agentToolGateway{}).callTool(context.Background(), session, json.RawMessage(`{"name":"workbench_tool_schema","arguments":{"name":"issues_list"}}`))+ if err != nil {+ t.Fatalf("long-running generation could not call a tool: %v", err)+ }+ return "检查完成", nil+ }+ if scheduled {+ task := assistantTask{Name: "代码扫描", Prompt: "检查代码", ProjectID: "workbench"}+ if err := h.executeAssistantTask(context.Background(), actor, &task); err != nil || task.LastStatus != "ok" {+ t.Fatalf("scheduled generation: status=%s error=%v", task.LastStatus, err)+ }+ } else {+ c, w := workbenchContext(actor, "POST", "/api/assistant/chat", bytes.NewBufferString(`{"sessionId":"long-turn","projectId":"workbench","messages":[{"role":"user","content":"检查代码"}]}`))+ h.chat(c)+ if w.Code != 200 {+ t.Fatalf("ordinary generation: status=%d body=%s", w.Code, w.Body.String())+ }+ }+ if calls != 1 {+ t.Fatalf("generation unexpectedly retried %d times", calls)+ }+ })+ }+}++func TestAgentToolSessionHonorsTurnDeadline(t *testing.T) {+ deadline := time.Now().Add(time.Hour)+ ctx, cancel := context.WithDeadline(context.Background(), deadline)+ defer cancel()+ session, files, err := startAgentToolSession(ctx, domain.User{ID: 1}, "project", AgentToolAssistant, assistantExecMode{}, "", nil, cancel, t.TempDir())+ if err != nil {+ t.Fatal(err)+ }+ defer session.Close()+ defer files.Cleanup()+ if !session.ExpiresAt.Equal(deadline) {+ t.Fatalf("gateway deadline differs from the turn: got %v want %v", session.ExpiresAt, deadline)+ }+ agentToolSessions.purgeExpired(time.Now().Add(10 * time.Minute))+ if _, ok := agentToolSessions.get(session.Token); !ok {+ t.Fatal("gateway expired before the turn deadline")+ }+ agentToolSessions.purgeExpired(deadline)+ if _, ok := agentToolSessions.get(session.Token); ok || ctx.Err() == nil || session.finished() {+ t.Fatal("deadline did not revoke access and cancel execution without submitting a reply")+ }+}++func TestAgentToolSessionRejectsCancelledStart(t *testing.T) {+ ctx, cancel := context.WithCancel(context.Background())+ cancel()+ session, files, err := startAgentToolSession(ctx, domain.User{}, "", AgentToolAssistant, assistantExecMode{}, "", nil, cancel, t.TempDir())+ if session != nil {+ defer session.Close()+ }+ defer files.Cleanup()+ if !errors.Is(err, context.Canceled) {+ t.Fatalf("cancelled turn created a gateway: %v", err)+ }+}++func TestAgentToolSessionClosedWithoutFinalRejectsCalls(t *testing.T) {+ ctx, cancel := context.WithCancel(context.Background())+ defer cancel()+ session := &AgentToolSession{Mode: AgentToolAssistant, ExpiresAt: time.Now().Add(-time.Second), CancelModel: cancel}+ if err := agentToolSessions.create(session); err != nil {+ t.Fatal(err)+ }+ defer session.Close()+ agentToolSessions.purgeExpired(time.Now())+ if ctx.Err() == nil || session.finished() {+ t.Fatal("expired session must cancel execution without claiming a final reply")+ }+ _, err := (&agentToolGateway{}).callTool(context.Background(), session, json.RawMessage(`{"name":"workbench_tool_schema","arguments":{"name":"issues_list"}}`))+ if !errors.Is(err, errAgentToolInvalidSession) {+ t.Fatalf("closed session accepted a tool or claimed a terminal reply: %v", err)+ }+ if err := session.commitFinal(AgentTerminalResult{Kind: AgentTerminalAssistant}); err == nil {+ t.Fatal("expired session accepted a late submission")+ }+}++func TestAgentToolSessionFinalSurvivesCancellationAndClose(t *testing.T) {+ ctx, cancel := context.WithCancel(context.Background())+ defer cancel()+ session, files, err := startAgentToolSession(ctx, domain.User{}, "", AgentToolAssistant, assistantExecMode{}, "", nil, cancel, t.TempDir())+ if err != nil {+ t.Fatal(err)+ }+ defer session.Close()+ defer files.Cleanup()+ reply := assistantReply{Message: "完成", Drafts: []assistantDraft{}}+ if err := session.commitFinal(AgentTerminalResult{Kind: AgentTerminalAssistant, Assistant: &reply}); err != nil {+ t.Fatal(err)+ }+ session.Close()+ if ctx.Err() == nil || !session.finished() {+ t.Fatal("successful terminal submission was lost during cleanup")+ }+ result, ok := session.takeFinal()+ if !ok || result.Assistant == nil || result.Assistant.Message != "完成" {+ t.Fatalf("cleanup lost the committed result: %+v", result)+ }+}diff --git a/internal/httpapi/agent_tool_mcp.go b/internal/httpapi/agent_tool_mcp.goindex 28f4b4a2..83bae6ff 100644--- a/internal/httpapi/agent_tool_mcp.go+++ b/internal/httpapi/agent_tool_mcp.go@@ -8,6 +8,7 @@ import ("io""net/http""strings"+ "time""agentflow/internal/domain""agentflow/internal/engine"@@ -155,6 +156,18 @@ func (h *agentToolGateway) callTool(ctx context.Context, session *AgentToolSessiif session.finished() {return nil, errAgentToolTerminalCommitted}+ if session.closed.Load() || session.expired(time.Now()) {+ return nil, errAgentToolInvalidSession+ }+ if session.ctx != nil {+ // Tool calls arrive on independent HTTP requests. Stopping the model+ // turn must also stop any in-flight work using its gateway.+ callCtx, cancel := context.WithCancel(ctx)+ stop := context.AfterFunc(session.ctx, cancel)+ defer stop()+ defer cancel()+ ctx = callCtx+ }var params struct {Name string `json:"name"`Arguments json.RawMessage `json:"arguments"`diff --git a/internal/httpapi/agent_tool_native.go b/internal/httpapi/agent_tool_native.goindex ad802157..557b0fac 100644--- a/internal/httpapi/agent_tool_native.go+++ b/internal/httpapi/agent_tool_native.go@@ -229,7 +229,7 @@ func startAgentToolSession(ctx context.Context, user domain.User, projectID striProjectID: projectID,Mode: mode,IssueID: issueID,- ExpiresAt: time.Now().Add(agentToolSessionTTL(ctx)),+ ctx: ctx,MCPServers: servers,User: user,ExecMode: exec,diff --git a/internal/httpapi/agent_tool_session.go b/internal/httpapi/agent_tool_session.goindex 5ec19e7d..08f48030 100644--- a/internal/httpapi/agent_tool_session.go+++ b/internal/httpapi/agent_tool_session.go@@ -46,8 +46,9 @@ type AgentTerminalResult struct {Report *domain.AINotificationContent}-// AgentToolSession is a short-lived, in-process MCP gateway binding for one-// model request. The token is CSPRNG random and is never logged or returned to+// AgentToolSession is an in-process MCP gateway binding for one model turn.+// Its lifetime follows the turn, including turns without a deadline.+// The token is CSPRNG random and is never logged or returned to// the browser.type AgentToolSession struct {Token string@@ -93,6 +94,9 @@ type AgentToolSession struct {// The value is the subagent id once the stream reports it.dispatches map[string]stringclosed atomic.Bool+ committed atomic.Bool+ ctx context.Context+ stopContext func() bool // protected by muCancelModel context.CancelFunc}@@ -224,19 +228,6 @@ func newAgentToolSessionToken() (string, error) {return hex.EncodeToString(raw[:]), nil}-func agentToolSessionTTL(ctx context.Context) time.Duration {- if ctx != nil {- if deadline, ok := ctx.Deadline(); ok {- d := time.Until(deadline)- if d < time.Second {- return time.Second- }- return d- }- }- return agentToolSessionDefaultTTL-}-func (r *agentToolSessionRegistry) create(session *AgentToolSession) error {if session == nil {return errAgentToolInvalidSession@@ -253,15 +244,29 @@ func (r *agentToolSessionRegistry) create(session *AgentToolSession) error {if session.Final == nil {session.Final = make(chan AgentTerminalResult, 1)}- if session.ExpiresAt.IsZero() {+ if session.ctx != nil {+ if err := session.ctx.Err(); err != nil {+ return err+ }+ // A live turn without a deadline must not inherit the fallback TTL+ // used by standalone bindings. Cancellation and Close revoke it.+ session.ExpiresAt, _ = session.ctx.Deadline()+ } else if session.ExpiresAt.IsZero() {session.ExpiresAt = time.Now().Add(agentToolSessionDefaultTTL)}r.mu.Lock()- defer r.mu.Unlock()if r.sessions == nil {r.sessions = map[string]*AgentToolSession{}}r.sessions[token] = session+ r.mu.Unlock()+ if session.ctx != nil {+ session.mu.Lock()+ if !session.closed.Load() {+ session.stopContext = context.AfterFunc(session.ctx, func() { r.delete(token) })+ }+ session.mu.Unlock()+ }ensureAgentToolJanitor()return nil}@@ -329,6 +334,9 @@ func (s *AgentToolSession) expired(now time.Time) bool {if s == nil {return true}+ if s.ctx != nil && s.ctx.Err() != nil {+ return true+ }return !s.ExpiresAt.IsZero() && !s.ExpiresAt.After(now)}@@ -336,8 +344,14 @@ func (s *AgentToolSession) shutdown() {if s == nil {return}- s.closed.Store(true)- if s.CancelModel != nil {+ closing := s.closed.CompareAndSwap(false, true)+ s.mu.Lock()+ if s.stopContext != nil {+ s.stopContext()+ s.stopContext = nil+ }+ s.mu.Unlock()+ if closing && s.CancelModel != nil {s.CancelModel()}}@@ -350,13 +364,16 @@ func (s *AgentToolSession) Close() {}func (s *AgentToolSession) finished() bool {- return s != nil && s.closed.Load()+ return s != nil && s.committed.Load()}func (s *AgentToolSession) commitFinal(result AgentTerminalResult) error {if s == nil {return errAgentToolInvalidSession}+ if s.expired(time.Now()) {+ return errAgentToolInvalidSession+ }if !s.closed.CompareAndSwap(false, true) {return errAgentToolTerminalCommitted}@@ -364,6 +381,7 @@ func (s *AgentToolSession) commitFinal(result AgentTerminalResult) error {case s.Final <- result:default:}+ s.committed.Store(true)if s.CancelModel != nil {s.CancelModel()}diff --git a/internal/httpapi/assistant.go b/internal/httpapi/assistant.goindex 16fd3896..c1c065be 100644--- a/internal/httpapi/assistant.go+++ b/internal/httpapi/assistant.go@@ -210,7 +210,7 @@ func (h *assistantHandlers) chat(c *gin.Context) {sourceRoot := h.resolvedSourceRoot()fullPrompt := h.turnPrompt(req, sourceRoot, false)turn := fullPrompt- ctx, cancel := context.WithTimeout(c.Request.Context(), assistantChatTimeout)+ ctx, cancel := context.WithCancel(c.Request.Context())defer cancel()var emit func(string, any)var activity assistantActivityLog@@ -238,6 +238,11 @@ func (h *assistantHandlers) chat(c *gin.Context) {var toolFiles agentToolFilesif sess, files, err := h.openAssistantToolSession(modelCtx, user, req.ProjectID, assistantExecModeForApproval(approvalMode), cancelModel); err != nil {logAgentToolEvent("session-fallback", "mode=assistant", "err="+truncateRunes(err.Error(), 160))+ if modelCtx.Err() != nil {+ status, message := assistantGenerationFailure(modelCtx, err)+ c.JSON(status, gin.H{"error": message})+ return+ }c.JSON(502, gin.H{"error": "无法启动工具会话,请重试"})return} else {@@ -437,6 +442,9 @@ func (h *assistantHandlers) chat(c *gin.Context) {return}raw, err := generate(modelCtx, turn, user)+ if err == nil && modelCtx.Err() != nil {+ err = modelCtx.Err()+ }if errors.Is(err, errAssistantCredentialRejected) {fail(400, err.Error())return@@ -683,31 +691,14 @@ func assistantAttachmentTurnNote(messages []assistantMessage) string {}const (- assistantMaxBatch = 1- assistantScheduleTimeout = 180 * time.Minute+ assistantMaxBatch = 1+ // assistantMCPCallTimeout bounds one HTTP call to a user MCP server so a+ // dead server cannot hang a tool call. Turns themselves have no time+ // limit, like the Codex and Claude Code CLIs: they end when the CLI+ // finishes or the user stops them.+ assistantMCPCallTimeout = 60 * time.Minute)-// assistantChatTimeout bounds one assistant turn. A turn that edits code,-// runs tests and reviews the diff can legitimately need more than the old 30-// minute cap, which cut long code changes off before the final answer.-// Operators can extend it with AGENTFLOW_ASSISTANT_CHAT_TIMEOUT (Go-// duration, 5m..4h); the range keeps a stuck generation from holding its-// workspace lease forever.-var assistantChatTimeout = assistantTurnTimeout()--func assistantTurnTimeout() time.Duration {- const fallback = 60 * time.Minute- raw := strings.TrimSpace(os.Getenv("AGENTFLOW_ASSISTANT_CHAT_TIMEOUT"))- if raw == "" {- return fallback- }- parsed, err := time.ParseDuration(raw)- if err != nil || parsed < 5*time.Minute || parsed > 4*time.Hour {- return fallback- }- return parsed-}-func assistantNativeRetryPrompt() string {return "本轮尚未完成,请沿当前上下文继续,核对已执行操作,避免重复写入。需要待确认操作时通过 mcp__agentflow_session__submit_assistant_reply 提交完整草稿;普通问答和已实际完成的操作用自然语言总结结果;若工具参数校验失败,修正字段后再提交。不要提交空草稿或进度占位回复。"}@@ -1478,7 +1469,7 @@ func prepareAssistantCommand(opts assistantCommandOpts) (runtime.CommandSpec, ersys = assistantSystemPromptText()}// Use the CLI's unlimited value; omitting the flag retains a finite default.- // The conversation deadline and explicit cancellation still stop execution.+ // A turn has no deadline; explicit cancellation still stops execution.args := []string{"-p", "--max-turns", nativeAssistantUnlimitedTurns, "--system-prompt", sys, "--output-format", "stream-json", "--include-partial-messages", "--mcp-config", opts.Config}if strings.TrimSpace(opts.Settings) != "" {args = append(args, "--settings", opts.Settings)@@ -1527,18 +1518,6 @@ func (h *assistantHandlers) openAssistantToolSession(ctx context.Context, user dreturn startAgentToolSession(ctx, user, projectID, AgentToolAssistant, exec, "", h.assistantHTTPMCPs(projectID, user.ID), cancel, filepath.Join(assistantSessionRoot(user.ID), "mcp-sessions"))}-func (h *assistantHandlers) openScheduledToolSession(ctx context.Context, user domain.User, projectID, sessionID string, cancel context.CancelFunc) (*AgentToolSession, agentToolFiles, error) {- // Use the same gateway and policy as a homepage conversation in full-access- // mode, so scheduled runs inherit its platform, MCP and workspace tools.- session, files, err := h.openAssistantToolSession(ctx, user, projectID, assistantExecModeForApproval(AssistantApprovalAuto), cancel)- if err != nil {- return nil, files, err- }- session.ChatSessionID = sessionID- session.ChatOwnerID = user.ID- return session, files, nil-}-func (h *assistantHandlers) assistantHTTPMCPs(projectID string, userID int64) []domain.MCPServerDefinition {if h == nil || h.repo == nil {return nildiff --git a/internal/httpapi/assistant_engines.go b/internal/httpapi/assistant_engines.goindex 18319b42..c533f463 100644--- a/internal/httpapi/assistant_engines.go+++ b/internal/httpapi/assistant_engines.go@@ -282,6 +282,18 @@ func assistantAllowedUserModel(id string, catalog assistantModelCatalog, user doreturn engine + ":" + model}+// assistantScheduledModel normalizes the model of an AI scheduled task on+// save. The run uses the project owner's keys, not the editor's, so a+// well-formed CLI model is kept as-is; the owner's key for that CLI is+// checked when it runs.+func assistantScheduledModel(id string, catalog assistantModelCatalog) string {+ engine, model := assistantModelEngine(id)+ if engine != assistantEngineCodeBuddy && assistantValidEngineModel(model) {+ return engine + ":" + model+ }+ return assistantAllowedModel(id, catalog)+}+// assistantEngineModels lists the Codex / Claude Code models the user can// chat with: the list from 个人配置 when set, otherwise the models the Base// URL publishes, otherwise the built-in executor catalog.diff --git a/internal/httpapi/assistant_failure_test.go b/internal/httpapi/assistant_failure_test.goindex a2cf834e..50663496 100644--- a/internal/httpapi/assistant_failure_test.go+++ b/internal/httpapi/assistant_failure_test.go@@ -5,6 +5,7 @@ import ("context""encoding/json""errors"+ "fmt""net/http""os""path/filepath"@@ -88,6 +89,46 @@ func TestPrivateAssistantReportsExecutionFailureWithoutReplayingTools(t *testing}}+func TestAssistantClosedToolSessionDoesNotRetrySubmission(t *testing.T) {+ for _, processError := range []bool{true, false} {+ t.Run(fmt.Sprintf("process_error=%t", processError), func(t *testing.T) {+ h, actor := workbenchFixture(t)+ calls := 0+ h.generate = func(ctx context.Context, _ string, _ domain.User) (string, error) {+ calls+++ if calls > 1 {+ return "", context.Canceled+ }+ agentToolSessions.mu.Lock()+ var session *AgentToolSession+ for _, candidate := range agentToolSessions.sessions {+ if candidate.ChatSessionID == "closed-tool-session" && candidate.UserID == actor.ID {+ session = candidate+ break+ }+ }+ agentToolSessions.mu.Unlock()+ if session == nil {+ t.Fatal("turn did not create its tool session")+ }+ session.Close()+ if ctx.Err() == nil {+ t.Fatal("closing the gateway did not cancel the model")+ }+ if processError {+ return "", ctx.Err()+ }+ return "", nil+ }+ c, w := workbenchContext(actor, "POST", "/api/assistant/chat", bytes.NewBufferString(`{"sessionId":"closed-tool-session","projectId":"workbench","messages":[{"role":"user","content":"检查代码"}]}`))+ h.chat(c)+ if calls != 1 || w.Code != http.StatusGatewayTimeout || !strings.Contains(w.Body.String(), "取消或超时") {+ t.Fatalf("cancelled execution retried or lost its cause: calls=%d status=%d body=%s", calls, w.Code, w.Body.String())+ }+ })+ }+}+func TestFailedSharedGenerationSnapshotKeepsCauseAndRetryHistory(t *testing.T) {for _, tc := range []struct {name, want stringdiff --git a/internal/httpapi/assistant_generation.go b/internal/httpapi/assistant_generation.goindex cc8c1f41..bc741428 100644--- a/internal/httpapi/assistant_generation.go+++ b/internal/httpapi/assistant_generation.go@@ -12,7 +12,6 @@ import ("github.com/gin-gonic/gin""net/http""strings"- "sync""time")@@ -255,52 +254,11 @@ func (w *generationHTTPWriter) Write(p []byte) (int, error) {func (w *generationHTTPWriter) Flush() {}func (h *assistantHandlers) executeGeneration(parent context.Context, req assistantRequest, g domain.AssistantGeneration, actor *auth.User) {- ctx, cancel := context.WithTimeout(parent, assistantChatTimeout)+ ctx, cancel := context.WithCancel(parent)defer cancel()- var mu sync.Mutex- sequence := 0- eventBytes := 0- var projection assistantStreamProjection- live := &assistantLiveGeneration{changed: make(chan struct{})}- live.read = func() domain.AssistantGeneration {- mu.Lock()- defer mu.Unlock()- copy := g- copy.Events = append([]domain.AssistantGenerationEvent(nil), g.Events...)- copy.Stream = projection.snapshot(sequence)- return copy- }- assistantLiveGenerations.Store(g.ID, live)- defer assistantLiveGenerations.Delete(g.ID)- sink := func(kind string, value any) {- mu.Lock()- defer func() { mu.Unlock(); live.publish() }()- raw, _ := json.Marshal(value)- switch kind {- case "thought":- if len(raw) > 256<<10 {- return- }- sequence++- projection.add(raw)- eventBytes += len(raw)- g.Events = append(g.Events, domain.AssistantGenerationEvent{Sequence: sequence, Data: raw})- for len(g.Events) > 500 || eventBytes > 2<<20 {- eventBytes -= len(g.Events[0].Data)- g.Events = g.Events[1:]- }- case "result":- g.Reply = raw- case "workspace_warning":- g.WorkspaceWarning = fmt.Sprint(value)- case "error":- var e struct {- Error string `json:"error"`- }- _ = json.Unmarshal(raw, &e)- g.Error = e.Error- }- }+ rec := newAssistantGenerationRecorder(g)+ defer rec.close()+ sink := rec.sinkstopped := make(chan struct{})done := make(chan struct{})go func() {@@ -319,19 +277,14 @@ func (h *assistantHandlers) executeGeneration(parent context.Context, req assist}old, ok := h.repo.AssistantGeneration(g.UserID, g.SessionID)if ok && old.ID == g.ID && old.Steer != nil {- mu.Lock()- g.Steer = old.Steer- mu.Unlock()+ rec.mu.Lock()+ rec.g.Steer = old.Steer+ rec.mu.Unlock()}if !ok || old.ID != g.ID || old.Status != "running" || old.CancelRequested {cancel()}- mu.Lock()- copy := g- copy.Events = append([]domain.AssistantGenerationEvent(nil), g.Events...)- copy.Stream = projection.snapshot(sequence)- mu.Unlock()- if err := h.repo.CheckpointAssistantGeneration(copy); err != nil {+ if err := h.repo.CheckpointAssistantGeneration(rec.snapshot()); err != nil {cancel()}}@@ -359,7 +312,8 @@ func (h *assistantHandlers) executeGeneration(parent context.Context, req assist}()close(stopped)<-done- mu.Lock()+ rec.mu.Lock()+ g = rec.gif req.workspaceToken != "" {saveCtx, stop := context.WithTimeout(context.WithoutCancel(parent), 30*time.Second)if err := h.engine.EndConversationWorkspaceUse(saveCtx, req.RunID, req.workspaceToken); err != nil {@@ -384,21 +338,18 @@ func (h *assistantHandlers) executeGeneration(parent context.Context, req assistif ctx.Err() != nil {g.Status = "cancelled"g.Error = "生成已停止"- if ctx.Err() == context.DeadlineExceeded {- g.Status = "failed"- g.Error = "生成超时,尚未完成;已有执行记录已保留,请核对后继续。"- }}}- g.Stream = projection.snapshot(sequence)+ rec.g = g+ g = rec.snapshotLocked()steer := g.Steer- mu.Unlock()+ rec.mu.Unlock()if steer == nil {if latest, ok := h.repo.AssistantGeneration(g.UserID, g.SessionID); ok && latest.ID == g.ID && latest.Steer != nil {- mu.Lock()+ rec.mu.Lock()g.Steer = latest.Steersteer = latest.Steer- mu.Unlock()+ rec.mu.Unlock()}}// A stop or a mid-turn redirect keeps the paragraphs and tool rows written@@ -412,7 +363,7 @@ func (h *assistantHandlers) executeGeneration(parent context.Context, req assistif err := h.repo.CheckpointAssistantGeneration(g); err != nil {fmt.Printf("assistant generation checkpoint failed: %T\n", err)}- live.publish()+ rec.live.publish()if steer != nil {h.followSteer(parent, g, steer, actor)}diff --git a/internal/httpapi/assistant_generation_recorder.go b/internal/httpapi/assistant_generation_recorder.gonew file mode 100644index 00000000..3a198828--- /dev/null+++ b/internal/httpapi/assistant_generation_recorder.go@@ -0,0 +1,85 @@+package httpapi++import (+ "encoding/json"+ "fmt"+ "sync"++ "agentflow/internal/domain"+)++// assistantGenerationRecorder accumulates a running turn's stream events into+// its generation record and publishes them to live SSE readers. Chat turns and+// scheduled runs share it so both stream to the conversation page the same way.+type assistantGenerationRecorder struct {+ mu sync.Mutex+ g domain.AssistantGeneration+ sequence int+ eventBytes int+ projection assistantStreamProjection+ live *assistantLiveGeneration+}++// newAssistantGenerationRecorder registers g as live; call close when the+// turn's final state has been checkpointed.+func newAssistantGenerationRecorder(g domain.AssistantGeneration) *assistantGenerationRecorder {+ r := &assistantGenerationRecorder{g: g, live: &assistantLiveGeneration{changed: make(chan struct{})}}+ r.live.read = r.snapshot+ assistantLiveGenerations.Store(g.ID, r.live)+ return r+}++func (r *assistantGenerationRecorder) close() { assistantLiveGenerations.Delete(r.g.ID) }++// snapshotLocked copies the generation with its current stream projection.+func (r *assistantGenerationRecorder) snapshotLocked() domain.AssistantGeneration {+ copy := r.g+ copy.Events = append([]domain.AssistantGenerationEvent(nil), r.g.Events...)+ copy.Stream = r.projection.snapshot(r.sequence)+ return copy+}++func (r *assistantGenerationRecorder) snapshot() domain.AssistantGeneration {+ r.mu.Lock()+ defer r.mu.Unlock()+ return r.snapshotLocked()+}++// sink records one chat-protocol event ("thought", "result", "error",+// "workspace_warning") and wakes live readers.+func (r *assistantGenerationRecorder) sink(kind string, value any) {+ r.mu.Lock()+ defer func() { r.mu.Unlock(); r.live.publish() }()+ raw, _ := json.Marshal(value)+ switch kind {+ case "thought":+ if len(raw) > 256<<10 {+ return+ }+ r.sequence+++ r.projection.add(raw)+ r.eventBytes += len(raw)+ r.g.Events = append(r.g.Events, domain.AssistantGenerationEvent{Sequence: r.sequence, Data: raw})+ for len(r.g.Events) > 500 || r.eventBytes > 2<<20 {+ r.eventBytes -= len(r.g.Events[0].Data)+ r.g.Events = r.g.Events[1:]+ }+ case "result":+ r.g.Reply = raw+ case "workspace_warning":+ r.g.WorkspaceWarning = fmt.Sprint(value)+ case "error":+ var e struct {+ Error string `json:"error"`+ }+ _ = json.Unmarshal(raw, &e)+ r.g.Error = e.Error+ }+}++// activity is the turn's tool/thinking log for the stored transcript.+func (r *assistantGenerationRecorder) activity() []domain.AssistantActivityEvent {+ r.mu.Lock()+ defer r.mu.Unlock()+ return r.projection.activity.snapshot()+}diff --git a/internal/httpapi/assistant_mcp.go b/internal/httpapi/assistant_mcp.goindex c3894891..e1b58e5e 100644--- a/internal/httpapi/assistant_mcp.go+++ b/internal/httpapi/assistant_mcp.go@@ -346,7 +346,7 @@ func (h *assistantHandlers) callAssistantMCP(user domain.User, projectID string,if err != nil || target.Host == "" || (target.Scheme != "http" && target.Scheme != "https") {return "", fmt.Errorf("MCP %s 的 URL 无效", server.Name)}- client := mcpclient.New(bound.URL, bound.Headers).WithTimeout(assistantChatTimeout)+ client := mcpclient.New(bound.URL, bound.Headers).WithTimeout(assistantMCPCallTimeout)tool := strings.TrimSpace(call.Tool)if tool == "" || tool == "tools/list" {tools, err := client.ListTools()diff --git a/internal/httpapi/assistant_mcp_test.go b/internal/httpapi/assistant_mcp_test.goindex 3561e4d6..452eaf16 100644--- a/internal/httpapi/assistant_mcp_test.go+++ b/internal/httpapi/assistant_mcp_test.go@@ -231,6 +231,7 @@ func TestScheduledTaskKeepsPlaintextAndDoesNotParseJSON(t *testing.T) {if !ok {t.Fatal("user")}+ joinScheduledProject(t, st, "platform", user.ID)if err := st.PutIssue(domain.Issue{ID: "iss-native", ProjectID: "platform", Title: "keep", Status: "backlog", Source: "tapd",}); err != nil {diff --git a/internal/httpapi/assistant_schedule.go b/internal/httpapi/assistant_schedule.goindex c1637820..d7be674a 100644--- a/internal/httpapi/assistant_schedule.go+++ b/internal/httpapi/assistant_schedule.go@@ -27,7 +27,7 @@ func (h *assistantHandlers) prepareScheduleJob(job domain.ScheduleJob) (string,if prompt == "" {return "", nil}- user, err := h.scheduleJobAssistantUser(job)+ user, err := h.scheduleJobAssistantUser(job, job.AssistantModel)if err != nil {return "", err}@@ -38,29 +38,32 @@ func (h *assistantHandlers) prepareScheduleJob(job domain.ScheduleJob) (string,ProjectID: job.ProjectID,Notifications: domain.CloneNotificationBindings(job.Notifications),}- ctx, cancel := context.WithTimeout(context.Background(), assistantScheduleTimeout)- defer cancel()- ctx = withAssistantExecMode(ctx, assistantExecModeForApproval(AssistantApprovalAuto))+ ctx := withAssistantExecMode(context.Background(), assistantExecModeForApproval(AssistantApprovalAuto))ctx = withAssistantSessionOrigin(ctx, domain.AssistantSourceScheduled, job.ID)if err := h.executeAssistantTask(ctx, user, &task); err != nil {if msg := strings.TrimSpace(task.LastError); msg != "" {return task.LastMessage, fmt.Errorf("%s", msg)}- if errors.Is(err, context.DeadlineExceeded) || errors.Is(err, context.Canceled) {- return task.LastMessage, fmt.Errorf("生成已取消或超时")+ if errors.Is(err, context.Canceled) {+ return task.LastMessage, fmt.Errorf("生成已停止")}return task.LastMessage, err}return firstNonEmpty(task.NotificationResult, task.LastMessage), nil}-func (h *assistantHandlers) scheduleJobAssistantUser(job domain.ScheduleJob) (domain.User, error) {+// scheduleJobAssistantUser picks whose keys run the job: the project owner,+// else (for a non-shared job) its owner. The model's CLI decides which key+// they need. A scheduled run does not borrow the platform shared CodeBuddy key.+func (h *assistantHandlers) scheduleJobAssistantUser(job domain.ScheduleJob, model string) (domain.User, error) {+ engine, _ := assistantModelEngine(model)try := func(id int64) (domain.User, bool) {if id == 0 || h.repo == nil {return domain.User{}, false}user, ok := h.repo.User(id)- return user, ok && strings.TrimSpace(user.CodeBuddyAPIKey) != ""+ key, _ := assistantEngineCredential(user, engine)+ return user, ok && key != ""}if project, ok := h.repo.Project(job.ProjectID); ok {if user, ok := try(project.OwnerID); ok {@@ -72,5 +75,5 @@ func (h *assistantHandlers) scheduleJobAssistantUser(job domain.ScheduleJob) (doreturn user, nil}}- return domain.User{}, fmt.Errorf("执行提示词需要项目 Owner 的 CodeBuddy API Key:请在该账号的个人配置中配置")+ return domain.User{}, fmt.Errorf("执行提示词需要项目 Owner 的 %s API Key:请在该账号的个人配置中配置", assistantEngineLabel(engine))}diff --git a/internal/httpapi/assistant_schedule_permissions_test.go b/internal/httpapi/assistant_schedule_permissions_test.goindex e25189a5..40808ae0 100644--- a/internal/httpapi/assistant_schedule_permissions_test.go+++ b/internal/httpapi/assistant_schedule_permissions_test.go@@ -8,7 +8,6 @@ import ("os""os/exec""path/filepath"- "reflect""slices""strings""testing"@@ -23,50 +22,6 @@ import ("github.com/gin-gonic/gin")-func TestScheduledToolSessionMatchesFullAccessConversation(t *testing.T) {- h, user := workbenchFixture(t)- ctx := context.Background()- scheduled, files, err := h.openScheduledToolSession(ctx, user, "workbench", "scheduled-chat", nil)- if err != nil {- t.Fatal(err)- }- defer scheduled.Close()- defer files.Cleanup()- auto := assistantExecModeForApproval(AssistantApprovalAuto)- home, homeFiles, err := h.openAssistantToolSession(ctx, user, "workbench", auto, nil)- if err != nil {- t.Fatal(err)- }- defer home.Close()- defer homeFiles.Cleanup()- home.ChatSessionID, home.ChatOwnerID = "homepage-chat", user.ID- if scheduled.Mode != home.Mode || scheduled.ExecMode != auto || scheduled.ChatOwnerID != user.ID {- t.Fatalf("scheduled session does not use homepage full access: %+v", scheduled.ExecMode)- }- gateway := &agentToolGateway{deps: h.deps}- names := func(s *AgentToolSession) []string {- var out []string- for _, d := range gateway.buildCatalog(ctx, s) {- out = append(out, d.Name)- }- slices.Sort(out)- return out- }- got, want := names(scheduled), names(home)- if !reflect.DeepEqual(got, want) || !reflect.DeepEqual(scheduled.MCPServers, home.MCPServers) {- t.Fatalf("scheduled and homepage tools differ:\nscheduled=%v\nhome=%v", got, want)- }- for _, name := range []string{"agentflow__issues_dispatch", "agentflow__runs_start", "agentflow__runs_retry", "agentflow__workflows_publish", "agentflow__schedule_jobs_save", "agentflow__schedule_jobs_delete", "workbench_workspace_open", "workbench_workspace_command", "workbench_workspace_submit_mr", "workbench_browser_navigate", "workbench_browser_screenshot"} {- if !slices.Contains(got, name) {- t.Errorf("full-access scheduled session is missing %s", name)- }- }- prompt := assistantScheduledSystemPromptText(auto)- if !strings.Contains(prompt, assistantSystemPromptForMode(AssistantApprovalAuto)) {- t.Fatal("scheduled system prompt must include the homepage full-access prompt")- }-}-func TestScheduledAssistantCanDispatchSOP(t *testing.T) {h, user := workbenchFixture(t)st := h.repo@@ -190,8 +145,8 @@ raise SystemExit(1)if !ok || task.SessionID != sessionID || conv.WorkspaceRunID != "scheduled-workspace" || !slices.Contains(conv.OwnWorkspaceRunIDs, "scheduled-workspace") {t.Fatalf("workspace binding was lost: %+v", conv)}- var reply assistantReply- if err := json.Unmarshal([]byte(conv.Messages[len(conv.Messages)-1].Content), &reply); err != nil || len(reply.Images) != 1 || reply.Images[0].Name != "report.md" {- t.Fatalf("scheduled report attachment was lost: %+v %v", reply.Images, err)+ // Reply files are attachments on the stored reply, as for a chat turn.+ if files := conv.Messages[len(conv.Messages)-1].Attachments; len(files) != 1 || files[0].Name != "report.md" {+ t.Fatalf("scheduled report attachment was lost: %+v", files)}}diff --git a/internal/httpapi/assistant_schedule_test.go b/internal/httpapi/assistant_schedule_test.goindex 390280ce..121efb18 100644--- a/internal/httpapi/assistant_schedule_test.go+++ b/internal/httpapi/assistant_schedule_test.go@@ -15,7 +15,8 @@ import ("agentflow/internal/tracker")-func TestScheduledAssistantReceives180MinuteDeadline(t *testing.T) {+// A scheduled run, like a chat turn, has no time limit.+func TestScheduledAssistantHasNoDeadline(t *testing.T) {st, err := repo.OpenTest()if err != nil {t.Fatal(err)@@ -29,10 +30,8 @@ func TestScheduledAssistantReceives180MinuteDeadline(t *testing.T) {stopped := errors.New("stop test generation")h := &assistantHandlers{deps: &deps{repo: st}, generate: func(ctx context.Context, _ string, _ domain.User) (string, error) {called = true- deadline, ok := ctx.Deadline()- remaining := time.Until(deadline)- if !ok || remaining > 180*time.Minute || remaining < 179*time.Minute {- t.Fatalf("scheduled generation deadline: ok=%v remaining=%s", ok, remaining)+ if deadline, ok := ctx.Deadline(); ok {+ t.Fatalf("scheduled generation has a deadline: %s", time.Until(deadline))}return "", stopped}}@@ -57,6 +56,7 @@ func TestScheduledAssistantAutoWritesWithoutConfirmation(t *testing.T) {t.Fatal(err)}user, _ := st.UserByLoginName("auto-owner")+ joinScheduledProject(t, st, "platform", user.ID)if err := st.PutIssue(domain.Issue{ID: "scheduled-issue", ProjectID: "platform", Title: "keep", Source: "tapd", Status: "backlog"}); err != nil {t.Fatal(err)}diff --git a/internal/httpapi/assistant_task_engines_test.go b/internal/httpapi/assistant_task_engines_test.gonew file mode 100644index 00000000..f4699870--- /dev/null+++ b/internal/httpapi/assistant_task_engines_test.go@@ -0,0 +1,193 @@+package httpapi++import (+ "context"+ "errors"+ "os"+ "path/filepath"+ "strings"+ "testing"+ "time"++ "agentflow/internal/domain"+ "agentflow/internal/repo"+)++func TestAssistantScheduledModelKeepsCLIModels(t *testing.T) {+ catalog := assistantFixedCatalog()+ for in, want := range map[string]string{+ "codex:gpt-6-sol": "codex:gpt-6-sol",+ " claude-code:opus ": "claude-code:opus",+ catalog.Default: catalog.Default,+ "glm-5.3-ioa": catalog.Default,+ "unknown-model": catalog.Default,+ "codex:bad model": catalog.Default,+ "": catalog.Default,+ } {+ if got := assistantScheduledModel(in, catalog); got != want {+ t.Errorf("assistantScheduledModel(%q) = %q, want %q", in, got, want)+ }+ }+}++// A scheduled task on another CLI runs with that CLI's own key, needs no+// CodeBuddy key, and records the CLI on its conversation.+func TestScheduledTaskRunsOnTaskCLI(t *testing.T) {+ st := cvAStore(t)+ _ = st.PutProject(domain.Project{ID: "cli-project", Name: "CLI"})+ _ = st.PutUser(domain.User{LoginName: "codex-only", CodexAPIKey: "codex-secret"})+ user, _ := st.UserByLoginName("codex-only")+ h := &assistantHandlers{deps: &deps{repo: st}}+ task := assistantTask{ID: "cli-job", Name: "巡检", Prompt: "检查", ProjectID: "cli-project", Model: "codex:gpt-6-sol", IntervalSec: 60, Enabled: true}+ h.generate = func(context.Context, string, domain.User) (string, error) { return "完成 codex-secret", nil }+ if err := h.executeAssistantTask(context.Background(), user, &task); err != nil {+ t.Fatalf("codex task = %v %+v", err, task)+ }+ if task.Model != "codex:gpt-6-sol" || strings.Contains(task.LastMessage, "codex-secret") || strings.Contains(task.LastMessage, "[redacted]完") {+ t.Fatalf("codex task result = %+v", task)+ }+ session, _ := st.AssistantSession(user.ID, task.SessionID)+ if session.Model != "codex:gpt-6-sol" || assistantConversationEngine(session.Messages) != assistantEngineCodex {+ t.Fatalf("codex session = model %q engine %q", session.Model, assistantConversationEngine(session.Messages))+ }++ task.Model = "claude-code:opus"+ if err := h.executeAssistantTask(context.Background(), user, &task); err == nil || !strings.Contains(task.LastError, "Claude Code API Key") {+ t.Fatalf("missing claude key = %v %q", err, task.LastError)+ }+ task.Model = ""+ if err := h.executeAssistantTask(context.Background(), user, &task); err == nil || !strings.Contains(task.LastError, "CodeBuddy API Key") {+ t.Fatalf("missing codebuddy key = %v %q", err, task.LastError)+ }+}++func TestScheduleJobAssistantUserNeedsModelCLIKey(t *testing.T) {+ st := cvAStore(t)+ _ = st.PutUser(domain.User{LoginName: "owner-codex", CodexAPIKey: "k"})+ owner, _ := st.UserByLoginName("owner-codex")+ _ = st.PutProject(domain.Project{ID: "owner-project", Name: "Owner", OwnerID: owner.ID})+ h := &assistantHandlers{deps: &deps{repo: st}}+ job := domain.ScheduleJob{ProjectID: "owner-project"}+ if got, err := h.scheduleJobAssistantUser(job, "codex:gpt-6-sol"); err != nil || got.ID != owner.ID {+ t.Fatalf("codex owner = %+v %v", got, err)+ }+ if _, err := h.scheduleJobAssistantUser(job, "glm-5.3-ioa"); err == nil || !strings.Contains(err.Error(), "CodeBuddy") {+ t.Fatalf("codebuddy without key = %v", err)+ }+}++// A scheduled run sees the project's skills in its CLI home, as a chat turn+// does, so the CLI's skill tool can load them.+func TestScheduledTaskWritesProjectSkills(t *testing.T) {+ h, user := workbenchFixture(t)+ if err := h.repo.PutSkill(domain.SkillDefinition{ID: "repo-reader", Name: "repo-reader", ProjectID: "workbench", Description: "读取仓库", Content: "# repo-reader\n读取仓库内容"}); err != nil {+ t.Fatal(err)+ }+ bin := filepath.Join(t.TempDir(), "codebuddy")+ script := `#!/bin/sh+skills=$(ls "$HOME/.codebuddy/skills" 2>/dev/null | tr '\n' ' ')+printf '{"type":"result","result":"skills: %s"}\n' "$skills"+`+ if err := os.WriteFile(bin, []byte(script), 0o700); err != nil {+ t.Fatal(err)+ }+ t.Setenv("AGENTFLOW_CODEBUDDY_BIN", bin)+ task := assistantTask{ID: "skill-job", Name: "skill", ProjectID: "workbench", Prompt: "加载 skill"}+ if err := h.executeAssistantTask(context.Background(), user, &task); err != nil {+ t.Fatalf("run = %v %+v", err, task)+ }+ if !strings.Contains(task.LastMessage, "repo-reader") {+ t.Fatalf("CLI home lacks the project skill: %q", task.LastMessage)+ }+}++// joinScheduledProject makes userID a member of projectID. A scheduled run is+// an ordinary project conversation, so its runner must be able to continue+// that project's conversations.+func joinScheduledProject(t *testing.T, st *repo.Store, projectID string, userID int64) {+ t.Helper()+ p, ok := st.Project(projectID)+ if !ok {+ t.Fatalf("project %s missing", projectID)+ }+ p.Members = append(p.Members, domain.ProjectMember{UserID: userID, Role: "member"})+ if err := st.PutProject(p); err != nil {+ t.Fatal(err)+ }+}++// A scheduled run is an ordinary chat turn: a live generation the page can+// follow, a transcript saved by chat, and the scheduled session's metadata.+func TestScheduledTaskRunsAsChatTurn(t *testing.T) {+ st := cvAStore(t)+ _ = st.PutProject(domain.Project{ID: "turn-project", Name: "Turn"})+ _ = st.PutUser(domain.User{LoginName: "turn-user", CodeBuddyAPIKey: "secret"})+ user, _ := st.UserByLoginName("turn-user")+ h := &assistantHandlers{deps: &deps{repo: st}}+ task := assistantTask{ID: "turn-job", Name: "巡检", Prompt: "检查", ProjectID: "turn-project", IntervalSec: 60, Enabled: true}++ var during domain.AssistantGeneration+ live := false+ h.generate = func(context.Context, string, domain.User) (string, error) {+ during, _ = st.AssistantGeneration(user.ID, task.SessionID)+ _, live = assistantLiveGenerations.Load(during.ID)+ return "巡检完成\n\n```notification\n{\"title\":\"T\",\"summary\":\"S\",\"body\":\"B\"}\n```", nil+ }+ if err := h.executeAssistantTask(context.Background(), user, &task); err != nil {+ t.Fatalf("run = %v %+v", err, task)+ }+ if during.Status != "running" || !live {+ t.Fatalf("generation during run = %+v live=%v", during, live)+ }+ done, _ := st.AssistantGeneration(user.ID, task.SessionID)+ if done.ID != during.ID || done.Status != "completed" {+ t.Fatalf("generation after run = %+v", done)+ }+ if task.LastStatus != "ok" || task.LastMessage != "巡检完成" || !strings.Contains(task.NotificationResult, "```notification") {+ t.Fatalf("task result = %+v", task)+ }+ session, _ := st.AssistantSession(user.ID, task.SessionID)+ if session.Source != domain.AssistantSourceScheduled || session.TaskID != task.ID || session.Title != "定时 · 巡检" {+ t.Fatalf("scheduled session metadata = source %q task %q title %q", session.Source, session.TaskID, session.Title)+ }+ if n := len(session.Messages); n != 2 || session.Messages[1].Model == "" || strings.Contains(session.Messages[1].Content, "```notification") {+ t.Fatalf("stored transcript = %+v", session.Messages)+ }++ first := task.SessionID+ if err := h.executeAssistantTask(context.Background(), user, &task); err != nil {+ t.Fatal(err)+ }+ if _, ok := st.AssistantSession(user.ID, first); ok || task.SessionID == first {+ t.Fatal("a new run must replace the previous scheduled session")+ }+}++// Stopping a scheduled run from its page cancels it like a chat turn.+func TestScheduledTaskStopFromPage(t *testing.T) {+ st := cvAStore(t)+ _ = st.PutProject(domain.Project{ID: "stop-project", Name: "Stop"})+ _ = st.PutUser(domain.User{LoginName: "stop-user", CodeBuddyAPIKey: "secret"})+ user, _ := st.UserByLoginName("stop-user")+ h := &assistantHandlers{deps: &deps{repo: st}}+ task := assistantTask{ID: "stop-job", Name: "巡检", Prompt: "检查", ProjectID: "stop-project", IntervalSec: 60, Enabled: true}+ h.generate = func(ctx context.Context, _ string, _ domain.User) (string, error) {+ g, _ := st.AssistantGeneration(user.ID, task.SessionID)+ if err := st.CancelAssistantGeneration(user.ID, task.SessionID, g.ID); err != nil {+ t.Error(err)+ }+ select {+ case <-ctx.Done():+ return "", ctx.Err()+ case <-time.After(5 * time.Second):+ return "", errors.New("run was not cancelled")+ }+ }+ if err := h.executeAssistantTask(context.Background(), user, &task); err == nil {+ t.Fatal("stopped run reported success")+ }+ g, _ := st.AssistantGeneration(user.ID, task.SessionID)+ if g.Status != "cancelled" || task.LastStatus != "error" {+ t.Fatalf("stopped generation = %+v task = %+v", g, task)+ }+}diff --git a/internal/httpapi/assistant_tasks.go b/internal/httpapi/assistant_tasks.goindex 5ca0e9b3..57efff12 100644--- a/internal/httpapi/assistant_tasks.go+++ b/internal/httpapi/assistant_tasks.go@@ -2,6 +2,7 @@ package httpapiimport ("context"+ "encoding/json""errors""flag""log"@@ -129,11 +130,16 @@ func (h *assistantHandlers) runTaskNow(c *gin.Context) {return}user, ok := h.repo.User(current.ID)- if !ok || strings.TrimSpace(user.CodeBuddyAPIKey) == "" {- c.JSON(400, gin.H{"error": "请先在个人配置中配置自己的 CodeBuddy API Key"})+ task, err := loadAssistantTask(h.repo, current.ID, c.Param("id"))+ engine, _ := assistantModelEngine(task.Model)+ if key, _ := assistantEngineCredential(user, engine); !ok || key == "" {+ msg := "请先在个人配置中配置自己的 CodeBuddy API Key"+ if engine != assistantEngineCodeBuddy {+ msg = assistantEngineMissingKey(engine)+ }+ c.JSON(400, gin.H{"error": msg})return}- task, err := loadAssistantTask(h.repo, current.ID, c.Param("id"))if err != nil {c.JSON(404, gin.H{"error": "定时任务不存在"})return@@ -174,9 +180,7 @@ func (h *assistantHandlers) tickAssistantTasks() {func (h *assistantHandlers) runStoredAssistantTask(user domain.User, task assistantTask) {defer inflightTasks.Add()()- ctx, cancel := context.WithTimeout(context.Background(), assistantChatTimeout)- defer cancel()- ctx = withAssistantSessionOrigin(ctx, domain.AssistantSourceScheduled, task.ID)+ ctx := withAssistantSessionOrigin(context.Background(), domain.AssistantSourceScheduled, task.ID)if err := h.executeAssistantTask(ctx, user, &task); err != nil {if errors.Is(err, errAssistantBusy) {return@@ -186,6 +190,12 @@ func (h *assistantHandlers) runStoredAssistantTask(user domain.User, task assist_ = h.repo.SaveAssistantTaskResult(user.ID, task)}+// executeAssistantTask runs one scheduled task as an ordinary chat turn: it+// opens a conversation with the task's prompt as the user message, runs it+// through the same generation path as the chat page (streaming, stop/steer,+// skills, CLIs, retries, drafts) and reads the outcome back into the task.+// Only the trigger lives here: who runs it, what is asked, the session's+// metadata and how the result is reported.func (h *assistantHandlers) executeAssistantTask(ctx context.Context, user domain.User, task *assistantTask) error {if _, loaded := h.active.LoadOrStore(user.ID, true); loaded {return errAssistantBusy@@ -208,173 +218,107 @@ func (h *assistantHandlers) executeAssistantTask(ctx context.Context, user domaiif strings.TrimSpace(task.ID) != "" {_ = saveAssistantTask(h.repo, user.ID, *task)}+ fail := func(msg string) error {+ task.LastStatus, task.LastError = "error", msg+ return errors.New(msg)+ }- if strings.TrimSpace(user.CodeBuddyAPIKey) == "" {- task.LastStatus = "error"- task.LastError = "未配置 CodeBuddy API Key"- return errors.New(task.LastError)+ // The task's model picks the CLI; a scheduled run needs the runner's own+ // key for it (no sponsor), checked before a conversation is opened.+ engine, _ := assistantModelEngine(task.Model)+ if key, _ := assistantEngineCredential(user, engine); key == "" {+ if engine != assistantEngineCodeBuddy {+ return fail(assistantEngineMissingKey(engine))+ }+ return fail("未配置 CodeBuddy API Key")}- catalog := loadAssistantModels(ctx, user.CodeBuddyInternetEnvironment)- model := assistantAllowedModel(task.Model, catalog)+ model := assistantAllowedUserModel(task.Model, loadAssistantModels(ctx, user.CodeBuddyInternetEnvironment), user)+ cliEngine, _ := assistantModelEngine(model)prevSession := strings.TrimSpace(task.SessionID)sessionID := newAssistantSessionID()- sourceRoot := h.resolvedSourceRoot()- modelCtx, cancelModel := context.WithCancel(ctx)- defer cancelModel()+ now := time.Now().UTC()req := assistantRequest{ApprovalMode: AssistantApprovalAuto,ProjectID: task.ProjectID,SessionID: sessionID,Model: model,- Messages: []assistantMessage{{Role: "user", Content: scheduledAssistantPrompt(*task, mode)}},+ Executor: cliEngine,+ Messages: []assistantMessage{{Role: "user", Content: scheduledAssistantPrompt(*task, mode), AuthorID: user.ID, AuthorName: user.LoginName, CreatedAt: now}},}- // Workspace tools persist their binding on the conversation while running.- // Create it before opening the gateway, including for failed generations.- conversation := assistantConversation{- ID: sessionID, Title: "定时 · " + task.Name, ProjectID: task.ProjectID,- Model: model, Source: origin.Source, TaskID: origin.TaskID, Messages: req.Messages,- }- if err := saveAssistantConversation(h.repo, user.ID, conversation); err != nil {- task.LastStatus, task.LastError = "error", "无法创建定时任务会话"+ g := domain.AssistantGeneration{StartedAt: now, ActorID: user.ID, ActorName: user.LoginName, ID: newAssistantSessionID(), SessionID: sessionID, UserID: user.ID, ProjectID: task.ProjectID, Status: "running", Events: []domain.AssistantGenerationEvent{}, MessageCount: len(req.Messages)}+ pending := assistantConversation{ID: sessionID, Title: "定时 · " + task.Name, ProjectID: task.ProjectID, Model: model, Executor: cliEngine, Source: origin.Source, TaskID: origin.TaskID, Messages: req.Messages}+ if err := h.repo.BeginAssistantGeneration(g, pending); err != nil {+ _ = fail("无法创建定时任务会话")return err}task.SessionID = sessionID- resultSaved := false- defer func() {- if task.LastStatus == "error" && !resultSaved {- conversation.Messages = append(req.Messages, assistantMessage{Role: "assistant", Content: jsonObject(gin.H{"message": task.LastError})})- if err := saveAssistantConversation(h.repo, user.ID, conversation); err != nil {- log.Printf("assistant failed task session save task=%s: %v", origin.TaskID, err)- }- }- }()- var toolFiles agentToolFiles- var toolSession *AgentToolSession- if h.generate == nil {- sess, files, err := h.openScheduledToolSession(modelCtx, user, task.ProjectID, sessionID, cancelModel)- if err != nil {- logAgentToolEvent("session-fallback", "mode=scheduled", "err="+truncateRunes(err.Error(), 160))- task.LastStatus = "error"- task.LastError = "无法启动工具会话"- return err- }- toolFiles = files- toolSession = sess- defer sess.Close()- defer files.Cleanup()- if h.engine != nil {- sess.workspaceTurn = newAssistantWorkspaceTurn(h.engine, cancelModel)- defer func() {- if err := sess.workspaceTurn.close(ctx); err != nil {- log.Printf("scheduled assistant workspace session=%s: %v", sessionID, err)- }- }()- }- }- // Scheduled runs are unattended. Keep the turn reminder aligned with- // the auto-write gateway and scheduled system prompt.- fullPrompt := h.turnPrompt(req, sourceRoot, false)- turn := fullPrompt- systemPrompt := assistantScheduledSystemPromptText(mode)- generate := h.generate- if generate == nil {- resume := false- generate = func(ctx context.Context, prompt string, u domain.User) (string, error) {- cliReq := assistantCLIRequest{Prompt: prompt, Model: model, SessionID: sessionID, Resume: resume, UserID: u.ID, SystemPrompt: systemPrompt, Native: true, MCPConfig: toolFiles.MCPConfig, Settings: toolFiles.Settings}- raw, _, err := runAssistantCLI(ctx, cliReq, u, nil)- resume = true- return raw, err+ task.Model = model++ // Like a chat turn, a scheduled run has no time limit: it ends when the+ // CLI finishes or someone stops it from the conversation page.+ h.executeGeneration(ctx, req, g, domainUserToAuth(user))+ return h.readScheduledTurn(user, task, g, len(req.Messages), prevSession, origin.TaskID)+}++// readScheduledTurn reports the finished turn back onto the task. The reply+// is the message right after the prompt; a steer from the page may have+// continued the conversation after it, which does not change this outcome.+func (h *assistantHandlers) readScheduledTurn(user domain.User, task *assistantTask, g domain.AssistantGeneration, prompts int, prevSession, taskID string) error {+ fail := func(msg string) error {+ task.LastStatus, task.LastError = "error", msg+ return errors.New(msg)+ }+ session, ok := h.repo.AssistantSession(user.ID, g.SessionID)+ var reply *assistantMessage+ if ok && len(session.Messages) > prompts && session.Messages[prompts].Role == "assistant" {+ reply = &session.Messages[prompts]+ }+ if reply == nil || reply.Unfinished != "" {+ msg := ""+ if reply != nil {+ msg = reply.Unfinished}- }- failGenerate := func(err error) error {- task.LastStatus = "error"- task.LastError = "生成失败或超时"- if ctx.Err() != nil {- task.LastError = "生成已取消或超时"+ if latest, found := h.repo.AssistantGeneration(user.ID, g.SessionID); found && latest.ID == g.ID {+ msg = firstNonEmpty(msg, latest.Error)}- if msg := strings.TrimSpace(err.Error()); msg != "" {- task.LastError += ":" + msg+ return fail(firstNonEmpty(strings.TrimSpace(msg), "未返回结果"))+ }+ var content struct {+ Message string `json:"message"`+ Drafts []assistantDraft `json:"drafts"`+ }+ _ = json.Unmarshal([]byte(reply.Content), &content)+ raw := strings.TrimSpace(content.Message)+ message := raw+ // The notification block is for the Bot; the transcript keeps the prose.+ if _, cleaned, has := domain.ParseNotificationResult(raw); has && strings.TrimSpace(cleaned) != "" {+ message = strings.TrimSpace(cleaned)+ var payload map[string]any+ if json.Unmarshal([]byte(reply.Content), &payload) == nil {+ payload["message"] = message+ reply.Content = jsonObject(payload)+ if err := saveAssistantConversation(h.repo, user.ID, session); err != nil {+ log.Printf("scheduled assistant notification strip session=%s: %v", g.SessionID, err)+ }}- log.Printf("assistant task %s generate failed: %v", task.ID, err)- return err- }- var reply assistantReply- if ctx.Err() != nil {- task.LastStatus = "error"- task.LastError = "生成已取消或超时"- return ctx.Err()}- raw, err := generate(modelCtx, turn, user)- if final, ok := toolSession.takeFinal(); ok && final.Assistant != nil {- // Terminal submission cancels the CLI after committing a valid reply.- reply = *final.Assistant- raw, err = reply.Message, nil+ task.NotificationResult = domain.NotificationText(raw, 18000)+ task.LastMessage = truncateRunes(message, 400)+ if message == "" && len(content.Drafts) == 0 {+ return fail("未返回结果")}- if err != nil {- return failGenerate(err)- }- message := strings.TrimSpace(redactAssistantSecrets(strings.ReplaceAll(raw, user.CodeBuddyAPIKey, "[redacted]"), user))- if message == "" {- task.LastStatus = "error"- task.LastError = "未返回结果"- return errors.New(task.LastError)- }- notificationResult := message- _, cleaned, hasNotification := domain.ParseNotificationResult(message)- if hasNotification && strings.TrimSpace(cleaned) != "" {- message = cleaned- }- reply.Message, reply.SessionID = message, sessionID- reply.Images = append(reply.Images, saveAgentReplyFiles(user.ID, toolSession.takeReplyFiles(), task.ProjectID)...)- if strings.TrimSpace(reply.Message) == "" && len(reply.Drafts) == 0 {- if task.LastStatus == "error" {- return errors.New(task.LastError)- }- task.LastStatus = "error"- task.LastError = "未返回结果"- return errors.New(task.LastError)- }- if len(reply.Drafts) > 0 {- reply.Drafts = h.applyAssistantDrafts(ctx, user, req.ProjectID, reply.Drafts)- for _, draft := range reply.Drafts {- if !draft.Saved {- task.LastStatus = "error"- task.LastError = "部分平台写入未落库"- break- }+ // Nobody confirms an unattended run: a write left as a card failed.+ for _, draft := range content.Drafts {+ if !draft.Saved {+ return fail("部分平台写入未落库")}}- stored := append([]assistantMessage{}, req.Messages...)- stored = append(stored, assistantMessage{Role: "assistant", Content: jsonObject(gin.H{"message": reply.Message, "drafts": reply.Drafts, "images": reply.Images})})- if saveErr := saveAssistantConversation(h.repo, user.ID, assistantConversation{- ID: sessionID,- Title: "定时 · " + task.Name,- ProjectID: task.ProjectID,- Model: model,- Source: origin.Source,- TaskID: origin.TaskID,- Messages: stored,- }); saveErr != nil {- log.Printf("assistant task session save failed task=%s: %v", origin.TaskID, saveErr)- } else {- resultSaved = true- if prevSession != "" && prevSession != sessionID {- _ = h.deleteConversation(user.ID, prevSession)- }- if origin.TaskID != "" {- h.deleteScheduledSessionsExcept(origin.TaskID, sessionID)- }+ task.LastStatus, task.LastError = "ok", ""+ if prevSession != "" && prevSession != g.SessionID {+ _ = h.deleteConversation(user.ID, prevSession)}- task.SessionID = sessionID- task.Model = model- if task.LastStatus != "error" {- task.LastStatus = "ok"- task.LastError = ""- }- task.NotificationResult = domain.NotificationText(notificationResult, 18000)- task.LastMessage = truncateRunes(reply.Message, 400)- if task.LastStatus == "error" {- return errors.New(task.LastError)+ if taskID != "" {+ h.deleteScheduledSessionsExcept(taskID, g.SessionID)}return nil}diff --git a/internal/httpapi/assistant_test.go b/internal/httpapi/assistant_test.goindex 39fda9c9..5e64a1f6 100644--- a/internal/httpapi/assistant_test.go+++ b/internal/httpapi/assistant_test.go@@ -436,6 +436,7 @@ func TestAssistantTaskRunUsesFreshSession(t *testing.T) {if !ok {t.Fatal("user")}+ joinScheduledProject(t, st, "platform", user.ID)task, err := normalizeAssistantTask(assistantTask{Name: "巡检", Prompt: "看一下待办", IntervalSec: 60, Enabled: true, ProjectID: "platform"}, assistantTask{})if err != nil {t.Fatal(err)@@ -511,24 +512,6 @@ func TestAssistantStreamEventsDedupRepeatedToolUse(t *testing.T) {}}-func TestAssistantChatTimeoutAllowsLongCodeTurns(t *testing.T) {- if assistantChatTimeout != 60*time.Minute {- t.Fatalf("assistant chat timeout %s", assistantChatTimeout)- }- t.Setenv("AGENTFLOW_ASSISTANT_CHAT_TIMEOUT", "90m")- if got := assistantTurnTimeout(); got != 90*time.Minute {- t.Fatalf("configured timeout %s", got)- }- t.Setenv("AGENTFLOW_ASSISTANT_CHAT_TIMEOUT", "not-a-duration")- if got := assistantTurnTimeout(); got != 60*time.Minute {- t.Fatalf("invalid timeout should fall back, got %s", got)- }- t.Setenv("AGENTFLOW_ASSISTANT_CHAT_TIMEOUT", "30s")- if got := assistantTurnTimeout(); got != 60*time.Minute {- t.Fatalf("out-of-range timeout should fall back, got %s", got)- }-}-func TestAssistantConversationRoundTrip(t *testing.T) {st, err := repo.OpenTest()if err != nil {diff --git a/internal/httpapi/assistant_write.go b/internal/httpapi/assistant_write.goindex 2d3c824f..9774d0e8 100644--- a/internal/httpapi/assistant_write.go+++ b/internal/httpapi/assistant_write.go@@ -64,17 +64,6 @@ func assistantDeferredSOPTool(name string) bool {}}-func assistantScheduledSystemPromptText(mode assistantExecMode) string {- if !mode.AutoWrite {- return assistantSystemPromptText()- }- extra := "这是无人值守定时任务:直接调用当前项目和个人已安装的 MCP,以及 agentflow__* 平台工具。读写都立即生效。issues_save 把需求 id 放在 body.id(也可同时放 path.id)。完成后用自然语言汇报。"- if mode.DeferSOP {- extra += " 不要调用 issues_dispatch、runs_start、schedule_jobs_run、schedule_jobs_save;需要派发 SOP 时请单独创建触发任务。"- }- return assistantSystemPromptForMode(AssistantApprovalAuto) + "\n" + extra-}-func (h *assistantHandlers) mergeIssueSaveBody(body any, path map[string]string) any {if h == nil || h.repo == nil {return bodydiff --git a/internal/httpapi/handler_edges_cases_test.go b/internal/httpapi/handler_edges_cases_test.goindex 874790f5..f1897314 100644--- a/internal/httpapi/handler_edges_cases_test.go+++ b/internal/httpapi/handler_edges_cases_test.go@@ -729,14 +729,14 @@ func TestAssistantTaskGenerationAndWriterBranches(t *testing.T) {task := assistantTask{ID: "cva-r3-empty", Name: "Empty", Prompt: "P", ProjectID: projectID, Enabled: true, IntervalSec: 60}h.generate = func(context.Context, string, domain.User) (string, error) { return " ", nil }- if err := h.executeAssistantTask(context.Background(), user, &task); err == nil || task.LastError != "未返回结果" {+ if err := h.executeAssistantTask(context.Background(), user, &task); err == nil || task.LastStatus != "error" || task.LastError == "" {t.Fatalf("empty result=%+v %v", task, err)}cancelCtx, cancel := context.WithCancel(context.Background())cancel()task.ID = "cva-r3-cancel"h.generate = func(context.Context, string, domain.User) (string, error) { return "unused", nil }- if err := h.executeAssistantTask(cancelCtx, user, &task); err == nil || !strings.Contains(task.LastError, "取消") {+ if err := h.executeAssistantTask(cancelCtx, user, &task); err == nil || !strings.Contains(task.LastError, "停止") {t.Fatalf("cancelled=%+v %v", task, err)}task.ID, task.LastRunAt = "cva-r3-due", time.Now().Add(-2*time.Minute)diff --git a/internal/httpapi/native_prompt_test.go b/internal/httpapi/native_prompt_test.goindex a79aa0c4..1e062e6c 100644--- a/internal/httpapi/native_prompt_test.go+++ b/internal/httpapi/native_prompt_test.go@@ -10,8 +10,6 @@ import (func TestNativePromptsAreToolFirst(t *testing.T) {prompts := []string{assistantSystemPromptText(),- assistantScheduledSystemPromptText(assistantExecMode{AutoWrite: true}),- assistantScheduledSystemPromptText(assistantExecMode{AutoWrite: true, DeferSOP: true}),scheduledAssistantPrompt(assistantTask{Name: "n", Prompt: "p", ProjectID: "platform"}, assistantExecMode{AutoWrite: true}),clarifySystemPrompt("intro", "mcp-step", "focus"),clarifyNativeRetryPrompt(),diff --git a/internal/httpapi/schedule.go b/internal/httpapi/schedule.goindex 732dcbbb..cb950ea9 100644--- a/internal/httpapi/schedule.go+++ b/internal/httpapi/schedule.go@@ -117,7 +117,7 @@ func (h *scheduleHandlers) scheduleJobs(c *gin.Context) {job.IntervalSec = 300}if job.SkipDispatch {- job.AssistantModel = assistantAllowedModel(job.AssistantModel, loadAssistantModels(c.Request.Context(), ""))+ job.AssistantModel = assistantScheduledModel(job.AssistantModel, loadAssistantModels(c.Request.Context(), ""))}if job.ProjectID == "" {job.ProjectID = "platform"diff --git a/web/app/assistant-models.js b/web/app/assistant-models.jsindex ff62c35d..13dd58ed 100644--- a/web/app/assistant-models.js+++ b/web/app/assistant-models.js@@ -37,6 +37,15 @@if (v === 'echo') return 'echo';return 'other';}+ // engineOf names the CLI that runs a model: catalog entries carry it, and a+ // saved "codex:…" id that the viewer cannot list still keeps its prefix.+ function engineOf(id) {+ const listed = (catalog.models || []).find(m => m.id === id);+ if (listed) return listed.engine || 'codebuddy';+ const value = String(id || '');+ const prefix = value.slice(0, Math.max(0, value.indexOf(':')));+ return (catalog.engines || []).some(e => e.id === prefix) ? prefix : 'codebuddy';+ }function modelMeta(id) {return (catalog.models || []).find(m => m.id === id) || {id: id || DEFAULT_MODEL, family: familyOf(id), name: id || DEFAULT_MODEL};}@@ -123,7 +132,7 @@function load() {if (!loading) {loading = fetchCatalog().then(data => {- if (data?.models?.length) catalog = {default: data.default || DEFAULT_MODEL, models: data.models};+ if (data?.models?.length) catalog = {default: data.default || DEFAULT_MODEL, models: data.models, engines: data.engines || []};return catalog;}).catch(() => catalog).finally(() => { loading = null; });}@@ -132,6 +141,7 @@window.AgentFlowAssistantModels = {DEFAULT: DEFAULT_MODEL,catalog: () => catalog,+ engineOf,load,paint,paintItem,diff --git a/web/app/sync-schedule.js b/web/app/sync-schedule.jsindex e829b2a0..7ad71c43 100644--- a/web/app/sync-schedule.js+++ b/web/app/sync-schedule.js@@ -147,6 +147,53 @@ function bindClarifyModelPicker(host){}};}+// The AI 定时任务 model picker: a CLI select narrows the model list to that+// CLI, like the chat composer's CLI switch. The menu is fixed-positioned so the+// modal's scroll area cannot clip it, and opens toward the side with room.+function scheduleEngineModels(engine){+ return (scheduleModelAPI()?.catalog?.().models||[]).filter(m=>(m.engine||'codebuddy')===engine);+}+function scheduleModelEngine(id){+ return scheduleModelAPI()?.engineOf?.(id)||'codebuddy';+}+function paintScheduleEngines(selected){+ const select=$('#scheduleEngine');+ if(!select)return;+ const current=scheduleModelEngine(selected);+ const engines=scheduleModelAPI()?.catalog?.().engines||[];+ const list=engines.length?[...engines]:[{id:'codebuddy',name:'CodeBuddy'}];+ if(!list.some(e=>e.id===current))list.push({id:current,name:current});+ // A CLI without listed models has no key in this account; a saved task+ // keeps its CLI selectable so editing it does not move it elsewhere.+ select.replaceChildren(...list.map(e=>{+ const usable=e.id===current||scheduleEngineModels(e.id).length>0;+ const option=new Option(usable?e.name:`${e.name}(未配置 Key)`,e.id);+ option.disabled=!usable;+ return option;+ }));+ select.value=current;+}+function closeScheduleModelMenu(){+ const host=$('#scheduleModelPicker');+ if(!host)return;+ host.querySelector('.ai-model-menu').hidden=true;+ host.querySelector('[data-model-toggle]').setAttribute('aria-expanded','false');+}+// Call with the menu shown: a short list must sit against its toggle, so the+// placement uses the rendered height, not the maximum.+function placeScheduleModelMenu(toggle,menu){+ const rect=toggle.getBoundingClientRect();+ const width=Math.min(Math.max(rect.width,320),window.innerWidth-24);+ menu.style.width=width+'px';+ menu.style.left=Math.max(12,Math.min(rect.left,window.innerWidth-width-12))+'px';+ menu.style.maxHeight='none';+ const need=Math.min(320,menu.scrollHeight,window.innerHeight-24);+ const below=window.innerHeight-rect.bottom-12,above=rect.top-12;+ const down=below>=need||below>=above;+ const room=Math.min(need,down?below:above);+ menu.style.maxHeight=room+'px';+ menu.style.top=(down?rect.bottom+6:Math.max(12,rect.top-room-6))+'px';+}function bindScheduleModelPicker(){const host=$('#scheduleModelPicker');if(!host||host.dataset.bound)return;@@ -154,28 +201,36 @@ function bindScheduleModelPicker(){const menu=host.querySelector('.ai-model-menu');if(!toggle||!menu)return;host.dataset.bound='1';+ const form=$('#scheduleJobForm');toggle.onclick=e=>{e.stopPropagation();const api=scheduleModelAPI();if(!api)return;const open=menu.hidden;- menu.hidden=!open;- toggle.setAttribute('aria-expanded',open?'true':'false');- if(open){- const selected=$('#scheduleJobForm').elements.assistantModel.value||api.DEFAULT;- api.renderList(menu, selected, id=>{- $('#scheduleJobForm').elements.assistantModel.value=id;- api.paint(toggle, id);- menu.hidden=true;- toggle.setAttribute('aria-expanded','false');- });- }+ closeScheduleModelMenu();+ if(!open)return;+ const selected=form.elements.assistantModel.value||api.DEFAULT;+ api.renderOptions(menu, scheduleEngineModels(scheduleModelEngine(selected)), selected, id=>{+ paintScheduleModel(id);+ closeScheduleModelMenu();+ });+ menu.hidden=false;+ placeScheduleModelMenu(toggle,menu);+ toggle.setAttribute('aria-expanded','true');};- document.addEventListener('click',e=>{- if(host.contains(e.target))return;- menu.hidden=true;- toggle.setAttribute('aria-expanded','false');- });+ const engine=$('#scheduleEngine');+ if(engine)engine.onchange=()=>{+ const api=scheduleModelAPI();+ const models=scheduleEngineModels(engine.value);+ const fallback=engine.value==='codebuddy'?(api?.catalog?.().default||api?.DEFAULT):'';+ const next=models.some(m=>m.id===fallback)?fallback:models[0]?.id;+ if(next)paintScheduleModel(next);+ };+ document.addEventListener('click',e=>{if(!host.contains(e.target))closeScheduleModelMenu()});+ document.addEventListener('keydown',e=>{if(e.key==='Escape')closeScheduleModelMenu()});+ // A fixed menu would drift from its toggle; close it when anything else scrolls.+ document.addEventListener('scroll',e=>{if(!menu.contains(e.target))closeScheduleModelMenu()},true);+ window.addEventListener('resize',closeScheduleModelMenu);}async function loadScheduleModels(){const api=scheduleModelAPI();@@ -192,6 +247,7 @@ function paintScheduleModel(selected){const keep=selected||f.elements.assistantModel.value||catalog.default||api.DEFAULT;f.elements.assistantModel.value=keep;api.paint(host.querySelector('[data-model-toggle]'), keep);+ paintScheduleEngines(keep);}function syncScheduleJobTiming(){const f=$('#scheduleJobForm');if(!f)return;@@ -217,7 +273,7 @@ function syncScheduleJobKind(){f.elements.name.required=kind==='assistant';const assistant=kind==='assistant';$('#scheduleModalTitle').textContent=assistant?'AI 定时任务':'触发配置';- $('#scheduleModalHint').textContent=assistant?'按计划用项目 Owner 的 CodeBuddy 执行提示词,使用与主页 AI 对话相同的完全权限,可调用 SOP、平台工具、工作区及浏览器。':'按计划扫描本项目选定状态、尚未跑过 SOP 的需求,通过基线门禁后派发 SOP。基线冲突会先由对齐 Agent 解决并合入,期间暂停派发。';+ $('#scheduleModalHint').textContent=assistant?'按计划用项目 Owner 在所选 CLI 上的 Key 执行提示词,使用与主页 AI 对话相同的完全权限,可调用 SOP、平台工具、工作区及浏览器。':'按计划扫描本项目选定状态、尚未跑过 SOP 的需求,通过基线门禁后派发 SOP。基线冲突会先由对齐 Agent 解决并合入,期间暂停派发。';$('#scheduleModal').querySelector('.schedule-head').hidden=assistant;$('#scheduleJobList').hidden=assistant||!projectTriggerJob();f.querySelector('[type="submit"]').textContent=assistant?'保存 AI 定时任务':'保存触发配置';@@ -372,7 +428,7 @@ function renderScheduleJobs(){if(count){count.textContent=!dispatch.length?'未配置':scheduleJobRunning(dispatch[0])?'运行中':dispatch[0].enabled?'已启用':'未启用';count.classList.toggle('is-running',dispatch.some(scheduleJobRunning))}const disabled='本实例不执行定时任务;任务可在主实例自动运行。';$('#scheduleRuntimeHint').textContent=canRun?'每个项目使用一份触发配置,修改后保存即可生效。立即运行在服务端执行,关闭页面不会中断。':disabled;- $('#aiScheduleRuntimeHint').textContent=!state.projectFilter?'请先在顶栏选择项目,再管理 AI 定时任务。':canRun?'使用项目 Owner 的 CodeBuddy,以完全权限执行,与主页 AI 对话相同。可调用 SOP、工作区及浏览器工具;关闭页面不会中断执行。':disabled;+ $('#aiScheduleRuntimeHint').textContent=!state.projectFilter?'请先在顶栏选择项目,再管理 AI 定时任务。':canRun?'使用项目 Owner 在所选 CLI 上的 Key,以完全权限执行,与主页 AI 对话相同。可调用 SOP、工作区及浏览器工具;关闭页面不会中断执行。':disabled;$('#aiScheduleProjectName').textContent=currentProject()?.name||'当前项目';$('#aiScheduleCount').textContent=`${assistant.length} 个任务`;$('#newAISchedule').disabled=!state.projectFilter;diff --git a/web/i18n-en.js b/web/i18n-en.jsindex 9e1373b9..23420355 100644--- a/web/i18n-en.js+++ b/web/i18n-en.js@@ -76,3 +76,11 @@ Object.assign(window.LF_I18N_EN,{"结论已保存到平台说明,可直接触发需求执行 SOP":"The conclusion is saved on the platform description. Start the SOP directly","可直接触发需求执行 SOP":"Start the SOP directly"});+Object.assign(window.LF_I18N_EN,{+"CLI 与模型":"CLI and model",+"执行 CLI":"Execution CLI",+"(未配置 Key)":" (no key configured)",+"与 AI 助手相同的 CLI 与模型,到点用项目 Owner 在所选 CLI 上配置的 Key 执行。":"Same CLI and model as the AI assistant. At the scheduled time it runs with the project owner's key for the selected CLI.",+"按计划用项目 Owner 在所选 CLI 上的 Key 执行提示词,使用与主页 AI 对话相同的完全权限,可调用 SOP、平台工具、工作区及浏览器。":"Runs the prompt on schedule with the project owner's key for the selected CLI, using the same full access as the home AI chat, including SOPs, platform tools, the workspace and the browser.",+"使用项目 Owner 在所选 CLI 上的 Key,以完全权限执行,与主页 AI 对话相同。可调用 SOP、工作区及浏览器工具;关闭页面不会中断执行。":"Uses the project owner's key for the selected CLI, with the same full access as the home AI chat. It can call SOPs, workspace and browser tools; closing the page does not stop it."+});diff --git a/web/index.html b/web/index.htmlindex c38d8151..40ad6fde 100644--- a/web/index.html+++ b/web/index.html@@ -1205,16 +1205,21 @@<p class="schedule-field-hint">可填写 1–10,留空默认 10;其余需求在后续执行时继续触发。</p></div><div data-schedule-kind="assistant" hidden>- <label>模型</label>- <div class="schedule-model-field" id="scheduleModelPicker">- <button type="button" class="ai-model-toggle" data-model-toggle aria-haspopup="listbox" aria-expanded="false">- <span class="ai-model-icon" data-family="glm">智</span>- <span data-model-label>GLM-5.3-Flash</span>- <span class="ai-model-caret" aria-hidden="true"></span>- </button>- <div class="ai-model-menu" hidden role="listbox"></div>+ <label for="scheduleEngine">CLI 与模型</label>+ <div class="schedule-model-row">+ <select id="scheduleEngine" class="select" name="assistantEngine" aria-label="执行 CLI">+ <option value="codebuddy">CodeBuddy</option>+ </select>+ <div class="schedule-model-field" id="scheduleModelPicker">+ <button type="button" class="ai-model-toggle" data-model-toggle aria-haspopup="listbox" aria-expanded="false" aria-label="模型">+ <span class="ai-model-icon" data-family="glm">智</span>+ <span data-model-label>GLM-5.3-Flash</span>+ <span class="ai-model-caret" aria-hidden="true"></span>+ </button>+ <div class="ai-model-menu" hidden role="listbox" aria-label="模型"></div>+ </div></div>- <p class="schedule-field-hint">与 AI 助手相同的 CodeBuddy 模型,用项目 Owner 的 Key 调用。</p>+ <p class="schedule-field-hint" id="scheduleModelHint">与 AI 助手相同的 CLI 与模型,到点用项目 Owner 在所选 CLI 上配置的 Key 执行。</p></div><div data-schedule-kind="assistant" data-schedule-prompt hidden><label>提示词</label>diff --git a/web/sync.css b/web/sync.cssindex 25d16076..ca0467c4 100644--- a/web/sync.css+++ b/web/sync.css@@ -93,8 +93,13 @@.schedule-model-field .ai-model-toggle [data-model-label]{flex:1;text-align:left}.schedule-model-field .ai-model-caret{margin-left:auto}.schedule-model-field .ai-model-menu{left:0;right:auto;top:auto;bottom:calc(100% + 6px);min-width:100%;width:max-content;max-width:min(440px,94vw);max-height:min(45vh,320px);z-index:20}+.schedule-model-row{display:grid;grid-template-columns:minmax(140px,200px) minmax(0,1fr);gap:8px;align-items:center}+.schedule-model-row .select{height:40px}+/* Placed by placeScheduleModelMenu; fixed so the modal's scroll area cannot clip it. */+#scheduleModelPicker .ai-model-menu{position:fixed;right:auto;bottom:auto;min-width:0;max-width:calc(100vw - 24px);z-index:100}@media (max-width: 640px){.schedule-timing-row{grid-template-columns:1fr}+ .schedule-model-row{grid-template-columns:1fr}}.button.danger{color:var(--red)}.schedule-job-item{display:flex;flex-direction:column;gap:6px}diff --git a/webtest/tests/sync-schedule.test.mjs b/webtest/tests/sync-schedule.test.mjsindex c74b8bae..07eb1e3b 100644--- a/webtest/tests/sync-schedule.test.mjs+++ b/webtest/tests/sync-schedule.test.mjs@@ -334,3 +334,61 @@ test('late save responses cannot close a newly opened editor',async t=>{assert.equal(form.elements.name.value,'正在编辑的新任务');assert.equal(form.elements.assistantPrompt.value,'new');assert.equal(form.querySelector('[type=submit]').disabled,false);});++test('AI schedule model picker narrows models to the chosen CLI and keeps a saved CLI model', async (t) => {+ const app = await loadApp();+ t.after(app.close);+ app.router.get('/api/assistant/models', () => ({+ default: 'glm-test',+ models: [+ { id: 'glm-test', name: 'GLM Test', family: 'glm' },+ { id: 'claude-test', name: 'Claude Test', family: 'claude' },+ { id: 'codex:gpt-6-sol', name: 'GPT-6-Sol', family: 'gpt', engine: 'codex' },+ ],+ engines: [+ { id: 'codebuddy', name: 'CodeBuddy', configured: true },+ { id: 'codex', name: 'Codex', configured: true },+ { id: 'claude-code', name: 'Claude Code', configured: false },+ ],+ }));+ await app.evaluate(`(async () => {+ fillScheduleJobForm({});+ const f=$('#scheduleJobForm');+ f.elements.jobKind.value='assistant';syncScheduleJobKind();+ await loadScheduleModels();+ })()`);+ const doc = app.document;+ const form = doc.querySelector('#scheduleJobForm');+ const engine = doc.querySelector('#scheduleEngine');+ assert.deepEqual([...engine.options].map(o => [o.value, o.disabled]), [['codebuddy', false], ['codex', false], ['claude-code', true]]);+ assert.match(engine.options[2].textContent, /未配置 Key/);+ assert.equal(engine.value, 'codebuddy');++ const toggle = doc.querySelector('#scheduleModelPicker [data-model-toggle]');+ const menu = doc.querySelector('#scheduleModelPicker .ai-model-menu');+ toggle.click();+ assert.equal(menu.hidden, false);+ assert.deepEqual([...menu.querySelectorAll('.ai-model-option')].map(o => o.dataset.id), ['glm-test', 'claude-test']);+ assert.ok(menu.style.top && menu.style.maxHeight, 'menu is placed against the viewport');+ toggle.click();+ assert.equal(menu.hidden, true);++ engine.value = 'codex';+ engine.dispatchEvent(new app.window.Event('change'));+ assert.equal(form.elements.assistantModel.value, 'codex:gpt-6-sol');+ toggle.click();+ assert.deepEqual([...menu.querySelectorAll('.ai-model-option')].map(o => o.dataset.id), ['codex:gpt-6-sol']);+ menu.querySelector('.ai-model-option').click();+ assert.equal(menu.hidden, true);++ engine.value = 'codebuddy';+ engine.dispatchEvent(new app.window.Event('change'));+ assert.equal(form.elements.assistantModel.value, 'glm-test');++ // A job saved on a CLI this editor has no key for stays on that CLI.+ app.evaluate(`paintScheduleModel('claude-code:opus')`);+ assert.equal(engine.value, 'claude-code');+ assert.equal(engine.selectedOptions[0].disabled, false);+ assert.equal(form.elements.assistantModel.value, 'claude-code:opus');+ assert.match(doc.querySelector('#scheduleModelHint').textContent, /所选 CLI/);+});