askrobots / dbbasic-object-server
Public
Runs live, versioned Python application objects on one VM, with a suite of apps: projects, notes, tasks, files and more.
danq9
signup: the person chooses the password and name on the confirm page
83c7aa6
2 weeks, 5 days ago
History
home.py · 10.7 KB · 257 lines
| 1 | """The front door: the app switchboard, folded over the nav registry. |
| 2 | |
| 3 | Reference implementation for the design system — no inline CSS of its |
| 4 | own; it links to the shared /style stylesheet (the site_style object) and |
| 5 | uses its shared classes. Retheme the whole instance by switching the |
| 6 | theme on /style; this page follows automatically. |
| 7 | |
| 8 | This page used to BE a registry: a hardcoded `_APPS` tuple, one of three |
| 9 | hand-maintained lists of the same apps (the others being site_nav's JS |
| 10 | array and its search-hit URL map), which had drifted to 21 entries |
| 11 | against the switcher's 25 and named none of the newest apps. It is now a |
| 12 | fold over `action_nav_entries`, which reads the `nav_entries` collection |
| 13 | that every package writes on install. Shipping an app puts it on this |
| 14 | page; nobody edits this file to add a door. |
| 15 | |
| 16 | `_APPS` survives underneath as the fallback, deliberately. A fresh |
| 17 | install renders this page before app-nav's own entries have landed, and a |
| 18 | blank switchboard is a worse first impression than a slightly stale one. |
| 19 | The fallback is what the box looked like when the registry was invented; |
| 20 | it is not maintained, and the comment on it says so. |
| 21 | |
| 22 | Above the grid sits the NEEDS YOU band: every queue an installed package |
| 23 | says is waiting for a person, loudest first, each one a link straight |
| 24 | through to the list it counts. That is the only question a home screen is |
| 25 | actually asked -- does anything need me? -- and this server can answer it |
| 26 | because it is built out of gates and derived states that produce those |
| 27 | queues constantly and have always thrown them away. |
| 28 | |
| 29 | **When everything is zero the band is absent entirely.** Not "0 |
| 30 | pending", not an empty panel with a heading: gone. A board that says zero |
| 31 | every day trains people to stop reading it, and once they have stopped |
| 32 | they do not start again on the day it says three. A page that is empty |
| 33 | when nothing needs them gets read every time, and "nothing needs you" is |
| 34 | a complete and welcome answer that a blank space gives better than any |
| 35 | sentence would. |
| 36 | |
| 37 | The counts are a rollup (`attention_counts`, written by the daemon), not |
| 38 | a live fold. Folding a dozen collections on every render is how a home |
| 39 | page becomes the slowest page -- and worse: this box went to 675MB |
| 40 | resident and swapped because something folded a big collection on a |
| 41 | timer. The page's cost is one small read no matter how many apps declare |
| 42 | a queue, and the age of the numbers is printed rather than pretended |
| 43 | away. |
| 44 | """ |
| 45 | |
| 46 | from datetime import datetime, timezone |
| 47 | |
| 48 | import object_execution |
| 49 | import python_object_runtime |
| 50 | |
| 51 | # Fallback only -- see the module docstring. Shown when the nav registry |
| 52 | # is empty (a fresh box, or app-nav installed before anything else), and |
| 53 | # deliberately NOT kept up to date: the registry is the list now, and a |
| 54 | # second maintained list is the exact failure this page was rebuilt to |
| 55 | # end. Grouped like the registry so the two render identically. |
| 56 | _APPS = [ |
| 57 | ("Work", "/shell", "Shell", "Talk to everything; AI with your tools"), |
| 58 | ("Work", "/notes", "Notes", "Quick capture, projects, public sharing"), |
| 59 | ("Work", "/tasks", "Tasks", "Lifecycle with enforced transitions"), |
| 60 | ("Work", "/projects", "Projects", "The hub everything links to"), |
| 61 | ("Work", "/contacts", "Contacts", "People, organizations, interactions"), |
| 62 | ("Work", "/links", "Links", "Saved bookmarks with tags"), |
| 63 | ("Work", "/calendar", "Calendar", "Events, meetings, and gatherings"), |
| 64 | ("Work", "/files", "Files", "Upload, share, and download"), |
| 65 | ("Work", "/templates", "Templates", "Structured data templates"), |
| 66 | ("Work", "/inbox", "Inbox", "Your private mailbox"), |
| 67 | ("Work", "/activity", "Activity", "Everything you did, newest first"), |
| 68 | ("Publishing", "/articles", "Articles", "Published writing with permalinks"), |
| 69 | ("Publishing", "/forum", "Forum", "Discussion, threaded replies"), |
| 70 | ("Publishing", "/profile/edit", "Profile", "Your public creator profile"), |
| 71 | ("Money", "/invoices", "Invoices", "Bill customers; integer-cent totals"), |
| 72 | ("Money", "/journals", "Finance", "Double-entry books and trial balance"), |
| 73 | ("Commerce", "/products", "Products", "Things you sell; prices in cents"), |
| 74 | ("Commerce", "/orders", "Orders", "Sales and purchase orders"), |
| 75 | ("Warehouse", "/stock", "Stock", "On-hand levels, derived from moves"), |
| 76 | ("System", "/dashboard", "Dashboard", "Live server health and activity"), |
| 77 | ("System", "/appearance", "Appearance", "Theme and design system"), |
| 78 | ] |
| 79 | |
| 80 | |
| 81 | def _escape(value): |
| 82 | return ( |
| 83 | str(value if value is not None else "") |
| 84 | .replace("&", "&").replace("<", "<").replace(">", ">") |
| 85 | .replace('"', """) |
| 86 | ) |
| 87 | |
| 88 | |
| 89 | # Severity, in the design system's own vocabulary. `warning` is work |
| 90 | # that is late and `danger` is something broken -- the stylesheet already |
| 91 | # owns what those colours mean, so this maps onto it rather than |
| 92 | # inventing a third palette nobody else uses. |
| 93 | _SEVERITY_CLASS = {"urgent": "badge danger", "warning": "badge warning", |
| 94 | "normal": "badge accent"} |
| 95 | |
| 96 | |
| 97 | def _badge(entry): |
| 98 | """A tile's count, or nothing. |
| 99 | |
| 100 | `action_nav_entries` only attaches `count` when it is non-zero, so the |
| 101 | absence of the key IS the empty queue -- this never has to decide |
| 102 | whether a zero is worth rendering, because a zero never arrives. |
| 103 | """ |
| 104 | count = entry.get("count") |
| 105 | if not count: |
| 106 | return "" |
| 107 | css = _SEVERITY_CLASS.get(str(entry.get("severity") or ""), "badge accent") |
| 108 | return f' <span class="{css}">{_escape(count)}</span>' |
| 109 | |
| 110 | |
| 111 | def _call(object_id, payload): |
| 112 | """Run a sibling object in-process. |
| 113 | |
| 114 | The page owns no visibility rules of its own: it asks the object that |
| 115 | does. Which tier of door this caller may see is decided once, in |
| 116 | action_nav_entries, and never restated here. |
| 117 | """ |
| 118 | runtime = python_object_runtime.PythonObjectRuntime() |
| 119 | result = object_execution.execute_object( |
| 120 | runtime, |
| 121 | object_execution.ObjectExecutionRequest( |
| 122 | object_id, method="POST", payload=payload)) |
| 123 | return result.result if result.ok else {} |
| 124 | |
| 125 | |
| 126 | def _fallback_groups(): |
| 127 | groups = [] |
| 128 | for group, path, label, blurb in _APPS: |
| 129 | if not groups or groups[-1]["group"] != group: |
| 130 | groups.append({"group": group, "entries": []}) |
| 131 | groups[-1]["entries"].append({"label": label, "path": path, "blurb": blurb}) |
| 132 | return groups |
| 133 | |
| 134 | |
| 135 | def _menu(request): |
| 136 | """The registry's answer: the doors, and what needs a human. |
| 137 | |
| 138 | One call for both, because both are folds over the same visibility |
| 139 | rule and asking twice would be asking the same question two ways. |
| 140 | """ |
| 141 | answer = _call("action_nav_entries", {"_identity": request.get("_identity") or {}}) |
| 142 | if not isinstance(answer, dict): |
| 143 | answer = {} |
| 144 | groups = answer.get("groups") |
| 145 | attention = answer.get("attention") or [] |
| 146 | if groups: |
| 147 | return groups, attention, False |
| 148 | return _fallback_groups(), attention, True |
| 149 | |
| 150 | |
| 151 | def _age(stamp): |
| 152 | """"as of 6 minutes ago", or "" when the stamp says nothing. |
| 153 | |
| 154 | The staleness is stated rather than hidden. A number a page implies is |
| 155 | live, and is not, is worse than the same number honestly dated. |
| 156 | """ |
| 157 | text = str(stamp or "").strip().replace("Z", "+00:00") |
| 158 | if not text: |
| 159 | return "" |
| 160 | try: |
| 161 | computed = datetime.fromisoformat(text) |
| 162 | except ValueError: |
| 163 | return "" |
| 164 | if computed.tzinfo is None: |
| 165 | computed = computed.replace(tzinfo=timezone.utc) |
| 166 | minutes = int((datetime.now(timezone.utc) - computed).total_seconds() // 60) |
| 167 | if minutes < 1: |
| 168 | return "as of just now" |
| 169 | if minutes < 60: |
| 170 | return f"as of {minutes} minute{'s' if minutes != 1 else ''} ago" |
| 171 | hours = minutes // 60 |
| 172 | if hours < 48: |
| 173 | return f"as of {hours} hour{'s' if hours != 1 else ''} ago" |
| 174 | return f"as of {hours // 24} days ago" |
| 175 | |
| 176 | |
| 177 | def _attention_band(attention): |
| 178 | """The band, or nothing at all. |
| 179 | |
| 180 | Returning the empty string when there is nothing waiting is the whole |
| 181 | design: no heading, no panel, no zero. The caller concatenates, so |
| 182 | "absent" costs exactly one branch and cannot decay into "present but |
| 183 | empty" the way a component with an empty state does. |
| 184 | """ |
| 185 | if not attention: |
| 186 | return "" |
| 187 | rows = "\n".join( |
| 188 | f'<a class="tile" href="{_escape(row.get("path"))}">' |
| 189 | f'<div class="name">{_escape(row.get("label"))}{_badge(row)}</div>' |
| 190 | f'<div class="desc">{_escape(row.get("detail"))}</div></a>' |
| 191 | for row in attention |
| 192 | ) |
| 193 | freshest = max((str(row.get("computed_at") or "") for row in attention), |
| 194 | default="") |
| 195 | age = _age(freshest) |
| 196 | stamp = f' <span class="muted">{_escape(age)}</span>' if age else "" |
| 197 | return (f"<h2>Needs you{stamp}</h2>\n<div class=\"grid\">\n{rows}\n</div>") |
| 198 | |
| 199 | |
| 200 | def GET(request): |
| 201 | identity = request.get("_identity", {}) |
| 202 | user_id = identity.get("user_id") |
| 203 | |
| 204 | groups, attention, fell_back = _menu(request) |
| 205 | _logger.info( |
| 206 | "site_home served", |
| 207 | user_id=user_id or "anonymous", |
| 208 | groups=len(groups), |
| 209 | attention=len(attention), |
| 210 | source="fallback" if fell_back else "nav_entries", |
| 211 | ) |
| 212 | |
| 213 | who = ( |
| 214 | f"signed in as <strong>{_escape(user_id)}</strong>" |
| 215 | if user_id |
| 216 | else '<a href="/login">sign in</a>' |
| 217 | ) |
| 218 | # The same number twice, deliberately: once in the band, where it is |
| 219 | # the thing you came for, and once as a badge on the tile, where it |
| 220 | # catches the person who was on their way somewhere else. A tile with |
| 221 | # no queue gets no badge -- not a zero. |
| 222 | sections = "\n".join( |
| 223 | f'<h2>{_escape(group["group"])}</h2>\n<div class="grid">\n' |
| 224 | + "\n".join( |
| 225 | f'<a class="tile" href="{_escape(entry["path"])}">' |
| 226 | f'<div class="name">{_escape(entry["label"])}{_badge(entry)}</div>' |
| 227 | f'<div class="desc">{_escape(entry.get("blurb"))}</div></a>' |
| 228 | for entry in group["entries"] |
| 229 | ) |
| 230 | + "\n</div>" |
| 231 | for group in groups |
| 232 | ) |
| 233 | band = _attention_band(attention) |
| 234 | html = f"""<!doctype html> |
| 235 | <html lang="en"> |
| 236 | <head> |
| 237 | <meta charset="utf-8"> |
| 238 | <meta name="viewport" content="width=device-width, initial-scale=1"> |
| 239 | <title>DBBASIC Object Server</title> |
| 240 | <link rel="stylesheet" href="/style"> |
| 241 | </head> |
| 242 | <body> |
| 243 | <div class="wrap"> |
| 244 | <header class="app"><h1>DBBASIC Object Server</h1><div class="who">{who}</div></header> |
| 245 | <p class="muted">Apps are packages: a schema, permission rules, and one page object each. |
| 246 | Everything here is served by a single small server, live-editable, permission-checked per record. |
| 247 | This page is a fold over the nav registry — installing an app puts it here.</p> |
| 248 | {band} |
| 249 | {sections} |
| 250 | <footer class="app">Open source: |
| 251 | <a href="https://github.com/askrobots/dbbasic-object-server">dbbasic-object-server</a> |
| 252 | · operator console: <a href="https://github.com/askrobots/dbbasic-scroll">dbbasic-scroll</a></footer> |
| 253 | </div> |
| 254 | <script src="/nav"></script> |
| 255 | </body> |
| 256 | </html>""" |
| 257 | return {"content_type": "text/html; charset=utf-8", "body": html} |