diff --git a/docs/development/plugins.md b/docs/development/plugins.md index 606114fd..5ef5dc71 100644 --- a/docs/development/plugins.md +++ b/docs/development/plugins.md @@ -185,7 +185,8 @@ Providers own functionality; compositions own navigation. Installing a plugin do | `menus` | Legacy default placement inside Console, including `parent/group/order/children` | | `entries` | Reusable business pages registered by stable provider/name identity; no automatic menu placement | | provider `scopes` | Context/title/icon metadata; not an application declaration | -| `registerNavigationComposition` | Ordered groups of provider/entry references; supplies a named application's navigation | +| `createPlugin({ navigationComposition })` | Named application owned by the same plugin as its business pages | +| `registerNavigationComposition` | A separate navigation-only plugin with ordered groups of provider/entry references | | host composition | `web/src/shell/console-navigation.ts`; the same group/reference model orders Console's built-in and plugin entries | ```tsx @@ -199,6 +200,15 @@ groups: [{ }], ``` +A plugin that includes both Console pages and an application can place its +Console pages in `menus` and its application pages in `entries`. Declare the +application scopes and groups in `navigationComposition`, and reference the +entries by their provider and name. An application is identified as +`/`. Set `launcher: false` inside the composition to keep +the application available through an account menu link or its routes while +hiding its launcher card. Shared route namespaces use the ordinary menus for +their default landing page. + - Change group/reference array order to reorder menus without changing plugin bundles or module load order. - Unreferenced legacy menus keep their default Console placement. North Star/Canary therefore integrates into Console, not a separate application. - References never override page components, permissions, backend checks or translation ownership. Missing providers and denied/hidden ancestors produce no menu. @@ -214,6 +224,34 @@ Authenticated `/clusters/{value}/oapis/` aliases do not select another cluster. not authorization aggregation. See the [single-cluster design](single-cluster-applications-design.md) for the unchanged original Dashboard Charts and browser verification. +### Account menu links + +Set `userMenu` on `createPlugin()` to add links to the account dropdown. Use +an entry name from your plugin or an application ID from a registered +navigation composition. + +```ts +userMenu: [ + { id: "overview", title: "My Plugin", target: { kind: "entry", name: "my-plugin" } }, + { id: "settings", title: "Settings", target: { kind: "application", id: "my-settings/platform" } }, +], +``` + +- Each `id` is unique within the plugin and uses kebab-case. Translate the + label at `userMenu.` in the plugin's namespace. The declared `title` + serves as the fallback. +- Set `order` to place the link among other plugin links. It defaults to + `999`, with ties sorted by plugin ID and link ID. +- An entry target resolves to a static page owned by this plugin. Console + checks the same visibility and permission rules it uses for navigation. +- An application target opens its default page if the user can access it + and the first accessible landing page otherwise. Console hides the link + if the application has no accessible landing page. + +Console resolves these links from the currently available plugins and pages. +Page guards and backend authorization still apply. An older Console with the +same SDK major version ignores account menu declarations. + ### Routes Menu paths and route keys are normalized before matching; a matching route @@ -230,6 +268,52 @@ Hidden or denied ancestors hide their navigation subtree, while child routes remain registered with their own guards. Detail routes inherit their nearest menu's `authKey`; backend authorization remains independent. +### Model details tabs + +Register a presentation with `resourceType: "catalog-model"` and +`placement: "resource.tabs"` to add a tab to the model details page. +Register the tab's component in the same plugin. + +```tsx +components: { ModelHistory }, +presentationExtensions: [{ + id: "model-history", + key: "history", + resourceType: "catalog-model", + placement: "resource.tabs", + component: "ModelHistory", + authKey: "my-plugin.history.view", + tab: { title: "History", order: 20 }, +}], +``` + +The component receives `resourceType`, `resourceKey`, `resource`, and `data`. +The SDK's `CatalogModelResource` describes `resource`, including the selected +catalog, model, variant references, and the resolved serving name and weights +path when available. The tab key is unique within the plugin for this surface. +Ordering defaults to `999`. If the plugin registers a backend, the tab also +requires read access to that backend. + +### Model catalog actions + +Register a presentation for the action's location. Its component can render a +button or a link using the catalog and model it receives. + +| Location | `resourceType` | `placement` | SDK resource type | +| --- | --- | --- | --- | +| Model library card footer | `catalog-model` | `collection.card.actions` | `CatalogModelResource` | +| Model details toolbar | `catalog-model` | `resource.header.actions` | `CatalogModelResource` | +| Recipe card footer on model details | `catalog-variant` | `collection.card.actions` | `CatalogVariantResource` | + +The model library card receives the catalog's model summary. Detail actions +also receive the resolved weights path and serving name when available. Recipe +actions receive the selected variant's ID, version, and digest. Use those +fields together when resolving a recipe in the plugin. + +The host checks the contribution's optional `authKey` and read access to the +registered plugin backend. The destination and its backend still enforce their +own permissions. + ### Data and permissions ```tsx @@ -354,6 +438,30 @@ spec: A frontend-only plugin needs no `ReverseProxy` and no IAM role. It appears in the sidebar for every authenticated user who can load Console. +### Authorization for configured backends + +For integrations listed under `backends` in the Console server configuration, +`accessRules` can assign a separate `backends` resource name and verb to an +endpoint. For example, approve reports with a dedicated role that grants +`update` on `report-approvals`. + +```yaml +backends: + - name: reports + prefix: /api/reports + url: https://reports.example.com + accessRules: + - pathPrefix: /approvals + methods: [POST] + resourceName: report-approvals + verb: update +``` + +Console matches the longest backend-relative path prefix on a path segment +boundary for the incoming method. An unmatched request uses the backend's name +and the standard method-to-verb mapping. Use a `/` rule with a separate resource +name when access to unmatched endpoints must have its own grant. + ## 7. Capabilities `provides` publishes values other packages can consume; `consumes` declares diff --git a/internal/config/config.go b/internal/config/config.go index 407b8167..b8433ff9 100644 --- a/internal/config/config.go +++ b/internal/config/config.go @@ -11,10 +11,12 @@ import ( "fmt" "net/url" "os" + "path" "path/filepath" "regexp" "strings" "time" + "unicode" "gopkg.in/yaml.v3" ) @@ -114,7 +116,16 @@ type Backend struct { // namespace can still take a copied key through a Secret volume. APIKeyEnv string `yaml:"apiKeyEnv,omitempty"` // WritePermission is an optional permission required in addition to backend update access. - WritePermission string `yaml:"writePermission,omitempty"` + WritePermission string `yaml:"writePermission,omitempty"` + AccessRules []BackendAccessRule `yaml:"accessRules,omitempty"` +} + +// BackendAccessRule overrides authorization for a backend-relative path and HTTP methods. +type BackendAccessRule struct { + PathPrefix string `yaml:"pathPrefix"` + Methods []string `yaml:"methods"` + ResourceName string `yaml:"resourceName"` + Verb string `yaml:"verb"` } // Gateway is an inference entrypoint resolved from the cluster at startup and @@ -311,9 +322,50 @@ func validateBackend(b Backend) error { if b.APIKeyEnv != "" && !envNameRE.MatchString(b.APIKeyEnv) { return fmt.Errorf("apiKeyEnv %q is not an environment variable name", b.APIKeyEnv) } + if err := validateBackendAccessRules(b.AccessRules); err != nil { + return err + } return nil } +func validateBackendAccessRules(rules []BackendAccessRule) error { + seen := make(map[string]bool) + for i, rule := range rules { + prefix := rule.PathPrefix + if !CanonicalBackendPath(prefix) || (prefix != "/" && strings.HasSuffix(prefix, "/")) { + return fmt.Errorf("accessRules[%d]: pathPrefix must be a clean backend-relative path", i) + } + if len(rule.Methods) == 0 || strings.TrimSpace(rule.ResourceName) != rule.ResourceName || rule.ResourceName == "" { + return fmt.Errorf("accessRules[%d]: methods and resourceName are required", i) + } + switch rule.Verb { + case "get", "create", "update", "delete": + default: + return fmt.Errorf("accessRules[%d]: verb must be get, create, update or delete", i) + } + for _, method := range rule.Methods { + switch method { + case "GET", "HEAD", "OPTIONS", "POST", "PUT", "PATCH", "DELETE": + default: + return fmt.Errorf("accessRules[%d]: unsupported HTTP method %q", i, method) + } + key := method + " " + prefix + if seen[key] { + return fmt.Errorf("accessRules[%d]: duplicate rule for %s", i, key) + } + seen[key] = true + } + } + return nil +} + +// CanonicalBackendPath permits a trailing slash but rejects ambiguous decoded paths. +func CanonicalBackendPath(p string) bool { + return strings.HasPrefix(p, "/") && + (p == "/" || path.Clean(p) == strings.TrimSuffix(p, "/")) && + !strings.ContainsAny(p, "%?#\\") && !strings.ContainsFunc(p, unicode.IsControl) +} + // validateGateway checks only what can be known without the cluster. Whether the // profile names a Service, whether the route ConfigMap has an aggregate route -- // those are answered at startup where the answer can be logged with the reason. diff --git a/internal/config/config_test.go b/internal/config/config_test.go index f6a1073c..46ced644 100644 --- a/internal/config/config_test.go +++ b/internal/config/config_test.go @@ -123,6 +123,34 @@ func TestBackendAPIKey(t *testing.T) { } } +func TestValidateBackendAccessRules(t *testing.T) { + base := BackendAccessRule{PathPrefix: "/policies", Methods: []string{"POST"}, ResourceName: "autotune-settings", Verb: "create"} + testCases := []struct { + name string + rules []BackendAccessRule + wantErr string + }{ + {"separate methods", []BackendAccessRule{base, {PathPrefix: "/policies", Methods: []string{"PUT"}, ResourceName: "autotune-settings", Verb: "update"}}, ""}, + {"catch-all", []BackendAccessRule{base, {PathPrefix: "/", Methods: []string{"POST"}, ResourceName: "autotune-unmapped", Verb: "create"}}, ""}, + {"duplicate method", []BackendAccessRule{base, base}, "duplicate rule"}, + {"trailing slash", []BackendAccessRule{{PathPrefix: "/policies/", Methods: base.Methods, ResourceName: base.ResourceName, Verb: base.Verb}}, "clean backend-relative path"}, + {"missing resource name", []BackendAccessRule{{PathPrefix: "/policies", Methods: base.Methods, Verb: base.Verb}}, "methods and resourceName"}, + {"unsupported method", []BackendAccessRule{{PathPrefix: "/policies", Methods: []string{"post"}, ResourceName: base.ResourceName, Verb: base.Verb}}, "unsupported HTTP method"}, + } + for _, tc := range testCases { + t.Run(tc.name, func(t *testing.T) { + backend := Backend{Name: "autotune", Prefix: "/api/autotune", URL: "http://autotune:8000/api", AccessRules: tc.rules} + err := validateBackend(backend) + if tc.wantErr == "" && err != nil { + t.Fatalf("unexpected error: %v", err) + } + if tc.wantErr != "" && (err == nil || !strings.Contains(err.Error(), tc.wantErr)) { + t.Fatalf("want error containing %q, got %v", tc.wantErr, err) + } + }) + } +} + // document is what a config file says, and the YAML key names are part of the // contract: KnownFields turns a typo into a startup failure instead of a setting // that quietly does nothing. diff --git a/internal/server/proxy.go b/internal/server/proxy.go index 8066a4f1..303b5aca 100644 --- a/internal/server/proxy.go +++ b/internal/server/proxy.go @@ -6,6 +6,7 @@ import ( "net/http" "net/http/httputil" "net/url" + "slices" "strings" "github.com/modelsphere/console/internal/config" @@ -72,8 +73,14 @@ func (s *Server) mountBackends(mux *http.ServeMux) { mux.HandleFunc(prefix+"/route-options", func(w http.ResponseWriter, r *http.Request) { s.handleRouteOptions(w, r, b, catalogResolve) }) - mux.HandleFunc(strings.TrimSuffix(b.Prefix, "/")+"/", func(w http.ResponseWriter, r *http.Request) { - if !s.authorize(w, r, backendVerb(r.Method), backendResource, b.Name) { + mux.HandleFunc(prefix+"/", func(w http.ResponseWriter, r *http.Request) { + relative := strings.TrimPrefix(r.URL.Path, prefix) + if len(b.AccessRules) > 0 && !config.CanonicalBackendPath(relative) { + writeError(w, http.StatusBadRequest, "invalid backend path") + return + } + verb, name := backendAccess(b, r.Method, relative) + if !s.authorize(w, r, verb, backendResource, name) { return } target, err := resolve(r.Context()) @@ -104,6 +111,20 @@ func (s *Server) mountBackends(mux *http.ServeMux) { } } +func backendAccess(b config.Backend, method, relative string) (verb, resourceName string) { + verb, resourceName = backendVerb(method), b.Name + longest := 0 + for _, rule := range b.AccessRules { + prefix := rule.PathPrefix + if len(prefix) > longest && (prefix == "/" || relative == prefix || strings.HasPrefix(relative, prefix+"/")) && + slices.Contains(rule.Methods, method) { + verb, resourceName = rule.Verb, rule.ResourceName + longest = len(prefix) + } + } + return verb, resourceName +} + // backendTargets resolves each backend once for the process: a gateway resolver // holds a cache, and the router and the backend's own prefix share it. func (s *Server) backendTargets() map[string]targetResolver { diff --git a/internal/server/proxy_test.go b/internal/server/proxy_test.go index d9949af1..f0656ea5 100644 --- a/internal/server/proxy_test.go +++ b/internal/server/proxy_test.go @@ -137,6 +137,58 @@ func TestProxyAuthorizesPerBackendAndVerb(t *testing.T) { } } +func TestProxySeparatesBackendAccessFromSettingsWrites(t *testing.T) { + up, seen := upstream(t) + h := testServerWithConfig(t, &config.Config{Backends: []config.Backend{{ + Name: "autotune", Prefix: "/api/autotune", URL: up.URL + "/api", + AccessRules: []config.BackendAccessRule{ + {PathPrefix: "/search-spaces", Methods: []string{"POST"}, ResourceName: "autotune-settings", Verb: "create"}, + {PathPrefix: "/search-spaces/preview", Methods: []string{"POST"}, ResourceName: "autotune", Verb: "get"}, + {PathPrefix: "/policies", Methods: []string{"POST"}, ResourceName: "autotune-settings", Verb: "create"}, + {PathPrefix: "/policies", Methods: []string{"PUT", "PATCH"}, ResourceName: "autotune-settings", Verb: "update"}, + {PathPrefix: "/policies", Methods: []string{"DELETE"}, ResourceName: "autotune-settings", Verb: "delete"}, + {PathPrefix: "/settings", Methods: []string{"GET", "HEAD", "OPTIONS"}, ResourceName: "autotune-settings", Verb: "get"}, + {PathPrefix: "/settings", Methods: []string{"PUT", "PATCH"}, ResourceName: "autotune-settings", Verb: "update"}, + {PathPrefix: "/campaigns", Methods: []string{"POST"}, ResourceName: "autotune", Verb: "create"}, + {PathPrefix: "/", Methods: []string{"POST", "PUT", "PATCH", "DELETE"}, ResourceName: "autotune-unmapped", Verb: "update"}, + }, + }}}).Handler() + bob := login(t, h, "bob", "bob-pw") + check := func(method, endpoint string, status int) { + t.Helper() + if rec := do(h, method, "/api/autotune"+endpoint, bob, ""); rec.Code != status { + t.Fatalf("%s %s: want %d, got %d %s", method, endpoint, status, rec.Code, rec.Body.String()) + } + } + + grantNamedBackend(t, h, "bob", "autotune", "get") + check("GET", "/policies", http.StatusTeapot) + check("POST", "/search-spaces/preview?limit=3", http.StatusTeapot) + check("POST", "/campaigns", http.StatusForbidden) + + for _, verb := range []string{"create", "update", "delete"} { + grantNamedBackend(t, h, "bob", "autotune", verb) + } + check("POST", "/campaigns", http.StatusTeapot) + check("POST", "/policies", http.StatusForbidden) + check("PUT", "/policies/7", http.StatusForbidden) + check("PATCH", "/policies/7", http.StatusForbidden) + check("DELETE", "/policies/7", http.StatusForbidden) + check("POST", "/search-spaces", http.StatusForbidden) + check("POST", "/search-spaces/previews", http.StatusForbidden) + check("POST", "/other", http.StatusForbidden) + check("GET", "/settings", http.StatusForbidden) + check("HEAD", "/settings", http.StatusForbidden) + check("PUT", "/settings", http.StatusForbidden) + + grantNamedBackend(t, h, "bob", "autotune-settings", "update") + check("PUT", "/policies/7", http.StatusTeapot) + check("PUT", "/other", http.StatusForbidden) + if len(*seen) != 4 || (*seen)[1].path != "/api/search-spaces/preview" || (*seen)[1].query != "limit=3" { + t.Fatalf("unexpected upstream requests: %+v", *seen) + } +} + // A backend with a credential of its own (the model gateway) gets that key as // its Bearer token, not the caller's session -- the session authorizes the // caller to console, and nothing else. @@ -350,13 +402,19 @@ func TestProxyLeavesOwnRoutesAlone(t *testing.T) { // grantBackend binds user to a role allowing verb on the "swiss" backend. func grantBackend(t *testing.T, h http.Handler, user, verb string) { + t.Helper() + grantNamedBackend(t, h, user, "swiss", verb) +} + +func grantNamedBackend(t *testing.T, h http.Handler, user, backend, verb string) { t.Helper() admin := login(t, h, "admin", "admin-pw") - role := `{"name":"swiss-` + verb + `","rules":[{"verbs":["` + verb + `"],"apiGroups":["iam.theriseunion.io"],"resources":["backends"],"resourceNames":["swiss"]}]}` + name := backend + "-" + verb + role := fmt.Sprintf(`{"name":%q,"rules":[{"verbs":[%q],"apiGroups":["iam.theriseunion.io"],"resources":["backends"],"resourceNames":[%q]}]}`, name, verb, backend) if rec := do(h, "POST", "/api/iam/roles", admin, role); rec.Code != http.StatusCreated { t.Fatalf("create role: %d %s", rec.Code, rec.Body.String()) } - binding := `{"name":"` + user + `-swiss-` + verb + `","role":"swiss-` + verb + `","subjects":[{"kind":"User","name":"` + user + `"}]}` + binding := fmt.Sprintf(`{"name":%q,"role":%q,"subjects":[{"kind":"User","name":%q}]}`, user+"-"+name, name, user) if rec := do(h, "POST", "/api/iam/rolebindings", admin, binding); rec.Code != http.StatusCreated { t.Fatalf("create binding: %d %s", rec.Code, rec.Body.String()) } diff --git a/internal/server/route_options.go b/internal/server/route_options.go index 6b074a7e..875a5e40 100644 --- a/internal/server/route_options.go +++ b/internal/server/route_options.go @@ -23,7 +23,8 @@ func (s *Server) handleRouteOptions(w http.ResponseWriter, r *http.Request, b co writeError(w, http.StatusMethodNotAllowed, "GET required") return } - if !s.authorize(w, r, "get", backendResource, b.Name) { + verb, name := backendAccess(b, r.Method, "/route-options") + if !s.authorize(w, r, verb, backendResource, name) { return } route := r.URL.Query().Get("route") diff --git a/web/packages/plugin-sdk/src/core.ts b/web/packages/plugin-sdk/src/core.ts index 4d62a42b..5cbeccb2 100644 --- a/web/packages/plugin-sdk/src/core.ts +++ b/web/packages/plugin-sdk/src/core.ts @@ -119,6 +119,11 @@ function validatePluginDefinition(def: unknown): void { def.menus.forEach((menu, index) => validateMenu(pluginName, `menus[${index}]`, menu)) } + if (def.entries !== undefined) { + if (!Array.isArray(def.entries)) validationError(pluginName, 'entries', '必须是数组') + def.entries.forEach((entry, index) => validateMenu(pluginName, `entries[${index}]`, entry)) + } + if (def.scopes !== undefined) { if (!Array.isArray(def.scopes)) validationError(pluginName, 'scopes', '必须是数组') def.scopes.forEach((scope, index) => { @@ -427,6 +432,9 @@ function registerDefinition(sdk: RiseHostSDK, def: PluginDefinition): void { scope: '', // plugin-level scope left empty for child plugins scopes: def.scopes || undefined, menus: bridgedMenus, + ...(def.entries === undefined ? {} : { entries: def.entries }), + ...(def.navigationComposition === undefined ? {} : { navigationComposition: def.navigationComposition }), + ...(def.userMenu === undefined ? {} : { userMenu: def.userMenu }), }) } diff --git a/web/packages/plugin-sdk/src/index.ts b/web/packages/plugin-sdk/src/index.ts index c1823a47..03cae679 100644 --- a/web/packages/plugin-sdk/src/index.ts +++ b/web/packages/plugin-sdk/src/index.ts @@ -6,6 +6,8 @@ export type { Scope, ViewMode, PluginMenu, + ScopeDeclaration, + PluginNavigationComposition, PluginContext, PluginAPI, RequestOpts, @@ -16,7 +18,12 @@ export type { DataExtensionRegistration, VisibilityExtensionRegistration, PresentationExtensionRegistration, + CatalogModelResource, + CatalogVariantReference, + CatalogVariantResource, ActionExtensionRegistration, + UserMenuTarget, + UserMenuItemDefinition, PluginDefinition, PluginInstance, RiseHostSDK, diff --git a/web/packages/plugin-sdk/src/types.ts b/web/packages/plugin-sdk/src/types.ts index df4630f6..6c8fdc33 100644 --- a/web/packages/plugin-sdk/src/types.ts +++ b/web/packages/plugin-sdk/src/types.ts @@ -232,6 +232,38 @@ export interface PresentationExtensionRegistration { placement: string key: string component: string + /** Console UI permission required to render this contribution. */ + authKey?: string + /** Metadata for a contribution at resource.tabs. */ + tab?: { title: string; order?: number } +} + +export interface CatalogVariantReference { + id: string + version: string + digest: string + engine: string + servedName?: string + default?: boolean + deprecated?: boolean | string +} + +export interface CatalogModelResource { + catalog: string + model: { + name: string + displayName?: string + source: { hf: string; revision?: string } + defaultVariant: string + variants: readonly CatalogVariantReference[] + } + schema?: 'v1' | 'v2' + localPath?: string + servedName?: string +} + +export interface CatalogVariantResource extends CatalogModelResource { + variant: CatalogVariantReference } export interface ActionExtensionRegistration { @@ -241,6 +273,21 @@ export interface ActionExtensionRegistration { evaluate: (context: { resourceType: string; resourceKey: string; resource: unknown; data: Record; action: string }) => false | string } +export type UserMenuTarget = + | { kind: 'entry'; name: string } + | { kind: 'application'; id: string } + +export interface UserMenuItemDefinition { + /** Unique kebab-case identifier within this plugin. */ + id: string + /** Fallback label for the plugin's userMenu. translation. */ + title: string + /** Sort order, defaulting to 999. */ + order?: number + /** Own static entry or the stable ID of an application. */ + target: UserMenuTarget +} + // ── Scope Declaration (Dock metadata) ──────────────────────── /** Declares a Dock entry for a specific scope. */ @@ -261,6 +308,17 @@ export interface ScopeDeclaration { path?: string } +export interface PluginNavigationComposition { + scopes: ScopeDeclaration[] + groups: { + name: string + title: string + menus: { provider: string; entry: string; scope?: string; viewport?: string }[] + }[] + /** Set to false to expose the application through account menu links and URLs. */ + launcher?: boolean +} + // ── Plugin Definition (createPlugin input) ────────────────── /** Input to `createPlugin()`. */ @@ -284,6 +342,15 @@ export interface PluginDefinition { /** Menu items to register */ menus?: PluginMenu[] + /** Business pages that can be referenced by a navigation composition. */ + entries?: PluginMenu[] + + /** A named application owned by this plugin. */ + navigationComposition?: PluginNavigationComposition + + /** Links contributed to the Console account menu. */ + userMenu?: UserMenuItemDefinition[] + /** * React components to register. Keys are component names, * values are React component functions/classes. diff --git a/web/packages/plugin-sdk/test/core.test.ts b/web/packages/plugin-sdk/test/core.test.ts index 12b45dd4..2bd8888d 100644 --- a/web/packages/plugin-sdk/test/core.test.ts +++ b/web/packages/plugin-sdk/test/core.test.ts @@ -357,6 +357,34 @@ describe('typed events', () => { }) describe('registration contract validation', () => { + it('forwards business entries and their application composition with the plugin definition', async () => { + const { registerPlugin } = installHost() + const createPlugin = await loadCreatePlugin() + const entries = [{ name: 'settings', path: '/example/settings', scope: 'platform' as const }] + const navigationComposition = { + scopes: [{ scope: 'platform', path: '/example/settings' }], + groups: [{ name: 'settings', title: '', menus: [{ provider: 'modelsphere.dev/example', entry: 'settings' }] }], + launcher: false, + } + + createPlugin({ ...baseDefinition, entries, navigationComposition }) + + expect(registerPlugin).toHaveBeenCalledWith(expect.objectContaining({ entries, navigationComposition })) + }) + + it('forwards account menu links with the plugin definition', async () => { + const { registerPlugin } = installHost() + const createPlugin = await loadCreatePlugin() + const userMenu: NonNullable = [ + { id: 'reports', title: 'Reports', order: 50, target: { kind: 'entry', name: 'reports' } }, + { id: 'settings', title: 'Settings', target: { kind: 'application', id: 'example/platform' } }, + ] + + createPlugin({ ...baseDefinition, userMenu }) + + expect(registerPlugin).toHaveBeenCalledWith(expect.objectContaining({ userMenu })) + }) + it('preserves scope visibility restrictions and recursive menus across the host bridge', async () => { const { registerPlugin } = installHost() const createPlugin = await loadCreatePlugin() diff --git a/web/packages/ui/src/components/detail-header.tsx b/web/packages/ui/src/components/detail-header.tsx index ae3bc89d..ba75b8bb 100644 --- a/web/packages/ui/src/components/detail-header.tsx +++ b/web/packages/ui/src/components/detail-header.tsx @@ -90,6 +90,7 @@ export interface DetailHeaderProps { * (LF 2026-09-15)。没有「平铺几个、剩下折叠」这种混合形态。 */ actions?: DetailAction[] + additionalActions?: React.ReactNode /** 规格条。空数组或不传则整块消失(含分隔线) */ meta?: DetailMetaItem[] @@ -201,6 +202,7 @@ export function DetailHeader({ accent, notice, actions = [], + additionalActions, meta = [], metaColumns = 4, tabs, @@ -209,6 +211,7 @@ export function DetailHeader({ const t = useUiT() const backText = backLabel === undefined ? t("shared.back") : backLabel const accentTone = accent === false ? null : (accent ?? status?.tone ?? null) + const showToolbar = Boolean(onBack || actions.length || additionalActions) // 要么全平铺、要么全折叠 —— 见 INLINE_ACTION_LIMIT。 const foldAll = actions.length > INLINE_ACTION_LIMIT const inline = foldAll ? [] : actions @@ -239,7 +242,7 @@ export function DetailHeader({ )}
- {(onBack || actions.length > 0) && ( + {showToolbar && (
{onBack ? ( // 用箭头而不是折角(chevron):折角在导航里表达的是「展开/下一级」, @@ -257,7 +260,7 @@ export function DetailHeader({ )} -
+
{inline.map((a) => ( ))} @@ -298,12 +301,13 @@ export function DetailHeader({ )} + {additionalActions}
)} {/* ── 标题行 ── */} -
+
{icon && ( {icon} diff --git a/web/packages/ui/src/components/section-card.tsx b/web/packages/ui/src/components/section-card.tsx index 7539c52f..514d05a1 100644 --- a/web/packages/ui/src/components/section-card.tsx +++ b/web/packages/ui/src/components/section-card.tsx @@ -96,6 +96,7 @@ export interface SectionCardProps { * 只在内容必须常驻、不能藏进浮层时才给(开发明确要求的那种)。 */ footer?: React.ReactNode + footerClassName?: string children?: React.ReactNode className?: string @@ -120,6 +121,7 @@ export function SectionCard({ onRetry, empty, footer, + footerClassName, children, className, contentClassName, @@ -299,7 +301,7 @@ export function SectionCard({ {/* 脚注:配了才出现,连同它上面那条分隔线 */} {footer && ( -