创建你的第一个任务
+描述目标让系统规划,或提供已有任务清单,在这里统一管理执行与结果。
+ +diff --git a/README.md b/README.md index b6ba4762..283d35d2 100644 --- a/README.md +++ b/README.md @@ -11,7 +11,7 @@ CyberStrikeAI is a cybersecurity agent workbench built with **Go + Pi**. Describe the outcome you want: the agent interprets your intent, plans steps, calls tools, and records evidence. It reports progress as it works, asks for missing information or decisions, and continues from the saved state after you answer. -This repository is maintained by **Sycun**, building on [AIPentest/CyberStrikeAI](https://github.com/AIPentest/CyberStrikeAI) with the upstream history, license, and copyright notices preserved. The current version is ready for team trials. Start the new workflow from **Task Management → Goal tasks**. +This repository is maintained by **Sycun**, building on [AIPentest/CyberStrikeAI](https://github.com/AIPentest/CyberStrikeAI) with the upstream history, license, and copyright notices preserved. The current version is ready for team trials. Start the new workflow from **Task Management → New task**. [Quick start](#quick-start) · [Delegate your first task](#delegation) · [Capabilities](#capabilities) · [Architecture](#architecture) · [Documentation](#documentation) · [Feedback](#contributing) @@ -76,11 +76,11 @@ A deployment needs the runtime source and a matching Pi worker bundle, or a fres -## Goal tasks +## Task management -Open **Task Management → Goal tasks**, describe the objective, scope and acceptance criteria, save a draft, then start it. The coordinator schedules dependent steps through the existing Pi Agent and revises the plan as results arrive. +Open **Task Management → New task** and choose autonomous planning or checklist execution. Objectives drive adaptive plans; supplied checklists support manual or Cron execution. Both appear in one searchable task list. -Inspect execution conversations, checkpoints and activity; pause/resume, supply guidance, answer questions, retry failed steps and adjust time or planning-round budgets. Completed work is retained. Blocked, interrupted and budget-exhausted tasks are distinct from successful completion. Existing batch queues remain in the same page. +Inspect execution conversations, checkpoints and activity; pause/resume, supply guidance, answer questions, retry failed steps and adjust time or planning-round budgets. Completed work is retained. Blocked, interrupted and budget-exhausted tasks are distinct from successful completion. Existing queues, schedules and execution records remain available in the shared list. See [task management, source research and validation boundaries](docs/zh-CN/long-running-tasks.md). diff --git a/README_CN.md b/README_CN.md index b39ce3a1..f4e7061a 100644 --- a/README_CN.md +++ b/README_CN.md @@ -11,7 +11,7 @@ CyberStrikeAI 是基于 **Go + Pi** 的网络安全智能体工作台。你描述希望完成的工作,智能体理解意图、规划步骤、调用工具并保存证据;执行中持续汇报进展,遇到缺失信息或需要你决定的问题时主动请示,得到答复后从原进度继续。 -本仓库由 **Sycun** 维护,基于 [AIPentest/CyberStrikeAI](https://github.com/AIPentest/CyberStrikeAI) 持续开发,保留上游历史、许可证与版权声明。当前版本适合团队内测,新功能入口为 **「任务管理 → 目标任务」**。 +本仓库由 **Sycun** 维护,基于 [AIPentest/CyberStrikeAI](https://github.com/AIPentest/CyberStrikeAI) 持续开发,保留上游历史、许可证与版权声明。当前版本适合团队内测,新功能入口为 **「任务管理 → 新建任务」**。 [快速上手](#quick-start) · [体验任务闭环](#delegation) · [主要能力](#capabilities) · [架构](#architecture) · [文档](#documentation) · [反馈](#contributing) @@ -76,11 +76,11 @@ go build -o cyberstrike-ai ./cmd/server -## 目标任务 +## 任务管理 -进入 **任务管理 → 目标任务**,描述目标、范围与验收条件,保存草稿后手动启动。系统把工作拆成有依赖的步骤,用现有 Pi Agent 执行,再根据结果调整路线。 +进入 **任务管理 → 新建任务**,在同一个表单中选择“自主规划”或“按清单执行”。前者根据目标、范围与验收条件持续规划和执行;后者执行每行一项的清单,也支持 Cron。所有任务在同一个列表中搜索、筛选和管理。 -可以查看每一步的执行会话、阶段结果与任务动态,暂停/继续,补充方向,答复问题,重试失败步骤,或调整时间与规划轮数预算。已完成步骤保留;预算耗尽、受阻和中断分别显示,不当成任务完成。原有批量队列位于同页的「批量队列」页签。 +可以查看每一步的执行会话、阶段结果与任务动态,暂停/继续,补充方向,答复问题,重试失败步骤,或调整时间与规划轮数预算。已完成步骤保留;预算耗尽、受阻和中断分别显示,不当成任务完成。已有清单、定时配置与执行记录保留在统一列表中。 实现、GitHub 调研依据、API 和验证边界见[任务管理与长程能力](docs/zh-CN/long-running-tasks.md)。 diff --git a/docs/zh-CN/long-running-tasks.md b/docs/zh-CN/long-running-tasks.md index 5310d83d..e07c6d9f 100644 --- a/docs/zh-CN/long-running-tasks.md +++ b/docs/zh-CN/long-running-tasks.md @@ -1,11 +1,11 @@ -# 任务管理:目标任务与批量队列 +# 统一任务管理 -2026-11-13。个人维护线用同一个「任务管理」入口承载两种工作:目标任务根据结果持续调整计划,批量队列执行用户给定的任务列表。原深度测评模块、专属 API、页面、权限及运行引擎已移除;上游 [PR #383](https://github.com/AIPentest/CyberStrikeAI/pull/383) 已关闭。 +2026-11-13。「任务管理」只有一个列表和一个「新建任务」入口。创建时选择“自主规划”或“按清单执行”:前者根据结果持续调整计划,后者执行用户提供的任务清单并可设置 Cron。原深度测评模块、专属 API、页面、权限及运行引擎已移除;上游 [PR #383](https://github.com/AIPentest/CyberStrikeAI/pull/383) 已关闭。 ## 使用 -1. 打开「任务管理 → 目标任务 → 新建目标任务」,填写目标、允许范围和验收条件。可选择项目、执行角色、模型渠道和工具审批方式。 -2. 保存后处于草稿状态。检查内容,点击「开始执行」。创建本身不调用模型或执行工具。 +1. 打开「任务管理 → 新建任务」。选择“自主规划”后填写目标、允许范围和验收条件;选择“按清单执行”后每行填写一个子任务。项目、角色、审批和并发设置在同一表单中。 +2. 自主规划保存为草稿,手动清单创建为待执行,均需手动开始;若明确选择 Cron,创建后按设定时间自动执行,表单会显示这一行为。 3. 查看持续推进路线、步骤依赖、已观察结果和任务动态。每个步骤关联一个可打开的执行会话,沿用现有过程详情、工具监控、Pi 会话与项目事实。 4. 运行中可提交补充方向,下一轮规划会使用。需要用户信息时,任务进入「待答复」;答复后尝试恢复,恢复失败会明确显示原因,已保存答复不会丢失。 5. 暂停后等到收尾完成再续跑。失败、中断、受阻步骤可明确重试;已完成步骤不重新执行。原执行会话继续保留。重试之前应检查前一次是否已经产生效果。 @@ -13,7 +13,7 @@ 例:目标为「整理已提供的本地安全测试材料,形成可交付报告」,范围列出允许读取的文件、输出目录以及“不访问新的目标”,验收条件列出需要包含的证据、覆盖缺口、文件格式及检查方式。不要把目标只写成“深度测评”,应描述希望交付什么。 -批量队列保留原创建、并发、Cron、单条执行和管理能力;目标任务不改变已有队列。 +旧任务、清单、Cron 和执行会话直接出现在统一列表中;清单详情嵌入同一工作区,保留单条执行、编辑、添加、重跑与定时设置。界面按状态和执行方式统一搜索、排序、分页。底层保留两种执行器及原 API,不重写已有数据。 ## 执行机制 @@ -58,10 +58,11 @@ flowchart TD ## API -使用现有 `tasks:read/write/delete` 权限,资源类型 `long_task`。所有单任务接口也检查资源范围。 +使用现有 `tasks:read/write/delete` 权限。统一列表分别检查 `long_task` 和 `batch_task` 资源范围,再合并、筛选与分页;相同 ID 的不同资源不会互相继承授权。原有单任务接口继续检查自身资源范围。 | 接口 | 用途 | | --- | --- | +| `GET /api/tasks?mode=&status=&q=&limit=30&offset=0` | 统一列表;mode 可为 goal/list,包含旧任务及清单,摘要不包含执行轨迹 | | `GET /api/long-tasks/options` | 可用项目、角色与模型渠道,不返回密钥 | | `GET /api/long-tasks?status=&q=&limit=30&offset=0` | 分页列表;摘要不携带完整目标材料或执行轨迹 | | `POST /api/long-tasks` | 保存草稿;字段见任务创建表单 | @@ -83,7 +84,7 @@ flowchart TD ### 本次实际验证 -- `go test ./...`、前端现有 344 项 Node 测试、Go 构建与相关包 `go vet` 通过。 +- 原有全量回归之外,增加统一列表的跨资源权限隔离、合并后分页、混合失败及 Cron 状态保留测试;浏览器检查从真实入口覆盖两种创建方式和详情切换。 - 新增任务控制器与 HTTP/真实 Pi Worker 集成回归:依赖链、慢规划/慢 Worker、失败路径替换、验收补做、时间/轮数预算、暂停恢复、事务失败不启动、权限/来源/版本冲突、任务记忆隔离与长输出尾部检索。 - 真实 Pi SDK 对接本地模拟模型与工具,验证工具—检查点—记忆—结果—验收闭环,以及工具失败后模型虚报成功被拒绝。这里的“真实 Pi”不代表使用了真实供应商模型。 - 真实前端的离线 Playwright 测试覆盖鉴权请求、草稿创建不执行、控制操作、报告下载、轮询保留输入、XSS 转义、明暗主题及 390/1440px 布局。夹具不操作任何现有任务或目标。 diff --git a/internal/app/app.go b/internal/app/app.go index cd88a9cf..a6631c0d 100644 --- a/internal/app/app.go +++ b/internal/app/app.go @@ -1110,7 +1110,8 @@ func setupRoutes( protected.PUT("/assets/:id", assetHandler.Update) protected.DELETE("/assets/:id", assetHandler.Delete) - // 任务管理:目标任务与批量队列 + // 统一任务列表,兼容两种既有执行方式 + protected.GET("/tasks", agentHandler.ListManagedTasks) protected.GET("/long-tasks/options", agentHandler.LongTaskOptions) protected.GET("/long-tasks", agentHandler.ListLongTasks) protected.POST("/long-tasks", agentHandler.CreateLongTask) diff --git a/internal/database/managed_tasks.go b/internal/database/managed_tasks.go new file mode 100644 index 00000000..40c1ec8c --- /dev/null +++ b/internal/database/managed_tasks.go @@ -0,0 +1,85 @@ +package database + +// ManagedTaskRow is the shared task-list projection. Execution data stays with +// its existing owner so saved queues, schedules and conversations keep working. +type ManagedTaskRow struct { + ID string `json:"id"` + Mode string `json:"mode"` + Name string `json:"name"` + Status string `json:"status"` + ProjectID string `json:"project_id"` + Summary string `json:"summary"` + UpdatedAt string `json:"updated_at"` + CompletedSteps int `json:"completed_steps"` + TotalSteps int `json:"total_steps"` + ScheduleMode string `json:"schedule_mode"` + NextRunAt string `json:"next_run_at,omitempty"` +} + +// ListManagedTasks merges before filtering/paging, avoiding gaps or duplicates +// caused by paginating the two sources independently. No execution traces enter +// the listing, and each source uses its own RBAC resource assignments. +func (db *DB) ListManagedTasks(user, scope, mode, status, query string, limit, offset int) ([]ManagedTaskRow, error) { + access := func(alias, resource string) (string, []any) { + if scope == RBACScopeAll { + return "1=1", nil + } + assigned := `EXISTS(SELECT 1 FROM rbac_resource_assignments r WHERE r.user_id=? AND r.resource_type='` + resource + `' AND r.resource_id=` + alias + `.id)` + if scope == RBACScopeOwn { + return `(` + alias + `.owner_user_id=? OR ` + assigned + `)`, []any{user, user} + } + return assigned, []any{user} + } + goals, ga := access("g", "long_task") + queues, qa := access("q", "batch_task") + sql := `WITH entries AS ( + SELECT g.id,'goal' AS mode,g.name,g.status,g.project_id, + substr(COALESCE(json_extract(g.payload,'$.summary'),''),1,2000) AS summary, + COALESCE(strftime('%Y-%m-%dT%H:%M:%fZ',g.updated_at),'') AS updated_at, + (SELECT COUNT(*) FROM json_each(g.payload,'$.steps') WHERE json_extract(value,'$.status')='completed') AS completed_steps, + (SELECT COUNT(*) FROM json_each(g.payload,'$.steps') WHERE json_extract(value,'$.status')<>'retired') AS total_steps, + 'manual' AS schedule_mode,'' AS next_run_at + FROM long_tasks g WHERE ` + goals + ` + UNION ALL + SELECT q.id,'list',COALESCE(NULLIF(q.title,''),q.id), + CASE WHEN q.status='completed' AND EXISTS(SELECT 1 FROM batch_tasks b WHERE b.queue_id=q.id AND b.status='failed') THEN + CASE WHEN EXISTS(SELECT 1 FROM batch_tasks b WHERE b.queue_id=q.id AND b.status='completed') THEN 'partial' ELSE 'failed' END + WHEN q.status='completed' AND q.schedule_mode='cron' AND COALESCE(q.schedule_enabled,1)=1 THEN 'scheduled' + ELSE q.status END, + COALESCE(q.project_id,''),substr(COALESCE(NULLIF(q.last_run_error,''),q.last_schedule_error,''),1,2000), + COALESCE(strftime('%Y-%m-%dT%H:%M:%fZ',COALESCE(q.completed_at,q.started_at,q.created_at)),''), + (SELECT COUNT(*) FROM batch_tasks b WHERE b.queue_id=q.id AND b.status='completed'), + (SELECT COUNT(*) FROM batch_tasks b WHERE b.queue_id=q.id), + COALESCE(q.schedule_mode,'manual'),COALESCE(strftime('%Y-%m-%dT%H:%M:%fZ',q.next_run_at),'') + FROM batch_task_queues q WHERE ` + queues + ` + ) SELECT id,mode,name,status,project_id,summary,updated_at,completed_steps,total_steps,schedule_mode,next_run_at FROM entries WHERE 1=1` + args := append(ga, qa...) + if mode != "" { + sql += ` AND mode=?` + args = append(args, mode) + } + if status != "" { + sql += ` AND status=?` + args = append(args, status) + } + if query != "" { + sql += ` AND (instr(lower(name),lower(?))>0 OR instr(id,?)>0)` + args = append(args, query, query) + } + sql += ` ORDER BY updated_at DESC,mode,id LIMIT ? OFFSET ?` + args = append(args, limit, offset) + rows, err := db.Query(sql, args...) + if err != nil { + return nil, err + } + defer rows.Close() + out := []ManagedTaskRow{} + for rows.Next() { + var row ManagedTaskRow + if err = rows.Scan(&row.ID, &row.Mode, &row.Name, &row.Status, &row.ProjectID, &row.Summary, &row.UpdatedAt, &row.CompletedSteps, &row.TotalSteps, &row.ScheduleMode, &row.NextRunAt); err != nil { + return nil, err + } + out = append(out, row) + } + return out, rows.Err() +} diff --git a/internal/handler/openapi_long_tasks.go b/internal/handler/openapi_long_tasks.go index 7b54ff03..db06124a 100644 --- a/internal/handler/openapi_long_tasks.go +++ b/internal/handler/openapi_long_tasks.go @@ -24,6 +24,7 @@ func addLongTaskSpec(spec map[string]interface{}) { return op } id := map[string]interface{}{"name": "id", "in": "path", "required": true, "schema": stringSchema} + paths["/api/tasks"] = map[string]interface{}{"get": operation("统一任务列表:按 mode、status、q 筛选后统一分页", nil, nil)} paths["/api/long-tasks"] = map[string]interface{}{"get": operation("分页查询目标任务;支持 status、q、limit、offset", nil, nil), "post": operation("创建目标任务草稿,不自动执行", create, nil)} paths["/api/long-tasks"].(map[string]interface{})["post"].(map[string]interface{})["responses"].(map[string]interface{})["201"] = map[string]interface{}{"description": "草稿已保存"} paths["/api/long-tasks/options"] = map[string]interface{}{"get": operation("查询可用项目、角色与模型渠道", nil, nil)} diff --git a/internal/handler/task_list.go b/internal/handler/task_list.go new file mode 100644 index 00000000..ddf1b229 --- /dev/null +++ b/internal/handler/task_list.go @@ -0,0 +1,48 @@ +package handler + +import ( + "fmt" + "strconv" + "strings" + + "cyberstrike-ai/internal/security" + "github.com/gin-gonic/gin" + "go.uber.org/zap" +) + +// ListManagedTasks is the single task-management listing for autonomous work +// and supplied checklists. Existing execution APIs remain compatible. +func (h *AgentHandler) ListManagedTasks(c *gin.Context) { + session, ok := security.CurrentSession(c) + if !ok { + c.JSON(401, gin.H{"error": "请先登录"}) + return + } + mode := c.Query("mode") + if mode != "" && mode != "goal" && mode != "list" { + longTaskError(c, fmt.Errorf("无效的执行方式")) + return + } + limit, _ := strconv.Atoi(c.DefaultQuery("limit", "30")) + if limit < 1 || limit > 100 { + limit = 30 + } + offset, _ := strconv.Atoi(c.DefaultQuery("offset", "0")) + if offset < 0 { + offset = 0 + } + if offset > 100000 { + offset = 100000 + } + rows, err := h.db.ListManagedTasks(session.UserID, session.ScopeFor("tasks:read"), mode, c.Query("status"), strings.TrimSpace(c.Query("q")), limit+1, offset) + if err != nil { + h.logger.Error("查询任务列表失败", zap.Error(err)) + c.JSON(500, gin.H{"error": "查询任务列表失败"}) + return + } + more := len(rows) > limit + if more { + rows = rows[:limit] + } + c.JSON(200, gin.H{"tasks": rows, "has_more": more}) +} diff --git a/internal/handler/task_list_test.go b/internal/handler/task_list_test.go new file mode 100644 index 00000000..07a701c4 --- /dev/null +++ b/internal/handler/task_list_test.go @@ -0,0 +1,107 @@ +package handler + +import ( + "encoding/json" + "net/http/httptest" + "testing" + + "cyberstrike-ai/internal/database" + "cyberstrike-ai/internal/security" + "github.com/gin-gonic/gin" +) + +func TestManagedTaskListMergesBeforePagingAndKeepsResourceScopes(t *testing.T) { + h, task := longTaskFixture(t) + initial, err := h.db.ListManagedTasks(task.OwnerID, database.RBACScopeOwn, "goal", "", "", 30, 0) + if err != nil || len(initial) != 1 || initial[0].UpdatedAt == "" { + t.Fatalf("invalid stored timestamp: %+v %v", initial, err) + } + other, err := h.db.CreateRBACUser("list-other", "Other", "hash", true, nil) + if err != nil { + t.Fatal(err) + } + insert := func(id, owner, title, status, created string) { + t.Helper() + _, err := h.db.Exec(`INSERT INTO batch_task_queues(id,title,owner_user_id,status,created_at) VALUES(?,?,?,?,?)`, id, title, owner, status, created) + if err != nil { + t.Fatal(err) + } + } + insert(task.ID, other.ID, "foreign with the same ID", "pending", "2030-01-03T00:00:00Z") + insert("owned", task.OwnerID, "owned checklist", "pending", "2030-01-02T00:00:00Z") + insert("shared", other.ID, "shared checklist", "pending", "2030-01-01T00:00:00Z") + if err = h.db.AssignResourceToUser(task.OwnerID, "batch_task", "shared"); err != nil { + t.Fatal(err) + } + if _, err = h.db.Exec(`UPDATE long_tasks SET updated_at='2030-01-04T00:00:00Z' WHERE id=?`, task.ID); err != nil { + t.Fatal(err) + } + r := gin.New() + r.Use(func(c *gin.Context) { + c.Set(security.ContextSessionKey, security.Session{UserID: task.OwnerID, Scope: database.RBACScopeOwn, Permissions: map[string]bool{"tasks:read": true}}) + }) + r.Use(security.RBACMiddleware(h.db)) + r.GET("/api/tasks", h.ListManagedTasks) + get := func(query string) struct { + Tasks []database.ManagedTaskRow `json:"tasks"` + More bool `json:"has_more"` + } { + t.Helper() + w := httptest.NewRecorder() + r.ServeHTTP(w, httptest.NewRequest("GET", "/api/tasks"+query, nil)) + if w.Code != 200 { + t.Fatalf("%d %s", w.Code, w.Body.String()) + } + var body struct { + Tasks []database.ManagedTaskRow `json:"tasks"` + More bool `json:"has_more"` + } + if err := json.Unmarshal(w.Body.Bytes(), &body); err != nil { + t.Fatal(err) + } + return body + } + first := get("?limit=1") + second := get("?limit=1&offset=1") + third := get("?limit=1&offset=2") + if len(first.Tasks) != 1 || first.Tasks[0].Mode != "goal" || !first.More || second.Tasks[0].ID != "owned" || third.Tasks[0].ID != "shared" || third.More { + t.Fatalf("bad merged pages: %+v %+v %+v", first, second, third) + } + if rows := get("?mode=list").Tasks; len(rows) != 2 { + t.Fatalf("cross-resource exposure or missing assignment: %+v", rows) + } + if rows := get("?q=foreign").Tasks; len(rows) != 0 { + t.Fatalf("foreign row exposed: %+v", rows) + } + if rows := get("?status=pending").Tasks; len(rows) != 2 { + t.Fatalf("bad status filtering: %+v", rows) + } + if rows := get("?q=owned").Tasks; len(rows) != 1 || rows[0].ID != "owned" { + t.Fatalf("bad search: %+v", rows) + } +} + +func TestManagedTaskListPreservesScheduledAndPartialOutcomes(t *testing.T) { + h, task := longTaskFixture(t) + for _, id := range []string{"partial", "failed", "scheduled"} { + if _, err := h.db.Exec(`INSERT INTO batch_task_queues(id,title,owner_user_id,status,created_at,schedule_mode,schedule_enabled,next_run_at) VALUES(?,?,?,'completed','2030-01-01T00:00:00Z','cron',1,'2030-01-02T00:00:00Z')`, id, id, task.OwnerID); err != nil { + t.Fatal(err) + } + } + for i, item := range []struct{ queue, status string }{{"partial", "completed"}, {"partial", "failed"}, {"failed", "failed"}, {"scheduled", "completed"}} { + if _, err := h.db.Exec(`INSERT INTO batch_tasks(id,queue_id,message,status) VALUES(?,?,?,?)`, i, item.queue, "PRIVATE EXECUTION INSTRUCTION", item.status); err != nil { + t.Fatal(err) + } + } + rows, err := h.db.ListManagedTasks(task.OwnerID, database.RBACScopeOwn, "list", "", "", 30, 0) + if err != nil { + t.Fatal(err) + } + found := map[string]database.ManagedTaskRow{} + for _, row := range rows { + found[row.ID] = row + } + if found["partial"].Status != "partial" || found["partial"].CompletedSteps != 1 || found["partial"].TotalSteps != 2 || found["failed"].Status != "failed" || found["scheduled"].Status != "scheduled" || found["scheduled"].NextRunAt == "" { + t.Fatalf("outcomes lost: %+v", found) + } +} diff --git a/internal/security/rbac_middleware.go b/internal/security/rbac_middleware.go index 98c20807..cb0bba08 100644 --- a/internal/security/rbac_middleware.go +++ b/internal/security/rbac_middleware.go @@ -123,7 +123,7 @@ func permissionForRequest(method, fullPath string) string { return "hitl:read" } return "hitl:write" - case strings.HasPrefix(path, "/agent-loop"), strings.HasPrefix(path, "/batch-tasks"), strings.HasPrefix(path, "/long-tasks"): + case path == "/tasks", strings.HasPrefix(path, "/agent-loop"), strings.HasPrefix(path, "/batch-tasks"), strings.HasPrefix(path, "/long-tasks"): return crudPermission(method, "tasks") case path == "/usage/tokens": return "dashboard:read" diff --git a/scripts/helpers/task-ui-fixture.cjs b/scripts/helpers/task-ui-fixture.cjs index ff2c9ebd..97db3102 100644 --- a/scripts/helpers/task-ui-fixture.cjs +++ b/scripts/helpers/task-ui-fixture.cjs @@ -40,6 +40,13 @@ async function fixture(t) { if (state.hook) { const intercepted = await state.hook(request); if (intercepted) return send(intercepted.status || 200, intercepted.body); } if (url.pathname === '/api/projects') return send(200, { projects: [] }); if (url.pathname === '/api/long-tasks/options') return send(200, { projects: [], roles: [], models: [] }); + if (url.pathname === '/api/tasks') { + const rows = [...state.tasks.values()].map(task => ({ ...task, mode: 'goal', completed_steps: task.steps.filter(step => step.status === 'completed').length, total_steps: task.steps.length })); + for (const q of state.queues.values()) rows.push({ id:q.id, mode:'list', name:q.title, status:q.status, summary:q.lastRunError || '', updated_at:q.createdAt, schedule_mode:q.scheduleMode, next_run_at:q.nextRunAt, completed_steps:q.tasks.filter(step => step.status==='completed').length, total_steps:q.tasks.length }); + const filtered=rows.filter(task => (!url.searchParams.get('mode') || task.mode===url.searchParams.get('mode')) && (!url.searchParams.get('status') || task.status===url.searchParams.get('status')) && (!url.searchParams.get('q') || task.name.includes(url.searchParams.get('q')))); + const offset=Number(url.searchParams.get('offset')||0),limit=Number(url.searchParams.get('limit')||30); + return send(200,{tasks:filtered.slice(offset,offset+limit),has_more:filtered.length>offset+limit}); + } if (url.pathname === '/api/long-tasks') { if (req.method === 'POST') { const task = { ...goal('new-' + state.tasks.size), ...body }; state.tasks.set(task.id, task); return send(201, { task }); } const tasks = [...state.tasks.values()].filter(task => (!url.searchParams.get('status') || task.status === url.searchParams.get('status')) && (!url.searchParams.get('q') || task.name.includes(url.searchParams.get('q')))); @@ -96,7 +103,7 @@ async function fixture(t) { await page.goto(`http://127.0.0.1:${server.address().port}/#tasks`); await page.locator('[data-lt-action=select][data-id=a]').waitFor(); await page.locator('#tasks-auto-refresh').uncheck(); - const select = async id => { await page.locator(`[data-lt-action=select][data-id="${id}"]`).click(); await page.waitForFunction(id => document.getElementById('lt-name').textContent === '目标 ' + id, id); }; + const select = async id => { await page.locator(`[data-lt-action=select][data-mode=goal][data-id="${id}"]`).click(); await page.waitForFunction(id => document.getElementById('lt-name').textContent === '目标 ' + id, id); }; const refresh = () => page.evaluate(() => refreshTaskWorkspace()); return { page, state, select, refresh }; } diff --git a/scripts/long-tasks-browser.test.cjs b/scripts/long-tasks-browser.test.cjs index 38c3ef16..2b5a8aea 100644 --- a/scripts/long-tasks-browser.test.cjs +++ b/scripts/long-tasks-browser.test.cjs @@ -33,6 +33,7 @@ test('goal task page: authenticated controls, stable polling, XSS, report and re if (req.url === '/api/auth/validate') { res.setHeader('Content-Type','application/json'); return res.end('{}'); } if (req.url === '/favicon.ico') { res.statusCode=204; return res.end(); } if (req.url.startsWith('/api/batch-tasks')) { res.setHeader('Content-Type','application/json'); return res.end(JSON.stringify({queues:[],total:0,total_pages:1})); } + if (req.url.startsWith('/api/tasks?')) { authenticated.push(req.headers.authorization); res.setHeader('Content-Type','application/json'); return res.end(JSON.stringify({tasks:[{...task,mode:'goal'}],has_more:false})); } if (req.url.startsWith('/api/long-tasks')) { authenticated.push(req.headers.authorization); if (req.headers.authorization !== 'Bearer fixture-token') { res.statusCode = 401; return res.end('{}'); } @@ -67,7 +68,7 @@ test('goal task page: authenticated controls, stable polling, XSS, report and re await page.waitForFunction(() => document.getElementById('long-task-workspace').dataset.initialized === 'true'); await page.evaluate(() => applyRBACToUI(document.getElementById('page-tasks'))); assert.equal(await page.locator('#task-new-goal').isVisible(), true); - assert.equal(await page.locator('#task-new-batch').isVisible(), false); + assert.equal(await page.locator('#task-new-batch').count(), 0); await page.locator('[data-lt-action=select]').click(); await page.locator('#lt-name').waitFor(); await page.waitForFunction(() => document.getElementById('lt-name').textContent.includes('本地材料')); @@ -105,15 +106,10 @@ test('goal task page: authenticated controls, stable polling, XSS, report and re await page.locator('#lt-modal [type=submit]').click(); await page.waitForFunction(() => !document.getElementById('lt-modal')); assert.equal(actions.filter(a => a === 'start').length, 1, 'creating a draft must not execute'); - await page.locator('[data-task-tab=batch]').click(); - assert.equal(await page.locator('#long-task-workspace').isVisible(), false); - assert.equal(await page.locator('#task-batch-workspace').isVisible(), true); - await page.evaluate(() => applyRBACToUI(document.getElementById('page-tasks'))); - assert.equal(await page.locator('#task-new-goal').isVisible(), false); - assert.equal(await page.locator('#task-new-batch').isVisible(), true); + assert.equal(await page.locator('[data-task-tab]').count(), 0, 'task management has one shared list'); await page.evaluate(() => { saveAuth('fixture-token',new Date(Date.now()+3600000),{permissions:['tasks:read'],scope:'own'}); applyRBACToUI(); }); - await page.locator('[data-task-tab=goals]').click(); - assert.equal(await page.locator('#task-new-goal').isVisible(), false, 'tab switches must preserve denied write permission'); + await page.locator('#lt-mode-filter').selectOption('goal'); + assert.equal(await page.locator('#task-new-goal').isVisible(), false, 'filters must preserve denied write permission'); await page.evaluate(() => cleanupTasksPage()); assert.equal(authenticated.every(a => a === 'Bearer fixture-token'), true); assert.ok(actions.includes('create') && actions.includes('report') && actions.includes('pause')); diff --git a/scripts/task-controls-browser.test.cjs b/scripts/task-controls-browser.test.cjs index b82164d3..ce91fa1a 100644 --- a/scripts/task-controls-browser.test.cjs +++ b/scripts/task-controls-browser.test.cjs @@ -73,8 +73,8 @@ test('goal paging, filters, refresh toggle, modal close and execution links work await page.locator('#task-new-goal').click(); await page.locator('#lt-modal').waitFor(); await page.locator('#lt-modal [data-close]').last().click(); await page.waitForFunction(() => !document.getElementById('lt-modal')); await page.locator('#task-new-goal').click(); await page.locator('#lt-modal').waitFor(); await page.keyboard.press('Escape'); await page.waitForFunction(() => !document.getElementById('lt-modal')); assert.equal(state.requests.filter(r => r.method === 'POST').length, 0); - await page.locator('#tasks-auto-refresh').check(); const count = state.requests.filter(r => r.path === '/api/long-tasks').length; - await page.waitForTimeout(4200); assert.ok(state.requests.filter(r => r.path === '/api/long-tasks').length > count); + await page.locator('#tasks-auto-refresh').check(); const count = state.requests.filter(r => r.path === '/api/tasks').length; + await page.waitForTimeout(4200); assert.ok(state.requests.filter(r => r.path === '/api/tasks').length > count); await page.locator('#tasks-auto-refresh').uncheck(); await refresh(); const stopped = state.requests.length; await page.waitForTimeout(4200); assert.equal(state.requests.length, stopped); await select('a'); await page.locator('.lt-step a').click(); await page.waitForFunction(() => window.visitedConversation === 'conversation-a'); @@ -112,14 +112,14 @@ test('creation failures keep form input, and budget/execution permissions match test('batch queue controls: create, close, metadata, add/edit/delete steps, single run, start/pause/resume/rerun/delete', async t => { const { page, state } = await fixture(t); - await page.locator('[data-task-tab=batch]').click(); await page.locator('#task-new-batch').click(); + await page.evaluate(() => showBatchImportModal()); await page.locator('#batch-import-modal').waitFor({ state: 'visible' }); await page.locator('#batch-queue-title').fill('New batch'); await page.locator('#batch-tasks-input').fill('Read local A\nRead local B'); await page.locator('[onclick="createBatchQueue()"]').click(); await page.locator('[data-bq-detail-for="new-queue"]').waitFor(); assert.equal(state.queues.get('new-queue').executeNow, false); - await page.locator('#batch-queue-detail-modal .modal-close').click(); - await page.locator('.batch-queue-item[data-queue-id=q1]').click(); await page.locator('[data-bq-detail-for=q1]').waitFor(); + await page.locator('[data-lt-action=select][data-id=a][data-mode=goal]').click(); + await page.locator('.lt-card[data-id=q1][data-mode=list]').click(); await page.locator('[data-bq-detail-for=q1]').waitFor(); await page.locator('#bq-title-val .bq-inline-editable').click(); await page.locator('#bq-edit-title').fill('Renamed queue'); await page.locator('#bq-edit-title').press('Enter'); await page.waitForFunction(() => document.getElementById('bq-title-val').textContent === 'Renamed queue'); assert.equal(state.queues.get('q1').title, 'Renamed queue'); await page.locator('#bq-concurrency-val .bq-inline-editable').click(); await page.locator('#bq-edit-concurrency').fill('2'); await page.locator('#bq-edit-concurrency').press('Enter'); @@ -136,14 +136,14 @@ test('batch queue controls: create, close, metadata, add/edit/delete steps, sing state.queues.get('q1').status = 'completed'; await page.evaluate(() => showBatchQueueDetail('q1')); await page.locator('#batch-queue-rerun-btn').click(); await page.locator('#batch-queue-pause-btn').waitFor({ state: 'visible' }); await page.locator('#batch-queue-pause-btn').click(); await page.locator('#batch-queue-delete-btn').waitFor({ state: 'visible' }); await page.locator('#batch-queue-delete-btn').click(); await page.locator('#batch-queue-detail-modal').waitFor({ state: 'hidden' }); assert.equal(state.queues.has('q1'), false); - await page.locator('.batch-queue-item[data-queue-id=new-queue] .batch-queue-icon-btn--danger').click(); await page.locator('.batch-queue-item[data-queue-id=new-queue]').waitFor({ state: 'detached' }); + await page.locator('.lt-card[data-id=new-queue][data-mode=list]').click(); await page.locator('[data-bq-detail-for=new-queue]').waitFor(); await page.locator('#batch-queue-delete-btn').click(); await page.locator('.lt-card[data-id=new-queue][data-mode=list]').waitFor({ state: 'detached' }); assert.deepEqual(state.pageErrors, []); }); test('batch create and add-step clicks cannot submit twice on a slow connection', async t => { const { page, state } = await fixture(t); state.hook = async req => { if (req.method === 'POST' && (req.path === '/api/batch-tasks' || req.path.endsWith('/tasks'))) await new Promise(resolve => setTimeout(resolve, 300)); }; - await page.locator('[data-task-tab=batch]').click(); await page.locator('#task-new-batch').click(); + await page.evaluate(() => showBatchImportModal()); await page.locator('#batch-tasks-input').fill('One local task'); await page.locator('[onclick="createBatchQueue()"]').dblclick(); await page.locator('[data-bq-detail-for="new-queue"]').waitFor(); assert.equal(state.requests.filter(r => r.method === 'POST' && r.path === '/api/batch-tasks').length, 1); @@ -155,15 +155,99 @@ test('batch create and add-step clicks cannot submit twice on a slow connection' test('late batch detail and creation lookups do not take over a newer selection or page', async t => { const { page, state } = await fixture(t); state.queues.set('q2', { ...state.queues.get('q1'), id: 'q2', title: 'Other queue' }); - await page.locator('[data-task-tab=batch]').click(); await page.evaluate(() => refreshBatchQueues()); + await page.evaluate(() => refreshBatchQueues()); let release; const gate = new Promise(resolve => { release = resolve; }); state.hook = async req => { if (req.path === '/api/batch-tasks/q1' && req.method === 'GET') await gate; }; - await page.locator('.batch-queue-item[data-queue-id=q1]').click(); await page.locator('#batch-queue-detail-modal .modal-close').click(); - await page.locator('.batch-queue-item[data-queue-id=q2]').click(); await page.locator('[data-bq-detail-for=q2]').waitFor(); + await page.locator('.lt-card[data-id=q1][data-mode=list]').click(); await page.locator('[data-lt-action=select][data-id=a][data-mode=goal]').click(); + await page.locator('.lt-card[data-id=q2][data-mode=list]').click(); await page.locator('[data-bq-detail-for=q2]').waitFor(); release(); await page.waitForTimeout(150); assert.equal(await page.locator('[data-bq-detail-for=q2]').count(), 1); - await page.locator('#batch-queue-detail-modal .modal-close').click(); + await page.locator('[data-lt-action=select][data-id=a][data-mode=goal]').click(); const createGate = new Promise(resolve => { release = resolve; }); state.hook = async req => { if (req.path === '/api/projects') await createGate; }; - await page.locator('#task-new-batch').click(); await page.evaluate(() => switchPage('dashboard')); release(); await page.waitForTimeout(150); + await page.evaluate(() => { void showBatchImportModal(); }); await page.evaluate(() => switchPage('dashboard')); release(); await page.waitForTimeout(150); assert.equal(await page.locator('#batch-import-modal').isVisible(), false); }); + +test('one task list and one creation form support objectives, checklists and schedules', async t => { + const { page, state } = await fixture(t); + assert.equal(await page.locator('[data-task-tab]').count(), 0); + assert.equal(await page.locator('#task-new-batch').count(), 0); + assert.equal(await page.locator('#lt-list [data-mode=goal]').count(), 2); + assert.equal(await page.locator('#lt-list [data-mode=list]').count(), 1); + await page.locator('#lt-mode-filter').selectOption('list'); + await page.waitForFunction(() => document.querySelectorAll('.lt-card').length === 1); + await page.locator('.lt-card[data-mode=list][data-id=q1]').click(); + await page.locator('#lt-batch-detail [data-bq-detail-for=q1]').waitFor(); + assert.equal(await page.locator('#batch-queue-detail-modal').evaluate(node => node.classList.contains('modal')), false); + await page.screenshot({path:'/tmp/csai-unified-task-list-preview.png'}); + assert.equal(await page.locator('#lt-detail').isVisible(),false); + await page.locator('#task-new-goal').click(); + await page.locator('#lt-modal [name=execution_mode][value=list]').check(); + await page.locator('#lt-modal [name=name]').fill('Unified checklist'); + await page.locator('#lt-modal [name=tasks_text]').fill('Read local A\nRead local B'); + await page.locator('#lt-modal [name=schedule_mode]').selectOption('cron'); + await page.locator('#lt-modal [name=cron_expr]').fill('0 2 * * *'); + assert.equal(await page.locator('#lt-modal [name=objective]').isDisabled(), true); + assert.match(await page.locator('.lt-dialog-note').textContent(), /自动执行/); + await page.locator('#lt-modal [type=submit]').click(); + await page.locator('#lt-batch-detail [data-bq-detail-for=new-queue]').waitFor(); + assert.equal(state.queues.get('new-queue').scheduleMode, 'cron'); + assert.equal(state.queues.get('new-queue').cronExpr, '0 2 * * *'); + assert.equal(state.queues.get('new-queue').executeNow, false); + assert.equal(state.queues.get('new-queue').tasks.length, 2); + assert.equal(await page.locator('#lt-list [data-mode=list]').count(), 2); + await page.locator('#task-new-goal').click(); + await page.locator('#lt-modal [name=name]').fill('Unified objective'); + await page.locator('#lt-modal [name=objective]').fill('Summarize the local report'); + await page.locator('#lt-modal [name=scope]').fill('Supplied local evidence only'); + await page.locator('#lt-modal [name=criteria]').fill('Every conclusion has evidence'); + assert.equal(await page.locator('#lt-modal [name=tasks_text]').isDisabled(), true); + await page.locator('#lt-modal [type=submit]').click(); + await page.waitForFunction(() => document.getElementById('lt-name').textContent === 'Unified objective'); + assert.equal(state.requests.filter(request => request.path.endsWith('/control/start')).length, 0); + assert.deepEqual(state.pageErrors, []); +}); + +test('creation and budget dialogs stay centered with visible actions on desktop and narrow screens', async t => { + const { page, state, select } = await fixture(t); + for (const theme of ['light', 'dark']) { + await page.evaluate(theme => document.documentElement.setAttribute('data-theme', theme), theme); + for (const size of [{width:1440,height:900},{width:1280,height:720},{width:390,height:844},{width:640,height:400}]) { + await page.setViewportSize(size); + await page.locator('#task-new-goal').click(); await page.locator('#lt-modal').waitFor(); + const layout = await page.evaluate(() => { + const rect = element => { const r=element.getBoundingClientRect();return {x:r.x,y:r.y,width:r.width,height:r.height,bottom:r.bottom,right:r.right}; }; + return {dialog:rect(document.getElementById('lt-modal')),footer:rect(document.querySelector('.lt-dialog-footer')),submit:rect(document.querySelector('#lt-modal [type=submit]')),body:rect(document.querySelector('.lt-dialog-body')),scrollWidth:document.querySelector('.lt-dialog-body').scrollWidth}; + }); + assert.ok(Math.abs(layout.dialog.x+layout.dialog.width/2-size.width/2)<2, JSON.stringify(layout)); + assert.ok(Math.abs(layout.dialog.y+layout.dialog.height/2-size.height/2)<2, JSON.stringify(layout)); + assert.ok(layout.dialog.y>=10 && layout.dialog.bottom<=size.height-10, JSON.stringify(layout)); + assert.ok(layout.submit.bottom<=size.height-10 && layout.submit.y>=0, JSON.stringify(layout)); + assert.ok(layout.scrollWidth<=layout.body.width+1, 'dialog body must not overflow horizontally'); + await page.evaluate(() => {const body=document.querySelector('.lt-dialog-body');body.scrollTop=body.scrollHeight;}); + const footer = await page.locator('.lt-dialog-footer').boundingBox(); assert.ok(Math.abs(footer.y-layout.footer.y)<2, 'footer must remain fixed while fields scroll'); + await page.evaluate(() => {document.querySelector('.lt-dialog-body').scrollTop=0;}); + if(size.width===1440 || size.width===390) await page.screenshot({path:`/tmp/csai-unified-task-dialog-${theme}-${size.width}.png`}); + if(theme==='light' && size.width===1440) await page.locator('#lt-modal').screenshot({path:'/tmp/csai-unified-task-dialog-preview.png'}); + await page.locator('#lt-modal .lt-dialog-close').click(); + } + } + await page.setViewportSize({width:1280,height:720}); await select('a'); await page.locator('[data-lt-action=budget]').click(); + const box=await page.locator('#lt-modal').boundingBox(); assert.ok(Math.abs(box.x+box.width/2-640)<2 && box.width<=550); + await page.locator('#lt-modal [data-close]').last().click(); assert.deepEqual(state.pageErrors, []); +}); + + +test('the unified empty state stays usable and checklist details fit narrow screens', async t => { + const { page,state,refresh }=await fixture(t); + await page.setViewportSize({width:390,height:844}); + await page.locator('.lt-card[data-mode=list][data-id=q1]').click();await page.locator('[data-bq-detail-for=q1]').waitFor(); + assert.ok(await page.evaluate(()=>document.documentElement.scrollWidth<=window.innerWidth+1)); + await page.locator('#batch-queue-start-btn').scrollIntoViewIfNeeded(); + const button=await page.locator('#batch-queue-start-btn').boundingBox();assert.ok(button.x>=0 && button.x+button.width<=390); + await page.screenshot({path:'/tmp/csai-unified-task-list-mobile.png'}); + await page.evaluate(()=>{onTaskQueueDeleted('q1');closeBatchQueueDetailModal();});state.tasks.clear();state.queues.clear();await refresh(); + await page.locator('#lt-empty-state').waitFor();assert.equal(await page.locator('#lt-board').isVisible(),false); + await page.locator('#lt-empty-state [data-lt-action=new]').click();await page.locator('#lt-modal').waitFor(); + await page.keyboard.press('Escape');assert.deepEqual(state.pageErrors,[]); +}); diff --git a/web/static/css/long-tasks.css b/web/static/css/long-tasks.css index e747cfd8..f5b2bc68 100644 --- a/web/static/css/long-tasks.css +++ b/web/static/css/long-tasks.css @@ -1,6 +1,3 @@ -.task-mode-tabs { display:flex; gap:6px; padding:0 24px 14px; border-bottom:1px solid var(--border-color,#ddd); } -.task-mode-tabs button { border:0; background:transparent; color:var(--text-secondary,#64748b); padding:10px 18px; border-radius:8px; cursor:pointer; font-weight:600; } -.task-mode-tabs button[aria-selected="true"] { background:var(--primary-color,#2563eb); color:white; } .lt-toolbar { display:flex; flex-wrap:wrap; gap:12px; align-items:center; margin-bottom:16px; } .lt-toolbar input { flex:1; min-width:140px; } .lt-toolbar input,.lt-toolbar select,.lt-dialog input,.lt-dialog select,.lt-dialog textarea,#lt-guidance-input { padding:10px 12px; border:1px solid var(--border-color,#d9dee7); border-radius:8px; background:var(--bg-primary,#fff); color:var(--text-primary,#172033); font:inherit; } @@ -43,24 +40,138 @@ #lt-events time { flex-shrink:0; color:var(--text-secondary,#64748b); } #lt-events span { white-space:pre-wrap; overflow-wrap:anywhere; min-width:0; } #lt-error,.lt-form-error { color:#b91c1c; padding:10px; overflow-wrap:anywhere; } -.lt-dialog { width:min(680px,calc(100vw - 32px)); max-height:90vh; box-sizing:border-box; border:1px solid var(--border-color,#e2e8f0); border-radius:14px; padding:24px; background:var(--bg-primary,#fff); color:var(--text-primary,#172033); } -.lt-dialog::backdrop { background:rgba(15,23,42,.55); } -.lt-dialog header,.lt-dialog footer { display:flex; align-items:center; justify-content:space-between; gap:12px; } -.lt-dialog header h3 { margin:0 0 12px; } -.lt-dialog [data-close] { cursor:pointer; } -.lt-dialog label { display:flex; flex-direction:column; gap:7px; margin-bottom:14px; font-size:13px; } -.lt-dialog textarea { resize:vertical; } -.lt-form-grid { display:grid; grid-template-columns:1fr 1fr; gap:0 16px; } -#long-task-workspace [hidden], #task-batch-workspace[hidden], #long-task-workspace[hidden] { display:none !important; } -@media(max-width:800px) { .lt-board { grid-template-columns:1fr; }.lt-sidebar { position:static; }#lt-list { max-height:240px; }.lt-detail { padding:14px; }.lt-form-grid { grid-template-columns:1fr; }.lt-step header { flex-wrap:wrap; }.task-mode-tabs { padding-left:12px; } } +/* Native dialogs need explicit centering after the application's global margin reset. */ +.lt-dialog { + position:fixed; + inset:0; + margin:auto; + width:min(540px,calc(100vw - 48px)); + height:fit-content; + max-width:none; + max-height:min(820px,calc(100vh - 48px)); + max-height:min(820px,calc(100dvh - 48px)); + overflow:hidden; + box-sizing:border-box; + padding:0; + border:1px solid var(--border-color,#e2e8f0); + border-radius:16px; + background:var(--bg-primary,#fff); + color:var(--text-primary,#172033); + box-shadow:0 24px 80px rgba(15,23,42,.24); +} +.lt-dialog--wide { width:min(1000px,calc(100vw - 48px)); } +.lt-dialog::backdrop { background:rgba(15,23,42,.42); backdrop-filter:blur(3px); } +.lt-dialog-form { display:flex; flex-direction:column; max-height:inherit; min-height:0; margin:0; } +.lt-dialog-header { display:flex; flex:0 0 auto; align-items:flex-start; justify-content:space-between; gap:20px; padding:24px 28px; border-bottom:1px solid var(--border-color,#e2e8f0); } +.lt-dialog-heading { display:flex; gap:14px; align-items:center; min-width:0; } +.lt-dialog-heading h3 { margin:0; font-size:21px; font-weight:650; line-height:1.4; letter-spacing:-.3px; } +.lt-dialog-heading p { margin:5px 0 0; color:var(--text-secondary,#64748b); font-size:13px; line-height:1.6; } +.lt-dialog-icon { display:grid; place-items:center; flex:0 0 42px; width:42px; height:42px; color:var(--accent-color,#2563eb); background:rgba(37,99,235,.08); border-radius:12px; } +.lt-dialog-icon svg { width:24px; height:24px; } +.lt-dialog-close { display:grid; place-items:center; flex:0 0 32px; width:32px; height:32px; margin:0; padding:0; border:0; border-radius:8px; background:transparent; color:var(--text-secondary,#64748b); cursor:pointer; } +.lt-dialog-close:hover { background:var(--bg-tertiary,#f1f5f9); color:var(--text-primary,#172033); } +.lt-dialog-body { flex:1 1 auto; min-height:0; overflow-y:auto; overscroll-behavior:contain; padding:24px 28px; } +.lt-create-layout { display:grid; grid-template-columns:minmax(0,1fr) 320px; gap:28px; } +.lt-create-main,.lt-create-settings { min-width:0; } +.lt-create-settings { align-self:start; padding:16px; background:var(--bg-secondary,#f8fafc); border:1px solid var(--border-color,#e2e8f0); border-radius:12px; } +.lt-dialog .lt-section-title { margin:0 0 17px; font-size:14px; font-weight:650; line-height:1.5; } +.lt-dialog .lt-form-field { display:flex; flex-direction:column; gap:8px; margin:0 0 17px; min-width:0; } +.lt-dialog .lt-form-field:last-child { margin-bottom:0; } +.lt-field-label { display:flex; gap:5px; align-items:center; font-size:13px; font-weight:550; line-height:1.5; } +.lt-required { color:var(--text-muted,#94a3b8); font-weight:400; } +.lt-dialog input,.lt-dialog select,.lt-dialog textarea { width:100%; min-width:0; box-sizing:border-box; padding:9px 11px; border:1px solid var(--border-color,#dce2eb); border-radius:8px; background:var(--bg-primary,#fff); color:var(--text-primary,#172033); font-family:inherit; font-size:14px; line-height:1.5; outline:none; transition:border-color .15s,box-shadow .15s; } +.lt-dialog input,.lt-dialog select { min-height:40px; } +.lt-dialog textarea { display:block; resize:vertical; min-height:88px; max-height:240px; } +.lt-dialog textarea[name="objective"] { min-height:112px; } +.lt-dialog input::placeholder,.lt-dialog textarea::placeholder { color:var(--text-muted,#94a3b8); font-size:13px; opacity:1; } +.lt-dialog input:focus,.lt-dialog select:focus,.lt-dialog textarea:focus { border-color:var(--accent-color,#2563eb); box-shadow:0 0 0 3px rgba(37,99,235,.1); } +.lt-budget-section { padding-top:18px; margin-top:20px; border-top:1px solid var(--border-color,#e2e8f0); } +.lt-form-grid { display:grid; grid-template-columns:minmax(0,1fr) minmax(0,1fr); gap:14px; } +.lt-form-grid .lt-form-field:last-child { margin-bottom:17px; } +.lt-dialog-footer { flex:0 0 auto; padding:16px 28px; border-top:1px solid var(--border-color,#e2e8f0); background:var(--bg-primary,#fff); } +.lt-dialog-footer-row { display:flex; gap:20px; align-items:center; justify-content:space-between; } +.lt-dialog-note { margin:0; color:var(--text-secondary,#64748b); font-size:12px; line-height:1.6; } +.lt-dialog-buttons { display:flex; flex-shrink:0; gap:10px; align-items:center; } +.lt-dialog .btn-primary,.lt-dialog .btn-secondary { min-height:40px; padding:8px 18px; border-radius:8px; font-size:14px; font-weight:600; line-height:1.5; white-space:nowrap; } +.lt-dialog .btn-primary { background:var(--accent-color,#2563eb); color:var(--bg-primary,#fff); } +.lt-dialog .btn-secondary { color:var(--text-primary,#172033); } +.lt-dialog button:focus-visible { outline:2px solid var(--accent-color,#2563eb); outline-offset:3px; } +.lt-dialog .lt-form-error { margin:0 0 12px; padding:0; color:var(--error-color,#b91c1c); font-size:13px; line-height:1.5; } +.lt-dialog .lt-form-error[hidden] { display:none; } +@media(max-width:760px) { + .lt-dialog,.lt-dialog--wide { width:calc(100vw - 24px); max-height:calc(100vh - 24px); max-height:calc(100dvh - 24px); border-radius:12px; } + .lt-dialog-header { padding:18px 20px; gap:12px; } + .lt-dialog-heading h3 { font-size:19px; } + .lt-dialog-icon { display:none; } + .lt-dialog-close { width:36px; height:36px; flex-basis:36px; } + .lt-dialog-body { padding:20px; } + .lt-create-layout { grid-template-columns:minmax(0,1fr); gap:22px; } + .lt-create-settings { padding:16px; } + .lt-settings-fields { display:grid; grid-template-columns:minmax(0,1fr) minmax(0,1fr); gap:0 14px; } + .lt-dialog-footer { padding:14px 20px; } + .lt-dialog-footer-row { gap:12px; } + .lt-dialog-note { max-width:48%; font-size:11px; } + .lt-dialog .btn-primary,.lt-dialog .btn-secondary { min-height:44px; padding:9px 14px; } +} +@media(max-width:440px) { + .lt-dialog-footer-row { flex-wrap:wrap; gap:10px; } + .lt-dialog-note { max-width:none; width:100%; } + .lt-dialog-buttons { width:100%; } + .lt-dialog-buttons button { flex:1; } +} +#long-task-workspace [hidden], #long-task-workspace[hidden] { display:none !important; } +@media(max-width:800px) { .lt-board { grid-template-columns:1fr; }.lt-sidebar { position:static; }#lt-list { max-height:240px; }.lt-detail { padding:14px; }.lt-step header { flex-wrap:wrap; } } /* The application also styles bare header elements; task rows are not app headers. */ -.lt-detail header,.lt-dialog header { padding:0; min-height:0; height:auto; background:transparent; border:0; box-shadow:none; position:static; flex-shrink:1; } -.task-mode-tabs button[aria-selected="true"] { background:var(--accent-color,#2563eb); color:var(--bg-primary,#fff); } +.lt-detail header { padding:0; min-height:0; height:auto; background:transparent; border:0; box-shadow:none; position:static; flex-shrink:1; } .lt-card.is-selected { border-color:var(--accent-color,#2563eb); box-shadow:inset 3px 0 var(--accent-color,#2563eb); } #page-tasks .btn-secondary:not(:disabled) { color:var(--text-primary,#172033); } #page-tasks .btn-primary { color:var(--bg-primary,#fff); background:var(--accent-color,#2563eb); } -#task-new-goal[hidden],#task-new-batch[hidden] { display:none !important; } +#task-new-goal[hidden] { display:none !important; } .lt-status-cleanup_unconfirmed { background:#fee2e2; color:#b91c1c; } -#page-tasks[data-task-mode="goals"] #task-new-batch, -#page-tasks[data-task-mode="batch"] #task-new-goal { display:none !important; } + +.lt-card-meta { grid-column:1/-1; font-size:12px; color:var(--text-secondary,#64748b); } +.lt-create-settings .lt-form-field { gap:6px; margin-bottom:12px; } +.lt-create-settings .lt-section-title { margin-bottom:14px; } +.lt-settings-fields,.lt-content-pair { display:grid; grid-template-columns:minmax(0,1fr) minmax(0,1fr); gap:0 14px; } +.lt-dialog [hidden] { display:none !important; } +.lt-dialog textarea[name="tasks_text"] { min-height:330px; max-height:500px; } +.lt-input-hint { margin:8px 0 0; color:var(--text-secondary,#64748b); font-size:12px; line-height:1.6; } +.lt-mode-picker { display:grid; grid-template-columns:1fr 1fr; gap:12px; border:0; padding:0; margin:0 0 24px; min-width:0; } +.lt-mode-picker legend { font-size:13px; font-weight:600; margin-bottom:10px; } +.lt-mode-option { display:flex; align-items:flex-start; gap:10px; padding:13px 15px; border:1px solid var(--border-color,#e2e8f0); border-radius:10px; cursor:pointer; min-width:0; } +.lt-mode-option:has(input:checked) { border-color:var(--accent-color,#2563eb); background:rgba(37,99,235,.045); } +.lt-mode-option input { flex:0 0 16px; width:16px; height:16px; min-height:0; margin:3px 0 0; padding:0; accent-color:var(--accent-color,#2563eb); } +.lt-mode-option strong { display:block; font-size:13px; font-weight:600; line-height:1.5; } +.lt-mode-option small { display:block; font-size:12px; color:var(--text-secondary,#64748b); line-height:1.5; margin-top:3px; } +.lt-empty-state { margin:12px 0; padding:64px 24px; text-align:center; border:1px solid var(--border-color,#e2e8f0); border-radius:14px; background:var(--bg-primary,#fff); } +.lt-empty-icon { display:grid; place-items:center; width:52px; height:52px; margin:0 auto 18px; border-radius:14px; background:var(--bg-secondary,#f8fafc); color:var(--accent-color,#2563eb); } +.lt-empty-icon svg { width:28px; height:28px; } +.lt-empty-state h3 { margin:0 0 8px; font-size:18px; font-weight:600; } +.lt-empty-state p { max-width:480px; margin:0 auto 20px; color:var(--text-secondary,#64748b); font-size:14px; line-height:1.7; } +.lt-inline-queue { position:static; width:100%; padding:0; background:none; z-index:auto; } +.lt-inline-queue > .modal-content { width:100%; max-width:none !important; max-height:none; margin:0; padding:0; border:0; box-shadow:none; background:transparent; } +.lt-inline-queue .modal-header { padding:0 0 16px; flex-wrap:wrap; gap:12px; } +.lt-inline-queue .modal-header h2 { font-size:18px; overflow-wrap:anywhere; } +.lt-inline-queue .modal-header-actions { display:flex; flex-wrap:wrap; gap:8px; } +.lt-inline-queue .modal-close { display:none; } +.lt-inline-queue .modal-body { padding:16px 0 0; max-height:none; overflow:visible; } +.lt-inline-queue .batch-queue-tasks-list { max-height:none; } +.lt-status-partial,.lt-status-scheduled { background:#fef3c7; color:#92400e; } +@media(max-width:760px) { + .lt-content-pair { grid-template-columns:1fr; } + .lt-mode-picker { gap:8px; } + .lt-mode-option { padding:10px; gap:7px; } + .lt-mode-option small { font-size:11px; } + .lt-dialog textarea[name="tasks_text"] { min-height:220px; } + .lt-empty-state { padding:42px 18px; } + .lt-inline-queue .modal-header > div { flex-wrap:wrap; } +} + +/* The full option card supplies the touch target; keep its radio visually compact. */ +.lt-dialog .lt-mode-option input[type="radio"] { width:16px !important; height:16px !important; min-width:16px !important; min-height:16px !important; } +@media(max-width:760px) { .lt-dialog-close { width:44px; height:44px; flex-basis:44px; } } +.lt-card { flex-shrink:0; } +.lt-inline-queue .modal-header { background:transparent; box-shadow:none; } +.lt-inline-queue .modal-header h2::before { display:none; } +.lt-inline-queue .batch-queue-detail-hero { padding:0; border:0; background:transparent; min-height:0; } diff --git a/web/static/i18n/en-US.json b/web/static/i18n/en-US.json index 66b1b155..9e39bfe9 100644 --- a/web/static/i18n/en-US.json +++ b/web/static/i18n/en-US.json @@ -5251,11 +5251,11 @@ "invalidNumber": "Enter valid attempt and timing values" }, "longTasks": { - "new": "New goal task", + "new": "New task", "newBatch": "New batch queue", "goals": "Goal tasks", "batch": "Batch queues", - "search": "Search goal tasks", + "search": "Search tasks", "all": "All statuses", "previous": "Previous", "next": "Next", @@ -5291,7 +5291,7 @@ "noPlan": "Start the task to generate its plan.", "noEvents": "No activity yet", "draftHint": "Saved as draft. Start when ready.", - "empty": "No goal tasks. Describe an objective, scope and acceptance criteria, then start when ready.", + "empty": "Describe an objective or provide a checklist. Manage execution and results together here.", "progress": "{{done}} / {{total}} planned steps done · Planning {{rounds}} / {{max}} rounds · About {{minutes}} budget minutes left", "deleteConfirm": "Delete this task and its activity? Execution conversations will be retained.", "cancelConfirm": "Cancel the whole goal task? Saved results will be retained.", @@ -5308,8 +5308,8 @@ "human": "Human approval", "audit": "Audit agent", "concurrency": "Parallel steps", - "rounds": "Maximum planning rounds", - "minutes": "Execution budget (minutes)", + "rounds": "Planning rounds", + "minutes": "Time (minutes)", "status": { "draft": "Draft", "pending": "Pending", @@ -5325,10 +5325,56 @@ "retired": "Superseded", "waiting_input": "Awaiting input", "budget_exhausted": "Budget exhausted", - "cleanup_unconfirmed": "Cleanup unconfirmed" + "cleanup_unconfirmed": "Cleanup unconfirmed", + "partial": "Partial failure", + "scheduled": "Scheduled" }, "answerSaved": "Answer saved; the task has not started:", "extendFirst": "Adjust the execution budget before resuming.", - "roundLimit": "The 200-round limit has been reached. Export the results and create a new goal task." + "roundLimit": "The 200-round limit has been reached. Export the results and create a new goal task.", + "taskContent": "Task details", + "executionSettings": "Execution settings", + "executionBudget": "Execution budget", + "createDescription": "Describe the work and choose how it should run.", + "draftNote": "Save a draft, then start when you are ready.", + "saveDraft": "Save draft", + "cancelEdit": "Cancel", + "budgetHint": "Adjust the time and planning rounds available for further work.", + "budgetNote": "Save the budget, then select Resume to continue.", + "namePlaceholder": "e.g. Review project evidence", + "objectivePlaceholder": "What should be done, and what should be delivered?", + "scopePlaceholder": "Allowed targets or materials, and constraints to follow.", + "criteriaPlaceholder": "What must be verified before this task is complete?", + "emptyTitle": "Create your first task", + "allModes": "All execution methods", + "modeGoal": "Autonomous planning", + "modeList": "Run a checklist", + "executionMode": "Execution method", + "modeGoalHint": "Plan, execute and verify an objective.", + "modeListHint": "Execute supplied items, with optional scheduling.", + "noMatches": "No matching tasks", + "changeFilters": "Try a different search or filter.", + "listProgress": "{{done}} / {{total}} steps", + "scheduledLabel": "Scheduled", + "checklist": "Task checklist", + "checklistPlaceholder": "One task per line, for example:\nRead the supplied local evidence\nCheck report citations\nSummarize remaining work", + "checklistHint": "Each line becomes an independent step, subject to the concurrency setting.", + "agentMode": "Agent mode", + "reviewEdit": "Review and edit", + "executionOptions": "Execution plan", + "schedule": "Start method", + "manualSchedule": "Start manually", + "cronSchedule": "Scheduled (Cron)", + "cron": "Cron expression", + "cronHint": "Use five fields; for example, 0 2 * * * runs daily at 02:00.", + "scheduleNote": "The task will run automatically at the scheduled times.", + "checklistNote": "Saved as pending; start manually when ready.", + "createTask": "Create task", + "noProject": "No project", + "defaultRole": "Default role", + "defaultModel": "Default model", + "untitled": "Untitled task", + "addStep": "Add step", + "rerunAll": "Rerun all" } } diff --git a/web/static/i18n/ru-RU.json b/web/static/i18n/ru-RU.json index 79262a6b..e06e4165 100644 --- a/web/static/i18n/ru-RU.json +++ b/web/static/i18n/ru-RU.json @@ -5264,7 +5264,7 @@ "invalidNumber": "Укажите допустимые значения попыток и интервалов" }, "longTasks": { - "new": "Новая целевая задача", + "new": "Новая задача", "newBatch": "Новая очередь", "goals": "Целевые задачи", "batch": "Очереди задач", @@ -5304,7 +5304,7 @@ "noPlan": "Запустите задачу, чтобы составить план.", "noEvents": "Событий пока нет", "draftHint": "Черновик сохранён. Запустите, когда будете готовы.", - "empty": "Нет целевых задач. Укажите цель, границы и критерии приёмки, затем запустите задачу.", + "empty": "Опишите цель или укажите список работ. Управляйте выполнением и результатами в одном месте.", "progress": "Выполнено {{done}} / {{total}} шагов · Планирование {{rounds}} / {{max}} · Осталось около {{minutes}} мин.", "deleteConfirm": "Удалить задачу и события? Диалоги выполнения сохранятся.", "cancelConfirm": "Отменить всю задачу? Сохранённые результаты останутся.", @@ -5320,9 +5320,9 @@ "hitl": "Подтверждение инструментов", "human": "Подтверждение человеком", "audit": "Агент аудита", - "concurrency": "Параллельных шагов", - "rounds": "Максимум раундов планирования", - "minutes": "Бюджет выполнения (минуты)", + "concurrency": "Параллельные шаги", + "rounds": "Раунды планирования", + "minutes": "Время (минуты)", "status": { "draft": "Черновик", "pending": "Ожидание", @@ -5338,10 +5338,56 @@ "retired": "Заменено", "waiting_input": "Ожидает ответа", "budget_exhausted": "Бюджет исчерпан", - "cleanup_unconfirmed": "Остановка не подтверждена" + "cleanup_unconfirmed": "Остановка не подтверждена", + "partial": "Частичная ошибка", + "scheduled": "Ожидает расписания" }, "answerSaved": "Ответ сохранён; задача не запущена:", "extendFirst": "Измените бюджет перед продолжением.", - "roundLimit": "Достигнут предел в 200 раундов. Экспортируйте результаты и создайте новую задачу." + "roundLimit": "Достигнут предел в 200 раундов. Экспортируйте результаты и создайте новую задачу.", + "taskContent": "Содержание задачи", + "executionSettings": "Настройки выполнения", + "executionBudget": "Бюджет выполнения", + "createDescription": "Опишите работу и выберите способ выполнения.", + "draftNote": "Сохраните черновик и запустите, когда будете готовы.", + "saveDraft": "Сохранить черновик", + "cancelEdit": "Отмена", + "budgetHint": "Измените время и число раундов для дальнейшей работы.", + "budgetNote": "Сохраните бюджет, затем нажмите «Продолжить».", + "namePlaceholder": "Например: обзор материалов проекта", + "objectivePlaceholder": "Какую работу нужно выполнить и какой результат получить?", + "scopePlaceholder": "Разрешённые цели или материалы и ограничения.", + "criteriaPlaceholder": "Что необходимо проверить перед завершением задачи?", + "emptyTitle": "Создайте первую задачу", + "allModes": "Все способы выполнения", + "modeGoal": "Автономное планирование", + "modeList": "Выполнение по списку", + "executionMode": "Способ выполнения", + "modeGoalHint": "Планирование, выполнение и проверка цели.", + "modeListHint": "Выполнение заданных пунктов, в том числе по расписанию.", + "noMatches": "Задачи не найдены", + "changeFilters": "Измените запрос или фильтры.", + "listProgress": "Шаги: {{done}} / {{total}}", + "scheduledLabel": "По расписанию", + "checklist": "Список задач", + "checklistPlaceholder": "Одна задача в строке, например:\nПрочитать локальные материалы\nПроверить ссылки на доказательства\nСоставить список незавершённого", + "checklistHint": "Каждая строка выполняется как отдельный шаг с учётом параллелизма.", + "agentMode": "Режим агента", + "reviewEdit": "Проверить и изменить", + "executionOptions": "Порядок выполнения", + "schedule": "Способ запуска", + "manualSchedule": "Ручной запуск", + "cronSchedule": "По расписанию (Cron)", + "cron": "Выражение Cron", + "cronHint": "Пять полей; например, 0 2 * * * — каждый день в 02:00.", + "scheduleNote": "После создания задача будет запускаться по расписанию.", + "checklistNote": "Сохраняется в ожидании; запустите вручную, когда будете готовы.", + "createTask": "Создать задачу", + "noProject": "Без проекта", + "defaultRole": "Роль по умолчанию", + "defaultModel": "Модель по умолчанию", + "untitled": "Задача без названия", + "addStep": "Добавить шаг", + "rerunAll": "Повторить всё" } } diff --git a/web/static/i18n/zh-CN.json b/web/static/i18n/zh-CN.json index eff7e738..121c94bf 100644 --- a/web/static/i18n/zh-CN.json +++ b/web/static/i18n/zh-CN.json @@ -5239,11 +5239,11 @@ "invalidNumber": "请填写有效的代理次数和时间参数" }, "longTasks": { - "new": "新建目标任务", + "new": "新建任务", "newBatch": "新建批量队列", "goals": "目标任务", "batch": "批量队列", - "search": "搜索目标任务", + "search": "搜索任务", "all": "全部状态", "previous": "上一页", "next": "下一页", @@ -5279,7 +5279,7 @@ "noPlan": "启动后根据目标生成计划。", "noEvents": "暂无动态", "draftHint": "任务已保存,点击开始后执行。", - "empty": "暂无目标任务。描述目标、范围和验收条件,创建后手动启动。", + "empty": "描述目标让系统规划,或提供已有任务清单,在这里统一管理执行与结果。", "progress": "已完成 {{done}} / 当前计划 {{total}} 步 · 规划 {{rounds}} / {{max}} 轮 · 剩余预算约 {{minutes}} 分钟", "deleteConfirm": "删除此任务及动态?关联执行会话仍保留。", "cancelConfirm": "取消整个目标任务?已保存的结果会保留。", @@ -5295,9 +5295,9 @@ "hitl": "工具审批", "human": "人工审批", "audit": "审计智能体", - "concurrency": "并行步骤数", - "rounds": "最多规划轮数", - "minutes": "执行时间预算(分钟)", + "concurrency": "并行步骤", + "rounds": "规划轮数上限", + "minutes": "时间预算(分钟)", "status": { "draft": "草稿", "pending": "待执行", @@ -5313,10 +5313,56 @@ "retired": "已替换方向", "waiting_input": "待答复", "budget_exhausted": "预算耗尽", - "cleanup_unconfirmed": "停止状态待确认" + "cleanup_unconfirmed": "停止状态待确认", + "partial": "部分失败", + "scheduled": "等待定时执行" }, "answerSaved": "答复已保存,任务暂未启动:", "extendFirst": "请先调整执行预算,再继续任务。", - "roundLimit": "已达到 200 轮上限,可导出结果后创建新的目标任务。" + "roundLimit": "已达到 200 轮上限,可导出结果后创建新的目标任务。", + "taskContent": "任务内容", + "executionSettings": "执行设置", + "executionBudget": "执行预算", + "createDescription": "描述要完成的工作,选择适合的执行方式。", + "draftNote": "先保存为草稿,准备好后再开始执行。", + "saveDraft": "保存草稿", + "cancelEdit": "取消", + "budgetHint": "调整后续执行的时间与规划轮数。", + "budgetNote": "保存预算后,点击“继续任务”执行。", + "namePlaceholder": "例如:整理项目测试材料", + "objectivePlaceholder": "希望完成什么工作?需要交付什么结果?", + "scopePlaceholder": "允许处理的目标或材料,以及需要遵守的限制。", + "criteriaPlaceholder": "满足哪些条件,才算这项任务完成?", + "emptyTitle": "创建你的第一个任务", + "allModes": "全部执行方式", + "modeGoal": "自主规划", + "modeList": "按清单执行", + "executionMode": "执行方式", + "modeGoalHint": "给定目标,持续规划、执行并验收。", + "modeListHint": "按已有清单逐项执行,支持定时。", + "noMatches": "没有匹配的任务", + "changeFilters": "试试其他关键字或筛选条件。", + "listProgress": "{{done}} / {{total}} 步", + "scheduledLabel": "定时", + "checklist": "任务清单", + "checklistPlaceholder": "每行一项工作,例如:\n读取指定的本地测试材料\n核对报告中的证据引用\n汇总尚未完成的项目", + "checklistHint": "每行会作为独立子任务执行,按并发数推进。", + "agentMode": "执行模式", + "reviewEdit": "审查并编辑", + "executionOptions": "执行安排", + "schedule": "启动方式", + "manualSchedule": "手动启动", + "cronSchedule": "定时执行(Cron)", + "cron": "Cron 表达式", + "cronHint": "使用 5 段表达式,例如 0 2 * * * 表示每天 02:00。", + "scheduleNote": "创建后将按设定时间自动执行。", + "checklistNote": "创建后保持待执行,准备好后手动开始。", + "createTask": "创建任务", + "noProject": "不关联项目", + "defaultRole": "默认角色", + "defaultModel": "默认模型", + "untitled": "未命名任务", + "addStep": "添加子任务", + "rerunAll": "重跑全部" } } diff --git a/web/static/js/long-tasks.js b/web/static/js/long-tasks.js index 416769fc..c9804d48 100644 --- a/web/static/js/long-tasks.js +++ b/web/static/js/long-tasks.js @@ -1,7 +1,7 @@ /* Durable objectives in the existing task-management page. */ (function () { 'use strict'; - const state = { active: false, tab: 'goals', tasks: [], selected: null, task: null, events: [], cursor: 0, offset: 0, more: false, epoch: 0, loading: false, timer: null, options: null, controller: null, optionsRequest: null, viewVersion: 0, searchTimer: null, mutating: new Set(), errorKind: null }; + const state = { active: false, tasks: [], selected: null, selectedMode: 'goal', task: null, events: [], cursor: 0, offset: 0, more: false, epoch: 0, loading: false, timer: null, options: null, controller: null, optionsRequest: null, viewVersion: 0, searchTimer: null, mutating: new Set(), errorKind: null }; const el = id => document.getElementById(id); const tr = (key, args) => typeof window.t === 'function' ? window.t('longTasks.' + key, args) : key; const esc = value => String(value == null ? '' : value).replace(/[&<>"']/g, c => ({ '&': '&', '<': '<', '>': '>', '"': '"', "'": ''' }[c])); @@ -11,32 +11,38 @@ const button = (action, label, extra = '', disabled = false) => ``; function writable(permission = 'tasks:write') { return typeof window.hasPermission !== 'function' || window.hasPermission(permission); } function canExecute() { return writable() && ['agent:execute', 'chat:read', 'chat:write'].every(permission => writable(permission)); } - function current(task) { return state.active && state.selected === task.id; } + function current(task) { return state.active && state.selectedMode === 'goal' && state.selected === task.id; } async function api(path, options = {}) { - const response = await window.apiFetch('/api/long-tasks' + path, { ...options, headers: { 'Content-Type': 'application/json', ...options.headers } }); + const response = await window.apiFetch(path.startsWith('/api/') ? path : '/api/long-tasks' + path, { ...options, headers: { 'Content-Type': 'application/json', ...options.headers } }); if (!response.ok) { const body = await response.json().catch(() => ({})); throw new Error(body.error || String(response.status)); } return response.json(); } function error(message, kind = 'action') { state.errorKind = message ? kind : null; const box = el('lt-error'); if (box) { box.textContent = message || ''; box.hidden = !message; } } - function switchTab(tab) { - state.viewVersion++; cancelOptions(); - state.tab = tab; - el('long-task-workspace').hidden = tab !== 'goals'; - el('task-batch-workspace').hidden = tab !== 'batch'; - // Page mode and RBAC own separate visibility rules. Permission refreshes - // must not reveal the other mode's button, or tab switches reveal denied controls. - el('page-tasks').dataset.taskMode = tab; - document.querySelectorAll('[data-task-tab]').forEach(b => b.setAttribute('aria-selected', String(b.dataset.taskTab === tab))); - if (tab === 'goals') refresh(); - } function renderList() { - el('lt-list').innerHTML = state.tasks.length ? state.tasks.map(t => ``).join('') : `
${esc(tr('createHint'))}
${field('name', '')}${field('objective', '')}${field('scope', '')}${field('criteria', '')}${esc(tr('checklistHint'))}
+