Slim root CLAUDE.md to global-only rules, move subsystem detail to nested files
DevPlace CI / test (push) Failing after 1h1m39s

This commit is contained in:
2026-11-08 20:33:09 +01:00
parent 078d0657ff
commit 33eb090e27
12 changed files with 107 additions and 171 deletions
+8
View File
@@ -265,3 +265,11 @@ Posts, gists, projects and news carry one status from `VISIBILITY_VALUES`: `publ
- **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. Delivery throttling (item 5) reuses the same key.
+18
View File
@@ -382,3 +382,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.
+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`.
+1 -1
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)
+4
View File
@@ -139,3 +139,7 @@ The client side is `static/js/TermsGate.js` (`app.termsGate`); see `devplacepy/s
- A new filter category: add rules to `rules.py` and the reason key to `REPORT_REASONS`; a unit test asserts every rule's category is a real reason.
- A new consent: add it to `CONSENT_KINDS` and enforce it at one choke point, never at N call sites.
- Never add a second removal path, a second suspension check, or a second consent gate.
## Account deletion CLI
`devplace accounts pending` lists deleted accounts awaiting purge; `devplace accounts prune` (with `--dry-run` to preview) permanently purges accounts past the deletion grace window.
+4
View File
@@ -45,6 +45,10 @@ Per article up to `IMG_PER_ARTICLE=5` candidate image URLs (from `_get_article_i
After the per-article loop, `_apply_landing_selection` queries recent (`<= LANDING_RECENCY_DAYS`) rows that are published + featured + `has_unique_image` + NOT `landing_locked`, sorts by `(-grade, -synced_at)`, sets `show_on_landing=1` for the top `LANDING_MAX` with `grade >= LANDING_MIN_SCORE` and `show_on_landing=0` for the rest of THAT service-managed set (self-rotating). When an admin manually toggles Featured or Landing (`routers/admin/news.py`), the matching `featured_locked`/`landing_locked` is set to 1 so the service stops auto-managing that row; updates of a locked Featured row never overwrite `featured`. New `news` columns: `ai_grade`, `featured`, `has_unique_image`, `image_url`, `featured_locked`, `landing_locked`, `author`, `article_published` (all added to the `init_db` ensure-block - the stale-schema rule). Audit events `news.service.ingest`/`news.service.publish`/`news.service.draft`/`news.service.reject`/`news.service.landing` (`record_system`, category `news`). New dep: `imagehash` (`Pillow` already present).
## CLI
`devplace news clear` deletes every news row; `devplace news sanitize` strips HTML from news descriptions/content.
## Editorial labels are admin-only on the public surfaces
The `&#x2605; Featured` badge and the `Grade {{ grade }}` chip are internal editorial signals, so on every PUBLIC news surface - the `/news` listing (`news.html`), the article page (`news_detail.html`), and the landing/home Developer News cards (`landing.html`) - both are wrapped in `{% if is_admin(user) %}`. Members and guests never see them; administrators still see them everywhere (including the public pages) and the admin **Manage News** area (`admin_news.html`) is unchanged, where the grade and featured state are the editorial controls. The article's source name and timestamp stay visible to everyone. Gating only the rendered labels does not touch the stored `grade`/`featured` columns, the grading/landing logic, or ordering (`/news` is still ordered by effective `grade`).
+1 -1
View File
@@ -126,7 +126,7 @@ and the post page is the surface. `serialize_war` is the single card/JSON shape
## Verification
The feature is a spendable resource + bounded state machine + multi-path read-then-write, so the
root CLAUDE.md four-layer procedure applies to any change here: property checks on `rules.py`
four-layer procedure in `tests/CLAUDE.md` ("Rigorous correctness verification") applies to any change here: property checks on `rules.py`
across the full domain, stateful fuzz asserting `war.hp_x == SUM(fighters.hp_x)` and
`coins >= 0` after every action, and REAL multi-process races (concurrent fight = exactly one
lands and exactly one fee; two wars vs 1.5x the fee = exactly one lands; concurrent resolve =
+9 -3
View File
@@ -20,9 +20,9 @@ Self-contained, presentational UI is built as custom elements with the `dp-` pre
**Prompt seeding on the shared Devii opener (`data-devii-prompt`).** `DeviiTerminal.bindTriggers` binds every `[data-devii-open]` element; it now reads `trigger.dataset.deviiPrompt` and passes it to `DeviiTerminal.open(prompt)`, which calls `this.element.open()` and then `devii-terminal.prefill(text)` (sets `this.input.value`, moves the caret to the end, focuses). **It never auto-sends** - the member reads the request and presses Enter, keeping the assistant's first action explicitly user-initiated. This is a platform-wide capability available to any page, not a quiz-only shim: add `data-devii-prompt="..."` beside `data-devii-open` and the terminal opens pre-filled.
`dp-chat` (`AppChat.js`) is the Slack-like DM chat widget that fully replaced the old page-controller trio `MessagesLayout.js`/`MessagesSocket.js`/`MessageSearch.js` (deleted) and `static/css/messages.css` (superseded by `static/css/chat.css`) on `/messages`. Unlike every other component here, it does NOT build its DOM from scratch on `connectedCallback` when server-rendered light-DOM children already exist (`mode="page"`) - it **adopts** the existing `.messages-list`/`.messages-main`/`.messages-thread`/`.message-bubble` markup `templates/messages.html` still renders (so no-JS and crawler fallback both keep working) and only builds a from-scratch skeleton when none is present (`mode="embed"`, a standalone `<dp-chat mode="embed" self-uid="..." with-uid="..." send-url="..." ws-url="...">` usable outside `/messages`). It owns its own `ChatSocket` instance, the conversation search dropdown (absorbed from the old `MessageSearch.js`, still built on the shared `ListNav` utility), consecutive-message grouping (`chat/MessageGrouping.js`), a working optimistic send with `.pending`/`.failed` (tap-to-retry) bubble states, and an opt-in (`ai-indicator` attribute) "Adjusted by AI" caption shown when a reconciled echo's `ai_processed` frame flag is true and the content changed from what was locally typed - never a diff/revert UI, the backend keeps no pre-correction copy to diff against. Presence needs no component code at all: the adopted markup keeps its `data-presence-uid` attributes, so the page-global `PresenceManager` (below) already drives it, and the conversation list it builds live uses the shared `Avatar.badgeElement(user)` rather than hand-rolled dot markup. In `mode="embed"`, where no page-global instance may exist, it constructs a root-scoped `PresenceManager` instead of re-implementing presence - `dp-chat` owns no presence logic of its own. The message body itself keeps rendering through `<dp-content>` (see "CLIENT-only now" below) - the redesign only removed the historical `no-copy` attribute on message bubbles so `dp-content`'s own existing `.content-copy-btn` doubles as the hover/focus-reveal action toolbar's Copy button (§6.3 of the design doc it was built from), instead of a second copy mechanism being hand-rolled.
`dp-chat` (`AppChat.js`) is the Slack-like DM chat widget that fully replaced the old page-controller trio `MessagesLayout.js`/`MessagesSocket.js`/`MessageSearch.js` (deleted) and `static/css/messages.css` (superseded by `static/css/chat.css`) on `/messages`. Unlike every other component here, it does NOT build its DOM from scratch on `connectedCallback` when server-rendered light-DOM children already exist (`mode="page"`) - it **adopts** the existing `.messages-list`/`.messages-main`/`.messages-thread`/`.message-bubble` markup `templates/messages.html` still renders (so no-JS and crawler fallback both keep working) and only builds a from-scratch skeleton when none is present (`mode="embed"`, a standalone `<dp-chat mode="embed" self-uid="..." with-uid="..." send-url="..." ws-url="...">` usable outside `/messages`). In `page`/`embed` mode it owns its own `ChatSocket` instance (`window` mode subscribes through the dock hub, see `dp-chat-dock` below). It owns the conversation search dropdown (absorbed from the old `MessageSearch.js`, still built on the shared `ListNav` utility), consecutive-message grouping (`chat/MessageGrouping.js`), a working optimistic send with `.pending`/`.failed` (tap-to-retry) bubble states, and an opt-in (`ai-indicator` attribute) "Adjusted by AI" caption shown when a reconciled echo's `ai_processed` frame flag is true and the content changed from what was locally typed - never a diff/revert UI, the backend keeps no pre-correction copy to diff against. Presence needs no component code at all: the adopted markup keeps its `data-presence-uid` attributes, so the page-global `PresenceManager` (below) already drives it, and the conversation list it builds live uses the shared `Avatar.badgeElement(user)` rather than hand-rolled dot markup. In `mode="embed"`, where no page-global instance may exist, it constructs a root-scoped `PresenceManager` instead of re-implementing presence - `dp-chat` owns no presence logic of its own. The message body itself keeps rendering through `<dp-content>` (see "CLIENT-only now" below) - the redesign only removed the historical `no-copy` attribute on message bubbles so `dp-content`'s own existing `.content-copy-btn` doubles as the hover/focus-reveal action toolbar's Copy button (§6.3 of the design doc it was built from), instead of a second copy mechanism being hand-rolled.
`dp-chat-dock` (`AppChatDock.js`, `app.chatDock`) is the Facebook-style docked chat, server-rendered once in `base.html` (block `chat_dock`, members only; `messages.html` empties the block so `/messages` has no dock). It builds the **Chats panel** (opened by any `[data-chat-panel-toggle]`, the topnav Messages icon; people search via `ListNav`, recent conversations from `/messages/conversations`, a New message compose window) and a bottom-right **tray** of chat windows plus minimized avatar heads. Each window is a plain `dp-chat` with `mode="window"`, so every chat behaviour (optimistic send, reconcile, AI frames, typing, receipts, delete, report, attachments, older history) is the one `AppChat` implementation. Rules that keep it correct: window `dp-chat` elements are **never moved in the DOM** (moving a custom element runs `disconnectedCallback`, which closes its socket channel, and the `_built` guard skips the rebuild), so windows are appended in creation order and removed, never reordered; a minimized window is destroyed and re-created on expand, which reloads its history and marks it read, so a head never marks anything read; open/minimized state lives in `sessionStorage` (per tab, the `ScrollMemory` precedent) under `devplace.chat-dock.<uid>`; at the 768px mobile breakpoint the dock renders nothing and every trigger falls through to its `href` (the full `/messages` page). Any element with `data-chat-open="<uid>"` (plus `data-chat-username`/`data-chat-avatar-seed`, emitted by the `_chat_open_attrs.html` partial) opens a window on click: the profile Send Message button and the `/notifications` card link of a `message` notification use it, and `LiveNotifications` routes a `message` toast's click through `app.chatDock.open()` and falls back to the URL when it returns `false`. All windows share ONE WebSocket through `chat/ChatSocketHub.js`: `subscribe(handlers)` returns a channel with the `ChatSocket` surface (`send`/`isOpen`/`close`, where `close` unsubscribes), the socket opens on the first subscriber and closes with the last, and a late subscriber gets `onReady` on a microtask. A `dp-chat` given `.hub` subscribes instead of opening its own socket, and drops `error` frames whose `client_id` is not one of its own pending sends. `chat/ConversationItem.js` is the one `.conversation-item` builder shared by `/messages` and the dock. `dp-chat` dispatches a bubbling `dp-chat:conversation` event (detail `{user}`) after it renders a conversation, which the dock uses to learn a window's partner name and to refresh the unread counters.
`dp-chat-dock` (`AppChatDock.js`, `app.chatDock`) is the Facebook-style docked chat, server-rendered once in `base.html` (block `chat_dock`, members only; `messages.html` empties the block so `/messages` has no dock). It builds the **Chats panel** (opened by any `[data-chat-panel-toggle]`, the topnav Messages icon; people search via `ListNav`, recent conversations from `/messages/conversations`, a New message compose window) and a bottom-right **tray** of chat windows plus minimized avatar heads. Each window is a plain `dp-chat` with `mode="window"`, so every chat behaviour (optimistic send, reconcile, AI frames, typing, receipts, delete, report, attachments, older history) is the one `AppChat` implementation. Rules that keep it correct: window `dp-chat` elements are **never moved in the DOM** (moving a custom element runs `disconnectedCallback`, which closes its socket channel, and the `_built` guard skips the rebuild), so windows are appended in creation order and removed, never reordered; a minimized window is destroyed and re-created on expand, which reloads its history and marks it read, so a head never marks anything read; open/minimized state lives in `sessionStorage` (per tab, the `ScrollMemory` precedent) under `devplace.chat-dock.<uid>`, cleared when a logout link is clicked; minimized-head unread counts are reconciled against `/messages/conversations` on connect and on panel open, so reading elsewhere never leaves a stale badge; at the 768px mobile breakpoint the dock renders nothing and every trigger falls through to its `href` (the full `/messages` page). Any element with `data-chat-open="<uid>"` (plus `data-chat-username`/`data-chat-avatar-seed`, emitted by the `_chat_open_attrs.html` partial) opens a window on click: the profile Send Message button and the `/notifications` card link of a `message` notification use it, and `LiveNotifications` routes a `message` toast's click through `app.chatDock.open()` and falls back to the URL when it returns `false`. All windows share ONE WebSocket through `chat/ChatSocketHub.js`: `subscribe(handlers)` returns a channel with the `ChatSocket` surface (`send`/`isOpen`/`close`, where `close` unsubscribes), the socket opens on the first subscriber and closes with the last, and a late subscriber gets `onReady` on a microtask. A `dp-chat` given `.hub` subscribes instead of opening its own socket, and drops `error` frames whose `client_id` is not one of its own pending sends. `chat/ConversationItem.js` is the one `.conversation-item` builder shared by `/messages` and the dock. `dp-chat` dispatches a bubbling `dp-chat:conversation` event (detail `{user}`) after it renders a conversation, which the dock uses to learn a window's partner name and to refresh the unread counters.
`static/js/chat/ChatSocket.js` and `static/js/chat/MessageGrouping.js` are chat-scoped helpers used only by `AppChat.js` - `ChatSocket` is modeled on `PubSubClient.js`'s real exponential backoff (200ms doubling to a 5000ms cap, reset on a successful connect) rather than the flat-delay retry the deleted `MessagesSocket.js` used, and preserves the same `4013` "wrong worker" fast-retry special case. `MessageGrouping.shouldGroup(previous, current)` is the one pure predicate (<=300s gap, same sender) shared by both the initial-history grouping pass and the live-append path, so the two can never disagree. Neither file is a general-purpose "do not reimplement" utility for the rest of the app (see the out-of-scope note in the design document this shipped from) - they are not added to the do-not-reimplement list below; a future non-chat WebSocket feature should keep hand-rolling its own client (as `DeviiSocket.js`/`DeepsearchProgressSocket.js`/`SeoProgressSocket.js`/`AppDeepsearchChat.js`'s inline socket already do) rather than reaching into `chat/`.
@@ -32,7 +32,7 @@ Conventions:
- **Light DOM only** (no `attachShadow`), so the site's global CSS applies - matching the existing `devii-*` elements. `dp-dialog`/`dp-context-menu` reuse the existing `.dialog-*`/`.context-menu*` styles in `components.css`; `dp-toast` styles are in `components.css` (`.dp-toast-host`/`.dp-toast`).
- Each file self-registers via `customElements.define` at the bottom. `components/index.js` imports them all and is imported by `Application.js`, so every element is defined on every page (including `/docs`).
- The behavioural singletons are created once in `Application.js` and exposed as `app.dialog`, `app.contextMenu`, `app.toast`. The `dp-dialog`/`dp-context-menu` elements keep the exact pre-existing `Dialog`/`ContextMenu` APIs (`confirm`/`prompt`/`alert`/`open`, `attach`/`open`/`close`) so existing callers (`ProjectFiles`, `ApiKeyManager`, `ModalManager`, `PushManager`, `ApiTester`) are unchanged. `Avatar`/`CodeBlock`/`Toast`/`ContentRenderer` remain as static/service modules (widely imported); the matching elements (`dp-avatar`, `dp-code`, `dp-content`) reuse them. `dp-content` wraps the shared `contentRenderer` engine that also powers the `data-render` attribute (driven by `ContentEnhancer`) - the engine stays a reusable service, the element is its component face. `dp-content` captures its raw markdown source before `contentRenderer.applyTo` overwrites `textContent`, then mounts a hover/focus reveal `.content-copy-btn` in its top-right corner that copies that original source to the clipboard (mirroring `CodeBlock.copyButton`); CSS lives beside `.code-copy-btn` in `docs.css`.
- **`dp-content` / `dp-title` are CLIENT-only now (live contexts).** `dp-content` (`AppContent.js`) and its inline companion `dp-title` (`AppTitle.js`, `contentRenderer.renderInline`) render markdown/emoji/media (and, for title, inline-only with an inline-tag allowlist) on the client from `textContent`. **They are no longer used for server-rendered content/titles** - those moved to the backend `render_content`/`render_title` globals (see the root CLAUDE.md "Content rendering pipeline" section) for SEO. The components remain defined and are used only where content is generated client-side after load: `dp-content` in the DeepSearch chat (`AppDeepsearchChat.js`) and the planning report (`PlanningGenerator.js` -> `admin_issues_planning.html`). Keep them for those live cases and future use; do NOT wrap server-known content/titles in them. Both are now used ONLY for live/client-generated content (chat, planning report, dynamically inserted bubbles); server-rendered content/titles use the backend `render_content`/`render_title` globals instead. The components are intentionally kept for those live contexts and future use.
- **`dp-content` / `dp-title` are CLIENT-only now (live contexts).** `dp-content` (`AppContent.js`) and its inline companion `dp-title` (`AppTitle.js`, `contentRenderer.renderInline`) render markdown/emoji/media (and, for title, inline-only with an inline-tag allowlist) on the client from `textContent`. **They are no longer used for server-rendered content/titles** - those moved to the backend `render_content`/`render_title` globals (see `devplacepy/templates/CLAUDE.md` "Content rendering pipeline") for SEO. The components remain defined and are used only where content is generated client-side after load: `dp-content` in the DeepSearch chat (`AppDeepsearchChat.js`) and the planning report (`PlanningGenerator.js` -> `admin_issues_planning.html`). Keep them for those live cases and future use; do NOT wrap server-known content/titles in them. Both are now used ONLY for live/client-generated content (chat, planning report, dynamically inserted bubbles); server-rendered content/titles use the backend `render_content`/`render_title` globals instead. The components are intentionally kept for those live contexts and future use.
- **What is NOT a component (by design):** partial-bound controllers (`ReactionBar`, `VoteManager`, `BookmarkManager`, `PollManager`, `CommentManager`, etc.) enhance server-rendered `_*.html` markup rather than render standalone UI; pure utilities (`Http`, `DomUtils`, `FormManager`, `Poller`, `JobPoller`, `OptimisticAction`) have no UI. These stay plain ES6 modules. The four optimistic engagement controllers extend the shared `OptimisticAction` base - see "Shared frontend utilities" below. Self-contained presentational widgets become components; partial-bound controllers (votes, reactions, comments) and pure utilities stay plain modules because they enhance server-rendered markup rather than render standalone UI.
- Documented in the public docs **Components** section (`templates/docs/component-*.html`, registered under `SECTION_COMPONENTS` in the `routers/docs` package). Each page has a `data-render` markdown block (with example markup HTML-escaped as `&lt;dp-...&gt;`, since `data-render` re-parses `textContent` and would otherwise instantiate the example) plus a live demo in a separate block whose `<script type="module">` imports its own component module (it runs before `Application.js`).
- **`dp-lightbox` (`AppLightbox.js`, `app.lightbox`, `static/css/lightbox.css`)** is the single image lightbox. It is **attribute-wired, not call-wired**: the singleton installs ONE delegated `document` click listener and opens any clicked `img[data-lightbox]` (showing `data-full` when present, else the image's own src; `alt` as caption; ignored when the image sits inside an `<a>`). To make a thumbnail open it, just add `data-lightbox` - never attach a click handler. Attachment thumbnails carry `data-lightbox`+`data-full` (`_attachment_display.html`); markdown content images are marked centrally in `ContentEnhancer.initContentRenderer` (one place covers every `data-render` surface), so embedded images are always clickable. The old hand-rolled `.attachment-lightbox` markup/CSS was dead (never wired) and has been removed.
@@ -122,3 +122,9 @@ The component validates size/type/count and reports errors via `app.toast`. CSS
## ReportDialog (`ReportDialog.js`, `app.reportDialog`)
One class, one dialog, every surface. It delegates a document-level click on `[data-report-type]` (emitted by `_report_button.html`), opens the single `#report-dialog` overlay with the standard `.visible` toggle, and submits through `Http.sendForm` to `/reports/{target_type}/{target_uid}`. The toast repeats the published response window returned by the endpoint, so the acknowledgement the user sees is the one the server actually committed to. It carries no reason list of its own - the options are server-rendered from the `REPORT_REASONS` Jinja global, so a client can never offer a reason the API would reject.
## Enter to send (`EnterSubmit.js`)
One shared helper owns Enter behaviour: `EnterSubmit.attach` (composers: comments on every target type and `dp-chat`; Enter submits when the `enter_to_submit` profile setting is on, Shift+Enter newlines, Ctrl+Enter always submits, IME composition and an open mention dropdown always win) and `EnterSubmit.attachEditors` (Ctrl+Enter submit for every other textarea). The setting is exposed as `body[data-enter-to-submit]`. Never add a per-form Enter handler.
Emoji shortcodes map: after an `emoji` dependency bump, regenerate `static/js/emoji-shortcodes.js` with `devplace emoji-sync`, never hand-edit.
+20
View File
@@ -79,6 +79,9 @@ Reuse these via `{% set _x = ... %}{% include %}` (the `_avatar_link.html` conve
- `_report_button.html` - the Report control (and Block, when `_owner_name` is given) for any content action bar. Locals: `_type`, `_uid`, `_owner` (owner uid - the control hides on your own content), `_owner_name` (optional), `_class` (the surrounding surface's button class). Included at fifteen sites; a new content surface MUST include it (see the root `CLAUDE.md` rule).
- `_report_dialog.html` - the one report dialog, included once in `base.html` for signed-in users and driven by `ReportDialog.js`. Reasons come from the `REPORT_REASONS` Jinja global; never hand-roll a second dialog.
- `_maturity_gate.html` - the interstitial rendered in place of a maturity-labelled item. Local: `_level`. Guard the include with the `maturity_hidden(level, user)` global; the item's `maturity` is attached by `enrich_items`/`load_detail`.
- `_card_link.html` - the stretched card link (`<a class="card-link">`). Locals: `_href`, optional `_label`, optional `_chat_user`. Always includes `_chat_open_attrs.html`, so any card link whose `_chat_user` is set becomes a dock chat opener.
- `_chat_open_attrs.html` - emits `data-chat-open`/`data-chat-username`/`data-chat-avatar-seed` (seed via the `avatar_seed()` choke point) when `_chat_user` with a uid is set, and nothing otherwise. `dp-chat-dock` intercepts clicks on any `[data-chat-open]` element and opens a docked window; without JS the enclosing link's `href` still navigates. Set `_chat_user` only on genuine Send Message links (profile, message notifications), never on unrelated cards.
- The `chat_dock` block in `base.html` renders `<dp-chat-dock>` once for signed-in users; `messages.html` empties the block so `/messages` has no dock. The topnav Messages link carries `data-chat-panel-toggle` plus server-rendered `aria-haspopup="dialog"`/`aria-controls="chat-panel"`/`aria-expanded` for the Chats panel.
Vote button styles live ONCE in `feed.css` (`.post-action-btn`) - never redefine them in `post.css`. Page-specific CSS goes in a `static/css/*.css` file referenced from `{% block extra_head %}`, never an inline `<style>` block. All CSS conventions (tokens, `--z-*` stacking bands, breakpoints, reduced motion) are in `devplacepy/static/css/CLAUDE.md`.
@@ -93,3 +96,20 @@ The three public listings (`/feed`, `/gists`, `/projects`) share one search box:
## Visibility partial
- `_visibility_field.html` - the `<select name="visibility">` for create and edit forms. Locals: `_visibility` (current value, default `published`), `_visibility_id` (unique element id). Options come from the `VISIBILITY_OPTIONS` global; `visibility_of(table, item)` and `visibility_label(value)` are the other globals. The admin news table reuses the generic `data-auto-submit` select pattern from `admin_users.html`.
## Action menus and composer order (requested_changes items 2 and 3)
- Creation forms put the title first (`_post_composer_form.html` leads with `#post-title`; projects, gists, issues, quizzes already did). Title inputs in modals carry `data-autofocus`; `ModalManager` prefers it on open. News has no creation form.
- Every content action bar (post, project, gist, news, quiz detail and post/quiz cards) keeps votes, reactions, the main call to action and Note primary, and groups the rest into the one existing `dp-action-menu`. Card menus never hardcode panel ids. `_bookmark_button.html` and `_report_button.html` take `_menu_action = true` inside a menu.
## Content rendering pipeline (backend, `devplacepy/rendering.py`)
Server-rendered content and titles are the default for everything that exists at request time (post bodies, comments, news, project/gist descriptions, DM history, every content title). Jinja globals `render_content(text)`/`render_title(text)`, mirrored client pipeline via mistune, `@lru_cache`d. Server-rendered code blocks get highlighting plus Copy client-side via `ContentEnhancer`.
The client pipeline (`ContentRenderer.js`, `dp-content`/`dp-title`) is ONLY for live content that does not exist at request time (live comments, DM bubbles, Devii/DeepSearch/Docs chat, planning report): marked, then `DOMPurify.sanitize` (fail-closed), then highlight.js and media/autolink. Never add `data-render` to server-rendered content.
Rules: emoji shortcodes are the full GitHub/Discord set, generated by `rendering.py` `build_emoji_shortcodes()` with the identical map in generated `static/js/emoji-shortcodes.js` (regenerate with `devplace emoji-sync` after a dependency bump, never hand-edit). YouTube embeds follow the single `devplacepy/embeds.py` spec only (validated ids, never substring matching, never another regex); the JS constants come from generated `static/js/embed-spec.js` (`devplace embeds-sync`, never hand-edit). Emails are masked in rendered text nodes only (never before mistune, or `*` parses as emphasis); `molodetz.nl` addresses stay verbatim. Em dashes become hyphens before mistune inside the cached render, so there is no per-template cost.
## Avatar seed choke point
The per-user avatar seed is the nullable `users.avatar_seed` column, falling back to the username. Always resolve it through the single null-safe choke point `avatar.avatar_seed(user)` (a Jinja global), never read `avatar_seed` or pass `username` to `avatar_url(...)` directly. Every render site (`_avatar_link.html`, `og_image`, the devRant avatar payload) goes through it. Regenerate is owner-or-admin at `POST /profile/{username}/regenerate-avatar` (fresh `generate_uid()`, cache invalidate, audit `profile.avatar.regenerate`); the old seed is never stored, so the old avatar cannot return. Devii tool `regenerate_avatar` (`CONFIRM_REQUIRED`).