Skip to content

:hedgehog: PostHog is the leading platform for building self-driving products. Our developer tools – AI observability, analytics, session replay, flags, experiments, error tracking, logs, and more – capture all the context agents need to diagnose problems, uncover opportunities, and ship fixes. Steer it all from Slack, web, desktop, or the MCP.

feat(devex): admin console ux pass and agent steering (#129884)

Julian Bez145223708e17
diff --git a/.agents/skills/extending-the-admin-console/SKILL.md b/.agents/skills/extending-the-admin-console/SKILL.md
new file mode 100644
index 000000000000..e7cb27c7639b
--- /dev/null
+++ b/.agents/skills/extending-the-admin-console/SKILL.md
@@ -0,0 +1,57 @@
+---
+name: extending-the-admin-console
+description: Add or change what staff see and do in PostHog Admin, the staff console at /admin/console/. Use when adding a panel to a team page, a staff action (an operation), or a cross-team report (a tool) in a `console.py`, when moving a button, view or page out of Django admin into the console, or when asked to "add an admin action", "add a staff tool", "show X to support in admin", or to touch `posthog/admin/console/` or `posthog/templates/admin_console/`. Covers choosing panel vs tool vs Django admin, the data-only contract, copy, danger operations, replacing the old Django admin entry point, and the checks before calling it done.
+---
+
+# Extending the admin console
+
+PostHog Admin is a shared surface. Every team adds to it, and staff use it under pressure, often while a customer waits.
+Consistency is the feature: a panel that looks and reads like every other panel is one staff can use without thinking.
+Read [`posthog/admin/console/AGENTS.md`](../../../posthog/admin/console/AGENTS.md) first. It holds the invariants and the add-a-panel and add-a-tool recipes. This skill holds the judgment around them.
+
+## 1. Decide where it goes
+
+- **Plain create, read, update or delete on one model** stays in Django admin. The console is not a second CRUD layer.
+- **Facts and actions about one team** go in a panel. One panel per product concern, owned by the team that owns the data.
+- **A report across many teams** is a tool. Tools only read. An action from a tool row links to the team page.
+- **A staff page your product already has in the app** (a DRF staff endpoint and scene) is legacy. Do not extend it and do not bridge to it. Ask the user whether to move it into the console as its own change.
+- **Anything else** (a new record type such as an organization or user page, a new block kind, a new tool group, a template change) is a shell change. Stop and ask the user: those need a review by the console owners (team-devex), not a product team alone.
+
+## 2. Write the panel or tool as data
+
+- Return `Fact`, `Operation` and tool blocks only. The contract rejects markup, unknown blocks and bad keys at import or render time, so fix the contribution, not the check.
+- Keep the logic out of `console.py`. Facts and handlers call your product's facade or a service function, even when the product is not isolated yet. `console.py` is an adapter, like a view: no ORM queries, no `.delay()` calls, no cache clients. A small dataclass the facade returns goes where [products/architecture.md](../../../products/architecture.md) puts facade contracts.
+- Show at most `MAX_FACTS_PER_PANEL` facts. Pick the ones that answer the questions staff ask in a ticket. History and long lists belong in a tool.
+- Do not repeat facts another panel shows (team ID, organization, API token are in Overview).
+
+## 3. Copy
+
+Invoke `/writing-user-facing-copy`. In the console that means:
+
+- Sentence case for titles, labels and buttons. Keep proper nouns and acronyms as they are (API, AI, ClickHouse).
+- An operation label starts with a verb and names the effect: "Suspend email sending", not "Email" or "Submit".
+- Use the words staff see in the app, not field names. "Revoked" beats `llm_gateway_revoked_at`.
+- An `Operation.description` says what happens to the customer, for example "The team gets an email".
+
+## 4. Classify every operation
+
+- **Read only** needs no operation at all. Make it a fact.
+- **Internal and reversible** (rebuild, clear or purge a cache that refills itself) is a plain operation.
+- **Gives the customer something back** (enable access, clear a revoke, re-enable sending, add credit) is a plain operation. Give it a form only when it needs input, as Add credit does for the amount and the reason.
+- **Takes something away from the customer, or cannot be undone** (suspend, revoke, replace a token) sets `danger=True`, takes a form with a `reason` field, and sets `undo_hint` to how staff undo it, or that they cannot. The console writes the reason to the audit log and shows the undo hint on the confirm page.
+- A handler that moves money or sends messages builds its idempotency key from the `form_nonce` the console posts, so a double submit runs once.
+- Offer an operation only in the state where it makes sense. The console runs only operations the panel offers right now.
+- To report a failure, a handler adds an error message and returns a 4xx or 5xx response. For an operation with a form, the console then shows the form again with what staff typed.
+
+## 5. Move a Django admin action without losing anyone
+
+1. Point the operation at the old view with `AdminViewBridge(Model, SomeAdmin.view_method)` while the logic still lives in the `ModelAdmin`.
+2. Replace the old button in Django admin with `MovedToConsole.team_action(team, "<panel-key>", "<what moved>")`, so staff who look in the usual place find the new one.
+3. When a whole page moves, keep its old URL name and route it to `MovedToConsole.page_redirect`, which tells staff the page moved.
+
+## 6. Before you call it done
+
+- Extend `posthog/admin/test_admin_console.py`: add the panel title to the team page test, and a parameterized case for each new operation's success and refusal. Do not add a new test file.
+- Run `pnpm --filter=@posthog/frontend build:admin-console` when you add an owner crest. Commit the output.
+- Open `/admin/console/teams/<id>/` on the local stack (log in as `[email protected]`) and look at the page at a narrow and a wide window. A panel that reads wrong in the browser is not done, whatever the tests say.
+- Put a screenshot of the panel in the PR description.
diff --git a/ee/urls.py b/ee/urls.py
index 7ead385d6be0..d3dc429fc274 100644
--- a/ee/urls.py
+++ b/ee/urls.py
@@ -10,6 +10,7 @@ from django_otp.plugins.otp_static.models import StaticDevice
from django_otp.plugins.otp_totp.models import TOTPDevice
from posthog.admin import register_all_admin
+from posthog.admin.console.moved import MovedToConsole
from posthog.admin.oauth2 import admin_oauth2_callback
from posthog.admin.oauth_views import admin_auth_check, admin_oauth_success
from posthog.api.sso import saml_metadata_view
@@ -101,7 +102,7 @@ if settings.ADMIN_PORTAL_ENABLED:
),
path(
"admin/events-retention/",
- RedirectView.as_view(url="/admin/console/tools/events-retention/", permanent=False, query_string=True),
+ MovedToConsole.page_redirect("Events retention", "/admin/console/tools/events-retention/"),
name="events-retention",
),
path(
diff --git a/frontend/public/admin-console/console.css b/frontend/public/admin-console/console.css
index 7e22f6cb943f..1c10af1dde86 100644
--- a/frontend/public/admin-console/console.css
+++ b/frontend/public/admin-console/console.css
@@ -9,6 +9,7 @@
--container-sm: 24rem;
--container-xl: 36rem;
--container-3xl: 48rem;
+ --container-5xl: 64rem;
--text-xs: 0.75rem;
--text-xs--line-height: 1rem;
--text-sm: 0.875rem;
@@ -383,6 +384,9 @@
.order-1 {
order: 1;
}
+ .col-span-2 {
+ grid-column: span 2 / span 2;
+ }
.container {
width: 100%;
}
@@ -447,8 +451,11 @@
.mt-2 {
margin-top: calc(0.25rem * 2);
}
- .mt-3 {
- margin-top: calc(0.25rem * 3);
+ .mt-4 {
+ margin-top: calc(0.25rem * 4);
+ }
+ .mt-8 {
+ margin-top: calc(0.25rem * 8);
}
.mt-auto {
margin-top: auto;
@@ -459,9 +466,15 @@
.mr-auto {
margin-right: auto;
}
+ .mb-0\.5 {
+ margin-bottom: calc(0.25rem * 0.5);
+ }
.mb-1 {
margin-bottom: calc(0.25rem * 1);
}
+ .mb-2 {
+ margin-bottom: calc(0.25rem * 2);
+ }
.mb-4 {
margin-bottom: calc(0.25rem * 4);
}
@@ -518,6 +531,10 @@
width: 7px;
height: 7px;
}
+ .size-\[18px\] {
+ width: 18px;
+ height: 18px;
+ }
.size-\[22px\] {
width: 22px;
height: 22px;
@@ -564,6 +581,12 @@
.w-10 {
width: calc(0.25rem * 10);
}
+ .w-12 {
+ width: calc(0.25rem * 12);
+ }
+ .w-16 {
+ width: calc(0.25rem * 16);
+ }
.w-24 {
width: calc(0.25rem * 24);
}
@@ -605,6 +628,9 @@
.max-w-3xl {
max-width: var(--container-3xl);
}
+ .max-w-5xl {
+ max-width: var(--container-5xl);
+ }
.max-w-\[32rem\] {
max-width: 32rem;
}
@@ -679,6 +705,9 @@
.cursor-row-resize {
cursor: row-resize;
}
+ .scroll-mt-4 {
+ scroll-margin-top: calc(0.25rem * 4);
+ }
.scroll-py-4 {
scroll-padding-block: calc(0.25rem * 4);
}
@@ -691,15 +720,18 @@
.list-disc {
list-style-type: disc;
}
+ .list-none {
+ list-style-type: none;
+ }
.grid-cols-7 {
grid-template-columns: repeat(7, minmax(0, 1fr));
}
- .grid-cols-\[96px_1fr\] {
- grid-template-columns: 96px 1fr;
- }
.grid-cols-\[max-content_1fr\] {
grid-template-columns: max-content 1fr;
}
+ .grid-cols-subgrid {
+ grid-template-columns: subgrid;
+ }
.flex-col {
flex-direction: column;
}
@@ -773,6 +805,10 @@
-moz-column-gap: calc(0.25rem * 2);
column-gap: calc(0.25rem * 2);
}
+ .gap-x-3 {
+ -moz-column-gap: calc(0.25rem * 3);
+ column-gap: calc(0.25rem * 3);
+ }
.gap-x-4 {
-moz-column-gap: calc(0.25rem * 4);
column-gap: calc(0.25rem * 4);
@@ -783,9 +819,15 @@
.gap-y-1\.5 {
row-gap: calc(0.25rem * 1.5);
}
+ .gap-y-2 {
+ row-gap: calc(0.25rem * 2);
+ }
.self-start {
align-self: flex-start;
}
+ .self-stretch {
+ align-self: stretch;
+ }
.truncate {
overflow: hidden;
text-overflow: ellipsis;
@@ -900,6 +942,9 @@
.p-4 {
padding: calc(0.25rem * 4);
}
+ .px-0 {
+ padding-inline: calc(0.25rem * 0);
+ }
.px-1\.5 {
padding-inline: calc(0.25rem * 1.5);
}
@@ -945,6 +990,9 @@
.pt-3 {
padding-top: calc(0.25rem * 3);
}
+ .pt-4 {
+ padding-top: calc(0.25rem * 4);
+ }
.pt-5 {
padding-top: calc(0.25rem * 5);
}
@@ -1083,6 +1131,15 @@
.no-underline {
text-decoration-line: none;
}
+ .underline {
+ text-decoration-line: underline;
+ }
+ .decoration-border {
+ text-decoration-color: var(--border);
+ }
+ .underline-offset-2 {
+ text-underline-offset: 2px;
+ }
.opacity-0 {
opacity: 0%;
}
@@ -1264,6 +1321,11 @@
.empty\:hidden:empty {
display: none;
}
+ @media (hover: hover) {
+ .hover\:border-primary:hover {
+ border-color: var(--primary);
+ }
+ }
@media (hover: hover) {
.hover\:bg-fill-hover\/50:hover {
background-color: var(--fill-hover);
@@ -1284,14 +1346,58 @@
color: var(--foreground);
}
}
+ @media (hover: hover) {
+ .hover\:underline:hover {
+ text-decoration-line: underline;
+ }
+ }
+ @media (hover: hover) {
+ .hover\:decoration-current:hover {
+ text-decoration-color: currentcolor;
+ }
+ }
@media (hover: hover) {
.not-disabled\:hover\:bg-fill-hover:not(*:disabled):hover {
background-color: var(--fill-hover);
}
}
+ .focus\:not-sr-only:focus {
+ position: static;
+ width: auto;
+ height: auto;
+ padding: 0;
+ margin: 0;
+ overflow: visible;
+ clip-path: none;
+ white-space: normal;
+ }
+ .focus\:absolute:focus {
+ position: absolute;
+ }
+ .focus\:top-2:focus {
+ top: calc(0.25rem * 2);
+ }
+ .focus\:left-2:focus {
+ left: calc(0.25rem * 2);
+ }
+ .focus\:z-10:focus {
+ z-index: 10;
+ }
+ .focus\:rounded:focus {
+ border-radius: 0.25rem;
+ }
+ .focus\:bg-background:focus {
+ background-color: var(--background);
+ }
.focus\:bg-fill-hover:focus {
background-color: var(--fill-hover);
}
+ .focus\:px-3:focus {
+ padding-inline: calc(0.25rem * 3);
+ }
+ .focus\:py-2:focus {
+ padding-block: calc(0.25rem * 2);
+ }
.focus-visible\:pointer-events-auto:focus-visible {
pointer-events: auto;
}
@@ -1348,6 +1454,13 @@
.aria-selected\:bg-fill-selected[aria-selected='true'] {
background-color: var(--fill-selected);
}
+ .aria-\[current\=page\]\:bg-\[var\(--fill-selected\)\][aria-current='page'] {
+ background-color: var(--fill-selected);
+ }
+ .aria-\[current\=page\]\:font-bold[aria-current='page'] {
+ --tw-font-weight: var(--font-weight-bold);
+ font-weight: var(--font-weight-bold);
+ }
.aria-\[orientation\=vertical\]\:flex-col[aria-orientation='vertical'] {
flex-direction: column;
}
@@ -1598,11 +1711,6 @@
flex: auto;
}
}
- @container (width >= 48rem) {
- .\@3xl\:col-span-2 {
- grid-column: span 2 / span 2;
- }
- }
@container (width >= 48rem) {
.\@3xl\:grid-cols-2 {
grid-template-columns: repeat(2, minmax(0, 1fr));
@@ -8765,22 +8873,24 @@ body.is-desktop .group\/field:has(> [role='checkbox']) .quill-label {
.console-env-dot {
background: var(--console-env);
}
- .console-danger {
- background: var(--destructive);
- }
- @supports (color: color-mix(in lab, red, red)) {
- .console-danger {
- background: color-mix(in oklab, var(--destructive) 35%, var(--card));
- }
+ :where(a, button, input, select, textarea, summary):focus-visible {
+ outline: 2px solid var(--primary-dark);
+ outline-offset: 2px;
}
.console-danger {
- border-color: var(--destructive-foreground);
+ box-shadow: 0 0 0 1px var(--destructive-foreground);
+ }
+ .console-attention {
+ background: var(--warning);
}
@supports (color: color-mix(in lab, red, red)) {
- .console-danger {
- border-color: color-mix(in oklab, var(--destructive-foreground) 45%, transparent);
+ .console-attention {
+ background: color-mix(in oklab, var(--warning) 45%, var(--card));
}
}
+ .console-attention {
+ box-shadow: 0 0 0 1px var(--warning-foreground);
+ }
}
@property --tw-translate-x {
syntax: '*';
diff --git a/frontend/public/admin-console/console.js b/frontend/public/admin-console/console.js
index 41e90ade6fbf..4f5662f7fe86 100644
--- a/frontend/public/admin-console/console.js
+++ b/frontend/public/admin-console/console.js
@@ -10,3 +10,19 @@ document.addEventListener('submit', (event) => {
button.setAttribute('aria-busy', 'true')
}
})
+
+document.addEventListener('keydown', (event) => {
+ const target = event.target
+ const typing =
+ target instanceof HTMLElement && (target.isContentEditable || target.closest('input, textarea, select'))
+ if (event.key !== '/' || typing || event.metaKey || event.ctrlKey || event.altKey) {
+ return
+ }
+ const search = document.getElementById('team-search')
+ if (search) {
+ event.preventDefault()
+ search.focus()
+ }
+})
+
+document.querySelector('form[data-autofocus]')?.querySelector('input:not([type=hidden]), textarea, select')?.focus()
diff --git a/frontend/src/styles/admin-console.css b/frontend/src/styles/admin-console.css
index 63904eff2d1e..a46c16edbfed 100644
--- a/frontend/src/styles/admin-console.css
+++ b/frontend/src/styles/admin-console.css
@@ -82,8 +82,21 @@
background: var(--console-env);
}
+ /* A destructive ring instead of a tinted fill, so the env tint (warm in US) cannot wash it out. */
+
+ /* quill's focus ring is a faint shadow. Staff who work from the keyboard need a solid one. */
+ :where(a, button, input, select, textarea, summary):focus-visible {
+ outline: 2px solid var(--primary-dark);
+ outline-offset: 2px;
+ }
+
+ /* quill draws a card's border as a 1px box-shadow ring. */
.console-danger {
- background: color-mix(in oklab, var(--destructive) 35%, var(--card));
- border-color: color-mix(in oklab, var(--destructive-foreground) 45%, transparent);
+ box-shadow: 0 0 0 1px var(--destructive-foreground);
+ }
+
+ .console-attention {
+ background: color-mix(in oklab, var(--warning) 45%, var(--card));
+ box-shadow: 0 0 0 1px var(--warning-foreground);
}
}
diff --git a/posthog/admin/admins/team_admin.py b/posthog/admin/admins/team_admin.py
index f8df604126da..a158873ec895 100644
--- a/posthog/admin/admins/team_admin.py
+++ b/posthog/admin/admins/team_admin.py
@@ -30,6 +30,7 @@ from temporalio import common
from temporalio.client import WorkflowExecutionStatus
from temporalio.common import SearchAttributePair, TypedSearchAttributes
+from posthog.admin.console.moved import MovedToConsole
from posthog.admin.inline_registry import extra_inlines_for
from posthog.admin.inlines.events_retention_config_inline import TeamEventsRetentionConfigInline
from posthog.admin.inlines.organization_member_for_related_inline import OrganizationMemberForRelatedInline
@@ -641,11 +642,10 @@ class TeamAdmin(admin.ModelAdmin):
def api_token_display(self, team: Team):
if not team.pk:
return "-"
- set_url = reverse("admin:posthog_team_set_api_token", args=[team.pk])
return format_html(
- '<span>{}</span> &nbsp; <a class="button" href="{}">Set API token</a>',
+ "<span>{}</span> &nbsp; {}",
team.api_token,
- set_url,
+ MovedToConsole.team_action(team, "api-token", "Set API token"),
)
@admin.display(description="Delete recordings")
@@ -679,8 +679,7 @@ class TeamAdmin(admin.ModelAdmin):
"admin/posthog/team/remote_config_cache_actions.html",
{
"view_url": reverse("admin:posthog_team_view_cache", args=[team.pk]),
- "rebuild_url": reverse("admin:posthog_team_rebuild_cache", args=[team.pk]),
- "team_name": team.name,
+ "rebuild_moved": MovedToConsole.team_action(team, "remote-config", "Rebuild cache"),
"cache_key": RemoteConfig.get_hypercache().get_cache_key(team.api_token),
},
)
@@ -948,20 +947,7 @@ class TeamAdmin(admin.ModelAdmin):
def email_sending_suspension_actions(self, team: Team):
if not team.pk:
return "-"
- state = get_email_sending_state(team.pk)
- is_suspended = bool(state and state.suspended_at)
- # nosemgrep: python.django.security.audit.avoid-mark-safe.avoid-mark-safe (admin-only, renders trusted template)
- return mark_safe(
- render_to_string(
- "admin/posthog/team/email_sending_suspension_actions.html",
- {
- "suspend_url": reverse("admin:posthog_team_suspend_email_sending", args=[team.pk]),
- "unsuspend_url": reverse("admin:posthog_team_unsuspend_email_sending", args=[team.pk]),
- "team_name": team.name,
- "is_suspended": is_suspended,
- },
- )
- )
+ return MovedToConsole.team_action(team, "email-sending", "Suspending and re-enabling email sending")
@admin.display(description="Email sending tier")
def email_sending_tier_state(self, team: Team) -> str:
@@ -1235,20 +1221,7 @@ class TeamAdmin(admin.ModelAdmin):
def ai_gateway_actions(self, team: Team):
if not team.pk:
return "-"
- # nosemgrep: python.django.security.audit.avoid-mark-safe.avoid-mark-safe (admin-only, renders trusted template)
- return mark_safe(
- render_to_string(
- "admin/posthog/team/ai_gateway_actions.html",
- {
- "enable_url": reverse("admin:posthog_team_enable_ai_gateway", args=[team.pk]),
- "revoke_url": reverse("admin:posthog_team_revoke_ai_gateway", args=[team.pk]),
- "clear_revoke_url": reverse("admin:posthog_team_clear_ai_gateway_revoke", args=[team.pk]),
- "team_name": team.name,
- "is_enabled": team.llm_gateway_enabled_at is not None,
- "is_revoked": team.llm_gateway_revoked_at is not None,
- },
- )
- )
+ return MovedToConsole.team_action(team, "ai-gateway", "Enabling and revoking access")
@admin.display(description="Admit state")
def admit_state(self, team: Team):
@@ -1279,7 +1252,7 @@ class TeamAdmin(admin.ModelAdmin):
"admin/posthog/team/ai_gateway_wallet_actions.html",
{
"wallet_url": reverse("admin:posthog_team_ai_gateway_wallet", args=[team.pk]),
- "add_credit_url": reverse("admin:posthog_team_add_ai_gateway_credit", args=[team.pk]),
+ "add_credit_moved": MovedToConsole.team_action(team, "ai-gateway", "Add credit"),
},
)
)
diff --git a/posthog/admin/console/AGENTS.md b/posthog/admin/console/AGENTS.md
index b2acf8342565..bcb032b0fced 100644
--- a/posthog/admin/console/AGENTS.md
+++ b/posthog/admin/console/AGENTS.md
@@ -4,6 +4,7 @@ The staff back office at `/admin/console/`.
It replaces custom Django admin views and templates for staff workflows.
The `no-new-custom-admin-views` semgrep rule blocks new ones, and the program ends when its findings reach zero.
The Django admin stays for plain CRUD on models.
+Before you add or change a panel, operation or tool, invoke `/extending-the-admin-console`. It holds the judgment calls: where a change goes, copy, how to classify an operation, and the checks before done.
## Invariants
@@ -11,11 +12,12 @@ The Django admin stays for plain CRUD on models.
- **Staff operations never go through DRF, MCP, or API keys.** Keys and MCP tokens skip the admin step-up. An operation is a Python callable that a console view runs.
- **A panel returns data, not markup.** Subclass `Panel` and return `Fact` and `Operation` objects. Do not write templates, `format_html`, or `mark_safe` for a panel. The shell renders every panel the same way, so a new panel cannot drift from the design.
- **Only the shell writes templates** (`posthog/templates/admin_console/`). They use quill's `quill-*` classes and Tailwind utilities, with the markup quill's React components emit, including their `data-*` attributes.
-- **A destructive operation sets `danger=True` and has a form with a `reason` field.** `Operation` refuses it otherwise, and the console writes the reason to the audit log.
+- **A destructive operation sets `danger=True`, has a form with a `reason` field, and sets `undo_hint`.** `Operation` refuses it otherwise. The console writes the reason to the audit log and shows the undo hint on the confirm page.
+- **The contract checks itself.** The registry refuses a key that is not a slug, a blank title and a tool group outside `TOOL_GROUPS`. `Fact` refuses markup, and `Page` refuses unknown blocks and table rows of the wrong width. When a check fires, fix the contribution. Do not loosen the check in the same change.
## Add a panel
-1. In `products/<product>/backend/console.py`, subclass `Panel` and decorate it with `@console.register_panel`. Import only your product's `facade/` and `posthog.admin.console`. `products/workflows/backend/console.py` is the reference.
+1. In `products/<product>/backend/console.py`, subclass `Panel` and decorate it with `@console.register_panel`. Import only your product's `facade/`, `posthog.admin.console`, and, for a bridge, the `ModelAdmin` that still holds the view. `products/workflows/backend/console.py` is the reference.
2. Set `owner = Owner(name=..., crest=...)`. The crest is a mini crest slug from `@posthog/brand`, for example `workflows`.
3. For each action, return an `Operation`. Put its inputs in a Django `forms.Form` (`form_class`); the console renders and validates it. Its `handler(request, obj, form)` returns `None` when done. The handler is a service function, or `AdminViewBridge(Model, SomeAdmin.view_method)` while the logic still lives in a `ModelAdmin`. A bridged view must take a POST and answer with a redirect. Later, replace the bridge with a service function; the panel stays as it is.
4. Run `pnpm --filter=@posthog/frontend build:admin-console` when you add an owner crest or change a template. `posthog/admin/test_admin_console.py` fails when a template class or an owner crest is missing from the build output.
@@ -26,7 +28,11 @@ A tool is a page that is not about one record, for example a report across all t
1. In `products/<product>/backend/console.py`, subclass `ConsoleTool` and decorate it with `@console.register_tool`. Set `key`, `title`, `owner` and `group`; the group is the navigation heading. `posthog/admin/console/events_retention_tool.py` is the reference.
2. `page(request)` returns a `Page` of blocks (`Notice`, `Table` with `Row` and `GroupRow`, `Paging`). The console renders the blocks, so a tool needs no template. When a tool needs a block that does not exist, add it to `tools.py` and `tool.html` in the shell, not a template in the product.
-3. When a tool replaces a Django admin page, keep the old URL name as a redirect to the tool, so existing links keep working.
+3. When a tool replaces a Django admin page, keep the old URL name and point it at `MovedToConsole.page_redirect`, so existing links keep working.
+
+## Move a Django admin action
+
+Replace the old button with `MovedToConsole.team_action(team, panel_key, label)` from `moved.py`. It links to the panel on the console team page, so staff who look in the usual place find the new one. When a whole page moves, route its old URL to `MovedToConsole.page_redirect(title, url)`, which tells staff the page moved.
## Read when needed
diff --git a/posthog/admin/console/bridge.py b/posthog/admin/console/bridge.py
index 5fbc0cb80d55..279b1279e622 100644
--- a/posthog/admin/console/bridge.py
+++ b/posthog/admin/console/bridge.py
@@ -2,13 +2,26 @@ from collections.abc import Callable
from typing import Any
from django import forms
-from django.contrib import admin
+from django.contrib import admin, messages
+from django.contrib.messages.storage.base import BaseStorage
from django.db.models import Model
from django.http import HttpRequest, HttpResponse, HttpResponseRedirect
AdminView = Callable[[Any, HttpRequest, str], HttpResponse]
+class QueuedMessages:
+ @staticmethod
+ def error_count(request: HttpRequest) -> int:
+ storage = messages.get_messages(request)
+ if not isinstance(storage, BaseStorage):
+ return 0
+ count = sum(1 for message in storage if message.level >= messages.ERROR)
+ # Reading the messages marks them as shown. Keep them for the page that renders next.
+ storage.used = False
+ return count
+
+
class AdminViewBridge:
"""Run an existing Django admin view as a console operation.
@@ -21,7 +34,8 @@ class AdminViewBridge:
Only bridge views that take a POST and answer with a redirect. The redirect points into Django admin,
so the bridge drops it and the console sends staff back to the console page. Messages the view adds
- still show there.
+ still show there. A view that adds an error message before it redirects reported a problem, so the
+ bridge answers 400 and lets the console decide whether the operation still needs doing.
"""
def __init__(self, model: type[Model], view: AdminView) -> None:
@@ -30,7 +44,10 @@ class AdminViewBridge:
def __call__(self, request: HttpRequest, obj: Model, form: forms.Form | None) -> HttpResponse | None:
model_admin = admin.site.get_model_admin(self.model)
+ errors_before = QueuedMessages.error_count(request)
response = self.view(model_admin, request, str(obj.pk))
- if isinstance(response, HttpResponseRedirect):
- return None
- return response
+ if not isinstance(response, HttpResponseRedirect):
+ return response
+ if QueuedMessages.error_count(request) > errors_before:
+ return HttpResponse(status=400)
+ return None
diff --git a/posthog/admin/console/events_retention_tool.py b/posthog/admin/console/events_retention_tool.py
index 57caed195ee4..d549078a6678 100644
--- a/posthog/admin/console/events_retention_tool.py
+++ b/posthog/admin/console/events_retention_tool.py
@@ -83,14 +83,20 @@ class EventsRetentionTool(ConsoleTool):
rows.append(_organization_row(team_list[0]))
rows.extend(_team_row(item, now) for item in team_list)
+ paging = Paging(
+ number=page.number,
+ num_pages=page.paginator.num_pages,
+ summary=f"{page.paginator.count} teams",
+ previous_url=f"?page={page.previous_page_number()}" if page.has_previous() else None,
+ next_url=f"?page={page.next_page_number()}" if page.has_next() else None,
+ )
return Page(
blocks=(
Notice(
text=(
- "Billing months is Team.event_retention_months, which the billing plan sets. It only hides "
- "older events in queries. Deletion retention is the staff setting that the monthly cleanup "
- "enforces. The cleanup deletes one calendar month at a time, and only when every event in "
- "that month is older than the retention."
+ "Billing months come from the team's billing plan. They only hide older events in queries. "
+ "Retention is the staff setting that the monthly cleanup enforces. The cleanup deletes one "
+ "calendar month at a time, and only when every event in that month is older than the retention."
)
),
Table(
@@ -98,12 +104,6 @@ class EventsRetentionTool(ConsoleTool):
rows=tuple(rows),
empty_text="No team has a deletion retention yet. Set one on the organization or team page.",
),
- Paging(
- number=page.number,
- num_pages=page.paginator.num_pages,
- summary=f"{page.paginator.count} teams",
- previous_url=f"?page={page.previous_page_number()}" if page.has_previous() else None,
- next_url=f"?page={page.next_page_number()}" if page.has_next() else None,
- ),
+ *((paging,) if page.paginator.count else ()),
)
)
diff --git a/posthog/admin/console/moved.py b/posthog/admin/console/moved.py
new file mode 100644
index 000000000000..a81dec543d5a
--- /dev/null
+++ b/posthog/admin/console/moved.py
@@ -0,0 +1,37 @@
+from collections.abc import Callable
+
+from django.contrib import messages
+from django.http import HttpRequest, HttpResponse, HttpResponseRedirect
+from django.urls import reverse
+from django.utils.html import format_html
+from django.utils.safestring import SafeString
+
+from posthog.models.team.team import Team
+
+
+class MovedToConsole:
+ """A Django admin notice that points staff to where an action lives in the console now.
+
+ Put it where the old button was, so staff who look in the usual place find the new one.
+ """
+
+ @staticmethod
+ def page_redirect(title: str, url: str) -> Callable[[HttpRequest], HttpResponse]:
+ """A view for the old URL of a page that moved. It says so once, so a bookmark does not move silently."""
+
+ def view(request: HttpRequest) -> HttpResponse:
+ messages.info(request, f"{title} moved to PostHog Admin. Update your bookmark to this page.")
+ query = request.META.get("QUERY_STRING", "")
+ return HttpResponseRedirect(url + (f"?{query}" if query else ""))
+
+ return view
+
+ @staticmethod
+ def team_action(team: Team, panel_key: str, action: str) -> SafeString:
+ url = reverse("admin_console_team", kwargs={"team_id": team.pk})
+ return format_html(
+ '<a href="{}#panel-{}">{}: now in PostHog Admin &#8599;</a>',
+ url,
+ panel_key,
+ action,
+ )
diff --git a/posthog/admin/console/panels.py b/posthog/admin/console/panels.py
index fc1292ac8c5d..53d186decd40 100644
--- a/posthog/admin/console/panels.py
+++ b/posthog/admin/console/panels.py
@@ -2,6 +2,7 @@ from enum import StrEnum
from typing import TYPE_CHECKING, ClassVar, Protocol
from django import forms
+from django.utils.safestring import SafeData
from posthog.dataclasses import frozen
@@ -25,6 +26,10 @@ class Owner:
crest: str
+# A card with more facts than this is a report. Put the detail in a tool and link to it.
+MAX_FACTS_PER_PANEL = 8
+
+
@frozen
class Fact:
label: str
@@ -32,8 +37,15 @@ class Fact:
tone: Tone | None = None
mono: bool = False
+ def __post_init__(self) -> None:
+ # The shell escapes facts. Markup from format_html or mark_safe would bypass the shared design.
+ if isinstance(self.label, SafeData) or isinstance(self.value, SafeData):
+ raise ValueError(f"Fact {self.label!r} must be plain text, not markup")
+
class OperationHandler(Protocol):
+ """Returns None when done. To report a failure, add an error message and return a 4xx or 5xx response."""
+
def __call__(self, request: "HttpRequest", obj: "Model", form: forms.Form | None) -> "HttpResponse | None": ...
@@ -50,11 +62,16 @@ class Operation:
danger: bool = False
form_class: type[forms.Form] | None = None
description: str = ""
+ undo_hint: str = ""
def __post_init__(self) -> None:
# The console writes the reason to the audit log, so nobody runs a destructive action without saying why.
if self.danger and (self.form_class is None or "reason" not in self.form_class.base_fields):
raise ValueError(f"Danger operation {self.key!r} needs a form with a reason field")
+ if self.danger and not self.undo_hint.strip():
+ raise ValueError(
+ f"Danger operation {self.key!r} needs an undo_hint that says how to undo it, or that it cannot be undone"
+ )
class ReasonForm(forms.Form):
diff --git a/posthog/admin/console/registry.py b/posthog/admin/console/registry.py
index c71a5128926b..58407f8fcfcd 100644
--- a/posthog/admin/console/registry.py
+++ b/posthog/admin/console/registry.py
@@ -1,9 +1,21 @@
+import re
+
from django.utils.module_loading import autodiscover_modules
from posthog.admin.console.panels import Panel
from posthog.admin.console.tools import ConsoleTool
RECORD_TYPES = frozenset({"team"})
+# Navigation headings. Add one here, in the shell, only when no existing group fits a new tool.
+TOOL_GROUPS = frozenset({"Data"})
+KEY_PATTERN = re.compile(r"^[a-z0-9]+(?:-[a-z0-9]+)*$")
+
+
+def _check_metadata(kind: str, cls: type, key: str, title: str) -> None:
+ if not KEY_PATTERN.match(key):
+ raise ValueError(f"Console {kind} {cls.__name__} needs a lowercase, dash-separated key, not {key!r}")
+ if not title.strip():
+ raise ValueError(f"Console {kind} {cls.__name__} needs a title")
class ConsoleRegistry:
@@ -13,6 +25,7 @@ class ConsoleRegistry:
self._discovered = False
def register_panel(self, panel_class: type[Panel]) -> type[Panel]:
+ _check_metadata("panel", panel_class, panel_class.key, panel_class.title)
if panel_class.record not in RECORD_TYPES:
raise ValueError(f"Unknown console record type {panel_class.record!r} on {panel_class.__name__}")
panels = self._panels[panel_class.record]
@@ -34,6 +47,11 @@ class ConsoleRegistry:
return panel_class() if panel_class else None
def register_tool(self, tool_class: type[ConsoleTool]) -> type[ConsoleTool]:
+ _check_metadata("tool", tool_class, tool_class.key, tool_class.title)
+ if tool_class.group not in TOOL_GROUPS:
+ raise ValueError(
+ f"Console tool {tool_class.__name__} uses group {tool_class.group!r}, not one of {sorted(TOOL_GROUPS)}"
+ )
existing = self._tools.get(tool_class.key)
if existing is not None and existing is not tool_class:
raise ValueError(f"Console tool key {tool_class.key!r} is already used by {existing.__name__}")
diff --git a/posthog/admin/console/team_panels.py b/posthog/admin/console/team_panels.py
index 6cddf122bc74..43447bf84fff 100644
--- a/posthog/admin/console/team_panels.py
+++ b/posthog/admin/console/team_panels.py
@@ -8,6 +8,7 @@ from posthog.admin.console.bridge import AdminViewBridge
from posthog.admin.console.panels import Fact, Operation, Owner, Panel, ReasonForm, Tone
from posthog.admin.console.registry import console
from posthog.models.activity_logging.activity_log import ActivityLog
+from posthog.models.organization import OrganizationMembership
from posthog.models.team.team import Team
# The console shell owns the core panels until a team claims one.
@@ -23,8 +24,17 @@ class TeamOverviewPanel(Panel):
def facts(self, obj: Model) -> list[Fact]:
assert isinstance(obj, Team)
+ owner = (
+ OrganizationMembership.objects.filter(
+ organization_id=obj.organization_id, level=OrganizationMembership.Level.OWNER
+ )
+ .select_related("user")
+ .order_by("joined_at")
+ .first()
+ )
return [
- Fact(label="Organization", value=obj.organization.name),
+ Fact(label="Owner", value=owner.user.email if owner else "No owner"),
+ Fact(label="Members", value=str(obj.organization.members.count())),
Fact(label="Project", value=str(obj.project_id), mono=True),
Fact(label="Created", value=obj.created_at.strftime("%b %-d, %Y")),
Fact(label="Timezone", value=obj.timezone),
@@ -33,7 +43,6 @@ class TeamOverviewPanel(Panel):
value="Yes" if obj.ingested_event else "Not yet",
tone=Tone.SUCCESS if obj.ingested_event else Tone.WARNING,
),
- Fact(label="API token", value=obj.api_token, mono=True),
]
@@ -45,7 +54,11 @@ class RemoteConfigPanel(Panel):
owner = DEV_EXPERIENCE
def facts(self, obj: Model) -> list[Fact]:
- return [Fact(label="Cache", value="Served from the hypercache, rebuilt on config changes")]
+ return [
+ Fact(
+ label="Cache", value="SDKs read the team's config from this cache. It rebuilds when the config changes."
+ )
+ ]
def operations(self, obj: Model) -> list[Operation]:
return [
@@ -126,6 +139,7 @@ class AIGatewayPanel(Panel):
key="enable",
label="Enable access",
handler=AdminViewBridge(Team, TeamAdmin.enable_ai_gateway_view),
+ description="Lets the team send requests through the AI gateway.",
)
)
if obj.llm_gateway_revoked_at is None:
@@ -137,6 +151,7 @@ class AIGatewayPanel(Panel):
danger=True,
description="Blocks the team's gateway requests until the revoke is cleared.",
form_class=ReasonForm,
+ undo_hint="To undo, use Clear revoke in the AI gateway panel.",
)
)
else:
@@ -145,6 +160,7 @@ class AIGatewayPanel(Panel):
key="clear-revoke",
label="Clear revoke",
handler=AdminViewBridge(Team, TeamAdmin.clear_ai_gateway_revoke_view),
+ description="Lets the team's gateway requests through again.",
)
)
return operations
@@ -171,5 +187,6 @@ class ApiTokenPanel(Panel):
danger=True,
description="SDKs that still send the old token stop reaching this team.",
form_class=SetApiTokenForm,
+ undo_hint="This cannot be undone automatically. To go back, set the old token again.",
)
]
diff --git a/posthog/admin/console/tools.py b/posthog/admin/console/tools.py
index aeaa8ba73fdf..ebd71a454b4a 100644
--- a/posthog/admin/console/tools.py
+++ b/posthog/admin/console/tools.py
@@ -61,6 +61,16 @@ Block = Notice | Table | Paging
class Page:
blocks: tuple[Block, ...]
+ def __post_init__(self) -> None:
+ # tool.html renders only the block kinds it knows, so an unknown block would vanish without an error.
+ for block in self.blocks:
+ if not isinstance(block, Notice | Table | Paging):
+ raise ValueError(f"{type(block).__name__} is not a console block. Add new blocks to the shell.")
+ if isinstance(block, Table):
+ for row in block.rows:
+ if isinstance(row, Row) and len(row.cells) != len(block.columns):
+ raise ValueError(f"A table row has {len(row.cells)} cells for {len(block.columns)} columns")
+
class ConsoleTool:
"""A console page that is not about one record, for example a report across all teams.
diff --git a/posthog/admin/console/urls.py b/posthog/admin/console/urls.py
index 2042e6b76773..b85454142f72 100644
--- a/posthog/admin/console/urls.py
+++ b/posthog/admin/console/urls.py
@@ -1,5 +1,5 @@
from django.contrib import admin
-from django.urls import path
+from django.urls import path, re_path
from posthog.admin.console import views
@@ -22,4 +22,11 @@ urlpatterns = [
admin.site.admin_view(views.tool_page),
name="admin_console_tool",
),
+ # APPEND_SLASH is off, so a console URL typed without its trailing slash would fall through to the
+ # Django admin catch-all.
+ re_path(
+ r"^admin/console(?P<rest>(?:/.*[^/])?)$",
+ admin.site.admin_view(views.append_slash),
+ name="admin_console_append_slash",
+ ),
]
diff --git a/posthog/admin/console/views.py b/posthog/admin/console/views.py
index da14cdf09149..8e61d46ecea1 100644
--- a/posthog/admin/console/views.py
+++ b/posthog/admin/console/views.py
@@ -6,13 +6,14 @@ from django.conf import settings
from django.contrib import messages
from django.contrib.staticfiles import finders
from django.db.models import Q
-from django.http import Http404, HttpRequest, HttpResponse, HttpResponseNotAllowed
+from django.http import Http404, HttpRequest, HttpResponse, HttpResponseNotAllowed, HttpResponseRedirect
from django.shortcuts import get_object_or_404, redirect, render
from django.urls import reverse
import structlog
-from posthog.admin.console.panels import Fact, Operation, Panel
+from posthog.admin.console.bridge import QueuedMessages
+from posthog.admin.console.panels import Fact, Operation, Panel, Tone
from posthog.admin.console.registry import console
from posthog.admin.console.tools import ConsoleTool
from posthog.dataclasses import frozen
@@ -23,6 +24,7 @@ from posthog.models.user import User
logger = structlog.get_logger(__name__)
SEARCH_LIMIT = 25
+RECENT_TEAMS_LIMIT = 8
@frozen
@@ -32,6 +34,17 @@ class RenderedPanel:
operations: list[Operation]
+@frozen
+class AttentionItem:
+ """A warning or destructive fact, lifted to the top of the record page so staff see what is wrong first."""
+
+ panel: Panel
+ fact: Fact
+
+
+ATTENTION_TONES = (Tone.WARNING, Tone.DESTRUCTIVE)
+
+
class ConsoleAssets:
"""A version for the console's CSS and JS URLs.
@@ -75,6 +88,25 @@ class ConsoleEnvironment:
}
+class RecentTeams:
+ """The teams this staff member opened last, kept in the session, so the home page has somewhere to start."""
+
+ SESSION_KEY = "admin_console_recent_teams"
+
+ @classmethod
+ def remember(cls, request: HttpRequest, team: Team) -> None:
+ recent = [team_id for team_id in request.session.get(cls.SESSION_KEY, []) if team_id != team.pk]
+ request.session[cls.SESSION_KEY] = [team.pk, *recent][:RECENT_TEAMS_LIMIT]
+
+ @classmethod
+ def load(cls, request: HttpRequest) -> list[Team]:
+ team_ids: list[int] = request.session.get(cls.SESSION_KEY, [])
+ if not team_ids:
+ return []
+ teams = Team.objects.select_related("organization").in_bulk(team_ids)
+ return [teams[team_id] for team_id in team_ids if team_id in teams]
+
+
def _search_teams(query: str) -> list[Team]:
if not query:
return []
@@ -92,17 +124,27 @@ def _search_teams(query: str) -> list[Team]:
def console_home(request: HttpRequest) -> HttpResponse:
query = request.GET.get("q", "").strip()
teams = _search_teams(query)
- if query.isdigit() and len(teams) == 1:
+ if len(teams) == 1:
+ if not query.isdigit():
+ messages.info(request, f'Opened the only team that matches "{query}".')
return redirect("admin_console_team", team_id=teams[0].pk)
return render(
request,
"admin_console/home.html",
- {**ConsoleEnvironment.context(), "query": query, "teams": teams},
+ {
+ **ConsoleEnvironment.context(),
+ "query": query,
+ "teams": teams,
+ "recent_teams": [] if query else RecentTeams.load(request),
+ "tools": console.tools(),
+ "team_panels": console.panels_for("team"),
+ },
)
def team_detail(request: HttpRequest, team_id: int) -> HttpResponse:
team = get_object_or_404(Team.objects.select_related("organization"), pk=team_id)
+ RecentTeams.remember(request, team)
panels = [
RenderedPanel(panel=panel, facts=panel.facts(team), operations=panel.operations(team))
for panel in console.panels_for("team")
@@ -113,12 +155,22 @@ def team_detail(request: HttpRequest, team_id: int) -> HttpResponse:
{
**ConsoleEnvironment.context(),
"team": team,
+ "attention": [
+ AttentionItem(panel=rendered.panel, fact=fact)
+ for rendered in panels
+ for fact in rendered.facts
+ if fact.tone in ATTENTION_TONES
+ ],
"regular_panels": [rendered for rendered in panels if not rendered.panel.danger],
"danger_panels": [rendered for rendered in panels if rendered.panel.danger],
},
)
+def _is_offered(panel: Panel, team: Team, operation_key: str) -> bool:
+ return any(operation.key == operation_key for operation in panel.operations(team))
+
+
def _find_operation(panel: Panel, team: Team, operation_key: str) -> Operation:
# Look the operation up in what the panel offers now, so a stale form cannot run an operation the
# current state no longer allows, for example suspending a team that is already suspended.
@@ -172,7 +224,17 @@ def run_team_operation(request: HttpRequest, team_id: int, panel_key: str, opera
if response is None:
return redirect(team_url)
if response.status_code >= 400:
- messages.error(request, f"{operation.label} failed with status {response.status_code}.")
+ team.refresh_from_db()
+ # A handler can fail after its state change committed, for example when a notification fails.
+ # The operation is then no longer offered, and staff belong on the team page, not on a dead form.
+ if form is not None and _is_offered(panel, team, operation.key):
+ return render(request, "admin_console/operation.html", context, status=400)
+ if QueuedMessages.error_count(request) == 0:
+ messages.error(
+ request,
+ f"{operation.label} failed with status {response.status_code}. The page below shows the current "
+ f"state. Try again, or ask the {panel.owner.name} team if it keeps failing.",
+ )
return redirect(team_url)
return response
@@ -187,3 +249,8 @@ def tool_page(request: HttpRequest, tool_key: str) -> HttpResponse:
"admin_console/tool.html",
{**ConsoleEnvironment.context(), "tool": tool, "page": page},
)
+
+
+def append_slash(request: HttpRequest, rest: str) -> HttpResponse:
+ query = request.META.get("QUERY_STRING", "")
+ return HttpResponseRedirect(f"/admin/console{rest}/" + (f"?{query}" if query else ""))
diff --git a/posthog/admin/test_admin_console.py b/posthog/admin/test_admin_console.py
index e1f284cec1f3..ac67f2d2ca38 100644
--- a/posthog/admin/test_admin_console.py
+++ b/posthog/admin/test_admin_console.py
@@ -1,4 +1,5 @@
import re
+from collections.abc import Callable
from pathlib import Path
import time_machine
@@ -7,12 +8,14 @@ from unittest.mock import MagicMock, patch
from django.conf import settings
from django.test import Client, SimpleTestCase
+from django.utils.html import format_html
from parameterized import parameterized
-from posthog.admin.console.panels import Operation, Owner, Panel
+from posthog.admin.console.panels import MAX_FACTS_PER_PANEL, Fact, Operation, Owner, Panel, ReasonForm
from posthog.admin.console.registry import ConsoleRegistry, console
-from posthog.llm.gateway_internal_client import CreditResult
+from posthog.admin.console.tools import Cell, ConsoleTool, Page, Row, Table
+from posthog.llm.gateway_internal_client import AIGatewayInternalError, CreditResult
from posthog.models.events_retention_config import OrganizationEventsRetentionConfig
from products.workflows.backend.facade.api import get_email_sending_state
@@ -39,6 +42,19 @@ class _DuplicatePanel(Panel):
owner = Owner(name="Dev experience", crest="dev-experience")
+class _Tool(ConsoleTool):
+ key = "some-report"
+ title = "Some report"
+ owner = Owner(name="Dev experience", crest="dev-experience")
+ group = "Data"
+
+
+def _register_twice() -> None:
+ registry = ConsoleRegistry()
+ registry.register_panel(type("FirstPanel", (_DuplicatePanel,), {}))
+ registry.register_panel(type("SecondPanel", (_DuplicatePanel,), {}))
+
+
class TestAdminConsoleAssets(SimpleTestCase):
def test_every_class_in_the_templates_is_in_the_compiled_stylesheet(self) -> None:
css = (CONSOLE_ASSETS / "console.css").read_text()
@@ -71,16 +87,54 @@ class TestAdminConsoleAssets(SimpleTestCase):
f"Console owners name crests the console does not ship: {missing}. Rebuild with `{REBUILD}`."
)
- def test_registering_a_second_panel_with_a_taken_key_fails(self) -> None:
- registry = ConsoleRegistry()
- registry.register_panel(type("FirstPanel", (_DuplicatePanel,), {}))
-
- with self.assertRaisesRegex(ValueError, "already used"):
- registry.register_panel(type("SecondPanel", (_DuplicatePanel,), {}))
-
- def test_a_danger_operation_without_a_reason_field_is_refused(self) -> None:
- with self.assertRaisesRegex(ValueError, "reason"):
- Operation(key="wipe", label="Wipe", handler=lambda request, obj, form: None, danger=True)
+ @parameterized.expand(
+ [
+ ("duplicate_panel_key", _register_twice, "already used"),
+ (
+ "panel_key_not_a_slug",
+ lambda: ConsoleRegistry().register_panel(type("P", (_DuplicatePanel,), {"key": "Over view"})),
+ "dash-separated key",
+ ),
+ (
+ "blank_panel_title",
+ lambda: ConsoleRegistry().register_panel(type("P", (_DuplicatePanel,), {"title": " "})),
+ "needs a title",
+ ),
+ (
+ "tool_group_outside_the_navigation",
+ lambda: ConsoleRegistry().register_tool(type("T", (_Tool,), {"group": "Misc"})),
+ "not one of",
+ ),
+ (
+ "danger_operation_without_reason",
+ lambda: Operation(key="wipe", label="Wipe", handler=lambda request, obj, form: None, danger=True),
+ "reason",
+ ),
+ (
+ "danger_operation_without_undo_hint",
+ lambda: Operation(
+ key="wipe",
+ label="Wipe",
+ handler=lambda request, obj, form: None,
+ danger=True,
+ form_class=ReasonForm,
+ ),
+ "undo_hint",
+ ),
+ ("fact_with_markup", lambda: Fact(label="Plan", value=format_html("<b>{}</b>", "Scale")), "plain text"),
+ ("unknown_tool_block", lambda: Page(blocks=(Fact(label="a", value="b"),)), "not a console block"), # type: ignore[arg-type]
+ (
+ "table_row_missing_a_cell",
+ lambda: Page(blocks=(Table(columns=("Team", "Months"), rows=(Row(cells=(Cell(text="a"),)),)),)),
+ "1 cells for 2 columns",
+ ),
+ ]
+ )
+ def test_the_console_contract_refuses_a_contribution_that_would_render_wrong(
+ self, _name: str, contribute: Callable[[], object], message: str
+ ) -> None:
+ with self.assertRaisesRegex(ValueError, message):
+ contribute()
class TestAdminConsoleViews(BaseTest):
@@ -116,12 +170,54 @@ class TestAdminConsoleViews(BaseTest):
content = response.content.decode()
for title in ("Overview", "Remote config cache", "Email sending", "AI gateway", "Project API token"):
assert title in content
+ assert "Needs attention" in content and "Ingested events:" in content
+ for panel in console.panels_for("team"):
+ assert len(panel.facts(self.team)) <= MAX_FACTS_PER_PANEL, f"{panel.key} shows too many facts"
+
+ home = self.client.get("/admin/console/").content.decode()
+ assert "Recently opened" in home
+ assert f"/admin/console/teams/{self.team.pk}/" in home
+
+ @parameterized.expand(
+ [
+ ("home", "/admin/console", "/admin/console/"),
+ ("team_with_query", "/admin/console/teams/7?tab=1", "/admin/console/teams/7/?tab=1"),
+ ]
+ )
+ def test_a_console_url_without_its_trailing_slash_redirects(self, _name: str, path: str, expected: str) -> None:
+ response = self.client.get(path)
+
+ assert response.status_code == 302
+ assert response["Location"] == expected
+
+ def test_a_name_with_one_match_opens_the_team(self) -> None:
+ response = self.client.get("/admin/console/", {"q": self.team.name})
+
+ assert response.status_code == 302
+ assert response["Location"] == f"/admin/console/teams/{self.team.pk}/"
+
+ def test_django_admin_team_page_points_moved_actions_to_the_console(self) -> None:
+ response = self.client.get(f"/admin/posthog/team/{self.team.pk}/change/")
+
+ assert response.status_code == 200
+ content = response.content.decode()
+ assert "team actions moved to PostHog Admin" in content
+ for panel_key in ("remote-config", "email-sending", "ai-gateway", "api-token"):
+ assert f"/admin/console/teams/{self.team.pk}/#panel-{panel_key}" in content
@parameterized.expand(
[
- ("suspend_with_reason", "suspend", {"reason": "Bounce rate above 10%"}, 302, True),
- ("suspend_without_reason", "suspend", {"reason": " "}, 400, False),
- ("operation_not_offered_in_this_state", "unsuspend", {}, 404, False),
+ ("suspend_with_reason", "suspend", {"reason": "Bounce rate above 10%"}, False, 302, True),
+ ("suspend_without_reason", "suspend", {"reason": " "}, False, 400, False),
+ (
+ "notification_fails_after_the_suspension",
+ "suspend",
+ {"reason": "Bounce rate above 10%"},
+ True,
+ 302,
+ True,
+ ),
+ ("operation_not_offered_in_this_state", "unsuspend", {}, False, 404, False),
]
)
@patch("posthog.admin.admins.team_admin.create_notification")
@@ -131,11 +227,15 @@ class TestAdminConsoleViews(BaseTest):
_name: str,
operation_key: str,
data: dict[str, str],
+ notification_fails: bool,
expected_status: int,
expect_suspended: bool,
- _send_email: object,
+ send_email: MagicMock,
_create_notification: object,
) -> None:
+ if notification_fails:
+ send_email.delay.side_effect = RuntimeError("broker down")
+
response = self.client.post(f"/admin/console/teams/{self.team.pk}/email-sending/{operation_key}/", data)
assert response.status_code == expected_status
@@ -163,6 +263,18 @@ class TestAdminConsoleViews(BaseTest):
assert add_credit.call_count == 2
assert len(keys) == 1
+ @patch("posthog.admin.admins.team_admin.add_credit", side_effect=AIGatewayInternalError("gateway down"))
+ def test_a_failed_operation_shows_the_form_again_with_what_staff_typed(self, _add_credit: MagicMock) -> None:
+ response = self.client.post(
+ f"/admin/console/teams/{self.team.pk}/ai-gateway/add-credit/",
+ {"amount_usd": "25", "reason": "Outage goodwill"},
+ )
+
+ assert response.status_code == 400
+ content = response.content.decode()
+ assert "gateway down" in content
+ assert "Outage goodwill" in content
+
@time_machine.travel("2026-10-20T12:00:00Z", tick=False)
def test_events_retention_tool_lists_the_teams_of_an_organization_with_a_default(self) -> None:
empty = self.client.get("/admin/console/tools/events-retention/")
@@ -176,6 +288,7 @@ class TestAdminConsoleViews(BaseTest):
assert response.redirect_chain == [("/admin/console/tools/events-retention/", 302)]
content = response.content.decode()
+ assert "Events retention moved to PostHog Admin" in content
assert f"/admin/console/teams/{self.team.pk}/" in content
assert "Organization default" in content
assert "September 2025" in content
diff --git a/posthog/templates/admin/base_site.html b/posthog/templates/admin/base_site.html
index 96ab84d414cd..4c06a368a7ef 100644
--- a/posthog/templates/admin/base_site.html
+++ b/posthog/templates/admin/base_site.html
@@ -37,6 +37,31 @@
// which leaves the operator on a page they cannot submit until they reload. A restore means
// the POST is done with. Only a control the handler above marked is released, so a control
// the template disabled on purpose stays disabled.
+ var BANNER_KEY = "console-banner-hidden-until";
+ document.addEventListener("DOMContentLoaded", function () {
+ var banner = document.querySelector(".console-banner");
+ if (!banner) {
+ return;
+ }
+ try {
+ if (Number(window.localStorage.getItem(BANNER_KEY)) > Date.now()) {
+ banner.hidden = true;
+ }
+ } catch (error) {
+ // Storage can be blocked. The banner then stays visible.
+ }
+ });
+ document.addEventListener("click", function (event) {
+ if (!event.target.closest("[data-hide-console-banner]")) {
+ return;
+ }
+ document.querySelector(".console-banner").hidden = true;
+ try {
+ window.localStorage.setItem(BANNER_KEY, String(Date.now() + 30 * 24 * 60 * 60 * 1000));
+ } catch (error) {
+ }
+ });
+
window.addEventListener("pageshow", function (event) {
if (!event.persisted) {
return;
@@ -50,6 +75,24 @@
{% endblock %}
{% block extrastyle %}
{{ block.super }}
+ <style>
+ .console-banner {
+ display: flex;
+ align-items: center;
+ gap: 14px;
+ padding: 8px 16px;
+ background: #fff4ec;
+ border-bottom: 2px solid #ff5c1c;
+ color: #3b2a1f;
+ font-size: 13px;
+ line-height: 1.4;
+ }
+ .console-banner img { width: 44px; height: auto; flex-shrink: 0; }
+ .console-banner p { margin: 0; padding: 0; }
+ .console-banner a.button { margin-left: auto; white-space: nowrap; }
+ .console-banner-hide { background: none; border: 0; color: inherit; text-decoration: underline; cursor: pointer; white-space: nowrap; }
+ .console-banner[hidden] { display: none; }
+ </style>
{% if is_impersonated_session %}
<style>
.impersonation-banner {
@@ -82,5 +125,17 @@
<a class="impersonation-stop" href="/admin/logout/">Stop impersonating</a>
</div>
{% endif %}
+ {% if user.is_staff %}
+ <div class="console-banner">
+ <img src="/static/admin-console/hoggies/desk-wizard.png" alt="" />
+ <p>
+ <strong>Psst, team actions moved to PostHog Admin,</strong> where the buttons say what they do.
+ This Django admin keeps the raw tables.
+ </p>
+ <a class="button"
+ href="{% block admin_console_url %}/admin/console/{% endblock %}">Open PostHog Admin &rarr;</a>
+ <button type="button" class="console-banner-hide" data-hide-console-banner>Hide for a month</button>
+ </div>
+ {% endif %}
{{ block.super }}
{% endblock %}
diff --git a/posthog/templates/admin/posthog/team/ai_gateway_actions.html b/posthog/templates/admin/posthog/team/ai_gateway_actions.html
deleted file mode 100644
index bb272931baf3..000000000000
--- a/posthog/templates/admin/posthog/team/ai_gateway_actions.html
+++ /dev/null
@@ -1,30 +0,0 @@
-<div style="margin: 10px 0;">
- <button type="submit"
- name="_enable_ai_gateway"
- class="button"
- formmethod="post"
- formaction="{{ enable_url }}"
- formnovalidate
- {% if is_enabled %}disabled title="Already enabled"{% else %}data-confirm="Enable AI gateway access for {{ team_name }}?"{% endif %}
- style="margin-right: 8px">Enable access</button>
- <button type="submit"
- name="_revoke_ai_gateway"
- class="button"
- formmethod="post"
- formaction="{{ revoke_url }}"
- formnovalidate
- {% if is_revoked %}disabled title="Already revoked"{% else %}data-confirm="Revoke AI gateway access for {{ team_name }}?"{% endif %}
- style="margin-right: 8px">Revoke access</button>
- <button type="submit"
- name="_clear_ai_gateway_revoke"
- class="button"
- formmethod="post"
- formaction="{{ clear_revoke_url }}"
- formnovalidate
- {% if not is_revoked %}disabled title="Not revoked"{% else %}data-confirm="Clear AI gateway revoke for {{ team_name }}?"{% endif %}>
- Clear revoke
- </button>
- <p style="margin-top: 8px; color: #666; font-size: 12px;">
- Sets <code>llm_gateway_enabled_at</code> / <code>llm_gateway_revoked_at</code> to now (or null). Per-region.
- </p>
-</div>
diff --git a/posthog/templates/admin/posthog/team/ai_gateway_wallet_actions.html b/posthog/templates/admin/posthog/team/ai_gateway_wallet_actions.html
index 2fa5321bb6ec..03cd28a28bdd 100644
--- a/posthog/templates/admin/posthog/team/ai_gateway_wallet_actions.html
+++ b/posthog/templates/admin/posthog/team/ai_gateway_wallet_actions.html
@@ -3,5 +3,5 @@
href="{{ wallet_url }}"
target="_blank"
style="margin-right: 10px">View wallet (balance + recent ledger)</a>
- <a class="button" href="{{ add_credit_url }}">Add credit</a>
+ {{ add_credit_moved }}
</div>
diff --git a/posthog/templates/admin/posthog/team/change_form.html b/posthog/templates/admin/posthog/team/change_form.html
index 71d9e8f0aabe..7d5ec11bf5b2 100644
--- a/posthog/templates/admin/posthog/team/change_form.html
+++ b/posthog/templates/admin/posthog/team/change_form.html
@@ -5,3 +5,10 @@
{# Team admin includes inline formsets (GroupTypeMapping, TeamMarketingAnalyticsConfig) #}
{# which require this template override for CSP compliance #}
{% endblock %}
+{% block admin_console_url %}
+ {% if original.pk %}
+ {% url 'admin_console_team' team_id=original.pk %}
+ {% else %}
+ {{ block.super }}
+ {% endif %}
+{% endblock %}
diff --git a/posthog/templates/admin/posthog/team/email_sending_suspension_actions.html b/posthog/templates/admin/posthog/team/email_sending_suspension_actions.html
deleted file mode 100644
index 30a3f0301946..000000000000
--- a/posthog/templates/admin/posthog/team/email_sending_suspension_actions.html
+++ /dev/null
@@ -1,18 +0,0 @@
-<div style="margin: 10px 0;">
- {% if is_suspended %}
- <button type="submit"
- name="_unsuspend_email_sending"
- class="button"
- formmethod="post"
- formaction="{{ unsuspend_url }}"
- formnovalidate
- data-confirm="Re-enable workflow email sending for {{ team_name }}? The team will be notified.">
- Re-enable email sending
- </button>
- {% else %}
- <a class="button" href="{{ suspend_url }}">Suspend email sending…</a>
- {% endif %}
- <p style="margin-top: 8px; color: #666; font-size: 12px;">
- Sets <code>email_sending_suspended_at</code> on the team's workflows config. Suspending asks for a reason and notifies the team.
- </p>
-</div>
diff --git a/posthog/templates/admin/posthog/team/remote_config_cache_actions.html b/posthog/templates/admin/posthog/team/remote_config_cache_actions.html
index 9c75054ce70c..c508627df6ba 100644
--- a/posthog/templates/admin/posthog/team/remote_config_cache_actions.html
+++ b/posthog/templates/admin/posthog/team/remote_config_cache_actions.html
@@ -3,13 +3,7 @@
href="{{ view_url }}"
target="_blank"
style="margin-right: 10px">View cached config JSON</a>
- <button type="submit"
- name="_rebuild_cache"
- class="button"
- formmethod="post"
- formaction="{{ rebuild_url }}"
- formnovalidate
- data-confirm="Rebuild cache for team {{ team_name }}?">Rebuild cache</button>
+ {{ rebuild_moved }}
<p style="margin-top: 8px; color: #666; font-size: 12px;">
Cache key: <code>{{ cache_key }}</code>
</p>
diff --git a/posthog/templates/admin_console/_badge.html b/posthog/templates/admin_console/_badge.html
index 0549a2d11849..21f4210deaff 100644
--- a/posthog/templates/admin_console/_badge.html
+++ b/posthog/templates/admin_console/_badge.html
@@ -1,2 +1,2 @@
{# A quill Badge. Every tone class is written out in full, so the Tailwind build sees it. #}
-<span class="quill-badge {% if tone == 'success' %}quill-badge--variant-success{% elif tone == 'warning' %}quill-badge--variant-warning{% elif tone == 'destructive' %}quill-badge--variant-destructive{% elif tone == 'info' %}quill-badge--variant-info{% else %}quill-badge--variant-default{% endif %}{% if mono %} font-mono{% endif %}">{{ label }}</span>
+<span class="quill-badge inline-flex w-fit shrink-0 items-center justify-center gap-1 overflow-hidden whitespace-nowrap {% if tone == 'success' %}quill-badge--variant-success{% elif tone == 'warning' %}quill-badge--variant-warning{% elif tone == 'destructive' %}quill-badge--variant-destructive{% elif tone == 'info' %}quill-badge--variant-info{% else %}quill-badge--variant-default{% endif %}{% if mono %} font-mono{% endif %}">{{ label }}</span>
diff --git a/posthog/templates/admin_console/_panel.html b/posthog/templates/admin_console/_panel.html
index bdca142ea2dd..f8a4a3603c4c 100644
--- a/posthog/templates/admin_console/_panel.html
+++ b/posthog/templates/admin_console/_panel.html
@@ -1,67 +1,72 @@
{# One registered Panel as a quill Card. `rendered` is a RenderedPanel from posthog/admin/console/views.py. #}
-<section class="quill-card group/card flex flex-col{% if rendered.panel.danger %} console-danger{% endif %}"
+<section class="quill-card group/card flex flex-col scroll-mt-4{% if rendered.panel.danger %} console-danger{% endif %}"
+ id="panel-{{ rendered.panel.key }}"
data-quill
data-slot="card"
data-size="default">
<div class="quill-card__header group/card-header" data-slot="card-header">
- <div class="quill-card__title{% if rendered.panel.danger %} text-destructive-foreground{% endif %}"
- data-slot="card-title">{{ rendered.panel.title }}</div>
+ <h2 class="quill-card__title m-0 flex items-center gap-2"
+ data-slot="card-title">
+ {{ rendered.panel.title }}
+ {% if rendered.panel.danger %}
+ <span class="text-[13px] font-normal">
+ {% include "admin_console/_badge.html" with label="Risky" tone="destructive" %}
+ </span>
+ {% endif %}
+ </h2>
<div class="quill-card__action flex items-center gap-1.5 text-[11px] text-muted-foreground"
data-slot="card-action"
title="Owned by {{ rendered.panel.owner.name }}">
{{ rendered.panel.owner.name }}
- <img class="size-[22px]"
+ <img class="size-[18px]"
src="/static/admin-console/crests/{{ rendered.panel.owner.crest }}.svg"
alt="" />
</div>
</div>
- <div class="quill-card__content{% if rendered.panel.danger %} grid grid-cols-[96px_1fr] gap-4{% endif %}"
+ <div class="quill-card__content flex flex-col gap-4"
data-slot="card-content">
- {% if rendered.panel.danger %}
- <img class="w-24"
- src="/static/admin-console/hoggies/traffic-police.png"
- alt="" />
+ {% if rendered.facts %}
+ <dl class="grid grid-cols-[max-content_1fr] gap-x-4 gap-y-1.5 m-0">
+ {% for fact in rendered.facts %}
+ <dt class="text-muted-foreground">{{ fact.label }}</dt>
+ <dd class="m-0 min-w-0 break-words">
+ {% if fact.tone %}
+ {% include "admin_console/_badge.html" with label=fact.value tone=fact.tone mono=fact.mono %}
+ {% elif fact.mono %}
+ <span class="font-mono text-xs">{{ fact.value }}</span>
+ {% else %}
+ {{ fact.value }}
+ {% endif %}
+ </dd>
+ {% endfor %}
+ </dl>
{% endif %}
- <div class="flex flex-col gap-3 min-w-0">
- {% if rendered.facts %}
- <dl class="grid grid-cols-[max-content_1fr] gap-x-4 gap-y-1.5 m-0">
- {% for fact in rendered.facts %}
- <dt class="text-muted-foreground">{{ fact.label }}</dt>
- <dd class="m-0 min-w-0 break-words">
- {% if fact.tone %}
- {% include "admin_console/_badge.html" with label=fact.value tone=fact.tone mono=fact.mono %}
- {% elif fact.mono %}
- <span class="font-mono text-xs">{{ fact.value }}</span>
- {% else %}
- {{ fact.value }}
+ {% if rendered.operations %}
+ <ul class="m-0 p-0 list-none grid grid-cols-[max-content_1fr] items-center gap-x-3 gap-y-2 pt-3 border-t border-border">
+ {% for operation in rendered.operations %}
+ <li class="grid grid-cols-subgrid col-span-2 items-center">
+ {% if operation.form_class %}
+ <a href="{% url 'admin_console_team_operation' team_id=team.pk panel_key=rendered.panel.key operation_key=operation.key %}"
+ class="quill-button {% if operation.danger %}quill-button--variant-destructive-outline{% else %}quill-button--variant-outline{% endif %} quill-button--size-sm group/button inline-flex shrink-0 items-center justify-center whitespace-nowrap">{{ operation.label }}</a>
+ {% else %}
+ <form method="post"
+ action="{% url 'admin_console_team_operation' team_id=team.pk panel_key=rendered.panel.key operation_key=operation.key %}">
+ {% csrf_token %}
+ <button type="submit"
+ class="quill-button quill-button--variant-outline quill-button--size-sm group/button inline-flex shrink-0 items-center justify-center whitespace-nowrap">
+ {{ operation.label }}
+ </button>
+ </form>
+ {% endif %}
+ <span class="text-xs text-muted-foreground">
+ {% if operation.danger %}
+ {% include "admin_console/_badge.html" with label="Risky" tone="destructive" %}
{% endif %}
- </dd>
- {% endfor %}
- </dl>
- {% endif %}
- {% for operation in rendered.operations %}
- {% if operation.description %}
- <p class="m-0 text-xs text-muted-foreground">{{ operation.label }}: {{ operation.description }}</p>
- {% endif %}
- {% endfor %}
- </div>
+ {{ operation.description }}
+ </span>
+ </li>
+ {% endfor %}
+ </ul>
+ {% endif %}
</div>
- {% if rendered.operations %}
- <div class="quill-card__footer flex flex-wrap gap-2"
- data-slot="card-footer">
- {% for operation in rendered.operations %}
- {% if operation.form_class %}
- <a href="{% url 'admin_console_team_operation' team_id=team.pk panel_key=rendered.panel.key operation_key=operation.key %}"
- class="quill-button {% if operation.danger %}quill-button--variant-destructive-outline{% else %}quill-button--variant-outline{% endif %} quill-button--size-sm group/button inline-flex shrink-0 items-center justify-center whitespace-nowrap">{{ operation.label }}…</a>
- {% else %}
- <form method="post"
- action="{% url 'admin_console_team_operation' team_id=team.pk panel_key=rendered.panel.key operation_key=operation.key %}">
- {% csrf_token %}
- <button type="submit"
- class="quill-button {% if operation.danger %}quill-button--variant-destructive-outline{% else %}quill-button--variant-outline{% endif %} quill-button--size-sm group/button inline-flex shrink-0 items-center justify-center whitespace-nowrap">{{ operation.label }}</button>
- </form>
- {% endif %}
- {% endfor %}
- </div>
- {% endif %}
</section>
diff --git a/posthog/templates/admin_console/_team_list.html b/posthog/templates/admin_console/_team_list.html
new file mode 100644
index 000000000000..d2f77946f6d0
--- /dev/null
+++ b/posthog/templates/admin_console/_team_list.html
@@ -0,0 +1,19 @@
+<table class="w-full border-collapse">
+ <thead>
+ <tr class="text-left text-xs text-muted-foreground border-b border-border">
+ <th class="py-1.5 font-bold">Team</th>
+ <th class="py-1.5 font-bold">Organization</th>
+ <th class="py-1.5 font-bold">ID</th>
+ </tr>
+ </thead>
+ <tbody>
+ {% for team in teams %}
+ <tr class="border-b border-border last:border-b-0">
+ <td class="py-1.5"><a class="font-semibold text-foreground underline decoration-border underline-offset-2 hover:decoration-current"
+ href="{% url 'admin_console_team' team_id=team.pk %}">{{ team.name }}</a></td>
+ <td class="py-1.5">{{ team.organization.name }}</td>
+ <td class="py-1.5 font-mono text-xs">{{ team.pk }}</td>
+ </tr>
+ {% endfor %}
+ </tbody>
+</table>
diff --git a/posthog/templates/admin_console/base.html b/posthog/templates/admin_console/base.html
index 89656fb85020..34134f11a877 100644
--- a/posthog/templates/admin_console/base.html
+++ b/posthog/templates/admin_console/base.html
@@ -12,6 +12,8 @@
defer></script>
</head>
<body class="console-body m-0 min-h-screen bg-background text-foreground text-[13px]">
+ <a class="sr-only focus:not-sr-only focus:absolute focus:top-2 focus:left-2 focus:z-10 focus:px-3 focus:py-2 focus:rounded focus:bg-background"
+ href="#content">Skip to content</a>
<div class="console-env-stripe h-1"></div>
<header class="flex flex-wrap items-center gap-4 min-h-12 px-4 py-2 bg-chrome border-b border-border">
<a href="{% url 'admin_console_home' %}"
@@ -21,38 +23,49 @@
<span class="console-env-pill inline-flex items-center gap-1.5 px-2 py-0.5 rounded-full text-[11px] font-bold uppercase tracking-wide whitespace-nowrap">
<span class="console-env-dot size-[7px] rounded-full"></span>{{ console_env_label }}
</span>
- <form method="get"
- action="{% url 'admin_console_home' %}"
- class="flex-1 min-w-[240px] max-w-[520px]">
- <input class="quill-input"
- type="search"
- name="q"
- value="{{ query|default:'' }}"
- placeholder="Find a team by ID, API token, team or organization name"
- aria-label="Search teams" />
- </form>
- <div class="ml-auto flex items-center gap-3 text-muted-foreground whitespace-nowrap">
- <span>{{ request.user.email }}</span>
- <a class="quill-button quill-button--variant-outline quill-button--size-sm group/button inline-flex shrink-0 items-center justify-center whitespace-nowrap"
- href="/admin/">Django admin</a>
- </div>
+ {% block header_search %}
+ <form method="get"
+ action="{% url 'admin_console_home' %}"
+ class="flex-1 min-w-[240px] max-w-[520px]">
+ <input class="quill-input"
+ id="team-search"
+ type="search"
+ name="q"
+ placeholder="Look up a team by ID, API token or name"
+ aria-label="Look up a team"
+ aria-keyshortcuts="/" />
+ </form>
+ {% endblock %}
+ <div class="ml-auto text-muted-foreground whitespace-nowrap">{{ request.user.email }}</div>
</header>
<div class="@container">
<div class="grid min-h-[calc(100vh-3.25rem)] @3xl:grid-cols-[200px_1fr]">
<nav class="flex flex-col gap-0.5 p-2 bg-chrome border-b @3xl:border-b-0 @3xl:border-r border-border"
aria-label="Console">
- <p class="mt-2 mb-1 mx-2 text-[11px] font-bold uppercase tracking-wide text-muted-foreground">Records</p>
- <a class="quill-button quill-button--variant-default quill-button--size-row justify-start group/button inline-flex shrink-0 items-center whitespace-nowrap"
- href="{% url 'admin_console_home' %}">Teams</a>
- {% for group, tools in console_tool_groups.items %}
- <p class="mt-3 mb-1 mx-2 text-[11px] font-bold uppercase tracking-wide text-muted-foreground">{{ group }}</p>
- {% for nav_tool in tools %}
- <a class="quill-button quill-button--variant-default quill-button--size-row justify-start group/button inline-flex shrink-0 items-center whitespace-nowrap"
- href="{% url 'admin_console_tool' tool_key=nav_tool.key %}">{{ nav_tool.title }}</a>
+ {% url 'admin_console_home' as home_url %}
+ <p class="mt-2 mb-1 mx-2 text-[11px] font-bold uppercase tracking-wide text-muted-foreground">Teams</p>
+ <a class="quill-button quill-button--variant-default quill-button--size-row justify-start group/button inline-flex shrink-0 items-center whitespace-nowrap aria-[current=page]:bg-[var(--fill-selected)] aria-[current=page]:font-bold"
+ href="{{ home_url }}"
+ {% if request.path == home_url %}aria-current="page"{% endif %}>Look up a team</a>
+ {% if console_tool_groups %}
+ <p class="mt-4 mb-1 mx-2 text-[11px] font-bold uppercase tracking-wide text-muted-foreground">Tools</p>
+ {% for group, tools in console_tool_groups.items %}
+ <p class="mt-1 mb-0.5 mx-2 text-[11px] text-muted-foreground">{{ group }}</p>
+ {% for nav_tool in tools %}
+ {% url 'admin_console_tool' tool_key=nav_tool.key as tool_url %}
+ <a class="quill-button quill-button--variant-default quill-button--size-row justify-start group/button inline-flex shrink-0 items-center whitespace-nowrap aria-[current=page]:bg-[var(--fill-selected)] aria-[current=page]:font-bold"
+ href="{{ tool_url }}"
+ {% if request.path == tool_url %}aria-current="page"{% endif %}>{{ nav_tool.title }}</a>
+ {% endfor %}
{% endfor %}
- {% endfor %}
+ {% endif %}
+ <div class="mt-auto mx-2 mb-2 pt-4 flex flex-col gap-1 text-xs text-muted-foreground">
+ <p class="m-0">Need a raw database table? Django admin still has every model.</p>
+ <a class="quill-button quill-button--variant-link-muted quill-button--size-sm justify-start px-0 group/button inline-flex shrink-0 items-center whitespace-nowrap"
+ href="/admin/">Leave for Django admin &rarr;</a>
+ </div>
</nav>
- <main class="min-w-0 px-6 pt-5 pb-20 @container">
+ <main id="content" class="min-w-0 px-6 pt-5 pb-20 @container">
{% if messages %}
<div class="flex flex-col gap-2 mb-4">
{% for message in messages %}
diff --git a/posthog/templates/admin_console/home.html b/posthog/templates/admin_console/home.html
index fe99a81b00ae..154c94b115d5 100644
--- a/posthog/templates/admin_console/home.html
+++ b/posthog/templates/admin_console/home.html
@@ -1,55 +1,145 @@
{% extends "admin_console/base.html" %}
+{% block header_search %}{% endblock %}
{% block content %}
- <h1 class="m-0 mb-4 text-[22px] font-extrabold">Find a team</h1>
- {% if not query %}
- <div class="quill-empty flex w-full min-w-0 flex-col items-center justify-center gap-4 py-10"
- data-slot="empty">
- <div class="quill-empty__media quill-empty__media--variant-default flex shrink-0 items-center justify-center">
- <img class="w-28"
- src="/static/admin-console/hoggies/desk-wizard.png"
- alt="" />
- </div>
- <div class="quill-empty__content flex flex-col items-center gap-1">
- <div class="quill-empty__title" data-slot="empty-title">Search for a team to get started</div>
- <div class="quill-empty__description" data-slot="empty-description">Use the search box above. A team ID opens the team right away.</div>
- </div>
- </div>
- {% elif not teams %}
- <div class="quill-empty flex w-full min-w-0 flex-col items-center justify-center gap-4 py-10"
- data-slot="empty">
- <div class="quill-empty__media quill-empty__media--variant-default flex shrink-0 items-center justify-center">
- <img class="w-28" src="/static/admin-console/hoggies/asleep.png" alt="" />
- </div>
- <div class="quill-empty__content flex flex-col items-center gap-1">
- <div class="quill-empty__title" data-slot="empty-title">No teams match "{{ query }}"</div>
- <div class="quill-empty__description" data-slot="empty-description">Try a team ID, the full API token, or part of the team or organization name.</div>
- </div>
+ <div class="flex flex-col gap-6 max-w-5xl">
+ <div>
+ <h1 class="m-0 text-[22px] font-extrabold">
+ <label for="team-search">Look up a team</label>
+ </h1>
+ <p class="m-0 mt-1 text-muted-foreground">
+ See a team's state and run staff actions on it. Reports across all teams are under Tools.
+ </p>
</div>
- {% else %}
- <section class="quill-card group/card flex flex-col max-w-3xl"
+ <section class="quill-card group/card flex flex-col"
data-quill
data-slot="card"
- data-size="sm">
+ data-size="default">
<div class="quill-card__content" data-slot="card-content">
- <table class="w-full border-collapse">
- <thead>
- <tr class="text-left text-xs text-muted-foreground border-b border-border">
- <th class="py-1.5 font-bold">Team</th>
- <th class="py-1.5 font-bold">Organization</th>
- <th class="py-1.5 font-bold">ID</th>
- </tr>
- </thead>
- <tbody>
- {% for team in teams %}
- <tr class="border-b border-border last:border-b-0">
- <td class="py-1.5"><a href="{% url 'admin_console_team' team_id=team.pk %}">{{ team.name }}</a></td>
- <td class="py-1.5">{{ team.organization.name }}</td>
- <td class="py-1.5 font-mono text-xs">{{ team.pk }}</td>
- </tr>
- {% endfor %}
- </tbody>
- </table>
+ <form method="get"
+ action="{% url 'admin_console_home' %}"
+ class="flex flex-wrap gap-2">
+ <input class="quill-input flex-1 min-w-[240px]"
+ id="team-search"
+ type="search"
+ name="q"
+ value="{{ query|default:'' }}"
+ placeholder="Team ID, project API token, or team or organization name"
+ aria-describedby="team-search-hint"
+ autofocus />
+ <button type="submit"
+ class="quill-button quill-button--variant-primary quill-button--size-default group/button inline-flex shrink-0 items-center justify-center whitespace-nowrap self-stretch h-auto">
+ Look up
+ </button>
+ </form>
+ <p id="team-search-hint" class="m-0 mt-2 text-xs text-muted-foreground">
+ A team ID, an API token or a name with one match opens the team right away. Press / on any page to jump here.
+ </p>
</div>
</section>
- {% endif %}
+ {% if query %}
+ {% if teams %}
+ <section class="quill-card group/card flex flex-col"
+ data-quill
+ data-slot="card"
+ data-size="sm">
+ <div class="quill-card__header group/card-header" data-slot="card-header">
+ <h2 class="quill-card__title m-0" data-slot="card-title">Teams matching "{{ query }}"</h2>
+ </div>
+ <div class="quill-card__content" data-slot="card-content">{% include "admin_console/_team_list.html" %}</div>
+ </section>
+ {% else %}
+ <div class="quill-empty flex w-full min-w-0 flex-col items-center justify-center gap-4 py-10"
+ data-slot="empty">
+ <div class="quill-empty__media quill-empty__media--variant-default flex shrink-0 items-center justify-center">
+ <img class="w-28" src="/static/admin-console/hoggies/asleep.png" alt="" />
+ </div>
+ <div class="quill-empty__content flex flex-col items-center gap-1">
+ <div class="quill-empty__title" data-slot="empty-title">No teams match "{{ query }}"</div>
+ <div class="quill-empty__description" data-slot="empty-description">
+ Try a team ID, the full project API token, or a shorter part of the name.
+ </div>
+ </div>
+ </div>
+ {% endif %}
+ {% else %}
+ <div class="@container">
+ <div class="grid gap-4 @3xl:grid-cols-2 items-start">
+ <section class="quill-card group/card flex flex-col"
+ data-quill
+ data-slot="card"
+ data-size="sm">
+ <div class="quill-card__header group/card-header" data-slot="card-header">
+ <h2 class="quill-card__title m-0" data-slot="card-title">Recently opened</h2>
+ </div>
+ <div class="quill-card__content" data-slot="card-content">
+ {% if recent_teams %}
+ {% include "admin_console/_team_list.html" with teams=recent_teams %}
+ {% else %}
+ <div class="flex items-center gap-3">
+ <img class="w-16"
+ src="/static/admin-console/hoggies/desk-wizard.png"
+ alt="" />
+ <p class="m-0 text-muted-foreground">Teams you open show up here, so you can get back to them quickly.</p>
+ </div>
+ {% endif %}
+ </div>
+ </section>
+ <section class="quill-card group/card flex flex-col"
+ data-quill
+ data-slot="card"
+ data-size="sm">
+ <div class="quill-card__header group/card-header" data-slot="card-header">
+ <h2 class="quill-card__title m-0" data-slot="card-title">On a team page</h2>
+ </div>
+ <div class="quill-card__content flex flex-col gap-2"
+ data-slot="card-content">
+ <p class="m-0 text-muted-foreground">Every team page shows these sections. Each team that owns one keeps it up to date.</p>
+ <ul class="m-0 p-0 list-none flex flex-col gap-1.5">
+ {% for panel in team_panels %}
+ <li class="flex items-center gap-2">
+ <img class="size-[18px]"
+ src="/static/admin-console/crests/{{ panel.owner.crest }}.svg"
+ alt="" />
+ <span class="font-semibold">{{ panel.title }}</span>
+ <span class="text-xs text-muted-foreground">{{ panel.owner.name }}</span>
+ </li>
+ {% endfor %}
+ </ul>
+ </div>
+ </section>
+ </div>
+ </div>
+ {% if tools %}
+ <section class="flex flex-col gap-2">
+ <h2 class="m-0 text-[15px] font-extrabold">Tools</h2>
+ <div class="@container">
+ <div class="grid gap-4 @3xl:grid-cols-2">
+ {% for tool in tools %}
+ <a class="quill-card group/card flex flex-col no-underline text-foreground hover:border-primary"
+ data-quill
+ data-slot="card"
+ data-size="sm"
+ href="{% url 'admin_console_tool' tool_key=tool.key %}">
+ <div class="quill-card__header group/card-header" data-slot="card-header">
+ <h3 class="quill-card__title m-0" data-slot="card-title">{{ tool.title }}</h3>
+ <div class="quill-card__action flex items-center gap-1.5 text-[11px] text-muted-foreground"
+ data-slot="card-action">
+ {{ tool.group }}
+ <img class="size-[18px]"
+ src="/static/admin-console/crests/{{ tool.owner.crest }}.svg"
+ alt="" />
+ </div>
+ </div>
+ {% if tool.description %}
+ <div class="quill-card__content text-muted-foreground"
+ data-slot="card-content">{{ tool.description }}</div>
+ {% endif %}
+ </a>
+ {% endfor %}
+ </div>
+ </div>
+ </section>
+ {% endif %}
+ {% endif %}
+ </div>
{% endblock %}
diff --git a/posthog/templates/admin_console/operation.html b/posthog/templates/admin_console/operation.html
index 639be18ce280..5fc01c5b071c 100644
--- a/posthog/templates/admin_console/operation.html
+++ b/posthog/templates/admin_console/operation.html
@@ -1,23 +1,40 @@
{% extends "admin_console/base.html" %}
{% block title %}{{ operation.label }} · {{ team.name }} · PostHog Admin{% endblock %}
{% block content %}
- <div class="text-xs text-muted-foreground">
+ <nav class="text-xs text-muted-foreground" aria-label="Breadcrumb">
+ <a class="text-muted-foreground" href="{% url 'admin_console_home' %}">Teams</a>
+ ›
<a class="text-muted-foreground"
- href="{% url 'admin_console_team' team_id=team.pk %}">{{ team.name }}</a> / {{ panel.title }} /
- </div>
+ href="{% url 'admin_console_team' team_id=team.pk %}">{{ team.name }}</a>
+ ›
+ <a class="text-muted-foreground"
+ href="{% url 'admin_console_team' team_id=team.pk %}#panel-{{ panel.key }}">{{ panel.title }}</a>
+ </nav>
<h1 class="mt-1.5 mb-4 text-[22px] font-extrabold">{{ operation.label }}</h1>
<section class="quill-card group/card flex flex-col max-w-xl{% if operation.danger %} console-danger{% endif %}"
data-quill
data-slot="card"
data-size="default">
- <form method="post" class="flex flex-col">
+ <div class="quill-card__header group/card-header" data-slot="card-header">
+ <div class="flex flex-col gap-1 min-w-0">
+ <span class="text-xs text-muted-foreground">This acts on</span>
+ <span class="flex flex-wrap items-center gap-2">
+ <strong class="text-[15px] break-words">{{ team.name }}</strong>
+ <span class="quill-badge inline-flex w-fit shrink-0 items-center justify-center gap-1 overflow-hidden whitespace-nowrap quill-badge--variant-default font-mono">Team {{ team.pk }}</span>
+ <span class="console-env-pill inline-flex items-center gap-1.5 px-2 py-0.5 rounded-full text-[11px] font-bold uppercase tracking-wide whitespace-nowrap">
+ <span class="console-env-dot size-[7px] rounded-full"></span>{{ console_env_label }}
+ </span>
+ </span>
+ <span class="text-muted-foreground">{{ team.organization.name }}</span>
+ </div>
+ </div>
+ <form method="post" class="flex flex-col" data-autofocus>
{% csrf_token %}
<input type="hidden" name="form_nonce" value="{{ form_nonce }}" />
<div class="quill-card__content flex flex-col gap-4"
data-slot="card-content">
- {% if operation.description %}
- <p class="m-0 text-muted-foreground">{{ operation.description }}</p>
- {% endif %}
+ {% if operation.description %}<p class="m-0">{{ operation.description }}</p>{% endif %}
+ {% if operation.undo_hint %}<p class="m-0 text-muted-foreground">{{ operation.undo_hint }}</p>{% endif %}
{% for error in form.non_field_errors %}
<p class="quill-field__error m-0" role="alert">{{ error }}</p>
{% endfor %}
@@ -28,7 +45,9 @@
<div class="quill-card__footer flex flex-wrap gap-2"
data-slot="card-footer">
<button type="submit"
- class="quill-button {% if operation.danger %}quill-button--variant-destructive-outline{% else %}quill-button--variant-primary{% endif %} quill-button--size-default group/button inline-flex shrink-0 items-center justify-center whitespace-nowrap">{{ operation.label }}</button>
+ class="quill-button {% if operation.danger %}quill-button--variant-destructive{% else %}quill-button--variant-primary{% endif %} quill-button--size-default group/button inline-flex shrink-0 items-center justify-center whitespace-nowrap">
+ {{ operation.label }} for {{ team.name|truncatechars:40 }}
+ </button>
<a href="{% url 'admin_console_team' team_id=team.pk %}"
class="quill-button quill-button--variant-outline quill-button--size-default group/button inline-flex shrink-0 items-center justify-center whitespace-nowrap">Cancel</a>
</div>
diff --git a/posthog/templates/admin_console/team.html b/posthog/templates/admin_console/team.html
index ebef4f523608..e352b6236b84 100644
--- a/posthog/templates/admin_console/team.html
+++ b/posthog/templates/admin_console/team.html
@@ -1,28 +1,68 @@
{% extends "admin_console/base.html" %}
{% block title %}{{ team.name }} · PostHog Admin{% endblock %}
{% block content %}
- <div class="text-xs text-muted-foreground">Teams / {{ team.organization.name }} /</div>
+ <nav class="text-xs text-muted-foreground" aria-label="Breadcrumb">
+ <a class="text-muted-foreground" href="{% url 'admin_console_home' %}">Teams</a>
+ ›
+ <a class="text-muted-foreground"
+ href="{% url 'admin_console_home' %}?q={{ team.organization.name|urlencode }}">{{ team.organization.name }}</a>
+ </nav>
<div class="flex flex-wrap items-start gap-4 mt-1.5 mb-4">
<div class="min-w-0">
<h1 class="m-0 text-[22px] font-extrabold break-words">{{ team.name }}</h1>
<div class="flex flex-wrap items-center gap-2 mt-1 text-muted-foreground">
- <span class="quill-badge quill-badge--variant-default font-mono">team {{ team.pk }}</span>
+ <span class="quill-badge inline-flex w-fit shrink-0 items-center justify-center gap-1 overflow-hidden whitespace-nowrap quill-badge--variant-default font-mono">Team {{ team.pk }}</span>
<span>{{ team.organization.name }}</span>
</div>
</div>
<div class="ml-auto flex flex-wrap gap-2">
<a class="quill-button quill-button--variant-outline quill-button--size-default group/button inline-flex shrink-0 items-center justify-center whitespace-nowrap"
- href="{% url 'admin:posthog_team_change' team.pk %}">Open in Django admin</a>
+ href="{% url 'admin:posthog_team_change' team.pk %}"
+ title="The raw Team row, with every field">Raw record in Django admin</a>
<a class="quill-button quill-button--variant-outline quill-button--size-default group/button inline-flex shrink-0 items-center justify-center whitespace-nowrap"
href="/project/{{ team.pk }}">Open in app ↗</a>
</div>
</div>
+ {% if attention %}
+ <section class="quill-card group/card flex flex-col mb-4 console-attention"
+ data-quill
+ data-slot="card"
+ data-size="sm"
+ aria-labelledby="attention-title">
+ <div class="quill-card__content flex flex-wrap items-center gap-x-4 gap-y-2"
+ data-slot="card-content">
+ <h2 id="attention-title" class="m-0 text-[13px] font-bold">Needs attention</h2>
+ {% for item in attention %}
+ <a class="flex items-center gap-1.5 text-foreground no-underline hover:underline"
+ href="#panel-{{ item.panel.key }}">
+ <span class="text-muted-foreground">{{ item.panel.title }} · {{ item.fact.label }}:</span>
+ {% include "admin_console/_badge.html" with label=item.fact.value tone=item.fact.tone %}
+ </a>
+ {% endfor %}
+ </div>
+ </section>
+ {% endif %}
<div class="grid gap-4 @3xl:grid-cols-2 items-start">
{% for rendered in regular_panels %}
{% include "admin_console/_panel.html" %}
{% endfor %}
- {% for rendered in danger_panels %}
- <div class="@3xl:col-span-2">{% include "admin_console/_panel.html" %}</div>
- {% endfor %}
</div>
+ {% if danger_panels %}
+ <section class="mt-8 flex flex-col gap-3" aria-labelledby="risky-title">
+ <div class="flex items-center gap-3">
+ <img class="w-12"
+ src="/static/admin-console/hoggies/traffic-police.png"
+ alt="" />
+ <div>
+ <p id="risky-title" class="m-0 text-[15px] font-extrabold">Risky actions</p>
+ <p class="m-0 text-muted-foreground">These change what the customer sees. Every action marked Risky asks for a reason and goes into the audit log.</p>
+ </div>
+ </div>
+ <div class="grid gap-4 @3xl:grid-cols-2 items-start">
+ {% for rendered in danger_panels %}
+ {% include "admin_console/_panel.html" %}
+ {% endfor %}
+ </div>
+ </section>
+ {% endif %}
{% endblock %}
diff --git a/posthog/templates/admin_console/tool.html b/posthog/templates/admin_console/tool.html
index b915f938c720..0b9d278b2116 100644
--- a/posthog/templates/admin_console/tool.html
+++ b/posthog/templates/admin_console/tool.html
@@ -1,7 +1,9 @@
{% extends "admin_console/base.html" %}
{% block title %}{{ tool.title }} · PostHog Admin{% endblock %}
{% block content %}
- <div class="text-xs text-muted-foreground">Tools / {{ tool.group }} /</div>
+ <nav class="text-xs text-muted-foreground" aria-label="Breadcrumb">
+ Tools › {{ tool.group }}
+ </nav>
<div class="flex flex-wrap items-start gap-4 mt-1.5 mb-4">
<div class="min-w-0">
<h1 class="m-0 text-[22px] font-extrabold">{{ tool.title }}</h1>
diff --git a/products/workflows/backend/console.py b/products/workflows/backend/console.py
index 8d13507f3a41..ee9faf0d4081 100644
--- a/products/workflows/backend/console.py
+++ b/products/workflows/backend/console.py
@@ -7,7 +7,7 @@ from posthog.admin.console.panels import Fact, Operation, Owner, Panel, Tone
from posthog.admin.console.registry import console
from posthog.models.team.team import Team
-from products.workflows.backend.facade.api import get_email_sending_state
+from products.workflows.backend.facade.api import get_email_sending_state, max_email_sending_tier
WORKFLOWS = Owner(name="Workflows", crest="workflows")
@@ -36,7 +36,12 @@ class EmailSendingPanel(Panel):
facts.append(Fact(label="Suspended at", value=state.suspended_at.strftime("%b %-d, %Y %H:%M UTC")))
facts.append(Fact(label="Reason", value=state.suspension_reason or "No reason recorded"))
if state is not None:
- facts.append(Fact(label="Tier", value=f"{state.tier}{' (pinned)' if state.tier_pinned else ''}"))
+ facts.append(
+ Fact(
+ label="Sending limit tier",
+ value=f"Tier {state.tier} of {max_email_sending_tier()}{', pinned by staff' if state.tier_pinned else ''}",
+ )
+ )
return facts
def operations(self, obj: Model) -> list[Operation]:
@@ -58,5 +63,6 @@ class EmailSendingPanel(Panel):
danger=True,
description="Stops workflow email for this team. The team gets an email and a notification.",
form_class=SuspendEmailSendingForm,
+ undo_hint="To undo, use Re-enable sending in the Email sending panel.",
)
]