Metadata-Version: 2.5
Name: jupyterlab_notifications_extension
Version: 1.2.28
Summary: JupyterLab extension that shows notifications sent by a JupyterHub administrator or by a script, as a toast and in the notification center.
Project-URL: Homepage, https://github.com/stellarshenson/jupyterlab_notifications_extension
Project-URL: Bug Tracker, https://github.com/stellarshenson/jupyterlab_notifications_extension/issues
Project-URL: Repository, https://github.com/stellarshenson/jupyterlab_notifications_extension.git
Author-email: Stellars Henson <konrad.jelen@gmail.com>
License: BSD 3-Clause License
        
        Copyright (c) 2025, Stellars Henson
        All rights reserved.
        
        Redistribution and use in source and binary forms, with or without
        modification, are permitted provided that the following conditions are met:
        
        1. Redistributions of source code must retain the above copyright notice, this
           list of conditions and the following disclaimer.
        
        2. Redistributions in binary form must reproduce the above copyright notice,
           this list of conditions and the following disclaimer in the documentation
           and/or other materials provided with the distribution.
        
        3. Neither the name of the copyright holder nor the names of its
           contributors may be used to endorse or promote products derived from
           this software without specific prior written permission.
        
        THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
        AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
        IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
        DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
        FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
        DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
        SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
        CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
        OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
        OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
License-File: LICENSE
Keywords: jupyter,jupyterlab,jupyterlab-extension
Classifier: Framework :: Jupyter
Classifier: Framework :: Jupyter :: JupyterLab
Classifier: Framework :: Jupyter :: JupyterLab :: 4
Classifier: Framework :: Jupyter :: JupyterLab :: Extensions
Classifier: Framework :: Jupyter :: JupyterLab :: Extensions :: Prebuilt
Classifier: License :: OSI Approved :: BSD License
Classifier: Programming Language :: Python
Classifier: Programming Language :: Python :: 3
Classifier: Programming Language :: Python :: 3.10
Classifier: Programming Language :: Python :: 3.11
Classifier: Programming Language :: Python :: 3.12
Classifier: Programming Language :: Python :: 3.13
Requires-Python: >=3.10
Requires-Dist: jupyter-server<3,>=2.21
Requires-Dist: tornado>=6.2
Provides-Extra: dev
Requires-Dist: jupyterlab<5,>=4.6; extra == 'dev'
Provides-Extra: test
Requires-Dist: pytest-asyncio<2,>=1.4; extra == 'test'
Requires-Dist: pytest-cov; extra == 'test'
Requires-Dist: pytest-jupyter[server]<1,>=0.11; extra == 'test'
Requires-Dist: pytest<10,>=9.1; extra == 'test'
Description-Content-Type: text/markdown

# jupyterlab_notifications_extension

[![GitHub Actions](https://github.com/stellarshenson/jupyterlab_notifications_extension/actions/workflows/build.yml/badge.svg)](https://github.com/stellarshenson/jupyterlab_notifications_extension/actions/workflows/build.yml)
[![npm version](https://img.shields.io/npm/v/jupyterlab_notifications_extension.svg)](https://www.npmjs.com/package/jupyterlab_notifications_extension)
[![PyPI version](https://img.shields.io/pypi/v/jupyterlab-notifications-extension.svg)](https://pypi.org/project/jupyterlab-notifications-extension/)
[![Total PyPI downloads](https://static.pepy.tech/badge/jupyterlab-notifications-extension)](https://pepy.tech/project/jupyterlab-notifications-extension)
[![JupyterLab 4](https://img.shields.io/badge/JupyterLab-4-orange.svg)](https://jupyterlab.readthedocs.io/en/stable/)

> [!TIP]
> This extension is part of the [stellars_jupyterlab_extensions](https://github.com/stellarshenson/stellars_jupyterlab_extensions) metapackage. Install all Stellars extensions at once: `pip install stellars_jupyterlab_extensions`

JupyterLab extension for sending notifications using the native JupyterLab notification system. External systems and extensions send alerts and status updates that appear in JupyterLab's notification center.

This extension serves as the notification backbone for [Stellars JupyterHub Platform for Data Science](https://github.com/stellarshenson/stellars-jupyterhub-ds), allowing administrators to send notification messages to a running JupyterLab server. Each send addresses one server.

Notification types with distinct visual styling provide clear status communication:

![Notification Types](.resources/screenshot-notifications.png)

Access via command palette for quick manual notification sending:

![Command Palette](.resources/screenshot-palette.png)

Interactive dialog with message input, type selection, auto-close timing, and an optional dismiss button:

![Send Dialog](.resources/screenshot-command.png)

**Key Features:**

- REST API for external systems to POST notifications with authentication
- Command palette integration with interactive dialog
- Programmatic command API for extensions and automation
- Six notification types (default, info, success, warning, error, in-progress)
- Configurable auto-close with millisecond precision or manual dismiss
- Action buttons with optional JupyterLab command execution
- Dynamic time-ago indicator showing when each notification was generated
- Best-effort delivery via 30-second polling (the first tab to poll takes it)
- Immediate WebSocket push for instant display (`--now` / `"immediate": true`)
- In-memory queue cleared after delivery

## Installation

```bash
pip install jupyterlab_notifications_extension
```

**Requirements**: JupyterLab >= 4.6.0, Python >= 3.10

## API Reference

### POST /jupyterlab-notifications-extension/ingest

Send notifications to JupyterLab. Requires authentication via an `Authorization: token <TOKEN>` header. Do not put the token in the URL, where it lands in server and proxy access logs.

**Endpoint**: `POST /jupyterlab-notifications-extension/ingest`

**Request Body** (application/json):

```json
{
  "message": "Your notification message",
  "type": "info",
  "autoClose": 5000,
  "immediate": true,
  "actions": [
    {
      "label": "Click here",
      "caption": "Additional info",
      "displayType": "accent"
    }
  ]
}
```

**Request Parameters**:

| Field       | Type           | Required | Default  | Description                                                                                                                            |
| ----------- | -------------- | -------- | -------- | -------------------------------------------------------------------------------------------------------------------------------------- |
| `message`   | string         | Yes      | -        | Notification text                                                                                                                      |
| `type`      | string         | No       | `"info"` | Visual style: `default`, `info`, `success`, `warning`, `error`, `in-progress`                                                          |
| `autoClose` | number/boolean | No       | `5000`   | Milliseconds before auto-dismiss. `false` = manual dismiss only. `0` = silent mode (notification center only, no toast)                |
| `immediate` | boolean        | No       | `false`  | Push instantly to connected clients via WebSocket instead of waiting for the next poll (see [Immediate Delivery](#immediate-delivery)) |
| `data`      | object         | No       | -        | Arbitrary JSON attached to the notification; every number in it must be finite                                                         |
| `actions`   | array          | No       | `[]`     | Action buttons (see below)                                                                                                             |

**Action Button Schema**:

| Field         | Type   | Required | Default     | Description                                                      |
| ------------- | ------ | -------- | ----------- | ---------------------------------------------------------------- |
| `label`       | string | Yes      | -           | Button text                                                      |
| `caption`     | string | No       | `""`        | Tooltip text                                                     |
| `displayType` | string | No       | `"default"` | Visual style: `default`, `accent`, `warn`, `link`                |
| `commandId`   | string | No       | -           | JupyterLab command ID to execute (e.g., `filebrowser:open-path`) |
| `args`        | object | No       | `{}`        | Arguments passed to the command                                  |

Note: Clicking any button dismisses the notification. If `commandId` is provided, the specified JupyterLab command executes before dismissal.

**Response** (200 OK):

```json
{
  "success": true,
  "notification_id": "notif_1762549476180_1"
}
```

**Error Responses**:

- `400 Bad Request` - invalid JSON, a body that is not a JSON object, a `message` that is missing, empty or not a string, an `actions` that is not a list, an action element that is not an object with a string `label`, or a number anywhere in the payload that is not finite (`NaN`, `Infinity`, or a literal that overflows to one)
- `403 Forbidden` - Missing or invalid authentication token
- `500 Internal Server Error` - Server-side processing error

## Usage Examples

### From JupyterLab Extensions

Send notifications programmatically from other extensions:

```javascript
// Basic notification
await app.commands.execute('jupyterlab-notifications:send', {
  message: 'Operation complete'
});

// Custom type and auto-close
await app.commands.execute('jupyterlab-notifications:send', {
  message: 'Build finished successfully',
  type: 'success',
  autoClose: 3000
});

// With dismiss button
await app.commands.execute('jupyterlab-notifications:send', {
  message: 'Error processing data',
  type: 'error',
  autoClose: false,
  actions: [{ label: 'Dismiss', displayType: 'default' }]
});

// Action button that executes a JupyterLab command
await app.commands.execute('jupyterlab-notifications:send', {
  message: 'Help Available!',
  type: 'info',
  autoClose: false,
  actions: [
    {
      label: 'Open Help',
      commandId: 'iframe:open',
      args: { path: 'local:///welcome.html' },
      displayType: 'accent'
    }
  ]
});
```

### CLI Tool

The `jupyterlab-notify` command is installed with the extension:

```bash
# Basic notification (auto-detects URL from running servers)
jupyterlab-notify -m "Deployment complete" -t success

# With explicit URL (e.g., JupyterHub)
jupyterlab-notify --url "http://127.0.0.1:8888/jupyterhub/user/alice" -m "Hello"

# Persistent warning (no auto-close)
jupyterlab-notify -m "System maintenance in 1 hour" -t warning --no-auto-close

# With dismiss button
jupyterlab-notify -m "Task complete" --action "Dismiss"

# Action button that executes a JupyterLab command
jupyterlab-notify -m "Help Available!" --action "Open Help" \
  --cmd "iframe:open" --command-args '{"path": "local:///welcome.html"}'

# Silent mode (notification center only, no toast)
jupyterlab-notify -m "Background task finished" --auto-close 0

# Immediate display (push now, don't wait for the next poll)
jupyterlab-notify -m "Deploy finished" --now
```

**URL auto-detection**: Queries `jupyter server list --json` to find running servers and constructs the URL from the record's own scheme, host and port, substituting a loopback address for a wildcard bind. When several are running and none matches `JUPYTERHUB_SERVICE_PREFIX`, it lists them and exits 2 rather than guess. Falls back to `JUPYTERHUB_SERVICE_PREFIX`, then to `http://127.0.0.1:$JUPYTER_PORT` (port 8888 when unset). An explicit `--url` that matches a listed record is re-addressed to that record's own host, so the host printed can differ from the host given: `--url http://localhost:8888` for a server bound to 0.0.0.0 is sent to `http://127.0.0.1:8888`. Any query string or fragment in `--url` is dropped, because the endpoint path is appended to the URL. Do not put a password in any `--url`: the `user:password@` part is dropped from a `--url` that names a host, because this tool authenticates by token only, but two malformed shapes keep it - one with no `//` at all, where the whole `user:password@host` is read as a path, and one whose password holds an unencoded `/`, where the host part ends at that slash.

**Authentication**: `JUPYTERLAB_NOTIFY_TOKEN` is this tool's own variable and is used for any target, including a remote one. Prefer it over `--token`, which puts the secret in argv where every local account can read `/proc/<pid>/cmdline`. The addressed server's own token is sent to the address its runtime record is reached at: 127.0.0.1 for a server bound to 0.0.0.0, and a host that might not be loopback if that server was started with `--ip <an address>`. The ambient `JUPYTERHUB_API_TOKEN` / `JPY_API_TOKEN` / `JUPYTER_TOKEN` belong to this host, not to the target, so they are sent only to a loopback target.

**`--now`**: Pushes the notification instantly to every open JupyterLab tab via WebSocket instead of waiting up to 30 seconds for the next poll (see [Immediate Delivery](#immediate-delivery)).

### cURL

```bash
# Localhost - a token is required, as on any other host
curl -X POST http://localhost:8888/jupyterlab-notifications-extension/ingest \
  -H "Content-Type: application/json" \
  -H "Authorization: token YOUR_JUPYTER_TOKEN" \
  -d '{"message": "Build completed", "type": "success"}'

# Localhost - warning that stays until dismissed
curl -X POST http://localhost:8888/jupyterlab-notifications-extension/ingest \
  -H "Content-Type: application/json" \
  -H "Authorization: token YOUR_JUPYTER_TOKEN" \
  -d '{"message": "System maintenance in 1 hour", "type": "warning", "autoClose": false}'

# Remote - requires authentication token
curl -X POST http://jupyterhub.example.com/user/alice/jupyterlab-notifications-extension/ingest \
  -H "Content-Type: application/json" \
  -H "Authorization: token YOUR_JUPYTER_TOKEN" \
  -d '{"message": "Deployment complete", "type": "info"}'

# Immediate display - push now instead of waiting for the next poll
curl -X POST http://localhost:8888/jupyterlab-notifications-extension/ingest \
  -H "Content-Type: application/json" \
  -H "Authorization: token YOUR_JUPYTER_TOKEN" \
  -d '{"message": "Deploy finished", "type": "success", "immediate": true}'
```

## Immediate Delivery

By default a notification waits up to 30 seconds for the frontend's next poll before it appears. Setting `immediate` (REST/cURL) or passing `--now` (CLI) pushes it instantly to every open JupyterLab tab over a WebSocket, so it displays the moment it is sent.

- **Transport**: the frontend keeps a WebSocket open to `/jupyterlab-notifications-extension/stream`; the server pushes flagged notifications to all connected clients
- **Push reaches every connected tab**: unlike the poll, the immediate push is delivered to all currently-open tabs at once
- **Poll is best-effort**: the poll queue is a single-consumer destructive drain - the first tab to poll empties it for all tabs - so a tab whose socket is down at push time is not guaranteed to receive that notification via the poll; the push is an accelerator over a best-effort baseline, not a durable per-client queue
- **Keepalive**: the socket uses ping/pong to survive proxy idle timeouts (works behind JupyterHub)
- **De-duplication**: the frontend tracks notification IDs (bounded), so a notification arriving via both the push and the poll is displayed only once
- **Reconnect**: the socket reconnects with capped exponential backoff, 5 seconds doubling to a 60-second ceiling, and keeps retrying for as long as the tab is open. There is no give-up: while the socket is down this tab competes for the destructive poll queue with every other tab and can miss a `--now` notification outright, so it warns once in the browser console and keeps trying

## Time-Ago Indicator

Each notification displays a relative timestamp (e.g., `just now`, `5m ago`, `2h ago`, `3d ago`) that updates every 10 seconds while the notification remains visible. Anything under a minute shows `just now`. The indicator appears below the message when no action buttons are present, or inline with the button bar when buttons exist. The notification center panel also shows time-ago for all listed notifications.

## Architecture

No per-recipient addressing: a notification is posted to one server, and the poll queue is taken by the first tab that polls.

**Flow**: External system POSTs to `/jupyterlab-notifications-extension/ingest` -> Server queues in memory -> Frontend polls `/jupyterlab-notifications-extension/notifications` every 30 seconds -> Displays via JupyterLab notification manager -> Clears queue after fetch. Notifications flagged `immediate` are additionally pushed over a WebSocket (`/jupyterlab-notifications-extension/stream`) for instant display, deduplicated against the poll by notification ID.

## Troubleshooting

**Frontend installed but not working**:

```bash
jupyter server extension list  # Verify server extension enabled
```

**Server extension enabled but frontend missing**:

```bash
jupyter labextension list  # Verify frontend extension installed
```

**Notifications not appearing**: Check browser console for polling errors or verify JupyterLab was restarted after installation.

## Uninstall

```bash
pip uninstall jupyterlab_notifications_extension
```

## Agent Skill

`.agents/skills/jupyterlab-notifications-extension/SKILL.md` tells an AI assistant how to drive the `jupyterlab-notify` CLI. It carries only the rules `--help` cannot state; the command reference stays in `jupyterlab-notify --help`.

The skill ships in the repository and in the wheel, which installs it at `<sys.prefix>/share/jupyter/agents/skills/jupyterlab-notifications-extension/SKILL.md`. No agent reads that directory, and a wheel cannot write into the home directory, so one of the two links below is what makes it readable.

After `pip install`, with the Python that runs the lab:

```bash
mkdir -p ~/.agents/skills && ln -sfn "$(python -c 'import sys; print(sys.prefix)')/share/jupyter/agents/skills/jupyterlab-notifications-extension" ~/.agents/skills/jupyterlab-notifications-extension
```

From a clone, into Claude Code:

```bash
ln -sfn "$PWD/.agents/skills/jupyterlab-notifications-extension" ~/.claude/skills/jupyterlab-notifications-extension
```

## Development

### Setup

Requires NodeJS to build the extension. Uses `jlpm` (JupyterLab's pinned yarn) for package management.

```bash
# Install in development mode
python -m venv .venv
source .venv/bin/activate
pip install --editable ".[dev,test]"

# Link extension with JupyterLab
jupyter labextension develop . --overwrite
jupyter server extension enable jupyterlab_notifications_extension

# Build TypeScript
jlpm build
```

### Development workflow

Run `jlpm watch` in one terminal to auto-rebuild on changes, and `jupyter lab` in another. Refresh browser after rebuilds to load changes.

```bash
jlpm watch           # Auto-rebuild on file changes
jupyter lab          # Run JupyterLab
```

### Cleanup

```bash
jupyter server extension disable jupyterlab_notifications_extension
pip uninstall jupyterlab_notifications_extension
# Remove symlink: find via `jupyter labextension list`
```

### Testing

**Python tests** (Pytest):

```bash
pip install -e ".[test]"
pytest -vv -r ap --cov jupyterlab_notifications_extension
```

**Frontend tests** (Jest):

```bash
jlpm test
```

**Integration tests** (Playwright/Galata): See [ui-tests/README.md](ui-tests/README.md)

### Packaging

See [RELEASE.md](RELEASE.md) for release procedures.
