Compare commits

..
26 Commits
Author SHA1 Message Date
retoor 5b117b5682 Gateway returns 404 for unknown models instead of default fallback 2026-11-28 12:00:14 +01:00
retoor 2d34cab61b Render link preview cards on the server with text and images 2026-11-28 11:36:49 +01:00
retoor 9b5a37f2ea Add site link preview cards with shared unfurl endpoint 2026-11-28 11:14:29 +01:00
retoor 9e174894f0 progress. 2026-11-28 10:55:54 +01:00
retoor 46a85232f8 Wire whole media catalog: real Pruna flow plus status/files consent fix 2026-11-27 09:50:15 +01:00
retoor 5ea7701c1a Restyle MCP tab with shared panel vocabulary 2026-11-26 21:20:55 +01:00
retoor 3774f1dd23 Fix MCP tab styling and panel state after generate/revoke 2026-11-26 20:57:35 +01:00
retoor c50f5e81a5 Add per-user MCP endpoint backed by the Devii catalog 2026-11-26 20:48:55 +01:00
retoor 3366e0372c Add bigrefs store, project blob sweep, and container lock/ref-action support
- New devii bigrefs store + controller with session registry wiring
- New project_blob_sweep service for binary blob lifecycle management
- Rework project_files blob storage with capacity guards and dedup
- Add container distributed locks and ref_actions dispatcher support
- Document container and devii services in CLAUDE.md files
- Cover new behavior with unit tests
2026-11-23 14:28:20 +01:00
retoorandClaude Sonnet 5.5 fc9e09c47a Keep hidden post links out of activity lists and battles
Comments on hidden posts no longer surface on the commenter's profile
activity or devRant profile, battles on hidden posts are unlisted and
gated by post visibility. Test helper opens action menus after an
instant scroll so the menu is not closed by the scroll listener.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-19 09:00:29 +01:00
retoorandClaude Sonnet 5.5 6a5ed75072 Test the unread count in the push payload and its APNs badge mapping
Provider tests cover aps.badge, the invalid values that leave it out
and the unchanged Web Push body. Funnel tests cover the count for
single notifications, grouped and ungrouped users and an in-app channel
that is off. Written in the existing unit style; not executed.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-15 04:06:15 +01:00
retoorandClaude Sonnet 5.5 585fab74a6 Document the unread count in the push payload
Specifies unread and aps.badge in the push and utils notes, records
the notifications ensure-block and the index that serves the unread
read in the database note, and updates the README and the push API
docs.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-15 04:05:28 +01:00
retoorandClaude Sonnet 5.5 2452f9e85b Ensure the notifications column set in init_db like messages and push_registration
notifications was filtered and indexed on user_uid and read without an
ensure-block, so a partial first insert could create it with a reduced
schema. The block mirrors the messages one and the table joins
FILTERED_COLUMNS. idx_notifications_user_read already serves the unread
count the push payload now reads.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-15 04:05:08 +01:00
retoorandClaude Sonnet 5.5 d815fbe9f8 APNs maps the unread count to aps.badge
The shared payload key unread becomes aps.badge when it is a
non-negative integer. A missing or invalid value leaves the key out, so
the welcome probe and any older caller keep their previous body.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-15 04:03:29 +01:00
retoorandClaude Sonnet 5.5 376c6ba99d Push payload carries the recipient's unread notification count
The notification funnel computes count_unread_groups right after the
in-app insert and adds it to the shared push payload as unread, only
when a push is actually sent. Providers decide how to present it.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-15 04:03:10 +01:00
retoorandClaude Sonnet 5.5 8b45a515f2 Remove unused vendored chart.js, templates load chartjs from static/vendor
Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-15 01:51:54 +01:00
retoorandClaude Sonnet 5.5 695be8ba9a Docs: update root CLAUDE.md, DEFINITION_OF_DONE, README and gitignore
Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-15 01:51:53 +01:00
retoorandClaude Sonnet 5.5 1a9201cb91 Admin pages: one shared specification, builders, fragments, caps and live refresh
Adds admin_sections registry, shared admin partials, WorkspaceList, admin CLAUDE.md spec,
capped node/flag listings, and api/unit tests enforcing the spec.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-15 01:50:50 +01:00
retoorandClaude Sonnet 5.5 8d4d06de61 Gateway: refine routing, vision and request handling, update docs and tests
Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-15 01:50:50 +01:00
retoorandClaude Sonnet 5.5 8e36807926 Gateway: per-target circuit breaker trips on first AI error and notifies all admins
Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-14 01:07:47 +01:00
retoorandClaude Sonnet 5.5 151476125f Gateway: auto-resolve request shape per provider and model
An upstream that rejects a key the gateway adds (e.g. thinking) now gets
retried with other shapes on a parsable 400/422; the working method is
stored per (provider, target model) and applied first-try from then on.
Fallback attempts are re-shaped per attempt. Admin list/reset, Devii
tools, audit event and ledger resolved_method included.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-13 11:34:26 +01:00
retoorandClaude Sonnet 5.5 3f6e83c753 Position the More action menu under its trigger and align form-wrapped items
Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-12 15:42:48 +01:00
retoor 8a48e3ef85 Keep composers usable, group actions and notifications, and drop the tool-count cap
Comment and post layouts stay full width on small screens. Secondary actions live in the More menu. Notifications can be grouped and throttled, and Enter can submit when that profile setting is on. Emulated-tool models accept large catalogs, with reserved names aliased on the wire and the catalog cached per owner. A dropped service-worker navigation is retried once. The test server waits 120s to finish importing before it is stopped.
2026-11-12 15:29:27 +01:00
retoor dbdd0d29dd Auth: username+password, email+password and API key everywhere; key returns carry username and email
POST /auth/login (form and JSON) now accepts the username in the email field, like HTTP Basic and POST /auth/token always did; the token endpoint no longer lowercases the identifier before the username lookup, fixing mixed-case usernames. The login field is relabelled and type=text so browsers accept a username.

Every JSON return of the personal API key now also returns the account username and email: the profile JSON gains a can_view_api_key-gated email beside api_key (username already rides profile_user), and POST /profile/regenerate-api-key returns {api_key, username, email}. A client holding only its DEVPLACE_API_KEY value can now fetch its full account via GET /profile in one call.

Documented fully: authentication prose page (three credentials, precedence, DEVPLACE_API_KEY, account fetch, separate DevRant/WebSocket auth domains), new auth-token docs_api card, regenerated-key sample, conventions, README, CLAUDE.md, OpenAPI description, corrected profile key hint. Summary in changes.md (left unversioned per request).

Tests: username/mixed-case/uppercase-email login and token cases, API-key account fetch via X-API-KEY and Bearer, owner/admin vs stranger/guest email gating, regenerate shape, browser login by username. Failing-first observed red, green after.
2026-11-11 16:07:43 +01:00
retoor 33eb090e27 Slim root CLAUDE.md to global-only rules, move subsystem detail to nested files 2026-11-08 20:33:09 +01:00
retoor 078d0657ff Merge pull request 'Messages: Facebook-style Chats panel and docked chat windows' (#191) from blindxfish/devplacepy:messenger-chat into master
Reviewed-on: retoor/devplacepy#191
2026-11-07 18:10:30 +01:00
318 changed files with 15800 additions and 2274 deletions
+2
View File
@@ -1,3 +1,5 @@
aura*
.*
.docs
.dpc
.devplace
+31 -165
View File
@@ -2,19 +2,22 @@
This file provides guidance to Claude Code when working with code in this repository. It holds only what applies regardless of which part of the codebase is being touched. Deep, subsystem-specific detail lives in nested `CLAUDE.md` files placed inside the relevant directory - Claude Code auto-loads a nested file only when a file under that directory is read or edited, so the always-loaded cost of this repository stays proportional to this file alone. See "Subsystem map" below for the full list.
It is a big project, whatever you are implementing, it is probably done before. You should look it up and match the implementation structurely and visually. For inconsistency there is zero tolerance policy. Develop dry, kiss, re-usable code, consistent with existing implementation. Literally always try to find relatable examples before making a modification. If no-example exists, explain to user what is the case and let user decide what to do and how to continue.
It is a big project, whatever you are implementing, it is probably done before. You should look it up and match the implementation structurely and visually. For inconsistency there is zero tolerance policy. Develop dry, kiss, re-usable code, consistent with existing implementation. Literally always try to find relatable examples before making a modification. If no-example exists, explain to user what is the case and let user decide what to do and how to continue.
The completion contract for every change is [DEFINITION_OF_DONE.md](./DEFINITION_OF_DONE.md): universal gates, test obligations, the four-layer rigor procedure for spendable resources and races, per-subsystem rules, and the final checklist. A change is done only when every applicable gate in it passes.
## Project
DevPlace is a server-rendered social network for developers. FastAPI backend serves Jinja2 templates with pure ES6 module JavaScript on the frontend. SQLite via the `dataset` library (auto-syncs schema). No JS framework, no NPM, no JWT.
- **Database:** `dataset` (auto-syncs schema, uses `uid` for PKs). SQLite.
- **Auth:** `session` cookie, plus `X-API-KEY` / `Authorization: Bearer <api_key>` / HTTP Basic (username-or-email:password) - all resolved in `get_current_user`. PBKDF2-SHA256 via passlib. No JWT. Every user has an `api_key` (uuid7), set at signup and backfilled in `init_db`/`devplace apikey backfill`. Docs site at `/docs` (`routers/docs/` package, `DOCS_PAGES` registry; FastAPI's Swagger is moved to `/swagger` so `/docs` is free).
- **Auth:** three account credentials: username+password, email+password, personal `api_key`. All password exchanges (`POST /auth/login` form+JSON, `POST /auth/token`, HTTP Basic, devRant `POST /api/users/auth-token`) take username-or-email as identifier (username case-sensitive, email lowered); the `api_key` rides `X-API-KEY` / `Authorization: Bearer` (client-side `DEVPLACE_API_KEY` env var holds its value, injected into containers) plus `session` cookie - all resolved in `get_current_user` (order: session, X-API-KEY, Bearer, Basic; headers also try DevRant/access tokens). Every JSON return of the personal key also returns `username`+`email` (login/signup `data`, gated `ProfileOut.email` beside `api_key`, regenerate), so `GET /profile` with an API key is the whoami/account fetch; never add `email` to public `UserOut`. PBKDF2-SHA256 via passlib. No JWT. Every user has an `api_key` (uuid7), set at signup and backfilled in `init_db`/`devplace apikey backfill`. Docs site at `/docs` (`routers/docs/` package, `DOCS_PAGES` registry; FastAPI's Swagger is moved to `/swagger` so `/docs` is free).
- **Static:** `devplacepy/static/` mounted at `/static`; URLs are boot-versioned (`/static/v<ts>/...`) via `static_url`/`assetUrl` and served immutable for a year.
- **Templates:** `devplacepy/templates/`. Shared `templates` instance from `devplacepy.templating` - all routers import from there, never instantiate their own.
- **Ports:** 10500 (dev), 10501 (tests; the serial suite uses a single uvicorn subprocess).
- **Username:** letters, numbers, hyphens, underscores only, 3-32 chars. **Password:** minimum 6 chars.
- **Avatars:** Multiavatar SVG generated locally from a seed in <5ms, in-memory cache cleared on restart, fallback to initial-based SVG on error. URL `/avatar/multiavatar/{seed}?size={size}`. The seed is per-user: the nullable `users.avatar_seed` column overrides the username. Always resolve it through the single null-safe choke point `avatar.avatar_seed(user)` (a Jinja global) - `user.get("avatar_seed") or user.get("username")` - never read `avatar_seed` or pass `username` to `avatar_url(...)` directly; every render site (the `_avatar_link.html` partial, `og_image`, the devRant avatar payload, etc.) goes through it. Regenerate is owner-or-admin at `POST /profile/{username}/regenerate-avatar` (writes a fresh `generate_uid()`, invalidates the user cache, audits `profile.avatar.regenerate`); the old seed is never stored, so the old avatar cannot return. Devii tool `regenerate_avatar` (`CONFIRM_REQUIRED`).
- **Avatars:** Multiavatar SVG generated locally at `/avatar/multiavatar/{seed}?size={size}`. Seed resolution, regenerate flow, and the owner-or-admin rule live in `devplacepy/templates/CLAUDE.md` ("Avatar seed choke point").
## Commands
@@ -55,60 +58,12 @@ devplace token list <username> # list a user's active access tokens
devplace token revoke <token_uid> # revoke a single access token by uid
devplace token revoke-all <username> # revoke all access tokens for a user
devplace token prune # soft-delete all expired access tokens
devplace news clear # delete all news rows
devplace news sanitize # strip HTML from news descriptions/content
devplace attachments prune # remove orphan attachment records/files
devplace system prune [--dry-run] # safe but aggressive: purges soft-deleted attachment/project-file blobs, sweeps blob files with zero DB reference at all (e.g. left by an interrupted/racing sync), and GCs orphaned container workspace dirs
devplace devii reset-quota <username> # reset one user's rolling 24h AI quota
devplace devii reset-quota --guests # reset every guest quota
devplace devii reset-quota --all # reset every quota (users and guests)
devplace devii tasks list [--all] # list scheduled Devii tasks and their owners
devplace devii tasks disable <uid> # disable one scheduled task
devplace devii tasks prune # disable every task whose owner may not schedule
devplace gateway quota list # list AI gateway quota rules and current 24h spend
devplace gateway quota set --limit-usd N [--owner-kind K] [--owner-id ID] [--app-reference APP] [--label L] [--uid UID]
devplace gateway quota delete <uid> # delete a quota rule
devplace gateway quota reset [--owner-kind K] [--owner-id ID] [--app-reference APP] # clear the counted 24h spend (keeps the usage history)
devplace zips prune # delete expired zip archives + job rows
devplace zips clear # delete every zip archive + job row
devplace forks prune # delete expired completed fork job rows (forked projects persist)
devplace forks clear # delete every fork job row (forked projects persist)
devplace community discover <query> [--run] [--relearn] [--dry-run] # discover, learn and generate collectors for an external community
devplace community run <slug> [--dry-run] # run a community's collectors through the sync API
devplace community login <slug> [--login-user U] [--login-email E] [--login-password P | --clear] # store or remove the account used to log in
devplace community list # list communities
devplace messaging prune-tickets # delete expired WebSocket auth tickets (ws_tickets)
devplace seo prune # delete expired SEO audit reports + job rows
devplace seo clear # delete every SEO audit report + job row
devplace seo-meta prune # delete expired SEO metadata job rows (generated metadata persists)
devplace seo-meta clear # delete every SEO metadata job row (generated metadata persists)
devplace deepsearch prune # delete expired DeepSearch sessions + job rows + collections
devplace deepsearch clear # delete every DeepSearch session + job row + collection
devplace isslop analyze <url> # run a AI usage analysis from the terminal (report persists)
devplace isslop prune # delete expired AI usage analysis job rows (analyses + reports persist)
devplace isslop clear # delete every AI usage analysis, its report and job rows
devplace quiz prune # delete abandoned/expired quiz attempts older than the retention window
devplace game market prune # delete Code Farm market tick buckets older than the tracking window
devplace game steals prune # delete Code Farm raid records older than the raid-efficiency window
devplace game era status # show the current Code Farm Era
devplace game era start <name> [--days N] # start a Code Farm Era (default 28 days)
devplace game era end # end the running Code Farm Era (ranks, awards Stars, records results)
devplace accounts pending # list deleted accounts awaiting their purge
devplace accounts prune # permanently purge accounts past the deletion grace window (--dry-run to preview)
devplace backups list # list recorded backups
devplace backups run <database|uploads|keys|full> # enqueue a backup (processed by the running server)
devplace backups prune # remove backup records whose archive file is missing
devplace backups clear # delete every backup archive + record
devplace containers list # list container instances
devplace containers reconcile # run one reconcile pass (desired vs docker ps)
devplace containers prune # reap orphan containers + dangling images
devplace containers prune-builds # remove legacy per-project images + clear dockerfiles/builds tables (one-time)
devplace containers gc-workspaces # remove workspace dirs with no instances
devplace emoji-sync # regenerate static/js/emoji-shortcodes.js from the emoji library (run after an emoji dep bump)
devplace embeds-sync # regenerate static/js/embed-spec.js from devplacepy/embeds.py (run after editing the embed table)
devplace migrate-data # relocate legacy runtime files into data/ (idempotent; --dry-run to preview)
```
Per-subsystem commands live in the nested file: `devplace devii ...` (Devii), `devplace gateway quota ...` (AI gateway), `devplace backups ...` (backup service), `devplace containers ...` (container manager), `devplace news ...` (news service), `devplace community ...` (community discovery), `devplace messaging prune-tickets` (messaging), `devplace {zips|forks|seo|seo-meta|deepsearch|isslop} ...` (async jobs), `devplace quiz prune` (quizzes), `devplace game ...` (Code Farm), `devplace accounts ...` (moderation), `devplace apikey backfill`, `devplace attachments prune`, `devplace system prune` (database), `devplace emoji-sync` (frontend JS), `devplace embeds-sync` (templates).devplace migrate-data # relocate legacy runtime files into data/ (idempotent; --dry-run to preview)
```
### Runtime data layout (single source of truth)
Every runtime/user-generated artifact lives under one root, `config.DATA_DIR` (`DEVPLACE_DATA_DIR`, default `<repo>/data`). `config.py` derives every runtime path from it and lists them in the `DATA_PATHS` registry; `ensure_data_dirs()` creates the whole tree before anything is written. **No module computes a runtime path from scratch** - import the constants (`UPLOADS_DIR`, `ATTACHMENTS_DIR`, `PROJECT_FILES_DIR`, `ZIPS_DIR`, `ZIP_STAGING_DIR`, `FORK_STAGING_DIR`, `KEYS_DIR`, `BOT_DIR`, `LOCKS_DIR`, `CONTAINER_WORKSPACES_DIR`, `DEVII_TASKS_DB`, `DEVII_LESSONS_DB`, `VAPID_*_FILE`, `SERVICE_LOCK_FILE`, `INIT_LOCK_FILE`). Uploads are physically under `data/uploads/` but still served at the unchanged `/static/uploads/` URL. Stored DB values for attachments/project files are relative (`directory` + `stored_name`), so no DB rewrite is ever needed for a layout change.
@@ -142,6 +97,7 @@ Nested `CLAUDE.md` files (loaded automatically by Claude Code only when a file i
| Path | Covers |
|------|--------|
| `devplacepy/routers/CLAUDE.md` | Full URL prefix map, route aggregation rules, HTML/JSON negotiation, FastAPI patterns, gists, feed/listing features, engagement (reactions/bookmarks/polls/heatmap/follow/block-mute), SEO implementation, polymorphic comments/votes |
| `devplacepy/routers/admin/CLAUDE.md` | The admin page specification (A1-A11): rendering, response contract, page anatomy, class vocabulary, time, caps, remote work, live refresh, assets, the nav registry, responsiveness |
| `devplacepy/routers/projects/CLAUDE.md` | Project detail page, virtual filesystem routes, visibility/read-only UI, deletion confirmation |
| `devplacepy/routers/docs/CLAUDE.md` | The `/docs` documentation site: `DOCS_PAGES`, audience tiers, prose rendering, API tester |
| `devplacepy/routers/devrant/CLAUDE.md` | devRant-compatible REST API (`/api`) |
@@ -191,75 +147,23 @@ The AI usage analyzer (`devplace isslop analyze`, the `/tools/isslop` job servic
### Routing layout
Routers in `devplacepy/routers/` are organised as a **directory tree that mirrors the endpoint (URL) path**, exactly like `tests/`. A domain with a single resource stays one flat file (`feed.py`, `posts.py`, ...); a domain with several sub-resources is a **package directory** split one file per sub-resource. Each leaf declares its own `router = APIRouter()`; the package `__init__.py` aggregates with `router.include_router(...)`. A leaf owning the domain's collection-root (`""`) route must be the package's base router (FastAPI rejects an empty path under an empty prefix). Full elaboration, per-domain detail, and the complete deep-dive live in `devplacepy/routers/CLAUDE.md` - read it before touching routing. Compact map:
| Prefix | Router |
|--------|--------|
| `/auth` | auth/ package |
| `/feed`, `/posts`, `/comments` | flat files |
| `/topics` | topics.py - crawlable per-topic category index pages (`/topics` hub, `/topics/{topic}` listing) |
| `/projects`, `/projects/{slug}/files`, `/projects/{slug}/containers` | projects/ package - see `routers/projects/CLAUDE.md` |
| `/profile` | profile/ package (customization, notifications, ai-correction, ai-modifier, interactions, telegram, usage) |
| `/messages` | messages.py - see `services/messaging/CLAUDE.md` |
| `/notifications`, `/votes`, `/reactions`, `/bookmarks`, `/polls`, `/avatar`, `/follow`, `/leaderboard` | flat files |
| (none) | relations.py - block/mute |
| `/` | landing.py - home route (guests get the splash, users the dashboard) |
| `/admin`, `/admin/services`, `/admin/containers` | admin/ package |
| `/issues` | issues/ package - see `services/gitea/CLAUDE.md` |
| `/gists`, `/news`, `/uploads`, `/media` | flat files |
| `/giphy` | giphy.py - GIF picker backend (search, trending, attach), see `services/giphy/CLAUDE.md` |
| `/openai` | openai_gateway.py - see `services/openai_gateway/CLAUDE.md` |
| `/devii` | devii.py - see `services/devii/CLAUDE.md` |
| `/zips`, `/forks` | see `services/jobs/CLAUDE.md` |
| `/tools` | tools/ package (SEO diagnostics, DeepSearch, AI Usage Analyzer) - see `services/jobs/CLAUDE.md` |
| `/p/{slug}` | proxy.py - container ingress reverse proxy |
| `/xmlrpc` | xmlrpc.py - see `services/xmlrpc/CLAUDE.md` |
| `/api` | devrant/ package - see `routers/devrant/CLAUDE.md` |
| `/dbapi` | dbapi/ package, **primary-administrator-only, strictly READ-ONLY** - see `services/dbapi/CLAUDE.md` |
| `/sync` | sync/ package, **administrator only**, off by default - see `services/sync/CLAUDE.md` |
| `/game` | game/ package - see `services/game/CLAUDE.md` |
| `/reports`, `/admin/moderation`, `/workspaces` | reports.py, admin/moderation.py, workspaces.py - see `services/moderation/CLAUDE.md` |
| `/quizzes` | quizzes/ package - see `services/quiz/CLAUDE.md` |
| `/battles` | battles.py - see `services/opinionwar/CLAUDE.md` |
| (none) | push.py (web push/PWA), docs.py (see `routers/docs/CLAUDE.md`) |
| `/pubsub` | pubsub.py - see `services/pubsub/CLAUDE.md` |
| (none) | seo.py - `/robots.txt`, `/sitemap.xml` |
Routers in `devplacepy/routers/` are organised as a **directory tree that mirrors the endpoint (URL) path**, exactly like `tests/` (one segment per directory, last segment is the file; packages aggregate with `include_router`). A leaf owning the domain's collection-root (`""`) route must be the package's base router. Full URL prefix map, aggregation rules, HTML/JSON negotiation, FastAPI patterns, and per-domain detail live in `devplacepy/routers/CLAUDE.md` - read it before touching routing. Sub-domain pages: `routers/projects/`, `routers/docs/`, `routers/devrant/` (each with its own nested file, see Subsystem map).
### Templates and frontend
- All routers MUST import the shared `templates` from `devplacepy.templating`. Do NOT instantiate `Jinja2Templates` per router.
- Templates extend `base.html`; page CSS via `{% block extra_head %}`, page JS via `{% block extra_js %}`.
- **Nav active state is the `nav_active` Jinja global**, never an inline path check.
- **Static asset URLs are boot-versioned:** never hardcode a bare `/static/...` href/src - use `static_url(path)` (Jinja) / `assetUrl(path)` (JS).
- All JS is ES6 modules, one class per file, instantiated as `app`. Custom web components (`dp-*` prefix) and shared frontend utilities (`Http`, `Poller`, `JobPoller`, `OptimisticAction`, `FloatingWindow`, `ScrollMemory`) are documented in `devplacepy/static/js/CLAUDE.md` - reuse them, never re-implement.
- CDN scripts in `base.html` MUST use `defer` or `type="module"`.
- Modal system, shared template partials (`_avatar_link.html`, `_user_link.html`, `_sidebar_search.html`) are documented in `devplacepy/templates/CLAUDE.md`.
All routers import the shared `templates` from `devplacepy.templating` (never instantiate per router); templates extend `base.html` (`extra_head`/`extra_js` blocks, `nav_active` global, boot-versioned `static_url`/`assetUrl`, deferred CDN scripts). JS is ES6 modules, one class per file, `dp-*` web components plus shared utilities (see `devplacepy/static/js/CLAUDE.md`). Modal system and shared partials: see `devplacepy/templates/CLAUDE.md`.
### Content rendering pipeline
**Server-rendered content and titles are rendered on the BACKEND for SEO** (`devplacepy/rendering.py`, Jinja globals `render_content(text)`/`render_title(text)`). This is the default for all content that exists at request time (post bodies, comments, news, project/gist descriptions, DM history, every content title). It mirrors the client pipeline using **mistune**: em-dash normalization, emoji shortcodes, GFM markdown (`escape=True` - the server XSS control), then a media pass turning bare URLs into embeds and `@mentions` into links. Both are `@lru_cache`d. Server-rendered code blocks get syntax highlighting + Copy button client-side via `ContentEnhancer`.
The CLIENT pipeline (`ContentRenderer.js`, `dp-content`/`dp-title`) is retained ONLY for genuinely live/dynamic content that does not exist at request time (live comments, DM bubbles, Devii/DeepSearch/Docs chat, planning report). Runs `marked` -> **`DOMPurify.sanitize`** (the client XSS control, fail-closed) -> highlight.js -> media/autolink. **Do NOT add `data-render` to server-rendered content - call `render_content`/`render_title` instead.**
**Emoji shortcodes are the full GitHub/Discord `:name:` set** (~4869 names), generated once from the `emoji` library by `rendering.py` `build_emoji_shortcodes()`; the frontend gets the identical map via the generated `static/js/emoji-shortcodes.js` (regenerate with `devplace emoji-sync` after bumping the dependency, never hand-edit).
**YouTube and YouTube Music embeds** have ONE specification, `devplacepy/embeds.py` (`EmbedParser.parse(url)` -> `Embed(kind, video_id, list_id, start, music)`, `EmbedParser.src(embed)`): exact host allowlists (never substring matching), query-order independent parsing, validated ids only (`[A-Za-z0-9_-]{11}` video, `{13,64}` list) so nothing but validated characters can reach an iframe `src`. YouTube Music has no player of its own and `music.youtube.com` sends `X-Frame-Options: SAMEORIGIN`, so a music link is YouTube's player (`www.youtube.com/embed/...`) wrapped in `<div class="embed-music">` with an "Open in YouTube Music" caption link; playlists/albums use `embed/videoseries?list=`. `/browse`, `/channel`, `/search`, `/library` carry no embeddable id and stay plain links. At most `MAX_MUSIC_EMBEDS` (3) music embeds render per content item, the overflow stays a plain link; plain YouTube is uncapped. `rendering.py` (`_youtube_embed`, per-`_MediaProcessor` `_EmbedBudget`) and `ContentRenderer.js` (`youtubeEmbed`, via `static/js/EmbedParser.js`) both follow it; the JS constants come from the generated `static/js/embed-spec.js` (`devplace embeds-sync`, never hand-edit). Never add another YouTube regex.
**Email anonymization:** both `_render_content` and `_render_title` mask email addresses to prevent doxing. `_mask_emails` in `rendering.py` runs on rendered text nodes only (inside `_transform_text`, `_MediaProcessor`, and `_InlineFilter` - never before mistune, or the `*` mask characters would be parsed as emphasis) and stars ~80% of the local part (keeps a leading 20%, minimum one visible char). Addresses on `molodetz.nl` (and its subdomains) are exempt and render verbatim.
**Em-dash normalization:** `_normalize_dashes` in `rendering.py` replaces all forms (em dash `\u2014`, en dash `\u2013`, and their HTML entities) with a hyphen BEFORE mistune processes the text. Runs inside `_render_content`/`_render_title` which are `@lru_cache`d, so each unique text is normalized once. No per-template overhead.
Server content renders on the backend for SEO (`render_content`/`render_title` in `devplacepy/rendering.py`); the client pipeline is only for live content (`DOMPurify` fail-closed). Full pipeline rules (emoji map, YouTube spec, email masking, dash normalization) live in `devplacepy/templates/CLAUDE.md` ("Content rendering pipeline").
### Auth
Session cookies named `session`, value a 64-char hex token. Passwords hashed with `pbkdf2_sha256` via passlib. `get_current_user(request)` returns user dict or `None`, per-process TTL cache (300s) keyed by token. `require_user(request)` raises a 303 redirect to `/` for guests; `require_admin(request)` redirects to `/feed` for non-admins. Public pages use `get_current_user` so guests can browse - POSTs are all guarded by `require_user`.
Session cookies named `session`, value a 64-char hex token. Passwords hashed with `pbkdf2_sha256` via passlib. `get_current_user(request)` returns user dict or `None`, per-process TTL cache (300s) keyed by token. `require_user(request)` raises a 303 redirect to `/` for guests; `require_admin(request)` redirects to `/feed` for non-admins. Public pages use `get_current_user` so guests can browse - POSTs are all guarded by `require_user`. Password exchanges (`routers/auth/login.py`, `routers/auth/token.py`) reuse the `LoginForm.email` field as username-or-email: look up `email=identifier.lower()` first, then `username=identifier` un-lowered (mirroring `_user_from_basic` semantics); never lower the identifier before the username lookup.
### Database
SQLite via `dataset.connect` with WAL + 30s busy timeout + 256MB mmap. **SQLite is synchronous by design and will never be made async (hard rule).** The `dataset`/SQLite layer is called directly inside async route handlers - the database is a local file tuned with WAL/`synchronous=NORMAL`/8MB page cache/256MB mmap, so queries are sub-millisecond and never meaningfully stall the event loop. Do NOT convert the database layer to async, wrap calls in a threadpool/`run_in_executor`/`to_thread`, or raise synchronous DB access as a blocking-I/O concern - this is a settled design decision, not open for revisiting.
`init_db()` is idempotent and **ensures the full column set of any table code filters on** before creating indexes - `dataset` gives a lazily-created table only the columns of its first insert, so a partial insert elsewhere would leave a reduced schema that later 500s with `no such column`. Full dataset rules, indexing conventions (the soft-delete planner trap), site settings, and the complete table list live in `devplacepy/database/CLAUDE.md`.
Runtime config lives in `site_settings`, read via `get_setting(key, default)`/`get_int_setting(key, default)` (60s TTL cache, cross-worker invalidated via `cache_state`). Batch helpers (`get_users_by_uids`, `get_comment_counts_by_post_uids`, `get_vote_counts`, `load_comments`) exist specifically to avoid N+1 - use them instead of per-row lookups.
**SQLite is synchronous by design and will never be made async (hard rule).** The `dataset`/SQLite layer is called directly inside async route handlers; never wrap it in a threadpool/`run_in_executor`/`to_thread` or raise sync DB access as a blocking-I/O concern. Dataset rules, indexing, soft delete, visibility spec, `site_settings`, batch helpers (use instead of N+1), and the table list live in `devplacepy/database/CLAUDE.md`.
### Per-user site customization (CSS/JS)
@@ -274,19 +178,19 @@ Users and guests inject their own CSS and JS, scoped to a page type or globally,
### Background task queue, AI correction/modifier, background services
`services/background.py` `background.submit(fn, *args)` is a generic fire-and-forget offload onto one per-worker `asyncio.Queue`; when the consumer isn't running (tests, full queue) it runs the callable **inline**, so audit/notification/XP writes stay deterministic for the suite while production defers them. It is the choke point for every audit-log write, every XP award, and every notification - handlers call `award_rewards`/`create_notification` directly (never wrap them in `background.submit`, that double-queues). AI content correction (opt-in, off by default) and the AI modifier (`@ai <instruction>` inline directive, on by default) rewrite user prose via the internal gateway; sync apply mode never blocks the event loop (`run_in_executor` + the `await_pending_corrections` middleware). `BaseService`/`ServiceManager` provide the async run loop and singleton registry for background services (`NewsService`, `GatewayService`, `DeviiService`, `BotsService`, container/audit/telegram reconcilers). Full detail on all of this, plus presence and the live view relay, is in `devplacepy/services/CLAUDE.md`.
`background.submit` offload, AI correction/modifier via the internal gateway, `BaseService`/`ServiceManager`, presence, and the live view relay: see `devplacepy/services/CLAUDE.md`.
### Container manager, Devii assistant, AI gateway, async jobs, audit log
DevPlace ships a Docker-backed **Container manager** (admin-only, one shared `ppy:latest` image, security-hardened rootless workflow via a `sudo` superclone and `aptroot`), the **Devii** in-platform agentic assistant (WebSocket terminal, per-owner-channel sessions, scheduler/reminders, self-learning lessons, user-defined virtual tools, self-configured behavior, browser-automation client tools), the **AI gateway** (`/openai/v1/*`, single point of truth for every AI call, per-user cost attribution, provider/model routing overlay), **async job services** (`JobService` base pattern: zip, fork, SEO diagnostics, SEO metadata generation, DeepSearch, AI Usage Analyzer), and an admin-only append-only **audit log** (`record`/`record_system` entrypoints, `events.md` catalogue of every recorded event key, never raises into the caller). These are among the largest subsystems in the codebase - read their dedicated nested `CLAUDE.md` files (see Subsystem map) before working in any of them; do not assume prior knowledge from this summary.
Container manager, Devii, AI gateway, async jobs, audit log: see their nested `CLAUDE.md` files (Subsystem map). Read the dedicated file before working in any of them.
### Telegram bot, email, devRant compatibility API, issue tracker
Devii is also reachable over **Telegram** (one supervised long-poller subprocess, `channel="telegram"` isolated conversation thread), can drive a user's own **external mailbox** over IMAP/SMTP (stdlib only, credentials in a soft-deletable table, SSRF-guarded), and DevPlace exposes a **devRant-compatible REST API** at `/api` (translates devRant requests onto native posts/comments/votes via reused audited cores, ID mapping is `posts.id`/`comments.id` directly). The **issue tracker** at `/issues` has no local store - it reads/writes Gitea live via one shared bot token, filing is an async AI-enhanced job. Full detail in the respective nested `CLAUDE.md` files.
Telegram bridge, email tools, devRant API, Gitea issue tracker: see their nested `CLAUDE.md` files (Subsystem map).
### SEO
`devplacepy/seo.py` generates JSON-LD schemas (WebSite, BreadcrumbList, DiscussionForumPosting, ProfilePage, SoftwareApplication). Every router builds context via `base_seo_context(request, ...)`. Auth/messages/notifications are `noindex,nofollow`; profiles with fewer than 2 posts are `noindex,follow`. `/robots.txt` and `/sitemap.xml` are served by `routers/seo.py`. Full implementation map (template layer, heading hierarchy, slugs, related posts, performance, default OG image, SEO tests) is in `devplacepy/routers/CLAUDE.md`.
JSON-LD schemas via `devplacepy/seo.py` and `base_seo_context`; index/follow rules per surface. Full implementation map in `devplacepy/routers/CLAUDE.md`.
## The production database is never touched without explicit confirmation (hard rule)
@@ -311,79 +215,41 @@ The escape hatch is deliberately two-factor and must never be self-served: after
- **Roles are stored capitalized:** `users.role` is exactly `"Admin"` or `"Member"`. Always test admin-ness through the `is_admin(user)` global (case-sensitive `== "Admin"`) - never hand-roll a lowercase compare. **Any write to `users.role` MUST call `database.invalidate_admins_cache()`.**
- **Admin seniority: a junior admin cannot manage a more senior admin.** Every per-user mutation in `routers/admin/users.py` and `routers/admin/moderation.py` is gated by `is_senior_admin(actor, target)` (`routers/admin/_shared.py`) - blocks (audits `result="denied"`) when the target is an Admin who registered earlier. Server-side, so it also covers Devii's admin tools.
- **Never pass a `respond()` context key that collides with a Jinja global.** `respond(request, template, ctx, model=XOut)` feeds the same `ctx` to both the Pydantic model (JSON) and the template. A key like `is_admin`/`avatar_url`/`is_self` holding a non-callable value shadows the global across the whole inheritance chain, turning `{% if is_admin(user) %}` into `False(user)` -> `TypeError`, a 500 that fires only for the branch that calls the global. Name viewer/permission flags distinctly (`viewer_is_admin`, not `is_admin`) in both schema and context.
- **Project visibility (`is_private`) and read-only (`read_only`)** are owner-controlled flags on `projects`. Read access is gated by the single `content.can_view_project(project, user)` predicate at EVERY read surface - never re-implement the check inline. Predicate: `not is_private OR is_owner OR (is_admin AND owner is not an admin)` - a project hidden by a member stays visible to any admin, but one hidden by an admin is visible only to that owner admin. **Containers have their own, stricter isolation predicates** (`owns_instance`, `can_view_project_containers`, `can_view_instance`, `can_manage_instance`) - the primary administrator sees/manages every container; any other admin can VIEW others' containers only on public projects and can MANAGE only instances they own. Read-only is enforced as a single data-layer guard `project_files._guard_writable(project_uid)` at the top of every mutation entrypoint - add it to any NEW file-mutating function. Devii may flip read-only/visibility only after explicit confirmation (`CONFIRM_REQUIRED`). Full UI-level detail in `devplacepy/routers/projects/CLAUDE.md`.
- **Content visibility (`published`/`hidden`/`draft`/`offline`) on posts, gists, projects and news is one specification, `devplacepy/database/visibility.py`.** Any new read of those tables applies `listed_clause`/`listed_sql` (or goes through `paginate`, which does it), and any single-item or target access uses `content.can_view_item`/`can_view_target`. NULL reads as published. Full detail in `devplacepy/database/CLAUDE.md`.
- **Project visibility and read-only** are owner-controlled flags gated by single predicates (`can_view_project`, container isolation predicates, `_guard_writable`): see `devplacepy/routers/projects/CLAUDE.md`.
- **Content visibility on posts, gists, projects and news is one specification** (`database/visibility.py`, choke points `listed_clause`/`listed_sql`, `can_view_item`/`can_view_target`): see `devplacepy/database/CLAUDE.md`.
- **Deletions ALWAYS require confirmation:** `confirmation_error` gates EVERY content delete tool via `CONFIRM_REQUIRED` (`delete_post`, `delete_comment`, `delete_gist`, `delete_project`, `project_delete_file`, `delete_media`, `delete_attachment`, `admin_delete_news`, container delete, and any `container_exec` matching `dispatcher.DESTRUCTIVE_COMMAND`). The first call is refused; the agent must show the exact target then pass `confirm=true`. **Load-bearing: every confirmation-gated tool MUST also declare a `confirm` boolean param in its catalog spec** - schemas set `additionalProperties: false`, so a gated tool without a declared `confirm` param can never receive it and loops forever.
## Every user-generated surface is reportable by construction (hard rule)
A new content table added to `SOFT_DELETE_TABLES` that is visible to anyone other than its author MUST be registered in `database/moderation.py` `REPORTABLE_TARGETS`, MUST resolve in `resolve_object_url`, and MUST include `_report_button.html` in its action bar. A table that is genuinely private to its owner goes in `UNREPORTABLE_TABLES` **with its reason** instead. `tests/unit/database/moderation.py` computes the difference and fails the suite on anything unclassified, so report coverage is closed under future additions rather than remembered; the e2e coverage test enforces the third requirement.
New user-generated tables are classified in `REPORTABLE_TARGETS` (with `resolve_object_url` and `_report_button.html`) or in `UNREPORTABLE_TABLES` with a reason; the suite enforces it. No social login, payment, purchasable randomness, advertising, or cross-app tracking without their app-store obligations. Full detail in `devplacepy/services/moderation/CLAUDE.md`.
The same rule keeps the untriggered app-store conditionals untriggered: **no social login, no payment path, no purchasable randomness, no advertising, and no cross-app tracking** may be introduced without also implementing the obligations each of them creates (Sign in with Apple, in-app purchase, odds disclosure, ad reporting, App Tracking Transparency). Full detail in `devplacepy/services/moderation/CLAUDE.md`.
## Admin pages follow one specification (hard rule)
Every `/admin` page is built to `devplacepy/routers/admin/CLAUDE.md`: backend-rendered first paint with no "Loading..." placeholder, one builder shared by the HTML route and the `/data` refresh endpoint, `respond()` with an `*Out` model, `admin-*` classes only, `local_dt` for every instant, every list paginated or capped, no remote call in a GET, `Poller` only, one Chart.js path, and the section list declared once in `devplacepy/admin_sections.py`. `tests/unit/admin_spec.py` enforces the mechanical rules. A new admin page that breaks the spec does not ship.
## Modal pattern
`Application.js` `initModals()` toggles a `.visible` CSS class on `.modal-overlay`; the CSS rule `.modal-overlay.visible { display: flex; }` handles visibility. Triggers usually have `href="#"`, so call `e.preventDefault()`. `.modal-close` is wired generically - no inline JS needed. Full modal/partial/CDN detail in `devplacepy/templates/CLAUDE.md`.
See `devplacepy/templates/CLAUDE.md` (modal system, partials, CDN).
## Polymorphic comments and votes
The `comments` table uses `(target_type, target_uid)` so `_comment_section.html` works for `post`, `project`, `gist`, and `news`. Votes follow the same shape via `/votes/{target_type}/{uid}`. `resolve_target_redirect()` in `comments.py` maps target_type back to the correct detail URL. Full detail (reactions/bookmarks/polls/heatmap/follow/block-mute reuse the same target-type pattern) in `devplacepy/routers/CLAUDE.md`.
`(target_type, target_uid)` shapes comments, votes, and the engagement reuse family: see `devplacepy/routers/CLAUDE.md`.
## Project-wide soft delete (hard rule)
**Every removal is a soft delete; only garbage collection is a hard delete.** Removable rows carry `deleted_at` (ISO timestamp) + `deleted_by` (actor uid or `system`); a live row has `deleted_at = NULL` and every list/count read filters `deleted_at IS NULL`. The table set is `database.SOFT_DELETE_TABLES`; `init_db` ensures both columns + a partial index per table. Core primitives in `database/`: `soft_delete`, `soft_delete_in`, `restore`, `purge`, `list_deleted`/`count_deleted`, `restore_event`/`purge_event`.
- **Every INSERT into a soft-deletable table MUST write `deleted_at: None, deleted_by: None`** - `dataset.find(deleted_at=None)` on a table missing the column matches NOTHING, silently hiding all rows on a fresh DB.
- **Any new read of a soft-deletable table MUST filter `deleted_at IS NULL`.**
- **Toggles revive, never duplicate:** look up the physical row ignoring `deleted_at`, stamp on toggle-off, clear on re-toggle.
- **Cascades share one `stamp`** so the event restores/purges atomically.
- **Delete authz is owner-OR-admin on the endpoint** - one check covers the UI and Devii.
- **GC stays HARD** (job sweep, metrics ring, usage-ledger prune/reset, expired-session cleanup, fork rollback). Logout is soft (auditable); only expiry GC is hard.
Admin **Trash** at `/admin/trash` restores/purges by event. Full table list, dataset rules, indexing conventions (the soft-delete planner trap), and site settings are in `devplacepy/database/CLAUDE.md`.
**Every removal is a soft delete; only garbage collection is a hard delete.** Inserts write `deleted_at: None, deleted_by: None`; reads filter `deleted_at IS NULL`; toggles revive; cascades share one stamp; delete authz is owner-OR-admin. Full table list, primitives, and indexing rules in `devplacepy/database/CLAUDE.md`.
## Testing
Playwright (NOT pytest-playwright). Around 2882 tests in `tests/`, split into three category directories by *what they exercise*: `tests/api/` (HTTP integration, no browser), `tests/e2e/` (Playwright browser), `tests/unit/` (pure in-process). **The directory tree mirrors the path** - one segment per directory, last segment is the file. `api`/`e2e` mirror the URL path (`GET /admin/ai-usage` -> `tests/e2e/admin/aiusage.py`); `unit` mirrors the source module path (`devplacepy/utils.py` -> `tests/unit/utils.py`). A test's tier is decided by its fixtures: `page`/`alice`/`bob` = e2e; `app_server`/`seeded_db` or any HTTP call = api; `local_db`-only or no fixture = unit. Run a tier with `make test-unit`/`make test-api`/`make test-e2e`; `make test` runs all three.
Fixture stack: `app_server` (session-scoped uvicorn subprocess on port 10501), `browser_context` (session-scoped Playwright context), `page` (function-scoped, fresh cookies), `alice`/`bob` (seeded logged-in users, `bob` gets its own context for multi-user tests).
Required patterns: every `page.goto(...)`/`page.wait_for_url(...)` MUST pass `wait_until="domcontentloaded"`; prefer `page.locator(...).wait_for(state="visible")` over `wait_for_selector`; scope ambiguous selectors (e.g. comment Delete is `.comment-action-btn:has-text('Delete')`). A test that flips a global `site_settings` value MUST restore it in `try/finally`. Full pitfalls/patterns catalogue is in `tests/CLAUDE.md`.
**Always run the full test suite (`make test` - unit, api, and e2e, every test) as the final validation of every change.** No tier may be skipped and no subset substituted for the whole. The clean import (`python -c "from devplacepy.main import app"`) and per-language manual checks are preliminary gates before the suite, not replacements for it. Any failure is a real signal and blocks completion until fixed.
Tiers, fixtures, required patterns (domcontentloaded, try/finally restores), and the triage loop live in `tests/CLAUDE.md`. The mandate: **full `make test` green as the final validation of every change, no tier skipped, no subset substituted.** Import gate and per-language manual checks are preliminary gates, never replacements.
## Rigorous correctness verification (money, state machines, concurrency)
The persisted test suite (`tests/unit`/`api`/`e2e`) is example-based: it proves the specific inputs someone wrote down behave correctly. It is structurally blind to three classes of bug - a formula wrong at an input nobody tried, an invariant violated only after a long sequence of actions, and a race that only two nearly-simultaneous requests trigger. **Any feature that touches a spendable resource (coins, credits, quotas), a bounded state machine (levels, tiers, counters with a floor/ceiling), or a read-then-write mutation reachable from more than one request path applies this procedure in addition to, not instead of, the normal persisted tests.** A simple CRUD toggle doesn't need it; an economy, inventory, ledger, or scoring feature does. This was built out fully for the Code Farm economy rebalance (see `devplacepy/services/game/CLAUDE.md`, "Every purchase/upgrade is atomic..." - the worked example, including every bug it actually caught) and is the standing procedure for anything shaped like it going forward.
Four escalating layers, run in order, as disposable Python scripts that call the real functions directly against a temp DB (`DEVPLACE_DATABASE_URL`/`DEVPLACE_DATA_DIR` pointed at a scratch file) - not pytest files, unless the user separately asks for persisted tests too:
1. **Property/invariant checks on every pure function, across the full input domain.** For each formula (a reward, a cost curve, a score, a discount), assert the mathematical property it must have - monotonicity, bounds, non-negativity, idempotency, additivity over a partition of its domain - by iterating the real range (hundreds to thousands of values), not a handful of hand-picked spot checks. A monotonicity bug at input 347 is invisible if only 0, 1, and 10 are tried.
2. **Stateful fuzzing.** Build N independent entities, fire a long randomized sequence of every mutating action across all of them against a live temp DB, and re-check invariants after every single action: balances never negative, counters that should only increase never decrease, levels/tiers never exceed their declared bounds. Catch the domain's expected exception type and continue - the goal is catching invariant violations and *unexpected* exceptions, not asserting every action succeeds. This proves safety (nothing bad happens) but not liveness (legitimate actions actually succeed) - a bug that wrongly blocks a valid action just raises a well-formed expected exception and sails through a pure fuzz test undetected. Layer 3 exists because of exactly this gap.
3. **Concurrency: prove races are closed, never infer it from luck.** Any read-then-write mutation reachable from more than one worker process (`uvicorn --workers N`) is a TOCTOU race until proven otherwise. Test with **real separate OS processes**, not threads in one process - `dataset` gives each thread its own pooled connection, and enough threads exhausts that pool and produces `database is locked` noise that is a test-harness artifact, not a finding about the application. Set up genuinely fresh, production-representative state before racing - **never pre-seed or zero a column that the real code path leaves unset/NULL.** This was the single most expensive mistake made building this procedure: a first race-safety pass "passed" only because its own setup script had artificially pre-zeroed columns that a real fresh row leaves as SQL `NULL` - silently hiding the exact bug the fix was supposed to prevent (`NULL = 0` evaluates to `NULL`, not true, in a SQL `WHERE` clause; any column not written in the row's original `INSERT` needs `COALESCE(column, 0)` in every later precondition and every arithmetic `SET`, not a bare comparison). Fire many concurrent attempts at the same resource, assert the exact right number succeed, and verify the final state matches the hand-computed expected total exactly (currency spent, levels advanced) - not just "the others were blocked." Fix a real race with a single atomic conditional SQL statement at the exact chokepoint (`UPDATE ... SET ... WHERE <precondition>`, checked via the driver's real `rowcount` - `dataset`'s wrapped `db.query()` does not expose it, use `db.executable.execute(sqlalchemy.text(...), params).rowcount` inside `with db:`), not a client-side lock or an optimistic-locking library this codebase doesn't otherwise use.
4. **Static analysis beyond `py_compile`.** A clean `python -m py_compile` and a clean `from devplacepy.main import app` only prove syntax and module-load order - neither catches a missing import inside a function body, which is a runtime `NameError` invisible until that exact line executes. Run `pyflakes`/`ruff check` on every touched file before calling a change done; it is nearly free and catches an entire class of bug that layers 1-3 can each individually miss if they don't happen to exercise the broken line.
Spendable resources, bounded state machines, and multi-worker read-then-write mutations additionally require the four-layer procedure (property checks, stateful fuzzing, real-process races, `pyflakes`/`ruff`): see `tests/CLAUDE.md` ("Rigorous correctness verification").
## Feature workflow
Every feature in DevPlace is **one data source fanning out into several consumers**. DevPlace has no isolated change - internalize this before editing. A single handler in `routers/{area}.py` is simultaneously the **four faces of one route**:
1. **HTML** - `respond()` returns a rendered template for browsers.
2. **JSON** - the SAME `respond(..., model=XOut)` returns JSON when `Accept: application/json`. The `*Out` schema is the gate: a context key not declared on `*Out` is silently dropped from JSON even though the template still sees it.
3. **Agent tool** - `services/devii/actions/catalog/` (the relevant module inside the package, e.g. `posts.py`, `admin.py`) exposes the route as an `Action` so Devii can call it on the user's behalf. `requires_auth` mirrors the route guard.
4. **Documented endpoint** - `docs_api.py` `endpoint()` describes it (params, auth, `sample_response`) in the right group, rendered at `/docs/{group}.html`.
A new public read almost always needs all four. The cardinal failure mode is changing one face and forgetting a connected one - a real worked example (followers/following listing) touched nine files across data helpers, output schema, route, view, agent tool, API docs, and the docs trio below for one conceptual feature; that count is the norm, not the exception. If a change touches only one file, confirm none of the four faces were missed. Checklist, ordered by data flow:
1. **Understand.** Read the router, template, matching tests (per the tier naming rule above), and the matching nested `CLAUDE.md`. Trace input model -> router -> data helper -> response (HTML and JSON).
2. **Data layer.** `database/` for query/batch helpers (never inline N+1 loops - use `get_users_by_uids`, `build_pagination`, `_in_clause`; guard raw SQL with `if "table" in db.tables`). `models/` for the Pydantic `Form` input model (add the class to the matching domain module and to the re-export list plus `__all__` in `models/__init__.py`). `schemas/` for the `*Out` JSON response model - every context key a JSON route exposes via `respond(..., model=XOut)` MUST exist on `XOut` or it is silently dropped. Schema auto-syncs via `dataset`; add indexes in `init_db()` with `CREATE INDEX IF NOT EXISTS`.
3. **Server layer.** Handler with the right auth guard (`get_current_user` public read, `require_user` member POST, `require_admin` admin). Specific paths (`/{username}/followers`) declared before catch-alls (`/{username}`). Return HTML+JSON via `respond(request, template, ctx, model=XOut)` or pure JSON via `JSONResponse`. Register any NEW router in `main.py`.
4. **View layer.** Extend `base.html`; page CSS in `{% block extra_head %}`, page JS in `{% block extra_js %}`. Reuse partials and template globals. JS is ES6 modules, one class per file, instantiated on `app`.
5. **Safety layer (skip only when the feature stores nothing and shows nothing).** If the feature adds a surface that carries user-generated content, register it in `database/moderation.py` `REPORTABLE_TARGETS` (or in `UNREPORTABLE_TABLES` with a reason), resolve it in `resolve_object_url`, and include `_report_button.html` in its action bar - the registry test and the e2e coverage test both fail otherwise. If it collects or transmits a new *category* of personal data, or sends anything new to a third party, update `/docs/privacy.html` and the app-store privacy declarations in the same change; that disclosure is part of the feature, not a follow-up.
6. **Agent + docs layer (the most-forgotten step - do not skip).** `services/devii/actions/catalog/` (the relevant module inside the package) - add an `Action` tool if a user could ask Devii to do this (`requires_auth=False` for public reads). `docs_api.py` - every public/auth endpoint gets an `endpoint()` entry with params and a `sample_response`. `routers/docs/pages.py` `DOCS_PAGES` for prose pages. SEO (`seo.py`) - `base_seo_context` and any JSON-LD for a new public page; add to `routers/seo.py` sitemap if indexable.
7. **Document.** `README.md` (product-facing, routes/config/dependencies/user-visible features), the relevant nested `CLAUDE.md` (any new mechanic, helper, pitfall, or cross-layer wiring), this root `CLAUDE.md` only when a NEW architectural rule or workflow step is introduced (not per feature).
8. **Validate.** Confirm a clean import (`python -c "from devplacepy.main import app"`), check each touched language manually, grep for em-dash in touched files (neither the character nor its HTML entity - use a hyphen), and run `pyflakes`/`ruff check` on every touched file. **If the feature touches a spendable resource, a bounded state machine, or a read-then-write mutation reachable from more than one request path, also run the four-layer procedure in "Rigorous correctness verification" above** - it is the default for that shape of feature, not an optional extra. **Finish by running the full persisted test suite (`make test` - every tier, every test) and fixing any failure before the change is done.** Write new tests in the matching tier/path, following the required patterns above.
Failures at any implementation step block the workflow - never skip a failed step.
Every feature is one data source fanning out into HTML, JSON, a Devii action, and a documented endpoint. The ordered checklist (understand, data, server, view, safety, agent+docs, document, validate) lives in `devplacepy/routers/CLAUDE.md` ("Feature checklist"). Failures at any step block the workflow.
## CI/CD
+76
View File
@@ -0,0 +1,76 @@
# Definition of Done
This is the completion contract for every change in this repository. A change is done only when every applicable gate below passes. It is linked from the root `CLAUDE.md` and draws on all nested `CLAUDE.md` files; where a nested file states a stricter rule for its subsystem, the stricter rule wins.
## 1. Universal gates (every change)
1. **Exact, minimal diffs.** Edit existing files; create a new file only when the change genuinely needs a home. No unrelated edits, no drive-by refactors.
2. **DRY, one choke point.** If the behaviour already exists somewhere, reuse it through the existing choke point; never add a second implementation, second focus system, second removal path, second suspension check, second consent gate, second terms check, second proxy, second bulk mechanism, or second query on a different basis. A per-type copy of shared logic is a defect.
3. **A specification exists somewhere.** Literally everything has a declared spec: a `spec.py` single source of truth, a registry (`REPORTABLE_TARGETS`, `DOCS_PAGES`, `NOTIFICATION_TYPES`, `GATEWAY_APPS`, `CUSTOMIZATION_PREF_COLUMNS`), a table in a `CLAUDE.md`, or an explicit decision section. The new behaviour is declared in it, not just implemented.
4. **Zero tolerance for inconsistency.** New code matches existing implementation structurally and visually. Before modifying, find the relatable example; if none exists, explain and let the user decide how to continue.
5. **The four faces.** Every feature is one data source fanning out into HTML, JSON (`respond(..., model=XOut)`, and a context key not on the `*Out` schema is silently dropped from JSON), a Devii agent action, and documentation. State each face explicitly, including "no change" where that is the decision.
6. **Import gate and static checks.** `python -c "from devplacepy.main import app"` imports clean; `pyflakes`/`ruff` on every touched file is clean (module-level load order and missing function-level imports are invisible to the other checks). Check each touched language manually (Python compiles/imports, JS parses, CSS braces and HTML tags balance).
7. **Full suite green.** `make test` (unit + api + e2e, serial, one pass) passes with no tier skipped and no subset substituted. Triage cheapest-first: `make test-fast`, then `make test-failed` until empty. A failing existing test is a contract to satisfy, never to skip, narrow (`-k`, `--deselect`), or rewrite to fit the change.
8. **Verification through the real path.** Real filesystem, real concurrency, real failure injection: bursts, races, and full disks are test cases, not weather. Re-running your own probe is not verification; the oracle must be independent (the repo's own tests, a golden file, a second method).
9. **Commit, deploy, verify, in that order, same session.** A change that is not running is not done. After deploy, verify live; green locally means nothing until prod confirms it.
10. **Production database untouched without explicit confirmation.** `data/devplace.db` and everything under `data/` is never read or written by an agent-initiated command without the user's own written confirmation plus the `I-HAVE-CONFIRMED-PRODUCTION-DB-ACCESS` token. Disposable verification scripts use `DEVPLACE_DATABASE_URL`/`DEVPLACE_DATA_DIR` on scratch files.
11. **No comments, no docstrings.** Code is self-documenting. No em dashes anywhere.
12. **Forbidden patterns respected.** No `_new`/`_old`/`_temp`/`_v2`/`better_`/`my_`/`the_` names; `RedirectResponse(url=..., status_code=302)` with an integer literal; no `is_admin`-style context key colliding with a Jinja global (use `viewer_is_admin`-style names); dates shown DD/MM/YYYY via `local_dt`/`dt_ago`.
## 2. Tests (committed, reusable, in the mirrored tree)
- HTTP tests under `tests/api/<url path>/`, browser tests under `tests/e2e/<url path>/`, pure-function tests under `tests/unit/<module path>/`. Reuse `alice`/`bob`, `app_server`, `seeded_db`, `local_db`.
- Browser rules: every `page.goto`/`wait_for_url` passes `wait_until="domcontentloaded"`; prefer `locator().wait_for(state="visible")`; scope ambiguous selectors; restore global `site_settings` flips in `try/finally`.
- A behavior change keeps one focused failing-first test with the change, in the existing layout, using the existing fixtures. No new test framework. Throwaway probes stay out of the repo (and a `/tmp` probe never substitutes for the committed test).
- Never weaken a failing test to obtain green; fix the product or justify the expectation change. Observe the authentic failure before the fix when safe and runnable; run the focused test after the final edit; run the broad suite once, at the end.
## 3. Concurrency and state-machine rigor (the four layers)
For any spendable resource (coins, credits, quotas), bounded state machine (levels, tiers, counters with a floor/ceiling), or read-then-write mutation reachable from more than one worker, the persisted suite is not enough. Run, in order, as disposable scripts against a temp DB (never pytest files unless also requested):
1. **Property checks** on every pure function over the full input domain (monotonicity, bounds, non-negativity, idempotency), iterating the real range, not spot checks.
2. **Stateful fuzzing**: many entities, long randomized action sequences, invariants re-checked after every action (balances never negative, monotonic counters never decrease, bounds never exceeded).
3. **Real multi-process races**: separate OS processes, never threads; production-representative state, never pre-seeded columns (NULL is not 0 in SQL, use `COALESCE`). Prove exact right-wins counts and hand-computed final totals. Fix with one atomic conditional SQL statement (`UPDATE ... WHERE <precondition>`, real driver `rowcount`), never a client-side lock.
4. **Static analysis** beyond `py_compile`: `pyflakes`/`ruff` on every touched file.
Single-process races do not count. Threads do not count. Luck does not count.
## 4. Data layer
- Every insert into a soft-deletable table writes `deleted_at: None, deleted_by: None`; every read filters `deleted_at IS NULL`. Toggles revive, never duplicate; cascades share one stamp; delete authz is owner-or-admin on the endpoint; GC stays hard. New user-generated tables are classified in `REPORTABLE_TARGETS` with `resolve_object_url` and `_report_button.html`, or in `UNREPORTABLE_TABLES` with a reason (the suite enforces this).
- `init_db` ensures the full column set of any table code filters on before creating indexes; new columns go through the ensure idiom plus the born-live pair, never bare DDL that misses pre-existing tables.
- Bounded, indexed reads: window functions over full-table loads, batch helpers over N+1, live-partial indexes built to plan without table scans. Nullable legacy columns need `COALESCE` in every precondition.
- Migrations: `init_db` is idempotent, guarded by locks, skipped seeds stay skipped (consumers pass defaults to `get_setting`, never assume the seed ran). Consent backfills are forbidden (never fabricate consent); `terms_version` stays NULL for legacy accounts.
- Runtime paths come only from `config.DATA_DIR` constants, never computed from scratch; blobs shard on uuid tail or hash, never the head.
## 5. Routing, templates, frontend
- Routers mirror the URL path (`routers/<path>.py`, packages aggregate with `include_router`); route guards mirror auth needs (`require_user`, `require_admin`, `require_user_api`); public pages use `get_current_user`. Mutations are POST with `data-confirm`; deletes additionally allow any admin; seniority gates (`is_senior_admin`) bind Devii too.
- One shared `templates` instance; `nav_active` for nav state; `static_url`/`assetUrl` for every asset, never a bare `/static/` href; `dp-*` web components (no duplicates, real-button triggers inside popovers so no-JS stays correct, Escape closes); new JS reuses `Http`/`Poller`/`JobPoller`/`OptimisticAction`/`FloatingWindow`/`ScrollMemory`.
- Server pipeline renders content for SEO (`render_content`/`render_title`, with `local_dt`/`dt_ago` for timestamps); the client pipeline is only for live content (`DOMPurify` fail-closed). Notifications use `render_title`. Emoji shortcodes come from the one map; YouTube embeds follow `embeds.py` only; emails are masked; em dashes become hyphens.
- CSS: tokens from `variables.css` only (file-scoped `--x-*` palette block per new file, then `--color-*`/`--space-*`); `--z-*` bands; closed breakpoints; `prefers-reduced-motion` disables animation; no literals, no `var()` fallbacks, one radius per element, matching dark theme on first paint.
- Admin pages conform to `devplacepy/routers/admin/CLAUDE.md` (A1-A11): server-rendered first paint, one builder for HTML and `/data`, `respond()` with an `*Out` model, `admin-*` classes, `local_dt`, capped lists, `Poller`, the `ADMIN_SECTIONS` registry; `tests/unit/admin_spec.py` passes.
## 6. Services and jobs
- Background services run only in the lock owner, supervised with health checks and lock files; a new `JobService` needs a server restart and registers its kind. The DB row is the queue; retention is built in; cleanup decisions are per-kind and deliberate (disposable archive vs permanent artifact).
- Services report state through the one live-view relay row, audit through `record`/`record_system` with catalogued `events.md` keys (never raising into the caller), and telegram/push delivery never invents new channels. New websockets get their own nginx upgrade `location` above `location /`.
- New dependencies are unpinned only by deliberate exception; outbound HTTP goes through stealth with `net_guard` where untrusted; feature code never blocks the event loop (gateway-adjacent sync calls run in `to_thread`).
## 7. AI, Devii, and money
- The gateway is the single point of truth for AI: every consumer points at it, keys fall back to the internal key, spend is attributed and metered, financial figures are admin-only everywhere. Consent (`ai_third_party`) gates user-content calls at exactly one place; structured internal callers may bypass the operator preamble, conversational ones never do.
- Devii: every gated tool declares a `confirm` boolean (`additionalProperties: false` makes a gateless confirm fatal); classifier recall beats precision; budget-bounded tools with fail-closed redaction; lessons carry provenance and are never auto-applied from third-party content; channels stay isolated; self-dial uses the real origin URL.
- Economy and scoring invariants hold exactly: one pure function per number, atomic transitions only, recomputation beats counters, races proven with real processes (see section 3).
## 8. Done means
- [ ] Minimal diff, no unrelated edits; new files only with a home.
- [ ] One choke point reused; spec/registry updated; four faces stated.
- [ ] Import gate + `pyflakes`/`ruff` clean; per-language manual checks done.
- [ ] Committed reusable tests added/updated in the mirrored tree; focused failure observed before, passing after.
- [ ] Section 3 layers run where applicable (spendable resource, bounded state machine, multi-worker mutation).
- [ ] `make test` fully green; no tier skipped, no test narrowed or rewritten to fit.
- [ ] No production data touched; scratch DBs only.
- [ ] Docs touched where the behaviour is user-visible (`/docs` prose + `DOCS_PAGES`, `docs_api` groups, `events.md`, nested `CLAUDE.md` notes).
- [ ] Committed, deployed, verified live, same session.
+23 -13
View File
@@ -351,13 +351,20 @@ accepts three header-based methods, resolved centrally in `get_current_user`
Every user has an `api_key` (a uuid7), set at signup and backfilled for existing
users on startup (and via `devplace apikey backfill`). The key is shown on the
profile page to its owner (and to admins for any user) with a live **Regenerate**
button; regenerating invalidates the old key immediately. A successful JSON
`POST /auth/login` or `POST /auth/signup` also returns the account's `email`,
`api_key`, and `is_admin` flag, and `GET /profile/{username}` as JSON reports
`profile_is_admin` plus the key (null unless the viewer owns the profile or is
an admin). Invalid credentials return `401`; requests with no credentials behave
as anonymous (browser redirect to login). Full details and copy-paste `curl`
examples live at `/docs/authentication.html`.
button; regenerating invalidates the old key immediately. The three account
credentials are username+password, email+password, and the personal API key: the
login form, JSON `POST /auth/login`, `POST /auth/token`, and HTTP Basic all accept
the username or the email address as the password identifier (usernames are
case-sensitive, email addresses are not), and clients conventionally carry the API
key in the `DEVPLACE_API_KEY` environment variable. Every JSON response that returns
the personal API key returns the account's `username` and `email` alongside it:
login/signup (`data`), `POST /profile/regenerate-api-key`, and the profile JSON
(`profile_user.username`, `email`, `api_key`; key and email null unless the viewer
owns the profile or is an admin). So a client holding only an API key fetches its
account in one call: `GET /profile` with `X-API-KEY` and `Accept: application/json`.
Invalid credentials return `401`; requests with no credentials behave as anonymous
(browser redirect to login). Full details and copy-paste `curl` examples live at
`/docs/authentication.html`.
```bash
curl -H "X-API-KEY: <your-key>" https://your-host/notifications
@@ -526,7 +533,7 @@ and its full configuration are documented automatically - including future servi
- **`ServiceManager`** - singleton: `register`, `describe_all`, `set_enabled`, `send_command`, `save_config`, `supervise`, `shutdown_all`
- **`NewsService`** - a fully automatic, zero-maintenance news pipeline: fetches news from `news.app.molodetz.nl/api`, cleans each article, fetches and perceptually compares the images to reject placeholders and detect uniqueness, grades each one against a free, local, deterministic quality model (aquality - no billed LLM call, no API key), optionally reformats articles that clear the publish grade threshold into clean Markdown with a generative AI model (off by default, since the default grading model cannot generate text), and auto-rotates the best articles to Featured and the landing page. Any AI spend it does incur is metered from the gateway response headers and reported on the admin Services page (calls, tokens, total cost, and per-call averages)
- **`BotsService`** - Playwright fleet of AI personas that browse and interact with a DevPlace instance, with live cost/usage metrics and a live screenshot monitor at `/admin/bots` (opt-in; install the `bots` extra)
- **`GatewayService`** - OpenAI-compatible LLM gateway at `/openai/v1/*`, forwarding to DeepSeek (default) with optional vision augmentation; the single point of truth for AI that every other service routes through (enabled by default). Every chat request is made date-aware by injecting the current date in EU `DD/MM/YYYY` format into the system message when it contains no date already (date only, never time, to keep upstream prompt caching effective), and an admin-configurable system preamble (`gateway_system_preamble`) can be prepended ahead of the client's system message on every call. **Thinking is disabled by default** on every chat and vision call (`thinking.type=disabled` on DeepSeek, `reasoning.effort=none` on OpenRouter, `think=false` on Ollama) so the fast path is the default; a client may re-enable it per request, and an administrator may flip `gateway_thinking` on. **Provider and model routing** (admin **Gateway** page, `/admin/gateway`) maps any number of requested model names onto named upstream providers and target models, each with its own pricing economy (input, output and cache-hit/cache-miss rates per million tokens) and an optional vision model that describes image content before forwarding, so text and vision models are merged transparently. Unmapped requests fall through to the default upstream unchanged, so existing clients are unaffected. Each route may also name a **fallback model** - another already-configured model of the same kind, picked from a select box of the public model names (never a free-text provider model id) - that the gateway retries once, automatically, whenever the primary model fails after its own retries are exhausted, so a struggling model degrades to a working one instead of failing the caller
- **`GatewayService`** - OpenAI-compatible LLM gateway at `/openai/v1/*`, forwarding to DeepSeek (default) with optional vision augmentation; the single point of truth for AI that every other service routes through (enabled by default). Every chat request is made date-aware by injecting the current date in EU `DD/MM/YYYY` format into the system message when it contains no date already (date only, never time, to keep upstream prompt caching effective), and an admin-configurable system preamble (`gateway_system_preamble`) can be prepended ahead of the client's system message on every call. **Thinking is disabled by default** on every chat and vision call (`thinking.type=disabled` on DeepSeek, `reasoning.effort=none` on OpenRouter, `think=false` on Ollama) so the fast path is the default; a client may re-enable it per request, and an administrator may flip `gateway_thinking` on. **Provider and model routing** (admin **Gateway** page, `/admin/gateway`) maps any number of requested model names onto named upstream providers and target models, each with its own pricing economy (input, output and cache-hit/cache-miss rates per million tokens) and an optional vision model that describes image content before forwarding, so text and vision models are merged transparently. Unmapped requests fall through to the default upstream unchanged, so existing clients are unaffected. Each route may also name a **fallback model** - another already-configured model of the same kind, picked from a select box of the public model names (never a free-text provider model id) - that the gateway retries once, automatically, whenever the primary model fails after its own retries are exhausted, so a struggling model degrades to a working one instead of failing the caller. When an upstream rejects a request key with a parsable unrecognized-key 400 (for example a strict-schema provider refusing the `thinking` field), the gateway automatically tries other request shapes, remembers the one that works per provider and target model, and applies it from then on; administrators see it as a `shape:` badge on the model grid with a Reset learned action
- **`JobService` / `ZipService` / `ForkService`** - generic async job framework (`services/jobs/`) for heavy, blocking work run off the request path; `ZipService` builds project zip archives in a subprocess, `ForkService` copies a project into a new project owned by the forking user
- **`ContainerService`** - the admin container manager (`services/containers/`): a reconciling supervisor for container instances, all running one shared prebuilt image
- **`AcceptanceService`** - grants every policy agreement (Terms of Service, Privacy Policy, third-party AI processing, activity recording, container credentials) to every account that has not declined it, so an instance kept production-identical for extended manual testing never interrupts with an acceptance dialog. Administrator-only, **off by default**, with a separate switch per agreement type and a dry run that reports what it would do without writing. An account that withdrew a consent is never granted it again, with no further action: the consent ledger itself is the decline register. It is not appropriate on a real production host
@@ -612,7 +619,7 @@ restart.
`ForkService` copies a project into a new project owned by the forking user. The **Fork** button on the project page (any signed-in user) prompts for a name; the job creates the destination project, duplicates the entire virtual filesystem, and records a directional `project_forks` relation so each fork shows a "Forked from X" link. The frontend `app.projectForker` enqueues, polls `/forks/{uid}`, and redirects to the new project once it is done; on failure the partially created project is rolled back. The forked project is permanent, so retention removes only the job tracking row. CLI: `devplace forks prune` / `devplace forks clear` (job rows only).
`SeoService` powers the public **SEO Diagnostics** auditor at `/tools/seo`. It runs a headless-browser (Playwright) crawl of a single URL or a sitemap (capped pages) in a subprocess and runs a broad battery of checks across eleven categories: crawlability and indexing (status, redirects, HTTPS/HSTS, canonical, robots/meta-robots, sitemap, URL hygiene, mixed content), on-page meta and content (title, description, headings, language, charset, viewport, favicon, content depth), links, structured data and rich results (JSON-LD validity and required properties, microdata/RDFa), social cards (Open Graph, Twitter), Core Web Vitals and performance (LCP, CLS, FCP, TTFB, page weight, requests, DOM size, compression, caching, image optimisation, console errors), mobile and accessibility (responsive layout, tap targets, image alt, form labels), security headers, and AI/LLM-search readiness (server-rendered-vs-JS content parity, `llms.txt`, semantic HTML). It produces a weighted score and grade with per-category subscores and a recommendation for every finding. Progress streams live over `WS /tools/seo/{uid}/ws`; the full report is available at `/tools/seo/{uid}/report` (HTML or JSON). CLI: `devplace seo prune` / `devplace seo clear`. Playwright is a core dependency; `make install` fetches the Chromium browser.
`SeoService` powers the public **SEO Diagnostics** auditor at `/tools/seo`. It runs a headless-browser (Playwright) crawl of a single URL or a sitemap (capped pages) in a subprocess and runs a broad battery of checks across eleven categories: crawlability and indexing (status, redirects, HTTPS/HSTS, canonical, robots/meta-robots, sitemap, URL hygiene, mixed content), on-page meta and content (title, description, headings, language, charset, viewport, favicon, content depth), links, structured data and rich results (JSON-LD validity and required properties, microdata/RDFa), social cards (Open Graph, Twitter), Core Web Vitals and performance (LCP, CLS, FCP, TTFB, page weight, requests, DOM size, compression, caching, image optimisation, console errors), mobile and accessibility (responsive layout, tap targets, image alt, form labels), security headers, and AI/LLM-search readiness (server-rendered-vs-JS content parity, `llms.txt`, semantic HTML). It produces a weighted score and grade with per-category subscores and a recommendation for every finding. Progress streams live over `WS /tools/seo/{uid}/ws`; the full report is available at `/tools/seo/{uid}/report` (HTML or JSON). CLI: `devplace seo prune` / `devplace seo clear` / `devplace seo refresh` (enforce the text plus picture procedure on the newest items, default 20, and print the total cost). Playwright is a core dependency; `make install` fetches the Chromium browser.
`SeoMetaService` is a separate AI subservice that generates a clean, search-optimised title, description and short keyword list for every published post, project, gist, news article and issue, entirely off the request path so it never slows the web server. The work is queued whenever content is created, edited or published; until the AI value is ready a plain-content default (built from the markdown-stripped text and clamped to safe lengths) fills the fields, so a page's metadata is **always populated, never empty**. The service uses the built-in internal AI gateway and meters its own AI cost and statistics in a dedicated usage table, surfaced together with its live task pipeline on the **Admin -> Services** page. This release also fixes the on-page metadata: the `<meta name="description">` is now stripped of markdown markup (it previously leaked `#`, `**` and `[](...)` from the raw body), a `<meta name="keywords">` tag is emitted (a short honest list, not stuffed), and social-card image dimensions and alt text are added. CLI: `devplace seo-meta prune` / `devplace seo-meta clear` (job rows only; the generated metadata persists).
@@ -767,6 +774,7 @@ Configuration on the Services tab:
| `gateway_rsearch_cost_per_call` | 0.0 | Flat cost attributed to each external `rsearch` call (web search / AI answer / chat / image describe), recorded under backend `rsearch` so external AI spend appears in AI usage |
| `gateway_max_retries` / `gateway_retry_backoff_ms` | 2 / 250 | Retry attempts and linear backoff on timeout, connection error, or upstream 5xx |
| `gateway_circuit_threshold` / `gateway_circuit_cooldown_seconds` | 5 / 30 | Consecutive failures before the circuit breaker opens, and its cooldown |
| `gateway_target_circuit_enabled` | on | Per-model circuit breaker: one upstream error opens it for the cooldown and notifies every admin with the error details |
| `gateway_usage_retention_hours` | 720 | How long per-call usage rows are kept before pruning (30 days) |
| `gateway_model_context_map` | JSON map | Model to max-context-tokens map for context-window utilization tracking |
@@ -791,7 +799,7 @@ token usage with averages and percentiles (p50/p90/p95/p99), latency (upstream r
gateway overhead, semaphore queue wait, connection establishment), error rates by category,
cost (per model, per caller, input vs output, projected monthly burn, caching savings),
caller behavior, and an hourly breakdown - divided and combined. The gateway also retries
transient upstream failures and opens a circuit breaker after repeated failures. Time to
transient upstream failures, opens a circuit breaker after repeated failures, and opens a per-model breaker on the first error of a model and notifies every admin. Time to
first token and inter-token latency are not reported because the gateway forwards
non-streaming to the upstream.
@@ -1067,7 +1075,9 @@ in real time, bridged onto the in-process pub/sub bus by a lock-owner relay:
| Issue-tracker update | reporter / admins |
`create_notification` schedules delivery as a fire-and-forget async task, so a dead
subscription or push-service error never blocks the triggering request. Delivery
subscription or push-service error never blocks the triggering request. The payload carries the recipient's unread count (`unread`, the same number as
`/notifications/counts`), which APNs presents as `aps.badge` so the app icon updates even
while the app is closed. Delivery
(`push.notify_user`) reads a user's subscriptions once, groups them by provider, builds
each provider's payload once, and sends over that provider's own HTTP client (stealth for
Web Push, a dedicated HTTP/2 client for APNs). A subscription the push service reports as
@@ -1126,8 +1136,8 @@ every page load. `PushManager.js` owns registration, subscription, and the opt-i
`manifest.json` (192/512 and maskable icons) and `service-worker.js` make the app
installable via the browser's native install affordance. The service worker uses a
network-first strategy for navigations and falls back to `static/offline.html` when
offline. Installation requires a secure origin (HTTPS, or `localhost` for development).
network-first strategy for navigations, retries a failed navigation once, and falls
back to `static/offline.html` when both attempts fail. Installation requires a secure origin (HTTPS, or `localhost` for development).
| File | Role |
|------|------|
+38
View File
@@ -0,0 +1,38 @@
# retoor <retoor@molodetz.nl>
from dataclasses import dataclass
@dataclass(frozen=True)
class AdminSection:
key: str
label: str
href: str
icon: str
ADMIN_SECTIONS: tuple[AdminSection, ...] = (
AdminSection("users", "Users", "/admin/users", "\U0001f465"),
AdminSection("news", "News", "/admin/news", "\U0001f4f0"),
AdminSection("media", "Media", "/admin/media", "\U0001f5bc️"),
AdminSection("moderation", "Moderation", "/admin/moderation", "\U0001f6a9"),
AdminSection("trash", "Trash", "/admin/trash", "\U0001f5d1️"),
AdminSection("services", "Services", "/admin/services", "⚙️"),
AdminSection("gateway", "Gateway", "/admin/gateway", "\U0001f500"),
AdminSection("containers", "Containers", "/admin/containers", "\U0001f4e6"),
AdminSection("workspaces", "Workspaces", "/admin/workspaces", "\U0001f4bb"),
AdminSection("devii-tasks", "Devii tasks", "/admin/devii-tasks", "⏰"),
AdminSection("communities", "Communities", "/admin/communities", "\U0001f310"),
AdminSection("nodes", "Community nodes", "/admin/nodes", "\U0001f4e1"),
AdminSection("bots", "Bot Monitor", "/admin/bots", "\U0001f916"),
AdminSection("game", "Code Farm", "/admin/game", "\U0001f69c"),
AdminSection("ai-usage", "AI usage", "/admin/ai-usage", "\U0001f4ca"),
AdminSection("statistics", "Statistics", "/admin/statistics", "\U0001f4c8"),
AdminSection("audit-log", "Audit Log", "/admin/audit-log", "\U0001f4cb"),
AdminSection("backups", "Backups", "/admin/backups", "\U0001f4be"),
AdminSection("issues", "Ticket Planning", "/admin/issues/planning", "\U0001f5c2️"),
AdminSection("notifications", "Notifications", "/admin/notifications", "\U0001f514"),
AdminSection("settings", "Settings", "/admin/settings", "\U0001f527"),
)
ADMIN_SECTION_KEYS: frozenset[str] = frozenset(section.key for section in ADMIN_SECTIONS)
+2
View File
@@ -22,6 +22,7 @@ from devplacepy.cli.jobs import (
cmd_forks_clear,
cmd_seo_prune,
cmd_seo_clear,
cmd_seo_refresh,
cmd_isslop_prune,
cmd_isslop_clear,
cmd_isslop_analyze,
@@ -73,6 +74,7 @@ __all__ = [
"cmd_forks_clear",
"cmd_seo_prune",
"cmd_seo_clear",
"cmd_seo_refresh",
"cmd_isslop_prune",
"cmd_isslop_clear",
"cmd_isslop_analyze",
+212
View File
@@ -86,6 +86,184 @@ def _remove_seo_artifacts(job):
shutil.rmtree(SEO_REPORTS_DIR / job["uid"], ignore_errors=True)
SEO_REFRESH_DEFAULT_TYPES = ("post", "project", "gist")
SEO_REFRESH_TEXT_ONLY_TYPES = ("news", "quiz")
SEO_REFRESH_ALL_TYPES = SEO_REFRESH_DEFAULT_TYPES + SEO_REFRESH_TEXT_ONLY_TYPES
SEO_REFRESH_TRIGGER = "refresh"
def _seo_refresh_candidates(limit, target_types):
from devplacepy.services.seo_meta import TYPE_TABLES
items = []
for target_type in target_types:
table = TYPE_TABLES.get(target_type, "")
rows = list(
get_table(table).find(
deleted_at=None, order_by=["-created_at"], _limit=limit
)
)
if target_type == "news":
rows = [row for row in rows if row.get("status") == "published"]
for row in rows:
items.append(
{
"target_type": target_type,
"target_uid": row.get("uid"),
"title": row.get("title") or "",
"created_at": row.get("created_at") or "",
}
)
items.sort(key=lambda item: item["created_at"], reverse=True)
return [item for item in items if item["target_uid"]][:limit]
def _run_seo_refresh_item(meta_service, image_service, item, model, skip_image):
import asyncio
from devplacepy.utils import generate_uid
meta_job = {
"uid": generate_uid(),
"payload": {
"target_type": item["target_type"],
"target_uid": item["target_uid"],
},
"owner_kind": "system",
"owner_id": "seo_refresh",
}
meta_result = asyncio.run(meta_service.process(meta_job))
image_result = None
if not skip_image and item["target_type"] in SEO_REFRESH_DEFAULT_TYPES:
image_job = {
"uid": generate_uid(),
"payload": {
"target_type": item["target_type"],
"target_uid": item["target_uid"],
"trigger": SEO_REFRESH_TRIGGER,
"model": model,
"dedupe_key": f"img:{item['target_type']}:{item['target_uid']}:refresh",
},
"owner_kind": "system",
"owner_id": "seo_refresh",
}
image_result = asyncio.run(image_service.process(image_job))
return meta_result, image_result
def cmd_seo_refresh(args):
import sys
import time
from devplacepy.services.jobs.seo_image_service import (
SEO_IMAGE_DEFAULT_MODEL,
SeoImageService,
validate_image_call,
)
from devplacepy.services.jobs.seo_meta_service import SeoMetaService
limit = int(args.limit if args.limit is not None else 20)
if limit < 1:
print("Limit must be at least 1")
sys.exit(1)
target_types = tuple(
part.strip().lower()
for part in str(args.types or "").split(",")
if part.strip()
) or SEO_REFRESH_DEFAULT_TYPES
unknown = [name for name in target_types if name not in SEO_REFRESH_ALL_TYPES]
if unknown:
print(
"Unknown content type(s): "
+ ", ".join(unknown)
+ " (choose from "
+ ", ".join(SEO_REFRESH_ALL_TYPES)
+ ")"
)
sys.exit(1)
model = args.model or SEO_IMAGE_DEFAULT_MODEL
skip_image = bool(args.skip_image)
if not skip_image:
try:
model = validate_image_call(model)
except ValueError as exc:
print(f"Refusing to run: {exc}")
sys.exit(1)
from devplacepy.database import get_seo_usage
items = _seo_refresh_candidates(limit, target_types)
if not items:
print("No published content found for the requested type(s)")
return
if bool(args.dry_run):
from devplacepy.services.jobs.seo_image_service import (
OPENROUTER_IMAGE_MODELS as dry_models,
)
print(f"SEO refresh DRY RUN: {len(items)} item(s), nothing will change")
imageable = 0
for item in items:
kinds = "text+picture" if item["target_type"] in SEO_REFRESH_DEFAULT_TYPES else "text"
print(f" {item['target_type']}/{item['target_uid']} [{kinds}] {item['title'][:80]}")
if item["target_type"] in SEO_REFRESH_DEFAULT_TYPES and not skip_image:
imageable += 1
if not skip_image:
estimate = dry_models.get(model, 0.0) * imageable
print(f"Estimated picture cost: ${estimate:.4f} ({imageable} image(s) x {model})")
print("Text cost is metered by the AI gateway at runtime and reported after a live run")
return
meta_service = SeoMetaService()
image_service = SeoImageService()
usage_before = get_seo_usage()["cost_usd"]
started = time.monotonic()
done = 0
failed = 0
image_total = 0.0
for item in items:
label = f"{item['target_type']}/{item['target_uid']}"
try:
meta_result, image_result = _run_seo_refresh_item(
meta_service, image_service, item, model, skip_image
)
line = f" ok {label} text={meta_result.get('source')}"
if image_result is not None:
cost = float(image_result.get("cost_usd", 0.0) or 0.0)
image_total += cost
line += f" picture=${cost:.4f}"
elif not skip_image:
line += " picture=skipped(text-only type)"
print(line)
done += 1
except Exception as exc:
print(f" failed {label}: {exc}")
failed += 1
text_total = get_seo_usage()["cost_usd"] - usage_before
total = text_total + image_total
elapsed = time.monotonic() - started
print(f"Refreshed {done} item(s), {failed} failed in {elapsed:.1f}s")
print(f"Text cost (AI gateway): ${text_total:.4f}")
print(f"Picture cost (OpenRouter {model}): ${image_total:.4f}")
print(f"Total cost of the operation: ${total:.4f}")
_audit_cli(
"cli.seo.refresh",
f"CLI SEO refresh completed for {done} item(s), {failed} failed, total ${total:.4f}",
metadata={
"items": done,
"failed": failed,
"limit": limit,
"types": list(target_types),
"model": model,
"text_cost_usd": round(text_total, 6),
"image_cost_usd": round(image_total, 6),
"total_cost_usd": round(total, 6),
"elapsed_seconds": round(elapsed, 3),
},
)
def cmd_seo_prune(args):
from datetime import datetime, timezone
from devplacepy.services.jobs import queue
@@ -340,6 +518,40 @@ def register_jobs(subparsers):
"clear", help="Delete every SEO audit report and job row"
)
seo_clear.set_defaults(func=cmd_seo_clear)
seo_refresh = seo_sub.add_parser(
"refresh",
help=(
"Enforce the SEO procedure (text metadata plus social picture) on the "
"newest content items and report the total cost of the operation"
),
)
seo_refresh.add_argument(
"--limit",
type=int,
default=20,
help="How many of the newest items to refresh (default 20)",
)
seo_refresh.add_argument(
"--types",
default="post,project,gist",
help="Comma-separated content types (choose from post, project, gist, news, quiz)",
)
seo_refresh.add_argument(
"--model",
default="",
help="OpenRouter image model for the picture step (default the SEO image model)",
)
seo_refresh.add_argument(
"--skip-image",
action="store_true",
help="Refresh text metadata only, skip the picture step",
)
seo_refresh.add_argument(
"--dry-run",
action="store_true",
help="List the items that would be refreshed with an estimated picture cost, change nothing",
)
seo_refresh.set_defaults(func=cmd_seo_refresh)
seo_meta = subparsers.add_parser("seo-meta", help="SEO metadata job management")
seo_meta_sub = seo_meta.add_subparsers(title="action", dest="action")
+55
View File
@@ -26,6 +26,10 @@ from devplacepy.database import (
clear_user_stars,
clear_user_post_count,
get_target_owner_uid,
get_current_object_image,
current_object_image_map,
OBJECT_IMAGE_TYPES,
note_object_image_served,
resolve_object_url,
soft_delete,
soft_delete_in,
@@ -68,6 +72,7 @@ from devplacepy.services.opinionwar import store as war_store
from devplacepy.services.correction import schedule_correction
from devplacepy.services.ai_modifier import schedule_modification
from devplacepy.services.seo_meta import schedule_seo_meta_for_table
from devplacepy.services.seo_image import schedule_seo_image_for_table
from devplacepy.services.moderation.screening import (
record as record_screening,
refuse_if_blocked,
@@ -129,6 +134,35 @@ def can_view_target(target_type: str, target_uid: str, user: dict | None) -> boo
return can_view_item(table_name, item, user)
def can_discover_target(target_type: str, target_uid: str, user: dict | None) -> bool:
table_name = TARGET_TABLES.get(target_type)
if not table_name:
return True
item = resolve_by_slug(get_table(table_name), target_uid)
if not item:
return True
if is_listed(table_name, item):
return True
return bool(user and (item.get("user_uid") == user.get("uid") or is_admin(user)))
def discoverable_target_rows(rows: list, user: dict | None) -> list:
memo: dict[tuple[str, str], bool] = {}
kept = []
for row in rows:
if user and row.get("user_uid") == user.get("uid"):
kept.append(row)
continue
target_type = row.get("target_type") or "post"
target_uid = row.get("target_uid") or row.get("post_uid") or ""
key = (target_type, target_uid)
if key not in memo:
memo[key] = can_discover_target(target_type, target_uid, user)
if memo[key]:
kept.append(row)
return kept
def mature_hidden_by_default() -> bool:
return get_int_setting("moderation_mature_default_hidden", 1) != 0
@@ -285,6 +319,20 @@ def first_image_url(item: dict, attachments: list | None) -> str | None:
return None
def social_image(
target_type: str, target_uid: str, fallback: str | None
) -> tuple[str | None, int, int]:
current = get_current_object_image(target_type, target_uid)
if current and current.get("url"):
note_object_image_served(current["uid"])
return (
current["url"],
int(current.get("width") or 1200),
int(current.get("height") or 630),
)
return fallback, 1200, 630
def _with_visibility(table_name: str, fields: dict) -> dict:
column = VISIBILITY_COLUMNS.get(table_name)
if not column:
@@ -366,6 +414,7 @@ def create_content_item(
schedule_correction(user, table_name, uid, request)
schedule_modification(user, table_name, uid, request)
schedule_seo_meta_for_table(table_name, uid)
schedule_seo_image_for_table(table_name, uid, "user", user["uid"])
return uid, slug
@@ -1010,6 +1059,11 @@ def enrich_items(
get_user_votes(user["uid"], [item["uid"] for item in items]) if user else {}
)
maturity = get_maturity_by_targets(key, [item["uid"] for item in items])
images = (
current_object_image_map(key, [item["uid"] for item in items])
if key in OBJECT_IMAGE_TYPES
else {}
)
enriched = []
for item in items:
entry = {
@@ -1018,6 +1072,7 @@ def enrich_items(
"time_ago": time_ago(item[ts_field]),
"my_vote": user_votes.get(item["uid"], 0),
"maturity": maturity.get(item["uid"], {}).get("level", "general"),
"social_image_url": images.get(item["uid"], ""),
}
for name, source in extra_maps.items():
entry[name] = (
+9
View File
@@ -260,8 +260,17 @@ Posts, gists, projects and news carry one status from `VISIBILITY_VALUES`: `publ
- **Column.** `VISIBILITY_COLUMNS = {posts, gists, projects: "visibility", news: "status"}`. News reuses its existing `status` column (it already held `published`/`draft`), so no news migration exists. `ensure_visibility_columns()` (called from `init_db`) adds the text column and `idx_<table>_visibility` ONLY to tables that already exist; it must never create the table (an empty `posts` table breaks every `"posts" in db.tables` guard and the first-signup schema). A NULL or unknown value reads as `published` everywhere (`normalize_visibility`, `item_visibility`), so legacy rows needed no backfill and `init_db` does no per-row work.
- **Every read goes through one of three choke points, never an inline compare.** `paginate`/`paginate_diverse` auto-append `listed_clause(table)` for any table in `VISIBILITY_COLUMNS` (`include_unlisted_of=<uid>` ORs in that owner's own rows, used for an owner's own profile/listing); `listed_clause(table, own_uid)` for `count()`/`find()` call sites; `listed_sql(table, alias)` for raw SQL (it returns `1 = 1` when the table or column does not exist yet, so a fresh database never errors). The predicates `is_listed`/`is_open` work on a row dict. Single-item access is `content.can_view_item(table, item, user)` (open, or owner, or admin) and `content.can_view_target(target_type, uid, user)` for polymorphic targets; `load_detail` applies the first, so every detail page 404s without per-route code. `can_view_project` composes visibility first, then the `is_private` rule.
- **Discoverability vs openness (hard rule).** A `hidden` link is the secret, so any surface that lists a user's activity must not expose it. `content.can_discover_target` / `discoverable_target_rows(rows, viewer)` keep a row only when its target is listed, or the viewer owns the target, is an administrator, or authored the row; the profile Activity tab and the devRant profile comments use it. Opinion Wars follow their post: `store._list_clauses` restricts `/battles` to wars whose post is listed (own posts and admins excepted), and every `/battles/{uid}` route 404s through `can_view_target` (`routers/battles._viewable_war`). Tests: `tests/api/content/visibility.py`.
- **Writes.** `content.apply_visibility` is the one writer (column update, cache invalidation, `<kind>.visibility.set` audit with old/new value). `edit_content_item` pops the optional `visibility` form field and calls `apply_visibility` when it changed; `content.set_visibility_item` exists only for the administrator news route (news has no edit form). `create_content_item` stamps the column (`_with_visibility`) and skips mention notifications for non-open items.
- **Public counters** (`get_user_post_count`, `get_site_stats`, `get_post_counts_by_user_uids`, trending topics, topic hub counts, sitemap author counts, happy-404 pool) count listed rows only, so the owner's own profile count excludes their hidden and offline posts.
- **Backwards compatibility (hard rule).** `visibility` is optional on every API: `VisibilityCreateMixin` defaults to `published`, `VisibilityEditMixin` defaults to `None` meaning keep the current value (never reset to published), NULL rows read as published, and the docs/Devii parameter descriptions say so (`tests/unit/docs_api/visibility.py`, `tests/api/content/visibility.py` legacy-client tests). Never make the field required.
- **Outputs.** `VisibleOut` (`schemas/content.py`) gives `PostOut`/`GistOut`/`ProjectOut` a `visibility` that reads NULL as `published`. Forms use `VisibilityCreateMixin` (default `published`) and `VisibilityEditMixin` (`None` keeps the current value); `VisibilityForm{value}` backs the admin news route.
- **Adding a table.** Put it in `VISIBILITY_COLUMNS` and `TARGET_TABLES`, add its form mixin and Out base, apply `listed_clause`/`listed_sql` to each new read, and extend `tests/api/content/visibility.py`. `tests/unit/database/visibility.py` asserts the spec is self-consistent.
## Notification grouping, throttling and keyboard settings
`users` carries `enter_to_submit`, `notif_grouping_enabled` and `notif_throttle_enabled` (all default 1, ensured in `schema.py`, owner-or-admin toggles on the profile page).
## Data CLI
`devplace apikey backfill` assigns keys to users that lack one. `devplace attachments prune` removes orphan attachment records/files. `devplace system prune` (with `--dry-run`) purges soft-deleted attachment/project-file blobs, sweeps blob files with zero DB reference, and GCs orphaned container workspace dirs. `database/notifications.py` owns the single grouping specification: `NOTIFICATION_GROUP_KEYS` (actor / target / single per type, unlisted types are single), `notification_group_key(row)`, and `count_unread_groups(user_uid)` (groups when enabled, rows when off). Every badge producer calls `count_unread_groups`; none counts rows itself. The push payload (`unread`, presented as `aps.badge`) is one of them. The `notifications` column set is ensured in `init_db` like `messages` (listed in `tests/unit/database/schema.py` `FILTERED_COLUMNS`), and the unread read `find(user_uid=..., read=False)` is served by `idx_notifications_user_read (user_uid, read)`. Delivery throttling (item 5) reuses the same key.
+27 -1
View File
@@ -29,10 +29,12 @@ from .awards import (
revoke_award,
)
from .seo_meta import SEO_META_TYPES, get_seo_metadata, get_seo_metadata_batch, has_fresh_seo_metadata, upsert_seo_metadata, mark_seo_metadata_stale
from .object_images import OBJECT_IMAGE_TYPES, OBJECT_IMAGE_RETENTION_DAYS, OG_WIDTH, OG_HEIGHT, THUMB_WIDTH, THUMB_HEIGHT, get_current_object_image, current_object_image_map, current_object_image_url, record_object_image, note_object_image_served, remove_object_image, restore_object_image, purge_object_images
from .activity import record_activity, record_unique_activity, get_user_activity, _activity_cache, _ACTIVITY_TABLES, get_activity_calendar, _activity_level, get_first_activity_date, HEATMAP_WEEKS, get_activity_heatmap, get_activity_months, get_streaks
from .customization import CUSTOMIZATION_GLOBAL_SCOPE, CUSTOMIZATION_LANGS, _customizations_cache, _customization_key, CUSTOMIZATION_PREF_COLUMNS, get_customization_prefs, set_customization_pref, get_custom_overrides, get_custom_override, list_custom_overrides, set_custom_override, delete_custom_override
from .email import EMAIL_ACCOUNT_DEFAULTS, list_email_accounts, get_email_account, set_email_account, delete_email_account
from .notifications import NOTIFICATION_TYPES, NOTIFICATION_CHANNELS, _NOTIFICATION_CHANNEL_COLUMNS, _NOTIFICATION_CHANNEL_DEFAULTS, _NOTIFICATION_TYPE_KEYS, _notification_prefs_cache, _notification_default, get_notification_default, set_notification_default, _notification_overrides, notification_enabled, get_notification_prefs, set_notification_pref, reset_notification_prefs, mark_notifications_read_by_target
from .notifications import NOTIFICATION_TYPES, NOTIFICATION_CHANNELS, _NOTIFICATION_CHANNEL_COLUMNS, _NOTIFICATION_CHANNEL_DEFAULTS, _NOTIFICATION_TYPE_KEYS, _notification_prefs_cache, _notification_default, get_notification_default, set_notification_default, _notification_overrides, notification_enabled, get_notification_prefs, set_notification_pref, reset_notification_prefs, mark_notifications_read_by_target, NOTIFICATION_GROUP_KEYS, notification_group_key, notification_throttle_key, get_notification_grouping_enabled, set_notification_grouping_enabled, get_notification_throttle_enabled, set_notification_throttle_enabled, count_unread_groups
from .enter_submit import get_enter_to_submit, set_enter_to_submit
from .forks import record_fork, get_fork_parent, count_forks, soft_delete_fork_relations, delete_fork_relations
from .follows import get_follow_counts, get_follow_list, get_following_among
from .deepsearch import _ds_now, create_deepsearch_session, update_deepsearch_session, get_deepsearch_session, list_deepsearch_sessions, add_deepsearch_message, get_deepsearch_messages, get_cached_deepsearch_url, upsert_deepsearch_url_cache
@@ -207,6 +209,20 @@ __all__ = [
"has_fresh_seo_metadata",
"upsert_seo_metadata",
"mark_seo_metadata_stale",
"OBJECT_IMAGE_TYPES",
"OBJECT_IMAGE_RETENTION_DAYS",
"OG_WIDTH",
"OG_HEIGHT",
"THUMB_WIDTH",
"THUMB_HEIGHT",
"get_current_object_image",
"current_object_image_map",
"current_object_image_url",
"record_object_image",
"note_object_image_served",
"remove_object_image",
"restore_object_image",
"purge_object_images",
"record_activity",
"record_unique_activity",
"get_user_activity",
@@ -251,6 +267,16 @@ __all__ = [
"set_notification_pref",
"reset_notification_prefs",
"mark_notifications_read_by_target",
"NOTIFICATION_GROUP_KEYS",
"notification_group_key",
"notification_throttle_key",
"get_notification_grouping_enabled",
"set_notification_grouping_enabled",
"get_notification_throttle_enabled",
"set_notification_throttle_enabled",
"count_unread_groups",
"get_enter_to_submit",
"set_enter_to_submit",
"record_fork",
"get_fork_parent",
"count_forks",
+22
View File
@@ -0,0 +1,22 @@
# retoor <retoor@molodetz.nl>
from .core import db, get_table
def get_enter_to_submit(owner_id: str) -> bool:
if "users" not in db.tables:
return True
user = db["users"].find_one(uid=owner_id)
if user is None:
return True
value = user.get("enter_to_submit")
return True if value is None else bool(value)
def set_enter_to_submit(owner_id: str, enabled: bool) -> None:
from devplacepy.utils import clear_user_cache
get_table("users").update(
{"uid": owner_id, "enter_to_submit": 1 if enabled else 0}, ["uid"]
)
clear_user_cache(owner_id)
+3
View File
@@ -64,6 +64,7 @@ UNREPORTABLE_TABLES: dict[str, str] = {
"quiz_answers": "private to the participant",
"sessions": "authentication state",
"access_tokens": "authentication state",
"mcp_tokens": "authentication state",
"devrant_tokens": "authentication state",
"user_relations": "private block and mute lists",
"notification_preferences": "private to the owner",
@@ -88,6 +89,8 @@ UNREPORTABLE_TABLES: dict[str, str] = {
"backup_schedules": "operator configuration",
"project_forks": "lineage index for reportable projects",
"seo_metadata": "generated metadata for reportable content",
"object_images": "generated social images for reportable content",
"link_preview_cache": "generated public URL metadata cache, not authored content",
}
+11 -2
View File
@@ -592,14 +592,23 @@ def raise_flag(kind: str, *, device_uid: str = "", user_uid: str = "", detail: s
return table.find_one(uid=uid)
def list_flags(status: str = FLAG_OPEN) -> list[dict]:
def list_flags(status: str = FLAG_OPEN, limit: int | None = None) -> list[dict]:
window = {} if limit is None else {"_limit": limit}
return list(
get_table("node_flags").find(
status=status, deleted_at=None, order_by=["-created_at"]
status=status, deleted_at=None, order_by=["-created_at"], **window
)
)
def count_flags(status: str = FLAG_OPEN) -> int:
return get_table("node_flags").count(status=status, deleted_at=None)
def count_all_devices() -> int:
return get_table("node_devices").count(deleted_at=None)
def resolve_flag(flag_uid: str, actor_uid: str) -> bool:
return (
_execute(
+84
View File
@@ -204,3 +204,87 @@ def mark_notifications_read_by_target(user_uid: str, target_url: str) -> int:
clear_unread_cache(user_uid)
return len(ids)
NOTIFICATION_GROUP_KEYS = {
"comment": "actor",
"reply": "actor",
"thread": "actor",
"mention": "actor",
"message": "actor",
"harvest_stolen": "actor",
"award": "actor",
"quiz_attempt": "actor",
"vote": "target",
"follow": "target",
"badge": "single",
"level": "single",
"issue": "single",
"reminder": "single",
"battle": "single",
"workspace": "single",
"moderation": "single",
"system": "single",
"ai_quota_warning": "single",
"game_upkeep": "single",
}
def notification_group_key(row) -> tuple:
ntype = (row.get("type") or "")
shape = NOTIFICATION_GROUP_KEYS.get(ntype, "single")
if shape == "actor":
return (ntype, row.get("related_uid") or "", row.get("target_url") or "")
if shape == "target":
if ntype == "follow":
return (ntype,)
return (ntype, row.get("target_url") or "")
return (ntype, row.get("uid") or "")
def notification_throttle_key(user_uid: str, notification_type: str, related_uid: str, target_url) -> tuple:
row = {"type": notification_type, "related_uid": related_uid or "", "target_url": target_url or "", "uid": ""}
return (user_uid,) + notification_group_key(row)
def _user_bool_pref(user_uid: str, column: str) -> bool:
if "users" not in db.tables:
return True
user = db["users"].find_one(uid=user_uid)
if user is None:
return True
value = user.get(column)
return True if value is None else bool(value)
def get_notification_grouping_enabled(user_uid: str) -> bool:
return _user_bool_pref(user_uid, "notif_grouping_enabled")
def get_notification_throttle_enabled(user_uid: str) -> bool:
return _user_bool_pref(user_uid, "notif_throttle_enabled")
def _set_user_bool_pref(user_uid: str, column: str, enabled: bool) -> None:
from devplacepy.utils import clear_user_cache
get_table("users").update({"uid": user_uid, column: 1 if enabled else 0}, ["uid"])
clear_user_cache(user_uid)
bump_cache_version("notif_prefs")
def set_notification_grouping_enabled(user_uid: str, enabled: bool) -> None:
_set_user_bool_pref(user_uid, "notif_grouping_enabled", enabled)
def set_notification_throttle_enabled(user_uid: str, enabled: bool) -> None:
_set_user_bool_pref(user_uid, "notif_throttle_enabled", enabled)
def count_unread_groups(user_uid: str) -> int:
if "notifications" not in db.tables:
return 0
rows = list(get_table("notifications").find(user_uid=user_uid, read=False))
if not get_notification_grouping_enabled(user_uid):
return len(rows)
return len({notification_group_key(row) for row in rows})
+198
View File
@@ -0,0 +1,198 @@
# retoor <retoor@molodetz.nl>
from sqlalchemy.exc import IntegrityError
from .core import _in_clause, _now_iso, db, get_table
OBJECT_IMAGE_TYPES = ("post", "gist", "project")
OBJECT_IMAGE_RETENTION_DAYS = 30
OG_WIDTH = 1200
OG_HEIGHT = 630
THUMB_WIDTH = 400
THUMB_HEIGHT = 210
def _table():
return get_table("object_images")
def get_current_object_image(target_type: str, target_uid: str) -> dict | None:
if not target_type or not target_uid or "object_images" not in db.tables:
return None
row = _table().find_one(
target_type=target_type,
target_uid=str(target_uid),
is_current=1,
status="active",
deleted_at=None,
)
return dict(row) if row else None
def current_object_image_url(target_type: str, target_uid: str) -> str:
row = get_current_object_image(target_type, target_uid)
return (row or {}).get("url") or ""
def current_object_image_map(target_type: str, target_uids: list) -> dict:
uids = [str(uid) for uid in (target_uids or []) if uid]
if not target_type or not uids or "object_images" not in db.tables:
return {}
placeholders, params = _in_clause(uids)
params["tt"] = target_type
rows = db.query(
f"SELECT target_uid, url FROM object_images "
f"WHERE target_type = :tt AND target_uid IN ({placeholders}) "
f"AND is_current = 1 AND status = 'active' AND deleted_at IS NULL",
**params,
)
return {str(row["target_uid"]): row["url"] for row in rows if row.get("url")}
def record_object_image(
target_type: str,
target_uid: str,
url: str,
prompt: str,
model: str,
user_uid: str = "",
filename: str = "",
original_url: str = "",
thumb_url: str = "",
width: int = OG_WIDTH,
height: int = OG_HEIGHT,
mimetype: str = "image/jpeg",
) -> dict:
from devplacepy.utils import generate_uid
now = _now_iso()
row = {
"uid": generate_uid(),
"target_type": target_type,
"target_uid": str(target_uid),
"user_uid": user_uid or "",
"filename": filename or "",
"url": url,
"original_url": original_url or "",
"thumb_url": thumb_url or "",
"prompt": prompt,
"model": model,
"width": int(width or OG_WIDTH),
"height": int(height or OG_HEIGHT),
"mimetype": mimetype or "image/jpeg",
"view_count": 0,
"is_current": 1,
"status": "active",
"created_at": now,
"deleted_at": None,
"deleted_by": None,
}
for _ in range(4):
try:
with db:
for old in _table().find(
target_type=target_type,
target_uid=str(target_uid),
is_current=1,
deleted_at=None,
):
_table().update({"id": old["id"], "is_current": 0}, ["id"])
_table().insert(row)
return row
except IntegrityError:
continue
with db:
for old in _table().find(
target_type=target_type,
target_uid=str(target_uid),
is_current=1,
deleted_at=None,
):
_table().update({"id": old["id"], "is_current": 0}, ["id"])
_table().insert(row)
return row
def note_object_image_served(uid: str) -> None:
if not uid or "object_images" not in db.tables:
return
row = _table().find_one(uid=uid, deleted_at=None)
if not row:
return
_table().update(
{"id": row["id"], "view_count": int(row.get("view_count") or 0) + 1},
["id"],
)
def remove_object_image(uid: str, deleted_by: str = "") -> bool:
if not uid or "object_images" not in db.tables:
return False
row = _table().find_one(uid=uid, deleted_at=None)
if not row:
return False
now = _now_iso()
with db:
_table().update(
{
"id": row["id"],
"is_current": 0,
"status": "deleted",
"deleted_at": now,
"deleted_by": deleted_by or None,
},
["id"],
)
return True
def restore_object_image(uid: str) -> bool:
if not uid or "object_images" not in db.tables:
return False
row = _table().find_one(uid=uid)
if not row or not row.get("deleted_at"):
return False
with db:
_table().update(
{
"id": row["id"],
"status": "active",
"deleted_at": None,
"deleted_by": None,
},
["id"],
)
current = _table().find_one(
target_type=row["target_type"],
target_uid=row["target_uid"],
is_current=1,
status="active",
deleted_at=None,
)
if current is None:
_table().update({"id": row["id"], "is_current": 1}, ["id"])
return True
def purge_object_images(retention_days: int = OBJECT_IMAGE_RETENTION_DAYS) -> list[dict]:
from datetime import datetime, timedelta, timezone
if "object_images" not in db.tables:
return []
cutoff = (datetime.now(timezone.utc) - timedelta(days=retention_days)).isoformat()
rows = [
dict(row)
for row in _table().find(status="deleted")
if row.get("deleted_at") and str(row["deleted_at"]) <= cutoff
]
if not rows:
return []
placeholders, params = _in_clause([row["uid"] for row in rows], prefix="o")
with db:
db.query(
f"DELETE FROM object_images WHERE uid IN ({placeholders})", **params
)
return rows
+76
View File
@@ -126,6 +126,19 @@ def init_db():
access_tokens.create_column_by_example(column, example)
_index(db, "access_tokens", "idx_access_tokens_token", ["token"])
_index(db, "access_tokens", "idx_access_tokens_user", ["user_uid"])
if "mcp_tokens" in tables:
mcp_tokens = get_table("mcp_tokens")
for column, example in (
("uid", ""),
("token", ""),
("user_uid", ""),
("label", ""),
("created_at", ""),
):
if not mcp_tokens.has_column(column):
mcp_tokens.create_column_by_example(column, example)
_index(db, "mcp_tokens", "idx_mcp_tokens_token", ["token"], unique=True)
_index(db, "mcp_tokens", "idx_mcp_tokens_user", ["user_uid"])
if "telegram_pairings" in tables:
telegram_pairings = get_table("telegram_pairings")
for column, example in (
@@ -200,6 +213,19 @@ def init_db():
)
_index(db, "messages", "idx_messages_updated_at", ["updated_at"])
_index(db, "messages", "idx_messages_dedupe", ["sender_uid", "client_id"])
notifications = get_table("notifications")
for column, example in (
("uid", ""),
("user_uid", ""),
("type", ""),
("message", ""),
("related_uid", ""),
("target_url", ""),
("read", False),
("created_at", ""),
):
if not notifications.has_column(column):
notifications.create_column_by_example(column, example)
_index(db, "notifications", "idx_notifications_user", ["user_uid"])
_index(db, "notifications", "idx_notifications_user_read", ["user_uid", "read"])
push_registration = get_table("push_registration")
@@ -685,6 +711,7 @@ def init_db():
("inter_token_ms", 0.0),
("provider", ""),
("fallback_used_route", ""),
("resolved_method", ""),
):
if not gateway_usage_ledger.has_column(column):
gateway_usage_ledger.create_column_by_example(column, example)
@@ -950,6 +977,10 @@ def init_db():
gateway_routing.ensure_tables()
from devplacepy.services.openai_gateway import learned as gateway_learned
gateway_learned.ensure_table()
from devplacepy.services.openai_gateway import quota as gateway_quota
gateway_quota.ensure_tables()
@@ -1195,6 +1226,45 @@ def init_db():
unique=True,
)
object_images = get_table("object_images")
for column, example in (
("uid", ""),
("target_type", ""),
("target_uid", ""),
("user_uid", ""),
("filename", ""),
("url", ""),
("original_url", ""),
("thumb_url", ""),
("prompt", ""),
("model", ""),
("width", 1200),
("height", 630),
("mimetype", "image/jpeg"),
("view_count", 0),
("is_current", 0),
("status", "active"),
("created_at", ""),
("deleted_at", ""),
("deleted_by", ""),
):
if not object_images.has_column(column):
object_images.create_column_by_example(column, example)
_index(
db,
"object_images",
"idx_object_images_target",
["target_type", "target_uid", "status"],
)
_index(
db,
"object_images",
"idx_object_images_current",
["target_type", "target_uid"],
where="is_current = 1",
unique=True,
)
email_accounts = get_table("email_accounts")
for column, example in (
("uid", ""),
@@ -2758,6 +2828,12 @@ def backfill_api_keys() -> int:
users.create_column_by_example("cust_disable_global", 0)
if not users.has_column("cust_disable_pagetype"):
users.create_column_by_example("cust_disable_pagetype", 0)
if not users.has_column("enter_to_submit"):
users.create_column_by_example("enter_to_submit", 1)
if not users.has_column("notif_grouping_enabled"):
users.create_column_by_example("notif_grouping_enabled", 1)
if not users.has_column("notif_throttle_enabled"):
users.create_column_by_example("notif_throttle_enabled", 1)
if not users.has_column("ai_correction_enabled"):
users.create_column_by_example("ai_correction_enabled", 0)
if not users.has_column("ai_correction_prompt"):
+2
View File
@@ -52,9 +52,11 @@ SOFT_DELETE_TABLES = [
"isslop_analyses",
"devrant_tokens",
"access_tokens",
"mcp_tokens",
"email_accounts",
"user_relations",
"seo_metadata",
"object_images",
"awards",
"quizzes",
"quiz_questions",
+43
View File
@@ -796,6 +796,49 @@ four ways to sign requests.
field("app_reference", "json", "string", False, "typosaurus", "App label (the X-App-Reference header). Blank = every app."),
],
),
endpoint(
id="admin-gateway-learned",
method="GET",
path="/admin/gateway/learned",
title="List learned gateway request shapes",
summary=(
"Every request shape the gateway learned automatically after an upstream rejected the "
"default one with an unrecognized-key 400, per provider and target model, plus the "
"resolved/exhausted/healed counters."
),
auth="admin",
sample_response={
"learned": [
{
"provider": "vaids",
"target_model": "deepseek-v4-1-flash-1017-uncensored",
"method": "none",
"thinking_dialect": "none",
"drop_keys": [],
"learned_at": "2026-11-13T00:55:00+00:00",
}
],
"count": 1,
"stats": {"resolved": 1, "exhausted": 0, "healed": 0},
},
),
endpoint(
id="admin-gateway-learned-reset",
method="POST",
path="/admin/gateway/learned/reset",
title="Reset a learned gateway request shape",
summary=(
"Forget the learned method for one provider and target model so the gateway starts from "
"the default shape again. Use provider 'default' for the base upstream."
),
auth="admin",
destructive=True,
params=[
field("provider", "json", "string", False, "vaids", "Provider name, or default."),
field("target_model", "json", "string", True, "deepseek-v4-1-flash-1017-uncensored", "Upstream target model."),
],
sample_response={"ok": True},
),
endpoint(
id="admin-gateway-quota-rule-delete",
method="DELETE",
+35 -8
View File
@@ -23,8 +23,10 @@ The POST endpoints are **actions**: they accept form fields, set or clear the `s
and return a `302` redirect (or the JSON envelope for JSON callers).
**Sign-up requires a unique `username` and `email`** plus a `confirm_password` that matches the
password; **you log in with your `email` and password**. JSON callers receive validation errors
as a `422` with the shape `{ "fields": {...}, "messages": [...] }`.
password; **you log in with your `username` or your `email`, plus your password** (the `email`
field accepts either identifier; usernames are case-sensitive, email addresses are not). The
same identifier rule applies to `POST /auth/token` and HTTP Basic. JSON callers receive
validation errors as a `422` with the shape `{ "fields": {...}, "messages": [...] }`.
""",
"endpoints": [
endpoint(
@@ -89,20 +91,20 @@ as a `422` with the shape `{ "fields": {...}, "messages": [...] }`.
method="POST",
path="/auth/login",
title="Log in",
summary="Authenticate with email and password. Sets the session cookie.",
summary="Authenticate with username (or email) and password. Sets the session cookie.",
auth="public",
encoding="form",
params=[
field("email", "form", "string", True, "alice@example.com", "Your registered email."),
field("email", "form", "string", True, "alice@example.com", "Your username or your registered email."),
field("password", "form", "string", True, "mysecret", "Your password."),
field("remember_me", "form", "string", False, "on", "Send 'on' to extend the session to the remember-me lifetime."),
field("next", "form", "string", False, "", "Redirect target after login."),
],
notes=[
"JSON callers receive the account's `email`, `api_key`, and "
"`is_admin` flag in `data`, so a script can trade one email/password "
"login for a reusable key. Failed logins return 401 and never "
"include the key.",
"JSON callers receive the account's `username`, `email`, `api_key`, "
"and `is_admin` flag in `data`, so a script can trade one "
"username/password or email/password login for a reusable key. "
"Failed logins return 401 and never include the key.",
],
sample_response={
"ok": True,
@@ -115,6 +117,31 @@ as a `422` with the shape `{ "fields": {...}, "messages": [...] }`.
},
},
),
endpoint(
id="auth-token",
method="POST",
path="/auth/token",
title="Issue access token",
summary="Exchange username (or email) and password for a short-lived access token. No session cookie is set.",
auth="public",
encoding="form",
params=[
field("email", "form", "string", True, "alice@example.com", "Your username or your registered email."),
field("password", "form", "string", True, "mysecret", "Your password."),
],
notes=[
"Accepts a JSON body with the same fields. The returned token "
"works as an `Authorization: Bearer` or `X-API-KEY` credential "
"until it expires (default 7 days). Missing fields return 400, "
"wrong credentials 401, a deactivated account 403; failures "
"never include a token.",
],
sample_response={
"access_token": "ACCESS_TOKEN",
"token_type": "bearer",
"expires_in": 604800,
},
),
endpoint(
id="auth-forgot-password",
method="GET",
+5 -4
View File
@@ -19,10 +19,11 @@ Every example uses your current host:
## Authentication
Each endpoint is tagged **public**, **user**, or **admin**. Authenticate user and admin
endpoints with any of the four methods in [Authentication](/docs/authentication.html): the
`session` cookie, an `X-API-KEY` header, a `Bearer` token, or HTTP Basic credentials. The
interactive panels on this site pre-fill your own API key, so you can run user-level calls
immediately.
endpoints with any of the methods in [Authentication](/docs/authentication.html): the
`session` cookie, an `X-API-KEY` header, a `Bearer` token, or HTTP Basic credentials
(username or email, plus password; the headers also accept native access tokens and
DevRant auth tokens). The interactive panels on this site pre-fill your own API key, so
you can run user-level calls immediately.
## Request bodies
+119
View File
@@ -36,6 +36,12 @@ generic model `molodetz-img-small`, which the gateway maps to the configured ima
Flux 1.1 Pro by default). Cost is tracked per call with a flat per-image price when the upstream
returns no native cost.
The gateway also serves async **media predictions** at `/openai/v1/media/predictions` (Pruna-backed:
text-to-image today, video and trainers later). A creation validates the prompt, estimates the USD cost,
rejects estimates over the per-call ceiling, queues a `media` job, and returns `202` with a prediction id.
Poll `GET .../{id}` for status (`pending`, `running`, `succeeded`, `failed`, `cancelled`), `POST .../{id}/cancel`
to cancel a live prediction, and `GET .../{id}/files` for finished-file attachments.
## Quick start
Copy the command below and paste it into a terminal. If you are signed in the `{{ api_key }}`
@@ -280,6 +286,119 @@ not this throttle.
"If `model` matches a configured image model route it is forwarded to that route's provider and upstream model; otherwise it falls back to the configured default image model.",
],
),
endpoint(
id="gateway-media-predictions",
method="POST",
path="/openai/v1/media/predictions",
title="Create media prediction",
summary="Queue an async media prediction. Returns 202 with a prediction id.",
auth="user",
encoding="json",
params=[
field(
"model",
"json",
"string",
False,
"molodetz-media-small",
"Media model id; unknown names fall back to the configured media model.",
),
field(
"prompt",
"json",
"string",
True,
'"a neon server room at night"',
"Text prompt describing the media to generate (max 4000 characters).",
),
field(
"count",
"json",
"string",
False,
"1",
"Outputs to generate (1-4).",
),
field(
"steps",
"json",
"string",
False,
"0",
"Optional diffusion steps override for cost estimation.",
),
field(
"seconds",
"json",
"string",
False,
"0",
"Optional duration override for video cost estimation.",
),
],
notes=[
"Returns `503` when media predictions are disabled.",
"Returns `400 media_ceiling_exceeded` when the estimate exceeds gateway_media_max_usd_per_call.",
],
),
endpoint(
id="gateway-media-status",
method="GET",
path="/openai/v1/media/predictions/{id}",
title="Media prediction status",
summary="Poll a media prediction. Owners and admins only.",
auth="user",
interactive=False,
params=[
field(
"id",
"path",
"string",
True,
"prediction uid",
"Prediction uid returned by the create call.",
)
],
),
endpoint(
id="gateway-media-cancel",
method="POST",
path="/openai/v1/media/predictions/{id}/cancel",
title="Cancel media prediction",
summary="Cancel a pending or running prediction. Finished predictions return 409.",
auth="user",
interactive=False,
destructive=True,
params=[
field(
"id",
"path",
"string",
True,
"prediction uid",
"Prediction uid returned by the create call.",
)
],
),
endpoint(
id="gateway-media-files",
method="GET",
path="/openai/v1/media/predictions/{id}/files",
title="Media prediction files",
summary="List finished-file attachments for a prediction. Owners and admins only.",
auth="user",
interactive=False,
params=[
field(
"id",
"path",
"string",
True,
"prediction uid",
"Prediction uid returned by the create call.",
)
],
),
endpoint(
id="gateway-passthrough",
method="POST",
+1 -2
View File
@@ -8,8 +8,7 @@ GROUP = {
"intro": """
# Notifications
Read your notification feed and mark items read. The unread counts endpoint backs the badges
in the navigation bar. Deliver these to the browser with [Web Push](/docs/push.html).
Read your notification feed and mark items read. With grouping on (the default, a profile setting), similar events share one entry in `event_entries` and the unread counts count groups; with it off, entries stay one per event. Repeat external alerts are throttled to one per similar event group per 5 minutes unless the user turned throttling off; in-app rows are never throttled. The unread counts endpoint backs the badges in the navigation bar. Deliver these to the browser with [Web Push](/docs/push.html).
Every endpoint follows the shared [Conventions & Errors](/docs/conventions.html) (auth, content
negotiation, pagination, status codes); see [Authentication](/docs/authentication.html) for the
+47 -1
View File
@@ -379,7 +379,11 @@ four ways to sign requests.
"> Running this invalidates the key these documentation panels use. Do it from your "
"[profile page](/profile/{{ username }}) instead, then reload these docs.",
],
sample_response={"api_key": "NEW_UUID"},
sample_response={
"api_key": "NEW_UUID",
"username": "alice",
"email": "alice@example.com",
},
),
endpoint(
id="profile-give-award",
@@ -500,6 +504,48 @@ four ways to sign requests.
),
],
),
endpoint(
id="profile-enter-to-submit",
method="POST",
path="/profile/{username}/enter-to-submit",
title="Toggle Enter to send",
summary="Enter posts comments and sends messages; Shift+Enter adds a new line. Admins may target any user.",
auth="user",
encoding="form",
destructive=True,
params=[
field("username", "path", "string", True, "bob_test", "Profile owner. Must be yourself unless you are an admin."),
field("value", "form", "boolean", False, "1", "1 for Enter to send, 0 for Enter adds a new line."),
],
),
endpoint(
id="profile-notification-grouping",
method="POST",
path="/profile/{username}/notifications/grouping",
title="Toggle grouped notifications",
summary="Group similar notifications into one card; the badge counts groups. Admins may target any user.",
auth="user",
encoding="form",
destructive=True,
params=[
field("username", "path", "string", True, "bob_test", "Profile owner. Must be yourself unless you are an admin."),
field("value", "form", "boolean", False, "1", "1 to group, 0 to show every event."),
],
),
endpoint(
id="profile-notification-throttling",
method="POST",
path="/profile/{username}/notifications/throttling",
title="Toggle throttled repeat alerts",
summary="At most one push, Telegram message and toast per similar event group per 5 minutes. In-app is never throttled. Admins may target any user.",
auth="user",
encoding="form",
destructive=True,
params=[
field("username", "path", "string", True, "bob_test", "Profile owner. Must be yourself unless you are an admin."),
field("value", "form", "boolean", False, "1", "1 to throttle repeat alerts, 0 to alert on every event."),
],
),
endpoint(
id="profile-notification-toggle",
method="POST",
+5
View File
@@ -20,6 +20,11 @@ its build. A registration body without a `provider` field is a `webpush` registr
existing clients need no change. An APNs body may include a stable `client_id` so a later
token rotation updates the same device instead of inserting another row.
Every delivered notification carries the recipient's unread count, the same number as
`notifications` in `GET /notifications/counts` ([Notifications](/docs/notifications.html)). `apns` presents it as `aps.badge`,
so a native app icon updates while the app is in the background; `webpush` forwards it as the
`unread` field of the payload.
`DELETE /push.json` removes a single registration by the same identity used to create it
(`endpoint` for webpush, `token` or `client_id` for apns). The server also stops delivering to a
subscription once its push endpoint reports it as gone. These mirror the in-app
+2 -1
View File
@@ -1,6 +1,7 @@
# retoor <retoor@molodetz.nl>
from devplacepy.database import (
count_unread_groups,
db,
get_table,
get_setting,
@@ -71,7 +72,7 @@ def _user_facts(user: dict) -> dict:
"followers": _count("follows", following_uid=uid),
"following": _count("follows", follower_uid=uid),
"bookmarks": _count("bookmarks", user_uid=uid),
"unread_notifications": _count("notifications", user_uid=uid, read=False),
"unread_notifications": count_unread_groups(uid),
"unread_messages": _count("messages", receiver_uid=uid, read=False, deleted_at=None),
},
"recent_posts": [
+6
View File
@@ -30,9 +30,11 @@ from devplacepy.services.jobs.award_service import AwardService
from devplacepy.services.jobs.deepsearch.service import DeepsearchService
from devplacepy.services.jobs.fork_service import ForkService
from devplacepy.services.jobs.issue_create_service import IssueCreateService
from devplacepy.services.jobs.media_service import MediaService
from devplacepy.services.jobs.isslop.service import IsslopService
from devplacepy.services.jobs.planning_service import PlanningReportService
from devplacepy.services.jobs.seo.service import SeoService
from devplacepy.services.jobs.seo_image_service import SeoImageService
from devplacepy.services.jobs.seo_meta_service import SeoMetaService
from devplacepy.services.jobs.zip_service import ZipService
from devplacepy.services.live_view_relay import LiveViewRelayService
@@ -44,6 +46,7 @@ from devplacepy.services.notification_relay import NotificationRelayService
from devplacepy.services.openai_gateway import GatewayService
from devplacepy.services.opinionwar.service import OpinionWarService
from devplacepy.services.presence_relay import PresenceRelayService
from devplacepy.services.project_blob_sweep import ProjectBlobSweepService
from devplacepy.services.pubsub import PubSubService
from devplacepy.services.push import PushService
from devplacepy.services.telegram import TelegramService
@@ -58,9 +61,11 @@ SERVICE_CLASSES = [
GatewayService,
DeviiService,
ZipService,
MediaService,
ForkService,
SeoService,
SeoMetaService,
SeoImageService,
AwardService,
BackupService,
DbApiJobService,
@@ -81,6 +86,7 @@ SERVICE_CLASSES = [
AuditService,
ModerationService,
AcceptanceService,
ProjectBlobSweepService,
CommunityService,
NodesService,
PushService,
+406
View File
@@ -0,0 +1,406 @@
# retoor <retoor@molodetz.nl>
from __future__ import annotations
import html
import re
import time
from html.parser import HTMLParser
from urllib.parse import urljoin, urlparse
from devplacepy import net_guard
from devplacepy.database import (
current_object_image_url,
get_news_images_by_uids,
get_table,
resolve_by_slug,
)
from devplacepy.database.visibility import OPEN_VALUES, is_listed, item_visibility
from devplacepy.rendering import plain_text
from devplacepy.utils import generate_uid
CACHE_TABLE = "link_preview_cache"
CACHE_TTL_SECONDS = 7 * 24 * 3600
FETCH_TIMEOUT_SECONDS = 8.0
MAX_HTML_BYTES = 512 * 1024
MAX_URL_LENGTH = 2000
RATE_WINDOW_SECONDS = 60.0
RATE_MAX_PER_USER = 30
INTERNAL_ROUTES = {
"posts": "posts",
"gists": "gists",
"projects": "projects",
"news": "news",
}
_rate_state: dict[str, list[float]] = {}
def rate_allowed(key: str) -> bool:
now = time.monotonic()
window_start = now - RATE_WINDOW_SECONDS
hits = [moment for moment in _rate_state.get(key, []) if moment > window_start]
if len(hits) >= RATE_MAX_PER_USER:
_rate_state[key] = hits
return False
hits.append(now)
_rate_state[key] = hits
return True
def normalize_url(value: str) -> str:
text = (value or "").strip()
if len(text) > MAX_URL_LENGTH:
raise ValueError("URL too long.")
parsed = urlparse(text)
if parsed.scheme not in ("http", "https") or not parsed.hostname:
raise ValueError("Only http(s) URLs are supported.")
return text
def preview_domain(url: str) -> str:
try:
return (urlparse(url).hostname or "").lower()
except ValueError:
return ""
def absolute_image_url(raw: str, base_url: str) -> str:
candidate = (raw or "").strip()
if not candidate:
return ""
joined = urljoin(base_url, candidate)
parsed = urlparse(joined)
if parsed.scheme not in ("http", "https"):
return ""
return joined
class _MetaParser(HTMLParser):
def __init__(self) -> None:
super().__init__(convert_charrefs=True)
self.meta: dict[str, str] = {}
self.title_parts: list[str] = []
self.in_title = False
self.first_img = ""
self.icon = ""
def handle_starttag(self, tag: str, attrs: list) -> None:
name = tag.lower()
if name == "title":
self.in_title = True
return
if name == "meta":
found = {key.lower(): value for key, value in attrs}
prop = found.get("property", "") or found.get("name", "")
content = found.get("content", "")
if prop and content and prop.lower() not in self.meta:
self.meta[prop.lower()] = content.strip()
return
if name == "link":
found = {key.lower(): value for key, value in attrs}
rel = found.get("rel", "").lower()
href = found.get("href", "").strip()
if href and "icon" in rel and not self.icon:
self.icon = href
return
if name == "img" and not self.first_img:
found = {key.lower(): value for key, value in attrs}
src = found.get("src", "").strip()
if src:
self.first_img = src
def handle_endtag(self, tag: str) -> None:
if tag.lower() == "title":
self.in_title = False
def handle_data(self, data: str) -> None:
if self.in_title:
self.title_parts.append(data.strip())
def parse_preview_html(html_text: str, base_url: str) -> dict:
parser = _MetaParser()
parser.feed(html_text[:MAX_HTML_BYTES])
parser.close()
meta = parser.meta
title = (
meta.get("og:title", "")
or meta.get("twitter:title", "")
or " ".join(part for part in parser.title_parts if part).strip()
)
description = (
meta.get("og:description", "")
or meta.get("twitter:description", "")
or meta.get("description", "")
)
image = (
meta.get("og:image", "")
or meta.get("twitter:image", "")
or parser.first_img
)
icon = meta.get("og:logo", "") or parser.icon
return {
"title": re.sub(r"\s+", " ", title).strip()[:200],
"description": re.sub(r"\s+", " ", description).strip()[:300],
"image": absolute_image_url(image, base_url),
"favicon": absolute_image_url(icon, base_url),
"site": preview_domain(base_url),
}
def internal_target_for(path: str) -> tuple[str, str] | None:
segments = [segment for segment in (path or "").split("/") if segment]
if len(segments) != 2:
return None
table = INTERNAL_ROUTES.get(segments[0].lower())
if not table or not segments[1]:
return None
return table, segments[1]
def internal_preview(
table: str, slug: str, viewer: dict | None, listed_only: bool = False
) -> dict | None:
row = resolve_by_slug(get_table(table), slug)
if not row or row.get("deleted_at"):
return None
if listed_only and not is_listed(table, row):
return None
if table == "projects" and row.get("is_private"):
owner = row.get("user_uid")
if not viewer or viewer.get("uid") != owner:
return None
visibility = item_visibility(table, row)
if visibility not in OPEN_VALUES:
owner = row.get("user_uid") or row.get("author_uid")
if not viewer or viewer.get("uid") != owner:
return None
title = row.get("title") or row.get("name") or slug
body = row.get("content") or row.get("description") or row.get("body") or ""
return {
"kind": "internal",
"table": table,
"title": plain_text(title)[:200],
"description": plain_text(body)[:300],
"image": _internal_image(table, row),
"favicon": "",
"site": "devplace",
"url": f"/{segments_for(table)}/{row.get('slug') or row.get('uid')}",
}
OBJECT_IMAGE_TARGETS = {
"posts": "post",
"gists": "gist",
"projects": "project",
}
def _internal_image(table: str, row: dict) -> str:
target = OBJECT_IMAGE_TARGETS.get(table)
if target:
return current_object_image_url(target, row.get("uid") or "")
if table == "news":
direct = row.get("image_url") or ""
if direct:
return direct
images = get_news_images_by_uids([row.get("uid") or ""])
return images.get(row.get("uid") or "", "")
return ""
def backend_preview(url: str) -> dict | None:
text = (url or "").strip()
if text.startswith("/"):
target = internal_target_for(urlparse(text).path)
if not target:
return None
return internal_preview(target[0], target[1], None, listed_only=True)
try:
target_url = normalize_url(text)
except ValueError:
return None
internal = internal_target_for(urlparse(target_url).path)
if internal:
preview = internal_preview(internal[0], internal[1], None, listed_only=True)
if preview:
return preview
cached = cached_preview(target_url)
if not cached:
return None
cached["url"] = target_url
cached["kind"] = "external"
return cached
def _card_image_src(preview: dict) -> str:
image = preview.get("image") or ""
if image.startswith("https://"):
return image
if preview.get("kind") == "internal" and image.startswith("/"):
return image
return ""
def render_card_html(preview: dict) -> str:
url = preview.get("url") or ""
title = preview.get("title") or preview.get("site") or url
description = preview.get("description") or ""
site = preview.get("site") or ""
favicon = preview.get("favicon") or ""
href = html.escape(url, quote=True)
rel = "noopener" if preview.get("kind") == "internal" else "noopener nofollow ugc"
image = _card_image_src(preview)
if image:
image_html = (
'<span class="link-card-image"><img src="'
+ html.escape(image, quote=True)
+ '" alt="'
+ html.escape(title, quote=True)
+ '" loading="lazy"></span>'
)
else:
image_html = ""
if favicon and (favicon.startswith("https://") or favicon.startswith("/")):
site_html = (
'<span class="link-card-site"><img class="link-card-favicon" src="'
+ html.escape(favicon, quote=True)
+ '" alt="" loading="lazy">'
+ html.escape(site)
+ "</span>"
)
elif site:
site_html = '<span class="link-card-site">' + html.escape(site) + "</span>"
else:
site_html = ""
if description:
desc_html = '<span class="link-card-desc">' + html.escape(description) + "</span>"
else:
desc_html = ""
return (
'<a class="link-card" href="'
+ href
+ '" target="_blank" rel="'
+ rel
+ '" data-link-preview="'
+ href
+ '">'
+ image_html
+ '<span class="link-card-body"><span class="link-card-title">'
+ html.escape(title)
+ "</span>"
+ desc_html
+ site_html
+ "</span></a>"
)
def segments_for(table: str) -> str:
for segment, name in INTERNAL_ROUTES.items():
if name == table:
return segment
return table
def cached_preview(url: str) -> dict | None:
table = get_table(CACHE_TABLE)
row = table.find_one(url=url, deleted_at=None)
if not row:
return None
fetched = row.get("fetched_at") or ""
try:
from datetime import datetime, timezone
moment = datetime.fromisoformat(str(fetched))
if not moment.tzinfo:
moment = moment.replace(tzinfo=timezone.utc)
age = (datetime.now(timezone.utc) - moment).total_seconds()
except ValueError:
return None
if age > CACHE_TTL_SECONDS:
return None
return {
"title": row.get("title") or "",
"description": row.get("description") or "",
"image": row.get("image") or "",
"favicon": row.get("favicon") or "",
"site": row.get("site") or preview_domain(url),
}
def store_preview(url: str, preview: dict) -> None:
from devplacepy.database import db
from devplacepy.database.core import _now_iso
table = get_table(CACHE_TABLE)
for column, example in (
("uid", ""),
("url", ""),
("title", ""),
("description", ""),
("image", ""),
("favicon", ""),
("site", ""),
("fetched_at", ""),
("deleted_at", ""),
("deleted_by", ""),
):
if not table.has_column(column):
table.create_column_by_example(column, example)
existing = table.find_one(url=url)
payload = {
"url": url,
"title": preview.get("title") or "",
"description": preview.get("description") or "",
"image": preview.get("image") or "",
"favicon": preview.get("favicon") or "",
"site": preview.get("site") or preview_domain(url),
"fetched_at": _now_iso(),
"deleted_at": None,
"deleted_by": None,
}
if existing:
with db:
db.query(
"UPDATE link_preview_cache SET title=:title, description=:description, "
"image=:image, favicon=:favicon, site=:site, fetched_at=:fetched_at, "
"deleted_at=NULL, deleted_by=NULL WHERE url=:url",
**{**payload},
)
return
payload["uid"] = generate_uid()
table.insert(payload)
async def fetch_external_preview(url: str) -> dict:
await net_guard.guard_public_url(url)
client = net_guard.guarded_async_client(timeout=FETCH_TIMEOUT_SECONDS)
async with client:
response = await client.get(
url, headers={"Accept": "text/html,application/xhtml+xml"}
)
response.raise_for_status()
content_type = response.headers.get("content-type", "")
if "html" not in content_type.lower():
raise ValueError("Target is not an HTML page.")
body = response.text[:MAX_HTML_BYTES]
preview = parse_preview_html(body, url)
if not preview.get("title"):
raise ValueError("No preview metadata found.")
preview["url"] = url
preview["kind"] = "external"
return preview
def preview_fallback(url: str) -> dict:
return {
"kind": "external",
"title": preview_domain(url),
"description": url[:300],
"image": "",
"favicon": "",
"site": preview_domain(url),
"url": url,
}
+13
View File
@@ -39,6 +39,7 @@ from devplacepy.routers import (
quizzes,
uploads,
giphy,
link_preview,
media,
push,
leaderboard,
@@ -51,6 +52,7 @@ from devplacepy.routers import (
docs,
openai_gateway,
devii,
mcp,
zips,
forks,
proxy,
@@ -77,6 +79,15 @@ logging.getLogger("alembic.runtime.migration").setLevel(logging.WARNING)
app = FastAPI(
title="DevPlace",
description=(
"Authentication: username+password, email+password (login form, JSON "
"POST /auth/login, POST /auth/token, and HTTP Basic all accept the "
"username or the email address), or the personal API key from the "
"profile page sent as X-API-KEY or Authorization: Bearer "
"(conventionally carried in the DEVPLACE_API_KEY environment variable). "
"GET /profile with an API key returns the account username, email, and "
"API key. Full reference: /docs/authentication.html"
),
docs_url="/swagger",
redoc_url=None,
openapi_url="/openapi.json",
@@ -123,11 +134,13 @@ app.include_router(push.router)
app.include_router(docs.router)
app.include_router(openai_gateway.router, prefix="/openai")
app.include_router(devii.router, prefix="/devii")
app.include_router(mcp.router)
app.include_router(issues.router, prefix="/issues")
app.include_router(gists.router, prefix="/gists")
app.include_router(news.router, prefix="/news")
app.include_router(uploads.router, prefix="/uploads")
app.include_router(giphy.router, prefix="/giphy")
app.include_router(link_preview.router, prefix="/link-preview")
app.include_router(media.router, prefix="/media")
app.include_router(zips.router, prefix="/zips")
app.include_router(forks.router, prefix="/forks")
+14 -2
View File
@@ -14,6 +14,9 @@ from devplacepy.templating import templates
from devplacepy.utils import client_ip, get_current_user
RATE_LIMIT_EXEMPT_PREFIXES = ("/openai", "/xmlrpc", "/mcp")
async def rate_limit_middleware(request: Request, call_next):
if state.RATE_LIMIT_DISABLED:
return await call_next(request)
@@ -22,7 +25,7 @@ async def rate_limit_middleware(request: Request, call_next):
"PUT",
"DELETE",
"PATCH",
) and not request.url.path.startswith(("/openai", "/xmlrpc")):
) and not request.url.path.startswith(RATE_LIMIT_EXEMPT_PREFIXES):
settings = state._hot_settings()
limit = state._worker_rate_limit(settings["rate_limit_per_minute"])
window = settings["rate_limit_window_seconds"]
@@ -57,7 +60,16 @@ async def rate_limit_middleware(request: Request, call_next):
return await call_next(request)
_MAINTENANCE_ALLOWED_PREFIXES = ("/static", "/avatar", "/auth", "/admin", "/openai")
# /mcp stays up in maintenance mode, consistent with /openai: token holders
# keep their harness access while page POSTs are gated for non-admins.
_MAINTENANCE_ALLOWED_PREFIXES = (
"/static",
"/avatar",
"/auth",
"/admin",
"/openai",
"/mcp",
)
async def maintenance_middleware(request: Request, call_next):
+2
View File
@@ -44,6 +44,7 @@ from devplacepy.models.projects import (
)
from devplacepy.models.profile import (
CustomizationToggleForm,
EnterToSubmitForm,
AwardGiveForm,
NotificationPrefForm,
AiCorrectionForm,
@@ -195,6 +196,7 @@ __all__ = [
"ProjectFileDeleteLinesForm",
"ProjectFileAppendForm",
"CustomizationToggleForm",
"EnterToSubmitForm",
"AwardGiveForm",
"NotificationPrefForm",
"AiCorrectionForm",
+4
View File
@@ -12,6 +12,10 @@ class CustomizationToggleForm(BaseModel):
value: bool = False
class EnterToSubmitForm(BaseModel):
value: bool = True
class AwardGiveForm(BaseModel):
description: str = Field(min_length=1, max_length=125)
+109 -46
View File
@@ -21,6 +21,9 @@ MAX_SEGMENT_LENGTH = 255
MAX_DEPTH = 32
_MISSING_BLOB_LOG_SECONDS = 60
_missing_blob_logged: dict[str, tuple[int, float]] = {}
MISSING_BLOB_RETRY_SECONDS = 600
MISSING_BLOB_MAX_TRACKED = 10000
_missing_blob_until: dict[tuple[str, str], float] = {}
TEXT_EXTENSIONS = {
".txt",
@@ -341,6 +344,18 @@ def _unlink_blob(node: dict) -> None:
)
def _blob_matches(node: dict, data: bytes) -> bool:
if not (node.get("is_binary") and node.get("stored_name") and node.get("directory")):
return False
if node.get("size") != len(data):
return False
try:
blob = PROJECT_FILES_DIR / node["directory"] / node["stored_name"]
return blob.read_bytes() == data
except OSError:
return False
def store_upload(
project_uid: str, user: dict, dir_path: str, filename: str, data: bytes
) -> dict:
@@ -365,46 +380,53 @@ def store_upload(
existing = get_node(project_uid, path)
if existing is not None and existing["type"] == "dir":
raise ProjectFileError(f"'{path}' is a directory")
if existing is not None and _blob_matches(existing, data):
return existing
if existing is None:
_guard_capacity(project_uid)
stored_name, directory, mime = _store_blob(data, base)
if existing is not None:
if existing.get("is_binary"):
_unlink_blob(existing)
_table().update(
{
"uid": existing["uid"],
"content": None,
"is_binary": 1,
"stored_name": stored_name,
"directory": directory,
"mime_type": mime,
"size": len(data),
"updated_at": _now(),
},
["uid"],
)
return get_node(project_uid, path)
_guard_capacity(project_uid)
_table().insert(
{
"uid": generate_uid(),
"project_uid": project_uid,
"deleted_at": None,
"deleted_by": None,
"user_uid": user["uid"],
"path": path,
"name": base,
"parent_path": _parent_of(path),
"type": "file",
"content": None,
"is_binary": 1,
"stored_name": stored_name,
"directory": directory,
"mime_type": mime,
"size": len(data),
"created_at": _now(),
"updated_at": _now(),
}
)
try:
if existing is not None:
_table().update(
{
"uid": existing["uid"],
"content": None,
"is_binary": 1,
"stored_name": stored_name,
"directory": directory,
"mime_type": mime,
"size": len(data),
"updated_at": _now(),
},
["uid"],
)
else:
_table().insert(
{
"uid": generate_uid(),
"project_uid": project_uid,
"deleted_at": None,
"deleted_by": None,
"user_uid": user["uid"],
"path": path,
"name": base,
"parent_path": _parent_of(path),
"type": "file",
"content": None,
"is_binary": 1,
"stored_name": stored_name,
"directory": directory,
"mime_type": mime,
"size": len(data),
"created_at": _now(),
"updated_at": _now(),
}
)
except Exception:
_unlink_blob({"stored_name": stored_name, "directory": directory})
raise
if existing is not None and existing.get("is_binary"):
_unlink_blob(existing)
return get_node(project_uid, path)
@@ -621,7 +643,7 @@ def sync_dir_bidirectional(project_uid: str, workspace, user: dict) -> dict:
new_manifest[path] = entry
continue
if db_epoch >= fs_epoch - _SYNC_CLOCK_SKEW_SECONDS or readonly:
recorded = _record_export(row, dest)
recorded = _export_with_backoff(project_uid, row, dest)
if recorded:
counts["exported"] += 1
new_manifest[path] = recorded
@@ -641,7 +663,7 @@ def sync_dir_bidirectional(project_uid: str, workspace, user: dict) -> dict:
or readonly
or db_epoch > entry["db_epoch"] + _SYNC_CLOCK_SKEW_SECONDS
):
recorded = _record_export(row, dest)
recorded = _export_with_backoff(project_uid, row, dest)
if recorded:
counts["exported"] += 1
new_manifest[path] = recorded
@@ -682,6 +704,21 @@ def sync_dir_bidirectional(project_uid: str, workspace, user: dict) -> dict:
return counts
def _export_with_backoff(project_uid: str, row: dict, dest: Path):
key = (project_uid, row["path"])
until = _missing_blob_until.get(key)
if until is not None and time.monotonic() < until:
return None
recorded = _record_export(row, dest)
if recorded is not None or not row.get("is_binary"):
_missing_blob_until.pop(key, None)
return recorded
if len(_missing_blob_until) >= MISSING_BLOB_MAX_TRACKED:
_missing_blob_until.clear()
_missing_blob_until[key] = time.monotonic() + MISSING_BLOB_RETRY_SECONDS
return None
def _record_export(row: dict, dest: Path):
target = _export_node(row, dest)
if target is None:
@@ -1090,9 +1127,7 @@ def purge_soft_deleted_project_files(*, dry_run: bool = False) -> tuple[int, int
return removed, freed
def sweep_orphan_project_file_blobs(*, dry_run: bool = False) -> tuple[int, int]:
if not PROJECT_FILES_DIR.exists():
return 0, 0
def referenced_project_blobs() -> set:
referenced = set()
if "project_files" in db.tables:
for row in _table().find(is_binary=1):
@@ -1100,8 +1135,21 @@ def sweep_orphan_project_file_blobs(*, dry_run: bool = False) -> tuple[int, int]
stored_name = row.get("stored_name")
if directory and stored_name:
referenced.add((directory, stored_name))
return referenced
def sweep_project_blob_tree(
referenced: set,
*,
dry_run: bool = False,
min_age_seconds: float = 0,
limit: int | None = None,
) -> tuple[int, int]:
if not PROJECT_FILES_DIR.exists():
return 0, 0
removed = 0
freed = 0
cutoff = time.time() - min_age_seconds
base = str(PROJECT_FILES_DIR)
for root, _dirs, files in os.walk(base):
directory = os.path.relpath(root, base)
@@ -1110,14 +1158,29 @@ def sweep_orphan_project_file_blobs(*, dry_run: bool = False) -> tuple[int, int]
continue
file_path = os.path.join(root, name)
try:
size = os.path.getsize(file_path)
stat = os.stat(file_path)
except OSError:
continue
if stat.st_mtime > cutoff:
continue
if not dry_run:
try:
os.unlink(file_path)
except OSError:
continue
removed += 1
freed += size
freed += stat.st_size
if limit is not None and removed >= limit:
return removed, freed
return removed, freed
def sweep_orphan_project_file_blobs(
*, dry_run: bool = False, min_age_seconds: float = 0, limit: int | None = None
) -> tuple[int, int]:
return sweep_project_blob_tree(
referenced_project_blobs(),
dry_run=dry_run,
min_age_seconds=min_age_seconds,
limit=limit,
)
+2 -1
View File
@@ -76,5 +76,6 @@ A match **updates** the row (token, client_id, environment) and clears `deleted_
- A `.p8` that does not parse is cached as a failure for the same window, so a misconfiguration costs one error log per window rather than one parse per notification.
- **`DEAD_REASONS` is deliberately narrow: only `BadDeviceToken` (400), `Unregistered` (410) and `ExpiredToken` (410).** These are the only reasons in Apple's documented table that describe the TOKEN itself as permanently invalid. `DeviceTokenNotForTopic` and `TopicDisallowed` are 400 errors about the **topic/provisioning matching the connection**, not the token - they fire identically for every token when `push_apns_topic` is misconfigured or the certificate/entitlements don't match, so treating them as dead would soft-delete the entire APNs subscriber base (a table deliberately kept OUT of `SOFT_DELETE_TABLES`, hence unrestorable) on the first delivery after a one-field admin typo. Never add a topic/provisioning-shaped reason to `DEAD_REASONS`.
- **A 410's `timestamp` is honored before deleting.** Apple's 410 body carries `{"reason": "Unregistered", "timestamp": <ms epoch>}` - the instant Apple last confirmed the token dead, which can trail real device state by "several days" per Apple engineering guidance (410 delivery is intentionally non-deterministic; do not use it to infer app-uninstall timing). `apns._dead_before` converts it to ISO and it rides on `Delivery.dead_before`; `store.mark_dead(id, dead_before)` compares it against the row's `registered_at` and **skips the delete** (logs at INFO instead) if the registration was re-registered/revived after that instant - closing the race where an in-flight delivery against a stale row state would otherwise undo a concurrent revival. `dead_before` is only ever set for a 410; the `BadDeviceToken`/`ExpiredToken` paths pass `None` (unconditional delete, as before), since those reasons carry no `timestamp`.
- The shared payload dict (`title`, `message`, `icon`, `url`) is translated once per batch into `aps.alert` plus the custom `url`/`icon` keys, mirroring what `service-worker.js` does for Web Push. `thread-id` mirrors the service worker's notification `tag`.
- The shared payload dict (`title`, `message`, `icon`, `url`, `unread`) is translated once per batch into `aps.alert` plus the custom `url`/`icon` keys, mirroring what `service-worker.js` does for Web Push. `thread-id` mirrors the service worker's notification `tag`.
- **`unread` becomes `aps.badge`.** `unread` is the recipient's unread notification count, `count_unread_groups(user_uid)` (groups when grouping is on, rows when off: the same number as `/notifications/counts`), computed by `utils/notifications.py` `_deliver_notification` right after the in-app insert and only when a push is actually sent. `apns._badge` accepts a non-negative integer (a `bool` is refused) and otherwise omits `aps.badge`, which leaves the app icon untouched; the welcome probe carries no `unread`. iOS applies `aps.badge` itself, so the icon updates while the app is backgrounded or terminated. The key is named `unread`, never `badge`, because `badge` already means the monochrome icon URL in the Notifications API. Web Push forwards the payload unchanged and the service worker ignores the extra key. A throttled push is not sent, so the badge shows the count at the last delivered push until the app is opened.
- `POST /push.json` probes a created or revived row immediately via `notify_registration`. The JSON is `{registered: true, delivered: bool, error?: string}`. `registered` stays true so existing clients keep working; `delivered`/`error` surface Apple's reason instead of killing the row silently from the client's point of view. The row is still marked dead on a `DEAD` outcome (subject to the `dead_before` guard above) so later `notify_user` calls do not keep hitting a known-bad token.
+19 -8
View File
@@ -230,6 +230,13 @@ def _dead_before(response: httpx.Response) -> str | None:
return None
def _badge(payload: dict[str, Any]) -> int | None:
unread = payload.get("unread")
if isinstance(unread, bool) or not isinstance(unread, int) or unread < 0:
return None
return unread
class ApnsProvider(PushProvider):
name = "apns"
label = PROVIDER_LABEL
@@ -323,16 +330,20 @@ class ApnsProvider(PushProvider):
return fields
def prepare(self, payload: dict[str, Any]) -> str:
aps: dict[str, Any] = {
"alert": {
"title": payload.get("title") or "DevPlace",
"body": payload.get("message") or "",
},
"sound": "default",
"thread-id": THREAD_ID,
}
badge = _badge(payload)
if badge is not None:
aps["badge"] = badge
return json.dumps(
{
"aps": {
"alert": {
"title": payload.get("title") or "DevPlace",
"body": payload.get("message") or "",
},
"sound": "default",
"thread-id": THREAD_ID,
},
"aps": aps,
"url": payload.get("url") or DEFAULT_PUSH_URL,
"icon": payload.get("icon") or PUSH_ICON,
}
+1
View File
@@ -100,6 +100,7 @@ def ensure_certificates() -> None:
):
return
lock_path = VAPID_PRIVATE_KEY_FILE.parent / ".vapid.lock"
lock_path.parent.mkdir(parents=True, exist_ok=True)
with open(lock_path, "w") as lock:
fcntl.flock(lock, fcntl.LOCK_EX)
try:
+118 -5
View File
@@ -218,7 +218,7 @@ def _youtube_embed(url: str, budget: _EmbedBudget) -> str | None:
)
def _embed_url(url: str, budget: _EmbedBudget) -> str:
def _embed_url(url: str, budget: _EmbedBudget, standalone: bool = False) -> str:
youtube = _youtube_embed(url, budget)
if youtube:
return youtube
@@ -230,12 +230,38 @@ def _embed_url(url: str, budget: _EmbedBudget) -> str:
return f'<video src="{escaped}" controls preload="metadata"></video>'
if _AUDIO_RE.search(url):
return f'<audio src="{escaped}" controls preload="metadata"></audio>'
if standalone:
return (
f'<a href="{escaped}" target="_blank" rel="noopener noreferrer" '
f'data-link-preview="{escaped}">'
f"{html.escape(url)}</a>"
)
return (
f'<a href="{escaped}" target="_blank" rel="noopener noreferrer">'
f"{html.escape(url)}</a>"
)
_CARD_SHELL_RE = re.compile(
r"<p>\s*(<a href=\"([^\"]+)\" target=\"_blank\" rel=\"noopener noreferrer\" "
r"data-link-preview=\"([^\"]+)\">.*?</a>)\s*</p>"
)
def _expand_link_cards(rendered: str) -> str:
from devplacepy.link_previews import backend_preview, render_card_html
def _replace(match: re.Match) -> str:
if match.group(2) != match.group(3):
return match.group(0)
preview = backend_preview(html.unescape(match.group(3)))
if not preview:
return match.group(0)
return "<p>" + render_card_html(preview) + "</p>"
return _CARD_SHELL_RE.sub(_replace, rendered)
def _mask_email(match: re.Match) -> str:
email = match.group(0)
local, _, domain = email.partition("@")
@@ -251,14 +277,21 @@ def _mask_emails(text: str) -> str:
def _transform_text(text: str, budget: _EmbedBudget) -> str:
matches = list(_TOKEN_RE.finditer(text))
standalone = (
len(matches) == 1
and matches[0].group("url")
and not text[:matches[0].start()].strip()
and not text[matches[0].end():].strip()
)
out: list[str] = []
pos = 0
for match in _TOKEN_RE.finditer(text):
for match in matches:
if match.start() > pos:
out.append(html.escape(_mask_emails(text[pos:match.start()])))
if match.group("url"):
url, trailing = _split_trailing_punct(match.group("url"))
out.append(_embed_url(url, budget))
out.append(_embed_url(url, budget, standalone=bool(standalone and not trailing)))
if trailing:
out.append(html.escape(trailing))
else:
@@ -352,6 +385,86 @@ def _keep_inline(rendered: str) -> str:
return inline.result()
class _PlainTextRenderer(mistune.HTMLRenderer):
def text(self, text: str) -> str:
return text
def emphasis(self, text: str) -> str:
return text
def strong(self, text: str) -> str:
return text
def strikethrough(self, text: str) -> str:
return text
def codespan(self, text: str) -> str:
return text
def linebreak(self) -> str:
return "\n"
def softbreak(self) -> str:
return " "
def link(self, text: str, url: str, title=None) -> str:
return text
def image(self, text: str, url: str, title=None) -> str:
return text
def inline_html(self, html: str) -> str:
return ""
def paragraph(self, text: str) -> str:
return text + "\n"
def heading(self, text: str, level: int, **attrs) -> str:
return text + "\n"
def blank_line(self) -> str:
return ""
def thematic_break(self) -> str:
return "\n"
def block_text(self, text: str) -> str:
return text
def block_code(self, code: str, info=None) -> str:
return code + "\n"
def block_quote(self, text: str) -> str:
return text
def block_html(self, html: str) -> str:
return ""
def block_error(self, text: str) -> str:
return text
def list(self, text: str, ordered: bool, **attrs) -> str:
return text
def list_item(self, text: str) -> str:
return text + "\n"
_plain_markdown = mistune.create_markdown(
renderer=_PlainTextRenderer(escape=False),
plugins=["strikethrough"],
)
_WIDGET_PLACEHOLDER_RE = re.compile(r"\x00WIDGET_\d+\x00")
def plain_text(text) -> str:
source, _widgets = _extract_widgets(str(text or ""))
source = _WIDGET_PLACEHOLDER_RE.sub("", source)
collapsed = re.sub(r"\s+", " ", _plain_markdown(source))
return html.unescape(collapsed).strip()
@lru_cache(maxsize=4096)
def _render_content(text: str) -> str:
text = _normalize_dashes(text)
@@ -388,8 +501,8 @@ def render_content(text, author_is_admin: bool = False) -> Markup:
modified, widgets = _extract_widgets(text_str)
rendered = _render_content(modified)
result = _reinsert_widgets(rendered, widgets)
return Markup(result)
return Markup(_render_content(text_str))
return Markup(_expand_link_cards(result))
return Markup(_expand_link_cards(_render_content(text_str)))
def render_title(text, author_is_admin: bool = False) -> Markup:
+11 -2
View File
@@ -19,7 +19,14 @@ def wants_json(request: Request) -> bool:
return "application/json" in accept and "text/html" not in accept
def respond(request: Request, template: str, context: dict, *, model: type[BaseModel]):
def respond(
request: Request,
template: str,
context: dict,
*,
model: type[BaseModel],
status_code: int = 200,
):
if wants_json(request):
try:
payload = model.model_validate(context).model_dump(mode="json")
@@ -29,7 +36,9 @@ def respond(request: Request, template: str, context: dict, *, model: type[BaseM
return JSONResponse(payload)
from devplacepy.templating import templates
return templates.TemplateResponse(request, template, context)
return templates.TemplateResponse(
request, template, context, status_code=status_code
)
def action_result(
+24 -2
View File
@@ -179,6 +179,10 @@ All dates displayed to users use European DD/MM/YYYY format. Implemented via:
- **`time_ago()`** returns `DD/MM/YYYY` for items older than 30 days (instead of `"Xmo ago"`)
- Services page has a JS `formatDate()` function for live polling updates
### Admin page specification
Every admin route and template conforms to `devplacepy/routers/admin/CLAUDE.md` (A1-A11). Read it before adding or changing anything under `/admin`; it is enforced by `tests/unit/admin_spec.py`.
### Admin pagination
Both `/admin/users` and `/admin/news` use offset-based pagination via a reusable component:
@@ -294,10 +298,10 @@ All SEO features are implemented across the following locations:
### Post page layout (three columns, mirrors `/feed`)
`post.html` reuses `/feed`'s exact layout building blocks rather than inventing new ones, wrapped in `.post-page-layout` (`static/css/post.css`, `grid-template-columns: var(--sidebar-width) minmax(0, 1fr) 280px`, collapsing to one column at 1024px):
`post.html` reuses `/feed`'s exact layout building blocks rather than inventing new ones, wrapped in `.post-page-layout` (`static/css/post.css`). The grid is `var(--sidebar-width) minmax(0, 1fr) 280px` only when both asides are present. Each column is placed explicitly (sidebar column 1, `.post-page` column 2, `.feed-right` column 3), and a missing aside drops its track instead of shifting the article into the 240px sidebar column. It collapses to one column at 1024px:
- **Left column** - `<aside class="post-page-sidebar">`, sticky, holding up to three separate `.sidebar-card` blocks (never merged into one card - each is its own bordered panel): "Gists from {author}" and "Projects from {author}" (`content.get_user_sidebar_gists`/`get_user_sidebar_projects`, up to 5 each, most-recently-modified first, private projects filtered via `can_view_project`), and "Related Discussions" (same-topic posts). Every card title is a `.sidebar-heading` div (the same class `feed.html`'s left sidebar uses for "Topics"/"Resources"/"Online now" - `.sidebar-card .sidebar-heading` in `sidebar.css`, so it only styles correctly nested inside a `.sidebar-card`, never bare). Each list item reuses the plain `.related-list`/`.related-link`/`.related-title`/`.related-meta` classes (`base.css`) with `content_preview()` for the ellipsis-truncated description.
- **Middle column** - `.post-page` (`max-width: 720px`): the post article, comments.
- **Middle column** - `.post-page` (`width: 100%`, `max-width: 720px`, centered in its column): the post article, comments. Below 1024px it fills the single column instead of shrink-wrapping to the post text.
- **Right column** - `<aside class="feed-right">`, the exact same class `feed.html` uses for its Daily Topic widget (sticky, hidden below 1024px via `feed.css`'s own media query - no post-page-specific override needed). Holds the "Featured" cards (`database.get_featured_topics`, up to 3, cached pool + per-request random sample): each is a `.daily-topic-card` with its own `.daily-topic-label` ("Featured") - matching the single Daily Topic card's internal label, since there is no section-level heading here (a `.sidebar-heading` div placed directly in `.feed-right` would NOT be styled, as noted above - the fix used is a per-card label instead of a bare heading).
All three columns are populated by `routers/posts.py` `post_page_context()`, the single context builder shared by the real `/posts/{slug}` route and `happy404.render()` (see the root `CLAUDE.md`), so a decoy happy-404 post page renders with the identical sidebar/featured layout as a real one.
@@ -382,3 +386,21 @@ The profile **Activity** tab (`/profile/{username}?tab=activity`, public) interl
## Content visibility routes
Posts, gists, projects and news share one four-value status (published, hidden, draft, offline); the specification, truth table and choke points are in `devplacepy/database/CLAUDE.md` ("Content visibility"). It is an ordinary field of the create and edit forms of posts, gists and projects (`visibility`, via the `_visibility_field.html` partial), handled by `create_content_item` and `edit_content_item` like every other field; there are no dedicated toggle routes. The only dedicated route is the administrator's `POST /admin/news/{uid}/visibility` (`VisibilityForm{value}`), because news has no edit form. Hidden items are `noindex,nofollow`. Comments, votes, reactions, bookmarks and notes refuse (404) a target the viewer cannot open (`content.can_view_target`), and the saved/notes lists skip such targets. The devRant API resolves rants through `post_by_id(rant_id, viewer)` and lists listed rants only. Audit key: `<kind>.visibility.set`. Devii: the `visibility` parameter on the create and edit tools, plus `admin_set_news_visibility`.
## Notifications grouping and profile settings (requested_changes items 1, 4, 5)
- `POST /profile/{username}/enter-to-submit`, `POST /profile/{username}/notifications/grouping` and `POST /profile/{username}/notifications/throttling` are owner-or-admin toggles through `routers/profile/_shared.resolve_customization_target`, audited as `profile.enter_to_submit.toggle`, `profile.notification.grouping.toggle` and `profile.notification.throttle.toggle`.
- `GET /notifications` groups events with `notification_group_key` when the recipient has grouping on (250 row fetch cap, 25 groups per page, date groups outside event groups). Opening or dismissing a grouped card marks every member read. With grouping off the page and badge keep the old one-row behaviour.
## Feature checklist (one data source, four faces)
Every feature is one data source fanning out into HTML, JSON (`respond(..., model=XOut)`; a context key not on `XOut` is silently dropped from JSON), a Devii agent action, and a documented endpoint. A change touching one file must confirm none of the four faces were missed. Checklist, ordered by data flow:
1. **Understand.** Read the router, template, matching tests, and the nested `CLAUDE.md`. Trace input model, router, data helper, response (HTML and JSON).
2. **Data layer.** `database/` for query/batch helpers (never inline N+1; guard raw SQL with `if "table" in db.tables`). `models/` for the Pydantic `Form` (add to the domain module, re-export list, and `__all__`). `schemas/` for the `*Out` JSON model; every context key a JSON route exposes must exist on it. Indexes via `CREATE INDEX IF NOT EXISTS` in `init_db()`.
3. **Server layer.** Guard matches the read (public), write (member), or admin surface. Specific paths before catch-alls. HTML+JSON via `respond(...)` or pure JSON via `JSONResponse`. Register any new router in `main.py`.
4. **View layer.** Extend `base.html`; page CSS/JS via `extra_head`/`extra_js`. Reuse partials and template globals. ES6 modules, one class per file, instantiated on `app`.
5. **Safety layer (skip only when the feature stores and shows nothing).** New user-generated surface: register in `REPORTABLE_TARGETS` (or `UNREPORTABLE_TABLES` with reason), resolve in `resolve_object_url`, include `_report_button.html`. New personal-data category or third-party transmission: update `/docs/privacy.html` and the app-store declarations in the same change.
6. **Agent + docs layer.** Devii `Action` where a user could ask for this (`requires_auth` mirrors the guard). `docs_api.py` `endpoint()` with params and `sample_response`. `DOCS_PAGES` prose. `seo.py` context and sitemap entry for new public pages.
7. **Document.** `README.md` for product-facing surface; the nested `CLAUDE.md` for any new mechanic or cross-layer wiring; root `CLAUDE.md` only for a new architectural rule or workflow step.
8. **Validate.** Import gate, per-language manual checks, no em dashes, `pyflakes`/`ruff check` on every touched file, the four-layer rigor procedure for spendable/state-machine/race shapes, then full `make test` green before done. Failures at any step block the workflow.
+82
View File
@@ -0,0 +1,82 @@
# CLAUDE.md
The specification every `/admin` page follows. Claude Code loads it whenever a file under `routers/admin/` is touched; the root, `routers/`, `templates/`, `static/js/` and `static/css/` `CLAUDE.md` files point here. A page that breaks a rule below is a defect, not a style choice. `tests/unit/admin_spec.py` enforces the mechanical rules (A1, A2, A5, A6, A7, A9, A10) against the real templates and routers, so a violation fails the suite.
Code references: the section registry is `devplacepy/admin_sections.py`; the caps and floors are `ADMIN_LIST_CAP` and `ADMIN_POLL_FLOOR_SECONDS` in `routers/admin/_shared.py`; the cap note is `templates/_admin_cap_note.html`.
## A1. Backend rendered, always
A GET of an admin page returns the complete content in the HTML: every table, card, key figure, tab label and empty state is rendered by Jinja from data the handler computed. A placeholder such as "Loading..." in a template is forbidden. The page must be readable and correct with JavaScript off.
JavaScript only enhances: live refresh, charts drawn on a `<canvas>`, sorting, modals. The numbers and tables around a chart are server rendered; the chart is drawn from JSON embedded in the page.
The only permitted live-first surface is a page whose whole purpose is a live channel (WebSocket) such as the Bot Monitor and the container terminal, and even those render their initial frame on the server.
## A2. One handler, one builder, one model
- The HTML route calls `respond(request, "<template>.html", ctx, model=XOut)` with `base_seo_context(..., robots="noindex,nofollow")` and a breadcrumb trail `Home > Admin > <Page>`. Never `templates.TemplateResponse` directly: that drops the JSON face and the `*Out` schema.
- The data the page shows is produced by ONE builder function. The HTML route and the refresh endpoint (`GET /admin/<page>/data`, `require_admin`, `JSONResponse`) both call it. The two must never compute the same figures twice with different code.
- Context keys never collide with a Jinja global (root rule: `viewer_is_admin`, not `is_admin`).
- Every admin page sets `"admin_section": "<key>"` where the key exists in `ADMIN_SECTIONS`.
## A3. Page anatomy
Every page extends `admin_base.html` and, in this order, renders:
1. `<div class="admin-toolbar">` holding the page title as `<h2>` (never `<h1>`; the layout owns the document heading), then `admin-count` spans, filters and the primary action.
2. Optional `<nav class="admin-tabs" data-overflow-tabs>` for page tabs. A tab is a real link (`?tab=`), rendered on the server.
3. The content: `admin-table-wrap > table.admin-table`, or cards, or a form `admin-settings-form`.
4. The empty state: `<p class="admin-empty">`, never `empty-state`, never an empty table.
5. Pagination via `_pagination.html` when the list is paged (A6).
Tables carry `<caption class="sr-only">`, every `<th>` has `scope="col"`, every icon-only or repeated row button has an `aria-label`. Page CSS goes in `{% block extra_head %}` after `{{ super() }}` (never re-link `admin.css` or `sidebar.css`; `admin_base.html` already loads them). No inline `<style>`, no `style=` attributes, no inline event handlers.
## A4. Class vocabulary
Buttons are `admin-btn` with `admin-btn-primary`, `admin-btn-danger`, `admin-btn-sm`. Fields are `admin-field`, selects `admin-select`, forms `admin-settings-form` or `admin-inline-form`, hints `admin-hint`. Status chips reuse the page family badge (`service-status`, `cm-badge`, `workspace-badge`). The public-site classes `btn`, `btn-primary`, `btn-danger`, `hint-text`, `empty-state`, `admin-header` are forbidden in admin templates. A missing admin class is added to `admin.css`, never worked around with a public class. Destructive buttons carry `data-confirm` (and `data-confirm-danger` for role/quota style changes).
## A5. Time
Every instant shown to a viewer is `local_dt(iso, mode)` or `dt_ago(iso)`; never `format_date`/`time_ago` for an instant (those stay for JSON and non-timestamp date fields). When client JS re-renders a row it emits the same `<time data-dt="...">` markup, and `LocalTime` localizes it through its MutationObserver; JS never formats an instant itself with `toLocaleString`/`toLocaleTimeString`.
## A6. Everything is capped
No list is unbounded.
- A list that can grow with users or content is paginated: `build_pagination(page, total)` plus `_limit/_offset` in the query and `_pagination.html`. Sorting is in SQL (`order_by`), never `rows.sort()` over the whole table.
- A list that is naturally small (services, gateway providers) still reads with `_limit=ADMIN_LIST_CAP` and renders `_admin_cap_note.html` (`_shown`, `_total`) so truncation is visible, never silent.
- Per-row work (queries, `await`s, service calls) is done for the visible page only, in batch (`get_users_by_uids` and friends), never per row of the whole table.
- Query parameters that size a computation (`hours`, `top_n`, `limit`) are clamped on the server to a declared constant.
## A7. Heavy and remote work
A GET handler must not wait on a remote service. Gitea, providers and any network call go through a cache with a fixed TTL and a hard item cap; the handler renders the cached value at once and keeps the page's explicit error state (`*_error`) when the source is down. A computation costing more than one page of plain queries (statistics, usage analytics) is computed once per request: the HTML route embeds its result, and a tab or window change either navigates (server render) or fetches `/data`, never both.
## A8. Live refresh
- The shared `Poller` only: `new Poller(fn, ms, { pauseHidden: true, immediate: false })`. `immediate: false` because the first paint is already on the page (A1). Raw `setInterval` is forbidden.
- Interval floor is `ADMIN_POLL_FLOOR_SECONDS` (15 s); a page that needs faster is a live channel.
- Fetch through `Http.getJson`; never a bare `fetch`.
- The refresh response is the `/data` JSON of A2, or, for a page made of server-rendered sections, HTML fetched with `Http.getHtml` (the page itself, or a `/fragment` route returning the same partial) and swapped into the `[data-live]` regions (Backups, Community pages, AI usage, Gateway stats). The markup then lives only in Jinja and the one builder feeds the page, the fragment and `/data`. The client re-renders only the regions that changed and preserves open modals, focus, scroll position and input values.
- Initial data for charts is embedded as `<script type="application/json" id="<root>-initial">{{ initial | tojson }}</script>` and read synchronously; the client does not issue a second request to learn what the server already knew.
## A9. Assets
- One copy of each vendored library. Chart.js is `/static/vendor/chartjs/chart.umd.min.js`, loaded with `defer` through `static_url(...)` from `{% block extra_js %}` only on pages that draw charts.
- Page JS is one ES6 module per class in `static/js/`, started from a three-line module block in `extra_js`. No page logic inline.
## A10. Navigation is one registry
The admin sections are declared once in `devplacepy/admin_sections.py` (`ADMIN_SECTIONS`, exposed as the `admin_sections` Jinja global). `admin_base.html` (desktop sidebar) and the admin block of `base.html` (the phone menu, because the sidebar is hidden at 1024 px and below) both loop over it. A new admin page adds one registry entry and nothing else; hand-writing a nav link in either template is forbidden. Every `admin_section` value passed by a route must exist in the registry.
## A11. Responsive
Everything works at 360 px. Tables sit in `admin-table-wrap` (horizontal scroll inside the wrap, never the page). A toolbar with more than three controls wraps; a button group of more than three becomes a `<select>` or a `dp-action-menu`. Touch targets are at least 44 px (`admin.css` already enforces it for `admin-btn`/`admin-select`).
## Checklist for a new or changed admin page
1. Registry entry in `ADMIN_SECTIONS`, `admin_section` matches.
2. Builder function, `respond(... model=XOut)`, `/data` endpoint if it refreshes, audit event for every mutation.
3. Template follows A3, A4, A5; no placeholder text; caps and pagination per A6.
4. JS (only if needed) per A8 and A9.
5. `tests/api/admin/...` asserts the first response already contains the data (not "Loading"), and `tests/unit/admin_spec.py` still passes.
+4
View File
@@ -8,6 +8,10 @@ from devplacepy.responses import action_result
from devplacepy.services.audit import record as audit
ADMIN_LIST_CAP = 200
ADMIN_POLL_FLOOR_SECONDS = 15
def seniority_key(user: dict) -> tuple[str, int]:
return (user.get("created_at") or "", user.get("id") or 0)
+50 -6
View File
@@ -8,16 +8,46 @@ from devplacepy.seo import base_seo_context, site_url, website_schema
from devplacepy.responses import respond
from devplacepy.schemas import GatewayUsageOut
from devplacepy.services.manager import service_manager
from devplacepy.services.openai_gateway.analytics import build_analytics
from devplacepy.services.openai_gateway.analytics import MAX_WINDOW_HOURS, build_analytics
from devplacepy.services.openai_gateway.usage import pricing_from_cfg
from devplacepy.templating import templates
logger = logging.getLogger(__name__)
router = APIRouter()
DEFAULT_WINDOW_HOURS = 48
MAX_TOP_N = 50
WINDOW_CHOICES = (
(1, "1 hour"),
(24, "24 hours"),
(48, "48 hours"),
(168, "7 days"),
(0, "All time"),
)
def _clamp_hours(hours: int) -> int:
if hours <= 0:
return 0
return min(hours, MAX_WINDOW_HOURS)
def _clamp_top_n(top_n: int) -> int:
return max(1, min(top_n, MAX_TOP_N))
def build_usage(hours: int, top_n: int) -> dict:
service = service_manager.get_service("openai")
pricing = pricing_from_cfg(service.get_config()) if service is not None else None
return build_analytics(_clamp_hours(hours), top_n=_clamp_top_n(top_n), pricing=pricing)
@router.get("/ai-usage", response_class=HTMLResponse)
async def admin_ai_usage(request: Request):
async def admin_ai_usage(
request: Request, hours: int = DEFAULT_WINDOW_HOURS, top_n: int = 10
):
admin = require_admin(request)
usage = build_usage(hours, top_n)
base = site_url(request)
seo_ctx = base_seo_context(
request,
@@ -39,14 +69,28 @@ async def admin_ai_usage(request: Request):
"request": request,
"user": admin,
"admin_section": "ai-usage",
"usage": usage,
"window_choices": WINDOW_CHOICES,
"window_hours": usage["window_hours"],
**usage,
},
model=GatewayUsageOut,
)
@router.get("/ai-usage/data")
async def admin_ai_usage_json(request: Request, hours: int = 48, top_n: int = 10):
async def admin_ai_usage_json(
request: Request, hours: int = DEFAULT_WINDOW_HOURS, top_n: int = 10
):
require_admin(request)
service = service_manager.get_service("openai")
pricing = pricing_from_cfg(service.get_config()) if service is not None else None
return JSONResponse(build_analytics(hours, top_n=top_n, pricing=pricing))
return JSONResponse(build_usage(hours, top_n))
@router.get("/ai-usage/fragment", response_class=HTMLResponse)
async def admin_ai_usage_fragment(
request: Request, hours: int = DEFAULT_WINDOW_HOURS, top_n: int = 10
):
require_admin(request)
usage = build_usage(hours, top_n)
html = templates.get_template("_ai_usage_report.html").render(usage=usage)
return HTMLResponse(html)
+7 -1
View File
@@ -20,6 +20,8 @@ from devplacepy.services.jobs import queue
from devplacepy.utils import is_primary_admin, not_found, require_admin
from fastapi import Depends, HTTPException
from devplacepy.dependencies import json_or_form
from devplacepy.database import db, get_table
from devplacepy.routers.admin._shared import ADMIN_LIST_CAP
logger = logging.getLogger(__name__)
router = APIRouter()
@@ -63,12 +65,16 @@ def _targets() -> list[dict]:
]
async def _dashboard(can_download: bool) -> dict:
backups = [_backup_payload(row, can_download) for row in store.list_backups()]
backups = [
_backup_payload(row, can_download)
for row in store.list_backups(limit=ADMIN_LIST_CAP)
]
schedules = store.list_schedules()
storage = await asyncio.to_thread(store.compute_storage_stats)
return {
"storage": storage,
"backups": backups,
"backups_total": get_table("backups").count() if "backups" in db.tables else 0,
"schedules": schedules,
"targets": _targets(),
"metrics": _metrics(backups),
+6 -3
View File
@@ -10,7 +10,7 @@ from urllib.parse import urlencode
from fastapi import APIRouter, Form, Request
from fastapi.responses import HTMLResponse
from devplacepy.database import get_setting, get_table, get_users_by_uids, resolve_object_url
from devplacepy.database import build_pagination, get_setting, get_table, get_users_by_uids, resolve_object_url
from devplacepy.database.sync import count_links, identity_map
from devplacepy.responses import action_result, json_error, respond
from devplacepy.schemas import AdminCommunitiesOut, AdminCommunityLedgerOut, AdminCommunityOut, AdminCommunitySchemaOut
@@ -174,8 +174,10 @@ def feed_summary(feed: dict) -> dict:
@router.get("/communities", response_class=HTMLResponse)
async def admin_communities(request: Request):
async def admin_communities(request: Request, page: int = 1):
admin = require_admin(request)
pagination = build_pagination(page, store.count())
offset = (pagination["page"] - 1) * pagination["per_page"]
return respond(
request,
"admin_communities.html",
@@ -183,7 +185,8 @@ async def admin_communities(request: Request):
**seo(request, "Communities", LIST_URL, "Communities"),
"request": request,
"user": admin,
"items": [public(row) for row in store.list()],
"items": [public(row) for row in store.list(pagination["per_page"], offset)],
"pagination": pagination,
"sync_enabled": sync_enabled(),
**service_flags(),
"admin_section": "communities",
+16 -5
View File
@@ -6,6 +6,7 @@ from fastapi import Depends, APIRouter, Request
from fastapi.responses import HTMLResponse, JSONResponse, RedirectResponse
from devplacepy.database import (
build_pagination,
db,
get_table,
get_users_by_uids,
@@ -111,10 +112,20 @@ def _audit_admin(request: Request, admin: dict, event_key: str, inst: dict, summ
result=result,
)
def _containers_payload(admin: dict, page: int) -> dict:
visible = _decorate(store.all_instances(), admin)
pagination = build_pagination(page, len(visible))
start = (pagination["page"] - 1) * pagination["per_page"]
return {
"instances": visible[start : start + pagination["per_page"]],
"pagination": pagination,
}
@router.get("", response_class=HTMLResponse)
async def containers_index(request: Request):
async def containers_index(request: Request, page: int = 1):
admin = require_admin(request)
instances = _decorate(store.all_instances(), admin)
payload = _containers_payload(admin, page)
base = site_url(request)
seo_ctx = base_seo_context(
request,
@@ -136,7 +147,7 @@ async def containers_index(request: Request):
**seo_ctx,
"request": request,
"user": admin,
"instances": instances,
**payload,
"boot_languages": BOOT_LANGUAGES,
"restart_policies": RESTART_POLICIES,
"admin_section": "containers",
@@ -145,9 +156,9 @@ async def containers_index(request: Request):
)
@router.get("/data")
async def containers_index_json(request: Request):
async def containers_index_json(request: Request, page: int = 1):
admin = require_admin(request)
return JSONResponse({"instances": _decorate(store.all_instances(), admin)})
return JSONResponse(_containers_payload(admin, page))
@router.get("/projects/search")
async def project_search(request: Request, q: str = ""):
+24 -8
View File
@@ -5,7 +5,13 @@ import logging
from fastapi import APIRouter, Request
from fastapi.responses import HTMLResponse
from devplacepy.database import db, get_admin_uids, get_int_setting, get_users_by_uids
from devplacepy.database import (
build_pagination,
db,
get_admin_uids,
get_int_setting,
get_users_by_uids,
)
from devplacepy.responses import action_result, respond
from devplacepy.schemas import AdminDeviiTasksOut
from devplacepy.seo import base_seo_context, site_url, website_schema
@@ -32,17 +38,26 @@ def _schedule_text(row: dict) -> str:
return f"once {row.get('run_at') or ''}".strip()
def _rows(state: str) -> list[dict]:
def _page(state: str, page: int) -> tuple[list[dict], dict]:
if TABLE not in db.tables:
return []
return [], build_pagination(page, 0)
criteria: dict = {"deleted_at": None}
if state == "active":
criteria["enabled"] = True
elif state == "inactive":
criteria["enabled"] = False
rows = list(db[TABLE].find(**criteria))
rows.sort(key=lambda row: int(row.get("run_count") or 0), reverse=True)
return rows
table = db[TABLE]
pagination = build_pagination(page, table.count(**criteria))
offset = (pagination["page"] - 1) * pagination["per_page"]
rows = list(
table.find(
order_by=["-run_count", "-created_at"],
_limit=pagination["per_page"],
_offset=offset,
**criteria,
)
)
return rows, pagination
def _quotas(owner_uids: set[str]) -> dict[str, dict]:
@@ -98,11 +113,11 @@ def _require_task(uid: str) -> dict:
@router.get("/devii-tasks", response_class=HTMLResponse)
async def admin_devii_tasks(request: Request, state: str = "active"):
async def admin_devii_tasks(request: Request, state: str = "active", page: int = 1):
admin = require_admin(request)
if state not in STATES:
state = "active"
rows = _rows(state)
rows, pagination = _page(state, page)
items = _items(rows)
bounds = {
"max_concurrent": get_int_setting(
@@ -149,6 +164,7 @@ async def admin_devii_tasks(request: Request, state: str = "active"):
"request": request,
"user": admin,
"items": items,
"pagination": pagination,
"state": state,
"tabs": tabs,
"limits": bounds,
+154 -8
View File
@@ -1,10 +1,11 @@
# retoor <retoor@molodetz.nl>
import logging
from datetime import datetime, timezone
from typing import Optional
from urllib.parse import quote
from fastapi import APIRouter, Request
from fastapi import APIRouter, Query, Request
from fastapi.responses import HTMLResponse, JSONResponse, RedirectResponse
from pydantic import ValidationError
@@ -16,6 +17,7 @@ from devplacepy.schemas import (
AdminGatewayQuotaFormOut,
)
from devplacepy.seo import base_seo_context, site_url, website_schema
from devplacepy.routers.admin._shared import ADMIN_LIST_CAP
from devplacepy.services.audit import record as audit
from devplacepy.services.manager import service_manager
from devplacepy.services.openai_gateway import (
@@ -24,6 +26,12 @@ from devplacepy.services.openai_gateway import (
quota,
routing,
)
from devplacepy.services.openai_gateway.learned import (
DEFAULT_PROVIDER,
LearnedResetIn,
learned_store,
)
from devplacepy.services.openai_gateway.shape import shape_stats
from devplacepy.templating import templates
from devplacepy.utils import not_found, require_admin
@@ -31,7 +39,8 @@ logger = logging.getLogger(__name__)
router = APIRouter()
INDEX_URL = "/admin/gateway"
TABS = ("models", "providers", "quota", "stats")
TABS = ("models", "providers", "quota", "stats", "media")
DEFAULT_STATS_RANGE = "24h"
def _default_provider_summary() -> dict:
@@ -46,6 +55,31 @@ def _default_provider_summary() -> dict:
"image_model": cfg.get("gateway_image_model", ""),
"vision_url": cfg.get("gateway_vision_url", ""),
"vision_model": cfg.get("gateway_vision_model", ""),
"media_url": cfg.get("gateway_media_url", ""),
"media_model": cfg.get("gateway_media_model", ""),
}
def _media_summary() -> dict:
from devplacepy.services.openai_gateway.pruna import PRUNA_MODELS
svc = service_manager.get_service("openai")
cfg = svc.get_config() if svc is not None else {}
return {
"enabled": bool(cfg.get("gateway_media_enabled", True)),
"url": cfg.get("gateway_media_url", ""),
"model": cfg.get("gateway_media_model", ""),
"price_per_call": cfg.get("gateway_media_price_per_call", 0),
"max_usd_per_call": cfg.get("gateway_media_max_usd_per_call", 0),
"catalog": [
{
"name": spec.name,
"kind": spec.kind,
"unit": spec.unit,
"price_per_unit_usd": spec.price_per_unit_usd,
}
for spec in PRUNA_MODELS
],
}
@@ -143,31 +177,69 @@ def _error_response(
):
if wants_json(request):
return json_error(status_code, message)
return templates.TemplateResponse(
return respond(
request,
template,
{**context, "request": request, "error": message},
model=AdminGatewayOut,
status_code=status_code,
)
def _models_with_learned(limit: int = ADMIN_LIST_CAP) -> list[dict]:
models = routing.model_store.list()[:limit]
for model in models:
method = learned_store.get(
model["provider"] or DEFAULT_PROVIDER, model["target_model"]
)
model["learned_shape"] = method.label if method is not None else ""
model["learned_provider"] = model["provider"] or DEFAULT_PROVIDER
return models
def _reset_learned(request: Request, admin: dict, payload: LearnedResetIn) -> bool:
provider = payload.provider or DEFAULT_PROVIDER
existed = learned_store.forget(provider, payload.target_model)
if existed:
audit.record(
request,
"gateway.learned.reset",
user=admin,
target_type="gateway_learned_method",
target_uid=f"{provider}/{payload.target_model}",
target_label=f"{provider}/{payload.target_model}",
summary=(
f"admin {admin['username']} reset the learned request shape "
f"for {provider}/{payload.target_model}"
),
)
return existed
# --- Index page (tabs: models / providers / quota) --------------------------
@router.get("/gateway", response_class=HTMLResponse)
async def gateway_config_page(
request: Request, tab: str = "models", tested: str = "", test_image: str = ""
request: Request,
tab: str = "models",
tested: str = "",
test_image: str = "",
stats_range: str = Query(DEFAULT_STATS_RANGE, alias="range"),
):
admin = require_admin(request)
if tab not in TABS:
tab = "models"
if not test_image.startswith("http"):
test_image = ""
quota_rules = quota.quota_rule_store.list()
all_quota_rules = quota.quota_rule_store.list()
quota_rules = all_quota_rules[:ADMIN_LIST_CAP]
for rule in quota_rules:
rule["spent_24h_usd"] = round(
quota.spent_24h(rule["owner_kind"], rule["owner_id"], rule["app_reference"]), 6
)
all_providers = routing.provider_store.list()
stats_context = _stats_context(stats_range) if tab == "stats" else {}
return respond(
request,
"admin_gateway.html",
@@ -176,9 +248,14 @@ async def gateway_config_page(
"user": admin,
"admin_section": "gateway",
"tab": tab,
"providers": routing.provider_store.list(),
"models": routing.model_store.list(),
"providers": all_providers[:ADMIN_LIST_CAP],
"providers_total": len(all_providers),
"models": _models_with_learned(),
"models_total": routing.model_store.count(),
"quota_rules": quota_rules,
"quota_rules_total": len(all_quota_rules),
**stats_context,
"media": _media_summary(),
"default_provider": _default_provider_summary(),
"quota_defaults": _quota_defaults_summary(),
"stats_ranges": list(model_stats_query.RANGE_SECONDS.keys()),
@@ -388,6 +465,44 @@ async def list_models(request: Request):
)
@router.get("/gateway/learned")
async def list_learned(request: Request):
require_admin(request)
rows = learned_store.list()
return JSONResponse(
{"learned": rows, "count": len(rows), "stats": shape_stats.snapshot()}
)
@router.post("/gateway/learned/reset")
async def reset_learned_json(request: Request):
admin = require_admin(request)
body = await _payload(request)
try:
payload = LearnedResetIn(**body)
except ValidationError as exc:
return _validation_error(exc)
if not _reset_learned(request, admin, payload):
return JSONResponse(
{"ok": False, "error": "No learned method for that route"},
status_code=404,
)
return JSONResponse({"ok": True})
@router.post("/gateway/learned/reset-page")
async def reset_learned_page(request: Request):
admin = require_admin(request)
body = await _payload(request)
try:
payload = LearnedResetIn(**body)
except ValidationError as exc:
return _validation_error(exc)
if not _reset_learned(request, admin, payload):
raise not_found("No learned method for that route")
return RedirectResponse(url=f"{INDEX_URL}?tab=models", status_code=302)
@router.get("/gateway/provider-models")
async def provider_models(request: Request, provider: str = ""):
require_admin(request)
@@ -1037,8 +1152,28 @@ async def reset_quota_rule_page(request: Request, uid: str):
# --- Stats: JSON API for the Stats tab's charts ------------------------------
def _stats_context(range_key: str) -> dict:
if range_key not in model_stats_query.RANGE_SECONDS:
range_key = DEFAULT_STATS_RANGE
summary = model_stats_query.compute_summary(range_key)
return _stats_view(summary, range_key)
def _stats_view(summary: dict, range_key: str) -> dict:
per_model = summary["per_model"]
generated = datetime.fromtimestamp(summary["generated_at"], tz=timezone.utc)
return {
"stats": summary,
"stats_range": range_key,
"stats_generated_iso": generated.isoformat(),
"stats_models": model_stats_query.list_known_models()[:ADMIN_LIST_CAP],
"stats_table_models": per_model[:ADMIN_LIST_CAP],
"stats_table_models_total": len(per_model),
}
@router.get("/gateway/stats/data")
async def gateway_stats_data(request: Request, range: str = "24h"):
async def gateway_stats_data(request: Request, range: str = DEFAULT_STATS_RANGE):
require_admin(request)
try:
return JSONResponse(model_stats_query.compute_summary(range))
@@ -1046,6 +1181,17 @@ async def gateway_stats_data(request: Request, range: str = "24h"):
return json_error(400, f"Unknown range: {range!r}")
@router.get("/gateway/stats/fragment", response_class=HTMLResponse)
async def gateway_stats_fragment(request: Request, range: str = DEFAULT_STATS_RANGE):
require_admin(request)
if range not in model_stats_query.RANGE_SECONDS:
return json_error(400, f"Unknown range: {range!r}")
context = _stats_context(range)
return HTMLResponse(
templates.get_template("_gateway_stats_fragment.html").render(**context)
)
@router.get("/gateway/stats/models")
async def gateway_stats_models(request: Request):
require_admin(request)
+15 -2
View File
@@ -1,10 +1,12 @@
# retoor <retoor@molodetz.nl>
import asyncio
import logging
from fastapi import APIRouter, Request
from fastapi.responses import HTMLResponse
from devplacepy.cache import TTLCache
from devplacepy.responses import respond
from devplacepy.schemas import AdminIssuesPlanningOut
from devplacepy.seo import base_seo_context
@@ -16,10 +18,20 @@ from devplacepy.utils import require_admin
logger = logging.getLogger(__name__)
router = APIRouter()
TICKETS_CACHE_SECONDS = 60
TICKETS_CACHE_KEY = "open"
TICKETS_FETCH_TIMEOUT_SECONDS = 8
_tickets_cache = TTLCache(TICKETS_CACHE_SECONDS, max_size=1)
async def _open_tickets() -> tuple[list[dict], bool]:
cached = _tickets_cache.get(TICKETS_CACHE_KEY)
if cached is not None:
return cached, False
try:
issues = await collect_open_issues(runtime.get_client())
issues = await asyncio.wait_for(
collect_open_issues(runtime.get_client()), TICKETS_FETCH_TIMEOUT_SECONDS
)
except Exception as exc:
logger.warning("Could not load open tickets for planning: %s", exc)
return [], True
@@ -35,6 +47,7 @@ async def _open_tickets() -> tuple[list[dict], bool]:
}
for issue in issues
]
_tickets_cache.set(TICKETS_CACHE_KEY, tickets)
return tickets, False
@@ -49,7 +62,7 @@ async def admin_issues_planning(request: Request):
breadcrumbs=[
{"name": "Home", "url": "/feed"},
{"name": "Admin", "url": "/admin"},
{"name": "Issues", "url": "/issues"},
{"name": "Ticket Planning", "url": "/admin/issues/planning"},
],
)
configured = gitea_config().is_configured
+5 -1
View File
@@ -15,6 +15,8 @@ from devplacepy.database.nodes import (
DEVICE_BREAKDOWN_COLUMNS,
LIMITS,
add_event,
count_all_devices,
count_flags,
count_open_requests,
device_breakdown,
cache_stats,
@@ -234,7 +236,7 @@ def overview() -> dict:
lifetime = lifetime_counters()
outcomes = {name: value for name, value in lifetime.items() if name.startswith(OUTCOME_PREFIX)}
devices = recent_devices(ADMIN_LIST_LIMIT)
flags = list_flags()[:ADMIN_LIST_LIMIT]
flags = list_flags(limit=ADMIN_LIST_LIMIT)
device_by_uid = {row["uid"]: row for row in devices}
missing = [row["device_uid"] for row in flags if row.get("device_uid") and row["device_uid"] not in device_by_uid]
for uid in missing:
@@ -251,7 +253,9 @@ def overview() -> dict:
**breakdowns,
"usage_today": usage_day_totals(),
"flags": flag_views(flags, owners, device_by_uid),
"flags_total": count_flags(),
"devices": device_views(devices, owners),
"devices_total": count_all_devices(),
"settings": settings_view(),
"limits": LIMITS.describe(),
"circuits": circuit_views(),
+31 -13
View File
@@ -4,7 +4,9 @@ import logging
from typing import Any
from fastapi import APIRouter, Request
from fastapi.responses import HTMLResponse, JSONResponse
from devplacepy.templating import templates
from devplacepy.responses import respond
from devplacepy.routers.admin._shared import ADMIN_LIST_CAP
from devplacepy.schemas import ServiceDetailOut, ServicesOut
from devplacepy.utils import require_admin, not_found
from devplacepy.services.manager import service_manager
from devplacepy.seo import base_seo_context, site_url, website_schema
@@ -15,10 +17,24 @@ logger = logging.getLogger(__name__)
router = APIRouter()
def _services_payload() -> dict:
services = service_manager.describe_all()
return {
"services": services[:ADMIN_LIST_CAP],
"services_total": len(services),
}
def _service_payload(name: str) -> dict | None:
svc = service_manager.get_service(name)
if svc is None:
return None
return {"service": svc.describe()}
@router.get("", response_class=HTMLResponse)
async def services_page(request: Request):
admin = require_admin(request)
services = service_manager.describe_all()
base = site_url(request)
seo_ctx = base_seo_context(
request,
@@ -32,32 +48,33 @@ async def services_page(request: Request):
],
schemas=[website_schema(base)],
)
return templates.TemplateResponse(
return respond(
request,
"services.html",
{
**seo_ctx,
"request": request,
"user": admin,
"services": services,
**_services_payload(),
"admin_section": "services",
},
model=ServicesOut,
)
@router.get("/data")
async def services_json(request: Request):
require_admin(request)
return JSONResponse({"services": service_manager.describe_all()})
return JSONResponse({"services": _services_payload()["services"]})
@router.get("/{name}", response_class=HTMLResponse)
async def service_detail(request: Request, name: str):
admin = require_admin(request)
svc = service_manager.get_service(name)
if svc is None:
payload = _service_payload(name)
if payload is None:
raise not_found("Service not found")
info = svc.describe()
info = payload["service"]
base = site_url(request)
seo_ctx = base_seo_context(
request,
@@ -73,27 +90,28 @@ async def service_detail(request: Request, name: str):
schemas=[website_schema(base)],
)
tool_groups = tool_prefs.group_overview() if name == "devii" else None
return templates.TemplateResponse(
return respond(
request,
"service_detail.html",
{
**seo_ctx,
"request": request,
"user": admin,
"service": info,
**payload,
"tool_groups": tool_groups,
"admin_section": "services",
},
model=ServiceDetailOut,
)
@router.get("/{name}/data")
async def service_detail_json(request: Request, name: str):
require_admin(request)
svc = service_manager.get_service(name)
if svc is None:
payload = _service_payload(name)
if payload is None:
return JSONResponse({"error": "unknown service"}, status_code=404)
return JSONResponse({"service": svc.describe()})
return JSONResponse(payload)
def _audit_service(request: Request, admin: dict, name: str, event_key: str, summary: str, **kwargs: Any) -> None:
+45 -16
View File
@@ -7,7 +7,7 @@ from devplacepy.responses import respond
from devplacepy.schemas.statistics import StatisticsOut
from devplacepy.seo import base_seo_context, site_url, website_schema
from devplacepy.services.statistics.build import build_statistics_tab
from devplacepy.services.statistics.common import VALID_TABS
from devplacepy.services.statistics.common import MAX_WINDOW_HOURS, VALID_TABS
from devplacepy.utils import require_admin
logger = logging.getLogger(__name__)
@@ -32,10 +32,45 @@ TAB_LABELS = (
)
@router.get("/statistics", response_class=HTMLResponse)
async def admin_statistics(request: Request, tab: str = "overview", hours: int = 168):
admin = require_admin(request)
STATISTICS_DEFAULT_HOURS = 168
STATISTICS_DEFAULT_TOP_N = 10
STATISTICS_MAX_TOP_N = 50
STATISTICS_WINDOWS = (
(24, "Last 24 hours"),
(168, "Last 7 days"),
(720, "Last 30 days"),
(2160, "Last 90 days"),
(0, "All time"),
)
def clamp_hours(hours: int) -> int:
if hours <= 0:
return 0
return min(hours, MAX_WINDOW_HOURS)
def statistics_view(tab: str, hours: int, compare: int, top_n: int) -> dict:
active = tab if tab in VALID_TABS else "overview"
bounded_top = max(1, min(top_n, STATISTICS_MAX_TOP_N))
return build_statistics_tab(
active,
clamp_hours(hours),
compare=bool(compare),
top_n=bounded_top,
)
@router.get("/statistics", response_class=HTMLResponse)
async def admin_statistics(
request: Request,
tab: str = "overview",
hours: int = STATISTICS_DEFAULT_HOURS,
compare: int = 1,
):
admin = require_admin(request)
initial = statistics_view(tab, hours, compare, STATISTICS_DEFAULT_TOP_N)
active = initial["tab"]
base = site_url(request)
seo_ctx = base_seo_context(
request,
@@ -49,7 +84,6 @@ async def admin_statistics(request: Request, tab: str = "overview", hours: int =
],
schemas=[website_schema(base)],
)
initial = build_statistics_tab(active, hours, compare=True, top_n=10)
tabs = [
{"key": key, "label": label, "icon": icon, "active": key == active}
for key, label, icon in TAB_LABELS
@@ -64,7 +98,9 @@ async def admin_statistics(request: Request, tab: str = "overview", hours: int =
"admin_section": "statistics",
"tabs": tabs,
"active_tab": active,
"window_hours": hours,
"window_hours": initial["window_hours"],
"compare": initial["compare"],
"windows": STATISTICS_WINDOWS,
"initial": initial,
},
model=StatisticsOut,
@@ -75,16 +111,9 @@ async def admin_statistics(request: Request, tab: str = "overview", hours: int =
async def admin_statistics_data(
request: Request,
tab: str = "overview",
hours: int = 168,
hours: int = STATISTICS_DEFAULT_HOURS,
compare: int = 1,
top_n: int = 10,
top_n: int = STATISTICS_DEFAULT_TOP_N,
):
require_admin(request)
return JSONResponse(
build_statistics_tab(
tab,
hours,
compare=bool(compare),
top_n=top_n,
)
)
return JSONResponse(statistics_view(tab, hours, compare, top_n))
+37 -11
View File
@@ -6,7 +6,12 @@ from typing import Annotated
from fastapi import APIRouter, Depends, Request
from fastapi.responses import JSONResponse
from devplacepy.database import get_projects_by_uids, get_table, get_users_by_uids
from devplacepy.database import (
build_pagination,
get_projects_by_uids,
get_table,
get_users_by_uids,
)
from devplacepy.dependencies import json_or_form
from devplacepy.models import (
EditorPrefsForm,
@@ -15,7 +20,7 @@ from devplacepy.models import (
WorkspaceSuspendForm,
)
from devplacepy.responses import action_result, json_error, respond
from devplacepy.routers.admin._shared import deny_senior, is_senior_admin
from devplacepy.routers.admin._shared import ADMIN_LIST_CAP, deny_senior, is_senior_admin
from devplacepy.schemas import AdminWorkspacesOut
from devplacepy.seo import base_seo_context
from devplacepy.services.audit import record as audit
@@ -49,8 +54,32 @@ async def _decorate(rows: list[dict]) -> list[dict]:
return decorated
def _all_workspaces() -> list[dict]:
return list(get_table("instances").find(is_workspace=1, deleted_at=None))
def _workspace_page(page: int) -> tuple[list[dict], dict]:
table = get_table("instances")
total = table.count(is_workspace=1, deleted_at=None)
pagination = build_pagination(page, total)
offset = (pagination["page"] - 1) * pagination["per_page"]
rows = list(
table.find(
is_workspace=1,
deleted_at=None,
order_by=["-created_at"],
_limit=pagination["per_page"],
_offset=offset,
)
)
return rows, pagination
async def _workspaces_payload(page: int) -> dict:
rows, pagination = _workspace_page(page)
open_flags = flags.list_flags()
return {
"workspaces": await _decorate(rows),
"flags": open_flags[:ADMIN_LIST_CAP],
"flags_total": len(open_flags),
"pagination": pagination,
}
def _instance_or_404(uid: str) -> dict:
@@ -75,13 +104,12 @@ def _audit(request: Request, admin: dict, event_key: str, instance: dict, **extr
@router.get("/workspaces")
async def admin_workspaces(request: Request):
async def admin_workspaces(request: Request, page: int = 1):
admin = require_admin(request)
if not isinstance(admin, dict):
return admin
context = {
"workspaces": await _decorate(_all_workspaces()),
"flags": flags.list_flags(),
**await _workspaces_payload(page),
"admin_section": "workspaces",
"user": admin,
**base_seo_context(
@@ -100,13 +128,11 @@ async def admin_workspaces(request: Request):
@router.get("/workspaces/data")
async def admin_workspaces_data(request: Request):
async def admin_workspaces_data(request: Request, page: int = 1):
admin = require_admin(request)
if not isinstance(admin, dict):
return admin
return JSONResponse(
{"workspaces": await _decorate(_all_workspaces()), "flags": flags.list_flags()}
)
return JSONResponse(await _workspaces_payload(page))
@router.post("/workspaces/{uid}/suspend")
+3 -2
View File
@@ -52,13 +52,14 @@ async def login_page(request: Request, next: str | None = None):
@router.post("/login")
async def login(request: Request, data: Annotated[LoginForm, Depends(json_or_form(LoginForm))]):
email = data.email.strip().lower()
identifier = data.email.strip()
email = identifier.lower()
password = data.password
remember_me = data.remember_me == "on"
errors = []
users = get_table("users")
user = users.find_one(email=email)
user = users.find_one(email=email) or users.find_one(username=identifier)
if not user or not await verify_password_async(password, user["password_hash"]):
errors.append("Invalid email or password")
+2 -2
View File
@@ -22,7 +22,7 @@ async def token(
request: Request,
data: Annotated[LoginForm, Depends(json_or_form(LoginForm))],
):
identifier = data.email.strip().lower()
identifier = data.email.strip()
password = data.password
if not identifier or not password:
@@ -32,7 +32,7 @@ async def token(
)
users = get_table("users")
user = users.find_one(email=identifier) or users.find_one(
user = users.find_one(email=identifier.lower()) or users.find_one(
username=identifier
)
+11 -10
View File
@@ -27,6 +27,13 @@ def _war_error(request: Request, message: str, redirect_url: str):
)
def _viewable_war(war_uid: str, user: dict | None) -> dict:
war = store.get_war(war_uid)
if not store.war_viewable(war, user):
raise not_found("Battle not found")
return war
def _post_url(war: dict) -> str:
return resolve_object_url("post", war["post_uid"])
@@ -76,7 +83,7 @@ async def battles_page(
@router.get("/{war_uid}")
async def battle_state(request: Request, war_uid: str):
user = get_current_user(request)
serialized = store.get_war_serialized(store.get_war(war_uid), user)
serialized = store.get_war_serialized(_viewable_war(war_uid, user), user)
if not serialized:
raise not_found("Battle not found")
return JSONResponse(WarOut.model_validate(serialized).model_dump())
@@ -86,9 +93,7 @@ async def battle_state(request: Request, war_uid: str):
async def battle_events(
request: Request, war_uid: str, after: int = 0, limit: int = rules.EVENT_LIMIT_DEFAULT
):
war = store.resolve_if_due(store.get_war(war_uid))
if not war:
raise not_found("Battle not found")
war = store.resolve_if_due(_viewable_war(war_uid, get_current_user(request)))
events = store.events_for(war_uid, after_seq=after, limit=limit)
return JSONResponse(
WarEventsOut.model_validate(
@@ -104,9 +109,7 @@ async def join_battle(
data: Annotated[WarJoinForm, Depends(json_or_form(WarJoinForm))],
):
user = require_user(request)
war = store.get_war(war_uid)
if not war:
raise not_found("Battle not found")
war = _viewable_war(war_uid, user)
url = _post_url(war)
try:
war = store.join_war(war, user, data.faction, request)
@@ -119,9 +122,7 @@ async def join_battle(
@router.post("/{war_uid}/fight")
async def fight_battle(request: Request, war_uid: str):
user = require_user(request)
war = store.get_war(war_uid)
if not war:
raise not_found("Battle not found")
war = _viewable_war(war_uid, user)
url = _post_url(war)
try:
war, damage = store.fight(war, user, request)
+1 -1
View File
@@ -14,7 +14,7 @@ The **Legal** section (`SECTION_LEGAL`, in the `AUDIENCE_START` tier so it is on
`DOCS_PAGES` entries take optional `admin: True` (hidden + 404 for non-admins, but still indexed and surfaced only to admins by `docs_search`) and `section: "..."` (a nested sidebar group rendered by `docs_base.html`). The sidebar groups `section`s under four ordered **audience tiers** (`AUDIENCES` in `routers/docs/pages.py`): `Start here` (General), `Build with the API` (API, Components, Styles), `Contribute and internals` (Architecture, Services, Devii internals, Bots internals, Testing, Claude Code), and `Operate` (Administration, Production). `nav_groups(visible_pages)` builds the `[(audience, [(section, [pages])])]` tree from the flat visible-page list (so a section's pages collect under one heading regardless of `DOCS_PAGES` order or the API/Administration interleave from `api_doc_pages()`); `views.py` passes it as `nav`, and `docs_base.html` renders an audience super-header (`.sidebar-tier`) above each section subheading (`.sidebar-subheading`). `DOCS_PAGES` stays the canonical list for search/export/routing - the tiering is sidebar-only.
The public `getting-started` page (`SECTION_GENERAL`) is the new-contributor on-ramp (install/run, the four-faces workflow, validation); gate its deep-internals links with `{% if is_admin(user) %}` so guests get no 404s. Keep one canonical home per concept: the `auth` API group intro in `docs_api.py` defers method detail to the `authentication` prose page rather than re-listing the four methods. The member-facing `devii` prose page is functional; admins also get a `Devii internals` section of `devii-*` technical subpages.
The public `getting-started` page (`SECTION_GENERAL`) is the new-contributor on-ramp (install/run, the four-faces workflow, validation); gate its deep-internals links with `{% if is_admin(user) %}` so guests get no 404s. Keep one canonical home per concept: the `auth` API group intro in `docs_api.py` defers method detail to the `authentication` prose page rather than re-listing the auth methods (three account credentials: username+password, email+password, personal API key; the prose page is canonical for precedence, `DEVPLACE_API_KEY`, the `GET /profile` account fetch, and the separate DevRant/WebSocket auth domains). The member-facing `devii` prose page is functional; admins also get a `Devii internals` section of `devii-*` technical subpages.
## Single source of truth
+18
View File
@@ -105,6 +105,12 @@ DOCS_PAGES = [
"kind": "prose",
"section": SECTION_GENERAL,
},
{
"slug": "link-previews",
"title": "Link previews",
"kind": "prose",
"section": SECTION_GENERAL,
},
{
"slug": "emoji-shortcodes",
"title": "Emoji shortcodes",
@@ -328,6 +334,12 @@ DOCS_PAGES = [
"kind": "prose",
"section": SECTION_COMPONENTS,
},
{
"slug": "component-dp-action-menu",
"title": "dp-action-menu",
"kind": "prose",
"section": SECTION_COMPONENTS,
},
{
"slug": "component-dp-lightbox",
"title": "dp-lightbox",
@@ -388,6 +400,12 @@ DOCS_PAGES = [
"kind": "prose",
"section": SECTION_API,
},
{
"slug": "mcp",
"title": "MCP server",
"kind": "prose",
"section": SECTION_API,
},
{
"slug": "xmlrpc",
"title": "XML-RPC API",
+10
View File
@@ -163,6 +163,15 @@ async def docs_page(request: Request, slug: str):
prose_html = None
group = None
if page["kind"] == "prose":
mcp_url = ""
if user:
from devplacepy.services import mcp_tokens as mcp_store
mcp_row = mcp_store.get_active(user["uid"])
if mcp_row:
from devplacepy.routers.mcp import mcp_url_for
mcp_url = mcp_url_for(request, mcp_row["token"])
prose_html = docs_prose.render_prose(
slug,
{
@@ -170,6 +179,7 @@ async def docs_page(request: Request, slug: str):
"user": user,
"username": user.get("username") if user else "",
"api_key": user.get("api_key") if user else "",
"mcp_url": mcp_url,
},
)
elif page.get("dynamic"):
+7 -1
View File
@@ -26,6 +26,7 @@ from devplacepy.content import (
detail_context,
canonical_redirect,
first_image_url,
social_image,
)
from devplacepy.utils import get_current_user, require_user, not_found, XP_GIST
from devplacepy.seo import (
@@ -168,6 +169,9 @@ async def gist_detail(request: Request, gist_slug: str):
)
base = site_url(request)
og_image, og_width, og_height = social_image(
"gist", gist["uid"], first_image_url(gist, detail["attachments"])
)
seo_ctx = base_seo_context(
request,
title=gist.get("title", "Gist"),
@@ -175,7 +179,9 @@ async def gist_detail(request: Request, gist_slug: str):
seo_target=("gist", gist["uid"]),
robots="index,follow" if is_listed("gists", gist) else "noindex,nofollow",
og_type="article",
og_image=first_image_url(gist, detail["attachments"]),
og_image=og_image,
og_image_width=og_width,
og_image_height=og_height,
breadcrumbs=[
{"name": "Home", "url": "/feed"},
{"name": "Gists", "url": "/gists"},
+82
View File
@@ -0,0 +1,82 @@
# retoor <retoor@molodetz.nl>
from urllib.parse import urlparse
from fastapi import APIRouter, Request
from fastapi.responses import JSONResponse
from devplacepy import link_previews
from devplacepy.responses import json_error
from devplacepy.utils import get_current_user
router = APIRouter()
def _viewer_key(request: Request, viewer: dict | None) -> str:
if viewer:
return f"user:{viewer['uid']}"
forwarded = request.headers.get("x-real-ip", "")
host = forwarded.strip() or (request.client.host if request.client else "anon")
return f"ip:{host}"
def _absolute_image(request: Request, preview: dict) -> dict:
if preview.get("kind") == "internal" and preview.get("image", "").startswith("/"):
preview["image"] = str(request.base_url).rstrip("/") + preview["image"]
return preview
@router.get("")
async def link_preview(request: Request, url: str = ""):
viewer = get_current_user(request)
if not link_previews.rate_allowed(_viewer_key(request, viewer)):
response = json_error(429, "Too many preview requests, slow down")
response.headers["Retry-After"] = "60"
return response
text = (url or "").strip()
if text.startswith("/"):
target = link_previews.internal_target_for(urlparse(text).path)
if not target:
return json_error(400, "Only /posts, /gists, /projects and /news paths resolve.")
preview = link_previews.internal_preview(target[0], target[1], viewer)
if not preview:
return json_error(404, "Preview not available.")
return JSONResponse(_absolute_image(request, preview))
try:
target_url = link_previews.normalize_url(text)
except ValueError as exc:
return json_error(400, str(exc))
internal = link_previews.internal_target_for(urlparse(target_url).path)
if internal:
preview = link_previews.internal_preview(internal[0], internal[1], viewer)
if preview:
return JSONResponse(_absolute_image(request, preview))
cached = link_previews.cached_preview(target_url)
if cached:
cached["url"] = target_url
cached["kind"] = "external"
return JSONResponse(cached)
try:
preview = await link_previews.fetch_external_preview(target_url)
except ValueError as exc:
return json_error(400, str(exc))
except Exception:
return JSONResponse(link_previews.preview_fallback(target_url))
link_previews.store_preview(target_url, preview)
return JSONResponse(preview)
@router.get("/resolve")
async def link_preview_resolve(request: Request, path: str = ""):
viewer = get_current_user(request)
if not link_previews.rate_allowed(_viewer_key(request, viewer)):
response = json_error(429, "Too many preview requests, slow down")
response.headers["Retry-After"] = "60"
return response
target = link_previews.internal_target_for(urlparse(path).path)
if not target:
return json_error(400, "Only /posts, /gists, /projects and /news paths resolve.")
preview = link_previews.internal_preview(target[0], target[1], viewer)
if not preview:
return json_error(404, "Preview not available.")
return JSONResponse(_absolute_image(request, preview))
+274
View File
@@ -0,0 +1,274 @@
# retoor <retoor@molodetz.nl>
"""Per-user MCP endpoint backed by the Devii tool catalog.
Transport only: resolves ``/mcp/{token}`` to the token owner, serves the
MCP Streamable HTTP surface (``initialize``, ``tools/list``, ``tools/call``
over JSON-RPC plus a minimal SSE GET), and maps errors to JSON-RPC. Tool
logic lives in the Devii catalog and dispatcher; nothing is reimplemented
here.
The official Python MCP SDK is deliberately not a dependency: the surface we
need (three methods, JSON-RPC errors, one SSE stream) is small, and the
codebase prefers narrow dependencies over new ones.
"""
import json
import logging
from typing import Any, Optional
from fastapi import APIRouter, Request
from fastapi.responses import JSONResponse, StreamingResponse
from devplacepy.seo import site_url
from devplacepy.services import presence
from devplacepy.services.audit import record as audit
from devplacepy.utils import (
_user_from_mcp_token,
is_admin,
is_primary_admin,
)
logger = logging.getLogger("mcp.router")
router = APIRouter()
_UNSET = object()
MCP_SERVER_NAME = "devplace"
MCP_SERVER_VERSION = "1.0"
_ERROR_CODES = {
"tool_input_error",
"auth_required",
"tool_disabled",
"network_error",
"upstream_error",
"llm_error",
"unexpected",
"error",
}
def mcp_url_for(request: Request, token: str) -> str:
return f"{site_url(request).rstrip('/')}/mcp/{token}"
def _resolve_mcp_user(request: Request, token: str) -> Optional[dict]:
cached = getattr(request.state, "_mcp_user", _UNSET)
if cached is not _UNSET:
return cached
user = _user_from_mcp_token(token)
try:
request.state._mcp_user = user
except Exception:
pass
return user
def _flags(user: dict) -> tuple[bool, bool, bool]:
return True, bool(is_admin(user)), bool(is_primary_admin(user))
def _tool_schemas(user: dict) -> list[dict[str, Any]]:
from devplacepy.services.devii.actions.catalog import PLATFORM_CATALOG
authenticated, admin, primary = _flags(user)
return PLATFORM_CATALOG.tool_schemas_for(authenticated, admin, primary)
def _mcp_tools(user: dict) -> list[dict[str, Any]]:
tools = []
for schema in _tool_schemas(user):
function = schema.get("function", {})
tools.append(
{
"name": function.get("name", ""),
"description": function.get("description", ""),
"inputSchema": function.get("parameters", {"type": "object"}),
}
)
return tools
def _jsonrpc_error(code: int, message: str, request_id: Any = None) -> dict:
return {
"jsonrpc": "2.0",
"id": request_id,
"error": {"code": code, "message": message},
}
def _jsonrpc_result(result: Any, request_id: Any) -> dict:
return {"jsonrpc": "2.0", "id": request_id, "result": result}
def _build_dispatcher(user: dict, base_url: str):
import dataclasses
from devplacepy.database import db
from devplacepy.services.devii.actions.catalog import PLATFORM_CATALOG
from devplacepy.services.devii.actions.dispatcher import Dispatcher
from devplacepy.services.devii.agentic import AgenticController, LessonStore
from devplacepy.services.devii.config import load_settings
from devplacepy.services.devii.http_client import PlatformClient
from devplacepy.services.devii.tasks import TaskController, TaskStore
settings = dataclasses.replace(
load_settings(),
base_url=base_url.rstrip("/"),
platform_api_key=user.get("api_key", ""),
)
client = PlatformClient(
settings.base_url, settings.timeout_seconds, user.get("api_key", "")
)
lessons = LessonStore(db, "user", user["uid"])
tasks = TaskController(TaskStore(db, "user", user["uid"], operator=True))
agentic = AgenticController(lessons, settings)
_, admin, primary = _flags(user)
dispatcher = Dispatcher(
PLATFORM_CATALOG,
client,
settings,
tasks,
agentic,
is_admin=admin,
is_primary_admin=primary,
owner_kind="user",
owner_id=user["uid"],
)
return dispatcher, client
async def _handle_single(
request: Request, user: dict, payload: dict
) -> Optional[dict]:
method = payload.get("method", "")
request_id = payload.get("id")
params = payload.get("params") or {}
if not isinstance(params, dict):
params = {}
if method == "initialize":
requested = params.get("protocolVersion", "2025-06-18")
tools = _mcp_tools(user)
logger.info(
"MCP initialize for %s: %d tools offered",
user.get("username", ""),
len(tools),
)
return _jsonrpc_result(
{
"protocolVersion": requested,
"capabilities": {"tools": {"listChanged": False}},
"serverInfo": {
"name": MCP_SERVER_NAME,
"version": MCP_SERVER_VERSION,
},
"catalogCount": len(tools),
},
request_id,
)
if method == "notifications/initialized":
return None
if method == "ping":
return _jsonrpc_result({}, request_id)
if method == "tools/list":
return _jsonrpc_result({"tools": _mcp_tools(user)}, request_id)
if method == "tools/call":
name = str(params.get("name", ""))
arguments = params.get("arguments") or {}
if not isinstance(arguments, dict):
arguments = {}
from devplacepy.services.devii.actions.catalog import PLATFORM_CATALOG
if name not in PLATFORM_CATALOG.by_name():
audit.record(
request,
"security.authz.denied",
user=user,
origin="mcp",
result="denied",
summary=f"MCP unknown tool: {name}",
metadata={"tool": name},
)
return _jsonrpc_error(-32601, f"Method not found: {name}", request_id)
dispatcher, client = _build_dispatcher(user, site_url(request))
try:
text = await dispatcher.dispatch(name, arguments)
finally:
try:
await client.aclose()
except Exception:
pass
presence.touch(user["uid"])
audit.record(
request,
"mcp.tools.call",
user=user,
target_label=name,
origin="mcp",
summary=f"MCP {user.get('username', '')} called {name}",
metadata={"tool": name},
)
is_error = False
try:
parsed = json.loads(text)
if isinstance(parsed, dict) and parsed.get("error") in _ERROR_CODES:
is_error = True
except (ValueError, TypeError):
pass
return _jsonrpc_result(
{
"content": [{"type": "text", "text": text}],
"isError": is_error,
},
request_id,
)
return _jsonrpc_error(-32601, f"Method not found: {method}", request_id)
@router.post("/mcp/{token}")
async def mcp_endpoint(request: Request, token: str):
user = _resolve_mcp_user(request, token)
if not user:
return JSONResponse({"error": "unknown token"}, status_code=404)
try:
body = await request.json()
except (ValueError, TypeError):
return JSONResponse(
_jsonrpc_error(-32700, "Parse error"), status_code=200
)
if isinstance(body, list):
replies = []
for item in body:
if isinstance(item, dict):
reply = await _handle_single(request, user, item)
if reply is not None:
replies.append(reply)
return JSONResponse(replies)
if not isinstance(body, dict):
return JSONResponse(
_jsonrpc_error(-32600, "Invalid Request"), status_code=200
)
reply = await _handle_single(request, user, body)
if reply is None:
return JSONResponse({"jsonrpc": "2.0", "id": body.get("id"), "result": {}})
return JSONResponse(reply)
@router.get("/mcp/{token}")
async def mcp_stream(request: Request, token: str):
user = _resolve_mcp_user(request, token)
if not user:
return JSONResponse({"error": "unknown token"}, status_code=404)
async def events():
yield ": connected\n\n"
return StreamingResponse(events(), media_type="text/event-stream")
+71 -18
View File
@@ -4,7 +4,7 @@ import logging
from datetime import datetime, timedelta, timezone
from fastapi import APIRouter, Request
from fastapi.responses import HTMLResponse, JSONResponse
from devplacepy.database import get_table, db
from devplacepy.database import get_table, db, get_notification_grouping_enabled, notification_group_key
from devplacepy.templating import (
clear_unread_cache,
jinja_unread_count,
@@ -20,6 +20,7 @@ logger = logging.getLogger(__name__)
router = APIRouter()
PAGE_SIZE = 25
GROUP_FETCH_LIMIT = 250
def _group_label(created_at: str) -> str:
@@ -42,24 +43,28 @@ def _group_label(created_at: str) -> str:
@router.get("", response_class=HTMLResponse)
async def notifications_page(request: Request, before: str = None):
user = require_user(request)
grouping = get_notification_grouping_enabled(user["uid"])
next_cursor = None
groups = []
try:
notifications_table = get_table("notifications")
filters = {"user_uid": user["uid"]}
if before:
filters["created_at"] = {"<": before}
limit = GROUP_FETCH_LIMIT if grouping else PAGE_SIZE + 1
raw_notifications = list(
notifications_table.find(
**filters, order_by=["-created_at"], _limit=PAGE_SIZE + 1
**filters, order_by=["-created_at"], _limit=limit
)
)
has_more = len(raw_notifications) > PAGE_SIZE
raw_notifications = raw_notifications[:PAGE_SIZE]
if has_more and raw_notifications:
next_cursor = raw_notifications[-1]["created_at"]
if grouping:
has_more_rows = len(raw_notifications) >= GROUP_FETCH_LIMIT
raw_notifications = raw_notifications[:GROUP_FETCH_LIMIT]
else:
has_more_rows = len(raw_notifications) > PAGE_SIZE
raw_notifications = raw_notifications[:PAGE_SIZE]
if has_more_rows and raw_notifications:
next_cursor = raw_notifications[-1]["created_at"]
enriched = []
if raw_notifications:
from devplacepy.database import get_users_by_uids
@@ -78,20 +83,51 @@ async def notifications_page(request: Request, before: str = None):
"time_ago": time_ago(n["created_at"]),
}
)
groups = []
current_label = None
current_entries = []
current_event_entries = []
event_index = {}
group_count = 0
last_consumed = None
for item in enriched:
label = _group_label(item["notification"]["created_at"])
if label != current_label:
if current_entries:
groups.append({"label": current_label, "entries": current_entries})
if current_entries or current_event_entries:
groups.append({"label": current_label, "entries": current_entries, "event_entries": current_event_entries})
current_label = label
current_entries = []
current_entries.append(item)
if current_entries:
groups.append({"label": current_label, "entries": current_entries})
current_event_entries = []
event_index = {}
if not grouping:
current_entries.append(item)
continue
key = notification_group_key(item["notification"])
key_text = "\x1f".join(key)
existing = event_index.get(key_text)
if existing is None:
if group_count >= PAGE_SIZE:
continue
existing = {
"key": key_text,
"count": 0,
"unread": False,
"actors": [],
"latest": item,
}
event_index[key_text] = existing
current_event_entries.append(existing)
group_count += 1
existing["count"] += 1
if not item["notification"].get("read"):
existing["unread"] = True
actor = item["actor"]
if actor and all(a.get("uid") != actor.get("uid") for a in existing["actors"]) and len(existing["actors"]) < 3:
existing["actors"].append(actor)
last_consumed = item["notification"]["created_at"]
if current_entries or current_event_entries:
groups.append({"label": current_label, "entries": current_entries, "event_entries": current_event_entries})
if grouping and (has_more_rows or group_count >= PAGE_SIZE) and last_consumed:
next_cursor = last_consumed
except Exception as e:
logger.exception(f"Error loading notifications: {e}")
groups = []
@@ -114,11 +150,28 @@ async def notifications_page(request: Request, before: str = None):
"user": user,
"notification_groups": groups,
"next_cursor": next_cursor,
"grouping": grouping,
},
model=NotificationsOut,
)
def _mark_group_read(user_uid: str, row) -> int:
notifications_table = get_table("notifications")
if not get_notification_grouping_enabled(user_uid):
if not row["read"]:
notifications_table.update({"id": row["id"], "read": True}, ["id"])
return 1
return 0
key = notification_group_key(row)
marked = 0
for other in notifications_table.find(user_uid=user_uid, read=False):
if notification_group_key(other) == key:
notifications_table.update({"id": other["id"], "read": True}, ["id"])
marked += 1
return marked
@router.get("/counts")
async def unread_counts(request: Request):
user = get_current_user(request)
@@ -140,7 +193,7 @@ async def open_notification(request: Request, notification_uid: str):
if not n or n["user_uid"] != user["uid"]:
return action_result(request, "/notifications")
if not n["read"]:
notifications_table.update({"id": n["id"], "read": True}, ["id"])
_mark_group_read(user["uid"], n)
clear_unread_cache(user["uid"])
audit.record(
request,
@@ -160,7 +213,7 @@ async def mark_read(request: Request, notification_uid: str):
notifications_table = get_table("notifications")
n = notifications_table.find_one(uid=notification_uid)
if n and n["user_uid"] == user["uid"]:
notifications_table.update({"id": n["id"], "read": True}, ["id"])
_mark_group_read(user["uid"], n)
clear_unread_cache(user["uid"])
audit.record(
request,
+7 -1
View File
@@ -33,6 +33,7 @@ from devplacepy.content import (
detail_context,
canonical_redirect,
first_image_url,
social_image,
get_user_sidebar_gists,
get_user_sidebar_projects,
)
@@ -176,6 +177,9 @@ def post_page_context(
comment_count = count_all(top_level)
base = site_url(request)
next_post_url = _next_post_url(post, user)
og_image, og_width, og_height = social_image(
"post", post["uid"], first_image_url(post, detail["attachments"])
)
seo_ctx = base_seo_context(
request,
title=post.get("title") or "Post",
@@ -192,7 +196,9 @@ def post_page_context(
},
],
og_type="article",
og_image=first_image_url(post, detail["attachments"]),
og_image=og_image,
og_image_width=og_width,
og_image_height=og_height,
next_url=next_post_url,
schemas=[
website_schema(base),
+27 -2
View File
@@ -3,8 +3,8 @@
import logging
from typing import Annotated
from fastapi import Depends, APIRouter, Request
from devplacepy.models import CustomizationToggleForm
from devplacepy.database import set_customization_pref
from devplacepy.models import CustomizationToggleForm, EnterToSubmitForm
from devplacepy.database import set_customization_pref, set_enter_to_submit
from devplacepy.responses import action_result
from devplacepy.services.audit import record as audit
@@ -47,6 +47,31 @@ async def set_customization_global(
):
return _toggle_customization(request, username, "global", data.value)
@router.post("/{username}/enter-to-submit")
async def set_enter_to_submit_route(
request: Request,
username: str,
data: Annotated[EnterToSubmitForm, Depends(json_or_form(EnterToSubmitForm))],
):
target, denied = resolve_customization_target(request, username)
if denied is not None:
return denied
set_enter_to_submit(target["uid"], data.value)
audit.record(
request,
"profile.enter_to_submit.toggle",
target_type="user",
target_uid=target["uid"],
target_label=target["username"],
old_value=0 if data.value else 1,
new_value=1 if data.value else 0,
summary=f"{'enabled' if data.value else 'disabled'} Enter to send for {target['username']}",
links=[audit.target("user", target["uid"], target["username"])],
)
url = f"/profile/{target['username']}"
return action_result(request, url, data={"url": url, "enter_to_submit": data.value})
@router.post("/{username}/customization/pagetype")
async def set_customization_pagetype(
request: Request,
+145 -7
View File
@@ -11,6 +11,9 @@ from devplacepy.database import (
is_listed,
get_table,
get_customization_prefs,
get_enter_to_submit,
get_notification_grouping_enabled,
get_notification_throttle_enabled,
get_notification_prefs,
get_user_stars,
get_user_rank,
@@ -39,7 +42,7 @@ from devplacepy.database.awards import (
get_prominent_award,
get_user_awards,
)
from devplacepy.content import can_view_project, enrich_items
from devplacepy.content import can_view_project, enrich_items, discoverable_target_rows
from devplacepy.routers.nodes.me import _me as node_me_view
from devplacepy.routers.profile.consent import consent_view
from devplacepy.services.moderation.deletion import grace_hours
@@ -155,6 +158,13 @@ async def profile_page(
profile_user = users.find_one(username=username)
if not profile_user:
raise not_found("Profile not found")
if tab == "mcp":
_mcp_owner = bool(
current_user and current_user["uid"] == profile_user["uid"]
)
_mcp_admin = bool(current_user and current_user.get("role") == "Admin")
if not (_mcp_owner or _mcp_admin):
tab = "posts"
viewing_self = bool(current_user and current_user["uid"] == profile_user["uid"])
if current_user:
mark_notifications_read_by_target(
@@ -277,11 +287,16 @@ async def profile_page(
}
)
comments_table = get_table("comments")
for c in comments_table.find(
user_uid=profile_user["uid"],
deleted_at=None,
order_by=["-created_at"],
_limit=10,
for c in discoverable_target_rows(
list(
comments_table.find(
user_uid=profile_user["uid"],
deleted_at=None,
order_by=["-created_at"],
_limit=10,
)
),
current_user,
):
target_uid = c.get("target_uid", c.get("post_uid", ""))
target_type = c.get("target_type", "post")
@@ -322,6 +337,54 @@ async def profile_page(
viewer_is_admin = bool(current_user and current_user.get("role") == "Admin")
can_view_api_key = bool(current_user and (is_owner or viewer_is_admin))
api_key = profile_user.get("api_key") if can_view_api_key else None
email = profile_user.get("email") if can_view_api_key else None
mcp_url = None
mcp_created_at = None
mcp_capabilities = []
if tab == "mcp" and can_view_api_key:
from devplacepy.services import mcp_tokens as mcp_store
mcp_row = mcp_store.get_active(profile_user["uid"])
if mcp_row:
from devplacepy.routers.mcp import mcp_url_for
mcp_url = mcp_url_for(request, mcp_row["token"])
mcp_created_at = mcp_row.get("created_at", "")
if current_user:
from devplacepy.services.devii.actions.catalog import (
CATALOG_GROUPS,
PLATFORM_CATALOG,
)
from devplacepy.utils import is_admin as _is_admin_fn
from devplacepy.utils import is_primary_admin as _is_primary_admin_fn
viewer_schemas = PLATFORM_CATALOG.tool_schemas_for(
True,
bool(_is_admin_fn(profile_user)),
bool(_is_primary_admin_fn(profile_user)),
)
viewer_names = {
schema.get("function", {}).get("name", "")
for schema in viewer_schemas
}
mcp_capabilities = [
{
"group": group,
"example": next(
(
action.name
for action in actions
if action.name in viewer_names
),
"",
),
}
for group, actions in CATALOG_GROUPS.items()
]
mcp_capabilities = [
entry for entry in mcp_capabilities if entry["example"]
]
ai_correction_enabled = (
bool(profile_user.get("ai_correction_enabled")) if is_owner else False
)
@@ -390,6 +453,19 @@ async def profile_page(
if (tab == "notifications" and can_manage_customization)
else []
)
enter_to_submit = (
get_enter_to_submit(profile_user["uid"]) if can_manage_customization else True
)
notif_grouping_enabled = (
get_notification_grouping_enabled(profile_user["uid"])
if (tab == "notifications" and can_manage_customization)
else True
)
notif_throttle_enabled = (
get_notification_throttle_enabled(profile_user["uid"])
if (tab == "notifications" and can_manage_customization)
else True
)
notif_telegram_paired = (
telegram_store.is_paired(profile_user["uid"])
if (tab == "notifications" and can_manage_customization)
@@ -485,6 +561,10 @@ async def profile_page(
"media_pagination": media_pagination,
"can_view_api_key": can_view_api_key,
"api_key": api_key,
"email": email,
"mcp_url": mcp_url,
"mcp_created_at": mcp_created_at,
"mcp_capabilities": mcp_capabilities,
"ai_correction_enabled": ai_correction_enabled,
"ai_correction_sync": ai_correction_sync,
"ai_correction_prompt": ai_correction_prompt,
@@ -500,6 +580,9 @@ async def profile_page(
"can_manage_customization": can_manage_customization,
"cust_disable_global": customization_prefs["disable_global"],
"cust_disable_pagetype": customization_prefs["disable_pagetype"],
"enter_to_submit": enter_to_submit,
"notif_grouping_enabled": notif_grouping_enabled,
"notif_throttle_enabled": notif_throttle_enabled,
"notification_prefs": notification_prefs,
"consents": consents,
"node_me": node_me,
@@ -594,7 +677,62 @@ async def regenerate_api_key(request: Request):
summary=f"{user['username']} regenerated their API key",
links=[audit.target("user", user["uid"], user["username"])],
)
return JSONResponse({"api_key": new_key})
return JSONResponse(
{
"api_key": new_key,
"username": user["username"],
"email": user["email"],
}
)
@router.post("/mcp/regenerate")
async def mcp_regenerate(request: Request):
user = require_user(request)
from devplacepy.routers.mcp import mcp_url_for
from devplacepy.services import mcp_tokens as mcp_store
result = mcp_store.regenerate(user)
url = mcp_url_for(request, result["token"])
logger.info(f"MCP URL regenerated for {user['username']}")
audit.record(
request,
"profile.mcp.regenerate",
user=user,
target_type="user",
target_uid=user["uid"],
target_label=user["username"],
summary=f"{user['username']} regenerated their MCP URL",
links=[audit.target("user", user["uid"], user["username"])],
)
return JSONResponse(
{
"token": result["token"],
"mcp_url": url,
"username": user["username"],
"email": user["email"],
}
)
@router.post("/mcp/revoke")
async def mcp_revoke(request: Request):
user = require_user(request)
from devplacepy.services import mcp_tokens as mcp_store
revoked = mcp_store.revoke(user["uid"])
logger.info(f"MCP URL revoked for {user['username']}")
audit.record(
request,
"profile.mcp.revoke",
user=user,
target_type="user",
target_uid=user["uid"],
target_label=user["username"],
summary=f"{user['username']} revoked their MCP URL",
links=[audit.target("user", user["uid"], user["username"])],
)
return JSONResponse({"revoked": revoked, "username": user["username"]})
+50 -2
View File
@@ -3,8 +3,13 @@
import logging
from typing import Annotated
from fastapi import Depends, APIRouter, Request
from devplacepy.models import NotificationPrefForm
from devplacepy.database import set_notification_pref, reset_notification_prefs
from devplacepy.models import NotificationPrefForm, CustomizationToggleForm
from devplacepy.database import (
set_notification_pref,
reset_notification_prefs,
set_notification_grouping_enabled,
set_notification_throttle_enabled,
)
from devplacepy.responses import action_result, json_error
from devplacepy.services.audit import record as audit
@@ -60,6 +65,49 @@ async def set_notification_preference(
},
)
def _toggle_notification_display(request: Request, username: str, kind: str, value: bool):
target, denied = resolve_customization_target(request, username)
if denied is not None:
return denied
if kind == "grouping":
set_notification_grouping_enabled(target["uid"], value)
field = "notif_grouping_enabled"
else:
set_notification_throttle_enabled(target["uid"], value)
field = "notif_throttle_enabled"
audit.record(
request,
f"profile.notification.{kind}.toggle",
target_type="user",
target_uid=target["uid"],
target_label=target["username"],
old_value=0 if value else 1,
new_value=1 if value else 0,
summary=f"{'enabled' if value else 'disabled'} notification {kind} for {target['username']}",
links=[audit.target("user", target["uid"], target["username"])],
)
url = f"/profile/{target['username']}?tab=notifications"
return action_result(request, url, data={"url": url, field: value})
@router.post("/{username}/notifications/grouping")
async def set_notification_grouping(
request: Request,
username: str,
data: Annotated[CustomizationToggleForm, Depends(json_or_form(CustomizationToggleForm))],
):
return _toggle_notification_display(request, username, "grouping", data.value)
@router.post("/{username}/notifications/throttling")
async def set_notification_throttling(
request: Request,
username: str,
data: Annotated[CustomizationToggleForm, Depends(json_or_form(CustomizationToggleForm))],
):
return _toggle_notification_display(request, username, "throttle", data.value)
@router.post("/{username}/notifications/reset")
async def reset_notification_preferences(request: Request, username: str):
target, denied = resolve_customization_target(request, username)
+5 -1
View File
@@ -31,7 +31,11 @@ Each project carries a virtual filesystem so it can hold a whole software projec
## Project visibility and read-only
Two owner-controlled flags on the `projects` row, both integer `0`/`1` (default `0`, set on the create insert so the columns always exist): `is_private` hides the project from other viewers, `read_only` freezes its filesystem against every mutation. **The full security predicates** (`content.can_view_project`, `owns_instance`, `can_view_project_containers`, `can_view_instance`, `can_manage_instance`, the primary-administrator container isolation rules) are documented once in the root CLAUDE.md's "Project visibility (`is_private`) and read-only" section - this file covers only the project-page/filesystem UI-level behavior that sits on top of those predicates.
Two owner-controlled flags on the `projects` row, both integer `0`/`1` (default `0`, set on the create insert so the columns always exist): `is_private` hides the project from other viewers, `read_only` freezes its filesystem against every mutation. **The full security predicates** (documented once, here):
- Project visibility (`is_private`) and read-only (`read_only`) are owner-controlled flags on `projects`. Read access is gated by the single `content.can_view_project(project, user)` predicate at EVERY read surface, never re-implemented inline. Predicate: `not is_private OR is_owner OR (is_admin AND owner is not an admin)`.
- Containers have their own, stricter isolation predicates (`owns_instance`, `can_view_project_containers`, `can_view_instance`, `can_manage_instance`): the primary administrator sees/manages every container; any other admin can VIEW others' containers only on public projects and can MANAGE only instances they own.
- Read-only is enforced as a single data-layer guard `project_files._guard_writable(project_uid)` at the top of every mutation entrypoint; add it to any NEW file-mutating function. Devii may flip read-only/visibility only after explicit confirmation.
**Toggle routes** (owner-only, `routers/projects/index.py`): `POST /projects/{slug}/private` and `POST /projects/{slug}/readonly`, each taking `ProjectFlagForm{value: bool}` and routed through `_set_project_flag`. The create form carries an `is_private` checkbox (`ProjectForm.is_private`); `project_detail.html` shows Private/Read-only badges and owner toggle buttons (**both** the private and read-only buttons carry `data-confirm` so `ModalManager.initConfirmations` gates them through `app.dialog`), and `project_files.html` hides the editing toolbar + shows a banner when read-only. Schemas: `is_private`/`read_only` on `ProjectOut` and `ProjectDetailOut`, `read_only`/`is_private` on `ProjectFilesOut`.
+12 -1
View File
@@ -23,6 +23,7 @@ from devplacepy.database import (
get_reactions_by_targets,
get_user_bookmarks,
get_polls_by_post_uids,
current_object_image_map,
)
from devplacepy.services.opinionwar import store as war_store
from devplacepy.database import (
@@ -48,6 +49,7 @@ from devplacepy.content import (
detail_context,
canonical_redirect,
first_image_url,
social_image,
is_owner,
can_view_project,
can_view_project_containers,
@@ -140,11 +142,13 @@ def get_projects_list(
recent_comments = get_recent_comments_by_target_uids(
"project", [p["uid"] for p in page], 3, viewer
)
images = current_object_image_map("project", [p["uid"] for p in page])
for p in page:
author = users_map.get(p["user_uid"])
p["author_name"] = author["username"] if author else "Unknown"
p["my_vote"] = user_votes.get(p["uid"], 0)
p["recent_comments"] = recent_comments.get(p["uid"], [])
p["social_image_url"] = images.get(p["uid"], "")
return page, next_cursor, total
@@ -253,13 +257,20 @@ async def project_detail(request: Request, project_slug: str, before: str = None
),
None,
)
og_image, og_width, og_height = social_image(
"project",
project["uid"],
cover_url or first_image_url(project, detail["attachments"]),
)
seo_ctx = base_seo_context(
request,
title=project.get("title", "Project"),
description=project.get("description", ""),
seo_target=("project", project["uid"]),
robots=robots,
og_image=cover_url or first_image_url(project, detail["attachments"]),
og_image=og_image,
og_image_width=og_width,
og_image_height=og_height,
breadcrumbs=[
{"name": "Home", "url": "/feed"},
{"name": "Projects", "url": "/projects"},
+10
View File
@@ -66,6 +66,16 @@ async def react(
reaction_event = "reaction.add" if added else "reaction.remove"
if added:
track_action(user["uid"], "reaction")
from devplacepy.content import get_target_owner_uid
from devplacepy.database import OBJECT_IMAGE_TYPES
from devplacepy.services.seo_image import schedule_seo_image_for_reactions
if added and target_type in OBJECT_IMAGE_TYPES:
schedule_seo_image_for_reactions(
target_type,
target_uid,
get_target_owner_uid(target_type, target_uid) or user["uid"],
)
audit.record(
request,
+3
View File
@@ -135,6 +135,9 @@ from devplacepy.schemas.admin import (
AdminNewsOut,
AdminNotificationsOut,
AdminSettingsOut,
ServiceDetailOut,
ServiceOut,
ServicesOut,
AdminTrashOut,
AdminUserOut,
AdminUsersOut,
+34
View File
@@ -94,12 +94,43 @@ class AdminDeviiTaskItemOut(_Out):
class AdminDeviiTasksOut(_Out):
items: list[AdminDeviiTaskItemOut] = []
pagination: Optional[Any] = None
state: str = "active"
tabs: list[dict] = []
limits: dict = {}
admin_section: Optional[str] = None
class ServiceOut(_Out):
name: Optional[str] = None
title: Optional[str] = None
description: Optional[str] = None
details: Optional[str] = None
enabled: bool = False
status: Optional[str] = None
interval_seconds: Optional[int] = None
last_run: Optional[str] = None
next_run: Optional[str] = None
heartbeat: Optional[str] = None
uptime: Optional[str] = None
log_buffer: list[str] = []
metrics: dict = {}
fields: list[Any] = []
field_groups: list[Any] = []
class ServicesOut(_Out):
services: list[ServiceOut] = []
services_total: Optional[int] = None
admin_section: Optional[str] = None
class ServiceDetailOut(_Out):
service: ServiceOut
tool_groups: Optional[list[Any]] = None
admin_section: Optional[str] = None
class AdminGameOut(_Out):
era_active: bool = False
era_name: str = ""
@@ -139,6 +170,7 @@ class AdminCommunityItemOut(_Out):
class AdminCommunitiesOut(_Out):
items: list[AdminCommunityItemOut] = []
pagination: Optional[Any] = None
sync_enabled: bool = False
service_enabled: bool = False
service_dry_run: bool = True
@@ -316,7 +348,9 @@ class AdminNodesOut(_Out):
devices_by_country: dict[str, int] = {}
usage_today: dict[str, int] = {}
flags: list[AdminNodeFlagOut] = []
flags_total: int = 0
devices: list[AdminNodeDeviceOut] = []
devices_total: int = 0
settings: list[AdminNodeSettingOut] = []
limits: dict[str, int] = {}
circuits: list[AdminNodeCircuitOut] = []
+1
View File
@@ -72,6 +72,7 @@ class BackupScheduleOut(_Out):
class BackupDashboardOut(_Out):
storage: dict = {}
backups: list[BackupOut] = []
backups_total: int = 0
schedules: list[BackupScheduleOut] = []
targets: list[dict] = []
metrics: dict = {}
+3
View File
@@ -48,6 +48,7 @@ class ContainersOut(_Out):
class AdminContainersOut(_Out):
instances: list = []
pagination: Optional[Any] = None
projects: list = []
boot_languages: list = []
restart_policies: list = []
@@ -199,5 +200,7 @@ class WorkspaceOut(_Out):
class AdminWorkspacesOut(_Out):
workspaces: list[WorkspaceViewOut] = []
flags: list[WorkspaceFlagOut] = []
flags_total: int = 0
pagination: Optional[Any] = None
admin_section: Optional[str] = None
user: Optional[Any] = None
+10
View File
@@ -50,6 +50,16 @@ class AdminGatewayOut(_Out):
default_provider: dict = {}
quota_defaults: dict = {}
stats_ranges: list = []
providers_total: int = 0
models_total: int = 0
quota_rules_total: int = 0
stats: dict = {}
stats_range: str = "24h"
stats_generated_iso: Optional[str] = None
stats_models: list = []
stats_table_models: list = []
stats_table_models_total: int = 0
media: dict = {}
admin_section: Optional[str] = None
tested: str = ""
test_image: str = ""
+13
View File
@@ -36,6 +36,7 @@ class FeedItemOut(_Out):
poll: Optional[PollOut] = None
war: Optional[WarOut] = None
project_link: Optional[ProjectLinkOut] = None
social_image_url: Optional[str] = None
class GistItemOut(_Out):
@@ -46,12 +47,14 @@ class GistItemOut(_Out):
my_vote: int = 0
comment_count: int = 0
recent_comments: list[CommentItemOut] = []
social_image_url: Optional[str] = None
class ProjectListItemOut(ProjectOut):
author_name: Optional[str] = None
my_vote: int = 0
recent_comments: list[CommentItemOut] = []
social_image_url: Optional[str] = None
class NewsListItemOut(_Out):
@@ -85,9 +88,18 @@ class NotificationItemOut(_Out):
time_ago: Optional[str] = None
class NotificationEventGroupOut(_Out):
key: Optional[str] = None
count: int = 0
unread: bool = False
actors: list[UserOut] = []
latest: Optional[NotificationItemOut] = None
class NotificationGroupOut(_Out):
label: Optional[str] = None
entries: list[NotificationItemOut] = []
event_entries: list[NotificationEventGroupOut] = []
class LeaderboardEntryOut(_Out):
@@ -262,6 +274,7 @@ class MessagesOut(_Out):
class NotificationsOut(_Out):
notification_groups: list[NotificationGroupOut] = []
next_cursor: Optional[str] = None
grouping: bool = True
class LeaderboardOut(_Out):
+7
View File
@@ -45,6 +45,10 @@ class ProfileOut(_Out):
profile_is_admin: bool = False
can_view_api_key: bool = False
api_key: Optional[str] = None
email: Optional[str] = None
mcp_url: Optional[str] = None
mcp_created_at: Optional[str] = None
mcp_capabilities: list[Any] = []
ai_correction_enabled: bool = False
ai_correction_sync: bool = False
ai_correction_prompt: Optional[str] = None
@@ -60,6 +64,9 @@ class ProfileOut(_Out):
can_manage_customization: bool = False
cust_disable_global: bool = False
cust_disable_pagetype: bool = False
enter_to_submit: bool = True
notif_grouping_enabled: bool = True
notif_throttle_enabled: bool = True
ai_quota: Optional[dict] = None
correction_usage: Optional[dict] = None
modifier_usage: Optional[dict] = None
+6
View File
@@ -14,6 +14,9 @@ class StatisticsMetricOut(BaseModel):
format: str = "int"
delta: Optional[float] = None
direction: Optional[str] = None
display: Optional[str] = None
arrow: Optional[str] = None
delta_display: Optional[str] = None
class StatisticsPointOut(BaseModel):
@@ -32,6 +35,9 @@ class StatisticsTableOut(BaseModel):
title: str
columns: list[str]
rows: list[list[Any]]
column_classes: list[str] = []
display_rows: list[list[str]] = []
row_count: Optional[str] = None
class StatisticsHighlightOut(BaseModel):
+4
View File
@@ -322,6 +322,8 @@ def base_seo_context(
robots="index,follow",
og_type="website",
og_image=None,
og_image_width=1200,
og_image_height=630,
breadcrumbs=None,
schemas=None,
prev_url=None,
@@ -366,6 +368,8 @@ def base_seo_context(
"og_title": seo_title or SITE_NAME,
"og_description": clean_description,
"og_image": og_img,
"og_image_width": og_image_width or 1200,
"og_image_height": og_image_height or 630,
"og_type": og_type,
"breadcrumbs": breadcrumbs or [],
"page_schema": combine(page_schemas),
+5 -1
View File
@@ -123,6 +123,10 @@ devplace devii reset-quota --all # Reset every quota (users and guests)
`AcceptanceService` is a lock-owner `BaseService` (**opt-in**, `default_enabled = False`, five minutes, floor 60s) that grants every policy agreement to every account which has not declined it, so a production-identical instance used for manual testing never interrupts with an acceptance dialog. It is invisible to the rest of the application by contract: one registration line in `main.py` is the only import anywhere, and there is no route, schema, template, Devii tool or environment flag. The decline register is the consent ledger itself - the service only ever writes `granted`, so any `withdrawn` row was written by a human and that pair is never touched again. Three gates stand between a fresh install and a single written row (service disabled, every agreement disabled, dry run on). Full subsystem detail in `devplacepy/services/acceptance/CLAUDE.md`; the design record is `accept.md` at the repository root.
## Project blob sweep (`services/project_blob_sweep.py`)
`ProjectBlobSweepService` is a lock-owner `BaseService` (default-enabled, six hours, floor 300s) that deletes project file blobs which no `project_files` row references and which are older than a minimum age, through `project_files.referenced_project_blobs` + `sweep_project_blob_tree` (the same code `devplace system prune` uses). Two static ceilings guard it: the minimum age (`project_blob_sweep_min_age_seconds`, default 3600, floor 300) so a blob written a moment before its row is never swept, and the orphan cap (`project_blob_sweep_max_orphans`, default 1000, ceiling 100000): above it the service deletes nothing, logs `BLOCKED` and reports Blocked, because that many orphans means a leak is running and a human should look. Full background in `devplacepy/services/containers/CLAUDE.md` ("Bidirectional sync").
## Multi-worker concurrency (preferred rules)
`uvicorn --workers N` = N independent processes sharing only the filesystem and SQLite DB. Module-global caches/counters are per-process, so a local `clear()` is invisible to siblings. Full reference: admin docs `Production -> Multi-worker and concurrency` (`templates/docs/production-concurrency.html`). Enforce these:
@@ -132,7 +136,7 @@ devplace devii reset-quota --all # Reset every quota (users and guests)
- **Deterministic / eventual caches skip version-sync on purpose.** Two caches need no `cache_state` name because correctness does not depend on cross-worker freshness: (1) `docs_prose._render_markdown` is an `@lru_cache` on the **static** prose source string (pure function of template content, so identical on every worker; changes only on deploy), and (2) `routers/landing.py` `_home_cache` (`TTLCache ttl=60`) memoizes the guest `/` blocks - the featured-news block (identical for everyone) and the latest-posts block **only for the no-block case**; a viewer with a non-empty block set bypasses the cache and is computed fresh, so the original block-filter semantics are preserved byte-for-byte and there is zero cross-user leakage. Worst case is a soft-deleted/edited public post lingering on `/` for <=60s. Use a plain `TTLCache`/`lru_cache` (no version name) ONLY when the value is deterministic or its staleness is purely cosmetic; anything whose staleness affects correctness or permissions MUST use the version-sync pattern above.
- **Authoritative state lives in the DB**, memory is only a short-TTL accelerator (sessions, the Devii 24h cap via `devii_usage_ledger`, cost counters).
- **Global rates/quotas are worker-count-aware or DB-backed.** The rate limiter enforces `ceil(limit / DEVPLACE_WEB_WORKERS)` per process so the aggregate matches the configured value with no per-request write. `DEVPLACE_WEB_WORKERS` MUST equal the real `--workers` (set in `make prod`=2 and the Dockerfile=2; default 1 for dev). Update it whenever you change worker count.
- **First-boot side effects are flock-serialized and idempotent.** `init_db()` runs under a blocking `flock` on `devplace-init.lock` (the seed-if-missing inserts would otherwise race to duplicate rows); `ensure_certificates()` early-returns when keys exist and otherwise generates under `.vapid.lock`. Any new run-once-at-startup work follows the same pattern (flock + exists-check / `INSERT OR IGNORE`).
- **First-boot side effects are flock-serialized and idempotent.** `init_db()` runs under a blocking `flock` on `devplace-init.lock` (the seed-if-missing inserts would otherwise race to duplicate rows); `ensure_certificates()` early-returns when keys exist and otherwise creates the key directory, then generates under `.vapid.lock`. Any new run-once-at-startup work follows the same pattern (flock + exists-check / `INSERT OR IGNORE`).
- **Run-once background work stays behind the services lock**, never per-worker: gate it on `service_manager.owns_lock()` (held via `devplace-services.lock`), as news/bots/Devii hub do.
## Performance caches (request-path)
+6 -2
View File
@@ -88,10 +88,14 @@ class CommunityStore:
row = table.find_one(slug=ref, deleted_at=None) or table.find_one(uid=ref, deleted_at=None)
return decode(row, JSON_COLUMNS)
def list(self) -> list[dict]:
rows = get_table("communities").find(deleted_at=None, order_by=["name"])
def list(self, limit: int | None = None, offset: int = 0) -> list[dict]:
window = {} if limit is None else {"_limit": limit, "_offset": offset}
rows = get_table("communities").find(deleted_at=None, order_by=["name"], **window)
return [decode(row, JSON_COLUMNS) for row in rows]
def count(self) -> int:
return get_table("communities").count(deleted_at=None)
def pending(self, limit: int) -> list[dict]:
horizon = iso(now() - timedelta(seconds=LIMITS.run_timeout_seconds))
table = get_table("communities")
+32 -8
View File
@@ -12,7 +12,7 @@ Admin-only. Supervises container instances, all running one shared prebuilt imag
Mounting the docker socket is root-equivalent on the host. Every run/exec/lifecycle/schedule operation is gated `require_admin` (HTTP) and `requires_admin=True` (Devii). `--privileged` is never passed. User input is never shell-interpolated - every call is an arg-list subprocess, never `shell=True`. Resource limits are applied via `--cpus`/`--memory`.
On top of the admin gate, **per-user container isolation** applies (see root CLAUDE.md "Project visibility (is_private) and read-only" convention): only the **primary administrator** (earliest-created Admin) and the instance owner (creator or project owner) may manage an instance; other admins get read-only access, and only when the instance's project is public. Enforced via `content.py` predicates `owns_instance`, `can_view_project_containers`, `can_view_instance`, `can_manage_instance` (all reusing `is_primary_admin`): the primary administrator sees and manages every container including those on private projects; any other admin can VIEW containers of others only when the instance's project is public (private-project containers of others are invisible; of private containers they see only their own), and can MANAGE (edit/lifecycle/exec/terminal/sync/delete/schedules) only instances they own - non-owners get 403 plus an audit row with `result="denied"` (WS close `1008`). This is enforced at every entrypoint: `routers/projects/containers/` (`project_for` + `manage_guard` + the exec WS), the admin Containers manager (`_decorate` filtering + per-row `can_manage`, `_viewable_instance_or_404`, `_manage_denied`, create + project-search), the Devii container tools (`ContainerController._project` + `_require_manage`), and the live view relay (broadcast topics never carry private-project instances).
On top of the admin gate, **per-user container isolation** applies (predicates documented once in `devplacepy/routers/projects/CLAUDE.md` "Project visibility and read-only" (is_private) and read-only" convention): only the **primary administrator** (earliest-created Admin) and the instance owner (creator or project owner) may manage an instance; other admins get read-only access, and only when the instance's project is public. Enforced via `content.py` predicates `owns_instance`, `can_view_project_containers`, `can_view_instance`, `can_manage_instance` (all reusing `is_primary_admin`): the primary administrator sees and manages every container including those on private projects; any other admin can VIEW containers of others only when the instance's project is public (private-project containers of others are invisible; of private containers they see only their own), and can MANAGE (edit/lifecycle/exec/terminal/sync/delete/schedules) only instances they own - non-owners get 403 plus an audit row with `result="denied"` (WS close `1008`). This is enforced at every entrypoint: `routers/projects/containers/` (`project_for` + `manage_guard` + the exec WS), the admin Containers manager (`_decorate` filtering + per-row `can_manage`, `_viewable_instance_or_404`, `_manage_denied`, create + project-search), the Devii container tools (`ContainerController._project` + `_require_manage`), and the live view relay (broadcast topics never carry private-project instances).
## One shared image, no in-app builds (load-bearing)
@@ -423,13 +423,17 @@ sustained over time this leaked **5.9 million orphan blobs (~96GB)** in producti
only when the host disk hit 100% full. Both are now closed at their root:
- **`api._sync_dir_bidirectional_locked`** wraps `project_files.sync_dir_bidirectional`
behind a per-`project_uid` `threading.Lock` (`api._sync_lock_for`, a lazily-created
registry - both `sync_workspace` and `sync_bidirectional_sync` call it instead of the
raw function). The acquire is **non-blocking**: a second sync for a project already mid-sync
is skipped outright (returns the zero-counts dict), never queued or awaited. This runs on
an `asyncio.to_thread` worker in both call sites, so blocking would tie up a thread pool
slot for no reason - a skipped project is simply picked up on the next tick or the user's
next explicit sync.
behind `locks.project_sync_lock(project_uid)`, a **cross-process** non-blocking `flock` on
`LOCKS_DIR/project-sync-<uid>.lock` (both `sync_workspace` and `sync_bidirectional_sync` call it
instead of the raw function). It is a file lock, not a `threading.Lock`, because production
runs several uvicorn workers: a user-triggered sync served by one worker and the reconciler on
the service-lock owner are different processes and an in-process lock never saw each other.
The acquire is **non-blocking**: a second sync for a project already mid-sync is skipped
outright (returns the zero-counts dict), never queued or awaited. This runs on an
`asyncio.to_thread` worker in both call sites, so blocking would tie up a thread pool slot for
no reason - a skipped project is simply picked up on the next tick or the user's next explicit
sync. The lock file name is the project uid with every character outside `[A-Za-z0-9_-]`
replaced, so a uid can never escape `LOCKS_DIR`.
- **`project_files.IMPORT_SKIP_NAMES`** gained common build-output directory names (`build`,
`dist`, `target`, `out`, `bin`, `obj`, `.next`, `.nuxt`, `.gradle`, `.tox`,
`cmake-build-debug`, `cmake-build-release`) and a NEW parallel set,
@@ -440,6 +444,26 @@ only when the host disk hit 100% full. Both are now closed at their root:
AND the sync path via `SYNC_SKIP_NAMES = IMPORT_SKIP_NAMES | {...}`), so compiled/build
artifacts are never imported into a project regardless of entry point, not just never synced.
- **`project_files.store_upload` never writes a blob it does not need and never strands one.** An
import whose bytes equal the existing row's blob (`_blob_matches`: same size, same bytes) returns
the existing node untouched, so a `touch`ed file costs no new blob and no row update. The capacity
guard runs BEFORE the blob is written, and a failure between writing the blob and writing the row
unlinks the new blob before re-raising. The old blob is unlinked only after the row points at the
new one.
- **A row whose blob is missing is retried at most every `MISSING_BLOB_RETRY_SECONDS` (600).**
`project_files._export_with_backoff` remembers `(project_uid, path)` after a failed export in a
per-process dict capped at `MISSING_BLOB_MAX_TRACKED` (10000, cleared when full), instead of
retrying the copy on every 60s tick forever. Such rows are counted in the throttled "missing
blob" warning and are never deleted by sync; repairing them is a human decision.
- **A scheduled sweep is the floor under all of the above.** `ProjectBlobSweepService`
(`services/project_blob_sweep.py`, lock-owner `BaseService`, default-enabled, every 6h, floor 300s)
deletes blobs with no DB reference that are older than `project_blob_sweep_min_age_seconds`
(default 3600, floor 300: a blob whose row is not inserted yet is never touched) and refuses to
delete anything when more than `project_blob_sweep_max_orphans` (default 1000) are found in one
run: it logs `BLOCKED`, shows Blocked on the Overview tab, and a human inspects and runs
`devplace system prune`. The tree walk runs in `asyncio.to_thread`; the DB read of the referenced
set stays inline. Gap: there is no push notification for Blocked, only the log and the stat card.
Neither fix requires (or should ever regress into) a redesign of the manifest/reconciliation
model above - the lock only prevents two runs from touching the same project's `project_files`
rows at once, and the skip sets only shrink what `_walk_workspace_files` yields. Recovering
+4 -18
View File
@@ -5,11 +5,11 @@ import json
import re
import secrets
import socket
import threading
from pathlib import Path
from devplacepy import config, project_files, stealth
from devplacepy.services.containers import store
from devplacepy.services.containers.locks import project_sync_lock
from devplacepy.services.containers.backend.base import (
WORKSPACE_MOUNT,
WORKSPACE_STATE_MOUNT,
@@ -624,8 +624,6 @@ def run_spec_for(instance: dict, image_tag: str) -> RunSpec:
)
_SYNC_LOCKS: dict[str, threading.Lock] = {}
_SYNC_LOCKS_GUARD = threading.Lock()
_SYNC_EMPTY_COUNTS = {
"exported": 0,
"imported": 0,
@@ -634,15 +632,6 @@ _SYNC_EMPTY_COUNTS = {
}
def _sync_lock_for(project_uid: str) -> threading.Lock:
with _SYNC_LOCKS_GUARD:
lock = _SYNC_LOCKS.get(project_uid)
if lock is None:
lock = threading.Lock()
_SYNC_LOCKS[project_uid] = lock
return lock
def _sync_dir_bidirectional_locked(project_uid: str, workspace, user: dict) -> dict:
# The user-triggered sync and the reconciler's periodic sync both call
# this, unsynchronized. Without this lock, two overlapping runs for the
@@ -652,13 +641,10 @@ def _sync_dir_bidirectional_locked(project_uid: str, workspace, user: dict) -> d
# nothing - an orphan on every race, forever. A non-blocking skip (never
# a blocking wait) is deliberate: this runs on an asyncio.to_thread
# worker, and a project mid-sync simply gets picked up on the next tick.
lock = _sync_lock_for(project_uid)
if not lock.acquire(blocking=False):
return dict(_SYNC_EMPTY_COUNTS)
try:
with project_sync_lock(project_uid) as acquired:
if not acquired:
return dict(_SYNC_EMPTY_COUNTS)
return project_files.sync_dir_bidirectional(project_uid, workspace, user)
finally:
lock.release()
async def sync_workspace(instance: dict, user: dict) -> dict:
+32
View File
@@ -1,5 +1,37 @@
# retoor <retoor@molodetz.nl>
import asyncio
import fcntl
import re
from contextlib import contextmanager
from devplacepy import config
NUMBERING_LOCK = asyncio.Lock()
SYNC_LOCK_PREFIX = "project-sync-"
SYNC_LOCK_SUFFIX = ".lock"
_UNSAFE_LOCK_CHARS = re.compile(r"[^A-Za-z0-9_-]")
def sync_lock_path(project_uid: str):
safe = _UNSAFE_LOCK_CHARS.sub("_", project_uid)
return config.LOCKS_DIR / f"{SYNC_LOCK_PREFIX}{safe}{SYNC_LOCK_SUFFIX}"
@contextmanager
def project_sync_lock(project_uid: str):
path = sync_lock_path(project_uid)
path.parent.mkdir(parents=True, exist_ok=True)
handle = open(path, "w")
try:
fcntl.flock(handle, fcntl.LOCK_EX | fcntl.LOCK_NB)
except OSError:
handle.close()
yield False
return
try:
yield True
finally:
fcntl.flock(handle, fcntl.LOCK_UN)
handle.close()
+6
View File
@@ -114,6 +114,10 @@ The upstream model `deepseek-v4-flash` (what `deepseek-chat` routes to; default
**`find_compaction_split` must accept any safe boundary, not only a `user`-role message (a second real incident of this same failure class).** `compact_messages` needs a split point where `messages[1:split]` (summarized away) and `messages[split:]` (kept verbatim) each stay internally self-contained - a tool result can never be separated from the assistant `tool_calls` message that produced it, or the provider rejects the request as malformed on the very next call. The original `find_compaction_split` enforced this by scanning backward from `len(messages) - keep_tail` for a `role == "user"` message and returning `1` (a **total no-op** - `compact_messages` then returns `messages` completely unchanged) if none was found before reaching index 1. That guard is correct for ordinary multi-turn chat, but a long single-turn agentic run (many consecutive `assistant` tool_calls + `tool` result pairs with no interleaved `user` message, e.g. a big scheduled task or a chat turn that just keeps calling tools) has **no `user`-role message anywhere in the scan range**, so both the proactive compaction (`context_size(messages) > context_compact_threshold`, checked every iteration) and the reactive overflow retry above silently did nothing at all, turn after turn, while `context_overflow_attempts` still climbed to `MAX_CONTEXT_OVERFLOW_RETRIES` and the loop still failed closed with the provider's raw 400 - "compaction" fired (visibly, as repeated `compact-overflow` trace events) but never actually shrank anything. The fix: track the closest safe fallback boundary (`role != "tool"`, i.e. `user` **or** a non-tool-calling point) seen during the same backward scan, and use it when no `user` message turns up - `assistant` is just as safe a split point as `user` since neither leaves an orphaned tool result on either side of the cut. Given the conversation always starts `[system, user, assistant, ...]`, this fallback is always found once `len(messages) >= keep_tail + 3` (the precondition `compact_messages` already checks before calling it), so the function can no longer degenerate to a permanent no-op. Regression-guarded by `tests/unit/services/devii/agentic/compaction.py` (`test_find_compaction_split_falls_back_to_a_non_tool_boundary_without_a_recent_user_message`, `test_find_compaction_split_never_lands_inside_a_tool_result_run`, `test_compact_messages_shrinks_a_tool_heavy_conversation_with_no_recent_user_message`) - each one fails against the pre-fix code with a synthetic tool-heavy, user-message-free conversation.
## Persistent big-result refs (summary + sha256, 10-day TTL)
Big tool results never travel as repeated full dumps. When a dispatched result exceeds `settings.max_response_chars`, `Dispatcher` persists it once through `BigRefStore` (`services/devii/bigrefs/`, owner-scoped over the session's `owned_db`, memory-only for guests/docs) and returns a small envelope `{ref_id: "mem:<hex12>", hash: "sha256:<hex>", summary, description, mime, bytes, total_chars, created_at, expires_at, preview}` with a `ref_read` hint, instead of the session-only `wrap_if_large` chunk path. The model pages slices with `ref_read` (`ref_id` required, optional `hash` verified, `offset`/`length` capped at 65536, default 4096). Every read re-verifies the sha256 and reports `not_found`/`expired`/`stale` instead of serving drifted bytes. Summaries are deterministic structural facts (chars, lines, opening text), never an extra LLM call. Rows expire after `BIGREF_TTL_DAYS` (10), are capped per owner (`BIGREF_MAX_PER_OWNER`, LRU), hard-deleted by `run_once` housekeeping, and never cross owner boundaries. Small results are untouched, so this is strictly an overflow path, not a behavior change.
## Multi-worker service-lock routing
Hubs are per-process, so `/devii/ws` is served **only** by the worker that holds the background-service lock (`service_manager.owns_lock()`, set in `main.py` startup); a non-owner worker `close(4013)` (an application code in the private 4000-4999 range, reliably delivered as the browser `CloseEvent.code`). `DeviiSocket.js` recognises 4013 as "wrong worker, not yet settled" and fast-retries in ~200ms **silently** (no "disconnected, reconnecting..." notice), so with 2 prod workers the client converges on the owner in a fraction of a second instead of bouncing every 1500ms. The visible "connected." notice is emitted on the first server frame (`onReady`), never on raw socket open, so an accepted-then-4013-closed handshake on the wrong worker is invisible. The disabled/no-service path keeps the standard `1013` (a real, user-visible disconnect). The cap stays correct regardless because it reads the DB.
@@ -259,6 +263,8 @@ Broker uses `present_plain` or emits a plain menu and waits; `parse_plain_reply`
Every non-docs turn appends `CA_IWP_SYSTEM_FRAGMENT` plus the live channel fragment from `_compose_system_prompt()`. Model rules: prefer `ui_prompt` when gated on; never invent HTML/CE tags; branch on `status` (submitted / cancelled / timeout / superseded / error).
The composed message ends with the `# CURRENT TIME` block (see Timezone awareness above), rounded to the hour, so the whole system prompt is byte-stable across turns within one hour. That stability is what lets a prefix-caching upstream keep serving a repeated emulated tool catalog from cache until the hour flips (see the gateway file's tool-emulation section).
### Tests
Unit coverage under `tests/unit/services/devii/interaction/` (capabilities, schema, markdown, parse, broker, controller) plus session tool-gating assertions and telegram callback emission. Mirror this layout for any extension.
@@ -208,6 +208,39 @@ GATEWAY_ACTIONS: tuple[Action, ...] = (
confirm(),
),
),
Action(
name="gateway_learned_list",
method="GET",
path="/admin/gateway/learned",
summary="List the request shapes the gateway learned automatically per provider and target model (admin only)",
description=(
"Returns JSON: every learned method (provider, target_model, the method label, its "
"thinking dialect and dropped keys, when it was learned) plus the resolve/exhausted/"
"healed counters. A method is learned when an upstream rejected the default request "
"shape with a parsable unrecognized-key 400 and a retry with another shape succeeded."
),
handler="http",
requires_admin=True,
read_only=True,
),
Action(
name="gateway_learned_reset",
method="POST",
path="/admin/gateway/learned/reset",
summary="Forget a learned request shape so the gateway re-learns it (admin only, confirmation required)",
description=(
"Deletes the learned method for one provider and target model; the next request starts "
"from the default shape again and re-resolves if the upstream still rejects it. Use "
"provider 'default' for the base upstream. 404 when nothing is learned for that route."
),
handler="http",
requires_admin=True,
params=(
body("provider", "Provider name, or 'default' for the base upstream."),
body("target_model", "The upstream (target) model name the method was learned for."),
confirm(),
),
),
Action(
name="gateway_quota_rule_delete",
method="DELETE",
@@ -61,6 +61,23 @@ PROFILE_ACTIONS: tuple[Action, ...] = (
),
),
),
Action(
name="mcp_regenerate_url",
method="POST",
path="/profile/mcp/regenerate",
summary="Issue a new MCP server URL and invalidate the current one",
description=(
"Returns the new MCP URL. Warning: this immediately invalidates any URL currently "
"used by connected harnesses, so confirm with the user before calling it."
),
params=(
body(
"confirm",
"Must be true, set only after the user has explicitly confirmed.",
required=True,
),
),
),
Action(
name="give_award",
method="POST",
@@ -63,7 +63,9 @@ UPLOAD_ACTIONS: tuple[Action, ...] = (
"returned uid in attachment_uids when you create_post, create_project, create_gist, "
"create_comment, create_issue, or send_message to attach it. The file type is taken from the "
"URL or its Content-Type; supply 'filename' (with an allowed extension) when the URL has no "
"usable name. Use this to attach an image or file straight from the internet."
"usable name. Use this to attach an image or file straight from the internet. This only "
"attaches what already exists: it never creates a picture (that is generate_image), and to "
"understand what a remote picture shows, describe it first with rsearch_describe_image."
),
params=(
body("url", "Public http(s) URL of the file to download and attach.", required=True),
@@ -82,7 +84,7 @@ UPLOAD_ACTIONS: tuple[Action, ...] = (
"Searches GIPHY and returns {query, results}. Each result carries id, title, preview (a small "
"still-animated rendition) and original (the full GIF). Pass a result's id to attach_gif to "
"attach it. Answers 503 when GIPHY is not configured by an administrator and 429 when you search "
"too fast."
"too fast. For an AI-created picture use generate_image instead of GIF search."
),
params=(
query("q", "Search keywords, 1-200 characters.", required=True),
@@ -121,14 +123,18 @@ UPLOAD_ACTIONS: tuple[Action, ...] = (
description=(
"The ONLY way to create a picture. Generates one image through the platform gateway's "
"default image model (never choose a model yourself, never call an image API with "
"http_request) and stores it as a real attachment, returning {uid, url, ...}. Pass the "
"returned uid in attachment_uids when you create_post, create_project, create_gist, "
"create_comment, create_issue, or send_message so the picture is actually delivered, and "
"show the user the url."
"http_request) and stores it as a real attachment named generated.png, returning "
"{uid, url, ...}. Pass the returned uid in attachment_uids when you create_post, "
"create_project, create_gist, create_comment, create_issue, or send_message so the picture "
"is actually delivered, and show the user the url. There is no server-side image editing, "
"upscaling, try-on, video, or avatar generation: to reuse an existing web image use "
"attach_url, for GIFs use search_gifs or trending_gifs with attach_gif, and to understand "
"a remote picture use rsearch_describe_image. A 502 means the upstream image backend "
"failed or is unconfigured; report it plainly and retry later rather than switching tools."
),
params=(
body("prompt", "Description of the image to generate.", required=True),
body("size", "Optional WIDTHxHEIGHT, e.g. 1024x1024 (the default)."),
body("size", "Optional WIDTHxHEIGHT, e.g. 1024x1024 (the default when omitted)."),
),
),
Action(
@@ -131,6 +131,23 @@ CUSTOMIZATION_ACTIONS: tuple[Action, ...] = (
),
),
),
Action(
name="enter_to_submit_set",
method="LOCAL",
path="",
summary="Turn Enter to send on or off for comments and direct messages",
description=(
"When enabled, Enter posts or sends and Shift+Enter adds a new line in comments and "
"direct messages. Long editors keep Enter for new lines and use Ctrl+Enter to submit. "
"Mirrors the Keyboard toggle on the user's profile page."
),
handler="customization",
requires_auth=True,
params=(
arg("enabled", "true for Enter to send, false for Enter adds a new line.", required=True, kind="boolean"),
arg("confirm", "Must be true after the user has confirmed the change.", required=True, kind="boolean"),
),
),
Action(
name="customize_set_enabled",
method="LOCAL",
@@ -60,6 +60,7 @@ CONFIRM_REQUIRED = {
"delete_project",
"delete_media",
"regenerate_api_key",
"mcp_regenerate_url",
"regenerate_avatar",
"delete_post",
"delete_comment",
@@ -76,10 +77,14 @@ CONFIRM_REQUIRED = {
"backup_delete",
"backup_schedule_delete",
"notification_reset",
"enter_to_submit_set",
"notification_grouping_set",
"notification_throttle_set",
"gateway_provider_delete",
"gateway_model_delete",
"gateway_quota_rule_delete",
"gateway_quota_reset",
"gateway_learned_reset",
"email_account_delete",
"email_delete_message",
"game_prestige",
@@ -196,6 +201,11 @@ def confirmation_error(name: str, arguments: dict[str, Any]) -> ToolInputError |
"behaves, and they apply on the next workspace start. Show the user the exact "
"values you are about to set, then call again with confirm=true."
)
if name in ("enter_to_submit_set", "notification_grouping_set", "notification_throttle_set"):
return ToolInputError(
"This changes how the user's keyboard or notifications behave everywhere. Ask the user "
"to confirm, then call again with confirm=true."
)
if name == "notification_reset":
return ToolInputError(
"Resetting clears every notification preference and restores the platform defaults; it "
@@ -237,6 +247,12 @@ def confirmation_error(name: str, arguments: dict[str, Any]) -> ToolInputError |
"scripts or services that use it. Ask the user to confirm explicitly, then call again "
"with confirm=true."
)
if name == "mcp_regenerate_url":
return ToolInputError(
"Regenerating your MCP URL immediately invalidates the current URL, which disconnects "
"every connected harness. Ask the user to confirm explicitly, then call again "
"with confirm=true."
)
if name == "delete_post":
slug = str(arguments.get("slug", arguments.get("post_slug", ""))).strip()
return ToolInputError(
@@ -300,7 +316,11 @@ def confirmation_error(name: str, arguments: dict[str, Any]) -> ToolInputError |
"get explicit confirmation, then call again with confirm=true."
)
if name == "delete_attachment":
uid = str(arguments.get("uid", "")).strip() or "(unspecified)"
uid = (
str(arguments.get("attachment_uid", "")).strip()
or str(arguments.get("uid", "")).strip()
or "(unspecified)"
)
return ToolInputError(
f"Deleting attachment '{uid}' is permanent and removes it from its parent. "
"Ask the user to confirm explicitly, then call again with confirm=true."
@@ -387,6 +407,7 @@ class Dispatcher:
behavior: Any = None,
interaction: Any = None,
agents: Any = None,
bigrefs: Any = None,
) -> None:
self._actions = catalog.by_name()
self._client = client
@@ -428,6 +449,7 @@ class Dispatcher:
self._telegram = TelegramSendController(owner_kind, owner_id)
self._virtual_tools = virtual_tools
self._bigrefs = bigrefs
self._behavior = behavior
self._interaction = interaction
self._agents = agents
@@ -458,6 +480,20 @@ class Dispatcher:
action = self._actions.get(name)
return bool(action and action.is_read_only)
def _store_big_result(self, name: str, result: str) -> str | None:
try:
ref = self._bigrefs.store_result(result, description=f"Large {name} result")
except Exception: # noqa: BLE001 - fall back to the session chunk path
logger.exception("Bigref store failed for %s", name)
return None
envelope = dict(ref)
envelope["hint"] = (
f"Result stored by reference to save context. Call ref_read with "
f"ref_id='{ref['ref_id']}' and an offset to read slices; summary and "
f"preview above are usually enough."
)
return json.dumps(envelope, ensure_ascii=False)
async def dispatch(self, name: str, arguments: dict[str, Any]) -> str:
action = self._actions.get(name)
if action is None:
@@ -514,6 +550,12 @@ class Dispatcher:
self._audit_mechanic(action, arguments)
if action.handler == "chunks":
return result
if action.handler == "bigrefs":
return result
if self._bigrefs is not None and len(result) > self._settings.max_response_chars:
ref = self._store_big_result(name, result)
if ref is not None:
return ref
return wrap_if_large(
result, self._settings.max_response_chars, resource_key
)
@@ -604,6 +646,11 @@ class Dispatcher:
if action.handler == "chunks":
return await self._chunks.dispatch(action.name, arguments)
if action.handler == "bigrefs":
if self._bigrefs is None:
return error_result(ToolInputError("Stored refs are not available in this session."))
return await self._bigrefs.dispatch(action.name, arguments)
if action.handler == "rsearch":
return await self._rsearch.dispatch(action.name, arguments)
@@ -58,6 +58,32 @@ NOTIFICATION_ACTIONS: tuple[Action, ...] = (
),
),
),
Action(
name="notification_grouping_set",
method="LOCAL",
path="",
summary="Turn grouped notifications on or off",
description="When enabled, similar notifications share one card and the badge counts groups. When disabled, every notification gets its own card and the badge counts every event. Mirrors the profile notifications toggle.",
handler="notification",
requires_auth=True,
params=(
arg("enabled", "true to group similar notifications, false to show every event.", required=True, kind="boolean"),
arg("confirm", "Must be true after the user has confirmed the change.", required=True, kind="boolean"),
),
),
Action(
name="notification_throttle_set",
method="LOCAL",
path="",
summary="Turn throttling of repeat notification alerts on or off",
description="When enabled, repeated similar events send at most one push, Telegram message and toast per 5 minutes. In-app notifications are never throttled. Mirrors the profile notifications toggle.",
handler="notification",
requires_auth=True,
params=(
arg("enabled", "true to throttle repeat alerts, false to alert on every event.", required=True, kind="boolean"),
arg("confirm", "Must be true after the user has confirmed the change.", required=True, kind="boolean"),
),
),
Action(
name="notification_reset",
method="LOCAL",
@@ -0,0 +1,49 @@
# retoor <retoor@molodetz.nl>
from __future__ import annotations
from .spec import Action, Param
REF_ACTIONS: tuple[Action, ...] = (
Action(
name="ref_read",
method="LOCAL",
path="",
summary="Read a slice of a previously stored big tool result",
description=(
"When a tool result is too big it is stored once and the tool returns a "
"reference envelope with ref_id, sha256 hash, summary, and preview instead of "
"the full content. Call ref_read with that ref_id and an offset to page through "
"the rest. Stored refs expire after 10 days and are private to your account. "
"Never guess a ref_id; only use one returned in this conversation."
),
handler="bigrefs",
requires_auth=False,
read_only=True,
params=(
Param(
name="ref_id",
location="body",
description="The ref_id from a stored-result envelope (mem:...).",
required=True,
),
Param(
name="hash",
location="body",
description="Optional sha256:<64 hex> to verify against the stored hash.",
),
Param(
name="offset",
location="body",
description="Character offset to read from (use next_offset from the prior part).",
type="integer",
),
Param(
name="length",
location="body",
description="Characters to return, 1-65536, default 4096.",
type="integer",
),
),
),
)
+19 -5
View File
@@ -44,6 +44,9 @@ SYSTEM_PROMPT = (
"call read_more with that chunk_id and offset to page through the rest until remaining_chars "
"is 0 whenever you need the full content. Use read_more to continue - never re-run the "
"original tool to get more of the same resource; its full content is already cached. "
"Very big results are instead stored by reference and return ref_id, hash, summary, "
"and preview; call ref_read with that ref_id and an offset to page them, and never "
"re-run the original tool either. "
"Platform calls return structured JSON: reads give objects with fields like uid, slug, "
"next_cursor, and nested authors/comments; write actions return {ok, redirect, data} where "
"data has the created resource's uid/slug/url. Always reuse those exact slugs/uids/urls for "
@@ -175,11 +178,22 @@ SYSTEM_PROMPT = (
"user-defined tools only re-run you and cannot perform network I/O themselves, so a tool that calls "
"the API by re-invoking you will recurse and fail the self-evaluation depth limit. Private and "
"loopback addresses are refused.\n\n"
"GENERATING IMAGES\n"
"To make a picture, call generate_image with a prompt. It uses the platform's configured image "
"model and returns an attachment uid and url. Never pick an image model yourself and never call an "
"image API through http_request. To deliver the picture, pass the uid in attachment_uids when you "
"create a post, project, gist, comment, issue or direct message, and show the url to the user.\n\n"
"PICTURES\n"
"Pictures come from four tools, each with one job. generate_image CREATES a picture from a text "
"prompt through the platform gateway's default image model and stores it as a real attachment "
"named generated.png, returning {uid, url}. attach_url ATTACHES a file that already exists at a "
"public URL (never creates anything). search_gifs and trending_gifs find GIFs and attach_gif stores "
"one as an attachment. rsearch_describe_image DESCRIBES what a public image URL shows. Never refuse "
"a picture request with a made-up policy: there is no content policy beyond the platform's own "
"upstream result, so always call the matching tool. Never pick an image model yourself and never "
"call an image API through http_request. Honest limits: the platform supports text-to-image "
"generation only; there is no server-side image editing, upscaling, try-on, video generation, or "
"avatar rendering, so say so plainly when asked and offer the closest real option (generate a new "
"picture, attach an existing URL, or fetch a GIF). A 502 from generate_image means the upstream "
"image backend failed or is unconfigured: report it plainly and offer to retry later. To deliver a "
"picture, pass its uid in attachment_uids when you create a post, project, gist, comment, issue or "
"direct message, and always show the url to the user. The size param is WIDTHxHEIGHT "
"(1024x1024 when omitted).\n\n"
"ATTACHING FILES FROM THE INTERNET\n"
"To attach an image or file that lives at a public URL to something you create (a post, project, "
"gist, comment, issue report, or direct message), call attach_url with that URL. It downloads the "
@@ -0,0 +1,27 @@
# retoor <retoor@molodetz.nl>
from __future__ import annotations
from .controller import BigRefController
from .store import (
BIGREF_MAX_BYTES,
BIGREF_MAX_PER_OWNER,
BIGREF_PREVIEW_CHARS,
BIGREF_SLICE_DEFAULT,
BIGREF_SLICE_MAX,
BIGREF_TTL_DAYS,
BigRefStore,
prune_expired,
)
__all__ = [
"BIGREF_MAX_BYTES",
"BIGREF_MAX_PER_OWNER",
"BIGREF_PREVIEW_CHARS",
"BIGREF_SLICE_DEFAULT",
"BIGREF_SLICE_MAX",
"BIGREF_TTL_DAYS",
"BigRefController",
"BigRefStore",
"prune_expired",
]
@@ -0,0 +1,79 @@
# retoor <retoor@molodetz.nl>
from __future__ import annotations
import json
import re
from typing import Any
from ..errors import ToolInputError
from .store import BIGREF_SLICE_DEFAULT, BIGREF_SLICE_MAX, BigRefStore
_HASH_RE = re.compile(r"^sha256:[0-9a-f]{64}$")
class BigRefController:
def __init__(self, store: BigRefStore) -> None:
self._store = store
def store_result(self, text: str, description: str = "", mime: str = "text/plain") -> dict[str, Any]:
ref = self._store.put(text, description=description, mime=mime)
if ref is None:
raise ToolInputError("Content is empty or exceeds the big-ref size cap.")
return ref
async def dispatch(self, name: str, arguments: dict[str, Any]) -> str:
if name != "ref_read":
raise ToolInputError(f"Unknown bigref tool: {name}")
ref_id = str(arguments.get("ref_id", "")).strip()
if not ref_id:
raise ToolInputError("ref_read requires a ref_id.")
claimed = str(arguments.get("hash", "")).strip()
if claimed and not _HASH_RE.match(claimed):
raise ToolInputError("hash must look like sha256:<64 hex>.")
try:
offset = max(0, int(arguments.get("offset", 0) or 0))
except (TypeError, ValueError):
raise ToolInputError("offset must be a non-negative integer.") from None
try:
length = int(arguments.get("length", BIGREF_SLICE_DEFAULT) or BIGREF_SLICE_DEFAULT)
except (TypeError, ValueError):
raise ToolInputError("length must be a positive integer.") from None
length = max(1, min(length, BIGREF_SLICE_MAX))
result = self._store.read(ref_id, offset, length)
status = result.get("status")
if status == "not_found":
return json.dumps(
{
"status": "not_found",
"message": (
f"No stored content for ref_id '{ref_id}'. It may have expired; "
"re-run the original tool to get a fresh ref."
),
}
)
if status == "expired":
return json.dumps(
{
"status": "expired",
"message": f"Stored content for ref_id '{ref_id}' expired after 10 days.",
}
)
if status == "stale":
return json.dumps(
{
"status": "stale",
"message": (
f"Stored content for ref_id '{ref_id}' failed hash verification. "
"Do not use it; re-run the original tool."
),
}
)
if claimed and claimed != result.get("hash"):
return json.dumps(
{
"status": "stale",
"message": "Hash mismatch: the stored content changed since the ref was issued.",
}
)
return json.dumps(result, ensure_ascii=False)
+186
View File
@@ -0,0 +1,186 @@
# retoor <retoor@molodetz.nl>
from __future__ import annotations
import hashlib
import logging
import uuid
from datetime import datetime, timedelta, timezone
from typing import Any, Optional
logger = logging.getLogger("devii.bigrefs")
TABLE = "devii_big_refs"
BIGREF_TTL_DAYS = 10
BIGREF_MAX_PER_OWNER = 100
BIGREF_MAX_BYTES = 8_000_000
BIGREF_SLICE_DEFAULT = 4096
BIGREF_SLICE_MAX = 65536
BIGREF_PREVIEW_CHARS = 2000
COLUMNS = (
("uid", ""),
("owner_kind", ""),
("owner_id", ""),
("ref_id", ""),
("hash", ""),
("summary", ""),
("description", ""),
("mime", ""),
("bytes", 0),
("content", ""),
("created_at", ""),
("expires_at", ""),
)
def _now_iso() -> str:
return datetime.now(timezone.utc).isoformat()
def digest_of(text: str) -> str:
return hashlib.sha256(text.encode("utf-8")).hexdigest()
def summarize(text: str) -> str:
chars = len(text)
lines = text.count("\n") + 1 if text else 0
head = " ".join(text.split())[:160]
return f"{chars} chars in {lines} lines. Starts with: {head}" if head else f"{chars} chars in {lines} lines"
class BigRefStore:
def __init__(self, db: Any, owner_kind: str, owner_id: str) -> None:
self._db = db
self._owner_kind = owner_kind
self._owner_id = owner_id
self._ensure_schema()
@property
def _table(self) -> Any:
return self._db[TABLE]
def _ensure_schema(self) -> None:
table = self._db[TABLE]
for column, example in COLUMNS:
if table.has_column(column):
continue
try:
table.create_column_by_example(column, example)
except Exception: # noqa: BLE001 - concurrent DDL from another worker
logger.debug("Column %s was created by another process", column)
try:
table.create_index(["owner_kind", "owner_id"])
except Exception: # noqa: BLE001 - index already exists
logger.debug("Bigref owner index exists")
try:
table.create_index(["hash"])
except Exception: # noqa: BLE001 - index already exists
logger.debug("Bigref hash index exists")
@property
def _scope(self) -> dict[str, str]:
return {"owner_kind": self._owner_kind, "owner_id": self._owner_id}
def put(self, text: str, description: str = "", mime: str = "text/plain") -> Optional[dict[str, Any]]:
if not isinstance(text, str) or not text:
return None
size = len(text.encode("utf-8"))
if size > BIGREF_MAX_BYTES:
return None
hexdigest = digest_of(text)
ref_id = "mem:" + hexdigest[:12]
full_hash = "sha256:" + hexdigest
now = _now_iso()
expires = (datetime.now(timezone.utc) + timedelta(days=BIGREF_TTL_DAYS)).isoformat()
existing = self._table.find_one(hash=full_hash, **self._scope)
if existing is not None:
if (existing.get("expires_at") or "") >= now and existing.get("content") == text:
self._table.update({"id": existing["id"], "expires_at": expires}, ["id"])
return self._envelope(existing, text, now, expires)
self._table.delete(id=existing["id"])
self._enforce_cap()
row = {
"uid": uuid.uuid4().hex,
"owner_kind": self._owner_kind,
"owner_id": self._owner_id,
"ref_id": ref_id,
"hash": full_hash,
"summary": summarize(text),
"description": description or "Large tool result stored by reference",
"mime": mime,
"bytes": size,
"content": text,
"created_at": now,
"expires_at": expires,
}
self._table.insert(row)
return self._envelope(row, text, now, expires)
def _envelope(self, row: dict[str, Any], text: str, now: str, expires: str) -> dict[str, Any]:
return {
"stored": True,
"ref_id": row["ref_id"],
"hash": row["hash"],
"summary": row["summary"],
"description": row["description"],
"mime": row["mime"],
"bytes": row["bytes"],
"total_chars": len(text),
"created_at": row.get("created_at") or now,
"expires_at": row.get("expires_at") or expires,
"preview": text[:BIGREF_PREVIEW_CHARS],
}
def _enforce_cap(self) -> None:
rows = sorted(
self._table.find(**self._scope),
key=lambda row: row.get("created_at") or "",
)
overflow = len(rows) - BIGREF_MAX_PER_OWNER + 1
for row in rows[: max(0, overflow)]:
self._table.delete(id=row["id"])
def read(self, ref_id: str, offset: int = 0, length: int = BIGREF_SLICE_DEFAULT) -> dict[str, Any]:
key = (ref_id or "").strip()
if not key.startswith("mem:"):
return {"status": "not_found"}
row = self._table.find_one(ref_id=key, **self._scope)
if row is None:
return {"status": "not_found"}
if (row.get("expires_at") or "") < _now_iso():
self._table.delete(id=row["id"])
return {"status": "expired"}
content = row.get("content") or ""
if digest_of(content) != (row.get("hash") or "").replace("sha256:", "", 1):
return {"status": "stale"}
total = len(content)
start = max(0, offset)
stop = min(total, start + max(1, min(length, BIGREF_SLICE_MAX)))
piece = content[start:stop]
has_more = stop < total
return {
"status": "success",
"ref_id": key,
"hash": row.get("hash"),
"offset": start,
"shown_chars": len(piece),
"total_chars": total,
"remaining_chars": total - stop,
"next_offset": stop if has_more else None,
"has_more": has_more,
"content": piece,
}
def prune_expired(db: Any, now_iso: Optional[str] = None) -> int:
if TABLE not in db.tables:
return 0
cutoff = now_iso or _now_iso()
rows = list(db[TABLE].find(expires_at={"<": cutoff}))
for row in rows:
db[TABLE].delete(id=row["id"])
if rows:
logger.info("Pruned %d expired big ref(s)", len(rows))
return len(rows)
+4
View File
@@ -166,6 +166,9 @@ async def run(settings: Settings, prompt: Optional[str] = None) -> None:
cost_tracker = CostTracker()
chunk_store = ChunkStore()
agentic = AgenticController(lessons, settings)
from .bigrefs.controller import BigRefController
from .bigrefs.store import BigRefStore
dispatcher = Dispatcher(
CATALOG,
client,
@@ -174,6 +177,7 @@ async def run(settings: Settings, prompt: Optional[str] = None) -> None:
agentic,
is_admin=True,
is_primary_admin=True,
bigrefs=BigRefController(BigRefStore(store.db, owner_kind, owner_id)),
)
from .tool_prefs import filter_disabled
@@ -15,6 +15,7 @@ from devplacepy.database import (
list_custom_overrides,
set_custom_override,
set_customization_pref,
set_enter_to_submit,
)
from devplacepy.services.devii.errors import ToolInputError
@@ -41,6 +42,8 @@ class CustomizationController:
return self._reset(arguments)
if name == "customize_set_enabled":
return self._set_enabled(arguments)
if name == "enter_to_submit_set":
return self._set_enter_to_submit(arguments)
raise ToolInputError(f"Unknown customization tool: {name}")
def _scope(self, arguments: dict[str, Any]) -> str:
@@ -123,6 +126,13 @@ class CustomizationController:
ensure_ascii=False,
)
def _set_enter_to_submit(self, arguments: dict[str, Any]) -> str:
if self._owner_kind != "user":
raise ToolInputError("Enter to send is only available for signed-in users.")
enabled = self._enabled(arguments)
set_enter_to_submit(self._owner_id, enabled)
return json.dumps({"status": "success", "enter_to_submit": enabled}, ensure_ascii=False)
def _category(self, arguments: dict[str, Any]) -> str:
category = str(arguments.get("category", "")).strip().lower()
if category not in CUSTOMIZATION_PREF_COLUMNS:
@@ -11,6 +11,8 @@ from devplacepy.database import (
get_notification_prefs,
reset_notification_prefs,
set_notification_pref,
set_notification_grouping_enabled,
set_notification_throttle_enabled,
)
from devplacepy.services.devii.errors import ToolInputError
@@ -29,6 +31,10 @@ class NotificationController:
return self._set(arguments)
if name == "notification_reset":
return self._reset()
if name == "notification_grouping_set":
return self._set_display(arguments, "grouping")
if name == "notification_throttle_set":
return self._set_display(arguments, "throttle")
raise ToolInputError(f"Unknown notification tool: {name}")
def _require_user(self) -> None:
@@ -82,6 +88,15 @@ class NotificationController:
ensure_ascii=False,
)
def _set_display(self, arguments: dict[str, Any], kind: str) -> str:
self._require_user()
enabled = self._value(arguments) if "enabled" not in arguments else self._value({**arguments, "value": arguments.get("enabled")})
if kind == "grouping":
set_notification_grouping_enabled(self._owner_id, enabled)
else:
set_notification_throttle_enabled(self._owner_id, enabled)
return json.dumps({"status": "success", kind: enabled}, ensure_ascii=False)
def _reset(self) -> str:
self._require_user()
removed = reset_notification_prefs(self._owner_id)
+4
View File
@@ -16,6 +16,7 @@ from .actions.docs_actions import DOCS_ACTIONS
from .actions.email_actions import EMAIL_ACTIONS
from .actions.fetch_actions import FETCH_ACTIONS
from .actions.notification_actions import NOTIFICATION_ACTIONS
from .actions.ref_actions import REF_ACTIONS
from .actions.rsearch_actions import RSEARCH_ACTIONS
from .actions.spec import Action, Catalog
from .actions.telegram_actions import TELEGRAM_ACTIONS
@@ -36,6 +37,7 @@ GROUPS: dict[str, tuple[Action, ...]] = {
"docs": DOCS_ACTIONS,
"cost": COST_ACTIONS,
"chunks": CHUNK_ACTIONS,
"bigrefs": REF_ACTIONS,
"rsearch": RSEARCH_ACTIONS,
"container": CONTAINER_ACTIONS,
"workspace": WORKSPACE_ACTIONS,
@@ -87,6 +89,7 @@ GROUP_LABELS: dict[str, str] = {
"docs": "Docs Search",
"cost": "Usage and Cost",
"chunks": "Large Result Paging",
"bigrefs": "Stored Big Results (10-day refs)",
"rsearch": "External Web Search",
"container": "Containers",
"workspace": "Workspaces",
@@ -112,6 +115,7 @@ CATALOG = Catalog(
+ DOCS_ACTIONS
+ COST_ACTIONS
+ CHUNK_ACTIONS
+ REF_ACTIONS
+ RSEARCH_ACTIONS
+ CONTAINER_ACTIONS
+ WORKSPACE_ACTIONS
+13 -2
View File
@@ -487,11 +487,12 @@ class DeviiService(BaseService):
pruned = hub.ledger.prune(48)
removed = await hub.gc_idle()
lessons_pruned = self._prune_old_lessons()
if pruned or removed or idle or lessons_pruned or runs_pruned or agents_pruned:
bigrefs_pruned = self._prune_bigrefs()
if pruned or removed or idle or lessons_pruned or runs_pruned or agents_pruned or bigrefs_pruned:
self.log(
f"Housekeeping: disabled {idle} idle-owner task(s), pruned {runs_pruned} task-run "
f"rows, pruned {agents_pruned} agent rows, pruned {pruned} ledger rows, pruned "
f"{lessons_pruned} lessons, closed {removed} idle sessions"
f"{lessons_pruned} lessons, pruned {bigrefs_pruned} big refs, closed {removed} idle sessions"
)
def _prune_task_runs(self) -> int:
@@ -532,6 +533,16 @@ class DeviiService(BaseService):
logger.exception("Devii lessons housekeeping failed")
return 0
def _prune_bigrefs(self) -> int:
try:
from devplacepy.database import db
from .bigrefs.store import prune_expired
return prune_expired(db)
except Exception:
logger.exception("Devii bigref housekeeping failed")
return 0
def scheduler(self) -> GlobalScheduler:
if self._scheduler is None:
from devplacepy.database import db
@@ -109,6 +109,11 @@ class DeviiSession:
)
self.store = task_store
self.task_controller = TaskController(self.store)
from ..bigrefs.controller import BigRefController
from ..bigrefs.store import BigRefStore
self.bigref_store = BigRefStore(self.store.db, owner_kind, owner_id)
self.bigrefs = BigRefController(self.bigref_store)
self.agentic = AgenticController(lessons, settings)
self.cost = CostTracker(pricing=pricing)
self.chunks = ChunkStore()
@@ -144,6 +149,7 @@ class DeviiSession:
behavior=self.behavior,
interaction=self.interaction,
agents=self.agent_controller,
bigrefs=self.bigrefs,
)
self.tools = self._builtin_tools()
self._system_prompt = (

Some files were not shown because too many files have changed in this diff Show More