From bb6f4fe3ba29260b70832384eb7e1379a13c93cf Mon Sep 17 00:00:00 2001 From: Robert0622 <53806540+Robert0622@users.noreply.github.com> Date: Thu, 19 Nov 2026 10:05:22 +0800 Subject: [PATCH 1/3] fix(schedule): bound AI tasks and wait for SOP outcomes --- docs/ai-scheduled-task-capabilities.md | 8 +- docs/api/README.md | 1 + docs/api/openapi.yaml | 46 ++++++++++ internal/application/operations.go | 3 +- internal/domain/schedule_execution.go | 24 ++++++ internal/domain/sync.go | 3 + internal/httpapi/agent_tool_mcp.go | 4 +- internal/httpapi/assistant_generation.go | 5 ++ internal/httpapi/assistant_schedule.go | 5 +- .../assistant_schedule_permissions_test.go | 28 +++--- internal/httpapi/assistant_schedule_test.go | 64 +++++++++++--- internal/httpapi/assistant_tasks.go | 19 ++++- internal/httpapi/run_wait.go | 85 +++++++++++++++++++ internal/httpapi/run_wait_test.go | 79 +++++++++++++++++ internal/httpapi/schedule.go | 6 ++ internal/httpapi/schedule_test.go | 17 +++- internal/httpapi/server.go | 1 + internal/repo/runs.go | 11 +++ web/app/sync-schedule.js | 4 + web/i18n-en.js | 6 ++ web/index.html | 5 ++ web/schedule_dispatch_limit_test.go | 1 + webtest/tests/sync-schedule.test.mjs | 11 +++ 23 files changed, 402 insertions(+), 34 deletions(-) create mode 100644 internal/httpapi/run_wait.go create mode 100644 internal/httpapi/run_wait_test.go diff --git a/docs/ai-scheduled-task-capabilities.md b/docs/ai-scheduled-task-capabilities.md index 473ffba21..07fd4cb1d 100644 --- a/docs/ai-scheduled-task-capabilities.md +++ b/docs/ai-scheduled-task-capabilities.md @@ -15,15 +15,17 @@ 执行身份由最后保存任务的人决定。未绑定身份的旧任务按项目 Owner、独立任务记录的 Owner 的顺序查找个人凭据。Codex 和 Claude Code 优先使用执行账号的默认个人执行机器上的「账号登录」,需要 Runner 0.10.2 或以上版本,并启用对应 CLI。默认机器离线或未启用账号登录时,任务改用执行账号在个人配置中填写的 API Key,以所选 CLI 和模型在云端执行。Key 缺失或执行失败时记录具体原因。CodeBuddy 缺少个人 Key 时可以使用平台共享 Key,模型限于管理员允许的列表。保存时会校验可用的凭据。 -工具访问范围由执行账号和项目决定。关闭页面后任务继续执行,直到 CLI 结束或在会话页停止。MCP 网关在本轮结束时关闭。 +工具访问范围由执行账号和项目决定。AI 定时任务可配置每轮执行时限 `timeoutMinutes`(1–240 分钟,默认 30 分钟,旧任务自动使用默认值)。关闭页面后任务继续执行,直到 CLI 结束、达到时限或用户在会话页停止。超时会停止 CLI 及本轮 MCP 调用,并在执行记录中显示失败原因。已派发的 SOP 按自己的生命周期运行。 + +提示词要求等待 SOP 结果时,使用 `runs_wait` 传入派发返回的运行 ID。服务端每次最多等 25 秒,读到成功、失败、取消、待人工处理或暂停就返回。窗口到期仍在运行时返回 `timedOut: true`,调用方可以继续等待同一运行。 由于任务以保存人(或项目 Owner)身份、完全权限执行,`/api/schedule-jobs` 的新建、修改、立即运行和删除都要求项目写权限(Owner、平台管理员或非 viewer 成员),列表只返回调用者所在项目的任务;按 id 保存时既校验原项目也校验目标项目。执行身份只由服务端决定,请求里的 `ownerUserId`、`runAsUserId` 不生效。项目记录已不存在的任务只允许平台管理员或该任务原 Owner 管理。 ## 实现与验证 -- `internal/httpapi/assistant_schedule.go`:按所选模型的 CLI 选择执行账号,不再给这一轮单独设超时。 +- `internal/httpapi/assistant_schedule.go`:按所选模型的 CLI 选择执行账号,并把每轮时限传给对话执行。 - `internal/httpapi/assistant_tasks.go`:定时任务打开一轮普通对话(`executeGeneration` → `POST /api/assistant/chat`),系统提示词、技能、流式和停止都走主页路径;跑完再把结果写回任务。 -- `internal/httpapi/agent_tool_session.go`:工具网关跟当前轮次的 context 一起结束,没有 5 分钟或固定时长的轮次上限。 +- `internal/httpapi/agent_tool_session.go`:工具网关随当前轮次结束,在途调用随执行取消。 - `TestScheduledAssistantCanDispatchSOP`:通过定时执行链路调用真实平台派发接口,使用内存测试数据和仅含审批节点的 SOP。 - `TestScheduledAssistantNativeGatewayKeepsWorkspaceAndTerminalReply`:模拟 CLI 通过本地回环网关提交最终回复,验证执行前会话、租约控制器初始化、绑定和附件留存。 diff --git a/docs/api/README.md b/docs/api/README.md index a78eb46b8..d861889fd 100644 --- a/docs/api/README.md +++ b/docs/api/README.md @@ -128,6 +128,7 @@ curl -H "Authorization: Bearer $AGENTFLOW_TOKEN" "$AGENTFLOW_URL/api/health" | `GET`, `POST` | `/api/runs` | | `GET`, `DELETE` | `/api/runs/{runId}` | | `GET` | `/api/runs/{runId}/stream` | +| `GET` | `/api/runs/{runId}/wait` | | `GET` | `/api/runs/{runId}/logs` | | `GET` | `/api/runs/{runId}/logs.txt` | | `GET` | `/api/runs/{runId}/telemetry` | diff --git a/docs/api/openapi.yaml b/docs/api/openapi.yaml index fad8b3b10..dd13807ed 100644 --- a/docs/api/openapi.yaml +++ b/docs/api/openapi.yaml @@ -30,6 +30,46 @@ tags: - name: Analytics - name: Feedback paths: + /api/runs/{id}/wait: + parameters: + - {name: id, in: path, required: true, schema: {type: string}} + get: + tags: [Runs] + operationId: waitForRun + summary: Wait for an SOP result or human action + description: | + Reads the current status of one SOP. Returns as soon as it is succeeded, + failed, cancelled, waiting or paused. If the wait window expires first, + the current status is returned with timedOut=true. + parameters: + - name: timeoutSec + in: query + description: Seconds to wait. Zero reads the current status immediately. + schema: {type: integer, minimum: 0, maximum: 25, default: 25} + responses: + "200": + description: Latest SOP status + content: + application/json: + schema: + type: object + required: [runId, projectId, status, terminal, timedOut] + properties: + runId: {type: string} + projectId: {type: string} + status: {type: string} + terminal: {type: boolean, description: "Status is succeeded, failed, or cancelled"} + timedOut: {type: boolean, description: The wait window ended while the run was still active or queued} + "400": + description: Invalid timeoutSec + "401": + $ref: "#/components/responses/Unauthorized" + "403": + $ref: "#/components/responses/Forbidden" + "404": + description: Run not found + "409": + description: The run is a conversation workspace /api/runs/{id}/control: parameters: - {name: id, in: path, required: true, schema: {type: string}} @@ -5343,6 +5383,12 @@ components: assistantModel: type: string description: Model id from GET /api/assistant/models?schedule=1. + timeoutMinutes: + type: integer + minimum: 0 + maximum: 240 + default: 30 + description: AI jobs only. Minutes allowed for each execution, including tool calls and waits. Omitted or 0 uses 30. Expiry stops the AI turn and records a failed execution. Dispatched SOPs continue independently. ownerUserId: type: integer format: int64 diff --git a/internal/application/operations.go b/internal/application/operations.go index 52183bb7e..3f690262b 100644 --- a/internal/application/operations.go +++ b/internal/application/operations.go @@ -94,6 +94,7 @@ func PublicOperations() []Operation { {Name: "runs_control_get", Description: "Read the run mode (sop or workspace), waiting reason, allowed control actions and delivery acceptance. Node execution progress is separate from test results and user acceptance. Read this before changing a run's state.", Method: "GET", Path: "/api/runs/{id}/control", ReadOnly: true}, {Name: "runs_start", Description: "Start an SOP Run", Method: "POST", Path: "/api/runs"}, {Name: "runs_get", Description: "Get one Run", Method: "GET", Path: "/api/runs/{id}", ReadOnly: true}, + {Name: "runs_wait", Description: "Wait for the SOP with path.id to succeed, fail, be cancelled, or need human action (waiting/paused). One call waits up to 25 seconds. If timedOut is true, the SOP is still active or queued; keep waiting on the same run ID if needed.", Method: "GET", Path: "/api/runs/{id}/wait", ReadOnly: true}, {Name: "runs_delete", Description: "Delete a finished Run", Method: "DELETE", Path: "/api/runs/{id}"}, {Name: "runs_eval_start", Description: "Manually start an LLM quality evaluation of a finished SOP run. Body: {model}. Uses the current user's CodeBuddy key and assistant model catalog.", Method: "POST", Path: "/api/runs/{id}/eval"}, {Name: "runs_eval_get", Description: "Get the latest SOP run evaluation", Method: "GET", Path: "/api/runs/{id}/eval", ReadOnly: true}, @@ -123,7 +124,7 @@ func PublicOperations() []Operation { {Name: "schedule_jobs_publish", Description: "Publish a credential-free shared AI task version from an independent task. baseVersion is required for optimistic concurrency.", Method: "POST", Path: "/api/schedule-jobs/{id}/publish"}, {Name: "schedule_jobs_list", Description: "List scheduled SOP jobs", Method: "GET", Path: "/api/schedule-jobs", ReadOnly: true}, {Name: "schedule_job_executions_list", Description: "List schedule job executions newest first: status, error, durationMs, AI reply summary and the runs[] (issueId, runId) each execution dispatched. Look up a Trace ID copied from the schedule execution panel or a scheduler log line (trace=...) with query.traceId; filter by jobId or status (running/success/failed/waiting). Follow runs[].runId with runs_get.", Method: "GET", Path: "/api/schedule-job-executions", ReadOnly: true}, - {Name: "schedule_jobs_save", Description: "Create or update a scheduled job. Two exclusive kinds: trigger jobs (skipDispatch=false, require workflowId) scan issues in issueStatuses (backlog/todo/in_progress/in_review/blocked; default backlog+todo), run baseline guard, and dispatch SOP with optional maxDispatch (1-10 successful issue dispatches per execution; omitted or 0 defaults to 10); AI jobs (skipDispatch=true, require assistantPrompt or sharedTaskId+sharedTaskVersion+parameterValues) run a CodeBuddy prompt only. Timing is intervalSec or 5-field cron (Asia/Shanghai). Optional notifications bind up to 3 configured project Bots (botId, events succeeded/failed, template, contentMode template/ai, aiInstruction). Use notification_bots_list to select an existing Bot. AI content reuses this task output; {{task.name}}, {{result}} and {{ai.summary}} are supported.", Method: "PUT", Path: "/api/schedule-jobs"}, + {Name: "schedule_jobs_save", Description: "Create or update a scheduled job. Two exclusive kinds: trigger jobs (skipDispatch=false, require workflowId) scan issues in issueStatuses (backlog/todo/in_progress/in_review/blocked; default backlog+todo), run baseline guard, and dispatch SOP with optional maxDispatch (1-10 successful issue dispatches per execution; omitted or 0 defaults to 10); AI jobs (skipDispatch=true, require assistantPrompt or sharedTaskId+sharedTaskVersion+parameterValues) run a prompt with timeoutMinutes (1-240; omitted or 0 defaults to 30). Timing is intervalSec or 5-field cron (Asia/Shanghai). Optional notifications bind up to 3 configured project Bots (botId, events succeeded/failed, template, contentMode template/ai, aiInstruction). Use notification_bots_list to select an existing Bot. AI content reuses this task output; {{task.name}}, {{result}} and {{ai.summary}} are supported.", Method: "PUT", Path: "/api/schedule-jobs"}, {Name: "schedule_jobs_delete", Description: "Delete a scheduled SOP job", Method: "DELETE", Path: "/api/schedule-jobs/{id}"}, {Name: "schedule_jobs_run", Description: "Start a scheduled job on the server and return immediately (lastStatus=running). Closing the client does not cancel it; poll schedule_jobs_list until lastStatus leaves running.", Method: "POST", Path: "/api/schedule-jobs/{id}/run"}, {Name: "assistant_sessions_list", Description: "List the assistant conversations the caller may read: their own sessions, SOP shared sessions of authorized runs, and conversations of projects they belong to. Use it to resolve a chat session link before reading it.", Method: "GET", Path: "/api/assistant/sessions", ReadOnly: true}, diff --git a/internal/domain/schedule_execution.go b/internal/domain/schedule_execution.go index 4498f7b7e..f42e10115 100644 --- a/internal/domain/schedule_execution.go +++ b/internal/domain/schedule_execution.go @@ -82,6 +82,30 @@ type ScheduleExecutionWindow struct { AvgMs int64 `json:"avgMs"` } +const ( + DefaultScheduleTimeoutMinutes = 30 + MaxScheduleTimeoutMinutes = 240 +) + +// NormalizeScheduleTimeoutMinutes validates an AI job's execution limit. +func NormalizeScheduleTimeoutMinutes(minutes int) (int, error) { + if minutes == 0 { + return DefaultScheduleTimeoutMinutes, nil + } + if minutes < 1 || minutes > MaxScheduleTimeoutMinutes { + return 0, fmt.Errorf("执行超时必须为 1–%d 分钟", MaxScheduleTimeoutMinutes) + } + return minutes, nil +} + +func (j ScheduleJob) ExecutionTimeout() time.Duration { + minutes, err := NormalizeScheduleTimeoutMinutes(j.TimeoutMinutes) + if err != nil { + minutes = DefaultScheduleTimeoutMinutes + } + return time.Duration(minutes) * time.Minute +} + // ScheduleSessionFixed is ScheduleJob.SessionMode for an AI job that keeps // running in one pinned conversation. const ScheduleSessionFixed = "fixed" diff --git a/internal/domain/sync.go b/internal/domain/sync.go index c88235563..eecb92fa1 100644 --- a/internal/domain/sync.go +++ b/internal/domain/sync.go @@ -85,6 +85,9 @@ type ScheduleJob struct { Cron string `json:"cron,omitempty"` AssistantPrompt string `json:"assistantPrompt,omitempty"` AssistantModel string `json:"assistantModel,omitempty"` + // TimeoutMinutes bounds one AI execution, including tool calls and SOP waits. + // Zero uses the default for jobs saved before this field existed. + TimeoutMinutes int `json:"timeoutMinutes,omitempty"` // SessionMode picks the Studio conversation an AI job runs in: empty opens // a new conversation for every execution; "fixed" keeps continuing // FixedSessionID. diff --git a/internal/httpapi/agent_tool_mcp.go b/internal/httpapi/agent_tool_mcp.go index 45985a97d..a2c758a35 100644 --- a/internal/httpapi/agent_tool_mcp.go +++ b/internal/httpapi/agent_tool_mcp.go @@ -410,7 +410,9 @@ func (h *agentToolGateway) dispatch(ctx context.Context, session *AgentToolSessi if session.WorkspaceToken != "" && session.RunID != "" && strings.HasPrefix(tool.UpstreamName, "runs_") && assistantToolInput(call).Path["id"] == session.RunID { ctx = engine.WithConversationWorkspaceToken(ctx, session.WorkspaceToken, session.RunID) } - if session.workspaceTurn != nil && strings.HasPrefix(tool.UpstreamName, "runs_") { + // Waiting only reads status. Do not hold the workspace operation lock + // while a separate tool or turn may be advancing the run. + if session.workspaceTurn != nil && strings.HasPrefix(tool.UpstreamName, "runs_") && tool.UpstreamName != "runs_wait" { releaseTurn := session.workspaceTurn.lockOperation() defer releaseTurn() ctx = session.workspaceTurn.withLease(ctx, assistantToolInput(call).Path["id"]) diff --git a/internal/httpapi/assistant_generation.go b/internal/httpapi/assistant_generation.go index 987dad720..789398c81 100644 --- a/internal/httpapi/assistant_generation.go +++ b/internal/httpapi/assistant_generation.go @@ -414,6 +414,11 @@ func (h *assistantHandlers) executeGeneration(parent context.Context, req assist g.Status = "failed" g.Error = "会话工作区续租失败,生成已中断" g.Failure = &domain.AssistantFailure{Code: "WORKSPACE_LEASE_LOST", Phase: "server", Message: g.Error, Suggestion: "检查已执行操作及工作区状态后再重试;可下载诊断信息排查。"} + } else if ctx.Err() == context.DeadlineExceeded { + failure := classifyAssistantFailure(ctx, ctx.Err()) + failure.Message = "生成超时" + g.Error, g.Failure = failure.Message, &failure + rec.diagnostics.terminate(failure.Code, failure.Message, diagUser) } else { g.Status = "cancelled" g.Error = "生成已停止" diff --git a/internal/httpapi/assistant_schedule.go b/internal/httpapi/assistant_schedule.go index 287a013ae..828b6fd4b 100644 --- a/internal/httpapi/assistant_schedule.go +++ b/internal/httpapi/assistant_schedule.go @@ -5,6 +5,7 @@ import ( "errors" "fmt" "strings" + "time" "agentflow/internal/domain" "agentflow/internal/repo" @@ -19,6 +20,8 @@ type scheduledSessionPolicy struct { // KeepHistory keeps the conversations of earlier runs so each execution // record can open its own; the session janitor trims them later. KeepHistory bool + // Timeout caps the turn and its tool calls, including waits for SOP results. + Timeout time.Duration // Opened, when set, learns the conversation as soon as it is created, // before the prompt finishes. Opened func(sessionID string) @@ -89,7 +92,7 @@ func (h *assistantHandlers) runScheduleJobPromptReporting(job domain.ScheduleJob } ctx := withAssistantExecMode(context.Background(), assistantExecModeForApproval(AssistantApprovalAuto)) ctx = withAssistantSessionOrigin(ctx, domain.AssistantSourceScheduled, job.ID) - policy := scheduledSessionPolicy{KeepHistory: true, Opened: opened} + policy := scheduledSessionPolicy{KeepHistory: true, Timeout: job.ExecutionTimeout(), Opened: opened} if job.UsesFixedSession() { policy.Continue = strings.TrimSpace(job.FixedSessionID) } diff --git a/internal/httpapi/assistant_schedule_permissions_test.go b/internal/httpapi/assistant_schedule_permissions_test.go index 2aae9174c..f622e55a1 100644 --- a/internal/httpapi/assistant_schedule_permissions_test.go +++ b/internal/httpapi/assistant_schedule_permissions_test.go @@ -38,7 +38,10 @@ func TestScheduledAssistantCanDispatchSOP(t *testing.T) { _ = en.Cancel(runID) } }) - h.generate = func(ctx context.Context, _ string, actor domain.User) (string, error) { + h.generate = func(ctx context.Context, prompt string, actor domain.User) (string, error) { + if !strings.Contains(prompt, "agentflow__runs_wait") { + t.Error("scheduled prompt must use the supported SOP wait tool") + } text, err := h.callAssistantPlatform(ctx, actor, "workbench", assistantMCPCall{Tool: "issues_dispatch", Path: map[string]any{"id": "scheduled-dispatch"}}) if err != nil { return "", err @@ -48,19 +51,24 @@ func TestScheduledAssistantCanDispatchSOP(t *testing.T) { return "", err } runID = task.RunID - return "已启动 SOP", nil + text, err = h.callAssistantPlatform(ctx, actor, "workbench", assistantMCPCall{ + Tool: "runs_wait", Path: map[string]any{"id": runID}, Query: map[string]any{"timeoutSec": "3"}, + }) + if err != nil { + return "", err + } + var result runWaitResult + if err := json.Unmarshal([]byte(text), &result); err != nil { + return "", err + } + if result.RunID != runID || result.Status != "waiting" || result.Terminal || result.TimedOut { + t.Errorf("SOP approval should end the wait: %+v", result) + } + return "SOP 等待人工审批", nil } if _, err := h.prepareScheduleJob(domain.ScheduleJob{ID: "ai-dispatch", ProjectID: "workbench", OwnerUserID: user.ID, Name: "Dispatch", AssistantPrompt: "启动需求的 SOP", SkipDispatch: true}); err != nil { t.Fatal(err) } - deadline := time.Now().Add(2 * time.Second) - for time.Now().Before(deadline) { - if run, ok := st.RunState(runID); ok && run.WorkflowID == wf.ID && run.Status == "waiting" { - return - } - time.Sleep(10 * time.Millisecond) - } - t.Fatalf("AI schedule did not reach the SOP approval gate: id=%q", runID) } func TestScheduledAssistantNativeGatewayKeepsWorkspaceAndTerminalReply(t *testing.T) { diff --git a/internal/httpapi/assistant_schedule_test.go b/internal/httpapi/assistant_schedule_test.go index 121efb182..74841c5db 100644 --- a/internal/httpapi/assistant_schedule_test.go +++ b/internal/httpapi/assistant_schedule_test.go @@ -15,8 +15,8 @@ import ( "agentflow/internal/tracker" ) -// A scheduled run, like a chat turn, has no time limit. -func TestScheduledAssistantHasNoDeadline(t *testing.T) { +func TestScheduledAssistantDeadline(t *testing.T) { + t.Setenv("AGENTFLOW_ASSISTANT_SESSION_DIR", t.TempDir()) st, err := repo.OpenTest() if err != nil { t.Fatal(err) @@ -26,17 +26,55 @@ func TestScheduledAssistantHasNoDeadline(t *testing.T) { t.Fatal(err) } user, _ := st.UserByLoginName("schedule-owner") - called := false - stopped := errors.New("stop test generation") - h := &assistantHandlers{deps: &deps{repo: st}, generate: func(ctx context.Context, _ string, _ domain.User) (string, error) { - called = true - if deadline, ok := ctx.Deadline(); ok { - t.Fatalf("scheduled generation has a deadline: %s", time.Until(deadline)) - } - return "", stopped - }} - if _, err := h.prepareScheduleJob(domain.ScheduleJob{OwnerUserID: user.ID, AssistantPrompt: "inspect"}); err == nil || !called { - t.Fatalf("generation was not reached: called=%v err=%v", called, err) + for _, tc := range []struct { + name string + minutes int + want time.Duration + }{ + {"existing job", 0, 30 * time.Minute}, + {"configured limit", 5, 5 * time.Minute}, + } { + t.Run(tc.name, func(t *testing.T) { + called := false + h := &assistantHandlers{deps: &deps{repo: st}, generate: func(ctx context.Context, _ string, _ domain.User) (string, error) { + called = true + deadline, ok := ctx.Deadline() + if remaining := time.Until(deadline); !ok || remaining > tc.want || remaining < tc.want-10*time.Second { + t.Errorf("scheduled generation deadline = %s remaining, want %s", remaining, tc.want) + } + return "定时巡检已完成", nil + }} + if _, err := h.prepareScheduleJob(domain.ScheduleJob{OwnerUserID: user.ID, AssistantPrompt: "inspect", TimeoutMinutes: tc.minutes}); err != nil || !called { + t.Fatalf("generation did not complete: called=%v err=%v", called, err) + } + }) + } +} + +func TestScheduledAssistantStopsAtDeadline(t *testing.T) { + h, user := workbenchFixture(t) + started := make(chan struct{}) + h.generate = func(ctx context.Context, _ string, _ domain.User) (string, error) { + close(started) + <-ctx.Done() + return "", ctx.Err() + } + task := assistantTask{ProjectID: "workbench", Name: "Timeout", Prompt: "wait"} + ctx := withScheduledSessionPolicy(context.Background(), scheduledSessionPolicy{Timeout: time.Second}) + if err := h.executeAssistantTask(ctx, user, &task); !errors.Is(err, context.DeadlineExceeded) { + t.Fatalf("scheduled generation error = %v, want DeadlineExceeded", err) + } + select { + case <-started: + default: + t.Fatal("deadline elapsed before the turn started") + } + if task.LastStatus != "error" || task.LastError != "定时任务执行超时" || task.SessionID == "" { + t.Fatalf("unexpected task outcome: %+v", task) + } + generation, ok := h.repo.PeekAssistantGeneration(user.ID, task.SessionID) + if !ok || generation.Status != "failed" || generation.Failure == nil || generation.Failure.Code != "EXECUTION_TIMEOUT" { + t.Fatalf("unexpected generation outcome: %+v", generation) } } diff --git a/internal/httpapi/assistant_tasks.go b/internal/httpapi/assistant_tasks.go index 77e11c5dd..a05b32647 100644 --- a/internal/httpapi/assistant_tasks.go +++ b/internal/httpapi/assistant_tasks.go @@ -212,6 +212,13 @@ func (h *assistantHandlers) executeAssistantTask(ctx context.Context, user domai return errAssistantBusy } defer h.active.Delete(activeKey) + policy := scheduledSessionPolicyFrom(ctx) + timeout := policy.Timeout + if timeout == 0 { + timeout = domain.DefaultScheduleTimeoutMinutes * time.Minute + } + ctx, cancel := context.WithTimeout(ctx, timeout) + defer cancel() ctx = withAssistantExecMode(ctx, assistantExecModeForApproval(AssistantApprovalAuto)) mode := assistantExecModeFrom(ctx) @@ -226,6 +233,10 @@ func (h *assistantHandlers) executeAssistantTask(ctx context.Context, user domai machine := scheduleLoginRunner(h.repo, user.ID, engine) machineOffline := machine.ID != "" && machine.Status != domain.RunnerStatusOnline fail := func(msg string) error { + if errors.Is(ctx.Err(), context.DeadlineExceeded) { + task.LastStatus, task.LastError = "error", "定时任务执行超时" + return context.DeadlineExceeded + } if machineOffline { msg = fmt.Sprintf("默认执行机器 %s 已离线。%s", firstNonEmpty(machine.Name, machine.ID), msg) } @@ -254,7 +265,6 @@ func (h *assistantHandlers) executeAssistantTask(ctx context.Context, user domai } } cliEngine, _ := assistantModelEngine(model) - policy := scheduledSessionPolicyFrom(ctx) prevSession := strings.TrimSpace(task.SessionID) sessionID := newAssistantSessionID() now := time.Now().UTC() @@ -294,8 +304,6 @@ func (h *assistantHandlers) executeAssistantTask(ctx context.Context, user domai if policy.Opened != nil { policy.Opened(sessionID) } - // 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)) if policy.KeepHistory { // Schedule jobs keep every run's conversation for their execution @@ -303,6 +311,9 @@ func (h *assistantHandlers) executeAssistantTask(ctx context.Context, user domai prevSession, origin.TaskID = "", "" } err := h.readScheduledTurn(user, task, g, len(req.Messages), prevSession, origin.TaskID) + if err != nil && errors.Is(ctx.Err(), context.DeadlineExceeded) { + return fail(err.Error()) + } if err != nil && machineOffline { return fail("使用个人 API Key 执行失败。" + err.Error()) } @@ -382,6 +393,8 @@ func scheduledAssistantPrompt(task assistantTask, mode assistantExecMode) string prefix += " 不要调用 issues_dispatch、runs_start、schedule_jobs_run、schedule_jobs_save;需要派发 SOP 时请单独创建触发任务。" } else { prefix += " 与主页 AI 对话的完全权限模式使用相同的工具和执行权限;按提示词调用 SOP、平台工具、工作区及浏览器工具完成任务。" + prefix += " 需要等待 SOP 结果时,用 agentflow__runs_wait,path.id 填派发结果的 runId(runs_start 返回 id)。" + + "只有 timedOut=true 才继续等待同一运行。收到终态(succeeded、failed、cancelled)或 waiting、paused 后结束等待并如实汇报,必要时用 runs_get 查看原因。" } return prefix + " 按下面的提示词原文执行。\n" + task.Prompt + domain.NotificationAIInstructions(task.Notifications) } diff --git a/internal/httpapi/run_wait.go b/internal/httpapi/run_wait.go new file mode 100644 index 000000000..b363b3736 --- /dev/null +++ b/internal/httpapi/run_wait.go @@ -0,0 +1,85 @@ +package httpapi + +import ( + "net/http" + "strconv" + "time" + + "agentflow/internal/domain" + + "github.com/gin-gonic/gin" +) + +const runWaitMaxSeconds = 25 + +type runWaitResult struct { + RunID string `json:"runId"` + ProjectID string `json:"projectId"` + Status string `json:"status"` + Terminal bool `json:"terminal"` + TimedOut bool `json:"timedOut"` +} + +// waitRun waits on durable state so the result also works when a worker or +// another API replica finishes the run. Only the status column is polled. +func (h *runsHandlers) waitRun(c *gin.Context) { + ctx := c.Request.Context() + run, err := h.repo.RunHeader(c.Param("id")) + if err != nil { + respond(c, err) + return + } + if run.ID == "" { + c.JSON(http.StatusNotFound, gin.H{"error": "run not found"}) + return + } + projectID := run.ExecutionContext.ProjectID + if _, ok := h.projectRunUser(c, projectID); !ok { + return + } + if run.IsWorkspace() { + c.JSON(http.StatusConflict, gin.H{"error": "only SOP runs can be waited on"}) + return + } + + seconds, err := strconv.Atoi(c.DefaultQuery("timeoutSec", strconv.Itoa(runWaitMaxSeconds))) + if err != nil || seconds < 0 || seconds > runWaitMaxSeconds { + c.JSON(http.StatusBadRequest, gin.H{"error": "timeoutSec must be an integer between 0 and 25"}) + return + } + deadline := time.Now().Add(time.Duration(seconds) * time.Second) + for { + status, found, err := h.repo.ReadRunStatus(ctx, run.ID) + if ctx.Err() != nil { + c.Status(http.StatusRequestTimeout) + return + } + if err != nil { + respond(c, err) + return + } + if !found { + c.JSON(http.StatusNotFound, gin.H{"error": "run not found"}) + return + } + remaining := time.Until(deadline) + result := runWaitResult{RunID: run.ID, ProjectID: projectID, Status: status, Terminal: domain.TerminalRunStatus(status)} + if result.Terminal || status == "waiting" || status == "paused" { + c.JSON(http.StatusOK, result) + return + } + if remaining <= 0 { + result.TimedOut = true + c.JSON(http.StatusOK, result) + return + } + timer := time.NewTimer(min(2*time.Second, remaining)) + select { + case <-ctx.Done(): + timer.Stop() + c.Status(http.StatusRequestTimeout) + return + case <-timer.C: + } + } +} diff --git a/internal/httpapi/run_wait_test.go b/internal/httpapi/run_wait_test.go new file mode 100644 index 000000000..e1d4cee13 --- /dev/null +++ b/internal/httpapi/run_wait_test.go @@ -0,0 +1,79 @@ +package httpapi + +import ( + "bytes" + "context" + "encoding/json" + "net/http" + "net/http/httptest" + "path/filepath" + "testing" + "time" + + "agentflow/internal/domain" + "agentflow/internal/engine" + "agentflow/internal/runtime" +) + +func TestWaitRunReadsOutcomeAndChecksAccess(t *testing.T) { + t.Setenv("AGENTFLOW_AUTH_REQUIRED", "true") + h, owner := workbenchFixture(t) + en := engine.New(h.repo, runtime.NewManager(filepath.Join(t.TempDir(), "workspaces"))) + api := New(h.repo, en, nil, "", "") + if err := h.repo.PutUser(domain.User{LoginName: "other-user"}); err != nil { + t.Fatal(err) + } + other, _ := h.repo.UserByLoginName("other-user") + for _, tc := range []struct { + status string + terminal bool + timedOut bool + }{ + {"succeeded", true, false}, + {"failed", true, false}, + {"cancelled", true, false}, + {"waiting", false, false}, + {"paused", false, false}, + {"running", false, true}, + {"queued", false, true}, + } { + run := domain.Run{ID: "sop-" + tc.status, Status: tc.status, ExecutionContext: domain.TelemetryContext{ProjectID: "workbench"}} + if err := h.repo.PutRun(run); err != nil { + t.Fatal(err) + } + c, rec := workbenchContext(owner, http.MethodGet, "/api/runs/"+run.ID+"/wait?timeoutSec=0", bytes.NewBuffer(nil)) + api.ServeHTTP(rec, c.Request) + var got runWaitResult + if err := json.Unmarshal(rec.Body.Bytes(), &got); rec.Code != http.StatusOK || err != nil { + t.Fatalf("wait %s: %d %s", tc.status, rec.Code, rec.Body) + } + if got.RunID != run.ID || got.Status != tc.status || got.Terminal != tc.terminal || got.TimedOut != tc.timedOut { + t.Errorf("wait %s: %+v", tc.status, got) + } + } + for _, tc := range []struct { + user domain.User + path string + code int + }{ + {other, "/api/runs/sop-running/wait", http.StatusForbidden}, + {owner, "/api/runs/missing/wait", http.StatusNotFound}, + {owner, "/api/runs/sop-running/wait?timeoutSec=26", http.StatusBadRequest}, + } { + c, rec := workbenchContext(tc.user, http.MethodGet, tc.path, bytes.NewBuffer(nil)) + api.ServeHTTP(rec, c.Request) + if rec.Code != tc.code { + t.Errorf("%s: got %d, want %d (%s)", tc.path, rec.Code, tc.code, rec.Body) + } + } + + ctx, cancel := context.WithTimeout(context.Background(), 100*time.Millisecond) + defer cancel() + req := httptest.NewRequestWithContext(context.WithValue(ctx, requestUserContextKey{}, domainUserToAuth(owner)), + http.MethodGet, "/api/runs/sop-running/wait", nil) + rec := httptest.NewRecorder() + api.ServeHTTP(rec, req) + if rec.Code != http.StatusRequestTimeout { + t.Fatalf("cancelled wait: %d %s", rec.Code, rec.Body) + } +} diff --git a/internal/httpapi/schedule.go b/internal/httpapi/schedule.go index c12274021..e6129670d 100644 --- a/internal/httpapi/schedule.go +++ b/internal/httpapi/schedule.go @@ -77,6 +77,11 @@ func (h *scheduleHandlers) scheduleJobs(c *gin.Context) { c.JSON(400, map[string]string{"error": "AI 定时任务必须填写提示词"}) return } + job.TimeoutMinutes, err = domain.NormalizeScheduleTimeoutMinutes(job.TimeoutMinutes) + if err != nil { + c.JSON(400, gin.H{"error": err.Error()}) + return + } job.WorkflowID = "" job.UseIssueWorkflow = false job.IssueStatuses = nil @@ -93,6 +98,7 @@ func (h *scheduleHandlers) scheduleJobs(c *gin.Context) { } job.AssistantPrompt = "" job.AssistantModel = "" + job.TimeoutMinutes = 0 job.IssueStatuses = domain.NormalizeScheduleIssueStatuses(job.IssueStatuses) if len(job.IssueStatuses) == 0 { job.IssueStatuses = append([]string{}, domain.DefaultScheduleIssueStatuses...) diff --git a/internal/httpapi/schedule_test.go b/internal/httpapi/schedule_test.go index 2a2b9f748..a41a48679 100644 --- a/internal/httpapi/schedule_test.go +++ b/internal/httpapi/schedule_test.go @@ -81,8 +81,21 @@ func TestScheduleJobCRUD(t *testing.T) { if len(promptOnly.IssueStatuses) != 0 { t.Fatalf("AI job must not keep issue statuses: %+v", promptOnly.IssueStatuses) } - if promptOnly.MaxDispatch != 0 { - t.Fatalf("AI job must not keep maxDispatch: %+v", promptOnly) + if promptOnly.MaxDispatch != 0 || promptOnly.TimeoutMinutes != domain.DefaultScheduleTimeoutMinutes { + t.Fatalf("unexpected AI job limits: %+v", promptOnly) + } + for _, invalid := range []any{-1, 241, 1.5, "30"} { + requestJSON[map[string]string](t, h, http.MethodPut, "/api/schedule-jobs", map[string]any{ + "id": promptOnly.ID, "name": promptOnly.Name, "assistantPrompt": promptOnly.AssistantPrompt, + "skipDispatch": true, "timeoutMinutes": invalid, + }, http.StatusBadRequest) + } + requestJSON[domain.ScheduleJob](t, h, http.MethodPut, "/api/schedule-jobs", map[string]any{ + "id": promptOnly.ID, "name": promptOnly.Name, "assistantPrompt": promptOnly.AssistantPrompt, + "skipDispatch": true, "timeoutMinutes": 75, + }, http.StatusOK) + if stored, ok := st.ScheduleJob(promptOnly.ID); !ok || stored.TimeoutMinutes != 75 { + t.Fatalf("saved timeout was lost: %+v", stored) } for _, method := range []string{http.MethodPost, http.MethodPut} { for _, invalid := range []any{-1, 11, 1.5, "3"} { diff --git a/internal/httpapi/server.go b/internal/httpapi/server.go index 70df9146d..8381dd82d 100644 --- a/internal/httpapi/server.go +++ b/internal/httpapi/server.go @@ -520,6 +520,7 @@ func newWithNotifications(s *repo.Store, e *engine.Engine, syncSvc *tracker.Serv g.GET("/api/runs", api.runs.runs) g.POST("/api/runs", api.runs.runs) g.GET("/api/runs/:id", api.runs.run) + g.GET("/api/runs/:id/wait", api.runs.waitRun) g.DELETE("/api/runs/:id", api.runs.run) g.GET("/api/runs/:id/telemetry", api.runs.run) g.GET("/api/runs/:id/logs", api.runs.run) diff --git a/internal/repo/runs.go b/internal/repo/runs.go index 32f45ffe5..074fffc52 100644 --- a/internal/repo/runs.go +++ b/internal/repo/runs.go @@ -1,6 +1,7 @@ package repo import ( + "context" "database/sql" "encoding/json" "errors" @@ -267,6 +268,16 @@ func (r *RunsRepo) RunStatuses() map[string]string { return out } +// ReadRunStatus reads a single run without loading its graph or event history. +func (r *RunsRepo) ReadRunStatus(ctx context.Context, id string) (status string, found bool, err error) { + var row runRow + err = r.DB.WithContext(ctx).Select("status").Where("id = ?", id).Take(&row).Error + if errors.Is(err, gorm.ErrRecordNotFound) { + return "", false, nil + } + return row.Status, err == nil, err +} + // RunsWithActiveNodes reports runs that still have running or pending_input nodes. // Used by task reconciliation without hydrating full run views. func (r *RunsRepo) RunsWithActiveNodes() map[string]bool { diff --git a/web/app/sync-schedule.js b/web/app/sync-schedule.js index 98928edd2..f910c7a84 100644 --- a/web/app/sync-schedule.js +++ b/web/app/sync-schedule.js @@ -284,6 +284,7 @@ function syncScheduleJobKind(){ f.elements.assistantPrompt.required=kind==='assistant'&&!f.elements.sharedTaskId?.value; f.elements.name.required=kind==='assistant'; const assistant=kind==='assistant'; + f.elements.timeoutMinutes.disabled=!assistant; $('#scheduleModalTitle').textContent=assistant?'AI 定时任务':'触发配置'; $('#scheduleModalHint').textContent=assistant?'按计划以保存人的身份和完全权限执行提示词,可调用 SOP、平台工具、工作区及浏览器。':'按计划扫描本项目选定状态、尚未跑过 SOP 的需求,通过基线门禁后派发 SOP。基线冲突会先由对齐 Agent 解决并合入,期间暂停派发。'; $('#scheduleModal').querySelector('.schedule-head').hidden=assistant; @@ -331,6 +332,7 @@ function fillScheduleJobForm(job={}){ f.elements.jobKind.value=job.id?scheduleJobKind(job):scheduleEditorKind; f.elements.assistantPrompt.value=job.assistantPrompt||''; f.elements.assistantModel.value=job.assistantModel||scheduleModelAPI()?.DEFAULT||'default'; + f.elements.timeoutMinutes.value=job.timeoutMinutes||''; fillScheduleSessionMode(f,job); f.elements.useIssueWorkflow.checked=job.id?!!job.useIssueWorkflow:true; f.elements.maxDispatch.value=job.maxDispatch||''; @@ -610,6 +612,7 @@ async function saveScheduleJob(e){ cron:cron?f.elements.cron.value.trim():'', assistantPrompt:assistant?f.elements.assistantPrompt.value.trim():'', assistantModel:assistant?f.elements.assistantModel.value.trim():'', + timeoutMinutes:assistant&&f.elements.timeoutMinutes.value!==''?Number(f.elements.timeoutMinutes.value):undefined, sessionMode:assistant&&f.elements.sessionMode?f.elements.sessionMode.value:'', sessionKeep:assistant&&f.elements.sessionKeep?Number(f.elements.sessionKeep.value)||50:0, enabled:assistant?scheduleSavedEnabled(f.elements.id.value):f.elements.enabled.checked @@ -617,6 +620,7 @@ async function saveScheduleJob(e){ if(assistant&&typeof sharedScheduleFormPayload==='function')Object.assign(payload,sharedScheduleFormPayload(f)); if(!payload.name)return toast('请填写任务名称'); if(assistant&&!payload.assistantPrompt&&!payload.sharedTaskId)return toast('请填写 AI 定时任务的提示词'); + if(assistant&&!f.elements.timeoutMinutes.validity.valid)return toast('执行超时必须为 1–240 分钟'); if(!assistant&&!payload.workflowId)return toast('请选择默认 SOP'); if(!assistant&&!payload.issueStatuses.length)return toast('请至少选择一个触发状态'); if(!assistant&&payload.maxDispatch!==undefined&&(!Number.isInteger(payload.maxDispatch)||payload.maxDispatch<1||payload.maxDispatch>10))return toast('单次最多触发需求数必须为 1–10,或留空使用默认值 10'); diff --git a/web/i18n-en.js b/web/i18n-en.js index c206952fa..6fc326367 100644 --- a/web/i18n-en.js +++ b/web/i18n-en.js @@ -238,3 +238,9 @@ Object.assign(window.LF_I18N_EN,{ "该 CLI 支持 API Key。使用服务商订阅套餐提供的 Key,执行用量会计入对应的套餐额度。请在「个人配置」中填写 API Key。":"This CLI supports API keys. With a key included in your provider's subscription, usage counts toward that plan's allowance. Enter the API key in Personal Settings." }); Object.assign(window.LF_I18N_EN,{"查看其他项目共享的技能;共享技能只读,会自动装入平台上所有对话和定时任务,也可绑定到本项目角色。": "Skills shared by other projects. Shared Skills are read-only, are installed automatically into every conversation and scheduled task on the platform, and can be bound to Roles in this project.", "共享后,这个技能会自动装入平台上所有用户的对话和定时任务(包括其他项目和无项目的对话),模型可以直接调用。继续?": "Once shared, this Skill is installed automatically into every user's conversations and scheduled tasks on the platform (including other projects and conversations without a project), and the model can call it directly. Continue?", "共享这个角色会同时共享它绑定的技能:": "Sharing this Role also shares the Skills bound to it: ", "已共享,所有对话和定时任务会自动装入": "Shared. Every conversation and scheduled task will install it automatically", "其他项目可在「共享角色」里选用;绑定的本项目技能会一起共享,并自动装入所有对话": "Other projects can pick it under Shared roles; the project Skills bound to it are shared too and installed into every conversation automatically", "共享技能": "Share Skill"}); +Object.assign(window.LF_I18N_EN, { + "执行超时(分钟)": "Execution timeout (minutes)", + "默认 30 分钟。达到时限会停止本次 AI 执行,已启动的 SOP 继续运行。": "Defaults to 30 minutes. The deadline stops the AI task. Any SOPs it started continue running.", + "执行超时必须为 1–240 分钟": "Execution timeout must be between 1 and 240 minutes", + "定时任务执行超时": "Scheduled task timed out" +}); diff --git a/web/index.html b/web/index.html index 279e1a123..6c2e6bbd7 100644 --- a/web/index.html +++ b/web/index.html @@ -1155,6 +1155,11 @@
Codex 和 Claude Code 优先使用保存人默认执行机器的账号登录。机器离线时改用个人 API Key,Key 缺失或不可用时任务失败。CodeBuddy 缺少个人 Key 时可使用平台共享 Key。
+默认 30 分钟。达到时限会停止本次 AI 执行,已启动的 SOP 继续运行。
+