mirror of
https://github.com/YspCoder/clawgo.git
synced 2026-04-14 11:17:28 +08:00
tasks.json structured CRUD: add /webui/api/tasks and task editor controls in audit page
This commit is contained in:
@@ -15,6 +15,7 @@ import (
|
||||
"path/filepath"
|
||||
"regexp"
|
||||
"runtime/debug"
|
||||
"sort"
|
||||
"strconv"
|
||||
"strings"
|
||||
"syscall"
|
||||
@@ -90,6 +91,7 @@ func (s *RegistryServer) Start(ctx context.Context) error {
|
||||
mux.HandleFunc("/webui/api/memory", s.handleWebUIMemory)
|
||||
mux.HandleFunc("/webui/api/task_audit", s.handleWebUITaskAudit)
|
||||
mux.HandleFunc("/webui/api/task_queue", s.handleWebUITaskQueue)
|
||||
mux.HandleFunc("/webui/api/tasks", s.handleWebUITasks)
|
||||
mux.HandleFunc("/webui/api/exec_approvals", s.handleWebUIExecApprovals)
|
||||
mux.HandleFunc("/webui/api/logs/stream", s.handleWebUILogsStream)
|
||||
mux.HandleFunc("/webui/api/logs/recent", s.handleWebUILogsRecent)
|
||||
@@ -1557,6 +1559,111 @@ func (s *RegistryServer) handleWebUITaskQueue(w http.ResponseWriter, r *http.Req
|
||||
_ = json.NewEncoder(w).Encode(map[string]interface{}{"ok": true, "running": running, "items": items, "stats": stats})
|
||||
}
|
||||
|
||||
func (s *RegistryServer) handleWebUITasks(w http.ResponseWriter, r *http.Request) {
|
||||
if !s.checkAuth(r) {
|
||||
http.Error(w, "unauthorized", http.StatusUnauthorized)
|
||||
return
|
||||
}
|
||||
tasksPath := filepath.Join(strings.TrimSpace(s.workspacePath), "memory", "tasks.json")
|
||||
if r.Method == http.MethodGet {
|
||||
b, err := os.ReadFile(tasksPath)
|
||||
if err != nil {
|
||||
_ = json.NewEncoder(w).Encode(map[string]interface{}{"ok": true, "items": []map[string]interface{}{}})
|
||||
return
|
||||
}
|
||||
var items []map[string]interface{}
|
||||
if err := json.Unmarshal(b, &items); err != nil {
|
||||
http.Error(w, "invalid tasks file", http.StatusInternalServerError)
|
||||
return
|
||||
}
|
||||
sort.Slice(items, func(i, j int) bool { return fmt.Sprintf("%v", items[i]["updated_at"]) > fmt.Sprintf("%v", items[j]["updated_at"]) })
|
||||
_ = json.NewEncoder(w).Encode(map[string]interface{}{"ok": true, "items": items})
|
||||
return
|
||||
}
|
||||
if r.Method != http.MethodPost {
|
||||
http.Error(w, "method not allowed", http.StatusMethodNotAllowed)
|
||||
return
|
||||
}
|
||||
var body map[string]interface{}
|
||||
if err := json.NewDecoder(r.Body).Decode(&body); err != nil {
|
||||
http.Error(w, "invalid json", http.StatusBadRequest)
|
||||
return
|
||||
}
|
||||
action := fmt.Sprintf("%v", body["action"])
|
||||
now := time.Now().UTC().Format(time.RFC3339)
|
||||
items := []map[string]interface{}{}
|
||||
if b, err := os.ReadFile(tasksPath); err == nil {
|
||||
_ = json.Unmarshal(b, &items)
|
||||
}
|
||||
switch action {
|
||||
case "create":
|
||||
it, _ := body["item"].(map[string]interface{})
|
||||
if it == nil {
|
||||
http.Error(w, "item required", http.StatusBadRequest)
|
||||
return
|
||||
}
|
||||
id := fmt.Sprintf("%v", it["id"])
|
||||
if id == "" {
|
||||
id = fmt.Sprintf("task_%d", time.Now().UnixNano())
|
||||
}
|
||||
it["id"] = id
|
||||
if fmt.Sprintf("%v", it["status"]) == "" {
|
||||
it["status"] = "todo"
|
||||
}
|
||||
if fmt.Sprintf("%v", it["source"]) == "" {
|
||||
it["source"] = "manual"
|
||||
}
|
||||
it["updated_at"] = now
|
||||
items = append(items, it)
|
||||
case "update":
|
||||
id := fmt.Sprintf("%v", body["id"])
|
||||
it, _ := body["item"].(map[string]interface{})
|
||||
if id == "" || it == nil {
|
||||
http.Error(w, "id and item required", http.StatusBadRequest)
|
||||
return
|
||||
}
|
||||
updated := false
|
||||
for _, row := range items {
|
||||
if fmt.Sprintf("%v", row["id"]) == id {
|
||||
for k, v := range it {
|
||||
row[k] = v
|
||||
}
|
||||
row["id"] = id
|
||||
row["updated_at"] = now
|
||||
updated = true
|
||||
break
|
||||
}
|
||||
}
|
||||
if !updated {
|
||||
http.Error(w, "task not found", http.StatusNotFound)
|
||||
return
|
||||
}
|
||||
case "delete":
|
||||
id := fmt.Sprintf("%v", body["id"])
|
||||
if id == "" {
|
||||
http.Error(w, "id required", http.StatusBadRequest)
|
||||
return
|
||||
}
|
||||
filtered := make([]map[string]interface{}, 0, len(items))
|
||||
for _, row := range items {
|
||||
if fmt.Sprintf("%v", row["id"]) != id {
|
||||
filtered = append(filtered, row)
|
||||
}
|
||||
}
|
||||
items = filtered
|
||||
default:
|
||||
http.Error(w, "unsupported action", http.StatusBadRequest)
|
||||
return
|
||||
}
|
||||
_ = os.MkdirAll(filepath.Dir(tasksPath), 0755)
|
||||
out, _ := json.MarshalIndent(items, "", " ")
|
||||
if err := os.WriteFile(tasksPath, out, 0644); err != nil {
|
||||
http.Error(w, err.Error(), http.StatusInternalServerError)
|
||||
return
|
||||
}
|
||||
_ = json.NewEncoder(w).Encode(map[string]interface{}{"ok": true})
|
||||
}
|
||||
|
||||
func (s *RegistryServer) handleWebUIExecApprovals(w http.ResponseWriter, r *http.Request) {
|
||||
if !s.checkAuth(r) {
|
||||
http.Error(w, "unauthorized", http.StatusUnauthorized)
|
||||
|
||||
@@ -27,6 +27,10 @@ const resources = {
|
||||
retryTask: 'Retry',
|
||||
completeTask: 'Complete',
|
||||
ignoreTask: 'Ignore',
|
||||
taskCrud: 'Task CRUD',
|
||||
createTask: 'Create',
|
||||
updateTask: 'Update',
|
||||
deleteTask: 'Delete',
|
||||
error: 'Error',
|
||||
noTaskAudit: 'No task audit records',
|
||||
selectTask: 'Select a task from the left list',
|
||||
@@ -188,6 +192,10 @@ const resources = {
|
||||
retryTask: '重试',
|
||||
completeTask: '完成',
|
||||
ignoreTask: '忽略',
|
||||
taskCrud: '任务 CRUD',
|
||||
createTask: '新建',
|
||||
updateTask: '更新',
|
||||
deleteTask: '删除',
|
||||
error: '错误',
|
||||
noTaskAudit: '暂无任务审计记录',
|
||||
selectTask: '请从左侧选择任务',
|
||||
|
||||
@@ -32,6 +32,7 @@ const TaskAudit: React.FC = () => {
|
||||
const [loading, setLoading] = useState(false);
|
||||
const [sourceFilter, setSourceFilter] = useState('all');
|
||||
const [statusFilter, setStatusFilter] = useState('all');
|
||||
const [draft, setDraft] = useState<any>({ id: '', content: '', priority: 'normal', status: 'todo', source: 'manual', due_at: '' });
|
||||
|
||||
const fetchData = async () => {
|
||||
setLoading(true);
|
||||
@@ -73,6 +74,21 @@ const TaskAudit: React.FC = () => {
|
||||
console.error(e);
|
||||
}
|
||||
};
|
||||
|
||||
const saveTask = async (action: 'create'|'update'|'delete') => {
|
||||
try {
|
||||
const url = `/webui/api/tasks${q}`;
|
||||
const payload: any = { action };
|
||||
if (action === 'create') payload.item = draft;
|
||||
if (action === 'update') { payload.id = draft.id; payload.item = draft; }
|
||||
if (action === 'delete') payload.id = draft.id;
|
||||
const r = await fetch(url, { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify(payload) });
|
||||
if (!r.ok) throw new Error(await r.text());
|
||||
await fetchData();
|
||||
} catch (e) {
|
||||
console.error(e);
|
||||
}
|
||||
};
|
||||
const selectedPretty = useMemo(() => selected ? JSON.stringify(selected, null, 2) : '', [selected]);
|
||||
|
||||
return (
|
||||
@@ -111,7 +127,7 @@ const TaskAudit: React.FC = () => {
|
||||
return (
|
||||
<button
|
||||
key={`${it.task_id || idx}-${it.time || idx}`}
|
||||
onClick={() => setSelected(it)}
|
||||
onClick={() => { setSelected(it); setDraft({ id: it.task_id || it.id || '', content: it.input_preview || it.content || '', priority: it.priority || 'normal', status: it.status || 'todo', source: it.source || 'manual', due_at: it.due_at || '' }); }}
|
||||
className={`w-full text-left px-3 py-2 border-b border-zinc-800/60 hover:bg-zinc-800/40 ${active ? 'bg-indigo-500/15' : ''}`}
|
||||
>
|
||||
<div className="text-sm font-medium text-zinc-100 truncate">{it.task_id || `task-${idx + 1}`}</div>
|
||||
@@ -134,6 +150,21 @@ const TaskAudit: React.FC = () => {
|
||||
<button onClick={()=>taskAction('ignore')} className="px-2 py-1 text-xs rounded bg-zinc-700 hover:bg-zinc-600">{t('ignoreTask')}</button>
|
||||
</div>
|
||||
)}
|
||||
<div className="p-3 border border-zinc-800 rounded-lg bg-zinc-950/40 space-y-2">
|
||||
<div className="text-xs text-zinc-400 uppercase tracking-wider">{t('taskCrud')}</div>
|
||||
<input value={draft.id} onChange={(e)=>setDraft({ ...draft, id: e.target.value })} placeholder="id" className="w-full px-2 py-1 text-xs bg-zinc-900 border border-zinc-700 rounded" />
|
||||
<textarea value={draft.content} onChange={(e)=>setDraft({ ...draft, content: e.target.value })} placeholder="content" className="w-full px-2 py-1 text-xs bg-zinc-900 border border-zinc-700 rounded min-h-[70px]" />
|
||||
<div className="grid grid-cols-3 gap-2">
|
||||
<input value={draft.priority} onChange={(e)=>setDraft({ ...draft, priority: e.target.value })} placeholder="priority" className="px-2 py-1 text-xs bg-zinc-900 border border-zinc-700 rounded" />
|
||||
<input value={draft.status} onChange={(e)=>setDraft({ ...draft, status: e.target.value })} placeholder="status" className="px-2 py-1 text-xs bg-zinc-900 border border-zinc-700 rounded" />
|
||||
<input value={draft.source} onChange={(e)=>setDraft({ ...draft, source: e.target.value })} placeholder="source" className="px-2 py-1 text-xs bg-zinc-900 border border-zinc-700 rounded" />
|
||||
</div>
|
||||
<div className="flex items-center gap-2 flex-wrap">
|
||||
<button onClick={()=>saveTask('create')} className="px-2 py-1 text-xs rounded bg-emerald-700/70 hover:bg-emerald-600">{t('createTask')}</button>
|
||||
<button onClick={()=>saveTask('update')} className="px-2 py-1 text-xs rounded bg-indigo-700/70 hover:bg-indigo-600">{t('updateTask')}</button>
|
||||
<button onClick={()=>saveTask('delete')} className="px-2 py-1 text-xs rounded bg-red-700/70 hover:bg-red-600">{t('deleteTask')}</button>
|
||||
</div>
|
||||
</div>
|
||||
{!selected ? (
|
||||
<div className="text-zinc-500">{t('selectTask')}</div>
|
||||
) : (
|
||||
|
||||
Reference in New Issue
Block a user