using Invercargill; using Invercargill.DataStructures; using Invercargill.Expressions; using Spry; using Spry.Authentication; using Statum; using ClankerSaddle.Data; using ClankerSaddle.Services; namespace ClankerSaddle { /** A saddle card on the dashboard. */ public class DashboardSaddleView : Object { public int64 id { get; set; } public string name { get; set; default = ""; } public string status { get; set; default = SADDLE_OFFLINE; } public string host { get; set; default = ""; } public int64 current_task_id { get; set; } public string current_task_title { get; set; default = ""; } /** * Set when the saddle's current task is a goal agent's run: * the card then links the GOAL (runs are internal — never a * task destination at a glance). */ public int64 current_goal_id { get; set; } public string current_goal_title { get; set; default = ""; } } /** One entry in the dashboard's cross-task activity timeline. */ public class DashboardActivityView : Object { public string kind { get; set; default = ""; } public int64 at_epoch { get; set; } public string when_display { get; set; default = ""; } public int64 task_id { get; set; } public string task_title { get; set; default = ""; } /** Plan 12: set on goal events — the row links the goal page. */ public int64 goal_id { get; set; } public string goal_title { get; set; default = ""; } public string text { get; set; default = ""; } } /** An active task with its latest progress line. */ public class DashboardActiveView : Object { public int64 id { get; set; } public string title { get; set; default = ""; } public string status { get; set; default = ""; } public string latest_progress { get; set; default = ""; } public string progress_display { get; set; default = ""; } public string task_branch { get; set; default = ""; } } /** * A pinned OPEN blocking item (plan 10 phase 3; plan 12 unified; * plan 15 C1 single-row): an unanswered question, RFC, review or * the goal agent's block (question/RFC, plan submission, * completion report — all rows of the goal-run task) rendered as * a link-through card. Goal items carry `item_type` "goal" and * link the goal page; task items carry "task" and link the task * page where the answer form lives. No inline answer forms on the * dashboard (settled). */ public class DashboardBlockView : Object { /** "task" or "goal" — the pile interleaves both. */ public string item_type { get; set; default = "task"; } public int64 id { get; set; } public int64 task_id { get; set; } public string task_title { get; set; default = ""; } /** Goal items only: the goal the block belongs to. */ public int64 goal_id { get; set; } public string goal_title { get; set; default = ""; } public string block_type { get; set; default = "question"; } public string question { get; set; default = ""; } public string created_display { get; set; default = ""; } /** The created stamp's epoch — the unified newest-first key. */ public int64 at_epoch { get; set; } } /** A project option in the note promote form's select. */ public class DashboardProjectOptionView : Object { public int64 id { get; set; } public string name { get; set; default = ""; } } /** * A scratchpad note row on the dashboard (goal 8 task 3): the * body, its done state, and the per-row actions. An unpromoted, * undone note carries the promote action; a promoted note carries * its goal link instead (and never a second promote). */ public class DashboardNoteView : Object { public int64 id { get; set; } public string body { get; set; default = ""; } public bool done { get; set; } public string done_display { get; set; default = ""; } public string created_display { get; set; default = ""; } /** The goal this note promoted into (0 = not promoted). */ public int64 goal_id { get; set; } public string goal_title { get; set; default = ""; } public Statum.Model.ActionDto? toggle { get; set; } public Statum.Model.ActionDto? delete { get; set; } public Statum.Model.ActionDto? promote { get; set; } } /** Public data of the dashboard's `dashboard` slot. */ public class DashboardPublic : Object { public int64 draft_count { get; set; } /** * Waiting-for-attention work (goal 2 QoL): everything the * system owes a dispatch or resume to — ready-to-dispatch * queued tasks (the ready_count subset) + parked work awaiting * resume (suspended tasks, suspended goal-agent runs included) * + tasks whose raised blocks are all answered and now wait * for a saddle to pick the resume up (these leave * blocked_count, which stays human-answerable rows only). * Raw queued rows gated on an unfinished auto-enqueue * predecessor are deliberately OUT — sequenced future work, * the predecessor itself is already counted. */ public int64 queued_count { get; set; } public int64 ready_count { get; set; } public int64 active_count { get; set; } public int64 blocked_count { get; set; } public int64 done_count { get; set; } public int64 failed_count { get; set; } public int64 idle_saddle_count { get; set; } public Statum.Model.ActionDto? refresh { get; set; } /** The VAPID public key the browser subscribes with ("" when push is unavailable). */ public string push_vapid_key { get; set; default = ""; } /** The signed-in user holds at least one push subscription. */ public bool push_subscribed { get; set; } public Statum.Model.ActionDto? push_subscribe { get; set; } public Statum.Model.ActionDto? push_unsubscribe { get; set; } /** Queues a REAL test push to this user (the bell's probe). */ public Statum.Model.ActionDto? push_test { get; set; } /** * Adds a scratchpad note (goal 8 task 3) — the Notes card's * add form. */ public Statum.Model.ActionDto? add_note { get; set; } } /** * Builds the `dashboard` slot state shared by the home entrypoint and * the {@link RefreshDashboardAction} pulse refresh, so both hydrate * identical state: queue counters, saddle cards, the pinned OPEN * blocking items as link-through cards (newest first — plan 10 * phase 3; goal items arrive with the run task's own blocks, * plan 15 C1), active tasks with their latest progress, and the * cross-task activity timeline ({@link TimelineService}: last ~50 * events, newest first). */ public class DashboardState : Object { /** * Loads the dashboard aggregate and shapes its PAGE slot. The * `db` session comes from the caller (entrypoint or action scope). */ public static async Statum.Slot build(StateService state_service, TaskService tasks, SaddleService saddles, TimelineService timeline, InvercargillSql.Orm.OrmSession db, NoteService notes, ActionRegistry? actions = null, PushService? push = null, int64 viewer_id = 0) throws GLib.Error { var pub = new DashboardPublic(); var titles = new Dictionary(); var all_tasks = yield tasks.list_tasks(null, null); // The ready-to-dispatch subset of the queued rows (see the // queued_count docblock), keyed by id so the status loop can // tell a dispatchable queued task from one still gated on // its auto-enqueue predecessor. var ready_ids = new HashSet(); int64 ready_count = 0; foreach (var ready in yield tasks.get_ready_tasks()) { ready_ids.add(ready.id.to_string()); if (ready.kind != TASK_KIND_GOAL_RUN) { ready_count++; } } pub.ready_count = ready_count; foreach (var task in all_tasks) { titles.set(task.id.to_string(), task.title); // Goal-agent runs are internal tasks — they never count // against the human-facing queue summary (the goal page // owns their visibility) EXCEPT parked: a suspended run // is goal work the system owes a resume, so it joins // queued_count (goal 2 QoL). if (task.kind == TASK_KIND_GOAL_RUN && task.status != STATUS_SUSPENDED) { continue; } switch (task.status) { case STATUS_DRAFT: pub.draft_count++; break; case STATUS_QUEUED: // Ready rows are the queued metric's core; // predecessor-gated rows are sequenced future // work the counters leave out (docblock above). if (ready_ids.has(task.id.to_string())) { pub.queued_count++; } break; case STATUS_ASSIGNED: case STATUS_WORKING: pub.active_count++; break; case STATUS_SUSPENDED: // Parked awaiting resume (goal 2 QoL): a // suspended task waits on the system, not on a // human — it reads as waiting, not blocked. pub.queued_count++; break; case STATUS_BLOCKED: case STATUS_REVIEW_REQUESTED: // Goal 2 QoL: answered blocks mean the human // already acted — the task now waits for a // saddle to resume it, so it joins the queued // metric and leaves blocked_count (which stays // genuinely-needs-a-human rows). if (yield blocks_all_answered(tasks, task.id)) { pub.queued_count++; } else { pub.blocked_count++; } break; case STATUS_DONE: pub.done_count++; break; case STATUS_FAILED: pub.failed_count++; break; default: break; } } var saddle_rows = new Vector(); foreach (var saddle in yield saddles.list_saddles()) { // Plan 16 item 23: the card reads the DERIVED view — // busy iff a running session exists, else the row's // stored OFFLINE probe state. var work = yield saddles.current_work_view(saddle); string status = SaddleService.derived_status(saddle, work); if (status == SADDLE_IDLE) { pub.idle_saddle_count++; } var view = new DashboardSaddleView() { id = saddle.id, name = saddle.name, status = status, host = saddle.host, current_task_id = work != null ? ((!)work).task_id : 0 }; if (work != null) { view.current_task_title = ((!)work).task_title; if (((!)work).goal_id > 0) { view.current_goal_id = ((!)work).goal_id; view.current_goal_title = ((!)work).goal_title; } } saddle_rows.add(view); } var active = new Vector(); var pinned = new Vector(); foreach (var task in yield tasks.list_tasks(null, null)) { // Goal-agent runs are internal — never an "active // task" row (the goal page shows the agent's // activity). Their BLOCKS still pin below (plan 15 // C1): the run task's rows are the goal's pile cards. bool internal_run = task.kind == TASK_KIND_GOAL_RUN; if (!internal_run && (task.status == STATUS_ASSIGNED || task.status == STATUS_WORKING || task.status == STATUS_BLOCKED || task.status == STATUS_REVIEW_REQUESTED)) { var row = new DashboardActiveView() { id = task.id, title = task.title, status = task.status, task_branch = task.task_branch ?? "" }; var progress = yield tasks.list_progress(task.id); if (progress.length > 0) { row.latest_progress = progress.first().summary; row.progress_display = format_stamp(progress.first().created_at); } active.add(row); } // Every unanswered block pins as a link-through card — // questions, RFCs and reviews alike. Plan 15 C1: the // goal agent's blocks ARE the run task's blocks (one // row each) — they render as goal items (goal badge, // goal link) straight from this same loop; there is no // goal-side pass and no mirror to consult. int64 block_goal_id = 0; string block_goal_title = ""; if (internal_run && task.goal_id > 0) { block_goal_id = task.goal_id; var goal_row = yield db.query() .where(expr("id == $0", elem(task.goal_id))) .first_async(); block_goal_title = goal_row != null ? ((!)goal_row).title : ""; } foreach (var block in yield tasks.list_blocks(task.id)) { if (block.answer != null) { continue; } var view = new DashboardBlockView() { item_type = block_goal_id > 0 ? "goal" : "task", id = block.id, task_id = task.id, task_title = task.title, goal_id = block_goal_id, goal_title = block_goal_title, block_type = block.block_type, question = block.question, created_display = format_stamp(block.created_at) }; if (block.created_at != null) { view.at_epoch = ((!)block.created_at).to_unix(); } pinned.add(view); } } // Newest first (plan 10 phase 3): the most recent question, // RFC, review or goal block leads the unified pile. var pinned_sorted = pinned.sort((a, b) => { if (a.at_epoch != b.at_epoch) { return a.at_epoch > b.at_epoch ? -1 : 1; } return a.id > b.id ? -1 : 1; }); if (actions != null) { pub.refresh = ((!)actions).author("GET"); pub.push_subscribe = ((!)actions).author(); pub.push_unsubscribe = ((!)actions).author(); pub.push_test = ((!)actions).author(); pub.add_note = ((!)actions).author(); } // Web Push bell state (plan 11 task E; per-browser since // the user-global flag lied to second browsers): the VAPID // key the browser needs, whether this user subscribed // anywhere (convenience), and this user's endpoint // FINGERPRINTS — the client compares its own subscription's // fingerprint against the list, so each browser shows its // own truth. pub.push_vapid_key = PushService.vapid_public_key; // Not a DashboardPublic property: GObjectMapping cannot // serialise array-shaped values, so the fingerprint list // rides the props dictionary like every other list here. string[] push_fingerprints = new string[0]; if (push != null && viewer_id > 0) { pub.push_subscribed = yield ((!)push).user_subscribed(db, viewer_id); push_fingerprints = yield ((!)push) .user_endpoint_fingerprints(db, viewer_id); } var activity = new Vector(); foreach (var item in yield timeline.recent_window()) { activity.add(new DashboardActivityView() { kind = item.kind, at_epoch = item.at_epoch, when_display = format_stamp(new DateTime.from_unix_local(item.at_epoch)), task_id = item.task_id, task_title = item.task_title, goal_id = item.goal_id, goal_title = item.goal_title, text = item.text }); } var props = (PropertyDictionary) GObjectMapping.to_properties(pub); props["saddles"] = StateJson.list(saddle_rows.to_immutable_buffer()); props["push_endpoints"] = StateJson.strings(push_fingerprints); props["activity"] = StateJson.list(activity.to_immutable_buffer()); props["active_tasks"] = StateJson.list(active.to_immutable_buffer()); props["pinned"] = StateJson.list(pinned_sorted.to_immutable_buffer()); // The scratchpad (goal 8 task 3): every note with its // per-row sealed actions; promoted notes link their goal // and never carry a promote action again. var note_rows = new Vector(); foreach (var note in yield notes.list_notes()) { var view = new DashboardNoteView() { id = note.id, body = note.body, done = note.done, created_display = format_stamp(note.created_at), toggle = ((!)actions).author_private( new NoteActionPrivate() { note_id = note.id }), delete = ((!)actions).author_private( new NoteActionPrivate() { note_id = note.id }) }; if (note.done_at != null) { view.done_display = format_stamp(note.done_at); } if (note.goal_id > 0) { view.goal_id = note.goal_id; var goal_row = yield db.query() .where(expr("id == $0", elem(note.goal_id))) .first_async(); if (goal_row != null) { view.goal_title = ((!)goal_row).title; } } else if (!note.done) { view.promote = ((!)actions).author_private( new NoteActionPrivate() { note_id = note.id }); } note_rows.add(view); } props["notes"] = StateJson.list(note_rows.to_immutable_buffer()); // The promote form's project options (goal 8 task 3): // every project, oldest first — a stable select order. var project_options = new Vector(); foreach (var project in yield db.query() .order_by(expr("id")) .materialise_async()) { project_options.add(new DashboardProjectOptionView() { id = project.id, name = project.name }); } props["projects"] = StateJson.list( project_options.to_immutable_buffer()); return state_service.new_slot(Scope.PAGE, new Statum.State() { type_name = "dashboard", public_data = props, private_data = new PropertyDictionary() }); } /** * True when the task has at least one block and every one of * them carries an answer (goal 2 QoL): the human already * acted, the dispatcher's resume is the only thing owed. A * task with no blocks at all is NOT answered-waiting — the * counters leave such rows in blocked_count untouched. */ private static async bool blocks_all_answered(TaskService tasks, int64 task_id) throws GLib.Error { bool any = false; foreach (var block in yield tasks.list_blocks(task_id)) { any = true; if (block.answer == null) { return false; } } return any; } } /** * Entrypoint for /: the dashboard — queue summary, the pinned OPEN * blocking items as link-through cards (newest first), active tasks * with their latest progress, saddle cards, and the cross-task * activity timeline (last ~50 events, newest first). The page * subscribes to the global pulse and re-runs its sealed refresh * action whenever task or saddle state changes anywhere in the app. */ public class HomeEntrypoint : StatumEntrypoint { private TaskService task_service = Inversion.inject(); private SaddleService saddle_service = Inversion.inject(); private TimelineService timeline_service = Inversion.inject(); private NoteService note_service = Inversion.inject(); private InvercargillSql.Orm.OrmSession db = Inversion.inject(); private PushService push_service = Inversion.inject(); private UserService users = Inversion.inject(); public override async DirectiveBuilder handle() throws GLib.Error { var guard = yield SpryAuth.require_login(directives(), request, users); if (guard != null) { return (!)guard; } var me = SpryAuth.current(request); var state = yield DashboardState.build(state_service, task_service, saddle_service, timeline_service, db, note_service, action_registry, push_service, me != null ? ((!)me).user_id : 0); return directives().set(state).subscribe_global(StatePulse.SLOT_TYPE); } } }