### Quick Start Form with Validation and Submission
Source: https://github.com/getsentry/sentry/blob/master/static/app/components/core/form/form.mdx
A minimal example demonstrating how to set up a form with Zod validation and a submit handler using `useScrapsForm`.
```jsx
import {z} from 'zod';
import {defaultFormOptions, useScrapsForm} from '@sentry/scraps/form';
const schema = z.object({
email: z.email('Please enter a valid email'),
name: z.string().min(2, 'Name must be at least 2 characters'),
});
function MyForm() {
const form = useScrapsForm({
...defaultFormOptions,
defaultValues: {email: '', name: ''},
validators: {onDynamic: schema},
onSubmit: ({value}) => {
console.log(value);
},
});
return (
{field => (
)}
Submit
);
}
```
--------------------------------
### Example Pipeline View: Get User Input
Source: https://github.com/getsentry/sentry/blob/master/src/sentry/pipeline/README.md
This example demonstrates a `PipelineView` subclass that handles user input. It binds the input to the pipeline's state and progresses to the next step, or returns an error if data is missing.
```python
class GetUserInput(PipelineView):
def dispatch(self, request: HttpRequest, pipeline: Pipeline) -> HttpResponseBase:
# The pipeline supports a generic error method that will render a
# pipeline error view
if 'my_data' not in request.POST:
return pipeline.error('Data was not sent')
# Form submitted, bind user data and move to and render the next step
# in the pipeline.
if request.POST is not None:
pipeline.bind_state('user_input', request.POST)
return pipeline.next_step()
# Render form template
return render_view('app/pipeline_input.html')
```
--------------------------------
### Sync Dependencies and Setup Environment
Source: https://github.com/getsentry/sentry/blob/master/AGENTS.md
Use 'devenv sync' to refresh dependencies. Set SENTRY_DEVENV_FRONTEND_ONLY=1 to skip migrations when only frontend changes are needed. 'direnv allow' activates the environment, and 'devservices up' starts necessary services.
```bash
# Refreshes dependencies.
# SENTRY_DEVENV_FRONTEND_ONLY=1 skips over migrations which is not needed for pytest. HIGHLY RECOMMENDED.
SENTRY_DEVENV_FRONTEND_ONLY=1 devenv sync
```
```bash
# refresh dependencies, apply migrations
# Only relevant if you want a working development server.
devenv sync
direnv allow # activate the environment
devservices up # bring up services
```
--------------------------------
### Start Frontend Development Server
Source: https://github.com/getsentry/sentry/blob/master/AGENTS.md
Use 'pnpm run dev' to start the full development server, which requires 'devservices up'. Use 'pnpm run dev-ui' to start only the UI development server with hot reload, proxying API requests to production sentry.io.
```bash
# Start the full development server (requires devservices up)
pnpm run dev
```
```bash
# Start only the UI development server with hot reload
# Proxies API requests to production sentry.io
pnpm run dev-ui
```
--------------------------------
### Install sentry-twilio
Source: https://github.com/getsentry/sentry/blob/master/src/sentry_plugins/twilio/Twilio_Instructions.md
Install the sentry-twilio package using pip.
```bash
$ pip install sentry-twilio
```
--------------------------------
### Replay Summary Task Status - Not Started
Source: https://github.com/getsentry/sentry/blob/master/src/sentry/replays/blueprints/api.md
Example of a replay summary task response when the task has not yet started.
```json
{
"status": "not_started",
"created_at": null,
"num_segments": null,
"data": null
}
```
--------------------------------
### Annotation Example
Source: https://github.com/getsentry/sentry/wiki/Plugin-v2-Notes
Illustrates how to create an Annotation object with label, URL, and description.
```python
Annotation(label='GH-1', url='https://github.com')
```
--------------------------------
### Component File Structure Example
Source: https://github.com/getsentry/sentry/blob/master/static/app/components/core/overview/contributing.mdx
Place the .mdx documentation file next to the component's source file.
```treeview
components/
└── myButton.tsx
└── myButton.mdx
```
--------------------------------
### Starting Siloed Servers with Ngrok
Source: https://github.com/getsentry/sentry/blob/master/src/sentry/silo/README.md
Commands to start the Sentry development servers for control and region silos, utilizing ngrok with specified hostnames for external access.
```sh
sentry devserver --ngrok=acme.ngrok.dev --silo=control
```
```sh
sentry devserver --ngrok=acme.ngrok.dev --silo=region
```
--------------------------------
### Basic Button Usage Example
Source: https://github.com/getsentry/sentry/blob/master/static/app/components/core/overview/contributing.mdx
Demonstrates the basic usage of the Button component, including necessary imports.
```tsx
import {Button} from 'sentry/components/core/button';
function Example() {
return ;
}
```
--------------------------------
### Placeholder Example
Source: https://github.com/getsentry/sentry/blob/master/static/app/components/core/input/numberDragInput.mdx
Demonstrates how to use the placeholder prop to provide hint text when the input is empty.
```jsx
```
--------------------------------
### DeployBadge Example
Source: https://github.com/getsentry/sentry/blob/master/static/app/components/core/badge/badge.mdx
Use DeployBadge to link to issues related to a specific release, displaying environment information.
```jsx
import {DeployBadge} from '@sentry/scraps/badge';
```
--------------------------------
### Browse Replays API Response Example
Source: https://github.com/getsentry/sentry/blob/master/src/sentry/replays/blueprints/api.md
This JSON structure represents a sample response from the Sentry Replays API's GET endpoint. It details the fields returned for a single replay, including metadata like OS, SDK, project ID, and user information.
```json
{
"id": "7e07485f-12f9-416b-8b14-26260799b51f",
"is_archived": false,
"os": {
"name": "iOS",
"version": "16.2"
},
"platform": "Sentry",
"project_id": "639195",
"releases": ["version@1.4"],
"sdk": {
"name": "Thundercat",
"version": "27.1"
},
"started_at": "2022-07-07T14:05:57.909921",
"tags": {
"hello": ["world", "Lionel Richie"]
},
"trace_ids": ["7e07485f-12f9-416b-8b14-26260799b51f"],
"urls": ["/organizations/abc123/issues"],
"user": {
"display_name": "John Doe",
"email": "john.doe@example.com",
"id": "30246326",
"ip": "213.164.1.114",
"username": "John Doe"
}
}
```
--------------------------------
### Callout Examples (Tip and Warning)
Source: https://github.com/getsentry/sentry/blob/master/static/app/components/core/overview/contributing.mdx
Illustrates the use of callouts for emphasizing important information, such as tips or warnings.
```mdx
> [!TIP]
> Helpful tips and best practices
> [!WARNING]
> Important warnings or limitations
```
--------------------------------
### Fetch Flag Log Response Example
Source: https://github.com/getsentry/sentry/blob/master/src/sentry/flags/docs/api.md
Example JSON response for fetching a single flag log. It details the flag's status, creation time, creator, and tags.
```json
{
"data": {
"action": "updated",
"createdAt": "2024-11-19T19:12:55",
"createdBy": "user@site.com",
"createdByType": "email",
"flag": "new-flag-name",
"id": 1,
"tags": {
"environment": "development"
}
}
}
```
--------------------------------
### LinkButton Internal Navigation Examples
Source: https://github.com/getsentry/sentry/blob/master/static/app/components/core/button/linkButton.mdx
Examples of using the `to` prop for internal app navigation, which renders as a Link component for client-side routing.
```jsx
Organization SettingsView Projects
```
--------------------------------
### Pride Loader Path Animation Setup
Source: https://github.com/getsentry/sentry/blob/master/src/sentry/templates/sentry/partial/loader-pride.html
Sets up the stroke-dasharray, stroke-dashoffset, and animation properties for the pride mask paths.
```css
#pride-mask g[data-index] path { stroke-dasharray: 522; stroke-dashoffset: 522; animation-duration: var(--pride-loop); animation-iteration-count: infinite; animation-fill-mode: both; animation-timing-function: cubic-bezier(0.455, 0.03, 0.515, 0.955); }
```
--------------------------------
### LinkButton External Navigation Examples
Source: https://github.com/getsentry/sentry/blob/master/static/app/components/core/button/linkButton.mdx
Examples of using the `href` prop for external URLs. These links open in a new tab with security attributes.
```jsx
Documentation
GitHub
```
--------------------------------
### BillingService Abstraction Example
Source: https://github.com/getsentry/sentry/blob/master/src/sentry/billing/platform/INTENTION.md
Illustrates the intended interface for interacting with billing services, emphasizing protobuf usage and service method decorators.
```python
# this example is meant to illustrate the intention, the nuances of the interface may change
from getsentry.services.billing import BillingService
from sentry_protos.billing.v1.sevices.contract import GetContractRequest, GetContractResponse
class ContractService(BillingService):
@service_method # denotes that this method can be called external to this service. The decorator also includes base functionality for service endpoints e.g. metrics/observability
def get_contract(self, request_proto: GetContractRequest) -> GetContractResponse:
# implementation here
pass
contract_proto = ContractService().get_contract(GetContractRequest(organization_id=1))
```
--------------------------------
### Example Integration Request Parser
Source: https://github.com/getsentry/sentry/blob/master/src/sentry/middleware/integrations/integration_control_middleware.md
Implement a custom parser by extending BaseRequestParser. This example shows how to extract integration IDs from headers and determine the appropriate response strategy based on the request path and target silos.
```python
class ExampleRequestParser(BaseRequestParser):
provider = "example" # will match `/extensions/example/*` request paths
def get_integration_from_request(self) -> Integration | None:
integration_id = self.request.headers.get("X-Sentry-Integration-Id")
return Integration.objects.filter(id=integration_id).first()
def get_response(self):
# You can use the url router to identify the endpoint/view the request is headed to
if self.view_class in [ExampleConfigureView, ExampleSetupView]:
return self.get_response_from_control_silo()
# This method calls self.get_organizations_from_integration which calls self.get_integration_from_request.
cells = self.get_cells_from_organizations()
# If we're getting responses from multiple cells asynchronously...
if '/async/' in self.request.path:
return self.get_response_from_webhookpayload(cells=cells)
# If we're getting responses from multiple cells synchronously...
response_map = self.get_responses_from_cell_silos(cells=cells)
# Require all forwarded requests to succeed...
if not all([result.error is None for result in response_map.values()])
return HttpResponse(status_code=200)
```
--------------------------------
### Browse Flag Logs Response Example
Source: https://github.com/getsentry/sentry/blob/master/src/sentry/flags/docs/api.md
Example JSON response when browsing flag logs. It includes details about flag actions, creation timestamps, creators, and associated tags.
```json
{
"data": [
{
"action": "created",
"createdAt": "2024-01-01T05:12:33",
"createdBy": "2552",
"createdByType": "id",
"flag": "my-flag-name",
"id": 1,
"tags": {
"environment": "production"
}
}
]
}
```
--------------------------------
### Initialize Sentry Setup Wizard React Component
Source: https://github.com/getsentry/sentry/blob/master/src/sentry/templates/sentry/setup-wizard.html
This JavaScript snippet initializes the Sentry Setup Wizard React component. It pushes configuration to a global array `__onSentryInit` which is expected to be processed by the Sentry frontend application. Ensure the container element and necessary props are correctly provided.
```javascript
window.__onSentryInit = window.__onSentryInit || [];
window.__onSentryInit.push({
name: 'renderReact',
component: 'SetupWizard',
container: '#setup-wizard-container',
props: {
hash: {{ hash|to_json|safe }},
organizations: {{ organizations|to_json|safe }},
enableProjectSelection: {{ enableProjectSelection|to_json|safe }},
},
});
```
--------------------------------
### InlineCode Example
Source: https://github.com/getsentry/sentry/blob/master/static/app/components/core/code/inlineCode.mdx
Demonstrates the basic usage of InlineCode to highlight code elements like function calls within a sentence.
```jsx
The console.log() function outputs messages to the browser
console.
```
--------------------------------
### Grid Alignment Example
Source: https://github.com/getsentry/sentry/blob/master/static/app/components/core/layout/grid.mdx
Demonstrates how to center items within a Grid component using justify and align props.
```jsx
Centered Item
Another Item
```
--------------------------------
### Tabbed Code Block for Installation Methods
Source: https://github.com/getsentry/sentry/blob/master/static/app/components/core/code/codeBlock.mdx
Creates a tabbed interface for displaying different code snippets, such as installation commands for npm and Yarn. Manages active tab state and click events.
```jsx
const [tab, setTab] = useState('npm');
setTab(t)}
language="bash"
>
{tab === 'npm' ? `npm install --save @sentry/browser` : 'yarn add @sentry/browser'}
```
--------------------------------
### Input Field Example
Source: https://github.com/getsentry/sentry/blob/master/static/app/components/core/form/fields.mdx
Shows how to use the `Input` field for single-line string values. Includes a `required` prop and a `placeholder` for user guidance.
```jsx
{field => (
)}
```
--------------------------------
### Browse Signing Secrets Response Example
Source: https://github.com/getsentry/sentry/blob/master/src/sentry/flags/docs/api.md
Example JSON response when browsing signing secrets. It shows the creation date, creator, ID, provider, and a redacted secret.
```json
{
"data": [
{
"createdAt": "2024-12-12T00:00:00+00:00",
"createdBy": 12345,
"id": 123,
"provider": "launchdarkly",
"secret": "abc123**********"
}
]
}
```
--------------------------------
### useScrapsForm Configuration Example
Source: https://github.com/getsentry/sentry/blob/master/static/app/components/core/form/form.mdx
Illustrates the basic configuration for the `useScrapsForm` hook, including default options, default values, validators, and an onSubmit handler.
```jsx
const form = useScrapsForm({
...defaultFormOptions,
defaultValues: {email: '', name: ''},
validators: {onDynamic: schema},
onSubmit: ({value, formApi}) => {
// Handle submission
},
});
```
--------------------------------
### CompositeSelect vs CompactSelect Example
Source: https://github.com/getsentry/sentry/blob/master/static/app/components/core/compactSelect/composite.mdx
Compares CompositeSelect for independent sections with different behaviors against CompactSelect for a single list of grouped options.
```jsx
// CompositeSelect: Independent sections with different behaviors
// CompactSelect: Single selection from grouped options
```
--------------------------------
### Animation Timing Example
Source: https://github.com/getsentry/sentry/blob/master/static/app/components/core/input/numberDragInput.mdx
Shows how to use NumberDragInput to allow users to interactively explore animation durations.
```jsx
```
--------------------------------
### Select Field Example
Source: https://github.com/getsentry/sentry/blob/master/static/app/components/core/form/fields.mdx
Illustrates the `Select` component for single-value dropdown selection. It requires an `options` array, where each option has a `value` and a `label`.
```jsx
{field => (
)}
```
--------------------------------
### Testing Routing with `initialRouterConfig`
Source: https://github.com/getsentry/sentry/blob/master/static/AGENTS.md
Demonstrates how to configure the initial router state, including location and query parameters, and how to interact with the router and test navigation.
```tsx
const {router} = render(, {
initialRouterConfig: {
location: {
pathname: '/foo/',
query: {page: '1'},
},
},
});
// Uses passes in config to set initial location
expect(router.location.pathname).toBe('/foo');
expect(router.location.query.page).toBe('1');
// Clicking links goes to the correct location
await userEvent.click(screen.getByRole('link', {name: 'Go to /bar/'}));
// Can check current route on the returned router
expect(router.location.pathname).toBe('/bar/');
// Can test manual route changes with router.navigate
router.navigate('/new/path/');
router.navigate(-1); // Simulates clicking the back button
```
--------------------------------
### Basic Python Code Block
Source: https://github.com/getsentry/sentry/blob/master/static/app/components/core/code/codeBlock.mdx
Renders a multi-line Python code snippet with syntax highlighting. Suitable for setup instructions or code examples.
```jsx
{samplePython}
```
--------------------------------
### Get Replay Delete Job Response
Source: https://github.com/getsentry/sentry/blob/master/src/sentry/replays/blueprints/api.md
Example response for fetching a specific replay delete job. It provides the job's ID, creation/update times, deletion parameters, status, and the count of deleted replays.
```json
{
"data": {
"id": 23,
"dateCreated": "2025-06-06T14:05:57.909921",
"dateUpdated": "2025-06-06T14:05:57.909921",
"rangeStart": "2025-06-01T00:00:00.000000",
"rangeEnd": "2025-06-04T00:00:00.000000",
"environments": ["production"],
"status": "pending",
"query": "release:2.3.0 AND url:*/billing*",
"countDeleted": 1452667
}
}
```
--------------------------------
### Run UI Development Server with Storybook and Type Generation
Source: https://github.com/getsentry/sentry/blob/master/static/app/components/core/overview/contributing.mdx
Run the development server with Storybook and generate component types at build time. This option may result in slower dev server startup.
```bash
pnpm run dev-ui-storybook
```
--------------------------------
### Threshold Adjustment Example
Source: https://github.com/getsentry/sentry/blob/master/static/app/components/core/input/numberDragInput.mdx
Example of using NumberDragInput for real-time adjustment of numeric thresholds, such as error percentages.
```jsx
```
--------------------------------
### Run Linting and Formatting Tools
Source: https://github.com/getsentry/sentry/blob/master/AGENTS.md
Use 'prek run -q' as the single entrypoint for all lint, format, and type-checking tools. It automatically detects changed files. Specific hooks like mypy or ruff can be run with file path arguments.
```bash
cd /path/to/sentry && .venv/bin/prek run -q
```
```bash
SENTRY_MYPY_PRE_PUSH=1 .venv/bin/prek run -q mypy --files src/sentry/foo/bar.py --stage pre-push
```
```bash
.venv/bin/prek run -q ruff --files src/sentry/foo/bar.py
```
--------------------------------
### List Projects with Autofix Settings Response
Source: https://github.com/getsentry/sentry/blob/master/src/sentry/seer/blueprints/api.md
Example JSON response for listing projects and their autofix automation settings. Shows project ID, tuning, stopping point, and repository count.
```json
[
{
"projectId": 123,
"autofixAutomationTuning": "medium",
"automatedRunStoppingPoint": "code_changes",
"reposCount": 2
},
{
"projectId": 456,
"autofixAutomationTuning": "off",
"automatedRunStoppingPoint": "root_cause",
"reposCount": 0
}
]
```
--------------------------------
### Visual Property Tuning Example
Source: https://github.com/getsentry/sentry/blob/master/static/app/components/core/input/numberDragInput.mdx
Example of using NumberDragInput for interactive adjustment of visual properties like border radius.
```jsx
```
--------------------------------
### Using the UsageService
Source: https://github.com/getsentry/sentry/blob/master/src/sentry/billing/platform/services/README.md
Illustrates how to retrieve daily usage data for an organization using the UsageService.
```python
from sentry.billing.platform.services.usage import UsageService
from sentry_protos.billing.v1.services.usage.v1.endpoint_usage_pb2 import GetUsageRequest
response = UsageService().get_usage(GetUsageRequest(organization_id=1))
```
--------------------------------
### SegmentedControl with Disabled Item Example
Source: https://github.com/getsentry/sentry/blob/master/static/app/components/core/segmentedControl/segmentedControl.mdx
A concise example demonstrating how to disable a specific item within a SegmentedControl. This highlights the `disabled` prop on the ``.
```jsx
Enabled
Disabled
```
--------------------------------
### Use Fixtures for Object Initialization
Source: https://github.com/getsentry/sentry/blob/master/static/AGENTS.md
Illustrates the preferred method of importing and using fixture functions to create object instances, instead of manually typing and initializing them.
```tsx
// ❌ Don't import type and initialize it
import type {Project} from 'sentry/types/project';
const project: Project = {...}
// ✅ Import a fixture instead
import {ProjectFixture} from 'sentry-fixture/project';
const project = ProjectFixture(partialProject)
```
--------------------------------
### Mocking Simple GET and POST Requests
Source: https://github.com/getsentry/sentry/blob/master/static/AGENTS.md
Use MockApiClient.addMockResponse to simulate GET and POST requests. Specify the URL and the desired response body.
```tsx
// Simple GET request
MockApiClient.addMockResponse({
url: '/projects/',
body: [{id: 1, name: 'my project'}],
});
// POST request
MockApiClient.addMockResponse({
url: '/projects/',
method: 'POST',
body: {id: 1, name: 'my project'},
});
```
--------------------------------
### Example StatefulDetectorHandler extract_value
Source: https://github.com/getsentry/sentry/blob/master/src/sentry/workflow_engine/handlers/detector/index.md
Implement the `extract_value` property to define how to extract the relevant value from a `DataPacket` for detector evaluation. This example retrieves a 'value' from the packet.
```python
class ExampleDetectorHandler(StatefulDetectorHandler):
@property
def extract_value(self, data_packet: DataPacket) -> DataPacketEvaluationType | dict[DetectorGroupType, DataPacketEvaluationType]:
return data_packet.packet.get("value")
```
--------------------------------
### Create Signing Secret Request Example
Source: https://github.com/getsentry/sentry/blob/master/src/sentry/flags/docs/api.md
Example JSON payload for creating a new signing secret. Requires the provider name and the secret value.
```json
{
"provider": "launchdarkly",
"secret": "d41d7d1adced450d9e2eb7f76dde6a04"
}
```
--------------------------------
### Async Resource Actions for Command Palette
Source: https://github.com/getsentry/sentry/blob/master/static/app/components/commandPalette/useCommandPaletteActions.mdx
Shows how to use the `resource` prop with `CMDKAction` to fetch and display asynchronous data. The `resource` prop takes a query function, and the children prop is a render function that processes the fetched results.
```tsx
import type {CommandPaletteAsyncResult} from 'sentry/components/commandPalette/types';
({
queryKey: ['/projects/', {query}],
queryFn: () => fetchProjects(query),
// transform response into CommandPaletteAsyncResult[]
select: (data): CommandPaletteAsyncResult[] =>
data.map(p => ({
display: {label: p.name},
to: `/projects/${p.slug}/`,
})),
})}
>
{(results: CommandPaletteAsyncResult[]) =>
results.map(r => (
))
}
;
```
--------------------------------
### Composite Select Region Example
Source: https://github.com/getsentry/sentry/blob/master/static/app/components/core/compactSelect/composite.mdx
Example of a CompositeSelect.Region component. Ensure labels clearly identify the controlled section and use aria-label if the visual label is insufficient.
```jsx
```
--------------------------------
### Composite Select Trigger Button Examples
Source: https://github.com/getsentry/sentry/blob/master/static/app/components/core/compactSelect/composite.mdx
Examples of descriptive trigger buttons for Composite Select. Consider showing selected values or counts in the trigger text for clarity.
```jsx
// Good: Descriptive trigger
Filters: {selectedCount} active
```
```jsx
// Good: Clear purpose
Date: {month}/{day}
```
--------------------------------
### Example StatefulDetectorHandler create_occurrence
Source: https://github.com/getsentry/sentry/blob/master/src/sentry/workflow_engine/handlers/detector/index.md
Implement the `create_occurrence` method to define how an issue occurrence is generated when a detector reaches a certain threshold. This example shows how to return a `DetectorOccurrence` with specific details.
```python
class ExampleDetectorHandler(StatefulDetectorHandler):
def create_occurrence(
self,
evaluation: DataPacketEvaluationType,
data_packet: DataPacket,
new_priority: DetectorPriority,
) -> DetectorOccurrence:
"""
if new_priority == DetectorPriorityLevel.HIGH:
# can invoke other methods for high priority handling
pass
return DetectorOccurrence(
issue_title=f"self.detector.name triggered",
substitle=f"Detector {self.detector.name} from {evaluation[0].condition_results[0].condition.type}",
evidence_data=evaluation,
evidence_display=[]
type=MetricIssue,
level="error",
culprit="A culprit that was found in the data"
)
```
--------------------------------
### Setup Git Worktree Environment
Source: https://github.com/getsentry/sentry/blob/master/AGENTS.md
When creating a new git worktree, a post-checkout hook runs 'devenv sync'. If not, manually run 'devenv sync' once in the new worktree and then 'direnv allow' to activate the dev environment.
```bash
git worktree add
devenv sync
direnv allow
```
--------------------------------
### Pipeline Provider: Declaring Pipeline Views
Source: https://github.com/getsentry/sentry/blob/master/src/sentry/pipeline/README.md
This example shows how a `PipelineProvider` subclass declares the sequence of `PipelineView` instances it will use for a pipeline flow.
```python
def get_pipeline_views(self) -> list[PipelineView]:
return [GetUserInput(), RequestApiTokenStep()]
```
--------------------------------
### Basic Select Usage
Source: https://github.com/getsentry/sentry/blob/master/static/app/components/core/select/select.mdx
Demonstrates the basic implementation of the Select component with a placeholder and a list of options. Use this for simple single-selection scenarios.
```jsx
```
--------------------------------
### Example StatefulDetectorHandler thresholds override
Source: https://github.com/getsentry/sentry/blob/master/src/sentry/workflow_engine/handlers/detector/index.md
Override the `thresholds` property to customize the priority level thresholds for creating issue occurrences. This example sets custom thresholds for LOW and HIGH priority levels.
```python
class ExampleDetectorHandler(StatefulDetectorHandler):
@property
def thresholds(self) -> DetectorThresholds:
return {
DetectorPriorityLevel.LOW: 10,
DetectorPriorityLevel.HIGH: 5,
}
```
--------------------------------
### Running Control and Region Silos
Source: https://github.com/getsentry/sentry/blob/master/src/sentry/silo/README.md
Commands to start the Sentry development server for both the control and region silos. The control silo runs on default ports, while the region silo can be started with the --ingest flag.
```sh
sentry devserver --silo=control --celery-beat --workers
```
```sh
sentry devserver --silo=region --celery-beat --workers --ingest
```
--------------------------------
### Replace Model.objects.create with Factory Method
Source: https://github.com/getsentry/sentry/blob/master/tests/AGENTS.md
Shows how to replace direct model creation with a factory method for better test setup consistency. Use `self.create_project` or other factory methods provided by Sentry's test utilities.
```diff
```diff
- direct_project = Project.objects.create(
- organization=self.organization,
- name="Directly Created",
- slug="directly-created"
- )
+ direct_project = self.create_project(
+ organization=self.organization,
+ name="Directly Created",
+ slug="directly-created" # Note: Ensure factory args match
+ )
```
```
--------------------------------
### Using Semantic Color Tokens
Source: https://github.com/getsentry/sentry/blob/master/static/app/components/core/principles/tokens/tokens.mdx
Demonstrates the correct way to apply background colors using semantic tokens instead of raw color values. Prefer semantic tokens to ensure UI consistency across theme changes and rebrands.
```jsx
const Component = styled('span')`
/* ❌ Do not use use raw color values */
background-color: ${p => p.theme.colors.red400}
/* ✅ Prefer use of semantic tokens */
background-color: ${p => p.theme.tokens.background.danger.vibrant}
`;
```
--------------------------------
### Drawer with Helper Components
Source: https://github.com/getsentry/sentry/blob/master/static/app/components/core/drawer/drawer.mdx
Demonstrates the usage of `DrawerHeader` and `DrawerBody` helper components for structuring drawer content. `DrawerHeader` provides a sticky header with a close button, and `DrawerBody` handles padding and scrolling.
```jsx
import {Fragment} from 'react';
import {DrawerBody, DrawerHeader} from '@sentry/scraps/drawer';
import {useDrawer} from '@sentry/scraps/drawer';
// Assuming openDrawer is available from useDrawer hook
const {openDrawer} = useDrawer();
openDrawer(
() => (
My DrawerLorem, ipsum...
),
{ariaLabel: 'My Drawer', onClose: () => alert('Called my handler!')}
);
```
--------------------------------
### Monospace Text Example
Source: https://github.com/getsentry/sentry/blob/master/static/app/components/core/text/text.mdx
Apply fixed-width formatting to text using the 'monospace' prop.
```jsx
12345678901234567890
```
--------------------------------
### Basic CompactSelect Usage
Source: https://github.com/getsentry/sentry/blob/master/static/app/components/core/compactSelect/compactSelect.mdx
Demonstrates the fundamental usage of CompactSelect with a single value selection. Options can include additional 'details' for context.
```jsx
setValue(option.value)}
options={[
{value: '1', label: 'Option 1'},
{value: '2', label: 'Option 2'},
{value: '3', label: 'Option 3'},
]}
/>
```
```jsx
const [value, setValue] = useState('');
const options = [
{value: '', label: 'All'},
{value: '2', label: '2XX', details: 'Success responses'},
{value: '3', label: '3XX', details: 'Redirects'},
];
setValue(option.value)}
options={options}
/>;
```
--------------------------------
### Ellipsis Overflow Example
Source: https://github.com/getsentry/sentry/blob/master/static/app/components/core/text/text.mdx
Truncate long text with an ellipsis using the 'ellipsis' prop.
```jsx
This is a very long text that will be truncated with an ellipsis
```
--------------------------------
### Selectable List Implementation
Source: https://github.com/getsentry/sentry/blob/master/static/app/components/core/menuListItem/menuListItem.mdx
Shows how to create a selectable list using MenuListItem. It handles focus and selection states, and displays icons and details for each item.
```jsx
{
items.map((item, index) => (
}
onClick={() => handleSelect(item.id)}
/>
));
}
```
--------------------------------
### Basic GitHub Plugin Implementation
Source: https://github.com/getsentry/sentry/wiki/Plugin-v2-Notes
A skeletal implementation of a GitHub plugin, demonstrating required methods like 'is_enabled_for_team', 'is_configured_for_project', and configuration retrieval methods.
```python
class GitHubPlugin(Plugin):
def is_enabled_for_team():
return self.is_enabled()
def is_configured_for_project():
return self.is_configured_for_team(project.team)
def is_configured(self):
return True
def get_site_config(self):
def get_team_config(self):
return [
('Notifications', 'HipChat', HipChatFormView)
]
def get_project_config(self):
return [
('Notifications', 'HipChat', HipChatFormView)
]
def get_rules(self):
return []
def get_permissions(self):
return []
def get_notifiers(self):
return []
def get_annotations(self):
return []
def get_panels(self):
return [
('Comments', CommentViewCallable),
]
def get_actions(self):
return [
('Create GitHub Issue', ViewCallable),
]
```
--------------------------------
### Text Density Examples
Source: https://github.com/getsentry/sentry/blob/master/static/app/components/core/text/text.mdx
Adjust line height with the 'density' prop. Options are 'compressed', default, and 'comfortable'.
```jsx
Compressed density text...Default density text...Comfortable density text...
```
--------------------------------
### Composite Index Strategy Examples
Source: https://github.com/getsentry/sentry/blob/master/src/AGENTS.md
Demonstrates scenarios requiring composite indexes for efficient multi-column filtering. Ensure index column order matches query filter order.
```python
# NEEDS COMPOSITE INDEX: Filtering on foreign_key_id AND id
Model.objects.filter(
foreign_key_id__in=ids, # First column
id__gt=last_id # Second column
)[:batch_size]
# Required: Index(fields=["foreign_key", "id"])
# NEEDS COMPOSITE INDEX: Status + timestamp range queries
Model.objects.filter(
status="open", # First column
created_at__gte=start # Second column
)
# Required: Index(fields=["status", "created_at"])
```
--------------------------------
### Basic MenuListItem
Source: https://github.com/getsentry/sentry/blob/master/static/app/components/core/menuListItem/menuListItem.mdx
A basic example of a MenuListItem with a label. It can be used as a fundamental building block for menus and lists.
```jsx
(state.isSelected ? '✓' : null)} />
```
--------------------------------
### useFetchSpanTimeSeries with Chart Widgets
Source: https://github.com/getsentry/sentry/blob/master/static/app/utils/timeSeries/useFetchEventsTimeSeries.mdx
Demonstrates integrating useFetchSpanTimeSeries with TimeSeriesWidgetVisualization for displaying chart data. Requires importing necessary components and the hook.
```jsx
import {useFetchSpanTimeSeries} from 'sentry/utils/timeSeries/useFetchEventsTimeSeries';
import {TimeSeriesWidgetVisualization} from 'sentry/views/dashboards/widgets/timeSeriesWidget/timeSeriesWidgetVisualization';
import {Widget} from 'sentry/views/dashboards/widgets/widget/widget';
import {Line} from 'sentry/views/dashboards/widgets/timeSeriesWidget/plottables/line';
...
const Chart () {
const {isPending, data, error} = useFetchSpanTimeSeries(
{
yAxis: ["p50(span.duration)", "p99(span.duration)"],
query: "span.category:db",
},
"api.storybook.example"
);
const lines = data.timeSeries?.map(timeSeries => {
return new Line(timeSeries);
});
return (
}
/>
);
}
```
--------------------------------
### Fetch Replay Response Example
Source: https://github.com/getsentry/sentry/blob/master/src/sentry/replays/blueprints/api.md
This JSON structure represents a successful response when fetching a single replay instance. It includes details about the replay's activity, browser, device, OS, and user information.
```json
{
"data": {
"activity": 5,
"browser": {
"name": "Chome",
"version": "103.0.38"
},
"count_dead_clicks": 6,
"count_rage_clicks": 1,
"count_errors": 1,
"count_segments": 0,
"count_urls": 1,
"device": {
"brand": "Apple",
"family": "iPhone",
"model": "11",
"name": "iPhone 11"
},
"dist": null,
"duration": 576,
"environment": "production",
"error_ids": ["7e07485f-12f9-416b-8b14-26260799b51f"],
"finished_at": "2022-07-07T14:15:33.201019",
"has_viewed": false,
"id": "7e07485f-12f9-416b-8b14-26260799b51f",
"os": {
"name": "iOS",
"version": "16.2"
},
"platform": "Sentry",
"project_id": "639195",
"releases": ["version@1.4"],
"sdk": {
"name": "Thundercat",
"version": "27.1"
},
"started_at": "2022-07-07T14:05:57.909921",
"tags": {
"hello": ["world", "Lionel Richie"]
},
"trace_ids": ["7e07485f-12f9-416b-8b14-26260799b51f"],
"urls": ["/organizations/abc123/issues"],
"user": {
"display_name": "John Doe",
"email": "john.doe@example.com",
"id": "30246326",
"ip": "213.164.1.114",
"username": "John Doe"
}
}
}
```
--------------------------------
### Replay Summary Task Status - Error
Source: https://github.com/getsentry/sentry/blob/master/src/sentry/replays/blueprints/api.md
Example of a replay summary task response when an error occurred.
```json
{
"status": "error",
"created_at": "2025-06-06T14:05:11.909921",
"num_segments": 5,
"data": null
}
```
--------------------------------
### Run UI Development Server
Source: https://github.com/getsentry/sentry/blob/master/static/app/components/core/overview/contributing.mdx
Run the development server for Scraps components. This command is used to work with core components locally.
```bash
pnpm run dev-ui
```