From 7d31cca394fc8e4850ca9f7e994c230a4c6617a3 Mon Sep 17 00:00:00 2001 From: Wolf Date: Fri, 25 Sep 2026 21:29:06 +0200 Subject: [PATCH] Two tabs and a cog: settings shell, one ranking, a script per page, the phone frame The top bar is Roles and Applications plus health's cog. Behind the cog, /settings/{ranking,searches,companies,pulls,messages,account} share one row of sub-tabs, an underlined row on a desktop and pills on a phone. The old paths answer 301 with their query string. Ranking edits the first enabled agent, or creates one, with the intent, the weights and the gates under Advanced. The order menu on Roles reads Newest and Best match with one enabled agent, and names them with several. config.yaml keeps the Copenhagen starter; the other two are commented examples in config.example.yaml. roles.js is split into roles.js, applications.js, ranking.js and companies.js; count, cell, debounce, the company list and the affinity control live once in app.js. app.css gets the phone frame after health and newsdesk: one-row bar, edge-to-edge panels, 44px targets and 16px fields on a coarse pointer, hover only where there is one, safe areas. The app is installable from a manifest and roledesk-coloured icons. Every lede touched is written for the person using the app. Co-Authored-By: Claude Opus 5.5 (1M context) --- app/jobs/cascade.py | 6 +- app/jobs/pull.py | 4 +- app/jobs/sources.py | 2 +- app/static/app.css | 133 ++++++- app/static/app.js | 92 ++++- app/static/apple-touch-icon.png | Bin 0 -> 1771 bytes app/static/applications.js | 76 ++++ app/static/companies.js | 50 +++ app/static/icon-192.png | Bin 0 -> 1523 bytes app/static/icon-512.png | Bin 0 -> 4386 bytes app/static/icon.svg | 25 ++ app/static/jobs.js | 2 +- app/static/manifest.json | 17 + app/static/ranking.js | 134 +++++++ app/static/roles.js | 368 +----------------- app/static/sources.js | 30 +- app/templates/agents.html | 37 -- app/templates/applications.html | 4 +- app/templates/base.html | 35 +- app/templates/error.html | 2 +- app/templates/schedules.html | 15 - app/templates/settings/_tabs.html | 8 + app/templates/{ => settings}/account.html | 7 +- app/templates/{ => settings}/companies.html | 8 +- app/templates/{ => settings}/messages.html | 5 +- .../{jobs.html => settings/pulls.html} | 21 +- app/templates/settings/ranking.html | 39 ++ .../{sources.html => settings/searches.html} | 10 +- app/web/__init__.py | 7 +- app/web/pages.py | 120 ++++-- config.example.yaml | 22 ++ config.yaml | 26 +- tests/test_score.py | 14 +- tests/test_web.py | 94 +++-- 34 files changed, 848 insertions(+), 565 deletions(-) create mode 100644 app/static/apple-touch-icon.png create mode 100644 app/static/applications.js create mode 100644 app/static/companies.js create mode 100644 app/static/icon-192.png create mode 100644 app/static/icon-512.png create mode 100644 app/static/icon.svg create mode 100644 app/static/manifest.json create mode 100644 app/static/ranking.js delete mode 100644 app/templates/agents.html delete mode 100644 app/templates/schedules.html create mode 100644 app/templates/settings/_tabs.html rename app/templates/{ => settings}/account.html (59%) rename app/templates/{ => settings}/companies.html (67%) rename app/templates/{ => settings}/messages.html (56%) rename app/templates/{jobs.html => settings/pulls.html} (50%) create mode 100644 app/templates/settings/ranking.html rename app/templates/{sources.html => settings/searches.html} (91%) diff --git a/app/jobs/cascade.py b/app/jobs/cascade.py index bb96406..3594b57 100644 --- a/app/jobs/cascade.py +++ b/app/jobs/cascade.py @@ -120,9 +120,9 @@ def run_pull(config: Any, store: Any, *, context: RunContext = NULL) -> dict[str return {"started": " > ".join(CASCADES["pull"])} -#: What `app job ` and the Jobs tab offer besides `pull`: one stage +#: What `app job ` and the Pulls page offer besides `pull`: one stage #: each, on its own. `pull` is not a task here, since it is a job: a name that -#: is both would be two buttons on the Jobs tab. +#: is both would be two buttons on the Pulls page. for _name in ("extract", "embed", "score"): TASKS[_name] = partial(task, _name) @@ -130,7 +130,7 @@ for _name in ("extract", "embed", "score"): # ---------------------------------------------------------------- schedules # The default, next to the job it fires. A starting point rather than a -# setting: a cadence edited or switched off on the Schedules tab survives +# setting: a cadence edited or switched off on the Pulls page survives # every restart (see pipeline/schedule.py). declare("pull", "pull", "every 6h", label="Pull every board, then extract, embed and score") diff --git a/app/jobs/pull.py b/app/jobs/pull.py index 8b90f21..e502d91 100644 --- a/app/jobs/pull.py +++ b/app/jobs/pull.py @@ -78,7 +78,7 @@ def run_batch(config: Config, store: Store, *, targets: list[str], source: str = they list. `targets` is keyword-only without a default, which is what makes it a - required payload key to the queue: the Jobs tab offers no button for a + required payload key to the queue: the Pulls page offers no button for a batch that could only fail without one. Builds the plugin scoped to just these targets — `Source.targets()` reads @@ -89,7 +89,7 @@ def run_batch(config: Config, store: Store, *, targets: list[str], source: str = from plugins.search import SearchSource # Fetchable now, not when the pull was queued: a board switched off on the - # Sources tab since then is skipped. + # Searches or Companies page since then is skipped. subs = {s.target: s for s in store.subscriptions(source=source, fetchable=True) if s.target in targets} options = dict(config.sources.get(source) or {}) diff --git a/app/jobs/sources.py b/app/jobs/sources.py index ef3456f..470705d 100644 --- a/app/jobs/sources.py +++ b/app/jobs/sources.py @@ -1,6 +1,6 @@ """What a pull reads, changed by hand: add a board or a search, switch one on or off, prune boards by region. `app companies`, `app searches` and the -Sources tab all call these, so the command line and the page cannot disagree +settings pages all call these, so the command line and the pages cannot disagree about what "off" means. A board or search switched off has its open roles closed at once. Nothing diff --git a/app/static/app.css b/app/static/app.css index 8ce18ca..40a8e87 100644 --- a/app/static/app.css +++ b/app/static/app.css @@ -1,11 +1,14 @@ /* The whole stylesheet: the boilerplate's, with roledesk's palette in the - * custom properties (a quiet UI face and newsdesk's teal signal colour) and - * roledesk's own tabs in the section at the bottom. No build step. + * custom properties (a quiet UI face and newsdesk's teal signal colour), the + * frame (a top bar of two tabs and a cog, the settings sub-tabs), roledesk's + * own pages, and at the bottom the phone: a width query for the layout and a + * pointer query for the sizes, after newsdesk and health. No build step. * - * The `--desk-jobs-*` block at the bottom is how `` is themed. The - * element keeps to a shadow root and reads those properties, so an app skins - * it without forking it -- which is the deal that lets the queue ship its own - * UI and still look like it belongs here. + * The `--desk-jobs-*` block is how ``, `` and + * `` are themed. Each keeps to a shadow root and reads those + * properties, so an app skins it without forking it -- which is the deal + * that lets the queue ship its own UI and still look like it belongs here -- + * and the app cannot lay it out beyond that. */ :root { @@ -45,6 +48,8 @@ } * { box-sizing: border-box; } +/* `hidden` has to win over any class that sets `display`, such as `.check`. */ +[hidden] { display: none !important; } body { margin: 0; @@ -65,6 +70,8 @@ a { color: var(--accent); } gap: var(--gap); flex-wrap: wrap; padding: 0.75rem 1.25rem; + /* Standalone on a phone with a notch: the bar clears the status area. */ + padding-top: calc(0.75rem + env(safe-area-inset-top)); background: var(--panel); border-bottom: 1px solid var(--line); position: sticky; @@ -80,7 +87,7 @@ a { color: var(--accent); } color: var(--fg); } -.top nav { display: flex; gap: 0.25rem; flex-wrap: wrap; } +.top nav { display: flex; gap: 0.25rem; flex-wrap: wrap; align-items: center; } .top nav a { padding: 0.35rem 0.7rem; @@ -88,13 +95,40 @@ a { color: var(--accent); } text-decoration: none; color: var(--dim); } -.top nav a:hover { background: color-mix(in srgb, var(--accent) 12%, transparent); } +/* The cog: an SVG, centred in a box the height of a word. */ +.top nav a.icon { display: inline-flex; align-items: center; padding-block: 0.45rem; } +/* Hover needs a pointer to hover with, and a phone has none: it fakes one on + the element last touched and leaves it there, so a tapped tab would keep a + tint it has no reason to have (newsdesk's app.css says the same). Every + `:hover` in this file is inside one of these. */ +@media (hover: hover) { + .top nav a:hover { background: color-mix(in srgb, var(--accent) 12%, transparent); } +} .top nav a.active { background: var(--accent); color: var(--accent-fg); } +/* The settings sub-tabs, health's: an underlined row here, pills on a phone. */ +.subtabs { + display: flex; gap: 4px; margin: 4px 0 14px; + border-bottom: 1px solid var(--line); +} +.subtabs a { + padding: 7px 12px; + color: var(--dim); + font-weight: 500; + text-decoration: none; + border-bottom: 2px solid transparent; + margin-bottom: -1px; +} +@media (hover: hover) { + .subtabs a:hover { color: var(--fg); } +} +.subtabs a.active { color: var(--accent); border-bottom-color: var(--accent); } + main { max-width: 62rem; margin: 0 auto; padding: 1.5rem 1.25rem 4rem; + padding-bottom: calc(4rem + env(safe-area-inset-bottom)); } h1 { font-size: 1.6rem; margin: 0 0 0.5rem; } @@ -243,11 +277,14 @@ desk-jobs, desk-schedules, auth-account { --desk-jobs-gap: var(--gap); --desk-jobs-radius: var(--radius); } +/* The schedule table has no narrow layout of its own yet, and what overflows + a shadow root widens the page. It scrolls inside its own box instead. */ +desk-schedules { overflow-x: auto; } /* -- roledesk's tabs ------------------------------------------------------ */ /* Roles, Applications, Agents and Companies, drawn by static/roles.js. */ -input, select, textarea { font: inherit; color: inherit; } +input, select, textarea { font: inherit; color: inherit; min-width: 0; max-width: 100%; } .filters { display: flex; flex-wrap: wrap; gap: .5rem; align-items: center; @@ -266,7 +303,6 @@ input, select, textarea { font: inherit; color: inherit; } display: flex; align-items: center; gap: .35rem; color: var(--dim); font-size: .9rem; white-space: nowrap; } -.check[hidden] { display: none; } button:focus-visible, a:focus-visible, input:focus-visible, select:focus-visible, textarea:focus-visible { @@ -285,7 +321,9 @@ textarea:focus-visible { } .role-main { display: flex; flex-wrap: wrap; align-items: baseline; gap: .5rem; } .role-title { font-weight: 600; text-decoration: none; } -.role-title:hover { text-decoration: underline; } +@media (hover: hover) { + .role-title:hover { text-decoration: underline; } +} .role-company { color: var(--dim); } .role-meta { display: flex; flex-wrap: wrap; align-items: center; gap: .5rem; @@ -346,11 +384,15 @@ textarea:focus-visible { background: var(--bg); border: 1px solid var(--line); border-radius: .3rem; padding: .35rem .5rem; width: 100%; } -.agent-form textarea { font-family: var(--mono); font-size: .85rem; } +/* Prose in a textarea is read in the page face; JSON is in the mono one. */ +.agent-form textarea.code { font-family: var(--mono); font-size: .85rem; } .agent-form .hint { color: var(--dim); font-size: .8rem; overflow-wrap: anywhere; } .weights { display: flex; gap: .75rem; flex-wrap: wrap; border: 1px solid var(--line); border-radius: .3rem; } -.weights label { flex: 1 1 6rem; } +/* A label that wraps to two lines pushes its box down; the boxes stay in line. */ +.weights label { flex: 1 1 6rem; justify-content: space-between; } .agent-actions { display: flex; gap: .5rem; flex-wrap: wrap; } +.agent-form details summary { cursor: pointer; color: var(--dim); font-size: .9rem; } +.agent-form details[open] summary { margin-bottom: .5rem; } /* sources */ @@ -365,7 +407,6 @@ textarea:focus-visible { border-radius: .3rem; padding: .35rem .5rem; } .source-form input[type="number"] { max-width: 6rem; } -.source-form [hidden] { display: none; } .sample { margin: 0; padding-left: 1.25rem; font-size: .9rem; } .sample li { margin: .15rem 0; } .mono { font-family: var(--mono); overflow-wrap: anywhere; } @@ -399,3 +440,67 @@ table.list select { padding: .25rem .4rem; } @media (max-width: 480px) { .role-age, .role-main .affinity { margin-left: 0; } } + +/* -- the phone ------------------------------------------------------------ */ +/* Two axes, and deliberately not the same one, as in newsdesk: width decides + the layout, pointer decides the sizes. A tablet is wide and touched, a + half-screen laptop window is narrow and moused, and sizing either by width + puts it in the other's clothes. */ + +@media (max-width: 640px) { + main { padding: 10px 10px calc(3rem + env(safe-area-inset-bottom)); } + h1 { font-size: 1.25rem; } + + /* The bar stays one row: the brand keeps its word, the two tabs share what + is left, and the cog keeps its own width rather than a share. */ + .top { flex-wrap: nowrap; gap: .5rem; padding: calc(4px + env(safe-area-inset-top)) .6rem 4px; } + .top nav { flex: 1; flex-wrap: nowrap; gap: .15rem; min-width: 0; } + .top nav a { flex: 1 1 auto; text-align: center; padding: .6rem .4rem; white-space: nowrap; } + .top nav a.icon { flex: 0 0 auto; justify-content: center; padding-inline: .7rem; } + + /* Six sub-tabs are too many for one row, and a scrolling strip does not + show that more are off the edge. They wrap, three to a row, as pills + rather than the desktop's underlined row. */ + .subtabs { flex-wrap: wrap; border-bottom: none; gap: 6px; } + .subtabs a { + flex: 1 1 30%; + padding: 7px 4px; + border-radius: 999px; + border-bottom: none; + margin-bottom: 0; + background: var(--panel); + text-align: center; + font-size: .85rem; + } + .subtabs a.active { background: var(--accent); color: var(--accent-fg); } + + /* A panel runs to both edges of the screen: no side margin, border or + rounded corner, so the content keeps all but its own 10 pixels of the + width. The page background between two panels reads as a band. */ + .card, .filters, .agent-form, .note { + margin-inline: -10px; border-radius: 0; border-inline: 0; + } + .card { padding: .8rem 10px; } + .row-between { flex-wrap: wrap; } +} + +/* The band between two full-width panels needs more contrast than the light + page background gives a white panel; the dark one is already distinct. */ +@media (max-width: 640px) and (prefers-color-scheme: light) { + :root { --bg: #e1e5e8; } +} + +/* Sizes for a finger. 2.75rem is 44px at the default root size, the smallest + target a thumb hits without aiming. */ +@media (pointer: coarse) { + /* Under 16px, iOS Safari zooms the page when a field takes focus, and does + not zoom back out when it loses it. */ + input, select, textarea { font-size: 16px; } + + button, .top nav a, .subtabs a { min-height: 2.75rem; } + .top nav a, .subtabs a { display: inline-flex; align-items: center; justify-content: center; } + .filters input[type="search"], .filters input[type="text"], .filters select, + .agent-form input, .source-form select { min-height: 2.75rem; } + .affinity button { min-width: 2.25rem; } + .check input { width: 1.25rem; height: 1.25rem; } +} diff --git a/app/static/app.js b/app/static/app.js index c4fe9d5..35d2d3b 100644 --- a/app/static/app.js +++ b/app/static/app.js @@ -12,6 +12,11 @@ * * `body` may be a plain object; it is JSON-encoded with the header set, since * forgetting the header is the failure that looks like a server bug. + * + * Beside `api` on `window`, the few helpers more than one page script uses: + * `count`, `cell`, `debounce`, and the company list with its affinity control + * (`loadCompanies`, `companies`, `affinityControl`, `setAffinity`). One copy + * each, since two copies of a helper is one of them being fixed. */ (function () { @@ -69,5 +74,90 @@ window.toast.error(String(detail)); }); - window.api = api; + // ----------------------------------------------------------------- helpers + + /** `count(3, "role")` is "3 roles"; `many` for an irregular plural. */ + function count(n, one, many) { + return `${n} ${n === 1 ? one : many || `${one}s`}`; + } + + /** A `` with its column name in `data-label`, which the phone layout + prints above the value once the table's head is hidden. */ + function cell(tr, label, content) { + const td = document.createElement("td"); + td.dataset.label = label; + if (typeof content === "string") td.textContent = content; + else td.appendChild(content); + tr.appendChild(td); + return td; + } + + function debounce(fn, ms) { + let timer; + return (...args) => { + clearTimeout(timer); + timer = setTimeout(() => fn(...args), ms); + }; + } + + // --------------------------------------------------------------- companies + + /** @type {Map} company_key -> row from /api/companies. One + Map, refilled in place, so a script holding it sees every reload. */ + const companies = new Map(); + + async function loadCompanies() { + const rows = await api("/api/companies"); + companies.clear(); + for (const c of rows) companies.set(c.key, c); + return companies; + } + + const AFFINITY_LEVELS = [ + { value: -1, label: "Mute" }, + { value: 0, label: "Neutral" }, + { value: 1, label: "Like" }, + { value: 2, label: "Favourite" }, + ]; + + /* The four buttons. `onChange` runs after the server accepted the change, + so each page decides what a change means for it: the role list refetches, + since muting changes which roles come back, and the company table redraws. */ + function affinityControl(companyKey, current, onChange) { + const span = document.createElement("span"); + span.className = "affinity"; + span.setAttribute("role", "group"); + span.setAttribute("aria-label", "Company affinity"); + for (const level of AFFINITY_LEVELS) { + const button = document.createElement("button"); + button.type = "button"; + button.dataset.value = String(level.value); + button.textContent = level.label[0]; + button.title = level.label; + button.setAttribute("aria-label", level.label); + button.setAttribute("aria-pressed", String(level.value === current)); + button.addEventListener("click", () => setAffinity(companyKey, level.value, onChange)); + span.appendChild(button); + } + return span; + } + + async function setAffinity(companyKey, affinity, onChange) { + if (!companyKey) return; + let updated; + try { + updated = await api(`/api/companies/${encodeURIComponent(companyKey)}/affinity`, { + method: "POST", body: { affinity }, + }); + } catch (err) { + return; + } + const company = companies.get(companyKey); + if (company) company.affinity = updated.affinity; + if (onChange) await onChange(); + } + + Object.assign(window, { + api, count, cell, debounce, companies, loadCompanies, affinityControl, setAffinity, + }); })(); diff --git a/app/static/apple-touch-icon.png b/app/static/apple-touch-icon.png new file mode 100644 index 0000000000000000000000000000000000000000..8ed727871a079eee5b706c28131c77c1d2ecfbc4 GIT binary patch literal 1771 zcmb`IYd8}M7{_;xno@EOr%+>ZQn|||grSBxm^7El+(L6%9Je*cG!H5wa$HWXkxL?z zTdvC?m&hfz#WvH77Ur^ShM66{pD*V*eRwa=|9QW?zxVwoUWHqUi=7k$0083FFzB_t zTE8EMe%#Bo)oH!}0I<*+YVL^5V@HNd?ti13gAtekhJfcJjs~83pztoN~13gI)kqj|YJO=CfA<;nLXVEjW zG0^WTI{AU_)4g<79#}nPXMSLcYRhVxt}1ogcE9(jTj(fK`0Ge4b*eql*@D5IjE5TE zFzQHtj4OI_QfABnyIW6$1(+$y2R}u6Y}n{!^c5IS2lHjPl^gUj z+lp%IF1s7t5=1azJG8e0uIJe;cekCrRy;9M&K|^rFfR=vFJ+3yCP|!Xc8t(Vj8_(I zjpmdBHU4B6VgyakHDnW^wuWdLf2lRld7}&=4JKV&udvUm^2>(2!_IFFcxhf+eYtCs z|>@|I(Em4ooK zzk`w1Dw?ul*_S4PgGC>0FY9^&o29N7W6GxH)qBakO=_~#|tyiL%Wi7R@&l)w-=OcWp|f2zJH<4v1=e_*Qd z(>?Dz-1@gAaV{6=oqXrucRr*!^%QbW4(!aWJlm>D9ReW;tqadPcN1|It_x=&bWay( z6=0K!RV1_ZnmY`#Z<_Ws1q7kB_eaE~IbH)&P-G<96Nx|E|=*c{T5?{^tX5Xd7G z`EzRR(TV%JPhvJ`v^UhN68%Ul7x49f%L!J+UW{YCI@##6ntkkVci|OLF(BE}`I87_K&8)!RN1 zy4xeQOvZ)aXI!jv3DfZzTRnFe|Hexo?W#Y&zU3eqUhmGQr4QRyws&Ssycr^{61Fz5 z!UczRvZLuj+_|hqO+OvqiCj3bJ&5~Y2J?7(;=1m3zlj8q$~KE=a(ktwqL@00&kdqOM?dzLcUZ<>}-6m<|i%JVvLsM|01qgu root.querySelector(sel); + + // `ROLEDESK_STATUSES` is set by applications.html from the same `STATUSES` + // tuple the store validates against, so this list can never drift from + // what a `POST .../status` will accept. + function statusSelect(current) { + const select = document.createElement("select"); + for (const status of window.ROLEDESK_STATUSES) { + const option = document.createElement("option"); + option.value = status; + option.textContent = status[0].toUpperCase() + status.slice(1); + option.selected = status === current; + select.appendChild(option); + } + return select; + } + + function render(applications) { + const body = $("#applications-list"); + body.replaceChildren(); + for (const application of applications) { + const tr = document.createElement("tr"); + if (application.url) { + const link = document.createElement("a"); + link.href = application.url; + link.target = "_blank"; + link.rel = "noopener"; + link.textContent = application.role_title || "(untitled)"; + cell(tr, "Role", link); + } else { + cell(tr, "Role", application.role_title || "(untitled)"); + } + const company = companies.get(application.company_key); + cell(tr, "Company", company ? company.name : application.company_key); + const select = statusSelect(application.status); + select.addEventListener("change", () => setStatus(application.id, select)); + cell(tr, "Status", select); + cell(tr, "Next", [application.next_action, application.next_date] + .filter(Boolean).join(" · ")); + body.appendChild(tr); + } + $("#applications-count").textContent = + count(applications.length, "tracked application"); + } + + async function setStatus(id, select) { + select.disabled = true; + try { + await api(`/api/applications/${encodeURIComponent(id)}/status`, { + method: "POST", body: { status: select.value }, + }); + render(await api("/api/applications")); + } catch (err) { + select.disabled = false; + } + } + + document.addEventListener("DOMContentLoaded", async () => { + try { + const [, applications] = await Promise.all([loadCompanies(), api("/api/applications")]); + render(applications); + } catch (err) { + /* already toasted */ + } + }); +})(); diff --git a/app/static/companies.js b/app/static/companies.js new file mode 100644 index 0000000..1a4b05a --- /dev/null +++ b/app/static/companies.js @@ -0,0 +1,50 @@ +/* The Companies page: every company, its open roles, and its affinity. + * + * The list is app.js's shared company list, and the affinity buttons are its + * `affinityControl`, the same ones the Roles tab draws on every row. Filtering + * is done here, over the list already loaded. + */ +(function () { + "use strict"; + + const { count, cell, debounce, companies, loadCompanies, affinityControl } = window; + const $ = (sel, root = document) => root.querySelector(sel); + + function render() { + const q = $("#c-q").value.trim().toLowerCase(); + const affinity = $("#c-affinity").value; + const rows = [...companies.values()] + .filter((c) => !q || c.name.toLowerCase().includes(q) || c.board.includes(q)) + .filter((c) => affinity === "" || String(c.affinity) === affinity) + .sort((a, b) => b.open_roles - a.open_roles || a.name.localeCompare(b.name)); + const body = $("#companies-list"); + body.replaceChildren(); + for (const company of rows) { + const tr = document.createElement("tr"); + if (company.affinity === -1) tr.classList.add("muted"); + const link = document.createElement("a"); + link.href = `/?company=${encodeURIComponent(company.name)}`; + link.title = "This company's open roles"; + link.textContent = company.name; + cell(tr, "Company", link); + cell(tr, "Board", company.board || ""); + cell(tr, "Open roles", String(company.open_roles)).className = "num"; + cell(tr, "Affinity", affinityControl(company.key, company.affinity, async () => render())); + body.appendChild(tr); + } + const open = rows.reduce((sum, c) => sum + c.open_roles, 0); + $("#companies-count").textContent = + `${count(rows.length, "company", "companies")}, ${count(open, "open role")}`; + } + + document.addEventListener("DOMContentLoaded", async () => { + try { + await loadCompanies(); + } catch (err) { + return; + } + render(); + $("#c-q").addEventListener("input", debounce(render, 150)); + $("#c-affinity").addEventListener("change", render); + }); +})(); diff --git a/app/static/icon-192.png b/app/static/icon-192.png new file mode 100644 index 0000000000000000000000000000000000000000..d616c2b00cefd6c88c4c8972fde657a5241f55d4 GIT binary patch literal 1523 zcmeAS@N?(olHy`uVBq!ia0vp^2SAvE2}s`E_d9@rfpvwai(^Q|oHuv9b3#%j+CP?C zO+WR;XwtNx#tTfF3K-RP2`Za0y7DNhsfqPWyf$^$!5xgf*-o!c9a$l5GA;HZFZbmm zw-Oc=rkcET6J8vWqj1H``t6x7RcU`F?J`iEHuJOn+n-tU<7YXY{{Csw8DnGH+^8Vo z$(789Rv9}uI7|=_P+?)=WOQ_*3v`?4QPkMBNX%(?#GX3_G^f2W?;*U?#9q&C@e>yx6DAz!|qsMsDazrXgM z*Z&i}7emj<+_`)6`rXaTb9YxBUfgge);?Y%RBLMWJRcRIoyT&5lbc=DkG*~B^>p(3 z_IvWblIk))&TD@i{BrYgzde_}mc%C6&JX!NSzq2opY>o#>Gt`L`*t4AJEA1?{+su(3coAZwRdEo6(zHHg)t9R>8-$^u266`G8{d@I2sTcaXXTt3t@$I)Q z*tx9!!>x}>3gzwd;#a)-_dP%F2=6SNdvB+&op$Not!;cU*Y%->1a2n&-xa z$ELA0u6A;q`(|*FpD-T1_t%J)x4$p7yWp!a_v^XO<0^I}ug^`IZM$IR&7BiB-q+PJ z&zmjnpGbuic;x@wl{Lj5+r;V}K-95d3EHITBmbF~NxgdQyJ6w+%`+{ID+|^;b4xGzFkM%&w%NzLRA;$zuoIEvoXMl-|cjFL)ET6xf@p#O|3R; zJ`7G1%lT#NwiM65`eNd_+Pn)k4^F54Ir?s%?n|Gq&)<8e|B8FFvE#_@zfRw0=IDkO zzkBrh(MscI?D0%h8}|O)s(gI4{r_hhCs*ITrK|KY?|shQvTrv|zB)hO`eTjzX|vDH zNl8Ze_kKLRcD9&#{=bsqoTG8F%Dq?SV$N%46Z({QzZrZzB zar3?Qe>`*Yo_hbfyWa}-aA(|f67Uh@zI^mi$jTS@_SoOPaOc8?tqTn|>xr-Xm>18} z^d~2CSxC|PyR&!d-dvV*ZSS{-i~i=#V{7Sc(qHC8pYjT+bo|51!0`XSpq=V_VA0J6 cDzljxOq-b50yCnX0!0`+UHx3vIVCg!0Ky4)?*IS* literal 0 HcmV?d00001 diff --git a/app/static/icon-512.png b/app/static/icon-512.png new file mode 100644 index 0000000000000000000000000000000000000000..63c225801939533302472766fbc49017c2b6e6c9 GIT binary patch literal 4386 zcmeHL`#Y3rAAeA?W;N}$5ut;u-C8CqTV!S`si>%gQcR7?DNQ*u^B9rsEs;`57-nl! z7z#PhOr`?hU7R5V|t7+r}weD?|<-K*Lz*N?@!NteedVG@9*jJ`F_9m^~0|F z^mL7M0RYf*-oNK40BFKXO+aVyLo{-v1HcNvdC#t6(b<#z#5CUskS)eVhFN4GoY!65 z7{6k7l^;ic&t~1#X&c;o1A`4|FE<=Fv8N4C6*CZ2DwQAzDnXltg^}h=G=s&ONp^_H9a@>*k$RngPap};G zTE43HvAyfm8pHl=_K~MaiY@AQ&Ep+~_1!$XGUIB>dyLS-M2Za)R8A{YjI4?fbThUz zQg#CxrJp2=Z0_ZSEXi})yO;fIf%9$9BKSR#M9*`5z9tCP;AQ{m$t@&VI7VHS?3he zp@P;)egBH?#r*uKD;VK^2*^JkkyfzWqf4W(Gi0vF5TUJozU5s_vtKUMJ2PfRPB?_E#r#V;F zjXli5RWY|XEjb-@(A1$Sj4J{kJ)*^g`M3I(U&lPt^?dpy7Ov;RqivuzZ?&YIqEv3oVF74pl0eN{)N2l3@!XdoO?kHEwbFfsE>MQZxYu3paO#G+6D7Bma)Cljo>sQ8 zjw)$nRU6qPa9{$By#{>gO!cXk=Qf0lySYQ(H>OetL%(~`8p{~OV&)UsaYys_L-`%K z;FtO&({JPXhWs*uVC;D2QTg760_*ojUc+X%;S@X{L2c#1XRV6Xr~+$U#s&Z#I`C?q zBSO=b7FZXYabfrPGfd-1LIF6p@=uX2dOd(HEi~Cz=;&?Re0%Z6;Z$|@1vYdu=w{G^ z-EKNNQ8#aNORA8&{)fI7Kx+Um2Ht_lLd^Gza4mKrZzR^tH5G&Sj*>`$+?A;)F^y__lfrnkQ z!HH%*wc&wq5GNdwclB#W*JmVTnFAk;46{C2+>2x0eioNDk#Q~;s`2+L)S8jWSzZBm zfUN-}(r*hM-bKols;%-O?k!3*Ns`{@lI$_$;izw92IxJUMQ++|oU?j%g}lhiqNRkP z6L73s+6R5SBIbj;mEQ>8rd|68hk(~x>!!fsb5@tuF3H=K9>Ty4KZ(GR3jh_*!py(z~CblWm^uzW%^B6)1n4E zZQZ|deaSZ%`&W}dmfyY<$(*Xt^ch(7Pp`2-u~h2}mgEo(VM^)?S^941AMcU>LU$Fw zu`WA*ulp~6!^P6wyW}qrw^?h^Abac2>tP6+Ye^0WVWf+`jn}r!aOELNDQo9(d~MZPBkZYICdvlo9fe`4k1>3v~pc9q3X_7&k*!S3LmH%|W9oC%3A z%qxe)OGrv;(AimL<=a1zUUa}!_;LIm*e$$c@^dfnAvBuwC8EVsLEGcw>tKd$q7VZS zxxT&*ggm37#freo&a@%agoA;ZStuWzo~QjgjL??YaFcr~E+R0K>l+tgdz^YklY`)5 zrR^(6;0rFlzcW-aJ^P1Im2ty%oAoV!q`!#mnGJfpTe2k2U_rj%8|IYkTIx&e@#xx5 zD}y<>Ylci3wx!u#to}6NI$h>?p?Y62an1>ak-lly^rDoB3j8sJ;n}d8CL}0D3Iess z^3qfdjxjmuDael9`b|7vmL&jXNfvJ6kOZMC2BM=FRO40f$>f;+15XrowaK0(F%p8x zm+G}7FY5f9lr{RR7us)JeC~#W-*~B%f63i;uiYj%py$6xS;7Uc;uDeh%neUaJH-85 z!SbUO)<4UpW + + + + + + + + + + + + + + + + + + + diff --git a/app/static/jobs.js b/app/static/jobs.js index 79adc3c..199c689 100644 --- a/app/static/jobs.js +++ b/app/static/jobs.js @@ -1,4 +1,4 @@ -/* The Jobs tab: a button per kind. +/* The Pulls page: a button per kind. * * The list comes from `/api/jobs/kinds`, which is the registry, so a new * `@job` in `app/jobs.py` is a new button and this file is not edited. What diff --git a/app/static/manifest.json b/app/static/manifest.json new file mode 100644 index 0000000..b5d6e4e --- /dev/null +++ b/app/static/manifest.json @@ -0,0 +1,17 @@ +{ + "name": "roledesk", + "short_name": "roledesk", + "description": "Job postings from boards and searches, ranked against what you are looking for.", + "start_url": "/", + "scope": "/", + "display": "standalone", + "background_color": "#eceff1", + "theme_color": "#ffffff", + "icons": [ + {"src": "/static/icon-192.png", "sizes": "192x192", "type": "image/png"}, + {"src": "/static/icon-512.png", "sizes": "512x512", "type": "image/png"}, + {"src": "/static/icon-512.png", "sizes": "512x512", "type": "image/png", + "purpose": "maskable"}, + {"src": "/static/icon.svg", "sizes": "any", "type": "image/svg+xml"} + ] +} diff --git a/app/static/ranking.js b/app/static/ranking.js new file mode 100644 index 0000000..f9c8327 --- /dev/null +++ b/app/static/ranking.js @@ -0,0 +1,134 @@ +/* The Ranking page: what Best match on the Roles tab is measured against. + * + * The UI shows one ranking. Underneath it is the first enabled search agent, + * the oldest by id, since the `agents` table still holds as many as the CLI + * or the config put there; this page edits that one and never lists, adds or + * deletes. An empty table gets its first agent on the first save. + * + * Every request goes through `api()` from app.js, so a failure is one toast + * carrying the server's own sentence. + */ +(function () { + "use strict"; + + const { api, count } = window; + const $ = (sel, root = document) => root.querySelector(sel); + + /** The name a ranking made here is saved under; the UI never shows it + unless the CLI adds a second one. */ + const NEW_NAME = "My ranking"; + const DEFAULT_WEIGHTS = { fit: 0.6, recency: 0.2, affinity: 0.2 }; + + /** @type {object | null} the agent this page edits, null until one is saved */ + let agent = null; + + /* The first enabled agent, else the first at all: editing it here means it + is wanted, so a save switches it on. */ + function pick(agents) { + const byId = [...agents].sort((a, b) => a.id - b.id); + return byId.find((a) => a.enabled) || byId[0] || null; + } + + function fill(others) { + $("#a-intent").value = agent ? agent.intent : ""; + $("#a-gates").value = JSON.stringify(agent ? agent.gates : [], null, 2); + const weights = agent ? agent.weights : DEFAULT_WEIGHTS; + $("#a-fit").value = weights.fit; + $("#a-recency").value = weights.recency; + $("#a-affinity").value = weights.affinity; + const note = $("#ranking-others"); + note.hidden = !(agent && others > 0); + if (!note.hidden) { + note.textContent = `This edits "${agent.name}". ${count(others, "other ranking")} ` + + "can be picked by name in the order menu on Roles."; + } + } + + async function save(event) { + event.preventDefault(); + const status = $("#ranking-status"); + let gates; + try { + gates = JSON.parse($("#a-gates").value || "[]"); + } catch (err) { + window.toast.error(`Gates are not valid JSON: ${err.message}`); + return; + } + const body = { + name: agent ? agent.name : NEW_NAME, + intent: $("#a-intent").value, + gates, + weights: { + fit: Number($("#a-fit").value), + recency: Number($("#a-recency").value), + affinity: Number($("#a-affinity").value), + }, + enabled: true, + }; + if (agent) body.id = agent.id; + const button = $("#ranking-form button[type=submit]"); + button.disabled = true; + try { + agent = await api("/api/agents", { method: "POST", body }); + } catch (err) { + status.textContent = ""; + button.disabled = false; + return; + } + await rescore(status); + button.disabled = false; + } + + // Start the `score` job and wait for it, so "Saved and scored" means the + // Roles tab already orders by what was saved. + async function rescore(status) { + status.textContent = "Saved. Scoring…"; + let job; + try { + job = await api("/api/jobs", { method: "POST", body: { kind: "score", payload: {} } }); + } catch (err) { + status.textContent = "Saved, but scoring did not start."; + return; + } + for (let i = 0; i < 300; i += 1) { + await new Promise((resolve) => setTimeout(resolve, 1000)); + let snapshot; + try { + snapshot = await api("/api/jobs"); + } catch (err) { + return; + } + const busy = [...snapshot.running, ...snapshot.queued].some((j) => j.id === job.id); + if (busy) continue; + const done = snapshot.recent.find((j) => j.id === job.id); + if (done && done.state !== "done") { + status.textContent = `Saved. Scoring ${done.state}.`; + if (done.error) window.toast.error(`Scoring ${done.state}: ${done.error}`); + return; + } + status.replaceChildren("Saved and scored. "); + const link = document.createElement("a"); + link.href = `/?agent=${agent.id}`; + link.textContent = "See the best matches"; + status.appendChild(link); + return; + } + status.replaceChildren("Saved. Scoring is still running; "); + const link = document.createElement("a"); + link.href = "/settings/pulls"; + link.textContent = "follow it under Pulls"; + status.append(link, "."); + } + + document.addEventListener("DOMContentLoaded", async () => { + let agents; + try { + agents = await api("/api/agents"); + } catch (err) { + return; + } + agent = pick(agents); + fill(agents.filter((a) => a.enabled && (!agent || a.id !== agent.id)).length); + $("#ranking-form").addEventListener("submit", save); + }); +})(); diff --git a/app/static/roles.js b/app/static/roles.js index 99523ec..e847a5f 100644 --- a/app/static/roles.js +++ b/app/static/roles.js @@ -1,10 +1,9 @@ -/* roledesk's four tabs: Roles, Applications, Agents and Companies. +/* The Roles tab: the filter bar and the list of open roles. * - * Each template renders an empty shell; everything on screen comes from the - * JSON routes in app/web/api.py, and every action (Save, an affinity click, a - * status change, an agent saved) is a fetch from here, not a form post. One - * script for the four, because they share the company list and the affinity - * control; `init` looks at which containers the page has. + * The template renders an empty shell; everything on screen comes from the + * JSON routes in app/web/api.py, and every action (Save, an affinity click) + * is a fetch from here, not a form post. The company list and its affinity + * control are app.js's, shared with the Companies page. * * Every request goes through `api()` from app.js, so a failure is one toast * carrying the server's own sentence. The catch blocks here only put the @@ -13,103 +12,26 @@ (function () { "use strict"; - const api = window.api; + const { api, count, debounce, companies, loadCompanies, affinityControl } = window; - /** @type {Map} company_key -> row from /api/companies */ - let companies = new Map(); /** @type {Map} role_uid -> application, for roles already tracked */ let trackedByRole = new Map(); /** @type {object[]} the last /api/roles response, already muted-filtered by the server */ let roles = []; - /** @type {object[]} every search agent, from /api/agents */ + /** @type {object[]} the enabled rankings, from /api/agents */ let agents = []; const $ = (sel, root = document) => root.querySelector(sel); - function debounce(fn, ms) { - let timer; - return (...args) => { - clearTimeout(timer); - timer = setTimeout(() => fn(...args), ms); - }; - } - - function count(n, one, many) { - return `${n} ${n === 1 ? one : many || `${one}s`}`; - } - - async function loadCompanies() { - const rows = await api("/api/companies"); - companies = new Map(rows.map((c) => [c.key, c])); - } - async function loadApplications() { const applications = await api("/api/applications"); trackedByRole = new Map(applications.filter((a) => a.role_uid).map((a) => [a.role_uid, a])); - return applications; } async function loadAgents() { - agents = await api("/api/agents"); + agents = (await api("/api/agents")).filter((a) => a.enabled); } - function cell(tr, label, content) { - const td = document.createElement("td"); - td.dataset.label = label; - if (typeof content === "string") td.textContent = content; - else td.appendChild(content); - tr.appendChild(td); - return td; - } - - // ---------------------------------------------------------------- affinity - - const AFFINITY_LEVELS = [ - { value: -1, label: "Mute" }, - { value: 0, label: "Neutral" }, - { value: 1, label: "Like" }, - { value: 2, label: "Favourite" }, - ]; - - /* The four buttons. `onChange` runs after the server accepted the change, - so each tab decides what a change means for it: the role list refetches, - since muting changes which roles come back, and the company table redraws. */ - function affinityControl(companyKey, current, onChange) { - const span = document.createElement("span"); - span.className = "affinity"; - span.setAttribute("role", "group"); - span.setAttribute("aria-label", "Company affinity"); - for (const level of AFFINITY_LEVELS) { - const button = document.createElement("button"); - button.type = "button"; - button.dataset.value = String(level.value); - button.textContent = level.label[0]; - button.title = level.label; - button.setAttribute("aria-label", level.label); - button.setAttribute("aria-pressed", String(level.value === current)); - button.addEventListener("click", () => setAffinity(companyKey, level.value, onChange)); - span.appendChild(button); - } - return span; - } - - async function setAffinity(companyKey, affinity, onChange) { - if (!companyKey) return; - let updated; - try { - updated = await api(`/api/companies/${encodeURIComponent(companyKey)}/affinity`, { - method: "POST", body: { affinity }, - }); - } catch (err) { - return; - } - const company = companies.get(companyKey); - if (company) company.affinity = updated.affinity; - await onChange(); - } - - // ------------------------------------------------------------------- roles - function filterParams() { const params = new URLSearchParams(); for (const key of ["q", "company", "place"]) { @@ -171,7 +93,7 @@ if (role.score !== null && role.score !== undefined) { const badge = node.querySelector(".role-score"); badge.textContent = role.gated_reason ? "gated" : role.score.toFixed(2); - badge.title = "Score for the selected agent"; + badge.title = "Match"; node.querySelector(".role-gated").textContent = role.gated_reason || ""; if (role.gated_reason) li.classList.add("gated"); } @@ -210,14 +132,16 @@ } } - // The filter bar's order: "Newest", or one agent's score. Keeps the current - // choice when the list is refreshed, unless that agent is gone. + /* The filter bar's order: Newest, or a ranking's score. One ranking is the + ordinary case and reads "Best match"; more than one only comes from the + CLI or the config, and then each is listed by name so none is lost. Keeps + the current choice when the list is refreshed, unless that one is gone. */ function renderAgentSelect() { const select = $("#f-agent"); const current = select.value; select.replaceChildren(new Option("Newest", "")); for (const agent of agents) { - const label = agent.enabled ? agent.name : `${agent.name} (off)`; + const label = agents.length === 1 ? "Best match" : agent.name; select.appendChild(new Option(label, String(agent.id))); } select.value = agents.some((a) => String(a.id) === current) ? current : ""; @@ -225,7 +149,7 @@ } /* `?q=`, `?company=`, `?place=` and `?agent=` prefill the filter bar, which - is how the Companies and Agents tabs link into this one. */ + is how the Companies and Ranking pages link into this one. */ function prefill() { const query = new URLSearchParams(location.search); for (const key of ["q", "company", "place"]) { @@ -238,7 +162,7 @@ } } - async function initRoles() { + document.addEventListener("DOMContentLoaded", async () => { try { await Promise.all([loadCompanies(), loadApplications(), loadAgents()]); } catch (err) { @@ -260,265 +184,5 @@ loadRoles(); }); $("#filters").addEventListener("submit", (e) => e.preventDefault()); - } - - // ------------------------------------------------------------ applications - - // `ROLEDESK_STATUSES` is set by applications.html from the same `STATUSES` - // tuple the store validates against, so this list can never drift from - // what a `POST .../status` will accept. - function statusSelect(current) { - const select = document.createElement("select"); - for (const status of window.ROLEDESK_STATUSES) { - const option = document.createElement("option"); - option.value = status; - option.textContent = status[0].toUpperCase() + status.slice(1); - option.selected = status === current; - select.appendChild(option); - } - return select; - } - - function renderApplications(applications) { - const body = $("#applications-list"); - body.replaceChildren(); - for (const application of applications) { - const tr = document.createElement("tr"); - if (application.url) { - const link = document.createElement("a"); - link.href = application.url; - link.target = "_blank"; - link.rel = "noopener"; - link.textContent = application.role_title || "(untitled)"; - cell(tr, "Role", link); - } else { - cell(tr, "Role", application.role_title || "(untitled)"); - } - const company = companies.get(application.company_key); - cell(tr, "Company", company ? company.name : application.company_key); - const select = statusSelect(application.status); - select.addEventListener("change", () => setStatus(application.id, select)); - cell(tr, "Status", select); - cell(tr, "Next", [application.next_action, application.next_date] - .filter(Boolean).join(" · ")); - body.appendChild(tr); - } - $("#applications-count").textContent = - count(applications.length, "tracked application"); - } - - async function setStatus(id, select) { - select.disabled = true; - try { - await api(`/api/applications/${encodeURIComponent(id)}/status`, { - method: "POST", body: { status: select.value }, - }); - renderApplications(await loadApplications()); - } catch (err) { - select.disabled = false; - } - } - - async function initApplications() { - try { - const [, applications] = await Promise.all([loadCompanies(), loadApplications()]); - renderApplications(applications); - } catch (err) { - /* already toasted */ - } - } - - // ------------------------------------------------------------------ agents - - function renderAgents() { - const list = $("#agents-list"); - list.replaceChildren(); - for (const agent of agents) { - const li = document.createElement("li"); - li.className = "agent"; - const name = document.createElement("a"); - name.href = `/?agent=${agent.id}`; - name.title = "Roles, ordered by this agent's score"; - name.textContent = agent.name; - const meta = document.createElement("span"); - meta.className = "agent-meta"; - const gates = agent.gates.map((g) => `${g.mode} ${g.field}`).join(", ") || "no gates"; - meta.textContent = `${agent.enabled ? "" : "off · "}${gates}`; - const edit = document.createElement("button"); - edit.type = "button"; - edit.className = "secondary"; - edit.textContent = "Edit"; - edit.addEventListener("click", () => fillAgentForm(agent)); - li.append(name, meta, edit); - list.appendChild(li); - } - $("#agents-count").textContent = count(agents.length, "agent"); - } - - function fillAgentForm(agent) { - $("#agent-form-title").textContent = agent ? `Edit ${agent.name}` : "New agent"; - $("#a-id").value = agent ? String(agent.id) : ""; - $("#a-name").value = agent ? agent.name : ""; - $("#a-intent").value = agent ? agent.intent : ""; - $("#a-gates").value = JSON.stringify(agent ? agent.gates : [], null, 2); - const weights = agent ? agent.weights : { fit: 0.6, recency: 0.2, affinity: 0.2 }; - $("#a-fit").value = weights.fit; - $("#a-recency").value = weights.recency; - $("#a-affinity").value = weights.affinity; - $("#a-enabled").checked = agent ? agent.enabled : true; - $("#a-delete").hidden = !agent; - $("#agent-status").textContent = ""; - } - - async function saveAgent(event) { - event.preventDefault(); - const status = $("#agent-status"); - let gates; - try { - gates = JSON.parse($("#a-gates").value || "[]"); - } catch (err) { - window.toast.error(`Gates are not valid JSON: ${err.message}`); - return; - } - const id = $("#a-id").value; - const body = { - name: $("#a-name").value.trim(), - intent: $("#a-intent").value, - gates, - weights: { - fit: Number($("#a-fit").value), - recency: Number($("#a-recency").value), - affinity: Number($("#a-affinity").value), - }, - enabled: $("#a-enabled").checked, - }; - if (id) body.id = Number(id); - let saved; - try { - saved = await api("/api/agents", { method: "POST", body }); - } catch (err) { - status.textContent = ""; - return; - } - try { - await loadAgents(); - renderAgents(); - } catch (err) { - /* already toasted; the save itself landed */ - } - fillAgentForm(saved); - await rescore(status, saved); - } - - async function deleteAgent() { - const id = $("#a-id").value; - if (!id || !confirm("Delete this agent and its scores?")) return; - try { - await api(`/api/agents/${encodeURIComponent(id)}`, { method: "DELETE" }); - fillAgentForm(null); - await loadAgents(); - renderAgents(); - } catch (err) { - /* already toasted */ - } - } - - // Start the `score` job and wait for it, so "Saved and scored" means the - // Roles tab already orders by what was saved. - async function rescore(status, agent) { - status.textContent = "Saved. Scoring…"; - let job; - try { - job = await api("/api/jobs", { method: "POST", body: { kind: "score", payload: {} } }); - } catch (err) { - status.textContent = "Saved, but scoring did not start."; - return; - } - for (let i = 0; i < 300; i += 1) { - await new Promise((resolve) => setTimeout(resolve, 1000)); - let snapshot; - try { - snapshot = await api("/api/jobs"); - } catch (err) { - return; - } - const busy = [...snapshot.running, ...snapshot.queued].some((j) => j.id === job.id); - if (busy) continue; - const done = snapshot.recent.find((j) => j.id === job.id); - if (done && done.state !== "done") { - status.textContent = `Saved. Scoring ${done.state}.`; - if (done.error) window.toast.error(`Scoring ${done.state}: ${done.error}`); - return; - } - status.replaceChildren("Saved and scored. "); - const link = document.createElement("a"); - link.href = `/?agent=${agent.id}`; - link.textContent = "See the roles"; - status.appendChild(link); - return; - } - status.textContent = "Saved. Scoring is still running; see the Jobs tab."; - } - - async function initAgents() { - try { - await loadAgents(); - } catch (err) { - return; - } - renderAgents(); - $("#agent-form").addEventListener("submit", saveAgent); - $("#a-new").addEventListener("click", () => fillAgentForm(null)); - $("#a-delete").addEventListener("click", deleteAgent); - } - - // --------------------------------------------------------------- companies - - function renderCompanies() { - const q = $("#c-q").value.trim().toLowerCase(); - const affinity = $("#c-affinity").value; - const rows = [...companies.values()] - .filter((c) => !q || c.name.toLowerCase().includes(q) || c.board.includes(q)) - .filter((c) => affinity === "" || String(c.affinity) === affinity) - .sort((a, b) => b.open_roles - a.open_roles || a.name.localeCompare(b.name)); - const body = $("#companies-list"); - body.replaceChildren(); - for (const company of rows) { - const tr = document.createElement("tr"); - if (company.affinity === -1) tr.classList.add("muted"); - const link = document.createElement("a"); - link.href = `/?company=${encodeURIComponent(company.name)}`; - link.title = "This company's open roles"; - link.textContent = company.name; - cell(tr, "Company", link); - cell(tr, "Board", company.board || ""); - cell(tr, "Open roles", String(company.open_roles)).className = "num"; - cell(tr, "Affinity", - affinityControl(company.key, company.affinity, async () => renderCompanies())); - body.appendChild(tr); - } - const open = rows.reduce((sum, c) => sum + c.open_roles, 0); - $("#companies-count").textContent = - `${count(rows.length, "company", "companies")}, ${count(open, "open role")}`; - } - - async function initCompanies() { - try { - await loadCompanies(); - } catch (err) { - return; - } - renderCompanies(); - $("#c-q").addEventListener("input", debounce(renderCompanies, 150)); - $("#c-affinity").addEventListener("change", renderCompanies); - } - - // -------------------------------------------------------------------- init - - document.addEventListener("DOMContentLoaded", () => { - if ($("#roles-list")) initRoles(); - if ($("#applications-list")) initApplications(); - if ($("#agents-list")) initAgents(); - if ($("#companies-list")) initCompanies(); }); })(); diff --git a/app/static/sources.js b/app/static/sources.js index 6b7f3e6..ac3d030 100644 --- a/app/static/sources.js +++ b/app/static/sources.js @@ -1,4 +1,5 @@ -/* The Sources tab: saved searches, company boards, and the prune by region. +/* The Searches page under Settings: saved searches, and for now the company + * boards and the prune by region as well. * * The template is a shell; the lists come from /api/sources and every action * is a fetch through `api()` from app.js, so a refusal (a search that finds @@ -8,7 +9,7 @@ (function () { "use strict"; - const api = window.api; + const { api, count, cell, debounce } = window; const $ = (sel, root = document) => root.querySelector(sel); /** @type {{searches: object[], boards: object[], adzuna_key: boolean}} */ @@ -16,27 +17,6 @@ /** @type {object[]} the boards the last prune preview named */ let pruneBoards = []; - function count(n, one, many) { - return `${n} ${n === 1 ? one : many || `${one}s`}`; - } - - function debounce(fn, ms) { - let timer; - return (...args) => { - clearTimeout(timer); - timer = setTimeout(() => fn(...args), ms); - }; - } - - function cell(tr, label, content) { - const td = document.createElement("td"); - td.dataset.label = label; - if (typeof content === "string") td.textContent = content; - else td.appendChild(content); - tr.appendChild(td); - return td; - } - /** "DK 120 · EU 4 · unknown 2", the three biggest. */ function countries(source) { const shown = source.countries.slice(0, 3) @@ -331,8 +311,8 @@ await api("/api/jobs", { method: "POST", body: { kind: "pull", payload: {} } }); $("#pull-status").replaceChildren("Pull started. "); const link = document.createElement("a"); - link.href = "/jobs"; - link.textContent = "Follow it on the Jobs tab"; + link.href = "/settings/pulls"; + link.textContent = "Follow it under Pulls"; $("#pull-status").appendChild(link); } catch (err) { /* already toasted */ diff --git a/app/templates/agents.html b/app/templates/agents.html deleted file mode 100644 index ea7b701..0000000 --- a/app/templates/agents.html +++ /dev/null @@ -1,37 +0,0 @@ -{% extends "base.html" %} -{% block title %}Agents — roledesk{% endblock %} - -{% block content %} -

Search agents

-

A search agent is a named search: an intent that fit is measured against, gates that require or prefer a column value, and the weights of each term. Saving one rescores it; the Roles tab orders by it when it is picked there.

- -

-
    - -
    -

    New agent

    - - - - -
    - Weights - - - -
    - -
    - - - -
    -

    -
    -{% endblock %} - -{% block scripts %} - -{% endblock %} diff --git a/app/templates/applications.html b/app/templates/applications.html index 9cad05a..a6fca10 100644 --- a/app/templates/applications.html +++ b/app/templates/applications.html @@ -3,7 +3,7 @@ {% block content %}

    Applications

    -

    Every role saved from the Roles tab, and where it stands. A status change is recorded as an event, which is what days to first screen and conversion are computed from.

    +

    Every role you saved on the Roles tab, and where it stands. Change the status as it moves.

    @@ -20,5 +20,5 @@ // store validates a status change against; see app/web/pages.py. window.ROLEDESK_STATUSES = {{ status_options | map(attribute=0) | list | tojson }}; - + {% endblock %} diff --git a/app/templates/base.html b/app/templates/base.html index 161af38..e21141a 100644 --- a/app/templates/base.html +++ b/app/templates/base.html @@ -1,12 +1,32 @@ -{# The frame every page is in. The nav is `TABS` from app/web/pages.py and - nothing else: adding a tab is one entry in that list, never a link here. #} +{# The frame every page is in. The top bar is `TABS` from app/web/pages.py + plus the cog, and the cog's sub-tabs are `SETTINGS` there: adding a page is + one entry in one of those lists, never a link here. #} {% block title %}roledesk{% endblock %} - + {# Kept on the home screen rather than in a tab, as newsdesk is: `display: + standalone` in the manifest drops the browser's chrome, which is worth a + row of roles on a phone. `manifest.json` and not `.webmanifest`, because + StaticFiles guesses the content type from the extension and not every + machine knows the second one. Two `theme-color`s so the status bar is the + colour of the header right under it. No service worker: the app is no use + without the server. #} + + + + + + + + {# iOS reads neither the manifest nor the line above: standalone mode, the + home screen label and the status bar are still set from its own + `apple-` metas. #} + + + @@ -17,6 +37,12 @@ {{ tab.label }} {% endfor %} + {# health's cog: an icon because it is not a place you go to often, and a + word would take a third of the bar on a phone. #} + @@ -26,7 +52,8 @@ {# toasts first, and the order is load-bearing: it owns `window.toast`, which app.js calls on a failed fetch and live.js feeds server notices into, and - `window.esc`, which every page script below builds its HTML with. #} + `window.esc`, which every page script below builds its HTML with. app.js + next, since every page script takes `api` and the shared helpers from it. #} diff --git a/app/templates/error.html b/app/templates/error.html index a8cd81c..00d0439 100644 --- a/app/templates/error.html +++ b/app/templates/error.html @@ -9,5 +9,5 @@ the API does not. #}

    {{ detail }}

    -

    Back to the roles, or see what the server has been saying.

    +

    Back to the roles, or see what the server has been saying.

    {% endblock %} diff --git a/app/templates/schedules.html b/app/templates/schedules.html deleted file mode 100644 index 2d20dd9..0000000 --- a/app/templates/schedules.html +++ /dev/null @@ -1,15 +0,0 @@ -{% extends "base.html" %} -{% block title %}Schedules — roledesk{% endblock %} - -{% block content %} -

    Schedules

    - -

    A schedule enqueues a job kind on a cadence: every 15m, every 6h, every 2d, daily at 06:00 or weekly mon 07:00, the clock ones read in timezone from config.yaml. The default, pull every 6h, is declared next to the pull job in app/jobs/cascade.py. It is a starting point: a cadence edited here, or a schedule switched off, survives restarts and deploys.

    - -
    - {# The element and its script are the scheduler's own, served by its own - router — see pipeline/web/static/schedules.js. Two lines, as with jobs. #} - - -
    -{% endblock %} diff --git a/app/templates/settings/_tabs.html b/app/templates/settings/_tabs.html new file mode 100644 index 0000000..4b90195 --- /dev/null +++ b/app/templates/settings/_tabs.html @@ -0,0 +1,8 @@ +{# The sub-tabs under the cog: `SETTINGS` from app/web/pages.py, each active by + its own path. Links, not a script: every sub-tab is a page of its own. #} + diff --git a/app/templates/account.html b/app/templates/settings/account.html similarity index 59% rename from app/templates/account.html rename to app/templates/settings/account.html index b09d305..f33eec1 100644 --- a/app/templates/account.html +++ b/app/templates/settings/account.html @@ -2,12 +2,13 @@ {% block title %}Account — roledesk{% endblock %} {% block content %} -

    Account

    +

    Settings

    +{% include "settings/_tabs.html" %} -

    One password, the sessions it has opened, and the passkeys registered beside it. There is no user to create and none to delete, because there is one. docs/password-protection.md is the reasoning behind every choice on this page; auth/README.md is how to take the folder into another project.

    +

    The one password, the devices signed in with it, and the passkeys that sign in without it.

    - {# As on the Jobs and Schedules tabs: the element and its script belong to + {# As on the Pulls page: the element and its script belong to the module, so this page is two lines and `auth/` owns what they draw. It says its own failures in place, beside the button that caused them, diff --git a/app/templates/companies.html b/app/templates/settings/companies.html similarity index 67% rename from app/templates/companies.html rename to app/templates/settings/companies.html index cd9a6ed..579d0a1 100644 --- a/app/templates/companies.html +++ b/app/templates/settings/companies.html @@ -2,8 +2,10 @@ {% block title %}Companies — roledesk{% endblock %} {% block content %} -

    Companies

    -

    Every company whose board is read, with how many of its roles are open. Affinity: Mute hides its roles and leaves them unscored, Neutral is the default, Like raises the affinity term, Favourite skips the gates and floors the score at 0.9.

    +

    Settings

    +{% include "settings/_tabs.html" %} + +

    Every company roledesk has seen, and how many of its roles are open. Mute keeps its roles out of the list, Like lifts them in Best match, and Favourite puts them at the top.

    @@ -26,5 +28,5 @@ {% endblock %} {% block scripts %} - + {% endblock %} diff --git a/app/templates/messages.html b/app/templates/settings/messages.html similarity index 56% rename from app/templates/messages.html rename to app/templates/settings/messages.html index 4ec08dc..63e2fca 100644 --- a/app/templates/messages.html +++ b/app/templates/settings/messages.html @@ -2,9 +2,10 @@ {% block title %}Messages — roledesk{% endblock %} {% block content %} -

    Messages

    +

    Settings

    +{% include "settings/_tabs.html" %} -

    Everything the server has said that nobody has cleared, newest first. A toast fades and is raised as often as not while no tab is open; this is where it is found again, with its fix, its raw error, and how many times it has been said. A row goes when you clear it, or a fortnight after it was last said.

    +

    What the server said that nobody has cleared yet, newest first, with the fix when there is one. A message goes when you clear it, or two weeks after it was last said.

    diff --git a/app/templates/jobs.html b/app/templates/settings/pulls.html similarity index 50% rename from app/templates/jobs.html rename to app/templates/settings/pulls.html index 5298c7a..7fcc32e 100644 --- a/app/templates/jobs.html +++ b/app/templates/settings/pulls.html @@ -1,15 +1,16 @@ {% extends "base.html" %} -{% block title %}Jobs — roledesk{% endblock %} +{% block title %}Pulls — roledesk{% endblock %} {% block content %} -

    Jobs

    +

    Settings

    +{% include "settings/_tabs.html" %} -

    pull runs the whole chain: every board, then extract, embed and score. extract, embed and score run one stage on their own. The buttons come from /api/jobs/kinds, so a new @job under app/jobs/ appears here without an edit.

    +

    Every 6 hours roledesk reads every board and search, then fills in what each posting says, embeds and scores. Change the cadence below.

    Start something

    - loading the job kinds… + loading…
    @@ -22,10 +23,20 @@ is always there is furniture — and a card with nothing in it and nothing above it reads as something that failed to load. #}

    What is running

    -

    Nothing at the moment. Press one of the buttons above.

    +

    Nothing at the moment.

    + +
    + {# The element and its script are the scheduler's own, served by its own + router — see pipeline/web/static/schedules.js. Two lines, as with jobs. + A cadence is typed as `every 15m`, `every 6h`, `daily at 06:00` or + `weekly mon 07:00`; its add row's placeholder shows two. #} +

    Schedule

    + + +
    {% endblock %} {% block scripts %} diff --git a/app/templates/settings/ranking.html b/app/templates/settings/ranking.html new file mode 100644 index 0000000..9cf5ffd --- /dev/null +++ b/app/templates/settings/ranking.html @@ -0,0 +1,39 @@ +{% extends "base.html" %} +{% block title %}Ranking — roledesk{% endblock %} + +{# One ranking in the UI, whatever the `agents` table holds: `static/ranking.js` + edits the first enabled agent and makes one on the first save if there is + none. No list, no New, no Delete. #} +{% block content %} +

    Settings

    +{% include "settings/_tabs.html" %} + +

    Describe the role you want. Best match on the Roles tab puts the postings closest to this first, and saving reorders them all.

    + + + + +
    + How much each counts + + + +
    +
    + Advanced + +
    +
    + +
    +

    + +{% endblock %} + +{% block scripts %} + +{% endblock %} diff --git a/app/templates/sources.html b/app/templates/settings/searches.html similarity index 91% rename from app/templates/sources.html rename to app/templates/settings/searches.html index f4fb6f7..35fc32c 100644 --- a/app/templates/sources.html +++ b/app/templates/settings/searches.html @@ -1,12 +1,16 @@ {% extends "base.html" %} -{% block title %}Sources — roledesk{% endblock %} +{% block title %}Searches — roledesk{% endblock %} {% block content %} +

    Settings

    +{% include "settings/_tabs.html" %} + +{# Still the old Sources page whole, company boards and prune included, until + the Companies page takes those over. #}
    -

    Sources

    +

    Where roles come from: saved searches find them at any company, and a followed company's board lists every role it has. Switching one off closes its roles until you switch it back on.

    -

    What a pull reads: saved searches, which find roles at any company, and company boards, which read every role one company lists. A pull runs on the Schedules tab's cadence. Switching one off closes its open roles at once; switched back on, the next pull reopens the ones it still finds.

    diff --git a/app/web/__init__.py b/app/web/__init__.py index 4b68540..adfb513 100644 --- a/app/web/__init__.py +++ b/app/web/__init__.py @@ -6,6 +6,9 @@ together. One door for all of it.""" from __future__ import annotations from app.web.api import router as api_router -from app.web.pages import STATIC_DIR, TABS, router as pages_router, templates +from app.web.pages import ( + MOVED, SETTINGS, STATIC_DIR, TABS, router as pages_router, templates, +) -__all__ = ["STATIC_DIR", "TABS", "api_router", "pages_router", "templates"] +__all__ = ["MOVED", "SETTINGS", "STATIC_DIR", "TABS", "api_router", "pages_router", + "templates"] diff --git a/app/web/pages.py b/app/web/pages.py index bcbcd2f..e6bf339 100644 --- a/app/web/pages.py +++ b/app/web/pages.py @@ -1,31 +1,38 @@ -"""The tabs: nine pages, declared once. +"""The pages: two tabs, a cog, and six settings pages behind it. -`TABS` is the whole navigation. `base.html` renders it, every page marks -itself active by its own `path`, and adding a tab is one entry here plus one -template. +`TABS` is the top bar, Roles and Applications, and `SETTINGS` is the row of +sub-tabs under the cog at `/settings/`: the setup pages first (Ranking, +Searches, Companies), the system ones after (Pulls, Messages, Account). +`base.html` renders the first, `settings/_tabs.html` the second, every page +marks itself active by its own `path`, and adding one is one entry here plus +one template. `/settings` itself is Ranking. -Every page is a shell. Roles, Applications, Agents and Companies are filled -and driven by `static/roles.js` from the JSON routes in `web/api.py`, Sources -by `static/sources.js`; Jobs, -Schedules and Account are shells around the modules' own elements. What the -server renders is only what a select needs to offer, so the options cannot -drift from what the store accepts. +Every page is a shell. Each is filled and driven by its own script under +`static/` from the JSON routes in `web/api.py`; Pulls and Account are shells +around the modules' own elements. What the server renders is only what a +select needs to offer, so the options cannot drift from what the store +accepts. + +The pages that were tabs before the settings shell (`/agents`, `/companies`, +`/sources`, `/jobs`, `/schedules`, `/messages`, `/account`) answer 301 to +their new place, query string kept, so a bookmark still lands. `FUNCTIONS` is `plugins.ats`'s, not `app`'s: the nine job functions are the classifier's vocabulary, and this reaches `plugins/` the same way `app.cli` does, since a plugin is app-agnostic and never reaches back into `app`. The -Jobindex areas and Adzuna countries on the Sources tab come from +Jobindex areas and Adzuna countries on the Searches page come from `plugins.search` for the same reason. """ from __future__ import annotations import sys +from collections.abc import Callable from dataclasses import dataclass from pathlib import Path from fastapi import APIRouter, Request -from fastapi.responses import HTMLResponse +from fastapi.responses import HTMLResponse, RedirectResponse from fastapi.templating import Jinja2Templates from app.models import REMOTE, STATUSES @@ -48,19 +55,33 @@ class Tab: template: str -#: The navigation, in order. One list; `base.html` is its only reader. +#: The top bar, in order. One list; `base.html` is its only reader. TABS: tuple[Tab, ...] = ( Tab("/", "Roles", "roles.html"), Tab("/applications", "Applications", "applications.html"), - Tab("/agents", "Agents", "agents.html"), - Tab("/companies", "Companies", "companies.html"), - Tab("/sources", "Sources", "sources.html"), - Tab("/jobs", "Jobs", "jobs.html"), - Tab("/schedules", "Schedules", "schedules.html"), - Tab("/messages", "Messages", "messages.html"), - Tab("/account", "Account", "account.html"), ) +#: The sub-tabs under the cog, in order; `settings/_tabs.html` renders them. +SETTINGS: tuple[Tab, ...] = ( + Tab("/settings/ranking", "Ranking", "settings/ranking.html"), + Tab("/settings/searches", "Searches", "settings/searches.html"), + Tab("/settings/companies", "Companies", "settings/companies.html"), + Tab("/settings/pulls", "Pulls", "settings/pulls.html"), + Tab("/settings/messages", "Messages", "settings/messages.html"), + Tab("/settings/account", "Account", "settings/account.html"), +) + +#: Where each page that used to be a tab lives now. +MOVED: dict[str, str] = { + "/agents": "/settings/ranking", + "/companies": "/settings/companies", + "/sources": "/settings/searches", + "/jobs": "/settings/pulls", + "/schedules": "/settings/pulls", + "/messages": "/settings/messages", + "/account": "/settings/account", +} + #: `value, label` for each select option. `FUNCTIONS` is already the value a #: role's `function` column holds; only the label is dressed up. FUNCTION_OPTIONS = [(f, f.replace("/", " / ").capitalize()) for f in FUNCTIONS] @@ -83,6 +104,7 @@ def asset(path: str) -> str: templates = Jinja2Templates(directory=str(TEMPLATE_DIR)) templates.env.globals["TABS"] = TABS +templates.env.globals["SETTINGS"] = SETTINGS templates.env.globals["asset"] = asset #: Out of the OpenAPI schema: these are pages. @@ -104,36 +126,50 @@ def applications(request: Request) -> HTMLResponse: return page(request, "applications.html", status_options=STATUS_OPTIONS) -@router.get("/agents", response_class=HTMLResponse) -def agents(request: Request) -> HTMLResponse: - return page(request, "agents.html") +@router.get("/settings", response_class=RedirectResponse) +def settings() -> RedirectResponse: + return RedirectResponse(SETTINGS[0].path, status_code=302) -@router.get("/companies", response_class=HTMLResponse) +@router.get("/settings/ranking", response_class=HTMLResponse) +def ranking(request: Request) -> HTMLResponse: + return page(request, "settings/ranking.html") + + +@router.get("/settings/searches", response_class=HTMLResponse) +def searches(request: Request) -> HTMLResponse: + return page(request, "settings/searches.html", areas=AREA_OPTIONS, + countries=COUNTRY_OPTIONS) + + +@router.get("/settings/companies", response_class=HTMLResponse) def companies(request: Request) -> HTMLResponse: - return page(request, "companies.html") + return page(request, "settings/companies.html") -@router.get("/sources", response_class=HTMLResponse) -def sources(request: Request) -> HTMLResponse: - return page(request, "sources.html", areas=AREA_OPTIONS, countries=COUNTRY_OPTIONS) +@router.get("/settings/pulls", response_class=HTMLResponse) +def pulls(request: Request) -> HTMLResponse: + return page(request, "settings/pulls.html") -@router.get("/jobs", response_class=HTMLResponse) -def jobs(request: Request) -> HTMLResponse: - return page(request, "jobs.html") - - -@router.get("/schedules", response_class=HTMLResponse) -def schedules(request: Request) -> HTMLResponse: - return page(request, "schedules.html") - - -@router.get("/messages", response_class=HTMLResponse) +@router.get("/settings/messages", response_class=HTMLResponse) def messages(request: Request) -> HTMLResponse: - return page(request, "messages.html") + return page(request, "settings/messages.html") -@router.get("/account", response_class=HTMLResponse) +@router.get("/settings/account", response_class=HTMLResponse) def account(request: Request) -> HTMLResponse: - return page(request, "account.html") + return page(request, "settings/account.html") + + +def _moved(to: str) -> Callable[[Request], RedirectResponse]: + """A 301 to `to`, carrying the query string, so `/agents?x=1` keeps it.""" + def redirect(request: Request) -> RedirectResponse: + query = request.url.query + return RedirectResponse(f"{to}?{query}" if query else to, status_code=301) + return redirect + + +for _old, _new in MOVED.items(): + router.add_api_route(_old, _moved(_new), methods=["GET"], + response_class=RedirectResponse) diff --git a/config.example.yaml b/config.example.yaml index 5a08873..d2592da 100644 --- a/config.example.yaml +++ b/config.example.yaml @@ -74,7 +74,29 @@ sources: {} # company. weights default to {fit: 0.6, recency: 0.2, affinity: 0.2}. A # country is an ISO code, filled from the board's location line; EU is a role # open anywhere in Europe. +# The UI edits the first enabled one as "the ranking"; with more than one, the +# order menu on Roles lists them by name. Two more, beside the starter in +# config.yaml: agents: [] +# - name: Remote from Europe +# intent: >- +# Staff or lead engineer role, fully remote from Europe. Platform and +# infrastructure work, distributed systems, developer tooling, technical +# leadership across teams. +# gates: +# - {field: remote, values: [remote], mode: require} +# - {field: country, values: [AT, BE, BG, HR, CY, CZ, DK, EE, FI, FR, DE, GR, HU, IE, IT, +# LV, LT, LU, MT, NL, PL, PT, RO, SK, SI, ES, SE, IS, LI, NO, +# GB, CH, EU], mode: require} +# - name: Europe hybrid +# intent: >- +# Senior backend or platform engineer in a European tech hub, hybrid or +# remote-first. Python and Go, distributed systems, cloud infrastructure. +# gates: +# - {field: country, values: [AT, BE, BG, HR, CY, CZ, DK, EE, FI, FR, DE, GR, HU, IE, IT, +# LV, LT, LU, MT, NL, PL, PT, RO, SK, SI, ES, SE, IS, LI, NO, +# GB, CH, EU], mode: require} +# - {field: remote, values: [hybrid, remote], mode: prefer, weight: 0.05} # Starter searches, imported once while there are no `search` subscriptions. # provider is jobindex (Denmark, no key: q, area, pages) or adzuna (the UK and diff --git a/config.yaml b/config.yaml index a09993b..a1ddd8a 100644 --- a/config.yaml +++ b/config.yaml @@ -20,9 +20,10 @@ extract: embed: model: sentence-transformers/all-MiniLM-L6-v2 sources: {} -# Starter search agents, imported once into an empty table. Edit them on the -# Agents tab afterwards; this list is not read again. EU in a country gate is a -# role open anywhere in Europe ("Remote - Europe", "EMEA"). +# The starter ranking, imported once into an empty table. Edit it under +# Settings, Ranking afterwards; this list is not read again. EU in a country +# gate is a role open anywhere in Europe ("Remote - Europe", "EMEA"). Two more +# are in config.example.yaml. agents: - name: Copenhagen engineering intent: >- @@ -32,25 +33,6 @@ agents: gates: - {field: country, values: [DK], mode: require} - {field: remote, values: [hybrid, remote], mode: prefer, weight: 0.05} - - name: Remote from Europe - intent: >- - Staff or lead engineer role, fully remote from Europe. Platform and - infrastructure work, distributed systems, developer tooling, technical - leadership across teams. - gates: - - {field: remote, values: [remote], mode: require} - - {field: country, values: [AT, BE, BG, HR, CY, CZ, DK, EE, FI, FR, DE, GR, HU, IE, IT, - LV, LT, LU, MT, NL, PL, PT, RO, SK, SI, ES, SE, IS, LI, NO, - GB, CH, EU], mode: require} - - name: Europe hybrid - intent: >- - Senior backend or platform engineer in a European tech hub, hybrid or - remote-first. Python and Go, distributed systems, cloud infrastructure. - gates: - - {field: country, values: [AT, BE, BG, HR, CY, CZ, DK, EE, FI, FR, DE, GR, HU, IE, IT, - LV, LT, LU, MT, NL, PL, PT, RO, SK, SI, ES, SE, IS, LI, NO, - GB, CH, EU], mode: require} - - {field: remote, values: [hybrid, remote], mode: prefer, weight: 0.05} # Starter searches, imported once while there are none. Each is a query on a # job board that spans companies (plugins/search.py); `app searches add` adds # more. area 1 is Jobindex's Region Hovedstaden. An adzuna search needs a key: diff --git a/tests/test_score.py b/tests/test_score.py index 970bf93..ad9741c 100644 --- a/tests/test_score.py +++ b/tests/test_score.py @@ -331,10 +331,18 @@ def test_the_shipped_starter_agents_validate() -> None: from app import config as config_mod agents = config_mod.load(ROOT / "config.yaml").agents - assert [a.name for a in agents] == ["Copenhagen engineering", "Remote from Europe", - "Europe hybrid"] + assert [a.name for a in agents] == ["Copenhagen engineering"] + # The two commented examples in config.example.yaml, uncommented, so they + # still validate when somebody copies them. + import yaml + lines = (ROOT / "config.example.yaml").read_text(encoding="utf-8").splitlines() + start = lines.index("agents: []") + 1 + block = [line[2:] for line in lines[start:] if line.startswith("# ")] + examples = [AgentSeed.model_validate(a) for a in yaml.safe_load("\n".join(block))] + assert [a.name for a in examples] == ["Remote from Europe", "Europe hybrid"] # Small enough that a prefer gate breaks ties rather than overrides fit. - assert {g.weight for a in agents for g in a.gates if g.mode == "prefer"} == {0.05} + assert {g.weight for a in [*agents, *examples] + for g in a.gates if g.mode == "prefer"} == {0.05} def test_the_shipped_starter_searches_validate() -> None: diff --git a/tests/test_web.py b/tests/test_web.py index 5c69407..141c86d 100644 --- a/tests/test_web.py +++ b/tests/test_web.py @@ -15,7 +15,7 @@ from fastapi.testclient import TestClient from app.config import Config, ServerConfig from app.main import create_app from app.storage import Store -from app.web import TABS +from app.web import MOVED, SETTINGS, TABS from auth import AuthConfig from desk.models import Item @@ -200,43 +200,93 @@ def test_set_status_validates_and_writes_an_event( # -------------------------------------------------------------------- tabs -def test_every_tab_renders_with_the_whole_nav(client: TestClient) -> None: - assert [t.label for t in TABS] == ["Roles", "Applications", "Agents", "Companies", - "Sources", "Jobs", "Schedules", "Messages", "Account"] - for tab in TABS: +def test_every_page_renders_with_the_whole_nav(client: TestClient) -> None: + assert [t.label for t in TABS] == ["Roles", "Applications"] + assert [t.label for t in SETTINGS] == ["Ranking", "Searches", "Companies", "Pulls", + "Messages", "Account"] + assert all(t.path.startswith("/settings/") for t in SETTINGS) + for tab in (*TABS, *SETTINGS): res = client.get(tab.path) assert res.status_code == 200, f"{tab.path} answered {res.status_code}" assert "roledesk" in res.text for other in TABS: assert f">{other.label}" in res.text + assert 'href="/settings" class="icon' in res.text + assert '' in res.text -def test_each_roledesk_tab_is_a_shell_for_roles_js(client: TestClient) -> None: - for path, container in [("/", 'id="roles-list"'), - ("/applications", 'id="applications-list"'), - ("/agents", 'id="agents-list"'), - ("/companies", 'id="companies-list"')]: +def test_the_cog_and_one_sub_tab_are_current_on_a_settings_page(client: TestClient) -> None: + page = client.get("/settings/pulls").text + assert 'class="icon active"' in page + for tab in SETTINGS: + assert f">{tab.label}" in page + assert page.count('aria-current="page"') == 1 + current = page.index('aria-current="page"') + assert page.rindex('href="', 0, current) == page.index('href="/settings/pulls"') + assert 'class="icon active"' not in client.get("/").text + + +def test_settings_is_ranking(client: TestClient) -> None: + res = client.get("/settings", follow_redirects=False) + assert res.status_code == 302 and res.headers["location"] == "/settings/ranking" + + +@pytest.mark.parametrize(("old", "new"), sorted(MOVED.items())) +def test_an_old_tab_moves_permanently_and_keeps_its_query( + client: TestClient, old: str, new: str) -> None: + res = client.get(old, follow_redirects=False) + assert res.status_code == 301 and res.headers["location"] == new + res = client.get(f"{old}?agent=3&q=a+b", follow_redirects=False) + assert res.status_code == 301 and res.headers["location"] == f"{new}?agent=3&q=a+b" + assert client.get(old).status_code == 200 + + +def test_each_page_loads_only_its_own_script(client: TestClient) -> None: + scripts = {"roles.js", "applications.js", "ranking.js", "companies.js", "sources.js", + "jobs.js", "messages.js"} + for path, container, script in [ + ("/", 'id="roles-list"', "roles.js"), + ("/applications", 'id="applications-list"', "applications.js"), + ("/settings/ranking", 'id="ranking-form"', "ranking.js"), + ("/settings/searches", 'id="searches-list"', "sources.js"), + ("/settings/companies", 'id="companies-list"', "companies.js"), + ("/settings/pulls", 'id="kinds"', "jobs.js"), + ("/settings/messages", 'id="notices"', "messages.js")]: page = client.get(path).text - assert container in page and "/static/roles.js" in page + assert container in page, path + assert [s for s in scripts if f"/static/{s}" in page] == [script], path # toasts.js before app.js before the page's own script: `api()` needs - # `window.toast`, and roles.js needs `api()`. - assert page.index("toasts.js") < page.index("app.js") < page.index("roles.js") + # `window.toast`, and every page script needs `api()` and the helpers. + assert page.index("toasts.js") < page.index("app.js") < page.index(f"/static/{script}") + assert client.get(f"/static/{script}").status_code == 200 assert "ROLEDESK_STATUSES" in client.get("/applications").text - assert client.get("/static/roles.js").status_code == 200 -def test_the_sources_tab_is_a_shell_for_sources_js(client: TestClient) -> None: - page = client.get("/sources").text +def test_the_ranking_page_edits_one_ranking(client: TestClient) -> None: + page = client.get("/settings/ranking").text + assert 'id="a-intent"' in page and " None: + page = client.get("/settings/searches").text assert 'id="searches-list"' in page and 'id="boards-list"' in page - assert page.index("app.js") < page.index("sources.js") assert 'value="1" selected>Region Hovedstaden' in page # from plugins.search - assert client.get("/static/sources.js").status_code == 200 def test_the_modules_bring_their_own_elements(client: TestClient) -> None: - assert "" in client.get("/jobs").text - assert "" in client.get("/schedules").text - assert "" in client.get("/account").text + pulls = client.get("/settings/pulls").text + assert pulls.index("") < pulls.index("") + assert "" in client.get("/settings/account").text + + +def test_the_install_files_are_served(client: TestClient) -> None: + manifest = client.get("/static/manifest.json").json() + assert manifest["name"] == "roledesk" and manifest["display"] == "standalone" + for icon in manifest["icons"]: + assert client.get(icon["src"]).status_code == 200 + assert client.get("/static/apple-touch-icon.png").status_code == 200 def test_pull_is_declared_every_six_hours(client: TestClient) -> None: @@ -275,7 +325,7 @@ def test_a_locked_app_shuts_every_tab_and_the_api( config = Config(server=ServerConfig(host="127.0.0.1", port=0), database=tmp_path / "locked.db", auth=AuthConfig(enabled="always")) with TestClient(create_app(config), follow_redirects=False) as locked: - for tab in TABS: + for tab in (*TABS, *SETTINGS): assert locked.get(tab.path).status_code == 303 assert locked.get("/api/roles").status_code == 401 assert locked.get("/health").status_code == 200