Skip to content

#1 PDF Application on GitHub that lets you edit PDFs on any device anywhere

Fix bugs on Pipelines page (#7801)

James Brunton0d099cafbc18
diff --git a/app/proprietary/src/main/java/stirling/software/proprietary/policy/controller/PolicyController.java b/app/proprietary/src/main/java/stirling/software/proprietary/policy/controller/PolicyController.java
index 3851ffa786..69a547c28b 100644
--- a/app/proprietary/src/main/java/stirling/software/proprietary/policy/controller/PolicyController.java
+++ b/app/proprietary/src/main/java/stirling/software/proprietary/policy/controller/PolicyController.java
@@ -67,6 +67,7 @@ import stirling.software.proprietary.policy.model.PipelineStep;
import stirling.software.proprietary.policy.model.PipelineValidation;
import stirling.software.proprietary.policy.model.Policy;
import stirling.software.proprietary.policy.model.PolicyInputs;
+import stirling.software.proprietary.policy.model.PolicyPermissions;
import stirling.software.proprietary.policy.model.PolicyRun;
import stirling.software.proprietary.policy.model.PolicyRunStatus;
import stirling.software.proprietary.policy.model.PolicyRunView;
@@ -275,6 +276,12 @@ public class PolicyController {
public ResponseEntity<Policy> savePolicy(@RequestBody Policy policy) {
requirePolicyEditingAllowed();
Policy owned = withStoredOutputSecrets(resolveOwnership(policy));
+ // Snapshot the previous version before saving so supporting files this edit dropped can
+ // be cleaned up once nothing references them.
+ Policy previous =
+ owned.id() == null || owned.id().isBlank()
+ ? null
+ : policyStore.get(owned.id()).orElse(null);
requireAccessibleSources(owned);
requireAccessibleOutput(owned);
try {
@@ -282,12 +289,6 @@ public class PolicyController {
} catch (IllegalArgumentException e) {
throw new ResponseStatusException(HttpStatus.BAD_REQUEST, e.getMessage());
}
- // Snapshot the previous version before saving so supporting files this edit dropped can
- // be cleaned up once nothing references them.
- Policy previous =
- owned.id() == null || owned.id().isBlank()
- ? null
- : policyStore.get(owned.id()).orElse(null);
Policy saved = policyStore.save(owned);
assetCleaner.cleanupAfterSave(previous, saved);
// Re-sync trigger registrations now so a new/changed folder-watch policy starts being
@@ -444,15 +445,10 @@ public class PolicyController {
}
/**
- * Creating, editing, pausing/resuming, and deleting policies requires the editor role for the
- * caller's team — a team leader on SaaS (see {@link PolicyManagementAuthority}); the global
- * admin gets no say on SaaS. Team scoping (which team's policies) is enforced separately by
- * {@link PolicyAccessGuard}. Every mutation routes through {@link #savePolicy} (pause/resume
- * re-save with a flipped {@code enabled} flag) or {@link #deletePolicy}, so gating those two
- * covers them all; runs over the caller's own files ({@code /{id}/run}) stay open to the team,
- * while source sweeps are gated by {@link #requirePolicySweepAllowed}. Single-user deployments
- * (login disabled) have no such role, so they trust the local operator. The path allowlist for
- * folder sources/outputs is enforced separately by {@link PolicyValidator} at validation time.
+ * Creating, editing, pausing, or deleting any pipeline or policy needs the manager role for the
+ * caller's team (see {@link PolicyManagementAuthority}). A team member without it may view and
+ * run the team's pipelines but not change them, so every mutation endpoint ({@link
+ * #savePolicy}, {@link #deletePolicy}, {@link #clearProcessedHistory}) calls this.
*/
private void requirePolicyEditingAllowed() {
if (!policyEditingAllowed()) {
@@ -482,8 +478,7 @@ public class PolicyController {
}
/**
- * Whether the caller may create/modify policies (a team leader, or any operator when login is
- * off).
+ * Whether the caller may create/modify policies (a manager, or any operator when login off).
*/
private boolean policyEditingAllowed() {
return !applicationProperties.getSecurity().isEnableLogin()
@@ -528,6 +523,17 @@ public class PolicyController {
.toList();
}
+ @GetMapping("/permissions")
+ @Operation(
+ summary = "The caller's policy-management permissions",
+ description =
+ "Whether the caller may create, edit, or delete pipelines and policies, so the UI"
+ + " can gate those controls; other team members may view but not change"
+ + " them.")
+ public PolicyPermissions permissions() {
+ return new PolicyPermissions(policyEditingAllowed());
+ }
+
@GetMapping("/{policyId}")
@Operation(
summary = "Get a policy by id",
@@ -550,7 +556,10 @@ public class PolicyController {
requirePolicyEditingAllowed();
// Scope to the caller's team: a policy in another team reads as not-found.
Policy policy = policyStore.get(policyId).filter(policyAccessGuard::canAccess).orElse(null);
- if (policy != null && policyStore.delete(policyId)) {
+ if (policy == null) {
+ return ResponseEntity.notFound().build();
+ }
+ if (policyStore.delete(policyId)) {
processedLedger.clearPolicy(policyId);
assetCleaner.cleanupAfterDelete(policy);
// Cancel any now-orphaned folder watch promptly rather than leaving the WatchKey open
@@ -571,9 +580,8 @@ public class PolicyController {
public ResponseEntity<Void> clearProcessedHistory(@PathVariable String policyId) {
requirePolicyEditingAllowed();
// Scope to the caller's team: a policy in another team reads as not-found.
- boolean accessible =
- policyStore.get(policyId).filter(policyAccessGuard::canAccess).isPresent();
- if (!accessible) {
+ Policy policy = policyStore.get(policyId).filter(policyAccessGuard::canAccess).orElse(null);
+ if (policy == null) {
return ResponseEntity.notFound().build();
}
processedLedger.clearPolicy(policyId);
diff --git a/app/proprietary/src/main/java/stirling/software/proprietary/policy/model/Policy.java b/app/proprietary/src/main/java/stirling/software/proprietary/policy/model/Policy.java
index 72d06a4149..ce304d3109 100644
--- a/app/proprietary/src/main/java/stirling/software/proprietary/policy/model/Policy.java
+++ b/app/proprietary/src/main/java/stirling/software/proprietary/policy/model/Policy.java
@@ -3,19 +3,7 @@ package stirling.software.proprietary.policy.model;
import java.util.List;
import java.util.Optional;
-/**
- * A stored automation: ordered tool steps, input bindings, and output destinations.
- *
- * <p>Always runnable on demand. Each {@link PipelineInput} references a persisted {@code Source}
- * connection (resolved live at run time) and carries its own optional {@link TriggerConfig}: the
- * trigger decides when that source is pulled, so one input can be watched while another polls, and
- * a {@code null} trigger makes that input manual-only. An input with no trigger, or a policy with
- * no triggered inputs, still runs when the policy is run on demand; a manual run pulls every input.
- *
- * <p>{@code outputIds} reference the {@code Source} locations (resolved live) a run's files are
- * delivered to - a run is delivered to every one; when empty the inline {@link #output} is used
- * (results returned to the caller), the case for editor and one-off policies.
- */
+/** A stored automation: ordered tool steps, input bindings, and output destinations. */
public record Policy(
String id,
String name,
@@ -40,9 +28,10 @@ public record Policy(
}
/**
- * Without the {@code required} flag, {@code icon}, or editor participation: defaults to not
- * org-required, no icon, and a swept/on-demand policy. Kept for the many callers and tests
- * written before those fields; the frontend and stores that care use the full constructor.
+ * Without the {@code required} flag, {@code icon}, or editor participation: defaults to an
+ * ordinary (non-blocking) pipeline, no icon, and a swept/on-demand policy. Kept for the many
+ * callers and tests written before those fields; the frontend and stores that care use the full
+ * constructor.
*/
public Policy(
String id,
@@ -60,7 +49,7 @@ public record Policy(
/**
* Without the {@code required} flag or {@code icon} but with explicit editor participation: the
* seeded Classification policy runs on the editor, so it must set {@link EditorConfig} even
- * though it predates the org-required and icon fields.
+ * though it predates the {@code required} and icon fields.
*/
public Policy(
String id,
diff --git a/app/proprietary/src/main/java/stirling/software/proprietary/policy/model/PolicyPermissions.java b/app/proprietary/src/main/java/stirling/software/proprietary/policy/model/PolicyPermissions.java
new file mode 100644
index 0000000000..d1d51725ae
--- /dev/null
+++ b/app/proprietary/src/main/java/stirling/software/proprietary/policy/model/PolicyPermissions.java
@@ -0,0 +1,9 @@
+package stirling.software.proprietary.policy.model;
+
+/**
+ * The current caller's policy-management permissions, for the portal to gate its UI. {@code
+ * canManagePolicies} is the same decision the mutation endpoints enforce: a manager, or any
+ * operator when login is disabled. Other team members may view but not change pipelines or
+ * policies.
+ */
+public record PolicyPermissions(boolean canManagePolicies) {}
diff --git a/app/proprietary/src/main/java/stirling/software/proprietary/policy/seed/DefaultClassificationPolicySeeder.java b/app/proprietary/src/main/java/stirling/software/proprietary/policy/seed/DefaultClassificationPolicySeeder.java
index 7d35198633..38d3e6ecb3 100644
--- a/app/proprietary/src/main/java/stirling/software/proprietary/policy/seed/DefaultClassificationPolicySeeder.java
+++ b/app/proprietary/src/main/java/stirling/software/proprietary/policy/seed/DefaultClassificationPolicySeeder.java
@@ -110,6 +110,8 @@ public class DefaultClassificationPolicySeeder {
// every consumer of owner already handles its absence.
null,
true,
+ true,
+ "",
List.of(),
List.of(new PipelineStep(CLASSIFY_ENDPOINT, Map.of())),
new OutputSpec("inline", options),
diff --git a/app/proprietary/src/test/java/stirling/software/proprietary/policy/controller/PolicyControllerTest.java b/app/proprietary/src/test/java/stirling/software/proprietary/policy/controller/PolicyControllerTest.java
index c72a30f98a..8d69b84fc9 100644
--- a/app/proprietary/src/test/java/stirling/software/proprietary/policy/controller/PolicyControllerTest.java
+++ b/app/proprietary/src/test/java/stirling/software/proprietary/policy/controller/PolicyControllerTest.java
@@ -51,6 +51,7 @@ import stirling.software.proprietary.policy.engine.SweepOutcome;
import stirling.software.proprietary.policy.ledger.ProcessedLedger;
import stirling.software.proprietary.policy.model.OutputSpec;
import stirling.software.proprietary.policy.model.PipelineDefinition;
+import stirling.software.proprietary.policy.model.PipelineInput;
import stirling.software.proprietary.policy.model.PipelineStep;
import stirling.software.proprietary.policy.model.PipelineValidation;
import stirling.software.proprietary.policy.model.Policy;
@@ -311,10 +312,11 @@ class PolicyControllerTest {
}
@Test
- @DisplayName("does not resolve a policy's stored assets for a caller who cannot edit it")
- void skipsStoredAssetsForNonEditor() throws Exception {
- // Gating asset resolution to editors keeps a member from rebinding a policy's stored
- // asset into an ad-hoc step to read it back.
+ @DisplayName("does not resolve stored assets for a non-manager")
+ void skipsStoredAssetsForNonManager() throws Exception {
+ // The exfiltration guard: only an editor (manager) may resolve a policy's stored asset
+ // bindings, so a member can't rebind one into an ad-hoc step to read it back. Checked
+ // before any lookup, so the store is never even consulted.
applicationProperties.getSecurity().setEnableLogin(true);
when(policyManagementAuthority.canEditPolicies()).thenReturn(false);
when(policyRunner.runAdHoc(any(), any(), eq(PolicyProgressListener.NOOP)))
@@ -325,6 +327,23 @@ class PolicyControllerTest {
verify(assetResolver, never()).resolve(any(), any());
verify(policyStore, never()).get(any());
}
+
+ @Test
+ @DisplayName("resolves stored assets for a manager")
+ void resolvesStoredAssetsForManager() throws Exception {
+ applicationProperties.getSecurity().setEnableLogin(true);
+ when(policyManagementAuthority.canEditPolicies()).thenReturn(true);
+ Policy p = policy("pol-1", 1L);
+ when(policyStore.get("pol-1")).thenReturn(Optional.of(p));
+ when(policyAccessGuard.canAccess(p)).thenReturn(true);
+ when(assetResolver.resolve(eq(p), any())).thenAnswer(inv -> inv.getArgument(1));
+ when(policyRunner.runAdHoc(any(), any(), eq(PolicyProgressListener.NOOP)))
+ .thenReturn(handle("run-1"));
+
+ controller.run(definitionWithStep(), "pol-1", new PolicyRunFiles());
+
+ verify(assetResolver).resolve(eq(p), any());
+ }
}
@Nested
@@ -453,11 +472,13 @@ class PolicyControllerTest {
}
@Test
- @DisplayName("forbidden when login enabled and caller cannot edit")
- void forbidden() {
+ @DisplayName("forbidden when a non-manager saves any pipeline or policy")
+ void forbidsSaveForNonManager() {
applicationProperties.getSecurity().setEnableLogin(true);
when(policyManagementAuthority.canEditPolicies()).thenReturn(false);
+ // Editing is manager-only regardless of the Pipeline vs Policy (required) flag, so even
+ // an ordinary pipeline is refused - and the gate runs before any lookup.
assertThatThrownBy(() -> controller.savePolicy(policy(null, null)))
.isInstanceOf(ResponseStatusException.class)
.satisfies(
@@ -465,9 +486,44 @@ class PolicyControllerTest {
assertThat(((ResponseStatusException) e).getStatusCode())
.isEqualTo(HttpStatus.FORBIDDEN));
verify(policyStore, never()).save(any());
+ verify(policyStore, never()).get(any());
verify(policyTriggerManager, never()).notifyPoliciesChanged();
}
+ @Test
+ @DisplayName(
+ "the manager gate runs before validation, so a forbidden save never leaks a 400")
+ void gatePrecedesValidation() {
+ applicationProperties.getSecurity().setEnableLogin(true);
+ when(policyManagementAuthority.canEditPolicies()).thenReturn(false);
+ // A required policy that also references an unknown source: reaching the source and
+ // validation checks would surface a 400. The 403 must win, so a non-manager can't
+ // probe those errors on a save they're forbidden from performing.
+ Policy withUnknownSource =
+ new Policy(
+ null,
+ "name",
+ "owner",
+ true,
+ true,
+ "",
+ List.of(PipelineInput.manual("src-missing")),
+ List.of(),
+ null,
+ List.of(),
+ null,
+ null);
+
+ assertThatThrownBy(() -> controller.savePolicy(withUnknownSource))
+ .isInstanceOf(ResponseStatusException.class)
+ .satisfies(
+ e ->
+ assertThat(((ResponseStatusException) e).getStatusCode())
+ .isEqualTo(HttpStatus.FORBIDDEN));
+ verify(policyValidator, never()).validate(any());
+ verify(policyStore, never()).save(any());
+ }
+
@Test
@DisplayName("bad request when validation fails")
void validationFails() {
@@ -640,17 +696,20 @@ class PolicyControllerTest {
}
@Test
- @DisplayName("forbidden when login enabled and caller cannot edit")
- void forbidden() {
+ @DisplayName("forbidden when a non-manager deletes any pipeline")
+ void forbidsDeleteForNonManager() {
applicationProperties.getSecurity().setEnableLogin(true);
when(policyManagementAuthority.canEditPolicies()).thenReturn(false);
+ // The gate runs before any lookup, so a delete by a non-manager is refused outright.
assertThatThrownBy(() -> controller.deletePolicy("a"))
.isInstanceOf(ResponseStatusException.class)
.satisfies(
e ->
assertThat(((ResponseStatusException) e).getStatusCode())
.isEqualTo(HttpStatus.FORBIDDEN));
+ verify(policyStore, never()).delete(any());
+ verify(policyStore, never()).get(any());
}
}
@@ -687,17 +746,52 @@ class PolicyControllerTest {
}
@Test
- @DisplayName("forbidden when login enabled and caller cannot edit")
- void forbidden() {
+ @DisplayName("forbidden when a non-manager clears any pipeline's history")
+ void forbidsClearForNonManager() {
applicationProperties.getSecurity().setEnableLogin(true);
when(policyManagementAuthority.canEditPolicies()).thenReturn(false);
+ // The gate runs before any lookup, so a clear by a non-manager is refused outright.
assertThatThrownBy(() -> controller.clearProcessedHistory("a"))
.isInstanceOf(ResponseStatusException.class)
.satisfies(
e ->
assertThat(((ResponseStatusException) e).getStatusCode())
.isEqualTo(HttpStatus.FORBIDDEN));
+ verify(processedLedger, never()).clearPolicy(any());
+ verify(policyStore, never()).get(any());
+ }
+ }
+
+ @Nested
+ @DisplayName("permissions")
+ class Permissions {
+
+ @Test
+ @DisplayName("a manager may manage policies")
+ void managerCanManage() {
+ applicationProperties.getSecurity().setEnableLogin(true);
+ when(policyManagementAuthority.canEditPolicies()).thenReturn(true);
+
+ assertThat(controller.permissions().canManagePolicies()).isTrue();
+ }
+
+ @Test
+ @DisplayName("a non-manager may not manage policies")
+ void nonManagerCannotManage() {
+ applicationProperties.getSecurity().setEnableLogin(true);
+ when(policyManagementAuthority.canEditPolicies()).thenReturn(false);
+
+ assertThat(controller.permissions().canManagePolicies()).isFalse();
+ }
+
+ @Test
+ @DisplayName("single-user (login off) may manage policies without a role")
+ void singleUserCanManage() {
+ applicationProperties.getSecurity().setEnableLogin(false);
+
+ assertThat(controller.permissions().canManagePolicies()).isTrue();
+ verify(policyManagementAuthority, never()).canEditPolicies();
}
}
diff --git a/app/proprietary/src/test/java/stirling/software/proprietary/policy/controller/PolicyRunRoutesTest.java b/app/proprietary/src/test/java/stirling/software/proprietary/policy/controller/PolicyRunRoutesTest.java
index e7081ec8ca..1c94b29dee 100644
--- a/app/proprietary/src/test/java/stirling/software/proprietary/policy/controller/PolicyRunRoutesTest.java
+++ b/app/proprietary/src/test/java/stirling/software/proprietary/policy/controller/PolicyRunRoutesTest.java
@@ -56,19 +56,20 @@ class PolicyRunRoutesTest {
/** Every request mapping on PolicyController, and whether it executes an automation. */
private static final Map<String, Boolean> EXPECTED =
- Map.of(
- "/api/v1/policies", false, // base: list (GET) + create (POST)
- "/api/v1/policies/run", true,
- "/api/v1/policies/run/stream", true,
- "/api/v1/policies/run/{runId}", false,
- "/api/v1/policies/runs", false,
- "/api/v1/policies/order", false,
- "/api/v1/policies/overview", false,
- "/api/v1/policies/triggers", false,
- "/api/v1/policies/{policyId}", false, // GET + DELETE
- "/api/v1/policies/{policyId}/processed-history", false);
-
- // Split out because Map.of caps at 10 entries; the execute {id} routes live here.
+ Map.ofEntries(
+ Map.entry("/api/v1/policies", false), // base: list (GET) + create (POST)
+ Map.entry("/api/v1/policies/run", true),
+ Map.entry("/api/v1/policies/run/stream", true),
+ Map.entry("/api/v1/policies/run/{runId}", false),
+ Map.entry("/api/v1/policies/runs", false),
+ Map.entry("/api/v1/policies/order", false),
+ Map.entry("/api/v1/policies/overview", false),
+ Map.entry("/api/v1/policies/triggers", false),
+ Map.entry("/api/v1/policies/permissions", false),
+ Map.entry("/api/v1/policies/{policyId}", false), // GET + DELETE
+ Map.entry("/api/v1/policies/{policyId}/processed-history", false));
+
+ // The execute {id} routes; kept as their own group.
private static final Map<String, Boolean> EXPECTED_ID_EXECUTES =
Map.of(
"/api/v1/policies/{policyId}/run", true,
diff --git a/app/proprietary/src/test/java/stirling/software/proprietary/policy/seed/DefaultClassificationPolicySeederTest.java b/app/proprietary/src/test/java/stirling/software/proprietary/policy/seed/DefaultClassificationPolicySeederTest.java
index fb4fa6d419..749d66ca60 100644
--- a/app/proprietary/src/test/java/stirling/software/proprietary/policy/seed/DefaultClassificationPolicySeederTest.java
+++ b/app/proprietary/src/test/java/stirling/software/proprietary/policy/seed/DefaultClassificationPolicySeederTest.java
@@ -61,6 +61,8 @@ class DefaultClassificationPolicySeederTest {
verify(policyStore).save(saved.capture());
Policy policy = saved.getValue();
assertThat(policy.enabled()).isTrue();
+ // Org-mandated: the seeded classification policy is a Policy, not an opt-in Pipeline.
+ assertThat(policy.required()).isTrue();
assertThat(policy.teamId()).isEqualTo(7L);
assertThat(policy.output().type()).isEqualTo("inline");
assertThat(policy.output().options().get("categoryId")).isEqualTo("classification");
diff --git a/frontend/editor/public/locales/en-US/translation.toml b/frontend/editor/public/locales/en-US/translation.toml
index ec5fc30abe..cf5369723f 100644
--- a/frontend/editor/public/locales/en-US/translation.toml
+++ b/frontend/editor/public/locales/en-US/translation.toml
@@ -8578,6 +8578,8 @@ platform = "PDF Platform"
processor = "PDF Processor"
[portal.pipelines]
+permissionsRetry = "Retry"
+permissionsUnavailable = "Couldn't check whether you can manage policies, so policy actions are unavailable for now."
subtitle = "Automate your document workflows. Start from a template for a simple, guided setup, or build a custom pipeline from scratch. Enforce any pipeline as a policy to run it on every document."
title = "Pipelines"
@@ -8630,6 +8632,7 @@ viewDefinition = "View definition"
destination = "Choose a destination"
heading = "To create this pipeline:"
incompatible = "Fix steps that can't run in order: {{tools}}"
+managerOnly = "Only an admin or team leader can modify a policy"
name = "Give the pipeline a name"
saveHeading = "To save your changes:"
schedule = "Set how often it runs"
@@ -8697,9 +8700,10 @@ description = "Create your first pipeline: pick the sources it runs over, chain
title = "No pipelines yet"
[portal.pipelines.enforce]
-desc = "Runs automatically; members can't turn it off"
+desc = "A policy blocks a file that fails it; an ordinary pipeline reports the error but lets the file through."
info = "What enforcing as a policy means"
label = "Enforce as policy"
+managerOnly = "Only an admin or team leader can enforce a pipeline as a policy"
[portal.pipelines.graph]
addFirstTool = "Add a tool"
@@ -8732,11 +8736,6 @@ failed_other = "Failed after {{done}} of {{count}} steps"
running_one = "Running the only step"
running_other = "Running step {{done}} of {{count}}"
-[portal.pipelines.kpi]
-active = "Active"
-paused = "Paused"
-total = "Pipelines"
-
[portal.pipelines.run]
allProcessed_one = "Nothing to run: the source's {{count}} document has already been processed."
allProcessed_other = "Nothing to run: all {{count}} documents in the sources have already been processed."
@@ -8904,6 +8903,7 @@ summary = "Detects and redacts PII, strips active content (JavaScript), and wate
[portal.policies.detail]
enforces = "Steps"
+managerOnly = "Only an admin or team leader can modify this policy"
onEveryExport = "On every export"
onEveryUpload = "On every upload"
outputAsNewFile = "as a new file"
@@ -9561,11 +9561,6 @@ cancel = "Cancel"
confirm = "Delete"
title = "Delete source?"
-[portal.sources.kpi]
-inUse = "In use"
-total = "Connections"
-unused = "Unused"
-
[portal.sources.networkFields.connection]
helperText = "The saved connection with the server address and credentials. Shared by every source that uses it."
label = "Connection"
diff --git a/frontend/editor/src/core/ui/IconPicker.tsx b/frontend/editor/src/core/ui/IconPicker.tsx
index e3c7a98128..c6fe67df11 100644
--- a/frontend/editor/src/core/ui/IconPicker.tsx
+++ b/frontend/editor/src/core/ui/IconPicker.tsx
@@ -21,6 +21,8 @@ export interface IconPickerProps {
/** Accessible name for the trigger (e.g. "Icon"). */
ariaLabel: string;
size?: "sm" | "md" | "lg";
+ /** Lock the picker: the trigger is disabled and the menu can't open. */
+ disabled?: boolean;
}
/**
@@ -34,6 +36,7 @@ export function IconPicker({
options,
ariaLabel,
size = "sm",
+ disabled = false,
}: IconPickerProps) {
// Controlled so a grid button (not a Dropdown.Item) can close the menu on pick.
const [open, setOpen] = useState(false);
@@ -45,9 +48,18 @@ export function IconPicker({
}
return (
- <Dropdown.Root open={open} onOpenChange={setOpen} align="start">
+ <Dropdown.Root
+ open={open}
+ onOpenChange={disabled ? () => {} : setOpen}
+ align="start"
+ >
<Dropdown.Trigger>
- <ActionIcon variant="secondary" size={size} aria-label={ariaLabel}>
+ <ActionIcon
+ variant="secondary"
+ size={size}
+ aria-label={ariaLabel}
+ disabled={disabled}
+ >
{selected?.node}
</ActionIcon>
</Dropdown.Trigger>
diff --git a/frontend/editor/src/core/ui/Modal.css b/frontend/editor/src/core/ui/Modal.css
index e41ffb0eda..f2fe607167 100644
--- a/frontend/editor/src/core/ui/Modal.css
+++ b/frontend/editor/src/core/ui/Modal.css
@@ -33,6 +33,7 @@
/* mobile browser chrome shrinks 100vh */
max-height: calc(100dvh - var(--modal-inset-block) * 2);
overflow: hidden;
+ overflow: clip;
animation: scaleIn 0.2s cubic-bezier(0.4, 0, 0.2, 1) both;
}
diff --git a/frontend/editor/src/portal/api/pipelines.ts b/frontend/editor/src/portal/api/pipelines.ts
index 69dcb0d3fe..e456426585 100644
--- a/frontend/editor/src/portal/api/pipelines.ts
+++ b/frontend/editor/src/portal/api/pipelines.ts
@@ -62,11 +62,7 @@ export interface Policy {
name: string;
owner?: string | null;
enabled: boolean;
- /**
- * Org-mandated ("this is a policy your organisation requires"). First-class, independent of the
- * trigger: a required pipeline can't be paused, disabled, or deleted by an ordinary member, and
- * enforces on their documents when its trigger targets the editor. Admin-only to set.
- */
+ /** Whether this is a policy (blocking) rather than an ordinary pipeline. */
required?: boolean;
/** Row icon key (see pipelineIcon); chosen in the builder. Empty falls back to the category glyph. */
icon?: string;
@@ -102,7 +98,7 @@ export interface PipelineView {
id: string;
name: string;
enabled: boolean;
- /** Org-mandated policy (see {@link Policy.required}); surfaced as a "Required" badge in the list. */
+ /** Whether this is a policy - blocking on failure (see {@link Policy.required}); badged in the list. */
required: boolean;
/** Icon key for the list row (see pipelineIcon). Empty when none set; may be a category id. */
icon: string;
@@ -179,6 +175,21 @@ export async function fetchTriggers(): Promise<TriggerInfo[]> {
return apiClient.local.json<TriggerInfo[]>("/api/v1/policies/triggers");
}
+/**
+ * The caller's policy-management capability, mirroring the backend gate: whether they may create,
+ * edit, or delete pipelines and policies (a manager). Others view but can't change them.
+ */
+export interface PolicyPermissions {
+ canManagePolicies: boolean;
+}
+
+/** GET /api/v1/policies/permissions: whether the caller may create/edit/delete pipelines & policies. */
+export async function fetchPolicyPermissions(): Promise<PolicyPermissions> {
+ return apiClient.local.json<PolicyPermissions>(
+ "/api/v1/policies/permissions",
+ );
+}
+
/**
* What a manual trigger found and started. Mirrors the backend `SweepOutcome`:
* when `runIds` is empty, the counts say why - no files listed, all already
diff --git a/frontend/editor/src/portal/api/policies.test.ts b/frontend/editor/src/portal/api/policies.test.ts
index e3b4210ff1..9ea68ff5fb 100644
--- a/frontend/editor/src/portal/api/policies.test.ts
+++ b/frontend/editor/src/portal/api/policies.test.ts
@@ -1,7 +1,33 @@
import { describe, expect, it } from "vitest";
-import { parseSimplePolicy } from "@portal/api/policies";
+import {
+ buildWireFromSetup,
+ parseSimplePolicy,
+ type PolicySetupResult,
+} from "@portal/api/policies";
import { policyStep, policyStepToWire } from "@app/policies/operations";
import type { Policy } from "@portal/api/pipelines";
+import type { TFunction } from "i18next";
+
+const t = ((key: string) => key) as unknown as TFunction;
+
+/** A minimal wizard result; the fields under test are the stored name/icon, not these. */
+function setupResult(): PolicySetupResult {
+ return {
+ required: false,
+ fieldValues: {},
+ sources: [],
+ runsOnEditor: true,
+ scopeTypes: [],
+ reviewerEmail: "",
+ outputMode: "new_version",
+ outputName: "",
+ outputNamePosition: "suffix",
+ runOn: "upload",
+ maxRetries: 0,
+ retryDelayMinutes: 0,
+ steps: [],
+ };
+}
/** A template-representable classification policy, `required` as given. */
function classificationPolicy(required: boolean): Policy {
@@ -44,3 +70,17 @@ describe("parseSimplePolicy", () => {
expect(entry?.policy?.state.runsOnEditor).toBe(true);
});
});
+
+describe("buildWireFromSetup", () => {
+ it("preserves the stored icon and name so a wizard save doesn't reset them", () => {
+ const policy: Policy = {
+ ...classificationPolicy(false),
+ name: "My classifier",
+ icon: "shield",
+ };
+ const entry = parseSimplePolicy(policy);
+ const wire = buildWireFromSetup(entry!, setupResult(), t);
+ expect(wire.icon).toBe("shield");
+ expect(wire.name).toBe("My classifier");
+ });
+});
diff --git a/frontend/editor/src/portal/api/policies.ts b/frontend/editor/src/portal/api/policies.ts
index 498b82658d..69c03323eb 100644
--- a/frontend/editor/src/portal/api/policies.ts
+++ b/frontend/editor/src/portal/api/policies.ts
@@ -71,7 +71,7 @@ export interface PolicyConfigDef {
export interface PolicyState {
configured: boolean;
status: PolicyStatus;
- /** Org-mandated policy (see the pipeline `Policy.required`). */
+ /** A policy rather than an ordinary pipeline (see `Policy.required`). */
required: boolean;
name?: string;
icon?: string;
@@ -605,7 +605,7 @@ export async function clearProcessedHistory(id: string): Promise<void> {
// Catalogue policy bodies carry categoryId at the top level so the pipelines
// mock handler can discriminate them from raw pipeline saves on the shared
// POST /api/v1/policies endpoint. The real backend ignores unknown fields.
-type CatalogueWireBody = WirePolicy & { categoryId: string };
+type CatalogueWireBody = WirePolicy & { categoryId: string; icon?: string };
/**
* The persisted policy name derived from its category, e.g. "Security Policy".
@@ -626,11 +626,13 @@ export function buildWireFromSetup(
t: TFunction,
enabled = true,
): CatalogueWireBody {
+ const stored = entry.policy?.state;
return {
categoryId: entry.category.id,
+ icon: stored?.icon,
...toWirePolicy({
- id: entry.policy?.state.backendId ?? "",
- name: policyDisplayName(entry, t),
+ id: stored?.backendId ?? "",
+ name: stored?.name ?? policyDisplayName(entry, t),
enabled,
required: result.required,
extraOptions: result.extraOptions,
diff --git a/frontend/editor/src/portal/components/pipelines/EnforceAsPolicyControl.tsx b/frontend/editor/src/portal/components/pipelines/EnforceAsPolicyControl.tsx
index 0da0257ae5..197c863e70 100644
--- a/frontend/editor/src/portal/components/pipelines/EnforceAsPolicyControl.tsx
+++ b/frontend/editor/src/portal/components/pipelines/EnforceAsPolicyControl.tsx
@@ -6,6 +6,13 @@ export interface EnforceAsPolicyControlProps {
/** Org-mandated policy (see Policy.required). */
required: boolean;
onRequiredChange: (required: boolean) => void;
+ /** Lock the toggle for a non-manager. */
+ disabled?: boolean;
+ /**
+ * The permission check is still loading. The toggle stays locked, but the manager-only tooltip is
+ * withheld so a still-loading manager isn't told they lack permission.
+ */
+ permissionsLoading?: boolean;
}
/**
@@ -16,6 +23,8 @@ export interface EnforceAsPolicyControlProps {
export function EnforceAsPolicyControl({
required,
onRequiredChange,
+ disabled = false,
+ permissionsLoading = false,
}: EnforceAsPolicyControlProps) {
const { t } = useTranslation();
return (
@@ -24,10 +33,15 @@ export function EnforceAsPolicyControl({
size="sm"
checked={required}
onChange={onRequiredChange}
+ disabled={disabled}
label={t("portal.pipelines.enforce.label")}
/>
<InfoTooltip
- label={t("portal.pipelines.enforce.desc")}
+ label={
+ disabled && !permissionsLoading
+ ? t("portal.pipelines.enforce.managerOnly")
+ : t("portal.pipelines.enforce.desc")
+ }
ariaLabel={t("portal.pipelines.enforce.info")}
position="bottom"
/>
diff --git a/frontend/editor/src/portal/components/pipelines/KpiStrip.tsx b/frontend/editor/src/portal/components/pipelines/KpiStrip.tsx
deleted file mode 100644
index a306536718..0000000000
--- a/frontend/editor/src/portal/components/pipelines/KpiStrip.tsx
+++ /dev/null
@@ -1,40 +0,0 @@
-import { useTranslation } from "react-i18next";
-import { MetricCard, MetricStrip } from "@app/ui";
-import { PipelinesIcon } from "@portal/components/icons";
-import type { PipelinesOverviewResponse } from "@portal/api/pipelines";
-
-/**
- * KPI labels are product copy: they describe what each metric IS, not its value.
- * They stay client-side so the strip's structure is stable across loading / empty
- * / ready states; only values + descriptions flow from the API. Order matches
- * PolicyOverviewService.buildKpis: total, active, paused.
- */
-const KPI_LABEL_KEYS = [
- "portal.pipelines.kpi.total",
- "portal.pipelines.kpi.active",
- "portal.pipelines.kpi.paused",
-] as const;
-
-interface KpiStripProps {
- data: PipelinesOverviewResponse | null;
- loading: boolean;
-}
-
-export function KpiStrip({ data, loading }: KpiStripProps) {
- const { t } = useTranslation();
- return (
- <MetricStrip layout="row" leading={<PipelinesIcon size={22} />}>
- {KPI_LABEL_KEYS.map((labelKey, i) => {
- const k = loading ? undefined : data?.kpis[i];
- return (
- <MetricCard
- key={labelKey}
- label={t(labelKey)}
- value={k?.value ?? "—"}
- description={k?.description}
- />
- );
- })}
- </MetricStrip>
- );
-}
diff --git a/frontend/editor/src/portal/components/pipelines/PipelineCreateHeader.test.tsx b/frontend/editor/src/portal/components/pipelines/PipelineCreateHeader.test.tsx
index 0f440a2e84..3b3345c0e3 100644
--- a/frontend/editor/src/portal/components/pipelines/PipelineCreateHeader.test.tsx
+++ b/frontend/editor/src/portal/components/pipelines/PipelineCreateHeader.test.tsx
@@ -43,6 +43,18 @@ function renderHeader(overrides: Partial<PipelineCreateHeaderProps> = {}) {
}
describe("PipelineCreateHeader", () => {
+ it("shows the enforce toggle only for an editor-sourced pipeline", () => {
+ renderHeader({ runsOnEditor: false });
+ expect(
+ screen.queryByRole("switch", { name: "portal.pipelines.enforce.label" }),
+ ).not.toBeInTheDocument();
+
+ renderHeader({ runsOnEditor: true });
+ expect(
+ screen.getByRole("switch", { name: "portal.pipelines.enforce.label" }),
+ ).toBeInTheDocument();
+ });
+
it("edits the pipeline's name", () => {
const handlers = renderHeader();
fireEvent.change(
diff --git a/frontend/editor/src/portal/components/pipelines/PipelineCreateHeader.tsx b/frontend/editor/src/portal/components/pipelines/PipelineCreateHeader.tsx
index d9dda2f88c..00506639b4 100644
--- a/frontend/editor/src/portal/components/pipelines/PipelineCreateHeader.tsx
+++ b/frontend/editor/src/portal/components/pipelines/PipelineCreateHeader.tsx
@@ -15,6 +15,15 @@ export interface PipelineCreateHeaderProps {
/** "Enforce as policy" toggle, shown in the actions row. */
required: boolean;
onRequiredChange: (required: boolean) => void;
+ /** Whether this pipeline's source is the editor. */
+ runsOnEditor?: boolean;
+ /** Whether the user may create pipelines and policies. */
+ canManagePolicies?: boolean;
+ /**
+ * The permission check is still loading. The enforce toggle stays locked, but the manager-only
+ * tooltip is withheld so a still-loading manager isn't told they lack permission.
+ */
+ permissionsLoading?: boolean;
canSave: boolean;
/** Everything still owed before the pipeline can be created, shown on the disabled create button. */
@@ -40,6 +49,9 @@ export function PipelineCreateHeader({
onIconChange,
required,
onRequiredChange,
+ runsOnEditor = false,
+ canManagePolicies = true,
+ permissionsLoading = false,
canSave,
blockers,
saving,
@@ -49,6 +61,8 @@ export function PipelineCreateHeader({
onBack,
}: PipelineCreateHeaderProps) {
const { t } = useTranslation();
+ // Only a manager may create a pipeline or policy; block create for others.
+ const readOnly = !canManagePolicies;
return (
<section className="portal-pipeline-create-header">
@@ -77,23 +91,31 @@ export function PipelineCreateHeader({
/>
<div className="portal-pipeline-create-header__actions">
- <EnforceAsPolicyControl
- required={required}
- onRequiredChange={onRequiredChange}
- />
+ {runsOnEditor && (
+ <EnforceAsPolicyControl
+ required={required}
+ onRequiredChange={onRequiredChange}
+ disabled={!canManagePolicies}
+ permissionsLoading={permissionsLoading}
+ />
+ )}
{/* The pair share one tooltip target because a disabled button swallows its own hover - the
wrapper is what the pointer lands on. */}
<PipelineBlockerTooltip
heading={t("portal.pipelines.builder.blocker.heading")}
- blockers={blockers}
+ blockers={
+ readOnly && !permissionsLoading
+ ? [t("portal.pipelines.builder.blocker.managerOnly")]
+ : blockers
+ }
>
<div className="portal-pipeline-create-header__create">
<Button
variant="secondary"
size="sm"
loading={saving && pendingCreateEnabled === false}
- disabled={!canSave}
+ disabled={!canSave || readOnly}
onClick={onCreatePaused}
>
{t("portal.pipelines.composer.createPaused")}
@@ -101,7 +123,7 @@ export function PipelineCreateHeader({
<Button
size="sm"
loading={saving && pendingCreateEnabled === true}
- disabled={!canSave}
+ disabled={!canSave || readOnly}
onClick={onCreate}
>
{t("portal.pipelines.composer.create")}
diff --git a/frontend/editor/src/portal/components/pipelines/PipelineEditHeader.test.tsx b/frontend/editor/src/portal/components/pipelines/PipelineEditHeader.test.tsx
index c491da17de..3422b26ebf 100644
--- a/frontend/editor/src/portal/components/pipelines/PipelineEditHeader.test.tsx
+++ b/frontend/editor/src/portal/components/pipelines/PipelineEditHeader.test.tsx
@@ -49,6 +49,18 @@ function renderHeader(overrides: Partial<PipelineEditHeaderProps> = {}) {
}
describe("PipelineEditHeader", () => {
+ it("shows the enforce toggle only for an editor-sourced pipeline", () => {
+ renderHeader({ runsOnEditor: false });
+ expect(
+ screen.queryByRole("switch", { name: "portal.pipelines.enforce.label" }),
+ ).not.toBeInTheDocument();
+
+ renderHeader({ runsOnEditor: true });
+ expect(
+ screen.getByRole("switch", { name: "portal.pipelines.enforce.label" }),
+ ).toBeInTheDocument();
+ });
+
it("shows the name as the title and renames it in place", () => {
const handlers = renderHeader();
expect(screen.getByText("Claims redaction")).toBeInTheDocument();
@@ -148,6 +160,24 @@ describe("PipelineEditHeader", () => {
).toBeDisabled();
});
+ it("is read-only for a required policy a non-manager can't manage", () => {
+ renderHeader({ required: true, canManagePolicies: false });
+ // No rename affordance and the icon picker is locked (edits would never persist)...
+ expect(
+ screen.queryByLabelText("portal.pipelines.builder.rename"),
+ ).not.toBeInTheDocument();
+ expect(
+ screen.getByLabelText("portal.pipelines.builder.icon.label"),
+ ).toBeDisabled();
+ // ...and the mutating actions are disabled.
+ expect(
+ screen.getByText("portal.pipelines.composer.save").closest("button"),
+ ).toBeDisabled();
+ expect(
+ screen.getByText("portal.pipelines.builder.pause").closest("button"),
+ ).toBeDisabled();
+ });
+
it("explains, on hover, why Save is disabled", async () => {
renderHeader({ canSave: false, blockers: ["Choose a destination"] });
const save = document.querySelector(
diff --git a/frontend/editor/src/portal/components/pipelines/PipelineEditHeader.tsx b/frontend/editor/src/portal/components/pipelines/PipelineEditHeader.tsx
index 64a4ac5cf1..ef64af58ec 100644
--- a/frontend/editor/src/portal/components/pipelines/PipelineEditHeader.tsx
+++ b/frontend/editor/src/portal/components/pipelines/PipelineEditHeader.tsx
@@ -23,6 +23,18 @@ export interface PipelineEditHeaderProps {
/** "Enforce as policy" toggle, shown in the actions row. */
required: boolean;
onRequiredChange: (required: boolean) => void;
+ /** Whether this pipeline's source is the editor. */
+ runsOnEditor?: boolean;
+ /**
+ * Whether the user may edit pipelines and policies (a manager). When false everything here is
+ * read-only - save, pause, delete, reprocess, rename and the enforce toggle.
+ */
+ canManagePolicies?: boolean;
+ /**
+ * The permission check has not resolved yet. Config actions stay locked (fail-closed), but the
+ * manager-only reason is withheld so a still-loading manager isn't told they lack permission.
+ */
+ permissionsLoading?: boolean;
/** The pipeline's live state. Toggling it takes effect immediately, not on save. */
enabled: boolean;
@@ -61,6 +73,9 @@ export function PipelineEditHeader({
onIconChange,
required,
onRequiredChange,
+ runsOnEditor = false,
+ canManagePolicies = true,
+ permissionsLoading = false,
enabled,
onTogglePause,
togglingEnabled,
@@ -76,6 +91,7 @@ export function PipelineEditHeader({
onDelete,
}: PipelineEditHeaderProps) {
const { t } = useTranslation();
+ const readOnly = !canManagePolicies;
const [renaming, setRenaming] = useState(false);
const [draft, setDraft] = useState(name);
const inputRef = useRef<HTMLInputElement>(null);
@@ -133,6 +149,7 @@ export function PipelineEditHeader({
onChange={onIconChange}
options={PIPELINE_ICON_OPTIONS}
ariaLabel={t("portal.pipelines.builder.icon.label")}
+ disabled={readOnly}
/>
{renaming ? (
@@ -151,23 +168,29 @@ export function PipelineEditHeader({
) : (
<>
<h1 className="portal-pipeline-edit-header__title">{name}</h1>
- <ActionIcon
- variant="quiet"
- size="sm"
- onClick={startRename}
- aria-label={t("portal.pipelines.builder.rename")}
- >
- <EditOutlinedIcon style={{ fontSize: "1rem" }} />
- </ActionIcon>
+ {!readOnly && (
+ <ActionIcon
+ variant="quiet"
+ size="sm"
+ onClick={startRename}
+ aria-label={t("portal.pipelines.builder.rename")}
+ >
+ <EditOutlinedIcon style={{ fontSize: "1rem" }} />
+ </ActionIcon>
+ )}
</>
)}
</div>
<div className="portal-pipeline-edit-header__actions">
- <EnforceAsPolicyControl
- required={required}
- onRequiredChange={onRequiredChange}
- />
+ {runsOnEditor && (
+ <EnforceAsPolicyControl
+ required={required}
+ onRequiredChange={onRequiredChange}
+ disabled={!canManagePolicies}
+ permissionsLoading={permissionsLoading}
+ />
+ )}
{/* Pause and Save both write the whole policy, so they are mutually exclusive: neither can
start while the other is committing, or the two writes race and the loser's version wins. */}
@@ -175,7 +198,7 @@ export function PipelineEditHeader({
variant="secondary"
size="sm"
loading={togglingEnabled}
- disabled={saving}
+ disabled={saving || readOnly}
onClick={onTogglePause}
leftSection={
enabled ? (
@@ -219,7 +242,7 @@ export function PipelineEditHeader({
<Dropdown.Menu>
<Dropdown.Item
onSelect={onReprocess}
- disabled={reprocessing || running}
+ disabled={reprocessing || running || readOnly}
leading={<ReplayRoundedIcon style={{ fontSize: "1.125rem" }} />}
>
{t("portal.pipelines.detail.clearHistory")}
@@ -227,6 +250,7 @@ export function PipelineEditHeader({
<Dropdown.Divider />
<Dropdown.Item
onSelect={onDelete}
+ disabled={readOnly}
className="portal-pipeline-edit-header__delete-item"
leading={
<DeleteOutlineRoundedIcon style={{ fontSize: "1.125rem" }} />
@@ -240,14 +264,18 @@ export function PipelineEditHeader({
{/* Wrapped in a span so the disabled button's hover still reaches the tooltip. */}
<PipelineBlockerTooltip
heading={t("portal.pipelines.builder.blocker.saveHeading")}
- blockers={blockers}
+ blockers={
+ readOnly && !permissionsLoading
+ ? [t("portal.pipelines.builder.blocker.managerOnly")]
+ : blockers
+ }
>
<span className="portal-pipeline-edit-header__save">
<Button
size="sm"
onClick={onSave}
loading={saving}
- disabled={!canSave || togglingEnabled}
+ disabled={!canSave || togglingEnabled || readOnly}
>
{t("portal.pipelines.composer.save")}
</Button>
diff --git a/frontend/editor/src/portal/components/policies/PolicyDetailPanel.tsx b/frontend/editor/src/portal/components/policies/PolicyDetailPanel.tsx
index 5e7576f1d6..36177a9f55 100644
--- a/frontend/editor/src/portal/components/policies/PolicyDetailPanel.tsx
+++ b/frontend/editor/src/portal/components/policies/PolicyDetailPanel.tsx
@@ -14,6 +14,13 @@ import "@portal/views/Policies.css";
interface PolicyDetailPanelProps {
policy: DecoratedPolicy | null;
busy?: boolean;
+ /** Whether the user may manage required policies; a required policy is read-only when false. */
+ canManagePolicies?: boolean;
+ /**
+ * The permission check has not resolved yet. Controls stay locked (fail-closed), but the
+ * manager-only note is withheld so a still-loading manager isn't told they lack permission.
+ */
+ permissionsLoading?: boolean;
onClose: () => void;
onEdit: () => void;
onTogglePause: () => void;
@@ -96,6 +103,8 @@ function ActivityError({ message }: { message: string }) {
export function PolicyDetailPanel({
policy,
busy = false,
+ canManagePolicies = true,
+ permissionsLoading = false,
onClose,
onEdit,
onTogglePause,
@@ -107,13 +116,14 @@ export function PolicyDetailPanel({
if (!policy) return null;
const { category, config, state, steps, stats, activity } = policy;
const isPaused = state.status === "paused";
- const canDelete = state.isDefault !== true;
+ const readOnly = !canManagePolicies;
+ const canDelete = state.isDefault !== true && !readOnly;
// Editor participation is its own flag (runsOnEditor), not a source. A legacy policy still carries
// "editor" in its stored sources until re-saved, so drop it here to count only real watched sources.
const realSources = state.sources.filter((s) => s !== "editor");
// Processed history only exists for watched sources; editor uploads are never ledgered.
const canClearHistory =
- onClearHistory !== undefined && realSources.length > 0;
+ onClearHistory !== undefined && realSources.length > 0 && !readOnly;
const enforceItems = steps.length > 0 ? steps.map((s) => s.operation) : null;
const hasEditorSource = state.runsOnEditor === true;
@@ -135,6 +145,11 @@ export function PolicyDetailPanel({
title={t(category.label)}
footer={
<div className="portal-policies__detail-foot">
+ {readOnly && !permissionsLoading && (
+ <span className="portal-policies__detail-readonly">
+ {t("portal.policies.detail.managerOnly")}
+ </span>
+ )}
{canDelete && (
<Button
variant="tertiary"
@@ -161,13 +176,13 @@ export function PolicyDetailPanel({
variant="secondary"
size="sm"
onClick={onTogglePause}
- disabled={busy}
+ disabled={busy || readOnly}
>
{isPaused
? t("portal.policies.detail.actions.resume")
: t("portal.policies.detail.actions.pause")}
</Button>
- <Button size="sm" onClick={onEdit} disabled={busy}>
+ <Button size="sm" onClick={onEdit} disabled={busy || readOnly}>
{t("portal.policies.detail.actions.editSettings")}
</Button>
</div>
diff --git a/frontend/editor/src/portal/components/policies/PolicySetupWizard.test.tsx b/frontend/editor/src/portal/components/policies/PolicySetupWizard.test.tsx
index baebfb7955..896ba8440c 100644
--- a/frontend/editor/src/portal/components/policies/PolicySetupWizard.test.tsx
+++ b/frontend/editor/src/portal/components/policies/PolicySetupWizard.test.tsx
@@ -240,4 +240,56 @@ describe("PolicySetupWizard", () => {
const result = onSubmit.mock.calls[0][1] as PolicySetupResult;
expect(result.runOn).toBe("export");
});
+
+ it("locks the wizard for a non-manager", async () => {
+ // Only a manager (admin / team leader) may create or edit; a non-manager sees it read-only.
+ const onSubmit = vi.fn().mockResolvedValue(undefined);
+ const entry: CatalogueEntry = {
+ category: security,
+ config: securityConfig,
+ policy: null,
+ };
+
+ render(
+ <PolicySetupWizard
+ entry={entry}
+ canManagePolicies={false}
+ onClose={vi.fn()}
+ onSubmit={onSubmit}
+ onCustomise={vi.fn()}
+ />,
+ );
+
+ expect(
+ screen.getByRole("switch", {
+ name: "portal.pipelines.enforce.label",
+ }),
+ ).toBeDisabled();
+ expect(await screen.findByRole("button", { name: ENABLE })).toBeDisabled();
+ });
+
+ it("defaults a new template to a policy (blocking)", async () => {
+ // A template's failure should block the file, so a new one defaults to required, independent of
+ // who is creating it.
+ const onSubmit = vi.fn().mockResolvedValue(undefined);
+ const entry: CatalogueEntry = {
+ category: security,
+ config: securityConfig,
+ policy: null,
+ };
+
+ render(
+ <PolicySetupWizard
+ entry={entry}
+ onClose={vi.fn()}
+ onSubmit={onSubmit}
+ onCustomise={vi.fn()}
+ />,
+ );
+ await submitWizard(ENABLE);
+
+ await waitFor(() => expect(onSubmit).toHaveBeenCalled());
+ const result = onSubmit.mock.calls[0][1] as PolicySetupResult;
+ expect(result.required).toBe(true);
+ });
});
diff --git a/frontend/editor/src/portal/components/policies/PolicySetupWizard.tsx b/frontend/editor/src/portal/components/policies/PolicySetupWizard.tsx
index 165732a74f..0986148cfa 100644
--- a/frontend/editor/src/portal/components/policies/PolicySetupWizard.tsx
+++ b/frontend/editor/src/portal/components/policies/PolicySetupWizard.tsx
@@ -32,6 +32,13 @@ import "@portal/views/Policies.css";
interface PolicySetupWizardProps {
/** The category being configured, or null when closed. */
entry: CatalogueEntry | null;
+ /** Whether the user may edit pipelines and policies (a manager); when false the wizard is read-only. */
+ canManagePolicies?: boolean;
+ /**
+ * The permission check is still loading. The enforce toggle stays locked, but the manager-only
+ * tooltip is withheld so a still-loading manager isn't told they lack permission.
+ */
+ permissionsLoading?: boolean;
onClose: () => void;
/**
* Fires on submit with the collected settings + built pipeline steps. May be
@@ -199,6 +206,8 @@ function seedTools(entry: CatalogueEntry): ToolState[] {
*/
export function PolicySetupWizard({
entry,
+ canManagePolicies = true,
+ permissionsLoading = false,
onClose,
onSubmit,
onCustomise,
@@ -209,6 +218,8 @@ export function PolicySetupWizard({
<PolicySetupWizardBody
key={entry.category.id}
entry={entry}
+ canManagePolicies={canManagePolicies}
+ permissionsLoading={permissionsLoading}
onClose={onClose}
onSubmit={onSubmit}
onCustomise={onCustomise}
@@ -218,11 +229,15 @@ export function PolicySetupWizard({
function PolicySetupWizardBody({
entry,
+ canManagePolicies,
+ permissionsLoading,
onClose,
onSubmit,
onCustomise,
}: {
entry: CatalogueEntry;
+ canManagePolicies: boolean;
+ permissionsLoading: boolean;
onClose: () => void;
onSubmit: (entry: CatalogueEntry, result: PolicySetupResult) => Promise<void>;
onCustomise: (entry: CatalogueEntry, result: PolicySetupResult) => void;
@@ -259,9 +274,10 @@ function PolicySetupWizardBody({
);
const [maxRetries] = useState(policy?.state.maxRetries ?? 0);
const [retryDelayMinutes] = useState(policy?.state.retryDelayMinutes ?? 0);
- // A suggested policy is something the org requires by nature, so new ones default to required;
- // editing preserves whatever was saved.
+ // A template is a policy by nature - a failure should block the file, not wave it through - so a
+ // new one defaults to required (blocking). Editing preserves whatever was saved.
const [required, setRequired] = useState(policy?.state.required ?? true);
+ const readOnly = !canManagePolicies;
const [submitting, setSubmitting] = useState(false);
const [error, setError] = useState<string | null>(null);
@@ -397,6 +413,7 @@ function PolicySetupWizardBody({
style={{ marginLeft: "auto" }}
onClick={submit}
loading={submitting}
+ disabled={readOnly}
>
{isEdit
? t("portal.policies.wizard.actions.saveChanges")
@@ -509,6 +526,8 @@ function PolicySetupWizardBody({
<EnforceAsPolicyControl
required={required}
onRequiredChange={setRequired}
+ disabled={!canManagePolicies}
+ permissionsLoading={permissionsLoading}
/>
</div>
</Modal>
diff --git a/frontend/editor/src/portal/components/sources/KpiStrip.stories.tsx b/frontend/editor/src/portal/components/sources/KpiStrip.stories.tsx
deleted file mode 100644
index c2233dcb47..0000000000
--- a/frontend/editor/src/portal/components/sources/KpiStrip.stories.tsx
+++ /dev/null
@@ -1,29 +0,0 @@
-import type { Meta, StoryObj } from "@storybook/react-vite";
-import type { SourcesResponse } from "@portal/api/sources";
-import { KpiStrip } from "@portal/components/sources/KpiStrip";
-
-const RESPONSE: SourcesResponse = {
- kpis: [
- { value: 4, description: "connections" },
- { value: 2, description: "referenced by a policy" },
- { value: 2, description: "unused" },
- ],
- sources: [],
-};
-
-const meta: Meta<typeof KpiStrip> = {
- title: "Portal/Sources/KpiStrip",
- component: KpiStrip,
- parameters: { layout: "padded" },
-};
-export default meta;
-type Story = StoryObj<typeof KpiStrip>;
-
-export const Ready: Story = {
- args: { data: RESPONSE, loading: false },
-};
-
-/** Loading collapses every card to the placeholder dash. */
-export const Loading: Story = {
- args: { data: null, loading: true },
-};
diff --git a/frontend/editor/src/portal/components/sources/KpiStrip.tsx b/frontend/editor/src/portal/components/sources/KpiStrip.tsx
deleted file mode 100644
index 970a0a7982..0000000000
--- a/frontend/editor/src/portal/components/sources/KpiStrip.tsx
+++ /dev/null
@@ -1,40 +0,0 @@
-import { useTranslation } from "react-i18next";
-import { MetricCard, MetricStrip } from "@app/ui";
-import { SourcesIcon } from "@portal/components/icons";
-import type { SourcesResponse } from "@portal/api/sources";
-
-/**
- * KPI labels are product copy: they describe what each metric IS, not its
- * current value. They stay client-side so the strip's structure is stable across
- * loading / empty / ready states; only values + descriptions flow from the API.
- * Order matches SourceOverviewService.buildKpis: total, in-use, unused.
- */
-const KPI_LABEL_KEYS = [
- "portal.sources.kpi.total",
- "portal.sources.kpi.inUse",
- "portal.sources.kpi.unused",
-] as const;
-
-interface KpiStripProps {
- data: SourcesResponse | null;
- loading: boolean;
-}
-
-export function KpiStrip({ data, loading }: KpiStripProps) {
- const { t } = useTranslation();
- return (
- <MetricStrip layout="row" leading={<SourcesIcon size={22} />}>
- {KPI_LABEL_KEYS.map((labelKey, i) => {
- const k = loading ? undefined : data?.kpis[i];
- return (
- <MetricCard
- key={labelKey}
- label={t(labelKey)}
- value={k?.value ?? "—"}
- description={k?.description}
- />
- );
- })}
- </MetricStrip>
- );
-}
diff --git a/frontend/editor/src/portal/hooks/usePortalSearchResults.test.ts b/frontend/editor/src/portal/hooks/usePortalSearchResults.test.ts
index f9696f0622..bdedb7608e 100644
--- a/frontend/editor/src/portal/hooks/usePortalSearchResults.test.ts
+++ b/frontend/editor/src/portal/hooks/usePortalSearchResults.test.ts
@@ -160,6 +160,7 @@ vi.mock("@portal/api/policies", async (importOriginal) => ({
vi.mock("@portal/api/pipelines", () => ({
fetchPipelines: vi.fn(),
+ fetchPolicyPermissions: () => Promise.resolve({ canManagePolicies: true }),
}));
vi.mock("@portal/api/sources", () => ({
diff --git a/frontend/editor/src/portal/mocks/handlers/pipelines.ts b/frontend/editor/src/portal/mocks/handlers/pipelines.ts
index d7e0a52497..1f1e4eca6b 100644
--- a/frontend/editor/src/portal/mocks/handlers/pipelines.ts
+++ b/frontend/editor/src/portal/mocks/handlers/pipelines.ts
@@ -219,6 +219,13 @@ export const pipelinesHandlers = [
]);
}),
+ // Policy-management permission. Mock mode presents the operator as a manager.
+ // Registered before "/:id" so "permissions" isn't read as a policy id.
+ http.get("/api/v1/policies/permissions", async () => {
+ await delay(60);
+ return HttpResponse.json({ canManagePolicies: true });
+ }),
+
// Supporting files. Registered before the `/policies/:id` matcher so "assets" isn't read as an id.
http.get("/api/v1/policies/assets", async () => {
await delay(80);
diff --git a/frontend/editor/src/portal/queries/keys.ts b/frontend/editor/src/portal/queries/keys.ts
index 1e4b830f7a..2962f3f016 100644
--- a/frontend/editor/src/portal/queries/keys.ts
+++ b/frontend/editor/src/portal/queries/keys.ts
@@ -15,6 +15,7 @@ export const qk = {
policyRuns: () => ["portal", "policies", "runs"] as const,
sources: () => ["portal", "sources"] as const,
pipelines: () => ["portal", "pipelines"] as const,
+ policyPermissions: () => ["portal", "policies", "permissions"] as const,
fleetStats: () => ["portal", "fleetStats"] as const,
appConfig: () => ["portal", "appConfig"] as const,
// Keyed on scope: the open queue and the closed one are different reads.
diff --git a/frontend/editor/src/portal/queries/policyPermissions.ts b/frontend/editor/src/portal/queries/policyPermissions.ts
new file mode 100644
index 0000000000..6f12c4532b
--- /dev/null
+++ b/frontend/editor/src/portal/queries/policyPermissions.ts
@@ -0,0 +1,25 @@
+import { useQuery } from "@tanstack/react-query";
+import { qk } from "@portal/queries/keys";
+import { fetchPolicyPermissions } from "@portal/api/pipelines";
+
+export interface PolicyPermissionsState {
+ canManage: boolean;
+ isLoading: boolean;
+ isError: boolean;
+ refetch: () => void;
+}
+
+/** Mirrors the backend policy-management gate so the UI matches what a save would actually allow. */
+export function useCanManagePolicies(): PolicyPermissionsState {
+ const query = useQuery({
+ queryKey: qk.policyPermissions(),
+ queryFn: fetchPolicyPermissions,
+ staleTime: 5 * 60 * 1000,
+ });
+ return {
+ canManage: query.data?.canManagePolicies ?? false,
+ isLoading: query.isPending,
+ isError: query.isError,
+ refetch: () => void query.refetch(),
+ };
+}
diff --git a/frontend/editor/src/portal/views/PipelineBuilder.test.tsx b/frontend/editor/src/portal/views/PipelineBuilder.test.tsx
index 3c680af40f..5f3185939a 100644
--- a/frontend/editor/src/portal/views/PipelineBuilder.test.tsx
+++ b/frontend/editor/src/portal/views/PipelineBuilder.test.tsx
@@ -43,6 +43,7 @@ vi.mock("@portal/api/pipelines", () => ({
deletePipeline: (id: string) => deletePipeline(id),
triggerPipeline: (id: string) => triggerPipeline(id),
fetchRun: (runId: string) => fetchRun(runId),
+ fetchPolicyPermissions: () => Promise.resolve({ canManagePolicies: true }),
runPipelineTest: (...args: unknown[]) => runPipelineTest(...args),
fetchRunOutput: (...args: unknown[]) => fetchRunOutput(...args),
}));
diff --git a/frontend/editor/src/portal/views/PipelineBuilder.tsx b/frontend/editor/src/portal/views/PipelineBuilder.tsx
index 100c9a8f03..0d2c9096d7 100644
--- a/frontend/editor/src/portal/views/PipelineBuilder.tsx
+++ b/frontend/editor/src/portal/views/PipelineBuilder.tsx
@@ -69,6 +69,7 @@ import { DestinationPicker } from "@portal/components/pipelines/DestinationPicke
import { availableOutputModes } from "@portal/components/pipelines/outputModes";
import { type SourceView } from "@portal/api/sources";
import { useSources } from "@portal/queries/sources";
+import { useCanManagePolicies } from "@portal/queries/policyPermissions";
import { SourceModal } from "@portal/components/sources/SourceModal";
import { EDITOR_SOURCE_TYPE } from "@portal/components/sources/sourceTypes";
import { useAsync } from "@portal/hooks/useAsync";
@@ -227,6 +228,8 @@ export function PipelineBuilder() {
[id],
);
const sourcesState = useSources();
+ const { canManage: canManagePolicies, isLoading: permissionsLoading } =
+ useCanManagePolicies();
const triggersState = useAsync<TriggerInfo[]>(
async () => await fetchTriggers(),
[],
@@ -274,8 +277,8 @@ export function PipelineBuilder() {
const [testRun, setTestRun] = useState<PolicyRunView | null>(null);
const [testing, setTesting] = useState(false);
const [outputIds, setOutputIds] = useState<string[]>([]);
- // Org-mandated policy (see Policy.required). Admin sets it; members can't pause/delete a required
- // pipeline, and it enforces on their documents when it runs on the editor.
+ // A policy (blocking on failure) vs an ordinary pipeline (see Policy.required). Only meaningful for
+ // an editor-sourced pipeline, so the toggle is shown only then and reset off otherwise (see save).
const [required, setRequired] = useState(false);
// First-class row icon (see Policy.icon), chosen from the picker in the header. Empty falls back to
// the template category glyph in the list; a custom pipeline defaults to none until picked.
@@ -860,7 +863,9 @@ export function PipelineBuilder() {
id: policyState.data?.id ?? seedDraft?.id ?? undefined,
name: name.trim(),
enabled: enabledOverride ?? enabled,
- required,
+ // Blocking is only meaningful for an editor pipeline; a source-backed one is never a policy,
+ // so don't persist a stale flag if the source was switched away from the editor.
+ required: isEditorInput && required,
icon,
// The editor is virtual - there is no stored Source to pull from, and nothing server-side
// sweeps it - so it is never a wire input; its participation is recorded on `editor` below.
@@ -1336,6 +1341,9 @@ export function PipelineBuilder() {
onIconChange={setIcon}
required={required}
onRequiredChange={setRequired}
+ runsOnEditor={isEditorInput}
+ canManagePolicies={canManagePolicies}
+ permissionsLoading={permissionsLoading}
enabled={enabled}
onTogglePause={handleTogglePause}
togglingEnabled={togglingEnabled}
@@ -1358,6 +1366,9 @@ export function PipelineBuilder() {
onIconChange={setIcon}
required={required}
onRequiredChange={setRequired}
+ runsOnEditor={isEditorInput}
+ canManagePolicies={canManagePolicies}
+ permissionsLoading={permissionsLoading}
canSave={canSave}
blockers={blockers}
saving={submitting}
diff --git a/frontend/editor/src/portal/views/Pipelines.gated.test.tsx b/frontend/editor/src/portal/views/Pipelines.gated.test.tsx
index fe28cf55b8..bc12e73969 100644
--- a/frontend/editor/src/portal/views/Pipelines.gated.test.tsx
+++ b/frontend/editor/src/portal/views/Pipelines.gated.test.tsx
@@ -38,6 +38,7 @@ const fetchPipeline = vi.fn();
vi.mock("@portal/api/pipelines", () => ({
fetchPipelines: () => fetchPipelines(),
fetchPipeline: (id: string) => fetchPipeline(id),
+ fetchPolicyPermissions: () => Promise.resolve({ canManagePolicies: true }),
}));
import { Pipelines } from "@portal/views/Pipelines";
diff --git a/frontend/editor/src/portal/views/Pipelines.test.tsx b/frontend/editor/src/portal/views/Pipelines.test.tsx
index 2e04fd6b84..56b0bf0690 100644
--- a/frontend/editor/src/portal/views/Pipelines.test.tsx
+++ b/frontend/editor/src/portal/views/Pipelines.test.tsx
@@ -19,6 +19,7 @@ function DraftProbe() {
pipeline page
<span data-testid="draft-icon">{draft?.icon ?? ""}</span>
<span data-testid="draft-name">{draft?.name ?? ""}</span>
+ <span data-testid="draft-enabled">{String(draft?.enabled ?? "")}</span>
</div>
);
}
@@ -52,12 +53,21 @@ vi.mock("react-i18next", () => ({
const fetchPipelines = vi.fn();
const fetchPipeline = vi.fn();
const savePipeline = vi.fn();
+const fetchPolicyPermissions = vi.fn();
vi.mock("@portal/api/pipelines", () => ({
fetchPipelines: () => fetchPipelines(),
fetchPipeline: (id: string) => fetchPipeline(id),
savePipeline: (policy: unknown) => savePipeline(policy),
+ fetchPolicyPermissions: () => fetchPolicyPermissions(),
}));
+// Spy the wizard's save without stubbing the rest of the module (parseSimplePolicy et al. stay real).
+const savePolicy = vi.fn();
+vi.mock("@portal/api/policies", async (importOriginal) => {
+ const actual = await importOriginal<typeof import("@portal/api/policies")>();
+ return { ...actual, savePolicy: (body: unknown) => savePolicy(body) };
+});
+
// The template gallery is out of scope here: keep the catalogue empty so the test focuses on the
// pipelines list.
vi.mock("@portal/queries/policies", () => ({
@@ -120,8 +130,26 @@ describe("Pipelines view", () => {
});
savePipeline.mockReset();
savePipeline.mockResolvedValue(undefined);
+ savePolicy.mockReset();
+ savePolicy.mockResolvedValue(undefined);
+ fetchPolicyPermissions.mockReset();
+ fetchPolicyPermissions.mockResolvedValue({ canManagePolicies: true });
});
+ /** A template-representable, currently-paused policy. */
+ const pausedPolicy = {
+ id: "plc-redaction",
+ name: "Redaction sweep",
+ enabled: false,
+ required: false,
+ icon: "shield",
+ inputs: [],
+ steps: [{ operation: "/api/v1/security/auto-redact", parameters: {} }],
+ output: { type: "inline", options: { categoryId: "security" } },
+ outputIds: [],
+ editor: { allowed: true, runOn: "upload" },
+ };
+
it("opens the builder when creating a pipeline", async () => {
renderView();
await screen.findByText("Redaction sweep");
@@ -197,13 +225,125 @@ describe("Pipelines view", () => {
);
});
- it("shows the KPI stat boxes when pipelines exist", async () => {
+ it("keeps a paused policy paused when saved from the wizard", async () => {
+ fetchPipeline.mockResolvedValue(pausedPolicy);
+
renderView();
- await screen.findByText("Redaction sweep");
- expect(screen.getByText("portal.pipelines.kpi.total")).toBeInTheDocument();
+ fireEvent.click(await screen.findByText("Redaction sweep")); // detail panel
+ fireEvent.click(
+ await screen.findByText("portal.policies.detail.actions.editSettings"),
+ ); // wizard
+ fireEvent.click(
+ await screen.findByText("portal.policies.wizard.actions.saveChanges"),
+ );
+
+ await waitFor(() => expect(savePolicy).toHaveBeenCalled());
+ // The wizard has no enabled control, so a save must not silently re-enable a paused policy.
+ expect(savePolicy.mock.calls[0][0]).toMatchObject({ enabled: false });
+ });
+
+ it("keeps a paused policy paused when customising from the wizard", async () => {
+ fetchPipeline.mockResolvedValue(pausedPolicy);
+
+ renderView();
+ fireEvent.click(await screen.findByText("Redaction sweep")); // detail panel
+ fireEvent.click(
+ await screen.findByText("portal.policies.detail.actions.editSettings"),
+ ); // wizard
+ fireEvent.click(
+ await screen.findByText("portal.policies.wizard.actions.customise"),
+ ); // hand off to the builder
+
+ expect(await screen.findByTestId("draft-enabled")).toHaveTextContent(
+ "false",
+ );
+ });
+
+ it("locks a required policy for a non-manager (read-only detail)", async () => {
+ fetchPolicyPermissions.mockResolvedValue({ canManagePolicies: false });
+ fetchPipeline.mockResolvedValue({
+ id: "plc-redaction",
+ name: "Redaction sweep",
+ enabled: true,
+ required: true,
+ icon: "shield",
+ inputs: [],
+ steps: [{ operation: "/api/v1/security/auto-redact", parameters: {} }],
+ output: { type: "inline", options: { categoryId: "security" } },
+ outputIds: [],
+ editor: { allowed: true, runOn: "upload" },
+ });
+
+ renderView();
+ fireEvent.click(await screen.findByText("Redaction sweep")); // detail panel
+
+ // The manager-only note shows and the modify actions are locked.
+ expect(
+ await screen.findByText("portal.policies.detail.managerOnly"),
+ ).toBeInTheDocument();
+ expect(
+ screen.getByRole("button", {
+ name: "portal.policies.detail.actions.editSettings",
+ }),
+ ).toBeDisabled();
+ expect(
+ screen.getByRole("button", {
+ name: "portal.policies.detail.actions.pause",
+ }),
+ ).toBeDisabled();
});
- it("hides the stat boxes and shows create + connect-source CTAs when empty", async () => {
+ it("withholds the manager-only note while the permission check is still loading", async () => {
+ // A check that never settles: canManage stays fail-closed false, isLoading stays true.
+ fetchPolicyPermissions.mockReset();
+ fetchPolicyPermissions.mockReturnValue(new Promise(() => {}));
+ fetchPipeline.mockResolvedValue({
+ id: "plc-redaction",
+ name: "Redaction sweep",
+ enabled: true,
+ required: true,
+ icon: "shield",
+ inputs: [],
+ steps: [{ operation: "/api/v1/security/auto-redact", parameters: {} }],
+ output: { type: "inline", options: { categoryId: "security" } },
+ outputIds: [],
+ editor: { allowed: true, runOn: "upload" },
+ });
+
+ renderView();
+ fireEvent.click(await screen.findByText("Redaction sweep")); // detail panel
+
+ // Controls stay locked (fail-closed), but a still-loading manager isn't told they're not allowed.
+ expect(
+ await screen.findByRole("button", {
+ name: "portal.policies.detail.actions.editSettings",
+ }),
+ ).toBeDisabled();
+ expect(
+ screen.queryByText("portal.policies.detail.managerOnly"),
+ ).not.toBeInTheDocument();
+ });
+
+ it("warns with a retry when the permission check fails, instead of locking silently", async () => {
+ fetchPolicyPermissions.mockReset();
+ fetchPolicyPermissions.mockRejectedValueOnce(new Error("boom"));
+ fetchPolicyPermissions.mockResolvedValue({ canManagePolicies: true });
+
+ renderView();
+ expect(
+ await screen.findByText("portal.pipelines.permissionsUnavailable"),
+ ).toBeInTheDocument();
+
+ // Retry refetches; on success the warning clears.
+ fireEvent.click(screen.getByText("portal.pipelines.permissionsRetry"));
+ await waitFor(() =>
+ expect(
+ screen.queryByText("portal.pipelines.permissionsUnavailable"),
+ ).not.toBeInTheDocument(),
+ );
+ });
+
+ it("shows create + connect-source CTAs when empty", async () => {
fetchPipelines.mockResolvedValue({
kpis: [
{ value: 0, description: "" },
@@ -219,9 +359,5 @@ describe("Pipelines view", () => {
expect(
screen.getByText("portal.pipelines.empty.connectSource"),
).toBeInTheDocument();
- // The KPI strip is gone: no stat-box labels over an empty page.
- expect(
- screen.queryByText("portal.pipelines.kpi.total"),
- ).not.toBeInTheDocument();
});
});
diff --git a/frontend/editor/src/portal/views/Pipelines.tsx b/frontend/editor/src/portal/views/Pipelines.tsx
index 07611520ec..c49e3c1933 100644
--- a/frontend/editor/src/portal/views/Pipelines.tsx
+++ b/frontend/editor/src/portal/views/Pipelines.tsx
@@ -26,12 +26,12 @@ import {
import { qk } from "@portal/queries/keys";
import { VIEW_PATHS, toPortalPath } from "@portal/contexts/ViewContext";
import { PipelinesIcon } from "@portal/components/icons";
-import { KpiStrip } from "@portal/components/pipelines/KpiStrip";
import { PipelinesTable } from "@portal/components/pipelines/PipelinesTable";
import { PipelineTemplateCard } from "@portal/components/pipelines/PipelineTemplateCard";
import { PolicyDetailPanel } from "@portal/components/policies/PolicyDetailPanel";
import { PolicySetupWizard } from "@portal/components/policies/PolicySetupWizard";
import { useAiEngineEnabled } from "@portal/hooks/useAiEngineEnabled";
+import { useCanManagePolicies } from "@portal/queries/policyPermissions";
import { useConnectGate } from "@portal/hooks/useConnectGate";
import "@portal/views/Pipelines.css";
@@ -49,7 +49,7 @@ export function Pipelines() {
const { guard } = useConnectGate();
const listState = usePipelines();
- const { data: overview, loading: overviewLoading } = listState;
+ const { data: overview } = listState;
const { isLoading: listLoading } = useSectionFlags(listState);
const catalogueState = usePoliciesOverview();
@@ -57,6 +57,12 @@ export function Pipelines() {
const { enabled: aiEngineEnabled, loading: aiEngineLoading } =
useAiEngineEnabled();
+ const {
+ canManage: canManagePolicies,
+ isLoading: permissionsLoading,
+ isError: permissionsError,
+ refetch: retryPermissions,
+ } = useCanManagePolicies();
const [detail, setDetail] = useState<CatalogueEntry | null>(null);
const [wizard, setWizard] = useState<CatalogueEntry | null>(null);
@@ -153,7 +159,7 @@ export function Pipelines() {
id: stored?.backendId,
name: stored?.name ?? wire.name,
icon: stored?.icon,
- enabled: wire.enabled,
+ enabled: stored ? stored.status !== "paused" : wire.enabled,
required: wire.required,
inputs: [],
steps: wire.steps,
@@ -172,7 +178,8 @@ export function Pipelines() {
) {
setPageError(null);
try {
- await savePolicy(buildWireFromSetup(entry, result, t));
+ const enabled = entry.policy?.state.status !== "paused";
+ await savePolicy(buildWireFromSetup(entry, result, t, enabled));
setWizard(null);
setDetail(null);
refetch();
@@ -258,13 +265,23 @@ export function Pipelines() {
{pageError && <Banner tone="danger" description={pageError} />}
+ {permissionsError && (
+ <Banner
+ tone="warning"
+ description={t("portal.pipelines.permissionsUnavailable")}
+ action={
+ <Button size="sm" variant="secondary" onClick={retryPermissions}>
+ {t("portal.pipelines.permissionsRetry")}
+ </Button>
+ }
+ />
+ )}
+
<section className="portal-pipelines__all">
<h2 className="portal-pipelines__section-title">
{t("portal.pipelines.all.title")}
</h2>
- {hasPipelines && <KpiStrip data={overview} loading={overviewLoading} />}
-
{listLoading && (
<div className="portal-pipelines__table-skeleton" aria-hidden>
{Array.from({ length: 5 }).map((_, i) => (
@@ -323,6 +340,8 @@ export function Pipelines() {
<PolicyDetailPanel
policy={detail?.policy ?? null}
busy={busy}
+ canManagePolicies={canManagePolicies}
+ permissionsLoading={permissionsLoading}
onClose={() => setDetail(null)}
onEdit={handleEdit}
onTogglePause={handleTogglePause}
@@ -332,6 +351,8 @@ export function Pipelines() {
<PolicySetupWizard
entry={wizard}
+ canManagePolicies={canManagePolicies}
+ permissionsLoading={permissionsLoading}
onClose={() => setWizard(null)}
onSubmit={handleSubmit}
onCustomise={handleCustomise}
diff --git a/frontend/editor/src/portal/views/Policies.css b/frontend/editor/src/portal/views/Policies.css
index eab898c1b3..8d1ebbe09f 100644
--- a/frontend/editor/src/portal/views/Policies.css
+++ b/frontend/editor/src/portal/views/Policies.css
@@ -13,6 +13,12 @@
width: 100%;
}
+.portal-policies__detail-readonly {
+ margin-right: auto;
+ color: var(--c-text-muted);
+ font-size: 0.8125rem;
+}
+
.portal-policies__wizard-banner {
margin-top: 0.75rem;
}
diff --git a/frontend/editor/src/portal/views/Sources.css b/frontend/editor/src/portal/views/Sources.css
index 67d94a0848..161d28b52e 100644
--- a/frontend/editor/src/portal/views/Sources.css
+++ b/frontend/editor/src/portal/views/Sources.css
@@ -37,8 +37,6 @@
max-width: 46rem;
}
-/* Metric strip now uses the shared <MetricStrip>. */
-
/* Table cells */
.portal-sources__name-cell {
display: flex;
diff --git a/frontend/editor/src/portal/views/Sources.test.tsx b/frontend/editor/src/portal/views/Sources.test.tsx
index 3891f1955d..abd5d22882 100644
--- a/frontend/editor/src/portal/views/Sources.test.tsx
+++ b/frontend/editor/src/portal/views/Sources.test.tsx
@@ -167,16 +167,4 @@ describe("Sources view", () => {
renderView("/processor/sources?tab=connections");
expect(await screen.findByText("integrations view")).toBeInTheDocument();
});
-
- it("hides the KPI strip when only the editor exists", async () => {
- fetchSources.mockResolvedValue({
- kpis: RESPONSE.kpis,
- sources: [RESPONSE.sources[0]],
- });
- renderView();
- expect(
- await screen.findByText("portal.sources.types.editor.label"),
- ).toBeInTheDocument();
- expect(screen.queryByText("portal.sources.kpi.total")).toBeNull();
- });
});
diff --git a/frontend/editor/src/portal/views/Sources.tsx b/frontend/editor/src/portal/views/Sources.tsx
index bb740f5d69..d185ee9bea 100644
--- a/frontend/editor/src/portal/views/Sources.tsx
+++ b/frontend/editor/src/portal/views/Sources.tsx
@@ -7,7 +7,6 @@ import { useSectionFlags } from "@portal/hooks/useAsync";
import { useSources } from "@portal/queries/sources";
import { type SourceView } from "@portal/api/sources";
import { VIEW_PATHS, toPortalPath } from "@portal/contexts/ViewContext";
-import { KpiStrip } from "@portal/components/sources/KpiStrip";
import { SourcesTable } from "@portal/components/sources/SourcesTable";
import { SourceModal } from "@portal/components/sources/SourceModal";
import { useConnectGate } from "@portal/hooks/useConnectGate";
@@ -19,7 +18,7 @@ export function Sources() {
const { guard, gated, connect } = useConnectGate();
const state = useSources();
- const { data, loading } = state;
+ const { data } = state;
const { isLoading } = useSectionFlags(state);
// Create/edit live in a modal on this list; `?new=1` (old /sources/new deep
@@ -46,11 +45,6 @@ export function Sources() {
const sources = data?.sources ?? [];
- // The editor is a virtual row that's always present, so "empty" means no
- // configured sources beyond it. Gates the KPI strip.
- const configuredCount = sources.filter((s) => s.type !== "editor").length;
- const showKpis = isLoading || configuredCount > 0;
-
// Connecting a source and editing one both need a linked account.
const openCreate = guard(() => setModal({ open: true, sourceId: null }));
const openSource = guard((source: SourceView) =>
@@ -80,8 +74,6 @@ export function Sources() {
</div>
</header>
- {showKpis && <KpiStrip data={data} loading={loading} />}
-
{isLoading && (
<div className="portal-sources__table-skeleton" aria-hidden>
{Array.from({ length: 5 }).map((_, i) => (
diff --git a/frontend/editor/src/proprietary/policies/types.ts b/frontend/editor/src/proprietary/policies/types.ts
index ded698e382..fc80ebcfd5 100644
--- a/frontend/editor/src/proprietary/policies/types.ts
+++ b/frontend/editor/src/proprietary/policies/types.ts
@@ -56,7 +56,7 @@ export interface WirePolicy {
name: string;
owner?: string;
enabled: boolean;
- /** Org-mandated policy; first-class on the record (see the pipeline `Policy.required`). */
+ /** A policy (blocking on failure) rather than an ordinary pipeline (see `Policy.required`). */
required?: boolean;
trigger: null;
steps: WirePipelineStep[];
@@ -102,7 +102,7 @@ export interface PolicyDecodedState {
id: string;
name: string;
enabled: boolean;
- /** Org-mandated policy; first-class on the record, not part of the options bag. */
+ /** A policy (blocking on failure) rather than an ordinary pipeline; first-class, not in options. */
required: boolean;
policyKey: string;
sources: string[];