HomeEntrypoint.vala 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403
  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. /** Public data of the dashboard's `dashboard` slot. */
  73. public class DashboardPublic : Object {
  74. public int64 draft_count { get; set; }
  75. /**
  76. * Waiting-for-attention work (goal 2 QoL): everything the
  77. * system owes a dispatch or resume to — ready-to-dispatch
  78. * queued tasks (the ready_count subset) + parked work awaiting
  79. * resume (suspended tasks, suspended goal-agent runs included)
  80. * + tasks whose raised blocks are all answered and now wait
  81. * for a saddle to pick the resume up (these leave
  82. * blocked_count, which stays human-answerable rows only).
  83. * Raw queued rows gated on an unfinished auto-enqueue
  84. * predecessor are deliberately OUT — sequenced future work,
  85. * the predecessor itself is already counted.
  86. */
  87. public int64 queued_count { get; set; }
  88. public int64 ready_count { get; set; }
  89. public int64 active_count { get; set; }
  90. public int64 blocked_count { get; set; }
  91. public int64 done_count { get; set; }
  92. public int64 failed_count { get; set; }
  93. public int64 idle_saddle_count { get; set; }
  94. public Statum.Model.ActionDto? refresh { get; set; }
  95. /** The VAPID public key the browser subscribes with ("" when push is unavailable). */
  96. public string push_vapid_key { get; set; default = ""; }
  97. /** The signed-in user holds at least one push subscription. */
  98. public bool push_subscribed { get; set; }
  99. public Statum.Model.ActionDto? push_subscribe { get; set; }
  100. public Statum.Model.ActionDto? push_unsubscribe { get; set; }
  101. /** Queues a REAL test push to this user (the bell's probe). */
  102. public Statum.Model.ActionDto? push_test { get; set; }
  103. }
  104. /**
  105. * Builds the `dashboard` slot state shared by the home entrypoint and
  106. * the {@link RefreshDashboardAction} pulse refresh, so both hydrate
  107. * identical state: queue counters, saddle cards, the pinned OPEN
  108. * blocking items as link-through cards (newest first — plan 10
  109. * phase 3; goal items arrive with the run task's own blocks,
  110. * plan 15 C1), active tasks with their latest progress, and the
  111. * cross-task activity timeline ({@link TimelineService}: last ~50
  112. * events, newest first).
  113. */
  114. public class DashboardState : Object {
  115. /**
  116. * Loads the dashboard aggregate and shapes its PAGE slot. The
  117. * `db` session comes from the caller (entrypoint or action scope).
  118. */
  119. public static async Statum.Slot build(StateService state_service, TaskService tasks,
  120. SaddleService saddles, TimelineService timeline,
  121. InvercargillSql.Orm.OrmSession db,
  122. ActionRegistry? actions = null, PushService? push = null,
  123. int64 viewer_id = 0) throws GLib.Error {
  124. var pub = new DashboardPublic();
  125. var titles = new Dictionary<string, string>();
  126. var all_tasks = yield tasks.list_tasks(null, null);
  127. // The ready-to-dispatch subset of the queued rows (see the
  128. // queued_count docblock), keyed by id so the status loop can
  129. // tell a dispatchable queued task from one still gated on
  130. // its auto-enqueue predecessor.
  131. var ready_ids = new HashSet<string>();
  132. int64 ready_count = 0;
  133. foreach (var ready in yield tasks.get_ready_tasks()) {
  134. ready_ids.add(ready.id.to_string());
  135. if (ready.kind != TASK_KIND_GOAL_RUN) {
  136. ready_count++;
  137. }
  138. }
  139. pub.ready_count = ready_count;
  140. foreach (var task in all_tasks) {
  141. titles.set(task.id.to_string(), task.title);
  142. // Goal-agent runs are internal tasks — they never count
  143. // against the human-facing queue summary (the goal page
  144. // owns their visibility) EXCEPT parked: a suspended run
  145. // is goal work the system owes a resume, so it joins
  146. // queued_count (goal 2 QoL).
  147. if (task.kind == TASK_KIND_GOAL_RUN && task.status != STATUS_SUSPENDED) {
  148. continue;
  149. }
  150. switch (task.status) {
  151. case STATUS_DRAFT:
  152. pub.draft_count++;
  153. break;
  154. case STATUS_QUEUED:
  155. // Ready rows are the queued metric's core;
  156. // predecessor-gated rows are sequenced future
  157. // work the counters leave out (docblock above).
  158. if (ready_ids.has(task.id.to_string())) {
  159. pub.queued_count++;
  160. }
  161. break;
  162. case STATUS_ASSIGNED:
  163. case STATUS_WORKING:
  164. pub.active_count++;
  165. break;
  166. case STATUS_SUSPENDED:
  167. // Parked awaiting resume (goal 2 QoL): a
  168. // suspended task waits on the system, not on a
  169. // human — it reads as waiting, not blocked.
  170. pub.queued_count++;
  171. break;
  172. case STATUS_BLOCKED:
  173. case STATUS_REVIEW_REQUESTED:
  174. // Goal 2 QoL: answered blocks mean the human
  175. // already acted — the task now waits for a
  176. // saddle to resume it, so it joins the queued
  177. // metric and leaves blocked_count (which stays
  178. // genuinely-needs-a-human rows).
  179. if (yield blocks_all_answered(tasks, task.id)) {
  180. pub.queued_count++;
  181. } else {
  182. pub.blocked_count++;
  183. }
  184. break;
  185. case STATUS_DONE:
  186. pub.done_count++;
  187. break;
  188. case STATUS_FAILED:
  189. pub.failed_count++;
  190. break;
  191. default:
  192. break;
  193. }
  194. }
  195. var saddle_rows = new Vector<DashboardSaddleView>();
  196. foreach (var saddle in yield saddles.list_saddles()) {
  197. // Plan 16 item 23: the card reads the DERIVED view —
  198. // busy iff a running session exists, else the row's
  199. // stored OFFLINE probe state.
  200. var work = yield saddles.current_work_view(saddle);
  201. string status = SaddleService.derived_status(saddle, work);
  202. if (status == SADDLE_IDLE) {
  203. pub.idle_saddle_count++;
  204. }
  205. var view = new DashboardSaddleView() {
  206. id = saddle.id,
  207. name = saddle.name,
  208. status = status,
  209. host = saddle.host,
  210. current_task_id = work != null ? ((!)work).task_id : 0
  211. };
  212. if (work != null) {
  213. view.current_task_title = ((!)work).task_title;
  214. if (((!)work).goal_id > 0) {
  215. view.current_goal_id = ((!)work).goal_id;
  216. view.current_goal_title = ((!)work).goal_title;
  217. }
  218. }
  219. saddle_rows.add(view);
  220. }
  221. var active = new Vector<DashboardActiveView>();
  222. var pinned = new Vector<DashboardBlockView>();
  223. foreach (var task in yield tasks.list_tasks(null, null)) {
  224. // Goal-agent runs are internal — never an "active
  225. // task" row (the goal page shows the agent's
  226. // activity). Their BLOCKS still pin below (plan 15
  227. // C1): the run task's rows are the goal's pile cards.
  228. bool internal_run = task.kind == TASK_KIND_GOAL_RUN;
  229. if (!internal_run
  230. && (task.status == STATUS_ASSIGNED || task.status == STATUS_WORKING
  231. || task.status == STATUS_BLOCKED || task.status == STATUS_REVIEW_REQUESTED)) {
  232. var row = new DashboardActiveView() {
  233. id = task.id,
  234. title = task.title,
  235. status = task.status,
  236. task_branch = task.task_branch ?? ""
  237. };
  238. var progress = yield tasks.list_progress(task.id);
  239. if (progress.length > 0) {
  240. row.latest_progress = progress.first().summary;
  241. row.progress_display = format_stamp(progress.first().created_at);
  242. }
  243. active.add(row);
  244. }
  245. // Every unanswered block pins as a link-through card —
  246. // questions, RFCs and reviews alike. Plan 15 C1: the
  247. // goal agent's blocks ARE the run task's blocks (one
  248. // row each) — they render as goal items (goal badge,
  249. // goal link) straight from this same loop; there is no
  250. // goal-side pass and no mirror to consult.
  251. int64 block_goal_id = 0;
  252. string block_goal_title = "";
  253. if (internal_run && task.goal_id > 0) {
  254. block_goal_id = task.goal_id;
  255. var goal_row = yield db.query<Goal>()
  256. .where(expr("id == $0", elem<int64?>(task.goal_id)))
  257. .first_async();
  258. block_goal_title = goal_row != null ? ((!)goal_row).title : "";
  259. }
  260. foreach (var block in yield tasks.list_blocks(task.id)) {
  261. if (block.answer != null) {
  262. continue;
  263. }
  264. var view = new DashboardBlockView() {
  265. item_type = block_goal_id > 0 ? "goal" : "task",
  266. id = block.id,
  267. task_id = task.id,
  268. task_title = task.title,
  269. goal_id = block_goal_id,
  270. goal_title = block_goal_title,
  271. block_type = block.block_type,
  272. question = block.question,
  273. created_display = format_stamp(block.created_at)
  274. };
  275. if (block.created_at != null) {
  276. view.at_epoch = ((!)block.created_at).to_unix();
  277. }
  278. pinned.add(view);
  279. }
  280. }
  281. // Newest first (plan 10 phase 3): the most recent question,
  282. // RFC, review or goal block leads the unified pile.
  283. var pinned_sorted = pinned.sort((a, b) => {
  284. if (a.at_epoch != b.at_epoch) {
  285. return a.at_epoch > b.at_epoch ? -1 : 1;
  286. }
  287. return a.id > b.id ? -1 : 1;
  288. });
  289. if (actions != null) {
  290. pub.refresh = ((!)actions).author<RefreshDashboardAction>("GET");
  291. pub.push_subscribe = ((!)actions).author<PushSubscribeAction>();
  292. pub.push_unsubscribe = ((!)actions).author<PushUnsubscribeAction>();
  293. pub.push_test = ((!)actions).author<PushTestAction>();
  294. }
  295. // Web Push bell state (plan 11 task E; per-browser since
  296. // the user-global flag lied to second browsers): the VAPID
  297. // key the browser needs, whether this user subscribed
  298. // anywhere (convenience), and this user's endpoint
  299. // FINGERPRINTS — the client compares its own subscription's
  300. // fingerprint against the list, so each browser shows its
  301. // own truth.
  302. pub.push_vapid_key = PushService.vapid_public_key;
  303. // Not a DashboardPublic property: GObjectMapping cannot
  304. // serialise array-shaped values, so the fingerprint list
  305. // rides the props dictionary like every other list here.
  306. string[] push_fingerprints = new string[0];
  307. if (push != null && viewer_id > 0) {
  308. pub.push_subscribed = yield ((!)push).user_subscribed(db, viewer_id);
  309. push_fingerprints = yield ((!)push)
  310. .user_endpoint_fingerprints(db, viewer_id);
  311. }
  312. var activity = new Vector<DashboardActivityView>();
  313. foreach (var item in yield timeline.recent_window()) {
  314. activity.add(new DashboardActivityView() {
  315. kind = item.kind,
  316. at_epoch = item.at_epoch,
  317. when_display = format_stamp(new DateTime.from_unix_local(item.at_epoch)),
  318. task_id = item.task_id,
  319. task_title = item.task_title,
  320. goal_id = item.goal_id,
  321. goal_title = item.goal_title,
  322. text = item.text
  323. });
  324. }
  325. var props = (PropertyDictionary) GObjectMapping.to_properties(pub);
  326. props["saddles"] = StateJson.list<DashboardSaddleView>(saddle_rows.to_immutable_buffer());
  327. props["push_endpoints"] = StateJson.strings(push_fingerprints);
  328. props["activity"] = StateJson.list<DashboardActivityView>(activity.to_immutable_buffer());
  329. props["active_tasks"] = StateJson.list<DashboardActiveView>(active.to_immutable_buffer());
  330. props["pinned"] = StateJson.list<DashboardBlockView>(pinned_sorted.to_immutable_buffer());
  331. return state_service.new_slot(Scope.PAGE, new Statum.State() {
  332. type_name = "dashboard",
  333. public_data = props,
  334. private_data = new PropertyDictionary()
  335. });
  336. }
  337. /**
  338. * True when the task has at least one block and every one of
  339. * them carries an answer (goal 2 QoL): the human already
  340. * acted, the dispatcher's resume is the only thing owed. A
  341. * task with no blocks at all is NOT answered-waiting — the
  342. * counters leave such rows in blocked_count untouched.
  343. */
  344. private static async bool blocks_all_answered(TaskService tasks, int64 task_id) throws GLib.Error {
  345. bool any = false;
  346. foreach (var block in yield tasks.list_blocks(task_id)) {
  347. any = true;
  348. if (block.answer == null) {
  349. return false;
  350. }
  351. }
  352. return any;
  353. }
  354. }
  355. /**
  356. * Entrypoint for /: the dashboard — queue summary, the pinned OPEN
  357. * blocking items as link-through cards (newest first), active tasks
  358. * with their latest progress, saddle cards, and the cross-task
  359. * activity timeline (last ~50 events, newest first). The page
  360. * subscribes to the global pulse and re-runs its sealed refresh
  361. * action whenever task or saddle state changes anywhere in the app.
  362. */
  363. public class HomeEntrypoint : StatumEntrypoint {
  364. private TaskService task_service = Inversion.inject<TaskService>();
  365. private SaddleService saddle_service = Inversion.inject<SaddleService>();
  366. private TimelineService timeline_service = Inversion.inject<TimelineService>();
  367. private InvercargillSql.Orm.OrmSession db = Inversion.inject<InvercargillSql.Orm.OrmSession>();
  368. private PushService push_service = Inversion.inject<PushService>();
  369. private UserService users = Inversion.inject<UserService>();
  370. public override async DirectiveBuilder handle() throws GLib.Error {
  371. var guard = yield SpryAuth.require_login(directives(), request, users);
  372. if (guard != null) {
  373. return (!)guard;
  374. }
  375. var me = SpryAuth.current(request);
  376. var state = yield DashboardState.build(state_service, task_service,
  377. saddle_service, timeline_service, db, action_registry,
  378. push_service, me != null ? ((!)me).user_id : 0);
  379. return directives().set(state).subscribe_global(StatePulse.SLOT_TYPE);
  380. }
  381. }
  382. }