HomeEntrypoint.vala 25 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526
  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. /**
  124. * True when an LLM endpoint resolves from the environment —
  125. * the dashboard's "Ask the advisor" composer renders disabled
  126. * with a notice when false (goal 27).
  127. */
  128. public bool advisor_configured { get; set; }
  129. /**
  130. * Starts a new advisor chat from the dashboard's hero
  131. * composer (goal 27): creates the chat, records the message
  132. * and kicks the background turn.
  133. */
  134. public Statum.Model.ActionDto? start_advisor { get; set; }
  135. public Statum.Model.ActionDto? push_subscribe { get; set; }
  136. public Statum.Model.ActionDto? push_unsubscribe { get; set; }
  137. /** Queues a REAL test push to this user (the bell's probe). */
  138. public Statum.Model.ActionDto? push_test { get; set; }
  139. /**
  140. * Adds a scratchpad note (goal 8 task 3) — the Notes card's
  141. * add form.
  142. */
  143. public Statum.Model.ActionDto? add_note { get; set; }
  144. }
  145. /** One of the five newest discoveries on the dashboard (goal 24). */
  146. public class DashboardDiscoveryView : Object {
  147. public string body { get; set; default = ""; }
  148. }
  149. /**
  150. * Builds the `dashboard` slot state shared by the home entrypoint and
  151. * the {@link RefreshDashboardAction} pulse refresh, so both hydrate
  152. * identical state: queue counters, saddle cards, the pinned OPEN
  153. * blocking items as link-through cards (newest first — plan 10
  154. * phase 3; goal items arrive with the run task's own blocks,
  155. * plan 15 C1), active tasks with their latest progress, and the
  156. * cross-task activity timeline ({@link TimelineService}: last ~50
  157. * events, newest first).
  158. */
  159. public class DashboardState : Object {
  160. /**
  161. * Loads the dashboard aggregate and shapes its PAGE slot. The
  162. * `db` session comes from the caller (entrypoint or action scope).
  163. */
  164. public static async Statum.Slot build(StateService state_service, TaskService tasks,
  165. SaddleService saddles, TimelineService timeline,
  166. InvercargillSql.Orm.OrmSession db, NoteService notes,
  167. ActionRegistry? actions = null, PushService? push = null,
  168. int64 viewer_id = 0) throws GLib.Error {
  169. var pub = new DashboardPublic();
  170. var titles = new Dictionary<string, string>();
  171. var all_tasks = yield tasks.list_tasks(null, null);
  172. // The ready-to-dispatch subset of the queued rows (see the
  173. // queued_count docblock), keyed by id so the status loop can
  174. // tell a dispatchable queued task from one still gated on
  175. // its auto-enqueue predecessor.
  176. var ready_ids = new HashSet<string>();
  177. int64 ready_count = 0;
  178. foreach (var ready in yield tasks.get_ready_tasks()) {
  179. ready_ids.add(ready.id.to_string());
  180. if (ready.kind != TASK_KIND_GOAL_RUN) {
  181. ready_count++;
  182. }
  183. }
  184. pub.ready_count = ready_count;
  185. foreach (var task in all_tasks) {
  186. titles.set(task.id.to_string(), task.title);
  187. // Goal-agent runs are internal tasks — they never count
  188. // against the human-facing queue summary (the goal page
  189. // owns their visibility) EXCEPT parked: a suspended run
  190. // is goal work the system owes a resume, so it joins
  191. // queued_count (goal 2 QoL).
  192. if (task.kind == TASK_KIND_GOAL_RUN && task.status != STATUS_SUSPENDED) {
  193. continue;
  194. }
  195. switch (task.status) {
  196. case STATUS_DRAFT:
  197. pub.draft_count++;
  198. break;
  199. case STATUS_QUEUED:
  200. // Ready rows are the queued metric's core;
  201. // predecessor-gated rows are sequenced future
  202. // work the counters leave out (docblock above).
  203. if (ready_ids.has(task.id.to_string())) {
  204. pub.queued_count++;
  205. }
  206. break;
  207. case STATUS_ASSIGNED:
  208. case STATUS_WORKING:
  209. pub.active_count++;
  210. break;
  211. case STATUS_SUSPENDED:
  212. // Parked awaiting resume (goal 2 QoL): a
  213. // suspended task waits on the system, not on a
  214. // human — it reads as waiting, not blocked.
  215. pub.queued_count++;
  216. break;
  217. case STATUS_BLOCKED:
  218. case STATUS_REVIEW_REQUESTED:
  219. // Goal 2 QoL: answered blocks mean the human
  220. // already acted — the task now waits for a
  221. // saddle to resume it, so it joins the queued
  222. // metric and leaves blocked_count (which stays
  223. // genuinely-needs-a-human rows).
  224. if (yield blocks_all_answered(tasks, task.id)) {
  225. pub.queued_count++;
  226. } else {
  227. pub.blocked_count++;
  228. }
  229. break;
  230. case STATUS_DONE:
  231. pub.done_count++;
  232. break;
  233. case STATUS_FAILED:
  234. pub.failed_count++;
  235. break;
  236. default:
  237. break;
  238. }
  239. }
  240. var saddle_rows = new Vector<DashboardSaddleView>();
  241. foreach (var saddle in yield saddles.list_saddles()) {
  242. // Plan 16 item 23: the card reads the DERIVED view —
  243. // busy iff a running session exists, else the row's
  244. // stored OFFLINE probe state.
  245. var work = yield saddles.current_work_view(saddle);
  246. string status = SaddleService.derived_status(saddle, work);
  247. if (status == SADDLE_IDLE) {
  248. pub.idle_saddle_count++;
  249. }
  250. var view = new DashboardSaddleView() {
  251. id = saddle.id,
  252. name = saddle.name,
  253. status = status,
  254. host = saddle.host,
  255. current_task_id = work != null ? ((!)work).task_id : 0
  256. };
  257. if (work != null) {
  258. view.current_task_title = ((!)work).task_title;
  259. if (((!)work).goal_id > 0) {
  260. view.current_goal_id = ((!)work).goal_id;
  261. view.current_goal_title = ((!)work).goal_title;
  262. }
  263. }
  264. saddle_rows.add(view);
  265. }
  266. var active = new Vector<DashboardActiveView>();
  267. var pinned = new Vector<DashboardBlockView>();
  268. foreach (var task in yield tasks.list_tasks(null, null)) {
  269. // Goal-agent runs are internal — never an "active
  270. // task" row (the goal page shows the agent's
  271. // activity). Their BLOCKS still pin below (plan 15
  272. // C1): the run task's rows are the goal's pile cards.
  273. bool internal_run = task.kind == TASK_KIND_GOAL_RUN;
  274. if (!internal_run
  275. && (task.status == STATUS_ASSIGNED || task.status == STATUS_WORKING
  276. || task.status == STATUS_BLOCKED || task.status == STATUS_REVIEW_REQUESTED)) {
  277. var row = new DashboardActiveView() {
  278. id = task.id,
  279. title = task.title,
  280. status = task.status,
  281. task_branch = task.task_branch ?? ""
  282. };
  283. var progress = yield tasks.list_progress(task.id);
  284. if (progress.length > 0) {
  285. row.latest_progress = progress.first().summary;
  286. row.progress_display = format_stamp(progress.first().created_at);
  287. }
  288. active.add(row);
  289. }
  290. // Every unanswered block pins as a link-through card —
  291. // questions, RFCs and reviews alike. Plan 15 C1: the
  292. // goal agent's blocks ARE the run task's blocks (one
  293. // row each) — they render as goal items (goal badge,
  294. // goal link) straight from this same loop; there is no
  295. // goal-side pass and no mirror to consult.
  296. int64 block_goal_id = 0;
  297. string block_goal_title = "";
  298. if (internal_run && task.goal_id > 0) {
  299. block_goal_id = task.goal_id;
  300. var goal_row = yield db.query<Goal>()
  301. .where(expr("id == $0", elem<int64?>(task.goal_id)))
  302. .first_async();
  303. block_goal_title = goal_row != null ? ((!)goal_row).title : "";
  304. }
  305. foreach (var block in yield tasks.list_blocks(task.id)) {
  306. if (block.answer != null) {
  307. continue;
  308. }
  309. var view = new DashboardBlockView() {
  310. item_type = block_goal_id > 0 ? "goal" : "task",
  311. id = block.id,
  312. task_id = task.id,
  313. task_title = task.title,
  314. goal_id = block_goal_id,
  315. goal_title = block_goal_title,
  316. block_type = block.block_type,
  317. question = block.question,
  318. created_display = format_stamp(block.created_at)
  319. };
  320. if (block.created_at != null) {
  321. view.at_epoch = ((!)block.created_at).to_unix();
  322. }
  323. pinned.add(view);
  324. }
  325. }
  326. // Newest first (plan 10 phase 3): the most recent question,
  327. // RFC, review or goal block leads the unified pile.
  328. var pinned_sorted = pinned.sort((a, b) => {
  329. if (a.at_epoch != b.at_epoch) {
  330. return a.at_epoch > b.at_epoch ? -1 : 1;
  331. }
  332. return a.id > b.id ? -1 : 1;
  333. });
  334. if (actions != null) {
  335. pub.refresh = ((!)actions).author<RefreshDashboardAction>("GET");
  336. pub.push_subscribe = ((!)actions).author<PushSubscribeAction>();
  337. pub.push_unsubscribe = ((!)actions).author<PushUnsubscribeAction>();
  338. pub.push_test = ((!)actions).author<PushTestAction>();
  339. pub.add_note = ((!)actions).author<AddNoteAction>();
  340. // The advisor composer (goal 27): an unsealed action —
  341. // the chat it creates belongs to the signed-in user
  342. // by construction.
  343. pub.start_advisor = ((!)actions).author<StartAdvisorChatAction>();
  344. }
  345. // Mirrors AdvisorService.configured (the same environment
  346. // resolution, resolved statically so the shared build
  347. // needs no new injected dependency) so the composer can
  348. // disable itself with a notice when no endpoint is set.
  349. pub.advisor_configured =
  350. Services.AdvisorLlmEndpoint.from_environment() != null;
  351. // Web Push bell state (plan 11 task E; per-browser since
  352. // the user-global flag lied to second browsers): the VAPID
  353. // key the browser needs, whether this user subscribed
  354. // anywhere (convenience), and this user's endpoint
  355. // FINGERPRINTS — the client compares its own subscription's
  356. // fingerprint against the list, so each browser shows its
  357. // own truth.
  358. pub.push_vapid_key = PushService.vapid_public_key;
  359. // Not a DashboardPublic property: GObjectMapping cannot
  360. // serialise array-shaped values, so the fingerprint list
  361. // rides the props dictionary like every other list here.
  362. string[] push_fingerprints = new string[0];
  363. if (push != null && viewer_id > 0) {
  364. pub.push_subscribed = yield ((!)push).user_subscribed(db, viewer_id);
  365. push_fingerprints = yield ((!)push)
  366. .user_endpoint_fingerprints(db, viewer_id);
  367. }
  368. var activity = new Vector<DashboardActivityView>();
  369. foreach (var item in yield timeline.recent_window()) {
  370. activity.add(new DashboardActivityView() {
  371. kind = item.kind,
  372. at_epoch = item.at_epoch,
  373. when_display = format_stamp(new DateTime.from_unix_local(item.at_epoch)),
  374. task_id = item.task_id,
  375. task_title = item.task_title,
  376. goal_id = item.goal_id,
  377. goal_title = item.goal_title,
  378. text = item.text
  379. });
  380. }
  381. var props = (PropertyDictionary) GObjectMapping.to_properties(pub);
  382. props["saddles"] = StateJson.list<DashboardSaddleView>(saddle_rows.to_immutable_buffer());
  383. props["push_endpoints"] = StateJson.strings(push_fingerprints);
  384. props["activity"] = StateJson.list<DashboardActivityView>(activity.to_immutable_buffer());
  385. props["active_tasks"] = StateJson.list<DashboardActiveView>(active.to_immutable_buffer());
  386. props["pinned"] = StateJson.list<DashboardBlockView>(pinned_sorted.to_immutable_buffer());
  387. // The scratchpad (goal 8 task 3): every note with its
  388. // per-row sealed actions; promoted notes link their goal
  389. // and never carry a promote action again.
  390. var note_rows = new Vector<DashboardNoteView>();
  391. foreach (var note in yield notes.list_notes()) {
  392. var view = new DashboardNoteView() {
  393. id = note.id,
  394. body = note.body,
  395. done = note.done,
  396. created_display = format_stamp(note.created_at),
  397. toggle = ((!)actions).author_private<ToggleNoteAction, NoteActionPrivate>(
  398. new NoteActionPrivate() { note_id = note.id }),
  399. delete = ((!)actions).author_private<DeleteNoteAction, NoteActionPrivate>(
  400. new NoteActionPrivate() { note_id = note.id })
  401. };
  402. if (note.done_at != null) {
  403. view.done_display = format_stamp(note.done_at);
  404. }
  405. if (note.goal_id > 0) {
  406. view.goal_id = note.goal_id;
  407. var goal_row = yield db.query<Goal>()
  408. .where(expr("id == $0", elem<int64?>(note.goal_id)))
  409. .first_async();
  410. if (goal_row != null) {
  411. view.goal_title = ((!)goal_row).title;
  412. }
  413. } else if (!note.done) {
  414. view.promote = ((!)actions).author_private<PromoteNoteAction, NoteActionPrivate>(
  415. new NoteActionPrivate() { note_id = note.id });
  416. }
  417. note_rows.add(view);
  418. }
  419. props["notes"] = StateJson.list<DashboardNoteView>(note_rows.to_immutable_buffer());
  420. // The five newest discoveries (goal 24): a one-glance slice
  421. // of the fleet's knowledge base; the Discoveries page owns
  422. // the full searchable listing.
  423. var discovery_rows = new Vector<DashboardDiscoveryView>();
  424. foreach (var discovery in yield db.query<Discovery>()
  425. .order_by_desc(expr("id"))
  426. .limit(5)
  427. .materialise_async()) {
  428. discovery_rows.add(new DashboardDiscoveryView() {
  429. body = discovery.body
  430. });
  431. }
  432. props["discoveries"] = StateJson.list<DashboardDiscoveryView>(
  433. discovery_rows.to_immutable_buffer());
  434. // The promote form's project options (goal 8 task 3):
  435. // every project, oldest first — a stable select order.
  436. var project_options = new Vector<DashboardProjectOptionView>();
  437. foreach (var project in yield db.query<Project>()
  438. .order_by(expr("id"))
  439. .materialise_async()) {
  440. project_options.add(new DashboardProjectOptionView() {
  441. id = project.id,
  442. name = project.name
  443. });
  444. }
  445. props["projects"] = StateJson.list<DashboardProjectOptionView>(
  446. project_options.to_immutable_buffer());
  447. return state_service.new_slot(Scope.PAGE, new Statum.State() {
  448. type_name = "dashboard",
  449. public_data = props,
  450. private_data = new PropertyDictionary()
  451. });
  452. }
  453. /**
  454. * True when the task has at least one block and every one of
  455. * them carries an answer (goal 2 QoL): the human already
  456. * acted, the dispatcher's resume is the only thing owed. A
  457. * task with no blocks at all is NOT answered-waiting — the
  458. * counters leave such rows in blocked_count untouched.
  459. */
  460. private static async bool blocks_all_answered(TaskService tasks, int64 task_id) throws GLib.Error {
  461. bool any = false;
  462. foreach (var block in yield tasks.list_blocks(task_id)) {
  463. any = true;
  464. if (block.answer == null) {
  465. return false;
  466. }
  467. }
  468. return any;
  469. }
  470. }
  471. /**
  472. * Entrypoint for /: the dashboard — queue summary, the pinned OPEN
  473. * blocking items as link-through cards (newest first), active tasks
  474. * with their latest progress, saddle cards, and the cross-task
  475. * activity timeline (last ~50 events, newest first). The page
  476. * subscribes to the global pulse and re-runs its sealed refresh
  477. * action whenever task or saddle state changes anywhere in the app.
  478. */
  479. public class HomeEntrypoint : StatumEntrypoint {
  480. private TaskService task_service = Inversion.inject<TaskService>();
  481. private SaddleService saddle_service = Inversion.inject<SaddleService>();
  482. private TimelineService timeline_service = Inversion.inject<TimelineService>();
  483. private NoteService note_service = Inversion.inject<NoteService>();
  484. private InvercargillSql.Orm.OrmSession db = Inversion.inject<InvercargillSql.Orm.OrmSession>();
  485. private PushService push_service = Inversion.inject<PushService>();
  486. private UserService users = Inversion.inject<UserService>();
  487. public override async DirectiveBuilder handle() throws GLib.Error {
  488. var guard = yield SpryAuth.require_login(directives(), request, users);
  489. if (guard != null) {
  490. return (!)guard;
  491. }
  492. var me = SpryAuth.current(request);
  493. var state = yield DashboardState.build(state_service, task_service,
  494. saddle_service, timeline_service, db, note_service, action_registry,
  495. push_service, me != null ? ((!)me).user_id : 0);
  496. return directives().set(state).subscribe_global(StatePulse.SLOT_TYPE);
  497. }
  498. }
  499. }