TaskActions.vala 23 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547
  1. using Inversion;
  2. using Spry;
  3. using Spry.Authentication;
  4. using Statum;
  5. using ClankerSaddle.Services;
  6. namespace ClankerSaddle {
  7. /** Sealed task id carried by the task row actions. */
  8. public class TaskActionPrivate : Object {
  9. public int64 task_id { get; set; }
  10. }
  11. /** Sealed block identity carried by {@link AnswerBlockAction}. */
  12. public class BlockAnswerPrivate : Object {
  13. public int64 task_id { get; set; }
  14. public int64 block_id { get; set; }
  15. }
  16. /**
  17. * Common base for actions sealed against a task id: materialises the
  18. * typed private blob and exposes the resolved id (falling back to the
  19. * hidden `task_id` form field).
  20. */
  21. public abstract class SealedTaskAction : TypedStatumAction<TaskActionPrivate> {
  22. protected override Type private_type { get { return typeof(TaskActionPrivate); } }
  23. /** The sealed task id, or 0 when neither blob nor form field carried one. */
  24. protected int64 sealed_task_id() {
  25. var ctx = request_private;
  26. return ctx != null ? ((!)ctx).task_id : Forms.integer(request, "task_id", 0);
  27. }
  28. }
  29. /**
  30. * Creates a task from the queue form (project and title required).
  31. * Priority clamps to 1–9; the design-task checkbox and the optional
  32. * parent id support design tasks and manual subtasks. Branch fields
  33. * are optional — `branch_from` prefills from the project's default
  34. * branch and `task_branch` is inherited from the parent task when
  35. * left blank.
  36. */
  37. public class CreateTaskAction : StatumAction {
  38. private TaskService tasks = inject<TaskService>();
  39. private CapabilityService capabilities = inject<CapabilityService>();
  40. private UserService users = inject<UserService>();
  41. public override async DirectiveBuilder handle() throws GLib.Error {
  42. var guard = yield SpryAuth.require_login(directives(), request, users);
  43. if (guard != null) {
  44. return (!)guard;
  45. }
  46. int64 project_id = Forms.integer(request, "project_id", 0);
  47. string title = Forms.field(request, "title");
  48. if (project_id <= 0 || title.length == 0) {
  49. return directives().notify("error", "Project and title are required").navigate("/tasks");
  50. }
  51. int64? parent_id = null;
  52. int64 parsed_parent = Forms.integer(request, "parent_task_id", 0);
  53. if (parsed_parent > 0) {
  54. parent_id = parsed_parent;
  55. }
  56. // Required capabilities: the create form's multi-select posts
  57. // several capability_id fields; every id must resolve before
  58. // the task is created. (A plain array — the Invercargill
  59. // collections mishandle boxed value types in foreach.)
  60. int64[] required = {};
  61. if (request.form != null) {
  62. foreach (var value in request.form.get_field_all("capability_id")) {
  63. int64 parsed = int64.parse(value.strip());
  64. if (parsed <= 0) {
  65. continue;
  66. }
  67. var capability = yield capabilities.get_capability(parsed);
  68. if (capability == null) {
  69. return directives().notify("error",
  70. @"No capability exists with id $(parsed)").navigate("/tasks");
  71. }
  72. required += parsed;
  73. }
  74. }
  75. try {
  76. var task = yield tasks.create_task(project_id, title,
  77. Forms.field_raw(request, "description"),
  78. Forms.integer(request, "priority", 5),
  79. Forms.field(request, "is_design_task") == "on", parent_id,
  80. Forms.optional(request, "task_branch"),
  81. Forms.optional(request, "branch_from"));
  82. if (Forms.field(request, "plan").length > 0) {
  83. yield tasks.update_plan(task.id, Forms.field_raw(request, "plan"));
  84. }
  85. foreach (int64 capability_id in required) {
  86. yield capabilities.attach_to_task(capability_id, task.id);
  87. }
  88. return directives().notify("success", @"Task '$(task.title)' queued")
  89. .navigate(@"/tasks/$(task.id)");
  90. } catch (Error e) {
  91. return directives().notify("error", @"Could not create the task: $(e.message)").navigate("/tasks");
  92. }
  93. }
  94. }
  95. /**
  96. * Saves the editable fields of a task; the id comes from the sealed
  97. * {@link TaskActionPrivate} blob (the hidden form field is a
  98. * fallback).
  99. */
  100. public class UpdateTaskAction : SealedTaskAction {
  101. private TaskService tasks = inject<TaskService>();
  102. private UserService users = inject<UserService>();
  103. public override async DirectiveBuilder handle() throws GLib.Error {
  104. var guard = yield SpryAuth.require_login(directives(), request, users);
  105. if (guard != null) {
  106. return (!)guard;
  107. }
  108. int64 task_id = sealed_task_id();
  109. if (task_id <= 0) {
  110. return directives().navigate("/tasks");
  111. }
  112. try {
  113. int64? priority = null;
  114. if (Forms.field(request, "priority").length > 0) {
  115. priority = Forms.integer(request, "priority", 5);
  116. }
  117. yield tasks.update_task(task_id,
  118. Forms.optional(request, "title"),
  119. request.form != null ? Forms.field(request, "description") : null,
  120. priority,
  121. Forms.optional(request, "status"));
  122. yield tasks.set_branch_fields(task_id,
  123. Forms.optional(request, "task_branch"),
  124. Forms.optional(request, "branch_from"));
  125. return directives().notify("success", "Task saved").navigate(@"/tasks/$(task_id)");
  126. } catch (Error e) {
  127. return directives().notify("error", @"Could not save the task: $(e.message)")
  128. .navigate(@"/tasks/$(task_id)");
  129. }
  130. }
  131. }
  132. /**
  133. * Appends a comment to a task as the signed-in user. An optional
  134. * `quote` field carries text the user highlighted in the terminal log
  135. * or an RFC body; the quote is stored with the comment and delivered
  136. * to the saddle as a quote block.
  137. */
  138. public class AddCommentAction : SealedTaskAction {
  139. private TaskService tasks = inject<TaskService>();
  140. private UserService users = inject<UserService>();
  141. public override async DirectiveBuilder handle() throws GLib.Error {
  142. var guard = yield SpryAuth.require_login(directives(), request, users);
  143. if (guard != null) {
  144. return (!)guard;
  145. }
  146. int64 task_id = sealed_task_id();
  147. string body = Forms.field_raw(request, "body");
  148. string quote = Forms.field_raw(request, "quote");
  149. if (task_id <= 0 || body.length == 0) {
  150. return directives().notify("error", "A comment body is required").navigate(@"/tasks/$(task_id)");
  151. }
  152. var me = SpryAuth.current(request);
  153. try {
  154. yield tasks.add_comment(task_id, @"user:$(me.username)", body, quote);
  155. yield tasks.log_session_entry(task_id, "user-comment",
  156. @"comment by user:$(me.username)", quote.length > 0 ? "> " + quote.replace("\n", "\n> ") + "\n\n" + body : body);
  157. // Terminals post with a return_to so the live view survives
  158. // the comment; every other caller lands on the task page.
  159. string return_to = Forms.field(request, "return_to");
  160. string destination = return_to.length > 0 && return_to.has_prefix("/")
  161. ? return_to : @"/tasks/$(task_id)";
  162. return directives().notify("success", "Comment added").navigate(destination);
  163. } catch (Error e) {
  164. return directives().notify("error", @"Could not add the comment: $(e.message)")
  165. .navigate(@"/tasks/$(task_id)");
  166. }
  167. }
  168. }
  169. /**
  170. * Saves the task's markdown plan from the web UI's plan editor (the
  171. * human counterpart of the agent's `saddle plan`).
  172. */
  173. public class UpdatePlanAction : SealedTaskAction {
  174. private TaskService tasks = inject<TaskService>();
  175. private UserService users = inject<UserService>();
  176. public override async DirectiveBuilder handle() throws GLib.Error {
  177. var guard = yield SpryAuth.require_login(directives(), request, users);
  178. if (guard != null) {
  179. return (!)guard;
  180. }
  181. int64 task_id = sealed_task_id();
  182. if (task_id <= 0) {
  183. return directives().navigate("/tasks");
  184. }
  185. try {
  186. yield tasks.update_plan(task_id, Forms.field_raw(request, "plan"));
  187. return directives().notify("success", "Plan saved").navigate(@"/tasks/$(task_id)");
  188. } catch (Error e) {
  189. return directives().notify("error", @"Could not save the plan: $(e.message)")
  190. .navigate(@"/tasks/$(task_id)");
  191. }
  192. }
  193. }
  194. /**
  195. * Records the human's answer to a block; the task and block ids come
  196. * from the sealed {@link BlockAnswerPrivate} blob. Question blocks
  197. * submit either a chosen `option` or the free-text `other` field.
  198. * Answers are stored verbatim — the saddle daemon applies its own
  199. * "Human selected: …" formatting, so a stored prefix would wrap the
  200. * answer a second time.
  201. */
  202. public class AnswerBlockAction : TypedStatumAction<BlockAnswerPrivate> {
  203. private TaskService tasks = inject<TaskService>();
  204. private UserService users = inject<UserService>();
  205. protected override Type private_type { get { return typeof(BlockAnswerPrivate); } }
  206. public override async DirectiveBuilder handle() throws GLib.Error {
  207. var guard = yield SpryAuth.require_login(directives(), request, users);
  208. if (guard != null) {
  209. return (!)guard;
  210. }
  211. var ctx = request_private;
  212. if (ctx == null) {
  213. return directives().navigate("/tasks");
  214. }
  215. int64 task_id = ((!)ctx).task_id;
  216. string option = Forms.field(request, "option");
  217. string other = Forms.field_raw(request, "other");
  218. string answer = Forms.field_raw(request, "answer");
  219. if (option == "__other__") {
  220. answer = other.strip().length > 0 ? other.strip() : answer;
  221. } else if (option.length > 0) {
  222. answer = option;
  223. }
  224. if (answer.length == 0) {
  225. return directives().notify("error", "An answer is required").navigate(@"/tasks/$(task_id)");
  226. }
  227. try {
  228. yield tasks.answer_block(((!)ctx).block_id, answer);
  229. return directives().notify("success", "Answer recorded; the saddle will collect it")
  230. .navigate(@"/tasks/$(task_id)");
  231. } catch (Error e) {
  232. return directives().notify("error", @"Could not answer the block: $(e.message)")
  233. .navigate(@"/tasks/$(task_id)");
  234. }
  235. }
  236. }
  237. /** Creates a child task under the sealed parent task id. */
  238. public class CreateSubtaskAction : SealedTaskAction {
  239. private TaskService tasks = inject<TaskService>();
  240. private UserService users = inject<UserService>();
  241. public override async DirectiveBuilder handle() throws GLib.Error {
  242. var guard = yield SpryAuth.require_login(directives(), request, users);
  243. if (guard != null) {
  244. return (!)guard;
  245. }
  246. int64 task_id = sealed_task_id();
  247. string title = Forms.field(request, "title");
  248. if (task_id <= 0 || title.length == 0) {
  249. return directives().notify("error", "A subtask title is required").navigate(@"/tasks/$(task_id)");
  250. }
  251. try {
  252. yield tasks.create_subtask(task_id, title, Forms.field_raw(request, "description"));
  253. return directives().notify("success", "Subtask created").navigate(@"/tasks/$(task_id)");
  254. } catch (Error e) {
  255. return directives().notify("error", @"Could not create the subtask: $(e.message)")
  256. .navigate(@"/tasks/$(task_id)");
  257. }
  258. }
  259. }
  260. /** Adds a dependency edge from the sealed task to the form's target. */
  261. public class AddDependencyAction : SealedTaskAction {
  262. private TaskService tasks = inject<TaskService>();
  263. private UserService users = inject<UserService>();
  264. public override async DirectiveBuilder handle() throws GLib.Error {
  265. var guard = yield SpryAuth.require_login(directives(), request, users);
  266. if (guard != null) {
  267. return (!)guard;
  268. }
  269. int64 task_id = sealed_task_id();
  270. int64 depends_on = Forms.integer(request, "depends_on_task_id", 0);
  271. if (task_id <= 0 || depends_on <= 0) {
  272. return directives().notify("error", "Pick a task to depend on").navigate(@"/tasks/$(task_id)");
  273. }
  274. try {
  275. yield tasks.add_dependency(task_id, depends_on);
  276. return directives().notify("success", "Dependency added").navigate(@"/tasks/$(task_id)");
  277. } catch (Error e) {
  278. return directives().notify("error", @"Could not add the dependency: $(e.message)")
  279. .navigate(@"/tasks/$(task_id)");
  280. }
  281. }
  282. }
  283. /**
  284. * Completes a task (summary and working branch from the form); closes
  285. * the open session and frees the saddle running it.
  286. */
  287. public class CompleteTaskAction : SealedTaskAction {
  288. private TaskService tasks = inject<TaskService>();
  289. private UserService users = inject<UserService>();
  290. public override async DirectiveBuilder handle() throws GLib.Error {
  291. var guard = yield SpryAuth.require_login(directives(), request, users);
  292. if (guard != null) {
  293. return (!)guard;
  294. }
  295. int64 task_id = sealed_task_id();
  296. if (task_id <= 0) {
  297. return directives().navigate("/tasks");
  298. }
  299. try {
  300. yield tasks.complete_task(task_id, Forms.optional(request, "summary"),
  301. Forms.optional(request, "working_branch"), "done");
  302. return directives().notify("success", "Task completed").navigate(@"/tasks/$(task_id)");
  303. } catch (Error e) {
  304. return directives().notify("error", @"Could not complete the task: $(e.message)")
  305. .navigate(@"/tasks/$(task_id)");
  306. }
  307. }
  308. }
  309. /**
  310. * Cancels a task (status 'failed'); the sealed id comes from the task
  311. * page's cancel button.
  312. */
  313. public class CancelTaskAction : SealedTaskAction {
  314. private TaskService tasks = inject<TaskService>();
  315. private SaddleService saddles = inject<SaddleService>();
  316. private UserService users = inject<UserService>();
  317. public override async DirectiveBuilder handle() throws GLib.Error {
  318. var guard = yield SpryAuth.require_login(directives(), request, users);
  319. if (guard != null) {
  320. return (!)guard;
  321. }
  322. int64 task_id = sealed_task_id();
  323. if (task_id <= 0) {
  324. return directives().navigate("/tasks");
  325. }
  326. try {
  327. yield saddles.abort_live_session(tasks, task_id, "cancelled");
  328. yield tasks.cancel_task(task_id);
  329. return directives().notify("success", "Task cancelled").navigate(@"/tasks/$(task_id)");
  330. } catch (Error e) {
  331. return directives().notify("error", @"Could not cancel the task: $(e.message)")
  332. .navigate(@"/tasks/$(task_id)");
  333. }
  334. }
  335. }
  336. /**
  337. * Retries a failed task: the requeue path with the failure summary
  338. * moved into a comment (and cleared), all history kept. The next
  339. * dispatch resumes the daemon-side workspace when it still exists.
  340. */
  341. public class RetryTaskAction : SealedTaskAction {
  342. private TaskService tasks = inject<TaskService>();
  343. private SaddleService saddles = inject<SaddleService>();
  344. private UserService users = inject<UserService>();
  345. public override async DirectiveBuilder handle() throws GLib.Error {
  346. var guard = yield SpryAuth.require_login(directives(), request, users);
  347. if (guard != null) {
  348. return (!)guard;
  349. }
  350. int64 task_id = sealed_task_id();
  351. if (task_id <= 0) {
  352. return directives().navigate("/tasks");
  353. }
  354. var detail = yield tasks.get_task(task_id);
  355. if (detail == null) {
  356. return directives().navigate("/tasks");
  357. }
  358. if (((!)detail).task.status != STATUS_FAILED) {
  359. return directives().notify("error", "Only failed tasks can be retried")
  360. .navigate(@"/tasks/$(task_id)");
  361. }
  362. try {
  363. yield saddles.abort_live_session(tasks, task_id, "retried");
  364. yield tasks.retry_task(task_id);
  365. return directives().notify("success", "Task requeued for another attempt")
  366. .navigate(@"/tasks/$(task_id)");
  367. } catch (Error e) {
  368. return directives().notify("error", @"Could not retry the task: $(e.message)")
  369. .navigate(@"/tasks/$(task_id)");
  370. }
  371. }
  372. }
  373. /**
  374. * Manually requeues a task stuck working/blocked on a saddle that
  375. * went offline (the automatic three-strike path may never fire when
  376. * the saddle row was refreshed to offline first). The same path as
  377. * the dispatcher's abandon: requeue + bot comment + saddle offline.
  378. */
  379. public class ResumeTaskAction : SealedTaskAction {
  380. private TaskService task_service = inject<TaskService>();
  381. private SaddleService saddle_service = inject<SaddleService>();
  382. private UserService users = inject<UserService>();
  383. public override async DirectiveBuilder handle() throws GLib.Error {
  384. var guard = yield SpryAuth.require_login(directives(), request, users);
  385. if (guard != null) {
  386. return (!)guard;
  387. }
  388. int64 task_id = sealed_task_id();
  389. if (task_id <= 0) {
  390. return directives().navigate("/tasks");
  391. }
  392. try {
  393. var session = yield task_service.open_session_for_task(task_id);
  394. if (session != null) {
  395. yield saddle_service.abort_live_session(task_service, task_id, "stopped");
  396. yield saddle_service.mark_saddle_unreachable(((!)session).saddle_id, task_service);
  397. } else {
  398. yield task_service.requeue_task(task_id);
  399. }
  400. return directives().notify("success",
  401. "Task requeued; the daemon restores its context on the next dispatch")
  402. .navigate(@"/tasks/$(task_id)");
  403. } catch (Error e) {
  404. return directives().notify("error", @"Could not requeue the task: $(e.message)")
  405. .navigate(@"/tasks/$(task_id)");
  406. }
  407. }
  408. }
  409. /**
  410. * Flips a task's subtask auto-approve toggle: when on, review blocks
  411. * raised by this task's descendants are answered automatically —
  412. * the task's own review stays a human gate.
  413. */
  414. public class ToggleAutoApproveAction : SealedTaskAction {
  415. private TaskService task_service = inject<TaskService>();
  416. private UserService users = inject<UserService>();
  417. public override async DirectiveBuilder handle() throws GLib.Error {
  418. var guard = yield SpryAuth.require_login(directives(), request, users);
  419. if (guard != null) {
  420. return (!)guard;
  421. }
  422. int64 task_id = sealed_task_id();
  423. if (task_id <= 0) {
  424. return directives().navigate("/tasks");
  425. }
  426. try {
  427. var task = yield task_service.update_task(task_id, null, null, null, null);
  428. if (task == null) {
  429. return directives().navigate("/tasks");
  430. }
  431. ((!)task).auto_approve = ((!)task).auto_approve != 0 ? 0 : 1;
  432. yield task_service.save_auto_approve(((!)task).id, ((!)task).auto_approve != 0);
  433. string state = ((!)task).auto_approve != 0 ? "on" : "off";
  434. return directives().notify("success",
  435. @"Subtask auto-approve is now $(state)")
  436. .navigate(@"/tasks/$(task_id)");
  437. } catch (Error e) {
  438. return directives().notify("error", @"Could not toggle auto-approve: $(e.message)")
  439. .navigate(@"/tasks/$(task_id)");
  440. }
  441. }
  442. }
  443. /**
  444. * The task detail page's polling action: rebuilds the `task` slot from
  445. * current data so the three-second client poll shows live comments,
  446. * blocks, output-driven status changes and completions. Navigates
  447. * nowhere; a failed reload leaves the client's state untouched.
  448. */
  449. public class RefreshTaskDataAction : SealedTaskAction {
  450. private TaskService task_service = inject<TaskService>();
  451. private ProjectService project_service = inject<ProjectService>();
  452. private SaddleService saddle_service = inject<SaddleService>();
  453. private RuleService rule_service = inject<RuleService>();
  454. private CapabilityService capability_service = inject<CapabilityService>();
  455. private UserService users = inject<UserService>();
  456. public override async DirectiveBuilder handle() throws GLib.Error {
  457. var guard = yield SpryAuth.require_login(directives(), request, users);
  458. if (guard != null) {
  459. return (!)guard;
  460. }
  461. int64 task_id = sealed_task_id();
  462. if (task_id <= 0) {
  463. return directives();
  464. }
  465. var state = yield TaskDetailState.build(state_service, task_service,
  466. project_service, saddle_service, rule_service, capability_service,
  467. action_registry, task_id);
  468. return directives().set(state);
  469. }
  470. }
  471. }