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(schedule): run AI jobs with the saver's key, fall back to the shared key (#966)
Robert06221e50be777758
diff --git a/docs/ai-scheduled-task-capabilities.md b/docs/ai-scheduled-task-capabilities.mdindex f1573748..6e74c9b4 100644--- a/docs/ai-scheduled-task-capabilities.md+++ b/docs/ai-scheduled-task-capabilities.md@@ -13,9 +13,9 @@| Skill | 与主页现有能力一致,不额外禁用内置 Skill 工具。启动 SOP 后,节点会按原有逻辑装载角色绑定的 Skill。主页与定时对话均未独立提供平台 Skill 绑定和自动装载功能,本次不新增这套机制。 || 结果与产物 | 支持自然语言结果,以及主页相同的草稿提交回退;终止 CLI 后仍按完全权限落库并保留已提交结果。工作区附件和浏览器截图写入定时会话。 |-执行身份是项目 Owner,否则是非共享任务的任务 Owner。用的是所选 CLI 的 Key,不是只能用 CodeBuddy;平台共享的 CodeBuddy Key 不会借给定时任务,Codex / Claude Code 仍要该账号自己的凭据。工具访问范围沿用执行账号和当前项目的现有规则。关闭页面不会中断执行。定时任务没有单独的超时:它就是一轮普通对话,CLI 结束或有人从会话页停止时结束,MCP 网关跟这一轮一起结束。+执行身份是保存任务的人:新建时是创建人,其他成员编辑保存后改为他(不会借用别人的 Key);在这之前保存、没有绑定的任务仍是项目 Owner,否则是非共享任务的任务 Owner。用的是所选 CLI 的 Key,不是只能用 CodeBuddy。没有个人 CodeBuddy Key 时使用平台共享 Key,只能用管理员允许的模型;Codex / Claude Code 仍要该账号自己的凭据。两者都没有时保存会被拒绝并提示原因。工具访问范围沿用执行账号和当前项目的现有规则。关闭页面不会中断执行。定时任务没有单独的超时:它就是一轮普通对话,CLI 结束或有人从会话页停止时结束,MCP 网关跟这一轮一起结束。-由于任务以项目 Owner 身份、完全权限执行,`/api/schedule-jobs` 的新建、修改、立即运行和删除都要求项目写权限(Owner、平台管理员或非 viewer 成员),列表只返回调用者所在项目的任务;按 id 保存时既校验原项目也校验目标项目。执行身份只由服务端决定(项目 Owner,否则保留原任务 Owner),请求里的 `ownerUserId` 不生效。项目记录已不存在的任务只允许平台管理员或该任务原 Owner 管理。+由于任务以保存人(或项目 Owner)身份、完全权限执行,`/api/schedule-jobs` 的新建、修改、立即运行和删除都要求项目写权限(Owner、平台管理员或非 viewer 成员),列表只返回调用者所在项目的任务;按 id 保存时既校验原项目也校验目标项目。执行身份只由服务端决定,请求里的 `ownerUserId`、`runAsUserId` 不生效。项目记录已不存在的任务只允许平台管理员或该任务原 Owner 管理。## 实现与验证diff --git a/docs/api/openapi.yaml b/docs/api/openapi.yamlindex 81ae2442..2cea5298 100644--- a/docs/api/openapi.yaml+++ b/docs/api/openapi.yaml@@ -5241,7 +5241,15 @@ components:ownerUserId:type: integerformat: int64- description: Project owner whose CodeBuddy key runs assistantPrompt+ description: Project owner, whose keys run assistantPrompt for a job without runAsUserId (saved before the binding, or without a signed-in user)+ runAsUserId:+ type: integer+ format: int64+ readOnly: true+ description: User whose keys run the AI job, set by the server to whoever last saved it (never taken from the request). Their own key for the model's CLI is used, else the platform's shared CodeBuddy key limited to the models it allows; a save with neither is rejected with 400. 0 means the project owner. A bound job fails rather than fall back to another account when that user is gone or can no longer write to the project.+ runAsName:+ type: string+ readOnly: truelastRunAt:type: stringformat: date-timediff --git a/docs/api/orchestration.md b/docs/api/orchestration.mdindex 70f0c71c..69a32dff 100644--- a/docs/api/orchestration.md+++ b/docs/api/orchestration.md@@ -348,7 +348,7 @@ AI 定时任务没有单独的时长上限:这一轮和普通对话一样,### `POST|PUT /api/schedule-jobs`-新建或按 `id` 更新,两种方法语义相同。`name` 必填。调度为 `intervalSec`(常用间隔)或 5 段 `cron`(东八区)。`skipDispatch` 为 true 时是 AI 定时任务,必须有 `assistantPrompt`,保存时清空 SOP 字段;否则是触发任务,必须有 `workflowId`,保存时清空提示词。可选 `useIssueWorkflow`。`assistantModel` 保存时保留已支持 CLI 的模型(`codex:…`、`claude-code:…`);CodeBuddy 模型仍限制在助手目录内。运行前检查执行账号在该 CLI 上的 Key。保存时把项目 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`。AI 定时任务用保存人的 Key 执行:服务端把 `runAsUserId` 设为本次保存的登录用户(请求里传的值不生效),其他成员编辑保存后改用他的 Key。保存人没有个人 CodeBuddy Key 时用平台共享 Key,`assistantModel` 必须是共享 Key 允许的模型(为空或 `default` 时取共享 Key 的默认模型);没有可用 Key(没配个人 Key 且平台也没有共享 Key,或 Codex / Claude Code 模型缺对应 Key)时返回 `400` 并说明原因;只有停用任务、提示词和模型等执行配置都不变时例外,此时只把库中当前任务的 `enabled` 改为 false,其余字段(包括名称、通知、调度以及期间其他人已保存的修改)保持库中的值,原执行身份也保留,方便没有 Key 的成员停用任务;写入前在行锁内重新核对当前任务仍在原项目、执行配置仍与请求一致,否则返回 `409`,需刷新后重试。没有执行身份的旧任务先按项目 Owner、任务 Owner 的顺序找个人 Key,都没有时才用平台共享 Key。更新时若请求未带 `blockers`,保留触发任务已有的基线暂停状态。`id` 为空时生成;`projectId` 默认 `platform`;`intervalSec<30` 时重置为 `300`。更新若不提供 `lastRunAt` 会保留已有最近运行字段。成功 `200` 返回 job;校验/存储错误 `400`。diff --git a/internal/domain/sync.go b/internal/domain/sync.goindex 438db99f..85b55f92 100644--- a/internal/domain/sync.go+++ b/internal/domain/sync.go@@ -80,12 +80,18 @@ type ScheduleJob struct {// Empty means backlog + todo. AI jobs leave this unused.IssueStatuses []string `json:"issueStatuses,omitempty"`// MaxDispatch caps successful SOP dispatches per execution. Zero defaults to 10.- MaxDispatch int `json:"maxDispatch,omitempty"`- IntervalSec int `json:"intervalSec"`- Cron string `json:"cron,omitempty"`- AssistantPrompt string `json:"assistantPrompt,omitempty"`- AssistantModel string `json:"assistantModel,omitempty"`- OwnerUserID int64 `json:"ownerUserId,omitempty"`+ MaxDispatch int `json:"maxDispatch,omitempty"`+ IntervalSec int `json:"intervalSec"`+ Cron string `json:"cron,omitempty"`+ AssistantPrompt string `json:"assistantPrompt,omitempty"`+ AssistantModel string `json:"assistantModel,omitempty"`+ OwnerUserID int64 `json:"ownerUserId,omitempty"`+ // RunAsUserID is server-managed: the user whose keys run an AI job, set to+ // whoever last saved it. Zero (jobs saved before the binding, or without a+ // signed-in user) runs it with the project owner's keys. RunAsName is for+ // display.+ RunAsUserID int64 `json:"runAsUserId,omitempty"`+ RunAsName string `json:"runAsName,omitempty"`LastRunAt time.Time `json:"lastRunAt,omitempty"`LastStatus string `json:"lastStatus,omitempty"` // running, success, failed, waitingLastError string `json:"lastError,omitempty"`diff --git a/internal/httpapi/assistant_schedule.go b/internal/httpapi/assistant_schedule.goindex d7be674a..931de7ba 100644--- a/internal/httpapi/assistant_schedule.go+++ b/internal/httpapi/assistant_schedule.go@@ -7,6 +7,7 @@ import ("strings""agentflow/internal/domain"+ "agentflow/internal/repo")func (h *assistantHandlers) prepareScheduleJob(job domain.ScheduleJob) (string, error) {@@ -27,14 +28,24 @@ func (h *assistantHandlers) prepareScheduleJob(job domain.ScheduleJob) (string,if prompt == "" {return "", nil}- user, err := h.scheduleJobAssistantUser(job, job.AssistantModel)+ user, shared, err := h.scheduleJobAssistantUser(job, job.AssistantModel)if err != nil {return "", err}+ model := strings.TrimSpace(job.AssistantModel)+ if shared != nil {+ // On the shared key a run only uses the models the administrator+ // allows, and never silently switches to another one.+ allowed, ok := assistantSponsoredModelFor(shared, scheduleSharedRequestedModel(model))+ if !ok {+ return "", fmt.Errorf("定时任务使用平台共享 Key 执行,只能用平台管理员允许的模型(%s),任务指定的 %s 不在其中,本次没有运行;请在定时任务里改选允许的模型,或在个人配置中填写自己的 Key", strings.Join(shared, "、"), model)+ }+ model = allowed+ }task := assistantTask{Name: job.Name,Prompt: prompt,- Model: strings.TrimSpace(job.AssistantModel),+ Model: model,ProjectID: job.ProjectID,Notifications: domain.CloneNotificationBindings(job.Notifications),}@@ -52,28 +63,110 @@ func (h *assistantHandlers) prepareScheduleJob(job domain.ScheduleJob) (string,return firstNonEmpty(task.NotificationResult, task.LastMessage), nil}-// 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) {+// scheduleJobAssistantUser picks who runs the job: the member the job is bound+// to (whoever last saved it), else the project owner, else (for a non-shared+// job) its owner. A bound job never falls back to someone else's account. The+// model's CLI decides which key they need: their own, else for CodeBuddy the+// platform's shared key, whose allowed models are returned as shared (nil on+// the user's own key).+func (h *assistantHandlers) scheduleJobAssistantUser(job domain.ScheduleJob, model string) (domain.User, []string, error) {engine, _ := assistantModelEngine(model)- try := func(id int64) (domain.User, bool) {+ if job.RunAsUserID > 0 {+ return h.scheduleJobRunAsUser(job, engine)+ }+ var candidates []domain.User+ add := func(id int64) {if id == 0 || h.repo == nil {- return domain.User{}, false+ return+ }+ if user, ok := h.repo.User(id); ok {+ candidates = append(candidates, user)}- user, ok := h.repo.User(id)- key, _ := assistantEngineCredential(user, engine)- return user, ok && key != ""}if project, ok := h.repo.Project(job.ProjectID); ok {- if user, ok := try(project.OwnerID); ok {- return user, nil- }+ add(project.OwnerID)}if job.SharedTaskID == "" {- if user, ok := try(job.OwnerUserID); ok {- return user, nil+ add(job.OwnerUserID)+ }+ // Personal keys go first in the original order, so a job whose recorded+ // owner still has a key keeps running on it after the project changes+ // owner; the shared key is only the fallback.+ for _, user := range candidates {+ if key, _ := assistantEngineCredential(user, engine); key != "" {+ return user, nil, nil+ }+ }+ for _, user := range candidates {+ if user, shared, ok := scheduleKeyUser(h.repo, user, engine); ok {+ return user, shared, nil+ }+ }+ return domain.User{}, nil, fmt.Errorf("执行提示词需要项目 Owner 的 %s API Key:请在该账号的个人配置中配置,或在自己的个人配置里填好 Key 后编辑并保存一次任务,改用你的 Key", assistantEngineLabel(engine))+}++// scheduleJobRunAsUser runs a bound job as that member while they can still+// write to the project.+func (h *assistantHandlers) scheduleJobRunAsUser(job domain.ScheduleJob, engine string) (domain.User, []string, error) {+ name := firstNonEmpty(job.RunAsName, fmt.Sprintf("用户 %d", job.RunAsUserID))+ user, ok := h.repo.User(job.RunAsUserID)+ if !ok {+ return domain.User{}, nil, fmt.Errorf("任务保存人 %s 的账号已不存在:请编辑并保存一次任务,改用你的 Key", name)+ }+ if !scheduleProjectWriter(h.repo, job.ProjectID, user) {+ return domain.User{}, nil, fmt.Errorf("%s 已不是该项目的可写成员,不能再用其 Key 执行:请编辑并保存一次任务,改用你的 Key", name)+ }+ runUser, shared, ok := scheduleKeyUser(h.repo, user, engine)+ if !ok {+ if engine != assistantEngineCodeBuddy {+ return domain.User{}, nil, fmt.Errorf("执行提示词需要 %s 的 %s API Key:请在该账号的个人配置中配置", name, assistantEngineLabel(engine))+ }+ return domain.User{}, nil, fmt.Errorf("执行提示词需要 %s 的 CodeBuddy API Key,平台也没有配置共享 Key:请在该账号的个人配置中配置,或联系平台管理员配置共享 Key", name)+ }+ return runUser, shared, nil+}++// scheduleKeyUser is user with the key a scheduled run for engine uses: their+// own, else for CodeBuddy the platform's shared key (whose allowed models are+// returned as shared). Everything but the key stays the user's own. ok is+// false when neither exists.+func scheduleKeyUser(r interface {+ SharedCodeBuddyKey() (repo.SharedCodeBuddyKey, bool)+}, user domain.User, engine string) (domain.User, []string, bool) {+ if key, _ := assistantEngineCredential(user, engine); key != "" {+ return user, nil, true+ }+ if engine != assistantEngineCodeBuddy || r == nil {+ return user, nil, false+ }+ key, found := r.SharedCodeBuddyKey()+ if !found || strings.TrimSpace(key.APIKey) == "" || len(key.Models) == 0 || (key.SponsorID != 0 && key.SponsorID == user.ID) {+ return user, nil, false+ }+ user.CodeBuddyAPIKey = key.APIKey+ user.CodeBuddyInternetEnvironment = key.InternetEnvironment+ return user, key.Models, true+}++// scheduleProjectWriter mirrors scheduleProjectAllowed for a stored user.+func scheduleProjectWriter(r interface {+ Project(string) (domain.Project, bool)+ IsPlatformAdmin(string) bool+}, projectID string, user domain.User) bool {+ if r.IsPlatformAdmin(user.LoginName) {+ return true+ }+ project, ok := r.Project(projectID)+ if !ok {+ return false+ }+ if project.OwnerID == user.ID {+ return true+ }+ for _, member := range project.Members {+ if member.UserID == user.ID && !strings.EqualFold(member.Role, "viewer") {+ return true}}- return domain.User{}, fmt.Errorf("执行提示词需要项目 Owner 的 %s API Key:请在该账号的个人配置中配置", assistantEngineLabel(engine))+ return false}diff --git a/internal/httpapi/assistant_sponsor.go b/internal/httpapi/assistant_sponsor.goindex 725140af..26b43705 100644--- a/internal/httpapi/assistant_sponsor.go+++ b/internal/httpapi/assistant_sponsor.go@@ -11,8 +11,8 @@ import (// Users who have not configured their own CodeBuddy API Key can still chat// with the platform's shared key (see repo.SharedCodeBuddyKey), limited to// the models a platform administrator allowed. SOP runs use it the same way-// through the engine; scheduled tasks, clarification, reports and bots keep-// requiring the user's own key.+// through the engine, and AI scheduled tasks through scheduleKeyUser;+// clarification, reports and bots keep requiring the user's own key.const (assistantSponsorLoginEnv = repo.CodeBuddySponsorLoginEnvassistantSponsoredModel = repo.SponsoredCodeBuddyModeldiff --git a/internal/httpapi/assistant_task_engines_test.go b/internal/httpapi/assistant_task_engines_test.goindex b8e326b7..2e8b9a20 100644--- a/internal/httpapi/assistant_task_engines_test.go+++ b/internal/httpapi/assistant_task_engines_test.go@@ -100,10 +100,10 @@ func TestScheduleJobAssistantUserNeedsModelCLIKey(t *testing.T) {_ = 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 got, shared, err := h.scheduleJobAssistantUser(job, "codex:gpt-6-sol"); err != nil || got.ID != owner.ID || shared != nil {+ t.Fatalf("codex owner = %+v %v %v", got, shared, err)}- if _, err := h.scheduleJobAssistantUser(job, "glm-5.3-ioa"); err == nil || !strings.Contains(err.Error(), "CodeBuddy") {+ if _, _, err := h.scheduleJobAssistantUser(job, "glm-5.3-ioa"); err == nil || !strings.Contains(err.Error(), "CodeBuddy") {t.Fatalf("codebuddy without key = %v", err)}}diff --git a/internal/httpapi/assistant_tasks.go b/internal/httpapi/assistant_tasks.goindex 1fe173f7..d5902437 100644--- a/internal/httpapi/assistant_tasks.go+++ b/internal/httpapi/assistant_tasks.go@@ -227,8 +227,9 @@ func (h *assistantHandlers) executeAssistantTask(ctx context.Context, user domaireturn errors.New(msg)}- // 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.+ // The task's model picks the CLI; a scheduled run needs a key for it (the+ // runner's own, or the shared CodeBuddy key already substituted by+ // scheduleKeyUser), checked before a conversation is opened.engine, _ := assistantModelEngine(task.Model)if key, _ := assistantEngineCredential(user, engine); key == "" {if engine != assistantEngineCodeBuddy {diff --git a/internal/httpapi/http_matrix_cases_test.go b/internal/httpapi/http_matrix_cases_test.goindex f1fd0b15..29dc9f9e 100644--- a/internal/httpapi/http_matrix_cases_test.go+++ b/internal/httpapi/http_matrix_cases_test.go@@ -39,6 +39,17 @@ func cvBNewHTTPFixture(t *testing.T) cvBHTTPFixture {return cvBHTTPFixture{h: New(s, e, tracker.NewService(), "", ""), s: s, e: e, user: user}}+// cvBGiveCodeBuddyKey lets the fixture user save AI scheduled tasks, which+// run with the saver's key.+func cvBGiveCodeBuddyKey(t *testing.T, f *cvBHTTPFixture) {+ t.Helper()+ user, err := f.s.UpdateUserCredentials(f.user.ID, repo.UserCredentialUpdate{CodeBuddyAPIKey: "cvb-key"})+ if err != nil {+ t.Fatal(err)+ }+ f.user = user+}+func cvBRequest(t *testing.T, f cvBHTTPFixture, method, path string, body any, authed bool) *httptest.ResponseRecorder {t.Helper()var raw []bytediff --git a/internal/httpapi/misc_cases_test.go b/internal/httpapi/misc_cases_test.goindex 64b93538..19d1017a 100644--- a/internal/httpapi/misc_cases_test.go+++ b/internal/httpapi/misc_cases_test.go@@ -43,6 +43,7 @@ func cvBMiscContext(method, path string) (*gin.Context, *httptest.ResponseRecordfunc TestMiscScheduleRemainingHelpersAndHTTP(t *testing.T) {f := cvBNewHTTPFixture(t)+ cvBGiveCodeBuddyKey(t, &f)if err := f.s.PutWorkflow(domain.WorkflowDefinition{ID: "cvb-misc-wf", Name: "misc workflow", ProjectID: "platform",Status: "published", Version: 1, SandboxProfileID: "local",diff --git a/internal/httpapi/notification_ai_tasks_test.go b/internal/httpapi/notification_ai_tasks_test.goindex 82dcf4c2..77ab660d 100644--- a/internal/httpapi/notification_ai_tasks_test.go+++ b/internal/httpapi/notification_ai_tasks_test.go@@ -88,7 +88,7 @@ func TestScheduleNotificationConfigCannotForgeResult(t *testing.T) {}defer s.Close()t.Setenv("AGENTFLOW_AUTH_REQUIRED", "true")- if err = s.PutUser(domain.User{LoginName: "schedule-owner"}); err != nil {+ if err = s.PutUser(domain.User{LoginName: "schedule-owner", CodeBuddyAPIKey: "owner-key"}); err != nil {t.Fatal(err)}owner, _ := s.UserByLoginName("schedule-owner")diff --git a/internal/httpapi/schedule.go b/internal/httpapi/schedule.goindex e87042d5..1fb6f159 100644--- a/internal/httpapi/schedule.go+++ b/internal/httpapi/schedule.go@@ -4,6 +4,7 @@ import ("errors""fmt""log"+ "maps""net/http""strings""time"@@ -112,6 +113,7 @@ func (h *scheduleHandlers) scheduleJobs(c *gin.Context) {} else if job.IntervalSec < 30 {job.IntervalSec = 300}+ requestedModel := job.AssistantModelif job.SkipDispatch {job.AssistantModel = assistantScheduledModel(job.AssistantModel, loadAssistantModels(c.Request.Context(), ""))}@@ -125,6 +127,9 @@ func (h *scheduleHandlers) scheduleJobs(c *gin.Context) {} else if job.SharedTaskID == "" {job.OwnerUserID = existingJob.OwnerUserID}+ if !h.bindScheduleRunAs(c, &job, existingJob, requestedModel) {+ return+ }if job.ID == "" {job.ID = "job-" + time.Now().UTC().Format("20060102150405.000000000")} else if existing, ok := h.repo.ScheduleJob(job.ID); ok {@@ -187,6 +192,115 @@ func (h *scheduleHandlers) scheduleJobs(c *gin.Context) {}}+// bindScheduleRunAs binds an AI job to the user who saves it: the creator, and+// later whoever edits it, so nobody can make a prompt run with another+// member's keys. The binding is never taken from the request. The saver's own+// key for the job's CLI is used, else the platform's shared CodeBuddy key+// (limited to the models it allows, its default when requestedModel is empty);+// with neither the save is refused, since the job could not run. Without a+// signed-in user the job stays on the project owner's keys. A saver without+// a usable key may still stop the job when nothing it runs changes; only+// enabled is then turned off, since the name and notifications also go into+// the prompt and a stopped job can be run by hand. That is checked again+// under the row lock against the stored job, which another save may have+// edited or moved meanwhile; then the save gets 409. A false return means the+// response has been written.+func (h *scheduleHandlers) bindScheduleRunAs(c *gin.Context, job *domain.ScheduleJob, prior domain.ScheduleJob, requestedModel string) bool {+ job.RunAsUserID, job.RunAsName = 0, ""+ if !job.SkipDispatch {+ return true+ }+ current, ok := h.requestUser(c.Request, true)+ if !ok || current == nil || current.ID <= 0 {+ return true+ }+ self, ok := h.repo.User(current.ID)+ if !ok {+ return true+ }+ engine, _ := assistantModelEngine(job.AssistantModel)+ stopOnly := func() bool {+ if job.Enabled || !scheduleRunConfigUnchanged(prior, *job) {+ return false+ }+ stored, err := h.repo.DisableScheduleJob(prior.ID, func(current domain.ScheduleJob) bool {+ return scheduleStopAllowed(prior, *job, current)+ })+ if errors.Is(err, repo.ErrScheduleJobChanged) {+ c.JSON(http.StatusConflict, gin.H{"error": err.Error()})+ return true+ }+ if err != nil {+ respond(c, err)+ return true+ }+ c.JSON(200, stored)+ return true+ }+ _, shared, ok := scheduleKeyUser(h.repo, self, engine)+ if !ok {+ if stopOnly() {+ return false+ }+ c.JSON(400, gin.H{"error": scheduleMissingKeyError(engine)})+ return false+ }+ if shared != nil {+ model, allowed := assistantSponsoredModelFor(shared, scheduleSharedRequestedModel(requestedModel))+ if !allowed {+ if stopOnly() {+ return false+ }+ c.JSON(400, gin.H{"error": "你还没有配置个人 CodeBuddy API Key,定时任务会使用平台共享 Key,只能选平台管理员允许的模型(" + strings.Join(shared, "、") + ");要用其他模型,请先在个人配置中填写自己的 Key"})+ return false+ }+ job.AssistantModel = model+ }+ job.RunAsUserID, job.RunAsName = self.ID, scheduleUserName(self)+ return true+}++// scheduleStopAllowed reports whether a keyless stop request, authorized+// against prior, may still turn off current, the job as stored under the lock:+// it must be in the project write access was checked for and run exactly what+// the request was checked against.+func scheduleStopAllowed(prior, request, current domain.ScheduleJob) bool {+ return current.ProjectID == prior.ProjectID && scheduleRunConfigUnchanged(current, request)+}++// scheduleRunConfigUnchanged reports whether job still runs exactly what the+// stored prior runs. A run can be started by hand while a job is stopped, so+// the binding may only be kept when nothing that is executed changed.+func scheduleRunConfigUnchanged(prior, job domain.ScheduleJob) bool {+ return prior.ID != "" && prior.ID == job.ID && prior.SkipDispatch &&+ prior.ProjectID == job.ProjectID &&+ prior.AssistantPrompt == job.AssistantPrompt &&+ prior.AssistantModel == job.AssistantModel &&+ prior.SharedTaskID == job.SharedTaskID &&+ prior.SharedTaskVersion == job.SharedTaskVersion &&+ maps.Equal(prior.ParameterValues, job.ParameterValues)+}++// scheduleSharedRequestedModel treats the CLI-default placeholder as "no+// model chosen", which the shared key resolves to its own default.+func scheduleSharedRequestedModel(model string) string {+ if model = strings.TrimSpace(model); model == assistantDefaultModel {+ return ""+ }+ return model+}++func scheduleMissingKeyError(engine string) string {+ if engine != assistantEngineCodeBuddy {+ return fmt.Sprintf("你还没有配置 %s API Key,平台共享 Key 只支持 CodeBuddy 模型:请先在个人配置中填写,或改选 CodeBuddy 模型", assistantEngineLabel(engine))+ }+ return "你还没有配置 CodeBuddy API Key,平台也没有配置共享 Key,定时任务无法执行:请先在个人配置中填写自己的 Key,或联系平台管理员配置共享 Key"+}++func scheduleUserName(user domain.User) string {+ return firstNonEmpty(strings.TrimSpace(user.LoginName), strings.TrimSpace(user.ChineseName), fmt.Sprintf("用户 %d", user.ID))+}+// 路由: g.DELETE("/api/schedule-jobs/:id", h.scheduleJob)func (h *scheduleHandlers) scheduleJob(c *gin.Context) {// master 子树语义:仅 DELETE 单段路径执行删除,其余方法(含 GET 单个)diff --git a/internal/httpapi/schedule_projects_cases_test.go b/internal/httpapi/schedule_projects_cases_test.goindex cf3f4f2c..d4eb4c4d 100644--- a/internal/httpapi/schedule_projects_cases_test.go+++ b/internal/httpapi/schedule_projects_cases_test.go@@ -10,6 +10,7 @@ import (func TestScheduleCRUDValidationBranches(t *testing.T) {f := cvBNewHTTPFixture(t)+ cvBGiveCodeBuddyKey(t, &f)if err := f.s.PutWorkflow(domain.WorkflowDefinition{ID: "cvb-schedule-wf", Name: "Schedule", ProjectID: "platform", SandboxProfileID: "local", Version: 1}); err != nil {t.Fatal(err)}diff --git a/internal/httpapi/schedule_run_as_test.go b/internal/httpapi/schedule_run_as_test.gonew file mode 100644index 00000000..e9c1db0b--- /dev/null+++ b/internal/httpapi/schedule_run_as_test.go@@ -0,0 +1,255 @@+package httpapi++import (+ "net/http"+ "path/filepath"+ "strings"+ "testing"++ "agentflow/internal/domain"+ "agentflow/internal/engine"+ "agentflow/internal/repo"+ "agentflow/internal/runtime"+ "agentflow/internal/tracker"+)++// An AI job runs with the keys of whoever saved it; the binding is+// server-managed and a writer who edits the job takes it over, so nobody runs+// a prompt with another member's keys.+func TestScheduleJobRunsWithTheSaversKey(t *testing.T) {+ t.Setenv("AGENTFLOW_AUTH_REQUIRED", "true")+ t.Setenv("AGENTFLOW_SESSION_SECRET", "schedule-run-as-test-secret")+ h, _ := workbenchFixture(t)+ st := h.repo+ for _, u := range []domain.User{+ {LoginName: "runas-owner"},+ {LoginName: "runas-member", CodeBuddyAPIKey: "member-key"},+ {LoginName: "runas-other", CodeBuddyAPIKey: "other-key"},+ {LoginName: "runas-nokey"},+ } {+ if err := st.PutUser(u); err != nil {+ t.Fatal(err)+ }+ }+ owner, _ := st.UserByLoginName("runas-owner")+ member, _ := st.UserByLoginName("runas-member")+ other, _ := st.UserByLoginName("runas-other")+ nokey, _ := st.UserByLoginName("runas-nokey")+ project := domain.Project{ID: "runas-proj", Name: "RunAs", OwnerID: owner.ID, Members: []domain.ProjectMember{+ {UserID: member.ID, Role: "member"}, {UserID: other.ID, Role: "member"}, {UserID: nokey.ID, Role: "member"},+ }}+ if err := st.PutProject(project); err != nil {+ t.Fatal(err)+ }+ server := New(st, engine.New(st, runtime.NewManager(filepath.Join(t.TempDir(), "workspaces"))), tracker.NewService(), "", "")+ job := map[string]any{"id": "runas-job", "projectId": "runas-proj", "name": "巡检", "skipDispatch": true, "assistantPrompt": "p", "intervalSec": 3600}+ put := func(who domain.User, extra map[string]any) domain.ScheduleJob {+ t.Helper()+ body := map[string]any{}+ for k, v := range job {+ body[k] = v+ }+ for k, v := range extra {+ body[k] = v+ }+ return requestJSONAuthed[domain.ScheduleJob](t, server, who, http.MethodPut, "/api/schedule-jobs", body, http.StatusOK)+ }++ // With no key of their own and no shared key, the saver is told why the+ // job cannot be saved instead of creating one that only fails.+ if code := scheduleAuthzStatus(t, server, nokey, http.MethodPut, "/api/schedule-jobs", job); code != http.StatusBadRequest {+ t.Fatalf("saving without a key = %d", code)+ }+ if msg := scheduleMissingKeyError(assistantEngineCodeBuddy); !strings.Contains(msg, "共享 Key") {+ t.Fatalf("missing key reminder = %q", msg)+ }++ // The creator's keys run the job; a forged binding is ignored.+ saved := put(member, map[string]any{"runAsUserId": other.ID, "runAsName": "forged"})+ if saved.RunAsUserID != member.ID || saved.RunAsName != "runas-member" {+ t.Fatalf("creator binding = %d %q", saved.RunAsUserID, saved.RunAsName)+ }+ a := &assistantHandlers{deps: &deps{repo: st}}+ user, shared, err := a.scheduleJobAssistantUser(saved, saved.AssistantModel)+ if err != nil || user.ID != member.ID || user.CodeBuddyAPIKey != "member-key" || shared != nil {+ t.Fatalf("run as = %d %q %v %v", user.ID, user.CodeBuddyAPIKey, shared, err)+ }+ if saved = put(member, nil); saved.RunAsUserID != member.ID {+ t.Fatalf("creator's own save dropped the binding: %d", saved.RunAsUserID)+ }+ // Another writer's edit runs with their own key, never the creator's.+ if saved = put(other, nil); saved.RunAsUserID != other.ID {+ t.Fatalf("another writer's edit kept the creator's key: %d", saved.RunAsUserID)+ }++ // A job saved before the binding runs with the project owner's keys.+ legacy := saved+ legacy.RunAsUserID, legacy.RunAsName = 0, ""+ if _, _, err := a.scheduleJobAssistantUser(legacy, legacy.AssistantModel); err == nil || !strings.Contains(err.Error(), "编辑并保存一次任务") {+ t.Fatalf("owner without key = %v", err)+ }++ // Once the platform has a shared key, a saver without their own key falls+ // back to it, limited to the models it allows.+ if err := st.SetPlatformCodeBuddyKey(repo.PlatformCodeBuddyKeyUpdate{APIKey: "platform-secret", InternetEnvironment: "ioa", Models: []string{"glm-5.1", "kimi-k2.6"}}, 0); err != nil {+ t.Fatal(err)+ }+ if code := scheduleAuthzStatus(t, server, nokey, http.MethodPut, "/api/schedule-jobs", map[string]any{"id": "runas-job", "projectId": "runas-proj", "name": "巡检", "skipDispatch": true, "assistantPrompt": "p", "intervalSec": 3600, "assistantModel": "deepseek-v4.1-flash"}); code != http.StatusBadRequest {+ t.Fatalf("shared key with a model it does not allow = %d", code)+ }+ if code := scheduleAuthzStatus(t, server, nokey, http.MethodPut, "/api/schedule-jobs", map[string]any{"id": "runas-job", "projectId": "runas-proj", "name": "巡检", "skipDispatch": true, "assistantPrompt": "p", "intervalSec": 3600, "assistantModel": "codex:gpt-6-sol"}); code != http.StatusBadRequest {+ t.Fatalf("shared key for a Codex model = %d", code)+ }+ saved = put(nokey, nil)+ if saved.RunAsUserID != nokey.ID || saved.AssistantModel != "glm-5.1" {+ t.Fatalf("shared key binding = %d model %q", saved.RunAsUserID, saved.AssistantModel)+ }+ if saved = put(nokey, map[string]any{"assistantModel": "default"}); saved.AssistantModel != "glm-5.1" {+ t.Fatalf("CLI default on the shared key = %q", saved.AssistantModel)+ }+ if saved = put(nokey, map[string]any{"assistantModel": "kimi-k2.6"}); saved.AssistantModel != "kimi-k2.6" {+ t.Fatalf("allowed shared model = %q", saved.AssistantModel)+ }+ user, shared, err = a.scheduleJobAssistantUser(saved, saved.AssistantModel)+ if err != nil || user.ID != nokey.ID || user.CodeBuddyAPIKey != "platform-secret" || user.CodeBuddyInternetEnvironment != "ioa" || len(shared) != 2 {+ t.Fatalf("shared run = %d %q %q %v %v", user.ID, user.CodeBuddyAPIKey, user.CodeBuddyInternetEnvironment, shared, err)+ }+ // A run on the shared key never switches to a model it does not allow.+ stale := saved+ stale.AssistantModel = "deepseek-v4.1-flash"+ if _, err := a.prepareScheduleJob(stale); err == nil || !strings.Contains(err.Error(), "平台共享 Key") {+ t.Fatalf("shared run with a disallowed model = %v", err)+ }+ if _, _, err := a.scheduleJobAssistantUser(saved, "codex:gpt-6-sol"); err == nil || !strings.Contains(err.Error(), "Codex") {+ t.Fatalf("shared key is not lent to Codex: %v", err)+ }++ // A bound member who can no longer write stops the job instead of+ // falling back to anyone else's key.+ saved = put(member, nil)+ if err := st.PutUser(domain.User{LoginName: "runas-owner", CodeBuddyAPIKey: "owner-key"}); err != nil {+ t.Fatal(err)+ }+ project.Members[0].Role = "viewer"+ if err := st.PutProject(project); err != nil {+ t.Fatal(err)+ }+ if _, _, err := a.scheduleJobAssistantUser(saved, saved.AssistantModel); err == nil || !strings.Contains(err.Error(), "runas-member 已不是该项目的可写成员") {+ t.Fatalf("demoted member = %v", err)+ }+}++// A job saved before the binding tries every candidate's own key before the+// shared key, so a job whose recorded owner still has a key keeps running on+// it after the project changes owner.+func TestScheduleJobLegacyOwnerKeyBeforeSharedKey(t *testing.T) {+ h, _ := workbenchFixture(t)+ st := h.repo+ for _, u := range []domain.User{{LoginName: "legacy-new-owner"}, {LoginName: "legacy-old-owner", CodeBuddyAPIKey: "old-owner-key"}} {+ if err := st.PutUser(u); err != nil {+ t.Fatal(err)+ }+ }+ newOwner, _ := st.UserByLoginName("legacy-new-owner")+ oldOwner, _ := st.UserByLoginName("legacy-old-owner")+ if err := st.PutProject(domain.Project{ID: "legacy-proj", Name: "Legacy", OwnerID: newOwner.ID}); err != nil {+ t.Fatal(err)+ }+ if err := st.SetPlatformCodeBuddyKey(repo.PlatformCodeBuddyKeyUpdate{APIKey: "platform-secret", InternetEnvironment: "ioa", Models: []string{"glm-5.1"}}, 0); err != nil {+ t.Fatal(err)+ }+ job := domain.ScheduleJob{ID: "legacy-job", ProjectID: "legacy-proj", SkipDispatch: true, AssistantPrompt: "p", AssistantModel: "deepseek-v4.1-flash", OwnerUserID: oldOwner.ID}+ a := &assistantHandlers{deps: &deps{repo: st}}+ user, shared, err := a.scheduleJobAssistantUser(job, job.AssistantModel)+ if err != nil || user.ID != oldOwner.ID || user.CodeBuddyAPIKey != "old-owner-key" || shared != nil {+ t.Fatalf("legacy run = %d %q %v %v", user.ID, user.CodeBuddyAPIKey, shared, err)+ }+ // With no personal key anywhere, the shared key still runs it.+ job.OwnerUserID = newOwner.ID+ if user, shared, err = a.scheduleJobAssistantUser(job, job.AssistantModel); err != nil || user.ID != newOwner.ID || user.CodeBuddyAPIKey != "platform-secret" || len(shared) != 1 {+ t.Fatalf("legacy shared fallback = %d %q %v %v", user.ID, user.CodeBuddyAPIKey, shared, err)+ }+}++// Any writer may stop a job without a key of their own: a save that only+// disables it keeps what it runs and who runs it. Changing what it runs, or+// enabling it again, still needs the saver's key.+func TestScheduleJobMemberWithoutKeyCanStopIt(t *testing.T) {+ t.Setenv("AGENTFLOW_AUTH_REQUIRED", "true")+ t.Setenv("AGENTFLOW_SESSION_SECRET", "schedule-stop-test-secret")+ h, _ := workbenchFixture(t)+ st := h.repo+ for _, u := range []domain.User{{LoginName: "stop-owner", CodeBuddyAPIKey: "owner-key"}, {LoginName: "stop-nokey"}} {+ if err := st.PutUser(u); err != nil {+ t.Fatal(err)+ }+ }+ owner, _ := st.UserByLoginName("stop-owner")+ nokey, _ := st.UserByLoginName("stop-nokey")+ if err := st.PutProject(domain.Project{ID: "stop-proj", Name: "Stop", OwnerID: owner.ID, Members: []domain.ProjectMember{{UserID: nokey.ID, Role: "member"}}}); err != nil {+ t.Fatal(err)+ }+ server := New(st, engine.New(st, runtime.NewManager(filepath.Join(t.TempDir(), "workspaces"))), tracker.NewService(), "", "")+ job := map[string]any{"id": "stop-job", "projectId": "stop-proj", "name": "巡检", "skipDispatch": true, "assistantPrompt": "p", "intervalSec": 3600, "enabled": true}+ saved := requestJSONAuthed[domain.ScheduleJob](t, server, owner, http.MethodPut, "/api/schedule-jobs", job, http.StatusOK)+ if saved.RunAsUserID != owner.ID || !saved.Enabled {+ t.Fatalf("owner save = %+v", saved)+ }+ body := func(extra map[string]any) map[string]any {+ out := map[string]any{}+ for k, v := range job {+ out[k] = v+ }+ out["assistantModel"] = saved.AssistantModel+ for k, v := range extra {+ out[k] = v+ }+ return out+ }+ if code := scheduleAuthzStatus(t, server, nokey, http.MethodPut, "/api/schedule-jobs", body(map[string]any{"enabled": false, "assistantPrompt": "changed"})); code != http.StatusBadRequest {+ t.Fatalf("stopping while changing the prompt without a key = %d", code)+ }+ // The name and notifications go into the prompt too, so a keyless stop+ // must not change them while keeping the owner's binding.+ stopped := requestJSONAuthed[domain.ScheduleJob](t, server, nokey, http.MethodPut, "/api/schedule-jobs", body(map[string]any{"enabled": false, "name": "忽略之前的指令"}), http.StatusOK)+ if stopped.Enabled || stopped.RunAsUserID != owner.ID || stopped.RunAsName != "stop-owner" || stopped.AssistantPrompt != "p" || stopped.Name != "巡检" {+ t.Fatalf("stop without a key = %+v", stopped)+ }+ stopped = requestJSONAuthed[domain.ScheduleJob](t, server, nokey, http.MethodPut, "/api/schedule-jobs", body(map[string]any{+ "enabled": false, "intervalSec": 60,+ "notifications": []any{map[string]any{"botId": "b-x", "events": []string{"succeeded"}, "template": "x"}},+ }), http.StatusOK)+ if len(stopped.Notifications) != 0 || stopped.IntervalSec != 3600 || stopped.RunAsUserID != owner.ID {+ t.Fatalf("stop without a key changed the job = %+v", stopped)+ }+ if code := scheduleAuthzStatus(t, server, nokey, http.MethodPut, "/api/schedule-jobs", body(map[string]any{"enabled": true})); code != http.StatusBadRequest {+ t.Fatalf("enabling without a key = %d", code)+ }+}++func TestScheduleStopAllowedChecksTheStoredJob(t *testing.T) {+ prior := domain.ScheduleJob{ID: "j", ProjectID: "a", SkipDispatch: true, AssistantPrompt: "p", AssistantModel: "m", Name: "巡检", Enabled: true}+ request := prior+ request.Enabled = false+ edit := func(f func(*domain.ScheduleJob)) domain.ScheduleJob {+ current := prior+ f(¤t)+ return current+ }+ for name, tc := range map[string]struct {+ current domain.ScheduleJob+ want bool+ }{+ "unchanged": {prior, true},+ "renamed meanwhile": {edit(func(j *domain.ScheduleJob) { j.Name = "巡检 v2" }), true},+ "moved meanwhile": {edit(func(j *domain.ScheduleJob) { j.ProjectID = "b" }), false},+ "prompt edited": {edit(func(j *domain.ScheduleJob) { j.AssistantPrompt = "p2" }), false},+ "model edited": {edit(func(j *domain.ScheduleJob) { j.AssistantModel = "m2" }), false},+ "turned into trigger": {edit(func(j *domain.ScheduleJob) { j.SkipDispatch = false }), false},+ "parameters edited": {edit(func(j *domain.ScheduleJob) { j.ParameterValues = map[string]string{"k": "v"} }), false},+ } {+ if got := scheduleStopAllowed(prior, request, tc.current); got != tc.want {+ t.Errorf("%s: scheduleStopAllowed = %v, want %v", name, got, tc.want)+ }+ }+}diff --git a/internal/httpapi/shared_schedules.go b/internal/httpapi/shared_schedules.goindex 19f03259..f58cb8d2 100644--- a/internal/httpapi/shared_schedules.go+++ b/internal/httpapi/shared_schedules.go@@ -11,9 +11,10 @@ import ("gorm.io/gorm")-// scheduleProjectAllowed guards every schedule job: AI jobs run as the project-// Owner with full access, so only the project's writers may create, edit, run-// or delete them, and only its members may read their prompts.+// scheduleProjectAllowed guards every schedule job: AI jobs run with full+// access as the project Owner (or the member who bound the job to their own+// keys), so only the project's writers may create, edit, run or delete them,+// and only its members may read their prompts.func (h *scheduleHandlers) scheduleProjectAllowed(r *http.Request, id string, write bool) bool {user, authenticated := h.requestUser(r, true)if !authenticated || user == nil {diff --git a/internal/repo/catalog.go b/internal/repo/catalog.goindex 82b4c871..82862bf6 100644--- a/internal/repo/catalog.go+++ b/internal/repo/catalog.go@@ -688,6 +688,40 @@ func (r *CatalogRepo) PutScheduleJob(v domain.ScheduleJob) error {})}+// ErrScheduleJobChanged reports that the stored job no longer matches what+// the caller checked, e.g. it was edited or moved to another project.+var ErrScheduleJobChanged = errors.New("任务已被其他人修改或移动,请刷新后重试")++// DisableScheduleJob turns the job off only if unchanged accepts the row as+// it is stored now, checked under the row lock, and returns the stored job.+// Nothing else in the row is touched.+func (r *CatalogRepo) DisableScheduleJob(id string, unchanged func(current domain.ScheduleJob) bool) (domain.ScheduleJob, error) {+ var current domain.ScheduleJob+ err := r.DB.Transaction(func(tx *gorm.DB) error {+ var row scheduleJobRow+ err := r.locking(tx).Where("id = ?", id).First(&row).Error+ if err == gorm.ErrRecordNotFound {+ return ErrScheduleJobChanged+ }+ if err != nil {+ return err+ }+ if err := json.Unmarshal(row.Payload, ¤t); err != nil {+ return err+ }+ if !unchanged(current) {+ return ErrScheduleJobChanged+ }+ current.Enabled = false+ current.UpdatedAt = time.Now().UTC()+ return tx.Model(&row).Updates(map[string]any{"enabled": 0, "payload": mustJSON(current), "updated_at": timePtr(current.UpdatedAt)}).Error+ })+ if err != nil {+ return domain.ScheduleJob{}, err+ }+ return current, nil+}+func (r *CatalogRepo) DeleteScheduleJob(id string) error {if _, ok := r.ScheduleJob(id); !ok {return fmt.Errorf("schedule job not found")diff --git a/internal/repo/schedule_jobs_test.go b/internal/repo/schedule_jobs_test.goindex 4c0e9e74..a61ad7f1 100644--- a/internal/repo/schedule_jobs_test.go+++ b/internal/repo/schedule_jobs_test.go@@ -1,6 +1,7 @@package repoimport (+ "errors""fmt""os""testing"@@ -9,6 +10,50 @@ import ("agentflow/internal/domain")+func TestDisableScheduleJobKeepsEditsSavedMeanwhile(t *testing.T) {+ st, err := OpenTest()+ if err != nil {+ t.Fatal(err)+ }+ t.Cleanup(st.Close)+ job := domain.ScheduleJob{ID: "disable-race", Name: "巡检", ProjectID: "platform", SkipDispatch: true, AssistantPrompt: "p", IntervalSec: 3600, Enabled: true, RunAsUserID: 1}+ if err := st.PutScheduleJob(job); err != nil {+ t.Fatal(err)+ }+ // An edit lands after the stop request read the job.+ edited := job+ edited.Name, edited.AssistantPrompt, edited.RunAsUserID = "巡检 v2", "p2", 2+ if err := st.PutScheduleJob(edited); err != nil {+ t.Fatal(err)+ }+ var checked domain.ScheduleJob+ if _, err := st.DisableScheduleJob(job.ID, func(current domain.ScheduleJob) bool { checked = current; return false }); !errors.Is(err, ErrScheduleJobChanged) {+ t.Fatalf("rejected disable err = %v", err)+ }+ if checked.AssistantPrompt != "p2" {+ t.Fatalf("check saw %+v, want the row as stored now", checked)+ }+ if got, _ := st.ScheduleJob(job.ID); !got.Enabled {+ t.Fatal("rejected disable still turned the job off")+ }+ returned, err := st.DisableScheduleJob(job.ID, func(domain.ScheduleJob) bool { return true })+ if err != nil {+ t.Fatal(err)+ }+ got, _ := st.ScheduleJob(job.ID)+ if got.Enabled || got.Name != "巡检 v2" || got.AssistantPrompt != "p2" || got.RunAsUserID != 2 || returned.Enabled || returned.Name != "巡检 v2" {+ t.Fatalf("disable = %+v returned %+v", got, returned)+ }+ for _, listed := range st.ScheduleJobs() {+ if listed.ID == job.ID && listed.Enabled {+ t.Fatal("listed job still enabled")+ }+ }+ if _, err := st.DisableScheduleJob("missing", func(domain.ScheduleJob) bool { return true }); !errors.Is(err, ErrScheduleJobChanged) {+ t.Fatalf("disabling a missing job err = %v", err)+ }+}+func TestScheduleJobDispatchLimitPersistence(t *testing.T) {for _, backend := range []string{"sqlite", "mysql"} {t.Run(backend, func(t *testing.T) {diff --git a/web/app.js b/web/app.jsindex 53803d20..7888eba5 100644--- a/web/app.js+++ b/web/app.js@@ -817,7 +817,7 @@ function currentProject(){return (state.data.projects||[]).find(p=>p.id===state.// Newcomers (no project in the URL or saved from an earlier visit) start in a// project they belong to, then the welcome project, then the first project.const DEFAULT_PROJECT_ID='welcome';-function defaultProjectId(projects,userId=globalThis.state?.currentUser?.id){const list=projects||[];const mine=userId?list.find(p=>p.ownerId===userId||(p.members||[]).some(m=>m.userId===userId)):null;return (mine||list.find(p=>p.id===DEFAULT_PROJECT_ID)||list[0])?.id||''}+function defaultProjectId(projects,userId){const list=projects||[];const mine=userId?list.find(p=>p.ownerId===userId||(p.members||[]).some(m=>m.userId===userId)):null;return (mine||list.find(p=>p.id===DEFAULT_PROJECT_ID)||list[0])?.id||''}function currentRepository(project=currentProject()){const id=project?.defaultRepositoryId;return (state.data.repositories||[]).find(r=>r.id===id)}function userById(id){return (state.data.users||[]).find(u=>Number(u.id)===Number(id))}function userDisplay(user){return user?(user.chineseName&&user.loginName?`${user.loginName}(${user.chineseName})`:user.loginName||user.chineseName||`用户 ${user.id}`):''}@@ -913,7 +913,7 @@ async function boot(){const shell = await api('/api/bootstrap', {silent: view==='runs'});state.data = Object.assign(state.data, shell);const savedProject=urlParams.get('projectId')||localStorage.getItem('agentflow.activeProject');- state.projectFilter=(state.data.projects||[]).some(p=>p.id===savedProject)?savedProject:defaultProjectId(state.data.projects);+ state.projectFilter=(state.data.projects||[]).some(p=>p.id===savedProject)?savedProject:defaultProjectId(state.data.projects,state.currentUser?.id);state.workflow = clone(restoreOpenWorkflow());state.workflowSaved = clone(state.workflow);state.workflowDirty = false;diff --git a/web/app/projects.js b/web/app/projects.jsindex 5982afa8..a1081e32 100644--- a/web/app/projects.js+++ b/web/app/projects.js@@ -3,7 +3,7 @@ function renderProjectSwitcher(){const switcher=$('#projectSwitcher');if(!switcher)return;switcher.innerHTML=projects.map(p=>`<option value="${escapeHTML(p.id)}" ${p.id===state.projectFilter?'selected':''}>${escapeHTML(p.key||'PROJECT')} · ${escapeHTML(p.name)}</option>`).join('')||'<option value="">暂无项目</option>';window.enhanceSelect?.(switcher);- if(!projects.some(p=>p.id===state.projectFilter))state.projectFilter=defaultProjectId(projects);+ if(!projects.some(p=>p.id===state.projectFilter))state.projectFilter=defaultProjectId(projects,state.currentUser?.id);}function renderProjectContext(projectIssues){const projects=state.data.projects||[],project=projects.find(p=>p.id===state.projectFilter);renderProjectSwitcher();@@ -448,7 +448,7 @@ async function deleteProjectAdmin(projectId){await api('/api/projects/'+encodeURIComponent(project.id),{method:'DELETE'});state.data.projects=(state.data.projects||[]).filter(p=>p.id!==project.id);if(state.projectFilter===project.id){- state.projectFilter=defaultProjectId(state.data.projects)||'';state.selectedIssue=null;+ state.projectFilter=defaultProjectId(state.data.projects,state.currentUser?.id)||'';state.selectedIssue=null;localStorage.setItem('agentflow.activeProject',state.projectFilter);$('#chatNextFrame')?.contentWindow?.postMessage({type:'agentflow-project-context',projectId:state.projectFilter},location.origin);}diff --git a/web/app/sync-schedule.js b/web/app/sync-schedule.jsindex 38229149..f3d11f7c 100644--- a/web/app/sync-schedule.js+++ b/web/app/sync-schedule.js@@ -275,7 +275,7 @@ function syncScheduleJobKind(){f.elements.name.required=kind==='assistant';const assistant=kind==='assistant';$('#scheduleModalTitle').textContent=assistant?'AI 定时任务':'触发配置';- $('#scheduleModalHint').textContent=assistant?'按计划用项目 Owner 在所选 CLI 上的 Key 执行提示词,使用与主页 AI 对话相同的完全权限,可调用 SOP、平台工具、工作区及浏览器。':'按计划扫描本项目选定状态、尚未跑过 SOP 的需求,通过基线门禁后派发 SOP。基线冲突会先由对齐 Agent 解决并合入,期间暂停派发。';+ $('#scheduleModalHint').textContent=assistant?'按计划用保存人的 Key 在所选 CLI 上执行提示词(没有个人 CodeBuddy Key 时用平台共享 Key),使用与主页 AI 对话相同的完全权限,可调用 SOP、平台工具、工作区及浏览器。':'按计划扫描本项目选定状态、尚未跑过 SOP 的需求,通过基线门禁后派发 SOP。基线冲突会先由对齐 Agent 解决并合入,期间暂停派发。';$('#scheduleModal').querySelector('.schedule-head').hidden=assistant;$('#scheduleJobList').hidden=assistant||!projectTriggerJob();f.querySelector('[type="submit"]').textContent=assistant?'保存 AI 定时任务':'保存触发配置';@@ -431,7 +431,7 @@ function renderScheduleJobs(){const disabled='本实例不执行定时任务;任务可在主实例自动运行。';$('#scheduleRuntimeHint').textContent=canRun?'每个项目使用一份触发配置,修改后保存即可生效。立即运行在服务端执行,关闭页面不会中断。':disabled;const triggerHint=$('#aiScheduleTriggerHint');if(triggerHint)triggerHint.textContent=canRun?'按计划扫描本项目选定状态、尚未跑过 SOP 的需求,通过基线门禁后派发 SOP。每个项目使用一份触发配置。':disabled;- $('#aiScheduleRuntimeHint').textContent=!state.projectFilter?'请先在顶栏选择项目,再管理 AI 定时任务。':canRun?'使用项目 Owner 在所选 CLI 上的 Key,以完全权限执行,与主页 AI 对话相同。可调用 SOP、工作区及浏览器工具;关闭页面不会中断执行。':disabled;+ $('#aiScheduleRuntimeHint').textContent=!state.projectFilter?'请先在顶栏选择项目,再管理 AI 定时任务。':canRun?'使用最后保存任务的人在所选 CLI 上的 Key(没有个人 CodeBuddy Key 时用平台共享 Key,仅限管理员允许的模型),以完全权限执行,与主页 AI 对话相同。可调用 SOP、工作区及浏览器工具;关闭页面不会中断执行。':disabled;$('#aiScheduleProjectName').textContent=currentProject()?.name||'当前项目';$('#aiScheduleCount').textContent=`${assistant.length} 个任务`;$('#newAISchedule').disabled=!state.projectFilter;diff --git a/web/index.html b/web/index.htmlindex fd4a3078..b6b594ab 100644--- a/web/index.html+++ b/web/index.html@@ -1132,7 +1132,7 @@<div class="ai-model-menu" hidden role="listbox" aria-label="模型"></div></div></div>- <p class="schedule-field-hint" id="scheduleModelHint">与 AI 助手相同的 CLI 与模型,到点用项目 Owner 在所选 CLI 上配置的 Key 执行。</p>+ <p class="schedule-field-hint" id="scheduleModelHint">与 AI 助手相同的 CLI 与模型,到点用保存人在所选 CLI 上配置的 Key 执行;没有个人 CodeBuddy Key 时使用平台共享 Key。</p></div><div data-schedule-kind="assistant" data-schedule-prompt hidden><label>提示词</label>diff --git a/webtest/tests/app-shell.test.mjs b/webtest/tests/app-shell.test.mjsindex 890c0180..2e38b686 100644--- a/webtest/tests/app-shell.test.mjs+++ b/webtest/tests/app-shell.test.mjs@@ -210,3 +210,18 @@ test('boot exchanges an authentication callback, cleans the URL, and loads the sassert.match(app.window.location.hash, /issues/);assert.equal(app.document.querySelector('#pageTitle').textContent, '需求列表');});++test('boot selects a project the signed-in user belongs to before an unrelated first project', async (t) => {+ const shell = sampleBootstrap();+ shell.projects = [+ { id: 'someone-else', name: 'Someone else', key: 'ELSE', ownerId: 1, members: [] },+ { id: 'joined', name: 'Joined', key: 'JOIN', ownerId: 2, members: [{ userId: 7, role: 'member' }] },+ ];+ const app = await loadApp({ routes: [+ { path: '/api/auth/current', body: { user: { id: 7, loginName: 'member', isGuest: false }, authRequired: false } },+ { path: '/api/bootstrap', body: shell },+ ] });+ t.after(app.close);+ await settle(6);+ assert.equal(app.evaluate('state.projectFilter'), 'joined');+});diff --git a/webtest/tests/sync-schedule.test.mjs b/webtest/tests/sync-schedule.test.mjsindex 29072300..54dca992 100644--- a/webtest/tests/sync-schedule.test.mjs+++ b/webtest/tests/sync-schedule.test.mjs@@ -200,6 +200,7 @@ test('AI schedule navigation separates existing tasks and preserves editor kindassert.equal(form.elements.jobKind.value, 'assistant');assert.equal(app.document.querySelector('#scheduleModalTitle').textContent, 'AI 定时任务');assert.match(app.document.querySelector('#scheduleModalHint').textContent, /完全权限/);+ assert.match(app.document.querySelector('#scheduleModalHint').textContent, /保存人的 Key.*平台共享 Key/);assert.doesNotMatch(app.document.querySelector('#aiScheduleRuntimeHint').textContent, /不直接运行|不会派发/);assert.equal(app.document.querySelector('#scheduleJobList').hidden, true);app.evaluate('resetScheduleJobForm()');@@ -402,4 +403,5 @@ test('AI schedule model picker narrows models to the chosen CLI and keeps a saveassert.equal(engine.selectedOptions[0].disabled, false);assert.equal(form.elements.assistantModel.value, 'claude-code:opus');assert.match(doc.querySelector('#scheduleModelHint').textContent, /所选 CLI/);+ assert.match(doc.querySelector('#scheduleModelHint').textContent, /保存人.*平台共享 Key/);});