mirror of
https://github.com/apache/superset.git
synced 2026-07-26 16:42:32 +00:00
Compare commits
43 Commits
test/chatb
...
fix/versio
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
0052909f10 | ||
|
|
898b3c498f | ||
|
|
81a4665813 | ||
|
|
b9dc9d722e | ||
|
|
fa41769a08 | ||
|
|
df21fe6571 | ||
|
|
12bef03f4a | ||
|
|
0b9764aed5 | ||
|
|
ac522ded1c | ||
|
|
c54990c861 | ||
|
|
3bbb35e8a3 | ||
|
|
a2a369cb5c | ||
|
|
9af6746dbe | ||
|
|
6abee0289b | ||
|
|
8c62f533d7 | ||
|
|
17d1a45bc9 | ||
|
|
6eaee211aa | ||
|
|
3e589436fa | ||
|
|
a9df2c7e5e | ||
|
|
8508af3201 | ||
|
|
49f3dbba73 | ||
|
|
616c243278 | ||
|
|
00dd31494d | ||
|
|
b97d3ef520 | ||
|
|
4d2b10d916 | ||
|
|
86fa5bb46f | ||
|
|
19c2b67d09 | ||
|
|
d2d46169bf | ||
|
|
1b8099811b | ||
|
|
242c27a974 | ||
|
|
24422c8311 | ||
|
|
1632b235ae | ||
|
|
093b43c7a5 | ||
|
|
4996d7c277 | ||
|
|
d26a7aac3d | ||
|
|
699e741c69 | ||
|
|
fc0245bdb0 | ||
|
|
7275116f4c | ||
|
|
88abd41c8b | ||
|
|
ddb647cd3a | ||
|
|
aba6ea536c | ||
|
|
ca8855dc03 | ||
|
|
052e567f77 |
4
.github/workflows/bashlib.sh
vendored
4
.github/workflows/bashlib.sh
vendored
@@ -20,10 +20,6 @@ set -e
|
||||
GITHUB_WORKSPACE=${GITHUB_WORKSPACE:-.}
|
||||
ASSETS_MANIFEST="$GITHUB_WORKSPACE/superset/static/assets/manifest.json"
|
||||
|
||||
# Rounded job start time, used to create a unique Cypress build id for
|
||||
# parallelization so we can manually rerun a job after 20 minutes
|
||||
NONCE=$(echo "$(date "+%Y%m%d%H%M") - ($(date +%M)%20)" | bc)
|
||||
|
||||
# Echo only when not in parallel mode
|
||||
say() {
|
||||
if [[ $(echo "$INPUT_PARALLEL" | tr '[:lower:]' '[:upper:]') != 'TRUE' ]]; then
|
||||
|
||||
895
CHATBOT_SIP.md
895
CHATBOT_SIP.md
@@ -1,895 +0,0 @@
|
||||
Chatbot extensions
|
||||
Author: Enzo Martellucci
|
||||
Team: Preset
|
||||
Status: Draft | Under Review | Completed
|
||||
Day: May, 2026
|
||||
|
||||
1. Introduction
|
||||
This SIP proposes a new extension point that enables third-party chatbot integrations to be embedded directly into the Superset user interface through the existing extension framework.
|
||||
The goal is to provide a stable, supported mechanism for chatbot providers to integrate with Superset without requiring direct access to internal application state, Redux stores, or implementation-specific frontend modules. Chatbot extensions should interact with Superset through the same extension-oriented principles already established for other extension surfaces, such as SQL Lab.
|
||||
The proposal focuses on three core concerns:
|
||||
• Defining how chatbot extensions are registered and rendered.
|
||||
• Defining how chatbot extensions receive contextual information about the currently active application surface.
|
||||
• Defining how administrators manage chatbot availability and select the active chatbot when multiple chatbot extensions are installed.
|
||||
This SIP intentionally does not prescribe any specific chatbot implementation, user experience, LLM provider, or backend architecture.
|
||||
1.1 Motivation
|
||||
AI-powered assistants are becoming a common way for users to interact with analytical applications. Superset should provide a standardized extension mechanism that allows community-built chatbot integrations to participate in the platform without depending on internal frontend implementation details.
|
||||
Today, chatbot integrations must either be embedded through custom application modifications or rely on unsupported access to internal application state. Both approaches create maintenance challenges and make integrations fragile when frontend architecture evolves.
|
||||
|
||||
This SIP introduces a stable extension contract that:
|
||||
• Enables chatbot integrations to be distributed as standard Superset extensions.
|
||||
• Preserves separation between host and extension responsibilities.
|
||||
• Allows chatbot implementations to access contextual information about the current page and entity being viewed.
|
||||
• Keeps authorization and permission enforcement aligned with existing Superset APIs.
|
||||
• Remains compatible with future frontend architecture changes.
|
||||
1.2 Goals
|
||||
The goals of this SIP are:
|
||||
Introduce a dedicated chatbot extension point within the Superset application shell.
|
||||
Provide chatbot extensions with host-managed, permission-aligned page context.
|
||||
Establish stable extension-facing APIs for dashboard, explore, dataset, and navigation context.
|
||||
Support deployment-wide administration of chatbot availability and selection.
|
||||
Maintain isolation between chatbot implementations and Superset internals.
|
||||
Preserve compatibility with future extension capabilities and AI-related initiatives.
|
||||
1.3 Out of Scope
|
||||
The following capabilities are explicitly out of scope for this SIP.
|
||||
Client Actions and Agentic UI Manipulation
|
||||
This SIP defines how chatbot extensions are mounted and how they receive context from the host application.
|
||||
It does not define how a chatbot performs actions within the user interface, such as:
|
||||
• Modifying chart configuration.
|
||||
• Updating dashboard layouts.
|
||||
• Editing SQL queries.
|
||||
• Triggering frontend workflows.
|
||||
These capabilities are deferred to the proposed Client Actions SIP.
|
||||
Chatbot User Experience
|
||||
The chatbot user interface remains entirely owned by the extension.
|
||||
This SIP does not prescribe:
|
||||
• Visual design.
|
||||
• Conversation experience.
|
||||
• Streaming behavior.
|
||||
• Message persistence.
|
||||
• Prompting strategy.
|
||||
• Accessibility implementation details.
|
||||
• Branding or styling.
|
||||
LLM and Backend Infrastructure
|
||||
The following concerns remain extension-specific:
|
||||
• Model providers.
|
||||
• MCP implementations.
|
||||
• Agent frameworks.
|
||||
• Tool execution systems.
|
||||
• Prompt orchestration.
|
||||
• Backend services.
|
||||
Superset acts only as the host application and context provider.
|
||||
|
||||
2. Requirements
|
||||
|
||||
2.1 Functional Requirements
|
||||
Registration and Rendering
|
||||
The platform must allow extensions to register chatbot providers through the standard extension system.
|
||||
The host must:
|
||||
• Support registration of chatbot extensions.
|
||||
• Render a chatbot UI contributed by an extension.
|
||||
• Maintain a single active chatbot instance at any given time.
|
||||
• Make the chatbot available across supported application surfaces.
|
||||
• Support fully custom chatbot user interfaces.
|
||||
|
||||
Context Sharing
|
||||
The platform must provide chatbot extensions with contextual information about the user's current application state.
|
||||
At minimum, the host must expose:
|
||||
• Current page type (`home`, `dashboard`, `explore`, `sqllab`, `dataset`, `other`).
|
||||
• Dashboard context.
|
||||
• Explore/chart context.
|
||||
• Dataset identity context.
|
||||
• SQL Lab context.
|
||||
• Navigation events.
|
||||
The chatbot must be notified of relevant context changes without polling.
|
||||
Examples include:
|
||||
• Route changes.
|
||||
• Dashboard changes.
|
||||
• Chart changes.
|
||||
• Dataset changes.
|
||||
• Title changes.
|
||||
• Filter changes.
|
||||
Host-Owned Context
|
||||
Context exposed to extensions must be computed by the host application.
|
||||
Extensions must not be required to:
|
||||
• Read Redux state.
|
||||
• Access internal application modules.
|
||||
• Depend on component-level implementation details.
|
||||
• Reconstruct semantic context from frontend internals.
|
||||
Instead, extensions consume stable namespace APIs provided by the host.
|
||||
Conversation State
|
||||
The conversation state remains entirely owned by the chatbot extension.
|
||||
This includes:
|
||||
• Message history.
|
||||
• Tool execution state.
|
||||
• Streaming buffers.
|
||||
• Conversation persistence.
|
||||
• Session management.
|
||||
The host is responsible only for exposing contextual information.
|
||||
2.2 Non-Functional Requirements
|
||||
Security and Authorization
|
||||
Context shared with chatbot extensions must remain aligned with Superset's existing authorization model.
|
||||
The host must not expose:
|
||||
• Entities the current user cannot access.
|
||||
• Metadata outside the user's permission scope.
|
||||
• Datasource-derived information unavailable through existing APIs.
|
||||
Authorization remains enforced by backend APIs. The extension-facing APIs defined by this SIP operate on data that has already been scoped to the current user.
|
||||
Stable Extension Contracts
|
||||
Extension-facing APIs must remain independent of frontend implementation details.
|
||||
Extensions should rely on documented namespace contracts rather than:
|
||||
• Redux slices.
|
||||
• Internal selectors.
|
||||
• Component state.
|
||||
• Routing implementation details.
|
||||
This allows frontend architecture to evolve without breaking extensions.
|
||||
Performance
|
||||
The architecture must minimize impact on existing application performance.
|
||||
In particular:
|
||||
• Context APIs must avoid unnecessary application re-renders.
|
||||
• Context change notifications must not rely on polling.
|
||||
• Chatbot integrations should not introduce additional work for unrelated surfaces.
|
||||
Fault Isolation
|
||||
Failures within chatbot extensions must not affect the stability of the host application.
|
||||
Errors originating from third-party chatbot implementations should be isolated to the chatbot mount boundary.
|
||||
Extensibility
|
||||
The architecture should support future:
|
||||
• Application surfaces.
|
||||
• AI-related capabilities.
|
||||
• Extension APIs.
|
||||
• Context providers.
|
||||
without requiring redesign of the chatbot extension model.
|
||||
Vendor Neutrality
|
||||
The architecture must remain independent of any specific:
|
||||
• LLM provider.
|
||||
• AI platform.
|
||||
• Agent framework.
|
||||
• Backend implementation.
|
||||
|
||||
3. Administration
|
||||
3.1 Overview
|
||||
Administrators can manage chatbot availability and select the active chatbot when multiple chatbot extensions are installed.
|
||||
Administration is exposed through the existing Extensions management interface.
|
||||
For chatbot extensions, administrators can:
|
||||
• Enable or disable individual chatbot extensions.
|
||||
• Select the default chatbot when multiple chatbot providers are available.
|
||||
Only one chatbot may be active at a time.
|
||||
3.2 Default Chatbot Selection
|
||||
Extensions that contribute a chatbot view participate in a deployment-wide chatbot selection process.
|
||||
The host discovers available chatbot candidates from the chatbot contribution location and allows administrators to designate a single active chatbot.
|
||||
|
||||
When multiple chatbot extensions are installed:
|
||||
Administrators select the preferred chatbot.
|
||||
The host resolves the active chatbot using the configured selection.
|
||||
Only the selected chatbot is rendered.
|
||||
Changes are applied dynamically without requiring a page reload.
|
||||
3.3 Scope of Administration
|
||||
The administration model introduced by this SIP is deployment-wide.
|
||||
Administrative settings answer the question:
|
||||
"Which chatbot integrations are available within this Superset deployment?"
|
||||
They do not answer:
|
||||
"Which chatbot integrations does a specific user prefer to use?"
|
||||
This distinction is intentional.
|
||||
Deployment administrators determine which integrations are available across the environment, while user-specific preferences remain a separate concern.
|
||||
3.4 Future User Preferences
|
||||
Per-user chatbot preferences are considered an important future capability but are intentionally out of scope for this SIP.
|
||||
This proposal does not introduce user-scoped extension availability.
|
||||
Instead, future user preferences should be layered on top of deployment availability using the following model:
|
||||
Effective Availability = Deployment Availability AND User Preference
|
||||
The recommended persistence layer for future user preferences is the Extension Storage API, which provides user-scoped extension storage and aligns with the architecture established by SIP-127 (User Preferences).
|
||||
This separation preserves a clear distinction between:
|
||||
• Deployment configuration.
|
||||
• User customization.
|
||||
and avoids introducing multiple ownership models for extension availability.
|
||||
Consequently, this SIP focuses exclusively on deployment-wide administration and active chatbot selection. 4. Proposed Extension Point
|
||||
4.1 Overview
|
||||
This SIP introduces a single extension point that allows chatbot providers to integrate directly into the Superset application shell.
|
||||
Extension Point
|
||||
Contribution Location
|
||||
Registration API
|
||||
Cardinality
|
||||
Chatbot Bubble
|
||||
superset.chatbot
|
||||
views.registerView()
|
||||
Singleton
|
||||
|
||||
The chatbot contribution point is application-wide and persists across supported Superset surfaces, including dashboards, Explore, SQL Lab, and dataset-related pages.
|
||||
Unlike most contribution locations, which allow multiple contributions to be rendered simultaneously, the chatbot location is intentionally exclusive and renders a single active provider.
|
||||
|
||||
4.2 Chatbot Contribution Location
|
||||
Contribution Area
|
||||
The contribution location introduced by this SIP is:
|
||||
superset.chatbot
|
||||
The host provides a fixed mount point within the application shell and renders the active chatbot provider at that location.
|
||||
The mount point persists across route changes, allowing chatbot conversations and UI state to remain available while users navigate between application surfaces.
|
||||
The chatbot extension contributes a single React component representing the entire chatbot experience.
|
||||
Manifest Support
|
||||
The current contribution manifest schema is focused on SQL Lab contribution locations and does not provide an application-shell-level contribution scope.
|
||||
To support chatbot integrations, the manifest schema must be extended with an application-level contribution scope capable of declaring:
|
||||
{
|
||||
"views": {
|
||||
"app": [
|
||||
{
|
||||
"location": "superset.chatbot"
|
||||
}
|
||||
]
|
||||
}
|
||||
}
|
||||
This is a schema-level change and requires updates to both:
|
||||
• Manifest validation.
|
||||
• Runtime registration infrastructure.
|
||||
The runtime registration API alone is not sufficient because chatbot contributions must also be discoverable through extension manifests.
|
||||
4.3 Singleton Rendering Model
|
||||
The chatbot location is intentionally exclusive.
|
||||
Only one chatbot may be active at a time.
|
||||
This differs from other contribution locations that allow multiple views to be rendered simultaneously.
|
||||
Motivation
|
||||
Chatbot interactions are inherently conversational and user-focused.
|
||||
Rendering multiple chatbot providers simultaneously would:
|
||||
• Create competing user experiences.
|
||||
• Introduce ambiguity regarding which chatbot should respond.
|
||||
• Increase UI complexity.
|
||||
• Reduce discoverability.
|
||||
For these reasons, chatbot rendering is treated as a deployment-level selection rather than a multi-provider composition model.
|
||||
Resolution Rules
|
||||
The host applies the following behavior:
|
||||
Installed Chatbots
|
||||
Behavior
|
||||
None
|
||||
No chatbot is rendered
|
||||
One
|
||||
The chatbot is rendered automatically
|
||||
Multiple
|
||||
The administrator-selected chatbot is rendered
|
||||
|
||||
The singleton policy is implemented entirely by the host.
|
||||
Extensions continue to register normally through the existing view registry.
|
||||
4.4 Provider Isolation
|
||||
A key architectural principle of this SIP is that extensions may discover registrations but may not invoke another extension's rendering logic.
|
||||
Public View Discovery
|
||||
The existing registry exposes:
|
||||
getViews(location);
|
||||
This API returns metadata describing registered views:
|
||||
interface View {
|
||||
id: string;
|
||||
name: string;
|
||||
description?: string;
|
||||
icon?: string;
|
||||
}
|
||||
The returned descriptors are intentionally passive metadata.
|
||||
They allow extensions and host components to:
|
||||
• Discover available contributions.
|
||||
• Display contribution information.
|
||||
• Populate administration interfaces.
|
||||
They do not allow rendering.
|
||||
Why Providers Are Not Exposed
|
||||
The view provider is executable rendering logic.
|
||||
If providers were exposed through the public registry:
|
||||
• Extensions could render another extension's UI.
|
||||
• Extensions could bypass host lifecycle management.
|
||||
• Extensions could circumvent fault-isolation boundaries.
|
||||
• Rendering ownership would become ambiguous.
|
||||
This would violate the separation between extension discovery and extension execution.
|
||||
For this reason:
|
||||
"Extensions may discover registered views, but only the host may render registered views."
|
||||
Host-Managed Resolution
|
||||
The host uses internal APIs to resolve the active chatbot provider.
|
||||
These APIs are not exposed through the public extension surface.
|
||||
Conceptually:
|
||||
const provider = getViewProvider("superset.chatbot", selectedId);
|
||||
The active chatbot is determined through a host-managed resolution policy:
|
||||
const chatbot = getActiveChatbot(adminSelectedId, enabledMap);
|
||||
This policy considers:
|
||||
• Enabled state.
|
||||
• Administrative selection.
|
||||
• Runtime settings.
|
||||
• Registration state.
|
||||
|
||||
before rendering any provider.
|
||||
As a result, chatbot selection is implemented as a host-side rendering policy rather than a new registration primitive.
|
||||
4.5 Chatbot Lifecycle
|
||||
Host Responsibilities
|
||||
The host is responsible for:
|
||||
• Providing the chatbot mount point.
|
||||
• Resolving the active chatbot provider.
|
||||
• Loading chatbot extensions.
|
||||
• Managing chatbot lifecycle integration.
|
||||
• Handling activation and deactivation.
|
||||
• Maintaining fault isolation boundaries.
|
||||
• Preserving chatbot availability across route changes.
|
||||
• Providing context APIs defined by this SIP.
|
||||
The host also provides fixed positioning and layering behavior to ensure chatbot visibility remains consistent throughout the application.
|
||||
Fault Isolation
|
||||
Chatbot providers execute within a host-managed boundary.
|
||||
Failures originating from a chatbot extension must not affect the rest of the application.
|
||||
Examples include:
|
||||
• Module Federation loading failures.
|
||||
• Runtime exceptions.
|
||||
• Provider initialization errors.
|
||||
If a chatbot fails to load, the host logs the failure, surfaces an appropriate notification, and continues operating normally.
|
||||
The application shell remains functional even when the chatbot provider is unavailable.
|
||||
|
||||
4.6 Extension Responsibilities
|
||||
The registered chatbot component owns the complete chatbot experience.
|
||||
The extension is responsible for:
|
||||
User Interface
|
||||
• Collapsed bubble UI.
|
||||
• Expanded panel UI.
|
||||
• Branding.
|
||||
• Icons and badges.
|
||||
• Layout.
|
||||
• Responsiveness.
|
||||
Interaction Model
|
||||
• Open and close behavior.
|
||||
• Keyboard shortcuts.
|
||||
• Focus management.
|
||||
• Accessibility behavior.
|
||||
• Conversation navigation.
|
||||
Conversation Runtime
|
||||
• Message history.
|
||||
• Streaming state.
|
||||
• Tool execution.
|
||||
• Persistence.
|
||||
• Session management.
|
||||
Backend Integration
|
||||
• LLM communication.
|
||||
• MCP integration.
|
||||
• Agent orchestration.
|
||||
• Tool invocation.
|
||||
The host does not manage any chatbot-specific runtime state.
|
||||
|
||||
4.7 Registration Example
|
||||
Chatbot extensions register a single provider through the existing view registration API.
|
||||
import { views, type ExtensionContext } from '@apache-superset/core';
|
||||
import { ChatbotApp } from './ChatbotApp';
|
||||
|
||||
export function activate(context: ExtensionContext) {
|
||||
const disposable = views.registerView(
|
||||
{
|
||||
id: 'acme.chatbot',
|
||||
name: 'Acme Chatbot',
|
||||
icon: 'Bubble',
|
||||
},
|
||||
'superset.chatbot',
|
||||
() => <ChatbotApp />,
|
||||
);
|
||||
context.subscriptions.push(disposable);
|
||||
}
|
||||
The registration process remains consistent with existing extension contribution patterns.
|
||||
The only difference is that the host applies singleton resolution before selecting the provider to render.
|
||||
|
||||
4.8 Chatbot Descriptor Metadata
|
||||
Chatbot registrations may include an optional icon descriptor.
|
||||
{
|
||||
id: 'acme.chatbot',
|
||||
name: 'Acme Chatbot',
|
||||
icon: 'Bubble',
|
||||
}
|
||||
This metadata is used by:
|
||||
• Extension administration interfaces.
|
||||
• Chatbot selection interfaces.
|
||||
• Extension discovery surfaces.
|
||||
Design Decision
|
||||
The icon descriptor is treated as static registration metadata.
|
||||
Runtime UI state such as:
|
||||
• Notification indicators.
|
||||
• Unread counts.
|
||||
• Loading states.
|
||||
• Thinking indicators.
|
||||
belongs to the chatbot component itself rather than the registration descriptor.
|
||||
This keeps the registry simple while allowing chatbot implementations complete control over their user experience.
|
||||
If future requirements emerge for host-visible dynamic icon updates, that capability can be introduced independently without expanding the registration model defined by this SIP. 5. Context and Namespace Model
|
||||
5.1 Overview
|
||||
Chatbot extensions require access to contextual information about the user's current activity within Superset. This SIP introduces a namespace-based context model that allows extensions to consume stable, host-managed APIs rather than depending on internal frontend implementation details.
|
||||
The host exposes context through a set of surface-specific namespaces. Each namespace owns the context for a particular application surface and provides:
|
||||
• Synchronous state getters.
|
||||
• Event-based change notifications.
|
||||
• Stable extension-facing contracts.
|
||||
• Context aligned with the current user's authorized application view.
|
||||
Extensions consume these namespaces and compose them into higher-level context models tailored to their own use cases.
|
||||
5.2 Design Principles
|
||||
The namespace model is guided by the following principles.
|
||||
Stable Extension Contracts
|
||||
Extensions must depend on documented APIs rather than frontend implementation details.
|
||||
In particular, extensions must not depend on:
|
||||
• Redux slices.
|
||||
• Store shape.
|
||||
• Selectors.
|
||||
• Component-local state.
|
||||
• Routing implementation details.
|
||||
This allows Superset to evolve its frontend architecture without breaking extension integrations.
|
||||
Host-Owned Context Normalization
|
||||
The host is responsible for transforming application state into semantic extension-facing contracts.
|
||||
Extensions consume normalized context rather than deriving it from raw frontend state.
|
||||
Backend-Authorized Context
|
||||
Authorization remains a backend responsibility.
|
||||
Namespaces expose context that has already been scoped by backend APIs according to the current user's permissions.
|
||||
Namespaces do not implement authorization logic themselves and should not be considered security boundaries.
|
||||
Event-Driven Updates
|
||||
Context changes are propagated through events rather than polling.
|
||||
Extensions can subscribe to context updates and react immediately when relevant application state changes.
|
||||
5.3 Available Namespaces
|
||||
The following namespaces are available to chatbot extensions.
|
||||
Namespace
|
||||
Status
|
||||
Purpose
|
||||
sqlLab
|
||||
Existing
|
||||
SQL Lab context and events
|
||||
authentication
|
||||
Existing
|
||||
Current user and session context
|
||||
commands
|
||||
Existing
|
||||
Host actions and commands
|
||||
dashboard
|
||||
New
|
||||
Dashboard context
|
||||
explore
|
||||
New
|
||||
Explore/chart context
|
||||
dataset
|
||||
New
|
||||
Dataset identity context
|
||||
navigation
|
||||
New
|
||||
Routing and page context
|
||||
|
||||
The new namespaces introduced by this SIP follow the same high-level contract pattern established by the existing sqlLab namespace.
|
||||
5.4 Namespace API Shape
|
||||
Each namespace follows a common structure:
|
||||
const current = namespace.getCurrent();
|
||||
const disposable = namespace.onDidChange((next) => {
|
||||
// react to updates
|
||||
});
|
||||
The exact contracts differ by surface, but every namespace provides:
|
||||
• One or more synchronous getters.
|
||||
• Event-based change notifications.
|
||||
• Stable semantic contracts.
|
||||
This pattern allows extensions to remain synchronized with application state without polling.
|
||||
|
||||
5.5 Dashboard Namespace
|
||||
The dashboard namespace provides contextual information about the currently active dashboard.
|
||||
API
|
||||
dashboard.getCurrentDashboard();
|
||||
Contract
|
||||
interface DashboardContext {
|
||||
dashboardId: number;
|
||||
title: string;
|
||||
filters: FilterValue[];
|
||||
charts: ChartSummary[];
|
||||
}
|
||||
|
||||
interface ChartSummary {
|
||||
chartId: number;
|
||||
chartName: string;
|
||||
vizType: string;
|
||||
datasourceId: number | null;
|
||||
datasourceName: string | null;
|
||||
isVisible: boolean;}
|
||||
The context includes:
|
||||
• Dashboard identity.
|
||||
• Active filter state.
|
||||
• Dashboard charts.
|
||||
• Per-chart visibility information.
|
||||
Returning all charts while exposing visibility allows chatbot implementations to answer both:
|
||||
• "Which charts are currently visible?"
|
||||
• "Find the chart named Revenue by Region."
|
||||
without requiring additional lookups.
|
||||
Normalization Requirements
|
||||
The namespace must expose semantic dashboard context rather than raw application state.
|
||||
For example:
|
||||
dashboard.getCurrentDashboard();
|
||||
returns a normalized contract rather than Redux slices or internal entities.
|
||||
This abstraction layer preserves compatibility as frontend implementation details evolve.
|
||||
Page-Type Guarding
|
||||
The getter returns undefined when the current page is not a dashboard.
|
||||
Conceptually:
|
||||
if (navigation.getPageType() !== "dashboard") {
|
||||
return undefined;
|
||||
}
|
||||
This prevents stale dashboard state from leaking across application surfaces.
|
||||
5.6 Explore Namespace
|
||||
The explore namespace provides context for the currently active Explore session.
|
||||
API
|
||||
explore.getCurrentChart();
|
||||
Contract
|
||||
interface ChartContext {
|
||||
chartId: number | null;
|
||||
chartName: string | null;
|
||||
datasourceId: number | null;
|
||||
datasourceName: string | null;
|
||||
vizType: string;
|
||||
}
|
||||
|
||||
The namespace exposes:
|
||||
• Chart identity. `chartId` and `chartName` are null for a new, unsaved chart that has not yet been persisted.
|
||||
• Saved chart metadata (name, datasource, viz type)
|
||||
• Current Explore context: `vizType` reflects the type currently selected in the editor, so the value tracks the live session rather than only the last saved state.
|
||||
The contract is intentionally focused on chart-specific information relevant to chatbot integrations.
|
||||
Reflecting the live editing session — rather than reconstructing chart state from
|
||||
the route alone — is the primary reason this SIP exposes frontend context
|
||||
directly (see §6.2, Option C).
|
||||
|
||||
Page-Type Guarding
|
||||
The getter returns undefined when the current page is not an Explore surface.
|
||||
Conceptually:
|
||||
if (navigation.getPageType() !== "explore") {
|
||||
return undefined;
|
||||
}
|
||||
This ensures the namespace reflects only active Explore context.
|
||||
5.7 Dataset Namespace
|
||||
The dataset namespace exposes the dataset currently being viewed or edited.
|
||||
API
|
||||
dataset.getCurrentDataset();
|
||||
Contract
|
||||
interface DatasetContext {
|
||||
datasetId: number;
|
||||
datasetName: string;
|
||||
schema: string | null;
|
||||
catalog: string | null;
|
||||
databaseName: string | null;
|
||||
isVirtual: boolean;}
|
||||
This contract is intentionally identity-focused.
|
||||
It answers:
|
||||
• Which dataset is currently in focus?
|
||||
• Is the dataset virtual or physical?
|
||||
• Which database and schema does it belong to?
|
||||
It does not expose:
|
||||
• Column definitions.
|
||||
• Lineage information.
|
||||
• Dataset dependencies.
|
||||
Those concerns are expected to be resolved by backend services using the dataset identifier.
|
||||
Producer-Backed Context
|
||||
Unlike dashboard and explore namespaces, dataset pages do not currently expose a shared source of truth suitable for namespace consumption.
|
||||
For this reason, dataset context is published by dataset pages through a host-managed producer mechanism.
|
||||
Dataset pages publish the active dataset as it loads, and:
|
||||
dataset.getCurrentDataset();
|
||||
returns the most recently published value.
|
||||
Until dataset information has been published, the getter returns:
|
||||
undefined;
|
||||
This design keeps the public contract stable without requiring the introduction of a dedicated Redux slice.
|
||||
|
||||
Example Use Cases
|
||||
The dataset namespace enables chatbot workflows such as:
|
||||
• Explain this dataset.
|
||||
• Summarize this dataset's purpose.
|
||||
• Show lineage for this dataset.
|
||||
• Which charts depend on this dataset?
|
||||
The namespace provides the identity required to perform those lookups while avoiding duplication of backend metadata.
|
||||
5.8 Navigation Namespace
|
||||
The navigation namespace provides routing-related context.
|
||||
API
|
||||
navigation.getPageType();
|
||||
Events
|
||||
navigation.onDidChangePage(...)
|
||||
|
||||
Contract
|
||||
type PageType =
|
||||
| "home"
|
||||
| "dashboard"
|
||||
| "explore"
|
||||
| "sqllab"
|
||||
| "dataset"
|
||||
| "other";
|
||||
The namespace answers a single question:
|
||||
"Which application surface is currently active?"
|
||||
It intentionally does not expose entity-specific information.
|
||||
Entity context remains owned by the corresponding surface namespace.
|
||||
Examples:
|
||||
dashboard.getCurrentDashboard();
|
||||
explore.getCurrentChart();
|
||||
dataset.getCurrentDataset();
|
||||
This separation preserves clear ownership boundaries and prevents duplication across namespaces.
|
||||
|
||||
5.9 Context Composition
|
||||
This SIP intentionally does not introduce a host-owned aggregate context object.
|
||||
Instead, extensions compose the context they require from individual namespaces.
|
||||
For example:
|
||||
const pageContext = {
|
||||
pageType: navigation.getPageType(),
|
||||
dashboard: dashboard.getCurrentDashboard(),
|
||||
chart: explore.getCurrentChart(),
|
||||
dataset: dataset.getCurrentDataset(),
|
||||
sqlLab: sqlLab.getCurrentTab(),
|
||||
};
|
||||
The extension assembles a higher-level context tailored to its own requirements.
|
||||
The host remains responsible for:
|
||||
• Context ownership.
|
||||
• Context normalization.
|
||||
• Authorization alignment.
|
||||
The extension remains responsible for:
|
||||
• Context composition.
|
||||
• Prompt construction.
|
||||
• Application-specific interpretation.
|
||||
This separation avoids introducing a centralized context abstraction while allowing new surfaces to be added incrementally over time.
|
||||
|
||||
5.10 Compatibility and Evolution
|
||||
Namespace contracts are part of the public Superset extension API surface.
|
||||
Breaking changes require standard compatibility and deprecation processes.
|
||||
Extensions should depend only on documented namespace contracts and must not rely on implementation details behind those contracts.
|
||||
As new application surfaces become extension-aware, additional namespaces may be introduced without affecting existing integrations.
|
||||
This additive model allows the extension ecosystem to evolve while preserving backward compatibility.
|
||||
|
||||
6. Design Decisions
|
||||
This section consolidates the key architectural decisions made by this SIP and summarizes the alternatives that were evaluated.
|
||||
The goal is to capture the rationale behind the extension model so that future contributors can understand not only what was selected, but why alternative approaches were rejected.
|
||||
6.1 Decision Summary
|
||||
Decision
|
||||
Topic
|
||||
Selected Approach
|
||||
D1
|
||||
Page Context Model
|
||||
Extension-composed context from host-provided namespaces
|
||||
D2
|
||||
Chatbot Resolution
|
||||
Host-managed singleton resolution
|
||||
D3
|
||||
Descriptor Metadata
|
||||
Static icon metadata
|
||||
D4
|
||||
Administration Scope
|
||||
Deployment-wide administration
|
||||
D5
|
||||
Per-Page Visibility
|
||||
Deferred - open question, see §8
|
||||
D6
|
||||
Generalized Floating Slots
|
||||
Deferred - open question, see §8
|
||||
|
||||
6.2 D1 — Page Context Model
|
||||
A central design question is how chatbot extensions obtain contextual information about the currently active application surface.
|
||||
Three approaches were considered.
|
||||
Option A — Host-Owned Aggregate Context
|
||||
The host exposes a single API:
|
||||
context.getPageContext();
|
||||
which returns a fully assembled context object containing dashboard, chart, dataset, navigation, and SQL Lab information.
|
||||
Rejected Because
|
||||
• The host becomes responsible for understanding every application surface.
|
||||
• The aggregate contract grows whenever a new surface is introduced.
|
||||
• Changes in any surface can trigger unnecessary recomputation.
|
||||
• The host becomes coupled to a single canonical context model.
|
||||
• Ownership boundaries become unclear over time.
|
||||
Option B — Surface Namespaces Composed by Extensions (Selected)
|
||||
The host exposes independent namespaces:
|
||||
• dashboard
|
||||
• explore
|
||||
• dataset
|
||||
• navigation
|
||||
• sqlLab
|
||||
Extensions compose these primitives into their own application-specific context.
|
||||
Advantages
|
||||
• Clear ownership boundaries.
|
||||
• Independent evolution of namespaces.
|
||||
• Additive extensibility.
|
||||
• Reduced coupling between surfaces.
|
||||
• Extensions subscribe only to the context they require.
|
||||
Option C — Route-Only Context
|
||||
The host exposes only routing information.
|
||||
Chatbot providers independently reconstruct context through APIs or backend services.
|
||||
Rejected Because
|
||||
This approach cannot reliably represent transient frontend state.
|
||||
Examples include:
|
||||
• Unsaved chart edits.
|
||||
• Temporary dashboard filters.
|
||||
• Active dashboard tabs.
|
||||
• SQL editor state.
|
||||
• Draft configuration changes.
|
||||
As a result, chatbot context would frequently drift from what the user is actually viewing.
|
||||
Decision
|
||||
Option B is selected.
|
||||
The host owns context normalization while extensions own context composition.
|
||||
This preserves separation of concerns, minimizes coupling, and provides a stable foundation for future extension capabilities.
|
||||
6.3 D2 — Singleton Chatbot Resolution
|
||||
When multiple chatbot extensions are installed, the host must determine which chatbot is rendered.
|
||||
This decision shapes both the rendering model and the extension isolation model.
|
||||
Option A — Expose Providers Through getViews()
|
||||
Allow:
|
||||
getViews(location);
|
||||
to return both metadata and rendering providers.
|
||||
Rejected Because
|
||||
Rendering providers are executable logic.
|
||||
Exposing providers would allow one extension to:
|
||||
• Render another extension.
|
||||
• Bypass host lifecycle management.
|
||||
• Circumvent fault isolation.
|
||||
• Assume ownership of another extension's UI.
|
||||
This violates a deliberate separation between extension discovery and extension execution.
|
||||
Option B — Host-Managed Provider Resolution (Selected)
|
||||
The host exposes only metadata publicly while retaining provider resolution internally.
|
||||
Conceptually:
|
||||
const provider = getViewProvider("superset.chatbot", selectedId);
|
||||
Chatbot selection is handled through a host-managed policy:
|
||||
const chatbot = getActiveChatbot(adminSelectedId, enabledMap);
|
||||
Advantages
|
||||
• Preserves extension isolation.
|
||||
• Preserves host ownership of rendering.
|
||||
• Supports administrative selection.
|
||||
• Supports enablement checks.
|
||||
• Supports future policy evolution.
|
||||
Option C — Reuse resolveView()
|
||||
Use the existing rendering helper:
|
||||
resolveView(id);
|
||||
to render chatbot providers.
|
||||
Rejected Because
|
||||
resolveView() assumes the caller already knows which view should be rendered.
|
||||
It does not account for:
|
||||
• Administrative selection.
|
||||
• Enablement state.
|
||||
• Settings synchronization.
|
||||
• Chatbot-specific resolution policy.
|
||||
Decision
|
||||
Option B is selected.
|
||||
The host owns chatbot selection and rendering.
|
||||
The registry remains a discovery mechanism rather than a rendering mechanism.
|
||||
Architectural Principle
|
||||
A core principle established by this SIP is:
|
||||
"Extensions may discover registered views, but only the host may render registered views."
|
||||
This preserves extension isolation and prevents cross-extension rendering dependencies.
|
||||
6.4 D3 — Descriptor Metadata Ownership
|
||||
Chatbot registrations may include metadata used by administrative and discovery interfaces.
|
||||
A key question is whether descriptor metadata should be static or runtime-updatable.
|
||||
|
||||
Option A — Static Descriptor Metadata (Selected)
|
||||
Metadata is defined at registration time and remains unchanged for the lifetime of the registration.
|
||||
Example:
|
||||
{
|
||||
id: 'acme.chatbot',
|
||||
name: 'Acme Chatbot',
|
||||
icon: 'Bubble',
|
||||
}
|
||||
Advantages
|
||||
• Simpler registry implementation.
|
||||
• Clear ownership model.
|
||||
• Consistent administration UI.
|
||||
• No registry update lifecycle.
|
||||
Option B — Runtime-Updatable Metadata
|
||||
Extensions can update descriptor metadata after registration.
|
||||
Examples:
|
||||
• Notification badges.
|
||||
• Thinking indicators.
|
||||
• Dynamic branding.
|
||||
Rejected Because
|
||||
These states belong to the chatbot user interface rather than the registration descriptor.
|
||||
Supporting dynamic metadata would:
|
||||
• Increase registry complexity.
|
||||
• Introduce update synchronization concerns.
|
||||
• Provide limited benefit for current consumers.
|
||||
Decision
|
||||
Option A is selected.
|
||||
Descriptor metadata remains static.
|
||||
Dynamic UI state remains the responsibility of the chatbot component.
|
||||
Future requirements for dynamic metadata can be addressed independently if needed.
|
||||
6.5 D4 — Administration Scope
|
||||
This SIP introduces deployment-wide chatbot administration.
|
||||
A key question is whether availability should be deployment-scoped or user-scoped.
|
||||
Option A — Deployment-Wide Administration (Selected)
|
||||
Administrators manage:
|
||||
• Extension availability.
|
||||
• Default chatbot selection.
|
||||
These settings apply to the entire deployment.
|
||||
Advantages
|
||||
• Clear administrative ownership.
|
||||
• Simple operational model.
|
||||
• Consistent with existing extension administration patterns.
|
||||
• Avoids introducing multiple configuration layers.
|
||||
Option B — User-Scoped Availability
|
||||
Availability and chatbot selection become user-specific settings.
|
||||
Rejected Because
|
||||
Administrative availability and user preference represent different concerns.
|
||||
Administrators answer:
|
||||
"Which integrations are available in this deployment?"
|
||||
Users answer:
|
||||
"Which available integrations do I prefer?"
|
||||
Combining these concerns into a single model creates unclear ownership and duplicated configuration responsibilities.
|
||||
|
||||
Decision
|
||||
Option A is selected.
|
||||
This SIP introduces only deployment-wide administration.
|
||||
Future user preferences should be layered on top using the following model:
|
||||
Effective Availability = Deployment Availability AND User Preference
|
||||
The recommended persistence mechanism for user-specific preferences is the Extension Storage API.
|
||||
This approach aligns with SIP-127 and preserves a clear separation between administrative configuration and user customization.
|
||||
|
||||
7. Risks and Future Considerations
|
||||
The selected architecture introduces several tradeoffs.
|
||||
Namespace Maintenance
|
||||
As additional application surfaces become extension-aware, new namespaces may be required.
|
||||
This increases the maintenance burden of the extension API surface.
|
||||
Contract Evolution
|
||||
Namespace contracts are intended to be stable.
|
||||
Over time, extensions may require additional context that is not initially exposed.
|
||||
Future additions must preserve compatibility and avoid leaking implementation details.
|
||||
Context Growth
|
||||
Dashboard and chart context may become increasingly rich over time.
|
||||
Care must be taken to ensure context APIs remain focused and do not evolve into large aggregate objects.
|
||||
Extension Expectations
|
||||
Chatbot vendors may request direct access to internal application state for convenience.
|
||||
This SIP intentionally rejects that approach in favor of stable semantic contracts.
|
||||
Maintaining that boundary may require additional namespace evolution over time. 8. Open Questions
|
||||
D5 — Per-Page Visibility
|
||||
Should chatbot extensions be able to declare page visibility constraints?
|
||||
Two approaches remain possible.
|
||||
Extension-Controlled Visibility
|
||||
Extensions observe:
|
||||
navigation.onDidChangePage(...)
|
||||
and decide whether to render themselves.
|
||||
Host-Enforced Visibility
|
||||
Extensions declare supported page types through manifest metadata and the host enforces visibility.
|
||||
Recommendation
|
||||
Defer this decision.
|
||||
The current architecture already supports extension-controlled visibility without requiring additional platform capabilities.
|
||||
|
||||
D6 — Generalized Floating Contribution Areas
|
||||
The current proposal introduces a chatbot-specific contribution location:
|
||||
superset.chatbot
|
||||
A future question is whether this should evolve into a more generic floating-widget framework.
|
||||
Examples might include:
|
||||
• Chatbots.
|
||||
• Guided tours.
|
||||
• Notification centers.
|
||||
• Productivity assistants.
|
||||
Recommendation
|
||||
Keep the contribution area chatbot-specific.
|
||||
If broader floating-widget requirements emerge, introduce a dedicated abstraction rather than expanding the scope of this SIP.
|
||||
|
||||
9. Related Documents
|
||||
Contribution types
|
||||
Client actions
|
||||
|
||||
The following proposals are related to this SIP.
|
||||
Extension Storage API
|
||||
Add storage API for extensions (#39171)
|
||||
Introduces namespace-isolated storage for extensions with support for:
|
||||
• Local storage.
|
||||
• Session storage.
|
||||
• Ephemeral server storage.
|
||||
• Persistent database-backed storage.
|
||||
This proposal is complementary to the administration model defined by this SIP and is the recommended foundation for future user-specific extension preferences.
|
||||
|
||||
SIP-127 — User Preferences
|
||||
[SIP-127] User Preferences (#28047)
|
||||
Establishes the per-user preference model used by Superset core.
|
||||
The Extension Storage API serves as the extension-scoped equivalent of this pattern and provides the recommended approach for future user-specific chatbot preferences. 10. Migration Plan
|
||||
Base branch enxdev/chat-prototype
|
||||
Branch for testing test/chatbot-local
|
||||
The following capabilities are required to fully realize this SIP.
|
||||
Core Platform Changes
|
||||
Implemented
|
||||
• superset.chatbot contribution location.
|
||||
• Host-side chatbot resolution.
|
||||
• Administration UI for chatbot selection.
|
||||
• Dashboard namespace.
|
||||
• Explore namespace.
|
||||
• Navigation namespace.
|
||||
• Runtime settings synchronization.
|
||||
Pending
|
||||
• Dataset namespace implementation.
|
||||
• Dashboard chart visibility context.
|
||||
• Permission-scoped dashboard context endpoint.
|
||||
• Manifest support for application-level contribution scopes.
|
||||
• Optional descriptor icon support.
|
||||
|
||||
11. Implementation Phases
|
||||
Phase 1 — Chatbot Mount Point
|
||||
• Chatbot contribution location.
|
||||
• Host-side rendering.
|
||||
• Lifecycle management.
|
||||
• Fault isolation.
|
||||
Status: Complete
|
||||
Phase 2 — Administration
|
||||
• Enable/disable support.
|
||||
• Default chatbot selection.
|
||||
• Runtime synchronization.
|
||||
Status: Complete
|
||||
Phase 3 — Context APIs
|
||||
• Dashboard namespace.
|
||||
• Explore namespace.
|
||||
• Navigation namespace.
|
||||
• Dataset namespace.
|
||||
Status: Partially Complete
|
||||
Remaining work:
|
||||
• Dataset namespace.
|
||||
• Dashboard chart visibility context.
|
||||
• Dashboard context endpoint.
|
||||
Phase 4 — Client Actions
|
||||
Client actions and agentic UI interactions remain outside the scope of this SIP and are expected to be addressed through a separate proposal.
|
||||
@@ -109,7 +109,7 @@ If yes, it is in scope. If no, it is out of scope. The lists below apply that te
|
||||
- Any action an Admin role can perform through documented configuration, API, or UI. The Admin role is a trusted operational principal by policy. Per MITRE CNA Operational Rules 4.1, a qualifying vulnerability must violate a security policy; behavior within a documented trust boundary does not.
|
||||
- Deployment or operator decisions: the values of secrets and tokens, whether internal networks are reachable from the server, which database connectors or cache backends are enabled, which feature flags are set, where notifications are delivered, and which third-party plugins are loaded.
|
||||
- Compromise, modification, or malicious control of trusted backend infrastructure. Apache Superset assumes the integrity of its metastore, cache backends (for example Redis or Memcached), message brokers, secret stores, and other operator-managed infrastructure. Findings that require an attacker to read from, write to, or otherwise tamper with these systems, including injecting malicious state, serialized objects, cache entries, task metadata, configuration, or database records, are post-compromise scenarios and do not constitute vulnerabilities in Apache Superset itself. A finding remains in scope only if an unprivileged user can cause such modification through a vulnerability in Apache Superset.
|
||||
- Code paths whose intended purpose is example data, demos, fixtures, local development, or documentation, rather than the production runtime.
|
||||
- The continued presence of expired key-value or metastore-cache entries that have not yet been deleted from the metadata database. Such entries are excluded from reads once expired, are purged opportunistically on write, and are removed in bulk by the scheduled `prune_key_value` maintenance task; their lingering until purged is an eventual-cleanup property, not a security boundary, and does not constitute a vulnerability.
|
||||
- How a downstream application (spreadsheet program, email client, browser handling user-downloaded files) interprets output Apache Superset produced for it.
|
||||
- Findings without a reproducible proof of concept against a supported release. The burden of demonstrating exploitability rests with the reporter; findings closed for lack of a proof of concept may be refiled if one is later produced.
|
||||
- Brute force, rate limiting, denial of service, or resource exhaustion that does not bypass a documented control.
|
||||
|
||||
322
TICKETS.md
322
TICKETS.md
@@ -1,322 +0,0 @@
|
||||
# Chatbot Extensions — Tickets
|
||||
|
||||
Lightweight, pre-implementation tickets. Each says what to build and where the
|
||||
boundaries are; it does not prescribe the final code. Stack order (bottom → top):
|
||||
contribution point → frontend API mount → eager loading → admin UI → backend
|
||||
settings/permissions → context sharing → import/delete.
|
||||
|
||||
---
|
||||
|
||||
## 1. Define the contribution point
|
||||
|
||||
**Goal:** Introduce the `superset.chatbot` contribution area and the host plumbing
|
||||
needed to mount a single chatbot at the application-shell level, persistent across
|
||||
routes. This is the keystone everything else builds on.
|
||||
|
||||
**Build:**
|
||||
|
||||
- Register `superset.chatbot` as a recognized contribution location in the view
|
||||
registry.
|
||||
- Add an app-shell / app-root contribution scope to the extension manifest schema
|
||||
so the location can be declared in `extension.json` (the current schema is
|
||||
SQL-Lab-only). Teach both manifest validation and runtime registration about it.
|
||||
- Provide an exclusive-location resolver that selects exactly one renderable
|
||||
chatbot for the slot, with a deterministic first-to-register fallback and a seam
|
||||
for an externally supplied "active chatbot id" (so admin/runtime policy can plug
|
||||
in later without touching the resolver).
|
||||
- Host-managed mount layout: fixed bottom-right, 24px margin, z-index above content
|
||||
and toasts, below modals.
|
||||
|
||||
**Out of scope:** fault isolation, admin selection UI, the lifecycle/teardown
|
||||
contract, eager loading, streaming, context namespaces, authoring docs.
|
||||
|
||||
**Depends on:** nothing — this unblocks the rest.
|
||||
|
||||
**Done when:** an extension can register at `superset.chatbot` and render at the
|
||||
app shell across routes; the resolver returns one provider (admin-id seam +
|
||||
first-to-register fallback); unregistering removes the mount cleanly with no
|
||||
duplicate bubbles.
|
||||
|
||||
Base branch: `enxdev/chat-prototype`
|
||||
|
||||
**External Links:** https://github.com/apache/superset/pull/40439
|
||||
|
||||
---
|
||||
|
||||
## 2. Host resolution & mount (frontend API entry point)
|
||||
|
||||
**Goal:** Turn a registered `superset.chatbot` view into a rendered, fault-isolated
|
||||
bubble — the host-internal provider accessor, the selection policy, and the
|
||||
fixed-position mount.
|
||||
|
||||
**Build:**
|
||||
|
||||
- Host-internal accessors on the views registry: `getViewProvider(location, id)`
|
||||
and `getRegisteredViewIds(location)`. Keep the public `getViews` descriptor-only —
|
||||
do not expose providers on the public surface.
|
||||
- A registry change subscription so a mount can re-resolve without polling (fired
|
||||
on register/unregister).
|
||||
- The `getActiveChatbot(adminSelectedId?, enabledMap?)` resolver implementing the
|
||||
selection policy: empty → none; drop disabled ids; admin-selected-and-enabled
|
||||
wins; else first enabled in registration order.
|
||||
- A `ChatbotMount` component at the app shell that renders the active provider
|
||||
inside the host `ErrorBoundary`, re-resolves on registry change, and renders
|
||||
nothing when no chatbot is active.
|
||||
|
||||
**Out of scope:** the contribution location itself (#40439); eager-loading the
|
||||
bundle (#40441); the settings endpoint (#40443, consumed here with silent
|
||||
fallback); admin UI; the lifecycle/teardown contract.
|
||||
|
||||
**Depends on:** #40439 (imports `CHATBOT_LOCATION`). The settings endpoint is a soft
|
||||
forward-dependency — the mount falls back to first-registered-enabled if it 404s.
|
||||
|
||||
**Done when:** the provider accessor and resolver behave per the policy; the mount
|
||||
renders/clears correctly and survives a throwing provider via `ErrorBoundary`;
|
||||
`getViews` stays descriptor-only.
|
||||
|
||||
Base branch: `enxdev/feat/chatbot-contribution-point` (on #40439)
|
||||
|
||||
**External Links:** https://github.com/apache/superset/pull/40440
|
||||
|
||||
---
|
||||
|
||||
## 3. Eager loading & extension lifecycle/teardown
|
||||
|
||||
> Merged: this ticket also covers the **lifecycle & teardown contract** — both are
|
||||
> implemented in the same PR (#40441), so they are tracked together.
|
||||
|
||||
**Goal:** Boot extension bundles at app-shell startup so contributions register
|
||||
before the first route, and define the host contract for tearing those
|
||||
contributions down on uninstall.
|
||||
|
||||
**Build — eager loading:**
|
||||
|
||||
- An `ExtensionsStartup` component that, once the session is confirmed and behind
|
||||
`FeatureFlag.EnableExtensions`, kicks off `initializeExtensions()` in the
|
||||
background. The host renders immediately; the mount re-resolves reactively when
|
||||
registrations land.
|
||||
- Wire `window.superset` so Module-Federation remotes can consume host namespaces.
|
||||
- Mount `<ChatbotMount />` as a sibling of the route switch, inside
|
||||
`ExtensionsStartup`.
|
||||
- On bundle-load failure: a danger toast, host stays interactive, corner stays
|
||||
empty. Add a global `unhandledrejection` logger (log only; do not suppress the
|
||||
browser default).
|
||||
|
||||
**Build — lifecycle/teardown contract (Model A1, per-contribution dispose):**
|
||||
|
||||
- During the `./index` factory call, intercept the public registrars and collect
|
||||
the returned `Disposable`s keyed by extension id.
|
||||
- `deactivateExtension(id)` is the single teardown entrypoint: it fires every
|
||||
collected `Disposable` and removes the extension from the index. A throwing
|
||||
`Disposable` must not block the others (catch per-disposable). Idempotent;
|
||||
unknown id is a no-op.
|
||||
- Trigger semantics to document: **uninstall** → `deactivateExtension(id)`;
|
||||
**disable** → mount filters by `enabledMap`, does NOT fire disposables, re-enable
|
||||
needs no reload; **replace** (singleton) → resolver re-selects, the losing
|
||||
extension is not deactivated. Disposal order is best-effort (registration order),
|
||||
not a contract — consumers must be order-independent.
|
||||
|
||||
**Out of scope:** selective per-type eager loading (not feasible without running the
|
||||
factory); the mount-boundary `ErrorBoundary` (#40440); the settings endpoint and
|
||||
its subscription primitive (#40443); context namespaces (#40444); an async-aware
|
||||
`deactivate(): Promise<void>` — file separately only if a graceful-flush
|
||||
requirement appears.
|
||||
|
||||
**Depends on:** #40440 (`ChatbotMount`, resolver, registry-subscription hook). Soft
|
||||
build-time deps on #40443 (settings subscription) and #40444 (namespaces) — land
|
||||
those first or stub the imports.
|
||||
|
||||
**Done when:** enabled extensions init once at startup behind the flag without
|
||||
gating initial render; the bubble appears reactively on registration;
|
||||
`deactivateExtension(id)` disposes all of an extension's contributions (per-disposable
|
||||
catch, idempotent); load failure toasts without throwing; teardown is verified
|
||||
end-to-end on the reference chatbot (including an abort-registry controller that must
|
||||
still abort on deactivate).
|
||||
|
||||
Base branch: `enxdev/feat/chatbot-frontend-api` (on #40440)
|
||||
|
||||
**External Links:** https://github.com/apache/superset/pull/40441
|
||||
|
||||
---
|
||||
|
||||
## 4. Admin configuration UI
|
||||
|
||||
**Goal:** Let an admin enable/disable the chatbot and, when more than one chatbot is
|
||||
installed, choose which is active.
|
||||
|
||||
**Resolve before building:**
|
||||
|
||||
- Is "disable the chatbot" the existing generic extension-disable, or a
|
||||
chatbot-specific toggle? (Determines the ticket's size — prefer reusing the
|
||||
existing flag.)
|
||||
- Where does the UI live? Default: the existing extensions management surface, not a
|
||||
new page.
|
||||
- How does the "default chatbot" selection persist? Reuse existing extension-state
|
||||
storage or a config value — do not invent a table.
|
||||
- Which permission gates it? Default: the existing Extensions-API write permission.
|
||||
|
||||
**Build:**
|
||||
|
||||
- Enable/disable control that empties the `superset.chatbot` slot when off (no broken
|
||||
placeholder).
|
||||
- (Gated on the singleton-policy decision) A selection control listing candidates via
|
||||
`getViews('superset.chatbot')`, activating the choice through the resolver, falling
|
||||
back to first-to-register when unset.
|
||||
- Switching the active chatbot or disabling it at runtime must dispose the previously
|
||||
active chatbot via its `Disposable` and release its in-flight stream readers (via
|
||||
`AbortController`) — no two bubbles, no leaked readers.
|
||||
|
||||
**Out of scope:** the singleton-policy decision itself; per-page visibility; the
|
||||
resolver implementation (consumed here).
|
||||
|
||||
**Depends on:** #40440 (resolver) for selection; enable/disable does not wait on the
|
||||
policy decision.
|
||||
|
||||
**Done when:** admin can enable/disable (gated by the chosen permission) and the slot
|
||||
empties when off; selection picks the active chatbot with first-to-register fallback;
|
||||
the persistence-mechanism and permission decisions are recorded in the ticket.
|
||||
|
||||
Base branch: `enxdev/chat-prototype`
|
||||
|
||||
**External Links:** https://github.com/apache/superset/pull/40442
|
||||
|
||||
---
|
||||
|
||||
## 5. Permissions
|
||||
|
||||
**Goal:** Guarantee the new page-context surface cannot expose anything the current
|
||||
user can't already access through Superset's standard security model. Chatbot
|
||||
extensions fetch data as any other frontend surface and inherit only the current
|
||||
user's privileges; this ticket covers only the new host → extension context-sharing
|
||||
path.
|
||||
|
||||
**Build:**
|
||||
|
||||
- The page-context namespaces (#40444) must derive entity metadata from the same
|
||||
permission checks that gate the underlying page — not a raw Redux pass-through.
|
||||
- Canonical threat (SIP §2.1): a dashboard the user can view that contains a chart
|
||||
whose dataset they cannot query — that chart's metadata (id, name, datasource,
|
||||
viz type, form_data) must be dropped from the context payload.
|
||||
- Context carries only lightweight semantic data + identifiers that resolve through
|
||||
already-protected APIs; never inline dataset rows or query results.
|
||||
- Filtering applies equally to the initial read and every change-notification
|
||||
payload. A chatbot an admin has disabled receives no context at all.
|
||||
|
||||
**Out of scope:** REST API authorization, RBAC, RLS (already enforced by Superset);
|
||||
LLM/backend auth; the singleton selection policy. The chatbot authenticates via the
|
||||
user's existing session (cookie + CSRF) — no separate credential is issued.
|
||||
|
||||
**Depends on:** the Spike sizing the new namespaces (the per-getter filtering lands
|
||||
with those getters); the Context-sharing ticket consumes the filtered getters this
|
||||
one specifies.
|
||||
|
||||
**Done when:** context never exposes entities/ids/metadata the user can't access
|
||||
(even via a manually-entered URL); the dashboard payload omits charts whose dataset
|
||||
the user can't query; no inline privileged payloads; filtering covers change events
|
||||
as well as the initial read; a disabled chatbot gets nothing.
|
||||
|
||||
Base branch: `enxdev/chat-prototype`
|
||||
|
||||
**External Links:** https://github.com/apache/superset/pull/40443
|
||||
|
||||
---
|
||||
|
||||
## 6. Context sharing
|
||||
|
||||
**Goal:** Let the chatbot read semantic page context and subscribe to changes through
|
||||
public per-surface core namespaces only — never the host Redux store.
|
||||
|
||||
**Approach:** Deliver context through per-surface namespaces — the existing `sqlLab`
|
||||
namespace plus new `dashboard` / `explore` / `navigation` namespaces that mirror its
|
||||
shape (a state getter + an `Event<T>` change subscription). No new aggregate context
|
||||
API. The new namespaces copy `sqlLab`'s shape but must filter the Redux state they
|
||||
read (the permission filtering itself is specified by #40443).
|
||||
|
||||
**Build:**
|
||||
|
||||
- Route all chatbot page-context reads through one narrow adapter module with a fixed
|
||||
interface — the adapter is the deliverable, not scattered call sites — so swapping
|
||||
to core namespaces is a one-line change.
|
||||
- Back the adapter with `sqlLab` immediately; back the dashboard/explore/navigation
|
||||
portions and wire change notifications through `navigation`'s page-change event once
|
||||
those namespaces ship.
|
||||
|
||||
**Out of scope:** the permission-filtering logic (#40443 + upstream namespace work);
|
||||
designing the namespace API surface (upstream OSS work, sized by the Spike).
|
||||
|
||||
**Depends on:** a Spike to size the new namespaces (state getters + events + the
|
||||
per-getter permission filtering). The namespace _shape_ is settled by the `sqlLab`
|
||||
precedent; the filtering is real design work.
|
||||
|
||||
**Done when:** all context reads go through the single adapter (zero direct Redux
|
||||
imports, greppable); SQL Lab context works today; dashboard/explore context is either
|
||||
delivered or explicitly tracked as OSS-blocked (not faked); change notifications need
|
||||
no polling; no extra host re-renders.
|
||||
|
||||
Base branch: `enxdev/chat-prototype`
|
||||
|
||||
**External Links:** https://github.com/apache/superset/pull/40444
|
||||
|
||||
---
|
||||
|
||||
## 7. Import / delete UI
|
||||
|
||||
**Goal:** Add an actions column to the extensions list with buttons to delete an
|
||||
extension, set-as-default (chatbot extensions only), and import a new extension.
|
||||
|
||||
**Build:**
|
||||
|
||||
- Import an extension bundle, refreshing the list on success.
|
||||
- Delete an installed extension.
|
||||
- A "set as default chatbot" control, shown only for chatbot extensions.
|
||||
|
||||
**Out of scope:** the settings endpoint itself (#40443); the resolver (#40440).
|
||||
|
||||
**Depends on:** #40442/#40443 for the settings + chatbot-selection plumbing.
|
||||
|
||||
**Done when:** an admin can import, delete, and set a default chatbot from the
|
||||
actions column, with the list reflecting changes.
|
||||
|
||||
Base branch: `enxdev/chat-prototype`
|
||||
|
||||
**External Links:** https://github.com/apache/superset/pull/40450
|
||||
|
||||
---
|
||||
|
||||
## ~~8. Fault isolation & error boundaries~~ — CLOSED (no ticket needed)
|
||||
|
||||
The protective fault-isolation mechanisms are **already implemented** across the
|
||||
mount and eager-loading PRs, so no standalone ticket is required:
|
||||
|
||||
- Render/lifecycle throw → host `ErrorBoundary` around the `superset.chatbot` slot
|
||||
(#40440, reinforced by the `ChatbotRenderer` wrapper in #40441).
|
||||
- Bundle-load failure → `.catch()` + danger toast in `ExtensionsLoader` (#40441).
|
||||
- `activate()` throw → host try/catch in `ExtensionsLoader` (#40441).
|
||||
- Escaped async rejection → `unhandledrejection` hook in `ExtensionsStartup` (#40441).
|
||||
- Failed-activation cleanup → driven by `deactivateExtension` (ticket 3 / #40441).
|
||||
|
||||
The host stays safe under every failure class today. The only unbuilt pieces were the
|
||||
**optional** "chatbot failed — Reload page" notification and structured
|
||||
failure-class/telemetry logging — both judged not worth a ticket (the original spec
|
||||
itself marked the reload notification "optional"). File a fresh ticket only if that
|
||||
UX is later wanted.
|
||||
|
||||
(Original link, for reference only: PR #40433 `feat(extensions): adds chatbot P1-P2` —
|
||||
closed/superseded; never a dedicated fault-isolation PR.)
|
||||
|
||||
---
|
||||
|
||||
## Notes on consolidation
|
||||
|
||||
- **Lifecycle/teardown** was a separate ticket pointing at the same PR as **Eager
|
||||
loading** (#40441) — merged into ticket 3 above. (This is the only true duplicate.)
|
||||
- The **Permissions** ticket (#40443) is kept as-is. Note its PR also contains
|
||||
backend settings-persistence code, but the original ticket only ever scoped the
|
||||
permission-safe context surface — so the ticket stays "Permissions" and no
|
||||
persistence ticket is invented.
|
||||
- The **Permissions** ticket previously had a truncated base branch
|
||||
(`enxdev/chat-protot`) — corrected to `enxdev/chat-prototype`.
|
||||
- **Fault isolation** was **closed without a ticket** (see the struck-through section
|
||||
above): its protective mechanisms already shipped in #40440/#40441, and the only
|
||||
unbuilt pieces (the optional "Reload page" notification + structured telemetry
|
||||
logging) were judged not worth a ticket.
|
||||
29
UPDATING.md
29
UPDATING.md
@@ -24,6 +24,35 @@ assists people when migrating to a new version.
|
||||
|
||||
## Next
|
||||
|
||||
### YDB now uses a native sqlglot dialect
|
||||
|
||||
YDB SQL parsing now relies on the dedicated [`ydb-sqlglot-plugin`](https://pypi.org/project/ydb-sqlglot-plugin/) dialect, which registers itself with sqlglot automatically. YDB users must install this plugin (e.g., via `pip install "apache-superset[ydb]"`) to avoid a `ValueError` when Superset parses YDB queries.
|
||||
|
||||
### Embedded dashboards enforce configured Allowed Domains for postMessage
|
||||
|
||||
The embedded dashboard page now validates the origin of incoming `postMessage` events against the dashboard's configured **Allowed Domains**. The server-rendered embedded page exposes the configured domains in its bootstrap payload, and the frontend rejects message events whose origin is not in that list.
|
||||
|
||||
Enforcement only applies when the Allowed Domains list is non-empty. If the list is empty (the default), any origin is accepted, so there is no behavior change for embeds that did not configure Allowed Domains.
|
||||
|
||||
### New `EXPOSE_VERSION_INFO` config to control `/version` detail
|
||||
|
||||
A new `EXPOSE_VERSION_INFO` config option controls how much detail the unauthenticated `/version` endpoint returns. It defaults to `True`, which preserves the existing behavior: the endpoint returns the full version metadata, including the Git SHA, full SHA, build number, and branch name when available.
|
||||
|
||||
Operators who prefer not to expose build-specific details to unauthenticated callers can set the following in `superset_config.py`:
|
||||
|
||||
```python
|
||||
EXPOSE_VERSION_INFO = False
|
||||
```
|
||||
|
||||
When disabled, `/version` returns only the human-readable `version_string` and omits the Git SHA, full SHA, build number, and branch name. Because the default is `True`, this change is non-breaking for existing deployments.
|
||||
|
||||
As an additional defense-in-depth hardening, Superset now sends a `Cross-Origin-Resource-Policy: same-site` response header by default via `DEFAULT_HTTP_HEADERS`. `same-site` is deliberately chosen over the stricter `same-origin` so that documented same-site embedding flows (e.g. the Embedded SDK, where a Superset subdomain is framed by a sibling application subdomain) continue to work unchanged. Deployments that serve Superset responses or static assets as subresources to a _cross-site_ origin may need to relax or remove this header. Because it is applied through `DEFAULT_HTTP_HEADERS`, the header is only set when a response does not already carry one, so it can be overridden per-response or by replacing the config value:
|
||||
|
||||
```python
|
||||
# Relax to permit cross-site consumers, or set to "same-origin" to harden further.
|
||||
DEFAULT_HTTP_HEADERS = {"Cross-Origin-Resource-Policy": "cross-origin"}
|
||||
```
|
||||
|
||||
### Dataset import validates catalog against the target connection
|
||||
|
||||
Importing a dataset now validates the `catalog` field against the target database connection. When the connection has multi-catalog disabled (`allow_multi_catalog` off) and the dataset's catalog is not the connection's default catalog, the import fails instead of silently persisting the non-default catalog. This matches the validation already enforced on the dataset update path and prevents imported datasets from querying an unintended database.
|
||||
|
||||
@@ -1,138 +0,0 @@
|
||||
<!--
|
||||
Licensed to the Apache Software Foundation (ASF) under one
|
||||
or more contributor license agreements. See the NOTICE file
|
||||
distributed with this work for additional information
|
||||
regarding copyright ownership. The ASF licenses this file
|
||||
to you under the Apache License, Version 2.0 (the
|
||||
"License"); you may not use this file except in compliance
|
||||
with the License. You may obtain a copy of the License at
|
||||
|
||||
http://www.apache.org/licenses/LICENSE-2.0
|
||||
|
||||
Unless required by applicable law or agreed to in writing,
|
||||
software distributed under the License is distributed on an
|
||||
"AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
|
||||
KIND, either express or implied. See the License for the
|
||||
specific language governing permissions and limitations
|
||||
under the License.
|
||||
-->
|
||||
|
||||
# Reference Chatbot Extension
|
||||
|
||||
Canonical environment-validation extension for the `superset.chatbot`
|
||||
contribution area. **Not** a product chatbot — there is no LLM, no backend,
|
||||
no persistence. Its purpose is to exercise the extension platform end-to-end:
|
||||
|
||||
- `views.registerView` at `superset.chatbot` (singleton resolution)
|
||||
- Lifecycle activation + a master disposable that tears down everything
|
||||
- `commands.registerCommand` for `core.chatbot__open|close|toggle`
|
||||
- Mock streaming with `AbortController` cancellation on dispose
|
||||
- Defense-in-depth React error boundary inside the panel
|
||||
- A single P3 page-context seam that lights up automatically as the
|
||||
`dashboard` / `explore` / `dataset` / `navigation` namespaces become
|
||||
available at runtime on the host
|
||||
|
||||
It is intended as the reference implementation third-party chatbot extension
|
||||
authors copy. Anything that ships as host-internal (the mount point, the
|
||||
admin picker, the `getActiveChatbot` resolver) is **not** here — see the
|
||||
host side at `superset-frontend/src/components/ChatbotMount/` and
|
||||
`superset-frontend/src/core/chatbot/`.
|
||||
|
||||
## Layout
|
||||
|
||||
```
|
||||
extensions/chat/
|
||||
├── extension.json Manifest (app.chatbot view + commands)
|
||||
├── package.json
|
||||
├── tsconfig.json
|
||||
├── webpack.config.js ModuleFederation → window.superset
|
||||
├── jest.config.js Self-contained unit tests
|
||||
└── src/
|
||||
├── index.tsx MF entry — calls activate() once
|
||||
├── activate.ts Returns master disposable
|
||||
├── commands.ts core.chatbot__open|close|toggle
|
||||
├── state.ts Module-scoped open/closed + emitter
|
||||
├── ReferenceChatbot.tsx Root component (bubble ↔ panel)
|
||||
├── components/
|
||||
│ ├── Bubble.tsx
|
||||
│ ├── Panel.tsx
|
||||
│ └── ErrorBoundary.tsx
|
||||
├── streaming/
|
||||
│ ├── mockStream.ts AsyncIterable<string> + AbortSignal
|
||||
│ └── registry.ts Cross-component abort tracking
|
||||
├── context/
|
||||
│ └── pageContext.ts P3 namespace seam (defensive)
|
||||
└── __tests__/
|
||||
├── sdkMock.ts In-memory @apache-superset/core mock
|
||||
└── activate.test.tsx
|
||||
```
|
||||
|
||||
## Run the unit tests
|
||||
|
||||
```bash
|
||||
cd extensions/chat
|
||||
npm install # first time only
|
||||
npx jest
|
||||
```
|
||||
|
||||
The tests mock `@apache-superset/core` via `src/__tests__/sdkMock.ts` so they
|
||||
do not depend on host runtime wiring.
|
||||
|
||||
## Build / bundle for deployment
|
||||
|
||||
```bash
|
||||
# from the extension folder
|
||||
npm install
|
||||
npm run build
|
||||
|
||||
# packaging into a .supx is handled by the Superset extensions CLI
|
||||
pip install apache-superset-extensions-cli
|
||||
superset-extensions bundle # produces apache-superset.reference-chatbot-0.1.0.supx
|
||||
```
|
||||
|
||||
Drop the `.supx` into the `EXTENSIONS_PATH` of a Superset instance that has
|
||||
`FEATURE_FLAGS = { "ENABLE_EXTENSIONS": True }`.
|
||||
|
||||
## Selecting it as the active chatbot
|
||||
|
||||
The host's singleton picker reads `active_chatbot_id` from the admin
|
||||
settings endpoint (`/api/v1/extensions/settings`). Set it to:
|
||||
|
||||
```
|
||||
apache-superset.reference-chatbot
|
||||
```
|
||||
|
||||
If no admin selection exists, the host falls back to the first-to-register
|
||||
chatbot — installing this extension alone is enough for the bubble to appear.
|
||||
|
||||
## P3 integration seams
|
||||
|
||||
All page-context derivation lives in [`src/context/pageContext.ts`](src/context/pageContext.ts).
|
||||
Each namespace branch (`dashboard`, `explore`, `dataset`, `navigation`) is
|
||||
called defensively — when the host implementation lands, the returned value
|
||||
becomes non-undefined automatically with no other change in the extension.
|
||||
|
||||
The panel re-reads context on `popstate`. Once `navigation.onDidChangePage`
|
||||
is live on the host, the panel's `useEffect` should subscribe to it instead;
|
||||
that is the only file in the extension that needs to change for full P3
|
||||
context sync.
|
||||
|
||||
## Known intentional non-features
|
||||
|
||||
- No conversation persistence — by design (extension scope per SIP §2).
|
||||
- No real network. The mock stream is a `setTimeout` token emitter so the
|
||||
cancellation contract is exercised without external dependencies.
|
||||
- No keyboard shortcut binding (Cmd+K). Extensions own that, but it adds
|
||||
surface area not needed for platform validation.
|
||||
- No notification badge / icon mutation. SIP §3.2 recommends static icons;
|
||||
the bubble re-renders freely already.
|
||||
|
||||
## TODOs
|
||||
|
||||
- **P1**: if/when the host gains `deactivate(): Promise<void>`, wrap the
|
||||
master disposer in `activate.ts` to flush async work before returning.
|
||||
- **P3**: replace the `popstate` listener in `Panel.tsx` with
|
||||
`navigation.onDidChangePage` once that event is wired up host-side.
|
||||
- **P4**: if the host pre-registers `core.chatbot__*` as host-owned intents,
|
||||
swap `commands.registerCommand` for the implementation hook in
|
||||
`commands.ts`. Command IDs do not change.
|
||||
@@ -1,40 +0,0 @@
|
||||
{
|
||||
"publisher": "apache-superset",
|
||||
"name": "reference-chatbot",
|
||||
"displayName": "Reference Chatbot",
|
||||
"description": "Canonical environment-validation chatbot extension for the superset.chatbot contribution area. Exercises registration, lifecycle, singleton resolution, commands, fault isolation, and streaming teardown. Not a product chatbot.",
|
||||
"version": "0.1.0",
|
||||
"license": "Apache-2.0",
|
||||
"permissions": [],
|
||||
"contributes": {
|
||||
"views": {
|
||||
"app": {
|
||||
"chatbot": [
|
||||
{
|
||||
"id": "apache-superset.reference-chatbot",
|
||||
"name": "Reference Chatbot",
|
||||
"description": "Validates the chatbot extension environment end-to-end.",
|
||||
"icon": "Bubble"
|
||||
}
|
||||
]
|
||||
}
|
||||
},
|
||||
"commands": [
|
||||
{
|
||||
"id": "core.chatbot__open",
|
||||
"title": "Open chatbot",
|
||||
"description": "Opens the reference chatbot panel."
|
||||
},
|
||||
{
|
||||
"id": "core.chatbot__close",
|
||||
"title": "Close chatbot",
|
||||
"description": "Closes the reference chatbot panel."
|
||||
},
|
||||
{
|
||||
"id": "core.chatbot__toggle",
|
||||
"title": "Toggle chatbot",
|
||||
"description": "Toggles the reference chatbot panel."
|
||||
}
|
||||
]
|
||||
}
|
||||
}
|
||||
@@ -1,53 +0,0 @@
|
||||
/**
|
||||
* Licensed to the Apache Software Foundation (ASF) under one
|
||||
* or more contributor license agreements. See the NOTICE file
|
||||
* distributed with this work for additional information
|
||||
* regarding copyright ownership. The ASF licenses this file
|
||||
* to you under the Apache License, Version 2.0 (the
|
||||
* "License"); you may not use this file except in compliance
|
||||
* with the License. You may obtain a copy of the License at
|
||||
*
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing,
|
||||
* software distributed under the License is distributed on an
|
||||
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
|
||||
* KIND, either express or implied. See the License for the
|
||||
* specific language governing permissions and limitations
|
||||
* under the License.
|
||||
*/
|
||||
const path = require('path');
|
||||
|
||||
// When run as a standalone package (`cd extensions/chat && npm test`), modules
|
||||
// resolve from this folder's own node_modules. When run from the superset-frontend
|
||||
// workspace (CI, dev convenience), resolve ts-jest there too.
|
||||
const tsJest = (() => {
|
||||
try {
|
||||
require.resolve('ts-jest');
|
||||
return 'ts-jest';
|
||||
} catch {
|
||||
return path.resolve(
|
||||
__dirname,
|
||||
'..',
|
||||
'..',
|
||||
'superset-frontend',
|
||||
'node_modules',
|
||||
'ts-jest',
|
||||
);
|
||||
}
|
||||
})();
|
||||
|
||||
module.exports = {
|
||||
testEnvironment: 'jsdom',
|
||||
rootDir: __dirname,
|
||||
testMatch: ['<rootDir>/src/**/*.test.{ts,tsx}'],
|
||||
// When running from the extension folder without node_modules installed,
|
||||
// resolve react / react-dom from the superset-frontend workspace.
|
||||
modulePaths: [path.resolve(__dirname, '..', '..', 'superset-frontend', 'node_modules')],
|
||||
moduleNameMapper: {
|
||||
'^@apache-superset/core$': '<rootDir>/src/__tests__/sdkMock.ts',
|
||||
},
|
||||
transform: {
|
||||
'^.+\\.tsx?$': [tsJest, { tsconfig: '<rootDir>/tsconfig.test.json' }],
|
||||
},
|
||||
};
|
||||
@@ -1,26 +0,0 @@
|
||||
{
|
||||
"name": "@apache-superset/reference-chatbot",
|
||||
"version": "0.1.0",
|
||||
"private": true,
|
||||
"license": "Apache-2.0",
|
||||
"description": "Reference chatbot extension that validates the Superset chatbot extension platform.",
|
||||
"scripts": {
|
||||
"start": "webpack serve --mode development",
|
||||
"build": "webpack --stats-error-details --mode production"
|
||||
},
|
||||
"peerDependencies": {
|
||||
"@apache-superset/core": "^0.1.0",
|
||||
"react": "^18.2.0",
|
||||
"react-dom": "^18.2.0"
|
||||
},
|
||||
"devDependencies": {
|
||||
"@apache-superset/core": "^0.1.0",
|
||||
"@types/react": "^18.2.0",
|
||||
"@types/react-dom": "^18.2.0",
|
||||
"ts-loader": "^9.5.0",
|
||||
"typescript": "^5.0.0",
|
||||
"webpack": "^5.0.0",
|
||||
"webpack-cli": "^5.0.0",
|
||||
"webpack-dev-server": "^5.0.0"
|
||||
}
|
||||
}
|
||||
@@ -1,45 +0,0 @@
|
||||
/**
|
||||
* Licensed to the Apache Software Foundation (ASF) under one
|
||||
* or more contributor license agreements. See the NOTICE file
|
||||
* distributed with this work for additional information
|
||||
* regarding copyright ownership. The ASF licenses this file
|
||||
* to you under the Apache License, Version 2.0 (the
|
||||
* "License"); you may not use this file except in compliance
|
||||
* with the License. You may obtain a copy of the License at
|
||||
*
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing,
|
||||
* software distributed under the License is distributed on an
|
||||
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
|
||||
* KIND, either express or implied. See the License for the
|
||||
* specific language governing permissions and limitations
|
||||
* under the License.
|
||||
*/
|
||||
import React, { useEffect, useState } from 'react';
|
||||
import { commands } from '@apache-superset/core';
|
||||
import { Bubble } from './components/Bubble';
|
||||
import { Panel } from './components/Panel';
|
||||
import { ExtensionErrorBoundary } from './components/ErrorBoundary';
|
||||
import { isOpen, subscribe } from './state';
|
||||
|
||||
/**
|
||||
* Root extension component. Mirrors module-state into React via `subscribe`
|
||||
* so the bubble↔panel transition is driven by the same command handlers
|
||||
* that external callers use (`core.chatbot__open`, `__close`, `__toggle`).
|
||||
*/
|
||||
export const ReferenceChatbot: React.FC = () => {
|
||||
const [open, setOpenState] = useState<boolean>(isOpen());
|
||||
|
||||
useEffect(() => subscribe(setOpenState), []);
|
||||
|
||||
return (
|
||||
<ExtensionErrorBoundary>
|
||||
{open ? (
|
||||
<Panel onClose={() => commands.executeCommand('core.chatbot__close')} />
|
||||
) : (
|
||||
<Bubble onClick={() => commands.executeCommand('core.chatbot__open')} />
|
||||
)}
|
||||
</ExtensionErrorBoundary>
|
||||
);
|
||||
};
|
||||
@@ -1,144 +0,0 @@
|
||||
/**
|
||||
* Licensed to the Apache Software Foundation (ASF) under one
|
||||
* or more contributor license agreements. See the NOTICE file
|
||||
* distributed with this work for additional information
|
||||
* regarding copyright ownership. The ASF licenses this file
|
||||
* to you under the Apache License, Version 2.0 (the
|
||||
* "License"); you may not use this file except in compliance
|
||||
* with the License. You may obtain a copy of the License at
|
||||
*
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing,
|
||||
* software distributed under the License is distributed on an
|
||||
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
|
||||
* KIND, either express or implied. See the License for the
|
||||
* specific language governing permissions and limitations
|
||||
* under the License.
|
||||
*/
|
||||
import { commands } from '@apache-superset/core';
|
||||
import { registry, reset } from './sdkMock';
|
||||
import { activate, VIEW_ID, CHATBOT_LOCATION } from '../activate';
|
||||
import { isOpen } from '../state';
|
||||
import { streamReply } from '../streaming/mockStream';
|
||||
import {
|
||||
registerActiveController,
|
||||
unregisterActiveController,
|
||||
abortAllActiveControllers,
|
||||
} from '../streaming/registry';
|
||||
|
||||
beforeEach(() => {
|
||||
reset();
|
||||
});
|
||||
|
||||
test('registers one view at superset.chatbot and three chatbot commands', () => {
|
||||
const disposable = activate();
|
||||
|
||||
try {
|
||||
expect(registry.views.size).toBe(1);
|
||||
const entry = registry.views.get(VIEW_ID);
|
||||
expect(entry?.location).toBe(CHATBOT_LOCATION);
|
||||
expect(entry?.view.icon).toBe('Bubble');
|
||||
|
||||
expect(Array.from(registry.commands.keys()).sort()).toEqual([
|
||||
'core.chatbot__close',
|
||||
'core.chatbot__open',
|
||||
'core.chatbot__toggle',
|
||||
]);
|
||||
} finally {
|
||||
disposable.dispose();
|
||||
}
|
||||
});
|
||||
|
||||
test('executeCommand drives open/close/toggle through module state', async () => {
|
||||
const disposable = activate();
|
||||
try {
|
||||
expect(isOpen()).toBe(false);
|
||||
|
||||
await commands.executeCommand('core.chatbot__open');
|
||||
expect(isOpen()).toBe(true);
|
||||
|
||||
await commands.executeCommand('core.chatbot__toggle');
|
||||
expect(isOpen()).toBe(false);
|
||||
|
||||
await commands.executeCommand('core.chatbot__toggle');
|
||||
expect(isOpen()).toBe(true);
|
||||
|
||||
await commands.executeCommand('core.chatbot__close');
|
||||
expect(isOpen()).toBe(false);
|
||||
} finally {
|
||||
disposable.dispose();
|
||||
}
|
||||
});
|
||||
|
||||
test('disposing the master disposable unregisters view + commands', () => {
|
||||
const disposable = activate();
|
||||
expect(registry.views.size).toBe(1);
|
||||
expect(registry.commands.size).toBe(3);
|
||||
|
||||
disposable.dispose();
|
||||
|
||||
expect(registry.views.size).toBe(0);
|
||||
expect(registry.commands.size).toBe(0);
|
||||
});
|
||||
|
||||
test('disposal is idempotent', () => {
|
||||
const disposable = activate();
|
||||
disposable.dispose();
|
||||
expect(() => disposable.dispose()).not.toThrow();
|
||||
expect(registry.views.size).toBe(0);
|
||||
});
|
||||
|
||||
test('re-activate after dispose works (validates replace semantics)', () => {
|
||||
const first = activate();
|
||||
first.dispose();
|
||||
|
||||
const second = activate();
|
||||
try {
|
||||
expect(registry.views.size).toBe(1);
|
||||
expect(registry.commands.size).toBe(3);
|
||||
expect(isOpen()).toBe(false); // resetState() cleared open flag
|
||||
} finally {
|
||||
second.dispose();
|
||||
}
|
||||
});
|
||||
|
||||
test('aborting an active controller stops the stream cleanly', async () => {
|
||||
const controller = new AbortController();
|
||||
registerActiveController(controller);
|
||||
|
||||
const iter = streamReply('hello world', controller.signal);
|
||||
const received: string[] = [];
|
||||
|
||||
const consume = (async () => {
|
||||
for await (const tok of iter) received.push(tok);
|
||||
})();
|
||||
|
||||
// Abort after a single tick — the iterator must return without throwing.
|
||||
await new Promise(r => setTimeout(r, 50));
|
||||
abortAllActiveControllers();
|
||||
await expect(consume).resolves.toBeUndefined();
|
||||
|
||||
unregisterActiveController(controller);
|
||||
expect(received.length).toBeLessThan(20); // would be ~20+ tokens if uncancelled
|
||||
});
|
||||
|
||||
test('disposing the extension aborts any in-flight controller', async () => {
|
||||
const disposable = activate();
|
||||
const controller = new AbortController();
|
||||
registerActiveController(controller);
|
||||
|
||||
const iter = streamReply('a longer prompt to ensure many tokens', controller.signal);
|
||||
const consume = (async () => {
|
||||
// eslint-disable-next-line no-unused-vars, @typescript-eslint/no-unused-vars
|
||||
for await (const _tok of iter) {
|
||||
// drain
|
||||
}
|
||||
})();
|
||||
|
||||
await new Promise(r => setTimeout(r, 30));
|
||||
disposable.dispose();
|
||||
|
||||
await expect(consume).resolves.toBeUndefined();
|
||||
expect(controller.signal.aborted).toBe(true);
|
||||
});
|
||||
@@ -1,119 +0,0 @@
|
||||
/**
|
||||
* Licensed to the Apache Software Foundation (ASF) under one
|
||||
* or more contributor license agreements. See the NOTICE file
|
||||
* distributed with this work for additional information
|
||||
* regarding copyright ownership. The ASF licenses this file
|
||||
* to you under the Apache License, Version 2.0 (the
|
||||
* "License"); you may not use this file except in compliance
|
||||
* with the License. You may obtain a copy of the License at
|
||||
*
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing,
|
||||
* software distributed under the License is distributed on an
|
||||
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
|
||||
* KIND, either express or implied. See the License for the
|
||||
* specific language governing permissions and limitations
|
||||
* under the License.
|
||||
*/
|
||||
|
||||
/**
|
||||
* In-memory mock of `@apache-superset/core` for unit-testing the extension.
|
||||
*
|
||||
* Mirrors only the surfaces the reference chatbot consumes:
|
||||
* - views.registerView returns a disposable that removes the view
|
||||
* - commands.registerCommand / executeCommand round-trip handlers
|
||||
* - sqlLab.getCurrentTab returns undefined (no SQL Lab in tests)
|
||||
*
|
||||
* The mock is intentionally observable: tests can read `registry.views` and
|
||||
* `registry.commands` to assert contract compliance.
|
||||
*/
|
||||
|
||||
import type { ReactElement } from 'react';
|
||||
|
||||
type Provider = () => ReactElement;
|
||||
|
||||
interface ViewDescriptor {
|
||||
id: string;
|
||||
name: string;
|
||||
icon?: string;
|
||||
description?: string;
|
||||
}
|
||||
|
||||
interface DisposableLike {
|
||||
dispose(): void;
|
||||
}
|
||||
|
||||
interface RegisteredView {
|
||||
view: ViewDescriptor;
|
||||
location: string;
|
||||
provider: Provider;
|
||||
}
|
||||
|
||||
interface RegisteredCommand {
|
||||
id: string;
|
||||
title: string;
|
||||
handler: (...args: any[]) => any;
|
||||
}
|
||||
|
||||
export const registry = {
|
||||
views: new Map<string, RegisteredView>(),
|
||||
commands: new Map<string, RegisteredCommand>(),
|
||||
};
|
||||
|
||||
export const reset = (): void => {
|
||||
registry.views.clear();
|
||||
registry.commands.clear();
|
||||
};
|
||||
|
||||
export const views = {
|
||||
registerView(
|
||||
view: ViewDescriptor,
|
||||
location: string,
|
||||
provider: Provider,
|
||||
): DisposableLike {
|
||||
registry.views.set(view.id, { view, location, provider });
|
||||
return {
|
||||
dispose: () => {
|
||||
registry.views.delete(view.id);
|
||||
},
|
||||
};
|
||||
},
|
||||
getViews(location: string) {
|
||||
return Array.from(registry.views.values())
|
||||
.filter(v => v.location === location)
|
||||
.map(v => v.view);
|
||||
},
|
||||
};
|
||||
|
||||
export const commands = {
|
||||
registerCommand(
|
||||
command: { id: string; title: string },
|
||||
handler: (...args: any[]) => any,
|
||||
): DisposableLike {
|
||||
registry.commands.set(command.id, {
|
||||
id: command.id,
|
||||
title: command.title,
|
||||
handler,
|
||||
});
|
||||
return {
|
||||
dispose: () => {
|
||||
registry.commands.delete(command.id);
|
||||
},
|
||||
};
|
||||
},
|
||||
async executeCommand(id: string, ...rest: any[]): Promise<unknown> {
|
||||
const cmd = registry.commands.get(id);
|
||||
return cmd?.handler(...rest);
|
||||
},
|
||||
getCommands() {
|
||||
return Array.from(registry.commands.values()).map(c => ({
|
||||
id: c.id,
|
||||
title: c.title,
|
||||
}));
|
||||
},
|
||||
};
|
||||
|
||||
export const sqlLab = {
|
||||
getCurrentTab: () => undefined,
|
||||
};
|
||||
@@ -1,88 +0,0 @@
|
||||
/**
|
||||
* Licensed to the Apache Software Foundation (ASF) under one
|
||||
* or more contributor license agreements. See the NOTICE file
|
||||
* distributed with this work for additional information
|
||||
* regarding copyright ownership. The ASF licenses this file
|
||||
* to you under the Apache License, Version 2.0 (the
|
||||
* "License"); you may not use this file except in compliance
|
||||
* with the License. You may obtain a copy of the License at
|
||||
*
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing,
|
||||
* software distributed under the License is distributed on an
|
||||
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
|
||||
* KIND, either express or implied. See the License for the
|
||||
* specific language governing permissions and limitations
|
||||
* under the License.
|
||||
*/
|
||||
import React from 'react';
|
||||
import { views } from '@apache-superset/core';
|
||||
import { ReferenceChatbot } from './ReferenceChatbot';
|
||||
import { registerChatbotCommands } from './commands';
|
||||
import { abortAllActiveControllers } from './streaming/registry';
|
||||
import { resetState } from './state';
|
||||
|
||||
export const VIEW_ID = 'apache-superset.reference-chatbot';
|
||||
export const CHATBOT_LOCATION = 'superset.chatbot';
|
||||
|
||||
interface DisposableLike {
|
||||
dispose(): void;
|
||||
}
|
||||
|
||||
/**
|
||||
* Registers the reference chatbot and returns a single disposable that
|
||||
* tears down everything it created. Idempotent across activate/dispose cycles.
|
||||
*
|
||||
* Cleanup order matters: stop in-flight streams first so listeners do not
|
||||
* receive late tokens, then unregister commands (so user clicks during teardown
|
||||
* become no-ops), then unregister the view (so the host's ChatbotMount unmounts
|
||||
* the React tree), and finally reset module state.
|
||||
*
|
||||
* Returns a plain `{ dispose }` object rather than constructing a Disposable
|
||||
* from the SDK — the SDK class is host-injected and only reliably available
|
||||
* via window.superset at runtime, while plain disposable-likes work in both
|
||||
* runtime and unit-test contexts.
|
||||
*
|
||||
* TODO(P1): when the host gains an async `deactivate(): Promise<void>` hook,
|
||||
* wrap the master disposer to flush in-flight async work before returning.
|
||||
*/
|
||||
export const activate = (): DisposableLike => {
|
||||
const commandDisposables = registerChatbotCommands();
|
||||
const viewDisposable = views.registerView(
|
||||
{
|
||||
id: VIEW_ID,
|
||||
name: 'Reference Chatbot',
|
||||
icon: 'Bubble',
|
||||
description: 'Validates the chatbot extension environment end-to-end.',
|
||||
},
|
||||
CHATBOT_LOCATION,
|
||||
() => React.createElement(ReferenceChatbot),
|
||||
);
|
||||
|
||||
let disposed = false;
|
||||
return {
|
||||
dispose() {
|
||||
if (disposed) return;
|
||||
disposed = true;
|
||||
try {
|
||||
abortAllActiveControllers();
|
||||
} catch {
|
||||
// streams are best-effort during teardown
|
||||
}
|
||||
commandDisposables.forEach(d => {
|
||||
try {
|
||||
d.dispose();
|
||||
} catch {
|
||||
// a single command failing to unregister must not block the rest
|
||||
}
|
||||
});
|
||||
try {
|
||||
viewDisposable.dispose();
|
||||
} catch {
|
||||
// ignore
|
||||
}
|
||||
resetState();
|
||||
},
|
||||
};
|
||||
};
|
||||
@@ -1,47 +0,0 @@
|
||||
/**
|
||||
* Licensed to the Apache Software Foundation (ASF) under one
|
||||
* or more contributor license agreements. See the NOTICE file
|
||||
* distributed with this work for additional information
|
||||
* regarding copyright ownership. The ASF licenses this file
|
||||
* to you under the Apache License, Version 2.0 (the
|
||||
* "License"); you may not use this file except in compliance
|
||||
* with the License. You may obtain a copy of the License at
|
||||
*
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing,
|
||||
* software distributed under the License is distributed on an
|
||||
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
|
||||
* KIND, either express or implied. See the License for the
|
||||
* specific language governing permissions and limitations
|
||||
* under the License.
|
||||
*/
|
||||
import { commands } from '@apache-superset/core';
|
||||
import { isOpen, setOpen } from './state';
|
||||
|
||||
interface DisposableLike {
|
||||
dispose(): void;
|
||||
}
|
||||
|
||||
/**
|
||||
* Registers the three chatbot intent commands and returns their disposables.
|
||||
*
|
||||
* TODO(P4): if/when the host pre-registers `core.chatbot__*` as host-owned
|
||||
* intents that extensions implement instead of own, swap registerCommand for
|
||||
* the implementation hook. The command ids stay the same so call sites do not
|
||||
* change.
|
||||
*/
|
||||
export const registerChatbotCommands = (): DisposableLike[] => [
|
||||
commands.registerCommand(
|
||||
{ id: 'core.chatbot__open', title: 'Open chatbot' },
|
||||
() => setOpen(true),
|
||||
),
|
||||
commands.registerCommand(
|
||||
{ id: 'core.chatbot__close', title: 'Close chatbot' },
|
||||
() => setOpen(false),
|
||||
),
|
||||
commands.registerCommand(
|
||||
{ id: 'core.chatbot__toggle', title: 'Toggle chatbot' },
|
||||
() => setOpen(!isOpen()),
|
||||
),
|
||||
];
|
||||
@@ -1,46 +0,0 @@
|
||||
/**
|
||||
* Licensed to the Apache Software Foundation (ASF) under one
|
||||
* or more contributor license agreements. See the NOTICE file
|
||||
* distributed with this work for additional information
|
||||
* regarding copyright ownership. The ASF licenses this file
|
||||
* to you under the Apache License, Version 2.0 (the
|
||||
* "License"); you may not use this file except in compliance
|
||||
* with the License. You may obtain a copy of the License at
|
||||
*
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing,
|
||||
* software distributed under the License is distributed on an
|
||||
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
|
||||
* KIND, either express or implied. See the License for the
|
||||
* specific language governing permissions and limitations
|
||||
* under the License.
|
||||
*/
|
||||
import React from 'react';
|
||||
|
||||
interface Props {
|
||||
onClick: () => void;
|
||||
}
|
||||
|
||||
export const Bubble: React.FC<Props> = ({ onClick }) => (
|
||||
<button
|
||||
type="button"
|
||||
onClick={onClick}
|
||||
data-test="reference-chatbot-bubble"
|
||||
aria-label="Open reference chatbot"
|
||||
style={{
|
||||
width: 56,
|
||||
height: 56,
|
||||
borderRadius: '50%',
|
||||
border: 'none',
|
||||
background: '#1f6feb',
|
||||
color: '#fff',
|
||||
fontSize: 24,
|
||||
fontWeight: 600,
|
||||
cursor: 'pointer',
|
||||
boxShadow: '0 4px 14px rgba(0,0,0,0.18)',
|
||||
}}
|
||||
>
|
||||
?
|
||||
</button>
|
||||
);
|
||||
@@ -1,66 +0,0 @@
|
||||
/**
|
||||
* Licensed to the Apache Software Foundation (ASF) under one
|
||||
* or more contributor license agreements. See the NOTICE file
|
||||
* distributed with this work for additional information
|
||||
* regarding copyright ownership. The ASF licenses this file
|
||||
* to you under the Apache License, Version 2.0 (the
|
||||
* "License"); you may not use this file except in compliance
|
||||
* with the License. You may obtain a copy of the License at
|
||||
*
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing,
|
||||
* software distributed under the License is distributed on an
|
||||
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
|
||||
* KIND, either express or implied. See the License for the
|
||||
* specific language governing permissions and limitations
|
||||
* under the License.
|
||||
*/
|
||||
import React from 'react';
|
||||
|
||||
interface State {
|
||||
error: Error | null;
|
||||
}
|
||||
|
||||
/**
|
||||
* Defense-in-depth boundary. The host already wraps the mount in its own
|
||||
* ErrorBoundary; this one keeps a panel crash from also bringing down the
|
||||
* bubble next to it.
|
||||
*/
|
||||
export class ExtensionErrorBoundary extends React.Component<
|
||||
React.PropsWithChildren<{}>,
|
||||
State
|
||||
> {
|
||||
state: State = { error: null };
|
||||
|
||||
static getDerivedStateFromError(error: Error): State {
|
||||
return { error };
|
||||
}
|
||||
|
||||
componentDidCatch(error: Error): void {
|
||||
// eslint-disable-next-line no-console
|
||||
console.error('[reference-chatbot] render error', error);
|
||||
}
|
||||
|
||||
render() {
|
||||
if (this.state.error) {
|
||||
return (
|
||||
<div
|
||||
data-test="reference-chatbot-error"
|
||||
style={{
|
||||
padding: 12,
|
||||
border: '1px solid #f5222d',
|
||||
borderRadius: 6,
|
||||
background: '#fff1f0',
|
||||
color: '#a8071a',
|
||||
fontSize: 12,
|
||||
maxWidth: 320,
|
||||
}}
|
||||
>
|
||||
Reference chatbot crashed: {this.state.error.message}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
return <>{this.props.children}</>;
|
||||
}
|
||||
}
|
||||
@@ -1,307 +0,0 @@
|
||||
/**
|
||||
* Licensed to the Apache Software Foundation (ASF) under one
|
||||
* or more contributor license agreements. See the NOTICE file
|
||||
* distributed with this work for additional information
|
||||
* regarding copyright ownership. The ASF licenses this file
|
||||
* to you under the Apache License, Version 2.0 (the
|
||||
* "License"); you may not use this file except in compliance
|
||||
* with the License. You may obtain a copy of the License at
|
||||
*
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing,
|
||||
* software distributed under the License is distributed on an
|
||||
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
|
||||
* KIND, either express or implied. See the License for the
|
||||
* specific language governing permissions and limitations
|
||||
* under the License.
|
||||
*/
|
||||
import React, { useCallback, useEffect, useRef, useState } from 'react';
|
||||
import { streamReply } from '../streaming/mockStream';
|
||||
import { getPageContext, PageContext, subscribeToPageChanges } from '../context/pageContext';
|
||||
import { registerActiveController, unregisterActiveController } from '../streaming/registry';
|
||||
|
||||
interface Props {
|
||||
onClose: () => void;
|
||||
}
|
||||
|
||||
interface Message {
|
||||
id: number;
|
||||
from: 'user' | 'bot';
|
||||
text: string;
|
||||
}
|
||||
|
||||
let messageSeq = 0;
|
||||
|
||||
/**
|
||||
* Builds the full set of context fields the host exposes for the current
|
||||
* surface, as ordered [label, value] rows. Whatever the host provides for where
|
||||
* the user is, the panel shows — nothing is summarized away. Returns an empty
|
||||
* array for surfaces with no active entity (list/home pages), where the
|
||||
* `page:` line alone is the context.
|
||||
*/
|
||||
const contextRows = (ctx: PageContext): Array<[string, string]> => {
|
||||
const rows: Array<[string, string]> = [];
|
||||
const push = (label: string, value: unknown) => {
|
||||
if (value !== undefined && value !== null && value !== '') {
|
||||
rows.push([label, String(value)]);
|
||||
}
|
||||
};
|
||||
|
||||
const chart = ctx.chart as
|
||||
| {
|
||||
chartId?: number | null;
|
||||
chartName?: string | null;
|
||||
vizType?: string;
|
||||
datasourceId?: number | null;
|
||||
datasourceName?: string | null;
|
||||
}
|
||||
| undefined;
|
||||
if (chart) {
|
||||
push('chart', chart.chartName ?? (chart.chartId == null ? '(unsaved)' : ''));
|
||||
push('chartId', chart.chartId);
|
||||
push('viz', chart.vizType);
|
||||
push('datasource', chart.datasourceName);
|
||||
push('datasourceId', chart.datasourceId);
|
||||
}
|
||||
|
||||
const dashboard = ctx.dashboard as
|
||||
| { dashboardId?: number; title?: string; filters?: Array<{ label: string; value: unknown }> }
|
||||
| undefined;
|
||||
if (dashboard) {
|
||||
push('dashboard', dashboard.title);
|
||||
push('dashboardId', dashboard.dashboardId);
|
||||
const filters = dashboard.filters ?? [];
|
||||
if (filters.length) {
|
||||
push(
|
||||
'filters',
|
||||
filters.map(f => `${f.label}=${JSON.stringify(f.value)}`).join(', '),
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
const dataset = ctx.dataset as
|
||||
| {
|
||||
datasetId?: number;
|
||||
datasetName?: string;
|
||||
schema?: string | null;
|
||||
catalog?: string | null;
|
||||
databaseName?: string | null;
|
||||
isVirtual?: boolean;
|
||||
}
|
||||
| undefined;
|
||||
if (dataset) {
|
||||
push('dataset', dataset.datasetName);
|
||||
push('datasetId', dataset.datasetId);
|
||||
push('schema', dataset.schema);
|
||||
push('catalog', dataset.catalog);
|
||||
push('database', dataset.databaseName);
|
||||
if (typeof dataset.isVirtual === 'boolean') {
|
||||
push('virtual', dataset.isVirtual);
|
||||
}
|
||||
}
|
||||
|
||||
if (ctx.sqlLab) {
|
||||
push('tab', ctx.sqlLab.title);
|
||||
}
|
||||
|
||||
return rows;
|
||||
};
|
||||
|
||||
export const Panel: React.FC<Props> = ({ onClose }) => {
|
||||
const [input, setInput] = useState('');
|
||||
const [messages, setMessages] = useState<Message[]>([]);
|
||||
const [streaming, setStreaming] = useState(false);
|
||||
const [pageContext, setPageContext] = useState<PageContext>(() => getPageContext());
|
||||
const controllerRef = useRef<AbortController | null>(null);
|
||||
|
||||
useEffect(
|
||||
() => subscribeToPageChanges(() => setPageContext(getPageContext())),
|
||||
[],
|
||||
);
|
||||
|
||||
useEffect(
|
||||
() => () => {
|
||||
// Component unmount cancels any in-flight stream.
|
||||
controllerRef.current?.abort();
|
||||
},
|
||||
[],
|
||||
);
|
||||
|
||||
const send = useCallback(async () => {
|
||||
const prompt = input.trim();
|
||||
if (!prompt || streaming) return;
|
||||
setInput('');
|
||||
const userMsg: Message = { id: ++messageSeq, from: 'user', text: prompt };
|
||||
const botMsg: Message = { id: ++messageSeq, from: 'bot', text: '' };
|
||||
setMessages(prev => [...prev, userMsg, botMsg]);
|
||||
setStreaming(true);
|
||||
|
||||
const controller = new AbortController();
|
||||
controllerRef.current = controller;
|
||||
registerActiveController(controller);
|
||||
|
||||
try {
|
||||
for await (const token of streamReply(prompt, controller.signal)) {
|
||||
setMessages(prev =>
|
||||
prev.map(m => (m.id === botMsg.id ? { ...m, text: m.text + token } : m)),
|
||||
);
|
||||
}
|
||||
} finally {
|
||||
unregisterActiveController(controller);
|
||||
controllerRef.current = null;
|
||||
setStreaming(false);
|
||||
}
|
||||
}, [input, streaming]);
|
||||
|
||||
const cancel = useCallback(() => {
|
||||
controllerRef.current?.abort();
|
||||
}, []);
|
||||
|
||||
return (
|
||||
<div
|
||||
data-test="reference-chatbot-panel"
|
||||
style={{
|
||||
width: 360,
|
||||
maxHeight: 480,
|
||||
display: 'flex',
|
||||
flexDirection: 'column',
|
||||
background: '#fff',
|
||||
border: '1px solid #d9d9d9',
|
||||
borderRadius: 8,
|
||||
boxShadow: '0 8px 24px rgba(0,0,0,0.18)',
|
||||
overflow: 'hidden',
|
||||
fontSize: 13,
|
||||
}}
|
||||
>
|
||||
<header
|
||||
style={{
|
||||
padding: '8px 12px',
|
||||
background: '#1f6feb',
|
||||
color: '#fff',
|
||||
display: 'flex',
|
||||
justifyContent: 'space-between',
|
||||
alignItems: 'center',
|
||||
}}
|
||||
>
|
||||
<span>Reference Chatbot</span>
|
||||
<button
|
||||
type="button"
|
||||
onClick={onClose}
|
||||
aria-label="Close chatbot"
|
||||
data-test="reference-chatbot-close"
|
||||
style={{
|
||||
background: 'transparent',
|
||||
border: 'none',
|
||||
color: '#fff',
|
||||
fontSize: 16,
|
||||
cursor: 'pointer',
|
||||
}}
|
||||
>
|
||||
×
|
||||
</button>
|
||||
</header>
|
||||
|
||||
<div
|
||||
data-test="reference-chatbot-context"
|
||||
style={{
|
||||
padding: '6px 12px',
|
||||
background: '#f6f8fa',
|
||||
borderBottom: '1px solid #eaecef',
|
||||
fontFamily: 'monospace',
|
||||
fontSize: 11,
|
||||
color: '#57606a',
|
||||
wordBreak: 'break-all',
|
||||
}}
|
||||
>
|
||||
<div>page: {pageContext.pageType}</div>
|
||||
{contextRows(pageContext).map(([label, value]) => (
|
||||
<div key={label}>
|
||||
{label}: {value}
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
|
||||
<div style={{ flex: 1, overflowY: 'auto', padding: 12 }}>
|
||||
{messages.length === 0 && (
|
||||
<p style={{ color: '#8c8c8c' }}>
|
||||
Ask anything — replies are canned tokens streamed by the reference extension.
|
||||
</p>
|
||||
)}
|
||||
{messages.map(m => (
|
||||
<div
|
||||
key={m.id}
|
||||
data-test={`reference-chatbot-msg-${m.from}`}
|
||||
style={{
|
||||
margin: '6px 0',
|
||||
textAlign: m.from === 'user' ? 'right' : 'left',
|
||||
}}
|
||||
>
|
||||
<span
|
||||
style={{
|
||||
display: 'inline-block',
|
||||
padding: '4px 8px',
|
||||
borderRadius: 6,
|
||||
background: m.from === 'user' ? '#1f6feb' : '#eef0f3',
|
||||
color: m.from === 'user' ? '#fff' : '#1f2328',
|
||||
maxWidth: '85%',
|
||||
whiteSpace: 'pre-wrap',
|
||||
}}
|
||||
>
|
||||
{m.text || '…'}
|
||||
</span>
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
|
||||
<footer
|
||||
style={{
|
||||
padding: 8,
|
||||
borderTop: '1px solid #eaecef',
|
||||
display: 'flex',
|
||||
gap: 6,
|
||||
}}
|
||||
>
|
||||
<input
|
||||
aria-label="Chat input"
|
||||
data-test="reference-chatbot-input"
|
||||
value={input}
|
||||
onChange={e => setInput(e.target.value)}
|
||||
onKeyDown={e => {
|
||||
if (e.key === 'Enter' && !e.shiftKey) {
|
||||
e.preventDefault();
|
||||
send();
|
||||
}
|
||||
}}
|
||||
placeholder="Type a message"
|
||||
style={{
|
||||
flex: 1,
|
||||
padding: '4px 8px',
|
||||
border: '1px solid #d9d9d9',
|
||||
borderRadius: 4,
|
||||
}}
|
||||
/>
|
||||
{streaming ? (
|
||||
<button
|
||||
type="button"
|
||||
onClick={cancel}
|
||||
data-test="reference-chatbot-cancel"
|
||||
style={{ padding: '4px 10px' }}
|
||||
>
|
||||
Stop
|
||||
</button>
|
||||
) : (
|
||||
<button
|
||||
type="button"
|
||||
onClick={send}
|
||||
data-test="reference-chatbot-send"
|
||||
disabled={!input.trim()}
|
||||
style={{ padding: '4px 10px' }}
|
||||
>
|
||||
Send
|
||||
</button>
|
||||
)}
|
||||
</footer>
|
||||
</div>
|
||||
);
|
||||
};
|
||||
@@ -1,159 +0,0 @@
|
||||
/**
|
||||
* Licensed to the Apache Software Foundation (ASF) under one
|
||||
* or more contributor license agreements. See the NOTICE file
|
||||
* distributed with this work for additional information
|
||||
* regarding copyright ownership. The ASF licenses this file
|
||||
* to you under the Apache License, Version 2.0 (the
|
||||
* "License"); you may not use this file except in compliance
|
||||
* with the License. You may obtain a copy of the License at
|
||||
*
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing,
|
||||
* software distributed under the License is distributed on an
|
||||
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
|
||||
* KIND, either express or implied. See the License for the
|
||||
* specific language governing permissions and limitations
|
||||
* under the License.
|
||||
*/
|
||||
|
||||
/**
|
||||
* Single integration seam for the P3 namespaces.
|
||||
*
|
||||
* Each surface namespace is consumed via a try/catch — the host may ship a
|
||||
* version where a namespace function is declared but not yet implemented at
|
||||
* runtime, and the reference extension must keep working in that case. As
|
||||
* each namespace lights up on the host, that branch starts returning real
|
||||
* data without any change here.
|
||||
*
|
||||
* Route inference is the fallback when navigation.getPageType() is absent.
|
||||
*/
|
||||
|
||||
import * as core from '@apache-superset/core';
|
||||
|
||||
export type PageType =
|
||||
| 'home'
|
||||
| 'dashboard'
|
||||
| 'dashboard_list'
|
||||
| 'chart'
|
||||
| 'chart_list'
|
||||
| 'sqllab'
|
||||
| 'query_history'
|
||||
| 'saved_queries'
|
||||
| 'dataset'
|
||||
| 'dataset_list'
|
||||
| 'unknown';
|
||||
|
||||
export interface PageContext {
|
||||
pageType: PageType;
|
||||
dashboard?: unknown;
|
||||
chart?: unknown;
|
||||
dataset?: unknown;
|
||||
sqlLab?: { tabId: string; title: string };
|
||||
href: string;
|
||||
}
|
||||
|
||||
const tryCall = <T>(fn: () => T | undefined): T | undefined => {
|
||||
try {
|
||||
return fn();
|
||||
} catch {
|
||||
return undefined;
|
||||
}
|
||||
};
|
||||
|
||||
const inferPageType = (pathname: string): PageType => {
|
||||
if (pathname.startsWith('/sqllab/history')) return 'query_history';
|
||||
if (pathname.startsWith('/savedqueryview/list')) return 'saved_queries';
|
||||
if (pathname.startsWith('/sqllab')) return 'sqllab';
|
||||
if (pathname.startsWith('/dashboard/list')) return 'dashboard_list';
|
||||
if (
|
||||
pathname.startsWith('/superset/dashboard') ||
|
||||
pathname.startsWith('/dashboard')
|
||||
)
|
||||
return 'dashboard';
|
||||
if (pathname.startsWith('/chart/list')) return 'chart_list';
|
||||
if (pathname.startsWith('/explore') || pathname.startsWith('/chart'))
|
||||
return 'chart';
|
||||
if (pathname.startsWith('/tablemodelview/list')) return 'dataset_list';
|
||||
if (pathname.startsWith('/tablemodelview') || pathname.startsWith('/dataset'))
|
||||
return 'dataset';
|
||||
if (pathname === '/' || pathname.startsWith('/superset/welcome'))
|
||||
return 'home';
|
||||
return 'unknown';
|
||||
};
|
||||
|
||||
const readSqlLabTab = (): PageContext['sqlLab'] => {
|
||||
const tab = tryCall(() => (core as any).sqlLab?.getCurrentTab?.());
|
||||
return tab ? { tabId: tab.id, title: tab.title } : undefined;
|
||||
};
|
||||
|
||||
const readPageType = (pathname: string): PageType => {
|
||||
const fromNav = tryCall(() => (core as any).navigation?.getPageType?.());
|
||||
return (fromNav as PageType | undefined) ?? inferPageType(pathname);
|
||||
};
|
||||
|
||||
/**
|
||||
* Subscribe to page-context changes and invoke `onChange` whenever any part of
|
||||
* the context may have changed. Returns a cleanup function.
|
||||
*
|
||||
* Three classes of change are watched:
|
||||
* - Navigation (`navigation.onDidChangePage`, or `popstate` as a fallback for
|
||||
* hosts without the namespace) — the user moved to a different surface.
|
||||
* - Entity hydration (`explore.onDidChangeChart`, `dashboard.onDidChangeDashboard`,
|
||||
* `dataset.onDidChangeDataset`) — the surface's entity loaded or changed
|
||||
* *after* navigation settled. This matters because a surface (notably Explore)
|
||||
* can finish hydrating several seconds after the route change fires, so a
|
||||
* navigation-only subscription would read empty entity context and never
|
||||
* refresh once the real data arrives.
|
||||
* - In-surface SQL Lab changes (`sqlLab.onDidChangeActiveTab`,
|
||||
* `sqlLab.onDidChangeTabTitle`) — switching or renaming a tab does not change
|
||||
* the route, so without these the panel would keep showing the first tab.
|
||||
*/
|
||||
export const subscribeToPageChanges = (onChange: () => void): (() => void) => {
|
||||
const disposers: Array<() => void> = [];
|
||||
|
||||
const nav = tryCall(() => (core as any).navigation);
|
||||
if (nav?.onDidChangePage) {
|
||||
const sub = nav.onDidChangePage(onChange);
|
||||
disposers.push(() => sub.dispose());
|
||||
} else {
|
||||
window.addEventListener('popstate', onChange);
|
||||
disposers.push(() => window.removeEventListener('popstate', onChange));
|
||||
}
|
||||
|
||||
// Entity-context change events. Each is optional — a host may not implement a
|
||||
// given namespace yet — so subscribe defensively and collect any disposer.
|
||||
const subscribeEntity = (
|
||||
getNamespace: () => any,
|
||||
method: string,
|
||||
): void => {
|
||||
const sub = tryCall(() => getNamespace()?.[method]?.(onChange));
|
||||
if (sub?.dispose) {
|
||||
disposers.push(() => sub.dispose());
|
||||
}
|
||||
};
|
||||
subscribeEntity(() => (core as any).explore, 'onDidChangeChart');
|
||||
subscribeEntity(() => (core as any).dashboard, 'onDidChangeDashboard');
|
||||
subscribeEntity(() => (core as any).dataset, 'onDidChangeDataset');
|
||||
// SQL Lab tab switches/renames happen without a route change.
|
||||
subscribeEntity(() => (core as any).sqlLab, 'onDidChangeActiveTab');
|
||||
subscribeEntity(() => (core as any).sqlLab, 'onDidChangeTabTitle');
|
||||
|
||||
return () => disposers.forEach(dispose => dispose());
|
||||
};
|
||||
|
||||
export const getPageContext = (): PageContext => {
|
||||
const { pathname, href } =
|
||||
typeof window !== 'undefined'
|
||||
? window.location
|
||||
: { pathname: '', href: '' };
|
||||
|
||||
return {
|
||||
pageType: readPageType(pathname),
|
||||
dashboard: tryCall(() => (core as any).dashboard?.getCurrentDashboard?.()),
|
||||
chart: tryCall(() => (core as any).explore?.getCurrentChart?.()),
|
||||
dataset: tryCall(() => (core as any).dataset?.getCurrentDataset?.()),
|
||||
sqlLab: readSqlLabTab(),
|
||||
href,
|
||||
};
|
||||
};
|
||||
@@ -1,57 +0,0 @@
|
||||
/**
|
||||
* Licensed to the Apache Software Foundation (ASF) under one
|
||||
* or more contributor license agreements. See the NOTICE file
|
||||
* distributed with this work for additional information
|
||||
* regarding copyright ownership. The ASF licenses this file
|
||||
* to you under the Apache License, Version 2.0 (the
|
||||
* "License"); you may not use this file except in compliance
|
||||
* with the License. You may obtain a copy of the License at
|
||||
*
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing,
|
||||
* software distributed under the License is distributed on an
|
||||
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
|
||||
* KIND, either express or implied. See the License for the
|
||||
* specific language governing permissions and limitations
|
||||
* under the License.
|
||||
*/
|
||||
|
||||
/**
|
||||
* Module-scoped open/closed state plus a tiny emitter the UI subscribes to.
|
||||
*
|
||||
* Lives entirely inside the extension — never reaches into the host store.
|
||||
* Reset on dispose so re-activation starts cleanly.
|
||||
*/
|
||||
|
||||
export type OpenStateListener = (open: boolean) => void;
|
||||
|
||||
let open = false;
|
||||
const listeners = new Set<OpenStateListener>();
|
||||
|
||||
export const isOpen = (): boolean => open;
|
||||
|
||||
export const setOpen = (next: boolean): void => {
|
||||
if (next === open) return;
|
||||
open = next;
|
||||
listeners.forEach(fn => {
|
||||
try {
|
||||
fn(open);
|
||||
} catch {
|
||||
// A listener throwing must not block other listeners or flip our state back.
|
||||
}
|
||||
});
|
||||
};
|
||||
|
||||
export const subscribe = (fn: OpenStateListener): (() => void) => {
|
||||
listeners.add(fn);
|
||||
return () => {
|
||||
listeners.delete(fn);
|
||||
};
|
||||
};
|
||||
|
||||
/** Drains listeners and resets state. Called from the master Disposable. */
|
||||
export const resetState = (): void => {
|
||||
open = false;
|
||||
listeners.clear();
|
||||
};
|
||||
@@ -1,73 +0,0 @@
|
||||
/**
|
||||
* Licensed to the Apache Software Foundation (ASF) under one
|
||||
* or more contributor license agreements. See the NOTICE file
|
||||
* distributed with this work for additional information
|
||||
* regarding copyright ownership. The ASF licenses this file
|
||||
* to you under the Apache License, Version 2.0 (the
|
||||
* "License"); you may not use this file except in compliance
|
||||
* with the License. You may obtain a copy of the License at
|
||||
*
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing,
|
||||
* software distributed under the License is distributed on an
|
||||
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
|
||||
* KIND, either express or implied. See the License for the
|
||||
* specific language governing permissions and limitations
|
||||
* under the License.
|
||||
*/
|
||||
|
||||
/**
|
||||
* Mock streaming reply used to validate stream teardown semantics.
|
||||
*
|
||||
* The reference chatbot is environment-validation only — there is no LLM.
|
||||
* This iterator yields canned tokens on a timer and exits cleanly when its
|
||||
* AbortSignal is fired. Disposal of the extension aborts any in-flight
|
||||
* controller, which is the contract that proves async cancellation works.
|
||||
*/
|
||||
|
||||
const TICK_MS = 40;
|
||||
|
||||
const buildReply = (prompt: string): string => {
|
||||
const trimmed = prompt.trim();
|
||||
if (!trimmed) {
|
||||
return 'Reference chatbot online. Send a message to validate streaming.';
|
||||
}
|
||||
return (
|
||||
`[reference-chatbot] received "${trimmed}". ` +
|
||||
'Streaming token-by-token to validate cancellation and teardown.'
|
||||
);
|
||||
};
|
||||
|
||||
const sleep = (ms: number, signal: AbortSignal): Promise<void> =>
|
||||
new Promise((resolve, reject) => {
|
||||
if (signal.aborted) {
|
||||
reject(new DOMException('aborted', 'AbortError'));
|
||||
return;
|
||||
}
|
||||
const timer = setTimeout(() => {
|
||||
signal.removeEventListener('abort', onAbort);
|
||||
resolve();
|
||||
}, ms);
|
||||
const onAbort = () => {
|
||||
clearTimeout(timer);
|
||||
reject(new DOMException('aborted', 'AbortError'));
|
||||
};
|
||||
signal.addEventListener('abort', onAbort, { once: true });
|
||||
});
|
||||
|
||||
export async function* streamReply(
|
||||
prompt: string,
|
||||
signal: AbortSignal,
|
||||
): AsyncIterableIterator<string> {
|
||||
const tokens = buildReply(prompt).split(/(\s+)/);
|
||||
for (const token of tokens) {
|
||||
if (signal.aborted) return;
|
||||
try {
|
||||
await sleep(TICK_MS, signal);
|
||||
} catch {
|
||||
return;
|
||||
}
|
||||
yield token;
|
||||
}
|
||||
}
|
||||
@@ -1,46 +0,0 @@
|
||||
/**
|
||||
* Licensed to the Apache Software Foundation (ASF) under one
|
||||
* or more contributor license agreements. See the NOTICE file
|
||||
* distributed with this work for additional information
|
||||
* regarding copyright ownership. The ASF licenses this file
|
||||
* to you under the Apache License, Version 2.0 (the
|
||||
* "License"); you may not use this file except in compliance
|
||||
* with the License. You may obtain a copy of the License at
|
||||
*
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing,
|
||||
* software distributed under the License is distributed on an
|
||||
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
|
||||
* KIND, either express or implied. See the License for the
|
||||
* specific language governing permissions and limitations
|
||||
* under the License.
|
||||
*/
|
||||
|
||||
/**
|
||||
* Module-scoped registry of in-flight stream AbortControllers.
|
||||
*
|
||||
* Lets the master Disposable abort any running stream even when the panel
|
||||
* is unmounted by a route change or by re-activation of the extension.
|
||||
*/
|
||||
|
||||
const active = new Set<AbortController>();
|
||||
|
||||
export const registerActiveController = (c: AbortController): void => {
|
||||
active.add(c);
|
||||
};
|
||||
|
||||
export const unregisterActiveController = (c: AbortController): void => {
|
||||
active.delete(c);
|
||||
};
|
||||
|
||||
export const abortAllActiveControllers = (): void => {
|
||||
active.forEach(c => {
|
||||
try {
|
||||
c.abort();
|
||||
} catch {
|
||||
// ignore — abort() should not throw, but stay defensive.
|
||||
}
|
||||
});
|
||||
active.clear();
|
||||
};
|
||||
@@ -1,16 +0,0 @@
|
||||
{
|
||||
"compilerOptions": {
|
||||
"target": "es2019",
|
||||
"module": "esnext",
|
||||
"moduleResolution": "node",
|
||||
"jsx": "react",
|
||||
"strict": true,
|
||||
"noImplicitAny": true,
|
||||
"esModuleInterop": true,
|
||||
"skipLibCheck": true,
|
||||
"forceConsistentCasingInFileNames": true,
|
||||
"lib": ["dom", "es2019"]
|
||||
},
|
||||
"include": ["src"],
|
||||
"exclude": ["src/**/*.test.ts", "src/**/*.test.tsx", "src/__tests__"]
|
||||
}
|
||||
@@ -1,16 +0,0 @@
|
||||
{
|
||||
"extends": "./tsconfig.json",
|
||||
"compilerOptions": {
|
||||
"baseUrl": ".",
|
||||
"paths": {
|
||||
"@apache-superset/core": ["src/__tests__/sdkMock.ts"]
|
||||
},
|
||||
"typeRoots": [
|
||||
"./node_modules/@types",
|
||||
"../../superset-frontend/node_modules/@types"
|
||||
],
|
||||
"types": ["jest", "node"]
|
||||
},
|
||||
"include": ["src"],
|
||||
"exclude": []
|
||||
}
|
||||
@@ -1,108 +0,0 @@
|
||||
/**
|
||||
* Licensed to the Apache Software Foundation (ASF) under one
|
||||
* or more contributor license agreements. See the NOTICE file
|
||||
* distributed with this work for additional information
|
||||
* regarding copyright ownership. The ASF licenses this file
|
||||
* to you under the Apache License, Version 2.0 (the
|
||||
* "License"); you may not use this file except in compliance
|
||||
* with the License. You may obtain a copy of the License at
|
||||
*
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing,
|
||||
* software distributed under the License is distributed on an
|
||||
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
|
||||
* KIND, either express or implied. See the License for the
|
||||
* specific language governing permissions and limitations
|
||||
* under the License.
|
||||
*/
|
||||
const path = require('path');
|
||||
const fs = require('fs');
|
||||
const { ModuleFederationPlugin } = require('webpack').container;
|
||||
const packageConfig = require('./package.json');
|
||||
const extensionConfig = require('./extension.json');
|
||||
|
||||
const MODULE_FEDERATION_NAME = 'apacheSuperset_referenceChatbot';
|
||||
|
||||
/**
|
||||
* Emits the `manifest.json` the host reads from the extension `dist/` root.
|
||||
*
|
||||
* The host (`superset/extensions/utils.py`) expects an extension dist laid out
|
||||
* as `dist/manifest.json` plus the federated bundle under `dist/frontend/dist/`.
|
||||
* The manifest carries `extension.json` verbatim, plus the composite `id` and a
|
||||
* `frontend` block naming the content-hashed `remoteEntry` so the host can load
|
||||
* the right file. Because the hash is only known after the build, the manifest
|
||||
* is written from the final asset names rather than checked in.
|
||||
*/
|
||||
class EmitManifestPlugin {
|
||||
apply(compiler) {
|
||||
compiler.hooks.afterEmit.tap('EmitManifestPlugin', compilation => {
|
||||
const assets = Object.keys(compilation.assets);
|
||||
const remoteEntry = assets.find(name => /^remoteEntry\..*\.js$/.test(name));
|
||||
if (!remoteEntry) {
|
||||
throw new Error('EmitManifestPlugin: no remoteEntry asset was emitted');
|
||||
}
|
||||
const manifest = {
|
||||
...extensionConfig,
|
||||
id: `${extensionConfig.publisher}.${extensionConfig.name}`,
|
||||
frontend: {
|
||||
remoteEntry,
|
||||
moduleFederationName: MODULE_FEDERATION_NAME,
|
||||
},
|
||||
};
|
||||
fs.writeFileSync(
|
||||
path.resolve(__dirname, 'dist', 'manifest.json'),
|
||||
`${JSON.stringify(manifest, null, 2)}\n`,
|
||||
);
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
module.exports = (env, argv) => {
|
||||
const isProd = argv.mode === 'production';
|
||||
|
||||
return {
|
||||
entry: isProd ? {} : './src/index.tsx',
|
||||
mode: isProd ? 'production' : 'development',
|
||||
devtool: isProd ? false : 'eval-cheap-module-source-map',
|
||||
devServer: {
|
||||
port: 3030,
|
||||
headers: { 'Access-Control-Allow-Origin': '*' },
|
||||
},
|
||||
output: {
|
||||
clean: true,
|
||||
filename: isProd ? undefined : '[name].[contenthash].js',
|
||||
chunkFilename: '[name].[contenthash].js',
|
||||
path: path.resolve(__dirname, 'dist', 'frontend', 'dist'),
|
||||
publicPath: `/api/v1/extensions/${extensionConfig.publisher}/${extensionConfig.name}/`,
|
||||
},
|
||||
resolve: { extensions: ['.ts', '.tsx', '.js', '.jsx'] },
|
||||
externalsType: 'window',
|
||||
externals: { '@apache-superset/core': 'superset' },
|
||||
module: {
|
||||
rules: [
|
||||
{ test: /\.tsx?$/, use: 'ts-loader', exclude: /node_modules/ },
|
||||
],
|
||||
},
|
||||
plugins: [
|
||||
new ModuleFederationPlugin({
|
||||
name: MODULE_FEDERATION_NAME,
|
||||
filename: 'remoteEntry.[contenthash].js',
|
||||
exposes: { './index': './src/index.tsx' },
|
||||
shared: {
|
||||
react: {
|
||||
singleton: true,
|
||||
requiredVersion: packageConfig.peerDependencies.react,
|
||||
import: false,
|
||||
},
|
||||
'react-dom': {
|
||||
singleton: true,
|
||||
requiredVersion: packageConfig.peerDependencies['react-dom'],
|
||||
import: false,
|
||||
},
|
||||
},
|
||||
}),
|
||||
new EmitManifestPlugin(),
|
||||
],
|
||||
};
|
||||
};
|
||||
@@ -1,138 +0,0 @@
|
||||
<!--
|
||||
Licensed to the Apache Software Foundation (ASF) under one
|
||||
or more contributor license agreements. See the NOTICE file
|
||||
distributed with this work for additional information
|
||||
regarding copyright ownership. The ASF licenses this file
|
||||
to you under the Apache License, Version 2.0 (the
|
||||
"License"); you may not use this file except in compliance
|
||||
with the License. You may obtain a copy of the License at
|
||||
|
||||
http://www.apache.org/licenses/LICENSE-2.0
|
||||
|
||||
Unless required by applicable law or agreed to in writing,
|
||||
software distributed under the License is distributed on an
|
||||
"AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
|
||||
KIND, either express or implied. See the License for the
|
||||
specific language governing permissions and limitations
|
||||
under the License.
|
||||
-->
|
||||
|
||||
# Reference Chatbot Extension
|
||||
|
||||
Canonical environment-validation extension for the `superset.chatbot`
|
||||
contribution area. **Not** a product chatbot — there is no LLM, no backend,
|
||||
no persistence. Its purpose is to exercise the extension platform end-to-end:
|
||||
|
||||
- `views.registerView` at `superset.chatbot` (singleton resolution)
|
||||
- Lifecycle activation + a master disposable that tears down everything
|
||||
- `commands.registerCommand` for `core.chatbot__open|close|toggle`
|
||||
- Mock streaming with `AbortController` cancellation on dispose
|
||||
- Defense-in-depth React error boundary inside the panel
|
||||
- A single P3 page-context seam that lights up automatically as the
|
||||
`dashboard` / `explore` / `dataset` / `navigation` namespaces become
|
||||
available at runtime on the host
|
||||
|
||||
It is intended as the reference implementation third-party chatbot extension
|
||||
authors copy. Anything that ships as host-internal (the mount point, the
|
||||
admin picker, the `getActiveChatbot` resolver) is **not** here — see the
|
||||
host side at `superset-frontend/src/components/ChatbotMount/` and
|
||||
`superset-frontend/src/core/chatbot/`.
|
||||
|
||||
## Layout
|
||||
|
||||
```
|
||||
extensions/chat/
|
||||
├── extension.json Manifest (app.chatbot view + commands)
|
||||
├── package.json
|
||||
├── tsconfig.json
|
||||
├── webpack.config.js ModuleFederation → window.superset
|
||||
├── jest.config.js Self-contained unit tests
|
||||
└── src/
|
||||
├── index.tsx MF entry — calls activate() once
|
||||
├── activate.ts Returns master disposable
|
||||
├── commands.ts core.chatbot__open|close|toggle
|
||||
├── state.ts Module-scoped open/closed + emitter
|
||||
├── ReferenceChatbot.tsx Root component (bubble ↔ panel)
|
||||
├── components/
|
||||
│ ├── Bubble.tsx
|
||||
│ ├── Panel.tsx
|
||||
│ └── ErrorBoundary.tsx
|
||||
├── streaming/
|
||||
│ ├── mockStream.ts AsyncIterable<string> + AbortSignal
|
||||
│ └── registry.ts Cross-component abort tracking
|
||||
├── context/
|
||||
│ └── pageContext.ts P3 namespace seam (defensive)
|
||||
└── __tests__/
|
||||
├── sdkMock.ts In-memory @apache-superset/core mock
|
||||
└── activate.test.tsx
|
||||
```
|
||||
|
||||
## Run the unit tests
|
||||
|
||||
```bash
|
||||
cd extensions/chat
|
||||
npm install # first time only
|
||||
npx jest
|
||||
```
|
||||
|
||||
The tests mock `@apache-superset/core` via `src/__tests__/sdkMock.ts` so they
|
||||
do not depend on host runtime wiring.
|
||||
|
||||
## Build / bundle for deployment
|
||||
|
||||
```bash
|
||||
# from the extension folder
|
||||
npm install
|
||||
npm run build
|
||||
|
||||
# packaging into a .supx is handled by the Superset extensions CLI
|
||||
pip install apache-superset-extensions-cli
|
||||
superset-extensions bundle # produces apache-superset.reference-chatbot-0.1.0.supx
|
||||
```
|
||||
|
||||
Drop the `.supx` into the `EXTENSIONS_PATH` of a Superset instance that has
|
||||
`FEATURE_FLAGS = { "ENABLE_EXTENSIONS": True }`.
|
||||
|
||||
## Selecting it as the active chatbot
|
||||
|
||||
The host's singleton picker reads `active_chatbot_id` from the admin
|
||||
settings endpoint (`/api/v1/extensions/settings`). Set it to:
|
||||
|
||||
```
|
||||
apache-superset.reference-chatbot
|
||||
```
|
||||
|
||||
If no admin selection exists, the host falls back to the first-to-register
|
||||
chatbot — installing this extension alone is enough for the bubble to appear.
|
||||
|
||||
## P3 integration seams
|
||||
|
||||
All page-context derivation lives in [`src/context/pageContext.ts`](src/context/pageContext.ts).
|
||||
Each namespace branch (`dashboard`, `explore`, `dataset`, `navigation`) is
|
||||
called defensively — when the host implementation lands, the returned value
|
||||
becomes non-undefined automatically with no other change in the extension.
|
||||
|
||||
The panel re-reads context on `popstate`. Once `navigation.onDidChangePage`
|
||||
is live on the host, the panel's `useEffect` should subscribe to it instead;
|
||||
that is the only file in the extension that needs to change for full P3
|
||||
context sync.
|
||||
|
||||
## Known intentional non-features
|
||||
|
||||
- No conversation persistence — by design (extension scope per SIP §2).
|
||||
- No real network. The mock stream is a `setTimeout` token emitter so the
|
||||
cancellation contract is exercised without external dependencies.
|
||||
- No keyboard shortcut binding (Cmd+K). Extensions own that, but it adds
|
||||
surface area not needed for platform validation.
|
||||
- No notification badge / icon mutation. SIP §3.2 recommends static icons;
|
||||
the bubble re-renders freely already.
|
||||
|
||||
## TODOs
|
||||
|
||||
- **P1**: if/when the host gains `deactivate(): Promise<void>`, wrap the
|
||||
master disposer in `activate.ts` to flush async work before returning.
|
||||
- **P3**: replace the `popstate` listener in `Panel.tsx` with
|
||||
`navigation.onDidChangePage` once that event is wired up host-side.
|
||||
- **P4**: if the host pre-registers `core.chatbot__*` as host-owned intents,
|
||||
swap `commands.registerCommand` for the implementation hook in
|
||||
`commands.ts`. Command IDs do not change.
|
||||
@@ -1,23 +0,0 @@
|
||||
{
|
||||
"publisher": "apache-superset",
|
||||
"name": "alt-chatbot",
|
||||
"displayName": "Alt Chatbot",
|
||||
"description": "Second chatbot for testing multi-chatbot selection in the superset.chatbot contribution area.",
|
||||
"version": "0.1.0",
|
||||
"license": "Apache-2.0",
|
||||
"permissions": [],
|
||||
"contributes": {
|
||||
"views": {
|
||||
"app": {
|
||||
"chatbot": [
|
||||
{
|
||||
"id": "apache-superset.alt-chatbot",
|
||||
"name": "Alt Chatbot",
|
||||
"description": "Second chatbot for testing singleton resolution.",
|
||||
"icon": "Star"
|
||||
}
|
||||
]
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,53 +0,0 @@
|
||||
/**
|
||||
* Licensed to the Apache Software Foundation (ASF) under one
|
||||
* or more contributor license agreements. See the NOTICE file
|
||||
* distributed with this work for additional information
|
||||
* regarding copyright ownership. The ASF licenses this file
|
||||
* to you under the Apache License, Version 2.0 (the
|
||||
* "License"); you may not use this file except in compliance
|
||||
* with the License. You may obtain a copy of the License at
|
||||
*
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing,
|
||||
* software distributed under the License is distributed on an
|
||||
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
|
||||
* KIND, either express or implied. See the License for the
|
||||
* specific language governing permissions and limitations
|
||||
* under the License.
|
||||
*/
|
||||
const path = require('path');
|
||||
|
||||
// When run as a standalone package (`cd extensions/chat && npm test`), modules
|
||||
// resolve from this folder's own node_modules. When run from the superset-frontend
|
||||
// workspace (CI, dev convenience), resolve ts-jest there too.
|
||||
const tsJest = (() => {
|
||||
try {
|
||||
require.resolve('ts-jest');
|
||||
return 'ts-jest';
|
||||
} catch {
|
||||
return path.resolve(
|
||||
__dirname,
|
||||
'..',
|
||||
'..',
|
||||
'superset-frontend',
|
||||
'node_modules',
|
||||
'ts-jest',
|
||||
);
|
||||
}
|
||||
})();
|
||||
|
||||
module.exports = {
|
||||
testEnvironment: 'jsdom',
|
||||
rootDir: __dirname,
|
||||
testMatch: ['<rootDir>/src/**/*.test.{ts,tsx}'],
|
||||
// When running from the extension folder without node_modules installed,
|
||||
// resolve react / react-dom from the superset-frontend workspace.
|
||||
modulePaths: [path.resolve(__dirname, '..', '..', 'superset-frontend', 'node_modules')],
|
||||
moduleNameMapper: {
|
||||
'^@apache-superset/core$': '<rootDir>/src/__tests__/sdkMock.ts',
|
||||
},
|
||||
transform: {
|
||||
'^.+\\.tsx?$': [tsJest, { tsconfig: '<rootDir>/tsconfig.test.json' }],
|
||||
},
|
||||
};
|
||||
@@ -1,26 +0,0 @@
|
||||
{
|
||||
"name": "@apache-superset/alt-chatbot",
|
||||
"version": "0.1.0",
|
||||
"private": true,
|
||||
"license": "Apache-2.0",
|
||||
"description": "Second chatbot extension for testing multi-chatbot selection in the Superset chatbot contribution area.",
|
||||
"scripts": {
|
||||
"start": "webpack serve --mode development",
|
||||
"build": "webpack --stats-error-details --mode production"
|
||||
},
|
||||
"peerDependencies": {
|
||||
"@apache-superset/core": "^0.1.0",
|
||||
"react": "^18.2.0",
|
||||
"react-dom": "^18.2.0"
|
||||
},
|
||||
"devDependencies": {
|
||||
"@apache-superset/core": "^0.1.0",
|
||||
"@types/react": "^18.2.0",
|
||||
"@types/react-dom": "^18.2.0",
|
||||
"ts-loader": "^9.5.0",
|
||||
"typescript": "^5.0.0",
|
||||
"webpack": "^5.0.0",
|
||||
"webpack-cli": "^5.0.0",
|
||||
"webpack-dev-server": "^5.0.0"
|
||||
}
|
||||
}
|
||||
@@ -1,46 +0,0 @@
|
||||
/**
|
||||
* Licensed to the Apache Software Foundation (ASF) under one
|
||||
* or more contributor license agreements. See the NOTICE file
|
||||
* distributed with this work for additional information
|
||||
* regarding copyright ownership. The ASF licenses this file
|
||||
* to you under the Apache License, Version 2.0 (the
|
||||
* "License"); you may not use this file except in compliance
|
||||
* with the License. You may obtain a copy of the License at
|
||||
*
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing,
|
||||
* software distributed under the License is distributed on an
|
||||
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
|
||||
* KIND, either express or implied. See the License for the
|
||||
* specific language governing permissions and limitations
|
||||
* under the License.
|
||||
*/
|
||||
import React, { useEffect, useState } from 'react';
|
||||
import { Bubble } from './components/Bubble';
|
||||
import { Panel } from './components/Panel';
|
||||
import { ExtensionErrorBoundary } from './components/ErrorBoundary';
|
||||
import { isOpen, setOpen, subscribe } from './state';
|
||||
|
||||
/**
|
||||
* Root extension component. Mirrors module-state into React via `subscribe`.
|
||||
*
|
||||
* Unlike the Reference Chatbot, Alt registers no `core.chatbot__*` commands
|
||||
* (those ids are globally owned by Reference), so the bubble↔panel transition
|
||||
* drives the local open-state directly via `setOpen`.
|
||||
*/
|
||||
export const ReferenceChatbot: React.FC = () => {
|
||||
const [open, setOpenState] = useState<boolean>(isOpen());
|
||||
|
||||
useEffect(() => subscribe(setOpenState), []);
|
||||
|
||||
return (
|
||||
<ExtensionErrorBoundary>
|
||||
{open ? (
|
||||
<Panel onClose={() => setOpen(false)} />
|
||||
) : (
|
||||
<Bubble onClick={() => setOpen(true)} />
|
||||
)}
|
||||
</ExtensionErrorBoundary>
|
||||
);
|
||||
};
|
||||
@@ -1,131 +0,0 @@
|
||||
/**
|
||||
* Licensed to the Apache Software Foundation (ASF) under one
|
||||
* or more contributor license agreements. See the NOTICE file
|
||||
* distributed with this work for additional information
|
||||
* regarding copyright ownership. The ASF licenses this file
|
||||
* to you under the Apache License, Version 2.0 (the
|
||||
* "License"); you may not use this file except in compliance
|
||||
* with the License. You may obtain a copy of the License at
|
||||
*
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing,
|
||||
* software distributed under the License is distributed on an
|
||||
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
|
||||
* KIND, either express or implied. See the License for the
|
||||
* specific language governing permissions and limitations
|
||||
* under the License.
|
||||
*/
|
||||
import { registry, reset } from './sdkMock';
|
||||
import { activate, VIEW_ID, CHATBOT_LOCATION } from '../activate';
|
||||
import { isOpen, setOpen } from '../state';
|
||||
import { streamReply } from '../streaming/mockStream';
|
||||
import {
|
||||
registerActiveController,
|
||||
unregisterActiveController,
|
||||
abortAllActiveControllers,
|
||||
} from '../streaming/registry';
|
||||
|
||||
beforeEach(() => {
|
||||
reset();
|
||||
});
|
||||
|
||||
test('registers one view at superset.chatbot and no commands', () => {
|
||||
const disposable = activate();
|
||||
|
||||
try {
|
||||
expect(registry.views.size).toBe(1);
|
||||
const entry = registry.views.get(VIEW_ID);
|
||||
expect(entry?.location).toBe(CHATBOT_LOCATION);
|
||||
expect(entry?.view.icon).toBe('Star');
|
||||
|
||||
// Alt Chatbot is view-only — the core.chatbot__* command ids are owned by
|
||||
// the Reference Chatbot, so Alt registers none of its own.
|
||||
expect(registry.commands.size).toBe(0);
|
||||
} finally {
|
||||
disposable.dispose();
|
||||
}
|
||||
});
|
||||
|
||||
test('setOpen drives open/close through module state', () => {
|
||||
const disposable = activate();
|
||||
try {
|
||||
expect(isOpen()).toBe(false);
|
||||
setOpen(true);
|
||||
expect(isOpen()).toBe(true);
|
||||
setOpen(false);
|
||||
expect(isOpen()).toBe(false);
|
||||
} finally {
|
||||
disposable.dispose();
|
||||
}
|
||||
});
|
||||
|
||||
test('disposing the master disposable unregisters the view', () => {
|
||||
const disposable = activate();
|
||||
expect(registry.views.size).toBe(1);
|
||||
|
||||
disposable.dispose();
|
||||
|
||||
expect(registry.views.size).toBe(0);
|
||||
expect(registry.commands.size).toBe(0);
|
||||
});
|
||||
|
||||
test('disposal is idempotent', () => {
|
||||
const disposable = activate();
|
||||
disposable.dispose();
|
||||
expect(() => disposable.dispose()).not.toThrow();
|
||||
expect(registry.views.size).toBe(0);
|
||||
});
|
||||
|
||||
test('re-activate after dispose works (validates replace semantics)', () => {
|
||||
const first = activate();
|
||||
first.dispose();
|
||||
|
||||
const second = activate();
|
||||
try {
|
||||
expect(registry.views.size).toBe(1);
|
||||
expect(isOpen()).toBe(false); // resetState() cleared open flag
|
||||
} finally {
|
||||
second.dispose();
|
||||
}
|
||||
});
|
||||
|
||||
test('aborting an active controller stops the stream cleanly', async () => {
|
||||
const controller = new AbortController();
|
||||
registerActiveController(controller);
|
||||
|
||||
const iter = streamReply('hello world', controller.signal);
|
||||
const received: string[] = [];
|
||||
|
||||
const consume = (async () => {
|
||||
for await (const tok of iter) received.push(tok);
|
||||
})();
|
||||
|
||||
// Abort after a single tick — the iterator must return without throwing.
|
||||
await new Promise(r => setTimeout(r, 50));
|
||||
abortAllActiveControllers();
|
||||
await expect(consume).resolves.toBeUndefined();
|
||||
|
||||
unregisterActiveController(controller);
|
||||
expect(received.length).toBeLessThan(20); // would be ~20+ tokens if uncancelled
|
||||
});
|
||||
|
||||
test('disposing the extension aborts any in-flight controller', async () => {
|
||||
const disposable = activate();
|
||||
const controller = new AbortController();
|
||||
registerActiveController(controller);
|
||||
|
||||
const iter = streamReply('a longer prompt to ensure many tokens', controller.signal);
|
||||
const consume = (async () => {
|
||||
// eslint-disable-next-line no-unused-vars, @typescript-eslint/no-unused-vars
|
||||
for await (const _tok of iter) {
|
||||
// drain
|
||||
}
|
||||
})();
|
||||
|
||||
await new Promise(r => setTimeout(r, 30));
|
||||
disposable.dispose();
|
||||
|
||||
await expect(consume).resolves.toBeUndefined();
|
||||
expect(controller.signal.aborted).toBe(true);
|
||||
});
|
||||
@@ -1,119 +0,0 @@
|
||||
/**
|
||||
* Licensed to the Apache Software Foundation (ASF) under one
|
||||
* or more contributor license agreements. See the NOTICE file
|
||||
* distributed with this work for additional information
|
||||
* regarding copyright ownership. The ASF licenses this file
|
||||
* to you under the Apache License, Version 2.0 (the
|
||||
* "License"); you may not use this file except in compliance
|
||||
* with the License. You may obtain a copy of the License at
|
||||
*
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing,
|
||||
* software distributed under the License is distributed on an
|
||||
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
|
||||
* KIND, either express or implied. See the License for the
|
||||
* specific language governing permissions and limitations
|
||||
* under the License.
|
||||
*/
|
||||
|
||||
/**
|
||||
* In-memory mock of `@apache-superset/core` for unit-testing the extension.
|
||||
*
|
||||
* Mirrors only the surfaces the reference chatbot consumes:
|
||||
* - views.registerView returns a disposable that removes the view
|
||||
* - commands.registerCommand / executeCommand round-trip handlers
|
||||
* - sqlLab.getCurrentTab returns undefined (no SQL Lab in tests)
|
||||
*
|
||||
* The mock is intentionally observable: tests can read `registry.views` and
|
||||
* `registry.commands` to assert contract compliance.
|
||||
*/
|
||||
|
||||
import type { ReactElement } from 'react';
|
||||
|
||||
type Provider = () => ReactElement;
|
||||
|
||||
interface ViewDescriptor {
|
||||
id: string;
|
||||
name: string;
|
||||
icon?: string;
|
||||
description?: string;
|
||||
}
|
||||
|
||||
interface DisposableLike {
|
||||
dispose(): void;
|
||||
}
|
||||
|
||||
interface RegisteredView {
|
||||
view: ViewDescriptor;
|
||||
location: string;
|
||||
provider: Provider;
|
||||
}
|
||||
|
||||
interface RegisteredCommand {
|
||||
id: string;
|
||||
title: string;
|
||||
handler: (...args: any[]) => any;
|
||||
}
|
||||
|
||||
export const registry = {
|
||||
views: new Map<string, RegisteredView>(),
|
||||
commands: new Map<string, RegisteredCommand>(),
|
||||
};
|
||||
|
||||
export const reset = (): void => {
|
||||
registry.views.clear();
|
||||
registry.commands.clear();
|
||||
};
|
||||
|
||||
export const views = {
|
||||
registerView(
|
||||
view: ViewDescriptor,
|
||||
location: string,
|
||||
provider: Provider,
|
||||
): DisposableLike {
|
||||
registry.views.set(view.id, { view, location, provider });
|
||||
return {
|
||||
dispose: () => {
|
||||
registry.views.delete(view.id);
|
||||
},
|
||||
};
|
||||
},
|
||||
getViews(location: string) {
|
||||
return Array.from(registry.views.values())
|
||||
.filter(v => v.location === location)
|
||||
.map(v => v.view);
|
||||
},
|
||||
};
|
||||
|
||||
export const commands = {
|
||||
registerCommand(
|
||||
command: { id: string; title: string },
|
||||
handler: (...args: any[]) => any,
|
||||
): DisposableLike {
|
||||
registry.commands.set(command.id, {
|
||||
id: command.id,
|
||||
title: command.title,
|
||||
handler,
|
||||
});
|
||||
return {
|
||||
dispose: () => {
|
||||
registry.commands.delete(command.id);
|
||||
},
|
||||
};
|
||||
},
|
||||
async executeCommand(id: string, ...rest: any[]): Promise<unknown> {
|
||||
const cmd = registry.commands.get(id);
|
||||
return cmd?.handler(...rest);
|
||||
},
|
||||
getCommands() {
|
||||
return Array.from(registry.commands.values()).map(c => ({
|
||||
id: c.id,
|
||||
title: c.title,
|
||||
}));
|
||||
},
|
||||
};
|
||||
|
||||
export const sqlLab = {
|
||||
getCurrentTab: () => undefined,
|
||||
};
|
||||
@@ -1,83 +0,0 @@
|
||||
/**
|
||||
* Licensed to the Apache Software Foundation (ASF) under one
|
||||
* or more contributor license agreements. See the NOTICE file
|
||||
* distributed with this work for additional information
|
||||
* regarding copyright ownership. The ASF licenses this file
|
||||
* to you under the Apache License, Version 2.0 (the
|
||||
* "License"); you may not use this file except in compliance
|
||||
* with the License. You may obtain a copy of the License at
|
||||
*
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing,
|
||||
* software distributed under the License is distributed on an
|
||||
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
|
||||
* KIND, either express or implied. See the License for the
|
||||
* specific language governing permissions and limitations
|
||||
* under the License.
|
||||
*/
|
||||
import React from 'react';
|
||||
import { views } from '@apache-superset/core';
|
||||
import { ReferenceChatbot } from './ReferenceChatbot';
|
||||
import { abortAllActiveControllers } from './streaming/registry';
|
||||
import { resetState } from './state';
|
||||
|
||||
export const VIEW_ID = 'apache-superset.alt-chatbot';
|
||||
export const CHATBOT_LOCATION = 'superset.chatbot';
|
||||
|
||||
interface DisposableLike {
|
||||
dispose(): void;
|
||||
}
|
||||
|
||||
/**
|
||||
* Registers the reference chatbot and returns a single disposable that
|
||||
* tears down everything it created. Idempotent across activate/dispose cycles.
|
||||
*
|
||||
* Cleanup order matters: stop in-flight streams first so listeners do not
|
||||
* receive late tokens, then unregister commands (so user clicks during teardown
|
||||
* become no-ops), then unregister the view (so the host's ChatbotMount unmounts
|
||||
* the React tree), and finally reset module state.
|
||||
*
|
||||
* Returns a plain `{ dispose }` object rather than constructing a Disposable
|
||||
* from the SDK — the SDK class is host-injected and only reliably available
|
||||
* via window.superset at runtime, while plain disposable-likes work in both
|
||||
* runtime and unit-test contexts.
|
||||
*
|
||||
* TODO(P1): when the host gains an async `deactivate(): Promise<void>` hook,
|
||||
* wrap the master disposer to flush in-flight async work before returning.
|
||||
*/
|
||||
export const activate = (): DisposableLike => {
|
||||
// Alt Chatbot deliberately registers no commands: the `core.chatbot__*`
|
||||
// command ids are owned by the Reference Chatbot, and command ids are global,
|
||||
// so a second registrant would collide. Alt is a view-only chatbot used to
|
||||
// exercise multi-chatbot selection.
|
||||
const viewDisposable = views.registerView(
|
||||
{
|
||||
id: VIEW_ID,
|
||||
name: 'Alt Chatbot',
|
||||
icon: 'Star',
|
||||
description: 'Second chatbot for testing singleton resolution.',
|
||||
},
|
||||
CHATBOT_LOCATION,
|
||||
() => React.createElement(ReferenceChatbot),
|
||||
);
|
||||
|
||||
let disposed = false;
|
||||
return {
|
||||
dispose() {
|
||||
if (disposed) return;
|
||||
disposed = true;
|
||||
try {
|
||||
abortAllActiveControllers();
|
||||
} catch {
|
||||
// streams are best-effort during teardown
|
||||
}
|
||||
try {
|
||||
viewDisposable.dispose();
|
||||
} catch {
|
||||
// ignore
|
||||
}
|
||||
resetState();
|
||||
},
|
||||
};
|
||||
};
|
||||
@@ -1,46 +0,0 @@
|
||||
/**
|
||||
* Licensed to the Apache Software Foundation (ASF) under one
|
||||
* or more contributor license agreements. See the NOTICE file
|
||||
* distributed with this work for additional information
|
||||
* regarding copyright ownership. The ASF licenses this file
|
||||
* to you under the Apache License, Version 2.0 (the
|
||||
* "License"); you may not use this file except in compliance
|
||||
* with the License. You may obtain a copy of the License at
|
||||
*
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing,
|
||||
* software distributed under the License is distributed on an
|
||||
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
|
||||
* KIND, either express or implied. See the License for the
|
||||
* specific language governing permissions and limitations
|
||||
* under the License.
|
||||
*/
|
||||
import React from 'react';
|
||||
|
||||
interface Props {
|
||||
onClick: () => void;
|
||||
}
|
||||
|
||||
export const Bubble: React.FC<Props> = ({ onClick }) => (
|
||||
<button
|
||||
type="button"
|
||||
onClick={onClick}
|
||||
data-test="reference-chatbot-bubble"
|
||||
aria-label="Open Alt chatbot"
|
||||
style={{
|
||||
width: 56,
|
||||
height: 56,
|
||||
borderRadius: '50%',
|
||||
border: 'none',
|
||||
background: '#2da44e',
|
||||
color: '#fff',
|
||||
fontSize: 24,
|
||||
fontWeight: 600,
|
||||
cursor: 'pointer',
|
||||
boxShadow: '0 4px 14px rgba(0,0,0,0.18)',
|
||||
}}
|
||||
>
|
||||
?
|
||||
</button>
|
||||
);
|
||||
@@ -1,66 +0,0 @@
|
||||
/**
|
||||
* Licensed to the Apache Software Foundation (ASF) under one
|
||||
* or more contributor license agreements. See the NOTICE file
|
||||
* distributed with this work for additional information
|
||||
* regarding copyright ownership. The ASF licenses this file
|
||||
* to you under the Apache License, Version 2.0 (the
|
||||
* "License"); you may not use this file except in compliance
|
||||
* with the License. You may obtain a copy of the License at
|
||||
*
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing,
|
||||
* software distributed under the License is distributed on an
|
||||
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
|
||||
* KIND, either express or implied. See the License for the
|
||||
* specific language governing permissions and limitations
|
||||
* under the License.
|
||||
*/
|
||||
import React from 'react';
|
||||
|
||||
interface State {
|
||||
error: Error | null;
|
||||
}
|
||||
|
||||
/**
|
||||
* Defense-in-depth boundary. The host already wraps the mount in its own
|
||||
* ErrorBoundary; this one keeps a panel crash from also bringing down the
|
||||
* bubble next to it.
|
||||
*/
|
||||
export class ExtensionErrorBoundary extends React.Component<
|
||||
React.PropsWithChildren<{}>,
|
||||
State
|
||||
> {
|
||||
state: State = { error: null };
|
||||
|
||||
static getDerivedStateFromError(error: Error): State {
|
||||
return { error };
|
||||
}
|
||||
|
||||
componentDidCatch(error: Error): void {
|
||||
// eslint-disable-next-line no-console
|
||||
console.error('[reference-chatbot] render error', error);
|
||||
}
|
||||
|
||||
render() {
|
||||
if (this.state.error) {
|
||||
return (
|
||||
<div
|
||||
data-test="reference-chatbot-error"
|
||||
style={{
|
||||
padding: 12,
|
||||
border: '1px solid #f5222d',
|
||||
borderRadius: 6,
|
||||
background: '#fff1f0',
|
||||
color: '#a8071a',
|
||||
fontSize: 12,
|
||||
maxWidth: 320,
|
||||
}}
|
||||
>
|
||||
Reference chatbot crashed: {this.state.error.message}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
return <>{this.props.children}</>;
|
||||
}
|
||||
}
|
||||
@@ -1,307 +0,0 @@
|
||||
/**
|
||||
* Licensed to the Apache Software Foundation (ASF) under one
|
||||
* or more contributor license agreements. See the NOTICE file
|
||||
* distributed with this work for additional information
|
||||
* regarding copyright ownership. The ASF licenses this file
|
||||
* to you under the Apache License, Version 2.0 (the
|
||||
* "License"); you may not use this file except in compliance
|
||||
* with the License. You may obtain a copy of the License at
|
||||
*
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing,
|
||||
* software distributed under the License is distributed on an
|
||||
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
|
||||
* KIND, either express or implied. See the License for the
|
||||
* specific language governing permissions and limitations
|
||||
* under the License.
|
||||
*/
|
||||
import React, { useCallback, useEffect, useRef, useState } from 'react';
|
||||
import { streamReply } from '../streaming/mockStream';
|
||||
import { getPageContext, PageContext, subscribeToPageChanges } from '../context/pageContext';
|
||||
import { registerActiveController, unregisterActiveController } from '../streaming/registry';
|
||||
|
||||
interface Props {
|
||||
onClose: () => void;
|
||||
}
|
||||
|
||||
interface Message {
|
||||
id: number;
|
||||
from: 'user' | 'bot';
|
||||
text: string;
|
||||
}
|
||||
|
||||
let messageSeq = 0;
|
||||
|
||||
/**
|
||||
* Builds the full set of context fields the host exposes for the current
|
||||
* surface, as ordered [label, value] rows. Whatever the host provides for where
|
||||
* the user is, the panel shows — nothing is summarized away. Returns an empty
|
||||
* array for surfaces with no active entity (list/home pages), where the
|
||||
* `page:` line alone is the context.
|
||||
*/
|
||||
const contextRows = (ctx: PageContext): Array<[string, string]> => {
|
||||
const rows: Array<[string, string]> = [];
|
||||
const push = (label: string, value: unknown) => {
|
||||
if (value !== undefined && value !== null && value !== '') {
|
||||
rows.push([label, String(value)]);
|
||||
}
|
||||
};
|
||||
|
||||
const chart = ctx.chart as
|
||||
| {
|
||||
chartId?: number | null;
|
||||
chartName?: string | null;
|
||||
vizType?: string;
|
||||
datasourceId?: number | null;
|
||||
datasourceName?: string | null;
|
||||
}
|
||||
| undefined;
|
||||
if (chart) {
|
||||
push('chart', chart.chartName ?? (chart.chartId == null ? '(unsaved)' : ''));
|
||||
push('chartId', chart.chartId);
|
||||
push('viz', chart.vizType);
|
||||
push('datasource', chart.datasourceName);
|
||||
push('datasourceId', chart.datasourceId);
|
||||
}
|
||||
|
||||
const dashboard = ctx.dashboard as
|
||||
| { dashboardId?: number; title?: string; filters?: Array<{ label: string; value: unknown }> }
|
||||
| undefined;
|
||||
if (dashboard) {
|
||||
push('dashboard', dashboard.title);
|
||||
push('dashboardId', dashboard.dashboardId);
|
||||
const filters = dashboard.filters ?? [];
|
||||
if (filters.length) {
|
||||
push(
|
||||
'filters',
|
||||
filters.map(f => `${f.label}=${JSON.stringify(f.value)}`).join(', '),
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
const dataset = ctx.dataset as
|
||||
| {
|
||||
datasetId?: number;
|
||||
datasetName?: string;
|
||||
schema?: string | null;
|
||||
catalog?: string | null;
|
||||
databaseName?: string | null;
|
||||
isVirtual?: boolean;
|
||||
}
|
||||
| undefined;
|
||||
if (dataset) {
|
||||
push('dataset', dataset.datasetName);
|
||||
push('datasetId', dataset.datasetId);
|
||||
push('schema', dataset.schema);
|
||||
push('catalog', dataset.catalog);
|
||||
push('database', dataset.databaseName);
|
||||
if (typeof dataset.isVirtual === 'boolean') {
|
||||
push('virtual', dataset.isVirtual);
|
||||
}
|
||||
}
|
||||
|
||||
if (ctx.sqlLab) {
|
||||
push('tab', ctx.sqlLab.title);
|
||||
}
|
||||
|
||||
return rows;
|
||||
};
|
||||
|
||||
export const Panel: React.FC<Props> = ({ onClose }) => {
|
||||
const [input, setInput] = useState('');
|
||||
const [messages, setMessages] = useState<Message[]>([]);
|
||||
const [streaming, setStreaming] = useState(false);
|
||||
const [pageContext, setPageContext] = useState<PageContext>(() => getPageContext());
|
||||
const controllerRef = useRef<AbortController | null>(null);
|
||||
|
||||
useEffect(
|
||||
() => subscribeToPageChanges(() => setPageContext(getPageContext())),
|
||||
[],
|
||||
);
|
||||
|
||||
useEffect(
|
||||
() => () => {
|
||||
// Component unmount cancels any in-flight stream.
|
||||
controllerRef.current?.abort();
|
||||
},
|
||||
[],
|
||||
);
|
||||
|
||||
const send = useCallback(async () => {
|
||||
const prompt = input.trim();
|
||||
if (!prompt || streaming) return;
|
||||
setInput('');
|
||||
const userMsg: Message = { id: ++messageSeq, from: 'user', text: prompt };
|
||||
const botMsg: Message = { id: ++messageSeq, from: 'bot', text: '' };
|
||||
setMessages(prev => [...prev, userMsg, botMsg]);
|
||||
setStreaming(true);
|
||||
|
||||
const controller = new AbortController();
|
||||
controllerRef.current = controller;
|
||||
registerActiveController(controller);
|
||||
|
||||
try {
|
||||
for await (const token of streamReply(prompt, controller.signal)) {
|
||||
setMessages(prev =>
|
||||
prev.map(m => (m.id === botMsg.id ? { ...m, text: m.text + token } : m)),
|
||||
);
|
||||
}
|
||||
} finally {
|
||||
unregisterActiveController(controller);
|
||||
controllerRef.current = null;
|
||||
setStreaming(false);
|
||||
}
|
||||
}, [input, streaming]);
|
||||
|
||||
const cancel = useCallback(() => {
|
||||
controllerRef.current?.abort();
|
||||
}, []);
|
||||
|
||||
return (
|
||||
<div
|
||||
data-test="reference-chatbot-panel"
|
||||
style={{
|
||||
width: 360,
|
||||
maxHeight: 480,
|
||||
display: 'flex',
|
||||
flexDirection: 'column',
|
||||
background: '#fff',
|
||||
border: '1px solid #d9d9d9',
|
||||
borderRadius: 8,
|
||||
boxShadow: '0 8px 24px rgba(0,0,0,0.18)',
|
||||
overflow: 'hidden',
|
||||
fontSize: 13,
|
||||
}}
|
||||
>
|
||||
<header
|
||||
style={{
|
||||
padding: '8px 12px',
|
||||
background: '#2da44e',
|
||||
color: '#fff',
|
||||
display: 'flex',
|
||||
justifyContent: 'space-between',
|
||||
alignItems: 'center',
|
||||
}}
|
||||
>
|
||||
<span>Alt Chatbot</span>
|
||||
<button
|
||||
type="button"
|
||||
onClick={onClose}
|
||||
aria-label="Close chatbot"
|
||||
data-test="reference-chatbot-close"
|
||||
style={{
|
||||
background: 'transparent',
|
||||
border: 'none',
|
||||
color: '#fff',
|
||||
fontSize: 16,
|
||||
cursor: 'pointer',
|
||||
}}
|
||||
>
|
||||
×
|
||||
</button>
|
||||
</header>
|
||||
|
||||
<div
|
||||
data-test="reference-chatbot-context"
|
||||
style={{
|
||||
padding: '6px 12px',
|
||||
background: '#f6f8fa',
|
||||
borderBottom: '1px solid #eaecef',
|
||||
fontFamily: 'monospace',
|
||||
fontSize: 11,
|
||||
color: '#57606a',
|
||||
wordBreak: 'break-all',
|
||||
}}
|
||||
>
|
||||
<div>page: {pageContext.pageType}</div>
|
||||
{contextRows(pageContext).map(([label, value]) => (
|
||||
<div key={label}>
|
||||
{label}: {value}
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
|
||||
<div style={{ flex: 1, overflowY: 'auto', padding: 12 }}>
|
||||
{messages.length === 0 && (
|
||||
<p style={{ color: '#8c8c8c' }}>
|
||||
Ask anything — replies are canned tokens streamed by the Alt Chatbot extension.
|
||||
</p>
|
||||
)}
|
||||
{messages.map(m => (
|
||||
<div
|
||||
key={m.id}
|
||||
data-test={`reference-chatbot-msg-${m.from}`}
|
||||
style={{
|
||||
margin: '6px 0',
|
||||
textAlign: m.from === 'user' ? 'right' : 'left',
|
||||
}}
|
||||
>
|
||||
<span
|
||||
style={{
|
||||
display: 'inline-block',
|
||||
padding: '4px 8px',
|
||||
borderRadius: 6,
|
||||
background: m.from === 'user' ? '#2da44e' : '#eef0f3',
|
||||
color: m.from === 'user' ? '#fff' : '#1f2328',
|
||||
maxWidth: '85%',
|
||||
whiteSpace: 'pre-wrap',
|
||||
}}
|
||||
>
|
||||
{m.text || '…'}
|
||||
</span>
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
|
||||
<footer
|
||||
style={{
|
||||
padding: 8,
|
||||
borderTop: '1px solid #eaecef',
|
||||
display: 'flex',
|
||||
gap: 6,
|
||||
}}
|
||||
>
|
||||
<input
|
||||
aria-label="Chat input"
|
||||
data-test="reference-chatbot-input"
|
||||
value={input}
|
||||
onChange={e => setInput(e.target.value)}
|
||||
onKeyDown={e => {
|
||||
if (e.key === 'Enter' && !e.shiftKey) {
|
||||
e.preventDefault();
|
||||
send();
|
||||
}
|
||||
}}
|
||||
placeholder="Type a message"
|
||||
style={{
|
||||
flex: 1,
|
||||
padding: '4px 8px',
|
||||
border: '1px solid #d9d9d9',
|
||||
borderRadius: 4,
|
||||
}}
|
||||
/>
|
||||
{streaming ? (
|
||||
<button
|
||||
type="button"
|
||||
onClick={cancel}
|
||||
data-test="reference-chatbot-cancel"
|
||||
style={{ padding: '4px 10px' }}
|
||||
>
|
||||
Stop
|
||||
</button>
|
||||
) : (
|
||||
<button
|
||||
type="button"
|
||||
onClick={send}
|
||||
data-test="reference-chatbot-send"
|
||||
disabled={!input.trim()}
|
||||
style={{ padding: '4px 10px' }}
|
||||
>
|
||||
Send
|
||||
</button>
|
||||
)}
|
||||
</footer>
|
||||
</div>
|
||||
);
|
||||
};
|
||||
@@ -1,159 +0,0 @@
|
||||
/**
|
||||
* Licensed to the Apache Software Foundation (ASF) under one
|
||||
* or more contributor license agreements. See the NOTICE file
|
||||
* distributed with this work for additional information
|
||||
* regarding copyright ownership. The ASF licenses this file
|
||||
* to you under the Apache License, Version 2.0 (the
|
||||
* "License"); you may not use this file except in compliance
|
||||
* with the License. You may obtain a copy of the License at
|
||||
*
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing,
|
||||
* software distributed under the License is distributed on an
|
||||
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
|
||||
* KIND, either express or implied. See the License for the
|
||||
* specific language governing permissions and limitations
|
||||
* under the License.
|
||||
*/
|
||||
|
||||
/**
|
||||
* Single integration seam for the P3 namespaces.
|
||||
*
|
||||
* Each surface namespace is consumed via a try/catch — the host may ship a
|
||||
* version where a namespace function is declared but not yet implemented at
|
||||
* runtime, and the reference extension must keep working in that case. As
|
||||
* each namespace lights up on the host, that branch starts returning real
|
||||
* data without any change here.
|
||||
*
|
||||
* Route inference is the fallback when navigation.getPageType() is absent.
|
||||
*/
|
||||
|
||||
import * as core from '@apache-superset/core';
|
||||
|
||||
export type PageType =
|
||||
| 'home'
|
||||
| 'dashboard'
|
||||
| 'dashboard_list'
|
||||
| 'chart'
|
||||
| 'chart_list'
|
||||
| 'sqllab'
|
||||
| 'query_history'
|
||||
| 'saved_queries'
|
||||
| 'dataset'
|
||||
| 'dataset_list'
|
||||
| 'unknown';
|
||||
|
||||
export interface PageContext {
|
||||
pageType: PageType;
|
||||
dashboard?: unknown;
|
||||
chart?: unknown;
|
||||
dataset?: unknown;
|
||||
sqlLab?: { tabId: string; title: string };
|
||||
href: string;
|
||||
}
|
||||
|
||||
const tryCall = <T>(fn: () => T | undefined): T | undefined => {
|
||||
try {
|
||||
return fn();
|
||||
} catch {
|
||||
return undefined;
|
||||
}
|
||||
};
|
||||
|
||||
const inferPageType = (pathname: string): PageType => {
|
||||
if (pathname.startsWith('/sqllab/history')) return 'query_history';
|
||||
if (pathname.startsWith('/savedqueryview/list')) return 'saved_queries';
|
||||
if (pathname.startsWith('/sqllab')) return 'sqllab';
|
||||
if (pathname.startsWith('/dashboard/list')) return 'dashboard_list';
|
||||
if (
|
||||
pathname.startsWith('/superset/dashboard') ||
|
||||
pathname.startsWith('/dashboard')
|
||||
)
|
||||
return 'dashboard';
|
||||
if (pathname.startsWith('/chart/list')) return 'chart_list';
|
||||
if (pathname.startsWith('/explore') || pathname.startsWith('/chart'))
|
||||
return 'chart';
|
||||
if (pathname.startsWith('/tablemodelview/list')) return 'dataset_list';
|
||||
if (pathname.startsWith('/tablemodelview') || pathname.startsWith('/dataset'))
|
||||
return 'dataset';
|
||||
if (pathname === '/' || pathname.startsWith('/superset/welcome'))
|
||||
return 'home';
|
||||
return 'unknown';
|
||||
};
|
||||
|
||||
const readSqlLabTab = (): PageContext['sqlLab'] => {
|
||||
const tab = tryCall(() => (core as any).sqlLab?.getCurrentTab?.());
|
||||
return tab ? { tabId: tab.id, title: tab.title } : undefined;
|
||||
};
|
||||
|
||||
const readPageType = (pathname: string): PageType => {
|
||||
const fromNav = tryCall(() => (core as any).navigation?.getPageType?.());
|
||||
return (fromNav as PageType | undefined) ?? inferPageType(pathname);
|
||||
};
|
||||
|
||||
/**
|
||||
* Subscribe to page-context changes and invoke `onChange` whenever any part of
|
||||
* the context may have changed. Returns a cleanup function.
|
||||
*
|
||||
* Three classes of change are watched:
|
||||
* - Navigation (`navigation.onDidChangePage`, or `popstate` as a fallback for
|
||||
* hosts without the namespace) — the user moved to a different surface.
|
||||
* - Entity hydration (`explore.onDidChangeChart`, `dashboard.onDidChangeDashboard`,
|
||||
* `dataset.onDidChangeDataset`) — the surface's entity loaded or changed
|
||||
* *after* navigation settled. This matters because a surface (notably Explore)
|
||||
* can finish hydrating several seconds after the route change fires, so a
|
||||
* navigation-only subscription would read empty entity context and never
|
||||
* refresh once the real data arrives.
|
||||
* - In-surface SQL Lab changes (`sqlLab.onDidChangeActiveTab`,
|
||||
* `sqlLab.onDidChangeTabTitle`) — switching or renaming a tab does not change
|
||||
* the route, so without these the panel would keep showing the first tab.
|
||||
*/
|
||||
export const subscribeToPageChanges = (onChange: () => void): (() => void) => {
|
||||
const disposers: Array<() => void> = [];
|
||||
|
||||
const nav = tryCall(() => (core as any).navigation);
|
||||
if (nav?.onDidChangePage) {
|
||||
const sub = nav.onDidChangePage(onChange);
|
||||
disposers.push(() => sub.dispose());
|
||||
} else {
|
||||
window.addEventListener('popstate', onChange);
|
||||
disposers.push(() => window.removeEventListener('popstate', onChange));
|
||||
}
|
||||
|
||||
// Entity-context change events. Each is optional — a host may not implement a
|
||||
// given namespace yet — so subscribe defensively and collect any disposer.
|
||||
const subscribeEntity = (
|
||||
getNamespace: () => any,
|
||||
method: string,
|
||||
): void => {
|
||||
const sub = tryCall(() => getNamespace()?.[method]?.(onChange));
|
||||
if (sub?.dispose) {
|
||||
disposers.push(() => sub.dispose());
|
||||
}
|
||||
};
|
||||
subscribeEntity(() => (core as any).explore, 'onDidChangeChart');
|
||||
subscribeEntity(() => (core as any).dashboard, 'onDidChangeDashboard');
|
||||
subscribeEntity(() => (core as any).dataset, 'onDidChangeDataset');
|
||||
// SQL Lab tab switches/renames happen without a route change.
|
||||
subscribeEntity(() => (core as any).sqlLab, 'onDidChangeActiveTab');
|
||||
subscribeEntity(() => (core as any).sqlLab, 'onDidChangeTabTitle');
|
||||
|
||||
return () => disposers.forEach(dispose => dispose());
|
||||
};
|
||||
|
||||
export const getPageContext = (): PageContext => {
|
||||
const { pathname, href } =
|
||||
typeof window !== 'undefined'
|
||||
? window.location
|
||||
: { pathname: '', href: '' };
|
||||
|
||||
return {
|
||||
pageType: readPageType(pathname),
|
||||
dashboard: tryCall(() => (core as any).dashboard?.getCurrentDashboard?.()),
|
||||
chart: tryCall(() => (core as any).explore?.getCurrentChart?.()),
|
||||
dataset: tryCall(() => (core as any).dataset?.getCurrentDataset?.()),
|
||||
sqlLab: readSqlLabTab(),
|
||||
href,
|
||||
};
|
||||
};
|
||||
@@ -1,30 +0,0 @@
|
||||
/**
|
||||
* Licensed to the Apache Software Foundation (ASF) under one
|
||||
* or more contributor license agreements. See the NOTICE file
|
||||
* distributed with this work for additional information
|
||||
* regarding copyright ownership. The ASF licenses this file
|
||||
* to you under the Apache License, Version 2.0 (the
|
||||
* "License"); you may not use this file except in compliance
|
||||
* with the License. You may obtain a copy of the License at
|
||||
*
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing,
|
||||
* software distributed under the License is distributed on an
|
||||
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
|
||||
* KIND, either express or implied. See the License for the
|
||||
* specific language governing permissions and limitations
|
||||
* under the License.
|
||||
*/
|
||||
|
||||
/**
|
||||
* Module Federation entry. The host loads `./index` and invokes the factory;
|
||||
* the side effect below registers the view + commands. The host's loader
|
||||
* intercepts registerView calls to collect disposables for deactivation, so
|
||||
* returning the master Disposable here is also captured by the test harness
|
||||
* for direct assertion.
|
||||
*/
|
||||
|
||||
import { activate } from './activate';
|
||||
|
||||
export const disposable = activate();
|
||||
@@ -1,57 +0,0 @@
|
||||
/**
|
||||
* Licensed to the Apache Software Foundation (ASF) under one
|
||||
* or more contributor license agreements. See the NOTICE file
|
||||
* distributed with this work for additional information
|
||||
* regarding copyright ownership. The ASF licenses this file
|
||||
* to you under the Apache License, Version 2.0 (the
|
||||
* "License"); you may not use this file except in compliance
|
||||
* with the License. You may obtain a copy of the License at
|
||||
*
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing,
|
||||
* software distributed under the License is distributed on an
|
||||
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
|
||||
* KIND, either express or implied. See the License for the
|
||||
* specific language governing permissions and limitations
|
||||
* under the License.
|
||||
*/
|
||||
|
||||
/**
|
||||
* Module-scoped open/closed state plus a tiny emitter the UI subscribes to.
|
||||
*
|
||||
* Lives entirely inside the extension — never reaches into the host store.
|
||||
* Reset on dispose so re-activation starts cleanly.
|
||||
*/
|
||||
|
||||
export type OpenStateListener = (open: boolean) => void;
|
||||
|
||||
let open = false;
|
||||
const listeners = new Set<OpenStateListener>();
|
||||
|
||||
export const isOpen = (): boolean => open;
|
||||
|
||||
export const setOpen = (next: boolean): void => {
|
||||
if (next === open) return;
|
||||
open = next;
|
||||
listeners.forEach(fn => {
|
||||
try {
|
||||
fn(open);
|
||||
} catch {
|
||||
// A listener throwing must not block other listeners or flip our state back.
|
||||
}
|
||||
});
|
||||
};
|
||||
|
||||
export const subscribe = (fn: OpenStateListener): (() => void) => {
|
||||
listeners.add(fn);
|
||||
return () => {
|
||||
listeners.delete(fn);
|
||||
};
|
||||
};
|
||||
|
||||
/** Drains listeners and resets state. Called from the master Disposable. */
|
||||
export const resetState = (): void => {
|
||||
open = false;
|
||||
listeners.clear();
|
||||
};
|
||||
@@ -1,73 +0,0 @@
|
||||
/**
|
||||
* Licensed to the Apache Software Foundation (ASF) under one
|
||||
* or more contributor license agreements. See the NOTICE file
|
||||
* distributed with this work for additional information
|
||||
* regarding copyright ownership. The ASF licenses this file
|
||||
* to you under the Apache License, Version 2.0 (the
|
||||
* "License"); you may not use this file except in compliance
|
||||
* with the License. You may obtain a copy of the License at
|
||||
*
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing,
|
||||
* software distributed under the License is distributed on an
|
||||
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
|
||||
* KIND, either express or implied. See the License for the
|
||||
* specific language governing permissions and limitations
|
||||
* under the License.
|
||||
*/
|
||||
|
||||
/**
|
||||
* Mock streaming reply used to validate stream teardown semantics.
|
||||
*
|
||||
* The reference chatbot is environment-validation only — there is no LLM.
|
||||
* This iterator yields canned tokens on a timer and exits cleanly when its
|
||||
* AbortSignal is fired. Disposal of the extension aborts any in-flight
|
||||
* controller, which is the contract that proves async cancellation works.
|
||||
*/
|
||||
|
||||
const TICK_MS = 40;
|
||||
|
||||
const buildReply = (prompt: string): string => {
|
||||
const trimmed = prompt.trim();
|
||||
if (!trimmed) {
|
||||
return 'Reference chatbot online. Send a message to validate streaming.';
|
||||
}
|
||||
return (
|
||||
`[reference-chatbot] received "${trimmed}". ` +
|
||||
'Streaming token-by-token to validate cancellation and teardown.'
|
||||
);
|
||||
};
|
||||
|
||||
const sleep = (ms: number, signal: AbortSignal): Promise<void> =>
|
||||
new Promise((resolve, reject) => {
|
||||
if (signal.aborted) {
|
||||
reject(new DOMException('aborted', 'AbortError'));
|
||||
return;
|
||||
}
|
||||
const timer = setTimeout(() => {
|
||||
signal.removeEventListener('abort', onAbort);
|
||||
resolve();
|
||||
}, ms);
|
||||
const onAbort = () => {
|
||||
clearTimeout(timer);
|
||||
reject(new DOMException('aborted', 'AbortError'));
|
||||
};
|
||||
signal.addEventListener('abort', onAbort, { once: true });
|
||||
});
|
||||
|
||||
export async function* streamReply(
|
||||
prompt: string,
|
||||
signal: AbortSignal,
|
||||
): AsyncIterableIterator<string> {
|
||||
const tokens = buildReply(prompt).split(/(\s+)/);
|
||||
for (const token of tokens) {
|
||||
if (signal.aborted) return;
|
||||
try {
|
||||
await sleep(TICK_MS, signal);
|
||||
} catch {
|
||||
return;
|
||||
}
|
||||
yield token;
|
||||
}
|
||||
}
|
||||
@@ -1,46 +0,0 @@
|
||||
/**
|
||||
* Licensed to the Apache Software Foundation (ASF) under one
|
||||
* or more contributor license agreements. See the NOTICE file
|
||||
* distributed with this work for additional information
|
||||
* regarding copyright ownership. The ASF licenses this file
|
||||
* to you under the Apache License, Version 2.0 (the
|
||||
* "License"); you may not use this file except in compliance
|
||||
* with the License. You may obtain a copy of the License at
|
||||
*
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing,
|
||||
* software distributed under the License is distributed on an
|
||||
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
|
||||
* KIND, either express or implied. See the License for the
|
||||
* specific language governing permissions and limitations
|
||||
* under the License.
|
||||
*/
|
||||
|
||||
/**
|
||||
* Module-scoped registry of in-flight stream AbortControllers.
|
||||
*
|
||||
* Lets the master Disposable abort any running stream even when the panel
|
||||
* is unmounted by a route change or by re-activation of the extension.
|
||||
*/
|
||||
|
||||
const active = new Set<AbortController>();
|
||||
|
||||
export const registerActiveController = (c: AbortController): void => {
|
||||
active.add(c);
|
||||
};
|
||||
|
||||
export const unregisterActiveController = (c: AbortController): void => {
|
||||
active.delete(c);
|
||||
};
|
||||
|
||||
export const abortAllActiveControllers = (): void => {
|
||||
active.forEach(c => {
|
||||
try {
|
||||
c.abort();
|
||||
} catch {
|
||||
// ignore — abort() should not throw, but stay defensive.
|
||||
}
|
||||
});
|
||||
active.clear();
|
||||
};
|
||||
@@ -1,16 +0,0 @@
|
||||
{
|
||||
"compilerOptions": {
|
||||
"target": "es2019",
|
||||
"module": "esnext",
|
||||
"moduleResolution": "node",
|
||||
"jsx": "react",
|
||||
"strict": true,
|
||||
"noImplicitAny": true,
|
||||
"esModuleInterop": true,
|
||||
"skipLibCheck": true,
|
||||
"forceConsistentCasingInFileNames": true,
|
||||
"lib": ["dom", "es2019"]
|
||||
},
|
||||
"include": ["src"],
|
||||
"exclude": ["src/**/*.test.ts", "src/**/*.test.tsx", "src/__tests__"]
|
||||
}
|
||||
@@ -1,16 +0,0 @@
|
||||
{
|
||||
"extends": "./tsconfig.json",
|
||||
"compilerOptions": {
|
||||
"baseUrl": ".",
|
||||
"paths": {
|
||||
"@apache-superset/core": ["src/__tests__/sdkMock.ts"]
|
||||
},
|
||||
"typeRoots": [
|
||||
"./node_modules/@types",
|
||||
"../../superset-frontend/node_modules/@types"
|
||||
],
|
||||
"types": ["jest", "node"]
|
||||
},
|
||||
"include": ["src"],
|
||||
"exclude": []
|
||||
}
|
||||
@@ -1,108 +0,0 @@
|
||||
/**
|
||||
* Licensed to the Apache Software Foundation (ASF) under one
|
||||
* or more contributor license agreements. See the NOTICE file
|
||||
* distributed with this work for additional information
|
||||
* regarding copyright ownership. The ASF licenses this file
|
||||
* to you under the Apache License, Version 2.0 (the
|
||||
* "License"); you may not use this file except in compliance
|
||||
* with the License. You may obtain a copy of the License at
|
||||
*
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing,
|
||||
* software distributed under the License is distributed on an
|
||||
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
|
||||
* KIND, either express or implied. See the License for the
|
||||
* specific language governing permissions and limitations
|
||||
* under the License.
|
||||
*/
|
||||
const path = require('path');
|
||||
const fs = require('fs');
|
||||
const { ModuleFederationPlugin } = require('webpack').container;
|
||||
const packageConfig = require('./package.json');
|
||||
const extensionConfig = require('./extension.json');
|
||||
|
||||
const MODULE_FEDERATION_NAME = 'apacheSuperset_altChatbot';
|
||||
|
||||
/**
|
||||
* Emits the `manifest.json` the host reads from the extension `dist/` root.
|
||||
*
|
||||
* The host (`superset/extensions/utils.py`) expects an extension dist laid out
|
||||
* as `dist/manifest.json` plus the federated bundle under `dist/frontend/dist/`.
|
||||
* The manifest carries `extension.json` verbatim, plus the composite `id` and a
|
||||
* `frontend` block naming the content-hashed `remoteEntry` so the host can load
|
||||
* the right file. Because the hash is only known after the build, the manifest
|
||||
* is written from the final asset names rather than checked in.
|
||||
*/
|
||||
class EmitManifestPlugin {
|
||||
apply(compiler) {
|
||||
compiler.hooks.afterEmit.tap('EmitManifestPlugin', compilation => {
|
||||
const assets = Object.keys(compilation.assets);
|
||||
const remoteEntry = assets.find(name => /^remoteEntry\..*\.js$/.test(name));
|
||||
if (!remoteEntry) {
|
||||
throw new Error('EmitManifestPlugin: no remoteEntry asset was emitted');
|
||||
}
|
||||
const manifest = {
|
||||
...extensionConfig,
|
||||
id: `${extensionConfig.publisher}.${extensionConfig.name}`,
|
||||
frontend: {
|
||||
remoteEntry,
|
||||
moduleFederationName: MODULE_FEDERATION_NAME,
|
||||
},
|
||||
};
|
||||
fs.writeFileSync(
|
||||
path.resolve(__dirname, 'dist', 'manifest.json'),
|
||||
`${JSON.stringify(manifest, null, 2)}\n`,
|
||||
);
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
module.exports = (env, argv) => {
|
||||
const isProd = argv.mode === 'production';
|
||||
|
||||
return {
|
||||
entry: isProd ? {} : './src/index.tsx',
|
||||
mode: isProd ? 'production' : 'development',
|
||||
devtool: isProd ? false : 'eval-cheap-module-source-map',
|
||||
devServer: {
|
||||
port: 3031,
|
||||
headers: { 'Access-Control-Allow-Origin': '*' },
|
||||
},
|
||||
output: {
|
||||
clean: true,
|
||||
filename: isProd ? undefined : '[name].[contenthash].js',
|
||||
chunkFilename: '[name].[contenthash].js',
|
||||
path: path.resolve(__dirname, 'dist', 'frontend', 'dist'),
|
||||
publicPath: `/api/v1/extensions/${extensionConfig.publisher}/${extensionConfig.name}/`,
|
||||
},
|
||||
resolve: { extensions: ['.ts', '.tsx', '.js', '.jsx'] },
|
||||
externalsType: 'window',
|
||||
externals: { '@apache-superset/core': 'superset' },
|
||||
module: {
|
||||
rules: [
|
||||
{ test: /\.tsx?$/, use: 'ts-loader', exclude: /node_modules/ },
|
||||
],
|
||||
},
|
||||
plugins: [
|
||||
new ModuleFederationPlugin({
|
||||
name: MODULE_FEDERATION_NAME,
|
||||
filename: 'remoteEntry.[contenthash].js',
|
||||
exposes: { './index': './src/index.tsx' },
|
||||
shared: {
|
||||
react: {
|
||||
singleton: true,
|
||||
requiredVersion: packageConfig.peerDependencies.react,
|
||||
import: false,
|
||||
},
|
||||
'react-dom': {
|
||||
singleton: true,
|
||||
requiredVersion: packageConfig.peerDependencies['react-dom'],
|
||||
import: false,
|
||||
},
|
||||
},
|
||||
}),
|
||||
new EmitManifestPlugin(),
|
||||
],
|
||||
};
|
||||
};
|
||||
@@ -147,7 +147,6 @@ exasol = ["sqlalchemy-exasol >= 2.4.0, < 8.0"]
|
||||
excel = ["xlrd>=1.2.0, <1.3"]
|
||||
fastmcp = [
|
||||
"fastmcp>=3.2.4,<4.0",
|
||||
"joserfc>=1.0.0,<2.0",
|
||||
# tiktoken backs the response-size-guard token estimator. Without
|
||||
# it, the middleware falls back to a coarser character-based
|
||||
# heuristic that under-counts JSON-heavy MCP responses.
|
||||
@@ -209,7 +208,7 @@ netezza = ["nzalchemy>=11.0.2"]
|
||||
starrocks = ["starrocks>=1.0.0"]
|
||||
doris = ["pydoris>=1.0.0, <2.0.0"]
|
||||
oceanbase = ["oceanbase_py>=0.0.1"]
|
||||
ydb = ["ydb-sqlalchemy>=0.1.2"]
|
||||
ydb = ["ydb-sqlalchemy>=0.1.2", "ydb-sqlglot-plugin>=0.2.5"]
|
||||
development = [
|
||||
# no bounds for apache-superset-extensions-cli until a stable version
|
||||
"apache-superset-extensions-cli",
|
||||
|
||||
@@ -183,7 +183,6 @@ cryptography==46.0.7
|
||||
# -c requirements/base-constraint.txt
|
||||
# apache-superset
|
||||
# authlib
|
||||
# joserfc
|
||||
# paramiko
|
||||
# pyjwt
|
||||
# pyopenssl
|
||||
@@ -472,8 +471,6 @@ jmespath==1.1.0
|
||||
# via
|
||||
# boto3
|
||||
# botocore
|
||||
joserfc==1.6.8
|
||||
# via apache-superset
|
||||
jsonpath-ng==1.7.0
|
||||
# via
|
||||
# -c requirements/base-constraint.txt
|
||||
|
||||
@@ -80,7 +80,7 @@ const restrictedImportsRules = {
|
||||
'no-jest-mock-console': {
|
||||
name: 'jest-mock-console',
|
||||
message: 'Please use native Jest spies, i.e. jest.spyOn(console, "warn")',
|
||||
},
|
||||
}
|
||||
};
|
||||
|
||||
module.exports = {
|
||||
|
||||
7
superset-frontend/package-lock.json
generated
7
superset-frontend/package-lock.json
generated
@@ -15,6 +15,7 @@
|
||||
],
|
||||
"dependencies": {
|
||||
"@apache-superset/core": "file:packages/superset-core",
|
||||
"@braintree/sanitize-url": "^7.1.2",
|
||||
"@deck.gl/aggregation-layers": "~9.2.5",
|
||||
"@deck.gl/core": "~9.2.5",
|
||||
"@deck.gl/extensions": "~9.2.5",
|
||||
@@ -2679,6 +2680,12 @@
|
||||
"url": "https://github.com/sponsors/Borewit"
|
||||
}
|
||||
},
|
||||
"node_modules/@braintree/sanitize-url": {
|
||||
"version": "7.1.2",
|
||||
"resolved": "https://registry.npmjs.org/@braintree/sanitize-url/-/sanitize-url-7.1.2.tgz",
|
||||
"integrity": "sha512-jigsZK+sMF/cuiB7sERuo9V7N9jx+dhmHHnQyDSVdpZwVutaBu7WvNYqMDLSgFgfB30n452TP3vjDAvFC973mA==",
|
||||
"license": "MIT"
|
||||
},
|
||||
"node_modules/@bramus/specificity": {
|
||||
"version": "2.4.2",
|
||||
"resolved": "https://registry.npmjs.org/@bramus/specificity/-/specificity-2.4.2.tgz",
|
||||
|
||||
@@ -98,6 +98,7 @@
|
||||
],
|
||||
"dependencies": {
|
||||
"@apache-superset/core": "file:packages/superset-core",
|
||||
"@braintree/sanitize-url": "^7.1.2",
|
||||
"@deck.gl/aggregation-layers": "~9.2.5",
|
||||
"@deck.gl/core": "~9.2.5",
|
||||
"@deck.gl/extensions": "~9.2.5",
|
||||
|
||||
@@ -18,22 +18,6 @@
|
||||
"types": "./lib/authentication/index.d.ts",
|
||||
"default": "./lib/authentication/index.js"
|
||||
},
|
||||
"./dashboard": {
|
||||
"types": "./lib/dashboard/index.d.ts",
|
||||
"default": "./lib/dashboard/index.js"
|
||||
},
|
||||
"./dataset": {
|
||||
"types": "./lib/dataset/index.d.ts",
|
||||
"default": "./lib/dataset/index.js"
|
||||
},
|
||||
"./explore": {
|
||||
"types": "./lib/explore/index.d.ts",
|
||||
"default": "./lib/explore/index.js"
|
||||
},
|
||||
"./navigation": {
|
||||
"types": "./lib/navigation/index.d.ts",
|
||||
"default": "./lib/navigation/index.js"
|
||||
},
|
||||
"./commands": {
|
||||
"types": "./lib/commands/index.d.ts",
|
||||
"default": "./lib/commands/index.js"
|
||||
|
||||
@@ -213,55 +213,6 @@ export declare interface Event<T> {
|
||||
(listener: (e: T) => any, thisArgs?: any): Disposable;
|
||||
}
|
||||
|
||||
/**
|
||||
* Context handed to an extension's `activate` function.
|
||||
*
|
||||
* The extension binds the lifetime of everything it registers to this object by
|
||||
* pushing the returned {@link Disposable}s onto `subscriptions`. Because the
|
||||
* context is owned by the extension for as long as it is active, registrations
|
||||
* performed asynchronously (after an `await`, in a timer, or in an event
|
||||
* callback) are tracked just the same as synchronous ones — the host disposes
|
||||
* the whole `subscriptions` array on deactivation.
|
||||
*
|
||||
* @example
|
||||
* ```typescript
|
||||
* export function activate(context: ExtensionContext) {
|
||||
* context.subscriptions.push(
|
||||
* commands.registerCommand('my_ext.hello', () => {}),
|
||||
* );
|
||||
* }
|
||||
* ```
|
||||
*/
|
||||
export interface ExtensionContext {
|
||||
/**
|
||||
* Disposables to be cleaned up when the extension is deactivated. Push every
|
||||
* {@link Disposable} returned by a `register*` call here.
|
||||
*/
|
||||
subscriptions: { dispose(): void }[];
|
||||
}
|
||||
|
||||
/**
|
||||
* Shape of an extension's entry module (its `./index`).
|
||||
*
|
||||
* Extensions are encouraged to export an `activate(context)` function so that
|
||||
* their registrations are tracked via `context.subscriptions` regardless of
|
||||
* whether they run synchronously or asynchronously. For backward compatibility,
|
||||
* a module may instead register its contributions as top-level side effects when
|
||||
* the module is evaluated; such registrations are only tracked when performed
|
||||
* synchronously during module evaluation.
|
||||
*/
|
||||
export interface ExtensionModule {
|
||||
/**
|
||||
* Called by the host once the extension module has loaded. May be async; the
|
||||
* host awaits it before considering the extension active.
|
||||
*/
|
||||
activate?(context: ExtensionContext): void | Promise<void>;
|
||||
/**
|
||||
* Optional hook called before the host disposes `context.subscriptions`.
|
||||
*/
|
||||
deactivate?(): void | Promise<void>;
|
||||
}
|
||||
|
||||
/**
|
||||
* Represents a Superset extension with its metadata.
|
||||
* Extensions are modular components that can extend Superset's functionality
|
||||
|
||||
@@ -43,9 +43,6 @@ export type SqlLabLocation =
|
||||
| 'results'
|
||||
| 'queryHistory';
|
||||
|
||||
/** Valid locations within the app shell (persist across all routes). */
|
||||
export type AppLocation = 'chatbot';
|
||||
|
||||
/**
|
||||
* Nested structure for view contributions by scope and location.
|
||||
* @example
|
||||
@@ -58,7 +55,6 @@ export type AppLocation = 'chatbot';
|
||||
*/
|
||||
export interface ViewContributions {
|
||||
sqllab?: Partial<Record<SqlLabLocation, View[]>>;
|
||||
app?: Partial<Record<AppLocation, View[]>>;
|
||||
}
|
||||
|
||||
/**
|
||||
|
||||
@@ -1,84 +0,0 @@
|
||||
/**
|
||||
* Licensed to the Apache Software Foundation (ASF) under one
|
||||
* or more contributor license agreements. See the NOTICE file
|
||||
* distributed with this work for additional information
|
||||
* regarding copyright ownership. The ASF licenses this file
|
||||
* to you under the Apache License, Version 2.0 (the
|
||||
* "License"); you may not use this file except in compliance
|
||||
* with the License. You may obtain a copy of the License at
|
||||
*
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing,
|
||||
* software distributed under the License is distributed on an
|
||||
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
|
||||
* KIND, either express or implied. See the License for the
|
||||
* specific language governing permissions and limitations
|
||||
* under the License.
|
||||
*/
|
||||
|
||||
/**
|
||||
* @fileoverview Dashboard namespace for Superset extensions (P3).
|
||||
*
|
||||
* Exposes dashboard identity and filter state as a stable semantic API.
|
||||
* Extensions must not depend on the Redux dashboard slice structure directly.
|
||||
*/
|
||||
|
||||
import { Event } from '../common';
|
||||
|
||||
/**
|
||||
* A single native filter's current selected value(s).
|
||||
* The value type is intentionally kept as `unknown` because filter values
|
||||
* are heterogeneous (date ranges, string lists, numbers, etc.).
|
||||
*/
|
||||
export interface FilterValue {
|
||||
/** The filter's stable id. */
|
||||
filterId: string;
|
||||
/** Display label of the filter. */
|
||||
label: string;
|
||||
/** Currently applied value, or `null` when the filter is cleared. */
|
||||
value: unknown;
|
||||
}
|
||||
|
||||
/**
|
||||
* Normalized dashboard context exposed to extensions on the Dashboard page.
|
||||
*/
|
||||
export interface DashboardContext {
|
||||
/** Numeric dashboard id. */
|
||||
dashboardId: number;
|
||||
/** Display title of the dashboard. */
|
||||
title: string;
|
||||
/**
|
||||
* Active native filter values keyed by filter id.
|
||||
* Only includes filters that have a value applied.
|
||||
*/
|
||||
filters: FilterValue[];
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns the normalized dashboard context for the page currently being viewed,
|
||||
* or `undefined` when the user is not on a Dashboard page.
|
||||
*
|
||||
* @example
|
||||
* ```typescript
|
||||
* const dash = dashboard.getCurrentDashboard();
|
||||
* if (dash) {
|
||||
* console.log(dash.title, dash.filters);
|
||||
* }
|
||||
* ```
|
||||
*/
|
||||
export declare function getCurrentDashboard(): DashboardContext | undefined;
|
||||
|
||||
/**
|
||||
* Event fired when the dashboard identity or its active filter values change.
|
||||
* Fired on native filter value changes and on navigation to a different dashboard.
|
||||
*
|
||||
* @example
|
||||
* ```typescript
|
||||
* const sub = dashboard.onDidChangeDashboard(dash => {
|
||||
* chatbot.updateContext({ dashboard: dash });
|
||||
* });
|
||||
* sub.dispose();
|
||||
* ```
|
||||
*/
|
||||
export declare const onDidChangeDashboard: Event<DashboardContext>;
|
||||
@@ -1,73 +0,0 @@
|
||||
/**
|
||||
* Licensed to the Apache Software Foundation (ASF) under one
|
||||
* or more contributor license agreements. See the NOTICE file
|
||||
* distributed with this work for additional information
|
||||
* regarding copyright ownership. The ASF licenses this file
|
||||
* to you under the Apache License, Version 2.0 (the
|
||||
* "License"); you may not use this file except in compliance
|
||||
* with the License. You may obtain a copy of the License at
|
||||
*
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing,
|
||||
* software distributed under the License is distributed on an
|
||||
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
|
||||
* KIND, either express or implied. See the License for the
|
||||
* specific language governing permissions and limitations
|
||||
* under the License.
|
||||
*/
|
||||
|
||||
/**
|
||||
* @fileoverview Dataset namespace for Superset extensions (P3).
|
||||
*
|
||||
* Exposes the dataset currently being viewed as a stable semantic API.
|
||||
* Aligned with backend-enforced dataset visibility and column-access semantics.
|
||||
*/
|
||||
|
||||
import { Event } from '../common';
|
||||
|
||||
/**
|
||||
* Normalized dataset context exposed to extensions on the Dataset page.
|
||||
*/
|
||||
export interface DatasetContext {
|
||||
/** Numeric dataset id. */
|
||||
datasetId: number;
|
||||
/** Display name (table name or virtual dataset name). */
|
||||
datasetName: string;
|
||||
/** Schema the dataset belongs to, if applicable. */
|
||||
schema: string | null;
|
||||
/** Catalog the dataset belongs to, if applicable. */
|
||||
catalog: string | null;
|
||||
/** Database name backing this dataset. */
|
||||
databaseName: string | null;
|
||||
/** Whether this is a virtual (SQL-defined) dataset. */
|
||||
isVirtual: boolean;
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns the normalized dataset context for the page currently being viewed,
|
||||
* or `undefined` when the user is not on a Dataset page.
|
||||
*
|
||||
* @example
|
||||
* ```typescript
|
||||
* const ds = dataset.getCurrentDataset();
|
||||
* if (ds) {
|
||||
* console.log(ds.datasetName, ds.schema);
|
||||
* }
|
||||
* ```
|
||||
*/
|
||||
export declare function getCurrentDataset(): DatasetContext | undefined;
|
||||
|
||||
/**
|
||||
* Event fired when the focused dataset changes (e.g. the user navigates to a
|
||||
* different dataset detail page).
|
||||
*
|
||||
* @example
|
||||
* ```typescript
|
||||
* const sub = dataset.onDidChangeDataset(ds => {
|
||||
* chatbot.updateContext({ dataset: ds });
|
||||
* });
|
||||
* sub.dispose();
|
||||
* ```
|
||||
*/
|
||||
export declare const onDidChangeDataset: Event<DatasetContext>;
|
||||
@@ -1,75 +0,0 @@
|
||||
/**
|
||||
* Licensed to the Apache Software Foundation (ASF) under one
|
||||
* or more contributor license agreements. See the NOTICE file
|
||||
* distributed with this work for additional information
|
||||
* regarding copyright ownership. The ASF licenses this file
|
||||
* to you under the Apache License, Version 2.0 (the
|
||||
* "License"); you may not use this file except in compliance
|
||||
* with the License. You may obtain a copy of the License at
|
||||
*
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing,
|
||||
* software distributed under the License is distributed on an
|
||||
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
|
||||
* KIND, either express or implied. See the License for the
|
||||
* specific language governing permissions and limitations
|
||||
* under the License.
|
||||
*/
|
||||
|
||||
/**
|
||||
* @fileoverview Explore namespace for Superset extensions (P3).
|
||||
*
|
||||
* Exposes the current chart/explore context as a stable semantic API.
|
||||
* Normalized over Explore Redux state — extensions must not depend on
|
||||
* the Redux slice structure directly.
|
||||
*/
|
||||
|
||||
import { Event } from '../common';
|
||||
|
||||
/**
|
||||
* Normalized chart context exposed to extensions during an Explore session.
|
||||
* Covers saved chart identity and transient editing context; excludes raw
|
||||
* form-data internals and datasource-implementation details.
|
||||
*/
|
||||
export interface ChartContext {
|
||||
/** The saved chart id, or `null` when the chart has not been persisted. */
|
||||
chartId: number | null;
|
||||
/** Display name of the saved chart, or `null` for a new/unsaved chart. */
|
||||
chartName: string | null;
|
||||
/** The visualization type currently selected in the editor. */
|
||||
vizType: string;
|
||||
/** Id of the datasource backing the chart (physical or virtual dataset). */
|
||||
datasourceId: number | null;
|
||||
/** Human-readable datasource name. */
|
||||
datasourceName: string | null;
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns the normalized chart context for the active Explore session, or
|
||||
* `undefined` when the user is not on the Explore page.
|
||||
*
|
||||
* @example
|
||||
* ```typescript
|
||||
* const chart = explore.getCurrentChart();
|
||||
* if (chart) {
|
||||
* console.log(chart.vizType, chart.chartName);
|
||||
* }
|
||||
* ```
|
||||
*/
|
||||
export declare function getCurrentChart(): ChartContext | undefined;
|
||||
|
||||
/**
|
||||
* Event fired when the chart context changes within the active Explore session
|
||||
* (e.g. when the viz type, datasource, or saved name changes).
|
||||
* Not fired during route changes — subscribe to `navigation.onDidChangePage` for those.
|
||||
*
|
||||
* @example
|
||||
* ```typescript
|
||||
* const sub = explore.onDidChangeChart(chart => {
|
||||
* chatbot.updateContext({ chart });
|
||||
* });
|
||||
* sub.dispose();
|
||||
* ```
|
||||
*/
|
||||
export declare const onDidChangeChart: Event<ChartContext>;
|
||||
@@ -19,13 +19,9 @@
|
||||
export * as common from './common';
|
||||
export * as authentication from './authentication';
|
||||
export * as commands from './commands';
|
||||
export * as dashboard from './dashboard';
|
||||
export * as dataset from './dataset';
|
||||
export * as editors from './editors';
|
||||
export * as explore from './explore';
|
||||
export * as extensions from './extensions';
|
||||
export * as menus from './menus';
|
||||
export * as navigation from './navigation';
|
||||
export * as sqlLab from './sqlLab';
|
||||
export * as views from './views';
|
||||
export * as contributions from './contributions';
|
||||
|
||||
@@ -1,84 +0,0 @@
|
||||
/**
|
||||
* Licensed to the Apache Software Foundation (ASF) under one
|
||||
* or more contributor license agreements. See the NOTICE file
|
||||
* distributed with this work for additional information
|
||||
* regarding copyright ownership. The ASF licenses this file
|
||||
* to you under the Apache License, Version 2.0 (the
|
||||
* "License"); you may not use this file except in compliance
|
||||
* with the License. You may obtain a copy of the License at
|
||||
*
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing,
|
||||
* software distributed under the License is distributed on an
|
||||
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
|
||||
* KIND, either express or implied. See the License for the
|
||||
* specific language governing permissions and limitations
|
||||
* under the License.
|
||||
*/
|
||||
|
||||
/**
|
||||
* @fileoverview Navigation namespace for Superset extensions (P3).
|
||||
*
|
||||
* Exposes the current application surface so extensions can react to route
|
||||
* changes without polling. Entity-level context (chart, dashboard, dataset)
|
||||
* is intentionally not included here — use the surface-specific namespace
|
||||
* (`explore`, `dashboard`, `dataset`) to retrieve entity payloads.
|
||||
*/
|
||||
|
||||
import { Event } from '../common';
|
||||
|
||||
/**
|
||||
* The set of top-level application surfaces.
|
||||
*
|
||||
* `'explore'`, `'dashboard'` and `'dataset'` are the single-entity
|
||||
* editing/viewing surfaces where `explore.getCurrentChart()` /
|
||||
* `dashboard.getCurrentDashboard()` / `dataset.getCurrentDataset()` resolve to a
|
||||
* concrete entity. `'chart_list'`, `'dashboard_list'` and `'dataset_list'` are
|
||||
* the browse/list surfaces, distinct from those because no single entity is
|
||||
* active. `'sqllab'` is the SQL editor where `sqlLab.getCurrentTab()` resolves;
|
||||
* `'query_history'` and `'saved_queries'` are the related SQL Lab browse pages,
|
||||
* which are not the editor. `'other'` covers any route not explicitly enumerated.
|
||||
*/
|
||||
export type PageType =
|
||||
| 'dashboard'
|
||||
| 'dashboard_list'
|
||||
| 'explore'
|
||||
| 'chart_list'
|
||||
| 'sqllab'
|
||||
| 'query_history'
|
||||
| 'saved_queries'
|
||||
| 'dataset'
|
||||
| 'dataset_list'
|
||||
| 'home'
|
||||
| 'other';
|
||||
|
||||
/**
|
||||
* Returns the current page surface type.
|
||||
*
|
||||
* @example
|
||||
* ```typescript
|
||||
* const pageType = navigation.getPageType();
|
||||
* if (pageType === 'dashboard') {
|
||||
* const ctx = dashboard.getCurrentDashboard();
|
||||
* }
|
||||
* ```
|
||||
*/
|
||||
export declare function getPageType(): PageType;
|
||||
|
||||
/**
|
||||
* Event fired whenever the user navigates to a different surface.
|
||||
* Use the surface-specific namespace to read entity context after the event.
|
||||
*
|
||||
* @example
|
||||
* ```typescript
|
||||
* const sub = navigation.onDidChangePage(pageType => {
|
||||
* if (pageType === 'dashboard') {
|
||||
* const ctx = dashboard.getCurrentDashboard();
|
||||
* }
|
||||
* });
|
||||
* // later:
|
||||
* sub.dispose();
|
||||
* ```
|
||||
*/
|
||||
export declare const onDidChangePage: Event<PageType>;
|
||||
@@ -115,6 +115,21 @@ export const GlobalStyles = () => {
|
||||
display: flex;
|
||||
margin-top: ${theme.marginXS}px;
|
||||
}
|
||||
|
||||
.superset-explore-popover.ant-popover
|
||||
.ant-popover-inner:has(.ant-popover-title) {
|
||||
padding-top: 0;
|
||||
}
|
||||
.superset-explore-popover.ant-popover .ant-popover-title {
|
||||
padding-top: ${theme.paddingXS}px;
|
||||
margin-bottom: ${theme.paddingSM}px;
|
||||
line-height: 1;
|
||||
}
|
||||
.superset-explore-popover.ant-popover
|
||||
.ant-popover-inner:has(.ant-popover-title)
|
||||
.ant-tabs-tab {
|
||||
padding-top: 0;
|
||||
}
|
||||
`}
|
||||
/>
|
||||
);
|
||||
|
||||
@@ -48,12 +48,6 @@ export interface View {
|
||||
name: string;
|
||||
/** Optional description of the view, for display in contribution manifests. */
|
||||
description?: string;
|
||||
/**
|
||||
* Optional icon identifier for the view, used in admin pickers and manifest
|
||||
* listings. Static — set once at registerView() time.
|
||||
* Dynamic icon states (e.g. notification badge) are the extension's concern.
|
||||
*/
|
||||
icon?: string;
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -62,12 +56,12 @@ export interface View {
|
||||
* The view provider function is called when the UI renders the location,
|
||||
* and should return a React element to display.
|
||||
*
|
||||
* @param view The view descriptor (id, name, and optional icon/description).
|
||||
* @param view The view descriptor (id and name).
|
||||
* @param location The location where this view should appear (e.g. "sqllab.panels").
|
||||
* @param provider A function that returns the React element to render.
|
||||
* @returns A Disposable that unregisters the view when disposed.
|
||||
*
|
||||
* @example SQL Lab panel
|
||||
* @example
|
||||
* ```typescript
|
||||
* views.registerView(
|
||||
* { id: 'my_ext.result_stats', name: 'Result Stats' },
|
||||
@@ -75,15 +69,6 @@ export interface View {
|
||||
* () => <ResultStatsPanel />,
|
||||
* );
|
||||
* ```
|
||||
*
|
||||
* @example Chatbot bubble (`superset.chatbot` — singleton, host renders one)
|
||||
* ```typescript
|
||||
* views.registerView(
|
||||
* { id: 'my_ext.chatbot', name: 'My Chatbot', icon: 'Bubble' },
|
||||
* 'superset.chatbot',
|
||||
* () => <ChatbotApp />,
|
||||
* );
|
||||
* ```
|
||||
*/
|
||||
export declare function registerView(
|
||||
view: View,
|
||||
@@ -91,21 +76,6 @@ export declare function registerView(
|
||||
provider: () => ReactElement,
|
||||
): Disposable;
|
||||
|
||||
/**
|
||||
* Narrowed descriptor for chatbot contributions (`superset.chatbot` location).
|
||||
*
|
||||
* Extension authors should use this type when calling `registerView` for the
|
||||
* chatbot area. It is identical to {@link View} but makes the registration
|
||||
* intent explicit and allows future narrowing (e.g. required `icon`).
|
||||
*
|
||||
* @example
|
||||
* ```typescript
|
||||
* const chatbot: ChatbotView = { id: 'my_ext.chatbot', name: 'My Chatbot', icon: 'Bubble' };
|
||||
* views.registerView(chatbot, 'superset.chatbot', () => <ChatbotApp />);
|
||||
* ```
|
||||
*/
|
||||
export type ChatbotView = View;
|
||||
|
||||
/**
|
||||
* Retrieves all views registered at a specific location.
|
||||
*
|
||||
|
||||
@@ -25,7 +25,7 @@ import {
|
||||
} from '@superset-ui/core';
|
||||
import { PostProcessingFactory } from './types';
|
||||
|
||||
const PERCENTILE_REGEX = /(\d+)\/(\d+) percentiles/;
|
||||
const PERCENTILE_REGEX = /(\d{1,3})\/(\d{1,3}) percentiles/;
|
||||
|
||||
export const boxplotOperator: PostProcessingFactory<PostProcessingBoxplot> = (
|
||||
formData,
|
||||
|
||||
@@ -27,6 +27,7 @@
|
||||
"@ant-design/icons": "^6.2.3",
|
||||
"@apache-superset/core": "*",
|
||||
"@babel/runtime": "^7.29.7",
|
||||
"@braintree/sanitize-url": "^7.1.2",
|
||||
"@types/json-bigint": "^1.0.4",
|
||||
"@visx/responsive": "^3.12.0",
|
||||
"ace-builds": "^1.44.0",
|
||||
|
||||
@@ -16,6 +16,7 @@
|
||||
* specific language governing permissions and limitations
|
||||
* under the License.
|
||||
*/
|
||||
import { sanitizeUrl } from '@braintree/sanitize-url';
|
||||
import { FC } from 'react';
|
||||
import { styled, useTheme, css } from '@apache-superset/core/theme';
|
||||
import { Skeleton } from '../Skeleton';
|
||||
@@ -140,7 +141,7 @@ const ThinSkeleton = styled(Skeleton)`
|
||||
const paragraphConfig = { rows: 1, width: 150 };
|
||||
|
||||
const AnchorLink: FC<LinkProps> = ({ to, children }) => (
|
||||
<a href={to}>{children}</a>
|
||||
<a href={to !== undefined ? sanitizeUrl(to) : undefined}>{children}</a>
|
||||
);
|
||||
|
||||
function ListViewCard({
|
||||
|
||||
@@ -519,8 +519,7 @@ const Select = forwardRef(
|
||||
handleSelectAll();
|
||||
}}
|
||||
>
|
||||
{t('Select all')}{' '}
|
||||
{`(${formatNumber('SMART_NUMBER', bulkSelectCounts.selectable)})`}
|
||||
{t('Select all')} {`(${formatNumber('SMART_NUMBER', bulkSelectCounts.selectable)})`}
|
||||
</Button>
|
||||
<Button
|
||||
type="link"
|
||||
@@ -537,8 +536,7 @@ const Select = forwardRef(
|
||||
handleDeselectAll();
|
||||
}}
|
||||
>
|
||||
{t('Clear')}{' '}
|
||||
{`(${formatNumber('SMART_NUMBER', bulkSelectCounts.deselectable)})`}
|
||||
{t('Clear')} {`(${formatNumber('SMART_NUMBER', bulkSelectCounts.deselectable)})`}
|
||||
</Button>
|
||||
</StyledBulkActionsContainer>
|
||||
),
|
||||
|
||||
@@ -16,6 +16,7 @@
|
||||
* specific language governing permissions and limitations
|
||||
* under the License.
|
||||
*/
|
||||
import { sanitizeUrl } from '@braintree/sanitize-url';
|
||||
import callApiAndParseWithTimeout from './callApi/callApiAndParseWithTimeout';
|
||||
import {
|
||||
ClientConfig,
|
||||
@@ -123,7 +124,7 @@ export default class SupersetClientClass {
|
||||
if (endpoint) {
|
||||
await this.ensureAuth();
|
||||
const hiddenForm = document.createElement('form');
|
||||
hiddenForm.action = this.getUrl({ endpoint });
|
||||
hiddenForm.action = sanitizeUrl(this.getUrl({ endpoint }));
|
||||
hiddenForm.method = 'POST';
|
||||
hiddenForm.target = target;
|
||||
const payloadWithToken: Record<string, any> = {
|
||||
|
||||
@@ -33,6 +33,35 @@ describe('sanitizeHtml', () => {
|
||||
const sanitizedString = sanitizeHtml(htmlString);
|
||||
expect(sanitizedString).not.toContain('script');
|
||||
});
|
||||
|
||||
test('should preserve allowed presentational CSS properties', () => {
|
||||
const htmlString =
|
||||
'<div style="color: red; background-color: blue; font-size: 12px; text-align: center">x</div>';
|
||||
const sanitizedString = sanitizeHtml(htmlString);
|
||||
expect(sanitizedString).toContain('color:red');
|
||||
expect(sanitizedString).toContain('background-color:blue');
|
||||
expect(sanitizedString).toContain('font-size:12px');
|
||||
expect(sanitizedString).toContain('text-align:center');
|
||||
});
|
||||
|
||||
test('should strip layout and positioning CSS properties', () => {
|
||||
const htmlString =
|
||||
'<div style="color: red; position: fixed; z-index: 9999; width: 100%; height: 100%">x</div>';
|
||||
const sanitizedString = sanitizeHtml(htmlString);
|
||||
expect(sanitizedString).toContain('color:red');
|
||||
expect(sanitizedString).not.toContain('position');
|
||||
expect(sanitizedString).not.toContain('z-index');
|
||||
expect(sanitizedString).not.toContain('width');
|
||||
expect(sanitizedString).not.toContain('height');
|
||||
});
|
||||
|
||||
test('should strip unsafe CSS property values', () => {
|
||||
const htmlString =
|
||||
'<div style="background-color: url(javascript:alert(1)); color: blue">x</div>';
|
||||
const sanitizedString = sanitizeHtml(htmlString);
|
||||
expect(sanitizedString).not.toContain('javascript');
|
||||
expect(sanitizedString).not.toContain('url(');
|
||||
});
|
||||
});
|
||||
|
||||
describe('isProbablyHTML', () => {
|
||||
|
||||
@@ -19,6 +19,50 @@
|
||||
import { FilterXSS, getDefaultWhiteList } from 'xss';
|
||||
import { DataRecordValue } from '../types';
|
||||
|
||||
// Restrict inline `style` attributes to a small set of presentational CSS
|
||||
// properties. Overlay/positioning properties (e.g. position, z-index, top,
|
||||
// left, transform) and sizing properties that could cover the page (e.g.
|
||||
// width, height) are intentionally excluded so that sanitized markup cannot
|
||||
// escape its container to overlay or obscure the surrounding page. The
|
||||
// allowlisted spacing/border properties (margin, padding, border) can still
|
||||
// affect layout within the container, which is acceptable. The `xss` library
|
||||
// also validates property values against this allowlist, stripping unsupported
|
||||
// constructs such as url()/expression().
|
||||
const allowedCssProperties = {
|
||||
color: true,
|
||||
'background-color': true,
|
||||
'text-align': true,
|
||||
'text-decoration': true,
|
||||
'font-family': true,
|
||||
'font-size': true,
|
||||
'font-style': true,
|
||||
'font-weight': true,
|
||||
'line-height': true,
|
||||
'letter-spacing': true,
|
||||
'white-space': true,
|
||||
padding: true,
|
||||
'padding-top': true,
|
||||
'padding-right': true,
|
||||
'padding-bottom': true,
|
||||
'padding-left': true,
|
||||
margin: true,
|
||||
'margin-top': true,
|
||||
'margin-right': true,
|
||||
'margin-bottom': true,
|
||||
'margin-left': true,
|
||||
border: true,
|
||||
'border-color': true,
|
||||
'border-style': true,
|
||||
'border-width': true,
|
||||
'border-radius': true,
|
||||
'vertical-align': true,
|
||||
// Needed by ECharts tooltips for row transparency and text truncation.
|
||||
opacity: true,
|
||||
'max-width': true,
|
||||
overflow: true,
|
||||
'text-overflow': true,
|
||||
};
|
||||
|
||||
const xssFilter = new FilterXSS({
|
||||
whiteList: {
|
||||
...getDefaultWhiteList(),
|
||||
@@ -45,7 +89,7 @@ const xssFilter = new FilterXSS({
|
||||
tfoot: ['align', 'valign', 'style'],
|
||||
},
|
||||
stripIgnoreTag: true,
|
||||
css: false,
|
||||
css: { whiteList: allowedCssProperties },
|
||||
});
|
||||
|
||||
export function sanitizeHtml(htmlString: string) {
|
||||
|
||||
@@ -161,10 +161,13 @@ test('should preserve table styling after sanitization (fixes ECharts tooltip fo
|
||||
</table>
|
||||
`;
|
||||
|
||||
// The `xss` CSS filter normalizes declarations, dropping the space after
|
||||
// each colon (e.g. `opacity: 0.8;` becomes `opacity:0.8;`) while preserving
|
||||
// the property/value pairs themselves.
|
||||
const sanitized = sanitizeHtml(tableWithStyles);
|
||||
expect(sanitized).toContain('style="opacity: 0.8;"');
|
||||
expect(sanitized).toContain('style="text-align: left; padding-left: 0px;"');
|
||||
expect(sanitized).toContain('style="text-align: right; padding-left: 16px;"');
|
||||
expect(sanitized).toContain('style="opacity:0.8;"');
|
||||
expect(sanitized).toContain('style="text-align:left; padding-left:0px;"');
|
||||
expect(sanitized).toContain('style="text-align:right; padding-left:16px;"');
|
||||
|
||||
const data = [
|
||||
['Metric', 'Value'],
|
||||
@@ -172,10 +175,10 @@ test('should preserve table styling after sanitization (fixes ECharts tooltip fo
|
||||
];
|
||||
const html = tooltipHtml(data, 'Test Tooltip');
|
||||
|
||||
expect(html).toContain('style="opacity: 0.8;"');
|
||||
expect(html).toContain('text-align: left');
|
||||
expect(html).toContain('text-align: right');
|
||||
expect(html).toContain('padding-left: 0px');
|
||||
expect(html).toContain('padding-left: 16px');
|
||||
expect(html).toContain('max-width: 300px');
|
||||
expect(html).toContain('style="opacity:0.8;"');
|
||||
expect(html).toContain('text-align:left');
|
||||
expect(html).toContain('text-align:right');
|
||||
expect(html).toContain('padding-left:0px');
|
||||
expect(html).toContain('padding-left:16px');
|
||||
expect(html).toContain('max-width:300px');
|
||||
});
|
||||
|
||||
@@ -182,7 +182,10 @@ testWithAssets(
|
||||
// Now track POST /api/v1/chart/data requests around Clear All
|
||||
const postsAfterClearAll: string[] = [];
|
||||
const handler = (req: any) => {
|
||||
if (req.url().includes('/api/v1/chart/data') && req.method() === 'POST') {
|
||||
if (
|
||||
req.url().includes('/api/v1/chart/data') &&
|
||||
req.method() === 'POST'
|
||||
) {
|
||||
postsAfterClearAll.push(req.url());
|
||||
}
|
||||
};
|
||||
|
||||
@@ -27,6 +27,7 @@ import {
|
||||
getNumberFormatter,
|
||||
getTimeFormatter,
|
||||
CategoricalColorNamespace,
|
||||
sanitizeHtml,
|
||||
} from '@superset-ui/core';
|
||||
|
||||
interface PartitionDataNode {
|
||||
@@ -345,7 +346,7 @@ function Icicle(element: HTMLElement, props: IcicleProps): void {
|
||||
t += '</tbody></table>';
|
||||
const [tipX, tipY] = d3.mouse(element);
|
||||
tip
|
||||
.html(t)
|
||||
.html(sanitizeHtml(t))
|
||||
.style('left', `${tipX + 15}px`)
|
||||
.style('top', `${tipY}px`);
|
||||
}
|
||||
|
||||
@@ -27,6 +27,7 @@ import {
|
||||
getTimeFormatter,
|
||||
getNumberFormatter,
|
||||
CategoricalColorNamespace,
|
||||
sanitizeHtml,
|
||||
} from '@superset-ui/core';
|
||||
|
||||
interface RoseDataEntry {
|
||||
@@ -146,24 +147,32 @@ function Rose(element: HTMLElement, props: RoseProps): void {
|
||||
function legendData(adatum: RoseData) {
|
||||
return adatum[times[0]].map((v: RoseDataEntry, i: number) => ({
|
||||
disabled: state.disabled[i],
|
||||
// Keep the raw name as `key` so it matches the value used for arc
|
||||
// fills (colorFn is called with d.name on arcs and d.key on the
|
||||
// legend). nvd3-fork's legend renders `key` via .text(), so the
|
||||
// raw value is escaped at the DOM sink.
|
||||
key: v.name,
|
||||
}));
|
||||
}
|
||||
|
||||
function tooltipData(d: ArcDatum, i: number, adatum: RoseData) {
|
||||
const timeIndex = Math.floor(d.arcId / numGroups);
|
||||
// nvd3-fork's nv.models.tooltip renders the `key` strings via .html(),
|
||||
// so any HTML in user-controlled column values would execute. Pass the
|
||||
// keys through sanitizeHtml to strip dangerous markup while preserving
|
||||
// legitimate text content.
|
||||
const series = useRichTooltip
|
||||
? adatum[times[timeIndex]]
|
||||
.filter(v => !state.disabled[v.id % numGroups])
|
||||
.map(v => ({
|
||||
key: v.name,
|
||||
key: sanitizeHtml(v.name),
|
||||
value: v.value,
|
||||
color: colorFn(v.name, sliceId),
|
||||
highlight: v.id === d.arcId,
|
||||
}))
|
||||
: [
|
||||
{
|
||||
key: d.name,
|
||||
key: sanitizeHtml(d.name),
|
||||
value: d.val,
|
||||
color: colorFn(d.name, sliceId),
|
||||
},
|
||||
|
||||
@@ -150,7 +150,8 @@ function WorldMap(element: HTMLElement, props: WorldMapProps): void {
|
||||
fillColor: colorFn(d.name, sliceId),
|
||||
}));
|
||||
} else {
|
||||
const rawExtents = d3Extent(filteredData, d => d.m1);
|
||||
const colorableData = filteredData.filter(d => d.m1 != null);
|
||||
const rawExtents = d3Extent(colorableData, d => d.m1);
|
||||
const extents: [number, number] =
|
||||
rawExtents[0] != null && rawExtents[1] != null
|
||||
? [rawExtents[0], rawExtents[1]]
|
||||
@@ -163,7 +164,7 @@ function WorldMap(element: HTMLElement, props: WorldMapProps): void {
|
||||
processedData = filteredData.map(d => ({
|
||||
...d,
|
||||
radius: radiusScale(Math.sqrt(d.m2)),
|
||||
fillColor: colorFn(d.m1) ?? theme.colorBorder,
|
||||
fillColor: d.m1 != null ? colorFn(d.m1) ?? theme.colorBorder : theme.colorBorder,
|
||||
}));
|
||||
}
|
||||
|
||||
|
||||
@@ -511,7 +511,7 @@ test('assigns fill colors from sequential scheme when colorBy is metric', () =>
|
||||
expect(data.CAN.fillColor).toMatch(/^(#|rgb)/);
|
||||
});
|
||||
|
||||
test('falls back to theme.colorBorder when metric values are null', () => {
|
||||
test('renders countries with null metric as no-data fill when colorBy is metric', () => {
|
||||
WorldMap(container, {
|
||||
...baseProps,
|
||||
colorBy: ColorBy.Metric,
|
||||
@@ -519,17 +519,66 @@ test('falls back to theme.colorBorder when metric values are null', () => {
|
||||
{
|
||||
country: 'USA',
|
||||
name: 'United States',
|
||||
m1: null as unknown as number,
|
||||
m1: 100,
|
||||
m2: 200,
|
||||
code: 'US',
|
||||
latitude: 37.0902,
|
||||
longitude: -95.7129,
|
||||
},
|
||||
{
|
||||
country: 'CAN',
|
||||
name: 'Canada',
|
||||
m1: null as unknown as number,
|
||||
m2: 100,
|
||||
code: 'CA',
|
||||
latitude: 56.1304,
|
||||
longitude: -106.3468,
|
||||
},
|
||||
],
|
||||
} as any);
|
||||
});
|
||||
|
||||
const data = lastDatamapConfig?.data as Record<string, { fillColor: string }>;
|
||||
expect(data.USA.fillColor).toBe('#e0e0e0');
|
||||
const data = lastDatamapConfig?.data as Record<
|
||||
string,
|
||||
WorldMapDataEntry & { fillColor: string }
|
||||
>;
|
||||
expect(data).toHaveProperty('USA');
|
||||
expect(data).toHaveProperty('CAN');
|
||||
expect(data.CAN.fillColor).toBe('#e0e0e0');
|
||||
});
|
||||
|
||||
test('renders countries with zero metric using the color scale when colorBy is metric', () => {
|
||||
WorldMap(container, {
|
||||
...baseProps,
|
||||
colorBy: ColorBy.Metric,
|
||||
data: [
|
||||
{
|
||||
country: 'USA',
|
||||
name: 'United States',
|
||||
m1: 100,
|
||||
m2: 200,
|
||||
code: 'US',
|
||||
latitude: 37.0902,
|
||||
longitude: -95.7129,
|
||||
},
|
||||
{
|
||||
country: 'MEX',
|
||||
name: 'Mexico',
|
||||
m1: 0,
|
||||
m2: 50,
|
||||
code: 'MX',
|
||||
latitude: 23.6345,
|
||||
longitude: -102.5528,
|
||||
},
|
||||
],
|
||||
});
|
||||
|
||||
const data = lastDatamapConfig?.data as Record<
|
||||
string,
|
||||
WorldMapDataEntry & { fillColor: string }
|
||||
>;
|
||||
expect(data).toHaveProperty('MEX');
|
||||
expect(data.MEX.fillColor).toMatch(/^(#|rgb)/);
|
||||
expect(data.MEX.fillColor).not.toBe('#e0e0e0');
|
||||
});
|
||||
|
||||
test('does not throw with empty data and metric coloring', () => {
|
||||
|
||||
@@ -152,7 +152,7 @@ export function generateMultiLineTooltipContent(d, xFormatter, yFormatters) {
|
||||
|
||||
d.series.forEach((series, i) => {
|
||||
const yFormatter = yFormatters[i];
|
||||
const key = getFormattedKey(series.key, false);
|
||||
const key = getFormattedKey(series.key, true);
|
||||
tooltip +=
|
||||
"<tr><td class='legend-color-guide'>" +
|
||||
`<div style="background-color: ${series.color};"></div></td>` +
|
||||
@@ -162,7 +162,7 @@ export function generateMultiLineTooltipContent(d, xFormatter, yFormatters) {
|
||||
|
||||
tooltip += '</tbody></table>';
|
||||
|
||||
return tooltip;
|
||||
return dompurify.sanitize(tooltip);
|
||||
}
|
||||
|
||||
export function generateTimePivotTooltip(d, xFormatter, yFormatter) {
|
||||
@@ -223,7 +223,7 @@ export function generateBubbleTooltipContent({
|
||||
s += createHTMLRow(getLabel(sizeField), sizeFormatter(point.size));
|
||||
s += '</table>';
|
||||
|
||||
return s;
|
||||
return dompurify.sanitize(s);
|
||||
}
|
||||
|
||||
// shouldRemove indicates whether the nvtooltips should be removed from the DOM
|
||||
@@ -262,11 +262,16 @@ export function wrapTooltip(chart) {
|
||||
: chart;
|
||||
const tooltipGeneratorFunc = tooltipLayer.tooltip.contentGenerator();
|
||||
tooltipLayer.tooltip.contentGenerator(d => {
|
||||
let tooltip = `<div>`;
|
||||
tooltip += tooltipGeneratorFunc(d);
|
||||
tooltip += '</div>';
|
||||
|
||||
return tooltip;
|
||||
// The nvd3-fork default contentGenerator builds tooltip HTML with
|
||||
// unescaped series keys (and feeds them into the tooltip's `.html()`
|
||||
// sink at render time). Run the final string through DOMPurify so
|
||||
// charts that do NOT install a custom contentGenerator (Line, Bar,
|
||||
// Area, Pie, BoxPlot, etc.) cannot execute stored payloads in
|
||||
// column or series names. Custom contentGenerators set elsewhere in
|
||||
// this module already return sanitized output, making this a
|
||||
// belt-and-braces wrap.
|
||||
const tooltip = `<div>${tooltipGeneratorFunc(d)}</div>`;
|
||||
return dompurify.sanitize(tooltip);
|
||||
});
|
||||
}
|
||||
|
||||
@@ -279,17 +284,19 @@ export function tipFactory(layer) {
|
||||
if (!d) {
|
||||
return '';
|
||||
}
|
||||
const title =
|
||||
const rawTitle =
|
||||
d[layer.titleColumn] && d[layer.titleColumn].length > 0
|
||||
? `${d[layer.titleColumn]} - ${layer.name}`
|
||||
: layer.name;
|
||||
const body = Array.isArray(layer.descriptionColumns)
|
||||
const rawBody = Array.isArray(layer.descriptionColumns)
|
||||
? layer.descriptionColumns.map(c => d[c])
|
||||
: Object.values(d);
|
||||
|
||||
return `<div><strong>${title}</strong></div><br/><div>${body.join(
|
||||
', ',
|
||||
)}</div>`;
|
||||
return dompurify.sanitize(
|
||||
`<div><strong>${rawTitle}</strong></div><br/><div>${rawBody.join(
|
||||
', ',
|
||||
)}</div>`,
|
||||
);
|
||||
});
|
||||
}
|
||||
|
||||
|
||||
@@ -24,8 +24,11 @@ import {
|
||||
|
||||
import {
|
||||
computeYDomain,
|
||||
generateBubbleTooltipContent,
|
||||
generateMultiLineTooltipContent,
|
||||
getTimeOrNumberFormatter,
|
||||
formatLabel,
|
||||
tipFactory,
|
||||
} from '../src/utils';
|
||||
|
||||
const DATA = [
|
||||
@@ -181,4 +184,96 @@ describe('nvd3/utils', () => {
|
||||
]);
|
||||
});
|
||||
});
|
||||
|
||||
// ------------------------------------------------------------------
|
||||
// Tooltip HTML sanitisation (XSS regression).
|
||||
// Each helper below feeds user-controlled column values into a
|
||||
// d3 / nvd3 .html() sink; the sanitised return must strip dangerous
|
||||
// markup so a stored payload cannot execute on hover.
|
||||
// ------------------------------------------------------------------
|
||||
|
||||
describe('generateBubbleTooltipContent() sanitises user input', () => {
|
||||
test('strips <script> from the entity column', () => {
|
||||
const html = generateBubbleTooltipContent({
|
||||
point: {
|
||||
color: 'red',
|
||||
group: 'g',
|
||||
entity: '<script>alert(1)</script>',
|
||||
x: 1,
|
||||
y: 2,
|
||||
size: 3,
|
||||
},
|
||||
entity: 'entity',
|
||||
xField: 'x',
|
||||
yField: 'y',
|
||||
sizeField: 'size',
|
||||
xFormatter: (v: number) => String(v),
|
||||
yFormatter: (v: number) => String(v),
|
||||
sizeFormatter: (v: number) => String(v),
|
||||
});
|
||||
expect(html).not.toMatch(/<script/i);
|
||||
expect(html).not.toMatch(/onerror=/i);
|
||||
});
|
||||
|
||||
test('strips <img onerror> injected via the group column', () => {
|
||||
const html = generateBubbleTooltipContent({
|
||||
point: {
|
||||
color: 'red',
|
||||
group: '<img src=x onerror=alert(1)>',
|
||||
entity: 'safe',
|
||||
x: 1,
|
||||
y: 2,
|
||||
size: 3,
|
||||
},
|
||||
entity: 'entity',
|
||||
xField: 'x',
|
||||
yField: 'y',
|
||||
sizeField: 'size',
|
||||
xFormatter: (v: number) => String(v),
|
||||
yFormatter: (v: number) => String(v),
|
||||
sizeFormatter: (v: number) => String(v),
|
||||
});
|
||||
expect(html).not.toMatch(/onerror/i);
|
||||
});
|
||||
});
|
||||
|
||||
describe('generateMultiLineTooltipContent() sanitises user input', () => {
|
||||
test('strips <script> from a series key', () => {
|
||||
const html = generateMultiLineTooltipContent(
|
||||
{
|
||||
value: 0,
|
||||
series: [
|
||||
{
|
||||
key: '<script>alert(1)</script>',
|
||||
color: 'red',
|
||||
value: 1,
|
||||
},
|
||||
],
|
||||
},
|
||||
(v: number) => String(v),
|
||||
[(v: number) => String(v)],
|
||||
);
|
||||
expect(html).not.toMatch(/<script/i);
|
||||
});
|
||||
});
|
||||
|
||||
describe('tipFactory() sanitises annotation columns', () => {
|
||||
test('strips <script> from a description column value', () => {
|
||||
const tip = tipFactory({
|
||||
annotationTipClass: 'foo',
|
||||
titleColumn: 'title',
|
||||
descriptionColumns: ['desc'],
|
||||
name: 'layer',
|
||||
});
|
||||
// d3-tip's .html(fn) stores the callback as the renderer; invoke
|
||||
// it directly to assert the sanitised output.
|
||||
const datum = {
|
||||
title: 'normal',
|
||||
desc: '<script>alert(1)</script>payload',
|
||||
};
|
||||
const html = tip.html()(datum);
|
||||
expect(html).not.toMatch(/<script/i);
|
||||
expect(html).toContain('payload');
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
@@ -86,6 +86,7 @@ export default function TableChart<D extends DataRecord = DataRecord>(
|
||||
onChartStateChange,
|
||||
chartState,
|
||||
metricSqlExpressions,
|
||||
showNumberedColumn,
|
||||
} = props;
|
||||
|
||||
const [searchOptions, setSearchOptions] = useState<SearchOption[]>([]);
|
||||
@@ -230,6 +231,9 @@ export default function TableChart<D extends DataRecord = DataRecord>(
|
||||
: (columns as InputColumn[]),
|
||||
data,
|
||||
serverPagination,
|
||||
serverPaginationData,
|
||||
serverPageLength,
|
||||
showNumberedColumn: showNumberedColumn && !emitCrossFilters,
|
||||
isRawRecords,
|
||||
defaultAlignPN: alignPositiveNegative,
|
||||
showCellBars,
|
||||
|
||||
@@ -42,3 +42,5 @@ export const FILTER_CONDITION_BODY_INDEX = {
|
||||
FIRST: 0,
|
||||
SECOND: 1,
|
||||
} as const;
|
||||
|
||||
export const ROW_NUMBER_COL_ID = '__row_number__';
|
||||
|
||||
@@ -281,11 +281,7 @@ const config: ControlPanelConfig = {
|
||||
{ controls, datasource, form_data }: ControlPanelState,
|
||||
controlState: ControlState,
|
||||
) => ({
|
||||
columns: datasource?.columns[0]?.hasOwnProperty('filterable')
|
||||
? (datasource as Dataset)?.columns?.filter(
|
||||
(c: ColumnMeta) => c.filterable,
|
||||
)
|
||||
: datasource?.columns,
|
||||
columns: datasource?.columns || [],
|
||||
savedMetrics: defineSavedMetrics(datasource),
|
||||
// current active adhoc metrics
|
||||
selectedMetrics:
|
||||
@@ -500,6 +496,18 @@ const config: ControlPanelConfig = {
|
||||
label: t('Visual formatting'),
|
||||
expanded: true,
|
||||
controlSetRows: [
|
||||
[
|
||||
{
|
||||
name: 'show_numbered_column',
|
||||
config: {
|
||||
type: 'CheckboxControl',
|
||||
label: t('Add numbered column'),
|
||||
renderTrigger: true,
|
||||
default: false,
|
||||
description: t('Whether to display the numbered column'),
|
||||
},
|
||||
},
|
||||
],
|
||||
[
|
||||
{
|
||||
name: 'column_config',
|
||||
|
||||
@@ -216,7 +216,13 @@ function convertFilterToSQL(
|
||||
if (conditions.length === 0) return null;
|
||||
if (conditions.length === 1) return conditions[0];
|
||||
|
||||
return `(${conditions.join(` ${filter.operator} `)})`;
|
||||
// The join operator is interpolated into raw SQL, so only allow the two
|
||||
// boolean connectors AG Grid produces.
|
||||
const joinOperator = String(filter.operator).toUpperCase();
|
||||
if (joinOperator !== 'AND' && joinOperator !== 'OR') {
|
||||
return null;
|
||||
}
|
||||
return `(${conditions.join(` ${joinOperator} `)})`;
|
||||
}
|
||||
|
||||
// Handle blank/notBlank operators for all filter types
|
||||
@@ -263,20 +269,26 @@ function convertFilterToSQL(
|
||||
filter.filter !== undefined &&
|
||||
filter.type
|
||||
) {
|
||||
// Number values are interpolated into the clause without quoting, so they
|
||||
// must be finite numbers. Coerce and skip the filter if it is not numeric.
|
||||
const numericValue = Number(filter.filter);
|
||||
if (!Number.isFinite(numericValue)) {
|
||||
return null;
|
||||
}
|
||||
// Map number filter types to SQL operators
|
||||
switch (filter.type) {
|
||||
case FILTER_OPERATORS.EQUALS:
|
||||
return `${colId} ${SQL_OPERATORS.EQUALS} ${filter.filter}`;
|
||||
return `${colId} ${SQL_OPERATORS.EQUALS} ${numericValue}`;
|
||||
case FILTER_OPERATORS.NOT_EQUAL:
|
||||
return `${colId} ${SQL_OPERATORS.NOT_EQUALS} ${filter.filter}`;
|
||||
return `${colId} ${SQL_OPERATORS.NOT_EQUALS} ${numericValue}`;
|
||||
case FILTER_OPERATORS.LESS_THAN:
|
||||
return `${colId} ${SQL_OPERATORS.LESS_THAN} ${filter.filter}`;
|
||||
return `${colId} ${SQL_OPERATORS.LESS_THAN} ${numericValue}`;
|
||||
case FILTER_OPERATORS.LESS_THAN_OR_EQUAL:
|
||||
return `${colId} ${SQL_OPERATORS.LESS_THAN_OR_EQUAL} ${filter.filter}`;
|
||||
return `${colId} ${SQL_OPERATORS.LESS_THAN_OR_EQUAL} ${numericValue}`;
|
||||
case FILTER_OPERATORS.GREATER_THAN:
|
||||
return `${colId} ${SQL_OPERATORS.GREATER_THAN} ${filter.filter}`;
|
||||
return `${colId} ${SQL_OPERATORS.GREATER_THAN} ${numericValue}`;
|
||||
case FILTER_OPERATORS.GREATER_THAN_OR_EQUAL:
|
||||
return `${colId} ${SQL_OPERATORS.GREATER_THAN_OR_EQUAL} ${filter.filter}`;
|
||||
return `${colId} ${SQL_OPERATORS.GREATER_THAN_OR_EQUAL} ${numericValue}`;
|
||||
default:
|
||||
return null;
|
||||
}
|
||||
@@ -314,7 +326,9 @@ export function convertFilterModel(
|
||||
return undefined;
|
||||
}
|
||||
|
||||
const sqlClauses: Record<string, string> = {};
|
||||
// Null-prototype object: column ids come from the (user-influenced) filter
|
||||
// model and are used as keys here, so avoid prototype-chain keys.
|
||||
const sqlClauses: Record<string, string> = Object.create(null);
|
||||
|
||||
Object.entries(filterModel).forEach(([colId, filter]) => {
|
||||
const sqlClause = convertFilterToSQL(colId, filter);
|
||||
|
||||
@@ -419,5 +419,11 @@ export const StyledChartContainer = styled.div<{
|
||||
color: ${theme.colorTextQuaternary};
|
||||
}
|
||||
}
|
||||
|
||||
.ag-header-center {
|
||||
.ag-header-cell-label {
|
||||
justify-content: center;
|
||||
}
|
||||
}
|
||||
`}
|
||||
`;
|
||||
|
||||
@@ -507,6 +507,7 @@ const transformProps = (
|
||||
conditional_formatting: conditionalFormatting,
|
||||
comparison_color_enabled: comparisonColorEnabled = false,
|
||||
comparison_color_scheme: comparisonColorScheme = ColorSchemeEnum.Green,
|
||||
show_numbered_column: showNumberedColumn = false,
|
||||
} = formData;
|
||||
|
||||
const allowRearrangeColumns = true;
|
||||
@@ -785,6 +786,7 @@ const transformProps = (
|
||||
metricSqlExpressions,
|
||||
chartState,
|
||||
onChartStateChange,
|
||||
showNumberedColumn,
|
||||
};
|
||||
};
|
||||
|
||||
|
||||
@@ -81,6 +81,7 @@ export type TableChartFormData = QueryFormData & {
|
||||
time_grain_sqla?: TimeGranularity;
|
||||
column_config?: Record<string, TableColumnConfig>;
|
||||
allow_rearrange_columns?: boolean;
|
||||
show_numbered_column?: boolean;
|
||||
};
|
||||
|
||||
export interface TableChartProps extends ChartProps {
|
||||
@@ -131,6 +132,7 @@ export interface AgGridTableChartTransformedProps<
|
||||
metricSqlExpressions: Record<string, string>;
|
||||
onChartStateChange?: (chartState: JsonObject) => void;
|
||||
chartState?: AgGridChartState;
|
||||
showNumberedColumn: boolean;
|
||||
}
|
||||
|
||||
export interface SortState {
|
||||
|
||||
@@ -17,9 +17,10 @@
|
||||
* specific language governing permissions and limitations
|
||||
* under the License.
|
||||
*/
|
||||
import { t } from '@apache-superset/core/translation';
|
||||
import { ColDef } from '@superset-ui/core/components/ThemedAgGridReact';
|
||||
import { useCallback, useMemo } from 'react';
|
||||
import { DataRecord, DataRecordValue } from '@superset-ui/core';
|
||||
import { DataRecord, DataRecordValue, JsonObject } from '@superset-ui/core';
|
||||
import { GenericDataType } from '@apache-superset/core/common';
|
||||
import { useTheme } from '@apache-superset/core/theme';
|
||||
import { ColorFormatters } from '@superset-ui/chart-controls';
|
||||
@@ -41,7 +42,7 @@ import { getAggFunc } from './getAggFunc';
|
||||
import { TextCellRenderer } from '../renderers/TextCellRenderer';
|
||||
import { NumericCellRenderer } from '../renderers/NumericCellRenderer';
|
||||
import CustomHeader from '../AgGridTable/components/CustomHeader';
|
||||
import { NOOP_FILTER_COMPARATOR } from '../consts';
|
||||
import { NOOP_FILTER_COMPARATOR, ROW_NUMBER_COL_ID } from '../consts';
|
||||
import { valueFormatter, valueGetter } from './formatValue';
|
||||
import getCellStyle from './getCellStyle';
|
||||
|
||||
@@ -53,6 +54,9 @@ type UseColDefsProps = {
|
||||
columns: InputColumn[];
|
||||
data: InputData[];
|
||||
serverPagination: boolean;
|
||||
serverPaginationData: JsonObject;
|
||||
serverPageLength: number;
|
||||
showNumberedColumn: boolean;
|
||||
isRawRecords: boolean;
|
||||
defaultAlignPN: boolean;
|
||||
showCellBars: boolean;
|
||||
@@ -216,6 +220,9 @@ export const useColDefs = ({
|
||||
columns,
|
||||
data,
|
||||
serverPagination,
|
||||
serverPaginationData,
|
||||
serverPageLength,
|
||||
showNumberedColumn,
|
||||
isRawRecords,
|
||||
defaultAlignPN,
|
||||
showCellBars,
|
||||
@@ -459,5 +466,61 @@ export const useColDefs = ({
|
||||
}, []);
|
||||
}, [stringifiedCols, getCommonColProps]);
|
||||
|
||||
return colDefs;
|
||||
const rawPageSize = serverPaginationData?.pageSize ?? serverPageLength;
|
||||
const pageSize = rawPageSize && rawPageSize > 0 ? rawPageSize : data.length;
|
||||
const currentPage = serverPaginationData?.currentPage ?? 0;
|
||||
const maxVisibleRowNumber = serverPagination
|
||||
? currentPage * pageSize + data.length
|
||||
: data.length;
|
||||
const rowIndexLength = `${Math.max(maxVisibleRowNumber, 1)}`.length;
|
||||
const rowNumberCol = useMemo<ColDef>(
|
||||
() => ({
|
||||
headerName: t('№'),
|
||||
headerClass: 'ag-header-center',
|
||||
field: ROW_NUMBER_COL_ID,
|
||||
valueGetter: params => {
|
||||
if (params.node?.rowPinned != null) return '';
|
||||
if (serverPagination && serverPaginationData) {
|
||||
return currentPage * pageSize + (params.node?.rowIndex ?? 0) + 1;
|
||||
}
|
||||
return (params.node?.rowIndex ?? 0) + 1;
|
||||
},
|
||||
headerStyle: {
|
||||
backgroundColor: theme.colorFillTertiary,
|
||||
fontSize: '1em',
|
||||
color: theme.colorTextTertiary,
|
||||
},
|
||||
width: 30 + rowIndexLength * 6,
|
||||
minWidth: 30 + rowIndexLength * 6,
|
||||
sortable: false,
|
||||
filter: false,
|
||||
pinned: 'left' as const,
|
||||
lockPosition: true,
|
||||
suppressNavigable: true,
|
||||
resizable: false,
|
||||
suppressMovable: true,
|
||||
suppressSizeToFit: true,
|
||||
cellStyle: {
|
||||
backgroundColor: theme.colorFillTertiary,
|
||||
padding: '0',
|
||||
textAlign: 'center',
|
||||
fontSize: '0.9em',
|
||||
color: theme.colorTextTertiary,
|
||||
},
|
||||
}),
|
||||
[
|
||||
currentPage,
|
||||
pageSize,
|
||||
rowIndexLength,
|
||||
serverPagination,
|
||||
serverPaginationData,
|
||||
theme.colorFillTertiary,
|
||||
theme.colorTextTertiary,
|
||||
],
|
||||
);
|
||||
|
||||
return useMemo(
|
||||
() => (showNumberedColumn ? [rowNumberCol, ...colDefs] : colDefs),
|
||||
[showNumberedColumn, rowNumberCol, colDefs],
|
||||
);
|
||||
};
|
||||
|
||||
@@ -19,6 +19,7 @@
|
||||
import { GenericDataType } from '@apache-superset/core/common';
|
||||
import { QueryFormData } from '@superset-ui/core';
|
||||
import {
|
||||
ColumnMeta,
|
||||
Dataset,
|
||||
isCustomControlItem,
|
||||
ControlConfig,
|
||||
@@ -45,6 +46,32 @@ const findConditionalFormattingControl = (): ControlConfig | null => {
|
||||
return null;
|
||||
};
|
||||
|
||||
const findMetricsMapStateToProps = ():
|
||||
| ControlConfig['mapStateToProps']
|
||||
| null => {
|
||||
for (const section of config.controlPanelSections) {
|
||||
if (!section) continue;
|
||||
for (const row of section.controlSetRows) {
|
||||
for (const control of row) {
|
||||
if (
|
||||
control &&
|
||||
typeof control === 'object' &&
|
||||
'name' in control &&
|
||||
(control as { name: string }).name === 'metrics' &&
|
||||
'override' in control
|
||||
) {
|
||||
return (
|
||||
control as {
|
||||
override: { mapStateToProps: ControlConfig['mapStateToProps'] };
|
||||
}
|
||||
).override.mapStateToProps;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
return null;
|
||||
};
|
||||
|
||||
const createMockControlState = (value: string[] | undefined): ControlState => ({
|
||||
type: 'SelectControl',
|
||||
value,
|
||||
@@ -206,3 +233,47 @@ test('static extraColorChoices removed from config', () => {
|
||||
|
||||
expect(controlConfig?.extraColorChoices).toBeUndefined();
|
||||
});
|
||||
|
||||
const createMockExploreWithColumns = (
|
||||
columns: Partial<ColumnMeta>[],
|
||||
): ControlPanelState => ({
|
||||
slice: { slice_id: 123 },
|
||||
datasource: {
|
||||
verbose_map: {},
|
||||
columns,
|
||||
metrics: [],
|
||||
} as Partial<Dataset> as Dataset,
|
||||
controls: {},
|
||||
form_data: {
|
||||
datasource: 'test',
|
||||
viz_type: 'table',
|
||||
} as QueryFormData,
|
||||
common: {},
|
||||
metadata: {},
|
||||
});
|
||||
|
||||
const createMockMetricsControlState = (): ControlState => ({
|
||||
type: 'MetricsControl',
|
||||
value: [],
|
||||
label: '',
|
||||
default: undefined,
|
||||
renderTrigger: false,
|
||||
});
|
||||
|
||||
test('metrics control includes non-filterable columns', () => {
|
||||
const mapStateToProps = findMetricsMapStateToProps();
|
||||
expect(mapStateToProps).toBeTruthy();
|
||||
|
||||
const explore = createMockExploreWithColumns([
|
||||
{ column_name: 'filterable_col', filterable: true },
|
||||
{ column_name: 'non_filterable_col', filterable: false },
|
||||
]);
|
||||
const result = mapStateToProps!(explore, createMockMetricsControlState());
|
||||
|
||||
expect(result.columns).toEqual(
|
||||
expect.arrayContaining([
|
||||
expect.objectContaining({ column_name: 'filterable_col' }),
|
||||
expect.objectContaining({ column_name: 'non_filterable_col' }),
|
||||
]),
|
||||
);
|
||||
});
|
||||
|
||||
@@ -0,0 +1,73 @@
|
||||
/**
|
||||
* Licensed to the Apache Software Foundation (ASF) under one
|
||||
* or more contributor license agreements. See the NOTICE file
|
||||
* distributed with this work for additional information
|
||||
* regarding copyright ownership. The ASF licenses this file
|
||||
* to you under the Apache License, Version 2.0 (the
|
||||
* "License"); you may not use this file except in compliance
|
||||
* with the License. You may obtain a copy of the License at
|
||||
*
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing,
|
||||
* software distributed under the License is distributed on an
|
||||
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
|
||||
* KIND, either express or implied. See the License for the
|
||||
* specific language governing permissions and limitations
|
||||
* under the License.
|
||||
*/
|
||||
import { convertFilterModel } from '../src/stateConversion';
|
||||
|
||||
describe('convertFilterModel', () => {
|
||||
test('emits a clause for a valid numeric comparison filter', () => {
|
||||
const result = convertFilterModel({
|
||||
revenue: { filterType: 'number', type: 'greaterThan', filter: 100 },
|
||||
} as any);
|
||||
|
||||
expect(result?.sqlClauses?.revenue).toBe('revenue > 100');
|
||||
});
|
||||
|
||||
test('drops a number filter whose value is not numeric', () => {
|
||||
const result = convertFilterModel({
|
||||
revenue: { filterType: 'number', type: 'equals', filter: '1 OR 1=1' },
|
||||
} as any);
|
||||
|
||||
expect(result).toBeUndefined();
|
||||
});
|
||||
|
||||
test('joins conditions with a valid boolean operator', () => {
|
||||
const result = convertFilterModel({
|
||||
revenue: {
|
||||
filterType: 'number',
|
||||
operator: 'AND',
|
||||
condition1: { filterType: 'number', type: 'greaterThan', filter: 1 },
|
||||
condition2: { filterType: 'number', type: 'lessThan', filter: 9 },
|
||||
},
|
||||
} as any);
|
||||
|
||||
expect(result?.sqlClauses?.revenue).toBe('(revenue > 1 AND revenue < 9)');
|
||||
});
|
||||
|
||||
test('drops a compound filter whose join operator is not AND/OR', () => {
|
||||
const result = convertFilterModel({
|
||||
revenue: {
|
||||
filterType: 'number',
|
||||
operator: 'AND 1=1) OR (1=1',
|
||||
condition1: { filterType: 'number', type: 'greaterThan', filter: 1 },
|
||||
condition2: { filterType: 'number', type: 'lessThan', filter: 9 },
|
||||
},
|
||||
} as any);
|
||||
|
||||
expect(result).toBeUndefined();
|
||||
});
|
||||
|
||||
test('stores clauses on a null-prototype map (prototype-safe column ids)', () => {
|
||||
const result = convertFilterModel({
|
||||
constructor: { filterType: 'number', type: 'equals', filter: 5 },
|
||||
} as any);
|
||||
|
||||
// The map has no prototype, so a column id like "constructor" is just data.
|
||||
expect(Object.getPrototypeOf(result?.sqlClauses)).toBeNull();
|
||||
expect(result?.sqlClauses?.constructor).toBe('constructor = 5');
|
||||
});
|
||||
});
|
||||
@@ -28,6 +28,7 @@ import tinycolor from 'tinycolor2';
|
||||
import { createElement, type ComponentProps, ReactNode } from 'react';
|
||||
import { useColDefs } from '../../src/utils/useColDefs';
|
||||
import { InputColumn } from '../../src/types';
|
||||
import { ROW_NUMBER_COL_ID } from '../../src/consts';
|
||||
|
||||
type TestCellStyleFunc = (params: unknown) => unknown;
|
||||
|
||||
@@ -122,6 +123,9 @@ const defaultThemeWrapper = makeThemeWrapper(supersetTheme);
|
||||
const defaultProps = {
|
||||
data: [{ test_col: 'value' }],
|
||||
serverPagination: false,
|
||||
serverPaginationData: {},
|
||||
serverPageLength: 0,
|
||||
showNumberedColumn: false,
|
||||
isRawRecords: true,
|
||||
defaultAlignPN: false,
|
||||
showCellBars: false,
|
||||
@@ -136,6 +140,12 @@ const defaultProps = {
|
||||
slice_id: 1,
|
||||
};
|
||||
|
||||
const basePropsNumericColumns = {
|
||||
...defaultProps,
|
||||
columns: [makeColumn({ key: 'a', label: 'A' })],
|
||||
data: [{ a: 1 }, { a: 2 }, { a: 3 }],
|
||||
};
|
||||
|
||||
test('boolean columns use agCheckboxCellRenderer', () => {
|
||||
const booleanCol = makeColumn({
|
||||
key: 'is_active',
|
||||
@@ -828,3 +838,233 @@ test('cellStyle respects explicit horizontal alignment overrides', () => {
|
||||
textAlign: 'center',
|
||||
});
|
||||
});
|
||||
|
||||
test('is not added when showNumberedColumn is false', () => {
|
||||
const { result } = renderHook(
|
||||
() => useColDefs({ ...basePropsNumericColumns, showNumberedColumn: false }),
|
||||
{ wrapper: defaultThemeWrapper },
|
||||
);
|
||||
expect(result.current.some(col => col.field === ROW_NUMBER_COL_ID)).toBe(
|
||||
false,
|
||||
);
|
||||
expect(result.current.length).toBe(1);
|
||||
});
|
||||
|
||||
test('is added as first column when showNumberedColumn is true', () => {
|
||||
const { result } = renderHook(
|
||||
() => useColDefs({ ...basePropsNumericColumns, showNumberedColumn: true }),
|
||||
{ wrapper: defaultThemeWrapper },
|
||||
);
|
||||
expect(result.current[0].field).toBe(ROW_NUMBER_COL_ID);
|
||||
expect(result.current[0].headerName).toBe('№');
|
||||
expect(result.current.length).toBe(2);
|
||||
});
|
||||
|
||||
test('width defaults to 36 when maxVisibleRowNumber is 0 (empty data)', () => {
|
||||
const emptyProps = {
|
||||
...basePropsNumericColumns,
|
||||
data: [],
|
||||
showNumberedColumn: true,
|
||||
};
|
||||
const { result } = renderHook(() => useColDefs(emptyProps), {
|
||||
wrapper: defaultThemeWrapper,
|
||||
});
|
||||
expect(result.current[0].width).toBe(36);
|
||||
});
|
||||
|
||||
test('width uses server pagination row count when available', () => {
|
||||
const serverProps = {
|
||||
...basePropsNumericColumns,
|
||||
serverPagination: true,
|
||||
serverPaginationData: { currentPage: 0, pageSize: 5 },
|
||||
data: [{ a: 1 }, { a: 2 }],
|
||||
showNumberedColumn: true,
|
||||
};
|
||||
const { result } = renderHook(() => useColDefs(serverProps), {
|
||||
wrapper: defaultThemeWrapper,
|
||||
});
|
||||
|
||||
expect(result.current[0].width).toBe(36);
|
||||
|
||||
const laterPageProps = {
|
||||
...serverProps,
|
||||
serverPaginationData: { currentPage: 3, pageSize: 5 },
|
||||
data: [{ a: 21 }, { a: 22 }],
|
||||
};
|
||||
const { result: resultLater } = renderHook(() => useColDefs(laterPageProps), {
|
||||
wrapper: defaultThemeWrapper,
|
||||
});
|
||||
expect(resultLater.current[0].width).toBe(42);
|
||||
});
|
||||
|
||||
test('valueGetter returns row numbers without server pagination', () => {
|
||||
const { result } = renderHook(
|
||||
() => useColDefs({ ...basePropsNumericColumns, showNumberedColumn: true }),
|
||||
{ wrapper: defaultThemeWrapper },
|
||||
);
|
||||
const colDef = result.current[0];
|
||||
const { valueGetter } = colDef;
|
||||
expect(valueGetter).toBeDefined();
|
||||
expect(typeof valueGetter).toBe('function');
|
||||
|
||||
const getter = valueGetter as (params: {
|
||||
node?: { rowIndex?: number };
|
||||
data?: Record<string, unknown>;
|
||||
}) => number;
|
||||
|
||||
const params = (rowIndex: number) => ({
|
||||
node: { rowIndex },
|
||||
data: basePropsNumericColumns.data[rowIndex],
|
||||
});
|
||||
|
||||
expect(getter(params(0))).toBe(1);
|
||||
expect(getter(params(1))).toBe(2);
|
||||
expect(getter(params(2))).toBe(3);
|
||||
});
|
||||
|
||||
test('valueGetter respects server pagination', () => {
|
||||
const serverProps = {
|
||||
...basePropsNumericColumns,
|
||||
serverPagination: true,
|
||||
serverPaginationData: { currentPage: 2, pageSize: 5 },
|
||||
data: [{ a: 11 }, { a: 12 }],
|
||||
};
|
||||
const { result } = renderHook(
|
||||
() => useColDefs({ ...serverProps, showNumberedColumn: true }),
|
||||
{ wrapper: defaultThemeWrapper },
|
||||
);
|
||||
const { valueGetter } = result.current[0];
|
||||
expect(typeof valueGetter).toBe('function');
|
||||
|
||||
const getter = valueGetter as (params: {
|
||||
node?: { rowIndex?: number };
|
||||
data?: Record<string, unknown>;
|
||||
}) => number;
|
||||
|
||||
expect(getter({ node: { rowIndex: 0 } })).toBe(11);
|
||||
expect(getter({ node: { rowIndex: 1 } })).toBe(12);
|
||||
});
|
||||
|
||||
test('has correct static column properties', () => {
|
||||
const { result } = renderHook(
|
||||
() => useColDefs({ ...basePropsNumericColumns, showNumberedColumn: true }),
|
||||
{ wrapper: defaultThemeWrapper },
|
||||
);
|
||||
const colDef = result.current[0];
|
||||
expect(colDef.sortable).toBe(false);
|
||||
expect(colDef.filter).toBe(false);
|
||||
expect(colDef.pinned).toBe('left');
|
||||
expect(colDef.lockPosition).toBe(true);
|
||||
expect(colDef.suppressNavigable).toBe(true);
|
||||
expect(colDef.suppressSizeToFit).toBe(true);
|
||||
expect(colDef.resizable).toBe(false);
|
||||
expect(colDef.suppressMovable).toBe(true);
|
||||
expect(colDef.headerStyle).toBeDefined();
|
||||
expect(colDef.cellStyle).toBeDefined();
|
||||
});
|
||||
|
||||
test('pageSize priority chain works correctly', () => {
|
||||
const props1 = {
|
||||
...basePropsNumericColumns,
|
||||
serverPagination: true,
|
||||
serverPaginationData: { currentPage: 2, pageSize: 10 },
|
||||
serverPageLength: 5,
|
||||
data: Array.from({ length: 3 }, () => ({ a: 1 })),
|
||||
showNumberedColumn: true,
|
||||
};
|
||||
const { result: res1 } = renderHook(() => useColDefs(props1), {
|
||||
wrapper: defaultThemeWrapper,
|
||||
});
|
||||
|
||||
expect(res1.current[0].width).toBe(42);
|
||||
|
||||
const props2 = {
|
||||
...props1,
|
||||
serverPaginationData: { currentPage: 2 },
|
||||
serverPageLength: 20,
|
||||
};
|
||||
const { result: res2 } = renderHook(() => useColDefs(props2), {
|
||||
wrapper: defaultThemeWrapper,
|
||||
});
|
||||
|
||||
expect(res2.current[0].width).toBe(42);
|
||||
});
|
||||
|
||||
test('column width adapts to max row number length in client mode', () => {
|
||||
const base = {
|
||||
...basePropsNumericColumns,
|
||||
showNumberedColumn: true,
|
||||
serverPagination: false,
|
||||
};
|
||||
|
||||
const props9 = { ...base, data: Array.from({ length: 9 }, () => ({ a: 1 })) };
|
||||
const { result: res9 } = renderHook(() => useColDefs(props9), {
|
||||
wrapper: defaultThemeWrapper,
|
||||
});
|
||||
expect(res9.current[0].width).toBe(36);
|
||||
|
||||
const props10 = {
|
||||
...base,
|
||||
data: Array.from({ length: 10 }, () => ({ a: 1 })),
|
||||
};
|
||||
const { result: res10 } = renderHook(() => useColDefs(props10), {
|
||||
wrapper: defaultThemeWrapper,
|
||||
});
|
||||
expect(res10.current[0].width).toBe(42);
|
||||
|
||||
const props100 = {
|
||||
...base,
|
||||
data: Array.from({ length: 100 }, () => ({ a: 1 })),
|
||||
};
|
||||
const { result: res100 } = renderHook(() => useColDefs(props100), {
|
||||
wrapper: defaultThemeWrapper,
|
||||
});
|
||||
expect(res100.current[0].width).toBe(48);
|
||||
});
|
||||
|
||||
test('row number column uses theme variables for styling', () => {
|
||||
const { result } = renderHook(
|
||||
() => useColDefs({ ...basePropsNumericColumns, showNumberedColumn: true }),
|
||||
{ wrapper: defaultThemeWrapper },
|
||||
);
|
||||
const colDef = result.current[0];
|
||||
expect(colDef.cellStyle).toMatchObject({
|
||||
backgroundColor: expect.any(String),
|
||||
padding: '0',
|
||||
textAlign: 'center',
|
||||
fontSize: '0.9em',
|
||||
color: expect.any(String),
|
||||
});
|
||||
expect(colDef.headerStyle).toMatchObject({
|
||||
backgroundColor: expect.any(String),
|
||||
fontSize: '1em',
|
||||
color: expect.any(String),
|
||||
});
|
||||
});
|
||||
|
||||
test('valueGetter handles missing node or rowIndex gracefully', () => {
|
||||
const { result } = renderHook(
|
||||
() => useColDefs({ ...basePropsNumericColumns, showNumberedColumn: true }),
|
||||
{ wrapper: defaultThemeWrapper },
|
||||
);
|
||||
const getter = result.current[0].valueGetter as (params: {
|
||||
node?: { rowIndex?: number };
|
||||
}) => number;
|
||||
expect(getter({})).toBe(1);
|
||||
expect(getter({ node: {} })).toBe(1);
|
||||
|
||||
const serverProps = {
|
||||
...basePropsNumericColumns,
|
||||
serverPagination: true,
|
||||
serverPaginationData: { currentPage: 2, pageSize: 5 },
|
||||
showNumberedColumn: true,
|
||||
};
|
||||
const { result: serverResult } = renderHook(() => useColDefs(serverProps), {
|
||||
wrapper: defaultThemeWrapper,
|
||||
});
|
||||
const serverGetter = serverResult.current[0].valueGetter as (params: {
|
||||
node?: { rowIndex?: number };
|
||||
}) => number;
|
||||
expect(serverGetter({})).toBe(2 * 5 + 1);
|
||||
expect(serverGetter({ node: {} })).toBe(11);
|
||||
});
|
||||
|
||||
@@ -288,7 +288,9 @@ describe('BigNumberWithTrendline transformProps', () => {
|
||||
height: 300,
|
||||
queriesData: [
|
||||
{
|
||||
data: [{ __timestamp: 1, value: 100 }] as unknown as BigNumberDatum[],
|
||||
data: [
|
||||
{ __timestamp: 1, value: 100 },
|
||||
] as unknown as BigNumberDatum[],
|
||||
colnames: ['__timestamp', 'value'],
|
||||
coltypes: ['TEMPORAL', 'NUMERIC'],
|
||||
},
|
||||
|
||||
@@ -21,13 +21,24 @@ import { histogramOperator } from '@superset-ui/chart-controls';
|
||||
import { HistogramFormData } from './types';
|
||||
|
||||
export default function buildQuery(formData: HistogramFormData) {
|
||||
const { column, groupby = [] } = formData;
|
||||
const { column, groupby = [], adhoc_filters } = formData;
|
||||
const hasHavingFilter = (adhoc_filters ?? []).some(
|
||||
(filter: { clause?: string }) => filter.clause === 'HAVING',
|
||||
);
|
||||
return buildQueryContext(formData, baseQueryObject => [
|
||||
{
|
||||
...baseQueryObject,
|
||||
columns: [...groupby, column],
|
||||
post_processing: [histogramOperator(formData, baseQueryObject)],
|
||||
metrics: undefined,
|
||||
metrics: hasHavingFilter
|
||||
? [
|
||||
{
|
||||
expressionType: 'SQL' as const,
|
||||
sqlExpression: 'COUNT(*)',
|
||||
label: 'COUNT(*)',
|
||||
},
|
||||
]
|
||||
: undefined,
|
||||
},
|
||||
]);
|
||||
}
|
||||
|
||||
@@ -284,11 +284,8 @@ function Echart(
|
||||
// setOption(notMerge:true) replaces the dataZoom config, dropping any
|
||||
// range the user has engaged. Preserve it across the call.
|
||||
const previousZoom = notMerge
|
||||
? (
|
||||
chartRef.current?.getOption() as {
|
||||
dataZoom?: DataZoomComponentOption[];
|
||||
}
|
||||
)?.dataZoom
|
||||
? (chartRef.current?.getOption() as { dataZoom?: DataZoomComponentOption[] })
|
||||
?.dataZoom
|
||||
: undefined;
|
||||
chartRef.current?.setOption(themedEchartOptions, {
|
||||
notMerge,
|
||||
|
||||
@@ -0,0 +1,81 @@
|
||||
/**
|
||||
* Licensed to the Apache Software Foundation (ASF) under one
|
||||
* or more contributor license agreements. See the NOTICE file
|
||||
* distributed with this work for additional information
|
||||
* regarding copyright ownership. The ASF licenses this file
|
||||
* to you under the Apache License, Version 2.0 (the
|
||||
* "License"); you may not use this file except in compliance
|
||||
* with the License. You may obtain a copy of the License at
|
||||
*
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing,
|
||||
* software distributed under the License is distributed on an
|
||||
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
|
||||
* KIND, either express or implied. See the License for the
|
||||
* specific language governing permissions and limitations
|
||||
* under the License.
|
||||
*/
|
||||
import buildQuery from '../../src/Histogram/buildQuery';
|
||||
import { HistogramFormData } from '../../src/Histogram/types';
|
||||
|
||||
const baseFormData: HistogramFormData = {
|
||||
datasource: '5__table',
|
||||
granularity_sqla: 'ds',
|
||||
column: 'price',
|
||||
groupby: [],
|
||||
bins: 10,
|
||||
viz_type: 'histogram',
|
||||
cumulative: false,
|
||||
normalize: false,
|
||||
sliceId: 1,
|
||||
showLegend: false,
|
||||
showValue: false,
|
||||
xAxisFormat: '',
|
||||
xAxisTitle: '',
|
||||
yAxisFormat: '',
|
||||
yAxisTitle: '',
|
||||
};
|
||||
|
||||
test('should build query with column and no metrics', () => {
|
||||
const queryContext = buildQuery(baseFormData);
|
||||
const [query] = queryContext.queries;
|
||||
expect(query.columns).toContain('price');
|
||||
expect(query.metrics).toBeUndefined();
|
||||
});
|
||||
|
||||
test('should include groupby columns in query columns', () => {
|
||||
const queryContext = buildQuery({ ...baseFormData, groupby: ['category'] });
|
||||
const [query] = queryContext.queries;
|
||||
expect(query.columns).toEqual(['category', 'price']);
|
||||
});
|
||||
|
||||
test('Regression for #30330: HAVING-clause metric filters require aggregation in the query', () => {
|
||||
/**
|
||||
* buildQuery unconditionally sets metrics: undefined, which means any
|
||||
* HAVING-clause adhoc_filter produces SQL with a HAVING clause but no
|
||||
* GROUP BY or aggregated metric — invalid SQL that most databases reject.
|
||||
*
|
||||
* The fix should preserve (or synthesise) a metric so the HAVING clause
|
||||
* has an aggregated value to filter on. This test asserts that desired
|
||||
* behaviour: when a HAVING adhoc_filter is present, query.metrics must
|
||||
* not be undefined or empty.
|
||||
*/
|
||||
const formDataWithHavingFilter: HistogramFormData = {
|
||||
...baseFormData,
|
||||
adhoc_filters: [
|
||||
{
|
||||
clause: 'HAVING',
|
||||
expressionType: 'SQL',
|
||||
sqlExpression: 'COUNT(*) > 5',
|
||||
},
|
||||
],
|
||||
};
|
||||
const queryContext = buildQuery(formDataWithHavingFilter);
|
||||
const [query] = queryContext.queries;
|
||||
|
||||
// HAVING filters without aggregation produce invalid SQL.
|
||||
// The query must include at least one metric when HAVING filters are present.
|
||||
expect(query.metrics).toBeDefined();
|
||||
expect((query.metrics as unknown[]).length).toBeGreaterThan(0);
|
||||
});
|
||||
@@ -20,8 +20,6 @@ import {
|
||||
ControlSetItem,
|
||||
ExtraControlProps,
|
||||
sharedControls,
|
||||
Dataset,
|
||||
ColumnMeta,
|
||||
} from '@superset-ui/chart-controls';
|
||||
import { t } from '@apache-superset/core/translation';
|
||||
import { ensureIsArray } from '@superset-ui/core';
|
||||
@@ -35,11 +33,7 @@ const dndAllColumns: typeof sharedControls.groupby = {
|
||||
mapStateToProps({ datasource, controls }, controlState) {
|
||||
const newState: ExtraControlProps = {};
|
||||
if (datasource) {
|
||||
if (datasource?.columns[0]?.hasOwnProperty('filterable')) {
|
||||
newState.options = (datasource as Dataset)?.columns?.filter(
|
||||
(c: ColumnMeta) => c.filterable,
|
||||
);
|
||||
} else newState.options = datasource.columns;
|
||||
newState.options = datasource.columns || [];
|
||||
}
|
||||
newState.queryMode = getQueryMode(controls);
|
||||
newState.externalValidationErrors =
|
||||
|
||||
@@ -21,8 +21,6 @@ import {
|
||||
ControlSetItem,
|
||||
ControlState,
|
||||
sharedControls,
|
||||
Dataset,
|
||||
ColumnMeta,
|
||||
defineSavedMetrics,
|
||||
} from '@superset-ui/chart-controls';
|
||||
import { t } from '@apache-superset/core/translation';
|
||||
@@ -77,11 +75,7 @@ export const metricsControlSetItem: ControlSetItem = {
|
||||
{ controls, datasource, form_data }: ControlPanelState,
|
||||
controlState: ControlState,
|
||||
) => ({
|
||||
columns: datasource?.columns[0]?.hasOwnProperty('filterable')
|
||||
? (datasource as Dataset)?.columns?.filter(
|
||||
(c: ColumnMeta) => c.filterable,
|
||||
)
|
||||
: datasource?.columns,
|
||||
columns: datasource?.columns || [],
|
||||
savedMetrics: defineSavedMetrics(datasource),
|
||||
// current active adhoc metrics
|
||||
selectedMetrics:
|
||||
|
||||
@@ -304,11 +304,7 @@ const config: ControlPanelConfig = {
|
||||
{ controls, datasource, form_data }: ControlPanelState,
|
||||
controlState: ControlState,
|
||||
) => ({
|
||||
columns: datasource?.columns[0]?.hasOwnProperty('filterable')
|
||||
? (datasource as Dataset)?.columns?.filter(
|
||||
(c: ColumnMeta) => c.filterable,
|
||||
)
|
||||
: datasource?.columns,
|
||||
columns: datasource?.columns || [],
|
||||
savedMetrics: defineSavedMetrics(datasource),
|
||||
// current active adhoc metrics
|
||||
selectedMetrics:
|
||||
|
||||
@@ -19,6 +19,7 @@
|
||||
import { GenericDataType } from '@apache-superset/core/common';
|
||||
import { QueryFormData } from '@superset-ui/core';
|
||||
import {
|
||||
ColumnMeta,
|
||||
Dataset,
|
||||
isCustomControlItem,
|
||||
ControlConfig,
|
||||
@@ -46,6 +47,32 @@ const findConditionalFormattingControl = (): ControlConfig | null => {
|
||||
return null;
|
||||
};
|
||||
|
||||
const findMetricsMapStateToProps = ():
|
||||
| ControlConfig['mapStateToProps']
|
||||
| null => {
|
||||
for (const section of config.controlPanelSections) {
|
||||
if (!section) continue;
|
||||
for (const row of section.controlSetRows) {
|
||||
for (const control of row) {
|
||||
if (
|
||||
control &&
|
||||
typeof control === 'object' &&
|
||||
'name' in control &&
|
||||
(control as { name: string }).name === 'metrics' &&
|
||||
'override' in control
|
||||
) {
|
||||
return (
|
||||
control as {
|
||||
override: { mapStateToProps: ControlConfig['mapStateToProps'] };
|
||||
}
|
||||
).override.mapStateToProps;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
return null;
|
||||
};
|
||||
|
||||
const createMockControlState = (value: string[] | undefined): ControlState => ({
|
||||
type: 'SelectControl',
|
||||
value,
|
||||
@@ -209,6 +236,50 @@ test('static extraColorChoices removed from config', () => {
|
||||
expect(controlConfig?.extraColorChoices).toBeUndefined();
|
||||
});
|
||||
|
||||
const createMockExploreWithColumns = (
|
||||
columns: Partial<ColumnMeta>[],
|
||||
): ControlPanelState => ({
|
||||
slice: { slice_id: 123 },
|
||||
datasource: {
|
||||
verbose_map: {},
|
||||
columns,
|
||||
metrics: [],
|
||||
} as Partial<Dataset> as Dataset,
|
||||
controls: {},
|
||||
form_data: {
|
||||
datasource: 'test',
|
||||
viz_type: 'table',
|
||||
} as QueryFormData,
|
||||
common: {},
|
||||
metadata: {},
|
||||
});
|
||||
|
||||
const createMockMetricsControlState = (): ControlState => ({
|
||||
type: 'MetricsControl',
|
||||
value: [],
|
||||
label: '',
|
||||
default: undefined,
|
||||
renderTrigger: false,
|
||||
});
|
||||
|
||||
test('metrics control includes non-filterable columns', () => {
|
||||
const mapStateToProps = findMetricsMapStateToProps();
|
||||
expect(mapStateToProps).toBeTruthy();
|
||||
|
||||
const explore = createMockExploreWithColumns([
|
||||
{ column_name: 'filterable_col', filterable: true },
|
||||
{ column_name: 'non_filterable_col', filterable: false },
|
||||
]);
|
||||
const result = mapStateToProps!(explore, createMockMetricsControlState());
|
||||
|
||||
expect(result.columns).toEqual(
|
||||
expect.arrayContaining([
|
||||
expect.objectContaining({ column_name: 'filterable_col' }),
|
||||
expect.objectContaining({ column_name: 'non_filterable_col' }),
|
||||
]),
|
||||
);
|
||||
});
|
||||
|
||||
test('columnOptions falls back to datasource columns when queriesResponse is empty', () => {
|
||||
const controlConfig = findConditionalFormattingControl();
|
||||
expect(controlConfig).toBeTruthy();
|
||||
|
||||
@@ -20,7 +20,7 @@
|
||||
import { useRef, useEffect, FC, useMemo } from 'react';
|
||||
|
||||
import { useSelector } from 'react-redux';
|
||||
import { useAppDispatch } from 'src/views/store';
|
||||
import { useAppDispatch } from 'src/SqlLab/hooks/useAppDispatch';
|
||||
import { logging } from '@apache-superset/core/utils';
|
||||
import {
|
||||
SqlLabRootState,
|
||||
|
||||
@@ -18,7 +18,7 @@
|
||||
*/
|
||||
import { useState, useEffect, useRef, useCallback, useMemo } from 'react';
|
||||
import { shallowEqual, useSelector } from 'react-redux';
|
||||
import { useAppDispatch } from 'src/views/store';
|
||||
import { useAppDispatch } from 'src/SqlLab/hooks/useAppDispatch';
|
||||
import { usePrevious } from '@superset-ui/core';
|
||||
import { css, useTheme } from '@apache-superset/core/theme';
|
||||
import { Global } from '@emotion/react';
|
||||
|
||||
@@ -18,7 +18,7 @@
|
||||
*/
|
||||
import { useEffect, useMemo, useRef } from 'react';
|
||||
import { useStore } from 'react-redux';
|
||||
import { useAppDispatch } from 'src/views/store';
|
||||
import { useAppDispatch } from 'src/SqlLab/hooks/useAppDispatch';
|
||||
import { t } from '@apache-superset/core/translation';
|
||||
import { getExtensionsRegistry } from '@superset-ui/core';
|
||||
|
||||
|
||||
@@ -17,7 +17,7 @@
|
||||
* under the License.
|
||||
*/
|
||||
import { useSelector } from 'react-redux';
|
||||
import { useAppDispatch } from 'src/views/store';
|
||||
import { useAppDispatch } from 'src/SqlLab/hooks/useAppDispatch';
|
||||
import { t } from '@apache-superset/core/translation';
|
||||
import { VizType } from '@superset-ui/core';
|
||||
import {
|
||||
|
||||
@@ -18,7 +18,7 @@
|
||||
*/
|
||||
import { useEffect, useState } from 'react';
|
||||
import { useSelector } from 'react-redux';
|
||||
import { useAppDispatch } from 'src/views/store';
|
||||
import { useAppDispatch } from 'src/SqlLab/hooks/useAppDispatch';
|
||||
import URI from 'urijs';
|
||||
import { pick } from 'lodash';
|
||||
import { useComponentDidUpdate } from '@superset-ui/core';
|
||||
|
||||
@@ -18,7 +18,7 @@
|
||||
*/
|
||||
import { useRef } from 'react';
|
||||
import { useSelector } from 'react-redux';
|
||||
import { useAppDispatch } from 'src/views/store';
|
||||
import { useAppDispatch } from 'src/SqlLab/hooks/useAppDispatch';
|
||||
import { isObject } from 'lodash';
|
||||
import rison from 'rison';
|
||||
import {
|
||||
|
||||
@@ -16,7 +16,7 @@
|
||||
* specific language governing permissions and limitations
|
||||
* under the License.
|
||||
*/
|
||||
import { useAppDispatch } from 'src/views/store';
|
||||
import { useAppDispatch } from 'src/SqlLab/hooks/useAppDispatch';
|
||||
import { t } from '@apache-superset/core/translation';
|
||||
import { Dropdown, Button } from '@superset-ui/core/components';
|
||||
import { Menu } from '@superset-ui/core/components/Menu';
|
||||
|
||||
@@ -31,7 +31,7 @@ import { t } from '@apache-superset/core/translation';
|
||||
import { QueryResponse, QueryState } from '@superset-ui/core';
|
||||
import { useTheme } from '@apache-superset/core/theme';
|
||||
import { shallowEqual, useSelector } from 'react-redux';
|
||||
import { useAppDispatch } from 'src/views/store';
|
||||
import { useAppDispatch } from 'src/SqlLab/hooks/useAppDispatch';
|
||||
|
||||
import {
|
||||
queryEditorSetSql,
|
||||
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user