HomeEntrypoint.vala 23 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484
  1. using Invercargill;
  2. using Invercargill.DataStructures;
  3. using Invercargill.Expressions;
  4. using Spry;
  5. using Spry.Authentication;
  6. using Statum;
  7. using ClankerSaddle.Data;
  8. using ClankerSaddle.Services;
  9. namespace ClankerSaddle {
  10. /** A saddle card on the dashboard. */
  11. public class DashboardSaddleView : Object {
  12. public int64 id { get; set; }
  13. public string name { get; set; default = ""; }
  14. public string status { get; set; default = SADDLE_OFFLINE; }
  15. public string host { get; set; default = ""; }
  16. public int64 current_task_id { get; set; }
  17. public string current_task_title { get; set; default = ""; }
  18. /**
  19. * Set when the saddle's current task is a goal agent's run:
  20. * the card then links the GOAL (runs are internal — never a
  21. * task destination at a glance).
  22. */
  23. public int64 current_goal_id { get; set; }
  24. public string current_goal_title { get; set; default = ""; }
  25. }
  26. /** One entry in the dashboard's cross-task activity timeline. */
  27. public class DashboardActivityView : Object {
  28. public string kind { get; set; default = ""; }
  29. public int64 at_epoch { get; set; }
  30. public string when_display { get; set; default = ""; }
  31. public int64 task_id { get; set; }
  32. public string task_title { get; set; default = ""; }
  33. /** Plan 12: set on goal events — the row links the goal page. */
  34. public int64 goal_id { get; set; }
  35. public string goal_title { get; set; default = ""; }
  36. public string text { get; set; default = ""; }
  37. }
  38. /** An active task with its latest progress line. */
  39. public class DashboardActiveView : Object {
  40. public int64 id { get; set; }
  41. public string title { get; set; default = ""; }
  42. public string status { get; set; default = ""; }
  43. public string latest_progress { get; set; default = ""; }
  44. public string progress_display { get; set; default = ""; }
  45. public string task_branch { get; set; default = ""; }
  46. }
  47. /**
  48. * A pinned OPEN blocking item (plan 10 phase 3; plan 12 unified;
  49. * plan 15 C1 single-row): an unanswered question, RFC, review or
  50. * the goal agent's block (question/RFC, plan submission,
  51. * completion report — all rows of the goal-run task) rendered as
  52. * a link-through card. Goal items carry `item_type` "goal" and
  53. * link the goal page; task items carry "task" and link the task
  54. * page where the answer form lives. No inline answer forms on the
  55. * dashboard (settled).
  56. */
  57. public class DashboardBlockView : Object {
  58. /** "task" or "goal" — the pile interleaves both. */
  59. public string item_type { get; set; default = "task"; }
  60. public int64 id { get; set; }
  61. public int64 task_id { get; set; }
  62. public string task_title { get; set; default = ""; }
  63. /** Goal items only: the goal the block belongs to. */
  64. public int64 goal_id { get; set; }
  65. public string goal_title { get; set; default = ""; }
  66. public string block_type { get; set; default = "question"; }
  67. public string question { get; set; default = ""; }
  68. public string created_display { get; set; default = ""; }
  69. /** The created stamp's epoch — the unified newest-first key. */
  70. public int64 at_epoch { get; set; }
  71. }
  72. /** A project option in the note promote form's select. */
  73. public class DashboardProjectOptionView : Object {
  74. public int64 id { get; set; }
  75. public string name { get; set; default = ""; }
  76. }
  77. /**
  78. * A scratchpad note row on the dashboard (goal 8 task 3): the
  79. * body, its done state, and the per-row actions. An unpromoted,
  80. * undone note carries the promote action; a promoted note carries
  81. * its goal link instead (and never a second promote).
  82. */
  83. public class DashboardNoteView : Object {
  84. public int64 id { get; set; }
  85. public string body { get; set; default = ""; }
  86. public bool done { get; set; }
  87. public string done_display { get; set; default = ""; }
  88. public string created_display { get; set; default = ""; }
  89. /** The goal this note promoted into (0 = not promoted). */
  90. public int64 goal_id { get; set; }
  91. public string goal_title { get; set; default = ""; }
  92. public Statum.Model.ActionDto? toggle { get; set; }
  93. public Statum.Model.ActionDto? delete { get; set; }
  94. public Statum.Model.ActionDto? promote { get; set; }
  95. }
  96. /** Public data of the dashboard's `dashboard` slot. */
  97. public class DashboardPublic : Object {
  98. public int64 draft_count { get; set; }
  99. /**
  100. * Waiting-for-attention work (goal 2 QoL): everything the
  101. * system owes a dispatch or resume to — ready-to-dispatch
  102. * queued tasks (the ready_count subset) + parked work awaiting
  103. * resume (suspended tasks, suspended goal-agent runs included)
  104. * + tasks whose raised blocks are all answered and now wait
  105. * for a saddle to pick the resume up (these leave
  106. * blocked_count, which stays human-answerable rows only).
  107. * Raw queued rows gated on an unfinished auto-enqueue
  108. * predecessor are deliberately OUT — sequenced future work,
  109. * the predecessor itself is already counted.
  110. */
  111. public int64 queued_count { get; set; }
  112. public int64 ready_count { get; set; }
  113. public int64 active_count { get; set; }
  114. public int64 blocked_count { get; set; }
  115. public int64 done_count { get; set; }
  116. public int64 failed_count { get; set; }
  117. public int64 idle_saddle_count { get; set; }
  118. public Statum.Model.ActionDto? refresh { get; set; }
  119. /** The VAPID public key the browser subscribes with ("" when push is unavailable). */
  120. public string push_vapid_key { get; set; default = ""; }
  121. /** The signed-in user holds at least one push subscription. */
  122. public bool push_subscribed { get; set; }
  123. public Statum.Model.ActionDto? push_subscribe { get; set; }
  124. public Statum.Model.ActionDto? push_unsubscribe { get; set; }
  125. /** Queues a REAL test push to this user (the bell's probe). */
  126. public Statum.Model.ActionDto? push_test { get; set; }
  127. /**
  128. * Adds a scratchpad note (goal 8 task 3) — the Notes card's
  129. * add form.
  130. */
  131. public Statum.Model.ActionDto? add_note { get; set; }
  132. }
  133. /**
  134. * Builds the `dashboard` slot state shared by the home entrypoint and
  135. * the {@link RefreshDashboardAction} pulse refresh, so both hydrate
  136. * identical state: queue counters, saddle cards, the pinned OPEN
  137. * blocking items as link-through cards (newest first — plan 10
  138. * phase 3; goal items arrive with the run task's own blocks,
  139. * plan 15 C1), active tasks with their latest progress, and the
  140. * cross-task activity timeline ({@link TimelineService}: last ~50
  141. * events, newest first).
  142. */
  143. public class DashboardState : Object {
  144. /**
  145. * Loads the dashboard aggregate and shapes its PAGE slot. The
  146. * `db` session comes from the caller (entrypoint or action scope).
  147. */
  148. public static async Statum.Slot build(StateService state_service, TaskService tasks,
  149. SaddleService saddles, TimelineService timeline,
  150. InvercargillSql.Orm.OrmSession db, NoteService notes,
  151. ActionRegistry? actions = null, PushService? push = null,
  152. int64 viewer_id = 0) throws GLib.Error {
  153. var pub = new DashboardPublic();
  154. var titles = new Dictionary<string, string>();
  155. var all_tasks = yield tasks.list_tasks(null, null);
  156. // The ready-to-dispatch subset of the queued rows (see the
  157. // queued_count docblock), keyed by id so the status loop can
  158. // tell a dispatchable queued task from one still gated on
  159. // its auto-enqueue predecessor.
  160. var ready_ids = new HashSet<string>();
  161. int64 ready_count = 0;
  162. foreach (var ready in yield tasks.get_ready_tasks()) {
  163. ready_ids.add(ready.id.to_string());
  164. if (ready.kind != TASK_KIND_GOAL_RUN) {
  165. ready_count++;
  166. }
  167. }
  168. pub.ready_count = ready_count;
  169. foreach (var task in all_tasks) {
  170. titles.set(task.id.to_string(), task.title);
  171. // Goal-agent runs are internal tasks — they never count
  172. // against the human-facing queue summary (the goal page
  173. // owns their visibility) EXCEPT parked: a suspended run
  174. // is goal work the system owes a resume, so it joins
  175. // queued_count (goal 2 QoL).
  176. if (task.kind == TASK_KIND_GOAL_RUN && task.status != STATUS_SUSPENDED) {
  177. continue;
  178. }
  179. switch (task.status) {
  180. case STATUS_DRAFT:
  181. pub.draft_count++;
  182. break;
  183. case STATUS_QUEUED:
  184. // Ready rows are the queued metric's core;
  185. // predecessor-gated rows are sequenced future
  186. // work the counters leave out (docblock above).
  187. if (ready_ids.has(task.id.to_string())) {
  188. pub.queued_count++;
  189. }
  190. break;
  191. case STATUS_ASSIGNED:
  192. case STATUS_WORKING:
  193. pub.active_count++;
  194. break;
  195. case STATUS_SUSPENDED:
  196. // Parked awaiting resume (goal 2 QoL): a
  197. // suspended task waits on the system, not on a
  198. // human — it reads as waiting, not blocked.
  199. pub.queued_count++;
  200. break;
  201. case STATUS_BLOCKED:
  202. case STATUS_REVIEW_REQUESTED:
  203. // Goal 2 QoL: answered blocks mean the human
  204. // already acted — the task now waits for a
  205. // saddle to resume it, so it joins the queued
  206. // metric and leaves blocked_count (which stays
  207. // genuinely-needs-a-human rows).
  208. if (yield blocks_all_answered(tasks, task.id)) {
  209. pub.queued_count++;
  210. } else {
  211. pub.blocked_count++;
  212. }
  213. break;
  214. case STATUS_DONE:
  215. pub.done_count++;
  216. break;
  217. case STATUS_FAILED:
  218. pub.failed_count++;
  219. break;
  220. default:
  221. break;
  222. }
  223. }
  224. var saddle_rows = new Vector<DashboardSaddleView>();
  225. foreach (var saddle in yield saddles.list_saddles()) {
  226. // Plan 16 item 23: the card reads the DERIVED view —
  227. // busy iff a running session exists, else the row's
  228. // stored OFFLINE probe state.
  229. var work = yield saddles.current_work_view(saddle);
  230. string status = SaddleService.derived_status(saddle, work);
  231. if (status == SADDLE_IDLE) {
  232. pub.idle_saddle_count++;
  233. }
  234. var view = new DashboardSaddleView() {
  235. id = saddle.id,
  236. name = saddle.name,
  237. status = status,
  238. host = saddle.host,
  239. current_task_id = work != null ? ((!)work).task_id : 0
  240. };
  241. if (work != null) {
  242. view.current_task_title = ((!)work).task_title;
  243. if (((!)work).goal_id > 0) {
  244. view.current_goal_id = ((!)work).goal_id;
  245. view.current_goal_title = ((!)work).goal_title;
  246. }
  247. }
  248. saddle_rows.add(view);
  249. }
  250. var active = new Vector<DashboardActiveView>();
  251. var pinned = new Vector<DashboardBlockView>();
  252. foreach (var task in yield tasks.list_tasks(null, null)) {
  253. // Goal-agent runs are internal — never an "active
  254. // task" row (the goal page shows the agent's
  255. // activity). Their BLOCKS still pin below (plan 15
  256. // C1): the run task's rows are the goal's pile cards.
  257. bool internal_run = task.kind == TASK_KIND_GOAL_RUN;
  258. if (!internal_run
  259. && (task.status == STATUS_ASSIGNED || task.status == STATUS_WORKING
  260. || task.status == STATUS_BLOCKED || task.status == STATUS_REVIEW_REQUESTED)) {
  261. var row = new DashboardActiveView() {
  262. id = task.id,
  263. title = task.title,
  264. status = task.status,
  265. task_branch = task.task_branch ?? ""
  266. };
  267. var progress = yield tasks.list_progress(task.id);
  268. if (progress.length > 0) {
  269. row.latest_progress = progress.first().summary;
  270. row.progress_display = format_stamp(progress.first().created_at);
  271. }
  272. active.add(row);
  273. }
  274. // Every unanswered block pins as a link-through card —
  275. // questions, RFCs and reviews alike. Plan 15 C1: the
  276. // goal agent's blocks ARE the run task's blocks (one
  277. // row each) — they render as goal items (goal badge,
  278. // goal link) straight from this same loop; there is no
  279. // goal-side pass and no mirror to consult.
  280. int64 block_goal_id = 0;
  281. string block_goal_title = "";
  282. if (internal_run && task.goal_id > 0) {
  283. block_goal_id = task.goal_id;
  284. var goal_row = yield db.query<Goal>()
  285. .where(expr("id == $0", elem<int64?>(task.goal_id)))
  286. .first_async();
  287. block_goal_title = goal_row != null ? ((!)goal_row).title : "";
  288. }
  289. foreach (var block in yield tasks.list_blocks(task.id)) {
  290. if (block.answer != null) {
  291. continue;
  292. }
  293. var view = new DashboardBlockView() {
  294. item_type = block_goal_id > 0 ? "goal" : "task",
  295. id = block.id,
  296. task_id = task.id,
  297. task_title = task.title,
  298. goal_id = block_goal_id,
  299. goal_title = block_goal_title,
  300. block_type = block.block_type,
  301. question = block.question,
  302. created_display = format_stamp(block.created_at)
  303. };
  304. if (block.created_at != null) {
  305. view.at_epoch = ((!)block.created_at).to_unix();
  306. }
  307. pinned.add(view);
  308. }
  309. }
  310. // Newest first (plan 10 phase 3): the most recent question,
  311. // RFC, review or goal block leads the unified pile.
  312. var pinned_sorted = pinned.sort((a, b) => {
  313. if (a.at_epoch != b.at_epoch) {
  314. return a.at_epoch > b.at_epoch ? -1 : 1;
  315. }
  316. return a.id > b.id ? -1 : 1;
  317. });
  318. if (actions != null) {
  319. pub.refresh = ((!)actions).author<RefreshDashboardAction>("GET");
  320. pub.push_subscribe = ((!)actions).author<PushSubscribeAction>();
  321. pub.push_unsubscribe = ((!)actions).author<PushUnsubscribeAction>();
  322. pub.push_test = ((!)actions).author<PushTestAction>();
  323. pub.add_note = ((!)actions).author<AddNoteAction>();
  324. }
  325. // Web Push bell state (plan 11 task E; per-browser since
  326. // the user-global flag lied to second browsers): the VAPID
  327. // key the browser needs, whether this user subscribed
  328. // anywhere (convenience), and this user's endpoint
  329. // FINGERPRINTS — the client compares its own subscription's
  330. // fingerprint against the list, so each browser shows its
  331. // own truth.
  332. pub.push_vapid_key = PushService.vapid_public_key;
  333. // Not a DashboardPublic property: GObjectMapping cannot
  334. // serialise array-shaped values, so the fingerprint list
  335. // rides the props dictionary like every other list here.
  336. string[] push_fingerprints = new string[0];
  337. if (push != null && viewer_id > 0) {
  338. pub.push_subscribed = yield ((!)push).user_subscribed(db, viewer_id);
  339. push_fingerprints = yield ((!)push)
  340. .user_endpoint_fingerprints(db, viewer_id);
  341. }
  342. var activity = new Vector<DashboardActivityView>();
  343. foreach (var item in yield timeline.recent_window()) {
  344. activity.add(new DashboardActivityView() {
  345. kind = item.kind,
  346. at_epoch = item.at_epoch,
  347. when_display = format_stamp(new DateTime.from_unix_local(item.at_epoch)),
  348. task_id = item.task_id,
  349. task_title = item.task_title,
  350. goal_id = item.goal_id,
  351. goal_title = item.goal_title,
  352. text = item.text
  353. });
  354. }
  355. var props = (PropertyDictionary) GObjectMapping.to_properties(pub);
  356. props["saddles"] = StateJson.list<DashboardSaddleView>(saddle_rows.to_immutable_buffer());
  357. props["push_endpoints"] = StateJson.strings(push_fingerprints);
  358. props["activity"] = StateJson.list<DashboardActivityView>(activity.to_immutable_buffer());
  359. props["active_tasks"] = StateJson.list<DashboardActiveView>(active.to_immutable_buffer());
  360. props["pinned"] = StateJson.list<DashboardBlockView>(pinned_sorted.to_immutable_buffer());
  361. // The scratchpad (goal 8 task 3): every note with its
  362. // per-row sealed actions; promoted notes link their goal
  363. // and never carry a promote action again.
  364. var note_rows = new Vector<DashboardNoteView>();
  365. foreach (var note in yield notes.list_notes()) {
  366. var view = new DashboardNoteView() {
  367. id = note.id,
  368. body = note.body,
  369. done = note.done,
  370. created_display = format_stamp(note.created_at),
  371. toggle = ((!)actions).author_private<ToggleNoteAction, NoteActionPrivate>(
  372. new NoteActionPrivate() { note_id = note.id }),
  373. delete = ((!)actions).author_private<DeleteNoteAction, NoteActionPrivate>(
  374. new NoteActionPrivate() { note_id = note.id })
  375. };
  376. if (note.done_at != null) {
  377. view.done_display = format_stamp(note.done_at);
  378. }
  379. if (note.goal_id > 0) {
  380. view.goal_id = note.goal_id;
  381. var goal_row = yield db.query<Goal>()
  382. .where(expr("id == $0", elem<int64?>(note.goal_id)))
  383. .first_async();
  384. if (goal_row != null) {
  385. view.goal_title = ((!)goal_row).title;
  386. }
  387. } else if (!note.done) {
  388. view.promote = ((!)actions).author_private<PromoteNoteAction, NoteActionPrivate>(
  389. new NoteActionPrivate() { note_id = note.id });
  390. }
  391. note_rows.add(view);
  392. }
  393. props["notes"] = StateJson.list<DashboardNoteView>(note_rows.to_immutable_buffer());
  394. // The promote form's project options (goal 8 task 3):
  395. // every project, oldest first — a stable select order.
  396. var project_options = new Vector<DashboardProjectOptionView>();
  397. foreach (var project in yield db.query<Project>()
  398. .order_by(expr("id"))
  399. .materialise_async()) {
  400. project_options.add(new DashboardProjectOptionView() {
  401. id = project.id,
  402. name = project.name
  403. });
  404. }
  405. props["projects"] = StateJson.list<DashboardProjectOptionView>(
  406. project_options.to_immutable_buffer());
  407. return state_service.new_slot(Scope.PAGE, new Statum.State() {
  408. type_name = "dashboard",
  409. public_data = props,
  410. private_data = new PropertyDictionary()
  411. });
  412. }
  413. /**
  414. * True when the task has at least one block and every one of
  415. * them carries an answer (goal 2 QoL): the human already
  416. * acted, the dispatcher's resume is the only thing owed. A
  417. * task with no blocks at all is NOT answered-waiting — the
  418. * counters leave such rows in blocked_count untouched.
  419. */
  420. private static async bool blocks_all_answered(TaskService tasks, int64 task_id) throws GLib.Error {
  421. bool any = false;
  422. foreach (var block in yield tasks.list_blocks(task_id)) {
  423. any = true;
  424. if (block.answer == null) {
  425. return false;
  426. }
  427. }
  428. return any;
  429. }
  430. }
  431. /**
  432. * Entrypoint for /: the dashboard — queue summary, the pinned OPEN
  433. * blocking items as link-through cards (newest first), active tasks
  434. * with their latest progress, saddle cards, and the cross-task
  435. * activity timeline (last ~50 events, newest first). The page
  436. * subscribes to the global pulse and re-runs its sealed refresh
  437. * action whenever task or saddle state changes anywhere in the app.
  438. */
  439. public class HomeEntrypoint : StatumEntrypoint {
  440. private TaskService task_service = Inversion.inject<TaskService>();
  441. private SaddleService saddle_service = Inversion.inject<SaddleService>();
  442. private TimelineService timeline_service = Inversion.inject<TimelineService>();
  443. private NoteService note_service = Inversion.inject<NoteService>();
  444. private InvercargillSql.Orm.OrmSession db = Inversion.inject<InvercargillSql.Orm.OrmSession>();
  445. private PushService push_service = Inversion.inject<PushService>();
  446. private UserService users = Inversion.inject<UserService>();
  447. public override async DirectiveBuilder handle() throws GLib.Error {
  448. var guard = yield SpryAuth.require_login(directives(), request, users);
  449. if (guard != null) {
  450. return (!)guard;
  451. }
  452. var me = SpryAuth.current(request);
  453. var state = yield DashboardState.build(state_service, task_service,
  454. saddle_service, timeline_service, db, note_service, action_registry,
  455. push_service, me != null ? ((!)me).user_id : 0);
  456. return directives().set(state).subscribe_global(StatePulse.SLOT_TYPE);
  457. }
  458. }
  459. }