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.
This commit is contained in:
2026-11-12 15:29:27 +01:00
parent dbdd0d29dd
commit 8a48e3ef85
103 changed files with 2680 additions and 378 deletions
+75
View File
@@ -0,0 +1,75 @@
# 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.
## 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.
+2 -2
View File
@@ -1133,8 +1133,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 |
|------|------|
+12 -1
View File
@@ -32,7 +32,8 @@ from .seo_meta import SEO_META_TYPES, get_seo_metadata, get_seo_metadata_batch,
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
@@ -251,6 +252,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)
+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})
+6
View File
@@ -2758,6 +2758,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"):
+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
+42
View File
@@ -504,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",
+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": [
+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)
+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:
+2 -2
View File
@@ -294,10 +294,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.
+6
View File
@@ -328,6 +328,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",
+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,
+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,
+19
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,
@@ -391,6 +394,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)
@@ -502,6 +518,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,
+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)
+10
View File
@@ -85,9 +85,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 +271,7 @@ class MessagesOut(_Out):
class NotificationsOut(_Out):
notification_groups: list[NotificationGroupOut] = []
next_cursor: Optional[str] = None
grouping: bool = True
class LeaderboardOut(_Out):
+3
View File
@@ -61,6 +61,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
+1 -1
View File
@@ -132,7 +132,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)
+2
View File
@@ -259,6 +259,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.
@@ -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",
@@ -76,6 +76,9 @@ 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",
@@ -196,6 +199,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 "
@@ -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",
@@ -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)
+2 -2
View File
@@ -85,11 +85,11 @@ Live/echoed message bubbles are NEVER injected as raw HTML. `AppChat._buildBubbl
## Frontend
The messaging frontend is the single self-booting custom element `<dp-chat>` (`static/js/components/AppChat.js`), which replaced the old page-controller trio `MessagesLayout.js`/`MessagesSocket.js`/`MessageSearch.js` (all deleted) and `messages.css` (superseded by `static/css/chat.css`) - see `devplacepy/static/js/CLAUDE.md` for the component roster entry. `MobileNav.js` does **not** own the mobile pane (that duplicate was removed; `dp-chat` is the only pane controller). `templates/messages.html` renders `<dp-chat mode="page" self-uid="..." with-uid="..." conversations-url="/messages/conversations" search-url="/messages/search" send-url="/messages/send" ws-url="/messages/ws" ai-indicator="true">` wrapping the SAME server-rendered `.messages-list`/`.messages-main`/`.messages-thread`/`.message-bubble` markup as before (no-JS/crawler fallback), which the component *adopts* on `connectedCallback` rather than discarding. It owns a `ChatSocket` (`static/js/chat/ChatSocket.js`, exponential backoff, `4013` fast-path, 25s ping), sends over WS with an optimistic pending bubble keyed by `client_id`, reconciles on the echoed `message` frame, applies later `ai_processed` frames in place (compare `dp-content[data-source]`, never rendered `textContent`), injects the Report control on every live incoming bubble, catches up with `{type:"sync"}` on reconnect, and switches conversations without dropping the socket (`GET /messages?with_uid=` JSON + `history.pushState`). Older history loads via `GET /messages?with_uid=&before=` when the thread is scrolled to the top. Mobile: CSS hides the inactive pane from `with-uid` / `.show-list` before JS runs (no stacked FOUC); the composer does not auto-focus on coarse pointers; keyboard inset uses `visualViewport.offsetTop + height`; Enter-to-send is desktop-only. **The send button is disabled while `dp-upload` is busy AND while a genuine new send is in flight** (the send-lock, see "Send dedupe" above) - a `.failed`-bubble retry never engages it, so retrying an old message never blocks typing/sending a new one. Presence in `mode="page"` stays on the page-global `PresenceManager`. An opt-in `ai-indicator="true"` attribute shows "Adjusting..." while `ai_pending` and "Adjusted by AI" when the revision lands. Styling is in `static/css/chat.css` using `variables.css` tokens only, responsive down to 360px.
The messaging frontend is the single self-booting custom element `<dp-chat>` (`static/js/components/AppChat.js`), which replaced the old page-controller trio `MessagesLayout.js`/`MessagesSocket.js`/`MessageSearch.js` (all deleted) and `messages.css` (superseded by `static/css/chat.css`) - see `devplacepy/static/js/CLAUDE.md` for the component roster entry. `MobileNav.js` does **not** own the mobile pane (that duplicate was removed; `dp-chat` is the only pane controller). `templates/messages.html` renders `<dp-chat mode="page" self-uid="..." with-uid="..." conversations-url="/messages/conversations" search-url="/messages/search" send-url="/messages/send" ws-url="/messages/ws" ai-indicator="true">` wrapping the SAME server-rendered `.messages-list`/`.messages-main`/`.messages-thread`/`.message-bubble` markup as before (no-JS/crawler fallback), which the component *adopts* on `connectedCallback` rather than discarding. In `page`/`embed` mode it owns a `ChatSocket` (`static/js/chat/ChatSocket.js`, exponential backoff, `4013` fast-path, 25s ping); in `window` mode it subscribes through the shared dock hub instead. It sends over WS with an optimistic pending bubble keyed by `client_id`, reconciles on the echoed `message` frame, applies later `ai_processed` frames in place (compare `dp-content[data-source]`, never rendered `textContent`), injects the Report control on every live incoming bubble, catches up with `{type:"sync"}` on reconnect, and switches conversations without dropping the socket (`GET /messages?with_uid=` JSON + `history.pushState`). Older history loads via `GET /messages?with_uid=&before=` when the thread is scrolled to the top. Mobile: CSS hides the inactive pane from `with-uid` / `.show-list` before JS runs (no stacked FOUC); the composer does not auto-focus on coarse pointers; keyboard inset uses `visualViewport.offsetTop + height`; Enter-to-send is desktop-only. **The send button is disabled while `dp-upload` is busy AND while a genuine new send is in flight** (the send-lock, see "Send dedupe" above) - a `.failed`-bubble retry never engages it, so retrying an old message never blocks typing/sending a new one. Presence in `mode="page"` stays on the page-global `PresenceManager`. An opt-in `ai-indicator="true"` attribute shows "Adjusting..." while `ai_pending` and "Adjusted by AI" when the revision lands. Styling is in `static/css/chat.css` using `variables.css` tokens only, responsive down to 360px.
**Composer layout (every mode).** The message form is `[+] [composer-tools] [composer-field] [send]`: the `.composer-more-btn` toggles `tools-open` on the form, revealing `.composer-tools` (`dp-upload` and `dp-gif-picker`); typing collapses the tools again unless an upload is in flight or attachments are pending, a starting upload (paste, drop, pick) opens them so the count stays visible, and a send collapses them. The textarea lives inside `.composer-field`, the pill that also holds the emoji button (`ContentEnhancer.initEmojiPickers` appends the button into the field and re-homes the picker popup onto the form, and the GIF panel is positioned against the form too, so neither popup is clipped by the narrow pill). `messages.html` and `AppChat._buildComposer` emit the identical structure.
**Docked windows (`mode="window"`).** On every page except `/messages`, `dp-chat-dock` (see `devplacepy/static/js/CLAUDE.md`) hosts small `dp-chat mode="window"` elements. Window mode builds its own skeleton (header via `_buildHeader` with avatar and name, no back button, no element ids so several windows can coexist), loads history through the same `GET /messages?with_uid=` JSON the page uses (`_loadConversation`, which also marks the conversation and its notifications read) **before** subscribing to the shared socket, so the reconnect `sync` starts from the newest loaded stamp, and never touches `history`. Its thread always counts as active (`_activePane = "thread"`), so read receipts and the active-conversation marker behave exactly as on the page. No server change was needed: the dock uses only `/messages/conversations`, `/messages/search`, `GET /messages?with_uid=` and `WS /messages/ws`.
**Docked windows (`mode="window"`).** On every page except `/messages`, `dp-chat-dock` (see `devplacepy/static/js/CLAUDE.md`) hosts small `dp-chat mode="window"` elements. Window mode builds its own skeleton (header via `_buildHeader` with avatar and name, no back button, no element ids so several windows can coexist), loads history through the same `GET /messages?with_uid=` JSON the page uses (`_loadConversation`, which also marks the conversation and its notifications read) **before** subscribing to the shared socket, so the reconnect `sync` starts from the newest loaded stamp, and never touches `history`. Its thread counts as active (`_activePane = "thread"`) only while the document is visible: a message arriving in a hidden tab stays unread server-side, and the conversation is marked read when the tab becomes visible again. No server change was needed: the dock uses only `/messages/conversations`, `/messages/search`, `GET /messages?with_uid=` and `WS /messages/ws`.
**Auto-scroll never fights a manual scroll-up.** `_startScrollWatcher`/`_stabilizeScroll` force `scrollTop = scrollHeight` on every thread mutation (new bubble, attachment/image finishing loading) ONLY while `_userAtBottom` is true, re-checked every `requestAnimationFrame` up to `STABILIZE_MAX_FRAMES`. The one thing that used to break this: while a multi-frame stabilize loop was in flight (`_stabilizePending`), the real `scroll` event listener (`_bindAutoScroll`) ignored EVERY scroll event outright, including a genuine user wheel/touch scroll-up that happened to land inside that window - so a rapid burst of incoming messages (each restarting the stabilize loop while attachments were still loading) could silently overwrite a user's attempt to scroll up to read history. The fix: every programmatic scroll (`_scrollThreadToEnd`, `_stabilizeScroll`) records the exact `scrollTop` it just set in `_lastForcedScrollTop`; the `scroll` listener only skips its own echo (`_stabilizePending && scrollTop === _lastForcedScrollTop`) and always processes a scroll that lands anywhere else, so a real user scroll-up is detected and `_userAtBottom` flips to `false` immediately, even mid-stabilization. Never gate scroll-intent detection on `_stabilizePending` alone again.
+16 -12
View File
@@ -2,7 +2,8 @@
from __future__ import annotations
from devplacepy.database import db
import time
from devplacepy.database import db, count_unread_groups, get_notification_throttle_enabled, notification_group_key, NOTIFICATION_GROUP_KEYS
from devplacepy.services.base import BaseService
from devplacepy.services.pubsub import publish as pubsub_publish
@@ -23,6 +24,7 @@ class NotificationRelayService(BaseService):
super().__init__(name="notification_relay", interval_seconds=1)
self._watermark = 0
self._primed = False
self._last_toast = {}
def _max_id(self) -> int:
if "notifications" not in db.tables:
@@ -32,17 +34,8 @@ class NotificationRelayService(BaseService):
return int(value or 0)
def _counts(self, user_uid: str) -> dict:
notifications = 0
notifications = count_unread_groups(user_uid)
messages = 0
if "notifications" in db.tables:
rows = list(
db.query(
"SELECT COUNT(*) AS c FROM notifications "
"WHERE user_uid = :u AND read = 0",
u=user_uid,
)
)
notifications = int(rows[0]["c"]) if rows else 0
if "messages" in db.tables:
rows = list(
db.query(
@@ -63,7 +56,7 @@ class NotificationRelayService(BaseService):
return
rows = list(
db.query(
"SELECT id, uid, user_uid, type, message, target_url "
"SELECT id, uid, user_uid, type, message, target_url, related_uid "
"FROM notifications WHERE id > :wm ORDER BY id ASC LIMIT :lim",
wm=self._watermark,
lim=BATCH_LIMIT,
@@ -73,6 +66,17 @@ class NotificationRelayService(BaseService):
return
delivered = 0
for row in rows:
if get_notification_throttle_enabled(row["user_uid"]):
if NOTIFICATION_GROUP_KEYS.get(row["type"], "single") != "single":
key = (row["user_uid"],) + notification_group_key(row)
now_ts = time.time()
last = self._last_toast.get(key)
if last is not None and now_ts - last < 300:
continue
self._last_toast[key] = now_ts
if len(self._last_toast) > 10000:
for old_key in list(self._last_toast)[:1000]:
self._last_toast.pop(old_key, None)
delivered += await pubsub_publish(
f"user.{row['user_uid']}.notifications",
{
+67 -7
View File
@@ -43,7 +43,10 @@ A model route (`gateway_models.tools_mode`, `native` default or `emulated`) decl
- **Request seam.** `gateway._chat_upstream_body` calls `emulate_request(payload)` first, BEFORE the Responses/Meta transpile, so the Meta path (`chat_to_responses`, Muse aliasing) simply receives a tool-less Chat payload. As a side effect the Meta reserved tool-name gate never fires, because `tools[]` is gone; `_response_tool_aliases` returns `{}` for emulated routes. `emulate_request` strips `tools`/`tool_choice`/`parallel_tool_calls`/`functions`/`function_call`, appends a Hermes-format catalog (`<tools>` JSON lines plus the `<tool_call>{"name","arguments"}</tool_call>` contract) to the system message (creating one when absent), maps `tool_choice` (`none` drops the catalog, `required`/named add a MUST directive, `parallel_tool_calls: false` adds a one-call rule), rewrites history (assistant `tool_calls` become `<tool_call>` blocks, `role: tool`/`function` messages become one merged user message of `<tool_response>` blocks matched back to names by call id), and adds `<tool_response>` as a stop sequence so the model cannot invent a result. It never mutates the caller's payload.
- **Response seams.** Non-streaming: `convert_completion` parses blocks out of `message.content` into `tool_calls` (generated `call_` ids, `finish_reason: "tool_calls"`, leftover text kept, `content: null` when empty), applied on both the chat and the Responses non-stream branches. Streaming: `_emulate_tool_stream` wraps the finished SSE iterator, so ledger/TTFT accounting stays inside the inner generator. `ToolCallStream` relays text live with a partial-`<tool_call>` holdback, buffers once a call opens, and emits each call whole in ONE `tool_calls` delta (never incremental arguments: that is where vLLM's Hermes parser kept breaking). Usage chunks and non-content deltas pass through.
- **Parsing is tolerant, validation strict.** Accepts code fences, an array of calls in one block, `parameters` for `arguments`, string-encoded arguments, and an unterminated final block. A call is valid only if the name is declared and the schema's `required` keys are present. An invalid block is NEVER dropped silently: it stays in `content` as text and is logged (`emulated tools: ...`). Known gap: there is no repair retry; an invalid call is returned as text.
- **Hard caps (400, no upstream call, no ledger row).** `MAX_TOOLS` 64, `MAX_CATALOG_CHARS` 60000, only `function` tools, `MAX_CALLS_PER_TURN` 8 (extra calls dropped with a warning). The catalog costs prompt tokens on every call, billed like any input.
- **No count/size caps (deliberate).** Any number of `function` tools is accepted and the full catalog is always injected - Devii alone declares hundreds of tools, so a count cap would make large catalogs unservable everywhere. Servability is bounded downstream: the context-window precheck routes an oversized request to a fallback model before dispatch, and the upstream's own context limit is relayed when nothing can serve it. What still 400s (no upstream call, no ledger row) is a malformed declaration: non-list `tools`, a non-`function` tool type, or a nameless function. `MAX_CALLS_PER_TURN` 8 (extra calls dropped with a warning) is unchanged. The catalog costs prompt tokens on every call, billed like any input.
- **Per-owner catalog cache (`tool_emulation.CatalogCache`, owned by `GatewayRuntime`).** Building the catalog (spec validation + instruction assembly, milliseconds at hundreds of tools) runs once per distinct `(owner, tools, tool_choice, parallel_tool_calls)` fingerprint and is reused across turns, retries, and fallback attempts; the response seams (`_emulated_tools`) resolve declarations from the same entry instead of re-validating. Entries are namespaced by owner (`(owner_kind, owner_id)`, so one user's tool set never serves another's) and bounded (`MAX_ENTRIES` 64, `MAX_CHARS` 2M, oldest-first eviction) - a cache key is content-derived, so no invalidation is needed.
- **Injection cadence: once per request, every request.** The catalog is injected exactly once per upstream attempt (one `<tools>` block; history converts without repeated blocks; the stop sequence is added only when absent), but it is re-sent on every turn, retry, and fallback attempt, because the upstream is stateless and each call needs the catalog in context. Fallback attempts never stack injections: every attempt rebuilds from the pristine client payload (`emulate_request` never mutates its input), and the per-owner cache only skips the rebuild, never changes the bytes.
- **Upstream prefix caching.** A prefix-caching upstream (DeepSeek context caching, tracked as `prompt_cache_hit_tokens`) can serve the repeated catalog from cache, but only while the bytes before it are stable. The catalog is appended after the client's system content, so anything volatile there re-bills the catalog too. Devii's system prompt is stable within the hour (its trailing `# CURRENT TIME` block is rounded to the hour, see the Devii file), so turns inside one hour share one prefix and the catalog hits; the hour rollover breaks it. Watch the cache-hit token split in `/admin/ai-usage` to confirm.
- **Surfaces.** `ModelRouteIn.tools_mode`, the admin model form (**Tool calling** select), the `tools: emulated` badge, `POST /admin/gateway/models` (`tools_mode`, documented in `docs_api`) and the Devii `gateway_model_set` tool.
- **Not covered:** constrained/guided decoding (provider-specific), and the format is Hermes JSON only. Tests: `tests/unit/services/openai_gateway/tool_emulation.py` (pure) and the `test_emulated_tools_*` tests in `gateway.py` (through the real Meta Responses path, streaming and non-streaming).
@@ -71,6 +74,10 @@ A dedicated per-IP throttle protects `/openai/v1/*` against unauthenticated prob
All config is `config_fields` (upstream url/model/key, force-model, the Prompt group's `gateway_system_preamble` and `gateway_thinking` (default off), timeout, instances, vision url/model/key/cache/toggle, the Embeddings group (`gateway_embed_enabled`/`_url`/`_model`/`_key`), the auth toggles + static key + internal key, plus the Pricing/Reliability/Tracking groups); live metrics (requests/errors/in-flight/vision-calls/embed-calls/latency plus 24h cost/tokens/success rollups) via `collect_metrics`.
## Vision model (current: `google/gemma-4-31b-it`)
Image content is described by the vision model before forwarding (augmentation defaults on via `gateway_vision_enabled`). The live value is the `gateway_vision_model` site setting (database, editable in admin UI, hot-reloads); the code fallback for fresh databases is `VISION_MODEL_DEFAULT` in `config.py` with its context window in `MODEL_CONTEXT_MAP_DEFAULT`. Keep the two in sync when switching models: the DB row wins at runtime, the code default wins on a fresh install. History: `gemma-3-12b-it` default, `gemma-3-27b-it` via DB, `gemma-4-31b-it` since 08/11/2026 (cheaper small variant `gemma-4-26b-a4b-it` also verified on OpenRouter and rejected in favour of quality).
## System-message composition (date awareness + operator preamble)
`system_message.py` (`apply_system_directives`) runs in `handle_chat` only (NOT `handle_embeddings`/`handle_passthrough`), after vision augmentation and before the upstream payload is assembled, so it reaches every chat consumer (news, bots, Devii guests, per-user direct API calls). It composes ONE system message in a fixed, cache-friendly order: **operator preamble (`gateway_system_preamble`) -> date line (`Current date: DD/MM/YYYY`) -> the client's original system content**.
@@ -337,15 +344,68 @@ The `muse` headers are defense in depth, NOT the attestation fix:
probes proved the key works from any client/TLS stack for plain calls
and the gate only fires on reserved `tools[].name` values. The real
fix is automatic tool-name aliasing (`muse_code.tool_aliases_for` /
`alias_chat_tools`, wired in `_chat_upstream_body` for Meta Responses
attempts only): any declared/history/tool_choice name exactly matching
`alias_chat_tools`, wired in `_chat_upstream_body` for Meta attempts on
BOTH wire protocols): any declared/history/tool_choice name exactly matching
`MUSE_RESERVED_TOOL_NAMES` (20 names, each measured denying while
near-misses pass) is rewritten to `ext_<name>` (growing underscores
on collision) and restored on the way back
(`restore_completion_names` / `restore_chunk_names`), so the model
(`restore_completion_names` / `restore_chunk_names`, with the alias map
threaded through `_stream_chat_response` for streamed chat), so the model
sees one consistent world and the client never sees the alias. The
map is rebuilt deterministically from the same payload at both ends,
so fallbacks crossing providers need no state. Clean requests pass
through untouched (same object, no log); aliased ones log
map is rebuilt deterministically from the same payload at both ends
(`_response_tool_aliases`, protocol-independent), so fallbacks crossing
providers need no state. Clean requests pass through untouched (same
object, no log, verbatim relay); aliased ones log
`Meta reserved tool names aliased: bash->ext_bash, ...`. If 403s
return, re-probe: Meta may have added a builtin.
Incident 2026-11-10 (tai `devplace/molodetz` 403s, Devii unaffected):
the gate scans NAMES, not counts. tai's 63-tool catalog shares 7 names
with the denylist (`shell`, `read_file`, `write_file`, `edit_file`,
`web_fetch`, `web_search`, `search`); Devii's 400+ domain tools share
0, so 400 tool calls never tripped it. Three rounds, 2026-11-10: (1) the aliasing
originally ran only for `responses`-protocol attempts while tai/detz
speak `chat_completions`, so colliding names reached Meta verbatim -
fixed by hoisting the aliasing above the protocol branch in
`_chat_upstream_body` and restoring names on the chat return paths
(non-streaming re-encode, streamed chunk restore); (2) the denylist was
missing `shell`, which tai/detz send on EVERY turn (first entry of
`CORE_TOOLS`, core loads always) - added (21 names), corroborated by
Pi's `pi-meta-oauth` denylist, live via `--reload` 18:26; (3) REFUTED
18:33: requests with all 5 known triggers aliased (`shell->ext_shell`
on the wire) plus stamped `muse` profile STILL 403. The 21-name gate
theory is therefore insufficient. Remaining fork: another ungated name
in the payload (candidates never probed by anyone: `web_fetch`,
`fork`, `poll`, `ask_user`, `remember`, `recall`, `load_skill`, ...),
the `ext_` scheme itself recognized, or the key fully gated for
non-genuine clients. Discriminator: two authenticated direct calls
against the route, one tool-less and one with a single clean tool -
see the research conclusion for the exact probes. If the tool-less call
also 403s, stop guessing names and put a pay-as-you-go key on the
route. Outcome 19:05, after a clean service restart: single-name live
probes proved `web_fetch` denied alone (added as 22nd name) while
`fork`, `poll`, `ask_user`, `remember`, `recall`, `load_skill`,
`ext_shell` each 200 alone; the full 63-tool tai catalog then 200d in
one call, and the journal shows `web_fetch->ext_web_fetch` aliasing on
real traffic with 9 upstream 200s and 0 403s since. The gate is names,
the denylist at 22 covers the whole static catalog, no key change
needed. Count caps measured live 2026-11-10 on the Meta route
(native `tools_mode`): 70, 100, 200 and 400 tools per call all HTTP
200 (63 real catalog names plus synthetic clean names) - there is no
count gate on this path. The only count cap in the system is the
gateway's own emulated-tools path (which had a 64-tool cap until
it was removed from the working tree the same day - `test_large_catalogs_are_served_with_no_cap`
pins 424 tools served, unrelated
to Meta). The companion
`openrouter/... 401 No cookie auth credentials found` in the same
report is unrelated: tai calling OpenRouter with no API key
configured, an operator setup gap, not a gateway behavior. Tests:
`tests/unit/services/openai_gateway/gateway.py`
(`test_meta_tool_names_aliased_on_wire_and_restored` /
`test_meta_tool_names_restored_on_stream_chunks` for Responses,
`test_meta_tool_names_aliased_on_chat_completions_wire` /
`test_meta_tool_names_restored_on_chat_completions_stream` for chat,
the chat tests pin `shell`+`read_file` end to end)
and `tests/unit/services/openai_gateway/muse_code.py` (denylist
membership + alias/round-trip unit tests). Full external-research
record: `research/muse-attestation-gate/` in the tai project.
+2 -1
View File
@@ -13,7 +13,7 @@ SYSTEM_PREAMBLE_DEFAULT = ""
THINKING_DEFAULT = False
VISION_URL_DEFAULT = "https://openrouter.ai/api/v1/chat/completions"
VISION_MODEL_DEFAULT = "google/gemma-3-12b-it"
VISION_MODEL_DEFAULT = "google/gemma-4-31b-it"
VISION_CACHE_SIZE_DEFAULT = 256
EMBED_URL_DEFAULT = "https://openrouter.ai/api/v1/embeddings"
@@ -50,4 +50,5 @@ MODEL_CONTEXT_MAP_DEFAULT = {
"deepseek-chat": 1_048_576,
"deepseek-reasoner": 1_048_576,
"google/gemma-3-12b-it": 8192,
"google/gemma-4-31b-it": 262144,
}
+47 -17
View File
@@ -31,13 +31,13 @@ from devplacepy.services.openai_gateway.responses import (
)
from devplacepy.services.openai_gateway.system_message import apply_system_directives
from devplacepy.services.openai_gateway.tool_emulation import (
CatalogCache,
ToolCallStream,
ToolEmulationError,
cached_emulated_tools,
convert_completion,
declared_tools,
emulate_request,
emulation_enabled,
parallel_allowed,
)
from devplacepy.services.openai_gateway.thinking import (
apply_thinking,
@@ -156,14 +156,22 @@ def _upstream_auth_guidance(resp, content: dict) -> Optional[str]:
def _chat_upstream_body(
payload: dict, client_body: dict, cfg: dict, protocol: str, log
payload: dict,
client_body: dict,
cfg: dict,
protocol: str,
log,
catalog_cache=None,
owner: tuple = ("anonymous", "anonymous"),
) -> dict:
# The handler reasons about a Chat payload throughout (routing, vision,
# precheck, fallback); only the bytes on the wire change per protocol.
# Meta aliasing applies to both wire protocols: api.meta.ai scans
# tools[] names on chat_completions exactly like on responses, so a
# chat_dialect client (tai, detz, any generic OpenAI caller) would 403
# without this. The restore side mirrors per protocol below.
if emulation_enabled(cfg):
payload = emulate_request(payload)
if protocol != "responses":
return payload
payload = emulate_request(payload, catalog_cache, owner)
if muse_code.is_meta_upstream(cfg.get("gateway_upstream_url")):
aliases = muse_code.tool_aliases_for(payload)
if aliases:
@@ -173,6 +181,8 @@ def _chat_upstream_body(
for alias, original in sorted(aliases.items())
)
log(f"Meta reserved tool names aliased: {renamed}")
if protocol != "responses":
return payload
send_body, warnings = chat_to_responses(payload)
if warnings:
shown = "; ".join(warnings[:3])
@@ -194,7 +204,9 @@ def _response_tool_aliases(payload: dict, protocol: str, cfg: dict) -> dict:
# Rebuilds the exact map _chat_upstream_body applied on the wire for
# this attempt (same payload, same deterministic rule), so response
# names restore without threading state through the fallback path.
if protocol != "responses" or emulation_enabled(cfg):
# Protocol-independent: aliasing now happens on the wire for both
# chat_completions and responses (see _chat_upstream_body).
if emulation_enabled(cfg):
return {}
if not muse_code.is_meta_upstream(cfg.get("gateway_upstream_url")):
return {}
@@ -208,17 +220,14 @@ def _tool_emulation_rejection(error: ToolEmulationError) -> JSONResponse:
)
def _emulated_tools(payload: dict, cfg: dict):
def _emulated_tools(payload: dict, cfg: dict, catalog_cache=None, owner=None):
# Same rebuild-from-the-attempt's-own-payload rule as _response_tool_aliases:
# the declared tools come from the Chat payload of the attempt that was
# actually sent, so a fallback crossing into or out of an emulated model
# needs no threaded state.
if not emulation_enabled(cfg):
return None
declared = declared_tools(payload)
if not declared:
return None
return declared, parallel_allowed(payload)
return cached_emulated_tools(payload, catalog_cache, owner)
def _emulate_completion(data: dict, emulated, log) -> dict:
@@ -361,6 +370,7 @@ class GatewayRuntime:
self._vision_breaker = CircuitBreaker(
config.CIRCUIT_THRESHOLD_DEFAULT, config.CIRCUIT_COOLDOWN_SECONDS_DEFAULT
)
self._catalog_cache = CatalogCache()
self.requests = 0
self.errors = 0
self.in_flight = 0
@@ -701,7 +711,9 @@ class GatewayRuntime:
send_start = time.monotonic()
try:
send_body = _chat_upstream_body(payload, body, cfg, protocol, log)
send_body = _chat_upstream_body(
payload, body, cfg, protocol, log, self._catalog_cache, owner
)
except ToolEmulationError as tool_error:
return _tool_emulation_rejection(tool_error)
resp, exc, timing = await self._send(
@@ -755,7 +767,7 @@ class GatewayRuntime:
send_start = time.monotonic()
try:
send_body = _chat_upstream_body(
payload, body, cfg, protocol, log
payload, body, cfg, protocol, log, self._catalog_cache, owner
)
except ToolEmulationError as tool_error:
return _tool_emulation_rejection(tool_error)
@@ -915,8 +927,11 @@ class GatewayRuntime:
handle_start,
send_start,
log,
tool_aliases=_response_tool_aliases(
payload, protocol, cfg
),
)
emulated = _emulated_tools(payload, cfg)
emulated = _emulated_tools(payload, cfg, self._catalog_cache, owner)
if emulated is not None:
body_iter = _emulate_tool_stream(body_iter, emulated, log)
return StreamingResponse(
@@ -955,7 +970,7 @@ class GatewayRuntime:
converted, _response_tool_aliases(payload, protocol, cfg)
)
converted = _emulate_completion(
converted, _emulated_tools(payload, cfg), log
converted, _emulated_tools(payload, cfg, self._catalog_cache, owner), log
)
if convert_warnings:
log(
@@ -969,15 +984,26 @@ class GatewayRuntime:
media_type="application/json",
headers=resp_headers,
)
aliases = _response_tool_aliases(payload, protocol, cfg)
if aliases:
# chat_completions upstreams echo the aliased wire names back;
# the client must see the names it declared.
data = muse_code.restore_completion_names(data, aliases)
resp_headers = finalize(200, True, None, data.get("usage"))
log(f"chat POST -> 200 ({timing['upstream_latency_ms']:.0f}ms)")
emulated = _emulated_tools(payload, cfg)
emulated = _emulated_tools(payload, cfg, self._catalog_cache, owner)
if emulated is not None:
return Response(
content=json.dumps(_emulate_completion(data, emulated, log)).encode("utf-8"),
media_type="application/json",
headers=resp_headers,
)
if aliases:
return Response(
content=json.dumps(data).encode("utf-8"),
media_type="application/json",
headers=resp_headers,
)
return Response(
content=resp.content,
media_type="application/json",
@@ -1106,7 +1132,9 @@ class GatewayRuntime:
handle_start: float,
send_start: float,
log,
tool_aliases: Optional[dict] = None,
):
tool_aliases = tool_aliases or {}
first_at: Optional[float] = None
last_at: Optional[float] = None
content_chunks = 0
@@ -1132,6 +1160,8 @@ class GatewayRuntime:
chunk = json.loads(data_str)
except ValueError:
continue
if tool_aliases:
chunk = muse_code.restore_chunk_names(chunk, tool_aliases)
choices = chunk.get("choices") or []
delta = (choices[0].get("delta") if choices else None) or {}
if delta.get("content") or delta.get("reasoning") or delta.get("reasoning_content"):
@@ -41,8 +41,12 @@ def _muse_user_agent() -> str:
# Every one of these trips api.meta.ai's client gate with 403
# client_attestation_denied when declared as a tools[] function name
# (measured 2026-10-30, all 20 deny, near-misses pass). Text, history,
# params, and descriptions are not scanned - only exact tools[].name.
# (measured 2026-10-30, all 20 deny, near-misses pass; "shell" and
# "web_fetch" added 2026-11-10 after live single-name probes proved
# each denied alone - "shell" also independently verified by Pi's
# pi-meta-oauth denylist, which names it among its 9 blocking names
# while ours covered the other 8). Text, history, params, and
# descriptions are not scanned - only exact tools[].name.
MUSE_RESERVED_TOOL_NAMES = frozenset(
{
"workflow",
@@ -64,6 +68,8 @@ MUSE_RESERVED_TOOL_NAMES = frozenset(
"update_goal",
"report_progress",
"read_skill",
"shell",
"web_fetch",
"write_todos",
}
)
@@ -1,17 +1,24 @@
# retoor <retoor@molodetz.nl>
import copy
import hashlib
import json
import re
import uuid
from collections import OrderedDict
from typing import Optional
TOOLS_MODE_NATIVE = "native"
TOOLS_MODE_EMULATED = "emulated"
TOOLS_MODES = (TOOLS_MODE_NATIVE, TOOLS_MODE_EMULATED)
MAX_TOOLS = 64
MAX_CATALOG_CHARS = 60_000
# There is deliberately no cap on the tool count or the catalog size: a
# client may declare any number of tools and the full catalog is always
# injected. Servability is bounded downstream, not here - the gateway's
# context-window precheck routes an oversized request to a fallback model
# before dispatch, and the upstream's own context limit is relayed when
# nothing can serve it. A count/size rejection here would make large
# catalogs (Devii alone declares hundreds of tools) unservable everywhere.
MAX_CALLS_PER_TURN = 8
MAX_STOP_SEQUENCES = 4
@@ -48,10 +55,6 @@ def _function_specs(payload: dict) -> list[dict]:
return []
if not isinstance(tools, list):
raise ToolEmulationError("tools must be a list")
if len(tools) > MAX_TOOLS:
raise ToolEmulationError(
f"too many tools for an emulated-tools model: {len(tools)} > {MAX_TOOLS}"
)
specs = []
for tool in tools:
if not isinstance(tool, dict) or tool.get("type") != "function":
@@ -88,13 +91,7 @@ def _choice_directive(payload: dict) -> tuple[bool, str]:
def _catalog_text(specs: list[dict]) -> str:
lines = [json.dumps({"type": "function", "function": spec}, ensure_ascii=False) for spec in specs]
catalog = "\n".join(lines)
if len(catalog) > MAX_CATALOG_CHARS:
raise ToolEmulationError(
f"tool catalog too large for an emulated-tools model: "
f"{len(catalog)} > {MAX_CATALOG_CHARS} characters"
)
return catalog
return "\n".join(lines)
def build_instruction(payload: dict, specs: list[dict]) -> str:
@@ -227,7 +224,91 @@ def _with_stop(payload: dict) -> None:
payload["stop"] = sequences + [RESPONSE_OPEN]
def emulate_request(payload: dict) -> dict:
class CatalogCache:
MAX_ENTRIES = 64
MAX_CHARS = 2_000_000
def __init__(self) -> None:
self._entries: OrderedDict[tuple, tuple[str, dict, bool]] = OrderedDict()
self._chars = 0
@staticmethod
def fingerprint(payload: dict) -> Optional[str]:
try:
canonical = json.dumps(
{
"tools": payload.get("tools"),
"tool_choice": payload.get("tool_choice"),
"parallel_tool_calls": payload.get("parallel_tool_calls"),
},
sort_keys=True,
ensure_ascii=False,
separators=(",", ":"),
default=str,
)
except (TypeError, ValueError):
return None
return hashlib.sha256(canonical.encode("utf-8")).hexdigest()
def lookup(
self, payload: dict, owner: Optional[tuple] = None
) -> Optional[tuple[str, dict, bool]]:
digest = self.fingerprint(payload)
if digest is None:
return None
key = ((owner or (None, None)), digest)
try:
found = self._entries.pop(key)
except KeyError:
return None
self._entries[key] = found
return found
def store(
self,
payload: dict,
owner: Optional[tuple],
instruction: str,
declared: dict,
allow_parallel: bool,
) -> None:
digest = self.fingerprint(payload)
if digest is None:
return
key = ((owner or (None, None)), digest)
previous = self._entries.pop(key, None)
if previous is not None:
self._chars -= len(previous[0])
self._entries[key] = (instruction, declared, allow_parallel)
self._chars += len(instruction)
while len(self._entries) > self.MAX_ENTRIES or self._chars > self.MAX_CHARS:
_, dropped = self._entries.popitem(last=False)
self._chars -= len(dropped[0])
def _cached_parts(
payload: dict,
specs: list[dict],
catalog_cache: Optional[CatalogCache],
owner: Optional[tuple],
) -> tuple[str, dict, bool]:
allow_parallel = parallel_allowed(payload)
if catalog_cache is not None:
found = catalog_cache.lookup(payload, owner)
if found is not None:
return found
declared = {str(spec["name"]): spec for spec in specs}
instruction = build_instruction(payload, specs)
if catalog_cache is not None:
catalog_cache.store(payload, owner, instruction, declared, allow_parallel)
return instruction, declared, allow_parallel
def emulate_request(
payload: dict,
catalog_cache: Optional[CatalogCache] = None,
owner: Optional[tuple] = None,
) -> dict:
specs = _function_specs(payload)
history = payload.get("messages") or []
has_tool_history = any(
@@ -236,14 +317,33 @@ def emulate_request(payload: dict) -> dict:
)
if not specs and not has_tool_history:
return payload
instruction, _, _ = _cached_parts(payload, specs, catalog_cache, owner)
converted = {k: copy.copy(v) for k, v in payload.items() if k not in REMOVED_PAYLOAD_KEYS}
messages = _rewrite_history(list(history))
converted["messages"] = _with_system_instruction(messages, build_instruction(payload, specs))
converted["messages"] = _with_system_instruction(messages, instruction)
if specs:
_with_stop(converted)
return converted
def cached_emulated_tools(
payload: dict,
catalog_cache: Optional[CatalogCache] = None,
owner: Optional[tuple] = None,
) -> Optional[tuple[dict, bool]]:
if catalog_cache is not None:
found = catalog_cache.lookup(payload, owner)
if found is not None:
_, declared, allow_parallel = found
if not declared:
return None
return declared, allow_parallel
declared = declared_tools(payload)
if not declared:
return None
return declared, parallel_allowed(payload)
def _strip_fence(text: str) -> str:
stripped = text.strip()
match = _FENCE.match(stripped)
+84 -23
View File
@@ -835,40 +835,73 @@ img {
.comment-author:hover { color: var(--accent); }
.comment-form {
display: flex;
gap: 0.75rem;
margin-top: 1rem;
padding-top: 1rem;
display: grid;
grid-template-columns: auto minmax(0, 1fr);
column-gap: var(--space-md);
row-gap: var(--space-sm);
width: 100%;
min-width: 0;
max-width: 100%;
margin-top: var(--space-lg);
padding-top: var(--space-lg);
border-top: 1px solid var(--border);
align-items: center;
}
.comment-form:not(:has(> a)) {
grid-template-columns: minmax(0, 1fr);
}
.comment-reply-form {
margin-top: 0.75rem;
margin-top: var(--space-md);
}
.comment-form > a {
flex-shrink: 0;
grid-column: 1;
grid-row: 1;
justify-self: start;
align-self: center;
line-height: 0;
}
.comment-form .mention-wrapper {
flex: 1;
.comment-form .mention-wrapper,
.comment-form > textarea {
grid-column: 2;
grid-row: 1;
min-width: 0;
width: auto;
width: 100%;
}
.comment-form:not(:has(> a)) .mention-wrapper,
.comment-form:not(:has(> a)) > textarea,
.comment-form:not(:has(> a)) .comment-form-actions,
.comment-form:not(:has(> a)) .issue-comment-form-footer {
grid-column: 1;
}
.comment-form textarea {
width: 100%;
min-width: 0;
max-width: 100%;
min-height: 44px;
max-height: 120px;
}
.comment-form-actions {
grid-column: 2;
grid-row: 2;
display: flex;
flex-wrap: wrap;
align-items: center;
flex-shrink: 0;
gap: var(--space-xs);
min-width: 0;
max-width: 100%;
}
.comment-form-actions > *,
.comment-form .dp-upload-chip {
min-width: 0;
max-width: 100%;
}
.comment-form-actions button {
@@ -919,6 +952,45 @@ button.comment-form-submit:hover {
}
}
@media (max-width: 480px) {
.comment-form,
.comment-form:not(:has(> a)) {
grid-template-columns: minmax(0, 1fr);
}
.comment-form > a {
grid-column: 1;
grid-row: 1;
}
.comment-form .mention-wrapper,
.comment-form > textarea,
.comment-form-actions,
.comment-form .issue-comment-form-footer {
grid-column: 1;
}
.comment-form .mention-wrapper,
.comment-form > textarea {
grid-row: 2;
}
.comment-form-actions,
.comment-form .issue-comment-form-footer {
grid-row: 3;
}
.comment-form:not(:has(> a)) .mention-wrapper,
.comment-form:not(:has(> a)) > textarea {
grid-row: 1;
}
.comment-form:not(:has(> a)) .comment-form-actions,
.comment-form:not(:has(> a)) .issue-comment-form-footer {
grid-row: 2;
}
}
@media (max-width: 768px) {
.post-detail-actions .label,
.post-detail-actions .bookmark-label,
@@ -933,18 +1005,6 @@ button.comment-form-submit:hover {
}
}
@media (max-width: 360px) {
.comment-form {
flex-wrap: wrap;
}
.comment-form > a {
display: none;
}
.comment-form .mention-wrapper {
flex: 1 1 100%;
}
}
.card {
background: var(--bg-card);
border: 1px solid var(--border);
@@ -1289,7 +1349,8 @@ body:has(.page-messages) {
.modal-card input,
.modal-card textarea,
.modal-card select {
.modal-card select,
.comment-form textarea {
font-size: 16px;
}
}
+4
View File
@@ -5,6 +5,7 @@ dp-chat-dock {
--chat-window-height: 455px;
--chat-panel-width: 360px;
--chat-head-size: 48px;
--chat-heads-max-height: calc(100vh - var(--nav-height) - var(--space-2xl));
--chat-icon-size: 28px;
--chat-fab-lane: 64px;
display: contents;
@@ -141,6 +142,8 @@ body:has(.feed-fab) .chat-dock-tray {
align-items: center;
gap: var(--space-sm);
padding-bottom: var(--space-lg);
max-height: var(--chat-heads-max-height);
overflow-y: auto;
}
.chat-dock-heads:empty {
@@ -154,6 +157,7 @@ body:has(.feed-fab) .chat-dock-tray {
.chat-window {
position: relative;
flex-shrink: 0;
width: var(--chat-window-width);
height: var(--chat-window-height);
max-height: calc(100vh - var(--nav-height) - var(--space-lg));
+5 -5
View File
@@ -462,8 +462,8 @@ dp-chat[mode="embed"] {
.composer-more-btn {
flex-shrink: 0;
width: 36px;
height: 36px;
width: var(--composer-btn-size);
height: var(--composer-btn-size);
padding: 0;
display: flex;
align-items: center;
@@ -492,7 +492,7 @@ dp-chat[mode="embed"] {
flex-shrink: 0;
align-items: center;
gap: var(--space-xs);
min-height: 36px;
min-height: var(--composer-btn-size);
}
.messages-input-area.tools-open .composer-tools {
@@ -584,8 +584,8 @@ dp-chat[mode="embed"] {
.messages-send-btn {
flex-shrink: 0;
width: 36px;
height: 36px;
width: var(--composer-btn-size);
height: var(--composer-btn-size);
padding: 0;
background: var(--accent);
color: var(--on-accent);
+3 -2
View File
@@ -178,8 +178,9 @@
color: var(--text-primary);
line-height: 1.55;
}
.issue-comment-form {
margin-top: 1rem;
.comment-form.issue-comment-form {
margin-top: var(--space-lg);
row-gap: 0;
}
.issue-comment-form textarea {
width: 100%;
+5
View File
@@ -119,3 +119,8 @@
flex-shrink: 0;
}
.notif-group-count {
font-weight: 700;
color: var(--text-secondary);
}
+39 -4
View File
@@ -2,12 +2,25 @@
.post-page-layout {
display: grid;
grid-template-columns: var(--sidebar-width) minmax(0, 1fr) 280px;
grid-template-columns: minmax(0, 1fr);
gap: 1.5rem;
align-items: start;
}
.post-page-layout:has(> .feed-right) {
grid-template-columns: minmax(0, 1fr) 280px;
}
.post-page-layout:has(> .post-page-sidebar) {
grid-template-columns: var(--sidebar-width) minmax(0, 1fr);
}
.post-page-layout:has(> .post-page-sidebar):has(> .feed-right) {
grid-template-columns: var(--sidebar-width) minmax(0, 1fr) 280px;
}
.post-page-sidebar {
grid-column: 1;
display: flex;
flex-direction: column;
gap: 1rem;
@@ -20,10 +33,26 @@
}
.post-page {
grid-column: 1;
width: 100%;
min-width: 0;
max-width: 720px;
justify-self: center;
margin: 0;
}
.post-page-layout:has(> .post-page-sidebar) > .post-page {
grid-column: 2;
}
.post-page-layout > .feed-right {
grid-column: 2;
}
.post-page-layout:has(> .post-page-sidebar) > .feed-right {
grid-column: 3;
}
.post-nav-row {
display: flex;
align-items: center;
@@ -39,7 +68,10 @@
}
@media (max-width: 1024px) {
.post-page-layout {
.post-page-layout,
.post-page-layout:has(> .feed-right),
.post-page-layout:has(> .post-page-sidebar),
.post-page-layout:has(> .post-page-sidebar):has(> .feed-right) {
grid-template-columns: minmax(0, 1fr);
}
@@ -47,8 +79,11 @@
display: none;
}
.post-page {
margin: 0 auto;
.post-page,
.post-page-layout:has(> .post-page-sidebar) > .post-page,
.post-page-layout > .feed-right,
.post-page-layout:has(> .post-page-sidebar) > .feed-right {
grid-column: 1;
}
}
+1
View File
@@ -60,6 +60,7 @@
--font-mono: "SF Mono", Monaco, "Cascadia Code", monospace;
--nav-height: 56px;
--composer-btn-size: 36px;
--sidebar-width: 240px;
--max-content: 1200px;
+3
View File
@@ -8,6 +8,7 @@ import { NotificationManager } from "./NotificationManager.js";
import { ProfileEditor } from "./ProfileEditor.js";
import { MobileNav } from "./MobileNav.js";
import { CommentManager } from "./CommentManager.js";
import { EnterSubmit } from "./EnterSubmit.js";
import { ContentEnhancer } from "./ContentEnhancer.js";
import { DomUtils } from "./DomUtils.js";
import { PushManager } from "./PushManager.js";
@@ -80,6 +81,8 @@ class Application {
this.termsGate = new TermsGate(this.dialog);
this.modals = new ModalManager();
this.forms = new FormManager();
EnterSubmit.attachComments(document);
EnterSubmit.attachEditors(document);
this.votes = new VoteManager();
this.notifications = new NotificationManager();
this.profile = new ProfileEditor();
+1 -1
View File
@@ -18,7 +18,7 @@ Self-contained, presentational UI is built as custom elements with the `dp-` pre
`dp-quiz-player` (`AppQuizPlayer.js`) and `dp-quiz-builder` (`AppQuizBuilder.js`) both **adopt** server-rendered markup rather than building it (the `dp-chat` `mode="page"` pattern): the player intercepts each question's real `<form method="post">` through `Http.sendForm`, renders the graded result in place, shows a `Checking…` state while a `free_text` grade is in flight, ticks the remaining time from `Format.duration`, and advances to the next slide; the builder toggles the kind-specific field groups from the question-kind picker and submits the add-question form through `Http.sendForm`. Neither re-renders a prompt (the server already rendered it through `render_content`), neither opens a WebSocket, and neither implements a fetch wrapper, a poller or a dialog. Removing the JS leaves a fully working no-JS quiz.
**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.
**Prompt seeding on the shared Devii opener (`data-devii-prompt`).** `DeviiTerminal.bindOpenTrigger` binds every `[data-devii-open]` element; it 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. Escape and a double-click on empty page space open the same terminal only when `_canOpenOnGesture` is clear: no visible modal, dialog, or context menu, no open popover (so Escape that dismisses a `dp-action-menu` does not also open Devii), no open chat panel or mobile nav, and focus is not in a field. The open state is persisted, so an accidental open covers the next page, including Sign in.
`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.
+4
View File
@@ -1,6 +1,7 @@
// retoor <retoor@molodetz.nl>
import { Http } from "./Http.js";
import { EnterSubmit } from "./EnterSubmit.js";
import { contentRenderer } from "./ContentRenderer.js";
export class CommentManager {
@@ -108,6 +109,7 @@ export class CommentManager {
this.submitEdit(form, text);
});
EnterSubmit.attach(textarea);
text.style.display = "none";
text.insertAdjacentElement("afterend", form);
@@ -191,6 +193,8 @@ export class CommentManager {
}
enhanceForm(form) {
const ta = form.querySelector("textarea");
if (ta) EnterSubmit.attach(ta);
const enhancer = window.app && window.app.content;
if (enhancer) {
enhancer.initEmojiPickers();
+2
View File
@@ -94,6 +94,8 @@ export class DeviiTerminal {
if (document.querySelector(".modal-overlay.visible")) return false;
if (document.querySelector(".dialog-overlay.visible")) return false;
if (document.querySelector(".context-menu.visible")) return false;
if (document.querySelector(":popover-open")) return false;
if (document.querySelector("[data-action-menu-trigger][aria-expanded='true']")) return false;
if (document.querySelector(".chat-panel:not([hidden])")) return false;
const mobilePanel = document.getElementById("mobile-panel");
if (mobilePanel && mobilePanel.classList.contains("open")) return false;
+68
View File
@@ -0,0 +1,68 @@
// retoor <retoor@molodetz.nl>
export class EnterSubmit {
static enabled() {
return document.body.dataset.enterToSubmit !== "0";
}
static mentionOpen(textarea) {
const wrap = textarea.closest(".mention-wrapper");
const dropdown = wrap ? wrap.querySelector(".mention-dropdown") : null;
return !!dropdown && dropdown.offsetParent !== null && dropdown.children.length > 0;
}
static submit(textarea) {
const form = textarea.closest("form");
if (form && form.requestSubmit) form.requestSubmit();
}
static attach(textarea, onSubmit, canSubmit) {
if (!textarea || textarea.dataset.enterSubmitAttached) return;
textarea.dataset.enterSubmitAttached = "1";
const send = onSubmit || (() => EnterSubmit.submit(textarea));
textarea.addEventListener("keydown", (event) => {
if (event.isComposing || event.keyCode === 229) return;
if (event.key !== "Enter") return;
if (event.shiftKey) return;
if (event.ctrlKey || event.metaKey) {
event.preventDefault();
send();
return;
}
if (EnterSubmit.mentionOpen(textarea)) return;
if (canSubmit && !canSubmit()) return;
if (!EnterSubmit.enabled()) return;
event.preventDefault();
send();
});
}
static attachCtrlEnter(textarea) {
if (!textarea || textarea.dataset.ctrlEnterAttached) return;
textarea.dataset.ctrlEnterAttached = "1";
textarea.addEventListener("keydown", (event) => {
if (event.isComposing || event.keyCode === 229) return;
if (event.key !== "Enter") return;
if (event.ctrlKey || event.metaKey) {
event.preventDefault();
EnterSubmit.submit(textarea);
}
});
}
static attachComments(root) {
(root || document)
.querySelectorAll(".comment-form textarea[name='content']")
.forEach((textarea) => EnterSubmit.attach(textarea));
}
static attachEditors(root) {
(root || document)
.querySelectorAll("textarea:not(.hidden-textarea):not([data-enter-editor-skip])")
.forEach((textarea) => {
if (textarea.closest(".comment-form")) return;
if (textarea.closest(".note-editor")) return;
EnterSubmit.attachCtrlEnter(textarea);
});
}
}
+10 -1
View File
@@ -113,8 +113,17 @@ export class ModalManager {
modal._a11yOpen = true;
modal._lastFocus = document.activeElement;
modal.addEventListener("keydown", trap);
const preferred = modal.querySelector("[data-autofocus]");
const items = this.focusable(modal);
if (items.length) setTimeout(() => items[0].focus(), 20);
const target = preferred || items[0];
if (target) {
setTimeout(() => {
if (!modal.isConnected || !modal.classList.contains("visible")) return;
const active = document.activeElement;
if (active && modal.contains(active)) return;
target.focus();
}, 20);
}
} else if (!visible && modal._a11yOpen) {
modal._a11yOpen = false;
modal.removeEventListener("keydown", trap);
+16 -4
View File
@@ -22,6 +22,7 @@ export class ChatSocket {
this._settled = false;
this._backoff = INITIAL_BACKOFF_MS;
this._pingId = null;
this._reconnectTimer = null;
}
connect() {
@@ -34,6 +35,7 @@ export class ChatSocket {
}
_open() {
if (!this._shouldRun) return;
this._settled = false;
const socket = new WebSocket(this.url);
this.socket = socket;
@@ -61,16 +63,14 @@ export class ChatSocket {
const wrongWorker = !this._settled && event.code === WRONG_WORKER_CODE;
this._settled = false;
if (wrongWorker) {
if (this._shouldRun) {
window.setTimeout(() => this._open(), WRONG_WORKER_RETRY_MS);
}
if (this._shouldRun) this._scheduleReconnect(WRONG_WORKER_RETRY_MS);
return;
}
this._emit("onClose", event);
if (this._shouldRun) {
const delay = this._backoff;
this._backoff = Math.min(this._backoff * 2, MAX_BACKOFF_MS);
window.setTimeout(() => this._open(), delay);
this._scheduleReconnect(delay);
}
});
@@ -88,9 +88,21 @@ export class ChatSocket {
close() {
this._shouldRun = false;
this._stopPing();
if (this._reconnectTimer) {
window.clearTimeout(this._reconnectTimer);
this._reconnectTimer = null;
}
if (this.socket) this.socket.close();
}
_scheduleReconnect(delay) {
if (this._reconnectTimer) window.clearTimeout(this._reconnectTimer);
this._reconnectTimer = window.setTimeout(() => {
this._reconnectTimer = null;
if (this._shouldRun) this._open();
}, delay);
}
_startPing() {
this._stopPing();
this._pingId = window.setInterval(() => {
+29 -13
View File
@@ -12,6 +12,7 @@ import { DomUtils } from "../DomUtils.js";
import { ListNav } from "../ListNav.js";
import { contentRenderer } from "../ContentRenderer.js";
import { PubSubClient } from "../PubSubClient.js";
import { EnterSubmit } from "../EnterSubmit.js";
import { PresenceManager } from "../PresenceManager.js";
const CHAT_CSS_ID = "chat-css";
@@ -117,7 +118,9 @@ export class AppChat extends Component {
}
disconnectedCallback() {
this._left = true;
if (this.socket) this.socket.close();
this.socket = null;
if (this._scrollWatcher) this._scrollWatcher.disconnect();
if (this._viewportIO) this._viewportIO.disconnect();
if (this._resizeObserver) this._resizeObserver.disconnect();
@@ -127,6 +130,7 @@ export class AppChat extends Component {
}
if (this._onWindowFocus) window.removeEventListener("focus", this._onWindowFocus);
if (this._onVisibilityChange) document.removeEventListener("visibilitychange", this._onVisibilityChange);
if (this._onSearchOutsideClick) document.removeEventListener("click", this._onSearchOutsideClick);
clearTimeout(this._typingHideTimer);
clearTimeout(this._disconnectTimer);
cancelAnimationFrame(this._autoGrowFrame);
@@ -286,12 +290,11 @@ export class AppChat extends Component {
this._setToolsOpen(!this.form.classList.contains("tools-open"));
});
}
this.input.addEventListener("keydown", (event) => {
if (event.key === "Enter" && !event.shiftKey && !this._isCoarse()) {
event.preventDefault();
this.form.requestSubmit();
}
});
EnterSubmit.attach(
this.input,
() => this.form.requestSubmit(),
() => !this._isCoarse()
);
this.input.addEventListener("input", () => {
if (!this._supportsFieldSizing) this._scheduleAutoGrow();
if (this.input.value.trim()) this._collapseTools();
@@ -695,14 +698,25 @@ export class AppChat extends Component {
}
async _connect() {
if (this._left || !this.isConnected) return;
if (this.hub) {
this.socket = this.hub.subscribe(this._socketHandlers());
const channel = this.hub.subscribe(this._socketHandlers());
if (this._left || !this.isConnected) {
channel.close();
return;
}
this.socket = channel;
return;
}
const url = await this._resolveWsUrl();
if (!url) return;
this.socket = new ChatSocket(url, this._socketHandlers());
this.socket.connect();
if (!url || this._left || !this.isConnected) return;
const socket = new ChatSocket(url, this._socketHandlers());
socket.connect();
if (this._left || !this.isConnected) {
socket.close();
return;
}
this.socket = socket;
}
_socketHandlers() {
@@ -800,6 +814,7 @@ export class AppChat extends Component {
_threadIsActive() {
if (!this.withUid) return false;
if (document.visibilityState !== "visible") return false;
if (!this._isMobile()) return true;
return this._activePane === "thread";
}
@@ -993,7 +1008,7 @@ export class AppChat extends Component {
_bindActiveConversation() {
this._onWindowFocus = () => this._sendActiveMarker();
this._onVisibilityChange = () => {
if (document.visibilityState === "visible") this._sendActiveMarker();
if (document.visibilityState === "visible") this._markRead();
};
window.addEventListener("focus", this._onWindowFocus);
document.addEventListener("visibilitychange", this._onVisibilityChange);
@@ -1661,9 +1676,10 @@ export class AppChat extends Component {
if (uid) this._openConversation(uid, true);
});
document.addEventListener("click", (event) => {
this._onSearchOutsideClick = (event) => {
if (!wrap.contains(event.target)) hide();
});
};
document.addEventListener("click", this._onSearchOutsideClick);
}
_initPresence() {
+91 -18
View File
@@ -10,7 +10,7 @@ import { ConversationItem } from "../chat/ConversationItem.js";
const MOBILE_BREAKPOINT_PX = 768;
const WINDOW_SLOT_PX = 336;
const DOCK_RESERVED_PX = 96;
const DOCK_RESERVED_PX = 160;
const MAX_OPEN_WINDOWS = 3;
const MAX_ENTRIES = 8;
const MAX_SEEN_FRAMES = 500;
@@ -30,6 +30,11 @@ export class AppChatDock extends Component {
this.conversations = null;
this.panelOpen = false;
this._resizeFrame = null;
this._searchTimers = new Set();
this._onDocumentClick = null;
this._onDocumentKeydown = null;
this._onWindowResize = null;
this._onLogoutClick = null;
}
connectedCallback() {
@@ -44,16 +49,42 @@ export class AppChatDock extends Component {
this._buildTray();
this._bindDocument();
this._bindToggles();
this._bindLogout();
this.entries = this._restore();
if (!this._isMobile()) this._enforceLimits();
this._render();
this._loadConversations();
}
disconnectedCallback() {
for (const entry of this.windows.values()) entry.section.remove();
this.windows.clear();
this.heads.clear();
if (this.channel) this.channel.close();
this.channel = null;
if (this._onDocumentClick) document.removeEventListener("click", this._onDocumentClick);
if (this._onDocumentKeydown) document.removeEventListener("keydown", this._onDocumentKeydown);
if (this._onWindowResize) window.removeEventListener("resize", this._onWindowResize);
if (this._onLogoutClick) {
document.querySelectorAll("a[href='/auth/logout']").forEach((link) => {
link.removeEventListener("click", this._onLogoutClick);
});
}
if (this._resizeFrame) cancelAnimationFrame(this._resizeFrame);
this._resizeFrame = null;
for (const timer of this._searchTimers) window.clearTimeout(timer);
this._searchTimers.clear();
}
_bindLogout() {
this._onLogoutClick = () => {
try {
window.sessionStorage.removeItem(this._storageKey());
} catch {}
};
document.querySelectorAll("a[href='/auth/logout']").forEach((link) => {
link.addEventListener("click", this._onLogoutClick);
});
}
open(user, { focus = true } = {}) {
@@ -161,9 +192,7 @@ export class AppChatDock extends Component {
_persist() {
try {
window.sessionStorage.setItem(this._storageKey(), JSON.stringify(this.entries));
} catch {
/* storage unavailable: the dock still works for this page */
}
} catch {}
}
_render() {
@@ -211,7 +240,9 @@ export class AppChatDock extends Component {
_onFrame(frame) {
if (!frame || frame.type !== "message" || !frame.uid || frame.sender_uid === this.selfUid) return;
if (this.seenFrames.has(frame.uid)) return;
if (this.seenFrames.size >= MAX_SEEN_FRAMES) this.seenFrames.clear();
if (this.seenFrames.size >= MAX_SEEN_FRAMES) {
this.seenFrames.delete(this.seenFrames.values().next().value);
}
this.seenFrames.add(frame.uid);
const entry = this.entries.find((item) => item.uid === frame.sender_uid);
if (!entry || !entry.minimized) return;
@@ -304,7 +335,7 @@ export class AppChatDock extends Component {
const results = document.createElement("div");
results.className = "chat-compose-results";
results.setAttribute("role", "listbox");
results.setAttribute("role", "list");
results.setAttribute("aria-label", "People");
section.append(header, to, results);
@@ -405,7 +436,7 @@ export class AppChatDock extends Component {
this.panelList = document.createElement("div");
this.panelList.className = "chat-panel-list";
this.panelList.setAttribute("role", "listbox");
this.panelList.setAttribute("role", "list");
this.panelList.setAttribute("aria-label", "Conversations");
const footer = document.createElement("a");
@@ -433,7 +464,10 @@ export class AppChatDock extends Component {
let timer = null;
let sequence = 0;
input.addEventListener("input", () => {
clearTimeout(timer);
if (timer) {
window.clearTimeout(timer);
this._searchTimers.delete(timer);
}
const query = input.value.trim();
sequence += 1;
if (!query) {
@@ -442,6 +476,7 @@ export class AppChatDock extends Component {
}
const token = sequence;
timer = window.setTimeout(async () => {
this._searchTimers.delete(timer);
let results = [];
try {
const data = await Http.getJson(`${this.searchUrl}?q=${encodeURIComponent(query)}`);
@@ -454,6 +489,7 @@ export class AppChatDock extends Component {
nav.opened();
if (results.length) nav.setActive(0);
}, SEARCH_DEBOUNCE_MS);
this._searchTimers.add(timer);
});
list.addEventListener("click", (event) => {
const item = event.target.closest(".conversation-item");
@@ -489,9 +525,29 @@ export class AppChatDock extends Component {
} catch {
this.conversations = this.conversations || [];
}
this._reconcileUnread();
if (this.panelOpen && !this.searchInput.value.trim()) this._showConversations();
}
_reconcileUnread() {
if (!Array.isArray(this.conversations)) return;
const server = new Map(
this.conversations.map((conv) => [(conv.other_user || {}).uid, !!conv.unread]),
);
let changed = false;
for (const entry of this.entries) {
if (!server.has(entry.uid)) continue;
const unread = server.get(entry.uid);
const next = entry.minimized && unread ? Math.max(1, entry.unread || 0) : 0;
if (next === (entry.unread || 0)) continue;
entry.unread = next;
changed = true;
const head = this.heads.get(entry.uid);
if (head) this._updateHead(head, entry);
}
if (changed) this._persist();
}
_openPanel() {
this.panelOpen = true;
this.panel.hidden = false;
@@ -531,7 +587,7 @@ export class AppChatDock extends Component {
}
_bindDocument() {
document.addEventListener("click", (event) => {
this._onDocumentClick = (event) => {
const toggle = event.target.closest("[data-chat-panel-toggle]");
if (toggle) {
if (!this._intercepts(event)) return;
@@ -551,14 +607,30 @@ export class AppChatDock extends Component {
return;
}
if (this.panelOpen && !this.panel.contains(event.target)) this._closePanel();
});
document.addEventListener("keydown", (event) => {
if (event.key !== "Escape" || !this.panelOpen) return;
this._closePanel();
const toggle = this._toggles()[0];
if (toggle) toggle.focus();
});
window.addEventListener("resize", () => {
};
document.addEventListener("click", this._onDocumentClick);
this._onDocumentKeydown = (event) => {
if (event.key !== "Escape") return;
if (this.panelOpen) {
this._closePanel();
const toggle = this._toggles()[0];
if (toggle) toggle.focus();
return;
}
if (this.compose && this.compose.contains(event.target)) {
this.closeCompose();
return;
}
if (event.target instanceof HTMLTextAreaElement) return;
if (this.compose) {
this.closeCompose();
return;
}
const expanded = this.entries.find((entry) => !entry.minimized);
if (expanded) this.minimize(expanded.uid);
};
document.addEventListener("keydown", this._onDocumentKeydown);
this._onWindowResize = () => {
cancelAnimationFrame(this._resizeFrame);
this._resizeFrame = requestAnimationFrame(() => {
if (this._isMobile()) {
@@ -569,7 +641,8 @@ export class AppChatDock extends Component {
}
this._render();
});
});
};
window.addEventListener("resize", this._onWindowResize);
}
}
@@ -70,7 +70,7 @@ export class AppDeepsearchChat extends Component {
this._submit(this.field.value);
});
this.field.addEventListener("keydown", (event) => {
if (event.key === "Enter" && !event.shiftKey) {
if (event.key === "Enter" && !event.shiftKey && !event.isComposing && event.keyCode !== 229) {
event.preventDefault();
this._submit(this.field.value);
}
@@ -71,7 +71,7 @@ export class AppDocsChat extends Component {
this._submit(this.field.value);
});
this.field.addEventListener("keydown", (event) => {
if (event.key === "Enter" && !event.shiftKey) {
if (event.key === "Enter" && !event.shiftKey && !event.isComposing && event.keyCode !== 229) {
event.preventDefault();
this._submit(this.field.value);
}
+13 -3
View File
@@ -25,13 +25,23 @@ self.addEventListener("activate", (event) => {
);
});
async function navigationResponse(request) {
try {
return await fetch(request.clone());
} catch (error) {
try {
return await fetch(request);
} catch (again) {
return caches.match(OFFLINE_URL);
}
}
}
self.addEventListener("fetch", (event) => {
if (event.request.mode !== "navigate") {
return;
}
event.respondWith(
fetch(event.request).catch(() => caches.match(OFFLINE_URL))
);
event.respondWith(navigationResponse(event.request));
});
function isClientOpen(url) {
+1 -1
View File
@@ -99,7 +99,7 @@ The three public listings (`/feed`, `/gists`, `/projects`) share one search box:
## 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.
- 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, and leaves focus alone when a field inside the modal is already focused. 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`)
+1 -1
View File
@@ -1,3 +1,3 @@
<button type="button" class="post-action-btn bookmark-btn{% if _bookmarked %} bookmarked{% endif %}" data-bookmark-type="{{ _type }}" data-bookmark-uid="{{ _uid }}" title="Save" aria-label="Save" aria-pressed="{% if _bookmarked %}true{% else %}false{% endif %}"{{ guest_disabled(user) }}>
<button type="button" class="post-action-btn bookmark-btn{% if _bookmarked %} bookmarked{% endif %}" data-bookmark-type="{{ _type }}" data-bookmark-uid="{{ _uid }}" title="Save" aria-label="Save" aria-pressed="{% if _bookmarked %}true{% else %}false{% endif %}"{{ guest_disabled(user) }}{% if _menu_action is defined and _menu_action %} data-menu-action{% endif %}>
<span class="bookmark-icon">&#x1F516;</span> <span class="bookmark-label">{% if _bookmarked %}Saved{% else %}Save{% endif %}</span>
</button>
+15 -10
View File
@@ -47,16 +47,21 @@
<a href="{{ content_url(item.post, 'posts') }}" class="post-action-btn share">
<span aria-hidden="true">&#x2197;&#xFE0E;</span> Open
</a>
{% if _show_share %}
<button type="button" class="post-action-btn" data-share="{{ content_url(item.post, 'posts') }}"><span aria-hidden="true">&#x1F517;</span> Share</button>
{% endif %}
{% set _type = "post" %}{% set _uid = item.post['uid'] %}{% set _bookmarked = item.bookmarked %}{% include "_bookmark_button.html" %}
{% set _type = "post" %}{% set _uid = item.post['uid'] %}{% set _owner = item.post['user_uid'] %}{% set _owner_name = (item.author or {}).get('username', '') %}{% set _class = "post-action-btn" %}{% include "_report_button.html" %}
{% if owns(item.post, user) or is_admin(user) %}
<form method="POST" action="/posts/delete/{{ item.post['slug'] or item.post['uid'] }}" class="inline-form">
<button type="submit" class="post-action-btn" data-confirm="Delete this post?"><span aria-hidden="true">🗑️</span> Delete</button>
</form>
{% endif %}
<dp-action-menu class="post-actions-menu">
<button type="button" class="post-action-btn" data-action-menu-trigger aria-haspopup="menu" aria-expanded="false" aria-label="More actions"><span aria-hidden="true">&#x22EF;</span> More</button>
<div class="action-menu-panel" data-action-menu-panel popover hidden>
{% if _show_share %}
<button type="button" class="post-action-btn" data-share="{{ content_url(item.post, 'posts') }}" data-menu-action><span aria-hidden="true">&#x1F517;</span> Share</button>
{% endif %}
{% set _type = "post" %}{% set _uid = item.post['uid'] %}{% set _bookmarked = item.bookmarked %}{% set _menu_action = true %}{% include "_bookmark_button.html" %}{% set _menu_action = false %}
{% set _type = "post" %}{% set _uid = item.post['uid'] %}{% set _owner = item.post['user_uid'] %}{% set _owner_name = (item.author or {}).get('username', '') %}{% set _class = "post-action-btn" %}{% set _menu_action = true %}{% include "_report_button.html" %}{% set _menu_action = false %}
{% if owns(item.post, user) or is_admin(user) %}
<form method="POST" action="/posts/delete/{{ item.post['slug'] or item.post['uid'] }}" class="inline-form">
<button type="submit" class="post-action-btn" data-confirm="Delete this post?" data-menu-action><span aria-hidden="true">🗑️</span> Delete</button>
</form>
{% endif %}
</div>
</dp-action-menu>
</div>
{% if item.recent_comments %}
@@ -1,4 +1,10 @@
<form id="create-post-form" method="POST" action="/posts/create" enctype="multipart/form-data">
<div class="auth-field auth-field-gap">
<label for="post-title">Title (optional)</label>
<input type="text" id="post-title" name="title" maxlength="500" placeholder="Post title" data-autofocus>
<small class="hint-text"><span id="post-title-count">0/500</span></small>
</div>
{% set _topics = TOPICS %}{% set _selected = _composer_topic or 'random' %}{% include "_topic_selector.html" %}
<div class="auth-field auth-field-gap">
@@ -7,12 +13,6 @@
<small class="hint-text"><span id="post-content-count">0/125000</span></small>
</div>
<div class="auth-field auth-field-gap">
<label for="post-title">Title (optional)</label>
<input type="text" id="post-title" name="title" maxlength="500" placeholder="Post title">
<small class="hint-text"><span id="post-title-count">0/500</span></small>
</div>
<div class="auth-field auth-field-gap">
<label for="project_uid">Link to Project (Optional)</label>
<select id="project_uid" name="project_uid">
+6 -1
View File
@@ -44,7 +44,12 @@
<span aria-hidden="true">&#x1F4AC;</span>{% if user %} {{ item.comment_count }}{% endif %}
</a>
{% set _type = "quiz" %}{% set _uid = item.uid %}{% set _reactions = item.reactions %}{% include "_reaction_bar.html" %}
{% set _type = "quiz" %}{% set _uid = item.uid %}{% set _bookmarked = item.bookmarked %}{% include "_bookmark_button.html" %}
<dp-action-menu class="post-actions-menu">
<button type="button" class="post-action-btn" data-action-menu-trigger aria-haspopup="menu" aria-expanded="false" aria-label="More actions"><span aria-hidden="true">&#x22EF;</span> More</button>
<div class="action-menu-panel" data-action-menu-panel popover hidden>
{% set _type = "quiz" %}{% set _uid = item.uid %}{% set _bookmarked = item.bookmarked %}{% set _menu_action = true %}{% include "_bookmark_button.html" %}{% set _menu_action = false %}
</div>
</dp-action-menu>
{% if item.viewer_state == 'in_progress' and item.viewer_attempt_uid %}
<a href="{{ item.url }}/attempts/{{ item.viewer_attempt_uid }}" class="post-action-btn quiz-card-cta">Resume</a>
{% elif item.viewer_state == 'done' %}
@@ -94,7 +94,7 @@
</div>
<div class="gw-field">
<label for="gw-model-vision-model">Vision model</label>
<input type="text" id="gw-model-vision-model" name="vision_model" placeholder="(optional) google/gemma-3-12b-it" value="{{ form.vision_model }}">
<input type="text" id="gw-model-vision-model" name="vision_model" placeholder="(optional) google/gemma-4-31b-it" value="{{ form.vision_model }}">
</div>
</div>
</fieldset>
+2 -2
View File
@@ -67,7 +67,7 @@
</script>
{% endif %}
</head>
<body data-user-uid="{{ user['uid'] if user else '' }}">
<body data-user-uid="{{ user['uid'] if user else '' }}" data-enter-to-submit="{{ 0 if user and user.get('enter_to_submit') == 0 else 1 }}">
<a class="skip-link" href="#main-content">Skip to main content</a>
<nav class="topnav" aria-label="Primary">
<div class="topnav-inner">
@@ -92,7 +92,7 @@
</a>
{% if user %}
{% set msg_unread = get_unread_messages(user["uid"]) %}
<a href="/messages" class="topnav-icon {{ nav_active(request, '/messages') }}" data-counter="messages" data-counter-noun="messages" data-chat-panel-toggle title="Messages" aria-label="{% if msg_unread %}{{ msg_unread }} unread messages{% else %}Messages, no unread{% endif %}">
<a href="/messages" class="topnav-icon {{ nav_active(request, '/messages') }}" data-counter="messages" data-counter-noun="messages" data-chat-panel-toggle title="Messages" aria-haspopup="dialog" aria-controls="chat-panel" aria-expanded="false" aria-label="{% if msg_unread %}{{ msg_unread }} unread messages{% else %}Messages, no unread{% endif %}">
<span class="nav-bell" aria-hidden="true">✉️<span class="nav-badge" data-counter-badge {% if msg_unread == 0 %}hidden{% endif %}>{{ msg_unread }}</span></span>
</a>
<button type="button" class="topnav-icon" data-push-enable hidden title="Enable push notifications" aria-label="Enable push notifications">
@@ -30,7 +30,8 @@ Source: `static/js/devii/devii-terminal.js`.
## Usage
Any element marked `data-devii-open` opens the terminal (the controller delegates these clicks),
so you rarely instantiate it directly:
so you rarely instantiate it directly. Escape and a double-click on empty page space open it too,
except while a modal, dialog, context menu, or popover is open, and except while focus is in a field:
```html
&lt;button data-devii-open&gt;Ask Devii&lt;/button&gt;
@@ -0,0 +1,43 @@
<div class="docs-content" data-render>
# dp-action-menu
The overflow ("More") menu for content action bars. Every content detail page and card (posts,
projects, gists, news, quizzes) keeps its voting, reactions, main call to action and private note in
the bar, and groups the rest (share, save, report, block, edit, delete) into this one menu.
Source: `static/js/components/AppActionMenu.js`. Registered as `dp-action-menu` on every page.
The markup lives in the light DOM: the trigger is a real button with `data-action-menu-trigger`, the
panel is a `popover` with `data-action-menu-panel`, and the actions inside stay real buttons, links
and forms, so existing confirm, modal and submit handlers keep working. Items marked
`data-menu-action` close the panel when chosen, and Escape closes it. If the panel has no actions,
the trigger hides itself. Panels on cards must not hardcode ids; the component generates them.
Without JavaScript the panel stays hidden, the same trade-off as the profile and project menus.
## Usage
```html
&lt;dp-action-menu&gt;
&lt;button type="button" data-action-menu-trigger aria-haspopup="menu" aria-expanded="false"&gt;More&lt;/button&gt;
&lt;div class="action-menu-panel" data-action-menu-panel popover hidden&gt;
&lt;button type="button" data-menu-action&gt;Share&lt;/button&gt;
&lt;/div&gt;
&lt;/dp-action-menu&gt;
```
</div>
<div class="component-demo">
<div class="component-demo-title">Live example</div>
<div class="component-demo-stage">
<dp-action-menu>
<button type="button" class="btn btn-secondary btn-sm" data-action-menu-trigger aria-haspopup="menu" aria-expanded="false">More</button>
<div class="action-menu-panel" data-action-menu-panel popover hidden>
<button type="button" data-menu-action>Share</button>
<button type="button" data-menu-action>Save</button>
</div>
</dp-action-menu>
</div>
</div>
<script type="module">
import "{{ static_url('/static/js/components/AppActionMenu.js') }}";
</script>
@@ -58,6 +58,21 @@ longer follows later changes to the default.
Use **Reset to defaults** at the bottom of the tab to clear all of your choices and return to the
platform defaults.
## Grouping similar notifications
The tab also carries two switches of its own. **Group similar notifications** (on by default) folds
repeated events into one card on the `/notifications` page: upvotes on the same post become one card,
messages from the same person become one card, and the unread badge counts cards, not individual
events. Turn it off to get one card and one badge count per event. **Throttle repeat alerts** (also on
by default) sends at most one push, one Telegram message, and one live toast per group of similar
events per 5 minutes. In-app notifications are never throttled: every event still lands on the page,
it just does not ping you every time. Turn it off to be alerted on every event. The two switches are
independent.
Your profile page also carries a **Keyboard** setting, **Enter to send** (on by default). With it on,
Enter posts a comment or sends a direct message, and Shift+Enter starts a new line. In long editors
(posts, gists, quiz answers) Enter keeps starting new lines and Ctrl+Enter submits instead.
## Turning push on
Toggling **Push** for a type only takes effect once you have enabled push notifications on the device
+3
View File
@@ -23,6 +23,9 @@ There are three ways to make one, and they all end at the same place:
3. **The API**, by POSTing one JSON document to `/quizzes/import`. This is the same call Devii
makes.
Free-text answers are long editors: Enter starts a new line there, and the answer is sent with the
attempt's submit button (Ctrl+Enter also submits the enclosing form).
## Publishing is permanent
A draft is fully editable. The moment you publish it, the quiz, its questions and its options are
@@ -36,7 +36,7 @@ Chat requests are augmented (vision), forwarded, retried, priced, and ledgered.
**Prompt:** `gateway_system_preamble` (multiline text, default empty) - operator text prepended ahead of every chat request's system message (see "System-message composition" below). `gateway_thinking` (bool, default off) - when off, the gateway disables model thinking on every chat call unless the client explicitly enables it; when on, thinking is enabled unless the client disables it (see "Thinking default" below).
**Vision:** `gateway_vision_enabled` (default on), `gateway_vision_url` (OpenRouter by default), `gateway_vision_model` (`google/gemma-3-12b-it`), `gateway_vision_key` (auto-migrated from `OPENROUTER_API_KEY`), `gateway_vision_cache_size` (LRU entries, default 256, 0 disables).
**Vision:** `gateway_vision_enabled` (default on), `gateway_vision_url` (OpenRouter by default), `gateway_vision_model` (`google/gemma-4-31b-it`), `gateway_vision_key` (auto-migrated from `OPENROUTER_API_KEY`), `gateway_vision_cache_size` (LRU entries, default 256, 0 disables).
**Images:** `gateway_image_enabled` (default on), `gateway_image_url` (OpenRouter by default), `gateway_image_model` (`black-forest-labs/flux-1.1-pro`), `gateway_image_key` (falls back to `gateway_api_key` / `OPENROUTER_API_KEY`).
@@ -63,7 +63,7 @@ Use these four breakpoints. They are `max-width` (desktop-first refinements) and
@media (hover: none) and (pointer: coarse) {
.btn, .topnav-link, .sidebar-link, .post-action-btn, .profile-tab { min-height: 44px; }
.topnav-icon, .emoji-toggle-btn { min-width: 44px; min-height: 44px; }
.modal-card input, .modal-card textarea, .modal-card select { font-size: 16px; }
.modal-card input, .modal-card textarea, .modal-card select, .comment-form textarea { font-size: 16px; }
}
```
+17 -12
View File
@@ -62,24 +62,29 @@
{% endif %}
<div class="gist-detail-actions">
<button type="button" class="gist-star-btn" data-share="/gists/{{ gist['slug'] or gist['uid'] }}"><span class="icon">&#x1F517;</span><span class="label"> Share</span></button>
{% if user %}
{% set _type = "gist" %}{% set _uid = gist['uid'] %}{% set _my_vote = my_vote %}{% set _count = star_count %}{% set _btn_class = "gist-star-btn" %}{% include "_star_vote.html" %}
{% endif %}
{% set _type = "gist" %}{% set _uid = gist['uid'] %}{% set _bookmarked = bookmarked %}{% include "_bookmark_button.html" %}
{% set _type = "gist" %}{% set _uid = gist['uid'] %}{% set _reactions = reactions %}{% include "_reaction_bar.html" %}
{% if user %}
{% set _type = "gist" %}{% set _uid = gist['uid'] %}{% set _note = note_content %}{% include "_note_button.html" %}
{% endif %}
{% set _type = "gist" %}{% set _uid = gist['uid'] %}{% set _owner = gist['user_uid'] %}{% set _owner_name = (author or {}).get('username', '') %}{% set _class = "gist-star-btn" %}{% include "_report_button.html" %}
{% if is_owner %}
<button type="button" class="gist-star-btn" data-modal="edit-gist-modal"><span class="icon">&#x270F;&#xFE0F;</span><span class="label">Edit</span></button>
{% endif %}
{% if is_owner or is_admin(user) %}
<form method="POST" action="/gists/delete/{{ gist['slug'] or gist['uid'] }}" class="inline-form">
<button type="submit" class="gist-star-btn" data-confirm="Delete this gist?"><span class="icon">&#x1F5D1;&#xFE0F;</span><span class="label">Delete</span></button>
</form>
{% endif %}
{% set _type = "gist" %}{% set _uid = gist['uid'] %}{% set _reactions = reactions %}{% include "_reaction_bar.html" %}
<dp-action-menu class="gist-actions-menu">
<button type="button" class="gist-star-btn" data-action-menu-trigger aria-haspopup="menu" aria-expanded="false" aria-controls="gist-actions-panel" aria-label="More actions"><span class="icon">&#x22EF;</span><span class="label"> More</span></button>
<div class="action-menu-panel" id="gist-actions-panel" data-action-menu-panel popover hidden>
<button type="button" class="gist-star-btn" data-share="/gists/{{ gist['slug'] or gist['uid'] }}" data-menu-action><span class="icon">&#x1F517;</span><span class="label"> Share</span></button>
{% set _type = "gist" %}{% set _uid = gist['uid'] %}{% set _bookmarked = bookmarked %}{% set _menu_action = true %}{% include "_bookmark_button.html" %}{% set _menu_action = false %}
{% set _type = "gist" %}{% set _uid = gist['uid'] %}{% set _owner = gist['user_uid'] %}{% set _owner_name = (author or {}).get('username', '') %}{% set _class = "gist-star-btn" %}{% set _menu_action = true %}{% include "_report_button.html" %}{% set _menu_action = false %}
{% if is_owner %}
<button type="button" class="gist-star-btn" data-modal="edit-gist-modal" data-menu-action><span class="icon">&#x270F;&#xFE0F;</span><span class="label">Edit</span></button>
{% endif %}
{% if is_owner or is_admin(user) %}
<form method="POST" action="/gists/delete/{{ gist['slug'] or gist['uid'] }}" class="inline-form">
<button type="submit" class="gist-star-btn" data-confirm="Delete this gist?" data-menu-action><span class="icon">&#x1F5D1;&#xFE0F;</span><span class="label">Delete</span></button>
</form>
{% endif %}
</div>
</dp-action-menu>
</div>
</article>
+1 -1
View File
@@ -105,7 +105,7 @@
<form method="POST" action="/gists/create">
<div class="auth-field auth-field-gap">
<label for="gist-title">Title</label>
<input type="text" id="gist-title" name="title" required maxlength="200" placeholder="Gist title">
<input type="text" id="gist-title" name="title" required maxlength="200" placeholder="Gist title" data-autofocus>
</div>
<div class="auth-field auth-field-gap">
+1 -1
View File
@@ -68,7 +68,7 @@
<p class="issues-modal-hint">Your report is improved by AI into a consistent ticket and filed on the tracker.</p>
<div class="auth-field auth-field-gap">
<label for="issue-title">Title</label>
<input type="text" id="issue-title" name="title" required aria-required="true" maxlength="200" placeholder="Brief description of the issue">
<input type="text" id="issue-title" name="title" required aria-required="true" maxlength="200" placeholder="Brief description of the issue" data-autofocus>
</div>
<div class="auth-field auth-field-gap">
<label for="issue-description">Description</label>
+8 -3
View File
@@ -44,12 +44,17 @@
<a href="{{ article['url'] }}" target="_blank" rel="noopener" class="news-detail-read-link">
Read on {{ article['source_name'] }} &#x2197;
</a>
<button type="button" class="news-detail-back" data-share="/news/{{ article['slug'] or article['uid'] }}">&#x1F517; Share</button>
{% set _type = "news" %}{% set _uid = article['uid'] %}{% set _bookmarked = bookmarked %}{% include "_bookmark_button.html" %}
{% if user %}
{% set _type = "news" %}{% set _uid = article['uid'] %}{% set _note = note_content %}{% include "_note_button.html" %}
{% endif %}
{% set _type = "news" %}{% set _uid = article['uid'] %}{% set _owner = "" %}{% set _owner_name = "" %}{% set _class = "news-detail-back" %}{% include "_report_button.html" %}
<dp-action-menu class="news-actions-menu">
<button type="button" class="news-detail-back" data-action-menu-trigger aria-haspopup="menu" aria-expanded="false" aria-controls="news-actions-panel" aria-label="More actions">&#x22EF; More</button>
<div class="action-menu-panel" id="news-actions-panel" data-action-menu-panel popover hidden>
<button type="button" class="news-detail-back" data-share="/news/{{ article['slug'] or article['uid'] }}" data-menu-action>&#x1F517; Share</button>
{% set _type = "news" %}{% set _uid = article['uid'] %}{% set _bookmarked = bookmarked %}{% set _menu_action = true %}{% include "_bookmark_button.html" %}{% set _menu_action = false %}
{% set _type = "news" %}{% set _uid = article['uid'] %}{% set _owner = "" %}{% set _owner_name = "" %}{% set _class = "news-detail-back" %}{% set _menu_action = true %}{% include "_report_button.html" %}{% set _menu_action = false %}
</div>
</dp-action-menu>
<a href="/news" class="news-detail-back">&larr; Back to News</a>
</div>
</div>
+22
View File
@@ -18,6 +18,27 @@
{% for group in notification_groups %}
<div class="notification-group">
<div class="notification-group-label">{{ group.label }}</div>
{% if grouping %}
{% for item in group.event_entries %}
{% set latest = item.latest %}
<div class="notification-card card-link-host {% if item.unread %}unread{% endif %}" role="listitem" data-notification-group="{{ item.key }}">
{% if item.unread %}<span class="sr-only">Unread notification. </span>{% endif %}
{% set _href = "/notifications/open/" ~ latest.notification['uid'] %}
{% set _label = latest.notification['message'] %}
{% with _chat_user = latest.actor if latest.notification['type'] == 'message' else none %}{% include "_card_link.html" %}{% endwith %}
<span class="notif-icon-fixed">
{% set _user = latest.actor %}{% set _size = 32 %}{% set _size_class = "sm" %}{% include "_avatar_link.html" %}
</span>
<div class="notification-body">
<div class="notification-text rendered-title">{{ render_title(latest.notification['message']) }}{% if item.count > 1 %} <span class="notif-group-count">&times;{{ item.count }}</span>{% endif %}</div>
<div class="notification-time">{{ dt_ago(latest.notification.created_at) if latest.notification.get('created_at') else latest.time_ago }}</div>
</div>
<form method="POST" action="/notifications/mark-read/{{ latest.notification['uid'] }}" class="inline-form">
<button type="submit" class="notification-dismiss" aria-label="Mark as read">&times;</button>
</form>
</div>
{% endfor %}
{% else %}
{% for item in group.entries %}
<div class="notification-card card-link-host {% if not item.notification['read'] %}unread{% endif %}" role="listitem">
{% if not item.notification['read'] %}<span class="sr-only">Unread notification. </span>{% endif %}
@@ -37,6 +58,7 @@
</form>
</div>
{% endfor %}
{% endif %}
</div>
{% else %}
<div class="empty-state">No notifications yet</div>
+19 -14
View File
@@ -107,32 +107,37 @@
<div class="post-detail-actions">
{% set _uid = post['uid'] %}{% set _my_vote = my_vote %}{% set _count = post.get('stars', 0) %}{% include "_post_votes.html" %}
{% set _type = "post" %}{% set _uid = post['uid'] %}{% set _reactions = reactions %}{% include "_reaction_bar.html" %}
<button type="button" class="post-action-btn" data-share="/posts/{{ post['slug'] or post['uid'] }}"><span class="icon">&#x1F517;</span><span class="label"> Share</span></button>
{% set _type = "post" %}{% set _uid = post['uid'] %}{% set _bookmarked = bookmarked %}{% include "_bookmark_button.html" %}
{% if user %}
{% set _type = "post" %}{% set _uid = post['uid'] %}{% set _note = note_content %}{% include "_note_button.html" %}
{% endif %}
{% set _type = "post" %}{% set _uid = post['uid'] %}{% set _owner = post['user_uid'] %}{% set _owner_name = (author or {}).get('username', '') %}{% set _class = "post-action-btn" %}{% include "_report_button.html" %}
{% if is_owner %}
<button type="button" class="post-action-btn" data-modal="edit-post-modal"><span class="icon">&#x270F;&#xFE0F;</span><span class="label">Edit</span></button>
{% endif %}
{% if is_owner or is_admin(user) %}
<form method="POST" action="/posts/delete/{{ post['slug'] or post['uid'] }}" class="inline-form">
<button type="submit" class="post-action-btn" data-confirm="Delete this post?"><span class="icon">&#x1F5D1;&#xFE0F;</span><span class="label">Delete</span></button>
</form>
{% endif %}
<dp-action-menu class="post-actions-menu">
<button type="button" class="post-action-btn" data-action-menu-trigger aria-haspopup="menu" aria-expanded="false" aria-controls="post-actions-panel" aria-label="More actions"><span class="icon">&#x22EF;</span><span class="label"> More</span></button>
<div class="action-menu-panel" id="post-actions-panel" data-action-menu-panel popover hidden>
<button type="button" class="post-action-btn" data-share="/posts/{{ post['slug'] or post['uid'] }}" data-menu-action><span class="icon">&#x1F517;</span><span class="label"> Share</span></button>
{% set _type = "post" %}{% set _uid = post['uid'] %}{% set _bookmarked = bookmarked %}{% set _menu_action = true %}{% include "_bookmark_button.html" %}{% set _menu_action = false %}
{% set _type = "post" %}{% set _uid = post['uid'] %}{% set _owner = post['user_uid'] %}{% set _owner_name = (author or {}).get('username', '') %}{% set _class = "post-action-btn" %}{% set _menu_action = true %}{% include "_report_button.html" %}{% set _menu_action = false %}
{% if is_owner %}
<button type="button" class="post-action-btn" data-modal="edit-post-modal" data-menu-action><span class="icon">&#x270F;&#xFE0F;</span><span class="label">Edit</span></button>
{% endif %}
{% if is_owner or is_admin(user) %}
<form method="POST" action="/posts/delete/{{ post['slug'] or post['uid'] }}" class="inline-form">
<button type="submit" class="post-action-btn" data-confirm="Delete this post?" data-menu-action><span class="icon">&#x1F5D1;&#xFE0F;</span><span class="label">Delete</span></button>
</form>
{% endif %}
</div>
</dp-action-menu>
</div>
</article>
{% if is_owner %}
{% call modal('edit-post-modal', 'Edit Post') %}
<form id="edit-post-form" method="POST" action="/posts/edit/{{ post['slug'] or post['uid'] }}">
{% set _topics = topics %}{% set _selected = post['topic'] %}{% include "_topic_selector.html" %}
{% set _visibility = visibility_of("posts", post) %}{% set _visibility_id = "edit-post-visibility" %}{% include "_visibility_field.html" %}
<div class="auth-field auth-field-gap">
<label for="edit-title">Title</label>
<input type="text" id="edit-title" name="title" maxlength="500" value="{{ post.get('title') or '' }}">
<input type="text" id="edit-title" name="title" maxlength="500" value="{{ post.get('title') or '' }}" data-autofocus>
</div>
{% set _topics = topics %}{% set _selected = post['topic'] %}{% include "_topic_selector.html" %}
{% set _visibility = visibility_of("posts", post) %}{% set _visibility_id = "edit-post-visibility" %}{% include "_visibility_field.html" %}
<div class="auth-field auth-field-gap">
<label for="edit-content">Content</label>
<textarea id="edit-content" name="content" required maxlength="125000" class="min-h-200" data-mention>{{ post['content'] }}</textarea>
+28
View File
@@ -214,6 +214,20 @@
</div>
<p class="customization-hint">Disabling hides your custom code without deleting it.</p>
</div>
<div class="customization-card" data-enter-to-submit-card data-username="{{ profile_user['username'] }}">
<div class="customization-head">
<span class="customization-title">Keyboard</span>
</div>
<div class="customization-row">
<span class="customization-label">Enter to send (Shift+Enter for a new line)</span>
<form method="POST" action="/profile/{{ profile_user['username'] }}/enter-to-submit">
<input type="hidden" name="value" value="{{ 0 if enter_to_submit else 1 }}">
<button type="submit" class="btn btn-sm {% if enter_to_submit %}btn-primary{% endif %}" data-confirm="{% if enter_to_submit %}Turn off Enter to send? Enter will add a new line and the button will send.{% else %}Turn on Enter to send? Enter posts, Shift+Enter adds a new line.{% endif %}">{% if enter_to_submit %}On{% else %}Off{% endif %}</button>
</form>
</div>
<p class="customization-hint">Applies to comments and direct messages. In long editors Enter keeps adding new lines and Ctrl+Enter submits.</p>
</div>
{% endif %}
{% if is_owner %}
@@ -792,6 +806,20 @@
</tbody>
</table>
</div>
<div class="customization-row">
<span class="customization-label">Group similar notifications</span>
<form method="POST" action="/profile/{{ profile_user['username'] }}/notifications/grouping">
<input type="hidden" name="value" value="{{ 0 if notif_grouping_enabled else 1 }}">
<button type="submit" class="btn btn-sm {% if notif_grouping_enabled %}btn-primary{% endif %}" data-confirm="{% if notif_grouping_enabled %}Turn off grouping? Every notification gets its own card and the badge counts every event.{% else %}Turn on grouping? Similar notifications share one card and the badge counts groups.{% endif %}">{% if notif_grouping_enabled %}On{% else %}Off{% endif %}</button>
</form>
</div>
<div class="customization-row">
<span class="customization-label">Throttle repeat alerts (one push per event group per 5 minutes)</span>
<form method="POST" action="/profile/{{ profile_user['username'] }}/notifications/throttling">
<input type="hidden" name="value" value="{{ 0 if notif_throttle_enabled else 1 }}">
<button type="submit" class="btn btn-sm {% if notif_throttle_enabled %}btn-primary{% endif %}" data-confirm="{% if notif_throttle_enabled %}Turn off throttling? Every event can send a push, Telegram message and toast.{% else %}Turn on throttling? Repeated similar events send at most one alert per 5 minutes. In-app notifications are never throttled.{% endif %}">{% if notif_throttle_enabled %}On{% else %}Off{% endif %}</button>
</form>
</div>
<div class="notif-prefs-actions">
<button type="button" class="btn btn-ghost btn-sm" data-notif-reset>Reset to defaults</button>
</div>
+3 -3
View File
@@ -77,19 +77,19 @@
<div class="project-detail-actions">
<a href="{{ project_url }}/files" class="project-star-btn"><span class="icon">&#x1F4C1;</span><span class="label"> Files ({{ file_count }} files)</span></a>
<button type="button" class="project-star-btn" data-share="{{ project_url }}"><span class="icon">&#x1F517;</span><span class="label"> Share</span></button>
{% if user %}
{% set _type = "project" %}{% set _uid = project['uid'] %}{% set _my_vote = my_vote %}{% set _count = star_count %}{% set _btn_class = "project-star-btn" %}{% include "_star_vote.html" %}
{% endif %}
{% set _type = "project" %}{% set _uid = project['uid'] %}{% set _bookmarked = bookmarked %}{% include "_bookmark_button.html" %}
{% if user %}
{% set _type = "project" %}{% set _uid = project['uid'] %}{% set _note = note_content %}{% include "_note_button.html" %}
{% endif %}
{% set _type = "project" %}{% set _uid = project['uid'] %}{% set _reactions = reactions %}{% include "_reaction_bar.html" %}
{% set _type = "project" %}{% set _uid = project['uid'] %}{% set _owner = project['user_uid'] %}{% set _owner_name = (author or {}).get('username', '') %}{% set _class = "project-star-btn" %}{% include "_report_button.html" %}
<dp-action-menu class="project-actions-more project-actions-menu">
<button type="button" class="project-star-btn" data-action-menu-trigger aria-haspopup="menu" aria-expanded="false" aria-controls="project-actions-panel" aria-label="More actions"><span class="icon">&#x22EF;</span><span class="label"> More</span></button>
<div class="action-menu-panel" id="project-actions-panel" data-action-menu-panel popover hidden>
<button type="button" class="project-star-btn" data-share="{{ project_url }}" data-menu-action><span class="icon">&#x1F517;</span><span class="label"> Share</span></button>
{% set _type = "project" %}{% set _uid = project['uid'] %}{% set _bookmarked = bookmarked %}{% set _menu_action = true %}{% include "_bookmark_button.html" %}{% set _menu_action = false %}
{% set _type = "project" %}{% set _uid = project['uid'] %}{% set _owner = project['user_uid'] %}{% set _owner_name = (author or {}).get('username', '') %}{% set _class = "project-star-btn" %}{% set _menu_action = true %}{% include "_report_button.html" %}{% set _menu_action = false %}
<button type="button" data-zip-download="{{ project_url }}/zip" data-menu-action data-menu-icon="&#x1F4E6;" data-menu-label="Download zip">Download zip</button>
{% if user %}
<button type="button" data-fork-project="{{ project_url }}/fork" data-fork-name="{{ project['title'] }}" data-menu-action data-menu-icon="&#x2442;" data-menu-label="Fork">Fork</button>
+1 -1
View File
@@ -107,7 +107,7 @@
<form method="POST" action="/projects/create">
<div class="auth-field auth-field-gap">
<label for="title">Title</label>
<input type="text" id="title" name="title" required maxlength="200" placeholder="Project name">
<input type="text" id="title" name="title" required maxlength="200" placeholder="Project name" data-autofocus>
</div>
<div class="auth-field auth-field-gap">
+19 -14
View File
@@ -47,22 +47,27 @@
<button type="submit" class="btn btn-primary" {{ guest_disabled(user) }}>{% if viewer_state == 'done' %}Play again{% else %}Start quiz{% endif %}</button>
</form>
{% endif %}
{% if viewer_state == 'done' and viewer_attempt_uid %}
<a href="{{ quiz.url }}/attempts/{{ viewer_attempt_uid }}/results" class="btn btn-secondary">My results</a>
{% endif %}
{% endif %}
{% if quiz.viewer_can_edit %}
<a href="{{ quiz.url }}/edit" class="btn btn-secondary">Edit</a>
{% endif %}
<a href="{{ quiz.url }}/export" class="btn btn-secondary">Export JSON</a>
{% set _type = "quiz" %}{% set _uid = quiz.uid %}{% set _my_vote = my_vote %}{% set _count = star_count %}{% set _btn_class = "btn btn-secondary" %}{% include "_star_vote.html" %}
{% set _type = "quiz" %}{% set _uid = quiz.uid %}{% set _bookmarked = bookmarked %}{% include "_bookmark_button.html" %}
{% set _type = "quiz" %}{% set _uid = quiz.uid %}{% set _owner = quiz.user_uid %}{% set _owner_name = (author or {}).get('username', '') %}{% set _class = "btn btn-secondary" %}{% include "_report_button.html" %}
{% if quiz.viewer_owns or is_admin(user) %}
<form method="POST" action="/quizzes/delete/{{ quiz.slug }}" class="inline-form">
<button type="submit" class="btn btn-danger" data-confirm="Delete this quiz and every attempt on it?" data-confirm-danger>Delete</button>
</form>
{% endif %}
<dp-action-menu class="quiz-actions-menu">
<button type="button" class="btn btn-secondary" data-action-menu-trigger aria-haspopup="menu" aria-expanded="false" aria-controls="quiz-actions-panel" aria-label="More actions">&#x22EF; More</button>
<div class="action-menu-panel" id="quiz-actions-panel" data-action-menu-panel popover hidden>
{% if quiz.status == 'published' and viewer_state == 'done' and viewer_attempt_uid %}
<a href="{{ quiz.url }}/attempts/{{ viewer_attempt_uid }}/results" class="btn btn-secondary" data-menu-action>My results</a>
{% endif %}
{% if quiz.viewer_can_edit %}
<a href="{{ quiz.url }}/edit" class="btn btn-secondary" data-menu-action>Edit</a>
{% endif %}
<a href="{{ quiz.url }}/export" class="btn btn-secondary" data-menu-action>Export JSON</a>
{% set _type = "quiz" %}{% set _uid = quiz.uid %}{% set _bookmarked = bookmarked %}{% set _menu_action = true %}{% include "_bookmark_button.html" %}{% set _menu_action = false %}
{% set _type = "quiz" %}{% set _uid = quiz.uid %}{% set _owner = quiz.user_uid %}{% set _owner_name = (author or {}).get('username', '') %}{% set _class = "btn btn-secondary" %}{% set _menu_action = true %}{% include "_report_button.html" %}{% set _menu_action = false %}
{% if quiz.viewer_owns or is_admin(user) %}
<form method="POST" action="/quizzes/delete/{{ quiz.slug }}" class="inline-form">
<button type="submit" class="btn btn-danger" data-confirm="Delete this quiz and every attempt on it?" data-confirm-danger data-menu-action>Delete</button>
</form>
{% endif %}
</div>
</dp-action-menu>
</div>
{% set _type = "quiz" %}{% set _uid = quiz.uid %}{% set _reactions = reactions %}{% include "_reaction_bar.html" %}
+1 -1
View File
@@ -11,7 +11,7 @@
<form method="POST" action="/quizzes/create" class="quiz-form">
<label class="quiz-field">
<span class="quiz-field-label">Title</span>
<input type="text" name="title" required minlength="3" maxlength="200" placeholder="SQLite fundamentals">
<input type="text" name="title" required minlength="3" maxlength="200" placeholder="SQLite fundamentals" data-autofocus>
</label>
<label class="quiz-field">
+8 -1
View File
@@ -104,7 +104,14 @@ def _cached_count(cache: TTLCache, table_name: str, cache_key: str, **filters) -
def jinja_unread_count(user_uid: str) -> int:
return _cached_count(_unread_cache, "notifications", user_uid, user_uid=user_uid, read=False)
cached = _unread_cache.get(user_uid)
if cached is not None:
return cached
from devplacepy.database import count_unread_groups
count = count_unread_groups(user_uid)
_unread_cache.set(user_uid, count)
return count
def jinja_unread_messages(user_uid: str) -> int:
+30
View File
@@ -6,6 +6,9 @@ from datetime import datetime, timezone
from devplacepy.database import (
get_table,
notification_enabled,
get_notification_throttle_enabled,
notification_group_key,
NOTIFICATION_GROUP_KEYS,
get_silenced_uids,
)
from devplacepy.services.background import background
@@ -14,6 +17,7 @@ from devplacepy.utils.text import generate_uid, extract_mentions
logger = logging.getLogger(__name__)
PUSH_ICON = "/static/apple-touch-icon.png"
PUSH_THROTTLE_SECONDS = 300
DEFAULT_PUSH_URL = "/notifications"
_push_tasks: set[asyncio.Task] = set()
@@ -90,6 +94,31 @@ def _deliver_notification(
in_app = notification_enabled(user_uid, notification_type, "in_app")
push = notification_enabled(user_uid, notification_type, "push")
telegram = notification_enabled(user_uid, notification_type, "telegram")
throttled = False
if get_notification_throttle_enabled(user_uid) and NOTIFICATION_GROUP_KEYS.get(notification_type, "single") != "single":
key = notification_group_key(
{"type": notification_type, "related_uid": related_uid or "", "target_url": target_url or "", "uid": ""}
)
now = datetime.now(timezone.utc)
try:
recent_rows = get_table("notifications").find(user_uid=user_uid, order_by=["-created_at"], _limit=100)
except Exception:
recent_rows = []
for recent in recent_rows:
try:
created = datetime.fromisoformat(recent.get("created_at") or "")
except ValueError:
continue
if created.tzinfo is None:
created = created.replace(tzinfo=timezone.utc)
if (now - created).total_seconds() > PUSH_THROTTLE_SECONDS:
break
if notification_group_key(recent) == key:
throttled = True
break
if throttled:
push = False
telegram = False
if in_app:
get_table("notifications").insert(
{
@@ -121,6 +150,7 @@ def _deliver_notification(
"in_app": in_app,
"push": push,
"telegram": telegram,
"throttled": throttled,
},
links=[
audit.recipient(user_uid),
+4
View File
@@ -65,6 +65,10 @@ Every state-changing action in DevPlace records one append-only row through `dev
| `profile.interactions` | `routers/profile/interactions.py`, `services/devii/actions/dispatcher.py` |
| `profile.notification.reset` | `routers/profile/notifications.py` |
| `profile.notification.toggle` | `routers/profile/notifications.py` |
| `profile.enter_to_submit.toggle` | `routers/profile/customization.py` |
| `profile.notification.grouping.toggle` | `routers/profile/notifications.py` |
| `profile.notification.throttle.toggle` | `routers/profile/notifications.py` |
| `notification.read.group` | `routers/notifications.py` |
| `profile.update` | `routers/devrant/auth.py`, `routers/profile/index.py` |
| `account.delete.purge` | `services/moderation/deletion.py` |
| `account.delete.request` | `routers/devrant/auth.py`, `routers/profile/delete.py` |
+1 -1
View File
@@ -1,6 +1,6 @@
[project]
name = "devplacepy"
version = "1.1.20"
version = "1.1.21"
description = "DevPlace - The Developer Social Network"
requires-python = ">=3.12"
dependencies = [
+100
View File
@@ -0,0 +1,100 @@
# retoor <retoor@molodetz.nl>
import time
from datetime import datetime, timezone
import requests
from tests.conftest import BASE_URL
from devplacepy.database import get_table, refresh_snapshot
from devplacepy.utils import generate_uid
_counter = [0]
JSON = {"Accept": "application/json"}
def _signup():
_counter[0] += 1
name = f"ngrp{int(time.time() * 1000)}{_counter[0]}"
session = requests.Session()
session.post(
f"{BASE_URL}/auth/signup",
data={
"username": name,
"email": f"{name}@t.dev",
"password": "secret123",
"confirm_password": "secret123",
"birth_date": "1990-01-01",
"accept_terms": "1",
},
allow_redirects=True,
)
return session, name
def _seed(session, name, count=5):
refresh_snapshot()
user = get_table("users").find_one(username=name)
now = datetime.now(timezone.utc).isoformat()
table = get_table("notifications")
for i in range(count):
table.insert(
{
"uid": generate_uid(),
"user_uid": user["uid"],
"type": "vote",
"message": f"actor-{i} ++'d your post",
"related_uid": user["uid"],
"target_url": "/posts/seeded",
"read": False,
"created_at": now,
}
)
refresh_snapshot()
return user
def _wait_counts(session, expected):
deadline = time.time() + 20
counts = {}
while time.time() < deadline:
counts = session.get(f"{BASE_URL}/notifications/counts").json()
if counts.get("notifications") == expected:
return counts
time.sleep(0.5)
return counts
def test_grouped_page_and_counts(app_server):
session, name = _signup()
_seed(session, name)
counts = _wait_counts(session, 1)
assert counts["notifications"] == 1, counts
page = session.get(f"{BASE_URL}/notifications", headers=JSON)
data = page.json()
assert data["grouping"] is True
events = [
entry
for group in data["notification_groups"]
for entry in group["event_entries"]
]
assert len(events) == 1
assert events[0]["count"] == 5
html = session.get(f"{BASE_URL}/notifications")
assert "&times;5" in html.text or "×5" in html.text
def test_grouping_off_restores_row_counts(app_server):
session, name = _signup()
_seed(session, name)
resp = session.post(
f"{BASE_URL}/profile/{name}/notifications/grouping",
data={"value": "false"},
headers=JSON,
)
assert resp.status_code == 200
counts = _wait_counts(session, 5)
assert counts["notifications"] == 5, counts
page = session.get(f"{BASE_URL}/notifications", headers=JSON)
data = page.json()
assert data["grouping"] is False
+109
View File
@@ -0,0 +1,109 @@
# retoor <retoor@molodetz.nl>
import time
import requests
from tests.conftest import BASE_URL
_counter = [0]
JSON = {"Accept": "application/json"}
def _signup():
_counter[0] += 1
name = f"nset{int(time.time() * 1000)}{_counter[0]}"
session = requests.Session()
session.post(
f"{BASE_URL}/auth/signup",
data={
"username": name,
"email": f"{name}@t.dev",
"password": "secret123",
"confirm_password": "secret123",
"birth_date": "1990-01-01",
"accept_terms": "1",
},
allow_redirects=True,
)
return session, name
def _toggle(session, name, kind, value):
return session.post(
f"{BASE_URL}/profile/{name}/notifications/{kind}",
data={"value": "true" if value else "false"},
headers=JSON,
)
def test_owner_toggles_grouping_and_throttling(app_server):
session, name = _signup()
for kind, field in (("grouping", "notif_grouping_enabled"), ("throttling", "notif_throttle_enabled")):
resp = _toggle(session, name, kind, False)
assert resp.status_code == 200, resp.text[:200]
assert resp.json()["data"][field] is False
resp = _toggle(session, name, kind, True)
assert resp.status_code == 200, resp.text[:200]
assert resp.json()["data"][field] is True
def test_other_user_cannot_toggle(app_server):
_, target = _signup()
attacker, _ = _signup()
for kind in ("grouping", "throttling"):
resp = attacker.post(
f"{BASE_URL}/profile/{target}/notifications/{kind}",
data={"value": "false"},
headers=JSON,
allow_redirects=False,
)
assert resp.status_code == 403
def test_admin_can_toggle(app_server, seeded_db):
_, target = _signup()
admin = requests.Session()
admin.post(
f"{BASE_URL}/auth/login",
data={"email": seeded_db["alice"]["email"], "password": seeded_db["alice"]["password"]},
allow_redirects=True,
)
resp = admin.post(
f"{BASE_URL}/profile/{target}/notifications/grouping",
data={"value": "false"},
headers=JSON,
)
assert resp.status_code == 200, resp.text[:200]
assert resp.json()["data"]["notif_grouping_enabled"] is False
def test_owner_toggles_enter_to_submit(app_server):
session, name = _signup()
resp = session.post(
f"{BASE_URL}/profile/{name}/enter-to-submit",
data={"value": "false"},
headers=JSON,
)
assert resp.status_code == 200, resp.text[:200]
assert resp.json()["data"]["enter_to_submit"] is False
page = session.get(f"{BASE_URL}/profile/{name}", headers=JSON)
assert page.json()["enter_to_submit"] is False
resp = session.post(
f"{BASE_URL}/profile/{name}/enter-to-submit",
data={"value": "true"},
headers=JSON,
)
assert resp.json()["data"]["enter_to_submit"] is True
def test_other_user_cannot_toggle_enter_to_submit(app_server):
_, target = _signup()
attacker, _ = _signup()
resp = attacker.post(
f"{BASE_URL}/profile/{target}/enter-to-submit",
data={"value": "false"},
headers=JSON,
allow_redirects=False,
)
assert resp.status_code == 403
+62 -20
View File
@@ -191,7 +191,7 @@ def app_server(test_db_path):
except OSError:
return ""
deadline = time.time() + 30
deadline = time.time() + 120
while time.time() < deadline:
try:
import urllib.request
@@ -208,8 +208,12 @@ def app_server(test_db_path):
time.sleep(0.5)
else:
proc.terminate()
proc.wait(timeout=5)
raise RuntimeError(f"Server did not start after 30s. Log:\n{server_log()}")
try:
proc.wait(timeout=15)
except subprocess.TimeoutExpired:
proc.kill()
proc.wait(timeout=5)
raise RuntimeError(f"Server did not start after 120s. Log:\n{server_log()}")
from devplacepy.database import set_setting as _set_setting
@@ -301,26 +305,39 @@ def page(browser_context):
p.close()
def signup_user(page, user):
def _reach_feed(page, url, fill, submit_text):
page.bring_to_front()
page.goto(f"{BASE_URL}/auth/signup", wait_until="domcontentloaded")
page.fill("#username", user["username"])
page.fill("#email", user["email"])
page.fill("#password", user["password"])
page.fill("#confirm_password", user["password"])
page.fill("#birth_date", "1990-01-01")
page.check("#accept_terms")
page.click("button:has-text('Create account')")
page.wait_for_url("**/feed", timeout=10000, wait_until="domcontentloaded")
for attempt in (1, 2):
page.goto(url, wait_until="domcontentloaded")
fill()
try:
page.click(f"button:has-text('{submit_text}')")
page.wait_for_url("**/feed", timeout=10000, wait_until="domcontentloaded")
return
except Exception as error:
dropped = "chrome-error://chromewebdata/" in str(error) or page.url.startswith("chrome-error:")
if attempt == 2 or not dropped:
raise
def signup_user(page, user):
def fill():
page.fill("#username", user["username"])
page.fill("#email", user["email"])
page.fill("#password", user["password"])
page.fill("#confirm_password", user["password"])
page.fill("#birth_date", "1990-01-01")
page.check("#accept_terms")
_reach_feed(page, f"{BASE_URL}/auth/signup", fill, "Create account")
def login_user(page, user):
page.bring_to_front()
page.goto(f"{BASE_URL}/auth/login", wait_until="domcontentloaded")
page.fill("#email", user["email"])
page.fill("#password", user["password"])
page.click("button:has-text('Sign in')")
page.wait_for_url("**/feed", timeout=10000, wait_until="domcontentloaded")
def fill():
page.fill("#email", user["email"])
page.fill("#password", user["password"])
_reach_feed(page, f"{BASE_URL}/auth/login", fill, "Sign in")
def paste_image(page, selector, name="pasted.png"):
@@ -365,10 +382,35 @@ def create_post_with_files(page, content, files, expected_count=1):
page.wait_for_url(f"{BASE_URL}/posts/*", wait_until="domcontentloaded")
def open_action_menu(locator):
target = locator.first
target.evaluate(
"""el => {
const menu = el.closest("dp-action-menu");
if (!menu) return;
const panel = menu.querySelector("[data-action-menu-panel]");
if (panel && panel.matches(":popover-open")) return;
if (typeof menu.open === "function") {
menu.open();
return;
}
const trigger = menu.querySelector("[data-action-menu-trigger]");
if (trigger) trigger.click();
}"""
)
return target
def click_menu_action(locator):
target = open_action_menu(locator)
target.click()
return target
def assert_share_copies(page, expected_fragment):
from playwright.sync_api import expect
share = page.locator("button[data-share]").first
share = open_action_menu(page.locator("button[data-share]"))
share.scroll_into_view_if_needed()
assert expected_fragment in (share.get_attribute("data-share") or ""), (
f"data-share={share.get_attribute('data-share')!r}"
+87 -1
View File
@@ -1,7 +1,7 @@
# retoor <retoor@molodetz.nl>
from playwright.sync_api import expect
from tests.conftest import BASE_URL
from tests.conftest import BASE_URL, assert_no_horizontal_overflow
from tests.e2e.post import create_post
@@ -43,6 +43,92 @@ def test_cancel_inline_edit(alice):
expect(page.locator(".comment-text:has-text('Keep this body')")).to_be_visible()
def _composer_metrics(textarea):
return textarea.evaluate(
"""el => {
const form = el.closest("form");
const actions = form.querySelector(".comment-form-actions");
const field = el.getBoundingClientRect();
const formBox = form.getBoundingClientRect();
const actionBox = actions.getBoundingClientRect();
const column = document.querySelector(".post-page, .feed-main");
const columnBox = column ? column.getBoundingClientRect() : formBox;
return {
field: field.width,
fieldHeight: field.height,
form: formBox.width,
column: columnBox.width,
actionsTop: actionBox.top,
actionsWidth: actionBox.width,
fieldBottom: field.bottom,
overflow: document.documentElement.scrollWidth - document.documentElement.clientWidth,
};
}"""
)
def _assert_composer_has_room(metrics, minimum_field, full_width=False):
slack = 8 if full_width else 64
assert metrics["field"] >= metrics["form"] - slack, metrics
assert metrics["field"] >= minimum_field, metrics
assert metrics["fieldHeight"] < 90, metrics
assert metrics["actionsTop"] >= metrics["fieldBottom"] - 2, metrics
assert metrics["actionsWidth"] <= metrics["form"] + 1, metrics
assert metrics["overflow"] <= 1, metrics
def _check_composer(page, textarea, minimum_field, full_width, min_column):
textarea.fill("helps a lot.")
metrics = _composer_metrics(textarea)
_assert_composer_has_room(metrics, minimum_field, full_width)
assert metrics["column"] >= min_column, metrics
def test_comment_composer_field_keeps_its_width(alice):
page, _ = alice
page.set_viewport_size({"width": 1280, "height": 800})
create_post(page, "devlog", "Post for the comment composer width")
_post_comment(page, "Parent for the reply box")
composer = page.locator(".comment-form:not(.comment-reply-form) textarea[name='content']").last
_check_composer(page, composer, 320, False, 480)
page.locator("[data-action='reply']").last.click()
reply = page.locator(".comment-reply-form textarea[name='content']")
expect(reply).to_be_visible()
_check_composer(page, reply, 320, False, 480)
page.set_viewport_size({"width": 768, "height": 1024})
_check_composer(page, reply, 280, False, 480)
page.set_viewport_size({"width": 390, "height": 844})
_check_composer(page, reply, 200, True, 300)
_check_composer(page, composer, 200, True, 300)
page.set_viewport_size({"width": 360, "height": 740})
_check_composer(page, reply, 180, True, 280)
assert_no_horizontal_overflow(page, ".post-page-layout")
page.set_viewport_size({"width": 1280, "height": 800})
page.goto(f"{BASE_URL}/feed", wait_until="domcontentloaded")
card = page.locator(".post-card").filter(has_text="Parent for the reply box").first
expect(card).to_be_visible()
card.locator("[data-action='reply']").first.click()
feed_reply = card.locator(".comment-reply-form textarea[name='content']")
expect(feed_reply).to_be_visible()
_check_composer(page, feed_reply, 200, False, 480)
page.set_viewport_size({"width": 768, "height": 1024})
_check_composer(page, feed_reply, 200, False, 400)
page.set_viewport_size({"width": 390, "height": 844})
_check_composer(page, feed_reply, 160, True, 300)
page.set_viewport_size({"width": 360, "height": 740})
_check_composer(page, feed_reply, 140, True, 280)
assert_no_horizontal_overflow(page, ".feed-layout")
def test_non_owner_sees_no_edit_button(alice, bob):
page, _ = alice
create_post(page, "random", "Post owned by alice")
+2 -2
View File
@@ -1,6 +1,6 @@
# retoor <retoor@molodetz.nl>
from tests.conftest import BASE_URL, CACHE_VERSION_PROPAGATION_SECONDS, create_post_with_files, paste_image
from tests.conftest import BASE_URL, CACHE_VERSION_PROPAGATION_SECONDS, click_menu_action, create_post_with_files, paste_image
import time
import requests
from playwright.sync_api import expect
@@ -849,7 +849,7 @@ def test_delete_own_post(alice):
page, _ = alice
create_post(page, "random", "Post to be deleted permanently here")
post_url = page.url
page.locator(".post-action-btn:has-text('Delete')").click()
click_menu_action(page.locator("#post-actions-panel button:has-text('Delete')"))
page.locator(".dialog-overlay.visible .dialog-confirm").click()
page.wait_for_url(f"{BASE_URL}/feed", wait_until="domcontentloaded")
set_setting("happy_404_enabled", "0")
+26
View File
@@ -35,6 +35,31 @@ def _warp_stealable(username):
)
def _clear_golden(username, crop="python"):
from devplacepy.database import get_table
from devplacepy.services.game import economy, store
user = get_table("users").find_one(username=username)
farm = store.get_farm(user["uid"])
for plot in store.get_plots(farm["uid"]):
if plot.get("crop_key") != crop:
continue
raw = plot.get("planted_at") or ""
try:
start = datetime.fromisoformat(raw)
except ValueError:
start = datetime.now(timezone.utc)
for step in range(2000):
candidate = (start + timedelta(seconds=step)).isoformat()
if economy.is_golden(plot["uid"], candidate):
continue
if candidate != raw:
get_table("game_plots").update(
{"uid": plot["uid"], "planted_at": candidate}, ["uid"]
)
break
def _farm_coins(username):
from devplacepy.database import get_table
from devplacepy.services.game import store
@@ -128,6 +153,7 @@ def test_steal_takes_build_and_pays_thief(bob):
reset_farm("bob_test", coins=0)
_plant_growing("alice_test", crop="python")
_warp_stealable("alice_test")
_clear_golden("alice_test")
alice_coins_before = _farm_coins("alice_test")
page.goto(f"{BASE_URL}/game/farm/alice_test", wait_until="domcontentloaded")
page.locator("[data-game-grid]").first.wait_for(state="visible")
+6 -7
View File
@@ -10,6 +10,7 @@ from tests.conftest import (
BASE_URL,
assert_no_horizontal_overflow,
assert_share_copies,
click_menu_action,
)
from devplacepy.database import get_table
from devplacepy.utils import make_combined_slug
@@ -201,8 +202,7 @@ def test_edit_gist(alice, app_server):
page, _ = alice
title = f"Edit Test Original {int(time.time())}"
_create_gist(page, title=title, source_code="x = 1")
page.locator("button:has-text('Edit')").wait_for(state="visible", timeout=5000)
page.click("button:has-text('Edit')")
click_menu_action(page.locator("#gist-actions-panel [data-modal='edit-gist-modal']"))
page.wait_for_timeout(800)
new_title = f"Edit Test Updated {int(time.time())}"
page.fill("#edit-gist-title", new_title)
@@ -230,8 +230,7 @@ def test_delete_gist(alice, app_server):
page, _ = alice
title = f"Delete Test {int(time.time())}"
_create_gist(page, title=title, source_code="delete_me = True")
page.locator("button[data-confirm='Delete this gist?']").wait_for(state="visible", timeout=5000)
page.click("button[data-confirm='Delete this gist?']")
click_menu_action(page.locator("#gist-actions-panel button[data-confirm='Delete this gist?']"))
page.locator(".dialog-overlay.visible .dialog-confirm").click()
page.wait_for_url(f"{BASE_URL}/gists", timeout=10000, wait_until="domcontentloaded")
@@ -595,7 +594,7 @@ def test_gist_created_hidden_leaves_the_listing(alice):
def _edit_gist_visibility(page, url, value):
page.goto(url, wait_until="domcontentloaded")
page.locator("[data-modal='edit-gist-modal']").click()
click_menu_action(page.locator("#gist-actions-panel [data-modal='edit-gist-modal']"))
page.select_option("#edit-gist-visibility", value)
page.locator("#edit-gist-modal button.btn-primary").click()
page.wait_for_url(url, wait_until="domcontentloaded")
@@ -621,7 +620,7 @@ def test_gist_edit_modal_changes_visibility(alice):
page, _ = alice
title = f"VisGistEdit{int(time.time() * 1000)}"
url = _create_gist_with_visibility(page, title, None)
page.locator("[data-modal='edit-gist-modal']").click()
click_menu_action(page.locator("#gist-actions-panel [data-modal='edit-gist-modal']"))
expect(page.locator("#edit-gist-visibility")).to_have_value("published")
page.select_option("#edit-gist-visibility", "hidden")
page.locator("#edit-gist-modal button.btn-primary").click()
@@ -633,6 +632,6 @@ def test_gist_visibility_field_fits_a_phone(mobile_page):
page, _ = mobile_page
title = f"VisGistPhone{int(time.time() * 1000)}"
_create_gist_with_visibility(page, title, "hidden")
page.locator("[data-modal='edit-gist-modal']").click()
click_menu_action(page.locator("#gist-actions-panel [data-modal='edit-gist-modal']"))
expect(page.locator("#edit-gist-visibility")).to_be_visible()
assert_no_horizontal_overflow(page, ".gist-detail-page")
+244 -4
View File
@@ -5,7 +5,6 @@ import time
from playwright.sync_api import expect
from tests.conftest import BASE_URL, paste_image
from devplacepy.database import get_table
import requests
def _seed_news_seo():
from datetime import datetime, timezone
from devplacepy.database import get_table
@@ -557,13 +556,15 @@ def _uid(username):
def _send_as(page, receiver_uid, content):
page.evaluate(
ok = page.evaluate(
"async ([uid, text]) => {"
" const body = new URLSearchParams({receiver_uid: uid, content: text});"
" await fetch('/messages/send', {method: 'POST', body, headers: {Accept: 'application/json'}});"
" const resp = await fetch('/messages/send', {method: 'POST', body, headers: {Accept: 'application/json'}});"
" return resp.ok;"
"}",
[receiver_uid, content],
)
assert ok, "seed message send must succeed"
def test_dock_icon_opens_chats_panel_then_a_docked_window(alice, bob):
@@ -666,7 +667,7 @@ def test_dock_is_absent_on_messages_page(alice):
def test_mobile_messages_icon_opens_the_messages_page(mobile_page):
page, _ = mobile_page
page.goto(f"{BASE_URL}/feed", wait_until="domcontentloaded")
page.locator("[data-chat-panel-toggle]").first.click(force=True)
page.locator("[data-chat-panel-toggle]").first.click()
page.wait_for_url(f"{BASE_URL}/messages", wait_until="domcontentloaded")
@@ -686,3 +687,242 @@ def test_composer_plus_button_reveals_attach_tools(alice):
area.locator("textarea[name='content']").fill("typing tucks the tools away")
expect(upload).to_be_hidden()
expect(more).to_have_attribute("aria-expanded", "false")
def test_dock_window_plus_button_reveals_attach_tools(alice, bob):
page_a, _ = alice
_, user_b = bob
uid_b = _uid(user_b["username"])
page_a.goto(f"{BASE_URL}/profile/{user_b['username']}", wait_until="domcontentloaded")
page_a.locator(f"[data-chat-open='{uid_b}']").click()
window = page_a.locator(f".chat-window[data-chat-uid='{uid_b}']")
area = window.locator(".messages-input-area")
upload = area.locator("dp-upload .dp-upload-btn")
more = area.locator(".composer-more-btn")
expect(upload).to_be_hidden()
more.click()
expect(upload).to_be_visible()
expect(more).to_have_attribute("aria-expanded", "true")
area.locator("textarea[name='content']").fill("typing in the window")
expect(upload).to_be_hidden()
def test_dock_open_window_survives_navigation(alice, bob):
page_a, user_a = alice
page_b, user_b = bob
uid_b = _uid(user_b["username"])
msg = f"Restore me {int(time.time() * 1000)}"
_send_as(page_b, _uid(user_a["username"]), msg)
page_a.goto(f"{BASE_URL}/profile/{user_b['username']}", wait_until="domcontentloaded")
page_a.locator(f"[data-chat-open='{uid_b}']").click()
window = page_a.locator(f".chat-window[data-chat-uid='{uid_b}']")
window.locator(f".message-bubble:has-text('{msg}')").wait_for(state="visible")
page_a.goto(f"{BASE_URL}/projects", wait_until="domcontentloaded")
window = page_a.locator(f".chat-window[data-chat-uid='{uid_b}']")
window.locator(f".message-bubble:has-text('{msg}')").wait_for(state="visible")
expect(window.locator("textarea[name='content']")).to_be_visible()
def test_dock_panel_search_and_see_all(alice, bob):
page_a, _ = alice
_, user_b = bob
uid_b = _uid(user_b["username"])
page_a.goto(f"{BASE_URL}/feed", wait_until="domcontentloaded")
page_a.locator("[data-chat-panel-toggle]").first.click()
panel = page_a.locator(".chat-panel")
expect(panel).to_be_visible()
expect(panel.locator(".chat-panel-footer")).to_have_attribute("href", "/messages")
panel.locator(".chat-panel-search-input").fill(user_b["username"])
item = panel.locator(f".conversation-item[data-conv-uid='{uid_b}']")
item.wait_for(state="visible")
item.click()
expect(panel).to_be_hidden()
expect(page_a.locator(f".chat-window[data-chat-uid='{uid_b}']")).to_have_count(1)
def test_dock_panel_and_window_close_controls(alice, bob):
page_a, _ = alice
_, user_b = bob
uid_b = _uid(user_b["username"])
page_a.goto(f"{BASE_URL}/feed", wait_until="domcontentloaded")
toggle = page_a.locator("[data-chat-panel-toggle]").first
panel = page_a.locator(".chat-panel")
toggle.click()
expect(panel).to_be_visible()
page_a.keyboard.press("Escape")
expect(panel).to_be_hidden()
toggle.click()
expect(panel).to_be_visible()
page_a.locator("body").click(position={"x": 700, "y": 500})
expect(panel).to_be_hidden()
page_a.goto(f"{BASE_URL}/profile/{user_b['username']}", wait_until="domcontentloaded")
page_a.locator(f"[data-chat-open='{uid_b}']").click()
window = page_a.locator(f".chat-window[data-chat-uid='{uid_b}']")
window.locator(".chat-window-close").click()
expect(window).to_have_count(0)
page_a.locator(f"[data-chat-open='{uid_b}']").click()
window.locator(".chat-window-minimize").click()
head = page_a.locator(f".chat-head[data-chat-uid='{uid_b}']")
head.wait_for(state="visible")
head.locator(".chat-head-close").click()
expect(head).to_have_count(0)
def test_dock_caps_expanded_windows_at_three(alice, bob):
page_a, _ = alice
_, user_b = bob
from devplacepy.utils import generate_uid
partners = [_uid(user_b["username"])]
for name in ("dockcap1", "dockcap2", "dockcap3"):
row = get_table("users").find_one(username=name)
if not row:
get_table("users").insert(
{
"deleted_at": None,
"deleted_by": None,
"uid": generate_uid(),
"username": name,
"email": f"{name}@test.devplace",
"password_hash": "x",
"role": "Member",
"is_active": True,
"created_at": "2026-01-01T00:00:00+00:00",
}
)
row = get_table("users").find_one(username=name)
partners.append(row["uid"])
page_a.goto(f"{BASE_URL}/feed", wait_until="domcontentloaded")
for uid in partners:
page_a.evaluate("(uid) => window.app.chatDock.open({ uid, username: 'x' }, { focus: false })", uid)
expect(page_a.locator(".chat-window:not(.chat-window-compose)")).to_have_count(3)
expect(page_a.locator(".chat-head")).to_have_count(1)
def test_dock_toast_click_opens_window(alice, bob):
page_a, user_a = alice
page_b, _ = bob
uid_a = _uid(user_a["username"])
uid_b = _uid("bob_test")
page_a.goto(f"{BASE_URL}/feed", wait_until="domcontentloaded")
page_a.wait_for_function("() => !!window.app && !!window.app.chatDock")
msg = f"Toast hello {int(time.time() * 1000)}"
_send_as(page_b, uid_a, msg)
page_a.evaluate(
"(sender) => window.app.liveNotifications.onNotification("
" { uid: 'toast-test', type: 'message', message: 'bob_test sent you a message',"
" target_url: `/messages?with_uid=${sender}` })",
uid_b,
)
toast = page_a.locator(".dp-toast-link")
toast.first.wait_for(state="visible", timeout=10000)
toast.first.click()
window = page_a.locator(f".chat-window[data-chat-uid='{uid_b}']")
window.locator(f".message-bubble:has-text('{msg}')").wait_for(state="visible", timeout=10000)
assert page_a.url.endswith("/feed")
def test_dock_window_live_message_shows_report_button(alice, bob):
page_a, user_a = alice
page_b, user_b = bob
uid_a = _uid(user_a["username"])
uid_b = _uid(user_b["username"])
page_a.goto(f"{BASE_URL}/profile/{user_b['username']}", wait_until="domcontentloaded")
page_a.locator(f"[data-chat-open='{uid_b}']").click()
window = page_a.locator(f".chat-window[data-chat-uid='{uid_b}']")
window.locator("textarea[name='content']").wait_for(state="visible")
msg = f"Flag in window {int(time.time() * 1000)}"
_send_as(page_b, uid_a, msg)
bubble = window.locator(f".message-bubble.theirs:has-text('{msg}')")
bubble.wait_for(state="visible", timeout=10000)
expect(bubble.locator(".message-report-btn")).to_be_visible()
def test_dock_reading_on_messages_page_clears_head_badge(alice, bob):
page_a, user_a = alice
page_b, user_b = bob
uid_a = _uid(user_a["username"])
uid_b = _uid(user_b["username"])
page_a.goto(f"{BASE_URL}/profile/{user_b['username']}", wait_until="domcontentloaded")
page_a.locator(f"[data-chat-open='{uid_b}']").click()
window = page_a.locator(f".chat-window[data-chat-uid='{uid_b}']")
window.locator(".chat-window-minimize").click()
head = page_a.locator(f".chat-head[data-chat-uid='{uid_b}']")
head.wait_for(state="visible")
_send_as(page_b, uid_a, f"Badge check {int(time.time() * 1000)}")
expect(head.locator(".chat-head-badge")).to_have_text("1", timeout=10000)
page_a.goto(f"{BASE_URL}/messages?with_uid={uid_b}", wait_until="domcontentloaded")
page_a.locator(".messages-thread .message-bubble").first.wait_for(state="visible")
page_a.goto(f"{BASE_URL}/feed", wait_until="domcontentloaded")
head = page_a.locator(f".chat-head[data-chat-uid='{uid_b}']")
head.wait_for(state="visible")
expect(head.locator(".chat-head-badge")).to_be_hidden(timeout=10000)
def test_dock_hidden_tab_does_not_mark_read_until_visible(alice, bob):
page_a, user_a = alice
page_b, user_b = bob
uid_a = _uid(user_a["username"])
uid_b = _uid(user_b["username"])
page_a.goto(f"{BASE_URL}/profile/{user_b['username']}", wait_until="domcontentloaded")
page_a.locator(f"[data-chat-open='{uid_b}']").click()
window = page_a.locator(f".chat-window[data-chat-uid='{uid_b}']")
window.locator("textarea[name='content']").wait_for(state="visible")
page_a.wait_for_function("() => document.querySelector('dp-chat-dock').hub.isOpen()")
page_a.evaluate(
"() => { Object.defineProperty(document, 'visibilityState', { value: 'hidden', configurable: true });"
" document.dispatchEvent(new Event('visibilitychange')); }"
)
msg = f"Hidden tab {int(time.time() * 1000)}"
_send_as(page_b, uid_a, msg)
window.locator(f".message-bubble:has-text('{msg}')").wait_for(state="visible", timeout=10000)
page_a.wait_for_timeout(500)
unread = page_a.evaluate(
"async (uid) => { const r = await fetch('/messages/conversations', {headers: {Accept: 'application/json'}});"
" const d = await r.json(); const c = (d.conversations || []).find((x) => x.other_user.uid === uid);"
" return c ? c.unread : null; }",
uid_b,
)
assert unread is True, "a message to a window in a hidden tab must stay unread"
page_a.evaluate(
"() => { Object.defineProperty(document, 'visibilityState', { value: 'visible', configurable: true });"
" document.dispatchEvent(new Event('visibilitychange')); }"
)
page_a.wait_for_function(
"async (uid) => { const r = await fetch('/messages/conversations', {headers: {Accept: 'application/json'}});"
" const d = await r.json(); const c = (d.conversations || []).find((x) => x.other_user.uid === uid);"
" return !!c && c.unread === false; }",
arg=uid_b,
timeout=10000,
)
def test_dock_socket_does_not_resurrect_after_last_window_closes(alice, bob):
page_a, _ = alice
_, user_b = bob
uid_b = _uid(user_b["username"])
page_a.goto(f"{BASE_URL}/profile/{user_b['username']}", wait_until="domcontentloaded")
page_a.locator(f"[data-chat-open='{uid_b}']").click()
page_a.locator(f".chat-window[data-chat-uid='{uid_b}'] textarea[name='content']").wait_for(state="visible")
page_a.wait_for_function("() => document.querySelector('dp-chat-dock').hub.isOpen()")
result = page_a.evaluate(
"async (uid) => {"
" const dock = document.querySelector('dp-chat-dock');"
" const cs = dock.hub.socket;"
" let opens = 0; const orig = cs._open.bind(cs);"
" cs._open = () => { opens += 1; return orig(); };"
" cs.socket.close();"
" await new Promise((r) => setTimeout(r, 100));"
" dock.close(uid);"
" await new Promise((r) => setTimeout(r, 900));"
" return { opens, hubSocket: dock.hub.socket === null, state: cs.socket ? cs.socket.readyState : null };"
"}",
uid_b,
)
assert result["hubSocket"], "the hub must not hold a socket after the last window closes"
assert result["opens"] == 0, f"a closed socket must not reconnect with zero subscribers: {result}"
+54
View File
@@ -0,0 +1,54 @@
# retoor <retoor@molodetz.nl>
from datetime import datetime, timezone
from playwright.sync_api import expect
from tests.conftest import BASE_URL
from devplacepy.database import get_table, refresh_snapshot
from devplacepy.utils import generate_uid
JSON = {"Accept": "application/json"}
def _seed_votes(user_uid, count=4):
now = datetime.now(timezone.utc).isoformat()
table = get_table("notifications")
for i in range(count):
table.insert(
{
"uid": generate_uid(),
"user_uid": user_uid,
"type": "vote",
"message": f"voter-{i} ++'d your post",
"related_uid": user_uid,
"target_url": "/posts/grouped-seed",
"read": False,
"created_at": now,
}
)
refresh_snapshot()
def test_grouped_notifications_card(alice, seeded_db):
page, user = alice
uid = get_table("users").find_one(username=user["username"])["uid"]
_seed_votes(uid)
try:
page.goto(f"{BASE_URL}/notifications", wait_until="domcontentloaded")
card = page.locator("[data-notification-group]").first
expect(card).to_be_visible(timeout=10000)
expect(card.locator(".notif-group-count")).to_have_text("×4")
finally:
get_table("notifications").delete(user_uid=uid, target_url="/posts/grouped-seed")
refresh_snapshot()
def test_grouping_toggle_on_profile_notifications_tab(alice):
page, user = alice
username = user["username"]
page.goto(f"{BASE_URL}/profile/{username}?tab=notifications", wait_until="domcontentloaded")
panel = page.locator("[data-notif-prefs]")
expect(panel.locator("form[action$='/notifications/grouping']")).to_be_attached()
expect(panel.locator("form[action$='/notifications/throttling']")).to_be_attached()
expect(page.locator("[data-enter-to-submit-card]")).to_be_attached()
-3
View File
@@ -4,7 +4,6 @@ from datetime import datetime, timedelta, timezone
from tests.conftest import BASE_URL
from devplacepy.database import get_table
from devplacepy.utils import generate_uid
import requests
def _seed_news_seo():
from datetime import datetime, timezone
from devplacepy.database import get_table
@@ -764,8 +763,6 @@ def test_message_notification_click_opens_conversation(app_server, browser, seed
card = pa.locator(".notification-card").filter(has_text="sent you a message").first
card.wait_for(state="visible", timeout=10000)
card.locator("a.card-link").click()
from devplacepy.database import get_table
bob_uid = get_table("users").find_one(username=seeded_db["bob"]["username"])["uid"]
window = pa.locator(f".chat-window[data-chat-uid='{bob_uid}']")
window.locator(".message-bubble:has-text('Click-through message from bob')").first.wait_for(
+5 -5
View File
@@ -14,7 +14,7 @@ def _create_plain_post_engagement_ui(page, content):
page.wait_for_url(f"{BASE_URL}/posts/*", wait_until="domcontentloaded")
from uuid import uuid4
from datetime import datetime, timedelta, timezone
from tests.conftest import BASE_URL, assert_share_copies
from tests.conftest import BASE_URL, assert_share_copies, click_menu_action, open_action_menu
from devplacepy.database import get_table
from devplacepy.utils import make_combined_slug
def _seed_posts(count):
@@ -378,7 +378,7 @@ def test_add_poll_to_existing_post_via_edit(alice):
_create_plain_post_engagement_ui(page, "Post that gains a poll through the edit modal.")
expect(page.locator(".poll")).to_have_count(0)
page.locator("[data-modal='edit-post-modal']").click()
click_menu_action(page.locator("#post-actions-panel [data-modal='edit-post-modal']"))
modal = page.locator("#edit-post-modal")
expect(modal).to_be_visible()
modal.locator("[data-poll-toggle]").click()
@@ -485,7 +485,7 @@ def test_post_edit_button(alice):
page.fill("#post-title", "Editable Post")
page.locator("#create-post-modal button.btn-primary:has-text('Post')").click()
page.wait_for_url(f"{BASE_URL}/posts/*", wait_until="domcontentloaded")
edit_btn = page.locator("button:has-text('Edit')")
edit_btn = open_action_menu(page.locator("#post-actions-panel [data-modal='edit-post-modal']"))
assert edit_btn.is_visible()
@@ -497,7 +497,7 @@ def test_post_edit_modal(alice):
page.fill("#post-title", "Edit Modal Test")
page.locator("#create-post-modal button.btn-primary:has-text('Post')").click()
page.wait_for_url(f"{BASE_URL}/posts/*", wait_until="domcontentloaded")
page.click("button:has-text('Edit')")
click_menu_action(page.locator("#post-actions-panel [data-modal='edit-post-modal']"))
assert page.is_visible("h3:has-text('Edit Post')")
@@ -509,7 +509,7 @@ def test_post_edit_submit(alice):
page.fill("#post-title", "Original Title")
page.locator("#create-post-modal button.btn-primary:has-text('Post')").click()
page.wait_for_url(f"{BASE_URL}/posts/*", wait_until="domcontentloaded")
page.click("button:has-text('Edit')")
click_menu_action(page.locator("#post-actions-panel [data-modal='edit-post-modal']"))
page.fill("#edit-title", "Edited Title")
page.fill("#edit-content", "Edited content for the post")
page.click("button:has-text('Save Changes')")
+99
View File
@@ -0,0 +1,99 @@
# retoor <retoor@molodetz.nl>
import time
from playwright.sync_api import expect
from tests.conftest import BASE_URL
JSON = {"Accept": "application/json"}
def _create_post(page, content):
page.goto(f"{BASE_URL}/feed", wait_until="domcontentloaded")
page.locator(".feed-fab").first.wait_for(state="visible", timeout=10000)
page.locator(".feed-fab").first.click()
page.fill("#post-title", f"Requested {int(time.time() * 1000)}")
page.fill("#post-content", content)
page.locator("#create-post-modal button.btn-primary:has-text('Post')").click()
page.wait_for_url(f"{BASE_URL}/posts/*", wait_until="domcontentloaded")
def test_title_is_first_and_focused(alice):
page, _user = alice
page.goto(f"{BASE_URL}/feed", wait_until="domcontentloaded")
page.locator(".feed-fab").first.wait_for(state="visible", timeout=10000)
page.locator(".feed-fab").first.click()
title = page.locator("#post-title")
expect(title).to_be_focused()
order = page.evaluate(
"""() => {
const title = document.querySelector('#post-title');
const content = document.querySelector('#post-content');
return (title.compareDocumentPosition(content) & Node.DOCUMENT_POSITION_FOLLOWING) !== 0;
}"""
)
assert order is True
def test_post_detail_groups_secondary_actions_in_more_menu(alice):
page, _user = alice
_create_post(page, "Menu grouping post content.")
expect(page.locator(".post-votes")).to_be_visible()
expect(page.locator("[data-action-menu-trigger]")).to_be_visible()
panel = page.locator("#post-actions-panel")
expect(panel).to_be_hidden()
page.locator("[data-action-menu-trigger]").click()
expect(panel).to_be_visible()
expect(panel.locator("[data-share]")).to_be_visible()
expect(panel.locator(".bookmark-btn")).to_be_visible()
page.keyboard.press("Escape")
expect(panel).to_be_hidden()
def test_comment_enter_posts_and_shift_enter_newlines(alice):
page, user = alice
username = user["username"]
try:
_create_post(page, "Enter key comment post content.")
box = page.locator(".comment-form textarea[name='content']").first
box.click()
box.fill("First line")
box.press("Shift+Enter")
box.type("second line")
assert "\n" in box.input_value()
box.fill("Posted by Enter key")
box.press("Enter")
expect(page.locator(".comment-text", has_text="Posted by Enter key").first).to_be_visible(timeout=10000)
finally:
page.request.post(
f"{BASE_URL}/profile/{username}/enter-to-submit",
form={"value": "true"},
headers=JSON,
)
def test_comment_enter_newlines_when_setting_off(alice):
page, user = alice
username = user["username"]
resp = page.request.post(
f"{BASE_URL}/profile/{username}/enter-to-submit",
form={"value": "false"},
headers=JSON,
)
assert resp.status == 200
try:
_create_post(page, "Enter off comment post content.")
box = page.locator(".comment-form textarea[name='content']").first
box.click()
box.fill("Not posted yet")
box.press("Enter")
box.type("still editing")
assert "still editing" in box.input_value()
expect(page.locator(".comment-text", has_text="Not posted yet")).to_have_count(0)
finally:
page.request.post(
f"{BASE_URL}/profile/{username}/enter-to-submit",
form={"value": "true"},
headers=JSON,
)
+6 -6
View File
@@ -2,7 +2,7 @@
import time
from playwright.sync_api import expect
from tests.conftest import BASE_URL, assert_no_horizontal_overflow
from tests.conftest import BASE_URL, assert_no_horizontal_overflow, click_menu_action
def _unique():
@@ -23,7 +23,7 @@ def _compose(page, token, visibility=None):
def _edit_visibility(page, url, value):
page.goto(url, wait_until="domcontentloaded")
page.locator("[data-modal='edit-post-modal']").click()
click_menu_action(page.locator("#post-actions-panel [data-modal='edit-post-modal']"))
page.select_option("#edit-post-visibility", value)
page.locator("#edit-post-form button.btn-primary").click()
page.wait_for_url(url, wait_until="domcontentloaded")
@@ -38,7 +38,7 @@ def test_new_post_defaults_to_published(alice):
page, _ = alice
token = _unique()
url = _compose(page, token)
page.locator("[data-modal='edit-post-modal']").click()
click_menu_action(page.locator("#post-actions-panel [data-modal='edit-post-modal']"))
expect(page.locator("#edit-post-visibility")).to_have_value("published")
assert _feed_has(page, token)
page.goto(url, wait_until="domcontentloaded")
@@ -57,7 +57,7 @@ def test_create_hidden_post_leaves_the_feed(alice):
page, _ = alice
token = _unique()
url = _compose(page, token, "hidden")
page.locator("[data-modal='edit-post-modal']").click()
click_menu_action(page.locator("#post-actions-panel [data-modal='edit-post-modal']"))
expect(page.locator("#edit-post-visibility")).to_have_value("hidden")
assert not _feed_has(page, token)
page.goto(url, wait_until="domcontentloaded")
@@ -92,7 +92,7 @@ def test_offline_post_is_not_shown_to_other_members(alice, bob):
def test_edit_form_lists_the_three_choices(alice):
page, _ = alice
_compose(page, _unique())
page.locator("[data-modal='edit-post-modal']").click()
click_menu_action(page.locator("#post-actions-panel [data-modal='edit-post-modal']"))
options = page.locator("#edit-post-visibility option")
assert options.all_text_contents() == ["Published", "Hidden", "Offline"]
@@ -100,6 +100,6 @@ def test_edit_form_lists_the_three_choices(alice):
def test_visibility_field_fits_a_phone(mobile_page):
page, _ = mobile_page
_compose(page, _unique(), "hidden")
page.locator("[data-modal='edit-post-modal']").click()
click_menu_action(page.locator("#post-actions-panel [data-modal='edit-post-modal']"))
expect(page.locator("#edit-post-visibility")).to_be_visible()
assert_no_horizontal_overflow(page, ".post-page")
+6 -24
View File
@@ -3,7 +3,7 @@
from uuid import uuid4
from datetime import datetime, timezone
from playwright.sync_api import expect
from tests.conftest import BASE_URL
from tests.conftest import BASE_URL, open_action_menu
from devplacepy.database import get_table
from devplacepy.utils import make_combined_slug
@@ -15,33 +15,15 @@ def _confirm(page):
page.locator(".dialog-overlay.visible .dialog-confirm").click()
TRIGGER = "[data-action-menu-trigger]"
def _open_menu(page):
# aria-expanded can lag behind the popover (a dialog closing, a light
# dismiss), so the open state that counts is whether the panel shows.
page.wait_for_function(
"() => document.querySelector('[data-action-menu-panel]') !== null"
" || document.querySelector('[data-action-menu-trigger]') === null"
)
panel = page.locator("[data-action-menu-panel]")
if panel.count() and panel.evaluate("(el) => el.matches(':popover-open')"):
return
page.click(TRIGGER)
page.wait_for_function(
"() => document.querySelector('[data-action-menu-panel]').matches(':popover-open')"
)
def _has(page, selector):
_open_menu(page)
return page.is_visible(selector)
loc = page.locator(selector)
if loc.count() == 0:
return False
return open_action_menu(loc).is_visible()
def _pick(page, selector):
_open_menu(page)
page.click(selector)
open_action_menu(page.locator(selector)).click()
def _reset_block(page):
+6 -24
View File
@@ -1,7 +1,7 @@
# retoor <retoor@molodetz.nl>
from playwright.sync_api import expect
from tests.conftest import BASE_URL
from tests.conftest import BASE_URL, open_action_menu
MUTE = "form[action='/mute/bob_test'] button"
UNMUTE = "form[action='/mute/unmute/bob_test'] button"
@@ -11,33 +11,15 @@ def _confirm(page):
page.locator(".dialog-overlay.visible .dialog-confirm").click()
TRIGGER = "[data-action-menu-trigger]"
def _open_menu(page):
# aria-expanded can lag behind the popover (a dialog closing, a light
# dismiss), so the open state that counts is whether the panel shows.
page.wait_for_function(
"() => document.querySelector('[data-action-menu-panel]') !== null"
" || document.querySelector('[data-action-menu-trigger]') === null"
)
panel = page.locator("[data-action-menu-panel]")
if panel.count() and panel.evaluate("(el) => el.matches(':popover-open')"):
return
page.click(TRIGGER)
page.wait_for_function(
"() => document.querySelector('[data-action-menu-panel]').matches(':popover-open')"
)
def _has(page, selector):
_open_menu(page)
return page.is_visible(selector)
loc = page.locator(selector)
if loc.count() == 0:
return False
return open_action_menu(loc).is_visible()
def _pick(page, selector):
_open_menu(page)
page.click(selector)
open_action_menu(page.locator(selector)).click()
def _reset_mute(page):
+4 -2
View File
@@ -3,7 +3,7 @@
from uuid import uuid4
from datetime import datetime, timezone, timedelta
from playwright.sync_api import expect
from tests.conftest import BASE_URL
from tests.conftest import BASE_URL, open_action_menu
from devplacepy.database import get_table
from devplacepy.utils import make_combined_slug
@@ -133,7 +133,9 @@ def test_devlog_shows_vote_and_comment_buttons(alice):
expect(post_card.locator(".post-action-btn.vote-up")).to_be_visible()
expect(post_card.locator(".post-action-btn.vote-down")).to_be_visible()
expect(post_card.locator(".post-vote-count")).to_be_visible()
expect(post_card.locator("form[action*='/posts/delete/']")).to_be_visible()
delete_form = post_card.locator("form[action*='/posts/delete/']")
open_action_menu(delete_form)
expect(delete_form).to_be_visible()
def test_devlog_load_more_appears_with_many_posts(alice):
+10 -10
View File
@@ -5,7 +5,7 @@ import time
from playwright.sync_api import expect
from devplacepy.database import get_table, refresh_snapshot, set_setting
from tests.conftest import BASE_URL, CACHE_VERSION_PROPAGATION_SECONDS
from tests.conftest import BASE_URL, CACHE_VERSION_PROPAGATION_SECONDS, click_menu_action, open_action_menu
def _create_post(page, content):
@@ -24,8 +24,9 @@ def test_the_report_control_is_present_on_the_feed_and_a_post(alice, bob):
_create_post(alice_page, "A post that another member can report from the feed.")
bob_page.goto(f"{BASE_URL}/feed", wait_until="domcontentloaded")
expect(bob_page.locator(".report-btn").first).to_be_visible()
expect(bob_page.locator(".block-btn").first).to_be_attached()
report = open_action_menu(bob_page.locator(".post-card .report-btn").first)
expect(report).to_be_visible()
expect(bob_page.locator(".post-card .block-btn").first).to_be_attached()
def test_the_report_control_is_absent_on_your_own_content(alice):
@@ -41,7 +42,7 @@ def test_reporting_a_post_end_to_end_through_the_dialog(alice, bob):
slug = _create_post(alice_page, "A post reported end to end through the dialog.")
bob_page.goto(f"{BASE_URL}/posts/{slug}", wait_until="domcontentloaded")
bob_page.locator(".report-btn").first.click()
click_menu_action(bob_page.locator("#post-actions-panel .report-btn"))
dialog = bob_page.locator("#report-dialog")
dialog.wait_for(state="visible")
@@ -61,7 +62,7 @@ def test_the_admin_queue_shows_the_report_and_its_sla_badge(alice, bob):
slug = _create_post(alice_page, "A post that must appear in the moderation queue.")
bob_page.goto(f"{BASE_URL}/posts/{slug}", wait_until="domcontentloaded")
bob_page.locator(".report-btn").first.click()
click_menu_action(bob_page.locator("#post-actions-panel .report-btn"))
bob_page.locator("#report-dialog").wait_for(state="visible")
bob_page.select_option("#report-reason", "spam")
bob_page.locator("#report-form button[type='submit']").click()
@@ -88,9 +89,10 @@ def test_blocking_from_a_content_action_bar_hides_the_author(alice, bob):
_create_post(alice_page, marker)
bob_page.goto(f"{BASE_URL}/feed", wait_until="domcontentloaded")
expect(bob_page.locator(".post-card").first).to_be_visible()
card = bob_page.locator(".post-card").filter(has_text=marker).first
expect(card).to_be_visible()
bob_page.locator(".block-btn").first.click()
click_menu_action(card.locator(".block-btn"))
bob_page.locator(".dialog-overlay.visible .dialog-confirm").click()
bob_page.wait_for_load_state("domcontentloaded")
@@ -100,9 +102,7 @@ def test_blocking_from_a_content_action_bar_hides_the_author(alice, bob):
bob_page.goto(
f"{BASE_URL}/profile/{alice_user['username']}", wait_until="domcontentloaded"
)
bob_page.locator("[data-action-menu-trigger]").first.click()
bob_page.locator("[data-action-menu-panel]").wait_for(state="visible")
bob_page.locator("button:has-text('Unblock')").first.click()
click_menu_action(bob_page.locator("#profile-actions-panel button:has-text('Unblock')"))
bob_page.locator(".dialog-overlay.visible .dialog-confirm").click()
bob_page.wait_for_load_state("domcontentloaded")
+10 -15
View File
@@ -1,7 +1,7 @@
# retoor <retoor@molodetz.nl>
from playwright.sync_api import expect
from tests.conftest import BASE_URL
from tests.conftest import BASE_URL, open_action_menu
from tests.e2e.project.files import _make_project_ui
def _open_project_with_delete(page, title):
proj_url = _make_project_ui(page, title)
@@ -12,19 +12,13 @@ PANEL = "[data-action-menu-panel]"
def _open_menu(page):
# aria-expanded can lag behind the popover, so the open state that counts
# is whether the panel shows.
page.wait_for_function(
"() => document.querySelector('[data-action-menu-panel]') !== null"
" || document.querySelector('[data-action-menu-trigger]') === null"
)
panel = page.locator(PANEL)
if panel.count() and panel.evaluate("(el) => el.matches(':popover-open')"):
panel = page.locator("#project-actions-panel")
if panel.count():
open_action_menu(panel)
return
page.click(TRIGGER)
page.wait_for_function(
"() => document.querySelector('[data-action-menu-panel]').matches(':popover-open')"
)
trigger = page.locator(TRIGGER).first
if trigger.count():
trigger.click()
def _menu_item(page, label):
@@ -35,8 +29,9 @@ def _menu_item(page, label):
def _pick(page, label):
_open_menu(page)
_menu_item(page, label).first.click()
item = _menu_item(page, label).first
open_action_menu(item)
item.click()
def _click_delete(page):
+113
View File
@@ -0,0 +1,113 @@
# retoor <retoor@molodetz.nl>
from datetime import datetime, timezone
from devplacepy.database import (
NOTIFICATION_GROUP_KEYS,
count_unread_groups,
get_notification_grouping_enabled,
get_notification_throttle_enabled,
notification_group_key,
set_notification_grouping_enabled,
set_notification_throttle_enabled,
)
from devplacepy.utils import generate_uid
def _row(ntype, related="actor-1", target="/posts/x", uid=None):
return {
"type": ntype,
"related_uid": related,
"target_url": target,
"uid": uid or generate_uid(),
}
def test_group_key_actor_target_single():
assert notification_group_key(_row("message")) == ("message", "actor-1", "/posts/x")
assert notification_group_key(_row("vote", related="a")) == notification_group_key(
_row("vote", related="b")
)
assert notification_group_key(_row("follow", related="a", target="/profile/a")) == ("follow",)
assert notification_group_key(_row("follow", related="b", target="/profile/b")) == ("follow",)
single = _row("badge")
assert notification_group_key(single) == ("badge", single["uid"])
def test_group_key_unlisted_type_is_single():
row = _row("some_future_type")
assert NOTIFICATION_GROUP_KEYS.get("some_future_type", "single") == "single"
assert notification_group_key(row) == ("some_future_type", row["uid"])
def test_all_registered_types_have_a_group_shape():
from devplacepy.database import NOTIFICATION_TYPES
for entry in NOTIFICATION_TYPES:
assert NOTIFICATION_GROUP_KEYS[entry["key"]] in ("actor", "target", "single")
def _seed_user(local_db, suffix):
uid = f"notif-{suffix}-{generate_uid()[-8:]}"
local_db["users"].insert(
{
"uid": uid,
"username": uid,
"terms_version": "1",
"role": "Member",
"created_at": "1990-01-01T00:00:00",
"deleted_at": None,
}
)
return uid
def _seed_notifications(local_db, user_uid, count, ntype="vote"):
table = local_db["notifications"]
now = datetime.now(timezone.utc).isoformat()
for i in range(count):
table.insert(
{
"uid": generate_uid(),
"user_uid": user_uid,
"type": ntype,
"message": f"seeded {i}",
"related_uid": f"actor-{i}",
"target_url": "/posts/seeded",
"read": False,
"created_at": now,
}
)
def test_count_unread_groups_respects_setting(local_db):
uid = _seed_user(local_db, "groups")
try:
_seed_notifications(local_db, uid, 5)
assert get_notification_grouping_enabled(uid) is True
assert count_unread_groups(uid) == 1
set_notification_grouping_enabled(uid, False)
assert get_notification_grouping_enabled(uid) is False
assert count_unread_groups(uid) == 5
set_notification_grouping_enabled(uid, True)
assert count_unread_groups(uid) == 1
finally:
local_db["notifications"].delete(user_uid=uid)
local_db["users"].delete(uid=uid)
def test_throttle_setting_defaults_on_and_toggles(local_db):
uid = _seed_user(local_db, "throttle")
try:
assert get_notification_throttle_enabled(uid) is True
set_notification_throttle_enabled(uid, False)
assert get_notification_throttle_enabled(uid) is False
set_notification_throttle_enabled(uid, True)
assert get_notification_throttle_enabled(uid) is True
finally:
local_db["users"].delete(uid=uid)
def test_missing_user_defaults_on():
assert get_notification_grouping_enabled("no-such-user") is True
assert get_notification_throttle_enabled("no-such-user") is True

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